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
pub mod v3 {
use std::{collections::BTreeMap, time::Duration};
use js_int::UInt;
use ruma_common::{
api::ruma_api,
events::{
presence::PresenceEvent, AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent,
AnyStrippedStateEvent, AnySyncEphemeralRoomEvent, AnySyncRoomEvent, AnySyncStateEvent,
AnyToDeviceEvent,
},
presence::PresenceState,
serde::{Incoming, Raw},
DeviceKeyAlgorithm, OwnedRoomId, OwnedUserId,
};
use serde::{Deserialize, Serialize};
use crate::filter::{FilterDefinition, IncomingFilterDefinition};
ruma_api! {
metadata: {
description: "Get all new events from all rooms since the last sync or a given point of time.",
method: GET,
name: "sync",
r0_path: "/_matrix/client/r0/sync",
stable_path: "/_matrix/client/v3/sync",
rate_limited: false,
authentication: AccessToken,
added: 1.0,
}
#[derive(Default)]
request: {
#[serde(skip_serializing_if = "Option::is_none")]
#[ruma_api(query)]
pub filter: Option<&'a Filter<'a>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ruma_api(query)]
pub since: Option<&'a str>,
#[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
#[ruma_api(query)]
pub full_state: bool,
#[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
#[ruma_api(query)]
pub set_presence: &'a PresenceState,
#[serde(
with = "ruma_common::serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none",
)]
#[ruma_api(query)]
pub timeout: Option<Duration>,
}
response: {
pub next_batch: String,
#[serde(default, skip_serializing_if = "Rooms::is_empty")]
pub rooms: Rooms,
#[serde(default, skip_serializing_if = "Presence::is_empty")]
pub presence: Presence,
#[serde(default, skip_serializing_if = "GlobalAccountData::is_empty")]
pub account_data: GlobalAccountData,
#[serde(default, skip_serializing_if = "ToDevice::is_empty")]
pub to_device: ToDevice,
#[serde(default, skip_serializing_if = "DeviceLists::is_empty")]
pub device_lists: DeviceLists,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub device_one_time_keys_count: BTreeMap<DeviceKeyAlgorithm, UInt>,
pub device_unused_fallback_key_types: Option<Vec<DeviceKeyAlgorithm>>,
}
error: crate::Error
}
impl Request<'_> {
pub fn new() -> Self {
Default::default()
}
}
impl Response {
pub fn new(next_batch: String) -> Self {
Self {
next_batch,
rooms: Default::default(),
presence: Default::default(),
account_data: Default::default(),
to_device: Default::default(),
device_lists: Default::default(),
device_one_time_keys_count: BTreeMap::new(),
device_unused_fallback_key_types: None,
}
}
}
#[derive(Clone, Debug, Incoming, Serialize)]
#[allow(clippy::large_enum_variant)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[serde(untagged)]
pub enum Filter<'a> {
#[serde(with = "ruma_common::serde::json_string")]
FilterDefinition(FilterDefinition<'a>),
FilterId(&'a str),
}
impl<'a> From<FilterDefinition<'a>> for Filter<'a> {
fn from(def: FilterDefinition<'a>) -> Self {
Self::FilterDefinition(def)
}
}
impl<'a> From<&'a str> for Filter<'a> {
fn from(id: &'a str) -> Self {
Self::FilterId(id)
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Rooms {
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub leave: BTreeMap<OwnedRoomId, LeftRoom>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub join: BTreeMap<OwnedRoomId, JoinedRoom>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub invite: BTreeMap<OwnedRoomId, InvitedRoom>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub knock: BTreeMap<OwnedRoomId, KnockedRoom>,
}
impl Rooms {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.leave.is_empty() && self.join.is_empty() && self.invite.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct LeftRoom {
#[serde(default, skip_serializing_if = "Timeline::is_empty")]
pub timeline: Timeline,
#[serde(default, skip_serializing_if = "State::is_empty")]
pub state: State,
#[serde(default, skip_serializing_if = "RoomAccountData::is_empty")]
pub account_data: RoomAccountData,
}
impl LeftRoom {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.timeline.is_empty() && self.state.is_empty() && self.account_data.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct JoinedRoom {
#[serde(default, skip_serializing_if = "RoomSummary::is_empty")]
pub summary: RoomSummary,
#[serde(default, skip_serializing_if = "UnreadNotificationsCount::is_empty")]
pub unread_notifications: UnreadNotificationsCount,
#[serde(default, skip_serializing_if = "Timeline::is_empty")]
pub timeline: Timeline,
#[serde(default, skip_serializing_if = "State::is_empty")]
pub state: State,
#[serde(default, skip_serializing_if = "RoomAccountData::is_empty")]
pub account_data: RoomAccountData,
#[serde(default, skip_serializing_if = "Ephemeral::is_empty")]
pub ephemeral: Ephemeral,
#[cfg(feature = "unstable-msc2654")]
#[serde(
rename = "org.matrix.msc2654.unread_count",
alias = "unread_count",
skip_serializing_if = "Option::is_none"
)]
pub unread_count: Option<UInt>,
}
impl JoinedRoom {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
let is_empty = self.summary.is_empty()
&& self.unread_notifications.is_empty()
&& self.timeline.is_empty()
&& self.state.is_empty()
&& self.account_data.is_empty()
&& self.ephemeral.is_empty();
#[cfg(not(feature = "unstable-msc2654"))]
return is_empty;
#[cfg(feature = "unstable-msc2654")]
return is_empty && self.unread_count.is_none();
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct KnockedRoom {
pub knock_state: KnockState,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct KnockState {
pub events: Vec<Raw<AnyStrippedStateEvent>>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct UnreadNotificationsCount {
#[serde(skip_serializing_if = "Option::is_none")]
pub highlight_count: Option<UInt>,
#[serde(skip_serializing_if = "Option::is_none")]
pub notification_count: Option<UInt>,
}
impl UnreadNotificationsCount {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.highlight_count.is_none() && self.notification_count.is_none()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Timeline {
#[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
pub limited: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub prev_batch: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Raw<AnySyncRoomEvent>>,
}
impl Timeline {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct State {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Raw<AnySyncStateEvent>>,
}
impl State {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct GlobalAccountData {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Raw<AnyGlobalAccountDataEvent>>,
}
impl GlobalAccountData {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct RoomAccountData {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Raw<AnyRoomAccountDataEvent>>,
}
impl RoomAccountData {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Ephemeral {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Raw<AnySyncEphemeralRoomEvent>>,
}
impl Ephemeral {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct RoomSummary {
#[serde(rename = "m.heroes", default, skip_serializing_if = "Vec::is_empty")]
pub heroes: Vec<String>,
#[serde(rename = "m.joined_member_count", skip_serializing_if = "Option::is_none")]
pub joined_member_count: Option<UInt>,
#[serde(rename = "m.invited_member_count", skip_serializing_if = "Option::is_none")]
pub invited_member_count: Option<UInt>,
}
impl RoomSummary {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.heroes.is_empty()
&& self.joined_member_count.is_none()
&& self.invited_member_count.is_none()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct InvitedRoom {
#[serde(default, skip_serializing_if = "InviteState::is_empty")]
pub invite_state: InviteState,
}
impl InvitedRoom {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.invite_state.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct InviteState {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Raw<AnyStrippedStateEvent>>,
}
impl InviteState {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Presence {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Raw<PresenceEvent>>,
}
impl Presence {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct ToDevice {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Raw<AnyToDeviceEvent>>,
}
impl ToDevice {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct DeviceLists {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub changed: Vec<OwnedUserId>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub left: Vec<OwnedUserId>,
}
impl DeviceLists {
pub fn new() -> Self {
Default::default()
}
pub fn is_empty(&self) -> bool {
self.changed.is_empty() && self.left.is_empty()
}
}
#[cfg(test)]
mod tests {
use assign::assign;
use matches::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::Timeline;
#[test]
fn timeline_serde() {
let timeline = assign!(Timeline::new(), { limited: true });
let timeline_serialized = json!({ "limited": true });
assert_eq!(to_json_value(timeline).unwrap(), timeline_serialized);
let timeline_deserialized = from_json_value(timeline_serialized);
assert_matches!(timeline_deserialized, Ok(Timeline { limited: true, .. }));
let timeline_default = Timeline::default();
assert_eq!(to_json_value(timeline_default).unwrap(), json!({}));
let timeline_default_deserialized = from_json_value(json!({}));
assert_matches!(timeline_default_deserialized, Ok(Timeline { limited: false, .. }));
}
}
#[cfg(all(test, feature = "client"))]
mod client_tests {
use std::time::Duration;
use ruma_common::api::{MatrixVersion, OutgoingRequest as _, SendAccessToken};
use super::{Filter, PresenceState, Request};
#[test]
fn serialize_all_params() {
let req: http::Request<Vec<u8>> = Request {
filter: Some(&Filter::FilterId("66696p746572")),
since: Some("s72594_4483_1934"),
full_state: true,
set_presence: &PresenceState::Offline,
timeout: Some(Duration::from_millis(30000)),
}
.try_into_http_request(
"https://homeserver.tld",
SendAccessToken::IfRequired("auth_tok"),
&[MatrixVersion::V1_1],
)
.unwrap();
let uri = req.uri();
let query = uri.query().unwrap();
assert_eq!(uri.path(), "/_matrix/client/v3/sync");
assert!(query.contains("filter=66696p746572"));
assert!(query.contains("since=s72594_4483_1934"));
assert!(query.contains("full_state=true"));
assert!(query.contains("set_presence=offline"));
assert!(query.contains("timeout=30000"))
}
}
#[cfg(all(test, feature = "server"))]
mod server_tests {
use std::time::Duration;
use matches::assert_matches;
use ruma_common::{api::IncomingRequest as _, presence::PresenceState};
use super::{IncomingFilter, IncomingRequest};
#[test]
fn deserialize_all_query_params() {
let uri = http::Uri::builder()
.scheme("https")
.authority("matrix.org")
.path_and_query(
"/_matrix/client/r0/sync\
?filter=myfilter\
&since=myts\
&full_state=false\
&set_presence=offline\
&timeout=5000",
)
.build()
.unwrap();
let req = IncomingRequest::try_from_http_request(
http::Request::builder().uri(uri).body(&[] as &[u8]).unwrap(),
&[] as &[String],
)
.unwrap();
assert_matches!(req.filter, Some(IncomingFilter::FilterId(id)) if id == "myfilter");
assert_eq!(req.since, Some("myts".into()));
assert!(!req.full_state);
assert_eq!(req.set_presence, PresenceState::Offline);
assert_eq!(req.timeout, Some(Duration::from_millis(5000)));
}
#[test]
fn deserialize_no_query_params() {
let uri = http::Uri::builder()
.scheme("https")
.authority("matrix.org")
.path_and_query("/_matrix/client/r0/sync")
.build()
.unwrap();
let req = IncomingRequest::try_from_http_request(
http::Request::builder().uri(uri).body(&[] as &[u8]).unwrap(),
&[] as &[String],
)
.unwrap();
assert_matches!(req.filter, None);
assert_eq!(req.since, None);
assert!(!req.full_state);
assert_eq!(req.set_presence, PresenceState::Online);
assert_eq!(req.timeout, None);
}
#[test]
fn deserialize_some_query_params() {
let uri = http::Uri::builder()
.scheme("https")
.authority("matrix.org")
.path_and_query(
"/_matrix/client/r0/sync\
?filter=EOKFFmdZYF\
&timeout=0",
)
.build()
.unwrap();
let req = IncomingRequest::try_from_http_request(
http::Request::builder().uri(uri).body(&[] as &[u8]).unwrap(),
&[] as &[String],
)
.unwrap();
assert_matches!(req.filter, Some(IncomingFilter::FilterId(id)) if id == "EOKFFmdZYF");
assert_eq!(req.since, None);
assert!(!req.full_state);
assert_eq!(req.set_presence, PresenceState::Online);
assert_eq!(req.timeout, Some(Duration::from_millis(0)));
}
}
}