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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Utilities for working with events to decide whether they are suitable for
//! use as a [crate::Room::latest_event].

#![cfg(any(feature = "e2e-encryption", feature = "experimental-sliding-sync"))]

use matrix_sdk_common::deserialized_responses::SyncTimelineEvent;
#[cfg(feature = "e2e-encryption")]
use ruma::events::{
    call::{invite::SyncCallInviteEvent, notify::SyncCallNotifyEvent},
    poll::unstable_start::SyncUnstablePollStartEvent,
    relation::RelationType,
    room::message::SyncRoomMessageEvent,
    AnySyncMessageLikeEvent, AnySyncTimelineEvent,
};
use ruma::{events::sticker::SyncStickerEvent, MxcUri, OwnedEventId};
use serde::{Deserialize, Serialize};

use crate::MinimalRoomMemberEvent;

/// Represents a decision about whether an event could be stored as the latest
/// event in a room. Variants starting with Yes indicate that this message could
/// be stored, and provide the inner event information, and those starting with
/// a No indicate that it could not, and give a reason.
#[cfg(feature = "e2e-encryption")]
#[derive(Debug)]
pub enum PossibleLatestEvent<'a> {
    /// This message is suitable - it is an m.room.message
    YesRoomMessage(&'a SyncRoomMessageEvent),
    /// This message is suitable - it is a sticker
    YesSticker(&'a SyncStickerEvent),
    /// This message is suitable - it is a poll
    YesPoll(&'a SyncUnstablePollStartEvent),

    /// This message is suitable - it is a call invite
    YesCallInvite(&'a SyncCallInviteEvent),

    /// This message is suitable - it's a call notification
    YesCallNotify(&'a SyncCallNotifyEvent),

    // Later: YesState(),
    // Later: YesReaction(),
    /// Not suitable - it's a state event
    NoUnsupportedEventType,
    /// Not suitable - it's not a m.room.message or an edit/replacement
    NoUnsupportedMessageLikeType,
    /// Not suitable - it's encrypted
    NoEncrypted,
}

/// Decide whether an event could be stored as the latest event in a room.
/// Returns a LatestEvent representing our decision.
#[cfg(feature = "e2e-encryption")]
pub fn is_suitable_for_latest_event(event: &AnySyncTimelineEvent) -> PossibleLatestEvent<'_> {
    match event {
        // Suitable - we have an m.room.message that was not redacted or edited
        AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(message)) => {
            // Check if this is a replacement for another message. If it is, ignore it
            if let Some(original_message) = message.as_original() {
                let is_replacement =
                    original_message.content.relates_to.as_ref().map_or(false, |relates_to| {
                        if let Some(relation_type) = relates_to.rel_type() {
                            relation_type == RelationType::Replacement
                        } else {
                            false
                        }
                    });

                if is_replacement {
                    return PossibleLatestEvent::NoUnsupportedMessageLikeType;
                } else {
                    return PossibleLatestEvent::YesRoomMessage(message);
                }
            }

            return PossibleLatestEvent::YesRoomMessage(message);
        }

        AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::UnstablePollStart(poll)) => {
            PossibleLatestEvent::YesPoll(poll)
        }

        AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::CallInvite(invite)) => {
            PossibleLatestEvent::YesCallInvite(invite)
        }

        AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::CallNotify(notify)) => {
            PossibleLatestEvent::YesCallNotify(notify)
        }

        AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::Sticker(sticker)) => {
            PossibleLatestEvent::YesSticker(sticker)
        }

        // Encrypted events are not suitable
        AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomEncrypted(_)) => {
            PossibleLatestEvent::NoEncrypted
        }

        // Later, if we support reactions:
        // AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::Reaction(_))

        // MessageLike, but not one of the types we want to show in message previews, so not
        // suitable
        AnySyncTimelineEvent::MessageLike(_) => PossibleLatestEvent::NoUnsupportedMessageLikeType,

        // We don't currently support state events
        AnySyncTimelineEvent::State(_) => PossibleLatestEvent::NoUnsupportedEventType,
    }
}

