### 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