ruma_events/
enums.rs

1use ruma_common::{
2    serde::from_raw_json_value, EventId, MilliSecondsSinceUnixEpoch, OwnedRoomId, RoomId,
3    TransactionId, UserId,
4};
5#[cfg(feature = "unstable-msc3381")]
6use ruma_events::{
7    poll::{start::PollStartEventContent, unstable_start::UnstablePollStartEventContent},
8    room::encrypted::Replacement,
9};
10use ruma_macros::{event_enum, EventEnumFromEvent};
11use serde::{de, Deserialize};
12use serde_json::value::RawValue as RawJsonValue;
13
14use super::room::encrypted;
15
16/// Event types that servers should send as [stripped state] to help clients identify a room when
17/// they can't access the full room state.
18///
19/// [stripped state]: https://spec.matrix.org/latest/client-server-api/#stripped-state
20pub const RECOMMENDED_STRIPPED_STATE_EVENT_TYPES: &[StateEventType] = &[
21    StateEventType::RoomCreate,
22    StateEventType::RoomName,
23    StateEventType::RoomAvatar,
24    StateEventType::RoomTopic,
25    StateEventType::RoomJoinRules,
26    StateEventType::RoomCanonicalAlias,
27    StateEventType::RoomEncryption,
28];
29
30event_enum! {
31    /// Any global account data event.
32    enum GlobalAccountData {
33        "m.direct" => super::direct,
34        "m.identity_server" => super::identity_server,
35        "m.ignored_user_list" => super::ignored_user_list,
36        "m.push_rules" => super::push_rules,
37        "m.secret_storage.default_key" => super::secret_storage::default_key,
38        "m.secret_storage.key.*" => super::secret_storage::key,
39        #[cfg(feature = "unstable-msc4278")]
40        "m.media_preview_config" => super::media_preview_config,
41        #[cfg(feature = "unstable-msc4278")]
42        #[ruma_enum(ident = UnstableMediaPreviewConfig)]
43        "io.element.msc4278.media_preview_config" => super::media_preview_config,
44        #[cfg(feature = "unstable-msc2545")]
45        #[ruma_enum(ident = AccountImagePack, alias = "m.image_pack")]
46        "im.ponies.user_emotes" => super::image_pack,
47        #[cfg(feature = "unstable-msc2545")]
48        #[ruma_enum(ident = ImagePackRooms, alias = "m.image_pack.rooms")]
49        "im.ponies.emote_rooms" => super::image_pack,
50    }
51
52    /// Any room account data event.
53    enum RoomAccountData {
54        "m.fully_read" => super::fully_read,
55        "m.tag" => super::tag,
56        "m.marked_unread" => super::marked_unread,
57        #[cfg(feature = "unstable-msc2867")]
58        #[ruma_enum(ident = UnstableMarkedUnread)]
59        "com.famedly.marked_unread" => super::marked_unread,
60        #[cfg(feature = "unstable-msc4278")]
61        "m.media_preview_config" => super::media_preview_config,
62        #[cfg(feature = "unstable-msc4278")]
63        #[ruma_enum(ident = UnstableMediaPreviewConfig)]
64        "io.element.msc4278.media_preview_config" => super::media_preview_config,
65    }
66
67    /// Any ephemeral room event.
68    enum EphemeralRoom {
69        "m.receipt" => super::receipt,
70        "m.typing" => super::typing,
71    }
72
73    /// Any message-like event.
74    enum MessageLike {
75        #[cfg(feature = "unstable-msc3927")]
76        #[ruma_enum(alias = "m.audio")]
77        "org.matrix.msc1767.audio" => super::audio,
78        "m.call.answer" => super::call::answer,
79        "m.call.invite" => super::call::invite,
80        "m.call.hangup" => super::call::hangup,
81        "m.call.candidates" => super::call::candidates,
82        "m.call.negotiate" => super::call::negotiate,
83        "m.call.reject" => super::call::reject,
84        #[ruma_enum(alias = "org.matrix.call.sdp_stream_metadata_changed")]
85        "m.call.sdp_stream_metadata_changed" => super::call::sdp_stream_metadata_changed,
86        "m.call.select_answer" => super::call::select_answer,
87        #[cfg(feature = "unstable-msc3954")]
88        #[ruma_enum(alias = "m.emote")]
89        "org.matrix.msc1767.emote" => super::emote,
90        #[cfg(feature = "unstable-msc3956")]
91        #[ruma_enum(alias = "m.encrypted")]
92        "org.matrix.msc1767.encrypted" => super::encrypted,
93        #[cfg(feature = "unstable-msc3551")]
94        #[ruma_enum(alias = "m.file")]
95        "org.matrix.msc1767.file" => super::file,
96        #[cfg(feature = "unstable-msc3552")]
97        #[ruma_enum(alias = "m.image")]
98        "org.matrix.msc1767.image" => super::image,
99        "m.key.verification.ready" => super::key::verification::ready,
100        "m.key.verification.start" => super::key::verification::start,
101        "m.key.verification.cancel" => super::key::verification::cancel,
102        "m.key.verification.accept" => super::key::verification::accept,
103        "m.key.verification.key" => super::key::verification::key,
104        "m.key.verification.mac" => super::key::verification::mac,
105        "m.key.verification.done" => super::key::verification::done,
106        #[cfg(feature = "unstable-msc3488")]
107        "m.location" => super::location,
108        #[cfg(feature = "unstable-msc1767")]
109        #[ruma_enum(alias = "m.message")]
110        "org.matrix.msc1767.message" => super::message,
111        #[cfg(feature = "unstable-msc3381")]
112        "m.poll.start" => super::poll::start,
113        #[cfg(feature = "unstable-msc3381")]
114        #[ruma_enum(ident = UnstablePollStart)]
115        "org.matrix.msc3381.poll.start" => super::poll::unstable_start,
116        #[cfg(feature = "unstable-msc3381")]
117        "m.poll.response" => super::poll::response,
118        #[cfg(feature = "unstable-msc3381")]
119        #[ruma_enum(ident = UnstablePollResponse)]
120        "org.matrix.msc3381.poll.response" => super::poll::unstable_response,
121        #[cfg(feature = "unstable-msc3381")]
122        "m.poll.end" => super::poll::end,
123        #[cfg(feature = "unstable-msc3381")]
124        #[ruma_enum(ident = UnstablePollEnd)]
125        "org.matrix.msc3381.poll.end" => super::poll::unstable_end,
126        #[cfg(feature = "unstable-msc3489")]
127        #[ruma_enum(alias = "m.beacon")]
128        "org.matrix.msc3672.beacon" => super::beacon,
129        "m.reaction" => super::reaction,
130        "m.room.encrypted" => super::room::encrypted,
131        "m.room.message" => super::room::message,
132        "m.room.redaction" => super::room::redaction,
133        "m.sticker" => super::sticker,
134        #[cfg(feature = "unstable-msc3553")]
135        #[ruma_enum(alias = "m.video")]
136        "org.matrix.msc1767.video" => super::video,
137        #[cfg(feature = "unstable-msc3245")]
138        #[ruma_enum(alias = "m.voice")]
139        "org.matrix.msc3245.voice.v2" => super::voice,
140        #[cfg(feature = "unstable-msc4075")]
141        #[ruma_enum(alias = "m.call.notify")]
142        "org.matrix.msc4075.call.notify" => super::call::notify,
143        #[cfg(feature = "unstable-msc4310")]
144        #[ruma_enum(alias = "m.rtc.decline")]
145        "org.matrix.msc4310.rtc.decline" => super::rtc::decline,
146    }
147
148    /// Any state event.
149    enum State {
150        "m.policy.rule.room" => super::policy::rule::room,
151        "m.policy.rule.server" => super::policy::rule::server,
152        "m.policy.rule.user" => super::policy::rule::user,
153        "m.room.aliases" => super::room::aliases,
154        "m.room.avatar" => super::room::avatar,
155        "m.room.canonical_alias" => super::room::canonical_alias,
156        "m.room.create" => super::room::create,
157        "m.room.encryption" => super::room::encryption,
158        #[cfg(feature = "unstable-msc3414")]
159        "m.room.encrypted" => super::room::encrypted::unstable_state,
160        "m.room.guest_access" => super::room::guest_access,
161        "m.room.history_visibility" => super::room::history_visibility,
162        "m.room.join_rules" => super::room::join_rules,
163        "m.room.member" => super::room::member,
164        "m.room.name" => super::room::name,
165        "m.room.pinned_events" => super::room::pinned_events,
166        "m.room.power_levels" => super::room::power_levels,
167        "m.room.server_acl" => super::room::server_acl,
168        "m.room.third_party_invite" => super::room::third_party_invite,
169        "m.room.tombstone" => super::room::tombstone,
170        "m.room.topic" => super::room::topic,
171        "m.space.child" => super::space::child,
172        "m.space.parent" => super::space::parent,
173        #[cfg(feature = "unstable-msc2545")]
174        #[ruma_enum(ident = RoomImagePack, alias = "m.image_pack")]
175        "im.ponies.room_emotes" => super::image_pack,
176        #[cfg(feature = "unstable-msc3489")]
177        #[ruma_enum(alias = "m.beacon_info")]
178        "org.matrix.msc3672.beacon_info" => super::beacon_info,
179        #[cfg(feature = "unstable-msc3401")]
180        #[ruma_enum(alias = "m.call.member")]
181        "org.matrix.msc3401.call.member" => super::call::member,
182        #[cfg(feature = "unstable-msc4171")]
183        #[ruma_enum(alias = "m.member_hints")]
184        "io.element.functional_members" => super::member_hints,
185    }
186
187    /// Any to-device event.
188    enum ToDevice {
189        "m.dummy" => super::dummy,
190        "m.room_key" => super::room_key,
191        #[cfg(feature = "unstable-msc4268")]
192        #[ruma_enum(alias = "m.room_key_bundle")]
193        "io.element.msc4268.room_key_bundle" => super::room_key_bundle,
194        "m.room_key_request" => super::room_key_request,
195        "m.room_key.withheld" => super::room_key::withheld,
196        "m.forwarded_room_key" => super::forwarded_room_key,
197        "m.key.verification.request" => super::key::verification::request,
198        "m.key.verification.ready" => super::key::verification::ready,
199        "m.key.verification.start" => super::key::verification::start,
200        "m.key.verification.cancel" => super::key::verification::cancel,
201        "m.key.verification.accept" => super::key::verification::accept,
202        "m.key.verification.key" => super::key::verification::key,
203        "m.key.verification.mac" => super::key::verification::mac,
204        "m.key.verification.done" => super::key::verification::done,
205        "m.room.encrypted" => super::room::encrypted,
206        "m.secret.request"=> super::secret::request,
207        "m.secret.send" => super::secret::send,
208    }
209}
210
211macro_rules! timeline_event_accessors {
212    (
213        $(
214            #[doc = $docs:literal]
215            pub fn $field:ident(&self) -> $ty:ty;
216        )*
217    ) => {
218        $(
219            #[doc = $docs]
220            pub fn $field(&self) -> $ty {
221                match self {
222                    Self::MessageLike(ev) => ev.$field(),
223                    Self::State(ev) => ev.$field(),
224                }
225            }
226        )*
227    };
228}
229
230/// Any room event.
231#[allow(clippy::large_enum_variant, clippy::exhaustive_enums)]
232#[derive(Clone, Debug, EventEnumFromEvent)]
233pub enum AnyTimelineEvent {
234    /// Any message-like event.
235    MessageLike(AnyMessageLikeEvent),
236
237    /// Any state event.
238    State(AnyStateEvent),
239}
240
241impl AnyTimelineEvent {
242    timeline_event_accessors! {
243        /// Returns this event's `origin_server_ts` field.
244        pub fn origin_server_ts(&self) -> MilliSecondsSinceUnixEpoch;
245
246        /// Returns this event's `room_id` field.
247        pub fn room_id(&self) -> &RoomId;
248
249        /// Returns this event's `event_id` field.
250        pub fn event_id(&self) -> &EventId;
251
252        /// Returns this event's `sender` field.
253        pub fn sender(&self) -> &UserId;
254
255        /// Returns this event's `transaction_id` from inside `unsigned`, if there is one.
256        pub fn transaction_id(&self) -> Option<&TransactionId>;
257    }
258
259    /// Returns this event's `type`.
260    pub fn event_type(&self) -> TimelineEventType {
261        match self {
262            Self::MessageLike(e) => e.event_type().into(),
263            Self::State(e) => e.event_type().into(),
264        }
265    }
266}
267
268/// Any sync room event.
269///
270/// Sync room events are room event without a `room_id`, as returned in `/sync` responses.
271#[allow(clippy::large_enum_variant, clippy::exhaustive_enums)]
272#[derive(Clone, Debug, EventEnumFromEvent)]
273pub enum AnySyncTimelineEvent {
274    /// Any sync message-like event.
275    MessageLike(AnySyncMessageLikeEvent),
276
277    /// Any sync state event.
278    State(AnySyncStateEvent),
279}
280
281impl AnySyncTimelineEvent {
282    timeline_event_accessors! {
283        /// Returns this event's `origin_server_ts` field.
284        pub fn origin_server_ts(&self) -> MilliSecondsSinceUnixEpoch;
285
286        /// Returns this event's `event_id` field.
287        pub fn event_id(&self) -> &EventId;
288
289        /// Returns this event's `sender` field.
290        pub fn sender(&self) -> &UserId;
291
292        /// Returns this event's `transaction_id` from inside `unsigned`, if there is one.
293        pub fn transaction_id(&self) -> Option<&TransactionId>;
294    }
295
296    /// Returns this event's `type`.
297    pub fn event_type(&self) -> TimelineEventType {
298        match self {
299            Self::MessageLike(e) => e.event_type().into(),
300            Self::State(e) => e.event_type().into(),
301        }
302    }
303
304    /// Converts `self` to an `AnyTimelineEvent` by adding the given a room ID.
305    pub fn into_full_event(self, room_id: OwnedRoomId) -> AnyTimelineEvent {
306        match self {
307            Self::MessageLike(ev) => AnyTimelineEvent::MessageLike(ev.into_full_event(room_id)),
308            Self::State(ev) => AnyTimelineEvent::State(ev.into_full_event(room_id)),
309        }
310    }
311}
312
313impl From<AnyTimelineEvent> for AnySyncTimelineEvent {
314    fn from(ev: AnyTimelineEvent) -> Self {
315        match ev {
316            AnyTimelineEvent::MessageLike(ev) => Self::MessageLike(ev.into()),
317            AnyTimelineEvent::State(ev) => Self::State(ev.into()),
318        }
319    }
320}
321
322#[derive(Deserialize)]
323#[allow(clippy::exhaustive_structs)]
324struct EventDeHelper {
325    state_key: Option<de::IgnoredAny>,
326}
327
328impl<'de> Deserialize<'de> for AnyTimelineEvent {
329    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
330    where
331        D: de::Deserializer<'de>,
332    {
333        let json = Box::<RawJsonValue>::deserialize(deserializer)?;
334        let EventDeHelper { state_key } = from_raw_json_value(&json)?;
335
336        if state_key.is_some() {
337            Ok(AnyTimelineEvent::State(from_raw_json_value(&json)?))
338        } else {
339            Ok(AnyTimelineEvent::MessageLike(from_raw_json_value(&json)?))
340        }
341    }
342}
343
344impl<'de> Deserialize<'de> for AnySyncTimelineEvent {
345    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
346    where
347        D: de::Deserializer<'de>,
348    {
349        let json = Box::<RawJsonValue>::deserialize(deserializer)?;
350        let EventDeHelper { state_key } = from_raw_json_value(&json)?;
351
352        if state_key.is_some() {
353            Ok(AnySyncTimelineEvent::State(from_raw_json_value(&json)?))
354        } else {
355            Ok(AnySyncTimelineEvent::MessageLike(from_raw_json_value(&json)?))
356        }
357    }
358}
359
360impl AnyMessageLikeEventContent {
361    /// Get a copy of the event's `m.relates_to` field, if any.
362    ///
363    /// This is a helper function intended for encryption. There should not be a reason to access
364    /// `m.relates_to` without first destructuring an `AnyMessageLikeEventContent` otherwise.
365    pub fn relation(&self) -> Option<encrypted::Relation> {
366        #[cfg(feature = "unstable-msc3489")]
367        use super::beacon::BeaconEventContent;
368        use super::key::verification::{
369            accept::KeyVerificationAcceptEventContent, cancel::KeyVerificationCancelEventContent,
370            done::KeyVerificationDoneEventContent, key::KeyVerificationKeyEventContent,
371            mac::KeyVerificationMacEventContent, ready::KeyVerificationReadyEventContent,
372            start::KeyVerificationStartEventContent,
373        };
374        #[cfg(feature = "unstable-msc3381")]
375        use super::poll::{
376            end::PollEndEventContent, response::PollResponseEventContent,
377            unstable_end::UnstablePollEndEventContent,
378            unstable_response::UnstablePollResponseEventContent,
379        };
380
381        match self {
382            #[rustfmt::skip]
383            Self::KeyVerificationReady(KeyVerificationReadyEventContent { relates_to, .. })
384            | Self::KeyVerificationStart(KeyVerificationStartEventContent { relates_to, .. })
385            | Self::KeyVerificationCancel(KeyVerificationCancelEventContent { relates_to, .. })
386            | Self::KeyVerificationAccept(KeyVerificationAcceptEventContent { relates_to, .. })
387            | Self::KeyVerificationKey(KeyVerificationKeyEventContent { relates_to, .. })
388            | Self::KeyVerificationMac(KeyVerificationMacEventContent { relates_to, .. })
389            | Self::KeyVerificationDone(KeyVerificationDoneEventContent { relates_to, .. }) => {
390                Some(encrypted::Relation::Reference(relates_to.clone()))
391            },
392            Self::Reaction(ev) => Some(encrypted::Relation::Annotation(ev.relates_to.clone())),
393            Self::RoomEncrypted(ev) => ev.relates_to.clone(),
394            Self::RoomMessage(ev) => ev.relates_to.clone().map(Into::into),
395            #[cfg(feature = "unstable-msc1767")]
396            Self::Message(ev) => ev.relates_to.clone().map(Into::into),
397            #[cfg(feature = "unstable-msc3954")]
398            Self::Emote(ev) => ev.relates_to.clone().map(Into::into),
399            #[cfg(feature = "unstable-msc3956")]
400            Self::Encrypted(ev) => ev.relates_to.clone(),
401            #[cfg(feature = "unstable-msc3245")]
402            Self::Voice(ev) => ev.relates_to.clone().map(Into::into),
403            #[cfg(feature = "unstable-msc3927")]
404            Self::Audio(ev) => ev.relates_to.clone().map(Into::into),
405            #[cfg(feature = "unstable-msc3488")]
406            Self::Location(ev) => ev.relates_to.clone().map(Into::into),
407            #[cfg(feature = "unstable-msc3551")]
408            Self::File(ev) => ev.relates_to.clone().map(Into::into),
409            #[cfg(feature = "unstable-msc3552")]
410            Self::Image(ev) => ev.relates_to.clone().map(Into::into),
411            #[cfg(feature = "unstable-msc3553")]
412            Self::Video(ev) => ev.relates_to.clone().map(Into::into),
413            #[cfg(feature = "unstable-msc3381")]
414            Self::PollResponse(PollResponseEventContent { relates_to, .. })
415            | Self::UnstablePollResponse(UnstablePollResponseEventContent { relates_to, .. })
416            | Self::PollEnd(PollEndEventContent { relates_to, .. })
417            | Self::UnstablePollEnd(UnstablePollEndEventContent { relates_to, .. }) => {
418                Some(encrypted::Relation::Reference(relates_to.clone()))
419            }
420            #[cfg(feature = "unstable-msc3489")]
421            Self::Beacon(BeaconEventContent { relates_to, .. }) => {
422                Some(encrypted::Relation::Reference(relates_to.clone()))
423            }
424            #[cfg(feature = "unstable-msc3381")]
425            Self::UnstablePollStart(UnstablePollStartEventContent::New(content)) => {
426                content.relates_to.clone().map(Into::into)
427            }
428            #[cfg(feature = "unstable-msc3381")]
429            Self::UnstablePollStart(UnstablePollStartEventContent::Replacement(content)) => {
430                Some(encrypted::Relation::Replacement(Replacement::new(
431                    content.relates_to.event_id.clone(),
432                )))
433            }
434            #[cfg(feature = "unstable-msc3381")]
435            Self::PollStart(PollStartEventContent { relates_to, .. }) => {
436                relates_to.clone().map(Into::into)
437            }
438            #[cfg(feature = "unstable-msc4075")]
439            Self::CallNotify(_) => None,
440            #[cfg(feature = "unstable-msc4310")]
441            Self::RtcDecline(ev) => Some(encrypted::Relation::Reference(ev.relates_to.clone())),
442            Self::CallSdpStreamMetadataChanged(_)
443            | Self::CallNegotiate(_)
444            | Self::CallReject(_)
445            | Self::CallSelectAnswer(_)
446            | Self::CallAnswer(_)
447            | Self::CallInvite(_)
448            | Self::CallHangup(_)
449            | Self::CallCandidates(_)
450            | Self::RoomRedaction(_)
451            | Self::Sticker(_)
452            | Self::_Custom { .. } => None,
453        }
454    }
455}