Skip to main content

zaun_client/
objects.rs

1//! Communities, channels, members, roles and messages as objects that act for themselves, in
2//! the spirit of discord.js: `message.reply("pong")`, `channel.send("hi")`, `member.kick(…)`,
3//! `channel.join()`. Each is a cheap handle (the [`Client`] and ids); what it reports comes
4//! from the cache when asked, so a handle kept for later sees later changes.
5
6use std::fmt;
7use std::path::{Path, PathBuf};
8use std::time::Duration;
9
10use zaun_community_protocol::bits::Permissions;
11use zaun_community_protocol::command::message;
12use zaun_community_protocol::command::object::{
13    Attachment as AttachmentData, Channel as ChannelData, Embed, Member as MemberData, Mentions,
14    Role as RoleData, VoiceParticipant,
15};
16use zaun_community_protocol::ids::{
17    AttachmentId, ChannelId, CommunityId, HostId, MemberId, MessageId, RoleId,
18};
19use zaun_community_protocol::keys::PublicKey;
20use zaun_community_protocol::model::ChannelKind;
21
22use crate::api::HandOff;
23use crate::cache::CommunityData;
24use crate::client::Client;
25use crate::compose::{EditMessage, MessageOptions};
26use crate::error::{Error, Result};
27use crate::voice::{VoiceOptions, VoiceSession};
28
29/// A community this client belongs to (or did: a handle outlives a leave).
30#[derive(Clone)]
31pub struct Community {
32    pub(crate) client: Client,
33    pub(crate) id: CommunityId,
34}
35
36impl fmt::Debug for Community {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.debug_tuple("Community").field(&self.id).finish()
39    }
40}
41
42impl PartialEq for Community {
43    fn eq(&self, other: &Self) -> bool {
44        self.id == other.id
45    }
46}
47
48impl Community {
49    /// Its id.
50    #[must_use]
51    pub const fn id(&self) -> CommunityId {
52        self.id
53    }
54
55    /// A copy of the cache: the whole community as plain data, or `None` when this client
56    /// does not belong to it (any more).
57    #[must_use]
58    pub fn data(&self) -> Option<CommunityData> {
59        self.client.data(&self.id)
60    }
61
62    /// `f` over the cache, without copying it; `None` when this client does not belong to
63    /// the community (any more).
64    pub(crate) fn read<T>(&self, f: impl FnOnce(&CommunityData) -> T) -> Option<T> {
65        self.client.read(&self.id, f)
66    }
67
68    /// Its name, from the descriptor the host's welcome proved (empty before).
69    #[must_use]
70    pub fn name(&self) -> String {
71        self.read(|c| c.name.clone()).unwrap_or_default()
72    }
73
74    /// Its description, from the same descriptor.
75    #[must_use]
76    pub fn description(&self) -> Option<String> {
77        self.read(|c| c.description.clone()).flatten()
78    }
79
80    /// Whether this client owns it.
81    #[must_use]
82    pub fn is_owner(&self) -> bool {
83        self.read(|c| c.is_owner).unwrap_or(false)
84    }
85
86    /// This client's member id in it.
87    fn my_id(&self) -> Option<MemberId> {
88        self.read(|c| c.me)
89    }
90
91    /// This client as a member of it.
92    #[must_use]
93    pub fn me(&self) -> Option<Member> {
94        self.my_id().map(|me| self.member(me))
95    }
96
97    /// Its channels and categories this member can see, in order.
98    #[must_use]
99    pub fn channels(&self) -> Vec<Channel> {
100        let ids = self.read(|c| {
101            let list = c.ordered_channels().into_iter();
102            list.map(|ch| ch.channel_id).collect::<Vec<_>>()
103        });
104        ids.unwrap_or_default()
105            .into_iter()
106            .map(|id| self.channel(id))
107            .collect()
108    }
109
110    /// The first channel named `name` (names are not unique).
111    #[must_use]
112    pub fn channel_by_name(&self, name: &str) -> Option<Channel> {
113        let id = self.read(|c| {
114            let mut list = c.ordered_channels().into_iter();
115            list.find(|ch| ch.name == name).map(|ch| ch.channel_id)
116        });
117        id.flatten().map(|id| self.channel(id))
118    }
119
120    /// The channel `id`, known to the cache or not.
121    #[must_use]
122    pub fn channel(&self, id: ChannelId) -> Channel {
123        Channel {
124            community: self.clone(),
125            id,
126        }
127    }
128
129    /// Its roles, highest first.
130    #[must_use]
131    pub fn roles(&self) -> Vec<Role> {
132        let ids = self.read(|c| ordered_roles(c).map(|r| r.role_id).collect::<Vec<_>>());
133        ids.unwrap_or_default()
134            .into_iter()
135            .map(|id| self.role(id))
136            .collect()
137    }
138
139    /// The first role named `name`.
140    #[must_use]
141    pub fn role_by_name(&self, name: &str) -> Option<Role> {
142        let id = self.read(|c| ordered_roles(c).find(|r| r.name == name).map(|r| r.role_id));
143        id.flatten().map(|id| self.role(id))
144    }
145
146    /// The role `id`, known to the cache or not.
147    #[must_use]
148    pub fn role(&self, id: RoleId) -> Role {
149        Role {
150            community: self.clone(),
151            id,
152        }
153    }
154
155    /// The members the cache has heard of; [`fetch_members`](Self::fetch_members) loads them
156    /// all.
157    #[must_use]
158    pub fn members(&self) -> Vec<Member> {
159        let ids = self.read(|c| c.members.keys().copied().collect::<Vec<_>>());
160        ids.unwrap_or_default()
161            .into_iter()
162            .map(|m| self.member(m))
163            .collect()
164    }
165
166    /// The member `id`, known to the cache or not.
167    #[must_use]
168    pub fn member(&self, id: MemberId) -> Member {
169        Member {
170            community: self.clone(),
171            id,
172        }
173    }
174
175    /// Loads every member into the cache.
176    ///
177    /// # Errors
178    /// The host refused or did not answer.
179    pub fn fetch_members(&self) -> Result<Vec<Member>> {
180        self.client.fetch_members(self.id)?;
181        Ok(self.members())
182    }
183
184    /// Makes a channel of `kind` named `name`.
185    ///
186    /// # Errors
187    /// The host refused (no `MANAGE_CHANNELS`) or did not answer.
188    pub fn create_channel(&self, name: &str, kind: ChannelKind) -> Result<Channel> {
189        let made = self.client.create_channel(self.id, name, kind, None)?;
190        Ok(self.keep_channel(made))
191    }
192
193    /// Makes a channel of `kind` named `name` inside the category `parent`.
194    ///
195    /// # Errors
196    /// As [`create_channel`](Self::create_channel).
197    pub fn create_channel_in(
198        &self,
199        parent: &Channel,
200        name: &str,
201        kind: ChannelKind,
202    ) -> Result<Channel> {
203        let made = self
204            .client
205            .create_channel(self.id, name, kind, Some(parent.id))?;
206        Ok(self.keep_channel(made))
207    }
208
209    /// Makes a role named `name` with `permissions`.
210    ///
211    /// # Errors
212    /// The host refused (no `MANAGE_ROLES`, or permissions this member lacks) or did not
213    /// answer.
214    pub fn create_role(&self, name: &str, permissions: Permissions) -> Result<Role> {
215        let made = self.client.create_role(self.id, name, permissions)?;
216        let id = made.role_id;
217        self.client.with_cache(|cache| {
218            if let Some(c) = cache.get_mut(&self.id) {
219                c.roles.entry(id).or_insert(made);
220            }
221        });
222        Ok(self.role(id))
223    }
224
225    /// Makes an invitation link for `max_uses` joins (0: no limit), expiring after
226    /// `expires_in` if given. The link is a secret: give it only to who should join.
227    ///
228    /// # Errors
229    /// The host refused or did not answer.
230    pub fn create_invite(&self, max_uses: u32, expires_in: Option<Duration>) -> Result<String> {
231        self.client
232            .create_invite(self.id, max_uses, expires_in.map(|d| d.as_secs()))
233    }
234
235    /// Leaves the community (the owner cannot). Once the host accepts, it is forgotten here:
236    /// its state and member key leave the store, [`Event::CommunityDelete`](crate::Event)
237    /// follows with `RemovalReason::Left`, and a later [`Client::join`](crate::Client::join)
238    /// of it starts afresh.
239    ///
240    /// # Errors
241    /// The host refused or did not answer.
242    pub fn leave(&self) -> Result<()> {
243        self.client.leave(self.id)
244    }
245
246    /// As the owner, hands the community to the host at `host_address` whose key is
247    /// `host_key`; see [`HandOff`].
248    ///
249    /// # Errors
250    /// This client does not hold the root key, the host refused, or no answer came.
251    pub fn hand_off(&self, host_address: &str, host_key: PublicKey) -> Result<HandOff> {
252        self.client.hand_off(self.id, host_address, host_key)
253    }
254
255    /// Follows the community to the host the owner named, when no descriptor update arrived.
256    ///
257    /// # Errors
258    /// The new host refused this member, or a timeout.
259    pub fn follow(&self, host_address: &str, host_key: PublicKey) -> Result<HostId> {
260        self.client.follow(self.id, host_address, host_key)
261    }
262
263    /// The host's answer to a creation, kept until its event brings the same.
264    fn keep_channel(&self, made: ChannelData) -> Channel {
265        let id = made.channel_id;
266        self.client.with_cache(|cache| {
267            if let Some(c) = cache.get_mut(&self.id) {
268                c.channels.entry(id).or_insert(made);
269            }
270        });
271        self.channel(id)
272    }
273
274    /// This member's voice channels.
275    #[must_use]
276    pub fn voice_channels(&self) -> Vec<Channel> {
277        self.channels()
278            .into_iter()
279            .filter(Channel::is_voice)
280            .collect()
281    }
282}
283
284/// Roles highest first (a stable sort, so equal positions keep id order).
285fn ordered_roles(c: &CommunityData) -> impl Iterator<Item = &RoleData> {
286    let mut roles: Vec<&RoleData> = c.roles.values().collect();
287    roles.sort_by_key(|r| std::cmp::Reverse(r.position));
288    roles.into_iter()
289}
290
291impl fmt::Display for Community {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        f.write_str(&self.name())
294    }
295}
296
297/// A channel or category of a community.
298#[derive(Clone)]
299pub struct Channel {
300    pub(crate) community: Community,
301    pub(crate) id: ChannelId,
302}
303
304impl fmt::Debug for Channel {
305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306        f.debug_tuple("Channel").field(&self.id).finish()
307    }
308}
309
310impl PartialEq for Channel {
311    fn eq(&self, other: &Self) -> bool {
312        (self.community.id, self.id) == (other.community.id, other.id)
313    }
314}
315
316impl Channel {
317    /// Its id.
318    #[must_use]
319    pub const fn id(&self) -> ChannelId {
320        self.id
321    }
322
323    /// The community it belongs to.
324    #[must_use]
325    pub const fn community(&self) -> &Community {
326        &self.community
327    }
328
329    /// The cache's copy, or `None` when the cache does not have it (any more).
330    #[must_use]
331    pub fn data(&self) -> Option<ChannelData> {
332        self.read(Clone::clone)
333    }
334
335    /// `f` over the cache's copy, without copying it.
336    fn read<T>(&self, f: impl FnOnce(&ChannelData) -> T) -> Option<T> {
337        self.community
338            .read(|c| c.channels.get(&self.id).map(f))
339            .flatten()
340    }
341
342    /// Its name (empty when the cache does not have it).
343    #[must_use]
344    pub fn name(&self) -> String {
345        self.read(|c| c.name.clone()).unwrap_or_default()
346    }
347
348    /// Text when the cache does not have it.
349    #[must_use]
350    pub fn kind(&self) -> ChannelKind {
351        self.read(|c| c.kind).unwrap_or(ChannelKind::Text)
352    }
353
354    /// Its topic.
355    #[must_use]
356    pub fn topic(&self) -> Option<String> {
357        self.read(|c| c.topic.clone()).flatten()
358    }
359
360    /// The category it is in.
361    #[must_use]
362    pub fn parent(&self) -> Option<Self> {
363        let parent = self.read(|c| c.parent_id).flatten();
364        parent.map(|id| self.community.channel(id))
365    }
366
367    /// Whether it is a voice (or stage) channel.
368    #[must_use]
369    pub fn is_voice(&self) -> bool {
370        matches!(self.kind(), ChannelKind::Voice | ChannelKind::Stage)
371    }
372
373    /// Whether it is a category.
374    #[must_use]
375    pub fn is_category(&self) -> bool {
376        self.kind() == ChannelKind::Category
377    }
378
379    /// Posts a message: text (`channel.send("hi")`), or [`MessageOptions`] with embeds,
380    /// files and the message it answers. An embed's pictures and the files are uploaded
381    /// first, each once, over this member's post-quantum connection to the host.
382    ///
383    /// # Errors
384    /// A broken embed or more than 10 files and pictures ([`Error::Protocol`], before
385    /// anything is uploaded); embeds to a host that does not keep them
386    /// ([`Error::Unsupported`]); a failed upload; or the host refused (no `SEND_MESSAGES`,
387    /// `EMBED_LINKS` or `ATTACH_FILES`, slowmode, too long) or did not answer.
388    pub fn send(&self, options: impl Into<MessageOptions>) -> Result<Message> {
389        let o = options.into();
390        let (sent, embeds) = self.community.client.post(self.community.id, self.id, &o)?;
391        let mentions = o.mentions.clone().unwrap_or_default();
392        Ok(self.sent(&sent, o.content, o.reply_to, mentions, embeds))
393    }
394
395    /// Posts like [`send`](Self::send) but returns at once with the message as it will look,
396    /// so it can be shown before the host answers (it takes a relay round trip or two). The
397    /// outcome comes as [`Event::MessageSent`](crate::Event::MessageSent) or
398    /// [`Event::MessageSendFailed`](crate::Event::MessageSendFailed) with the same
399    /// [`pending`](PendingMessage::pending) number. Text posts keep their order; a post
400    /// with files uploads them first and may land after text sent later.
401    ///
402    /// # Errors
403    /// What [`send`](Self::send) refuses before anything leaves (a broken embed, too many
404    /// files, a host without embeds), not yet a member, or the client stopped.
405    #[cfg(not(target_arch = "wasm32"))]
406    pub fn send_pending(&self, options: impl Into<MessageOptions>) -> Result<PendingMessage> {
407        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
408        let o = options.into();
409        let author = self.community.my_id().ok_or(Error::UnknownCommunity)?;
410        let pending = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
411        let shown = PendingMessage {
412            pending,
413            channel: self.clone(),
414            author,
415            content: o.content.clone(),
416            reply_to: o.reply_to,
417            created_at: self.community.client.now_ms(),
418        };
419        let post = crate::driver::PendingPost {
420            pending,
421            channel: self.id,
422            author,
423            content: o.content.clone(),
424            embeds: Vec::new(),
425            reply_to: o.reply_to,
426            mentions: o.mentions.clone().unwrap_or_default(),
427        };
428        self.community
429            .client
430            .post_pending(self.community.id, self.id, o, post)?;
431        Ok(shown)
432    }
433
434    /// Posts `content` with the files at `paths` attached (each uploaded first, over this
435    /// member's post-quantum connection to the host).
436    ///
437    /// # Errors
438    /// A file the host would not take (too large, a file server it does not use), a failed
439    /// upload, or as [`send`](Self::send).
440    pub fn send_files(&self, content: &str, paths: &[impl AsRef<Path>]) -> Result<Message> {
441        let client = &self.community.client;
442        let mut ids: Vec<AttachmentId> = Vec::new();
443        for p in paths {
444            ids.push(client.upload(self.community.id, self.id, p)?);
445        }
446        let sent = client.send_with_attachments(self.community.id, self.id, content, &ids)?;
447        Ok(self.sent(
448            &sent,
449            content.to_owned(),
450            None,
451            Mentions::default(),
452            Vec::new(),
453        ))
454    }
455
456    /// Up to `limit` messages before sequence `before` (the newest without it), oldest first.
457    ///
458    /// # Errors
459    /// The host refused (no `READ_MESSAGE_HISTORY`) or did not answer.
460    pub fn messages(&self, before: Option<u64>, limit: u32) -> Result<Vec<Message>> {
461        let page = self
462            .community
463            .client
464            .history(self.community.id, self.id, before, limit)?;
465        Ok(page
466            .messages
467            .into_iter()
468            .map(|m| Message {
469                channel: self.clone(),
470                id: m.message_id,
471                sequence: m.sequence,
472                author: m.author_id,
473                content: m.content,
474                embeds: m.embeds,
475                components: m.components,
476                flags: m.flags,
477                interaction: m.interaction_metadata.map(|b| *b),
478                reply_to: m.reply_to,
479                mentions: m.mentions,
480                attachments: m.attachments,
481                timestamp: m.created_at,
482            })
483            .collect())
484    }
485
486    /// Deletes the channel or category.
487    ///
488    /// # Errors
489    /// The host refused or did not answer.
490    pub fn delete(&self) -> Result<()> {
491        self.community
492            .client
493            .delete_channel(self.community.id, self.id)
494    }
495
496    /// Who is in this voice channel now (no key material).
497    #[must_use]
498    pub fn participants(&self) -> Vec<VoiceParticipant> {
499        self.read(|c| c.voice_participants.clone())
500            .flatten()
501            .unwrap_or_default()
502    }
503
504    /// Joins this voice channel: relayed through the host's TURN server, every frame sealed
505    /// end to end. See [`VoiceSession`].
506    ///
507    /// # Errors
508    /// Not a voice channel, already in voice in this community, a host media policy this
509    /// client does not accept, no relay to be had, or the host refused.
510    pub fn join(&self) -> Result<VoiceSession> {
511        self.join_with(VoiceOptions::default())
512    }
513
514    /// [`join`](Self::join) with `options` (a direct path, joining muted or deafened).
515    ///
516    /// # Errors
517    /// As [`join`](Self::join).
518    pub fn join_with(&self, options: VoiceOptions) -> Result<VoiceSession> {
519        if self
520            .read(|c| c.kind)
521            .is_some_and(|k| !matches!(k, ChannelKind::Voice | ChannelKind::Stage))
522        {
523            return Err(Error::Voice("not a voice channel".into()));
524        }
525        self.community
526            .client
527            .join_voice(self.community.id, self.id, options)
528    }
529
530    /// The message just posted, as the host's receipt and what was sent say. Its
531    /// attachments are not at hand (only their ids were), so it lists none.
532    fn sent(
533        &self,
534        sent: &message::Sent,
535        content: String,
536        reply_to: Option<MessageId>,
537        mentions: Mentions,
538        embeds: Vec<Embed>,
539    ) -> Message {
540        Message {
541            channel: self.clone(),
542            id: sent.message_id,
543            sequence: sent.sequence,
544            author: self
545                .community
546                .my_id()
547                .unwrap_or_else(|| MemberId::from_bytes([0; 16])),
548            content,
549            embeds,
550            components: Vec::new(),
551            flags: 0,
552            interaction: None,
553            reply_to,
554            mentions,
555            attachments: Vec::new(),
556            timestamp: sent.timestamp,
557        }
558    }
559}
560
561impl fmt::Display for Channel {
562    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563        write!(f, "#{}", self.name())
564    }
565}
566
567/// A post on its way ([`Channel::send_pending`]): what to show until the host answers.
568#[derive(Debug, Clone)]
569pub struct PendingMessage {
570    /// This client's number for it, named again by the outcome event.
571    pub pending: u64,
572    /// Where it was posted.
573    pub channel: Channel,
574    /// This member.
575    pub author: MemberId,
576    /// Its text.
577    pub content: String,
578    /// The message it answers, if any.
579    pub reply_to: Option<MessageId>,
580    /// When it was posted here, ms since the Unix epoch (the host's time comes with it).
581    pub created_at: u64,
582}
583
584/// A member of a community.
585#[derive(Clone)]
586pub struct Member {
587    pub(crate) community: Community,
588    pub(crate) id: MemberId,
589}
590
591impl fmt::Debug for Member {
592    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593        f.debug_tuple("Member").field(&self.id).finish()
594    }
595}
596
597impl PartialEq for Member {
598    fn eq(&self, other: &Self) -> bool {
599        (self.community.id, self.id) == (other.community.id, other.id)
600    }
601}
602
603impl Member {
604    /// Its id.
605    #[must_use]
606    pub const fn id(&self) -> MemberId {
607        self.id
608    }
609
610    /// The community it belongs to.
611    #[must_use]
612    pub const fn community(&self) -> &Community {
613        &self.community
614    }
615
616    /// The cache's copy, or `None` before the cache heard of this member
617    /// ([`Community::fetch_members`]).
618    #[must_use]
619    pub fn data(&self) -> Option<MemberData> {
620        self.read(Clone::clone)
621    }
622
623    /// `f` over the cache's copy, without copying it.
624    fn read<T>(&self, f: impl FnOnce(&MemberData) -> T) -> Option<T> {
625        self.community
626            .read(|c| c.members.get(&self.id).map(f))
627            .flatten()
628    }
629
630    /// Their name in this community.
631    #[must_use]
632    pub fn display_name(&self) -> String {
633        self.read(|m| m.display_name.clone()).unwrap_or_default()
634    }
635
636    /// Whether this member is this client.
637    #[must_use]
638    pub fn is_me(&self) -> bool {
639        self.community.my_id() == Some(self.id)
640    }
641
642    /// Their roles.
643    #[must_use]
644    pub fn roles(&self) -> Vec<Role> {
645        let ids = self.read(|m| m.role_ids.clone()).unwrap_or_default();
646        ids.into_iter().map(|r| self.community.role(r)).collect()
647    }
648
649    /// When a timeout ends, ms since the epoch; `None` when not timed out.
650    #[must_use]
651    pub fn timed_out_until(&self) -> Option<u64> {
652        let until = self.read(|m| m.timeout_until).flatten()?;
653        (until > self.community.client.now_ms()).then_some(until)
654    }
655
656    /// What this member may do in the community, or in `channel`, as the cache sees it; the
657    /// host still decides.
658    #[must_use]
659    pub fn permissions(&self, channel: Option<&Channel>) -> Permissions {
660        let now = self.community.client.now_ms();
661        self.community
662            .read(|c| c.permissions(&self.id, channel.map(|ch| &ch.id), now))
663            .flatten()
664            .map_or(Permissions::empty(), |r| r.effective)
665    }
666
667    /// Whether this member has `permission` (in `channel`), as the cache sees it.
668    #[must_use]
669    pub fn can(&self, permission: Permissions, channel: Option<&Channel>) -> bool {
670        let now = self.community.client.now_ms();
671        self.community
672            .read(|c| c.can(&self.id, channel.map(|ch| &ch.id), permission, now))
673            .unwrap_or(false)
674    }
675
676    /// Gives this member `role`.
677    ///
678    /// # Errors
679    /// The host refused (no `MANAGE_ROLES`, or a role above this member's) or did not answer.
680    pub fn add_role(&self, role: &Role) -> Result<()> {
681        self.set_roles(&[role], &[])
682    }
683
684    /// Takes `role` from this member.
685    ///
686    /// # Errors
687    /// As [`add_role`](Self::add_role).
688    pub fn remove_role(&self, role: &Role) -> Result<()> {
689        self.set_roles(&[], &[role])
690    }
691
692    /// Adds and removes roles in one command.
693    ///
694    /// # Errors
695    /// As [`add_role`](Self::add_role).
696    pub fn set_roles(&self, add: &[&Role], remove: &[&Role]) -> Result<()> {
697        let ids = |r: &[&Role]| r.iter().map(|r| r.id).collect::<Vec<_>>();
698        self.community
699            .client
700            .set_roles(self.community.id, self.id, &ids(add), &ids(remove))
701            .map(drop)
702    }
703
704    /// Removes this member; they may join again with a new invitation.
705    ///
706    /// # Errors
707    /// The host refused (no `KICK_MEMBERS`, or a member above this one) or did not answer.
708    pub fn kick(&self, reason: Option<&str>) -> Result<()> {
709        self.community
710            .client
711            .kick(self.community.id, self.id, reason)
712    }
713
714    /// Removes this member and keeps them out.
715    ///
716    /// # Errors
717    /// The host refused (no `BAN_MEMBERS`) or did not answer.
718    pub fn ban(&self, reason: Option<&str>) -> Result<()> {
719        self.community
720            .client
721            .ban(self.community.id, self.id, reason)
722            .map(drop)
723    }
724
725    /// Times this member out for `duration`, or lifts it with `None`.
726    ///
727    /// # Errors
728    /// The host refused (no `TIMEOUT_MEMBERS`) or did not answer.
729    pub fn timeout(&self, duration: Option<Duration>, reason: Option<&str>) -> Result<()> {
730        let client = &self.community.client;
731        let until =
732            duration.map(|d| client.now_ms() + u64::try_from(d.as_millis()).unwrap_or(u64::MAX));
733        client
734            .timeout(self.community.id, self.id, until, reason)
735            .map(drop)
736    }
737
738    /// The fingerprint of this member's key (this client's own, or the one pinned on first
739    /// sight), to compare out of band.
740    #[must_use]
741    pub fn fingerprint(&self) -> Option<String> {
742        self.community
743            .client
744            .member_key_fingerprint(self.community.id, self.id)
745    }
746}
747
748impl fmt::Display for Member {
749    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
750        f.write_str(&self.display_name())
751    }
752}
753
754/// A role of a community.
755#[derive(Clone)]
756pub struct Role {
757    pub(crate) community: Community,
758    pub(crate) id: RoleId,
759}
760
761impl fmt::Debug for Role {
762    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
763        f.debug_tuple("Role").field(&self.id).finish()
764    }
765}
766
767impl PartialEq for Role {
768    fn eq(&self, other: &Self) -> bool {
769        (self.community.id, self.id) == (other.community.id, other.id)
770    }
771}
772
773impl Role {
774    /// Its id.
775    #[must_use]
776    pub const fn id(&self) -> RoleId {
777        self.id
778    }
779
780    /// The community it belongs to.
781    #[must_use]
782    pub const fn community(&self) -> &Community {
783        &self.community
784    }
785
786    /// The cache's copy, or `None` when the cache does not have it.
787    #[must_use]
788    pub fn data(&self) -> Option<RoleData> {
789        self.read(Clone::clone)
790    }
791
792    /// `f` over the cache's copy, without copying it.
793    fn read<T>(&self, f: impl FnOnce(&RoleData) -> T) -> Option<T> {
794        self.community
795            .read(|c| c.roles.get(&self.id).map(f))
796            .flatten()
797    }
798
799    /// Its name (empty when the cache does not have it).
800    #[must_use]
801    pub fn name(&self) -> String {
802        self.read(|r| r.name.clone()).unwrap_or_default()
803    }
804
805    /// Its permissions.
806    #[must_use]
807    pub fn permissions(&self) -> Permissions {
808        self.read(|r| r.permissions).unwrap_or(Permissions::empty())
809    }
810
811    /// Deletes the role.
812    ///
813    /// # Errors
814    /// The host refused or did not answer.
815    pub fn delete(&self) -> Result<()> {
816        self.community
817            .client
818            .delete_role(self.community.id, self.id)
819    }
820}
821
822impl fmt::Display for Role {
823    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
824        write!(f, "@{}", self.name())
825    }
826}
827
828/// A message in a channel.
829#[derive(Clone)]
830pub struct Message {
831    pub(crate) channel: Channel,
832    pub(crate) id: MessageId,
833    pub(crate) sequence: u64,
834    pub(crate) author: MemberId,
835    pub(crate) content: String,
836    pub(crate) embeds: Vec<Embed>,
837    pub(crate) components: Vec<zaun_community_protocol::command::object::Component>,
838    pub(crate) flags: u32,
839    pub(crate) interaction: Option<zaun_community_protocol::command::object::InteractionMetadata>,
840    pub(crate) reply_to: Option<MessageId>,
841    pub(crate) mentions: Mentions,
842    pub(crate) attachments: Vec<AttachmentData>,
843    pub(crate) timestamp: u64,
844}
845
846impl fmt::Debug for Message {
847    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
848        f.debug_struct("Message")
849            .field("id", &self.id)
850            .field("channel", &self.channel.id)
851            .finish_non_exhaustive()
852    }
853}
854
855impl PartialEq for Message {
856    fn eq(&self, other: &Self) -> bool {
857        (self.channel == other.channel) && self.id == other.id
858    }
859}
860
861impl Message {
862    /// Its id.
863    #[must_use]
864    pub const fn id(&self) -> MessageId {
865        self.id
866    }
867
868    /// Its text (empty when it has embeds or attachments instead).
869    #[must_use]
870    pub fn content(&self) -> &str {
871        &self.content
872    }
873
874    /// Its rich embeds. A picture names one of [`attachments`](Self::attachments)
875    /// ([`attachment`](Self::attachment) finds it); nothing is fetched from elsewhere.
876    #[must_use]
877    pub fn embeds(&self) -> &[Embed] {
878        &self.embeds
879    }
880
881    /// The channel it is in.
882    #[must_use]
883    pub const fn channel(&self) -> &Channel {
884        &self.channel
885    }
886
887    /// The community it belongs to.
888    #[must_use]
889    pub const fn community(&self) -> &Community {
890        &self.channel.community
891    }
892
893    /// Who wrote it.
894    #[must_use]
895    pub fn author(&self) -> Member {
896        self.channel.community.member(self.author)
897    }
898
899    /// Whether this client wrote it.
900    #[must_use]
901    pub fn is_mine(&self) -> bool {
902        self.channel.community.my_id() == Some(self.author)
903    }
904
905    /// Its position in the channel.
906    #[must_use]
907    pub const fn sequence(&self) -> u64 {
908        self.sequence
909    }
910
911    /// When the host accepted it, ms since the epoch.
912    #[must_use]
913    pub const fn timestamp(&self) -> u64 {
914        self.timestamp
915    }
916
917    /// The message it answers.
918    #[must_use]
919    pub const fn reply_to(&self) -> Option<MessageId> {
920        self.reply_to
921    }
922
923    /// Its files; [`Attachment::download`] fetches one.
924    #[must_use]
925    pub fn attachments(&self) -> Vec<Attachment> {
926        self.attachments
927            .iter()
928            .map(|a| Attachment {
929                message: self.clone(),
930                data: a.clone(),
931            })
932            .collect()
933    }
934
935    /// One of its attachments, by id: an embed's picture, say.
936    #[must_use]
937    pub fn attachment(&self, id: AttachmentId) -> Option<Attachment> {
938        self.attachments().into_iter().find(|a| a.id() == id)
939    }
940
941    /// Answers this message in its channel: text, or [`MessageOptions`].
942    ///
943    /// # Errors
944    /// As [`Channel::send`].
945    pub fn reply(&self, options: impl Into<MessageOptions>) -> Result<Self> {
946        self.channel.send(options.into().reply_to(self.id))
947    }
948
949    /// Edits this message (one of this member's): new text (`message.edit("…")`), or an
950    /// [`EditMessage`] that also replaces or removes the embeds or the mentions. Text not
951    /// given stays, and so do the mentions unless the edit names some (then they replace
952    /// them all). Pictures of new embeds must be attachments the message already has.
953    ///
954    /// # Errors
955    /// A picture still to upload or a broken embed ([`Error::Protocol`]), embeds to a host
956    /// that does not keep them ([`Error::Unsupported`]), or the host refused or did not
957    /// answer.
958    pub fn edit(&mut self, options: impl Into<EditMessage>) -> Result<()> {
959        let o = options.into();
960        let content = o.content.clone().unwrap_or_else(|| self.content.clone());
961        let own: Vec<AttachmentId> = self.attachments.iter().map(|a| a.attachment_id).collect();
962        // A message this client just posted does not list its attachments (only their ids
963        // were at hand), so the host alone checks its pictures.
964        let own = (!own.is_empty()).then_some(own.as_slice());
965        let c = &self.channel.community;
966        let edited = c
967            .client
968            .edit_with(c.id, self.channel.id, self.id, &content, &o, own)?;
969        self.content = content;
970        if let Some(embeds) = edited.embeds {
971            self.embeds = embeds;
972        }
973        // As asked: the host may drop some (`Event::MessageUpdate` says which it kept).
974        if let Some(mentions) = edited.mentions {
975            self.mentions = mentions;
976        }
977        Ok(())
978    }
979
980    /// Deletes this message (one's own, or any with `MANAGE_MESSAGES`).
981    ///
982    /// # Errors
983    /// The host refused or did not answer.
984    pub fn delete(&self) -> Result<()> {
985        let c = &self.channel.community;
986        c.client
987            .delete_message(c.id, self.channel.id, self.id)
988            .map(drop)
989    }
990
991    /// Adds `emoji` as this member.
992    ///
993    /// # Errors
994    /// The host refused or did not answer.
995    pub fn react(&self, emoji: &str) -> Result<()> {
996        let c = &self.channel.community;
997        c.client.react(c.id, self.channel.id, self.id, emoji)
998    }
999
1000    /// Takes this member's `emoji` off.
1001    ///
1002    /// # Errors
1003    /// The host refused or did not answer.
1004    pub fn unreact(&self, emoji: &str) -> Result<()> {
1005        let c = &self.channel.community;
1006        c.client.unreact(c.id, self.channel.id, self.id, emoji)
1007    }
1008}
1009
1010impl fmt::Display for Message {
1011    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012        f.write_str(&self.content)
1013    }
1014}
1015
1016/// A message known only by its id, as an edit, a deletion or a reaction names it: the client
1017/// keeps no message history, so its text and author are not at hand. It acts like a
1018/// [`Message`].
1019#[derive(Clone)]
1020pub struct PartialMessage {
1021    pub(crate) channel: Channel,
1022    pub(crate) id: MessageId,
1023}
1024
1025impl fmt::Debug for PartialMessage {
1026    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027        f.debug_struct("PartialMessage")
1028            .field("id", &self.id)
1029            .field("channel", &self.channel.id)
1030            .finish_non_exhaustive()
1031    }
1032}
1033
1034impl PartialEq for PartialMessage {
1035    fn eq(&self, other: &Self) -> bool {
1036        (self.channel == other.channel) && self.id == other.id
1037    }
1038}
1039
1040impl PartialMessage {
1041    /// Its id.
1042    #[must_use]
1043    pub const fn id(&self) -> MessageId {
1044        self.id
1045    }
1046
1047    /// Its channel.
1048    #[must_use]
1049    pub const fn channel(&self) -> &Channel {
1050        &self.channel
1051    }
1052
1053    /// Its community.
1054    #[must_use]
1055    pub const fn community(&self) -> &Community {
1056        &self.channel.community
1057    }
1058
1059    /// Answers this message in its channel: text, or [`MessageOptions`].
1060    ///
1061    /// # Errors
1062    /// As [`Channel::send`].
1063    pub fn reply(&self, options: impl Into<MessageOptions>) -> Result<Message> {
1064        self.channel.send(options.into().reply_to(self.id))
1065    }
1066
1067    /// Edits this message (one of this member's): new text, or an [`EditMessage`] with its
1068    /// text and new embeds (whose pictures must be attachments the message already has) or
1069    /// mentions.
1070    ///
1071    /// # Errors
1072    /// No text given ([`Error::Protocol`]: a partial message does not know its own, and the
1073    /// protocol replaces it), or as [`Message::edit`].
1074    pub fn edit(&self, options: impl Into<EditMessage>) -> Result<()> {
1075        let o = options.into();
1076        let Some(content) = &o.content else {
1077            return Err(Error::Protocol(
1078                "message.edit: a partial message's text is not known; give the text".into(),
1079            ));
1080        };
1081        let c = &self.channel.community;
1082        c.client
1083            .edit_with(c.id, self.channel.id, self.id, content, &o, None)
1084            .map(drop)
1085    }
1086
1087    /// Deletes this message (one's own, or any with `MANAGE_MESSAGES`).
1088    ///
1089    /// # Errors
1090    /// The host refused or did not answer.
1091    pub fn delete(&self) -> Result<()> {
1092        let c = &self.channel.community;
1093        c.client
1094            .delete_message(c.id, self.channel.id, self.id)
1095            .map(drop)
1096    }
1097
1098    /// Adds `emoji` as this member.
1099    ///
1100    /// # Errors
1101    /// The host refused or did not answer.
1102    pub fn react(&self, emoji: &str) -> Result<()> {
1103        let c = &self.channel.community;
1104        c.client.react(c.id, self.channel.id, self.id, emoji)
1105    }
1106
1107    /// Takes this member's `emoji` off.
1108    ///
1109    /// # Errors
1110    /// The host refused or did not answer.
1111    pub fn unreact(&self, emoji: &str) -> Result<()> {
1112        let c = &self.channel.community;
1113        c.client.unreact(c.id, self.channel.id, self.id, emoji)
1114    }
1115}
1116
1117impl From<&Message> for PartialMessage {
1118    fn from(m: &Message) -> Self {
1119        Self {
1120            channel: m.channel.clone(),
1121            id: m.id,
1122        }
1123    }
1124}
1125
1126impl Channel {
1127    /// The message `id` in this channel, to act on without fetching it.
1128    #[must_use]
1129    pub fn message(&self, id: MessageId) -> PartialMessage {
1130        PartialMessage {
1131            channel: self.clone(),
1132            id,
1133        }
1134    }
1135}
1136
1137/// A file on a message.
1138#[derive(Clone)]
1139pub struct Attachment {
1140    message: Message,
1141    data: AttachmentData,
1142}
1143
1144impl fmt::Debug for Attachment {
1145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1146        f.debug_tuple("Attachment")
1147            .field(&self.data.attachment_id)
1148            .finish()
1149    }
1150}
1151
1152impl Attachment {
1153    /// Its id.
1154    #[must_use]
1155    pub const fn id(&self) -> AttachmentId {
1156        self.data.attachment_id
1157    }
1158
1159    /// Its name (empty when the cache does not have it).
1160    #[must_use]
1161    pub fn name(&self) -> &str {
1162        &self.data.name
1163    }
1164
1165    /// Its size in bytes.
1166    #[must_use]
1167    pub const fn size(&self) -> u64 {
1168        self.data.size
1169    }
1170
1171    /// Its media type.
1172    #[must_use]
1173    pub fn content_type(&self) -> &str {
1174        &self.data.mime
1175    }
1176
1177    /// The attachment as the protocol describes it.
1178    #[must_use]
1179    pub const fn data(&self) -> &AttachmentData {
1180        &self.data
1181    }
1182
1183    /// The message it is on.
1184    #[must_use]
1185    pub const fn message(&self) -> &Message {
1186        &self.message
1187    }
1188
1189    /// Downloads the file into the folder `dest` under a safe name and answers its path,
1190    /// once its size and SHA3-256 match.
1191    ///
1192    /// # Errors
1193    /// The host refused, the transfer failed or timed out, or the file does not match.
1194    pub fn download(&self, dest: impl AsRef<Path>) -> Result<PathBuf> {
1195        let channel = &self.message.channel;
1196        let c = &channel.community;
1197        c.client.download(c.id, channel.id, &self.data, dest)
1198    }
1199}