Struct matrix_sdk::room::Room

source ·
pub struct Room { /* private fields */ }
Expand description

A struct containing methods that are common for Joined, Invited and Left Rooms

Implementations§

source§

impl Room

source

pub async fn leave(&self) -> Result<()>

Leave this room.

Only invited and joined rooms can be left.

source

pub async fn join(&self) -> Result<()>

Join this room.

Only invited and left rooms can be joined via this method.

source

pub fn client(&self) -> Client

Get the inner client saved in this room instance.

Returns the client this room is part of.

source

pub fn is_synced(&self) -> bool

Get the sync state of this room, i.e. whether it was fully synced with the server.

source

pub async fn avatar(&self, format: MediaFormat) -> Result<Option<Vec<u8>>>

Gets the avatar of this room, if set.

Returns the avatar. If a thumbnail is requested no guarantee on the size of the image is given.

§Arguments
  • format - The desired format of the avatar.
§Examples
let client = Client::new(homeserver).await.unwrap();
client.matrix_auth().login_username(user, "password").send().await.unwrap();
let room_id = room_id!("!roomid:example.com");
let room = client.get_room(&room_id).unwrap();
if let Some(avatar) = room.avatar(MediaFormat::File).await.unwrap() {
    std::fs::write("avatar.png", avatar);
}
source

pub async fn messages(&self, options: MessagesOptions) -> Result<Messages>

Sends a request to /_matrix/client/r0/rooms/{room_id}/messages and returns a Messages struct that contains a chunk of room and state events (RoomEvent and AnyStateEvent).

With the encryption feature, messages are decrypted if possible. If decryption fails for an individual message, that message is returned undecrypted.

§Examples
use matrix_sdk::{room::MessagesOptions, Client};

let options =
    MessagesOptions::backward().from("t47429-4392820_219380_26003_2265");

let mut client = Client::new(homeserver).await.unwrap();
let room = client.get_room(room_id!("!roomid:example.com")).unwrap();
assert!(room.messages(options).await.is_ok());
source

pub fn add_event_handler<Ev, Ctx, H>(&self, handler: H) -> EventHandlerHandle
where Ev: SyncEvent + DeserializeOwned + Send + 'static, H: EventHandler<Ev, Ctx>,

Register a handler for events of a specific type, within this room.

This method works the same way as Client::add_event_handler, except that the handler will only be called for events within this room. See that method for more details on event handler functions.

room.add_event_handler(hdl) is equivalent to client.add_room_event_handler(room_id, hdl). Use whichever one is more convenient in your use case.

source

pub fn subscribe_to_updates(&self) -> Receiver<RoomUpdate>

Subscribe to all updates for this room.

The returned receiver will receive a new message for each sync response that contains updates for this room.

source

pub fn subscribe_to_typing_notifications( &self ) -> (EventHandlerDropGuard, Receiver<Vec<OwnedUserId>>)

Subscribe to typing notifications for this room.

The returned receiver will receive a new vector of user IDs for each sync response that contains ‘m.typing’ event. The current user ID will be filtered out.

source

pub async fn event(&self, event_id: &EventId) -> Result<TimelineEvent>

Fetch the event with the given EventId in this room.

source

pub async fn event_with_context( &self, event_id: &EventId, lazy_load_members: bool, context_size: UInt ) -> Result<EventWithContextResponse>

Fetch the event with the given EventId in this room, using the /context endpoint to get more information.

source

pub async fn is_encrypted(&self) -> Result<bool>

Check whether this room is encrypted. If the room encryption state is not synced yet, it will send a request to fetch it.

Returns true if the room is encrypted, otherwise false.

source

pub async fn sync_members(&self) -> Result<()>

Sync the member list with the server.

This method will de-duplicate requests if it is called multiple times in quick succession, in that case the return value will be None. This method does nothing if the members are already synced.

source

pub async fn active_members(&self) -> Result<Vec<RoomMember>>

👎Deprecated: Use members with RoomMemberships::ACTIVE instead

Get active members for this room, includes invited, joined members.

Note: This method will fetch the members from the homeserver if the member list isn’t synchronized due to member lazy loading. Because of that, it might panic if it isn’t run on a tokio thread.

Use active_members_no_sync() if you want a method that doesn’t do any requests.

source

pub async fn active_members_no_sync(&self) -> Result<Vec<RoomMember>>

👎Deprecated: Use members_no_sync with RoomMemberships::ACTIVE instead

Get active members for this room, includes invited, joined members.

Note: This method will not fetch the members from the homeserver if the member list isn’t synchronized due to member lazy loading. Thus, members could be missing from the list.

Use active_members() if you want to ensure to always get the full member list.

source

pub async fn joined_members(&self) -> Result<Vec<RoomMember>>

👎Deprecated: Use members with RoomMemberships::JOIN instead

Get all the joined members of this room.

Note: This method will fetch the members from the homeserver if the member list isn’t synchronized due to member lazy loading. Because of that it might panic if it isn’t run on a tokio thread.

Use joined_members_no_sync() if you want a method that doesn’t do any requests.

source

pub async fn joined_members_no_sync(&self) -> Result<Vec<RoomMember>>

👎Deprecated: Use members_no_sync with RoomMemberships::JOIN instead

Get all the joined members of this room.

Note: This method will not fetch the members from the homeserver if the member list isn’t synchronized due to member lazy loading. Thus, members could be missing from the list.

Use joined_members() if you want to ensure to always get the full member list.

source

