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};
#[derive(Clone, Debug, PartialEq)]
pub struct PowerLevelsEvent {
pub content: PowerLevelsEventContent,
pub event_id: EventId,
pub origin_server_ts: UInt,
pub prev_content: Option<PowerLevelsEventContent>,
pub room_id: Option<RoomId>,
pub unsigned: Map<String, Value>,
pub sender: UserId,
pub state_key: String,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct PowerLevelsEventContent {
#[serde(skip_serializing_if = "is_default_power_level")]
pub ban: Int,
#[serde(skip_serializing_if = "HashMap::is_empty")]
pub events: HashMap<EventType, Int>,
#[serde(skip_serializing_if = "is_power_level_zero")]
pub events_default: Int,
#[serde(skip_serializing_if = "is_default_power_level")]
pub invite: Int,
#[serde(skip_serializing_if = "is_default_power_level")]
pub kick: Int,
#[serde(skip_serializing_if = "is_default_power_level")]
pub redact: Int,
#[serde(skip_serializing_if = "is_default_power_level")]
pub state_default: Int,
#[serde(skip_serializing_if = "HashMap::is_empty")]
pub users: HashMap<UserId, Int>,
#[serde(skip_serializing_if = "is_power_level_zero")]
pub users_default: Int,
#[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::*;
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PowerLevelsEvent {
pub content: PowerLevelsEventContent,
pub event_id: EventId,
pub origin_server_ts: UInt,
pub prev_content: Option<PowerLevelsEventContent>,
pub room_id: Option<RoomId>,
#[serde(default)]
pub unsigned: Map<String, Value>,
pub sender: UserId,
pub state_key: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PowerLevelsEventContent {
#[serde(default = "default_power_level")]
pub ban: Int,
#[serde(default)]
pub events: HashMap<EventType, Int>,
#[serde(default)]
pub events_default: Int,
#[serde(default = "default_power_level")]
pub invite: Int,
#[serde(default = "default_power_level")]
pub kick: Int,
#[serde(default = "default_power_level")]
pub redact: Int,
#[serde(default = "default_power_level")]
pub state_default: Int,
#[serde(default)]
pub users: HashMap<UserId, Int>,
#[serde(default)]
pub users_default: Int,
#[serde(default)]
pub notifications: NotificationPowerLevels,
}
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub struct NotificationPowerLevels {
#[serde(default = "default_power_level")]
pub room: Int,
}
impl NotificationPowerLevels {
#[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(),
}
}
}
fn default_power_level() -> Int {
Int::from(50)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_default_power_level(l: &Int) -> bool {
*l == Int::from(50)
}
#[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 {
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);
}
}