Skip to main content

sew_call_client/
provider.rs

1//! The host's join callback: the engine asks the host for Sew's join answer
2//! to join and to re-join when Sew dropped the join, and (Sew 0.7.3) to send the person's
3//! answer to a recording notice. The web UI never sees a token.
4//!
5//! Recording consent goes through the host, never the call credential: the host sends it with
6//! the person's own Sew session (its server route for an App), so it is the person's act with
7//! Sew's `notice_version` check and audit. The engine only asks ([`JoinProvider::consent`],
8//! [`JoinRequest::recording_notice`]) and reads Sew's answer; joining never implies consent and
9//! no answer means not recorded.
10
11use std::fmt;
12use std::future::Future;
13use std::pin::Pin;
14
15use serde::{Deserialize, Serialize};
16use sew_proto::id::Id;
17use sew_proto::recording::{ConsentPrompt, ConsentRequest, Recording, RecordingNotice};
18use sew_proto::voice::VoiceJoinResponse;
19
20/// A boxed future, as the trait methods return.
21pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
22
23/// Why the engine asks for a join again.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26#[non_exhaustive]
27pub enum RejoinReason {
28    /// The reconnect window (20 s) ran out, or the engine said the admit is gone.
29    AdmitLost,
30    /// The call credential expired (a long sleep) and can't be renewed.
31    CredentialExpired,
32}
33
34/// What the host joins. Its JSON (`{target, room, muted, deafened, rejoin}`, plus
35/// `recording_notice` when there is one) is what a host's provider may forward to its own server
36/// (tauri-plugin-sew-voice's App server route).
37#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
38#[non_exhaustive]
39pub struct JoinRequest {
40    /// Opaque to the engine: the host's target (K2: the server label; an App: its Sew).
41    pub target: String,
42    /// Opaque to the engine: the voice channel or DM call.
43    pub room: String,
44    /// Join muted.
45    pub muted: bool,
46    /// Join deafened (implies muted).
47    pub deafened: bool,
48    /// `None` for the first join; why Sew dropped the join otherwise.
49    pub rejoin: Option<RejoinReason>,
50    /// The person's answer to the recording notice (Sew 0.7.3): Sew's
51    /// `VoiceJoinRequest.recording_notice`, to forward unchanged. The engine sets it when the
52    /// host answers a call held at `consent_required` ([`crate::Call::consent`]), and keeps the
53    /// last answer for its re-joins (Sew asks again when the notice changed). `None`: no
54    /// answer; a join into a recorded room is then refused `409 recording_consent_required`
55    /// ([`ProviderError::ConsentRequired`]). Written only when present.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub recording_notice: Option<RecordingNotice>,
58}
59
60impl JoinRequest {
61    /// A first join of `room` through `target`: not muted, not deafened, no `rejoin`, no
62    /// `recording_notice` (set them with the `with_*` setters or on the fields).
63    pub fn new(target: impl Into<String>, room: impl Into<String>) -> JoinRequest {
64        JoinRequest {
65            target: target.into(),
66            room: room.into(),
67            muted: false,
68            deafened: false,
69            rejoin: None,
70            recording_notice: None,
71        }
72    }
73
74    /// Sets `muted`.
75    pub fn with_muted(mut self, muted: bool) -> JoinRequest {
76        self.muted = muted;
77        self
78    }
79
80    /// Sets `deafened`. A deafened join is muted, so `with_deafened(true)` also sets `muted` to
81    /// `true` (un-deafening later leaves the call muted, as the engine does for its own
82    /// deafened joins); `with_deafened(false)` leaves `muted` as it is. A `with_muted` after
83    /// this one still sets `muted`.
84    pub fn with_deafened(mut self, deafened: bool) -> JoinRequest {
85        self.deafened = deafened;
86        if deafened {
87            self.muted = true;
88        }
89        self
90    }
91
92    /// Sets `rejoin` to `Some(rejoin)`: why Sew dropped the join this one replaces.
93    pub fn with_rejoin(mut self, rejoin: RejoinReason) -> JoinRequest {
94        self.rejoin = Some(rejoin);
95        self
96    }
97
98    /// Sets `rejoin` from an `Option` (`None`: a first join), for a caller that holds one.
99    pub fn with_rejoin_opt(mut self, rejoin: Option<RejoinReason>) -> JoinRequest {
100        self.rejoin = rejoin;
101        self
102    }
103
104    /// Sets `recording_notice`: the person's answer to the recording notice.
105    pub fn with_recording_notice(mut self, notice: RecordingNotice) -> JoinRequest {
106        self.recording_notice = Some(notice);
107        self
108    }
109}
110
111/// Sew's `409 recording_consent_required` on a join (Sew 0.7.3): the room is
112/// recorded (or the channel records itself on its first join) and the join carried no answer
113/// to the current notice. Its `error.details`, unchanged.
114#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
115#[non_exhaustive]
116pub struct ConsentRequired {
117    /// The consent modal's data: `recording_id` (an id, or `"auto"`), `notice_version` (to
118    /// echo with the answer) and every slot a template shows.
119    pub consent_prompt: ConsentPrompt,
120    /// The recording as the joiner sees it (`None` for an auto-record channel that has none
121    /// yet).
122    #[serde(default)]
123    pub recording: Option<Recording>,
124    /// An auto-record channel's first join.
125    #[serde(default)]
126    pub auto: bool,
127}
128
129impl ConsentRequired {
130    /// From the refusal's `error.details` (`{recording, auto, consent_prompt}`); `None` when it
131    /// carries no prompt.
132    pub fn from_details(details: &serde_json::Value) -> Option<ConsentRequired> {
133        serde_json::from_value(details.clone()).ok()
134    }
135
136    /// The prompt's version (what the answer echoes).
137    pub fn notice_version(&self) -> u32 {
138        self.consent_prompt.notice_version
139    }
140
141    /// The join's `recording_notice` answering this prompt with `consent`.
142    pub fn notice(&self, consent: bool) -> RecordingNotice {
143        RecordingNotice {
144            recording_id: self.consent_prompt.recording_id,
145            consent: Some(consent),
146            notice_version: Some(self.consent_prompt.notice_version),
147        }
148    }
149}
150
151/// The person's answer to a live recording's notice, for the host to send with the person's
152/// own Sew session: `POST {path}` with `{body}` (Sew's `POST /api/v1/recordings/{id}/consent`),
153/// whose `200` is the recording as the person sees it ([`ConsentAnswer::recording_from_json`]).
154/// `consent: false` while granted is a withdrawal ("Stop recording me"); before that, a
155/// decline.
156#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
157#[non_exhaustive]
158pub struct ConsentAnswer {
159    /// The call's `target` (the join's).
160    pub target: String,
161    /// The call's `room` (the join's, or a move's destination).
162    pub room: String,
163    /// The recording.
164    pub recording_id: Id,
165    /// Grant (`true`), or decline / withdraw (`false`).
166    pub consent: bool,
167    /// The notice version the person saw (`None` for a withdrawal: Sew then checks none).
168    pub notice_version: Option<u32>,
169    /// This device in Sew's call keys (its device id), for the host's own records; not part of
170    /// Sew's body.
171    pub device_id: Option<String>,
172}
173
174impl ConsentAnswer {
175    /// Sew's route, under the client API (`/api/v1/recordings/{id}/consent`).
176    pub fn path(&self) -> String {
177        sew_proto::routes::with_id(sew_proto::routes::RECORDING_CONSENT, self.recording_id)
178    }
179
180    /// Sew's body (`{consent, notice_version}`).
181    pub fn body(&self) -> ConsentRequest {
182        ConsentRequest {
183            consent: self.consent,
184            notice_version: self.notice_version,
185        }
186    }
187
188    /// Reads Sew's `200` answer (the recording as the person sees it). The error never quotes
189    /// the body.
190    pub fn recording_from_json(body: &[u8]) -> Result<Recording, ProviderError> {
191        serde_json::from_slice(body)
192            .map_err(|_| ProviderError::Other("the consent answer did not parse".to_owned()))
193    }
194}
195
196/// The `Refused` code of [`JoinProvider::consent`]'s default: the host sends no consent.
197pub const CONSENT_UNSUPPORTED: &str = "consent_unsupported";
198
199/// What the person asks of the call's recording: press Record, or Stop.
200#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
201#[serde(rename_all = "snake_case")]
202#[non_exhaustive]
203pub enum RecordingControl {
204    /// Start recording the call's room (Sew's `POST /api/v1/channels/{id}/recording/start`).
205    Start,
206    /// Stop the room's active recording (Sew's `POST /api/v1/recordings/{id}/stop`).
207    Stop,
208}
209
210/// The person's Record or Stop, for the host to send with the person's own Sew session, as
211/// [`ConsentAnswer`] is: `POST {path}` with `{body}`, whose `200` is the recording as the person
212/// sees it ([`RecordingRequest::recording_from_json`]). Never the call credential: starting and
213/// stopping are the person's acts, with Sew's permission checks and audit.
214///
215/// Its JSON, `{target, room, action: "start" | "stop", recording_id?, device_id?}`, is what a
216/// provider forwards to its own server (the Sew App kit's native lane:
217/// `POST /sew/native/voice/recording`), which maps `room` to Sew's channel as its join does.
218///
219/// Sew decides who may: a refusal comes back with Sew's reason (`not_in_voice`,
220/// `recording_active`, `recording_disabled`, `recording_required` for a Stop while the room
221/// requires its recording, `cap_ceiling`, …), read by [`ProviderError::from_sew_error`].
222#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
223#[non_exhaustive]
224pub struct RecordingRequest {
225    /// The call's `target` (the join's).
226    pub target: String,
227    /// The call's `room` (the join's, or a move's destination).
228    pub room: String,
229    /// Start or Stop.
230    pub action: RecordingControl,
231    /// The call's channel as Sew names it (the voice channel, DM or group DM of the join
232    /// answer, or a move's destination), for a provider that calls Sew itself
233    /// ([`RecordingRequest::path`]). Not in the JSON: a server maps `room` itself.
234    #[serde(skip)]
235    pub channel_id: Option<Id>,
236    /// The active recording: Stop's route (`None` for a Start).
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub recording_id: Option<Id>,
239    /// This device in Sew's call keys (its device id), for the host's own records; not part of
240    /// Sew's body.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub device_id: Option<String>,
243}
244
245impl RecordingRequest {
246    /// A Start of `channel_id`'s recording, for the call on `target` / `room`.
247    pub fn start(target: impl Into<String>, room: impl Into<String>, channel_id: Id) -> Self {
248        RecordingRequest {
249            target: target.into(),
250            room: room.into(),
251            action: RecordingControl::Start,
252            channel_id: Some(channel_id),
253            recording_id: None,
254            device_id: None,
255        }
256    }
257
258    /// A Stop of `recording_id` in `channel_id`, for the call on `target` / `room`.
259    pub fn stop(
260        target: impl Into<String>,
261        room: impl Into<String>,
262        channel_id: Id,
263        recording_id: Id,
264    ) -> Self {
265        RecordingRequest {
266            target: target.into(),
267            room: room.into(),
268            action: RecordingControl::Stop,
269            channel_id: Some(channel_id),
270            recording_id: Some(recording_id),
271            device_id: None,
272        }
273    }
274
275    /// Sew's route, under the client API: `/api/v1/channels/{channel_id}/recording/start` for
276    /// a Start, `/api/v1/recordings/{recording_id}/stop` for a Stop. A request without its id
277    /// (read from JSON, or a Stop the engine never sends) keeps the route's `{id}` unfilled,
278    /// which Sew refuses: a Stop never becomes a Start.
279    pub fn path(&self) -> String {
280        use sew_proto::routes;
281        match (self.action, self.channel_id, self.recording_id) {
282            (RecordingControl::Start, Some(ch), _) => {
283                routes::with_id(routes::CHANNEL_RECORDING_START, ch)
284            }
285            (RecordingControl::Start, None, _) => routes::CHANNEL_RECORDING_START.to_owned(),
286            (_, _, Some(id)) => routes::with_id(routes::RECORDING_STOP, id),
287            (_, _, None) => routes::RECORDING_STOP.to_owned(),
288        }
289    }
290
291    /// Sew's body: `{}` for both (a Start takes the room's defaults for keep days, mixing and
292    /// language).
293    pub fn body(&self) -> serde_json::Value {
294        serde_json::Value::Object(serde_json::Map::new())
295    }
296
297    /// Reads Sew's `200` answer (the recording as the person sees it). The error never quotes
298    /// the body.
299    pub fn recording_from_json(body: &[u8]) -> Result<Recording, ProviderError> {
300        serde_json::from_slice(body)
301            .map_err(|_| ProviderError::Other("the recording answer did not parse".to_owned()))
302    }
303}
304
305/// The `Refused` code of [`JoinProvider::recording`]'s default: the host sends no Record or
306/// Stop.
307pub const RECORDING_UNSUPPORTED: &str = "recording_unsupported";
308
309/// The call-scoped credential minted with the join answer
310/// (`VoiceJoinResponse.call_credential`, flag `call_credential`, Sew 0.7.1).
311///
312/// The same JSON shape as `sew_proto::voice::CallCredential` (Sew 0.7.1); the engine reads it
313/// from the join answer's JSON ([`JoinAnswer::from_json`]).
314#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
315#[non_exhaustive]
316pub struct CallCredential {
317    /// `sewcc_<selector>.<secret>`.
318    pub token: String,
319    /// When it stops working (RFC 3339); renewed at half its life.
320    pub expires_at: sew_proto::time::Timestamp,
321    /// The join it is bound to (32 hex).
322    pub join_id: String,
323    /// Opaque and stable for the login lineage (32 hex): the device store keys on it.
324    pub device_scope: String,
325}
326
327impl CallCredential {
328    /// A credential from its four fields (every field is required).
329    pub fn new(
330        token: impl Into<String>,
331        expires_at: sew_proto::time::Timestamp,
332        join_id: impl Into<String>,
333        device_scope: impl Into<String>,
334    ) -> CallCredential {
335        CallCredential {
336            token: token.into(),
337            expires_at,
338            join_id: join_id.into(),
339            device_scope: device_scope.into(),
340        }
341    }
342}
343
344impl fmt::Debug for CallCredential {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        f.debug_struct("CallCredential")
347            .field("token", &"<redacted>")
348            .field("expires_at", &self.expires_at)
349            .field("join_id", &self.join_id)
350            .field("device_scope", &self.device_scope)
351            .finish()
352    }
353}
354
355/// Sew's join answer as the host got it, and the door to Sew's client API.
356///
357/// A voice join answers a `VoiceJoinResponse`; a DM call join (`call/join`) answers a
358/// `CallJoinResponse` (`{call, created, voice, recording}`), whose `voice` is the same voice
359/// answer. [`JoinAnswer::from_json`] takes either body unchanged.
360#[derive(Clone)]
361pub struct JoinAnswer {
362    /// Sew's `VoiceJoinResponse` (a voice join's answer, or a DM call join's `voice`),
363    /// unchanged.
364    pub join: VoiceJoinResponse,
365    /// The HTTPS base the engine uses for Sew's client API with the call credential (under K2: the
366    /// hosting daemon's lane on the box's own host name; never `turn.` or `voice.`).
367    pub api_base: url::Url,
368    credential: Option<CallCredential>,
369    dm_call: Option<DmCall>,
370}
371
372/// The DM call of a DM call join's answer (`CallJoinResponse.call` and `created`), kept by
373/// [`JoinAnswer::from_json`].
374#[derive(Clone, Debug, PartialEq, Eq)]
375#[non_exhaustive]
376pub struct DmCall {
377    /// The call (`calls.id`): the id the decline, cancel and re-ring routes take.
378    pub call_id: Id,
379    /// The DM or group DM: the `room` a host joins (and re-joins) the call with.
380    pub channel_id: Id,
381    /// Who started it.
382    pub started_by: Id,
383    /// Whether this join started the call.
384    pub created: bool,
385}
386
387impl fmt::Debug for JoinAnswer {
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        f.debug_struct("JoinAnswer")
390            .field("url", &self.join.url)
391            .field("token", &"<redacted>")
392            .field("room", &self.join.room)
393            .field("api_base", &self.api_base.as_str())
394            .field("call_credential", &self.credential)
395            .field("dm_call", &self.dm_call)
396            .finish_non_exhaustive()
397    }
398}
399
400/// Why a join answer could not be read.
401#[derive(Debug, thiserror::Error)]
402#[error("join answer: {0}")]
403pub struct AnswerError(String);
404
405impl JoinAnswer {
406    /// The answer from the HTTP body Sew (or the host's BFF) returned, as is: the recommended
407    /// constructor (it keeps `call_credential` whatever `sew-proto` version is pinned).
408    ///
409    /// The body is a voice join's `VoiceJoinResponse`, or a DM call join's `CallJoinResponse`
410    /// (`{call, created, voice, recording}`): then the voice answer and its `call_credential`
411    /// are read from `voice`, and the call from `call` ([`JoinAnswer::dm_call`]).
412    pub fn from_json(body: &[u8], api_base: url::Url) -> Result<JoinAnswer, AnswerError> {
413        let mut v: serde_json::Value =
414            serde_json::from_slice(body).map_err(|e| AnswerError(e.to_string()))?;
415        let mut dm_call = None;
416        if v.get("voice").is_some_and(serde_json::Value::is_object)
417            && v.get("call").is_some_and(serde_json::Value::is_object)
418        {
419            dm_call = Some(DmCall::from_answer(&v)?);
420            v = v["voice"].take();
421        }
422        let credential = match v.get("call_credential") {
423            None | Some(serde_json::Value::Null) => None,
424            Some(c) => Some(
425                serde_json::from_value::<CallCredential>(c.clone())
426                    .map_err(|e| AnswerError(format!("call_credential: {e}")))?,
427            ),
428        };
429        let join: VoiceJoinResponse =
430            serde_json::from_value(v).map_err(|e| AnswerError(e.to_string()))?;
431        Ok(JoinAnswer {
432            join,
433            api_base,
434            credential,
435            dm_call,
436        })
437    }
438
439    /// An answer from parts (tests, hosts that already parsed the body).
440    pub fn new(
441        join: VoiceJoinResponse,
442        api_base: url::Url,
443        credential: Option<CallCredential>,
444    ) -> JoinAnswer {
445        JoinAnswer {
446            join,
447            api_base,
448            credential,
449            dm_call: None,
450        }
451    }
452
453    /// The call credential, when the join asked for one.
454    pub fn call_credential(&self) -> Option<&CallCredential> {
455        self.credential.as_ref()
456    }
457
458    /// The DM call, when the answer was a DM call join's (`CallJoinResponse`).
459    pub fn dm_call(&self) -> Option<&DmCall> {
460        self.dm_call.as_ref()
461    }
462}
463
464impl DmCall {
465    /// From a `CallJoinResponse` body: `call.id`, `call.channel_id`, `call.started_by` and
466    /// `created`. The error never quotes the body.
467    fn from_answer(v: &serde_json::Value) -> Result<DmCall, AnswerError> {
468        let id = |field: &str| -> Result<Id, AnswerError> {
469            v["call"][field]
470                .as_str()
471                .and_then(|s| s.parse::<Id>().ok())
472                .ok_or_else(|| AnswerError(format!("call.{field}: not an id")))
473        };
474        Ok(DmCall {
475            call_id: id("id")?,
476            channel_id: id("channel_id")?,
477            started_by: id("started_by")?,
478            created: v["created"].as_bool().unwrap_or(false),
479        })
480    }
481}
482
483/// Why the host could not join.
484#[derive(Clone, Debug, PartialEq, thiserror::Error)]
485#[non_exhaustive]
486pub enum ProviderError {
487    /// The host has no Sew session (the call ends with `signin_required`).
488    #[error("sign-in required")]
489    SigninRequired,
490    /// Sew refused the join (`code` and `detail` passed through to the `errors` event).
491    #[error("refused: {code}")]
492    Refused {
493        /// Sew's error code (or the host's).
494        code: String,
495        /// Its details.
496        detail: serde_json::Value,
497    },
498    /// Sew or the host is unavailable; retry after `retry_after_ms` when given.
499    #[error("unavailable")]
500    Unavailable {
501        /// Sew's `Retry-After`, when it gave one.
502        retry_after_ms: Option<u64>,
503    },
504    /// Sew's `409 recording_consent_required` (Sew 0.7.3): the room is recorded and the
505    /// person has not answered its current notice. A join holds the call at
506    /// `consent_required` until the host answers ([`crate::Call::consent`]) or leaves.
507    #[error("recording_consent_required")]
508    ConsentRequired(Box<ConsentRequired>),
509    /// Anything else.
510    #[error("{0}")]
511    Other(String),
512}
513
514impl ProviderError {
515    /// Sew's error answer as the engine reads it: `401` is [`ProviderError::SigninRequired`];
516    /// `409 recording_consent_required` with a prompt is [`ProviderError::ConsentRequired`];
517    /// `429` and `5xx` are [`ProviderError::Unavailable`] (with `retry_after_ms`, from
518    /// `Retry-After`); anything else is [`ProviderError::Refused`] with `error.details.reason`
519    /// (else `error.code`, else `http_<status>`) and `error.details`. A host's server route that
520    /// returns Sew's error body unchanged is read the same way.
521    pub fn from_sew_error(status: u16, retry_after_ms: Option<u64>, body: &[u8]) -> ProviderError {
522        let v: serde_json::Value = serde_json::from_slice(body).unwrap_or_default();
523        let e = &v["error"];
524        let details = &e["details"];
525        let reason = details["reason"].as_str();
526        if status == 401 {
527            return ProviderError::SigninRequired;
528        }
529        if reason == Some(sew_proto::recording::reasons::RECORDING_CONSENT_REQUIRED)
530            && let Some(c) = ConsentRequired::from_details(details)
531        {
532            return ProviderError::ConsentRequired(Box::new(c));
533        }
534        if status == 429 || status >= 500 {
535            return ProviderError::Unavailable { retry_after_ms };
536        }
537        let code = reason
538            .or_else(|| e["code"].as_str())
539            .map_or_else(|| format!("http_{status}"), str::to_owned);
540        ProviderError::Refused {
541            code,
542            detail: details.clone(),
543        }
544    }
545}
546
547/// The host's join callback: call Sew's voice or DM call join with `call_credential: true`
548/// (and no `e2ee`) and return the answer unchanged.
549///
550/// # What implementing it needs
551///
552/// The trait and its types ([`BoxFuture`], [`JoinRequest`], [`JoinAnswer`], [`ProviderError`])
553/// are this crate's. Beside `sew-call-client`, a provider needs:
554///
555/// - `url = "2"`: [`JoinAnswer::from_json`] takes Sew's client API base as a `url::Url`;
556/// - an HTTP client of the app's choice to call Sew with the app's own session. The full
557///   example below uses `reqwest = { version = "0.12", default-features = false, features =
558///   ["json", "rustls-tls"] }` and `serde_json = "1"`;
559/// - to run a call, a Tokio runtime (`tokio = { version = "1", features = ["rt-multi-thread",
560///   "macros"] }`): [`crate::CallClient::join`] must be called from inside one.
561///
562/// The smallest provider, over the app's own HTTP code:
563///
564/// ```
565/// use sew_call_client::{BoxFuture, JoinAnswer, JoinProvider, JoinRequest, ProviderError};
566///
567/// struct AppJoin {
568///     /// Sew's client API base, e.g. `https://chat.example.com/`.
569///     api_base: url::Url,
570/// }
571///
572/// impl AppJoin {
573///     /// The app's own call to Sew's voice join for `req.room` (with `call_credential: true`),
574///     /// answering the response body.
575///     async fn post_voice_join(&self, req: &JoinRequest) -> Result<Vec<u8>, ProviderError> {
576///         # let _ = req;
577///         # Err(ProviderError::Unavailable { retry_after_ms: None })
578///     }
579/// }
580///
581/// impl JoinProvider for AppJoin {
582///     fn join(&self, req: JoinRequest) -> BoxFuture<'_, Result<JoinAnswer, ProviderError>> {
583///         Box::pin(async move {
584///             let body = self.post_voice_join(&req).await?;
585///             JoinAnswer::from_json(&body, self.api_base.clone())
586///                 .map_err(|e| ProviderError::Other(e.to_string()))
587///         })
588///     }
589/// }
590/// ```
591///
592/// A complete provider for an app that holds its own Sew session (a bearer token for Sew's
593/// client API), and a call through it:
594///
595/// ```no_run
596/// use std::path::PathBuf;
597/// use std::sync::Arc;
598///
599/// use sew_call_client::{
600///     BoxFuture, CallClient, ClientConfig, JoinAnswer, JoinProvider, JoinRequest, ProviderError,
601/// };
602///
603/// /// The app's sign-in, kept in Rust: Sew's client API base and the app's session token.
604/// struct MyJoinProvider {
605///     http: reqwest::Client,
606///     api_base: url::Url,
607///     session_token: String,
608/// }
609///
610/// impl JoinProvider for MyJoinProvider {
611///     fn join(&self, req: JoinRequest) -> BoxFuture<'_, Result<JoinAnswer, ProviderError>> {
612///         Box::pin(async move {
613///             // Sew's voice join for the channel, asking for a call credential (no `e2ee`).
614///             let path = format!("api/v1/channels/{}/voice/join", req.room);
615///             let url = self
616///                 .api_base
617///                 .join(&path)
618///                 .map_err(|e| ProviderError::Other(e.to_string()))?;
619///             let body = serde_json::json!({
620///                 "self_mute": req.muted,
621///                 "self_deaf": req.deafened,
622///                 "call_credential": true,
623///             });
624///             let resp = self
625///                 .http
626///                 .post(url)
627///                 .bearer_auth(&self.session_token)
628///                 .json(&body)
629///                 .send()
630///                 .await
631///                 .map_err(|_| ProviderError::Unavailable { retry_after_ms: None })?;
632///             if resp.status() == reqwest::StatusCode::UNAUTHORIZED {
633///                 return Err(ProviderError::SigninRequired);
634///             }
635///             if !resp.status().is_success() {
636///                 return Err(ProviderError::Refused {
637///                     code: resp.status().as_u16().to_string(),
638///                     detail: serde_json::Value::Null,
639///                 });
640///             }
641///             let bytes = resp
642///                 .bytes()
643///                 .await
644///                 .map_err(|e| ProviderError::Other(e.to_string()))?;
645///             // The answer, unchanged; the engine reaches Sew's client API at `api_base`.
646///             JoinAnswer::from_json(&bytes, self.api_base.clone())
647///                 .map_err(|e| ProviderError::Other(e.to_string()))
648///         })
649///     }
650/// }
651///
652/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
653/// let provider = Arc::new(MyJoinProvider {
654///     http: reqwest::Client::new(),
655///     api_base: url::Url::parse("https://chat.example.com/")?,
656///     session_token: "the app's Sew session".into(),
657/// });
658/// // Where the engine keeps the device key and its pins: a directory of the app's own.
659/// let data_dir = PathBuf::from("/var/lib/example-app/sew-voice");
660/// let client = CallClient::with_mls(ClientConfig::new("com.example.app", data_dir));
661/// let call = client
662///     .join(
663///         provider,
664///         // The room is the voice channel's id.
665///         JoinRequest::new("chat.example.com", "48831765147549699"),
666///     )
667///     .await?;
668/// let mut events = call.events(); // CallEvent::State, Participants, Speaking, Error
669/// while let Ok(event) = events.recv().await {
670///     println!("{event:?}");
671/// }
672/// # Ok(())
673/// # }
674/// ```
675pub trait JoinProvider: Send + Sync + 'static {
676    /// Join (or re-join) `req.room` on `req.target`, with `req.recording_notice` as the voice
677    /// join's `recording_notice` when it has one. A refusal that is Sew's
678    /// `409 recording_consent_required` should come back as
679    /// [`ProviderError::ConsentRequired`] ([`ProviderError::from_sew_error`] reads it), so the
680    /// call can hold for the person's answer.
681    fn join(&self, req: JoinRequest) -> BoxFuture<'_, Result<JoinAnswer, ProviderError>>;
682
683    /// Send the person's answer to a live recording's notice with the person's own Sew
684    /// session (Sew 0.7.3): `POST answer.path()` with `answer.body()`, and return Sew's
685    /// answer ([`ConsentAnswer::recording_from_json`]); a refusal as in
686    /// [`ProviderError::from_sew_error`] (a stale `notice_version` is
687    /// [`ProviderError::ConsentRequired`] with the current prompt). The engine never treats a
688    /// call as consented by itself: only Sew's answer, or a later `recording_updated`, moves
689    /// this device to `granted` and releases its key to the recorder.
690    ///
691    /// The default sends nothing and answers `Refused { code: "consent_unsupported" }`: the
692    /// person then stays unrecorded (`pending`) in a call recorded after they joined.
693    fn consent(&self, answer: ConsentAnswer) -> BoxFuture<'_, Result<Recording, ProviderError>> {
694        let _ = answer;
695        Box::pin(std::future::ready(Err(ProviderError::Refused {
696            code: CONSENT_UNSUPPORTED.to_owned(),
697            detail: serde_json::Value::Null,
698        })))
699    }
700
701    /// Send the person's Record or Stop with the person's own Sew session (Sew 0.9.0):
702    /// `POST req.path()` with `req.body()`, and return Sew's answer
703    /// ([`RecordingRequest::recording_from_json`]); a refusal as in
704    /// [`ProviderError::from_sew_error`]. Sew's answer becomes the call's recording at once,
705    /// and the call socket's `recording_updated` follows for everyone in the room. A Start is
706    /// the starter's own consent (Sew records it as their answer, so show the notice as a
707    /// confirmation first) and nobody else's: everyone else in the room is `pending` until
708    /// they answer.
709    ///
710    /// The default sends nothing and answers `Refused { code: "recording_unsupported" }`.
711    fn recording(&self, req: RecordingRequest) -> BoxFuture<'_, Result<Recording, ProviderError>> {
712        let _ = req;
713        Box::pin(std::future::ready(Err(ProviderError::Refused {
714            code: RECORDING_UNSUPPORTED.to_owned(),
715            detail: serde_json::Value::Null,
716        })))
717    }
718}
719
720#[cfg(test)]
721mod tests {
722    #![allow(clippy::unwrap_used)]
723    use super::*;
724
725    #[test]
726    fn with_deafened_true_also_mutes_and_false_leaves_muted() {
727        let r = JoinRequest::new("t", "r").with_deafened(true);
728        assert!(r.deafened, "with_deafened(true) did not set deafened");
729        assert!(r.muted, "with_deafened(true) did not set muted");
730
731        let r = JoinRequest::new("t", "r").with_deafened(false);
732        assert!(!r.deafened);
733        assert!(
734            !r.muted,
735            "with_deafened(false) changed an unmuted join's muted"
736        );
737
738        let r = JoinRequest::new("t", "r")
739            .with_muted(true)
740            .with_deafened(false);
741        assert!(!r.deafened);
742        assert!(r.muted, "with_deafened(false) cleared muted");
743
744        let r = JoinRequest::new("t", "r")
745            .with_deafened(true)
746            .with_deafened(false);
747        assert!(!r.deafened);
748        assert!(r.muted, "un-deafening the builder cleared muted");
749    }
750
751    #[test]
752    fn with_rejoin_opt_sets_and_clears_rejoin() {
753        let r = JoinRequest::new("t", "r").with_rejoin_opt(Some(RejoinReason::CredentialExpired));
754        assert_eq!(r.rejoin, Some(RejoinReason::CredentialExpired));
755
756        let r = JoinRequest::new("t", "r")
757            .with_rejoin(RejoinReason::AdmitLost)
758            .with_rejoin_opt(None);
759        assert_eq!(
760            r.rejoin, None,
761            "with_rejoin_opt(None) kept the earlier reason"
762        );
763
764        let a = JoinRequest::new("t", "r").with_rejoin(RejoinReason::AdmitLost);
765        let b = JoinRequest::new("t", "r").with_rejoin_opt(Some(RejoinReason::AdmitLost));
766        assert_eq!(a, b);
767    }
768
769    fn body(cred: bool) -> Vec<u8> {
770        let mut v = serde_json::json!({
771            "url": "wss://voice.example",
772            "token": "media-token",
773            "expires_at": "2026-11-02T10:00:00Z",
774            "room": sew_proto::e2ee::CallId::from_random([7; 16]),
775            "state": {
776                "member_id": "1001",
777                "channel_id": "2002",
778                "connection": "connecting",
779                "secure": false,
780                "self_mute": false,
781                "self_deaf": false,
782                "server_mute": false,
783                "server_deaf": false,
784                "speak_denied": false,
785                "joined_at": "2026-11-02T09:58:00Z"
786            }
787        });
788        if cred {
789            v["call_credential"] = serde_json::json!({
790                "token": "sewcc_sel.secret",
791                "expires_at": "2026-11-02T10:08:00Z",
792                "join_id": "0123456789abcdef0123456789abcdef",
793                "device_scope": "fedcba9876543210fedcba9876543210"
794            });
795        }
796        serde_json::to_vec(&v).unwrap()
797    }
798
799    fn prompt() -> serde_json::Value {
800        serde_json::json!({
801            "recording_id": "77", "notice_version": 3141, "recorder_name": "Sew Notes",
802            "feature_label": "Sew Notes",
803            "started_by": {"member_id": "1001", "display_name": "Alice"},
804            "room": {"channel_id": "2002", "kind": "voice", "name": "lounge"},
805            "audio_keep_days": 30,
806            "transcript": {"posted_to_channel": true, "readable_by": ["channel_members"],
807                           "e2ee": false},
808            "admin_download": false, "decline_mode": "join_unrecorded",
809            "recorded_now": ["1001"]
810        })
811    }
812
813    #[test]
814    fn sews_consent_refusal_becomes_consent_required() {
815        let body = serde_json::json!({"ok": false, "error": {
816            "code": "conflict", "hint": "answer the recording notice",
817            "details": {"reason": "recording_consent_required", "recording": null, "auto": false,
818                        "consent_prompt": prompt()}}});
819        let e = ProviderError::from_sew_error(409, None, &serde_json::to_vec(&body).unwrap());
820        let ProviderError::ConsentRequired(c) = e else {
821            panic!("not consent_required: {e:?}");
822        };
823        assert_eq!(c.notice_version(), 3141);
824        let n = serde_json::to_value(c.notice(true)).unwrap();
825        assert_eq!(
826            n,
827            serde_json::json!({"recording_id": "77", "consent": true, "notice_version": 3141})
828        );
829        // The other answers.
830        assert_eq!(
831            ProviderError::from_sew_error(401, None, b"{}"),
832            ProviderError::SigninRequired
833        );
834        assert_eq!(
835            ProviderError::from_sew_error(503, Some(2000), b"not json"),
836            ProviderError::Unavailable {
837                retry_after_ms: Some(2000)
838            }
839        );
840        let denied = serde_json::json!({"ok": false, "error": {"code": "policy_denied",
841            "hint": "x", "details": {"reason": "recording_consent_required_to_join"}}});
842        match ProviderError::from_sew_error(403, None, &serde_json::to_vec(&denied).unwrap()) {
843            ProviderError::Refused { code, detail } => {
844                assert_eq!(code, "recording_consent_required_to_join");
845                assert_eq!(detail["reason"], "recording_consent_required_to_join");
846            }
847            e => panic!("{e:?}"),
848        }
849        // A 409 without a prompt is a plain refusal.
850        let bare = serde_json::json!({"ok": false, "error": {"code": "conflict", "hint": "x",
851            "details": {"reason": "recording_consent_required"}}});
852        assert!(matches!(
853            ProviderError::from_sew_error(409, None, &serde_json::to_vec(&bare).unwrap()),
854            ProviderError::Refused { .. }
855        ));
856    }
857
858    #[test]
859    fn join_request_writes_the_notice_only_when_there_is_one() {
860        let mut req = JoinRequest {
861            target: "acme".into(),
862            room: "2002".into(),
863            muted: false,
864            deafened: false,
865            rejoin: None,
866            recording_notice: None,
867        };
868        assert_eq!(
869            serde_json::to_value(&req).unwrap(),
870            serde_json::json!({"target": "acme", "room": "2002", "muted": false,
871                               "deafened": false, "rejoin": null})
872        );
873        req.recording_notice = Some(RecordingNotice {
874            recording_id: sew_proto::recording::RecordingRef::Auto,
875            consent: Some(false),
876            notice_version: Some(7),
877        });
878        assert_eq!(
879            serde_json::to_value(&req).unwrap()["recording_notice"],
880            serde_json::json!({"recording_id": "auto", "consent": false, "notice_version": 7})
881        );
882        let a = ConsentAnswer {
883            target: "acme".into(),
884            room: "2002".into(),
885            recording_id: Id::new(77).unwrap(),
886            consent: false,
887            notice_version: None,
888            device_id: None,
889        };
890        assert_eq!(a.path(), "/api/v1/recordings/77/consent");
891        assert_eq!(
892            serde_json::to_value(a.body()).unwrap(),
893            serde_json::json!({"consent": false})
894        );
895    }
896
897    #[test]
898    fn a_recording_says_what_started_it() {
899        use crate::call::CallRecording;
900        use sew_proto::recording::RecordingTrigger;
901        let rec = |auto: bool| {
902            serde_json::json!({
903                "id": "77", "channel_id": "2002", "state": "recording", "started_by": "1001",
904                "started_at": "2026-11-02T09:58:00Z", "auto": auto, "message_id": "88",
905                "mixed": false, "audio_keep_days": 30, "max_duration_ms": 14_400_000u64,
906                "participants": []
907            })
908        };
909        for (auto, want) in [
910            (false, RecordingTrigger::Manual),
911            (true, RecordingTrigger::Auto),
912        ] {
913            let r: Recording = serde_json::from_value(rec(auto)).unwrap();
914            let v = CallRecording::from_sew(&r);
915            assert_eq!(v.trigger, want);
916            assert!(!v.required, "a 0.8.x recording is never required");
917            assert_eq!(
918                serde_json::to_value(&v).unwrap()["trigger"],
919                serde_json::to_value(want).unwrap()
920            );
921        }
922        // A held join with no recording yet: an auto-record room's first join.
923        let c = ConsentRequired::from_details(&serde_json::json!({
924            "recording": null, "auto": true, "consent_prompt": prompt()
925        }))
926        .unwrap();
927        let v = CallRecording::from_consent_required(&c);
928        assert_eq!(v.trigger, RecordingTrigger::Auto);
929        assert!(!v.required);
930    }
931
932    #[test]
933    fn a_recording_carries_its_start_clock() {
934        use crate::call::CallRecording;
935        let rec = serde_json::json!({
936            "id": "77", "channel_id": "2002", "state": "recording", "started_by": "1001",
937            "started_at": "2026-11-02T09:58:00Z", "auto": false, "message_id": "88",
938            "mixed": false, "audio_keep_days": 30, "max_duration_ms": 14_400_000u64,
939            "participants": []
940        });
941        let r: Recording = serde_json::from_value(rec.clone()).unwrap();
942        let v = CallRecording::from_sew(&r);
943        assert_eq!(v.started_by.as_deref(), Some("1001"));
944        let at = v.started_at.expect("Sew's recording carries its start");
945        assert_eq!(at.to_wire(), "2026-11-02T09:58:00.000Z");
946        let json = serde_json::to_value(&v).unwrap();
947        assert_eq!(json["started_at"], "2026-11-02T09:58:00.000Z");
948        assert_eq!(json["started_by"], "1001");
949        // Joining a call already being recorded: the held join's recording keeps both.
950        let c = ConsentRequired::from_details(&serde_json::json!({
951            "recording": rec, "auto": false, "consent_prompt": prompt()
952        }))
953        .unwrap();
954        let held = CallRecording::from_consent_required(&c);
955        assert_eq!(held.started_at, Some(at));
956        assert_eq!(held.started_by.as_deref(), Some("1001"));
957        // An auto-record room's first join: no recording yet, so no start.
958        let c = ConsentRequired::from_details(&serde_json::json!({
959            "recording": null, "auto": true, "consent_prompt": prompt()
960        }))
961        .unwrap();
962        let v = CallRecording::from_consent_required(&c);
963        assert_eq!(v.started_at, None);
964        let json = serde_json::to_value(&v).unwrap();
965        assert!(
966            json.get("started_at").is_none(),
967            "left out when unknown: {json}"
968        );
969    }
970
971    #[test]
972    fn a_recording_carries_its_audio_keep_days() {
973        use crate::call::{CallRecording, RecordingConsent};
974        let rec = |days: u16| {
975            serde_json::json!({
976                "id": "77", "channel_id": "2002", "state": "recording", "started_by": "1001",
977                "started_at": "2026-11-02T09:58:00Z", "auto": false, "message_id": "88",
978                "mixed": false, "audio_keep_days": days, "max_duration_ms": 14_400_000u64,
979                "participants": [], "my_consent": "granted"
980            })
981        };
982        // Sew's recording, after the person answered: the keep days stay with it.
983        let r: Recording = serde_json::from_value(rec(7)).unwrap();
984        let v = CallRecording::from_sew(&r);
985        assert_eq!(v.audio_keep_days, 7);
986        assert_eq!(v.my_consent, RecordingConsent::Granted);
987        assert!(v.consent_prompt.is_none(), "answered: no notice");
988        assert_eq!(serde_json::to_value(&v).unwrap()["audio_keep_days"], 7);
989        // 0 (deleted once the transcript is final) is a real value and is written.
990        let r: Recording = serde_json::from_value(rec(0)).unwrap();
991        let v = CallRecording::from_sew(&r);
992        assert_eq!(v.audio_keep_days, 0);
993        assert_eq!(serde_json::to_value(&v).unwrap()["audio_keep_days"], 0);
994        // A held join into a call already being recorded: the recording's.
995        let mut p = prompt();
996        p["audio_keep_days"] = serde_json::json!(7);
997        let c = ConsentRequired::from_details(&serde_json::json!({
998            "recording": rec(7), "auto": false, "consent_prompt": p
999        }))
1000        .unwrap();
1001        assert_eq!(CallRecording::from_consent_required(&c).audio_keep_days, 7);
1002        // An auto-record room's first join: no recording yet, so the notice's.
1003        let mut p = prompt();
1004        p["recording_id"] = serde_json::json!("auto");
1005        p["audio_keep_days"] = serde_json::json!(14);
1006        let c = ConsentRequired::from_details(&serde_json::json!({
1007            "recording": null, "auto": true, "consent_prompt": p
1008        }))
1009        .unwrap();
1010        let v = CallRecording::from_consent_required(&c);
1011        assert_eq!(v.recording_id, "auto");
1012        assert_eq!(v.audio_keep_days, 14);
1013        assert_eq!(serde_json::to_value(&v).unwrap()["audio_keep_days"], 14);
1014    }
1015
1016    #[test]
1017    fn recording_requests_name_sews_routes() {
1018        let ch = Id::new(2002).unwrap();
1019        let start = RecordingRequest::start("acme", "2002", ch);
1020        assert_eq!(start.path(), "/api/v1/channels/2002/recording/start");
1021        assert_eq!(start.body(), serde_json::json!({}));
1022        assert_eq!(
1023            serde_json::to_value(&start).unwrap(),
1024            serde_json::json!({"target": "acme", "room": "2002", "action": "start"})
1025        );
1026        let stop = RecordingRequest::stop("acme", "2002", ch, Id::new(77).unwrap());
1027        assert_eq!(stop.path(), "/api/v1/recordings/77/stop");
1028        assert_eq!(stop.body(), serde_json::json!({}));
1029        assert_eq!(
1030            serde_json::to_value(&stop).unwrap(),
1031            serde_json::json!({"target": "acme", "room": "2002", "action": "stop",
1032                               "recording_id": "77"})
1033        );
1034        // Read from a server's JSON: no channel, so a Start's route stays unfilled.
1035        let read: RecordingRequest = serde_json::from_value(
1036            serde_json::json!({"target": "acme", "room": "2002", "action": "start"}),
1037        )
1038        .unwrap();
1039        assert_eq!(read.channel_id, None);
1040        assert_eq!(read.path(), "/api/v1/channels/{id}/recording/start");
1041        // A Stop that names no recording never becomes a Start.
1042        let mut bare = stop.clone();
1043        bare.recording_id = None;
1044        assert_eq!(bare.path(), "/api/v1/recordings/{id}/stop");
1045        assert!(RecordingRequest::recording_from_json(b"not json").is_err());
1046    }
1047
1048    #[test]
1049    fn the_default_provider_sends_no_record_or_stop() {
1050        struct P;
1051        impl JoinProvider for P {
1052            fn join(&self, _: JoinRequest) -> BoxFuture<'_, Result<JoinAnswer, ProviderError>> {
1053                Box::pin(std::future::ready(Err(ProviderError::SigninRequired)))
1054            }
1055        }
1056        let rt = tokio::runtime::Builder::new_current_thread()
1057            .build()
1058            .unwrap();
1059        let req = RecordingRequest::start("acme", "2002", Id::new(2002).unwrap());
1060        match rt.block_on(P.recording(req)) {
1061            Err(ProviderError::Refused { code, .. }) => assert_eq!(code, RECORDING_UNSUPPORTED),
1062            other => panic!("{other:?}"),
1063        }
1064    }
1065
1066    #[test]
1067    fn answer_keeps_the_credential_and_redacts_tokens() {
1068        let base = url::Url::parse("https://chat.example.com/_k2/voice/sew/").unwrap();
1069        let a = match JoinAnswer::from_json(&body(true), base.clone()) {
1070            Ok(a) => a,
1071            Err(e) => panic!("{e}"),
1072        };
1073        let c = a.call_credential().unwrap();
1074        assert_eq!(c.token, "sewcc_sel.secret");
1075        assert_eq!(c.device_scope.len(), 32);
1076        let dbg = format!("{a:?}");
1077        assert!(
1078            !dbg.contains("sewcc_sel.secret") && !dbg.contains("media-token"),
1079            "{dbg}"
1080        );
1081        let a = JoinAnswer::from_json(&body(false), base).unwrap();
1082        assert!(a.call_credential().is_none());
1083        assert!(
1084            a.dm_call().is_none(),
1085            "a voice join's answer has no DM call"
1086        );
1087    }
1088
1089    /// A DM call join's answer (`CallJoinResponse`), as Sew writes it.
1090    fn call_join_body(cred: bool) -> Vec<u8> {
1091        let voice: serde_json::Value = serde_json::from_slice(&body(cred)).unwrap();
1092        let v = serde_json::json!({
1093            "call": {
1094                "id": "3003",
1095                "channel_id": "2002",
1096                "message_id": "4004",
1097                "started_by": "1001",
1098                "started_at": "2026-11-02T09:58:00Z",
1099                "state": "active",
1100                "participant_ids": ["1001"],
1101                "rings": [{"member_id": "1005", "state": "ringing",
1102                           "expires_at": "2026-11-02T09:58:45Z"}]
1103            },
1104            "created": true,
1105            "voice": voice
1106        });
1107        serde_json::to_vec(&v).unwrap()
1108    }
1109
1110    #[test]
1111    fn a_dm_call_join_answer_is_read_unchanged() {
1112        let base = url::Url::parse("https://chat.example.com/_k2/voice/sew/").unwrap();
1113        for cred in [true, false] {
1114            let a = match JoinAnswer::from_json(&call_join_body(cred), base.clone()) {
1115                Ok(a) => a,
1116                Err(e) => panic!("{e}"),
1117            };
1118            // The voice half is the same answer as a voice join's.
1119            let plain = JoinAnswer::from_json(&body(cred), base.clone()).unwrap();
1120            assert_eq!(a.join, plain.join);
1121            assert_eq!(a.call_credential(), plain.call_credential());
1122            assert_eq!(a.call_credential().is_some(), cred);
1123            assert_eq!(a.api_base, base);
1124            let call = a.dm_call().unwrap();
1125            assert_eq!(call.call_id, Id::new(3003).unwrap());
1126            assert_eq!(call.channel_id, Id::new(2002).unwrap());
1127            assert_eq!(call.started_by, Id::new(1001).unwrap());
1128            assert!(call.created);
1129            // The DM is the room a host joins and re-joins with: the voice state's channel.
1130            assert_eq!(a.join.state.channel_id, call.channel_id);
1131            let dbg = format!("{a:?}");
1132            assert!(
1133                !dbg.contains("sewcc_sel.secret") && !dbg.contains("media-token"),
1134                "{dbg}"
1135            );
1136        }
1137        // A call/join answer that does not parse fails without quoting it.
1138        let mut bad: serde_json::Value = serde_json::from_slice(&call_join_body(true)).unwrap();
1139        bad["call"]["id"] = serde_json::json!(null);
1140        let e = JoinAnswer::from_json(&serde_json::to_vec(&bad).unwrap(), base.clone())
1141            .err()
1142            .unwrap();
1143        assert!(!e.to_string().contains("sewcc_"), "{e}");
1144        let mut bad: serde_json::Value = serde_json::from_slice(&call_join_body(true)).unwrap();
1145        bad["voice"]["token"] = serde_json::json!(7);
1146        assert!(JoinAnswer::from_json(&serde_json::to_vec(&bad).unwrap(), base).is_err());
1147    }
1148}