lamprey-common 0.1.1

yet another chat thing?
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
use serde::{Deserialize, Serialize};

#[cfg(feature = "utoipa")]
use utoipa::{IntoParams, ToSchema};

use crate::v1::types::{
    application::Connection, user_status::StatusPatch, util::Time, webhook::Webhook, ApplicationId,
    AuditLogEntry, CalendarEventId, InviteTargetId, InviteWithMetadata, Relationship, RoomBan,
    ThreadMember, WebhookId,
};

use super::{
    calendar::CalendarEvent,
    emoji::EmojiCustom,
    notifications::{Notification, NotificationFlush, NotificationMarkRead},
    reaction::ReactionKey,
    role::RoleReorderItem,
    user_config::{UserConfigChannel, UserConfigGlobal, UserConfigRoom, UserConfigUser},
    voice::{SignallingMessage, VoiceState},
    Channel, ChannelId, EmojiId, InviteCode, Message, MessageId, MessageVerId, Role, RoleId, Room,
    RoomId, RoomMember, Session, SessionId, SessionToken, User, UserId,
};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[serde(tag = "type")]
pub enum MessageClient {
    /// initial message
    Hello {
        token: SessionToken,

        status: Option<StatusPatch>,

        #[serde(flatten)]
        resume: Option<SyncResume>,
    },

    /// set status
    Status { status: StatusPatch },

    /// heartbeat
    Pong,

    /// send arbitrary data to a voice server
    // NOTE: should i split this into multiple messages? i'll probably keep it how it is currently tbh
    // TODO: handle multiple connections/servers (or find out how to split one connection amongst multiple hosts?)
    VoiceDispatch {
        user_id: UserId,
        payload: SignallingMessage,
    },

