matrix_sdk/room/
privacy_settings.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use matrix_sdk_base::Room as BaseRoom;
use ruma::{
    api::client::{
        directory::{get_room_visibility, set_room_visibility},
        room::Visibility,
        state::send_state_event,
    },
    assign,
    events::{
        room::{
            canonical_alias::RoomCanonicalAliasEventContent,
            history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
            join_rules::{JoinRule, RoomJoinRulesEventContent},
        },
        EmptyStateKey,
    },
    OwnedRoomAliasId, RoomAliasId,
};

use crate::{Client, Result};

/// A helper to group the methods in [Room](crate::Room) related to the room's
/// visibility and access.
#[derive(Debug)]
pub struct RoomPrivacySettings<'a> {
    room: &'a BaseRoom,
    client: &'a Client,
}

impl<'a> RoomPrivacySettings<'a> {
    pub(crate) fn new(room: &'a BaseRoom, client: &'a Client) -> Self {
        Self { room, client }
    }

    /// Publish a new room alias for this room in the room directory.
    ///
    /// Returns:
    /// - `true` if the room alias didn't exist and it's now published.
    /// - `false` if the room alias was already present so it couldn't be
    ///   published.
    pub async fn publish_room_alias_in_room_directory(
        &'a self,
        alias: &RoomAliasId,
    ) -> Result<bool> {
        if self.client.is_room_alias_available(alias).await? {
            self.client.create_room_alias(alias, self.room.room_id()).await?;
            return Ok(true);
        }

        Ok(false)
    }

    /// Remove an existing room alias for this room in the room directory.
    ///
    /// Returns:
    /// - `true` if the room alias was present and it's now removed from the
    ///   room directory.
    /// - `false` if the room alias didn't exist so it couldn't be removed.
    pub async fn remove_room_alias_from_room_directory(
        &'a self,
        alias: &RoomAliasId,
    ) -> Result<bool> {
        if self.client.resolve_room_alias(alias).await.is_ok() {
            self.client.remove_room_alias(alias).await?;
            return Ok(true);
        }

        Ok(false)
    }

    /// Update the canonical alias of the room.
    ///
    /// # Arguments:
    /// * `alias` - The new main alias to use for the room. A `None` value
    ///   removes the existing main canonical alias.
    /// * `alt_aliases` - The list of alternative aliases for this room.
    ///
    /// See <https://spec.matrix.org/v1.12/client-server-api/#mroomcanonical_alias> for more info about the canonical alias.
    ///
    /// Note that publishing the alias in the room directory is done separately,
    /// and a room alias must have already been published before it can be set
    /// as the canonical alias.
    pub async fn update_canonical_alias(
        &'a self,
        alias: Option<OwnedRoomAliasId>,
        alt_aliases: Vec<OwnedRoomAliasId>,
    ) -> Result<()> {
        // Create a new alias event combining both the new and previous values
        let content = assign!(
            RoomCanonicalAliasEventContent::new(),
            { alias, alt_aliases }
        );

        // Send the state event
        let request = send_state_event::v3::Request::new(
            self.room.room_id().to_owned(),
            &EmptyStateKey,
            &content,
        )?;
        self.client.send(request).await?;

        Ok(())
    }

    /// Update room history visibility for this room.
    ///
    /// The history visibility controls whether a user can see the events that
    /// happened in a room before they joined.
    ///
    /// See <https://spec.matrix.org/v1.12/client-server-api/#mroomcanonical_alias> for more info.
    pub async fn update_room_history_visibility(
        &'a self,
        new_value: HistoryVisibility,
    ) -> Result<()> {
        let request = send_state_event::v3::Request::new(
            self.room.room_id().to_owned(),
            &EmptyStateKey,
            &RoomHistoryVisibilityEventContent::new(new_value),
        )?;
        self.client.send(request).await?;
        Ok(())
    }

