Skip to main content

matrix_sdk/room/
mod.rs

1// Copyright 2024 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! High-level room API
16
17use std::{
18    borrow::Borrow,
19    collections::{BTreeMap, HashMap},
20    future::Future,
21    ops::Deref,
22    sync::Arc,
23    time::Duration,
24};
25
26use async_stream::stream;
27use eyeball::SharedObservable;
28use futures_core::Stream;
29use futures_util::{
30    StreamExt, future::join_all, stream as futures_stream, stream::FuturesUnordered,
31};
32use http::StatusCode;
33#[cfg(feature = "e2e-encryption")]
34pub use identity_status_changes::IdentityStatusChanges;
35#[cfg(feature = "experimental-encrypted-state-events")]
36use matrix_sdk_base::crypto::types::events::room::encrypted::EncryptedEvent;
37#[cfg(feature = "e2e-encryption")]
38use matrix_sdk_base::crypto::{
39    IdentityStatusChange, RoomIdentityProvider, UserIdentity, types::events::CryptoContextInfo,
40};
41pub use matrix_sdk_base::store::StoredThreadSubscription;
42use matrix_sdk_base::{
43    ComposerDraft, DmRoomDefinition, EncryptionState, RoomInfoNotableUpdateReasons,
44    RoomMemberships, SendOutsideWasm, StateStoreDataKey, StateStoreDataValue,
45    deserialized_responses::{
46        RawAnySyncOrStrippedState, RawSyncOrStrippedState, SyncOrStrippedState,
47    },
48    media::{MediaThumbnailSettings, store::IgnoreMediaRetentionPolicy},
49    serde_helpers::extract_relation,
50    store::{StateStoreExt, ThreadSubscriptionStatus},
51};
52#[cfg(feature = "e2e-encryption")]
53use matrix_sdk_base::{crypto::RoomEventDecryptionResult, deserialized_responses::EncryptionInfo};
54#[cfg(feature = "e2e-encryption")]
55use matrix_sdk_common::BoxFuture;
56use matrix_sdk_common::{
57    deserialized_responses::TimelineEvent,
58    executor::{JoinHandle, spawn},
59    timeout::timeout,
60};
61use mime::Mime;
62use reply::Reply;
63#[cfg(feature = "unstable-msc4536")]
64use ruma::api::FeatureFlag;
65#[cfg(feature = "e2e-encryption")]
66use ruma::events::AnySyncMessageLikeEvent;
67#[cfg(feature = "experimental-encrypted-state-events")]
68use ruma::events::AnySyncStateEvent;
69#[cfg(feature = "unstable-msc4274")]
70use ruma::events::room::message::GalleryItemType;
71#[cfg(feature = "e2e-encryption")]
72use ruma::events::{
73    AnySyncTimelineEvent, SyncMessageLikeEvent, room::encrypted::OriginalSyncRoomEncryptedEvent,
74};
75use ruma::{
76    EventId, Int, MatrixToUri, MatrixUri, MxcUri, OwnedEventId, OwnedRoomId, OwnedServerName,
77    OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UInt, UserId,
78    api::{
79        client::{
80            config::{set_global_account_data, set_room_account_data},
81            context,
82            filter::LazyLoadOptions,
83            membership::{
84                Invite3pid, ban_user, forget_room, get_member_events,
85                invite_user::{
86                    self,
87                    v3::{InvitationRecipient, InviteUserId},
88                },
89                kick_user, leave_room, unban_user,
90            },
91            message::send_message_event,
92            read_marker::set_read_marker,
93            receipt::create_receipt,
94            redact::redact_event,
95            retention::get_retention_configuration,
96            room::{get_room_event, report_content, report_room},
97            state::{get_state_event_for_key, send_state_event},
98            tag::{create_tag, delete_tag},
99            threads::{get_thread_subscription, subscribe_thread, unsubscribe_thread},
100            typing::create_typing_event::{
101                self,
102                v3::{Typing, TypingInfo},
103            },
104        },
105        error::ErrorKind,
106    },
107    assign,
108    events::{
109        AnyRoomAccountDataEvent, AnyRoomAccountDataEventContent, AnyTimelineEvent, EmptyStateKey,
110        Mentions, MessageLikeEventContent, OriginalSyncStateEvent, RedactContent,
111        RedactedStateEventContent, RoomAccountDataEvent, RoomAccountDataEventContent,
112        RoomAccountDataEventType, StateEventContent, StateEventType, StaticEventContent,
113        StaticStateEventContent, SyncStateEvent,
114        beacon::BeaconEventContent,
115        beacon_info::BeaconInfoEventContent,
116        direct::DirectEventContent,
117        marked_unread::MarkedUnreadEventContent,
118        receipt::{Receipt, ReceiptThread, ReceiptType},
119        relation::RelationType,
120        room::{
121            ImageInfo, MediaSource, ThumbnailInfo,
122            avatar::{self, RoomAvatarEventContent},
123            encryption::PossiblyRedactedRoomEncryptionEventContent,
124            history_visibility::HistoryVisibility,
125            member::{MembershipChange, RoomMemberEventContent, SyncRoomMemberEvent},
126            message::{
127                AudioInfo, AudioMessageEventContent, FileInfo, FileMessageEventContent,
128                ImageMessageEventContent, MessageType, RoomMessageEventContent,
129                TextMessageEventContent, UnstableAmplitude, UnstableAudioDetailsContentBlock,
130                UnstableVoiceContentBlock, VideoInfo, VideoMessageEventContent,
131            },
132            name::RoomNameEventContent,
133            pinned_events::RoomPinnedEventsEventContent,
134            power_levels::{
135                RoomPowerLevels, RoomPowerLevelsEventContent, RoomPowerLevelsSource, UserPowerLevel,
136            },
137            retention::RoomRetentionEventContent,
138            server_acl::RoomServerAclEventContent,
139            topic::RoomTopicEventContent,
140        },
141        space::{child::SpaceChildEventContent, parent::SpaceParentEventContent},
142        tag::{TagInfo, TagName},
143        typing::SyncTypingEvent,
144    },
145    int,
146    push::{Action, AnyPushRuleRef, PushConditionRoomCtx, Ruleset},
147    serde::Raw,
148    time::Instant,
149    uint,
150};
151#[cfg(feature = "experimental-encrypted-state-events")]
152use ruma::{
153    events::room::encrypted::unstable_state::OriginalSyncStateRoomEncryptedEvent,
154    serde::JsonCastable,
155};
156use serde::de::DeserializeOwned;
157use thiserror::Error;
158use tokio::{join, sync::broadcast};
159use tracing::{debug, error, info, instrument, trace, warn};
160
161use self::futures::{
162    SendAttachment, SendMessageLikeEvent, SendRawMessageLikeEvent, SendRawStateEvent,
163};
164pub use self::{
165    member::{RoomMember, RoomMemberRole},
166    messages::{
167        EventWithContextResponse, IncludeRelations, ListThreadsOptions, Messages, MessagesOptions,
168        Relations, RelationsOptions, ThreadRoots,
169    },
170};
171#[cfg(feature = "e2e-encryption")]
172use crate::encryption::backups::BackupState;
173#[cfg(doc)]
174use crate::event_cache::EventCache;
175#[cfg(feature = "experimental-encrypted-state-events")]
176use crate::room::futures::SendStateEvent;
177use crate::{
178    BaseRoom, Client, Error, HttpResult, Result, RoomState, TransmissionProgress,
179    attachment::{AttachmentConfig, AttachmentInfo},
180    client::WeakClient,
181    config::RequestConfig,
182    error::{BeaconError, WrongRoomState},
183    event_handler::{EventHandler, EventHandlerDropGuard, EventHandlerHandle, SyncEvent},
184    live_locations_observer::LiveLocationsObserver,
185    media::{MediaFormat, MediaRequestParameters},
186    notification_settings::{IsEncrypted, IsOneToOne, RoomNotificationMode},
187    room::{
188        knock_requests::{KnockRequest, KnockRequestMemberInfo},
189        power_levels::{RoomPowerLevelChanges, RoomPowerLevelsExt},
190        privacy_settings::RoomPrivacySettings,
191    },
192    sync::{RoomUpdate, State},
193    utils::{IntoRawMessageLikeEventContent, IntoRawStateEventContent},
194};
195
196pub mod edit;
197pub mod futures;
198pub mod identity_status_changes;
199/// Contains code related to requests to join a room.
200pub mod knock_requests;
201mod member;
202mod messages;
203pub mod power_levels;
204pub mod reply;
205
206pub mod calls;
207
208/// Contains all the functionality for modifying the privacy settings in a room.
209pub mod privacy_settings;
210
211#[cfg(feature = "e2e-encryption")]
212pub(crate) mod shared_room_history;
213
214/// A struct containing methods that are common for Joined, Invited and Left
215/// Rooms
216#[derive(Debug, Clone)]
217pub struct Room {
218    inner: BaseRoom,
219    pub(crate) client: Client,
220}
221
222impl Deref for Room {
223    type Target = BaseRoom;
224
225    fn deref(&self) -> &Self::Target {
226        &self.inner
227    }
228}
229
230const TYPING_NOTICE_TIMEOUT: Duration = Duration::from_secs(4);
231const TYPING_NOTICE_RESEND_TIMEOUT: Duration = Duration::from_secs(3);
232
233/// A thread subscription, according to the semantics of MSC4306.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub struct ThreadSubscription {
236    /// Whether the subscription was made automatically by a client, not by
237    /// manual user choice.
238    pub automatic: bool,
239}
240
241/// Context allowing to compute the push actions for a given event.
242#[derive(Debug)]
243pub struct PushContext {
244    /// The Ruma context used to compute the push actions.
245    push_condition_room_ctx: PushConditionRoomCtx,
246
247    /// Push rules for this room, based on the push rules state event, or the
248    /// global server default as defined by [`Ruleset::server_default`].
249    push_rules: Ruleset,
250}
251
252impl PushContext {
253    /// Create a new [`PushContext`] from its inner components.
254    pub fn new(push_condition_room_ctx: PushConditionRoomCtx, push_rules: Ruleset) -> Self {
255        Self { push_condition_room_ctx, push_rules }
256    }
257
258    /// Compute the push rules for a given event.
259    pub async fn for_event<T>(&self, event: &Raw<T>) -> Vec<Action> {
260        self.push_rules.get_actions(event, &self.push_condition_room_ctx).await.to_owned()
261    }
262
263    /// Compute the push rules for a given event, with extra logging to help
264    /// debugging.
265    #[doc(hidden)]
266    #[instrument(skip_all)]
267    pub async fn traced_for_event<T>(&self, event: &Raw<T>) -> Vec<Action> {
268        let rules = self
269            .push_rules
270            .iter()
271            .filter_map(|r| {
272                if !r.enabled() {
273                    return None;
274                }
275
276                let simplified_action = if r.actions().is_empty() { "inhibit" } else { "notify" };
277
278                let conditions = match r {
279                    AnyPushRuleRef::Override(r) => {
280                        format!("{:?}", r.conditions)
281                    }
282                    AnyPushRuleRef::Content(r) => format!("content-body-match:{}", r.pattern),
283                    AnyPushRuleRef::Room(r) => format!("room-match:{}", r.rule_id),
284                    AnyPushRuleRef::Sender(r) => format!("sender-match:{}", r.rule_id),
285                    AnyPushRuleRef::Underride(r) => format!("{:?}", r.conditions),
286                    _ => "<unknown push rule kind>".to_owned(),
287                };
288
289                Some(format!("- {}: {conditions} => {simplified_action}", r.rule_id(),))
290            })
291            .collect::<Vec<_>>()
292            .join("\n");
293        trace!("rules:\n\n{rules}\n\n");
294
295        let found = self.push_rules.get_match(event, &self.push_condition_room_ctx).await;
296
297        if let Some(found) = found {
298            trace!("rule {} matched", found.rule_id());
299            found.actions().to_owned()
300        } else {
301            trace!("no match");
302            Vec::new()
303        }
304    }
305}
306
307macro_rules! make_media_type {
308    ($t:ty, $content_type: ident, $filename: ident, $source: ident, $caption: ident, $info: ident, $thumbnail: ident) => {{
309        // If caption is set, use it as body, and filename as the file name;
310        // otherwise, body is the filename, and the filename is not set.
311        // https://github.com/matrix-org/matrix-spec-proposals/blob/main/proposals/2530-body-as-caption.md
312        let (body, formatted, filename) = match $caption {
313            Some(TextMessageEventContent { body, formatted, .. }) => (body, formatted, Some($filename)),
314            None => ($filename, None, None),
315        };
316
317        let (thumbnail_source, thumbnail_info) = $thumbnail.unzip();
318
319        match $content_type.type_() {
320            mime::IMAGE => {
321                let info = assign!($info.map(ImageInfo::from).unwrap_or_default(), {
322                    mimetype: Some($content_type.as_ref().to_owned()),
323                    thumbnail_source,
324                    thumbnail_info
325                });
326                let content = assign!(ImageMessageEventContent::new(body, $source), {
327                    info: Some(Box::new(info)),
328                    formatted,
329                    filename
330                });
331                <$t>::Image(content)
332            }
333
334            mime::AUDIO => {
335                let mut content = assign!(AudioMessageEventContent::new(body, $source), {
336                    formatted,
337                    filename
338                });
339
340                if let Some(AttachmentInfo::Audio(audio_info) | AttachmentInfo::Voice(audio_info)) = &$info &&
341                 let Some(duration) = audio_info.duration && let Some(waveform_vec) = &audio_info.waveform {
342                    let waveform = waveform_vec
343                        .iter()
344                        .map(|v| ((*v).clamp(0.0, 1.0) * UnstableAmplitude::MAX as f32) as u16)
345                        .map(Into::into)
346                        .collect();
347                    content.audio =
348                        Some(UnstableAudioDetailsContentBlock::new(duration, waveform));
349                }
350
351                if matches!($info, Some(AttachmentInfo::Voice(_))) {
352                    content.voice = Some(UnstableVoiceContentBlock::new());
353                }
354
355                let mut audio_info = $info.map(AudioInfo::from).unwrap_or_default();
356                audio_info.mimetype = Some($content_type.as_ref().to_owned());
357                let content = content.info(Box::new(audio_info));
358
359                <$t>::Audio(content)
360            }
361
362            mime::VIDEO => {
363                #[cfg(feature = "unstable-msc4546")]
364                let circle = match &$info {
365                    Some(AttachmentInfo::Video(video_info)) => video_info.circle,
366                    _ => false,
367                };
368                let info = assign!($info.map(VideoInfo::from).unwrap_or_default(), {
369                    mimetype: Some($content_type.as_ref().to_owned()),
370                    thumbnail_source,
371                    thumbnail_info
372                });
373                let content = assign!(VideoMessageEventContent::new(body, $source), {
374                    info: Some(Box::new(info)),
375                    formatted,
376                    filename,
377                });
378                #[cfg(feature = "unstable-msc4546")]
379                let content = content.circle(circle);
380                <$t>::Video(content)
381            }
382
383            _ => {
384                let info = assign!($info.map(FileInfo::from).unwrap_or_default(), {
385                    mimetype: Some($content_type.as_ref().to_owned()),
386                    thumbnail_source,
387                    thumbnail_info
388                });
389                let content = assign!(FileMessageEventContent::new(body, $source), {
390                    info: Some(Box::new(info)),
391                    formatted,
392                    filename,
393                });
394                <$t>::File(content)
395            }
396        }
397    }};
398}
399
400impl Room {
401    /// Create a new `Room`
402    ///
403    /// # Arguments
404    ///
405    /// - `client` - The client used to make requests.
406    /// - `room` - The underlying room.
407    pub(crate) fn new(client: Client, room: BaseRoom) -> Self {
408        Self { inner: room, client }
409    }
410
411    /// Leave this room. If the room was in [`RoomState::Invited`] state, it'll
412    /// also be forgotten automatically.
413    ///
414    /// Only invited and joined rooms can be left.
415    #[doc(alias = "reject_invitation")]
416    #[instrument(skip_all, fields(room_id = ?self.inner.room_id()))]
417    async fn leave_impl(&self) -> (Result<()>, &Room) {
418        let state = self.state();
419        if state == RoomState::Left {
420            return (
421                Err(Error::WrongRoomState(Box::new(WrongRoomState::new(
422                    "Joined or Invited",
423                    state,
424                )))),
425                self,
426            );
427        }
428
429        // If the room was in Invited state we should also forget it when
430        // declining the invite.
431        let should_forget = matches!(self.state(), RoomState::Invited);
432
433        let request = leave_room::v3::Request::new(self.inner.room_id().to_owned());
434        let response = self.client.send(request).await;
435
436        // The server can return with an error that is acceptable to ignore.
437        // Let's find which one.
438        if let Err(error) = response {
439            #[allow(clippy::collapsible_match)]
440            let ignore_error = if let Some(error) = error.client_api_error_kind() {
441                match error {
442                    // The user is trying to leave a room but doesn't have
443                    // permissions to do so. Let's consider the user has left
444                    // the room.
445                    ErrorKind::Forbidden => true,
446                    _ => false,
447                }
448            } else {
449                false
450            };
451
452            error!(?error, ignore_error, should_forget, "Failed to leave the room");
453
454            if !ignore_error {
455                return (Err(error.into()), self);
456            }
457        }
458
459        if let Err(e) = self.client.base_client().room_left(self.room_id()).await {
460            return (Err(e.into()), self);
461        }
462
463        if should_forget {
464            trace!("Trying to forget the room");
465
466            if let Err(error) = self.forget().await {
467                error!(?error, "Failed to forget the room");
468            }
469        }
470
471        (Ok(()), self)
472    }
473
474    /// Leave this room and all predecessors. If any room was in
475    /// [`RoomState::Invited`] state, it'll also be forgotten automatically.
476    ///
477    /// Only invited and joined rooms can be left. Will return an error if the
478    /// current room fails to leave but will only warn if a predecessor fails to
479    /// leave.
480    pub async fn leave(&self) -> Result<()> {
481        let mut rooms: Vec<Room> = vec![self.clone()];
482        let mut current_room = self;
483
484        while let Some(predecessor) = current_room.predecessor_room() {
485            let maybe_predecessor_room = current_room.client.get_room(&predecessor.room_id);
486
487            if let Some(predecessor_room) = maybe_predecessor_room {
488                rooms.push(predecessor_room);
489                current_room = rooms.last().expect("Room just pushed so can't be empty");
490            } else {
491                warn!("Cannot find predecessor room");
492                break;
493            }
494        }
495
496        let batch_size = 5;
497
498        let rooms_futures: Vec<_> = rooms
499            .iter()
500            .filter_map(|room| match room.state() {
501                RoomState::Joined | RoomState::Invited | RoomState::Knocked => {
502                    Some(room.leave_impl())
503                }
504                RoomState::Banned | RoomState::Left => None,
505            })
506            .collect();
507
508        let mut futures_stream = futures_stream::iter(rooms_futures).buffer_unordered(batch_size);
509
510        let mut maybe_this_room_failed_with: Option<Error> = None;
511
512        while let Some(result) = futures_stream.next().await {
513            if let (Err(e), room) = result {
514                if room.room_id() == self.room_id() {
515                    maybe_this_room_failed_with = Some(e);
516                } else {
517                    warn!("Failure while attempting to leave predecessor room: {e:?}");
518                }
519            }
520        }
521
522        maybe_this_room_failed_with.map_or(Ok(()), Err)
523    }
524
525    /// Join this room.
526    ///
527    /// Only invited and left rooms can be joined via this method.
528    #[doc(alias = "accept_invitation")]
529    pub async fn join(&self) -> Result<()> {
530        let prev_room_state = self.inner.state();
531
532        if prev_room_state == RoomState::Joined {
533            return Err(Error::WrongRoomState(Box::new(WrongRoomState::new(
534                "Invited or Left",
535                prev_room_state,
536            ))));
537        }
538
539        self.client.join_room_by_id(self.room_id()).await?;
540
541        Ok(())
542    }
543
544    /// Get the inner client saved in this room instance.
545    ///
546    /// Returns the client this room is part of.
547    pub fn client(&self) -> Client {
548        self.client.clone()
549    }
550
551    /// Get the sync state of this room, i.e. whether it was fully synced with
552    /// the server.
553    pub fn is_synced(&self) -> bool {
554        self.inner.is_state_fully_synced()
555    }
556
557    /// Gets the avatar of this room, if set.
558    ///
559    /// Returns the avatar. If a thumbnail is requested no guarantee on the size
560    /// of the image is given.
561    ///
562    /// # Arguments
563    ///
564    /// - `format` - The desired format of the avatar.
565    ///
566    /// # Examples
567    ///
568    /// ```no_run
569    /// # use matrix_sdk::Client;
570    /// # use matrix_sdk::ruma::room_id;
571    /// # use matrix_sdk::media::MediaFormat;
572    /// # use url::Url;
573    /// # let homeserver = Url::parse("http://example.com").unwrap();
574    /// # async {
575    /// # let user = "example";
576    /// let client = Client::new(homeserver).await.unwrap();
577    /// client.matrix_auth().login_username(user, "password").send().await.unwrap();
578    /// let room_id = room_id!("!roomid:example.com");
579    /// let room = client.get_room(&room_id).unwrap();
580    /// if let Some(avatar) = room.avatar(MediaFormat::File).await.unwrap() {
581    ///     std::fs::write("avatar.png", avatar);
582    /// }
583    /// # };
584    /// ```
585    pub async fn avatar(&self, format: MediaFormat) -> Result<Option<Vec<u8>>> {
586        let Some(url) = self.avatar_url() else { return Ok(None) };
587        let request = MediaRequestParameters { source: MediaSource::Plain(url.to_owned()), format };
588        Ok(Some(self.client.media().get_media_content(&request, true).await?))
589    }
590
591    /// Sends a request to `/_matrix/client/r0/rooms/{room_id}/messages` and
592    /// returns a `Messages` struct that contains a chunk of room and state
593    /// events (`RoomEvent` and `AnyStateEvent`).
594    ///
595    /// With the encryption feature, messages are decrypted if possible. If
596    /// decryption fails for an individual message, that message is returned
597    /// undecrypted.
598    ///
599    /// # Examples
600    ///
601    /// ```no_run
602    /// use matrix_sdk::{Client, room::MessagesOptions};
603    /// # use matrix_sdk::ruma::{
604    /// #     api::client::filter::RoomEventFilter,
605    /// #     room_id,
606    /// # };
607    /// # use url::Url;
608    ///
609    /// # let homeserver = Url::parse("http://example.com").unwrap();
610    /// # async {
611    /// let options =
612    ///     MessagesOptions::backward().from("t47429-4392820_219380_26003_2265");
613    ///
614    /// let mut client = Client::new(homeserver).await.unwrap();
615    /// let room = client.get_room(room_id!("!roomid:example.com")).unwrap();
616    /// assert!(room.messages(options).await.is_ok());
617    /// # };
618    /// ```
619    #[instrument(skip_all, fields(room_id = ?self.inner.room_id(), ?options))]
620    pub async fn messages(&self, options: MessagesOptions) -> Result<Messages> {
621        let room_id = self.inner.room_id();
622        let request = options.into_request(room_id);
623        let http_response = self.client.send(request).await?;
624
625        let push_ctx = self.push_context().await?;
626        let chunk = join_all(
627            http_response.chunk.into_iter().map(|ev| self.try_decrypt_event(ev, push_ctx.as_ref())),
628        )
629        .await;
630
631        Ok(Messages {
632            start: http_response.start,
633            end: http_response.end,
634            chunk,
635            state: http_response.state,
636        })
637    }
638
639    /// Register a handler for events of a specific type, within this room.
640    ///
641    /// This method works the same way as [`Client::add_event_handler`], except
642    /// that the handler will only be called for events within this room. See
643    /// that method for more details on event handler functions.
644    ///
645    /// `room.add_event_handler(hdl)` is equivalent to
646    /// `client.add_room_event_handler(room_id, hdl)`. Use whichever one is more
647    /// convenient in your use case.
648    pub fn add_event_handler<Ev, Ctx, H>(&self, handler: H) -> EventHandlerHandle
649    where
650        Ev: SyncEvent + DeserializeOwned + Send + 'static,
651        H: EventHandler<Ev, Ctx>,
652    {
653        self.client.add_room_event_handler(self.room_id(), handler)
654    }
655
656    /// Subscribe to all updates for this room.
657    ///
658    /// The returned receiver will receive a new message for each sync response
659    /// that contains updates for this room.
660    pub fn subscribe_to_updates(&self) -> broadcast::Receiver<RoomUpdate> {
661        self.client.subscribe_to_room_updates(self.room_id())
662    }
663
664    /// Subscribe to typing notifications for this room.
665    ///
666    /// The returned receiver will receive a new vector of user IDs for each
667    /// sync response that contains 'm.typing' event. The current user ID will
668    /// be filtered out.
669    pub fn subscribe_to_typing_notifications(
670        &self,
671    ) -> (EventHandlerDropGuard, broadcast::Receiver<Vec<OwnedUserId>>) {
672        let (sender, receiver) = broadcast::channel(16);
673        let typing_event_handler_handle = self.client.add_room_event_handler(self.room_id(), {
674            let own_user_id = self.own_user_id().to_owned();
675            move |event: SyncTypingEvent| async move {
676                // Ignore typing notifications from own user.
677                let typing_user_ids = event
678                    .content
679                    .user_ids
680                    .into_iter()
681                    .filter(|user_id| *user_id != own_user_id)
682                    .collect();
683                // Ignore the result. It can only fail if there are no
684                // listeners.
685                let _ = sender.send(typing_user_ids);
686            }
687        });
688        let drop_guard = self.client().event_handler_drop_guard(typing_event_handler_handle);
689        (drop_guard, receiver)
690    }
691
692    /// Subscribe to the state events of a given type in this room.
693    ///
694    /// The returned stream yields the full list of state events of that type,
695    /// one per state key, as [`get_state_events()`][Self::get_state_events]
696    /// would return it: first as it currently is, then after every sync
697    /// response that reported state changes of that type for this room.
698    ///
699    /// Reading the state can fail, in which case the error is yielded and the
700    /// stream carries on with the next sync. The stream ends when the
701    /// [`Client`] is dropped.
702    pub fn subscribe_to_state_events(
703        &self,
704        event_type: StateEventType,
705    ) -> impl Stream<Item = Result<Vec<RawAnySyncOrStrippedState>>> + use<> {
706        let room = self.clone();
707        let mut room_updates = self.subscribe_to_updates();
708
709        stream! {
710            // Emit the current state first. We subscribed to the room updates
711            // before reading it, so a change happening in between isn't missed;
712            // it may be reported twice instead, which is harmless for a
713            // snapshot.
714            yield room.get_state_events(event_type.clone()).await;
715
716            loop {
717                match room_updates.recv().await {
718                    Ok(update) => {
719                        if !has_state_events_of_type(&update, &event_type) {
720                            continue;
721                        }
722                    }
723                    // Sync responses were missed because they weren't consumed
724                    // fast enough; a fresh snapshot catches up on all of them
725                    // at once.
726                    Err(broadcast::error::RecvError::Lagged(_)) => {}
727                    Err(broadcast::error::RecvError::Closed) => break,
728                }
729
730                yield room.get_state_events(event_type.clone()).await;
731            }
732        }
733    }
734
735    /// Subscribe to updates about users who are in "pin violation" i.e. their
736    /// identity has changed and the user has not yet acknowledged this.
737    ///
738    /// The returned receiver will receive a new vector of
739    /// [`IdentityStatusChange`] each time a /keys/query response shows a
740    /// changed identity for a member of this room, or a sync shows a change to
741    /// the membership of an affected user. (Changes to the current user are not
742    /// directly included, but some changes to the current user's identity can
743    /// trigger changes to how we see other users' identities, which will be
744    /// included.)
745    ///
746    /// The first item in the stream provides the current state of the room:
747    /// each member of the room who is not in "pinned" or "verified" state will
748    /// be included (except the current user).
749    ///
750    /// If the `changed_to` property of an [`IdentityStatusChange`] is set to
751    /// `PinViolation` then a warning should be displayed to the user. If it is
752    /// set to `Pinned` then no warning should be displayed.
753    ///
754    /// Note that if a user who is in pin violation leaves the room, a `Pinned`
755    /// update is sent, to indicate that the warning should be removed, even
756    /// though the user's identity is not necessarily pinned.
757    #[cfg(feature = "e2e-encryption")]
758    pub async fn subscribe_to_identity_status_changes(
759        &self,
760    ) -> Result<impl Stream<Item = Vec<IdentityStatusChange>> + use<>> {
761        IdentityStatusChanges::create_stream(self.clone()).await
762    }
763
764    /// Subscribes to active live location shares in this room.
765    ///
766    /// Returns a [`LiveLocationsObserver`] that holds the current state and
767    /// exposes a stream of incremental [`eyeball_im::VectorDiff`] updates via
768    /// [`LiveLocationsObserver::subscribe`].
769    ///
770    /// Event handlers are active for as long as the returned struct is alive.
771    pub async fn live_locations_observer(&self) -> LiveLocationsObserver {
772        LiveLocationsObserver::new(self.clone()).await
773    }
774
775    /// Returns a wrapping `TimelineEvent` for the input `AnyTimelineEvent`,
776    /// decrypted if needs be.
777    ///
778    /// Only logs from the crypto crate will indicate a failure to decrypt.
779    #[cfg(not(feature = "experimental-encrypted-state-events"))]
780    #[allow(clippy::unused_async)] // Used only in e2e-encryption.
781    async fn try_decrypt_event(
782        &self,
783        event: Raw<AnyTimelineEvent>,
784        push_ctx: Option<&PushContext>,
785    ) -> TimelineEvent {
786        #[cfg(feature = "e2e-encryption")]
787        if let Ok(AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomEncrypted(
788            SyncMessageLikeEvent::Original(_),
789        ))) = event.deserialize_as::<AnySyncTimelineEvent>()
790            && let Ok(event) = self.decrypt_event(event.cast_ref_unchecked(), push_ctx).await
791        {
792            return event;
793        }
794
795        let mut event = TimelineEvent::from_plaintext(event.cast());
796        if let Some(push_ctx) = push_ctx {
797            event.set_push_actions(push_ctx.for_event(event.raw()).await);
798        }
799
800        event
801    }
802
803    /// Returns a wrapping `TimelineEvent` for the input `AnyTimelineEvent`,
804    /// decrypted if needs be.
805    ///
806    /// Only logs from the crypto crate will indicate a failure to decrypt.
807    #[cfg(feature = "experimental-encrypted-state-events")]
808    #[allow(clippy::unused_async)] // Used only in e2e-encryption.
809    async fn try_decrypt_event(
810        &self,
811        event: Raw<AnyTimelineEvent>,
812        push_ctx: Option<&PushContext>,
813    ) -> TimelineEvent {
814        // If we have either an encrypted message-like or state event, try to
815        // decrypt.
816        match event.deserialize_as::<AnySyncTimelineEvent>() {
817            Ok(AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomEncrypted(
818                SyncMessageLikeEvent::Original(_),
819            ))) => {
820                if let Ok(event) = self
821                    .decrypt_event(
822                        event.cast_ref_unchecked::<OriginalSyncRoomEncryptedEvent>(),
823                        push_ctx,
824                    )
825                    .await
826                {
827                    return event;
828                }
829            }
830            Ok(AnySyncTimelineEvent::State(AnySyncStateEvent::RoomEncrypted(
831                SyncStateEvent::Original(_),
832            ))) => {
833                if let Ok(event) = self
834                    .decrypt_event(
835                        event.cast_ref_unchecked::<OriginalSyncStateRoomEncryptedEvent>(),
836                        push_ctx,
837                    )
838                    .await
839                {
840                    return event;
841                }
842            }
843            _ => {}
844        }
845
846        let mut event = TimelineEvent::from_plaintext(event.cast());
847        if let Some(push_ctx) = push_ctx {
848            event.set_push_actions(push_ctx.for_event(event.raw()).await);
849        }
850
851        event
852    }
853
854    /// Fetch the event with the given `EventId` in this room.
855    ///
856    /// It uses the given [`RequestConfig`] if provided, or the client's default
857    /// one otherwise.
858    pub async fn event(
859        &self,
860        event_id: &EventId,
861        request_config: Option<RequestConfig>,
862    ) -> Result<TimelineEvent> {
863        let request =
864            get_room_event::v3::Request::new(self.room_id().to_owned(), event_id.to_owned());
865
866        let raw_event = self.client.send(request).with_request_config(request_config).await?.event;
867        let push_ctx = self.push_context().await?;
868        let event = self.try_decrypt_event(raw_event, push_ctx.as_ref()).await;
869
870        Ok(event)
871    }
872
873    /// Try to load the event from the [`EventCache`][crate::event_cache], if
874    /// it's enabled, or fetch it from the homeserver.
875    ///
876    /// When running the request against the homeserver, it uses the given
877    /// [`RequestConfig`] if provided, or the client's default one otherwise.
878    pub async fn load_or_fetch_event(
879        &self,
880        event_id: &EventId,
881        request_config: Option<RequestConfig>,
882    ) -> Result<TimelineEvent> {
883        if let Some(event_cache) = self.client.event_cache() {
884            match event_cache.room(self.room_id()).await {
885                Ok((room_event_cache, _drop_handles)) => {
886                    if let Some(event) = room_event_cache.find_event(event_id).await? {
887                        return Ok(event);
888                    }
889                    // Fallthrough: try with a request.
890                }
891                Err(err) => {
892                    debug!("error when getting the event cache: {err}");
893                }
894            }
895        }
896
897        self.event(event_id, request_config).await
898
899        // DO NOT save the event in the Event Cache!
900        //
901        // 1. This method might not be called by the Event Cache and thus
902        //    mustn't interfere with it,
903        // 2. Depending on how the event is saved in the Event Cache, it can
904        //    create deadlocks (see
905        //    https://github.com/matrix-org/matrix-rust-sdk/pull/6629).
906        // 3. If the Event Cache calls this method, it is very likely that the
907        //    event will be saved permanently in the database later on, so
908        //    saving it here is a waste of time and a source of possible bugs.
909        //
910        // `load_or_fetch_event_with_relations` has the same problem. It has a
911        // comment pointing to this comment to avoid duplicated explanations.
912    }
913
914    /// Try to load the event and its relations from the
915    /// [`EventCache`][crate::event_cache], if it's enabled, or fetch it from
916    /// the homeserver.
917    ///
918    /// You can control which types of related events are retrieved using
919    /// `filter`. A `None` value will retrieve any type of related event.
920    ///
921    /// If the event is found in the event cache, but we can't find any
922    /// relations for it there, then we will still attempt to fetch the
923    /// relations from the homeserver.
924    ///
925    /// When running any request against the homeserver, it uses the given
926    /// [`RequestConfig`] if provided, or the client's default one otherwise.
927    ///
928    /// Returns a tuple formed of the event and a vector of its relations (that
929    /// can be empty).
930    pub async fn load_or_fetch_event_with_relations(
931        &self,
932        event_id: &EventId,
933        filter: Option<Vec<RelationType>>,
934        request_config: Option<RequestConfig>,
935    ) -> Result<(TimelineEvent, Vec<TimelineEvent>)> {
936        let fetch_relations = async || {
937            // If there's only a single filter, we can use a more efficient
938            // request, specialized on the filter type.
939            //
940            // Otherwise, we need to get all the relations:
941            //
942            // - either because no filters implies we fetch all relations,
943            // - or because there are multiple filters and we must filter out
944            //   manually.
945            let include_relations = if let Some(filter) = &filter
946                && filter.len() == 1
947            {
948                IncludeRelations::RelationsOfType(filter[0].clone())
949            } else {
950                IncludeRelations::AllRelations
951            };
952
953            let mut opts = RelationsOptions {
954                include_relations,
955                recurse: true,
956                limit: Some(uint!(256)),
957                ..Default::default()
958            };
959
960            let mut events = Vec::new();
961            loop {
962                match self.relations(event_id.to_owned(), opts.clone()).await {
963                    Ok(relations) => {
964                        if let Some(filter) = filter.as_ref() {
965                            // Manually filter out the relation types we're
966                            // interested in.
967                            events.extend(relations.chunk.into_iter().filter_map(|ev| {
968                                let (rel_type, _) = extract_relation(ev.raw())?;
969                                filter
970                                    .iter()
971                                    .any(|ruma_filter| ruma_filter == &rel_type)
972                                    .then_some(ev)
973                            }));
974                        } else {
975                            // No filter: include all events from the response.
976                            events.extend(relations.chunk);
977                        }
978
979                        if let Some(next_from) = relations.next_batch_token {
980                            opts.from = Some(next_from);
981                        } else {
982                            break events;
983                        }
984                    }
985
986                    Err(err) => {
987                        warn!(%event_id, "error when loading relations of pinned event from server: {err}");
988                        break events;
989                    }
990                }
991            }
992        };
993
994        // First, try to load the event _and_ its relations from the event
995        // cache, all at once.
996        let room_event_cache = match self.client.event_cache() {
997            Some(event_cache) => {
998                match event_cache.room(self.room_id()).await {
999                    Ok((event_cache, drop_handles)) => {
1000                        if let Some((event, mut relations)) =
1001                            event_cache.find_event_with_relations(event_id, filter.clone()).await?
1002                        {
1003                            if relations.is_empty() {
1004                                // The event cache doesn't have any relations
1005                                // for this
1006                                // event, try to fetch them from the server
1007                                // instead.
1008                                relations = fetch_relations().await;
1009                            }
1010
1011                            return Ok((event, relations));
1012                        }
1013
1014                        // Otherwise, get the event from the server.
1015                        Some((event_cache, drop_handles))
1016                    }
1017
1018                    Err(err) => {
1019                        debug!("error when getting the event cache: {err}");
1020                        // Fallthrough: try with a request.
1021                        None
1022                    }
1023                }
1024            }
1025
1026            None => None,
1027        };
1028
1029        // Fetch the event from the server. A failure here is fatal, as we must
1030        // return the target event.
1031        let event = self.event(event_id, request_config).await?;
1032
1033        // DO NOT save the event in the Event Cache!
1034        //
1035        // To understand why, see the documentation in `load_or_fetch_event`.
1036
1037        // Try to get the relations from the event cache (if we have one).
1038        if let Some((event_cache, _drop_handles)) = room_event_cache
1039            && let Some(relations) =
1040                event_cache.find_event_relations(event_id, filter.clone()).await.ok()
1041            && !relations.is_empty()
1042        {
1043            return Ok((event, relations));
1044        }
1045
1046        // We couldn't find the relations in the event cache; fetch them from
1047        // the server.
1048        Ok((event, fetch_relations().await))
1049    }
1050
1051    /// Fetch the event with the given `EventId` in this room, using the
1052    /// `/context` endpoint to get more information.
1053    pub async fn event_with_context(
1054        &self,
1055        event_id: &EventId,
1056        lazy_load_members: bool,
1057        context_size: UInt,
1058        request_config: Option<RequestConfig>,
1059    ) -> Result<EventWithContextResponse> {
1060        let mut request =
1061            context::get_context::v3::Request::new(self.room_id().to_owned(), event_id.to_owned());
1062
1063        request.limit = context_size;
1064
1065        if lazy_load_members {
1066            request.filter.lazy_load_options =
1067                LazyLoadOptions::Enabled { include_redundant_members: false };
1068        }
1069
1070        let response = self.client.send(request).with_request_config(request_config).await?;
1071
1072        let push_ctx = self.push_context().await?;
1073        let push_ctx = push_ctx.as_ref();
1074        let target_event = if let Some(event) = response.event {
1075            Some(self.try_decrypt_event(event, push_ctx).await)
1076        } else {
1077            None
1078        };
1079
1080        // Note: the joined future will fail if any future failed, but
1081        // [`Self::try_decrypt_event`] doesn't hard-fail when there's a
1082        // decryption error, so we should prevent against most bad cases here.
1083        let (events_before, events_after) = join!(
1084            join_all(
1085                response.events_before.into_iter().map(|ev| self.try_decrypt_event(ev, push_ctx)),
1086            ),
1087            join_all(
1088                response.events_after.into_iter().map(|ev| self.try_decrypt_event(ev, push_ctx)),
1089            ),
1090        );
1091
1092        Ok(EventWithContextResponse {
1093            event: target_event,
1094            events_before,
1095            events_after,
1096            state: response.state,
1097            prev_batch_token: response.start,
1098            next_batch_token: response.end,
1099        })
1100    }
1101
1102    pub(crate) async fn request_members(&self) -> Result<()> {
1103        self.client
1104            .locks()
1105            .members_request_deduplicated_handler
1106            .run(self.room_id().to_owned(), async move {
1107                let request = get_member_events::v3::Request::new(self.inner.room_id().to_owned());
1108                let response = self
1109                    .client
1110                    .send(request.clone())
1111                    .with_request_config(
1112                        // In some cases it can take longer than 30s to load:
1113                        // https://github.com/element-hq/synapse/issues/16872
1114                        RequestConfig::new().timeout(Duration::from_secs(60)).retry_limit(3),
1115                    )
1116                    .await?;
1117
1118                // That's a large `Future`. Let's `Box::pin` to reduce its size
1119                // on the stack.
1120                Box::pin(self.client.base_client().receive_all_members(
1121                    self.room_id(),
1122                    &request,
1123                    &response,
1124                ))
1125                .await?;
1126
1127                Ok(())
1128            })
1129            .await
1130    }
1131
1132    /// Request to update the encryption state for this room.
1133    ///
1134    /// It does nothing if the encryption state is already
1135    /// [`EncryptionState::Encrypted`] or [`EncryptionState::NotEncrypted`].
1136    pub async fn request_encryption_state(&self) -> Result<()> {
1137        if !self.inner.encryption_state().is_unknown() {
1138            return Ok(());
1139        }
1140
1141        self.client
1142            .locks()
1143            .encryption_state_deduplicated_handler
1144            .run(self.room_id().to_owned(), async move {
1145                // Request the event from the server.
1146                let request = get_state_event_for_key::v3::Request::new(
1147                    self.room_id().to_owned(),
1148                    StateEventType::RoomEncryption,
1149                    "".to_owned(),
1150                );
1151                let response = match self.client.send(request).await {
1152                    Ok(response) => Some(
1153                        response
1154                            .into_content()
1155                            .deserialize_as_unchecked::<PossiblyRedactedRoomEncryptionEventContent>(
1156                            )?,
1157                    ),
1158                    Err(err) if err.client_api_error_kind() == Some(&ErrorKind::NotFound) => None,
1159                    Err(err) => return Err(err.into()),
1160                };
1161
1162                // Persist the event and the fact that we requested it from the
1163                // server in `RoomInfo`.
1164                self.update_and_save_room_info(|mut room_info| {
1165                    room_info.mark_encryption_state_synced();
1166                    room_info.set_encryption_event(response);
1167                    (room_info, RoomInfoNotableUpdateReasons::empty())
1168                })
1169                .await?;
1170
1171                Ok(())
1172            })
1173            .await
1174    }
1175
1176    /// Check the encryption state of this room.
1177    ///
1178    /// If the result is [`EncryptionState::Unknown`], one might want to call
1179    /// [`Room::request_encryption_state`].
1180    pub fn encryption_state(&self) -> EncryptionState {
1181        self.inner.encryption_state()
1182    }
1183
1184    /// Force to update the encryption state by calling
1185    /// [`Room::request_encryption_state`], and then calling
1186    /// [`Room::encryption_state`].
1187    ///
1188    /// This method is useful to ensure the encryption state is up-to-date.
1189    pub async fn latest_encryption_state(&self) -> Result<EncryptionState> {
1190        self.request_encryption_state().await?;
1191
1192        Ok(self.encryption_state())
1193    }
1194
1195    /// Gets additional context info about the client crypto.
1196    #[cfg(feature = "e2e-encryption")]
1197    pub async fn crypto_context_info(&self) -> CryptoContextInfo {
1198        let encryption = self.client.encryption();
1199
1200        let this_device_is_verified = match encryption.get_own_device().await {
1201            Ok(Some(device)) => device.is_verified_with_cross_signing(),
1202
1203            // Should not happen, there will always be an own device
1204            _ => true,
1205        };
1206
1207        let backup_exists_on_server =
1208            encryption.backups().exists_on_server().await.unwrap_or(false);
1209
1210        CryptoContextInfo {
1211            device_creation_ts: encryption.device_creation_timestamp().await,
1212            this_device_is_verified,
1213            is_backup_configured: encryption.backups().state() == BackupState::Enabled,
1214            backup_exists_on_server,
1215        }
1216    }
1217
1218    fn are_events_visible(&self) -> bool {
1219        if let RoomState::Invited = self.inner.state() {
1220            return matches!(
1221                self.inner.history_visibility_or_default(),
1222                HistoryVisibility::WorldReadable | HistoryVisibility::Invited
1223            );
1224        }
1225
1226        true
1227    }
1228
1229    /// Sync the member list with the server.
1230    ///
1231    /// This method will de-duplicate requests if it is called multiple times in
1232    /// quick succession, in that case the return value will be `None`. This
1233    /// method does nothing if the members are already synced.
1234    pub async fn sync_members(&self) -> Result<()> {
1235        if !self.are_events_visible() {
1236            return Ok(());
1237        }
1238
1239        if !self.are_members_synced() {
1240            self.request_members().await?;
1241
1242            // While we're at it, calculate the active service members
1243            self.update_active_service_members().await?;
1244
1245            Ok(())
1246        } else {
1247            Ok(())
1248        }
1249    }
1250
1251    /// Get a specific member of this room.
1252    ///
1253    /// _Note_: This method will fetch the members from the homeserver if the
1254    /// member list isn't synchronized due to member lazy loading. Because of
1255    /// that it might panic if it isn't run on a tokio thread.
1256    ///
1257    /// Use [get_member_no_sync()](#method.get_member_no_sync) if you want a
1258    /// method that doesn't do any requests.
1259    ///
1260    /// # Arguments
1261    ///
1262    /// - `user_id` - The ID of the user that should be fetched out of the
1263    ///   store.
1264    pub async fn get_member(&self, user_id: &UserId) -> Result<Option<RoomMember>> {
1265        self.sync_members().await?;
1266        self.get_member_no_sync(user_id).await
1267    }
1268
1269    /// Get a specific member of this room.
1270    ///
1271    /// _Note_: This method will not fetch the members from the homeserver if
1272    /// the member list isn't synchronized due to member lazy loading. Thus,
1273    /// members could be missing.
1274    ///
1275    /// Use [get_member()](#method.get_member) if you want to ensure to always
1276    /// have the full member list to chose from.
1277    ///
1278    /// # Arguments
1279    ///
1280    /// - `user_id` - The ID of the user that should be fetched out of the
1281    ///   store.
1282    pub async fn get_member_no_sync(&self, user_id: &UserId) -> Result<Option<RoomMember>> {
1283        Ok(self
1284            .inner
1285            .get_member(user_id)
1286            .await?
1287            .map(|member| RoomMember::new(self.client.clone(), member)))
1288    }
1289
1290    /// Get members for this room, with the given memberships.
1291    ///
1292    /// _Note_: This method will fetch the members from the homeserver if the
1293    /// member list isn't synchronized due to member lazy loading. Because of
1294    /// that it might panic if it isn't run on a tokio thread.
1295    ///
1296    /// Use [members_no_sync()](#method.members_no_sync) if you want a method
1297    /// that doesn't do any requests.
1298    pub async fn members(&self, memberships: RoomMemberships) -> Result<Vec<RoomMember>> {
1299        self.sync_members().await?;
1300        self.members_no_sync(memberships).await
1301    }
1302
1303    /// Get members for this room, with the given memberships.
1304    ///
1305    /// _Note_: This method will not fetch the members from the homeserver if
1306    /// the member list isn't synchronized due to member lazy loading. Thus,
1307    /// members could be missing.
1308    ///
1309    /// Use [members()](#method.members) if you want to ensure to always get the
1310    /// full member list.
1311    pub async fn members_no_sync(&self, memberships: RoomMemberships) -> Result<Vec<RoomMember>> {
1312        Ok(self
1313            .inner
1314            .members(memberships)
1315            .await?
1316            .into_iter()
1317            .map(|member| RoomMember::new(self.client.clone(), member))
1318            .collect())
1319    }
1320
1321    /// Fetch the missing global profiles of this room's joined members in the
1322    /// background, e.g. after loading the members with [`Room::members()`].
1323    ///
1324    /// This returns once the fetch is queued, without waiting for the profiles.
1325    /// They are announced through
1326    /// [`Client::subscribe_to_global_profile_updates()`] as they are
1327    /// stored.
1328    ///
1329    /// This does nothing unless the room is joined, global profiles are being
1330    /// synced (see [`Client::is_global_profile_sync_enabled()`]) and the
1331    /// homeserver supports [MSC4536]. The first two are needed for the sync to
1332    /// keep the fetched profiles up to date.
1333    ///
1334    /// [MSC4536]: https://github.com/matrix-org/matrix-spec-proposals/pull/4536
1335    #[cfg(feature = "unstable-msc4536")]
1336    pub async fn fetch_missing_global_profiles_in_background(&self) -> Result<()> {
1337        if self.state() != RoomState::Joined {
1338            return Ok(());
1339        }
1340
1341        if !self.client.is_global_profile_sync_enabled().await? {
1342            return Ok(());
1343        }
1344
1345        if !self.client.unstable_features().await?.contains(&FeatureFlag::Msc4536) {
1346            debug!("The homeserver doesn't support fetching multiple profiles");
1347            return Ok(());
1348        }
1349
1350        let user_ids = self.inner.joined_user_ids().await?;
1351        self.client.global_profile_fetcher().enqueue(user_ids);
1352
1353        Ok(())
1354    }
1355
1356    /// Get the user IDs of the members with the given memberships, without the
1357    /// service members. The current user is part of the result. Fetches the
1358    /// member list if it is not synced yet.
1359    pub async fn human_member_ids(&self, memberships: RoomMemberships) -> Result<Vec<OwnedUserId>> {
1360        self.sync_members().await?;
1361        self.human_member_ids_no_sync(memberships).await
1362    }
1363
1364    /// Same as [`Self::human_member_ids`], without a request to the homeserver,
1365    /// so members can be missing.
1366    pub async fn human_member_ids_no_sync(
1367        &self,
1368        memberships: RoomMemberships,
1369    ) -> Result<Vec<OwnedUserId>> {
1370        Ok(self.inner.human_member_ids(memberships).await?)
1371    }
1372
1373    /// Sets the display name of the current user within this room.
1374    ///
1375    /// _Note_: This is different to [`crate::Account::set_display_name`] which
1376    /// updates the user's display name across all of their rooms.
1377    pub async fn set_own_member_display_name(
1378        &self,
1379        display_name: Option<String>,
1380    ) -> Result<send_state_event::v3::Response> {
1381        let user_id = self.own_user_id();
1382        let member_event =
1383            self.get_state_event_static_for_key::<RoomMemberEventContent, _>(user_id).await?;
1384
1385        let Some(RawSyncOrStrippedState::Sync(raw_event)) = member_event else {
1386            return Err(Error::InsufficientData);
1387        };
1388
1389        let event = raw_event.deserialize()?;
1390
1391        let mut content = match event {
1392            SyncStateEvent::Original(original_event) => original_event.content,
1393            SyncStateEvent::Redacted(redacted_event) => {
1394                RoomMemberEventContent::new(redacted_event.content.membership)
1395            }
1396        };
1397
1398        content.displayname = display_name;
1399        self.send_state_event_for_key(user_id, content).await
1400    }
1401
1402    /// Get all state events of a given type in this room.
1403    pub async fn get_state_events(
1404        &self,
1405        event_type: StateEventType,
1406    ) -> Result<Vec<RawAnySyncOrStrippedState>> {
1407        self.client
1408            .state_store()
1409            .get_state_events(self.room_id(), event_type)
1410            .await
1411            .map_err(Into::into)
1412    }
1413
1414    /// Get all state events of a given statically-known type in this room.
1415    ///
1416    /// # Examples
1417    ///
1418    /// ```no_run
1419    /// # async {
1420    /// # let room: matrix_sdk::Room = todo!();
1421    /// use matrix_sdk::ruma::{
1422    ///     events::room::member::RoomMemberEventContent, serde::Raw,
1423    /// };
1424    ///
1425    /// let room_members =
1426    ///     room.get_state_events_static::<RoomMemberEventContent>().await?;
1427    /// # anyhow::Ok(())
1428    /// # };
1429    /// ```
1430    pub async fn get_state_events_static<C>(&self) -> Result<Vec<RawSyncOrStrippedState<C>>>
1431    where
1432        C: StaticEventContent<IsPrefix = ruma::events::False>
1433            + StaticStateEventContent
1434            + RedactContent,
1435        C::Redacted: RedactedStateEventContent,
1436    {
1437        Ok(self.client.state_store().get_state_events_static(self.room_id()).await?)
1438    }
1439
1440    /// Get the state events of a given type with the given state keys in this
1441    /// room.
1442    pub async fn get_state_events_for_keys(
1443        &self,
1444        event_type: StateEventType,
1445        state_keys: &[&str],
1446    ) -> Result<Vec<RawAnySyncOrStrippedState>> {
1447        self.client
1448            .state_store()
1449            .get_state_events_for_keys(self.room_id(), event_type, state_keys)
1450            .await
1451            .map_err(Into::into)
1452    }
1453
1454    /// Get the state events of a given statically-known type with the given
1455    /// state keys in this room.
1456    ///
1457    /// # Examples
1458    ///
1459    /// ```no_run
1460    /// # async {
1461    /// # let room: matrix_sdk::Room = todo!();
1462    /// # let user_ids: &[matrix_sdk::ruma::OwnedUserId] = &[];
1463    /// use matrix_sdk::ruma::events::room::member::RoomMemberEventContent;
1464    ///
1465    /// let room_members = room
1466    ///     .get_state_events_for_keys_static::<RoomMemberEventContent, _, _>(
1467    ///         user_ids,
1468    ///     )
1469    ///     .await?;
1470    /// # anyhow::Ok(())
1471    /// # };
1472    /// ```
1473    pub async fn get_state_events_for_keys_static<'a, C, K, I>(
1474        &self,
1475        state_keys: I,
1476    ) -> Result<Vec<RawSyncOrStrippedState<C>>>
1477    where
1478        C: StaticEventContent<IsPrefix = ruma::events::False>
1479            + StaticStateEventContent
1480            + RedactContent,
1481        C::StateKey: Borrow<K>,
1482        C::Redacted: RedactedStateEventContent,
1483        K: AsRef<str> + Sized + Sync + 'a,
1484        I: IntoIterator<Item = &'a K> + Send,
1485        I::IntoIter: Send,
1486    {
1487        Ok(self
1488            .client
1489            .state_store()
1490            .get_state_events_for_keys_static(self.room_id(), state_keys)
1491            .await?)
1492    }
1493
1494    /// Get a specific state event in this room.
1495    pub async fn get_state_event(
1496        &self,
1497        event_type: StateEventType,
1498        state_key: &str,
1499    ) -> Result<Option<RawAnySyncOrStrippedState>> {
1500        self.client
1501            .state_store()
1502            .get_state_event(self.room_id(), event_type, state_key)
1503            .await
1504            .map_err(Into::into)
1505    }
1506
1507    /// Get a specific state event of statically-known type with an empty state
1508    /// key in this room.
1509    ///
1510    /// # Examples
1511    ///
1512    /// ```no_run
1513    /// # async {
1514    /// # let room: matrix_sdk::Room = todo!();
1515    /// use matrix_sdk::ruma::events::room::power_levels::RoomPowerLevelsEventContent;
1516    ///
1517    /// let power_levels = room
1518    ///     .get_state_event_static::<RoomPowerLevelsEventContent>()
1519    ///     .await?
1520    ///     .expect("every room has a power_levels event")
1521    ///     .deserialize()?;
1522    /// # anyhow::Ok(())
1523    /// # };
1524    /// ```
1525    pub async fn get_state_event_static<C>(&self) -> Result<Option<RawSyncOrStrippedState<C>>>
1526    where
1527        C: StaticEventContent<IsPrefix = ruma::events::False>
1528            + StaticStateEventContent<StateKey = EmptyStateKey>
1529            + RedactContent,
1530        C::Redacted: RedactedStateEventContent,
1531    {
1532        self.get_state_event_static_for_key(&EmptyStateKey).await
1533    }
1534
1535    /// Get a specific state event of statically-known type in this room.
1536    ///
1537    /// # Examples
1538    ///
1539    /// ```no_run
1540    /// # async {
1541    /// # let room: matrix_sdk::Room = todo!();
1542    /// use matrix_sdk::ruma::{
1543    ///     events::room::member::RoomMemberEventContent, serde::Raw, user_id,
1544    /// };
1545    ///
1546    /// let member_event = room
1547    ///     .get_state_event_static_for_key::<RoomMemberEventContent, _>(user_id!(
1548    ///         "@alice:example.org"
1549    ///     ))
1550    ///     .await?;
1551    /// # anyhow::Ok(())
1552    /// # };
1553    /// ```
1554    pub async fn get_state_event_static_for_key<C, K>(
1555        &self,
1556        state_key: &K,
1557    ) -> Result<Option<RawSyncOrStrippedState<C>>>
1558    where
1559        C: StaticEventContent<IsPrefix = ruma::events::False>
1560            + StaticStateEventContent
1561            + RedactContent,
1562        C::StateKey: Borrow<K>,
1563        C::Redacted: RedactedStateEventContent,
1564        K: AsRef<str> + ?Sized + Sync,
1565    {
1566        Ok(self
1567            .client
1568            .state_store()
1569            .get_state_event_static_for_key(self.room_id(), state_key)
1570            .await?)
1571    }
1572
1573    /// Returns the parents this room advertises as its parents.
1574    ///
1575    /// Results are in no particular order.
1576    pub async fn parent_spaces(&self) -> Result<impl Stream<Item = Result<ParentSpace>> + '_> {
1577        // Implements this algorithm:
1578        // https://spec.matrix.org/v1.8/client-server-api/#mspaceparent-relationships
1579
1580        // Get all m.space.parent events for this room
1581        Ok(self
1582            .get_state_events_static::<SpaceParentEventContent>()
1583            .await?
1584            .into_iter()
1585            // Extract state key (ie. the parent's id) and sender
1586            .filter_map(|parent_event| match parent_event.deserialize() {
1587                Ok(SyncOrStrippedState::Sync(SyncStateEvent::Original(e))) => {
1588                    Some((e.state_key, e.sender))
1589                }
1590                Ok(SyncOrStrippedState::Sync(SyncStateEvent::Redacted(_))) => None,
1591                Ok(SyncOrStrippedState::Stripped(e)) => Some((e.state_key, e.sender)),
1592                Err(e) => {
1593                    info!(room_id = ?self.room_id(), "Could not deserialize m.space.parent: {e}");
1594                    None
1595                }
1596            })
1597            // Check whether the parent recognizes this room as its child
1598            .map(|(state_key, sender): (OwnedRoomId, OwnedUserId)| async move {
1599                let Some(parent_room) = self.client.get_room(&state_key) else {
1600                    // We are not in the room, cannot check if the relationship
1601                    // is reciprocal TODO: try peeking into the room
1602                    return Ok(ParentSpace::Unverifiable(state_key));
1603                };
1604                // Get the m.space.child state of the parent with this room's id
1605                // as state key.
1606                if let Some(child_event) = parent_room
1607                    .get_state_event_static_for_key::<SpaceChildEventContent, _>(self.room_id())
1608                    .await?
1609                {
1610                    match child_event.deserialize() {
1611                        Ok(SyncOrStrippedState::Sync(SyncStateEvent::Original(_))) => {
1612                            // There is a valid m.space.child in the parent
1613                            // pointing to this room
1614                            return Ok(ParentSpace::Reciprocal(parent_room));
1615                        }
1616                        Ok(SyncOrStrippedState::Sync(SyncStateEvent::Redacted(_))) => {}
1617                        Ok(SyncOrStrippedState::Stripped(_)) => {}
1618                        Err(e) => {
1619                            info!(
1620                                room_id = ?self.room_id(), parent_room_id = ?state_key,
1621                                "Could not deserialize m.space.child: {e}"
1622                            );
1623                        }
1624                    }
1625                    // Otherwise the event is either invalid or redacted. If
1626                    // redacted it would be missing the `via` key, thereby
1627                    // invalidating that end of the relationship:
1628                    // https://spec.matrix.org/v1.8/client-server-api/#mspacechild
1629                }
1630
1631                // No reciprocal m.space.child found, let's check if the sender
1632                // has the power to set it
1633                let Some(member) = parent_room.get_member(&sender).await? else {
1634                    // Sender is not even in the parent room
1635                    return Ok(ParentSpace::Illegitimate(parent_room));
1636                };
1637
1638                if member.can_send_state(StateEventType::SpaceChild) {
1639                    // Sender does have the power to set m.room.child
1640                    Ok(ParentSpace::WithPowerlevel(parent_room))
1641                } else {
1642                    Ok(ParentSpace::Illegitimate(parent_room))
1643                }
1644            })
1645            .collect::<FuturesUnordered<_>>())
1646    }
1647
1648    /// Read account data in this room, from storage.
1649    pub async fn account_data(
1650        &self,
1651        data_type: RoomAccountDataEventType,
1652    ) -> Result<Option<Raw<AnyRoomAccountDataEvent>>> {
1653        self.client
1654            .state_store()
1655            .get_room_account_data_event(self.room_id(), data_type)
1656            .await
1657            .map_err(Into::into)
1658    }
1659
1660    /// Get account data of a statically-known type in this room, from storage.
1661    ///
1662    /// # Examples
1663    ///
1664    /// ```no_run
1665    /// # async {
1666    /// # let room: matrix_sdk::Room = todo!();
1667    /// use matrix_sdk::ruma::events::fully_read::FullyReadEventContent;
1668    ///
1669    /// match room.account_data_static::<FullyReadEventContent>().await? {
1670    ///     Some(fully_read) => {
1671    ///         println!("Found read marker: {:?}", fully_read.deserialize()?)
1672    ///     }
1673    ///     None => println!("No read marker for this room"),
1674    /// }
1675    /// # anyhow::Ok(())
1676    /// # };
1677    /// ```
1678    pub async fn account_data_static<C>(&self) -> Result<Option<Raw<RoomAccountDataEvent<C>>>>
1679    where
1680        C: StaticEventContent<IsPrefix = ruma::events::False> + RoomAccountDataEventContent,
1681    {
1682        Ok(self.account_data(C::TYPE.into()).await?.map(Raw::cast_unchecked))
1683    }
1684
1685    /// Check if all members of this room are verified and all their devices are
1686    /// verified.
1687    ///
1688    /// Returns true if all devices in the room are verified, otherwise false.
1689    #[cfg(feature = "e2e-encryption")]
1690    pub async fn contains_only_verified_devices(&self) -> Result<bool> {
1691        let user_ids = self
1692            .client
1693            .state_store()
1694            .get_user_ids(self.room_id(), RoomMemberships::empty())
1695            .await?;
1696
1697        for user_id in user_ids {
1698            let devices = self.client.encryption().get_user_devices(&user_id).await?;
1699            let any_unverified = devices.devices().any(|d| !d.is_verified());
1700
1701            if any_unverified {
1702                return Ok(false);
1703            }
1704        }
1705
1706        Ok(true)
1707    }
1708
1709    /// Set the given account data event for this room.
1710    ///
1711    /// # Example
1712    ///
1713    /// ```
1714    /// # async {
1715    /// # let room: matrix_sdk::Room = todo!();
1716    /// # let event_id: ruma::OwnedEventId = todo!();
1717    /// use matrix_sdk::ruma::events::fully_read::FullyReadEventContent;
1718    /// let content = FullyReadEventContent::new(event_id);
1719    ///
1720    /// room.set_account_data(content).await?;
1721    /// # anyhow::Ok(())
1722    /// # };
1723    /// ```
1724    pub async fn set_account_data<T>(
1725        &self,
1726        content: T,
1727    ) -> Result<set_room_account_data::v3::Response>
1728    where
1729        T: RoomAccountDataEventContent,
1730    {
1731        let own_user = self.client.user_id().ok_or(Error::AuthenticationRequired)?;
1732
1733        let request = set_room_account_data::v3::Request::new(
1734            own_user.to_owned(),
1735            self.room_id().to_owned(),
1736            &content,
1737        )?;
1738
1739        Ok(self.client.send(request).await?)
1740    }
1741
1742    /// Set the given raw account data event in this room.
1743    ///
1744    /// # Example
1745    ///
1746    /// ```
1747    /// # async {
1748    /// # let room: matrix_sdk::Room = todo!();
1749    /// use matrix_sdk::ruma::{
1750    ///     events::{
1751    ///         AnyRoomAccountDataEventContent, RoomAccountDataEventContent,
1752    ///         marked_unread::MarkedUnreadEventContent,
1753    ///     },
1754    ///     serde::Raw,
1755    /// };
1756    /// let marked_unread_content = MarkedUnreadEventContent::new(true);
1757    /// let full_event: AnyRoomAccountDataEventContent =
1758    ///     marked_unread_content.clone().into();
1759    /// room.set_account_data_raw(
1760    ///     marked_unread_content.event_type(),
1761    ///     Raw::new(&full_event).unwrap(),
1762    /// )
1763    /// .await?;
1764    /// # anyhow::Ok(())
1765    /// # };
1766    /// ```
1767    pub async fn set_account_data_raw(
1768        &self,
1769        event_type: RoomAccountDataEventType,
1770        content: Raw<AnyRoomAccountDataEventContent>,
1771    ) -> Result<set_room_account_data::v3::Response> {
1772        let own_user = self.client.user_id().ok_or(Error::AuthenticationRequired)?;
1773
1774        let request = set_room_account_data::v3::Request::new_raw(
1775            own_user.to_owned(),
1776            self.room_id().to_owned(),
1777            event_type,
1778            content,
1779        );
1780
1781        Ok(self.client.send(request).await?)
1782    }
1783
1784    /// Adds a tag to the room, or updates it if it already exists.
1785    ///
1786    /// Returns the [`create_tag::v3::Response`] from the server.
1787    ///
1788    /// # Arguments
1789    ///
1790    /// - `tag` - The tag to add or update.
1791    /// - `tag_info` - Information about the tag, generally containing the
1792    ///   `order` parameter.
1793    ///
1794    /// # Examples
1795    ///
1796    /// ```no_run
1797    /// # use std::str::FromStr;
1798    /// # use ruma::events::tag::{TagInfo, TagName, UserTagName};
1799    /// # async {
1800    /// # let homeserver = url::Url::parse("http://localhost:8080")?;
1801    /// # let mut client = matrix_sdk::Client::new(homeserver).await?;
1802    /// # let room_id = matrix_sdk::ruma::room_id!("!test:localhost");
1803    /// use matrix_sdk::ruma::events::tag::TagInfo;
1804    ///
1805    /// if let Some(room) = client.get_room(&room_id) {
1806    ///     let mut tag_info = TagInfo::new();
1807    ///     tag_info.order = Some(0.9);
1808    ///     let user_tag = UserTagName::from_str("u.work")?;
1809    ///
1810    ///     room.set_tag(TagName::User(user_tag), tag_info).await?;
1811    /// }
1812    /// # anyhow::Ok(()) };
1813    /// ```
1814    pub async fn set_tag(
1815        &self,
1816        tag: TagName,
1817        tag_info: TagInfo,
1818    ) -> Result<create_tag::v3::Response> {
1819        let user_id = self.client.user_id().ok_or(Error::AuthenticationRequired)?;
1820        let request = create_tag::v3::Request::new(
1821            user_id.to_owned(),
1822            self.inner.room_id().to_owned(),
1823            tag.to_string(),
1824            tag_info,
1825        );
1826        Ok(self.client.send(request).await?)
1827    }
1828
1829    /// Removes a tag from the room.
1830    ///
1831    /// Returns the [`delete_tag::v3::Response`] from the server.
1832    ///
1833    /// # Arguments
1834    ///
1835    /// - `tag` - The tag to remove.
1836    pub async fn remove_tag(&self, tag: TagName) -> Result<delete_tag::v3::Response> {
1837        let user_id = self.client.user_id().ok_or(Error::AuthenticationRequired)?;
1838        let request = delete_tag::v3::Request::new(
1839            user_id.to_owned(),
1840            self.inner.room_id().to_owned(),
1841            tag.to_string(),
1842        );
1843        Ok(self.client.send(request).await?)
1844    }
1845
1846    /// Add or remove the `m.favourite` flag for this room.
1847    ///
1848    /// If `is_favourite` is `true`, and the `m.low_priority` tag is set on the
1849    /// room, the tag will be removed too.
1850    ///
1851    /// # Arguments
1852    ///
1853    /// - `is_favourite` - Whether to mark this room as favourite.
1854    /// - `tag_order` - The order of the tag if any.
1855    pub async fn set_is_favourite(&self, is_favourite: bool, tag_order: Option<f64>) -> Result<()> {
1856        if is_favourite {
1857            let tag_info = assign!(TagInfo::new(), { order: tag_order });
1858
1859            self.set_tag(TagName::Favorite, tag_info).await?;
1860
1861            if self.is_low_priority() {
1862                self.remove_tag(TagName::LowPriority).await?;
1863            }
1864        } else {
1865            self.remove_tag(TagName::Favorite).await?;
1866        }
1867        Ok(())
1868    }
1869
1870    /// Add or remove the `m.lowpriority` flag for this room.
1871    ///
1872    /// If `is_low_priority` is `true`, and the `m.favourite` tag is set on the
1873    /// room, the tag will be removed too.
1874    ///
1875    /// # Arguments
1876    ///
1877    /// - `is_low_priority` - Whether to mark this room as low_priority or not.
1878    /// - `tag_order` - The order of the tag if any.
1879    pub async fn set_is_low_priority(
1880        &self,
1881        is_low_priority: bool,
1882        tag_order: Option<f64>,
1883    ) -> Result<()> {
1884        if is_low_priority {
1885            let tag_info = assign!(TagInfo::new(), { order: tag_order });
1886
1887            self.set_tag(TagName::LowPriority, tag_info).await?;
1888
1889            if self.is_favourite() {
1890                self.remove_tag(TagName::Favorite).await?;
1891            }
1892        } else {
1893            self.remove_tag(TagName::LowPriority).await?;
1894        }
1895        Ok(())
1896    }
1897
1898    /// Sets whether this room is a DM.
1899    ///
1900    /// When setting this room as DM, it will be marked as DM for all active
1901    /// members of the room. When unsetting this room as DM, it will be unmarked
1902    /// as DM for all users, not just the members.
1903    ///
1904    /// # Arguments
1905    ///
1906    /// - `is_direct` - Whether to mark this room as direct.
1907    pub async fn set_is_direct(&self, is_direct: bool) -> Result<()> {
1908        let user_id = self.client.user_id().ok_or(Error::AuthenticationRequired)?;
1909
1910        let mut content = self
1911            .client
1912            .account()
1913            .account_data::<DirectEventContent>()
1914            .await?
1915            .map(|c| c.deserialize())
1916            .transpose()?
1917            .unwrap_or_default();
1918
1919        let this_room_id = self.inner.room_id();
1920
1921        if is_direct {
1922            let mut room_members = self.members(RoomMemberships::ACTIVE).await?;
1923            room_members.retain(|member| member.user_id() != self.own_user_id());
1924
1925            for member in room_members {
1926                let entry = content.entry(member.user_id().into()).or_default();
1927                if !entry.iter().any(|room_id| room_id == this_room_id) {
1928                    entry.push(this_room_id.to_owned());
1929                }
1930            }
1931        } else {
1932            for list in content.values_mut() {
1933                list.retain(|room_id| *room_id != this_room_id);
1934            }
1935
1936            // Remove user ids that don't have any room marked as DM
1937            content.retain(|_, list| !list.is_empty());
1938        }
1939
1940        let request = set_global_account_data::v3::Request::new(user_id.to_owned(), &content)?;
1941
1942        self.client.send(request).await?;
1943        Ok(())
1944    }
1945
1946    /// Tries to decrypt a room event.
1947    ///
1948    /// # Arguments
1949    ///
1950    /// - `event` - The room event to be decrypted.
1951    ///
1952    /// Returns the decrypted event. In the case of a decryption error, returns
1953    /// a `TimelineEvent` representing the decryption error.
1954    #[cfg(feature = "e2e-encryption")]
1955    #[cfg(not(feature = "experimental-encrypted-state-events"))]
1956    pub async fn decrypt_event(
1957        &self,
1958        event: &Raw<OriginalSyncRoomEncryptedEvent>,
1959        push_ctx: Option<&PushContext>,
1960    ) -> Result<TimelineEvent> {
1961        let machine = self.client.olm_machine().await;
1962        let machine = machine.as_ref().ok_or(Error::NoOlmMachine)?;
1963
1964        match machine
1965            .try_decrypt_room_event(
1966                event.cast_ref(),
1967                self.inner.room_id(),
1968                self.client.decryption_settings(),
1969            )
1970            .await?
1971        {
1972            RoomEventDecryptionResult::Decrypted(decrypted) => {
1973                let push_actions = if let Some(push_ctx) = push_ctx {
1974                    Some(push_ctx.for_event(&decrypted.event).await)
1975                } else {
1976                    None
1977                };
1978                Ok(TimelineEvent::from_decrypted(decrypted, push_actions))
1979            }
1980            RoomEventDecryptionResult::UnableToDecrypt(utd_info) => {
1981                self.client
1982                    .encryption()
1983                    .backups()
1984                    .maybe_download_room_key(self.room_id().to_owned(), event.clone());
1985                Ok(TimelineEvent::from_utd(event.clone().cast(), utd_info))
1986            }
1987        }
1988    }
1989
1990    /// Tries to decrypt a room event.
1991    ///
1992    /// # Arguments
1993    ///
1994    /// - `event` - The room event to be decrypted.
1995    ///
1996    /// Returns the decrypted event. In the case of a decryption error, returns
1997    /// a `TimelineEvent` representing the decryption error.
1998    #[cfg(feature = "experimental-encrypted-state-events")]
1999    pub async fn decrypt_event<T: JsonCastable<EncryptedEvent>>(
2000        &self,
2001        event: &Raw<T>,
2002        push_ctx: Option<&PushContext>,
2003    ) -> Result<TimelineEvent> {
2004        let machine = self.client.olm_machine().await;
2005        let machine = machine.as_ref().ok_or(Error::NoOlmMachine)?;
2006
2007        match machine
2008            .try_decrypt_room_event(
2009                event.cast_ref(),
2010                self.inner.room_id(),
2011                self.client.decryption_settings(),
2012            )
2013            .await?
2014        {
2015            RoomEventDecryptionResult::Decrypted(decrypted) => {
2016                let push_actions = if let Some(push_ctx) = push_ctx {
2017                    Some(push_ctx.for_event(&decrypted.event).await)
2018                } else {
2019                    None
2020                };
2021                Ok(TimelineEvent::from_decrypted(decrypted, push_actions))
2022            }
2023            RoomEventDecryptionResult::UnableToDecrypt(utd_info) => {
2024                self.client
2025                    .encryption()
2026                    .backups()
2027                    .maybe_download_room_key(self.room_id().to_owned(), event.clone());
2028                // Cast safety: Anything that can be cast to EncryptedEvent must
2029                // be a timeline event.
2030                Ok(TimelineEvent::from_utd(event.clone().cast_unchecked(), utd_info))
2031            }
2032        }
2033    }
2034
2035    /// Fetches the [`EncryptionInfo`] for an event decrypted with the supplied
2036    /// session_id.
2037    ///
2038    /// This may be used when we receive an update for a session, and we want to
2039    /// reflect the changes in messages we have received that were encrypted
2040    /// with that session, e.g. to remove a warning shield because a device is
2041    /// now verified.
2042    ///
2043    /// # Arguments
2044    ///
2045    /// - `session_id` - The ID of the Megolm session to get information for.
2046    /// - `sender` - The (claimed) sender of the event where the session was
2047    ///   used.
2048    #[cfg(feature = "e2e-encryption")]
2049    pub async fn get_encryption_info(
2050        &self,
2051        session_id: &str,
2052        sender: &UserId,
2053    ) -> Option<Arc<EncryptionInfo>> {
2054        let machine = self.client.olm_machine().await;
2055        let machine = machine.as_ref()?;
2056        machine.get_session_encryption_info(self.room_id(), session_id, sender).await.ok()
2057    }
2058
2059    /// Forces the currently active room key, which is used to encrypt messages,
2060    /// to be rotated.
2061    ///
2062    /// A new room key will be crated and shared with all the room members the
2063    /// next time a message will be sent. You don't have to call this method,
2064    /// room keys will be rotated automatically when necessary. This method is
2065    /// still useful for debugging purposes.
2066    ///
2067    /// For more info please take a look a the [`encryption`] module
2068    /// documentation.
2069    ///
2070    /// [`encryption`]: crate::encryption
2071    #[cfg(feature = "e2e-encryption")]
2072    pub async fn discard_room_key(&self) -> Result<()> {
2073        let machine = self.client.olm_machine().await;
2074        if let Some(machine) = machine.as_ref() {
2075            machine.discard_room_key(self.inner.room_id()).await?;
2076            Ok(())
2077        } else {
2078            Err(Error::NoOlmMachine)
2079        }
2080    }
2081
2082    /// Ban the user with `UserId` from this room.
2083    ///
2084    /// # Arguments
2085    ///
2086    /// * `user_id` - The user to ban with `UserId`.
2087    ///
2088    /// * `reason` - The reason for banning this user.
2089    #[instrument(skip_all)]
2090    pub async fn ban_user(&self, user_id: &UserId, reason: Option<&str>) -> Result<()> {
2091        let request = assign!(
2092            ban_user::v3::Request::new(self.room_id().to_owned(), user_id.to_owned()),
2093            { reason: reason.map(ToOwned::to_owned) }
2094        );
2095        self.client.send(request).await?;
2096        Ok(())
2097    }
2098
2099    /// Unban the user with `UserId` from this room.
2100    ///
2101    /// # Arguments
2102    ///
2103    /// * `user_id` - The user to unban with `UserId`.
2104    ///
2105    /// * `reason` - The reason for unbanning this user.
2106    #[instrument(skip_all)]
2107    pub async fn unban_user(&self, user_id: &UserId, reason: Option<&str>) -> Result<()> {
2108        let request = assign!(
2109            unban_user::v3::Request::new(self.room_id().to_owned(), user_id.to_owned()),
2110            { reason: reason.map(ToOwned::to_owned) }
2111        );
2112        self.client.send(request).await?;
2113        Ok(())
2114    }
2115
2116    /// Kick a user out of this room.
2117    ///
2118    /// # Arguments
2119    ///
2120    /// - `user_id` - The `UserId` of the user that should be kicked out of the
2121    ///   room.
2122    ///
2123    /// - `reason` - Optional reason why the room member is being kicked out.
2124    #[instrument(skip_all)]
2125    pub async fn kick_user(&self, user_id: &UserId, reason: Option<&str>) -> Result<()> {
2126        let request = assign!(
2127            kick_user::v3::Request::new(self.room_id().to_owned(), user_id.to_owned()),
2128            { reason: reason.map(ToOwned::to_owned) }
2129        );
2130        self.client.send(request).await?;
2131        Ok(())
2132    }
2133
2134    /// Invite the specified user by `UserId` to this room.
2135    ///
2136    /// # Arguments
2137    ///
2138    /// * `user_id` - The `UserId` of the user to invite to the room.
2139    #[instrument(skip_all)]
2140    pub async fn invite_user_by_id(&self, user_id: &UserId) -> Result<()> {
2141        #[cfg(feature = "e2e-encryption")]
2142        if self.client.inner.enable_share_history_on_invite {
2143            shared_room_history::share_room_history(self, user_id.to_owned()).await?;
2144        }
2145
2146        let recipient = InvitationRecipient::UserId(InviteUserId::new(user_id.to_owned()));
2147        let request = invite_user::v3::Request::new(self.room_id().to_owned(), recipient);
2148        self.client.send(request).await?;
2149
2150        // Force a future room members reload before sending any event to
2151        // prevent UTDs that can happen when some event is sent after a room
2152        // member has been invited but before the /sync request could fetch the
2153        // membership change event.
2154        self.mark_members_missing();
2155
2156        Ok(())
2157    }
2158
2159    /// Invite the specified user by third party id to this room.
2160    ///
2161    /// # Arguments
2162    ///
2163    /// * `invite_id` - A third party id of a user to invite to the room.
2164    #[instrument(skip_all)]
2165    pub async fn invite_user_by_3pid(&self, invite_id: Invite3pid) -> Result<()> {
2166        let recipient = InvitationRecipient::ThirdPartyId(invite_id);
2167        let request = invite_user::v3::Request::new(self.room_id().to_owned(), recipient);
2168        self.client.send(request).await?;
2169
2170        // Force a future room members reload before sending any event to
2171        // prevent UTDs that can happen when some event is sent after a room
2172        // member has been invited but before the /sync request could fetch the
2173        // membership change event.
2174        self.mark_members_missing();
2175
2176        Ok(())
2177    }
2178
2179    /// Activate typing notice for this room.
2180    ///
2181    /// The typing notice remains active for 4s. It can be deactivate at any
2182    /// point by setting typing to `false`. If this method is called while the
2183    /// typing notice is active nothing will happen. This method can be called
2184    /// on every key stroke, since it will do nothing while typing is active.
2185    ///
2186    /// # Arguments
2187    ///
2188    /// - `typing` - Whether the user is typing or has stopped typing.
2189    ///
2190    /// # Examples
2191    ///
2192    /// ```no_run
2193    /// use std::time::Duration;
2194    ///
2195    /// use matrix_sdk::ruma::api::client::typing::create_typing_event::v3::Typing;
2196    /// # use matrix_sdk::{
2197    /// #     Client, config::SyncSettings,
2198    /// #     ruma::room_id,
2199    /// # };
2200    /// # use url::Url;
2201    ///
2202    /// # async {
2203    /// # let homeserver = Url::parse("http://localhost:8080")?;
2204    /// # let client = Client::new(homeserver).await?;
2205    /// let room_id = room_id!("!SVkFJHzfwvuaIEawgC:localhost");
2206    ///
2207    /// if let Some(room) = client.get_room(&room_id) {
2208    ///     room.typing_notice(true).await?
2209    /// }
2210    /// # anyhow::Ok(()) };
2211    /// ```
2212    pub async fn typing_notice(&self, typing: bool) -> Result<()> {
2213        self.ensure_room_joined()?;
2214
2215        // Only send a request to the homeserver if the old timeout has elapsed
2216        // or the typing notice changed state within the `TYPING_NOTICE_TIMEOUT`
2217        let send = if let Some(typing_time) =
2218            self.client.inner.typing_notice_times.read().unwrap().get(self.room_id())
2219        {
2220            if typing_time.elapsed() > TYPING_NOTICE_RESEND_TIMEOUT {
2221                // We always reactivate the typing notice if typing is true or
2222                // we may need to deactivate it if it's currently active if
2223                // typing is false
2224                typing || typing_time.elapsed() <= TYPING_NOTICE_TIMEOUT
2225            } else {
2226                // Only send a request when we need to deactivate typing
2227                !typing
2228            }
2229        } else {
2230            // Typing notice is currently deactivated, therefore, send a request
2231            // only when it's about to be activated
2232            typing
2233        };
2234
2235        if send {
2236            self.send_typing_notice(typing).await?;
2237        }
2238
2239        Ok(())
2240    }
2241
2242    #[instrument(name = "typing_notice", skip(self))]
2243    async fn send_typing_notice(&self, typing: bool) -> Result<()> {
2244        let typing = if typing {
2245            self.client
2246                .inner
2247                .typing_notice_times
2248                .write()
2249                .unwrap()
2250                .insert(self.room_id().to_owned(), Instant::now());
2251            Typing::Yes(TypingInfo::new(TYPING_NOTICE_TIMEOUT))
2252        } else {
2253            self.client.inner.typing_notice_times.write().unwrap().remove(self.room_id());
2254            Typing::No
2255        };
2256
2257        let request = create_typing_event::v3::Request::new(
2258            self.own_user_id().to_owned(),
2259            self.room_id().to_owned(),
2260            typing,
2261        );
2262
2263        self.client.send(request).await?;
2264
2265        Ok(())
2266    }
2267
2268    /// Send a request to set a single receipt.
2269    ///
2270    /// If an unthreaded receipt is sent, this will also unset the unread flag
2271    /// of the room if necessary.
2272    ///
2273    /// # Arguments
2274    ///
2275    /// - `receipt_type` - The type of the receipt to set. Note that it is
2276    ///   possible to set the fully-read marker although it is technically not a
2277    ///   receipt.
2278    ///
2279    /// - `thread` - The thread where this receipt should apply, if any. Note
2280    ///   that this must be [`ReceiptThread::Unthreaded`] when sending a
2281    ///   [`ReceiptType::FullyRead`][create_receipt::v3::ReceiptType::FullyRead].
2282    ///
2283    /// - `event_id` - The `EventId` of the event to set the receipt on.
2284    #[instrument(skip_all)]
2285    pub async fn send_single_receipt(
2286        &self,
2287        receipt_type: create_receipt::v3::ReceiptType,
2288        thread: ReceiptThread,
2289        event_id: OwnedEventId,
2290    ) -> Result<()> {
2291        // Since the receipt type and the thread aren't Hash/Ord, flatten then
2292        // as a string key.
2293        let request_key = format!("{}|{}", receipt_type, thread.as_str().unwrap_or("<unthreaded>"));
2294
2295        self.client
2296            .inner
2297            .locks
2298            .read_receipt_deduplicated_handler
2299            .run((request_key, event_id.clone()), async {
2300                // We will unset the unread flag if we send an unthreaded
2301                // receipt.
2302                let is_unthreaded = thread == ReceiptThread::Unthreaded;
2303
2304                let mut request = create_receipt::v3::Request::new(
2305                    self.room_id().to_owned(),
2306                    receipt_type,
2307                    event_id,
2308                );
2309                request.thread = thread;
2310
2311                self.client.send(request).await?;
2312
2313                if is_unthreaded {
2314                    self.set_unread_flag(false).await?;
2315                }
2316
2317                Ok(())
2318            })
2319            .await
2320    }
2321
2322    /// Send a request to set multiple receipts at once.
2323    ///
2324    /// This will also unset the unread flag of the room if necessary.
2325    ///
2326    /// # Arguments
2327    ///
2328    /// * `receipts` - The `Receipts` to send.
2329    ///
2330    /// If `receipts` is empty, this is a no-op.
2331    #[instrument(skip_all)]
2332    pub async fn send_multiple_receipts(&self, receipts: Receipts) -> Result<()> {
2333        if receipts.is_empty() {
2334            return Ok(());
2335        }
2336
2337        let Receipts { fully_read, public_read_receipt, private_read_receipt } = receipts;
2338        let request = assign!(set_read_marker::v3::Request::new(self.room_id().to_owned()), {
2339            fully_read,
2340            read_receipt: public_read_receipt,
2341            private_read_receipt,
2342        });
2343
2344        self.client.send(request).await?;
2345
2346        self.set_unread_flag(false).await?;
2347
2348        Ok(())
2349    }
2350
2351    /// Helper function to enable End-to-end encryption in this room.
2352    /// `encrypted_state_events` is not used unless the
2353    /// `experimental-encrypted-state-events` feature is enabled.
2354    #[allow(unused_variables, unused_mut)]
2355    async fn enable_encryption_inner(&self, encrypted_state_events: bool) -> Result<()> {
2356        use ruma::{
2357            EventEncryptionAlgorithm, events::room::encryption::RoomEncryptionEventContent,
2358        };
2359        const SYNC_WAIT_TIME: Duration = Duration::from_secs(3);
2360
2361        if !self.latest_encryption_state().await?.is_encrypted() {
2362            let mut content =
2363                RoomEncryptionEventContent::new(EventEncryptionAlgorithm::MegolmV1AesSha2);
2364            #[cfg(feature = "experimental-encrypted-state-events")]
2365            if encrypted_state_events {
2366                content = content.with_encrypted_state();
2367            }
2368            self.send_state_event(content).await?;
2369
2370            // Spin on the sync beat event, since the first sync we receive
2371            // might not include the encryption event.
2372            //
2373            // TODO do we want to return an error here if we time out? This
2374            // could be quite useful if someone wants to enable encryption and
2375            // send a message right after it's enabled.
2376            let res = timeout(
2377                async {
2378                    loop {
2379                        // Listen for sync events, then check if the encryption
2380                        // state is known.
2381                        self.client.inner.sync_beat.listen().await;
2382                        let _state_store_lock =
2383                            self.client.base_client().state_store_lock().lock().await;
2384
2385                        if !self.inner.encryption_state().is_unknown() {
2386                            break;
2387                        }
2388                    }
2389                },
2390                SYNC_WAIT_TIME,
2391            )
2392            .await;
2393
2394            let store_guard = self.client.base_client().state_store_lock().lock().await;
2395
2396            // If encryption was enabled, return.
2397            #[cfg(not(feature = "experimental-encrypted-state-events"))]
2398            if res.is_ok() && self.inner.encryption_state().is_encrypted() {
2399                debug!("room successfully marked as encrypted");
2400                return Ok(());
2401            }
2402
2403            // If encryption with state event encryption was enabled, return.
2404            #[cfg(feature = "experimental-encrypted-state-events")]
2405            if res.is_ok() && {
2406                if encrypted_state_events {
2407                    self.inner.encryption_state().is_state_encrypted()
2408                } else {
2409                    self.inner.encryption_state().is_encrypted()
2410                }
2411            } {
2412                debug!("room successfully marked as encrypted");
2413                return Ok(());
2414            }
2415
2416            // If after waiting for multiple syncs, we don't have the encryption
2417            // state we expect, assume the local encryption state is incorrect;
2418            // this will cause the SDK to re-request it later for confirmation,
2419            // instead of assuming it's sync'd and correct (and not encrypted).
2420            debug!("still not marked as encrypted, marking encryption state as missing");
2421
2422            self.update_and_save_room_info_with_store_guard(&store_guard, |mut info| {
2423                info.mark_encryption_state_missing();
2424                (info, RoomInfoNotableUpdateReasons::empty())
2425            })
2426            .await?;
2427        }
2428
2429        Ok(())
2430    }
2431
2432    /// Enable End-to-end encryption in this room.
2433    ///
2434    /// This method will be a noop if encryption is already enabled, otherwise
2435    /// sends a `m.room.encryption` state event to the room. This might fail if
2436    /// you don't have the appropriate power level to enable end-to-end
2437    /// encryption.
2438    ///
2439    /// A sync needs to be received to update the local room state. This method
2440    /// will wait for a sync to be received, this might time out if no sync loop
2441    /// is running or if the server is slow.
2442    ///
2443    /// # Examples
2444    ///
2445    /// ```no_run
2446    /// # use matrix_sdk::{
2447    /// #     Client, config::SyncSettings,
2448    /// #     ruma::room_id,
2449    /// # };
2450    /// # use url::Url;
2451    /// #
2452    /// # async {
2453    /// # let homeserver = Url::parse("http://localhost:8080")?;
2454    /// # let client = Client::new(homeserver).await?;
2455    /// # let room_id = room_id!("!test:localhost");
2456    /// let room_id = room_id!("!SVkFJHzfwvuaIEawgC:localhost");
2457    ///
2458    /// if let Some(room) = client.get_room(&room_id) {
2459    ///     room.enable_encryption().await?
2460    /// }
2461    /// # anyhow::Ok(()) };
2462    /// ```
2463    #[instrument(skip_all)]
2464    pub async fn enable_encryption(&self) -> Result<()> {
2465        self.enable_encryption_inner(false).await
2466    }
2467
2468    /// Enable End-to-end encryption in this room, opting into experimental
2469    /// state event encryption.
2470    ///
2471    /// This method will be a noop if encryption is already enabled, otherwise
2472    /// sends a `m.room.encryption` state event to the room. This might fail if
2473    /// you don't have the appropriate power level to enable end-to-end
2474    /// encryption.
2475    ///
2476    /// A sync needs to be received to update the local room state. This method
2477    /// will wait for a sync to be received, this might time out if no sync loop
2478    /// is running or if the server is slow.
2479    ///
2480    /// # Examples
2481    ///
2482    /// ```no_run
2483    /// # use matrix_sdk::{
2484    /// #     Client, config::SyncSettings,
2485    /// #     ruma::room_id,
2486    /// # };
2487    /// # use url::Url;
2488    /// #
2489    /// # async {
2490    /// # let homeserver = Url::parse("http://localhost:8080")?;
2491    /// # let client = Client::new(homeserver).await?;
2492    /// # let room_id = room_id!("!test:localhost");
2493    /// let room_id = room_id!("!SVkFJHzfwvuaIEawgC:localhost");
2494    ///
2495    /// if let Some(room) = client.get_room(&room_id) {
2496    ///     room.enable_encryption_with_state_event_encryption().await?
2497    /// }
2498    /// # anyhow::Ok(()) };
2499    /// ```
2500    #[instrument(skip_all)]
2501    #[cfg(feature = "experimental-encrypted-state-events")]
2502    pub async fn enable_encryption_with_state_event_encryption(&self) -> Result<()> {
2503        self.enable_encryption_inner(true).await
2504    }
2505
2506    /// Share a room key with users in the given room.
2507    ///
2508    /// This will create Olm sessions with all the users/device pairs in the
2509    /// room if necessary and share a room key that can be shared with them.
2510    ///
2511    /// Does nothing if no room key needs to be shared.
2512    // TODO: expose this publicly so people can pre-share a group session if
2513    // e.g. a user starts to type a message for a room.
2514    #[cfg(feature = "e2e-encryption")]
2515    #[instrument(skip_all, fields(room_id = ?self.room_id()))]
2516    async fn preshare_room_key(&self) -> Result<()> {
2517        self.ensure_room_joined()?;
2518
2519        // Take and release the lock on the store, if needs be.
2520        let _guard = self.client.encryption().spin_lock_store(Some(60000)).await?;
2521
2522        self.client
2523            .locks()
2524            .group_session_deduplicated_handler
2525            .run(self.room_id().to_owned(), async move {
2526                {
2527                    let members = self
2528                        .client
2529                        .state_store()
2530                        .get_user_ids(self.room_id(), RoomMemberships::ACTIVE)
2531                        .await?;
2532                    self.client.claim_one_time_keys(members.iter().map(Deref::deref)).await?;
2533                };
2534
2535                let response = self.share_room_key().await;
2536
2537                // If one of the responses failed invalidate the group session
2538                // as using it would end up in undecryptable messages.
2539                if let Err(r) = response {
2540                    let machine = self.client.olm_machine().await;
2541                    if let Some(machine) = machine.as_ref() {
2542                        machine.discard_room_key(self.room_id()).await?;
2543                    }
2544                    return Err(r);
2545                }
2546
2547                Ok(())
2548            })
2549            .await
2550    }
2551
2552    /// Share a group session for a room.
2553    ///
2554    /// # Panics
2555    ///
2556    /// Panics if the client isn't logged in.
2557    #[cfg(feature = "e2e-encryption")]
2558    #[instrument(skip_all)]
2559    async fn share_room_key(&self) -> Result<()> {
2560        self.ensure_room_joined()?;
2561
2562        let requests = self.client.base_client().share_room_key(self.room_id()).await?;
2563
2564        for request in requests {
2565            let response = self.client.send_to_device(&request).await?;
2566            self.client.mark_request_as_sent(&request.txn_id, &response).await?;
2567        }
2568
2569        Ok(())
2570    }
2571
2572    /// Wait for the room to be fully synced.
2573    ///
2574    /// This method makes sure the room that was returned when joining a room
2575    /// has been echoed back in the sync.
2576    ///
2577    /// Warning: This waits until a sync happens and does not return if no sync
2578    /// is happening. It can also return early when the room is not a joined
2579    /// room anymore.
2580    #[instrument(skip_all)]
2581    pub async fn sync_up(&self) {
2582        while !self.is_synced() && self.state() == RoomState::Joined {
2583            let wait_for_beat = self.client.inner.sync_beat.listen();
2584            // We don't care whether it's a timeout or a sync beat.
2585            let _ = timeout(wait_for_beat, Duration::from_millis(1000)).await;
2586        }
2587    }
2588
2589    /// Send a message-like event to this room.
2590    ///
2591    /// Returns the parsed response from the server.
2592    ///
2593    /// If the encryption feature is enabled this method will transparently
2594    /// encrypt the event if this room is encrypted (except for `m.reaction`
2595    /// events, which are never encrypted).
2596    ///
2597    /// **Note**: If you just want to send an event with custom JSON content to
2598    /// a room, you can use the [`send_raw()`][Self::send_raw] method for that.
2599    ///
2600    /// If you want to set a transaction ID for the event, use
2601    /// [`.with_transaction_id()`][SendMessageLikeEvent::with_transaction_id]
2602    /// on the returned value before `.await`ing it.
2603    ///
2604    /// # Arguments
2605    ///
2606    /// - `content` - The content of the message event.
2607    ///
2608    /// # Examples
2609    ///
2610    /// ```no_run
2611    /// # use std::sync::{Arc, RwLock};
2612    /// # use matrix_sdk::{Client, config::SyncSettings};
2613    /// # use url::Url;
2614    /// # use matrix_sdk::ruma::room_id;
2615    /// # use serde::{Deserialize, Serialize};
2616    /// use matrix_sdk::ruma::{
2617    ///     MilliSecondsSinceUnixEpoch, TransactionId,
2618    ///     events::{
2619    ///         macros::EventContent,
2620    ///         room::message::{RoomMessageEventContent, TextMessageEventContent},
2621    ///     },
2622    ///     uint,
2623    /// };
2624    ///
2625    /// # async {
2626    /// # let homeserver = Url::parse("http://localhost:8080")?;
2627    /// # let mut client = Client::new(homeserver).await?;
2628    /// # let room_id = room_id!("!test:localhost");
2629    /// let content = RoomMessageEventContent::text_plain("Hello world");
2630    /// let txn_id = TransactionId::new();
2631    ///
2632    /// if let Some(room) = client.get_room(&room_id) {
2633    ///     room.send(content).with_transaction_id(txn_id).await?;
2634    /// }
2635    ///
2636    /// // Custom events work too:
2637    /// #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
2638    /// #[ruma_event(type = "org.shiny_new_2fa.token", kind = MessageLike)]
2639    /// struct TokenEventContent {
2640    ///     token: String,
2641    ///     #[serde(rename = "exp")]
2642    ///     expires_at: MilliSecondsSinceUnixEpoch,
2643    /// }
2644    ///
2645    /// # fn generate_token() -> String { todo!() }
2646    /// let content = TokenEventContent {
2647    ///     token: generate_token(),
2648    ///     expires_at: {
2649    ///         let now = MilliSecondsSinceUnixEpoch::now();
2650    ///         MilliSecondsSinceUnixEpoch(now.0 + uint!(30_000))
2651    ///     },
2652    /// };
2653    ///
2654    /// if let Some(room) = client.get_room(&room_id) {
2655    ///     room.send(content).await?;
2656    /// }
2657    /// # anyhow::Ok(()) };
2658    /// ```
2659    pub fn send(&self, content: impl MessageLikeEventContent) -> SendMessageLikeEvent<'_> {
2660        SendMessageLikeEvent::new(self, content)
2661    }
2662
2663    /// Run /keys/query requests for all the non-tracked users, and for users
2664    /// with an out-of-date device list.
2665    #[cfg(feature = "e2e-encryption")]
2666    async fn query_keys_for_untracked_or_dirty_users(&self) -> Result<()> {
2667        let olm = self.client.olm_machine().await;
2668        let olm = olm.as_ref().expect("Olm machine wasn't started");
2669
2670        let members =
2671            self.client.state_store().get_user_ids(self.room_id(), RoomMemberships::ACTIVE).await?;
2672
2673        let tracked: HashMap<_, _> = olm
2674            .store()
2675            .load_tracked_users()
2676            .await?
2677            .into_iter()
2678            .map(|tracked| (tracked.user_id, tracked.dirty))
2679            .collect();
2680
2681        // A member has no unknown devices iff it was tracked _and_ the tracking
2682        // is not considered dirty.
2683        let members_with_unknown_devices =
2684            members.iter().filter(|member| tracked.get(*member).is_none_or(|dirty| *dirty));
2685
2686        let (req_id, request) =
2687            olm.query_keys_for_users(members_with_unknown_devices.map(|owned| owned.borrow()));
2688
2689        if !request.device_keys.is_empty() {
2690            self.client.keys_query(&req_id, request.device_keys).await?;
2691        }
2692
2693        Ok(())
2694    }
2695
2696    /// Send a message-like event with custom JSON content to this room.
2697    ///
2698    /// Returns the parsed response from the server.
2699    ///
2700    /// If the encryption feature is enabled this method will transparently
2701    /// encrypt the event if this room is encrypted (except for `m.reaction`
2702    /// events, which are never encrypted).
2703    ///
2704    /// This method is equivalent to the [`send()`][Self::send] method but
2705    /// allows sending custom JSON payloads, e.g. constructed using the
2706    /// [`serde_json::json!()`] macro.
2707    ///
2708    /// If you want to set a transaction ID for the event, use
2709    /// [`.with_transaction_id()`][SendRawMessageLikeEvent::with_transaction_id]
2710    /// on the returned value before `.await`ing it.
2711    ///
2712    /// # Arguments
2713    ///
2714    /// - `event_type` - The type of the event.
2715    /// - `content` - The content of the event as a raw JSON value. The argument
2716    ///   type can be `serde_json::Value`, but also other raw JSON types; for
2717    ///   the full list check the documentation of
2718    ///   [`IntoRawMessageLikeEventContent`].
2719    ///
2720    /// # Examples
2721    ///
2722    /// ```no_run
2723    /// # use std::sync::{Arc, RwLock};
2724    /// # use matrix_sdk::{Client, config::SyncSettings};
2725    /// # use url::Url;
2726    /// # use matrix_sdk::ruma::room_id;
2727    /// # async {
2728    /// # let homeserver = Url::parse("http://localhost:8080")?;
2729    /// # let mut client = Client::new(homeserver).await?;
2730    /// # let room_id = room_id!("!test:localhost");
2731    /// use serde_json::json;
2732    ///
2733    /// if let Some(room) = client.get_room(&room_id) {
2734    ///     room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;
2735    /// }
2736    /// # anyhow::Ok(()) };
2737    /// ```
2738    #[instrument(skip_all, fields(event_type, room_id = ?self.room_id(), transaction_id, is_room_encrypted, event_id))]
2739    pub fn send_raw<'a>(
2740        &'a self,
2741        event_type: &'a str,
2742        content: impl IntoRawMessageLikeEventContent,
2743    ) -> SendRawMessageLikeEvent<'a> {
2744        // Note: the recorded instrument fields are saved in
2745        // `SendRawMessageLikeEvent::into_future`.
2746        SendRawMessageLikeEvent::new(self, event_type, content)
2747    }
2748
2749    /// Send an attachment to this room.
2750    ///
2751    /// This will upload the given data that the reader produces using the
2752    /// [`upload()`] method and post an event to the given room. If the room is
2753    /// encrypted and the encryption feature is enabled the upload will be
2754    /// encrypted.
2755    ///
2756    /// This is a convenience method that calls the [`upload()`] and afterwards
2757    /// the [`send()`].
2758    ///
2759    /// # Arguments
2760    ///
2761    /// - `filename` - The file name.
2762    /// - `content_type` - The type of the media, this will be used as the
2763    /// content-type header.
2764    /// - `reader` - A `Reader` that will be used to fetch the raw bytes of the
2765    /// media.
2766    /// - `config` - Metadata and configuration for the attachment.
2767    ///
2768    /// # Examples
2769    ///
2770    /// ```no_run
2771    /// # use std::fs;
2772    /// # use matrix_sdk::{Client, ruma::room_id, attachment::AttachmentConfig};
2773    /// # use url::Url;
2774    /// # use mime;
2775    /// # async {
2776    /// # let homeserver = Url::parse("http://localhost:8080")?;
2777    /// # let mut client = Client::new(homeserver).await?;
2778    /// # let room_id = room_id!("!test:localhost");
2779    /// let mut image = fs::read("/home/example/my-cat.jpg")?;
2780    ///
2781    /// if let Some(room) = client.get_room(&room_id) {
2782    ///     room.send_attachment(
2783    ///         "my_favorite_cat.jpg",
2784    ///         &mime::IMAGE_JPEG,
2785    ///         image,
2786    ///         AttachmentConfig::new(),
2787    ///     ).await?;
2788    /// }
2789    /// # anyhow::Ok(()) };
2790    /// ```
2791    ///
2792    /// [`upload()`]: crate::Media::upload
2793    /// [`send()`]: Self::send
2794    #[instrument(skip_all)]
2795    pub fn send_attachment<'a>(
2796        &'a self,
2797        filename: impl Into<String>,
2798        content_type: &'a Mime,
2799        data: Vec<u8>,
2800        config: AttachmentConfig,
2801    ) -> SendAttachment<'a> {
2802        SendAttachment::new(self, filename.into(), content_type, data, config)
2803    }
2804
2805    /// Prepare and send an attachment to this room.
2806    ///
2807    /// This will upload the given data that the reader produces using the
2808    /// [`upload()`](#method.upload) method and post an event to the given room.
2809    /// If the room is encrypted and the encryption feature is enabled the
2810    /// upload will be encrypted.
2811    ///
2812    /// This is a convenience method that calls the
2813    /// [`Client::upload()`](#Client::method.upload) and afterwards the
2814    /// [`send()`](#method.send).
2815    ///
2816    /// # Arguments
2817    ///
2818    /// - `filename` - The file name.
2819    /// - `content_type` - The type of the media, this will be used as the
2820    ///   content-type header.
2821    ///
2822    /// - `reader` - A `Reader` that will be used to fetch the raw bytes of the
2823    ///   media.
2824    ///
2825    /// - `config` - Metadata and configuration for the attachment.
2826    /// - `send_progress` - An observable to transmit forward progress about the
2827    ///   upload.
2828    ///
2829    /// - `store_in_cache` - A boolean defining whether the uploaded media will
2830    ///   be stored in the cache immediately after a successful upload.
2831    #[instrument(skip_all)]
2832    pub(super) async fn prepare_and_send_attachment<'a>(
2833        &'a self,
2834        filename: String,
2835        content_type: &'a Mime,
2836        data: Vec<u8>,
2837        mut config: AttachmentConfig,
2838        send_progress: SharedObservable<TransmissionProgress>,
2839        store_in_cache: bool,
2840    ) -> Result<send_message_event::v3::Response> {
2841        self.ensure_room_joined()?;
2842
2843        let txn_id = config.txn_id.take();
2844        let extra_content = config.extra_content.take();
2845        let mentions = config.mentions.take();
2846
2847        let thumbnail = config.thumbnail.take();
2848
2849        // If necessary, store caching data for the thumbnail ahead of time.
2850        let thumbnail_cache_info = if store_in_cache {
2851            thumbnail
2852                .as_ref()
2853                .map(|thumbnail| (thumbnail.data.clone(), thumbnail.height, thumbnail.width))
2854        } else {
2855            None
2856        };
2857
2858        #[cfg(feature = "e2e-encryption")]
2859        let (media_source, thumbnail) = if self.latest_encryption_state().await?.is_encrypted() {
2860            self.client
2861                .upload_encrypted_media_and_thumbnail(&data, thumbnail, send_progress)
2862                .await?
2863        } else {
2864            self.client
2865                .media()
2866                .upload_plain_media_and_thumbnail(
2867                    content_type,
2868                    // TODO: get rid of this clone; wait for Ruma to use `Bytes`
2869                    // or something similar.
2870                    data.clone(),
2871                    thumbnail,
2872                    send_progress,
2873                )
2874                .await?
2875        };
2876
2877        #[cfg(not(feature = "e2e-encryption"))]
2878        let (media_source, thumbnail) = self
2879            .client
2880            .media()
2881            .upload_plain_media_and_thumbnail(content_type, data.clone(), thumbnail, send_progress)
2882            .await?;
2883
2884        if store_in_cache {
2885            let media_store_lock_guard = self.client.media_store().lock().await?;
2886
2887            // A failure to cache shouldn't prevent the whole upload from
2888            // finishing properly, so only log errors during caching.
2889
2890            debug!("caching the media");
2891            let request =
2892                MediaRequestParameters { source: media_source.clone(), format: MediaFormat::File };
2893
2894            if let Err(err) = media_store_lock_guard
2895                .add_media_content(&request, data, IgnoreMediaRetentionPolicy::No)
2896                .await
2897            {
2898                warn!("unable to cache the media after uploading it: {err}");
2899            }
2900
2901            if let Some(((data, height, width), source)) =
2902                thumbnail_cache_info.zip(thumbnail.as_ref().map(|tuple| &tuple.0))
2903            {
2904                debug!("caching the thumbnail");
2905
2906                let request = MediaRequestParameters {
2907                    source: source.clone(),
2908                    format: MediaFormat::Thumbnail(MediaThumbnailSettings::new(width, height)),
2909                };
2910
2911                if let Err(err) = media_store_lock_guard
2912                    .add_media_content(&request, data, IgnoreMediaRetentionPolicy::No)
2913                    .await
2914                {
2915                    warn!("unable to cache the media after uploading it: {err}");
2916                }
2917            }
2918        }
2919
2920        let content = self
2921            .make_media_event(
2922                Room::make_attachment_type(
2923                    content_type,
2924                    filename,
2925                    media_source,
2926                    config.caption,
2927                    config.info,
2928                    thumbnail,
2929                ),
2930                mentions,
2931                config.reply,
2932            )
2933            .await?;
2934
2935        // With extra content, the event is sent raw so the custom fields can be
2936        // included; fields of the media event itself take precedence over extra
2937        // fields with the same name.
2938        if let Some(extra_content) = extra_content.filter(|extra| !extra.is_empty()) {
2939            let serde_json::Value::Object(mut object) = serde_json::to_value(&content)
2940                .map_err(|error| Error::UnknownError(Box::new(error)))?
2941            else {
2942                unreachable!("a room message event content always serializes to a JSON object");
2943            };
2944            for (key, value) in extra_content {
2945                match object.entry(key) {
2946                    serde_json::map::Entry::Occupied(entry) => {
2947                        warn!(
2948                            key = entry.key(),
2949                            "extra content field shadowed by the event's own field"
2950                        );
2951                    }
2952                    serde_json::map::Entry::Vacant(entry) => {
2953                        entry.insert(value);
2954                    }
2955                }
2956            }
2957
2958            let event_type = content.event_type().to_string();
2959            let mut fut = self.send_raw(&event_type, serde_json::Value::Object(object));
2960            if let Some(txn_id) = &txn_id {
2961                fut = fut.with_transaction_id(txn_id);
2962            }
2963            return fut.await.map(|result| result.response);
2964        }
2965
2966        let mut fut = self.send(content);
2967        if let Some(txn_id) = txn_id {
2968            fut = fut.with_transaction_id(txn_id);
2969        }
2970
2971        fut.await.map(|result| result.response)
2972    }
2973
2974    /// Creates the inner [`MessageType`] for an already-uploaded media file
2975    /// provided by its source.
2976    #[allow(clippy::too_many_arguments)]
2977    pub(crate) fn make_attachment_type(
2978        content_type: &Mime,
2979        filename: String,
2980        source: MediaSource,
2981        caption: Option<TextMessageEventContent>,
2982        info: Option<AttachmentInfo>,
2983        thumbnail: Option<(MediaSource, Box<ThumbnailInfo>)>,
2984    ) -> MessageType {
2985        make_media_type!(MessageType, content_type, filename, source, caption, info, thumbnail)
2986    }
2987
2988    /// Creates the [`RoomMessageEventContent`] based on the message type,
2989    /// mentions and reply information.
2990    pub(crate) async fn make_media_event(
2991        &self,
2992        msg_type: MessageType,
2993        mentions: Option<Mentions>,
2994        reply: Option<Reply>,
2995    ) -> Result<RoomMessageEventContent> {
2996        let mut content = RoomMessageEventContent::new(msg_type);
2997        if let Some(mentions) = mentions {
2998            content = content.add_mentions(mentions);
2999        }
3000        if let Some(reply) = reply {
3001            // Since we just created the event, there is no relation attached to
3002            // it. Thus, it is safe to add the reply relation without overriding
3003            // anything.
3004            content = self.make_reply_event(content.into(), reply).await?;
3005        }
3006        Ok(content)
3007    }
3008
3009    /// Creates the inner [`GalleryItemType`] for an already-uploaded media file
3010    /// provided by its source.
3011    #[cfg(feature = "unstable-msc4274")]
3012    #[allow(clippy::too_many_arguments)]
3013    pub(crate) fn make_gallery_item_type(
3014        content_type: &Mime,
3015        filename: String,
3016        source: MediaSource,
3017        caption: Option<TextMessageEventContent>,
3018        info: Option<AttachmentInfo>,
3019        thumbnail: Option<(MediaSource, Box<ThumbnailInfo>)>,
3020    ) -> GalleryItemType {
3021        make_media_type!(GalleryItemType, content_type, filename, source, caption, info, thumbnail)
3022    }
3023
3024    /// Update the power levels of a select set of users of this room.
3025    ///
3026    /// Issue a `power_levels` state event request to the server, changing the
3027    /// given UserId -> Int levels. May fail if the `power_levels` aren't
3028    /// locally known yet or the server rejects the state event update, e.g.
3029    /// because of insufficient permissions. Neither permissions to update nor
3030    /// whether the data might be stale is checked prior to issuing the request.
3031    pub async fn update_power_levels(
3032        &self,
3033        updates: Vec<(&UserId, Int)>,
3034    ) -> Result<send_state_event::v3::Response> {
3035        let mut power_levels = self.power_levels().await?;
3036
3037        for (user_id, new_level) in updates {
3038            if new_level == power_levels.users_default {
3039                power_levels.users.remove(user_id);
3040            } else {
3041                power_levels.users.insert(user_id.to_owned(), new_level);
3042            }
3043        }
3044
3045        self.send_state_event(RoomPowerLevelsEventContent::try_from(power_levels)?).await
3046    }
3047
3048    /// Applies a set of power level changes to this room.
3049    ///
3050    /// Any values that are `None` in the given `RoomPowerLevelChanges` will
3051    /// remain unchanged.
3052    pub async fn apply_power_level_changes(&self, changes: RoomPowerLevelChanges) -> Result<()> {
3053        let mut power_levels = self.power_levels().await?;
3054        power_levels.apply(changes)?;
3055        self.send_state_event(RoomPowerLevelsEventContent::try_from(power_levels)?).await?;
3056        Ok(())
3057    }
3058
3059    /// Resets the room's power levels to the default values
3060    ///
3061    /// [spec]: https://spec.matrix.org/v1.9/client-server-api/#mroompower_levels
3062    pub async fn reset_power_levels(&self) -> Result<RoomPowerLevels> {
3063        let creators = self.creators().unwrap_or_default();
3064        let rules = self.clone_info().room_version_rules_or_default();
3065
3066        let default_power_levels =
3067            RoomPowerLevels::new(RoomPowerLevelsSource::None, &rules.authorization, creators);
3068        let changes = RoomPowerLevelChanges::from(default_power_levels);
3069        self.apply_power_level_changes(changes).await?;
3070        Ok(self.power_levels().await?)
3071    }
3072
3073    /// Gets the suggested role for the user with the provided `user_id`.
3074    ///
3075    /// This method checks the `RoomPowerLevels` events instead of loading the
3076    /// member list and looking for the member.
3077    pub async fn get_suggested_user_role(&self, user_id: &UserId) -> Result<RoomMemberRole> {
3078        let power_level = self.get_user_power_level(user_id).await?;
3079        Ok(RoomMemberRole::suggested_role_for_power_level(power_level))
3080    }
3081
3082    /// Gets the power level the user with the provided `user_id`.
3083    ///
3084    /// This method checks the `RoomPowerLevels` events instead of loading the
3085    /// member list and looking for the member.
3086    pub async fn get_user_power_level(&self, user_id: &UserId) -> Result<UserPowerLevel> {
3087        let event = self.power_levels().await?;
3088        Ok(event.for_user(user_id))
3089    }
3090
3091    /// Gets a map with the `UserId` of users with power levels other than `0`
3092    /// and this power level.
3093    pub async fn users_with_power_levels(&self) -> HashMap<OwnedUserId, i64> {
3094        let power_levels = self.power_levels().await.ok();
3095        let mut user_power_levels = HashMap::<OwnedUserId, i64>::new();
3096        if let Some(power_levels) = power_levels {
3097            for (id, level) in power_levels.users.into_iter() {
3098                user_power_levels.insert(id, level.into());
3099            }
3100        }
3101        user_power_levels
3102    }
3103
3104    /// Sets the name of this room.
3105    pub async fn set_name(&self, name: String) -> Result<send_state_event::v3::Response> {
3106        self.send_state_event(RoomNameEventContent::new(name)).await
3107    }
3108
3109    /// Sets a new topic for this room.
3110    pub async fn set_room_topic(&self, topic: &str) -> Result<send_state_event::v3::Response> {
3111        self.send_state_event(RoomTopicEventContent::new(topic.into())).await
3112    }
3113
3114    /// Sets the new avatar url for this room.
3115    ///
3116    /// # Arguments
3117    ///
3118    /// - `avatar_url` - The owned Matrix uri that represents the avatar
3119    /// - `info` - The optional image info that can be provided for the avatar
3120    pub async fn set_avatar_url(
3121        &self,
3122        url: &MxcUri,
3123        info: Option<avatar::ImageInfo>,
3124    ) -> Result<send_state_event::v3::Response> {
3125        self.ensure_room_joined()?;
3126
3127        let mut room_avatar_event = RoomAvatarEventContent::new();
3128        room_avatar_event.url = Some(url.to_owned());
3129        room_avatar_event.info = info.map(Box::new);
3130
3131        self.send_state_event(room_avatar_event).await
3132    }
3133
3134    /// Removes the avatar from the room
3135    pub async fn remove_avatar(&self) -> Result<send_state_event::v3::Response> {
3136        self.send_state_event(RoomAvatarEventContent::new()).await
3137    }
3138
3139    /// Uploads a new avatar for this room.
3140    ///
3141    /// # Arguments
3142    ///
3143    /// - `mime` - The mime type describing the data
3144    /// - `data` - The data representation of the avatar
3145    /// - `info` - The optional image info provided for the avatar, the blurhash
3146    ///   and the mimetype will always be updated
3147    pub async fn upload_avatar(
3148        &self,
3149        mime: &Mime,
3150        data: Vec<u8>,
3151        info: Option<avatar::ImageInfo>,
3152    ) -> Result<send_state_event::v3::Response> {
3153        self.ensure_room_joined()?;
3154
3155        let upload_response = self.client.media().upload(mime, data, None).await?;
3156        let mut info = info.unwrap_or_default();
3157        info.blurhash = upload_response.blurhash;
3158        info.mimetype = Some(mime.to_string());
3159
3160        self.set_avatar_url(&upload_response.content_uri, Some(info)).await
3161    }
3162
3163    /// Send a state event with an empty state key to the homeserver.
3164    ///
3165    /// For state events with a non-empty state key, see
3166    /// [`send_state_event_for_key`][Self::send_state_event_for_key].
3167    ///
3168    /// Returns the parsed response from the server.
3169    ///
3170    /// # Arguments
3171    ///
3172    /// - `content` - The content of the state event.
3173    ///
3174    /// # Examples
3175    ///
3176    /// ```no_run
3177    /// # use serde::{Deserialize, Serialize};
3178    /// # async {
3179    /// # let joined_room: matrix_sdk::Room = todo!();
3180    /// use matrix_sdk::ruma::{
3181    ///     EventEncryptionAlgorithm,
3182    ///     events::{
3183    ///         EmptyStateKey, macros::EventContent,
3184    ///         room::encryption::RoomEncryptionEventContent,
3185    ///     },
3186    /// };
3187    ///
3188    /// let encryption_event_content = RoomEncryptionEventContent::new(
3189    ///     EventEncryptionAlgorithm::MegolmV1AesSha2,
3190    /// );
3191    /// joined_room.send_state_event(encryption_event_content).await?;
3192    ///
3193    /// // Custom event:
3194    /// #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
3195    /// #[ruma_event(
3196    ///     type = "org.matrix.msc_9000.xxx",
3197    ///     kind = State,
3198    ///     state_key_type = EmptyStateKey,
3199    /// )]
3200    /// struct XxxStateEventContent {/* fields... */}
3201    ///
3202    /// let content: XxxStateEventContent = todo!();
3203    /// joined_room.send_state_event(content).await?;
3204    /// # anyhow::Ok(()) };
3205    /// ```
3206    #[cfg(not(feature = "experimental-encrypted-state-events"))]
3207    #[instrument(skip_all)]
3208    pub async fn send_state_event(
3209        &self,
3210        content: impl StateEventContent<StateKey = EmptyStateKey>,
3211    ) -> Result<send_state_event::v3::Response> {
3212        self.send_state_event_for_key(&EmptyStateKey, content).await
3213    }
3214
3215    /// Send a state event with an empty state key to the homeserver.
3216    ///
3217    /// For state events with a non-empty state key, see
3218    /// [`send_state_event_for_key`][Self::send_state_event_for_key].
3219    ///
3220    /// If the experimental state event encryption feature is enabled, this
3221    /// method will transparently encrypt the event if this room is encrypted
3222    /// (except if the event type is considered critical for the room to
3223    /// function, as outlined in [MSC4362][msc4362]).
3224    ///
3225    /// Returns the parsed response from the server.
3226    ///
3227    /// # Arguments
3228    ///
3229    /// - `content` - The content of the state event.
3230    ///
3231    /// # Examples
3232    ///
3233    /// ```no_run
3234    /// # use serde::{Deserialize, Serialize};
3235    /// # async {
3236    /// # let joined_room: matrix_sdk::Room = todo!();
3237    /// use matrix_sdk::ruma::{
3238    ///     EventEncryptionAlgorithm,
3239    ///     events::{
3240    ///         EmptyStateKey, macros::EventContent,
3241    ///         room::encryption::RoomEncryptionEventContent,
3242    ///     },
3243    /// };
3244    ///
3245    /// let encryption_event_content = RoomEncryptionEventContent::new(
3246    ///     EventEncryptionAlgorithm::MegolmV1AesSha2,
3247    /// );
3248    /// joined_room.send_state_event(encryption_event_content).await?;
3249    ///
3250    /// // Custom event:
3251    /// #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
3252    /// #[ruma_event(
3253    ///     type = "org.matrix.msc_9000.xxx",
3254    ///     kind = State,
3255    ///     state_key_type = EmptyStateKey,
3256    /// )]
3257    /// struct XxxStateEventContent {/* fields... */}
3258    ///
3259    /// let content: XxxStateEventContent = todo!();
3260    /// joined_room.send_state_event(content).await?;
3261    /// # anyhow::Ok(()) };
3262    /// ```
3263    ///
3264    /// [msc4362]: https://github.com/matrix-org/matrix-spec-proposals/blob/travis/msc/encrypted-state/proposals/4362-encrypted-state.md
3265    #[cfg(feature = "experimental-encrypted-state-events")]
3266    #[instrument(skip_all)]
3267    pub fn send_state_event<'a>(
3268        &'a self,
3269        content: impl StateEventContent<StateKey = EmptyStateKey>,
3270    ) -> SendStateEvent<'a> {
3271        self.send_state_event_for_key(&EmptyStateKey, content)
3272    }
3273
3274    /// Send a state event to the homeserver.
3275    ///
3276    /// Returns the parsed response from the server.
3277    ///
3278    /// # Arguments
3279    ///
3280    /// - `content` - The content of the state event.
3281    /// - `state_key` - A unique key which defines the overwriting semantics for
3282    ///   this piece of room state.
3283    ///
3284    /// # Examples
3285    ///
3286    /// ```no_run
3287    /// # use serde::{Deserialize, Serialize};
3288    /// # async {
3289    /// # let joined_room: matrix_sdk::Room = todo!();
3290    /// use matrix_sdk::ruma::{
3291    ///     events::{
3292    ///         macros::EventContent,
3293    ///         room::member::{RoomMemberEventContent, MembershipState},
3294    ///     },
3295    ///     mxc_uri,
3296    /// };
3297    ///
3298    /// let avatar_url = mxc_uri!("mxc://example.org/avatar").to_owned();
3299    /// let mut content = RoomMemberEventContent::new(MembershipState::Join);
3300    /// content.avatar_url = Some(avatar_url);
3301    ///
3302    /// joined_room.send_state_event_for_key(ruma::user_id!("@foo:bar.com"), content).await?;
3303    ///
3304    /// // Custom event:
3305    /// #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
3306    /// #[ruma_event(type = "org.matrix.msc_9000.xxx", kind = State, state_key_type = String)]
3307    /// struct XxxStateEventContent { /* fields... */ }
3308    ///
3309    /// let content: XxxStateEventContent = todo!();
3310    /// joined_room.send_state_event_for_key("foo", content).await?;
3311    /// # anyhow::Ok(()) };
3312    /// ```
3313    #[cfg(not(feature = "experimental-encrypted-state-events"))]
3314    pub async fn send_state_event_for_key<C, K>(
3315        &self,
3316        state_key: &K,
3317        content: C,
3318    ) -> Result<send_state_event::v3::Response>
3319    where
3320        C: StateEventContent,
3321        C::StateKey: Borrow<K>,
3322        K: AsRef<str> + ?Sized,
3323    {
3324        self.ensure_room_joined()?;
3325        let request =
3326            send_state_event::v3::Request::new(self.room_id().to_owned(), state_key, &content)?;
3327        let response = self.client.send(request).await?;
3328        Ok(response)
3329    }
3330
3331    /// Send a state event to the homeserver. If state encryption is enabled in
3332    /// this room, the event will be encrypted.
3333    ///
3334    /// If the experimental state event encryption feature is enabled, this
3335    /// method will transparently encrypt the event if this room is encrypted
3336    /// (except if the event type is considered critical for the room to
3337    /// function, as outlined in [MSC4362][msc4362]).
3338    ///
3339    /// Returns the parsed response from the server.
3340    ///
3341    /// # Arguments
3342    ///
3343    /// - `content` - The content of the state event.
3344    /// - `state_key` - A unique key which defines the overwriting semantics for
3345    ///   this piece of room state.
3346    ///
3347    /// # Examples
3348    ///
3349    /// ```no_run
3350    /// # use serde::{Deserialize, Serialize};
3351    /// # async {
3352    /// # let joined_room: matrix_sdk::Room = todo!();
3353    /// use matrix_sdk::ruma::{
3354    ///     events::{
3355    ///         macros::EventContent,
3356    ///         room::member::{RoomMemberEventContent, MembershipState},
3357    ///     },
3358    ///     mxc_uri,
3359    /// };
3360    ///
3361    /// let avatar_url = mxc_uri!("mxc://example.org/avatar").to_owned();
3362    /// let mut content = RoomMemberEventContent::new(MembershipState::Join);
3363    /// content.avatar_url = Some(avatar_url);
3364    ///
3365    /// joined_room.send_state_event_for_key(ruma::user_id!("@foo:bar.com"), content).await?;
3366    ///
3367    /// // Custom event:
3368    /// #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
3369    /// #[ruma_event(type = "org.matrix.msc_9000.xxx", kind = State, state_key_type = String)]
3370    /// struct XxxStateEventContent { /* fields... */ }
3371    ///
3372    /// let content: XxxStateEventContent = todo!();
3373    /// joined_room.send_state_event_for_key("foo", content).await?;
3374    /// # anyhow::Ok(()) };
3375    /// ```
3376    ///
3377    /// [msc4362]: https://github.com/matrix-org/matrix-spec-proposals/pull/4362
3378    #[cfg(feature = "experimental-encrypted-state-events")]
3379    pub fn send_state_event_for_key<'a, C, K>(
3380        &'a self,
3381        state_key: &K,
3382        content: C,
3383    ) -> SendStateEvent<'a>
3384    where
3385        C: StateEventContent,
3386        C::StateKey: Borrow<K>,
3387        K: AsRef<str> + ?Sized,
3388    {
3389        SendStateEvent::new(self, state_key, content)
3390    }
3391
3392    /// Send a raw room state event to the homeserver.
3393    ///
3394    /// If the experimental state event encryption feature is enabled, this
3395    /// method will transparently encrypt the event if this room is encrypted
3396    /// (except if the event type is considered critical for the room to
3397    /// function, as outlined in [MSC4362][msc4362]).
3398    ///
3399    /// Returns the parsed response from the server.
3400    ///
3401    /// # Arguments
3402    ///
3403    /// - `event_type` - The type of the event that we're sending out.
3404    /// - `state_key` - A unique key which defines the overwriting semantics for
3405    /// this piece of room state. This value is often a zero-length string.
3406    /// - `content` - The content of the event as a raw JSON value. The argument
3407    ///   type can be `serde_json::Value`, but also other raw JSON types; for
3408    ///   the full list check the documentation of [`IntoRawStateEventContent`].
3409    ///
3410    /// # Examples
3411    ///
3412    /// ```no_run
3413    /// use serde_json::json;
3414    ///
3415    /// # async {
3416    /// # let homeserver = url::Url::parse("http://localhost:8080")?;
3417    /// # let mut client = matrix_sdk::Client::new(homeserver).await?;
3418    /// # let room_id = matrix_sdk::ruma::room_id!("!test:localhost");
3419    ///
3420    /// if let Some(room) = client.get_room(&room_id) {
3421    ///     room.send_state_event_raw("m.room.member", "", json!({
3422    ///         "avatar_url": "mxc://example.org/SEsfnsuifSDFSSEF",
3423    ///         "displayname": "Alice Margatroid",
3424    ///         "membership": "join",
3425    ///     })).await?;
3426    /// }
3427    /// # anyhow::Ok(()) };
3428    /// ```
3429    ///
3430    /// [msc4362]: https://github.com/matrix-org/matrix-spec-proposals/pull/4362
3431    #[instrument(skip_all)]
3432    pub fn send_state_event_raw<'a>(
3433        &'a self,
3434        event_type: &'a str,
3435        state_key: &'a str,
3436        content: impl IntoRawStateEventContent,
3437    ) -> SendRawStateEvent<'a> {
3438        SendRawStateEvent::new(self, event_type, state_key, content)
3439    }
3440
3441    /// Strips all information out of an event of the room.
3442    ///
3443    /// Returns the [`redact_event::v3::Response`] from the server.
3444    ///
3445    /// This cannot be undone. Users may redact their own events, and any user
3446    /// with a power level greater than or equal to the redact power level of
3447    /// the room may redact events there.
3448    ///
3449    /// # Arguments
3450    ///
3451    /// - `event_id` - The ID of the event to redact
3452    /// - `reason` - The reason for the event being redacted.
3453    /// - `txn_id` - A unique ID that can be attached to this event as
3454    /// its transaction ID. If not given one is created for the message.
3455    ///
3456    /// # Examples
3457    ///
3458    /// ```no_run
3459    /// use matrix_sdk::ruma::event_id;
3460    ///
3461    /// # async {
3462    /// # let homeserver = url::Url::parse("http://localhost:8080")?;
3463    /// # let mut client = matrix_sdk::Client::new(homeserver).await?;
3464    /// # let room_id = matrix_sdk::ruma::room_id!("!test:localhost");
3465    /// #
3466    /// if let Some(room) = client.get_room(&room_id) {
3467    ///     let event_id = event_id!("$xxxxxx:example.org");
3468    ///     let reason = Some("Indecent material");
3469    ///     room.redact(&event_id, reason, None).await?;
3470    /// }
3471    /// # anyhow::Ok(()) };
3472    /// ```
3473    #[instrument(skip_all)]
3474    pub async fn redact(
3475        &self,
3476        event_id: &EventId,
3477        reason: Option<&str>,
3478        txn_id: Option<OwnedTransactionId>,
3479    ) -> HttpResult<redact_event::v3::Response> {
3480        let txn_id = txn_id.unwrap_or_else(TransactionId::new);
3481        let request = assign!(
3482            redact_event::v3::Request::new(self.room_id().to_owned(), event_id.to_owned(), txn_id),
3483            { reason: reason.map(ToOwned::to_owned) }
3484        );
3485
3486        self.client.send(request).await
3487    }
3488
3489    /// Get a list of servers that should know this room.
3490    ///
3491    /// Uses the synced members of the room and the suggested
3492    /// [routing algorithm] from the Matrix spec.
3493    ///
3494    /// Returns at most three servers.
3495    ///
3496    /// [routing algorithm]: https://spec.matrix.org/v1.3/appendices/#routing
3497    pub async fn route(&self) -> Result<Vec<OwnedServerName>> {
3498        let acl_ev = self
3499            .get_state_event_static::<RoomServerAclEventContent>()
3500            .await?
3501            .and_then(|ev| ev.deserialize().ok());
3502        let acl = acl_ev.as_ref().and_then(|ev| match ev {
3503            SyncOrStrippedState::Sync(ev) => ev.as_original().map(|ev| &ev.content),
3504            SyncOrStrippedState::Stripped(ev) => Some(&ev.content),
3505        });
3506
3507        // Filter out server names that:
3508        //
3509        // - Are blocked due to server ACLs
3510        // - Are IP addresses
3511        let members: Vec<_> = self
3512            .members_no_sync(RoomMemberships::JOIN)
3513            .await?
3514            .into_iter()
3515            .filter(|member| {
3516                let server = member.user_id().server_name();
3517                acl.filter(|acl| !acl.is_allowed(server)).is_none() && !server.is_ip_literal()
3518            })
3519            .collect();
3520
3521        // Get the server of the highest power level user in the room, provided
3522        // they are at least power level 50.
3523        let max = members
3524            .iter()
3525            .max_by_key(|member| member.power_level())
3526            .filter(|max| max.power_level() >= int!(50))
3527            .map(|member| member.user_id().server_name());
3528
3529        // Sort the servers by population.
3530        let servers = members
3531            .iter()
3532            .map(|member| member.user_id().server_name())
3533            .filter(|server| max.filter(|max| max == server).is_none())
3534            .fold(BTreeMap::<_, u32>::new(), |mut servers, server| {
3535                *servers.entry(server).or_default() += 1;
3536                servers
3537            });
3538        let mut servers: Vec<_> = servers.into_iter().collect();
3539        servers.sort_unstable_by(|(_, count_a), (_, count_b)| count_b.cmp(count_a));
3540
3541        Ok(max
3542            .into_iter()
3543            .chain(servers.into_iter().map(|(name, _)| name))
3544            .take(3)
3545            .map(ToOwned::to_owned)
3546            .collect())
3547    }
3548
3549    /// Get a `matrix.to` permalink to this room.
3550    ///
3551    /// If this room has an alias, we use it. Otherwise, we try to use the
3552    /// synced members in the room for [routing] the room ID.
3553    ///
3554    /// [routing]: https://spec.matrix.org/v1.3/appendices/#routing
3555    pub async fn matrix_to_permalink(&self) -> Result<MatrixToUri> {
3556        if let Some(alias) = self.canonical_alias().or_else(|| self.alt_aliases().pop()) {
3557            return Ok(alias.matrix_to_uri());
3558        }
3559
3560        let via = self.route().await?;
3561        Ok(self.room_id().matrix_to_uri_via(via))
3562    }
3563
3564    /// Get a `matrix:` permalink to this room.
3565    ///
3566    /// If this room has an alias, we use it. Otherwise, we try to use the
3567    /// synced members in the room for [routing] the room ID.
3568    ///
3569    /// # Arguments
3570    ///
3571    /// - `join` - Whether the user should join the room.
3572    ///
3573    /// [routing]: https://spec.matrix.org/v1.3/appendices/#routing
3574    pub async fn matrix_permalink(&self, join: bool) -> Result<MatrixUri> {
3575        if let Some(alias) = self.canonical_alias().or_else(|| self.alt_aliases().pop()) {
3576            return Ok(alias.matrix_uri(join));
3577        }
3578
3579        let via = self.route().await?;
3580        Ok(self.room_id().matrix_uri_via(via, join))
3581    }
3582
3583    /// Get a `matrix.to` permalink to an event in this room.
3584    ///
3585    /// We try to use the synced members in the room for [routing] the room ID.
3586    ///
3587    /// _Note_: This method does not check if the given event ID is actually
3588    /// part of this room. It needs to be checked before calling this method
3589    /// otherwise the permalink won't work.
3590    ///
3591    /// # Arguments
3592    ///
3593    /// - `event_id` - The ID of the event.
3594    ///
3595    /// [routing]: https://spec.matrix.org/v1.3/appendices/#routing
3596    pub async fn matrix_to_event_permalink(
3597        &self,
3598        event_id: impl Into<OwnedEventId>,
3599    ) -> Result<MatrixToUri> {
3600        // Don't use the alias because an event is tied to a room ID, but an
3601        // alias might point to another room, e.g. after a room upgrade.
3602        let via = self.route().await?;
3603        Ok(self.room_id().matrix_to_event_uri_via(event_id, via))
3604    }
3605
3606    /// Get a `matrix:` permalink to an event in this room.
3607    ///
3608    /// We try to use the synced members in the room for [routing] the room ID.
3609    ///
3610    /// _Note_: This method does not check if the given event ID is actually
3611    /// part of this room. It needs to be checked before calling this method
3612    /// otherwise the permalink won't work.
3613    ///
3614    /// # Arguments
3615    ///
3616    /// - `event_id` - The ID of the event.
3617    ///
3618    /// [routing]: https://spec.matrix.org/v1.3/appendices/#routing
3619    pub async fn matrix_event_permalink(
3620        &self,
3621        event_id: impl Into<OwnedEventId>,
3622    ) -> Result<MatrixUri> {
3623        // Don't use the alias because an event is tied to a room ID, but an
3624        // alias might point to another room, e.g. after a room upgrade.
3625        let via = self.route().await?;
3626        Ok(self.room_id().matrix_event_uri_via(event_id, via))
3627    }
3628
3629    /// Get the latest receipt of a user in this room.
3630    ///
3631    /// # Arguments
3632    ///
3633    /// - `receipt_type` - The type of receipt to get.
3634    /// - `receipt_thread` - The thread a receipt applies to.
3635    /// - `user_id` - The ID of the user.
3636    ///
3637    /// Returns the ID of the event on which the receipt applies and the
3638    /// receipt.
3639    pub async fn load_user_receipt(
3640        &self,
3641        receipt_type: ReceiptType,
3642        receipt_thread: &ReceiptThread,
3643        user_id: &UserId,
3644    ) -> Result<Option<(OwnedEventId, Receipt)>> {
3645        self.inner
3646            .load_user_receipt(receipt_type, receipt_thread, user_id)
3647            .await
3648            .map_err(Into::into)
3649    }
3650
3651    /// Load the receipts for an event in this room from storage.
3652    ///
3653    /// # Arguments
3654    ///
3655    /// - `receipt_type` - The type of receipt to get.
3656    /// - `receipt_thread` - The thread a receipt applies to.
3657    /// - `event_id` - The ID of the event.
3658    ///
3659    /// Returns a list of IDs of users who have sent a receipt for the event and
3660    /// the corresponding receipts.
3661    pub async fn load_event_receipts(
3662        &self,
3663        receipt_type: ReceiptType,
3664        receipt_thread: &ReceiptThread,
3665        event_id: &EventId,
3666    ) -> Result<Vec<(OwnedUserId, Receipt)>> {
3667        self.inner
3668            .load_event_receipts(receipt_type, receipt_thread, event_id)
3669            .await
3670            .map_err(Into::into)
3671    }
3672
3673    /// Get the push-condition context for this room.
3674    ///
3675    /// Returns `None` if some data couldn't be found. This should only happen
3676    /// in brand new rooms, while we process its state.
3677    pub async fn push_condition_room_ctx(&self) -> Result<Option<PushConditionRoomCtx>> {
3678        self.push_condition_room_ctx_internal(self.client.enabled_thread_subscriptions().await?)
3679            .await
3680    }
3681
3682    /// Get the push-condition context for this room, with a choice to include
3683    /// thread subscriptions or not, based on the extra
3684    /// `with_threads_subscriptions` parameter.
3685    ///
3686    /// Returns `None` if some data couldn't be found. This should only happen
3687    /// in brand new rooms, while we process its state.
3688    pub(crate) async fn push_condition_room_ctx_internal(
3689        &self,
3690        with_threads_subscriptions: bool,
3691    ) -> Result<Option<PushConditionRoomCtx>> {
3692        let room_id = self.room_id();
3693        let user_id = self.own_user_id();
3694        let room_info = self.clone_info();
3695        let member_count = room_info.active_members_count();
3696
3697        let user_display_name = if let Some(member) = self.get_member_no_sync(user_id).await? {
3698            member.name().to_owned()
3699        } else {
3700            return Ok(None);
3701        };
3702
3703        let power_levels = match self.power_levels().await {
3704            Ok(power_levels) => Some(power_levels.into()),
3705            Err(error) => {
3706                if matches!(room_info.state(), RoomState::Joined) {
3707                    // It's normal to not have the power levels in a non-joined
3708                    // room, so don't log the error if the room is not joined
3709                    error!("Could not compute power levels for push conditions: {error}");
3710                }
3711                None
3712            }
3713        };
3714
3715        let mut ctx = assign!(PushConditionRoomCtx::new(
3716            room_id.to_owned(),
3717            UInt::new(member_count).unwrap_or(UInt::MAX),
3718            user_id.to_owned(),
3719            user_display_name,
3720        ),
3721        {
3722            power_levels,
3723        });
3724
3725        if with_threads_subscriptions {
3726            let this = self.clone();
3727            ctx = ctx.with_has_thread_subscription_fn(move |event_id: &EventId| {
3728                let room = this.clone();
3729                Box::pin(async move {
3730                    if let Ok(maybe_sub) = room.load_or_fetch_thread_subscription(event_id).await {
3731                        maybe_sub.is_some()
3732                    } else {
3733                        false
3734                    }
3735                })
3736            });
3737        }
3738
3739        Ok(Some(ctx))
3740    }
3741
3742    /// Retrieves a [`PushContext`] that can be used to compute the push actions
3743    /// for events.
3744    pub async fn push_context(&self) -> Result<Option<PushContext>> {
3745        self.push_context_internal(self.client.enabled_thread_subscriptions().await?).await
3746    }
3747
3748    /// Retrieves a [`PushContext`] that can be used to compute the push actions
3749    /// for events, with a choice to include thread subscriptions or not, based
3750    /// on the extra `with_threads_subscriptions` parameter.
3751    #[instrument(skip(self))]
3752    pub(crate) async fn push_context_internal(
3753        &self,
3754        with_threads_subscriptions: bool,
3755    ) -> Result<Option<PushContext>> {
3756        let Some(push_condition_room_ctx) =
3757            self.push_condition_room_ctx_internal(with_threads_subscriptions).await?
3758        else {
3759            debug!("Could not aggregate push context");
3760            return Ok(None);
3761        };
3762        let push_rules = self.client().account().push_rules().await?;
3763        Ok(Some(PushContext::new(push_condition_room_ctx, push_rules)))
3764    }
3765
3766    /// Get the push actions for the given event with the current room state.
3767    ///
3768    /// Note that it is possible that no push action is returned because the
3769    /// current room state does not have all the required state events.
3770    pub async fn event_push_actions<T>(&self, event: &Raw<T>) -> Result<Option<Vec<Action>>> {
3771        if let Some(ctx) = self.push_context().await? {
3772            Ok(Some(ctx.for_event(event).await))
3773        } else {
3774            Ok(None)
3775        }
3776    }
3777
3778    /// The membership details of the (latest) invite for the logged-in user in
3779    /// this room.
3780    pub async fn invite_details(&self) -> Result<Invite> {
3781        let state = self.state();
3782
3783        if state != RoomState::Invited {
3784            return Err(Error::WrongRoomState(Box::new(WrongRoomState::new("Invited", state))));
3785        }
3786
3787        let invitee = self
3788            .get_member_no_sync(self.own_user_id())
3789            .await?
3790            .ok_or_else(|| Error::UnknownError(Box::new(InvitationError::EventMissing)))?;
3791        let event = invitee.event();
3792
3793        let inviter_id = event.sender().to_owned();
3794        let inviter = self.get_member_no_sync(&inviter_id).await?;
3795
3796        Ok(Invite { invitee, inviter_id, inviter })
3797    }
3798
3799    /// Get the membership details for the current user.
3800    ///
3801    /// Returns:
3802    ///     - If the user was present in the room, a
3803    ///       [`RoomMemberWithSenderInfo`] containing both the user info and the
3804    ///       member info of the sender of the `m.room.member` event.
3805    ///     - If the current user is not present, an error.
3806    pub async fn member_with_sender_info(
3807        &self,
3808        user_id: &UserId,
3809    ) -> Result<RoomMemberWithSenderInfo> {
3810        let Some(member) = self.get_member_no_sync(user_id).await? else {
3811            return Err(Error::InsufficientData);
3812        };
3813
3814        let sender_member = if let Some(member) =
3815            self.get_member_no_sync(member.event().sender()).await?
3816        {
3817            // If the sender room member info is already available, return it
3818            Some(member)
3819        } else if self.are_members_synced() {
3820            // The room members are synced and we couldn't find the sender info
3821            None
3822        } else if self.sync_members().await.is_ok() {
3823            // Try getting the sender room member info again after syncing
3824            self.get_member_no_sync(member.event().sender()).await?
3825        } else {
3826            None
3827        };
3828
3829        Ok(RoomMemberWithSenderInfo { room_member: member, sender_info: sender_member })
3830    }
3831
3832    /// Forget this room.
3833    ///
3834    /// This communicates to the homeserver that it should forget the room.
3835    ///
3836    /// Only left or banned-from rooms can be forgotten.
3837    pub async fn forget(&self) -> Result<()> {
3838        let state = self.state();
3839        match state {
3840            RoomState::Joined | RoomState::Invited | RoomState::Knocked => {
3841                return Err(Error::WrongRoomState(Box::new(WrongRoomState::new(
3842                    "Left / Banned",
3843                    state,
3844                ))));
3845            }
3846            RoomState::Left | RoomState::Banned => {}
3847        }
3848
3849        let room_id = self.room_id();
3850
3851        let request = forget_room::v3::Request::new(room_id.to_owned());
3852        let _response = self.client.send(request).await?;
3853
3854        // If it was a DM, remove the room from the `m.direct` global account
3855        // data.
3856        if self.inner.direct_targets_length() != 0
3857            && let Err(e) = self.set_is_direct(false).await
3858        {
3859            // It is not important whether we managed to remove the room, it
3860            // will not have any consequences, so just log the error.
3861            warn!(?room_id, "failed to remove room from m.direct account data: {e}");
3862        }
3863
3864        self.client.base_client().forget_room(room_id).await?;
3865
3866        if let Some(event_cache) = self.client.event_cache() {
3867            event_cache.forget_room(room_id).await?;
3868        }
3869
3870        Ok(())
3871    }
3872
3873    fn ensure_room_joined(&self) -> Result<()> {
3874        let state = self.state();
3875        if state == RoomState::Joined {
3876            Ok(())
3877        } else {
3878            Err(Error::WrongRoomState(Box::new(WrongRoomState::new("Joined", state))))
3879        }
3880    }
3881
3882    /// Get the notification mode.
3883    pub async fn notification_mode(&self) -> Option<RoomNotificationMode> {
3884        if !matches!(self.state(), RoomState::Joined) {
3885            return None;
3886        }
3887
3888        let notification_settings = self.client().notification_settings().await;
3889
3890        // Get the user-defined mode if available
3891        let notification_mode =
3892            notification_settings.get_user_defined_room_notification_mode(self.room_id()).await;
3893
3894        if notification_mode.is_some() {
3895            notification_mode
3896        } else if let Ok(is_encrypted) =
3897            self.latest_encryption_state().await.map(|state| state.is_encrypted())
3898        {
3899            // Otherwise, if encrypted status is available, get the default mode
3900            // for this type of room. From the point of view of notification
3901            // settings, a `one-to-one` room is one that involves exactly two
3902            // people.
3903            let is_one_to_one = IsOneToOne::from(self.active_members_count() == 2);
3904            let default_mode = notification_settings
3905                .get_default_room_notification_mode(IsEncrypted::from(is_encrypted), is_one_to_one)
3906                .await;
3907            Some(default_mode)
3908        } else {
3909            None
3910        }
3911    }
3912
3913    /// Get the user-defined notification mode.
3914    ///
3915    /// The result is cached for fast and non-async call. To read the cached
3916    /// result, use
3917    /// [`matrix_sdk_base::Room::cached_user_defined_notification_mode`].
3918    // Note for maintainers:
3919    //
3920    // The fact the result is cached is an important property. If you change
3921    // that in the future, please review all calls to this method.
3922    pub async fn user_defined_notification_mode(&self) -> Option<RoomNotificationMode> {
3923        if !matches!(self.state(), RoomState::Joined) {
3924            return None;
3925        }
3926
3927        let notification_settings = self.client().notification_settings().await;
3928
3929        // Get the user-defined mode if available.
3930        let mode =
3931            notification_settings.get_user_defined_room_notification_mode(self.room_id()).await;
3932
3933        if let Some(mode) = mode {
3934            self.update_cached_user_defined_notification_mode(mode);
3935        }
3936
3937        mode
3938    }
3939
3940    /// Report an event as inappropriate to the homeserver's administrator.
3941    ///
3942    /// # Arguments
3943    ///
3944    /// - `event_id` - The ID of the event to report.
3945    /// - `score` - The score to rate this content.
3946    /// - `reason` - The reason the content is being reported.
3947    ///
3948    /// # Errors
3949    ///
3950    /// Returns an error if the room is not joined or if an error occurs with
3951    /// the request.
3952    pub async fn report_content(
3953        &self,
3954        event_id: OwnedEventId,
3955        reason: Option<String>,
3956    ) -> Result<report_content::v3::Response> {
3957        let state = self.state();
3958        if state != RoomState::Joined {
3959            return Err(Error::WrongRoomState(Box::new(WrongRoomState::new("Joined", state))));
3960        }
3961
3962        let request = assign!(
3963            report_content::v3::Request::new(
3964                self.inner.room_id().to_owned(),
3965                event_id,
3966            ), {
3967                reason: reason
3968            }
3969        );
3970        Ok(self.client.send(request).await?)
3971    }
3972
3973    /// Reports a room as inappropriate to the server. The caller is not
3974    /// required to be joined to the room to report it.
3975    ///
3976    /// # Arguments
3977    ///
3978    /// - `reason` - The reason the room is being reported.
3979    ///
3980    /// # Errors
3981    ///
3982    /// Returns an error if the room is not found or on rate limit
3983    pub async fn report_room(&self, reason: String) -> Result<report_room::v3::Response> {
3984        let request = report_room::v3::Request::new(self.inner.room_id().to_owned(), reason);
3985
3986        Ok(self.client.send(request).await?)
3987    }
3988
3989    /// Set a flag on the room to indicate that the user has explicitly marked
3990    /// it as (un)read.
3991    ///
3992    /// This is a no-op if [`BaseRoom::is_marked_unread()`] returns the same
3993    /// value as `unread`.
3994    pub async fn set_unread_flag(&self, unread: bool) -> Result<()> {
3995        if self.is_marked_unread() == unread {
3996            // The request is not necessary.
3997            return Ok(());
3998        }
3999
4000        let user_id = self.client.user_id().ok_or(Error::AuthenticationRequired)?;
4001
4002        let content = MarkedUnreadEventContent::new(unread);
4003
4004        let request = set_room_account_data::v3::Request::new(
4005            user_id.to_owned(),
4006            self.inner.room_id().to_owned(),
4007            &content,
4008        )?;
4009
4010        self.client.send(request).await?;
4011        Ok(())
4012    }
4013
4014    /// Get the beacon information event in the room for the `user_id`.
4015    ///
4016    /// # Errors
4017    ///
4018    /// Returns an error if the event is redacted, stripped, not found or could
4019    /// not be deserialized.
4020    pub(crate) async fn get_user_beacon_info(
4021        &self,
4022        user_id: &UserId,
4023    ) -> Result<OriginalSyncStateEvent<BeaconInfoEventContent>, BeaconError> {
4024        let raw_event = self
4025            .get_state_event_static_for_key::<BeaconInfoEventContent, _>(user_id)
4026            .await?
4027            .ok_or(BeaconError::NotFound)?;
4028
4029        match raw_event.deserialize()? {
4030            SyncOrStrippedState::Sync(SyncStateEvent::Original(beacon_info)) => Ok(beacon_info),
4031            SyncOrStrippedState::Sync(SyncStateEvent::Redacted(_)) => Err(BeaconError::Redacted),
4032            SyncOrStrippedState::Stripped(_) => Err(BeaconError::Stripped),
4033        }
4034    }
4035
4036    /// Start sharing live location in the room.
4037    ///
4038    /// # Arguments
4039    ///
4040    /// - `duration_millis` - The duration for which the live location is
4041    ///   shared, in milliseconds.
4042    /// - `description` - An optional description for the live location share.
4043    ///
4044    /// # Errors
4045    ///
4046    /// Returns an error if the room is not joined or if the state event could
4047    /// not be sent.
4048    pub async fn start_live_location_share(
4049        &self,
4050        duration_millis: u64,
4051        description: Option<String>,
4052    ) -> Result<send_state_event::v3::Response> {
4053        self.ensure_room_joined()?;
4054
4055        self.send_state_event_for_key(
4056            self.own_user_id(),
4057            BeaconInfoEventContent::new(
4058                description,
4059                Duration::from_millis(duration_millis),
4060                true,
4061                None,
4062            ),
4063        )
4064        .await
4065    }
4066
4067    /// Stop sharing live location in the room.
4068    ///
4069    /// # Errors
4070    ///
4071    /// Returns an error if the room is not joined, if the beacon information is
4072    /// redacted or stripped, if the state event is not found, or if the
4073    /// existing beacon is no longer live.
4074    pub async fn stop_live_location_share(
4075        &self,
4076    ) -> Result<send_state_event::v3::Response, BeaconError> {
4077        self.ensure_room_joined()?;
4078
4079        let mut beacon_info_event = self.get_user_beacon_info(self.own_user_id()).await?;
4080
4081        if beacon_info_event.content.live {
4082            beacon_info_event.content.stop();
4083            Ok(self.send_state_event_for_key(self.own_user_id(), beacon_info_event.content).await?)
4084        } else {
4085            Err(BeaconError::NotLive)
4086        }
4087    }
4088
4089    /// Send a location beacon event in the current room.
4090    ///
4091    /// # Arguments
4092    ///
4093    /// - `geo_uri` - The geo URI of the location beacon.
4094    ///
4095    /// # Errors
4096    ///
4097    /// Returns an error if the room is not joined, if the beacon information is
4098    /// redacted or stripped, if the location share is no longer live, or if the
4099    /// state event is not found.
4100    pub async fn send_location_beacon(
4101        &self,
4102        geo_uri: String,
4103    ) -> Result<send_message_event::v3::Response, BeaconError> {
4104        self.ensure_room_joined()?;
4105
4106        let beacon_info_event = self.get_user_beacon_info(self.own_user_id()).await?;
4107
4108        if beacon_info_event.content.is_live() {
4109            let content = BeaconEventContent::new(beacon_info_event.event_id, geo_uri, None);
4110            Ok(self
4111                .send(content)
4112                .with_request_config(RequestConfig::new().retry_limit(6))
4113                .await?
4114                .response)
4115        } else {
4116            Err(BeaconError::NotLive)
4117        }
4118    }
4119
4120    /// Store the given `ComposerDraft` in the state store using the current
4121    /// room id and optional thread root id as identifier.
4122    pub async fn save_composer_draft(
4123        &self,
4124        draft: ComposerDraft,
4125        thread_root: Option<&EventId>,
4126    ) -> Result<()> {
4127        self.client
4128            .state_store()
4129            .set_kv_data(
4130                StateStoreDataKey::ComposerDraft(self.room_id(), thread_root),
4131                StateStoreDataValue::ComposerDraft(draft),
4132            )
4133            .await?;
4134        Ok(())
4135    }
4136
4137    /// Retrieve the `ComposerDraft` stored in the state store for this room and
4138    /// given thread, if any.
4139    pub async fn load_composer_draft(
4140        &self,
4141        thread_root: Option<&EventId>,
4142    ) -> Result<Option<ComposerDraft>> {
4143        let data = self
4144            .client
4145            .state_store()
4146            .get_kv_data(StateStoreDataKey::ComposerDraft(self.room_id(), thread_root))
4147            .await?;
4148        Ok(data.and_then(|d| d.into_composer_draft()))
4149    }
4150
4151    /// Remove the `ComposerDraft` stored in the state store for this room and
4152    /// given thread, if any.
4153    pub async fn clear_composer_draft(&self, thread_root: Option<&EventId>) -> Result<()> {
4154        self.client
4155            .state_store()
4156            .remove_kv_data(StateStoreDataKey::ComposerDraft(self.room_id(), thread_root))
4157            .await?;
4158        Ok(())
4159    }
4160
4161    /// Load pinned state events for a room from the `/state` endpoint in the
4162    /// home server.
4163    pub async fn load_pinned_events(&self) -> Result<Option<Vec<OwnedEventId>>> {
4164        let response = self
4165            .client
4166            .send(get_state_event_for_key::v3::Request::new(
4167                self.room_id().to_owned(),
4168                StateEventType::RoomPinnedEvents,
4169                "".to_owned(),
4170            ))
4171            .await;
4172
4173        match response {
4174            Ok(response) => Ok(Some(
4175                response
4176                    .into_content()
4177                    .deserialize_as_unchecked::<RoomPinnedEventsEventContent>()?
4178                    .pinned,
4179            )),
4180            Err(http_error) => match http_error.as_client_api_error() {
4181                Some(error) if error.status_code == StatusCode::NOT_FOUND => Ok(None),
4182                _ => Err(http_error.into()),
4183            },
4184        }
4185    }
4186
4187    /// Subscribe to knock requests in this `Room`.
4188    ///
4189    /// The current requests to join the room will be emitted immediately when
4190    /// subscribing.
4191    ///
4192    /// A new set of knock requests will be emitted whenever:
4193    ///
4194    /// - A new member event is received.
4195    /// - A knock request is marked as seen.
4196    /// - A sync is gappy (limited), so room membership information may be
4197    ///   outdated.
4198    ///
4199    /// Returns both a stream of knock requests and a handle for a task that
4200    /// will clean up the seen knock request ids when possible.
4201    pub async fn subscribe_to_knock_requests(
4202        &self,
4203    ) -> Result<(impl Stream<Item = Vec<KnockRequest>> + use<>, JoinHandle<()>)> {
4204        let this = Arc::new(self.clone());
4205
4206        let room_member_events_observer =
4207            self.client.observe_room_events::<SyncRoomMemberEvent, (Client, Room)>(this.room_id());
4208
4209        let current_seen_ids = self.get_seen_knock_request_ids().await?;
4210        let mut seen_request_ids_stream = self
4211            .seen_knock_request_ids_map
4212            .subscribe()
4213            .await
4214            .map(|values| values.unwrap_or_default());
4215
4216        let mut room_info_stream = self.subscribe_info();
4217
4218        // Spawn a task that will clean up the seen knock request ids when
4219        // updated room members are received
4220        let clear_seen_ids_handle = spawn({
4221            let this = self.clone();
4222            async move {
4223                let mut member_updates_stream = this.room_member_updates_sender.subscribe();
4224                while member_updates_stream.recv().await.is_ok() {
4225                    // If room members were updated, try to remove outdated seen
4226                    // knock request ids
4227                    if let Err(err) = this.remove_outdated_seen_knock_requests_ids().await {
4228                        warn!("Failed to remove seen knock requests: {err}")
4229                    }
4230                }
4231            }
4232        });
4233
4234        let combined_stream = stream! {
4235            // Emit current requests to join
4236            match this.get_current_join_requests(&current_seen_ids).await {
4237                Ok(initial_requests) => yield initial_requests,
4238                Err(err) => warn!("Failed to get initial requests to join: {err}")
4239            }
4240
4241            let mut requests_stream = room_member_events_observer.subscribe();
4242            let mut seen_ids = current_seen_ids.clone();
4243
4244            loop {
4245                // This is equivalent to a combine stream operation, triggering
4246                // a new emission when any of the branches changes
4247                tokio::select! {
4248                    Some((event, _)) = requests_stream.next() => {
4249                        if let Some(event) = event.as_original() {
4250                            // If we can calculate the membership change, try to emit only when needed
4251                            let emit = if event.prev_content().is_some() {
4252                                matches!(event.membership_change(),
4253                                    MembershipChange::Banned |
4254                                    MembershipChange::Knocked |
4255                                    MembershipChange::KnockAccepted |
4256                                    MembershipChange::KnockDenied |
4257                                    MembershipChange::KnockRetracted
4258                                )
4259                            } else {
4260                                // If we can't calculate the membership change,
4261                                // assume we need to emit updated values
4262                                true
4263                            };
4264
4265                            if emit {
4266                                match this.get_current_join_requests(&seen_ids).await {
4267                                    Ok(requests) => yield requests,
4268                                    Err(err) => {
4269                                        warn!("Failed to get updated knock requests on new member event: {err}")
4270                                    }
4271                                }
4272                            }
4273                        }
4274                    }
4275
4276                    Some(new_seen_ids) = seen_request_ids_stream.next() => {
4277                        // Update the current seen ids
4278                        seen_ids = new_seen_ids;
4279
4280                        // If seen requests have changed we need to recalculate
4281                        // all the knock requests
4282                        match this.get_current_join_requests(&seen_ids).await {
4283                            Ok(requests) => yield requests,
4284                            Err(err) => {
4285                                warn!("Failed to get updated knock requests on seen ids changed: {err}")
4286                            }
4287                        }
4288                    }
4289
4290                    Some(room_info) = room_info_stream.next() => {
4291                        // We need to emit new items when we may have missing
4292                        // room members: this usually happens after a gappy
4293                        // (limited) sync
4294                        if !room_info.are_members_synced() {
4295                            match this.get_current_join_requests(&seen_ids).await {
4296                                Ok(requests) => yield requests,
4297                                Err(err) => {
4298                                    warn!("Failed to get updated knock requests on gappy (limited) sync: {err}")
4299                                }
4300                            }
4301                        }
4302                    }
4303                    // If the streams in all branches are closed, stop the loop
4304                    else => break,
4305                }
4306            }
4307        };
4308
4309        Ok((combined_stream, clear_seen_ids_handle))
4310    }
4311
4312    async fn get_current_join_requests(
4313        &self,
4314        seen_request_ids: &BTreeMap<OwnedEventId, OwnedUserId>,
4315    ) -> Result<Vec<KnockRequest>> {
4316        Ok(self
4317            .members(RoomMemberships::KNOCK)
4318            .await?
4319            .into_iter()
4320            .filter_map(|member| {
4321                let event_id = member.event().event_id()?;
4322                Some(KnockRequest::new(
4323                    self,
4324                    event_id,
4325                    member.event().timestamp(),
4326                    KnockRequestMemberInfo::from_member(&member),
4327                    seen_request_ids.contains_key(event_id),
4328                ))
4329            })
4330            .collect())
4331    }
4332
4333    /// Compute the effective message retention policy for this room.
4334    ///
4335    /// Fetches the server's retention configuration and applies the MSC1763
4336    /// algorithm. Use [`Self::effective_retention_with_server_config`] to
4337    /// supply a pre-fetched server config and avoid a network call.
4338    ///
4339    /// Returns `Ok(None)` if the homeserver does not implement MSC1763. A
4340    /// homeserver that does not implement this endpoint also does not purge
4341    /// events on its own, so we don't apply retention limits locally.
4342    ///
4343    /// See
4344    /// [MSC1763](https://github.com/matrix-org/matrix-spec-proposals/pull/1763)
4345    /// for more info.
4346    pub async fn effective_retention(&self) -> Result<Option<RoomRetentionEventContent>> {
4347        let config = match self.client.get_retention_configuration().await {
4348            Ok(config) => config,
4349            Err(e) if e.is_endpoint_not_implemented() => {
4350                debug!(
4351                    room_id = ?self.room_id(),
4352                    "Homeserver doesn't implement the MSC1763 retention configuration \
4353                     endpoint; treating this room as having no effective retention policy"
4354                );
4355                return Ok(None);
4356            }
4357            Err(e) => return Err(e.into()),
4358        };
4359        Ok(self.effective_retention_with_server_config(&config))
4360    }
4361
4362    /// Compute the effective message retention policy for this room using a
4363    /// pre-fetched server configuration.
4364    ///
4365    /// Applies the MSC1763 algorithm, combining the server's configuration with
4366    /// the room's own `m.room.retention` state event:
4367    ///
4368    /// 1. If the server defines a per-room override for this room, use it.
4369    /// 2. Else if the room has no retention state event, return the server's
4370    ///    default policy (`"*"`), or `None` if absent.
4371    /// 3. Else return the room's state event clamped to the server's limits.
4372    ///
4373    /// Prefer this over [`Self::effective_retention`] when computing the policy
4374    /// for multiple rooms in the same pass, to avoid redundant network calls.
4375    ///
4376    /// See
4377    /// [MSC1763](https://github.com/matrix-org/matrix-spec-proposals/pull/1763)
4378    /// for more info.
4379    pub fn effective_retention_with_server_config(
4380        &self,
4381        config: &get_retention_configuration::msc1763::Response,
4382    ) -> Option<RoomRetentionEventContent> {
4383        use ruma::api::client::retention::{
4384            RoomIdOrAllRooms, get_retention_configuration::msc1763::LifetimeLimits,
4385        };
4386
4387        fn clamp(value: Option<Duration>, limits: &Option<LifetimeLimits>) -> Option<Duration> {
4388            // No limit for this property: per MSC1763, use the room's value
4389            // as-is, whether it has a value or not
4390            let Some(limits) = limits else { return value };
4391            let Some(value) = value else {
4392                // A value is not set, fall back to the minimum limit (which may
4393                // itself be absent, yielding an unbounded result).
4394                return limits.min();
4395            };
4396            // The limit exists, clamp to limits
4397            let min = limits.min().unwrap_or(Duration::ZERO);
4398            let max = limits.max().unwrap_or(Duration::MAX);
4399            Some(value.clamp(min, max))
4400        }
4401
4402        // 1. Server per-room override takes precedence.
4403        if let Some(policy) =
4404            config.policies.get(&RoomIdOrAllRooms::RoomId(self.room_id().to_owned()))
4405        {
4406            return Some(policy.clone());
4407        }
4408
4409        // 2. No room state event → fall back to server default or nothing.
4410        let Some(room_policy) = self.retention() else {
4411            return config.policies.get(&RoomIdOrAllRooms::AllRooms).cloned();
4412        };
4413
4414        // 3. Clamp room policy by server limits.
4415        let max_lifetime = clamp(room_policy.max_lifetime(), &config.limits.max_lifetime);
4416        let min_lifetime = clamp(room_policy.min_lifetime(), &config.limits.min_lifetime);
4417
4418        // The two bounds are clamped independently against separate limits, so
4419        // they can still conflict (min_lifetime > max_lifetime). MSC1763 treats
4420        // `max_lifetime` as a MUST (mandatory purge deadline) and
4421        // `min_lifetime` as a SHOULD (retention floor), so we should honor the
4422        // `max_lifetime` as having a greater priority and cap `min_lifetime` as
4423        // such, in the event of this overlap.
4424        let min_lifetime = min_lifetime.map(|min| {
4425            let Some(max) = max_lifetime else { return min };
4426            if min > max {
4427                warn!(
4428                    room_id = ?self.room_id(),
4429                    ?min, ?max,
4430                    "Retention min_lifetime exceeds max_lifetime after clamping to server limits; \
4431                     capping min_lifetime to max_lifetime"
4432                );
4433                max
4434            } else {
4435                min
4436            }
4437        });
4438
4439        match (max_lifetime, min_lifetime) {
4440            (Some(max), Some(min)) => RoomRetentionEventContent::from_range(min..=max),
4441            (Some(max), None) => RoomRetentionEventContent::new().at_most(max),
4442            (None, Some(min)) => RoomRetentionEventContent::new().at_least(min),
4443            (None, None) => Some(RoomRetentionEventContent::new()),
4444        }
4445    }
4446
4447    /// Access the room settings related to privacy and visibility.
4448    pub fn privacy_settings(&self) -> RoomPrivacySettings<'_> {
4449        RoomPrivacySettings::new(&self.inner, &self.client)
4450    }
4451
4452    /// Retrieve a list of all the threads for the current room.
4453    ///
4454    /// Since this client-server API is paginated, the return type may include a
4455    /// token used to resuming back-pagination into the list of results, in
4456    /// [`ThreadRoots::prev_batch_token`]. This token can be fed back into
4457    /// [`ListThreadsOptions::from`] to continue the pagination from the
4458    /// previous position.
4459    pub async fn list_threads(&self, opts: ListThreadsOptions) -> Result<ThreadRoots> {
4460        let request = opts.into_request(self.room_id());
4461
4462        let response = self.client.send(request).await?;
4463
4464        let push_ctx = self.push_context().await?;
4465        let chunk = join_all(
4466            response.chunk.into_iter().map(|ev| self.try_decrypt_event(ev, push_ctx.as_ref())),
4467        )
4468        .await;
4469
4470        Ok(ThreadRoots { chunk, prev_batch_token: response.next_batch })
4471    }
4472
4473    /// Retrieve a list of relations for the given event, according to the given
4474    /// options, using the network.
4475    ///
4476    /// Since this client-server API is paginated, the return type may include a
4477    /// token used to resuming back-pagination into the list of results, in
4478    /// [`Relations::prev_batch_token`]. This token can be fed back into
4479    /// [`RelationsOptions::from`] to continue the pagination from the previous
4480    /// position.
4481    ///
4482    /// **Note**: if [`RelationsOptions::from`] is set for a subsequent request,
4483    /// then it must be used with the same
4484    /// [`RelationsOptions::include_relations`] value as the request that
4485    /// returns the `from` token, otherwise the server behavior is undefined.
4486    pub async fn relations(
4487        &self,
4488        event_id: OwnedEventId,
4489        opts: RelationsOptions,
4490    ) -> Result<Relations> {
4491        opts.send(self, event_id).await
4492    }
4493
4494    /// Subscribe to a given thread in this room.
4495    ///
4496    /// This will subscribe the user to the thread, so that they will receive
4497    /// notifications for that thread specifically.
4498    ///
4499    /// # Arguments
4500    ///
4501    /// - `thread_root`: The ID of the thread root event to subscribe to.
4502    /// - `automatic`: Whether the subscription was made automatically by a
4503    ///   client, not by manual user choice. If set, must include the latest
4504    ///   event ID that's known in the thread and that is causing the automatic
4505    ///   subscription. If unset (i.e. we're now subscribing manually) and there
4506    ///   was a previous automatic subscription, the subscription will be
4507    ///   overridden to a manual one instead.
4508    ///
4509    /// # Returns
4510    ///
4511    /// - A 404 error if the event isn't known, or isn't a thread root.
4512    /// - An `Ok` result if the subscription was successful, or if the server
4513    ///   skipped an automatic subscription (as the user unsubscribed from the
4514    ///   thread after the event causing the automatic subscription).
4515    #[instrument(skip(self), fields(room_id = %self.room_id()))]
4516    pub async fn subscribe_thread(
4517        &self,
4518        thread_root: OwnedEventId,
4519        automatic: Option<OwnedEventId>,
4520    ) -> Result<()> {
4521        let is_automatic = automatic.is_some();
4522
4523        match self
4524            .client
4525            .send(subscribe_thread::msc4306::Request::new(
4526                self.room_id().to_owned(),
4527                thread_root.clone(),
4528                automatic,
4529            ))
4530            .await
4531        {
4532            Ok(_response) => {
4533                trace!("Server acknowledged the thread subscription; saving in db");
4534
4535                // Immediately save the result into the database.
4536                self.client
4537                    .state_store()
4538                    .upsert_thread_subscriptions(vec![(
4539                        self.room_id(),
4540                        &thread_root,
4541                        StoredThreadSubscription {
4542                            status: ThreadSubscriptionStatus::Subscribed {
4543                                automatic: is_automatic,
4544                            },
4545                            bump_stamp: None,
4546                        },
4547                    )])
4548                    .await?;
4549
4550                Ok(())
4551            }
4552
4553            Err(err) => {
4554                if let Some(ErrorKind::ConflictingUnsubscription) = err.client_api_error_kind() {
4555                    // In this case: the server indicates that the user
4556                    // unsubscribed _after_ the event ID we've used in an
4557                    // automatic subscription; don't save the subscription state
4558                    // in the database, as the previous one should be more
4559                    // correct.
4560                    trace!("Thread subscription skipped: {err}");
4561                    Ok(())
4562                } else {
4563                    // Forward the error to the caller.
4564                    Err(err.into())
4565                }
4566            }
4567        }
4568    }
4569
4570    /// Subscribe to a thread if needed, based on a current subscription to it.
4571    ///
4572    /// This is like [`Self::subscribe_thread`], but it first checks if the user
4573    /// has already subscribed to a thread, so as to minimize sending
4574    /// unnecessary subscriptions which would be ignored by the server.
4575    pub async fn subscribe_thread_if_needed(
4576        &self,
4577        thread_root: &EventId,
4578        automatic: Option<OwnedEventId>,
4579    ) -> Result<()> {
4580        if let Some(prev_sub) = self.load_or_fetch_thread_subscription(thread_root).await? {
4581            // If we have a previous subscription, we should only send the new
4582            // one if it's manual and the previous one was automatic.
4583            if !prev_sub.automatic || automatic.is_some() {
4584                // Either we had already a manual subscription, or we had an
4585                // automatic one and the new one is automatic too: nothing to
4586                // do!
4587                return Ok(());
4588            }
4589        }
4590        self.subscribe_thread(thread_root.to_owned(), automatic).await
4591    }
4592
4593    /// Unsubscribe from a given thread in this room.
4594    ///
4595    /// # Arguments
4596    ///
4597    /// - `thread_root`: The ID of the thread root event to unsubscribe to.
4598    ///
4599    /// # Returns
4600    ///
4601    /// - An `Ok` result if the unsubscription was successful, or the thread was
4602    ///   already unsubscribed.
4603    /// - A 404 error if the event isn't known, or isn't a thread root.
4604    #[instrument(skip(self), fields(room_id = %self.room_id()))]
4605    pub async fn unsubscribe_thread(&self, thread_root: OwnedEventId) -> Result<()> {
4606        self.client
4607            .send(unsubscribe_thread::msc4306::Request::new(
4608                self.room_id().to_owned(),
4609                thread_root.clone(),
4610            ))
4611            .await?;
4612
4613        trace!("Server acknowledged the thread subscription removal; removed it from db too");
4614
4615        // Immediately save the result into the database.
4616        self.client
4617            .state_store()
4618            .upsert_thread_subscriptions(vec![(
4619                self.room_id(),
4620                &thread_root,
4621                StoredThreadSubscription {
4622                    status: ThreadSubscriptionStatus::Unsubscribed,
4623                    bump_stamp: None,
4624                },
4625            )])
4626            .await?;
4627
4628        Ok(())
4629    }
4630
4631    /// Return the current thread subscription for the given thread root in this
4632    /// room.
4633    ///
4634    /// # Arguments
4635    ///
4636    /// - `thread_root`: The ID of the thread root event to get the subscription
4637    ///   for.
4638    ///
4639    /// # Returns
4640    ///
4641    /// - An `Ok` result with `Some(ThreadSubscription)` if we have some
4642    ///   subscription information.
4643    /// - An `Ok` result with `None` if the subscription does not exist, or the
4644    ///   event couldn't be found, or the event isn't a thread.
4645    /// - An error if the request fails for any other reason, such as a network
4646    ///   error.
4647    #[instrument(skip(self), fields(room_id = %self.room_id()))]
4648    pub async fn fetch_thread_subscription(
4649        &self,
4650        thread_root: OwnedEventId,
4651    ) -> Result<Option<ThreadSubscription>> {
4652        let result = self
4653            .client
4654            .send(get_thread_subscription::msc4306::Request::new(
4655                self.room_id().to_owned(),
4656                thread_root.clone(),
4657            ))
4658            .await;
4659
4660        let subscription = match result {
4661            Ok(response) => Some(ThreadSubscription { automatic: response.automatic }),
4662            Err(http_error) => match http_error.as_client_api_error() {
4663                Some(error) if error.status_code == StatusCode::NOT_FOUND => None,
4664                _ => return Err(http_error.into()),
4665            },
4666        };
4667
4668        // Keep the database in sync.
4669        if let Some(sub) = &subscription {
4670            self.client
4671                .state_store()
4672                .upsert_thread_subscriptions(vec![(
4673                    self.room_id(),
4674                    &thread_root,
4675                    StoredThreadSubscription {
4676                        status: ThreadSubscriptionStatus::Subscribed { automatic: sub.automatic },
4677                        bump_stamp: None,
4678                    },
4679                )])
4680                .await?;
4681        } else {
4682            // If the subscription was not found, remove it from the database.
4683            self.client
4684                .state_store()
4685                .remove_thread_subscription(self.room_id(), &thread_root)
4686                .await?;
4687        }
4688
4689        Ok(subscription)
4690    }
4691
4692    /// Return the current thread subscription for the given thread root in this
4693    /// room, by getting it from storage if possible, or fetching it from
4694    /// network otherwise.
4695    ///
4696    /// See also [`Self::fetch_thread_subscription`] for the exact semantics of
4697    /// this method.
4698    pub async fn load_or_fetch_thread_subscription(
4699        &self,
4700        thread_root: &EventId,
4701    ) -> Result<Option<ThreadSubscription>> {
4702        // If the thread subscriptions list is outdated, fetch from the server.
4703        if self.client.thread_subscription_catchup().is_outdated() {
4704            return self.fetch_thread_subscription(thread_root.to_owned()).await;
4705        }
4706
4707        // Otherwise, we can rely on the store information.
4708        Ok(self
4709            .client
4710            .state_store()
4711            .load_thread_subscription(self.room_id(), thread_root)
4712            .await
4713            .map(|maybe_sub| {
4714                maybe_sub.and_then(|stored| match stored.status {
4715                    ThreadSubscriptionStatus::Unsubscribed => None,
4716                    ThreadSubscriptionStatus::Subscribed { automatic } => {
4717                        Some(ThreadSubscription { automatic })
4718                    }
4719                })
4720            })?)
4721    }
4722
4723    /// Adds a new pinned event by sending an updated `m.room.pinned_events`
4724    /// event containing the new event id.
4725    ///
4726    /// This method will first try to get the pinned events from the current
4727    /// room's state and if it fails to do so it'll try to load them from the
4728    /// homeserver.
4729    ///
4730    /// Returns `true` if we pinned the event, `false` if the event was already
4731    /// pinned.
4732    pub async fn pin_event(&self, event_id: &EventId) -> Result<bool> {
4733        let mut pinned_event_ids = if let Some(event_ids) = self.pinned_event_ids() {
4734            event_ids
4735        } else {
4736            self.load_pinned_events().await?.unwrap_or_default()
4737        };
4738        let event_id = event_id.to_owned();
4739        if pinned_event_ids.contains(&event_id) {
4740            Ok(false)
4741        } else {
4742            pinned_event_ids.push(event_id);
4743            let content = RoomPinnedEventsEventContent::new(pinned_event_ids);
4744            self.send_state_event(content).await?;
4745            Ok(true)
4746        }
4747    }
4748
4749    /// Removes a pinned event by sending an updated `m.room.pinned_events`
4750    /// event without the event id we want to remove.
4751    ///
4752    /// This method will first try to get the pinned events from the current
4753    /// room's state and if it fails to do so it'll try to load them from the
4754    /// homeserver.
4755    ///
4756    /// Returns `true` if we unpinned the event, `false` if the event wasn't
4757    /// pinned before.
4758    pub async fn unpin_event(&self, event_id: &EventId) -> Result<bool> {
4759        let mut pinned_event_ids = if let Some(event_ids) = self.pinned_event_ids() {
4760            event_ids
4761        } else {
4762            self.load_pinned_events().await?.unwrap_or_default()
4763        };
4764        let event_id = event_id.to_owned();
4765        if let Some(idx) = pinned_event_ids.iter().position(|e| *e == *event_id) {
4766            pinned_event_ids.remove(idx);
4767            let content = RoomPinnedEventsEventContent::new(pinned_event_ids);
4768            self.send_state_event(content).await?;
4769            Ok(true)
4770        } else {
4771            Ok(false)
4772        }
4773    }
4774
4775    /// Computes if the current room is a DM, stores the loaded values, and then
4776    /// returns the result.
4777    pub async fn compute_is_dm(&self) -> Result<bool> {
4778        Ok(self.inner.compute_is_dm(self.client.dm_room_definition()).await?)
4779    }
4780
4781    /// Checks if the current room is a DM in a synchronous way, without
4782    /// actually checking any local stores. Note this can be either a cached or
4783    /// an approximate value, since some important data may be unavailable and
4784    /// we may need to make some assumptions.
4785    pub fn is_dm(&self) -> bool {
4786        // Note: this value may be wrong for invited rooms.
4787        let is_direct = self.direct_targets_length() == 1;
4788        match self.client.dm_room_definition() {
4789            DmRoomDefinition::MatrixSpec => {
4790                // If there is a single target, it's a DM.
4791                is_direct
4792            }
4793            DmRoomDefinition::TwoMembers => {
4794                // If there is a single target and at most 2 active members,
4795                // it's a DM. Try getting the calculated active service members
4796                // count from the room info.
4797                let active_service_member_count =
4798                    self.active_service_members_count().unwrap_or_else(|| {
4799                        // Otherwise just use an approximated value based on the
4800                        // service members count.
4801                        self.service_members().map(|members| members.len()).unwrap_or_default()
4802                            as u64
4803                    });
4804                let has_at_most_two_active_members =
4805                    self.active_members_count().saturating_sub(active_service_member_count) <= 2;
4806                is_direct && has_at_most_two_active_members
4807            }
4808        }
4809    }
4810}
4811
4812#[cfg(feature = "e2e-encryption")]
4813impl RoomIdentityProvider for Room {
4814    fn is_member<'a>(&'a self, user_id: &'a UserId) -> BoxFuture<'a, bool> {
4815        Box::pin(async { self.get_member(user_id).await.unwrap_or(None).is_some() })
4816    }
4817
4818    fn member_identities(&self) -> BoxFuture<'_, Vec<UserIdentity>> {
4819        Box::pin(async {
4820            let members = self
4821                .members(RoomMemberships::JOIN | RoomMemberships::INVITE)
4822                .await
4823                .unwrap_or_else(|_| Default::default());
4824
4825            let mut ret: Vec<UserIdentity> = Vec::new();
4826            for member in members {
4827                if let Some(i) = self.user_identity(member.user_id()).await {
4828                    ret.push(i);
4829                }
4830            }
4831            ret
4832        })
4833    }
4834
4835    fn user_identity<'a>(&'a self, user_id: &'a UserId) -> BoxFuture<'a, Option<UserIdentity>> {
4836        Box::pin(async {
4837            self.client
4838                .encryption()
4839                .get_user_identity(user_id)
4840                .await
4841                .unwrap_or(None)
4842                .map(|u| u.underlying_identity())
4843        })
4844    }
4845}
4846
4847/// A wrapper for a weak client and a room id that allows to lazily retrieve a
4848/// room, only when needed.
4849#[derive(Clone, Debug)]
4850pub(crate) struct WeakRoom {
4851    client: WeakClient,
4852    room_id: OwnedRoomId,
4853}
4854
4855impl WeakRoom {
4856    /// Create a new `WeakRoom` given its weak components.
4857    pub fn new(client: WeakClient, room_id: OwnedRoomId) -> Self {
4858        Self { client, room_id }
4859    }
4860
4861    /// Attempts to reconstruct the room.
4862    pub fn get(&self) -> Option<Room> {
4863        self.client.get().and_then(|client| client.get_room(&self.room_id))
4864    }
4865
4866    /// The room id for that room.
4867    pub fn room_id(&self) -> &RoomId {
4868        &self.room_id
4869    }
4870}
4871
4872/// Details of the (latest) invite.
4873#[derive(Debug, Clone)]
4874pub struct Invite {
4875    /// Who has been invited.
4876    pub invitee: RoomMember,
4877
4878    /// The user ID of who sent the invite.
4879    ///
4880    /// This is useful if `Self::inviter` is `None`.
4881    pub inviter_id: OwnedUserId,
4882
4883    /// Who sent the invite.
4884    ///
4885    /// If `None`, check `Self::inviter_id`, it might be useful as a fallback.
4886    pub inviter: Option<RoomMember>,
4887}
4888
4889#[derive(Error, Debug)]
4890enum InvitationError {
4891    #[error("No membership event found")]
4892    EventMissing,
4893}
4894
4895/// Receipts to send all at once.
4896#[derive(Debug, Clone, Default)]
4897#[non_exhaustive]
4898pub struct Receipts {
4899    /// Fully-read marker (room account data).
4900    pub fully_read: Option<OwnedEventId>,
4901    /// Read receipt (public ephemeral room event).
4902    pub public_read_receipt: Option<OwnedEventId>,
4903    /// Read receipt (private ephemeral room event).
4904    pub private_read_receipt: Option<OwnedEventId>,
4905}
4906
4907impl Receipts {
4908    /// Create an empty `Receipts`.
4909    pub fn new() -> Self {
4910        Self::default()
4911    }
4912
4913    /// Set the last event the user has read.
4914    ///
4915    /// It means that the user has read all the events before this event.
4916    ///
4917    /// This is a private marker only visible by the user.
4918    ///
4919    /// Note that this is technically not a receipt as it is persisted in the
4920    /// room account data.
4921    pub fn fully_read_marker(mut self, event_id: impl Into<Option<OwnedEventId>>) -> Self {
4922        self.fully_read = event_id.into();
4923        self
4924    }
4925
4926    /// Set the last event presented to the user and forward it to the other
4927    /// users in the room.
4928    ///
4929    /// This is used to reset the unread messages/notification count and
4930    /// advertise to other users the last event that the user has likely seen.
4931    pub fn public_read_receipt(mut self, event_id: impl Into<Option<OwnedEventId>>) -> Self {
4932        self.public_read_receipt = event_id.into();
4933        self
4934    }
4935
4936    /// Set the last event presented to the user and don't forward it.
4937    ///
4938    /// This is used to reset the unread messages/notification count.
4939    pub fn private_read_receipt(mut self, event_id: impl Into<Option<OwnedEventId>>) -> Self {
4940        self.private_read_receipt = event_id.into();
4941        self
4942    }
4943
4944    /// Whether this `Receipts` is empty.
4945    pub fn is_empty(&self) -> bool {
4946        self.fully_read.is_none()
4947            && self.public_read_receipt.is_none()
4948            && self.private_read_receipt.is_none()
4949    }
4950}
4951
4952/// [Parent space](https://spec.matrix.org/v1.8/client-server-api/#mspaceparent-relationships)
4953/// listed by a room, possibly validated by checking the space's state.
4954#[derive(Debug)]
4955pub enum ParentSpace {
4956    /// The room recognizes the given room as its parent, and the parent
4957    /// recognizes it as its child.
4958    Reciprocal(Room),
4959    /// The room recognizes the given room as its parent, but the parent does
4960    /// not recognizes it as its child. However, the author of the
4961    /// `m.space.parent` event in the room has a sufficient power level in the
4962    /// parent to create the child event.
4963    WithPowerlevel(Room),
4964    /// The room recognizes the given room as its parent, but the parent does
4965    /// not recognizes it as its child.
4966    Illegitimate(Room),
4967    /// The room recognizes the given id as its parent room, but we cannot check
4968    /// whether the parent recognizes it as its child.
4969    Unverifiable(OwnedRoomId),
4970}
4971
4972pub(crate) trait EventSource {
4973    fn get_event(
4974        &self,
4975        event_id: &EventId,
4976    ) -> impl Future<Output = Result<TimelineEvent, Error>> + SendOutsideWasm;
4977}
4978
4979impl EventSource for &Room {
4980    async fn get_event(&self, event_id: &EventId) -> Result<TimelineEvent, Error> {
4981        self.load_or_fetch_event(event_id, None).await
4982    }
4983}
4984
4985/// Contains the current user's room member info and the optional room member
4986/// info of the sender of the `m.room.member` event that this info represents.
4987#[derive(Debug)]
4988pub struct RoomMemberWithSenderInfo {
4989    /// The actual room member.
4990    pub room_member: RoomMember,
4991    /// The info of the sender of the event `room_member` is based on, if
4992    /// available.
4993    pub sender_info: Option<RoomMember>,
4994}
4995
4996/// Whether a room update reports state events of the given type, in the state
4997/// section of the sync response (state events found in the timeline are not
4998/// considered).
4999fn has_state_events_of_type(update: &RoomUpdate, event_type: &StateEventType) -> bool {
5000    // We only care about the state of rooms we are in.
5001    let RoomUpdate::Joined { updates, .. } = update else {
5002        return false;
5003    };
5004
5005    let (State::Before(state_events) | State::After(state_events)) = &updates.state;
5006
5007    state_events.iter().any(|raw| {
5008        raw.get_field::<StateEventType>("type")
5009            .ok()
5010            .flatten()
5011            .is_some_and(|received_type| received_type == *event_type)
5012    })
5013}
5014
5015#[cfg(all(test, not(target_family = "wasm")))]
5016mod tests {
5017    use std::time::Duration;
5018
5019    use matrix_sdk_base::{ComposerDraft, DraftAttachment, store::ComposerDraftType};
5020    use matrix_sdk_test::{
5021        JoinedRoomBuilder, SyncResponseBuilder, TestRoom, async_test, event_factory::EventFactory,
5022    };
5023    use ruma::{
5024        RoomVersionId, event_id,
5025        events::{
5026            relation::RelationType,
5027            room::{member::MembershipState, retention::RoomRetentionEventContent},
5028        },
5029        owned_event_id, room_id, user_id,
5030    };
5031    use wiremock::{
5032        Mock, MockServer, ResponseTemplate,
5033        matchers::{header, method, path, path_regex},
5034    };
5035
5036    use crate::{
5037        Client, Room,
5038        config::RequestConfig,
5039        room::messages::{IncludeRelations, ListThreadsOptions, RelationsOptions},
5040        test_utils::{
5041            client::mock_matrix_session,
5042            logged_in_client,
5043            mocks::{MatrixMockServer, RoomRelationsResponseTemplate},
5044        },
5045    };
5046
5047    #[cfg(all(feature = "sqlite", feature = "e2e-encryption"))]
5048    #[async_test]
5049    async fn test_cache_invalidation_while_encrypt() {
5050        use matrix_sdk_base::store::RoomLoadSettings;
5051        use matrix_sdk_test::{TestRoom, message_like_event_content};
5052
5053        let tmp_dir = tempfile::tempdir().unwrap();
5054        let sqlite_path = tmp_dir.path().join("cache_invalidation_while_encrypt.db");
5055        let session = mock_matrix_session();
5056
5057        let client = Client::builder()
5058            .homeserver_url("http://localhost:1234")
5059            .request_config(RequestConfig::new().disable_retry())
5060            .sqlite_store(&sqlite_path, None)
5061            .build()
5062            .await
5063            .unwrap();
5064        client
5065            .matrix_auth()
5066            .restore_session(session.clone(), RoomLoadSettings::default())
5067            .await
5068            .unwrap();
5069
5070        client.encryption().enable_cross_process_store_lock("client1".to_owned()).await.unwrap();
5071
5072        // Mock receiving an event to create an internal room.
5073        let server = MockServer::start().await;
5074        {
5075            Mock::given(method("GET"))
5076                .and(path_regex(r"^/_matrix/client/r0/rooms/.*/state/m.*room.*encryption.?"))
5077                .and(header("authorization", "Bearer 1234"))
5078                .respond_with(
5079                    ResponseTemplate::new(200)
5080                        .set_body_json(EventFactory::new().room_encryption().into_content()),
5081                )
5082                .mount(&server)
5083                .await;
5084            let f = EventFactory::new().sender(user_id!("@example:localhost"));
5085            let response = SyncResponseBuilder::default()
5086                .add_joined_room(
5087                    JoinedRoomBuilder::default()
5088                        .add_state_event(
5089                            f.member(user_id!("@example:localhost")).display_name("example"),
5090                        )
5091                        .add_state_event(f.power_levels())
5092                        .add_state_event(f.room_encryption()),
5093                )
5094                .build_sync_response();
5095            client.base_client().receive_sync_response(response).await.unwrap();
5096        }
5097
5098        let room = client.get_room(TestRoom::Default.into()).expect("Room should exist");
5099
5100        // Step 1, preshare the room keys.
5101        room.preshare_room_key().await.unwrap();
5102
5103        // Step 2, force lock invalidation by pretending another client obtained
5104        // the lock.
5105        {
5106            let client = Client::builder()
5107                .homeserver_url("http://localhost:1234")
5108                .request_config(RequestConfig::new().disable_retry())
5109                .sqlite_store(&sqlite_path, None)
5110                .build()
5111                .await
5112                .unwrap();
5113            client
5114                .matrix_auth()
5115                .restore_session(session.clone(), RoomLoadSettings::default())
5116                .await
5117                .unwrap();
5118            client
5119                .encryption()
5120                .enable_cross_process_store_lock("client2".to_owned())
5121                .await
5122                .unwrap();
5123
5124            let guard = client.encryption().spin_lock_store(None).await.unwrap();
5125            assert!(guard.is_some());
5126        }
5127
5128        // Step 3, take the crypto-store lock.
5129        let guard = client.encryption().spin_lock_store(None).await.unwrap();
5130        assert!(guard.is_some());
5131
5132        // Step 4, try to encrypt a message.
5133        let olm = client.olm_machine().await;
5134        let olm = olm.as_ref().expect("Olm machine wasn't started");
5135
5136        // Now pretend we're encrypting an event; the olm machine shouldn't rely
5137        // on caching the outgoing session before.
5138        let _encrypted_content = olm
5139            .encrypt_room_event_raw(room.room_id(), "test-event", &message_like_event_content!({}))
5140            .await
5141            .unwrap();
5142    }
5143
5144    #[async_test]
5145    async fn test_composer_draft() {
5146        let client = logged_in_client(None).await;
5147
5148        let response = SyncResponseBuilder::default()
5149            .add_joined_room(JoinedRoomBuilder::default())
5150            .build_sync_response();
5151        client.base_client().receive_sync_response(response).await.unwrap();
5152        let room = client.get_room(TestRoom::Default.into()).expect("Room should exist");
5153
5154        assert_eq!(room.load_composer_draft(None).await.unwrap(), None);
5155
5156        // Save 2 drafts, one for the room and one for a thread.
5157
5158        let draft = ComposerDraft {
5159            plain_text: "Hello, world!".to_owned(),
5160            html_text: Some("<strong>Hello</strong>, world!".to_owned()),
5161            draft_type: ComposerDraftType::NewMessage,
5162            attachments: vec![DraftAttachment {
5163                filename: "cat.txt".to_owned(),
5164                content: matrix_sdk_base::DraftAttachmentContent::File {
5165                    data: b"meow".to_vec(),
5166                    mimetype: Some("text/plain".to_owned()),
5167                    size: Some(5),
5168                },
5169            }],
5170        };
5171
5172        room.save_composer_draft(draft.clone(), None).await.unwrap();
5173
5174        let thread_root = owned_event_id!("$thread_root:b.c");
5175        let thread_draft = ComposerDraft {
5176            plain_text: "Hello, thread!".to_owned(),
5177            html_text: Some("<strong>Hello</strong>, thread!".to_owned()),
5178            draft_type: ComposerDraftType::NewMessage,
5179            attachments: vec![DraftAttachment {
5180                filename: "dog.txt".to_owned(),
5181                content: matrix_sdk_base::DraftAttachmentContent::File {
5182                    data: b"wuv".to_vec(),
5183                    mimetype: Some("text/plain".to_owned()),
5184                    size: Some(4),
5185                },
5186            }],
5187        };
5188
5189        room.save_composer_draft(thread_draft.clone(), Some(&thread_root)).await.unwrap();
5190
5191        // Check that the room draft was saved correctly
5192        assert_eq!(room.load_composer_draft(None).await.unwrap(), Some(draft));
5193
5194        // Check that the thread draft was saved correctly
5195        assert_eq!(
5196            room.load_composer_draft(Some(&thread_root)).await.unwrap(),
5197            Some(thread_draft.clone())
5198        );
5199
5200        // Clear the room draft
5201        room.clear_composer_draft(None).await.unwrap();
5202        assert_eq!(room.load_composer_draft(None).await.unwrap(), None);
5203
5204        // Check that the thread one is still there
5205        assert_eq!(room.load_composer_draft(Some(&thread_root)).await.unwrap(), Some(thread_draft));
5206
5207        // Clear the thread draft as well
5208        room.clear_composer_draft(Some(&thread_root)).await.unwrap();
5209        assert_eq!(room.load_composer_draft(Some(&thread_root)).await.unwrap(), None);
5210    }
5211
5212    #[async_test]
5213    async fn test_mark_join_requests_as_seen() {
5214        let server = MatrixMockServer::new().await;
5215        let client = server.client_builder().build().await;
5216        let event_id = event_id!("$a:b.c");
5217        let room_id = room_id!("!a:b.c");
5218        let user_id = user_id!("@alice:b.c");
5219
5220        let f = EventFactory::new().room(room_id);
5221        let joined_room_builder = JoinedRoomBuilder::new(room_id).add_state_bulk(vec![
5222            f.member(user_id).membership(MembershipState::Knock).event_id(event_id).into(),
5223        ]);
5224        let room = server.sync_room(&client, joined_room_builder).await;
5225
5226        // When loading the initial seen ids, there are none
5227        let seen_ids =
5228            room.get_seen_knock_request_ids().await.expect("Couldn't load seen join request ids");
5229        assert!(seen_ids.is_empty());
5230
5231        // We mark a random event id as seen
5232        room.mark_knock_requests_as_seen(&[user_id.to_owned()])
5233            .await
5234            .expect("Couldn't mark join request as seen");
5235
5236        // Then we can check it was successfully marked as seen
5237        let seen_ids =
5238            room.get_seen_knock_request_ids().await.expect("Couldn't load seen join request ids");
5239        assert_eq!(seen_ids.len(), 1);
5240        assert_eq!(
5241            seen_ids.into_iter().next().expect("No next value"),
5242            (event_id.to_owned(), user_id.to_owned())
5243        )
5244    }
5245
5246    #[async_test]
5247    async fn test_own_room_membership_with_no_own_member_event() {
5248        let server = MatrixMockServer::new().await;
5249        let client = server.client_builder().build().await;
5250        let room_id = room_id!("!a:b.c");
5251
5252        let room = server.sync_joined_room(&client, room_id).await;
5253
5254        // Since there is no member event for the own user, the method fails.
5255        // This should never happen in an actual room.
5256        let error = room.member_with_sender_info(client.user_id().unwrap()).await.err();
5257        assert!(error.is_some());
5258    }
5259
5260    #[async_test]
5261    async fn test_own_room_membership_with_own_member_event_but_unknown_sender() {
5262        let server = MatrixMockServer::new().await;
5263        let client = server.client_builder().build().await;
5264        let room_id = room_id!("!a:b.c");
5265        let user_id = user_id!("@example:localhost");
5266
5267        let f = EventFactory::new().room(room_id).sender(user_id!("@alice:b.c"));
5268        let joined_room_builder =
5269            JoinedRoomBuilder::new(room_id).add_state_bulk(vec![f.member(user_id).into()]);
5270        let room = server.sync_room(&client, joined_room_builder).await;
5271
5272        // When we load the membership details
5273        let ret = room
5274            .member_with_sender_info(client.user_id().unwrap())
5275            .await
5276            .expect("Room member info should be available");
5277
5278        // We get the member info for the current user
5279        assert_eq!(ret.room_member.event().user_id(), user_id);
5280
5281        // But there is no info for the sender
5282        assert!(ret.sender_info.is_none());
5283    }
5284
5285    #[async_test]
5286    async fn test_own_room_membership_with_own_member_event_and_own_sender() {
5287        let server = MatrixMockServer::new().await;
5288        let client = server.client_builder().build().await;
5289        let room_id = room_id!("!a:b.c");
5290        let user_id = user_id!("@example:localhost");
5291
5292        let f = EventFactory::new().room(room_id).sender(user_id);
5293        let joined_room_builder =
5294            JoinedRoomBuilder::new(room_id).add_state_bulk(vec![f.member(user_id).into()]);
5295        let room = server.sync_room(&client, joined_room_builder).await;
5296
5297        // When we load the membership details
5298        let ret = room
5299            .member_with_sender_info(client.user_id().unwrap())
5300            .await
5301            .expect("Room member info should be available");
5302
5303        // We get the current user's member info
5304        assert_eq!(ret.room_member.event().user_id(), user_id);
5305
5306        // And the sender has the same info, since it's also the current user
5307        assert!(ret.sender_info.is_some());
5308        assert_eq!(ret.sender_info.unwrap().event().user_id(), user_id);
5309    }
5310
5311    #[async_test]
5312    async fn test_own_room_membership_with_own_member_event_and_known_sender() {
5313        let server = MatrixMockServer::new().await;
5314        let client = server.client_builder().build().await;
5315        let room_id = room_id!("!a:b.c");
5316        let user_id = user_id!("@example:localhost");
5317        let sender_id = user_id!("@alice:b.c");
5318
5319        let f = EventFactory::new().room(room_id).sender(sender_id);
5320        let joined_room_builder = JoinedRoomBuilder::new(room_id).add_state_bulk(vec![
5321            f.member(user_id).into(),
5322            // The sender info comes from the sync
5323            f.member(sender_id).into(),
5324        ]);
5325        let room = server.sync_room(&client, joined_room_builder).await;
5326
5327        // When we load the membership details
5328        let ret = room
5329            .member_with_sender_info(client.user_id().unwrap())
5330            .await
5331            .expect("Room member info should be available");
5332
5333        // We get the current user's member info
5334        assert_eq!(ret.room_member.event().user_id(), user_id);
5335
5336        // And also the sender info from the events received in the sync
5337        assert!(ret.sender_info.is_some());
5338        assert_eq!(ret.sender_info.unwrap().event().user_id(), sender_id);
5339    }
5340
5341    #[async_test]
5342    async fn test_own_room_membership_with_own_member_event_and_unknown_but_available_sender() {
5343        let server = MatrixMockServer::new().await;
5344        let client = server.client_builder().build().await;
5345        let room_id = room_id!("!a:b.c");
5346        let user_id = user_id!("@example:localhost");
5347        let sender_id = user_id!("@alice:b.c");
5348
5349        let f = EventFactory::new().room(room_id).sender(sender_id);
5350        let joined_room_builder =
5351            JoinedRoomBuilder::new(room_id).add_state_bulk(vec![f.member(user_id).into()]);
5352        let room = server.sync_room(&client, joined_room_builder).await;
5353
5354        // We'll receive the member info through the /members endpoint
5355        server
5356            .mock_get_members()
5357            .ok(vec![f.member(sender_id).into_raw()])
5358            .mock_once()
5359            .mount()
5360            .await;
5361
5362        // We get the current user's member info
5363        let ret = room
5364            .member_with_sender_info(client.user_id().unwrap())
5365            .await
5366            .expect("Room member info should be available");
5367
5368        // We get the current user's member info
5369        assert_eq!(ret.room_member.event().user_id(), user_id);
5370
5371        // And also the sender info from the /members endpoint
5372        assert!(ret.sender_info.is_some());
5373        assert_eq!(ret.sender_info.unwrap().event().user_id(), sender_id);
5374    }
5375
5376    #[async_test]
5377    async fn test_list_threads() {
5378        let server = MatrixMockServer::new().await;
5379        let client = server.client_builder().build().await;
5380
5381        let room_id = room_id!("!a:b.c");
5382        let sender_id = user_id!("@alice:b.c");
5383        let f = EventFactory::new().room(room_id).sender(sender_id);
5384
5385        let eid1 = event_id!("$1");
5386        let eid2 = event_id!("$2");
5387        let batch1 = vec![f.text_msg("Thread root 1").event_id(eid1).into_raw()];
5388        let batch2 = vec![f.text_msg("Thread root 2").event_id(eid2).into_raw()];
5389
5390        server
5391            .mock_room_threads()
5392            .ok(batch1.clone(), Some("prev_batch".to_owned()))
5393            .mock_once()
5394            .mount()
5395            .await;
5396        server
5397            .mock_room_threads()
5398            .match_from("prev_batch")
5399            .ok(batch2, None)
5400            .mock_once()
5401            .mount()
5402            .await;
5403
5404        let room = server.sync_joined_room(&client, room_id).await;
5405        let result =
5406            room.list_threads(ListThreadsOptions::default()).await.expect("Failed to list threads");
5407        assert_eq!(result.chunk.len(), 1);
5408        assert_eq!(result.chunk[0].event_id().unwrap(), eid1);
5409        assert!(result.prev_batch_token.is_some());
5410
5411        let opts = ListThreadsOptions { from: result.prev_batch_token, ..Default::default() };
5412        let result = room.list_threads(opts).await.expect("Failed to list threads");
5413        assert_eq!(result.chunk.len(), 1);
5414        assert_eq!(result.chunk[0].event_id().unwrap(), eid2);
5415        assert!(result.prev_batch_token.is_none());
5416    }
5417
5418    #[async_test]
5419    async fn test_relations() {
5420        let server = MatrixMockServer::new().await;
5421        let client = server.client_builder().build().await;
5422
5423        let room_id = room_id!("!a:b.c");
5424        let sender_id = user_id!("@alice:b.c");
5425        let f = EventFactory::new().room(room_id).sender(sender_id);
5426
5427        let target_event_id = owned_event_id!("$target");
5428        let eid1 = event_id!("$1");
5429        let eid2 = event_id!("$2");
5430        let batch1 = vec![f.text_msg("Related event 1").event_id(eid1).into_raw()];
5431        let batch2 = vec![f.text_msg("Related event 2").event_id(eid2).into_raw()];
5432
5433        server
5434            .mock_room_relations()
5435            .match_target_event(target_event_id.clone())
5436            .ok(RoomRelationsResponseTemplate::default().events(batch1).next_batch("next_batch"))
5437            .mock_once()
5438            .mount()
5439            .await;
5440
5441        server
5442            .mock_room_relations()
5443            .match_target_event(target_event_id.clone())
5444            .match_from("next_batch")
5445            .ok(RoomRelationsResponseTemplate::default().events(batch2))
5446            .mock_once()
5447            .mount()
5448            .await;
5449
5450        let room = server.sync_joined_room(&client, room_id).await;
5451
5452        // Main endpoint: no relation type filtered out.
5453        let mut opts = RelationsOptions {
5454            include_relations: IncludeRelations::AllRelations,
5455            ..Default::default()
5456        };
5457        let result = room
5458            .relations(target_event_id.clone(), opts.clone())
5459            .await
5460            .expect("Failed to list relations the first time");
5461        assert_eq!(result.chunk.len(), 1);
5462        assert_eq!(result.chunk[0].event_id().unwrap(), eid1);
5463        assert!(result.prev_batch_token.is_none());
5464        assert!(result.next_batch_token.is_some());
5465        assert!(result.recursion_depth.is_none());
5466
5467        opts.from = result.next_batch_token;
5468        let result = room
5469            .relations(target_event_id, opts)
5470            .await
5471            .expect("Failed to list relations the second time");
5472        assert_eq!(result.chunk.len(), 1);
5473        assert_eq!(result.chunk[0].event_id().unwrap(), eid2);
5474        assert!(result.prev_batch_token.is_none());
5475        assert!(result.next_batch_token.is_none());
5476        assert!(result.recursion_depth.is_none());
5477    }
5478
5479    #[async_test]
5480    async fn test_relations_with_reltype() {
5481        let server = MatrixMockServer::new().await;
5482        let client = server.client_builder().build().await;
5483
5484        let room_id = room_id!("!a:b.c");
5485        let sender_id = user_id!("@alice:b.c");
5486        let f = EventFactory::new().room(room_id).sender(sender_id);
5487
5488        let target_event_id = owned_event_id!("$target");
5489        let eid1 = event_id!("$1");
5490        let eid2 = event_id!("$2");
5491        let batch1 = vec![f.text_msg("In-thread event 1").event_id(eid1).into_raw()];
5492        let batch2 = vec![f.text_msg("In-thread event 2").event_id(eid2).into_raw()];
5493
5494        server
5495            .mock_room_relations()
5496            .match_target_event(target_event_id.clone())
5497            .match_subrequest(IncludeRelations::RelationsOfType(RelationType::Thread))
5498            .ok(RoomRelationsResponseTemplate::default().events(batch1).next_batch("next_batch"))
5499            .mock_once()
5500            .mount()
5501            .await;
5502
5503        server
5504            .mock_room_relations()
5505            .match_target_event(target_event_id.clone())
5506            .match_from("next_batch")
5507            .match_subrequest(IncludeRelations::RelationsOfType(RelationType::Thread))
5508            .ok(RoomRelationsResponseTemplate::default().events(batch2))
5509            .mock_once()
5510            .mount()
5511            .await;
5512
5513        let room = server.sync_joined_room(&client, room_id).await;
5514
5515        // Reltype-filtered endpoint, for threads \o/
5516        let mut opts = RelationsOptions {
5517            include_relations: IncludeRelations::RelationsOfType(RelationType::Thread),
5518            ..Default::default()
5519        };
5520        let result = room
5521            .relations(target_event_id.clone(), opts.clone())
5522            .await
5523            .expect("Failed to list relations the first time");
5524        assert_eq!(result.chunk.len(), 1);
5525        assert_eq!(result.chunk[0].event_id().unwrap(), eid1);
5526        assert!(result.prev_batch_token.is_none());
5527        assert!(result.next_batch_token.is_some());
5528        assert!(result.recursion_depth.is_none());
5529
5530        opts.from = result.next_batch_token;
5531        let result = room
5532            .relations(target_event_id, opts)
5533            .await
5534            .expect("Failed to list relations the second time");
5535        assert_eq!(result.chunk.len(), 1);
5536        assert_eq!(result.chunk[0].event_id().unwrap(), eid2);
5537        assert!(result.prev_batch_token.is_none());
5538        assert!(result.next_batch_token.is_none());
5539        assert!(result.recursion_depth.is_none());
5540    }
5541
5542    #[async_test]
5543    async fn test_power_levels_computation() {
5544        let server = MatrixMockServer::new().await;
5545        let client = server.client_builder().build().await;
5546
5547        let room_id = room_id!("!a:b.c");
5548        let sender_id = client.user_id().expect("No session id");
5549        let f = EventFactory::new().room(room_id).sender(sender_id);
5550
5551        // Computing the power levels will need these 3 state events:
5552        let room_create_event = f.create(sender_id, RoomVersionId::V1).into();
5553        let power_levels_event = f.power_levels().set_users([(sender_id, 50)]).into();
5554        let room_member_event = f.member(sender_id).into();
5555
5556        // With only the room member event
5557        let room = server
5558            .sync_room(&client, JoinedRoomBuilder::new(room_id).add_state_bulk([room_member_event]))
5559            .await;
5560        let ctx = room
5561            .push_condition_room_ctx()
5562            .await
5563            .expect("Failed to get push condition context")
5564            .expect("Could not get push condition context");
5565
5566        // The internal power levels couldn't be computed
5567        assert!(ctx.power_levels.is_none());
5568
5569        // Adding the room creation event
5570        let room = server
5571            .sync_room(&client, JoinedRoomBuilder::new(room_id).add_state_bulk([room_create_event]))
5572            .await;
5573        let ctx = room
5574            .push_condition_room_ctx()
5575            .await
5576            .expect("Failed to get push condition context")
5577            .expect("Could not get push condition context");
5578
5579        // The internal power levels still couldn't be computed
5580        assert!(ctx.power_levels.is_none());
5581
5582        // With the room member, room creation and the power levels events
5583        let room = server
5584            .sync_room(
5585                &client,
5586                JoinedRoomBuilder::new(room_id).add_state_bulk([power_levels_event]),
5587            )
5588            .await;
5589        let ctx = room
5590            .push_condition_room_ctx()
5591            .await
5592            .expect("Failed to get push condition context")
5593            .expect("Could not get push condition context");
5594
5595        // The internal power levels can finally be computed
5596        assert!(ctx.power_levels.is_some());
5597    }
5598
5599    // effective retention tests
5600
5601    const ONE_DAY: Duration = Duration::from_secs(86_400);
5602    const ONE_WEEK: Duration = Duration::from_secs(86_400 * 7);
5603    const ONE_HOUR: Duration = Duration::from_secs(3_600);
5604
5605    fn retention_room_id() -> &'static ruma::RoomId {
5606        room_id!("!a:b.c")
5607    }
5608
5609    async fn mock_retention_config(
5610        server: &MatrixMockServer,
5611        body: serde_json::Value,
5612    ) -> wiremock::MockGuard {
5613        Mock::given(method("GET"))
5614            .and(path("/_matrix/client/unstable/org.matrix.msc1763/retention/configuration"))
5615            .respond_with(ResponseTemplate::new(200).set_body_json(body))
5616            .mount_as_scoped(server.server())
5617            .await
5618    }
5619
5620    async fn room_with_retention(
5621        server: &MatrixMockServer,
5622        client: &Client,
5623        content: RoomRetentionEventContent,
5624    ) -> Room {
5625        server
5626            .sync_room(
5627                client,
5628                JoinedRoomBuilder::new(retention_room_id()).add_state_event(
5629                    EventFactory::new().sender(user_id!("@alice:b.c")).event(content).state_key(""),
5630                ),
5631            )
5632            .await
5633    }
5634
5635    #[async_test]
5636    async fn test_effective_retention_no_policy_anywhere() {
5637        let server = MatrixMockServer::new().await;
5638        let client = server.client_builder().build().await;
5639        let room = server.sync_joined_room(&client, retention_room_id()).await;
5640
5641        let _mock = mock_retention_config(
5642            &server,
5643            serde_json::json!({
5644                "policies": {},
5645                "limits": {},
5646            }),
5647        )
5648        .await;
5649
5650        let result = room.effective_retention().await.unwrap();
5651        assert!(result.is_none());
5652    }
5653
5654    #[async_test]
5655    async fn test_effective_retention_endpoint_not_implemented() {
5656        // A homeserver that hasn't implemented MSC1763 responds to the
5657        // retention configuration endpoint with `M_UNRECOGNIZED`. This
5658        // shouldn't surface as an error, since a server that doesn't support
5659        // the endpoint also won't enforce any server-side purging.
5660        let server = MatrixMockServer::new().await;
5661        let client = server.client_builder().build().await;
5662        let room = room_with_retention(
5663            &server,
5664            &client,
5665            RoomRetentionEventContent::new().at_most(ONE_DAY).unwrap(),
5666        )
5667        .await;
5668
5669        Mock::given(method("GET"))
5670            .and(path("/_matrix/client/unstable/org.matrix.msc1763/retention/configuration"))
5671            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
5672                "errcode": "M_UNRECOGNIZED",
5673                "error": "Unrecognized request",
5674            })))
5675            .mount(server.server())
5676            .await;
5677
5678        let result = room.effective_retention().await.unwrap();
5679        assert!(result.is_none());
5680    }
5681
5682    #[async_test]
5683    async fn test_effective_retention_server_default_only() {
5684        let server = MatrixMockServer::new().await;
5685        let client = server.client_builder().build().await;
5686        let room = server.sync_joined_room(&client, retention_room_id()).await;
5687
5688        let _mock = mock_retention_config(
5689            &server,
5690            serde_json::json!({
5691                "policies": {
5692                    "*": { "max_lifetime": ONE_WEEK.as_millis() as u64 }
5693                },
5694                "limits": {},
5695            }),
5696        )
5697        .await;
5698
5699        let result = room.effective_retention().await.unwrap().unwrap();
5700        assert_eq!(result.max_lifetime(), Some(ONE_WEEK));
5701        assert!(result.min_lifetime().is_none());
5702    }
5703
5704    #[async_test]
5705    async fn test_effective_retention_server_room_override() {
5706        // Server per-room override should win even if room has its own state
5707        // event.
5708        let server = MatrixMockServer::new().await;
5709        let client = server.client_builder().build().await;
5710        let room = room_with_retention(
5711            &server,
5712            &client,
5713            RoomRetentionEventContent::new().at_most(ONE_DAY).unwrap(),
5714        )
5715        .await;
5716
5717        let _mock = mock_retention_config(
5718            &server,
5719            serde_json::json!({
5720                "policies": {
5721                    "*": { "max_lifetime": ONE_WEEK.as_millis() as u64 },
5722                    "!a:b.c": { "max_lifetime": ONE_HOUR.as_millis() as u64 }
5723                },
5724                "limits": {},
5725            }),
5726        )
5727        .await;
5728
5729        let result = room.effective_retention().await.unwrap().unwrap();
5730        assert_eq!(result.max_lifetime(), Some(ONE_HOUR));
5731    }
5732
5733    #[async_test]
5734    async fn test_effective_retention_room_policy_with_limits() {
5735        struct TestCase {
5736            description: &'static str,
5737            room_max: Option<Duration>,
5738            room_min: Option<Duration>,
5739            limits: serde_json::Value,
5740            expected_max: Option<Duration>,
5741            expected_min: Option<Duration>,
5742        }
5743
5744        let test_cases = vec![
5745            TestCase {
5746                description: "room sets `max_lifetime` only, no server limits configured",
5747                room_max: Some(ONE_DAY),
5748                room_min: None,
5749                limits: serde_json::json!({}),
5750                expected_max: Some(ONE_DAY),
5751                expected_min: None,
5752            },
5753            TestCase {
5754                description: "room sets `min_lifetime` only, no server limits configured",
5755                room_max: None,
5756                room_min: Some(ONE_HOUR),
5757                limits: serde_json::json!({}),
5758                expected_max: None,
5759                expected_min: Some(ONE_HOUR),
5760            },
5761            TestCase {
5762                description: "room sets `max_lifetime` and `min_lifetime`, no server limits configured",
5763                room_max: Some(ONE_DAY),
5764                room_min: Some(ONE_HOUR),
5765                limits: serde_json::json!({}),
5766                expected_max: Some(ONE_DAY),
5767                expected_min: Some(ONE_HOUR),
5768            },
5769            TestCase {
5770                description: "room `max_lifetime` above server `max_lifetime.max` → outcome uses server `max_lifetime.max`",
5771                room_max: Some(ONE_WEEK),
5772                room_min: None,
5773                limits: serde_json::json!({
5774                    "max_lifetime": { "max": ONE_DAY.as_millis() as u64 }
5775                }),
5776                expected_max: Some(ONE_DAY),
5777                expected_min: None,
5778            },
5779            TestCase {
5780                description: "room `max_lifetime` below server `max_lifetime.min` → outcome uses server `max_lifetime.min`",
5781                room_max: Some(ONE_HOUR),
5782                room_min: None,
5783                limits: serde_json::json!({
5784                    "max_lifetime": { "min": ONE_DAY.as_millis() as u64 }
5785                }),
5786                expected_max: Some(ONE_DAY),
5787                expected_min: None,
5788            },
5789            TestCase {
5790                description: "room `min_lifetime` above server `min_lifetime.max` → outcome uses server `min_lifetime.max`",
5791                room_max: None,
5792                room_min: Some(ONE_WEEK),
5793                limits: serde_json::json!({
5794                    "min_lifetime": { "max": ONE_DAY.as_millis() as u64 }
5795                }),
5796                expected_max: None,
5797                expected_min: Some(ONE_DAY),
5798            },
5799            TestCase {
5800                description: "room `min_lifetime` below server `min_lifetime.min` → outcome uses server `min_lifetime.min`",
5801                room_max: None,
5802                room_min: Some(ONE_HOUR),
5803                limits: serde_json::json!({
5804                    "min_lifetime": { "min": ONE_DAY.as_millis() as u64 }
5805                }),
5806                expected_max: None,
5807                expected_min: Some(ONE_DAY),
5808            },
5809            TestCase {
5810                description: "room `max_lifetime` and `min_lifetime` both within their respective server limits → unchanged",
5811                room_max: Some(ONE_DAY),
5812                room_min: Some(ONE_HOUR),
5813                limits: serde_json::json!({
5814                    "max_lifetime": {
5815                        "min": ONE_HOUR.as_millis() as u64,
5816                        "max": ONE_WEEK.as_millis() as u64,
5817                    },
5818                    "min_lifetime": {
5819                        "min": Duration::from_secs(60).as_millis() as u64,
5820                        "max": ONE_DAY.as_millis() as u64,
5821                    },
5822                }),
5823                expected_max: Some(ONE_DAY),
5824                expected_min: Some(ONE_HOUR),
5825            },
5826            TestCase {
5827                description: "room `max_lifetime` omitted, server `max_lifetime.min` is used",
5828                room_max: None,
5829                room_min: None,
5830                limits: serde_json::json!({
5831                    "max_lifetime": { "min": ONE_DAY.as_millis() as u64 }
5832                }),
5833                expected_max: Some(ONE_DAY),
5834                expected_min: None,
5835            },
5836            TestCase {
5837                description: "room `min_lifetime` omitted, server `min_lifetime.min` is used",
5838                room_max: None,
5839                room_min: None,
5840                limits: serde_json::json!({
5841                    "min_lifetime": { "min": ONE_HOUR.as_millis() as u64 }
5842                }),
5843                expected_max: None,
5844                expected_min: Some(ONE_HOUR),
5845            },
5846            TestCase {
5847                description: "independently-clamped `max_lifetime`/`min_lifetime` cross → `min_lifetime` capped down to `max_lifetime`",
5848                room_max: Some(ONE_DAY),
5849                room_min: Some(ONE_HOUR),
5850                limits: serde_json::json!({
5851                    "max_lifetime": { "max": ONE_HOUR.as_millis() as u64 },
5852                    "min_lifetime": { "min": ONE_WEEK.as_millis() as u64 },
5853                }),
5854                expected_max: Some(ONE_HOUR),
5855                expected_min: Some(ONE_HOUR),
5856            },
5857            TestCase {
5858                description: "room `max_lifetime` omitted, server sets `max_lifetime.max` but no `.min` → stays unbounded (documents MSC1763 gap)",
5859                room_max: None,
5860                room_min: None,
5861                limits: serde_json::json!({
5862                    "max_lifetime": { "max": ONE_WEEK.as_millis() as u64 }
5863                }),
5864                expected_max: None,
5865                expected_min: None,
5866            },
5867        ];
5868
5869        for case in test_cases {
5870            let server = MatrixMockServer::new().await;
5871            let client = server.client_builder().build().await;
5872
5873            let mut content = RoomRetentionEventContent::new();
5874            if let Some(max) = case.room_max {
5875                content = content.at_most(max).unwrap();
5876            }
5877            if let Some(min) = case.room_min {
5878                content = content.at_least(min).unwrap();
5879            }
5880
5881            let room = room_with_retention(&server, &client, content).await;
5882
5883            let _mock = mock_retention_config(
5884                &server,
5885                serde_json::json!({
5886                    "policies": {},
5887                    "limits": case.limits,
5888                }),
5889            )
5890            .await;
5891
5892            let result = room
5893                .effective_retention()
5894                .await
5895                .unwrap_or_else(|e| panic!("{}: effective_retention failed: {e}", case.description))
5896                .unwrap_or_else(|| panic!("{}: expected Some, got None", case.description));
5897
5898            assert_eq!(result.max_lifetime(), case.expected_max, "{}", case.description);
5899            assert_eq!(result.min_lifetime(), case.expected_min, "{}", case.description);
5900        }
5901    }
5902
5903    #[async_test]
5904    async fn test_send_state_event_raw_with_request_config() {
5905        let server = MatrixMockServer::new().await;
5906        // The client retries by default, the request below must override that.
5907        let client = server
5908            .client_builder()
5909            .on_builder(|builder| builder.request_config(RequestConfig::new().retry_limit(3)))
5910            .build()
5911            .await;
5912        let room = server.sync_joined_room(&client, room_id!("!a:b.c")).await;
5913
5914        server.mock_room_send_state().error500().expect(1).mount().await;
5915
5916        room.send_state_event_raw("org.example.custom", "", serde_json::json!({}))
5917            .with_request_config(RequestConfig::new().disable_retry())
5918            .await
5919            .unwrap_err();
5920    }
5921}