-
Notifications
You must be signed in to change notification settings - Fork 253
/
client.rs
2052 lines (1814 loc) · 79.2 KB
/
client.rs
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
// Copyright 2020 Damir Jelić
// Copyright 2020 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(feature = "e2e-encryption")]
use std::ops::Deref;
use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
fmt, iter,
sync::Arc,
};
use eyeball::{SharedObservable, Subscriber};
#[cfg(not(target_arch = "wasm32"))]
use eyeball_im::{Vector, VectorDiff};
#[cfg(not(target_arch = "wasm32"))]
use futures_util::Stream;
#[cfg(feature = "e2e-encryption")]
use matrix_sdk_crypto::{
store::DynCryptoStore, CollectStrategy, DecryptionSettings, EncryptionSettings,
EncryptionSyncChanges, OlmError, OlmMachine, ToDeviceRequest, TrustRequirement,
};
#[cfg(feature = "e2e-encryption")]
use ruma::events::{
room::{history_visibility::HistoryVisibility, message::MessageType},
SyncMessageLikeEvent,
};
#[cfg(doc)]
use ruma::DeviceId;
use ruma::{
api::client as api,
events::{
ignored_user_list::IgnoredUserListEvent,
push_rules::{PushRulesEvent, PushRulesEventContent},
room::{
member::{MembershipState, RoomMemberEventContent, SyncRoomMemberEvent},
power_levels::{
RoomPowerLevelsEvent, RoomPowerLevelsEventContent, StrippedRoomPowerLevelsEvent,
},
},
AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnyStrippedStateEvent,
AnySyncEphemeralRoomEvent, AnySyncMessageLikeEvent, AnySyncStateEvent,
AnySyncTimelineEvent, GlobalAccountDataEventType, StateEvent, StateEventType,
SyncStateEvent,
},
push::{Action, PushConditionRoomCtx, Ruleset},
serde::Raw,
time::Instant,
OwnedRoomId, OwnedUserId, RoomId, RoomVersionId, UInt, UserId,
};
use tokio::sync::{broadcast, Mutex};
#[cfg(feature = "e2e-encryption")]
use tokio::sync::{RwLock, RwLockReadGuard};
use tracing::{debug, info, instrument, trace, warn};
#[cfg(all(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]
use crate::latest_event::{is_suitable_for_latest_event, LatestEvent, PossibleLatestEvent};
#[cfg(feature = "e2e-encryption")]
use crate::RoomMemberships;
use crate::{
deserialized_responses::{RawAnySyncOrStrippedTimelineEvent, SyncTimelineEvent},
error::{Error, Result},
event_cache_store::DynEventCacheStore,
rooms::{
normal::{RoomInfoNotableUpdate, RoomInfoNotableUpdateReasons},
Room, RoomInfo, RoomState,
},
store::{
ambiguity_map::AmbiguityCache, DynStateStore, MemoryStore, Result as StoreResult,
StateChanges, StateStoreDataKey, StateStoreDataValue, StateStoreExt, Store, StoreConfig,
},
sync::{JoinedRoomUpdate, LeftRoomUpdate, Notification, RoomUpdates, SyncResponse, Timeline},
RoomStateFilter, SessionMeta,
};
/// A no IO Client implementation.
///
/// This Client is a state machine that receives responses and events and
/// accordingly updates its state.
#[derive(Clone)]
pub struct BaseClient {
/// Database
pub(crate) store: Store,
/// The store used by the event cache.
event_cache_store: Arc<DynEventCacheStore>,
/// The store used for encryption.
///
/// This field is only meant to be used for `OlmMachine` initialization.
/// All operations on it happen inside the `OlmMachine`.
#[cfg(feature = "e2e-encryption")]
crypto_store: Arc<DynCryptoStore>,
/// The olm-machine that is created once the
/// [`SessionMeta`][crate::session::SessionMeta] is set via
/// [`BaseClient::set_session_meta`]
#[cfg(feature = "e2e-encryption")]
olm_machine: Arc<RwLock<Option<OlmMachine>>>,
/// Observable of when a user is ignored/unignored.
pub(crate) ignore_user_list_changes: SharedObservable<Vec<String>>,
/// A sender that is used to communicate changes to room information. Each
/// event contains the room and a boolean whether this event should
/// trigger a room list update.
pub(crate) room_info_notable_update_sender: broadcast::Sender<RoomInfoNotableUpdate>,
/// The strategy to use for picking recipient devices, when sending an
/// encrypted message.
#[cfg(feature = "e2e-encryption")]
pub room_key_recipient_strategy: CollectStrategy,
}
#[cfg(not(tarpaulin_include))]
impl fmt::Debug for BaseClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client")
.field("session_meta", &self.store.session_meta())
.field("sync_token", &self.store.sync_token)
.finish_non_exhaustive()
}
}
impl BaseClient {
/// Create a new default client.
pub fn new() -> Self {
BaseClient::with_store_config(StoreConfig::default())
}
/// Create a new client.
///
/// # Arguments
///
/// * `config` - An optional session if the user already has one from a
/// previous login call.
pub fn with_store_config(config: StoreConfig) -> Self {
let (room_info_notable_update_sender, _room_info_notable_update_receiver) =
broadcast::channel(100);
BaseClient {
store: Store::new(config.state_store),
event_cache_store: config.event_cache_store,
#[cfg(feature = "e2e-encryption")]
crypto_store: config.crypto_store,
#[cfg(feature = "e2e-encryption")]
olm_machine: Default::default(),
ignore_user_list_changes: Default::default(),
room_info_notable_update_sender,
#[cfg(feature = "e2e-encryption")]
room_key_recipient_strategy: Default::default(),
}
}
/// Clones the current base client to use the same crypto store but a
/// different, in-memory store config, and resets transient state.
#[cfg(feature = "e2e-encryption")]
pub fn clone_with_in_memory_state_store(&self) -> Self {
let config = StoreConfig::new().state_store(MemoryStore::new());
let config = config.crypto_store(self.crypto_store.clone());
let mut result = Self::with_store_config(config);
result.room_key_recipient_strategy = self.room_key_recipient_strategy.clone();
result
}
/// Clones the current base client to use the same crypto store but a
/// different, in-memory store config, and resets transient state.
#[cfg(not(feature = "e2e-encryption"))]
pub fn clone_with_in_memory_state_store(&self) -> Self {
let config = StoreConfig::new().state_store(MemoryStore::new());
Self::with_store_config(config)
}
/// Get the session meta information.
///
/// If the client is currently logged in, this will return a
/// [`SessionMeta`] object which contains the user ID and device ID.
/// Otherwise it returns `None`.
pub fn session_meta(&self) -> Option<&SessionMeta> {
self.store.session_meta()
}
/// Get all the rooms this client knows about.
pub fn rooms(&self) -> Vec<Room> {
self.store.rooms()
}
/// Get all the rooms this client knows about, filtered by room state.
pub fn rooms_filtered(&self, filter: RoomStateFilter) -> Vec<Room> {
self.store.rooms_filtered(filter)
}
/// Get a stream of all the rooms changes, in addition to the existing
/// rooms.
#[cfg(not(target_arch = "wasm32"))]
pub fn rooms_stream(&self) -> (Vector<Room>, impl Stream<Item = Vec<VectorDiff<Room>>>) {
self.store.rooms_stream()
}
/// Lookup the Room for the given RoomId, or create one, if it didn't exist
/// yet in the store
pub fn get_or_create_room(&self, room_id: &RoomId, room_state: RoomState) -> Room {
self.store.get_or_create_room(
room_id,
room_state,
self.room_info_notable_update_sender.clone(),
)
}
/// Get a reference to the store.
#[allow(unknown_lints, clippy::explicit_auto_deref)]
pub fn store(&self) -> &DynStateStore {
&*self.store
}
/// Get a reference to the event cache store.
pub fn event_cache_store(&self) -> &DynEventCacheStore {
&*self.event_cache_store
}
/// Is the client logged in.
pub fn logged_in(&self) -> bool {
self.store.session_meta().is_some()
}
/// Set the meta of the session.
///
/// If encryption is enabled, this also initializes or restores the
/// `OlmMachine`.
///
/// # Arguments
///
/// * `session_meta` - The meta of a session that the user already has from
/// a previous login call.
///
/// * `custom_account` - A custom
/// [`matrix_sdk_crypto::vodozemac::olm::Account`] to be used for the
/// identity and one-time keys of this [`BaseClient`]. If no account is
/// provided, a new default one or one from the store will be used. If an
/// account is provided and one already exists in the store for this
/// [`UserId`]/[`DeviceId`] combination, an error will be raised. This is
/// useful if one wishes to create identity keys before knowing the
/// user/device IDs, e.g., to use the identity key as the device ID.
///
/// This method panics if it is called twice.
pub async fn set_session_meta(
&self,
session_meta: SessionMeta,
#[cfg(feature = "e2e-encryption")] custom_account: Option<
crate::crypto::vodozemac::olm::Account,
>,
) -> Result<()> {
debug!(user_id = ?session_meta.user_id, device_id = ?session_meta.device_id, "Restoring login");
self.store
.set_session_meta(session_meta.clone(), &self.room_info_notable_update_sender)
.await?;
#[cfg(feature = "e2e-encryption")]
self.regenerate_olm(custom_account).await?;
Ok(())
}
/// Recreate an `OlmMachine` from scratch.
///
/// In particular, this will clear all its caches.
#[cfg(feature = "e2e-encryption")]
pub async fn regenerate_olm(
&self,
custom_account: Option<crate::crypto::vodozemac::olm::Account>,
) -> Result<()> {
tracing::debug!("regenerating OlmMachine");
let session_meta = self.session_meta().ok_or(Error::OlmError(OlmError::MissingSession))?;
// Recreate the `OlmMachine` and wipe the in-memory cache in the store
// because we suspect it has stale data.
let olm_machine = OlmMachine::with_store(
&session_meta.user_id,
&session_meta.device_id,
self.crypto_store.clone(),
custom_account,
)
.await
.map_err(OlmError::from)?;
*self.olm_machine.write().await = Some(olm_machine);
Ok(())
}
/// Get the current, if any, sync token of the client.
/// This will be None if the client didn't sync at least once.
pub async fn sync_token(&self) -> Option<String> {
self.store.sync_token.read().await.clone()
}
#[cfg(feature = "e2e-encryption")]
async fn handle_verification_event(
&self,
event: &AnySyncMessageLikeEvent,
room_id: &RoomId,
) -> Result<()> {
if let Some(olm) = self.olm_machine().await.as_ref() {
olm.receive_verification_event(&event.clone().into_full_event(room_id.to_owned()))
.await?;
}
Ok(())
}
#[cfg(feature = "e2e-encryption")]
async fn decrypt_sync_room_event(
&self,
event: &Raw<AnySyncTimelineEvent>,
room_id: &RoomId,
) -> Result<Option<SyncTimelineEvent>> {
let olm = self.olm_machine().await;
let Some(olm) = olm.as_ref() else { return Ok(None) };
let decryption_settings =
DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted };
let event: SyncTimelineEvent =
olm.decrypt_room_event(event.cast_ref(), room_id, &decryption_settings).await?.into();
if let Ok(AnySyncTimelineEvent::MessageLike(e)) = event.event.deserialize() {
match &e {
AnySyncMessageLikeEvent::RoomMessage(SyncMessageLikeEvent::Original(
original_event,
)) => {
if let MessageType::VerificationRequest(_) = &original_event.content.msgtype {
self.handle_verification_event(&e, room_id).await?;
}
}
_ if e.event_type().to_string().starts_with("m.key.verification") => {
self.handle_verification_event(&e, room_id).await?;
}
_ => (),
}
}
Ok(Some(event))
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all, fields(room_id = ?room_info.room_id))]
pub(crate) async fn handle_timeline(
&self,
room: &Room,
limited: bool,
events: Vec<Raw<AnySyncTimelineEvent>>,
prev_batch: Option<String>,
push_rules: &Ruleset,
user_ids: &mut BTreeSet<OwnedUserId>,
room_info: &mut RoomInfo,
changes: &mut StateChanges,
notifications: &mut BTreeMap<OwnedRoomId, Vec<Notification>>,
ambiguity_cache: &mut AmbiguityCache,
) -> Result<Timeline> {
let mut timeline = Timeline::new(limited, prev_batch);
let mut push_context = self.get_push_room_context(room, room_info, changes).await?;
for event in events {
let mut event: SyncTimelineEvent = event.into();
match event.event.deserialize() {
Ok(e) => {
#[allow(clippy::single_match)]
match &e {
AnySyncTimelineEvent::State(s) => {
match s {
AnySyncStateEvent::RoomMember(member) => {
Box::pin(ambiguity_cache.handle_event(
changes,
room.room_id(),
member,
))
.await?;
match member.membership() {
MembershipState::Join | MembershipState::Invite => {
user_ids.insert(member.state_key().to_owned());
}
_ => {
user_ids.remove(member.state_key());
}
}
handle_room_member_event_for_profiles(
room.room_id(),
member,
changes,
);
}
_ => {
room_info.handle_state_event(s);
}
}
let raw_event: Raw<AnySyncStateEvent> = event.event.clone().cast();
changes.add_state_event(room.room_id(), s.clone(), raw_event);
}
AnySyncTimelineEvent::MessageLike(
AnySyncMessageLikeEvent::RoomRedaction(r),
) => {
let room_version =
room_info.room_version().unwrap_or(&RoomVersionId::V1);
if let Some(redacts) = r.redacts(room_version) {
room_info.handle_redaction(r, event.event.cast_ref());
let raw_event = event.event.clone().cast();
changes.add_redaction(room.room_id(), redacts, raw_event);
}
}
#[cfg(feature = "e2e-encryption")]
AnySyncTimelineEvent::MessageLike(e) => match e {
AnySyncMessageLikeEvent::RoomEncrypted(
SyncMessageLikeEvent::Original(_),
) => {
if let Ok(Some(e)) = Box::pin(
self.decrypt_sync_room_event(&event.event, room.room_id()),
)
.await
{
event = e;
}
}
AnySyncMessageLikeEvent::RoomMessage(
SyncMessageLikeEvent::Original(original_event),
) => match &original_event.content.msgtype {
MessageType::VerificationRequest(_) => {
Box::pin(self.handle_verification_event(e, room.room_id()))
.await?;
}
_ => (),
},
_ if e.event_type().to_string().starts_with("m.key.verification") => {
Box::pin(self.handle_verification_event(e, room.room_id())).await?;
}
_ => (),
},
#[cfg(not(feature = "e2e-encryption"))]
AnySyncTimelineEvent::MessageLike(_) => (),
}
if let Some(context) = &mut push_context {
self.update_push_room_context(
context,
room.own_user_id(),
room_info,
changes,
)
} else {
push_context = self.get_push_room_context(room, room_info, changes).await?;
}
if let Some(context) = &push_context {
let actions = push_rules.get_actions(&event.event, context);
if actions.iter().any(Action::should_notify) {
notifications.entry(room.room_id().to_owned()).or_default().push(
Notification {
actions: actions.to_owned(),
event: RawAnySyncOrStrippedTimelineEvent::Sync(
event.event.clone(),
),
},
);
}
event.push_actions = actions.to_owned();
}
}
Err(e) => {
warn!("Error deserializing event: {e}");
}
}
timeline.events.push(event);
}
Ok(timeline)
}
#[instrument(skip_all, fields(room_id = ?room_info.room_id))]
pub(crate) async fn handle_invited_state(
&self,
room: &Room,
events: &[Raw<AnyStrippedStateEvent>],
push_rules: &Ruleset,
room_info: &mut RoomInfo,
changes: &mut StateChanges,
notifications: &mut BTreeMap<OwnedRoomId, Vec<Notification>>,
) -> Result<()> {
let mut state_events = BTreeMap::new();
for raw_event in events {
match raw_event.deserialize() {
Ok(e) => {
room_info.handle_stripped_state_event(&e);
state_events
.entry(e.event_type())
.or_insert_with(BTreeMap::new)
.insert(e.state_key().to_owned(), raw_event.clone());
}
Err(err) => {
warn!(
room_id = ?room_info.room_id,
"Couldn't deserialize stripped state event: {err:?}",
);
}
}
}
changes.stripped_state.insert(room_info.room_id().to_owned(), state_events.clone());
// We need to check for notifications after we have handled all state
// events, to make sure we have the full push context.
if let Some(push_context) = self.get_push_room_context(room, room_info, changes).await? {
// Check every event again for notification.
for event in state_events.values().flat_map(|map| map.values()) {
let actions = push_rules.get_actions(event, &push_context);
if actions.iter().any(Action::should_notify) {
notifications.entry(room.room_id().to_owned()).or_default().push(
Notification {
actions: actions.to_owned(),
event: RawAnySyncOrStrippedTimelineEvent::Stripped(event.clone()),
},
);
}
}
}
Ok(())
}
/// Process the events provided during a sync.
///
/// events must be exactly the same list of events that are in raw_events,
/// but deserialised. We demand them here to avoid deserialising
/// multiple times.
#[instrument(skip_all, fields(room_id = ?room_info.room_id))]
pub(crate) async fn handle_state(
&self,
raw_events: &[Raw<AnySyncStateEvent>],
events: &[AnySyncStateEvent],
room_info: &mut RoomInfo,
changes: &mut StateChanges,
ambiguity_cache: &mut AmbiguityCache,
) -> StoreResult<BTreeSet<OwnedUserId>> {
let mut state_events = BTreeMap::new();
let mut user_ids = BTreeSet::new();
assert_eq!(raw_events.len(), events.len());
for (raw_event, event) in iter::zip(raw_events, events) {
room_info.handle_state_event(event);
if let AnySyncStateEvent::RoomMember(member) = &event {
ambiguity_cache.handle_event(changes, &room_info.room_id, member).await?;
match member.membership() {
MembershipState::Join | MembershipState::Invite => {
user_ids.insert(member.state_key().to_owned());
}
_ => (),
}
handle_room_member_event_for_profiles(&room_info.room_id, member, changes);
}
state_events
.entry(event.event_type())
.or_insert_with(BTreeMap::new)
.insert(event.state_key().to_owned(), raw_event.clone());
}
changes.state.insert((*room_info.room_id).to_owned(), state_events);
Ok(user_ids)
}
#[instrument(skip_all, fields(?room_id))]
pub(crate) async fn handle_room_account_data(
&self,
room_id: &RoomId,
events: &[Raw<AnyRoomAccountDataEvent>],
changes: &mut StateChanges,
room_info_notable_updates: &mut BTreeMap<OwnedRoomId, RoomInfoNotableUpdateReasons>,
) {
// Small helper to make the code easier to read.
//
// It finds the appropriate `RoomInfo`, allowing the caller to modify it, and
// save it in the correct place.
fn on_room_info<F>(
room_id: &RoomId,
changes: &mut StateChanges,
client: &BaseClient,
mut on_room_info: F,
) where
F: FnMut(&mut RoomInfo),
{
// `StateChanges` has the `RoomInfo`.
if let Some(room_info) = changes.room_infos.get_mut(room_id) {
// Show time.
on_room_info(room_info);
}
// The `BaseClient` has the `Room`, which has the `RoomInfo`.
else if let Some(room) = client.store.room(room_id) {
// Clone the `RoomInfo`.
let mut room_info = room.clone_info();
// Show time.
on_room_info(&mut room_info);
// Update the `RoomInfo` via `StateChanges`.
changes.add_room(room_info);
}
}
// Handle new events.
for raw_event in events {
match raw_event.deserialize() {
Ok(event) => {
changes.add_room_account_data(room_id, event.clone(), raw_event.clone());
match event {
AnyRoomAccountDataEvent::MarkedUnread(event) => {
on_room_info(room_id, changes, self, |room_info| {
if room_info.base_info.is_marked_unread != event.content.unread {
// Notify the room list about a manual read marker change if the
// value's changed.
room_info_notable_updates
.entry(room_id.to_owned())
.or_default()
.insert(RoomInfoNotableUpdateReasons::UNREAD_MARKER);
}
room_info.base_info.is_marked_unread = event.content.unread;
});
}
AnyRoomAccountDataEvent::Tag(event) => {
on_room_info(room_id, changes, self, |room_info| {
room_info.base_info.handle_notable_tags(&event.content.tags);
});
}
// Nothing.
_ => {}
}
}
Err(err) => {
warn!("unable to deserialize account data event: {err}");
}
}
}
}
#[instrument(skip_all)]
pub(crate) async fn handle_account_data(
&self,
events: &[Raw<AnyGlobalAccountDataEvent>],
changes: &mut StateChanges,
) {
let mut account_data = BTreeMap::new();
for raw_event in events {
let event = match raw_event.deserialize() {
Ok(e) => e,
Err(e) => {
let event_type: Option<String> = raw_event.get_field("type").ok().flatten();
warn!(event_type, "Failed to deserialize a global account data event: {e}");
continue;
}
};
if let AnyGlobalAccountDataEvent::Direct(e) = &event {
let mut new_dms = HashMap::<&RoomId, HashSet<OwnedUserId>>::new();
for (user_id, rooms) in e.content.iter() {
for room_id in rooms {
new_dms.entry(room_id).or_default().insert(user_id.clone());
}
}
let rooms = self.store.rooms();
let mut old_dms = rooms
.iter()
.filter_map(|r| {
let direct_targets = r.direct_targets();
(!direct_targets.is_empty()).then(|| (r.room_id(), direct_targets))
})
.collect::<HashMap<_, _>>();
// Update the direct targets of rooms if they changed.
for (room_id, new_direct_targets) in new_dms {
if let Some(old_direct_targets) = old_dms.remove(&room_id) {
if old_direct_targets == new_direct_targets {
continue;
}
}
trace!(
?room_id, targets = ?new_direct_targets,
"Marking room as direct room"
);
if let Some(info) = changes.room_infos.get_mut(room_id) {
info.base_info.dm_targets = new_direct_targets;
} else if let Some(room) = self.store.room(room_id) {
let mut info = room.clone_info();
info.base_info.dm_targets = new_direct_targets;
changes.add_room(info);
}
}
// Remove the targets of old direct chats.
for room_id in old_dms.keys() {
trace!(?room_id, "Unmarking room as direct room");
if let Some(info) = changes.room_infos.get_mut(*room_id) {
info.base_info.dm_targets.clear();
} else if let Some(room) = self.store.room(room_id) {
let mut info = room.clone_info();
info.base_info.dm_targets.clear();
changes.add_room(info);
}
}
}
account_data.insert(event.event_type(), raw_event.clone());
}
changes.account_data = account_data;
}
#[cfg(feature = "e2e-encryption")]
#[instrument(skip_all)]
pub(crate) async fn preprocess_to_device_events(
&self,
encryption_sync_changes: EncryptionSyncChanges<'_>,
#[cfg(feature = "experimental-sliding-sync")] changes: &mut StateChanges,
#[cfg(not(feature = "experimental-sliding-sync"))] _changes: &mut StateChanges,
#[cfg(feature = "experimental-sliding-sync")] room_info_notable_updates: &mut BTreeMap<
OwnedRoomId,
RoomInfoNotableUpdateReasons,
>,
#[cfg(not(feature = "experimental-sliding-sync"))]
_room_info_notable_updates: &mut BTreeMap<
OwnedRoomId,
RoomInfoNotableUpdateReasons,
>,
) -> Result<Vec<Raw<ruma::events::AnyToDeviceEvent>>> {
if let Some(o) = self.olm_machine().await.as_ref() {
// Let the crypto machine handle the sync response, this
// decrypts to-device events, but leaves room events alone.
// This makes sure that we have the decryption keys for the room
// events at hand.
let (events, room_key_updates) =
o.receive_sync_changes(encryption_sync_changes).await?;
#[cfg(feature = "experimental-sliding-sync")]
for room_key_update in room_key_updates {
if let Some(room) = self.get_room(&room_key_update.room_id) {
self.decrypt_latest_events(&room, changes, room_info_notable_updates).await;
}
}
#[cfg(not(feature = "experimental-sliding-sync"))]
drop(room_key_updates); // Silence unused variable warning
Ok(events)
} else {
// If we have no OlmMachine, just return the events that were passed in.
// This should not happen unless we forget to set things up by calling
// set_session_meta().
Ok(encryption_sync_changes.to_device_events)
}
}
/// Decrypt any of this room's latest_encrypted_events
/// that we can and if we can, change latest_event to reflect what we
/// found, and remove any older encrypted events from
/// latest_encrypted_events.
#[cfg(all(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]
async fn decrypt_latest_events(
&self,
room: &Room,
changes: &mut StateChanges,
room_info_notable_updates: &mut BTreeMap<OwnedRoomId, RoomInfoNotableUpdateReasons>,
) {
// Try to find a message we can decrypt and is suitable for using as the latest
// event. If we found one, set it as the latest and delete any older
// encrypted events
if let Some((found, found_index)) = self.decrypt_latest_suitable_event(room).await {
room.on_latest_event_decrypted(found, found_index, changes, room_info_notable_updates);
}
}
/// Attempt to decrypt a latest event, trying the latest stored encrypted
/// one first, and walking backwards, stopping when we find an event
/// that we can decrypt, and that is suitable to be the latest event
/// (i.e. we can usefully display it as a message preview). Returns the
/// decrypted event if we found one, along with its index in the
/// latest_encrypted_events list, or None if we didn't find one.
#[cfg(all(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]
async fn decrypt_latest_suitable_event(
&self,
room: &Room,
) -> Option<(Box<LatestEvent>, usize)> {
let enc_events = room.latest_encrypted_events();
// Walk backwards through the encrypted events, looking for one we can decrypt
for (i, event) in enc_events.iter().enumerate().rev() {
// Size of the decrypt_sync_room_event future should not impact this
// async fn since it is likely that there aren't even any encrypted
// events when calling it.
let decrypt_sync_room_event =
Box::pin(self.decrypt_sync_room_event(event, room.room_id()));
if let Ok(Some(decrypted)) = decrypt_sync_room_event.await {
// We found an event we can decrypt
if let Ok(any_sync_event) = decrypted.event.deserialize() {
// We can deserialize it to find its type
match is_suitable_for_latest_event(&any_sync_event) {
PossibleLatestEvent::YesRoomMessage(_)
| PossibleLatestEvent::YesPoll(_)
| PossibleLatestEvent::YesCallInvite(_)
| PossibleLatestEvent::YesCallNotify(_)
| PossibleLatestEvent::YesSticker(_) => {
// The event is the right type for us to use as latest_event
return Some((Box::new(LatestEvent::new(decrypted)), i));
}
_ => (),
}
}
}
}
None
}
/// User has joined a room.
///
/// Update the internal and cached state accordingly. Return the final Room.
pub async fn room_joined(&self, room_id: &RoomId) -> Result<Room> {
let room = self.store.get_or_create_room(
room_id,
RoomState::Joined,
self.room_info_notable_update_sender.clone(),
);
if room.state() != RoomState::Joined {
let _sync_lock = self.sync_lock().lock().await;
let mut room_info = room.clone_info();
room_info.mark_as_joined();
room_info.mark_state_partially_synced();
room_info.mark_members_missing(); // the own member event changed
let mut changes = StateChanges::default();
changes.add_room(room_info.clone());
self.store.save_changes(&changes).await?; // Update the store
room.set_room_info(room_info, RoomInfoNotableUpdateReasons::MEMBERSHIP);
}
Ok(room)
}
/// User has left a room.
///
/// Update the internal and cached state accordingly.
pub async fn room_left(&self, room_id: &RoomId) -> Result<()> {
let room = self.store.get_or_create_room(
room_id,
RoomState::Left,
self.room_info_notable_update_sender.clone(),
);
if room.state() != RoomState::Left {
let _sync_lock = self.sync_lock().lock().await;
let mut room_info = room.clone_info();
room_info.mark_as_left();
room_info.mark_state_partially_synced();
room_info.mark_members_missing(); // the own member event changed
let mut changes = StateChanges::default();
changes.add_room(room_info.clone());
self.store.save_changes(&changes).await?; // Update the store
room.set_room_info(room_info, RoomInfoNotableUpdateReasons::MEMBERSHIP);
}
Ok(())
}
/// Get access to the store's sync lock.
pub fn sync_lock(&self) -> &Mutex<()> {
self.store.sync_lock()
}
/// Receive a response from a sync call.
///
/// # Arguments
///
/// * `response` - The response that we received after a successful sync.
#[instrument(skip_all)]
pub async fn receive_sync_response(
&self,
response: api::sync::sync_events::v3::Response,
) -> Result<SyncResponse> {
// The server might respond multiple times with the same sync token, in
// that case we already received this response and there's nothing to
// do.
if self.store.sync_token.read().await.as_ref() == Some(&response.next_batch) {
info!("Got the same sync response twice");
return Ok(SyncResponse::default());
}
let now = Instant::now();
let mut changes = Box::new(StateChanges::new(response.next_batch.clone()));
#[cfg_attr(not(feature = "e2e-encryption"), allow(unused_mut))]
let mut room_info_notable_updates =
BTreeMap::<OwnedRoomId, RoomInfoNotableUpdateReasons>::new();
#[cfg(feature = "e2e-encryption")]
let to_device = self
.preprocess_to_device_events(
EncryptionSyncChanges {
to_device_events: response.to_device.events,
changed_devices: &response.device_lists,
one_time_keys_counts: &response.device_one_time_keys_count,
unused_fallback_keys: response.device_unused_fallback_key_types.as_deref(),
next_batch_token: Some(response.next_batch.clone()),
},
&mut changes,
&mut room_info_notable_updates,
)
.await?;
#[cfg(not(feature = "e2e-encryption"))]
let to_device = response.to_device.events;
let mut ambiguity_cache = AmbiguityCache::new(self.store.inner.clone());
self.handle_account_data(&response.account_data.events, &mut changes).await;
let push_rules = self.get_push_rules(&changes).await?;
let mut new_rooms = RoomUpdates::default();
let mut notifications = Default::default();
for (room_id, new_info) in response.rooms.join {
let room = self.store.get_or_create_room(
&room_id,
RoomState::Joined,
self.room_info_notable_update_sender.clone(),
);
let mut room_info = room.clone_info();
room_info.mark_as_joined();
room_info.update_from_ruma_summary(&new_info.summary);
room_info.set_prev_batch(new_info.timeline.prev_batch.as_deref());
room_info.mark_state_fully_synced();
let state_events = Self::deserialize_state_events(&new_info.state.events);
let (raw_state_events, state_events): (Vec<_>, Vec<_>) =
state_events.into_iter().unzip();
let mut user_ids = self
.handle_state(
&raw_state_events,
&state_events,
&mut room_info,
&mut changes,
&mut ambiguity_cache,
)
.await?;
for raw in &new_info.ephemeral.events {
match raw.deserialize() {
Ok(AnySyncEphemeralRoomEvent::Receipt(event)) => {
changes.add_receipts(&room_id, event.content);
}
Ok(_) => {}
Err(e) => {
let event_id: Option<String> = raw.get_field("event_id").ok().flatten();
#[rustfmt::skip]
info!(
?room_id, event_id,
"Failed to deserialize ephemeral room event: {e}"
);