use std::{borrow::Cow, collections::BTreeMap};
use ruma_events_macros::EventContent;
use ruma_identifiers::RoomId;
use ruma_serde::from_raw_json_value;
use serde::{
de::{Deserializer, Error},
Deserialize, Serialize,
};
use serde_json::{value::RawValue as RawJsonValue, Value as JsonValue};
use crate::PrivOwnedStr;
#[derive(Clone, Debug, Serialize, EventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.room.join_rules", kind = State)]
pub struct RoomJoinRulesEventContent {
#[ruma_event(skip_redaction)]
#[serde(flatten)]
pub join_rule: JoinRule,
}
impl RoomJoinRulesEventContent {
pub fn new(join_rule: JoinRule) -> Self {
Self { join_rule }
}
pub fn restricted(allow: Vec<AllowRule>) -> Self {
Self { join_rule: JoinRule::Restricted(Restricted::new(allow)) }
}
}
impl<'de> Deserialize<'de> for RoomJoinRulesEventContent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let join_rule = JoinRule::deserialize(deserializer)?;
Ok(RoomJoinRulesEventContent { join_rule })
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[serde(tag = "join_rule")]
pub enum JoinRule {
#[serde(rename = "invite")]
Invite,
#[serde(rename = "knock")]
Knock,
#[serde(rename = "private")]
Private,
#[serde(rename = "restricted")]
Restricted(Restricted),
#[serde(rename = "public")]
Public,
#[doc(hidden)]
#[serde(skip_serializing)]
_Custom(PrivOwnedStr),
}
impl JoinRule {
pub fn as_str(&self) -> &str {
match self {
JoinRule::Invite => "invite",
JoinRule::Knock => "knock",
JoinRule::Private => "private",
JoinRule::Restricted(_) => "restricted",
JoinRule::Public => "public",
JoinRule::_Custom(rule) => &rule.0,
}
}
}
impl<'de> Deserialize<'de> for JoinRule {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let json: Box<RawJsonValue> = Box::deserialize(deserializer)?;
#[derive(Deserialize)]
struct ExtractType<'a> {
join_rule: Option<Cow<'a, str>>,
}
let join_rule = serde_json::from_str::<ExtractType<'_>>(json.get())
.map_err(serde::de::Error::custom)?
.join_rule
.ok_or_else(|| D::Error::missing_field("join_rule"))?;
match join_rule.as_ref() {
"invite" => Ok(Self::Invite),
"knock" => Ok(Self::Knock),
"private" => Ok(Self::Private),
"restricted" => from_raw_json_value(&json).map(Self::Restricted),
"public" => Ok(Self::Public),
_ => Ok(Self::_Custom(PrivOwnedStr(join_rule.into()))),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Restricted {
allow: Vec<AllowRule>,
}
impl Restricted {
pub fn new(allow: Vec<AllowRule>) -> Self {
Self { allow }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[serde(tag = "type")]
pub enum AllowRule {
#[serde(rename = "m.room_membership")]
RoomMembership(RoomMembership),
#[doc(hidden)]
_Custom(CustomAllowRule),
}
impl AllowRule {
pub fn room_membership(room_id: Box<RoomId>) -> Self {
Self::RoomMembership(RoomMembership::new(room_id))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct RoomMembership {
pub room_id: Box<RoomId>,
}
impl RoomMembership {
pub fn new(room_id: Box<RoomId>) -> Self {
Self { room_id }
}
}
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct CustomAllowRule {
#[serde(rename = "type")]
rule_type: String,
#[serde(flatten)]
extra: BTreeMap<String, JsonValue>,
}
impl<'de> Deserialize<'de> for AllowRule {
fn deserialize<D>(deserializer: D) -> Result<AllowRule, D::Error>
where
D: Deserializer<'de>,
{
let json: Box<RawJsonValue> = Box::deserialize(deserializer)?;
#[derive(Deserialize)]
struct ExtractType<'a> {
#[serde(borrow, rename = "type")]
rule_type: Option<Cow<'a, str>>,
}
let rule_type = serde_json::from_str::<ExtractType<'_>>(json.get())
.map_err(serde::de::Error::custom)?
.rule_type;
match rule_type.as_deref() {
Some("m.room_membership") => from_raw_json_value(&json).map(Self::RoomMembership),
Some(_) => from_raw_json_value(&json).map(Self::_Custom),
None => Err(D::Error::missing_field("type")),
}
}
}
#[cfg(test)]
mod tests {
use matches::assert_matches;
use ruma_identifiers::room_id;
use super::{AllowRule, JoinRule, RoomJoinRulesEventContent, SyncRoomJoinRulesEvent};
#[test]
fn deserialize() {
let json = r#"{"join_rule": "public"}"#;
let event: RoomJoinRulesEventContent = serde_json::from_str(json).unwrap();
assert_matches!(event, RoomJoinRulesEventContent { join_rule: JoinRule::Public });
}
#[test]
fn deserialize_restricted() {
let json = r#"{
"join_rule": "restricted",
"allow": [
{
"type": "m.room_membership",
"room_id": "!mods:example.org"
},
{
"type": "m.room_membership",
"room_id": "!users:example.org"
}
]
}"#;
let event: RoomJoinRulesEventContent = serde_json::from_str(json).unwrap();
match event.join_rule {
JoinRule::Restricted(restricted) => assert_eq!(
restricted.allow,
&[
AllowRule::room_membership(room_id!("!mods:example.org").to_owned()),
AllowRule::room_membership(room_id!("!users:example.org").to_owned())
]
),
rule => panic!("Deserialized to wrong variant: {:?}", rule),
}
}
#[test]
fn deserialize_restricted_event() {
let json = r#"{
"type": "m.room.join_rules",
"sender": "@admin:community.rs",
"content": {
"join_rule": "restricted",
"allow":[
{ "type": "m.room_membership","room_id": "!KqeUnzmXPIhHRaWMTs:mccarty.io" }
]
},
"state_key": "",
"origin_server_ts":1630508835342,
"unsigned": {
"age":4165521871
},
"event_id": "$0ACb9KSPlT3al3kikyRYvFhMqXPP9ZcQOBrsdIuh58U"
}"#;
assert_matches!(serde_json::from_str::<SyncRoomJoinRulesEvent>(json), Ok(_));
}
}