matrix-sdk-ui 0.17.0

GUI-centric utilities on top of matrix-rust-sdk (experimental).
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.

use matrix_sdk::{Client, Room, latest_events::LocalLatestEventValue};
use matrix_sdk_base::latest_event::LatestEventValue as BaseLatestEventValue;
use ruma::{MilliSecondsSinceUnixEpoch, OwnedUserId};
use tracing::trace;

use crate::timeline::{
    Profile, TimelineDetails, TimelineItemContent, event_handler::TimelineAction,
};

/// A simplified version of [`matrix_sdk_base::latest_event::LatestEventValue`]
/// tailored for this `timeline` module.
#[derive(Debug)]
pub enum LatestEventValue {
    /// No value has been computed yet, or no candidate value was found.
    None,

    /// The latest event represents a remote event.
    Remote {
        /// The timestamp of the remote event.
        timestamp: MilliSecondsSinceUnixEpoch,

        /// The sender of the remote event.
        sender: OwnedUserId,

        /// Has this event been sent by the current logged user?
        is_own: bool,

        /// The sender's profile.
        profile: TimelineDetails<Profile>,

        /// The content of the remote event.
        content: TimelineItemContent,
    },

    /// The latest event represents an invite to a room.
    RemoteInvite {
        /// The timestamp of the invite.
        timestamp: MilliSecondsSinceUnixEpoch,

        /// The inviter (can be unknown).
        inviter: Option<OwnedUserId>,

        /// The inviter's profile (can be unknown).
        inviter_profile: TimelineDetails<Profile>,
    },

    /// The latest event represents a local event that is sending, or that
    /// cannot be sent, either because a previous local event, or this local
    /// event cannot be sent.
    Local {
        /// The timestamp of the local event.
        timestamp: MilliSecondsSinceUnixEpoch,

        /// The sender of the remote event.
        sender: OwnedUserId,

        /// The sender's profile.
        profile: TimelineDetails<Profile>,

        /// The content of the local event.
        content: TimelineItemContent,

        /// Whether the local event is sending, has been sent or cannot be sent.
        state: LatestEventValueLocalState,
    },
}

#[derive(Debug)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
pub enum LatestEventValueLocalState {
    IsSending,
    HasBeenSent,
    CannotBeSent,
}

