events: Remove Serialize impls for all event types except ToDeviceEvent

This commit is contained in:
Jonas Platte 2022-12-14 13:37:01 +01:00 committed by Jonas Platte
parent 80733a8cee
commit cdabe8e52d
35 changed files with 775 additions and 1634 deletions

View File

@ -51,19 +51,15 @@ mod tests {
let mut content = DirectEventContent(BTreeMap::new()); let mut content = DirectEventContent(BTreeMap::new());
let server_name = server_name!("ruma.io"); let server_name = server_name!("ruma.io");
let alice = UserId::new(server_name); let alice = UserId::new(server_name);
let room = vec![RoomId::new(server_name)]; let rooms = vec![RoomId::new(server_name)];
content.insert(alice.clone(), room.clone()); content.insert(alice.clone(), rooms.clone());
let event = DirectEvent { content };
let json_data = json!({ let json_data = json!({
"content": { alice.to_string(): rooms,
alice.to_string(): vec![room[0].to_string()],
},
"type": "m.direct"
}); });
assert_eq!(to_json_value(&event).unwrap(), json_data); assert_eq!(to_json_value(&content).unwrap(), json_data);
} }
#[test] #[test]

View File

@ -55,29 +55,20 @@ mod tests {
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::IgnoredUserListEventContent; use super::IgnoredUserListEventContent;
use crate::{ use crate::{events::AnyGlobalAccountDataEvent, user_id};
events::{AnyGlobalAccountDataEvent, GlobalAccountDataEvent},
user_id,
};
#[test] #[test]
fn serialization() { fn serialization() {
let ignored_user_list_event = GlobalAccountDataEvent { let ignored_user_list =
content: IgnoredUserListEventContent::users(vec![ IgnoredUserListEventContent::users(vec![user_id!("@carl:example.com").to_owned()]);
user_id!("@carl:example.com").to_owned()
]),
};
let json = json!({ let json = json!({
"content": { "ignored_users": {
"ignored_users": { "@carl:example.com": {}
"@carl:example.com": {}
}
}, },
"type": "m.ignored_user_list"
}); });
assert_eq!(to_json_value(ignored_user_list_event).unwrap(), json); assert_eq!(to_json_value(ignored_user_list).unwrap(), json);
} }
#[test] #[test]

View File

@ -177,7 +177,6 @@ mod tests {
event_id, event_id,
events::{relation::Reference, ToDeviceEvent}, events::{relation::Reference, ToDeviceEvent},
serde::Base64, serde::Base64,
user_id,
}; };
#[test] #[test]
@ -193,37 +192,22 @@ mod tests {
}), }),
}; };
let sender = user_id!("@example:localhost").to_owned();
let json_data = json!({ let json_data = json!({
"content": { "transaction_id": "456",
"transaction_id": "456", "method": "m.sas.v1",
"method": "m.sas.v1", "commitment": "aGVsbG8",
"commitment": "aGVsbG8", "key_agreement_protocol": "curve25519",
"key_agreement_protocol": "curve25519", "hash": "sha256",
"hash": "sha256", "message_authentication_code": "hkdf-hmac-sha256",
"message_authentication_code": "hkdf-hmac-sha256", "short_authentication_string": ["decimal"]
"short_authentication_string": ["decimal"]
},
"sender": sender,
"type": "m.key.verification.accept"
}); });
let key_verification_accept = assert_eq!(to_json_value(&key_verification_accept_content).unwrap(), json_data);
ToDeviceEvent { sender, content: key_verification_accept_content };
assert_eq!(to_json_value(&key_verification_accept).unwrap(), json_data);
let sender = user_id!("@example:localhost").to_owned();
let json_data = json!({ let json_data = json!({
"content": { "transaction_id": "456",
"transaction_id": "456", "method": "m.sas.custom",
"method": "m.sas.custom", "test": "field",
"test": "field",
},
"sender": sender,
"type": "m.key.verification.accept"
}); });
let key_verification_accept_content = ToDeviceKeyVerificationAcceptEventContent { let key_verification_accept_content = ToDeviceKeyVerificationAcceptEventContent {
@ -236,10 +220,7 @@ mod tests {
}), }),
}; };
let key_verification_accept = assert_eq!(to_json_value(&key_verification_accept_content).unwrap(), json_data);
ToDeviceEvent { sender, content: key_verification_accept_content };
assert_eq!(to_json_value(&key_verification_accept).unwrap(), json_data);
} }
#[test] #[test]

View File