pub async fn get_member(&self, user_id: &UserId) -> Result<Option<RoomMember>>

Get a specific member of this room.

Note: This method will fetch the members from the homeserver if the member list isn’t synchronized due to member lazy loading. Because of that it might panic if it isn’t run on a tokio thread.

Use get_member_no_sync() if you want a method that doesn’t do any requests.

§Arguments
  • user_id - The ID of the user that should be fetched out of the store.
source

pub async fn get_member_no_sync( &self, user_id: &UserId ) -> Result<Option<RoomMember>>

Get a specific member of this room.

Note: This method will not fetch the members from the homeserver if the member list isn’t synchronized due to member lazy loading. Thus, members could be missing.

Use get_member() if you want to ensure to always have the full member list to chose from.

§Arguments
  • user_id - The ID of the user that should be fetched out of the store.
source

pub async fn members( &self, memberships: RoomMemberships ) -> Result<Vec<RoomMember>>

Get members for this room, with the given memberships.

Note: This method will fetch the members from the homeserver if the member list isn’t synchronized due to member lazy loading. Because of that it might panic if it isn’t run on a tokio thread.

Use members_no_sync() if you want a method that doesn’t do any requests.

source

pub async fn members_no_sync( &self, memberships: RoomMemberships ) -> Result<Vec<RoomMember>>

Get members for this room, with the given memberships.

Note: This method will not fetch the members from the homeserver if the member list isn’t synchronized due to member lazy loading. Thus, members could be missing.

Use members() if you want to ensure to always get the full member list.

source

pub async fn get_state_events( &self, event_type: StateEventType ) -> Result<Vec<RawAnySyncOrStrippedState>>

Get all state events of a given type in this room.

source

pub async fn get_state_events_static<C>( &self ) -> Result<Vec<RawSyncOrStrippedState<C>>>

Get all state events of a given statically-known type in this room.

§Examples
use matrix_sdk::ruma::{
    events::room::member::RoomMemberEventContent, serde::Raw,
};

let room_members =
    room.get_state_events_static::<RoomMemberEventContent>().await?;
source

pub async fn get_state_events_for_keys( &self, event_type: StateEventType, state_keys: &[&str] ) -> Result<Vec<RawAnySyncOrStrippedState>>

Get the state events of a given type with the given state keys in this room.

source

pub async fn get_state_events_for_keys_static<'a, C, K, I>( &self, state_keys: I ) -> Result<Vec<RawSyncOrStrippedState<C>>>

Get the state events of a given statically-known type with the given state keys in this room.

§Examples
use matrix_sdk::ruma::events::room::member::RoomMemberEventContent;

let room_members = room
    .get_state_events_for_keys_static::<RoomMemberEventContent, _, _>(
        user_ids,
    )
    .await?;
source

pub async fn get_state_event( &self, event_type: StateEventType, state_key: &str ) -> Result<Option<RawAnySyncOrStrippedState>>

Get a specific state event in this room.

source

pub async fn get_state_event_static<C>( &self ) -> Result<Option<RawSyncOrStrippedState<C>>>

Get a specific state event of statically-known type with an empty state key in this room.

§Examples
use matrix_sdk::ruma::events::room::power_levels::RoomPowerLevelsEventContent;

let power_levels = room
    .get_state_event_static::<RoomPowerLevelsEventContent>()
    .await?
    .expect("every room has a power_levels event")
    .deserialize()?;
source

pub async fn get_state_event_static_for_key<C, K>( &self, state_key: &K ) -> Result<Option<RawSyncOrStrippedState<C>>>

Get a specific state event of statically-known type in this room.

§Examples
use matrix_sdk::ruma::{
    events::room::member::RoomMemberEventContent, serde::Raw, user_id,
};

let member_event = room
    .get_state_event_static_for_key::<RoomMemberEventContent, _>(user_id!(
        "@alice:example.org"
    ))
    .await?;
source

pub async fn parent_spaces( &self ) -> Result<impl Stream<Item = Result<ParentSpace>> + '_>

Returns the parents this room advertises as its parents.

Results are in no particular order.

source

pub async fn account_data( &self, data_type: RoomAccountDataEventType ) -> Result<Option<Raw<AnyRoomAccountDataEvent>>>

Read account data in this room, from storage.

source

pub async fn account_data_static<C>( &self ) -> Result<Option<Raw<RoomAccountDataEvent<C>>>>

Get account data of a statically-known type in this room, from storage.

§Examples
use matrix_sdk::ruma::events::fully_read::FullyReadEventContent;

match room.account_data_static::<FullyReadEventContent>().await? {
    Some(fully_read) => {
        println!("Found read marker: {:?}", fully_read.deserialize()?)
    }
    None => println!("No read marker for this room"),
}
source

pub async fn contains_only_verified_devices(&self) -> Result<bool>

Available on crate feature e2e-encryption only.

Check if all members of this room are verified and all their devices are verified.

Returns true if all devices in the room are verified, otherwise false.

source

pub async fn set_tag( &self, tag: TagName, tag_info: TagInfo ) -> HttpResult<Response>

Adds a tag to the room, or updates it if it already exists.

Returns the create_tag::v3::Response from the server.

§Arguments
  • tag - The tag to add or update.

  • tag_info - Information about the tag, generally containing the order parameter.

§Examples
use matrix_sdk::ruma::events::tag::TagInfo;

