1use 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#[derive(Debug, Clone, PartialEq, serde::Serialize)]
19pub struct CommunityData {
20 pub id: CommunityId,
22 pub me: MemberId,
24 pub is_owner: bool,
26 pub loaded: bool,
29 pub name: String,
32 pub description: Option<String>,
34 pub profile: Option<CommunityProfile>,
36 pub channels: BTreeMap<ChannelId, Channel>,
38 pub dms: BTreeMap<ChannelId, crate::dm::DmChannel>,
41 pub roles: BTreeMap<RoleId, Role>,
43 pub members: BTreeMap<MemberId, Member>,
45 pub attachments: Option<HostAttachments>,
48 pub capabilities: Vec<String>,
51 pub commands: BTreeMap<CommandId, ApplicationCommand>,
54 pub bots: BTreeMap<BotId, BotCard>,
56 pub typing: BTreeMap<ChannelId, crate::typing::TypingSeen>,
59 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 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 #[must_use]
101 pub fn supports(&self, capability: &str) -> bool {
102 self.capabilities.iter().any(|c| c == capability)
103 }
104
105 #[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 #[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 #[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 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 pub(crate) fn absorb(&mut self, item: SnapshotItem) -> Option<crate::dm::DmChannel> {
150 match item {
151 SnapshotItem::Channel(c) => {
152 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 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 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); }
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}