### Example: Get server vendor info Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/struct.Client.html?search=std%3A%3Avec This example shows how to create a Client and call server_vendor_info to get the server's software name and version. It uses the federation-api feature and calls the /_matrix/federation/v1/version endpoint. ```rust let client = Client::new(homeserver).await?; let server_info = client.server_vendor_info(None).await?; println!( "Server: {}, Version: {}", server_info.server_name, server_info.version ); ``` -------------------------------- ### replace example (partial) Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/utils/local_server/struct.QueryString.html?search= Partial example for replace, showing the initial string. ```rust let s = "this is old"; ``` -------------------------------- ### Basic Client login and sync example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Basic usage of the matrix-sdk crate: instantiate a Client, log in with a username and password, register an event handler for room messages, and start syncing. The sync call never returns unless there is an error. Requires the tokio runtime and anyhow for error handling. ```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(()) } ``` -------------------------------- ### Login with token using login_token Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/authentication/matrix/struct.MatrixAuth.html?search=std%3A%3Avec Example of logging in with a token received from an SSO flow. It shows getting the SSO URL, then using the login token to log in and printing the user ID, device ID, and access token. ```rust use matrix_sdk::Client; let client = Client::new(homeserver).await.unwrap(); let auth = client.matrix_auth(); let sso_url = auth.get_sso_login_url(redirect_url, None); // Let the user authenticate at the SSO URL. // Receive the loginToken param at the redirect_url. let response = auth .login_token(login_token) .initial_device_display_name("My app") .await .unwrap(); println!( "Logged in as {}, got device_id {} and access_token {}", response.user_id, response.device_id, response.access_token, ); ``` -------------------------------- ### Subscribe to VerificationState changes Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/encryption/struct.Encryption.html?search= Example from the `verification_state` method documentation. It shows how to get a `Subscriber` for the `VerificationState`, retrieve the current value, and await updates. Requires the `e2e-encryption` feature and a logged-in client. ```rust use matrix_sdk::{Client, encryption}; use url::Url; let homeserver = Url::parse("http://example.com")?; let client = Client::new(homeserver).await?; let mut subscriber = client.encryption().verification_state(); let current_value = subscriber.get(); println!("The current verification state is: {current_value:?}"); if let Some(verification_state) = subscriber.next().await { println!("Received verification state update {:?}", verification_state) } ``` -------------------------------- ### word_to_titlecase example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/utils/local_server/struct.QueryString.html?search=std%3A%3Avec Example for the `word_to_titlecase` method, showing that it converts a string to title case, capitalizing the first letter of each word. ```rust assert_eq!("Ο οδυσσέας βασιλιάς της ιθάκης", odysseus_king_of_ithaca.word_to_titlecase()); ``` -------------------------------- ### match_indices

(&self, pat: P) -> MatchIndices<'_, P> Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/utils/local_server/struct.QueryString.html?search= Documentation for the `match_indices` method on string slices, which returns an iterator over matches along with their starting indices. ```APIDOC ## match_indices