if let Some(room) = client.get_room(&room_id) {
    let mut tag_info = TagInfo::new();
    tag_info.order = Some(0.9);
    let user_tag = UserTagName::from_str("u.work")?;

    room.set_tag(TagName::User(user_tag), tag_info).await?;
}
source

pub async fn remove_tag(&self, tag: TagName) -> HttpResult<Response>

Removes a tag from the room.

Returns the delete_tag::v3::Response from the server.

§Arguments
  • tag - The tag to remove.
source

pub async fn set_is_favourite( &self, is_favourite: bool, tag_order: Option<f64> ) -> Result<()>

Add or remove the m.favourite flag for this room.

If is_favourite is true, and the m.low_priority tag is set on the room, the tag will be removed too.

§Arguments
  • is_favourite - Whether to mark this room as favourite.
  • tag_order - The order of the tag if any.
source

pub async fn set_is_low_priority( &self, is_low_priority: bool, tag_order: Option<f64> ) -> Result<()>

Add or remove the m.lowpriority flag for this room.

If is_low_priority is true, and the m.favourite tag is set on the room, the tag will be removed too.

§Arguments
  • is_low_priority - Whether to mark this room as low_priority or not.
  • tag_order - The order of the tag if any.
source

pub async fn set_is_direct(&self, is_direct: bool) -> Result<()>

Sets whether this room is a DM.

When setting this room as DM, it will be marked as DM for all active members of the room. When unsetting this room as DM, it will be unmarked as DM for all users, not just the members.

§Arguments
  • is_direct - Whether to mark this room as direct.
source

pub async fn decrypt_event( &self, event: &Raw<OriginalSyncRoomEncryptedEvent> ) -> Result<TimelineEvent>

Available on crate feature e2e-encryption only.

Tries to decrypt a room event.

§Arguments
  • event - The room event to be decrypted.

Returns the decrypted event.

source

pub async fn discard_room_key(&self) -> Result<()>

Available on crate feature e2e-encryption only.

Forces the currently active room key, which is used to encrypt messages, to be rotated.

A new room key will be crated and shared with all the room members the next time a message will be sent. You don’t have to call this method, room keys will be rotated automatically when necessary. This method is still useful for debugging purposes.

For more info please take a look a the encryption module documentation.

source

pub async fn ban_user( &self, user_id: &UserId, reason: Option<&str> ) -> Result<()>

Ban the user with UserId from this room.

§Arguments
  • user_id - The user to ban with UserId.

  • reason - The reason for banning this user.

source

pub async fn unban_user( &self, user_id: &UserId, reason: Option<&str> ) -> Result<()>

Unban the user with UserId from this room.

§Arguments
  • user_id - The user to unban with UserId.

  • reason - The reason for unbanning this user.

source

pub async fn kick_user( &self, user_id: &UserId, reason: Option<&str> ) -> Result<()>

Kick a user out of this room.

§Arguments
  • user_id - The UserId of the user that should be kicked out of the room.

  • reason - Optional reason why the room member is being kicked out.

source

pub async fn invite_user_by_id(&self, user_id: &UserId) -> Result<()>

Invite the specified user by UserId to this room.

§Arguments
  • user_id - The UserId of the user to invite to the room.
source

pub async fn invite_user_by_3pid(&self, invite_id: Invite3pid) -> Result<()>

Invite the specified user by third party id to this room.

§Arguments
  • invite_id - A third party id of a user to invite to the room.
source

pub async fn typing_notice(&self, typing: bool) -> Result<()>

Activate typing notice for this room.

The typing notice remains active for 4s. It can be deactivate at any point by setting typing to false. If this method is called while the typing notice is active nothing will happen. This method can be called on every key stroke, since it will do nothing while typing is active.

§Arguments
  • typing - Whether the user is typing or has stopped typing.
§Examples
use std::time::Duration;

use matrix_sdk::ruma::api::client::typing::create_typing_event::v3::Typing;

let room_id = room_id!("!SVkFJHzfwvuaIEawgC:localhost");

if let Some(room) = client.get_room(&room_id) {
    room.typing_notice(true).await?
}
source

pub async fn send_single_receipt( &self, receipt_type: ReceiptType, thread: ReceiptThread, event_id: OwnedEventId ) -> Result<()>

Send a request to set a single receipt.

§Arguments
  • receipt_type - The type of the receipt to set. Note that it is possible to set the fully-read marker although it is technically not a receipt.

  • thread - The thread where this receipt should apply, if any. Note that this must be ReceiptThread::Unthreaded when sending a ReceiptType::FullyRead.

  • event_id - The EventId of the event to set the receipt on.

source

pub async fn send_multiple_receipts(&self, receipts: Receipts) -> Result<()>

Send a request to set multiple receipts at once.

§Arguments
  • receipts - The Receipts to send.

If receipts is empty, this is a no-op.

source

pub async fn enable_encryption(&self) -> Result<()>

Enable End-to-end encryption in this room.

This method will be a noop if encryption is already enabled, otherwise sends a m.room.encryption state event to the room. This might fail if you don’t have the appropriate power level to enable end-to-end encryption.

A sync needs to be received to update the local room state. This method will wait for a sync to be received, this might time out if no sync loop is running or if the server is slow.

§Examples
let room_id = room_id!("!SVkFJHzfwvuaIEawgC:localhost");

if let Some(room) = client.get_room(&room_id) {
    room.enable_encryption().await?
}
source

pub async fn sync_up(&self)

Wait for the room to be fully synced.

This method makes sure the room that was returned when joining a room has been echoed back in the sync.

