fractal/session/model/room/
permissions.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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use std::fmt;

use gettextrs::gettext;
use gtk::{
    glib,
    glib::{clone, closure_local},
    prelude::*,
    subclass::prelude::*,
};
use matrix_sdk::event_handler::EventHandlerDropGuard;
use ruma::{
    events::{
        room::power_levels::{
            PowerLevelAction, PowerLevelUserAction, RoomPowerLevels, RoomPowerLevelsEventContent,
        },
        MessageLikeEventType, StateEventType, SyncStateEvent,
    },
    Int, OwnedUserId, UserId,
};
use tracing::error;

use super::{Member, Membership, Room};
use crate::{prelude::*, spawn, spawn_tokio};

/// Power level of a user.
///
/// Is usually in the range (0..=100), but can be any JS integer.
pub type PowerLevel = i64;

/// The maximum power level that can be set, according to the Matrix
/// specification.
///
/// This is the same value as `MAX_SAFE_INT` from the `js_int` crate.
pub const POWER_LEVEL_MAX: PowerLevel = 0x001F_FFFF_FFFF_FFFF;
/// The minimum power level that can be set, according to the Matrix
/// specification.
///
/// This is the same value as `MIN_SAFE_INT` from the `js_int` crate.
pub const POWER_LEVEL_MIN: PowerLevel = -POWER_LEVEL_MAX;
/// The minimum power level to have the role of Administrator, according to the
/// Matrix specification.
pub const POWER_LEVEL_ADMIN: PowerLevel = 100;
/// The minimum power level to have the role of Moderator, according to the
/// Matrix specification.
pub const POWER_LEVEL_MOD: PowerLevel = 50;

/// Role of a room member, like admin or moderator.
#[derive(Debug, Default, Hash, Eq, PartialEq, Clone, Copy, glib::Enum)]
#[enum_type(name = "MemberRole")]
pub enum MemberRole {
    /// A room member with the default power level.
    #[default]
    Default,
    /// A room member with a non-default power level, but lower than and a
    /// moderator.
    Custom,
    /// A moderator.
    Moderator,
    /// An administrator.
    Administrator,
    /// A room member that cannot send messages.
    Muted,
}

impl fmt::Display for MemberRole {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            // Translators: As in 'Default power level', meaning permissions.
            Self::Default => write!(f, "{}", gettext("Default")),
            // Translators: As in, 'Custom power level', meaning permissions.
            Self::Custom => write!(f, "{}", gettext("Custom")),
            Self::Moderator => write!(f, "{}", gettext("Moderator")),
            Self::Administrator => write!(f, "{}", gettext("Admin")),
            // Translators: As in 'Muted room member', a member that cannot send messages.
            Self::Muted => write!(f, "{}", gettext("Muted")),
        }
    }
}

mod imp {
    use std::{
        cell::{Cell, OnceCell, RefCell},
        sync::LazyLock,
    };

    use glib::subclass::Signal;
    use ruma::events::room::power_levels::NotificationPowerLevelType;

    use super::*;

    #[derive(Debug, glib::Properties)]
    #[properties(wrapper_type = super::Permissions)]
    pub struct Permissions {
        /// The room where these permissions apply.
        #[property(get)]
        pub(super) room: glib::WeakRef<Room>,
        /// The source of the power levels information.
        pub(super) power_levels: RefCell<RoomPowerLevels>,
        power_levels_drop_guard: OnceCell<EventHandlerDropGuard>,
        /// Whether our own member is joined.
        #[property(get)]
        is_joined: Cell<bool>,
        /// The power level of our own member.
        #[property(get)]
        own_power_level: Cell<PowerLevel>,
        /// The default power level for members.
        #[property(get)]
        default_power_level: Cell<PowerLevel>,
        /// The power level to mute members.
        #[property(get)]
        mute_power_level: Cell<PowerLevel>,
        /// Whether our own member can change the room's avatar.
        #[property(get)]
        can_change_avatar: Cell<bool>,
        /// Whether our own member can change the room's name.
        #[property(get)]
        can_change_name: Cell<bool>,
        /// Whether our own member can change the room's topic.
        #[property(get)]
        can_change_topic: Cell<bool>,
        /// Whether our own member can invite another user.
        #[property(get)]
        can_invite: Cell<bool>,
        /// Whether our own member can send a message.
        #[property(get)]
        can_send_message: Cell<bool>,
        /// Whether our own member can send a reaction.
        #[property(get)]
        can_send_reaction: Cell<bool>,
        /// Whether our own member can redact their own event.
        #[property(get)]
        can_redact_own: Cell<bool>,
        /// Whether our own member can redact the event of another user.
        #[property(get)]
        can_redact_other: Cell<bool>,
        /// Whether our own member can notify the whole room.
        #[property(get)]
        can_notify_room: Cell<bool>,
    }