@ -219,7 +219,6 @@ mod tests {
event_id, event_id,
events::{relation::Reference, ToDeviceEvent}, events::{relation::Reference, ToDeviceEvent},
serde::Base64, serde::Base64,
user_id,
}; };
#[test] #[test]
@ -238,38 +237,23 @@ mod tests {
), ),
}; };
let sender = user_id!("@example:localhost").to_owned();
let json_data = json!({ let json_data = json!({
"content": { "from_device": "123",
"from_device": "123", "transaction_id": "456",
"transaction_id": "456", "method": "m.sas.v1",
"method": "m.sas.v1", "key_agreement_protocols": ["curve25519"],
"key_agreement_protocols": ["curve25519"], "hashes": ["sha256"],
"hashes": ["sha256"], "message_authentication_codes": ["hkdf-hmac-sha256"],
"message_authentication_codes": ["hkdf-hmac-sha256"], "short_authentication_string": ["decimal"]
"short_authentication_string": ["decimal"]
},
"type": "m.key.verification.start",
"sender": sender
}); });
let key_verification_start = assert_eq!(to_json_value(&key_verification_start_content).unwrap(), json_data);
ToDeviceEvent { sender, content: key_verification_start_content };
assert_eq!(to_json_value(&key_verification_start).unwrap(), json_data);
let sender = user_id!("@example:localhost").to_owned();
let json_data = json!({ let json_data = json!({
"content": { "from_device": "123",
"from_device": "123", "transaction_id": "456",
"transaction_id": "456", "method": "m.sas.custom",
"method": "m.sas.custom", "test": "field",
"test": "field",
},
"type": "m.key.verification.start",
"sender": sender
}); });
let key_verification_start_content = ToDeviceKeyVerificationStartEventContent { let key_verification_start_content = ToDeviceKeyVerificationStartEventContent {
@ -283,10 +267,7 @@ mod tests {
}), }),
}; };
let key_verification_start = assert_eq!(to_json_value(&key_verification_start_content).unwrap(), json_data);
ToDeviceEvent { sender, content: key_verification_start_content };
assert_eq!(to_json_value(&key_verification_start).unwrap(), json_data);
{ {
let secret = Base64::new(b"This is a secret to everybody".to_vec()); let secret = Base64::new(b"This is a secret to everybody".to_vec());

View File

@ -1,7 +1,7 @@
#![allow(clippy::exhaustive_structs)] #![allow(clippy::exhaustive_structs)]
use ruma_macros::Event; use ruma_macros::Event;
use serde::{Deserialize, Deserializer, Serialize}; use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize};
use serde_json::value::RawValue as RawJsonValue; use serde_json::value::RawValue as RawJsonValue;
use super::{ use super::{
@ -146,8 +146,7 @@ pub struct RedactedSyncMessageLikeEvent<C: RedactedMessageLikeEventContent> {
/// `MessageLikeEvent` implements the comparison traits using only the `event_id` field, a sorted /// `MessageLikeEvent` implements the comparison traits using only the `event_id` field, a sorted
/// list would be sorted lexicographically based on the event's `EventId`. /// list would be sorted lexicographically based on the event's `EventId`.
#[allow(clippy::exhaustive_enums)] #[allow(clippy::exhaustive_enums)]
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug)]
#[serde(untagged)]
pub enum MessageLikeEvent<C: MessageLikeEventContent + RedactContent> pub enum MessageLikeEvent<C: MessageLikeEventContent + RedactContent>
where where
C::Redacted: RedactedMessageLikeEventContent, C::Redacted: RedactedMessageLikeEventContent,
@ -164,8 +163,7 @@ where
/// `SyncMessageLikeEvent` implements the comparison traits using only the `event_id` field, a /// `SyncMessageLikeEvent` implements the comparison traits using only the `event_id` field, a
/// sorted list would be sorted lexicographically based on the event's `EventId`. /// sorted list would be sorted lexicographically based on the event's `EventId`.
#[allow(clippy::exhaustive_enums)] #[allow(clippy::exhaustive_enums)]
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug)]
#[serde(untagged)]
pub enum SyncMessageLikeEvent<C: MessageLikeEventContent + RedactContent> pub enum SyncMessageLikeEvent<C: MessageLikeEventContent + RedactContent>
where where
C::Redacted: RedactedMessageLikeEventContent, C::Redacted: RedactedMessageLikeEventContent,
@ -331,8 +329,7 @@ pub struct RedactedSyncStateEvent<C: RedactedStateEventContent> {
/// `StateEvent` implements the comparison traits using only the `event_id` field, a sorted list /// `StateEvent` implements the comparison traits using only the `event_id` field, a sorted list
/// would be sorted lexicographically based on the event's `EventId`. /// would be sorted lexicographically based on the event's `EventId`.
#[allow(clippy::exhaustive_enums)] #[allow(clippy::exhaustive_enums)]
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug)]
#[serde(untagged)]
pub enum StateEvent<C: StateEventContent + RedactContent> pub enum StateEvent<C: StateEventContent + RedactContent>
where where
C::Redacted: RedactedStateEventContent, C::Redacted: RedactedStateEventContent,
@ -349,8 +346,7 @@ where
/// `SyncStateEvent` implements the comparison traits using only the `event_id` field, a sorted list /// `SyncStateEvent` implements the comparison traits using only the `event_id` field, a sorted list
/// would be sorted lexicographically based on the event's `EventId`. /// would be sorted lexicographically based on the event's `EventId`.
#[allow(clippy::exhaustive_enums)] #[allow(clippy::exhaustive_enums)]
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug)]
#[serde(untagged)]
pub enum SyncStateEvent<C: StateEventContent + RedactContent> pub enum SyncStateEvent<C: StateEventContent + RedactContent>
where where
C::Redacted: RedactedStateEventContent, C::Redacted: RedactedStateEventContent,
@ -372,6 +368,19 @@ pub struct ToDeviceEvent<C: ToDeviceEventContent> {
pub sender: OwnedUserId, pub sender: OwnedUserId,
} }
impl<C: ToDeviceEventContent> Serialize for ToDeviceEvent<C> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_struct("ToDeviceEvent", 3)?;
state.serialize_field("type", &self.content.event_type())?;
state.serialize_field("content", &self.content)?;
state.serialize_field("sender", &self.sender)?;
state.end()
}
}
/// The decrypted payload of an `m.olm.v1.curve25519-aes-sha2` event. /// The decrypted payload of an `m.olm.v1.curve25519-aes-sha2` event.
#[derive(Clone, Debug, Event)] #[derive(Clone, Debug, Event)]
pub struct DecryptedOlmV1Event<C: MessageLikeEventContent> { pub struct DecryptedOlmV1Event<C: MessageLikeEventContent> {

View File

@ -17,55 +17,29 @@ pub struct PolicyRuleRoomEventContent(pub PolicyRuleEventContent);
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use js_int::int;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{OriginalPolicyRuleRoomEvent, PolicyRuleRoomEventContent}; use super::{OriginalPolicyRuleRoomEvent, PolicyRuleRoomEventContent};
use crate::{ use crate::{
event_id, events::policy::rule::{PolicyRuleEventContent, Recommendation},
events::{
policy::rule::{PolicyRuleEventContent, Recommendation},
StateUnsigned,
},
room_id,
serde::Raw, serde::Raw,
user_id, MilliSecondsSinceUnixEpoch,
}; };
#[test] #[test]
fn serialization() { fn serialization() {
let room_event = OriginalPolicyRuleRoomEvent { let content = PolicyRuleRoomEventContent(PolicyRuleEventContent {
event_id: event_id!("$143273582443PhrSn:example.org").to_owned(), entity: "#*:example.org".into(),
sender: user_id!("@example:example.org").to_owned(), reason: "undesirable content".into(),
origin_server_ts: MilliSecondsSinceUnixEpoch(1_432_735_824_653_u64.try_into().unwrap()), recommendation: Recommendation::Ban,
room_id: room_id!("!jEsUZKDJdhlrceRyVU:example.org").to_owned(),
state_key: "rule:#*:example.org".into(),
unsigned: StateUnsigned { age: Some(int!(1234)), ..StateUnsigned::default() },
content: PolicyRuleRoomEventContent(PolicyRuleEventContent {
entity: "#*:example.org".into(),
reason: "undesirable content".into(),
recommendation: Recommendation::Ban,
}),
};
let json = json!({
"content": {
"entity": "#*:example.org",
"reason": "undesirable content",
"recommendation": "m.ban"
},
"event_id": "$143273582443PhrSn:example.org",
"origin_server_ts": 1_432_735_824_653_u64,
"room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"sender": "@example:example.org",
"state_key": "rule:#*:example.org",
"type": "m.policy.rule.room",
"unsigned": {
"age": 1234
}
}); });
assert_eq!(to_json_value(room_event).unwrap(), json); let json = json!({
"entity": "#*:example.org",
"reason": "undesirable content",
"recommendation": "m.ban"
});
assert_eq!(to_json_value(content).unwrap(), json);
} }
#[test] #[test]

View File

@ -83,35 +83,28 @@ mod tests {
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{PresenceEvent, PresenceEventContent}; use super::{PresenceEvent, PresenceEventContent};
use crate::{mxc_uri, presence::PresenceState, user_id}; use crate::{mxc_uri, presence::PresenceState};
#[test] #[test]
fn serialization() { fn serialization() {
let event = PresenceEvent { let content = PresenceEventContent {
content: PresenceEventContent { avatar_url: Some(mxc_uri!("mxc://localhost/wefuiwegh8742w").to_owned()),
avatar_url: Some(mxc_uri!("mxc://localhost/wefuiwegh8742w").to_owned()), currently_active: Some(false),
currently_active: Some(false), displayname: None,
displayname: None, last_active_ago: Some(uint!(2_478_593)),
last_active_ago: Some(uint!(2_478_593)), presence: PresenceState::Online,
presence: PresenceState::Online, status_msg: Some("Making cupcakes".into()),
status_msg: Some("Making cupcakes".into()),
},
sender: user_id!("@example:localhost").to_owned(),
}; };
let json = json!({ let json = json!({
"content": { "avatar_url": "mxc://localhost/wefuiwegh8742w",
"avatar_url": "mxc://localhost/wefuiwegh8742w", "currently_active": false,
"currently_active": false, "last_active_ago": 2_478_593,
"last_active_ago": 2_478_593, "presence": "online",
"presence": "online", "status_msg": "Making cupcakes"
"status_msg": "Making cupcakes"
},
"sender": "@example:localhost",
"type": "m.presence"
}); });
assert_eq!(to_json_value(&event).unwrap(), json); assert_eq!(to_json_value(&content).unwrap(), json);
} }
#[test] #[test]

View File

@ -39,42 +39,21 @@ impl RoomCanonicalAliasEventContent {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use js_int::uint;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::RoomCanonicalAliasEventContent; use super::RoomCanonicalAliasEventContent;
use crate::{ use crate::{events::OriginalStateEvent, room_alias_id};
event_id,
events::{EmptyStateKey, OriginalStateEvent, StateUnsigned},
room_alias_id, room_id, user_id, MilliSecondsSinceUnixEpoch,
};
#[test] #[test]
fn serialization_with_optional_fields_as_none() { fn serialization_with_optional_fields_as_none() {
let canonical_alias_event = OriginalStateEvent { let content = RoomCanonicalAliasEventContent {
content: RoomCanonicalAliasEventContent { alias: Some(room_alias_id!("#somewhere:localhost").to_owned()),
alias: Some(room_alias_id!("#somewhere:localhost").to_owned()), alt_aliases: Vec::new(),
alt_aliases: Vec::new(),
},
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!dummy:example.com").to_owned(),
sender: user_id!("@carl:example.com").to_owned(),
state_key: EmptyStateKey,
unsigned: StateUnsigned::default(),
}; };
let actual = to_json_value(&canonical_alias_event).unwrap(); let actual = to_json_value(&content).unwrap();
let expected = json!({ let expected = json!({
"content": { "alias": "#somewhere:localhost",
"alias": "#somewhere:localhost"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!dummy:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.canonical_alias"
}); });
assert_eq!(actual, expected); assert_eq!(actual, expected);

View File

@ -30,41 +30,18 @@ impl RoomNameEventContent {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use assert_matches::assert_matches; use assert_matches::assert_matches;
use js_int::{int, uint};
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::RoomNameEventContent; use super::RoomNameEventContent;
use crate::{ use crate::{events::OriginalStateEvent, serde::Raw};
event_id,
events::{EmptyStateKey, OriginalStateEvent, StateUnsigned},
room_id,
serde::Raw,
user_id, MilliSecondsSinceUnixEpoch,
};
#[test] #[test]
fn serialization_with_optional_fields_as_none() { fn serialization_with_optional_fields_as_none() {
let name_event = OriginalStateEvent { let content = RoomNameEventContent { name: Some("The room name".to_owned()) };
content: RoomNameEventContent { name: Some("The room name".to_owned()) },
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!n8f893n9:example.com").to_owned(),
sender: user_id!("@carl:example.com").to_owned(),
state_key: EmptyStateKey,
unsigned: StateUnsigned::default(),
};
let actual = to_json_value(&name_event).unwrap(); let actual = to_json_value(&content).unwrap();
let expected = json!({ let expected = json!({
"content": { "name": "The room name",
"name": "The room name"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
}); });
assert_eq!(actual, expected); assert_eq!(actual, expected);
@ -72,35 +49,11 @@ mod tests {
#[test] #[test]
fn serialization_with_all_fields() { fn serialization_with_all_fields() {
let name_event = OriginalStateEvent { let content = RoomNameEventContent { name: Some("The room name".to_owned()) };
content: RoomNameEventContent { name: Some("The room name".to_owned()) },
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!n8f893n9:example.com").to_owned(),
sender: user_id!("@carl:example.com").to_owned(),
state_key: EmptyStateKey,
unsigned: StateUnsigned {
age: Some(int!(100)),
prev_content: Some(RoomNameEventContent { name: Some("The old name".to_owned()) }),
..StateUnsigned::default()
},
};
let actual = to_json_value(&name_event).unwrap(); let actual = to_json_value(&content).unwrap();
let expected = json!({ let expected = json!({
"content": { "name": "The room name",
"name": "The room name"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name",
"unsigned": {
"age": 100,
"prev_content": { "name": "The old name" },
}
}); });
assert_eq!(actual, expected); assert_eq!(actual, expected);

View File

@ -28,10 +28,7 @@ impl RoomPinnedEventsEventContent {
#[cfg(all(test, feature = "rand"))] #[cfg(all(test, feature = "rand"))]
mod tests { mod tests {
use super::RoomPinnedEventsEventContent; use super::RoomPinnedEventsEventContent;
use crate::{ use crate::{server_name, EventId};
events::{EmptyStateKey, OriginalStateEvent, StateUnsigned},
server_name, EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId,
};
#[test] #[test]
fn serialization_deserialization() { fn serialization_deserialization() {
@ -42,28 +39,10 @@ mod tests {
content.pinned.push(EventId::new(server_name)); content.pinned.push(EventId::new(server_name));
content.pinned.push(EventId::new(server_name)); content.pinned.push(EventId::new(server_name));
let event = OriginalStateEvent { let serialized = serde_json::to_string(&content).unwrap();
content: content.clone(), let parsed_content: RoomPinnedEventsEventContent =
event_id: EventId::new(server_name), serde_json::from_str(&serialized).unwrap();
origin_server_ts: MilliSecondsSinceUnixEpoch(1_432_804_485_886_u64.try_into().unwrap()),
room_id: RoomId::new(server_name),
sender: UserId::new(server_name),
state_key: EmptyStateKey,
unsigned: StateUnsigned::default(),
};
let serialized_event = serde_json::to_string(&event).unwrap(); assert_eq!(parsed_content.pinned, content.pinned);
let parsed_event: OriginalStateEvent<RoomPinnedEventsEventContent> =
serde_json::from_str(&serialized_event).unwrap();
assert_eq!(parsed_event.event_id, event.event_id);
assert_eq!(parsed_event.room_id, event.room_id);
assert_eq!(parsed_event.sender, event.sender);
assert_eq!(parsed_event.state_key, event.state_key);
assert_eq!(parsed_event.origin_server_ts, event.origin_server_ts);
assert_eq!(parsed_event.content.pinned, event.content.pinned);
assert_eq!(parsed_event.content.pinned[0], content.pinned[0]);
assert_eq!(parsed_event.content.pinned[1], content.pinned[1]);
} }
} }

View File

@ -351,52 +351,32 @@ mod tests {
use std::collections::BTreeMap; use std::collections::BTreeMap;
use assign::assign; use assign::assign;
use js_int::{int, uint}; use js_int::int;
use maplit::btreemap; use maplit::btreemap;
use serde_json::{json, to_value as to_json_value}; use serde_json::{json, to_value as to_json_value};
use super::{default_power_level, NotificationPowerLevels, RoomPowerLevelsEventContent}; use super::{default_power_level, NotificationPowerLevels, RoomPowerLevelsEventContent};
use crate::{ use crate::user_id;
event_id,
events::{EmptyStateKey, OriginalStateEvent, StateUnsigned},
room_id, user_id, MilliSecondsSinceUnixEpoch,
};
#[test] #[test]
fn serialization_with_optional_fields_as_none() { fn serialization_with_optional_fields_as_none() {
let default = default_power_level(); let default = default_power_level();
let power_levels_event = OriginalStateEvent { let power_levels = RoomPowerLevelsEventContent {
content: RoomPowerLevelsEventContent { ban: default,
ban: default, events: BTreeMap::new(),
events: BTreeMap::new(), events_default: int!(0),
events_default: int!(0), invite: int!(0),
invite: int!(0), kick: default,
kick: default, redact: default,
redact: default, state_default: default,
state_default: default, users: BTreeMap::new(),
users: BTreeMap::new(), users_default: int!(0),
users_default: int!(0), notifications: NotificationPowerLevels::default(),
notifications: NotificationPowerLevels::default(),
},
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!n8f893n9:example.com").to_owned(),
unsigned: StateUnsigned::default(),
sender: user_id!("@carl:example.com").to_owned(),
state_key: EmptyStateKey,
}; };
let actual = to_json_value(&power_levels_event).unwrap(); let actual = to_json_value(&power_levels).unwrap();
let expected = json!({ let expected = json!({});
"content": {},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.power_levels"
});
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }
@ -404,99 +384,41 @@ mod tests {
#[test] #[test]
fn serialization_with_all_fields() { fn serialization_with_all_fields() {
let user = user_id!("@carl:example.com"); let user = user_id!("@carl:example.com");
let power_levels_event = OriginalStateEvent { let power_levels_event = RoomPowerLevelsEventContent {
content: RoomPowerLevelsEventContent { ban: int!(23),
ban: int!(23), events: btreemap! {
events: btreemap! { "m.dummy".into() => int!(23)
"m.dummy".into() => int!(23)
},
events_default: int!(23),
invite: int!(23),
kick: int!(23),
redact: int!(23),
state_default: int!(23),
users: btreemap! {
user.to_owned() => int!(23)
},
users_default: int!(23),
notifications: assign!(NotificationPowerLevels::new(), { room: int!(23) }),
}, },
event_id: event_id!("$h29iv0s8:example.com").to_owned(), events_default: int!(23),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), invite: int!(23),
room_id: room_id!("!n8f893n9:example.com").to_owned(), kick: int!(23),
unsigned: StateUnsigned { redact: int!(23),
age: Some(int!(100)), state_default: int!(23),
prev_content: Some(RoomPowerLevelsEventContent { users: btreemap! {
// Make just one field different so we at least know they're two different user.to_owned() => int!(23)
// objects.
ban: int!(42),
events: btreemap! {
"m.dummy".into() => int!(42)
},
events_default: int!(42),
invite: int!(42),
kick: int!(42),
redact: int!(42),
state_default: int!(42),
users: btreemap! {
user.to_owned() => int!(42)
},
users_default: int!(42),
notifications: assign!(NotificationPowerLevels::new(), { room: int!(42) }),
}),
..StateUnsigned::default()
}, },
sender: user.to_owned(), users_default: int!(23),
state_key: EmptyStateKey, notifications: assign!(NotificationPowerLevels::new(), { room: int!(23) }),
}; };
let actual = to_json_value(&power_levels_event).unwrap(); let actual = to_json_value(&power_levels_event).unwrap();
let expected = json!({ let expected = json!({
"content": { "ban": 23,
"ban": 23, "events": {
"events": { "m.dummy": 23
"m.dummy": 23 },
}, "events_default": 23,
"events_default": 23, "invite": 23,
"invite": 23, "kick": 23,
"kick": 23, "redact": 23,
"redact": 23, "state_default": 23,
"state_default": 23, "users": {
"users": { "@carl:example.com": 23
"@carl:example.com": 23 },
}, "users_default": 23,
"users_default": 23, "notifications": {
"notifications": { "room": 23
"room": 23
}
}, },
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.power_levels",
"unsigned": {
"age": 100,
"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
},
},
}
}); });
assert_eq!(actual, expected); assert_eq!(actual, expected);

View File

@ -17,8 +17,7 @@ use crate::{
/// A possibly-redacted redaction event. /// A possibly-redacted redaction event.
#[allow(clippy::exhaustive_enums)] #[allow(clippy::exhaustive_enums)]
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug)]
#[serde(untagged)]
pub enum RoomRedactionEvent { pub enum RoomRedactionEvent {
/// Original, unredacted form of the event. /// Original, unredacted form of the event.
Original(OriginalRoomRedactionEvent), Original(OriginalRoomRedactionEvent),
@ -29,8 +28,7 @@ pub enum RoomRedactionEvent {
/// A possibly-redacted redaction event without a `room_id`. /// A possibly-redacted redaction event without a `room_id`.
#[allow(clippy::exhaustive_enums)] #[allow(clippy::exhaustive_enums)]
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug)]
#[serde(untagged)]
pub enum SyncRoomRedactionEvent { pub enum SyncRoomRedactionEvent {
/// Original, unredacted form of the event. /// Original, unredacted form of the event.
Original(OriginalSyncRoomRedactionEvent), Original(OriginalSyncRoomRedactionEvent),

View File

@ -44,35 +44,27 @@ impl ToDeviceRoomKeyEventContent {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{room_id, user_id, EventEncryptionAlgorithm}; use crate::{room_id, EventEncryptionAlgorithm};
use serde_json::{json, to_value as to_json_value}; use serde_json::{json, to_value as to_json_value};
use super::ToDeviceRoomKeyEventContent; use super::ToDeviceRoomKeyEventContent;
use crate::events::ToDeviceEvent;
#[test] #[test]
fn serialization() { fn serialization() {
let ev = ToDeviceEvent { let content = ToDeviceRoomKeyEventContent {
content: ToDeviceRoomKeyEventContent { algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2, room_id: room_id!("!testroomid:example.org").to_owned(),
room_id: room_id!("!testroomid:example.org").to_owned(), session_id: "SessId".into(),
session_id: "SessId".into(), session_key: "SessKey".into(),
session_key: "SessKey".into(),
},
sender: user_id!("@user:example.org").to_owned(),
}; };
assert_eq!( assert_eq!(
to_json_value(ev).unwrap(), to_json_value(content).unwrap(),
json!({ json!({
"type": "m.room_key", "algorithm": "m.megolm.v1.aes-sha2",
"content": { "room_id": "!testroomid:example.org",
"algorithm": "m.megolm.v1.aes-sha2", "session_id": "SessId",
"room_id": "!testroomid:example.org", "session_key": "SessKey",
"session_id": "SessId",
"session_key": "SessKey",
},
"sender": "@user:example.org",
}) })
); );
} }

View File

@ -245,19 +245,15 @@ mod tests {
}, },
); );
content.name = Some("my_key".to_owned()); content.name = Some("my_key".to_owned());
let event = GlobalAccountDataEvent { content };
let json = json!({ let json = json!({
"type": "m.secret_storage.key.my_key_id", "name": "my_key",
"content": { "algorithm": "m.secret_storage.v1.aes-hmac-sha2",
"name": "my_key", "iv": "YWJjZGVmZ2hpamtsbW5vcA",
"algorithm": "m.secret_storage.v1.aes-hmac-sha2", "mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
"iv": "YWJjZGVmZ2hpamtsbW5vcA",
"mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
}
}); });
assert_eq!(to_json_value(&event).unwrap(), json); assert_eq!(to_json_value(&content).unwrap(), json);
} }
#[test] #[test]

View File

@ -75,7 +75,7 @@ mod tests {
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{HierarchySpaceChildEvent, SpaceChildEventContent}; use super::{HierarchySpaceChildEvent, SpaceChildEventContent};
use crate::{server_name, user_id, MilliSecondsSinceUnixEpoch}; use crate::{server_name, MilliSecondsSinceUnixEpoch};
#[test] #[test]
fn space_child_serialization() { fn space_child_serialization() {
@ -105,29 +105,18 @@ mod tests {
#[test] #[test]
fn hierarchy_space_child_serialization() { fn hierarchy_space_child_serialization() {
let event = HierarchySpaceChildEvent { let content = SpaceChildEventContent {
content: SpaceChildEventContent { via: Some(vec![server_name!("example.com").to_owned()]),
via: Some(vec![server_name!("example.com").to_owned()]), order: Some("uwu".to_owned()),
order: Some("uwu".to_owned()), suggested: None,
suggested: None,
},
sender: user_id!("@example:localhost").to_owned(),
state_key: "!child:localhost".to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1_629_413_349)),
}; };
let json = json!({ let json = json!({
"content": { "via": ["example.com"],
"via": ["example.com"], "order": "uwu",
"order": "uwu",
},
"sender": "@example:localhost",
"state_key": "!child:localhost",
"origin_server_ts": 1_629_413_349,
"type": "m.space.child",
}); });
assert_eq!(to_json_value(&event).unwrap(), json); assert_eq!(to_json_value(&content).unwrap(), json);
} }
#[test] #[test]

View File

@ -143,7 +143,7 @@ impl<C: StateEventContent> Default for StateUnsigned<C> {
} }
/// Extra information about a redacted event that is not incorporated into the event's hash. /// Extra information about a redacted event that is not incorporated into the event's hash.
#[derive(Clone, Debug, Default, Deserialize, Serialize)] #[derive(Clone, Debug, Default, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct RedactedUnsigned { pub struct RedactedUnsigned {
/// The event that redacted this event, if any. /// The event that redacted this event, if any.

View File

@ -16,11 +16,11 @@ use ruma_common::{
message::{AudioMessageEventContent, MessageType, Relation, RoomMessageEventContent}, message::{AudioMessageEventContent, MessageType, Relation, RoomMessageEventContent},
JsonWebKeyInit, MediaSource, JsonWebKeyInit, MediaSource,
}, },
AnyMessageLikeEvent, MessageLikeEvent, MessageLikeUnsigned, OriginalMessageLikeEvent, AnyMessageLikeEvent, MessageLikeEvent,
}, },
mxc_uri, room_id, mxc_uri,
serde::{Base64, CanBeEmpty}, serde::{Base64, CanBeEmpty},
user_id, MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
@ -129,70 +129,56 @@ fn encrypted_content_serialization() {
#[test] #[test]
fn event_serialization() { fn event_serialization() {
let event = OriginalMessageLikeEvent { let content = assign!(
content: assign!( AudioEventContent::with_message(
AudioEventContent::with_message( MessageContent::html(
MessageContent::html( "Upload: my_mix.mp3",
"Upload: my_mix.mp3", "Upload: <strong>my_mix.mp3</strong>",
"Upload: <strong>my_mix.mp3</strong>",
),
FileContent::plain(
mxc_uri!("mxc://notareal.hs/abcdef").to_owned(),
Some(Box::new(assign!(
FileContentInfo::new(),
{
name: Some("my_mix.mp3".to_owned()),
mimetype: Some("audio/mp3".to_owned()),
size: Some(uint!(897_774)),
}
))),
)
), ),
{ FileContent::plain(
audio: assign!( mxc_uri!("mxc://notareal.hs/abcdef").to_owned(),
AudioContent::new(), Some(Box::new(assign!(
FileContentInfo::new(),
{ {
duration: Some(Duration::from_secs(123)) name: Some("my_mix.mp3".to_owned()),
mimetype: Some("audio/mp3".to_owned()),
size: Some(uint!(897_774)),
} }
), ))),
relates_to: Some(Relation::Reply { )
in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()),
}),
}
), ),
event_id: event_id!("$event:notareal.hs").to_owned(), {
sender: user_id!("@user:notareal.hs").to_owned(), audio: assign!(
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)), AudioContent::new(),
room_id: room_id!("!roomid:notareal.hs").to_owned(), {
unsigned: MessageLikeUnsigned::default(), duration: Some(Duration::from_secs(123))
}; }
),
relates_to: Some(Relation::Reply {
in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()),
}),
}
);
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "org.matrix.msc1767.html": "Upload: <strong>my_mix.mp3</strong>",
"org.matrix.msc1767.html": "Upload: <strong>my_mix.mp3</strong>", "org.matrix.msc1767.text": "Upload: my_mix.mp3",
"org.matrix.msc1767.text": "Upload: my_mix.mp3", "m.file": {
"m.file": { "url": "mxc://notareal.hs/abcdef",
"url": "mxc://notareal.hs/abcdef", "name": "my_mix.mp3",
"name": "my_mix.mp3", "mimetype": "audio/mp3",
"mimetype": "audio/mp3", "size": 897_774,
"size": 897_774, },
}, "m.audio": {
"m.audio": { "duration": 123_000,
"duration": 123_000, },
}, "m.relates_to": {
"m.relates_to": { "m.in_reply_to": {
"m.in_reply_to": { "event_id": "$replyevent:example.com"
"event_id": "$replyevent:example.com"
}
} }
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.audio",
}) })
); );
} }

View File

@ -4,7 +4,6 @@ use assert_matches::assert_matches;
use assign::assign; use assign::assign;
use js_int::uint; use js_int::uint;
use ruma_common::{ use ruma_common::{
event_id,
events::{ events::{
call::{ call::{
answer::CallAnswerEventContent, answer::CallAnswerEventContent,
@ -17,9 +16,9 @@ use ruma_common::{
AnswerSessionDescription, CallCapabilities, OfferSessionDescription, AnswerSessionDescription, CallCapabilities, OfferSessionDescription,
SessionDescription, SessionDescriptionType, SessionDescription, SessionDescriptionType,
}, },
AnyMessageLikeEvent, MessageLikeEvent, MessageLikeUnsigned, OriginalMessageLikeEvent, AnyMessageLikeEvent, MessageLikeEvent,
}, },
room_id, user_id, MilliSecondsSinceUnixEpoch, VoipVersionId, VoipVersionId,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
@ -47,39 +46,25 @@ fn invite_content_serialization() {
#[test] #[test]
fn invite_event_serialization() { fn invite_event_serialization() {
let event = OriginalMessageLikeEvent { let content = CallInviteEventContent::version_1(
content: CallInviteEventContent::version_1( "abcdef".into(),
"abcdef".into(), "9876".into(),
"9876".into(), uint!(60000),
uint!(60000), OfferSessionDescription::new("not a real sdp".to_owned()),
OfferSessionDescription::new("not a real sdp".to_owned()), CallCapabilities::new(),
CallCapabilities::new(), );
),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "call_id": "abcdef",
"call_id": "abcdef", "party_id": "9876",
"party_id": "9876", "lifetime": 60000,
"lifetime": 60000, "version": "1",
"version": "1", "offer": {
"offer": { "type": "offer",
"type": "offer", "sdp": "not a real sdp",
"sdp": "not a real sdp",
},
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.call.invite",
}) })
); );
} }
@ -140,40 +125,26 @@ fn answer_content_serialization() {
#[test] #[test]
fn answer_event_serialization() { fn answer_event_serialization() {
let event = OriginalMessageLikeEvent { let content = CallAnswerEventContent::version_1(
content: CallAnswerEventContent::version_1( AnswerSessionDescription::new("not a real sdp".to_owned()),
AnswerSessionDescription::new("not a real sdp".to_owned()), "abcdef".into(),
"abcdef".into(), "9876".into(),
"9876".into(), assign!(CallCapabilities::new(), { dtmf: true }),
assign!(CallCapabilities::new(), { dtmf: true }), );
),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "call_id": "abcdef",
"call_id": "abcdef", "party_id": "9876",
"party_id": "9876", "version": "1",
"version": "1", "answer": {
"answer": { "type": "answer",
"type": "answer", "sdp": "not a real sdp",
"sdp": "not a real sdp", },
}, "capabilities": {
"capabilities": { "m.call.dtmf": true,
"m.call.dtmf": true,
},
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.call.answer",
}) })
); );
} }
@ -238,47 +209,33 @@ fn candidates_content_serialization() {
#[test] #[test]
fn candidates_event_serialization() { fn candidates_event_serialization() {
let event = OriginalMessageLikeEvent { let content = CallCandidatesEventContent::version_1(
content: CallCandidatesEventContent::version_1( "abcdef".into(),
"abcdef".into(), "9876".into(),
"9876".into(), vec![
vec![ Candidate::new("not a real candidate".to_owned(), "0".to_owned(), uint!(0)),
Candidate::new("not a real candidate".to_owned(), "0".to_owned(), uint!(0)), Candidate::new("another fake candidate".to_owned(), "0".to_owned(), uint!(1)),
Candidate::new("another fake candidate".to_owned(), "0".to_owned(), uint!(1)), ],
], );
),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "call_id": "abcdef",
"call_id": "abcdef", "party_id": "9876",
"party_id": "9876", "version": "1",
"version": "1", "candidates": [
"candidates": [ {
{ "candidate": "not a real candidate",
"candidate": "not a real candidate", "sdpMid": "0",
"sdpMid": "0", "sdpMLineIndex": 0,
"sdpMLineIndex": 0, },
}, {
{ "candidate": "another fake candidate",
"candidate": "another fake candidate", "sdpMid": "0",
"sdpMid": "0", "sdpMLineIndex": 1,
"sdpMLineIndex": 1, },
}, ],
],
},
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.call.candidates",
}) })
); );
} }
@ -344,33 +301,16 @@ fn hangup_content_serialization() {
#[test] #[test]
fn hangup_event_serialization() { fn hangup_event_serialization() {
let event = OriginalMessageLikeEvent { let content =
content: CallHangupEventContent::version_1( CallHangupEventContent::version_1("abcdef".into(), "9876".into(), Reason::IceFailed);
"abcdef".into(),
"9876".into(),
Reason::IceFailed,
),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "call_id": "abcdef",
"call_id": "abcdef", "party_id": "9876",
"party_id": "9876", "version": "1",
"version": "1", "reason": "ice_failed",
"reason": "ice_failed",
},
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.call.hangup",
}) })
); );
} }
@ -404,37 +344,23 @@ fn hangup_event_deserialization() {
#[test] #[test]
fn negotiate_event_serialization() { fn negotiate_event_serialization() {
let event = OriginalMessageLikeEvent { let content = CallNegotiateEventContent::new(
content: CallNegotiateEventContent::new( "abcdef".into(),
"abcdef".into(), "9876".into(),
"9876".into(), uint!(30000),
uint!(30000), SessionDescription::new(SessionDescriptionType::Offer, "not a real sdp".to_owned()),
SessionDescription::new(SessionDescriptionType::Offer, "not a real sdp".to_owned()), );
),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "call_id": "abcdef",
"call_id": "abcdef", "party_id": "9876",
"party_id": "9876", "lifetime": 30000,
"lifetime": 30000, "description": {
"description": { "type": "offer",
"type": "offer", "sdp": "not a real sdp",
"sdp": "not a real sdp",
}
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.call.negotiate",
}) })
); );
} }
@ -473,28 +399,14 @@ fn negotiate_event_deserialization() {
#[test] #[test]
fn reject_event_serialization() { fn reject_event_serialization() {
let event = OriginalMessageLikeEvent { let content = CallRejectEventContent::version_1("abcdef".into(), "9876".into());
content: CallRejectEventContent::version_1("abcdef".into(), "9876".into()),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "call_id": "abcdef",
"call_id": "abcdef", "party_id": "9876",
"party_id": "9876", "version": "1",
"version": "1",
},
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.call.reject",
}) })
); );
} }
@ -527,33 +439,16 @@ fn reject_event_deserialization() {
#[test] #[test]
fn select_answer_event_serialization() { fn select_answer_event_serialization() {
let event = OriginalMessageLikeEvent { let content =
content: CallSelectAnswerEventContent::version_1( CallSelectAnswerEventContent::version_1("abcdef".into(), "9876".into(), "6336".into());
"abcdef".into(),
"9876".into(),
"6336".into(),
),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "call_id": "abcdef",
"call_id": "abcdef", "party_id": "9876",
"party_id": "9876", "selected_party_id": "6336",
"selected_party_id": "6336", "version": "1",
"version": "1",
},
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.call.select_answer",
}) })
); );
} }

