sew-proto 0.11.6

Sew wire contracts: ids, addresses, errors, HTTP and gateway bodies, permissions, policies, audit.
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
//! DM and group-DM calls: the call object, rings, the call-record
//! summary on the DM's message, the call routes' bodies and the call events.
//!
//! A call never carries a room name, a join id, an identity, a key-group id or an epoch on the
//! wire. `voice.call_id` of a join answer is the `calls.id` (this module's [`Call::id`]);
//! `voice.e2ee.call_id` is the encrypted call's room name.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::e2ee::E2eeJoin;
use crate::error::{Validate, ValidationError};
use crate::id::Id;
use crate::time::Timestamp;
use crate::voice::VoiceJoinResponse;

/// Most members a re-ring may name (a group DM holds at most 9 people).
pub const RING_TARGETS_MAX: usize = 16;
/// Most active calls in READY `calls`.
pub const READY_CALLS_MAX: usize = 100;

unit_enum! {
    /// Whether a call is live.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum CallState {
        /// Live.
        Active = "active",
        /// Over (`ended_at` and `end_reason` set).
        Ended = "ended",
    }
}

unit_enum! {
    /// A ring's state as every DM member sees it.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum RingState {
        /// Ringing.
        Ringing = "ringing",
        /// Ringing, but the callee is already in voice (a silent ring).
        Busy = "busy",
        /// The callee joined.
        Accepted = "accepted",
        /// The callee declined.
        Declined = "declined",
        /// Not answered in time, or the call ended first.
        Missed = "missed",
        /// The starter cancelled the call before anyone else joined (flag `call_cancel`); not
        /// a missed call.
        Cancelled = "cancelled",
    }
}

coded_enum! {
    /// Why a call ended. Stored in `calls.end_reason`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum CallEndReason {
        /// Nobody left in the call.
        Empty = "empty" => 1,
        /// A 1:1 callee declined.
        Declined = "declined" => 2,
        /// Nobody answered.
        NoAnswer = "no_answer" => 3,
        /// One person alone too long.
        AloneTimeout = "alone_timeout" => 4,
        /// The media engine lost the call.
        MediaRestarted = "media_restarted" => 5,
        /// The media engine failed before anyone connected.
        MediaFailed = "media_failed" => 6,
        /// Voice was turned off.
        VoiceDisabled = "voice_disabled" => 7,
        /// Nobody left who may connect.
        PermsLost = "perms_lost" => 8,
        /// The starter cancelled the call before anyone else joined (flag `call_cancel`).
        Cancelled = "cancelled" => 9,
    }
}

/// One ring of a call. Only rung members appear; the starter never does.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallRing {
    /// The callee.
    pub member_id: Id,
    /// Its state.
    pub state: RingState,
    /// When an unanswered ring becomes `missed` (only while `ringing` or `busy`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<Timestamp>,
}

/// The member's own ring in READY (`Call.my_ring`, the member's copy only).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MyRing {
    /// A silent ring (busy, DND or a muted DM).
    pub silent: bool,
    /// `busy`, `dnd` or `muted` for a silent ring.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// A call.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct Call {
    /// The call (`calls.id`).
    pub id: Id,
    /// The DM or group DM.
    pub channel_id: Id,
    /// The call-record message in the DM.
    pub message_id: Id,
    /// Who started it.
    pub started_by: Id,
    /// When.
    pub started_at: Timestamp,
    /// `active` or `ended`.
    pub state: CallState,
    /// When it ended.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<Timestamp>,
    /// Why it ended.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_reason: Option<CallEndReason>,
    /// Members with a voice entry in the call now (connecting or connected), ascending.
    pub participant_ids: Vec<Id>,
    /// Rings, by member id.
    pub rings: Vec<CallRing>,
    /// The viewer's own ring (READY, the member's copy only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub my_ring: Option<MyRing>,
}