/// Represent all information required to represent a latest event in an
/// efficient way.
///
/// ## Implementation details
///
/// Serialization and deserialization should be a breeze, but we introduced a
/// change in the format without realizing, and without a migration. Ideally,
/// this would be handled with a `serde(untagged)` enum that would be used to
/// deserialize in either the older format, or to the new format. Unfortunately,
/// untagged enums don't play nicely with `serde_json::value::RawValue`,
/// so we did have to implement a custom `Deserialize` for `LatestEvent`, that
/// first deserializes the thing as a raw JSON value, and then deserializes the
/// JSON string as one variant or the other.
///
/// Because of that, `LatestEvent` should only be (de)serialized using
/// serde_json.
///
/// Whenever you introduce new fields to `LatestEvent` make sure to add them to
/// `SerializedLatestEvent` too.
#[derive(Clone, Debug, Serialize)]
pub struct LatestEvent {
    /// The actual event.
    event: SyncTimelineEvent,

    /// The member profile of the event' sender.
    #[serde(skip_serializing_if = "Option::is_none")]
    sender_profile: Option<MinimalRoomMemberEvent>,

    /// The name of the event' sender is ambiguous.
    #[serde(skip_serializing_if = "Option::is_none")]
    sender_name_is_ambiguous: Option<bool>,
}

#[derive(Deserialize)]
struct SerializedLatestEvent {
    /// The actual event.
    event: SyncTimelineEvent,

    /// The member profile of the event' sender.
    #[serde(skip_serializing_if = "Option::is_none")]
    sender_profile: Option<MinimalRoomMemberEvent>,

    /// The name of the event' sender is ambiguous.
    #[serde(skip_serializing_if = "Option::is_none")]
    sender_name_is_ambiguous: Option<bool>,
}

// Note: this deserialize implementation for LatestEvent will *only* work with
// serde_json.
impl<'de> Deserialize<'de> for LatestEvent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let raw: Box<serde_json::value::RawValue> = Box::deserialize(deserializer)?;

        let mut variant_errors = Vec::new();

        match serde_json::from_str::<SerializedLatestEvent>(raw.get()) {
            Ok(value) => {
                return Ok(LatestEvent {
                    event: value.event,
                    sender_profile: value.sender_profile,
                    sender_name_is_ambiguous: value.sender_name_is_ambiguous,
                });
            }
            Err(err) => variant_errors.push(err),
        }

        match serde_json::from_str::<SyncTimelineEvent>(raw.get()) {
            Ok(value) => {
                return Ok(LatestEvent {
                    event: value,
                    sender_profile: None,
                    sender_name_is_ambiguous: None,
                });
            }
            Err(err) => variant_errors.push(err),
        }

        Err(serde::de::Error::custom(
            format!("data did not match any variant of serialized LatestEvent (using serde_json). Observed errors: {variant_errors:?}")
        ))
    }
}

impl LatestEvent {
    /// Create a new [`LatestEvent`] without the sender's profile.
    pub fn new(event: SyncTimelineEvent) -> Self {
        Self { event, sender_profile: None, sender_name_is_ambiguous: None }
    }

    /// Create a new [`LatestEvent`] with maybe the sender's profile.
    pub fn new_with_sender_details(
        event: SyncTimelineEvent,
        sender_profile: Option<MinimalRoomMemberEvent>,
        sender_name_is_ambiguous: Option<bool>,
    ) -> Self {
        Self { event, sender_profile, sender_name_is_ambiguous }
    }

    /// Transform [`Self`] into an event.
    pub fn into_event(self) -> SyncTimelineEvent {
        self.event
    }

    /// Get a reference to the event.
    pub fn event(&self) -> &SyncTimelineEvent {
        &self.event
    }

    /// Get a mutable reference to the event.
    pub fn event_mut(&mut self) -> &mut SyncTimelineEvent {
        &mut self.event
    }

    /// Get the event ID.
    pub fn event_id(&self) -> Option<OwnedEventId> {
        self.event.event_id()
    }

    /// Check whether [`Self`] has a sender profile.
    pub fn has_sender_profile(&self) -> bool {
        self.sender_profile.is_some()
    }

