1use 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]
37#[derive(Default)]
38pub struct Request {
39 #[serde(skip_serializing_if = "Option::is_none")]
45 #[ruma_api(query)]
46 pub pos: Option<String>,
47
48 #[serde(skip_serializing_if = "Option::is_none")]
59 pub conn_id: Option<String>,
60
61 #[serde(skip_serializing_if = "Option::is_none")]
64 pub txn_id: Option<String>,
65
66 #[serde(with = "opt_ms", default, skip_serializing_if = "Option::is_none")]
70 #[ruma_api(query)]
71 pub timeout: Option<Duration>,
72
73 #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
77 #[ruma_api(query)]
78 pub set_presence: PresenceState,
79
80 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
82 pub lists: BTreeMap<String, request::List>,
83
84 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
89 pub room_subscriptions: BTreeMap<OwnedRoomId, request::RoomSubscription>,
90
91 #[serde(default, skip_serializing_if = "request::Extensions::is_empty")]
93 pub extensions: request::Extensions,
94}
95
96impl Request {
97 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
131pub 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 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
145 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
146 pub struct List {
147 pub ranges: Vec<(UInt, UInt)>,
149
150 #[serde(flatten)]
152 pub room_details: RoomDetails,
153
154 #[serde(skip_serializing_if = "Option::is_none")]
156 pub filters: Option<ListFilters>,
157 }
158
159 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 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
183 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
184 pub struct ListFilters {
185 #[serde(skip_serializing_if = "Option::is_none")]
188 pub is_dm: Option<bool>,
189
190 #[serde(skip_serializing_if = "Option::is_none")]
193 pub is_encrypted: Option<bool>,
194
195 #[serde(skip_serializing_if = "Option::is_none")]
197 pub is_invite: Option<bool>,
198
199 #[serde(default, skip_serializing_if = "<[_]>::is_empty")]
204 pub room_types: Vec<RoomTypeFilter>,
205
206 #[serde(default, skip_serializing_if = "<[_]>::is_empty")]
211 pub not_room_types: Vec<RoomTypeFilter>,
212 }
213
214 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 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
240 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
241 pub struct RoomSubscription {
242 #[serde(default, skip_serializing_if = "Vec::is_empty")]
245 pub required_state: Vec<(StateEventType, String)>,
246
247 pub timeline_limit: UInt,
249 }
250
251 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 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
284 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
285 pub struct RoomDetails {
286 #[serde(default, skip_serializing_if = "Vec::is_empty")]
288 pub required_state: Vec<(StateEventType, String)>,
289
290 pub timeline_limit: UInt,
292 }
293
294 #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
296 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
297 pub struct Extensions {
298 #[serde(default, skip_serializing_if = "ToDevice::is_disabled")]
300 pub to_device: ToDevice,
301
302 #[serde(default, skip_serializing_if = "E2EE::is_disabled")]
304 pub e2ee: E2EE,
305
306 #[serde(default, skip_serializing_if = "AccountData::is_empty")]
308 pub account_data: AccountData,
309
310 #[serde(default, skip_serializing_if = "Receipts::is_empty")]
312 pub receipts: Receipts,
313
314 #[serde(default, skip_serializing_if = "Typing::is_empty")]
316 pub typing: Typing,
317
318 #[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 #[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 #[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 #[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 #[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 #[serde(flatten)]
365 other: BTreeMap<String, serde_json::Value>,
366 }
367
368 impl Extensions {
369 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 #[derive(Clone, Debug, PartialEq)]
505 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
506 pub enum ExtensionRoomConfig {
507 AllSubscribed,
509
510 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 #[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 #[serde(skip_serializing_if = "Option::is_none")]
547 pub enabled: Option<bool>,
548
549 #[serde(skip_serializing_if = "Option::is_none")]
553 pub limit: Option<UInt>,
554
555 #[serde(skip_serializing_if = "Option::is_none")]
560 pub lists: Option<Vec<String>>,
561
562 #[serde(skip_serializing_if = "Option::is_none")]
568 pub rooms: Option<Vec<ExtensionRoomConfig>>,
569 }
570
571 #[cfg(feature = "unstable-msc4480")]
572 impl StickyEvents {
573 pub fn is_empty(&self) -> bool {
575 self.enabled.is_none()
576 }
577 }
578
579 #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
584 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
585 pub struct AccountData {
586 #[serde(skip_serializing_if = "Option::is_none")]
588 pub enabled: Option<bool>,
589
590 #[serde(skip_serializing_if = "Option::is_none")]
597 pub lists: Option<Vec<String>>,
598
599 #[serde(skip_serializing_if = "Option::is_none")]
607 pub rooms: Option<Vec<ExtensionRoomConfig>>,
608 }
609
610 impl AccountData {
611 pub fn is_empty(&self) -> bool {
613 self.enabled.is_none()
614 }
615 }
616
617 #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
621 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
622 pub struct Receipts {
623 #[serde(skip_serializing_if = "Option::is_none")]
625 pub enabled: Option<bool>,
626
627 #[serde(skip_serializing_if = "Option::is_none")]
632 pub lists: Option<Vec<String>>,
633
634 #[serde(skip_serializing_if = "Option::is_none")]
640 pub rooms: Option<Vec<ExtensionRoomConfig>>,
641 }
642
643 impl Receipts {
644 pub fn is_empty(&self) -> bool {
646 self.enabled.is_none()
647 }
648 }
649
650 #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
655 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
656 pub struct Typing {
657 #[serde(skip_serializing_if = "Option::is_none")]
659 pub enabled: Option<bool>,
660
661 #[serde(skip_serializing_if = "Option::is_none")]
666 pub lists: Option<Vec<String>>,
667
668 #[serde(skip_serializing_if = "Option::is_none")]
674 pub rooms: Option<Vec<ExtensionRoomConfig>>,
675 }
676
677 impl Typing {
678 pub fn is_empty(&self) -> bool {
680 self.enabled.is_none()
681 }
682 }
683
684 #[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 #[serde(skip_serializing_if = "Option::is_none")]
693 pub enabled: Option<bool>,
694
695 #[serde(skip_serializing_if = "Option::is_none")]
700 pub lists: Option<Vec<String>>,
701
702 #[serde(skip_serializing_if = "Option::is_none")]
708 pub rooms: Option<Vec<ExtensionRoomConfig>>,
709
710 #[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 pub fn is_empty(&self) -> bool {
720 self.enabled.is_none()
721 }
722 }
723
724 #[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 #[serde(skip_serializing_if = "Option::is_none")]
733 pub enabled: Option<bool>,
734
735 #[serde(skip_serializing_if = "Option::is_none")]
740 pub lists: Option<Vec<String>>,
741
742 #[serde(skip_serializing_if = "Option::is_none")]
748 pub rooms: Option<Vec<ExtensionRoomConfig>>,
749 }
750
751 #[cfg(feature = "unstable-msc4559")]
752 impl Presence {
753 pub fn is_empty(&self) -> bool {
755 self.enabled.is_none()
756 }
757 }
758}
759
760#[response]
762pub struct Response {
763 #[serde(skip_serializing_if = "Option::is_none")]
765 pub txn_id: Option<String>,
766
767 pub pos: String,
770
771 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
773 pub lists: BTreeMap<String, response::List>,
774
775 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
777 pub rooms: BTreeMap<OwnedRoomId, response::Room>,
778
779 #[serde(default, skip_serializing_if = "response::Extensions::is_empty")]
781 pub extensions: response::Extensions,
782}
783
784impl Response {
785 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
814pub 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 #[derive(Clone, Debug, Default, Deserialize, Serialize)]
843 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
844 pub struct List {
845 pub count: UInt,
847 }
848
849 #[derive(Clone, Debug, Default, Deserialize, Serialize)]
851 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
852 pub struct Room {
853 #[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 #[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 #[serde(skip_serializing_if = "Option::is_none")]
877 pub initial: Option<bool>,
878
879 #[serde(skip_serializing_if = "Option::is_none")]
881 pub is_dm: Option<bool>,
882
883 #[serde(skip_serializing_if = "Option::is_none")]
886 pub invite_state: Option<Vec<Raw<AnyStrippedStateEvent>>>,
887
888 #[serde(flatten, default, skip_serializing_if = "UnreadNotificationsCount::is_empty")]
890 pub unread_notifications: UnreadNotificationsCount,
891
892 #[serde(default, skip_serializing_if = "Vec::is_empty")]
894 pub timeline: Vec<Raw<AnySyncTimelineEvent>>,
895
896 #[serde(default, skip_serializing_if = "Vec::is_empty")]
898 pub required_state: Vec<Raw<AnySyncStateEvent>>,
899
900 #[serde(skip_serializing_if = "Option::is_none")]
903 pub prev_batch: Option<String>,
904
905 #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
908 pub limited: bool,
909
910 #[serde(skip_serializing_if = "Option::is_none")]
913 pub joined_count: Option<UInt>,
914
915 #[serde(skip_serializing_if = "Option::is_none")]
917 pub invited_count: Option<UInt>,
918
919 #[serde(skip_serializing_if = "Option::is_none")]
922 pub num_live: Option<UInt>,
923
924 #[serde(skip_serializing_if = "Option::is_none")]
931 pub bump_stamp: Option<UInt>,
932
933 #[serde(skip_serializing_if = "Option::is_none")]
935 pub heroes: Option<Vec<Hero>>,
936 }
937
938 impl Room {
939 pub fn new() -> Self {
941 Default::default()
942 }
943 }
944
945 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 #[derive(Clone, Debug, Deserialize, Serialize)]
1003 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1004 pub struct Hero {
1005 pub user_id: OwnedUserId,
1007
1008 #[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 #[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 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 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1047 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1048 pub struct Extensions {
1049 #[serde(skip_serializing_if = "Option::is_none")]
1051 pub to_device: Option<ToDevice>,
1052
1053 #[serde(default, skip_serializing_if = "E2EE::is_empty")]
1055 pub e2ee: E2EE,
1056
1057 #[serde(default, skip_serializing_if = "AccountData::is_empty")]
1059 pub account_data: AccountData,
1060
1061 #[serde(default, skip_serializing_if = "Receipts::is_empty")]
1063 pub receipts: Receipts,
1064
1065 #[serde(default, skip_serializing_if = "Typing::is_empty")]
1067 pub typing: Typing,
1068
1069 #[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 #[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 #[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 #[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 #[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 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 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1260 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1261 pub struct ToDevice {
1262 pub next_batch: String,
1264
1265 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1267 pub events: Vec<Raw<AnyToDeviceEvent>>,
1268 }
1269
1270 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1274 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1275 pub struct E2EE {
1276 #[serde(default, skip_serializing_if = "DeviceLists::is_empty")]
1278 pub device_lists: DeviceLists,
1279
1280 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1283 pub device_one_time_keys_count: BTreeMap<OneTimeKeyAlgorithm, UInt>,
1284
1285 #[serde(skip_serializing_if = "Option::is_none")]
1290 pub device_unused_fallback_key_types: Option<Vec<OneTimeKeyAlgorithm>>,
1291 }
1292
1293 impl E2EE {
1294 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 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1306 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1307 pub struct Receipts {
1308 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1310 pub rooms: BTreeMap<OwnedRoomId, Raw<SyncReceiptEvent>>,
1311 }
1312
1313 impl Receipts {
1314 pub fn is_empty(&self) -> bool {
1316 self.rooms.is_empty()
1317 }
1318 }
1319
1320 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
1325 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
1326 pub struct Typing {
1327 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1329 pub rooms: BTreeMap<OwnedRoomId, Raw<SyncTypingEvent>>,
1330 }
1331
1332 impl Typing {
1333 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 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}