matrix_sdk

Struct Account

Source
pub struct Account { /* private fields */ }
Expand description

A high-level API to manage the client owner’s account.

All the methods on this struct send a request to the homeserver.

Implementations§

Source§

impl Account

Source

pub async fn get_display_name(&self) -> Result<Option<String>>

Get the display name of the account.

§Examples
let user = "example";
let client = Client::new(homeserver).await?;
client.matrix_auth().login_username(user, "password").send().await?;

if let Some(name) = client.account().get_display_name().await? {
    println!("Logged in as user '{user}' with display name '{name}'");
}
Source

pub async fn set_display_name(&self, name: Option<&str>) -> Result<()>

Set the display name of the account.

§Examples
let user = "example";
let client = Client::new(homeserver).await?;
client.matrix_auth().login_username(user, "password").send().await?;

client.account().set_display_name(Some("Alice")).await?;
Source

pub async fn get_avatar_url(&self) -> Result<Option<OwnedMxcUri>>

Get the MXC URI of the account’s avatar, if set.

This always sends a request to the server to retrieve this information. If successful, this fills the cache, and makes it so that Self::get_cached_avatar_url will always return something.

§Examples
let client = Client::new(homeserver).await?;
client.matrix_auth().login_username(user, "password").send().await?;

if let Some(url) = client.account().get_avatar_url().await? {
    println!("Your avatar's mxc url is {url}");
}
Source

pub async fn get_cached_avatar_url(&self) -> Result<Option<OwnedMxcUri>>

Get the URL of the account’s avatar, if is stored in cache.

Source

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

Set the MXC URI of the account’s avatar.

The avatar is unset if url is None.

Source

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

Get the account’s avatar, 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?;
client.matrix_auth().login_username(user, "password").send().await?;

if let Some(avatar) = client.account().get_avatar(MediaFormat::File).await?
{
    std::fs::write("avatar.png", avatar);
}
Source

pub async fn upload_avatar( &self, content_type: &Mime, data: Vec<u8>, ) -> Result<OwnedMxcUri>

Upload and set the account’s avatar.

This will upload the data produced by the reader to the homeserver’s content repository, and set the user’s avatar to the MXC URI for the uploaded file.

This is a convenience method for calling Media::upload(), followed by Account::set_avatar_url().

Returns the MXC URI of the uploaded avatar.

§Examples
let image = fs::read("/home/example/selfie.jpg")?;

client.account().upload_avatar(&mime::IMAGE_JPEG, image).await?;
Source

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

Get the profile of the account.

Allows to get both the display name and avatar URL in a single call.

§Examples
let profile = client.account().fetch_user_profile().await?;
println!(
    "You are '{:?}' with avatar '{:?}'",
    profile.displayname, profile.avatar_url
);
Source

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

Get the profile for a given user id

§Arguments
  • user_id the matrix id this function downloads the profile for
Source

pub async fn change_password( &self, new_password: &str, auth_data: Option<AuthData>, ) -> Result<Response>

Change the password of the account.

§Arguments
  • new_password - The new password to set.

  • auth_data - This request uses the User-Interactive Authentication API. The first request needs to set this to None and will always fail with an UiaaResponse. The response will contain information for the interactive auth and the same request needs to be made but this time with some auth_data provided.

§Returns

This method might return an ErrorKind::WeakPassword error if the new password is considered insecure by the homeserver, with details about the strength requirements in the error’s message.

§Examples
client.account().change_password(
    "myverysecretpassword",
    Some(AuthData::Dummy(Dummy::new())),
).await?;
Source

pub async fn deactivate( &self, id_server: Option<&str>, auth_data: Option<AuthData>, erase_data: bool, ) -> Result<Response>

Deactivate this account definitively.

§Arguments
  • id_server - The identity server from which to unbind the user’s Third Party Identifiers.

  • auth_data - This request uses the User-Interactive Authentication API. The first request needs to set this to None and will always fail with an UiaaResponse. The response will contain information for the interactive auth and the same request needs to be made but this time with some auth_data provided.

  • erase - Whether the user would like their content to be erased as much as possible from the server.