View File

@ -1,28 +1,23 @@
use assert_matches::assert_matches; use assert_matches::assert_matches;
use js_int::{int, uint}; use js_int::int;
use ruma_common::{ use ruma_common::{
event_id,
events::{MessageLikeEvent, StateEvent, SyncMessageLikeEvent, SyncStateEvent}, events::{MessageLikeEvent, StateEvent, SyncMessageLikeEvent, SyncStateEvent},
room_alias_id, room_id, room_alias_id,
serde::test::serde_json_eq, serde::test::serde_json_eq,
user_id,
}; };
use serde_json::{from_value as from_json_value, json, Value as JsonValue}; use serde_json::{from_value as from_json_value, json, Value as JsonValue};
use ruma_common::{ use ruma_common::events::{
events::{ room::{
room::{ aliases::RoomAliasesEventContent,
aliases::RoomAliasesEventContent, message::{MessageType, RoomMessageEventContent},
message::{MessageType, RoomMessageEventContent}, power_levels::RoomPowerLevelsEventContent,
power_levels::RoomPowerLevelsEventContent,
},
AnyEphemeralRoomEvent, AnyMessageLikeEvent, AnyStateEvent, AnySyncMessageLikeEvent,
AnySyncStateEvent, AnySyncTimelineEvent, AnyTimelineEvent, EphemeralRoomEventType,
GlobalAccountDataEventType, MessageLikeEventType, MessageLikeUnsigned,
OriginalMessageLikeEvent, OriginalStateEvent, OriginalSyncMessageLikeEvent,
OriginalSyncStateEvent, RoomAccountDataEventType, StateEventType, ToDeviceEventType,
}, },
MilliSecondsSinceUnixEpoch, AnyEphemeralRoomEvent, AnyMessageLikeEvent, AnyStateEvent, AnySyncMessageLikeEvent,
AnySyncStateEvent, AnySyncTimelineEvent, AnyTimelineEvent, EphemeralRoomEventType,
GlobalAccountDataEventType, MessageLikeEventType, OriginalMessageLikeEvent, OriginalStateEvent,
OriginalSyncMessageLikeEvent, OriginalSyncStateEvent, RoomAccountDataEventType, StateEventType,
ToDeviceEventType,
}; };
fn message_event() -> JsonValue { fn message_event() -> JsonValue {
@ -205,25 +200,18 @@ fn message_room_event_deserialization() {
#[test] #[test]
fn message_event_serialization() { fn message_event_serialization() {
let event = OriginalMessageLikeEvent { let content = RoomMessageEventContent::text_plain("test");
content: RoomMessageEventContent::text_plain("test"),
event_id: event_id!("$1234:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(0)),
room_id: room_id!("!roomid:example.com").to_owned(),
sender: user_id!("@test:example.com").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
#[cfg(not(feature = "unstable-msc1767"))] #[cfg(not(feature = "unstable-msc1767"))]
assert_eq!( assert_eq!(
serde_json::to_string(&event).expect("Failed to serialize message event"), serde_json::to_string(&content).expect("Failed to serialize message event content"),
r#"{"type":"m.room.message","content":{"msgtype":"m.text","body":"test"},"event_id":"$1234:example.com","sender":"@test:example.com","origin_server_ts":0,"room_id":"!roomid:example.com"}"# r#"{"msgtype":"m.text","body":"test"}"#
); );
#[cfg(feature = "unstable-msc1767")] #[cfg(feature = "unstable-msc1767")]
assert_eq!( assert_eq!(
serde_json::to_string(&event).expect("Failed to serialize message event"), serde_json::to_string(&content).expect("Failed to serialize message event content"),
r#"{"type":"m.room.message","content":{"msgtype":"m.text","body":"test","org.matrix.msc1767.text":"test"},"event_id":"$1234:example.com","sender":"@test:example.com","origin_server_ts":0,"room_id":"!roomid:example.com"}"# r#"{"msgtype":"m.text","body":"test","org.matrix.msc1767.text":"test"}"#
); );
} }

View File

@ -1,31 +1,22 @@
use assert_matches::assert_matches; use assert_matches::assert_matches;
use js_int::uint; use js_int::uint;
use maplit::btreemap; use maplit::btreemap;
use ruma_common::{ use ruma_common::{event_id, events::receipt::ReceiptType, user_id, MilliSecondsSinceUnixEpoch};
event_id, events::receipt::ReceiptType, room_id, user_id, MilliSecondsSinceUnixEpoch,
};
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use ruma_common::events::{ use ruma_common::events::{
receipt::{Receipt, ReceiptEventContent}, receipt::{Receipt, ReceiptEventContent},
typing::TypingEventContent, typing::TypingEventContent,
AnyEphemeralRoomEvent, EphemeralRoomEvent, AnyEphemeralRoomEvent,
}; };
#[test] #[test]
fn ephemeral_serialize_typing() { fn ephemeral_serialize_typing() {
let aliases_event = EphemeralRoomEvent { let content = TypingEventContent::new(vec![user_id!("@carl:example.com").to_owned()]);
content: TypingEventContent::new(vec![user_id!("@carl:example.com").to_owned()]),
room_id: room_id!("!roomid:room.com").to_owned(),
};
let actual = to_json_value(&aliases_event).unwrap(); let actual = to_json_value(&content).unwrap();
let expected = json!({ let expected = json!({
"content": { "user_ids": ["@carl:example.com"],
"user_ids": [ "@carl:example.com" ]
},
"room_id": "!roomid:room.com",
"type": "m.typing",
}); });
assert_eq!(actual, expected); assert_eq!(actual, expected);
@ -55,28 +46,21 @@ fn ephemeral_serialize_receipt() {
let event_id = event_id!("$h29iv0s8:example.com").to_owned(); let event_id = event_id!("$h29iv0s8:example.com").to_owned();
let user_id = user_id!("@carl:example.com").to_owned(); let user_id = user_id!("@carl:example.com").to_owned();
let aliases_event = EphemeralRoomEvent { let content = ReceiptEventContent(btreemap! {
content: ReceiptEventContent(btreemap! { event_id => btreemap! {
event_id => btreemap! { ReceiptType::Read => btreemap! {
ReceiptType::Read => btreemap! { user_id => Receipt::new(MilliSecondsSinceUnixEpoch(uint!(1))),
user_id => Receipt::new(MilliSecondsSinceUnixEpoch(uint!(1))),
},
}, },
}),
room_id: room_id!("!roomid:room.com").to_owned(),
};
let actual = to_json_value(&aliases_event).unwrap();
let expected = json!({
"content": {
"$h29iv0s8:example.com": {
"m.read": {
"@carl:example.com": { "ts": 1 }
}
}
}, },
"room_id": "!roomid:room.com", });
"type": "m.receipt"
let actual = to_json_value(&content).unwrap();
let expected = json!({
"$h29iv0s8:example.com": {
"m.read": {
"@carl:example.com": { "ts": 1 }
}
}
}); });
assert_eq!(actual, expected); assert_eq!(actual, expected);

View File

@ -13,11 +13,11 @@ use ruma_common::{
message::{FileMessageEventContent, MessageType, Relation, RoomMessageEventContent}, message::{FileMessageEventContent, MessageType, Relation, RoomMessageEventContent},
EncryptedFileInit, JsonWebKeyInit, MediaSource, EncryptedFileInit, JsonWebKeyInit, MediaSource,
}, },
AnyMessageLikeEvent, MessageLikeEvent, MessageLikeUnsigned, OriginalMessageLikeEvent, AnyMessageLikeEvent, MessageLikeEvent,
}, },
mxc_uri, room_id, mxc_uri,
serde::{Base64, CanBeEmpty}, serde::{Base64, CanBeEmpty},
user_id, MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
@ -91,8 +91,7 @@ fn encrypted_content_serialization() {
#[test] #[test]
fn file_event_serialization() { fn file_event_serialization() {
let event = OriginalMessageLikeEvent { let content = assign!(
content: assign!(
FileEventContent::plain_message( FileEventContent::plain_message(
MessageContent::html( MessageContent::html(
"Upload: my_file.txt", "Upload: my_file.txt",
@ -113,37 +112,24 @@ fn file_event_serialization() {
in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()), in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()),
}), }),
} }
), );
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "org.matrix.msc1767.html": "Upload: <strong>my_file.txt</strong>",
"org.matrix.msc1767.html": "Upload: <strong>my_file.txt</strong>", "org.matrix.msc1767.text": "Upload: my_file.txt",
"org.matrix.msc1767.text": "Upload: my_file.txt", "m.file": {
"m.file": { "url": "mxc://notareal.hs/abcdef",
"url": "mxc://notareal.hs/abcdef", "name": "my_file.txt",
"name": "my_file.txt", "mimetype": "text/plain",
"mimetype": "text/plain", "size": 774,
"size": 774, },
}, "m.relates_to": {
"m.relates_to": { "m.in_reply_to": {
"m.in_reply_to": { "event_id": "$replyevent:example.com"
"event_id": "$replyevent:example.com"
}
} }
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.file",
}) })
); );
} }