    impl Default for Permissions {
        fn default() -> Self {
            Self {
                room: Default::default(),
                power_levels: RefCell::new(RoomPowerLevelsEventContent::default().into()),
                power_levels_drop_guard: Default::default(),
                is_joined: Default::default(),
                own_power_level: Default::default(),
                default_power_level: Default::default(),
                mute_power_level: Default::default(),
                can_change_avatar: Default::default(),
                can_change_name: Default::default(),
                can_change_topic: Default::default(),
                can_invite: Default::default(),
                can_send_message: Default::default(),
                can_send_reaction: Default::default(),
                can_redact_own: Default::default(),
                can_redact_other: Default::default(),
                can_notify_room: Default::default(),
            }
        }
    }

    #[glib::object_subclass]
    impl ObjectSubclass for Permissions {
        const NAME: &'static str = "RoomPermissions";
        type Type = super::Permissions;
    }

    #[glib::derived_properties]
    impl ObjectImpl for Permissions {
        fn signals() -> &'static [Signal] {
            static SIGNALS: LazyLock<Vec<Signal>> =
                LazyLock::new(|| vec![Signal::builder("changed").build()]);
            SIGNALS.as_ref()
        }
    }

    impl Permissions {
        /// Initialize the room.
        pub(super) fn init_own_member(&self, own_member: &Member) {
            own_member.connect_membership_notify(clone!(
                #[weak(rename_to = imp)]
                self,
                move |_| {
                    imp.update_is_joined();
                }
            ));

            self.update_is_joined();
        }

        /// The room member for our own user.
        pub(super) fn own_member(&self) -> Option<Member> {
            self.room.upgrade().map(|r| r.own_member())
        }

        /// Initialize the power levels from the store.
        pub(super) async fn init_power_levels(&self) {
            let Some(room) = self.room.upgrade() else {
                return;
            };

            let matrix_room = room.matrix_room();

            let matrix_room_clone = matrix_room.clone();
            let handle = spawn_tokio!(async move { matrix_room_clone.power_levels().await });

            match handle.await.expect("task was not aborted") {
                Ok(power_levels) => self.update_power_levels(&power_levels),
                Err(error) => {
                    error!("Could not load room power levels: {error}");
                }
            }

            let obj_weak = glib::SendWeakRef::from(self.obj().downgrade());
            let handle = matrix_room.add_event_handler(
                move |event: SyncStateEvent<RoomPowerLevelsEventContent>| {
                    let obj_weak = obj_weak.clone();
                    async move {
                        let ctx = glib::MainContext::default();
                        ctx.spawn(async move {
                            spawn!(async move {
                                if let Some(obj) = obj_weak.upgrade() {
                                    obj.imp().update_power_levels(&event.power_levels());
                                }
                            });
                        });
                    }
                },
            );

            let drop_guard = matrix_room.client().event_handler_drop_guard(handle);
            self.power_levels_drop_guard
                .set(drop_guard)
                .expect("power levels drop guard is uninitialized");
        }

        /// Update whether our own member is joined
        fn update_is_joined(&self) {
            let Some(own_member) = self.own_member() else {
                return;
            };

            let is_joined = own_member.membership() == Membership::Join;

            if self.is_joined.get() == is_joined {
                return;
            }

            self.is_joined.set(is_joined);
            self.permissions_changed();
        }

        /// Update the power levels with the given data.
        fn update_power_levels(&self, power_levels: &RoomPowerLevels) {
            self.power_levels.replace(power_levels.clone());
            self.permissions_changed();

            if let Some(room) = self.room.upgrade() {
                if let Some(members) = room.members() {
                    members.update_power_levels(power_levels);
                } else {
                    let own_member = room.own_member();
                    let own_user_id = own_member.user_id();
                    own_member.set_power_level(power_levels.for_user(own_user_id).into());
                }
            }
        }

        /// Trigger updates when the permissions changed.
        fn permissions_changed(&self) {
            self.update_own_power_level();
            self.update_default_power_level();
            self.update_mute_power_level();
            self.update_can_change_avatar();
            self.update_can_change_name();
            self.update_can_change_topic();
            self.update_can_invite();
            self.update_can_send_message();
            self.update_can_send_reaction();
            self.update_can_redact_own();
            self.update_can_redact_other();
            self.update_can_notify_room();
            self.obj().emit_by_name::<()>("changed", &[]);
        }

        /// Update the power level of our own member.
        fn update_own_power_level(&self) {
            let Some(room) = self.room.upgrade() else {
                return;
            };
            let own_member = room.own_member();

            let power_level = self
                .power_levels
                .borrow()
                .for_user(own_member.user_id())
                .into();

            if self.own_power_level.get() == power_level {
                return;
            }

            self.own_power_level.set(power_level);
            self.obj().notify_own_power_level();
        }

        /// Update the default power level for members.
        fn update_default_power_level(&self) {
            let power_level = self.power_levels.borrow().users_default.into();

            if self.default_power_level.get() == power_level {
                return;
            }

            self.default_power_level.set(power_level);
            self.obj().notify_default_power_level();
        }

        /// Update the power level to mute members.
        fn update_mute_power_level(&self) {
            // To mute user they must not have enough power to send messages.
            let power_levels = self.power_levels.borrow();
            let message_power_level = power_levels
                .events
                .get(&MessageLikeEventType::RoomMessage.into())
                .copied()
                .unwrap_or(power_levels.events_default);
            let power_level = (-1).min(message_power_level.into());

            if self.mute_power_level.get() == power_level {
                return;
            }

            self.mute_power_level.set(power_level);
            self.obj().notify_mute_power_level();
        }

        /// Whether our own member is allowed to do the given action.
        pub(super) fn is_allowed_to(&self, room_action: PowerLevelAction) -> bool {
            if !self.is_joined.get() {
                // We cannot do anything if the member is not joined.
                return false;
            }

            let Some(own_member) = self.own_member() else {
                return false;
            };

            self.power_levels
                .borrow()
                .user_can_do(own_member.user_id(), room_action)
        }

        /// Update whether our own member can change the room's avatar.
        fn update_can_change_avatar(&self) {
            let can_change_avatar =
                self.is_allowed_to(PowerLevelAction::SendState(StateEventType::RoomAvatar));

            if self.can_change_avatar.get() == can_change_avatar {
                return;
            };

            self.can_change_avatar.set(can_change_avatar);
            self.obj().notify_can_change_avatar();
        }

        /// Update whether our own member can change the room's name.
        fn update_can_change_name(&self) {
            let can_change_name =
                self.is_allowed_to(PowerLevelAction::SendState(StateEventType::RoomName));

            if self.can_change_name.get() == can_change_name {
                return;
            };

            self.can_change_name.set(can_change_name);
            self.obj().notify_can_change_name();
        }

        /// Update whether our own member can change the room's topic.
        fn update_can_change_topic(&self) {
            let can_change_topic =
                self.is_allowed_to(PowerLevelAction::SendState(StateEventType::RoomTopic));

            if self.can_change_topic.get() == can_change_topic {
                return;
            };

            self.can_change_topic.set(can_change_topic);
            self.obj().notify_can_change_topic();
        }

        /// Update whether our own member can invite another user in the room.
        fn update_can_invite(&self) {
            let can_invite = self.is_allowed_to(PowerLevelAction::Invite);

            if self.can_invite.get() == can_invite {
                return;
            };

            self.can_invite.set(can_invite);
            self.obj().notify_can_invite();
        }

        /// Update whether our own member can send a message in the room.
        fn update_can_send_message(&self) {
            let can_send_message = self.is_allowed_to(PowerLevelAction::SendMessage(
                MessageLikeEventType::RoomMessage,
            ));

            if self.can_send_message.get() == can_send_message {
                return;
            };

            self.can_send_message.set(can_send_message);
            self.obj().notify_can_send_message();
        }

        /// Update whether our own member can send a reaction.
        fn update_can_send_reaction(&self) {
            let can_send_reaction = self.is_allowed_to(PowerLevelAction::SendMessage(
                MessageLikeEventType::Reaction,
            ));

            if self.can_send_reaction.get() == can_send_reaction {
                return;
            };

            self.can_send_reaction.set(can_send_reaction);
            self.obj().notify_can_send_reaction();
        }

        /// Update whether our own member can redact their own event.
        fn update_can_redact_own(&self) {
            let can_redact_own = self.is_allowed_to(PowerLevelAction::RedactOwn);

            if self.can_redact_own.get() == can_redact_own {
                return;
            };

            self.can_redact_own.set(can_redact_own);
            self.obj().notify_can_redact_own();
        }

        /// Update whether our own member can redact the event of another user.
        fn update_can_redact_other(&self) {
            let can_redact_other = self.is_allowed_to(PowerLevelAction::RedactOther);

            if self.can_redact_other.get() == can_redact_other {
                return;
            };

            self.can_redact_other.set(can_redact_other);
            self.obj().notify_can_redact_other();
        }

        /// Update whether our own member can notify the whole room.
        fn update_can_notify_room(&self) {
            let can_notify_room = self.is_allowed_to(PowerLevelAction::TriggerNotification(
                NotificationPowerLevelType::Room,
            ));

            if self.can_notify_room.get() == can_notify_room {
                return;
            };

            self.can_notify_room.set(can_notify_room);
            self.obj().notify_can_notify_room();
        }
    }
}

