atagen

macltok

public
Star0
Watch0
80381e06a573f253c11a8b4c89366a9aa299ca55
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/model.rsRust2209 lines62.9 KB
1
use std::{fmt, sync::Arc};
2
3
use imbl::Vector;
4
use ruma::{
5
    MxcUri, OwnedDeviceId, OwnedEventId, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId,
6
    OwnedRoomOrAliasId, OwnedServerName, OwnedTransactionId, OwnedUserId, RoomId,
7
    events::{
8
        AnyGlobalAccountDataEventContent, AnyRoomAccountDataEventContent, AnySyncTimelineEvent,
9
        GlobalAccountDataEventType, RoomAccountDataEventType,
10
        room::member::StrippedRoomMemberEvent,
11
    },
12
    serde::Raw,
13
};
14
#[cfg(feature = "serde")]
15
use serde::{Deserialize, Serialize};
16
17
/// every command answers exactly once through `ClientHandle::send` or `execute`.
18
/// the event stream only ever carries state
19
#[derive(Debug)]
20
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
21
#[non_exhaustive]
22
pub enum Command {
23
    Account(AccountCommand),
24
    Room(RoomCommand),
25
    Timeline(TimelineCommand),
26
    EventContext(EventContextCommand),
27
    Mentions(crate::MentionsCommand),
28
    Media(MediaCommand),
29
    Encryption(EncryptionCommand),
30
    Notification(NotificationCommand),
31
    Lifecycle(LifecycleCommand),
32
    Pack(PackCommand),
33
    HistoryRepair(crate::HistoryRepairCommand),
34
}
35
36
#[derive(Clone, Debug, Eq, PartialEq)]
37
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
38
#[non_exhaustive]
39
pub enum EventContextCommand {
40
    Fetch {
41
        room_id: OwnedRoomId,
42
        event_id: OwnedEventId,
43
        before_limit: u16,
44
        after_limit: u16,
45
    },
46
    Before {
47
        room_id: OwnedRoomId,
48
        limit: u16,
49
        token: String,
50
    },
51
    After {
52
        room_id: OwnedRoomId,
53
        limit: u16,
54
        token: String,
55
    },
56
}
57
58
#[derive(Debug)]
59
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
60
#[non_exhaustive]
61
pub enum AccountCommand {
62
    Logout,
63
    SetAccountData {
64
        event_type: GlobalAccountDataEventType,
65
        content: Raw<AnyGlobalAccountDataEventContent>,
66
    },
67
    SetDisplayName(Option<String>),
68
    SetAvatar(Option<OwnedMxcUri>),
69
    /// uploads the image and points the profile at it, same byte cap as any upload
70
    UploadAvatar {
71
        mimetype: String,
72
        bytes: Vec<u8>,
73
    },
74
    /// unencrypted, answers with `CommandOutput::Mxc`. same byte cap as any upload
75
    UploadMedia {
76
        mimetype: String,
77
        bytes: Vec<u8>,
78
    },
79
    IgnoreUser(OwnedUserId),
80
    UnignoreUser(OwnedUserId),
81
    /// writes msc3230 orders so these spaces sort in exactly this sequence, touching as few as it can
82
    ReorderSpaces(Vec<OwnedRoomId>),
83
    RenameDevice {
84
        device_id: OwnedDeviceId,
85
        display_name: String,
86
    },
87
    DeleteDevices {
88
        device_ids: Vec<OwnedDeviceId>,
89
        auth: Option<crate::InteractiveAuth>,
90
    },
91
}
92
93
#[derive(Clone, Debug)]
94
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
95
#[non_exhaustive]
96
pub enum RoomCommand {
97
    /// the snapshot turns up as `Event::TimelineReset`. opening an open room sends a fresh one
98
    Open(OwnedRoomId),
99
    Close(OwnedRoomId),
100
    Join {
101
        room: OwnedRoomOrAliasId,
102
        via: Vec<OwnedServerName>,
103
    },
104
    Leave(OwnedRoomId),
105
    Forget(OwnedRoomId),
106
    AcceptInvite(OwnedRoomId),
107
    RejectInvite(OwnedRoomId),
108
    InviteUser {
109
        room_id: OwnedRoomId,
110
        user_id: OwnedUserId,
111
    },
112
    KickUser {
113
        room_id: OwnedRoomId,
114
        user_id: OwnedUserId,
115
        reason: Option<String>,
116
    },
117
    BanUser {
118
        room_id: OwnedRoomId,
119
        user_id: OwnedUserId,
120
        reason: Option<String>,
121
    },
122
    UnbanUser {
123
        room_id: OwnedRoomId,
124
        user_id: OwnedUserId,
125
        reason: Option<String>,
126
    },
127
    SetPowerLevels {
128
        room_id: OwnedRoomId,
129
        changes: PowerLevelChanges,
130
    },
131
    SetUserPowerLevel {
132
        room_id: OwnedRoomId,
133
        user_id: OwnedUserId,
134
        level: i64,
135
    },
136
    /// muting drops them below what sending a message takes, unmuting puts a muted user back
137
    /// at users_default and leaves anyone else alone
138
    MuteUser {
139
        room_id: OwnedRoomId,
140
        user_id: OwnedUserId,
141
        muted: bool,
142
    },
143
    /// pinning appends, so the newest pin is last like everywhere else
144
    SetPinned {
145
        room_id: OwnedRoomId,
146
        event_id: OwnedEventId,
147
        pinned: bool,
148
    },
149
    /// adding m.favourite drops m.lowpriority, the way Element does
150
    SetFavourite {
151
        room_id: OwnedRoomId,
152
        favourite: bool,
153
    },
154
    /// your name in one room. None goes back to your global name
155
    SetOwnDisplayName {
156
        room_id: OwnedRoomId,
157
        name: Option<String>,
158
    },
159
    /// your avatar in one room. None goes back to your global avatar
160
    SetOwnAvatar {
161
        room_id: OwnedRoomId,
162
        avatar: Option<OwnedMxcUri>,
163
    },
164
    Create(CreateRoomOptions),
165
    /// hands back the existing dm if there is one
166
    CreateDirect(OwnedUserId),
167
    CancelSend {
168
        room_id: OwnedRoomId,
169
        transaction_id: OwnedTransactionId,
170
    },
171
    RetrySend {
172
        room_id: OwnedRoomId,
173
        transaction_id: OwnedTransactionId,
174
    },
175
    SetTyping {
176
        room_id: OwnedRoomId,
177
        typing: bool,
178
    },
179
    /// the key work a send into an encrypted room would otherwise start with, done now.
180
    /// nothing in a plain room, and a second ask joins the first
181
    PrepareToSend(OwnedRoomId),
182
    SetAccountData {
183
        room_id: OwnedRoomId,
184
        event_type: RoomAccountDataEventType,
185
        content: Raw<AnyRoomAccountDataEventContent>,
186
    },
187
}
188
189
#[derive(Clone, Debug, Default, Eq, PartialEq)]
190
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
191
#[non_exhaustive]
192
pub struct CreateRoomOptions {
193
    pub name: Option<String>,
194
    pub topic: Option<String>,
195
    pub alias_localpart: Option<String>,
196
    pub invite: Vec<OwnedUserId>,
197
    pub direct: bool,
198
    pub visibility: RoomVisibility,
199
    pub preset: Option<RoomPreset>,
200
}
201
202
impl CreateRoomOptions {
203
    #[must_use]
204
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
205
        self.name = Some(name.into());
206
        self
207
    }
208
209
    #[must_use]
210
    pub fn with_topic(mut self, topic: impl Into<String>) -> Self {
211
        self.topic = Some(topic.into());
212
        self
213
    }
214
215
    #[must_use]
216
    pub fn with_alias_localpart(mut self, localpart: impl Into<String>) -> Self {
217
        self.alias_localpart = Some(localpart.into());
218
        self
219
    }
220
221
    #[must_use]
222
    pub fn with_invite(mut self, invite: impl IntoIterator<Item = OwnedUserId>) -> Self {
223
        self.invite = invite.into_iter().collect();
224
        self
225
    }
226
227
    #[must_use]
228
    pub const fn with_direct(mut self, direct: bool) -> Self {
229
        self.direct = direct;
230
        self
231
    }
232
233
    #[must_use]
234
    pub const fn with_visibility(mut self, visibility: RoomVisibility) -> Self {
235
        self.visibility = visibility;
236
        self
237
    }
238
239
    #[must_use]
240
    pub const fn with_preset(mut self, preset: RoomPreset) -> Self {
241
        self.preset = Some(preset);
242
        self
243
    }