    /// Return the sender's display name if it was known at the time [`Self`]
    /// was built.
    pub fn sender_display_name(&self) -> Option<&str> {
        self.sender_profile.as_ref().and_then(|profile| {
            profile.as_original().and_then(|event| event.content.displayname.as_deref())
        })
    }

    /// Return `Some(true)` if the sender's name is ambiguous, `Some(false)` if
    /// it isn't, `None` if ambiguity detection wasn't possible at the time
    /// [`Self`] was built.
    pub fn sender_name_ambiguous(&self) -> Option<bool> {
        self.sender_name_is_ambiguous
    }

    /// Return the sender's avatar URL if it was known at the time [`Self`] was
    /// built.
    pub fn sender_avatar_url(&self) -> Option<&MxcUri> {
        self.sender_profile.as_ref().and_then(|profile| {
            profile.as_original().and_then(|event| event.content.avatar_url.as_deref())
        })
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use assert_matches::assert_matches;
    use assert_matches2::assert_let;
    use matrix_sdk_common::deserialized_responses::SyncTimelineEvent;
    use ruma::{
        events::{
            call::{
                invite::{CallInviteEventContent, SyncCallInviteEvent},
                notify::{
                    ApplicationType, CallNotifyEventContent, NotifyType, SyncCallNotifyEvent,
                },
                SessionDescription,
            },
            poll::{
                unstable_response::{
                    SyncUnstablePollResponseEvent, UnstablePollResponseEventContent,
                },
                unstable_start::{
                    NewUnstablePollStartEventContent, SyncUnstablePollStartEvent,
                    UnstablePollAnswer, UnstablePollStartContentBlock,
                },
            },
            relation::Replacement,
            room::{
                encrypted::{
                    EncryptedEventScheme, OlmV1Curve25519AesSha2Content, RoomEncryptedEventContent,
                    SyncRoomEncryptedEvent,
                },
                message::{
                    ImageMessageEventContent, MessageType, RedactedRoomMessageEventContent,
                    Relation, RoomMessageEventContent, SyncRoomMessageEvent,
                },
                topic::{RoomTopicEventContent, SyncRoomTopicEvent},
                ImageInfo, MediaSource,
            },
            sticker::{StickerEventContent, SyncStickerEvent},
            AnySyncMessageLikeEvent, AnySyncStateEvent, AnySyncTimelineEvent, EmptyStateKey,
            Mentions, MessageLikeUnsigned, OriginalSyncMessageLikeEvent, OriginalSyncStateEvent,
            RedactedSyncMessageLikeEvent, RedactedUnsigned, StateUnsigned, SyncMessageLikeEvent,
            UnsignedRoomRedactionEvent,
        },
        owned_event_id, owned_mxc_uri, owned_user_id,
        serde::Raw,
        MilliSecondsSinceUnixEpoch, UInt, VoipVersionId,
    };
    use serde_json::json;

    use crate::latest_event::{is_suitable_for_latest_event, LatestEvent, PossibleLatestEvent};

    #[test]
    fn test_room_messages_are_suitable() {
        let event = AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(
            SyncRoomMessageEvent::Original(OriginalSyncMessageLikeEvent {
                content: RoomMessageEventContent::new(MessageType::Image(
                    ImageMessageEventContent::new(
                        "".to_owned(),
                        MediaSource::Plain(owned_mxc_uri!("mxc://example.com/1")),
                    ),
                )),
                event_id: owned_event_id!("$1"),
                sender: owned_user_id!("@a:b.c"),
                origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
                unsigned: MessageLikeUnsigned::new(),
            }),
        ));
        assert_let!(
            PossibleLatestEvent::YesRoomMessage(SyncMessageLikeEvent::Original(m)) =
                is_suitable_for_latest_event(&event)
        );

        assert_eq!(m.content.msgtype.msgtype(), "m.image");
    }