impl LatestEventValue {
    pub(crate) async fn from_base_latest_event_value(
        value: BaseLatestEventValue,
        room: &Room,
        client: &Client,
    ) -> Self {
        match value {
            BaseLatestEventValue::None => Self::None,
            BaseLatestEventValue::Remote(timeline_event) => {
                let Some(timestamp) = timeline_event.timestamp() else {
                    return Self::None;
                };
                let Some(sender) = timeline_event.sender() else {
                    return Self::None;
                };
                let is_own = client.user_id().map(|user_id| user_id == sender).unwrap_or(false);

                let profile =
                    TimelineDetails::from_initial_value(Profile::load(room, &sender).await);

                match TimelineItemContent::from_event(room, timeline_event).await {
                    Some(content) => Self::Remote { timestamp, sender, is_own, profile, content },
                    None => Self::None,
                }
            }
            BaseLatestEventValue::RemoteInvite { timestamp, inviter, .. } => {
                let inviter_profile = if let Some(inviter_id) = &inviter {
                    TimelineDetails::from_initial_value(Profile::load(room, inviter_id).await)
                } else {
                    TimelineDetails::Unavailable
                };

                Self::RemoteInvite { timestamp, inviter, inviter_profile }
            }
            BaseLatestEventValue::LocalIsSending(ref local_value)
            | BaseLatestEventValue::LocalHasBeenSent { value: ref local_value, .. }
            | BaseLatestEventValue::LocalCannotBeSent(ref local_value) => {
                let LocalLatestEventValue { timestamp, content: serialized_content } = local_value;

                let Ok(message_like_event_content) = serialized_content.deserialize() else {
                    return Self::None;
                };

                let sender =
                    client.user_id().expect("The `Client` is supposed to be logged").to_owned();
                let profile =
                    TimelineDetails::from_initial_value(Profile::load(room, &sender).await);

                match TimelineAction::from_content(message_like_event_content, None, None, None) {
                    TimelineAction::AddItem { content } => Self::Local {
                        timestamp: *timestamp,
                        sender,
                        profile,
                        content,
                        state: match value {
                            BaseLatestEventValue::LocalIsSending(_) => {
                                LatestEventValueLocalState::IsSending
                            }
                            BaseLatestEventValue::LocalHasBeenSent { .. } => {
                                LatestEventValueLocalState::HasBeenSent
                            }
                            BaseLatestEventValue::LocalCannotBeSent(_) => {
                                LatestEventValueLocalState::CannotBeSent
                            }
                            BaseLatestEventValue::Remote(_)
                            | BaseLatestEventValue::RemoteInvite { .. }
                            | BaseLatestEventValue::None => {
                                unreachable!("Only local latest events are supposed to be handled");
                            }
                        },
                    },

                    TimelineAction::HandleAggregation { kind, .. } => {
                        // Add some debug logging here to help diagnose issues with the latest
                        // event.
                        trace!("latest event is an aggregation: {}", kind.debug_string());
                        Self::None
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{ops::Not, time::Duration};

    use assert_matches::assert_matches;
    use matrix_sdk::{
        latest_events::{LocalLatestEventValue, RemoteLatestEventValue},
        store::SerializableEventContent,
        test_utils::mocks::MatrixMockServer,
    };
    use matrix_sdk_test::{JoinedRoomBuilder, async_test, event_factory::EventFactory};
    use ruma::{
        MilliSecondsSinceUnixEpoch, event_id,
        events::{AnyMessageLikeEventContent, room::message::RoomMessageEventContent},
        owned_event_id, room_id, uint, user_id,
    };

    use super::{
        super::{MsgLikeContent, MsgLikeKind, TimelineItemContent},
        BaseLatestEventValue, LatestEventValue, LatestEventValueLocalState, TimelineDetails,
    };

    #[async_test]
    async fn test_none() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let room = server.sync_room(&client, JoinedRoomBuilder::new(room_id!("!r0"))).await;

        let base_value = BaseLatestEventValue::None;
        let value =
            LatestEventValue::from_base_latest_event_value(base_value, &room, &client).await;

        assert_matches!(value, LatestEventValue::None);
    }

    #[async_test]
    async fn test_remote() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let room = server.sync_room(&client, JoinedRoomBuilder::new(room_id!("!r0"))).await;
        let sender = user_id!("@mnt_io:matrix.org");
        let event_factory = EventFactory::new();

        let base_value = BaseLatestEventValue::Remote(RemoteLatestEventValue::from_plaintext(
            event_factory
                .server_ts(42)
                .sender(sender)
                .text_msg("raclette")
                .event_id(event_id!("$ev0"))
                .into_raw_sync(),
        ));
        let value =
            LatestEventValue::from_base_latest_event_value(base_value, &room, &client).await;

        assert_matches!(value, LatestEventValue::Remote { timestamp, sender: received_sender, is_own, profile, content } => {
            assert_eq!(u64::from(timestamp.get()), 42u64);
            assert_eq!(received_sender, sender);
            assert!(is_own.not());
            assert_matches!(profile, TimelineDetails::Unavailable);
            assert_matches!(
                content,
                TimelineItemContent::MsgLike(MsgLikeContent { kind: MsgLikeKind::Message(message), .. }) => {
                    assert_eq!(message.body(), "raclette");
                }
            );
        })
    }

    #[async_test]
    async fn test_remote_invite() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let room = server.sync_room(&client, JoinedRoomBuilder::new(room_id!("!r0"))).await;
        let user_id = user_id!("@mnt_io:matrix.org");

        let base_value = BaseLatestEventValue::RemoteInvite {
            event_id: None,
            timestamp: MilliSecondsSinceUnixEpoch(42u32.into()),
            inviter: Some(user_id.to_owned()),
        };
        let value =
            LatestEventValue::from_base_latest_event_value(base_value, &room, &client).await;

        assert_matches!(value, LatestEventValue::RemoteInvite { timestamp, inviter, inviter_profile} => {
            assert_eq!(u64::from(timestamp.get()), 42u64);
            assert_eq!(inviter.as_deref(), Some(user_id));
            assert_matches!(inviter_profile, TimelineDetails::Unavailable);
        })
    }

    #[async_test]
    async fn test_local_is_sending() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let room = server.sync_room(&client, JoinedRoomBuilder::new(room_id!("!r0"))).await;

        let base_value = BaseLatestEventValue::LocalIsSending(LocalLatestEventValue {
            timestamp: MilliSecondsSinceUnixEpoch(uint!(42)),
            content: SerializableEventContent::new(&AnyMessageLikeEventContent::RoomMessage(
                RoomMessageEventContent::text_plain("raclette"),
            ))
            .unwrap(),
        });
        let value =
            LatestEventValue::from_base_latest_event_value(base_value, &room, &client).await;

        assert_matches!(value, LatestEventValue::Local { timestamp, sender, profile, content, state } => {
            assert_eq!(u64::from(timestamp.get()), 42u64);
            assert_eq!(sender, "@example:localhost");
            assert_matches!(profile, TimelineDetails::Unavailable);
            assert_matches!(
                content,
                TimelineItemContent::MsgLike(MsgLikeContent { kind: MsgLikeKind::Message(_), .. })
            );
            assert_matches!(state, LatestEventValueLocalState::IsSending);
        })
    }

    #[async_test]
    async fn test_local_has_been_sent() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let room = server.sync_room(&client, JoinedRoomBuilder::new(room_id!("!r0"))).await;

        let base_value = BaseLatestEventValue::LocalHasBeenSent {
            event_id: owned_event_id!("$ev0"),
            value: LocalLatestEventValue {
                timestamp: MilliSecondsSinceUnixEpoch(uint!(42)),
                content: SerializableEventContent::new(&AnyMessageLikeEventContent::RoomMessage(
                    RoomMessageEventContent::text_plain("raclette"),
                ))
                .unwrap(),
            },
        };
        let value =
            LatestEventValue::from_base_latest_event_value(base_value, &room, &client).await;

        assert_matches!(value, LatestEventValue::Local { timestamp, sender, profile, content, state } => {
            assert_eq!(u64::from(timestamp.get()), 42u64);
            assert_eq!(sender, "@example:localhost");
            assert_matches!(profile, TimelineDetails::Unavailable);
            assert_matches!(
                content,
                TimelineItemContent::MsgLike(MsgLikeContent { kind: MsgLikeKind::Message(_), .. })
            );
            assert_matches!(state, LatestEventValueLocalState::HasBeenSent);
        })
    }

