Struct matrix_sdk::Client[][src]

pub struct Client { /* fields omitted */ }
Expand description

An async/await enabled Matrix client.

All of the state is held in an Arc so the Client can be cloned freely.

Implementations

Creates a new client for making HTTP requests to the given homeserver.

Arguments

  • homeserver_url - The homeserver that the client should connect to.

Create a new client with the given configuration.

Arguments

  • homeserver_url - The homeserver that the client should connect to.

  • config - Configuration for the client.

Creates a new client for making HTTP requests to the homeserver of the given user. Follows homeserver discovery directions described here.

Arguments

  • user_id - The id of the user whose homeserver the client should connect to.

Example

let alice = UserId::try_from("@alice:example.org").unwrap();
let client = Client::new_from_user_id(alice.clone()).await.unwrap();
client.login(alice.localpart(), "password", None, None).await.unwrap();

Creates a new client for making HTTP requests to the homeserver of the given user and configuration. Follows homeserver discovery directions described here.

Arguments

  • user_id - The id of the user whose homeserver the client should connect to.

  • config - Configuration for the client.

Change the homeserver URL used by this client.

Arguments

  • homeserver_url - The new URL to use.

Is the client logged in.

The Homeserver of the client.

Get the user id of the current owner of the client.

Get the device id that identifies the current session.

This is supported on encryption only.

Get the public ed25519 key of our own device. This is usually what is called the fingerprint of the device.

Fetches the display name of the owner of the client.

Example

let user = "example";
let client = Client::new(homeserver).unwrap();
client.login(user, "password", None, None).await.unwrap();

if let Some(name) = client.display_name().await.unwrap() {
    println!("Logged in as user '{}' with display name '{}'", user, name);
}

Sets the display name of the owner of the client.

Example

let user = "example";
let client = Client::new(homeserver).unwrap();
client.login(user, "password", None, None).await.unwrap();

client.set_display_name(Some("Alice")).await.expect("Failed setting display name");

Gets the mxc avatar url of the owner of the client, if set.

Example

let client = Client::new(homeserver).unwrap();
client.login(user, "password", None, None).await.unwrap();

if let Some(url) = client.avatar_url().await.unwrap() {
    println!("Your avatar's mxc url is {}", url);
}

Gets the avatar of the owner of the client, 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.

Example

let client = Client::new(homeserver).unwrap();
client.login(user, "password", None, None).await.unwrap();

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

Get a reference to the store.

Sets the mxc avatar url of the client’s owner. The avatar gets unset if url is None.

Upload and set the owning client’s avatar.

The will upload the data produced by the reader to the homeserver’s content repository, and set the user’s avatar to the mxc url for the uploaded file.

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

Example

let path = Path::new("/home/example/selfie.jpg");
let mut image = File::open(&path).unwrap();

client.upload_avatar(&mime::IMAGE_JPEG, &mut image).await.expect("Can't set avatar");

Add EventHandler to Client.

The methods of EventHandler are called when the respective RoomEvents occur.

Get all the rooms the client knows about.

This will return the list of joined, invited, and left rooms.

Returns the joined rooms this client knows about.

Returns the invited rooms this client knows about.

Returns the left rooms this client knows about.

Get a room with the given room id.

Arguments

room_id - The unique id of the room that should be fetched.

Get a joined room with the given room id.

Arguments

room_id - The unique id of the room that should be fetched.

Get an invited room with the given room id.

Arguments

room_id - The unique id of the room that should be fetched.

Get a left room with the given room id.

Arguments

room_id - The unique id of the room that should be fetched.

Gets the homeserver’s supported login types.

This should be the first step when trying to login so you can call the appropriate method for the next step.

Get the URL to use to login via Single Sign-On.

Returns a URL that should be opened in a web browser to let the user login.

After a successful login, the loginToken received at the redirect URL should be used to login with login_with_token.

Arguments

  • redirect_url - The URL that will receive a loginToken after a successful SSO login.

Login to the server.

This can be used for the first login as well as for subsequent logins, note that if the device id isn’t provided a new device will be created.

If this isn’t the first login a device id should be provided to restore the correct stores.

Alternatively the restore_login method can be used to restore a logged in client without the password.

