matrix_sdk/notification_settings/
rule_commands.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
use ruma::{
    push::{
        Action, PredefinedContentRuleId, PredefinedOverrideRuleId, RemovePushRuleError, RuleKind,
        Ruleset,
    },
    RoomId,
};

use super::command::Command;
use crate::NotificationSettingsError;

/// A `RuleCommand` allows to generate a list of `Command` needed to modify a
/// `Ruleset`
#[derive(Clone, Debug)]
pub(crate) struct RuleCommands {
    pub(crate) commands: Vec<Command>,
    pub(crate) rules: Ruleset,
}

impl RuleCommands {
    pub(crate) fn new(rules: Ruleset) -> Self {
        RuleCommands { commands: vec![], rules }
    }

    /// Insert a new rule
    pub(crate) fn insert_rule(
        &mut self,
        kind: RuleKind,
        room_id: &RoomId,
        notify: bool,
    ) -> Result<(), NotificationSettingsError> {
        let command = match kind {
            RuleKind::Room => Command::SetRoomPushRule { room_id: room_id.to_owned(), notify },
            RuleKind::Override => Command::SetOverridePushRule {
                rule_id: room_id.to_string(),
                room_id: room_id.to_owned(),
                notify,
            },
            _ => {
                return Err(NotificationSettingsError::InvalidParameter(
                    "cannot insert a rule for this kind.".to_owned(),
                ))
            }
        };

        self.rules.insert(command.to_push_rule()?, None, None)?;
        self.commands.push(command);

        Ok(())
    }

    /// Insert a new rule for a keyword.
    pub(crate) fn insert_keyword_rule(
        &mut self,
        keyword: String,
    ) -> Result<(), NotificationSettingsError> {
        let command = Command::SetKeywordPushRule { keyword };

        self.rules.insert(command.to_push_rule()?, None, None)?;
        self.commands.push(command);

        Ok(())
    }

    /// Delete a rule
    pub(crate) fn delete_rule(
        &mut self,
        kind: RuleKind,
        rule_id: String,
    ) -> Result<(), RemovePushRuleError> {
        self.rules.remove(kind.clone(), &rule_id)?;
        self.commands.push(Command::DeletePushRule { kind, rule_id });

        Ok(())
    }

    fn set_enabled_internal(
        &mut self,
        kind: RuleKind,
        rule_id: &str,
        enabled: bool,
    ) -> Result<(), NotificationSettingsError> {
        self.rules
            .set_enabled(kind.clone(), rule_id, enabled)
            .map_err(|_| NotificationSettingsError::RuleNotFound(rule_id.to_owned()))?;
        self.commands.push(Command::SetPushRuleEnabled {
            kind,
            rule_id: rule_id.to_owned(),
            enabled,
        });
        Ok(())
    }

    /// Set whether a rule is enabled
    pub(crate) fn set_rule_enabled(
        &mut self,
        kind: RuleKind,
        rule_id: &str,
        enabled: bool,
    ) -> Result<(), NotificationSettingsError> {
        if rule_id == PredefinedOverrideRuleId::IsRoomMention.as_str() {
            // Handle specific case for `PredefinedOverrideRuleId::IsRoomMention`
            self.set_room_mention_enabled(enabled)
        } else if rule_id == PredefinedOverrideRuleId::IsUserMention.as_str() {
            // Handle specific case for `PredefinedOverrideRuleId::IsUserMention`
            self.set_user_mention_enabled(enabled)
        } else {
            self.set_enabled_internal(kind, rule_id, enabled)
        }
    }

    /// Set whether `IsUserMention` is enabled
    fn set_user_mention_enabled(&mut self, enabled: bool) -> Result<(), NotificationSettingsError> {
        // Add a command for the `IsUserMention` `Override` rule (MSC3952).
        // This is a new push rule that may not yet be present.
        self.set_enabled_internal(
            RuleKind::Override,
            PredefinedOverrideRuleId::IsUserMention.as_str(),
            enabled,
        )?;

        // For compatibility purpose, we still need to add commands for
        // `ContainsUserName` and `ContainsDisplayName` (deprecated rules).
        #[allow(deprecated)]
        {
            // `ContainsUserName`
            self.set_enabled_internal(
                RuleKind::Content,
                PredefinedContentRuleId::ContainsUserName.as_str(),
                enabled,
            )?;

            // `ContainsDisplayName`
            self.set_enabled_internal(
                RuleKind::Override,
                PredefinedOverrideRuleId::ContainsDisplayName.as_str(),
                enabled,
            )?;
        }

        Ok(())
    }

