BlueGit

ict rusty-teams

Files

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

captions.rs

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