glib::wrapper! {
    /// The permissions of our own user in a room.
    pub struct Permissions(ObjectSubclass<imp::Permissions>);
}

impl Permissions {
    pub fn new() -> Self {
        glib::Object::new()
    }

    /// Set our own member.
    pub(super) async fn init(&self, room: &Room) {
        let imp = self.imp();

        imp.room.set(Some(room));
        imp.init_own_member(&room.own_member());
        imp.init_power_levels().await;
    }

    /// The source of the power levels information.
    pub(crate) fn power_levels(&self) -> RoomPowerLevels {
        self.imp().power_levels.borrow().clone()
    }

    /// The current [`MemberRole`] for the given power level.
    pub(crate) fn role(&self, power_level: PowerLevel) -> MemberRole {
        if power_level >= POWER_LEVEL_ADMIN {
            MemberRole::Administrator
        } else if power_level >= POWER_LEVEL_MOD {
            MemberRole::Moderator
        } else if power_level == self.default_power_level() {
            MemberRole::Default
        } else if power_level < self.default_power_level() && power_level <= self.mute_power_level()
        {
            // Only set role as muted for members below default, to avoid visual noise in
            // rooms where muted is the default.
            MemberRole::Muted
        } else {
            MemberRole::Custom
        }
    }

    /// Whether our own member is allowed to do the given action.
    pub(crate) fn is_allowed_to(&self, room_action: PowerLevelAction) -> bool {
        self.imp().is_allowed_to(room_action)
    }