    /// Set whether `IsRoomMention` is enabled
    fn set_room_mention_enabled(&mut self, enabled: bool) -> Result<(), NotificationSettingsError> {
        // Sets the `IsRoomMention` `Override` rule (MSC3952).
        // This is a new push rule that may not yet be present.
        self.set_enabled_internal(
            RuleKind::Override,
            PredefinedOverrideRuleId::IsRoomMention.as_str(),
            enabled,
        )?;

        // For compatibility purpose, we still need to set `RoomNotif` (deprecated
        // rule).
        #[allow(deprecated)]
        self.set_enabled_internal(
            RuleKind::Override,
            PredefinedOverrideRuleId::RoomNotif.as_str(),
            enabled,
        )?;

        Ok(())
    }

    /// Set the actions of the rule from the given kind and with the given
    /// `rule_id`
    pub(crate) fn set_rule_actions(
        &mut self,
        kind: RuleKind,
        rule_id: &str,
        actions: Vec<Action>,
    ) -> Result<(), NotificationSettingsError> {
        self.rules
            .set_actions(kind.clone(), rule_id, actions.clone())
            .map_err(|_| NotificationSettingsError::RuleNotFound(rule_id.to_owned()))?;
        self.commands.push(Command::SetPushRuleActions {
            kind,
            rule_id: rule_id.to_owned(),
            actions,
        });
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;
    use matrix_sdk_test::async_test;
    use ruma::{
        push::{
            Action, NewPushRule, NewSimplePushRule, PredefinedContentRuleId,
            PredefinedOverrideRuleId, PredefinedUnderrideRuleId, RemovePushRuleError, RuleKind,
            Ruleset, Tweak,
        },
        OwnedRoomId, RoomId, UserId,
    };

    use super::RuleCommands;
    use crate::{error::NotificationSettingsError, notification_settings::command::Command};

    fn get_server_default_ruleset() -> Ruleset {
        let user_id = UserId::parse("@user:matrix.org").unwrap();
        Ruleset::server_default(&user_id)
    }

    fn get_test_room_id() -> OwnedRoomId {
        RoomId::parse("!AAAaAAAAAaaAAaaaaa:matrix.org").unwrap()
    }

    #[async_test]
    async fn test_insert_rule_room() {
        let room_id = get_test_room_id();
        let mut rule_commands = RuleCommands::new(get_server_default_ruleset());
        rule_commands.insert_rule(RuleKind::Room, &room_id, true).unwrap();

        // A rule must have been inserted in the ruleset.
        assert!(rule_commands.rules.get(RuleKind::Room, &room_id).is_some());

        // Exactly one command must have been created.
        assert_eq!(rule_commands.commands.len(), 1);
        assert_matches!(&rule_commands.commands[0],
            Command::SetRoomPushRule { room_id: command_room_id, notify } => {
                assert_eq!(command_room_id, &room_id);
                assert!(notify);
            }
        );
    }

    #[async_test]
    async fn test_insert_rule_override() {
        let room_id = get_test_room_id();
        let mut rule_commands = RuleCommands::new(get_server_default_ruleset());
        rule_commands.insert_rule(RuleKind::Override, &room_id, true).unwrap();

        // A rule must have been inserted in the ruleset.
        assert!(rule_commands.rules.get(RuleKind::Override, &room_id).is_some());

        // Exactly one command must have been created.
        assert_eq!(rule_commands.commands.len(), 1);
        assert_matches!(&rule_commands.commands[0],
            Command::SetOverridePushRule {room_id: command_room_id, rule_id, notify } => {
                assert_eq!(command_room_id, &room_id);
                assert_eq!(rule_id, room_id.as_str());
                assert!(notify);
            }
        );
    }

    #[async_test]
    async fn test_insert_rule_unsupported() {
        let room_id = get_test_room_id();
        let mut rule_commands = RuleCommands::new(get_server_default_ruleset());

        assert_matches!(
            rule_commands.insert_rule(RuleKind::Underride, &room_id, true),
            Err(NotificationSettingsError::InvalidParameter(_)) => {}
        );

        assert_matches!(
            rule_commands.insert_rule(RuleKind::Content, &room_id, true),
            Err(NotificationSettingsError::InvalidParameter(_)) => {}
        );

        assert_matches!(
            rule_commands.insert_rule(RuleKind::Sender, &room_id, true),
            Err(NotificationSettingsError::InvalidParameter(_)) => {}
        );
    }

    #[async_test]
    async fn test_delete_rule() {
        let room_id = get_test_room_id();
        let mut ruleset = get_server_default_ruleset();

        let new_rule = NewSimplePushRule::new(room_id.to_owned(), vec![]);
        ruleset.insert(NewPushRule::Room(new_rule), None, None).unwrap();

        let mut rule_commands = RuleCommands::new(ruleset);

        // Delete must succeed.
        rule_commands.delete_rule(RuleKind::Room, room_id.to_string()).unwrap();

        // The ruleset must have been updated.
        assert!(rule_commands.rules.get(RuleKind::Room, &room_id).is_none());

        // Exactly one command must have been created.
        assert_eq!(rule_commands.commands.len(), 1);
        assert_matches!(&rule_commands.commands[0],
            Command::DeletePushRule { kind, rule_id } => {
                assert_eq!(kind, &RuleKind::Room);
                assert_eq!(rule_id, room_id.as_str());
            }
        );
    }

    #[async_test]
    async fn test_delete_rule_errors() {
        let room_id = get_test_room_id();
        let ruleset = get_server_default_ruleset();

        let mut rule_commands = RuleCommands::new(ruleset);

        // Deletion should fail if an attempt is made to delete a rule that does not
        // exist.
        assert_matches!(
            rule_commands.delete_rule(RuleKind::Room, room_id.to_string()),
            Err(RemovePushRuleError::NotFound) => {}
        );

        // Deletion should fail if an attempt is made to delete a default server rule.
        assert_matches!(
            rule_commands.delete_rule(RuleKind::Override, PredefinedOverrideRuleId::IsUserMention.to_string()),
            Err(RemovePushRuleError::ServerDefault) => {}
        );

        assert!(rule_commands.commands.is_empty());
    }

    #[async_test]
    async fn test_set_rule_enabled() {
        let mut ruleset = get_server_default_ruleset();

        // Initialize with `Reaction` rule disabled.
        ruleset.set_enabled(RuleKind::Override, PredefinedOverrideRuleId::Reaction, false).unwrap();

        let mut rule_commands = RuleCommands::new(ruleset);
        rule_commands
            .set_rule_enabled(RuleKind::Override, PredefinedOverrideRuleId::Reaction.as_str(), true)
            .unwrap();

        // The ruleset must have been updated
        let rule = rule_commands
            .rules
            .get(RuleKind::Override, PredefinedOverrideRuleId::Reaction.as_str())
            .unwrap();
        assert!(rule.enabled());

        // Exactly one command must have been created.
        assert_eq!(rule_commands.commands.len(), 1);
        assert_matches!(&rule_commands.commands[0],
            Command::SetPushRuleEnabled { kind, rule_id, enabled } => {
                assert_eq!(kind, &RuleKind::Override);
                assert_eq!(rule_id, PredefinedOverrideRuleId::Reaction.as_str());
                assert!(enabled);
            }
        );
    }

    #[async_test]
    async fn test_set_rule_enabled_not_found() {
        let ruleset = get_server_default_ruleset();
        let mut rule_commands = RuleCommands::new(ruleset);
        assert_eq!(
            rule_commands.set_rule_enabled(RuleKind::Room, "unknown_rule_id", true),
            Err(NotificationSettingsError::RuleNotFound("unknown_rule_id".to_owned()))
        );
    }

    #[async_test]
    async fn test_set_rule_enabled_user_mention() {
        let mut ruleset = get_server_default_ruleset();
        let mut rule_commands = RuleCommands::new(ruleset.clone());

        ruleset
            .set_enabled(RuleKind::Override, PredefinedOverrideRuleId::IsUserMention, false)
            .unwrap();

        #[allow(deprecated)]
        {
            ruleset
                .set_enabled(
                    RuleKind::Override,
                    PredefinedOverrideRuleId::ContainsDisplayName,
                    false,
                )
                .unwrap();
            ruleset
                .set_enabled(RuleKind::Content, PredefinedContentRuleId::ContainsUserName, false)
                .unwrap();
        }

        // Enable the user mention rule.
        rule_commands
            .set_rule_enabled(
                RuleKind::Override,
                PredefinedOverrideRuleId::IsUserMention.as_str(),
                true,
            )
            .unwrap();

        // The ruleset must have been updated.
        assert!(rule_commands
            .rules
            .get(RuleKind::Override, PredefinedOverrideRuleId::IsUserMention)
            .unwrap()
            .enabled());
        #[allow(deprecated)]
        {
            assert!(rule_commands
                .rules
                .get(RuleKind::Override, PredefinedOverrideRuleId::ContainsDisplayName)
                .unwrap()
                .enabled());
            assert!(rule_commands
                .rules
                .get(RuleKind::Content, PredefinedContentRuleId::ContainsUserName)
                .unwrap()
                .enabled());
        }

        // Three commands are expected.
        assert_eq!(rule_commands.commands.len(), 3);

        assert_matches!(&rule_commands.commands[0],
            Command::SetPushRuleEnabled { kind, rule_id, enabled } => {
                assert_eq!(kind, &RuleKind::Override);
                assert_eq!(rule_id, PredefinedOverrideRuleId::IsUserMention.as_str());
                assert!(enabled);
            }
        );

        #[allow(deprecated)]
        {
            assert_matches!(&rule_commands.commands[1],
                Command::SetPushRuleEnabled { kind, rule_id, enabled } => {
                    assert_eq!(kind, &RuleKind::Content);
                    assert_eq!(rule_id, PredefinedContentRuleId::ContainsUserName.as_str());
                    assert!(enabled);
                }
            );

            assert_matches!(&rule_commands.commands[2],
                Command::SetPushRuleEnabled { kind, rule_id, enabled } => {
                    assert_eq!(kind, &RuleKind::Override);
                    assert_eq!(rule_id, PredefinedOverrideRuleId::ContainsDisplayName.as_str());
                    assert!(enabled);
                }
            );
        }
    }

    #[async_test]
    async fn test_set_rule_enabled_room_mention() {
        let mut ruleset = get_server_default_ruleset();
        let mut rule_commands = RuleCommands::new(ruleset.clone());

        ruleset
            .set_enabled(RuleKind::Override, PredefinedOverrideRuleId::IsRoomMention, false)
            .unwrap();

        #[allow(deprecated)]
        {
            ruleset
                .set_enabled(RuleKind::Override, PredefinedOverrideRuleId::RoomNotif, false)
                .unwrap();
        }

        rule_commands
            .set_rule_enabled(
                RuleKind::Override,
                PredefinedOverrideRuleId::IsRoomMention.as_str(),
                true,
            )
            .unwrap();

        // The ruleset must have been updated.
        assert!(rule_commands
            .rules
            .get(RuleKind::Override, PredefinedOverrideRuleId::IsRoomMention)
            .unwrap()
            .enabled());
        #[allow(deprecated)]
        {
            assert!(rule_commands
                .rules
                .get(RuleKind::Override, PredefinedOverrideRuleId::RoomNotif)
                .unwrap()
                .enabled());
        }

        // Two commands are expected.
        assert_eq!(rule_commands.commands.len(), 2);

        assert_matches!(&rule_commands.commands[0],
            Command::SetPushRuleEnabled {  kind, rule_id, enabled } => {
                assert_eq!(kind, &RuleKind::Override);
                assert_eq!(rule_id, PredefinedOverrideRuleId::IsRoomMention.as_str());
                assert!(enabled);
            }
        );

        #[allow(deprecated)]
        {
            assert_matches!(&rule_commands.commands[1],
                Command::SetPushRuleEnabled { kind, rule_id, enabled } => {
                    assert_eq!(kind, &RuleKind::Override);
                    assert_eq!(rule_id, PredefinedOverrideRuleId::RoomNotif.as_str());
                    assert!(enabled);
                }
            );
        }
    }

    #[async_test]
    async fn test_set_rule_actions() {
        let mut ruleset = get_server_default_ruleset();
        let mut rule_commands = RuleCommands::new(ruleset.clone());

        // Starting with an empty action list for `PredefinedUnderrideRuleId::Message`.
        ruleset
            .set_actions(RuleKind::Underride, PredefinedUnderrideRuleId::Message, vec![])
            .unwrap();

        // After setting a list of actions
        rule_commands
            .set_rule_actions(
                RuleKind::Underride,
                PredefinedUnderrideRuleId::Message.as_str(),
                vec![Action::Notify, Action::SetTweak(Tweak::Sound("default".into()))],
            )
            .unwrap();

        // The ruleset must have been updated
        let actions = rule_commands
            .rules
            .get(RuleKind::Underride, PredefinedUnderrideRuleId::Message)
            .unwrap()
            .actions();
        assert_eq!(actions.len(), 2);

        // and a `SetPushRuleActions` command must have been added
        assert_eq!(rule_commands.commands.len(), 1);
        assert_matches!(&rule_commands.commands[0],
            Command::SetPushRuleActions { kind, rule_id, actions } => {
                assert_eq!(kind, &RuleKind::Underride);
                assert_eq!(rule_id, PredefinedUnderrideRuleId::Message.as_str());
                assert_eq!(actions.len(), 2);
                assert_matches!(&actions[0], Action::Notify);
                assert_matches!(&actions[1], Action::SetTweak(Tweak::Sound(sound)) => {
                    assert_eq!(sound, "default");
                });
            }
        );
    }
}