matrix-ui-serializable 0.4.0

Opinionated abstraction of the matrix-sdk crate with serializable structs
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
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
use matrix_sdk::{
    OwnedServerName, RoomMemberships,
    media::MediaRequestParameters,
    room::{RoomMember, edit::EditedContent},
    ruma::{
        OwnedEventId, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedUserId,
        api::client::receipt::create_receipt::v3::ReceiptType,
        events::room::message::RoomMessageEventContentWithoutRelation, matrix_uri::MatrixId,
    },
};
use matrix_sdk_ui::timeline::TimelineEventItemId;
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use tokio::sync::oneshot;

use crate::{
    UserProfile,
    events::timeline::{PaginationDirection, TimelineKind},
    init::singletons::REQUEST_SENDER,
    models::profile::ProfileModel,
    room::frontend_events::timeline_item_id::FrontendTimelineEventItemId,
};

// Re-exports
pub use matrix_sdk::ruma::api::client::user_directory::search_users::v3::User;

/// Submits a request to the worker thread to be executed asynchronously.
pub(crate) fn submit_async_request(req: MatrixRequest) {
    REQUEST_SENDER
        .get()
        .unwrap() // this is initialized
        .send(req)
        .expect("BUG: async worker task receiver has died!");
}

/// The set of requests for async work that can be made to the worker thread.
#[allow(clippy::large_enum_variant)]
pub enum MatrixRequest {
    /// Request to paginate the older (or newer) events of a room or thread timeline.
    PaginateTimeline {
        timeline_kind: TimelineKind,
        /// The maximum number of timeline events to fetch in each pagination batch.
        num_events: u16,
        direction: PaginationDirection,
    },
    /// Request to edit the content of an event in the given room's timeline.
    EditMessage {
        timeline_kind: TimelineKind,
        timeline_event_item_id: TimelineEventItemId,
        edited_content: EditedContent,
    },
    /// Request to fetch the full details of the given event in the given room's timeline.
    FetchDetailsForEvent {
        timeline_kind: TimelineKind,
        event_id: OwnedEventId,
    },
    /// Request to create a thread timeline focused on the given thread root event in the given room.
    CreateThreadTimeline {
        room_id: OwnedRoomId,
        thread_root_event_id: OwnedEventId,
        sender: oneshot::Sender<()>,
    },
    /// Request to fetch profile information for all members of a room.
    /// This can be *very* slow depending on the number of members in the room.
    SyncRoomMemberList { timeline_kind: TimelineKind },
    /// Request to join the given room.
    JoinRoom { room_id: OwnedRoomId },
    /// Request to leave the given room.
    LeaveRoom { room_id: OwnedRoomId },
    /// Request to get the actual list of members in a room.
    /// This returns the list of members that can be displayed in the UI.
    GetRoomMembers {
        timeline_kind: TimelineKind,
        memberships: RoomMemberships,
        /// * If `true` (not recommended), only the local cache will be accessed.
        /// * If `false` (recommended), details will be fetched from the server.
        local_only: bool,
    },
    /// Request to fetch profile information for the given user ID.
    GetUserProfile {
        user_id: OwnedUserId,
        /// * If `Some`, the user is known to be a member of a room, so this will
        ///   fetch the user's profile from that room's membership info.
        /// * If `None`, the user's profile info will be fetched from the server
        ///   in a room-agnostic manner, and no room membership info will be returned.
        room_id: Option<OwnedRoomId>,
        /// * If `true` (not recommended), only the local cache will be accessed.
        /// * If `false` (recommended), details will be fetched from the server.
        local_only: bool,
        /// matrix-svelte-client: sender used if a command is awaiting for the
        /// profile. We send it directly through this channel
        sender: Option<oneshot::Sender<Option<UserProfile>>>,
    },
    /// Request to fetch the number of unread messages in the given room.
    GetNumberUnreadMessages { timeline_kind: TimelineKind },
    /// Request to ignore/block or unignore/unblock a user.
    IgnoreUser {
        /// Whether to ignore (`true`) or unignore (`false`) the user.
        ignore: bool,
        /// The room membership info of the user to (un)ignore.
        room_member: RoomMember,
        /// The room ID of the room where the user is a member,
        /// which is only needed because it isn't present in the `RoomMember` object.
        room_id: OwnedRoomId,
    },
    /// Request to resolve a room alias into a room ID and the servers that know about that room.
    ResolveRoomAlias(OwnedRoomAliasId),
    /// Request to fetch media from the server.
    /// Upon completion of the async media request, the `on_fetched` function
    /// will be invoked with four arguments: the `destination`, the `media_request`,
    /// the result of the media fetch, and the `update_sender`.
    FetchMedia {
        media_request: MediaRequestParameters,
        content_sender: oneshot::Sender<Result<Vec<u8>, matrix_sdk::Error>>,
    },
    /// Request to send a message to the given room.
    SendTextMessage {
        timeline_kind: TimelineKind,
        message: String,
        replied_to_id: Option<OwnedEventId>,
    },
    /// Sends a notice to the given room that the current user is or is not typing.
    ///
    /// This request does not return a response or notify the UI thread, and
    /// furthermore, there is no need to send a follow-up request to stop typing
    /// (though you certainly can do so).
    SendTypingNotice { room_id: OwnedRoomId, typing: bool },
    /// Subscribe to typing notices for the given room.
    ///
    /// This request does not return a response or notify the UI thread.
    SubscribeToTypingNotices {
        room_id: OwnedRoomId,
        /// Whether to subscribe or unsubscribe from typing notices for this room.
        subscribe: bool,
    },
    /// Subscribe to changes in the read receipts of our own user.
    ///
    /// This request does not return a response or notify the UI thread.
    SubscribeToOwnUserReadReceiptsChanged {
        timeline_kind: TimelineKind,
        /// Whether to subscribe or unsubscribe.
        subscribe: bool,
    },
    /// Sends a read receipt for the given event in the given room.
    ReadReceipt {
        timeline_kind: TimelineKind,
        event_id: OwnedEventId,
        receipt_type: ReceiptType,
    },
    /// Sends a read receipt in the given room.
    MarkRoomAsRead { timeline_kind: TimelineKind },
    /// Sends a request to obtain the power levels for this room.
    ///
    /// The response is delivered back to the main UI thread via [`TimelineUpdate::UserPowerLevels`].
    GetRoomPowerLevels { timeline_kind: TimelineKind },
    /// Toggles the given reaction to the given event in the given room.
    ToggleReaction {
        timeline_kind: TimelineKind,
        timeline_event_id: TimelineEventItemId,
        reaction: String,
    },
    /// Redacts (deletes) the given event in the given room.
    #[doc(alias("delete"))]
    RedactMessage {
        timeline_kind: TimelineKind,
        timeline_event_id: TimelineEventItemId,
        reason: Option<String>,
    },
    /// Sends a request to obtain the room's pill link info for the given Matrix ID.
    ///
    /// The MatrixLinkPillInfo::Loaded variant is sent back to the main UI thread via.
    GetMatrixRoomLinkPillInfo {
        matrix_id: MatrixId,
        via: Vec<OwnedServerName>,
    },
    SearchUsers {
        search_term: String,
        limit: u64,
        content_sender: oneshot::Sender<Result<Vec<ProfileModel>, matrix_sdk::Error>>,
    },
    /// Create a DM room with a given UserId
    CreateDMRoom { user_id: OwnedUserId },
    /// Create a Matrix room
    CreateRoom {
        room_name: String,
        room_avatar: Option<OwnedMxcUri>,
        invited_user_ids: Vec<OwnedUserId>,
        topic: Option<String>,
    },
    /// Invite a list of users to a room
    InviteUsersInRoom {
        room_id: OwnedRoomId,
        invited_user_ids: Vec<OwnedUserId>,
    },
    KickOrBanUserFromRoom {
        room_id: OwnedRoomId,
        user_id: OwnedUserId,
        reason: Option<String>,
        is_ban: bool,
    },
}
// Deserialize trait is implemented in models/async_requests.rs

