Skip to main content

ruma_common/
room.rs

1//! Common types for rooms.
2
3use std::borrow::Cow;
4
5use as_variant::as_variant;
6use js_int::UInt;
7use serde::{Deserialize, Serialize, de};
8use serde_json::{Value as JsonValue, value::RawValue as RawJsonValue};
9
10use crate::{
11    EventEncryptionAlgorithm, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, PrivOwnedStr,
12    RoomVersionId,
13    serde::{JsonObject, StringEnum, from_raw_json_value},
14};
15
16/// An enum of possible room types.
17#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
18#[derive(Clone, StringEnum)]
19#[non_exhaustive]
20pub enum RoomType {
21    /// Defines the room as a moderation policy list.
22    #[ruma_enum(rename = "m.policy")]
23    Policy,
24
25    /// Defines the room as a space.
26    #[ruma_enum(rename = "m.space")]
27    Space,
28
29    /// Defines the room as a call.
30    ///
31    /// This uses the unstable prefix in
32    /// [MSC3417](https://github.com/matrix-org/matrix-spec-proposals/pull/3417).
33    #[cfg(feature = "unstable-msc3417")]
34    #[ruma_enum(rename = "org.matrix.msc3417.call")]
35    Call,
36
37    /// Defines the room as a custom type.
38    #[doc(hidden)]
39    _Custom(PrivOwnedStr),
40}
41
42/// The rule used for users wishing to join this room.
43///
44/// This type can hold an arbitrary join rule. To check for values that are not available as a
45/// documented variant here, get its kind with [`.kind()`](Self::kind) or its string representation
46/// with [`.as_str()`](Self::as_str), and its associated data with [`.data()`](Self::data).
47#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
48#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
49#[serde(tag = "join_rule", rename_all = "snake_case")]
50pub enum JoinRule {
51    /// A user who wishes to join the room must first receive an invite to the room from someone
52    /// already inside of the room.
53    Invite,
54
55    /// Users can join the room if they are invited, or they can request an invite to the room.
56    ///
57    /// They can be allowed (invited) or denied (kicked/banned) access.
58    Knock,
59
60    /// Reserved but not yet implemented by the Matrix specification.
61    Private,
62
63    /// Users can join the room if they are invited, or if they meet any of the conditions
64    /// described in a set of [`AllowRule`]s.
65    Restricted(Restricted),
66
67    /// Users can join the room if they are invited, or if they meet any of the conditions
68    /// described in a set of [`AllowRule`]s, or they can request an invite to the room.
69    KnockRestricted(Restricted),
70
71    /// Anyone can join the room without any prior action.
72    Public,
73
74    #[doc(hidden)]
75    #[serde(untagged)]
76    _Custom(CustomJoinRule),
77}
78
79impl JoinRule {
80    /// Returns the kind of this `JoinRule`.
81    pub fn kind(&self) -> JoinRuleKind {
82        match self {
83            Self::Invite => JoinRuleKind::Invite,
84            Self::Knock => JoinRuleKind::Knock,
85            Self::Private => JoinRuleKind::Private,
86            Self::Restricted(_) => JoinRuleKind::Restricted,
87            Self::KnockRestricted(_) => JoinRuleKind::KnockRestricted,
88            Self::Public => JoinRuleKind::Public,
89            Self::_Custom(CustomJoinRule { join_rule, .. }) => {
90                JoinRuleKind::_Custom(PrivOwnedStr(join_rule.as_str().into()))
91            }
92        }
93    }
94
95    /// Returns the string name of this `JoinRule`
96    pub fn as_str(&self) -> &str {
97        match self {
98            JoinRule::Invite => "invite",
99            JoinRule::Knock => "knock",
100            JoinRule::Private => "private",
101            JoinRule::Restricted(_) => "restricted",
102            JoinRule::KnockRestricted(_) => "knock_restricted",
103            JoinRule::Public => "public",
104            JoinRule::_Custom(CustomJoinRule { join_rule, .. }) => join_rule,
105        }
106    }
107
108    /// Returns the associated data of this `JoinRule`.
109    ///
110    /// The returned JSON object won't contain the `join_rule` field, use
111    /// [`.kind()`](Self::kind) or [`.as_str()`](Self::as_str) to access those.
112    ///
113    /// Prefer to use the public variants of `JoinRule` where possible; this method is meant to
114    /// be used for custom join rules only.
115    pub fn data(&self) -> Cow<'_, JsonObject> {
116        fn serialize<T: Serialize>(obj: &T) -> JsonObject {
117            match serde_json::to_value(obj).expect("join rule serialization should succeed") {
118                JsonValue::Object(mut obj) => {
119                    obj.remove("body");
120                    obj
121                }
122                _ => panic!("all message types should serialize to objects"),
123            }
124        }
125
126        match self {
127            JoinRule::Invite | JoinRule::Knock | JoinRule::Private | JoinRule::Public => {
128                Cow::Owned(JsonObject::new())
129            }
130            JoinRule::Restricted(restricted) | JoinRule::KnockRestricted(restricted) => {
131                Cow::Owned(serialize(restricted))
132            }
133            Self::_Custom(c) => Cow::Borrowed(&c.data),
134        }
135    }
136}
137
138impl<'de> Deserialize<'de> for JoinRule {
139    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
140    where
141        D: de::Deserializer<'de>,
142    {
143        let json: Box<RawJsonValue> = Box::deserialize(deserializer)?;
144
145        #[derive(Deserialize)]
146        struct ExtractType<'a> {
147            #[serde(borrow)]
148            join_rule: Cow<'a, str>,
149        }
150
151        let ExtractType { join_rule } = from_raw_json_value(&json)?;
152
153        match join_rule.as_ref() {
154            "invite" => Ok(Self::Invite),
155            "knock" => Ok(Self::Knock),
156            "private" => Ok(Self::Private),
157            "restricted" => from_raw_json_value(&json).map(Self::Restricted),
158            "knock_restricted" => from_raw_json_value(&json).map(Self::KnockRestricted),
159            "public" => Ok(Self::Public),
160            _ => {
161                let mut data = from_raw_json_value::<JsonObject, _>(&json)?;
162                let join_rule = as_variant!(
163                    data.remove("join_rule")
164                        .expect("we already checked that the join_rule field is present"),
165                    JsonValue::String
166                )
167                .expect("we already checked that the join rule is a string");
168
169                Ok(Self::_Custom(CustomJoinRule { join_rule, data }))
170            }
171        }
172    }
173}
174
175/// The payload for an unsupported join rule.
176#[doc(hidden)]
177#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
178pub struct CustomJoinRule {
179    /// The kind of join rule.
180    join_rule: String,
181
182    /// The remaining data.
183    #[serde(flatten)]
184    data: JsonObject,
185}
186
187/// Configuration of the `Restricted` join rule.
188#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
189#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
190pub struct Restricted {
191    /// Allow rules which describe conditions that allow joining a room.
192    #[serde(default, deserialize_with = "crate::serde::ignore_invalid_sequence_items")]
193    pub allow: Vec<AllowRule>,
194}
195
196impl Restricted {
197    /// Constructs a new rule set for restricted rooms with the given rules.
198    pub fn new(allow: Vec<AllowRule>) -> Self {
199        Self { allow }
200    }
201}
202
203/// An allow rule which defines a condition that allows joining a room.
204#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
205#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
206#[serde(untagged)]
207pub enum AllowRule {
208    /// Joining is allowed if a user is already a member of the room with the id `room_id`.
209    RoomMembership(RoomMembership),
210
211    #[doc(hidden)]
212    _Custom(CustomAllowRule),
213}
214
215impl AllowRule {
216    /// Constructs an `AllowRule` with membership of the room with the given id as its predicate.
217    pub fn room_membership(room_id: OwnedRoomId) -> Self {
218        Self::RoomMembership(RoomMembership::new(room_id))
219    }
220
221    /// Returns the string name of this `AllowRule`.
222    pub fn rule_type(&self) -> &str {
223        match self {
224            AllowRule::RoomMembership(_) => "m.room_membership",
225            AllowRule::_Custom(CustomAllowRule { rule_type, .. }) => rule_type,
226        }
227    }
228
229    /// Returns the associated data of this `AllowRule`.
230    ///
231    /// The returned JSON object won't contain the `type` field, use
232    /// [`Self::rule_type`] to access that.
233    ///
234    /// Prefer to use the public variants of `AllowRule` where possible; this method is meant to
235    /// be used for custom allow rules only.
236    pub fn data(&self) -> Cow<'_, JsonObject> {
237        fn serialize<T: Serialize>(obj: &T) -> JsonObject {
238            match serde_json::to_value(obj).expect("join rule serialization should succeed") {
239                JsonValue::Object(obj) => obj,
240                _ => panic!("all message types should serialize to objects"),
241            }
242        }
243
244        match self {
245            AllowRule::RoomMembership(membership) => Cow::Owned(serialize(membership)),
246            Self::_Custom(custom) => Cow::Borrowed(&custom.data),
247        }
248    }
249}
250
251/// Allow rule which grants permission to join based on the membership of another room.
252#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
253#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
254#[serde(tag = "type", rename = "m.room_membership")]
255pub struct RoomMembership {
256    /// The id of the room which being a member of grants permission to join another room.
257    pub room_id: OwnedRoomId,
258}
259
260impl RoomMembership {
261    /// Constructs a new room membership rule for the given room id.
262    pub fn new(room_id: OwnedRoomId) -> Self {
263        Self { room_id }
264    }
265}
266
267#[doc(hidden)]
268#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
269#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
270pub struct CustomAllowRule {
271    /// The type of the allow rule.
272    #[serde(rename = "type")]
273    rule_type: String,
274
275    /// The remaining data.
276    #[serde(flatten)]
277    data: JsonObject,
278}
279
280impl<'de> Deserialize<'de> for AllowRule {
281    fn deserialize<D>(deserializer: D) -> Result<AllowRule, D::Error>
282    where
283        D: de::Deserializer<'de>,
284    {
285        let json: Box<RawJsonValue> = Box::deserialize(deserializer)?;
286
287        // Extracts the `type` value.
288        #[derive(Deserialize)]
289        struct ExtractType<'a> {
290            #[serde(borrow, rename = "type")]
291            rule_type: Cow<'a, str>,
292        }
293
294        // Get the value of `type` if present.
295        let ExtractType { rule_type } = from_raw_json_value(&json)?;
296
297        match rule_type.as_ref() {
298            "m.room_membership" => from_raw_json_value(&json).map(Self::RoomMembership),
299            _ => {
300                let mut data = from_raw_json_value::<JsonObject, _>(&json)?;
301                let rule_type = as_variant!(
302                    data.remove("type").expect("we already checked that the type field is present"),
303                    JsonValue::String
304                )
305                .expect("we already checked that the type is a string");
306
307                Ok(Self::_Custom(CustomAllowRule { rule_type, data }))
308            }
309        }
310    }
311}
312
313/// The kind of rule used for users wishing to join this room.
314#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
315#[derive(Clone, Default, StringEnum)]
316#[ruma_enum(rename_all = "snake_case")]
317#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
318pub enum JoinRuleKind {
319    /// A user who wishes to join the room must first receive an invite to the room from someone
320    /// already inside of the room.
321    Invite,
322
323    /// Users can join the room if they are invited, or they can request an invite to the room.
324    ///
325    /// They can be allowed (invited) or denied (kicked/banned) access.
326    Knock,
327
328    /// Reserved but not yet implemented by the Matrix specification.
329    Private,
330
331    /// Users can join the room if they are invited, or if they meet any of the conditions
332    /// described in a set of rules.
333    Restricted,
334
335    /// Users can join the room if they are invited, or if they meet any of the conditions
336    /// described in a set of rules, or they can request an invite to the room.
337    KnockRestricted,
338
339    /// Anyone can join the room without any prior action.
340    #[default]
341    Public,
342
343    #[doc(hidden)]
344    _Custom(PrivOwnedStr),
345}
346
347impl From<JoinRuleKind> for JoinRuleSummary {
348    fn from(value: JoinRuleKind) -> Self {
349        match value {
350            JoinRuleKind::Invite => Self::Invite,
351            JoinRuleKind::Knock => Self::Knock,
352            JoinRuleKind::Private => Self::Private,
353            JoinRuleKind::Restricted => Self::Restricted(Default::default()),
354            JoinRuleKind::KnockRestricted => Self::KnockRestricted(Default::default()),
355            JoinRuleKind::Public => Self::Public,
356            JoinRuleKind::_Custom(s) => Self::_Custom(s),
357        }
358    }
359}
360
361/// The summary of a room's state.
362#[derive(Debug, Clone, Serialize)]
363#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
364pub struct RoomSummary {
365    /// The ID of the room.
366    pub room_id: OwnedRoomId,
367
368    /// The canonical alias of the room, if any.
369    ///
370    /// If the `compat-empty-string-null` cargo feature is enabled, this field being an empty
371    /// string in JSON will result in `None` here during deserialization.
372    #[serde(skip_serializing_if = "Option::is_none")]
373    pub canonical_alias: Option<OwnedRoomAliasId>,
374
375    /// The name of the room, if any.
376    #[serde(skip_serializing_if = "Option::is_none")]
377    pub name: Option<String>,
378
379    /// The topic of the room, if any.
380    #[serde(skip_serializing_if = "Option::is_none")]
381    pub topic: Option<String>,
382
383    /// The URL for the room's avatar, if one is set.
384    ///
385    /// If you activate the `compat-empty-string-null` feature, this field being an empty string in
386    /// JSON will result in `None` here during deserialization.
387    #[serde(skip_serializing_if = "Option::is_none")]
388    pub avatar_url: Option<OwnedMxcUri>,
389
390    /// The type of room from `m.room.create`, if any.
391    #[serde(skip_serializing_if = "Option::is_none")]
392    pub room_type: Option<RoomType>,
393
394    /// The number of members joined to the room.
395    pub num_joined_members: UInt,
396
397    /// The join rule of the room.
398    #[serde(flatten, skip_serializing_if = "ruma_common::serde::is_default")]
399    pub join_rule: JoinRuleSummary,
400
401    /// Whether the room may be viewed by users without joining.
402    pub world_readable: bool,
403
404    /// Whether guest users may join the room and participate in it.
405    ///
406    /// If they can, they will be subject to ordinary power level rules like any other user.
407    pub guest_can_join: bool,
408
409    /// If the room is encrypted, the algorithm used for this room.
410    #[serde(skip_serializing_if = "Option::is_none")]
411    pub encryption: Option<EventEncryptionAlgorithm>,
412
413    /// The version of the room.
414    #[serde(skip_serializing_if = "Option::is_none")]
415    pub room_version: Option<RoomVersionId>,
416}
417
418impl RoomSummary {
419    /// Construct a new `RoomSummary` with the given required fields.
420    pub fn new(
421        room_id: OwnedRoomId,
422        join_rule: JoinRuleSummary,
423        guest_can_join: bool,
424        num_joined_members: UInt,
425        world_readable: bool,
426    ) -> Self {
427        Self {
428            room_id,
429            canonical_alias: None,
430            name: None,
431            topic: None,
432            avatar_url: None,
433            room_type: None,
434            num_joined_members,
435            join_rule,
436            world_readable,
437            guest_can_join,
438            encryption: None,
439            room_version: None,
440        }
441    }
442}
443
444impl<'de> Deserialize<'de> for RoomSummary {
445    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
446    where
447        D: de::Deserializer<'de>,
448    {
449        /// Helper type to deserialize [`RoomSummary`] because using `flatten` on `join_rule`
450        /// returns an error.
451        #[derive(Deserialize)]
452        struct RoomSummaryDeHelper {
453            room_id: OwnedRoomId,
454            #[cfg_attr(
455                feature = "compat-empty-string-null",
456                serde(default, deserialize_with = "ruma_common::serde::empty_string_as_none")
457            )]
458            canonical_alias: Option<OwnedRoomAliasId>,
459            name: Option<String>,
460            topic: Option<String>,
461            #[cfg_attr(
462                feature = "compat-empty-string-null",
463                serde(default, deserialize_with = "ruma_common::serde::empty_string_as_none")
464            )]
465            avatar_url: Option<OwnedMxcUri>,
466            room_type: Option<RoomType>,
467            num_joined_members: UInt,
468            world_readable: bool,
469            guest_can_join: bool,
470            encryption: Option<EventEncryptionAlgorithm>,
471            room_version: Option<RoomVersionId>,
472        }
473
474        let json = Box::<RawJsonValue>::deserialize(deserializer)?;
475        let RoomSummaryDeHelper {
476            room_id,
477            canonical_alias,
478            name,
479            topic,
480            avatar_url,
481            room_type,
482            num_joined_members,
483            world_readable,
484            guest_can_join,
485            encryption,
486            room_version,
487        } = from_raw_json_value(&json)?;
488        let join_rule: JoinRuleSummary = from_raw_json_value(&json)?;
489
490        Ok(Self {
491            room_id,
492            canonical_alias,
493            name,
494            topic,
495            avatar_url,
496            room_type,
497            num_joined_members,
498            join_rule,
499            world_readable,
500            guest_can_join,
501            encryption,
502            room_version,
503        })
504    }
505}
506
507/// The rule used for users wishing to join a room.
508///
509/// In contrast to the regular [`JoinRule`], this enum holds only simplified conditions for joining
510/// restricted rooms.
511///
512/// This type can hold an arbitrary join rule. To check for values that are not available as a
513/// documented variant here, get its kind with `.kind()` or use its string representation, obtained
514/// through `.as_str()`.
515///
516/// Because this type contains a few neighbouring fields instead of a whole object, and it is not
517/// possible to know which fields to parse for unknown variants, this type will fail to serialize if
518/// it doesn't match one of the documented variants. It is only possible to construct an
519/// undocumented variant by deserializing it, so do not re-serialize this type.
520#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
521#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
522#[serde(tag = "join_rule", rename_all = "snake_case")]
523pub enum JoinRuleSummary {
524    /// A user who wishes to join the room must first receive an invite to the room from someone
525    /// already inside of the room.
526    Invite,
527
528    /// Users can join the room if they are invited, or they can request an invite to the room.
529    ///
530    /// They can be allowed (invited) or denied (kicked/banned) access.
531    Knock,
532
533    /// Reserved but not yet implemented by the Matrix specification.
534    Private,
535
536    /// Users can join the room if they are invited, or if they meet one of the conditions
537    /// described in the [`RestrictedSummary`].
538    Restricted(RestrictedSummary),
539
540    /// Users can join the room if they are invited, or if they meet one of the conditions
541    /// described in the [`RestrictedSummary`], or they can request an invite to the room.
542    KnockRestricted(RestrictedSummary),
543
544    /// Anyone can join the room without any prior action.
545    #[default]
546    Public,
547
548    #[doc(hidden)]
549    #[serde(skip_serializing)]
550    _Custom(PrivOwnedStr),
551}
552
553impl JoinRuleSummary {
554    /// Returns the kind of this `JoinRuleSummary`.
555    pub fn kind(&self) -> JoinRuleKind {
556        match self {
557            Self::Invite => JoinRuleKind::Invite,
558            Self::Knock => JoinRuleKind::Knock,
559            Self::Private => JoinRuleKind::Private,
560            Self::Restricted(_) => JoinRuleKind::Restricted,
561            Self::KnockRestricted(_) => JoinRuleKind::KnockRestricted,
562            Self::Public => JoinRuleKind::Public,
563            Self::_Custom(rule) => JoinRuleKind::_Custom(rule.clone()),
564        }
565    }
566
567    /// Returns the string name of this `JoinRuleSummary`.
568    pub fn as_str(&self) -> &str {
569        match self {
570            Self::Invite => "invite",
571            Self::Knock => "knock",
572            Self::Private => "private",
573            Self::Restricted(_) => "restricted",
574            Self::KnockRestricted(_) => "knock_restricted",
575            Self::Public => "public",
576            Self::_Custom(rule) => &rule.0,
577        }
578    }
579}
580
581impl From<JoinRule> for JoinRuleSummary {
582    fn from(value: JoinRule) -> Self {
583        match value {
584            JoinRule::Invite => Self::Invite,
585            JoinRule::Knock => Self::Knock,
586            JoinRule::Private => Self::Private,
587            JoinRule::Restricted(restricted) => Self::Restricted(restricted.into()),
588            JoinRule::KnockRestricted(restricted) => Self::KnockRestricted(restricted.into()),
589            JoinRule::Public => Self::Public,
590            JoinRule::_Custom(CustomJoinRule { join_rule, .. }) => {
591                Self::_Custom(PrivOwnedStr(join_rule.into()))
592            }
593        }
594    }
595}
596
597impl<'de> Deserialize<'de> for JoinRuleSummary {
598    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
599    where
600        D: de::Deserializer<'de>,
601    {
602        let json: Box<RawJsonValue> = Box::deserialize(deserializer)?;
603
604        #[derive(Deserialize)]
605        struct ExtractType<'a> {
606            #[serde(borrow)]
607            join_rule: Option<Cow<'a, str>>,
608        }
609
610        let Some(join_rule) = serde_json::from_str::<ExtractType<'_>>(json.get())
611            .map_err(de::Error::custom)?
612            .join_rule
613        else {
614            return Ok(Self::default());
615        };
616
617        match join_rule.as_ref() {
618            "invite" => Ok(Self::Invite),
619            "knock" => Ok(Self::Knock),
620            "private" => Ok(Self::Private),
621            "restricted" => from_raw_json_value(&json).map(Self::Restricted),
622            "knock_restricted" => from_raw_json_value(&json).map(Self::KnockRestricted),
623            "public" => Ok(Self::Public),
624            _ => Ok(Self::_Custom(PrivOwnedStr(join_rule.into()))),
625        }
626    }
627}
628
629/// A summary of the conditions for joining a restricted room.
630#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
631#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
632pub struct RestrictedSummary {
633    /// The room IDs which are specified by the join rules.
634    #[serde(default)]
635    pub allowed_room_ids: Vec<OwnedRoomId>,
636}
637
638impl RestrictedSummary {
639    /// Constructs a new `RestrictedSummary` with the given room IDs.
640    pub fn new(allowed_room_ids: Vec<OwnedRoomId>) -> Self {
641        Self { allowed_room_ids }
642    }
643}
644
645impl From<Restricted> for RestrictedSummary {
646    fn from(value: Restricted) -> Self {
647        let allowed_room_ids = value
648            .allow
649            .into_iter()
650            .filter_map(|allow_rule| {
651                let membership = as_variant!(allow_rule, AllowRule::RoomMembership)?;
652                Some(membership.room_id)
653            })
654            .collect();
655
656        Self::new(allowed_room_ids)
657    }
658}
659
660#[cfg(test)]
661mod tests {
662    use assert_matches::assert_matches;
663    use js_int::uint;
664    use ruma_common::{OwnedRoomId, owned_room_id};
665    use serde_json::{from_value as from_json_value, json};
666    use strass::assert_let;
667
668    use super::{
669        AllowRule, CustomAllowRule, JoinRule, JoinRuleSummary, Restricted, RestrictedSummary,
670        RoomMembership, RoomSummary,
671    };
672    use crate::{assert_to_canonical_json_eq, serde::JsonObject};
673
674    #[test]
675    fn deserialize_summary_no_join_rule() {
676        let json = json!({
677            "room_id": "!room:localhost",
678            "num_joined_members": 5,
679            "world_readable": false,
680            "guest_can_join": false,
681        });
682
683        let summary: RoomSummary = from_json_value(json).unwrap();
684        assert_eq!(summary.room_id, "!room:localhost");
685        assert_eq!(summary.num_joined_members, uint!(5));
686        assert!(!summary.world_readable);
687        assert!(!summary.guest_can_join);
688        assert_matches!(summary.join_rule, JoinRuleSummary::Public);
689    }
690
691    #[test]
692    fn deserialize_summary_private_join_rule() {
693        let json = json!({
694            "room_id": "!room:localhost",
695            "num_joined_members": 5,
696            "world_readable": false,
697            "guest_can_join": false,
698            "join_rule": "private",
699        });
700
701        let summary: RoomSummary = from_json_value(json).unwrap();
702        assert_eq!(summary.room_id, "!room:localhost");
703        assert_eq!(summary.num_joined_members, uint!(5));
704        assert!(!summary.world_readable);
705        assert!(!summary.guest_can_join);
706        assert_matches!(summary.join_rule, JoinRuleSummary::Private);
707    }
708
709    #[test]
710    fn deserialize_summary_restricted_join_rule() {
711        let json = json!({
712            "room_id": "!room:localhost",
713            "num_joined_members": 5,
714            "world_readable": false,
715            "guest_can_join": false,
716            "join_rule": "restricted",
717            "allowed_room_ids": ["!otherroom:localhost"],
718        });
719
720        let summary: RoomSummary = from_json_value(json).unwrap();
721        assert_eq!(summary.room_id, "!room:localhost");
722        assert_eq!(summary.num_joined_members, uint!(5));
723        assert!(!summary.world_readable);
724        assert!(!summary.guest_can_join);
725        assert_let!(JoinRuleSummary::Restricted(restricted) = summary.join_rule);
726        assert_eq!(restricted.allowed_room_ids.len(), 1);
727    }
728
729    #[test]
730    fn deserialize_summary_restricted_join_rule_no_allowed_room_ids() {
731        let json = json!({
732            "room_id": "!room:localhost",
733            "num_joined_members": 5,
734            "world_readable": false,
735            "guest_can_join": false,
736            "join_rule": "restricted",
737        });
738
739        let summary: RoomSummary = from_json_value(json).unwrap();
740        assert_eq!(summary.room_id, "!room:localhost");
741        assert_eq!(summary.num_joined_members, uint!(5));
742        assert!(!summary.world_readable);
743        assert!(!summary.guest_can_join);
744        assert_let!(JoinRuleSummary::Restricted(restricted) = summary.join_rule);
745        assert_eq!(restricted.allowed_room_ids.len(), 0);
746    }
747
748    #[test]
749    fn serialize_summary_knock_join_rule() {
750        let summary = RoomSummary::new(
751            owned_room_id!("!room:localhost"),
752            JoinRuleSummary::Knock,
753            false,
754            uint!(5),
755            false,
756        );
757
758        assert_to_canonical_json_eq!(
759            summary,
760            json!({
761                "room_id": "!room:localhost",
762                "num_joined_members": 5,
763                "world_readable": false,
764                "guest_can_join": false,
765                "join_rule": "knock",
766            })
767        );
768    }
769
770    #[test]
771    fn serialize_summary_restricted_join_rule() {
772        let summary = RoomSummary::new(
773            owned_room_id!("!room:localhost"),
774            JoinRuleSummary::Restricted(RestrictedSummary::new(vec![owned_room_id!(
775                "!otherroom:localhost"
776            )])),
777            false,
778            uint!(5),
779            false,
780        );
781
782        assert_to_canonical_json_eq!(
783            summary,
784            json!({
785                "room_id": "!room:localhost",
786                "num_joined_members": 5,
787                "world_readable": false,
788                "guest_can_join": false,
789                "join_rule": "restricted",
790                "allowed_room_ids": ["!otherroom:localhost"],
791            })
792        );
793    }
794
795    #[test]
796    fn custom_join_rule_serialize_roundtrip() {
797        let json = json!({
798            "join_rule": "local.dev.unicorns",
799            "rainbows": true,
800        });
801
802        let join_rule = from_json_value::<JoinRule>(json.clone()).unwrap();
803        assert_eq!(join_rule.kind().as_str(), "local.dev.unicorns");
804        let data = &*join_rule.data();
805        assert_eq!(data.len(), 1);
806        assert_eq!(data["rainbows"], true);
807
808        assert_to_canonical_json_eq!(join_rule, json);
809    }
810
811    #[test]
812    fn join_rule_to_join_rule_summary() {
813        assert_eq!(JoinRuleSummary::Invite, JoinRule::Invite.into());
814        assert_eq!(JoinRuleSummary::Knock, JoinRule::Knock.into());
815        assert_eq!(JoinRuleSummary::Public, JoinRule::Public.into());
816        assert_eq!(JoinRuleSummary::Private, JoinRule::Private.into());
817
818        assert_let!(
819            JoinRuleSummary::KnockRestricted(restricted) =
820                JoinRule::KnockRestricted(Restricted::default()).into()
821        );
822        assert_eq!(restricted.allowed_room_ids, &[] as &[OwnedRoomId]);
823
824        let room_id = owned_room_id!("!room:localhost");
825        assert_let!(
826            JoinRuleSummary::Restricted(restricted) =
827                JoinRule::Restricted(Restricted::new(vec![AllowRule::RoomMembership(
828                    RoomMembership::new(room_id.clone())
829                )]))
830                .into()
831        );
832        assert_eq!(restricted.allowed_room_ids, [room_id]);
833    }
834
835    #[test]
836    fn roundtrip_custom_allow_rule() {
837        let json = json!({ "type": "org.msc9000.something", "foo": "bar"});
838
839        let allow_rule: AllowRule = from_json_value(json.clone()).unwrap();
840        assert_eq!(allow_rule.rule_type(), "org.msc9000.something");
841        let data = &*allow_rule.data();
842        assert_eq!(data.len(), 1);
843        assert_eq!(data["foo"], "bar");
844
845        assert_to_canonical_json_eq!(allow_rule, json);
846    }
847
848    #[test]
849    fn invalid_allow_items() {
850        let json = r#"{
851            "join_rule": "restricted",
852            "allow": [
853                {
854                    "type": "m.room_membership",
855                    "room_id": "!mods:example.org"
856                },
857                {
858                    "type": "m.room_membership",
859                    "room_id": ""
860                },
861                {
862                    "type": "m.room_membership",
863                    "room_id": "not a room id"
864                },
865                {
866                    "type": "org.example.custom",
867                    "org.example.minimum_role": "developer"
868                },
869                {
870                    "not even close": "to being correct",
871                    "any object": "passes this test",
872                    "only non-objects in this array": "cause deserialization to fail"
873                }
874            ]
875        }"#;
876        let join_rule: JoinRule = serde_json::from_str(json).unwrap();
877
878        assert_let!(JoinRule::Restricted(restricted) = join_rule);
879        assert_eq!(
880            restricted.allow,
881            &[
882                AllowRule::room_membership(owned_room_id!("!mods:example.org")),
883                AllowRule::_Custom(CustomAllowRule {
884                    rule_type: "org.example.custom".into(),
885                    data: JsonObject::from_iter([(
886                        "org.example.minimum_role".to_owned(),
887                        "developer".into()
888                    )]),
889                })
890            ]
891        );
892    }
893}