Arguments

  • user - The user that should be logged in to the homeserver.

  • password - The password of the user.

  • device_id - A unique id that will be associated with this session. If not given the homeserver will create one. Can be an existing device_id from a previous login call. Note that this should be done only if the client also holds the encryption keys for this device.

Example

let client = Client::new(homeserver).unwrap();
let user = "example";
let response = client
    .login(user, "wordpass", None, Some("My bot")).await
    .unwrap();

println!("Logged in as {}, got device_id {} and access_token {}",
         user, response.device_id, response.access_token);
This is supported on sso_login and non-WebAssembly only.

Login to the server via Single Sign-On.

This takes care of the whole SSO flow:

  • Spawn a local http server
  • Provide a callback to open the SSO login URL in a web browser
  • Wait for the local http server to get the loginToken
  • Call login_with_token

If cancellation is needed the method should be wrapped in a cancellable task. Note that users with root access to the system have the ability to snoop in on the data/token that is passed to the local HTTP server that will be spawned.

If you need more control over the SSO login process, you should use get_sso_login_url and login_with_token directly.

This should only be used for the first login.

The restore_login method should be used to restore a logged in client after the first login.

A device id should be provided to restore the correct stores, if the device id isn’t provided a new device will be created.

Arguments

  • use_sso_login_url - A callback that will receive the SSO Login URL. It should usually be used to open the SSO URL in a browser and must return Ok(()) if the URL was successfully opened. If it returns Err, the error will be forwarded.

  • server_url - The local URL the server is going to try to bind to, e.g. http://localhost:3030. If None, the server will try to open a random port on localhost.

  • server_response - The text that will be shown on the webpage at the end of the login process. This can be an HTML page. If None, a default text will be displayed.

  • device_id - A unique id that will be associated with this session. If not given the homeserver will create one. Can be an existing device_id from a previous login call. Note that this should be provided only if the client also holds the encryption keys for this device.

  • initial_device_display_name - A public display name that will be associated with the device_id. Only necessary the first time you login with this device_id. It can be changed later.

Example

let client = Client::new(homeserver).unwrap();

let response = client
    .login_with_sso(
        |sso_url| async move {
            // Open sso_url
            Ok(())
        },
        None,
        None,
        None,
        Some("My app")
    )
    .await
    .unwrap();

println!("Logged in as {}, got device_id {} and access_token {}",
         response.user_id, response.device_id, response.access_token);

Login to the server with a token.

This token is usually received in the SSO flow after following the URL provided by get_sso_login_url, note that this is not the access token of a session.

This should only be used for the first login.

The restore_login method should be used to restore a logged in client after the first login.

A device id should be provided to restore the correct stores, if the device id isn’t provided a new device will be created.

Arguments

  • token - A login token.

  • device_id - A unique id that will be associated with this session. If not given the homeserver will create one. Can be an existing device_id from a previous login call. Note that this should be provided only if the client also holds the encryption keys for this device.

  • initial_device_display_name - A public display name that will be associated with the device_id. Only necessary the first time you login with this device_id. It can be changed later.

Example

let client = Client::new(homeserver).unwrap();
let sso_url = client.get_sso_login_url(redirect_url);

// Let the user authenticate at the SSO URL
// Receive the loginToken param at redirect_url

let response = client
    .login_with_token(login_token, None, Some("My app")).await
    .unwrap();

println!("Logged in as {}, got device_id {} and access_token {}",
         response.user_id, response.device_id, response.access_token);

Restore a previously logged in session.

This can be used to restore the client to a logged in state, loading all the stored state and encryption keys.

Alternatively, if the whole session isn’t stored the login method can be used with a device id.

Arguments

  • session - A session that the user already has from a previous login call.

Register a user to the server.

Arguments

  • registration - The easiest way to create this request is using the register::Request itself.

Examples


let request = assign!(RegistrationRequest::new(), {
    username: Some("user"),
    password: Some("password"),
    auth: Some(AuthData::FallbackAcknowledgement { session: "foobar" }),
});
let client = Client::new(homeserver).unwrap();
client.register(request).await;

Get or upload a sync filter.

This method will either get a filter ID from the store or upload the filter definition to the homeserver and return the new filter ID.

Arguments

  • filter_name - The unique name of the filter, this name will be used locally to store and identify the filter ID returned by the server.

  • definition - The filter definition that should be uploaded to the server if no filter ID can be found in the store.

