Skip to main content

ruma_client_api/sync/sync_events/
v4.rs

1//! `POST /_matrix/client/v4/sync` ([MSC])
2//!
3//! Get all new events in a sliding window of rooms since the last sync or a given point in time.
4//!
5//! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186
6
7use std::{collections::BTreeMap, time::Duration};
8
9use js_int::UInt;
10use js_option::JsOption;
11use ruma_common::{
12    OwnedMxcUri, OwnedRoomId, OwnedUserId,
13    api::{auth_scheme::AccessToken, request, response},
14    metadata,
15    presence::PresenceState,
16    serde::{Raw, duration::opt_ms},
17};
18use ruma_events::{AnyStrippedStateEvent, AnySyncStateEvent, AnySyncTimelineEvent, StateEventType};
19use serde::{Deserialize, Serialize};
20
21metadata! {
22    method: POST,
23    rate_limited: false,
24    authentication: AccessToken,
25    history: {
26        stable("org.matrix.simplified_msc3575.stable") => "/_matrix/client/v4/sync",
27    }
28}
29
30/// Request type for the `/sync` endpoint.
31#[request]
32#[derive(Default)]
33pub struct Request {
34    /// A unique string identifier for this connection to the server.
35    ///
36    /// Only one connection is allowed per given `conn_id`, empty or not.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub conn_id: Option<String>,
39
40    /// A point in time to continue a sync from.
41    ///
42    /// This is the `pos` from the previous response. `None` starts a new connection.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub pos: Option<String>,
45
46    /// The maximum time to poll before responding to this request.
47    ///
48    /// `None` or zero means the server responds immediately. Ignored when [`Self::pos`] is
49    /// `None`.
50    #[serde(with = "opt_ms", default, skip_serializing_if = "Option::is_none")]
51    pub timeout: Option<Duration>,
52
53    /// Controls whether the client is automatically marked as online by polling this API.
54    ///
55    /// Defaults to `PresenceState::Online`.
56    #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
57    pub set_presence: PresenceState,
58
59    /// Lists of rooms we are interested in, keyed by an opaque identifier.
60    ///
61    /// The server rejects requests with more than 100 lists.
62    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
63    pub lists: BTreeMap<String, request::List>,
64
65    /// Specific rooms we are interested in.
66    ///
67    /// It is useful to receive updates from rooms that are possibly out of range of all the
68    /// lists (see [`Self::lists`]).
69    ///
70    /// The server rejects requests with more than 100 room subscriptions.
71    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
72    pub room_subscriptions: BTreeMap<OwnedRoomId, request::RoomSubscription>,
73
74    /// Extensions configuration.
75    #[serde(default, skip_serializing_if = "request::Extensions::is_empty")]
76    pub extensions: request::Extensions,
77}
78
79impl Request {
80    /// Creates an empty `Request`.
81    pub fn new() -> Self {
82        Default::default()
83    }
84}
85
86/// HTTP types related to a [`Request`].
87pub mod request {
88    use ruma_common::{OwnedRoomId, directory::RoomTypeFilter};
89    use ruma_events::tag::TagName;
90
91    use super::{BTreeMap, Deserialize, Serialize, StateEventType, UInt};
92
93    /// A list of rooms (see [`super::Request::lists`]).
94    #[derive(Clone, Debug, Serialize, Deserialize)]
95    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
96    pub struct List {
97        /// The range of rooms we're interested in, inclusive and 0-indexed.
98        ///
99        /// `None` means all the rooms that match the filters.
100        #[serde(skip_serializing_if = "Option::is_none")]
101        pub range: Option<(UInt, UInt)>,
102
103        /// Required state for each returned room.
104        pub required_state: RequiredState,
105
106        /// The maximum number of timeline events to return per room.
107        pub timeline_limit: UInt,
108
109        /// Filters to apply to the list.
110        #[serde(default, skip_serializing_if = "ListFilters::is_empty")]
111        pub filters: ListFilters,
112    }
113
114    impl List {
115        /// Creates a new `List` with the given required state and timeline limit.
116        pub fn new(required_state: RequiredState, timeline_limit: UInt) -> Self {
117            Self { range: None, required_state, timeline_limit, filters: ListFilters::new() }
118        }
119    }
120
121    /// The filters of a list (see [`List::filters`]).
122    ///
123    /// All fields are applied with _AND_ operators. The absence of fields
124    /// implies no filter on that criteria: it does NOT imply `false`.
125    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
126    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
127    pub struct ListFilters {
128        /// Whether to return DM rooms (as determined by the `m.direct` account data event).
129        ///
130        /// Defaults to [`FilterMode::Both`].
131        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
132        pub is_dm: FilterMode,
133
134        /// Only list rooms that are direct children of any of these spaces, according to their
135        /// `m.space.child` state events.
136        #[serde(default, skip_serializing_if = "Vec::is_empty")]
137        pub spaces: Vec<OwnedRoomId>,
138
139        /// Whether to return encrypted rooms (as determined by the existence of an
140        /// `m.room.encryption` state event).
141        ///
142        /// Defaults to [`FilterMode::Both`].
143        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
144        pub is_encrypted: FilterMode,
145
146        /// Whether to return rooms the user is invited to.
147        ///
148        /// Defaults to [`FilterMode::Both`].
149        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
150        pub is_invited: FilterMode,
151
152        /// Only list rooms with these create-types, or all.
153        ///
154        /// If a room type is specified in both `room_types` and `not_room_types`,
155        /// `not_room_types` wins and the corresponding rooms are not included.
156        #[serde(default, skip_serializing_if = "Vec::is_empty")]
157        pub room_types: Vec<RoomTypeFilter>,
158
159        /// Only list rooms that are not of these create-types, or all.
160        ///
161        /// If a room type is specified in both `room_types` and `not_room_types`,
162        /// `not_room_types` wins and the corresponding rooms are not included.
163        #[serde(default, skip_serializing_if = "Vec::is_empty")]
164        pub not_room_types: Vec<RoomTypeFilter>,
165
166        /// Only list rooms with any of these tags, or all.
167        #[serde(default, skip_serializing_if = "Vec::is_empty")]
168        pub tags: Vec<TagName>,
169
170        /// Only list rooms with none of these tags, or all.
171        ///
172        /// Takes priority over `tags`.
173        #[serde(default, skip_serializing_if = "Vec::is_empty")]
174        pub not_tags: Vec<TagName>,
175    }
176
177    impl ListFilters {
178        /// Creates an empty `ListFilters`.
179        pub fn new() -> Self {
180            Default::default()
181        }
182
183        /// Whether no filter is set.
184        pub fn is_empty(&self) -> bool {
185            let Self {
186                is_dm,
187                spaces,
188                is_encrypted,
189                is_invited,
190                room_types,
191                not_room_types,
192                tags,
193                not_tags,
194            } = self;
195
196            *is_dm == FilterMode::Both
197                && spaces.is_empty()
198                && *is_encrypted == FilterMode::Both
199                && *is_invited == FilterMode::Both
200                && room_types.is_empty()
201                && not_room_types.is_empty()
202                && tags.is_empty()
203                && not_tags.is_empty()
204        }
205    }
206
207    /// How a filter of [`ListFilters`] applies to the rooms matching its criterion.
208    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
209    #[serde(from = "Option<bool>", into = "Option<bool>")]
210    #[allow(clippy::exhaustive_enums)]
211    pub enum FilterMode {
212        /// Return both the rooms that match the criterion and the rooms that don't.
213        #[default]
214        Both,
215
216        /// Return only the rooms that match the criterion.
217        Only,
218
219        /// Return only the rooms that don't match the criterion.
220        Exclude,
221    }
222
223    impl From<Option<bool>> for FilterMode {
224        fn from(value: Option<bool>) -> Self {
225            match value {
226                None => Self::Both,
227                Some(true) => Self::Only,
228                Some(false) => Self::Exclude,
229            }
230        }
231    }
232
233    impl From<FilterMode> for Option<bool> {
234        fn from(value: FilterMode) -> Self {
235            match value {
236                FilterMode::Both => None,
237                FilterMode::Only => Some(true),
238                FilterMode::Exclude => Some(false),
239            }
240        }
241    }
242
243    /// A room subscription (see [`super::Request::room_subscriptions`]).
244    #[derive(Clone, Debug, Serialize, Deserialize)]
245    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
246    pub struct RoomSubscription {
247        /// Required state for the room.
248        pub required_state: RequiredState,
249
250        /// The maximum number of timeline events to return for the room.
251        pub timeline_limit: UInt,
252    }
253
254    impl RoomSubscription {
255        /// Creates a new `RoomSubscription` with the given required state and timeline limit.
256        pub fn new(required_state: RequiredState, timeline_limit: UInt) -> Self {
257            Self { required_state, timeline_limit }
258        }
259    }
260
261    /// The set of state that the server should return for a room.
262    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
263    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
264    pub struct RequiredState {
265        /// The state to return, unless filtered out by `exclude`.
266        #[serde(default, skip_serializing_if = "Vec::is_empty")]
267        pub include: Vec<RequiredStateElement>,
268
269        /// The state to filter out before returning.
270        #[serde(default, skip_serializing_if = "Vec::is_empty")]
271        pub exclude: Vec<RequiredStateElement>,
272
273        /// Whether to enable lazy-loading of room members.
274        ///
275        /// Defaults to `false`.
276        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
277        pub lazy_members: bool,
278    }
279
280    impl RequiredState {
281        /// Creates an empty `RequiredState`.
282        pub fn new() -> Self {
283            Default::default()
284        }
285    }
286
287    /// A matcher for state events (see [`RequiredState`]).
288    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
289    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
290    pub struct RequiredStateElement {
291        /// The event type to match.
292        ///
293        /// `None` matches all types.
294        #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
295        pub event_type: Option<StateEventType>,
296
297        /// The state key to match.
298        ///
299        /// `None` matches all state keys.
300        #[serde(skip_serializing_if = "Option::is_none")]
301        pub state_key: Option<String>,
302    }
303
304    impl RequiredStateElement {
305        /// Creates a `RequiredStateElement` that matches all state events.
306        pub fn new() -> Self {
307            Default::default()
308        }
309
310        /// Only match state events with the given event type.
311        pub fn with_event_type(mut self, event_type: StateEventType) -> Self {
312            self.event_type = Some(event_type);
313            self
314        }
315
316        /// Only match state events with the given state key.
317        pub fn with_state_key(mut self, state_key: String) -> Self {
318            self.state_key = Some(state_key);
319            self
320        }
321    }
322
323    /// Extensions configuration (see [`super::Request::extensions`]).
324    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
325    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
326    pub struct Extensions {
327        /// Configure the to-device extension.
328        #[serde(default, skip_serializing_if = "ToDevice::is_disabled")]
329        pub to_device: ToDevice,
330
331        /// Configure the E2EE extension.
332        #[serde(default, skip_serializing_if = "E2EE::is_disabled")]
333        pub e2ee: E2EE,
334
335        /// Configure the account data extension.
336        #[serde(default, skip_serializing_if = "AccountData::is_disabled")]
337        pub account_data: AccountData,
338
339        /// Configure the receipts extension.
340        #[serde(default, skip_serializing_if = "Receipts::is_disabled")]
341        pub receipts: Receipts,
342
343        /// Configure the typing extension.
344        #[serde(default, skip_serializing_if = "Typing::is_disabled")]
345        pub typing: Typing,
346
347        /// Configure the thread subscriptions extension.
348        #[cfg(feature = "unstable-msc4308")]
349        #[serde(
350            default,
351            skip_serializing_if = "ThreadSubscriptions::is_disabled",
352            rename = "io.element.msc4308.thread_subscriptions"
353        )]
354        pub thread_subscriptions: ThreadSubscriptions,
355
356        /// Configure the threads extension.
357        #[cfg(feature = "unstable-msc4360")]
358        #[serde(
359            default,
360            skip_serializing_if = "Threads::is_disabled",
361            rename = "io.element.msc4360.threads"
362        )]
363        pub threads: Threads,
364
365        /// Configure the profiles extension.
366        #[cfg(feature = "unstable-msc4262")]
367        #[serde(
368            default,
369            skip_serializing_if = "Profiles::is_disabled",
370            rename = "org.matrix.msc4262.profiles"
371        )]
372        pub profiles: Profiles,
373
374        /// Configure the sticky events extension.
375        #[cfg(feature = "unstable-msc4480")]
376        #[serde(
377            default,
378            skip_serializing_if = "StickyEvents::is_disabled",
379            rename = "org.matrix.msc4354.sticky_events"
380        )]
381        pub sticky_events: StickyEvents,
382
383        /// Configure the presence extension.
384        #[cfg(feature = "unstable-msc4559")]
385        #[serde(
386            default,
387            skip_serializing_if = "Presence::is_disabled",
388            rename = "org.continuwuity.presence_v2.msc4559.presence"
389        )]
390        pub presence: Presence,
391
392        /// Extensions may add further fields to the list.
393        #[serde(flatten)]
394        pub(crate) other: BTreeMap<String, serde_json::Value>,
395    }
396
397    impl Extensions {
398        /// Creates an empty `Extensions`.
399        pub fn new() -> Self {
400            Default::default()
401        }
402
403        /// Whether all the extensions are disabled.
404        pub fn is_empty(&self) -> bool {
405            let Self {
406                to_device,
407                e2ee,
408                account_data,
409                receipts,
410                typing,
411                #[cfg(feature = "unstable-msc4308")]
412                thread_subscriptions,
413                #[cfg(feature = "unstable-msc4360")]
414                threads,
415                #[cfg(feature = "unstable-msc4262")]
416                profiles,
417                #[cfg(feature = "unstable-msc4480")]
418                sticky_events,
419                #[cfg(feature = "unstable-msc4559")]
420                presence,
421                other,
422            } = self;
423
424            #[allow(unused_mut)]
425            let mut empty = to_device.is_disabled()
426                && e2ee.is_disabled()
427                && account_data.is_disabled()
428                && receipts.is_disabled()
429                && typing.is_disabled()
430                && other.is_empty();
431
432            #[cfg(feature = "unstable-msc4308")]
433            {
434                empty &= thread_subscriptions.is_disabled();
435            }
436
437            #[cfg(feature = "unstable-msc4360")]
438            {
439                empty &= threads.is_disabled();
440            }
441
442            #[cfg(feature = "unstable-msc4262")]
443            {
444                empty &= profiles.is_disabled();
445            }
446
447            #[cfg(feature = "unstable-msc4480")]
448            {
449                empty &= sticky_events.is_disabled();
450            }
451
452            #[cfg(feature = "unstable-msc4559")]
453            {
454                empty &= presence.is_disabled();
455            }
456
457            empty
458        }
459    }
460
461    /// To-device extension configuration.
462    ///
463    /// According to [MSC4538](https://github.com/matrix-org/matrix-spec-proposals/pull/4538).
464    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
465    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
466    pub struct ToDevice {
467        /// Whether this extension is enabled.
468        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
469        pub enabled: bool,
470
471        /// Maximum number of to-device messages per response.
472        ///
473        /// Defaults to 100.
474        #[serde(skip_serializing_if = "Option::is_none")]
475        pub limit: Option<UInt>,
476
477        /// Give messages since this token only.
478        #[serde(skip_serializing_if = "Option::is_none")]
479        pub since: Option<String>,
480    }
481
482    impl ToDevice {
483        /// Creates a disabled `ToDevice`.
484        pub fn new() -> Self {
485            Default::default()
486        }
487
488        /// Whether this extension is disabled.
489        pub fn is_disabled(&self) -> bool {
490            !self.enabled
491        }
492    }
493
494    /// E2EE extension configuration.
495    ///
496    /// According to [MSC4543](https://github.com/matrix-org/matrix-spec-proposals/pull/4543).
497    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
498    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
499    pub struct E2EE {
500        /// Whether this extension is enabled.
501        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
502        pub enabled: bool,
503    }
504
505    impl E2EE {
506        /// Creates a disabled `E2EE`.
507        pub fn new() -> Self {
508            Default::default()
509        }
510
511        /// Whether this extension is disabled.
512        pub fn is_disabled(&self) -> bool {
513            !self.enabled
514        }
515    }
516
517    /// Account data extension configuration.
518    ///
519    /// According to [MSC4548](https://github.com/matrix-org/matrix-spec-proposals/pull/4548).
520    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
521    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
522    pub struct AccountData {
523        /// Whether this extension is enabled.
524        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
525        pub enabled: bool,
526
527        /// The keys of the lists the extension applies to.
528        ///
529        /// `None` means all the lists, and an empty list means none of them.
530        #[serde(skip_serializing_if = "Option::is_none")]
531        pub lists: Option<Vec<String>>,
532
533        /// The room subscriptions the extension applies to.
534        ///
535        /// `None` means all the room subscriptions, and an empty list means none of them.
536        #[serde(skip_serializing_if = "Option::is_none")]
537        pub rooms: Option<Vec<OwnedRoomId>>,
538    }
539
540    impl AccountData {
541        /// Creates a disabled `AccountData`.
542        pub fn new() -> Self {
543            Default::default()
544        }
545
546        /// Whether this extension is disabled.
547        pub fn is_disabled(&self) -> bool {
548            !self.enabled
549        }
550    }
551
552    /// Receipts extension configuration.
553    ///
554    /// According to [MSC4551](https://github.com/matrix-org/matrix-spec-proposals/pull/4551).
555    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
556    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
557    pub struct Receipts {
558        /// Whether this extension is enabled.
559        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
560        pub enabled: bool,
561
562        /// The keys of the lists the extension applies to.
563        ///
564        /// `None` means all the lists, and an empty list means none of them.
565        #[serde(skip_serializing_if = "Option::is_none")]
566        pub lists: Option<Vec<String>>,
567
568        /// The room subscriptions the extension applies to.
569        ///
570        /// `None` means all the room subscriptions, and an empty list means none of them.
571        #[serde(skip_serializing_if = "Option::is_none")]
572        pub rooms: Option<Vec<OwnedRoomId>>,
573    }
574
575    impl Receipts {
576        /// Creates a disabled `Receipts`.
577        pub fn new() -> Self {
578            Default::default()
579        }
580
581        /// Whether this extension is disabled.
582        pub fn is_disabled(&self) -> bool {
583            !self.enabled
584        }
585    }
586
587    /// Typing extension configuration.
588    ///
589    /// According to [MSC4508](https://github.com/matrix-org/matrix-spec-proposals/pull/4508).
590    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
591    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
592    pub struct Typing {
593        /// Whether this extension is enabled.
594        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
595        pub enabled: bool,
596
597        /// The keys of the lists the extension applies to.
598        ///
599        /// `None` means all the lists, and an empty list means none of them.
600        #[serde(skip_serializing_if = "Option::is_none")]
601        pub lists: Option<Vec<String>>,
602
603        /// The room subscriptions the extension applies to.
604        ///
605        /// `None` means all the room subscriptions, and an empty list means none of them.
606        #[serde(skip_serializing_if = "Option::is_none")]
607        pub rooms: Option<Vec<OwnedRoomId>>,
608    }
609
610    impl Typing {
611        /// Creates a disabled `Typing`.
612        pub fn new() -> Self {
613            Default::default()
614        }
615
616        /// Whether this extension is disabled.
617        pub fn is_disabled(&self) -> bool {
618            !self.enabled
619        }
620    }
621
622    /// Thread subscriptions extension configuration.
623    ///
624    /// According to [MSC4308](https://github.com/matrix-org/matrix-spec-proposals/pull/4308).
625    #[cfg(feature = "unstable-msc4308")]
626    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
627    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
628    pub struct ThreadSubscriptions {
629        /// Whether this extension is enabled.
630        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
631        pub enabled: bool,
632
633        /// Maximum number of thread subscription changes to receive in the response.
634        ///
635        /// Defaults to 100.
636        /// Servers may impose a smaller limit than what is requested here.
637        #[serde(skip_serializing_if = "Option::is_none")]
638        pub limit: Option<UInt>,
639    }
640
641    #[cfg(feature = "unstable-msc4308")]
642    impl ThreadSubscriptions {
643        /// Creates a disabled `ThreadSubscriptions`.
644        pub fn new() -> Self {
645            Default::default()
646        }
647
648        /// Whether this extension is disabled.
649        pub fn is_disabled(&self) -> bool {
650            !self.enabled
651        }
652    }
653
654    /// Threads extension configuration.
655    ///
656    /// According to [MSC4360](https://github.com/matrix-org/matrix-spec-proposals/pull/4360).
657    #[cfg(feature = "unstable-msc4360")]
658    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
659    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
660    pub struct Threads {
661        /// Whether this extension is enabled.
662        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
663        pub enabled: bool,
664
665        /// Whether to include the thread root events in the response.
666        pub include_roots: bool,
667
668        /// Maximum number of thread updates to receive in the response.
669        ///
670        /// Defaults to 100.
671        /// Servers may impose a smaller limit than what is requested here.
672        #[serde(skip_serializing_if = "Option::is_none")]
673        pub limit: Option<UInt>,
674    }
675
676    #[cfg(feature = "unstable-msc4360")]
677    impl Threads {
678        /// Creates a disabled `Threads`.
679        pub fn new() -> Self {
680            Default::default()
681        }
682
683        /// Whether this extension is disabled.
684        pub fn is_disabled(&self) -> bool {
685            !self.enabled
686        }
687    }
688
689    /// User profiles extension configuration.
690    ///
691    /// According to [MSC4262](https://github.com/matrix-org/matrix-spec-proposals/pull/4262).
692    #[cfg(feature = "unstable-msc4262")]
693    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
694    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
695    pub struct Profiles {
696        /// Whether this extension is enabled.
697        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
698        pub enabled: bool,
699
700        /// The profile fields to receive updates for.
701        ///
702        /// `None` means all the profile fields.
703        #[serde(skip_serializing_if = "Option::is_none")]
704        pub fields: Option<Vec<ruma_common::profile::ProfileFieldName>>,
705
706        /// The keys of the lists the extension applies to.
707        ///
708        /// `None` means all the lists, and an empty list means none of them.
709        #[serde(skip_serializing_if = "Option::is_none")]
710        pub lists: Option<Vec<String>>,
711
712        /// The room subscriptions the extension applies to.
713        ///
714        /// `None` means all the room subscriptions, and an empty list means none of them.
715        #[serde(skip_serializing_if = "Option::is_none")]
716        pub rooms: Option<Vec<OwnedRoomId>>,
717    }
718
719    #[cfg(feature = "unstable-msc4262")]
720    impl Profiles {
721        /// Creates a disabled `Profiles`.
722        pub fn new() -> Self {
723            Default::default()
724        }
725
726        /// Whether this extension is disabled.
727        pub fn is_disabled(&self) -> bool {
728            !self.enabled
729        }
730    }
731
732    /// Sticky events extension configuration.
733    ///
734    /// According to [MSC4480](https://github.com/matrix-org/matrix-spec-proposals/pull/4480).
735    #[cfg(feature = "unstable-msc4480")]
736    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
737    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
738    pub struct StickyEvents {
739        /// Whether this extension is enabled.
740        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
741        pub enabled: bool,
742
743        /// Maximum number of sticky events to return per response.
744        ///
745        /// Defaults to 100 (server-side) and the server may override it to a lower value.
746        #[serde(skip_serializing_if = "Option::is_none")]
747        pub limit: Option<UInt>,
748
749        /// The keys of the lists the extension applies to.
750        ///
751        /// `None` means all the lists, and an empty list means none of them.
752        #[serde(skip_serializing_if = "Option::is_none")]
753        pub lists: Option<Vec<String>>,
754
755        /// The room subscriptions the extension applies to.
756        ///
757        /// `None` means all the room subscriptions, and an empty list means none of them.
758        #[serde(skip_serializing_if = "Option::is_none")]
759        pub rooms: Option<Vec<OwnedRoomId>>,
760    }
761
762    #[cfg(feature = "unstable-msc4480")]
763    impl StickyEvents {
764        /// Creates a disabled `StickyEvents`.
765        pub fn new() -> Self {
766            Default::default()
767        }
768
769        /// Whether this extension is disabled.
770        pub fn is_disabled(&self) -> bool {
771            !self.enabled
772        }
773    }
774
775    /// Presence extension configuration.
776    ///
777    /// According to [MSC4559](https://github.com/matrix-org/matrix-spec-proposals/pull/4559).
778    #[cfg(feature = "unstable-msc4559")]
779    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
780    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
781    pub struct Presence {
782        /// Whether this extension is enabled.
783        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
784        pub enabled: bool,
785
786        /// The keys of the lists the extension applies to.
787        ///
788        /// `None` means all the lists, and an empty list means none of them.
789        #[serde(skip_serializing_if = "Option::is_none")]
790        pub lists: Option<Vec<String>>,
791
792        /// The room subscriptions the extension applies to.
793        ///
794        /// `None` means all the room subscriptions, and an empty list means none of them.
795        #[serde(skip_serializing_if = "Option::is_none")]
796        pub rooms: Option<Vec<OwnedRoomId>>,
797    }
798
799    #[cfg(feature = "unstable-msc4559")]
800    impl Presence {
801        /// Creates a disabled `Presence`.
802        pub fn new() -> Self {
803            Default::default()
804        }
805
806        /// Whether this extension is disabled.
807        pub fn is_disabled(&self) -> bool {
808            !self.enabled
809        }
810    }
811}
812
813/// Response type for the `/sync` endpoint.
814#[response]
815pub struct Response {
816    /// The token to supply in the `pos` field of the next `/sync` request
817    /// (see [`Request::pos`]).
818    pub pos: String,
819
820    /// Resulting details of the lists.
821    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
822    pub lists: BTreeMap<String, response::List>,
823
824    /// The updated rooms.
825    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
826    pub rooms: BTreeMap<OwnedRoomId, response::Room>,
827
828    /// Extensions data.
829    #[serde(default, skip_serializing_if = "response::Extensions::is_empty")]
830    pub extensions: response::Extensions,
831}
832
833impl Response {
834    /// Creates a new `Response` with the given `pos`.
835    pub fn new(pos: String) -> Self {
836        Self {
837            pos,
838            lists: Default::default(),
839            rooms: Default::default(),
840            extensions: Default::default(),
841        }
842    }
843}
844
845/// HTTP types related to a [`Response`].
846pub mod response {
847    #[cfg(any(feature = "unstable-msc4308", feature = "unstable-msc4360"))]
848    use ruma_common::OwnedEventId;
849    #[cfg(feature = "unstable-msc4559")]
850    use ruma_common::presence::PresenceStatus;
851    #[cfg(feature = "unstable-msc4262")]
852    use ruma_common::profile::UserProfileUpdate;
853    use ruma_common::{OneTimeKeyAlgorithm, serde::from_raw_json_value};
854    use ruma_events::{
855        AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnyToDeviceEvent,
856        receipt::ReceiptEventContent, room::member::MembershipState, typing::TypingEventContent,
857    };
858    use serde::de::IgnoredAny;
859    use serde_json::value::RawValue as RawJsonValue;
860
861    #[cfg(feature = "unstable-msc4559")]
862    use super::PresenceState;
863    use super::{
864        super::DeviceLists, AnyStrippedStateEvent, AnySyncStateEvent, AnySyncTimelineEvent,
865        BTreeMap, Deserialize, JsOption, OwnedMxcUri, OwnedRoomId, OwnedUserId, Raw, Serialize,
866        StateEventType, UInt,
867    };
868    #[cfg(feature = "unstable-msc4308")]
869    use crate::threads::get_thread_subscriptions_changes::msc4308::{
870        ThreadSubscription, ThreadUnsubscription,
871    };
872
873    /// The details of a list (see [`super::Response::lists`]).
874    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
875    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
876    pub struct List {
877        /// The total number of rooms that match the filters of this list, ignoring the range.
878        pub count: UInt,
879    }
880
881    impl List {
882        /// Creates a new `List` with the given count.
883        pub fn new(count: UInt) -> Self {
884            Self { count }
885        }
886    }
887
888    /// An updated room (see [`super::Response::rooms`]).
889    #[derive(Clone, Debug, Serialize)]
890    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
891    pub struct Room {
892        /// An integer that can be used to sort rooms based on their last activity.
893        ///
894        /// Greater means more recent. The value is opaque and may decrease.
895        #[serde(skip_serializing_if = "Option::is_none")]
896        pub bump_stamp: Option<UInt>,
897
898        /// The current membership of the user in the room.
899        #[serde(skip_serializing_if = "Option::is_none")]
900        pub membership: Option<MembershipState>,
901
902        /// The keys of the lists that match this room.
903        #[serde(default, skip_serializing_if = "Vec::is_empty")]
904        pub lists: Vec<String>,
905
906        /// The data of the room, depending on the membership of the user.
907        #[serde(flatten)]
908        pub data: RoomData,
909    }
910
911    impl Room {
912        /// Creates a new `Room` with the given data.
913        pub fn new(data: RoomData) -> Self {
914            Self { bump_stamp: None, membership: None, lists: Vec::new(), data }
915        }
916    }
917
918    impl<'de> Deserialize<'de> for Room {
919        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
920        where
921            D: serde::Deserializer<'de>,
922        {
923            #[derive(Deserialize)]
924            struct RoomDeHelper {
925                bump_stamp: Option<UInt>,
926                membership: Option<MembershipState>,
927                #[serde(default)]
928                lists: Vec<String>,
929            }
930
931            let json = Box::<RawJsonValue>::deserialize(deserializer)?;
932            let RoomDeHelper { bump_stamp, membership, lists } = from_raw_json_value(&json)?;
933            let data = from_raw_json_value(&json)?;
934
935            Ok(Self { bump_stamp, membership, lists, data })
936        }
937    }
938
939    /// The data of a [`Room`].
940    #[derive(Clone, Debug, Serialize)]
941    #[serde(untagged)]
942    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
943    pub enum RoomData {
944        /// The data of a room the user is or has been joined to.
945        Full(FullRoomData),
946
947        /// The data of a room the user has not been joined to, e.g. an invite or a knock.
948        Stripped(StrippedRoomData),
949    }
950
951    impl<'de> Deserialize<'de> for RoomData {
952        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
953        where
954            D: serde::Deserializer<'de>,
955        {
956            #[derive(Deserialize)]
957            struct StrippedStateDeHelper {
958                stripped_state: Option<IgnoredAny>,
959            }
960
961            let json = Box::<RawJsonValue>::deserialize(deserializer)?;
962            let StrippedStateDeHelper { stripped_state } = from_raw_json_value(&json)?;
963
964            if stripped_state.is_some() {
965                Ok(Self::Stripped(from_raw_json_value(&json)?))
966            } else {
967                Ok(Self::Full(from_raw_json_value(&json)?))
968            }
969        }
970    }
971
972    impl From<FullRoomData> for RoomData {
973        fn from(value: FullRoomData) -> Self {
974            Self::Full(value)
975        }
976    }
977
978    impl From<StrippedRoomData> for RoomData {
979        fn from(value: StrippedRoomData) -> Self {
980            Self::Stripped(value)
981        }
982    }
983
984    /// The data of a room the user is or has been joined to (see [`RoomData::Full`]).
985    ///
986    /// When [`FullRoomData::initial`] is `false`, an omitted field means that it is unchanged.
987    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
988    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
989    pub struct FullRoomData {
990        /// The name as calculated by the server.
991        ///
992        /// `Null` if the room name was removed.
993        #[serde(default, skip_serializing_if = "JsOption::is_undefined")]
994        pub name: JsOption<String>,
995
996        /// The avatar.
997        ///
998        /// `Null` if the room avatar was removed.
999        #[serde(default, skip_serializing_if = "JsOption::is_undefined")]
1000        pub avatar: JsOption<OwnedMxcUri>,
1001
1002        /// Heroes of the room, if the room has no name.
1003        #[serde(skip_serializing_if = "Option::is_none")]
1004        pub heroes: Option<Vec<Hero>>,
1005
1006        /// Whether it is a direct room.
1007        #[serde(skip_serializing_if = "Option::is_none")]
1008        pub is_dm: Option<bool>,
1009
1010        /// Whether it is the first time this room is sent on this connection, or the client
1011        /// should replace all its room data with what is returned.
1012        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
1013        pub initial: bool,
1014
1015        /// Whether more historic events are returned because the timeline limit increased.
1016        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
1017        pub expanded_timeline: bool,
1018
1019        /// Changes in the current state of the room.
1020        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1021        pub required_state: Vec<RequiredStateEntry>,
1022
1023        /// The latest events in the room.
1024        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1025        pub timeline: Vec<Raw<AnySyncTimelineEvent>>,
1026
1027        /// The `prev_batch` allowing you to paginate through the messages
1028        /// before the given ones.
1029        #[serde(skip_serializing_if = "Option::is_none")]
1030        pub prev_batch: Option<String>,
1031
1032        /// Whether there are more events since the previous sync than were included in the
1033        /// timeline.
1034        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
1035        pub limited: bool,
1036
1037        /// The number of timeline events which have just occurred and are not
1038        /// historical.
1039        #[serde(skip_serializing_if = "Option::is_none")]
1040        pub num_live: Option<UInt>,
1041
1042        /// The number of users with membership of `join`, including the
1043        /// client’s own user ID.
1044        #[serde(skip_serializing_if = "Option::is_none")]
1045        pub joined_count: Option<UInt>,
1046
1047        /// The number of users with membership of `invite`.
1048        #[serde(skip_serializing_if = "Option::is_none")]
1049        pub invited_count: Option<UInt>,
1050    }
1051
1052    impl FullRoomData {
1053        /// Creates an empty `FullRoomData`.
1054        pub fn new() -> Self {
1055            Default::default()
1056        }
1057    }
1058
1059    /// The data of a room the user has not been joined to (see [`RoomData::Stripped`]).
1060    #[derive(Clone, Debug, Deserialize, Serialize)]
1061    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1062    pub struct StrippedRoomData {
1063        /// Stripped state events of the room.
1064        pub stripped_state: Vec<Raw<AnyStrippedStateEvent>>,
1065    }
1066
1067    impl StrippedRoomData {
1068        /// Creates a new `StrippedRoomData` with the given stripped state.
1069        pub fn new(stripped_state: Vec<Raw<AnyStrippedStateEvent>>) -> Self {
1070            Self { stripped_state }
1071        }
1072    }
1073
1074    /// A room hero (see [`FullRoomData::heroes`]).
1075    #[derive(Clone, Debug, Deserialize, Serialize)]
1076    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1077    pub struct Hero {
1078        /// The user ID.
1079        pub user_id: OwnedUserId,
1080
1081        /// The display name from the membership event, if set.
1082        #[serde(skip_serializing_if = "Option::is_none")]
1083        pub displayname: Option<String>,
1084
1085        /// The avatar URL from the membership event, if set.
1086        #[serde(skip_serializing_if = "Option::is_none")]
1087        pub avatar_url: Option<OwnedMxcUri>,
1088    }
1089
1090    impl Hero {
1091        /// Creates a new `Hero` with the given user ID.
1092        pub fn new(user_id: OwnedUserId) -> Self {
1093            Self { user_id, displayname: None, avatar_url: None }
1094        }
1095    }
1096
1097    /// An entry of [`FullRoomData::required_state`].
1098    #[derive(Clone, Debug, Serialize)]
1099    #[serde(untagged)]
1100    #[allow(clippy::exhaustive_enums)]
1101    pub enum RequiredStateEntry {
1102        /// A state event.
1103        Event(Raw<AnySyncStateEvent>),
1104
1105        /// A state entry that was deleted.
1106        Deleted(StateStub),
1107    }
1108
1109    impl<'de> Deserialize<'de> for RequiredStateEntry {
1110        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1111        where
1112            D: serde::Deserializer<'de>,
1113        {
1114            #[derive(Deserialize)]
1115            struct ContentDeHelper {
1116                #[serde(default)]
1117                content: JsOption<IgnoredAny>,
1118            }
1119
1120            let json = Box::<RawJsonValue>::deserialize(deserializer)?;
1121            let ContentDeHelper { content } = from_raw_json_value(&json)?;
1122
1123            if content.is_undefined() {
1124                Ok(Self::Deleted(from_raw_json_value(&json)?))
1125            } else {
1126                Ok(Self::Event(Raw::from_json(json)))
1127            }
1128        }
1129    }
1130
1131    /// A state entry that was deleted (see [`RequiredStateEntry::Deleted`]).
1132    #[derive(Clone, Debug, Deserialize, Serialize)]
1133    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1134    pub struct StateStub {
1135        /// The type of the deleted state entry.
1136        #[serde(rename = "type")]
1137        pub event_type: StateEventType,
1138
1139        /// The state key of the deleted state entry.
1140        pub state_key: String,
1141    }
1142
1143    impl StateStub {
1144        /// Creates a new `StateStub` with the given event type and state key.
1145        pub fn new(event_type: StateEventType, state_key: String) -> Self {
1146            Self { event_type, state_key }
1147        }
1148    }
1149
1150    /// Extensions data (see [`super::Response::extensions`]).
1151    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1152    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1153    pub struct Extensions {
1154        /// To-device extension response.
1155        #[serde(skip_serializing_if = "Option::is_none")]
1156        pub to_device: Option<ToDevice>,
1157
1158        /// E2EE extension response.
1159        #[serde(skip_serializing_if = "Option::is_none")]
1160        pub e2ee: Option<E2EE>,
1161
1162        /// Account data extension response.
1163        #[serde(default, skip_serializing_if = "AccountData::is_empty")]
1164        pub account_data: AccountData,
1165
1166        /// Receipts extension response.
1167        #[serde(default, skip_serializing_if = "Receipts::is_empty")]
1168        pub receipts: Receipts,
1169
1170        /// Typing extension response.
1171        #[serde(default, skip_serializing_if = "Typing::is_empty")]
1172        pub typing: Typing,
1173
1174        /// Thread subscriptions extension response.
1175        #[cfg(feature = "unstable-msc4308")]
1176        #[serde(
1177            default,
1178            skip_serializing_if = "ThreadSubscriptions::is_empty",
1179            rename = "io.element.msc4308.thread_subscriptions"
1180        )]
1181        pub thread_subscriptions: ThreadSubscriptions,
1182
1183        /// Threads extension response.
1184        #[cfg(feature = "unstable-msc4360")]
1185        #[serde(
1186            default,
1187            skip_serializing_if = "Threads::is_empty",
1188            rename = "io.element.msc4360.threads"
1189        )]
1190        pub threads: Threads,
1191
1192        /// Profiles extension response.
1193        #[cfg(feature = "unstable-msc4262")]
1194        #[serde(
1195            default,
1196            skip_serializing_if = "Profiles::is_empty",
1197            rename = "org.matrix.msc4262.profiles"
1198        )]
1199        pub profiles: Profiles,
1200
1201        /// Sticky events extension response.
1202        #[cfg(feature = "unstable-msc4480")]
1203        #[serde(
1204            default,
1205            skip_serializing_if = "StickyEvents::is_empty",
1206            rename = "org.matrix.msc4354.sticky_events"
1207        )]
1208        pub sticky_events: StickyEvents,
1209
1210        /// Presence extension response.
1211        #[cfg(feature = "unstable-msc4559")]
1212        #[serde(
1213            default,
1214            skip_serializing_if = "Presence::is_empty",
1215            rename = "org.continuwuity.presence_v2.msc4559.presence"
1216        )]
1217        pub presence: Presence,
1218    }
1219
1220    impl Extensions {
1221        /// Creates an empty `Extensions`.
1222        pub fn new() -> Self {
1223            Default::default()
1224        }
1225
1226        /// Whether the extension data is empty.
1227        pub fn is_empty(&self) -> bool {
1228            let Self {
1229                to_device,
1230                e2ee,
1231                account_data,
1232                receipts,
1233                typing,
1234                #[cfg(feature = "unstable-msc4308")]
1235                thread_subscriptions,
1236                #[cfg(feature = "unstable-msc4360")]
1237                threads,
1238                #[cfg(feature = "unstable-msc4262")]
1239                profiles,
1240                #[cfg(feature = "unstable-msc4480")]
1241                sticky_events,
1242                #[cfg(feature = "unstable-msc4559")]
1243                presence,
1244            } = self;
1245
1246            #[allow(unused_mut)]
1247            let mut empty = to_device.is_none()
1248                && e2ee.is_none()
1249                && account_data.is_empty()
1250                && receipts.is_empty()
1251                && typing.is_empty();
1252
1253            #[cfg(feature = "unstable-msc4308")]
1254            {
1255                empty &= thread_subscriptions.is_empty();
1256            }
1257
1258            #[cfg(feature = "unstable-msc4360")]
1259            {
1260                empty &= threads.is_empty();
1261            }
1262
1263            #[cfg(feature = "unstable-msc4262")]
1264            {
1265                empty &= profiles.is_empty();
1266            }
1267
1268            #[cfg(feature = "unstable-msc4480")]
1269            {
1270                empty &= sticky_events.is_empty();
1271            }
1272
1273            #[cfg(feature = "unstable-msc4559")]
1274            {
1275                empty &= presence.is_empty();
1276            }
1277
1278            empty
1279        }
1280    }
1281
1282    /// To-device extension response.
1283    ///
1284    /// According to [MSC4538](https://github.com/matrix-org/matrix-spec-proposals/pull/4538).
1285    #[derive(Clone, Debug, Serialize, Deserialize)]
1286    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1287    pub struct ToDevice {
1288        /// The token to send as `since` in the next request.
1289        pub next_batch: String,
1290
1291        /// The messages for this device, in order of arrival.
1292        pub messages: Vec<Raw<AnyToDeviceEvent>>,
1293    }
1294
1295    impl ToDevice {
1296        /// Creates a new `ToDevice` with the given `next_batch` and messages.
1297        pub fn new(next_batch: String, messages: Vec<Raw<AnyToDeviceEvent>>) -> Self {
1298            Self { next_batch, messages }
1299        }
1300    }
1301
1302    /// E2EE extension response.
1303    ///
1304    /// According to [MSC4543](https://github.com/matrix-org/matrix-spec-proposals/pull/4543).
1305    #[derive(Clone, Debug, Serialize, Deserialize)]
1306    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1307    pub struct E2EE {
1308        /// Information on E2EE device updates.
1309        #[serde(default, skip_serializing_if = "DeviceLists::is_empty")]
1310        pub device_lists: DeviceLists,
1311
1312        /// For each key algorithm, the number of unclaimed one-time keys currently held on the
1313        /// server for this device.
1314        ///
1315        /// An algorithm that is not listed has a count of 0.
1316        pub device_one_time_keys_count: BTreeMap<OneTimeKeyAlgorithm, UInt>,
1317
1318        /// The key algorithms for which the device has an unused fallback key.
1319        pub device_unused_fallback_key_types: Vec<OneTimeKeyAlgorithm>,
1320    }
1321
1322    impl E2EE {
1323        /// Creates a new `E2EE` with the given one-time keys count and unused fallback key types.
1324        pub fn new(
1325            device_one_time_keys_count: BTreeMap<OneTimeKeyAlgorithm, UInt>,
1326            device_unused_fallback_key_types: Vec<OneTimeKeyAlgorithm>,
1327        ) -> Self {
1328            Self {
1329                device_lists: DeviceLists::new(),
1330                device_one_time_keys_count,
1331                device_unused_fallback_key_types,
1332            }
1333        }
1334    }
1335
1336    /// Account data extension response.
1337    ///
1338    /// According to [MSC4548](https://github.com/matrix-org/matrix-spec-proposals/pull/4548).
1339    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1340    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1341    pub struct AccountData {
1342        /// The global private data created by this user.
1343        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1344        pub global: Vec<Raw<AnyGlobalAccountDataEvent>>,
1345
1346        /// The private data that this user has attached to each room.
1347        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1348        pub rooms: BTreeMap<OwnedRoomId, Vec<Raw<AnyRoomAccountDataEvent>>>,
1349    }
1350
1351    impl AccountData {
1352        /// Creates an empty `AccountData`.
1353        pub fn new() -> Self {
1354            Default::default()
1355        }
1356
1357        /// Whether all fields are empty.
1358        pub fn is_empty(&self) -> bool {
1359            let Self { global, rooms } = self;
1360            global.is_empty() && rooms.is_empty()
1361        }
1362    }
1363
1364    /// Receipts extension response.
1365    ///
1366    /// According to [MSC4551](https://github.com/matrix-org/matrix-spec-proposals/pull/4551).
1367    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1368    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1369    pub struct Receipts {
1370        /// The receipts in each room.
1371        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1372        pub rooms: BTreeMap<OwnedRoomId, Raw<ReceiptEventContent>>,
1373    }
1374
1375    impl Receipts {
1376        /// Creates an empty `Receipts`.
1377        pub fn new() -> Self {
1378            Default::default()
1379        }
1380
1381        /// Whether all fields are empty.
1382        pub fn is_empty(&self) -> bool {
1383            let Self { rooms } = self;
1384            rooms.is_empty()
1385        }
1386    }
1387
1388    /// Typing extension response.
1389    ///
1390    /// According to [MSC4508](https://github.com/matrix-org/matrix-spec-proposals/pull/4508).
1391    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1392    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1393    pub struct Typing {
1394        /// The users currently typing in each room.
1395        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1396        pub rooms: BTreeMap<OwnedRoomId, TypingEventContent>,
1397    }
1398
1399    impl Typing {
1400        /// Creates an empty `Typing`.
1401        pub fn new() -> Self {
1402            Default::default()
1403        }
1404
1405        /// Whether all fields are empty.
1406        pub fn is_empty(&self) -> bool {
1407            let Self { rooms } = self;
1408            rooms.is_empty()
1409        }
1410    }
1411
1412    /// Thread subscriptions extension response.
1413    ///
1414    /// According to [MSC4308](https://github.com/matrix-org/matrix-spec-proposals/pull/4308).
1415    #[cfg(feature = "unstable-msc4308")]
1416    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1417    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1418    pub struct ThreadSubscriptions {
1419        /// New thread subscriptions.
1420        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1421        pub subscribed: BTreeMap<OwnedRoomId, BTreeMap<OwnedEventId, ThreadSubscription>>,
1422
1423        /// New thread unsubscriptions.
1424        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1425        pub unsubscribed: BTreeMap<OwnedRoomId, BTreeMap<OwnedEventId, ThreadUnsubscription>>,
1426
1427        /// A token that can be used to backpaginate (via the companion endpoint) other thread
1428        /// subscription changes that occurred since the last sync, but that were not included in
1429        /// this response.
1430        ///
1431        /// Only set when there are more changes to fetch.
1432        #[serde(skip_serializing_if = "Option::is_none")]
1433        pub prev_batch: Option<String>,
1434    }
1435
1436    #[cfg(feature = "unstable-msc4308")]
1437    impl ThreadSubscriptions {
1438        /// Creates an empty `ThreadSubscriptions`.
1439        pub fn new() -> Self {
1440            Default::default()
1441        }
1442
1443        /// Whether all fields are empty or `None`.
1444        pub fn is_empty(&self) -> bool {
1445            let Self { subscribed, unsubscribed, prev_batch } = self;
1446            subscribed.is_empty() && unsubscribed.is_empty() && prev_batch.is_none()
1447        }
1448    }
1449
1450    /// Threads extension response.
1451    ///
1452    /// According to [MSC4360](https://github.com/matrix-org/matrix-spec-proposals/pull/4360).
1453    #[cfg(feature = "unstable-msc4360")]
1454    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1455    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1456    pub struct Threads {
1457        /// The updated threads, by room ID and thread root event ID.
1458        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1459        pub updates: BTreeMap<OwnedRoomId, BTreeMap<OwnedEventId, ThreadUpdate>>,
1460
1461        /// A token to paginate the thread updates that were not included in this response, with
1462        /// the `/thread_updates` endpoint.
1463        ///
1464        /// Only set when there are more updates to fetch.
1465        #[serde(skip_serializing_if = "Option::is_none")]
1466        pub prev_batch: Option<String>,
1467    }
1468
1469    #[cfg(feature = "unstable-msc4360")]
1470    impl Threads {
1471        /// Creates an empty `Threads`.
1472        pub fn new() -> Self {
1473            Default::default()
1474        }
1475
1476        /// Whether all fields are empty or `None`.
1477        pub fn is_empty(&self) -> bool {
1478            let Self { updates, prev_batch } = self;
1479            updates.is_empty() && prev_batch.is_none()
1480        }
1481    }
1482
1483    /// An update to a thread in the threads extension response.
1484    ///
1485    /// According to [MSC4360](https://github.com/matrix-org/matrix-spec-proposals/pull/4360).
1486    #[cfg(feature = "unstable-msc4360")]
1487    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1488    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1489    pub struct ThreadUpdate {
1490        /// The thread root event, with the bundled `m.thread` aggregation.
1491        ///
1492        /// Only present if `include_roots` is set in the request.
1493        #[serde(skip_serializing_if = "Option::is_none")]
1494        pub thread_root: Option<Raw<AnySyncTimelineEvent>>,
1495
1496        /// A token to paginate the other updates in this thread with the `/relations` endpoint.
1497        #[serde(skip_serializing_if = "Option::is_none")]
1498        pub prev_batch: Option<String>,
1499    }
1500
1501    #[cfg(feature = "unstable-msc4360")]
1502    impl ThreadUpdate {
1503        /// Creates an empty `ThreadUpdate`.
1504        pub fn new() -> Self {
1505            Default::default()
1506        }
1507    }
1508
1509    /// Profiles extension response.
1510    ///
1511    /// According to [MSC4262](https://github.com/matrix-org/matrix-spec-proposals/pull/4262).
1512    #[cfg(feature = "unstable-msc4262")]
1513    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1514    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1515    pub struct Profiles {
1516        /// Profile updates keyed by user ID.
1517        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1518        pub users: BTreeMap<OwnedUserId, UserProfileUpdate>,
1519    }
1520
1521    #[cfg(feature = "unstable-msc4262")]
1522    impl Profiles {
1523        /// Creates an empty `Profiles`.
1524        pub fn new() -> Self {
1525            Default::default()
1526        }
1527
1528        /// Whether all fields are empty.
1529        pub fn is_empty(&self) -> bool {
1530            let Self { users } = self;
1531            users.is_empty()
1532        }
1533    }
1534
1535    /// Sticky events extension response.
1536    ///
1537    /// According to [MSC4480](https://github.com/matrix-org/matrix-spec-proposals/pull/4480).
1538    #[cfg(feature = "unstable-msc4480")]
1539    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1540    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1541    pub struct StickyEvents {
1542        /// The sticky events, grouped by room.
1543        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1544        pub rooms: BTreeMap<OwnedRoomId, StickyEventsRoom>,
1545    }
1546
1547    #[cfg(feature = "unstable-msc4480")]
1548    impl StickyEvents {
1549        /// Creates an empty `StickyEvents`.
1550        pub fn new() -> Self {
1551            Default::default()
1552        }
1553
1554        /// Whether all fields are empty.
1555        pub fn is_empty(&self) -> bool {
1556            let Self { rooms } = self;
1557            rooms.is_empty()
1558        }
1559    }
1560
1561    /// Sticky events for a single room in the sticky events extension response.
1562    #[cfg(feature = "unstable-msc4480")]
1563    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1564    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1565    pub struct StickyEventsRoom {
1566        /// The sticky events for this room.
1567        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1568        pub events: Vec<Raw<AnySyncTimelineEvent>>,
1569    }
1570
1571    #[cfg(feature = "unstable-msc4480")]
1572    impl StickyEventsRoom {
1573        /// Creates an empty `StickyEventsRoom`.
1574        pub fn new() -> Self {
1575            Default::default()
1576        }
1577    }
1578
1579    /// An update to a user's presence.
1580    ///
1581    /// According to [MSC4559](https://github.com/matrix-org/matrix-spec-proposals/pull/4559).
1582    #[cfg(feature = "unstable-msc4559")]
1583    #[derive(Clone, Debug, Serialize, Deserialize)]
1584    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1585    pub struct PresenceUpdate {
1586        /// The user's presence state.
1587        ///
1588        /// Defaults to `PresenceState::Offline`.
1589        #[serde(default = "presence_offline", skip_serializing_if = "is_presence_offline")]
1590        pub presence: PresenceState,
1591
1592        /// The status information for this user's presence, using the format from [MSC4532].
1593        ///
1594        /// [MSC4532]: https://github.com/matrix-org/matrix-spec-proposals/pull/4532
1595        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
1596        pub status: PresenceStatus,
1597    }
1598
1599    #[cfg(feature = "unstable-msc4559")]
1600    impl PresenceUpdate {
1601        /// Creates a new `PresenceUpdate` with the `offline` presence state and no status.
1602        pub fn new() -> Self {
1603            Self { presence: PresenceState::Offline, status: PresenceStatus::default() }
1604        }
1605    }
1606
1607    #[cfg(feature = "unstable-msc4559")]
1608    impl Default for PresenceUpdate {
1609        fn default() -> Self {
1610            Self::new()
1611        }
1612    }
1613
1614    #[cfg(feature = "unstable-msc4559")]
1615    fn presence_offline() -> PresenceState {
1616        PresenceState::Offline
1617    }
1618
1619    #[cfg(feature = "unstable-msc4559")]
1620    fn is_presence_offline(presence: &PresenceState) -> bool {
1621        *presence == PresenceState::Offline
1622    }
1623
1624    /// Presence extension response.
1625    ///
1626    /// According to [MSC4559](https://github.com/matrix-org/matrix-spec-proposals/pull/4559).
1627    #[cfg(feature = "unstable-msc4559")]
1628    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1629    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1630    pub struct Presence {
1631        /// Presence updates keyed by user ID.
1632        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1633        pub user_ids: BTreeMap<OwnedUserId, PresenceUpdate>,
1634    }
1635
1636    #[cfg(feature = "unstable-msc4559")]
1637    impl Presence {
1638        /// Creates an empty `Presence`.
1639        pub fn new() -> Self {
1640            Default::default()
1641        }
1642
1643        /// Whether all fields are empty.
1644        pub fn is_empty(&self) -> bool {
1645            let Self { user_ids } = self;
1646            user_ids.is_empty()
1647        }
1648    }
1649}
1650
1651#[cfg(test)]
1652mod tests {
1653    use js_int::uint;
1654    use ruma_common::{assert_to_canonical_json_eq, owned_room_id};
1655    use ruma_events::StateEventType;
1656    use serde_json::{from_value as from_json_value, json};
1657    use strass::assert_let;
1658
1659    use super::{
1660        request::{
1661            Extensions, FilterMode, List, ListFilters, RequiredState, RequiredStateElement,
1662            RoomSubscription,
1663        },
1664        response::{self, RequiredStateEntry, Room, RoomData, StateStub},
1665    };
1666
1667    #[test]
1668    fn serialize_list() {
1669        let mut required_state = RequiredState::new();
1670        required_state.include.push(
1671            RequiredStateElement::new()
1672                .with_event_type(StateEventType::RoomCreate)
1673                .with_state_key(String::new()),
1674        );
1675        required_state.lazy_members = true;
1676
1677        let mut list = List::new(required_state, uint!(10));
1678        list.range = Some((uint!(0), uint!(99)));
1679
1680        assert_to_canonical_json_eq!(
1681            list,
1682            json!({
1683                "range": [0, 99],
1684                "required_state": {
1685                    "include": [{ "type": "m.room.create", "state_key": "" }],
1686                    "lazy_members": true,
1687                },
1688                "timeline_limit": 10,
1689            })
1690        );
1691    }
1692
1693    #[test]
1694    fn serialize_room_subscription_all_state() {
1695        let mut required_state = RequiredState::new();
1696        required_state.include.push(RequiredStateElement::new());
1697        let subscription = RoomSubscription::new(required_state, uint!(10));
1698
1699        assert_to_canonical_json_eq!(
1700            subscription,
1701            json!({
1702                "required_state": { "include": [{}] },
1703                "timeline_limit": 10,
1704            })
1705        );
1706    }
1707
1708    #[test]
1709    fn list_filters_serde() {
1710        let mut filters = ListFilters::new();
1711        filters.is_dm = FilterMode::Only;
1712        filters.is_invited = FilterMode::Exclude;
1713
1714        assert_to_canonical_json_eq!(filters, json!({ "is_dm": true, "is_invited": false }));
1715
1716        let filters: ListFilters =
1717            from_json_value(json!({ "is_dm": true, "is_invited": false })).unwrap();
1718        assert_eq!(filters.is_dm, FilterMode::Only);
1719        assert_eq!(filters.is_encrypted, FilterMode::Both);
1720        assert_eq!(filters.is_invited, FilterMode::Exclude);
1721    }
1722
1723    #[test]
1724    fn deserialize_full_room() {
1725        let room: Room = from_json_value(json!({
1726            "name": null,
1727            "initial": true,
1728            "membership": "join",
1729            "lists": ["foo-list"],
1730            "required_state": [
1731                {
1732                    "content": {},
1733                    "event_id": "$create:example.com",
1734                    "origin_server_ts": 1,
1735                    "sender": "@alice:example.com",
1736                    "state_key": "",
1737                    "type": "m.room.create",
1738                },
1739                { "type": "m.room.topic", "state_key": "" },
1740            ],
1741        }))
1742        .unwrap();
1743
1744        assert_eq!(room.lists, ["foo-list"]);
1745        assert_let!(RoomData::Full(data) = room.data);
1746        assert!(data.name.is_null());
1747        assert!(data.initial);
1748        assert!(!data.expanded_timeline);
1749        assert_eq!(data.required_state.len(), 2);
1750        assert_let!(RequiredStateEntry::Event(_) = &data.required_state[0]);
1751        assert_let!(RequiredStateEntry::Deleted(stub) = &data.required_state[1]);
1752        assert_eq!(stub.event_type, StateEventType::RoomTopic);
1753        assert_eq!(stub.state_key, "");
1754    }
1755
1756    #[test]
1757    fn deserialize_stripped_room() {
1758        let room: Room = from_json_value(json!({
1759            "bump_stamp": 4,
1760            "membership": "invite",
1761            "stripped_state": [],
1762        }))
1763        .unwrap();
1764
1765        assert_eq!(room.bump_stamp, Some(uint!(4)));
1766        assert_let!(RoomData::Stripped(data) = room.data);
1767        assert_eq!(data.stripped_state.len(), 0);
1768    }
1769
1770    #[test]
1771    fn serialize_extensions() {
1772        let mut extensions = Extensions::new();
1773        extensions.typing.enabled = true;
1774        extensions.typing.lists = Some(vec![]);
1775        extensions.typing.rooms = Some(vec![owned_room_id!("!a:example.com")]);
1776
1777        assert_to_canonical_json_eq!(
1778            extensions,
1779            json!({ "typing": { "enabled": true, "lists": [], "rooms": ["!a:example.com"] } })
1780        );
1781    }
1782
1783    #[test]
1784    fn deserialize_extensions_response() {
1785        let extensions: response::Extensions = from_json_value(json!({
1786            "to_device": { "next_batch": "1", "messages": [] },
1787            "e2ee": {
1788                "device_one_time_keys_count": { "signed_curve25519": 50 },
1789                "device_unused_fallback_key_types": ["signed_curve25519"],
1790            },
1791            "receipts": {
1792                "rooms": {
1793                    "!a:example.com": {
1794                        "$e:example.com": { "m.read": { "@b:example.com": { "ts": 1 } } },
1795                    },
1796                },
1797            },
1798            "typing": { "rooms": { "!a:example.com": { "user_ids": ["@b:example.com"] } } },
1799        }))
1800        .unwrap();
1801
1802        assert_eq!(extensions.to_device.unwrap().next_batch, "1");
1803        assert_eq!(extensions.e2ee.unwrap().device_unused_fallback_key_types.len(), 1);
1804        assert_eq!(extensions.receipts.rooms.len(), 1);
1805        let typing = &extensions.typing.rooms["!a:example.com"];
1806        assert_eq!(typing.user_ids, ["@b:example.com"]);
1807
1808        // `device_one_time_keys_count` and `device_unused_fallback_key_types` are required.
1809        from_json_value::<response::Extensions>(json!({ "e2ee": {} })).unwrap_err();
1810    }
1811
1812    #[test]
1813    fn deserialize_null_content_as_event() {
1814        let entry: RequiredStateEntry = from_json_value(json!({
1815            "content": null,
1816            "type": "m.room.topic",
1817            "state_key": "",
1818        }))
1819        .unwrap();
1820
1821        assert_let!(RequiredStateEntry::Event(_) = entry);
1822    }
1823
1824    #[test]
1825    fn serialize_deleted_state() {
1826        let entry =
1827            RequiredStateEntry::Deleted(StateStub::new(StateEventType::RoomTopic, String::new()));
1828
1829        assert_to_canonical_json_eq!(entry, json!({ "type": "m.room.topic", "state_key": "" }));
1830    }
1831
1832    #[cfg(feature = "unstable-msc4480")]
1833    #[test]
1834    fn deserialize_sticky_events() {
1835        let sticky_events: response::StickyEvents = from_json_value(json!({
1836            "rooms": {
1837                "!room:example.com": {
1838                    "events": [{
1839                        "content": { "body": "sticky", "msgtype": "m.text" },
1840                        "event_id": "$1:example.com",
1841                        "origin_server_ts": 1,
1842                        "sender": "@alice:example.com",
1843                        "type": "m.room.message",
1844                        "sticky": { "duration_ms": 300_000 },
1845                    }]
1846                }
1847            }
1848        }))
1849        .unwrap();
1850
1851        assert_eq!(sticky_events.rooms.len(), 1);
1852        let room = sticky_events.rooms.values().next().unwrap();
1853        assert_eq!(room.events.len(), 1);
1854    }
1855
1856    #[cfg(feature = "unstable-msc4360")]
1857    #[test]
1858    fn threads_extension_serde() {
1859        use super::request;
1860
1861        let mut extensions = Extensions::new();
1862        extensions.threads = request::Threads { enabled: true, include_roots: true, limit: None };
1863        assert_to_canonical_json_eq!(
1864            extensions,
1865            json!({ "io.element.msc4360.threads": { "enabled": true, "include_roots": true } })
1866        );
1867
1868        let extensions: response::Extensions = from_json_value(json!({
1869            "io.element.msc4360.threads": {
1870                "updates": {
1871                    "!room:example.com": {
1872                        "$root:example.com": { "prev_batch": "t1" },
1873                    },
1874                },
1875                "prev_batch": "t2",
1876            },
1877        }))
1878        .unwrap();
1879
1880        let threads = extensions.threads;
1881        let update = &threads.updates["!room:example.com"]["$root:example.com"];
1882        assert!(update.thread_root.is_none());
1883        assert_eq!(update.prev_batch.as_deref(), Some("t1"));
1884        assert_eq!(threads.prev_batch.as_deref(), Some("t2"));
1885    }
1886
1887    #[cfg(feature = "unstable-msc4559")]
1888    #[test]
1889    fn presence_update_defaults() {
1890        use ruma_common::presence::PresenceState;
1891
1892        let update: response::PresenceUpdate = from_json_value(json!({})).unwrap();
1893        assert_eq!(update.presence, PresenceState::Offline);
1894        assert_to_canonical_json_eq!(update, json!({}));
1895    }
1896}
1897
1898#[cfg(all(test, feature = "client"))]
1899mod client_tests {
1900    use std::{borrow::Cow, time::Duration};
1901
1902    use ruma_common::{
1903        api::{
1904            FeatureFlag, MatrixVersion, OutgoingRequestExt as _, SupportedVersions,
1905            auth_scheme::SendAccessToken,
1906        },
1907        assert_to_canonical_json_eq,
1908    };
1909    use serde_json::{Value as JsonValue, from_slice as from_json_slice, json};
1910
1911    use super::Request;
1912
1913    #[test]
1914    fn serialize_request() {
1915        let supported = SupportedVersions {
1916            versions: [MatrixVersion::V1_19].into(),
1917            features: [FeatureFlag::Msc4186Stable].into(),
1918        };
1919        let mut request = Request::new();
1920        request.conn_id = Some("main".to_owned());
1921        request.pos = Some("s58_224".to_owned());
1922        request.timeout = Some(Duration::from_millis(30000));
1923
1924        let req: http::Request<Vec<u8>> = request
1925            .try_into_http_request(
1926                "https://homeserver.tld",
1927                SendAccessToken::IfRequired("auth_tok"),
1928                Cow::Owned(supported),
1929            )
1930            .unwrap();
1931
1932        assert_eq!(req.uri().path(), "/_matrix/client/v4/sync");
1933        assert_eq!(req.uri().query(), None);
1934        assert_to_canonical_json_eq!(
1935            from_json_slice::<JsonValue>(req.body()).unwrap(),
1936            json!({ "conn_id": "main", "pos": "s58_224", "timeout": 30000 })
1937        );
1938    }
1939}