impl<'de> Deserialize<'de> for MatrixRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        // First deserialize into a generic Value to inspect the structure
        let value = Value::deserialize(deserializer)?;

        // Extract the "event" field to determine the variant
        let event = value
            .get("event")
            .and_then(|v| v.as_str())
            .ok_or_else(|| serde::de::Error::missing_field("event"))?;

        // Extract the "payload" field containing the variant data
        let payload = value
            .get("payload")
            .ok_or_else(|| serde::de::Error::missing_field("payload"))?;

        // Match on the event type and deserialize the appropriate variant
        match event {
            "paginateTimeline" => {
                let data: PaginateTimelinePayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::PaginateTimeline {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                    num_events: data.num_events,
                    direction: data.direction,
                })
            }
            "editMessage" => {
                let data: EditMessagePayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::EditMessage {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                    // We only use remote event_id for now. Transaction (local) ids could be supported in the future
                    timeline_event_item_id: data.timeline_event_item_id.inner(),
                    // We only allow editing messages for now.
                    edited_content: EditedContent::RoomMessage(data.edited_content),
                })
            }
            "fetchDetailsForEvent" => {
                let data: FetchDetailsForEventPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::FetchDetailsForEvent {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                    event_id: data.event_id,
                })
            }
            // "syncRoomMemberList" => {
            //     let data: SyncRoomMemberListPayload =
            //         serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
            //     Ok(MatrixRequest::SyncRoomMemberList {
            //         room_id: data.room_id,
            //     })
            // }
            "joinRoom" => {
                let data: JoinRoomPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::JoinRoom {
                    room_id: data.room_id,
                })
            }
            "leaveRoom" => {
                let data: LeaveRoomPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::LeaveRoom {
                    room_id: data.room_id,
                })
            }
            // "getRoomMembers" => {
            //     let data: GetRoomMembersPayload =
            //         serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
            //     Ok(MatrixRequest::GetRoomMembers {
            //         room_id: data.room_id,
            //         memberships: data.memberships,
            //         local_only: data.local_only,
            //     })
            // }
            "getUserProfile" => {
                let data: GetUserProfilePayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::GetUserProfile {
                    user_id: data.user_id,
                    room_id: data.room_id,
                    local_only: data.local_only,
                    sender: None,
                })
            }
            "getNumberUnreadMessages" => {
                let data: GetNumberUnreadMessagesPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::GetNumberUnreadMessages {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                })
            }
            // "ignoreUser" => {
            //     let data: IgnoreUserPayload =
            //         serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
            //     Ok(MatrixRequest::IgnoreUser {
            //         ignore: data.ignore,
            //         room_member: data.room_member,
            //         room_id: data.room_id,
            //     })
            // }
            "resolveRoomAlias" => {
                let alias =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::ResolveRoomAlias(alias))
            }
            "sendTextMessage" => {
                let data: SendTextMessagePayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::SendTextMessage {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                    message: data.message,
                    replied_to_id: data.reply_to_id,
                })
            }
            "sendTypingNotice" => {
                let data: SendTypingNoticePayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::SendTypingNotice {
                    room_id: data.room_id,
                    typing: data.typing,
                })
            }
            "subscribeToTypingNotices" => {
                let data: SubscribeToTypingNoticesPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::SubscribeToTypingNotices {
                    room_id: data.room_id,
                    subscribe: data.subscribe,
                })
            }
            "subscribeToOwnUserReadReceiptsChanged" => {
                let data: SubscribeToOwnUserReadReceiptsChangedPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::SubscribeToOwnUserReadReceiptsChanged {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                    subscribe: data.subscribe,
                })
            }
            "readReceipt" => {
                let data: ReadReceiptPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::ReadReceipt {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                    event_id: data.event_id,
                    receipt_type: data.receipt_type,
                })
            }
            "markRoomAsRead" => {
                let data: MarkRoomAsRead =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::MarkRoomAsRead {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                })
            }
            "getRoomPowerLevels" => {
                let data: GetRoomPowerLevelsPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::GetRoomPowerLevels {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                })
            }
            "toggleReaction" => {
                let data: ToggleReactionPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::ToggleReaction {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                    timeline_event_id: TimelineEventItemId::EventId(
                        OwnedEventId::try_from(data.timeline_event_id)
                            .expect("Frontend sent incorrect event id"),
                    ), // We only use eventId, not transactions.
                    reaction: data.reaction,
                })
            }
            "redactMessage" => {
                let data: RedactMessagePayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::RedactMessage {
                    timeline_kind: get_timeline_kind(data.room_id, data.thread_root_event_id),
                    timeline_event_id: TimelineEventItemId::EventId(data.timeline_event_id),
                    reason: data.reason,
                })
            }
            // "getMatrixRoomLinkPillInfo" => {
            //     let data: GetMatrixRoomLinkPillInfoPayload =
            //         serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
            //     Ok(MatrixRequest::GetMatrixRoomLinkPillInfo {
            //         matrix_id: data.matrix_id,
            //         via: data.via,
            //     })
            // }
            "createRoom" => {
                let data: CreateRoomPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::CreateRoom {
                    room_name: data.room_name,
                    room_avatar: data.room_avatar,
                    invited_user_ids: data.invited_user_ids,
                    topic: data.topic,
                })
            }
            "createDMRoom" => {
                let data: CreateDMRoomPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::CreateDMRoom {
                    user_id: data.user_id,
                })
            }
            "inviteUsersInRoom" => {
                let data: InviteUsersInRoomPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::InviteUsersInRoom {
                    room_id: data.room_id,
                    invited_user_ids: data.invited_user_ids,
                })
            }
            "kickOrBanUserFromRoom" => {
                let data: KickOrBanUserFromRoomPayload =
                    serde_json::from_value(payload.clone()).map_err(serde::de::Error::custom)?;
                Ok(MatrixRequest::KickOrBanUserFromRoom {
                    room_id: data.room_id,
                    user_id: data.user_id,
                    reason: data.reason,
                    is_ban: data.is_ban,
                })
            }
            _ => Err(serde::de::Error::unknown_variant(
                event,
                &[
                    "paginateTimeline",
                    "editMessage",
                    "fetchDetailsForEvent",
                    // "syncRoomMemberList",
                    "joinRoom",
                    "leaveRoom",
                    // "getRoomMembers",
                    "getUserProfile",
                    "getNumberUnreadMessages",
                    // "ignoreUser",
                    "resolveRoomAlias",
                    "sendTextMessage",
                    "sendTypingNotice",
                    "subscribeToTypingNotices",
                    "subscribeToOwnUserReadReceiptsChanged",
                    "readReceipt",
                    "markRoomAsRead",
                    "getRoomPowerLevels",
                    "toggleReaction",
                    "redactMessage",
                    // "getMatrixRoomLinkPillInfo",
                    "createDMRoom",
                    "createRoom",
                    "inviteUsersInRoom",
                    "kickOrBanUserFromRoom",
                ],
            )),
        }
    }
}

