BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / recording.rs

recording.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
recording.rs 15.9 KiB Download Raw
1use serde_json::{Value, json};
2
3use crate::captions::recorder_features;
4use crate::trouter_events::find_key;
5
6const CLOUD_RECORDING: &str = "cloudRecording";
7const TRANSCRIPTION: &str = "transcription";
8const CONSENT_DETAILS: &str = "recordingConsentDetails";
9const ACTIVE: &str = "Active";
10const RECORDING_AND_TRANSCRIPT: [&str; 2] = ["recording", "realTimeTranscript"];
11const RECORDING_ONLY: [&str; 1] = ["recording"];
12const TRANSCRIPT_ONLY: [&str; 1] = ["realTimeTranscript"];
13const TRANSCRIPTION_MODE: &str = "transcription";
14const RECORDING_MODE_KEY: &str = "recording";
15const STORAGE_TYPE: &str = "OnedriveForBusiness";
16const STORAGE_LOCATION: &str = "Recordings";
17const VIDEO_MODE: &str = "Normal";
18const AUDIO_ONLY_MODE: &str = "AudioOnly";
19const FILE_SUFFIX: &str = "Meeting Recording";
20const CONSENT_STATE: &str = "consentToRecording";
21const DENY_STATE: &str = "denyConsentToRecording";
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub struct StateChange {
25 pub recording: Option<bool>,
26 pub transcription: Option<bool>,
27 pub consent_required: Option<bool>,
28}
29
30impl StateChange {
31 pub fn is_empty(&self) -> bool {
32 self.recording.is_none() && self.transcription.is_none() && self.consent_required.is_none()
33 }
34}
35
36#[derive(Debug, Clone, Copy, Default)]
37pub struct RecordingStatus {
38 active: bool,
39 transcribing: bool,
40 consent_required: bool,
41 sequence: u64,
42 transcription_sequence: u64,
43}
44
45impl RecordingStatus {
46 pub fn active(&self) -> bool {
47 self.active
48 }
49
50 pub fn transcribing(&self) -> bool {
51 self.transcribing
52 }
53
54 pub fn consent_required(&self) -> bool {
55 self.consent_required
56 }
57
58 fn newer_state(body: &Value, key: &str, last_sequence: &mut u64) -> Option<bool> {
59 let state = find_key(body, key)?;
60 let sequence = state["sequenceNumber"].as_u64().unwrap_or_default();
61 let current = state["value"]["State"]
62 .as_str()
63 .map(|name| name == ACTIVE)?;
64 (sequence >= *last_sequence).then(|| {
65 *last_sequence = sequence;
66 current
67 })
68 }
69
70 pub fn apply(&mut self, body: &Value) -> StateChange {
71 let mut change = StateChange::default();
72 if let Some(current) = Self::newer_state(body, CLOUD_RECORDING, &mut self.sequence)
73 && current != self.active
74 {
75 self.active = current;
76 change.recording = Some(current);
77 }
78 if let Some(current) =
79 Self::newer_state(body, TRANSCRIPTION, &mut self.transcription_sequence)
80 && current != self.transcribing
81 {
82 self.transcribing = current;
83 change.transcription = Some(current);
84 }
85 if let Some(required) = find_key(body, CONSENT_DETAILS)
86 .and_then(|details| details["consentActivelyRequired"].as_bool())
87 && required != self.consent_required
88 {
89 self.consent_required = required;
90 change.consent_required = Some(required);
91 }
92 change
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
97pub enum RecordingKind {
98 #[default]
99 Video,
100 AudioOnly,
101 TranscriptOnly,
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
105pub enum StopScope {
106 #[default]
107 Both,
108 RecordingOnly,
109 TranscriptionOnly,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum RecordingCommand {
114 Start(RecordingKind),
115 Stop(StopScope),
116}
117
118#[derive(Debug, Clone, Default)]
119pub struct RecordingPlan {
120 pub title: String,
121 pub kind: RecordingKind,
122 pub scope: StopScope,
123}
124
125impl RecordingPlan {
126 pub fn start(&self) -> RecordingCommand {
127 RecordingCommand::Start(self.kind)
128 }
129
130 pub fn stop(&self) -> RecordingCommand {
131 RecordingCommand::Stop(self.scope)
132 }
133}
134
135#[derive(Debug, Clone, Copy)]
136pub struct StartDetails<'a> {
137 pub own_mri: &'a str,
138 pub participant_leg_id: &'a str,
139 pub timestamp: &'a str,
140 pub file_name: &'a str,
141 pub meeting_title: &'a str,
142 pub organizer_name: &'a str,
143 pub correlation_id: &'a str,
144}
145
146/// The skype token is added inside the page, so the body travels without it.
147pub fn start_body(kind: RecordingKind, details: StartDetails<'_>) -> Value {
148 let mut parameters = json!({
149 "recordingFeatures": recorder_features(),
150 "recordingStorageSettings": [{
151 "StorageType": STORAGE_TYPE,
152 "StorageLocation": STORAGE_LOCATION,
153 "FileName": details.file_name,
154 }],
155 "correlationId": details.correlation_id,
156 "meetingTitle": details.meeting_title,
157 "exchangeId": null,
158 "meetingOrganizer": details.organizer_name,
159 "spokenLanguage": "",
160 "type": "start",
161 });
162 let mut body = json!({
163 "timestamp": details.timestamp,
164 "participantMri": details.own_mri,
165 "participantLegId": details.participant_leg_id,
166 "action": "start",
167 });
168 match kind {
169 RecordingKind::Video => parameters["recordingMode"] = json!(VIDEO_MODE),
170 RecordingKind::AudioOnly => parameters["recordingMode"] = json!(AUDIO_ONLY_MODE),
171 RecordingKind::TranscriptOnly => body["mode"] = json!(TRANSCRIPTION_MODE),
172 }
173 body["processingModes"] = match kind {
174 RecordingKind::TranscriptOnly => json!(TRANSCRIPT_ONLY),
175 RecordingKind::Video | RecordingKind::AudioOnly => json!(RECORDING_AND_TRANSCRIPT),
176 };
177 body["actionParameters"] = parameters;
178 body
179}
180
181pub fn stop_body(
182 scope: StopScope,
183 own_mri: &str,
184 participant_leg_id: &str,
185 timestamp: &str,
186) -> Value {
187 let mut body = json!({
188 "timestamp": timestamp,
189 "participantMri": own_mri,
190 "participantLegId": participant_leg_id,
191 "action": "stop",
192 });
193 match scope {
194 StopScope::Both => body["processingModes"] = json!(RECORDING_AND_TRANSCRIPT),
195 StopScope::RecordingOnly => {
196 body["mode"] = json!(RECORDING_MODE_KEY);
197 body["processingModes"] = json!(RECORDING_ONLY);
198 }
199 StopScope::TranscriptionOnly => {
200 body["mode"] = json!(TRANSCRIPTION_MODE);
201 body["processingModes"] = json!(TRANSCRIPT_ONLY);
202 }
203 }
204 body
205}
206
207pub fn command_body(command: RecordingCommand, details: StartDetails<'_>) -> Value {
208 match command {
209 RecordingCommand::Start(kind) => start_body(kind, details),
210 RecordingCommand::Stop(scope) => stop_body(
211 scope,
212 details.own_mri,
213 details.participant_leg_id,
214 details.timestamp,
215 ),
216 }
217}
218
219pub fn file_name(meeting_title: &str, now: chrono::DateTime<chrono::Utc>) -> String {
220 let title = if meeting_title.trim().is_empty() {
221 "Meeting"
222 } else {
223 meeting_title.trim()
224 };
225 let safe: String = title
226 .chars()
227 .map(|letter| {
228 if letter.is_alphanumeric() || letter == ' ' || letter == '-' {
229 letter
230 } else {
231 '_'
232 }
233 })
234 .collect();
235 format!("{safe}-{}-{FILE_SUFFIX}", now.format("%Y%m%d_%H%M%S"))
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239pub enum Consent {
240 Give,
241 Deny,
242}
243
244pub fn consent_body(from: Value, sequence_number: u32, consent: Consent) -> Value {
245 let state_type = match consent {
246 Consent::Give => CONSENT_STATE,
247 Consent::Deny => DENY_STATE,
248 };
249 json!({
250 "from": from,
251 "publishedState": {
252 "stateType": state_type,
253 "level": "user",
254 "content": "{}",
255 "sequenceNumber": sequence_number,
256 },
257 })
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263
264 fn update(state: &str, sequence: u64) -> Value {
265 json!({"meetingStates": {"cloudRecording": {"value": {"State": state}, "sequenceNumber": sequence}, "transcription": {"value": {"State": state}, "sequenceNumber": sequence}}})
266 }
267
268 fn consent(required: bool) -> Value {
269 json!({"meetingDetails": {"recordingConsentDetails": {"explicitRecordingConsentEnabled": true, "consentActivelyRequired": required}}})
270 }
271
272 #[test]
273 fn the_recording_state_follows_the_meeting_state_and_ignores_stale_updates() {
274 let mut status = RecordingStatus::default();
275 assert_eq!(
276 status.apply(&update("Active", 3)),
277 StateChange {
278 recording: Some(true),
279 transcription: Some(true),
280 consent_required: None
281 }
282 );
283 assert!(status.active());
284 assert!(status.apply(&update("Active", 3)).is_empty());
285 assert!(status.apply(&update("Inactive", 2)).is_empty());
286 assert!(status.active());
287 assert_eq!(status.apply(&update("Inactive", 4)).recording, Some(false));
288 assert!(!status.active());
289 }
290
291 #[test]
292 fn transcription_runs_on_its_own_state_and_sequence() {
293 let mut status = RecordingStatus::default();
294 let transcript_only = json!({"meetingStates": {"transcription": {"value": {"State": "Active"}, "sequenceNumber": 2}}});
295 assert_eq!(
296 status.apply(&transcript_only),
297 StateChange {
298 recording: None,
299 transcription: Some(true),
300 consent_required: None
301 }
302 );
303 assert!(status.transcribing() && !status.active());
304 let stale = json!({"meetingStates": {"transcription": {"value": {"State": "Inactive"}, "sequenceNumber": 1}}});
305 assert!(status.apply(&stale).is_empty());
306 let stopped = json!({"meetingStates": {"transcription": {"value": {"State": "Inactive"}, "sequenceNumber": 3}}});
307 assert_eq!(status.apply(&stopped).transcription, Some(false));
308 }
309
310 #[test]
311 fn unrelated_updates_change_nothing() {
312 let mut status = RecordingStatus::default();
313 assert!(
314 status
315 .apply(&json!({"activeModalities": {"groupChat": {"threadId": "19:x"}}}))
316 .is_empty()
317 );
318 assert!(status.apply(&Value::Null).is_empty());
319 }
320
321 #[test]
322 fn consent_is_required_when_the_meeting_says_so() {
323 let mut status = RecordingStatus::default();
324 assert!(status.apply(&consent(false)).is_empty());
325 assert_eq!(
326 status.apply(&consent(true)),
327 StateChange {
328 recording: None,
329 transcription: None,
330 consent_required: Some(true)
331 }
332 );
333 assert!(status.consent_required());
334 assert!(status.apply(&consent(true)).is_empty());
335 assert_eq!(status.apply(&consent(false)).consent_required, Some(false));
336 }
337
338 #[test]
339 fn one_update_can_carry_both_states() {
340 let mut both = update("Active", 1);
341 both["meetingDetails"] = consent(true)["meetingDetails"].clone();
342 let change = RecordingStatus::default().apply(&both);
343 assert_eq!(
344 change,
345 StateChange {
346 recording: Some(true),
347 transcription: Some(true),
348 consent_required: Some(true)
349 }
350 );
351 }
352
353 fn details() -> StartDetails<'static> {
354 StartDetails {
355 own_mri: "8:orgid:me",
356 participant_leg_id: "leg-1",
357 timestamp: "2026-10-10T08:44:12.705Z",
358 file_name: "Standup-20261010_084412-Meeting Recording",
359 meeting_title: "Standup",
360 organizer_name: "Me",
361 correlation_id: "corr-1",
362 }
363 }
364
365 #[test]
366 fn the_start_command_records_video_to_onedrive_without_a_mode_key() {
367 let body = command_body(RecordingCommand::Start(RecordingKind::Video), details());
368 assert_eq!(body["action"], "start");
369 assert_eq!(
370 body["processingModes"],
371 json!(["recording", "realTimeTranscript"])
372 );
373 assert!(body.get("mode").is_none());
374 assert!(body.get("participantSkypeToken").is_none());
375 let parameters = &body["actionParameters"];
376 assert_eq!(parameters["type"], "start");
377 assert_eq!(parameters["recordingMode"], "Normal");
378 assert_eq!(parameters["meetingTitle"], "Standup");
379 assert_eq!(
380 parameters["recordingStorageSettings"][0]["StorageType"],
381 "OnedriveForBusiness"
382 );
383 assert_eq!(
384 parameters["recordingStorageSettings"][0]["StorageLocation"],
385 "Recordings"
386 );
387 assert_eq!(
388 parameters["recordingStorageSettings"][0]["FileName"],
389 "Standup-20261010_084412-Meeting Recording"
390 );
391 assert_eq!(body["participantLegId"], "leg-1");
392 }
393
394 #[test]
395 fn audio_only_differs_from_video_in_the_recording_mode_alone() {
396 let video = start_body(RecordingKind::Video, details());
397 let mut audio = start_body(RecordingKind::AudioOnly, details());
398 assert_eq!(audio["actionParameters"]["recordingMode"], "AudioOnly");
399 audio["actionParameters"]["recordingMode"] =
400 video["actionParameters"]["recordingMode"].clone();
401 assert_eq!(audio, video);
402 }
403
404 #[test]
405 fn transcription_only_has_a_mode_one_processing_mode_and_no_recording_mode() {
406 let body = start_body(RecordingKind::TranscriptOnly, details());
407 assert_eq!(body["action"], "start");
408 assert_eq!(body["mode"], "transcription");
409 assert_eq!(body["processingModes"], json!(["realTimeTranscript"]));
410 assert!(body["actionParameters"].get("recordingMode").is_none());
411 assert_eq!(body["actionParameters"]["type"], "start");
412 assert_eq!(body["actionParameters"]["meetingTitle"], "Standup");
413 }
414
415 #[test]
416 fn the_three_stop_variants_match_the_capture() {
417 let stop = |scope| command_body(RecordingCommand::Stop(scope), details());
418 let both = stop(StopScope::Both);
419 assert_eq!(both["action"], "stop");
420 assert_eq!(
421 both["processingModes"],
422 json!(["recording", "realTimeTranscript"])
423 );
424 assert!(both.get("mode").is_none());
425 assert!(both.get("actionParameters").is_none());
426 assert_eq!(both["timestamp"], "2026-10-10T08:44:12.705Z");
427 let recording = stop(StopScope::RecordingOnly);
428 assert_eq!(recording["mode"], "recording");
429 assert_eq!(recording["processingModes"], json!(["recording"]));
430 let transcription = stop(StopScope::TranscriptionOnly);
431 assert_eq!(transcription["mode"], "transcription");
432 assert_eq!(
433 transcription["processingModes"],
434 json!(["realTimeTranscript"])
435 );
436 }
437
438 #[test]
439 fn a_plan_names_its_start_and_stop_commands() {
440 let plan = RecordingPlan {
441 title: "Standup".into(),
442 kind: RecordingKind::AudioOnly,
443 scope: StopScope::RecordingOnly,
444 };
445 assert_eq!(
446 plan.start(),
447 RecordingCommand::Start(RecordingKind::AudioOnly)
448 );
449 assert_eq!(
450 plan.stop(),
451 RecordingCommand::Stop(StopScope::RecordingOnly)
452 );
453 }
454
455 #[test]
456 fn file_names_are_safe_and_stamped() {
457 let at = chrono::DateTime::parse_from_rfc3339("2026-10-10T08:44:12Z")
458 .unwrap()
459 .with_timezone(&chrono::Utc);
460 assert_eq!(
461 file_name("Q3 / Plan: v2", at),
462 "Q3 _ Plan_ v2-20261010_084412-Meeting Recording"
463 );
464 assert_eq!(
465 file_name(" ", at),
466 "Meeting-20261010_084412-Meeting Recording"
467 );
468 }
469
470 #[test]
471 fn consent_and_denial_publish_a_user_state() {
472 let given = consent_body(json!({"id": "8:orgid:me"}), 4, Consent::Give);
473 assert_eq!(given["publishedState"]["stateType"], "consentToRecording");
474 assert_eq!(given["publishedState"]["level"], "user");
475 assert_eq!(given["publishedState"]["content"], "{}");
476 assert_eq!(given["publishedState"]["sequenceNumber"], 4);
477 let denied = consent_body(json!({"id": "8:orgid:me"}), 5, Consent::Deny);
478 assert_eq!(
479 denied["publishedState"]["stateType"],
480 "denyConsentToRecording"
481 );
482 }
483}