Warning: This waits until a sync happens and does not return if no sync is happening. It can also return early when the room is not a joined room anymore.

source

pub fn send( &self, content: impl MessageLikeEventContent ) -> SendMessageLikeEvent<'_>

Send a message-like event to this room.

Returns the parsed response from the server.

If the encryption feature is enabled this method will transparently encrypt the event if this room is encrypted (except for m.reaction events, which are never encrypted).

Note: If you just want to send an event with custom JSON content to a room, you can use the send_raw() method for that.

If you want to set a transaction ID for the event, use .with_transaction_id() on the returned value before .awaiting it.

§Arguments
  • content - The content of the message event.
§Examples
use matrix_sdk::ruma::{
    events::{
        macros::EventContent,
        room::message::{RoomMessageEventContent, TextMessageEventContent},
    },
    uint, MilliSecondsSinceUnixEpoch, TransactionId,
};

let content = RoomMessageEventContent::text_plain("Hello world");
let txn_id = TransactionId::new();

if let Some(room) = client.get_room(&room_id) {
    room.send(content).with_transaction_id(&txn_id).await?;
}

// Custom events work too:
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[ruma_event(type = "org.shiny_new_2fa.token", kind = MessageLike)]
struct TokenEventContent {
    token: String,
    #[serde(rename = "exp")]
    expires_at: MilliSecondsSinceUnixEpoch,
}

let content = TokenEventContent {
    token: generate_token(),
    expires_at: {
        let now = MilliSecondsSinceUnixEpoch::now();
        MilliSecondsSinceUnixEpoch(now.0 + uint!(30_000))
    },
};

if let Some(room) = client.get_room(&room_id) {
    room.send(content).await?;
}
source

pub fn send_raw<'a>( &'a self, event_type: &'a str, content: impl IntoRawMessageLikeEventContent ) -> SendRawMessageLikeEvent<'a>

Send a message-like event with custom JSON content to this room.

Returns the parsed response from the server.

If the encryption feature is enabled this method will transparently encrypt the event if this room is encrypted (except for m.reaction events, which are never encrypted).

This method is equivalent to the send() method but allows sending custom JSON payloads, e.g. constructed using the serde_json::json!() macro.

If you want to set a transaction ID for the event, use .with_transaction_id() on the returned value before .awaiting it.

§Arguments
  • event_type - The type of the event.

  • content - The content of the event as a raw JSON value. The argument type can be serde_json::Value, but also other raw JSON types; for the full list check the documentation of IntoRawMessageLikeEventContent.

§Examples
use serde_json::json;

if let Some(room) = client.get_room(&room_id) {
    room.send_raw("m.room.message", json!({ "body": "Hello world" })).await?;
}
source

pub fn send_attachment<'a>( &'a self, filename: &'a str, content_type: &'a Mime, data: Vec<u8>, config: AttachmentConfig ) -> SendAttachment<'a>

Send an attachment to this room.

This will upload the given data that the reader produces using the upload() method and post an event to the given room. If the room is encrypted and the encryption feature is enabled the upload will be encrypted.

This is a convenience method that calls the upload() and afterwards the send().

§Arguments
  • filename - The file name.

  • content_type - The type of the media, this will be used as the content-type header.

  • reader - A Reader that will be used to fetch the raw bytes of the media.

  • config - Metadata and configuration for the attachment.

§Examples
let mut image = fs::read("/home/example/my-cat.jpg")?;

if let Some(room) = client.get_room(&room_id) {
    room.send_attachment(
        "my_favorite_cat.jpg",
        &mime::IMAGE_JPEG,
        image,
        AttachmentConfig::new(),
    ).await?;
}
source

pub async fn update_power_levels( &self, updates: Vec<(&UserId, Int)> ) -> Result<Response>

Update the power levels of a select set of users of this room.

Issue a power_levels state event request to the server, changing the given UserId -> Int levels. May fail if the power_levels aren’t locally known yet or the server rejects the state event update, e.g. because of insufficient permissions. Neither permissions to update nor whether the data might be stale is checked prior to issuing the request.

source

pub async fn apply_power_level_changes( &self, changes: RoomPowerLevelChanges ) -> Result<()>

Applies a set of power level changes to this room.

Any values that are None in the given RoomPowerLevelChanges will remain unchanged.

source

pub async fn room_power_levels(&self) -> Result<RoomPowerLevels>

Get the current power levels of this room.

source

pub async fn reset_power_levels(&self) -> Result<RoomPowerLevels>

Resets the room’s power levels to the default values

source

pub async fn get_suggested_user_role( &self, user_id: &UserId ) -> Result<RoomMemberRole>

Gets the suggested role for the user with the provided user_id.

This method checks the RoomPowerLevels events instead of loading the member list and looking for the member.

source

pub async fn get_user_power_level(&self, user_id: &UserId) -> Result<i64>

Gets the power level the user with the provided user_id.

This method checks the RoomPowerLevels events instead of loading the member list and looking for the member.

source

pub async fn users_with_power_levels(&self) -> HashMap<OwnedUserId, i64>

Gets a map with the UserId of users with power levels other than 0 and this power level.

source

pub async fn set_name(&self, name: String) -> Result<Response>

Sets the name of this room.

source

pub async fn set_room_topic(&self, topic: &str) -> Result<Response>

Sets a new topic for this room.

source

pub async fn set_avatar_url( &self, url: &MxcUri, info: Option<ImageInfo> ) -> Result<Response>

