Skip to main content

matrix_sdk_base/
sync.rs

1// Copyright 2022 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The SDK's representation of the result of a `/sync` request.
16
17use 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/// Generalized representation of a `/sync` response.
47///
48/// This type is intended to be applicable regardless of the endpoint used for
49/// syncing.
50#[derive(Clone, Default)]
51pub struct SyncResponse {
52    /// Updates to rooms.
53    pub rooms: RoomUpdates,
54    /// Updates to the presence status of other users.
55    pub presence: Vec<Raw<PresenceEvent>>,
56    /// The global private data created by this user.
57    pub account_data: Vec<Raw<AnyGlobalAccountDataEvent>>,
58    /// Messages sent directly between devices.
59    pub to_device: Vec<ProcessedToDeviceEvent>,
60    /// New notifications per room.
61    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/// Updates to rooms in a [`SyncResponse`].
77#[derive(Clone, Default)]
78pub struct RoomUpdates {
79    /// The rooms that the user has left or been banned from.
80    pub left: BTreeMap<OwnedRoomId, LeftRoomUpdate>,
81    /// The rooms that the user has joined.
82    pub joined: BTreeMap<OwnedRoomId, JoinedRoomUpdate>,
83    /// The rooms that the user has been invited to.
84    pub invited: BTreeMap<OwnedRoomId, InvitedRoomUpdate>,
85    /// The rooms that the user has knocked on.
86    pub knocked: BTreeMap<OwnedRoomId, KnockedRoomUpdate>,
87}
88
89impl RoomUpdates {
90    /// Iterate over all room IDs, from [`RoomUpdates::left`],
91    /// [`RoomUpdates::joined`], [`RoomUpdates::invited`] and
92    /// [`RoomUpdates::knocked`].
93    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    /// Returns whether or not this update contains any changes to the list of
102    /// invited, joined, knocked or left rooms.
103    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/// Updates to joined rooms.
124#[derive(Clone, Default)]
125pub struct JoinedRoomUpdate {
126    /// Counts of unread notifications for this room.
127    pub unread_notifications: UnreadNotificationsCount,
128    /// The timeline of messages and state changes in the room.
129    pub timeline: Timeline,
130    /// Updates to the state.
131    ///
132    /// If `since` is missing or `full_state` is true, the start point of the
133    /// update is the beginning of the timeline. Otherwise, the start point is
134    /// the time specified in `since`.
135    ///
136    /// If `state_after` was used, the end point of the update is the end of the
137    /// `timeline`. Otherwise, the end point of these updates is the start of
138    /// the `timeline`, and to calculate room state we must scan the `timeline`
139    /// for state events as well as using this information in this property.
140    pub state: State,
141    /// The private data that this user has attached to this room.
142    pub account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
143    /// The ephemeral events in the room that aren't recorded in the timeline or
144    /// state of the room. e.g. typing.
145    pub ephemeral: Vec<Raw<AnySyncEphemeralRoomEvent>>,
146    /// Collection of ambiguity changes that room member events trigger.
147    ///
148    /// This is a map of event ID of the `m.room.member` event to the details of
149    /// the ambiguity change.
150    pub ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
151    /// Collection of avatar changes that room member events trigger.
152    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/// Counts of unread notifications for a room.
192#[derive(Copy, Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
193pub struct UnreadNotificationsCount {
194    /// The number of unread notifications for this room with the highlight flag
195    /// set.
196    pub highlight_count: u64,
197    /// The total number of unread notifications for this room.
198    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/// Updates to left rooms.
211#[derive(Clone, Default)]
212pub struct LeftRoomUpdate {
213    /// The timeline of messages and state changes in the room up to the point
214    /// when the user left.
215    pub timeline: Timeline,
216    /// Updates to the state.
217    ///
218    /// If `since` is missing or `full_state` is true, the start point of the
219    /// update is the beginning of the timeline. Otherwise, the start point is
220    /// the time specified in `since`.
221    ///
222    /// If `state_after` was used, the end point of the update is the end of the
223    /// `timeline`. Otherwise, the end point of these updates is the start of
224    /// the `timeline`, and to calculate room state we must scan the `timeline`
225    /// for state events as well as using this information in this property.
226    pub state: State,
227    /// The private data that this user has attached to this room.
228    pub account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
229    /// Collection of ambiguity changes that room member events trigger.
230    ///
231    /// This is a map of event ID of the `m.room.member` event to the details of
232    /// the ambiguity change.
233    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/// Events in the room.
260#[derive(Clone, Debug, Default)]
261pub struct Timeline {
262    /// True if the number of events returned was limited by the `limit` on the
263    /// filter.
264    pub limited: bool,
265
266    /// A token that can be supplied to to the `from` parameter of the
267    /// `/rooms/{roomId}/messages` endpoint.
268    pub prev_batch: Option<String>,
269
270    /// A list of events.
271    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/// State changes in the room.
281#[derive(Clone)]
282pub enum State {
283    /// The state changes between the previous sync and the start of the
284    /// timeline.
285    ///
286    /// To get the full list of state changes since the previous sync, the state
287    /// events in [`Timeline`] must be added to these events to update the local
288    /// state.
289    Before(Vec<Raw<AnySyncStateEvent>>),
290
291    /// The state changes between the previous sync and the end of the timeline.
292    ///
293    /// This contains the full list of state changes since the previous sync.
294    /// State events in [`Timeline`] must be ignored to update the local state.
295    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/// A notification triggered by a sync response.
337#[derive(Clone)]
338pub struct Notification {
339    /// The actions to perform when the conditions for this rule are met.
340    pub actions: Vec<Action>,
341
342    /// The event that triggered the notification.
343    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}