example_get_profiles/
main.rs1use std::{env, process::exit};
2
3use matrix_sdk::{
4 Client, Result as MatrixResult,
5 reqwest::StatusCode,
6 ruma::{
7 OwnedMxcUri, UserId,
8 api::client::profile::{self, AvatarUrl, DisplayName},
9 },
10};
11use url::Url;
12
13#[derive(Debug)]
14#[allow(dead_code)]
15struct UserProfile {
16 avatar_url: Option<OwnedMxcUri>,
17 displayname: Option<String>,
18}
19
20async fn get_profile(client: Client, mxid: &UserId) -> MatrixResult<UserProfile> {
28 let request = profile::get_profile::v3::Request::new(mxid.to_owned());
31
32 let resp = client.send(request).await?;
36
37 let user_profile = UserProfile {
41 avatar_url: resp.get_static::<AvatarUrl>()?,
42 displayname: resp.get_static::<DisplayName>()?,
43 };
44 Ok(user_profile)
45}
46
47async fn get_profile_authenticated(client: Client) -> MatrixResult<UserProfile> {
50 let resp = client.account().fetch_user_profile().await?;
51
52 let user_profile = UserProfile {
53 avatar_url: resp.get_static::<AvatarUrl>()?,
54 displayname: resp.get_static::<DisplayName>()?,
55 };
56 Ok(user_profile)
57}
58
59async fn login(
60 homeserver_url: String,
61 username: &str,
62 password: &str,
63) -> matrix_sdk::Result<Client> {
64 let homeserver_url = Url::parse(&homeserver_url).expect("Couldn't parse the homeserver URL");
65 let client = Client::new(homeserver_url).await.unwrap();
66
67 client
68 .matrix_auth()
69 .login_username(username, password)
70 .initial_device_display_name("rust-sdk")
71 .await?;
72
73 Ok(client)
74}
75
76#[tokio::main]
77async fn main() -> anyhow::Result<()> {
78 tracing_subscriber::fmt::init();
79
80 let (Some(homeserver_url), Some(username), Some(password)) =
82 (env::args().nth(1), env::args().nth(2), env::args().nth(3))
83 else {
84 eprintln!("Usage: {} <homeserver_url> <mxid> <password>", env::args().next().unwrap());
85 exit(1)
86 };
87
88 let client = login(homeserver_url, &username, &password).await?;
89
90 let user_id = UserId::parse(username).expect("Couldn't parse the MXID");
91 let profile = match get_profile(client.clone(), &user_id).await {
92 Ok(profile) => profile,
93 Err(e) => {
94 if e.as_client_api_error()
95 .is_some_and(|err| err.status_code == StatusCode::UNAUTHORIZED)
96 {
97 eprintln!(
98 "Authentication error: {e}. Check if the server requires authentication for profile requests. Trying to fetch profile using the authenticated client instead..."
99 );
100 get_profile_authenticated(client).await?
101 } else {
102 eprintln!("Error fetching profile: {e}");
103 UserProfile { avatar_url: None, displayname: None }
104 }
105 }
106 };
107
108 println!("{profile:#?}");
109 Ok(())
110}