    #[test]
    fn test_polls_are_suitable() {
        let event = AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::UnstablePollStart(
            SyncUnstablePollStartEvent::Original(OriginalSyncMessageLikeEvent {
                content: NewUnstablePollStartEventContent::new(UnstablePollStartContentBlock::new(
                    "do you like rust?",
                    vec![UnstablePollAnswer::new("id", "yes")].try_into().unwrap(),
                ))
                .into(),
                event_id: owned_event_id!("$1"),
                sender: owned_user_id!("@a:b.c"),
                origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
                unsigned: MessageLikeUnsigned::new(),
            }),
        ));
        assert_let!(
            PossibleLatestEvent::YesPoll(SyncMessageLikeEvent::Original(m)) =
                is_suitable_for_latest_event(&event)
        );

        assert_eq!(m.content.poll_start().question.text, "do you like rust?");
    }

    #[test]
    fn test_call_invites_are_suitable() {
        let event = AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::CallInvite(
            SyncCallInviteEvent::Original(OriginalSyncMessageLikeEvent {
                content: CallInviteEventContent::new(
                    "call_id".into(),
                    UInt::new(123).unwrap(),
                    SessionDescription::new("".into(), "".into()),
                    VoipVersionId::V1,
                ),
                event_id: owned_event_id!("$1"),
                sender: owned_user_id!("@a:b.c"),
                origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
                unsigned: MessageLikeUnsigned::new(),
            }),
        ));
        assert_let!(
            PossibleLatestEvent::YesCallInvite(SyncMessageLikeEvent::Original(_)) =
                is_suitable_for_latest_event(&event)
        );
    }

    #[test]
    fn test_call_notifications_are_suitable() {
        let event = AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::CallNotify(
            SyncCallNotifyEvent::Original(OriginalSyncMessageLikeEvent {
                content: CallNotifyEventContent::new(
                    "call_id".into(),
                    ApplicationType::Call,
                    NotifyType::Ring,
                    Mentions::new(),
                ),
                event_id: owned_event_id!("$1"),
                sender: owned_user_id!("@a:b.c"),
                origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
                unsigned: MessageLikeUnsigned::new(),
            }),
        ));
        assert_let!(
            PossibleLatestEvent::YesCallNotify(SyncMessageLikeEvent::Original(_)) =
                is_suitable_for_latest_event(&event)
        );
    }

    #[test]
    fn test_stickers_are_suitable() {
        let event = AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::Sticker(
            SyncStickerEvent::Original(OriginalSyncMessageLikeEvent {
                content: StickerEventContent::new(
                    "sticker!".to_owned(),
                    ImageInfo::new(),
                    owned_mxc_uri!("mxc://example.com/1"),
                ),
                event_id: owned_event_id!("$1"),
                sender: owned_user_id!("@a:b.c"),
                origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
                unsigned: MessageLikeUnsigned::new(),
            }),
        ));

        assert_matches!(
            is_suitable_for_latest_event(&event),
            PossibleLatestEvent::YesSticker(SyncStickerEvent::Original(_))
        );
    }

    #[test]
    fn test_different_types_of_messagelike_are_unsuitable() {
        let event =
            AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::UnstablePollResponse(
                SyncUnstablePollResponseEvent::Original(OriginalSyncMessageLikeEvent {
                    content: UnstablePollResponseEventContent::new(
                        vec![String::from("option1")],
                        owned_event_id!("$1"),
                    ),
                    event_id: owned_event_id!("$2"),
                    sender: owned_user_id!("@a:b.c"),
                    origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
                    unsigned: MessageLikeUnsigned::new(),
                }),
            ));

        assert_matches!(
            is_suitable_for_latest_event(&event),
            PossibleLatestEvent::NoUnsupportedMessageLikeType
        );
    }

    #[test]
    fn test_redacted_messages_are_suitable() {
        // Ruma does not allow constructing UnsignedRoomRedactionEvent instances.
        let room_redaction_event: UnsignedRoomRedactionEvent = serde_json::from_value(json!({
            "content": {},
            "event_id": "$redaction",
            "sender": "@x:y.za",
            "origin_server_ts": 223543,
            "unsigned": { "reason": "foo" }
        }))
        .unwrap();

        let event = AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(
            SyncRoomMessageEvent::Redacted(RedactedSyncMessageLikeEvent {
                content: RedactedRoomMessageEventContent::new(),
                event_id: owned_event_id!("$1"),
                sender: owned_user_id!("@a:b.c"),
                origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
                unsigned: RedactedUnsigned::new(room_redaction_event),
            }),
        ));

        assert_matches!(
            is_suitable_for_latest_event(&event),
            PossibleLatestEvent::YesRoomMessage(SyncMessageLikeEvent::Redacted(_))
        );
    }

    #[test]
    fn test_encrypted_messages_are_unsuitable() {
        let event = AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomEncrypted(
            SyncRoomEncryptedEvent::Original(OriginalSyncMessageLikeEvent {
                content: RoomEncryptedEventContent::new(
                    EncryptedEventScheme::OlmV1Curve25519AesSha2(
                        OlmV1Curve25519AesSha2Content::new(BTreeMap::new(), "".to_owned()),
                    ),
                    None,
                ),
                event_id: owned_event_id!("$1"),
                sender: owned_user_id!("@a:b.c"),
                origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
                unsigned: MessageLikeUnsigned::new(),
            }),
        ));

        assert_matches!(is_suitable_for_latest_event(&event), PossibleLatestEvent::NoEncrypted);
    }

    #[test]
    fn test_state_events_are_unsuitable() {
        let event = AnySyncTimelineEvent::State(AnySyncStateEvent::RoomTopic(
            SyncRoomTopicEvent::Original(OriginalSyncStateEvent {
                content: RoomTopicEventContent::new("".to_owned()),
                event_id: owned_event_id!("$1"),
                sender: owned_user_id!("@a:b.c"),
                origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
                unsigned: StateUnsigned::new(),
                state_key: EmptyStateKey,
            }),
        ));

        assert_matches!(
            is_suitable_for_latest_event(&event),
            PossibleLatestEvent::NoUnsupportedEventType
        );
    }

    #[test]
    fn test_replacement_events_are_unsuitable() {
        let mut event_content = RoomMessageEventContent::text_plain("Bye bye, world!");
        event_content.relates_to = Some(Relation::Replacement(Replacement::new(
            owned_event_id!("$1"),
            RoomMessageEventContent::text_plain("Hello, world!").into(),
        )));

        let event = AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(
            SyncRoomMessageEvent::Original(OriginalSyncMessageLikeEvent {
                content: event_content,
                event_id: owned_event_id!("$2"),
                sender: owned_user_id!("@a:b.c"),
                origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
                unsigned: MessageLikeUnsigned::new(),
            }),
        ));

        assert_matches!(
            is_suitable_for_latest_event(&event),
            PossibleLatestEvent::NoUnsupportedMessageLikeType
        );
    }

    #[test]
    fn test_deserialize_latest_event() {
        #[derive(Debug, serde::Serialize, serde::Deserialize)]
        struct TestStruct {
            latest_event: LatestEvent,
        }

        let event = SyncTimelineEvent::new(
            Raw::from_json_string(json!({ "event_id": "$1" }).to_string()).unwrap(),
        );

        let initial = TestStruct {
            latest_event: LatestEvent {
                event: event.clone(),
                sender_profile: None,
                sender_name_is_ambiguous: None,
            },
        };

        // When serialized, LatestEvent always uses the new format.
        let serialized = serde_json::to_value(&initial).unwrap();
        assert_eq!(
            serialized,
            json!({
                "latest_event": {
                    "event": {
                        "encryption_info": null,
                        "event": {
                            "event_id": "$1"
                        }
                    },
                }
            })
        );

        // And it can be properly deserialized from the new format.
        let deserialized: TestStruct = serde_json::from_value(serialized).unwrap();
        assert_eq!(deserialized.latest_event.event().event_id().unwrap(), "$1");
        assert!(deserialized.latest_event.sender_profile.is_none());
        assert!(deserialized.latest_event.sender_name_is_ambiguous.is_none());

        // The previous format can also be deserialized.
        let serialized = json!({
            "latest_event": event
        });

        let deserialized: TestStruct = serde_json::from_value(serialized).unwrap();
        assert_eq!(deserialized.latest_event.event().event_id().unwrap(), "$1");
        assert!(deserialized.latest_event.sender_profile.is_none());
        assert!(deserialized.latest_event.sender_name_is_ambiguous.is_none());
    }
}