atagen

macltok

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