Skip to main content

zaun_client/
events.rs

1//! What a [`Client`] reports, as objects that act for themselves. The cache is already
2//! updated when an event arrives.
3
4use zaun_community_protocol::command::object::{Embed, Mentions};
5use zaun_community_protocol::event::{Event as Catalogue, RemovalReason, VoiceLeftReason};
6use zaun_community_protocol::ids::HostId;
7
8use crate::bots::{EphemeralReply, Interaction, InteractionFailure, ModalOpen, Suggestions};
9use crate::client::Client;
10use crate::event::Event as Inner;
11use crate::objects::{Channel, Community, Member, Message, PartialMessage, Role};
12
13/// One thing that happened.
14#[derive(Debug, Clone)]
15pub enum Event {
16    /// A community is connected and its cache loaded: after a join, a creation, a restart, or
17    /// the host coming back.
18    Ready(Community),
19    /// The community's bots and their commands loaded (just after [`Event::Ready`]).
20    AppsReady(Community),
21    /// Who is online loaded (just after [`Event::Ready`]); [`Community::presences`] has it.
22    PresencesReady(Community),
23    /// A member's status or activity changed; offline members leave
24    /// [`Community::presences`].
25    PresenceUpdate {
26        /// The community.
27        community: Community,
28        /// What everyone sees now.
29        presence: crate::Presence,
30    },
31    /// A bot's commands changed ([`Community::commands`] has the new list).
32    CommandsUpdate {
33        /// The community.
34        community: Community,
35        /// The bot.
36        bot: zaun_community_protocol::ids::BotId,
37    },
38    /// A bot was installed, updated, re-granted, enabled, disabled or crashed: its card.
39    BotUpdate {
40        /// The community.
41        community: Community,
42        /// The bot's public card.
43        card: Box<zaun_community_protocol::command::object::BotCard>,
44    },
45    /// A bot was removed.
46    BotRemove {
47        /// The community.
48        community: Community,
49        /// The bot.
50        bot: zaun_community_protocol::ids::BotId,
51        /// Its member.
52        member: Member,
53    },
54    /// As a bot: someone used one of this bot's commands, components or modals.
55    InteractionCreate(Box<Interaction>),
56    /// A bot's ephemeral reply to this member.
57    InteractionReply(EphemeralReply),
58    /// A bot asks this member to fill in a modal.
59    ModalOpen(ModalOpen),
60    /// A bot's autocomplete suggestions.
61    Autocomplete(Suggestions),
62    /// One of this member's interactions got no answer.
63    InteractionFail(InteractionFailure),
64    /// A new message.
65    MessageCreate(Message),
66    /// A message was edited by its author.
67    MessageUpdate {
68        /// The message.
69        message: PartialMessage,
70        /// Its author, when the host said (only an author edits).
71        author: Option<Member>,
72        /// Its new text.
73        content: String,
74        /// Its new embeds; `None` when the edit left them as they were, `Some` of none when
75        /// it removed them all.
76        embeds: Option<Vec<Embed>>,
77        /// Who it mentions now, as the host honoured them; `None` when the edit left its
78        /// mentions as they were (a 0.3 host never says).
79        mentions: Option<Mentions>,
80        /// When it was edited, ms since the Unix epoch.
81        edited_at: u64,
82    },
83    /// A message was deleted.
84    MessageDelete {
85        /// The message.
86        message: PartialMessage,
87        /// Who deleted it, when the host said.
88        by: Option<Member>,
89    },
90    /// Several messages were deleted at once.
91    MessageDeleteBulk {
92        /// The channel.
93        channel: Channel,
94        /// The messages.
95        messages: Vec<PartialMessage>,
96    },
97    /// Someone added a reaction.
98    ReactionAdd(Reaction),
99    /// Someone took a reaction off.
100    ReactionRemove(Reaction),
101    /// A channel was made, or became visible to this member.
102    ChannelCreate(Channel),
103    /// A channel changed.
104    ChannelUpdate(Channel),
105    /// A channel was deleted, or is no longer visible to this member.
106    ChannelDelete(Channel),
107    /// A role was made.
108    RoleCreate(Role),
109    /// A role changed.
110    RoleUpdate(Role),
111    /// A role was deleted.
112    RoleDelete(Role),
113    /// Someone joined the community.
114    MemberAdd(Member),
115    /// A member changed: their name, roles or timeout.
116    MemberUpdate(Member),
117    /// A member left or was removed.
118    MemberRemove(Member),
119    /// Someone joined, left or changed state in a voice channel.
120    VoiceStateUpdate(VoiceState),
121    /// The community's profile changed.
122    CommunityUpdate(Community),
123    /// This client left a community, or was removed from it (kicked, banned, …); it is
124    /// forgotten here, keys and saved state included. A removal while this client was away
125    /// comes on its next session, from a host after 0.4.0 (which says it again after a
126    /// welcome without the binding, or sends an uncorrelated `BANNED`).
127    CommunityDelete {
128        /// The community.
129        community: Community,
130        /// Why.
131        reason: RemovalReason,
132    },
133    /// The owner handed the community to a new host; this client is moving there.
134    CommunityMoving {
135        /// The community.
136        community: Community,
137        /// The new host.
138        host: HostId,
139    },
140    /// This client moved with its community to the new host.
141    CommunityMoved {
142        /// The community.
143        community: Community,
144        /// The new host.
145        host: HostId,
146    },
147    /// The new host refused this member; the move is given up.
148    CommunityMoveRefused {
149        /// The community.
150        community: Community,
151        /// The host's error code.
152        code: String,
153    },
154    /// The connection to a community's host closed; the community stays saved.
155    Disconnect(Community),
156    /// No SimpleX relay is reachable.
157    Offline,
158    /// A relay is reachable again.
159    Online,
160    /// Something was ignored safely; the text names no content or secret.
161    Warning(String),
162    /// DM: a direct message became known: opened by either side, or found when the
163    /// community loaded. `recipient` is the other participant.
164    DmCreate {
165        /// The DM's channel; post with [`Channel::send`](crate::Channel::send).
166        channel: Channel,
167        /// The other participant.
168        recipient: Member,
169    },
170    /// DM: this member closed a direct message.
171    DmDelete(Channel),
172    /// A post made with [`Channel::send_pending`](crate::Channel::send_pending) is in: the
173    /// host accepted it as `message`, which replaces the pending one shown (matched by
174    /// `pending`). Its `message.created` may also arrive as a [`Event::MessageCreate`].
175    MessageSent {
176        /// The [`PendingMessage::pending`](crate::PendingMessage::pending) number.
177        pending: u64,
178        /// The message as the host keeps it.
179        message: Message,
180    },
181    /// A post made with [`Channel::send_pending`](crate::Channel::send_pending) did not go
182    /// through; the pending one shown should say so.
183    MessageSendFailed {
184        /// The [`PendingMessage::pending`](crate::PendingMessage::pending) number.
185        pending: u64,
186        /// Its channel.
187        channel: Channel,
188        /// Why (the host refused, an upload failed, or the connection gave up).
189        error: String,
190    },
191    /// Someone else is typing in a channel (typing): members by id in a `named` channel, only
192    /// how many in an `anonymous` one. It shows for [`TYPING_SHOWN_MS`](crate::TYPING_SHOWN_MS)
193    /// unless repeated; [`Channel::typing`](crate::Channel::typing) gives the current state.
194    TypingStart {
195        /// The channel.
196        channel: Channel,
197        /// Who, or how many.
198        typing: crate::TypingNow,
199    },
200    /// Any other community event, as the protocol has it.
201    Raw {
202        /// The community.
203        community: Community,
204        /// The channel, for a channel event.
205        channel: Option<Channel>,
206        /// Who caused it, when the host names them.
207        actor: Option<Member>,
208        /// The event.
209        event: Box<Catalogue>,
210    },
211}
212
213/// A reaction added or taken off.
214#[derive(Debug, Clone)]
215pub struct Reaction {
216    /// The message.
217    pub message: PartialMessage,
218    /// The emoji.
219    pub emoji: String,
220    /// Who reacted.
221    pub member: Member,
222}
223
224/// Someone's state in a voice channel.
225#[derive(Debug, Clone)]
226pub struct VoiceState {
227    /// Who.
228    pub member: Member,
229    /// The voice channel.
230    pub channel: Channel,
231    /// They joined it now.
232    pub joined: bool,
233    /// They left it now: why, and where to, when a moderator moved them.
234    pub left: Option<VoiceLeave>,
235    /// Their mute and deafen state; `None` when they left.
236    pub mute: Option<VoiceMute>,
237}
238
239/// Why someone left a voice channel.
240#[derive(Debug, Clone)]
241pub struct VoiceLeave {
242    /// Why.
243    pub reason: VoiceLeftReason,
244    /// The channel a moderator moved them to.
245    pub moved_to: Option<Channel>,
246}
247
248/// Someone's mute and deafen state in a voice channel.
249#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
250#[allow(
251    clippy::struct_excessive_bools,
252    reason = "four independent flags, as the host sends them"
253)]
254pub struct VoiceMute {
255    /// Muted by themselves.
256    pub self_mute: bool,
257    /// Deafened by themselves.
258    pub self_deaf: bool,
259    /// Muted by a moderator.
260    pub server_mute: bool,
261    /// Deafened by a moderator.
262    pub server_deaf: bool,
263}
264
265impl Client {
266    /// The driver's event as the application sees it.
267    pub(crate) fn wrap(&self, e: Inner) -> Event {
268        let community = |id| self.community(id);
269        match e {
270            Inner::Ready(c) => Event::Ready(community(c)),
271            Inner::Apps(c) => Event::AppsReady(community(c)),
272            Inner::Presences(c) => Event::PresencesReady(community(c)),
273            Inner::Message(m) => {
274                let channel = community(m.community).channel(m.channel);
275                Event::MessageCreate(Message {
276                    channel,
277                    id: m.id,
278                    sequence: m.sequence,
279                    author: m.author,
280                    content: m.content,
281                    embeds: m.embeds,
282                    components: m.components,
283                    flags: m.flags,
284                    interaction: m.interaction,
285                    reply_to: m.reply_to,
286                    mentions: m.mentions,
287                    attachments: m.attachments,
288                    timestamp: m.timestamp,
289                })
290            }
291            Inner::Update {
292                community: c,
293                channel,
294                actor,
295                event,
296            } => {
297                let c = community(c);
298                let channel = channel.map(|ch| c.channel(ch));
299                let actor = actor.map(|a| c.member(a));
300                self.update(c, channel, actor, *event)
301            }
302            Inner::Removed {
303                community: c,
304                reason,
305            } => Event::CommunityDelete {
306                community: community(c),
307                reason,
308            },
309            Inner::Moving { community: c, host } => Event::CommunityMoving {
310                community: community(c),
311                host,
312            },
313            Inner::Moved { community: c, host } => Event::CommunityMoved {
314                community: community(c),
315                host,
316            },
317            Inner::MoveRefused { community: c, code } => Event::CommunityMoveRefused {
318                community: community(c),
319                code,
320            },
321            Inner::Disconnected(c) => Event::Disconnect(community(c)),
322            Inner::Offline(true) => Event::Offline,
323            Inner::Offline(false) => Event::Online,
324            Inner::Warning(w) => Event::Warning(w),
325            Inner::DmCreated { community: c, dm } => {
326                let community = community(c);
327                let me = community.me().map_or(dm.participants[0], |m| m.id());
328                Event::DmCreate {
329                    channel: community.channel(dm.channel_id),
330                    recipient: community.member(dm.other(me)),
331                }
332            }
333            Inner::DmClosed {
334                community: c,
335                channel,
336            } => Event::DmDelete(community(c).channel(channel)),
337            Inner::Sent {
338                pending,
339                message: m,
340            } => {
341                let channel = community(m.community).channel(m.channel);
342                Event::MessageSent {
343                    pending,
344                    message: Message {
345                        channel,
346                        id: m.id,
347                        sequence: m.sequence,
348                        author: m.author,
349                        content: m.content,
350                        embeds: m.embeds,
351                        components: m.components,
352                        flags: m.flags,
353                        interaction: m.interaction,
354                        reply_to: m.reply_to,
355                        mentions: m.mentions,
356                        attachments: m.attachments,
357                        timestamp: m.timestamp,
358                    },
359                }
360            }
361            Inner::SendFailed {
362                pending,
363                community: c,
364                channel,
365                error,
366            } => Event::MessageSendFailed {
367                pending,
368                channel: community(c).channel(channel),
369                error,
370            },
371        }
372    }
373
374    fn update(
375        &self,
376        community: Community,
377        channel: Option<Channel>,
378        actor: Option<Member>,
379        event: Catalogue,
380    ) -> Event {
381        let member = |id| community.member(id);
382        match (event, channel) {
383            (Catalogue::MessageUpdated(m), Some(channel)) => Event::MessageUpdate {
384                message: channel.message(m.message_id),
385                author: actor,
386                content: m.content,
387                embeds: m.embeds,
388                mentions: m.mentions,
389                edited_at: m.edited_at,
390            },
391            (Catalogue::MessageDeleted(m), Some(channel)) => Event::MessageDelete {
392                message: channel.message(m.message_id),
393                by: actor,
394            },
395            (Catalogue::MessagesBulkDeleted(m), Some(channel)) => Event::MessageDeleteBulk {
396                messages: m
397                    .message_ids
398                    .iter()
399                    .map(|id| channel.message(*id))
400                    .collect(),
401                channel,
402            },
403            (Catalogue::ReactionAdded(r), Some(channel)) => Event::ReactionAdd(Reaction {
404                member: member(r.member_id),
405                message: channel.message(r.message_id),
406                emoji: r.emoji,
407            }),
408            (Catalogue::ReactionRemoved(r), Some(channel)) => Event::ReactionRemove(Reaction {
409                member: member(r.member_id),
410                message: channel.message(r.message_id),
411                emoji: r.emoji,
412            }),
413            (Catalogue::CommunityUpdated(_), _) => Event::CommunityUpdate(community),
414            (Catalogue::ChannelCreated(c), _) => {
415                Event::ChannelCreate(community.channel(c.channel.channel_id))
416            }
417            (Catalogue::ChannelUpdated(c), _) => {
418                Event::ChannelUpdate(community.channel(c.channel_id))
419            }
420            (Catalogue::ChannelDeleted(c), _) => {
421                Event::ChannelDelete(community.channel(c.channel_id))
422            }
423            (Catalogue::RoleCreated(r), _) => Event::RoleCreate(community.role(r.role_id)),
424            (Catalogue::RoleUpdated(r), _) => Event::RoleUpdate(community.role(r.role_id)),
425            (Catalogue::RoleDeleted(r), _) => Event::RoleDelete(community.role(r.role_id)),
426            (Catalogue::MemberJoined(m), _) => Event::MemberAdd(member(m.member_id)),
427            (Catalogue::MemberUpdated(m), _) => Event::MemberUpdate(member(m.member_id)),
428            (Catalogue::MemberRolesUpdated(m), _) => Event::MemberUpdate(member(m.member_id)),
429            (Catalogue::MemberTimedOut(m), _) => Event::MemberUpdate(member(m.member_id)),
430            (Catalogue::MemberLeft(m), _) => Event::MemberRemove(member(m.member_id)),
431            (Catalogue::CommandUpdated(u), _) => Event::CommandsUpdate {
432                community,
433                bot: u.bot_id,
434            },
435            (Catalogue::BotUpdated(card), _) => Event::BotUpdate { community, card },
436            (Catalogue::BotRemoved(r), _) => Event::BotRemove {
437                member: member(r.member_id),
438                community,
439                bot: r.bot_id,
440            },
441            (Catalogue::InteractionCreated(data), _) => {
442                Event::InteractionCreate(Box::new(Interaction { community, data }))
443            }
444            (Catalogue::InteractionMessage(m), channel) => {
445                Event::InteractionReply(EphemeralReply {
446                    channel,
447                    interaction: m.interaction_id,
448                    op: m.op,
449                    message: m.message,
450                })
451            }
452            (Catalogue::InteractionModal(m), channel) => Event::ModalOpen(ModalOpen {
453                channel,
454                interaction: m.interaction_id,
455                custom_id: m.custom_id,
456                title: m.title,
457                components: m.components,
458            }),
459            (Catalogue::InteractionAutocomplete(a), channel) => Event::Autocomplete(Suggestions {
460                community,
461                channel,
462                interaction: a.interaction_id,
463                choices: a.choices,
464            }),
465            (Catalogue::InteractionFailed(f), channel) => {
466                Event::InteractionFail(InteractionFailure {
467                    channel,
468                    interaction: f.interaction_id,
469                    reason: f.reason,
470                })
471            }
472            (Catalogue::VoiceJoined(v), _) => voice(&community, v.channel_id, &v.participant, true),
473            (Catalogue::VoiceUpdated(v), _) => {
474                voice(&community, v.channel_id, &v.participant, false)
475            }
476            (Catalogue::VoiceLeft(v), _) => Event::VoiceStateUpdate(VoiceState {
477                member: member(v.member_id),
478                channel: community.channel(v.channel_id),
479                joined: false,
480                left: Some(VoiceLeave {
481                    reason: v.reason,
482                    moved_to: v.moved_to.map(|c| community.channel(c)),
483                }),
484                mute: None,
485            }),
486            (Catalogue::SignalPresence(p), _) => Event::PresenceUpdate {
487                community,
488                presence: crate::Presence::from(&p),
489            },
490            (Catalogue::SignalTyping(t), _) => match crate::TypingNow::from_signal(&t) {
491                Some(typing) => Event::TypingStart {
492                    channel: community.channel(t.channel_id),
493                    typing,
494                },
495                None => Event::Warning("an empty typing signal".to_owned()),
496            },
497            (other, channel) => Event::Raw {
498                community,
499                channel,
500                actor,
501                event: Box::new(other),
502            },
503        }
504    }
505}
506
507fn voice(
508    community: &Community,
509    channel: zaun_community_protocol::ids::ChannelId,
510    p: &zaun_community_protocol::command::object::VoiceParticipant,
511    joined: bool,
512) -> Event {
513    Event::VoiceStateUpdate(VoiceState {
514        member: community.member(p.member_id),
515        channel: community.channel(channel),
516        joined,
517        left: None,
518        mute: Some(VoiceMute {
519            self_mute: p.self_mute,
520            self_deaf: p.self_deaf,
521            server_mute: p.server_mute,
522            server_deaf: p.server_deaf,
523        }),
524    })
525}