244
}
245
246
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
247
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
248
pub enum RoomVisibility {
249
    #[default]
250
    Private,
251
    Public,
252
}
253
254
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
255
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
256
pub enum RoomPreset {
257
    PrivateChat,
258
    TrustedPrivateChat,
259
    PublicChat,
260
}
261
262
#[derive(Clone, Debug, Eq, PartialEq)]
263
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
264
#[non_exhaustive]
265
pub enum TimelineCommand {
266
    OpenThread {
267
        room_id: OwnedRoomId,
268
        root_event_id: OwnedEventId,
269
    },
270
    CloseThread {
271
        room_id: OwnedRoomId,
272
        root_event_id: OwnedEventId,
273
    },
274
    /// the room's pinned events as a timeline of their own, kept current as pins change.
275
    /// it can't send or paginate, the pins are all it holds
276
    OpenPinned(OwnedRoomId),
277
    ClosePinned(OwnedRoomId),
278
    /// Re-emit an authoritative reset for an open room or thread without
279
    /// closing it. The reset arrives before this command's terminal result.
280
    Resync {
281
        timeline_id: TimelineId,
282
    },
283
    Paginate {
284
        timeline_id: TimelineId,
285
        limit: u16,
286
    },
287
    Send {
288
        timeline_id: TimelineId,
289
        content: MessageContent,
290
    },
291
    Edit {
292
        timeline_id: TimelineId,
293
        target: EventRef,
294
        content: MessageEditContent,
295
    },
296
    /// redacting your own unsent message just cancels it
297
    Redact {
298
        timeline_id: TimelineId,
299
        target: EventRef,
300
        reason: Option<String>,
301
    },
302
    ToggleReaction {
303
        timeline_id: TimelineId,
304
        target: EventRef,
305
        key: String,
306
        /// a custom emote's shortcode, sent along so clients without the pack can label it
307
        shortcode: Option<String>,
308
    },
309
    /// works on a closed room too, it just can't refuse to move the marker backwards
310
    MarkRead {
311
        timeline_id: TimelineId,
312
        event_id: OwnedEventId,
313
    },
314
}
315
316
impl TimelineCommand {
317
    #[must_use]
318
    pub const fn room_id(&self) -> &OwnedRoomId {
319
        match self {
320
            Self::OpenThread { room_id, .. }
321
            | Self::CloseThread { room_id, .. }
322
            | Self::OpenPinned(room_id)
323
            | Self::ClosePinned(room_id) => room_id,
324
            Self::Resync { timeline_id }
325
            | Self::Paginate { timeline_id, .. }
326
            | Self::Send { timeline_id, .. }
327
            | Self::Edit { timeline_id, .. }
328
            | Self::Redact { timeline_id, .. }
329
            | Self::ToggleReaction { timeline_id, .. }
330
            | Self::MarkRead { timeline_id, .. } => timeline_id.room_id(),
331
        }
332
    }
333
334
    #[must_use]
335
    pub const fn timeline_id(&self) -> Option<&TimelineId> {
336
        match self {
337
            Self::OpenThread { .. }
338
            | Self::CloseThread { .. }
339
            | Self::OpenPinned(_)
340
            | Self::ClosePinned(_) => None,
341
            Self::Resync { timeline_id }
342
            | Self::Paginate { timeline_id, .. }
343
            | Self::Send { timeline_id, .. }
344
            | Self::Edit { timeline_id, .. }
345
            | Self::Redact { timeline_id, .. }
346
            | Self::ToggleReaction { timeline_id, .. }
347
            | Self::MarkRead { timeline_id, .. } => Some(timeline_id),
348
        }
349
    }
350
}
351
352
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
353
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
354
pub enum TimelineId {
355
    Room(OwnedRoomId),
356
    Thread {
357
        room_id: OwnedRoomId,
358
        root_event_id: OwnedEventId,
359
    },
360
    Pinned(OwnedRoomId),
361
}
362
363
impl TimelineId {
364
    #[must_use]
365
    pub const fn room_id(&self) -> &OwnedRoomId {
366
        match self {
367
            Self::Room(room_id) | Self::Thread { room_id, .. } | Self::Pinned(room_id) => room_id,
368
        }
369
    }
370
371
    #[must_use]
372
    pub fn thread(room_id: OwnedRoomId, root_event_id: OwnedEventId) -> Self {
373
        Self::Thread {
374
            room_id,
375
            root_event_id,
376
        }
377
    }
378
379
    #[must_use]
380
    pub fn thread_root(&self) -> Option<&OwnedEventId> {
381
        match self {
382
            Self::Room(_) | Self::Pinned(_) => None,
383
            Self::Thread { root_event_id, .. } => Some(root_event_id),
384
        }
385
    }
386
}
387
388
impl From<OwnedRoomId> for TimelineId {
389
    fn from(room_id: OwnedRoomId) -> Self {
390
        Self::Room(room_id)
391
    }
392
}
393
394
#[derive(Clone, Debug, Eq, PartialEq)]
395
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
396
#[non_exhaustive]
397
pub enum MediaCommand {
398
    /// succeeds once the send queue has it. progress and failure arrive as events
399
    Upload(AttachmentUpload),
400
}
401
402
/// msc2545 pack editing. edits read the server's copy and keep keys macltok doesn't model
403
#[derive(Clone, Debug, Eq, PartialEq)]
404
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
405
#[non_exhaustive]
406
pub enum PackCommand {
407
    /// body defaults to the shortcode
408
    SendSticker {
409
        room_id: OwnedRoomId,
410
        pack_id: String,
411
        shortcode: String,
412
    },
413
    /// fails if the state key already holds a pack
414
    CreateRoomPack {
415
        room_id: OwnedRoomId,
416
        state_key: String,
417
        display_name: String,
418
    },
419
    /// empties the content, which is all deleting a pack can mean
420
    Delete(ImagePackSource),
421
    SetMeta {
422
        pack: ImagePackSource,
423
        display_name: Patch<String>,
424
        avatar: Patch<OwnedMxcUri>,
425
        usage: Patch<Vec<PackUsage>>,
426
    },
427
    /// adds or replaces by shortcode. a replaced image keeps its info unless the url changed
428
    PutImage {
429
        pack: ImagePackSource,
430
        shortcode: String,
431
        mxc: OwnedMxcUri,
432
        body: Option<String>,
433
        usage: Option<Vec<PackUsage>>,
434
        info: Option<PackImageInfo>,
435
    },
436
    /// fails if `to` is taken
437
    RenameImage {
438
        pack: ImagePackSource,
439
        from: String,
440
        to: String,
441
    },
442
    RemoveImage {
443
        pack: ImagePackSource,
444
        shortcode: String,
445
    },
446
    SetEnabledEverywhere {
447
        room_id: OwnedRoomId,
448
        state_key: String,
449
        enabled: bool,
450
    },
451
    /// answers with `CommandOutput::Mxc`, the same uri when it already lives on your homeserver
452
    Rehost(OwnedMxcUri),
453
    /// the rest answer with `CommandOutput::Cloned`. clashes get `-2`, `-3` and so on
454
    CloneImage {
455
        from_pack: String,
456
        shortcode: String,
457
        to: ImagePackSource,
458
    },
459
    CloneSticker {
460
        room_id: OwnedRoomId,
461
        event_id: OwnedEventId,
462
        to: ImagePackSource,
463
        shortcode: String,
464
    },
465
    /// makes the room pack if its state key is free, else merges. images that can't be
466
    /// fetched are skipped and listed, the rest are written
467
    ClonePack {
468
        from_pack: String,
469
        to: ImagePackSource,
470
        display_name: Option<String>,
471
    },
472
}
473
474
#[derive(Clone, Debug, Default, Eq, PartialEq)]
475
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
476
pub enum Patch<T> {
477
    #[default]
478
    Keep,
479
    Clear,
480
    Set(T),
481
}
482
483
#[derive(Clone, Debug, Default, Eq, PartialEq)]
484
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
485
#[non_exhaustive]
486
pub struct PackImageInfo {
487
    pub mimetype: Option<String>,
488
    pub size_bytes: Option<u64>,
489
    pub width: Option<u64>,
490
    pub height: Option<u64>,
491
}
492
493
impl PackImageInfo {
494
    #[must_use]
495
    pub fn new(
496
        mimetype: Option<String>,
497
        size_bytes: Option<u64>,
498
        width: Option<u64>,
499
        height: Option<u64>,
500
    ) -> Self {
501
        Self {
502
            mimetype,
503
            size_bytes,
504
            width,
505
            height,
506
        }
507
    }
508
}
509
510
#[derive(Clone, Debug, Eq, PartialEq)]
511
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
512
#[non_exhaustive]
513
pub struct AttachmentUpload {
514
    pub timeline_id: TimelineId,
515
    pub filename: String,
516
    pub mimetype: String,
517
    pub bytes: Vec<u8>,
518
    pub caption: Option<RichText>,
519
    pub mentions: MessageMentions,
520
    pub reply_to: Option<OwnedEventId>,
521
    pub notify_replied_to: bool,
522
    pub details: Option<UploadDetails>,
523
    pub thumbnail: Option<UploadThumbnail>,
524
}
525
526
impl AttachmentUpload {
527
    #[must_use]
528
    pub fn new(
529
        timeline_id: impl Into<TimelineId>,
530
        filename: impl Into<String>,
531
        mimetype: impl Into<String>,
532
        bytes: Vec<u8>,
533
    ) -> Self {
534
        Self {
535
            timeline_id: timeline_id.into(),
536
            filename: filename.into(),
537
            mimetype: mimetype.into(),
538
            bytes,
539
            caption: None,
540
            mentions: MessageMentions::default(),
541
            reply_to: None,
542
            notify_replied_to: true,
543
            details: None,
544
            thumbnail: None,
545
        }
546
    }
547
}
548
549
#[derive(Clone, Debug, Eq, PartialEq)]
550
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
551
#[non_exhaustive]
552
pub enum UploadDetails {
553
    Image {
554
        width: Option<u32>,
555
        height: Option<u32>,
556
        blurhash: Option<String>,
557
    },
558
    Video {
559
        width: Option<u32>,
560
        height: Option<u32>,
561
        duration_ms: Option<u64>,
562
        blurhash: Option<String>,
563
    },
564
    Audio {
565
        duration_ms: Option<u64>,
566
    },
567
    Voice {
568
        duration_ms: u64,
569
        waveform: Vec<u16>,
570
    },
571
    File,
572
}
573
574
#[derive(Clone, Debug, Eq, PartialEq)]
575
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
576
#[non_exhaustive]
577
pub struct UploadThumbnail {
578
    pub bytes: Vec<u8>,
579
    pub mimetype: String,
580
    pub width: u32,
581
    pub height: u32,
582
}
583
584
impl UploadThumbnail {
585
    #[must_use]
586
    pub fn new(bytes: Vec<u8>, mimetype: impl Into<String>, width: u32, height: u32) -> Self {
587
        Self {
588
            bytes,
589
            mimetype: mimetype.into(),
590
            width,
591
            height,
592
        }
593
    }
594
}
595
596
#[derive(Eq, PartialEq)]
597
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
598
#[non_exhaustive]
599
pub enum EncryptionCommand {
600
    Recover(String),
601
    CreateKeyBackup,
602
    EnableKeyBackup,
603
    DisableKeyBackup { delete_from_server: bool },
604
    RecoverKeyBackup(String),
605
    StartVerification(VerificationTarget),
606
    Verify(VerificationAction),
607
}
608
609
impl fmt::Debug for EncryptionCommand {
610
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
611
        match self {
612
            Self::Recover(_) => formatter.debug_tuple("Recover").field(&"...").finish(),
613
            Self::CreateKeyBackup => formatter.write_str("CreateKeyBackup"),
614
            Self::EnableKeyBackup => formatter.write_str("EnableKeyBackup"),
615
            Self::DisableKeyBackup { delete_from_server } => formatter
616
                .debug_struct("DisableKeyBackup")
617
                .field("delete_from_server", delete_from_server)
618
                .finish(),
619
            Self::RecoverKeyBackup(_) => formatter
620
                .debug_tuple("RecoverKeyBackup")
621
                .field(&"...")
622
                .finish(),
623
            Self::StartVerification(target) => formatter
624
                .debug_tuple("StartVerification")
625
                .field(target)
626
                .finish(),
627
            Self::Verify(action) => formatter.debug_tuple("Verify").field(action).finish(),
628
        }
629
    }
