atagen

macltok

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