matrix-sdk-common 0.16.1

Collection of common types and imports used in the matrix-sdk
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// Copyright 2025 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A collection of serde helpers to avoid having to deserialize an entire event
//! to access some fields.

use ruma::{
    MilliSecondsSinceUnixEpoch, OwnedEventId,
    events::{
        AnyMessageLikeEventContent, AnySyncMessageLikeEvent, AnySyncTimelineEvent,
        relation::BundledThread,
    },
    serde::Raw,
};
use serde::Deserialize;

use crate::deserialized_responses::{ThreadSummary, ThreadSummaryStatus};

#[derive(Deserialize)]
enum RelationsType {
    #[serde(rename = "m.thread")]
    Thread,
    #[serde(rename = "m.replace")]
    Edit,
}

#[derive(Deserialize)]
struct RelatesTo {
    #[serde(rename = "rel_type")]
    rel_type: RelationsType,
    #[serde(rename = "event_id")]
    event_id: Option<OwnedEventId>,
}

#[allow(missing_debug_implementations)]
#[derive(Deserialize)]
struct SimplifiedContent {
    #[serde(rename = "m.relates_to")]
    relates_to: Option<RelatesTo>,
}

/// Try to extract the thread root from an event's content, if provided.
///
/// The thread root is the field located at `m.relates_to`.`event_id`,
/// if the field at `m.relates_to`.`rel_type` is `m.thread`.
///
/// Returns `None` if we couldn't find a thread root, or if there was an issue
/// during deserialization.
pub fn extract_thread_root_from_content(
    content: Raw<AnyMessageLikeEventContent>,
) -> Option<OwnedEventId> {
    let relates_to = content.deserialize_as_unchecked::<SimplifiedContent>().ok()?.relates_to?;
    match relates_to.rel_type {
        RelationsType::Thread => relates_to.event_id,
        RelationsType::Edit => None,
    }
}

/// Try to extract the thread root from a timeline event, if provided.
///
/// The thread root is the field located at `content`.`m.relates_to`.`event_id`,
/// if the field at `content`.`m.relates_to`.`rel_type` is `m.thread`.
///
/// Returns `None` if we couldn't find a thread root, or if there was an issue
/// during deserialization.
pub fn extract_thread_root(event: &Raw<AnySyncTimelineEvent>) -> Option<OwnedEventId> {
    extract_thread_root_from_content(event.get_field("content").ok().flatten()?)
}

/// Try to extract the target of an edit event, from a raw timeline event, if
/// provided.
///
/// The target event is the field located at
/// `content`.`m.relates_to`.`event_id`, if the field at
/// `content`.`m.relates_to`.`rel_type` is `m.replace`.
///
/// Returns `None` if we couldn't find it, or if there was an issue
/// during deserialization.
pub fn extract_edit_target(event: &Raw<AnySyncTimelineEvent>) -> Option<OwnedEventId> {
    let relates_to = event.get_field::<SimplifiedContent>("content").ok().flatten()?.relates_to?;
    match relates_to.rel_type {
        RelationsType::Edit => relates_to.event_id,
        RelationsType::Thread => None,
    }
}

#[allow(missing_debug_implementations)]
#[derive(Deserialize)]
struct Relations {
    #[serde(rename = "m.thread")]
    thread: Option<Box<BundledThread>>,
}

#[allow(missing_debug_implementations)]
#[derive(Deserialize)]
struct Unsigned {
    #[serde(rename = "m.relations")]
    relations: Option<Relations>,
}

/// Try to extract a bundled thread summary of a timeline event, if available.
pub fn extract_bundled_thread_summary(
    event: &Raw<AnySyncTimelineEvent>,
) -> (ThreadSummaryStatus, Option<Raw<AnySyncMessageLikeEvent>>) {
    match event.get_field::<Unsigned>("unsigned") {
        Ok(Some(Unsigned { relations: Some(Relations { thread: Some(bundled_thread) }) })) => {
            // Take the count from the bundled thread summary, if available. If it can't be
            // converted to a `u32`, we use `u32::MAX` as a fallback, as this is unlikely
            // to happen to have that many events in real-world threads.
            let count = bundled_thread.count.try_into().unwrap_or(u32::MAX);

            let latest_reply =
                bundled_thread.latest_event.get_field::<OwnedEventId>("event_id").ok().flatten();

            (
                ThreadSummaryStatus::Some(ThreadSummary { num_replies: count, latest_reply }),
                Some(bundled_thread.latest_event),
            )
        }
        Ok(_) => (ThreadSummaryStatus::None, None),
        Err(_) => (ThreadSummaryStatus::Unknown, None),
    }
}