View File

@ -17,11 +17,11 @@ use ruma_common::{
message::{ImageMessageEventContent, MessageType, Relation, RoomMessageEventContent}, message::{ImageMessageEventContent, MessageType, Relation, RoomMessageEventContent},
JsonWebKeyInit, MediaSource, JsonWebKeyInit, MediaSource,
}, },
AnyMessageLikeEvent, MessageLikeEvent, MessageLikeUnsigned, OriginalMessageLikeEvent, AnyMessageLikeEvent, MessageLikeEvent,
}, },
mxc_uri, room_id, mxc_uri,
serde::{Base64, CanBeEmpty}, serde::{Base64, CanBeEmpty},
user_id, MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
@ -98,90 +98,76 @@ fn encrypted_content_serialization() {
#[test] #[test]
fn image_event_serialization() { fn image_event_serialization() {
let event = OriginalMessageLikeEvent { let content = assign!(
content: assign!( ImageEventContent::with_message(
ImageEventContent::with_message( MessageContent::html(
MessageContent::html( "Upload: my_house.jpg",
"Upload: my_house.jpg", "Upload: <strong>my_house.jpg</strong>",
"Upload: <strong>my_house.jpg</strong>",
),
FileContent::plain(
mxc_uri!("mxc://notareal.hs/abcdef").to_owned(),
Some(Box::new(assign!(
FileContentInfo::new(),
{
name: Some("my_house.jpg".to_owned()),
mimetype: Some("image/jpeg".to_owned()),
size: Some(uint!(897_774)),
}
))),
)
), ),
{ FileContent::plain(
image: Box::new(ImageContent::with_size(uint!(1920), uint!(1080))), mxc_uri!("mxc://notareal.hs/abcdef").to_owned(),
thumbnail: vec![ThumbnailContent::new( Some(Box::new(assign!(
ThumbnailFileContent::plain( FileContentInfo::new(),
mxc_uri!("mxc://notareal.hs/thumbnail").to_owned(), {
Some(Box::new(assign!(ThumbnailFileContentInfo::new(), { name: Some("my_house.jpg".to_owned()),
mimetype: Some("image/jpeg".to_owned()), mimetype: Some("image/jpeg".to_owned()),
size: Some(uint!(334_593)), size: Some(uint!(897_774)),
}))) }
), ))),
None )
)],
caption: Some(MessageContent::plain("This is my house")),
relates_to: Some(Relation::Reply {
in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()),
}),
}
), ),
event_id: event_id!("$event:notareal.hs").to_owned(), {
sender: user_id!("@user:notareal.hs").to_owned(), image: Box::new(ImageContent::with_size(uint!(1920), uint!(1080))),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)), thumbnail: vec![ThumbnailContent::new(
room_id: room_id!("!roomid:notareal.hs").to_owned(), ThumbnailFileContent::plain(
unsigned: MessageLikeUnsigned::default(), mxc_uri!("mxc://notareal.hs/thumbnail").to_owned(),
}; Some(Box::new(assign!(ThumbnailFileContentInfo::new(), {
mimetype: Some("image/jpeg".to_owned()),
size: Some(uint!(334_593)),
})))
),
None
)],
caption: Some(MessageContent::plain("This is my house")),
relates_to: Some(Relation::Reply {
in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()),
}),
}
);
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "org.matrix.msc1767.html": "Upload: <strong>my_house.jpg</strong>",
"org.matrix.msc1767.html": "Upload: <strong>my_house.jpg</strong>", "org.matrix.msc1767.text": "Upload: my_house.jpg",
"org.matrix.msc1767.text": "Upload: my_house.jpg", "m.file": {
"m.file": { "url": "mxc://notareal.hs/abcdef",
"url": "mxc://notareal.hs/abcdef", "name": "my_house.jpg",
"name": "my_house.jpg", "mimetype": "image/jpeg",
"size": 897_774,
},
"m.image": {
"width": 1920,
"height": 1080,
},
"m.thumbnail": [
{
"url": "mxc://notareal.hs/thumbnail",
"mimetype": "image/jpeg", "mimetype": "image/jpeg",
"size": 897_774, "size": 334_593,
}, }
"m.image": { ],
"width": 1920, "m.caption": [
"height": 1080, {
}, "body": "This is my house",
"m.thumbnail": [ "mimetype": "text/plain",
{ }
"url": "mxc://notareal.hs/thumbnail", ],
"mimetype": "image/jpeg", "m.relates_to": {
"size": 334_593, "m.in_reply_to": {
} "event_id": "$replyevent:example.com"
],
"m.caption": [
{
"body": "This is my house",
"mimetype": "text/plain",
}
],
"m.relates_to": {
"m.in_reply_to": {
"event_id": "$replyevent:example.com"
}
} }
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.image",
}) })
); );
} }