(&self, pat: P) -> MatchIndices<'_, P> ### Description Returns an iterator over the disjoint matches of a pattern within this string slice as well as the index that the match starts at. For matches that overlap, only the indices corresponding to the first match are returned. ### Method match_indices ### Parameters - **pat** (P) - Required - The pattern to search for. Must implement the `Pattern` trait. ### Return Value An iterator over tuples of (start index, matched substring). ### Examples ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` ``` -------------------------------- ### Full Sliding Sync example with lists and extensions Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/sliding_sync/index.html Complete example of setting up a Sliding Sync client with two lists (full-sync and active-list), enabling account-data, e2ee, and to-device extensions, then spawning a task to listen for room updates and continuously polling the sync stream. Requires a `Client` instance and uses `tokio` for async execution. ```rust use matrix_sdk::{Client, sliding_sync::{SlidingSyncList, SlidingSyncMode, Version}}; use ruma::{api::client::sync::sync_events::v5 as http, assign, events::StateEventType}; use tracing::{warn, error, info, debug}; use futures_util::{pin_mut, StreamExt}; use url::Url; use std::future::ready; let full_sync_list_name = "full-sync".to_owned(); let active_list_name = "active-list".to_owned(); let sliding_sync_builder = client .sliding_sync("main-sync")? .version(Version::Native) .with_account_data_extension( assign!(http::request::AccountData::default(), { enabled: Some(true) }), ) // we enable the account-data extension .with_e2ee_extension(assign!(http::request::E2EE::default(), { enabled: Some(true) })) // and the e2ee extension .with_to_device_extension( assign!(http::request::ToDevice::default(), { enabled: Some(true) }), ); // and the to-device extension let full_sync_list = SlidingSyncList::builder(&full_sync_list_name) .sync_mode(SlidingSyncMode::Growing { batch_size: 50, maximum_number_of_rooms_to_fetch: Some(500) }) // sync up by growing the window .required_state(vec![ (StateEventType::RoomEncryption, "".to_owned()) ]); // only want to know if the room is encrypted let active_list = SlidingSyncList::builder(&active_list_name) // the active window .sync_mode(SlidingSyncMode::new_selective().add_range(0..=9)) // sync up the specific range only, first 10 items .timeline_limit(5u32) // add the last 5 timeline items for room preview and faster timeline loading .required_state(vec![ // we want to know immediately: (StateEventType::RoomEncryption, "".to_owned()), // is it encrypted (StateEventType::RoomTopic, "".to_owned()), // any topic if known (StateEventType::RoomAvatar, "".to_owned()), // avatar if set ]); let sliding_sync = sliding_sync_builder .add_list(active_list) .add_list(full_sync_list) .build() .await?; tokio::spawn(async move { // subscribe to rooms updates let (_rooms, rooms_stream) = client.rooms_stream(); // do something with `_rooms` pin_mut!(rooms_stream); while let Some(_room) = rooms_stream.next().await { info!("a room has been updated"); } }); let stream = sliding_sync.sync(); // continuously poll for updates pin_mut!(stream); loop { let update = match stream.next().await { Some(Ok(u)) => { info!("Received an update. Summary: {u:?}"); }, Some(Err(e)) => { error!("loop was stopped by client error processing: {e}"); } None => { error!("Streaming loop ended unexpectedly"); break; } }; } ``` -------------------------------- ### Example: Accessing JSON text with RawValue::get() Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/event_handler/struct.RawEvent.html Shows how to use the get() method from RawValue to access the underlying JSON text. The example defines a Response struct with a borrowed RawValue field and processes a JSON input, checking if the payload starts with '{'. ```rust use serde::Deserialize; use serde_json::{Result, value::RawValue}; #[derive(Deserialize)] struct Response<'a> { code: u32, #[serde(borrow)] payload: &'a RawValue, } fn process(input: &str) -> Result<()> { let response: Response = serde_json::from_str(input)?; let payload = response.payload.get(); if payload.starts_with('{') { // handle a payload which is a JSON map } else { // handle any other type } Ok(()) } fn main() -> Result<()> { process(r#" {"code": 200, "payload": {}} "#)?; Ok(()) } ``` -------------------------------- ### match_indices example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/authentication/oauth/struct.ClientId.html Example for the match_indices method, collecting matches with their starting indices. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` -------------------------------- ### Full Sliding Sync example with lists and extensions Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/sliding_sync/index.html?search=std%3A%3Avec Complete example of setting up a Sliding Sync session with two lists (full-sync and active-list), enabling account-data, e2ee, and to-device extensions, and then polling for updates. Requires a `Client` and uses `SlidingSyncMode::Growing` and `SlidingSyncMode::new_selective()`. The example spawns a task to subscribe to room updates and then continuously polls the sync stream, logging each update or error. ```rust use matrix_sdk::{Client, sliding_sync::{SlidingSyncList, SlidingSyncMode, Version}}; use ruma::{api::client::sync::sync_events::v5 as http, assign, events::StateEventType}; use tracing::{warn, error, info, debug}; use futures_util::{pin_mut, StreamExt}; use url::Url; use std::future::ready; let full_sync_list_name = "full-sync".to_owned(); let active_list_name = "active-list".to_owned(); let sliding_sync_builder = client .sliding_sync("main-sync")? .version(Version::Native) .with_account_data_extension( assign!(http::request::AccountData::default(), { enabled: Some(true) }), ) // we enable the account-data extension .with_e2ee_extension(assign!(http::request::E2EE::default(), { enabled: Some(true) })) // and the e2ee extension .with_to_device_extension( assign!(http::request::ToDevice::default(), { enabled: Some(true) }), ); // and the to-device extension let full_sync_list = SlidingSyncList::builder(&full_sync_list_name) .sync_mode(SlidingSyncMode::Growing { batch_size: 50, maximum_number_of_rooms_to_fetch: Some(500) }) // sync up by growing the window .required_state(vec![ (StateEventType::RoomEncryption, "".to_owned()) ]); // only want to know if the room is encrypted let active_list = SlidingSyncList::builder(&active_list_name) // the active window .sync_mode(SlidingSyncMode::new_selective().add_range(0..=9)) // sync up the specific range only, first 10 items .timeline_limit(5u32) // add the last 5 timeline items for room preview and faster timeline loading .required_state(vec![ // we want to know immediately: (StateEventType::RoomEncryption, "".to_owned()), // is it encrypted (StateEventType::RoomTopic, "".to_owned()), // any topic if known (StateEventType::RoomAvatar, "".to_owned()), // avatar if set ]); let sliding_sync = sliding_sync_builder .add_list(active_list) .add_list(full_sync_list) .build() .await?; tokio::spawn(async move { // subscribe to rooms updates let (_rooms, rooms_stream) = client.rooms_stream(); // do something with `_rooms` pin_mut!(rooms_stream); while let Some(_room) = rooms_stream.next().await { info!("a room has been updated"); } }); let stream = sliding_sync.sync(); // continuously poll for updates pin_mut!(stream); loop { let update = match stream.next().await { Some(Ok(u)) => { info!("Received an update. Summary: {u:?}"); }, Some(Err(e)) => { error!("loop was stopped by client error processing: {e}"); } None => { error!("Streaming loop ended unexpectedly"); break; } }; } ``` -------------------------------- ### Start verification (deprecated) Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/encryption/identities/struct.Device.html?search=u32+-%3E+bool Example of starting interactive verification using the deprecated start_verification method. ```rust let device = client.encryption().get_device(alice, device_id!("DEVICEID")).await?; if let Some(device) = device { let verification = device.start_verification().await?; } ``` -------------------------------- ### enable example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/encryption/recovery/struct.Recovery.html Example for the enable method. It enables secret storage and backups, optionally with a passphrase, and shows how to subscribe to progress updates. ```rust use futures_util::StreamExt; let recovery = client.encryption().recovery(); let enable = recovery .enable() .wait_for_backups_to_upload() .with_passphrase("my passphrase"); let mut progress_stream = enable.subscribe_to_progress(); tokio::spawn(async move { while let Some(update) = progress_stream.next().await { let Ok(update) = update else { panic!("Update to the enable progress lagged") }; match update { EnableProgress::CreatingBackup => { println!("Creating a new backup"); } EnableProgress::CreatingRecoveryKey => { println!("Creating a new recovery key"); } EnableProgress::Done { .. } => { println!("Recovery has been enabled"); break; } _ => (), } } }); let recovery_key = enable.await?; ``` -------------------------------- ### RangeInclusive::new example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/sliding_sync/type.Range.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example for RangeInclusive::new, which creates an inclusive range equivalent to start..=end. ```rust use std::ops::RangeInclusive; assert_eq!(3..=5, RangeInclusive::new(3, 5)); ``` -------------------------------- ### Login with username and password using login_username Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/authentication/matrix/struct.MatrixAuth.html?search=std%3A%3Avec Example of logging in with a username and password, setting an initial device display name, and printing the device ID and access token. Requires a homeserver URL and a user ID or localpart. ```rust use matrix_sdk::Client; let client = Client::new(homeserver).await?; let user = "example"; let response = client .matrix_auth() .login_username(user, "wordpass") .initial_device_display_name("My bot") .await?; println!( "Logged in as {user}, got device_id {} and access_token {}", response.device_id, response.access_token, ); ``` -------------------------------- ### new Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/struct.HomeserverCapabilities.html?search= Creates a new HomeserverCapabilities instance. ```APIDOC ## new ### Description Creates a new `HomeserverCapabilities` instance. ### Method `pub fn new(client: Client) -> Self` ### Parameters - `client` (Client) - Required - The Matrix client used to query the homeserver. ### Returns - `Self` - A new `HomeserverCapabilities` instance. ``` -------------------------------- ### trim_start directionality example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/authentication/oauth/struct.ClientId.html Directionality example for the trim_start method, showing that it removes leading whitespace from the start of the string. ```rust let s = " English "; assert!(Some('E') == s.trim_start().chars().next()); ``` -------------------------------- ### enable_backup example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/encryption/recovery/struct.Recovery.html Example for the enable_backup method. It creates a new backup if one does not exist and asserts the backup state becomes Enabled. ```rust let recovery = client.encryption().recovery(); recovery.enable_backup().await?; assert_eq!(client.encryption().backups().state(), BackupState::Enabled); ``` -------------------------------- ### FromIterator for Result: partial example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/cross_process_lock/type.AcquireCrossProcessLockResult.html?search=u32+-%3E+bool Partial example for `FromIterator>` on `Result`, showing the start of a variation that demonstrates that no further elements are taken from the iterator after the first `Err`. The example is incomplete in the source. ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; ``` -------------------------------- ### Sync once with default settings Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/struct.Client.html?search=std%3A%3Avec Shows how to create a client, log in, and perform a single sync with default settings to receive the client state and old messages. ```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?; // Sync once so we receive the client state and old messages. client.sync_once(SyncSettings::default()).await?; ``` -------------------------------- ### Get room avatar example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/room/struct.Room.html Example usage of the avatar method. It logs in, retrieves a room by ID, and fetches the room avatar as a file, writing it to avatar.png if present. ```rust 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(); if let Some(avatar) = room.avatar(MediaFormat::File).await.unwrap() { std::fs::write("avatar.png", avatar); } ``` -------------------------------- ### Result::as_mut example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/cross_process_lock/type.AcquireCrossProcessLockResult.html?search=u32+-%3E+bool Shows how to use `Result::as_mut` to get a mutable reference to the `Ok` or `Err` value and modify it in place. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### QR code login example using scan method Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/authentication/oauth/struct.LoginWithQrCodeBuilder.html?search= Example showing how to log in by scanning a QR code. It parses the QR code data, builds a client, and uses `login_with_qr_code` with `scan`. The example subscribes to progress to display the check code and user code, then awaits the login future. ```rust use anyhow::bail; use futures_util::StreamExt; use matrix_sdk::{ authentication::oauth::{ registration::ClientMetadata, qrcode::{LoginProgress, Msc4108IntentData, QrCodeData, QrCodeIntentData, QrProgress}, }, ruma::serde::Raw, Client, }; // You'll need to use a different library to scan and extract the raw bytes from the QR // code. let qr_code_data = QrCodeData::from_bytes(bytes)?; // Fetch the homeserver out of the parsed QR code data. let QrCodeIntentData::Msc4108 { data: Msc4108IntentData::Reciprocate { server_name }, ..} = qr_code_data.intent_data() else { bail!("The QR code is invalid, we did not receive a homeserver in the QR code."); }; // Build the client as usual. let client = Client::builder() .server_name_or_homeserver_url(server_name) .handle_refresh_tokens() .build() .await?; let oauth = client.oauth(); let client_metadata: Raw = client_metadata(); let registration_data = client_metadata.into(); // Subscribing to the progress is necessary since we need to input the check // code on the existing device. let login = oauth.login_with_qr_code(Some(®istration_data)).scan(&qr_code_data); let mut progress = login.subscribe_to_progress(); // Create a task which will show us the progress and tell us the check // code to input in the existing device. let task = tokio::spawn(async move { while let Some(state) = progress.next().await { match state { LoginProgress::Starting | LoginProgress::SyncingSecrets => (), LoginProgress::EstablishingSecureChannel(QrProgress { check_code }) => { println!("Please enter the following code into the other device {check_code:02}"); }, LoginProgress::WaitingForToken { user_code } => { println!("Please use your other device to confirm the log in {user_code}") }, LoginProgress::Done => break, } } }); // Now run the future to complete the login. login.await?; task.abort(); println!("Successfully logged in: {:?} {:?}", client.user_id(), client.device_id()); ``` -------------------------------- ### login_with_sso_callback example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/authentication/matrix/struct.MatrixAuth.html?search=std%3A%3Avec Completes an SSO login after the user has authenticated at the SSO URL. Requires the callback URL or query string carrying the login token. The example shows creating a client, getting the SSO URL, and then calling login_with_sso_callback with the callback data. ```rust use matrix_sdk::Client; let client = Client::new(homeserver).await.unwrap(); let auth = client.matrix_auth(); let sso_url = auth.get_sso_login_url(redirect_url, None); // Let the user authenticate at the SSO URL. // Receive the callback url or query string. let response = auth .login_with_sso_callback(url_or_query) .unwrap() .initial_device_display_name("My app") .await .unwrap(); println!( "Logged in as {}, got device_id {} and access_token {}", response.user_id, response.device_id, response.access_token, ); ``` -------------------------------- ### Example: Enable Recovery with Progress Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/encryption/recovery/struct.Recovery.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example showing how to enable recovery with a passphrase and monitor progress. It prints progress updates and awaits the recovery key. ```rust use futures_util::StreamExt; let recovery = client.encryption().recovery(); let enable = recovery .enable() .wait_for_backups_to_upload() .with_passphrase("my passphrase"); let mut progress = enable.subscribe_to_progress(); tokio::spawn(async move { while let Some(update) = progress.next().await { let Ok(update) = update else { panic!("Update to the enable progress lagged") }; match update { EnableProgress::CreatingBackup => { println!("Creating a new backup"); } EnableProgress::CreatingRecoveryKey => { println!("Creating a new recovery key"); } EnableProgress::Done { .. } => { println!("Recovery has been enabled"); break; } _ => (), } } }); let recovery_key = enable.await?; ``` -------------------------------- ### RoomDirectorySearch usage example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/room_directory_search/struct.RoomDirectorySearch.html?search= Example of creating a Client, initializing RoomDirectorySearch, performing a search, retrieving results, and requesting the next page. Uses anyhow for error handling. ```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 display name example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/struct.Account.html Logs in and retrieves the account's display name, printing it if present. Requires a homeserver URL and valid credentials. ```rust let user = "example"; let client = Client::new(homeserver).await?; client.matrix_auth().login_username(user, "password").send().await?; if let Some(name) = client.account().get_display_name().await? { println!("Logged in as user '{user}' with display name '{name}'"); } ``` -------------------------------- ### Get all devices of a user Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/encryption/struct.Encryption.html?search= Example from the `get_user_devices` method documentation. It retrieves a map of all devices for a user and iterates over them. Returns an empty map if the client is not logged in. ```rust let devices = client.encryption().get_user_devices(alice).await?; for device in devices.devices() { println!("{device:?}"); } ``` -------------------------------- ### Client::new Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/struct.Client.html?search=std%3A%3Avec Creates a new `Client` instance with the specified homeserver URL. ```APIDOC ## Client::new ### Description Creates a new `Client` that will use the given homeserver. All state is held in an `Arc` so the `Client` can be cloned freely. ### Method `async fn new(homeserver_url: Url) -> Result` ### Parameters - `homeserver_url` (Url) - Required - The homeserver that the client should connect to. ### Returns - `Result` - A new `Client` instance or a build error. ``` -------------------------------- ### Get all state events of a statically-known type Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/room/struct.Room.html Retrieves all state events of a given statically-known type, e.g., RoomMemberEventContent. The example shows how to call it and await the result. ```rust use matrix_sdk::ruma::{ events::room::member::RoomMemberEventContent, serde::Raw, }; let room_members = room.get_state_events_static::().await?; ``` -------------------------------- ### login_sso example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/authentication/matrix/struct.MatrixAuth.html?search=std%3A%3Avec Performs the full SSO login flow, spawning a local HTTP server and using a callback to open the SSO URL in a browser. Only available with the `sso-login` feature. The callback must return Ok(()) if the URL was opened successfully; otherwise the error is forwarded. This method should only be used for the first login; use restore_session afterwards. ```rust use matrix_sdk::Client; let client = Client::new(homeserver).await.unwrap(); let response = client .matrix_auth() .login_sso(|sso_url| async move { // Open sso_url Ok(()) }) .initial_device_display_name("My app") .await .unwrap(); println!( "Logged in as {}, got device_id {} and access_token {}", response.user_id, response.device_id, response.access_token ); ``` -------------------------------- ### Fetch messages with MessagesOptions Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/room/struct.Room.html Example of using Room::messages with MessagesOptions::backward() and a from token. It creates a client, gets a room, and asserts that the messages request succeeds. ```rust use matrix_sdk::{Client, room::MessagesOptions}; let options = MessagesOptions::backward().from("t47429-4392820_219380_26003_2265"); let mut client = Client::new(homeserver).await.unwrap(); let room = client.get_room(room_id!("!roomid:example.com")).unwrap(); assert!(room.messages(options).await.is_ok()); ``` -------------------------------- ### Observe media preview configuration with observe_media_preview_config Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/struct.Account.html Use this snippet to observe the media preview configuration. It returns the initial value stored in account data and a stream of updates. Requires the account object and imports for pin_mut and StreamExt. ```rust let account = client.account(); let (initial_config, config_stream) = account.observe_media_preview_config().await?; println!("Initial media preview config: {:?}", initial_config); pin_mut!(config_stream); while let Some(new_config) = config_stream.next().await { println!("Updated media preview config: {:?}", new_config); } ``` -------------------------------- ### substr_range example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/authentication/oauth/struct.ClientId.html Shows how to use substr_range to get the byte range of each substring produced by str::split. The method uses pointer arithmetic and does not search the string. ```rust use core::range::Range; let data = "a, b, b, a"; let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap()); assert_eq!(iter.next(), Some(Range { start: 0, end: 1 })); assert_eq!(iter.next(), Some(Range { start: 3, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 6, end: 7 })); assert_eq!(iter.next(), Some(Range { start: 9, end: 10 })); ``` -------------------------------- ### listen_and_subscribe_to_thread Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/latest_events/struct.LatestEvents.html?search=std%3A%3Avec Starts listening to updates (if not already) for a particular room and thread, and returns a Subscriber to get current and future LatestEventValues. Returns Some if the room and thread exist, None otherwise. ```APIDOC ## [RUST_METHOD] listen_and_subscribe_to_thread ### Description Start listening to updates (if not already) for a particular room and a particular thread in this room, and return a `Subscriber` to get the current and future `LatestEventValue`s. It returns `Some` if the room and the thread exists, `None` otherwise. ### Method Rust async method ### Endpoint `pub async fn listen_and_subscribe_to_thread(&self, room_id: &RoomId, thread_id: &EventId) -> Result>, LatestEventsError>` ### Parameters #### Path Parameters - **room_id** (`&RoomId`) - Required - The ID of the room containing the thread. - **thread_id** (`&EventId`) - Required - The ID of the thread to listen to. ### Response #### Success Response (200) - **Option>** - `Some` if the room and thread exist, `None` otherwise. #### Error Response - **LatestEventsError** - Returned if an error occurs while starting to listen. ``` -------------------------------- ### Verification Examples Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/encryption/identities/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Code examples demonstrating how to verify devices and user identities using the matrix-sdk encryption module. ```APIDOC ## [RUST] Device::request_verification ### Description Requests an interactive verification flow for a device. This method is called on a `Device` instance obtained from the client's encryption module. ### Method Rust method call ### Endpoint `Device::request_verification` ### Parameters None ### Request Example ```rust let verification = device.request_verification().await?; ``` ### Response #### Success Response Returns a `Verification` object that can be used to manage the verification flow. #### Response Example ```rust let verification = device.request_verification().await?; ``` ``` ```APIDOC ## [RUST] Device::verify ### Description Manually marks a device as verified. This method is called on a `Device` instance obtained from the client's encryption module. ### Method Rust method call ### Endpoint `Device::verify` ### Parameters None ### Request Example ```rust device.verify().await?; ``` ### Response #### Success Response Returns `Ok(())` on success. #### Response Example ```rust device.verify().await?; ``` ``` ```APIDOC ## [RUST] Verification::cancel ### Description Cancels an ongoing interactive verification flow. This method is called on a `Verification` object returned from `request_verification`. ### Method Rust method call ### Endpoint `Verification::cancel` ### Parameters None ### Request Example ```rust verification.cancel().await?; ``` ### Response #### Success Response Returns `Ok(())` on success. #### Response Example ```rust verification.cancel().await?; ``` ``` ```APIDOC ## [RUST] UserIdentity::request_verification ### Description Requests an interactive verification flow for a user identity. This method is called on a `UserIdentity` instance obtained from the client's encryption module. ### Method Rust method call ### Endpoint `UserIdentity::request_verification` ### Parameters None ### Request Example ```rust let verification = user.request_verification().await?; ``` ### Response #### Success Response Returns a `Verification` object that can be used to manage the verification flow. #### Response Example ```rust let verification = user.request_verification().await?; ``` ``` ```APIDOC ## [RUST] UserIdentity::verify ### Description Manually marks a user identity as verified. This method is called on a `UserIdentity` instance obtained from the client's encryption module. ### Method Rust method call ### Endpoint `UserIdentity::verify` ### Parameters None ### Request Example ```rust user.verify().await?; ``` ### Response #### Success Response Returns `Ok(())` on success. #### Response Example ```rust user.verify().await?; ``` ``` -------------------------------- ### str::is_char_boundary() example Source: https://docs.rs/matrix-sdk/latest/matrix_sdk/authentication/oauth/struct.ClientId.html Checks if a byte index is a valid UTF-8 code point boundary. The start and end of the string are considered boundaries; returns false if index is greater than `len`. ```rust let s = "Löwe 老虎 Léopard"; assert!(s.is_char_boundary(0)); // start of `老` assert!(s.is_char_boundary(6)); assert!(s.is_char_boundary(s.len())); // second byte of `ö` assert!(!s.is_char_boundary(2)); // third byte of `老` assert!(!s.is_char_boundary(8)); ```