Examples

let mut filter = FilterDefinition::default();
let mut room_filter = RoomFilter::default();
let mut event_filter = RoomEventFilter::default();

// Let's enable member lazy loading.
event_filter.lazy_load_options = LazyLoadOptions::Enabled {
    include_redundant_members: false,
};
room_filter.state = event_filter;
filter.room = room_filter;

let filter_id = client
    .get_or_upload_filter("sync", filter)
    .await
    .unwrap();

let sync_settings = SyncSettings::new()
    .filter(Filter::FilterId(&filter_id));

let response = client.sync_once(sync_settings).await.unwrap();

Join a room by RoomId.

Returns a join_room_by_id::Response consisting of the joined rooms RoomId.

Arguments

  • room_id - The RoomId of the room to be joined.

Join a room by RoomId.

Returns a join_room_by_id_or_alias::Response consisting of the joined rooms RoomId.

Arguments

  • alias - The RoomId or RoomAliasId of the room to be joined. An alias looks like #name:example.com.

Search the homeserver’s directory of public rooms.

Sends a request to “_matrix/client/r0/publicRooms”, returns a get_public_rooms::Response.

Arguments

  • limit - The number of PublicRoomsChunks in each response.

  • since - Pagination token from a previous request.

  • server - The name of the server, if None the requested server is used.

Examples

use matrix_sdk::Client;

let mut client = Client::new(homeserver).unwrap();

client.public_rooms(limit, since, server).await;

Create a room using the RoomBuilder and send the request.

Sends a request to /_matrix/client/r0/createRoom, returns a create_room::Response, this is an empty response.

Arguments

  • room - The easiest way to create this request is using the create_room::Request itself.

Examples

use matrix_sdk::Client;

let request = CreateRoomRequest::new();
let client = Client::new(homeserver).unwrap();
assert!(client.create_room(request).await.is_ok());

Search the homeserver’s directory of public rooms with a filter.

Sends a request to “_matrix/client/r0/publicRooms”, returns a get_public_rooms_filtered::Response.

Arguments

  • room_search - The easiest way to create this request is using the get_public_rooms_filtered::Request itself.

Examples

let mut client = Client::new(homeserver).unwrap();

let generic_search_term = Some("matrix-rust-sdk");
let filter = assign!(Filter::new(), { generic_search_term });
let request = assign!(PublicRoomsFilterRequest::new(), { filter });

client.public_rooms_filtered(request).await;

Upload some media to the server.

Arguments

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

Examples

let path = PathBuf::from("/home/example/my-cat.jpg");
let mut image = File::open(path).unwrap();

let response = client
    .upload(&mime::IMAGE_JPEG, &mut image)
    .await
    .expect("Can't upload my cat.");

println!("Cat URI: {}", response.content_uri);

Send a room message to a room.

Returns the parsed response from the server.

If the encryption feature is enabled this method will transparently encrypt the room message if this room is encrypted.

Note: This method will send an unencrypted message if the room cannot be found in the store, prefer the higher level send() method that can be found for the Joined room struct to avoid this.

Arguments

  • room_id - The unique id of the room.

  • content - The content of the message event.

  • txn_id - A unique Uuid that can be attached to a MessageEvent held in its unsigned field as transaction_id. If not given one is created for the message.

Example

use matrix_sdk::events::{
    AnyMessageEventContent,
    room::message::{MessageEventContent, TextMessageEventContent},
};
use matrix_sdk_common::uuid::Uuid;

let content = AnyMessageEventContent::RoomMessage(
    MessageEventContent::text_plain("Hello world")
);

let txn_id = Uuid::new_v4();
client.room_send(&room_id, content, Some(txn_id)).await.unwrap();

Send an arbitrary request to the server, without updating client state.

Warning: Because this method does not update the client state, it is important to make sure than you account for this yourself, and use wrapper methods where available. This method should only be used if a wrapper method for the endpoint you’d like to use is not available.

Arguments

  • request - A filled out and valid request for the endpoint to be hit

  • timeout - An optional request timeout setting, this overrides the default request setting if one was set.

Example

use matrix_sdk::api::r0::profile;
use matrix_sdk::identifiers::user_id;

