1pub mod v3 {
9 #[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]
47 #[derive(Default)]
48 pub struct Request {}
49
50 #[response]
52 pub struct Response {
53 pub capabilities: Capabilities,
55 }
56
57 impl Request {
58 pub fn new() -> Self {
60 Self {}
61 }
62 }
63
64 impl Response {
65 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 #[derive(Clone, Debug, Default, Serialize)]
79 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
80 #[allow(deprecated)]
81 pub struct Capabilities {
82 #[serde(
84 rename = "m.change_password",
85 default,
86 skip_serializing_if = "ChangePasswordCapability::is_default"
87 )]
88 pub change_password: ChangePasswordCapability,
89
90 #[serde(
92 rename = "m.room_versions",
93 default,
94 skip_serializing_if = "RoomVersionsCapability::is_default"
95 )]
96 pub room_versions: RoomVersionsCapability,
97
98 #[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 #[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 #[serde(
119 rename = "m.3pid_changes",
120 default,
121 skip_serializing_if = "ThirdPartyIdChangesCapability::is_default"
122 )]
123 pub thirdparty_id_changes: ThirdPartyIdChangesCapability,
124
125 #[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 #[serde(rename = "m.profile_fields", skip_serializing_if = "Option::is_none")]
136 pub profile_fields: Option<ProfileFieldsCapability>,
137
138 #[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 #[serde(
151 rename = "m.account_moderation",
152 default,
153 skip_serializing_if = "AccountModerationCapability::is_default"
154 )]
155 pub account_moderation: AccountModerationCapability,
156
157 #[serde(
159 rename = "m.preview_url",
160 default,
161 skip_serializing_if = "PreviewUrlCapability::is_default"
162 )]
163 pub preview_url: PreviewUrlCapability,
164
165 #[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 #[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 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 pub fn new() -> Self {
244 Default::default()
245 }
246
247 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 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 #[derive(Clone, Debug, Serialize, Deserialize)]
317 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
318 pub struct ChangePasswordCapability {
319 pub enabled: bool,
321 }
322
323 impl ChangePasswordCapability {
324 pub fn new(enabled: bool) -> Self {
326 Self { enabled }
327 }
328
329 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 #[derive(Clone, Debug, Serialize, Deserialize)]
343 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
344 pub struct RoomVersionsCapability {
345 pub default: RoomVersionId,
347
348 pub available: BTreeMap<RoomVersionId, RoomVersionStability>,
350 }
351
352 impl RoomVersionsCapability {
353 pub fn new(
356 default: RoomVersionId,
357 available: BTreeMap<RoomVersionId, RoomVersionStability>,
358 ) -> Self {
359 Self { default, available }
360 }
361
362 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 #[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 Stable,
391
392 Unstable,
394
395 #[doc(hidden)]
396 _Custom(PrivOwnedStr),
397 }
398
399 #[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 pub enabled: bool,
406 }
407
408 #[allow(deprecated)]
409 impl SetDisplayNameCapability {
410 pub fn new(enabled: bool) -> Self {
412 Self { enabled }
413 }
414
415 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 #[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 pub enabled: bool,
435 }
436
437 #[allow(deprecated)]
438 impl SetAvatarUrlCapability {
439 pub fn new(enabled: bool) -> Self {
441 Self { enabled }
442 }
443
444 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 #[derive(Clone, Debug, Serialize, Deserialize)]
459 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
460 pub struct ThirdPartyIdChangesCapability {
461 pub enabled: bool,
464 }
465
466 impl ThirdPartyIdChangesCapability {
467 pub fn new(enabled: bool) -> Self {
469 Self { enabled }
470 }
471
472 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 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
486 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
487 pub struct GetLoginTokenCapability {
488 pub enabled: bool,
490 }
491
492 impl GetLoginTokenCapability {
493 pub fn new(enabled: bool) -> Self {
495 Self { enabled }
496 }
497
498 pub fn is_default(&self) -> bool {
500 !self.enabled
501 }
502 }
503
504 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
506 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
507 pub struct ProfileFieldsCapability {
508 pub enabled: bool,
510
511 #[serde(skip_serializing_if = "Option::is_none")]
513 pub allowed: Option<Vec<ProfileFieldName>>,
514
515 #[serde(skip_serializing_if = "Option::is_none")]
519 pub disallowed: Option<Vec<ProfileFieldName>>,
520 }
521
522 impl ProfileFieldsCapability {
523 pub fn new(enabled: bool) -> Self {
525 Self { enabled, allowed: None, disallowed: None }
526 }
527
528 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 true
541 }
542 }
543 }
544
545 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
549 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
550 pub struct ForgetForcedUponLeaveCapability {
551 pub enabled: bool,
556 }
557
558 impl ForgetForcedUponLeaveCapability {
559 pub fn new(enabled: bool) -> Self {
561 Self { enabled }
562 }
563
564 pub fn is_default(&self) -> bool {
566 !self.enabled
567 }
568 }
569
570 #[derive(Clone, Debug, Default, Serialize, Deserialize)]
572 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
573 pub struct AccountModerationCapability {
574 #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
576 pub suspend: bool,
577
578 #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
580 pub lock: bool,
581 }
582
583 impl AccountModerationCapability {
584 pub fn new(suspend: bool, lock: bool) -> Self {
587 Self { suspend, lock }
588 }
589
590 pub fn is_default(&self) -> bool {
592 !self.suspend && !self.lock
593 }
594 }
595
596 #[derive(Clone, Debug, Serialize, Deserialize)]
598 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
599 pub struct PreviewUrlCapability {
600 pub enabled: bool,
602 }
603
604 impl PreviewUrlCapability {
605 pub fn new(enabled: bool) -> Self {
607 Self { enabled }
608 }
609
610 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 #[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 pub allowed_scopes: BTreeSet<OAuthClientScope>,
631 }
632
633 #[cfg(feature = "unstable-msc4540")]
634 impl AdminCapability {
635 pub fn new(allowed_scopes: BTreeSet<OAuthClientScope>) -> Self {
637 Self { allowed_scopes }
638 }
639
640 pub fn is_admin(&self) -> bool {
643 !self.allowed_scopes.is_empty()
644 }
645
646 pub fn is_scope_allowed(&self, scope: &OAuthClientScope) -> bool {
649 self.allowed_scopes.contains(scope)
650 }
651
652 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 #[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(©).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}