Skip to main content

ruma_client_api/discovery/
get_capabilities.rs

1//! `GET /_matrix/client/*/capabilities`
2//!
3//! Get information about the server's supported feature set and other relevant capabilities
4//! ([spec]).
5//!
6//! [spec]: https://spec.matrix.org/v1.19/client-server-api/#capabilities-negotiation
7
8pub mod v3 {
9    //! `/v3/` ([spec])
10    //!
11    //! [spec]: https://spec.matrix.org/v1.19/client-server-api/#get_matrixclientv3capabilities
12
13    #[cfg(feature = "unstable-msc4540")]
14    use std::collections::BTreeSet;
15    use std::{borrow::Cow, collections::BTreeMap};
16
17    use maplit::btreemap;
18    #[cfg(feature = "unstable-msc4540")]
19    use ruma_common::api::OAuthClientScope;
20    use ruma_common::{
21        RoomVersionId,
22        api::{auth_scheme::AccessToken, request, response},
23        metadata,
24        profile::ProfileFieldName,
25        serde::StringEnum,
26    };
27    use serde::{Deserialize, Deserializer, Serialize, de};
28    use serde_json::{
29        Map as JsonMap, Value as JsonValue, from_value as from_json_value,
30        to_value as to_json_value,
31    };
32
33    use crate::PrivOwnedStr;
34
35    metadata! {
36        method: GET,
37        rate_limited: true,
38        authentication: AccessToken,
39        history: {
40            1.0 => "/_matrix/client/r0/capabilities",
41            1.1 => "/_matrix/client/v3/capabilities",
42        }
43    }
44
45    /// Request type for the `get_capabilities` endpoint.
46    #[request]
47    #[derive(Default)]
48    pub struct Request {}
49
50    /// Response type for the `get_capabilities` endpoint.
51    #[response]
52    pub struct Response {
53        /// The capabilities the server supports
54        pub capabilities: Capabilities,
55    }
56
57    impl Request {
58        /// Creates an empty `Request`.
59        pub fn new() -> Self {
60            Self {}
61        }
62    }
63
64    impl Response {
65        /// Creates a new `Response` with the given capabilities.
66        pub fn new(capabilities: Capabilities) -> Self {
67            Self { capabilities }
68        }
69    }
70
71    impl From<Capabilities> for Response {
72        fn from(capabilities: Capabilities) -> Self {
73            Self::new(capabilities)
74        }
75    }
76
77    /// Contains information about all the capabilities that the server supports.
78    #[derive(Clone, Debug, Default, Serialize)]
79    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
80    #[allow(deprecated)]
81    pub struct Capabilities {
82        /// Capability to indicate if the user can change their password.
83        #[serde(
84            rename = "m.change_password",
85            default,
86            skip_serializing_if = "ChangePasswordCapability::is_default"
87        )]
88        pub change_password: ChangePasswordCapability,
89
90        /// The room versions the server supports.
91        #[serde(
92            rename = "m.room_versions",
93            default,
94            skip_serializing_if = "RoomVersionsCapability::is_default"
95        )]
96        pub room_versions: RoomVersionsCapability,
97
98        /// Capability to indicate if the user can change their display name.
99        #[serde(
100            rename = "m.set_displayname",
101            default,
102            skip_serializing_if = "SetDisplayNameCapability::is_default"
103        )]
104        #[deprecated = "Since Matrix 1.16, prefer profile_fields if it is set."]
105        pub set_displayname: SetDisplayNameCapability,
106
107        /// Capability to indicate if the user can change their avatar.
108        #[serde(
109            rename = "m.set_avatar_url",
110            default,
111            skip_serializing_if = "SetAvatarUrlCapability::is_default"
112        )]
113        #[deprecated = "Since Matrix 1.16, prefer profile_fields if it is set."]
114        pub set_avatar_url: SetAvatarUrlCapability,
115
116        /// Capability to indicate if the user can change the third-party identifiers associated
117        /// with their account.
118        #[serde(
119            rename = "m.3pid_changes",
120            default,
121            skip_serializing_if = "ThirdPartyIdChangesCapability::is_default"
122        )]
123        pub thirdparty_id_changes: ThirdPartyIdChangesCapability,
124
125        /// Capability to indicate if the user can generate tokens to log further clients into
126        /// their account.
127        #[serde(
128            rename = "m.get_login_token",
129            default,
130            skip_serializing_if = "GetLoginTokenCapability::is_default"
131        )]
132        pub get_login_token: GetLoginTokenCapability,
133
134        /// Capability to indicate if the user can set extended profile fields.
135        #[serde(rename = "m.profile_fields", skip_serializing_if = "Option::is_none")]
136        pub profile_fields: Option<ProfileFieldsCapability>,
137
138        /// Capability to indicate if the server automatically forgets rooms that the user leaves.
139        #[serde(
140            rename = "m.forget_forced_upon_leave",
141            default,
142            skip_serializing_if = "ForgetForcedUponLeaveCapability::is_default"
143        )]
144        pub forget_forced_upon_leave: ForgetForcedUponLeaveCapability,
145
146        /// Capability to indicate if the user can perform account moderation actions via [server
147        /// administration] endpoints.
148        ///
149        /// [server administration]: https://spec.matrix.org/v1.19/client-server-api/#server-administration
150        #[serde(
151            rename = "m.account_moderation",
152            default,
153            skip_serializing_if = "AccountModerationCapability::is_default"
154        )]
155        pub account_moderation: AccountModerationCapability,
156
157        /// Capability to indicate if the user can request URL previews.
158        #[serde(
159            rename = "m.preview_url",
160            default,
161            skip_serializing_if = "PreviewUrlCapability::is_default"
162        )]
163        pub preview_url: PreviewUrlCapability,
164
165        /// Capability to indicate if the user can perform administrative actions. ([MSC4540])
166        ///
167        /// [MSC4540]: https://github.com/matrix-org/matrix-spec-proposals/pull/4540
168        #[cfg(feature = "unstable-msc4540")]
169        #[serde(
170            rename = "org.continuwuity.msc4540.admin",
171            default,
172            skip_serializing_if = "AdminCapability::is_default"
173        )]
174        pub admin: AdminCapability,
175
176        /// Any other custom capabilities that the server supports outside of the specification,
177        /// labeled using the Java package naming convention and stored as arbitrary JSON values.
178        #[serde(flatten)]
179        custom_capabilities: BTreeMap<String, JsonValue>,
180    }
181
182    impl<'de> Deserialize<'de> for Capabilities {
183        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
184            #[derive(Deserialize)]
185            #[allow(deprecated)]
186            struct CapabilitiesDeHelper {
187                #[serde(rename = "m.change_password", default)]
188                change_password: ChangePasswordCapability,
189                #[serde(rename = "m.room_versions", default)]
190                room_versions: RoomVersionsCapability,
191                #[serde(rename = "m.set_displayname", default)]
192                set_displayname: SetDisplayNameCapability,
193                #[serde(rename = "m.set_avatar_url", default)]
194                set_avatar_url: SetAvatarUrlCapability,
195                #[serde(rename = "m.3pid_changes", default)]
196                thirdparty_id_changes: ThirdPartyIdChangesCapability,
197                #[serde(rename = "m.get_login_token", default)]
198                get_login_token: GetLoginTokenCapability,
199                #[serde(rename = "m.profile_fields", alias = "uk.tcpip.msc4133.profile_fields")]
200                profile_fields: Option<ProfileFieldsCapability>,
201                #[serde(rename = "m.forget_forced_upon_leave", default)]
202                forget_forced_upon_leave: ForgetForcedUponLeaveCapability,
203                #[serde(rename = "m.account_moderation", default)]
204                account_moderation: AccountModerationCapability,
205                #[serde(rename = "m.preview_url", default)]
206                preview_url: PreviewUrlCapability,
207                #[cfg(feature = "unstable-msc4540")]
208                #[serde(rename = "org.continuwuity.msc4540.admin", default)]
209                admin: AdminCapability,
210                #[serde(flatten)]
211                custom_capabilities: BTreeMap<String, JsonValue>,
212            }
213
214            let mut capabilities = JsonMap::deserialize(deserializer)?;
215            // Servers may send both names, which serde rejects as a duplicate field.
216            if capabilities.contains_key("m.profile_fields") {
217                capabilities.remove("uk.tcpip.msc4133.profile_fields");
218            }
219            let helper = CapabilitiesDeHelper::deserialize(JsonValue::Object(capabilities))
220                .map_err(de::Error::custom)?;
221
222            #[allow(deprecated)]
223            Ok(Self {
224                change_password: helper.change_password,
225                room_versions: helper.room_versions,
226                set_displayname: helper.set_displayname,
227                set_avatar_url: helper.set_avatar_url,
228                thirdparty_id_changes: helper.thirdparty_id_changes,
229                get_login_token: helper.get_login_token,
230                profile_fields: helper.profile_fields,
231                forget_forced_upon_leave: helper.forget_forced_upon_leave,
232                account_moderation: helper.account_moderation,
233                preview_url: helper.preview_url,
234                #[cfg(feature = "unstable-msc4540")]
235                admin: helper.admin,
236                custom_capabilities: helper.custom_capabilities,
237            })
238        }
239    }
240
241    impl Capabilities {
242        /// Creates empty `Capabilities`.
243        pub fn new() -> Self {
244            Default::default()
245        }
246
247        /// Returns the value of the given capability.
248        ///
249        /// Prefer to use the public fields of `Capabilities` where possible; this method is meant
250        /// to be used for unsupported capabilities only.
251        pub fn get(&self, capability: &str) -> Option<Cow<'_, JsonValue>> {
252            fn serialize<T: Serialize>(cap: &T) -> JsonValue {
253                to_json_value(cap).expect("capability serialization to succeed")
254            }
255
256            match capability {
257                "m.change_password" => Some(Cow::Owned(serialize(&self.change_password))),
258                "m.room_versions" => Some(Cow::Owned(serialize(&self.room_versions))),
259                #[allow(deprecated)]
260                "m.set_displayname" => Some(Cow::Owned(serialize(&self.set_displayname))),
261                #[allow(deprecated)]
262                "m.set_avatar_url" => Some(Cow::Owned(serialize(&self.set_avatar_url))),
263                "m.3pid_changes" => Some(Cow::Owned(serialize(&self.thirdparty_id_changes))),
264                "m.get_login_token" => Some(Cow::Owned(serialize(&self.get_login_token))),
265                "m.profile_fields" | "uk.tcpip.msc4133.profile_fields" => {
266                    self.profile_fields.as_ref().map(|cap| Cow::Owned(serialize(cap)))
267                }
268                "m.forget_forced_upon_leave" => {
269                    Some(Cow::Owned(serialize(&self.forget_forced_upon_leave)))
270                }
271                "m.account_moderation" => Some(Cow::Owned(serialize(&self.account_moderation))),
272                "m.preview_url" => Some(Cow::Owned(serialize(&self.preview_url))),
273                #[cfg(feature = "unstable-msc4540")]
274                "org.continuwuity.msc4540.admin" => Some(Cow::Owned(serialize(&self.admin))),
275                _ => self.custom_capabilities.get(capability).map(Cow::Borrowed),
276            }
277        }
278
279        /// Sets a capability to the given value.
280        ///
281        /// Prefer to use the public fields of `Capabilities` where possible; this method is meant
282        /// to be used for unsupported capabilities only and does not allow setting
283        /// arbitrary data for supported ones.
284        pub fn set(&mut self, capability: &str, value: JsonValue) -> serde_json::Result<()> {
285            match capability {
286                "m.change_password" => self.change_password = from_json_value(value)?,
287                "m.room_versions" => self.room_versions = from_json_value(value)?,
288                #[allow(deprecated)]
289                "m.set_displayname" => self.set_displayname = from_json_value(value)?,
290                #[allow(deprecated)]
291                "m.set_avatar_url" => self.set_avatar_url = from_json_value(value)?,
292                "m.3pid_changes" => self.thirdparty_id_changes = from_json_value(value)?,
293                "m.get_login_token" => self.get_login_token = from_json_value(value)?,
294                "m.profile_fields" | "uk.tcpip.msc4133.profile_fields" => {
295                    self.profile_fields = from_json_value(value)?;
296                }
297                "m.forget_forced_upon_leave" => {
298                    self.forget_forced_upon_leave = from_json_value(value)?;
299                }
300                "m.account_moderation" => {
301                    self.account_moderation = from_json_value(value)?;
302                }
303                "m.preview_url" => self.preview_url = from_json_value(value)?,
304                #[cfg(feature = "unstable-msc4540")]
305                "org.continuwuity.msc4540.admin" => self.admin = from_json_value(value)?,
306                _ => {
307                    self.custom_capabilities.insert(capability.to_owned(), value);
308                }
309            }
310
311            Ok(())
312        }
313    }
314
315    /// Information about the m.change_password capability
316    #[derive(Clone, Debug, Serialize, Deserialize)]
317    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
318    pub struct ChangePasswordCapability {
319        /// `true` if the user can change their password, `false` otherwise.
320        pub enabled: bool,
321    }
322
323    impl ChangePasswordCapability {
324        /// Creates a new `ChangePasswordCapability` with the given enabled flag.
325        pub fn new(enabled: bool) -> Self {
326            Self { enabled }
327        }
328
329        /// Returns whether all fields have their default value.
330        pub fn is_default(&self) -> bool {
331            self.enabled
332        }
333    }
334
335    impl Default for ChangePasswordCapability {
336        fn default() -> Self {
337            Self { enabled: true }
338        }
339    }
340
341    /// Information about the m.room_versions capability
342    #[derive(Clone, Debug, Serialize, Deserialize)]
343    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
344    pub struct RoomVersionsCapability {
345        /// The default room version the server is using for new rooms.
346        pub default: RoomVersionId,
347
348        /// A detailed description of the room versions the server supports.
349        pub available: BTreeMap<RoomVersionId, RoomVersionStability>,
350    }
351
352    impl RoomVersionsCapability {
353        /// Creates a new `RoomVersionsCapability` with the given default room version ID and room
354        /// version descriptions.
355        pub fn new(
356            default: RoomVersionId,
357            available: BTreeMap<RoomVersionId, RoomVersionStability>,
358        ) -> Self {
359            Self { default, available }
360        }
361
362        /// Returns whether all fields have their default value.
363        pub fn is_default(&self) -> bool {
364            self.default == RoomVersionId::V1
365                && self.available.len() == 1
366                && self
367                    .available
368                    .get(&RoomVersionId::V1)
369                    .map(|stability| *stability == RoomVersionStability::Stable)
370                    .unwrap_or(false)
371        }
372    }
373
374    impl Default for RoomVersionsCapability {
375        fn default() -> Self {
376            Self {
377                default: RoomVersionId::V1,
378                available: btreemap! { RoomVersionId::V1 => RoomVersionStability::Stable },
379            }
380        }
381    }
382
383    /// The stability of a room version.
384    #[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
385    #[derive(Clone, StringEnum)]
386    #[ruma_enum(rename_all = "lowercase")]
387    #[non_exhaustive]
388    pub enum RoomVersionStability {
389        /// Support for the given version is stable.
390        Stable,
391
392        /// Support for the given version is unstable.
393        Unstable,
394
395        #[doc(hidden)]
396        _Custom(PrivOwnedStr),
397    }
398
399    /// Information about the `m.set_displayname` capability
400    #[derive(Clone, Debug, Serialize, Deserialize)]
401    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
402    #[deprecated = "Since Matrix 1.16, prefer ProfileFieldsCapability instead."]
403    pub struct SetDisplayNameCapability {
404        /// `true` if the user can change their display name, `false` otherwise.
405        pub enabled: bool,
406    }
407
408    #[allow(deprecated)]
409    impl SetDisplayNameCapability {
410        /// Creates a new `SetDisplayNameCapability` with the given enabled flag.
411        pub fn new(enabled: bool) -> Self {
412            Self { enabled }
413        }
414
415        /// Returns whether all fields have their default value.
416        pub fn is_default(&self) -> bool {
417            self.enabled
418        }
419    }
420
421    #[allow(deprecated)]
422    impl Default for SetDisplayNameCapability {
423        fn default() -> Self {
424            Self { enabled: true }
425        }
426    }
427
428    /// Information about the `m.set_avatar_url` capability
429    #[derive(Clone, Debug, Serialize, Deserialize)]
430    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
431    #[deprecated = "Since Matrix 1.16, prefer ProfileFieldsCapability instead."]
432    pub struct SetAvatarUrlCapability {
433        /// `true` if the user can change their avatar, `false` otherwise.
434        pub enabled: bool,
435    }
436
437    #[allow(deprecated)]
438    impl SetAvatarUrlCapability {
439        /// Creates a new `SetAvatarUrlCapability` with the given enabled flag.
440        pub fn new(enabled: bool) -> Self {
441            Self { enabled }
442        }
443
444        /// Returns whether all fields have their default value.
445        pub fn is_default(&self) -> bool {
446            self.enabled
447        }
448    }
449
450    #[allow(deprecated)]
451    impl Default for SetAvatarUrlCapability {
452        fn default() -> Self {
453            Self { enabled: true }
454        }
455    }
456
457    /// Information about the `m.3pid_changes` capability
458    #[derive(Clone, Debug, Serialize, Deserialize)]
459    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
460    pub struct ThirdPartyIdChangesCapability {
461        /// `true` if the user can change the third-party identifiers associated with their
462        /// account, `false` otherwise.
463        pub enabled: bool,
464    }
465
466    impl ThirdPartyIdChangesCapability {
467        /// Creates a new `ThirdPartyIdChangesCapability` with the given enabled flag.
468        pub fn new(enabled: bool) -> Self {
469            Self { enabled }
470        }
471
472        /// Returns whether all fields have their default value.
473        pub fn is_default(&self) -> bool {
474            self.enabled
475        }
476    }
477
478    impl Default for ThirdPartyIdChangesCapability {
479        fn default() -> Self {
480            Self { enabled: true }
481        }
482    }
483
484    /// Information about the `m.get_login_token` capability.
485    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
486    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
487    pub struct GetLoginTokenCapability {
488        /// Whether the user can request a login token.
489        pub enabled: bool,
490    }
491
492    impl GetLoginTokenCapability {
493        /// Creates a new `GetLoginTokenCapability` with the given enabled flag.
494        pub fn new(enabled: bool) -> Self {
495            Self { enabled }
496        }
497
498        /// Returns whether all fields have their default value.
499        pub fn is_default(&self) -> bool {
500            !self.enabled
501        }
502    }
503
504    /// Information about the `m.profile_fields` capability.
505    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
506    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
507    pub struct ProfileFieldsCapability {
508        /// Whether the user can set extended profile fields.
509        pub enabled: bool,
510
511        /// The fields that can be set by the user.
512        #[serde(skip_serializing_if = "Option::is_none")]
513        pub allowed: Option<Vec<ProfileFieldName>>,
514
515        /// The fields that cannot be set by the user.
516        ///
517        /// This list is ignored if `allowed` is provided.
518        #[serde(skip_serializing_if = "Option::is_none")]
519        pub disallowed: Option<Vec<ProfileFieldName>>,
520    }
521
522    impl ProfileFieldsCapability {
523        /// Creates a new `ProfileFieldsCapability` with the given enabled flag.
524        pub fn new(enabled: bool) -> Self {
525            Self { enabled, allowed: None, disallowed: None }
526        }
527
528        /// Whether the server advertises that the field with the given name can be set.
529        pub fn can_set_field(&self, field: &ProfileFieldName) -> bool {
530            if !self.enabled {
531                return false;
532            }
533
534            if let Some(allowed) = &self.allowed {
535                allowed.contains(field)
536            } else if let Some(disallowed) = &self.disallowed {
537                !disallowed.contains(field)
538            } else {
539                // The default is that any field is allowed.
540                true
541            }
542        }
543    }
544
545    /// Information about the [`m.forget_forced_upon_leave`] capability.
546    ///
547    /// [`m.forget_forced_upon_leave`]: https://spec.matrix.org/v1.19/client-server-api/#mforget_forced_upon_leave-capability
548    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
549    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
550    pub struct ForgetForcedUponLeaveCapability {
551        /// Whether the server will automatically forget any room that the user leaves.
552        ///
553        /// This behavior applies irrespective of whether the user has left the room on their own
554        /// or has been kicked or banned from the room by another user.
555        pub enabled: bool,
556    }
557
558    impl ForgetForcedUponLeaveCapability {
559        /// Creates a new `ForgetForcedUponLeaveCapability` with the given enabled flag.
560        pub fn new(enabled: bool) -> Self {
561            Self { enabled }
562        }
563
564        /// Returns whether all fields have their default value.
565        pub fn is_default(&self) -> bool {
566            !self.enabled
567        }
568    }
569
570    /// Information about the `m.account_moderation` capability.
571    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
572    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
573    pub struct AccountModerationCapability {
574        /// Whether the user can suspend a user via `PUT /admin/suspend/{userId}`.
575        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
576        pub suspend: bool,
577
578        /// Whether the user can lock a user via `PUT /admin/lock/{userId}`.
579        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
580        pub lock: bool,
581    }
582
583    impl AccountModerationCapability {
584        /// Creates a new `AccountModerationCapability` with the given suspend and lock
585        /// capabilities.
586        pub fn new(suspend: bool, lock: bool) -> Self {
587            Self { suspend, lock }
588        }
589
590        /// Returns whether all fields have their default value.
591        pub fn is_default(&self) -> bool {
592            !self.suspend && !self.lock
593        }
594    }
595
596    /// Information about the `m.preview_url` capability.
597    #[derive(Clone, Debug, Serialize, Deserialize)]
598    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
599    pub struct PreviewUrlCapability {
600        /// `true` if the user can request URL previews, `false` otherwise.
601        pub enabled: bool,
602    }
603
604    impl PreviewUrlCapability {
605        /// Creates a new `PreviewUrlCapability` with the given enabled flag.
606        pub fn new(enabled: bool) -> Self {
607            Self { enabled }
608        }
609
610        /// Returns whether all fields have their default value.
611        pub fn is_default(&self) -> bool {
612            self.enabled
613        }
614    }
615
616    impl Default for PreviewUrlCapability {
617        fn default() -> Self {
618            Self { enabled: true }
619        }
620    }
621
622    /// Information about the `m.admin` capability. ([MSC4540])
623    ///
624    /// [MSC4540]: https://github.com/matrix-org/matrix-spec-proposals/pull/4540
625    #[cfg(feature = "unstable-msc4540")]
626    #[derive(Clone, Debug, Default, Serialize, Deserialize)]
627    #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
628    pub struct AdminCapability {
629        /// The scopes the device may request to access administrative functionality.
630        pub allowed_scopes: BTreeSet<OAuthClientScope>,
631    }
632
633    #[cfg(feature = "unstable-msc4540")]
634    impl AdminCapability {
635        /// Create a new [`AdminCapability`].
636        pub fn new(allowed_scopes: BTreeSet<OAuthClientScope>) -> Self {
637            Self { allowed_scopes }
638        }
639
640        /// Returns whether the capability indicates that the authenticated user
641        /// is able to access some administrative functionality.
642        pub fn is_admin(&self) -> bool {
643            !self.allowed_scopes.is_empty()
644        }
645
646        /// Returns whether the admin functionality gated by a particular scope
647        /// is available to the authenticated user.
648        pub fn is_scope_allowed(&self, scope: &OAuthClientScope) -> bool {
649            self.allowed_scopes.contains(scope)
650        }
651
652        /// Returns whether all fields have their default value.
653        fn is_default(&self) -> bool {
654            let Self { allowed_scopes } = self;
655
656            allowed_scopes.is_empty()
657        }
658    }
659
660    #[cfg(test)]
661    mod tests {
662        use ruma_common::RoomVersionId;
663        #[cfg(feature = "unstable-msc4540")]
664        use ruma_common::api::OAuthClientScope;
665        use serde_json::to_value as to_json_value;
666
667        #[allow(deprecated)]
668        use super::{
669            AccountModerationCapability, Capabilities, ChangePasswordCapability,
670            ForgetForcedUponLeaveCapability, GetLoginTokenCapability, PreviewUrlCapability,
671            ProfileFieldsCapability, RoomVersionStability, RoomVersionsCapability,
672            SetAvatarUrlCapability, SetDisplayNameCapability, ThirdPartyIdChangesCapability,
673        };
674
675        /// Capabilities with every typed field set to a non-default value.
676        #[allow(deprecated)]
677        fn non_default_capabilities() -> Capabilities {
678            Capabilities {
679                change_password: ChangePasswordCapability::new(false),
680                room_versions: RoomVersionsCapability::new(
681                    RoomVersionId::V11,
682                    [(RoomVersionId::V11, RoomVersionStability::Stable)].into(),
683                ),
684                set_displayname: SetDisplayNameCapability::new(false),
685                set_avatar_url: SetAvatarUrlCapability::new(false),
686                thirdparty_id_changes: ThirdPartyIdChangesCapability::new(false),
687                get_login_token: GetLoginTokenCapability::new(true),
688                profile_fields: Some(ProfileFieldsCapability::new(true)),
689                forget_forced_upon_leave: ForgetForcedUponLeaveCapability::new(true),
690                account_moderation: AccountModerationCapability::new(true, true),
691                preview_url: PreviewUrlCapability::new(false),
692                #[cfg(feature = "unstable-msc4540")]
693                admin: super::AdminCapability::new([OAuthClientScope::ApiFullAccess].into()),
694                custom_capabilities: Default::default(),
695            }
696        }
697
698        #[test]
699        fn get_and_set_cover_typed_fields() {
700            let caps = non_default_capabilities();
701            let serialized = to_json_value(&caps).unwrap();
702            let serialized = serialized.as_object().unwrap();
703
704            let mut copy = Capabilities::new();
705            for (name, value) in serialized {
706                assert_eq!(caps.get(name).as_deref(), Some(value), "get({name})");
707                copy.set(name, value.clone()).unwrap();
708            }
709
710            assert!(copy.custom_capabilities.is_empty(), "{:?}", copy.custom_capabilities);
711            assert_eq!(to_json_value(&copy).unwrap(), to_json_value(&caps).unwrap());
712        }
713
714        #[test]
715        fn serialize_deserialize_capabilities() {
716            for mut caps in [Capabilities::new(), non_default_capabilities()] {
717                caps.set("com.example.custom", serde_json::json!({ "enabled": true })).unwrap();
718                let serialized = to_json_value(&caps).unwrap();
719                let deserialized: Capabilities =
720                    serde_json::from_value(serialized.clone()).unwrap();
721
722                assert_eq!(to_json_value(&deserialized).unwrap(), serialized);
723            }
724        }
725
726        #[test]
727        fn deserialize_stable_and_unstable_profile_fields() {
728            let caps: Capabilities = serde_json::from_value(serde_json::json!({
729                "m.profile_fields": { "enabled": true },
730                "uk.tcpip.msc4133.profile_fields": { "enabled": false },
731                "m.room_versions": { "default": "11", "available": { "11": "stable" } },
732            }))
733            .unwrap();
734
735            assert!(caps.profile_fields.unwrap().enabled);
736            assert_eq!(caps.room_versions.default, RoomVersionId::V11);
737            assert!(caps.custom_capabilities.is_empty());
738        }
739
740        #[test]
741        fn deserialize_unstable_profile_fields() {
742            let caps: Capabilities = serde_json::from_value(serde_json::json!({
743                "uk.tcpip.msc4133.profile_fields": { "enabled": true },
744            }))
745            .unwrap();
746
747            assert!(caps.profile_fields.unwrap().enabled);
748        }
749    }
750}