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
use gtk::{glib, glib::clone, prelude::*, subclass::prelude::*};
use matrix_sdk::room::RoomMember;
use ruma::{
    events::room::{
        member::MembershipState,
        power_levels::{NotificationPowerLevelType, PowerLevelAction},
    },
    OwnedEventId, OwnedUserId,
};
use tracing::{debug, error};

use super::{
    permissions::{PowerLevel, POWER_LEVEL_MAX, POWER_LEVEL_MIN},
    MemberRole, Room,
};
use crate::{components::PillSource, prelude::*, session::model::User, spawn, spawn_tokio};

#[derive(Debug, Default, Hash, Eq, PartialEq, Clone, Copy, glib::Enum, glib::Variant)]
#[variant_enum(repr)]
#[repr(u32)]
#[enum_type(name = "Membership")]
pub enum Membership {
    #[default]
    Leave = 0,
    Join = 1,
    Invite = 2,
    Ban = 3,
    Knock = 4,
    Custom = 5,
}

impl From<&MembershipState> for Membership {
    fn from(state: &MembershipState) -> Self {
        match state {
            MembershipState::Leave => Membership::Leave,
            MembershipState::Join => Membership::Join,
            MembershipState::Invite => Membership::Invite,
            MembershipState::Ban => Membership::Ban,
            MembershipState::Knock => Membership::Knock,
            _ => Membership::Custom,
        }
    }
}

impl From<MembershipState> for Membership {
    fn from(state: MembershipState) -> Self {
        Membership::from(&state)
    }
}

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

    use super::*;

    #[derive(Debug, Default, glib::Properties)]
    #[properties(wrapper_type = super::Member)]
    pub struct Member {
        /// The room of the member.
        #[property(get, set = Self::set_room, construct_only)]
        pub room: OnceCell<Room>,
        /// The power level of the member.
        #[property(get, minimum = POWER_LEVEL_MIN, maximum = POWER_LEVEL_MAX)]
        pub power_level: Cell<PowerLevel>,
        /// The role of the member.
        #[property(get, builder(MemberRole::default()))]
        pub role: Cell<MemberRole>,
        /// This member's membership state.
        #[property(get, builder(Membership::default()))]
        pub membership: Cell<Membership>,
        /// The timestamp of the latest activity of this member.
        #[property(get, set = Self::set_latest_activity, explicit_notify)]
        pub latest_activity: Cell<u64>,
        power_level_handlers: RefCell<Vec<glib::SignalHandlerId>>,
    }

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

    #[glib::derived_properties]
    impl ObjectImpl for Member {
        fn dispose(&self) {
            if let Some(room) = self.room.get() {
                for handler in self.power_level_handlers.take() {
                    room.permissions().disconnect(handler);
                }
            }
        }
    }

    impl PillSourceImpl for Member {
        fn identifier(&self) -> String {
            self.obj().upcast_ref::<User>().user_id_string()
        }
    }

    impl Member {
        /// Set the room of the member.
        fn set_room(&self, room: Room) {
            let obj = self.obj();

            let default_pl_handler = room.permissions().connect_default_power_level_notify(
                clone!(@weak obj => move |_| {
                    obj.update_role();
                }),
            );
            let mute_pl_handler =
                room.permissions()
                    .connect_mute_power_level_notify(clone!(@weak obj => move |_| {
                        obj.update_role();
                    }));
            self.power_level_handlers
                .replace(vec![default_pl_handler, mute_pl_handler]);

            self.room.set(room).unwrap();
        }

        /// Set the timestamp of the latest activity of this member.
        fn set_latest_activity(&self, activity: u64) {
            if self.latest_activity.get() >= activity {
                return;
            }

            self.latest_activity.set(activity);
            self.obj().notify_latest_activity();
        }
    }
}

glib::wrapper! {
    /// A User in the context of a given room.
    pub struct Member(ObjectSubclass<imp::Member>) @extends PillSource, User;
}

impl Member {
    pub fn new(room: &Room, user_id: OwnedUserId) -> Self {
        let session = room.session();
        let obj = glib::Object::builder::<Self>()
            .property("session", &session)
            .property("room", room)
            .build();

        obj.upcast_ref::<User>().imp().set_user_id(user_id);
        obj
    }

    /// Set the power level of the member.
    pub(super) fn set_power_level(&self, power_level: PowerLevel) {
        if self.power_level() == power_level {
            return;
        }

        self.imp().power_level.set(power_level);
        self.update_role();
        self.notify_power_level();
    }

    /// Update the role of the member.
    fn update_role(&self) {
        let role = self.room().permissions().role(self.power_level());

        if self.role() == role {
            return;
        }

        self.imp().role.set(role);
        self.notify_role();
    }

    /// Set this member's membership state.
    fn set_membership(&self, membership: Membership) {
        if self.membership() == membership {
            return;
        }

        let imp = self.imp();
        imp.membership.replace(membership);
        self.notify_membership();
    }

    /// Update this member with the data from the given SDK's member.
    pub fn update_from_room_member(&self, member: &RoomMember) {
        if member.user_id() != self.user_id() {
            error!("Tried Member update from RoomMember with wrong user ID.");
            return;
        };

        self.set_name(member.display_name().map(ToOwned::to_owned));
        self.set_is_name_ambiguous(member.name_ambiguous());
        self.avatar_data()
            .image()
            .unwrap()
            .set_uri(member.avatar_url().map(ToString::to_string));
        self.set_power_level(member.power_level());
        self.set_membership(member.membership().into());
    }

    /// Update this member with the SDK's data.
    pub fn update(&self) {
        spawn!(clone!(@weak self as obj => async move {
            obj.update_inner().await;
        }));
    }

    async fn update_inner(&self) {
        let room = self.room();

        let matrix_room = room.matrix_room().clone();
        let user_id = self.user_id().clone();
        let handle = spawn_tokio!(async move { matrix_room.get_member_no_sync(&user_id).await });

        match handle.await.unwrap() {
            Ok(Some(member)) => self.update_from_room_member(&member),
            Ok(None) => {
                debug!("Room member {} not found", self.user_id());
            }
            Err(error) => {
                error!("Could not load room member {}: {error}", self.user_id());
            }
        }
    }

    /// The IDs of the events sent by this member that can be redacted.
    pub fn redactable_events(&self) -> Vec<OwnedEventId> {
        self.room().timeline().redactable_events_for(self.user_id())
    }

    /// Whether this room member can notify the whole room.
    pub fn can_notify_room(&self) -> bool {
        self.room().permissions().user_is_allowed_to(
            self.user_id(),
            PowerLevelAction::TriggerNotification(NotificationPowerLevelType::Room),
        )
    }
}