View File

@ -12,7 +12,7 @@ use ruma_common::{
room::message::{ room::message::{
LocationMessageEventContent, MessageType, Relation, RoomMessageEventContent, LocationMessageEventContent, MessageType, Relation, RoomMessageEventContent,
}, },
AnyMessageLikeEvent, MessageLikeEvent, MessageLikeUnsigned, OriginalMessageLikeEvent, AnyMessageLikeEvent, MessageLikeEvent,
}, },
room_id, room_id,
serde::CanBeEmpty, serde::CanBeEmpty,
@ -40,58 +40,44 @@ fn plain_content_serialization() {
#[test] #[test]
fn event_serialization() { fn event_serialization() {
let event = OriginalMessageLikeEvent { let content = assign!(
content: assign!( LocationEventContent::with_message(
LocationEventContent::with_message( MessageContent::html(
MessageContent::html( "Alice was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021",
"Alice was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021", "Alice was at <strong>geo:51.5008,0.1247;u=35</strong> as of <em>Sat Nov 13 18:50:58 2021</em>",
"Alice was at <strong>geo:51.5008,0.1247;u=35</strong> as of <em>Sat Nov 13 18:50:58 2021</em>",
),
assign!(
LocationContent::new("geo:51.5008,0.1247;u=35".to_owned()),
{
description: Some("Alice's whereabouts".into()),
zoom_level: Some(ZoomLevel::new(4).unwrap())
}
)
), ),
{ assign!(
ts: Some(MilliSecondsSinceUnixEpoch(uint!(1_636_829_458))), LocationContent::new("geo:51.5008,0.1247;u=35".to_owned()),
relates_to: Some(Relation::Reply { {
in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()), description: Some("Alice's whereabouts".into()),
}), zoom_level: Some(ZoomLevel::new(4).unwrap())
} }
)
), ),
event_id: event_id!("$event:notareal.hs").to_owned(), {
sender: user_id!("@user:notareal.hs").to_owned(), ts: Some(MilliSecondsSinceUnixEpoch(uint!(1_636_829_458))),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)), relates_to: Some(Relation::Reply {
room_id: room_id!("!roomid:notareal.hs").to_owned(), in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()),
unsigned: MessageLikeUnsigned::default(), }),
}; }
);
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "org.matrix.msc1767.html": "Alice was at <strong>geo:51.5008,0.1247;u=35</strong> as of <em>Sat Nov 13 18:50:58 2021</em>",
"org.matrix.msc1767.html": "Alice was at <strong>geo:51.5008,0.1247;u=35</strong> as of <em>Sat Nov 13 18:50:58 2021</em>", "org.matrix.msc1767.text": "Alice was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021",
"org.matrix.msc1767.text": "Alice was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021", "m.location": {
"m.location": { "uri": "geo:51.5008,0.1247;u=35",
"uri": "geo:51.5008,0.1247;u=35", "description": "Alice's whereabouts",
"description": "Alice's whereabouts", "zoom_level": 4,
"zoom_level": 4, },
}, "m.ts": 1_636_829_458,
"m.ts": 1_636_829_458, "m.relates_to": {
"m.relates_to": { "m.in_reply_to": {
"m.in_reply_to": { "event_id": "$replyevent:example.com",
"event_id": "$replyevent:example.com",
},
}, },
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.location",
}) })
); );
} }

View File

@ -11,11 +11,10 @@ use ruma_common::{
notice::NoticeEventContent, notice::NoticeEventContent,
relation::InReplyTo, relation::InReplyTo,
room::message::{EmoteMessageEventContent, MessageType, Relation, RoomMessageEventContent}, room::message::{EmoteMessageEventContent, MessageType, Relation, RoomMessageEventContent},
AnyMessageLikeEvent, MessageLikeEvent, MessageLikeUnsigned, OriginalMessageLikeEvent, AnyMessageLikeEvent, MessageLikeEvent,
}, },
room_id,
serde::CanBeEmpty, serde::CanBeEmpty,
user_id, MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
@ -146,27 +145,10 @@ fn relates_to_content_serialization() {
#[test] #[test]
fn message_event_serialization() { fn message_event_serialization() {
let event = OriginalMessageLikeEvent { let content = MessageEventContent::plain("Hello, World!");
content: MessageEventContent::plain("Hello, World!"),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({ "org.matrix.msc1767.text": "Hello, World!" })
"content": {
"org.matrix.msc1767.text": "Hello, World!",
},
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.message",
})
); );
} }
@ -469,27 +451,10 @@ fn room_message_message_unstable_deserialization() {
#[test] #[test]
fn notice_event_serialization() { fn notice_event_serialization() {
let event = OriginalMessageLikeEvent { let content = NoticeEventContent::plain("Hello, I'm a robot!");
content: NoticeEventContent::plain("Hello, I'm a robot!"),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({ "org.matrix.msc1767.text": "Hello, I'm a robot!" })
"content": {
"org.matrix.msc1767.text": "Hello, I'm a robot!",
},
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.notice",
})
); );
} }
@ -616,30 +581,14 @@ fn room_message_notice_unstable_deserialization() {
#[test] #[test]
fn emote_event_serialization() { fn emote_event_serialization() {
let event = OriginalMessageLikeEvent { let content =
content: EmoteEventContent::html( EmoteEventContent::html("is testing some code…", "is testing some <code>code</code>…");
"is testing some code…",
"is testing some <code>code</code>…",
),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "org.matrix.msc1767.html": "is testing some <code>code</code>…",
"org.matrix.msc1767.html": "is testing some <code>code</code>…", "org.matrix.msc1767.text": "is testing some code…",
"org.matrix.msc1767.text": "is testing some code…",
},
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.emote",
}) })
); );
} }

View File

