example_get_profiles/
main.rs

1use std::{env, process::exit};
2
3use matrix_sdk::{
4    Client, Result as MatrixResult,
5    ruma::{
6        OwnedMxcUri, UserId,
7        api::client::profile::{self, AvatarUrl, DisplayName},
8    },
9};
10use url::Url;
11
12#[derive(Debug)]
13#[allow(dead_code)]
14struct UserProfile {
15    avatar_url: Option<OwnedMxcUri>,
16    displayname: Option<String>,
17}
18
19/// This function calls the GET profile endpoint
20/// Spec: <https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-profile-userid>
21/// Ruma: <https://docs.rs/ruma-client-api/0.9.0/ruma_client_api/r0/profile/get_profile/index.html>
22async fn get_profile(client: Client, mxid: &UserId) -> MatrixResult<UserProfile> {
23    // First construct the request you want to make
24    // See https://docs.rs/ruma-client-api/0.9.0/ruma_client_api/index.html for all available Endpoints
25    let request = profile::get_profile::v3::Request::new(mxid.to_owned());
26
27    // Start the request using matrix_sdk::Client::send
28    let resp = client.send(request).await?;
29
30    // Use the response and construct a UserProfile struct.
31    // See https://docs.rs/ruma-client-api/0.9.0/ruma_client_api/r0/profile/get_profile/struct.Response.html
32    // for details on the Response for this Request
33    let user_profile = UserProfile {
34        avatar_url: resp.get_static::<AvatarUrl>()?,
35        displayname: resp.get_static::<DisplayName>()?,
36    };
37    Ok(user_profile)
38}
39
40async fn login(
41    homeserver_url: String,
42    username: &str,
43    password: &str,
44) -> matrix_sdk::Result<Client> {
45    let homeserver_url = Url::parse(&homeserver_url).expect("Couldn't parse the homeserver URL");
46    let client = Client::new(homeserver_url).await.unwrap();
47
48    client
49        .matrix_auth()
50        .login_username(username, password)
51        .initial_device_display_name("rust-sdk")
52        .await?;
53
54    Ok(client)
55}
56
57#[tokio::main]
58async fn main() -> anyhow::Result<()> {
59    tracing_subscriber::fmt::init();
60
61    // parse the command line for homeserver, username and password
62    let (Some(homeserver_url), Some(username), Some(password)) =
63        (env::args().nth(1), env::args().nth(2), env::args().nth(3))
64    else {
65        eprintln!("Usage: {} <homeserver_url> <mxid> <password>", env::args().next().unwrap());
66        exit(1)
67    };
68
69    let client = login(homeserver_url, &username, &password).await?;
70
71    let user_id = UserId::parse(username).expect("Couldn't parse the MXID");
72    let profile = get_profile(client, &user_id).await?;
73    println!("{profile:#?}");
74    Ok(())
75}