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
//! Types for the *m.room.power_levels* event.

use std::collections::HashMap;

use js_int::{Int, UInt};
use ruma_identifiers::{EventId, RoomId, UserId};
use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
use serde_json::{Map, Value};

use crate::{Event as _, EventType, FromRaw};

/// Defines the power levels (privileges) of users in the room.
#[derive(Clone, Debug, PartialEq)]
pub struct PowerLevelsEvent {
    /// The event's content.
    pub content: PowerLevelsEventContent,

    /// The unique identifier for the event.
    pub event_id: EventId,

    /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this
    /// event was sent.
    pub origin_server_ts: UInt,

    /// The previous content for this state key, if any.
    pub prev_content: Option<PowerLevelsEventContent>,

    /// The unique identifier for the room associated with this event.
    pub room_id: Option<RoomId>,

    /// Additional key-value pairs not signed by the homeserver.
    pub unsigned: Map<String, Value>,

    /// The unique identifier for the user who sent this event.
    pub sender: UserId,

    /// A key that determines which piece of room state the event represents.
    pub state_key: String,
}

/// The payload for `PowerLevelsEvent`.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct PowerLevelsEventContent {
    /// The level required to ban a user.
    #[serde(skip_serializing_if = "is_default_power_level")]
    pub ban: Int,

    /// The level required to send specific event types.
    ///
    /// This is a mapping from event type to power level required.
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub events: HashMap<EventType, Int>,

    /// The default level required to send message events.
    #[serde(skip_serializing_if = "is_power_level_zero")]
    pub events_default: Int,

    /// The level required to invite a user.
    #[serde(skip_serializing_if = "is_default_power_level")]
    pub invite: Int,

    /// The level required to kick a user.
    #[serde(skip_serializing_if = "is_default_power_level")]
    pub kick: Int,

    /// The level required to redact an event.
    #[serde(skip_serializing_if = "is_default_power_level")]
    pub redact: Int,

    /// The default level required to send state events.
    #[serde(skip_serializing_if = "is_default_power_level")]
    pub state_default: Int,

    /// The power levels for specific users.
    ///
    /// This is a mapping from `user_id` to power level for that user.
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub users: HashMap<UserId, Int>,

    /// The default power level for every user in the room.
    #[serde(skip_serializing_if = "is_power_level_zero")]
    pub users_default: Int,

    /// The power level requirements for specific notification types.
    ///
    /// This is a mapping from `key` to power level for that notifications key.
    #[serde(skip_serializing_if = "NotificationPowerLevels::is_default")]
    pub notifications: NotificationPowerLevels,
}

impl FromRaw for PowerLevelsEvent {
    type Raw = raw::PowerLevelsEvent;

    fn from_raw(raw: raw::PowerLevelsEvent) -> Self {
        Self {
            content: FromRaw::from_raw(raw.content),
            event_id: raw.event_id,
            origin_server_ts: raw.origin_server_ts,
            prev_content: raw.prev_content.map(FromRaw::from_raw),
            room_id: raw.room_id,
            unsigned: raw.unsigned,
            sender: raw.sender,
            state_key: raw.state_key,
        }
    }
}

impl FromRaw for PowerLevelsEventContent {
    type Raw = raw::PowerLevelsEventContent;

    fn from_raw(raw: raw::PowerLevelsEventContent) -> Self {
        Self {
            ban: raw.ban,
            events: raw.events,
            events_default: raw.events_default,
            invite: raw.invite,
            kick: raw.kick,
            redact: raw.redact,
            state_default: raw.state_default,
            users: raw.users,
            users_default: raw.users_default,
            notifications: raw.notifications,
        }
    }
}

