Skip to main content

matrix_sdk_base/
client.rs

1// Copyright 2020 Damir Jelić
2// Copyright 2020 The Matrix.org Foundation C.I.C.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#[cfg(feature = "e2e-encryption")]
17use std::sync::Arc;
18#[cfg(all(feature = "e2e-encryption", feature = "unstable-msc4354"))]
19use std::sync::Mutex as StdMutex;
20use std::{
21    collections::{BTreeMap, BTreeSet, HashMap},
22    fmt,
23    ops::Deref,
24};
25
26use eyeball::{SharedObservable, Subscriber};
27use eyeball_im::{Vector, VectorDiff};
28use futures_util::Stream;
29#[cfg(all(feature = "e2e-encryption", feature = "unstable-msc4354"))]
30use matrix_sdk_common::executor::AbortOnDrop;
31use matrix_sdk_common::{cross_process_lock::CrossProcessLockConfig, timer};
32#[cfg(feature = "experimental-x509-identity-verification")]
33use matrix_sdk_crypto::x509::{RawX509Signer, RawX509Verifier};
34#[cfg(feature = "e2e-encryption")]
35use matrix_sdk_crypto::{
36    CollectStrategy, DecryptionSettings, EncryptionSettings, OlmError, OlmMachine,
37    OlmMachineBuilder, TrustRequirement, store::DynCryptoStore,
38    store::types::RoomPendingKeyBundleDetails, types::requests::ToDeviceRequest,
39};
40#[cfg(doc)]
41use ruma::DeviceId;
42#[cfg(feature = "unstable-msc4536")]
43use ruma::MilliSecondsSinceUnixEpoch;
44#[cfg(feature = "e2e-encryption")]
45use ruma::events::room::{history_visibility::HistoryVisibility, member::MembershipState};
46use ruma::{
47    OwnedRoomId, OwnedUserId, RoomId, UserId,
48    api::client::{self as api, sync::sync_events::msc4186},
49    events::{
50        StateEvent, StateEventType,
51        ignored_user_list::IgnoredUserListEventContent,
52        push_rules::{PushRulesEvent, PushRulesEventContent},
53        room::member::SyncRoomMemberEvent,
54    },
55    profile::UserProfileUpdate,
56    push::Ruleset,
57};
58use tokio::sync::{Mutex, MutexGuard, broadcast};
59#[cfg(feature = "e2e-encryption")]
60use tokio::sync::{RwLock, RwLockReadGuard};
61use tracing::{Level, debug, info, instrument, warn};
62
63#[cfg(feature = "e2e-encryption")]
64use crate::RoomMemberships;
65use crate::{
66    RoomStateFilter, SessionMeta, StateStore,
67    deserialized_responses::DisplayName,
68    error::{Error, Result},
69    event_cache::store::EventCacheStoreLock,
70    media::store::MediaStoreLock,
71    response_processors::{self as processors, Context},
72    room::{
73        Room, RoomInfoNotableUpdate, RoomInfoNotableUpdateReasons, RoomMembersUpdate, RoomState,
74    },
75    store::{
76        AvatarCache, BaseStateStore, DynStateStore, MemoryStore, Result as StoreResult,
77        RoomLoadSettings, StateChanges, StateStoreDataKey, StateStoreDataValue, StateStoreExt,
78        StoreConfig,
79        ambiguity_map::{AmbiguityCache, is_member_active},
80    },
81    sync::{RoomUpdates, SyncResponse},
82};
83
84/// A no (network) IO client implementation.
85///
86/// This client is a state machine that receives responses and events and
87/// accordingly updates its state. It is not designed to be used directly, but
88/// rather through `matrix_sdk::Client`.
89///
90/// ```rust
91/// use matrix_sdk_base::{
92///     BaseClient, DmRoomDefinition, ThreadingSupport, store::StoreConfig,
93/// };
94/// use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
95///
96/// let client = BaseClient::new(
97///     StoreConfig::new(CrossProcessLockConfig::multi_process(
98///         "cross-process-holder-name".to_owned(),
99///     )),
100///     ThreadingSupport::Disabled,
101///     DmRoomDefinition::default(),
102/// );
103/// ```
104#[derive(Clone)]
105pub struct BaseClient {
106    /// The state store.
107    pub(crate) state_store: BaseStateStore,
108
109    /// The store used by the event cache.
110    event_cache_store: EventCacheStoreLock,
111
112    /// The store used by the media cache.
113    media_store: MediaStoreLock,
114
115    /// The store used for encryption.
116    ///
117    /// This field is only meant to be used for `OlmMachine` initialization. All
118    /// operations on it happen inside the `OlmMachine`.
119    #[cfg(feature = "e2e-encryption")]
120    crypto_store: Arc<DynCryptoStore>,
121
122    /// The olm-machine that is created once the
123    /// [`SessionMeta`][crate::session::SessionMeta] is set via
124    /// [`BaseClient::activate`]
125    #[cfg(feature = "e2e-encryption")]
126    olm_machine: Arc<RwLock<Option<OlmMachine>>>,
127
128    /// Observable of when a user is ignored/unignored.
129    pub(crate) ignore_user_list_changes: SharedObservable<Vec<OwnedUserId>>,
130
131    /// Broadcasts the user IDs whose global profile changed during a sync.
132    /// Requires the Profiles sliding sync extension to be enabled.
133    pub(crate) global_profile_updates_sender: broadcast::Sender<BTreeSet<OwnedUserId>>,
134
135    /// The strategy to use for picking recipient devices, when sending an
136    /// encrypted message.
137    #[cfg(feature = "e2e-encryption")]
138    pub room_key_recipient_strategy: CollectStrategy,
139
140    /// The settings to use for decrypting events.
141    #[cfg(feature = "e2e-encryption")]
142    pub decryption_settings: DecryptionSettings,
143
144    /// If the client should handle verification events received when syncing.
145    #[cfg(feature = "e2e-encryption")]
146    pub handle_verification_events: bool,
147
148    /// The task retrying to decrypt encrypted sticky events (MSC4354) as room
149    /// keys arrive. Bound to the room keys stream of the current `OlmMachine`,
150    /// so it is replaced whenever the machine is.
151    #[cfg(all(feature = "e2e-encryption", feature = "unstable-msc4354"))]
152    sticky_redecryptor: Arc<StdMutex<Option<AbortOnDrop<()>>>>,
153
154    /// Whether the client supports threads or not.
155    pub threading_support: ThreadingSupport,
156
157    /// If supported, the signer that allows us to sign our cross-signing key
158    /// with an X.509 certificate.
159    #[cfg(feature = "experimental-x509-identity-verification")]
160    x509_signer: Option<Arc<dyn RawX509Signer>>,
161
162    /// If supported, the verifier that allows us to verify that items have been
163    /// signed by a valid X.509 certificate.
164    #[cfg(feature = "experimental-x509-identity-verification")]
165    x509_verifier: Option<Arc<dyn RawX509Verifier>>,
166
167    /// The definition of what is considered a DM room.
168    pub dm_room_definition: DmRoomDefinition,
169}
170
171#[cfg(not(tarpaulin_include))]
172impl fmt::Debug for BaseClient {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        f.debug_struct("BaseClient")
175            .field("session_meta", &self.state_store.session_meta())
176            .field("sync_token", &self.state_store.sync_token)
177            .finish_non_exhaustive()
178    }
179}
180
181/// Whether this client instance supports threading or not. Currently used to
182/// determine how the client handles read receipts and unread count computations
183/// on the base SDK level.
184///
185/// Timelines on the other hand have a separate `TimelineFocus`
186/// `hide_threaded_events` associated value that can be used to hide threaded
187/// events but also to enable threaded read receipt sending. This is because
188/// certain timeline instances should ignore threading no matter what's defined
189/// at the client level. One such example are media filtered timelines which
190/// should contain all the room's media no matter what thread its in (unless
191/// explicitly opted into).
192#[derive(Clone, Copy, Debug)]
193pub enum ThreadingSupport {
194    /// Threading enabled.
195    Enabled {
196        /// Enable client-wide thread subscriptions support (MSC4306 / MSC4308).
197        ///
198        /// This may cause filtering out of thread subscriptions, and loading
199        /// the thread subscriptions via the sliding sync extension, when the
200        /// room list service is being used.
201        with_subscriptions: bool,
202    },
203    /// Threading disabled.
204    Disabled,
205}
206
207impl BaseClient {
208    /// Create a new client.
209    ///
210    /// # Arguments
211    ///
212    /// - `config` - the configuration for the stores (state store, event cache
213    ///   store and crypto store).
214    pub fn new(
215        config: StoreConfig,
216        threading_support: ThreadingSupport,
217        dm_room_definition: DmRoomDefinition,
218    ) -> Self {
219        let store = BaseStateStore::new(config.state_store);
220
221        BaseClient {
222            state_store: store,
223            event_cache_store: config.event_cache_store,
224            media_store: config.media_store,
225            #[cfg(feature = "e2e-encryption")]
226            crypto_store: config.crypto_store,
227            #[cfg(feature = "e2e-encryption")]
228            olm_machine: Default::default(),
229            ignore_user_list_changes: Default::default(),
230            global_profile_updates_sender: broadcast::Sender::new(16),
231            #[cfg(feature = "e2e-encryption")]
232            room_key_recipient_strategy: Default::default(),
233            #[cfg(feature = "e2e-encryption")]
234            decryption_settings: DecryptionSettings {
235                sender_device_trust_requirement: TrustRequirement::Untrusted,
236            },
237            #[cfg(feature = "e2e-encryption")]
238            handle_verification_events: true,
239            #[cfg(all(feature = "e2e-encryption", feature = "unstable-msc4354"))]
240            sticky_redecryptor: Default::default(),
241            threading_support,
242            #[cfg(feature = "experimental-x509-identity-verification")]
243            x509_signer: None,
244            #[cfg(feature = "experimental-x509-identity-verification")]
245            x509_verifier: None,
246            dm_room_definition,
247        }
248    }
249
250    /// Clones the current base client to use the same crypto store but a
251    /// different, in-memory store config, and resets transient state.
252    #[cfg(feature = "e2e-encryption")]
253    pub async fn clone_with_in_memory_state_store(
254        &self,
255        cross_process_mode: CrossProcessLockConfig,
256        handle_verification_events: bool,
257    ) -> Result<Self> {
258        let config = StoreConfig::new(cross_process_mode).state_store(MemoryStore::new());
259        let config = config.crypto_store(self.crypto_store.clone());
260
261        let copy = Self {
262            state_store: BaseStateStore::new(config.state_store),
263            event_cache_store: config.event_cache_store,
264            media_store: config.media_store,
265            // We copy the crypto store as well as the `OlmMachine` for two
266            // reasons:
267            //
268            // 1. The `self.crypto_store` is the same as the one used inside the `OlmMachine`.
269            // 2. We need to ensure that the parent and child use the same data and caches inside
270            //    the `OlmMachine` so the various ratchets and places where new randomness gets
271            //    introduced don't diverge, i.e. one-time keys that get generated by the Olm Account
272            //    or Olm sessions when they encrypt or decrypt messages.
273            crypto_store: self.crypto_store.clone(),
274            olm_machine: self.olm_machine.clone(),
275            ignore_user_list_changes: Default::default(),
276            global_profile_updates_sender: broadcast::Sender::new(16),
277            room_key_recipient_strategy: self.room_key_recipient_strategy.clone(),
278            decryption_settings: self.decryption_settings.clone(),
279            handle_verification_events,
280            #[cfg(feature = "unstable-msc4354")]
281            sticky_redecryptor: Default::default(),
282            threading_support: self.threading_support,
283            #[cfg(feature = "experimental-x509-identity-verification")]
284            x509_signer: self.x509_signer.clone(),
285            #[cfg(feature = "experimental-x509-identity-verification")]
286            x509_verifier: self.x509_verifier.clone(),
287            dm_room_definition: self.dm_room_definition.clone(),
288        };
289
290        copy.state_store.derive_from_other(&self.state_store).await?;
291
292        Ok(copy)
293    }
294
295    /// Provide the signer we will use to sign master signing keys and outgoing
296    /// secret requests.
297    #[cfg(feature = "experimental-x509-identity-verification")]
298    pub fn set_x509_signer(&mut self, x509_signer: Option<Arc<dyn RawX509Signer>>) {
299        self.x509_signer = x509_signer;
300    }
301
302    /// Provide the verifier we will use to verify master signing keys and
303    /// incoming secret requests.
304    #[cfg(feature = "experimental-x509-identity-verification")]
305    pub fn set_x509_verifier(&mut self, x509_verifier: Option<Arc<dyn RawX509Verifier>>) {
306        self.x509_verifier = x509_verifier
307    }
308
309    /// Clones the current base client to use the same crypto store but a
310    /// different, in-memory store config, and resets transient state.
311    #[cfg(not(feature = "e2e-encryption"))]
312    #[allow(clippy::unused_async)]
313    pub async fn clone_with_in_memory_state_store(
314        &self,
315        cross_process_store_config: CrossProcessLockConfig,
316        _handle_verification_events: bool,
317    ) -> Result<Self> {
318        let config = StoreConfig::new(cross_process_store_config).state_store(MemoryStore::new());
319        Ok(Self::new(config, ThreadingSupport::Disabled, DmRoomDefinition::default()))
320    }
321
322    /// Get the session meta information.
323    ///
324    /// If the client is currently logged in, this will return a [`SessionMeta`]
325    /// object which contains the user ID and device ID. Otherwise it returns
326    /// `None`.
327    pub fn session_meta(&self) -> Option<&SessionMeta> {
328        self.state_store.session_meta()
329    }
330
331    /// Get all the rooms this client knows about.
332    pub fn rooms(&self) -> Vec<Room> {
333        self.state_store.rooms()
334    }
335
336    /// Get all the rooms this client knows about, filtered by room state.
337    pub fn rooms_filtered(&self, filter: RoomStateFilter) -> Vec<Room> {
338        self.state_store.rooms_filtered(filter)
339    }
340
341    /// Get a stream of all the rooms changes, in addition to the existing
342    /// rooms.
343    pub fn rooms_stream(
344        &self,
345    ) -> (Vector<Room>, impl Stream<Item = Vec<VectorDiff<Room>>> + use<>) {
346        self.state_store.rooms_stream()
347    }
348
349    /// Lookup the Room for the given RoomId, or create one, if it didn't exist
350    /// yet in the store
351    pub fn get_or_create_room(&self, room_id: &RoomId, room_state: RoomState) -> Room {
352        self.state_store.get_or_create_room(room_id, room_state)
353    }
354
355    /// Get a reference to the state store.
356    pub fn state_store(&self) -> &DynStateStore {
357        self.state_store.deref()
358    }
359
360    /// Get a reference to the event cache store.
361    pub fn event_cache_store(&self) -> &EventCacheStoreLock {
362        &self.event_cache_store
363    }
364
365    /// Get a reference to the media store.
366    pub fn media_store(&self) -> &MediaStoreLock {
367        &self.media_store
368    }
369
370    /// Check whether the client has been activated.
371    ///
372    /// See [`BaseClient::activate`] to know what it means.
373    pub fn is_active(&self) -> bool {
374        self.state_store.session_meta().is_some()
375    }
376
377    /// Activate the client.
378    ///
379    /// A client is considered active when:
380    ///
381    /// 1. It has a `SessionMeta` (user ID, device ID and access token),
382    /// 2. Has loaded cached data from storage,
383    /// 3. If encryption is enabled, it also initialized or restored its
384    ///    `OlmMachine`.
385    ///
386    /// # Arguments
387    ///
388    /// - `session_meta` - The meta of a session that the user already has from
389    ///   a previous login call.
390    /// - `room_load_settings` — Specify how many rooms must be restored; use
391    ///   `::default()` if you don't know which value to pick.
392    /// - `custom_account` - A custom
393    ///   [`matrix_sdk_crypto::vodozemac::olm::Account`] to be used for the
394    ///   identity and one-time keys of this [`BaseClient`]. If no account is
395    ///   provided, a new default one or one from the store will be used. If an
396    ///   account is provided and one already exists in the store for this
397    ///   [`UserId`]/[`DeviceId`] combination, an error will be raised. This is
398    ///   useful if one wishes to create identity keys before knowing the
399    ///   user/device IDs, e.g., to use the identity key as the device ID.
400    ///
401    /// # Panics
402    ///
403    /// This method panics if it is called twice.
404    ///
405    /// [`UserId`]: ruma::UserId
406    pub async fn activate(
407        &self,
408        session_meta: SessionMeta,
409        room_load_settings: RoomLoadSettings,
410        #[cfg(feature = "e2e-encryption")] custom_account: Option<
411            crate::crypto::vodozemac::olm::Account,
412        >,
413    ) -> Result<()> {
414        debug!(user_id = ?session_meta.user_id, device_id = ?session_meta.device_id, "Activating the client");
415
416        self.state_store.load_rooms(&session_meta.user_id, room_load_settings).await?;
417        self.state_store.load_sync_token().await?;
418        self.state_store.set_session_meta(session_meta);
419
420        // Always notify subscribers, even if the stored value is the same as
421        // the default one, so subscribers created before the activation
422        // always receive exactly one update for the initial load.
423        let ignore_user_list = self.get_ignore_user_list().await?;
424        self.ignore_user_list_changes.set(ignore_user_list);
425
426        #[cfg(feature = "e2e-encryption")]
427        self.regenerate_olm(custom_account).await?;
428
429        Ok(())
430    }
431
432    /// Recreate an `OlmMachine` from scratch.
433    ///
434    /// In particular, this will clear all its caches.
435    #[cfg(feature = "e2e-encryption")]
436    pub async fn regenerate_olm(
437        &self,
438        custom_account: Option<crate::crypto::vodozemac::olm::Account>,
439    ) -> Result<()> {
440        tracing::debug!("regenerating OlmMachine");
441        let session_meta = self.session_meta().ok_or(Error::OlmError(OlmError::MissingSession))?;
442
443        // Recreate the `OlmMachine` and wipe the in-memory cache in the store
444        // because we suspect it has stale data.
445        let builder = OlmMachineBuilder::new(&session_meta.user_id, &session_meta.device_id)
446            .with_crypto_store(self.crypto_store.clone())
447            .with_custom_account(custom_account);
448
449        #[cfg(feature = "experimental-x509-identity-verification")]
450        let builder = builder
451            .with_x509_verifier(self.x509_verifier.clone())
452            .with_x509_signer(self.x509_signer.clone());
453
454        let olm_machine = builder.build().await.map_err(OlmError::from)?;
455
456        // Subscribe before the machine is shared, so that no room key is
457        // missed.
458        #[cfg(feature = "unstable-msc4354")]
459        let room_keys_stream = olm_machine.store().room_keys_received_stream();
460
461        *self.olm_machine.write().await = Some(olm_machine);
462
463        // Retry pending encrypted sticky events as this machine receives room
464        // keys; the task bound to the previous machine, if any, is dropped.
465        #[cfg(feature = "unstable-msc4354")]
466        {
467            let redecryptor = crate::sticky::spawn_redecryptor(
468                room_keys_stream,
469                self.olm_machine.clone(),
470                self.decryption_settings.clone(),
471                self.state_store.clone(),
472            );
473            *self.sticky_redecryptor.lock().unwrap() = Some(redecryptor);
474        }
475
476        Ok(())
477    }
478
479    /// Get the current, if any, sync token of the client. This will be None if
480    /// the client didn't sync at least once.
481    pub async fn sync_token(&self) -> Option<String> {
482        self.state_store.sync_token.read().await.clone()
483    }
484
485    /// User has knocked on a room.
486    ///
487    /// Update the internal and cached state accordingly. Return the final Room.
488    pub async fn room_knocked(&self, room_id: &RoomId) -> Result<Room> {
489        let room = self.state_store.get_or_create_room(room_id, RoomState::Knocked);
490
491        if room.state() != RoomState::Knocked {
492            let store_guard = self.state_store.lock().lock().await;
493
494            // We are no longer joined to the room, so the invite acceptance
495            // details are no longer relevant.
496            #[cfg(feature = "e2e-encryption")]
497            if let Some(olm_machine) = self.olm_machine().await.as_ref() {
498                olm_machine.store().clear_room_pending_key_bundle(room_id).await?
499            }
500
501            room.update_and_save_room_info_with_store_guard(&store_guard, |mut info| {
502                info.mark_as_knocked();
503                info.mark_state_partially_synced();
504                info.mark_members_missing(); // the own member event changed
505                (info, RoomInfoNotableUpdateReasons::MEMBERSHIP)
506            })
507            .await?;
508        }
509
510        Ok(room)
511    }
512
513    /// The user has joined a room using this specific client.
514    ///
515    /// This method should be called if the user accepts an invite or if they
516    /// join a public room.
517    ///
518    /// The method will create a [`Room`] object if one does not exist yet and
519    /// set the state of the [`Room`] to [`RoomState::Joined`]. The [`Room`]
520    /// object will be persisted in the cache. Please note that the [`Room`]
521    /// will be a stub until a sync has been received with the full room state
522    /// using [`BaseClient::receive_sync_response`].
523    ///
524    /// Update the internal and cached state accordingly. Return the final Room.
525    ///
526    /// # Arguments
527    ///
528    /// - `room_id` - The unique ID identifying the joined room.
529    /// - `inviter` - When joining this room in response to an invitation, the
530    ///   inviter should be recorded before sending the join request to the
531    ///   server. Providing the inviter here ensures that the
532    ///   [`RoomPendingKeyBundleDetails`] are stored for this room.
533    ///
534    /// # Examples
535    ///
536    /// ```rust
537    /// # use matrix_sdk_base::{BaseClient, store::StoreConfig, RoomState, ThreadingSupport, DmRoomDefinition};
538    /// # use ruma::{OwnedRoomId, OwnedUserId, RoomId};
539    /// use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
540    /// # async {
541    /// # let client = BaseClient::new(
542    ///     StoreConfig::new(CrossProcessLockConfig::multi_process("example")),
543    ///     ThreadingSupport::Disabled,
544    ///     DmRoomDefinition::default()
545    /// );
546    /// # async fn send_join_request() -> anyhow::Result<OwnedRoomId> { todo!() }
547    /// # async fn maybe_get_inviter(room_id: &RoomId) -> anyhow::Result<Option<OwnedUserId>> { todo!() }
548    /// # let room_id: &RoomId = todo!();
549    /// let maybe_inviter = maybe_get_inviter(room_id).await?;
550    /// let room_id = send_join_request().await?;
551    /// let room = client.room_joined(&room_id, maybe_inviter).await?;
552    ///
553    /// assert_eq!(room.state(), RoomState::Joined);
554    /// # matrix_sdk_test::TestResult::Ok(()) };
555    /// ```
556    pub async fn room_joined(
557        &self,
558        room_id: &RoomId,
559        inviter: Option<OwnedUserId>,
560    ) -> Result<Room> {
561        let room = self.state_store.get_or_create_room(room_id, RoomState::Joined);
562
563        // If the state isn't `RoomState::Joined` then this means that we knew
564        // about this room before. Let's modify the existing state now.
565        if room.state() != RoomState::Joined {
566            let store_guard = self.state_store_lock().lock().await;
567
568            #[cfg(feature = "e2e-encryption")]
569            {
570                // If our previous state was an invite and we're now in the
571                // joined state, this means that the user has explicitly
572                // accepted an invite. Let's remember some details about the
573                // invite.
574                //
575                // This is somewhat of a workaround for our lack of
576                // cryptographic membership. Later on we will decide if historic
577                // room keys should be accepted based on this info. If a user
578                // has accepted an invite and we receive a room key bundle
579                // shortly after, we might accept it. If we don't do this, the
580                // homeserver could trick us into accepting any historic room
581                // key bundle.
582                let previous_state = room.state();
583                if previous_state == RoomState::Invited
584                    && let Some(inviter) = inviter
585                    && let Some(olm_machine) = self.olm_machine().await.as_ref()
586                {
587                    olm_machine.store().store_room_pending_key_bundle(room_id, &inviter).await?
588                }
589            }
590            #[cfg(not(feature = "e2e-encryption"))]
591            {
592                // suppress unused argument warning
593                let _ = inviter;
594            }
595
596            room.update_and_save_room_info_with_store_guard(&store_guard, |mut info| {
597                info.mark_as_joined();
598                info.mark_state_partially_synced();
599                info.mark_members_missing(); // the own member event changed
600                (info, RoomInfoNotableUpdateReasons::MEMBERSHIP)
601            })
602            .await?;
603        }
604
605        Ok(room)
606    }
607
608    /// User has left a room.
609    ///
610    /// Update the internal and cached state accordingly.
611    pub async fn room_left(&self, room_id: &RoomId) -> Result<()> {
612        let room = self.state_store.get_or_create_room(room_id, RoomState::Left);
613
614        if room.state() != RoomState::Left {
615            let store_guard = self.state_store.lock().lock().await;
616
617            // We are no longer joined to the room, so the invite acceptance
618            // details are no longer relevant.
619            #[cfg(feature = "e2e-encryption")]
620            if let Some(olm_machine) = self.olm_machine().await.as_ref() {
621                olm_machine.store().clear_room_pending_key_bundle(room_id).await?
622            }
623
624            room.update_and_save_room_info_with_store_guard(&store_guard, |mut info| {
625                info.mark_as_left();
626                info.mark_state_partially_synced();
627                info.mark_members_missing(); // the own member event changed
628                (info, RoomInfoNotableUpdateReasons::MEMBERSHIP)
629            })
630            .await?;
631        }
632
633        Ok(())
634    }
635
636    /// Get a lock to the state store, with an exclusive access.
637    ///
638    /// It doesn't give an access to the state store itself. It's rather a lock
639    /// to synchronise all accesses to the state store.
640    pub fn state_store_lock(&self) -> &Mutex<()> {
641        self.state_store.lock()
642    }
643
644    /// Receive a response from a sync call.
645    ///
646    /// # Arguments
647    ///
648    /// * `response` - The response that we received after a successful sync.
649    #[instrument(skip_all)]
650    pub async fn receive_sync_response(
651        &self,
652        response: api::sync::sync_events::v3::Response,
653    ) -> Result<SyncResponse> {
654        self.receive_sync_response_with_requested_required_states(
655            response,
656            &RequestedRequiredStates::default(),
657        )
658        .await
659    }
660
661    /// Receive a response from a sync call, with the requested required state
662    /// events.
663    ///
664    /// # Arguments
665    ///
666    /// - `response` - The response that we received after a successful sync.
667    /// - `requested_required_states` - The requested required state events.
668    pub async fn receive_sync_response_with_requested_required_states(
669        &self,
670        response: api::sync::sync_events::v3::Response,
671        requested_required_states: &RequestedRequiredStates,
672    ) -> Result<SyncResponse> {
673        // The server might respond multiple times with the same sync token, in
674        // that case we already received this response and there's nothing to
675        // do.
676        if self.state_store.sync_token.read().await.as_ref() == Some(&response.next_batch) {
677            info!("Got the same sync response twice");
678            return Ok(SyncResponse::default());
679        }
680
681        let _time = timer!(Level::INFO, "Processing a sync response");
682
683        // Acquire the state store lock and hold on to it while processing the
684        // sync response below.
685        let state_store_guard = self.state_store_lock().lock().await;
686
687        let user_id = self
688            .session_meta()
689            .expect("Sync shouldn't run without an authenticated user")
690            .user_id
691            .to_owned();
692
693        #[cfg(feature = "e2e-encryption")]
694        let olm_machine = self.olm_machine().await;
695
696        let mut context = Context::new(StateChanges::new(response.next_batch.clone()));
697
698        #[cfg(feature = "e2e-encryption")]
699        let processors::e2ee::to_device::Output { processed_to_device_events: to_device } =
700            processors::e2ee::to_device::from_sync_v2(
701                &response,
702                olm_machine.as_ref(),
703                &self.decryption_settings,
704            )
705            .await?;
706
707        #[cfg(not(feature = "e2e-encryption"))]
708        let to_device = response
709            .to_device
710            .events
711            .into_iter()
712            .map(|raw| {
713                use matrix_sdk_common::deserialized_responses::{
714                    ProcessedToDeviceEvent, ToDeviceUnableToDecryptInfo,
715                    ToDeviceUnableToDecryptReason,
716                };
717                use ruma::events::ToDeviceEventType;
718
719                if let Ok(Some(event_type)) = raw.get_field::<ToDeviceEventType>("type") {
720                    if event_type == ToDeviceEventType::RoomEncrypted {
721                        ProcessedToDeviceEvent::UnableToDecrypt {
722                            encrypted_event: raw,
723                            utd_info: ToDeviceUnableToDecryptInfo {
724                                reason: ToDeviceUnableToDecryptReason::EncryptionIsDisabled,
725                            },
726                        }
727                    } else {
728                        ProcessedToDeviceEvent::PlainText(raw)
729                    }
730                } else {
731                    // Exclude events with no type
732                    ProcessedToDeviceEvent::Invalid(raw)
733                }
734            })
735            .collect();
736
737        let mut ambiguity_cache = AmbiguityCache::new(self.state_store.inner.clone());
738        let mut avatar_cache = AvatarCache::new(self.state_store.inner.clone());
739
740        let global_account_data_processor =
741            processors::account_data::global(&response.account_data.events);
742
743        let push_rules = self.get_push_rules(&global_account_data_processor).await?;
744
745        let mut room_updates = RoomUpdates::default();
746        let mut notifications = Default::default();
747
748        let mut updated_members_in_room: BTreeMap<OwnedRoomId, BTreeSet<OwnedUserId>> =
749            BTreeMap::new();
750
751        #[cfg(feature = "e2e-encryption")]
752        let e2ee_context = processors::e2ee::E2EE::new(
753            olm_machine.as_ref(),
754            &self.decryption_settings,
755            self.handle_verification_events,
756        );
757
758        for (room_id, joined_room) in response.rooms.join {
759            let joined_room_update = processors::room::sync_v2::update_joined_room(
760                &mut context,
761                processors::room::RoomCreationData::new(
762                    &room_id,
763                    requested_required_states,
764                    &mut ambiguity_cache,
765                    &mut avatar_cache,
766                ),
767                joined_room,
768                &mut updated_members_in_room,
769                processors::notification::Notification::new(
770                    &push_rules,
771                    &mut notifications,
772                    &self.state_store,
773                ),
774                #[cfg(feature = "e2e-encryption")]
775                &e2ee_context,
776            )
777            .await?;
778
779            room_updates.joined.insert(room_id, joined_room_update);
780        }
781
782        for (room_id, left_room) in response.rooms.leave {
783            let left_room_update = processors::room::sync_v2::update_left_room(
784                &mut context,
785                processors::room::RoomCreationData::new(
786                    &room_id,
787                    requested_required_states,
788                    &mut ambiguity_cache,
789                    &mut avatar_cache,
790                ),
791                left_room,
792                processors::notification::Notification::new(
793                    &push_rules,
794                    &mut notifications,
795                    &self.state_store,
796                ),
797                #[cfg(feature = "e2e-encryption")]
798                &e2ee_context,
799            )
800            .await?;
801
802            room_updates.left.insert(room_id, left_room_update);
803        }
804
805        for (room_id, invited_room) in response.rooms.invite {
806            let invited_room_update = processors::room::sync_v2::update_invited_room(
807                &mut context,
808                &room_id,
809                &user_id,
810                invited_room,
811                processors::notification::Notification::new(
812                    &push_rules,
813                    &mut notifications,
814                    &self.state_store,
815                ),
816                #[cfg(feature = "e2e-encryption")]
817                &e2ee_context,
818            )
819            .await?;
820
821            room_updates.invited.insert(room_id, invited_room_update);
822        }
823
824        for (room_id, knocked_room) in response.rooms.knock {
825            let knocked_room_update = processors::room::sync_v2::update_knocked_room(
826                &mut context,
827                &room_id,
828                &user_id,
829                knocked_room,
830                processors::notification::Notification::new(
831                    &push_rules,
832                    &mut notifications,
833                    &self.state_store,
834                ),
835                #[cfg(feature = "e2e-encryption")]
836                &e2ee_context,
837            )
838            .await?;
839
840            room_updates.knocked.insert(room_id, knocked_room_update);
841        }
842
843        global_account_data_processor.apply(&mut context, &self.state_store).await;
844
845        context.state_changes.presence = response
846            .presence
847            .events
848            .iter()
849            .filter_map(|e| {
850                let event = e.deserialize().ok()?;
851                Some((event.sender, e.clone()))
852            })
853            .collect();
854
855        context.state_changes.ambiguity_maps = ambiguity_cache.cache;
856
857        processors::changes::save_and_apply(
858            context,
859            &self.state_store,
860            &state_store_guard,
861            &self.ignore_user_list_changes,
862            Some(response.next_batch.clone()),
863        )
864        .await?;
865
866        let mut context = Context::default();
867
868        // Now that all the rooms information have been saved, update the
869        // display name of the updated rooms (which relies on information stored
870        // in the database).
871        processors::room::display_name::update_for_rooms(
872            &mut context,
873            &room_updates,
874            &self.state_store,
875        )
876        .await;
877
878        // Save the new display name updates if any.
879        processors::changes::save_only(context, &self.state_store, &state_store_guard).await?;
880
881        for (room_id, member_ids) in updated_members_in_room {
882            if let Some(room) = self.get_room(&room_id) {
883                let _ =
884                    room.room_member_updates_sender.send(RoomMembersUpdate::Partial(member_ids));
885            }
886        }
887
888        // Release the state store lock
889        drop(state_store_guard);
890
891        let response = SyncResponse {
892            rooms: room_updates,
893            presence: response.presence.events,
894            account_data: response.account_data.events,
895            to_device,
896            notifications,
897        };
898
899        Ok(response)
900    }
901
902    /// Receive a get member events response and convert it to a deserialized
903    /// `MembersResponse`
904    ///
905    /// This client-server request must be made without filters to make sure all
906    /// members are received. Otherwise, an error is returned.
907    ///
908    /// # Arguments
909    ///
910    /// - `room_id` - The room id this response belongs to.
911    /// - `response` - The raw response that was received from the server.
912    #[instrument(skip_all, fields(?room_id))]
913    pub async fn receive_all_members(
914        &self,
915        room_id: &RoomId,
916        request: &api::membership::get_member_events::v3::Request,
917        response: &api::membership::get_member_events::v3::Response,
918    ) -> Result<()> {
919        if request.membership.is_some() || request.not_membership.is_some() || request.at.is_some()
920        {
921            // This function assumes all members are loaded at once to optimise
922            // how display name disambiguation works. Using it with partial
923            // member list results would produce incorrect disambiguated display
924            // name entries
925            return Err(Error::InvalidReceiveMembersParameters);
926        }
927
928        let Some(room) = self.state_store.room(room_id) else {
929            // The room is unknown to us: leave early.
930            return Ok(());
931        };
932
933        let mut context = Context::default();
934
935        #[cfg(feature = "e2e-encryption")]
936        let mut user_ids = BTreeSet::new();
937
938        let mut ambiguity_map: HashMap<DisplayName, BTreeSet<OwnedUserId>> = Default::default();
939
940        for raw_event in &response.chunk {
941            let member = match raw_event.deserialize() {
942                Ok(ev) => ev,
943                Err(e) => {
944                    let event_id: Option<String> = raw_event.get_field("event_id").ok().flatten();
945                    debug!(event_id, "Failed to deserialize member event: {e}");
946                    continue;
947                }
948            };
949
950            // TODO: All the actions in this loop used to be done only when the
951            // membership event was not in the store before. This was changed
952            // with the new room API, because e.g. leaving a room makes members
953            // events outdated and they need to be fetched by `members`.
954            // Therefore, they need to be overwritten here, even if they exist.
955            // However, this makes a new problem occur where setting the member
956            // events here potentially races with the sync. See [#1205].
957            //
958            // [#1205]: https://github.com/matrix-org/matrix-rust-sdk/issues/1205
959
960            #[cfg(feature = "e2e-encryption")]
961            match member.membership() {
962                MembershipState::Join | MembershipState::Invite => {
963                    user_ids.insert(member.state_key().to_owned());
964                }
965                _ => (),
966            }
967
968            if let StateEvent::Original(e) = &member
969                && is_member_active(&e.content.membership)
970                && let Some(d) = &e.content.displayname
971            {
972                let display_name = DisplayName::new(d);
973                ambiguity_map.entry(display_name).or_default().insert(member.state_key().clone());
974            }
975
976            let event_type = member.event_type();
977            let state_key = member.state_key().to_string();
978
979            let sync_member: SyncRoomMemberEvent = member.into();
980            processors::profiles::upsert_or_delete(&mut context, room_id, &sync_member);
981
982            context
983                .state_changes
984                .state
985                .entry(room_id.to_owned())
986                .or_default()
987                .entry(event_type)
988                .or_default()
989                .insert(state_key, raw_event.clone().cast());
990        }
991
992        #[cfg(feature = "e2e-encryption")]
993        processors::e2ee::tracked_users::update(
994            self.olm_machine().await.as_ref(),
995            room.encryption_state(),
996            &user_ids,
997        )
998        .await?;
999
1000        context.state_changes.ambiguity_maps.insert(room_id.to_owned(), ambiguity_map);
1001
1002        {
1003            let state_store_guard = self.state_store_lock().lock().await;
1004
1005            let mut room_info = room.clone_info();
1006            room_info.mark_members_synced();
1007            context.state_changes.add_room(room_info);
1008
1009            processors::changes::save_and_apply(
1010                context,
1011                &self.state_store,
1012                &state_store_guard,
1013                &self.ignore_user_list_changes,
1014                None,
1015            )
1016            .await?;
1017        }
1018
1019        let _ = room.room_member_updates_sender.send(RoomMembersUpdate::FullReload);
1020
1021        #[cfg(feature = "e2e-encryption")]
1022        if let Some(olm) = self.olm_machine().await.as_ref() {
1023            // With the introduction of MSC4268, it is no longer sufficient to
1024            // check for changes to session recipients when we send a message,
1025            // since we may miss join/leave pairs in our view of the room state.
1026            // Instead, we should rotate the room key whenever we fully reload
1027            // the member list as a precaution.
1028            tracing::debug!("Rotating room key due to full member list reload");
1029            if let Err(e) = olm.discard_room_key(room_id).await {
1030                tracing::warn!("Error discarding room key: {e:?}");
1031            }
1032        }
1033
1034        Ok(())
1035    }
1036
1037    /// Receive a successful filter upload response, the filter id will be
1038    /// stored under the given name in the store.
1039    ///
1040    /// The filter id can later be retrieved with the [`get_filter`] method.
1041    ///
1042    /// # Arguments
1043    ///
1044    /// - `filter_name` - The name that should be used to persist the filter id
1045    ///   in the store.
1046    ///
1047    /// - `response` - The successful filter upload response containing the
1048    ///   filter id.
1049    ///
1050    /// [`get_filter`]: #method.get_filter
1051    pub async fn receive_filter_upload(
1052        &self,
1053        filter_name: &str,
1054        response: &api::filter::create_filter::v3::Response,
1055    ) -> Result<()> {
1056        Ok(self
1057            .state_store
1058            .set_kv_data(
1059                StateStoreDataKey::Filter(filter_name),
1060                StateStoreDataValue::Filter(response.filter_id.clone()),
1061            )
1062            .await?)
1063    }
1064
1065    /// Get the filter id of a previously uploaded filter.
1066    ///
1067    /// _Note_: A filter will first need to be uploaded and persisted using
1068    /// [`receive_filter_upload`].
1069    ///
1070    /// # Arguments
1071    ///
1072    /// - `filter_name` - The name of the filter that was previously used to
1073    ///   persist the filter.
1074    ///
1075    /// [`receive_filter_upload`]: #method.receive_filter_upload
1076    pub async fn get_filter(&self, filter_name: &str) -> StoreResult<Option<String>> {
1077        let filter = self
1078            .state_store
1079            .get_kv_data(StateStoreDataKey::Filter(filter_name))
1080            .await?
1081            .map(|d| d.into_filter().expect("State store data not a filter"));
1082
1083        Ok(filter)
1084    }
1085
1086    /// Get a to-device request that will share a room key with users in a room.
1087    #[cfg(feature = "e2e-encryption")]
1088    pub async fn share_room_key(&self, room_id: &RoomId) -> Result<Vec<Arc<ToDeviceRequest>>> {
1089        match self.olm_machine().await.as_ref() {
1090            Some(o) => {
1091                let Some(room) = self.get_room(room_id) else {
1092                    return Err(Error::InsufficientData);
1093                };
1094
1095                let history_visibility = room.history_visibility_or_default();
1096                let Some(room_encryption_event) = room.encryption_settings() else {
1097                    return Err(Error::EncryptionNotEnabled);
1098                };
1099
1100                // Don't share the group session with members that are invited
1101                // if the history visibility is set to `Joined`
1102                let filter = if history_visibility == HistoryVisibility::Joined {
1103                    RoomMemberships::JOIN
1104                } else {
1105                    RoomMemberships::ACTIVE
1106                };
1107
1108                let members = self.state_store.get_user_ids(room_id, filter).await?;
1109
1110                let Some(settings) = EncryptionSettings::from_possibly_redacted(
1111                    room_encryption_event,
1112                    history_visibility,
1113                    self.room_key_recipient_strategy.clone(),
1114                ) else {
1115                    return Err(Error::EncryptionNotEnabled);
1116                };
1117
1118                Ok(o.share_room_key(room_id, members.iter().map(Deref::deref), settings).await?)
1119            }
1120            None => panic!("Olm machine wasn't started"),
1121        }
1122    }
1123
1124    /// Get the room with the given room id.
1125    ///
1126    /// # Arguments
1127    ///
1128    /// * `room_id` - The id of the room that should be fetched.
1129    pub fn get_room(&self, room_id: &RoomId) -> Option<Room> {
1130        self.state_store.room(room_id)
1131    }
1132
1133    /// Forget the room with the given room ID.
1134    ///
1135    /// The room will be dropped from the room list and the store.
1136    ///
1137    /// # Arguments
1138    ///
1139    /// * `room_id` - The id of the room that should be forgotten.
1140    pub async fn forget_room(&self, room_id: &RoomId) -> Result<()> {
1141        // Forget the room in the state store.
1142        self.state_store.forget_room(room_id).await?;
1143
1144        Ok(())
1145    }
1146
1147    /// Get the olm machine.
1148    #[cfg(feature = "e2e-encryption")]
1149    pub async fn olm_machine(&self) -> RwLockReadGuard<'_, Option<OlmMachine>> {
1150        self.olm_machine.read().await
1151    }
1152
1153    /// Get the push rules.
1154    ///
1155    /// Gets the push rules previously processed, otherwise get them from the
1156    /// store. As a fallback, uses [`Ruleset::server_default`] if the user is
1157    /// logged in.
1158    pub(crate) async fn get_push_rules(
1159        &self,
1160        global_account_data_processor: &processors::account_data::Global,
1161    ) -> Result<Ruleset> {
1162        let _timer = timer!(Level::TRACE, "get_push_rules");
1163        if let Some(event) = global_account_data_processor
1164            .push_rules()
1165            .and_then(|ev| ev.deserialize_as_unchecked::<PushRulesEvent>().ok())
1166        {
1167            Ok(event.content.global)
1168        } else if let Some(event) = self
1169            .state_store
1170            .get_account_data_event_static::<PushRulesEventContent>()
1171            .await?
1172            .and_then(|ev| ev.deserialize().ok())
1173        {
1174            Ok(event.content.global)
1175        } else if let Some(session_meta) = self.state_store.session_meta() {
1176            Ok(Ruleset::server_default(&session_meta.user_id))
1177        } else {
1178            Ok(Ruleset::new())
1179        }
1180    }
1181
1182    /// Gets the ignore user list.
1183    ///
1184    /// Retrieves the ignored users from the state store, returning an empty
1185    /// list if no ignored user list has been stored.
1186    async fn get_ignore_user_list(&self) -> Result<Vec<OwnedUserId>> {
1187        let Some(raw) =
1188            self.state_store.get_account_data_event_static::<IgnoredUserListEventContent>().await?
1189        else {
1190            return Ok(Vec::new());
1191        };
1192
1193        let event = raw.deserialize()?;
1194
1195        Ok(event.content.ignored_users.into_keys().collect())
1196    }
1197
1198    /// Returns a subscriber that publishes an event every time the ignore user
1199    /// list changes
1200    pub fn subscribe_to_ignore_user_list_changes(&self) -> Subscriber<Vec<OwnedUserId>> {
1201        self.ignore_user_list_changes.subscribe()
1202    }
1203
1204    /// Returns a new receiver that gets future room info notable updates.
1205    ///
1206    /// Learn more by reading the [`RoomInfoNotableUpdate`] type.
1207    pub fn room_info_notable_update_receiver(&self) -> broadcast::Receiver<RoomInfoNotableUpdate> {
1208        self.state_store.room_info_notable_update_sender.subscribe()
1209    }
1210
1211    /// Returns a receiver of the user IDs whose global profile changed during a
1212    /// sync. Consumers can use this as a trigger to e.g. merge any global
1213    /// fields into a user's room profile.
1214    ///
1215    /// Requires the Profiles sliding sync extension to be enabled.
1216    pub fn subscribe_to_global_profile_updates(
1217        &self,
1218    ) -> broadcast::Receiver<BTreeSet<OwnedUserId>> {
1219        self.global_profile_updates_sender.subscribe()
1220    }
1221
1222    /// Our own global profile has been updated.
1223    ///
1224    /// Updates the internal and cached state accordingly, so the change is
1225    /// observable before the next sync reflects it.
1226    ///
1227    /// **Note:** This method should only be called when global profile syncing
1228    /// is enabled.
1229    pub async fn own_profile_updated(&self, update: UserProfileUpdate) -> Result<()> {
1230        let own_user_id = self.session_meta().ok_or(Error::InsufficientData)?.user_id.clone();
1231        let state_store_guard = self.state_store_lock().lock().await;
1232
1233        let mut changes = StateChanges::default();
1234        changes.global_profiles.insert(own_user_id.clone(), update);
1235        self.state_store.save_changes_with_guard(&state_store_guard, &changes).await?;
1236
1237        self.notify_global_profile_updates(BTreeSet::from([own_user_id]), &state_store_guard)
1238    }
1239
1240    /// Receive global profiles fetched from the homeserver outside of a sync,
1241    /// e.g. via MSC4536, along with any users whose global profiles need to
1242    /// be marked as unavailable.
1243    ///
1244    /// Updates the internal and cached state accordingly, and notifies any
1245    /// subscribers of the changed user IDs.
1246    ///
1247    /// **Note:** This method should only be called when global profile syncing
1248    /// is enabled.
1249    #[cfg(feature = "unstable-msc4536")]
1250    pub async fn receive_fetched_global_profiles(
1251        &self,
1252        profiles: BTreeMap<OwnedUserId, UserProfileUpdate>,
1253        unavailable_profiles: BTreeMap<OwnedUserId, MilliSecondsSinceUnixEpoch>,
1254    ) -> Result<()> {
1255        if profiles.is_empty() && unavailable_profiles.is_empty() {
1256            return Ok(());
1257        }
1258
1259        let state_store_guard = self.state_store_lock().lock().await;
1260        let user_ids = profiles.keys().cloned().collect();
1261
1262        let changes = StateChanges {
1263            global_profiles: profiles,
1264            unavailable_global_profiles: unavailable_profiles,
1265            ..Default::default()
1266        };
1267        self.state_store.save_changes_with_guard(&state_store_guard, &changes).await?;
1268
1269        self.notify_global_profile_updates(user_ids, &state_store_guard)
1270    }
1271
1272    /// Notify the rest of the SDK that the global profiles of the given users
1273    /// changed in the store.
1274    ///
1275    /// Broadcasts the changed user IDs, and nudges the `RoomInfo` of any room
1276    /// where one of them is a hero so the hero fields are re-read.
1277    pub(crate) fn notify_global_profile_updates(
1278        &self,
1279        user_ids: BTreeSet<OwnedUserId>,
1280        #[cfg_attr(not(feature = "unstable-msc4426"), allow(unused_variables))]
1281        state_store_guard: &MutexGuard<'_, ()>,
1282    ) -> Result<()> {
1283        if user_ids.is_empty() {
1284            return Ok(());
1285        }
1286
1287        // Nudge `RoomInfo` so hero status/call fields are re-read.
1288        #[cfg(feature = "unstable-msc4426")]
1289        for room in self.state_store.rooms() {
1290            if room.hero_user_ids().iter().any(|hero| user_ids.contains(hero)) {
1291                room.update_room_info_with_store_guard(state_store_guard, |room_info| {
1292                    (room_info, RoomInfoNotableUpdateReasons::HEROES)
1293                })
1294                .map_err(crate::StoreError::from)?;
1295            }
1296        }
1297
1298        let _ = self.global_profile_updates_sender.send(user_ids);
1299
1300        Ok(())
1301    }
1302
1303    /// Checks whether the provided `user_id` belongs to an ignored user.
1304    pub async fn is_user_ignored(&self, user_id: &UserId) -> bool {
1305        match self.state_store.get_account_data_event_static::<IgnoredUserListEventContent>().await
1306        {
1307            Ok(Some(raw_ignored_user_list)) => match raw_ignored_user_list.deserialize() {
1308                Ok(current_ignored_user_list) => {
1309                    current_ignored_user_list.content.ignored_users.contains_key(user_id)
1310                }
1311                Err(error) => {
1312                    warn!(?error, "Failed to deserialize the ignored user list event");
1313                    false
1314                }
1315            },
1316            Ok(None) => false,
1317            Err(error) => {
1318                warn!(?error, "Could not get the ignored user list from the state store");
1319                false
1320            }
1321        }
1322    }
1323
1324    /// Check the record of whether we are waiting for an [MSC4268] key bundle
1325    /// for the given room.
1326    ///
1327    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
1328    #[cfg(feature = "e2e-encryption")]
1329    pub async fn get_pending_key_bundle_details_for_room(
1330        &self,
1331        room_id: &RoomId,
1332    ) -> Result<Option<RoomPendingKeyBundleDetails>> {
1333        let result = match self.olm_machine().await.as_ref() {
1334            Some(machine) => {
1335                machine.store().get_pending_key_bundle_details_for_room(room_id).await?
1336            }
1337            None => None,
1338        };
1339        Ok(result)
1340    }
1341
1342    /// Close all stores, releasing database connections and file locks.
1343    ///
1344    /// In-flight operations will complete before this returns.
1345    pub async fn close_stores(&self) -> Result<()> {
1346        self.state_store.close().await?;
1347        self.event_cache_store.close().await.map_err(Error::EventCacheStore)?;
1348        self.media_store.close().await.map_err(Error::MediaStore)?;
1349
1350        #[cfg(feature = "e2e-encryption")]
1351        self.crypto_store.close().await.map_err(Error::CryptoStore)?;
1352
1353        Ok(())
1354    }
1355
1356    /// Reopen all stores after a close, re-opening database connections.
1357    pub async fn reopen_stores(&self) -> Result<()> {
1358        #[cfg(feature = "e2e-encryption")]
1359        self.crypto_store.reopen().await.map_err(Error::CryptoStore)?;
1360
1361        self.media_store.reopen().await.map_err(Error::MediaStore)?;
1362        self.event_cache_store.reopen().await.map_err(Error::EventCacheStore)?;
1363        self.state_store.reopen().await?;
1364
1365        Ok(())
1366    }
1367}
1368
1369/// Represent the `required_state` values sent by a sync request.
1370///
1371/// This is useful to track what state events have been requested when handling
1372/// a response.
1373///
1374/// For example, if a sync requests the `m.room.encryption` state event, and the
1375/// server replies with nothing, if means the room **is not** encrypted. Without
1376/// knowing which state event was required by the sync, it is impossible to
1377/// interpret the absence of state event from the server as
1378/// _the room's encryption state is **not encrypted**_ or
1379/// _the room's encryption state is **unknown**_.
1380#[derive(Debug, Default)]
1381pub struct RequestedRequiredStates {
1382    default: Vec<(StateEventType, String)>,
1383    for_rooms: HashMap<OwnedRoomId, Vec<(StateEventType, String)>>,
1384}
1385
1386impl RequestedRequiredStates {
1387    /// Create a new `RequestedRequiredStates`.
1388    ///
1389    /// `default` represents the `required_state` value for all rooms.
1390    /// `for_rooms` is the `required_state` per room.
1391    pub fn new(
1392        default: Vec<(StateEventType, String)>,
1393        for_rooms: HashMap<OwnedRoomId, Vec<(StateEventType, String)>>,
1394    ) -> Self {
1395        Self { default, for_rooms }
1396    }
1397
1398    /// Get the `required_state` value for a specific room.
1399    pub fn for_room(&self, room_id: &RoomId) -> &[(StateEventType, String)] {
1400        self.for_rooms.get(room_id).unwrap_or(&self.default)
1401    }
1402}
1403
1404impl From<&msc4186::Request> for RequestedRequiredStates {
1405    fn from(request: &msc4186::Request) -> Self {
1406        // The following information is missing in the MSC4186 at the time of
1407        // writing (2025-03-12) but: the `required_state`s from all lists and
1408        // from all room subscriptions are combined by doing an union.
1409        //
1410        // Thus, we can do the same here, put the union in `default` and keep
1411        // `for_rooms` empty. The `Self::for_room` will automatically do the
1412        // fallback.
1413        let mut default = BTreeSet::new();
1414
1415        for list in request.lists.values() {
1416            default.extend(BTreeSet::from_iter(list.room_details.required_state.iter().cloned()));
1417        }
1418
1419        for room_subscription in request.room_subscriptions.values() {
1420            default.extend(BTreeSet::from_iter(room_subscription.required_state.iter().cloned()));
1421        }
1422
1423        Self { default: default.into_iter().collect(), for_rooms: HashMap::new() }
1424    }
1425}
1426
1427/// An enum that defines what the [`BaseClient`] should consider a DM room.
1428#[derive(Debug, Clone, Default)]
1429#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1430pub enum DmRoomDefinition {
1431    /// Standard Matrix spec definition: a room linked to a user in an
1432    /// `m.direct` event.
1433    #[default]
1434    MatrixSpec,
1435    /// A room that is direct, as per the spec but also contains at most 2
1436    /// active members.
1437    TwoMembers,
1438}
1439
1440#[cfg(test)]
1441mod tests {
1442    use std::collections::HashMap;
1443
1444    use futures_util::FutureExt as _;
1445    use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
1446    use matrix_sdk_test::{
1447        InvitedRoomBuilder, LeftRoomBuilder, SyncResponseBuilder, User, async_test,
1448        event_factory::EventFactory, ruma_response_from_json,
1449    };
1450    #[cfg(feature = "unstable-msc4426")]
1451    use ruma::profile::{
1452        ProfileFieldValue, StatusProfileField, UserProfileChanges, UserProfileUpdate,
1453    };
1454    use ruma::{
1455        RoomId,
1456        api::client::{self as api, sync::sync_events::msc4186},
1457        event_id,
1458        events::{StateEventType, room::member::MembershipState},
1459        room_id,
1460        serde::Raw,
1461        user_id,
1462    };
1463    use serde_json::{json, value::to_raw_value};
1464    use strass::assert_let;
1465
1466    use super::{BaseClient, RequestedRequiredStates};
1467    use crate::{
1468        DmRoomDefinition, RoomDisplayName, RoomState, SessionMeta,
1469        client::ThreadingSupport,
1470        store::{RoomLoadSettings, StateStoreExt, StoreConfig},
1471        test_utils::logged_in_base_client,
1472    };
1473    #[cfg(feature = "unstable-msc4426")]
1474    use crate::{RoomMemberships, store::StateChanges};
1475
1476    #[test]
1477    fn test_requested_required_states() {
1478        let room_id_0 = room_id!("!r0");
1479        let room_id_1 = room_id!("!r1");
1480
1481        let requested_required_states = RequestedRequiredStates::new(
1482            vec![(StateEventType::RoomAvatar, "".to_owned())],
1483            HashMap::from([(
1484                room_id_0.to_owned(),
1485                vec![
1486                    (StateEventType::RoomMember, "foo".to_owned()),
1487                    (StateEventType::RoomEncryption, "".to_owned()),
1488                ],
1489            )]),
1490        );
1491
1492        // A special set of state events exists for `room_id_0`.
1493        assert_eq!(
1494            requested_required_states.for_room(room_id_0),
1495            &[
1496                (StateEventType::RoomMember, "foo".to_owned()),
1497                (StateEventType::RoomEncryption, "".to_owned()),
1498            ]
1499        );
1500
1501        // No special list for `room_id_1`, it should return the defaults.
1502        assert_eq!(
1503            requested_required_states.for_room(room_id_1),
1504            &[(StateEventType::RoomAvatar, "".to_owned()),]
1505        );
1506    }
1507
1508    #[test]
1509    fn test_requested_required_states_from_sync_v5_request() {
1510        let room_id_0 = room_id!("!r0");
1511        let room_id_1 = room_id!("!r1");
1512
1513        // Empty request.
1514        let mut request = msc4186::Request::new();
1515
1516        {
1517            let requested_required_states = RequestedRequiredStates::from(&request);
1518
1519            assert!(requested_required_states.default.is_empty());
1520            assert!(requested_required_states.for_rooms.is_empty());
1521        }
1522
1523        // One list.
1524        request.lists.insert("foo".to_owned(), {
1525            let mut list = msc4186::request::List::default();
1526            list.room_details.required_state = vec![
1527                (StateEventType::RoomAvatar, "".to_owned()),
1528                (StateEventType::RoomEncryption, "".to_owned()),
1529            ];
1530
1531            list
1532        });
1533
1534        {
1535            let requested_required_states = RequestedRequiredStates::from(&request);
1536
1537            assert_eq!(
1538                requested_required_states.default,
1539                &[
1540                    (StateEventType::RoomAvatar, "".to_owned()),
1541                    (StateEventType::RoomEncryption, "".to_owned())
1542                ]
1543            );
1544            assert!(requested_required_states.for_rooms.is_empty());
1545        }
1546
1547        // Two lists.
1548        request.lists.insert("bar".to_owned(), {
1549            let mut list = msc4186::request::List::default();
1550            list.room_details.required_state = vec![
1551                (StateEventType::RoomEncryption, "".to_owned()),
1552                (StateEventType::RoomName, "".to_owned()),
1553            ];
1554
1555            list
1556        });
1557
1558        {
1559            let requested_required_states = RequestedRequiredStates::from(&request);
1560
1561            // Union of the state events.
1562            assert_eq!(
1563                requested_required_states.default,
1564                &[
1565                    (StateEventType::RoomAvatar, "".to_owned()),
1566                    (StateEventType::RoomEncryption, "".to_owned()),
1567                    (StateEventType::RoomName, "".to_owned()),
1568                ]
1569            );
1570            assert!(requested_required_states.for_rooms.is_empty());
1571        }
1572
1573        // One room subscription.
1574        request.room_subscriptions.insert(room_id_0.to_owned(), {
1575            let mut room_subscription = msc4186::request::RoomSubscription::default();
1576
1577            room_subscription.required_state = vec![
1578                (StateEventType::RoomJoinRules, "".to_owned()),
1579                (StateEventType::RoomEncryption, "".to_owned()),
1580            ];
1581
1582            room_subscription
1583        });
1584
1585        {
1586            let requested_required_states = RequestedRequiredStates::from(&request);
1587
1588            // Union of state events, all in `default`, still nothing in
1589            // `for_rooms`.
1590            assert_eq!(
1591                requested_required_states.default,
1592                &[
1593                    (StateEventType::RoomAvatar, "".to_owned()),
1594                    (StateEventType::RoomEncryption, "".to_owned()),
1595                    (StateEventType::RoomJoinRules, "".to_owned()),
1596                    (StateEventType::RoomName, "".to_owned()),
1597                ]
1598            );
1599            assert!(requested_required_states.for_rooms.is_empty());
1600        }
1601
1602        // Two room subscriptions.
1603        request.room_subscriptions.insert(room_id_1.to_owned(), {
1604            let mut room_subscription = msc4186::request::RoomSubscription::default();
1605
1606            room_subscription.required_state = vec![
1607                (StateEventType::RoomName, "".to_owned()),
1608                (StateEventType::RoomTopic, "".to_owned()),
1609            ];
1610
1611            room_subscription
1612        });
1613
1614        {
1615            let requested_required_states = RequestedRequiredStates::from(&request);
1616
1617            // Union of state events, all in `default`, still nothing in
1618            // `for_rooms`.
1619            assert_eq!(
1620                requested_required_states.default,
1621                &[
1622                    (StateEventType::RoomAvatar, "".to_owned()),
1623                    (StateEventType::RoomEncryption, "".to_owned()),
1624                    (StateEventType::RoomJoinRules, "".to_owned()),
1625                    (StateEventType::RoomName, "".to_owned()),
1626                    (StateEventType::RoomTopic, "".to_owned()),
1627                ]
1628            );
1629        }
1630    }
1631
1632    #[async_test]
1633    async fn test_invite_after_leaving() {
1634        let user_id = user_id!("@alice:example.org");
1635        let room_id = room_id!("!test:example.org");
1636
1637        let client = logged_in_base_client(Some(user_id)).await;
1638        let f = EventFactory::new();
1639
1640        let mut sync_builder = SyncResponseBuilder::new();
1641
1642        let response = sync_builder
1643            .add_left_room(
1644                LeftRoomBuilder::new(room_id).add_timeline_event(
1645                    EventFactory::new()
1646                        .member(user_id)
1647                        .membership(MembershipState::Leave)
1648                        .display_name("Alice")
1649                        .event_id(event_id!("$994173582443PhrSn:example.org")),
1650                ),
1651            )
1652            .build_sync_response();
1653        client.receive_sync_response(response).await.unwrap();
1654        assert_eq!(client.get_room(room_id).unwrap().state(), RoomState::Left);
1655
1656        let response = sync_builder
1657            .add_invited_room(
1658                InvitedRoomBuilder::new(room_id).add_state_event(
1659                    f.member(user_id)
1660                        .sender(user_id!("@example:example.org"))
1661                        .membership(MembershipState::Invite)
1662                        .display_name("Alice"),
1663                ),
1664            )
1665            .build_sync_response();
1666        client.receive_sync_response(response).await.unwrap();
1667        assert_eq!(client.get_room(room_id).unwrap().state(), RoomState::Invited);
1668    }
1669
1670    #[async_test]
1671    async fn test_invite_displayname() {
1672        let user_id = user_id!("@alice:example.org");
1673        let room_id = room_id!("!ithpyNKDtmhneaTQja:example.org");
1674
1675        let client = logged_in_base_client(Some(user_id)).await;
1676
1677        let response = ruma_response_from_json(&json!({
1678            "next_batch": "asdkl;fjasdkl;fj;asdkl;f",
1679            "device_one_time_keys_count": {
1680                "signed_curve25519": 50u64
1681            },
1682            "device_unused_fallback_key_types": [
1683                "signed_curve25519"
1684            ],
1685            "rooms": {
1686                "invite": {
1687                    "!ithpyNKDtmhneaTQja:example.org": {
1688                        "invite_state": {
1689                            "events": [
1690                                {
1691                                    "content": {
1692                                        "creator": "@test:example.org",
1693                                        "room_version": "9"
1694                                    },
1695                                    "sender": "@test:example.org",
1696                                    "state_key": "",
1697                                    "type": "m.room.create"
1698                                },
1699                                {
1700                                    "content": {
1701                                        "join_rule": "invite"
1702                                    },
1703                                    "sender": "@test:example.org",
1704                                    "state_key": "",
1705                                    "type": "m.room.join_rules"
1706                                },
1707                                {
1708                                    "content": {
1709                                        "algorithm": "m.megolm.v1.aes-sha2"
1710                                    },
1711                                    "sender": "@test:example.org",
1712                                    "state_key": "",
1713                                    "type": "m.room.encryption"
1714                                },
1715                                {
1716                                    "content": {
1717                                        "avatar_url": "mxc://example.org/dcBBDwuWEUrjfrOchvkirUST",
1718                                        "displayname": "Kyra",
1719                                        "membership": "join"
1720                                    },
1721                                    "sender": "@test:example.org",
1722                                    "state_key": "@test:example.org",
1723                                    "type": "m.room.member"
1724                                },
1725                                {
1726                                    "content": {
1727                                        "avatar_url": "mxc://example.org/ABFEXSDrESxovWwEnCYdNcHT",
1728                                        "displayname": "alice",
1729                                        "is_direct": true,
1730                                        "membership": "invite"
1731                                    },
1732                                    "origin_server_ts": 1650878657984u64,
1733                                    "sender": "@test:example.org",
1734                                    "state_key": "@alice:example.org",
1735                                    "type": "m.room.member",
1736                                    "unsigned": {
1737                                        "age": 14u64
1738                                    },
1739                                    "event_id": "$fLDqltg9Puj-kWItLSFVHPGN4YkgpYQf2qImPzdmgrE"
1740                                }
1741                            ]
1742                        }
1743                    }
1744                }
1745            }
1746        }));
1747
1748        client.receive_sync_response(response).await.unwrap();
1749
1750        let room = client.get_room(room_id).expect("Room not found");
1751        assert_eq!(room.state(), RoomState::Invited);
1752        assert_eq!(
1753            room.compute_display_name().await.expect("fetching display name failed").into_inner(),
1754            RoomDisplayName::Calculated("Kyra".to_owned())
1755        );
1756    }
1757
1758    #[async_test]
1759    async fn test_deserialization_failure() {
1760        let user_id = user_id!("@alice:example.org");
1761        let room_id = room_id!("!ithpyNKDtmhneaTQja:example.org");
1762
1763        let client = BaseClient::new(
1764            StoreConfig::new(CrossProcessLockConfig::SingleProcess),
1765            ThreadingSupport::Disabled,
1766            DmRoomDefinition::default(),
1767        );
1768        client
1769            .activate(
1770                SessionMeta { user_id: user_id.to_owned(), device_id: "FOOBAR".into() },
1771                RoomLoadSettings::default(),
1772                #[cfg(feature = "e2e-encryption")]
1773                None,
1774            )
1775            .await
1776            .unwrap();
1777
1778        let response = ruma_response_from_json(&json!({
1779            "next_batch": "asdkl;fjasdkl;fj;asdkl;f",
1780            "rooms": {
1781                "join": {
1782                    "!ithpyNKDtmhneaTQja:example.org": {
1783                        "state": {
1784                            "events": [
1785                                {
1786                                    "invalid": "invalid",
1787                                },
1788                                {
1789                                    "content": {
1790                                        "name": "The room name"
1791                                    },
1792                                    "event_id": "$143273582443PhrSn:example.org",
1793                                    "origin_server_ts": 1432735824653u64,
1794                                    "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
1795                                    "sender": "@example:example.org",
1796                                    "state_key": "",
1797                                    "type": "m.room.name",
1798                                    "unsigned": {
1799                                        "age": 1234
1800                                    }
1801                                },
1802                            ]
1803                        }
1804                    }
1805                }
1806            }
1807        }));
1808
1809        client.receive_sync_response(response).await.unwrap();
1810        client
1811            .state_store()
1812            .get_state_event_static::<ruma::events::room::name::RoomNameEventContent>(room_id)
1813            .await
1814            .expect("Failed to fetch state event")
1815            .expect("State event not found")
1816            .deserialize()
1817            .expect("Failed to deserialize state event");
1818    }
1819
1820    #[async_test]
1821    async fn test_invited_members_arent_ignored() {
1822        let user_id = user_id!("@alice:example.org");
1823        let inviter_user_id = user_id!("@bob:example.org");
1824        let room_id = room_id!("!ithpyNKDtmhneaTQja:example.org");
1825
1826        let client = BaseClient::new(
1827            StoreConfig::new(CrossProcessLockConfig::SingleProcess),
1828            ThreadingSupport::Disabled,
1829            DmRoomDefinition::default(),
1830        );
1831        client
1832            .activate(
1833                SessionMeta { user_id: user_id.to_owned(), device_id: "FOOBAR".into() },
1834                RoomLoadSettings::default(),
1835                #[cfg(feature = "e2e-encryption")]
1836                None,
1837            )
1838            .await
1839            .unwrap();
1840
1841        // Preamble: let the SDK know about the room.
1842        let mut sync_builder = SyncResponseBuilder::new();
1843        let response = sync_builder
1844            .add_joined_room(matrix_sdk_test::JoinedRoomBuilder::new(room_id))
1845            .build_sync_response();
1846        client.receive_sync_response(response).await.unwrap();
1847
1848        // When I process the result of a /members request that only contains an
1849        // invited member,
1850        let request = api::membership::get_member_events::v3::Request::new(room_id.to_owned());
1851
1852        let raw_member_event = json!({
1853            "content": {
1854                "avatar_url": "mxc://localhost/fewjilfewjil42",
1855                "displayname": "Invited Alice",
1856                "membership": "invite"
1857            },
1858            "event_id": "$151800140517rfvjc:localhost",
1859            "origin_server_ts": 151800140,
1860            "room_id": room_id,
1861            "sender": inviter_user_id,
1862            "state_key": user_id,
1863            "type": "m.room.member",
1864            "unsigned": {
1865                "age": 13374242,
1866            }
1867        });
1868        let response = api::membership::get_member_events::v3::Response::new(vec![Raw::from_json(
1869            to_raw_value(&raw_member_event).unwrap(),
1870        )]);
1871
1872        // It's correctly processed,
1873        client.receive_all_members(room_id, &request, &response).await.unwrap();
1874
1875        let room = client.get_room(room_id).unwrap();
1876
1877        // And I can get the invited member display name and avatar.
1878        let member = room.get_member(user_id).await.expect("ok").expect("exists");
1879
1880        assert_eq!(member.user_id(), user_id);
1881        assert_eq!(member.display_name().unwrap(), "Invited Alice");
1882        assert_eq!(member.avatar_url().unwrap().to_string(), "mxc://localhost/fewjilfewjil42");
1883    }
1884
1885    #[async_test]
1886    async fn test_reinvited_members_get_a_display_name() {
1887        let user_id = user_id!("@alice:example.org");
1888        let inviter_user_id = user_id!("@bob:example.org");
1889        let room_id = room_id!("!ithpyNKDtmhneaTQja:example.org");
1890
1891        let client = BaseClient::new(
1892            StoreConfig::new(CrossProcessLockConfig::SingleProcess),
1893            ThreadingSupport::Disabled,
1894            DmRoomDefinition::default(),
1895        );
1896        client
1897            .activate(
1898                SessionMeta { user_id: user_id.to_owned(), device_id: "FOOBAR".into() },
1899                RoomLoadSettings::default(),
1900                #[cfg(feature = "e2e-encryption")]
1901                None,
1902            )
1903            .await
1904            .unwrap();
1905
1906        // Preamble: let the SDK know about the room, and that the invited user
1907        // left it.
1908        let f = EventFactory::new().sender(user_id);
1909        let mut sync_builder = SyncResponseBuilder::new();
1910        let response = sync_builder
1911            .add_joined_room(
1912                matrix_sdk_test::JoinedRoomBuilder::new(room_id)
1913                    .add_state_event(f.member(user_id).leave()),
1914            )
1915            .build_sync_response();
1916        client.receive_sync_response(response).await.unwrap();
1917
1918        // Now, say that the user has been re-invited.
1919        let request = api::membership::get_member_events::v3::Request::new(room_id.to_owned());
1920
1921        let raw_member_event = json!({
1922            "content": {
1923                "avatar_url": "mxc://localhost/fewjilfewjil42",
1924                "displayname": "Invited Alice",
1925                "membership": "invite"
1926            },
1927            "event_id": "$151800140517rfvjc:localhost",
1928            "origin_server_ts": 151800140,
1929            "room_id": room_id,
1930            "sender": inviter_user_id,
1931            "state_key": user_id,
1932            "type": "m.room.member",
1933            "unsigned": {
1934                "age": 13374242,
1935            }
1936        });
1937        let response = api::membership::get_member_events::v3::Response::new(vec![Raw::from_json(
1938            to_raw_value(&raw_member_event).unwrap(),
1939        )]);
1940
1941        // It's correctly processed,
1942        client.receive_all_members(room_id, &request, &response).await.unwrap();
1943
1944        let room = client.get_room(room_id).unwrap();
1945
1946        // And I can get the invited member display name and avatar.
1947        let member = room.get_member(user_id).await.expect("ok").expect("exists");
1948
1949        assert_eq!(member.user_id(), user_id);
1950        assert_eq!(member.display_name().unwrap(), "Invited Alice");
1951        assert_eq!(member.avatar_url().unwrap().to_string(), "mxc://localhost/fewjilfewjil42");
1952    }
1953
1954    async fn base_client_with_joined_room(room_id: &RoomId) -> BaseClient {
1955        let client = logged_in_base_client(Some(user_id!("@alice:example.org"))).await;
1956
1957        let mut sync_builder = SyncResponseBuilder::new();
1958        let response = sync_builder
1959            .add_joined_room(matrix_sdk_test::JoinedRoomBuilder::new(room_id))
1960            .build_sync_response();
1961        client.receive_sync_response(response).await.unwrap();
1962
1963        client
1964    }
1965
1966    #[async_test]
1967    async fn test_inactive_members_do_not_make_a_display_name_ambiguous() {
1968        let joined_user_id = user_id!("@bob:example.org");
1969        let left_user_id = user_id!("@carol:example.org");
1970        let room_id = room_id!("!ithpyNKDtmhneaTQja:example.org");
1971
1972        let client = base_client_with_joined_room(room_id).await;
1973
1974        // A joined member and a member who left share a display name.
1975        let f = EventFactory::new().room(room_id);
1976        let request = api::membership::get_member_events::v3::Request::new(room_id.to_owned());
1977        let response = api::membership::get_member_events::v3::Response::new(vec![
1978            f.member(joined_user_id).display_name("Amandine").into_raw(),
1979            f.member(left_user_id)
1980                .display_name("Amandine")
1981                .membership(MembershipState::Leave)
1982                .into_raw(),
1983        ]);
1984
1985        client.receive_all_members(room_id, &request, &response).await.unwrap();
1986
1987        let room = client.get_room(room_id).unwrap();
1988        let member = room.get_member(joined_user_id).await.expect("ok").expect("exists");
1989
1990        assert_eq!(member.display_name().unwrap(), "Amandine");
1991        assert!(!member.name_ambiguous());
1992    }
1993
1994    #[async_test]
1995    async fn test_active_members_make_a_display_name_ambiguous() {
1996        let joined_user_id = user_id!("@bob:example.org");
1997        let invited_user_id = user_id!("@carol:example.org");
1998        let room_id = room_id!("!ithpyNKDtmhneaTQja:example.org");
1999
2000        let client = base_client_with_joined_room(room_id).await;
2001
2002        // A joined member and an invited member share a display name.
2003        let f = EventFactory::new().room(room_id);
2004        let request = api::membership::get_member_events::v3::Request::new(room_id.to_owned());
2005        let response = api::membership::get_member_events::v3::Response::new(vec![
2006            f.member(joined_user_id).display_name("Amandine").into_raw(),
2007            f.member(invited_user_id)
2008                .display_name("Amandine")
2009                .membership(MembershipState::Invite)
2010                .into_raw(),
2011        ]);
2012
2013        client.receive_all_members(room_id, &request, &response).await.unwrap();
2014
2015        // Then both display names are ambiguous.
2016        let room = client.get_room(room_id).unwrap();
2017
2018        let joined = room.get_member(joined_user_id).await.expect("ok").expect("exists");
2019        assert!(joined.name_ambiguous());
2020
2021        let invited = room.get_member(invited_user_id).await.expect("ok").expect("exists");
2022        assert!(invited.name_ambiguous());
2023    }
2024
2025    #[cfg(feature = "unstable-msc4426")]
2026    #[async_test]
2027    async fn test_room_member_carries_global_profile_status() {
2028        let user_id = user_id!("@alice:example.org");
2029        let room_id = room_id!("!ithpyNKDtmhneaTQja:example.org");
2030
2031        let client = BaseClient::new(
2032            StoreConfig::new(CrossProcessLockConfig::SingleProcess),
2033            ThreadingSupport::Disabled,
2034            DmRoomDefinition::default(),
2035        );
2036        client
2037            .activate(
2038                SessionMeta { user_id: user_id.to_owned(), device_id: "FOOBAR".into() },
2039                RoomLoadSettings::default(),
2040                #[cfg(feature = "e2e-encryption")]
2041                None,
2042            )
2043            .await
2044            .unwrap();
2045
2046        // Let the SDK know about the room, with the user as a joined member.
2047        let f = EventFactory::new().sender(user_id);
2048        let mut sync_builder = SyncResponseBuilder::new();
2049        let response = sync_builder
2050            .add_joined_room(
2051                matrix_sdk_test::JoinedRoomBuilder::new(room_id).add_state_event(f.member(user_id)),
2052            )
2053            .build_sync_response();
2054        client.receive_sync_response(response).await.unwrap();
2055
2056        let room = client.get_room(room_id).unwrap();
2057
2058        // Without a global profile, the member has no status.
2059        let member = room.get_member(user_id).await.expect("ok").expect("exists");
2060        assert!(member.status().is_none());
2061
2062        // Save a global profile carrying an `m.status` for the member.
2063        let mut changes = StateChanges::default();
2064        changes.global_profiles.insert(user_id.to_owned(), {
2065            let mut profile_changes = UserProfileChanges::new();
2066            profile_changes.insert_updated_value(ProfileFieldValue::Status(
2067                StatusProfileField::new("Working".to_owned(), "💻".to_owned()),
2068            ));
2069            UserProfileUpdate::Updated(profile_changes)
2070        });
2071        client.state_store().save_changes(&changes).await.unwrap();
2072
2073        // `get_member` surfaces the status from the global profile.
2074        let member = room.get_member(user_id).await.expect("ok").expect("exists");
2075        let status = member.status().expect("status is set");
2076        assert_eq!(status.text, "Working");
2077        assert_eq!(status.emoji, "💻");
2078
2079        // `members` surfaces it too.
2080        let members = room.members(RoomMemberships::JOIN).await.unwrap();
2081        let member =
2082            members.iter().find(|m| m.user_id() == user_id).expect("member is in the list");
2083        let status = member.status().expect("status is set");
2084        assert_eq!(status.text, "Working");
2085        assert_eq!(status.emoji, "💻");
2086    }
2087
2088    #[async_test]
2089    async fn test_ignored_user_list_changes() {
2090        let user_id = user_id!("@alice:example.org");
2091        let client = BaseClient::new(
2092            StoreConfig::new(CrossProcessLockConfig::SingleProcess),
2093            ThreadingSupport::Disabled,
2094            DmRoomDefinition::default(),
2095        );
2096
2097        client
2098            .activate(
2099                SessionMeta { user_id: user_id.to_owned(), device_id: "FOOBAR".into() },
2100                RoomLoadSettings::default(),
2101                #[cfg(feature = "e2e-encryption")]
2102                None,
2103            )
2104            .await
2105            .unwrap();
2106
2107        let mut subscriber = client.subscribe_to_ignore_user_list_changes();
2108        assert!(subscriber.next().now_or_never().is_none());
2109
2110        let f = EventFactory::new();
2111        let mut sync_builder = SyncResponseBuilder::new();
2112        let response = sync_builder
2113            .add_global_account_data(f.ignored_user_list([User::Bob.into()]))
2114            .build_sync_response();
2115        client.receive_sync_response(response).await.unwrap();
2116
2117        assert_let!(Some(ignored) = subscriber.next().await);
2118        assert_eq!(ignored, [User::Bob]);
2119
2120        // Receive the same response.
2121        let response = sync_builder
2122            .add_global_account_data(f.ignored_user_list([User::Bob.into()]))
2123            .build_sync_response();
2124        client.receive_sync_response(response).await.unwrap();
2125
2126        // No changes in the ignored list.
2127        assert!(subscriber.next().now_or_never().is_none());
2128
2129        // Now remove Bob from the ignored list.
2130        let response =
2131            sync_builder.add_global_account_data(f.ignored_user_list([])).build_sync_response();
2132        client.receive_sync_response(response).await.unwrap();
2133
2134        assert_let!(Some(ignored) = subscriber.next().await);
2135        assert!(ignored.is_empty());
2136    }
2137
2138    async fn store_with_ignored_user() -> StoreConfig {
2139        let store = StoreConfig::new(CrossProcessLockConfig::SingleProcess);
2140        let user_id = user_id!("@alice:example.org");
2141
2142        let client =
2143            BaseClient::new(store.clone(), ThreadingSupport::Disabled, DmRoomDefinition::default());
2144
2145        client
2146            .activate(
2147                SessionMeta { user_id: user_id.to_owned(), device_id: "FOOBAR".into() },
2148                RoomLoadSettings::default(),
2149                #[cfg(feature = "e2e-encryption")]
2150                None,
2151            )
2152            .await
2153            .unwrap();
2154
2155        // Ignore a user.
2156        let event_factory = EventFactory::new();
2157        let response = SyncResponseBuilder::new()
2158            .add_global_account_data(event_factory.ignored_user_list([User::Bob.into()]))
2159            .build_sync_response();
2160
2161        client.receive_sync_response(response).await.unwrap();
2162
2163        store
2164    }
2165
2166    #[async_test]
2167    async fn test_ignored_user_list_restored_on_activation() {
2168        let store = store_with_ignored_user().await;
2169        let user_id = user_id!("@alice:example.org");
2170
2171        // New client with the previously populated store.
2172        let client =
2173            BaseClient::new(store, ThreadingSupport::Disabled, DmRoomDefinition::default());
2174
2175        // Acrivation should hydrate the ignored user list.
2176        client
2177            .activate(
2178                SessionMeta { user_id: user_id.to_owned(), device_id: "FOOBAR".into() },
2179                RoomLoadSettings::default(),
2180                #[cfg(feature = "e2e-encryption")]
2181                None,
2182            )
2183            .await
2184            .unwrap();
2185
2186        let mut subscriber = client.subscribe_to_ignore_user_list_changes();
2187
2188        // The ignored user list is restored from the store.
2189        assert_eq!(subscriber.get(), [User::Bob]);
2190
2191        // No changes occurred after subscribing.
2192        assert!(subscriber.next().now_or_never().is_none());
2193    }
2194
2195    #[async_test]
2196    async fn test_is_user_ignored() {
2197        let ignored_user_id = user_id!("@alice:example.org");
2198        let client = logged_in_base_client(None).await;
2199
2200        let mut sync_builder = SyncResponseBuilder::new();
2201        let f = EventFactory::new();
2202        let response = sync_builder
2203            .add_global_account_data(f.ignored_user_list([ignored_user_id.to_owned()]))
2204            .build_sync_response();
2205        client.receive_sync_response(response).await.unwrap();
2206
2207        assert!(client.is_user_ignored(ignored_user_id).await);
2208    }
2209
2210    #[cfg(feature = "e2e-encryption")]
2211    #[async_test]
2212    async fn test_invite_details_are_set() {
2213        let user_id = user_id!("@alice:localhost");
2214        let client = logged_in_base_client(Some(user_id)).await;
2215        let known_room_id = room_id!("!invited:localhost");
2216        let unknown_room_id = room_id!("!unknown:localhost");
2217
2218        let mut sync_builder = SyncResponseBuilder::new();
2219        let response = sync_builder
2220            .add_invited_room(InvitedRoomBuilder::new(known_room_id))
2221            .build_sync_response();
2222        client.receive_sync_response(response).await.unwrap();
2223
2224        // Let us first check the initial state, we should have a room in the
2225        // invite state.
2226        let invited_room = client
2227            .get_room(known_room_id)
2228            .expect("The sync should have created a room in the invited state");
2229
2230        assert_eq!(invited_room.state(), RoomState::Invited);
2231        assert!(
2232            client.get_pending_key_bundle_details_for_room(known_room_id).await.unwrap().is_none()
2233        );
2234
2235        // Now we join the room.
2236        let joined_room = client
2237            .room_joined(known_room_id, Some(user_id.to_owned()))
2238            .await
2239            .expect("We should be able to mark a room as joined");
2240
2241        // Yup, we now have some invite details.
2242        assert_eq!(joined_room.state(), RoomState::Joined);
2243        assert_let!(
2244            Ok(Some(details)) = client.get_pending_key_bundle_details_for_room(known_room_id).await
2245        );
2246        assert_eq!(details.inviter, user_id);
2247
2248        // If we didn't know about the room before the join, we assume that
2249        // there wasn't an invite and we don't record the timestamp.
2250        assert!(client.get_room(unknown_room_id).is_none());
2251        let unknown_room = client
2252            .room_joined(unknown_room_id, Some(user_id.to_owned()))
2253            .await
2254            .expect("We should be able to mark a room as joined");
2255
2256        assert_eq!(unknown_room.state(), RoomState::Joined);
2257        assert!(
2258            client
2259                .get_pending_key_bundle_details_for_room(unknown_room_id)
2260                .await
2261                .unwrap()
2262                .is_none()
2263        );
2264
2265        sync_builder.clear();
2266        let response =
2267            sync_builder.add_left_room(LeftRoomBuilder::new(known_room_id)).build_sync_response();
2268        client.receive_sync_response(response).await.unwrap();
2269
2270        // Now that we left the room, we shouldn't have any details anymore.
2271        let left_room = client
2272            .get_room(known_room_id)
2273            .expect("The sync should have created a room in the invited state");
2274
2275        assert_eq!(left_room.state(), RoomState::Left);
2276        assert!(
2277            client.get_pending_key_bundle_details_for_room(known_room_id).await.unwrap().is_none()
2278        );
2279    }
2280}