    /// Update the join rule for this room.
    ///
    /// The join rules controls if and how a new user can get access to the
    /// room.
    ///
    /// See <https://spec.matrix.org/v1.12/client-server-api/#mroomjoin_rules> for more info.
    pub async fn update_join_rule(&'a self, new_rule: JoinRule) -> Result<()> {
        let request = send_state_event::v3::Request::new(
            self.room.room_id().to_owned(),
            &EmptyStateKey,
            &RoomJoinRulesEventContent::new(new_rule),
        )?;
        self.client.send(request).await?;
        Ok(())
    }

    /// Returns the visibility for this room in the room directory.
    ///
    /// [Public](`Visibility::Public`) rooms are listed in the room directory
    /// and can be found using it.
    pub async fn get_room_visibility(&'a self) -> Result<Visibility> {
        let request = get_room_visibility::v3::Request::new(self.room.room_id().to_owned());
        let response = self.client.send(request).await?;
        Ok(response.visibility)
    }

    /// Update the visibility for this room in the room directory.
    ///
    /// [Public](`Visibility::Public`) rooms are listed in the room directory
    /// and can be found using it.
    pub async fn update_room_visibility(&'a self, visibility: Visibility) -> Result<()> {
        let request =
            set_room_visibility::v3::Request::new(self.room.room_id().to_owned(), visibility);

        self.client.send(request).await?;

        Ok(())
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use std::ops::Not;

    use matrix_sdk_test::{async_test, JoinedRoomBuilder, StateTestEvent};
    use ruma::{
        api::client::room::Visibility,
        event_id,
        events::{
            room::{history_visibility::HistoryVisibility, join_rules::JoinRule},
            StateEventType,
        },
        owned_room_alias_id, room_id,
    };

    use crate::test_utils::mocks::MatrixMockServer;

    #[async_test]
    async fn test_publish_room_alias_to_room_directory() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

        let room_id = room_id!("!a:b.c");
        let room = server.sync_joined_room(&client, room_id).await;

        let room_alias = owned_room_alias_id!("#a:b.c");

        // First we'd check if the new alias needs to be created
        server
            .mock_room_directory_resolve_alias()
            .for_alias(room_alias.to_string())
            .not_found()
            .mock_once()
            .mount()
            .await;

        // After that, we'd create a new room alias association in the room directory
        server.mock_room_directory_create_room_alias().ok().mock_once().mount().await;

        let published = room
            .privacy_settings()
            .publish_room_alias_in_room_directory(&room_alias)
            .await
            .expect("we should get a result value, not an error");
        assert!(published);
    }

    #[async_test]
    async fn test_publish_room_alias_to_room_directory_when_alias_exists() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

        let room_id = room_id!("!a:b.c");
        let room = server.sync_joined_room(&client, room_id).await;

        let room_alias = owned_room_alias_id!("#a:b.c");

        // First we'd check if the new alias needs to be created. It does not.
        server
            .mock_room_directory_resolve_alias()
            .for_alias(room_alias.to_string())
            .ok(room_id.as_ref(), Vec::new())
            .mock_once()
            .mount()
            .await;

        // Since the room alias already exists we won't create it again.
        server.mock_room_directory_create_room_alias().ok().never().mount().await;