630
}
631
632
#[derive(Clone, Debug, Eq, PartialEq)]
633
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
634
#[non_exhaustive]
635
pub enum NotificationCommand {
636
    SetRoomMode {
637
        room_id: OwnedRoomId,
638
        mode: RoomNotificationMode,
639
    },
640
    ResetRoomMode(OwnedRoomId),
641
    SetDefaultMode {
642
        encrypted: bool,
643
        one_to_one: bool,
644
        mode: RoomNotificationMode,
645
    },
646
    AddKeyword(String),
647
    RemoveKeyword(String),
648
}
649
650
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
651
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
652
#[non_exhaustive]
653
pub enum LifecycleCommand {
654
    Shutdown,
655
}
656
657
#[derive(Clone, Debug, PartialEq)]
658
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
659
pub enum CommandOutput {
660
    Done,
661
    Room(OwnedRoomId),
662
    Mxc(OwnedMxcUri),
663
    /// the shortcodes the copies ended up under, and the ones that couldn't be fetched
664
    Cloned {
665
        shortcodes: Vec<String>,
666
        skipped: Vec<String>,
667
    },
668
    EventContext(EventContext),
669
    EventContextPage(EventContextPage),
670
    MentionsPage(crate::MentionsPage),
671
    MentionContext(crate::SavedMentionContext),
672
    HistoryRepair(crate::HistoryRepairReport),
673
    HistoryRepairPolicy(crate::HistoryRepairPolicy),
674
}
675
676
#[derive(Clone, Debug, Eq, PartialEq)]
677
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
678
#[non_exhaustive]
679
pub struct EventContext {
680
    pub events_before: Vec<TimelineItem>,
681
    pub event: Option<TimelineItem>,
682
    pub events_after: Vec<TimelineItem>,
683
    pub start_token: Option<String>,
684
    pub end_token: Option<String>,
685
}
686
687
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
688
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
689
pub enum EventContextDirection {
690
    Before,
691
    After,
692
}
693
694
#[derive(Clone, Debug, Eq, PartialEq)]
695
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
696
#[non_exhaustive]
697
pub struct EventContextPage {
698
    pub direction: EventContextDirection,
699
    pub events: Vec<TimelineItem>,
700
    pub next_token: Option<String>,
701
    pub end_reached: bool,
702
}
703
704
#[derive(Clone, Debug, Eq, PartialEq)]
705
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
706
#[non_exhaustive]
707
pub enum MessageContent {
708
    Text {
709
        content: RichText,
710
        mentions: MessageMentions,
711
    },
712
    Emote {
713
        content: RichText,
714
        mentions: MessageMentions,
715
    },
716
    /// m.notice, for bots. clients render it muted and never answer it automatically
717
    Notice {
718
        content: RichText,
719
        mentions: MessageMentions,
720
    },
721
    Reply {
722
        event_id: OwnedEventId,
723
        content: RichText,
724
        mentions: MessageMentions,
725
        notify_replied_to: bool,
726
    },
727
}
728
729
impl MessageContent {
730
    #[must_use]
731
    pub fn text(body: impl Into<String>) -> Self {
732
        Self::Text {
733
            content: RichText::plain(body),
734
            mentions: MessageMentions::default(),
735
        }
736
    }
737
738
    #[must_use]
739
    pub fn html(body: impl Into<String>, formatted_body: impl Into<String>) -> Self {
740
        Self::Text {
741
            content: RichText::html(body, formatted_body),
742
            mentions: MessageMentions::default(),
743
        }
744
    }
745
746
    #[must_use]
747
    pub fn emote(content: RichText, mentions: MessageMentions) -> Self {
748
        Self::Emote { content, mentions }
749
    }
750
751
    #[must_use]
752
    pub fn notice(content: RichText, mentions: MessageMentions) -> Self {
753
        Self::Notice { content, mentions }
754
    }
755
756
    #[must_use]
757
    pub fn reply(event_id: OwnedEventId, content: RichText, mentions: MessageMentions) -> Self {
758
        Self::Reply {
759
            event_id,
760
            content,
761
            mentions,
762
            notify_replied_to: true,
763
        }
764
    }
765
766
    #[must_use]
767
    pub fn reply_without_notification(
768
        event_id: OwnedEventId,
769
        content: RichText,
770
        mentions: MessageMentions,
771
    ) -> Self {
772
        Self::Reply {
773
            event_id,
774
            content,
775
            mentions,
776
            notify_replied_to: false,
777
        }
778
    }
779
}
780
781
#[derive(Clone, Debug, Eq, PartialEq)]
782
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
783
#[non_exhaustive]
784
pub enum MessageEditContent {
785
    Text {
786
        content: RichText,
787
        mentions: MessageMentions,
788
    },
789
    Emote {
790
        content: RichText,
791
        mentions: MessageMentions,
792
    },
793
}
794
795
impl MessageEditContent {
796
    #[must_use]
797
    pub fn text(body: impl Into<String>) -> Self {
798
        Self::Text {
799
            content: RichText::plain(body),
800
            mentions: MessageMentions::default(),
801
        }
802
    }
803
804
    #[must_use]
805
    pub fn html(body: impl Into<String>, formatted_body: impl Into<String>) -> Self {
806
        Self::Text {
807
            content: RichText::html(body, formatted_body),
808
            mentions: MessageMentions::default(),
809
        }
810
    }
811
812
    #[must_use]
813
    pub fn emote(content: RichText, mentions: MessageMentions) -> Self {
814
        Self::Emote { content, mentions }
815
    }
816
}
817
818
#[derive(Clone, Debug, Default, Eq, PartialEq)]
819
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
820
#[non_exhaustive]
821
pub struct RichText {
822
    pub body: String,
823
    pub formatted_body: Option<String>,
824
}
825
826
impl RichText {
827
    #[must_use]
828
    pub fn plain(body: impl Into<String>) -> Self {
829
        Self {
830
            body: body.into(),
831
            formatted_body: None,
832
        }
833
    }
834
835
    #[must_use]
836
    pub fn html(body: impl Into<String>, formatted_body: impl Into<String>) -> Self {
837
        Self {
838
            body: body.into(),
839
            formatted_body: Some(formatted_body.into()),
840
        }
841
    }
842
}
843
844
#[derive(Clone, Debug, Default, Eq, PartialEq)]
845
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
846
#[non_exhaustive]
847
pub struct MessageMentions {
848
    pub user_ids: Vec<OwnedUserId>,
849
    pub room: bool,
850
}
851
852
impl MessageMentions {
853
    #[must_use]
854
    pub fn with_user_ids(user_ids: impl IntoIterator<Item = OwnedUserId>) -> Self {
855
        Self {
856
            user_ids: user_ids.into_iter().collect(),
857
            room: false,
858
        }
859
    }
860
861
    #[must_use]
862
    pub fn room() -> Self {
863
        Self {
864
            user_ids: Vec::new(),
865
            room: true,
866
        }
867
    }
868
}
869
870
#[derive(Clone, Debug, PartialEq)]
871
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
872
pub enum Event {
873
    ConnectionChanged(ConnectionState),
874
    Authenticated {
875
        user_id: OwnedUserId,
876
    },
877
    /// the tokens rotated. with a `SessionStore` the record is already saved by now,
878
    /// without one persist a fresh `ClientHandle::session_record()` atomically
879
    SessionTokensChanged,
880
    /// the rotated tokens didn't reach the `SessionStore`, so the saved record may not
881
    /// restore. the engine tries again on the next rotation
882
    SessionSaveFailed {
883
        message: String,
884
    },
885
    /// the server stopped honouring our token and the engine stops. a soft logout
886
    /// names the device to log in again as, keeping the store. otherwise the record
887
    /// and the store are both dead
888
    SessionAccessRejected {
889
        soft_logout: Option<OwnedDeviceId>,
890
    },
891
    NotificationSettingsChanged,
892
    VerificationTargetChanged(VerificationTarget),
893
    RoomsChanged,
894
    MentionsChanged(crate::MentionsUpdate),
895
    /// an image pack came, went or changed somewhere. ask `image_packs` again
896
    ImagePacksChanged,
897
    /// replaces whatever you had for this timeline. every diff after it applies to it
898
    TimelineReset {
899
        timeline_id: TimelineId,
900
        items: Vector<TimelineItem>,
901
    },
902
    TimelineChanged {
903
        timeline_id: TimelineId,
904
        diffs: Vec<TimelineDiff>,
905
    },
906
    HistoryChanged {
907
        timeline_id: TimelineId,
908
        state: HistoryState,
909
    },
910
    HistoryRepairChanged(crate::HistoryRepairReport),
911
    #[doc(hidden)]
912
    HistoryRepairPublished {
913
        report: crate::HistoryRepairReport,
914
        #[cfg_attr(feature = "serde", serde(skip))]
915
        acknowledgement: Option<crate::PublicationAck>,
916
    },
917
    /// the timeline was closed, or its room was left, and nothing more comes for it
918
    /// until another `TimelineReset`
919
    TimelineClosed {
920
        timeline_id: TimelineId,
921
    },
922
    /// a room that stops being watched says so with an empty `users`
923
    TypingChanged(TypingState),
924
    MediaUploadProgress {
925
        room_id: OwnedRoomId,
926
        transaction_id: OwnedTransactionId,
927
        uploaded_bytes: u64,
928
        total_bytes: u64,
929
        complete: bool,
930
    },
931
    /// not the end of it. `will_retry` means the send queue has another go by itself,
932
    /// otherwise it waits for `retry_send` or `cancel_send`
933
    MediaUploadFailed {
934
        room_id: OwnedRoomId,
935
        transaction_id: OwnedTransactionId,
936
        kind: crate::ErrorKind,
937
        will_retry: bool,
938
    },
939
    /// an upload that turned up in a progress or failure event gets exactly one of
940
    /// these while the engine runs, and nothing about it after. stopping ends
941
    /// nothing, `Stopped` covers whatever is still going and the sdk resumes it next run
942
    MediaUploadFinished {
943
        room_id: OwnedRoomId,
944
        transaction_id: OwnedTransactionId,
945
        outcome: UploadOutcome,
946
    },
947
    EncryptionChanged(EncryptionState),
948
    VerificationChanged(VerificationState),
949
    /// logout went through and the engine stops. delete the record and the store
950
    LoggedOut,
951
    Failed(EngineFailure),
952
    /// always the last event. keep the saved record unless `LoggedOut` or a
953
    /// hard `SessionAccessRejected` came first. commands still in flight answer `Interrupted`
954
    Stopped,
955
}
956
957
#[derive(Clone, Debug, Eq, PartialEq)]
958
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
959
pub enum UploadOutcome {
960
    Sent {
961
        event_id: OwnedEventId,
962
    },
963
    Cancelled,
964
    /// its room was forgotten, and the queue with it
965
    RoomForgotten,
966
    /// the sdk's update channel overflowed while it ended, so whether it was sent is unknown
967
    Missed,
968
}
969
970
/// why `Engine::run` came back, when nothing went wrong
971
#[derive(Clone, Debug, Eq, PartialEq)]
972
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
973
pub enum Termination {
974
    ShutDown,
975
    /// every `ClientHandle` was dropped, so nobody could have asked for anything else
976
    HandlesDropped,
977
    LoggedOut,
978
    /// the server rejected our token for good
979
    AccessRevoked,
980
    /// the server wants this device to log in again, and its e2ee keys live in the store
981
    SoftLoggedOut {
982
        device_id: OwnedDeviceId,
983
    },
984
}
985
986
impl Termination {
987
    #[must_use]
988
    pub const fn retain(&self) -> Retain {
989
        match self {
990
            Self::ShutDown | Self::HandlesDropped => Retain::RecordAndStore,
991
            Self::SoftLoggedOut { .. } => Retain::Store,
992
            Self::LoggedOut | Self::AccessRevoked => Retain::Nothing,
993
        }
994
    }
995
}
996
997
/// what's still worth keeping of the saved record and the store
998
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
999
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1000
pub enum Retain {
1001
    RecordAndStore,
1002
    /// keep the store and a record naming the device to log in again as
1003
    Store,
1004
    Nothing,
1005
}
1006
1007
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1008
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1009
pub enum ConnectionState {
1010
    Idle,
1011
    Connecting,
1012
    Online,
1013
    Offline,
1014
    Stopped,
1015
}
1016
1017
#[derive(Clone, Debug, Eq, PartialEq)]
1018
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1019
#[non_exhaustive]
1020
pub struct RoomSummary {
1021
    pub room_id: OwnedRoomId,
1022
    pub name: String,
1023
    pub membership: RoomMembership,
1024
    pub unread_messages: u64,
1025
    pub unread_mentions: u64,
1026
    /// unread events the push rules said to notify about, which is neither of the above
1027
    pub unread_notifications: u64,
1028
    pub encrypted: bool,
1029
    pub space: bool,
1030
    pub direct: bool,
1031
    pub favourite: bool,
1032
    pub low_priority: bool,
1033
    pub avatar: Option<MediaId>,
1034
    pub latest_event_timestamp_ms: Option<u64>,
1035
    pub latest_event: Option<LatestEvent>,
1036
    pub notification_mode: Option<RoomNotificationMode>,
1037
    pub notification_mode_custom: bool,
1038
    pub topic: Option<String>,
1039
    pub canonical_alias: Option<OwnedRoomAliasId>,
1040
    pub joined_members: u64,
1041
    pub invited_members: u64,
1042
    /// who a nameless room gets named after
1043
    pub heroes: Vec<RoomHero>,
1044
    /// set once the room has been upgraded, this is where everyone went
1045
    pub successor: Option<OwnedRoomId>,
1046
    pub inviter: Option<OwnedUserId>,
1047
    /// joined spaces that list this room as a child
1048
    pub parent_spaces: Vec<OwnedRoomId>,
1049
    /// for a space, the children it lists, joined or not
1050
    pub children: Vec<OwnedRoomId>,
1051
    /// a space's msc3230 order. ordered spaces sort first by (order, room id), the rest by room id
1052
    pub space_order: Option<String>,
1053
    /// you can send im.ponies.room_emotes here, so you can make and edit its packs
1054
    pub can_edit_packs: bool,
1055
    /// m.room.pinned_events in order, the newest pin last
1056
    pub pinned_events: Vec<OwnedEventId>,
1057
    pub can_pin: bool,
1058
}
1059
1060
#[derive(Clone, Debug, Eq, PartialEq)]
1061
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1062
#[non_exhaustive]
1063
pub struct RoomHero {
1064
    pub user_id: OwnedUserId,
1065
    pub display_name: Option<String>,
1066
    pub avatar: Option<MediaId>,
1067
}
1068
1069
/// enough for a room list preview line. `kind` and `body` are only set for messages,
1070
/// and an edit shows its new text
1071
#[derive(Clone, Debug, Eq, PartialEq)]
1072
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1073
#[non_exhaustive]
1074
pub struct LatestEvent {
1075
    pub sender: Option<OwnedUserId>,
1076
    pub kind: Option<MessageKind>,
1077
    pub body: Option<String>,
1078
    pub timestamp_ms: Option<u64>,
1079
    pub send_state: SendState,
1080
}
1081
1082
#[derive(Clone, Debug, Eq, PartialEq)]
1083
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1084
#[non_exhaustive]
1085
pub struct Profile {
1086
    pub user_id: OwnedUserId,
1087
    pub display_name: Option<String>,
1088
    pub avatar: Option<MediaId>,
1089
}
1090
1091
/// one room in a space's hierarchy, as the server describes it, which may be a room you're not in
1092
#[derive(Clone, Debug, Eq, PartialEq)]
1093
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1094
#[non_exhaustive]
1095
pub struct SpaceChild {
1096
    pub room_id: OwnedRoomId,
1097
    pub name: String,
1098
    pub topic: Option<String>,
1099
    pub avatar: Option<MediaId>,
1100
    pub canonical_alias: Option<OwnedRoomAliasId>,
1101
    pub joined_members: u64,
1102
    pub space: bool,
1103
    pub children_count: u64,
1104
    pub membership: Option<RoomMembership>,
1105
    pub via: Vec<OwnedServerName>,
1106
    pub suggested: bool,
1107
    pub world_readable: Option<bool>,
1108
    pub guest_can_join: bool,
1109
}
1110
1111
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1112
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1113
pub enum RoomNotificationMode {
1114
    AllMessages,
1115
    MentionsAndKeywordsOnly,
1116
    Mute,
1117
}
1118
1119
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1120
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1121
#[non_exhaustive]
1122
pub struct RoomNotificationSettings {
1123
    pub mode: RoomNotificationMode,
1124
    pub custom: bool,
1125
}
1126
1127
#[derive(Clone, Debug)]
1128
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1129
pub enum PushNotificationStatus {
1130
    Event(Box<PushNotification>),
1131
    NotFound,
1132
    FilteredOut,
1133
    Redacted,
1134
}
1135
1136
#[derive(Clone, Debug)]
1137
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1138
#[non_exhaustive]
1139
pub struct PushNotification {
1140
    pub event_id: OwnedEventId,
1141
    pub event: PushNotificationEvent,
1142
    pub sender: PushNotificationSender,
1143
    pub room: PushNotificationRoom,
1144
    pub noisy: Option<bool>,
1145
    pub has_mention: Option<bool>,
1146
    pub thread_id: Option<OwnedEventId>,
1147
}
1148
1149
#[derive(Clone, Debug, Eq, PartialEq)]
1150
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1151
#[non_exhaustive]
1152
pub struct PushNotificationSender {
1153
    pub user_id: OwnedUserId,
1154
    pub display_name: Option<String>,
1155
    pub avatar_url: Option<MediaId>,
1156
    pub name_ambiguous: bool,
1157
}
1158
1159
#[derive(Clone, Debug, Eq, PartialEq)]
1160
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1161
#[non_exhaustive]
1162
pub struct PushNotificationRoom {
1163
    pub room_id: OwnedRoomId,
1164
    pub name: String,
1165
    pub avatar_url: Option<MediaId>,
1166
    pub canonical_alias: Option<OwnedRoomAliasId>,
1167
    pub topic: Option<String>,
1168
    pub encrypted: Option<bool>,
1169
    pub direct: bool,
1170
    pub joined_members_count: u64,
1171
    pub service_members: Vec<OwnedUserId>,
1172
    pub active_service_members_count: u64,
1173
    pub space: bool,
1174
}
1175
1176
#[derive(Clone, Debug)]
1177
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1178
pub enum PushNotificationEvent {
1179
    Timeline(Raw<AnySyncTimelineEvent>),
1180
    Invite(Raw<StrippedRoomMemberEvent>),
1181
}
1182
1183
#[derive(Clone, Debug, Eq, PartialEq)]
1184
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1185
#[non_exhaustive]
1186
pub struct RoomPowerLevels {
1187
    pub ban: i64,
1188
    pub invite: i64,
1189
    pub kick: i64,
1190
    pub redact: i64,
1191
    pub events_default: i64,
1192
    pub state_default: i64,
1193
    pub users_default: i64,
1194
    pub room_notification: i64,
1195
    pub users: Vec<(OwnedUserId, i64)>,
1196
    pub events: Vec<(String, i64)>,
1197
    /// in rooms from version 12 the creators outrank everyone and aren't listed in `users`
1198
    pub creators: Vec<OwnedUserId>,
1199
}
1200
1201
#[derive(Clone, Debug, Default, Eq, PartialEq)]
1202
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1203
#[non_exhaustive]
1204
pub struct PowerLevelChanges {
1205
    pub ban: Option<i64>,
1206
    pub invite: Option<i64>,
1207
    pub kick: Option<i64>,
1208
    pub redact: Option<i64>,
1209
    pub events_default: Option<i64>,
1210
    pub state_default: Option<i64>,
1211
    pub users_default: Option<i64>,
1212
    pub room_notification: Option<i64>,
1213
    pub room_name: Option<i64>,
1214
    pub room_avatar: Option<i64>,
1215
    pub room_topic: Option<i64>,
1216
    pub space_child: Option<i64>,
1217
    pub beacon: Option<i64>,
1218
    pub beacon_info: Option<i64>,
1219
}
1220
1221
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1222
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1223
pub enum RoomMembership {
1224
    Joined,
1225
    Invited,
1226
    Left,
1227
    Knocked,
1228
    Banned,
1229
}
1230
1231
#[derive(Clone, Debug, Default, Eq, PartialEq)]
1232
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1233
#[non_exhaustive]
1234
pub struct RoomListFilter {
1235
    pub membership: Option<RoomMembership>,
1236
    pub category: Option<RoomCategory>,
1237
    pub favourite: Option<bool>,
1238
    pub unread_only: bool,
1239
    pub search: Option<String>,
1240
}
1241
1242
impl RoomListFilter {
1243
    #[must_use]
1244
    pub fn with_membership(mut self, membership: RoomMembership) -> Self {
1245
        self.membership = Some(membership);
1246
        self
1247
    }
1248
1249
    #[must_use]
1250
    pub fn with_category(mut self, category: RoomCategory) -> Self {
1251
        self.category = Some(category);
1252
        self
1253
    }
1254
1255
    #[must_use]
1256
    pub fn with_favourite(mut self, favourite: bool) -> Self {
1257
        self.favourite = Some(favourite);
1258
        self
1259
    }
1260
1261
    #[must_use]
1262
    pub const fn with_unread_only(mut self, unread_only: bool) -> Self {
1263
        self.unread_only = unread_only;
1264
        self
1265
    }
1266
1267
    #[must_use]
1268
    pub fn with_search(mut self, search: impl Into<String>) -> Self {
1269
        self.search = Some(search.into());
1270
        self
1271
    }
1272
1273
    #[must_use]
1274
    pub fn matches(&self, room: &RoomSummary) -> bool {
1275
        self.matcher().matches(room)
1276
    }
1277
1278
    /// lowercases the search once, for filtering a whole list
1279
    #[must_use]
1280
    pub fn matcher(&self) -> RoomMatcher<'_> {
1281
        RoomMatcher {
1282
            filter: self,
1283
            search: self.search.as_deref().map(str::to_lowercase),
1284
        }
1285
    }
