Skip to main content

ruma_events/
unsigned.rs

1#[cfg(feature = "unstable-msc4354")]
2use std::time::Duration;
3
4use js_int::Int;
5use ruma_common::{
6    EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, OwnedUserId, UserId,
7    serde::{CanBeEmpty, Raw},
8};
9use serde::{Deserialize, de::DeserializeOwned};
10
11use super::{
12    MessageLikeEventContent, OriginalSyncMessageLikeEvent, PossiblyRedactedStateEventContent,
13    relation::{BundledMessageLikeRelations, BundledStateRelations},
14    room::redaction::RoomRedactionEventContent,
15};
16use crate::TimelineEventType;
17
18mod redacted_because_serde;
19
20/// Extra information about a message event that is not incorporated into the event's hash.
21#[derive(Clone, Debug, Deserialize)]
22#[serde(bound = "OriginalSyncMessageLikeEvent<C>: DeserializeOwned")]
23#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
24pub struct MessageLikeUnsigned<C: MessageLikeEventContent> {
25    /// The time in milliseconds that has elapsed since the event was sent.
26    ///
27    /// This field is generated by the local homeserver, and may be incorrect if the local time on
28    /// at least one of the two servers is out of sync, which can cause the age to either be
29    /// negative or greater than it actually is.
30    pub age: Option<Int>,
31
32    /// The client-supplied transaction ID, if the client being given the event is the same one
33    /// which sent it.
34    pub transaction_id: Option<OwnedTransactionId>,
35
36    /// [Bundled aggregations] of related child events.
37    ///
38    /// [Bundled aggregations]: https://spec.matrix.org/v1.19/client-server-api/#aggregations-of-child-events
39    #[serde(rename = "m.relations", default)]
40    pub relations: BundledMessageLikeRelations<OriginalSyncMessageLikeEvent<C>>,
41
42    /// Milliseconds remaining until this sticky event expires.
43    ///
44    /// Only present in `/sync` responses for sticky events. See [MSC4354].
45    ///
46    /// [MSC4354]: https://github.com/matrix-org/matrix-spec-proposals/pull/4354
47    #[cfg(feature = "unstable-msc4354")]
48    #[serde(rename = "msc4354_sticky_duration_ttl_ms", default)]
49    #[serde(with = "ruma_common::serde::duration::opt_ms")]
50    pub sticky_duration_ttl_ms: Option<Duration>,
51}
52
53impl<C: MessageLikeEventContent> MessageLikeUnsigned<C> {
54    /// Create a new `Unsigned` with fields set to `None`.
55    pub fn new() -> Self {
56        Self {
57            age: None,
58            transaction_id: None,
59            relations: BundledMessageLikeRelations::default(),
60            #[cfg(feature = "unstable-msc4354")]
61            sticky_duration_ttl_ms: None,
62        }
63    }
64}
65
66impl<C: MessageLikeEventContent> Default for MessageLikeUnsigned<C> {
67    fn default() -> Self {
68        Self::new()
69    }
70}
71
72impl<C: MessageLikeEventContent> CanBeEmpty for MessageLikeUnsigned<C> {
73    /// Whether this unsigned data is empty (all fields are `None`).
74    ///
75    /// This method is used to determine whether to skip serializing the `unsigned` field in room
76    /// events. Do not use it to determine whether an incoming `unsigned` field was present - it
77    /// could still have been present but contained none of the known fields.
78    fn is_empty(&self) -> bool {
79        let empty =
80            self.age.is_none() && self.transaction_id.is_none() && self.relations.is_empty();
81        #[cfg(feature = "unstable-msc4354")]
82        let empty = empty && self.sticky_duration_ttl_ms.is_none();
83        empty
84    }
85}
86
87/// Extra information about a state event that is not incorporated into the event's hash.
88#[derive(Clone, Debug, Deserialize)]
89#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
90pub struct StateUnsigned<C: PossiblyRedactedStateEventContent> {
91    /// The time in milliseconds that has elapsed since the event was sent.
92    ///
93    /// This field is generated by the local homeserver, and may be incorrect if the local time on
94    /// at least one of the two servers is out of sync, which can cause the age to either be
95    /// negative or greater than it actually is.
96    pub age: Option<Int>,
97
98    /// The client-supplied transaction ID, if the client being given the event is the same one
99    /// which sent it.
100    pub transaction_id: Option<OwnedTransactionId>,
101
102    /// The event ID of the state event replaced by this event.
103    ///
104    /// This field is generated by the local homeserver. Unlike `prev_content`, it is included
105    /// regardless of history visibility.
106    pub replaces_state: Option<OwnedEventId>,
107
108    /// Optional previous content of the event.
109    pub prev_content: Option<C>,
110
111    /// The user ID of the sender of the state event replaced by this event.
112    ///
113    /// This field is generated by the local homeserver. Unlike `prev_content`, it is included
114    /// regardless of history visibility.
115    pub prev_sender: Option<OwnedUserId>,
116
117    /// [Bundled aggregations] of related child events.
118    ///
119    /// [Bundled aggregations]: https://spec.matrix.org/v1.19/client-server-api/#aggregations-of-child-events
120    #[serde(rename = "m.relations", default)]
121    pub relations: BundledStateRelations,
122
123    /// Milliseconds remaining until this sticky event expires.
124    ///
125    /// Only present in `/sync` responses for sticky events. See [MSC4354].
126    ///
127    /// [MSC4354]: https://github.com/matrix-org/matrix-spec-proposals/pull/4354
128    #[cfg(feature = "unstable-msc4354")]
129    #[serde(rename = "msc4354_sticky_duration_ttl_ms", default)]
130    #[serde(with = "ruma_common::serde::duration::opt_ms")]
131    pub sticky_duration_ttl_ms: Option<Duration>,
132}
133
134impl<C: PossiblyRedactedStateEventContent> StateUnsigned<C> {
135    /// Create a new `Unsigned` with fields set to `None`.
136    pub fn new() -> Self {
137        Self {
138            age: None,
139            transaction_id: None,
140            replaces_state: None,
141            prev_content: None,
142            prev_sender: None,
143            relations: Default::default(),
144            #[cfg(feature = "unstable-msc4354")]
145            sticky_duration_ttl_ms: None,
146        }
147    }
148}
149
150impl<C: PossiblyRedactedStateEventContent> CanBeEmpty for StateUnsigned<C> {
151    /// Whether this unsigned data is empty (all fields are `None`).
152    ///
153    /// This method is used to determine whether to skip serializing the `unsigned` field in room
154    /// events. Do not use it to determine whether an incoming `unsigned` field was present - it
155    /// could still have been present but contained none of the known fields.
156    fn is_empty(&self) -> bool {
157        let Self {
158            age,
159            transaction_id,
160            replaces_state,
161            prev_content,
162            prev_sender,
163            relations,
164            #[cfg(feature = "unstable-msc4354")]
165            sticky_duration_ttl_ms,
166        } = self;
167
168        let empty = age.is_none()
169            && transaction_id.is_none()
170            && replaces_state.is_none()
171            && prev_content.is_none()
172            && prev_sender.is_none()
173            && relations.is_empty();
174        #[cfg(feature = "unstable-msc4354")]
175        let empty = empty && sticky_duration_ttl_ms.is_none();
176        empty
177    }
178}
179
180impl<C: PossiblyRedactedStateEventContent> Default for StateUnsigned<C> {
181    fn default() -> Self {
182        Self::new()
183    }
184}
185
186/// Extra information about a redacted event that is not incorporated into the event's hash.
187#[derive(Clone, Debug, Deserialize)]
188#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
189pub struct RedactedUnsigned {
190    /// The event that redacted this event, if any.
191    pub redacted_because: Raw<AnyRedactionEvent>,
192}
193
194impl RedactedUnsigned {
195    /// Create a new `RedactedUnsigned` with the given redaction event.
196    pub fn new(redacted_because: Raw<AnyRedactionEvent>) -> Self {
197        Self { redacted_because }
198    }
199}
200
201/// Any event that can redact another event, i.e. an event that can be found in
202/// `unsigned.redacted_because`.
203#[derive(Clone, Debug)]
204#[non_exhaustive]
205#[allow(clippy::large_enum_variant)]
206pub enum AnyRedactionEvent {
207    /// m.room.redaction
208    RoomRedaction(UnsignedRoomRedactionEvent),
209
210    /// m.room.member
211    #[cfg(feature = "unstable-msc4293")]
212    RoomMember(super::room::member::SyncRoomMemberEvent),
213
214    #[doc(hidden)]
215    _Custom(CustomRedactionEvent),
216}
217
218impl AnyRedactionEvent {
219    /// Returns the `type` of this event.
220    pub fn event_type(&self) -> TimelineEventType {
221        match self {
222            Self::RoomRedaction(_) => TimelineEventType::RoomRedaction,
223            #[cfg(feature = "unstable-msc4293")]
224            Self::RoomMember(_) => TimelineEventType::RoomMember,
225            Self::_Custom(e) => TimelineEventType::from(&*e.event_type),
226        }
227    }
228
229    /// Returns the `origin_server_ts` of this event.
230    pub fn origin_server_ts(&self) -> MilliSecondsSinceUnixEpoch {
231        match self {
232            Self::RoomRedaction(e) => e.origin_server_ts,
233            #[cfg(feature = "unstable-msc4293")]
234            Self::RoomMember(e) => e.origin_server_ts(),
235            Self::_Custom(e) => e.origin_server_ts,
236        }
237    }
238
239    /// Returns the `event_id` of this event.
240    pub fn event_id(&self) -> &EventId {
241        match self {
242            Self::RoomRedaction(e) => &e.event_id,
243            #[cfg(feature = "unstable-msc4293")]
244            Self::RoomMember(e) => e.event_id(),
245            Self::_Custom(e) => &e.event_id,
246        }
247    }
248
249    /// Returns the `sender` of this event.
250    pub fn sender(&self) -> &UserId {
251        match self {
252            Self::RoomRedaction(e) => &e.sender,
253            #[cfg(feature = "unstable-msc4293")]
254            Self::RoomMember(e) => e.sender(),
255            Self::_Custom(e) => &e.sender,
256        }
257    }
258}
259
260/// An `m.room.redaction` event as found in `unsigned.redacted_because`.
261///
262/// While servers usually send this with the `redacts` field (unless nested), the ID of the event
263/// being redacted is known from context wherever this type is used, so it's not reflected as a
264/// field here.
265///
266/// It is intentionally not possible to create an instance of this type other than through `Clone`
267/// or `Deserialize`.
268#[derive(Clone, Debug, Deserialize)]
269#[non_exhaustive]
270pub struct UnsignedRoomRedactionEvent {
271    /// Data specific to the event type.
272    pub content: RoomRedactionEventContent,
273
274    /// The globally unique event identifier for the user who sent the event.
275    pub event_id: OwnedEventId,
276
277    /// The fully-qualified ID of the user who sent this event.
278    pub sender: OwnedUserId,
279
280    /// Timestamp in milliseconds on originating homeserver when this event was sent.
281    pub origin_server_ts: MilliSecondsSinceUnixEpoch,
282
283    /// Additional key-value pairs not signed by the homeserver.
284    #[serde(default)]
285    pub unsigned: MessageLikeUnsigned<RoomRedactionEventContent>,
286}
287
288/// A custom redaction event.
289#[doc(hidden)]
290#[derive(Clone, Debug)]
291pub struct CustomRedactionEvent {
292    /// The type of the event
293    event_type: Box<str>,
294
295    /// The globally unique event identifier for the user who sent the event.
296    event_id: OwnedEventId,
297
298    /// The fully-qualified ID of the user who sent this event.
299    sender: OwnedUserId,
300
301    /// Timestamp in milliseconds on originating homeserver when this event was sent.
302    origin_server_ts: MilliSecondsSinceUnixEpoch,
303}
304
305#[cfg(test)]
306mod tests {
307    use assert_matches::assert_matches;
308    use js_int::uint;
309    use serde_json::{from_value as from_json_value, json};
310
311    use super::AnyRedactionEvent;
312    use crate::TimelineEventType;
313
314    #[test]
315    fn deserialize_any_redaction_event_room_redaction() {
316        let json = json!({
317            "type": "m.room.redaction",
318            "content": {
319                "redacts": "$redactedevent",
320            },
321            "event_id": "$redactionevent",
322            "origin_server_ts": 1,
323            "sender": "@carl:example.com",
324        });
325
326        let event = from_json_value::<AnyRedactionEvent>(json).unwrap();
327        assert_eq!(event.event_id(), "$redactionevent");
328        assert_eq!(event.origin_server_ts().0, uint!(1));
329        assert_eq!(event.sender(), "@carl:example.com");
330        assert_eq!(event.event_type(), TimelineEventType::RoomRedaction);
331        assert_matches!(event, AnyRedactionEvent::RoomRedaction(_));
332    }
333
334    #[test]
335    fn deserialize_any_redaction_event_custom() {
336        let json = json!({
337            "type": "local.dev.custom_type",
338            "content": {},
339            "event_id": "$redactionevent",
340            "origin_server_ts": 1,
341            "sender": "@carl:example.com",
342        });
343
344        let event = from_json_value::<AnyRedactionEvent>(json).unwrap();
345        assert_eq!(event.event_id(), "$redactionevent");
346        assert_eq!(event.origin_server_ts().0, uint!(1));
347        assert_eq!(event.sender(), "@carl:example.com");
348        assert_eq!(event.event_type().to_string(), "local.dev.custom_type");
349    }
350}