BlueGit

ict rusty-teams

Files

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

captions.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
captions.rs 15.0 KiB Download Raw
1use serde_json::{Value, json};
2
3use crate::roster::CaptionBot;
4use crate::trouter_events::CallbackLinks;
5
6pub const CAPTIONS_DATA_ID: u8 = 3;
7pub const RECORDING_BOT_MRI: &str = "28:bdd75849-e0a6-4cce-8fc1-d7c0d4da43e5";
8pub const RECORDER_RESOURCE: &str = "4580fd1d-e5a3-4f56-9ad1-aab0e3bf8f76";
9pub const RECORDER_SCOPE: &str = "access_recorder_service";
10pub const INITIATOR_TOKEN_PLACEHOLDER: &str = "@@recorder-token@@";
11pub const COMMAND_SCRIPT: &str = include_str!("../assets/caption_command.js");
12const BOT_MODE: &str = "RecordingAndTranscription";
13const COMMAND_MODE: &str = "transcription";
14const CLOSED_CAPTIONS: &str = "closedCaptions";
15const RECOGNITION_RESULTS: &str = "recognitionResults";
16const TEXT_TRACKS: &str = "textTracks";
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct CaptionEntry {
20 pub id: String,
21 pub user_id: String,
22 pub display_name: String,
23 pub text: String,
24 pub is_final: bool,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum CaptionState {
29 Off,
30 Starting,
31 On,
32 Failed(String),
33}
34
35pub fn parse_caption_message(payload: &[u8]) -> Vec<CaptionEntry> {
36 let Ok(message) = serde_json::from_slice::<Value>(payload) else {
37 return Vec::new();
38 };
39 [RECOGNITION_RESULTS, TEXT_TRACKS]
40 .into_iter()
41 .filter_map(|key| message[key].as_array())
42 .flatten()
43 .filter_map(entry_from)
44 .collect()
45}
46
47fn entry_from(item: &Value) -> Option<CaptionEntry> {
48 let text = item["text"]
49 .as_str()
50 .or_else(|| item["rawText"].as_str())?
51 .trim();
52 if text.is_empty() {
53 return None;
54 }
55 let user_id = item["userId"].as_str().unwrap_or_default().to_owned();
56 let id = item["utteranceId"]
57 .as_str()
58 .or_else(|| item["id"].as_str())
59 .map_or_else(|| user_id.clone(), str::to_owned);
60 Some(CaptionEntry {
61 id,
62 user_id,
63 display_name: item["displayName"].as_str().unwrap_or_default().to_owned(),
64 text: text.to_owned(),
65 is_final: item["isFinal"].as_bool().unwrap_or(false),
66 })
67}
68
69pub fn recorder_features() -> Value {
70 json!({
71 "enablePPTSharing": true,
72 "intermediateLiveCaptions": false,
73 "actionItemsEnabled": false,
74 "enableEmailAndMeetingLanguageModel": true,
75 "ceoSummit": false,
76 "useUnmixedAudio": true,
77 "enableTranscriptMeetingChaptering": false,
78 })
79}
80
81pub fn add_bot_body(
82 from: Value,
83 thread_id: &str,
84 call_id: &str,
85 organizer_name: &str,
86 callbacks: &CallbackLinks,
87 threadless: bool,
88) -> Value {
89 let group_chat = if threadless {
90 Value::Null
91 } else {
92 json!({"threadId": thread_id, "messageId": null})
93 };
94 json!({
95 "disableUnmute": false,
96 "participants": {
97 "from": from,
98 "to": [{"id": RECORDING_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],
99 },
100 "participantInvitationData": {"botData": {
101 "meetingTitle": "",
102 "clientInfo": "Teams-R4",
103 "callId": call_id,
104 "threadId": thread_id,
105 "recorderFeatures": recorder_features(),
106 "mode": BOT_MODE,
107 "iCalUid": null,
108 "consumerType": "Teams",
109 "spokenLanguage": "",
110 "initiatorUserToken": INITIATOR_TOKEN_PLACEHOLDER,
111 "exchangeId": null,
112 "meetingOrganizer": organizer_name,
113 }},
114 "replacementDetails": null,
115 "groupContext": null,
116 "groupChat": group_chat,
117 "links": {
118 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
119 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
120 },
121 })
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum BotAction {
126 Start,
127 Stop,
128}
129
130impl BotAction {
131 fn name(self) -> &'static str {
132 match self {
133 BotAction::Start => "start",
134 BotAction::Stop => "stop",
135 }
136 }
137}
138
139/// The skype token is added inside the page, so the body travels without it.
140pub fn command_body(
141 action: BotAction,
142 own_mri: &str,
143 participant_leg_id: &str,
144 timestamp: &str,
145) -> Value {
146 json!({
147 "timestamp": timestamp,
148 "participantMri": own_mri,
149 "participantLegId": participant_leg_id,
150 "action": action.name(),
151 "mode": COMMAND_MODE,
152 "processingModes": [CLOSED_CAPTIONS],
153 })
154}
155
156pub const SPOKEN_LANGUAGES: [(&str, &str); 12] = [
157 ("en-US", "English (US)"),
158 ("en-GB", "English (UK)"),
159 ("de-DE", "German"),
160 ("fr-FR", "French"),
161 ("es-ES", "Spanish"),
162 ("it-IT", "Italian"),
163 ("nl-NL", "Dutch"),
164 ("pt-BR", "Portuguese (Brazil)"),
165 ("ja-JP", "Japanese"),
166 ("zh-CN", "Chinese (Simplified)"),
167 ("sv-SE", "Swedish"),
168 ("pl-PL", "Polish"),
169];
170
171pub fn language_body(
172 own_mri: &str,
173 participant_leg_id: &str,
174 timestamp: &str,
175 language_tag: &str,
176) -> Value {
177 json!({
178 "timestamp": timestamp,
179 "participantMri": own_mri,
180 "participantLegId": participant_leg_id,
181 "action": "setLanguage",
182 "mode": COMMAND_MODE,
183 "processingModes": [CLOSED_CAPTIONS],
184 "actionParameters": {"spokenLanguage": language_tag.to_ascii_lowercase(), "type": "setLanguage"},
185 })
186}
187
188pub fn endpoint_metadata(captions: bool) -> Value {
189 json!({"holographicCapabilities": 3, "transcriptionPrefs": {"closedCaptions": captions}})
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193pub enum CaptionStep {
194 AddBot,
195 Start,
196 Stop,
197 ReportOn,
198 Wait,
199}
200
201#[derive(Default)]
202pub struct CaptionFlow {
203 wanted: bool,
204 bot_requested: bool,
205 started: bool,
206 reported: bool,
207}
208
209impl CaptionFlow {
210 pub fn want(&mut self, wanted: bool) {
211 self.wanted = wanted;
212 if !wanted {
213 self.reported = false;
214 }
215 }
216
217 pub fn stop(&mut self) {
218 self.wanted = false;
219 self.started = true;
220 self.reported = false;
221 }
222
223 pub fn wanted(&self) -> bool {
224 self.wanted
225 }
226
227 pub fn on(&self) -> bool {
228 self.reported
229 }
230
231 pub fn text_arrived(&mut self) -> bool {
232 self.wanted && self.started && !std::mem::replace(&mut self.reported, true)
233 }
234
235 pub fn failed(&mut self) {
236 *self = CaptionFlow::default();
237 }
238
239 pub fn next(&mut self, bot: Option<&CaptionBot>) -> CaptionStep {
240 self.next_for(bot, |bot| bot.active)
241 }
242
243 pub fn next_for(
244 &mut self,
245 bot: Option<&CaptionBot>,
246 is_active: fn(&CaptionBot) -> bool,
247 ) -> CaptionStep {
248 if !self.wanted {
249 return if std::mem::take(&mut self.started) {
250 CaptionStep::Stop
251 } else {
252 CaptionStep::Wait
253 };
254 }
255 let Some(bot) = bot else {
256 return if std::mem::replace(&mut self.bot_requested, true) {
257 CaptionStep::Wait
258 } else {
259 CaptionStep::AddBot
260 };
261 };
262 if bot.command_url.is_some() && !std::mem::replace(&mut self.started, true) {
263 return CaptionStep::Start;
264 }
265 if self.started && is_active(bot) && !std::mem::replace(&mut self.reported, true) {
266 return CaptionStep::ReportOn;
267 }
268 CaptionStep::Wait
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275
276 fn bot(command_url: bool, active: bool) -> CaptionBot {
277 CaptionBot {
278 mri: RECORDING_BOT_MRI.into(),
279 command_url: command_url.then(|| "https://x/v2/oncommand/1".into()),
280 active,
281 recording: false,
282 audio_only: false,
283 }
284 }
285
286 #[test]
287 fn recognition_results_become_entries_with_speaker_and_finality() {
288 let message = json!({"recognitionResults": [
289 {"id": "u1", "text": " Hello there ", "isFinal": false, "userId": "8:orgid:ana", "displayName": "Ana"},
290 {"id": "u2", "text": "", "userId": "8:orgid:bo"},
291 {"utteranceId": "u3", "rawText": "raw", "isFinal": true, "userId": "8:orgid:bo"},
292 ]});
293 let entries = parse_caption_message(message.to_string().as_bytes());
294 assert_eq!(entries.len(), 2);
295 assert_eq!(
296 entries[0],
297 CaptionEntry {
298 id: "u1".into(),
299 user_id: "8:orgid:ana".into(),
300 display_name: "Ana".into(),
301 text: "Hello there".into(),
302 is_final: false
303 }
304 );
305 assert_eq!(entries[1].id, "u3");
306 assert!(entries[1].is_final);
307 assert_eq!(entries[1].display_name, "");
308 }
309
310 #[test]
311 fn text_tracks_count_and_other_messages_and_bad_json_do_not() {
312 let tracks = json!({"textTracks": [{"id": "t", "text": "from a track", "userId": "x", "isFinal": true}]});
313 assert_eq!(
314 parse_caption_message(tracks.to_string().as_bytes()).len(),
315 1
316 );
317 assert!(parse_caption_message(br#"{"events": [{"type": "x"}]}"#).is_empty());
318 assert!(parse_caption_message(b"not json").is_empty());
319 assert!(parse_caption_message(&[]).is_empty());
320 }
321
322 #[test]
323 fn the_bot_invitation_carries_the_meeting_and_a_token_placeholder() {
324 let callbacks = CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1");
325 let body = add_bot_body(
326 json!({"id": "8:orgid:me"}),
327 "19:meeting_x@thread.v2",
328 "call-1",
329 "Me",
330 &callbacks,
331 false,
332 );
333 let direct = add_bot_body(
334 json!({"id": "8:orgid:me"}),
335 "19:a_b@unq.gbl.spaces",
336 "call-1",
337 "Me",
338 &callbacks,
339 true,
340 );
341 assert_eq!(direct["groupChat"], Value::Null);
342 assert_eq!(
343 direct["participantInvitationData"]["botData"]["threadId"],
344 "19:a_b@unq.gbl.spaces"
345 );
346 let bot_data = &body["participantInvitationData"]["botData"];
347 assert_eq!(body["participants"]["to"][0]["id"], RECORDING_BOT_MRI);
348 assert_eq!(bot_data["mode"], "RecordingAndTranscription");
349 assert_eq!(bot_data["threadId"], "19:meeting_x@thread.v2");
350 assert_eq!(bot_data["callId"], "call-1");
351 assert_eq!(bot_data["initiatorUserToken"], INITIATOR_TOKEN_PLACEHOLDER);
352 assert_eq!(body["groupChat"]["threadId"], "19:meeting_x@thread.v2");
353 assert!(
354 body["links"]["addParticipantFailure"]
355 .as_str()
356 .unwrap()
357 .contains("/conversation/addParticipantFailure/")
358 );
359 }
360
361 #[test]
362 fn start_and_stop_commands_differ_only_in_the_action() {
363 let start = command_body(
364 BotAction::Start,
365 "8:orgid:me",
366 "leg-1",
367 "2026-10-10T08:44:12.705Z",
368 );
369 let stop = command_body(
370 BotAction::Stop,
371 "8:orgid:me",
372 "leg-1",
373 "2026-10-10T08:44:12.705Z",
374 );
375 assert_eq!(start["action"], "start");
376 assert_eq!(stop["action"], "stop");
377 assert_eq!(start["mode"], "transcription");
378 assert_eq!(start["processingModes"], json!(["closedCaptions"]));
379 assert_eq!(start["participantLegId"], "leg-1");
380 assert!(start.get("participantSkypeToken").is_none());
381 assert_eq!(start["timestamp"], stop["timestamp"]);
382 }
383
384 #[test]
385 fn the_language_command_sets_a_lower_case_spoken_language() {
386 let body = language_body("8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z", "de-DE");
387 assert_eq!(body["action"], "setLanguage");
388 assert_eq!(body["mode"], "transcription");
389 assert_eq!(body["processingModes"], json!(["closedCaptions"]));
390 assert_eq!(
391 body["actionParameters"],
392 json!({"spokenLanguage": "de-de", "type": "setLanguage"})
393 );
394 assert_eq!(body["participantLegId"], "leg-1");
395 assert!(body.get("participantSkypeToken").is_none());
396 }
397
398 #[test]
399 fn every_listed_language_is_a_region_tag_with_a_label() {
400 assert!(
401 SPOKEN_LANGUAGES
402 .iter()
403 .all(|(tag, label)| tag.len() == 5 && tag.contains('-') && !label.is_empty())
404 );
405 assert!(SPOKEN_LANGUAGES.iter().any(|(tag, _)| *tag == "en-US"));
406 }
407
408 #[test]
409 fn a_forced_stop_reaches_the_bot_even_when_this_session_did_not_start_it() {
410 let mut flow = CaptionFlow::default();
411 flow.stop();
412 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
413 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
414 }
415
416 #[test]
417 fn the_endpoint_metadata_switches_the_caption_preference() {
418 assert_eq!(
419 endpoint_metadata(true)["transcriptionPrefs"]["closedCaptions"],
420 true
421 );
422 assert_eq!(
423 endpoint_metadata(false)["transcriptionPrefs"]["closedCaptions"],
424 false
425 );
426 assert_eq!(endpoint_metadata(true)["holographicCapabilities"], 3);
427 }
428
429 #[test]
430 fn the_flow_adds_the_bot_once_then_starts_then_reports_then_stops() {
431 let mut flow = CaptionFlow::default();
432 assert_eq!(flow.next(None), CaptionStep::Wait);
433 flow.want(true);
434 assert_eq!(flow.next(None), CaptionStep::AddBot);
435 assert_eq!(flow.next(None), CaptionStep::Wait);
436 assert_eq!(flow.next(Some(&bot(false, false))), CaptionStep::Wait);
437 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
438 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Wait);
439 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);
440 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
441 flow.want(false);
442 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
443 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
444 }
445
446 #[test]
447 fn turning_captions_on_again_reuses_the_bot_in_the_roster() {
448 let mut flow = CaptionFlow::default();
449 flow.want(true);
450 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
451 flow.want(false);
452 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
453 flow.want(true);
454 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Start);
455 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);
456 }
457
458 #[test]
459 fn caption_text_proves_the_captions_are_on_even_before_the_roster_says_so() {
460 let mut flow = CaptionFlow::default();
461 assert!(!flow.text_arrived());
462 flow.want(true);
463 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
464 assert!(flow.text_arrived());
465 assert!(!flow.text_arrived());
466 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
467 flow.want(false);
468 assert!(!flow.text_arrived());
469 }
470
471 #[test]
472 fn a_failed_invitation_allows_another_try() {
473 let mut flow = CaptionFlow::default();
474 flow.want(true);
475 assert_eq!(flow.next(None), CaptionStep::AddBot);
476 flow.failed();
477 assert!(!flow.wanted());
478 flow.want(true);
479 assert_eq!(flow.next(None), CaptionStep::AddBot);
480 }
481}