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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
//! Call recording and per-speaker transcripts: the recording
//! object, consent and capture, the consent modal contract, the record-message summary,
//! transcript turns, the audio listing and the compliance download.
//!
//! No engine identity, join id, room name, key or certificate ever appears in these types;
//! the recorder's engine identity reaches clients only in the encrypted call's `recorder` dispatch.

use std::borrow::Cow;
use std::fmt;

use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::e2ee::ConsentState;
use crate::error::{Validate, ValidationError};
use crate::id::Id;
use crate::time::Timestamp;

mod apps;
mod consent_text;
pub mod controls;
pub use apps::{
    RecordingEventKind, RecordingRequiredPolicy, RecordingRule, RecordingStartLevel,
    RecordingTrigger,
};
pub use consent_text::{ConsentAsk, ConsentChoice};

/// The recorder's display name: the roster entry, the recording banner and every
/// notice text use it. Never sent to the engine (its engine name stays empty).
pub const RECORDER_DISPLAY_NAME: &str = crate::RECORDER_DISPLAY_NAME;
/// The optional feature label templates may show for recording + transcripts.
pub const RECORDING_FEATURE_LABEL: &str = "Sew Notes";
/// Most active recordings in READY `recordings`.
pub const READY_RECORDINGS_MAX: usize = 100;
/// Most bytes of a compliance download's `reason`.
pub const DOWNLOAD_REASON_MAX: usize = 500;
/// The format string of recorder-sealed audio.
pub const SEALED_AUDIO_FORMAT: &str = "sew-stream-v1+audio/ogg; codecs=opus";

/// Whisper language codes accepted as a hint (mostly ISO 639-1, plus e.g.
/// `haw`, `yue`), besides `auto`.
pub const WHISPER_LANGUAGES: &[&str] = &[
    "en", "zh", "de", "es", "ru", "ko", "fr", "ja", "pt", "tr", "pl", "ca", "nl", "ar", "sv", "it",
    "id", "hi", "fi", "vi", "he", "uk", "el", "ms", "cs", "ro", "da", "hu", "ta", "no", "th", "ur",
    "hr", "bg", "lt", "la", "mi", "ml", "cy", "sk", "te", "fa", "lv", "bn", "sr", "az", "sl", "kn",
    "et", "mk", "br", "eu", "is", "hy", "ne", "mn", "bs", "kk", "sq", "sw", "gl", "mr", "pa", "si",
    "km", "sn", "yo", "so", "af", "oc", "ka", "be", "tg", "sd", "gu", "am", "yi", "lo", "uz", "fo",
    "ht", "ps", "tk", "nn", "mt", "sa", "lb", "my", "bo", "tl", "mg", "as", "tt", "haw", "ln",
    "ha", "ba", "jw", "su", "yue",
];

/// Whether `s` is `auto` or a known Whisper language code.
pub fn language_ok(s: &str) -> bool {
    s == "auto" || WHISPER_LANGUAGES.contains(&s)
}

/// `details.reason` values.
pub mod reasons {
    /// `503`: `[recording] enabled = false`.
    pub const RECORDING_UNAVAILABLE: &str = "recording_unavailable";
    /// `503`: the recorder is unhealthy.
    pub const RECORDER_UNAVAILABLE: &str = "recorder_unavailable";
    /// `503`: the transcriber is unhealthy.
    pub const TRANSCRIBER_UNAVAILABLE: &str = "transcriber_unavailable";
    /// `503`: too many active recordings.
    pub const RECORDING_CAPACITY: &str = "recording_capacity";
    /// `503`: the transcription backlog is too large.
    pub const TRANSCRIBE_BACKLOG: &str = "transcribe_backlog";
    /// `503`: the room's key group is rebuilding.
    pub const E2EE_REBUILDING: &str = "e2ee_rebuilding";
    /// `403 policy_denied`: policy `recording.enabled` is off.
    pub const RECORDING_DISABLED: &str = "recording_disabled";
    /// `403 policy_denied`: policy `recording.dm_enabled` is off.
    pub const DM_RECORDING_DISABLED: &str = "dm_recording_disabled";
    /// `403 policy_denied`: agents and act-as never start, stop or consent.
    pub const AGENTS_CANNOT_RECORD: &str = "agents_cannot_record";
    /// `403 policy_denied`: agents never get audio.
    pub const AGENTS_NO_AUDIO: &str = "agents_no_audio";
    /// `403 policy_denied`: declining means not joining (`recording.require_consent_to_join`).
    pub const RECORDING_CONSENT_REQUIRED_TO_JOIN: &str = "recording_consent_required_to_join";
    /// `409`: a recording is already active in the room.
    pub const RECORDING_ACTIVE: &str = "recording_active";
    /// `409`: the join needs the consent modal's answer.
    pub const RECORDING_CONSENT_REQUIRED: &str = crate::e2ee::RECORDING_CONSENT_REQUIRED;
    /// `422`: the recording is not active.
    pub const RECORDING_NOT_ACTIVE: &str = "recording_not_active";
    /// `422`: the record message cannot be deleted while the recording or its transcript runs.
    pub const RECORDING_IN_PROGRESS: &str = "recording_in_progress";
    /// `422`: the record message cannot be edited.
    pub const RECORDING_RECORD_IMMUTABLE: &str = "recording_record_immutable";
    /// `422`: transcript turns cannot be edited.
    pub const TRANSCRIPT_IMMUTABLE: &str = "transcript_immutable";
    /// `422`: the audio is no longer available.
    pub const AUDIO_EXPIRED: &str = "audio_expired";
    /// `422`: the audio was purged.
    pub const AUDIO_PURGED: &str = "audio_purged";
    /// `422`: the caller has no voice entry in the room.
    pub const NOT_IN_VOICE: &str = "not_in_voice";
    /// `422`: not a voice channel, DM or group DM.
    pub const NOT_VOICE_CHANNEL: &str = "not_voice_channel";
    /// `422 invalid_state`: the room records every call with two or more people, and two or
    /// more are in it, so its recording cannot be stopped from a client. "Stop recording me"
    /// still works.
    pub const RECORDING_REQUIRED: &str = "recording_required";
}