@ -2,117 +2,95 @@ use assert_matches::assert_matches;
use assign::assign; use assign::assign;
use js_int::{uint, UInt}; use js_int::{uint, UInt};
use ruma_common::{ use ruma_common::{
event_id,
events::{ events::{
room::{ImageInfo, MediaSource, ThumbnailInfo}, room::{ImageInfo, MediaSource, ThumbnailInfo},
sticker::StickerEventContent, sticker::StickerEventContent,
AnyMessageLikeEvent, AnyMessageLikeEventContent, AnySyncMessageLikeEvent, MessageLikeEvent, AnyMessageLikeEvent, AnyMessageLikeEventContent, AnySyncMessageLikeEvent, MessageLikeEvent,
MessageLikeEventType, MessageLikeUnsigned, OriginalMessageLikeEvent, MessageLikeEventType,
}, },
mxc_uri, room_id, mxc_uri, room_id,
serde::{CanBeEmpty, Raw}, serde::{CanBeEmpty, Raw},
user_id, MilliSecondsSinceUnixEpoch, VoipVersionId, MilliSecondsSinceUnixEpoch, VoipVersionId,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
#[test] #[test]
fn message_serialize_sticker() { fn message_serialize_sticker() {
let aliases_event = OriginalMessageLikeEvent { let content = StickerEventContent::new(
content: StickerEventContent::new( "Hello".into(),
"Hello".into(), assign!(ImageInfo::new(), {
assign!(ImageInfo::new(), { height: UInt::new(423),
height: UInt::new(423), width: UInt::new(1011),
width: UInt::new(1011), mimetype: Some("image/png".into()),
size: UInt::new(84242),
thumbnail_info: Some(Box::new(assign!(ThumbnailInfo::new(), {
width: UInt::new(800),
height: UInt::new(334),
mimetype: Some("image/png".into()), mimetype: Some("image/png".into()),
size: UInt::new(84242), size: UInt::new(82595),
thumbnail_info: Some(Box::new(assign!(ThumbnailInfo::new(), { }))),
width: UInt::new(800), thumbnail_source: Some(MediaSource::Plain(mxc_uri!("mxc://matrix.org/irsns989Rrsn").to_owned())),
height: UInt::new(334), }),
mimetype: Some("image/png".into()), mxc_uri!("mxc://matrix.org/rnsldl8srs98IRrs").to_owned(),
size: UInt::new(82595), );
}))),
thumbnail_source: Some(MediaSource::Plain(mxc_uri!("mxc://matrix.org/irsns989Rrsn").to_owned())),
}),
mxc_uri!("mxc://matrix.org/rnsldl8srs98IRrs").to_owned(),
),
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!roomid:room.com").to_owned(),
sender: user_id!("@carl:example.com").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
let actual = to_json_value(&aliases_event).unwrap(); let actual = to_json_value(&content).unwrap();
#[cfg(not(feature = "unstable-msc3552"))] #[cfg(not(feature = "unstable-msc3552"))]
let expected = json!({ let expected = json!({
"content": { "body": "Hello",
"body": "Hello", "info": {
"info": { "h": 423,
"h": 423, "mimetype": "image/png",
"size": 84242,
"thumbnail_info": {
"h": 334,
"mimetype": "image/png", "mimetype": "image/png",
"size": 84242, "size": 82595,
"thumbnail_info": { "w": 800
"h": 334, },
"mimetype": "image/png", "thumbnail_url": "mxc://matrix.org/irsns989Rrsn",
"size": 82595, "w": 1011
"w": 800 },
}, "url": "mxc://matrix.org/rnsldl8srs98IRrs",
"thumbnail_url": "mxc://matrix.org/irsns989Rrsn",
"w": 1011
},
"url": "mxc://matrix.org/rnsldl8srs98IRrs"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!roomid:room.com",
"sender": "@carl:example.com",
"type": "m.sticker",
}); });
#[cfg(feature = "unstable-msc3552")] #[cfg(feature = "unstable-msc3552")]
let expected = json!({ let expected = json!({
"content": { "body": "Hello",
"body": "Hello", "info": {
"info": { "h": 423,
"h": 423, "mimetype": "image/png",
"size": 84242,
"thumbnail_info": {
"h": 334,
"mimetype": "image/png", "mimetype": "image/png",
"size": 84242, "size": 82595,
"thumbnail_info": { "w": 800
"h": 334, },
"mimetype": "image/png", "thumbnail_url": "mxc://matrix.org/irsns989Rrsn",
"size": 82595, "w": 1011
"w": 800 },
}, "url": "mxc://matrix.org/rnsldl8srs98IRrs",
"thumbnail_url": "mxc://matrix.org/irsns989Rrsn", "org.matrix.msc1767.text": "Hello",
"w": 1011 "org.matrix.msc1767.file": {
},
"url": "mxc://matrix.org/rnsldl8srs98IRrs", "url": "mxc://matrix.org/rnsldl8srs98IRrs",
"org.matrix.msc1767.text": "Hello", "mimetype": "image/png",
"org.matrix.msc1767.file": { "size": 84242,
"url": "mxc://matrix.org/rnsldl8srs98IRrs",
"mimetype": "image/png",
"size": 84242,
},
"org.matrix.msc1767.image": {
"height": 423,
"width": 1011,
},
"org.matrix.msc1767.thumbnail": [
{
"url": "mxc://matrix.org/irsns989Rrsn",
"mimetype": "image/png",
"size": 82595,
"height": 334,
"width": 800,
}
],
}, },
"event_id": "$h29iv0s8:example.com", "org.matrix.msc1767.image": {
"origin_server_ts": 1, "height": 423,
"room_id": "!roomid:room.com", "width": 1011,
"sender": "@carl:example.com", },
"type": "m.sticker", "org.matrix.msc1767.thumbnail": [
{
"url": "mxc://matrix.org/irsns989Rrsn",
"mimetype": "image/png",
"size": 82595,
"height": 334,
"width": 800,
}
],
}); });
assert_eq!(actual, expected); assert_eq!(actual, expected);

View File

@ -16,9 +16,8 @@ use ruma_common::{
}, },
}, },
relation::Reference, relation::Reference,
AnyMessageLikeEvent, MessageLikeEvent, MessageLikeUnsigned, OriginalMessageLikeEvent, AnyMessageLikeEvent, MessageLikeEvent,
}, },
room_id, user_id, MilliSecondsSinceUnixEpoch,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
@ -105,48 +104,34 @@ fn start_content_serialization() {
#[test] #[test]
fn start_event_serialization() { fn start_event_serialization() {
let event = OriginalMessageLikeEvent { let content = PollStartEventContent::new(assign!(
content: PollStartEventContent::new(assign!( PollStartContent::new(
PollStartContent::new( MessageContent::plain("How's the weather?"),
MessageContent::plain("How's the weather?"), PollKind::Disclosed,
PollKind::Disclosed, vec![
vec![ PollAnswer::new("not-bad".to_owned(), MessageContent::plain("Not bad…")),
PollAnswer::new("not-bad".to_owned(), MessageContent::plain("Not bad…")), PollAnswer::new("fine".to_owned(), MessageContent::plain("Fine.")),
PollAnswer::new("fine".to_owned(), MessageContent::plain("Fine.")), PollAnswer::new("amazing".to_owned(), MessageContent::plain("Amazing!")),
PollAnswer::new("amazing".to_owned(), MessageContent::plain("Amazing!")), ]
] .try_into()
.try_into() .unwrap(),
.unwrap(), ),
), { max_selections: uint!(2) }
{ max_selections: uint!(2) } ));
)),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "org.matrix.msc3381.poll.start": {
"org.matrix.msc3381.poll.start": { "question": { "org.matrix.msc1767.text": "How's the weather?" },
"question": { "org.matrix.msc1767.text": "How's the weather?" }, "kind": "org.matrix.msc3381.poll.disclosed",
"kind": "org.matrix.msc3381.poll.disclosed", "max_selections": 2,
"max_selections": 2, "answers": [
"answers": [ { "id": "not-bad", "org.matrix.msc1767.text": "Not bad…"},
{ "id": "not-bad", "org.matrix.msc1767.text": "Not bad…"}, { "id": "fine", "org.matrix.msc1767.text": "Fine."},
{ "id": "fine", "org.matrix.msc1767.text": "Fine."}, { "id": "amazing", "org.matrix.msc1767.text": "Amazing!"},
{ "id": "amazing", "org.matrix.msc1767.text": "Amazing!"}, ]
]
},
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "org.matrix.msc3381.poll.start",
}) })
); );
} }
@ -255,35 +240,21 @@ fn response_content_serialization() {
#[test] #[test]
fn response_event_serialization() { fn response_event_serialization() {
let event = OriginalMessageLikeEvent { let content = PollResponseEventContent::new(
content: PollResponseEventContent::new( PollResponseContent::new(vec!["first-answer".to_owned(), "second-answer".to_owned()]),
PollResponseContent::new(vec!["first-answer".to_owned(), "second-answer".to_owned()]), event_id!("$related_event:notareal.hs").to_owned(),
event_id!("$related_event:notareal.hs").to_owned(), );
),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "org.matrix.msc3381.poll.response": {
"org.matrix.msc3381.poll.response": { "answers": ["first-answer", "second-answer"],
"answers": ["first-answer", "second-answer"], },
}, "m.relates_to": {
"m.relates_to": { "rel_type": "m.reference",
"rel_type": "m.reference", "event_id": "$related_event:notareal.hs",
"event_id": "$related_event:notareal.hs",
}
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "org.matrix.msc3381.poll.response",
}) })
); );
} }
@ -380,33 +351,19 @@ fn end_content_serialization() {
#[test] #[test]
fn end_event_serialization() { fn end_event_serialization() {
let event = OriginalMessageLikeEvent { let content = PollEndEventContent::new(
content: PollEndEventContent::new( PollEndContent::new(),
PollEndContent::new(), event_id!("$related_event:notareal.hs").to_owned(),
event_id!("$related_event:notareal.hs").to_owned(), );
),
event_id: event_id!("$event:notareal.hs").to_owned(),
sender: user_id!("@user:notareal.hs").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)),
room_id: room_id!("!roomid:notareal.hs").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "org.matrix.msc3381.poll.end": {},
"org.matrix.msc3381.poll.end": {}, "m.relates_to": {
"m.relates_to": { "rel_type": "m.reference",
"rel_type": "m.reference", "event_id": "$related_event:notareal.hs",
"event_id": "$related_event:notareal.hs",
}
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "org.matrix.msc3381.poll.end",
}) })
); );
} }

View File

