1use std::{collections::BTreeMap, fmt};
18
19use matrix_sdk_common::{
20 debug::DebugRawEvent,
21 deserialized_responses::{ProcessedToDeviceEvent, TimelineEvent},
22};
23pub use ruma::api::client::sync::sync_events::v3::{
24 InvitedRoom as InvitedRoomUpdate, KnockedRoom as KnockedRoomUpdate,
25};
26use ruma::{
27 OwnedEventId, OwnedMxcUri, OwnedRoomId, OwnedUserId,
28 api::client::sync::sync_events::UnreadNotificationsCount as RumaUnreadNotificationsCount,
29 events::{
30 AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnySyncEphemeralRoomEvent,
31 AnySyncStateEvent, presence::PresenceEvent,
32 },
33 push::Action,
34 serde::Raw,
35};
36use serde::{Deserialize, Serialize};
37
38use crate::{
39 debug::{
40 DebugInvitedRoom, DebugKnockedRoom, DebugListOfProcessedToDeviceEvents,
41 DebugListOfRawEvents, DebugListOfRawEventsNoId,
42 },
43 deserialized_responses::{AmbiguityChange, RawAnySyncOrStrippedTimelineEvent},
44};
45
46#[derive(Clone, Default)]
51pub struct SyncResponse {
52 pub rooms: RoomUpdates,
54 pub presence: Vec<Raw<PresenceEvent>>,
56 pub account_data: Vec<Raw<AnyGlobalAccountDataEvent>>,
58 pub to_device: Vec<ProcessedToDeviceEvent>,
60 pub notifications: BTreeMap<OwnedRoomId, Vec<Notification>>,
62}
63
64#[cfg(not(tarpaulin_include))]
65impl fmt::Debug for SyncResponse {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 f.debug_struct("SyncResponse")
68 .field("rooms", &self.rooms)
69 .field("account_data", &DebugListOfRawEventsNoId(&self.account_data))
70 .field("to_device", &DebugListOfProcessedToDeviceEvents(&self.to_device))
71 .field("notifications", &self.notifications)
72 .finish_non_exhaustive()
73 }
74}
75
76#[derive(Clone, Default)]
78pub struct RoomUpdates {
79 pub left: BTreeMap<OwnedRoomId, LeftRoomUpdate>,
81 pub joined: BTreeMap<OwnedRoomId, JoinedRoomUpdate>,
83 pub invited: BTreeMap<OwnedRoomId, InvitedRoomUpdate>,
85 pub knocked: BTreeMap<OwnedRoomId, KnockedRoomUpdate>,
87}
88
89impl RoomUpdates {
90 pub fn iter_all_room_ids(&self) -> impl Iterator<Item = &OwnedRoomId> {
94 self.left
95 .keys()
96 .chain(self.joined.keys())
97 .chain(self.invited.keys())
98 .chain(self.knocked.keys())
99 }
100
101 pub fn is_empty(&self) -> bool {
104 self.invited.is_empty()
105 && self.joined.is_empty()
106 && self.knocked.is_empty()
107 && self.left.is_empty()
108 }
109}
110
111#[cfg(not(tarpaulin_include))]
112impl fmt::Debug for RoomUpdates {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 f.debug_struct("RoomUpdates")
115 .field("left", &self.left)
116 .field("joined", &self.joined)
117 .field("invited", &DebugInvitedRoomUpdates(&self.invited))
118 .field("knocked", &DebugKnockedRoomUpdates(&self.knocked))
119 .finish()
120 }
121}
122
123#[derive(Clone, Default)]
125pub struct JoinedRoomUpdate {
126 pub unread_notifications: UnreadNotificationsCount,
128 pub timeline: Timeline,
130 pub state: State,
141 pub account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
143 pub ephemeral: Vec<Raw<AnySyncEphemeralRoomEvent>>,
146 pub ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
151 pub avatar_changes: Option<BTreeMap<OwnedUserId, Option<OwnedMxcUri>>>,
153}
154
155#[cfg(not(tarpaulin_include))]
156impl fmt::Debug for JoinedRoomUpdate {
157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158 f.debug_struct("JoinedRoomUpdate")
159 .field("unread_notifications", &self.unread_notifications)
160 .field("timeline", &self.timeline)
161 .field("state", &self.state)
162 .field("account_data", &DebugListOfRawEventsNoId(&self.account_data))
163 .field("ephemeral", &self.ephemeral)
164 .field("ambiguity_changes", &self.ambiguity_changes)
165 .finish()
166 }
167}
168
169impl JoinedRoomUpdate {
170 pub(crate) fn new(
171 timeline: Timeline,
172 state: State,
173 account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
174 ephemeral: Vec<Raw<AnySyncEphemeralRoomEvent>>,
175 unread_notifications: UnreadNotificationsCount,
176 ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
177 avatar_changes: Option<BTreeMap<OwnedUserId, Option<OwnedMxcUri>>>,
178 ) -> Self {
179 Self {
180 unread_notifications,
181 timeline,
182 state,
183 account_data,
184 ephemeral,
185 ambiguity_changes,
186 avatar_changes,
187 }
188 }
189}
190
191#[derive(Copy, Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
193pub struct UnreadNotificationsCount {
194 pub highlight_count: u64,
197 pub notification_count: u64,
199}
200
201impl From<RumaUnreadNotificationsCount> for UnreadNotificationsCount {
202 fn from(notifications: RumaUnreadNotificationsCount) -> Self {
203 Self {
204 highlight_count: notifications.highlight_count.map(|c| c.into()).unwrap_or(0),
205 notification_count: notifications.notification_count.map(|c| c.into()).unwrap_or(0),
206 }
207 }
208}
209
210#[derive(Clone, Default)]
212pub struct LeftRoomUpdate {
213 pub timeline: Timeline,
216 pub state: State,
227 pub account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
229 pub ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
234}
235
236impl LeftRoomUpdate {
237 pub(crate) fn new(
238 timeline: Timeline,
239 state: State,
240 account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
241 ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
242 ) -> Self {
243 Self { timeline, state, account_data, ambiguity_changes }
244 }
245}
246
247#[cfg(not(tarpaulin_include))]
248impl fmt::Debug for LeftRoomUpdate {
249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 f.debug_struct("LeftRoomUpdate")
251 .field("timeline", &self.timeline)
252 .field("state", &self.state)
253 .field("account_data", &DebugListOfRawEventsNoId(&self.account_data))
254 .field("ambiguity_changes", &self.ambiguity_changes)
255 .finish()
256 }
257}
258
259#[derive(Clone, Debug, Default)]
261pub struct Timeline {
262 pub limited: bool,
265
266 pub prev_batch: Option<String>,
269
270 pub events: Vec<TimelineEvent>,
272}
273
274impl Timeline {
275 pub(crate) fn new(limited: bool, prev_batch: Option<String>) -> Self {
276 Self { limited, prev_batch, ..Default::default() }
277 }
278}
279
280#[derive(Clone)]
282pub enum State {
283 Before(Vec<Raw<AnySyncStateEvent>>),
290
291 After(Vec<Raw<AnySyncStateEvent>>),
296}
297
298impl Default for State {
299 fn default() -> Self {
300 Self::Before(vec![])
301 }
302}
303
304#[cfg(not(tarpaulin_include))]
305impl fmt::Debug for State {
306 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307 match self {
308 Self::Before(events) => {
309 f.debug_tuple("Before").field(&DebugListOfRawEvents(events)).finish()
310 }
311 Self::After(events) => {
312 f.debug_tuple("After").field(&DebugListOfRawEvents(events)).finish()
313 }
314 }
315 }
316}
317
318struct DebugInvitedRoomUpdates<'a>(&'a BTreeMap<OwnedRoomId, InvitedRoomUpdate>);
319
320#[cfg(not(tarpaulin_include))]
321impl fmt::Debug for DebugInvitedRoomUpdates<'_> {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 f.debug_map().entries(self.0.iter().map(|(k, v)| (k, DebugInvitedRoom(v)))).finish()
324 }
325}
326
327struct DebugKnockedRoomUpdates<'a>(&'a BTreeMap<OwnedRoomId, KnockedRoomUpdate>);
328
329#[cfg(not(tarpaulin_include))]
330impl fmt::Debug for DebugKnockedRoomUpdates<'_> {
331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332 f.debug_map().entries(self.0.iter().map(|(k, v)| (k, DebugKnockedRoom(v)))).finish()
333 }
334}
335
336#[derive(Clone)]
338pub struct Notification {
339 pub actions: Vec<Action>,
341
342 pub event: RawAnySyncOrStrippedTimelineEvent,
344}
345
346#[cfg(not(tarpaulin_include))]
347impl fmt::Debug for Notification {
348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
349 let event_debug = match &self.event {
350 RawAnySyncOrStrippedTimelineEvent::Sync(ev) => DebugRawEvent(ev),
351 RawAnySyncOrStrippedTimelineEvent::Stripped(ev) => {
352 DebugRawEvent(ev.cast_ref_unchecked())
353 }
354 };
355
356 f.debug_struct("Notification")
357 .field("actions", &self.actions)
358 .field("event", &event_debug)
359 .finish()
360 }
361}
362
363#[cfg(test)]
364mod tests {
365 use std::collections::BTreeMap;
366
367 use assert_matches::assert_matches;
368 use ruma::room_id;
369
370 use super::{
371 InvitedRoomUpdate, JoinedRoomUpdate, KnockedRoomUpdate, LeftRoomUpdate, RoomUpdates,
372 };
373
374 #[test]
375 fn test_room_updates_iter_all_room_ids() {
376 let room_id_0 = room_id!("!r0");
377 let room_id_1 = room_id!("!r1");
378 let room_id_2 = room_id!("!r2");
379 let room_id_3 = room_id!("!r3");
380 let room_id_4 = room_id!("!r4");
381 let room_id_5 = room_id!("!r5");
382 let room_id_6 = room_id!("!r6");
383 let room_id_7 = room_id!("!r7");
384 let room_updates = RoomUpdates {
385 left: {
386 let mut left = BTreeMap::new();
387 left.insert(room_id_0.to_owned(), LeftRoomUpdate::default());
388 left.insert(room_id_1.to_owned(), LeftRoomUpdate::default());
389 left
390 },
391 joined: {
392 let mut joined = BTreeMap::new();
393 joined.insert(room_id_2.to_owned(), JoinedRoomUpdate::default());
394 joined.insert(room_id_3.to_owned(), JoinedRoomUpdate::default());
395 joined
396 },
397 invited: {
398 let mut invited = BTreeMap::new();
399 invited.insert(room_id_4.to_owned(), InvitedRoomUpdate::default());
400 invited.insert(room_id_5.to_owned(), InvitedRoomUpdate::default());
401 invited
402 },
403 knocked: {
404 let mut knocked = BTreeMap::new();
405 knocked.insert(room_id_6.to_owned(), KnockedRoomUpdate::default());
406 knocked.insert(room_id_7.to_owned(), KnockedRoomUpdate::default());
407 knocked
408 },
409 };
410
411 let mut iter = room_updates.iter_all_room_ids();
412 assert_matches!(iter.next(), Some(room_id) => assert_eq!(room_id, room_id_0));
413 assert_matches!(iter.next(), Some(room_id) => assert_eq!(room_id, room_id_1));
414 assert_matches!(iter.next(), Some(room_id) => assert_eq!(room_id, room_id_2));
415 assert_matches!(iter.next(), Some(room_id) => assert_eq!(room_id, room_id_3));
416 assert_matches!(iter.next(), Some(room_id) => assert_eq!(room_id, room_id_4));
417 assert_matches!(iter.next(), Some(room_id) => assert_eq!(room_id, room_id_5));
418 assert_matches!(iter.next(), Some(room_id) => assert_eq!(room_id, room_id_6));
419 assert_matches!(iter.next(), Some(room_id) => assert_eq!(room_id, room_id_7));
420 assert!(iter.next().is_none());
421 }
422
423 #[test]
424 fn test_empty_room_updates() {
425 let room_updates = RoomUpdates::default();
426
427 let mut iter = room_updates.iter_all_room_ids();
428 assert!(iter.next().is_none());
429
430 assert!(room_updates.is_empty());
431 }
432}