1286
}
1287
1288
#[derive(Debug)]
1289
pub struct RoomMatcher<'a> {
1290
    filter: &'a RoomListFilter,
1291
    search: Option<String>,
1292
}
1293
1294
impl RoomMatcher<'_> {
1295
    #[must_use]
1296
    pub fn matches(&self, room: &RoomSummary) -> bool {
1297
        let filter = self.filter;
1298
        filter
1299
            .membership
1300
            .is_none_or(|membership| room.membership == membership)
1301
            && filter.category.is_none_or(|category| match category {
1302
                RoomCategory::People => room.direct && !room.space,
1303
                RoomCategory::Rooms => !room.direct && !room.space,
1304
                RoomCategory::Spaces => room.space,
1305
            })
1306
            && filter
1307
                .favourite
1308
                .is_none_or(|favourite| room.favourite == favourite)
1309
            && (!filter.unread_only || room.unread_messages > 0 || room.unread_mentions > 0)
1310
            && self.search.as_ref().is_none_or(|search| {
1311
                room.name.to_lowercase().contains(search)
1312
                    || room.room_id.as_str().to_lowercase().contains(search)
1313
            })
1314
    }
1315
}
1316
1317
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1318
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1319
#[non_exhaustive]
1320
pub enum RoomCategory {
1321
    People,
1322
    Rooms,
1323
    Spaces,
1324
}
1325
1326
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1327
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1328
#[non_exhaustive]
1329
pub enum MemberFilter {
1330
    Active,
1331
    Joined,
1332
    Invited,
1333
    Banned,
1334
    Left,
1335
    All,
1336
}
1337
1338
#[derive(Clone, Debug, Eq, PartialEq)]
1339
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1340
pub enum MemberMembership {
1341
    Joined,
1342
    Invited,
1343
    Left,
1344
    Knocked,
1345
    Banned,
1346
    Custom(String),
1347
}
1348
1349
#[derive(Clone, Debug, Eq, PartialEq)]
1350
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1351
#[non_exhaustive]
1352
pub struct MemberSummary {
1353
    pub user_id: OwnedUserId,
1354
    pub name: String,
1355
    pub display_name: Option<String>,
1356
    pub avatar: Option<MediaId>,
1357
    pub membership: MemberMembership,
1358
    pub own: bool,
1359
    pub name_ambiguous: bool,
1360
    pub ignored: bool,
1361
    pub service: bool,
1362
}
1363
1364
#[derive(Clone, Debug, Eq, PartialEq)]
1365
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1366
#[non_exhaustive]
1367
pub struct OwnDevice {
1368
    pub device_id: OwnedDeviceId,
1369
    pub display_name: Option<String>,
1370
    pub last_seen_ip: Option<String>,
1371
    pub last_seen_timestamp_ms: Option<u64>,
1372
    pub current: bool,
1373
}
1374
1375
#[derive(Clone, Debug, Eq, PartialEq)]
1376
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1377
pub enum TimelineItem {
1378
    Event(Box<TimelineEvent>),
1379
    DayDivider { timestamp_ms: u64 },
1380
    ReadMarker,
1381
    TimelineStart,
1382
}
1383
1384
#[derive(Clone, Debug, Eq, PartialEq)]
1385
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1386
pub enum TimelineDiff {
1387
    Append { values: Vec<TimelineItem> },
1388
    Clear,
1389
    PushFront { value: TimelineItem },
1390
    PushBack { value: TimelineItem },
1391
    PopFront,
1392
    PopBack,
1393
    Insert { index: usize, value: TimelineItem },
1394
    Set { index: usize, value: TimelineItem },
1395
    Remove { index: usize },
1396
    Truncate { length: usize },
1397
    Reset { values: Vec<TimelineItem> },
1398
}
1399
1400
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
1401
#[error("timeline diff is incompatible with the current {length}-item snapshot")]
1402
pub struct TimelineDiffError {
1403
    pub length: usize,
1404
}
1405
1406
impl TimelineDiff {
1407
    /// Apply a diff only when its indices match the current snapshot.
1408
    /// On error the snapshot is unchanged; request `TimelineCommand::Resync`
1409
    /// and ignore further diffs until the corresponding `TimelineReset`.
1410
    pub fn try_apply(self, items: &mut Vector<TimelineItem>) -> Result<(), TimelineDiffError> {
1411
        let length = items.len();
1412
        if self.length_after(length).is_none() {
1413
            return Err(TimelineDiffError { length });
1414
        }
1415
        self.apply(items);
1416
        Ok(())
1417
    }
1418
1419
    /// a whole `TimelineChanged` or none of it. whether a diff fits depends only on the
1420
    /// length before it, so the batch is checked against lengths alone before anything
1421
    /// moves. the error carries the length the snapshot would have had at the misfit
1422
    pub fn try_apply_all(
1423
        diffs: Vec<Self>,
1424
        items: &mut Vector<TimelineItem>,
1425
    ) -> Result<(), TimelineDiffError> {
1426
        diffs.iter().try_fold(items.len(), |length, diff| {
1427
            diff.length_after(length)
1428
                .ok_or(TimelineDiffError { length })
1429
        })?;
1430
        for diff in diffs {
1431
            diff.apply(items);
1432
        }
1433
        Ok(())
1434
    }
1435
1436
    fn length_after(&self, length: usize) -> Option<usize> {
1437
        match self {
1438
            Self::Append { values } => Some(length + values.len()),
1439
            Self::Clear => Some(0),
1440
            Self::PushFront { .. } | Self::PushBack { .. } => Some(length + 1),
1441
            Self::PopFront | Self::PopBack => length.checked_sub(1),
1442
            Self::Insert { index, .. } => (*index <= length).then_some(length + 1),
1443
            Self::Set { index, .. } => (*index < length).then_some(length),
1444
            Self::Remove { index } => (*index < length).then(|| length - 1),
1445
            Self::Truncate { length: target } => (*target <= length).then_some(*target),
1446
            Self::Reset { values } => Some(values.len()),
1447
        }
1448
    }
1449
1450
    fn apply(self, items: &mut Vector<TimelineItem>) {
1451
        match self {
1452
            Self::Append { values } => items.extend(values),
1453
            Self::Clear => items.clear(),
1454
            Self::PushFront { value } => items.push_front(value),
1455
            Self::PushBack { value } => items.push_back(value),
1456
            Self::PopFront => {
1457
                items.pop_front();
1458
            }
1459
            Self::PopBack => {
1460
                items.pop_back();
1461
            }
1462
            Self::Insert { index, value } => items.insert(index, value),
1463
            Self::Set { index, value } => {
1464
                items.set(index, value);
1465
            }
1466
            Self::Remove { index } => {
1467
                items.remove(index);
1468
            }
1469
            Self::Truncate { length } => items.truncate(length),
1470
            Self::Reset { values } => *items = values.into_iter().collect(),
1471
        }
1472
    }
1473
}
1474
1475
#[cfg(test)]
1476
mod tests {
1477
    use imbl::{Vector, vector};
1478
1479
    use super::{TimelineDiff, TimelineItem};
1480
1481
    fn item(timestamp_ms: u64) -> TimelineItem {
1482
        TimelineItem::DayDivider { timestamp_ms }
1483
    }
1484
1485
    #[test]
1486
    fn timeline_diff_try_apply_handles_every_variant() {
1487
        let mut items = vector![item(1), item(2)];
1488
1489
        TimelineDiff::Append {
1490
            values: vec![item(3)],
1491
        }
1492
        .try_apply(&mut items)
1493
        .unwrap();
1494
        assert_eq!(items, vector![item(1), item(2), item(3)]);
1495
1496
        TimelineDiff::Clear.try_apply(&mut items).unwrap();
1497
        assert!(items.is_empty());
1498
1499
        TimelineDiff::PushFront { value: item(2) }
1500
            .try_apply(&mut items)
1501
            .unwrap();
1502
        TimelineDiff::PushBack { value: item(3) }
1503
            .try_apply(&mut items)
1504
            .unwrap();
1505
        assert_eq!(items, vector![item(2), item(3)]);
1506
1507
        TimelineDiff::PopFront.try_apply(&mut items).unwrap();
1508
        TimelineDiff::PopBack.try_apply(&mut items).unwrap();
1509
        assert!(items.is_empty());
1510
1511
        TimelineDiff::Reset {
1512
            values: vec![item(1), item(3)],
1513
        }
1514
        .try_apply(&mut items)
1515
        .unwrap();
1516
        TimelineDiff::Insert {
1517
            index: 1,
1518
            value: item(2),
1519
        }
1520
        .try_apply(&mut items)
1521
        .unwrap();
1522
        assert_eq!(items, vector![item(1), item(2), item(3)]);
1523
1524
        TimelineDiff::Set {
1525
            index: 1,
1526
            value: item(4),
1527
        }
1528
        .try_apply(&mut items)
1529
        .unwrap();
1530
        assert_eq!(items, vector![item(1), item(4), item(3)]);
1531
1532
        TimelineDiff::Remove { index: 1 }
1533
            .try_apply(&mut items)
1534
            .unwrap();
1535
        assert_eq!(items, vector![item(1), item(3)]);
1536
1537
        TimelineDiff::Truncate { length: 1 }
1538
            .try_apply(&mut items)
1539
            .unwrap();
1540
        assert_eq!(items, vector![item(1)]);
1541
    }
1542
1543
    #[test]
1544
    fn invalid_timeline_diff_leaves_snapshot_unchanged() {
1545
        let invalid = [
1546
            TimelineDiff::Insert {
1547
                index: 3,
1548
                value: item(3),
1549
            },
1550
            TimelineDiff::Set {
1551
                index: 2,
1552
                value: item(3),
1553
            },
1554
            TimelineDiff::Remove { index: 2 },
1555
            TimelineDiff::Truncate { length: 3 },
1556
        ];
1557
        for diff in invalid {
1558
            let mut items = vector![item(1), item(2)];
1559
            assert_eq!(diff.try_apply(&mut items).unwrap_err().length, 2);
1560
            assert_eq!(items, vector![item(1), item(2)]);
1561
        }
1562
        for diff in [TimelineDiff::PopFront, TimelineDiff::PopBack] {
1563
            let mut items = Vector::new();
1564
            assert_eq!(diff.try_apply(&mut items).unwrap_err().length, 0);
1565
            assert!(items.is_empty());
1566
        }
1567
    }
1568
1569
    #[test]
1570
    fn a_batch_that_goes_wrong_halfway_changes_nothing() {
1571
        let mut items = vector![item(1), item(2)];
1572
        let batch = vec![
1573
            TimelineDiff::PushBack { value: item(3) },
1574
            TimelineDiff::PushBack { value: item(4) },
1575
            TimelineDiff::Remove { index: 0 },
1576
            TimelineDiff::Set {
1577
                index: 3,
1578
                value: item(5),
1579
            },
1580
        ];
1581
        assert_eq!(
1582
            TimelineDiff::try_apply_all(batch, &mut items)
1583
                .unwrap_err()
1584
                .length,
1585
            3
1586
        );
1587
        assert_eq!(items, vector![item(1), item(2)]);
1588
1589
        let batch = vec![
1590
            TimelineDiff::PushBack { value: item(3) },
1591
            TimelineDiff::Remove { index: 0 },
1592
            TimelineDiff::Set {
1593
                index: 1,
1594
                value: item(4),
1595
            },
1596
        ];
1597
        TimelineDiff::try_apply_all(batch, &mut items).unwrap();
1598
        assert_eq!(items, vector![item(2), item(4)]);
1599
    }
1600
}
1601
1602
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1603
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1604
pub struct TimelineItemId(String);
1605
1606
impl TimelineItemId {
1607
    pub(crate) fn new(value: String) -> Self {
1608
        Self(value)
1609
    }
1610
1611
    #[must_use]
1612
    pub fn as_str(&self) -> &str {
1613
        &self.0
1614
    }
1615
}
1616
1617
#[derive(Clone, Debug, Eq, PartialEq)]
1618
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1619
#[non_exhaustive]
1620
pub struct TimelineEvent {
1621
    pub item_id: TimelineItemId,
1622
    pub event_id: Option<OwnedEventId>,
1623
    pub transaction_id: Option<OwnedTransactionId>,
1624
    pub sender: Sender,
1625
    pub timestamp_ms: u64,
1626
    pub own: bool,
1627
    pub send_state: SendState,
1628
    pub content: TimelineContent,
1629
    pub reply_to: Option<ReplyReference>,
1630
    pub thread_root: Option<OwnedEventId>,
1631
    pub thread_summary: Option<ThreadSummary>,
1632
    pub reactions: Vec<Reaction>,
1633
    pub read_by: Vec<OwnedUserId>,
1634
    pub editable: bool,
1635
}
1636
1637
impl TimelineEvent {
1638
    /// what to hand edit, redact and react. works before the server has echoed it back
1639
    #[must_use]
1640
    pub fn target(&self) -> Option<EventRef> {
1641
        self.event_id
1642
            .clone()
1643
            .map(EventRef::Remote)
1644
            .or_else(|| self.transaction_id.clone().map(EventRef::Local))
1645
    }
1646
}
1647
1648
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1649
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1650
#[non_exhaustive]
1651
pub enum EventRef {
1652
    Remote(OwnedEventId),
1653
    /// a local echo, by the transaction id it was queued under
1654
    Local(OwnedTransactionId),
1655
}
1656
1657
impl From<OwnedEventId> for EventRef {
1658
    fn from(event_id: OwnedEventId) -> Self {
1659
        Self::Remote(event_id)
1660
    }
1661
}
1662
1663
#[derive(Clone, Debug, Eq, PartialEq)]
1664
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1665
#[non_exhaustive]
1666
pub struct Sender {
1667
    pub user_id: OwnedUserId,
1668
    pub display_name: Option<String>,
1669
    pub avatar: Option<MediaId>,
1670
    /// someone else in the room goes by the same name, so show the user id too
1671
    pub name_ambiguous: bool,
1672
}
1673
1674
impl Sender {
1675
    #[must_use]
1676
    pub fn name(&self) -> &str {
1677
        self.display_name
1678
            .as_deref()
1679
            .unwrap_or_else(|| self.user_id.as_str())
1680
    }
1681
}
1682
1683
#[derive(Clone, Debug, Eq, PartialEq)]
1684
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1685
pub enum TimelineContent {
1686
    Message(Message),
1687
    Sticker {
1688
        body: String,
1689
        media: MediaDescriptor,
1690
    },
1691
    Poll {
1692
        question: String,
1693
    },
1694
    Redacted,
1695
    UnableToDecrypt(UtdCause),
1696
    Membership {
1697
        user_id: OwnedUserId,
1698
        display_name: Option<String>,
1699
        change: MembershipChange,
1700
    },
1701
    Profile {
1702
        user_id: OwnedUserId,
1703
        display_name: Option<Change<Option<String>>>,
1704
        avatar: Option<Change<Option<MediaId>>>,
1705
    },
1706
    /// `None` means it was cleared, or the event was redacted
1707
    RoomName(Option<String>),
1708
    RoomTopic(Option<String>),
1709
    RoomAvatar(Option<MediaId>),
1710
    EncryptionEnabled,
1711
    RoomCreated,
1712
    RoomUpgraded {
1713
        successor: OwnedRoomId,
1714
    },
1715
    OtherState {
1716
        event_type: String,
1717
        state_key: String,
1718
    },
1719
    Other {
1720
        event_type: String,
1721
    },
1722
}
1723
1724
#[derive(Clone, Debug, Eq, PartialEq)]
1725
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1726
#[non_exhaustive]
1727
pub struct Message {
1728
    pub kind: MessageKind,
1729
    pub body: String,
1730
    /// only for `MessageKind::Location`
1731
    pub geo_uri: Option<String>,
1732
    pub formatted_body: Option<String>,
1733
    pub mentions: Option<MessageMentions>,
1734
    pub edited: bool,
1735
    pub media: Option<MediaDescriptor>,
1736
    /// previews the sender attached (msc4095), so showing them asks no one about the url.
1737
    /// one for a url the body doesn't contain is dropped
1738
    pub link_previews: Vec<LinkPreview>,
1739
}
1740
1741
/// a link card, from the sender's own message or from `ClientHandle::url_preview`. page
1742
/// text passes through whoever made it unfiltered, so it arrives trimmed to a sane length
1743
#[derive(Clone, Debug, Eq, PartialEq)]
1744
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1745
#[non_exhaustive]
1746
pub struct LinkPreview {
1747
    /// the url as it appears in the message, or as it was asked about
1748
    pub url: String,
1749
    /// where the page says it lives, when that's somewhere else
1750
    pub canonical_url: Option<String>,
1751
    pub title: Option<String>,
1752
    pub description: Option<String>,
1753
    pub site_name: Option<String>,
1754
    pub image: Option<LinkPreviewImage>,
1755
}
1756
1757
#[derive(Clone, Debug, Eq, PartialEq)]
1758
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1759
#[non_exhaustive]
1760
pub struct LinkPreviewImage {
1761
    pub media_id: MediaId,
1762
    pub mimetype: Option<String>,
1763
    pub size_bytes: Option<u64>,
1764
    pub width: Option<u64>,
1765
    pub height: Option<u64>,
1766
}
1767
1768
#[derive(Clone, Debug, Eq, PartialEq)]
1769
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1770
pub enum MessageKind {
1771
    Text,
1772
    Emote,
1773
    Notice,
1774
    ServerNotice,
1775
    Image,
1776
    Video,
1777
    Audio,
1778
    File,
1779
    Location,
1780
    VerificationRequest,
1781
    Other(String),
1782
}
1783
1784
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1785
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1786
pub enum MembershipChange {
1787
    Joined,
1788
    Left,
1789
    Banned,
1790
    Unbanned,
1791
    Kicked,
1792
    KickedAndBanned,
1793
    Invited,
1794
    InvitationAccepted,
1795
    InvitationRejected,
1796
    InvitationRevoked,
1797
    Knocked,
1798
    KnockAccepted,
1799
    KnockRetracted,
1800
    KnockDenied,
1801
    /// nothing a person would call a change, or something the sdk couldn't make sense of
1802
    Other,
1803
}
1804
1805
#[derive(Clone, Debug, Eq, PartialEq)]
1806
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1807
pub struct Change<T> {
1808
    pub old: T,
1809
    pub new: T,
1810
}
1811
1812
/// why a message couldn't be read, worth telling the user since some of these they can fix
1813
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1814
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1815
pub enum UtdCause {
1816
    Unknown,
1817
    SentBeforeWeJoined,
1818
    VerificationViolation,
1819
    UnsignedDevice,
1820
    UnknownDevice,
1821
    HistoricalMessageAndBackupIsDisabled,
1822
    WithheldForUnverifiedOrInsecureDevice,
1823
    WithheldBySender,
1824
    HistoricalMessageAndDeviceIsUnverified,
1825
}
1826
1827
#[derive(Clone, Debug, Eq, PartialEq)]
1828
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1829
#[non_exhaustive]
1830
pub struct ThreadSummary {
1831
    pub reply_count: u32,
1832
    pub latest_event_id: Option<OwnedEventId>,
1833
    pub latest_event_timestamp_ms: Option<u64>,
1834
}
1835
1836
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1837
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1838
pub enum SendState {
1839
    Sent,
1840
    Sending,
1841
    /// `will_retry` means macltok has it in hand. otherwise it's wedged until you
1842
    /// `retry_send` or `cancel_send`, so that's when to show a retry button
1843
    Failed {
1844
        will_retry: bool,
1845
    },
1846
}
1847
1848
#[derive(Clone, Debug, Eq, PartialEq)]
1849
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1850
#[non_exhaustive]
1851
pub struct ReplyReference {
1852
    pub event_id: OwnedEventId,
1853
    pub details: ReplyDetails,
1854
}
1855
1856
/// the replied-to event. macltok asks for it when it isn't loaded, `Pending` then turns into one of the others
1857
#[derive(Clone, Debug, Eq, PartialEq)]
1858
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1859
pub enum ReplyDetails {
1860
    Pending,
1861
    Ready {
1862
        sender: Sender,
1863
        content: Box<TimelineContent>,
1864
        timestamp_ms: u64,
1865
    },
1866
    Unavailable,
1867
}
1868
1869
#[derive(Clone, Debug, Eq, PartialEq)]
1870
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1871
#[non_exhaustive]
1872
pub struct Reaction {
1873
    pub key: String,
1874
    /// a custom emote's shortcode, from whichever sender gave one
1875
    pub shortcode: Option<String>,
1876
    /// the custom emote itself, when the key is an image
1877
    pub image: Option<MediaId>,
1878
    pub count: usize,
1879
    pub own: bool,
1880
    pub senders: Vec<OwnedUserId>,
1881
}
1882
1883
/// every custom emote and sticker pack the account can reach, from the user's own
1884
/// pack, each joined room's packs, and the rooms the user enabled everywhere
1885
#[derive(Clone, Debug, Default, Eq, PartialEq)]
1886
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1887
#[non_exhaustive]
1888
pub struct ImagePacks {
1889
    /// the user's own pack, then the packs of rooms enabled everywhere
1890
    pub global: Vec<ImagePack>,
1891
    /// each joined room's own packs, rooms without any left out
1892
    pub rooms: imbl::HashMap<OwnedRoomId, Vec<ImagePack>>,
1893
}
1894
1895
impl ImagePacks {
1896
    /// what a picker in this room offers. the user's pack, the room's own, then the
1897
    /// rest of the enabled ones, each pack once
1898
    #[must_use]
1899
    pub fn for_room(&self, room_id: Option<&RoomId>) -> Vec<&ImagePack> {
1900
        let is_user = |pack: &&ImagePack| pack.source == ImagePackSource::User;
1901
        let own = room_id.and_then(|room_id| self.rooms.get(room_id));
1902
        let mut packs: Vec<&ImagePack> = self.global.iter().filter(is_user).collect();
1903
        packs.extend(own.into_iter().flatten());
1904
        for pack in self.global.iter().filter(|pack| !is_user(pack)) {
1905
            if !packs.iter().any(|seen| seen.id == pack.id) {
1906
                packs.push(pack);
1907
            }
1908
        }
1909
        packs
1910
    }
1911
}
1912
1913
#[derive(Clone, Debug, Eq, PartialEq)]
1914
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1915
#[non_exhaustive]
1916
pub struct ImagePack {
1917
    /// `user`, or `room:<room id>:<state key>`, the same across calls
1918
    pub id: String,
1919
    pub display_name: Option<String>,
1920
    pub avatar: Option<MediaId>,
1921
    pub attribution: Option<String>,
1922
    pub source: ImagePackSource,
1923
    pub images: Vec<PackImage>,
1924
    /// your own pack, or a room pack whose state you're allowed to send
1925
    pub editable: bool,
1926
    /// listed in im.ponies.emote_rooms. always true for your own pack
1927
    pub enabled_everywhere: bool,
1928
}
1929
1930
#[derive(Clone, Debug, Eq, PartialEq)]
1931
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1932
pub enum ImagePackSource {
1933
    User,
1934
    Room {
1935
        room_id: OwnedRoomId,
1936
        state_key: String,
1937
    },
1938
}
1939
1940
#[derive(Clone, Debug, Eq, PartialEq)]
1941
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1942
#[non_exhaustive]
1943
pub struct PackImage {
1944
    pub shortcode: String,
1945
    pub media_id: MediaId,
1946
    /// what `toggle_reaction` takes to react with this image
1947
    pub reaction_key: String,
1948
    pub body: Option<String>,
1949
    pub mimetype: Option<String>,
1950
    pub width: Option<u64>,
1951
    pub height: Option<u64>,
1952
    /// the image's own, else its pack's, else both
1953
    pub usage: Vec<PackUsage>,
1954
}
1955
1956
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1957
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1958
pub enum PackUsage {
1959
    Emoticon,
1960
    Sticker,
1961
}
1962
1963
#[derive(Clone, Debug, Eq, PartialEq)]
1964
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1965
#[non_exhaustive]
1966
pub struct MediaDescriptor {
1967
    pub id: MediaId,
1968
    pub kind: MediaKind,
1969
    /// only for unencrypted media, an encrypted file's mxc is ciphertext without the keys
1970
    pub mxc: Option<OwnedMxcUri>,
1971
    pub filename: String,
1972
    pub caption: Option<String>,
1973
    pub mimetype: Option<String>,
1974
    pub size_bytes: Option<u64>,
1975
    pub width: Option<u64>,
1976
    pub height: Option<u64>,
1977
    pub duration_ms: Option<u64>,
1978
    pub blurhash: Option<String>,
1979
    /// the uploader sent a thumbnail, so `MediaSize::Thumbnail` won't need the server to resize
1980
    pub has_thumbnail: bool,
1981
}
1982
1983
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1984
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1985
pub struct MediaId(String);
1986
1987
impl MediaId {
1988
    pub(crate) fn new(value: String) -> Self {
1989
        Self(value)
1990
    }
1991
1992
    /// plain media carries no keys, so it needs no registering and never expires
1993
    pub(crate) fn plain<U: AsRef<str> + ?Sized>(uri: &U) -> Self {
1994
        Self(uri.as_ref().to_owned())
1995
    }
1996
1997
    pub(crate) fn as_plain(&self) -> Option<&MxcUri> {
1998
        self.0.starts_with("mxc://").then(|| self.0.as_str().into())
1999
    }
2000
2001
    #[must_use]
2002
    pub fn as_str(&self) -> &str {
2003
        &self.0
2004
    }
2005
}
2006
2007
/// media ids are opaque but they do have to survive a trip through a browser. a made up one just fails `MediaUnknown`
2008
impl std::str::FromStr for MediaId {
2009
    type Err = std::convert::Infallible;
2010
2011
    fn from_str(value: &str) -> Result<Self, Self::Err> {
2012
        Ok(Self(value.to_owned()))
2013
    }
2014
}
2015
2016
impl From<String> for MediaId {
2017
    fn from(value: String) -> Self {
2018
        Self(value)
2019
    }
2020
}
2021
2022
impl std::fmt::Display for MediaId {
2023
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2024
        self.0.fmt(formatter)
2025
    }