Sets the new avatar url for this room.

§Arguments
  • avatar_url - The owned matrix uri that represents the avatar
  • info - The optional image info that can be provided for the avatar
source

pub async fn remove_avatar(&self) -> Result<Response>

Removes the avatar from the room

source

pub async fn upload_avatar( &self, mime: &Mime, data: Vec<u8>, info: Option<ImageInfo> ) -> Result<Response>

Uploads a new avatar for this room.

§Arguments
  • mime - The mime type describing the data
  • data - The data representation of the avatar
  • info - The optional image info provided for the avatar, the blurhash and the mimetype will always be updated
source

pub async fn send_state_event( &self, content: impl StateEventContent<StateKey = EmptyStateKey> ) -> Result<Response>

Send a state event with an empty state key to the homeserver.

For state events with a non-empty state key, see send_state_event_for_key.

Returns the parsed response from the server.

§Arguments
  • content - The content of the state event.
§Examples
use matrix_sdk::ruma::{
    events::{
        macros::EventContent, room::encryption::RoomEncryptionEventContent,
        EmptyStateKey,
    },
    EventEncryptionAlgorithm,
};

let encryption_event_content = RoomEncryptionEventContent::new(
    EventEncryptionAlgorithm::MegolmV1AesSha2,
);
joined_room.send_state_event(encryption_event_content).await?;

// Custom event:
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[ruma_event(
    type = "org.matrix.msc_9000.xxx",
    kind = State,
    state_key_type = EmptyStateKey,
)]
struct XxxStateEventContent {/* fields... */}

let content: XxxStateEventContent = todo!();
joined_room.send_state_event(content).await?;
source

pub async fn send_state_event_for_key<C, K>( &self, state_key: &K, content: C ) -> Result<Response>
where C: StateEventContent, C::StateKey: Borrow<K>, K: AsRef<str> + ?Sized,

Send a state event to the homeserver.

Returns the parsed response from the server.

§Arguments
  • content - The content of the state event.

  • state_key - A unique key which defines the overwriting semantics for this piece of room state.

§Examples
use matrix_sdk::ruma::{
    events::{
        macros::EventContent,
        room::member::{RoomMemberEventContent, MembershipState},
    },
    mxc_uri,
};

let avatar_url = mxc_uri!("mxc://example.org/avatar").to_owned();
let mut content = RoomMemberEventContent::new(MembershipState::Join);
content.avatar_url = Some(avatar_url);

joined_room.send_state_event_for_key(ruma::user_id!("@foo:bar.com"), content).await?;

// Custom event:
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[ruma_event(type = "org.matrix.msc_9000.xxx", kind = State, state_key_type = String)]
struct XxxStateEventContent { /* fields... */ }

let content: XxxStateEventContent = todo!();
joined_room.send_state_event_for_key("foo", content).await?;
source

pub async fn send_state_event_raw( &self, event_type: &str, state_key: &str, content: impl IntoRawStateEventContent ) -> Result<Response>

Send a raw room state event to the homeserver.

Returns the parsed response from the server.

§Arguments
  • event_type - The type of the event that we’re sending out.

  • state_key - A unique key which defines the overwriting semantics for this piece of room state. This value is often a zero-length string.

  • content - The content of the event as a raw JSON value. The argument type can be serde_json::Value, but also other raw JSON types; for the full list check the documentation of IntoRawStateEventContent.

§Examples
use serde_json::json;


if let Some(room) = client.get_room(&room_id) {
    room.send_state_event_raw("m.room.member", "", json!({
        "avatar_url": "mxc://example.org/SEsfnsuifSDFSSEF",
        "displayname": "Alice Margatroid",
        "membership": "join",
    })).await?;
}
source

pub async fn redact( &self, event_id: &EventId, reason: Option<&str>, txn_id: Option<OwnedTransactionId> ) -> HttpResult<Response>

Strips all information out of an event of the room.

Returns the redact_event::v3::Response from the server.

This cannot be undone. Users may redact their own events, and any user with a power level greater than or equal to the redact power level of the room may redact events there.

§Arguments
  • event_id - The ID of the event to redact

  • reason - The reason for the event being redacted.

  • txn_id - A unique ID that can be attached to this event as its transaction ID. If not given one is created for the message.

§Examples
use matrix_sdk::ruma::event_id;

if let Some(room) = client.get_room(&room_id) {
    let event_id = event_id!("$xxxxxx:example.org");
    let reason = Some("Indecent material");
    room.redact(&event_id, reason, None).await?;
}
source

pub async fn can_user_redact_own(&self, user_id: &UserId) -> Result<bool>

Returns true if the user with the given user_id is able to redact their own messages in the room.

The call may fail if there is an error in getting the power levels.

source

pub async fn can_user_redact_other(&self, user_id: &UserId) -> Result<bool>

Returns true if the user with the given user_id is able to redact messages of other users in the room.

The call may fail if there is an error in getting the power levels.

source

pub async fn can_user_ban(&self, user_id: &UserId) -> Result<bool>

Returns true if the user with the given user_id is able to ban in the room.

The call may fail if there is an error in getting the power levels.

source

pub async fn can_user_invite(&self, user_id: &UserId) -> Result<bool>

Returns true if the user with the given user_id is able to kick in the room.

The call may fail if there is an error in getting the power levels.

source

pub async fn can_user_kick(&self, user_id: &UserId) -> Result<bool>

Returns true if the user with the given user_id is able to kick in the room.

The call may fail if there is an error in getting the power levels.