§Examples
let response = account.deactivate(None, None, false).await;

// Proceed with UIAA.
Source

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

Get the registered Third Party Identifiers on the homeserver of the account.

These 3PIDs may be used by the homeserver to authenticate the user during sensitive operations.

§Examples
let threepids = client.account().get_3pids().await?.threepids;

for threepid in threepids {
    println!(
        "Found 3PID '{}' of type '{}'",
        threepid.address, threepid.medium
    );
}
Source

pub async fn request_3pid_email_token( &self, client_secret: &ClientSecret, email: &str, send_attempt: UInt, ) -> Result<Response>

Request a token to validate an email address as a Third Party Identifier.

This is the first step in registering an email address as 3PID. Next, call Account::add_3pid() with the same client_secret and the returned sid.

§Arguments
  • client_secret - A client-generated secret string used to protect this session.

  • email - The email address to validate.

  • send_attempt - The attempt number. This number needs to be incremented if you want to request another token for the same validation.

§Returns
  • sid - The session ID to be used in following requests for this 3PID.

  • submit_url - If present, the user will submit the token to the client, that must send it to this URL. If not, the client will not be involved in the token submission.

This method might return an ErrorKind::ThreepidInUse error if the email address is already registered for this account or another, or an ErrorKind::ThreepidDenied error if it is denied.

§Examples
let token_response = account
    .request_3pid_email_token(&secret, "john@matrix.org", uint!(0))
    .await?;

// Wait for the user to confirm that the token was submitted or prompt
// the user for the token and send it to submit_url.

let uiaa_response =
    account.add_3pid(&secret, &token_response.sid, None).await;

// Proceed with UIAA.
Source

pub async fn request_3pid_msisdn_token( &self, client_secret: &ClientSecret, country: &str, phone_number: &str, send_attempt: UInt, ) -> Result<Response>

Request a token to validate a phone number as a Third Party Identifier.

This is the first step in registering a phone number as 3PID. Next, call Account::add_3pid() with the same client_secret and the returned sid.

§Arguments
  • client_secret - A client-generated secret string used to protect this session.

  • country - The two-letter uppercase ISO-3166-1 alpha-2 country code that the number in phone_number should be parsed as if it were dialled from.

  • phone_number - The phone number to validate.

  • send_attempt - The attempt number. This number needs to be incremented if you want to request another token for the same validation.

§Returns
  • sid - The session ID to be used in following requests for this 3PID.

  • submit_url - If present, the user will submit the token to the client, that must send it to this URL. If not, the client will not be involved in the token submission.

This method might return an ErrorKind::ThreepidInUse error if the phone number is already registered for this account or another, or an ErrorKind::ThreepidDenied error if it is denied.

§Examples
let token_response = account
    .request_3pid_msisdn_token(&secret, "FR", "0123456789", uint!(0))
    .await?;

// Wait for the user to confirm that the token was submitted or prompt
// the user for the token and send it to submit_url.

let uiaa_response =
    account.add_3pid(&secret, &token_response.sid, None).await;

// Proceed with UIAA.
Source

pub async fn add_3pid( &self, client_secret: &ClientSecret, sid: &SessionId, auth_data: Option<AuthData>, ) -> Result<Response>

Add a Third Party Identifier on the homeserver for this account.

This 3PID may be used by the homeserver to authenticate the user during sensitive operations.

This method should be called after Account::request_3pid_email_token() or Account::request_3pid_msisdn_token() to complete the 3PID

§Arguments
Source

pub async fn delete_3pid( &self, address: &str, medium: Medium, id_server: Option<&str>, ) -> Result<Response>

Delete a Third Party Identifier from the homeserver for this account.