    /// subscribe to a range of room or thread members. you can subscribe to one list at a time.
    MemberListSubscribe {
        // TODO: rename thread_id -> channel_id
        // one of room_id or thread_id must be provided
        room_id: Option<RoomId>,
        thread_id: Option<ChannelId>,

        /// the ranges to subscribe to
        ranges: Vec<(u64, u64)>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct SyncResume {
    pub conn: String,
    pub seq: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct MessageEnvelope {
    #[serde(flatten)]
    pub payload: MessagePayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[serde(tag = "op")]
pub enum MessagePayload {
    /// heartbeat
    Ping,

    /// data to keep local copy of state in sync with server
    Sync { data: Box<MessageSync>, seq: u64 },

    /// some kind of error
    Error { error: String },

    /// successfully connected
    Ready {
        /// current user, null if session is unauthed
        user: Box<Option<User>>,

        /// current session
        session: Session,

        /// connection id
        conn: String,

        /// sequence id for reconnecting
        seq: u64,
    },

    /// successfully reconnected
    Resumed,

    /// client needs to disconnect and reconnect
    Reconnect { can_resume: bool },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[serde(tag = "type")]
pub enum MessageSync {
    RoomCreate {
        room: Room,
    },

    RoomUpdate {
        room: Room,
    },

    RoomDelete {
        room_id: RoomId,
    },

    ChannelCreate {
        channel: Box<Channel>,
    },

    ChannelUpdate {
        channel: Box<Channel>,
    },

    ChannelTyping {
        channel_id: ChannelId,
        user_id: UserId,
        until: Time,
    },

    /// read receipt update
    ChannelAck {
        user_id: UserId,
        channel_id: ChannelId,
        message_id: MessageId,
        version_id: MessageVerId,
    },

    MessageCreate {
        message: Message,
    },

    MessageUpdate {
        message: Message,
    },

    MessageDelete {
        channel_id: ChannelId,
        message_id: MessageId,
    },

    MessageVersionDelete {
        channel_id: ChannelId,
        message_id: MessageId,
        version_id: MessageVerId,
    },

    /// delete multiple messages at once
    MessageDeleteBulk {
        channel_id: ChannelId,
        message_ids: Vec<MessageId>,
    },

    MessageRemove {
        channel_id: ChannelId,
        message_ids: Vec<MessageId>,
    },

    MessageRestore {
        channel_id: ChannelId,
        // NOTE: if messages are not returned for listing endpoints, i should return a vec of Messages insetad
        message_ids: Vec<MessageId>,
    },

    RoomMemberUpsert {
        member: RoomMember,
    },

    ThreadMemberUpsert {
        member: ThreadMember,
    },

    RoleCreate {
        role: Role,
    },

    RoleUpdate {
        role: Role,
    },

    RoleDelete {
        room_id: RoomId,
        role_id: RoleId,
    },

    RoleReorder {
        room_id: RoomId,
        roles: Vec<RoleReorderItem>,
    },

    InviteCreate {
        invite: InviteWithMetadata,
    },

    InviteUpdate {
        invite: InviteWithMetadata,
    },

    InviteDelete {
        code: InviteCode,
        target: InviteTargetId,
    },

    ReactionCreate {
        user_id: UserId,
        channel_id: ChannelId,
        message_id: MessageId,
        key: ReactionKey,
    },

    ReactionDelete {
        user_id: UserId,
        channel_id: ChannelId,
        message_id: MessageId,
        key: ReactionKey,
    },

    /// remove all reactions
    ReactionPurge {
        channel_id: ChannelId,
        message_id: MessageId,
    },

    EmojiCreate {
        emoji: EmojiCustom,
    },

    EmojiUpdate {
        emoji: EmojiCustom,
    },

    EmojiDelete {
        emoji_id: EmojiId,
        room_id: RoomId,
    },

    /// receive a signalling message from a voice server
    VoiceDispatch {
        /// who to send this dispatch to
        user_id: UserId,
        payload: SignallingMessage,
    },

    VoiceState {
        user_id: UserId,
        state: Option<VoiceState>,

        // HACK: make it possible to use this for auth checks
        #[serde(skip)]
        old_state: Option<VoiceState>,
    },

    UserCreate {
        user: User,
    },

    UserUpdate {
        user: User,
    },

    // TODO: rename these UserConfig -> Config
    UserConfigGlobal {
        user_id: UserId,
        config: UserConfigGlobal,
    },

    UserConfigRoom {
        user_id: UserId,
        room_id: RoomId,
        config: UserConfigRoom,
    },

    UserConfigChannel {
        user_id: UserId,
        channel_id: ChannelId,
        config: UserConfigChannel,
    },

    UserConfigUser {
        user_id: UserId,
        target_user_id: UserId,
        config: UserConfigUser,
    },

    UserDelete {
        id: UserId,
    },

    SessionCreate {
        session: Session,
    },

    SessionUpdate {
        session: Session,
    },

    SessionDelete {
        id: SessionId,
        user_id: Option<UserId>,
    },

    RelationshipUpsert {
        user_id: UserId,
        target_user_id: UserId,
        relationship: Relationship,
    },

    RelationshipDelete {
        user_id: UserId,
        target_user_id: UserId,
    },

    ConnectionCreate {
        user_id: UserId,
        connection: Connection,
    },

    ConnectionDelete {
        user_id: UserId,
        app_id: ApplicationId,
    },

    AuditLogEntryCreate {
        entry: AuditLogEntry,
    },

    BanCreate {
        room_id: RoomId,
        ban: RoomBan,
    },

    BanDelete {
        room_id: RoomId,
        user_id: UserId,
    },

    MemberListSync {
        /// which user this list sync is for
        user_id: UserId,
        room_id: Option<RoomId>,
        channel_id: Option<ChannelId>,
        ops: Vec<MemberListOp>,
        groups: Vec<MemberListGroup>,
    },

    InboxNotificationCreate {
        user_id: UserId,
        notification: Notification,
    },

    InboxMarkRead {
        user_id: UserId,
        #[serde(flatten)]
        params: NotificationMarkRead,
    },

    InboxMarkUnread {
        user_id: UserId,
        #[serde(flatten)]
        params: NotificationMarkRead,
    },

    InboxFlush {
        user_id: UserId,
        #[serde(flatten)]
        params: NotificationFlush,
    },

    CalendarEventCreate {
        event: CalendarEvent,
    },

    CalendarEventUpdate {
        event: CalendarEvent,
    },

    CalendarEventDelete {
        channel_id: ChannelId,
        event_id: CalendarEventId,
    },

    WebhookCreate {
        webhook: Webhook,
    },

    WebhookUpdate {
        webhook: Webhook,
    },

    WebhookDelete {
        webhook_id: WebhookId,
        room_id: Option<RoomId>,
        channel_id: ChannelId,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[serde(tag = "type")]
pub enum MemberListOp {
    /// replace a range of members
    Sync {
        /// the start of the range
        position: u64,

        /// only returned if channel is in a room
        room_members: Option<Vec<RoomMember>>,

        /// only returned if listing members in a thread
        thread_members: Option<Vec<ThreadMember>>,

        users: Vec<User>,
    },

    /// insert a member
    Insert {
        position: u64,
        room_member: Option<RoomMember>,
        thread_member: Option<ThreadMember>,
        user: Box<User>,
    },

    /// delete a range of one or more members
    Delete {
        position: u64,
        // usually will be 1
        count: u64,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct MemberListGroup {
    pub id: MemberListGroupId,
    pub count: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub enum MemberListGroupId {
    /// online members without a hoisted role
    Online,

    /// offline members, including those with a role
    Offline,

    /// hoisted roles
    // TODO: implement role hoisting
    #[serde(untagged)]
    Role(RoleId),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema, IntoParams))]
pub struct SyncParams {
    pub version: SyncVersion,
    pub compression: Option<SyncCompression>,
    #[serde(default)]
    pub format: SyncFormat,
}

// i thought that putting the api version in the path would be better, but
// apparently websockets are hard to load balance. being able to use arbitrary
// urls/paths in the future could be helpful.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[repr(u8)]
pub enum SyncVersion {
    V1 = 1,
}

impl Serialize for SyncVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_u8(*self as u8)
    }
}

impl<'de> Deserialize<'de> for SyncVersion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        match u8::deserialize(deserializer)? {
            1 => Ok(SyncVersion::V1),
            n => Err(serde::de::Error::unknown_variant(&n.to_string(), &["1"])),
        }
    }
}

// TODO(#249): websocket msgpack
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub enum SyncFormat {
    #[default]
    Json,
    // Msgpack,
}

// TODO(#209): implement websocket compression
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub enum SyncCompression {
    // Zlib, // new DecompressionStream("deflate")
}