1use 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
20pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26#[non_exhaustive]
27pub enum RejoinReason {
28 AdmitLost,
30 CredentialExpired,
32}
33
34#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
38#[non_exhaustive]
39pub struct JoinRequest {
40 pub target: String,
42 pub room: String,
44 pub muted: bool,
46 pub deafened: bool,
48 pub rejoin: Option<RejoinReason>,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub recording_notice: Option<RecordingNotice>,
58}
59
60impl JoinRequest {
61 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 pub fn with_muted(mut self, muted: bool) -> JoinRequest {
76 self.muted = muted;
77 self
78 }
79
80 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 pub fn with_rejoin(mut self, rejoin: RejoinReason) -> JoinRequest {
94 self.rejoin = Some(rejoin);
95 self
96 }
97
98 pub fn with_rejoin_opt(mut self, rejoin: Option<RejoinReason>) -> JoinRequest {
100 self.rejoin = rejoin;
101 self
102 }
103
104 pub fn with_recording_notice(mut self, notice: RecordingNotice) -> JoinRequest {
106 self.recording_notice = Some(notice);
107 self
108 }
109}
110
111#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
115#[non_exhaustive]
116pub struct ConsentRequired {
117 pub consent_prompt: ConsentPrompt,
120 #[serde(default)]
123 pub recording: Option<Recording>,
124 #[serde(default)]
126 pub auto: bool,
127}
128
129impl ConsentRequired {
130 pub fn from_details(details: &serde_json::Value) -> Option<ConsentRequired> {
133 serde_json::from_value(details.clone()).ok()
134 }
135
136 pub fn notice_version(&self) -> u32 {
138 self.consent_prompt.notice_version
139 }
140
141 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
157#[non_exhaustive]
158pub struct ConsentAnswer {
159 pub target: String,
161 pub room: String,
163 pub recording_id: Id,
165 pub consent: bool,
167 pub notice_version: Option<u32>,
169 pub device_id: Option<String>,
172}
173
174impl ConsentAnswer {
175 pub fn path(&self) -> String {
177 sew_proto::routes::with_id(sew_proto::routes::RECORDING_CONSENT, self.recording_id)
178 }
179
180 pub fn body(&self) -> ConsentRequest {
182 ConsentRequest {
183 consent: self.consent,
184 notice_version: self.notice_version,
185 }
186 }
187
188 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
196pub const CONSENT_UNSUPPORTED: &str = "consent_unsupported";
198
199#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
201#[serde(rename_all = "snake_case")]
202#[non_exhaustive]
203pub enum RecordingControl {
204 Start,
206 Stop,
208}
209
210#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
223#[non_exhaustive]
224pub struct RecordingRequest {
225 pub target: String,
227 pub room: String,
229 pub action: RecordingControl,
231 #[serde(skip)]
235 pub channel_id: Option<Id>,
236 #[serde(default, skip_serializing_if = "Option::is_none")]
238 pub recording_id: Option<Id>,
239 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub device_id: Option<String>,
243}
244
245impl RecordingRequest {
246 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 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 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 pub fn body(&self) -> serde_json::Value {
294 serde_json::Value::Object(serde_json::Map::new())
295 }
296
297 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
305pub const RECORDING_UNSUPPORTED: &str = "recording_unsupported";
308
309#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
315#[non_exhaustive]
316pub struct CallCredential {
317 pub token: String,
319 pub expires_at: sew_proto::time::Timestamp,
321 pub join_id: String,
323 pub device_scope: String,
325}
326
327impl CallCredential {
328 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#[derive(Clone)]
361pub struct JoinAnswer {
362 pub join: VoiceJoinResponse,
365 pub api_base: url::Url,
368 credential: Option<CallCredential>,
369 dm_call: Option<DmCall>,
370}
371
372#[derive(Clone, Debug, PartialEq, Eq)]
375#[non_exhaustive]
376pub struct DmCall {
377 pub call_id: Id,
379 pub channel_id: Id,
381 pub started_by: Id,
383 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#[derive(Debug, thiserror::Error)]
402#[error("join answer: {0}")]
403pub struct AnswerError(String);
404
405impl JoinAnswer {
406 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 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 pub fn call_credential(&self) -> Option<&CallCredential> {
455 self.credential.as_ref()
456 }
457
458 pub fn dm_call(&self) -> Option<&DmCall> {
460 self.dm_call.as_ref()
461 }
462}
463
464impl DmCall {
465 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#[derive(Clone, Debug, PartialEq, thiserror::Error)]
485#[non_exhaustive]
486pub enum ProviderError {
487 #[error("sign-in required")]
489 SigninRequired,
490 #[error("refused: {code}")]
492 Refused {
493 code: String,
495 detail: serde_json::Value,
497 },
498 #[error("unavailable")]
500 Unavailable {
501 retry_after_ms: Option<u64>,
503 },
504 #[error("recording_consent_required")]
508 ConsentRequired(Box<ConsentRequired>),
509 #[error("{0}")]
511 Other(String),
512}
513
514impl ProviderError {
515 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
547pub trait JoinProvider: Send + Sync + 'static {
676 fn join(&self, req: JoinRequest) -> BoxFuture<'_, Result<JoinAnswer, ProviderError>>;
682
683 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}