source

pub async fn can_user_send_state( &self, user_id: &UserId, state_event: StateEventType ) -> Result<bool>

Returns true if the user with the given user_id is able to send a specific state event type in the room.

The call may fail if there is an error in getting the power levels.

source

pub async fn can_user_send_message( &self, user_id: &UserId, message: MessageLikeEventType ) -> Result<bool>

Returns true if the user with the given user_id is able to send a specific message type in the room.

The call may fail if there is an error in getting the power levels.

source

pub async fn can_user_trigger_room_notification( &self, user_id: &UserId ) -> Result<bool>

Returns true if the user with the given user_id is able to trigger a notification in the room.

The call may fail if there is an error in getting the power levels.

source

pub async fn route(&self) -> Result<Vec<OwnedServerName>>

Get a list of servers that should know this room.

Uses the synced members of the room and the suggested routing algorithm from the Matrix spec.

Returns at most three servers.

Get a matrix.to permalink to this room.

If this room has an alias, we use it. Otherwise, we try to use the synced members in the room for routing the room ID.

Get a matrix: permalink to this room.

If this room has an alias, we use it. Otherwise, we try to use the synced members in the room for routing the room ID.

§Arguments
  • join - Whether the user should join the room.

Get a matrix.to permalink to an event in this room.

We try to use the synced members in the room for routing the room ID.

Note: This method does not check if the given event ID is actually part of this room. It needs to be checked before calling this method otherwise the permalink won’t work.

§Arguments
  • event_id - The ID of the event.

Get a matrix: permalink to an event in this room.

We try to use the synced members in the room for routing the room ID.

Note: This method does not check if the given event ID is actually part of this room. It needs to be checked before calling this method otherwise the permalink won’t work.

§Arguments
  • event_id - The ID of the event.
source

pub async fn load_user_receipt( &self, receipt_type: ReceiptType, thread: ReceiptThread, user_id: &UserId ) -> Result<Option<(OwnedEventId, Receipt)>>

Get the latest receipt of a user in this room.

§Arguments
  • receipt_type - The type of receipt to get.

  • thread - The thread containing the event of the receipt, if any.

  • user_id - The ID of the user.

Returns the ID of the event on which the receipt applies and the receipt.

source

pub async fn load_event_receipts( &self, receipt_type: ReceiptType, thread: ReceiptThread, event_id: &EventId ) -> Result<Vec<(OwnedUserId, Receipt)>>

Load the receipts for an event in this room from storage.

§Arguments
  • receipt_type - The type of receipt to get.

  • thread - The thread containing the event of the receipt, if any.

  • event_id - The ID of the event.

Returns a list of IDs of users who have sent a receipt for the event and the corresponding receipts.

source

pub async fn push_context(&self) -> Result<Option<PushConditionRoomCtx>>

Get the push context for this room.

Returns None if some data couldn’t be found. This should only happen in brand new rooms, while we process its state.

source

pub async fn event_push_actions<T>( &self, event: &Raw<T> ) -> Result<Option<Vec<Action>>>

Get the push actions for the given event with the current room state.

Note that it is possible that no push action is returned because the current room state does not have all the required state events.

source

pub async fn invite_details(&self) -> Result<Invite>

The membership details of the (latest) invite for the logged-in user in this room.

source

pub async fn forget(&self) -> Result<()>

Forget this room.

This communicates to the homeserver that it should forget the room.

Only left rooms can be forgotten.

source

pub async fn notification_mode(&self) -> Option<RoomNotificationMode>

Get the notification mode

source

pub async fn user_defined_notification_mode( &self ) -> Option<RoomNotificationMode>

Get the user-defined notification mode

source

pub async fn report_content( &self, event_id: OwnedEventId, score: Option<ReportedContentScore>, reason: Option<String> ) -> Result<Response>

Report an event as inappropriate to the homeserver’s administrator.

§Arguments
  • event_id - The ID of the event to report.
  • score - The score to rate this content.
  • reason - The reason the content is being reported.
§Errors

Returns an error if the room is not joined or if an error occurs with the request.

source

pub async fn set_unread_flag(&self, unread: bool) -> Result<()>

Set a flag on the room to indicate that the user has explicitly marked it as (un)read.

source

pub async fn event_cache( &self ) -> Result<(RoomEventCache, Arc<EventCacheDropHandles>)>

Returns the RoomEventCache associated to this room, assuming the global EventCache has been enabled for subscription.

source

pub async fn send_call_notification_if_needed(&self) -> Result<()>

This will only send a call notification event if appropriate.

This function is supposed to be called whenever the user creates a room call. It will send a m.call.notify event if:

  • there is not yet a running call. It will configure the notify type: ring or notify based on:
  • is this a DM room -> ring
  • is this a group with more than one other member -> notify
source

pub async fn send_call_notification( &self, call_id: String, application: ApplicationType, notify_type: NotifyType, mentions: Mentions ) -> Result<()>

Send a call notification event in the current room.

This is only supposed to be used in custom situations where the user explicitly chooses to send a m.call.notify event to invite/notify someone explicitly in unusual conditions. The default should be to use send_call_notification_if_needed just before a new room call is created/joined.

One example could be that the UI allows to start a call with a subset of users of the room members first. And then later on the user can invite more users to the call.

Methods from Deref<Target = BaseRoom>§

source

pub fn room_id(&self) -> &RoomId

Get the unique room id of the room.

source

pub fn own_user_id(&self) -> &UserId