// Helper structs for deserializing payloads
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PaginateTimelinePayload {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
    num_events: u16,
    direction: PaginationDirection,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct EditMessagePayload {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
    timeline_event_item_id: FrontendTimelineEventItemId,
    edited_content: RoomMessageEventContentWithoutRelation,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct FetchDetailsForEventPayload {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
    event_id: OwnedEventId,
}

// #[derive(Deserialize)]
// #[serde(rename_all = "camelCase")]
// struct SyncRoomMemberListPayload {
//     room_id: OwnedRoomId,
// }

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct JoinRoomPayload {
    room_id: OwnedRoomId,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct LeaveRoomPayload {
    room_id: OwnedRoomId,
}

// #[derive(Deserialize)]
// #[serde(rename_all = "camelCase")]
// struct GetRoomMembersPayload {
//     room_id: OwnedRoomId,
//     memberships: RoomMemberships,
//     local_only: bool,
// }

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GetUserProfilePayload {
    user_id: OwnedUserId,
    room_id: Option<OwnedRoomId>,
    local_only: bool,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GetNumberUnreadMessagesPayload {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
}

// #[derive(Deserialize)]
// #[serde(rename_all = "camelCase")]
// struct IgnoreUserPayload {
//     ignore: bool,
//     room_member: RoomMember,
//     room_id: OwnedRoomId,
// }

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SendTextMessagePayload {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
    message: String,
    reply_to_id: Option<OwnedEventId>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SendTypingNoticePayload {
    room_id: OwnedRoomId,
    typing: bool,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SubscribeToTypingNoticesPayload {
    room_id: OwnedRoomId,
    subscribe: bool,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SubscribeToOwnUserReadReceiptsChangedPayload {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
    subscribe: bool,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ReadReceiptPayload {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
    event_id: OwnedEventId,
    receipt_type: ReceiptType,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct MarkRoomAsRead {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GetRoomPowerLevelsPayload {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ToggleReactionPayload {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
    timeline_event_id: String,
    reaction: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RedactMessagePayload {
    room_id: OwnedRoomId,
    thread_root_event_id: Option<OwnedEventId>,
    timeline_event_id: OwnedEventId,
    reason: Option<String>,
}

// #[derive(Deserialize)]
// #[serde(rename_all = "camelCase")]
// struct GetMatrixRoomLinkPillInfoPayload {
//     matrix_id: MatrixId,
//     via: Vec<OwnedServerName>,
// }

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateDMRoomPayload {
    user_id: OwnedUserId,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateRoomPayload {
    room_name: String,
    room_avatar: Option<OwnedMxcUri>,
    invited_user_ids: Vec<OwnedUserId>,
    topic: Option<String>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct InviteUsersInRoomPayload {
    room_id: OwnedRoomId,
    invited_user_ids: Vec<OwnedUserId>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct KickOrBanUserFromRoomPayload {
    room_id: OwnedRoomId,
    user_id: OwnedUserId,
    reason: Option<String>,
    is_ban: bool,
}

pub(crate) fn get_timeline_kind(room_id: OwnedRoomId, root: Option<OwnedEventId>) -> TimelineKind {
    if let Some(thread_root_event_id) = root {
        TimelineKind::Thread {
            room_id,
            thread_root_event_id,
        }
    } else {
        TimelineKind::MainRoom { room_id }
    }
}