        let published = room
            .privacy_settings()
            .publish_room_alias_in_room_directory(&room_alias)
            .await
            .expect("we should get a result value, not an error");
        assert!(published.not());
    }

    #[async_test]
    async fn test_remove_room_alias() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

        let room_id = room_id!("!a:b.c");
        let joined_room_builder =
            JoinedRoomBuilder::new(room_id).add_state_event(StateTestEvent::Alias);
        let room = server.sync_room(&client, joined_room_builder).await;

        let room_alias = owned_room_alias_id!("#a:b.c");

        // First we'd check if the alias exists
        server
            .mock_room_directory_resolve_alias()
            .for_alias(room_alias.to_string())
            .ok(room_id.as_ref(), Vec::new())
            .mock_once()
            .mount()
            .await;

        // After that we'd remove it
        server.mock_room_directory_remove_room_alias().ok().mock_once().mount().await;

        let removed = room
            .privacy_settings()
            .remove_room_alias_from_room_directory(&room_alias)
            .await
            .expect("we should get a result value, not an error");
        assert!(removed);
    }

    #[async_test]
    async fn test_remove_room_alias_if_it_does_not_exist() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

        let room_id = room_id!("!a:b.c");
        let joined_room_builder =
            JoinedRoomBuilder::new(room_id).add_state_event(StateTestEvent::Alias);
        let room = server.sync_room(&client, joined_room_builder).await;

        let room_alias = owned_room_alias_id!("#a:b.c");

        // First we'd check if the alias exists. It doesn't.
        server
            .mock_room_directory_resolve_alias()
            .for_alias(room_alias.to_string())
            .not_found()
            .mock_once()
            .mount()
            .await;

        // So we can't remove it after the check.
        server.mock_room_directory_remove_room_alias().ok().never().mount().await;

        let removed = room
            .privacy_settings()
            .remove_room_alias_from_room_directory(&room_alias)
            .await
            .expect("we should get a result value, not an error");
        assert!(removed.not());
    }

    #[async_test]
    async fn test_update_canonical_alias_with_some_value() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

        let room_id = room_id!("!a:b.c");
        let room = server.sync_joined_room(&client, room_id).await;

        server
            .mock_room_send_state()
            .for_type(StateEventType::RoomCanonicalAlias)
            .ok(event_id!("$a:b.c"))
            .mock_once()
            .mount()
            .await;

        let room_alias = owned_room_alias_id!("#a:b.c");
        let ret = room
            .privacy_settings()
            .update_canonical_alias(Some(room_alias.clone()), Vec::new())
            .await;
        assert!(ret.is_ok());
    }

    #[async_test]
    async fn test_update_canonical_alias_with_no_value() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

        let room_id = room_id!("!a:b.c");
        let room = server.sync_joined_room(&client, room_id).await;

        server
            .mock_room_send_state()
            .for_type(StateEventType::RoomCanonicalAlias)
            .ok(event_id!("$a:b.c"))
            .mock_once()
            .mount()
            .await;

        let ret = room.privacy_settings().update_canonical_alias(None, Vec::new()).await;
        assert!(ret.is_ok());
    }

    #[async_test]
    async fn test_update_room_history_visibility() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

        let room_id = room_id!("!a:b.c");
        let room = server.sync_joined_room(&client, room_id).await;

        server
            .mock_room_send_state()
            .for_type(StateEventType::RoomHistoryVisibility)
            .ok(event_id!("$a:b.c"))
            .mock_once()
            .mount()
            .await;

        let ret =
            room.privacy_settings().update_room_history_visibility(HistoryVisibility::Joined).await;
        assert!(ret.is_ok());
    }

    #[async_test]
    async fn test_update_join_rule() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

        let room_id = room_id!("!a:b.c");
        let room = server.sync_joined_room(&client, room_id).await;

        server
            .mock_room_send_state()
            .for_type(StateEventType::RoomJoinRules)
            .ok(event_id!("$a:b.c"))
            .mock_once()
            .mount()
            .await;

        let ret = room.privacy_settings().update_join_rule(JoinRule::Public).await;
        assert!(ret.is_ok());
    }

    #[async_test]
    async fn test_get_room_visibility() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

        let room_id = room_id!("!a:b.c");
        let room = server.sync_joined_room(&client, room_id).await;

        server
            .mock_room_send_state()
            .for_type(StateEventType::RoomJoinRules)
            .ok(event_id!("$a:b.c"))
            .mock_once()
            .mount()
            .await;

        let ret = room.privacy_settings().update_join_rule(JoinRule::Public).await;
        assert!(ret.is_ok());
    }

    #[async_test]
    async fn test_update_room_visibility() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;

        let room_id = room_id!("!a:b.c");
        let room = server.sync_joined_room(&client, room_id).await;

        server.mock_room_directory_set_room_visibility().ok().mock_once().mount().await;

        let ret = room.privacy_settings().update_room_visibility(Visibility::Private).await;
        assert!(ret.is_ok());
    }
}