// First construct the request you want to make
// See https://docs.rs/ruma-client-api/latest/ruma_client_api/index.html
// for all available Endpoints
let user_id = user_id!("@example:localhost");
let request = profile::get_profile::Request::new(&user_id);

// Start the request using Client::send()
let response = client.send(request, None).await.unwrap();

// Check the corresponding Response struct to find out what types are
// returned

Get information of all our own devices.

Examples

let response = client.devices().await.expect("Can't get devices from server");

for device in response.devices {
    println!(
        "Device: {} {}",
        device.device_id,
        device.display_name.as_deref().unwrap_or("")
    );
}

Delete the given devices from the server.

Arguments

  • devices - The list of devices that should be deleted from the server.

  • auth_data - This request requires user interactive auth, 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.

let devices = &["DEVICEID".into()];

if let Err(e) = client.delete_devices(devices, None).await {
    if let Some(info) = e.uiaa_response() {
        let mut auth_parameters = BTreeMap::new();

        let identifier = json!({
            "type": "m.id.user",
            "user": "example",
        });
        auth_parameters.insert("identifier".to_owned(), identifier);
        auth_parameters.insert("password".to_owned(), "wordpass".into());

        let auth_data = AuthData::DirectRequest {
            kind: "m.login.password",
            auth_parameters,
            session: info.session.as_deref(),
        };

        client
            .delete_devices(devices, Some(auth_data))
            .await
            .expect("Can't delete devices");
    }
}

Synchronize the client’s state with the latest state on the server.

Note: You should not use this method to repeatedly sync if encryption support is enabled, the sync method will make additional requests between syncs that are needed for E2E encryption to work.

Arguments

  • sync_settings - Settings for the sync call.

Repeatedly call sync to synchronize the client state with the server.

This method will never return, if cancellation is needed the method should be wrapped in a cancelable task or the sync_with_callback method can be used.

Arguments

  • sync_settings - Settings for the sync call. Note that those settings will be only used for the first sync call.

Repeatedly call sync to synchronize the client state with the server.

Arguments

  • sync_settings - Settings for the sync call. Note that those settings will be only used for the first sync call.

  • callback - A callback that will be called every time a successful response has been fetched from the server. The callback must return a boolean which signalizes if the method should stop syncing. If the callback returns LoopCtrl::Continue the sync will continue, if the callback returns LoopCtrl::Break the sync will be stopped.

Examples

The following example demonstrates how to sync forever while sending all the interesting events through a mpsc channel to another thread e.g. a UI thread.


use tokio::sync::mpsc::channel;

let (tx, rx) = channel(100);

let sync_channel = &tx;
let sync_settings = SyncSettings::new()
    .timeout(Duration::from_secs(30));

client
    .sync_with_callback(sync_settings, |response| async move {
        let channel = sync_channel;

        for (room_id, room) in response.rooms.join {
            for event in room.timeline.events {
                channel.send(event).await.unwrap();
            }
        }

        LoopCtrl::Continue
    })
    .await;
})

Get the current, if any, sync token of the client. This will be None if the client didn’t sync at least once.

This is supported on encryption only.

Get a verification object with the given flow id.

This is supported on encryption only.

Get a VerificationRequest object for the given user with the given flow id.

This is supported on encryption only.

Get a specific device of a user.

Arguments

  • user_id - The unique id of the user that the device belongs to.

  • device_id - The unique id of the device.

Returns a Device if one is found and the crypto store didn’t throw an error.

This will always return None if the client hasn’t been logged in.

Example

let device = client.get_device(&alice, "DEVICEID".into())
    .await
    .unwrap()
    .unwrap();

println!("{:?}", device.is_trusted());

let verification = device.start_verification().await.unwrap();
This is supported on encryption only.

Create and upload a new cross signing identity.

Arguments

  • auth_data - This request requires user interactive auth, 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


fn auth_data<'a>(user: &UserId, password: &str, session: Option<&'a str>) -> AuthData<'a> {
    let mut auth_parameters = BTreeMap::new();
    let identifier = json!({
        "type": "m.id.user",
        "user": user,
    });
    auth_parameters.insert("identifier".to_owned(), identifier);
    auth_parameters.insert("password".to_owned(), password.to_owned().into());

    AuthData::DirectRequest {
        kind: "m.login.password",
        auth_parameters,
        session,
    }
}

