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
//! Power level configuration types used in [the `room` module][super].

use std::collections::HashMap;

use ruma::{
    events::{
        room::power_levels::{
            PossiblyRedactedRoomPowerLevelsEventContent, RoomPowerLevels,
            RoomPowerLevelsEventContent,
        },
        StateEventType,
    },
    OwnedUserId,
};

use crate::Result;

/// A set of common power levels required for various operations within a room,
/// that can be applied as a single operation. When updating these
/// settings, any levels that are `None` will remain unchanged.
#[derive(Debug)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct RoomPowerLevelChanges {
    // Actions
    /// The level required to ban a user.
    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
    pub ban: Option<i64>,
    /// The level required to invite a user.
    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
    pub invite: Option<i64>,
    /// The level required to kick a user.
    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
    pub kick: Option<i64>,
    /// The level required to redact an event.
    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
    pub redact: Option<i64>,

    // Events
    /// The default level required to send message events.
    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
    pub events_default: Option<i64>,
    /// The default level required to send state events.
    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
    pub state_default: Option<i64>,
    /// The default power level for every user in the room.
    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
    pub users_default: Option<i64>,
    /// The level required to change the room's name.
    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
    pub room_name: Option<i64>,
    /// The level required to change the room's avatar.
    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
    pub room_avatar: Option<i64>,
    /// The level required to change the room's topic.
    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
    pub room_topic: Option<i64>,
}

impl RoomPowerLevelChanges {
    /// Constructs an empty set of `RoomPowerLevelChanges`.
    pub fn new() -> Self {
        Self {
            ban: None,
            invite: None,
            kick: None,
            redact: None,
            events_default: None,
            state_default: None,
            users_default: None,
            room_name: None,
            room_avatar: None,
            room_topic: None,
        }
    }
}

impl Default for RoomPowerLevelChanges {
    fn default() -> Self {
        Self::new()
    }
}

impl From<RoomPowerLevels> for RoomPowerLevelChanges {
    fn from(value: RoomPowerLevels) -> Self {
        Self {
            ban: Some(value.ban.into()),
            invite: Some(value.invite.into()),
            kick: Some(value.kick.into()),
            redact: Some(value.redact.into()),
            events_default: Some(value.events_default.into()),
            state_default: Some(value.state_default.into()),
            users_default: Some(value.users_default.into()),
            room_name: value
                .events
                .get(&StateEventType::RoomName.into())
                .map(|v| (*v).into())
                .or(Some(value.state_default.into())),
            room_avatar: value
                .events
                .get(&StateEventType::RoomAvatar.into())
                .map(|v| (*v).into())
                .or(Some(value.state_default.into())),
            room_topic: value
                .events
                .get(&StateEventType::RoomTopic.into())
                .map(|v| (*v).into())
                .or(Some(value.state_default.into())),
        }
    }
}

pub(crate) trait RoomPowerLevelsExt {
    /// Applies the updated settings to the power levels. Any levels that are
    /// `None` will remain unchanged. Unlike with members, we don't remove the
    /// event if the new level matches the default as this could result in
    /// unintended privileges when updating the default power level in
    /// isolation of the others.
    fn apply(&mut self, settings: RoomPowerLevelChanges) -> Result<()>;
}

impl RoomPowerLevelsExt for RoomPowerLevels {
    fn apply(&mut self, settings: RoomPowerLevelChanges) -> Result<()> {
        if let Some(ban) = settings.ban {
            self.ban = ban.try_into()?;
        }
        if let Some(invite) = settings.invite {
            self.invite = invite.try_into()?;
        }
        if let Some(kick) = settings.kick {
            self.kick = kick.try_into()?;
        }
        if let Some(redact) = settings.redact {
            self.redact = redact.try_into()?;
        }
        if let Some(events_default) = settings.events_default {
            self.events_default = events_default.try_into()?;
        }
        if let Some(state_default) = settings.state_default {
            self.state_default = state_default.try_into()?;
        }
        if let Some(users_default) = settings.users_default {
            self.users_default = users_default.try_into()?;
        }
        if let Some(room_name) = settings.room_name {
            self.events.insert(StateEventType::RoomName.into(), room_name.try_into()?);
        }
        if let Some(room_avatar) = settings.room_avatar {
            self.events.insert(StateEventType::RoomAvatar.into(), room_avatar.try_into()?);
        }
        if let Some(room_topic) = settings.room_topic {
            self.events.insert(StateEventType::RoomTopic.into(), room_topic.try_into()?);
        }

        Ok(())
    }
}

impl From<js_int::TryFromIntError> for crate::error::Error {
    fn from(e: js_int::TryFromIntError) -> Self {
        crate::error::Error::UnknownError(Box::new(e))
    }
}