2026
}
2027
2028
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
2029
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2030
#[non_exhaustive]
2031
pub enum MediaSize {
2032
    Full,
2033
    /// a hint. an uploader's own thumbnail wins over the server resizing anything
2034
    Thumbnail {
2035
        width: u32,
2036
        height: u32,
2037
    },
2038
}
2039
2040
#[derive(Clone, Debug, Eq, PartialEq)]
2041
#[non_exhaustive]
2042
pub struct Media {
2043
    pub bytes: Arc<[u8]>,
2044
    pub mimetype: String,
2045
}
2046
2047
/// where media lives, for a host that fetches and decrypts it itself
2048
#[derive(Clone, Debug, Eq, PartialEq)]
2049
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2050
pub enum MediaLocation {
2051
    File(MediaFile),
2052
    /// a resize of plaintext, so never encrypted. plenty of servers refuse some, and `media`
2053
    /// then fetches `fallback` instead, so should you
2054
    ServerThumbnail {
2055
        url: String,
2056
        fallback: MediaFile,
2057
    },
2058
    /// still in the send queue with no url yet. `media` has the bytes
2059
    Local,
2060
}
2061
2062
#[derive(Clone, Debug, Eq, PartialEq)]
2063
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2064
#[non_exhaustive]
2065
pub struct MediaFile {
2066
    pub url: String,
2067
    pub mimetype: Option<String>,
2068
    pub declared_size: Option<u64>,
2069
    pub encryption: Option<AttachmentEncryption>,
2070
}
2071
2072
/// AES-256-CTR, the only attachment cipher matrix has
2073
#[derive(Clone, Debug, Eq, PartialEq)]
2074
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2075
#[non_exhaustive]
2076
pub struct AttachmentEncryption {
2077
    /// the JWK `k`, unpadded url-safe base64
2078
    pub key: String,
2079
    /// unpadded base64, the initial counter block
2080
    pub iv: String,
2081
    /// unpadded base64 SHA-256 of the whole ciphertext, so a partial read goes unchecked
2082
    pub sha256: String,
2083
}
2084
2085
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2086
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2087
pub enum MediaKind {
2088
    Image,
2089
    Video,
2090
    Audio,
2091
    File,
2092
    Sticker,
2093
}
2094
2095
#[derive(Clone, Debug, Eq, PartialEq)]
2096
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2097
#[non_exhaustive]
2098
pub struct TypingState {
2099
    pub room_id: OwnedRoomId,
2100
    pub users: Vec<OwnedUserId>,
2101
}
2102
2103
#[derive(Clone, Debug, Eq, PartialEq)]
2104
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2105
pub enum HistoryState {
2106
    Idle,
2107
    Loading,
2108
    StartReached,
2109
    Failed(String),
2110
}
2111
2112
#[derive(Clone, Debug, Eq, PartialEq)]
2113
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2114
#[non_exhaustive]
2115
pub struct EncryptionState {
2116
    pub device_id: OwnedDeviceId,
2117
    pub device_verified: bool,
2118
    pub recovery: RecoveryState,
2119
    pub key_backup: KeyBackupState,
2120
}
2121
2122
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2123
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2124
pub enum KeyBackupState {
2125
    Unknown,
2126
    Creating,
2127
    Enabling,
2128
    Resuming,
2129
    Downloading,
2130
    Enabled,
2131
    Disabling,
2132
}
2133
2134
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2135
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2136
pub enum RecoveryState {
2137
    Unknown,
2138
    Disabled,
2139
    Incomplete,
2140
    Enabled,
2141
}
2142
2143
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2144
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2145
#[non_exhaustive]
2146
pub enum VerificationAction {
2147
    /// take up a request another device sent, which arrives as `VerificationState::Incoming`
2148
    Accept,
2149
    Confirm,
2150
    Reject,
2151
    Cancel,
2152
}
2153
2154
#[derive(Clone, Debug, Eq, PartialEq)]
2155
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2156
#[non_exhaustive]
2157
pub enum VerificationTarget {
2158
    OwnIdentity,
2159
    User(OwnedUserId),
2160
    Device {
2161
        user_id: OwnedUserId,
2162
        device_id: OwnedDeviceId,
2163
    },
2164
}
2165
2166
#[derive(Clone, Debug, Eq, PartialEq)]
2167
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2168
pub enum VerificationState {
2169
    Waiting,
2170
    /// someone else asked. `Accept` to go ahead, `Cancel` to turn them down
2171
    Incoming {
2172
        user_id: OwnedUserId,
2173
        device_id: Option<OwnedDeviceId>,
2174
    },
2175
    Comparison {
2176
        emojis: Vec<(String, String)>,
2177
        decimals: (u16, u16, u16),
2178
    },
2179
    Confirmed,
2180
    Done,
2181
    Cancelled(String),
2182
    Failed(VerificationFailure),
2183
}
2184
2185
#[derive(Clone, Debug, Eq, PartialEq)]
2186
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2187
pub enum VerificationFailure {
2188
    RequestAcceptance(String),
2189
    SasStartup(String),
2190
    SasAcceptance(String),
2191
    RequestStreamEnded,
2192
    SasStreamEnded,
2193
}
2194
2195
#[derive(Clone, Debug, Eq, PartialEq)]
2196
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2197
#[non_exhaustive]
2198
pub struct EngineFailure {
2199
    pub kind: EngineErrorKind,
2200
    pub message: String,
2201
}
2202
2203
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2204
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2205
pub enum EngineErrorKind {
2206
    EventReceiverClosed,
2207
    Watcher,
2208
    Other,
2209
}