-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathnormal.rs
3808 lines (3291 loc) · 140 KB
/
normal.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 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(all(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]
use std::sync::RwLock as SyncRwLock;
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
mem,
sync::{atomic::AtomicBool, Arc},
};
use as_variant::as_variant;
use bitflags::bitflags;
use eyeball::{AsyncLock, ObservableWriteGuard, SharedObservable, Subscriber};
use futures_util::{Stream, StreamExt};
#[cfg(feature = "experimental-sliding-sync")]
use matrix_sdk_common::deserialized_responses::TimelineEventKind;
#[cfg(all(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]
use matrix_sdk_common::ring_buffer::RingBuffer;
#[cfg(feature = "experimental-sliding-sync")]
use ruma::events::AnySyncTimelineEvent;
use ruma::{
api::client::sync::sync_events::v3::RoomSummary as RumaSummary,
events::{
call::member::{CallMemberStateKey, MembershipData},
direct::OwnedDirectUserIdentifier,
ignored_user_list::IgnoredUserListEventContent,
member_hints::MemberHintsEventContent,
receipt::{Receipt, ReceiptThread, ReceiptType},
room::{
avatar::{self, RoomAvatarEventContent},
encryption::RoomEncryptionEventContent,
guest_access::GuestAccess,
history_visibility::HistoryVisibility,
join_rules::JoinRule,
member::{MembershipState, RoomMemberEventContent},
pinned_events::RoomPinnedEventsEventContent,
power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent},
redaction::SyncRoomRedactionEvent,
tombstone::RoomTombstoneEventContent,
},
tag::{TagEventContent, Tags},
AnyRoomAccountDataEvent, AnyStrippedStateEvent, AnySyncStateEvent,
RoomAccountDataEventType, StateEventType, SyncStateEvent,
},
room::RoomType,
serde::Raw,
EventId, MxcUri, OwnedEventId, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedUserId,
RoomAliasId, RoomId, RoomVersionId, UserId,
};
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;
use tracing::{debug, field::debug, info, instrument, trace, warn};
use super::{
members::MemberRoomInfo, BaseRoomInfo, RoomCreateWithCreatorEventContent, RoomDisplayName,
RoomMember, RoomNotableTags,
};
#[cfg(feature = "experimental-sliding-sync")]
use crate::latest_event::LatestEvent;
use crate::{
deserialized_responses::{
DisplayName, MemberEvent, RawMemberEvent, RawSyncOrStrippedState, SyncOrStrippedState,
},
notification_settings::RoomNotificationMode,
read_receipts::RoomReadReceipts,
store::{DynStateStore, Result as StoreResult, StateStoreExt},
sync::UnreadNotificationsCount,
Error, MinimalStateEvent, OriginalMinimalStateEvent, RoomMemberships, StateStoreDataKey,
StateStoreDataValue, StoreError,
};
/// Indicates that a notable update of `RoomInfo` has been applied, and why.
///
/// A room info notable update is an update that can be interested for other
/// parts of the code. This mechanism is used in coordination with
/// [`BaseClient::room_info_notable_update_receiver`][baseclient] (and
/// `Room::inner` plus `Room::room_info_notable_update_sender`) where `RoomInfo`
/// can be observed and some of its updates can be spread to listeners.
///
/// [baseclient]: crate::BaseClient::room_info_notable_update_receiver
#[derive(Debug, Clone)]
pub struct RoomInfoNotableUpdate {
/// The room which was updated.
pub room_id: OwnedRoomId,
/// The reason for this update.
pub reasons: RoomInfoNotableUpdateReasons,
}
bitflags! {
/// The reason why a [`RoomInfoNotableUpdate`] is emitted.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RoomInfoNotableUpdateReasons: u8 {
/// The recency stamp of the `Room` has changed.
const RECENCY_STAMP = 0b0000_0001;
/// The latest event of the `Room` has changed.
const LATEST_EVENT = 0b0000_0010;
/// A read receipt has changed.
const READ_RECEIPT = 0b0000_0100;
/// The user-controlled unread marker value has changed.
const UNREAD_MARKER = 0b0000_1000;
/// A membership change happened for the current user.
const MEMBERSHIP = 0b0001_0000;
}
}
/// The result of a room summary computation.
///
/// If the homeserver does not provide a room summary, we perform a best-effort
/// computation to generate one ourselves. If the homeserver does provide the
/// summary, we augment it with additional information about the service members
/// in the room.
struct ComputedSummary {
/// The list of display names that will be used to calculate the room
/// display name.
heroes: Vec<String>,
/// The number of joined service members in the room.
num_service_members: u64,
/// The number of joined and invited members, not including any service
/// members.
num_joined_invited_guess: u64,
}
impl Default for RoomInfoNotableUpdateReasons {
fn default() -> Self {
Self::empty()
}
}
/// The underlying room data structure collecting state for joined, left and
/// invited rooms.
#[derive(Debug, Clone)]
pub struct Room {
/// The room ID.
room_id: OwnedRoomId,
/// Our own user ID.
own_user_id: OwnedUserId,
inner: SharedObservable<RoomInfo>,
room_info_notable_update_sender: broadcast::Sender<RoomInfoNotableUpdate>,
store: Arc<DynStateStore>,
/// The most recent few encrypted events. When the keys come through to
/// decrypt these, the most recent relevant one will replace
/// `latest_event`. (We can't tell which one is relevant until
/// they are decrypted.)
///
/// Currently, these are held in Room rather than RoomInfo, because we were
/// not sure whether holding too many of them might make the cache too
/// slow to load on startup. Keeping them here means they are not cached
/// to disk but held in memory.
#[cfg(all(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]
pub latest_encrypted_events: Arc<SyncRwLock<RingBuffer<Raw<AnySyncTimelineEvent>>>>,
/// A map for ids of room membership events in the knocking state linked to
/// the user id of the user affected by the member event, that the current
/// user has marked as seen so they can be ignored.
pub seen_knock_request_ids_map:
SharedObservable<Option<BTreeMap<OwnedEventId, OwnedUserId>>, AsyncLock>,
/// A sender that will notify receivers when room member updates happen.
pub room_member_updates_sender: broadcast::Sender<RoomMembersUpdate>,
}
/// The room summary containing member counts and members that should be used to
/// calculate the room display name.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct RoomSummary {
/// The heroes of the room, members that can be used as a fallback for the
/// room's display name or avatar if these haven't been set.
///
/// This was called `heroes` and contained raw `String`s of the `UserId`
/// before. Following this it was called `heroes_user_ids` and a
/// complimentary `heroes_names` existed too; changing the field's name
/// helped with avoiding a migration.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) room_heroes: Vec<RoomHero>,
/// The number of members that are considered to be joined to the room.
pub(crate) joined_member_count: u64,
/// The number of members that are considered to be invited to the room.
pub(crate) invited_member_count: u64,
}
/// Information about a member considered to be a room hero.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoomHero {
/// The user id of the hero.
pub user_id: OwnedUserId,
/// The display name of the hero.
pub display_name: Option<String>,
/// The avatar url of the hero.
pub avatar_url: Option<OwnedMxcUri>,
}
#[cfg(test)]
impl RoomSummary {
pub(crate) fn heroes(&self) -> &[RoomHero] {
&self.room_heroes
}
}
/// Enum keeping track in which state the room is, e.g. if our own user is
/// joined, RoomState::Invited, or has left the room.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum RoomState {
/// The room is in a joined state.
Joined,
/// The room is in a left state.
Left,
/// The room is in an invited state.
Invited,
/// The room is in a knocked state.
Knocked,
/// The room is in a banned state.
Banned,
}
impl From<&MembershipState> for RoomState {
fn from(membership_state: &MembershipState) -> Self {
match membership_state {
MembershipState::Ban => Self::Banned,
MembershipState::Invite => Self::Invited,
MembershipState::Join => Self::Joined,
MembershipState::Knock => Self::Knocked,
MembershipState::Leave => Self::Left,
_ => panic!("Unexpected MembershipState: {}", membership_state),
}
}
}
/// The number of heroes chosen to compute a room's name, if the room didn't
/// have a name set by the users themselves.
///
/// A server must return at most 5 heroes, according to the paragraph below
/// https://spec.matrix.org/v1.10/client-server-api/#get_matrixclientv3sync (grep for "heroes"). We
/// try to behave similarly here.
const NUM_HEROES: usize = 5;
/// A filter to remove our own user and the users specified in the member hints
/// state event, so called service members, from the list of heroes.
///
/// The heroes will then be used to calculate a display name for the room if one
/// wasn't explicitly defined.
fn heroes_filter<'a>(
own_user_id: &'a UserId,
member_hints: &'a MemberHintsEventContent,
) -> impl Fn(&UserId) -> bool + use<'a> {
move |user_id| user_id != own_user_id && !member_hints.service_members.contains(user_id)
}
/// The kind of room member updates that just happened.
#[derive(Debug, Clone)]
pub enum RoomMembersUpdate {
/// The whole list room members was reloaded.
FullReload,
/// A few members were updated, their user ids are included.
Partial(BTreeSet<OwnedUserId>),
}
impl Room {
/// The size of the latest_encrypted_events RingBuffer
// SAFETY: `new_unchecked` is safe because 10 is not zero.
#[cfg(all(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]
const MAX_ENCRYPTED_EVENTS: std::num::NonZeroUsize =
unsafe { std::num::NonZeroUsize::new_unchecked(10) };
pub(crate) fn new(
own_user_id: &UserId,
store: Arc<DynStateStore>,
room_id: &RoomId,
room_state: RoomState,
room_info_notable_update_sender: broadcast::Sender<RoomInfoNotableUpdate>,
) -> Self {
let room_info = RoomInfo::new(room_id, room_state);
Self::restore(own_user_id, store, room_info, room_info_notable_update_sender)
}
pub(crate) fn restore(
own_user_id: &UserId,
store: Arc<DynStateStore>,
room_info: RoomInfo,
room_info_notable_update_sender: broadcast::Sender<RoomInfoNotableUpdate>,
) -> Self {
let (room_member_updates_sender, _) = broadcast::channel(10);
Self {
own_user_id: own_user_id.into(),
room_id: room_info.room_id.clone(),
store,
inner: SharedObservable::new(room_info),
#[cfg(all(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]
latest_encrypted_events: Arc::new(SyncRwLock::new(RingBuffer::new(
Self::MAX_ENCRYPTED_EVENTS,
))),
room_info_notable_update_sender,
seen_knock_request_ids_map: SharedObservable::new_async(None),
room_member_updates_sender,
}
}
/// Get the unique room id of the room.
pub fn room_id(&self) -> &RoomId {
&self.room_id
}
/// Get a copy of the room creator.
pub fn creator(&self) -> Option<OwnedUserId> {
self.inner.read().creator().map(ToOwned::to_owned)
}
/// Get our own user id.
pub fn own_user_id(&self) -> &UserId {
&self.own_user_id
}
/// Get the state of the room.
pub fn state(&self) -> RoomState {
self.inner.read().room_state
}
/// Get the previous state of the room, if it had any.
pub fn prev_state(&self) -> Option<RoomState> {
self.inner.read().prev_room_state
}
/// Whether this room's [`RoomType`] is `m.space`.
pub fn is_space(&self) -> bool {
self.inner.read().room_type().is_some_and(|t| *t == RoomType::Space)
}
/// Returns the room's type as defined in its creation event
/// (`m.room.create`).
pub fn room_type(&self) -> Option<RoomType> {
self.inner.read().room_type().map(ToOwned::to_owned)
}
/// Get the unread notification counts.
pub fn unread_notification_counts(&self) -> UnreadNotificationsCount {
self.inner.read().notification_counts
}
/// Get the number of unread messages (computed client-side).
///
/// This might be more precise than [`Self::unread_notification_counts`] for
/// encrypted rooms.
pub fn num_unread_messages(&self) -> u64 {
self.inner.read().read_receipts.num_unread
}
/// Get the detailed information about read receipts for the room.
pub fn read_receipts(&self) -> RoomReadReceipts {
self.inner.read().read_receipts.clone()
}
/// Get the number of unread notifications (computed client-side).
///
/// This might be more precise than [`Self::unread_notification_counts`] for
/// encrypted rooms.
pub fn num_unread_notifications(&self) -> u64 {
self.inner.read().read_receipts.num_notifications
}
/// Get the number of unread mentions (computed client-side), that is,
/// messages causing a highlight in a room.
///
/// This might be more precise than [`Self::unread_notification_counts`] for
/// encrypted rooms.
pub fn num_unread_mentions(&self) -> u64 {
self.inner.read().read_receipts.num_mentions
}
/// Check if the room has its members fully synced.
///
/// Members might be missing if lazy member loading was enabled for the
/// sync.
///
/// Returns true if no members are missing, false otherwise.
pub fn are_members_synced(&self) -> bool {
self.inner.read().members_synced
}
/// Mark this Room as still missing member information.
pub fn mark_members_missing(&self) {
self.inner.update_if(|info| {
// notify observable subscribers only if the previous value was false
mem::replace(&mut info.members_synced, false)
})
}
/// Check if the room states have been synced
///
/// States might be missing if we have only seen the room_id of this Room
/// so far, for example as the response for a `create_room` request without
/// being synced yet.
///
/// Returns true if the state is fully synced, false otherwise.
pub fn is_state_fully_synced(&self) -> bool {
self.inner.read().sync_info == SyncInfo::FullySynced
}
/// Check if the room state has been at least partially synced.
///
/// See [`Room::is_state_fully_synced`] for more info.
pub fn is_state_partially_or_fully_synced(&self) -> bool {
self.inner.read().sync_info != SyncInfo::NoState
}
/// Check if the room has its encryption event synced.
///
/// The encryption event can be missing when the room hasn't appeared in
/// sync yet.
///
/// Returns true if the encryption state is synced, false otherwise.
pub fn is_encryption_state_synced(&self) -> bool {
self.inner.read().encryption_state_synced
}
/// Get the `prev_batch` token that was received from the last sync. May be
/// `None` if the last sync contained the full room history.
pub fn last_prev_batch(&self) -> Option<String> {
self.inner.read().last_prev_batch.clone()
}
/// Get the avatar url of this room.
pub fn avatar_url(&self) -> Option<OwnedMxcUri> {
self.inner.read().avatar_url().map(ToOwned::to_owned)
}
/// Get information about the avatar of this room.
pub fn avatar_info(&self) -> Option<avatar::ImageInfo> {
self.inner.read().avatar_info().map(ToOwned::to_owned)
}
/// Get the canonical alias of this room.
pub fn canonical_alias(&self) -> Option<OwnedRoomAliasId> {
self.inner.read().canonical_alias().map(ToOwned::to_owned)
}
/// Get the canonical alias of this room.
pub fn alt_aliases(&self) -> Vec<OwnedRoomAliasId> {
self.inner.read().alt_aliases().to_owned()
}
/// Get the `m.room.create` content of this room.
///
/// This usually isn't optional but some servers might not send an
/// `m.room.create` event as the first event for a given room, thus this can
/// be optional.
///
/// For room versions earlier than room version 11, if the event is
/// redacted, all fields except `creator` will be set to their default
/// value.
pub fn create_content(&self) -> Option<RoomCreateWithCreatorEventContent> {
match self.inner.read().base_info.create.as_ref()? {
MinimalStateEvent::Original(ev) => Some(ev.content.clone()),
MinimalStateEvent::Redacted(ev) => Some(ev.content.clone()),
}
}
/// Is this room considered a direct message.
///
/// Async because it can read room info from storage.
#[instrument(skip_all, fields(room_id = ?self.room_id))]
pub async fn is_direct(&self) -> StoreResult<bool> {
match self.state() {
RoomState::Joined | RoomState::Left | RoomState::Banned => {
Ok(!self.inner.read().base_info.dm_targets.is_empty())
}
RoomState::Invited => {
let member = self.get_member(self.own_user_id()).await?;
match member {
None => {
info!("RoomMember not found for the user's own id");
Ok(false)
}
Some(member) => match member.event.as_ref() {
MemberEvent::Sync(_) => {
warn!("Got MemberEvent::Sync in an invited room");
Ok(false)
}
MemberEvent::Stripped(event) => {
Ok(event.content.is_direct.unwrap_or(false))
}
},
}
}
// TODO: implement logic once we have the stripped events as we'd have with an Invite
RoomState::Knocked => Ok(false),
}
}
/// If this room is a direct message, get the members that we're sharing the
/// room with.
///
/// *Note*: The member list might have been modified in the meantime and
/// the targets might not even be in the room anymore. This setting should
/// only be considered as guidance. We leave members in this list to allow
/// us to re-find a DM with a user even if they have left, since we may
/// want to re-invite them.
pub fn direct_targets(&self) -> HashSet<OwnedDirectUserIdentifier> {
self.inner.read().base_info.dm_targets.clone()
}
/// If this room is a direct message, returns the number of members that
/// we're sharing the room with.
pub fn direct_targets_length(&self) -> usize {
self.inner.read().base_info.dm_targets.len()
}
/// Is the room encrypted.
pub fn is_encrypted(&self) -> bool {
self.inner.read().is_encrypted()
}
/// Get the `m.room.encryption` content that enabled end to end encryption
/// in the room.
pub fn encryption_settings(&self) -> Option<RoomEncryptionEventContent> {
self.inner.read().base_info.encryption.clone()
}
/// Get the guest access policy of this room.
pub fn guest_access(&self) -> GuestAccess {
self.inner.read().guest_access().clone()
}
/// Get the history visibility policy of this room.
pub fn history_visibility(&self) -> Option<HistoryVisibility> {
self.inner.read().history_visibility().cloned()
}
/// Get the history visibility policy of this room, or a sensible default if
/// the event is missing.
pub fn history_visibility_or_default(&self) -> HistoryVisibility {
self.inner.read().history_visibility_or_default().clone()
}
/// Is the room considered to be public.
pub fn is_public(&self) -> bool {
matches!(self.join_rule(), JoinRule::Public)
}
/// Get the join rule policy of this room.
pub fn join_rule(&self) -> JoinRule {
self.inner.read().join_rule().clone()
}
/// Get the maximum power level that this room contains.
///
/// This is useful if one wishes to normalize the power levels, e.g. from
/// 0-100 where 100 would be the max power level.
pub fn max_power_level(&self) -> i64 {
self.inner.read().base_info.max_power_level
}
/// Get the current power levels of this room.
pub async fn power_levels(&self) -> Result<RoomPowerLevels, Error> {
Ok(self
.store
.get_state_event_static::<RoomPowerLevelsEventContent>(self.room_id())
.await?
.ok_or(Error::InsufficientData)?
.deserialize()?
.power_levels())
}
/// Get the `m.room.name` of this room.
///
/// The returned string may be empty if the event has been redacted, or it's
/// missing from storage.
pub fn name(&self) -> Option<String> {
self.inner.read().name().map(ToOwned::to_owned)
}
/// Has the room been tombstoned.
pub fn is_tombstoned(&self) -> bool {
self.inner.read().base_info.tombstone.is_some()
}
/// Get the `m.room.tombstone` content of this room if there is one.
pub fn tombstone(&self) -> Option<RoomTombstoneEventContent> {
self.inner.read().tombstone().cloned()
}
/// Get the topic of the room.
pub fn topic(&self) -> Option<String> {
self.inner.read().topic().map(ToOwned::to_owned)
}
/// Is there a non expired membership with application "m.call" and scope
/// "m.room" in this room
pub fn has_active_room_call(&self) -> bool {
self.inner.read().has_active_room_call()
}
/// Returns a Vec of userId's that participate in the room call.
///
/// MatrixRTC memberships with application "m.call" and scope "m.room" are
/// considered. A user can occur twice if they join with two devices.
/// convert to a set depending if the different users are required or the
/// amount of sessions.
///
/// The vector is ordered by oldest membership user to newest.
pub fn active_room_call_participants(&self) -> Vec<OwnedUserId> {
self.inner.read().active_room_call_participants()
}
/// Calculate a room's display name, or return the cached value, taking into
/// account its name, aliases and members.
///
/// The display name is calculated according to [this algorithm][spec].
///
/// While the underlying computation can be slow, the result is cached and
/// returned on the following calls. The cache is also filled on every
/// successful sync, since a sync may cause a change in the display
/// name.
///
/// If you need a variant that's sync (but with the drawback that it returns
/// an `Option`), consider using [`Room::cached_display_name`].
///
/// [spec]: <https://matrix.org/docs/spec/client_server/latest#calculating-the-display-name-for-a-room>
pub async fn display_name(&self) -> StoreResult<RoomDisplayName> {
if let Some(name) = self.cached_display_name() {
Ok(name)
} else {
self.compute_display_name().await
}
}
/// Force recalculating a room's display name, taking into account its name,
/// aliases and members.
///
/// The display name is calculated according to [this algorithm][spec].
///
/// ⚠ This may be slowish to compute. As such, the result is cached and can
/// be retrieved via [`Room::cached_display_name`] (sync, returns an option)
/// or [`Room::display_name`] (async, always returns a value), which should
/// be preferred in general.
///
/// [spec]: <https://matrix.org/docs/spec/client_server/latest#calculating-the-display-name-for-a-room>
pub(crate) async fn compute_display_name(&self) -> StoreResult<RoomDisplayName> {
enum DisplayNameOrSummary {
Summary(RoomSummary),
DisplayName(RoomDisplayName),
}
let display_name_or_summary = {
let inner = self.inner.read();
match (inner.name(), inner.canonical_alias()) {
(Some(name), _) => {
let name = RoomDisplayName::Named(name.trim().to_owned());
DisplayNameOrSummary::DisplayName(name)
}
(None, Some(alias)) => {
let name = RoomDisplayName::Aliased(alias.alias().trim().to_owned());
DisplayNameOrSummary::DisplayName(name)
}
// We can't directly compute the display name from the summary here because Rust
// thinks that the `inner` lock is still held even if we explicitly call `drop()`
// on it. So we introduced the DisplayNameOrSummary type and do the computation in
// two steps.
(None, None) => DisplayNameOrSummary::Summary(inner.summary.clone()),
}
};
let display_name = match display_name_or_summary {
DisplayNameOrSummary::Summary(summary) => {
self.compute_display_name_from_summary(summary).await?
}
DisplayNameOrSummary::DisplayName(display_name) => display_name,
};
// Update the cached display name before we return the newly computed value.
self.inner.update_if(|info| {
if info.cached_display_name.as_ref() != Some(&display_name) {
info.cached_display_name = Some(display_name.clone());
true
} else {
false
}
});
Ok(display_name)
}
/// Compute a [`RoomDisplayName`] from the given [`RoomSummary`].
async fn compute_display_name_from_summary(
&self,
summary: RoomSummary,
) -> StoreResult<RoomDisplayName> {
let computed_summary = if !summary.room_heroes.is_empty() {
self.extract_and_augment_summary(&summary).await?
} else {
self.compute_summary().await?
};
let ComputedSummary { heroes, num_service_members, num_joined_invited_guess } =
computed_summary;
let summary_member_count = (summary.joined_member_count + summary.invited_member_count)
.saturating_sub(num_service_members);
let num_joined_invited = if self.state() == RoomState::Invited {
// when we were invited we don't have a proper summary, we have to do best
// guessing
heroes.len() as u64 + 1
} else if summary_member_count == 0 {
num_joined_invited_guess
} else {
summary_member_count
};
debug!(
room_id = ?self.room_id(),
own_user = ?self.own_user_id,
num_joined_invited,
heroes = ?heroes,
"Calculating name for a room based on heroes",
);
let display_name = compute_display_name_from_heroes(
num_joined_invited,
heroes.iter().map(|hero| hero.as_str()).collect(),
);
Ok(display_name)
}
/// Extracts and enhances the [`RoomSummary`] provided by the homeserver.
///
/// This method extracts the relevant data from the [`RoomSummary`] and
/// augments it with additional information that may not be included in
/// the initial response, such as details about service members in the
/// room.
///
/// Returns a [`ComputedSummary`].
async fn extract_and_augment_summary(
&self,
summary: &RoomSummary,
) -> StoreResult<ComputedSummary> {
let heroes = &summary.room_heroes;
let mut names = Vec::with_capacity(heroes.len());
let own_user_id = self.own_user_id();
let member_hints = self.get_member_hints().await?;
// If we have some service members in the heroes, that means that they are also
// part of the joined member counts. They shouldn't be so, otherwise
// we'll wrongly assume that there are more members in the room than
// they are for the "Bob and 2 others" case.
let num_service_members = heroes
.iter()
.filter(|hero| member_hints.service_members.contains(&hero.user_id))
.count() as u64;
// Construct a filter that is specific to this own user id, set of member hints,
// and accepts a `RoomHero` type.
let heroes_filter = heroes_filter(own_user_id, &member_hints);
let heroes_filter = |hero: &&RoomHero| heroes_filter(&hero.user_id);
for hero in heroes.iter().filter(heroes_filter) {
if let Some(display_name) = &hero.display_name {
names.push(display_name.clone());
} else {
match self.get_member(&hero.user_id).await {
Ok(Some(member)) => {
names.push(member.name().to_owned());
}
Ok(None) => {
warn!("Ignoring hero, no member info for {}", hero.user_id);
}
Err(error) => {
warn!("Ignoring hero, error getting member: {}", error);
}
}
}
}
let num_joined_invited_guess = summary.joined_member_count + summary.invited_member_count;
// If the summary doesn't provide the number of joined/invited members, let's
// guess something.
let num_joined_invited_guess = if num_joined_invited_guess == 0 {
let guess = self
.store
.get_user_ids(self.room_id(), RoomMemberships::JOIN | RoomMemberships::INVITE)
.await?
.len() as u64;
guess.saturating_sub(num_service_members)
} else {
// Otherwise, accept the numbers provided by the summary as the guess.
num_joined_invited_guess
};
Ok(ComputedSummary { heroes: names, num_service_members, num_joined_invited_guess })
}
/// Compute the room summary with the data present in the store.
///
/// The summary might be incorrect if the database info is outdated.
///
/// Returns the [`ComputedSummary`].
async fn compute_summary(&self) -> StoreResult<ComputedSummary> {
let member_hints = self.get_member_hints().await?;
// Construct a filter that is specific to this own user id, set of member hints,
// and accepts a `RoomMember` type.
let heroes_filter = heroes_filter(&self.own_user_id, &member_hints);
let heroes_filter = |u: &RoomMember| heroes_filter(u.user_id());
let mut members = self.members(RoomMemberships::JOIN | RoomMemberships::INVITE).await?;
// If we have some service members, they shouldn't count to the number of
// joined/invited members, otherwise we'll wrongly assume that there are more
// members in the room than they are for the "Bob and 2 others" case.
let num_service_members = members
.iter()
.filter(|member| member_hints.service_members.contains(member.user_id()))
.count();
// We can make a good prediction of the total number of joined and invited
// members here. This might be incorrect if the database info is
// outdated.
//
// Note: Subtracting here is fine because `num_service_members` is a subset of
// `members.len()` due to the above filter operation.
let num_joined_invited = members.len() - num_service_members;
if num_joined_invited == 0
|| (num_joined_invited == 1 && members[0].user_id() == self.own_user_id)
{
// No joined or invited members, heroes should be banned and left members.
members = self.members(RoomMemberships::LEAVE | RoomMemberships::BAN).await?;
}
// Make the ordering deterministic.
members.sort_unstable_by(|lhs, rhs| lhs.name().cmp(rhs.name()));
let heroes = members
.into_iter()
.filter(heroes_filter)
.take(NUM_HEROES)
.map(|u| u.name().to_owned())
.collect();
trace!(
?heroes,
num_joined_invited,
num_service_members,
"Computed a room summary since we didn't receive one."
);
let num_service_members = num_service_members as u64;
let num_joined_invited_guess = num_joined_invited as u64;
Ok(ComputedSummary { heroes, num_service_members, num_joined_invited_guess })
}
async fn get_member_hints(&self) -> StoreResult<MemberHintsEventContent> {
Ok(self
.store
.get_state_event_static::<MemberHintsEventContent>(self.room_id())
.await?
.and_then(|event| {
event
.deserialize()
.inspect_err(|e| warn!("Couldn't deserialize the member hints event: {e}"))
.ok()
})
.and_then(|event| as_variant!(event, SyncOrStrippedState::Sync(SyncStateEvent::Original(e)) => e.content))
.unwrap_or_default())
}
/// Returns the cached computed display name, if available.
///
/// This cache is refilled every time we call [`Self::display_name`].
pub fn cached_display_name(&self) -> Option<RoomDisplayName> {
self.inner.read().cached_display_name.clone()
}
/// Update the cached user defined notification mode.
///
/// This is automatically recomputed on every successful sync, and the
/// cached result can be retrieved in
/// [`Self::cached_user_defined_notification_mode`].
pub fn update_cached_user_defined_notification_mode(&self, mode: RoomNotificationMode) {
self.inner.update_if(|info| {
if info.cached_user_defined_notification_mode.as_ref() != Some(&mode) {
info.cached_user_defined_notification_mode = Some(mode);
true
} else {
false
}
});
}
/// Returns the cached user defined notification mode, if available.
///
/// This cache is refilled every time we call
/// [`Self::update_cached_user_defined_notification_mode`].
pub fn cached_user_defined_notification_mode(&self) -> Option<RoomNotificationMode> {
self.inner.read().cached_user_defined_notification_mode
}
/// Return the last event in this room, if one has been cached during
/// sliding sync.
#[cfg(feature = "experimental-sliding-sync")]
pub fn latest_event(&self) -> Option<LatestEvent> {
self.inner.read().latest_event.as_deref().cloned()
}
/// Return the most recent few encrypted events. When the keys come through
/// to decrypt these, the most recent relevant one will replace
/// latest_event. (We can't tell which one is relevant until
/// they are decrypted.)
#[cfg(all(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]
pub(crate) fn latest_encrypted_events(&self) -> Vec<Raw<AnySyncTimelineEvent>> {
self.latest_encrypted_events.read().unwrap().iter().cloned().collect()
}
/// Replace our latest_event with the supplied event, and delete it and all
/// older encrypted events from latest_encrypted_events, given that the
/// new event was at the supplied index in the latest_encrypted_events
/// list.
///
/// Panics if index is not a valid index in the latest_encrypted_events
/// list.
///
/// It is the responsibility of the caller to apply the changes into the
/// state store after calling this function.
#[cfg(all(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]
pub(crate) fn on_latest_event_decrypted(
&self,
latest_event: Box<LatestEvent>,
index: usize,
changes: &mut crate::StateChanges,
room_info_notable_updates: &mut BTreeMap<OwnedRoomId, RoomInfoNotableUpdateReasons>,
) {
self.latest_encrypted_events.write().unwrap().drain(0..=index);
let room_info = changes
.room_infos
.entry(self.room_id().to_owned())
.or_insert_with(|| self.clone_info());
room_info.latest_event = Some(latest_event);
room_info_notable_updates
.entry(self.room_id().to_owned())
.or_default()
.insert(RoomInfoNotableUpdateReasons::LATEST_EVENT);
}
/// Get the list of users ids that are considered to be joined members of
/// this room.
pub async fn joined_user_ids(&self) -> StoreResult<Vec<OwnedUserId>> {
self.store.get_user_ids(self.room_id(), RoomMemberships::JOIN).await
}
/// Get the `RoomMember`s of this room that are known to the store, with the
/// given memberships.
pub async fn members(&self, memberships: RoomMemberships) -> StoreResult<Vec<RoomMember>> {
let user_ids = self.store.get_user_ids(self.room_id(), memberships).await?;
if user_ids.is_empty() {
return Ok(Vec::new());
}
let member_events = self
.store
.get_state_events_for_keys_static::<RoomMemberEventContent, _, _>(
self.room_id(),
&user_ids,
)
.await?
.into_iter()
.map(|raw_event| raw_event.deserialize())
.collect::<Result<Vec<_>, _>>()?;