/// Checks for changes in the power levels of users in a room based on a new
/// event.
pub fn power_level_user_changes(
    content: &RoomPowerLevelsEventContent,
    prev_content: &Option<PossiblyRedactedRoomPowerLevelsEventContent>,
) -> HashMap<OwnedUserId, i64> {
    let Some(prev_content) = prev_content.as_ref() else {
        return Default::default();
    };

    let mut changes = HashMap::new();
    let mut prev_users = prev_content.users.clone();
    let new_users = content.users.clone();

    // If a user is in the new power levels, but not in the old ones, or if the
    // power level has changed, add them to the changes.
    for (user_id, power_level) in new_users {
        let prev_power_level = prev_users.remove(&user_id).unwrap_or(prev_content.users_default);
        if power_level != prev_power_level {
            changes.insert(user_id, power_level.into());
        }
    }

    // Any remaining users from the old power levels have had their power level set
    // back to default.
    for (user_id, power_level) in prev_users {
        if power_level != content.users_default {
            changes.insert(user_id, content.users_default.into());
        }
    }

    changes
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use ruma::{int, power_levels::NotificationPowerLevels};

    use super::*;

    #[test]
    fn test_apply_actions() {
        // Given a set of power levels and some settings that only change the
        // actions.
        let mut power_levels = default_power_levels();

        let new_level = int!(100);
        let settings = RoomPowerLevelChanges {
            ban: Some(new_level.into()),
            invite: Some(new_level.into()),
            kick: Some(new_level.into()),
            redact: Some(new_level.into()),
            events_default: None,
            state_default: None,
            users_default: None,
            room_name: None,
            room_avatar: None,
            room_topic: None,
        };

        // When applying the settings to the power levels.
        let original_levels = power_levels.clone();
        power_levels.apply(settings).unwrap();

        // Then the levels for the actions should be updated.
        assert_eq!(power_levels.ban, new_level);
        assert_eq!(power_levels.invite, new_level);
        assert_eq!(power_levels.kick, new_level);
        assert_eq!(power_levels.redact, new_level);
        // And the rest should remain unchanged.
        assert_eq!(power_levels.events_default, original_levels.events_default);
        assert_eq!(power_levels.state_default, original_levels.state_default);
        assert_eq!(power_levels.users_default, original_levels.users_default);
        assert_eq!(power_levels.events, original_levels.events);
    }

    #[test]
    fn test_apply_room_settings() {
        // Given a set of power levels and some settings that only change the specific
        // state event levels.
        let mut power_levels = default_power_levels();

        let new_level = int!(100);
        let settings = RoomPowerLevelChanges {
            ban: None,
            invite: None,
            kick: None,
            redact: None,
            events_default: None,
            state_default: None,
            users_default: None,
            room_name: Some(new_level.into()),
            room_avatar: Some(new_level.into()),
            room_topic: Some(new_level.into()),
        };

        // When applying the settings to the power levels.
        let original_levels = power_levels.clone();
        power_levels.apply(settings).unwrap();

        // Then levels for the necessary state events should be added.
        assert_eq!(
            power_levels.events,
            BTreeMap::from_iter(vec![
                (StateEventType::RoomName.into(), new_level),
                (StateEventType::RoomAvatar.into(), new_level),
                (StateEventType::RoomTopic.into(), new_level),
            ])
        );
        // And the rest should remain unchanged.
        assert_eq!(power_levels.ban, original_levels.ban);
        assert_eq!(power_levels.invite, original_levels.invite);
        assert_eq!(power_levels.kick, original_levels.kick);
        assert_eq!(power_levels.redact, original_levels.redact);
        assert_eq!(power_levels.events_default, original_levels.events_default);
        assert_eq!(power_levels.state_default, original_levels.state_default);
        assert_eq!(power_levels.users_default, original_levels.users_default);
    }

    #[test]
    fn test_apply_state_event_to_default() {
        // Given a set of power levels and some settings that change the room name level
        // back to the default level.
        let original_level = int!(100);
        let mut power_levels = default_power_levels();
        power_levels.events = BTreeMap::from_iter(vec![
            (StateEventType::RoomName.into(), original_level),
            (StateEventType::RoomAvatar.into(), original_level),
            (StateEventType::RoomTopic.into(), original_level),
        ]);

        let settings = RoomPowerLevelChanges {
            ban: None,
            invite: None,
            kick: None,
            redact: None,
            events_default: None,
            state_default: None,
            users_default: None,
            room_name: Some(power_levels.state_default.into()),
            room_avatar: None,
            room_topic: None,
        };

        // When applying the settings to the power levels.
        let original_levels = power_levels.clone();
        power_levels.apply(settings).unwrap();

        // Then the room name level should be updated (but not removed) without
        // affecting any other state events.
        assert_eq!(
            power_levels.events,
            BTreeMap::from_iter(vec![
                (StateEventType::RoomName.into(), power_levels.state_default),
                (StateEventType::RoomAvatar.into(), original_level),
                (StateEventType::RoomTopic.into(), original_level),
            ])
        );
        // And the rest should remain unchanged.
        assert_eq!(power_levels.ban, original_levels.ban);
        assert_eq!(power_levels.invite, original_levels.invite);
        assert_eq!(power_levels.kick, original_levels.kick);
        assert_eq!(power_levels.redact, original_levels.redact);
        assert_eq!(power_levels.events_default, original_levels.events_default);
        assert_eq!(power_levels.state_default, original_levels.state_default);
        assert_eq!(power_levels.users_default, original_levels.users_default);
    }

    #[test]
    fn test_user_power_level_changes_add_mod() {
        // Given a set of power levels and a new set of power levels that adds a new
        // moderator.
        let prev_content = default_power_levels_event_content();
        let mut content = prev_content.clone();
        content.users.insert(OwnedUserId::try_from("@charlie:example.com").unwrap(), int!(50));

        // When calculating the changes.
        let changes = power_level_user_changes(&content, &Some(prev_content));

        // Then the changes should reflect the new moderator.
        assert_eq!(changes.len(), 1);
        assert_eq!(changes.get(&OwnedUserId::try_from("@charlie:example.com").unwrap()), Some(&50));
    }

    #[test]
    fn test_user_power_level_changes_remove_mod() {
        // Given a set of power levels and a new set of power levels that removes a
        // moderator.
        let prev_content = default_power_levels_event_content();
        let mut content = prev_content.clone();
        content.users.remove(&OwnedUserId::try_from("@bob:example.com").unwrap());

        // When calculating the changes.
        let changes = power_level_user_changes(&content, &Some(prev_content));

        // Then the changes should reflect the removed moderator.
        assert_eq!(changes.len(), 1);
        assert_eq!(changes.get(&OwnedUserId::try_from("@bob:example.com").unwrap()), Some(&0));
    }

    #[test]
    fn test_user_power_level_changes_change_mod() {
        // Given a set of power levels and a new set of power levels that changes a
        // moderator to an admin.
        let prev_content = default_power_levels_event_content();
        let mut content = prev_content.clone();
        content.users.insert(OwnedUserId::try_from("@bob:example.com").unwrap(), int!(100));

        // When calculating the changes.
        let changes = power_level_user_changes(&content, &Some(prev_content));

        // Then the changes should reflect the new admin.
        assert_eq!(changes.len(), 1);
        assert_eq!(changes.get(&OwnedUserId::try_from("@bob:example.com").unwrap()), Some(&100));
    }

    #[test]
    fn test_user_power_level_changes_new_default() {
        // Given a set of power levels and a new set of power levels that changes the
        // default user power level to moderator and removes the only moderator.
        let prev_content = default_power_levels_event_content();
        let mut content = prev_content.clone();
        content.users_default = int!(50);
        content.users.remove(&OwnedUserId::try_from("@bob:example.com").unwrap());

        // When calculating the changes.
        let changes = power_level_user_changes(&content, &Some(prev_content));

        // Then there should be no changes.
        assert!(changes.is_empty());
    }

    #[test]
    fn test_user_power_level_changes_no_change() {
        // Given a set of power levels and a new set of power levels that's the same.
        let prev_content = default_power_levels_event_content();
        let content = prev_content.clone();

        // When calculating the changes.
        let changes = power_level_user_changes(&content, &Some(prev_content));

        // Then there should be no changes.
        assert!(changes.is_empty());
    }

    #[test]
    fn test_user_power_level_changes_other_properties() {
        // Given a set of power levels and a new set of power levels with changes that
        // don't include the user power levels.
        let prev_content = default_power_levels_event_content();
        let mut content = prev_content.clone();
        content.events_default = int!(100);

        // When calculating the changes.
        let changes = power_level_user_changes(&content, &Some(prev_content));

        // Then there should be no changes.
        assert!(changes.is_empty());
    }

    fn default_power_levels() -> RoomPowerLevels {
        default_power_levels_event_content().into()
    }

    fn default_power_levels_event_content() -> RoomPowerLevelsEventContent {
        let mut content = RoomPowerLevelsEventContent::new();
        content.ban = int!(50);
        content.invite = int!(50);
        content.kick = int!(50);
        content.redact = int!(50);
        content.events_default = int!(0);
        content.state_default = int!(50);
        content.users_default = int!(0);
        content.users = BTreeMap::from_iter(vec![
            (OwnedUserId::try_from("@alice:example.com").unwrap(), int!(100)),
            (OwnedUserId::try_from("@bob:example.com").unwrap(), int!(50)),
        ]);
        content.notifications = NotificationPowerLevels::default();
        content
    }
}