Expand description
A high-level, batteries-included Matrix client library written in Rust.
This crate seeks to be a general-purpose library for writing software using the Matrix Client-Server API to communicate with a Matrix homeserver. If you’re writing a typical Matrix client or bot, this is likely the crate you need.
However, the crate is designed in a modular way and depends on several other lower-level crates. If you’re attempting something more custom, you might be interested in these:
matrix_sdk_base: A no-network-IO client state machine which can be used to embed a Matrix client into an existing network stack or to build a new Matrix client library on top.matrix_sdk_crypto: A no-network-IO encryption state machine which can be used to add Matrix E2EE support into an existing client or library.
§Getting started
The central component you’ll be interacting with is the Client. A basic use
case will include instantiating the client, logging in as a user, registering
some event handlers and then syncing.
This is demonstrated in the example below.
use matrix_sdk::{
Client, config::SyncSettings,
ruma::{user_id, events::room::message::SyncRoomMessageEvent},
};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let alice = user_id!("@alice:example.org");
let client = Client::builder().server_name(alice.server_name()).build().await?;
// First we need to log in.
client.matrix_auth().login_username(alice, "password").send().await?;
client.add_event_handler(|ev: SyncRoomMessageEvent| async move {
println!("Received a message {:?}", ev);
});
// Syncing is important to synchronize the client state with the server.
// This method will never return unless there is an error.
client.sync(SyncSettings::default()).await?;
Ok(())
}More examples can be found in the examples directory.
§Crate Feature Flags
The following crate feature flags are available:
| Feature | Default | Description |
|---|---|---|
anyhow | No | Better logging for event handlers that return anyhow::Result |
e2e-encryption | Yes | End-to-end encryption (E2EE) support |
eyre | No | Better logging for event handlers that return eyre::Result |
js | No | Enables JavaScript API usage on WASM (does nothing on other targets) |
markdown | No | Support for sending Markdown-formatted messages |
qrcode | Yes | QR code verification support |
sqlite | Yes | Persistent storage of state and E2EE data (optionally, if feature e2e-encryption is enabled), via SQLite available on system |
bundled-sqlite | No | Persistent storage of state and E2EE data (optionally, if feature e2e-encryption is enabled), via SQLite compiled and bundled with the binary |
indexeddb | No | Persistent storage of state and E2EE data (optionally, if feature e2e-encryption is enabled) for browsers, via IndexedDB |
socks | No | SOCKS support in the default HTTP client, reqwest |
sso-login | No | Support for SSO login with a local HTTP server |
§Enabling logging
Users of the matrix-sdk crate can enable log output by depending on the
tracing-subscriber crate and including the following line in their
application (e.g. at the start of main):
tracing_subscriber::fmt::init();The log output is controlled via the RUST_LOG environment variable by
setting it to one of the error, warn, info, debug or trace levels.
The output is printed to stdout.
The RUST_LOG variable also supports a more advanced syntax for filtering
log output more precisely, for instance with crate-level granularity. For
more information on this, check out the tracing_subscriber documentation.
Re-exports§
pub use authentication::AuthApi;pub use authentication::AuthSession;pub use authentication::SessionTokens;pub use media::Media;pub use pusher::Pusher;pub use room::Room;pub use sliding_sync::SlidingSync;pub use sliding_sync::SlidingSyncBuilder;pub use sliding_sync::SlidingSyncList;pub use sliding_sync::SlidingSyncListBuilder;pub use sliding_sync::SlidingSyncListLoadingState;pub use sliding_sync::SlidingSyncMode;pub use sliding_sync::UpdateSummary;pub use bytes;pub use matrix_sdk_base::crypto;e2e-encryptionpub use reqwest;
Modules§
- attachment
- Types and traits for attachments.
- authentication
- Types and functions related to authentication in Matrix.
- config
- Configuration to change the behaviour of the
Client. - debug
- Helpers for creating
std::fmt::Debugimplementations. - deserialized_
responses - SDK-specific variations of response types from Ruma.
- encryption
e2e-encryption - End-to-end encryption related types
- event_
cache - The event cache is an abstraction layer, sitting between the Rust SDK and a final client, that acts as a global observer of all the rooms, gathering and inferring some extra useful information about each room. In particular, this doesn’t require subscribing to a specific room to get access to this information.
- event_
handler - Types and traits related for event handlers. For usage, see
Client::add_event_handler. - executor
- Abstraction over an executor so we can spawn tasks under Wasm the same way we do usually.
- failures_
cache - A TTL cache which can be used to time out repeated operations that might experience intermittent failures.
- futures
- Named futures returned from methods on types in the crate root.
- latest_
events - The Latest Events API provides a lazy, reactive and efficient way to compute the latest event for a room or a thread.
- linked_
chunk - A linked chunk is the underlying data structure that holds all events.
- live_
location_ share - Types for live location sharing.
- locks
- Simplified locks hat panic instead of returning a
Resultwhen the lock is poisoned. - media
- High-level media API.
- notification_
settings - High-level push notification settings API
- paginators
- Stateful paginators to help with paginated APIs.
- pusher
- High-level pusher API.
- ring_
buffer - room
- High-level room API
- room_
directory_ search - Types for searching the public room directory.
- room_
preview - Preview of a room, whether we’ve joined it/left it/been invited to it, or not.
- ruma
- Types and traits for working with the Matrix protocol.
- send_
queue - A send queue facility to serializing queuing and sending of messages.
- serde_
helpers - A collection of serde helpers to avoid having to deserialize an entire event to access some fields.
- sleep
- sliding_
sync - Sliding Sync Client implementation of MSC3575 & extensions
- store
- The state store holds the overall state for rooms, users and their
profiles and their timelines. It is an overall cache for faster access
and convenience- accessible through
Store. - store_
locks - Collection of small helpers that implement store-based locks.
- stream
- Platform-specific stream utilities.
- sync
- The SDK’s representation of the result of a
/syncrequest. - timeout
- tracing_
timer - ttl_
cache - A TTL cache which can be used to time out repeated operations that might experience intermittent failures.
- utils
- Utility types and traits.
Macros§
- boxed_
into_ future - timer
- Macro to create a RAII timer that will log on
Drophow long its covered section took to execute.
Structs§
- Account
- A high-level API to manage the client owner’s account.
- Base
Room - The underlying room data structure collecting state for joined, left and invited rooms.
- Base
Room Member - A member of a room.
- Client
- An async/await enabled Matrix client.
- Client
Builder - Builder that allows creating and configuring various parts of a
Client. - Composer
Draft - Current draft of the composer for the room.
- Memory
Store - In-memory, non-persistent implementation of the
StateStore. - Owned
Server Name - Owned variant of ServerName
- Predecessor
Room - When a room A is tombstoned, it is replaced by a room B. The room A is the
predecessor of B, and B is the successor of A. This type holds information
about the predecessor room. See
Room::predecessor_room. - Room
Create With Creator Event Content - The content of an
m.room.createevent, with a requiredcreatorfield. - Room
Hero - Information about a member considered to be a room hero.
- Room
Info - The underlying pure data structure for joined and left rooms.
- Room
Memberships - Room membership filter as a bitset.
- Server
Name - A Matrix-spec compliant server name.
- Server
Vendor Info - Information about the server vendor obtained from the federation API.
- Session
Meta - The Matrix user session info.
- Sqlite
Crypto Store e2e-encryptionandsqlite - An SQLite-based crypto store.
- Sqlite
Event Cache Store sqlite - An SQLite-based event cache store.
- Sqlite
State Store sqlite - An SQLite-based state store.
- Sqlite
Store Config sqlite - A configuration structure used for opening a store.
- State
Changes - Store state changes and pass them to the StateStore.
- Successor
Room - When a room A is tombstoned, it is replaced by a room B. The room A is the
predecessor of B, and B is the successor of A. This type holds information
about the successor room. See
Room::successor_room. - Transmission
Progress - Progress of sending or receiving a payload.
Enums§
- Client
Build Error - Errors that can happen in
ClientBuilder::build. - Composer
Draft Type - The type of draft of the composer.
- Encryption
State - Represents the state of a room encryption.
- Error
- Internal representation of errors.
- Http
Error - An HTTP error, representing either a connection error or an error while converting the raw HTTP response into a Matrix response.
- IdParse
Error - An error encountered when trying to parse an invalid ID string.
- Loop
Ctrl - Enum controlling if a loop running callbacks should continue or abort.
- Notification
Settings Error - Errors that can occur when manipulating push notification settings.
- Queue
Wedge Error - Represents a failed to send unrecoverable error of an event sent via the send queue.
- Refresh
Token Error - Errors that can happen when refreshing an access token.
- Room
Display Name - The name of the room, either from the metadata or calculated according to matrix specification
- Room
State - Enum keeping track in which state the room is, e.g. if our own user is joined, RoomState::Invited, or has left the room.
- Ruma
ApiError - An error response from a Matrix API call, using a client API specific representation if the endpoint is from that.
- Search
Index Store Kind experimental-search - Type of location to store
RoomIndex - Session
Change - Represents changes that can occur to a
ClientsSession. - Store
Error - State store specific error type.
- Threading
Support - Whether this client instance supports threading or not. Currently used to determine how the client handles read receipts and unread count computations on the base SDK level.
Constants§
- LEASE_
DURATION_ MS - Amount of time a lease of the lock should last, in milliseconds.
- ROOM_
VERSION_ FALLBACK - The room version to use as a fallback when the version of a room is unknown.
- ROOM_
VERSION_ RULES_ FALLBACK - The room version rules to use as a fallback when the version of a room is unknown or unsupported.
- STATE_
STORE_ DATABASE_ NAME sqlite - The filename used for the SQLITE database file used by the state store.
Traits§
- Async
Trait Deps - Super trait that is used for our store traits, this trait will differ if
it’s used on WASM. WASM targets will not require
SendandSyncto have implemented, while other targets will. - Send
Outside Wasm - Alias for
Sendon non-wasm, empty trait (implemented by everything) on wasm. - State
Store - An abstract state store trait that can be used to implement different stores for the SDK.
- State
Store Ext - Convenience functionality for state stores.
- Sync
Outside Wasm - Alias for
Syncon non-wasm, empty trait (implemented by everything) on wasm.
Functions§
- sanitize_
server_ name - Creates a server name from a user supplied string. The string is first sanitized by removing whitespace, the http(s) scheme and any trailing slashes before being parsed.
Type Aliases§
- BoxFuture
- DynState
Store - A type-erased
StateStore. - Http
Result - Result type of a pure HTTP request.
- Result
- Result type of the matrix-sdk.