coded_enum! {
    /// A recording's lifecycle state. Stored in `recordings.state`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum RecordingState {
        /// Admitting and certifying the recorder.
        Starting = "starting" => 1,
        /// The recorder joined.
        Recording = "recording" => 2,
        /// Draining the recorder.
        Stopping = "stopping" => 3,
        /// Over.
        Stopped = "stopped" => 4,
    }
}

impl RecordingState {
    /// `starting`, `recording` or `stopping`.
    pub const fn is_active(self) -> bool {
        matches!(
            self,
            RecordingState::Starting | RecordingState::Recording | RecordingState::Stopping
        )
    }
}

coded_enum! {
    /// Why a recording stopped. Stored in `recordings.stop_reason`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum StopReason {
        /// The stop route.
        Stopped = "stopped" => 1,
        /// No standard voice entries left in the room.
        RoomEmpty = "room_empty" => 2,
        /// The DM call ended.
        CallEnded = "call_ended" => 3,
        /// `recording.max_duration_ms` reached.
        MaxDuration = "max_duration" => 4,
        /// The recorder failed (join timeout, certificate, unreachable, too many rejoins).
        RecorderFailed = "recorder_failed" => 5,
        /// The engine room was lost beyond the re-admit grace.
        MediaRestarted = "media_restarted" => 6,
        /// Three consecutive `storage_full` segment writes.
        StorageFull = "storage_full" => 7,
        /// Recording was disabled (policy, config, archive, `sew recording disable`).
        Disabled = "disabled" => 8,
        /// `recording.max_bytes` reached.
        MaxBytes = "max_bytes" => 9,
        /// Stopped over the management API (the App or K2 governing the room).
        MgmtStopped = "mgmt_stopped" => 10,
    }
}

coded_enum! {
    /// What a participant said to the recording notice. Stored in
    /// `recording_participants.consent`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum Consent {
        /// In the room, has not answered.
        Pending = "pending" => 1,
        /// Agreed.
        Granted = "granted" => 2,
        /// Refused; stays in the room unrecorded (unless declining means not joining).
        Declined = "declined" => 3,
        /// Agreed earlier, then withdrew.
        Withdrawn = "withdrawn" => 4,
    }
}

impl Consent {
    /// The three-valued state the call key service's `ConsentSource` and the client's
    /// `Input::Recording` take (fallback: `Granted` iff `granted`; declined and withdrawn are
    /// `Denied`).
    pub const fn to_state(self) -> ConsentState {
        match self {
            Consent::Granted => ConsentState::Granted,
            Consent::Pending => ConsentState::Pending,
            Consent::Declined | Consent::Withdrawn | Consent::Unknown => ConsentState::Denied,
        }
    }
}

unit_enum! {
    /// Whether a granted participant's microphone is actually captured.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum Capture {
        /// The recorder captures this member.
        Recorded = "recorded",
        /// Not captured (see the reason).
        NotRecorded = "not_recorded",
    }
}

coded_enum! {
    /// Why a granted participant is not captured. Stored in
    /// `recording_participants.capture_reason`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum NotRecordedReason {
        /// A track cap is reached; not allowlisted.
        TrackCap = "track_cap" => 1,
        /// No microphone published.
        NoMicrophone = "no_microphone" => 2,
        /// The recorder could not decrypt the member's frames.
        NoKey = "no_key" => 3,
        /// The track was published unencrypted.
        Unencrypted = "unencrypted" => 4,
        /// The track is not Opus.
        Codec = "codec" => 5,
        /// Not subscribable under the room's permissions.
        Permission = "permission" => 6,
    }
}

coded_enum! {
    /// How a consent answer arrived (audit `via`). Stored in `recording_participants.via`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum ConsentVia {
        /// The starter's start request.
        Start = "start" => 1,
        /// A join's `recording_notice`.
        Join = "join" => 2,
        /// The in-room prompt (`POST …/consent`).
        Prompt = "prompt" => 3,
        /// A withdrawal.
        Withdraw = "withdraw" => 4,
        /// The joiner of an auto-record channel.
        Auto = "auto" => 5,
    }
}

coded_enum! {
    /// Where the person answered. Stored in `recording_participants.surface`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum ConsentSurface {
        /// The blocking modal before joining.
        Modal = "modal" => 1,
        /// The in-room prompt.
        Prompt = "prompt" => 2,
        /// The starter's confirmation before `start`.
        Start = "start" => 3,
    }
}

unit_enum! {
    /// What declining does (from `recording.require_consent_to_join`).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum DeclineMode {
        /// The decliner joins, unrecorded (the default).
        JoinUnrecorded = "join_unrecorded",
        /// Declining means not joining.
        NotJoin = "not_join",
    }
}

coded_enum! {
    /// The recording's audio. Stored in `recordings.audio_state`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum AudioState {
        /// Kept.
        Available = "available" => 1,
        /// Hidden; links may still exist (held or not yet purged).
        Expired = "expired" => 2,
        /// Every link deleted; the content key is gone.
        Purged = "purged" => 3,
    }
}

