Skip to main content

ruma_common/
directory.rs

1//! Common types for room directory endpoints.
2
3use js_int::UInt;
4use serde::{Deserialize, Serialize};
5
6mod filter_room_type_serde;
7mod room_network_serde;
8
9use crate::{
10    OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, PrivOwnedStr,
11    room::{JoinRuleKind, RoomSummary, RoomType},
12};
13
14/// A chunk of a room list response, describing one room.
15///
16/// To create an instance of this type, first create a [`PublicRoomsChunkInit`] and convert it via
17/// `PublicRoomsChunk::from` / `.into()`. It is also possible to construct this type from or convert
18/// it to a [`RoomSummary`].
19#[derive(Clone, Debug, Deserialize, Serialize)]
20#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
21pub struct PublicRoomsChunk {
22    /// The canonical alias of the room, if any.
23    #[serde(skip_serializing_if = "Option::is_none")]
24    #[cfg_attr(
25        feature = "compat-empty-string-null",
26        serde(default, deserialize_with = "crate::serde::empty_string_as_none")
27    )]
28    pub canonical_alias: Option<OwnedRoomAliasId>,
29
30    /// The name of the room, if any.
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub name: Option<String>,
33
34    /// The number of members joined to the room.
35    pub num_joined_members: UInt,
36
37    /// The ID of the room.
38    pub room_id: OwnedRoomId,
39
40    /// The topic of the room, if any.
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub topic: Option<String>,
43
44    /// Whether the room may be viewed by guest users without joining.
45    pub world_readable: bool,
46
47    /// Whether guest users may join the room and participate in it.
48    ///
49    /// If they can, they will be subject to ordinary power level rules like any other user.
50    pub guest_can_join: bool,
51
52    /// The URL for the room's avatar, if one is set.
53    ///
54    /// If you activate the `compat-empty-string-null` feature, this field being an empty string in
55    /// JSON will result in `None` here during deserialization.
56    #[serde(skip_serializing_if = "Option::is_none")]
57    #[cfg_attr(
58        feature = "compat-empty-string-null",
59        serde(default, deserialize_with = "crate::serde::empty_string_as_none")
60    )]
61    pub avatar_url: Option<OwnedMxcUri>,
62
63    /// The join rule of the room.
64    #[serde(default, skip_serializing_if = "crate::serde::is_default")]
65    pub join_rule: JoinRuleKind,
66
67    /// The type of room from `m.room.create`, if any.
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub room_type: Option<RoomType>,
70}
71
72/// Initial set of mandatory fields of `PublicRoomsChunk`.
73///
74/// This struct will not be updated even if additional fields are added to `PublicRoomsChunk` in a
75/// new (non-breaking) release of the Matrix specification.
76#[derive(Debug)]
77#[allow(clippy::exhaustive_structs)]
78pub struct PublicRoomsChunkInit {
79    /// The number of members joined to the room.
80    pub num_joined_members: UInt,
81
82    /// The ID of the room.
83    pub room_id: OwnedRoomId,
84
85    /// Whether the room may be viewed by guest users without joining.
86    pub world_readable: bool,
87
88    /// Whether guest users may join the room and participate in it.
89    ///
90    /// If they can, they will be subject to ordinary power level rules like any other user.
91    pub guest_can_join: bool,
92}
93
94impl From<PublicRoomsChunkInit> for PublicRoomsChunk {
95    fn from(init: PublicRoomsChunkInit) -> Self {
96        let PublicRoomsChunkInit { num_joined_members, room_id, world_readable, guest_can_join } =
97            init;
98
99        Self {
100            canonical_alias: None,
101            name: None,
102            num_joined_members,
103            room_id,
104            topic: None,
105            world_readable,
106            guest_can_join,
107            avatar_url: None,
108            join_rule: JoinRuleKind::default(),
109            room_type: None,
110        }
111    }
112}
113
114impl From<RoomSummary> for PublicRoomsChunk {
115    fn from(value: RoomSummary) -> Self {
116        let RoomSummary {
117            room_id,
118            canonical_alias,
119            name,
120            topic,
121            avatar_url,
122            room_type,
123            num_joined_members,
124            join_rule,
125            world_readable,
126            guest_can_join,
127            ..
128        } = value;
129
130        Self {
131            canonical_alias,
132            name,
133            num_joined_members,
134            room_id,
135            topic,
136            world_readable,
137            guest_can_join,
138            avatar_url,
139            join_rule: join_rule.as_str().into(),
140            room_type,
141        }
142    }
143}
144
145impl From<PublicRoomsChunk> for RoomSummary {
146    fn from(value: PublicRoomsChunk) -> Self {
147        let PublicRoomsChunk {
148            room_id,
149            canonical_alias,
150            name,
151            topic,
152            avatar_url,
153            room_type,
154            num_joined_members,
155            join_rule,
156            world_readable,
157            guest_can_join,
158        } = value;
159
160        Self {
161            canonical_alias,
162            name,
163            num_joined_members,
164            room_id,
165            topic,
166            world_readable,
167            guest_can_join,
168            avatar_url,
169            join_rule: join_rule.into(),
170            room_type,
171            encryption: None,
172            room_version: None,
173        }
174    }
175}
176
177/// A filter for public rooms lists.
178#[derive(Clone, Debug, Default, Deserialize, Serialize)]
179#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
180pub struct Filter {
181    /// A string to search for in the room metadata, e.g. name, topic, canonical alias etc.
182    #[serde(skip_serializing_if = "Option::is_none")]
183    pub generic_search_term: Option<String>,
184
185    /// The room types to include in the results.
186    ///
187    /// Includes all room types if it is empty.
188    ///
189    /// If the `compat-null` feature is enabled, a `null` value is allowed in deserialization, and
190    /// treated the same way as an empty list.
191    #[serde(default, skip_serializing_if = "Vec::is_empty")]
192    #[cfg_attr(feature = "compat-null", serde(deserialize_with = "crate::serde::none_as_default"))]
193    pub room_types: Vec<RoomTypeFilter>,
194}
195
196impl Filter {
197    /// Creates an empty `Filter`.
198    pub fn new() -> Self {
199        Default::default()
200    }
201
202    /// Returns `true` if the filter is empty.
203    pub fn is_empty(&self) -> bool {
204        self.generic_search_term.is_none() && self.room_types.is_empty()
205    }
206}
207
208/// Information about which networks/protocols from application services on the
209/// homeserver from which to request rooms.
210#[derive(Clone, Debug, Default, PartialEq, Eq)]
211#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
212pub enum RoomNetwork {
213    /// Return rooms from the Matrix network.
214    #[default]
215    Matrix,
216
217    /// Return rooms from all the networks/protocols the homeserver knows about.
218    All,
219
220    /// Return rooms from a specific third party network/protocol.
221    ThirdParty(String),
222}
223
224/// An enum of possible room types to filter.
225///
226/// This type can hold an arbitrary string. To build this with a custom value, convert it from an
227/// `Option<string>` with `::from()` / `.into()`. [`RoomTypeFilter::Default`] can be constructed
228/// from `None`.
229///
230/// To check for values that are not available as a documented variant here, use its string
231/// representation, obtained through [`.as_str()`](Self::as_str()).
232#[derive(Clone, Debug, PartialEq, Eq)]
233#[non_exhaustive]
234pub enum RoomTypeFilter {
235    /// The default room type, defined without a `room_type`.
236    Default,
237
238    /// A moderation policy list.
239    Policy,
240
241    /// A space.
242    Space,
243
244    /// A call room as specified in [MSC3417].
245    ///
246    /// [MSC3417]: <https://github.com/matrix-org/matrix-spec-proposals/pull/3417>
247    #[cfg(feature = "unstable-msc3417")]
248    Call,
249
250    /// A custom room type.
251    #[doc(hidden)]
252    _Custom(PrivOwnedStr),
253}
254
255impl RoomTypeFilter {
256    /// Get the string representation of this `RoomTypeFilter`.
257    ///
258    /// [`RoomTypeFilter::Default`] returns `None`.
259    pub fn as_str(&self) -> Option<&str> {
260        match self {
261            RoomTypeFilter::Default => None,
262            RoomTypeFilter::Policy => Some("m.policy"),
263            RoomTypeFilter::Space => Some("m.space"),
264            #[cfg(feature = "unstable-msc3417")]
265            RoomTypeFilter::Call => Some("org.matrix.msc3417.call"),
266            RoomTypeFilter::_Custom(s) => Some(&s.0),
267        }
268    }
269}
270
271impl<T> From<Option<T>> for RoomTypeFilter
272where
273    T: AsRef<str> + Into<Box<str>>,
274{
275    fn from(s: Option<T>) -> Self {
276        match s {
277            None => Self::Default,
278            Some(s) => match s.as_ref() {
279                "m.policy" => Self::Policy,
280                "m.space" => Self::Space,
281                #[cfg(feature = "unstable-msc3417")]
282                "org.matrix.msc3417.call" => Self::Call,
283                _ => Self::_Custom(PrivOwnedStr(s.into())),
284            },
285        }
286    }
287}
288
289impl From<Option<RoomType>> for RoomTypeFilter {
290    fn from(t: Option<RoomType>) -> Self {
291        match t {
292            None => Self::Default,
293            Some(s) => match s {
294                RoomType::Policy => Self::Policy,
295                RoomType::Space => Self::Space,
296                #[cfg(feature = "unstable-msc3417")]
297                RoomType::Call => Self::Call,
298                _ => Self::from(Some(s.as_str())),
299            },
300        }
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use assert_matches::assert_matches;
307    use serde_json::{from_value as from_json_value, json};
308
309    use super::{Filter, RoomNetwork, RoomTypeFilter};
310    use crate::{assert_to_canonical_json_eq, room::RoomType};
311
312    #[test]
313    fn test_from_policy_room_type() {
314        let test = RoomType::Policy;
315        let other: RoomTypeFilter = RoomTypeFilter::from(Some(test));
316        assert_eq!(other, RoomTypeFilter::Policy);
317    }
318
319    #[test]
320    fn test_from_space_room_type() {
321        let test = RoomType::Space;
322        let other: RoomTypeFilter = RoomTypeFilter::from(Some(test));
323        assert_eq!(other, RoomTypeFilter::Space);
324    }
325
326    #[test]
327    #[cfg(feature = "unstable-msc3417")]
328    fn test_from_call_room_type() {
329        let test = RoomType::Call;
330        let other: RoomTypeFilter = RoomTypeFilter::from(Some(test));
331        assert_eq!(other, RoomTypeFilter::Call);
332    }
333
334    #[test]
335    fn serialize_matrix_network_only() {
336        assert_to_canonical_json_eq!(RoomNetwork::Matrix, json!({}));
337    }
338
339    #[test]
340    fn deserialize_matrix_network_only() {
341        let json = json!({ "include_all_networks": false });
342        assert_eq!(from_json_value::<RoomNetwork>(json).unwrap(), RoomNetwork::Matrix);
343    }
344
345    #[test]
346    fn serialize_default_network_is_empty() {
347        assert_to_canonical_json_eq!(RoomNetwork::default(), json!({}));
348    }
349
350    #[test]
351    fn deserialize_empty_network_is_default() {
352        let json = json!({});
353        assert_eq!(from_json_value::<RoomNetwork>(json).unwrap(), RoomNetwork::Matrix);
354    }
355
356    #[test]
357    fn serialize_include_all_networks() {
358        assert_to_canonical_json_eq!(RoomNetwork::All, json!({ "include_all_networks": true }));
359    }
360
361    #[test]
362    fn deserialize_include_all_networks() {
363        let json = json!({ "include_all_networks": true });
364        assert_eq!(from_json_value::<RoomNetwork>(json).unwrap(), RoomNetwork::All);
365    }
366
367    #[test]
368    fn serialize_third_party_network() {
369        assert_to_canonical_json_eq!(
370            RoomNetwork::ThirdParty("freenode".to_owned()),
371            json!({ "third_party_instance_id": "freenode" }),
372        );
373    }
374
375    #[test]
376    fn deserialize_third_party_network() {
377        let json = json!({ "third_party_instance_id": "freenode" });
378        assert_eq!(
379            from_json_value::<RoomNetwork>(json).unwrap(),
380            RoomNetwork::ThirdParty("freenode".into())
381        );
382    }
383
384    #[test]
385    fn deserialize_include_all_networks_and_third_party_exclusivity() {
386        let json = json!({ "include_all_networks": true, "third_party_instance_id": "freenode" });
387        assert_eq!(
388            from_json_value::<RoomNetwork>(json).unwrap_err().to_string(),
389            "`include_all_networks = true` and `third_party_instance_id` are mutually exclusive."
390        );
391    }
392
393    #[test]
394    fn serialize_filter_empty() {
395        assert_to_canonical_json_eq!(Filter::default(), json!({}));
396    }
397
398    #[test]
399    fn deserialize_filter_empty() {
400        let json = json!({});
401        let filter = from_json_value::<Filter>(json).unwrap();
402        assert_eq!(filter.generic_search_term, None);
403        assert_eq!(filter.room_types.len(), 0);
404    }
405
406    #[test]
407    fn serialize_filter_room_types() {
408        let filter = Filter {
409            generic_search_term: None,
410            room_types: vec![
411                RoomTypeFilter::Default,
412                RoomTypeFilter::Policy,
413                RoomTypeFilter::Space,
414                Some("custom_type").into(),
415            ],
416        };
417        assert_to_canonical_json_eq!(
418            filter,
419            json!({ "room_types": [null, "m.policy", "m.space", "custom_type"] }),
420        );
421    }
422
423    #[test]
424    #[cfg(feature = "unstable-msc3417")]
425    fn serialize_filter_call_room_types() {
426        let filter = Filter {
427            generic_search_term: None,
428            room_types: vec![RoomTypeFilter::Default, RoomTypeFilter::Call],
429        };
430        assert_to_canonical_json_eq!(
431            filter,
432            json!({ "room_types": [null, "org.matrix.msc3417.call"] }),
433        );
434    }
435
436    #[test]
437    fn deserialize_filter_room_types() {
438        let json = json!({ "room_types": [null, "m.policy", "m.space", "custom_type"] });
439        let filter = from_json_value::<Filter>(json).unwrap();
440        assert_eq!(filter.room_types.len(), 4);
441        assert_eq!(filter.room_types[0], RoomTypeFilter::Default);
442        assert_eq!(filter.room_types[1], RoomTypeFilter::Policy);
443        assert_eq!(filter.room_types[2], RoomTypeFilter::Space);
444        assert_matches!(&filter.room_types[3], RoomTypeFilter::_Custom(_));
445        assert_eq!(filter.room_types[3].as_str(), Some("custom_type"));
446    }
447
448    #[test]
449    #[cfg(feature = "unstable-msc3417")]
450    fn deserialize_filter_call_room_types() {
451        let json = json!({ "room_types": [null, "m.space", "org.matrix.msc3417.call"] });
452        let filter = from_json_value::<Filter>(json).unwrap();
453        assert_eq!(filter.room_types.len(), 3);
454        assert_eq!(filter.room_types[0], RoomTypeFilter::Default);
455        assert_eq!(filter.room_types[1], RoomTypeFilter::Space);
456        assert_matches!(&filter.room_types[2], RoomTypeFilter::Call);
457    }
458}