### Example: Getting LoginTermsParams Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/client/uiaa/struct.UiaaInfo.html An example demonstrating how to use the `params` method to retrieve `LoginTermsParams` for a given `AuthType`. ```rust use ruma_client_api::uiaa::{AuthType, LoginTermsParams}; let login_terms_params = uiaa_info.params::(&AuthType::Terms)?; ``` -------------------------------- ### KeyId algorithm Example Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/type.OneTimeKeyId.html Example demonstrating how to extract the algorithm from a `DeviceKeyId` using the `algorithm()` method. ```rust use ruma_common::{DeviceKeyAlgorithm, DeviceKeyId}; let k = DeviceKeyId::parse("ed25519:1").unwrap(); assert_eq!(k.algorithm(), DeviceKeyAlgorithm::Ed25519); ``` -------------------------------- ### Get algorithm from KeyId Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/struct.KeyId.html Example of retrieving the algorithm part (before the colon) from a parsed DeviceKeyId. ```rust use ruma_common::{DeviceKeyAlgorithm, DeviceKeyId}; let k = DeviceKeyId::parse("ed25519:1").unwrap(); assert_eq!(k.algorithm(), DeviceKeyAlgorithm::Ed25519); ``` -------------------------------- ### OS-Specific Instant Behavior Example Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/time/struct.Instant.html Illustrates an example that works on Linux but panics on macOS due to OS-specific behaviors with large durations. ```rust use std::time::{Instant, Duration}; let now = Instant::now(); let days_per_10_millennia = 365_2425; let solar_seconds_per_day = 60 * 60 * 24; let millennium_in_solar_seconds = 31_556_952_000; assert_eq!(millennium_in_solar_seconds, days_per_10_millennia * solar_seconds_per_day / 10); let duration = Duration::new(millennium_in_solar_seconds, 0); println!("{:?}", now + duration); ``` -------------------------------- ### Configuring Store and Client Builder Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.ClientBuilder.html Example of setting up store configuration with cross-process locks and initializing the client builder. ```rust use matrix_sdk::{Client, config::StoreConfig}; use matrix_sdk::cross_process_lock::CrossProcessLockConfig; let store_config = StoreConfig::new(CrossProcessLockConfig::MultiProcess { holder_name: "cross-process-store-locks-holder-name".to_owned(), }) .state_store(custom_state_store); let client_builder = Client::builder().store_config(store_config); ``` -------------------------------- ### KeyId key_name Example Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/type.OneTimeKeyId.html Example demonstrating how to extract the key name from a `DeviceKeyId` using the `key_name()` method. ```rust use ruma_common::{DeviceKeyId, device_id}; let k = DeviceKeyId::parse("ed25519:DEV1").unwrap(); assert_eq!(k.key_name(), device_id!("DEV1")); ``` -------------------------------- ### Create Forward Request Example Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/client/message/get_message_events/v3/struct.Request.html Use this example to create a `Request` for fetching messages in chronological order. Pagination starts from the beginning of the accessible room timeline if `from` is not set. ```rust let request = get_message_events::v3::Request::forward(room_id).from(token); ``` -------------------------------- ### Get Duration Since UNIX_EPOCH Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/time/constant.UNIX_EPOCH.html This example demonstrates how to get the duration since the UNIX_EPOCH. It prints the number of seconds elapsed since the epoch or panics if the current time is before the epoch. ```rust use std::time::{SystemTime, UNIX_EPOCH}; match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), Err(_) => panic!("SystemTime before UNIX EPOCH!"), } ``` -------------------------------- ### Example: Creating a matrix.to URI with via servers Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/struct.OwnedRoomId.html Shows how to generate a matrix.to URI that includes a list of servers to route through, using `matrix_to_uri_via`. ```rust use ruma_common::{room_id, server_name}; assert_eq!( room_id!("!somewhere:example.org") .matrix_to_uri_via([&*server_name!("example.org"), &*server_name!("alt.example.org")]) .to_string(), "https://matrix.to/#/!somewhere:example.org?via=example.org&via=alt.example.org" ); ``` -------------------------------- ### Request Metadata: GET, Rate Limited, VersionHistory PathBuilder (No Auth) Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Example implementation for a GET request that is rate-limited and requires no access token, using VersionHistory for path building. ```rust const METHOD: Method = ::ruma_common::exports::http::Method::GET; const RATE_LIMITED: bool = true; const PATH_BUILDER: VersionHistory; type Authentication = NoAccessToken; type PathBuilder = VersionHistory; ``` -------------------------------- ### Create Backward Request Example Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/client/message/get_message_events/v3/struct.Request.html Use this example to create a `Request` for fetching messages in reverse chronological order. Pagination starts from the end of the accessible room timeline if `from` is not set. ```rust let request = get_message_events::v3::Request::backward(room_id).from(token); ``` -------------------------------- ### Basic Client Sync with Event Handler Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.Client.html Demonstrates how to initialize a client, log in, sync once to get initial state, register an event handler for new messages, and then continuously sync. ```rust use matrix_sdk::config::SyncSettings; use matrix_sdk::{Client, ruma::events::room::message::OriginalSyncRoomMessageEvent}; let client = Client::new(homeserver).await?; client.matrix_auth().login_username(username, password).send().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.add_event_handler(|ev: OriginalSyncRoomMessageEvent| async move { println!("Received event {}: {:?}", ev.sender, ev.content); }); // Now keep on syncing forever. `sync()` will use the stored sync token // from our `sync_once()` call automatically. client.sync(SyncSettings::default()).await; ``` -------------------------------- ### Example: Parsing and Accessing KeyId Components Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/type.SigningKeyId.html Demonstrates parsing a DeviceKeyId and accessing its algorithm and key name components. ```rust use ruma_common::{DeviceKeyAlgorithm, DeviceKeyId}; let k = DeviceKeyId::parse("ed25519:1").unwrap(); assert_eq!(k.algorithm(), DeviceKeyAlgorithm::Ed25519); ``` ```rust use ruma_common::{DeviceKeyId, device_id}; let k = DeviceKeyId::parse("ed25519:DEV1").unwrap(); assert_eq!(k.key_name(), device_id!("DEV1")); ``` -------------------------------- ### Slice get_unchecked() Method Example Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/events/poll/start/struct.PollAnswers.html Demonstrates how to get an element or subslice without bounds checking. This is an unsafe operation and should be used with caution. For a safe alternative, use `get`. This is applicable to PollAnswers. ```rust pub unsafe fn get_unchecked( &self, index: I, ) -> &>::Output where I: SliceIndex<[T]> ``` -------------------------------- ### Basic Matrix Client Usage Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/index.html Demonstrates instantiating a client, logging in, adding an event handler for messages, and initiating a sync with the server. Requires the `tokio` runtime. ```rust 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(()) } ``` -------------------------------- ### new Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/store/struct.MemoryStore.html Creates a new, empty MemoryStore instance. This is the default store if no other is configured at startup. ```APIDOC ## new ### Description Creates a new empty MemoryStore. ### Method `new()` ### Returns A new `MemoryStore` instance. ``` -------------------------------- ### Iterating Over Slice Elements Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/events/poll/response/struct.SelectionsContentBlock.html Use the `iter` method to get an iterator that yields references to all elements in the slice from start to end. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### Example: Creating a matrix URI Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/struct.OwnedRoomId.html Demonstrates how to construct a `matrix:` URI for a RoomId, with an option to indicate if the URI should facilitate joining the room. ```rust use ruma_common::{room_id, server_name}; assert_eq!( room_id!("!somewhere:example.org").matrix_uri(false).to_string(), "matrix:roomid/somewhere:example.org" ); ``` -------------------------------- ### Instant::now() Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/time/struct.Instant.html Returns an instant corresponding to the current time. This is the primary way to get a starting point for measuring elapsed time. ```APIDOC ## Instant::now() ### Description Returns an instant corresponding to “now”. ### Method `Instant::now()` ### Returns - `Instant`: An instant representing the current time. ``` -------------------------------- ### Get Room State Events by Type Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/room/struct.Room.html Retrieves all state events of a specific type from a room. Useful for fetching all member events, for example. ```rust use matrix_sdk::ruma::{ events::room::member::RoomMemberEventContent, serde::Raw, }; let room_members = room.get_state_events_static::().await?; ``` -------------------------------- ### Client::new Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.Client.html Creates a new Client instance for a given homeserver URL. This is the primary way to initialize the Matrix client. ```APIDOC ## Client::new ### Description Create a new `Client` that will use the given homeserver. ### Method `new` ### Parameters #### Arguments - **homeserver_url** (Url) - Required - The homeserver that the client should connect to. ### Returns - `Result` - A new `Client` instance or a `ClientBuildError`. ``` -------------------------------- ### Example: Safely extracting panic reason with try_into_panic Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/executor/struct.JoinError.html Demonstrates using `try_into_panic` to get the panic payload without panicking the current task if the error is not a panic. ```rust use std::panic; #[tokio::main] async fn main() { let err = tokio::spawn(async { panic!("boom"); }).await.unwrap_err(); if let Ok(reason) = err.try_into_panic() { // Resume the panic on the main task panic::resume_unwind(reason); } } ``` -------------------------------- ### new Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/media/store/struct.MemoryMediaStore.html Creates a new, empty MemoryMediaStore instance. ```APIDOC ## new() ### Description Creates a new empty MemoryMediaStore. ### Returns A new `MemoryMediaStore` instance. ``` -------------------------------- ### Get Message Events Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/client/message/get_message_events/v3/struct.Request.html Fetches message events from a Matrix room. You can specify a starting point, an ending point, the direction of retrieval, a limit on the number of events, and a filter to apply. ```APIDOC ## GET /_matrix/client/v3/rooms/{roomId}/messages ### Description Retrieves a list of message events from a Matrix room. This endpoint can be used for pagination and filtering of room messages. ### Method GET ### Endpoint `/_matrix/client/v3/rooms/{roomId}/messages` ### Parameters #### Path Parameters - **roomId** (OwnedRoomId) - Required - The ID of the room to retrieve events from. #### Query Parameters - **from** (Option) - Optional - The token to start returning events from. If `None`, pagination starts from the beginning or end of the room history depending on `dir`. - **to** (Option) - Optional - The token to stop returning events at. - **dir** (Direction) - Required - The direction to return events from (e.g., `Forward` or `Backward`). - **limit** (UInt) - Optional - The maximum number of events to return. Defaults to 10. - **filter** (RoomEventFilter) - Optional - A filter to apply to the returned events. ### Request Example ```json { "roomId": "!roomid:example.org", "from": "t392-xyzabc", "to": "t392-defghi", "dir": "Forward", "limit": 20, "filter": { "event_type": "m.room.message" } } ``` ### Response #### Success Response (200) - **chunk** (Vec) - A list of message events. - **start** (String) - The token for the first event in the chunk. - **end** (String) - The token for the last event in the chunk. - **next_batch** (Option) - A token that can be used to paginate backwards. - **prev_batch** (Option) - A token that can be used to paginate forwards. #### Response Example ```json { "chunk": [ { "event_id": "$abcdef:example.org", "origin": "example.org", "origin_server_ts": 1678886400000, "room_id": "!roomid:example.org", "sender": "@user:example.org", "type": "m.room.message", "content": { "body": "Hello, world!", "msgtype": "m.text" } } ], "start": "t392-xyzabc", "end": "t392-defghi", "next_batch": "t392-jklmno", "prev_batch": "t392-wxyzab" } ``` ``` -------------------------------- ### TaskMonitor Example Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/task_monitor/struct.TaskMonitor.html Demonstrates creating a TaskMonitor, subscribing to failures, and spawning an infinite task. ```rust use matrix_sdk_common::task_monitor::TaskMonitor; let monitor = TaskMonitor::new(); // Subscribe to failures let mut failures = monitor.subscribe(); // Spawn a task that runs indefinitely let _handle = monitor.spawn_infinite_task("worker", async { loop { // Do work... matrix_sdk_common::sleep::sleep(std::time::Duration::from_secs(1)) .await; } }); ``` -------------------------------- ### Get Room Member Avatar Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/room/struct.RoomMember.html Retrieves the avatar of a room member in a specified format. If a thumbnail is requested, its size is not guaranteed. Ensure you have the necessary client setup and authentication before calling this method. ```rust use matrix_sdk::{ Client, RoomMemberships, media::MediaFormat, room::RoomMember, ruma::room_id, }; let client = Client::new(homeserver).await.unwrap(); client.matrix_auth().login_username(user, "password").send().await.unwrap(); let room_id = room_id!("!roomid:example.com"); let room = client.get_room(&room_id).unwrap(); let members = room.members(RoomMemberships::empty()).await.unwrap(); let member = members.first().unwrap(); if let Some(avatar) = member.avatar(MediaFormat::File).await.unwrap() { std::fs::write("avatar.png", avatar); } ``` -------------------------------- ### Open and Use SecretStore Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/encryption/secret_storage/struct.SecretStore.html Demonstrates how to open a SecretStore with a password, import secrets, and check the cross-signing status. Ensure you have the necessary client and encryption modules initialized. ```rust use ruma::events::secret::request::SecretName; let secret_store = client .encryption() .secret_storage() .open_secret_store("It's a secret to everybody") .await?; secret_store.import_secrets().await?; let status = client .encryption() .cross_signing_status() .await .expect("We should be able to check out cross-signing status"); println!("Cross-signing status {status:?}"); ``` -------------------------------- ### Set a custom MediaStore implementation Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/store/struct.StoreConfig.html This example shows how to set a custom MediaStore implementation for StoreConfig. This is used for managing media-related data. ```rust let store_config = store_config.media_store(custom_media_store); ``` -------------------------------- ### Get RTC Foci Information Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.Client.html Retrieves information about the homeserver’s advertised Real-Time Communication (RTC) foci. This example shows how to find and print the default LiveKit service URL if available. ```rust let rtc_foci = client.rtc_foci().await?; let default_livekit_focus_info = rtc_foci.iter().find_map(|focus| match focus { RtcFocusInfo::LiveKit(info) => Some(info), _ => None, }); if let Some(info) = default_livekit_focus_info { println!("Default LiveKit service URL: {}", info.service_url); } ``` -------------------------------- ### Creating a MatrixSession Instance Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/authentication/matrix/struct.MatrixSession.html Example of how to create and initialize a MatrixSession with user ID, device ID, and access token. ```rust use matrix_sdk:: SessionMeta, SessionTokens, authentication::matrix::MatrixSession, }; use ruma::{owned_device_id, owned_user_id}; let session = MatrixSession { meta: SessionMeta { user_id: owned_user_id!("@example:localhost"), device_id: owned_device_id!("MYDEVICEID"), }, tokens: SessionTokens { access_token: "My-Token".to_owned(), refresh_token: None, }, }; assert_eq!(session.meta.device_id, "MYDEVICEID"); ``` -------------------------------- ### BTreeMap lower_bound cursor example Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/struct.Signatures.html Demonstrates how to use `lower_bound` with `Bound::Included`, `Bound::Excluded`, and `Bound::Unbounded` to get a cursor pointing to the gap before the smallest key greater than or equal to the bound. ```rust #![feature(btree_cursors)] use std::collections::BTreeMap; use std::ops::Bound; let map = BTreeMap::from([ (1, "a"), (2, "b"), (3, "c"), (4, "d"), ]); let cursor = map.lower_bound(Bound::Included(&2)); assert_eq!(cursor.peek_prev(), Some((&1, &"a"))); assert_eq!(cursor.peek_next(), Some((&2, &"b"))); let cursor = map.lower_bound(Bound::Excluded(&2)); assert_eq!(cursor.peek_prev(), Some((&2, &"b"))); assert_eq!(cursor.peek_next(), Some((&3, &"c"))); let cursor = map.lower_bound(Bound::Unbounded); assert_eq!(cursor.peek_prev(), None); assert_eq!(cursor.peek_next(), Some((&1, &"a"))); ``` -------------------------------- ### Iterating Over Character Indices in a String Slice Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/authentication/oauth/struct.ClientId.html Use `char_indices()` to get an iterator that yields tuples of (byte_position, char) for each Unicode Scalar Value in a string slice. This is useful when you need both the character and its starting byte index. ```rust let word = "goodbye"; let count = word.char_indices().count(); assert_eq!(7, count); let mut char_indices = word.char_indices(); assert_eq!(Some((0, 'g')), char_indices.next()); assert_eq!(Some((1, 'o')), char_indices.next()); assert_eq!(Some((2, 'o')), char_indices.next()); assert_eq!(Some((3, 'd')), char_indices.next()); assert_eq!(Some((4, 'b')), char_indices.next()); assert_eq!(Some((5, 'y')), char_indices.next()); assert_eq!(Some((6, 'e')), char_indices.next()); assert_eq!(None, char_indices.next()); ``` ```rust let yes = "y̆es"; let mut char_indices = yes.char_indices(); assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆') assert_eq!(Some((1, '\u{0306}')), char_indices.next()); // note the 3 here - the previous character took up two bytes assert_eq!(Some((3, 'e')), char_indices.next()); assert_eq!(Some((4, 's')), char_indices.next()); assert_eq!(None, char_indices.next()); ``` -------------------------------- ### Request Constructor: new Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/client/authenticated_media/get_content_as_filename/v1/struct.Request.html Creates a new `Request` instance for fetching media content by providing the media ID, server name, and desired filename. ```rust pub fn new( media_id: String, server_name: OwnedServerName, filename: String, ) -> Request ``` -------------------------------- ### Create a Room Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.Client.html This example shows how to create a new Matrix room with custom settings. It uses the `CreateRoomRequest` to specify room parameters. ```rust use matrix_sdk::{ Client, ruma::api::client::room::create_room::v3::Request as CreateRoomRequest, }; let request = CreateRoomRequest::new(); let client = Client::new(homeserver).await.unwrap(); assert!(client.create_room(request).await.is_ok()); ``` -------------------------------- ### Get Filter Request Metadata Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Metadata for the request to get a filter. This is a GET request and is not rate-limited. ```APIDOC ## GET /_matrix/client/:version/filter/:filter_id ### Description Retrieves a filter by its ID. ### Method GET ### Endpoint /_matrix/client/:version/filter/:filter_id ### Parameters #### Path Parameters - **filter_id** (string) - Required - The ID of the filter to retrieve. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **content** (Filter) - The filter object. #### Response Example ```json { "content": { "account_data": {}, "event_format": "key-values", "event_fields": [], "room": { "account_data": {}, "ephemeral": {}, "state": {}, "timeline": {}, "account_data_types": [], "ephemeral_types": [], "state_types": [], "timeline_types": [] }, "presence": { "notifs": {} }, "senders": [], "senders_cached": [], "senders_lazy_loaded_only": [] } } ``` ``` -------------------------------- ### Get Content Request Metadata Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Metadata for the request to get content from the media repository. This is a GET request and is not rate-limited. ```APIDOC ## GET /_matrix/client/:version/media/download/:server_name/:media_id ### Description Downloads content from the media repository. ### Method GET ### Endpoint /_matrix/client/:version/media/download/:server_name/:media_id ### Parameters #### Path Parameters - **server_name** (string) - Required - The server name. - **media_id** (string) - Required - The media ID. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **content** (binary) - The content of the media. - **content_type** (string) - The MIME type of the content. #### Response Example (Binary response, no JSON example) ``` -------------------------------- ### RoomDirectorySearch::new Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/room_directory_search/struct.RoomDirectorySearch.html Constructor for RoomDirectorySearch. Requires a Client instance. ```APIDOC ## RoomDirectorySearch::new ### Description Constructor for the `RoomDirectorySearch`, requires a `Client`. ### Signature `pub fn new(client: Client) -> Self` ``` -------------------------------- ### Example: Creating a matrix.to URI for a RoomId Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/struct.OwnedRoomId.html Illustrates how to create a basic matrix.to URI for a given RoomId using the `matrix_to_uri` method. ```rust use ruma_common::{room_id, server_name}; assert_eq!( room_id!("!somewhere:example.org").matrix_to_uri().to_string(), "https://matrix.to/#/!somewhere:example.org" ); ``` -------------------------------- ### Get Key Changes Request Metadata Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Metadata for the request to get key changes. This is a GET request and is not rate-limited. ```APIDOC ## GET /_matrix/client/:version/keys/changes ### Description Gets a list of users who have changed their keys since a given point in time. ### Method GET ### Endpoint /_matrix/client/:version/keys/changes ### Parameters #### Path Parameters None #### Query Parameters - **from** (string) - Required - The token to start searching from. - **to** (string) - Required - The token to stop searching at. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **changed** (array) - A list of users who have changed their keys. - **user_id** (string) - The ID of the user. - **next_batch** (string) - The token to use to paginate to the next batch of results. #### Response Example ```json { "changed": [ "@alice:example.org", "@bob:example.org" ], "next_batch": "s71_6_1_1_1_0_0_0_0" } ``` ``` -------------------------------- ### Get Content Thumbnail Request Metadata Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Metadata for the request to get a thumbnail of content from the media repository. This is a GET request and is not rate-limited. ```APIDOC ## GET /_matrix/client/:version/media/thumbnail/:server_name/:media_id ### Description Downloads a thumbnail of content from the media repository. ### Method GET ### Endpoint /_matrix/client/:version/media/thumbnail/:server_name/:media_id ### Parameters #### Path Parameters - **server_name** (string) - Required - The server name. - **media_id** (string) - Required - The media ID. #### Query Parameters - **width** (integer) - Optional - The desired width of the thumbnail. - **height** (integer) - Optional - The desired height of the thumbnail. - **method** (string) - Optional - The thumbnail resizing method (e.g., "crop", "scale"). #### Request Body None ### Request Example None ### Response #### Success Response (200) - **thumbnail** (binary) - The thumbnail image data. - **content_type** (string) - The MIME type of the thumbnail. #### Response Example (Binary response, no JSON example) ``` -------------------------------- ### Creating a New ApplicationService Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/client/session/login/v3/struct.ApplicationService.html Demonstrates how to create a new ApplicationService instance using the `new` constructor, which requires a `UserIdentifier`. ```rust pub fn new(identifier: UserIdentifier) -> ApplicationService ``` -------------------------------- ### Get Content As Filename Request Metadata Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Metadata for the request to get content from the media repository as a file. This is a GET request and is not rate-limited. ```APIDOC ## GET /_matrix/client/:version/media/download/:server_name/:media_id/:filename ### Description Downloads content from the media repository with a specified filename. ### Method GET ### Endpoint /_matrix/client/:version/media/download/:server_name/:media_id/:filename ### Parameters #### Path Parameters - **server_name** (string) - Required - The server name. - **media_id** (string) - Required - The media ID. - **filename** (string) - Required - The desired filename. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **content** (binary) - The content of the media. - **content_type** (string) - The MIME type of the content. #### Response Example (Binary response, no JSON example) ``` -------------------------------- ### Create HomeserverCapabilities Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.HomeserverCapabilities.html Creates a new HomeserverCapabilities instance. This is the entry point for interacting with server capabilities. ```rust pub fn new(client: Client) -> Self ``` -------------------------------- ### Get Space Hierarchy v1 Request Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Metadata for the v1 get space hierarchy request. This endpoint uses the GET method and is rate-limited. ```APIDOC ## GET /_matrix/client/v1/spaces/{spaceId}/hierarchy ### Description Retrieves the hierarchy of a space, including its children. ### Method GET ### Endpoint /_matrix/client/v1/spaces/{spaceId}/hierarchy ### Parameters #### Path Parameters - **spaceId** (string) - Required - The ID of the space to retrieve the hierarchy for. #### Query Parameters - **max_depth** (integer) - Optional - The maximum depth of the hierarchy to retrieve. - **from** (string) - Optional - A token to retrieve the next page of results. - **limit** (integer) - Optional - The maximum number of results to return. ### Response #### Success Response (200) - **entries** (array) - A list of space hierarchy entries. - **room_id** (string) - The ID of the room. - **name** (string) - The name of the room. - **num_joined_members** (integer) - The number of joined members in the room. - **topic** (string) - The topic of the room. - **children_state** (string) - The state of the children (e.g., "loaded", "more"). - **children** (array) - A list of child rooms. - **next_batch** (string) - A token to retrieve the next page of results. #### Response Example { "entries": [ { "room_id": "!space_id:example.org", "name": "My Space", "num_joined_members": 100, "topic": "A space for all users", "children_state": "loaded", "children": [ { "room_id": "!room1:example.org", "name": "Room 1", "num_joined_members": 50, "topic": "Topic for room 1", "children_state": "loaded", "children": [] } ] } ], "next_batch": "next_batch_token" } ``` -------------------------------- ### Get Login Types v3 Request Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Metadata for the v3 get login types request. This endpoint uses the GET method and is rate-limited. ```APIDOC ## GET /_matrix/client/v3/login/types ### Description Retrieves the supported login types for the homeserver. ### Method GET ### Endpoint /_matrix/client/v3/login/types ### Response #### Success Response (200) - **types** (array) - A list of supported login types. #### Response Example { "types": [ {"name": "m.password"}, {"name": "m.token"} ] } ``` -------------------------------- ### Initialize and Search Public Rooms Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/room_directory_search/struct.RoomDirectorySearch.html Demonstrates how to initialize RoomDirectorySearch with a client, perform an initial search, and retrieve results. This is useful for fetching the first page of public rooms. ```rust use matrix_sdk::{Client, room_directory_search::RoomDirectorySearch}; use url::Url; async { let homeserver = Url::parse("http://localhost:8080")?; let client = Client::new(homeserver).await?; let mut room_directory_search = RoomDirectorySearch::new(client); room_directory_search.search(None, 10, None).await?; let (results, mut stream) = room_directory_search.results(); room_directory_search.next_page().await?; anyhow::Ok(()) }; ``` -------------------------------- ### Get Threads Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Retrieves a list of threads. This is a GET request and is rate-limited. ```APIDOC ## GET /_matrix/client/v1/threads ### Description Retrieves a list of threads. ### Method GET ### Endpoint /_matrix/client/v1/threads ### Parameters #### Query Parameters - **room_id** (string) - Required - The ID of the room to get threads from. - **limit** (integer) - Optional - The maximum number of threads to return. - **from** (string) - Optional - A token from a previous request to get threads since that point. ### Response #### Success Response (200) - **data** (object) - Contains the list of threads. #### Response Example { "data": { "threads": [ { "thread_id": "some_thread_id", "last_event": { ... }, "original_event": { ... } } ], "next_batch": "some_token" } } ``` -------------------------------- ### Realistic Example with assign! Macro Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/macro.assign.html Shows a more practical application of the `assign` macro for configuring command-line argument options. ```rust // in awesome_cli_lib #[non_exhaustive] struct ArgOptions { pub name: String, pub short: Option, pub long: Option, pub help: Option, pub required: bool, pub takes_value: bool, pub multiple: bool, pub default_value: Option, } impl ArgOptions { pub fn new(name: String) -> Self { // ... } } // your crate use assign::assign; let arg = Arg::new(assign!(ArgOptions::new("version".into()), { short: Some("V".into()), long: Some("version".into()), help: Some("prints the version and quits.".into()), })); ``` -------------------------------- ### Open SqliteMediaStore with Config Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.SqliteMediaStore.html Opens an SQLite-based media store using a provided configuration object. This method is asynchronous. ```rust pub async fn open_with_config( config: &SqliteStoreConfig, ) -> Result ``` -------------------------------- ### Get Type ID Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/authentication/enum.AuthSession.html Gets the TypeId of the AuthSession. This is a blanket implementation for Any. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Get Room Type Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.RoomInfo.html Gets the room type of this room. This is an immutable operation. ```rust pub fn room_type(&self) -> Option<&RoomType> ``` -------------------------------- ### Creating a new VerifyKey Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/federation/discovery/struct.VerifyKey.html Demonstrates how to create a new VerifyKey instance using the `new` associated function, providing the Base64 encoded public key. ```rust pub fn new(key: Base64) -> VerifyKey ``` -------------------------------- ### Creating a new UiaaInfo instance Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/client/uiaa/struct.UiaaInfo.html Demonstrates how to create a new UiaaInfo instance by providing a vector of available authentication flows. ```rust pub fn new(flows: Vec) -> UiaaInfo ``` -------------------------------- ### Get Room Version Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.RoomInfo.html Gets the room version of this room. This is an immutable operation. ```rust pub fn room_version(&self) -> Option<&RoomVersionId> ``` -------------------------------- ### Continuous Client Sync with Event Handler Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.Client.html Shows how to set up a client, log in, register an event handler, and then continuously sync the client state with the server. This method is suitable for long-running synchronization tasks. ```rust use matrix_sdk::{Client, config::SyncSettings, ruma::events::room::message::OriginalSyncRoomMessageEvent}; let client = Client::new(homeserver).await?; client.matrix_auth().login_username(&username, &password).send().await?; // Register our handler so we start responding once we receive a new // event. client.add_event_handler(|ev: OriginalSyncRoomMessageEvent| async move { println!("Received event {}: {:?}", ev.sender, ev.content); }); // Now keep on syncing forever. `sync()` will use the latest sync token // automatically. client.sync(SyncSettings::default()).await?; ``` -------------------------------- ### Get Alternative Aliases Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.RoomInfo.html Gets the alternative aliases of this room. This is an immutable operation. ```rust pub fn alt_aliases(&self) -> &[OwnedRoomAliasId] ``` -------------------------------- ### SqliteMediaStore::open_with_config Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.SqliteMediaStore.html Opens an SQLite-based media store using a provided configuration object. ```APIDOC ## SqliteMediaStore::open_with_config ### Description Opens the SQLite-based media store with the provided configuration. ### Method ``` pub async fn open_with_config( config: &SqliteStoreConfig, ) -> Result ``` ### Parameters * `config`: A reference to a `SqliteStoreConfig` object containing the configuration for the store. ``` -------------------------------- ### Get Canonical Alias Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/struct.RoomInfo.html Gets the canonical alias of this room. This is an immutable operation. ```rust pub fn canonical_alias(&self) -> Option<&RoomAliasId> ``` -------------------------------- ### Creating DeviceKeyAlgorithm from String Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/enum.DeviceKeyAlgorithm.html Demonstrates how to create a DeviceKeyAlgorithm instance from a string, useful for handling custom or unknown algorithm values. ```rust let algorithm = DeviceKeyAlgorithm::from("some_custom_algorithm"); // or let algorithm: DeviceKeyAlgorithm = "some_custom_algorithm".into(); ``` -------------------------------- ### Get Presence v3 Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Retrieves the presence status of users. This is a GET request and is not rate-limited. ```APIDOC ## GET /_matrix/client/v3/presence/{userId} ### Description Retrieves the presence status of a specific user. ### Method GET ### Endpoint /_matrix/client/v3/presence/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user whose presence status to retrieve. ### Response #### Success Response (200) - **presence** (string) - The presence status of the user (e.g., "online", "offline"). - **last_active_ago** (integer) - The time in milliseconds since the user was last active. - **status_msg** (string) - An optional status message. #### Response Example { "presence": "online", "last_active_ago": 10000, "status_msg": "Available" } ``` -------------------------------- ### Create New MemoryMediaStore Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/media/store/struct.MemoryMediaStore.html Instantiates a new, empty MemoryMediaStore. This is the constructor for the in-memory media store. ```rust pub fn new() -> MemoryMediaStore ``` -------------------------------- ### Get Message Events v3 Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Retrieves message events. This is a GET request and is not rate-limited. ```APIDOC ## GET /_matrix/client/v3/room/{roomId}/messages ### Description Retrieves message events from a room. ### Method GET ### Endpoint /_matrix/client/v3/room/{roomId}/messages ### Parameters #### Path Parameters - **roomId** (string) - Required - The ID of the room to retrieve messages from. ### Response #### Success Response (200) - **chunk** (array) - A list of message events. - **end** (string) - The token to use to paginate backwards. - **start** (string) - The token to use to paginate forwards. #### Response Example { "chunk": [ { "content": { "body": "Hello world!", "msgtype": "m.text" }, "event_id": "$abcdef:example.com", "origin_server_ts": 1678886400000, "sender": "@user:example.com", "type": "m.room.message", "room_id": "!roomid:example.com" } ], "end": "t39_abcdef", "start": "t39_ghijkl" } ``` -------------------------------- ### Get Media Configuration Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Retrieves the media configuration for the homeserver. This is a GET request and is rate-limited. ```APIDOC ## GET /_matrix/media/v3/config ### Description Retrieves the media configuration for the homeserver. ### Method GET ### Endpoint /_matrix/media/v3/config ### Parameters ### Request Example ### Response #### Success Response (200) #### Response Example ``` -------------------------------- ### Create Candidate for VoIP Version 0 Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/events/call/candidates/struct.Candidate.html Constructs a `Candidate` for VoIP version 0, requiring the SDP 'a' line, SDP media type, and SDP media line index. ```rust pub fn version_0( candidate: String, sdp_mid: String, sdp_m_line_index: UInt, ) -> Candidate ``` -------------------------------- ### Get Dehydrated Device Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Retrieves information about a dehydrated device. This is a GET request and is not rate-limited. ```APIDOC ## GET /_matrix/client/unstable/dehydrated_device/{deviceId} ### Description Retrieves information about a dehydrated device. ### Method GET ### Endpoint /_matrix/client/unstable/dehydrated_device/{deviceId} ### Parameters #### Path Parameters - **deviceId** (string) - Required - The ID of the dehydrated device to retrieve. ### Response #### Success Response (200) - **content** (object) - The dehydrated device information. #### Response Example { "example": "{\"content\": {}}" } ``` -------------------------------- ### Constructing ClientMetadata Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/authentication/oauth/registration/struct.ClientMetadata.html Demonstrates how to create a new ClientMetadata instance using only the required fields: application_type, grant_types, and client_uri. ```rust pub fn new( application_type: ApplicationType, grant_types: Vec, client_uri: Localized, ) -> Self ``` -------------------------------- ### Get Context Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/trait.Metadata.html Retrieves messages in the context of a given event. This is a GET request and is not rate-limited. ```APIDOC ## GET /_matrix/client/context/{roomId}/{eventId} ### Description Retrieves messages in the context of a given event. ### Method GET ### Endpoint /_matrix/client/context/{roomId}/{eventId} ### Parameters #### Path Parameters - **roomId** (string) - Required - The ID of the room. - **eventId** (string) - Required - The ID of the event. #### Query Parameters - **limit** (integer) - Optional - The maximum number of messages to return before and after the event. - **since** (string) - Optional - A token indicating where to start returning events from. ### Response #### Success Response (200) - **events_before** (array) - A list of events before the given event. - **events_after** (array) - A list of events after the given event. - **state** (array) - A list of state events. - **start** (string) - A token indicating where to start returning events from. - **end** (string) - A token indicating where to end returning events from. #### Response Example { "example": "{\"events_before\": [], \"events_after\": [], \"state\": [], \"start\": \"token1\", \"end\": \"token2\"}" } ``` -------------------------------- ### Create New DeviceInfo Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/client/admin/get_user_info/v3/struct.DeviceInfo.html Provides a constructor function to create a new DeviceInfo instance with an empty list of sessions. ```rust pub fn new() -> DeviceInfo ``` -------------------------------- ### PartialEq Implementations for ServerSigningKeyVersion Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/struct.ServerSigningKeyVersion.html Provides methods for comparing ServerSigningKeyVersion instances with other types like OwnedServerSigningKeyVersion, &str, String, and itself. These implementations are crucial for equality checks. ```APIDOC ## PartialEq for ServerSigningKeyVersion ### Description Tests for `self` and `other` values to be equal, and is used by `==`. ### Method `eq` ### Parameters - **other** (OwnedServerSigningKeyVersion) - Description not available ## PartialEq for &str ### Description Tests for `self` and `other` values to be equal, and is used by `==`. ### Method `eq` ### Parameters - **other** (&ServerSigningKeyVersion) - Description not available ## PartialEq for OwnedServerSigningKeyVersion ### Description Tests for `self` and `other` values to be equal, and is used by `==`. ### Method `eq` ### Parameters - **other** (&ServerSigningKeyVersion) - Description not available ## PartialEq for ServerSigningKeyVersion ### Description Tests for `self` and `other` values to be equal, and is used by `==`. ### Method `eq` ### Parameters - **other** (&String) - Description not available ## PartialEq for ServerSigningKeyVersion ### Description Tests for `self` and `other` values to be equal, and is used by `==`. ### Method `eq` ### Parameters - **other** (&str) - Description not available ## PartialEq for ServerSigningKeyVersion ### Description Tests for `self` and `other` values to be equal, and is used by `==`. ### Method `eq` ### Parameters - **other** (&ServerSigningKeyVersion) - Description not available ``` -------------------------------- ### Get Event By Timestamp Source: https://docs.rs/matrix-sdk/0.17.0/matrix_sdk/ruma/api/federation/event/get_event_by_timestamp/v1/struct.Request.html Retrieves an event from a room by its timestamp and direction. This is a GET request. ```APIDOC ## GET /_matrix/federation/v1/get_event/{roomId}/{eventId} ### Description Retrieves an event from a room by its timestamp and direction. ### Method GET ### Endpoint `/_matrix/federation/v1/get_event/{roomId}/{eventId}` ### Parameters #### Path Parameters - **roomId** (string) - Required - The ID of the room the event is in. - **eventId** (string) - Required - The ID of the event to retrieve. #### Query Parameters - **ts** (integer) - Required - The timestamp to search from in milliseconds since the Unix epoch. - **dir** (string) - Required - The direction in which to search. Can be "f" (forward) or "b" (backward). ### Response #### Success Response (200) - **event** (object) - The event object. - **origin** (string) - The homeserver that originated the event. #### Response Example ```json { "event": { "content": {}, "event_id": "$someEventId", "origin": "example.com", "origin_server_ts": 1678886400000, "room_id": "!someRoomId:example.com", "sender": "@user:example.com", "type": "m.room.message", "unsigned": { "age": 1000 }, "signatures": { "example.com": { "ed25519:key1": "signature1" } } }, "origin": "example.com" } ``` ```