impl Serialize for PowerLevelsEvent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 6;

        if self.prev_content.is_some() {
            len += 1;
        }

        if self.room_id.is_some() {
            len += 1;
        }

        if !self.unsigned.is_empty() {
            len += 1;
        }

        let mut state = serializer.serialize_struct("PowerLevelsEvent", len)?;

        state.serialize_field("content", &self.content)?;
        state.serialize_field("event_id", &self.event_id)?;
        state.serialize_field("origin_server_ts", &self.origin_server_ts)?;

        if self.prev_content.is_some() {
            state.serialize_field("prev_content", &self.prev_content)?;
        }

        if self.room_id.is_some() {
            state.serialize_field("room_id", &self.room_id)?;
        }

        state.serialize_field("sender", &self.sender)?;
        state.serialize_field("state_key", &self.state_key)?;
        state.serialize_field("type", &self.event_type())?;

        if !self.unsigned.is_empty() {
            state.serialize_field("unsigned", &self.unsigned)?;
        }

        state.end()
    }
}

impl_state_event!(
    PowerLevelsEvent,
    PowerLevelsEventContent,
    EventType::RoomPowerLevels
);

pub(crate) mod raw {
    use super::*;

    /// Defines the power levels (privileges) of users in the room.
    #[derive(Clone, Debug, Deserialize, PartialEq)]
    pub struct PowerLevelsEvent {
        /// The event's content.
        pub content: PowerLevelsEventContent,

        /// The unique identifier for the event.
        pub event_id: EventId,

        /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this
        /// event was sent.
        pub origin_server_ts: UInt,

        /// The previous content for this state key, if any.
        pub prev_content: Option<PowerLevelsEventContent>,

        /// The unique identifier for the room associated with this event.
        pub room_id: Option<RoomId>,

        /// Additional key-value pairs not signed by the homeserver.
        #[serde(default)]
        pub unsigned: Map<String, Value>,

        /// The unique identifier for the user who sent this event.
        pub sender: UserId,

        /// A key that determines which piece of room state the event represents.
        pub state_key: String,
    }

    /// The payload for `PowerLevelsEvent`.
    #[derive(Clone, Debug, Deserialize, PartialEq)]
    pub struct PowerLevelsEventContent {
        /// The level required to ban a user.
        #[serde(default = "default_power_level")]
        pub ban: Int,

        /// The level required to send specific event types.
        ///
        /// This is a mapping from event type to power level required.
        #[serde(default)]
        pub events: HashMap<EventType, Int>,

        /// The default level required to send message events.
        #[serde(default)]
        pub events_default: Int,

        /// The level required to invite a user.
        #[serde(default = "default_power_level")]
        pub invite: Int,

        /// The level required to kick a user.
        #[serde(default = "default_power_level")]
        pub kick: Int,

        /// The level required to redact an event.
        #[serde(default = "default_power_level")]
        pub redact: Int,

        /// The default level required to send state events.
        #[serde(default = "default_power_level")]
        pub state_default: Int,

        /// The power levels for specific users.
        ///
        /// This is a mapping from `user_id` to power level for that user.
        #[serde(default)]
        pub users: HashMap<UserId, Int>,

        /// The default power level for every user in the room.
        #[serde(default)]
        pub users_default: Int,

        /// The power level requirements for specific notification types.
        ///
        /// This is a mapping from `key` to power level for that notifications key.
        #[serde(default)]
        pub notifications: NotificationPowerLevels,
    }
}

/// The power level requirements for specific notification types.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub struct NotificationPowerLevels {
    /// The level required to trigger an `@room` notification.
    #[serde(default = "default_power_level")]
    pub room: Int,
}

impl NotificationPowerLevels {
    // TODO: Make public under this name?
    // pass-by-ref required for #[serde(skip_serializing_if)]
    #[allow(clippy::trivially_copy_pass_by_ref)]
    fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

impl Default for NotificationPowerLevels {
    fn default() -> Self {
        Self {
            room: default_power_level(),
        }
    }
}

/// Used to default power levels to 50 during deserialization.
fn default_power_level() -> Int {
    Int::from(50)
}

/// Used with #[serde(skip_serializing_if)] to omit default power levels.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_default_power_level(l: &Int) -> bool {
    *l == Int::from(50)
}