impl Call {
    /// A `Call` with its required fields: every list empty and every optional field unset.
    pub fn new(
        id: Id,
        channel_id: Id,
        message_id: Id,
        started_by: Id,
        started_at: Timestamp,
        state: CallState,
    ) -> Self {
        Call {
            id,
            channel_id,
            message_id,
            started_by,
            started_at,
            state,
            ended_at: None,
            end_reason: None,
            participant_ids: Vec::new(),
            rings: Vec::new(),
            my_ring: None,
        }
    }
}

/// The call summary on the call-record message (`Message.call`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallSummary {
    /// The call.
    pub call_id: Id,
    /// Who started it.
    pub started_by: Id,
    /// When.
    pub started_at: Timestamp,
    /// When it ended.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<Timestamp>,
    /// `ended_at − started_at` once ended.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<u64>,
    /// Why it ended.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_reason: Option<CallEndReason>,
    /// Everyone who ever connected, the starter included, ascending.
    pub joined_ids: Vec<Id>,
    /// Everyone ever rung, ascending.
    pub rung_ids: Vec<Id>,
    /// Rings resolved `declined`.
    pub declined_ids: Vec<Id>,
    /// Rings resolved `missed` (a cancelled call's rings are not).
    pub missed_ids: Vec<Id>,
}

/// `POST /api/v1/channels/{id}/call/join` body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CallJoinRequest {
    /// Ring the other members when this join starts a call (default `true`).
    #[serde(default = "default_true")]
    pub ring: bool,
    /// Join muted.
    #[serde(default)]
    pub self_mute: bool,
    /// Join deafened (implies muted).
    #[serde(default)]
    pub self_deaf: bool,
    /// Join with a camera lease.
    #[serde(default)]
    pub self_video: bool,
    /// The key join. `None` answers `422 e2ee_unsupported_client`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub e2ee: Option<E2eeJoin>,
    /// The answer to the recording consent modal.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_notice: Option<crate::recording::RecordingNotice>,
    /// Flag `call_credential`: mint a call-scoped credential with the answer
    /// (`voice.call_credential`) and key-join later; never with `e2ee`. Sent only when `true`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub call_credential: bool,
    /// Flag `app_origins`: the web origin the browser reached the App on, as on
    /// [`crate::voice::VoiceJoinRequest::origin`]: the session App's `origin` or one of its
    /// `origins` (`422 invalid_state` `origin_not_listed` otherwise), the answer's
    /// `voice.url`. Absent: the App's `origin`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
}

fn default_true() -> bool {
    true
}

fn is_false(v: &bool) -> bool {
    !*v
}

impl Default for CallJoinRequest {
    fn default() -> Self {
        CallJoinRequest {
            ring: true,
            self_mute: false,
            self_deaf: false,
            self_video: false,
            e2ee: None,
            recording_notice: None,
            call_credential: false,
            origin: None,
        }
    }
}

impl Validate for CallJoinRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(n) = &self.recording_notice {
            n.validate().map_err(|e| e.nested("recording_notice"))?;
        }
        crate::voice::check_join_origin(self.origin.as_deref())?;
        crate::voice::check_credential_join(self.call_credential, self.e2ee.as_ref())
    }
}

/// The call join answer. `voice.call_id` is [`Call::id`]; `voice.e2ee.call_id` is the
/// engine room (the key group's scope).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallJoinResponse {
    /// The call after the join.
    pub call: Call,
    /// Whether this join started the call.
    pub created: bool,
    /// The media half (the voice join answer with `media` and `call_id`).
    pub voice: VoiceJoinResponse,
    /// The call's active recording as the joiner sees it (also in
    /// `voice.recording`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording: Option<crate::recording::Recording>,
}

/// `POST /api/v1/channels/{id}/call/decline` body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CallDeclineRequest {
    /// The active call.
    pub call_id: Id,
}

impl Validate for CallDeclineRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        Ok(())
    }
}

/// `POST /api/v1/channels/{id}/call/cancel` body (flag `call_cancel`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CallCancelRequest {
    /// The active call.
    pub call_id: Id,
}

impl Validate for CallCancelRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        Ok(())
    }
}

/// Flag `call_cancel`: `POST /api/v1/channels/{id}/call/cancel`, the `cancelled` end reason,
/// ring state and `call_ring` stop reason.
pub const FEATURE_CALL_CANCEL: &str = "call_cancel";

