Skip to main content

matrix_sdk_base/room/
room_info.rs

1// Copyright 2025 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16    collections::{BTreeMap, BTreeSet, HashSet},
17    sync::{Arc, atomic::AtomicBool},
18};
19
20use as_variant::as_variant;
21use bitflags::bitflags;
22use eyeball::Subscriber;
23use matrix_sdk_common::{ROOM_VERSION_FALLBACK, ROOM_VERSION_RULES_FALLBACK};
24use ruma::{
25    EventId, MxcUri, OwnedEventId, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedUserId,
26    RoomAliasId, RoomId, RoomVersionId,
27    api::client::sync::sync_events::v3::RoomSummary as RumaSummary,
28    events::{
29        AnyPossiblyRedactedStateEventContent, AnyStrippedStateEvent, AnySyncStateEvent,
30        AnySyncTimelineEvent, StateEventType,
31        call::member::{
32            CallMemberStateKey, MembershipData, PossiblyRedactedCallMemberEventContent,
33        },
34        direct::OwnedDirectUserIdentifier,
35        member_hints::PossiblyRedactedMemberHintsEventContent,
36        room::{
37            avatar::{self, PossiblyRedactedRoomAvatarEventContent},
38            canonical_alias::PossiblyRedactedRoomCanonicalAliasEventContent,
39            encryption::PossiblyRedactedRoomEncryptionEventContent,
40            guest_access::{GuestAccess, PossiblyRedactedRoomGuestAccessEventContent},
41            history_visibility::{
42                HistoryVisibility, PossiblyRedactedRoomHistoryVisibilityEventContent,
43            },
44            join_rules::{JoinRule, PossiblyRedactedRoomJoinRulesEventContent},
45            name::PossiblyRedactedRoomNameEventContent,
46            pinned_events::{
47                PossiblyRedactedRoomPinnedEventsEventContent, RoomPinnedEventsEventContent,
48            },
49            redaction::SyncRoomRedactionEvent,
50            retention::RoomRetentionEventContent,
51            tombstone::PossiblyRedactedRoomTombstoneEventContent,
52            topic::PossiblyRedactedRoomTopicEventContent,
53        },
54        rtc::notification::CallIntent,
55        tag::{TagEventContent, TagName, Tags},
56    },
57    room::RoomType,
58    room_version_rules::{RedactionRules, RoomVersionRules},
59    serde::Raw,
60};
61use serde::{Deserialize, Serialize};
62use tokio::sync::MutexGuard;
63use tracing::{field::debug, info, instrument, warn};
64
65use super::{
66    AccountDataSource, EncryptionState, Room, RoomCreateWithCreatorEventContent, RoomDisplayName,
67    RoomHero, RoomNotableTags, RoomState, RoomSummary,
68};
69use crate::{
70    MinimalStateEvent, StateChanges, StoreError,
71    deserialized_responses::RawSyncOrStrippedState,
72    latest_event::LatestEventValue,
73    notification_settings::RoomNotificationMode,
74    read_receipts::ReadReceipts,
75    room::call::CallIntentConsensus,
76    store::{IncorrectMutexGuardError, SaveLockedStateStore, StateStoreExt},
77    sync::UnreadNotificationsCount,
78    utils::{AnyStateEventEnum, RawStateEventWithKeys},
79};
80
81/// The default value of the maximum power level.
82const DEFAULT_MAX_POWER_LEVEL: i64 = 100;
83
84impl Room {
85    /// Subscribe to the inner `RoomInfo`.
86    pub fn subscribe_info(&self) -> Subscriber<RoomInfo> {
87        self.info.subscribe()
88    }
89
90    /// Clone the inner `RoomInfo`.
91    pub fn clone_info(&self) -> RoomInfo {
92        self.info.get()
93    }
94
95    /// Update [`RoomInfo`] with the given function `F`. Updates are atomic as
96    /// this function acquires the lock of the underlying store before updating
97    /// the [`RoomInfo`].
98    pub async fn update_room_info<F>(&self, f: F)
99    where
100        F: FnOnce(RoomInfo) -> (RoomInfo, RoomInfoNotableUpdateReasons),
101    {
102        self.update_room_info_with_store_guard(&self.store.lock().lock().await, f)
103            .expect("should have correct mutex!")
104    }
105
106    /// Same as [`Self::update_room_info`], but allows the caller to provide a
107    /// guard for the lock of the underlying store in case it has already been
108    /// acquired.
109    ///
110    /// This function returns an [`IncorrectMutexGuardError`] if the provided
111    /// guard is not associated with the lock of the underlying store.
112    pub fn update_room_info_with_store_guard<F>(
113        &self,
114        guard: &MutexGuard<'_, ()>,
115        f: F,
116    ) -> Result<(), IncorrectMutexGuardError>
117    where
118        F: FnOnce(RoomInfo) -> (RoomInfo, RoomInfoNotableUpdateReasons),
119    {
120        if !std::ptr::eq(MutexGuard::mutex(guard), self.store.lock()) {
121            return Err(IncorrectMutexGuardError);
122        }
123
124        let (info, mut reasons) = f(self.clone_info());
125        self.info.set(info);
126
127        if reasons.is_empty() {
128            // TODO: remove this block! Read
129            // `RoomInfoNotableUpdateReasons::NONE` to understand why it must be
130            // removed.
131            reasons = RoomInfoNotableUpdateReasons::NONE;
132        }
133        let _ = self
134            .room_info_notable_update_sender
135            .send(RoomInfoNotableUpdate { room_id: self.room_id.clone(), reasons });
136
137        Ok(())
138    }
139
140    /// Same as [`Self::update_room_info`] but also saves the changes to the
141    /// underlying store.
142    pub async fn update_and_save_room_info<F>(&self, f: F) -> Result<(), StoreError>
143    where
144        F: FnOnce(RoomInfo) -> (RoomInfo, RoomInfoNotableUpdateReasons),
145    {
146        self.update_and_save_room_info_with_store_guard(&self.store.lock().lock().await, f).await
147    }
148
149    /// Same as [`Self::update_and_save_room_info`], but allows the caller to
150    /// provide a guard for the lock of the underlying store in case it has
151    /// already been acquired.
152    ///
153    /// This function returns an [`IncorrectMutexGuardError`] if the provided
154    /// guard is not associated with the lock of the underlying store.
155    pub async fn update_and_save_room_info_with_store_guard<F>(
156        &self,
157        guard: &MutexGuard<'_, ()>,
158        f: F,
159    ) -> Result<(), StoreError>
160    where
161        F: FnOnce(RoomInfo) -> (RoomInfo, RoomInfoNotableUpdateReasons),
162    {
163        let (info, reasons) = f(self.clone_info());
164        let mut changes = StateChanges::default();
165        changes.add_room(info.clone());
166        self.store.save_changes_with_guard(guard, &changes).await?;
167        self.update_room_info_with_store_guard(guard, |_| (info, reasons))?;
168        Ok(())
169    }
170}
171
172/// A base room info struct that is the backbone of normal as well as stripped
173/// rooms. Holds all the state events that are important to present a room to
174/// users.
175#[derive(Clone, Debug, Serialize, Deserialize)]
176pub struct BaseRoomInfo {
177    /// The avatar URL of this room.
178    pub(crate) avatar: Option<MinimalStateEvent<PossiblyRedactedRoomAvatarEventContent>>,
179    /// The canonical alias of this room.
180    pub(crate) canonical_alias:
181        Option<MinimalStateEvent<PossiblyRedactedRoomCanonicalAliasEventContent>>,
182    /// The `m.room.create` event content of this room.
183    pub(crate) create: Option<MinimalStateEvent<RoomCreateWithCreatorEventContent>>,
184    /// A list of user ids this room is considered as direct message, if this
185    /// room is a DM.
186    pub(crate) dm_targets: HashSet<OwnedDirectUserIdentifier>,
187    /// The `m.room.encryption` event content that enabled E2EE in this room.
188    pub(crate) encryption: Option<PossiblyRedactedRoomEncryptionEventContent>,
189    /// The guest access policy of this room.
190    pub(crate) guest_access: Option<MinimalStateEvent<PossiblyRedactedRoomGuestAccessEventContent>>,
191    /// The history visibility policy of this room.
192    pub(crate) history_visibility:
193        Option<MinimalStateEvent<PossiblyRedactedRoomHistoryVisibilityEventContent>>,
194    /// The join rule policy of this room.
195    pub(crate) join_rules: Option<MinimalStateEvent<PossiblyRedactedRoomJoinRulesEventContent>>,
196    /// The maximal power level that can be found in this room.
197    pub(crate) max_power_level: i64,
198    /// The member hints for the room as per MSC4171, including service members,
199    /// if available.
200    pub(crate) member_hints: Option<MinimalStateEvent<PossiblyRedactedMemberHintsEventContent>>,
201    /// The `m.room.name` of this room.
202    pub(crate) name: Option<MinimalStateEvent<PossiblyRedactedRoomNameEventContent>>,
203    /// The message retention policy of this room.
204    pub(crate) retention: Option<MinimalStateEvent<RoomRetentionEventContent>>,
205    /// The `m.room.tombstone` event content of this room.
206    pub(crate) tombstone: Option<MinimalStateEvent<PossiblyRedactedRoomTombstoneEventContent>>,
207    /// The topic of this room.
208    pub(crate) topic: Option<MinimalStateEvent<PossiblyRedactedRoomTopicEventContent>>,
209    /// All minimal state events that containing one or more running matrixRTC
210    /// memberships.
211    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
212    pub(crate) rtc_member_events:
213        BTreeMap<CallMemberStateKey, MinimalStateEvent<PossiblyRedactedCallMemberEventContent>>,
214    /// Whether this room has been manually marked as unread.
215    #[serde(default)]
216    pub(crate) is_marked_unread: bool,
217    /// The source of is_marked_unread.
218    #[serde(default)]
219    pub(crate) is_marked_unread_source: AccountDataSource,
220    /// Some notable tags.
221    ///
222    /// We are not interested by all the tags. Some tags are more important than
223    /// others, and this field collects them.
224    #[serde(skip_serializing_if = "RoomNotableTags::is_empty", default)]
225    pub(crate) notable_tags: RoomNotableTags,
226    /// The `m.room.pinned_events` of this room.
227    pub(crate) pinned_events: Option<PossiblyRedactedRoomPinnedEventsEventContent>,
228}
229
230impl BaseRoomInfo {
231    /// Create a new, empty base room info.
232    pub fn new() -> Self {
233        Self::default()
234    }
235
236    /// Get the room version of this room.
237    ///
238    /// For room versions earlier than room version 11, if the event is
239    /// redacted, this will return the default of [`RoomVersionId::V1`].
240    pub fn room_version(&self) -> Option<&RoomVersionId> {
241        Some(&self.create.as_ref()?.content.room_version)
242    }
243
244    /// Handle a state event for this room and update our info accordingly.
245    ///
246    /// Returns true if the event modified the info, false otherwise.
247    pub fn handle_state_event<T: AnyStateEventEnum>(
248        &mut self,
249        raw_event: &mut RawStateEventWithKeys<T>,
250    ) -> bool {
251        match (&raw_event.event_type, raw_event.state_key.as_str()) {
252            (StateEventType::RoomEncryption, "") => {
253                // To avoid breaking encrypted rooms, we ignore
254                // `m.room.encryption` events that fail to deserialize or that
255                // are redacted (i.e. they don't contain the algorithm used for
256                // encryption).
257                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
258                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomEncryption)
259                }) && event.content.algorithm.is_some()
260                {
261                    self.encryption = Some(event.content);
262                    true
263                } else {
264                    false
265                }
266            }
267            (StateEventType::RoomAvatar, "") => {
268                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
269                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomAvatar)
270                }) {
271                    self.avatar = Some(event);
272                    true
273                } else {
274                    // Remove the previous content if the new content is
275                    // unknown.
276                    self.avatar.take().is_some()
277                }
278            }
279            (StateEventType::RoomName, "") => {
280                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
281                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomName)
282                }) {
283                    self.name = Some(event);
284                    true
285                } else {
286                    // Remove the previous content if the new content is
287                    // unknown.
288                    self.name.take().is_some()
289                }
290            }
291            // `m.room.create` CANNOT be overwritten.
292            (StateEventType::RoomCreate, "") if self.create.is_none() => {
293                if let Some(any_event) = raw_event.deserialize()
294                    && let Some(content) = as_variant!(
295                        any_event.get_content(),
296                        AnyPossiblyRedactedStateEventContent::RoomCreate
297                    )
298                {
299                    self.create = Some(MinimalStateEvent {
300                        content: RoomCreateWithCreatorEventContent::from_event_content(
301                            content,
302                            any_event.get_sender().to_owned(),
303                        ),
304                        event_id: any_event.get_event_id().map(ToOwned::to_owned),
305                    });
306                    true
307                } else {
308                    false
309                }
310            }
311            (StateEventType::RoomHistoryVisibility, "") => {
312                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
313                    as_variant!(
314                        any_event,
315                        AnyPossiblyRedactedStateEventContent::RoomHistoryVisibility
316                    )
317                }) {
318                    self.history_visibility = Some(event);
319                    true
320                } else {
321                    // Remove the previous content if the new content is
322                    // unknown.
323                    self.history_visibility.take().is_some()
324                }
325            }
326            (StateEventType::RoomRetention, "") => {
327                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
328                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomRetention)
329                }) {
330                    self.retention = Some(event);
331                    true
332                } else {
333                    // Remove the previous content if the new content is
334                    // unknown.
335                    self.retention.take().is_some()
336                }
337            }
338            (StateEventType::RoomGuestAccess, "") => {
339                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
340                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomGuestAccess)
341                }) {
342                    self.guest_access = Some(event);
343                    true
344                } else {
345                    // Remove the previous content if the new content is
346                    // unknown.
347                    self.guest_access.take().is_some()
348                }
349            }
350            (StateEventType::MemberHints, "") => {
351                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
352                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::MemberHints)
353                }) {
354                    self.member_hints = Some(event);
355                    true
356                } else {
357                    // Remove the previous content if the new content is
358                    // unknown.
359                    self.member_hints.take().is_some()
360                }
361            }
362            (StateEventType::RoomJoinRules, "") => {
363                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
364                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomJoinRules)
365                }) {
366                    match &event.content.join_rule {
367                        JoinRule::Invite
368                        | JoinRule::Knock
369                        | JoinRule::Private
370                        | JoinRule::Restricted(_)
371                        | JoinRule::KnockRestricted(_)
372                        | JoinRule::Public => {
373                            self.join_rules = Some(event);
374                            true
375                        }
376                        r => {
377                            warn!(join_rule = ?r.as_str(), "Encountered a custom join rule, skipping");
378                            // Remove the previous content if the new content is
379                            // unsupported.
380                            self.join_rules.take().is_some()
381                        }
382                    }
383                } else {
384                    // Remove the previous content if the new content is
385                    // unknown.
386                    self.join_rules.take().is_some()
387                }
388            }
389            (StateEventType::RoomCanonicalAlias, "") => {
390                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
391                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomCanonicalAlias)
392                }) {
393                    self.canonical_alias = Some(event);
394                    true
395                } else {
396                    // Remove the previous content if the new content is
397                    // unknown.
398                    self.canonical_alias.take().is_some()
399                }
400            }
401            (StateEventType::RoomTopic, "") => {
402                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
403                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomTopic)
404                }) {
405                    self.topic = Some(event);
406                    true
407                } else {
408                    // Remove the previous content if the new content is
409                    // unknown.
410                    self.topic.take().is_some()
411                }
412            }
413            (StateEventType::RoomTombstone, "") => {
414                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
415                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomTombstone)
416                }) {
417                    self.tombstone = Some(event);
418                    true
419                } else {
420                    // Remove the previous content if the new content is
421                    // unknown.
422                    self.tombstone.take().is_some()
423                }
424            }
425            (StateEventType::RoomPowerLevels, "") => {
426                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
427                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomPowerLevels)
428                }) {
429                    let new_max = i64::from(
430                        event
431                            .content
432                            .users
433                            .values()
434                            .fold(event.content.users_default, |max_pl, user_pl| {
435                                max_pl.max(*user_pl)
436                            }),
437                    );
438
439                    if self.max_power_level != new_max {
440                        self.max_power_level = new_max;
441                        true
442                    } else {
443                        false
444                    }
445                } else if self.max_power_level != DEFAULT_MAX_POWER_LEVEL {
446                    // Reset the previous value if the new value is unknown.
447                    self.max_power_level = DEFAULT_MAX_POWER_LEVEL;
448                    true
449                } else {
450                    false
451                }
452            }
453            (StateEventType::CallMember, _) => {
454                if let Ok(call_member_key) = raw_event.state_key.parse::<CallMemberStateKey>() {
455                    if let Some(any_event) = raw_event.deserialize()
456                        && let Some(content) = as_variant!(
457                            any_event.get_content(),
458                            AnyPossiblyRedactedStateEventContent::CallMember
459                        )
460                    {
461                        let mut event = MinimalStateEvent {
462                            content,
463                            event_id: any_event.get_event_id().map(ToOwned::to_owned),
464                        };
465
466                        if let Some(origin_server_ts) = any_event.get_origin_server_ts() {
467                            event.content.set_created_ts_if_none(origin_server_ts);
468                        }
469
470                        // Add the new event.
471                        self.rtc_member_events.insert(call_member_key, event);
472
473                        // Remove all events that don't contain any memberships
474                        // anymore.
475                        self.rtc_member_events
476                            .retain(|_, ev| !ev.content.active_memberships(None).is_empty());
477
478                        true
479                    } else {
480                        // Remove the previous content with the same state key
481                        // if the new content is unknown.
482                        self.rtc_member_events.remove(&call_member_key).is_some()
483                    }
484                } else {
485                    false
486                }
487            }
488            (StateEventType::RoomPinnedEvents, "") => {
489                if let Some(event) = raw_event.deserialize_as_minimal_event(|any_event| {
490                    as_variant!(any_event, AnyPossiblyRedactedStateEventContent::RoomPinnedEvents)
491                }) {
492                    self.pinned_events = Some(event.content);
493                    true
494                } else {
495                    // Remove the previous content if the new content is
496                    // unknown.
497                    self.pinned_events.take().is_some()
498                }
499            }
500            _ => false,
501        }
502    }
503
504    pub(super) fn handle_redaction(&mut self, redacts: &EventId) {
505        let redaction_rules = self
506            .room_version()
507            .and_then(|room_version| room_version.rules())
508            .unwrap_or(ROOM_VERSION_RULES_FALLBACK)
509            .redaction;
510
511        if let Some(ev) = &mut self.avatar
512            && ev.event_id.as_deref() == Some(redacts)
513        {
514            ev.redact(&redaction_rules);
515        } else if let Some(ev) = &mut self.canonical_alias
516            && ev.event_id.as_deref() == Some(redacts)
517        {
518            ev.redact(&redaction_rules);
519        } else if let Some(ev) = &mut self.create
520            && ev.event_id.as_deref() == Some(redacts)
521        {
522            ev.redact(&redaction_rules);
523        } else if let Some(ev) = &mut self.guest_access
524            && ev.event_id.as_deref() == Some(redacts)
525        {
526            ev.redact(&redaction_rules);
527        } else if let Some(ev) = &mut self.history_visibility
528            && ev.event_id.as_deref() == Some(redacts)
529        {
530            ev.redact(&redaction_rules);
531        } else if let Some(ev) = &mut self.join_rules
532            && ev.event_id.as_deref() == Some(redacts)
533        {
534            ev.redact(&redaction_rules);
535        } else if let Some(ev) = &mut self.name
536            && ev.event_id.as_deref() == Some(redacts)
537        {
538            ev.redact(&redaction_rules);
539        } else if let Some(ev) = &mut self.retention
540            && ev.event_id.as_deref() == Some(redacts)
541        {
542            ev.redact(&redaction_rules);
543        } else if let Some(ev) = &mut self.tombstone
544            && ev.event_id.as_deref() == Some(redacts)
545        {
546            ev.redact(&redaction_rules);
547        } else if let Some(ev) = &mut self.topic
548            && ev.event_id.as_deref() == Some(redacts)
549        {
550            ev.redact(&redaction_rules);
551        } else {
552            self.rtc_member_events
553                .retain(|_, member_event| member_event.event_id.as_deref() != Some(redacts));
554        }
555    }
556
557    pub fn handle_notable_tags(&mut self, tags: &Tags) {
558        let mut notable_tags = RoomNotableTags::empty();
559
560        if tags.contains_key(&TagName::Favorite) {
561            notable_tags.insert(RoomNotableTags::FAVOURITE);
562        }
563
564        if tags.contains_key(&TagName::LowPriority) {
565            notable_tags.insert(RoomNotableTags::LOW_PRIORITY);
566        }
567
568        self.notable_tags = notable_tags;
569    }
570}
571
572impl Default for BaseRoomInfo {
573    fn default() -> Self {
574        Self {
575            avatar: None,
576            canonical_alias: None,
577            create: None,
578            dm_targets: Default::default(),
579            member_hints: None,
580            encryption: None,
581            guest_access: None,
582            history_visibility: None,
583            join_rules: None,
584            max_power_level: DEFAULT_MAX_POWER_LEVEL,
585            name: None,
586            retention: None,
587            tombstone: None,
588            topic: None,
589            rtc_member_events: BTreeMap::new(),
590            is_marked_unread: false,
591            is_marked_unread_source: AccountDataSource::Unstable,
592            notable_tags: RoomNotableTags::empty(),
593            pinned_events: None,
594        }
595    }
596}
597
598/// The underlying pure data structure for joined and left rooms.
599///
600/// Holds all the info needed to persist a room into the state store.
601#[derive(Clone, Debug, Serialize, Deserialize)]
602pub struct RoomInfo {
603    /// The version of the room info type. It is used to migrate the `RoomInfo`
604    /// serialization from one version to another.
605    #[serde(default, alias = "version")]
606    pub(crate) data_format_version: u8,
607
608    /// The unique room id of the room.
609    pub(crate) room_id: OwnedRoomId,
610
611    /// The state of the room.
612    pub(crate) room_state: RoomState,
613
614    /// The unread notifications counts, as returned by the server.
615    ///
616    /// These might be incorrect for encrypted rooms, since the server doesn't
617    /// have access to the content of the encrypted events.
618    pub(crate) notification_counts: UnreadNotificationsCount,
619
620    /// The summary of this room.
621    pub(crate) summary: RoomSummary,
622
623    /// Flag remembering if the room members are synced.
624    pub(crate) members_synced: bool,
625
626    /// The prev batch of this room we received during the last sync.
627    pub(crate) last_prev_batch: Option<String>,
628
629    /// How much we know about this room.
630    pub(crate) sync_info: SyncInfo,
631
632    /// Whether or not the encryption info was been synced.
633    pub(crate) encryption_state_synced: bool,
634
635    /// The latest event value of this room.
636    #[serde(default)]
637    pub(crate) latest_event_value: LatestEventValue,
638
639    /// Information about read receipts for this room.
640    #[serde(default)]
641    pub(crate) read_receipts: ReadReceipts,
642
643    /// Base room info which holds some basic event contents important for the
644    /// room state.
645    pub(crate) base_info: Box<BaseRoomInfo>,
646
647    /// Whether we already warned about unknown room version rules in
648    /// [`RoomInfo::room_version_rules_or_default`]. This is done to avoid
649    /// spamming about unknown room versions rules in the log for the same room.
650    #[serde(skip)]
651    pub(crate) warned_about_unknown_room_version_rules: Arc<AtomicBool>,
652
653    /// Cached display name, useful for sync access.
654    ///
655    /// Filled by calling [`Room::compute_display_name`]. It's automatically
656    /// filled at start when creating a room, or on every successful sync.
657    #[serde(default, skip_serializing_if = "Option::is_none")]
658    pub(crate) cached_display_name: Option<RoomDisplayName>,
659
660    /// Cached user defined notification mode.
661    #[serde(default, skip_serializing_if = "Option::is_none")]
662    pub(crate) cached_user_defined_notification_mode: Option<RoomNotificationMode>,
663
664    /// The recency stamp of this room.
665    ///
666    /// It's not to be confused with the `origin_server_ts` value of an event.
667    /// Sliding Sync might “ignore” some events when computing the recency stamp
668    /// of the room. The recency stamp must be considered as an opaque unsigned
669    /// integer value.
670    ///
671    /// # Sorting rooms
672    ///
673    /// The recency stamp is designed to _sort_ rooms between them. The room
674    /// with the highest stamp should be at the top of a room list. However, in
675    /// some situation, it might be inaccurate (for example if the server and
676    /// the client disagree on which events should increment the recency stamp).
677    /// The [`LatestEventValue`] might be a useful alternative to sort rooms
678    /// between them as it's all computed client-side. In this case, the recency
679    /// stamp nicely acts as a default fallback.
680    #[serde(default)]
681    pub(crate) recency_stamp: Option<RoomRecencyStamp>,
682}
683
684impl RoomInfo {
685    #[doc(hidden)] // used by store tests, otherwise it would be pub(crate)
686    pub fn new(room_id: &RoomId, room_state: RoomState) -> Self {
687        Self {
688            data_format_version: 1,
689            room_id: room_id.into(),
690            room_state,
691            notification_counts: Default::default(),
692            summary: Default::default(),
693            members_synced: false,
694            last_prev_batch: None,
695            sync_info: SyncInfo::NoState,
696            encryption_state_synced: false,
697            latest_event_value: LatestEventValue::default(),
698            read_receipts: Default::default(),
699            base_info: Box::new(BaseRoomInfo::new()),
700            warned_about_unknown_room_version_rules: Arc::new(false.into()),
701            cached_display_name: None,
702            cached_user_defined_notification_mode: None,
703            recency_stamp: None,
704        }
705    }
706
707    /// Mark this Room as joined.
708    pub fn mark_as_joined(&mut self) {
709        self.set_state(RoomState::Joined);
710    }
711
712    /// Mark this Room as left.
713    pub fn mark_as_left(&mut self) {
714        self.set_state(RoomState::Left);
715    }
716
717    /// Mark this Room as invited.
718    pub fn mark_as_invited(&mut self) {
719        self.set_state(RoomState::Invited);
720    }
721
722    /// Mark this Room as knocked.
723    pub fn mark_as_knocked(&mut self) {
724        self.set_state(RoomState::Knocked);
725    }
726
727    /// Mark this Room as banned.
728    pub fn mark_as_banned(&mut self) {
729        self.set_state(RoomState::Banned);
730    }
731
732    /// Set the membership RoomState of this Room
733    pub fn set_state(&mut self, room_state: RoomState) {
734        self.room_state = room_state;
735    }
736
737    /// Mark this Room as having all the members synced.
738    pub fn mark_members_synced(&mut self) {
739        self.members_synced = true;
740    }
741
742    /// Mark this Room as still missing member information.
743    pub fn mark_members_missing(&mut self) {
744        self.members_synced = false;
745    }
746
747    /// Returns whether the room members are synced.
748    pub fn are_members_synced(&self) -> bool {
749        self.members_synced
750    }
751
752    /// Mark this Room as still missing some state information.
753    pub fn mark_state_partially_synced(&mut self) {
754        self.sync_info = SyncInfo::PartiallySynced;
755    }
756
757    /// Mark this Room as still having all state synced.
758    pub fn mark_state_fully_synced(&mut self) {
759        self.sync_info = SyncInfo::FullySynced;
760    }
761
762    /// Mark this Room as still having no state synced.
763    pub fn mark_state_not_synced(&mut self) {
764        self.sync_info = SyncInfo::NoState;
765    }
766
767    /// Mark this Room as having the encryption state synced.
768    pub fn mark_encryption_state_synced(&mut self) {
769        self.encryption_state_synced = true;
770    }
771
772    /// Mark this Room as still missing encryption state information.
773    pub fn mark_encryption_state_missing(&mut self) {
774        self.encryption_state_synced = false;
775    }
776
777    /// Set the `prev_batch`-token. Returns whether the token has differed and
778    /// thus has been upgraded: `false` means no update was applied as the were
779    /// the same
780    pub fn set_prev_batch(&mut self, prev_batch: Option<&str>) -> bool {
781        if self.last_prev_batch.as_deref() != prev_batch {
782            self.last_prev_batch = prev_batch.map(|p| p.to_owned());
783            true
784        } else {
785            false
786        }
787    }
788
789    /// Returns the state this room is in.
790    pub fn state(&self) -> RoomState {
791        self.room_state
792    }
793
794    /// Returns the encryption state of this room.
795    #[cfg(not(feature = "experimental-encrypted-state-events"))]
796    pub fn encryption_state(&self) -> EncryptionState {
797        if !self.encryption_state_synced {
798            EncryptionState::Unknown
799        } else if self.base_info.encryption.is_some() {
800            EncryptionState::Encrypted
801        } else {
802            EncryptionState::NotEncrypted
803        }
804    }
805
806    /// Returns the encryption state of this room.
807    #[cfg(feature = "experimental-encrypted-state-events")]
808    pub fn encryption_state(&self) -> EncryptionState {
809        if !self.encryption_state_synced {
810            EncryptionState::Unknown
811        } else {
812            self.base_info
813                .encryption
814                .as_ref()
815                .map(|state| {
816                    if state.encrypt_state_events {
817                        EncryptionState::StateEncrypted
818                    } else {
819                        EncryptionState::Encrypted
820                    }
821                })
822                .unwrap_or(EncryptionState::NotEncrypted)
823        }
824    }
825
826    /// Set the encryption event content in this room.
827    pub fn set_encryption_event(
828        &mut self,
829        event: Option<PossiblyRedactedRoomEncryptionEventContent>,
830    ) {
831        self.base_info.encryption = event;
832    }
833
834    /// Handle the encryption state.
835    pub fn handle_encryption_state(
836        &mut self,
837        requested_required_states: &[(StateEventType, String)],
838    ) {
839        if requested_required_states
840            .iter()
841            .any(|(state_event, _)| state_event == &StateEventType::RoomEncryption)
842        {
843            // The `m.room.encryption` event was requested during the sync.
844            // Whether we have received a `m.room.encryption` event in return
845            // doesn't matter: we must mark the encryption state as synced; if
846            // the event is present, it means the room _is_ encrypted, otherwise
847            // it means the room _is not_ encrypted.
848
849            self.mark_encryption_state_synced();
850        }
851    }
852
853    /// Handle the given state event.
854    ///
855    /// Returns true if the event modified the info, false otherwise.
856    pub fn handle_state_event(
857        &mut self,
858        raw_event: &mut RawStateEventWithKeys<AnySyncStateEvent>,
859    ) -> bool {
860        // When we receive a `m.room.member_hints` event
861        if raw_event.event_type == StateEventType::MemberHints
862            && let Some(AnySyncStateEvent::MemberHints(new_hints)) = raw_event.deserialize()
863            // If we have both old and new member hints events
864            && let (Some(current_hints), Some(new)) =
865                (&self.base_info.member_hints, new_hints.as_original())
866            // Then we check if their contents don't match
867            && current_hints
868                .content
869                .service_members
870                .as_ref()
871                .is_some_and(|current_members| *current_members != new.content.service_members)
872        {
873            // And reset the computed value in that case
874            self.summary.active_service_members = None;
875        }
876
877        // Store the state event in the `BaseRoomInfo`.
878        let base_info_has_been_modified = self.base_info.handle_state_event(raw_event);
879
880        if raw_event.event_type == StateEventType::RoomEncryption && raw_event.state_key.is_empty()
881        {
882            // The `m.room.encryption` event was or wasn't explicitly requested,
883            // we don't know here (see `Self::handle_encryption_state`) but we
884            // got one in return! In this case, we can deduce the room _is_
885            // encrypted, but we cannot know if it _is not_ encrypted.
886
887            self.mark_encryption_state_synced();
888        }
889
890        base_info_has_been_modified
891    }
892
893    /// Handle the given stripped state event.
894    ///
895    /// Returns true if the event modified the info, false otherwise.
896    pub fn handle_stripped_state_event(
897        &mut self,
898        raw_event: &mut RawStateEventWithKeys<AnyStrippedStateEvent>,
899    ) -> bool {
900        self.base_info.handle_state_event(raw_event)
901    }
902
903    /// Handle the given redaction.
904    #[instrument(skip_all, fields(redacts))]
905    pub fn handle_redaction(
906        &mut self,
907        event: &SyncRoomRedactionEvent,
908        _raw: &Raw<SyncRoomRedactionEvent>,
909    ) {
910        let redaction_rules = self.room_version_rules_or_default().redaction;
911
912        let Some(redacts) = event.redacts(&redaction_rules) else {
913            info!("Can't apply redaction, redacts field is missing");
914            return;
915        };
916        tracing::Span::current().record("redacts", debug(redacts));
917
918        self.base_info.handle_redaction(redacts);
919    }
920
921    /// Returns the current room avatar.
922    pub fn avatar_url(&self) -> Option<&MxcUri> {
923        self.base_info.avatar.as_ref().and_then(|e| e.content.url.as_deref())
924    }
925
926    /// Update the room avatar.
927    pub fn update_avatar(&mut self, url: Option<OwnedMxcUri>) {
928        self.base_info.avatar = url.map(|url| {
929            let mut content = PossiblyRedactedRoomAvatarEventContent::new();
930            content.url = Some(url);
931
932            MinimalStateEvent { content, event_id: None }
933        });
934    }
935
936    /// Returns information about the current room avatar.
937    pub fn avatar_info(&self) -> Option<&avatar::ImageInfo> {
938        self.base_info.avatar.as_ref().and_then(|e| e.content.info.as_deref())
939    }
940
941    /// Update the notifications count.
942    pub fn update_notification_count(&mut self, notification_counts: UnreadNotificationsCount) {
943        self.notification_counts = notification_counts;
944    }
945
946    /// Update the RoomSummary from a Ruma `RoomSummary`.
947    ///
948    /// Returns true if any field has been updated, false otherwise.
949    pub fn update_from_ruma_summary(&mut self, summary: &RumaSummary) -> bool {
950        let mut changed = false;
951
952        if !summary.is_empty() {
953            if !summary.heroes.is_empty() {
954                self.summary.room_heroes = summary
955                    .heroes
956                    .iter()
957                    .map(|hero_id| RoomHero {
958                        user_id: hero_id.to_owned(),
959                        display_name: None,
960                        avatar_url: None,
961                    })
962                    .collect();
963
964                changed = true;
965            }
966
967            if let Some(joined) = summary.joined_member_count {
968                self.summary.joined_member_count = joined.into();
969                changed = true;
970            }
971
972            if let Some(invited) = summary.invited_member_count {
973                self.summary.invited_member_count = invited.into();
974                changed = true;
975            }
976        }
977
978        if changed {
979            self.summary.active_service_members = None;
980        }
981
982        changed
983    }
984
985    /// Updates the joined member count.
986    pub(crate) fn update_joined_member_count(&mut self, count: u64) {
987        self.summary.joined_member_count = count;
988    }
989
990    /// Updates the invited member count.
991    pub(crate) fn update_invited_member_count(&mut self, count: u64) {
992        self.summary.invited_member_count = count;
993    }
994
995    /// Updates the room heroes.
996    pub(crate) fn update_heroes(&mut self, heroes: Vec<RoomHero>) {
997        self.summary.room_heroes = heroes;
998    }
999
1000    /// The heroes for this room.
1001    pub fn heroes(&self) -> &[RoomHero] {
1002        &self.summary.room_heroes
1003    }
1004
1005    /// The number of active members (invited + joined) in the room.
1006    ///
1007    /// The return value is saturated at `u64::MAX`.
1008    pub fn active_members_count(&self) -> u64 {
1009        self.summary.joined_member_count.saturating_add(self.summary.invited_member_count)
1010    }
1011
1012    /// The number of invited members in the room
1013    pub fn invited_members_count(&self) -> u64 {
1014        self.summary.invited_member_count
1015    }
1016
1017    /// The number of joined members in the room
1018    pub fn joined_members_count(&self) -> u64 {
1019        self.summary.joined_member_count
1020    }
1021
1022    /// Get the canonical alias of this room.
1023    pub fn canonical_alias(&self) -> Option<&RoomAliasId> {
1024        self.base_info.canonical_alias.as_ref()?.content.alias.as_deref()
1025    }
1026
1027    /// Get the alternative aliases of this room.
1028    pub fn alt_aliases(&self) -> &[OwnedRoomAliasId] {
1029        self.base_info
1030            .canonical_alias
1031            .as_ref()
1032            .map(|ev| ev.content.alt_aliases.as_ref())
1033            .unwrap_or_default()
1034    }
1035
1036    /// Get the room ID of this room.
1037    pub fn room_id(&self) -> &RoomId {
1038        &self.room_id
1039    }
1040
1041    /// Get the room version of this room.
1042    pub fn room_version(&self) -> Option<&RoomVersionId> {
1043        self.base_info.room_version()
1044    }
1045
1046    /// Get the room version rules of this room, or a sensible default.
1047    ///
1048    /// Will warn (at most once) if the room create event is missing from this
1049    /// [`RoomInfo`] or if the room version is unsupported.
1050    pub fn room_version_rules_or_default(&self) -> RoomVersionRules {
1051        use std::sync::atomic::Ordering;
1052
1053        self.base_info.room_version().and_then(|room_version| room_version.rules()).unwrap_or_else(
1054            || {
1055                if self
1056                    .warned_about_unknown_room_version_rules
1057                    .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
1058                    .is_ok()
1059                {
1060                    warn!("Unable to get the room version rules, defaulting to rules for room version {ROOM_VERSION_FALLBACK}");
1061                }
1062
1063                ROOM_VERSION_RULES_FALLBACK
1064            },
1065        )
1066    }
1067
1068    /// Get the room type of this room.
1069    pub fn room_type(&self) -> Option<&RoomType> {
1070        self.base_info.create.as_ref()?.content.room_type.as_ref()
1071    }
1072
1073    /// Get the creators of this room.
1074    pub fn creators(&self) -> Option<Vec<OwnedUserId>> {
1075        Some(self.base_info.create.as_ref()?.content.creators())
1076    }
1077
1078    pub(super) fn guest_access(&self) -> &GuestAccess {
1079        self.base_info
1080            .guest_access
1081            .as_ref()
1082            .and_then(|event| event.content.guest_access.as_ref())
1083            .unwrap_or(&GuestAccess::Forbidden)
1084    }
1085
1086    /// Returns the history visibility for this room.
1087    ///
1088    /// Returns None if the event was never seen during sync.
1089    pub fn history_visibility(&self) -> Option<&HistoryVisibility> {
1090        Some(&self.base_info.history_visibility.as_ref()?.content.history_visibility)
1091    }
1092
1093    /// Returns the history visibility for this room, or a sensible default.
1094    ///
1095    /// Returns `Shared`, the default specified by the [spec], when the event is
1096    /// missing.
1097    ///
1098    /// [spec]: https://spec.matrix.org/latest/client-server-api/#server-behaviour-7
1099    pub fn history_visibility_or_default(&self) -> &HistoryVisibility {
1100        self.history_visibility().unwrap_or(&HistoryVisibility::Shared)
1101    }
1102
1103    /// Returns the message retention policy for this room.
1104    ///
1105    /// Returns `None` if the event was never seen during sync.
1106    pub fn retention(&self) -> Option<&RoomRetentionEventContent> {
1107        self.base_info.retention.as_ref().map(|e| &e.content)
1108    }
1109
1110    /// Return the join rule for this room, if the `m.room.join_rules` event is
1111    /// available.
1112    pub fn join_rule(&self) -> Option<&JoinRule> {
1113        Some(&self.base_info.join_rules.as_ref()?.content.join_rule)
1114    }
1115
1116    /// Return the service members for this room if the `m.member_hints` event
1117    /// is available
1118    pub fn service_members(&self) -> Option<&BTreeSet<OwnedUserId>> {
1119        self.base_info.member_hints.as_ref()?.content.service_members.as_ref()
1120    }
1121
1122    /// Get the name of this room.
1123    pub fn name(&self) -> Option<&str> {
1124        self.base_info.name.as_ref()?.content.name.as_deref().filter(|name| !name.is_empty())
1125    }
1126
1127    /// Get the content of the `m.room.create` event if any.
1128    pub fn create(&self) -> Option<&RoomCreateWithCreatorEventContent> {
1129        Some(&self.base_info.create.as_ref()?.content)
1130    }
1131
1132    /// Get the content of the `m.room.tombstone` event if any.
1133    pub fn tombstone(&self) -> Option<&PossiblyRedactedRoomTombstoneEventContent> {
1134        Some(&self.base_info.tombstone.as_ref()?.content)
1135    }
1136
1137    /// Returns the topic for this room, if set.
1138    pub fn topic(&self) -> Option<&str> {
1139        self.base_info.topic.as_ref()?.content.topic.as_deref()
1140    }
1141
1142    /// Get a list of all the valid (non expired) matrixRTC memberships and
1143    /// associated UserId's in this room.
1144    ///
1145    /// The vector is ordered by oldest membership to newest.
1146    fn active_matrix_rtc_memberships(&self) -> Vec<(CallMemberStateKey, MembershipData<'_>)> {
1147        let mut v = self
1148            .base_info
1149            .rtc_member_events
1150            .iter()
1151            .flat_map(|(state_key, ev)| {
1152                ev.content.active_memberships(None).into_iter().map(move |m| (state_key.clone(), m))
1153            })
1154            .collect::<Vec<_>>();
1155        v.sort_by_key(|(_, m)| m.created_ts());
1156        v
1157    }
1158
1159    /// Similar to
1160    /// [`matrix_rtc_memberships`](Self::active_matrix_rtc_memberships) but only
1161    /// returns Memberships with application "m.call" and scope "m.room".
1162    ///
1163    /// The vector is ordered by oldest membership user to newest.
1164    fn active_room_call_memberships(&self) -> Vec<(CallMemberStateKey, MembershipData<'_>)> {
1165        self.active_matrix_rtc_memberships()
1166            .into_iter()
1167            .filter(|(_user_id, m)| m.is_room_call())
1168            .collect()
1169    }
1170
1171    /// Is there a non expired membership with application "m.call" and scope
1172    /// "m.room" in this room.
1173    pub fn has_active_room_call(&self) -> bool {
1174        !self.active_room_call_memberships().is_empty()
1175    }
1176
1177    /// Whether the given `(user_id, device_id)` tuple is currently a
1178    /// participant in this room's active MatrixRTC call.
1179    ///
1180    /// Distinct from [`Self::active_room_call_participants`] which returns only
1181    /// user IDs. Callers that must not conflate multiple devices of the same
1182    /// user (e.g. profile-field mirroring) should use this.
1183    pub fn is_device_in_active_room_call(
1184        &self,
1185        user_id: &ruma::UserId,
1186        device_id: &ruma::DeviceId,
1187    ) -> bool {
1188        self.active_room_call_memberships().iter().any(|(state_key, membership)| {
1189            state_key.user_id() == user_id && membership.device_id() == device_id
1190        })
1191    }
1192
1193    /// Get the call intent consensus for the current call, based on what
1194    /// members are advertising.
1195    ///
1196    /// This provides detailed information about the consensus state (is it an
1197    /// audio or video call), including whether it's full (all members agree) or
1198    /// partial (only some members advertise), allowing callers to distinguish
1199    /// between different levels of consensus.
1200    ///
1201    /// # Returns
1202    ///
1203    /// - [`CallIntentConsensus::Full`] if all members advertise and agree on
1204    ///   the same intent
1205    /// - [`CallIntentConsensus::Partial`] if only some members advertise but
1206    ///   those who do agree
1207    /// - [`CallIntentConsensus::None`] if no one advertises or advertisers
1208    ///   disagree
1209    pub fn active_room_call_consensus_intent(&self) -> CallIntentConsensus {
1210        let memberships = self.active_room_call_memberships();
1211        let total_count: u64 = memberships.len() as u64;
1212
1213        if total_count == 0 {
1214            return CallIntentConsensus::None;
1215        }
1216
1217        // Track the first intent found and count how many members advertise it
1218        let mut consensus_intent: Option<CallIntent> = None;
1219        let mut agreeing_count: u64 = 0;
1220
1221        for (_, data) in memberships.iter() {
1222            if let Some(intent) = data.call_intent() {
1223                match &consensus_intent {
1224                    // First intent found, set it as consensus
1225                    None => {
1226                        consensus_intent = Some(intent.clone());
1227                        agreeing_count = 1;
1228                    }
1229                    // Check if this intent matches the consensus
1230                    Some(current) if current == intent => {
1231                        agreeing_count += 1;
1232                    }
1233                    // Intents differ, no consensus
1234                    Some(_) => return CallIntentConsensus::None,
1235                }
1236            }
1237        }
1238
1239        // Return the appropriate consensus type based on participation
1240        match consensus_intent {
1241            None => CallIntentConsensus::None,
1242            Some(intent) if agreeing_count == total_count => {
1243                // All members advertise and agree
1244                CallIntentConsensus::Full(intent)
1245            }
1246            Some(intent) => {
1247                // Some members advertise and agree, others don't advertise
1248                CallIntentConsensus::Partial { intent, agreeing_count, total_count }
1249            }
1250        }
1251    }
1252
1253    /// Returns a Vec of userId's that participate in the room call.
1254    ///
1255    /// matrix_rtc memberships with application "m.call" and scope "m.room" are
1256    /// considered. A user can occur twice if they join with two devices.
1257    /// convert to a set depending if the different users are required or the
1258    /// amount of sessions.
1259    ///
1260    /// The vector is ordered by oldest membership user to newest.
1261    pub fn active_room_call_participants(&self) -> Vec<OwnedUserId> {
1262        self.active_room_call_memberships()
1263            .iter()
1264            .map(|(call_member_state_key, _)| call_member_state_key.user_id().to_owned())
1265            .collect()
1266    }
1267
1268    /// Sets the new [`LatestEventValue`].
1269    pub fn set_latest_event(&mut self, new_value: LatestEventValue) {
1270        self.latest_event_value = new_value;
1271    }
1272
1273    /// Updates the recency stamp of this room.
1274    ///
1275    /// Please read `Self::recency_stamp` to learn more.
1276    pub fn update_recency_stamp(&mut self, stamp: RoomRecencyStamp) {
1277        self.recency_stamp = Some(stamp);
1278    }
1279
1280    /// Returns the current pinned event ids for this room.
1281    pub fn pinned_event_ids(&self) -> Option<Vec<OwnedEventId>> {
1282        self.base_info.pinned_events.clone().and_then(|c| c.pinned)
1283    }
1284
1285    /// Checks if an `EventId` is currently pinned. It avoids having to clone
1286    /// the whole list of event ids to check a single value.
1287    ///
1288    /// Returns `true` if the provided `event_id` is pinned, `false` otherwise.
1289    pub fn is_pinned_event(&self, event_id: &EventId) -> bool {
1290        self.base_info
1291            .pinned_events
1292            .as_ref()
1293            .and_then(|content| content.pinned.as_deref())
1294            .is_some_and(|pinned| pinned.contains(&event_id.to_owned()))
1295    }
1296
1297    /// Returns the computed read receipts for this room.
1298    pub fn read_receipts(&self) -> &ReadReceipts {
1299        &self.read_receipts
1300    }
1301
1302    /// Set the computed read receipts for this room.
1303    pub fn set_read_receipts(&mut self, read_receipts: ReadReceipts) {
1304        self.read_receipts = read_receipts;
1305    }
1306
1307    /// Apply migrations to this `RoomInfo` if needed.
1308    ///
1309    /// This should be used to populate new fields with data from the state
1310    /// store.
1311    ///
1312    /// Returns `true` if migrations were applied and this `RoomInfo` needs to
1313    /// be persisted to the state store.
1314    #[instrument(skip_all, fields(room_id = ?self.room_id))]
1315    pub(crate) async fn apply_migrations(&mut self, store: SaveLockedStateStore) -> bool {
1316        let mut migrated = false;
1317
1318        if self.data_format_version < 1 {
1319            info!("Migrating room info to version 1");
1320
1321            // notable_tags
1322            match store.get_room_account_data_event_static::<TagEventContent>(&self.room_id).await {
1323                // Pinned events are never in stripped state.
1324                Ok(Some(raw_event)) => match raw_event.deserialize() {
1325                    Ok(event) => {
1326                        self.base_info.handle_notable_tags(&event.content.tags);
1327                    }
1328                    Err(error) => {
1329                        warn!("Failed to deserialize room tags: {error}");
1330                    }
1331                },
1332                Ok(_) => {
1333                    // Nothing to do.
1334                }
1335                Err(error) => {
1336                    warn!("Failed to load room tags: {error}");
1337                }
1338            }
1339
1340            // pinned_events
1341            match store.get_state_event_static::<RoomPinnedEventsEventContent>(&self.room_id).await
1342            {
1343                // Pinned events are never in stripped state.
1344                Ok(Some(RawSyncOrStrippedState::Sync(raw_event))) => {
1345                    if let Some(mut raw_event) =
1346                        RawStateEventWithKeys::try_from_raw_state_event(raw_event.cast())
1347                    {
1348                        self.handle_state_event(&mut raw_event);
1349                    }
1350                }
1351                Ok(_) => {
1352                    // Nothing to do.
1353                }
1354                Err(error) => {
1355                    warn!("Failed to load room pinned events: {error}");
1356                }
1357            }
1358
1359            self.data_format_version = 1;
1360            migrated = true;
1361        }
1362
1363        migrated
1364    }
1365
1366    /// Returns the number of active (joined/invited) service members in the
1367    /// room, if known.
1368    pub fn active_service_member_count(&self) -> Option<u64> {
1369        self.summary.active_service_members
1370    }
1371
1372    /// Updates the cached value for the number of active service members in the
1373    /// room.
1374    pub fn update_active_service_member_count(&mut self, count: Option<u64>) {
1375        self.summary.active_service_members = count;
1376    }
1377}
1378
1379/// Type to represent a `RoomInfo::recency_stamp`.
1380#[repr(transparent)]
1381#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
1382#[serde(transparent)]
1383pub struct RoomRecencyStamp(u64);
1384
1385impl From<u64> for RoomRecencyStamp {
1386    fn from(value: u64) -> Self {
1387        Self(value)
1388    }
1389}
1390
1391impl From<RoomRecencyStamp> for u64 {
1392    fn from(value: RoomRecencyStamp) -> Self {
1393        value.0
1394    }
1395}
1396
1397#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1398pub(crate) enum SyncInfo {
1399    /// We only know the room exists and whether it is in invite / joined / left
1400    /// state.
1401    ///
1402    /// This is the case when we have a limited sync or only seen the room
1403    /// because of a request we've done, like a room creation event.
1404    NoState,
1405
1406    /// Some states have been synced, but they might have been filtered or is
1407    /// stale, as it is from a room we've left.
1408    PartiallySynced,
1409
1410    /// We have all the latest state events.
1411    FullySynced,
1412}
1413
1414/// Apply a redaction to the given target `event`, given the raw redaction event
1415/// and the room version.
1416pub fn apply_redaction(
1417    event: &Raw<AnySyncTimelineEvent>,
1418    raw_redaction: &Raw<SyncRoomRedactionEvent>,
1419    rules: &RedactionRules,
1420) -> Option<Raw<AnySyncTimelineEvent>> {
1421    use ruma::canonical_json::{RedactedBecause, redact_in_place};
1422
1423    let mut event_json = match event.deserialize_as() {
1424        Ok(json) => json,
1425        Err(e) => {
1426            warn!("Failed to deserialize latest event: {e}");
1427            return None;
1428        }
1429    };
1430
1431    let redacted_because = match RedactedBecause::from_raw_event(raw_redaction) {
1432        Ok(rb) => rb,
1433        Err(e) => {
1434            warn!("Redaction event is not valid canonical JSON: {e}");
1435            return None;
1436        }
1437    };
1438
1439    let redact_result = redact_in_place(&mut event_json, rules, Some(redacted_because));
1440
1441    if let Err(e) = redact_result {
1442        warn!("Failed to redact event: {e}");
1443        return None;
1444    }
1445
1446    let raw = Raw::new(&event_json).expect("CanonicalJsonObject must be serializable");
1447    Some(raw.cast_unchecked())
1448}
1449
1450/// Indicates that a notable update of `RoomInfo` has been applied, and why.
1451///
1452/// A room info notable update is an update that can be interesting for other
1453/// parts of the code. This mechanism is used in coordination with
1454/// [`BaseClient::room_info_notable_update_receiver`][baseclient] (and
1455/// `Room::info` plus `Room::room_info_notable_update_sender`) where `RoomInfo`
1456/// can be observed and some of its updates can be spread to listeners.
1457///
1458/// [baseclient]: crate::BaseClient::room_info_notable_update_receiver
1459#[derive(Debug, Clone)]
1460pub struct RoomInfoNotableUpdate {
1461    /// The room which was updated.
1462    pub room_id: OwnedRoomId,
1463
1464    /// The reason for this update.
1465    pub reasons: RoomInfoNotableUpdateReasons,
1466}
1467
1468bitflags! {
1469    /// The reason why a [`RoomInfoNotableUpdate`] is emitted.
1470    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1471    pub struct RoomInfoNotableUpdateReasons: u16 {
1472        /// The recency stamp of the `Room` has changed.
1473        const RECENCY_STAMP = 0b0000_0000_0000_0001;
1474
1475        /// The latest event of the `Room` has changed.
1476        const LATEST_EVENT = 0b0000_0000_0000_0010;
1477
1478        /// A read receipt has changed.
1479        const READ_RECEIPT = 0b0000_0000_0000_0100;
1480
1481        /// The user-controlled unread marker value has changed.
1482        const UNREAD_MARKER = 0b0000_0000_0000_1000;
1483
1484        /// A membership change happened for the current user.
1485        const MEMBERSHIP = 0b0000_0000_0001_0000;
1486
1487        /// The display name has changed.
1488        const DISPLAY_NAME = 0b0000_0000_0010_0000;
1489
1490        /// The active service members have changed.
1491        const ACTIVE_SERVICE_MEMBERS = 0b0000_0000_0100_0000;
1492
1493        /// This is a temporary hack.
1494        ///
1495        /// So here is the thing. Ideally, we DO NOT want to emit this reason.
1496        /// It does not makes sense. However, all notable update reasons are not
1497        /// clearly identified so far. Why is it a problem? The
1498        /// `matrix_sdk_ui::room_list_service::RoomList` is listening this
1499        /// stream of [`RoomInfoNotableUpdate`], and emits an update on a room
1500        /// item if it receives a notable reason. Because all reasons are not
1501        /// identified, we are likely to miss particular updates, and it can
1502        /// feel broken. Ultimately, we want to clearly identify all the notable
1503        /// update reasons, and remove this one.
1504        const NONE = 0b0000_0000_1000_0000;
1505
1506        /// A room hero's global profile changed (e.g. their status or call).
1507        const HEROES = 0b0000_0010_0000_0000;
1508    }
1509}
1510
1511impl Default for RoomInfoNotableUpdateReasons {
1512    fn default() -> Self {
1513        Self::empty()
1514    }
1515}
1516
1517#[cfg(test)]
1518mod tests {
1519    use std::{collections::BTreeSet, str::FromStr, sync::Arc, time::Duration};
1520
1521    use assert_matches::assert_matches;
1522    use futures_util::future::{self, Either};
1523    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
1524    use gloo_timers::future::sleep;
1525    use matrix_sdk_common::executor::spawn;
1526    use matrix_sdk_test::{async_test, event_factory::EventFactory};
1527    use ruma::{
1528        assign,
1529        events::{
1530            AnyRoomAccountDataEvent,
1531            room::{
1532                pinned_events::RoomPinnedEventsEventContent, retention::RoomRetentionEventContent,
1533            },
1534            tag::{TagInfo, TagName, Tags, UserTagName},
1535        },
1536        owned_event_id, owned_mxc_uri, owned_user_id, room_id,
1537        serde::Raw,
1538        user_id,
1539    };
1540    use serde_json::json;
1541    use similar_asserts::assert_eq;
1542    use tokio::sync::Mutex;
1543    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
1544    use tokio::time::sleep;
1545
1546    use super::{BaseRoomInfo, LatestEventValue, RoomInfo, SyncInfo};
1547    use crate::{
1548        RawStateEventWithKeys, Room, RoomDisplayName, RoomHero, RoomInfoNotableUpdateReasons,
1549        RoomState, StateChanges, StateStore,
1550        notification_settings::RoomNotificationMode,
1551        room::{RoomNotableTags, RoomSummary},
1552        store::{IntoStateStore, MemoryStore, RoomLoadSettings, SaveLockedStateStore},
1553        sync::UnreadNotificationsCount,
1554    };
1555
1556    #[test]
1557    fn test_room_info_serialization() {
1558        // This test exists to make sure we don't accidentally change the
1559        // serialized format for `RoomInfo`.
1560
1561        let info = RoomInfo {
1562            data_format_version: 1,
1563            room_id: room_id!("!gda78o:server.tld").into(),
1564            room_state: RoomState::Invited,
1565            notification_counts: UnreadNotificationsCount {
1566                highlight_count: 1,
1567                notification_count: 2,
1568            },
1569            summary: RoomSummary {
1570                room_heroes: vec![RoomHero {
1571                    user_id: owned_user_id!("@somebody:example.org"),
1572                    display_name: None,
1573                    avatar_url: None,
1574                }],
1575                joined_member_count: 5,
1576                invited_member_count: 0,
1577                active_service_members: None,
1578            },
1579            members_synced: true,
1580            last_prev_batch: Some("pb".to_owned()),
1581            sync_info: SyncInfo::FullySynced,
1582            encryption_state_synced: true,
1583            latest_event_value: LatestEventValue::None,
1584            base_info: Box::new(
1585                assign!(BaseRoomInfo::new(), { pinned_events: Some(RoomPinnedEventsEventContent::new(vec![owned_event_id!("$a")]).into()) }),
1586            ),
1587            read_receipts: Default::default(),
1588            warned_about_unknown_room_version_rules: Arc::new(false.into()),
1589            cached_display_name: None,
1590            cached_user_defined_notification_mode: None,
1591            recency_stamp: Some(42.into()),
1592        };
1593
1594        let info_json = json!({
1595            "data_format_version": 1,
1596            "room_id": "!gda78o:server.tld",
1597            "room_state": "Invited",
1598            "notification_counts": {
1599                "highlight_count": 1,
1600                "notification_count": 2,
1601            },
1602            "summary": {
1603                "room_heroes": [{
1604                    "user_id": "@somebody:example.org",
1605                    "display_name": null,
1606                    "avatar_url": null
1607                }],
1608                "joined_member_count": 5,
1609                "invited_member_count": 0,
1610            },
1611            "members_synced": true,
1612            "last_prev_batch": "pb",
1613            "sync_info": "FullySynced",
1614            "encryption_state_synced": true,
1615            "latest_event_value": "None",
1616            "base_info": {
1617                "avatar": null,
1618                "canonical_alias": null,
1619                "create": null,
1620                "dm_targets": [],
1621                "encryption": null,
1622                "guest_access": null,
1623                "history_visibility": null,
1624                "is_marked_unread": false,
1625                "is_marked_unread_source": "Unstable",
1626                "join_rules": null,
1627                "max_power_level": 100,
1628                "member_hints": null,
1629                "name": null,
1630                "retention": null,
1631                "tombstone": null,
1632                "topic": null,
1633                "pinned_events": {
1634                    "pinned": ["$a"]
1635                },
1636            },
1637            "read_receipts": {
1638                "num_unread": 0,
1639                "num_mentions": 0,
1640                "num_notifications": 0,
1641                "latest_active": null,
1642                "pending": {
1643                    "items": [],
1644                    "capacity": 10,
1645                },
1646            },
1647            "recency_stamp": 42,
1648        });
1649
1650        assert_eq!(serde_json::to_value(info).unwrap(), info_json);
1651    }
1652
1653    #[async_test]
1654    async fn test_room_info_migration_v1() {
1655        let store = SaveLockedStateStore::new(MemoryStore::new().into_state_store());
1656
1657        let room_info_json = json!({
1658            "room_id": "!gda78o:server.tld",
1659            "room_state": "Joined",
1660            "notification_counts": {
1661                "highlight_count": 1,
1662                "notification_count": 2,
1663            },
1664            "summary": {
1665                "room_heroes": [{
1666                    "user_id": "@somebody:example.org",
1667                    "display_name": null,
1668                    "avatar_url": null
1669                }],
1670                "joined_member_count": 5,
1671                "invited_member_count": 0,
1672            },
1673            "members_synced": true,
1674            "last_prev_batch": "pb",
1675            "sync_info": "FullySynced",
1676            "encryption_state_synced": true,
1677            "latest_event": {
1678                "event": {
1679                    "encryption_info": null,
1680                    "event": {
1681                        "sender": "@u:i.uk",
1682                    },
1683                },
1684            },
1685            "base_info": {
1686                "avatar": null,
1687                "canonical_alias": null,
1688                "create": null,
1689                "dm_targets": [],
1690                "encryption": null,
1691                "guest_access": null,
1692                "history_visibility": null,
1693                "join_rules": null,
1694                "max_power_level": 100,
1695                "name": null,
1696                "tombstone": null,
1697                "topic": null,
1698            },
1699            "read_receipts": {
1700                "num_unread": 0,
1701                "num_mentions": 0,
1702                "num_notifications": 0,
1703                "latest_active": null,
1704                "pending": []
1705            },
1706            "recency_stamp": 42,
1707        });
1708        let mut room_info: RoomInfo = serde_json::from_value(room_info_json).unwrap();
1709
1710        assert_eq!(room_info.data_format_version, 0);
1711        assert!(room_info.base_info.notable_tags.is_empty());
1712        assert!(room_info.base_info.pinned_events.is_none());
1713
1714        // Apply migrations with an empty store.
1715        assert!(room_info.apply_migrations(store.clone()).await);
1716
1717        assert_eq!(room_info.data_format_version, 1);
1718        assert!(room_info.base_info.notable_tags.is_empty());
1719        assert!(room_info.base_info.pinned_events.is_none());
1720
1721        // Applying migrations again has no effect.
1722        assert!(!room_info.apply_migrations(store.clone()).await);
1723
1724        assert_eq!(room_info.data_format_version, 1);
1725        assert!(room_info.base_info.notable_tags.is_empty());
1726        assert!(room_info.base_info.pinned_events.is_none());
1727
1728        // Add events to the store.
1729        let mut changes = StateChanges::default();
1730
1731        let f = EventFactory::new().room(&room_info.room_id).sender(user_id!("@example:localhost"));
1732        let mut tags = Tags::new();
1733        tags.insert(TagName::Favorite, TagInfo::new());
1734        tags.insert(TagName::User(UserTagName::from_str("u.work").unwrap()), TagInfo::new());
1735        let raw_tag_event: Raw<AnyRoomAccountDataEvent> = f.tag(tags).into();
1736        let tag_event = raw_tag_event.deserialize().unwrap();
1737        changes.add_room_account_data(&room_info.room_id, tag_event, raw_tag_event);
1738
1739        let raw_pinned_events_event: Raw<_> = f
1740            .room_pinned_events(vec![owned_event_id!("$a"), owned_event_id!("$b")])
1741            .into_raw_sync_state();
1742        let pinned_events_event = raw_pinned_events_event.deserialize().unwrap();
1743        changes.add_state_event(&room_info.room_id, pinned_events_event, raw_pinned_events_event);
1744
1745        store.save_changes(&changes).await.unwrap();
1746
1747        // Reset to version 0 and reapply migrations.
1748        room_info.data_format_version = 0;
1749        assert!(room_info.apply_migrations(store.clone()).await);
1750
1751        assert_eq!(room_info.data_format_version, 1);
1752        assert!(room_info.base_info.notable_tags.contains(RoomNotableTags::FAVOURITE));
1753        assert!(room_info.base_info.pinned_events.is_some());
1754
1755        // Creating a new room info initializes it to version 1.
1756        let new_room_info = RoomInfo::new(room_id!("!new_room:localhost"), RoomState::Joined);
1757        assert_eq!(new_room_info.data_format_version, 1);
1758    }
1759
1760    #[test]
1761    fn test_room_info_deserialization() {
1762        let info_json = json!({
1763            "room_id": "!gda78o:server.tld",
1764            "room_state": "Joined",
1765            "notification_counts": {
1766                "highlight_count": 1,
1767                "notification_count": 2,
1768            },
1769            "summary": {
1770                "room_heroes": [{
1771                    "user_id": "@somebody:example.org",
1772                    "display_name": "Somebody",
1773                    "avatar_url": "mxc://example.org/abc"
1774                }],
1775                "joined_member_count": 5,
1776                "invited_member_count": 0,
1777            },
1778            "members_synced": true,
1779            "last_prev_batch": "pb",
1780            "sync_info": "FullySynced",
1781            "encryption_state_synced": true,
1782            "base_info": {
1783                "avatar": null,
1784                "canonical_alias": null,
1785                "create": null,
1786                "dm_targets": [],
1787                "encryption": null,
1788                "guest_access": null,
1789                "history_visibility": null,
1790                "join_rules": null,
1791                "max_power_level": 100,
1792                "member_hints": null,
1793                "name": null,
1794                "tombstone": null,
1795                "topic": null,
1796            },
1797            "cached_display_name": { "Calculated": "lol" },
1798            "cached_user_defined_notification_mode": "Mute",
1799            "recency_stamp": 42,
1800        });
1801
1802        let info: RoomInfo = serde_json::from_value(info_json).unwrap();
1803
1804        assert_eq!(info.room_id, "!gda78o:server.tld");
1805        assert_eq!(info.room_state, RoomState::Joined);
1806        assert_eq!(info.notification_counts.highlight_count, 1);
1807        assert_eq!(info.notification_counts.notification_count, 2);
1808        assert_eq!(
1809            info.summary.room_heroes,
1810            vec![RoomHero {
1811                user_id: owned_user_id!("@somebody:example.org"),
1812                display_name: Some("Somebody".to_owned()),
1813                avatar_url: Some(owned_mxc_uri!("mxc://example.org/abc")),
1814            }]
1815        );
1816        assert_eq!(info.summary.joined_member_count, 5);
1817        assert_eq!(info.summary.invited_member_count, 0);
1818        assert!(info.members_synced);
1819        assert_eq!(info.last_prev_batch, Some("pb".to_owned()));
1820        assert_eq!(info.sync_info, SyncInfo::FullySynced);
1821        assert!(info.encryption_state_synced);
1822        assert_matches!(info.latest_event_value, LatestEventValue::None);
1823        assert!(info.base_info.avatar.is_none());
1824        assert!(info.base_info.canonical_alias.is_none());
1825        assert!(info.base_info.create.is_none());
1826        assert_eq!(info.base_info.dm_targets.len(), 0);
1827        assert!(info.base_info.encryption.is_none());
1828        assert!(info.base_info.guest_access.is_none());
1829        assert!(info.base_info.history_visibility.is_none());
1830        assert!(info.base_info.join_rules.is_none());
1831        assert_eq!(info.base_info.max_power_level, 100);
1832        assert!(info.base_info.member_hints.is_none());
1833        assert!(info.base_info.name.is_none());
1834        assert!(info.base_info.tombstone.is_none());
1835        assert!(info.base_info.topic.is_none());
1836
1837        assert_eq!(
1838            info.cached_display_name.as_ref(),
1839            Some(&RoomDisplayName::Calculated("lol".to_owned())),
1840        );
1841        assert_eq!(
1842            info.cached_user_defined_notification_mode.as_ref(),
1843            Some(&RoomNotificationMode::Mute)
1844        );
1845        assert_eq!(info.recency_stamp.as_ref(), Some(&42.into()));
1846    }
1847
1848    // Ensure we can still deserialize RoomInfos before we added things to its
1849    // schema
1850    //
1851    // In an ideal world, we must not change this test. Please see
1852    // [`test_room_info_serialization`] if you want to test a “recent”
1853    // `RoomInfo` deserialization.
1854    #[test]
1855    fn test_room_info_deserialization_without_optional_items() {
1856        // The following JSON should never change if we want to be able to read
1857        // in old cached state
1858        let info_json = json!({
1859            "room_id": "!gda78o:server.tld",
1860            "room_state": "Invited",
1861            "notification_counts": {
1862                "highlight_count": 1,
1863                "notification_count": 2,
1864            },
1865            "summary": {
1866                "room_heroes": [{
1867                    "user_id": "@somebody:example.org",
1868                    "display_name": "Somebody",
1869                    "avatar_url": "mxc://example.org/abc"
1870                }],
1871                "joined_member_count": 5,
1872                "invited_member_count": 0,
1873            },
1874            "members_synced": true,
1875            "last_prev_batch": "pb",
1876            "sync_info": "FullySynced",
1877            "encryption_state_synced": true,
1878            "base_info": {
1879                "avatar": null,
1880                "canonical_alias": null,
1881                "create": null,
1882                "dm_targets": [],
1883                "encryption": null,
1884                "guest_access": null,
1885                "history_visibility": null,
1886                "join_rules": null,
1887                "max_power_level": 100,
1888                "name": null,
1889                "tombstone": null,
1890                "topic": null,
1891            },
1892        });
1893
1894        let info: RoomInfo = serde_json::from_value(info_json).unwrap();
1895
1896        assert_eq!(info.room_id, "!gda78o:server.tld");
1897        assert_eq!(info.room_state, RoomState::Invited);
1898        assert_eq!(info.notification_counts.highlight_count, 1);
1899        assert_eq!(info.notification_counts.notification_count, 2);
1900        assert_eq!(
1901            info.summary.room_heroes,
1902            vec![RoomHero {
1903                user_id: owned_user_id!("@somebody:example.org"),
1904                display_name: Some("Somebody".to_owned()),
1905                avatar_url: Some(owned_mxc_uri!("mxc://example.org/abc")),
1906            }]
1907        );
1908        assert_eq!(info.summary.joined_member_count, 5);
1909        assert_eq!(info.summary.invited_member_count, 0);
1910        assert!(info.members_synced);
1911        assert_eq!(info.last_prev_batch, Some("pb".to_owned()));
1912        assert_eq!(info.sync_info, SyncInfo::FullySynced);
1913        assert!(info.encryption_state_synced);
1914        assert!(info.base_info.avatar.is_none());
1915        assert!(info.base_info.canonical_alias.is_none());
1916        assert!(info.base_info.create.is_none());
1917        assert_eq!(info.base_info.dm_targets.len(), 0);
1918        assert!(info.base_info.encryption.is_none());
1919        assert!(info.base_info.guest_access.is_none());
1920        assert!(info.base_info.history_visibility.is_none());
1921        assert!(info.base_info.join_rules.is_none());
1922        assert_eq!(info.base_info.max_power_level, 100);
1923        assert!(info.base_info.name.is_none());
1924        assert!(info.base_info.tombstone.is_none());
1925        assert!(info.base_info.topic.is_none());
1926    }
1927
1928    #[test]
1929    fn test_member_hints_with_different_contents_reset_computed_value() {
1930        let expected = BTreeSet::from_iter([
1931            owned_user_id!("@alice:example.org"),
1932            owned_user_id!("@bob:example.org"),
1933        ]);
1934
1935        let info_json = json!({
1936            "room_id": "!gda78o:server.tld",
1937            "room_state": "Invited",
1938            "notification_counts": {
1939                "highlight_count": 1,
1940                "notification_count": 2,
1941            },
1942            "summary": {
1943                "room_heroes": [{
1944                    "user_id": "@somebody:example.org",
1945                    "display_name": "Somebody",
1946                    "avatar_url": "mxc://example.org/abc"
1947                }],
1948                "joined_member_count": 5,
1949                "invited_member_count": 0,
1950                "active_service_members": 2,
1951            },
1952            "members_synced": true,
1953            "last_prev_batch": "pb",
1954            "sync_info": "FullySynced",
1955            "encryption_state_synced": true,
1956            "base_info": {
1957                "avatar": null,
1958                "canonical_alias": null,
1959                "create": null,
1960                "dm_targets": [],
1961                "encryption": null,
1962                "guest_access": null,
1963                "history_visibility": null,
1964                "join_rules": null,
1965                "max_power_level": 100,
1966                "member_hints": {
1967                    "Original": {
1968                        "content": {
1969                            "service_members": ["@alice:example.org", "@bob:example.org"]
1970                        }
1971                    }
1972                },
1973                "name": null,
1974                "tombstone": null,
1975                "topic": null,
1976            },
1977        });
1978
1979        let info: RoomInfo = serde_json::from_value(info_json.clone()).unwrap();
1980        assert_eq!(info.base_info.member_hints.unwrap().content.service_members.unwrap(), expected);
1981        assert_eq!(info.summary.active_service_members, Some(2));
1982
1983        // We receive a new event with the same values as the stored ones
1984        let mut info: RoomInfo = serde_json::from_value(info_json.clone()).unwrap();
1985        let mut raw_state_event_with_keys = RawStateEventWithKeys::try_from_raw_state_event(
1986            EventFactory::new()
1987                .sender(user_id!("@alice:example.org"))
1988                .member_hints(expected.clone())
1989                .into_raw_sync_state(),
1990        )
1991        .expect("Expected member hints event is created");
1992
1993        info.handle_state_event(&mut raw_state_event_with_keys);
1994
1995        // Nothing changed
1996        assert_eq!(info.base_info.member_hints.unwrap().content.service_members.unwrap(), expected);
1997        // And the computed value is kept
1998        assert_eq!(info.summary.active_service_members, Some(2));
1999
2000        // We receive a new event with different values from the stored ones
2001        let mut info: RoomInfo = serde_json::from_value(info_json).unwrap();
2002        let new_member_hints = BTreeSet::from_iter([owned_user_id!("@alice:example.org")]);
2003        let mut raw_state_event_with_keys = RawStateEventWithKeys::try_from_raw_state_event(
2004            EventFactory::new()
2005                .sender(user_id!("@alice:example.org"))
2006                .member_hints(new_member_hints.clone())
2007                .into_raw_sync_state(),
2008        )
2009        .expect("New member hints event is created");
2010
2011        info.handle_state_event(&mut raw_state_event_with_keys);
2012
2013        // The new member hints were applied
2014        assert_eq!(
2015            info.base_info.member_hints.unwrap().content.service_members.unwrap(),
2016            new_member_hints
2017        );
2018        // And the computed value is reset
2019        assert!(info.summary.active_service_members.is_none());
2020    }
2021
2022    fn make_room_and_state_store(room_state: RoomState) -> (Room, SaveLockedStateStore) {
2023        let state_store = SaveLockedStateStore::new(MemoryStore::new().into_state_store());
2024        let user_id = user_id!("@user:localhost");
2025        let room_id = room_id!("!room:localhost");
2026        let (sender, _) = tokio::sync::broadcast::channel(1);
2027        let room = Room::new(user_id, state_store.clone(), room_id, room_state, sender);
2028        (room, state_store)
2029    }
2030
2031    #[async_test]
2032    async fn test_update_room_info_only_updates_in_memory_room_info() {
2033        let (room, state_store) = make_room_and_state_store(RoomState::Joined);
2034
2035        let before = room.clone_info();
2036        assert_eq!(before.state(), RoomState::Joined);
2037        room.update_room_info(|mut info| {
2038            info.mark_as_banned();
2039            (info, RoomInfoNotableUpdateReasons::MEMBERSHIP)
2040        })
2041        .await;
2042        let after = room.clone_info();
2043        assert_eq!(after.state(), RoomState::Banned);
2044
2045        let infos = state_store
2046            .get_room_infos(&RoomLoadSettings::One(room.room_id.clone()))
2047            .await
2048            .expect("get room info");
2049        assert!(infos.is_empty());
2050    }
2051
2052    #[async_test]
2053    async fn test_update_room_info_with_store_guard_only_updates_in_memory_room_info() {
2054        let (room, state_store) = make_room_and_state_store(RoomState::Joined);
2055
2056        let before = room.clone_info();
2057        assert_eq!(before.state(), RoomState::Joined);
2058        room.update_room_info_with_store_guard(&state_store.lock().lock().await, |mut info| {
2059            info.mark_as_banned();
2060            (info, RoomInfoNotableUpdateReasons::MEMBERSHIP)
2061        })
2062        .expect("update room info");
2063        let after = room.clone_info();
2064        assert_eq!(after.state(), RoomState::Banned);
2065
2066        let infos = state_store
2067            .get_room_infos(&RoomLoadSettings::One(room.room_id.clone()))
2068            .await
2069            .expect("get room info");
2070        assert!(infos.is_empty());
2071    }
2072
2073    #[async_test]
2074    async fn test_update_room_info_only_accepts_guard_for_underlying_mutex() {
2075        let (room, state_store) = make_room_and_state_store(RoomState::Joined);
2076
2077        room.update_room_info_with_store_guard(&state_store.lock().lock().await, |info| {
2078            (info, RoomInfoNotableUpdateReasons::NONE)
2079        })
2080        .expect("room accepts guard for underlying mutex");
2081
2082        let mutex = Mutex::new(());
2083        room.update_room_info_with_store_guard(&mutex.lock().await, |info| {
2084            (info, RoomInfoNotableUpdateReasons::NONE)
2085        })
2086        .expect_err("room does not accept guard for unknown mutex");
2087    }
2088
2089    #[async_test]
2090    async fn test_update_and_save_room_info_updates_room_info_in_memory_and_store() {
2091        let (room, state_store) = make_room_and_state_store(RoomState::Joined);
2092
2093        let before = room.clone_info();
2094        assert_eq!(before.state(), RoomState::Joined);
2095        room.update_and_save_room_info(|mut info| {
2096            info.mark_as_banned();
2097            (info, RoomInfoNotableUpdateReasons::MEMBERSHIP)
2098        })
2099        .await
2100        .expect("update and save room info");
2101        let after = room.clone_info();
2102        assert_eq!(after.state(), RoomState::Banned);
2103
2104        let infos = state_store
2105            .get_room_infos(&RoomLoadSettings::One(room.room_id.clone()))
2106            .await
2107            .expect("get room info");
2108        assert_eq!(infos.len(), 1);
2109        assert_matches!(infos.first(), Some(info) => {
2110            info.state() == RoomState::Banned
2111        });
2112    }
2113
2114    #[async_test]
2115    async fn test_update_and_save_room_info_with_store_guard_updates_room_info_in_memory_and_store()
2116    {
2117        let (room, state_store) = make_room_and_state_store(RoomState::Joined);
2118
2119        let before = room.clone_info();
2120        assert_eq!(before.state(), RoomState::Joined);
2121        room.update_and_save_room_info_with_store_guard(
2122            &state_store.lock().lock().await,
2123            |mut info| {
2124                info.mark_as_banned();
2125                (info, RoomInfoNotableUpdateReasons::MEMBERSHIP)
2126            },
2127        )
2128        .await
2129        .expect("update and save room info");
2130        let after = room.clone_info();
2131        assert_eq!(after.state(), RoomState::Banned);
2132
2133        let infos = state_store
2134            .get_room_infos(&RoomLoadSettings::One(room.room_id.clone()))
2135            .await
2136            .expect("get room info");
2137        assert_eq!(infos.len(), 1);
2138        assert_matches!(infos.first(), Some(info) => {
2139            info.state() == RoomState::Banned
2140        });
2141    }
2142
2143    #[async_test]
2144    async fn test_update_and_save_room_info_only_accepts_guard_for_underlying_mutex() {
2145        let (room, state_store) = make_room_and_state_store(RoomState::Joined);
2146
2147        room.update_and_save_room_info_with_store_guard(&state_store.lock().lock().await, |info| {
2148            (info, RoomInfoNotableUpdateReasons::NONE)
2149        })
2150        .await
2151        .expect("room accepts guard for underlying mutex");
2152
2153        let mutex = Mutex::new(());
2154        room.update_and_save_room_info_with_store_guard(&mutex.lock().await, |info| {
2155            (info, RoomInfoNotableUpdateReasons::NONE)
2156        })
2157        .await
2158        .expect_err("room does not accept guard for unknown mutex");
2159    }
2160
2161    #[derive(Debug)]
2162    struct Elapsed;
2163
2164    async fn timeout<F: Future + Unpin>(duration: Duration, f: F) -> Result<F::Output, Elapsed> {
2165        #[cfg(all(target_family = "wasm", target_os = "unknown"))]
2166        {
2167            match future::select(sleep(duration), f).await {
2168                Either::Left(_) => return Err(Elapsed),
2169                Either::Right((output, _)) => Ok(output),
2170            }
2171        }
2172        #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
2173        {
2174            tokio::time::timeout(duration, f).await.map_err(|_| Elapsed)
2175        }
2176    }
2177
2178    #[async_test]
2179    async fn test_update_room_info_waits_to_acquire_lock_before_updating_room_info() {
2180        let (room, state_store) = make_room_and_state_store(RoomState::Joined);
2181
2182        // Acquire lock and hold it for 5 seconds
2183        let lock_task = spawn({
2184            let state_store = state_store.clone();
2185            async move {
2186                let lock = state_store.lock();
2187                let _guard = lock.lock().await;
2188                sleep(Duration::from_secs(5)).await;
2189            }
2190        });
2191
2192        // Try to update room info while the lock is held by another task
2193        let save_task = spawn(async move {
2194            room.update_room_info(|info| (info, RoomInfoNotableUpdateReasons::NONE)).await
2195        });
2196
2197        // Ensure that the second task does not progress until the first task
2198        // has completed and, therefore, releases the save lock
2199        assert_matches!(future::select(lock_task, save_task).await, Either::Left((_, save_task)) => {
2200            timeout(Duration::from_millis(100), save_task)
2201                .await
2202                .expect("task completes before timeout")
2203                .expect("task completes successfully")
2204        });
2205    }
2206
2207    #[async_test]
2208    async fn test_update_and_save_room_info_waits_to_acquire_lock_before_updating_room_info() {
2209        let (room, state_store) = make_room_and_state_store(RoomState::Joined);
2210
2211        // Acquire lock and hold it for 5 seconds
2212        let lock_task = spawn({
2213            let state_store = state_store.clone();
2214            async move {
2215                let lock = state_store.lock();
2216                let _guard = lock.lock().await;
2217                sleep(Duration::from_secs(5)).await;
2218            }
2219        });
2220
2221        // Try to update room info while the lock is held by another task
2222        let save_task = spawn(async move {
2223            room.update_and_save_room_info(|info| (info, RoomInfoNotableUpdateReasons::NONE)).await
2224        });
2225
2226        // Ensure that the second task does not progress until the first task
2227        // has completed and, therefore, releases the save lock
2228        assert_matches!(future::select(lock_task, save_task).await, Either::Left((_, save_task)) => {
2229            timeout(Duration::from_millis(100), save_task)
2230                .await
2231                .expect("task completes before timeout")
2232                .expect("task completes successfully")
2233                .expect("update and save room info");
2234        });
2235    }
2236
2237    #[test]
2238    fn test_retention_stored_on_handle_state_event() {
2239        let mut info = RoomInfo::new(room_id!("!gda78o:server.tld"), RoomState::Joined);
2240        assert!(info.retention().is_none(), "retention should be absent before any event");
2241
2242        let max_lifetime = Duration::from_secs(86_400); // 1 day
2243        let content = RoomRetentionEventContent::new().at_most(max_lifetime).unwrap();
2244
2245        let mut raw = RawStateEventWithKeys::try_from_raw_state_event(
2246            EventFactory::new()
2247                .sender(user_id!("@alice:example.org"))
2248                .event(content)
2249                .state_key("")
2250                .into_raw_sync_state(),
2251        )
2252        .expect("retention state event should be constructable");
2253
2254        info.handle_state_event(&mut raw);
2255
2256        let retention = info.retention().expect("retention should be set after event");
2257        assert_eq!(retention.max_lifetime(), Some(max_lifetime));
2258        assert!(retention.min_lifetime().is_none());
2259    }
2260}