    #[async_test]
    async fn test_local_cannot_be_sent() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let room = server.sync_room(&client, JoinedRoomBuilder::new(room_id!("!r0"))).await;

        let base_value = BaseLatestEventValue::LocalCannotBeSent(LocalLatestEventValue {
            timestamp: MilliSecondsSinceUnixEpoch(uint!(42)),
            content: SerializableEventContent::new(&AnyMessageLikeEventContent::RoomMessage(
                RoomMessageEventContent::text_plain("raclette"),
            ))
            .unwrap(),
        });
        let value =
            LatestEventValue::from_base_latest_event_value(base_value, &room, &client).await;

        assert_matches!(value, LatestEventValue::Local { timestamp, sender, profile, content, state } => {
            assert_eq!(u64::from(timestamp.get()), 42u64);
            assert_eq!(sender, "@example:localhost");
            assert_matches!(profile, TimelineDetails::Unavailable);
            assert_matches!(
                content,
                TimelineItemContent::MsgLike(MsgLikeContent { kind: MsgLikeKind::Message(_), .. })
            );
            assert_matches!(state, LatestEventValueLocalState::CannotBeSent);
        })
    }

    #[async_test]
    async fn test_remote_edit() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let room = server.sync_room(&client, JoinedRoomBuilder::new(room_id!("!r0"))).await;
        let sender = user_id!("@mnt_io:matrix.org");
        let event_factory = EventFactory::new();

        let base_value = BaseLatestEventValue::Remote(RemoteLatestEventValue::from_plaintext(
            event_factory
                .server_ts(42)
                .sender(sender)
                .text_msg("bonjour")
                .event_id(event_id!("$ev1"))
                .edit(event_id!("$ev0"), RoomMessageEventContent::text_plain("fondue").into())
                .into_raw_sync(),
        ));
        let value =
            LatestEventValue::from_base_latest_event_value(base_value, &room, &client).await;

        assert_matches!(value, LatestEventValue::Remote { timestamp, sender: received_sender, is_own, profile, content } => {
            assert_eq!(u64::from(timestamp.get()), 42u64);
            assert_eq!(received_sender, sender);
            assert!(is_own.not());
            assert_matches!(profile, TimelineDetails::Unavailable);
            assert_matches!(
                content,
                TimelineItemContent::MsgLike(MsgLikeContent { kind: MsgLikeKind::Message(message), .. }) => {
                    assert_eq!(message.body(), "fondue");
                }
            );
        })
    }

    #[async_test]
    async fn test_remote_beacon_stop() {
        let server = MatrixMockServer::new().await;
        let client = server.client_builder().build().await;
        let room = server.sync_room(&client, JoinedRoomBuilder::new(room_id!("!r0"))).await;
        let sender = user_id!("@mnt_io:matrix.org");
        let event_factory = EventFactory::new();

        let base_value = BaseLatestEventValue::Remote(RemoteLatestEventValue::from_plaintext(
            event_factory
                .server_ts(42)
                .sender(sender)
                .beacon_info(Some("Alice's walk".to_owned()), Duration::from_secs(60), false, None)
                .state_key(sender)
                .event_id(event_id!("$beacon-stop"))
                .into_raw_sync(),
        ));
        let value =
            LatestEventValue::from_base_latest_event_value(base_value, &room, &client).await;

        assert_matches!(value, LatestEventValue::Remote { timestamp, sender: received_sender, is_own, profile, content } => {
            assert_eq!(u64::from(timestamp.get()), 42u64);
            assert_eq!(received_sender, sender);
            assert!(is_own.not());
            assert_matches!(profile, TimelineDetails::Unavailable);
            assert_matches!(
                content,
                TimelineItemContent::MsgLike(MsgLikeContent { kind: MsgLikeKind::LiveLocation(state), .. }) => {
                    assert!(!state.is_live(), "stop beacon should not be live");
                    assert_eq!(state.description(), Some("Alice's walk"));
                }
            );
        })
    }
}