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