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