§Arguments
  • address - The 3PID being removed.

  • medium - The type of the 3PID.

  • id_server - The identity server to unbind from. If not provided, the homeserver should unbind the 3PID from the identity server it was bound to previously.

§Returns
§Examples
match account
    .delete_3pid("paul@matrix.org", Medium::Email, None)
    .await?
    .id_server_unbind_result
{
    ThirdPartyIdRemovalStatus::Success => {
        println!("3PID unbound from the Identity Server");
    }
    _ => println!("Could not unbind 3PID from the Identity Server"),
}
Source

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

Get the content of an account data event of statically-known type.

§Examples
use matrix_sdk::ruma::events::ignored_user_list::IgnoredUserListEventContent;

let maybe_content = account.account_data::<IgnoredUserListEventContent>().await?;
if let Some(raw_content) = maybe_content {
    let content = raw_content.deserialize()?;
    println!("Ignored users:");
    for user_id in content.ignored_users.keys() {
        println!("- {user_id}");
    }
}
Source

pub async fn account_data_raw( &self, event_type: GlobalAccountDataEventType, ) -> Result<Option<Raw<AnyGlobalAccountDataEventContent>>>

Get the content of an account data event of a given type.

Source

pub async fn fetch_account_data( &self, event_type: GlobalAccountDataEventType, ) -> Result<Option<Raw<AnyGlobalAccountDataEventContent>>>

Fetch a global account data event from the server.

The content from the response will not be persisted in the store.

Examples

use matrix_sdk::ruma::events::{ignored_user_list::IgnoredUserListEventContent, GlobalAccountDataEventType};

if let Some(raw_content) = account.fetch_account_data(GlobalAccountDataEventType::IgnoredUserList).await? {
    let content = raw_content.deserialize_as::<IgnoredUserListEventContent>()?;

    println!("Ignored users:");

    for user_id in content.ignored_users.keys() {
        println!("- {user_id}");
    }
}
Source

pub async fn set_account_data<T>(&self, content: T) -> Result<Response>

Set the given account data event.

§Examples
use matrix_sdk::ruma::{
    events::ignored_user_list::{IgnoredUser, IgnoredUserListEventContent},
    user_id,
};

let mut content = account
    .account_data::<IgnoredUserListEventContent>()
    .await?
    .map(|c| c.deserialize())
    .transpose()?
    .unwrap_or_default();
content
    .ignored_users
    .insert(user_id!("@foo:bar.com").to_owned(), IgnoredUser::new());
account.set_account_data(content).await?;
Source

pub async fn set_account_data_raw( &self, event_type: GlobalAccountDataEventType, content: Raw<AnyGlobalAccountDataEventContent>, ) -> Result<Response>

Set the given raw account data event.

Source

pub async fn mark_as_dm( &self, room_id: &RoomId, user_ids: &[OwnedUserId], ) -> Result<()>

Marks the room identified by room_id as a “direct chat” with each user in user_ids.

§Arguments
  • room_id - The room ID of the direct message room.
  • user_ids - The user IDs to be associated with this direct message room.
Source

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

Adds the given user ID to the account’s ignore list.

Source

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

Removes the given user ID from the account’s ignore list.

Source

pub async fn push_rules(&self) -> Result<Ruleset>

Get the current push rules from storage.

If no push rules event was found, or it fails to deserialize, a ruleset with the server-default push rules is returned.

Panics if called when the client is not logged in.

Source

pub async fn get_recently_visited_rooms(&self) -> Result<Vec<OwnedRoomId>>

Retrieves the user’s recently visited room list

Source

pub async fn track_recently_visited_room( &self, room_id: OwnedRoomId, ) -> Result<(), Error>

Moves/inserts the given room to the front of the recently visited list

Trait Implementations§

Source§

impl Clone for Account

Source§

fn clone(&self) -> Account

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 Account

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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
Source§

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

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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,

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§

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§

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> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

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>,

Source§

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>,

Source§

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<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T

Source§

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

Source§

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