coded_enum! {
    /// The transcript. Stored in `recordings.transcript_state`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum TranscriptState {
        /// No segment transcribed yet.
        Pending = "pending" => 1,
        /// Turns are being posted.
        Running = "running" => 2,
        /// Final, complete.
        Done = "done" => 3,
        /// Final, with gaps or failed segments.
        Partial = "partial" => 4,
        /// Final, no turn posted and at least one segment failed.
        Failed = "failed" => 5,
    }
}

coded_enum! {
    /// Why a span of a recording is missing. Stored in `recording_gaps.reason`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum GapReason {
        /// The recorder process restarted.
        RecorderRestarted = "recorder_restarted" => 1,
        /// The recorder's buffer was full.
        RecorderBufferFull = "recorder_buffer_full" => 2,
        /// The blob store was full.
        StorageFull = "storage_full" => 3,
        /// A segment exceeded `recording.segment_max_bytes`.
        TooLarge = "too_large" => 4,
        /// Transcription failed for a segment.
        TranscribeFailed = "transcribe_failed" => 5,
        /// The audio was purged before it was transcribed.
        AudioGone = "audio_gone" => 6,
        /// A track cap.
        TrackCap = "track_cap" => 7,
        /// The recorder held no key for a consenting speaker.
        NoKey = "no_key" => 8,
        /// The recorder rejoined with a new admit.
        RecorderReconnected = "recorder_reconnected" => 9,
        /// A key was missing mid-segment.
        KeyMissing = "key_missing" => 10,
        /// A media discontinuity.
        Discontinuity = "discontinuity" => 11,
        /// The engine restarted (same admit, fresh token).
        EngineRestart = "engine_restart" => 12,
    }
}

coded_enum! {
    /// Why a transcript is `failed` or `partial` ([`TranscriptFailure::code`]). Stored in
    /// `recordings.transcript_failure`. Later releases add codes: show
    /// [`TranscriptFailure::message`] for a code this build does not know.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum TranscriptFailureCode {
        /// The audio was deleted (expired, purged, or its record message deleted) before it was
        /// transcribed.
        AudioGone = "audio_gone" => 1,
        /// The transcriber does not support the language spoken, even when asked to detect it.
        UnsupportedLanguage = "unsupported_language" => 2,
        /// The transcriber could not transcribe the audio (it timed out, failed or gave an
        /// answer Sew could not read) after its retries.
        TranscriberError = "transcriber_error" => 3,
        /// Part of the call's audio never reached the recording (the recorder restarted or
        /// reconnected, storage was full, a key was missing, and the like). Only on `partial`.
        AudioNotCaptured = "audio_not_captured" => 4,
    }
}

impl TranscriptFailureCode {
    /// The plain words a client shows for the code, the same as [`TranscriptFailure::message`].
    pub const fn message(self) -> &'static str {
        match self {
            TranscriptFailureCode::AudioGone => {
                "The audio was deleted before it could be transcribed."
            }
            TranscriptFailureCode::UnsupportedLanguage => {
                "The language spoken in the call is not supported for transcripts."
            }
            TranscriptFailureCode::TranscriberError => {
                "The transcription service could not process the audio."
            }
            TranscriptFailureCode::AudioNotCaptured => {
                "Some of the call's audio was not captured, so the transcript has gaps."
            }
            TranscriptFailureCode::Unknown => "The transcript could not be completed.",
        }
    }
}

/// Why a recording's transcript could not be made (`failed`) or is incomplete (`partial`):
/// `{"code": "transcriber_error", "message": "The transcription service could not process the
/// audio."}`. `message` is plain words for the person, written by the server; `code` is stable
/// for a client that picks its own words.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct TranscriptFailure {
    /// The cause.
    pub code: TranscriptFailureCode,
    /// Plain words for the person.
    pub message: String,
}

impl TranscriptFailure {
    /// The failure for `code`, with its plain words.
    pub fn new(code: TranscriptFailureCode) -> TranscriptFailure {
        TranscriptFailure {
            code,
            message: code.message().to_owned(),
        }
    }
}

unit_enum! {
    /// Whether the audio listing hands out keys.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum Playback {
        /// No in-app playback (the default).
        Off = "off",
        /// Keys and ciphertext URLs for local unsealing.
        ClientUnseal = "client_unseal",
    }
}

coded_enum! {
    /// What a compliance download covers. Stored in `recording_downloads.what`.
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum DownloadWhat {
        /// The mixed parts.
        Mixed = "mixed" => 1,
        /// The per-speaker segments.
        Segments = "segments" => 2,
        /// Both.
        #[default]
        Both = "both" => 3,
    }
}

/// What a `recording_notice` refers to: a live recording, or `"auto"` for an auto-record
/// channel with no recording yet.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RecordingRef {
    /// The live recording.
    Id(Id),
    /// Start one on join.
    Auto,
}

impl fmt::Display for RecordingRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RecordingRef::Id(id) => write!(f, "{id}"),
            RecordingRef::Auto => f.write_str("auto"),
        }
    }
}

impl Serialize for RecordingRef {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            RecordingRef::Id(id) => id.serialize(s),
            RecordingRef::Auto => s.serialize_str("auto"),
        }
    }
}

impl<'de> Deserialize<'de> for RecordingRef {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        if s == "auto" {
            return Ok(RecordingRef::Auto);
        }
        s.parse::<Id>()
            .map(RecordingRef::Id)
            .map_err(serde::de::Error::custom)
    }
}

impl JsonSchema for RecordingRef {
    fn inline_schema() -> bool {
        true
    }

    fn schema_name() -> Cow<'static, str> {
        "RecordingRef".into()
    }

    fn json_schema(_: &mut SchemaGenerator) -> Schema {
        json_schema!({
            "type": "string",
            "pattern": "^(auto|[1-9][0-9]{0,18})$",
            "description": "A recording id, or \"auto\" for an auto-record channel with no recording yet."
        })
    }
}