Get our own user id.

source

pub fn state(&self) -> RoomState

Get the state of the room.

source

pub fn is_space(&self) -> bool

Whether this room’s RoomType is m.space.

source

pub fn room_type(&self) -> Option<RoomType>

Returns the room’s type as defined in its creation event (m.room.create).

source

pub fn unread_notification_counts(&self) -> UnreadNotificationsCount

Get the unread notification counts.

source

pub fn num_unread_messages(&self) -> u64

Get the number of unread messages (computed client-side).

This might be more precise than Self::unread_notification_counts for encrypted rooms.

source

pub fn read_receipts(&self) -> RoomReadReceipts

Get the detailed information about read receipts for the room.

source

pub fn num_unread_notifications(&self) -> u64

Get the number of unread notifications (computed client-side).

This might be more precise than Self::unread_notification_counts for encrypted rooms.

source

pub fn num_unread_mentions(&self) -> u64

Get the number of unread mentions (computed client-side), that is, messages causing a highlight in a room.

This might be more precise than Self::unread_notification_counts for encrypted rooms.

source

pub fn are_members_synced(&self) -> bool

Check if the room has its members fully synced.

Members might be missing if lazy member loading was enabled for the sync.

Returns true if no members are missing, false otherwise.

source

pub fn mark_members_missing(&self)

Mark this Room as still missing member information.

source

pub fn is_state_fully_synced(&self) -> bool

Check if the room states have been synced

States might be missing if we have only seen the room_id of this Room so far, for example as the response for a create_room request without being synced yet.

Returns true if the state is fully synced, false otherwise.

source

pub fn is_encryption_state_synced(&self) -> bool

Check if the room has its encryption event synced.

The encryption event can be missing when the room hasn’t appeared in sync yet.

Returns true if the encryption state is synced, false otherwise.

source

pub fn last_prev_batch(&self) -> Option<String>

Get the prev_batch token that was received from the last sync. May be None if the last sync contained the full room history.

source

pub fn avatar_url(&self) -> Option<OwnedMxcUri>

Get the avatar url of this room.

source

pub fn canonical_alias(&self) -> Option<OwnedRoomAliasId>

Get the canonical alias of this room.

source

pub fn alt_aliases(&self) -> Vec<OwnedRoomAliasId>

Get the canonical alias of this room.

source

pub fn create_content(&self) -> Option<RoomCreateWithCreatorEventContent>

Get the m.room.create content of this room.

This usually isn’t optional but some servers might not send an m.room.create event as the first event for a given room, thus this can be optional.

For room versions earlier than room version 11, if the event is redacted, all fields except creator will be set to their default value.

source

pub async fn is_direct(&self) -> Result<bool, StoreError>

Is this room considered a direct message.

Async because it can read room info from storage.

source

pub fn direct_targets(&self) -> HashSet<OwnedUserId>

If this room is a direct message, get the members that we’re sharing the room with.

Note: The member list might have been modified in the meantime and the targets might not even be in the room anymore. This setting should only be considered as guidance. We leave members in this list to allow us to re-find a DM with a user even if they have left, since we may want to re-invite them.

source

pub fn direct_targets_length(&self) -> usize

If this room is a direct message, returns the number of members that we’re sharing the room with.

source

pub fn is_encrypted(&self) -> bool

Is the room encrypted.

source

pub fn encryption_settings(&self) -> Option<RoomEncryptionEventContent>

Get the m.room.encryption content that enabled end to end encryption in the room.

source

pub fn guest_access(&self) -> GuestAccess

Get the guest access policy of this room.

source

pub fn history_visibility(&self) -> HistoryVisibility

Get the history visibility policy of this room.

source

pub fn is_public(&self) -> bool

Is the room considered to be public.

source

pub fn join_rule(&self) -> JoinRule

Get the join rule policy of this room.

source

pub fn max_power_level(&self) -> i64

Get the maximum power level that this room contains.

This is useful if one wishes to normalize the power levels, e.g. from 0-100 where 100 would be the max power level.

source

pub fn name(&self) -> Option<String>

Get the m.room.name of this room.

The returned string may be empty if the event has been redacted, or it’s missing from storage.

source

pub fn is_tombstoned(&self) -> bool

Has the room been tombstoned.

source

pub fn tombstone(&self) -> Option<RoomTombstoneEventContent>

Get the m.room.tombstone content of this room if there is one.

source

pub fn topic(&self) -> Option<String>

Get the topic of the room.

source

pub fn has_active_room_call(&self) -> bool

Is there a non expired membership with application “m.call” and scope “m.room” in this room

source

pub fn active_room_call_participants(&self) -> Vec<OwnedUserId>

Returns a Vec of userId’s that participate in the room call.

matrix_rtc memberships with application “m.call” and scope “m.room” are considered. A user can occur twice if they join with two devices. convert to a set depending if the different users are required or the amount of sessions.

The vector is ordered by oldest membership user to newest.

source

pub async fn computed_display_name(&self) -> Result<DisplayName, StoreError>

Return the cached display name of the room if it was provided via sync, or otherwise calculate it, taking into account its name, aliases and members.

The display name is calculated according to this algorithm.

source

pub fn latest_event(&self) -> Option<LatestEvent>

Available on crate feature experimental-sliding-sync only.

Return the last event in this room, if one has been cached during sliding sync.

source

pub async fn joined_user_ids(&self) -> Result<Vec<OwnedUserId>, StoreError>