    /// Whether our own user can do the given action on the user with the given
    /// ID.
    pub(crate) fn can_do_to_user(&self, user_id: &UserId, action: PowerLevelUserAction) -> bool {
        let imp = self.imp();

        if !self.is_joined() {
            // We cannot do anything if the member is not joined.
            return false;
        }

        let Some(own_member) = imp.own_member() else {
            return false;
        };
        let own_user_id = own_member.user_id();

        let power_levels = imp.power_levels.borrow();

        if own_user_id == user_id {
            // The only action we can do for our own user is change the power level.
            return action == PowerLevelUserAction::ChangePowerLevel
                && power_levels.user_can_send_state(own_user_id, StateEventType::RoomPowerLevels);
        }

        power_levels.user_can_do_to_user(own_user_id, user_id, action)
    }

    /// Set the power level of the room member with the given user ID.
    pub(crate) async fn set_user_power_level(
        &self,
        user_id: OwnedUserId,
        power_level: PowerLevel,
    ) -> Result<(), ()> {
        let Some(room) = self.room() else {
            return Err(());
        };

        let matrix_room = room.matrix_room().clone();
        let handle = spawn_tokio!(async move {
            let power_level = Int::new_saturating(power_level);
            matrix_room
                .update_power_levels(vec![(&user_id, power_level)])
                .await
        });

        match handle.await.expect("task was not aborted") {
            Ok(_) => Ok(()),
            Err(error) => {
                error!("Could not set user power level: {error}");
                Err(())
            }
        }
    }

    /// Set the power levels.
    pub(crate) async fn set_power_levels(&self, power_levels: RoomPowerLevels) -> Result<(), ()> {
        let Some(room) = self.room() else {
            return Err(());
        };

        let matrix_room = room.matrix_room().clone();
        let handle = spawn_tokio!(async move {
            let event = RoomPowerLevelsEventContent::from(power_levels);
            matrix_room.send_state_event(event).await
        });

        match handle.await.expect("task was not aborted") {
            Ok(_) => Ok(()),
            Err(error) => {
                error!("Failed to set power levels: {error}");
                Err(())
            }
        }
    }

    /// Whether the user with the given ID is allowed to do the given action.
    pub(crate) fn user_is_allowed_to(
        &self,
        user_id: &UserId,
        room_action: PowerLevelAction,
    ) -> bool {
        self.imp()
            .power_levels
            .borrow()
            .user_can_do(user_id, room_action)
    }

    /// Connect to the signal emitted when the permissions changed.
    pub(crate) fn connect_changed<F: Fn(&Self) + 'static>(&self, f: F) -> glib::SignalHandlerId {
        self.connect_closure(
            "changed",
            true,
            closure_local!(move |obj: Self| {
                f(&obj);
            }),
        )
    }
}

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