/// The answer to the consent modal, sent with a voice join or call join/accept.
/// Joining never implies consent: `consent` is required and `notice_version` must echo the
/// current [`ConsentPrompt`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RecordingNotice {
    /// The recording (or `"auto"`).
    pub recording_id: RecordingRef,
    /// The person's answer. Missing → `400 validation_failed`, field `recording_notice.consent`.
    #[serde(default)]
    pub consent: Option<bool>,
    /// The prompt version the person saw.
    #[serde(default)]
    pub notice_version: Option<u32>,
}

impl Validate for RecordingNotice {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.consent.is_none() {
            return Err(ValidationError::invalid(
                "consent",
                "the consent modal's answer is required; joining never implies consent",
            ));
        }
        Ok(())
    }
}

/// One participant of a recording, as everyone in the audience sees it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RecordingParticipant {
    /// The member.
    pub member_id: Id,
    /// What they said.
    pub consent: Consent,
    /// Whether they are captured (only for `granted`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture: Option<Capture>,
    /// Why not (only for `not_recorded`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<NotRecordedReason>,
}

/// The starter as the consent modal shows them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct PromptMember {
    /// The member.
    pub member_id: Id,
    /// Their display name.
    pub display_name: String,
}

unit_enum! {
    /// The room kind the modal names.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum PromptRoomKind {
        /// A voice channel.
        Voice = "voice",
        /// A DM call.
        Dm = "dm",
        /// A group-DM call.
        GroupDm = "group_dm",
    }
}

/// Where the recording is.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct PromptRoom {
    /// The voice channel or DM.
    pub channel_id: Id,
    /// Its kind.
    pub kind: PromptRoomKind,
    /// The channel's name (voice channels only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// What happens to the words.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct PromptTranscript {
    /// Transcripts are posted into the channel as ordinary messages.
    pub posted_to_channel: bool,
    /// Who can read them: `channel_members`, `search`, `agents`.
    pub readable_by: Vec<String>,
    /// Transcripts are not end-to-end encrypted.
    pub e2ee: bool,
}

impl Default for PromptTranscript {
    fn default() -> Self {
        PromptTranscript {
            posted_to_channel: true,
            readable_by: vec![
                "channel_members".to_owned(),
                "search".to_owned(),
                "agents".to_owned(),
            ],
            e2ee: false,
        }
    }
}

/// The consent modal's data. Every slot is data; templates supply the
/// sentences. `notice_version` is a stable hash of every other slot; the answer must echo it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct ConsentPrompt {
    /// What the answer refers to.
    pub recording_id: RecordingRef,
    /// A stable hash of every other slot value.
    pub notice_version: u32,
    /// [`RECORDER_DISPLAY_NAME`].
    pub recorder_name: String,
    /// [`RECORDING_FEATURE_LABEL`].
    pub feature_label: String,
    /// Who started it (`None` for an auto channel with no recording yet).
    pub started_by: Option<PromptMember>,
    /// Where.
    pub room: PromptRoom,
    /// How long audio is kept (0 = until the transcript is final).
    pub audio_keep_days: u16,
    /// What happens to the words.
    pub transcript: PromptTranscript,
    /// Authorised compliance admins can download the audio (always `true` in v1).
    pub admin_download: bool,
    /// What declining does.
    pub decline_mode: DeclineMode,
    /// Who is currently recorded (granted and captured), ascending.
    pub recorded_now: Vec<Id>,
    /// The room records every call with two or more people (absent when not).
    #[serde(default, skip_serializing_if = "is_false")]
    pub required: bool,
    /// The display names of the Apps whose servers can read the transcript (the Space's
    /// governing App, when it may); absent when none.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub app_readers: Vec<String>,
    /// Agents in this channel can read the transcript (a coworker agent is a member of it);
    /// absent when none is.
    #[serde(default, skip_serializing_if = "is_false")]
    pub agent_readers: bool,
}

impl ConsentPrompt {
    /// A prompt for `recording_id` in `room`: no starter, nobody recorded yet, audio deleted
    /// once the transcript is final, the default transcript slots, admin download on, declining
    /// joins unrecorded, and none of the optional slots. `notice_version` is 0 until
    /// [`ConsentPrompt::sealed`].
    pub fn new(recording_id: RecordingRef, room: PromptRoom) -> ConsentPrompt {
        ConsentPrompt {
            recording_id,
            notice_version: 0,
            recorder_name: RECORDER_DISPLAY_NAME.to_owned(),
            feature_label: RECORDING_FEATURE_LABEL.to_owned(),
            started_by: None,
            room,
            audio_keep_days: 0,
            transcript: PromptTranscript::default(),
            admin_download: true,
            decline_mode: DeclineMode::JoinUnrecorded,
            recorded_now: Vec::new(),
            required: false,
            app_readers: Vec::new(),
            agent_readers: false,
        }
    }
}

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

