Struct matrix_sdk::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.

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

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> ) -> 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.

§Examples
let response = account.deactivate(None, None).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.

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

Retrieves the user’s recently visited room list

source

pub async fn track_recently_visited_room( &self, room_id: String ) -> 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
§

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.

§

impl<T> FutureExt for T

§

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

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

fn with_current_context(self) -> WithContext<Self>

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

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

§

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

Create a new handle for an Arc value Read more
§

fn clone_handle(handle: Handle) -> Handle

Clone a handle Read more
§

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

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

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

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

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

§

const WITNESS: W = W::MAKE

A constant of the type witness
§

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>).
§

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.

§

impl<T> IntoResult<T> for T

§

type Err = Infallible

§

fn into_result(self) -> Result<T, <T as IntoResult<T>>::Err>

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

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

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

§

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> SendOutsideWasm for T
where T: Send,

source§

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