Skip to main content

zaun_client/
cache.rs

1//! The local view of one community: filled from `sync.snapshot`, kept current by its events.
2
3use std::collections::BTreeMap;
4
5use zaun_community_protocol::command::object::{
6    ApplicationCommand, BotCard, Channel, CommunityProfile, Member, Role, VoiceParticipant,
7};
8use zaun_community_protocol::command::session::HostAttachments;
9use zaun_community_protocol::command::sync::SnapshotItem;
10use zaun_community_protocol::event::Event;
11use zaun_community_protocol::ids::{BotId, ChannelId, CommandId, CommunityId, MemberId, RoleId};
12
13/// A community as this client last heard of it. Cheap to clone; a clone does not update.
14///
15/// Every map is bounded by the community itself: entries leave when the host reports the
16/// channel, role or member gone. `members` holds the members this client has heard of
17/// (events, [`Community::fetch_members`](crate::Community::fetch_members)), not always all.
18#[derive(Debug, Clone, PartialEq, serde::Serialize)]
19pub struct CommunityData {
20    /// The community.
21    pub id: CommunityId,
22    /// This client's member id in it.
23    pub me: MemberId,
24    /// Whether this client is the owner.
25    pub is_owner: bool,
26    /// The host's snapshot has loaded at least once ([`Event::Ready`](crate::Event::Ready)
27    /// was said).
28    pub loaded: bool,
29    /// The community's name, from its descriptor as the host's welcome proved it (empty
30    /// until then).
31    pub name: String,
32    /// Its description, from the same descriptor.
33    pub description: Option<String>,
34    /// The host-managed profile, once the snapshot has it.
35    pub profile: Option<CommunityProfile>,
36    /// Channels and categories this member can see.
37    pub channels: BTreeMap<ChannelId, Channel>,
38    /// DM: this member's open direct messages with bots, by channel. Entries leave when the
39    /// DM is closed here or the community is.
40    pub dms: BTreeMap<ChannelId, crate::dm::DmChannel>,
41    /// Roles, `@everyone` (`RoleId::EVERYONE`) included.
42    pub roles: BTreeMap<RoleId, Role>,
43    /// Members heard of, this client included once the snapshot arrived.
44    pub members: BTreeMap<MemberId, Member>,
45    /// What the host takes as attachments (its largest file, the file servers it downloads
46    /// from), from its last welcome; `None` before one, or when the host did not say.
47    pub attachments: Option<HostAttachments>,
48    /// The capabilities this client and the host both support (`frag`, `embeds`, …), from the
49    /// host's last welcome; empty before one. Replaced at each welcome, so it never grows.
50    pub capabilities: Vec<String>,
51    /// The bots' application commands (§8.14), each with its `bot_id`. A bot's whole list is
52    /// replaced by `command.updated` and dropped with the bot, so it never outgrows the bots.
53    pub commands: BTreeMap<CommandId, ApplicationCommand>,
54    /// Installed bots' public cards (§8.13); an entry leaves with `bot.removed`.
55    pub bots: BTreeMap<BotId, BotCard>,
56    /// Typing: who else is typing per channel ([`CommunityData::typing_in`]). One entry per
57    /// channel, replaced by each `signal.typing`, gone with the channel.
58    pub typing: BTreeMap<ChannelId, crate::typing::TypingSeen>,
59    /// Presence: every member not offline, as others see them (`presence.list`, then each
60    /// `signal.presence`); see [`CommunityData::presence_of`].
61    pub presences: BTreeMap<MemberId, zaun_community_protocol::event::PresenceSignal>,
62}
63
64impl CommunityData {
65    pub(crate) fn new(id: CommunityId, me: MemberId, is_owner: bool) -> Self {
66        Self {
67            id,
68            me,
69            is_owner,
70            loaded: false,
71            name: String::new(),
72            description: None,
73            profile: None,
74            channels: BTreeMap::new(),
75            dms: BTreeMap::new(),
76            roles: BTreeMap::new(),
77            members: BTreeMap::new(),
78            attachments: None,
79            capabilities: Vec::new(),
80            commands: BTreeMap::new(),
81            bots: BTreeMap::new(),
82            typing: BTreeMap::new(),
83            presences: BTreeMap::new(),
84        }
85    }
86
87    /// Replaces bot `bot`'s commands (`command.updated`, or its part of `command.list`).
88    pub(crate) fn set_commands(&mut self, bot: BotId, commands: &[ApplicationCommand]) {
89        self.commands.retain(|_, c| c.bot_id != Some(bot));
90        for c in commands {
91            if let Some(id) = c.command_id {
92                let mut c = c.clone();
93                c.bot_id = Some(bot);
94                self.commands.insert(id, c);
95            }
96        }
97    }
98
99    /// Whether the host's last welcome listed `capability`.
100    #[must_use]
101    pub fn supports(&self, capability: &str) -> bool {
102        self.capabilities.iter().any(|c| c == capability)
103    }
104
105    /// The first channel named `name` (channel names are not unique).
106    #[must_use]
107    pub fn channel_by_name(&self, name: &str) -> Option<&Channel> {
108        self.channels.values().find(|c| c.name == name)
109    }
110
111    /// The first role named `name`.
112    #[must_use]
113    pub fn role_by_name(&self, name: &str) -> Option<&Role> {
114        self.roles.values().find(|r| r.name == name)
115    }
116
117    /// Channels in display order: by position, categories' children after them.
118    #[must_use]
119    pub fn ordered_channels(&self) -> Vec<&Channel> {
120        let mut list: Vec<&Channel> = self.channels.values().collect();
121        list.sort_by_key(|c| {
122            (
123                c.parent_id.map(|p| self.position(&p)),
124                c.position,
125                c.channel_id,
126            )
127        });
128        list
129    }
130
131    fn position(&self, id: &ChannelId) -> u32 {
132        self.channels.get(id).map_or(0, |c| c.position)
133    }
134
135    /// Puts a participant in a voice channel's roster, without its key material.
136    fn voice_set(&mut self, channel: ChannelId, p: &VoiceParticipant) {
137        let Some(c) = self.channels.get_mut(&channel) else {
138            return;
139        };
140        let list = c.voice_participants.get_or_insert_with(Vec::new);
141        list.retain(|q| q.member_id != p.member_id);
142        let mut p = p.clone();
143        p.key_package = None;
144        p.member_public_key = None;
145        list.push(p);
146    }
147
148    /// Takes one snapshot item; a DM the cache did not know yet is returned.
149    pub(crate) fn absorb(&mut self, item: SnapshotItem) -> Option<crate::dm::DmChannel> {
150        match item {
151            SnapshotItem::Channel(c) => {
152                // DM: a DM is never one of the visible channels; it goes to `dms`.
153                if let Some(dm) = crate::dm::DmChannel::from_channel(&c) {
154                    return self
155                        .dms
156                        .insert(dm.channel_id, dm.clone())
157                        .is_none()
158                        .then_some(dm);
159                }
160                self.channels.insert(c.channel_id, *c);
161            }
162            SnapshotItem::Role(r) => {
163                self.roles.insert(r.role_id, r);
164            }
165            SnapshotItem::Community(c) => {
166                self.profile = Some(c.profile);
167                self.members.insert(c.member.member_id, c.member);
168            }
169        }
170        None
171    }
172
173    /// Applies one event; message, reaction, signal and report events change nothing here.
174    pub(crate) fn apply(&mut self, event: &Event) {
175        match event {
176            Event::CommunityUpdated(p) => self.profile = Some(*p),
177            Event::ChannelCreated(c) => {
178                if crate::dm::DmChannel::from_channel(&c.channel).is_none() {
179                    self.channels
180                        .insert(c.channel.channel_id, c.channel.clone());
181                }
182            }
183            // DM: opened (by either side) and closed for this member.
184            Event::DmCreated(c) => {
185                if let Some(dm) = crate::dm::DmChannel::from_channel(c) {
186                    self.dms.insert(dm.channel_id, dm);
187                }
188            }
189            Event::DmClosed(d) => {
190                self.dms.remove(&d.channel_id);
191            }
192            Event::ChannelUpdated(c) => {
193                self.channels.insert(c.channel_id, (**c).clone());
194            }
195            Event::ChannelDeleted(d) => {
196                self.channels.remove(&d.channel_id);
197                self.typing.remove(&d.channel_id); // typing
198            }
199            Event::ChannelReordered(r) => {
200                for p in &r.positions {
201                    if let Some(c) = self.channels.get_mut(&p.channel_id) {
202                        c.position = p.position;
203                        c.parent_id = p.parent_id;
204                    }
205                }
206            }
207            Event::RoleCreated(r) | Event::RoleUpdated(r) => {
208                self.roles.insert(r.role_id, r.clone());
209            }
210            Event::RoleDeleted(d) => {
211                self.roles.remove(&d.role_id);
212                for m in self.members.values_mut() {
213                    m.role_ids.retain(|id| *id != d.role_id);
214                }
215            }
216            Event::RoleReordered(r) => {
217                for p in &r.positions {
218                    if let Some(role) = self.roles.get_mut(&p.role_id) {
219                        role.position = p.position;
220                    }
221                }
222            }
223            Event::MemberRolesUpdated(u) => {
224                if let Some(m) = self.members.get_mut(&u.member_id) {
225                    m.role_ids.clone_from(&u.role_ids);
226                }
227            }
228            Event::MemberTimedOut(t) => {
229                if let Some(m) = self.members.get_mut(&t.member_id) {
230                    m.timeout_until = t.until;
231                }
232            }
233            Event::MemberJoined(m) | Event::MemberUpdated(m) | Event::MembershipRequested(m) => {
234                self.members.insert(m.member_id, m.clone());
235            }
236            Event::MembershipUpdated(u) => {
237                if let Some(m) = self.members.get_mut(&u.member_id) {
238                    m.state = Some(u.state);
239                }
240            }
241            Event::MemberLeft(l) => {
242                self.members.remove(&l.member_id);
243            }
244            Event::MessageCreated(_)
245            | Event::MessageUpdated(_)
246            | Event::MessageDeleted(_)
247            | Event::MessagesBulkDeleted(_)
248            | Event::ReactionAdded(_)
249            | Event::ReactionRemoved(_)
250            | Event::DescriptorUpdated(_)
251            | Event::MemberRemoved(_)
252            | Event::AdmissionPolicyUpdated(_)
253            | Event::LockdownUpdated(_)
254            | Event::ReportCreated(_)
255            | Event::ReportUpdated(_)
256            | Event::SignalTyping(_)
257            | Event::SignalPresence(_)
258            | Event::AttachmentUpdated(_)
259            | Event::VoiceSignal(_)
260            | Event::VoiceKeys(_)
261            | Event::InteractionCreated(_)
262            | Event::InteractionMessage(_)
263            | Event::InteractionModal(_)
264            | Event::InteractionAutocomplete(_)
265            | Event::InteractionFailed(_) => {}
266            Event::BotUpdated(card) => {
267                self.bots.insert(card.bot_id, (**card).clone());
268            }
269            Event::BotRemoved(r) => {
270                self.bots.remove(&r.bot_id);
271                self.commands.retain(|_, c| c.bot_id != Some(r.bot_id));
272            }
273            Event::CommandUpdated(u) => self.set_commands(u.bot_id, &u.commands),
274            Event::VoiceJoined(j) => self.voice_set(j.channel_id, &j.participant),
275            Event::VoiceUpdated(u) => self.voice_set(u.channel_id, &u.participant),
276            Event::VoiceLeft(l) => {
277                if let Some(list) = self
278                    .channels
279                    .get_mut(&l.channel_id)
280                    .and_then(|c| c.voice_participants.as_mut())
281                {
282                    list.retain(|p| p.voice_session != l.voice_session);
283                }
284            }
285        }
286    }
287}