@ -1,117 +1,55 @@
use assert_matches::assert_matches; use assert_matches::assert_matches;
use js_int::uint;
use ruma_common::{ use ruma_common::{
event_id,
events::{ events::{
room::{ room::{
aliases::RedactedRoomAliasesEventContent, aliases::RedactedRoomAliasesEventContent,
create::{RedactedRoomCreateEventContent, RoomCreateEventContent}, create::{RedactedRoomCreateEventContent, RoomCreateEventContent},
message::{RedactedRoomMessageEventContent, RoomMessageEventContent}, message::{RedactedRoomMessageEventContent, RoomMessageEventContent},
redaction::{ redaction::RoomRedactionEventContent,
OriginalSyncRoomRedactionEvent, RoomRedactionEventContent, SyncRoomRedactionEvent,
},
}, },
AnyMessageLikeEvent, AnySyncMessageLikeEvent, AnySyncStateEvent, AnySyncTimelineEvent, AnyMessageLikeEvent, AnySyncMessageLikeEvent, AnySyncStateEvent, AnySyncTimelineEvent,
AnyTimelineEvent, EventContent, MessageLikeEvent, MessageLikeUnsigned, RedactContent, AnyTimelineEvent, EventContent, MessageLikeEvent, RedactContent, SyncMessageLikeEvent,
RedactedSyncMessageLikeEvent, RedactedSyncStateEvent, RedactedUnsigned, SyncStateEvent,
SyncMessageLikeEvent, SyncStateEvent,
}, },
server_name, user_id, MilliSecondsSinceUnixEpoch, RoomVersionId, RoomVersionId,
}; };
use serde_json::{ use serde_json::{
from_value as from_json_value, json, to_value as to_json_value, from_value as from_json_value, json, to_value as to_json_value,
value::to_raw_value as to_raw_json_value, value::to_raw_value as to_raw_json_value, Value as JsonValue,
}; };
fn unsigned() -> RedactedUnsigned { fn unsigned() -> JsonValue {
let mut unsigned = RedactedUnsigned::default(); json!({
unsigned.redacted_because = "redacted_because": {
Some(Box::new(SyncRoomRedactionEvent::Original(OriginalSyncRoomRedactionEvent { "type": "m.room.redaction",
content: RoomRedactionEventContent::with_reason("redacted because".into()), "content": RoomRedactionEventContent::with_reason("redacted because".into()),
redacts: event_id!("$h29iv0s8:example.com").to_owned(), "redacts": "$h29iv0s8:example.com",
event_id: event_id!("$h29iv0s8:example.com").to_owned(), "event_id": "$h29iv0s8:example.com",
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), "origin_server_ts": 1,
sender: user_id!("@carl:example.com").to_owned(), "sender": "@carl:example.com",
unsigned: MessageLikeUnsigned::default(), }
}))); })
unsigned
} }
#[test] #[test]
fn redacted_message_event_serialize() { fn serialize_redacted_message_event_content() {
let redacted = RedactedSyncMessageLikeEvent { assert_eq!(to_json_value(RedactedRoomMessageEventContent::new()).unwrap(), json!({}));
content: RedactedRoomMessageEventContent::new(),
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
sender: user_id!("@carl:example.com").to_owned(),
unsigned: RedactedUnsigned::default(),
};
let expected = json!({
"content": {},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"type": "m.room.message",
});
let actual = to_json_value(&redacted).unwrap();
assert_eq!(actual, expected);
} }
#[test] #[test]
fn redacted_aliases_event_serialize_empty_content() { fn serialize_empty_redacted_aliases_event_content() {
let redacted = RedactedSyncStateEvent { assert_eq!(to_json_value(&RedactedRoomAliasesEventContent::default()).unwrap(), json!({}));
content: RedactedRoomAliasesEventContent::default(),
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
state_key: server_name!("example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
sender: user_id!("@carl:example.com").to_owned(),
unsigned: RedactedUnsigned::default(),
};
let expected = json!({
"content": {},
"event_id": "$h29iv0s8:example.com",
"state_key": "example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"type": "m.room.aliases",
});
let actual = to_json_value(&redacted).unwrap();
assert_eq!(actual, expected);
} }
#[test] #[test]
fn redacted_aliases_event_serialize_with_content() { fn redacted_aliases_event_serialize_with_content() {
let redacted = RedactedSyncStateEvent { let expected = json!({ "aliases": [] });
content: RedactedRoomAliasesEventContent::new_v1(vec![]), let actual = to_json_value(&RedactedRoomAliasesEventContent::new_v1(vec![])).unwrap();
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
state_key: server_name!("example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
sender: user_id!("@carl:example.com").to_owned(),
unsigned: RedactedUnsigned::default(),
};
let expected = json!({
"content": {
"aliases": []
},
"event_id": "$h29iv0s8:example.com",
"state_key": "example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"type": "m.room.aliases",
});
let actual = to_json_value(&redacted).unwrap();
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }
#[test] #[test]
fn redacted_aliases_deserialize() { fn deserialize_redacted_aliases() {
let redacted = json!({ let redacted = json!({
"content": {}, "content": {},
"event_id": "$h29iv0s8:example.com", "event_id": "$h29iv0s8:example.com",
@ -135,7 +73,7 @@ fn redacted_aliases_deserialize() {
} }
#[test] #[test]
fn redacted_deserialize_any_room() { fn deserialize_redacted_any_room() {
let redacted = json!({ let redacted = json!({
"content": {}, "content": {},
"event_id": "$h29iv0s8:example.com", "event_id": "$h29iv0s8:example.com",
@ -159,27 +97,13 @@ fn redacted_deserialize_any_room() {
} }
#[test] #[test]
fn redacted_deserialize_any_room_sync() { fn deserialize_redacted_any_room_sync() {
let mut unsigned = RedactedUnsigned::default();
// The presence of `redacted_because` triggers the event enum (AnySyncTimelineEvent in this
// case) to return early with `RedactedContent` instead of failing to deserialize according
// to the event type string.
unsigned.redacted_because =
Some(Box::new(SyncRoomRedactionEvent::Original(OriginalSyncRoomRedactionEvent {
content: RoomRedactionEventContent::with_reason("redacted because".into()),
redacts: event_id!("$h29iv0s8:example.com").to_owned(),
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
sender: user_id!("@carl:example.com").to_owned(),
unsigned: MessageLikeUnsigned::default(),
})));
let redacted = json!({ let redacted = json!({
"content": {}, "content": {},
"event_id": "$h29iv0s8:example.com", "event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1, "origin_server_ts": 1,
"sender": "@carl:example.com", "sender": "@carl:example.com",
"unsigned": unsigned, "unsigned": unsigned(),
"type": "m.room.message", "type": "m.room.message",
}); });
@ -195,7 +119,7 @@ fn redacted_deserialize_any_room_sync() {
} }
#[test] #[test]
fn redacted_state_event_deserialize() { fn deserialize_redacted_state_event() {
let redacted = json!({ let redacted = json!({
"content": { "content": {
"creator": "@carl:example.com", "creator": "@carl:example.com",
@ -220,7 +144,7 @@ fn redacted_state_event_deserialize() {
} }
#[test] #[test]
fn redacted_custom_event_deserialize() { fn deserialize_redacted_custom_event() {
let redacted = json!({ let redacted = json!({
"content": {}, "content": {},
"event_id": "$h29iv0s8:example.com", "event_id": "$h29iv0s8:example.com",

View File

@ -1,25 +1,32 @@
use assert_matches::assert_matches; use assert_matches::assert_matches;
use js_int::uint; use js_int::uint;
use ruma_common::{ use ruma_common::{
event_id,
events::{ events::{
room::redaction::{ room::redaction::{RoomRedactionEvent, RoomRedactionEventContent},
OriginalRoomRedactionEvent, RoomRedactionEvent, RoomRedactionEventContent, AnyMessageLikeEvent,
},
AnyMessageLikeEvent, MessageLikeUnsigned,
}, },
room_id,
serde::CanBeEmpty, serde::CanBeEmpty,
user_id, MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch,
};
use serde_json::{
from_value as from_json_value, json, to_value as to_json_value, Value as JsonValue,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
fn redaction() -> JsonValue { #[test]
json!({ fn serialize_redaction_content() {
let content = RoomRedactionEventContent::with_reason("being very unfriendly".into());
let actual = to_json_value(content).unwrap();
let expected = json!({
"reason": "being very unfriendly"
});
assert_eq!(actual, expected);
}
#[test]
fn deserialize_redaction() {
let json_data = json!({
"content": { "content": {
"reason": "being a turd" "reason": "being very unfriendly"
}, },
"redacts": "$nomore:example.com", "redacts": "$nomore:example.com",
"event_id": "$h29iv0s8:example.com", "event_id": "$h29iv0s8:example.com",
@ -27,36 +34,13 @@ fn redaction() -> JsonValue {
"origin_server_ts": 1, "origin_server_ts": 1,
"room_id": "!roomid:room.com", "room_id": "!roomid:room.com",
"type": "m.room.redaction" "type": "m.room.redaction"
}) });
}
#[test]
fn serialize_redaction() {
let aliases_event = OriginalRoomRedactionEvent {
content: RoomRedactionEventContent::with_reason("being a turd".into()),
redacts: event_id!("$nomore:example.com").to_owned(),
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!roomid:room.com").to_owned(),
sender: user_id!("@carl:example.com").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
let actual = to_json_value(&aliases_event).unwrap();
let expected = redaction();
assert_eq!(actual, expected);
}
#[test]
fn deserialize_redaction() {
let json_data = redaction();
let ev = assert_matches!( let ev = assert_matches!(
from_json_value::<AnyMessageLikeEvent>(json_data), from_json_value::<AnyMessageLikeEvent>(json_data),
Ok(AnyMessageLikeEvent::RoomRedaction(RoomRedactionEvent::Original(ev))) => ev Ok(AnyMessageLikeEvent::RoomRedaction(RoomRedactionEvent::Original(ev))) => ev
); );
assert_eq!(ev.content.reason.as_deref(), Some("being a turd")); assert_eq!(ev.content.reason.as_deref(), Some("being very unfriendly"));
assert_eq!(ev.event_id, "$h29iv0s8:example.com"); assert_eq!(ev.event_id, "$h29iv0s8:example.com");
assert_eq!(ev.redacts, "$nomore:example.com"); assert_eq!(ev.redacts, "$nomore:example.com");
assert_eq!(ev.origin_server_ts, MilliSecondsSinceUnixEpoch(uint!(1))); assert_eq!(ev.origin_server_ts, MilliSecondsSinceUnixEpoch(uint!(1)));

View File

@ -34,55 +34,35 @@ macro_rules! json_object {
#[test] #[test]
fn serialization() { fn serialization() {
let ev = OriginalRoomMessageEvent { let content =
content: RoomMessageEventContent::new(MessageType::Audio(AudioMessageEventContent::plain( RoomMessageEventContent::new(MessageType::Audio(AudioMessageEventContent::plain(
"test".into(), "test".into(),
mxc_uri!("mxc://example.org/ffed755USFFxlgbQYZGtryd").to_owned(), mxc_uri!("mxc://example.org/ffed755USFFxlgbQYZGtryd").to_owned(),
None, None,
))), )));
event_id: event_id!("$143273582443PhrSn:example.org").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(10_000)),
room_id: room_id!("!testroomid:example.org").to_owned(),
sender: user_id!("@user:example.org").to_owned(),
unsigned: MessageLikeUnsigned::default(),
};
#[cfg(not(feature = "unstable-msc3246"))] #[cfg(not(feature = "unstable-msc3246"))]
assert_eq!( assert_eq!(
to_json_value(ev).unwrap(), to_json_value(content).unwrap(),
json!({ json!({
"type": "m.room.message", "body": "test",
"event_id": "$143273582443PhrSn:example.org", "msgtype": "m.audio",
"origin_server_ts": 10_000, "url": "mxc://example.org/ffed755USFFxlgbQYZGtryd",
"room_id": "!testroomid:example.org",
"sender": "@user:example.org",
"content": {
"body": "test",
"msgtype": "m.audio",
"url": "mxc://example.org/ffed755USFFxlgbQYZGtryd",
}
}) })
); );
#[cfg(feature = "unstable-msc3246")] #[cfg(feature = "unstable-msc3246")]
assert_eq!( assert_eq!(
to_json_value(ev).unwrap(), to_json_value(content).unwrap(),
json!({ json!({
"type": "m.room.message", "body": "test",
"event_id": "$143273582443PhrSn:example.org", "msgtype": "m.audio",
"origin_server_ts": 10_000, "url": "mxc://example.org/ffed755USFFxlgbQYZGtryd",
"room_id": "!testroomid:example.org", "org.matrix.msc1767.text": "test",
"sender": "@user:example.org", "org.matrix.msc1767.file": {
"content": {
"body": "test",
"msgtype": "m.audio",
"url": "mxc://example.org/ffed755USFFxlgbQYZGtryd", "url": "mxc://example.org/ffed755USFFxlgbQYZGtryd",
"org.matrix.msc1767.text": "test", },
"org.matrix.msc1767.file": { "org.matrix.msc1767.audio": {},
"url": "mxc://example.org/ffed755USFFxlgbQYZGtryd",
},
"org.matrix.msc1767.audio": {},
}
}) })
); );
} }

View File

@ -1,20 +1,15 @@
use assert_matches::assert_matches; use assert_matches::assert_matches;
use assign::assign;
use js_int::uint; use js_int::uint;
use ruma_common::{ use ruma_common::{
event_id,
events::{ events::{
room::aliases::RoomAliasesEventContent, AnyStateEvent, AnyStateEventContent, AnyStateEvent, AnyStateEventContent, AnySyncStateEvent, AnyTimelineEvent, StateEvent,
AnySyncStateEvent, AnyTimelineEvent, OriginalStateEvent, StateEvent, StateEventType, StateEventType, SyncStateEvent,
StateUnsigned, SyncStateEvent,
}, },
mxc_uri, room_alias_id, room_id, mxc_uri, room_alias_id,
serde::{CanBeEmpty, Raw}, serde::{CanBeEmpty, Raw},
server_name, user_id, MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch,
};
use serde_json::{
from_value as from_json_value, json, to_value as to_json_value, Value as JsonValue,
}; };
use serde_json::{from_value as from_json_value, json, Value as JsonValue};
fn aliases_event_with_prev_content() -> JsonValue { fn aliases_event_with_prev_content() -> JsonValue {
json!({ json!({
@ -35,65 +30,10 @@ fn aliases_event_with_prev_content() -> JsonValue {
}) })
} }
#[test]
fn serialize_aliases_with_prev_content() {
let aliases_event = OriginalStateEvent {
content: RoomAliasesEventContent::new(vec![
room_alias_id!("#somewhere:localhost").to_owned()
]),
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!roomid:room.com").to_owned(),
sender: user_id!("@carl:example.com").to_owned(),
state_key: server_name!("room.com").to_owned(),
unsigned: assign!(StateUnsigned::default(), {
prev_content: Some(RoomAliasesEventContent::new(vec![room_alias_id!(
"#inner:localhost"
)
.to_owned()])),
}),
};
let actual = to_json_value(&aliases_event).unwrap();
let expected = aliases_event_with_prev_content();
assert_eq!(actual, expected);
}
#[test]
fn serialize_aliases_without_prev_content() {
let aliases_event = OriginalStateEvent {
content: RoomAliasesEventContent::new(vec![
room_alias_id!("#somewhere:localhost").to_owned()
]),
event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!roomid:room.com").to_owned(),
sender: user_id!("@carl:example.com").to_owned(),
state_key: server_name!("example.com").to_owned(),
unsigned: StateUnsigned::default(),
};
let actual = to_json_value(&aliases_event).unwrap();
let expected = json!({
"content": {
"aliases": [ "#somewhere:localhost" ]
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!roomid:room.com",
"sender": "@carl:example.com",
"state_key": "example.com",
"type": "m.room.aliases",
});
assert_eq!(actual, expected);
}
#[test] #[test]
fn deserialize_aliases_content() { fn deserialize_aliases_content() {
let json_data = json!({ let json_data = json!({
"aliases": [ "#somewhere:localhost" ] "aliases": ["#somewhere:localhost"],
}); });
let content = assert_matches!( let content = assert_matches!(

View File

@ -3,30 +3,18 @@ use js_int::uint;
use ruma_common::{ use ruma_common::{
events::{ events::{
room::{join_rules::JoinRule, topic::RoomTopicEventContent}, room::{join_rules::JoinRule, topic::RoomTopicEventContent},
AnyStrippedStateEvent, EmptyStateKey, StrippedStateEvent, AnyStrippedStateEvent,
}, },
mxc_uri, user_id, mxc_uri,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
#[test] #[test]
fn serialize_stripped_state_event_any_content() { fn serialize_stripped_state_event_any_content() {
let event = StrippedStateEvent { assert_eq!(
content: RoomTopicEventContent::new("Testing room".into()), to_json_value(RoomTopicEventContent::new("Testing room".into())).unwrap(),
state_key: EmptyStateKey, json!({ "topic": "Testing room" })
sender: user_id!("@example:localhost").to_owned(), );
};
let json_data = json!({
"content": {
"topic": "Testing room"
},
"type": "m.room.topic",
"state_key": "",
"sender": "@example:localhost"
});
assert_eq!(to_json_value(&event).unwrap(), json_data);
} }
#[test] #[test]

View File

@ -1,32 +1,24 @@
use ruma_common::{ use ruma_common::{
events::{room_key::ToDeviceRoomKeyEventContent, ToDeviceEvent}, events::room_key::ToDeviceRoomKeyEventContent, room_id, EventEncryptionAlgorithm,
room_id, user_id, EventEncryptionAlgorithm,
}; };
use serde_json::{json, to_value as to_json_value}; use serde_json::{json, to_value as to_json_value};
#[test] #[test]
fn serialization() { fn serialization() {
let ev = ToDeviceEvent { let content = ToDeviceRoomKeyEventContent::new(
sender: user_id!("@example:example.org").to_owned(), EventEncryptionAlgorithm::MegolmV1AesSha2,
content: ToDeviceRoomKeyEventContent::new( room_id!("!testroomid:example.org").to_owned(),
EventEncryptionAlgorithm::MegolmV1AesSha2, "SessId".into(),
room_id!("!testroomid:example.org").to_owned(), "SessKey".into(),
"SessId".into(), );
"SessKey".into(),
),
};
assert_eq!( assert_eq!(
to_json_value(&ev).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"type": "m.room_key", "algorithm": "m.megolm.v1.aes-sha2",
"sender": "@example:example.org", "room_id": "!testroomid:example.org",
"content": { "session_id": "SessId",
"algorithm": "m.megolm.v1.aes-sha2", "session_key": "SessKey",
"room_id": "!testroomid:example.org",
"session_id": "SessId",
"session_key": "SessKey",
},
}) })
); );
} }

View File

@ -17,11 +17,11 @@ use ruma_common::{
JsonWebKeyInit, MediaSource, JsonWebKeyInit, MediaSource,
}, },
video::{VideoContent, VideoEventContent}, video::{VideoContent, VideoEventContent},
AnyMessageLikeEvent, MessageLikeEvent, MessageLikeUnsigned, OriginalMessageLikeEvent, AnyMessageLikeEvent, MessageLikeEvent,
}, },
mxc_uri, room_id, mxc_uri,
serde::{Base64, CanBeEmpty}, serde::{Base64, CanBeEmpty},
user_id, MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
@ -98,98 +98,84 @@ fn encrypted_content_serialization() {
#[test] #[test]
fn event_serialization() { fn event_serialization() {
let event = OriginalMessageLikeEvent { let content = assign!(
content: assign!( VideoEventContent::with_message(
VideoEventContent::with_message( MessageContent::html(
MessageContent::html( "Upload: my_lava_lamp.webm",
"Upload: my_lava_lamp.webm", "Upload: <strong>my_lava_lamp.webm</strong>",
"Upload: <strong>my_lava_lamp.webm</strong>",
),
FileContent::plain(
mxc_uri!("mxc://notareal.hs/abcdef").to_owned(),
Some(Box::new(assign!(
FileContentInfo::new(),
{
name: Some("my_lava_lamp.webm".to_owned()),
mimetype: Some("video/webm".to_owned()),
size: Some(uint!(1_897_774)),
}
))),
)
), ),
{ FileContent::plain(
video: Box::new(assign!( mxc_uri!("mxc://notareal.hs/abcdef").to_owned(),
VideoContent::new(), Some(Box::new(assign!(
FileContentInfo::new(),
{ {
width: Some(uint!(1920)), name: Some("my_lava_lamp.webm".to_owned()),
height: Some(uint!(1080)), mimetype: Some("video/webm".to_owned()),
duration: Some(Duration::from_secs(15)), size: Some(uint!(1_897_774)),
} }
)), ))),
thumbnail: vec![ThumbnailContent::new( )
ThumbnailFileContent::plain(
mxc_uri!("mxc://notareal.hs/thumbnail").to_owned(),
Some(Box::new(assign!(ThumbnailFileContentInfo::new(), {
mimetype: Some("image/jpeg".to_owned()),
size: Some(uint!(334_593)),
})))
),
None
)],
caption: Some(MessageContent::plain("This is my awesome vintage lava lamp")),
relates_to: Some(Relation::Reply {
in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()),
}),
}
), ),
event_id: event_id!("$event:notareal.hs").to_owned(), {
sender: user_id!("@user:notareal.hs").to_owned(), video: Box::new(assign!(
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)), VideoContent::new(),
room_id: room_id!("!roomid:notareal.hs").to_owned(), {
unsigned: MessageLikeUnsigned::default(), width: Some(uint!(1920)),
}; height: Some(uint!(1080)),
duration: Some(Duration::from_secs(15)),
}
)),
thumbnail: vec![ThumbnailContent::new(
ThumbnailFileContent::plain(
mxc_uri!("mxc://notareal.hs/thumbnail").to_owned(),
Some(Box::new(assign!(ThumbnailFileContentInfo::new(), {
mimetype: Some("image/jpeg".to_owned()),
size: Some(uint!(334_593)),
})))
),
None
)],
caption: Some(MessageContent::plain("This is my awesome vintage lava lamp")),
relates_to: Some(Relation::Reply {
in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()),
}),
}
);
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "org.matrix.msc1767.html": "Upload: <strong>my_lava_lamp.webm</strong>",
"org.matrix.msc1767.html": "Upload: <strong>my_lava_lamp.webm</strong>", "org.matrix.msc1767.text": "Upload: my_lava_lamp.webm",
"org.matrix.msc1767.text": "Upload: my_lava_lamp.webm", "m.file": {
"m.file": { "url": "mxc://notareal.hs/abcdef",
"url": "mxc://notareal.hs/abcdef", "name": "my_lava_lamp.webm",
"name": "my_lava_lamp.webm", "mimetype": "video/webm",
"mimetype": "video/webm", "size": 1_897_774,
"size": 1_897_774,
},
"m.video": {
"width": 1920,
"height": 1080,
"duration": 15_000,
},
"m.thumbnail": [
{
"url": "mxc://notareal.hs/thumbnail",
"mimetype": "image/jpeg",
"size": 334_593,
}
],
"m.caption": [
{
"body": "This is my awesome vintage lava lamp",
"mimetype": "text/plain",
}
],
"m.relates_to": {
"m.in_reply_to": {
"event_id": "$replyevent:example.com"
}
}
}, },
"event_id": "$event:notareal.hs", "m.video": {
"origin_server_ts": 134_829_848, "width": 1920,
"room_id": "!roomid:notareal.hs", "height": 1080,
"sender": "@user:notareal.hs", "duration": 15_000,
"type": "m.video", },
"m.thumbnail": [
{
"url": "mxc://notareal.hs/thumbnail",
"mimetype": "image/jpeg",
"size": 334_593,
}
],
"m.caption": [
{
"body": "This is my awesome vintage lava lamp",
"mimetype": "text/plain",
}
],
"m.relates_to": {
"m.in_reply_to": {
"event_id": "$replyevent:example.com"
}
}
}) })
); );
} }

View File

@ -16,77 +16,63 @@ use ruma_common::{
MediaSource, MediaSource,
}, },
voice::{VoiceContent, VoiceEventContent}, voice::{VoiceContent, VoiceEventContent},
AnyMessageLikeEvent, MessageLikeEvent, MessageLikeUnsigned, OriginalMessageLikeEvent, AnyMessageLikeEvent, MessageLikeEvent,
}, },
mxc_uri, room_id, mxc_uri,
serde::CanBeEmpty, serde::CanBeEmpty,
user_id, MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch,
}; };
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
#[test] #[test]
fn event_serialization() { fn event_serialization() {
let event = OriginalMessageLikeEvent { let content = assign!(
content: assign!( VoiceEventContent::plain(
VoiceEventContent::plain( "Voice message",
"Voice message", FileContent::plain(
FileContent::plain( mxc_uri!("mxc://notareal.hs/abcdef").to_owned(),
mxc_uri!("mxc://notareal.hs/abcdef").to_owned(), Some(Box::new(assign!(
Some(Box::new(assign!( FileContentInfo::new(),
FileContentInfo::new(),
{
name: Some("voice_message.ogg".to_owned()),
mimetype: Some("audio/opus".to_owned()),
size: Some(uint!(897_774)),
}
))),
)
),
{
audio: assign!(
AudioContent::new(),
{ {
duration: Some(Duration::from_secs(23)) name: Some("voice_message.ogg".to_owned()),
mimetype: Some("audio/opus".to_owned()),
size: Some(uint!(897_774)),
} }
), ))),
relates_to: Some(Relation::Reply { )
in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()),
}),
}
), ),
event_id: event_id!("$event:notareal.hs").to_owned(), {
sender: user_id!("@user:notareal.hs").to_owned(), audio: assign!(
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(134_829_848)), AudioContent::new(),
room_id: room_id!("!roomid:notareal.hs").to_owned(), {
unsigned: MessageLikeUnsigned::default(), duration: Some(Duration::from_secs(23))
}; }
),
relates_to: Some(Relation::Reply {
in_reply_to: InReplyTo::new(event_id!("$replyevent:example.com").to_owned()),
}),
}
);
assert_eq!( assert_eq!(
to_json_value(&event).unwrap(), to_json_value(&content).unwrap(),
json!({ json!({
"content": { "org.matrix.msc1767.text": "Voice message",
"org.matrix.msc1767.text": "Voice message", "m.file": {
"m.file": { "url": "mxc://notareal.hs/abcdef",
"url": "mxc://notareal.hs/abcdef", "name": "voice_message.ogg",
"name": "voice_message.ogg", "mimetype": "audio/opus",
"mimetype": "audio/opus", "size": 897_774,
"size": 897_774, },
}, "m.audio": {
"m.audio": { "duration": 23_000,
"duration": 23_000, },
}, "m.voice": {},
"m.voice": {}, "m.relates_to": {
"m.relates_to": { "m.in_reply_to": {
"m.in_reply_to": { "event_id": "$replyevent:example.com"
"event_id": "$replyevent:example.com"
}
} }
}, },
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.voice",
}) })
); );
} }

View File

@ -41,7 +41,6 @@ pub fn expand_event(input: DeriveInput) -> syn::Result<TokenStream> {
let mut res = TokenStream::new(); let mut res = TokenStream::new();
res.extend(expand_serialize_event(&input, var, &fields, &ruma_common));
res.extend( res.extend(
expand_deserialize_event(&input, kind, var, &fields, &ruma_common) expand_deserialize_event(&input, kind, var, &fields, &ruma_common)
.unwrap_or_else(syn::Error::into_compile_error), .unwrap_or_else(syn::Error::into_compile_error),
@ -58,72 +57,6 @@ pub fn expand_event(input: DeriveInput) -> syn::Result<TokenStream> {
Ok(res) Ok(res)
} }
fn expand_serialize_event(
input: &DeriveInput,
var: EventKindVariation,
fields: &[Field],
ruma_common: &TokenStream,
) -> TokenStream {
let serde = quote! { #ruma_common::exports::serde };
let ident = &input.ident;
let (impl_gen, ty_gen, where_clause) = input.generics.split_for_impl();
let serialize_fields: Vec<_> = fields
.iter()
.map(|field| {
let name = field.ident.as_ref().unwrap();
if name == "content" && var.is_redacted() {
quote! {
state.serialize_field("content", &self.content)?;
}
} else if name == "unsigned" {
quote! {
if !#ruma_common::serde::is_empty(&self.unsigned) {
state.serialize_field("unsigned", &self.unsigned)?;
}
}
} else {
let name_s = name.to_string();
match &field.ty {
syn::Type::Path(syn::TypePath { path: syn::Path { segments, .. }, .. })
if segments.last().unwrap().ident == "Option" =>
{
quote! {
if let Some(content) = self.#name.as_ref() {
state.serialize_field(#name_s, content)?;
}
}
}
_ => quote! {
state.serialize_field(#name_s, &self.#name)?;
},
}
}
})
.collect();
quote! {
#[automatically_derived]
impl #impl_gen #serde::ser::Serialize for #ident #ty_gen #where_clause {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: #serde::ser::Serializer,
{
use #serde::ser::{SerializeStruct as _, Error as _};
let mut state = serializer.serialize_struct(stringify!(#ident), 7)?;
let event_type = #ruma_common::events::EventContent::event_type(&self.content);
state.serialize_field("type", &event_type)?;
#( #serialize_fields )*
state.end()
}
}
}
}
fn expand_deserialize_event( fn expand_deserialize_event(
input: &DeriveInput, input: &DeriveInput,
kind: EventKind, kind: EventKind,