impl ConsentPrompt {
    /// The stable hash of every slot but `notice_version` (FNV-1a 32 over a canonical text).
    pub fn compute_version(&self) -> u32 {
        let mut text = String::new();
        let started = self
            .started_by
            .as_ref()
            .map(|m| format!("{}:{}", m.member_id, m.display_name))
            .unwrap_or_default();
        let recorded: Vec<String> = self.recorded_now.iter().map(Id::to_string).collect();
        text.push_str(&format!(
            "v1|{}|{}|{}|{}|{}|{:?}|{:?}|{}|{}|{}|{:?}|{}|{}|{}",
            self.recording_id,
            self.recorder_name,
            self.feature_label,
            started,
            self.room.channel_id,
            self.room.kind.as_str(),
            self.room.name,
            self.audio_keep_days,
            self.transcript.posted_to_channel,
            self.transcript.readable_by.join(","),
            self.transcript.e2ee,
            self.admin_download,
            self.decline_mode.as_str(),
            recorded.join(","),
        ));
        // Slots added later are hashed only when set, so a prompt that sets none keeps the
        // version it always had.
        if self.required {
            text.push_str("|required");
        }
        if !self.app_readers.is_empty() {
            text.push_str(&format!("|app_readers:{:?}", self.app_readers));
        }
        if self.agent_readers {
            text.push_str("|agent_readers");
        }
        let mut h: u32 = 0x811c_9dc5;
        for b in text.bytes() {
            h ^= u32::from(b);
            h = h.wrapping_mul(0x0100_0193);
        }
        h
    }

    /// Sets `notice_version` from the other slots.
    pub fn sealed(mut self) -> ConsentPrompt {
        self.notice_version = self.compute_version();
        self
    }
}

/// A recording.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct Recording {
    /// The recording.
    pub id: Id,
    /// The voice channel or DM.
    pub channel_id: Id,
    /// The DM call (`calls.id`) of a DM-call recording.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub call_record_id: Option<Id>,
    /// The channel's space (absent for DMs).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space_id: Option<Id>,
    /// Its state.
    pub state: RecordingState,
    /// Who started it.
    pub started_by: Id,
    /// When.
    pub started_at: Timestamp,
    /// Started by an auto-record channel's first join, or (`trigger: required`) by the room
    /// reaching two people.
    pub auto: bool,
    /// What started it: `manual` (someone pressed Record), `auto` (an auto-record room's
    /// first join) or `required` (the room reached two people while it records every call
    /// with more than one person). Always sent; a payload without it (an older Sew) reads as
    /// `manual`, and `auto` then tells an automatic start.
    #[serde(default)]
    pub trigger: RecordingTrigger,
    /// When it stopped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stopped_at: Option<Timestamp>,
    /// Why.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<StopReason>,
    /// The record message.
    pub message_id: Id,
    /// A mixed file is made after stop.
    pub mixed: bool,
    /// Audio keep days (0 = until the transcript is final).
    pub audio_keep_days: u16,
    /// The language hint (`None` = auto).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// `recording.max_duration_ms`.
    pub max_duration_ms: u64,
    /// Members in the room plus members who ever granted, ascending.
    pub participants: Vec<RecordingParticipant>,
    /// The viewer's own consent (self only; absent for non-participants).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub my_consent: Option<Consent>,
    /// The consent modal (self only, while the viewer is `pending`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub consent_prompt: Option<ConsentPrompt>,
    /// The viewer's own Record and Stop (self only), while the viewer is in the recording's
    /// room. Absent from servers that predate it, and for viewers outside the room.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub my_controls: Option<RecordingControls>,
}

impl Recording {
    /// A recording `starting`, started manually by `started_by` at `started_at`, with its
    /// record message: no participants yet, no mixed file, keep days 0, no limit set; every
    /// optional field unset.
    pub fn new(
        id: Id,
        channel_id: Id,
        started_by: Id,
        started_at: Timestamp,
        message_id: Id,
    ) -> Recording {
        Recording {
            id,
            channel_id,
            call_record_id: None,
            space_id: None,
            state: RecordingState::Starting,
            started_by,
            started_at,
            auto: false,
            trigger: RecordingTrigger::Manual,
            stopped_at: None,
            stop_reason: None,
            message_id,
            mixed: false,
            audio_keep_days: 0,
            language: None,
            max_duration_ms: 0,
            participants: Vec::new(),
            my_consent: None,
            consent_prompt: None,
            my_controls: None,
        }
    }
}

impl Recording {
    /// The pair the client's `Input::Recording` takes: the live recording id and the
    /// viewer's consent mapped to the three [`ConsentState`] values.
    pub fn e2ee_input(&self) -> (Option<Id>, ConsentState) {
        let live = self.state.is_active().then_some(self.id);
        let c = self
            .my_consent
            .map(Consent::to_state)
            .unwrap_or(ConsentState::Pending);
        (live, c)
    }
}

/// `POST /api/v1/channels/{id}/recording/start` body.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct StartRecordingRequest {
    /// Audio keep days (clamped).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audio_keep_days: Option<u16>,
    /// Make a mixed file after stop (default `true`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mixed: Option<bool>,
    /// A Whisper language code or `auto`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
}

impl Validate for StartRecordingRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(l) = &self.language
            && !language_ok(l)
        {
            return Err(ValidationError::invalid(
                "language",
                "not a supported language code",
            ));
        }
        Ok(())
    }
}

/// `POST /api/v1/recordings/{id}/consent` body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ConsentRequest {
    /// Grant or decline/withdraw.
    pub consent: bool,
    /// The prompt version the person saw.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notice_version: Option<u32>,
}

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

/// `POST /api/v1/recordings/{id}/audio/retention` body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AudioRetentionRequest {
    /// New keep days (clamped).
    pub audio_keep_days: u16,
}

impl Validate for AudioRetentionRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        // Any value is clamped.
        Ok(())
    }
}

/// `GET /api/v1/channels/{id}/recording` answer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ActiveRecording {
    /// The active recording, if any.
    pub recording: Option<Recording>,
}

/// The audio part of a [`RecordingSummary`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct SummaryAudio {
    /// Its state.
    pub state: AudioState,
    /// When it expires (set at transcript final).
    pub expires_at: Option<Timestamp>,
    /// A mixed file is (or will be) made.
    pub mixed: bool,
    /// Keep days.
    pub keep_days: u16,
}

