ruma_client_api/
profile.rs

1//! Endpoints for user profiles.
2
3use std::borrow::Cow;
4
5use ruma_common::{
6    api::{
7        path_builder::{StablePathSelector, VersionHistory},
8        MatrixVersion,
9    },
10    serde::StringEnum,
11    OwnedMxcUri,
12};
13use serde::Serialize;
14use serde_json::{from_value as from_json_value, to_value as to_json_value, Value as JsonValue};
15
16pub mod delete_profile_field;
17pub mod get_avatar_url;
18pub mod get_display_name;
19pub mod get_profile;
20pub mod get_profile_field;
21mod profile_field_serde;
22pub mod set_avatar_url;
23pub mod set_display_name;
24pub mod set_profile_field;
25mod static_profile_field;
26
27pub use self::static_profile_field::*;
28
29/// The possible fields of a user's [profile].
30///
31/// [profile]: https://spec.matrix.org/latest/client-server-api/#profiles
32#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
33#[derive(Clone, StringEnum)]
34#[ruma_enum(rename_all = "snake_case")]
35#[non_exhaustive]
36pub enum ProfileFieldName {
37    /// The user's avatar URL.
38    AvatarUrl,
39
40    /// The user's display name.
41    #[ruma_enum(rename = "displayname")]
42    DisplayName,
43
44    /// The user's time zone.
45    #[ruma_enum(rename = "m.tz")]
46    TimeZone,
47
48    #[doc(hidden)]
49    _Custom(crate::PrivOwnedStr),
50}
51
52impl ProfileFieldName {
53    /// Whether this field name existed already before custom fields were officially supported in
54    /// profiles.
55    fn existed_before_extended_profiles(&self) -> bool {
56        matches!(self, Self::AvatarUrl | Self::DisplayName)
57    }
58}
59
60/// The possible values of a field of a user's [profile].
61///
62/// [profile]: https://spec.matrix.org/latest/client-server-api/#profiles
63#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
64#[serde(rename_all = "snake_case")]
65#[non_exhaustive]
66pub enum ProfileFieldValue {
67    /// The user's avatar URL.
68    AvatarUrl(OwnedMxcUri),
69
70    /// The user's display name.
71    #[serde(rename = "displayname")]
72    DisplayName(String),
73
74    /// The user's time zone.
75    #[serde(rename = "m.tz")]
76    TimeZone(String),
77
78    #[doc(hidden)]
79    #[serde(untagged)]
80    _Custom(CustomProfileFieldValue),
81}
82
83impl ProfileFieldValue {
84    /// Construct a new `ProfileFieldValue` with the given field and value.
85    ///
86    /// Prefer to use the public variants of `ProfileFieldValue` where possible; this constructor is
87    /// meant to be used for unsupported fields only and does not allow setting arbitrary data for
88    /// supported ones.
89    ///
90    /// # Errors
91    ///
92    /// Returns an error if the `field` is known and serialization of `value` to the corresponding
93    /// `ProfileFieldValue` variant fails.
94    pub fn new(field: &str, value: JsonValue) -> serde_json::Result<Self> {
95        Ok(match field {
96            "avatar_url" => Self::AvatarUrl(from_json_value(value)?),
97            "displayname" => Self::DisplayName(from_json_value(value)?),
98            "m.tz" => Self::TimeZone(from_json_value(value)?),
99            _ => Self::_Custom(CustomProfileFieldValue { field: field.to_owned(), value }),
100        })
101    }
102
103    /// The name of the field for this value.
104    pub fn field_name(&self) -> ProfileFieldName {
105        match self {
106            Self::AvatarUrl(_) => ProfileFieldName::AvatarUrl,
107            Self::DisplayName(_) => ProfileFieldName::DisplayName,
108            Self::TimeZone(_) => ProfileFieldName::TimeZone,
109            Self::_Custom(CustomProfileFieldValue { field, .. }) => field.as_str().into(),
110        }
111    }
112
113    /// Returns the value of the field.
114    ///
115    /// Prefer to use the public variants of `ProfileFieldValue` where possible; this method is
116    /// meant to be used for custom fields only.
117    pub fn value(&self) -> Cow<'_, JsonValue> {
118        match self {
119            Self::AvatarUrl(value) => {
120                Cow::Owned(to_json_value(value).expect("value should serialize successfully"))
121            }
122            Self::DisplayName(value) => {
123                Cow::Owned(to_json_value(value).expect("value should serialize successfully"))
124            }
125            Self::TimeZone(value) => {
126                Cow::Owned(to_json_value(value).expect("value should serialize successfully"))
127            }
128            Self::_Custom(c) => Cow::Borrowed(&c.value),
129        }
130    }
131}
132
133/// A custom value for a user's profile field.
134#[derive(Debug, Clone, PartialEq, Eq)]
135#[doc(hidden)]
136pub struct CustomProfileFieldValue {
137    /// The name of the field.
138    field: String,
139
140    /// The value of the field
141    value: JsonValue,
142}
143
144/// Endpoint version history valid only for profile fields that didn't exist before Matrix 1.16.
145const EXTENDED_PROFILE_FIELD_HISTORY: VersionHistory = VersionHistory::new(
146    &[(
147        Some("uk.tcpip.msc4133"),
148        "/_matrix/client/unstable/uk.tcpip.msc4133/profile/{user_id}/{field}",
149    )],
150    &[(
151        StablePathSelector::Version(MatrixVersion::V1_16),
152        "/_matrix/client/v3/profile/{user_id}/{field}",
153    )],
154    None,
155    None,
156);
157
158#[cfg(test)]
159mod tests {
160    use ruma_common::owned_mxc_uri;
161    use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
162
163    use super::ProfileFieldValue;
164
165    #[test]
166    fn serialize_profile_field_value() {
167        // Avatar URL.
168        let value = ProfileFieldValue::AvatarUrl(owned_mxc_uri!("mxc://localhost/abcdef"));
169        assert_eq!(
170            to_json_value(value).unwrap(),
171            json!({ "avatar_url": "mxc://localhost/abcdef" })
172        );
173
174        // Display name.
175        let value = ProfileFieldValue::DisplayName("Alice".to_owned());
176        assert_eq!(to_json_value(value).unwrap(), json!({ "displayname": "Alice" }));
177
178        // Custom field.
179        let value = ProfileFieldValue::new("custom_field", "value".into()).unwrap();
180        assert_eq!(to_json_value(value).unwrap(), json!({ "custom_field": "value" }));
181    }
182
183    #[test]
184    fn deserialize_any_profile_field_value() {
185        // Avatar URL.
186        let json = json!({ "avatar_url": "mxc://localhost/abcdef" });
187        assert_eq!(
188            from_json_value::<ProfileFieldValue>(json).unwrap(),
189            ProfileFieldValue::AvatarUrl(owned_mxc_uri!("mxc://localhost/abcdef"))
190        );
191
192        // Display name.
193        let json = json!({ "displayname": "Alice" });
194        assert_eq!(
195            from_json_value::<ProfileFieldValue>(json).unwrap(),
196            ProfileFieldValue::DisplayName("Alice".to_owned())
197        );
198
199        // Custom field.
200        let json = json!({ "custom_field": "value" });
201        let value = from_json_value::<ProfileFieldValue>(json).unwrap();
202        assert_eq!(value.field_name().as_str(), "custom_field");
203        assert_eq!(value.value().as_str(), Some("value"));
204
205        // Error if the object is empty.
206        let json = json!({});
207        from_json_value::<ProfileFieldValue>(json).unwrap_err();
208    }
209}