Struct matrix_sdk::Client
source · [−]pub struct Client { /* private fields */ }
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
sourceimpl Client
impl Client
sourcepub fn builder() -> ClientBuilder
pub fn builder() -> ClientBuilder
Create a new ClientBuilder
.
sourcepub async fn set_homeserver(&self, homeserver_url: Url)
pub async fn set_homeserver(&self, homeserver_url: Url)
sourcepub async fn get_capabilities(&self) -> HttpResult<Capabilities>
pub async fn get_capabilities(&self) -> HttpResult<Capabilities>
Get the capabilities of the homeserver.
This method should be used to check what features are supported by the homeserver.
Example
let client = Client::new(homeserver).await?;
let capabilities = client.get_capabilities().await?;
if capabilities.change_password.enabled {
// Change password
}
sourcepub async fn homeserver(&self) -> Url
pub async fn homeserver(&self) -> Url
The Homeserver of the client.
sourcepub async fn user_id(&self) -> Option<OwnedUserId>
pub async fn user_id(&self) -> Option<OwnedUserId>
Get the user id of the current owner of the client.
sourcepub async fn device_id(&self) -> Option<OwnedDeviceId>
pub async fn device_id(&self) -> Option<OwnedDeviceId>
Get the device id that identifies the current session.
sourcepub async fn session(&self) -> Option<Session>
pub async fn session(&self) -> Option<Session>
Get the whole session info of this client.
Will be None
if the client has not been logged in.
Can be used with Client::restore_login
to restore a previously
logged in session.
sourcepub fn encryption(&self) -> Encryption
Available on crate feature e2e-encryption
only.
pub fn encryption(&self) -> Encryption
e2e-encryption
only.Get the encryption manager of the client.
sourcepub 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::SyncRoomMessageEvent, topic::SyncRoomTopicEvent},
},
Int, MilliSecondsSinceUnixEpoch,
},
Client,
};
use serde::{Deserialize, Serialize};
client
.register_event_handler(
|ev: SyncRoomMessageEvent, room: Room, client: Client| async move {
// Common usage: Room event plus room and client.
},
)
.await
.register_event_handler(
|ev: SyncRoomMessageEvent, 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: SyncRoomTopicEvent| 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 = MessageLike)]
struct TokenEventContent {
token: String,
#[serde(rename = "exp")]
expires_at: MilliSecondsSinceUnixEpoch,
}
client.register_event_handler(|ev: SyncTokenEvent, 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_owned();
client.register_event_handler({
let data = data.clone();
move |ev: SyncRoomMessageEvent | {
let data = data.clone();
async move {
println!("Calling the handler with identifier {}", data);
}
}
}).await;
sourcepub fn register_event_handler_context<T>(&self, ctx: T) -> &Self where
T: Clone + Send + Sync + 'static,
pub fn register_event_handler_context<T>(&self, ctx: T) -> &Self where
T: Clone + Send + Sync + 'static,
Add an arbitrary value for use as event handler context.
The value can be obtained in an event handler by adding an argument of
the type Ctx<T>
.
If a value of the same type has been added before, it will be overwritten.
Example
use matrix_sdk::{
event_handler::Ctx,
room::Room,
ruma::events::room::message::SyncRoomMessageEvent,
};
// Handle used to send messages to the UI part of the app
let my_gui_handle: SomeType = obtain_gui_handle();
client
.register_event_handler_context(my_gui_handle.clone())
.register_event_handler(
|ev: SyncRoomMessageEvent, room: Room, gui_handle: Ctx<SomeType>| async move {
// gui_handle.send(DisplayMessage { message: ev });
},
)
.await;
sourcepub async fn register_notification_handler<H, Fut>(&self, handler: H) -> &Self where
H: Fn(Notification, Room, Client) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
pub async fn register_notification_handler<H, Fut>(&self, handler: H) -> &Self where
H: Fn(Notification, Room, Client) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
Register a handler for a notification.
Similar to Client::register_event_handler
, but only allows functions
or closures with exactly the three arguments [Notification
],
room::Room
, Client
for now.
sourcepub fn rooms(&self) -> Vec<Room>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
pub fn rooms(&self) -> Vec<Room>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
A: Allocator,
Get all the rooms the client knows about.
This will return the list of joined, invited, and left rooms.
sourcepub fn joined_rooms(&self) -> Vec<Joined>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
pub fn joined_rooms(&self) -> Vec<Joined>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
A: Allocator,
Returns the joined rooms this client knows about.
sourcepub fn invited_rooms(&self) -> Vec<Invited>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
pub fn invited_rooms(&self) -> Vec<Invited>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
A: Allocator,
Returns the invited rooms this client knows about.
sourcepub fn left_rooms(&self) -> Vec<Left>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
pub fn left_rooms(&self) -> Vec<Left>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
A: Allocator,
Returns the left rooms this client knows about.
sourcepub fn get_room(&self, room_id: &RoomId) -> Option<Room>
pub fn get_room(&self, room_id: &RoomId) -> Option<Room>
Get a room with the given room id.
Arguments
room_id
- The unique id of the room that should be fetched.
sourcepub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined>
pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined>
Get a joined room with the given room id.
Arguments
room_id
- The unique id of the room that should be fetched.
sourcepub fn get_invited_room(&self, room_id: &RoomId) -> Option<Invited>
pub fn get_invited_room(&self, room_id: &RoomId) -> Option<Invited>
Get an invited room with the given room id.
Arguments
room_id
- The unique id of the room that should be fetched.
sourcepub fn get_left_room(&self, room_id: &RoomId) -> Option<Left>
pub fn get_left_room(&self, room_id: &RoomId) -> Option<Left>
Get a left room with the given room id.
Arguments
room_id
- The unique id of the room that should be fetched.
sourcepub async fn get_login_types(&self) -> HttpResult<Response>
pub async fn get_login_types(&self) -> HttpResult<Response>
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.
sourcepub async fn get_sso_login_url(
&self,
redirect_url: &str,
idp_id: Option<&str>
) -> Result<String>
pub async fn get_sso_login_url(
&self,
redirect_url: &str,
idp_id: Option<&str>
) -> Result<String>
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. -
idp_id
- The optional ID of the identity provider to login with.
sourcepub async fn login(
&self,
user: impl AsRef<str>,
password: &str,
device_id: Option<&str>,
initial_device_display_name: Option<&str>
) -> Result<Response>
pub async fn login(
&self,
user: impl AsRef<str>,
password: &str,
device_id: Option<&str>,
initial_device_display_name: Option<&str>
) -> Result<Response>
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
use matrix_sdk::Client;
let client = Client::new(homeserver).await?;
let user = "example";
let response = client
.login(user, "wordpass", None, Some("My bot")).await?;
println!(
"Logged in as {}, got device_id {} and access_token {}",
user, response.device_id, response.access_token
);
sourcepub async fn login_with_sso<C>(
&self,
use_sso_login_url: impl FnOnce(String) -> C + Send,
server_url: Option<&str>,
server_response: Option<&str>,
device_id: Option<&str>,
initial_device_display_name: Option<&str>,
idp_id: Option<&str>
) -> Result<Response> where
C: Future<Output = Result<()>> + Send,
Available on crate feature sso-login
and non-WebAssembly only.
pub async fn login_with_sso<C>(
&self,
use_sso_login_url: impl FnOnce(String) -> C + Send,
server_url: Option<&str>,
server_response: Option<&str>,
device_id: Option<&str>,
initial_device_display_name: Option<&str>,
idp_id: Option<&str>
) -> Result<Response> where
C: Future<Output = Result<()>> + Send,
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 on127.0.0.1
. -
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. -
idp_id
- The optional ID of the identity provider to login with.
Example
let client = Client::new(homeserver).await.unwrap();
let response = client
.login_with_sso(
|sso_url| async move {
// Open sso_url
Ok(())
},
None,
None,
None,
Some("My app"),
None,
)
.await
.unwrap();
println!("Logged in as {}, got device_id {} and access_token {}",
response.user_id, response.device_id, response.access_token);
sourcepub async fn login_with_token(
&self,
token: &str,
device_id: Option<&str>,
initial_device_display_name: Option<&str>
) -> Result<Response>
pub async fn login_with_token(
&self,
token: &str,
device_id: Option<&str>,
initial_device_display_name: Option<&str>
) -> Result<Response>
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).await.unwrap();
let sso_url = client.get_sso_login_url(redirect_url, None);
// 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);
sourcepub async fn restore_login(&self, session: Session) -> Result<()>
pub async fn restore_login(&self, session: Session) -> Result<()>
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.
Examples
use matrix_sdk::{Client, Session, ruma::{device_id, user_id}};
let homeserver = Url::parse("http://example.com")?;
let client = Client::new(homeserver).await?;
let session = Session {
access_token: "My-Token".to_owned(),
user_id: user_id!("@example:localhost").to_owned(),
device_id: device_id!("MYDEVICEID").to_owned(),
};
client.restore_login(session).await?;
The Session
object can also be created from the response the
Client::login()
method returns:
use matrix_sdk::{Client, Session};
let homeserver = Url::parse("http://example.com")?;
let client = Client::new(homeserver).await?;
let session: Session = client
.login("example", "my-password", None, None)
.await?
.into();
// Persist the `Session` so it can later be used to restore the login.
client.restore_login(session).await?;
sourcepub async fn register(
&self,
registration: impl Into<Request<'_>>
) -> HttpResult<Response>
pub async fn register(
&self,
registration: impl Into<Request<'_>>
) -> HttpResult<Response>
Register a user to the server.
Arguments
registration
- The easiest way to create this request is using the [register::v3::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).await.unwrap();
client.register(request).await;
sourcepub 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's enable member lazy loading.
filter.room.state.lazy_load_options =
LazyLoadOptions::Enabled { include_redundant_members: false };
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();
sourcepub async fn join_room_by_id(&self, room_id: &RoomId) -> HttpResult<Response>
pub async fn join_room_by_id(&self, room_id: &RoomId) -> HttpResult<Response>
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.
sourcepub async fn join_room_by_id_or_alias(
&self,
alias: &RoomOrAliasId,
server_names: &[OwnedServerName]
) -> HttpResult<Response>
pub async fn join_room_by_id_or_alias(
&self,
alias: &RoomOrAliasId,
server_names: &[OwnedServerName]
) -> 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
.
sourcepub 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).await.unwrap();
client.public_rooms(limit, since, server).await;
sourcepub async fn create_room(
&self,
room: impl Into<Request<'_>>
) -> HttpResult<Response>
pub async fn create_room(
&self,
room: impl Into<Request<'_>>
) -> HttpResult<Response>
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).await.unwrap();
assert!(client.create_room(request).await.is_ok());
sourcepub 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 for public rooms with a filter.
Arguments
room_search
- The easiest way to create this request is using theget_public_rooms_filtered::Request
itself.
Examples
use matrix_sdk::{
ruma::{
api::client::directory::get_public_rooms_filtered::v3::Request,
directory::Filter,
assign,
}
};
let generic_search_term = Some("rust");
let filter = assign!(Filter::new(), { generic_search_term });
let request = assign!(Request::new(), { filter });
let response = client.public_rooms_filtered(request).await?;
for room in response.chunk {
println!("Found room {:?}", room);
}
sourcepub async fn upload(
&self,
content_type: &Mime,
reader: &mut impl Read + ?Sized
) -> Result<Response>
pub async fn upload(
&self,
content_type: &Mime,
reader: &mut impl Read + ?Sized
) -> Result<Response>
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)?;
let response = client
.upload(&mime::IMAGE_JPEG, &mut image)
.await?;
println!("Cat URI: {}", response.content_uri);
sourcepub 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 that 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::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::v3::Request::new(&user_id);
// Start the request using Client::send()
let response = client.send(request, None).await?;
// Check the corresponding Response struct to find out what types are
// returned
sourcepub async fn devices(&self) -> HttpResult<Response>
pub async fn devices(&self) -> HttpResult<Response>
Get information of all our own devices.
Examples
let response = client.devices().await?;
for device in response.devices {
println!(
"Device: {} {}",
device.device_id,
device.display_name.as_deref().unwrap_or("")
);
}
sourcepub async fn delete_devices(
&self,
devices: &[OwnedDeviceId],
auth_data: Option<AuthData<'_>>
) -> HttpResult<Response>
pub async fn delete_devices(
&self,
devices: &[OwnedDeviceId],
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 = &[device_id!("DEVICEID").to_owned()];
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::UserIdOrLocalpart("example"),
"wordpass",
), {
session: info.session.as_deref(),
}
));
client
.delete_devices(devices, Some(auth_data))
.await?;
}
}
sourcepub async fn sync_once(
&self,
sync_settings: SyncSettings<'_>
) -> Result<SyncResponse>
pub async fn sync_once(
&self,
sync_settings: SyncSettings<'_>
) -> Result<SyncResponse>
Synchronize the client’s state with the latest state on the server.
Syncing Events
Messages or any other type of event need to be periodically fetched from
the server, this is achieved by sending a /sync
request to the server.
The first sync is sent out without a token
. The response of the
first sync will contain a next_batch
field which should then be
used in the subsequent sync calls as the token
. This ensures that we
don’t receive the same events multiple times.
Long Polling
A sync should in the usual case always be in flight. The
SyncSettings
have a timeout
option, which controls how
long the server will wait for new events before it will respond.
The server will respond immediately if some new events arrive before the
timeout has expired. If no changes arrive and the timeout expires an
empty sync response will be sent to the client.
This method of sending a request that may not receive a response immediately is called long polling.
Filtering Events
The number or type of messages and events that the client should receive
from the server can be altered using a Filter
.
Filters can be non-trivial and, since they will be sent with every sync request, they may take up a bunch of unnecessary bandwidth.
Luckily filters can be uploaded to the server and reused using an unique
identifier, this can be achieved using the get_or_upload_filter()
method.
Arguments
sync_settings
- Settings for the sync call, this allows us to set various options to configure the sync:filter
- To configure which events we receive and which get filtered by the servertimeout
- To configure our long polling setup.token
- To tell the server which events we already received and where we wish to continue syncing.full_state
- To tell the server that we wish to receive all state events, regardless of our configuredtoken
.
Examples
use matrix_sdk::{
Client, config::SyncSettings,
ruma::events::room::message::OriginalSyncRoomMessageEvent,
};
let client = Client::new(homeserver).await?;
client.login(&username, &password, None, None).await?;
// Sync once so we receive the client state and old messages.
client.sync_once(SyncSettings::default()).await?;
// Register our handler so we start responding once we receive a new
// event.
client.register_event_handler(|ev: OriginalSyncRoomMessageEvent| async move {
println!("Received event {}: {:?}", ev.sender, ev.content);
}).await;
// Now keep on syncing forever. `sync()` will use the stored sync token
// from our `sync_once()` call automatically.
client.sync(SyncSettings::default()).await;
sourcepub async fn sync(&self, sync_settings: SyncSettings<'_>)
pub async fn sync(&self, sync_settings: SyncSettings<'_>)
Repeatedly 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
Client::sync_with_callback
method can be used.
This method will internally call Client::sync_once
in a loop.
This method can be used with the Client::register_event_handler
method to react to individual events. If you instead wish to handle
events in a bulk manner the Client::sync_with_callback
and
Client::sync_stream
methods can be used instead. Those two methods
repeatedly return the whole sync response.
Arguments
sync_settings
- Settings for the sync call. Note that those settings will be only used for the first sync call. See the argument docs forClient::sync_once
for more info.
Examples
use matrix_sdk::{
Client, config::SyncSettings,
ruma::events::room::message::OriginalSyncRoomMessageEvent,
};
let client = Client::new(homeserver).await?;
client.login(&username, &password, None, None).await?;
// Register our handler so we start responding once we receive a new
// event.
client.register_event_handler(|ev: OriginalSyncRoomMessageEvent| async move {
println!("Received event {}: {:?}", ev.sender, ev.content);
}).await;
// Now keep on syncing forever. `sync()` will use the latest sync token
// automatically.
client.sync(SyncSettings::default()).await;
sourcepub 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. See the argument docs forClient::sync_once
for more info. -
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;
})
sourcepub async fn sync_stream<'a>(
&'a self,
sync_settings: SyncSettings<'a>
) -> impl Stream<Item = Result<SyncResponse>> + 'a
pub async fn sync_stream<'a>(
&'a self,
sync_settings: SyncSettings<'a>
) -> impl Stream<Item = Result<SyncResponse>> + 'a
This method will internally call Client::sync_once
in a loop and is
equivalent to the Client::sync
method but the responses are provided
as an async stream.
Arguments
sync_settings
- Settings for the sync call. Note that those settings will be only used for the first sync call. See the argument docs forClient::sync_once
for more info.
Examples
use futures::StreamExt;
use matrix_sdk::{Client, config::SyncSettings};
let client = Client::new(homeserver).await?;
client.login(&username, &password, None, None).await?;
let mut sync_stream = Box::pin(client.sync_stream(SyncSettings::default()).await);
while let Some(Ok(response)) = sync_stream.next().await {
for room in response.rooms.join.values() {
for e in &room.timeline.events {
if let Ok(event) = e.event.deserialize() {
println!("Received event {:?}", event);
}
}
}
}
sourcepub async fn sync_token(&self) -> Option<String>
pub async fn sync_token(&self) -> Option<String>
Get the current, if any, sync token of the client. This will be None if the client didn’t sync at least once.
sourcepub 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.
sourcepub async fn remove_media_content(&self, request: &MediaRequest) -> Result<()>
pub async fn remove_media_content(&self, request: &MediaRequest) -> Result<()>
sourcepub async fn remove_media_content_for_uri(&self, uri: &MxcUri) -> Result<()>
pub async fn remove_media_content_for_uri(&self, uri: &MxcUri) -> Result<()>
Delete all the media content corresponding to the given uri from the store.
Arguments
uri
- TheMxcUri
of the files.
sourcepub async fn get_file(
&self,
event_content: impl MediaEventContent,
use_cache: bool
) -> Result<Option<Vec<u8>>>
pub async fn get_file(
&self,
event_content: impl MediaEventContent,
use_cache: bool
) -> Result<Option<Vec<u8>>>
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.
sourcepub async fn remove_file(
&self,
event_content: impl MediaEventContent
) -> Result<()>
pub async fn remove_file(
&self,
event_content: impl MediaEventContent
) -> Result<()>
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.
sourcepub 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.
sourcepub 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
.
sourcepub async fn whoami(&self) -> HttpResult<Response>
pub async fn whoami(&self) -> HttpResult<Response>
Gets information about the owner of a given access token.
Trait Implementations
impl EventHandlerContext for Client
Auto Trait Implementations
impl !RefUnwindSafe for Client
impl Send for Client
impl Sync for Client
impl Unpin for Client
impl !UnwindSafe for Client
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
impl<T> Pointable for T
impl<T> Pointable for T
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcefn clone_into(&self, target: &mut T)
fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
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
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more