impl SummaryAudio {
    /// The audio part in `state`, with no expiry yet; set the other fields.
    pub fn new(state: AudioState, mixed: bool, keep_days: u16) -> SummaryAudio {
        SummaryAudio {
            state,
            expires_at: None,
            mixed,
            keep_days,
        }
    }
}

/// The transcript part of a [`RecordingSummary`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct SummaryTranscript {
    /// Its state.
    pub state: TranscriptState,
    /// Turns posted.
    pub turns: u32,
    /// Total gap time.
    pub gaps_ms: u64,
    /// The majority language of the turns.
    pub lang: Option<String>,
    /// Why the transcript is `failed` or `partial`, as a stable code and plain words for the
    /// person (`{"code": "transcriber_error", "message": "..."}`). Absent otherwise, when no
    /// cause is known, and from servers that predate it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failure: Option<TranscriptFailure>,
}

impl SummaryTranscript {
    /// The transcript part in `state`: no turns, no gaps, no language, no failure; set the
    /// other fields.
    pub fn new(state: TranscriptState) -> SummaryTranscript {
        SummaryTranscript {
            state,
            turns: 0,
            gaps_ms: 0,
            lang: None,
            failure: None,
        }
    }
}

/// `Message.recording` on the record message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct RecordingSummary {
    /// The recording.
    pub recording_id: Id,
    /// Who started it.
    pub started_by: Id,
    /// When.
    pub started_at: Timestamp,
    /// Auto-started.
    pub auto: bool,
    /// When it stopped.
    pub stopped_at: Option<Timestamp>,
    /// Why.
    pub stop_reason: Option<StopReason>,
    /// `stopped_at − started_at` once stopped.
    pub duration_ms: Option<u64>,
    /// Members whose speech was stored, ascending.
    pub speaker_ids: Vec<Id>,
    /// The audio.
    pub audio: SummaryAudio,
    /// The transcript.
    pub transcript: SummaryTranscript,
    /// Always `true` in v2: every call is end-to-end encrypted.
    pub e2ee: bool,
}

impl RecordingSummary {
    /// A recording that `started_by` started at `started_at` and that has not stopped: manual,
    /// no speakers yet, end-to-end encrypted; set the other fields.
    pub fn new(
        recording_id: Id,
        started_by: Id,
        started_at: Timestamp,
        audio: SummaryAudio,
        transcript: SummaryTranscript,
    ) -> RecordingSummary {
        RecordingSummary {
            recording_id,
            started_by,
            started_at,
            auto: false,
            stopped_at: None,
            stop_reason: None,
            duration_ms: None,
            speaker_ids: Vec::new(),
            audio,
            transcript,
            e2ee: true,
        }
    }
}

/// One piece of a transcript turn (numbers only; text lives in the message body).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct TurnPiece {
    /// Start, ms from the recording start.
    pub start_ms: u64,
    /// End, ms from the recording start.
    pub end_ms: u64,
    /// Byte offset of the piece's text in the body.
    pub offset: u32,
    /// Byte length of the piece's text in the body.
    pub len: u32,
}

/// `Message.transcript` on a transcript turn.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct TranscriptTurn {
    /// The recording.
    pub recording_id: Id,
    /// The speaker (also the message author).
    pub speaker_id: Id,
    /// Start, ms from the recording start.
    pub start_ms: u64,
    /// End, ms from the recording start.
    pub end_ms: u64,
    /// When it was said (`created_at` is posting time).
    pub spoken_at: Timestamp,
    /// The turn's language.
    pub lang: Option<String>,
    /// The pieces.
    pub pieces: Vec<TurnPiece>,
}

/// One mixed part in an audio listing or download.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MixedPart {
    /// Part number, from 1.
    pub part: u16,
    /// Offset from the recording start.
    pub offset_ms: u64,
    /// Length (≤ 60 min).
    pub duration_ms: u64,
    /// Sealed size.
    pub bytes: u64,
    /// The ciphertext URL (`client_unseal` playback or download only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// The part key, base64 (`client_unseal` playback or download only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    /// [`SEALED_AUDIO_FORMAT`] (`client_unseal` playback only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
}

/// One speaker's track in an audio listing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct AudioTrack {
    /// The speaker.
    pub member_id: Id,
    /// Stored segments.
    pub segments: u32,
    /// Their speech.
    pub speech_ms: u64,
}

/// `GET /api/v1/recordings/{id}/audio`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RecordingAudio {
    /// The audio's state.
    pub state: AudioState,
    /// When it expires.
    pub expires_at: Option<Timestamp>,
    /// `off` or `client_unseal`.
    pub playback: Playback,
    /// The mixed parts.
    pub mixed: Vec<MixedPart>,
    /// Per-speaker tracks.
    pub tracks: Vec<AudioTrack>,
}

/// One segment of a track page (keys and URLs only with `client_unseal` playback).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct AudioSegment {
    /// The segment.
    pub segment_id: Id,
    /// Offset from the recording start.
    pub start_ms: u64,
    /// Length.
    pub duration_ms: u32,
    /// Sealed size.
    pub bytes: u32,
    /// The ciphertext URL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// The segment key, base64.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    /// [`SEALED_AUDIO_FORMAT`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
}

/// `POST /api/v1/compliance/recordings/{id}/downloads` body.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DownloadRequest {
    /// What to download (default `both`).
    #[serde(default)]
    pub what: DownloadWhat,
    /// Why (≤ 500 bytes; audited only as `reason_given`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

impl Validate for DownloadRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if self
            .reason
            .as_ref()
            .is_some_and(|r| r.len() > DOWNLOAD_REASON_MAX)
        {
            return Err(ValidationError::invalid("reason", "at most 500 bytes"));
        }
        Ok(())
    }
}

