events: Split Basic enum into GlobalAccountData, RoomAccountData and BasicToDevice enums

Closes #563
This commit is contained in:
Kévin Commaille 2021-05-10 14:37:54 +02:00 committed by Jonas Platte
parent dcff455c19
commit 8d8ca81e04
18 changed files with 153 additions and 71 deletions

View File

@ -1,7 +1,7 @@
//! [GET /_matrix/client/r0/user/{userId}/account_data/{type}](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-user-userid-account-data-type)
use ruma_api::ruma_api;
use ruma_events::AnyBasicEventContent;
use ruma_events::AnyGlobalAccountDataEventContent;
use ruma_identifiers::UserId;
use ruma_serde::Raw;
@ -30,7 +30,7 @@ ruma_api! {
///
/// Use `ruma_events::RawExt` for deserialization.
#[ruma_api(body)]
pub account_data: Raw<AnyBasicEventContent>,
pub account_data: Raw<AnyGlobalAccountDataEventContent>,
}
error: crate::Error
@ -45,7 +45,7 @@ impl<'a> Request<'a> {
impl Response {
/// Creates a new `Response` with the given account data.
pub fn new(account_data: Raw<AnyBasicEventContent>) -> Self {
pub fn new(account_data: Raw<AnyGlobalAccountDataEventContent>) -> Self {
Self { account_data }
}
}

View File

@ -1,7 +1,7 @@
//! [GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-user-userid-rooms-roomid-account-data-type)
use ruma_api::ruma_api;
use ruma_events::AnyBasicEventContent;
use ruma_events::AnyRoomAccountDataEventContent;
use ruma_identifiers::{RoomId, UserId};
use ruma_serde::Raw;
@ -34,7 +34,7 @@ ruma_api! {
///
/// Use `ruma_events::RawExt` for deserialization.
#[ruma_api(body)]
pub account_data: Raw<AnyBasicEventContent>,
pub account_data: Raw<AnyRoomAccountDataEventContent>,
}
error: crate::Error
@ -49,7 +49,7 @@ impl<'a> Request<'a> {
impl Response {
/// Creates a new `Response` with the given account data.
pub fn new(account_data: Raw<AnyBasicEventContent>) -> Self {
pub fn new(account_data: Raw<AnyRoomAccountDataEventContent>) -> Self {
Self { account_data }
}
}

View File

@ -6,8 +6,9 @@ use js_int::UInt;
use ruma_api::ruma_api;
use ruma_common::presence::PresenceState;
use ruma_events::{
presence::PresenceEvent, AnyBasicEvent, AnyStrippedStateEvent, AnySyncEphemeralRoomEvent,
AnySyncRoomEvent, AnySyncStateEvent, AnyToDeviceEvent,
presence::PresenceEvent, AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent,
AnyStrippedStateEvent, AnySyncEphemeralRoomEvent, AnySyncRoomEvent, AnySyncStateEvent,
AnyToDeviceEvent,
};
use ruma_identifiers::{DeviceKeyAlgorithm, RoomId, UserId};
use ruma_serde::{Outgoing, Raw};
@ -75,8 +76,8 @@ ruma_api! {
pub presence: Presence,
/// The global private data created by this user.
#[serde(default, skip_serializing_if = "AccountData::is_empty")]
pub account_data: AccountData,
#[serde(default, skip_serializing_if = "GlobalAccountData::is_empty")]
pub account_data: GlobalAccountData,
/// Messages sent dirrectly between devices.
#[serde(default, skip_serializing_if = "ToDevice::is_empty")]
@ -219,8 +220,8 @@ pub struct LeftRoom {
pub state: State,
/// The private data that this user has attached to this room.
#[serde(default, skip_serializing_if = "AccountData::is_empty")]
pub account_data: AccountData,
#[serde(default, skip_serializing_if = "RoomAccountData::is_empty")]
pub account_data: RoomAccountData,
#[cfg(not(feature = "unstable-exhaustive-types"))]
#[doc(hidden)]
@ -275,8 +276,8 @@ pub struct JoinedRoom {
pub state: State,
/// The private data that this user has attached to this room.
#[serde(default, skip_serializing_if = "AccountData::is_empty")]
pub account_data: AccountData,
#[serde(default, skip_serializing_if = "RoomAccountData::is_empty")]
pub account_data: RoomAccountData,
/// The ephemeral events in the room that aren't recorded in the timeline or state of the
/// room. e.g. typing.
@ -444,12 +445,12 @@ impl Default for State {
}
}
/// The private data that this user has attached to this room.
/// The global private data created by this user.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AccountData {
pub struct GlobalAccountData {
/// A list of events.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Raw<AnyBasicEvent>>,
pub events: Vec<Raw<AnyGlobalAccountDataEvent>>,
#[cfg(not(feature = "unstable-exhaustive-types"))]
#[doc(hidden)]
@ -457,19 +458,54 @@ pub struct AccountData {
pub __test_exhaustive: crate::Private,
}
impl AccountData {
/// Creates an empty `AccountData`.
impl GlobalAccountData {
/// Creates an empty `GlobalAccountData`.
pub fn new() -> Self {
Default::default()
}
/// Returns true if there are no account data updates.
/// Returns true if there are no global account data updates.
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
impl Default for AccountData {
impl Default for GlobalAccountData {
fn default() -> Self {
Self {
events: vec![],
#[cfg(not(feature = "unstable-exhaustive-types"))]
__test_exhaustive: crate::private(),
}
}
}
/// The private data that this user has attached to this room.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RoomAccountData {
/// A list of events.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Raw<AnyRoomAccountDataEvent>>,
#[cfg(not(feature = "unstable-exhaustive-types"))]
#[doc(hidden)]
#[serde(skip, default = "crate::private")]
pub __test_exhaustive: crate::Private,
}
impl RoomAccountData {
/// Creates an empty `RoomAccountData`.
pub fn new() -> Self {
Default::default()
}
/// Returns true if there are no room account data updates.
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
impl Default for RoomAccountData {
fn default() -> Self {
Self {
events: vec![],

View File

@ -680,7 +680,15 @@ fn marker_traits(kind: &EventKind, ruma_events: &TokenStream) -> TokenStream {
#[automatically_derived]
impl #ruma_events::EphemeralRoomEventContent for #ident {}
},
EventKind::Basic => quote! {
EventKind::GlobalAccountData => quote! {
#[automatically_derived]
impl #ruma_events::BasicEventContent for #ident {}
},
EventKind::RoomAccountData => quote! {
#[automatically_derived]
impl #ruma_events::BasicEventContent for #ident {}
},
EventKind::BasicToDevice => quote! {
#[automatically_derived]
impl #ruma_events::BasicEventContent for #ident {}
},

View File

@ -63,10 +63,12 @@ impl EventKindVariation {
// If the variants of this enum change `to_event_path` needs to be updated as well.
#[derive(Debug, Eq, PartialEq)]
pub enum EventKind {
Basic,
GlobalAccountData,
RoomAccountData,
Ephemeral,
Message,
State,
BasicToDevice,
ToDevice,
Redaction,
Presence,
@ -75,10 +77,12 @@ pub enum EventKind {
impl fmt::Display for EventKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
EventKind::Basic => write!(f, "BasicEvent"),
EventKind::GlobalAccountData => write!(f, "GlobalAccountDataEvent"),
EventKind::RoomAccountData => write!(f, "RoomAccountDataEvent"),
EventKind::Ephemeral => write!(f, "EphemeralRoomEvent"),
EventKind::Message => write!(f, "MessageEvent"),
EventKind::State => write!(f, "StateEvent"),
EventKind::BasicToDevice => write!(f, "BasicToDeviceEvent"),
EventKind::ToDevice => write!(f, "ToDeviceEvent"),
EventKind::Redaction => write!(f, "RedactionEvent"),
EventKind::Presence => write!(f, "PresenceEvent"),
@ -131,17 +135,19 @@ impl Parse for EventKind {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let ident: Ident = input.parse()?;
Ok(match ident.to_string().as_str() {
"Basic" => EventKind::Basic,
"GlobalAccountData" => EventKind::GlobalAccountData,
"RoomAccountData" => EventKind::RoomAccountData,
"EphemeralRoom" => EventKind::Ephemeral,
"Message" => EventKind::Message,
"State" => EventKind::State,
"BasicToDevice" => EventKind::BasicToDevice,
"ToDevice" => EventKind::ToDevice,
id => {
return Err(syn::Error::new(
input.span(),
format!(
"valid event kinds are Basic, EphemeralRoom, Message, State, ToDevice \
found `{}`",
"valid event kinds are GlobalAccountData, RoomAccountData, EphemeralRoom, \
Message, State, BasicToDevice, ToDevice found `{}`",
id
),
));
@ -156,7 +162,8 @@ impl Parse for EventKind {
pub fn to_kind_variation(ident: &Ident) -> Option<(EventKind, EventKindVariation)> {
let ident_str = ident.to_string();
match ident_str.as_str() {
"BasicEvent" => Some((EventKind::Basic, EventKindVariation::Full)),
"GlobalAccountDataEvent" => Some((EventKind::GlobalAccountData, EventKindVariation::Full)),
"RoomAccountDataEvent" => Some((EventKind::RoomAccountData, EventKindVariation::Full)),
"EphemeralRoomEvent" => Some((EventKind::Ephemeral, EventKindVariation::Full)),
"SyncEphemeralRoomEvent" => Some((EventKind::Ephemeral, EventKindVariation::Sync)),
"MessageEvent" => Some((EventKind::Message, EventKindVariation::Full)),
@ -172,6 +179,7 @@ pub fn to_kind_variation(ident: &Ident) -> Option<(EventKind, EventKindVariation
"RedactedStrippedStateEvent" => {
Some((EventKind::State, EventKindVariation::RedactedStripped))
}
"BasicToDeviceEvent" => Some((EventKind::BasicToDevice, EventKindVariation::Full)),
"ToDeviceEvent" => Some((EventKind::ToDevice, EventKindVariation::Full)),
"PresenceEvent" => Some((EventKind::Presence, EventKindVariation::Full)),
"RedactionEvent" => Some((EventKind::Redaction, EventKindVariation::Full)),

View File

@ -41,8 +41,8 @@ Breaking changes:
sticker::StickerEventContent
```
* Add `tag::TagName` type and use it for `tag::Tags`
* Move `FullyRead` from `EphemeralRoom` enum to `Basic` enum
* Change `receipt::Receipts` struct to a `BTreeMap<ReceiptType, UserReceipts>`
* Move `FullyRead` from `EphemeralRoom` enum to `RoomAccountData` enum
* Split `Basic` enum into `GlobalAccountData`, `RoomAccountData` and `BasicToDevice` enums
Improvements:

View File

@ -10,7 +10,7 @@ use ruma_identifiers::{RoomId, UserId};
use serde::{Deserialize, Serialize};
/// Informs the client about the rooms that are considered direct by a user.
pub type DirectEvent = crate::BasicEvent<DirectEventContent>;
pub type DirectEvent = crate::GlobalAccountDataEvent<DirectEventContent>;
/// The payload for `DirectEvent`.
///

View File

@ -3,7 +3,7 @@
use ruma_events_macros::BasicEventContent;
use serde::{Deserialize, Serialize};
use crate::BasicEvent;
use crate::BasicToDeviceEvent;
/// This event type is used to indicate new Olm sessions for end-to-end encryption.
///
@ -14,7 +14,7 @@ use crate::BasicEvent;
/// this *m.dummy* event as the most recent event and using the keyshare request to set up the
/// session. The keyshare request and *m.dummy* combination should result in the original
/// sending client receiving keys over the newly established session.
pub type DummyEvent = BasicEvent<DummyEventContent>;
pub type DummyEvent = BasicToDeviceEvent<DummyEventContent>;
/// The payload for `DummyEvent`.
#[derive(Clone, Debug, Deserialize, Serialize, BasicEventContent)]

View File

@ -5,16 +5,20 @@ use serde_json::value::RawValue as RawJsonValue;
use crate::{from_raw_json_value, EventDeHelper};
event_enum! {
/// Any basic event.
kind: Basic,
/// Any global account data event.
kind: GlobalAccountData,
events: [
"m.direct",
"m.dummy",
"m.fully_read",
"m.ignored_user_list",
"m.presence",
"m.push_rules",
"m.room_key",
]
}
event_enum! {
/// Any room account data event.
kind: RoomAccountData,
events: [
"m.fully_read",
"m.tag",
]
}
@ -94,6 +98,15 @@ event_enum! {
]
}
event_enum! {
/// Any basic to-device event.
kind: BasicToDevice,
events: [
"m.dummy",
"m.room_key",
]
}
event_enum! {
/// Any to-device event.
kind: ToDevice,

View File

@ -9,9 +9,16 @@ use crate::{
StateEventContent, Unsigned,
};
/// A basic event one that consists only of it's type and the `content` object.
/// A global account data event.
#[derive(Clone, Debug, Event)]
pub struct BasicEvent<C: BasicEventContent> {
pub struct GlobalAccountDataEvent<C: BasicEventContent> {
/// Data specific to the event type.
pub content: C,
}
/// A room account data event.
#[derive(Clone, Debug, Event)]
pub struct RoomAccountDataEvent<C: BasicEventContent> {
/// Data specific to the event type.
pub content: C,
}
@ -310,6 +317,14 @@ pub struct RedactedStrippedStateEvent<C: RedactedStateEventContent> {
pub state_key: String,
}
/// A basic event sent using send-to-device event messaging one that consists only of it's type
/// and the `content` object.
#[derive(Clone, Debug, Event)]
pub struct BasicToDeviceEvent<C: BasicEventContent> {
/// Data specific to the event type.
pub content: C,
}
/// An event sent using send-to-device messaging.
#[derive(Clone, Debug, Event)]
pub struct ToDeviceEvent<C: EventContent> {

View File

@ -4,13 +4,13 @@ use ruma_events_macros::BasicEventContent;
use ruma_identifiers::EventId;
use serde::{Deserialize, Serialize};
use crate::BasicEvent;
use crate::RoomAccountDataEvent;
/// The current location of the user's read marker in a room.
///
/// This event appears in the user's room account data for the room the marker is applicable
/// for.
pub type FullyReadEvent = BasicEvent<FullyReadEventContent>;
pub type FullyReadEvent = RoomAccountDataEvent<FullyReadEventContent>;
/// The payload for `FullyReadEvent`.
#[derive(Clone, Debug, Deserialize, Serialize, BasicEventContent)]

View File

@ -4,10 +4,10 @@ use ruma_events_macros::BasicEventContent;
use ruma_identifiers::UserId;
use serde::{Deserialize, Serialize};
use crate::BasicEvent;
use crate::GlobalAccountDataEvent;
/// A list of users to ignore.
pub type IgnoredUserListEvent = BasicEvent<IgnoredUserListEventContent>;
pub type IgnoredUserListEvent = GlobalAccountDataEvent<IgnoredUserListEventContent>;
/// The payload for `IgnoredUserListEvent`.
#[derive(Clone, Debug, Deserialize, Serialize, BasicEventContent)]
@ -34,11 +34,11 @@ mod tests {
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::IgnoredUserListEventContent;
use crate::{AnyBasicEventContent, BasicEvent};
use crate::{AnyGlobalAccountDataEventContent, GlobalAccountDataEvent};
#[test]
fn serialization() {
let ignored_user_list_event = BasicEvent {
let ignored_user_list_event = GlobalAccountDataEvent {
content: IgnoredUserListEventContent {
ignored_users: vec![user_id!("@carl:example.com")],
},
@ -68,12 +68,12 @@ mod tests {
});
assert_matches!(
from_json_value::<Raw<BasicEvent<AnyBasicEventContent>>>(json)
from_json_value::<Raw<GlobalAccountDataEvent<AnyGlobalAccountDataEventContent>>>(json)
.unwrap()
.deserialize()
.unwrap(),
BasicEvent {
content: AnyBasicEventContent::IgnoredUserList(IgnoredUserListEventContent {
GlobalAccountDataEvent {
content: AnyGlobalAccountDataEventContent::IgnoredUserList(IgnoredUserListEventContent {
ignored_users,
}),
} if ignored_users == vec![user_id!("@carl:example.com")]

View File

@ -187,22 +187,24 @@ pub mod typing;
pub use self::relation::Relations;
pub use self::{
enums::{
AnyBasicEvent, AnyBasicEventContent, AnyEphemeralRoomEvent, AnyEphemeralRoomEventContent,
AnyInitialStateEvent, AnyMessageEvent, AnyMessageEventContent,
AnyPossiblyRedactedMessageEvent, AnyPossiblyRedactedStateEvent,
AnyEphemeralRoomEvent, AnyEphemeralRoomEventContent, AnyGlobalAccountDataEvent,
AnyGlobalAccountDataEventContent, AnyInitialStateEvent, AnyMessageEvent,
AnyMessageEventContent, AnyPossiblyRedactedMessageEvent, AnyPossiblyRedactedStateEvent,
AnyPossiblyRedactedStrippedStateEvent, AnyPossiblyRedactedSyncMessageEvent,
AnyPossiblyRedactedSyncStateEvent, AnyRedactedMessageEvent, AnyRedactedStateEvent,
AnyRedactedStrippedStateEvent, AnyRedactedSyncMessageEvent, AnyRedactedSyncStateEvent,
AnyRoomEvent, AnyStateEvent, AnyStateEventContent, AnyStrippedStateEvent,
AnySyncEphemeralRoomEvent, AnySyncMessageEvent, AnySyncRoomEvent, AnySyncStateEvent,
AnyToDeviceEvent, AnyToDeviceEventContent,
AnyRoomAccountDataEvent, AnyRoomAccountDataEventContent, AnyRoomEvent, AnyStateEvent,
AnyStateEventContent, AnyStrippedStateEvent, AnySyncEphemeralRoomEvent,
AnySyncMessageEvent, AnySyncRoomEvent, AnySyncStateEvent, AnyToDeviceEvent,
AnyToDeviceEventContent,
},
error::{FromStrError, InvalidInput},
event_kinds::{
BasicEvent, EphemeralRoomEvent, InitialStateEvent, MessageEvent, RedactedMessageEvent,
RedactedStateEvent, RedactedStrippedStateEvent, RedactedSyncMessageEvent,
RedactedSyncStateEvent, StateEvent, StrippedStateEvent, SyncEphemeralRoomEvent,
SyncMessageEvent, SyncStateEvent, ToDeviceEvent,
BasicToDeviceEvent, EphemeralRoomEvent, GlobalAccountDataEvent, InitialStateEvent,
MessageEvent, RedactedMessageEvent, RedactedStateEvent, RedactedStrippedStateEvent,
RedactedSyncMessageEvent, RedactedSyncStateEvent, RoomAccountDataEvent, StateEvent,
StrippedStateEvent, SyncEphemeralRoomEvent, SyncMessageEvent, SyncStateEvent,
ToDeviceEvent,
},
event_type::EventType,
};

View File

@ -4,10 +4,10 @@ use ruma_common::push::Ruleset;
use ruma_events_macros::BasicEventContent;
use serde::{Deserialize, Serialize};
use crate::BasicEvent;
use crate::GlobalAccountDataEvent;
/// Describes all push rules for a user.
pub type PushRulesEvent = BasicEvent<PushRulesEventContent>;
pub type PushRulesEvent = GlobalAccountDataEvent<PushRulesEventContent>;
/// The payload for `PushRulesEvent`.
#[derive(Clone, Debug, Deserialize, Serialize, BasicEventContent)]

View File

@ -4,10 +4,10 @@ use ruma_events_macros::BasicEventContent;
use ruma_identifiers::{EventEncryptionAlgorithm, RoomId};
use serde::{Deserialize, Serialize};
use crate::BasicEvent;
use crate::BasicToDeviceEvent;
/// Typically encrypted as an *m.room.encrypted* event, then sent as a to-device event.
pub type RoomKeyEvent = BasicEvent<RoomKeyEventContent>;
pub type RoomKeyEvent = BasicToDeviceEvent<RoomKeyEventContent>;
/// The payload for `RoomKeyEvent`.
#[derive(Clone, Debug, Deserialize, Serialize, BasicEventContent)]
@ -37,11 +37,11 @@ mod tests {
use serde_json::{json, to_value as to_json_value};
use super::RoomKeyEventContent;
use crate::BasicEvent;
use crate::BasicToDeviceEvent;
#[test]
fn serialization() {
let ev = BasicEvent {
let ev = BasicToDeviceEvent {
content: RoomKeyEventContent {
algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
room_id: room_id!("!testroomid:example.org"),

View File

@ -6,10 +6,10 @@ use ruma_events_macros::BasicEventContent;
use ruma_serde::deserialize_cow_str;
use serde::{Deserialize, Serialize};
use crate::BasicEvent;
use crate::RoomAccountDataEvent;
/// Informs the client of tags on a room.
pub type TagEvent = BasicEvent<TagEventContent>;
pub type TagEvent = RoomAccountDataEvent<TagEventContent>;
/// Map of tag names to tag info.
pub type Tags = BTreeMap<TagName, TagInfo>;

View File

@ -1,8 +1,8 @@
use ruma_events_macros::event_enum;
event_enum! {
/// Any basic event.
kind: Basic,
/// Any global account data event.
kind: GlobalAccountData,
events: [
"m.direct",
#[cfg(test)]

View File

@ -1,4 +1,4 @@
error: valid event kinds are Basic, EphemeralRoom, Message, State, ToDevice found `NotReal`
error: valid event kinds are GlobalAccountData, RoomAccountData, EphemeralRoom, Message, State, BasicToDevice, ToDevice found `NotReal`
--> $DIR/09-enum-invalid-kind.rs:4:18
|
4 | kind: NotReal,