Skip to main content

matrix_sdk/client/
mod.rs

1// Copyright 2020 Damir Jelić
2// Copyright 2020 The Matrix.org Foundation C.I.C.
3// Copyright 2022 Famedly GmbH
4// Copyright 2026 Nordeck IT + Consulting GmbH <info@nordeck.net>
5//
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10//     http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18#[cfg(feature = "unstable-msc4536")]
19use std::sync::OnceLock as StdOnceLock;
20use std::{
21    collections::{BTreeMap, BTreeSet, btree_map},
22    fmt::{self, Debug},
23    future::{Future, ready},
24    pin::Pin,
25    sync::{Arc, Mutex as StdMutex, RwLock as StdRwLock, Weak},
26    time::Duration,
27};
28
29use async_stream::stream;
30use eyeball::{SharedObservable, Subscriber};
31use eyeball_im::{Vector, VectorDiff};
32use futures_core::Stream;
33use futures_util::{StreamExt, future::OptionFuture, join};
34#[cfg(feature = "e2e-encryption")]
35use matrix_sdk_base::crypto::{
36    DecryptionSettings, store::LockableCryptoStore, store::types::RoomPendingKeyBundleDetails,
37    vodozemac::olm,
38};
39use matrix_sdk_base::{
40    BaseClient, DmRoomDefinition, RoomInfoNotableUpdate, RoomState, RoomStateFilter,
41    SendOutsideWasm, SessionMeta, StateStoreDataKey, StateStoreDataValue, StoreError,
42    SyncOutsideWasm, ThreadingSupport,
43    deserialized_responses::EncryptionInfo,
44    event_cache::store::EventCacheStoreLock,
45    media::store::MediaStoreLock,
46    store::{DynStateStore, RoomLoadSettings, SupportedVersionsResponse, WellKnownResponse},
47    sync::{Notification, RoomUpdates},
48    task_monitor::TaskMonitor,
49};
50use matrix_sdk_common::{cross_process_lock::CrossProcessLockConfig, sleep::sleep, ttl::TtlValue};
51#[cfg(feature = "e2e-encryption")]
52use ruma::events::{InitialStateEvent, room::encryption::RoomEncryptionEventContent};
53use ruma::{
54    DeviceId, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName,
55    OwnedUserId, RoomAliasId, RoomId, RoomOrAliasId, ServerName, UInt, UserId,
56    api::{
57        FeatureFlag, MatrixVersion, Metadata, OutgoingRequest, SupportedVersions,
58        client::{
59            account::whoami,
60            alias::{create_alias, delete_alias, get_alias},
61            authenticated_media,
62            delayed_events::update_delayed_event,
63            device::{self, delete_devices, get_devices, update_device},
64            directory::{get_public_rooms, get_public_rooms_filtered},
65            discovery::{discover_homeserver, get_supported_versions},
66            filter::{FilterDefinition, create_filter::v3::Request as FilterUploadRequest},
67            knock::knock_room,
68            media,
69            membership::{join_room_by_id, join_room_by_id_or_alias},
70            presence::{get_presence, set_presence as set_presence_status},
71            reporting::report_user,
72            retention::get_retention_configuration,
73            room::create_room,
74            rtc::{
75                RtcTransport,
76                livekit::{delegate_delayed_leave, get_token},
77                transports,
78            },
79            session::login::v3::DiscoveryInfo,
80            sync::sync_events,
81            threads::get_thread_subscriptions_changes,
82            uiaa,
83            user_directory::search_users,
84        },
85        error::{ErrorKind, FromHttpResponseError, UnknownTokenErrorData},
86        path_builder::PathBuilder,
87    },
88    assign,
89    events::{
90        AnyToDeviceEvent, ToDeviceEventType, beacon_info::OriginalSyncBeaconInfoEvent,
91        direct::DirectUserIdentifier,
92    },
93    presence::PresenceState,
94    push::Ruleset,
95    serde::Raw,
96    time::Instant,
97};
98use serde::de::DeserializeOwned;
99use tokio::sync::{Mutex, OnceCell, RwLock, RwLockReadGuard, broadcast, mpsc::unbounded_channel};
100use tracing::{Instrument, Span, debug, error, info, instrument, trace, warn};
101use url::Url;
102
103use self::{
104    caches::{Cache, CachedValue, ClientCaches},
105    futures::SendRequest,
106};
107#[cfg(feature = "unstable-msc4536")]
108use crate::client::global_profiles::GlobalProfileFetcher;
109use crate::{
110    Account, AuthApi, AuthSession, Error, HttpError, Media, Pusher, RefreshTokenError, Result,
111    Room, SessionTokens, TransmissionProgress,
112    authentication::{
113        AuthCtx, AuthData, ReloadSessionCallback, SaveSessionCallback, matrix::MatrixAuth,
114        oauth::OAuth,
115    },
116    client::{
117        homeserver_capabilities::HomeserverCapabilities,
118        thread_subscriptions::ThreadSubscriptionCatchup,
119    },
120    config::{RequestConfig, SyncToken},
121    deduplicating_handler::DeduplicatingHandler,
122    error::HttpResult,
123    event_cache::EventCache,
124    event_handler::{
125        EventHandler, EventHandlerContext, EventHandlerDropGuard, EventHandlerHandle,
126        EventHandlerStore, ObservableEventHandler, SyncEvent,
127    },
128    http_client::{HttpClient, SupportedAuthScheme, SupportedPathBuilder},
129    latest_events::LatestEvents,
130    live_locations_observer::BeaconInfoUpdate,
131    media::{MediaError, MediaFetcher},
132    notification_settings::NotificationSettings,
133    room::RoomMember,
134    room_preview::RoomPreview,
135    send_queue::{SendQueue, SendQueueData},
136    sliding_sync::Version as SlidingSyncVersion,
137    sync::{RoomUpdate, SyncResponse},
138};
139#[cfg(feature = "e2e-encryption")]
140use crate::{
141    cross_process_lock::CrossProcessLock,
142    encryption::{
143        DuplicateOneTimeKeyErrorMessage, Encryption, EncryptionData, EncryptionSettings,
144        VerificationState,
145    },
146};
147
148mod builder;
149pub(crate) mod caches;
150pub(crate) mod futures;
151#[cfg(feature = "unstable-msc4536")]
152pub(crate) mod global_profiles;
153pub(crate) mod homeserver_capabilities;
154pub(crate) mod thread_subscriptions;
155
156pub use self::builder::{ClientBuildError, ClientBuilder, sanitize_server_name};
157#[cfg(feature = "experimental-search")]
158use crate::search_index::SearchIndex;
159
160/// How long the cached homeserver message retention configuration is
161/// considered fresh: 6 hours.
162const RETENTION_CONFIGURATION_TTL: Duration = Duration::from_hours(6);
163
164#[cfg(not(target_family = "wasm"))]
165type NotificationHandlerFut = Pin<Box<dyn Future<Output = ()> + Send>>;
166#[cfg(target_family = "wasm")]
167type NotificationHandlerFut = Pin<Box<dyn Future<Output = ()>>>;
168
169#[cfg(not(target_family = "wasm"))]
170type NotificationHandlerFn =
171    Box<dyn Fn(Notification, Room, Client) -> NotificationHandlerFut + Send + Sync>;
172#[cfg(target_family = "wasm")]
173type NotificationHandlerFn = Box<dyn Fn(Notification, Room, Client) -> NotificationHandlerFut>;
174
175/// Enum controlling if a loop running callbacks should continue or abort.
176///
177/// This is mainly used in the [`sync_with_callback`] method, the return value
178/// of the provided callback controls if the sync loop should be exited.
179///
180/// [`sync_with_callback`]: #method.sync_with_callback
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum LoopCtrl {
183    /// Continue running the loop.
184    Continue,
185    /// Break out of the loop.
186    Break,
187}
188
189/// Represents changes that can occur to a `Client`s `Session`.
190#[derive(Debug, Clone, PartialEq)]
191pub enum SessionChange {
192    /// The session's token is no longer valid.
193    UnknownToken(UnknownTokenErrorData),
194    /// The session's tokens have been refreshed.
195    TokensRefreshed,
196}
197
198/// Information about the server vendor obtained from the federation API.
199#[derive(Debug, Clone, PartialEq, Eq)]
200#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
201pub struct ServerVendorInfo {
202    /// The server name.
203    pub server_name: String,
204    /// The server version.
205    pub version: String,
206}
207
208/// Information about a map tile server advertised by the homeserver through the
209/// `tile_server` field of the matrix client well-known (MSC3488).
210#[derive(Debug, Clone, PartialEq, Eq, Hash)]
211#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
212pub struct TileServerInfo {
213    /// The URL of a map tile server's `style.json` file. See the
214    /// [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/)
215    /// for more details.
216    pub map_style_url: String,
217}
218
219impl From<discover_homeserver::TileServerInfo> for TileServerInfo {
220    fn from(value: discover_homeserver::TileServerInfo) -> Self {
221        Self { map_style_url: value.map_style_url }
222    }
223}
224
225/// An async/await enabled Matrix client.
226///
227/// All of the state is held in an `Arc` so the `Client` can be cloned freely.
228#[derive(Clone)]
229pub struct Client {
230    pub(crate) inner: Arc<ClientInner>,
231}
232
233#[derive(Default)]
234pub(crate) struct ClientLocks {
235    /// Lock ensuring that only a single room may be marked as a DM at once.
236    /// Look at the [`Account::mark_as_dm()`] method for a more detailed
237    /// explanation.
238    pub(crate) mark_as_dm_lock: Mutex<()>,
239
240    /// Lock ensuring that only a single image pack may be enabled or disabled
241    /// globally at once. Look at the
242    /// [`Account::set_image_pack_enabled_globally()`] method for a more
243    /// detailed explanation.
244    pub(crate) image_pack_rooms_lock: Mutex<()>,
245
246    /// Lock ensuring that only a single secret store is getting opened at the
247    /// same time.
248    ///
249    /// This is important so we don't accidentally create multiple different new
250    /// default secret storage keys.
251    #[cfg(feature = "e2e-encryption")]
252    pub(crate) open_secret_store_lock: Mutex<()>,
253
254    /// Lock ensuring that we're only storing a single secret at a time.
255    ///
256    /// Take a look at the [`SecretStore::put_secret`] method for a more
257    /// detailed explanation.
258    ///
259    /// [`SecretStore::put_secret`]: crate::encryption::secret_storage::SecretStore::put_secret
260    #[cfg(feature = "e2e-encryption")]
261    pub(crate) store_secret_lock: Mutex<()>,
262
263    /// Lock ensuring that only one method at a time might modify our backup.
264    #[cfg(feature = "e2e-encryption")]
265    pub(crate) backup_modify_lock: Mutex<()>,
266
267    /// Lock ensuring that we're going to attempt to upload backups for a single
268    /// requester.
269    #[cfg(feature = "e2e-encryption")]
270    pub(crate) backup_upload_lock: Mutex<()>,
271
272    /// Handler making sure we only have one group session sharing request in
273    /// flight per room.
274    #[cfg(feature = "e2e-encryption")]
275    pub(crate) group_session_deduplicated_handler: DeduplicatingHandler<OwnedRoomId>,
276
277    /// Lock making sure we're only doing one key claim request at a time.
278    #[cfg(feature = "e2e-encryption")]
279    pub(crate) key_claim_lock: Mutex<()>,
280
281    /// Handler to ensure that only one members request is running at a time,
282    /// given a room.
283    pub(crate) members_request_deduplicated_handler: DeduplicatingHandler<OwnedRoomId>,
284
285    /// Handler to ensure that only one encryption state request is running at a
286    /// time, given a room.
287    pub(crate) encryption_state_deduplicated_handler: DeduplicatingHandler<OwnedRoomId>,
288
289    /// Deduplicating handler for sending read receipts. The string is an
290    /// internal implementation detail, see [`Self::send_single_receipt`].
291    pub(crate) read_receipt_deduplicated_handler: DeduplicatingHandler<(String, OwnedEventId)>,
292
293    #[cfg(feature = "e2e-encryption")]
294    pub(crate) cross_process_crypto_store_lock: OnceCell<CrossProcessLock<LockableCryptoStore>>,
295
296    /// Latest "generation" of data known by the crypto store.
297    ///
298    /// This is a counter that only increments, set in the database (and can
299    /// wrap). It's incremented whenever some process acquires a lock for the
300    /// first time. *This assumes the crypto store lock is being held, to avoid
301    /// data races on writing to this value in the store*.
302    ///
303    /// The current process will maintain this value in local memory and in the
304    /// DB over time. Observing a different value than the one read in memory,
305    /// when reading from the store indicates that somebody else has written
306    /// into the database under our feet.
307    ///
308    /// TODO: this should live in the `OlmMachine`, since it's information
309    /// related to the lock. As of today (2023-07-28), we blow up the entire olm
310    /// machine when there's a generation mismatch. So storing the generation in
311    /// the olm machine would make the client think there's _always_ a mismatch,
312    /// and that's why we need to store the generation outside the `OlmMachine`.
313    #[cfg(feature = "e2e-encryption")]
314    pub(crate) crypto_store_generation: Arc<Mutex<Option<u64>>>,
315}
316
317pub(crate) struct ClientInner {
318    /// All the data related to authentication and authorization.
319    pub(crate) auth_ctx: Arc<AuthCtx>,
320
321    /// The URL of the server.
322    ///
323    /// Not to be confused with the `Self::homeserver`. `server` is usually the
324    /// server part in a user ID, e.g. with `@mnt_io:matrix.org`, here
325    /// `matrix.org` is the server, whilst `matrix-client.matrix.org` is the
326    /// homeserver (at the time of writing — 2024-08-28).
327    ///
328    /// This value is optional depending on how the `Client` has been built. If
329    /// it's been built from a homeserver URL directly, we don't know the
330    /// server. However, if the `Client` has been built from a server URL or
331    /// name, then the homeserver has been discovered, and we know both.
332    server: StdRwLock<Option<Url>>,
333
334    /// The URL of the homeserver to connect to.
335    ///
336    /// This is the URL for the client-server Matrix API.
337    homeserver: StdRwLock<Url>,
338
339    /// The sliding sync version.
340    sliding_sync_version: StdRwLock<SlidingSyncVersion>,
341
342    /// Default presence state to send with generated sync requests.
343    ///
344    /// This is process-local. Consumers that create clients in multiple
345    /// processes must configure it in each process.
346    sync_presence: Arc<StdRwLock<PresenceState>>,
347
348    /// The underlying HTTP client.
349    pub(crate) http_client: HttpClient,
350
351    /// User session data.
352    pub(super) base_client: BaseClient,
353
354    /// Collection of in-memory caches for the [`Client`].
355    pub(crate) caches: ClientCaches,
356
357    /// Collection of locks individual client methods might want to use, either
358    /// to ensure that only a single call to a method happens at once or to
359    /// deduplicate multiple calls to a method.
360    pub(crate) locks: ClientLocks,
361
362    /// The cross-process lock configuration.
363    ///
364    /// The SDK provides cross-process store locks (see
365    /// [`matrix_sdk_common::cross_process_lock::CrossProcessLock`]) when
366    /// [`CrossProcessLockConfig::MultiProcess`] is used.
367    ///
368    /// If multiple `Client`s are running in different processes, this value
369    /// MUST be different for each `Client`.
370    cross_process_lock_config: CrossProcessLockConfig,
371
372    /// A mapping of the times at which the current user sent typing notices,
373    /// keyed by room.
374    pub(crate) typing_notice_times: StdRwLock<BTreeMap<OwnedRoomId, Instant>>,
375
376    /// Event handlers. See `add_event_handler`.
377    pub(crate) event_handlers: EventHandlerStore,
378
379    /// Notification handlers. See `register_notification_handler`.
380    notification_handlers: RwLock<Vec<NotificationHandlerFn>>,
381
382    /// The sender-side of channels used to receive room updates.
383    pub(crate) room_update_channels: StdMutex<BTreeMap<OwnedRoomId, broadcast::Sender<RoomUpdate>>>,
384
385    /// The sender-side of a channel used to observe all the room updates of a
386    /// sync response.
387    pub(crate) room_updates_sender: broadcast::Sender<RoomUpdates>,
388
389    /// Whether the client should update its homeserver URL with the discovery
390    /// information present in the login response.
391    respect_login_well_known: bool,
392
393    /// Whether all the `.well-known/matrix/client` lookups are disabled.
394    ///
395    /// See [`ClientBuilder::disable_well_known_lookup`].
396    well_known_lookup_disabled: StdRwLock<bool>,
397
398    /// An event that can be listened on to wait for a successful sync. The
399    /// event will only be fired if a sync loop is running. Can be used for
400    /// synchronization, e.g. if we send out a request to create a room, we can
401    /// wait for the sync to get the data to fetch a room object from the state
402    /// store.
403    pub(crate) sync_beat: event_listener::Event,
404
405    /// A central cache for events.
406    pub(crate) event_cache: OnceCell<EventCache>,
407
408    /// End-to-end encryption related state.
409    #[cfg(feature = "e2e-encryption")]
410    pub(crate) e2ee: EncryptionData,
411
412    /// The verification state of our own device.
413    #[cfg(feature = "e2e-encryption")]
414    pub(crate) verification_state: SharedObservable<VerificationState>,
415
416    /// Whether to enable the experimental support for sending and receiving
417    /// encrypted room history on invite, per [MSC4268].
418    ///
419    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
420    #[cfg(feature = "e2e-encryption")]
421    pub(crate) enable_share_history_on_invite: bool,
422
423    /// Data related to the [`SendQueue`].
424    ///
425    /// [`SendQueue`]: crate::send_queue::SendQueue
426    pub(crate) send_queue_data: Arc<SendQueueData>,
427
428    /// The `max_upload_size` value of the homeserver, it contains the max
429    /// request size you can send.
430    pub(crate) server_max_upload_size: Mutex<OnceCell<UInt>>,
431
432    /// The entry point to get the [`LatestEvent`] of rooms and threads.
433    ///
434    /// [`LatestEvent`]: crate::latest_event::LatestEvent
435    latest_events: OnceCell<LatestEvents>,
436
437    /// Service handling the catching up of thread subscriptions in the
438    /// background.
439    thread_subscription_catchup: OnceCell<Arc<ThreadSubscriptionCatchup>>,
440
441    /// Service fetching missing global profiles in the background, created
442    /// lazily on first use.
443    #[cfg(feature = "unstable-msc4536")]
444    global_profile_fetcher: StdOnceLock<GlobalProfileFetcher>,
445
446    #[cfg(feature = "experimental-search")]
447    /// Handler for [`RoomIndex`]'s of each room
448    search_index: SearchIndex,
449
450    /// A monitor for background tasks spawned by the client.
451    pub(crate) task_monitor: TaskMonitor,
452
453    /// A sender to notify subscribers about duplicate key upload errors
454    /// triggered by requests to /keys/upload.
455    #[cfg(feature = "e2e-encryption")]
456    pub(crate) duplicate_key_upload_error_sender:
457        broadcast::Sender<Option<DuplicateOneTimeKeyErrorMessage>>,
458
459    pub(crate) media_fetcher: RwLock<Arc<dyn MediaFetcher>>,
460
461    /// When `Some`, `m.call` auto-sync is enabled and the held
462    /// [`AutomaticCallStatus`] owns the event handler registration. Dropping
463    /// the `Option` (via [`Client::enable_automatic_call_status`]) drops the
464    /// syncer, which drops its `EventHandlerDropGuard`, which deregisters the
465    /// handler.
466    ///
467    /// [`AutomaticCallStatus`]: crate::automatic_call_status::AutomaticCallStatus
468    #[cfg(feature = "unstable-msc4426")]
469    pub(crate) automatic_call_status:
470        StdMutex<Option<crate::automatic_call_status::AutomaticCallStatus>>,
471}
472
473impl ClientInner {
474    /// Create a new `ClientInner`.
475    ///
476    /// All the fields passed as parameters here are those that must be cloned
477    /// upon instantiation of a sub-client, e.g. a client specialized for
478    /// notifications.
479    #[allow(clippy::too_many_arguments)]
480    async fn new(
481        auth_ctx: Arc<AuthCtx>,
482        server: Option<Url>,
483        homeserver: Url,
484        sliding_sync_version: SlidingSyncVersion,
485        sync_presence: Arc<StdRwLock<PresenceState>>,
486        http_client: HttpClient,
487        base_client: BaseClient,
488        supported_versions: CachedValue<TtlValue<SupportedVersions>>,
489        well_known: CachedValue<TtlValue<Option<WellKnownResponse>>>,
490        retention_configuration: Option<TtlValue<get_retention_configuration::msc1763::Response>>,
491        respect_login_well_known: bool,
492        well_known_lookup_disabled: bool,
493        enable_automatic_back_pagination: bool,
494        enable_event_cache: bool,
495        send_queue: Arc<SendQueueData>,
496        #[cfg(feature = "e2e-encryption")] encryption_settings: EncryptionSettings,
497        #[cfg(feature = "e2e-encryption")] enable_share_history_on_invite: bool,
498        cross_process_lock_config: CrossProcessLockConfig,
499        #[cfg(feature = "experimental-search")] search_index_handler: SearchIndex,
500        thread_subscription_catchup: OnceCell<Arc<ThreadSubscriptionCatchup>>,
501        media_fetcher: Arc<dyn MediaFetcher>,
502    ) -> Arc<Self> {
503        let caches = ClientCaches {
504            supported_versions: Cache::with_value(supported_versions),
505            well_known: Cache::with_value(well_known),
506            server_metadata: Cache::new(),
507            homeserver_capabilities: Cache::new(),
508            rtc_transports: Cache::new(),
509            retention_configuration: SharedObservable::new(retention_configuration),
510        };
511
512        let client = Self {
513            server: StdRwLock::new(server),
514            homeserver: StdRwLock::new(homeserver),
515            auth_ctx,
516            sliding_sync_version: StdRwLock::new(sliding_sync_version),
517            sync_presence,
518            http_client,
519            base_client,
520            caches,
521            locks: Default::default(),
522            cross_process_lock_config,
523            typing_notice_times: Default::default(),
524            event_handlers: Default::default(),
525            notification_handlers: Default::default(),
526            room_update_channels: Default::default(),
527            // A single `RoomUpdates` is sent once per sync, so we assume that
528            // 32 is sufficient ballast for all observers to catch up.
529            room_updates_sender: broadcast::Sender::new(32),
530            respect_login_well_known,
531            well_known_lookup_disabled: StdRwLock::new(well_known_lookup_disabled),
532            sync_beat: event_listener::Event::new(),
533            event_cache: OnceCell::new(),
534            send_queue_data: send_queue,
535            latest_events: OnceCell::new(),
536            #[cfg(feature = "e2e-encryption")]
537            e2ee: EncryptionData::new(encryption_settings),
538            #[cfg(feature = "e2e-encryption")]
539            verification_state: SharedObservable::new(VerificationState::Unknown),
540            #[cfg(feature = "e2e-encryption")]
541            enable_share_history_on_invite,
542            server_max_upload_size: Mutex::new(OnceCell::new()),
543            #[cfg(feature = "experimental-search")]
544            search_index: search_index_handler,
545            thread_subscription_catchup,
546            #[cfg(feature = "unstable-msc4536")]
547            global_profile_fetcher: StdOnceLock::new(),
548            task_monitor: TaskMonitor::new(),
549            #[cfg(feature = "e2e-encryption")]
550            duplicate_key_upload_error_sender: broadcast::channel(1).0,
551            media_fetcher: RwLock::new(media_fetcher),
552            #[cfg(feature = "unstable-msc4426")]
553            automatic_call_status: StdMutex::new(None),
554        };
555
556        #[allow(clippy::let_and_return)]
557        let client = Arc::new(client);
558
559        #[cfg(feature = "e2e-encryption")]
560        client.e2ee.initialize_tasks(&client);
561
562        let init_event_cache = OptionFuture::from(enable_event_cache.then(|| {
563            client.event_cache.get_or_init(|| async {
564                EventCache::new(
565                    &client,
566                    client.base_client.event_cache_store().clone(),
567                    enable_automatic_back_pagination,
568                )
569            })
570        }));
571
572        let init_thread_subscription_catchup = client
573            .thread_subscription_catchup
574            .get_or_init(|| ThreadSubscriptionCatchup::new(Client { inner: client.clone() }));
575
576        let _ = join!(init_event_cache, init_thread_subscription_catchup);
577
578        client
579    }
580}
581
582#[cfg(not(tarpaulin_include))]
583impl Debug for Client {
584    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
585        write!(fmt, "Client")
586    }
587}
588
589impl Client {
590    /// Create a new [`Client`] that will use the given homeserver.
591    ///
592    /// # Arguments
593    ///
594    /// * `homeserver_url` - The homeserver that the client should connect to.
595    pub async fn new(homeserver_url: Url) -> Result<Self, ClientBuildError> {
596        Self::builder().homeserver_url(homeserver_url).build().await
597    }
598
599    /// Activate the client.
600    ///
601    /// A client is considered active when:
602    ///
603    /// 1. It has a `SessionMeta` (user ID, device ID and access token),
604    /// 2. Has loaded cached data from storage,
605    /// 3. If encryption is enabled:
606    ///    - it initialized or restored its `OlmMachine`,
607    ///    - it initialized R2D2 (aka `event_cache::redecryptor::Redecryptor`).
608    ///
609    /// # Arguments
610    ///
611    /// - `session_meta` - The meta of a session that the user already has from
612    ///   a previous login call.
613    /// - `room_load_settings` — Specify how many rooms must be restored; use
614    ///   `::default()` if you don't know which value to pick.
615    #[cfg_attr(
616        feature = "e2e-encryption",
617        doc = " - `custom_account` - A custom
618  [`matrix_sdk_base::crypto::vodozemac::olm::Account`] to be used for the
619  identity and one-time keys of this [`BaseClient`]. If no account is
620  provided, a new default one or one from the store will be used. If an
621  account is provided and one already exists in the store for this
622  [`UserId`]/[`DeviceId`] combination, an error will be raised. This is
623  useful if one wishes to create identity keys before knowing the
624  user/device IDs, e.g., to use the identity key as the device ID."
625    )]
626    ///
627    /// # Panics
628    ///
629    /// This method panics if it is called twice.
630    ///
631    /// [`UserId`]: ruma::UserId
632    pub(crate) async fn activate(
633        &self,
634        session_meta: SessionMeta,
635        room_load_settings: RoomLoadSettings,
636        #[cfg(feature = "e2e-encryption")] custom_account: Option<olm::Account>,
637    ) -> Result<()> {
638        // First off, activate the base client.
639        self.inner
640            .base_client
641            .activate(
642                session_meta,
643                room_load_settings,
644                #[cfg(feature = "e2e-encryption")]
645                custom_account,
646            )
647            .await?;
648
649        // Next, activate R2D2 since the `OlmMachine` is now setup.
650        #[cfg(feature = "e2e-encryption")]
651        if let Some(event_cache) = self.event_cache() {
652            event_cache.initialise_redecryptor()?;
653        }
654
655        Ok(())
656    }
657
658    /// Create a [`WeakClient`], i.e. a weak reference to the [`Client`], for
659    /// use in background tasks.
660    ///
661    /// See doc comment of [`WeakClient`].
662    pub fn downgrade(&self) -> WeakClient {
663        WeakClient::from_inner(&self.inner)
664    }
665
666    /// Returns a subscriber that publishes an event every time the ignore user
667    /// list changes.
668    pub fn subscribe_to_ignore_user_list_changes(&self) -> Subscriber<Vec<OwnedUserId>> {
669        self.inner.base_client.subscribe_to_ignore_user_list_changes()
670    }
671
672    /// Create a new [`ClientBuilder`].
673    pub fn builder() -> ClientBuilder {
674        ClientBuilder::new()
675    }
676
677    pub(crate) fn base_client(&self) -> &BaseClient {
678        &self.inner.base_client
679    }
680
681    /// The [`HttpClient`] used by this client, with its [`RequestConfig`]
682    /// retry and concurrency limits.
683    ///
684    /// Use [`HttpClient::raw()`] to get the underlying [`reqwest::Client`].
685    pub fn http_client(&self) -> &HttpClient {
686        &self.inner.http_client
687    }
688
689    pub(crate) fn locks(&self) -> &ClientLocks {
690        &self.inner.locks
691    }
692
693    pub(crate) fn auth_ctx(&self) -> &AuthCtx {
694        &self.inner.auth_ctx
695    }
696
697    /// The cross-process store lock configuration used by this [`Client`].
698    ///
699    /// The SDK provides cross-process store locks (see
700    /// [`matrix_sdk_common::cross_process_lock::CrossProcessLock`]) when this
701    /// value is [`CrossProcessLockConfig::MultiProcess`]. Its holder name is
702    /// the value used for all cross-process store locks used by this `Client`.
703    pub fn cross_process_lock_config(&self) -> &CrossProcessLockConfig {
704        &self.inner.cross_process_lock_config
705    }
706
707    /// Change the homeserver URL used by this client.
708    ///
709    /// Note that this will reset [`Client::server`] to `None`.
710    ///
711    /// # Arguments
712    ///
713    /// * `homeserver_url` - The new URL to use.
714    fn set_homeserver(&self, homeserver_url: Url) {
715        let mut homeserver = self.inner.homeserver.write().unwrap();
716        let mut server = self.inner.server.write().unwrap();
717
718        *homeserver = homeserver_url;
719        *server = None;
720    }
721
722    /// Change to a different homeserver and re-resolve well-known.
723    #[cfg(feature = "e2e-encryption")]
724    pub(crate) async fn switch_homeserver_and_re_resolve_well_known(
725        &self,
726        homeserver_url: Url,
727    ) -> Result<()> {
728        self.set_homeserver(homeserver_url);
729        self.reset_well_known().await?;
730        if let Some(well_known) = self.well_known().await {
731            self.set_homeserver(Url::parse(&well_known.homeserver.base_url)?);
732        }
733        Ok(())
734    }
735
736    /// Retrieves a helper component to access the [`HomeserverCapabilities`]
737    /// supported or disabled by the homeserver.
738    pub fn homeserver_capabilities(&self) -> HomeserverCapabilities {
739        HomeserverCapabilities::new(self.clone())
740    }
741
742    /// Get the server vendor information from the federation API.
743    ///
744    /// This method calls the `/_matrix/federation/v1/version` endpoint to get
745    /// both the server's software name and version.
746    ///
747    /// # Examples
748    ///
749    /// ```no_run
750    /// # use matrix_sdk::Client;
751    /// # use url::Url;
752    /// # async {
753    /// # let homeserver = Url::parse("http://example.com")?;
754    /// let client = Client::new(homeserver).await?;
755    ///
756    /// let server_info = client.server_vendor_info(None).await?;
757    /// println!(
758    ///     "Server: {}, Version: {}",
759    ///     server_info.server_name, server_info.version
760    /// );
761    /// # anyhow::Ok(()) };
762    /// ```
763    #[cfg(feature = "federation-api")]
764    pub async fn server_vendor_info(
765        &self,
766        request_config: Option<RequestConfig>,
767    ) -> HttpResult<ServerVendorInfo> {
768        use ruma::api::federation::discovery::get_server_version;
769
770        let res = self
771            .send_inner(get_server_version::v1::Request::new(), request_config, Default::default())
772            .await?;
773
774        // Extract server info, using defaults if fields are missing.
775        let server = res.server.unwrap_or_default();
776        let server_name_str = server.name.unwrap_or_else(|| "unknown".to_owned());
777        let version = server.version.unwrap_or_else(|| "unknown".to_owned());
778
779        Ok(ServerVendorInfo { server_name: server_name_str, version })
780    }
781
782    /// Get a copy of the default request config.
783    ///
784    /// The default request config is what's used when sending requests if no
785    /// `RequestConfig` is explicitly passed to [`send`][Self::send] or another
786    /// function with such a parameter.
787    ///
788    /// If the default request config was not customized through
789    /// [`ClientBuilder`] when creating this `Client`, the returned value will
790    /// be equivalent to [`RequestConfig::default()`].
791    pub fn request_config(&self) -> RequestConfig {
792        self.inner.http_client.request_config
793    }
794
795    /// Check whether the client has been activated.
796    ///
797    /// A client is considered active when:
798    ///
799    /// 1. It has a `SessionMeta` (user ID, device ID and access token), i.e. it
800    ///    is logged in,
801    /// 2. Has loaded cached data from storage,
802    /// 3. If encryption is enabled, it also initialized or restored its
803    ///    `OlmMachine`, and R2D2 is enabled.
804    pub fn is_active(&self) -> bool {
805        self.inner.base_client.is_active()
806    }
807
808    /// The server used by the client.
809    ///
810    /// See `Self::server` to learn more.
811    pub fn server(&self) -> Option<Url> {
812        self.inner.server.read().unwrap().clone()
813    }
814
815    /// The homeserver of the client.
816    pub fn homeserver(&self) -> Url {
817        self.inner.homeserver.read().unwrap().clone()
818    }
819
820    /// Get the sliding sync version.
821    pub fn sliding_sync_version(&self) -> SlidingSyncVersion {
822        self.inner.sliding_sync_version.read().unwrap().clone()
823    }
824
825    /// Override the sliding sync version.
826    pub fn set_sliding_sync_version(&self, version: SlidingSyncVersion) {
827        let mut lock = self.inner.sliding_sync_version.write().unwrap();
828        *lock = version;
829    }
830
831    /// Get the default presence state used by generated sync requests.
832    pub(crate) fn sync_presence(&self) -> PresenceState {
833        self.inner.sync_presence.read().unwrap().clone()
834    }
835
836    /// Get the Matrix user session meta information.
837    ///
838    /// If the client is currently logged in, this will return a [`SessionMeta`]
839    /// object which contains the user ID and device ID. Otherwise it returns
840    /// `None`.
841    pub fn session_meta(&self) -> Option<&SessionMeta> {
842        self.base_client().session_meta()
843    }
844
845    /// Returns a receiver that gets events for each room info update. To watch
846    /// for new events, use `receiver.resubscribe()`.
847    pub fn room_info_notable_update_receiver(&self) -> broadcast::Receiver<RoomInfoNotableUpdate> {
848        self.base_client().room_info_notable_update_receiver()
849    }
850
851    /// Returns a receiver of the user IDs whose global profile changed during a
852    /// sync. Consumers can use this as a trigger to e.g. merge any global
853    /// fields into a user's room profile.
854    ///
855    /// Requires the Profiles sliding sync extension to be enabled.
856    pub fn subscribe_to_global_profile_updates(
857        &self,
858    ) -> broadcast::Receiver<BTreeSet<OwnedUserId>> {
859        self.base_client().subscribe_to_global_profile_updates()
860    }
861
862    /// Observe updates to the current user's global profile.
863    ///
864    /// Emits the current value immediately, then again whenever the user's
865    /// global profile changes during sync. When no profile is stored (nothing
866    /// received yet) an empty [`UserProfile`] is emitted.
867    ///
868    /// **Note:** Without the Profiles sliding sync extension enabled only an
869    /// empty profile will be emitted and no updates will be published.
870    ///
871    /// [`UserProfile`]: ruma::profile::UserProfile
872    pub fn subscribe_to_own_profile(
873        &self,
874    ) -> Result<impl Stream<Item = ruma::profile::UserProfile> + use<>> {
875        let own_user_id = self.user_id().ok_or(Error::AuthenticationRequired)?.to_owned();
876        let mut updates = self.subscribe_to_global_profile_updates();
877        let client = self.clone();
878
879        Ok(async_stream::stream! {
880            // Emit the initial value.
881            match client.state_store().get_global_profile(&own_user_id).await {
882                Ok(profile) => yield profile.unwrap_or_default(),
883                Err(error) => error!(?error, "Failed to load the stored global profile"),
884            }
885
886            while let Ok(updated_user_ids) = updates.recv().await {
887                if !updated_user_ids.contains(&own_user_id) {
888                    continue;
889                }
890
891                match client.state_store().get_global_profile(&own_user_id).await {
892                    Ok(profile) => yield profile.unwrap_or_default(),
893                    Err(error) => error!(?error, "Failed to load the updated global profile"),
894                }
895            }
896        })
897    }
898
899    /// Performs a search for users. The search is performed case-insensitively
900    /// on user IDs and display names
901    ///
902    /// # Arguments
903    ///
904    /// - `search_term` - The search term for the search
905    /// - `limit` - The maximum number of results to return. Defaults to 10.
906    ///
907    /// [user directory]: https://spec.matrix.org/v1.6/client-server-api/#user-directory
908    pub async fn search_users(
909        &self,
910        search_term: &str,
911        limit: u64,
912    ) -> HttpResult<search_users::v3::Response> {
913        let mut request = search_users::v3::Request::new(search_term.to_owned());
914
915        if let Some(limit) = UInt::new(limit) {
916            request.limit = limit;
917        }
918
919        self.send(request).await
920    }
921
922    /// Get the user id of the current owner of the client.
923    pub fn user_id(&self) -> Option<&UserId> {
924        self.session_meta().map(|s| s.user_id.as_ref())
925    }
926
927    /// Get the device ID that identifies the current session.
928    pub fn device_id(&self) -> Option<&DeviceId> {
929        self.session_meta().map(|s| s.device_id.as_ref())
930    }
931
932    /// Get the current access token for this session.
933    ///
934    /// Will be `None` if the client has not been logged in.
935    pub fn access_token(&self) -> Option<String> {
936        self.auth_ctx().access_token()
937    }
938
939    /// Set the presence state for the current user.
940    ///
941    /// The presence state is stored as the default used by future generated
942    /// sync requests, regardless of `immediate`. The initial default is
943    /// [`PresenceState::Online`]. If `immediate` is `true`, this also calls the
944    /// Matrix presence endpoint directly. `status_msg` is only sent when
945    /// `immediate` is `true`.
946    pub async fn set_presence(
947        &self,
948        presence: PresenceState,
949        status_msg: Option<String>,
950        immediate: bool,
951    ) -> Result<()> {
952        *self.inner.sync_presence.write().unwrap() = presence.clone();
953
954        if !immediate {
955            return Ok(());
956        }
957
958        let user_id = self.user_id().ok_or(Error::AuthenticationRequired)?.to_owned();
959        let mut request = set_presence_status::v3::Request::new(user_id, presence);
960        request.status_msg = status_msg;
961
962        self.send(request).await?;
963
964        Ok(())
965    }
966
967    /// Fetch the presence of a user from the homeserver.
968    pub async fn fetch_presence(&self, user_id: &UserId) -> Result<get_presence::v3::Response> {
969        let request = get_presence::v3::Request::new(user_id.to_owned());
970        Ok(self.send(request).await?)
971    }
972
973    /// Get the current tokens for this session.
974    ///
975    /// To be notified of changes in the session tokens, use
976    /// [`Client::subscribe_to_session_changes()`] or
977    /// [`Client::set_session_callbacks()`].
978    ///
979    /// Returns `None` if the client has not been logged in.
980    pub fn session_tokens(&self) -> Option<SessionTokens> {
981        self.auth_ctx().session_tokens()
982    }
983
984    /// Access the authentication API used to log in this client.
985    ///
986    /// Will be `None` if the client has not been logged in.
987    pub fn auth_api(&self) -> Option<AuthApi> {
988        match self.auth_ctx().auth_data.get()? {
989            AuthData::Matrix => Some(AuthApi::Matrix(self.matrix_auth())),
990            AuthData::OAuth(_) => Some(AuthApi::OAuth(self.oauth())),
991        }
992    }
993
994    /// Get the whole session info of this client.
995    ///
996    /// Will be `None` if the client has not been logged in.
997    ///
998    /// Can be used with [`Client::restore_session`] to restore a previously
999    /// logged-in session.
1000    pub fn session(&self) -> Option<AuthSession> {
1001        match self.auth_api()? {
1002            AuthApi::Matrix(api) => api.session().map(Into::into),
1003            AuthApi::OAuth(api) => api.full_session().map(Into::into),
1004        }
1005    }
1006
1007    /// Get a reference to the state store.
1008    pub fn state_store(&self) -> &DynStateStore {
1009        self.base_client().state_store()
1010    }
1011
1012    /// Get a reference to the event cache store.
1013    pub fn event_cache_store(&self) -> &EventCacheStoreLock {
1014        self.base_client().event_cache_store()
1015    }
1016
1017    /// Get a reference to the media store.
1018    pub fn media_store(&self) -> &MediaStoreLock {
1019        self.base_client().media_store()
1020    }
1021
1022    /// Access the native Matrix authentication API with this client.
1023    pub fn matrix_auth(&self) -> MatrixAuth {
1024        MatrixAuth::new(self.clone())
1025    }
1026
1027    /// Get the account of the current owner of the client.
1028    pub fn account(&self) -> Account {
1029        Account::new(self.clone())
1030    }
1031
1032    /// Get the encryption manager of the client.
1033    #[cfg(feature = "e2e-encryption")]
1034    pub fn encryption(&self) -> Encryption {
1035        Encryption::new(self.clone())
1036    }
1037
1038    /// Get the media manager of the client.
1039    pub fn media(&self) -> Media {
1040        Media::new(self.clone())
1041    }
1042
1043    /// Get the pusher manager of the client.
1044    pub fn pusher(&self) -> Pusher {
1045        Pusher::new(self.clone())
1046    }
1047
1048    /// Access the OAuth 2.0 API of the client.
1049    pub fn oauth(&self) -> OAuth {
1050        OAuth::new(self.clone())
1051    }
1052
1053    /// Register a handler for a specific event type.
1054    ///
1055    /// The handler is a function or closure with one or more arguments. The
1056    /// first argument is the event itself. All additional arguments are
1057    /// "context" arguments: They have to implement [`EventHandlerContext`].
1058    /// This trait is named that way because most of the types implementing it
1059    /// give additional context about an event: The room it was in, its raw form
1060    /// and other similar things. As two exceptions to this, [`Client`] and
1061    /// [`EventHandlerHandle`] also implement the `EventHandlerContext` trait so
1062    /// you don't have to clone your client into the event handler manually and
1063    /// a handler can decide to remove itself.
1064    ///
1065    /// Some context arguments are not universally applicable. A context
1066    /// argument that isn't available for the given event type will result in
1067    /// the event handler being skipped and an error being logged. The following
1068    /// context argument types are only available for a subset of event types:
1069    ///
1070    /// - [`Room`] is only available for room-specific events, i.e. not for
1071    ///   events like global account data events or presence events.
1072    ///
1073    /// You can provide custom context via
1074    /// [`add_event_handler_context`](Client::add_event_handler_context) and
1075    /// then use [`Ctx<T>`](crate::event_handler::Ctx) to extract the context
1076    /// into the event handler.
1077    ///
1078    /// [`EventHandlerContext`]: crate::event_handler::EventHandlerContext
1079    ///
1080    /// # Examples
1081    ///
1082    /// ```no_run
1083    /// use matrix_sdk::{
1084    ///     deserialized_responses::EncryptionInfo,
1085    ///     event_handler::Ctx,
1086    ///     ruma::{
1087    ///         events::{
1088    ///             macros::EventContent,
1089    ///             push_rules::PushRulesEvent,
1090    ///             room::{
1091    ///                 message::SyncRoomMessageEvent,
1092    ///                 topic::SyncRoomTopicEvent,
1093    ///                 member::{StrippedRoomMemberEvent, SyncRoomMemberEvent},
1094    ///             },
1095    ///         },
1096    ///         push::Action,
1097    ///         Int, MilliSecondsSinceUnixEpoch,
1098    ///     },
1099    ///     Client, Room,
1100    /// };
1101    /// use serde::{Deserialize, Serialize};
1102    ///
1103    /// # async fn example(client: Client) {
1104    /// client.add_event_handler(
1105    ///     |ev: SyncRoomMessageEvent, room: Room, client: Client| async move {
1106    ///         // Common usage: Room event plus room and client.
1107    ///     },
1108    /// );
1109    /// client.add_event_handler(
1110    ///     |ev: SyncRoomMessageEvent, room: Room, encryption_info: Option<EncryptionInfo>| {
1111    ///         async move {
1112    ///             // An `Option<EncryptionInfo>` parameter lets you distinguish between
1113    ///             // unencrypted events and events that were decrypted by the SDK.
1114    ///         }
1115    ///     },
1116    /// );
1117    /// client.add_event_handler(
1118    ///     |ev: SyncRoomMessageEvent, room: Room, push_actions: Vec<Action>| {
1119    ///         async move {
1120    ///             // A `Vec<Action>` parameter allows you to know which push actions
1121    ///             // are applicable for an event. For example, an event with
1122    ///             // `Action::SetTweak(Tweak::Highlight(HighlightTweakValue::Yes))`
1123    ///             // should be highlighted in the timeline.
1124    ///         }
1125    ///     },
1126    /// );
1127    /// client.add_event_handler(|ev: SyncRoomTopicEvent| async move {
1128    ///     // You can omit any or all arguments after the first.
1129    /// });
1130    ///
1131    /// // Registering a temporary event handler:
1132    /// let handle = client.add_event_handler(|ev: SyncRoomMessageEvent| async move {
1133    ///     /* Event handler */
1134    /// });
1135    /// client.remove_event_handler(handle);
1136    ///
1137    /// // Registering custom event handler context:
1138    /// #[derive(Debug, Clone)] // The context will be cloned for event handler.
1139    /// struct MyContext {
1140    ///     number: usize,
1141    /// }
1142    /// client.add_event_handler_context(MyContext { number: 5 });
1143    /// client.add_event_handler(|ev: SyncRoomMessageEvent, context: Ctx<MyContext>| async move {
1144    ///     // Use the context
1145    /// });
1146    ///
1147    /// // This will handle membership events in joined rooms. Invites are special, see below.
1148    /// client.add_event_handler(
1149    ///     |ev: SyncRoomMemberEvent| async move {},
1150    /// );
1151    ///
1152    /// // To handle state events in invited rooms (including invite membership events),
1153    /// // `StrippedRoomMemberEvent` should be used.
1154    /// // https://spec.matrix.org/v1.16/client-server-api/#stripped-state
1155    /// client.add_event_handler(
1156    ///     |ev: StrippedRoomMemberEvent| async move {},
1157    /// );
1158    ///
1159    /// // Custom events work exactly the same way, you just need to declare
1160    /// // the content struct and use the EventContent derive macro on it.
1161    /// #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
1162    /// #[ruma_event(type = "org.shiny_new_2fa.token", kind = MessageLike)]
1163    /// struct TokenEventContent {
1164    ///     token: String,
1165    ///     #[serde(rename = "exp")]
1166    ///     expires_at: MilliSecondsSinceUnixEpoch,
1167    /// }
1168    ///
1169    /// client.add_event_handler(async |ev: SyncTokenEvent, room: Room| -> () {
1170    ///     todo!("Display the token");
1171    /// });
1172    ///
1173    /// // Event handler closures can also capture local variables.
1174    /// // Make sure they are cheap to clone though, because they will be cloned
1175    /// // every time the closure is called.
1176    /// let data: std::sync::Arc<str> = "MyCustomIdentifier".into();
1177    ///
1178    /// client.add_event_handler(move |ev: SyncRoomMessageEvent | async move {
1179    ///     println!("Calling the handler with identifier {data}");
1180    /// });
1181    /// # }
1182    /// ```
1183    pub fn add_event_handler<Ev, Ctx, H>(&self, handler: H) -> EventHandlerHandle
1184    where
1185        Ev: SyncEvent + DeserializeOwned + SendOutsideWasm + 'static,
1186        H: EventHandler<Ev, Ctx>,
1187    {
1188        self.add_event_handler_impl(handler, None)
1189    }
1190
1191    /// Register a handler for a specific room, and event type.
1192    ///
1193    /// This method works the same way as
1194    /// [`add_event_handler`][Self::add_event_handler], except that the handler
1195    /// will only be called for events in the room with the specified ID. See
1196    /// that method for more details on event handler functions.
1197    ///
1198    /// `client.add_room_event_handler(room_id, hdl)` is equivalent to
1199    /// `room.add_event_handler(hdl)`. Use whichever one is more convenient in
1200    /// your use case.
1201    pub fn add_room_event_handler<Ev, Ctx, H>(
1202        &self,
1203        room_id: &RoomId,
1204        handler: H,
1205    ) -> EventHandlerHandle
1206    where
1207        Ev: SyncEvent + DeserializeOwned + SendOutsideWasm + 'static,
1208        H: EventHandler<Ev, Ctx>,
1209    {
1210        self.add_event_handler_impl(handler, Some(room_id.to_owned()))
1211    }
1212
1213    /// Observe a specific event type.
1214    ///
1215    /// `Ev` represents the kind of event that will be observed. `Ctx`
1216    /// represents the context that will come with the event. It relies on the
1217    /// same mechanism as [`Client::add_event_handler`]. The main difference is
1218    /// that it returns an [`ObservableEventHandler`] and doesn't require a
1219    /// user-defined closure. It is possible to subscribe to the
1220    /// [`ObservableEventHandler`] to get an [`EventHandlerSubscriber`], which
1221    /// implements a [`Stream`]. The `Stream::Item` will be of type `(Ev, Ctx)`.
1222    ///
1223    /// Be careful that only the most recent value can be observed. Subscribers
1224    /// are notified when a new value is sent, but there is no guarantee that
1225    /// they will see all values.
1226    ///
1227    /// # Example
1228    ///
1229    /// Let's see a classical usage:
1230    ///
1231    /// ```
1232    /// use futures_util::StreamExt as _;
1233    /// use matrix_sdk::{
1234    ///     Client, Room,
1235    ///     ruma::{events::room::message::SyncRoomMessageEvent, push::Action},
1236    /// };
1237    ///
1238    /// # async fn example(client: Client) -> Option<()> {
1239    /// let observer =
1240    ///     client.observe_events::<SyncRoomMessageEvent, (Room, Vec<Action>)>();
1241    ///
1242    /// let mut subscriber = observer.subscribe();
1243    ///
1244    /// let (event, (room, push_actions)) = subscriber.next().await?;
1245    /// # Some(())
1246    /// # }
1247    /// ```
1248    ///
1249    /// Now let's see how to get several contexts that can be useful for you:
1250    ///
1251    /// ```
1252    /// use matrix_sdk::{
1253    ///     Client, Room,
1254    ///     deserialized_responses::EncryptionInfo,
1255    ///     ruma::{
1256    ///         events::room::{
1257    ///             message::SyncRoomMessageEvent, topic::SyncRoomTopicEvent,
1258    ///         },
1259    ///         push::Action,
1260    ///     },
1261    /// };
1262    ///
1263    /// # async fn example(client: Client) {
1264    /// // Observe `SyncRoomMessageEvent` and fetch `Room` + `Client`.
1265    /// let _ = client.observe_events::<SyncRoomMessageEvent, (Room, Client)>();
1266    ///
1267    /// // Observe `SyncRoomMessageEvent` and fetch `Room` + `EncryptionInfo`
1268    /// // to distinguish between unencrypted events and events that were decrypted
1269    /// // by the SDK.
1270    /// let _ = client
1271    ///     .observe_events::<SyncRoomMessageEvent, (Room, Option<EncryptionInfo>)>(
1272    ///     );
1273    ///
1274    /// // Observe `SyncRoomMessageEvent` and fetch `Room` + push actions.
1275    /// // For example, an event with `Action::SetTweak(Tweak::Highlight(HighlightTweakValue::Yes))`
1276    /// // should be highlighted in the timeline.
1277    /// let _ =
1278    ///     client.observe_events::<SyncRoomMessageEvent, (Room, Vec<Action>)>();
1279    ///
1280    /// // Observe `SyncRoomTopicEvent` and fetch nothing else.
1281    /// let _ = client.observe_events::<SyncRoomTopicEvent, ()>();
1282    /// # }
1283    /// ```
1284    ///
1285    /// [`EventHandlerSubscriber`]: crate::event_handler::EventHandlerSubscriber
1286    pub fn observe_events<Ev, Ctx>(&self) -> ObservableEventHandler<(Ev, Ctx)>
1287    where
1288        Ev: SyncEvent + DeserializeOwned + SendOutsideWasm + SyncOutsideWasm + 'static,
1289        Ctx: EventHandlerContext + SendOutsideWasm + SyncOutsideWasm + 'static,
1290    {
1291        self.observe_room_events_impl(None)
1292    }
1293
1294    /// Observe a specific room, and event type.
1295    ///
1296    /// This method works the same way as [`Client::observe_events`], except
1297    /// that the observability will only be applied for events in the room with
1298    /// the specified ID. See that method for more details.
1299    ///
1300    /// Be careful that only the most recent value can be observed. Subscribers
1301    /// are notified when a new value is sent, but there is no guarantee that
1302    /// they will see all values.
1303    pub fn observe_room_events<Ev, Ctx>(
1304        &self,
1305        room_id: &RoomId,
1306    ) -> ObservableEventHandler<(Ev, Ctx)>
1307    where
1308        Ev: SyncEvent + DeserializeOwned + SendOutsideWasm + SyncOutsideWasm + 'static,
1309        Ctx: EventHandlerContext + SendOutsideWasm + SyncOutsideWasm + 'static,
1310    {
1311        self.observe_room_events_impl(Some(room_id.to_owned()))
1312    }
1313
1314    /// Shared implementation for `Client::observe_events` and
1315    /// `Client::observe_room_events`.
1316    fn observe_room_events_impl<Ev, Ctx>(
1317        &self,
1318        room_id: Option<OwnedRoomId>,
1319    ) -> ObservableEventHandler<(Ev, Ctx)>
1320    where
1321        Ev: SyncEvent + DeserializeOwned + SendOutsideWasm + SyncOutsideWasm + 'static,
1322        Ctx: EventHandlerContext + SendOutsideWasm + SyncOutsideWasm + 'static,
1323    {
1324        // The default value is `None`. It becomes `Some((Ev, Ctx))` once it has
1325        // a new value.
1326        let shared_observable = SharedObservable::new(None);
1327
1328        ObservableEventHandler::new(
1329            shared_observable.clone(),
1330            self.event_handler_drop_guard(self.add_event_handler_impl(
1331                move |event: Ev, context: Ctx| {
1332                    shared_observable.set(Some((event, context)));
1333
1334                    ready(())
1335                },
1336                room_id,
1337            )),
1338        )
1339    }
1340
1341    /// Subscribe to future `beacon_info` updates for the current user across
1342    /// all rooms.
1343    ///
1344    /// This stream is push-only: it emits only updates observed during sync
1345    /// processing. Only the room's current own `beacon_info` is emitted, older
1346    /// ones replayed in a sync timeline are skipped. The current one may be
1347    /// emitted again if sync sends it again, e.g. on a new connection.
1348    pub fn observe_own_beacon_info_updates(
1349        &self,
1350    ) -> Result<impl Stream<Item = BeaconInfoUpdate> + use<>> {
1351        let observer = self.observe_events::<OriginalSyncBeaconInfoEvent, Room>();
1352        let mut stream = observer.subscribe();
1353        let own_user_id = self.user_id().ok_or(Error::AuthenticationRequired)?.to_owned();
1354        Ok(async_stream::stream! {
1355            let _observer = observer;
1356
1357            while let Some((event, room)) = stream.next().await {
1358                if event.state_key != own_user_id {
1359                    continue;
1360                }
1361                // Sync stores the room state before calling event handlers, so
1362                // anything that isn't the stored one is an older replay.
1363                let is_current = room
1364                    .get_user_beacon_info(&own_user_id)
1365                    .await
1366                    .is_ok_and(|current| current.event_id == event.event_id);
1367                if !is_current {
1368                    continue;
1369                }
1370                yield BeaconInfoUpdate {
1371                    room_id: room.room_id().to_owned(),
1372                    event_id: event.event_id,
1373                    content: event.content,
1374                };
1375            }
1376        })
1377    }
1378
1379    /// Remove the event handler associated with the handle.
1380    ///
1381    /// Note that you **must not** call `remove_event_handler` from the
1382    /// non-async part of an event handler, that is:
1383    ///
1384    /// ```ignore
1385    /// client.add_event_handler(|ev: SomeEvent, client: Client, handle: EventHandlerHandle| {
1386    ///     // ⚠ this will cause a deadlock ⚠
1387    ///     client.remove_event_handler(handle);
1388    ///
1389    ///     async move {
1390    ///         // removing the event handler here is fine
1391    ///         client.remove_event_handler(handle);
1392    ///     }
1393    /// })
1394    /// ```
1395    ///
1396    /// Note also that handlers that remove themselves will still execute with
1397    /// events received in the same sync cycle.
1398    ///
1399    /// # Arguments
1400    ///
1401    /// `handle` - The [`EventHandlerHandle`] that is returned when registering
1402    /// the event handler with [`Client::add_event_handler`].
1403    ///
1404    /// # Examples
1405    ///
1406    /// ```no_run
1407    /// # use url::Url;
1408    /// # use tokio::sync::mpsc;
1409    /// #
1410    /// # let homeserver = Url::parse("http://localhost:8080").unwrap();
1411    /// #
1412    /// use matrix_sdk::{
1413    ///     Client, event_handler::EventHandlerHandle,
1414    ///     ruma::events::room::member::SyncRoomMemberEvent,
1415    /// };
1416    /// #
1417    /// # futures_executor::block_on(async {
1418    /// # let client = matrix_sdk::Client::builder()
1419    /// #     .homeserver_url(homeserver)
1420    /// #     .server_versions([ruma::api::MatrixVersion::V1_0])
1421    /// #     .build()
1422    /// #     .await
1423    /// #     .unwrap();
1424    ///
1425    /// client.add_event_handler(
1426    ///     |ev: SyncRoomMemberEvent,
1427    ///      client: Client,
1428    ///      handle: EventHandlerHandle| async move {
1429    ///         // Common usage: Check arriving Event is the expected one
1430    ///         println!("Expected RoomMemberEvent received!");
1431    ///         client.remove_event_handler(handle);
1432    ///     },
1433    /// );
1434    /// # });
1435    /// ```
1436    pub fn remove_event_handler(&self, handle: EventHandlerHandle) {
1437        self.inner.event_handlers.remove(handle);
1438    }
1439
1440    /// Create an [`EventHandlerDropGuard`] for the event handler identified by
1441    /// the given handle.
1442    ///
1443    /// When the returned value is dropped, the event handler will be removed.
1444    pub fn event_handler_drop_guard(&self, handle: EventHandlerHandle) -> EventHandlerDropGuard {
1445        EventHandlerDropGuard::new(handle, self.clone())
1446    }
1447
1448    /// Add an arbitrary value for use as event handler context.
1449    ///
1450    /// The value can be obtained in an event handler by adding an argument of
1451    /// the type [`Ctx<T>`][crate::event_handler::Ctx].
1452    ///
1453    /// If a value of the same type has been added before, it will be
1454    /// overwritten.
1455    ///
1456    /// # Examples
1457    ///
1458    /// ```no_run
1459    /// use matrix_sdk::{
1460    ///     Room, event_handler::Ctx,
1461    ///     ruma::events::room::message::SyncRoomMessageEvent,
1462    /// };
1463    /// # #[derive(Clone)]
1464    /// # struct SomeType;
1465    /// # fn obtain_gui_handle() -> SomeType { SomeType }
1466    /// # let homeserver = url::Url::parse("http://localhost:8080").unwrap();
1467    /// # futures_executor::block_on(async {
1468    /// # let client = matrix_sdk::Client::builder()
1469    /// #     .homeserver_url(homeserver)
1470    /// #     .server_versions([ruma::api::MatrixVersion::V1_0])
1471    /// #     .build()
1472    /// #     .await
1473    /// #     .unwrap();
1474    ///
1475    /// // Handle used to send messages to the UI part of the app
1476    /// let my_gui_handle: SomeType = obtain_gui_handle();
1477    ///
1478    /// client.add_event_handler_context(my_gui_handle.clone());
1479    /// client.add_event_handler(
1480    ///     |ev: SyncRoomMessageEvent, room: Room, gui_handle: Ctx<SomeType>| {
1481    ///         async move {
1482    ///             // gui_handle.send(DisplayMessage { message: ev });
1483    ///         }
1484    ///     },
1485    /// );
1486    /// # });
1487    /// ```
1488    pub fn add_event_handler_context<T>(&self, ctx: T)
1489    where
1490        T: Clone + Send + Sync + 'static,
1491    {
1492        self.inner.event_handlers.add_context(ctx);
1493    }
1494
1495    /// Register a handler for a notification.
1496    ///
1497    /// Similar to [`Client::add_event_handler`], but only allows functions or
1498    /// closures with exactly the three arguments [`Notification`], [`Room`],
1499    /// [`Client`] for now.
1500    pub async fn register_notification_handler<H, Fut>(&self, handler: H) -> &Self
1501    where
1502        H: Fn(Notification, Room, Client) -> Fut + SendOutsideWasm + SyncOutsideWasm + 'static,
1503        Fut: Future<Output = ()> + SendOutsideWasm + 'static,
1504    {
1505        self.inner.notification_handlers.write().await.push(Box::new(
1506            move |notification, room, client| Box::pin((handler)(notification, room, client)),
1507        ));
1508
1509        self
1510    }
1511
1512    /// Subscribe to all updates for the room with the given ID.
1513    ///
1514    /// The returned receiver will receive a new message for each sync response
1515    /// that contains updates for that room.
1516    pub fn subscribe_to_room_updates(&self, room_id: &RoomId) -> broadcast::Receiver<RoomUpdate> {
1517        match self.inner.room_update_channels.lock().unwrap().entry(room_id.to_owned()) {
1518            btree_map::Entry::Vacant(entry) => {
1519                let (tx, rx) = broadcast::channel(8);
1520                entry.insert(tx);
1521                rx
1522            }
1523            btree_map::Entry::Occupied(entry) => entry.get().subscribe(),
1524        }
1525    }
1526
1527    /// Subscribe to all updates to all rooms, whenever any has been received in
1528    /// a sync response.
1529    pub fn subscribe_to_all_room_updates(&self) -> broadcast::Receiver<RoomUpdates> {
1530        self.inner.room_updates_sender.subscribe()
1531    }
1532
1533    /// Subscribe to the custom to-device messages received by this client.
1534    ///
1535    /// The returned stream yields every to-device message whose type is one of
1536    /// `event_types`, or every custom to-device message if `event_types` is
1537    /// empty, as they are received. A message that was sent encrypted is
1538    /// yielded decrypted, along with its [`EncryptionInfo`].
1539    ///
1540    /// The to-device traffic the SDK uses for its own crypto machinery (room
1541    /// keys, verification, secret sharing, ...) and the messages it could not
1542    /// decrypt are never yielded, whatever `event_types` says.
1543    ///
1544    /// Forwarding stops once the returned stream is dropped.
1545    ///
1546    /// # Examples
1547    ///
1548    /// ```no_run
1549    /// # async {
1550    /// # let client: matrix_sdk::Client = unimplemented!();
1551    /// use std::pin::pin;
1552    ///
1553    /// use futures_util::StreamExt;
1554    /// use matrix_sdk::ruma::events::ToDeviceEventType;
1555    ///
1556    /// let messages = client.subscribe_to_custom_to_device_messages(vec![
1557    ///     ToDeviceEventType::from("io.element.call.encryption_keys"),
1558    /// ]);
1559    /// let mut messages = pin!(messages);
1560    ///
1561    /// while let Some(message) = messages.next().await {
1562    ///     let Some(encryption_info) = &message.encryption_info else {
1563    ///         // The message was not encrypted, don't trust it.
1564    ///         continue;
1565    ///     };
1566    ///     println!("{} sent {}", encryption_info.sender, message.raw.json());
1567    /// }
1568    /// # };
1569    /// ```
1570    pub fn subscribe_to_custom_to_device_messages(
1571        &self,
1572        event_types: Vec<ToDeviceEventType>,
1573    ) -> impl Stream<Item = ToDeviceMessage> + use<> {
1574        let (sender, mut receiver) = unbounded_channel();
1575
1576        // Event handlers can only filter by type for statically-known event
1577        // content types, so a runtime list of types has to be filtered here
1578        // instead.
1579        let handle = self.add_event_handler(
1580            move |raw: Raw<AnyToDeviceEvent>, encryption_info: Option<EncryptionInfo>| {
1581                let Ok(Some(event_type)) = raw.get_field::<ToDeviceEventType>("type") else {
1582                    trace!("Ignoring a to-device message without a type");
1583                    return ready(());
1584                };
1585
1586                if is_internal_to_device_type(&event_type) {
1587                    trace!(%event_type, "Not forwarding an internal to-device message");
1588                } else if event_types.is_empty() || event_types.contains(&event_type) {
1589                    // Ignore the result: it can only fail if the stream was
1590                    // dropped.
1591                    let _ = sender.send(ToDeviceMessage { raw, encryption_info });
1592                }
1593
1594                ready(())
1595            },
1596        );
1597
1598        let drop_guard = self.event_handler_drop_guard(handle);
1599
1600        stream! {
1601            // Deregisters the event handler when the stream is dropped.
1602            let _drop_guard = drop_guard;
1603
1604            while let Some(message) = receiver.recv().await {
1605                yield message;
1606            }
1607        }
1608    }
1609
1610    pub(crate) async fn notification_handlers(
1611        &self,
1612    ) -> RwLockReadGuard<'_, Vec<NotificationHandlerFn>> {
1613        self.inner.notification_handlers.read().await
1614    }
1615
1616    /// Get all the rooms the client knows about.
1617    ///
1618    /// This will return the list of joined, invited, and left rooms.
1619    pub fn rooms(&self) -> Vec<Room> {
1620        self.base_client().rooms().into_iter().map(|room| Room::new(self.clone(), room)).collect()
1621    }
1622
1623    /// Get all the rooms the client knows about, filtered by room state.
1624    pub fn rooms_filtered(&self, filter: RoomStateFilter) -> Vec<Room> {
1625        self.base_client()
1626            .rooms_filtered(filter)
1627            .into_iter()
1628            .map(|room| Room::new(self.clone(), room))
1629            .collect()
1630    }
1631
1632    /// Get a stream of all the rooms, in addition to the existing rooms.
1633    pub fn rooms_stream(&self) -> (Vector<Room>, impl Stream<Item = Vec<VectorDiff<Room>>> + '_) {
1634        let (rooms, stream) = self.base_client().rooms_stream();
1635
1636        let map_room = |room| Room::new(self.clone(), room);
1637
1638        (
1639            rooms.into_iter().map(map_room).collect(),
1640            stream.map(move |diffs| diffs.into_iter().map(|diff| diff.map(map_room)).collect()),
1641        )
1642    }
1643
1644    /// Returns the joined rooms this client knows about.
1645    pub fn joined_rooms(&self) -> Vec<Room> {
1646        self.rooms_filtered(RoomStateFilter::JOINED)
1647    }
1648
1649    /// Returns the invited rooms this client knows about.
1650    pub fn invited_rooms(&self) -> Vec<Room> {
1651        self.rooms_filtered(RoomStateFilter::INVITED)
1652    }
1653
1654    /// Returns the left rooms this client knows about.
1655    pub fn left_rooms(&self) -> Vec<Room> {
1656        self.rooms_filtered(RoomStateFilter::LEFT)
1657    }
1658
1659    /// Returns the joined space rooms this client knows about.
1660    pub fn joined_space_rooms(&self) -> Vec<Room> {
1661        self.base_client()
1662            .rooms_filtered(RoomStateFilter::JOINED)
1663            .into_iter()
1664            .flat_map(|room| room.is_space().then_some(Room::new(self.clone(), room)))
1665            .collect()
1666    }
1667
1668    /// The total number of client-side computed unread notifications across all
1669    /// joined rooms. Rooms the user marked as unread by hand count as one each.
1670    ///
1671    /// Spaces and rooms that aren't the active version (their successor is
1672    /// joined, left or banned) are skipped, as room lists hide them and the
1673    /// user couldn't clear their notifications.
1674    pub fn total_unread_notifications(&self) -> u64 {
1675        self.base_client()
1676            .rooms_filtered(RoomStateFilter::JOINED)
1677            .iter()
1678            .map(|room| (room, room.num_unread_notifications().max(room.is_marked_unread().into())))
1679            // Check whether the room is hidden only for the few rooms that count.
1680            .filter(|(_, count)| *count > 0)
1681            .filter(|(room, _)| !room.is_space())
1682            .filter(|(room, _)| {
1683                !room
1684                    .successor_room()
1685                    .and_then(|successor| self.base_client().get_room(&successor.room_id))
1686                    .is_some_and(|successor| {
1687                        matches!(
1688                            successor.state(),
1689                            RoomState::Joined | RoomState::Left | RoomState::Banned
1690                        )
1691                    })
1692            })
1693            .map(|(_, count)| count)
1694            .sum()
1695    }
1696
1697    /// Returns a [`Stream`] containing the total unread notification count
1698    /// updates, which will be computed at most once every `min_interval` when
1699    /// new [`RoomInfoNotableUpdate`] items are received, to avoid computing
1700    /// this value dozens or hundreds of times in a short amount of time.
1701    pub fn observe_total_unread_notifications(
1702        &self,
1703        min_interval: Duration,
1704    ) -> impl Stream<Item = u64> + use<> {
1705        let mut update_receiver = self.room_info_notable_update_receiver();
1706        let this = self.clone();
1707
1708        stream! {
1709            // Initial value.
1710            let mut current = this.total_unread_notifications();
1711
1712            // Yield the current total.
1713            yield current;
1714
1715            // TODO ideally we'd filter `RoomInfoNotableUpdateReasons` here, but several
1716            //  reasons can cause the unread notifications to change and it's not always
1717            //  clear when this can happen. So let's not filter them *yet*.
1718            loop {
1719                // Drain all updates.
1720                while update_receiver.try_recv().is_ok() {}
1721
1722                // Wait `min_interval`.
1723                sleep(min_interval).await;
1724
1725                // Wait for an update.
1726                // Either it arrived while sleeping (the `Recv` future will resolve immediately),
1727                // or it will arrive in the future.
1728                if update_receiver.recv().await.is_err() {
1729                    break;
1730                }
1731
1732                // When we got an update, re-compute the total.
1733                let next = this.total_unread_notifications();
1734
1735                if next != current {
1736                    current = next;
1737
1738                    // Yield the current total.
1739                    yield current;
1740                }
1741            }
1742        }
1743    }
1744    /// Get a room with the given room id.
1745    ///
1746    /// # Arguments
1747    ///
1748    /// `room_id` - The unique id of the room that should be fetched.
1749    pub fn get_room(&self, room_id: &RoomId) -> Option<Room> {
1750        self.base_client().get_room(room_id).map(|room| Room::new(self.clone(), room))
1751    }
1752
1753    /// Gets the preview of a room, whether the current user has joined it or
1754    /// not.
1755    pub async fn get_room_preview(
1756        &self,
1757        room_or_alias_id: &RoomOrAliasId,
1758        via: Vec<OwnedServerName>,
1759    ) -> Result<RoomPreview> {
1760        let room_id = match <&RoomId>::try_from(room_or_alias_id) {
1761            Ok(room_id) => room_id.to_owned(),
1762            Err(alias) => self.resolve_room_alias(alias).await?.room_id,
1763        };
1764
1765        if let Some(room) = self.get_room(&room_id) {
1766            // The cached data can only be trusted if the room state is joined
1767            // or banned: for invite and knock rooms, no updates will be
1768            // received for the rooms after the invite/knock action took place
1769            // so we may have very out to date data for important fields such as
1770            // `join_rule`. For left rooms, the homeserver should return the
1771            // latest info.
1772            match room.state() {
1773                RoomState::Joined | RoomState::Banned => {
1774                    return Ok(RoomPreview::from_known_room(&room).await);
1775                }
1776                RoomState::Left | RoomState::Invited | RoomState::Knocked => {}
1777            }
1778        }
1779
1780        RoomPreview::from_remote_room(self, room_id, room_or_alias_id, via).await
1781    }
1782
1783    /// Resolve a room alias to a room id and a list of servers which know about
1784    /// it.
1785    ///
1786    /// # Arguments
1787    ///
1788    /// `room_alias` - The room alias to be resolved.
1789    pub async fn resolve_room_alias(
1790        &self,
1791        room_alias: &RoomAliasId,
1792    ) -> HttpResult<get_alias::v3::Response> {
1793        let request = get_alias::v3::Request::new(room_alias.to_owned());
1794        self.send(request).await
1795    }
1796
1797    /// Checks if a room alias is not in use yet.
1798    ///
1799    /// Returns:
1800    ///
1801    /// - `Ok(true)` if the room alias is available.
1802    /// - `Ok(false)` if it's not (the resolve alias request returned a `404`
1803    ///   status code).
1804    /// - An `Err` otherwise.
1805    pub async fn is_room_alias_available(&self, alias: &RoomAliasId) -> HttpResult<bool> {
1806        match self.resolve_room_alias(alias).await {
1807            // The room alias was resolved, so it's already in use.
1808            Ok(_) => Ok(false),
1809            Err(error) => {
1810                match error.client_api_error_kind() {
1811                    // The room alias wasn't found, so it's available.
1812                    Some(ErrorKind::NotFound) => Ok(true),
1813                    _ => Err(error),
1814                }
1815            }
1816        }
1817    }
1818
1819    /// Adds a new room alias associated with a room to the room directory.
1820    pub async fn create_room_alias(&self, alias: &RoomAliasId, room_id: &RoomId) -> HttpResult<()> {
1821        let request = create_alias::v3::Request::new(alias.to_owned(), room_id.to_owned());
1822        self.send(request).await?;
1823        Ok(())
1824    }
1825
1826    /// Removes a room alias from the room directory.
1827    pub async fn remove_room_alias(&self, alias: &RoomAliasId) -> HttpResult<()> {
1828        let request = delete_alias::v3::Request::new(alias.to_owned());
1829        self.send(request).await?;
1830        Ok(())
1831    }
1832
1833    /// Update the homeserver from the login response well-known if needed.
1834    ///
1835    /// # Arguments
1836    ///
1837    /// - `login_well_known` - The `well_known` field from a successful login
1838    ///   response.
1839    pub(crate) fn maybe_update_login_well_known(&self, login_well_known: Option<&DiscoveryInfo>) {
1840        if self.inner.respect_login_well_known
1841            && let Some(well_known) = login_well_known
1842            && let Ok(homeserver) = Url::parse(&well_known.homeserver.base_url)
1843        {
1844            self.set_homeserver(homeserver);
1845        }
1846    }
1847
1848    /// Similar to [`Client::restore_session_with`], with
1849    /// [`RoomLoadSettings::default()`].
1850    ///
1851    /// # Panics
1852    ///
1853    /// Panics if a session was already restored or logged in.
1854    #[instrument(skip_all)]
1855    pub async fn restore_session(&self, session: impl Into<AuthSession>) -> Result<()> {
1856        self.restore_session_with(session, RoomLoadSettings::default()).await
1857    }
1858
1859    /// Restore a session previously logged-in using one of the available
1860    /// authentication APIs. The number of rooms to restore is controlled by
1861    /// [`RoomLoadSettings`].
1862    ///
1863    /// See the documentation of the corresponding authentication API's
1864    /// `restore_session` method for more information.
1865    ///
1866    /// # Persisting the store
1867    ///
1868    /// Restoring a session only reattaches the [`Client`] to its stored state;
1869    /// it does not recreate that state. If the [`ClientBuilder`] was configured
1870    /// with a persistent store (for example via
1871    /// [`ClientBuilder::sqlite_store()`]), the same store must be configured
1872    /// when the session is restored, otherwise the encryption keys and room
1873    /// state will not be available. In particular, when the `e2e-encryption`
1874    /// feature is enabled, restoring on top of an in-memory store will leave
1875    /// the client unable to send or receive encrypted messages, since the Olm
1876    /// and outbound group session state cannot be recovered.
1877    ///
1878    /// See the [`persist_session`] example for an end-to-end sample of how to
1879    /// persist a session and its store across runs.
1880    ///
1881    /// [`ClientBuilder`]: crate::ClientBuilder
1882    /// [`ClientBuilder::sqlite_store()`]: crate::ClientBuilder::sqlite_store
1883    /// [`persist_session`]: https://github.com/matrix-org/matrix-rust-sdk/tree/main/examples/persist_session
1884    ///
1885    /// # Panics
1886    ///
1887    /// Panics if a session was already restored or logged in.
1888    #[instrument(skip_all)]
1889    pub async fn restore_session_with(
1890        &self,
1891        session: impl Into<AuthSession>,
1892        room_load_settings: RoomLoadSettings,
1893    ) -> Result<()> {
1894        let session = session.into();
1895        match session {
1896            AuthSession::Matrix(session) => {
1897                Box::pin(self.matrix_auth().restore_session(session, room_load_settings)).await
1898            }
1899            AuthSession::OAuth(session) => {
1900                Box::pin(self.oauth().restore_session(*session, room_load_settings)).await
1901            }
1902        }
1903    }
1904
1905    /// Refresh the access token using the authentication API used to log into
1906    /// this session.
1907    ///
1908    /// See the documentation of the authentication API's `refresh_access_token`
1909    /// method for more information.
1910    pub async fn refresh_access_token(&self) -> Result<(), RefreshTokenError> {
1911        let Some(auth_api) = self.auth_api() else {
1912            return Err(RefreshTokenError::RefreshTokenRequired);
1913        };
1914
1915        match auth_api {
1916            AuthApi::Matrix(api) => {
1917                trace!("Token refresh: Using the homeserver.");
1918                Box::pin(api.refresh_access_token()).await?;
1919            }
1920            AuthApi::OAuth(api) => {
1921                trace!("Token refresh: Using OAuth 2.0.");
1922                Box::pin(api.refresh_access_token()).await?;
1923            }
1924        }
1925
1926        Ok(())
1927    }
1928
1929    /// Log out the current session using the proper authentication API.
1930    ///
1931    /// Once the session is logged out, the background work of the
1932    /// [`EventCache`] (automatic back-paginations, redecryption of UTDs, search
1933    /// indexing…) is stopped, since it can't make any request anymore.
1934    ///
1935    /// # Errors
1936    ///
1937    /// Returns an error if the session is not authenticated or if an error
1938    /// occurred while making the request to the server.
1939    pub async fn logout(&self) -> Result<(), Error> {
1940        let auth_api = self.auth_api().ok_or(Error::AuthenticationRequired)?;
1941        match auth_api {
1942            AuthApi::Matrix(matrix_auth) => {
1943                matrix_auth.logout().await?;
1944            }
1945            AuthApi::OAuth(oauth) => oauth.logout().await?,
1946        }
1947
1948        if let Some(event_cache) = self.event_cache() {
1949            event_cache.shut_down();
1950        }
1951
1952        Ok(())
1953    }
1954
1955    /// Get or upload a sync filter.
1956    ///
1957    /// This method will either get a filter ID from the store or upload the
1958    /// filter definition to the homeserver and return the new filter ID.
1959    ///
1960    /// # Arguments
1961    ///
1962    /// - `filter_name` - The unique name of the filter, this name will be used
1963    /// locally to store and identify the filter ID returned by the server.
1964    /// - `definition` - The filter definition that should be uploaded to the
1965    /// server if no filter ID can be found in the store.
1966    ///
1967    /// # Examples
1968    ///
1969    /// ```no_run
1970    /// # use matrix_sdk::{
1971    /// #    Client, config::SyncSettings,
1972    /// #    ruma::api::client::{
1973    /// #        filter::{
1974    /// #           FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter,
1975    /// #        },
1976    /// #        sync::sync_events::v3::Filter,
1977    /// #    }
1978    /// # };
1979    /// # use url::Url;
1980    /// # async {
1981    /// # let homeserver = Url::parse("http://example.com").unwrap();
1982    /// # let client = Client::new(homeserver).await.unwrap();
1983    /// let mut filter = FilterDefinition::default();
1984    ///
1985    /// // Let's enable member lazy loading.
1986    /// filter.room.state.lazy_load_options =
1987    ///     LazyLoadOptions::Enabled { include_redundant_members: false };
1988    ///
1989    /// let filter_id = client
1990    ///     .get_or_upload_filter("sync", filter)
1991    ///     .await
1992    ///     .unwrap();
1993    ///
1994    /// let sync_settings = SyncSettings::new()
1995    ///     .filter(Filter::FilterId(filter_id));
1996    ///
1997    /// let response = client.sync_once(sync_settings).await.unwrap();
1998    /// # };
1999    /// ```
2000    #[instrument(skip(self, definition))]
2001    pub async fn get_or_upload_filter(
2002        &self,
2003        filter_name: &str,
2004        definition: FilterDefinition,
2005    ) -> Result<String> {
2006        if let Some(filter) = self.inner.base_client.get_filter(filter_name).await? {
2007            debug!("Found filter locally");
2008            Ok(filter)
2009        } else {
2010            debug!("Didn't find filter locally");
2011            let user_id = self.user_id().ok_or(Error::AuthenticationRequired)?;
2012            let request = FilterUploadRequest::new(user_id.to_owned(), definition);
2013            let response = self.send(request).await?;
2014
2015            self.inner.base_client.receive_filter_upload(filter_name, &response).await?;
2016
2017            Ok(response.filter_id)
2018        }
2019    }
2020
2021    /// Prepare to join a room by ID, by getting the current details about it
2022    async fn prepare_join_room_by_id(&self, room_id: &RoomId) -> Option<PreJoinRoomInfo> {
2023        let room = self.get_room(room_id)?;
2024
2025        let inviter = match room.invite_details().await {
2026            Ok(details) => details.inviter,
2027            Err(Error::WrongRoomState(_)) => None,
2028            Err(e) => {
2029                warn!("Error fetching invite details for room: {e:?}");
2030                None
2031            }
2032        };
2033
2034        Some(PreJoinRoomInfo { inviter })
2035    }
2036
2037    /// Finish joining a room.
2038    ///
2039    /// If the room was an invite that should be marked as a DM, will include it
2040    /// in the DM event after creating the joined room.
2041    ///
2042    /// If encrypted history sharing is enabled, will check to see if we have a
2043    /// key bundle, and import it if so.
2044    ///
2045    /// # Arguments
2046    ///
2047    /// - `room_id` - The `RoomId` of the room that was joined.
2048    /// - `pre_join_room_info` - Information about the room before we joined.
2049    async fn finish_join_room(
2050        &self,
2051        room_id: &RoomId,
2052        pre_join_room_info: Option<PreJoinRoomInfo>,
2053    ) -> Result<Room> {
2054        info!(?room_id, ?pre_join_room_info, "Completing room join");
2055        let mark_as_dm = if let Some(room) = self.get_room(room_id) {
2056            room.state() == RoomState::Invited
2057                && room.is_direct().await.unwrap_or_else(|e| {
2058                    warn!(%room_id, "is_direct() failed: {e}");
2059                    false
2060                })
2061        } else {
2062            false
2063        };
2064
2065        let base_room = self
2066            .base_client()
2067            .room_joined(
2068                room_id,
2069                pre_join_room_info
2070                    .as_ref()
2071                    .and_then(|info| info.inviter.as_ref())
2072                    .map(|i| i.user_id().to_owned()),
2073            )
2074            .await?;
2075        let room = Room::new(self.clone(), base_room);
2076
2077        if mark_as_dm {
2078            room.set_is_direct(true).await?;
2079        }
2080
2081        // If we joined following an invite, check if we had previously received
2082        // a key bundle from the inviter, and import it if so.
2083        //
2084        // It's important that we only do this once `BaseClient::room_joined`
2085        // has completed: see the notes on `BundleReceiverTask::handle_bundle`
2086        // on avoiding a race.
2087        #[cfg(feature = "e2e-encryption")]
2088        if self.inner.enable_share_history_on_invite
2089            && let Some(inviter) =
2090                pre_join_room_info.as_ref().and_then(|info| info.inviter.as_ref())
2091        {
2092            crate::room::shared_room_history::maybe_accept_key_bundle(&room, inviter.user_id())
2093                .await?;
2094        }
2095
2096        // Suppress "unused variable" and "unused field" lints
2097        #[cfg(not(feature = "e2e-encryption"))]
2098        let _ = pre_join_room_info.map(|i| i.inviter);
2099
2100        Ok(room)
2101    }
2102
2103    /// Join a room by `RoomId`.
2104    ///
2105    /// Returns the `Room` in the joined state.
2106    ///
2107    /// # Arguments
2108    ///
2109    /// * `room_id` - The `RoomId` of the room to be joined.
2110    #[instrument(skip(self))]
2111    pub async fn join_room_by_id(&self, room_id: &RoomId) -> Result<Room> {
2112        // See who invited us to this room, if anyone. Note we have to do this
2113        // before making the `/join` request, otherwise we could race against
2114        // the sync.
2115        let pre_join_info = self.prepare_join_room_by_id(room_id).await;
2116
2117        let request = join_room_by_id::v3::Request::new(room_id.to_owned());
2118        let response = self.send(request).await?;
2119        self.finish_join_room(&response.room_id, pre_join_info).await
2120    }
2121
2122    /// Join a room by `RoomOrAliasId`.
2123    ///
2124    /// Returns the `Room` in the joined state.
2125    ///
2126    /// # Arguments
2127    ///
2128    /// - `alias` - The `RoomId` or `RoomAliasId` of the room to be joined. An
2129    ///   alias looks like `#name:example.com`.
2130    /// - `server_names` - The server names to be used for resolving the alias,
2131    ///   if needs be.
2132    #[instrument(skip(self))]
2133    pub async fn join_room_by_id_or_alias(
2134        &self,
2135        alias: &RoomOrAliasId,
2136        server_names: &[OwnedServerName],
2137    ) -> Result<Room> {
2138        let room_id = match <&RoomId>::try_from(alias) {
2139            Ok(room_id) => room_id,
2140            Err(room_alias) => &self.resolve_room_alias(room_alias).await?.room_id,
2141        };
2142        let pre_join_info = self.prepare_join_room_by_id(room_id).await;
2143        let request = assign!(join_room_by_id_or_alias::v3::Request::new(alias.to_owned()), {
2144            via: server_names.to_owned(),
2145        });
2146        let response = self.send(request).await?;
2147        self.finish_join_room(&response.room_id, pre_join_info).await
2148    }
2149
2150    /// Search the homeserver's directory of public rooms.
2151    ///
2152    /// Sends a request to "_matrix/client/r0/publicRooms", returns a
2153    /// `get_public_rooms::Response`.
2154    ///
2155    /// # Arguments
2156    ///
2157    /// - `limit` - The number of `PublicRoomsChunk`s in each response.
2158    /// - `since` - Pagination token from a previous request.
2159    /// - `server` - The name of the server, if `None` the requested server is
2160    ///   used.
2161    ///
2162    /// # Examples
2163    ///
2164    /// ```no_run
2165    /// use matrix_sdk::Client;
2166    /// # use url::Url;
2167    /// # let homeserver = Url::parse("http://example.com").unwrap();
2168    /// # let limit = Some(10);
2169    /// # let since = Some("since token");
2170    /// # let server = Some("servername.com".try_into().unwrap());
2171    /// # async {
2172    /// let mut client = Client::new(homeserver).await.unwrap();
2173    ///
2174    /// client.public_rooms(limit, since, server).await;
2175    /// # };
2176    /// ```
2177    // TODO: Re-enable once https://github.com/rust-lang/rust-clippy/issues/17812 is resolved.
2178    // #[cfg_attr(not(target_family = "wasm"), deny(clippy::future_not_send))]
2179    pub async fn public_rooms(
2180        &self,
2181        limit: Option<u32>,
2182        since: Option<&str>,
2183        server: Option<&ServerName>,
2184    ) -> HttpResult<get_public_rooms::v3::Response> {
2185        let limit = limit.map(UInt::from);
2186
2187        let request = assign!(get_public_rooms::v3::Request::new(), {
2188            limit,
2189            since: since.map(ToOwned::to_owned),
2190            server: server.map(ToOwned::to_owned),
2191        });
2192        self.send(request).await
2193    }
2194
2195    /// Create a room with the given parameters.
2196    ///
2197    /// Sends a request to `/_matrix/client/r0/createRoom` and returns the
2198    /// created room.
2199    ///
2200    /// If you want to create a direct message with one specific user, you can
2201    /// use [`create_dm`][Self::create_dm], which is more convenient than
2202    /// assembling the [`create_room::v3::Request`] yourself.
2203    ///
2204    /// If the `is_direct` field of the request is set to `true` and at least
2205    /// one user is invited, the room will be automatically added to the direct
2206    /// rooms in the account data.
2207    ///
2208    /// # Examples
2209    ///
2210    /// ```no_run
2211    /// use matrix_sdk::{
2212    ///     Client,
2213    ///     ruma::api::client::room::create_room::v3::Request as CreateRoomRequest,
2214    /// };
2215    /// # use url::Url;
2216    /// #
2217    /// # async {
2218    /// # let homeserver = Url::parse("http://example.com").unwrap();
2219    /// let request = CreateRoomRequest::new();
2220    /// let client = Client::new(homeserver).await.unwrap();
2221    /// assert!(client.create_room(request).await.is_ok());
2222    /// # };
2223    /// ```
2224    pub async fn create_room(&self, request: create_room::v3::Request) -> Result<Room> {
2225        let invite = request.invite.clone();
2226        let is_direct_room = request.is_direct;
2227
2228        let request_config = self.request_config().disable_retry();
2229        let response = self.send(request).with_request_config(request_config).await?;
2230
2231        let base_room = self.base_client().get_or_create_room(&response.room_id, RoomState::Joined);
2232
2233        let joined_room = Room::new(self.clone(), base_room);
2234
2235        if is_direct_room
2236            && !invite.is_empty()
2237            && let Err(error) =
2238                self.account().mark_as_dm(joined_room.room_id(), invite.as_slice()).await
2239        {
2240            // FIXME: Retry in the background
2241            error!("Failed to mark room as DM: {error}");
2242        }
2243
2244        Ok(joined_room)
2245    }
2246
2247    /// Create a DM room.
2248    ///
2249    /// Convenience shorthand for [`create_room`][Self::create_room] with the
2250    /// given user being invited, the room marked `is_direct` and both the
2251    /// creator and invitee getting the default maximum power level.
2252    ///
2253    /// If the `e2e-encryption` feature is enabled, the room will also be
2254    /// encrypted.
2255    ///
2256    /// # Arguments
2257    ///
2258    /// - `user_id` - The ID of the user to create a DM for.
2259    pub async fn create_dm(&self, user_id: &UserId) -> Result<Room> {
2260        #[cfg(feature = "e2e-encryption")]
2261        let initial_state = vec![
2262            InitialStateEvent::with_empty_state_key(
2263                RoomEncryptionEventContent::with_recommended_defaults(),
2264            )
2265            .to_raw_any(),
2266        ];
2267
2268        #[cfg(not(feature = "e2e-encryption"))]
2269        let initial_state = vec![];
2270
2271        let request = assign!(create_room::v3::Request::new(), {
2272            invite: vec![user_id.to_owned()],
2273            is_direct: true,
2274            preset: Some(create_room::v3::RoomPreset::TrustedPrivateChat),
2275            initial_state,
2276        });
2277
2278        self.create_room(request).await
2279    }
2280
2281    /// Get the first existing DM room with the given user, if any.
2282    pub fn get_dm_room(&self, user_id: &UserId) -> Option<Room> {
2283        self.get_dm_rooms(user_id).next()
2284    }
2285
2286    /// Get an iterator with the existing DM rooms for the given user.
2287    pub fn get_dm_rooms(&self, user_id: &UserId) -> impl Iterator<Item = Room> {
2288        let rooms = self.joined_rooms();
2289
2290        let dm_definition = &self.base_client().dm_room_definition;
2291
2292        // Find the room we share with the `user_id` and only with `user_id`
2293        let rooms = rooms.into_iter().filter(move |r| {
2294            let targets = r.direct_targets();
2295            let targets_match =
2296                targets.len() == 1 && targets.contains(<&DirectUserIdentifier>::from(user_id));
2297            match dm_definition {
2298                DmRoomDefinition::MatrixSpec => targets_match,
2299                DmRoomDefinition::TwoMembers => {
2300                    let service_members_count =
2301                        r.service_members().map(|s| s.len()).unwrap_or_default() as u64;
2302                    let active_non_service_members =
2303                        r.active_members_count().saturating_sub(service_members_count);
2304                    targets_match && active_non_service_members <= 2
2305                }
2306            }
2307        });
2308
2309        trace!(?user_id, ?rooms, "Found DM rooms with user");
2310        rooms
2311    }
2312
2313    /// Search the homeserver's directory for public rooms with a filter.
2314    ///
2315    /// # Arguments
2316    ///
2317    /// - `room_search` - The easiest way to create this request is using the
2318    ///   `get_public_rooms_filtered::Request` itself.
2319    ///
2320    /// # Examples
2321    ///
2322    /// ```no_run
2323    /// # use url::Url;
2324    /// # use matrix_sdk::Client;
2325    /// # async {
2326    /// # let homeserver = Url::parse("http://example.com")?;
2327    /// use matrix_sdk::ruma::{
2328    ///     api::client::directory::get_public_rooms_filtered, directory::Filter,
2329    /// };
2330    /// # let mut client = Client::new(homeserver).await?;
2331    ///
2332    /// let mut filter = Filter::new();
2333    /// filter.generic_search_term = Some("rust".to_owned());
2334    /// let mut request = get_public_rooms_filtered::v3::Request::new();
2335    /// request.filter = filter;
2336    ///
2337    /// let response = client.public_rooms_filtered(request).await?;
2338    ///
2339    /// for room in response.chunk {
2340    ///     println!("Found room {room:?}");
2341    /// }
2342    /// # anyhow::Ok(()) };
2343    /// ```
2344    pub async fn public_rooms_filtered(
2345        &self,
2346        request: get_public_rooms_filtered::v3::Request,
2347    ) -> HttpResult<get_public_rooms_filtered::v3::Response> {
2348        self.send(request).await
2349    }
2350
2351    /// Send an arbitrary request to the server, without updating client state.
2352    ///
2353    /// **Warning:** Because this method _does not_ update the client state, it
2354    /// is important to make sure that you account for this yourself, and use
2355    /// wrapper methods where available. This method should _only_ be used if a
2356    /// wrapper method for the endpoint you'd like to use is not available.
2357    ///
2358    /// # Arguments
2359    ///
2360    /// - `request` - A filled out and valid request for the endpoint to be hit
2361    /// - `timeout` - An optional request timeout setting, this overrides the
2362    ///   default request setting if one was set.
2363    ///
2364    /// # Examples
2365    ///
2366    /// ```no_run
2367    /// # use matrix_sdk::{Client, config::SyncSettings};
2368    /// # use url::Url;
2369    /// # async {
2370    /// # let homeserver = Url::parse("http://localhost:8080")?;
2371    /// # let mut client = Client::new(homeserver).await?;
2372    /// use matrix_sdk::ruma::{api::client::profile, owned_user_id};
2373    ///
2374    /// // First construct the request you want to make
2375    /// // See https://docs.rs/ruma-client-api/latest/ruma_client_api/index.html
2376    /// // for all available Endpoints
2377    /// let user_id = owned_user_id!("@example:localhost");
2378    /// let request = profile::get_profile::v3::Request::new(user_id);
2379    ///
2380    /// // Start the request using Client::send()
2381    /// let response = client.send(request).await?;
2382    ///
2383    /// // Check the corresponding Response struct to find out what types are
2384    /// // returned
2385    /// # anyhow::Ok(()) };
2386    /// ```
2387    pub fn send<Request>(&self, request: Request) -> SendRequest<Request>
2388    where
2389        Request: OutgoingRequest + Clone + Debug,
2390        Request::Authentication: SupportedAuthScheme,
2391        Request::PathBuilder: SupportedPathBuilder,
2392        for<'a> <Request::PathBuilder as PathBuilder>::Input<'a>: SendOutsideWasm + SyncOutsideWasm,
2393        HttpError: From<FromHttpResponseError<Request::EndpointError>>,
2394    {
2395        SendRequest {
2396            client: self.clone(),
2397            request,
2398            config: None,
2399            send_progress: Default::default(),
2400        }
2401    }
2402
2403    pub(crate) async fn send_inner<Request>(
2404        &self,
2405        request: Request,
2406        config: Option<RequestConfig>,
2407        send_progress: SharedObservable<TransmissionProgress>,
2408    ) -> HttpResult<Request::IncomingResponse>
2409    where
2410        Request: OutgoingRequest + Debug,
2411        Request::Authentication: SupportedAuthScheme,
2412        Request::PathBuilder: SupportedPathBuilder,
2413        for<'a> <Request::PathBuilder as PathBuilder>::Input<'a>: SendOutsideWasm + SyncOutsideWasm,
2414        HttpError: From<FromHttpResponseError<Request::EndpointError>>,
2415    {
2416        let homeserver = self.homeserver().to_string();
2417        let access_token = self.access_token();
2418        let skip_auth = config.map(|c| c.skip_auth).unwrap_or(self.request_config().skip_auth);
2419
2420        let path_builder_input =
2421            Request::PathBuilder::get_path_builder_input(self, skip_auth).await?;
2422
2423        let result = self
2424            .inner
2425            .http_client
2426            .send(
2427                request,
2428                config,
2429                homeserver,
2430                access_token.as_deref(),
2431                path_builder_input,
2432                send_progress,
2433            )
2434            .await;
2435
2436        if let Err(Some(ErrorKind::UnknownToken { .. })) =
2437            result.as_ref().map_err(HttpError::client_api_error_kind)
2438            && let Some(access_token) = &access_token
2439        {
2440            // Mark the access token as expired.
2441            self.auth_ctx().set_access_token_expired(access_token);
2442        }
2443
2444        result
2445    }
2446
2447    fn broadcast_unknown_token(&self, unknown_token_data: &UnknownTokenErrorData) {
2448        _ = self
2449            .inner
2450            .auth_ctx
2451            .session_change_sender
2452            .send(SessionChange::UnknownToken(unknown_token_data.clone()));
2453    }
2454
2455    /// Fetches server versions from network; no caching.
2456    pub async fn fetch_server_versions(
2457        &self,
2458        request_config: Option<RequestConfig>,
2459    ) -> HttpResult<get_supported_versions::Response> {
2460        // Since this was called by the user, try to refresh the access token if
2461        // necessary.
2462        self.fetch_server_versions_inner(false, request_config).await
2463    }
2464
2465    /// Fetches server versions from network; no caching.
2466    ///
2467    /// If the access token is expired and `failsafe` is `false`, this will
2468    /// attempt to refresh the access token, otherwise this will try to make an
2469    /// unauthenticated request instead.
2470    pub(crate) async fn fetch_server_versions_inner(
2471        &self,
2472        failsafe: bool,
2473        request_config: Option<RequestConfig>,
2474    ) -> HttpResult<get_supported_versions::Response> {
2475        if !failsafe {
2476            // `Client::send()` handles refreshing access tokens.
2477            return self
2478                .send(get_supported_versions::Request::new())
2479                .with_request_config(request_config)
2480                .await;
2481        }
2482
2483        let homeserver = self.homeserver().to_string();
2484
2485        // If we have a fresh access token, try with it first.
2486        if !request_config.as_ref().is_some_and(|config| config.skip_auth && !config.force_auth)
2487            && self.auth_ctx().has_valid_access_token()
2488            && let Some(access_token) = self.access_token()
2489        {
2490            let result = self
2491                .inner
2492                .http_client
2493                .send(
2494                    get_supported_versions::Request::new(),
2495                    request_config,
2496                    homeserver.clone(),
2497                    Some(&access_token),
2498                    (),
2499                    Default::default(),
2500                )
2501                .await;
2502
2503            if let Err(Some(ErrorKind::UnknownToken { .. })) =
2504                result.as_ref().map_err(HttpError::client_api_error_kind)
2505            {
2506                // If the access token is actually expired, mark it as expired
2507                // and fallback to the unauthenticated request below.
2508                self.auth_ctx().set_access_token_expired(&access_token);
2509            } else {
2510                // If the request succeeded or it's an other error, just stop
2511                // now.
2512                return result;
2513            }
2514        }
2515
2516        // Try without authentication.
2517        self.inner
2518            .http_client
2519            .send(
2520                get_supported_versions::Request::new(),
2521                request_config,
2522                homeserver.clone(),
2523                None,
2524                (),
2525                Default::default(),
2526            )
2527            .await
2528    }
2529
2530    /// Fetches client well_known from network; no caching.
2531    ///
2532    /// 1. If the [`Client::server`] value is available, we use it to fetch the
2533    ///    well-known contents.
2534    /// 2. If it's not, we try extracting the server name from the
2535    ///    [`Client::user_id`] and building the server URL from it.
2536    /// 3. If we couldn't get the well-known contents with either the explicit
2537    ///    server name or the implicit extracted one, we try the homeserver URL
2538    ///    as a last resort.
2539    ///
2540    /// Always returns `None` if well-known lookups were disabled with
2541    /// [`ClientBuilder::disable_well_known_lookup`].
2542    pub async fn fetch_client_well_known(&self) -> Option<discover_homeserver::Response> {
2543        if self.well_known_lookup_disabled() {
2544            return None;
2545        }
2546
2547        let homeserver = self.homeserver();
2548        let scheme = homeserver.scheme();
2549
2550        // Use the server name, either an explicit one or an implicit one taken
2551        // from the user id: sometimes we'll have only the homeserver url
2552        // available and no server name, but the server name can be extracted
2553        // from the current user id.
2554        let server_url = self
2555            .server()
2556            .map(|server| server.to_string())
2557            // If the server name wasn't available, extract it from the user id
2558            // and build a URL: Reuse the same scheme as the homeserver url
2559            // does, assuming if it's `http` there it will be the same for the
2560            // public server url, lacking a better candidate.
2561            .or_else(|| self.user_id().map(|id| format!("{}://{}", scheme, id.server_name())));
2562
2563        // If the server name is available, first try using it
2564        let response = if let Some(server_url) = server_url {
2565            // First try using the server name
2566            self.fetch_client_well_known_with_url(server_url).await
2567        } else {
2568            None
2569        };
2570
2571        // If we didn't get a well-known value yet, try with the homeserver url
2572        // instead:
2573        if response.is_none() {
2574            // Sometimes people configure their well-known directly on the
2575            // homeserver so use this as a fallback when the server name is
2576            // unknown.
2577            warn!(
2578                "Fetching the well-known from the server name didn't work, using the homeserver url instead"
2579            );
2580            self.fetch_client_well_known_with_url(homeserver.to_string()).await
2581        } else {
2582            response
2583        }
2584    }
2585
2586    async fn fetch_client_well_known_with_url(
2587        &self,
2588        url: String,
2589    ) -> Option<discover_homeserver::Response> {
2590        let well_known = self
2591            .inner
2592            .http_client
2593            .send(
2594                discover_homeserver::Request::new(),
2595                Some(RequestConfig::short_retry()),
2596                url,
2597                None,
2598                (),
2599                Default::default(),
2600            )
2601            .await;
2602
2603        match well_known {
2604            Ok(well_known) => Some(well_known),
2605            Err(http_error) => {
2606                // It is perfectly valid to not have a well-known file. Maybe we
2607                // should check for a specific error code to be sure?
2608                warn!("Failed to fetch client well-known: {http_error}");
2609                None
2610            }
2611        }
2612    }
2613
2614    /// Load supported versions from storage, or fetch them from network and
2615    /// cache them.
2616    ///
2617    /// If `failsafe` is true, this will try to minimize side effects to avoid
2618    /// possible deadlocks.
2619    async fn fetch_supported_versions(
2620        &self,
2621        failsafe: bool,
2622    ) -> HttpResult<SupportedVersionsResponse> {
2623        let server_versions = self.fetch_server_versions_inner(failsafe, None).await?;
2624        let supported_versions = SupportedVersionsResponse {
2625            versions: server_versions.versions,
2626            unstable_features: server_versions.unstable_features,
2627        };
2628
2629        Ok(supported_versions)
2630    }
2631
2632    /// Get the Matrix versions and features supported by the homeserver by
2633    /// fetching them from the server or the cache.
2634    ///
2635    /// This is equivalent to calling both [`Client::server_versions()`] and
2636    /// [`Client::unstable_features()`]. To always fetch the result from the
2637    /// homeserver, you can call [`Client::fetch_server_versions()`] instead,
2638    /// and then `.as_supported_versions()` on the response.
2639    ///
2640    /// # Examples
2641    ///
2642    /// ```no_run
2643    /// use ruma::api::{FeatureFlag, MatrixVersion};
2644    /// # use matrix_sdk::{Client, config::SyncSettings};
2645    /// # use url::Url;
2646    /// # async {
2647    /// # let homeserver = Url::parse("http://localhost:8080")?;
2648    /// # let mut client = Client::new(homeserver).await?;
2649    ///
2650    /// let supported = client.supported_versions().await?;
2651    /// let supports_1_1 = supported.versions.contains(&MatrixVersion::V1_1);
2652    /// println!("The homeserver supports Matrix 1.1: {supports_1_1:?}");
2653    ///
2654    /// let msc_x_feature = FeatureFlag::from("msc_x");
2655    /// let supports_msc_x = supported.features.contains(&msc_x_feature);
2656    /// println!("The homeserver supports msc X: {supports_msc_x:?}");
2657    /// # anyhow::Ok(()) };
2658    /// ```
2659    pub async fn supported_versions(&self) -> HttpResult<SupportedVersions> {
2660        self.supported_versions_inner(false).await
2661    }
2662
2663    /// Get the Matrix versions and features supported by the homeserver by
2664    /// fetching them from the server or the cache.
2665    ///
2666    /// If `failsafe` is true, this will try to minimize side effects to avoid
2667    /// possible deadlocks.
2668    pub(crate) async fn supported_versions_inner(
2669        &self,
2670        failsafe: bool,
2671    ) -> HttpResult<SupportedVersions> {
2672        match self.supported_versions_cached_inner(failsafe).await {
2673            Ok(Some(value)) => {
2674                return Ok(value);
2675            }
2676            Ok(None) => {
2677                // The cache is empty, make a request.
2678            }
2679            Err(error) => {
2680                warn!("error when loading cached supported versions: {error}");
2681                // Fallthrough to make a request.
2682            }
2683        }
2684
2685        self.refresh_supported_versions_cache(failsafe).await
2686    }
2687
2688    /// Refresh the Matrix versions and features supported by the homeserver in
2689    /// the cache.
2690    ///
2691    /// If `failsafe` is true, this will try to minimize side effects to avoid
2692    /// possible deadlocks.
2693    async fn refresh_supported_versions_cache(
2694        &self,
2695        failsafe: bool,
2696    ) -> HttpResult<SupportedVersions> {
2697        let cached_supported_versions = &self.inner.caches.supported_versions;
2698
2699        let mut supported_versions_guard = match cached_supported_versions.refresh_lock.try_lock() {
2700            Ok(guard) => guard,
2701            Err(_) => {
2702                // There is already a refresh in progress, wait for it to
2703                // finish.
2704                let guard = cached_supported_versions.refresh_lock.lock().await;
2705
2706                if let Err(error) = guard.as_ref() {
2707                    // There was an error in the previous refresh, return it.
2708                    return Err(HttpError::Cached(error.clone()));
2709                }
2710
2711                // Reuse the data if it was cached and it hasn't expired.
2712                if let CachedValue::Cached(value) = cached_supported_versions.value()
2713                    && !value.has_expired()
2714                {
2715                    return Ok(value.into_data());
2716                }
2717
2718                // The data wasn't cached or has expired, we need to make
2719                // another request.
2720                guard
2721            }
2722        };
2723
2724        let response = match self.fetch_supported_versions(failsafe).await {
2725            Ok(response) => {
2726                *supported_versions_guard = Ok(());
2727                TtlValue::new(response)
2728            }
2729            Err(error) => {
2730                let error = Arc::new(error);
2731                *supported_versions_guard = Err(error.clone());
2732                return Err(HttpError::Cached(error));
2733            }
2734        };
2735
2736        let supported_versions = response.as_ref().map(|response| response.supported_versions());
2737
2738        // Only cache the result if the request was authenticated.
2739        if self.auth_ctx().has_valid_access_token() {
2740            if let Err(err) = self
2741                .state_store()
2742                .set_kv_data(
2743                    StateStoreDataKey::SupportedVersions,
2744                    StateStoreDataValue::SupportedVersions(response),
2745                )
2746                .await
2747            {
2748                warn!("error when caching supported versions: {err}");
2749            }
2750
2751            cached_supported_versions.set_value(supported_versions.clone());
2752        }
2753
2754        Ok(supported_versions.into_data())
2755    }
2756
2757    /// Get the Matrix versions and features supported by the homeserver by
2758    /// fetching them from the cache.
2759    ///
2760    /// For a version of this function that fetches the supported versions and
2761    /// features from the homeserver if the [`SupportedVersions`] aren't found
2762    /// in the cache, take a look at the [`Client::supported_versions()`]
2763    /// method.
2764    ///
2765    /// If the data in the cache has expired, this will trigger a background
2766    /// task to refresh it.
2767    ///
2768    /// # Examples
2769    ///
2770    /// ```no_run
2771    /// use ruma::api::{FeatureFlag, MatrixVersion};
2772    /// # use matrix_sdk::{Client, config::SyncSettings};
2773    /// # use url::Url;
2774    /// # async {
2775    /// # let homeserver = Url::parse("http://localhost:8080")?;
2776    /// # let mut client = Client::new(homeserver).await?;
2777    ///
2778    /// let supported =
2779    ///     if let Some(supported) = client.supported_versions_cached().await? {
2780    ///         supported
2781    ///     } else {
2782    ///         client.fetch_server_versions(None).await?.as_supported_versions()
2783    ///     };
2784    ///
2785    /// let supports_1_1 = supported.versions.contains(&MatrixVersion::V1_1);
2786    /// println!("The homeserver supports Matrix 1.1: {supports_1_1:?}");
2787    ///
2788    /// let msc_x_feature = FeatureFlag::from("msc_x");
2789    /// let supports_msc_x = supported.features.contains(&msc_x_feature);
2790    /// println!("The homeserver supports msc X: {supports_msc_x:?}");
2791    /// # anyhow::Ok(()) };
2792    /// ```
2793    pub async fn supported_versions_cached(&self) -> Result<Option<SupportedVersions>, StoreError> {
2794        self.supported_versions_cached_inner(false).await
2795    }
2796
2797    async fn supported_versions_cached_inner(
2798        &self,
2799        failsafe: bool,
2800    ) -> Result<Option<SupportedVersions>, StoreError> {
2801        let supported_versions_cache = &self.inner.caches.supported_versions;
2802
2803        let value = if let CachedValue::Cached(cached) = supported_versions_cache.value() {
2804            cached
2805        } else if let Some(stored) = self
2806            .state_store()
2807            .get_kv_data(StateStoreDataKey::SupportedVersions)
2808            .await?
2809            .and_then(|value| value.into_supported_versions())
2810        {
2811            let stored = stored.map(|response| response.supported_versions());
2812
2813            // Copy the data from the store in the in-memory cache.
2814            supported_versions_cache.set_value(stored.clone());
2815
2816            stored
2817        } else {
2818            return Ok(None);
2819        };
2820
2821        // Spawn a task to refresh the cache if it has expired and we have a
2822        // valid access token.
2823        if value.has_expired() && self.auth_ctx().has_valid_access_token() {
2824            debug!("spawning task to refresh supported versions cache");
2825
2826            let client = self.clone();
2827            self.task_monitor().spawn_finite_task("refresh supported versions cache", async move {
2828                if let Err(error) = client.refresh_supported_versions_cache(failsafe).await {
2829                    warn!("failed to refresh supported versions cache: {error}");
2830                }
2831            });
2832        }
2833
2834        Ok(Some(value.into_data()))
2835    }
2836
2837    /// Get the Matrix versions supported by the homeserver by fetching them
2838    /// from the server or the cache.
2839    ///
2840    /// # Examples
2841    ///
2842    /// ```no_run
2843    /// use ruma::api::MatrixVersion;
2844    /// # use matrix_sdk::{Client, config::SyncSettings};
2845    /// # use url::Url;
2846    /// # async {
2847    /// # let homeserver = Url::parse("http://localhost:8080")?;
2848    /// # let mut client = Client::new(homeserver).await?;
2849    ///
2850    /// let server_versions = client.server_versions().await?;
2851    /// let supports_1_1 = server_versions.contains(&MatrixVersion::V1_1);
2852    /// println!("The homeserver supports Matrix 1.1: {supports_1_1:?}");
2853    /// # anyhow::Ok(()) };
2854    /// ```
2855    pub async fn server_versions(&self) -> HttpResult<BTreeSet<MatrixVersion>> {
2856        Ok(self.supported_versions().await?.versions)
2857    }
2858
2859    /// Get the unstable features supported by the homeserver by fetching them
2860    /// from the server or the cache.
2861    ///
2862    /// # Examples
2863    ///
2864    /// ```no_run
2865    /// use matrix_sdk::ruma::api::FeatureFlag;
2866    /// # use matrix_sdk::{Client, config::SyncSettings};
2867    /// # use url::Url;
2868    /// # async {
2869    /// # let homeserver = Url::parse("http://localhost:8080")?;
2870    /// # let mut client = Client::new(homeserver).await?;
2871    ///
2872    /// let msc_x_feature = FeatureFlag::from("msc_x");
2873    /// let unstable_features = client.unstable_features().await?;
2874    /// let supports_msc_x = unstable_features.contains(&msc_x_feature);
2875    /// println!("The homeserver supports msc X: {supports_msc_x:?}");
2876    /// # anyhow::Ok(()) };
2877    /// ```
2878    pub async fn unstable_features(&self) -> HttpResult<BTreeSet<FeatureFlag>> {
2879        Ok(self.supported_versions().await?.features)
2880    }
2881
2882    /// Empty the supported versions and unstable features cache.
2883    ///
2884    /// Since the SDK caches the supported versions, it's possible to have a
2885    /// stale entry in the cache. This functions makes it possible to force
2886    /// reset it.
2887    pub async fn reset_supported_versions(&self) -> Result<()> {
2888        // Empty the in-memory cache.
2889        self.inner.caches.supported_versions.reset();
2890
2891        // Empty the store cache.
2892        Ok(self.state_store().remove_kv_data(StateStoreDataKey::SupportedVersions).await?)
2893    }
2894
2895    /// Get the well-known file of the homeserver from the cache.
2896    ///
2897    /// If the data in the cache has expired, this will trigger a background
2898    /// task to refresh it.
2899    async fn well_known_cached(
2900        &self,
2901    ) -> Result<CachedValue<Option<WellKnownResponse>>, StoreError> {
2902        let well_known_cache = &self.inner.caches.well_known;
2903
2904        let value = if let CachedValue::Cached(cached) = well_known_cache.value() {
2905            cached
2906        } else if let Some(stored) = self
2907            .state_store()
2908            .get_kv_data(StateStoreDataKey::WellKnown)
2909            .await?
2910            .and_then(|value| value.into_well_known())
2911        {
2912            // Copy the data from the store into the in-memory cache.
2913            well_known_cache.set_value(stored.clone());
2914
2915            stored
2916        } else {
2917            return Ok(CachedValue::NotSet);
2918        };
2919
2920        // Spawn a task to refresh the cache if it has expired.
2921        if value.has_expired() {
2922            debug!("spawning task to refresh well-known cache");
2923
2924            let client = self.clone();
2925            self.task_monitor().spawn_finite_task("refresh well-known cache", async move {
2926                client.refresh_well_known_cache().await;
2927            });
2928        }
2929
2930        Ok(CachedValue::Cached(value.into_data()))
2931    }
2932
2933    /// Refresh the well-known file of the homeserver in the cache.
2934    async fn refresh_well_known_cache(&self) -> Option<WellKnownResponse> {
2935        let well_known_cache = &self.inner.caches.well_known;
2936
2937        let _well_known_guard = match well_known_cache.refresh_lock.try_lock() {
2938            Ok(guard) => guard,
2939            Err(_) => {
2940                // There is already a refresh in progress, wait for it to
2941                // finish.
2942                let guard = well_known_cache.refresh_lock.lock().await;
2943
2944                // A refresh can't fail because we ignore failures, so there
2945                // shouldn't be an error in the refresh lock.
2946
2947                // Reuse the data if it was cached and it hasn't expired.
2948                if let CachedValue::Cached(value) = well_known_cache.value()
2949                    && !value.has_expired()
2950                {
2951                    return value.into_data();
2952                }
2953
2954                // The data wasn't cached or has expired, we need to make
2955                // another request.
2956                guard
2957            }
2958        };
2959
2960        let well_known = TtlValue::new(self.fetch_client_well_known().await.map(Into::into));
2961
2962        if let Err(err) = self
2963            .state_store()
2964            .set_kv_data(
2965                StateStoreDataKey::WellKnown,
2966                StateStoreDataValue::WellKnown(well_known.clone()),
2967            )
2968            .await
2969        {
2970            warn!("error when caching well-known: {err}");
2971        }
2972
2973        well_known_cache.set_value(well_known.clone());
2974
2975        well_known.into_data()
2976    }
2977
2978    /// Whether this client is allowed to look up the homeserver's
2979    /// /.well-known/matrix/client file.
2980    fn well_known_lookup_disabled(&self) -> bool {
2981        *self.inner.well_known_lookup_disabled.read().unwrap()
2982    }
2983
2984    /// Change whether this client is allowed to look up the homeserver's
2985    /// /.well-known/matrix/client file.
2986    pub fn disable_well_known_lookup(&self, disable: bool) {
2987        *self.inner.well_known_lookup_disabled.write().unwrap() = disable;
2988    }
2989
2990    /// Get the well-known file of the homeserver by fetching it from the server
2991    /// or the cache.
2992    ///
2993    /// Always returns `None` if well-known discovery was disabled with
2994    /// [`ClientBuilder::disable_well_known_lookup`].
2995    async fn well_known(&self) -> Option<WellKnownResponse> {
2996        if self.well_known_lookup_disabled() {
2997            return None;
2998        }
2999
3000        match self.well_known_cached().await {
3001            Ok(CachedValue::Cached(value)) => {
3002                return value;
3003            }
3004            Ok(CachedValue::NotSet) => {
3005                // The cache is empty, make a request.
3006            }
3007            Err(error) => {
3008                warn!("error when loading cached well-known: {error}");
3009                // Fallthrough to make a request.
3010            }
3011        }
3012
3013        self.refresh_well_known_cache().await
3014    }
3015
3016    /// Get information about the homeserver's advertised RTC transports by
3017    /// fetching the well-known file from the server or the cache.
3018    ///
3019    /// Returns an empty list if well-known discovery was disabled with
3020    /// [`ClientBuilder::disable_well_known_lookup`].
3021    #[deprecated = "Use `Client::discover_rtc_transports` instead"]
3022    pub async fn rtc_foci(&self) -> HttpResult<Vec<RtcTransport>> {
3023        self.well_known_rtc_transports().await
3024    }
3025
3026    /// Get information about the homeserver's advertised RTC foci by fetching
3027    /// the well-known file from the server or the cache.
3028    ///
3029    /// This will be soon deprecated in favor of
3030    /// [`Client::discover_rtc_transports`], which fetches the RTC transports
3031    /// advertised by the homeserver through the authenticated
3032    /// `GET /_matrix/client/v1/rtc/transports` endpoint.
3033    ///
3034    /// Returns an empty list if well-known discovery was disabled with
3035    /// [`ClientBuilder::disable_well_known_lookup`].
3036    ///
3037    /// # Examples
3038    ///
3039    /// ```no_run
3040    /// # #![allow(deprecated)]
3041    /// # use matrix_sdk::{Client, config::SyncSettings, ruma::api::client::rtc::RtcTransport};
3042    /// # use url::Url;
3043    /// # async {
3044    /// # let homeserver = Url::parse("http://localhost:8080")?;
3045    /// # let mut client = Client::new(homeserver).await?;
3046    /// let rtc_foci = client.well_known_rtc_transports().await?;
3047    /// // Well-known foci may still use the legacy `livekit` transport type.
3048    /// let default_livekit_url = rtc_foci.iter().find_map(|focus| match focus {
3049    ///     RtcTransport::LiveKit(info) => Some(&info.url),
3050    ///     RtcTransport::LegacyLiveKit(info) => info.url.as_ref(),
3051    ///     _ => None,
3052    /// });
3053    /// if let Some(url) = default_livekit_url {
3054    ///     println!("Default LiveKit SFU URL: {url}");
3055    /// }
3056    /// # anyhow::Ok(()) };
3057    /// ```
3058    pub async fn well_known_rtc_transports(&self) -> HttpResult<Vec<RtcTransport>> {
3059        let well_known = self.well_known().await;
3060
3061        Ok(well_known.map(|well_known| well_known.rtc_foci).unwrap_or_default())
3062    }
3063
3064    /// Get the RTC transports advertised by the homeserver by fetching them
3065    /// from the server or the cache.
3066    ///
3067    /// The transports are discovered through the authenticated
3068    /// `GET /_matrix/client/v1/rtc/transports` endpoint
3069    /// ([MSC4143](https://github.com/matrix-org/matrix-spec-proposals/pull/4143)).
3070    async fn rtc_transports(&self) -> HttpResult<Option<Vec<RtcTransport>>> {
3071        match self.rtc_transports_cached() {
3072            CachedValue::Cached(value) => Ok(value),
3073            // The cache is empty, make a request.
3074            CachedValue::NotSet => self.refresh_rtc_transports_cache().await,
3075        }
3076    }
3077
3078    /// Get the RTC transports advertised by the homeserver from the cache.
3079    ///
3080    /// Returns [`CachedValue::NotSet`] if nothing has been cached yet. If the
3081    /// cached data has expired, this triggers a background task to refresh it
3082    /// and returns the stale value.
3083    fn rtc_transports_cached(&self) -> CachedValue<Option<Vec<RtcTransport>>> {
3084        let cache = &self.inner.caches.rtc_transports;
3085
3086        let CachedValue::Cached(value) = cache.value() else {
3087            return CachedValue::NotSet;
3088        };
3089
3090        // Spawn a task to refresh the cache if it has expired and we have a
3091        // valid access token.
3092        if value.has_expired() && self.auth_ctx().has_valid_access_token() {
3093            debug!("spawning task to refresh RTC transports cache");
3094
3095            let client = self.clone();
3096            self.task_monitor().spawn_finite_task("refresh RTC transports cache", async move {
3097                if let Err(error) = client.refresh_rtc_transports_cache().await {
3098                    warn!("failed to refresh RTC transports cache: {error}");
3099                }
3100            });
3101        }
3102
3103        CachedValue::Cached(value.into_data())
3104    }
3105
3106    /// Refresh the RTC transports advertised by the homeserver in the cache.
3107    async fn refresh_rtc_transports_cache(&self) -> HttpResult<Option<Vec<RtcTransport>>> {
3108        let cache = &self.inner.caches.rtc_transports;
3109
3110        let mut refresh_guard = match cache.refresh_lock.try_lock() {
3111            Ok(guard) => guard,
3112            Err(_) => {
3113                // There is already a refresh in progress, wait for it to
3114                // finish.
3115                let guard = cache.refresh_lock.lock().await;
3116
3117                if let Err(error) = guard.as_ref() {
3118                    // There was an error in the previous refresh, return it.
3119                    return Err(HttpError::Cached(error.clone()));
3120                }
3121
3122                // Reuse the data if it was cached and it hasn't expired.
3123                if let CachedValue::Cached(value) = cache.value()
3124                    && !value.has_expired()
3125                {
3126                    return Ok(value.into_data());
3127                }
3128
3129                // The data wasn't cached or has expired, we need to make
3130                // another request.
3131                guard
3132            }
3133        };
3134
3135        match self.fetch_rtc_transports().await {
3136            Ok(transports) => {
3137                *refresh_guard = Ok(());
3138                cache.set_value(TtlValue::new(Some(transports.clone())));
3139                Ok(Some(transports))
3140            }
3141            Err(error) if error.is_endpoint_not_implemented() => {
3142                // The homeserver doesn't implement the RTC transports endpoint.
3143                // Cache `None` (with the normal TTL) so we don't hit the
3144                // endpoint on every call; this self-heals after the TTL in case
3145                // the homeserver is upgraded. `None` is kept distinct from
3146                // `Some(vec![])` (a homeserver that advertises no transports)
3147                // so callers can decide whether to fall back to the well-known
3148                // foci (see `Client::rtc_foci`).
3149                debug!("homeserver does not implement the RTC transports endpoint");
3150                *refresh_guard = Ok(());
3151                cache.set_value(TtlValue::new(None));
3152                Ok(None)
3153            }
3154            Err(error) => {
3155                let error = Arc::new(error);
3156                *refresh_guard = Err(error.clone());
3157                Err(HttpError::Cached(error))
3158            }
3159        }
3160    }
3161
3162    /// Fetch the RTC transports advertised by the homeserver from the network,
3163    /// bypassing the cache.
3164    pub async fn fetch_rtc_transports(&self) -> HttpResult<Vec<RtcTransport>> {
3165        let response = self
3166            .send(transports::msc4143::Request::new())
3167            .with_request_config(RequestConfig::short_retry())
3168            .await?;
3169        Ok(response.rtc_transports)
3170    }
3171
3172    /// Empty the RTC transports cache.
3173    ///
3174    /// Since the SDK caches the RTC transports, it's possible to have a stale
3175    /// entry in the cache. This function makes it possible to force reset it.
3176    pub fn reset_rtc_transports(&self) {
3177        self.inner.caches.rtc_transports.reset();
3178    }
3179
3180    /// Discover the RTC transports advertised by the homeserver.
3181    ///
3182    /// The transports are first looked up through the authenticated
3183    /// `GET /_matrix/client/v1/rtc/transports` endpoint
3184    /// ([MSC4143](https://github.com/matrix-org/matrix-spec-proposals/pull/4143)).
3185    /// If the homeserver doesn't implement that endpoint, this falls back to
3186    /// the `m.rtc_foci` field of the well-known, see
3187    /// [`Client::well_known_rtc_transports`] — unless well-known discovery was
3188    /// disabled with [`ClientBuilder::disable_well_known_lookup`].
3189    ///
3190    /// Returns `None` if neither source could provide transports, which is kept
3191    /// distinct from `Some(vec![])`, i.e. a homeserver that advertises no
3192    /// transports at all.
3193    ///
3194    /// # Examples
3195    ///
3196    /// ```no_run
3197    /// # use matrix_sdk::Client;
3198    /// # use url::Url;
3199    /// # async {
3200    /// # let homeserver = Url::parse("http://localhost:8080")?;
3201    /// # let client = Client::new(homeserver).await?;
3202    /// for transport in client.discover_rtc_transports().await?.unwrap_or_default()
3203    /// {
3204    ///     println!("transport type: {}", transport.transport_type());
3205    /// }
3206    /// # anyhow::Ok(()) };
3207    /// ```
3208    pub async fn discover_rtc_transports(&self) -> HttpResult<Option<Vec<RtcTransport>>> {
3209        if let Some(transports) = self.rtc_transports().await? {
3210            return Ok(Some(transports));
3211        }
3212
3213        // The homeserver doesn't implement the discovery endpoint or does not
3214        // expose any transports, fall back to the well-known foci. `well_known`
3215        // returns `None` when well-known discovery is disabled, which correctly
3216        // collapses into "nothing was discovered".
3217        Ok(self.well_known().await.map(|well_known| well_known.rtc_foci))
3218    }
3219
3220    /// Obtain a token to authenticate with a LiveKit SFU, by calling the
3221    /// homeserver's `/rtc/livekit/get_token` endpoint
3222    ///
3223    /// # Arguments
3224    ///
3225    /// * `url` - The WebSocket URL of the LiveKit SFU to obtain a token for, as
3226    ///   advertised by a LiveKit [`RtcTransport`].
3227    /// * `room_id` - The room where the `m.rtc.member` event is present.
3228    /// * `slot_id` - The slot ID from the `m.rtc.member` event.
3229    /// * `member_id` - The `member.id` property of the user's own
3230    ///   `m.rtc.member` event.
3231    /// * `server_name` - The server name of the sender of the `m.rtc.member`
3232    ///   event that advertised the SFU. If `None`, the homeserver uses its own
3233    ///   server name.
3234    ///
3235    /// Homeservers that don't implement the endpoint respond with an
3236    /// `M_UNRECOGNIZED` error, which is returned as-is.
3237    pub async fn rtc_livekit_get_token(
3238        &self,
3239        url: String,
3240        room_id: OwnedRoomId,
3241        slot_id: String,
3242        member_id: String,
3243        server_name: Option<OwnedServerName>,
3244    ) -> HttpResult<get_token::v1::Response> {
3245        let request =
3246            assign!(get_token::v1::Request::new(url, room_id, slot_id, member_id), { server_name });
3247        self.send(request).await
3248    }
3249
3250    /// Hand the delayed leave event of a MatrixRTC session over to the
3251    /// homeserver, by calling its `/rtc/livekit/delegate_delayed_leave`
3252    /// endpoint.
3253    ///
3254    /// The homeserver then takes care of keeping the delayed event alive
3255    /// while the user is connected to the LiveKit SFU, and lets it be sent
3256    /// once the user disconnects.
3257    ///
3258    /// # Arguments
3259    ///
3260    /// * `url` - The WebSocket URL of the LiveKit SFU that the user has
3261    ///   connected to.
3262    /// * `room_id` - The room where the `m.rtc.member` event is present.
3263    /// * `slot_id` - The slot ID from the `m.rtc.member` event.
3264    /// * `member_id` - The `member.id` property of the `m.rtc.member` event.
3265    /// * `delay_id` - The ID of the delayed `m.rtc.member` leave event to
3266    ///   delegate.
3267    ///
3268    /// The stable endpoint is used if the homeserver advertises the
3269    /// `org.matrix.msc4195.stable` feature, the unstable one otherwise.
3270    ///
3271    /// Homeservers that don't implement the endpoint respond with an
3272    /// `M_UNRECOGNIZED` error, which is returned as-is.
3273    pub async fn rtc_livekit_delegate_delayed_leave(
3274        &self,
3275        url: String,
3276        room_id: OwnedRoomId,
3277        slot_id: String,
3278        member_id: String,
3279        delay_id: String,
3280    ) -> HttpResult<delegate_delayed_leave::v1::Response> {
3281        let request =
3282            delegate_delayed_leave::v1::Request::new(url, room_id, slot_id, member_id, delay_id);
3283        self.send(request).await
3284    }
3285
3286    /// Get information about the homeserver's advertised map tile server, if
3287    /// any, by fetching the well-known file from the server or the cache.
3288    ///
3289    /// Returns `None` if the homeserver has not advertised a tile server in its
3290    /// well-known, or if the well-known is otherwise unavailable — including
3291    /// when well-known discovery was disabled with
3292    /// [`ClientBuilder::disable_well_known_lookup`].
3293    pub async fn tile_server(&self) -> Option<TileServerInfo> {
3294        self.well_known().await.and_then(|well_known| well_known.tile_server).map(Into::into)
3295    }
3296
3297    /// Empty the well-known cache.
3298    ///
3299    /// Since the SDK caches the well-known, it's possible to have a stale entry
3300    /// in the cache. This functions makes it possible to force reset it.
3301    pub async fn reset_well_known(&self) -> Result<()> {
3302        // Empty the in-memory caches.
3303        self.inner.caches.well_known.reset();
3304
3305        // Empty the store cache.
3306        Ok(self.state_store().remove_kv_data(StateStoreDataKey::WellKnown).await?)
3307    }
3308
3309    /// Check whether MSC 4028 is enabled on the homeserver.
3310    ///
3311    /// # Examples
3312    ///
3313    /// ```no_run
3314    /// # use matrix_sdk::{Client, config::SyncSettings};
3315    /// # use url::Url;
3316    /// # async {
3317    /// # let homeserver = Url::parse("http://localhost:8080")?;
3318    /// # let mut client = Client::new(homeserver).await?;
3319    /// let msc4028_enabled =
3320    ///     client.can_homeserver_push_encrypted_event_to_device().await?;
3321    /// # anyhow::Ok(()) };
3322    /// ```
3323    pub async fn can_homeserver_push_encrypted_event_to_device(&self) -> HttpResult<bool> {
3324        Ok(self.unstable_features().await?.contains(&FeatureFlag::from("org.matrix.msc4028")))
3325    }
3326
3327    /// Check whether the homeserver supports sticky events.
3328    ///
3329    /// This is async and fallible as it may use the network to retrieve the
3330    /// server supported features, if they aren't cached already.
3331    #[cfg(feature = "unstable-msc4354")]
3332    pub async fn supports_sticky_events(&self) -> HttpResult<bool> {
3333        Ok(self.unstable_features().await?.contains(&FeatureFlag::from("org.matrix.msc4354")))
3334    }
3335
3336    /// Update a delayed event that was previously scheduled with
3337    /// [`SendRawMessageLikeEvent::into_delayed`] or
3338    /// [`SendRawStateEvent::into_delayed`] ([MSC4140]).
3339    ///
3340    /// Depending on the `action` this cancels the delayed event, restarts its
3341    /// timeout, or sends it to the room right away.
3342    ///
3343    /// # Arguments
3344    ///
3345    /// * `delay_id` - The identifier of the delayed event, as returned by the
3346    ///   homeserver when the event was scheduled.
3347    ///
3348    /// * `action` - What to do with the delayed event.
3349    ///
3350    /// * `request_config` - The [`RequestConfig`] to use for this request, for
3351    ///   example to control retries. If `None`, the client's default request
3352    ///   config is used.
3353    ///
3354    /// [MSC4140]: https://github.com/matrix-org/matrix-spec-proposals/pull/4140
3355    /// [`SendRawMessageLikeEvent::into_delayed`]: crate::room::futures::SendRawMessageLikeEvent::into_delayed
3356    /// [`SendRawStateEvent::into_delayed`]: crate::room::futures::SendRawStateEvent::into_delayed
3357    #[instrument(skip_all)]
3358    pub async fn update_delayed_event(
3359        &self,
3360        delay_id: String,
3361        action: update_delayed_event::UpdateAction,
3362        request_config: Option<RequestConfig>,
3363    ) -> Result<update_delayed_event::msc4140_v2::Response> {
3364        let request = update_delayed_event::msc4140_v2::Request::new(delay_id, action);
3365
3366        // Ruma declares this endpoint as not requiring authentication, but the
3367        // homeserver only lets the owner of the delayed event update it, so the
3368        // access token must be sent anyway.
3369        let request_config = request_config.unwrap_or_else(|| self.request_config()).force_auth();
3370
3371        Ok(self.send(request).with_request_config(request_config).await?)
3372    }
3373
3374    /// Get information of all our own devices.
3375    ///
3376    /// # Examples
3377    ///
3378    /// ```no_run
3379    /// # use matrix_sdk::{Client, config::SyncSettings};
3380    /// # use url::Url;
3381    /// # async {
3382    /// # let homeserver = Url::parse("http://localhost:8080")?;
3383    /// # let mut client = Client::new(homeserver).await?;
3384    /// let response = client.devices().await?;
3385    ///
3386    /// for device in response.devices {
3387    ///     println!(
3388    ///         "Device: {} {}",
3389    ///         device.device_id,
3390    ///         device.display_name.as_deref().unwrap_or("")
3391    ///     );
3392    /// }
3393    /// # anyhow::Ok(()) };
3394    /// ```
3395    pub async fn devices(&self) -> HttpResult<get_devices::v3::Response> {
3396        let request = get_devices::v3::Request::new();
3397
3398        self.send(request).await
3399    }
3400
3401    /// Fetch the server's message retention policy configuration.
3402    ///
3403    /// Returns the server-level retention policy limits and any per-room
3404    /// overrides defined by the server, or `None` if the homeserver doesn't
3405    /// implement the endpoint.
3406    ///
3407    /// This always makes a request to the homeserver. On success, the
3408    /// response is stored in the client's cache and persisted in the state
3409    /// store, so it can be read with [`Self::retention_configuration`] and
3410    /// observed with [`Self::subscribe_to_retention_configuration`], even
3411    /// after a restart without connectivity.
3412    ///
3413    /// See
3414    /// [MSC1763](https://github.com/matrix-org/matrix-spec-proposals/pull/1763)
3415    /// for more info.
3416    pub async fn fetch_retention_configuration(
3417        &self,
3418    ) -> HttpResult<Option<get_retention_configuration::msc1763::Response>> {
3419        let response =
3420            match self.send(get_retention_configuration::msc1763::Request::default()).await {
3421                Ok(response) => response,
3422                Err(error) if error.is_endpoint_not_implemented() => return Ok(None),
3423                Err(error) => return Err(error),
3424            };
3425        let value = TtlValue::new(response.clone());
3426
3427        if let Err(error) = self
3428            .state_store()
3429            .set_kv_data(
3430                StateStoreDataKey::RetentionConfiguration,
3431                StateStoreDataValue::RetentionConfiguration(value.clone().map(Into::into)),
3432            )
3433            .await
3434        {
3435            warn!("error when persisting the retention configuration: {error}");
3436        }
3437
3438        self.inner.caches.retention_configuration.set(Some(value));
3439
3440        Ok(Some(response))
3441    }
3442
3443    /// Get the server's message retention policy configuration, from the cache
3444    /// if possible.
3445    ///
3446    /// If the cached value is missing or older than 6 hours, it is re-fetched
3447    /// from the homeserver with [`Self::fetch_retention_configuration`]. If
3448    /// that request fails (e.g. because there is no connectivity) and a stale
3449    /// value is cached, the stale value is returned instead. The only
3450    /// exception is when the homeserver doesn't implement the endpoint, in
3451    /// which case `None` is always returned.
3452    ///
3453    /// See
3454    /// [MSC1763](https://github.com/matrix-org/matrix-spec-proposals/pull/1763)
3455    /// for more info.
3456    pub async fn retention_configuration(
3457        &self,
3458    ) -> HttpResult<Option<get_retention_configuration::msc1763::Response>> {
3459        let cached = self.inner.caches.retention_configuration.get();
3460
3461        if let Some(cached) = &cached
3462            && !cached.has_expired_after(RETENTION_CONFIGURATION_TTL)
3463        {
3464            return Ok(Some(cached.data().clone()));
3465        }
3466
3467        match self.fetch_retention_configuration().await {
3468            Ok(response) => Ok(response),
3469            Err(error) => match cached {
3470                Some(cached) => {
3471                    warn!(
3472                        "failed to refresh the retention configuration, using the stale cached \
3473                         value: {error}"
3474                    );
3475                    Ok(Some(cached.into_data()))
3476                }
3477                None => Err(error),
3478            },
3479        }
3480    }
3481
3482    /// Subscribe to changes of the cached server message retention policy
3483    /// configuration.
3484    ///
3485    /// The initial value is the one persisted in the state store, if any. It is
3486    /// `None` until it has been successfully fetched at least once with
3487    /// [`Self::fetch_retention_configuration`] (or
3488    /// [`Self::retention_configuration`]).
3489    ///
3490    /// See
3491    /// [MSC1763](https://github.com/matrix-org/matrix-spec-proposals/pull/1763)
3492    /// for more info.
3493    pub fn subscribe_to_retention_configuration(
3494        &self,
3495    ) -> Subscriber<Option<TtlValue<get_retention_configuration::msc1763::Response>>> {
3496        self.inner.caches.retention_configuration.subscribe()
3497    }
3498
3499    /// Delete the given devices from the server.
3500    ///
3501    /// # Arguments
3502    ///
3503    /// - `devices` - The list of devices that should be deleted from the
3504    ///   server.
3505    ///
3506    /// - `auth_data` - This request requires user interactive auth, the first
3507    ///   request needs to set this to `None` and will always fail with an
3508    ///   `UiaaResponse`. The response will contain information for the
3509    ///   interactive auth and the same request needs to be made but this time
3510    ///   with some `auth_data` provided.
3511    ///
3512    /// ```no_run
3513    /// # use matrix_sdk::{
3514    /// #    ruma::{api::client::uiaa, owned_device_id},
3515    /// #    Client, Error, config::SyncSettings,
3516    /// # };
3517    /// # use serde_json::json;
3518    /// # use url::Url;
3519    /// # use std::collections::BTreeMap;
3520    /// # async {
3521    /// # let homeserver = Url::parse("http://localhost:8080")?;
3522    /// # let mut client = Client::new(homeserver).await?;
3523    /// let devices = &[owned_device_id!("DEVICEID")];
3524    ///
3525    /// if let Err(e) = client.delete_devices(devices, None).await {
3526    ///     if let Some(info) = e.as_uiaa_response() {
3527    ///         let mut password = uiaa::Password::new(
3528    ///             uiaa::UserIdentifier::Matrix(uiaa::MatrixUserIdentifier::new(
3529    ///                 "example".to_owned(),
3530    ///             )),
3531    ///             "wordpass".to_owned(),
3532    ///         );
3533    ///         password.session = info.session.clone();
3534    ///
3535    ///         client
3536    ///             .delete_devices(
3537    ///                 devices,
3538    ///                 Some(uiaa::AuthData::Password(password)),
3539    ///             )
3540    ///             .await?;
3541    ///     }
3542    /// }
3543    /// # anyhow::Ok(()) };
3544    /// ```
3545    pub async fn delete_devices(
3546        &self,
3547        devices: &[OwnedDeviceId],
3548        auth_data: Option<uiaa::AuthData>,
3549    ) -> HttpResult<delete_devices::v3::Response> {
3550        let mut request = delete_devices::v3::Request::new(devices.to_owned());
3551        request.auth = auth_data;
3552
3553        self.send(request).await
3554    }
3555
3556    /// Change the display name of a device owned by the current user.
3557    ///
3558    /// Returns a `update_device::Response` which specifies the result of the
3559    /// operation.
3560    ///
3561    /// # Arguments
3562    ///
3563    /// - `device_id` - The ID of the device to change the display name of.
3564    /// - `display_name` - The new display name to set.
3565    pub async fn rename_device(
3566        &self,
3567        device_id: &DeviceId,
3568        display_name: &str,
3569    ) -> HttpResult<update_device::v3::Response> {
3570        let mut request = update_device::v3::Request::new(device_id.to_owned());
3571        request.display_name = Some(display_name.to_owned());
3572
3573        self.send(request).await
3574    }
3575
3576    /// Check whether a device with a specific ID exists on the server.
3577    ///
3578    /// Returns Ok(true) if the device exists, Ok(false) if the server responded
3579    /// with 404 and the underlying error otherwise.
3580    ///
3581    /// # Arguments
3582    ///
3583    /// - `device_id` - The ID of the device to query.
3584    pub async fn device_exists(&self, device_id: OwnedDeviceId) -> Result<bool> {
3585        let request = device::get_device::v3::Request::new(device_id);
3586        match self.send(request).await {
3587            Ok(_) => Ok(true),
3588            Err(err) => {
3589                if let Some(error) = err.as_client_api_error()
3590                    && error.status_code == 404
3591                {
3592                    Ok(false)
3593                } else {
3594                    Err(err.into())
3595                }
3596            }
3597        }
3598    }
3599
3600    /// Synchronize the client's state with the latest state on the server.
3601    ///
3602    /// ## Syncing events
3603    ///
3604    /// Messages or any other type of event need to be periodically fetched from
3605    /// the server, this is achieved by sending a `/sync` request to the server.
3606    ///
3607    /// The first sync is sent out without a [`token`]. The response of the
3608    /// first sync will contain a [`next_batch`] field which should then be used
3609    /// in the subsequent sync calls as the [`token`]. This ensures that we
3610    /// don't receive the same events multiple times.
3611    ///
3612    /// ## Long polling
3613    ///
3614    /// A sync should in the usual case always be in flight. The
3615    /// [`SyncSettings`] have a [`timeout`] option, which controls how long the
3616    /// server will wait for new events before it will respond. The server will
3617    /// respond immediately if some new events arrive before the timeout has
3618    /// expired. If no changes arrive and the timeout expires an empty sync
3619    /// response will be sent to the client.
3620    ///
3621    /// This method of sending a request that may not receive a response
3622    /// immediately is called long polling.
3623    ///
3624    /// ## Filtering events
3625    ///
3626    /// The number or type of messages and events that the client should receive
3627    /// from the server can be altered using a [`Filter`].
3628    ///
3629    /// Filters can be non-trivial and, since they will be sent with every sync
3630    /// request, they may take up a bunch of unnecessary bandwidth.
3631    ///
3632    /// Luckily filters can be uploaded to the server and reused using an unique
3633    /// identifier, this can be achieved using the [`get_or_upload_filter()`]
3634    /// method.
3635    ///
3636    /// # Arguments
3637    ///
3638    /// - `sync_settings` - Settings for the sync call, this allows us to set
3639    /// various options to configure the sync:
3640    ///   - [`filter`] - To configure which events we receive and which get
3641    ///     [filtered] by the server
3642    ///   - [`timeout`] - To configure our [long polling] setup.
3643    ///   - [`token`] - To tell the server which events we already received and
3644    ///     where we wish to continue syncing.
3645    ///   - [`full_state`] - To tell the server that we wish to receive all
3646    ///     state events, regardless of our configured [`token`].
3647    ///   - [`set_presence`] - To override the presence state sent with this
3648    ///     classic `/sync` request. If this is not set, the request uses the
3649    ///     client-owned sync presence configured with [`Client::set_presence`],
3650    ///     which defaults to [`PresenceState::Online`].
3651    ///
3652    /// # Examples
3653    ///
3654    /// ```no_run
3655    /// # use url::Url;
3656    /// # async {
3657    /// # let homeserver = Url::parse("http://localhost:8080")?;
3658    /// # let username = "";
3659    /// # let password = "";
3660    /// use matrix_sdk::{
3661    ///     Client, config::SyncSettings,
3662    ///     ruma::events::room::message::OriginalSyncRoomMessageEvent,
3663    /// };
3664    ///
3665    /// let client = Client::new(homeserver).await?;
3666    /// client.matrix_auth().login_username(username, password).send().await?;
3667    ///
3668    /// // Sync once so we receive the client state and old messages.
3669    /// client.sync_once(SyncSettings::default()).await?;
3670    ///
3671    /// // Register our handler so we start responding once we receive a new
3672    /// // event.
3673    /// client.add_event_handler(|ev: OriginalSyncRoomMessageEvent| async move {
3674    ///     println!("Received event {}: {:?}", ev.sender, ev.content);
3675    /// });
3676    ///
3677    /// // Now keep on syncing forever. `sync()` will use the stored sync token
3678    /// // from our `sync_once()` call automatically.
3679    /// client.sync(SyncSettings::default()).await;
3680    /// # anyhow::Ok(()) };
3681    /// ```
3682    ///
3683    /// [`sync`]: #method.sync
3684    /// [`SyncSettings`]: crate::config::SyncSettings
3685    /// [`token`]: crate::config::SyncSettings#method.token
3686    /// [`timeout`]: crate::config::SyncSettings#method.timeout
3687    /// [`full_state`]: crate::config::SyncSettings#method.full_state
3688    /// [`set_presence`]: crate::config::SyncSettings::set_presence
3689    /// [`filter`]: crate::config::SyncSettings#method.filter
3690    /// [`Filter`]: ruma::api::client::sync::sync_events::v3::Filter
3691    /// [`next_batch`]: SyncResponse#structfield.next_batch
3692    /// [`get_or_upload_filter()`]: #method.get_or_upload_filter
3693    /// [long polling]: #long-polling
3694    /// [filtered]: #filtering-events
3695    #[instrument(skip(self))]
3696    pub async fn sync_once(
3697        &self,
3698        sync_settings: crate::config::SyncSettings,
3699    ) -> Result<SyncResponse> {
3700        // The sync might not return for quite a while due to the timeout. We'll
3701        // see if there's anything crypto related to send out before we sync,
3702        // i.e. if we closed our client after a sync but before the crypto
3703        // requests were sent out.
3704        //
3705        // This will mostly be a no-op.
3706        #[cfg(feature = "e2e-encryption")]
3707        if let Err(e) = self.send_outgoing_requests().await {
3708            error!(error = ?e, "Error while sending outgoing E2EE requests");
3709        }
3710
3711        let token = match sync_settings.token {
3712            SyncToken::Specific(token) => Some(token),
3713            SyncToken::NoToken => None,
3714            SyncToken::ReusePrevious => self.sync_token().await,
3715        };
3716
3717        let request = assign!(sync_events::v3::Request::new(), {
3718            filter: sync_settings.filter.map(|f| *f),
3719            since: token,
3720            full_state: sync_settings.full_state,
3721            set_presence: sync_settings.set_presence.unwrap_or_else(|| self.sync_presence()),
3722            timeout: sync_settings.timeout,
3723            use_state_after: true,
3724        });
3725        let mut request_config = self.request_config();
3726        if let Some(timeout) = sync_settings.timeout {
3727            let base_timeout = request_config.timeout.unwrap_or(Duration::from_secs(30));
3728            request_config.timeout = Some(base_timeout + timeout);
3729        }
3730
3731        let response = self.send(request).with_request_config(request_config).await?;
3732        let next_batch = response.next_batch.clone();
3733        let response = self.process_sync(response).await?;
3734
3735        #[cfg(feature = "e2e-encryption")]
3736        if let Err(e) = self.send_outgoing_requests().await {
3737            error!(error = ?e, "Error while sending outgoing E2EE requests");
3738        }
3739
3740        self.inner.sync_beat.notify(usize::MAX);
3741
3742        Ok(SyncResponse::new(next_batch, response))
3743    }
3744
3745    /// Repeatedly synchronize the client state with the server.
3746    ///
3747    /// This method will only return on error, if cancellation is needed the
3748    /// method should be wrapped in a cancelable task or the
3749    /// [`Client::sync_with_callback`] method can be used or
3750    /// [`Client::sync_with_result_callback`] if you want to handle error cases
3751    /// in the loop, too.
3752    ///
3753    /// This method will internally call [`Client::sync_once`] in a loop.
3754    ///
3755    /// This method can be used with the [`Client::add_event_handler`] method to
3756    /// react to individual events. If you instead wish to handle events in a
3757    /// bulk manner the [`Client::sync_with_callback`],
3758    /// [`Client::sync_with_result_callback`] and [`Client::sync_stream`]
3759    /// methods can be used instead. Those methods repeatedly return the whole
3760    /// sync response.
3761    ///
3762    /// # Arguments
3763    ///
3764    /// - `sync_settings` - Settings for the sync call. _Note_ that those
3765    ///   settings will be only used for the first sync call. See the argument
3766    ///   docs for [`Client::sync_once`] for more info.
3767    ///
3768    /// # Return
3769    ///
3770    /// The sync runs until an error occurs, returning with `Err(Error)`. It is
3771    /// up to the user of the API to check the error and decide whether the sync
3772    /// should continue or not.
3773    ///
3774    /// # Examples
3775    ///
3776    /// ```no_run
3777    /// # use url::Url;
3778    /// # async {
3779    /// # let homeserver = Url::parse("http://localhost:8080")?;
3780    /// # let username = "";
3781    /// # let password = "";
3782    /// use matrix_sdk::{
3783    ///     Client, config::SyncSettings,
3784    ///     ruma::events::room::message::OriginalSyncRoomMessageEvent,
3785    /// };
3786    ///
3787    /// let client = Client::new(homeserver).await?;
3788    /// client.matrix_auth().login_username(&username, &password).send().await?;
3789    ///
3790    /// // Register our handler so we start responding once we receive a new
3791    /// // event.
3792    /// client.add_event_handler(|ev: OriginalSyncRoomMessageEvent| async move {
3793    ///     println!("Received event {}: {:?}", ev.sender, ev.content);
3794    /// });
3795    ///
3796    /// // Now keep on syncing forever. `sync()` will use the latest sync token
3797    /// // automatically.
3798    /// client.sync(SyncSettings::default()).await?;
3799    /// # anyhow::Ok(()) };
3800    /// ```
3801    ///
3802    /// [argument docs]: #method.sync_once
3803    /// [`sync_with_callback`]: #method.sync_with_callback
3804    pub async fn sync(&self, sync_settings: crate::config::SyncSettings) -> Result<(), Error> {
3805        self.sync_with_callback(sync_settings, |_| async { LoopCtrl::Continue }).await
3806    }
3807
3808    /// Repeatedly call sync to synchronize the client state with the server.
3809    ///
3810    /// # Arguments
3811    ///
3812    /// - `sync_settings` - Settings for the sync call. _Note_ that those
3813    ///   settings will be only used for the first sync call. See the argument
3814    ///   docs for [`Client::sync_once`] for more info.
3815    ///
3816    /// - `callback` - A callback that will be called every time a successful
3817    ///   response has been fetched from the server. The callback must return a
3818    ///   boolean which signalizes if the method should stop syncing. If the
3819    ///   callback returns `LoopCtrl::Continue` the sync will continue, if the
3820    ///   callback returns `LoopCtrl::Break` the sync will be stopped.
3821    ///
3822    /// # Return
3823    ///
3824    /// The sync runs until an error occurs or the callback indicates that the
3825    /// Loop should stop. If the callback asked for a regular stop, the result
3826    /// will be `Ok(())` otherwise the `Err(Error)` is returned.
3827    ///
3828    /// # Examples
3829    ///
3830    /// The following example demonstrates how to sync forever while sending all
3831    /// the interesting events through a mpsc channel to another thread e.g. a
3832    /// UI thread.
3833    ///
3834    /// ```no_run
3835    /// # use std::time::Duration;
3836    /// # use matrix_sdk::{Client, config::SyncSettings, LoopCtrl};
3837    /// # use url::Url;
3838    /// # async {
3839    /// # let homeserver = Url::parse("http://localhost:8080").unwrap();
3840    /// # let mut client = Client::new(homeserver).await.unwrap();
3841    ///
3842    /// use tokio::sync::mpsc::channel;
3843    ///
3844    /// let (tx, rx) = channel(100);
3845    ///
3846    /// let sync_channel = &tx;
3847    /// let sync_settings = SyncSettings::new()
3848    ///     .timeout(Duration::from_secs(30));
3849    ///
3850    /// client
3851    ///     .sync_with_callback(sync_settings, |response| async move {
3852    ///         let channel = sync_channel;
3853    ///         for (room_id, room) in response.rooms.joined {
3854    ///             for event in room.timeline.events {
3855    ///                 channel.send(event).await.unwrap();
3856    ///             }
3857    ///         }
3858    ///
3859    ///         LoopCtrl::Continue
3860    ///     })
3861    ///     .await;
3862    /// };
3863    /// ```
3864    #[instrument(skip_all)]
3865    pub async fn sync_with_callback<C>(
3866        &self,
3867        sync_settings: crate::config::SyncSettings,
3868        callback: impl Fn(SyncResponse) -> C,
3869    ) -> Result<(), Error>
3870    where
3871        C: Future<Output = LoopCtrl>,
3872    {
3873        self.sync_with_result_callback(sync_settings, |result| async {
3874            Ok(callback(result?).await)
3875        })
3876        .await
3877    }
3878
3879    /// Repeatedly call sync to synchronize the client state with the server.
3880    ///
3881    /// # Arguments
3882    ///
3883    /// - `sync_settings` - Settings for the sync call. _Note_ that those
3884    ///   settings will be only used for the first sync call. See the argument
3885    ///   docs for [`Client::sync_once`] for more info.
3886    ///
3887    /// - `callback` - A callback that will be called every time after a
3888    ///   response has been received, failure or not. The callback returns a
3889    ///   `Result<LoopCtrl, Error>`, too. When returning
3890    ///   `Ok(LoopCtrl::Continue)` the sync will continue, if the callback
3891    ///   returns `Ok(LoopCtrl::Break)` the sync will be stopped and the
3892    ///   function returns `Ok(())`. In case the callback can't handle the
3893    ///   `Error` or has a different malfunction, it can return an `Err(Error)`,
3894    ///   which results in the sync ending and the `Err(Error)` being returned.
3895    ///
3896    /// # Return
3897    ///
3898    /// The sync runs until an error occurs that the callback can't handle or
3899    /// the callback indicates that the Loop should stop. If the callback asked
3900    /// for a regular stop, the result will be `Ok(())` otherwise the
3901    /// `Err(Error)` is returned.
3902    ///
3903    /// _Note_: Lower-level configuration (e.g. for retries) are not changed by
3904    /// this, and are handled first without sending the result to the callback.
3905    /// Only after they have exceeded is the `Result` handed to the callback.
3906    ///
3907    /// # Examples
3908    ///
3909    /// The following example demonstrates how to sync forever while sending all
3910    /// the interesting events through a mpsc channel to another thread e.g. a
3911    /// UI thread.
3912    ///
3913    /// ```no_run
3914    /// # use std::time::Duration;
3915    /// # use matrix_sdk::{Client, config::SyncSettings, LoopCtrl};
3916    /// # use url::Url;
3917    /// # async {
3918    /// # let homeserver = Url::parse("http://localhost:8080").unwrap();
3919    /// # let mut client = Client::new(homeserver).await.unwrap();
3920    /// #
3921    /// use tokio::sync::mpsc::channel;
3922    ///
3923    /// let (tx, rx) = channel(100);
3924    ///
3925    /// let sync_channel = &tx;
3926    /// let sync_settings = SyncSettings::new()
3927    ///     .timeout(Duration::from_secs(30));
3928    ///
3929    /// client
3930    ///     .sync_with_result_callback(sync_settings, |response| async move {
3931    ///         let channel = sync_channel;
3932    ///         let sync_response = response?;
3933    ///         for (room_id, room) in sync_response.rooms.joined {
3934    ///              for event in room.timeline.events {
3935    ///                  channel.send(event).await.unwrap();
3936    ///               }
3937    ///         }
3938    ///
3939    ///         Ok(LoopCtrl::Continue)
3940    ///     })
3941    ///     .await;
3942    /// };
3943    /// ```
3944    #[instrument(skip(self, callback))]
3945    pub async fn sync_with_result_callback<C>(
3946        &self,
3947        sync_settings: crate::config::SyncSettings,
3948        callback: impl Fn(Result<SyncResponse, Error>) -> C,
3949    ) -> Result<(), Error>
3950    where
3951        C: Future<Output = Result<LoopCtrl, Error>>,
3952    {
3953        let mut sync_stream = Box::pin(self.sync_stream(sync_settings).await);
3954
3955        while let Some(result) = sync_stream.next().await {
3956            trace!("Running callback");
3957            if callback(result).await? == LoopCtrl::Break {
3958                trace!("Callback told us to stop");
3959                break;
3960            }
3961            trace!("Done running callback");
3962        }
3963
3964        Ok(())
3965    }
3966
3967    /// Repeatedly synchronize the client state with the server.
3968    /// This method will internally call [`Client::sync_once`] in a loop and is
3969    /// equivalent to the [`Client::sync`] method but the responses are provided
3970    /// as an async stream.
3971    ///
3972    /// # Arguments
3973    ///
3974    /// - `sync_settings` - Settings for the sync call. _Note_ that those
3975    ///   settings will be only used for the first sync call. See the argument
3976    ///   docs for [`Client::sync_once`] for more info.
3977    ///
3978    /// # Examples
3979    ///
3980    /// ```no_run
3981    /// # use url::Url;
3982    /// # async {
3983    /// # let homeserver = Url::parse("http://localhost:8080")?;
3984    /// # let username = "";
3985    /// # let password = "";
3986    /// use futures_util::StreamExt;
3987    /// use matrix_sdk::{Client, config::SyncSettings};
3988    ///
3989    /// let client = Client::new(homeserver).await?;
3990    /// client.matrix_auth().login_username(&username, &password).send().await?;
3991    ///
3992    /// let mut sync_stream =
3993    ///     Box::pin(client.sync_stream(SyncSettings::default()).await);
3994    ///
3995    /// while let Some(Ok(response)) = sync_stream.next().await {
3996    ///     for room in response.rooms.joined.values() {
3997    ///         for e in &room.timeline.events {
3998    ///             if let Ok(event) = e.raw().deserialize() {
3999    ///                 println!("Received event {:?}", event);
4000    ///             }
4001    ///         }
4002    ///     }
4003    /// }
4004    ///
4005    /// # anyhow::Ok(()) };
4006    /// ```
4007    #[allow(unknown_lints, clippy::let_with_type_underscore)] // triggered by instrument macro
4008    #[instrument(skip(self))]
4009    pub async fn sync_stream(
4010        &self,
4011        mut sync_settings: crate::config::SyncSettings,
4012    ) -> impl Stream<Item = Result<SyncResponse>> + '_ {
4013        let mut is_first_sync = true;
4014        let mut timeout = None;
4015        let mut last_sync_time: Option<Instant> = None;
4016
4017        let parent_span = Span::current();
4018
4019        async_stream::stream!({
4020            loop {
4021                trace!("Syncing");
4022
4023                if sync_settings.ignore_timeout_on_first_sync {
4024                    if is_first_sync {
4025                        timeout = sync_settings.timeout.take();
4026                    } else if sync_settings.timeout.is_none() && timeout.is_some() {
4027                        sync_settings.timeout = timeout.take();
4028                    }
4029
4030                    is_first_sync = false;
4031                }
4032
4033                yield self
4034                    .sync_loop_helper(&mut sync_settings)
4035                    .instrument(parent_span.clone())
4036                    .await;
4037
4038                if sync_settings.throttle_sync_loop {
4039                    Client::delay_sync(&mut last_sync_time).await
4040                }
4041            }
4042        })
4043    }
4044
4045    /// Get the current, if any, sync token of the client. This will be None if
4046    /// the client didn't sync at least once.
4047    pub(crate) async fn sync_token(&self) -> Option<String> {
4048        self.inner.base_client.sync_token().await
4049    }
4050
4051    /// Wait until the next sync has been processed by the [`Client`].
4052    ///
4053    /// This will block until the [`Client`] has processed a sync response. This
4054    /// works both for the sync v2 and the simplified sliding sync.
4055    ///
4056    /// Note this isn't concerned whether the sync was done by a specific
4057    /// high-level sync service (like the encryption service or the sliding
4058    /// sync service), but about low-level sync connections: for such
4059    /// services, it will wait until *any* sync has completed.
4060    pub async fn wait_for_sync(&self) {
4061        self.inner.sync_beat.listen().await;
4062    }
4063
4064    /// Gets information about the owner of a given access token.
4065    pub async fn whoami(&self) -> HttpResult<whoami::v3::Response> {
4066        let request = whoami::v3::Request::new();
4067        self.send(request).await
4068    }
4069
4070    /// Subscribes a new receiver to client SessionChange broadcasts.
4071    pub fn subscribe_to_session_changes(&self) -> broadcast::Receiver<SessionChange> {
4072        let broadcast = &self.auth_ctx().session_change_sender;
4073        broadcast.subscribe()
4074    }
4075
4076    /// Sets the save/restore session callbacks.
4077    ///
4078    /// This is another mechanism to get synchronous updates to session tokens,
4079    /// while [`Self::subscribe_to_session_changes`] provides an async update.
4080    pub fn set_session_callbacks(
4081        &self,
4082        reload_session_callback: Box<ReloadSessionCallback>,
4083        save_session_callback: Box<SaveSessionCallback>,
4084    ) -> Result<()> {
4085        self.inner
4086            .auth_ctx
4087            .reload_session_callback
4088            .set(reload_session_callback)
4089            .map_err(|_| Error::MultipleSessionCallbacks)?;
4090
4091        self.inner
4092            .auth_ctx
4093            .save_session_callback
4094            .set(save_session_callback)
4095            .map_err(|_| Error::MultipleSessionCallbacks)?;
4096
4097        Ok(())
4098    }
4099
4100    /// Get the notification settings of the current owner of the client.
4101    pub async fn notification_settings(&self) -> NotificationSettings {
4102        let ruleset = self.account().push_rules().await.unwrap_or_else(|_| Ruleset::new());
4103        NotificationSettings::new(self.clone(), ruleset)
4104    }
4105
4106    /// Create a new specialized `Client` that can process notifications.
4107    ///
4108    /// See [`CrossProcessLock::new`] to learn more about
4109    /// `cross_process_lock_config`.
4110    ///
4111    /// [`CrossProcessLock::new`]: matrix_sdk_common::cross_process_lock::CrossProcessLock::new
4112    pub async fn notification_client(
4113        &self,
4114        cross_process_lock_config: CrossProcessLockConfig,
4115    ) -> Result<Client> {
4116        let client = Client {
4117            inner: ClientInner::new(
4118                self.inner.auth_ctx.clone(),
4119                self.server(),
4120                self.homeserver(),
4121                self.sliding_sync_version(),
4122                self.inner.sync_presence.clone(),
4123                self.inner.http_client.clone(),
4124                self.inner
4125                    .base_client
4126                    .clone_with_in_memory_state_store(cross_process_lock_config.clone(), false)
4127                    .await?,
4128                self.inner.caches.supported_versions.value(),
4129                self.inner.caches.well_known.value(),
4130                self.inner.caches.retention_configuration.get(),
4131                self.inner.respect_login_well_known,
4132                self.well_known_lookup_disabled(),
4133                false,
4134                // We don't need the `EventCache` in a notification client.
4135                false,
4136                self.inner.send_queue_data.clone(),
4137                #[cfg(feature = "e2e-encryption")]
4138                self.inner.e2ee.encryption_settings,
4139                #[cfg(feature = "e2e-encryption")]
4140                self.inner.enable_share_history_on_invite,
4141                cross_process_lock_config,
4142                #[cfg(feature = "experimental-search")]
4143                self.inner.search_index.clone(),
4144                self.inner.thread_subscription_catchup.clone(),
4145                (*self.inner.media_fetcher.read().await).clone(),
4146            )
4147            .await,
4148        };
4149
4150        Ok(client)
4151    }
4152
4153    /// The [`EventCache`] instance for this [`Client`].
4154    pub fn event_cache(&self) -> Option<&EventCache> {
4155        self.inner.event_cache.get()
4156    }
4157
4158    /// The [`LatestEvents`] instance for this [`Client`], if the [`EventCache`]
4159    /// is enabled.
4160    pub async fn latest_events(&self) -> Option<&LatestEvents> {
4161        if let Some(event_cache) = self.event_cache() {
4162            Some(
4163                self.inner
4164                    .latest_events
4165                    .get_or_init(|| async {
4166                        LatestEvents::new(
4167                            self.downgrade(),
4168                            event_cache.clone(),
4169                            SendQueue::new(self.clone()),
4170                            self.room_info_notable_update_receiver(),
4171                        )
4172                    })
4173                    .await,
4174            )
4175        } else {
4176            None
4177        }
4178    }
4179
4180    /// Waits until an at least partially synced room is received, and returns
4181    /// it.
4182    ///
4183    /// **Note: this function will loop endlessly until either it finds the room
4184    /// or an externally set timeout happens.**
4185    pub async fn await_room_remote_echo(&self, room_id: &RoomId) -> Room {
4186        loop {
4187            if let Some(room) = self.get_room(room_id) {
4188                if room.is_state_partially_or_fully_synced() {
4189                    debug!("Found just created room!");
4190                    return room;
4191                }
4192                debug!("Room wasn't partially synced, waiting for sync beat to try again");
4193            } else {
4194                debug!("Room wasn't found, waiting for sync beat to try again");
4195            }
4196            self.inner.sync_beat.listen().await;
4197        }
4198    }
4199
4200    /// Knock on a room given its `room_id_or_alias` to ask for permission to
4201    /// join it.
4202    pub async fn knock(
4203        &self,
4204        room_id_or_alias: OwnedRoomOrAliasId,
4205        reason: Option<String>,
4206        server_names: Vec<OwnedServerName>,
4207    ) -> Result<Room> {
4208        let request =
4209            assign!(knock_room::v3::Request::new(room_id_or_alias), { reason, via: server_names });
4210        let response = self.send(request).await?;
4211        let base_room = self.inner.base_client.room_knocked(&response.room_id).await?;
4212        Ok(Room::new(self.clone(), base_room))
4213    }
4214
4215    /// Checks whether the provided `user_id` belongs to an ignored user.
4216    pub async fn is_user_ignored(&self, user_id: &UserId) -> bool {
4217        self.base_client().is_user_ignored(user_id).await
4218    }
4219
4220    /// Reports a user to the homeserver admins.
4221    ///
4222    /// # Arguments
4223    ///
4224    /// - `user_id` - The ID of the user being reported.
4225    /// - `reason` - The reason for the user being reported (can be blank).
4226    ///
4227    /// # Errors
4228    ///
4229    /// Returns an error if the user is not found.
4230    pub async fn report_user(
4231        &self,
4232        user_id: &UserId,
4233        reason: String,
4234    ) -> Result<report_user::v3::Response> {
4235        let request = report_user::v3::Request::new(user_id.to_owned(), reason);
4236        Ok(self.send(request).await?)
4237    }
4238
4239    /// Gets the `max_upload_size` value from the homeserver, getting either a
4240    /// cached value or with a `/_matrix/client/v1/media/config` request if it's
4241    /// missing.
4242    ///
4243    /// Check [the specification for more info][spec].
4244    ///
4245    /// [spec]: https://spec.matrix.org/v1.14/client-server-api/#get_matrixclientv1mediaconfig
4246    pub async fn load_or_fetch_max_upload_size(&self) -> Result<UInt> {
4247        let max_upload_size_lock = self.inner.server_max_upload_size.lock().await;
4248        if let Some(data) = max_upload_size_lock.get() {
4249            return Ok(data.to_owned());
4250        }
4251
4252        // Use the authenticated endpoint when the server supports it.
4253        let supported_versions = self.supported_versions().await?;
4254        let use_auth = authenticated_media::get_media_config::v1::Request::PATH_BUILDER
4255            .is_supported(&supported_versions);
4256
4257        let upload_size = if use_auth {
4258            self.send(authenticated_media::get_media_config::v1::Request::default())
4259                .await?
4260                .upload_size
4261        } else {
4262            #[allow(deprecated)]
4263            self.send(media::get_media_config::v3::Request::default()).await?.upload_size
4264        };
4265
4266        let Some(upload_size) = upload_size else {
4267            return Err(Error::Media(MediaError::FetchMaxUploadSizeFailed(
4268                "the homeserver does not advertise `m.upload.size`".to_owned(),
4269            )));
4270        };
4271
4272        match max_upload_size_lock.set(upload_size) {
4273            Ok(_) => Ok(upload_size),
4274            Err(error) => {
4275                Err(Error::Media(MediaError::FetchMaxUploadSizeFailed(error.to_string())))
4276            }
4277        }
4278    }
4279
4280    /// The settings to use for decrypting events.
4281    #[cfg(feature = "e2e-encryption")]
4282    pub fn decryption_settings(&self) -> &DecryptionSettings {
4283        &self.base_client().decryption_settings
4284    }
4285
4286    /// Returns the [`SearchIndex`] for this [`Client`].
4287    #[cfg(feature = "experimental-search")]
4288    pub fn search_index(&self) -> &SearchIndex {
4289        &self.inner.search_index
4290    }
4291
4292    /// Whether the client is configured to take thread subscriptions (MSC4306
4293    /// and MSC4308) into account, and the server enabled the experimental
4294    /// feature flag for it.
4295    ///
4296    /// This may cause filtering out of thread subscriptions, and loading the
4297    /// thread subscriptions via the sliding sync extension, when the room list
4298    /// service is being used.
4299    ///
4300    /// This is async and fallible as it may use the network to retrieve the
4301    /// server supported features, if they aren't cached already.
4302    pub async fn enabled_thread_subscriptions(&self) -> Result<bool> {
4303        // Check if the client is configured to support thread subscriptions
4304        // first.
4305        match self.base_client().threading_support {
4306            ThreadingSupport::Enabled { with_subscriptions: false }
4307            | ThreadingSupport::Disabled => return Ok(false),
4308            ThreadingSupport::Enabled { with_subscriptions: true } => {}
4309        }
4310
4311        // Now, let's check that the server supports it.
4312        let server_enabled = self
4313            .supported_versions()
4314            .await?
4315            .features
4316            .contains(&FeatureFlag::from("org.matrix.msc4306"));
4317
4318        Ok(server_enabled)
4319    }
4320
4321    /// Whether global user profiles are included in the sync response.
4322    ///
4323    /// Requires
4324    /// [MSC4262](https://github.com/matrix-org/matrix-spec-proposals/pull/4262)
4325    /// for sliding sync. Not implemented for sync v2.
4326    pub async fn is_global_profile_sync_enabled(&self) -> Result<bool> {
4327        if matches!(self.sliding_sync_version(), SlidingSyncVersion::None) {
4328            return Ok(false);
4329        }
4330
4331        Ok(self
4332            .supported_versions()
4333            .await?
4334            .features
4335            .contains(&FeatureFlag::from("org.matrix.msc4262")))
4336    }
4337
4338    /// Fetch thread subscriptions changes between `from` and up to `to`.
4339    ///
4340    /// The `limit` optional parameter can be used to limit the number of
4341    /// entries in a response. It can also be overridden by the server, if it's
4342    /// deemed too large.
4343    pub async fn fetch_thread_subscriptions(
4344        &self,
4345        from: Option<String>,
4346        to: Option<String>,
4347        limit: Option<UInt>,
4348    ) -> Result<get_thread_subscriptions_changes::msc4308::Response> {
4349        let request = assign!(get_thread_subscriptions_changes::msc4308::Request::new(), {
4350            from,
4351            to,
4352            limit,
4353        });
4354        Ok(self.send(request).await?)
4355    }
4356
4357    pub(crate) fn thread_subscription_catchup(&self) -> &ThreadSubscriptionCatchup {
4358        self.inner.thread_subscription_catchup.get().unwrap()
4359    }
4360
4361    #[cfg(feature = "unstable-msc4536")]
4362    pub(crate) fn global_profile_fetcher(&self) -> &GlobalProfileFetcher {
4363        self.inner.global_profile_fetcher.get_or_init(|| GlobalProfileFetcher::new(self))
4364    }
4365
4366    /// Pause the client for background suspension.
4367    ///
4368    /// This method:
4369    ///
4370    /// 1. Disables all send queues (prevents new message sends).
4371    /// 2. Pauses all database stores, waiting for in-flight operations and
4372    ///    releasing all connections and file locks.
4373    ///
4374    /// Call [`Client::resume()`] when the app returns to the foreground.
4375    ///
4376    /// # iOS
4377    ///
4378    /// Call this before the app is suspended to avoid `0xdead10cc` kills.
4379    /// Typically called from
4380    /// [`applicationDidEnterBackground`](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/applicationdidenterbackground(_:))
4381    /// or an equivalent SwiftUI lifecycle event, _after_ stopping the
4382    /// `matrix_sdk_ui::sync_service::SyncService`.
4383    pub async fn pause(&self) -> Result<()> {
4384        info!("Client::pause — releasing database resources");
4385
4386        // Disable send queues so no new sends hit the stores.
4387        self.send_queue().set_enabled(false).await;
4388
4389        // Close all stores (waits for in-flight ops, closes connections).
4390        self.base_client().close_stores().await?;
4391
4392        info!("Client::pause — complete, all database connections released");
4393        Ok(())
4394    }
4395
4396    /// Resume the client after a [`Client::pause()`].
4397    ///
4398    /// Re-acquires store resources and re-enables send queues.
4399    ///
4400    /// If your app stopped the `matrix_sdk_ui::sync_service::SyncService`
4401    /// before pausing, restart it separately as appropriate for your app
4402    /// lifecycle.
4403    pub async fn resume(&self) -> Result<()> {
4404        info!("Client::resume — re-acquiring database resources");
4405
4406        // Reopen stores (creates new connection pools).
4407        self.base_client().reopen_stores().await?;
4408
4409        // Re-enable send queues.
4410        self.send_queue().set_enabled(true).await;
4411
4412        info!("Client::resume — complete");
4413        Ok(())
4414    }
4415
4416    /// Perform database optimizations if any are available, i.e. vacuuming in
4417    /// SQLite.
4418    ///
4419    /// **Warning:** this was added to check if SQLite fragmentation was the
4420    /// source of performance issues, **DO NOT use in production**.
4421    #[doc(hidden)]
4422    pub async fn optimize_stores(&self) -> Result<()> {
4423        trace!("Optimizing state store...");
4424        self.state_store().optimize().await?;
4425
4426        trace!("Optimizing event cache store...");
4427        if let Some(clean_lock) = self.event_cache_store().lock().await?.as_clean() {
4428            clean_lock.optimize().await?;
4429        }
4430
4431        trace!("Optimizing media store...");
4432        self.media_store().lock().await?.optimize().await?;
4433
4434        Ok(())
4435    }
4436
4437    /// Returns the sizes of the existing stores, if known.
4438    pub async fn get_store_sizes(&self) -> Result<StoreSizes> {
4439        #[cfg(feature = "e2e-encryption")]
4440        let crypto_store_size = if let Some(olm_machine) = self.olm_machine().await.as_ref()
4441            && let Ok(Some(store_size)) = olm_machine.store().get_size().await
4442        {
4443            Some(store_size)
4444        } else {
4445            None
4446        };
4447        #[cfg(not(feature = "e2e-encryption"))]
4448        let crypto_store_size = None;
4449
4450        let state_store_size = self.state_store().get_size().await.ok().flatten();
4451
4452        let event_cache_store_size = if let Some(clean_lock) =
4453            self.event_cache_store().lock().await?.as_clean()
4454            && let Ok(Some(store_size)) = clean_lock.get_size().await
4455        {
4456            Some(store_size)
4457        } else {
4458            None
4459        };
4460
4461        let media_store_size = self.media_store().lock().await?.get_size().await.ok().flatten();
4462
4463        #[cfg(feature = "experimental-search")]
4464        let search_index_size = self.search_index().size();
4465        #[cfg(not(feature = "experimental-search"))]
4466        let search_index_size = None;
4467
4468        Ok(StoreSizes {
4469            crypto_store: crypto_store_size,
4470            state_store: state_store_size,
4471            event_cache_store: event_cache_store_size,
4472            media_store: media_store_size,
4473            search_index: search_index_size,
4474        })
4475    }
4476
4477    /// Get a reference to the client's task monitor, for spawning background
4478    /// tasks.
4479    pub fn task_monitor(&self) -> &TaskMonitor {
4480        &self.inner.task_monitor
4481    }
4482
4483    /// Add a subscriber for duplicate key upload error notifications triggered
4484    /// by requests to /keys/upload.
4485    #[cfg(feature = "e2e-encryption")]
4486    pub fn subscribe_to_duplicate_key_upload_errors(
4487        &self,
4488    ) -> broadcast::Receiver<Option<DuplicateOneTimeKeyErrorMessage>> {
4489        self.inner.duplicate_key_upload_error_sender.subscribe()
4490    }
4491
4492    /// Check the record of whether we are waiting for an [MSC4268] key bundle
4493    /// for the given room.
4494    ///
4495    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
4496    #[cfg(feature = "e2e-encryption")]
4497    pub async fn get_pending_key_bundle_details_for_room(
4498        &self,
4499        room_id: &RoomId,
4500    ) -> Result<Option<RoomPendingKeyBundleDetails>> {
4501        Ok(self.base_client().get_pending_key_bundle_details_for_room(room_id).await?)
4502    }
4503
4504    /// Returns the [`DmRoomDefinition`] this client uses to check if a room is
4505    /// a DM.
4506    pub fn dm_room_definition(&self) -> &DmRoomDefinition {
4507        &self.inner.base_client.dm_room_definition
4508    }
4509
4510    /// Replaces the [`MediaFetcher`] used to download media from the media
4511    /// server with the provided one.
4512    pub async fn set_media_fetcher(&self, media_fetcher: Arc<dyn MediaFetcher>) {
4513        *self.inner.media_fetcher.write().await = media_fetcher;
4514    }
4515
4516    /// Returns the currently used [`MediaFetcher`] used to download media from
4517    /// the media server.
4518    pub async fn get_media_fetcher(&self) -> Arc<dyn MediaFetcher> {
4519        self.inner.media_fetcher.read().await.clone()
4520    }
4521}
4522
4523/// Contains the disk size of the different stores, if known. It won't be
4524/// available for in-memory stores.
4525#[derive(Debug, Clone)]
4526pub struct StoreSizes {
4527    /// The size of the CryptoStore.
4528    pub crypto_store: Option<usize>,
4529    /// The size of the StateStore.
4530    pub state_store: Option<usize>,
4531    /// The size of the EventCacheStore.
4532    pub event_cache_store: Option<usize>,
4533    /// The size of the MediaStore.
4534    pub media_store: Option<usize>,
4535    /// The size of the search index.
4536    pub search_index: Option<usize>,
4537}
4538
4539/// A custom to-device message received by the client.
4540///
4541/// Yielded by [`Client::subscribe_to_custom_to_device_messages`].
4542#[derive(Debug, Clone)]
4543pub struct ToDeviceMessage {
4544    /// The event as it was received, decrypted if it was sent encrypted.
4545    pub raw: Raw<AnyToDeviceEvent>,
4546
4547    /// The encryption data of this message, if it was sent encrypted, or `None`
4548    /// if it arrived in the clear.
4549    ///
4550    /// When present, its `sender` is the cryptographically attested sender of
4551    /// the message, and should be trusted over the `sender` field of the event.
4552    pub encryption_info: Option<EncryptionInfo>,
4553}
4554
4555/// Whether a to-device event type is used by the SDK for its own crypto
4556/// machinery, and must therefore not be exposed to, or sent on behalf of,
4557/// consumers of custom to-device messages.
4558///
4559/// `m.room.encrypted` is included because a to-device message that could not be
4560/// decrypted keeps that type.
4561pub(crate) fn is_internal_to_device_type(event_type: &ToDeviceEventType) -> bool {
4562    matches!(
4563        event_type.to_string().as_str(),
4564        "m.dummy"
4565            | "m.room_key"
4566            | "m.room_key_request"
4567            | "m.forwarded_room_key"
4568            | "m.key.verification.request"
4569            | "m.key.verification.ready"
4570            | "m.key.verification.start"
4571            | "m.key.verification.cancel"
4572            | "m.key.verification.accept"
4573            | "m.key.verification.key"
4574            | "m.key.verification.mac"
4575            | "m.key.verification.done"
4576            | "m.secret.request"
4577            | "m.secret.send"
4578            | "m.room.encrypted"
4579    )
4580}
4581
4582#[cfg(any(feature = "testing", test))]
4583impl Client {
4584    /// Test helper to mark users as tracked by the crypto layer.
4585    #[cfg(feature = "e2e-encryption")]
4586    pub async fn update_tracked_users_for_testing(
4587        &self,
4588        user_ids: impl IntoIterator<Item = &UserId>,
4589    ) {
4590        let olm = self.olm_machine().await;
4591        let olm = olm.as_ref().unwrap();
4592        olm.update_tracked_users(user_ids).await.unwrap();
4593    }
4594}
4595
4596/// A weak reference to the inner [`Client`], useful when trying to get a handle
4597/// on the owning client.
4598///
4599/// This is intended for use in background tasks that require a [`Client`], as
4600/// otherwise killing all the [`Client`] instances wouldn't be sufficient to
4601/// drop the underlying inner client, and resume in a memory leak at best, and
4602/// confusing background syncs for a supposedly dead client at worst.
4603#[derive(Clone, Debug)]
4604pub struct WeakClient {
4605    client: Weak<ClientInner>,
4606}
4607
4608impl WeakClient {
4609    /// Construct a [`WeakClient`] from a `Arc<ClientInner>`.
4610    pub(crate) fn from_inner(client: &Arc<ClientInner>) -> Self {
4611        Self { client: Arc::downgrade(client) }
4612    }
4613
4614    /// Attempts to get a [`Client`] from this [`WeakClient`].
4615    pub fn get(&self) -> Option<Client> {
4616        self.client.upgrade().map(|inner| Client { inner })
4617    }
4618
4619    /// Gets the number of strong (`Arc`) pointers still pointing to this
4620    /// client.
4621    pub fn strong_count(&self) -> usize {
4622        self.client.strong_count()
4623    }
4624}
4625
4626/// Information about the state of a room before we joined it.
4627#[derive(Debug, Clone, Default)]
4628struct PreJoinRoomInfo {
4629    /// The user who invited us to the room, if any.
4630    pub inviter: Option<RoomMember>,
4631}
4632
4633// The http mocking library is not supported for wasm32
4634#[cfg(all(test, not(target_family = "wasm")))]
4635pub(crate) mod tests {
4636    use std::{
4637        collections::BTreeMap,
4638        pin::pin,
4639        sync::{
4640            Arc,
4641            atomic::{AtomicU32, Ordering},
4642        },
4643        time::Duration,
4644    };
4645
4646    use assert_matches::assert_matches;
4647    use eyeball::SharedObservable;
4648    use futures_util::{FutureExt, StreamExt};
4649    use js_int::{UInt, uint};
4650    use matrix_sdk_base::{
4651        RoomInfoNotableUpdateReasons, RoomState,
4652        read_receipts::ReadReceipts,
4653        store::{MemoryStore, StoreConfig},
4654        ttl::TtlValue,
4655    };
4656    use matrix_sdk_test::{
4657        JoinedRoomBuilder, SyncResponseBuilder, TestRoom, User, async_test,
4658        event_factory::EventFactory,
4659    };
4660    use strass::assert_let;
4661    #[cfg(target_family = "wasm")]
4662    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
4663
4664    use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
4665    use ruma::{
4666        RoomId, ServerName, UserId,
4667        api::{
4668            FeatureFlag, MatrixVersion,
4669            client::{
4670                retention::{
4671                    RoomIdOrAllRooms, get_retention_configuration::msc1763::RetentionLimits,
4672                },
4673                room::create_room::v3::Request as CreateRoomRequest,
4674                rtc::{LiveKitRtcTransport, RtcTransport},
4675            },
4676        },
4677        assign,
4678        events::{
4679            ignored_user_list::IgnoredUserListEventContent,
4680            invite_permission_config::{
4681                InvitePermissionAction, InvitePermissionConfigEventContent,
4682            },
4683            media_preview_config::{InviteAvatars, MediaPreviewConfigEventContent, MediaPreviews},
4684            room::retention::RoomRetentionEventContent,
4685        },
4686        owned_device_id,
4687        presence::PresenceState,
4688        room_alias_id, user_id,
4689    };
4690    use serde_json::json;
4691    use stream_assert::{assert_next_matches, assert_pending};
4692    use tokio::{
4693        spawn,
4694        time::{sleep, timeout},
4695    };
4696    use url::Url;
4697
4698    use super::Client;
4699    use crate::{
4700        Error, Result, TransmissionProgress, assert_next_eq_with_timeout,
4701        client::{caches::CachedValue, futures::SendMediaUploadRequest},
4702        config::{RequestConfig, SyncSettings},
4703        futures::SendRequest,
4704        media::MediaError,
4705        test_utils::{client::MockClientBuilder, mocks::MatrixMockServer},
4706    };
4707
4708    #[async_test]
4709    async fn test_sync_presence_is_shared_by_client_clones_and_notification_child() {
4710        let client = MockClientBuilder::new(None).build().await;
4711        let clone = client.clone();
4712        let notification_client =
4713            client.notification_client(CrossProcessLockConfig::SingleProcess).await.unwrap();
4714
4715        assert_eq!(client.sync_presence(), PresenceState::Online);
4716        assert_eq!(clone.sync_presence(), PresenceState::Online);
4717        assert_eq!(notification_client.sync_presence(), PresenceState::Online);
4718
4719        client
4720            .set_presence(PresenceState::Unavailable, None, false)
4721            .await
4722            .expect("presence should update");
4723
4724        assert_eq!(client.sync_presence(), PresenceState::Unavailable);
4725        assert_eq!(clone.sync_presence(), PresenceState::Unavailable);
4726        assert_eq!(notification_client.sync_presence(), PresenceState::Unavailable);
4727
4728        notification_client
4729            .set_presence(PresenceState::Offline, None, false)
4730            .await
4731            .expect("presence should update");
4732
4733        assert_eq!(client.sync_presence(), PresenceState::Offline);
4734        assert_eq!(clone.sync_presence(), PresenceState::Offline);
4735        assert_eq!(notification_client.sync_presence(), PresenceState::Offline);
4736    }
4737
4738    // Without the `e2e-encryption` feature, the notification client has no
4739    // session and can't sync.
4740    #[cfg(feature = "e2e-encryption")]
4741    #[async_test]
4742    async fn test_disabled_event_cache_is_inherited_by_notification_client() {
4743        let server = MatrixMockServer::new().await;
4744        let client = server
4745            .client_builder()
4746            .on_builder(|builder| builder.with_event_cache(false))
4747            .build()
4748            .await;
4749        let notification_client =
4750            client.notification_client(CrossProcessLockConfig::SingleProcess).await.unwrap();
4751        assert!(client.event_cache().is_none());
4752        assert!(notification_client.event_cache().is_none());
4753    }
4754
4755    #[async_test]
4756    async fn test_sync_once_uses_client_sync_presence_unless_overridden() {
4757        let server = MatrixMockServer::new().await;
4758        let client = server.client_builder().build().await;
4759
4760        {
4761            let _sync_guard = server
4762                .mock_sync()
4763                .set_presence_missing()
4764                .ok(|_| {})
4765                .expect(1)
4766                .mount_as_scoped()
4767                .await;
4768
4769            client.sync_once(SyncSettings::new()).await.expect("sync should succeed");
4770        }
4771
4772        client
4773            .set_presence(PresenceState::Offline, None, false)
4774            .await
4775            .expect("presence should update");
4776
4777        {
4778            let _sync_guard = server
4779                .mock_sync()
4780                .set_presence("offline")
4781                .ok(|_| {})
4782                .expect(1)
4783                .mount_as_scoped()
4784                .await;
4785
4786            client.sync_once(SyncSettings::new()).await.expect("sync should succeed");
4787        }
4788
4789        {
4790            let _sync_guard = server
4791                .mock_sync()
4792                .set_presence("unavailable")
4793                .ok(|_| {})
4794                .expect(1)
4795                .mount_as_scoped()
4796                .await;
4797
4798            client
4799                .sync_once(SyncSettings::new().set_presence(PresenceState::Unavailable))
4800                .await
4801                .expect("sync should succeed");
4802        }
4803    }
4804
4805    #[async_test]
4806    async fn test_set_presence_sends_presence_status_update() {
4807        let server = MatrixMockServer::new().await;
4808        let client = server.client_builder().build().await;
4809
4810        let state = PresenceState::Online;
4811        let status_msg = "Here".to_owned();
4812
4813        server.mock_update_presence(&state, Some(&status_msg)).ok().expect(1).mount().await;
4814
4815        client
4816            .set_presence(state.clone(), Some(status_msg), true)
4817            .await
4818            .expect("presence update should succeed");
4819
4820        assert_eq!(client.sync_presence(), state);
4821    }
4822
4823    #[async_test]
4824    async fn test_set_presence_requires_authentication() {
4825        let client = MockClientBuilder::new(None).unlogged().build().await;
4826
4827        assert_matches!(
4828            client.set_presence(PresenceState::Unavailable, None, true).await,
4829            Err(Error::AuthenticationRequired)
4830        );
4831    }
4832
4833    #[async_test]
4834    async fn test_set_presence_without_immediate_does_not_require_authentication() {
4835        let client = MockClientBuilder::new(None).unlogged().build().await;
4836
4837        client
4838            .set_presence(PresenceState::Offline, None, false)
4839            .await
4840            .expect("presence should update");
4841
4842        assert_eq!(client.sync_presence(), PresenceState::Offline);
4843    }
4844
4845    #[async_test]
4846    async fn test_fetch_presence_returns_the_users_presence() {
4847        let server = MatrixMockServer::new().await;
4848        let client = server.client_builder().build().await;
4849        let alice = user_id!("@alice:example.org");
4850
4851        server.mock_get_presence(alice).ok(&PresenceState::Unavailable).expect(1).mount().await;
4852
4853        let response = client.fetch_presence(alice).await.expect("presence lookup should succeed");
4854
4855        assert_eq!(response.presence, PresenceState::Unavailable);
4856    }
4857
4858    #[async_test]
4859    async fn test_account_data() {
4860        let server = MatrixMockServer::new().await;
4861        let client = server.client_builder().build().await;
4862
4863        let f = EventFactory::new();
4864        server
4865            .mock_sync()
4866            .ok_and_run(&client, |builder| {
4867                builder.add_global_account_data(f.ignored_user_list([User::Bob.into()]));
4868            })
4869            .await;
4870
4871        let content = client
4872            .account()
4873            .account_data::<IgnoredUserListEventContent>()
4874            .await
4875            .unwrap()
4876            .unwrap()
4877            .deserialize()
4878            .unwrap();
4879
4880        assert_eq!(content.ignored_users.len(), 1);
4881    }
4882
4883    #[async_test]
4884    async fn test_successful_discovery() {
4885        // Imagine this is `matrix.org`.
4886        let server = MatrixMockServer::new().await;
4887        let server_url = server.uri();
4888
4889        // Imagine this is `matrix-client.matrix.org`.
4890        let homeserver = MatrixMockServer::new().await;
4891        let homeserver_url = homeserver.uri();
4892
4893        // Imagine Alice has the user ID `@alice:matrix.org`.
4894        let domain = server_url.strip_prefix("http://").unwrap();
4895        let alice = UserId::parse("@alice:".to_owned() + domain).unwrap();
4896
4897        // The `.well-known` is on the server (e.g. `matrix.org`).
4898        server
4899            .mock_well_known()
4900            .ok_with_homeserver_url(&homeserver_url)
4901            .mock_once()
4902            .named("well-known")
4903            .mount()
4904            .await;
4905
4906        // The `/versions` is on the homeserver (e.g.
4907        // `matrix-client.matrix.org`).
4908        homeserver.mock_versions().ok().mock_once().named("versions").mount().await;
4909
4910        let client = Client::builder()
4911            .insecure_server_name_no_tls(alice.server_name())
4912            .build()
4913            .await
4914            .unwrap();
4915
4916        assert_eq!(client.server().unwrap(), Url::parse(&server_url).unwrap());
4917        assert_eq!(client.homeserver(), Url::parse(&homeserver_url).unwrap());
4918        client.server_versions().await.unwrap();
4919    }
4920
4921    #[async_test]
4922    async fn test_homeserver_swap_resets_server_field() {
4923        let homeserver = MatrixMockServer::new().await;
4924        let homeserver_url = homeserver.uri();
4925
4926        let domain = homeserver_url.strip_prefix("http://").unwrap();
4927        let alice = UserId::parse("@alice:".to_owned() + domain).unwrap();
4928
4929        homeserver.mock_well_known().ok().mock_once().named("well-known").mount().await;
4930
4931        let client = Client::builder()
4932            .insecure_server_name_no_tls(alice.server_name())
4933            .build()
4934            .await
4935            .unwrap();
4936
4937        assert_eq!(client.server().unwrap(), Url::parse(&homeserver_url).unwrap());
4938        assert_eq!(client.homeserver(), Url::parse(&homeserver_url).unwrap());
4939
4940        let new_server = Url::parse("http://example.org").unwrap();
4941        // Since we're explicitly setting the server to something else, like we
4942        // might do during QR code login...
4943        client.set_homeserver(new_server.clone());
4944
4945        // The new URL should be set in the homeserver field.
4946        assert_eq!(client.homeserver(), new_server);
4947        // But the server field should be set to empty, since we didn't do any
4948        // discovery now.
4949        assert!(client.server().is_none())
4950    }
4951
4952    #[async_test]
4953    async fn test_discovery_broken_server() {
4954        let server = MatrixMockServer::new().await;
4955        let server_url = server.uri();
4956        let domain = server_url.strip_prefix("http://").unwrap();
4957        let alice = UserId::parse("@alice:".to_owned() + domain).unwrap();
4958
4959        server.mock_well_known().error404().mock_once().named("well-known").mount().await;
4960
4961        assert!(
4962            Client::builder()
4963                .insecure_server_name_no_tls(alice.server_name())
4964                .build()
4965                .await
4966                .is_err(),
4967            "Creating a client from a user ID should fail when the .well-known request fails."
4968        );
4969    }
4970
4971    #[async_test]
4972    async fn test_room_creation() {
4973        let server = MatrixMockServer::new().await;
4974        let client = server.client_builder().build().await;
4975
4976        let f = EventFactory::new().sender(User::Alice);
4977
4978        let room = server
4979            .sync_room(
4980                &client,
4981                JoinedRoomBuilder::default()
4982                    .add_state_event(f.member(User::Alice).display_name("example"))
4983                    .add_state_event(f.power_levels()),
4984            )
4985            .await;
4986
4987        assert_eq!(room.state(), RoomState::Joined);
4988    }
4989
4990    #[async_test]
4991    async fn test_retry_limit_http_requests() {
4992        let server = MatrixMockServer::new().await;
4993        let client = server
4994            .client_builder()
4995            .on_builder(|builder| builder.request_config(RequestConfig::new().retry_limit(4)))
4996            .build()
4997            .await;
4998
4999        assert!(client.request_config().retry_limit.unwrap() == 4);
5000
5001        server.mock_who_am_i().error500().expect(4).mount().await;
5002
5003        client.whoami().await.unwrap_err();
5004    }
5005
5006    #[async_test]
5007    async fn test_retry_timeout_http_requests() {
5008        // Keep this timeout small so that the test doesn't take long
5009        let retry_timeout = Duration::from_secs(5);
5010        let server = MatrixMockServer::new().await;
5011        let client = server
5012            .client_builder()
5013            .on_builder(|builder| {
5014                builder.request_config(RequestConfig::new().max_retry_time(retry_timeout))
5015            })
5016            .build()
5017            .await;
5018
5019        assert!(client.request_config().max_retry_time.unwrap() == retry_timeout);
5020
5021        server.mock_login().error500().expect(2..).mount().await;
5022
5023        client.matrix_auth().login_username("example", "wordpass").send().await.unwrap_err();
5024    }
5025
5026    #[async_test]
5027    async fn test_short_retry_initial_http_requests() {
5028        let server = MatrixMockServer::new().await;
5029        let client = server
5030            .client_builder()
5031            .on_builder(|builder| builder.request_config(RequestConfig::short_retry()))
5032            .build()
5033            .await;
5034
5035        server.mock_login().error500().expect(3..).mount().await;
5036
5037        client.matrix_auth().login_username("example", "wordpass").send().await.unwrap_err();
5038    }
5039
5040    #[async_test]
5041    async fn test_no_retry_http_requests() {
5042        let server = MatrixMockServer::new().await;
5043        let client = server.client_builder().build().await;
5044
5045        server.mock_devices().error500().mock_once().mount().await;
5046
5047        client.devices().await.unwrap_err();
5048    }
5049
5050    #[async_test]
5051    async fn test_set_homeserver() {
5052        let client = MockClientBuilder::new(None).build().await;
5053        assert_eq!(client.homeserver().as_ref(), "http://localhost/");
5054
5055        let homeserver = Url::parse("http://example.com/").unwrap();
5056        client.set_homeserver(homeserver.clone());
5057        assert_eq!(client.homeserver(), homeserver);
5058    }
5059
5060    #[async_test]
5061    async fn test_search_user_request() {
5062        let server = MatrixMockServer::new().await;
5063        let client = server.client_builder().build().await;
5064
5065        server.mock_user_directory().ok().mock_once().mount().await;
5066
5067        let response = client.search_users("test", 50).await.unwrap();
5068        assert_eq!(response.results.len(), 1);
5069        let result = &response.results[0];
5070        assert_eq!(result.user_id.to_string(), "@test:example.me");
5071        assert_eq!(result.display_name.clone().unwrap(), "Test");
5072        assert_eq!(result.avatar_url.clone().unwrap().to_string(), "mxc://example.me/someid");
5073        assert!(!response.limited);
5074    }
5075
5076    #[async_test]
5077    async fn test_request_unstable_features() {
5078        let server = MatrixMockServer::new().await;
5079        let client = server.client_builder().no_server_versions().build().await;
5080
5081        server
5082            .mock_versions()
5083            .with_feature("org.matrix.e2e_cross_signing", true)
5084            .ok()
5085            .mock_once()
5086            .mount()
5087            .await;
5088
5089        let unstable_features = client.unstable_features().await.unwrap();
5090        assert!(unstable_features.contains(&FeatureFlag::from("org.matrix.e2e_cross_signing")));
5091        assert!(!unstable_features.contains(&FeatureFlag::from("you.shall.pass")));
5092    }
5093
5094    #[async_test]
5095    async fn test_rtc_livekit_endpoints_path_selection() {
5096        use wiremock::{
5097            Mock, ResponseTemplate,
5098            matchers::{method, path},
5099        };
5100
5101        for (stable, prefix) in
5102            [(false, "/_matrix/client/unstable/io.element.msc4195"), (true, "/_matrix/client/v1")]
5103        {
5104            let server = MatrixMockServer::new().await;
5105            let client = server.client_builder().no_server_versions().build().await;
5106
5107            server
5108                .mock_versions()
5109                .with_feature("org.matrix.msc4195.stable", stable)
5110                .ok()
5111                .mock_once()
5112                .mount()
5113                .await;
5114
5115            Mock::given(method("POST"))
5116                .and(path(format!("{prefix}/rtc/livekit/get_token")))
5117                .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "jwt": "the-jwt" })))
5118                .expect(1)
5119                .mount(server.server())
5120                .await;
5121
5122            Mock::given(method("POST"))
5123                .and(path(format!("{prefix}/rtc/livekit/delegate_delayed_leave")))
5124                .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
5125                .expect(1)
5126                .mount(server.server())
5127                .await;
5128
5129            let room_id = ruma::owned_room_id!("!1:example.org");
5130
5131            let response = client
5132                .rtc_livekit_get_token(
5133                    "wss://livekit.example.org".to_owned(),
5134                    room_id.clone(),
5135                    "m.call".to_owned(),
5136                    "member-id".to_owned(),
5137                    None,
5138                )
5139                .await
5140                .unwrap();
5141            assert_eq!(response.jwt, "the-jwt");
5142
5143            client
5144                .rtc_livekit_delegate_delayed_leave(
5145                    "wss://livekit.example.org".to_owned(),
5146                    room_id,
5147                    "m.call".to_owned(),
5148                    "member-id".to_owned(),
5149                    "delay-id".to_owned(),
5150                )
5151                .await
5152                .unwrap();
5153        }
5154    }
5155
5156    #[async_test]
5157    async fn test_can_homeserver_push_encrypted_event_to_device() {
5158        let server = MatrixMockServer::new().await;
5159        let client = server.client_builder().no_server_versions().build().await;
5160
5161        server.mock_versions().with_push_encrypted_events().ok().mock_once().mount().await;
5162
5163        let msc4028_enabled = client.can_homeserver_push_encrypted_event_to_device().await.unwrap();
5164        assert!(msc4028_enabled);
5165    }
5166
5167    #[cfg(feature = "unstable-msc4354")]
5168    #[async_test]
5169    async fn test_supports_sticky_events() {
5170        // A homeserver that doesn't advertise the feature.
5171        let server = MatrixMockServer::new().await;
5172        let client = server.client_builder().no_server_versions().build().await;
5173
5174        server.mock_versions().ok().mock_once().mount().await;
5175
5176        assert!(!client.supports_sticky_events().await.unwrap());
5177
5178        // A homeserver that does.
5179        let server = MatrixMockServer::new().await;
5180        let client = server.client_builder().no_server_versions().build().await;
5181
5182        server.mock_versions().with_sticky_events().ok().mock_once().mount().await;
5183
5184        assert!(client.supports_sticky_events().await.unwrap());
5185    }
5186
5187    #[async_test]
5188    async fn test_recently_visited_rooms() {
5189        let room_1 = TestRoom::Default;
5190        let room_2 = TestRoom::V12;
5191
5192        // Tracking recently visited rooms requires authentication
5193        let client = MockClientBuilder::new(None).unlogged().build().await;
5194        assert_matches!(
5195            client.account().track_recently_visited_room(room_1.into()).await,
5196            Err(Error::AuthenticationRequired)
5197        );
5198
5199        let client = MockClientBuilder::new(None).build().await;
5200        let account = client.account();
5201
5202        // We should start off with an empty list
5203        assert_eq!(account.get_recently_visited_rooms().await.unwrap().len(), 0);
5204
5205        // Tracking a valid room id should add it to the list
5206        account.track_recently_visited_room(room_1.into()).await.unwrap();
5207        assert_eq!(account.get_recently_visited_rooms().await.unwrap(), &[room_1]);
5208
5209        // And the existing list shouldn't be changed
5210        assert_eq!(account.get_recently_visited_rooms().await.unwrap(), &[room_1]);
5211
5212        // Tracking the same room again shouldn't change the list
5213        account.track_recently_visited_room(room_1.into()).await.unwrap();
5214        assert_eq!(account.get_recently_visited_rooms().await.unwrap(), &[room_1]);
5215
5216        // Tracking a second room should add it to the front of the list
5217        account.track_recently_visited_room(room_2.into()).await.unwrap();
5218        assert_eq!(account.get_recently_visited_rooms().await.unwrap(), &[room_2, room_1]);
5219
5220        // Tracking the first room yet again should move it to the front of the
5221        // list
5222        account.track_recently_visited_room(room_1.into()).await.unwrap();
5223        assert_eq!(account.get_recently_visited_rooms().await.unwrap(), &[room_1, room_2]);
5224
5225        // Tracking should be capped at 20
5226        for n in 0..20 {
5227            account
5228                .track_recently_visited_room(RoomId::parse(format!("!{n}:localhost")).unwrap())
5229                .await
5230                .unwrap();
5231        }
5232
5233        assert_eq!(account.get_recently_visited_rooms().await.unwrap().len(), 20);
5234
5235        // And the initial rooms should've been pushed out
5236        let rooms = account.get_recently_visited_rooms().await.unwrap();
5237        assert!(!rooms.contains(&room_1.into()));
5238        assert!(!rooms.contains(&room_2.into()));
5239
5240        // And the last tracked room should be the first
5241        assert_eq!(rooms.first().unwrap(), "!19:localhost");
5242    }
5243
5244    #[async_test]
5245    async fn test_client_no_cycle_with_event_cache() {
5246        let client = MockClientBuilder::new(None).build().await;
5247
5248        // Wait for the init tasks to die.
5249        sleep(Duration::from_secs(1)).await;
5250
5251        let weak_client = client.downgrade();
5252        assert_eq!(weak_client.strong_count(), 1);
5253
5254        {
5255            // Have the client know the room.
5256            let response = SyncResponseBuilder::default()
5257                .add_joined_room(JoinedRoomBuilder::default())
5258                .build_sync_response();
5259            client.inner.base_client.receive_sync_response(response).await.unwrap();
5260
5261            let (_room_event_cache, _drop_handles) =
5262                client.event_cache().unwrap().room(TestRoom::Default.into()).await.unwrap();
5263        }
5264
5265        drop(client);
5266
5267        // Give a bit of time for background tasks to die.
5268        sleep(Duration::from_secs(1)).await;
5269
5270        // The weak client must be the last reference to the client now.
5271        assert_eq!(weak_client.strong_count(), 0);
5272        let client = weak_client.get();
5273        assert!(
5274            client.is_none(),
5275            "too many strong references to the client: {}",
5276            Arc::strong_count(&client.unwrap().inner)
5277        );
5278    }
5279
5280    #[async_test]
5281    async fn test_supported_versions_caching() {
5282        let server = MatrixMockServer::new().await;
5283
5284        let versions_mock = server
5285            .mock_versions()
5286            .expect_default_access_token()
5287            .with_feature("org.matrix.e2e_cross_signing", true)
5288            .ok()
5289            .named("first versions mock")
5290            .expect(1)
5291            .mount_as_scoped()
5292            .await;
5293
5294        let memory_store = Arc::new(MemoryStore::new());
5295        let client = server
5296            .client_builder()
5297            .no_server_versions()
5298            .on_builder(|builder| {
5299                builder.store_config(
5300                    StoreConfig::new(CrossProcessLockConfig::SingleProcess)
5301                        .state_store(memory_store.clone()),
5302                )
5303            })
5304            .build()
5305            .await;
5306
5307        assert!(client.server_versions().await.unwrap().contains(&MatrixVersion::V1_0));
5308
5309        // The result was cached.
5310        assert_matches!(client.supported_versions_cached().await, Ok(Some(_)));
5311        // This subsequent call hits the in-memory cache.
5312        assert!(client.server_versions().await.unwrap().contains(&MatrixVersion::V1_0));
5313
5314        drop(client);
5315
5316        let client = server
5317            .client_builder()
5318            .no_server_versions()
5319            .on_builder(|builder| {
5320                builder.store_config(
5321                    StoreConfig::new(CrossProcessLockConfig::SingleProcess)
5322                        .state_store(memory_store.clone()),
5323                )
5324            })
5325            .build()
5326            .await;
5327
5328        // These calls to the new client hit the on-disk cache.
5329        assert!(
5330            client
5331                .unstable_features()
5332                .await
5333                .unwrap()
5334                .contains(&FeatureFlag::from("org.matrix.e2e_cross_signing"))
5335        );
5336
5337        let supported = client.supported_versions().await.unwrap();
5338        assert!(supported.versions.contains(&MatrixVersion::V1_0));
5339        assert!(supported.features.contains(&FeatureFlag::from("org.matrix.e2e_cross_signing")));
5340
5341        // Then this call hits the in-memory cache.
5342        let supported = client.supported_versions().await.unwrap();
5343        assert!(supported.versions.contains(&MatrixVersion::V1_0));
5344        assert!(supported.features.contains(&FeatureFlag::from("org.matrix.e2e_cross_signing")));
5345
5346        drop(versions_mock);
5347
5348        // Now, reset the cache, and observe the endpoint being called again
5349        // once.
5350        client.reset_supported_versions().await.unwrap();
5351
5352        server.mock_versions().ok().expect(2).named("second versions mock").mount().await;
5353
5354        // Hits network again.
5355        assert!(client.server_versions().await.unwrap().contains(&MatrixVersion::V1_0));
5356        // Hits in-memory cache again.
5357        assert!(client.server_versions().await.unwrap().contains(&MatrixVersion::V1_0));
5358        assert_matches!(client.inner.caches.supported_versions.value(), CachedValue::Cached(value) if !value.has_expired());
5359
5360        // Force an expiry of the data.
5361        let supported_versions = client.supported_versions_cached().await.unwrap().unwrap();
5362        let mut ttl_value = TtlValue::new(supported_versions);
5363        ttl_value.expire();
5364        client.inner.caches.supported_versions.set_value(ttl_value);
5365
5366        // Call the method to trigger a cache refresh background task.
5367        client.supported_versions_cached().await.unwrap().unwrap();
5368
5369        // We wait for the task to finish, the endpoint should have been called
5370        // again.
5371        sleep(Duration::from_secs(1)).await;
5372        assert_matches!(client.inner.caches.supported_versions.value(), CachedValue::Cached(value) if !value.has_expired());
5373    }
5374
5375    #[async_test]
5376    async fn test_well_known_caching() {
5377        let server = MatrixMockServer::new().await;
5378        let server_url = server.uri();
5379        let domain = server_url.strip_prefix("http://").unwrap();
5380        let server_name = <&ServerName>::try_from(domain).unwrap();
5381        let rtc_foci = vec![RtcTransport::LiveKit(LiveKitRtcTransport::new(
5382            "wss://livekit.example.com".to_owned(),
5383        ))];
5384
5385        let well_known_mock = server
5386            .mock_well_known()
5387            .ok()
5388            .named("well known mock")
5389            .expect(2) // One for ClientBuilder discovery, one for the ServerInfo cache.
5390            .mount_as_scoped()
5391            .await;
5392
5393        let memory_store = Arc::new(MemoryStore::new());
5394        let client = Client::builder()
5395            .insecure_server_name_no_tls(server_name)
5396            .store_config(
5397                StoreConfig::new(CrossProcessLockConfig::SingleProcess)
5398                    .state_store(memory_store.clone()),
5399            )
5400            .build()
5401            .await
5402            .unwrap();
5403
5404        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5405
5406        // This subsequent call hits the in-memory cache.
5407        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5408
5409        drop(client);
5410
5411        let client = server
5412            .client_builder()
5413            .no_server_versions()
5414            .on_builder(|builder| {
5415                builder.store_config(
5416                    StoreConfig::new(CrossProcessLockConfig::SingleProcess)
5417                        .state_store(memory_store.clone()),
5418                )
5419            })
5420            .build()
5421            .await;
5422
5423        // This call to the new client hits the on-disk cache.
5424        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5425
5426        // Then this call hits the in-memory cache.
5427        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5428
5429        drop(well_known_mock);
5430
5431        // Now, reset the cache, and observe the endpoints being called again
5432        // once.
5433        client.reset_well_known().await.unwrap();
5434
5435        server.mock_well_known().ok().named("second well known mock").expect(2).mount().await;
5436
5437        // Hits network again.
5438        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5439        // Hits in-memory cache again.
5440        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5441
5442        // Force an expiry of the data.
5443        let well_known = client.well_known().await;
5444        let mut ttl_value = TtlValue::new(well_known);
5445        ttl_value.expire();
5446        client.inner.caches.well_known.set_value(ttl_value);
5447
5448        // Call the method again to trigger a cache refresh background task.
5449        client.well_known().await;
5450
5451        // We wait for the task to finish, the endpoint should have been called
5452        // again. We need to wait a bit because the first requests using the
5453        // server name of the user will fail, only the requests using the
5454        // homeserver URL will succeed.
5455        sleep(Duration::from_secs(5)).await;
5456        assert_matches!(client.inner.caches.well_known.value(), CachedValue::Cached(value) if !value.has_expired());
5457    }
5458
5459    #[async_test]
5460    async fn test_rtc_transports_caching() {
5461        let server = MatrixMockServer::new().await;
5462        let transports = vec![RtcTransport::LiveKit(LiveKitRtcTransport::new(
5463            "wss://livekit.example.com".to_owned(),
5464        ))];
5465
5466        let transports_mock = server
5467            .mock_get_rtc_transports()
5468            .ok()
5469            .named("first transports mock")
5470            .expect(1)
5471            .mount_as_scoped()
5472            .await;
5473
5474        let client = server.client_builder().build().await;
5475
5476        // First call hits the network.
5477        assert_eq!(client.rtc_transports().await.unwrap(), Some(transports.clone()));
5478        // Subsequent call hits the in-memory cache.
5479        assert_eq!(client.rtc_transports().await.unwrap(), Some(transports.clone()));
5480        assert_matches!(client.inner.caches.rtc_transports.value(), CachedValue::Cached(value) if !value.has_expired());
5481
5482        drop(transports_mock);
5483
5484        // Reset the cache, and observe the endpoint being called again once.
5485        client.reset_rtc_transports();
5486
5487        server
5488            .mock_get_rtc_transports()
5489            .ok()
5490            .named("second transports mock")
5491            .expect(2)
5492            .mount()
5493            .await;
5494
5495        // Hits network again.
5496        assert_eq!(client.rtc_transports().await.unwrap(), Some(transports.clone()));
5497        // Hits in-memory cache again.
5498        assert_eq!(client.rtc_transports().await.unwrap(), Some(transports.clone()));
5499
5500        // Force an expiry of the data.
5501        let mut ttl_value = TtlValue::new(Some(transports.clone()));
5502        ttl_value.expire();
5503        client.inner.caches.rtc_transports.set_value(ttl_value);
5504
5505        // Call the method again to trigger a cache refresh background task.
5506        client.rtc_transports().await.unwrap();
5507
5508        // We wait for the task to finish, the endpoint should have been called
5509        // again.
5510        sleep(Duration::from_secs(1)).await;
5511        assert_matches!(client.inner.caches.rtc_transports.value(), CachedValue::Cached(value) if !value.has_expired());
5512    }
5513
5514    #[async_test]
5515    async fn test_rtc_transports_unsupported_caching() {
5516        let server = MatrixMockServer::new().await;
5517
5518        // The homeserver doesn't implement the endpoint: it responds with a 404
5519        // and an `M_UNRECOGNIZED` error (as a homeserver does for an
5520        // unrecognized endpoint). We expect it to be hit only once, despite
5521        // several calls, thanks to the negative caching.
5522        server
5523            .mock_get_rtc_transports()
5524            .error_unrecognized()
5525            .named("unrecognized transports mock")
5526            .expect(1)
5527            .mount()
5528            .await;
5529
5530        let client = server.client_builder().build().await;
5531
5532        // First call hits the network and gets a 404, which is cached as `None`
5533        // (unsupported), distinct from `Some(vec![])` (supported but empty).
5534        assert_eq!(client.rtc_transports().await.unwrap(), None);
5535        // Subsequent call hits the in-memory cache, without re-hitting the
5536        // endpoint.
5537        assert_eq!(client.rtc_transports().await.unwrap(), None);
5538        assert_matches!(client.inner.caches.rtc_transports.value(), CachedValue::Cached(value) if !value.has_expired());
5539    }
5540
5541    /// Mounts a scoped mock for the MSC4143 RTC transports endpoint, either
5542    /// advertising a single LiveKit transport, or responding with the
5543    /// `M_UNRECOGNIZED` error of a homeserver that doesn't implement it.
5544    async fn mock_rtc_transports_endpoint(
5545        server: &MatrixMockServer,
5546        supported: bool,
5547    ) -> wiremock::MockGuard {
5548        let endpoint = server.mock_get_rtc_transports();
5549
5550        let mock = if supported { endpoint.ok() } else { endpoint.error_unrecognized() };
5551
5552        mock.named("transports mock").expect(1).mount_as_scoped().await
5553    }
5554
5555    #[async_test]
5556    async fn test_discover_rtc_transports_prefers_the_endpoint() {
5557        let server = MatrixMockServer::new().await;
5558        let transports = vec![RtcTransport::LiveKit(LiveKitRtcTransport::new(
5559            "wss://livekit.example.com".to_owned(),
5560        ))];
5561
5562        let _transports_mock = mock_rtc_transports_endpoint(&server, true).await;
5563
5564        // The homeserver implements the discovery endpoint, so the well-known
5565        // must not be queried at all.
5566        let _well_known_mock = server
5567            .mock_well_known()
5568            .ok()
5569            .named("well-known mock")
5570            .expect(0)
5571            .mount_as_scoped()
5572            .await;
5573
5574        let client = server.client_builder().build().await;
5575
5576        assert_eq!(client.discover_rtc_transports().await.unwrap(), Some(transports));
5577    }
5578
5579    #[async_test]
5580    async fn test_discover_rtc_transports_falls_back_to_well_known() {
5581        let server = MatrixMockServer::new().await;
5582        // The `m.rtc_foci` advertised by `WellKnownEndpoint::ok`.
5583        let rtc_foci = vec![RtcTransport::LiveKit(LiveKitRtcTransport::new(
5584            "wss://livekit.example.com".to_owned(),
5585        ))];
5586
5587        let _transports_mock = mock_rtc_transports_endpoint(&server, false).await;
5588
5589        let _well_known_mock = server
5590            .mock_well_known()
5591            .ok()
5592            .named("well-known mock")
5593            .expect(1)
5594            .mount_as_scoped()
5595            .await;
5596
5597        let client = server.client_builder().build().await;
5598
5599        // The homeserver doesn't implement the discovery endpoint, so the
5600        // well-known foci are used instead.
5601        assert_eq!(client.discover_rtc_transports().await.unwrap(), Some(rtc_foci));
5602    }
5603
5604    /// Mounts a well-known mock that must never be hit.
5605    async fn mock_well_known_never_called(server: &MatrixMockServer) -> wiremock::MockGuard {
5606        server.mock_well_known().ok().named("well-known mock").expect(0).mount_as_scoped().await
5607    }
5608
5609    #[async_test]
5610    async fn test_well_known_lookup_disabled() {
5611        let server = MatrixMockServer::new().await;
5612
5613        let _transports_mock = mock_rtc_transports_endpoint(&server, false).await;
5614
5615        // There should be no requests to fetch the well-known.
5616        let _well_known_mock = mock_well_known_never_called(&server).await;
5617
5618        // Disable well-known lookups at client build time.
5619        let client = server
5620            .client_builder()
5621            .on_builder(|builder| builder.disable_well_known_lookup(true))
5622            .build()
5623            .await;
5624
5625        // The homeserver doesn't implement the discovery endpoint, and falling
5626        // back to the well-known isn't allowed, so nothing could be discovered.
5627        assert_eq!(client.discover_rtc_transports().await.unwrap(), None);
5628        // The other well-known consumers are disabled too.
5629        assert!(client.well_known_rtc_transports().await.unwrap().is_empty());
5630        assert!(client.tile_server().await.is_none());
5631        assert!(client.fetch_client_well_known().await.is_none());
5632    }
5633
5634    #[async_test]
5635    async fn test_well_known_lookup_disabled_after_build() {
5636        let server = MatrixMockServer::new().await;
5637
5638        let _transports_mock = mock_rtc_transports_endpoint(&server, false).await;
5639
5640        // There should be no requests to fetch the well-known.
5641        let _well_known_mock = mock_well_known_never_called(&server).await;
5642
5643        // Disable well-known lookups after building the client.
5644        let client = server.client_builder().build().await;
5645        client.disable_well_known_lookup(true);
5646
5647        // The homeserver doesn't implement the discovery endpoint, and falling
5648        // back to the well-known isn't allowed, so nothing could be discovered.
5649        assert_eq!(client.discover_rtc_transports().await.unwrap(), None);
5650        // The other well-known consumers are disabled too.
5651        assert!(client.well_known_rtc_transports().await.unwrap().is_empty());
5652        assert!(client.tile_server().await.is_none());
5653        assert!(client.fetch_client_well_known().await.is_none());
5654    }
5655
5656    #[async_test]
5657    async fn test_missing_well_known_caching() {
5658        let server = MatrixMockServer::new().await;
5659        let rtc_foci: Vec<RtcTransport> = vec![];
5660
5661        let well_known_mock = server
5662            .mock_well_known()
5663            .error_unrecognized()
5664            .named("first well-known mock")
5665            .expect(1)
5666            .mount_as_scoped()
5667            .await;
5668
5669        let memory_store = Arc::new(MemoryStore::new());
5670        let client = server
5671            .client_builder()
5672            .on_builder(|builder| {
5673                builder.store_config(
5674                    StoreConfig::new(CrossProcessLockConfig::SingleProcess)
5675                        .state_store(memory_store.clone()),
5676                )
5677            })
5678            .build()
5679            .await;
5680
5681        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5682
5683        // This subsequent call hits the in-memory cache.
5684        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5685
5686        drop(client);
5687
5688        let client = server
5689            .client_builder()
5690            .on_builder(|builder| {
5691                builder.store_config(
5692                    StoreConfig::new(CrossProcessLockConfig::SingleProcess)
5693                        .state_store(memory_store.clone()),
5694                )
5695            })
5696            .build()
5697            .await;
5698
5699        // This call to the new client hits the on-disk cache.
5700        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5701
5702        // Then this call hits the in-memory cache.
5703        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5704
5705        drop(well_known_mock);
5706
5707        // Now, reset the cache, and observe the endpoints being called again
5708        // once.
5709        client.reset_well_known().await.unwrap();
5710
5711        server
5712            .mock_well_known()
5713            .error_unrecognized()
5714            .expect(1)
5715            .named("second well-known mock")
5716            .mount()
5717            .await;
5718
5719        // Hits network again.
5720        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5721        // Hits in-memory cache again.
5722        assert_eq!(client.well_known_rtc_transports().await.unwrap(), rtc_foci);
5723    }
5724
5725    #[async_test]
5726    async fn test_no_network_doesnt_cause_infinite_retries() {
5727        // We want infinite retries for transient errors.
5728        let client = MockClientBuilder::new(None)
5729            .on_builder(|builder| builder.request_config(RequestConfig::new()))
5730            .build()
5731            .await;
5732
5733        // We don't define a mock server on purpose here, so that the error is
5734        // really a network error.
5735        client.whoami().await.unwrap_err();
5736    }
5737
5738    #[async_test]
5739    async fn test_await_room_remote_echo_returns_the_room_if_it_was_already_synced() {
5740        let server = MatrixMockServer::new().await;
5741        let client = server.client_builder().build().await;
5742
5743        let room_id = TestRoom::Default;
5744
5745        server
5746            .mock_sync()
5747            .ok_and_run(&client, |builder| {
5748                builder.add_joined_room(JoinedRoomBuilder::default());
5749            })
5750            .await;
5751
5752        let room = client.await_room_remote_echo(room_id.into()).now_or_never().unwrap();
5753        assert_eq!(room.room_id(), room_id);
5754    }
5755
5756    #[async_test]
5757    async fn test_await_room_remote_echo_returns_the_room_when_it_is_ready() {
5758        let server = MatrixMockServer::new().await;
5759        let client = server.client_builder().build().await;
5760
5761        let room_id = TestRoom::Default;
5762
5763        let client = Arc::new(client);
5764
5765        // Perform the /sync request with a delay so it starts after the
5766        // `await_room_remote_echo` call has happened
5767        spawn({
5768            let client = client.clone();
5769            async move {
5770                sleep(Duration::from_millis(100)).await;
5771
5772                server
5773                    .mock_sync()
5774                    .ok_and_run(&client, |builder| {
5775                        builder.add_joined_room(JoinedRoomBuilder::default());
5776                    })
5777                    .await;
5778            }
5779        });
5780
5781        let room = timeout(Duration::from_secs(10), client.await_room_remote_echo(room_id.into()))
5782            .await
5783            .unwrap();
5784        assert_eq!(room.room_id(), room_id);
5785    }
5786
5787    #[async_test]
5788    async fn test_await_room_remote_echo_will_timeout_if_no_room_is_found() {
5789        let client = MockClientBuilder::new(None).build().await;
5790
5791        // Room is not present so the client won't be able to find it. The call
5792        // will timeout.
5793        timeout(Duration::from_secs(1), client.await_room_remote_echo(TestRoom::Default.into()))
5794            .await
5795            .unwrap_err();
5796    }
5797
5798    #[async_test]
5799    async fn test_await_room_remote_echo_will_timeout_if_room_is_found_but_not_synced() {
5800        let server = MatrixMockServer::new().await;
5801        let client = server.client_builder().build().await;
5802
5803        server.mock_create_room().ok().mount().await;
5804
5805        // Create a room in the internal store
5806        let room = client
5807            .create_room(assign!(CreateRoomRequest::new(), {
5808                invite: vec![],
5809                is_direct: false,
5810            }))
5811            .await
5812            .unwrap();
5813
5814        // Room is locally present, but not synced, the call will timeout
5815        timeout(Duration::from_secs(1), client.await_room_remote_echo(room.room_id()))
5816            .await
5817            .unwrap_err();
5818    }
5819
5820    #[async_test]
5821    async fn test_create_room_is_not_retried() {
5822        let server = MatrixMockServer::new().await;
5823
5824        let client = server
5825            .client_builder()
5826            .on_builder(|builder| builder.request_config(RequestConfig::new().retry_limit(3)))
5827            .build()
5828            .await;
5829
5830        // Creating a room isn't idempotent, so retrying could create duplicate
5831        // rooms.
5832        server.mock_create_room().error500().expect(1).mount().await;
5833
5834        client.create_room(CreateRoomRequest::new()).await.unwrap_err();
5835    }
5836
5837    #[async_test]
5838    async fn test_is_room_alias_available_if_alias_is_not_resolved() {
5839        let server = MatrixMockServer::new().await;
5840        let client = server.client_builder().build().await;
5841
5842        server.mock_room_directory_resolve_alias().not_found().expect(1).mount().await;
5843
5844        let ret = client.is_room_alias_available(room_alias_id!("#some_alias:matrix.org")).await;
5845        assert_matches!(ret, Ok(true));
5846    }
5847
5848    #[async_test]
5849    async fn test_is_room_alias_available_if_alias_is_resolved() {
5850        let server = MatrixMockServer::new().await;
5851        let client = server.client_builder().build().await;
5852
5853        server
5854            .mock_room_directory_resolve_alias()
5855            .ok("!some_room_id:matrix.org", Vec::new())
5856            .expect(1)
5857            .mount()
5858            .await;
5859
5860        let ret = client.is_room_alias_available(room_alias_id!("#some_alias:matrix.org")).await;
5861        assert_matches!(ret, Ok(false));
5862    }
5863
5864    #[async_test]
5865    async fn test_is_room_alias_available_if_error_found() {
5866        let server = MatrixMockServer::new().await;
5867        let client = server.client_builder().build().await;
5868
5869        server.mock_room_directory_resolve_alias().error500().expect(1).mount().await;
5870
5871        let ret = client.is_room_alias_available(room_alias_id!("#some_alias:matrix.org")).await;
5872        assert_matches!(ret, Err(_));
5873    }
5874
5875    #[async_test]
5876    async fn test_create_room_alias() {
5877        let server = MatrixMockServer::new().await;
5878        let client = server.client_builder().build().await;
5879
5880        server.mock_room_directory_create_room_alias().ok().expect(1).mount().await;
5881
5882        let ret = client
5883            .create_room_alias(room_alias_id!("#some_alias:matrix.org"), TestRoom::Default.into())
5884            .await;
5885        assert_matches!(ret, Ok(()));
5886    }
5887
5888    #[async_test]
5889    async fn test_join_room_by_id_or_alias() {
5890        let server = MatrixMockServer::new().await;
5891        let client = server.client_builder().build().await;
5892
5893        let target_room_id = TestRoom::Default;
5894        let target_alias = room_alias_id!("#some_alias:matrix.org");
5895
5896        server
5897            .mock_room_join_by_id_or_alias(target_room_id)
5898            .ok(target_room_id)
5899            .expect(1)
5900            .mount()
5901            .await;
5902
5903        server
5904            .mock_room_join_by_id_or_alias(target_alias)
5905            .ok(target_room_id)
5906            .expect(1)
5907            .mount()
5908            .await;
5909
5910        server
5911            .mock_room_directory_resolve_alias()
5912            .ok(target_room_id.as_str(), Vec::new())
5913            .mount()
5914            .await;
5915
5916        let ret = client.join_room_by_id_or_alias(target_alias.into(), &[]).await;
5917        assert!(ret.is_ok());
5918
5919        let ret = client.join_room_by_id_or_alias(target_room_id.into(), &[]).await;
5920        assert!(ret.is_ok());
5921    }
5922
5923    #[async_test]
5924    async fn test_room_preview_for_invited_room_hits_summary_endpoint() {
5925        let server = MatrixMockServer::new().await;
5926        let client = server.client_builder().build().await;
5927
5928        let room_id = TestRoom::Default;
5929
5930        // Make sure the summary endpoint is called once
5931        server.mock_room_summary().ok(room_id).mock_once().mount().await;
5932
5933        // We create a locally cached invited room
5934        let invited_room =
5935            client.inner.base_client.get_or_create_room(room_id.into(), RoomState::Invited);
5936
5937        // And we get a preview, the server endpoint was reached
5938        let preview = client
5939            .get_room_preview(room_id.into(), Vec::new())
5940            .await
5941            .expect("Room preview should be retrieved");
5942
5943        assert_eq!(invited_room.room_id(), preview.room_id);
5944    }
5945
5946    #[async_test]
5947    async fn test_room_preview_for_left_room_hits_summary_endpoint() {
5948        let server = MatrixMockServer::new().await;
5949        let client = server.client_builder().build().await;
5950
5951        let room_id = TestRoom::Default;
5952
5953        // Make sure the summary endpoint is called once
5954        server.mock_room_summary().ok(room_id).mock_once().mount().await;
5955
5956        // We create a locally cached left room
5957        let left_room =
5958            client.inner.base_client.get_or_create_room(room_id.into(), RoomState::Left);
5959
5960        // And we get a preview, the server endpoint was reached
5961        let preview = client
5962            .get_room_preview(room_id.into(), Vec::new())
5963            .await
5964            .expect("Room preview should be retrieved");
5965
5966        assert_eq!(left_room.room_id(), preview.room_id);
5967    }
5968
5969    #[async_test]
5970    async fn test_room_preview_for_knocked_room_hits_summary_endpoint() {
5971        let server = MatrixMockServer::new().await;
5972        let client = server.client_builder().build().await;
5973
5974        let room_id = TestRoom::Default;
5975
5976        // Make sure the summary endpoint is called once
5977        server.mock_room_summary().ok(room_id).mock_once().mount().await;
5978
5979        // We create a locally cached knocked room
5980        let knocked_room =
5981            client.inner.base_client.get_or_create_room(room_id.into(), RoomState::Knocked);
5982
5983        // And we get a preview, the server endpoint was reached
5984        let preview = client
5985            .get_room_preview(room_id.into(), Vec::new())
5986            .await
5987            .expect("Room preview should be retrieved");
5988
5989        assert_eq!(knocked_room.room_id(), preview.room_id);
5990    }
5991
5992    #[async_test]
5993    async fn test_room_preview_for_joined_room_retrieves_local_room_info() {
5994        let server = MatrixMockServer::new().await;
5995        let client = server.client_builder().build().await;
5996
5997        let room_id = TestRoom::Default;
5998
5999        // Make sure the summary endpoint is not called
6000        server.mock_room_summary().ok(room_id).never().mount().await;
6001
6002        // We create a locally cached joined room
6003        let joined_room =
6004            client.inner.base_client.get_or_create_room(room_id.into(), RoomState::Joined);
6005
6006        // And we get a preview, no server endpoint was reached
6007        let preview = client
6008            .get_room_preview(room_id.into(), Vec::new())
6009            .await
6010            .expect("Room preview should be retrieved");
6011
6012        assert_eq!(joined_room.room_id(), preview.room_id);
6013    }
6014
6015    #[async_test]
6016    async fn test_media_preview_config() {
6017        let server = MatrixMockServer::new().await;
6018        let client = server.client_builder().build().await;
6019
6020        server
6021            .mock_sync()
6022            .ok_and_run(&client, |builder| {
6023                builder.add_custom_global_account_data(json!({
6024                    "content": {
6025                        "media_previews": "private",
6026                        "invite_avatars": "off"
6027                    },
6028                    "type": "m.media_preview_config"
6029                }));
6030            })
6031            .await;
6032
6033        let (initial_value, stream) =
6034            client.account().observe_media_preview_config().await.unwrap();
6035
6036        let initial_value: MediaPreviewConfigEventContent = initial_value.unwrap();
6037        assert_eq!(initial_value.invite_avatars, Some(InviteAvatars::Off));
6038        assert_eq!(initial_value.media_previews, Some(MediaPreviews::Private));
6039        let mut stream = pin!(stream);
6040        assert_pending!(stream);
6041
6042        server
6043            .mock_sync()
6044            .ok_and_run(&client, |builder| {
6045                builder.add_custom_global_account_data(json!({
6046                    "content": {
6047                        "media_previews": "off",
6048                        "invite_avatars": "on"
6049                    },
6050                    "type": "m.media_preview_config"
6051                }));
6052            })
6053            .await;
6054
6055        assert_next_matches!(
6056            stream,
6057            MediaPreviewConfigEventContent {
6058                media_previews: Some(MediaPreviews::Off),
6059                invite_avatars: Some(InviteAvatars::On),
6060                ..
6061            }
6062        );
6063        assert_pending!(stream);
6064    }
6065
6066    #[async_test]
6067    async fn test_unstable_media_preview_config() {
6068        let server = MatrixMockServer::new().await;
6069        let client = server.client_builder().build().await;
6070
6071        server
6072            .mock_sync()
6073            .ok_and_run(&client, |builder| {
6074                builder.add_custom_global_account_data(json!({
6075                    "content": {
6076                        "media_previews": "private",
6077                        "invite_avatars": "off"
6078                    },
6079                    "type": "io.element.msc4278.media_preview_config"
6080                }));
6081            })
6082            .await;
6083
6084        let (initial_value, stream) =
6085            client.account().observe_media_preview_config().await.unwrap();
6086
6087        let initial_value: MediaPreviewConfigEventContent = initial_value.unwrap();
6088        assert_eq!(initial_value.invite_avatars, Some(InviteAvatars::Off));
6089        assert_eq!(initial_value.media_previews, Some(MediaPreviews::Private));
6090        let mut stream = pin!(stream);
6091        assert_pending!(stream);
6092
6093        server
6094            .mock_sync()
6095            .ok_and_run(&client, |builder| {
6096                builder.add_custom_global_account_data(json!({
6097                    "content": {
6098                        "media_previews": "off",
6099                        "invite_avatars": "on"
6100                    },
6101                    "type": "io.element.msc4278.media_preview_config"
6102                }));
6103            })
6104            .await;
6105
6106        assert_next_matches!(
6107            stream,
6108            MediaPreviewConfigEventContent {
6109                media_previews: Some(MediaPreviews::Off),
6110                invite_avatars: Some(InviteAvatars::On),
6111                ..
6112            }
6113        );
6114        assert_pending!(stream);
6115    }
6116
6117    #[async_test]
6118    async fn test_media_preview_config_not_found() {
6119        let server = MatrixMockServer::new().await;
6120        let client = server.client_builder().build().await;
6121
6122        let (initial_value, _) = client.account().observe_media_preview_config().await.unwrap();
6123
6124        assert!(initial_value.is_none());
6125    }
6126
6127    #[async_test]
6128    async fn test_load_or_fetch_max_upload_size_with_auth_matrix_version() {
6129        // The default Matrix version we use is 1.11 or higher, so authenticated
6130        // media is supported.
6131        let server = MatrixMockServer::new().await;
6132        let client = server.client_builder().build().await;
6133
6134        assert!(!client.inner.server_max_upload_size.lock().await.initialized());
6135
6136        server.mock_authenticated_media_config().ok(uint!(2)).mock_once().mount().await;
6137        client.load_or_fetch_max_upload_size().await.unwrap();
6138
6139        assert_eq!(*client.inner.server_max_upload_size.lock().await.get().unwrap(), uint!(2));
6140    }
6141
6142    #[async_test]
6143    async fn test_load_or_fetch_max_upload_size_with_auth_stable_feature() {
6144        // The server must advertise support for the stable feature for
6145        // authenticated media support, so we mock the `GET /versions` response.
6146        let server = MatrixMockServer::new().await;
6147        let client = server.client_builder().no_server_versions().build().await;
6148
6149        server
6150            .mock_versions()
6151            .with_versions(vec!["v1.7", "v1.8", "v1.9", "v1.10"])
6152            .with_feature("org.matrix.msc3916.stable", true)
6153            .ok()
6154            .named("versions")
6155            .expect(1)
6156            .mount()
6157            .await;
6158
6159        assert!(!client.inner.server_max_upload_size.lock().await.initialized());
6160
6161        server.mock_authenticated_media_config().ok(uint!(2)).mock_once().mount().await;
6162        client.load_or_fetch_max_upload_size().await.unwrap();
6163
6164        assert_eq!(*client.inner.server_max_upload_size.lock().await.get().unwrap(), uint!(2));
6165    }
6166
6167    #[async_test]
6168    async fn test_load_or_fetch_max_upload_size_no_auth() {
6169        // The server must not support Matrix 1.11 or higher for unauthenticated
6170        // media requests, so we mock the `GET /versions` response.
6171        let server = MatrixMockServer::new().await;
6172        let client = server.client_builder().no_server_versions().build().await;
6173
6174        server
6175            .mock_versions()
6176            .with_versions(vec!["v1.1"])
6177            .ok()
6178            .named("versions")
6179            .expect(1)
6180            .mount()
6181            .await;
6182
6183        assert!(!client.inner.server_max_upload_size.lock().await.initialized());
6184
6185        server.mock_media_config().ok(uint!(2)).mock_once().mount().await;
6186        client.load_or_fetch_max_upload_size().await.unwrap();
6187
6188        assert_eq!(*client.inner.server_max_upload_size.lock().await.get().unwrap(), uint!(2));
6189    }
6190
6191    #[async_test]
6192    async fn test_uploading_a_too_large_media_file() {
6193        let server = MatrixMockServer::new().await;
6194        let client = server.client_builder().build().await;
6195
6196        server.mock_authenticated_media_config().ok(uint!(1)).mock_once().mount().await;
6197        client.load_or_fetch_max_upload_size().await.unwrap();
6198        assert_eq!(*client.inner.server_max_upload_size.lock().await.get().unwrap(), uint!(1));
6199
6200        let data = vec![1, 2];
6201        let upload_request =
6202            ruma::api::client::media::create_content::v3::Request::new(data.clone());
6203        let request = SendRequest {
6204            client: client.clone(),
6205            request: upload_request,
6206            config: None,
6207            send_progress: SharedObservable::new(TransmissionProgress::default()),
6208        };
6209        let media_request = SendMediaUploadRequest::new(request);
6210
6211        let error = media_request.await.err();
6212        assert_let!(Some(Error::Media(MediaError::MediaTooLargeToUpload { max, current })) = error);
6213        assert_eq!(max, uint!(1));
6214        assert_eq!(current, UInt::new_wrapping(data.len() as u64));
6215    }
6216
6217    #[async_test]
6218    async fn test_dont_ignore_timeout_on_first_sync() {
6219        let server = MatrixMockServer::new().await;
6220        let client = server.client_builder().build().await;
6221
6222        server
6223            .mock_sync()
6224            .timeout(Some(Duration::from_secs(30)))
6225            .ok(|_| {})
6226            .mock_once()
6227            .named("sync_with_timeout")
6228            .mount()
6229            .await;
6230
6231        // Call the endpoint once to check the timeout.
6232        let mut stream = Box::pin(client.sync_stream(SyncSettings::new()).await);
6233
6234        timeout(Duration::from_secs(1), async {
6235            stream.next().await.unwrap().unwrap();
6236        })
6237        .await
6238        .unwrap();
6239    }
6240
6241    #[async_test]
6242    async fn test_ignore_timeout_on_first_sync() {
6243        let server = MatrixMockServer::new().await;
6244        let client = server.client_builder().build().await;
6245
6246        server
6247            .mock_sync()
6248            .timeout(None)
6249            .ok(|_| {})
6250            .mock_once()
6251            .named("sync_no_timeout")
6252            .mount()
6253            .await;
6254        server
6255            .mock_sync()
6256            .timeout(Some(Duration::from_secs(30)))
6257            .ok(|_| {})
6258            .mock_once()
6259            .named("sync_with_timeout")
6260            .mount()
6261            .await;
6262
6263        // Call each version of the endpoint once to check the timeouts.
6264        let mut stream = Box::pin(
6265            client.sync_stream(SyncSettings::new().ignore_timeout_on_first_sync(true)).await,
6266        );
6267
6268        timeout(Duration::from_secs(1), async {
6269            stream.next().await.unwrap().unwrap();
6270            stream.next().await.unwrap().unwrap();
6271        })
6272        .await
6273        .unwrap();
6274    }
6275
6276    #[async_test]
6277    async fn test_disable_room_invites() {
6278        use wiremock::{
6279            Mock, ResponseTemplate,
6280            matchers::{body_json, method, path},
6281        };
6282
6283        let server = MatrixMockServer::new().await;
6284        let client = server.client_builder().build().await;
6285        let user_id = client.user_id().unwrap();
6286
6287        Mock::given(method("PUT"))
6288            .and(path(format!(
6289                "/_matrix/client/v3/user/{user_id}/account_data/m.invite_permission_config"
6290            )))
6291            .and(body_json(json!({
6292                "default_action": "block"
6293            })))
6294            .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
6295            .expect(1)
6296            .mount(server.server())
6297            .await;
6298
6299        let mut config = InvitePermissionConfigEventContent::new();
6300        // Set config to block invites.
6301        config.default_action = Some(InvitePermissionAction::Block);
6302
6303        // Disables invites.
6304        client.account().set_invite_permission_config(config).await.unwrap();
6305    }
6306
6307    #[async_test]
6308    async fn test_enable_room_invites() {
6309        use wiremock::{
6310            Mock, ResponseTemplate,
6311            matchers::{body_json, method, path},
6312        };
6313
6314        let server = MatrixMockServer::new().await;
6315        let client = server.client_builder().build().await;
6316        let user_id = client.user_id().unwrap();
6317
6318        Mock::given(method("PUT"))
6319            .and(path(format!(
6320                "/_matrix/client/v3/user/{user_id}/account_data/m.invite_permission_config"
6321            )))
6322            .and(body_json(json!({})))
6323            .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
6324            .expect(1)
6325            .mount(server.server())
6326            .await;
6327        let mut config = InvitePermissionConfigEventContent::new();
6328        // Just to be explicit.
6329        config.default_action = None;
6330
6331        // Enables invites.
6332        client.account().set_invite_permission_config(config).await.unwrap();
6333    }
6334
6335    #[async_test]
6336    async fn test_fetch_disabled_invite_permission_config() {
6337        use wiremock::{
6338            Mock, ResponseTemplate,
6339            matchers::{method, path},
6340        };
6341
6342        let server = MatrixMockServer::new().await;
6343        let client = server.client_builder().build().await;
6344        let user_id = client.user_id().unwrap();
6345
6346        Mock::given(method("GET"))
6347            .and(path(format!(
6348                "/_matrix/client/v3/user/{user_id}/account_data/m.invite_permission_config"
6349            )))
6350            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
6351                "default_action": "block"
6352            })))
6353            .expect(1)
6354            .mount(server.server())
6355            .await;
6356
6357        let config = client.account().fetch_invite_permission_config().await.unwrap();
6358        // Invites are disabled.
6359        assert_eq!(config.unwrap().default_action, Some(InvitePermissionAction::Block));
6360    }
6361
6362    #[async_test]
6363    async fn test_fetch_enabled_invite_permission_config() {
6364        use wiremock::{
6365            Mock, ResponseTemplate,
6366            matchers::{method, path},
6367        };
6368
6369        let server = MatrixMockServer::new().await;
6370        let client = server.client_builder().build().await;
6371        let user_id = client.user_id().unwrap();
6372
6373        Mock::given(method("GET"))
6374            .and(path(format!(
6375                "/_matrix/client/v3/user/{user_id}/account_data/m.invite_permission_config"
6376            )))
6377            .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
6378            .expect(1)
6379            .mount(server.server())
6380            .await;
6381
6382        let config = client.account().fetch_invite_permission_config().await.unwrap();
6383        // Invites are enabled.
6384        assert_eq!(config.unwrap().default_action, None);
6385    }
6386
6387    #[async_test]
6388    async fn test_fetch_missing_invite_permission_config() {
6389        use wiremock::{
6390            Mock, ResponseTemplate,
6391            matchers::{method, path},
6392        };
6393
6394        let server = MatrixMockServer::new().await;
6395        let client = server.client_builder().build().await;
6396        let user_id = client.user_id().unwrap();
6397
6398        Mock::given(method("GET"))
6399            .and(path(format!(
6400                "/_matrix/client/v3/user/{user_id}/account_data/m.invite_permission_config"
6401            )))
6402            .respond_with(ResponseTemplate::new(404).set_body_json(json!({
6403                "errcode": "M_NOT_FOUND",
6404                "error": "Account data not found"
6405            })))
6406            .expect(1)
6407            .mount(server.server())
6408            .await;
6409
6410        let config = client.account().fetch_invite_permission_config().await.unwrap();
6411
6412        // No config found.
6413        assert!(config.is_none());
6414    }
6415
6416    #[async_test]
6417    async fn test_get_disabled_invite_permission_config() {
6418        let server = MatrixMockServer::new().await;
6419        let client = server.client_builder().build().await;
6420
6421        server
6422            .mock_sync()
6423            .ok_and_run(&client, |builder| {
6424                builder.add_custom_global_account_data(json!({
6425                    "content": {
6426                        "default_action": "block"
6427                    },
6428                    "type": "m.invite_permission_config"
6429                }));
6430            })
6431            .await;
6432
6433        let config = client.account().get_invite_permission_config().await.unwrap();
6434
6435        // Invites are disabled.
6436        assert_eq!(config.unwrap().default_action, Some(InvitePermissionAction::Block));
6437    }
6438
6439    #[async_test]
6440    async fn test_get_enabled_invite_permission_config() {
6441        let server = MatrixMockServer::new().await;
6442        let client = server.client_builder().build().await;
6443
6444        server
6445            .mock_sync()
6446            .ok_and_run(&client, |builder| {
6447                builder.add_custom_global_account_data(json!({
6448                    "content": {},
6449                    "type": "m.invite_permission_config"
6450                }));
6451            })
6452            .await;
6453
6454        let config = client.account().get_invite_permission_config().await.unwrap();
6455
6456        assert!(config.is_some());
6457        // Invites are enabled.
6458        assert_eq!(config.unwrap().default_action, None);
6459    }
6460
6461    #[async_test]
6462    async fn test_get_invite_permission_config_not_found() {
6463        let server = MatrixMockServer::new().await;
6464        let client = server.client_builder().build().await;
6465
6466        let config = client.account().get_invite_permission_config().await.unwrap();
6467
6468        // No config found.
6469        assert!(config.is_none());
6470    }
6471
6472    #[async_test]
6473    async fn test_observe_invite_permission_config() {
6474        let server = MatrixMockServer::new().await;
6475        let client = server.client_builder().build().await;
6476
6477        // Room invitations are disabled.
6478        server
6479            .mock_sync()
6480            .ok_and_run(&client, |builder| {
6481                builder.add_custom_global_account_data(json!({
6482                    "content": {
6483                        "default_action": "block"
6484                    },
6485                    "type": "m.invite_permission_config"
6486                }));
6487            })
6488            .await;
6489
6490        let (initial_value, stream) =
6491            client.account().observe_invite_permission_config().await.unwrap();
6492
6493        let initial_value = initial_value.unwrap();
6494        assert_eq!(initial_value.default_action, Some(InvitePermissionAction::Block));
6495
6496        let mut stream = pin!(stream);
6497        assert_pending!(stream);
6498
6499        // Room invitations are enabled again.
6500        server
6501            .mock_sync()
6502            .ok_and_run(&client, |builder| {
6503                builder.add_custom_global_account_data(json!({
6504                    "content": {},
6505                    "type": "m.invite_permission_config"
6506                }));
6507            })
6508            .await;
6509
6510        assert_next_matches!(
6511            stream,
6512            InvitePermissionConfigEventContent { default_action: None, .. }
6513        );
6514        assert_pending!(stream);
6515    }
6516
6517    #[async_test]
6518    async fn test_observe_invite_permission_config_after_initial_subscription() {
6519        let server = MatrixMockServer::new().await;
6520        let client = server.client_builder().build().await;
6521
6522        let (initial_value, stream) =
6523            client.account().observe_invite_permission_config().await.unwrap();
6524
6525        // No config found.
6526        assert!(initial_value.is_none());
6527
6528        let mut stream = pin!(stream);
6529        assert_pending!(stream);
6530
6531        // Room invitations are disabled.
6532        server
6533            .mock_sync()
6534            .ok_and_run(&client, |builder| {
6535                builder.add_custom_global_account_data(json!({
6536                    "content": {
6537                        "default_action": "block"
6538                    },
6539                    "type": "m.invite_permission_config"
6540                }));
6541            })
6542            .await;
6543
6544        assert_next_matches!(
6545            stream,
6546            InvitePermissionConfigEventContent {
6547                default_action: Some(InvitePermissionAction::Block),
6548                ..
6549            }
6550        );
6551        assert_pending!(stream);
6552    }
6553
6554    #[async_test]
6555    async fn test_observe_invite_permission_config_not_found() {
6556        let server = MatrixMockServer::new().await;
6557        let client = server.client_builder().build().await;
6558
6559        let (initial_value, _) = client.account().observe_invite_permission_config().await.unwrap();
6560
6561        // No config found.
6562        assert!(initial_value.is_none());
6563    }
6564
6565    #[async_test]
6566    async fn test_get_dm_room_returns_the_room_we_have_with_this_user() {
6567        let server = MatrixMockServer::new().await;
6568        let client = server.client_builder().build().await;
6569        let user = User::Carol;
6570
6571        // When we receive a sync response saying the user is part of a DM.
6572        let f = EventFactory::new();
6573        server
6574            .mock_sync()
6575            .ok_and_run(&client, |builder| {
6576                builder
6577                    .add_joined_room(JoinedRoomBuilder::default().add_state_event(f.member(user)))
6578                    .add_global_account_data(f.direct().add_user(user, TestRoom::Default));
6579            })
6580            .await;
6581
6582        // Then get_dm_room finds this room
6583        let found_room = client.get_dm_room(user.into()).expect("DM not found!");
6584        assert!(found_room.get_member_no_sync(user.into()).await.unwrap().is_some());
6585    }
6586
6587    #[async_test]
6588    async fn test_get_dm_room_still_finds_room_where_participant_is_only_invited() {
6589        let server = MatrixMockServer::new().await;
6590        let client = server.client_builder().build().await;
6591        // This is the user that is invited.
6592        let user = User::Carol;
6593
6594        // When we receive a sync response saying "invited" is invited to a DM
6595        let f = EventFactory::new().sender(User::Alice);
6596        server
6597            .mock_sync()
6598            .ok_and_run(&client, |builder| {
6599                builder
6600                    .add_joined_room(
6601                        JoinedRoomBuilder::default()
6602                            .add_state_event(f.member(user).invited(user).display_name("example")),
6603                    )
6604                    .add_global_account_data(f.direct().add_user(user, TestRoom::Default));
6605            })
6606            .await;
6607
6608        // Then get_dm_room finds this room
6609        let found_room = client.get_dm_room(user.into()).expect("DM not found!");
6610        assert!(found_room.get_member_no_sync(user.into()).await.unwrap().is_some());
6611    }
6612
6613    #[async_test]
6614    async fn test_get_dm_room_still_finds_left_room() {
6615        // See the discussion in
6616        // https://github.com/matrix-org/matrix-rust-sdk/issues/2017 and the
6617        // high-level issue at
6618        // https://github.com/vector-im/element-x-ios/issues/1077
6619
6620        let server = MatrixMockServer::new().await;
6621        let client = server.client_builder().build().await;
6622        let user = User::Carol;
6623
6624        // When we receive a sync response saying "invited" has left a DM
6625        let f = EventFactory::new().sender(user);
6626        server
6627            .mock_sync()
6628            .ok_and_run(&client, |builder| {
6629                builder
6630                    .add_joined_room(
6631                        JoinedRoomBuilder::default().add_state_event(f.member(user).leave()),
6632                    )
6633                    .add_global_account_data(f.direct().add_user(user, TestRoom::Default));
6634            })
6635            .await;
6636
6637        // Then get_dm_room finds this room
6638        let found_room = client.get_dm_room(user.into()).expect("DM not found!");
6639        assert!(found_room.get_member_no_sync(user.into()).await.unwrap().is_some());
6640    }
6641
6642    #[async_test]
6643    async fn test_device_exists() {
6644        let server = MatrixMockServer::new().await;
6645        let client = server.client_builder().build().await;
6646
6647        server.mock_get_device().ok().expect(1).mount().await;
6648
6649        assert_matches!(client.device_exists(owned_device_id!("ABCDEF")).await, Ok(true));
6650    }
6651
6652    #[async_test]
6653    async fn test_device_exists_404() {
6654        let server = MatrixMockServer::new().await;
6655        let client = server.client_builder().build().await;
6656
6657        assert_matches!(client.device_exists(owned_device_id!("ABCDEF")).await, Ok(false));
6658    }
6659
6660    #[async_test]
6661    async fn test_device_exists_500() {
6662        let server = MatrixMockServer::new().await;
6663        let client = server.client_builder().build().await;
6664
6665        server.mock_get_device().error500().expect(1).mount().await;
6666
6667        assert_matches!(client.device_exists(owned_device_id!("ABCDEF")).await, Err(_));
6668    }
6669
6670    #[async_test]
6671    async fn test_fetching_well_known_with_homeserver_url() {
6672        let server = MatrixMockServer::new().await;
6673        let client = server.client_builder().build().await;
6674        server.mock_well_known().ok().mount().await;
6675
6676        assert_matches!(client.fetch_client_well_known().await, Some(_));
6677    }
6678
6679    #[async_test]
6680    async fn test_fetching_well_known_with_server_name() {
6681        let server = MatrixMockServer::new().await;
6682        let server_name = ServerName::parse(server.server().address().to_string()).unwrap();
6683
6684        server.mock_well_known().ok().mount().await;
6685
6686        let client = MockClientBuilder::new(None)
6687            .on_builder(|builder| builder.insecure_server_name_no_tls(&server_name))
6688            .build()
6689            .await;
6690
6691        assert_matches!(client.fetch_client_well_known().await, Some(_));
6692    }
6693
6694    #[async_test]
6695    async fn test_fetching_well_known_with_domain_part_of_user_id() {
6696        let server = MatrixMockServer::new().await;
6697        server.mock_well_known().ok().mount().await;
6698
6699        let user_id =
6700            UserId::parse(format!("@user:{}", server.server().address())).expect("Invalid user id");
6701        let client = MockClientBuilder::new(None)
6702            .logged_in_with_token("A_TOKEN".to_owned(), user_id, owned_device_id!("ABCDEF"))
6703            .build()
6704            .await;
6705
6706        assert_matches!(client.fetch_client_well_known().await, Some(_));
6707    }
6708
6709    #[cfg(feature = "e2e-encryption")]
6710    #[async_test]
6711    async fn test_syncing_one_time_key_counts_updates() -> Result<()> {
6712        use wiremock::ResponseTemplate;
6713
6714        macro_rules! assert_key_count {
6715            ($client: ident, $count:literal) => {{
6716                let machine = $client.olm_machine().await;
6717                let uploaded_key_counts =
6718                    machine.as_ref().unwrap().uploaded_key_count().await.unwrap();
6719                assert_eq!(uploaded_key_counts, $count)
6720            }};
6721        }
6722
6723        macro_rules! sync_with_key_count {
6724            ($client: ident, $server:ident, $count:literal) => {
6725                let count = Some($count);
6726                sync_with_key_count!($client, $server, count);
6727            };
6728            ($client: ident, $server:ident, $count:ident) => {{
6729                use rand::RngExt as _;
6730
6731                let next_batch: String = rand::rng()
6732                    .sample_iter(&rand::distr::Alphanumeric)
6733                    .take(16)
6734                    .map(char::from)
6735                    .collect();
6736
6737                let count: Option<u32> = $count;
6738
6739                let template = if let Some(count) = count {
6740                    ResponseTemplate::new(200).set_body_json(json!({
6741                        "next_batch": next_batch,
6742                        "rooms": {"leave": {}, "join": {}, "invite": {}},
6743                        "device_lists": {
6744                          "changed": [],
6745                          "left": [],
6746                        },
6747                        "device_one_time_keys_count": {
6748                          "signed_curve25519": count
6749                        },
6750                    }))
6751                } else {
6752                    ResponseTemplate::new(200).set_body_json(json!({
6753                        "next_batch": next_batch,
6754                        "rooms": {"leave": {}, "join": {}, "invite": {}},
6755                        "device_lists": {
6756                          "changed": [],
6757                          "left": [],
6758                        },
6759                        "device_one_time_keys_count": {},
6760                    }))
6761                };
6762
6763                let _sync_mock_guard = $server.mock_sync().respond_with(template).mount_as_scoped().await;
6764                $client.sync_once(Default::default()).await?;
6765            }}
6766        }
6767
6768        let server = MatrixMockServer::new().await;
6769        let client = server.client_builder().build().await;
6770
6771        server.mock_upload_keys().ok_with_signed_curve_key_count(50).mock_once().mount().await;
6772
6773        // In the beginning there were no uploaded keys.
6774        assert_key_count!(client, 0);
6775
6776        // The first sync will upload 50 one-time keys.
6777        sync_with_key_count!(client, server, 50);
6778        assert_key_count!(client, 50);
6779
6780        // Syncing with a key count, will update the key count.
6781        sync_with_key_count!(client, server, 10);
6782        assert_key_count!(client, 10);
6783
6784        // Syncing with no key count will set the key count to zero.
6785        sync_with_key_count!(client, server, None);
6786        assert_key_count!(client, 0);
6787
6788        Ok(())
6789    }
6790
6791    #[async_test]
6792    async fn test_fetch_retention_configuration() {
6793        let server = MatrixMockServer::new().await;
6794        let client = server.client_builder().build().await;
6795
6796        server.mock_get_retention_configuration().ok_empty().mock_once().mount().await;
6797
6798        let response = client.fetch_retention_configuration().await;
6799        assert!(response.is_ok());
6800        let response = response.unwrap().unwrap();
6801        assert!(response.policies.is_empty());
6802        assert!(response.limits.max_lifetime.is_none());
6803        assert!(response.limits.min_lifetime.is_none());
6804    }
6805
6806    #[async_test]
6807    async fn test_retention_configuration_is_cached_and_observable() {
6808        let server = MatrixMockServer::new().await;
6809        let client = server.client_builder().build().await;
6810
6811        let mut subscriber = client.subscribe_to_retention_configuration();
6812        assert!(subscriber.get().is_none());
6813
6814        server
6815            .mock_get_retention_configuration()
6816            .ok_empty()
6817            // Only the first call hits the network, the second one uses the cache.
6818            .mock_once()
6819            .mount()
6820            .await;
6821
6822        client.retention_configuration().await.unwrap();
6823
6824        assert_next_matches!(subscriber, Some(cached) => {
6825            assert!(!cached.has_expired_after(super::RETENTION_CONFIGURATION_TTL));
6826        });
6827
6828        client.retention_configuration().await.unwrap();
6829        assert_pending!(subscriber);
6830    }
6831
6832    #[async_test]
6833    async fn test_retention_configuration_is_persisted() {
6834        let server = MatrixMockServer::new().await;
6835        let memory_store = Arc::new(MemoryStore::new());
6836        let build_client = || {
6837            server
6838                .client_builder()
6839                .on_builder(|builder| {
6840                    builder.store_config(
6841                        StoreConfig::new(CrossProcessLockConfig::SingleProcess)
6842                            .state_store(memory_store.clone()),
6843                    )
6844                })
6845                .build()
6846        };
6847
6848        {
6849            let _guard = server
6850                .mock_get_retention_configuration()
6851                .ok(
6852                    BTreeMap::from([(
6853                        RoomIdOrAllRooms::AllRooms,
6854                        RoomRetentionEventContent::new()
6855                            .at_most(Duration::from_secs(24 * 60 * 60))
6856                            .unwrap(),
6857                    )]),
6858                    RetentionLimits::default(),
6859                )
6860                .mock_once()
6861                .mount_as_scoped()
6862                .await;
6863
6864            let client = build_client().await;
6865            assert!(client.subscribe_to_retention_configuration().get().is_none());
6866            client.fetch_retention_configuration().await.unwrap();
6867        }
6868
6869        // A new client using the same store gets the persisted value, without
6870        // any request to the homeserver.
6871        let client = build_client().await;
6872
6873        let cached = client
6874            .subscribe_to_retention_configuration()
6875            .get()
6876            .expect("the retention configuration should have been loaded from the store");
6877        assert_eq!(cached.data().policies.len(), 1);
6878
6879        let config = client.retention_configuration().await.unwrap().unwrap();
6880        assert_eq!(config.policies.len(), 1);
6881    }
6882
6883    #[async_test]
6884    async fn test_retention_configuration_falls_back_to_stale_value() {
6885        let server = MatrixMockServer::new().await;
6886        let client = server
6887            .client_builder()
6888            .on_builder(|builder| builder.request_config(RequestConfig::new().disable_retry()))
6889            .build()
6890            .await;
6891
6892        {
6893            let _guard = server
6894                .mock_get_retention_configuration()
6895                .ok(
6896                    BTreeMap::from([(
6897                        RoomIdOrAllRooms::AllRooms,
6898                        RoomRetentionEventContent::new()
6899                            .at_most(Duration::from_secs(24 * 60 * 60))
6900                            .unwrap(),
6901                    )]),
6902                    RetentionLimits::default(),
6903                )
6904                .mock_once()
6905                .mount_as_scoped()
6906                .await;
6907
6908            client.fetch_retention_configuration().await.unwrap();
6909        }
6910
6911        // Expire the cached value.
6912        let mut cached = client.inner.caches.retention_configuration.get().unwrap();
6913        cached.expire();
6914        client.inner.caches.retention_configuration.set(Some(cached));
6915
6916        // The homeserver is unreachable: the stale value is returned.
6917        {
6918            let _guard = server
6919                .mock_get_retention_configuration()
6920                .error500()
6921                .mock_once()
6922                .mount_as_scoped()
6923                .await;
6924
6925            let config = client.retention_configuration().await.unwrap().unwrap();
6926            assert_eq!(config.policies.len(), 1);
6927        }
6928
6929        // The homeserver doesn't implement the endpoint: `None` is returned,
6930        // even though a stale value is cached.
6931        {
6932            let _guard = server
6933                .mock_get_retention_configuration()
6934                .error_unrecognized()
6935                .mock_once()
6936                .mount_as_scoped()
6937                .await;
6938
6939            let config = client.retention_configuration().await.unwrap();
6940            assert!(config.is_none());
6941        }
6942    }
6943
6944    #[async_test]
6945    async fn test_wait_for_sync() {
6946        let server = MatrixMockServer::new().await;
6947        let client = server.client_builder().build().await;
6948
6949        let num_syncs = AtomicU32::new(0);
6950
6951        assert_eq!(num_syncs.load(Ordering::SeqCst), 0);
6952
6953        // Spawn a task that waits for 2 syncs in the background.
6954        let client_clone = client.clone();
6955        let task = spawn(async move {
6956            client_clone.wait_for_sync().await;
6957            client_clone.wait_for_sync().await;
6958        });
6959
6960        // Sync once,
6961        server
6962            .mock_sync()
6963            .ok_and_run(&client, |_| {
6964                num_syncs.fetch_add(1, Ordering::SeqCst);
6965            })
6966            .await;
6967
6968        assert_eq!(num_syncs.load(Ordering::SeqCst), 1);
6969
6970        // Sync twice,
6971        server
6972            .mock_sync()
6973            .ok_and_run(&client, |_| {
6974                num_syncs.fetch_add(1, Ordering::SeqCst);
6975            })
6976            .await;
6977
6978        assert_eq!(num_syncs.load(Ordering::SeqCst), 2);
6979
6980        // The two waits should have completed by now!
6981        timeout(Duration::from_secs(1), task)
6982            .await
6983            .expect("no timeout")
6984            .expect("task didn't panick");
6985    }
6986
6987    #[async_test]
6988    async fn test_observe_total_unread_notifications() {
6989        let server = MatrixMockServer::new().await;
6990        let client = server.client_builder().build().await;
6991        let f = EventFactory::new();
6992
6993        let set_num_notifications = async |room: &crate::Room, num: u64| {
6994            room.update_room_info(|mut room_info| {
6995                room_info.set_read_receipts(ReadReceipts {
6996                    num_notifications: num,
6997                    ..Default::default()
6998                });
6999                (room_info, RoomInfoNotableUpdateReasons::READ_RECEIPT)
7000            })
7001            .await;
7002        };
7003
7004        let room = server.sync_default_joined_room(&client).await;
7005        set_num_notifications(&room, 1).await;
7006
7007        let min_interval = Duration::from_millis(100);
7008        let mut stream = pin!(client.observe_total_unread_notifications(min_interval));
7009
7010        // The current value is emitted right away when subscribing.
7011        assert_next_eq_with_timeout!(stream, 1);
7012        assert_pending!(stream);
7013
7014        // Several updates in a short amount of time are coalesced, and only the
7015        // latest value is emitted, once the interval is over.
7016        set_num_notifications(&room, 3).await;
7017        set_num_notifications(&room, 5).await;
7018
7019        assert_next_eq_with_timeout!(stream, 5, 300 ms);
7020        assert_pending!(stream);
7021
7022        // An update that doesn't change the total doesn't emit a new value.
7023        set_num_notifications(&room, 5).await;
7024        assert!(timeout(min_interval * 3, stream.next()).await.is_err());
7025
7026        // Marking another room as unread adds one to the total.
7027        server
7028            .sync_room(
7029                &client,
7030                JoinedRoomBuilder::new(TestRoom::V12).add_account_data(f.marked_unread(true)),
7031            )
7032            .await;
7033
7034        assert_next_eq_with_timeout!(stream, 6, 300 ms);
7035        assert_pending!(stream);
7036    }
7037}