/// A download's speaker.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DownloadSpeaker {
    /// The member.
    pub member_id: Id,
    /// Their display name.
    pub display_name: String,
}

/// A compliance download grant: sealed files and the keys to open them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RecordingDownload {
    /// The grant.
    pub download_id: Id,
    /// The recording.
    pub recording_id: Id,
    /// Its channel.
    pub channel_id: Id,
    /// When it started.
    pub started_at: Timestamp,
    /// When it stopped.
    pub stopped_at: Option<Timestamp>,
    /// The audio's state.
    pub audio_state: AudioState,
    /// [`SEALED_AUDIO_FORMAT`].
    pub format: String,
    /// When the grant and its URLs expire.
    pub expires_at: Timestamp,
    /// The speakers.
    pub speakers: Vec<DownloadSpeaker>,
    /// The mixed parts with URLs and keys (when asked for).
    pub mixed: Vec<MixedPart>,
    /// The segment pages (when segments were asked for).
    pub segments_url: Option<String>,
}

/// One segment of a compliance download.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DownloadSegment {
    /// The segment.
    pub segment_id: Id,
    /// The speaker.
    pub member_id: Id,
    /// Offset from the recording start.
    pub start_ms: u64,
    /// Length.
    pub duration_ms: u32,
    /// Sealed size.
    pub bytes: u32,
    /// The viewer-bound ciphertext URL.
    pub url: String,
    /// The segment key, base64.
    pub key: String,
}

/// `recording_updated`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RecordingUpdated {
    /// The recording (with the receiver's own `my_consent` / `consent_prompt`).
    pub recording: Recording,
}

unit_enum! {
    /// Why Record would be refused for now although the person may record: a hint a client
    /// may show on a greyed Record. It never changes `can_record`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum RecordUnavailable {
        /// The install runs as many recordings as it allows.
        RecordingCapacity = "recording_capacity",
        /// The recorder does not answer.
        RecorderUnavailable = "recorder_unavailable",
    }
}

/// A person's Record and Stop in the room they are in, as Sew would take them now
/// (`Recording.my_controls`, the call socket's READY). Of two values, the larger `rev` is the
/// newer.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct RecordingControls {
    /// Sew would take this person's Record now (passing conditions aside).
    pub can_record: bool,
    /// Sew would take this person's Stop now.
    pub can_stop: bool,
    /// A server-wide increasing revision.
    #[serde(default)]
    pub rev: u64,
    /// While the person may record: why a start would be refused for now (a hint only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub record_unavailable: Option<RecordUnavailable>,
}

impl RecordingControls {
    /// The pair with `rev` 0 and no hint.
    pub const fn new(can_record: bool, can_stop: bool) -> RecordingControls {
        RecordingControls {
            can_record,
            can_stop,
            rev: 0,
            record_unavailable: None,
        }
    }

    /// Whether `other` says the same (`rev` aside).
    pub fn same_as(&self, other: &RecordingControls) -> bool {
        self.can_record == other.can_record
            && self.can_stop == other.can_stop
            && self.record_unavailable == other.record_unavailable
    }
}

/// `recording_controls_updated` (to the person's own sessions only): their Record and Stop in
/// the room they are in changed, or a new session needs the current value.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct RecordingControlsUpdated {
    /// The room's voice channel or DM.
    pub channel_id: Id,
    /// The DM call (`calls.id`) of a DM call.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub call_id: Option<Id>,
    /// Sew would take this person's Record now.
    pub can_record: bool,
    /// Sew would take this person's Stop now.
    pub can_stop: bool,
    /// The value's revision ([`RecordingControls::rev`]).
    pub rev: u64,
    /// While the person may record: why a start would be refused for now (a hint only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub record_unavailable: Option<RecordUnavailable>,
}

impl RecordingControlsUpdated {
    /// The event for `channel_id` with `controls`.
    pub fn new(
        channel_id: Id,
        call_id: Option<Id>,
        controls: &RecordingControls,
    ) -> RecordingControlsUpdated {
        RecordingControlsUpdated {
            channel_id,
            call_id,
            can_record: controls.can_record,
            can_stop: controls.can_stop,
            rev: controls.rev,
            record_unavailable: controls.record_unavailable,
        }
    }

    /// The value it carries.
    pub fn controls(&self) -> RecordingControls {
        RecordingControls {
            can_record: self.can_record,
            can_stop: self.can_stop,
            rev: self.rev,
            record_unavailable: self.record_unavailable,
        }
    }
}

/// `status.recording`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct StatusRecording {
    /// `[recording] enabled`.
    pub enabled: bool,
    /// The recorder answers health.
    pub recorder_ok: bool,
    /// The transcriber answers health.
    pub transcriber_ok: bool,
    /// The model the transcriber reports.
    pub model: Option<String>,
    /// Its backend.
    pub backend: Option<String>,
    /// Its workers.
    pub workers: u32,
    /// Active recordings.
    pub active: u32,
    /// Allowlisted tracks install-wide.
    pub tracks: u32,
    /// Rejoins in the last hour.
    pub rejoins_1h: u32,
    /// Queued speech awaiting transcription.
    pub backlog_audio_s: u64,
    /// Age of the oldest stored, untranscribed segment.
    pub oldest_pending_s: u64,
    /// Realtime factor over the last hour.
    pub rtf_1h: Option<f64>,
    /// Stored audio bytes.
    pub audio_bytes: u64,
    /// Held audio bytes.
    pub held_audio_bytes: u64,
}

