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
// Copyright 2020 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Arc,
};

use ruma::{
    events::{
        presence::PresenceEvent,
        room::{
            member::MembershipState,
            power_levels::{PowerLevelAction, RoomPowerLevels, RoomPowerLevelsEventContent},
        },
        MessageLikeEventType, StateEventType,
    },
    MxcUri, OwnedUserId, UserId,
};

use crate::{
    deserialized_responses::{MemberEvent, SyncOrStrippedState},
    MinimalRoomMemberEvent,
};

/// A member of a room.
#[derive(Clone, Debug)]
pub struct RoomMember {
    pub(crate) event: Arc<MemberEvent>,
    // The latest member event sent by the member themselves.
    // Stored in addition to the latest member event overall to get displayname
    // and avatar from, which should be ignored on events sent by others.
    pub(crate) profile: Arc<Option<MinimalRoomMemberEvent>>,
    #[allow(dead_code)]
    pub(crate) presence: Arc<Option<PresenceEvent>>,
    pub(crate) power_levels: Arc<Option<SyncOrStrippedState<RoomPowerLevelsEventContent>>>,
    pub(crate) max_power_level: i64,
    pub(crate) is_room_creator: bool,
    pub(crate) display_name_ambiguous: bool,
    pub(crate) is_ignored: bool,
}

impl RoomMember {
    pub(crate) fn from_parts(
        event: MemberEvent,
        profile: Option<MinimalRoomMemberEvent>,
        presence: Option<PresenceEvent>,
        room_info: &MemberRoomInfo<'_>,
    ) -> Self {
        let MemberRoomInfo {
            power_levels,
            max_power_level,
            room_creator,
            users_display_names,
            ignored_users,
        } = room_info;

        let is_room_creator = room_creator.as_deref() == Some(event.user_id());
        let display_name_ambiguous =
            users_display_names.get(event.display_name()).is_some_and(|s| s.len() > 1);
        let is_ignored = ignored_users.as_ref().is_some_and(|s| s.contains(event.user_id()));

        Self {
            event: event.into(),
            profile: profile.into(),
            presence: presence.into(),
            power_levels: power_levels.clone(),
            max_power_level: *max_power_level,
            is_room_creator,
            display_name_ambiguous,
            is_ignored,
        }
    }

    /// Get the unique user id of this member.
    pub fn user_id(&self) -> &UserId {
        self.event.user_id()
    }

    /// Get the original member event
    pub fn event(&self) -> &Arc<MemberEvent> {
        &self.event
    }

    /// Get the display name of the member if there is one.
    pub fn display_name(&self) -> Option<&str> {
        if let Some(p) = self.profile.as_ref() {
            p.as_original().and_then(|e| e.content.displayname.as_deref())
        } else {
            self.event.original_content()?.displayname.as_deref()
        }
    }

    /// Get the name of the member.
    ///
    /// This returns either the display name or the local part of the user id if
    /// the member didn't set a display name.
    pub fn name(&self) -> &str {
        if let Some(d) = self.display_name() {
            d
        } else {
            self.user_id().localpart()
        }
    }

    /// Get the avatar url of the member, if there is one.
    pub fn avatar_url(&self) -> Option<&MxcUri> {
        if let Some(p) = self.profile.as_ref() {
            p.as_original().and_then(|e| e.content.avatar_url.as_deref())
        } else {
            self.event.original_content()?.avatar_url.as_deref()
        }
    }

    /// Get the normalized power level of this member.
    ///
    /// The normalized power level depends on the maximum power level that can
    /// be found in a certain room, positive values are always in the range of
    /// 0-100.
    pub fn normalized_power_level(&self) -> i64 {
        if self.max_power_level > 0 {
            (self.power_level() * 100) / self.max_power_level
        } else {
            self.power_level()
        }
    }

    /// Get the power level of this member.
    pub fn power_level(&self) -> i64 {
        (*self.power_levels)
            .as_ref()
            .map(|e| e.power_levels().for_user(self.user_id()).into())
            .unwrap_or_else(|| if self.is_room_creator { 100 } else { 0 })
    }