/// Try to extract the `origin_server_ts`, if available.
///
/// If the value is larger than `max_value`, it becomes `max_value`. This is
/// necessary to prevent against user-forged value pretending an event is coming
/// from the future.
pub fn extract_timestamp(
    event: &Raw<AnySyncTimelineEvent>,
    max_value: MilliSecondsSinceUnixEpoch,
) -> Option<MilliSecondsSinceUnixEpoch> {
    let mut origin_server_ts = event.get_field("origin_server_ts").ok().flatten()?;

    if origin_server_ts > max_value {
        origin_server_ts = max_value;
    }

    Some(origin_server_ts)
}

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;
    use ruma::{UInt, event_id};
    use serde_json::json;

    use super::{
        MilliSecondsSinceUnixEpoch, Raw, extract_bundled_thread_summary, extract_thread_root,
        extract_timestamp,
    };
    use crate::deserialized_responses::{ThreadSummary, ThreadSummaryStatus};

    #[test]
    fn test_extract_thread_root() {
        // No event factory in this crate :( There would be a dependency cycle with the
        // `matrix-sdk-test` crate if we tried to use it here.

        // We can extract the thread root from a regular message that contains one.
        let thread_root = event_id!("$thread_root_event_id:example.com");
        let event = Raw::new(&json!({
            "event_id": "$eid:example.com",
            "type": "m.room.message",
            "sender": "@alice:example.com",
            "origin_server_ts": 42,
            "content": {
                "body": "Hello, world!",
                "m.relates_to": {
                    "rel_type": "m.thread",
                    "event_id": thread_root,
                }
            }
        }))
        .unwrap()
        .cast_unchecked();

        let observed_thread_root = extract_thread_root(&event);
        assert_eq!(observed_thread_root.as_deref(), Some(thread_root));

        // If the event doesn't have a content for some reason (redacted), it returns
        // None.
        let event = Raw::new(&json!({
            "event_id": "$eid:example.com",
            "type": "m.room.message",
            "sender": "@alice:example.com",
            "origin_server_ts": 42,
        }))
        .unwrap()
        .cast_unchecked();

        let observed_thread_root = extract_thread_root(&event);
        assert_matches!(observed_thread_root, None);

        // If the event has a content but with no `m.relates_to` field, it returns None.
        let event = Raw::new(&json!({
            "event_id": "$eid:example.com",
            "type": "m.room.message",
            "sender": "@alice:example.com",
            "origin_server_ts": 42,
            "content": {
                "body": "Hello, world!",
            }
        }))
        .unwrap()
        .cast_unchecked();

        let observed_thread_root = extract_thread_root(&event);
        assert_matches!(observed_thread_root, None);

        // If the event has a relation, but it's not a thread reply, it returns None.
        let event = Raw::new(&json!({
            "event_id": "$eid:example.com",
            "type": "m.room.message",
            "sender": "@alice:example.com",
            "origin_server_ts": 42,
            "content": {
                "body": "Hello, world!",
                "m.relates_to": {
                    "rel_type": "m.reference",
                    "event_id": "$referenced_event_id:example.com",
                }
            }
        }))
        .unwrap()
        .cast_unchecked();

        let observed_thread_root = extract_thread_root(&event);
        assert_matches!(observed_thread_root, None);
    }

    #[test]
    fn test_extract_bundled_thread_summary() {
        // When there's a bundled thread summary, we can extract it.
        let event = Raw::new(&json!({
            "event_id": "$eid:example.com",
            "type": "m.room.message",
            "sender": "@alice:example.com",
            "origin_server_ts": 42,
            "content": {
                "body": "Hello, world!",
            },
            "unsigned": {
                "m.relations": {
                    "m.thread": {
                        "latest_event": {
                            "event_id": "$latest_event:example.com",
                            "type": "m.room.message",
                            "sender": "@bob:example.com",
                            "origin_server_ts": 42,
                            "content": {
                                "body": "Hello to you too!",
                            }
                        },
                        "count": 2,
                        "current_user_participated": true,
                    }
                }
            }
        }))
        .unwrap()
        .cast_unchecked();

        assert_matches!(
            extract_bundled_thread_summary(&event),
            (ThreadSummaryStatus::Some(ThreadSummary { .. }), Some(..))
        );

        // When there's a bundled thread summary, we can assert it with certainty.
        let event = Raw::new(&json!({
            "event_id": "$eid:example.com",
            "type": "m.room.message",
            "sender": "@alice:example.com",
            "origin_server_ts": 42,
        }))
        .unwrap()
        .cast_unchecked();

        assert_matches!(extract_bundled_thread_summary(&event), (ThreadSummaryStatus::None, None));

        // When there's a bundled replace, we can assert there's no thread summary.
        let event = Raw::new(&json!({
            "event_id": "$eid:example.com",
            "type": "m.room.message",
            "sender": "@alice:example.com",
            "origin_server_ts": 42,
            "content": {
                "body": "Bonjour, monde!",
            },
            "unsigned": {
                "m.relations": {
                    "m.replace":
                    {
                        "event_id": "$update:example.com",
                        "type": "m.room.message",
                        "sender": "@alice:example.com",
                        "origin_server_ts": 43,
                        "content": {
                            "body": "* Hello, world!",
                        }
                    },
                }
            }
        }))
        .unwrap()
        .cast_unchecked();

        assert_matches!(extract_bundled_thread_summary(&event), (ThreadSummaryStatus::None, None));

        // When the bundled thread summary is malformed, we return
        // `ThreadSummaryStatus::Unknown`.
        let event = Raw::new(&json!({
            "event_id": "$eid:example.com",
            "type": "m.room.message",
            "sender": "@alice:example.com",
            "origin_server_ts": 42,
            "unsigned": {
                "m.relations": {
                    "m.thread": {
                        // Missing `latest_event` field.
                    }
                }
            }
        }))
        .unwrap()
        .cast_unchecked();

        assert_matches!(
            extract_bundled_thread_summary(&event),
            (ThreadSummaryStatus::Unknown, None)
        );
    }

    #[test]
    fn test_extract_timestamp() {
        let event = Raw::new(&json!({
            "event_id": "$ev0",
            "type": "m.room.message",
            "sender": "@mnt_io:matrix.org",
            "origin_server_ts": 42,
            "content": {
                "body": "Le gras, c'est la vie",
            }
        }))
        .unwrap()
        .cast_unchecked();

        let timestamp = extract_timestamp(&event, MilliSecondsSinceUnixEpoch(UInt::from(100u32)));

        assert_eq!(timestamp, Some(MilliSecondsSinceUnixEpoch(UInt::from(42u32))));
    }

    #[test]
    fn test_extract_timestamp_no_origin_server_ts() {
        let event = Raw::new(&json!({
            "event_id": "$ev0",
            "type": "m.room.message",
            "sender": "@mnt_io:matrix.org",
            "content": {
                "body": "Le gras, c'est la vie",
            }
        }))
        .unwrap()
        .cast_unchecked();

        let timestamp = extract_timestamp(&event, MilliSecondsSinceUnixEpoch(UInt::from(100u32)));

        assert!(timestamp.is_none());
    }

    #[test]
    fn test_extract_timestamp_invalid_origin_server_ts() {
        let event = Raw::new(&json!({
            "event_id": "$ev0",
            "type": "m.room.message",
            "sender": "@mnt_io:matrix.org",
            "origin_server_ts": "saucisse",
            "content": {
                "body": "Le gras, c'est la vie",
            }
        }))
        .unwrap()
        .cast_unchecked();

        let timestamp = extract_timestamp(&event, MilliSecondsSinceUnixEpoch(UInt::from(100u32)));

        assert!(timestamp.is_none());
    }

    #[test]
    fn test_extract_timestamp_malicious_origin_server_ts() {
        let event = Raw::new(&json!({
            "event_id": "$ev0",
            "type": "m.room.message",
            "sender": "@mnt_io:matrix.org",
            "origin_server_ts": 101,
            "content": {
                "body": "Le gras, c'est la vie",
            }
        }))
        .unwrap()
        .cast_unchecked();

        let timestamp = extract_timestamp(&event, MilliSecondsSinceUnixEpoch(UInt::from(100u32)));

        assert_eq!(timestamp, Some(MilliSecondsSinceUnixEpoch(UInt::from(100u32))));
    }
}