/// `POST /api/v1/channels/{id}/call/ring` body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CallRingRequest {
    /// The active call.
    pub call_id: Id,
    /// Whom to ring (default: every ringable member not in the call and not ringing).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub member_ids: Option<Vec<Id>>,
}

impl Validate for CallRingRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(ids) = &self.member_ids {
            if ids.is_empty() {
                return Err(ValidationError::invalid(
                    "member_ids",
                    "name at least one member, or leave member_ids out",
                ));
            }
            if ids.len() > RING_TARGETS_MAX {
                return Err(ValidationError::invalid(
                    "member_ids",
                    format!("at most {RING_TARGETS_MAX} members"),
                ));
            }
        }
        Ok(())
    }
}

/// `GET /api/v1/channels/{id}/call`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ChannelCall {
    /// The DM's active call, if any.
    pub call: Option<Call>,
}

/// `GET /api/v1/me/calls`: active calls in the caller's DMs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MyCalls {
    /// The calls.
    pub items: Vec<Call>,
}

/// Body of `call_updated`, to the DM's members.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallUpdated {
    /// The call now.
    pub call: Call,
}

/// Body of `call_ring`, to every session of the callee.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallRingEvent {
    /// The call.
    pub call_id: Id,
    /// Its DM (a client prepares a KeyPackage scoped `call:<channel_id>` on a ring).
    pub channel_id: Id,
    /// Who started it.
    pub started_by: Id,
    /// `true`: ring; `false`: stop ringing.
    pub ringing: bool,
    /// A silent ring (busy, DND, muted).
    pub silent: bool,
    /// Why: `busy`, `dnd`, `muted` (a silent ring); `accepted`, `declined`, `timeout`,
    /// `call_ended`, `cancelled` (a stop).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// When the ring becomes missed (while ringing).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<Timestamp>,
}

/// `call_ring.reason` and `MyRing.reason` values.
pub mod ring_reason {
    /// The callee is already in voice.
    pub const BUSY: &str = "busy";
    /// The callee is in Do Not Disturb.
    pub const DND: &str = "dnd";
    /// The callee muted the DM.
    pub const MUTED: &str = "muted";
    /// The callee joined.
    pub const ACCEPTED: &str = "accepted";
    /// The callee declined.
    pub const DECLINED: &str = "declined";
    /// Nobody answered in time.
    pub const TIMEOUT: &str = "timeout";
    /// The call ended first.
    pub const CALL_ENDED: &str = "call_ended";
    /// The starter cancelled the call (flag `call_cancel`).
    pub const CANCELLED: &str = "cancelled";
}

/// Every call reason string under the existing error codes.
pub mod reasons {
    /// `422`: a call needs a DM or group DM.
    pub const NOT_DM: &str = "not_dm";
    /// `403`: policy `calls.dm_enabled` is off.
    pub const DM_CALLS_DISABLED: &str = "dm_calls_disabled";
    /// `422`: nobody in the DM can be rung.
    pub const NO_CALLABLE_MEMBERS: &str = "no_callable_members";
    /// `422`: the call is not the DM's active call.
    pub const CALL_NOT_ACTIVE: &str = "call_not_active";
    /// `422`: the caller has no pending ring.
    pub const NOT_RINGING: &str = "not_ringing";
    /// `422`: a cancel needs the call's starter, before anyone else joined.
    pub const NOT_CANCELLABLE: &str = "not_cancellable";
    /// `422`: a re-ring needs the caller in the call.
    pub const NOT_IN_CALL: &str = "not_in_call";
    /// `422`: the member cannot be rung (`details.member_id`).
    pub const NOT_RINGABLE: &str = "not_ringable";
    /// `429`: a member was rung too often in this call.
    pub const RING_LIMIT: &str = "ring_limit";
    /// `422`: the call-record message cannot be edited.
    pub const CALL_RECORD_IMMUTABLE: &str = "call_record_immutable";
    /// `422`: moderation aimed at a DM call.
    pub const NOT_SPACE_CHANNEL: &str = "not_space_channel";
}