1use std::fmt;
2
3use ruma_common::serde::{CanBeEmpty, Raw};
4use serde::{de::DeserializeOwned, Serialize};
5use serde_json::{from_str as from_json_str, value::RawValue as RawJsonValue};
6
7use super::{
8 EphemeralRoomEventType, GlobalAccountDataEventType, MessageLikeEventType,
9 RoomAccountDataEventType, StateEventType, ToDeviceEventType,
10};
11
12pub trait EventContent: Sized + Serialize {
18 type EventType;
20
21 fn event_type(&self) -> Self::EventType;
23}
24
25pub trait RawExt<T: EventContentFromType> {
27 fn deserialize_with_type(&self, event_type: T::EventType) -> serde_json::Result<T>;
29}
30
31impl<T> RawExt<T> for Raw<T>
32where
33 T: EventContentFromType,
34 T::EventType: fmt::Display,
35{
36 fn deserialize_with_type(&self, event_type: T::EventType) -> serde_json::Result<T> {
37 T::from_parts(&event_type.to_string(), self.json())
38 }
39}
40
41pub trait StaticEventContent: EventContent {
43 const TYPE: &'static str;
45}
46
47pub trait GlobalAccountDataEventContent:
49 EventContent<EventType = GlobalAccountDataEventType>
50{
51}
52
53pub trait RoomAccountDataEventContent: EventContent<EventType = RoomAccountDataEventType> {}
55
56pub trait EphemeralRoomEventContent: EventContent<EventType = EphemeralRoomEventType> {}
58
59pub trait MessageLikeEventContent: EventContent<EventType = MessageLikeEventType> {}
61
62pub trait RedactedMessageLikeEventContent: EventContent<EventType = MessageLikeEventType> {}
64
65pub trait StateEventContent: EventContent<EventType = StateEventType> {
67 type StateKey: AsRef<str> + Clone + fmt::Debug + DeserializeOwned + Serialize;
69}
70
71pub trait StaticStateEventContent: StateEventContent {
73 type PossiblyRedacted: PossiblyRedactedStateEventContent;
75
76 type Unsigned: Clone + fmt::Debug + Default + CanBeEmpty + DeserializeOwned;
78}
79
80pub trait RedactedStateEventContent: EventContent<EventType = StateEventType> {
82 type StateKey: AsRef<str> + Clone + fmt::Debug + DeserializeOwned + Serialize;
84}
85
86pub trait PossiblyRedactedStateEventContent: EventContent<EventType = StateEventType> {
88 type StateKey: AsRef<str> + Clone + fmt::Debug + DeserializeOwned + Serialize;
90}
91
92pub trait ToDeviceEventContent: EventContent<EventType = ToDeviceEventType> {}
94
95pub trait EventContentFromType: EventContent {
97 fn from_parts(event_type: &str, content: &RawJsonValue) -> serde_json::Result<Self>;
99}
100
101impl<T> EventContentFromType for T
102where
103 T: EventContent + DeserializeOwned,
104{
105 fn from_parts(_event_type: &str, content: &RawJsonValue) -> serde_json::Result<Self> {
106 from_json_str(content.get())
107 }
108}