    /// Whether this user can ban other users based on the power levels.
    ///
    /// Same as `member.can_do(PowerLevelAction::Ban)`.
    pub fn can_ban(&self) -> bool {
        self.can_do_impl(|pls| pls.user_can_ban(self.user_id()))
    }

    /// Whether this user can invite other users based on the power levels.
    ///
    /// Same as `member.can_do(PowerLevelAction::Invite)`.
    pub fn can_invite(&self) -> bool {
        self.can_do_impl(|pls| pls.user_can_invite(self.user_id()))
    }

    /// Whether this user can kick other users based on the power levels.
    ///
    /// Same as `member.can_do(PowerLevelAction::Kick)`.
    pub fn can_kick(&self) -> bool {
        self.can_do_impl(|pls| pls.user_can_kick(self.user_id()))
    }

    /// Whether this user can redact their own events based on the power levels.
    ///
    /// Same as `member.can_do(PowerLevelAction::RedactOwn)`.
    pub fn can_redact_own(&self) -> bool {
        self.can_do_impl(|pls| pls.user_can_redact_own_event(self.user_id()))
    }

    /// Whether this user can redact events of other users based on the power
    /// levels.
    ///
    /// Same as `member.can_do(PowerLevelAction::RedactOther)`.
    pub fn can_redact_other(&self) -> bool {
        self.can_do_impl(|pls| pls.user_can_redact_event_of_other(self.user_id()))
    }

    /// Whether this user can send message events based on the power levels.
    ///
    /// Same as `member.can_do(PowerLevelAction::SendMessage(msg_type))`.
    pub fn can_send_message(&self, msg_type: MessageLikeEventType) -> bool {
        self.can_do_impl(|pls| pls.user_can_send_message(self.user_id(), msg_type))
    }

    /// Whether this user can send state events based on the power levels.
    ///
    /// Same as `member.can_do(PowerLevelAction::SendState(state_type))`.
    pub fn can_send_state(&self, state_type: StateEventType) -> bool {
        self.can_do_impl(|pls| pls.user_can_send_state(self.user_id(), state_type))
    }

    /// Whether this user can pin or unpin events based on the power levels.
    pub fn can_pin_or_unpin_event(&self) -> bool {
        self.can_send_state(StateEventType::RoomPinnedEvents)
    }

    /// Whether this user can notify everybody in the room by writing `@room` in
    /// a message.
    ///
    /// Same as `member.
    /// can_do(PowerLevelAction::TriggerNotification(NotificationPowerLevelType::Room))`.
    pub fn can_trigger_room_notification(&self) -> bool {
        self.can_do_impl(|pls| pls.user_can_trigger_room_notification(self.user_id()))
    }

    /// Whether this user can do the given action based on the power
    /// levels.
    pub fn can_do(&self, action: PowerLevelAction) -> bool {
        self.can_do_impl(|pls| pls.user_can_do(self.user_id(), action))
    }

    fn can_do_impl(&self, f: impl FnOnce(RoomPowerLevels) -> bool) -> bool {
        match &*self.power_levels {
            Some(event) => f(event.power_levels()),
            None => self.is_room_creator,
        }
    }

    /// Is the name that the member uses ambiguous in the room.
    ///
    /// A name is considered to be ambiguous if at least one other member shares
    /// the same name.
    pub fn name_ambiguous(&self) -> bool {
        self.display_name_ambiguous
    }

    /// Get the membership state of this member.
    pub fn membership(&self) -> &MembershipState {
        self.event.membership()
    }

    /// Is the room member ignored by the current account user
    pub fn is_ignored(&self) -> bool {
        self.is_ignored
    }
}

// Information about the room a member is in.
pub(crate) struct MemberRoomInfo<'a> {
    pub(crate) power_levels: Arc<Option<SyncOrStrippedState<RoomPowerLevelsEventContent>>>,
    pub(crate) max_power_level: i64,
    pub(crate) room_creator: Option<OwnedUserId>,
    pub(crate) users_display_names: BTreeMap<&'a str, BTreeSet<OwnedUserId>>,
    pub(crate) ignored_users: Option<BTreeSet<OwnedUserId>>,
}