#[cfg(test)]
// The package has no clippy.toml (Sew's allows unwrap in tests); the module says it itself.
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn recording_ref_round_trip() {
        let a: RecordingRef = serde_json::from_str("\"auto\"").unwrap();
        assert_eq!(a, RecordingRef::Auto);
        let id = Id::new(48_831_765_147_549_701).unwrap();
        let s = serde_json::to_string(&RecordingRef::Id(id)).unwrap();
        assert_eq!(s, "\"48831765147549701\"");
        let b: RecordingRef = serde_json::from_str(&s).unwrap();
        assert_eq!(b, RecordingRef::Id(id));
        assert!(serde_json::from_str::<RecordingRef>("\"nope\"").is_err());
    }

    #[test]
    fn consent_maps_to_s50_states() {
        assert_eq!(Consent::Granted.to_state(), ConsentState::Granted);
        assert_eq!(Consent::Pending.to_state(), ConsentState::Pending);
        assert_eq!(Consent::Declined.to_state(), ConsentState::Denied);
        assert_eq!(Consent::Withdrawn.to_state(), ConsentState::Denied);
    }

    #[test]
    fn notice_without_consent_invalid() {
        let n: RecordingNotice = serde_json::from_str(r#"{"recording_id":"auto"}"#).unwrap();
        assert!(n.validate().is_err());
    }

    #[test]
    fn notice_version_changes_with_every_slot() {
        let id = Id::new(48_831_765_147_549_701).unwrap();
        let p = ConsentPrompt {
            recording_id: RecordingRef::Id(id),
            notice_version: 0,
            recorder_name: RECORDER_DISPLAY_NAME.to_owned(),
            feature_label: RECORDING_FEATURE_LABEL.to_owned(),
            started_by: None,
            room: PromptRoom {
                channel_id: id,
                kind: PromptRoomKind::Voice,
                name: Some("standup".to_owned()),
            },
            audio_keep_days: 30,
            transcript: PromptTranscript::default(),
            admin_download: true,
            decline_mode: DeclineMode::JoinUnrecorded,
            recorded_now: vec![],
            required: false,
            app_readers: vec![],
            agent_readers: false,
        }
        .sealed();
        let mut q = p.clone();
        q.audio_keep_days = 7;
        assert_ne!(p.notice_version, q.compute_version());
        let mut r = p.clone();
        r.decline_mode = DeclineMode::NotJoin;
        assert_ne!(p.notice_version, r.compute_version());
        assert_eq!(p.notice_version, p.compute_version());
    }

    /// A prompt that sets neither new slot keeps the version 0.8.x gave it (0.8.x's blessed
    /// `ConsentPrompt.full` and `.auto` fixtures), so an old client's echoed answer still
    /// matches; setting `required` or `app_readers` changes it.
    #[test]
    fn new_slots_hash_only_when_set() {
        let id = |n: u64| Id::new(n).unwrap();
        let full = ConsentPrompt {
            recording_id: RecordingRef::Id(id(48_831_765_147_550_202)),
            notice_version: 0,
            recorder_name: RECORDER_DISPLAY_NAME.to_owned(),
            feature_label: RECORDING_FEATURE_LABEL.to_owned(),
            started_by: Some(PromptMember {
                member_id: id(48_831_765_147_549_699),
                display_name: "Morgan".to_owned(),
            }),
            room: PromptRoom {
                channel_id: id(48_831_765_147_549_698),
                kind: PromptRoomKind::Voice,
                name: Some("standup".to_owned()),
            },
            audio_keep_days: 30,
            transcript: PromptTranscript::default(),
            admin_download: true,
            decline_mode: DeclineMode::JoinUnrecorded,
            recorded_now: vec![id(48_831_765_147_549_699)],
            required: false,
            app_readers: vec![],
            agent_readers: false,
        }
        .sealed();
        assert_eq!(full.notice_version, 357_303_234);
        let auto = ConsentPrompt {
            recording_id: RecordingRef::Auto,
            started_by: None,
            room: PromptRoom {
                channel_id: id(48_831_765_147_549_698),
                kind: PromptRoomKind::Voice,
                name: None,
            },
            audio_keep_days: 0,
            decline_mode: DeclineMode::NotJoin,
            recorded_now: vec![],
            ..full.clone()
        }
        .sealed();
        assert_eq!(auto.notice_version, 3_743_614_694);
        // The JSON of a prompt without the new slots is 0.8.x's: neither key is written.
        let v = serde_json::to_value(&full).unwrap();
        assert!(v.get("required").is_none() && v.get("app_readers").is_none());
        let old: ConsentPrompt = serde_json::from_value(v).unwrap();
        assert_eq!(old, full);
        let mut r = full.clone();
        r.required = true;
        let r = r.sealed();
        assert_ne!(r.notice_version, full.notice_version);
        let mut a = full.clone();
        a.app_readers = vec!["Helpdesk".to_owned()];
        let a = a.sealed();
        assert_ne!(a.notice_version, full.notice_version);
        assert_ne!(a.notice_version, r.notice_version);
        let mut b = a.clone();
        b.app_readers = vec!["Payroll".to_owned()];
        assert_ne!(b.compute_version(), a.notice_version);
        // `agent_readers` too: hashed only when set, and left out of the JSON when not.
        let mut g = full.clone();
        g.agent_readers = true;
        let g = g.sealed();
        assert_ne!(g.notice_version, full.notice_version);
        assert_ne!(g.notice_version, r.notice_version);
        assert_eq!(serde_json::to_value(&g).unwrap()["agent_readers"], true);
        assert!(
            serde_json::to_value(&full)
                .unwrap()
                .get("agent_readers")
                .is_none()
        );
    }

    #[test]
    fn languages() {
        assert!(language_ok("auto") && language_ok("de") && language_ok("haw"));
        assert!(!language_ok("xx"));
    }
}