Get the list of users ids that are considered to be joined members of this room.

source

pub async fn members( &self, memberships: RoomMemberships ) -> Result<Vec<RoomMember>, StoreError>

Get the RoomMembers of this room that are known to the store, with the given memberships.

source

pub async fn joined_members(&self) -> Result<Vec<RoomMember>, StoreError>

👎Deprecated: Use members with RoomMemberships::JOIN instead

Get the list of RoomMembers that are considered to be joined members of this room.

source

pub async fn active_members(&self) -> Result<Vec<RoomMember>, StoreError>

👎Deprecated: Use members with RoomMemberships::ACTIVE instead

Get the list of RoomMembers that are considered to be joined or invited members of this room.

source

pub fn active_members_count(&self) -> u64

Returns the number of members who have joined or been invited to the room.

source

pub fn invited_members_count(&self) -> u64

Returns the number of members who have been invited to the room.

source

pub fn joined_members_count(&self) -> u64

Returns the number of members who have joined the room.

source

pub fn subscribe_info(&self) -> Subscriber<RoomInfo>

Subscribe to the inner RoomInfo.

source

pub fn clone_info(&self) -> RoomInfo

Clone the inner RoomInfo.

source

pub fn set_room_info(&self, room_info: RoomInfo, trigger_room_list_update: bool)

Update the summary with given RoomInfo.

This also triggers an update for room info observers if trigger_room_list_update is true.

source

pub async fn get_member( &self, user_id: &UserId ) -> Result<Option<RoomMember>, StoreError>

Get the RoomMember with the given user_id.

Returns None if the member was never part of this room, otherwise return a RoomMember that can be in a joined, invited, left, banned state.

Async because it can read from storage.

source

pub async fn tags( &self ) -> Result<Option<BTreeMap<TagName, TagInfo>>, StoreError>

Get the Tags for this room.

source

pub fn is_favourite(&self) -> bool

Check whether the room is marked as favourite.

A room is considered favourite if it has received the m.favourite tag.

source

pub fn is_low_priority(&self) -> bool

Check whether the room is marked as low priority.

A room is considered low priority if it has received the m.lowpriority tag.

source

pub async fn load_user_receipt( &self, receipt_type: ReceiptType, thread: ReceiptThread, user_id: &UserId ) -> Result<Option<(OwnedEventId, Receipt)>, StoreError>

Get the receipt as an OwnedEventId and Receipt tuple for the given receipt_type, thread and user_id in this room.

source

pub async fn load_event_receipts( &self, receipt_type: ReceiptType, thread: ReceiptThread, event_id: &EventId ) -> Result<Vec<(OwnedUserId, Receipt)>, StoreError>

Load from storage the receipts as a list of OwnedUserId and Receipt tuples for the given receipt_type, thread and event_id in this room.

source

pub fn is_marked_unread(&self) -> bool

Returns a boolean indicating if this room has been manually marked as unread

Trait Implementations§

source§

impl Clone for Room

source§

fn clone(&self) -> Room

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Room

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Deref for Room

§

type Target = Room

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl PaginableRoom for Room

source§

fn event_with_context<'life0, 'life1, 'async_trait>( &'life0 self, event_id: &'life1 EventId, lazy_load_members: bool, num_events: UInt ) -> Pin<Box<dyn Future<Output = Result<EventWithContextResponse, PaginatorError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Runs a /context query for the given room. Read more
source§

fn messages<'life0, 'async_trait>( &'life0 self, opts: MessagesOptions ) -> Pin<Box<dyn Future<Output = Result<Messages, PaginatorError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Runs a /messages query for the given room.
source§

impl EventHandlerContext for Room

This event handler context argument is only applicable to room-specific events.

Trying to use it in the event handler for another event, for example a global account data or presence event, will result in the event handler being skipped and an error getting logged.

Auto Trait Implementations§

§

impl Freeze for Room

§

impl !RefUnwindSafe for Room

§

impl Send for Room

§

impl Sync for Room

§

impl Unpin for Room

§

impl !UnwindSafe for Room

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
source§

impl<T> DynClone for T
where T: Clone,

source§

fn __clone_box(&self, _: Private) -> *mut ()

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> FromRef<T> for T
where T: Clone,

source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
source§

impl<T> FutureExt for T

source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
source§

impl<T, UT> HandleAlloc<UT> for T
where T: Send + Sync,

source§

fn new_handle(value: Arc<T>) -> Handle

Create a new handle for an Arc value Read more
source§

fn clone_handle(handle: Handle) -> Handle

Clone a handle Read more
source§

fn consume_handle(handle: Handle) -> Arc<T>

Consume a handle, getting back the initial Arc<>
source§

fn get_arc(handle: Handle) -> Arc<Self>

Get a clone of the Arc<> using a “borrowed” handle. Read more
source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

source§

const WITNESS: W = W::MAKE

A constant of the type witness
source§

impl<T> Identity for T
where T: ?Sized,

§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> Any for T
where T: Any,

source§

impl<T> AsyncTraitDeps for T

source§

impl<T> CloneAny for T
where T: Any + Clone,

source§

impl<T> CloneAnySend for T
where T: Any + Send + Clone,

source§

impl<T> CloneAnySendSync for T
where T: Any + Send + Sync + Clone,

source§

impl<T> CloneAnySync for T
where T: Any + Sync + Clone,

source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

source§

impl<T> SendOutsideWasm for T
where T: Send,

source§

impl<T> SyncOutsideWasm for T
where T: Sync,