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