/// Used with #[serde(skip_serializing_if)] to omit default power levels.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_power_level_zero(l: &Int) -> bool {
    *l == Int::from(0)
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, convert::TryFrom};

    use js_int::{Int, UInt};
    use maplit::hashmap;
    use ruma_identifiers::{EventId, RoomId, UserId};
    use serde_json::Map;

    use super::{
        default_power_level, NotificationPowerLevels, PowerLevelsEvent, PowerLevelsEventContent,
    };
    use crate::EventType;

    #[test]
    fn serialization_with_optional_fields_as_none() {
        let default = default_power_level();

        let power_levels_event = PowerLevelsEvent {
            content: PowerLevelsEventContent {
                ban: default,
                events: HashMap::new(),
                events_default: Int::from(0),
                invite: default,
                kick: default,
                redact: default,
                state_default: default,
                users: HashMap::new(),
                users_default: Int::from(0),
                notifications: NotificationPowerLevels::default(),
            },
            event_id: EventId::try_from("$h29iv0s8:example.com").unwrap(),
            origin_server_ts: UInt::from(1u32),
            prev_content: None,
            room_id: None,
            unsigned: Map::new(),
            sender: UserId::try_from("@carl:example.com").unwrap(),
            state_key: "".to_string(),
        };

        let actual = serde_json::to_string(&power_levels_event).unwrap();
        let expected = r#"{"content":{},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.power_levels"}"#;

        assert_eq!(actual, expected);
    }

    #[test]
    fn serialization_with_all_fields() {
        let user = UserId::try_from("@carl:example.com").unwrap();
        let power_levels_event = PowerLevelsEvent {
            content: PowerLevelsEventContent {
                ban: Int::from(23),
                events: hashmap! {
                    EventType::Dummy => Int::from(23)
                },
                events_default: Int::from(23),
                invite: Int::from(23),
                kick: Int::from(23),
                redact: Int::from(23),
                state_default: Int::from(23),
                users: hashmap! {
                    user.clone() => Int::from(23)
                },
                users_default: Int::from(23),
                notifications: NotificationPowerLevels {
                    room: Int::from(23),
                },
            },
            event_id: EventId::try_from("$h29iv0s8:example.com").unwrap(),
            origin_server_ts: UInt::from(1u32),
            prev_content: Some(PowerLevelsEventContent {
                // Make just one field different so we at least know they're two different objects.
                ban: Int::from(42),
                events: hashmap! {
                    EventType::Dummy => Int::from(42)
                },
                events_default: Int::from(42),
                invite: Int::from(42),
                kick: Int::from(42),
                redact: Int::from(42),
                state_default: Int::from(42),
                users: hashmap! {
                    user.clone() => Int::from(42)
                },
                users_default: Int::from(42),
                notifications: NotificationPowerLevels {
                    room: Int::from(42),
                },
            }),
            room_id: Some(RoomId::try_from("!n8f893n9:example.com").unwrap()),
            unsigned: serde_json::from_str(r#"{"foo":"bar"}"#).unwrap(),
            sender: user,
            state_key: "".to_string(),
        };

        let actual = serde_json::to_string(&power_levels_event).unwrap();
        let expected = r#"{"content":{"ban":23,"events":{"m.dummy":23},"events_default":23,"invite":23,"kick":23,"redact":23,"state_default":23,"users":{"@carl:example.com":23},"users_default":23,"notifications":{"room":23}},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"prev_content":{"ban":42,"events":{"m.dummy":42},"events_default":42,"invite":42,"kick":42,"redact":42,"state_default":42,"users":{"@carl:example.com":42},"users_default":42,"notifications":{"room":42}},"room_id":"!n8f893n9:example.com","sender":"@carl:example.com","state_key":"","type":"m.room.power_levels","unsigned":{"foo":"bar"}}"#;

        assert_eq!(actual, expected);
    }
}