Skip to main content

matrix_sdk_base/room/
mod.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
15#![allow(clippy::assign_op_pattern)] // Triggered by bitflags! usage
16
17mod call;
18mod create;
19mod display_name;
20mod encryption;
21mod knock;
22mod latest_event;
23mod members;
24mod room_info;
25mod state;
26mod tags;
27mod tombstone;
28
29use std::{
30    collections::{BTreeMap, BTreeSet, HashSet},
31    sync::Arc,
32};
33
34pub use create::*;
35pub use display_name::{RoomDisplayName, RoomHero};
36pub(crate) use display_name::{RoomSummary, UpdatedRoomDisplayName};
37pub use encryption::EncryptionState;
38use eyeball::{AsyncLock, SharedObservable};
39use futures_util::{Stream, StreamExt};
40pub use members::{RoomMember, RoomMembersUpdate, RoomMemberships};
41pub(crate) use room_info::SyncInfo;
42pub use room_info::{
43    BaseRoomInfo, RoomInfo, RoomInfoNotableUpdate, RoomInfoNotableUpdateReasons, RoomRecencyStamp,
44    apply_redaction,
45};
46use ruma::{
47    EventId, OwnedEventId, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, RoomId,
48    RoomVersionId, UserId,
49    events::{
50        direct::OwnedDirectUserIdentifier,
51        receipt::{Receipt, ReceiptThread, ReceiptType},
52        room::{
53            avatar,
54            guest_access::GuestAccess,
55            history_visibility::HistoryVisibility,
56            join_rules::JoinRule,
57            power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent, RoomPowerLevelsSource},
58        },
59    },
60    room::RoomType,
61};
62use serde::{Deserialize, Serialize};
63pub use state::{RoomState, RoomStateFilter};
64pub(crate) use tags::RoomNotableTags;
65use tokio::sync::broadcast;
66pub use tombstone::{PredecessorRoom, SuccessorRoom};
67use tracing::{info, instrument, warn};
68
69use crate::{
70    Error,
71    deserialized_responses::MemberEvent,
72    notification_settings::RoomNotificationMode,
73    read_receipts::RoomReadReceipts,
74    store::{DynStateStore, Result as StoreResult, StateStoreExt},
75    sync::UnreadNotificationsCount,
76};
77
78/// The underlying room data structure collecting state for joined, left and
79/// invited rooms.
80#[derive(Debug, Clone)]
81pub struct Room {
82    /// The room ID.
83    pub(super) room_id: OwnedRoomId,
84
85    /// Our own user ID.
86    pub(super) own_user_id: OwnedUserId,
87
88    pub(super) info: SharedObservable<RoomInfo>,
89
90    /// A clone of the [`BaseStateStore::room_info_notable_update_sender`].
91    ///
92    /// [`BaseStateStore::room_info_notable_update_sender`]: crate::store::BaseStateStore::room_info_notable_update_sender
93    pub(super) room_info_notable_update_sender: broadcast::Sender<RoomInfoNotableUpdate>,
94
95    /// A clone of the state store.
96    pub(super) store: Arc<DynStateStore>,
97
98    /// A map for ids of room membership events in the knocking state linked to
99    /// the user id of the user affected by the member event, that the current
100    /// user has marked as seen so they can be ignored.
101    pub seen_knock_request_ids_map:
102        SharedObservable<Option<BTreeMap<OwnedEventId, OwnedUserId>>, AsyncLock>,
103
104    /// A sender that will notify receivers when room member updates happen.
105    pub room_member_updates_sender: broadcast::Sender<RoomMembersUpdate>,
106}
107
108impl Room {
109    pub(crate) fn new(
110        own_user_id: &UserId,
111        store: Arc<DynStateStore>,
112        room_id: &RoomId,
113        room_state: RoomState,
114        room_info_notable_update_sender: broadcast::Sender<RoomInfoNotableUpdate>,
115    ) -> Self {
116        let room_info = RoomInfo::new(room_id, room_state);
117        Self::restore(own_user_id, store, room_info, room_info_notable_update_sender)
118    }
119
120    pub(crate) fn restore(
121        own_user_id: &UserId,
122        store: Arc<DynStateStore>,
123        room_info: RoomInfo,
124        room_info_notable_update_sender: broadcast::Sender<RoomInfoNotableUpdate>,
125    ) -> Self {
126        let (room_member_updates_sender, _) = broadcast::channel(10);
127        Self {
128            own_user_id: own_user_id.into(),
129            room_id: room_info.room_id.clone(),
130            store,
131            info: SharedObservable::new(room_info),
132            room_info_notable_update_sender,
133            seen_knock_request_ids_map: SharedObservable::new_async(None),
134            room_member_updates_sender,
135        }
136    }
137
138    /// Get the unique room id of the room.
139    pub fn room_id(&self) -> &RoomId {
140        &self.room_id
141    }
142
143    /// Get a copy of the room creators.
144    pub fn creators(&self) -> Option<Vec<OwnedUserId>> {
145        self.info.read().creators()
146    }
147
148    /// Get our own user id.
149    pub fn own_user_id(&self) -> &UserId {
150        &self.own_user_id
151    }
152
153    /// Whether this room's [`RoomType`] is `m.space`.
154    pub fn is_space(&self) -> bool {
155        self.info.read().room_type().is_some_and(|t| *t == RoomType::Space)
156    }
157
158    /// Returns the room's type as defined in its creation event
159    /// (`m.room.create`).
160    pub fn room_type(&self) -> Option<RoomType> {
161        self.info.read().room_type().map(ToOwned::to_owned)
162    }
163
164    /// Get the unread notification counts.
165    pub fn unread_notification_counts(&self) -> UnreadNotificationsCount {
166        self.info.read().notification_counts
167    }
168
169    /// Get the number of unread messages (computed client-side).
170    ///
171    /// This might be more precise than [`Self::unread_notification_counts`] for
172    /// encrypted rooms.
173    pub fn num_unread_messages(&self) -> u64 {
174        self.info.read().read_receipts.num_unread
175    }
176
177    /// Get the detailed information about read receipts for the room.
178    pub fn read_receipts(&self) -> RoomReadReceipts {
179        self.info.read().read_receipts.clone()
180    }
181
182    /// Get the number of unread notifications (computed client-side).
183    ///
184    /// This might be more precise than [`Self::unread_notification_counts`] for
185    /// encrypted rooms.
186    pub fn num_unread_notifications(&self) -> u64 {
187        self.info.read().read_receipts.num_notifications
188    }
189
190    /// Get the number of unread mentions (computed client-side), that is,
191    /// messages causing a highlight in a room.
192    ///
193    /// This might be more precise than [`Self::unread_notification_counts`] for
194    /// encrypted rooms.
195    pub fn num_unread_mentions(&self) -> u64 {
196        self.info.read().read_receipts.num_mentions
197    }
198
199    /// Check if the room states have been synced
200    ///
201    /// States might be missing if we have only seen the room_id of this Room
202    /// so far, for example as the response for a `create_room` request without
203    /// being synced yet.
204    ///
205    /// Returns true if the state is fully synced, false otherwise.
206    pub fn is_state_fully_synced(&self) -> bool {
207        self.info.read().sync_info == SyncInfo::FullySynced
208    }
209
210    /// Check if the room state has been at least partially synced.
211    ///
212    /// See [`Room::is_state_fully_synced`] for more info.
213    pub fn is_state_partially_or_fully_synced(&self) -> bool {
214        self.info.read().sync_info != SyncInfo::NoState
215    }
216
217    /// Get the `prev_batch` token that was received from the last sync. May be
218    /// `None` if the last sync contained the full room history.
219    pub fn last_prev_batch(&self) -> Option<String> {
220        self.info.read().last_prev_batch.clone()
221    }
222
223    /// Get the avatar url of this room.
224    pub fn avatar_url(&self) -> Option<OwnedMxcUri> {
225        self.info.read().avatar_url().map(ToOwned::to_owned)
226    }
227
228    /// Get information about the avatar of this room.
229    pub fn avatar_info(&self) -> Option<avatar::ImageInfo> {
230        self.info.read().avatar_info().map(ToOwned::to_owned)
231    }
232
233    /// Get the canonical alias of this room.
234    pub fn canonical_alias(&self) -> Option<OwnedRoomAliasId> {
235        self.info.read().canonical_alias().map(ToOwned::to_owned)
236    }
237
238    /// Get the canonical alias of this room.
239    pub fn alt_aliases(&self) -> Vec<OwnedRoomAliasId> {
240        self.info.read().alt_aliases().to_owned()
241    }
242
243    /// Get the `m.room.create` content of this room.
244    ///
245    /// This usually isn't optional but some servers might not send an
246    /// `m.room.create` event as the first event for a given room, thus this can
247    /// be optional.
248    ///
249    /// For room versions earlier than room version 11, if the event is
250    /// redacted, all fields except `creator` will be set to their default
251    /// value.
252    pub fn create_content(&self) -> Option<RoomCreateWithCreatorEventContent> {
253        Some(self.info.read().base_info.create.as_ref()?.content.clone())
254    }
255
256    /// Is this room considered a direct message.
257    ///
258    /// Async because it can read room info from storage.
259    #[instrument(skip_all, fields(room_id = ?self.room_id))]
260    pub async fn is_direct(&self) -> StoreResult<bool> {
261        match self.state() {
262            RoomState::Joined | RoomState::Left | RoomState::Banned => {
263                Ok(!self.info.read().base_info.dm_targets.is_empty())
264            }
265
266            RoomState::Invited => {
267                let member = self.get_member(self.own_user_id()).await?;
268
269                match member {
270                    None => {
271                        info!("RoomMember not found for the user's own id");
272                        Ok(false)
273                    }
274                    Some(member) => match member.event.as_ref() {
275                        MemberEvent::Sync(_) => {
276                            warn!("Got MemberEvent::Sync in an invited room");
277                            Ok(false)
278                        }
279                        MemberEvent::Stripped(event) => {
280                            Ok(event.content.is_direct.unwrap_or(false))
281                        }
282                    },
283                }
284            }
285
286            // TODO: implement logic once we have the stripped events as we'd have with an Invite
287            RoomState::Knocked => Ok(false),
288        }
289    }
290
291    /// If this room is a direct message, get the members that we're sharing the
292    /// room with.
293    ///
294    /// *Note*: The member list might have been modified in the meantime and
295    /// the targets might not even be in the room anymore. This setting should
296    /// only be considered as guidance. We leave members in this list to allow
297    /// us to re-find a DM with a user even if they have left, since we may
298    /// want to re-invite them.
299    pub fn direct_targets(&self) -> HashSet<OwnedDirectUserIdentifier> {
300        self.info.read().base_info.dm_targets.clone()
301    }
302
303    /// If this room is a direct message, returns the number of members that
304    /// we're sharing the room with.
305    pub fn direct_targets_length(&self) -> usize {
306        self.info.read().base_info.dm_targets.len()
307    }
308
309    /// Get the guest access policy of this room.
310    pub fn guest_access(&self) -> GuestAccess {
311        self.info.read().guest_access().clone()
312    }
313
314    /// Get the history visibility policy of this room.
315    pub fn history_visibility(&self) -> Option<HistoryVisibility> {
316        self.info.read().history_visibility().cloned()
317    }
318
319    /// Get the history visibility policy of this room, or a sensible default if
320    /// the event is missing.
321    pub fn history_visibility_or_default(&self) -> HistoryVisibility {
322        self.info.read().history_visibility_or_default().clone()
323    }
324
325    /// Is the room considered to be public.
326    ///
327    /// May return `None` if the join rule event is not available.
328    pub fn is_public(&self) -> Option<bool> {
329        self.info.read().join_rule().map(|join_rule| matches!(join_rule, JoinRule::Public))
330    }
331
332    /// Get the join rule policy of this room, if available.
333    pub fn join_rule(&self) -> Option<JoinRule> {
334        self.info.read().join_rule().cloned()
335    }
336
337    /// Get the maximum power level that this room contains.
338    ///
339    /// This is useful if one wishes to normalize the power levels, e.g. from
340    /// 0-100 where 100 would be the max power level.
341    pub fn max_power_level(&self) -> i64 {
342        self.info.read().base_info.max_power_level
343    }
344
345    /// Get the service members in this room, if available.
346    pub fn service_members(&self) -> Option<BTreeSet<OwnedUserId>> {
347        self.info.read().service_members().cloned()
348    }
349
350    /// Get the current power levels of this room.
351    pub async fn power_levels(&self) -> Result<RoomPowerLevels, Error> {
352        let power_levels_content = self
353            .store
354            .get_state_event_static::<RoomPowerLevelsEventContent>(self.room_id())
355            .await?
356            .ok_or(Error::InsufficientData)?
357            .deserialize()?;
358        let creators = self.creators().ok_or(Error::InsufficientData)?;
359        let rules = self.info.read().room_version_rules_or_default();
360
361        Ok(power_levels_content.power_levels(&rules.authorization, creators))
362    }
363
364    /// Get the current power levels of this room, or a sensible default if they
365    /// are not known.
366    pub async fn power_levels_or_default(&self) -> RoomPowerLevels {
367        if let Ok(power_levels) = self.power_levels().await {
368            return power_levels;
369        }
370
371        // As a fallback, create the default power levels of a room.
372        let rules = self.info.read().room_version_rules_or_default();
373        RoomPowerLevels::new(
374            RoomPowerLevelsSource::None,
375            &rules.authorization,
376            self.creators().into_iter().flatten(),
377        )
378    }
379
380    /// Get the `m.room.name` of this room.
381    ///
382    /// The returned string may be empty if the event has been redacted, or it's
383    /// missing from storage.
384    pub fn name(&self) -> Option<String> {
385        self.info.read().name().map(ToOwned::to_owned)
386    }
387
388    /// Get the topic of the room.
389    pub fn topic(&self) -> Option<String> {
390        self.info.read().topic().map(ToOwned::to_owned)
391    }
392
393    /// Update the cached user defined notification mode.
394    ///
395    /// This is automatically recomputed on every successful sync, and the
396    /// cached result can be retrieved in
397    /// [`Self::cached_user_defined_notification_mode`].
398    pub fn update_cached_user_defined_notification_mode(&self, mode: RoomNotificationMode) {
399        self.info.update_if(|info| {
400            if info.cached_user_defined_notification_mode.as_ref() != Some(&mode) {
401                info.cached_user_defined_notification_mode = Some(mode);
402
403                true
404            } else {
405                false
406            }
407        });
408    }
409
410    /// Returns the cached user defined notification mode, if available.
411    ///
412    /// This cache is refilled every time we call
413    /// [`Self::update_cached_user_defined_notification_mode`].
414    pub fn cached_user_defined_notification_mode(&self) -> Option<RoomNotificationMode> {
415        self.info.read().cached_user_defined_notification_mode
416    }
417
418    /// Removes any existing cached value for the user defined notification
419    /// mode.
420    pub fn clear_user_defined_notification_mode(&self) {
421        self.info.update_if(|info| {
422            if info.cached_user_defined_notification_mode.is_some() {
423                info.cached_user_defined_notification_mode = None;
424                true
425            } else {
426                false
427            }
428        })
429    }
430
431    /// Get the list of users ids that are considered to be joined members of
432    /// this room.
433    pub async fn joined_user_ids(&self) -> StoreResult<Vec<OwnedUserId>> {
434        self.store.get_user_ids(self.room_id(), RoomMemberships::JOIN).await
435    }
436
437    /// Get the heroes for this room.
438    pub fn heroes(&self) -> Vec<RoomHero> {
439        self.info.read().heroes().to_vec()
440    }
441
442    /// Get the receipt as an `OwnedEventId` and `Receipt` tuple for the given
443    /// `receipt_type`, `thread` and `user_id` in this room.
444    pub async fn load_user_receipt(
445        &self,
446        receipt_type: ReceiptType,
447        thread: ReceiptThread,
448        user_id: &UserId,
449    ) -> StoreResult<Option<(OwnedEventId, Receipt)>> {
450        self.store.get_user_room_receipt_event(self.room_id(), receipt_type, thread, user_id).await
451    }
452
453    /// Load from storage the receipts as a list of `OwnedUserId` and `Receipt`
454    /// tuples for the given `receipt_type`, `thread` and `event_id` in this
455    /// room.
456    pub async fn load_event_receipts(
457        &self,
458        receipt_type: ReceiptType,
459        thread: ReceiptThread,
460        event_id: &EventId,
461    ) -> StoreResult<Vec<(OwnedUserId, Receipt)>> {
462        self.store
463            .get_event_room_receipt_events(self.room_id(), receipt_type, thread, event_id)
464            .await
465    }
466
467    /// Returns a boolean indicating if this room has been manually marked as
468    /// unread
469    pub fn is_marked_unread(&self) -> bool {
470        self.info.read().base_info.is_marked_unread
471    }
472
473    /// Returns the [`RoomVersionId`] of the room, if known.
474    pub fn version(&self) -> Option<RoomVersionId> {
475        self.info.read().room_version().cloned()
476    }
477
478    /// Returns the recency stamp of the room.
479    ///
480    /// Please read `RoomInfo::recency_stamp` to learn more.
481    pub fn recency_stamp(&self) -> Option<RoomRecencyStamp> {
482        self.info.read().recency_stamp
483    }
484
485    /// Get a `Stream` of loaded pinned events for this room.
486    /// If no pinned events are found a single empty `Vec` will be returned.
487    pub fn pinned_event_ids_stream(&self) -> impl Stream<Item = Vec<OwnedEventId>> + use<> {
488        self.info
489            .subscribe()
490            .map(|i| i.base_info.pinned_events.map(|c| c.pinned).unwrap_or_default())
491    }
492
493    /// Returns the current pinned event ids for this room.
494    pub fn pinned_event_ids(&self) -> Option<Vec<OwnedEventId>> {
495        self.info.read().pinned_event_ids()
496    }
497}
498
499// See https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823.
500#[cfg(not(feature = "test-send-sync"))]
501unsafe impl Send for Room {}
502
503// See https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823.
504#[cfg(not(feature = "test-send-sync"))]
505unsafe impl Sync for Room {}
506
507#[cfg(feature = "test-send-sync")]
508#[test]
509// See https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823.
510fn test_send_sync_for_room() {
511    fn assert_send_sync<
512        T: matrix_sdk_common::SendOutsideWasm + matrix_sdk_common::SyncOutsideWasm,
513    >() {
514    }
515
516    assert_send_sync::<Room>();
517}
518
519/// The possible sources of an account data type.
520#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
521pub(crate) enum AccountDataSource {
522    /// The source is account data with the stable prefix.
523    Stable,
524
525    /// The source is account data with the unstable prefix.
526    #[default]
527    Unstable,
528}