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();
pub async fn new_from_user_id_with_config(
user_id: UserId,
config: ClientConfig
) -> Result<Self>
pub async fn new_from_user_id_with_config(
user_id: UserId,
config: ClientConfig
) -> Result<Self>
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.
encryption
only.Get the public ed25519 key of our own device. This is usually what is called the fingerprint of the device.
This is supported on encryption
only.
encryption
only.Get all the tracked users we know about
Tracked users are users for which we keep the device list of E2EE capable devices up to date.
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);
}
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");
pub async fn register_event_handler<Ev, Ctx, H>(&self, handler: H) -> &Self where
Ev: SyncEvent + DeserializeOwned + Send + 'static,
H: EventHandler<Ev, Ctx>,
<H::Future as Future>::Output: EventHandlerResult,
pub async fn register_event_handler<Ev, Ctx, H>(&self, handler: H) -> &Self where
Ev: SyncEvent + DeserializeOwned + Send + 'static,
H: EventHandler<Ev, Ctx>,
<H::Future as Future>::Output: EventHandlerResult,
Register a handler for a specific event type.
The handler is a function or closure with one or more arguments. The
first argument is the event itself. All additional arguments are
“context” arguments: They have to implement EventHandlerContext
.
This trait is named that way because most of the types implementing it
give additional context about an event: The room it was in, its raw form
and other similar things. As an exception to this,
Client
also implements the EventHandlerContext
trait
so you don’t have to clone your client into the event handler manually.
Some context arguments are not universally applicable. A context argument that isn’t available for the given event type will result in the event handler being skipped and an error being logged. The following context argument types are only available for a subset of event types:
Room
is only available for room-specific events, i.e. not for events like global account data events or presence events
Examples
use matrix_sdk::{
deserialized_responses::EncryptionInfo,
room::Room,
ruma::{
events::{
macros::EventContent,
push_rules::PushRulesEvent,
room::{message::MessageEventContent, topic::TopicEventContent},
SyncMessageEvent, SyncStateEvent,
},
Int, MilliSecondsSinceUnixEpoch,
},
Client,
};
use serde::{Deserialize, Serialize};
client
.register_event_handler(
|ev: SyncMessageEvent<MessageEventContent>,
room: Room,
client: Client| async move {
// Common usage: Room event plus room and client.
},
)
.await
.register_event_handler(
|ev: SyncMessageEvent<MessageEventContent>,
room: Room,
encryption_info: Option<EncryptionInfo>| async move {
// An `Option<EncryptionInfo>` parameter lets you distinguish between
// unencrypted events and events that were decrypted by the SDK.
},
)
.await
.register_event_handler(
|ev: SyncStateEvent<TopicEventContent>| async move {
// You can omit any or all arguments after the first.
}
)
.await;
// Custom events work exactly the same way, you just need to declare
// the content struct and use the EventContent derive macro on it.
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[ruma_event(type = "org.shiny_new_2fa.token", kind = Message)]
struct TokenEventContent {
token: String,
#[serde(rename = "exp")]
expires_at: MilliSecondsSinceUnixEpoch,
}
client.register_event_handler(
|ev: SyncMessageEvent<TokenEventContent>, room: Room| async move {
todo!("Display the token");
},
).await;
// Adding your custom data to the handler can be done as well
let data = "MyCustomIdentifier".to_string();
client.register_event_handler({
let data = data.clone();
move |ev: SyncMessageEvent<MessageEventContent> | {
let data = data.clone();
async move {
println!("Calling the handler with identifier {}", data);
}
}
}).await;
Register a handler for a notification.
Similar to .register_event_handler
, but only allows functions or
closures with exactly the three arguments Notification
, room::Room
,
Client
for now.
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 aloginToken
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);
pub async fn login_with_sso<C>(
&self,
use_sso_login_url: impl Fn(String) -> C,
server_url: Option<&str>,
server_response: Option<&str>,
device_id: Option<&str>,
initial_device_display_name: Option<&str>
) -> Result<Response> where
C: Future<Output = Result<()>>,
This is supported on sso_login
and non-WebAssembly only.
pub async fn login_with_sso<C>(
&self,
use_sso_login_url: impl Fn(String) -> C,
server_url: Option<&str>,
server_response: Option<&str>,
device_id: Option<&str>,
initial_device_display_name: Option<&str>
) -> Result<Response> where
C: Future<Output = Result<()>>,
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 returnOk(())
if the URL was successfully opened. If it returnsErr
, the error will be forwarded. -
server_url
- The local URL the server is going to try to bind to, e.g.http://localhost:3030
. IfNone
, 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. IfNone
, 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 theregister::Request
itself.
Examples
let request = assign!(RegistrationRequest::new(), {
username: Some("user"),
password: Some("password"),
auth: Some(uiaa::AuthData::FallbackAcknowledgement(
uiaa::FallbackAcknowledgement::new("foobar"),
)),
});
let client = Client::new(homeserver).unwrap();
client.register(request).await;
pub async fn get_or_upload_filter(
&self,
filter_name: &str,
definition: FilterDefinition<'_>
) -> Result<String>
pub async fn get_or_upload_filter(
&self,
filter_name: &str,
definition: FilterDefinition<'_>
) -> Result<String>
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
- TheRoomId
of the room to be joined.
pub async fn join_room_by_id_or_alias(
&self,
alias: &RoomIdOrAliasId,
server_names: &[Box<ServerName>]
) -> HttpResult<Response>
pub async fn join_room_by_id_or_alias(
&self,
alias: &RoomIdOrAliasId,
server_names: &[Box<ServerName>]
) -> HttpResult<Response>
Join a room by RoomId
.
Returns a join_room_by_id_or_alias::Response
consisting of the
joined rooms RoomId
.
Arguments
alias
- TheRoomId
orRoomAliasId
of the room to be joined. An alias looks like#name:example.com
.
pub async fn public_rooms(
&self,
limit: Option<u32>,
since: Option<&str>,
server: Option<&ServerName>
) -> HttpResult<Response>
pub async fn public_rooms(
&self,
limit: Option<u32>,
since: Option<&str>,
server: Option<&ServerName>
) -> HttpResult<Response>
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 ofPublicRoomsChunk
s in each response. -
since
- Pagination token from a previous request. -
server
- The name of the server, ifNone
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 thecreate_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());
pub async fn public_rooms_filtered(
&self,
room_search: impl Into<Request<'_>>
) -> HttpResult<Response>
pub async fn public_rooms_filtered(
&self,
room_search: impl Into<Request<'_>>
) -> HttpResult<Response>
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 theget_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
- AReader
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 uniqueUuid
that can be attached to aMessageEvent
held in its unsigned field astransaction_id
. If not given one is created for the message.
Example
use matrix_sdk::ruma::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();
pub async fn send<Request>(
&self,
request: Request,
config: Option<RequestConfig>
) -> HttpResult<Request::IncomingResponse> where
Request: OutgoingRequest + Debug,
HttpError: From<FromHttpResponseError<Request::EndpointError>>,
pub async fn send<Request>(
&self,
request: Request,
config: Option<RequestConfig>
) -> HttpResult<Request::IncomingResponse> where
Request: OutgoingRequest + Debug,
HttpError: From<FromHttpResponseError<Request::EndpointError>>,
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::ruma::{api::client::r0::profile, 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("")
);
}
pub async fn delete_devices(
&self,
devices: &[DeviceIdBox],
auth_data: Option<AuthData<'_>>
) -> HttpResult<Response>
pub async fn delete_devices(
&self,
devices: &[DeviceIdBox],
auth_data: Option<AuthData<'_>>
) -> HttpResult<Response>
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 toNone
and will always fail with anUiaaResponse
. The response will contain information for the interactive auth and the same request needs to be made but this time with someauth_data
provided.
let devices = &["DEVICEID".into()];
if let Err(e) = client.delete_devices(devices, None).await {
if let Some(info) = e.uiaa_response() {
let auth_data = uiaa::AuthData::Password(assign!(
uiaa::Password::new(uiaa::UserIdentifier::MatrixId("example"), "wordpass"),
{ 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.
pub async fn sync_with_callback<C>(
&self,
sync_settings: SyncSettings<'_>,
callback: impl Fn(SyncResponse) -> C
) where
C: Future<Output = LoopCtrl>,
pub async fn sync_with_callback<C>(
&self,
sync_settings: SyncSettings<'_>,
callback: impl Fn(SyncResponse) -> C
) where
C: Future<Output = LoopCtrl>,
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 returnsLoopCtrl::Continue
the sync will continue, if the callback returnsLoopCtrl::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.
encryption
only.Get a verification object with the given flow id.
pub async fn get_verification_request(
&self,
user_id: &UserId,
flow_id: impl AsRef<str>
) -> Option<VerificationRequest>
This is supported on encryption
only.
pub async fn get_verification_request(
&self,
user_id: &UserId,
flow_id: impl AsRef<str>
) -> Option<VerificationRequest>
encryption
only.Get a VerificationRequest
object for the given user with the given
flow id.
pub async fn get_device(
&self,
user_id: &UserId,
device_id: &DeviceId
) -> StdResult<Option<Device>, CryptoStoreError>
This is supported on encryption
only.
pub async fn get_device(
&self,
user_id: &UserId,
device_id: &DeviceId
) -> StdResult<Option<Device>, CryptoStoreError>
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.verified());
let verification = device.request_verification().await.unwrap();
pub async fn get_user_identity(
&self,
user_id: &UserId
) -> StdResult<Option<UserIdentity>, CryptoStoreError>
This is supported on encryption
only.
pub async fn get_user_identity(
&self,
user_id: &UserId
) -> StdResult<Option<UserIdentity>, CryptoStoreError>
encryption
only.Get a E2EE identity of an user.
Arguments
user_id
- The unique id of the user that the identity belongs to.
Returns a UserIdentity
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 user = client.get_user_identity(&alice).await?;
if let Some(user) = user {
println!("{:?}", user.verified());
let verification = user.request_verification().await?;
}
This is supported on encryption
only.
encryption
only.Get the status of the private cross signing keys.
This can be used to check which private cross signing keys we have stored locally.
This is supported on encryption
only.
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 toNone
and will always fail with anUiaaResponse
. The response will contain information for the interactive auth and the same request needs to be made but this time with someauth_data
provided.
Examples
if let Err(e) = client.bootstrap_cross_signing(None).await {
if let Some(response) = e.uiaa_response() {
let auth_data = uiaa::AuthData::Password(assign!(
uiaa::Password::new(uiaa::UserIdentifier::MatrixId("example"), "wordpass"),
{ session: 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);
}
}
pub async fn get_user_devices(
&self,
user_id: &UserId
) -> StdResult<UserDevices, CryptoStoreError>
This is supported on encryption
only.
pub async fn get_user_devices(
&self,
user_id: &UserId
) -> StdResult<UserDevices, CryptoStoreError>
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);
}
pub async fn export_keys(
&self,
path: PathBuf,
passphrase: &str,
predicate: impl FnMut(&InboundGroupSession) -> bool
) -> Result<()>
This is supported on encryption
and non-WebAssembly only.
pub async fn export_keys(
&self,
path: PathBuf,
passphrase: &str,
predicate: impl FnMut(&InboundGroupSession) -> bool
) -> Result<()>
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 knownInboundGroupSession
, which represents a room key. If the closure returnstrue
theInboundGroupSessoin
will be included in the export, if the closure returnsfalse
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.");
pub async fn import_keys(
&self,
path: PathBuf,
passphrase: &str
) -> StdResult<(usize, usize), RoomKeyImportError>
This is supported on encryption
and non-WebAssembly only.
pub async fn import_keys(
&self,
path: PathBuf,
passphrase: &str
) -> StdResult<(usize, usize), RoomKeyImportError>
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");
pub async fn get_media_content(
&self,
request: &MediaRequest,
use_cache: bool
) -> Result<Vec<u8>>
pub async fn get_media_content(
&self,
request: &MediaRequest,
use_cache: bool
) -> Result<Vec<u8>>
Get a media file’s content.
If the content is encrypted and encryption is enabled, the content will be decrypted.
Arguments
-
request
- TheMediaRequest
of the content. -
use_cache
- If we should use the media cache for this request.
Delete all the media content corresponding to the given uri from the store.
Arguments
uri
- TheMxcUri
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.
pub async fn get_thumbnail(
&self,
event_content: impl MediaEventContent,
size: MediaThumbnailSize,
use_cache: bool
) -> Result<Option<Vec<u8>>>
pub async fn get_thumbnail(
&self,
event_content: impl MediaEventContent,
size: MediaThumbnailSize,
use_cache: bool
) -> Result<Option<Vec<u8>>>
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.
pub async fn remove_thumbnail(
&self,
event_content: impl MediaEventContent,
size: MediaThumbnailSize
) -> Result<()>
pub async fn remove_thumbnail(
&self,
event_content: impl MediaEventContent,
size: MediaThumbnailSize
) -> Result<()>
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 withget_thumbnail
.
Gets information about the owner of a given access token.
Trait Implementations
Auto Trait Implementations
impl !RefUnwindSafe for Client
impl !UnwindSafe for Client
Blanket Implementations
Mutably borrows from an owned value. Read more
Instruments this type with the provided Span
, returning an
Instrumented
wrapper. Read more