if let Err(e) = client.bootstrap_cross_signing(None).await {
    if let Some(response) = e.uiaa_response() {
        let auth_data = auth_data(&user_id, "wordpass", response.session.as_deref());
           client
               .bootstrap_cross_signing(Some(auth_data))
               .await
               .expect("Couldn't bootstrap cross signing")
    } else {
        panic!("Error durign cross signing bootstrap {:#?}", e);
    }
}
This is supported on encryption only.

Get a map holding all the devices of an user.

This will always return an empty map if the client hasn’t been logged in.

Arguments

  • user_id - The unique id of the user that the devices belong to.

Example

let devices = client.get_user_devices(&alice).await.unwrap();

for device in devices.devices() {
    println!("{:?}", device);
}
This is supported on encryption and non-WebAssembly only.

Export E2EE keys that match the given predicate encrypting them with the given passphrase.

Arguments

  • path - The file path where the exported key file will be saved.

  • passphrase - The passphrase that will be used to encrypt the exported room keys.

  • predicate - A closure that will be called for every known InboundGroupSession, which represents a room key. If the closure returns true the InboundGroupSessoin will be included in the export, if the closure returns false it will not be included.

Panics

This method will panic if it isn’t run on a Tokio runtime.

This method will panic if it can’t get enough randomness from the OS to encrypt the exported keys securely.

Examples

let path = PathBuf::from("/home/example/e2e-keys.txt");
// Export all room keys.
client
    .export_keys(path, "secret-passphrase", |_| true)
    .await
    .expect("Can't export keys.");

// Export only the room keys for a certain room.
let path = PathBuf::from("/home/example/e2e-room-keys.txt");
let room_id = room_id!("!test:localhost");

client
    .export_keys(path, "secret-passphrase", |s| s.room_id() == &room_id)
    .await
    .expect("Can't export keys.");
This is supported on encryption and non-WebAssembly only.

Import E2EE keys from the given file path.

Arguments

  • path - The file path where the exported key file will can be found.

  • passphrase - The passphrase that should be used to decrypt the exported room keys.

Returns a tuple of numbers that represent the number of sessions that were imported and the total number of sessions that were found in the key export.

Panics

This method will panic if it isn’t run on a Tokio runtime.

let path = PathBuf::from("/home/example/e2e-keys.txt");
client
    .import_keys(path, "secret-passphrase")
    .await
    .expect("Can't import keys");

Get a media file’s content.

If the content is encrypted and encryption is enabled, the content will be decrypted.

Arguments

  • request - The MediaRequest of the content.

  • use_cache - If we should use the media cache for this request.

Remove a media file’s content from the store.

Arguments

  • request - The MediaRequest of the content.

Delete all the media content corresponding to the given uri from the store.

Arguments

  • uri - The MxcUri of the files.

Get the file of the given media event content.

If the content is encrypted and encryption is enabled, the content will be decrypted.

Returns Ok(None) if the event content has no file.

This is a convenience method that calls the get_media_content method.

Arguments

  • event_content - The media event content.

  • use_cache - If we should use the media cache for this file.

Remove the file of the given media event content from the cache.

This is a convenience method that calls the remove_media_content method.

Arguments

  • event_content - The media event content.

Get a thumbnail of the given media event content.

If the content is encrypted and encryption is enabled, the content will be decrypted.

Returns Ok(None) if the event content has no thumbnail.

This is a convenience method that calls the get_media_content method.

Arguments

  • event_content - The media event content.

  • size - The desired size of the thumbnail. The actual thumbnail may not match the size specified.

  • use_cache - If we should use the media cache for this thumbnail.

Remove the thumbnail of the given media event content from the cache.

This is a convenience method that calls the remove_media_content method.

Arguments

  • event_content - The media event content.

  • size - The desired size of the thumbnail. Must match the size requested with get_thumbnail.

Gets information about the owner of a given access token.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

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

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

Performs the conversion.

The alignment of pointer.

The type for initializers.

Initializes a with the given initializer. Read more

Dereferences the given pointer. Read more

Mutably dereferences the given pointer. Read more

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

Should always be Self

The resulting type after obtaining ownership.

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

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

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

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.