Skip to main content

ruma_client_api/sync/sync_events/
msc4186.rs

1//! `POST /_matrix/client/unstable/org.matrix.simplified_msc3575/sync` ([MSC])
2//!
3//! A simplified version of sliding sync ([MSC3575]).
4//!
5//! Get all new events in a sliding window of rooms since the last sync or a given point in time.
6//!
7//! [MSC3575]: https://github.com/matrix-org/matrix-spec-proposals/pull/3575
8//! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186
9
10use std::{collections::BTreeMap, time::Duration};
11
12use js_int::UInt;
13use js_option::JsOption;
14use ruma_common::{
15    OwnedMxcUri, OwnedRoomId, OwnedUserId,
16    api::{auth_scheme::AccessToken, request, response},
17    metadata,
18    presence::PresenceState,
19    serde::{Raw, duration::opt_ms},
20};
21use ruma_events::{AnySyncStateEvent, AnySyncTimelineEvent, StateEventType};
22use serde::{Deserialize, Serialize};
23
24use super::{UnreadNotificationsCount, v4};
25
26metadata! {
27    method: POST,
28    rate_limited: false,
29    authentication: AccessToken,
30    history: {
31        unstable("org.matrix.simplified_msc3575") => "/_matrix/client/unstable/org.matrix.simplified_msc3575/sync",
32    }
33}
34
35/// Request type for the `/sync` endpoint.
36#[request]
37#[derive(Default)]
38pub struct Request {
39    /// A point in time to continue a sync from.
40    ///
41    /// This is an opaque value taken from the `pos` field of a previous `/sync`
42    /// response. A `None` value asks the server to start a new _session_ (mind
43    /// it can be costly)
44    #[serde(skip_serializing_if = "Option::is_none")]
45    #[ruma_api(query)]
46    pub pos: Option<String>,
47
48    /// A unique string identifier for this connection to the server.
49    ///
50    /// If this is missing, only one sliding sync connection can be made to
51    /// the server at any one time. Clients need to set this to allow more
52    /// than one connection concurrently, so the server can distinguish between
53    /// connections. This must be provided with every request, if your client
54    /// needs more than one concurrent connection.
55    ///
56    /// Limitation: it must not contain more than 16 chars, due to it being
57    /// required with every request.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub conn_id: Option<String>,
60
61    /// Allows clients to know what request params reached the server,
62    /// functionally similar to txn IDs on `/send` for events.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub txn_id: Option<String>,
65
66    /// The maximum time to poll before responding to this request.
67    ///
68    /// `None` means no timeout, so virtually an infinite wait from the server.
69    #[serde(with = "opt_ms", default, skip_serializing_if = "Option::is_none")]
70    #[ruma_api(query)]
71    pub timeout: Option<Duration>,
72
73    /// Controls whether the client is automatically marked as online by polling this API.
74    ///
75    /// Defaults to `PresenceState::Online`.
76    #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
77    #[ruma_api(query)]
78    pub set_presence: PresenceState,
79
80    /// Lists of rooms we are interested by, represented by ranges.
81    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
82    pub lists: BTreeMap<String, request::List>,
83
84    /// Specific rooms we are interested by.
85    ///
86    /// It is useful to receive updates from rooms that are possibly
87    /// out-of-range of all the lists (see [`Self::lists`]).
88    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
89    pub room_subscriptions: BTreeMap<OwnedRoomId, request::RoomSubscription>,
90
91    /// Extensions.
92    #[serde(default, skip_serializing_if = "request::Extensions::is_empty")]
93    pub extensions: request::Extensions,
94}
95
96impl Request {
97    /// Creates an empty `Request`.
98    pub fn new() -> Self {
99        Default::default()
100    }
101}
102
103impl From<v4::Request> for Request {
104    fn from(value: v4::Request) -> Self {
105        let v4::Request {
106            conn_id,
107            pos,
108            timeout,
109            set_presence,
110            lists,
111            room_subscriptions,
112            extensions,
113        } = value;
114
115        Self {
116            pos,
117            conn_id,
118            txn_id: None,
119            timeout,
120            set_presence,
121            lists: lists.into_iter().map(|(key, list)| (key, list.into())).collect(),
122            room_subscriptions: room_subscriptions
123                .into_iter()
124                .map(|(room_id, subscription)| (room_id, subscription.into()))
125                .collect(),
126            extensions: extensions.into(),
127        }
128    }
129}
130
131/// HTTP types related to a [`Request`].
132pub mod request {
133    use ruma_common::{RoomId, directory::RoomTypeFilter, serde::deserialize_cow_str};
134    use serde::de::Error as _;
135
136    #[cfg(feature = "unstable-msc4308")]
137    pub use super::v4::request::ThreadSubscriptions;
138    #[cfg(feature = "unstable-msc4360")]
139    pub use super::v4::request::Threads;
140    pub use super::v4::request::{E2EE, ToDevice};
141    use super::{BTreeMap, Deserialize, OwnedRoomId, Serialize, StateEventType, UInt, v4};
142
143    /// A sliding sync list request (see [`super::Request::lists`]).
144    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
145    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
146    pub struct List {
147        /// The ranges of rooms we're interested in.
148        pub ranges: Vec<(UInt, UInt)>,
149
150        /// The details to be included per room.
151        #[serde(flatten)]
152        pub room_details: RoomDetails,
153
154        /// Filters to apply to the list before sorting.
155        #[serde(skip_serializing_if = "Option::is_none")]
156        pub filters: Option<ListFilters>,
157    }
158
159    /// The conversion is lossy: the `exclude` field of the required state and the `spaces`,
160    /// `tags` and `not_tags` filters are dropped.
161    ///
162    /// A missing `range` becomes a range covering all the rooms.
163    impl From<v4::request::List> for List {
164        fn from(value: v4::request::List) -> Self {
165            let v4::request::List { range, required_state, timeline_limit, filters } = value;
166
167            Self {
168                ranges: vec![range.unwrap_or((UInt::MIN, UInt::MAX))],
169                room_details: RoomDetails {
170                    required_state: required_state_from_v4(required_state),
171                    timeline_limit,
172                },
173                filters: (!filters.is_empty()).then(|| filters.into()),
174            }
175        }
176    }
177
178    /// A sliding sync list request filters (see [`List::filters`]).
179    ///
180    /// All fields are applied with _AND_ operators. The absence of fields
181    /// implies no filter on that criteria: it does NOT imply `false`.
182    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
183    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
184    pub struct ListFilters {
185        /// Whether to return only DM rooms (as determined by the `m.direct` account data event),
186        /// only non-DM rooms, or both.
187        #[serde(skip_serializing_if = "Option::is_none")]
188        pub is_dm: Option<bool>,
189
190        /// Whether to return only encrypted rooms (as determined by the existence of an
191        /// `m.room.encryption` state event), only unencrypted rooms, or both.
192        #[serde(skip_serializing_if = "Option::is_none")]
193        pub is_encrypted: Option<bool>,
194
195        /// Whether to return only invited rooms, only joined rooms, or both.
196        #[serde(skip_serializing_if = "Option::is_none")]
197        pub is_invite: Option<bool>,
198
199        /// Only list rooms with these create-types, or all.
200        ///
201        /// If a room type is specified in both `room_types` and `not_room_types`,
202        /// `not_room_types` wins and the corresponding rooms are not included.
203        #[serde(default, skip_serializing_if = "<[_]>::is_empty")]
204        pub room_types: Vec<RoomTypeFilter>,
205
206        /// Only list rooms that are not of these create-types, or all.
207        ///
208        /// If a room type is specified in both `room_types` and `not_room_types`,
209        /// `not_room_types` wins and the corresponding rooms are not included.
210        #[serde(default, skip_serializing_if = "<[_]>::is_empty")]
211        pub not_room_types: Vec<RoomTypeFilter>,
212    }
213
214    /// The conversion is lossy: the `spaces`, `tags` and `not_tags` filters are dropped.
215    impl From<v4::request::ListFilters> for ListFilters {
216        fn from(value: v4::request::ListFilters) -> Self {
217            let v4::request::ListFilters {
218                is_dm,
219                spaces: _,
220                is_encrypted,
221                is_invited,
222                room_types,
223                not_room_types,
224                tags: _,
225                not_tags: _,
226            } = value;
227
228            Self {
229                is_dm: is_dm.into(),
230                is_encrypted: is_encrypted.into(),
231                is_invite: is_invited.into(),
232                room_types,
233                not_room_types,
234            }
235        }
236    }
237
238    /// Sliding sync request room subscription (see [`super::Request::room_subscriptions`]).
239    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
240    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
241    pub struct RoomSubscription {
242        /// Required state for each returned room. An array of event type and
243        /// state key tuples.
244        #[serde(default, skip_serializing_if = "Vec::is_empty")]
245        pub required_state: Vec<(StateEventType, String)>,
246
247        /// The maximum number of timeline events to return per room.
248        pub timeline_limit: UInt,
249    }
250
251    /// The conversion is lossy: the `exclude` field of the required state is dropped.
252    impl From<v4::request::RoomSubscription> for RoomSubscription {
253        fn from(value: v4::request::RoomSubscription) -> Self {
254            let v4::request::RoomSubscription { required_state, timeline_limit } = value;
255            Self { required_state: required_state_from_v4(required_state), timeline_limit }
256        }
257    }
258
259    fn required_state_from_v4(
260        required_state: v4::request::RequiredState,
261    ) -> Vec<(StateEventType, String)> {
262        let v4::request::RequiredState { include, exclude: _, lazy_members } = required_state;
263
264        let mut required_state: Vec<_> = include
265            .into_iter()
266            .map(|element| {
267                let v4::request::RequiredStateElement { event_type, state_key } = element;
268                (
269                    event_type.unwrap_or_else(|| "*".into()),
270                    state_key.unwrap_or_else(|| "*".to_owned()),
271                )
272            })
273            .collect();
274
275        if lazy_members {
276            required_state.push((StateEventType::RoomMember, "$LAZY".to_owned()));
277        }
278
279        required_state
280    }
281
282    /// Sliding sync request room details (see [`List::room_details`]).
283    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
284    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
285    pub struct RoomDetails {
286        /// Required state for each returned room. An array of event type and state key tuples.
287        #[serde(default, skip_serializing_if = "Vec::is_empty")]
288        pub required_state: Vec<(StateEventType, String)>,
289
290        /// The maximum number of timeline events to return per room.
291        pub timeline_limit: UInt,
292    }
293
294    /// Sliding sync request extensions (see [`super::Request::extensions`]).
295    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
296    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
297    pub struct Extensions {
298        /// Configure the to-device extension.
299        #[serde(default, skip_serializing_if = "ToDevice::is_disabled")]
300        pub to_device: ToDevice,
301
302        /// Configure the E2EE extension.
303        #[serde(default, skip_serializing_if = "E2EE::is_disabled")]
304        pub e2ee: E2EE,
305
306        /// Configure the account data extension.
307        #[serde(default, skip_serializing_if = "AccountData::is_empty")]
308        pub account_data: AccountData,
309
310        /// Configure the receipts extension.
311        #[serde(default, skip_serializing_if = "Receipts::is_empty")]
312        pub receipts: Receipts,
313
314        /// Configure the typing extension.
315        #[serde(default, skip_serializing_if = "Typing::is_empty")]
316        pub typing: Typing,
317
318        /// Configure the thread subscriptions extension.
319        #[cfg(feature = "unstable-msc4308")]
320        #[serde(
321            default,
322            skip_serializing_if = "ThreadSubscriptions::is_disabled",
323            rename = "io.element.msc4308.thread_subscriptions"
324        )]
325        pub thread_subscriptions: ThreadSubscriptions,
326
327        /// Configure the threads extension.
328        #[cfg(feature = "unstable-msc4360")]
329        #[serde(
330            default,
331            skip_serializing_if = "Threads::is_disabled",
332            rename = "io.element.msc4360.threads"
333        )]
334        pub threads: Threads,
335
336        /// Configure the profiles extension.
337        #[cfg(feature = "unstable-msc4262")]
338        #[serde(
339            default,
340            skip_serializing_if = "Profiles::is_empty",
341            rename = "org.matrix.msc4262.profiles"
342        )]
343        pub profiles: Profiles,
344
345        /// Configure the sticky events extension.
346        #[cfg(feature = "unstable-msc4480")]
347        #[serde(
348            default,
349            skip_serializing_if = "StickyEvents::is_empty",
350            rename = "org.matrix.msc4354.sticky_events"
351        )]
352        pub sticky_events: StickyEvents,
353
354        /// Configure the presence extension.
355        #[cfg(feature = "unstable-msc4559")]
356        #[serde(
357            default,
358            skip_serializing_if = "Presence::is_empty",
359            rename = "org.continuwuity.presence_v2.msc4559.presence"
360        )]
361        pub presence: Presence,
362
363        /// Extensions may add further fields to the list.
364        #[serde(flatten)]
365        other: BTreeMap<String, serde_json::Value>,
366    }
367
368    impl Extensions {
369        /// Whether all fields are empty or `None`.
370        pub fn is_empty(&self) -> bool {
371            let Self {
372                to_device,
373                e2ee,
374                account_data,
375                receipts,
376                typing,
377                #[cfg(feature = "unstable-msc4308")]
378                thread_subscriptions,
379                #[cfg(feature = "unstable-msc4360")]
380                threads,
381                #[cfg(feature = "unstable-msc4262")]
382                profiles,
383                #[cfg(feature = "unstable-msc4480")]
384                sticky_events,
385                #[cfg(feature = "unstable-msc4559")]
386                presence,
387                other,
388            } = self;
389
390            #[allow(unused_mut)]
391            let mut empty = to_device.is_disabled()
392                && e2ee.is_disabled()
393                && account_data.is_empty()
394                && receipts.is_empty()
395                && typing.is_empty()
396                && other.is_empty();
397
398            #[cfg(feature = "unstable-msc4308")]
399            {
400                empty &= thread_subscriptions.is_disabled();
401            }
402
403            #[cfg(feature = "unstable-msc4360")]
404            {
405                empty &= threads.is_disabled();
406            }
407
408            #[cfg(feature = "unstable-msc4262")]
409            {
410                empty &= profiles.is_empty();
411            }
412
413            #[cfg(feature = "unstable-msc4480")]
414            {
415                empty &= sticky_events.is_empty();
416            }
417
418            #[cfg(feature = "unstable-msc4559")]
419            {
420                empty &= presence.is_empty();
421            }
422
423            empty
424        }
425    }
426
427    impl From<v4::request::Extensions> for Extensions {
428        fn from(value: v4::request::Extensions) -> Self {
429            let v4::request::Extensions {
430                to_device,
431                e2ee,
432                account_data,
433                receipts,
434                typing,
435                #[cfg(feature = "unstable-msc4308")]
436                thread_subscriptions,
437                #[cfg(feature = "unstable-msc4360")]
438                threads,
439                #[cfg(feature = "unstable-msc4262")]
440                profiles,
441                #[cfg(feature = "unstable-msc4480")]
442                sticky_events,
443                #[cfg(feature = "unstable-msc4559")]
444                presence,
445                other,
446            } = value;
447
448            Self {
449                to_device,
450                e2ee,
451                account_data: AccountData {
452                    enabled: enabled_from_v4(account_data.enabled),
453                    lists: account_data.lists,
454                    rooms: rooms_from_v4(account_data.rooms),
455                },
456                receipts: Receipts {
457                    enabled: enabled_from_v4(receipts.enabled),
458                    lists: receipts.lists,
459                    rooms: rooms_from_v4(receipts.rooms),
460                },
461                typing: Typing {
462                    enabled: enabled_from_v4(typing.enabled),
463                    lists: typing.lists,
464                    rooms: rooms_from_v4(typing.rooms),
465                },
466                #[cfg(feature = "unstable-msc4308")]
467                thread_subscriptions,
468                #[cfg(feature = "unstable-msc4360")]
469                threads,
470                #[cfg(feature = "unstable-msc4262")]
471                profiles: Profiles {
472                    enabled: enabled_from_v4(profiles.enabled),
473                    lists: profiles.lists,
474                    rooms: rooms_from_v4(profiles.rooms),
475                    fields: profiles.fields,
476                },
477                #[cfg(feature = "unstable-msc4480")]
478                sticky_events: StickyEvents {
479                    enabled: enabled_from_v4(sticky_events.enabled),
480                    limit: sticky_events.limit,
481                    lists: sticky_events.lists,
482                    rooms: rooms_from_v4(sticky_events.rooms),
483                },
484                #[cfg(feature = "unstable-msc4559")]
485                presence: Presence {
486                    enabled: enabled_from_v4(presence.enabled),
487                    lists: presence.lists,
488                    rooms: rooms_from_v4(presence.rooms),
489                },
490                other,
491            }
492        }
493    }
494
495    fn enabled_from_v4(enabled: bool) -> Option<bool> {
496        enabled.then_some(true)
497    }
498
499    fn rooms_from_v4(rooms: Option<Vec<OwnedRoomId>>) -> Option<Vec<ExtensionRoomConfig>> {
500        rooms.map(|rooms| rooms.into_iter().map(ExtensionRoomConfig::Room).collect())
501    }
502
503    /// Single entry for a room subscription configuration in an extension request.
504    #[derive(Clone, Debug, PartialEq)]
505    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
506    pub enum ExtensionRoomConfig {
507        /// Apply extension to all global room subscriptions.
508        AllSubscribed,
509
510        /// Additionally apply extension to this specific room.
511        Room(OwnedRoomId),
512    }
513
514    impl Serialize for ExtensionRoomConfig {
515        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
516        where
517            S: serde::Serializer,
518        {
519            match self {
520                Self::AllSubscribed => serializer.serialize_str("*"),
521                Self::Room(r) => r.serialize(serializer),
522            }
523        }
524    }
525
526    impl<'de> Deserialize<'de> for ExtensionRoomConfig {
527        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
528        where
529            D: serde::de::Deserializer<'de>,
530        {
531            match deserialize_cow_str(deserializer)?.as_ref() {
532                "*" => Ok(Self::AllSubscribed),
533                other => Ok(Self::Room(RoomId::parse(other).map_err(D::Error::custom)?)),
534            }
535        }
536    }
537
538    /// Sticky events extension configuration.
539    ///
540    /// According to [MSC4480](https://github.com/matrix-org/matrix-spec-proposals/pull/4480).
541    #[cfg(feature = "unstable-msc4480")]
542    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
543    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
544    pub struct StickyEvents {
545        /// Activate or deactivate this extension.
546        #[serde(skip_serializing_if = "Option::is_none")]
547        pub enabled: Option<bool>,
548
549        /// Maximum number of sticky events to return per response.
550        ///
551        /// Defaults to 100 (server-side) and the server may override it to a lower value.
552        #[serde(skip_serializing_if = "Option::is_none")]
553        pub limit: Option<UInt>,
554
555        /// List of list names for which sticky events should be enabled.
556        ///
557        /// If not defined, will be enabled for *all* the lists appearing in the
558        /// request. If defined and empty, will be disabled for all the lists.
559        #[serde(skip_serializing_if = "Option::is_none")]
560        pub lists: Option<Vec<String>>,
561
562        /// List of room names for which sticky events should be enabled.
563        ///
564        /// If not defined, will be enabled for *all* the rooms appearing in the
565        /// room subscriptions. If defined and empty, will be disabled for all
566        /// the rooms.
567        #[serde(skip_serializing_if = "Option::is_none")]
568        pub rooms: Option<Vec<ExtensionRoomConfig>>,
569    }
570
571    #[cfg(feature = "unstable-msc4480")]
572    impl StickyEvents {
573        /// Whether all fields are empty or `None`.
574        pub fn is_empty(&self) -> bool {
575            self.enabled.is_none()
576        }
577    }
578
579    /// Account-data extension.
580    ///
581    /// Not yet part of the spec proposal. Taken from the reference implementation
582    /// <https://github.com/matrix-org/sliding-sync/blob/main/sync3/extensions/account_data.go>
583    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
584    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
585    pub struct AccountData {
586        /// Activate or deactivate this extension.
587        #[serde(skip_serializing_if = "Option::is_none")]
588        pub enabled: Option<bool>,
589
590        /// List of list names for which account data should be enabled.
591        ///
592        /// This is specific to room account data (e.g. user-defined room tags).
593        ///
594        /// If not defined, will be enabled for *all* the lists appearing in the
595        /// request. If defined and empty, will be disabled for all the lists.
596        #[serde(skip_serializing_if = "Option::is_none")]
597        pub lists: Option<Vec<String>>,
598
599        /// List of room names for which account data should be enabled.
600        ///
601        /// This is specific to room account data (e.g. user-defined room tags).
602        ///
603        /// If not defined, will be enabled for *all* the rooms appearing in the
604        /// room subscriptions. If defined and empty, will be disabled for all
605        /// the rooms.
606        #[serde(skip_serializing_if = "Option::is_none")]
607        pub rooms: Option<Vec<ExtensionRoomConfig>>,
608    }
609
610    impl AccountData {
611        /// Whether all fields are empty or `None`.
612        pub fn is_empty(&self) -> bool {
613            self.enabled.is_none()
614        }
615    }
616
617    /// Receipt extension.
618    ///
619    /// According to [MSC3960](https://github.com/matrix-org/matrix-spec-proposals/pull/3960)
620    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
621    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
622    pub struct Receipts {
623        /// Activate or deactivate this extension.
624        #[serde(skip_serializing_if = "Option::is_none")]
625        pub enabled: Option<bool>,
626
627        /// List of list names for which receipts should be enabled.
628        ///
629        /// If not defined, will be enabled for *all* the lists appearing in the
630        /// request. If defined and empty, will be disabled for all the lists.
631        #[serde(skip_serializing_if = "Option::is_none")]
632        pub lists: Option<Vec<String>>,
633
634        /// List of room names for which receipts should be enabled.
635        ///
636        /// If not defined, will be enabled for *all* the rooms appearing in the
637        /// room subscriptions. If defined and empty, will be disabled for all
638        /// the rooms.
639        #[serde(skip_serializing_if = "Option::is_none")]
640        pub rooms: Option<Vec<ExtensionRoomConfig>>,
641    }
642
643    impl Receipts {
644        /// Whether all fields are empty or `None`.
645        pub fn is_empty(&self) -> bool {
646            self.enabled.is_none()
647        }
648    }
649
650    /// Typing extension configuration.
651    ///
652    /// Not yet part of the spec proposal. Taken from the reference implementation
653    /// <https://github.com/matrix-org/sliding-sync/blob/main/sync3/extensions/typing.go>
654    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
655    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
656    pub struct Typing {
657        /// Activate or deactivate this extension.
658        #[serde(skip_serializing_if = "Option::is_none")]
659        pub enabled: Option<bool>,
660
661        /// List of list names for which typing notifications should be enabled.
662        ///
663        /// If not defined, will be enabled for *all* the lists appearing in the
664        /// request. If defined and empty, will be disabled for all the lists.
665        #[serde(skip_serializing_if = "Option::is_none")]
666        pub lists: Option<Vec<String>>,
667
668        /// List of room names for which typing notifications should be enabled.
669        ///
670        /// If not defined, will be enabled for *all* the rooms appearing in the
671        /// room subscriptions. If defined and empty, will be disabled for all
672        /// the rooms.
673        #[serde(skip_serializing_if = "Option::is_none")]
674        pub rooms: Option<Vec<ExtensionRoomConfig>>,
675    }
676
677    impl Typing {
678        /// Whether all fields are empty or `None`.
679        pub fn is_empty(&self) -> bool {
680            self.enabled.is_none()
681        }
682    }
683
684    /// User profiles extension.
685    ///
686    /// Specified as part of [MSC4262](https://github.com/matrix-org/matrix-spec-proposals/pull/4262).
687    #[cfg(feature = "unstable-msc4262")]
688    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
689    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
690    pub struct Profiles {
691        /// Activate or deactivate this extension.
692        #[serde(skip_serializing_if = "Option::is_none")]
693        pub enabled: Option<bool>,
694
695        /// List of list names for which user profiles should be enabled.
696        ///
697        /// If not defined, will be enabled for *all* the lists appearing in the
698        /// request. If defined and empty, will be disabled for all the lists.
699        #[serde(skip_serializing_if = "Option::is_none")]
700        pub lists: Option<Vec<String>>,
701
702        /// List of room names for which user profiles should be enabled.
703        ///
704        /// If not defined, will be enabled for *all* the rooms appearing in the
705        /// room subscriptions. If defined and empty, will be disabled for all
706        /// the rooms.
707        #[serde(skip_serializing_if = "Option::is_none")]
708        pub rooms: Option<Vec<ExtensionRoomConfig>>,
709
710        /// Optional filter to control which profile fields to receive updates for. If omitted, all
711        /// profile field updates are included.
712        #[serde(skip_serializing_if = "Option::is_none")]
713        pub fields: Option<Vec<ruma_common::profile::ProfileFieldName>>,
714    }
715
716    #[cfg(feature = "unstable-msc4262")]
717    impl Profiles {
718        /// Whether all fields are empty or `None`.
719        pub fn is_empty(&self) -> bool {
720            self.enabled.is_none()
721        }
722    }
723
724    /// Presence extension.
725    ///
726    /// Specified as part of [MSC4559](https://github.com/matrix-org/matrix-spec-proposals/pull/4559).
727    #[cfg(feature = "unstable-msc4559")]
728    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
729    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
730    pub struct Presence {
731        /// Activate or deactivate this extension.
732        #[serde(skip_serializing_if = "Option::is_none")]
733        pub enabled: Option<bool>,
734
735        /// List of list names for which user presence should be enabled.
736        ///
737        /// If not defined, will be enabled for *all* the lists appearing in the
738        /// request. If defined and empty, will be disabled for all the lists.
739        #[serde(skip_serializing_if = "Option::is_none")]
740        pub lists: Option<Vec<String>>,
741
742        /// List of room names for which user presence should be enabled.
743        ///
744        /// If not defined, will be enabled for *all* the rooms appearing in the
745        /// room subscriptions. If defined and empty, will be disabled for all
746        /// the rooms.
747        #[serde(skip_serializing_if = "Option::is_none")]
748        pub rooms: Option<Vec<ExtensionRoomConfig>>,
749    }
750
751    #[cfg(feature = "unstable-msc4559")]
752    impl Presence {
753        /// Whether all fields are empty or `None`.
754        pub fn is_empty(&self) -> bool {
755            self.enabled.is_none()
756        }
757    }
758}
759
760/// Response type for the `/sync` endpoint.
761#[response]
762pub struct Response {
763    /// Matches the `txn_id` sent by the request (see [`Request::txn_id`]).
764    #[serde(skip_serializing_if = "Option::is_none")]
765    pub txn_id: Option<String>,
766
767    /// The token to supply in the `pos` parameter of the next `/sync` request
768    /// (see [`Request::pos`]).
769    pub pos: String,
770
771    /// Resulting details of the lists.
772    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
773    pub lists: BTreeMap<String, response::List>,
774
775    /// The updated rooms.
776    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
777    pub rooms: BTreeMap<OwnedRoomId, response::Room>,
778
779    /// Extensions.
780    #[serde(default, skip_serializing_if = "response::Extensions::is_empty")]
781    pub extensions: response::Extensions,
782}
783
784impl Response {
785    /// Creates a new `Response` with the given `pos`.
786    pub fn new(pos: String) -> Self {
787        Self {
788            txn_id: None,
789            pos,
790            lists: Default::default(),
791            rooms: Default::default(),
792            extensions: Default::default(),
793        }
794    }
795}
796
797impl From<v4::Response> for Response {
798    fn from(value: v4::Response) -> Self {
799        let v4::Response { pos, lists, rooms, extensions } = value;
800
801        Self {
802            txn_id: None,
803            pos,
804            lists: lists
805                .into_iter()
806                .map(|(key, list)| (key, response::List { count: list.count }))
807                .collect(),
808            rooms: rooms.into_iter().map(|(room_id, room)| (room_id, room.into())).collect(),
809            extensions: extensions.into(),
810        }
811    }
812}
813
814/// HTTP types related to a [`Response`].
815pub mod response {
816    use as_variant::as_variant;
817    use ruma_common::OneTimeKeyAlgorithm;
818    use ruma_events::{
819        AnyStrippedStateEvent, AnyToDeviceEvent, receipt::SyncReceiptEvent, typing::SyncTypingEvent,
820    };
821    use serde_json::{json, value::to_raw_value as to_raw_json_value};
822
823    pub use super::v4::response::AccountData;
824    #[cfg(feature = "unstable-msc4262")]
825    pub use super::v4::response::Profiles;
826    #[cfg(feature = "unstable-msc4308")]
827    pub use super::v4::response::ThreadSubscriptions;
828    #[cfg(feature = "unstable-msc4559")]
829    pub use super::v4::response::{Presence, PresenceUpdate};
830    #[cfg(feature = "unstable-msc4480")]
831    pub use super::v4::response::{StickyEvents, StickyEventsRoom};
832    #[cfg(feature = "unstable-msc4360")]
833    pub use super::v4::response::{ThreadUpdate, Threads};
834    use super::{
835        super::DeviceLists, AnySyncStateEvent, AnySyncTimelineEvent, BTreeMap, Deserialize,
836        JsOption, OwnedMxcUri, OwnedRoomId, OwnedUserId, Raw, Serialize, UInt,
837        UnreadNotificationsCount, v4,
838    };
839
840    /// A sliding sync response updates to joiend rooms (see
841    /// [`super::Response::lists`]).
842    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
843    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
844    pub struct List {
845        /// The total number of rooms found for this list.
846        pub count: UInt,
847    }
848
849    /// A sliding sync response updated room (see [`super::Response::rooms`]).
850    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
851    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
852    pub struct Room {
853        /// The name as calculated by the server.
854        ///
855        /// If the `unstable-compat-lax-syncv5-deser` feature is enabled,
856        /// this field is ignored if its deserialization fails.
857        #[serde(skip_serializing_if = "Option::is_none")]
858        #[cfg_attr(
859            feature = "unstable-compat-lax-syncv5-deser",
860            serde(default, deserialize_with = "ruma_common::serde::default_on_error")
861        )]
862        pub name: Option<String>,
863
864        /// The avatar.
865        ///
866        /// If the `unstable-compat-lax-syncv5-deser` feature is enabled,
867        /// this field is ignored if its deserialization fails.
868        #[serde(default, skip_serializing_if = "JsOption::is_undefined")]
869        #[cfg_attr(
870            feature = "unstable-compat-lax-syncv5-deser",
871            serde(deserialize_with = "ruma_common::serde::default_on_error")
872        )]
873        pub avatar: JsOption<OwnedMxcUri>,
874
875        /// Whether it is an initial response.
876        #[serde(skip_serializing_if = "Option::is_none")]
877        pub initial: Option<bool>,
878
879        /// Whether it is a direct room.
880        #[serde(skip_serializing_if = "Option::is_none")]
881        pub is_dm: Option<bool>,
882
883        /// If this is `Some(_)`, this is a not-yet-accepted invite containing
884        /// the given stripped state events.
885        #[serde(skip_serializing_if = "Option::is_none")]
886        pub invite_state: Option<Vec<Raw<AnyStrippedStateEvent>>>,
887
888        /// Number of unread notifications.
889        #[serde(flatten, default, skip_serializing_if = "UnreadNotificationsCount::is_empty")]
890        pub unread_notifications: UnreadNotificationsCount,
891
892        /// Message-like events and live state events.
893        #[serde(default, skip_serializing_if = "Vec::is_empty")]
894        pub timeline: Vec<Raw<AnySyncTimelineEvent>>,
895
896        /// State events as configured by the request.
897        #[serde(default, skip_serializing_if = "Vec::is_empty")]
898        pub required_state: Vec<Raw<AnySyncStateEvent>>,
899
900        /// The `prev_batch` allowing you to paginate through the messages
901        /// before the given ones.
902        #[serde(skip_serializing_if = "Option::is_none")]
903        pub prev_batch: Option<String>,
904
905        /// True if the number of events returned was limited by the limit on
906        /// the filter.
907        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
908        pub limited: bool,
909
910        /// The number of users with membership of `join`, including the
911        /// client’s own user ID.
912        #[serde(skip_serializing_if = "Option::is_none")]
913        pub joined_count: Option<UInt>,
914
915        /// The number of users with membership of `invite`.
916        #[serde(skip_serializing_if = "Option::is_none")]
917        pub invited_count: Option<UInt>,
918
919        /// The number of timeline events which have just occurred and are not
920        /// historical.
921        #[serde(skip_serializing_if = "Option::is_none")]
922        pub num_live: Option<UInt>,
923
924        /// The bump stamp of the room.
925        ///
926        /// It can be interpreted as a “recency stamp” or “streaming order
927        /// index”. For example, consider `roomA` with `bump_stamp = 2`, `roomB`
928        /// with `bump_stamp = 1` and `roomC` with `bump_stamp = 0`. If `roomC`
929        /// receives an update, its `bump_stamp` will be 3.
930        #[serde(skip_serializing_if = "Option::is_none")]
931        pub bump_stamp: Option<UInt>,
932
933        /// Heroes of the room.
934        #[serde(skip_serializing_if = "Option::is_none")]
935        pub heroes: Option<Vec<Hero>>,
936    }
937
938    impl Room {
939        /// Creates an empty `Room`.
940        pub fn new() -> Self {
941            Default::default()
942        }
943    }
944
945    /// The conversion is lossy: `membership`, `lists`, `expanded_timeline`, deleted state
946    /// entries and the removal of the room name are dropped.
947    impl From<v4::response::Room> for Room {
948        fn from(value: v4::response::Room) -> Self {
949            let v4::response::Room { bump_stamp, membership: _, lists: _, data } = value;
950
951            match data {
952                v4::response::RoomData::Full(data) => {
953                    let v4::response::FullRoomData {
954                        name,
955                        avatar,
956                        heroes,
957                        is_dm,
958                        initial,
959                        expanded_timeline: _,
960                        required_state,
961                        timeline,
962                        prev_batch,
963                        limited,
964                        num_live,
965                        joined_count,
966                        invited_count,
967                    } = data;
968
969                    Self {
970                        name: name.into_option(),
971                        avatar,
972                        initial: initial.then_some(true),
973                        is_dm,
974                        invite_state: None,
975                        unread_notifications: UnreadNotificationsCount::new(),
976                        timeline,
977                        required_state: required_state
978                            .into_iter()
979                            .filter_map(|entry| {
980                                as_variant!(entry, v4::response::RequiredStateEntry::Event)
981                            })
982                            .collect(),
983                        prev_batch,
984                        limited,
985                        joined_count,
986                        invited_count,
987                        num_live,
988                        bump_stamp,
989                        heroes: heroes.map(|heroes| heroes.into_iter().map(Into::into).collect()),
990                    }
991                }
992                v4::response::RoomData::Stripped(data) => {
993                    let v4::response::StrippedRoomData { stripped_state } = data;
994
995                    Self { invite_state: Some(stripped_state), bump_stamp, ..Default::default() }
996                }
997            }
998        }
999    }
1000
1001    /// A sliding sync response room hero (see [`Room::heroes`]).
1002    #[derive(Clone, Debug, Deserialize, Serialize)]
1003    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1004    pub struct Hero {
1005        /// The user ID.
1006        pub user_id: OwnedUserId,
1007
1008        /// The name.
1009        ///
1010        /// If the `unstable-compat-lax-syncv5-deser` feature is enabled,
1011        /// this field is ignored if its deserialization fails.
1012        #[serde(rename = "displayname", skip_serializing_if = "Option::is_none")]
1013        #[cfg_attr(
1014            feature = "unstable-compat-lax-syncv5-deser",
1015            serde(default, deserialize_with = "ruma_common::serde::default_on_error")
1016        )]
1017        pub name: Option<String>,
1018
1019        /// The avatar.
1020        ///
1021        /// If the `unstable-compat-lax-syncv5-deser` feature is enabled,
1022        /// this field is ignored if its deserialization fails.
1023        #[serde(rename = "avatar_url", skip_serializing_if = "Option::is_none")]
1024        #[cfg_attr(
1025            feature = "unstable-compat-lax-syncv5-deser",
1026            serde(default, deserialize_with = "ruma_common::serde::default_on_error")
1027        )]
1028        pub avatar: Option<OwnedMxcUri>,
1029    }
1030
1031    impl Hero {
1032        /// Creates a new `Hero` with the given user ID.
1033        pub fn new(user_id: OwnedUserId) -> Self {
1034            Self { user_id, name: None, avatar: None }
1035        }
1036    }
1037
1038    impl From<v4::response::Hero> for Hero {
1039        fn from(value: v4::response::Hero) -> Self {
1040            let v4::response::Hero { user_id, displayname, avatar_url } = value;
1041            Self { user_id, name: displayname, avatar: avatar_url }
1042        }
1043    }
1044
1045    /// Extensions responses.
1046    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1047    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1048    pub struct Extensions {
1049        /// To-device extension response.
1050        #[serde(skip_serializing_if = "Option::is_none")]
1051        pub to_device: Option<ToDevice>,
1052
1053        /// E2EE extension response.
1054        #[serde(default, skip_serializing_if = "E2EE::is_empty")]
1055        pub e2ee: E2EE,
1056
1057        /// Account data extension response.
1058        #[serde(default, skip_serializing_if = "AccountData::is_empty")]
1059        pub account_data: AccountData,
1060
1061        /// Receipts extension response.
1062        #[serde(default, skip_serializing_if = "Receipts::is_empty")]
1063        pub receipts: Receipts,
1064
1065        /// Typing extension response.
1066        #[serde(default, skip_serializing_if = "Typing::is_empty")]
1067        pub typing: Typing,
1068
1069        /// Thread subscriptions extension response.
1070        #[cfg(feature = "unstable-msc4308")]
1071        #[serde(
1072            default,
1073            skip_serializing_if = "ThreadSubscriptions::is_empty",
1074            rename = "io.element.msc4308.thread_subscriptions"
1075        )]
1076        pub thread_subscriptions: ThreadSubscriptions,
1077
1078        /// Threads extension response.
1079        #[cfg(feature = "unstable-msc4360")]
1080        #[serde(
1081            default,
1082            skip_serializing_if = "Threads::is_empty",
1083            rename = "io.element.msc4360.threads"
1084        )]
1085        pub threads: Threads,
1086
1087        /// Profiles extension response.
1088        #[cfg(feature = "unstable-msc4262")]
1089        #[serde(
1090            default,
1091            skip_serializing_if = "Profiles::is_empty",
1092            rename = "org.matrix.msc4262.profiles"
1093        )]
1094        pub profiles: Profiles,
1095
1096        /// Sticky events extension response.
1097        #[cfg(feature = "unstable-msc4480")]
1098        #[serde(
1099            default,
1100            skip_serializing_if = "StickyEvents::is_empty",
1101            rename = "org.matrix.msc4354.sticky_events"
1102        )]
1103        pub sticky_events: StickyEvents,
1104
1105        /// Presence extension response.
1106        #[cfg(feature = "unstable-msc4559")]
1107        #[serde(
1108            default,
1109            skip_serializing_if = "Presence::is_empty",
1110            rename = "org.continuwuity.presence_v2.msc4559.presence"
1111        )]
1112        pub presence: Presence,
1113    }
1114
1115    impl Extensions {
1116        /// Whether the extension data is empty.
1117        ///
1118        /// True if neither to-device, e2ee nor account data are to be found.
1119        pub fn is_empty(&self) -> bool {
1120            let Self {
1121                to_device,
1122                e2ee,
1123                account_data,
1124                receipts,
1125                typing,
1126                #[cfg(feature = "unstable-msc4308")]
1127                thread_subscriptions,
1128                #[cfg(feature = "unstable-msc4360")]
1129                threads,
1130                #[cfg(feature = "unstable-msc4262")]
1131                profiles,
1132                #[cfg(feature = "unstable-msc4480")]
1133                sticky_events,
1134                #[cfg(feature = "unstable-msc4559")]
1135                presence,
1136            } = self;
1137
1138            #[allow(unused_mut)]
1139            let mut empty = to_device.is_none()
1140                && e2ee.is_empty()
1141                && account_data.is_empty()
1142                && receipts.is_empty()
1143                && typing.is_empty();
1144
1145            #[cfg(feature = "unstable-msc4308")]
1146            {
1147                empty &= thread_subscriptions.is_empty();
1148            }
1149
1150            #[cfg(feature = "unstable-msc4360")]
1151            {
1152                empty &= threads.is_empty();
1153            }
1154
1155            #[cfg(feature = "unstable-msc4262")]
1156            {
1157                empty &= profiles.is_empty();
1158            }
1159
1160            #[cfg(feature = "unstable-msc4480")]
1161            {
1162                empty &= sticky_events.is_empty();
1163            }
1164
1165            #[cfg(feature = "unstable-msc4559")]
1166            {
1167                empty &= presence.is_empty();
1168            }
1169
1170            empty
1171        }
1172    }
1173
1174    impl From<v4::response::Extensions> for Extensions {
1175        fn from(value: v4::response::Extensions) -> Self {
1176            let v4::response::Extensions {
1177                to_device,
1178                e2ee,
1179                account_data,
1180                receipts,
1181                typing,
1182                #[cfg(feature = "unstable-msc4308")]
1183                thread_subscriptions,
1184                #[cfg(feature = "unstable-msc4360")]
1185                threads,
1186                #[cfg(feature = "unstable-msc4262")]
1187                profiles,
1188                #[cfg(feature = "unstable-msc4480")]
1189                sticky_events,
1190                #[cfg(feature = "unstable-msc4559")]
1191                presence,
1192            } = value;
1193
1194            Self {
1195                to_device: to_device.map(|to_device| {
1196                    let v4::response::ToDevice { next_batch, messages } = to_device;
1197                    ToDevice { next_batch, events: messages }
1198                }),
1199                e2ee: e2ee
1200                    .map(|e2ee| {
1201                        let v4::response::E2EE {
1202                            device_lists,
1203                            device_one_time_keys_count,
1204                            device_unused_fallback_key_types,
1205                        } = e2ee;
1206
1207                        E2EE {
1208                            device_lists,
1209                            device_one_time_keys_count,
1210                            device_unused_fallback_key_types: Some(
1211                                device_unused_fallback_key_types,
1212                            ),
1213                        }
1214                    })
1215                    .unwrap_or_default(),
1216                account_data,
1217                receipts: Receipts {
1218                    rooms: receipts
1219                        .rooms
1220                        .into_iter()
1221                        .map(|(room_id, content)| {
1222                            let event = to_raw_json_value(&json!({
1223                                "type": "m.receipt",
1224                                "content": content,
1225                            }))
1226                            .expect("serialized receipt event should be valid JSON");
1227                            (room_id, Raw::from_json(event))
1228                        })
1229                        .collect(),
1230                },
1231                typing: Typing {
1232                    rooms: typing
1233                        .rooms
1234                        .into_iter()
1235                        .map(|(room_id, content)| {
1236                            let event = Raw::new(&SyncTypingEvent::new(content))
1237                                .expect("serialized typing event should be valid JSON");
1238                            (room_id, event)
1239                        })
1240                        .collect(),
1241                },
1242                #[cfg(feature = "unstable-msc4308")]
1243                thread_subscriptions,
1244                #[cfg(feature = "unstable-msc4360")]
1245                threads,
1246                #[cfg(feature = "unstable-msc4262")]
1247                profiles,
1248                #[cfg(feature = "unstable-msc4480")]
1249                sticky_events,
1250                #[cfg(feature = "unstable-msc4559")]
1251                presence,
1252            }
1253        }
1254    }
1255
1256    /// To-device extension response.
1257    ///
1258    /// According to [MSC3885](https://github.com/matrix-org/matrix-spec-proposals/pull/3885).
1259    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1260    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1261    pub struct ToDevice {
1262        /// Fetch the next batch from this entry.
1263        pub next_batch: String,
1264
1265        /// The to-device events.
1266        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1267        pub events: Vec<Raw<AnyToDeviceEvent>>,
1268    }
1269
1270    /// E2EE extension response.
1271    ///
1272    /// According to [MSC3884](https://github.com/matrix-org/matrix-spec-proposals/pull/3884).
1273    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1274    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1275    pub struct E2EE {
1276        /// Information on E2EE device updates.
1277        #[serde(default, skip_serializing_if = "DeviceLists::is_empty")]
1278        pub device_lists: DeviceLists,
1279
1280        /// For each key algorithm, the number of unclaimed one-time keys
1281        /// currently held on the server for a device.
1282        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1283        pub device_one_time_keys_count: BTreeMap<OneTimeKeyAlgorithm, UInt>,
1284
1285        /// The unused fallback key algorithms.
1286        ///
1287        /// The presence of this field indicates that the server supports
1288        /// fallback keys.
1289        #[serde(skip_serializing_if = "Option::is_none")]
1290        pub device_unused_fallback_key_types: Option<Vec<OneTimeKeyAlgorithm>>,
1291    }
1292
1293    impl E2EE {
1294        /// Whether all fields are empty or `None`.
1295        pub fn is_empty(&self) -> bool {
1296            self.device_lists.is_empty()
1297                && self.device_one_time_keys_count.is_empty()
1298                && self.device_unused_fallback_key_types.is_none()
1299        }
1300    }
1301
1302    /// Receipt extension response.
1303    ///
1304    /// According to [MSC3960](https://github.com/matrix-org/matrix-spec-proposals/pull/3960)
1305    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1306    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1307    pub struct Receipts {
1308        /// The ephemeral receipt room event for each room.
1309        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1310        pub rooms: BTreeMap<OwnedRoomId, Raw<SyncReceiptEvent>>,
1311    }
1312
1313    impl Receipts {
1314        /// Whether all fields are empty or `None`.
1315        pub fn is_empty(&self) -> bool {
1316            self.rooms.is_empty()
1317        }
1318    }
1319
1320    /// Typing extension response.
1321    ///
1322    /// Not yet part of the spec proposal. Taken from the reference implementation
1323    /// <https://github.com/matrix-org/sliding-sync/blob/main/sync3/extensions/typing.go>
1324    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1325    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1326    pub struct Typing {
1327        /// The ephemeral typing event for each room.
1328        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1329        pub rooms: BTreeMap<OwnedRoomId, Raw<SyncTypingEvent>>,
1330    }
1331
1332    impl Typing {
1333        /// Whether all fields are empty or `None`.
1334        pub fn is_empty(&self) -> bool {
1335            self.rooms.is_empty()
1336        }
1337    }
1338}
1339
1340#[cfg(test)]
1341mod tests {
1342    use js_int::uint;
1343    use ruma_common::{assert_to_canonical_json_eq, owned_room_id};
1344    use ruma_events::StateEventType;
1345    use serde_json::{from_value as from_json_value, json};
1346
1347    use super::{Request, request, request::ExtensionRoomConfig, response, v4};
1348
1349    #[test]
1350    fn serialize_request_extension_room_config() {
1351        let entry = ExtensionRoomConfig::AllSubscribed;
1352        assert_eq!(serde_json::to_string(&entry).unwrap().as_str(), r#""*""#);
1353
1354        let entry = ExtensionRoomConfig::Room(owned_room_id!("!foo:bar.baz"));
1355        assert_eq!(serde_json::to_string(&entry).unwrap().as_str(), r#""!foo:bar.baz""#);
1356    }
1357
1358    #[test]
1359    fn deserialize_request_extension_room_config() {
1360        assert_eq!(
1361            serde_json::from_str::<ExtensionRoomConfig>(r#""*""#).unwrap(),
1362            ExtensionRoomConfig::AllSubscribed
1363        );
1364
1365        assert_eq!(
1366            serde_json::from_str::<ExtensionRoomConfig>(r#""!foo:bar.baz""#).unwrap(),
1367            ExtensionRoomConfig::Room(owned_room_id!("!foo:bar.baz"))
1368        );
1369    }
1370
1371    #[test]
1372    fn request_from_v4() {
1373        let mut required_state = v4::request::RequiredState::new();
1374        required_state.include = vec![
1375            v4::request::RequiredStateElement::new(),
1376            v4::request::RequiredStateElement::new()
1377                .with_event_type(StateEventType::RoomTopic)
1378                .with_state_key(String::new()),
1379        ];
1380        required_state.lazy_members = true;
1381
1382        let mut list = v4::request::List::new(required_state, uint!(10));
1383        list.filters.is_invited = v4::request::FilterMode::Exclude;
1384
1385        let mut v4_request = v4::Request::new();
1386        v4_request.lists.insert("all".to_owned(), list);
1387
1388        let mut request = Request::from(v4_request);
1389
1390        assert_to_canonical_json_eq!(
1391            request.lists.remove("all").unwrap(),
1392            json!({
1393                "ranges": [[0, 9_007_199_254_740_991_u64]],
1394                "required_state": [["*", "*"], ["m.room.topic", ""], ["m.room.member", "$LAZY"]],
1395                "timeline_limit": 10,
1396                "filters": { "is_invite": false },
1397            })
1398        );
1399    }
1400
1401    #[test]
1402    fn request_extensions_from_v4() {
1403        let mut extensions = v4::request::Extensions::new();
1404        extensions.typing.enabled = true;
1405        extensions.receipts.enabled = true;
1406        extensions.receipts.rooms = Some(vec![owned_room_id!("!a:example.com")]);
1407        extensions.account_data.lists = Some(vec![]);
1408
1409        assert_to_canonical_json_eq!(
1410            request::Extensions::from(extensions),
1411            json!({
1412                "typing": { "enabled": true },
1413                "receipts": { "enabled": true, "rooms": ["!a:example.com"] },
1414            })
1415        );
1416    }
1417
1418    #[test]
1419    fn response_extensions_from_v4() {
1420        let extensions: v4::response::Extensions = from_json_value(json!({
1421            "to_device": { "next_batch": "1", "messages": [] },
1422            "e2ee": { "device_one_time_keys_count": {}, "device_unused_fallback_key_types": [] },
1423            "receipts": {
1424                "rooms": {
1425                    "!a:example.com": {
1426                        "$e:example.com": { "m.read": { "@b:example.com": { "ts": 1 } } },
1427                    },
1428                },
1429            },
1430            "typing": { "rooms": { "!a:example.com": { "user_ids": ["@b:example.com"] } } },
1431        }))
1432        .unwrap();
1433
1434        assert_to_canonical_json_eq!(
1435            response::Extensions::from(extensions),
1436            json!({
1437                "to_device": { "next_batch": "1" },
1438                "e2ee": { "device_unused_fallback_key_types": [] },
1439                "receipts": {
1440                    "rooms": {
1441                        "!a:example.com": {
1442                            "type": "m.receipt",
1443                            "content": {
1444                                "$e:example.com": { "m.read": { "@b:example.com": { "ts": 1 } } },
1445                            },
1446                        },
1447                    },
1448                },
1449                "typing": {
1450                    "rooms": {
1451                        "!a:example.com": {
1452                            "type": "m.typing",
1453                            "content": { "user_ids": ["@b:example.com"] },
1454                        },
1455                    },
1456                },
1457            })
1458        );
1459    }
1460
1461    #[cfg(feature = "unstable-msc4480")]
1462    #[test]
1463    fn serialize_sticky_events_request() {
1464        let mut extensions = request::Extensions::default();
1465        extensions.sticky_events = request::StickyEvents {
1466            enabled: Some(true),
1467            rooms: Some(vec![ExtensionRoomConfig::AllSubscribed]),
1468            ..Default::default()
1469        };
1470
1471        assert_to_canonical_json_eq!(
1472            extensions,
1473            json!({ "org.matrix.msc4354.sticky_events": { "enabled": true, "rooms": ["*"] } })
1474        );
1475    }
1476
1477    #[test]
1478    fn full_room_from_v4() {
1479        let room: v4::response::Room = from_json_value(json!({
1480            "name": null,
1481            "initial": true,
1482            "membership": "join",
1483            "required_state": [
1484                {
1485                    "content": {},
1486                    "event_id": "$create:example.com",
1487                    "origin_server_ts": 1,
1488                    "sender": "@alice:example.com",
1489                    "state_key": "",
1490                    "type": "m.room.create",
1491                },
1492                { "type": "m.room.topic", "state_key": "" },
1493            ],
1494            "heroes": [{ "user_id": "@bob:example.com", "displayname": "Bob" }],
1495        }))
1496        .unwrap();
1497
1498        let room = response::Room::from(room);
1499
1500        assert_eq!(room.name, None);
1501        assert_eq!(room.initial, Some(true));
1502        assert_eq!(room.required_state.len(), 1);
1503        assert_eq!(room.heroes.unwrap()[0].name.as_deref(), Some("Bob"));
1504        assert!(room.invite_state.is_none());
1505    }
1506
1507    #[test]
1508    fn stripped_room_from_v4() {
1509        let room: v4::response::Room =
1510            from_json_value(json!({ "bump_stamp": 2, "stripped_state": [] })).unwrap();
1511
1512        let room = response::Room::from(room);
1513
1514        assert_eq!(room.bump_stamp, Some(uint!(2)));
1515        assert_eq!(room.invite_state.unwrap().len(), 0);
1516    }
1517
1518    #[test]
1519    #[cfg(feature = "unstable-compat-lax-syncv5-deser")]
1520    fn deserialize_room_ignores_invalid_string_fields() {
1521        use super::response::Room;
1522
1523        let room: Room = serde_json::from_str(
1524            r#"{
1525                "name": {},
1526                "avatar": {},
1527                "heroes": [{ "user_id": "@alice:localhost", "displayname": {}, "avatar_url": {} }]
1528            }"#,
1529        )
1530        .unwrap();
1531
1532        assert_eq!(room.name, None);
1533        assert!(room.avatar.is_undefined());
1534        let hero = &room.heroes.unwrap()[0];
1535        assert_eq!(hero.name, None);
1536        assert_eq!(hero.avatar, None);
1537
1538        // Valid values are still kept.
1539        let room: Room = serde_json::from_str(
1540            r#"{ "name": "Room", "avatar": "mxc://localhost/a", "heroes": [{ "user_id": "@alice:localhost", "displayname": "Alice", "avatar_url": "mxc://localhost/b" }] }"#,
1541        )
1542        .unwrap();
1543
1544        assert_eq!(room.name.as_deref(), Some("Room"));
1545        assert_eq!(room.avatar.into_option().unwrap().as_str(), "mxc://localhost/a");
1546        let hero = &room.heroes.unwrap()[0];
1547        assert_eq!(hero.name.as_deref(), Some("Alice"));
1548        assert_eq!(hero.avatar.as_ref().unwrap().as_str(), "mxc://localhost/b");
1549    }
1550}