BlueGit

ict rusty-teams

Files

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

captions.rs

captions.rs 11.3 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 add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks) -> Value {
64 json!({
65 "disableUnmute": false,
66 "participants": {
67 "from": from,
68 "to": [{"id": RECORDING_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],
69 },
70 "participantInvitationData": {"botData": {
71 "meetingTitle": "",
72 "clientInfo": "Teams-R4",
73 "callId": call_id,
74 "threadId": thread_id,
75 "recorderFeatures": {
76 "enablePPTSharing": true,
77 "intermediateLiveCaptions": false,
78 "actionItemsEnabled": false,
79 "enableEmailAndMeetingLanguageModel": true,
80 "ceoSummit": false,
81 "useUnmixedAudio": true,
82 "enableTranscriptMeetingChaptering": false,
83 },
84 "mode": BOT_MODE,
85 "iCalUid": null,
86 "consumerType": "Teams",
87 "spokenLanguage": "",
88 "initiatorUserToken": INITIATOR_TOKEN_PLACEHOLDER,
89 "exchangeId": null,
90 "meetingOrganizer": organizer_name,
91 }},
92 "replacementDetails": null,
93 "groupContext": null,
94 "groupChat": {"threadId": thread_id, "messageId": null},
95 "links": {
96 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
97 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
98 },
99 })
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum BotAction {
104 Start,
105 Stop,
106}
107
108impl BotAction {
109 fn name(self) -> &'static str {
110 match self {
111 BotAction::Start => "start",
112 BotAction::Stop => "stop",
113 }
114 }
115}
116
117/// The skype token is added inside the page, so the body travels without it.
118pub fn command_body(action: BotAction, own_mri: &str, participant_leg_id: &str, timestamp: &str) -> Value {
119 json!({
120 "timestamp": timestamp,
121 "participantMri": own_mri,
122 "participantLegId": participant_leg_id,
123 "action": action.name(),
124 "mode": COMMAND_MODE,
125 "processingModes": [CLOSED_CAPTIONS],
126 })
127}
128
129pub fn endpoint_metadata(captions: bool) -> Value {
130 json!({"holographicCapabilities": 3, "transcriptionPrefs": {"closedCaptions": captions}})
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum CaptionStep {
135 AddBot,
136 Start,
137 Stop,
138 ReportOn,
139 Wait,
140}
141
142#[derive(Default)]
143pub struct CaptionFlow {
144 wanted: bool,
145 bot_requested: bool,
146 started: bool,
147 reported: bool,
148}
149
150impl CaptionFlow {
151 pub fn want(&mut self, wanted: bool) {
152 self.wanted = wanted;
153 if !wanted {
154 self.reported = false;
155 }
156 }
157
158 pub fn wanted(&self) -> bool {
159 self.wanted
160 }
161
162 pub fn on(&self) -> bool {
163 self.reported
164 }
165
166 pub fn text_arrived(&mut self) -> bool {
167 self.wanted && self.started && !std::mem::replace(&mut self.reported, true)
168 }
169
170 pub fn failed(&mut self) {
171 *self = CaptionFlow::default();
172 }
173
174 pub fn next(&mut self, bot: Option<&CaptionBot>) -> CaptionStep {
175 if !self.wanted {
176 return if std::mem::take(&mut self.started) { CaptionStep::Stop } else { CaptionStep::Wait };
177 }
178 let Some(bot) = bot else {
179 return if std::mem::replace(&mut self.bot_requested, true) { CaptionStep::Wait } else { CaptionStep::AddBot };
180 };
181 if bot.command_url.is_some() && !std::mem::replace(&mut self.started, true) {
182 return CaptionStep::Start;
183 }
184 if self.started && bot.active && !std::mem::replace(&mut self.reported, true) {
185 return CaptionStep::ReportOn;
186 }
187 CaptionStep::Wait
188 }
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 fn bot(command_url: bool, active: bool) -> CaptionBot {
196 CaptionBot { mri: RECORDING_BOT_MRI.into(), command_url: command_url.then(|| "https://x/v2/oncommand/1".into()), active }
197 }
198
199 #[test]
200 fn recognition_results_become_entries_with_speaker_and_finality() {
201 let message = json!({"recognitionResults": [
202 {"id": "u1", "text": " Hello there ", "isFinal": false, "userId": "8:orgid:ana", "displayName": "Ana"},
203 {"id": "u2", "text": "", "userId": "8:orgid:bo"},
204 {"utteranceId": "u3", "rawText": "raw", "isFinal": true, "userId": "8:orgid:bo"},
205 ]});
206 let entries = parse_caption_message(message.to_string().as_bytes());
207 assert_eq!(entries.len(), 2);
208 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 });
209 assert_eq!(entries[1].id, "u3");
210 assert!(entries[1].is_final);
211 assert_eq!(entries[1].display_name, "");
212 }
213
214 #[test]
215 fn text_tracks_count_and_other_messages_and_bad_json_do_not() {
216 let tracks = json!({"textTracks": [{"id": "t", "text": "from a track", "userId": "x", "isFinal": true}]});
217 assert_eq!(parse_caption_message(tracks.to_string().as_bytes()).len(), 1);
218 assert!(parse_caption_message(br#"{"events": [{"type": "x"}]}"#).is_empty());
219 assert!(parse_caption_message(b"not json").is_empty());
220 assert!(parse_caption_message(&[]).is_empty());
221 }
222
223 #[test]
224 fn the_bot_invitation_carries_the_meeting_and_a_token_placeholder() {
225 let callbacks = CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1");
226 let body = add_bot_body(json!({"id": "8:orgid:me"}), "19:meeting_x@thread.v2", "call-1", "Me", &callbacks);
227 let bot_data = &body["participantInvitationData"]["botData"];
228 assert_eq!(body["participants"]["to"][0]["id"], RECORDING_BOT_MRI);
229 assert_eq!(bot_data["mode"], "RecordingAndTranscription");
230 assert_eq!(bot_data["threadId"], "19:meeting_x@thread.v2");
231 assert_eq!(bot_data["callId"], "call-1");
232 assert_eq!(bot_data["initiatorUserToken"], INITIATOR_TOKEN_PLACEHOLDER);
233 assert_eq!(body["groupChat"]["threadId"], "19:meeting_x@thread.v2");
234 assert!(body["links"]["addParticipantFailure"].as_str().unwrap().contains("/conversation/addParticipantFailure/"));
235 }
236
237 #[test]
238 fn start_and_stop_commands_differ_only_in_the_action() {
239 let start = command_body(BotAction::Start, "8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z");
240 let stop = command_body(BotAction::Stop, "8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z");
241 assert_eq!(start["action"], "start");
242 assert_eq!(stop["action"], "stop");
243 assert_eq!(start["mode"], "transcription");
244 assert_eq!(start["processingModes"], json!(["closedCaptions"]));
245 assert_eq!(start["participantLegId"], "leg-1");
246 assert!(start.get("participantSkypeToken").is_none());
247 assert_eq!(start["timestamp"], stop["timestamp"]);
248 }
249
250 #[test]
251 fn the_endpoint_metadata_switches_the_caption_preference() {
252 assert_eq!(endpoint_metadata(true)["transcriptionPrefs"]["closedCaptions"], true);
253 assert_eq!(endpoint_metadata(false)["transcriptionPrefs"]["closedCaptions"], false);
254 assert_eq!(endpoint_metadata(true)["holographicCapabilities"], 3);
255 }
256
257 #[test]
258 fn the_flow_adds_the_bot_once_then_starts_then_reports_then_stops() {
259 let mut flow = CaptionFlow::default();
260 assert_eq!(flow.next(None), CaptionStep::Wait);
261 flow.want(true);
262 assert_eq!(flow.next(None), CaptionStep::AddBot);
263 assert_eq!(flow.next(None), CaptionStep::Wait);
264 assert_eq!(flow.next(Some(&bot(false, false))), CaptionStep::Wait);
265 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
266 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Wait);
267 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);
268 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
269 flow.want(false);
270 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
271 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
272 }
273
274 #[test]
275 fn turning_captions_on_again_reuses_the_bot_in_the_roster() {
276 let mut flow = CaptionFlow::default();
277 flow.want(true);
278 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
279 flow.want(false);
280 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
281 flow.want(true);
282 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Start);
283 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);
284 }
285
286 #[test]
287 fn caption_text_proves_the_captions_are_on_even_before_the_roster_says_so() {
288 let mut flow = CaptionFlow::default();
289 assert!(!flow.text_arrived());
290 flow.want(true);
291 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
292 assert!(flow.text_arrived());
293 assert!(!flow.text_arrived());
294 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
295 flow.want(false);
296 assert!(!flow.text_arrived());
297 }
298
299 #[test]
300 fn a_failed_invitation_allows_another_try() {
301 let mut flow = CaptionFlow::default();
302 flow.want(true);
303 assert_eq!(flow.next(None), CaptionStep::AddBot);
304 flow.failed();
305 assert!(!flow.wanted());
306 flow.want(true);
307 assert_eq!(flow.next(None), CaptionStep::AddBot);
308 }
309}