BlueGit

ict rusty-teams

Files

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

captions.rs

captions.rs 13.6 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"].as_str().or_else(|| item["rawText"].as_str())?.trim();
49 if text.is_empty() {
50 return None;
51 }
52 let user_id = item["userId"].as_str().unwrap_or_default().to_owned();
53 let id = item["utteranceId"].as_str().or_else(|| item["id"].as_str()).map_or_else(|| user_id.clone(), str::to_owned);
54 Some(CaptionEntry {
55 id,
56 user_id,
57 display_name: item["displayName"].as_str().unwrap_or_default().to_owned(),
58 text: text.to_owned(),
59 is_final: item["isFinal"].as_bool().unwrap_or(false),
60 })
61}
62
63pub fn recorder_features() -> Value {
64 json!({
65 "enablePPTSharing": true,
66 "intermediateLiveCaptions": false,
67 "actionItemsEnabled": false,
68 "enableEmailAndMeetingLanguageModel": true,
69 "ceoSummit": false,
70 "useUnmixedAudio": true,
71 "enableTranscriptMeetingChaptering": false,
72 })
73}
74
75pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks) -> Value {
76 json!({
77 "disableUnmute": false,
78 "participants": {
79 "from": from,
80 "to": [{"id": RECORDING_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],
81 },
82 "participantInvitationData": {"botData": {
83 "meetingTitle": "",
84 "clientInfo": "Teams-R4",
85 "callId": call_id,
86 "threadId": thread_id,
87 "recorderFeatures": recorder_features(),
88 "mode": BOT_MODE,
89 "iCalUid": null,
90 "consumerType": "Teams",
91 "spokenLanguage": "",
92 "initiatorUserToken": INITIATOR_TOKEN_PLACEHOLDER,
93 "exchangeId": null,
94 "meetingOrganizer": organizer_name,
95 }},
96 "replacementDetails": null,
97 "groupContext": null,
98 "groupChat": {"threadId": thread_id, "messageId": null},
99 "links": {
100 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
101 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
102 },
103 })
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum BotAction {
108 Start,
109 Stop,
110}
111
112impl BotAction {
113 fn name(self) -> &'static str {
114 match self {
115 BotAction::Start => "start",
116 BotAction::Stop => "stop",
117 }
118 }
119}
120
121/// The skype token is added inside the page, so the body travels without it.
122pub fn command_body(action: BotAction, own_mri: &str, participant_leg_id: &str, timestamp: &str) -> Value {
123 json!({
124 "timestamp": timestamp,
125 "participantMri": own_mri,
126 "participantLegId": participant_leg_id,
127 "action": action.name(),
128 "mode": COMMAND_MODE,
129 "processingModes": [CLOSED_CAPTIONS],
130 })
131}
132
133pub const SPOKEN_LANGUAGES: [(&str, &str); 12] = [
134 ("en-US", "English (US)"),
135 ("en-GB", "English (UK)"),
136 ("de-DE", "German"),
137 ("fr-FR", "French"),
138 ("es-ES", "Spanish"),
139 ("it-IT", "Italian"),
140 ("nl-NL", "Dutch"),
141 ("pt-BR", "Portuguese (Brazil)"),
142 ("ja-JP", "Japanese"),
143 ("zh-CN", "Chinese (Simplified)"),
144 ("sv-SE", "Swedish"),
145 ("pl-PL", "Polish"),
146];
147
148pub fn language_body(own_mri: &str, participant_leg_id: &str, timestamp: &str, language_tag: &str) -> Value {
149 json!({
150 "timestamp": timestamp,
151 "participantMri": own_mri,
152 "participantLegId": participant_leg_id,
153 "action": "setLanguage",
154 "mode": COMMAND_MODE,
155 "processingModes": [CLOSED_CAPTIONS],
156 "actionParameters": {"spokenLanguage": language_tag.to_ascii_lowercase(), "type": "setLanguage"},
157 })
158}
159
160pub fn endpoint_metadata(captions: bool) -> Value {
161 json!({"holographicCapabilities": 3, "transcriptionPrefs": {"closedCaptions": captions}})
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum CaptionStep {
166 AddBot,
167 Start,
168 Stop,
169 ReportOn,
170 Wait,
171}
172
173#[derive(Default)]
174pub struct CaptionFlow {
175 wanted: bool,
176 bot_requested: bool,
177 started: bool,
178 reported: bool,
179}
180
181impl CaptionFlow {
182 pub fn want(&mut self, wanted: bool) {
183 self.wanted = wanted;
184 if !wanted {
185 self.reported = false;
186 }
187 }
188
189 pub fn stop(&mut self) {
190 self.wanted = false;
191 self.started = true;
192 self.reported = false;
193 }
194
195 pub fn wanted(&self) -> bool {
196 self.wanted
197 }
198
199 pub fn on(&self) -> bool {
200 self.reported
201 }
202
203 pub fn text_arrived(&mut self) -> bool {
204 self.wanted && self.started && !std::mem::replace(&mut self.reported, true)
205 }
206
207 pub fn failed(&mut self) {
208 *self = CaptionFlow::default();
209 }
210
211 pub fn next(&mut self, bot: Option<&CaptionBot>) -> CaptionStep {
212 self.next_for(bot, |bot| bot.active)
213 }
214
215 pub fn next_for(&mut self, bot: Option<&CaptionBot>, is_active: fn(&CaptionBot) -> bool) -> CaptionStep {
216 if !self.wanted {
217 return if std::mem::take(&mut self.started) { CaptionStep::Stop } else { CaptionStep::Wait };
218 }
219 let Some(bot) = bot else {
220 return if std::mem::replace(&mut self.bot_requested, true) { CaptionStep::Wait } else { CaptionStep::AddBot };
221 };
222 if bot.command_url.is_some() && !std::mem::replace(&mut self.started, true) {
223 return CaptionStep::Start;
224 }
225 if self.started && is_active(bot) && !std::mem::replace(&mut self.reported, true) {
226 return CaptionStep::ReportOn;
227 }
228 CaptionStep::Wait
229 }
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235
236 fn bot(command_url: bool, active: bool) -> CaptionBot {
237 CaptionBot { mri: RECORDING_BOT_MRI.into(), command_url: command_url.then(|| "https://x/v2/oncommand/1".into()), active, recording: false, audio_only: false }
238 }
239
240 #[test]
241 fn recognition_results_become_entries_with_speaker_and_finality() {
242 let message = json!({"recognitionResults": [
243 {"id": "u1", "text": " Hello there ", "isFinal": false, "userId": "8:orgid:ana", "displayName": "Ana"},
244 {"id": "u2", "text": "", "userId": "8:orgid:bo"},
245 {"utteranceId": "u3", "rawText": "raw", "isFinal": true, "userId": "8:orgid:bo"},
246 ]});
247 let entries = parse_caption_message(message.to_string().as_bytes());
248 assert_eq!(entries.len(), 2);
249 assert_eq!(entries[0], CaptionEntry { id: "u1".into(), user_id: "8:orgid:ana".into(), display_name: "Ana".into(), text: "Hello there".into(), is_final: false });
250 assert_eq!(entries[1].id, "u3");
251 assert!(entries[1].is_final);
252 assert_eq!(entries[1].display_name, "");
253 }
254
255 #[test]
256 fn text_tracks_count_and_other_messages_and_bad_json_do_not() {
257 let tracks = json!({"textTracks": [{"id": "t", "text": "from a track", "userId": "x", "isFinal": true}]});
258 assert_eq!(parse_caption_message(tracks.to_string().as_bytes()).len(), 1);
259 assert!(parse_caption_message(br#"{"events": [{"type": "x"}]}"#).is_empty());
260 assert!(parse_caption_message(b"not json").is_empty());
261 assert!(parse_caption_message(&[]).is_empty());
262 }
263
264 #[test]
265 fn the_bot_invitation_carries_the_meeting_and_a_token_placeholder() {
266 let callbacks = CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1");
267 let body = add_bot_body(json!({"id": "8:orgid:me"}), "19:meeting_x@thread.v2", "call-1", "Me", &callbacks);
268 let bot_data = &body["participantInvitationData"]["botData"];
269 assert_eq!(body["participants"]["to"][0]["id"], RECORDING_BOT_MRI);
270 assert_eq!(bot_data["mode"], "RecordingAndTranscription");
271 assert_eq!(bot_data["threadId"], "19:meeting_x@thread.v2");
272 assert_eq!(bot_data["callId"], "call-1");
273 assert_eq!(bot_data["initiatorUserToken"], INITIATOR_TOKEN_PLACEHOLDER);
274 assert_eq!(body["groupChat"]["threadId"], "19:meeting_x@thread.v2");
275 assert!(body["links"]["addParticipantFailure"].as_str().unwrap().contains("/conversation/addParticipantFailure/"));
276 }
277
278 #[test]
279 fn start_and_stop_commands_differ_only_in_the_action() {
280 let start = command_body(BotAction::Start, "8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z");
281 let stop = command_body(BotAction::Stop, "8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z");
282 assert_eq!(start["action"], "start");
283 assert_eq!(stop["action"], "stop");
284 assert_eq!(start["mode"], "transcription");
285 assert_eq!(start["processingModes"], json!(["closedCaptions"]));
286 assert_eq!(start["participantLegId"], "leg-1");
287 assert!(start.get("participantSkypeToken").is_none());
288 assert_eq!(start["timestamp"], stop["timestamp"]);
289 }
290
291 #[test]
292 fn the_language_command_sets_a_lower_case_spoken_language() {
293 let body = language_body("8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z", "de-DE");
294 assert_eq!(body["action"], "setLanguage");
295 assert_eq!(body["mode"], "transcription");
296 assert_eq!(body["processingModes"], json!(["closedCaptions"]));
297 assert_eq!(body["actionParameters"], json!({"spokenLanguage": "de-de", "type": "setLanguage"}));
298 assert_eq!(body["participantLegId"], "leg-1");
299 assert!(body.get("participantSkypeToken").is_none());
300 }
301
302 #[test]
303 fn every_listed_language_is_a_region_tag_with_a_label() {
304 assert!(SPOKEN_LANGUAGES.iter().all(|(tag, label)| tag.len() == 5 && tag.contains('-') && !label.is_empty()));
305 assert!(SPOKEN_LANGUAGES.iter().any(|(tag, _)| *tag == "en-US"));
306 }
307
308 #[test]
309 fn a_forced_stop_reaches_the_bot_even_when_this_session_did_not_start_it() {
310 let mut flow = CaptionFlow::default();
311 flow.stop();
312 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
313 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
314 }
315
316 #[test]
317 fn the_endpoint_metadata_switches_the_caption_preference() {
318 assert_eq!(endpoint_metadata(true)["transcriptionPrefs"]["closedCaptions"], true);
319 assert_eq!(endpoint_metadata(false)["transcriptionPrefs"]["closedCaptions"], false);
320 assert_eq!(endpoint_metadata(true)["holographicCapabilities"], 3);
321 }
322
323 #[test]
324 fn the_flow_adds_the_bot_once_then_starts_then_reports_then_stops() {
325 let mut flow = CaptionFlow::default();
326 assert_eq!(flow.next(None), CaptionStep::Wait);
327 flow.want(true);
328 assert_eq!(flow.next(None), CaptionStep::AddBot);
329 assert_eq!(flow.next(None), CaptionStep::Wait);
330 assert_eq!(flow.next(Some(&bot(false, false))), CaptionStep::Wait);
331 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
332 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Wait);
333 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);
334 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
335 flow.want(false);
336 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
337 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
338 }
339
340 #[test]
341 fn turning_captions_on_again_reuses_the_bot_in_the_roster() {
342 let mut flow = CaptionFlow::default();
343 flow.want(true);
344 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
345 flow.want(false);
346 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
347 flow.want(true);
348 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Start);
349 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);
350 }
351
352 #[test]
353 fn caption_text_proves_the_captions_are_on_even_before_the_roster_says_so() {
354 let mut flow = CaptionFlow::default();
355 assert!(!flow.text_arrived());
356 flow.want(true);
357 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
358 assert!(flow.text_arrived());
359 assert!(!flow.text_arrived());
360 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
361 flow.want(false);
362 assert!(!flow.text_arrived());
363 }
364
365 #[test]
366 fn a_failed_invitation_allows_another_try() {
367 let mut flow = CaptionFlow::default();
368 flow.want(true);
369 assert_eq!(flow.next(None), CaptionStep::AddBot);
370 flow.failed();
371 assert!(!flow.wanted());
372 flow.want(true);
373 assert_eq!(flow.next(None), CaptionStep::AddBot);
374 }
375}