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