BlueGit

ict rusty-teams

Files

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

captions.rs

captions.rs 11.5 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 fn endpoint_metadata(captions: bool) -> Value {
134 json!({"holographicCapabilities": 3, "transcriptionPrefs": {"closedCaptions": captions}})
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum CaptionStep {
139 AddBot,
140 Start,
141 Stop,
142 ReportOn,
143 Wait,
144}
145
146#[derive(Default)]
147pub struct CaptionFlow {
148 wanted: bool,
149 bot_requested: bool,
150 started: bool,
151 reported: bool,
152}
153
154impl CaptionFlow {
155 pub fn want(&mut self, wanted: bool) {
156 self.wanted = wanted;
157 if !wanted {
158 self.reported = false;
159 }
160 }
161
162 pub fn wanted(&self) -> bool {
163 self.wanted
164 }
165
166 pub fn on(&self) -> bool {
167 self.reported
168 }
169
170 pub fn text_arrived(&mut self) -> bool {
171 self.wanted && self.started && !std::mem::replace(&mut self.reported, true)
172 }
173
174 pub fn failed(&mut self) {
175 *self = CaptionFlow::default();
176 }
177
178 pub fn next(&mut self, bot: Option<&CaptionBot>) -> CaptionStep {
179 self.next_for(bot, |bot| bot.active)
180 }
181
182 pub fn next_for(&mut self, bot: Option<&CaptionBot>, is_active: fn(&CaptionBot) -> bool) -> CaptionStep {
183 if !self.wanted {
184 return if std::mem::take(&mut self.started) { CaptionStep::Stop } else { CaptionStep::Wait };
185 }
186 let Some(bot) = bot else {
187 return if std::mem::replace(&mut self.bot_requested, true) { CaptionStep::Wait } else { CaptionStep::AddBot };
188 };
189 if bot.command_url.is_some() && !std::mem::replace(&mut self.started, true) {
190 return CaptionStep::Start;
191 }
192 if self.started && is_active(bot) && !std::mem::replace(&mut self.reported, true) {
193 return CaptionStep::ReportOn;
194 }
195 CaptionStep::Wait
196 }
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 fn bot(command_url: bool, active: bool) -> CaptionBot {
204 CaptionBot { mri: RECORDING_BOT_MRI.into(), command_url: command_url.then(|| "https://x/v2/oncommand/1".into()), active, recording: false }
205 }
206
207 #[test]
208 fn recognition_results_become_entries_with_speaker_and_finality() {
209 let message = json!({"recognitionResults": [
210 {"id": "u1", "text": " Hello there ", "isFinal": false, "userId": "8:orgid:ana", "displayName": "Ana"},
211 {"id": "u2", "text": "", "userId": "8:orgid:bo"},
212 {"utteranceId": "u3", "rawText": "raw", "isFinal": true, "userId": "8:orgid:bo"},
213 ]});
214 let entries = parse_caption_message(message.to_string().as_bytes());
215 assert_eq!(entries.len(), 2);
216 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 });
217 assert_eq!(entries[1].id, "u3");
218 assert!(entries[1].is_final);
219 assert_eq!(entries[1].display_name, "");
220 }
221
222 #[test]
223 fn text_tracks_count_and_other_messages_and_bad_json_do_not() {
224 let tracks = json!({"textTracks": [{"id": "t", "text": "from a track", "userId": "x", "isFinal": true}]});
225 assert_eq!(parse_caption_message(tracks.to_string().as_bytes()).len(), 1);
226 assert!(parse_caption_message(br#"{"events": [{"type": "x"}]}"#).is_empty());
227 assert!(parse_caption_message(b"not json").is_empty());
228 assert!(parse_caption_message(&[]).is_empty());
229 }
230
231 #[test]
232 fn the_bot_invitation_carries_the_meeting_and_a_token_placeholder() {
233 let callbacks = CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1");
234 let body = add_bot_body(json!({"id": "8:orgid:me"}), "19:meeting_x@thread.v2", "call-1", "Me", &callbacks);
235 let bot_data = &body["participantInvitationData"]["botData"];
236 assert_eq!(body["participants"]["to"][0]["id"], RECORDING_BOT_MRI);
237 assert_eq!(bot_data["mode"], "RecordingAndTranscription");
238 assert_eq!(bot_data["threadId"], "19:meeting_x@thread.v2");
239 assert_eq!(bot_data["callId"], "call-1");
240 assert_eq!(bot_data["initiatorUserToken"], INITIATOR_TOKEN_PLACEHOLDER);
241 assert_eq!(body["groupChat"]["threadId"], "19:meeting_x@thread.v2");
242 assert!(body["links"]["addParticipantFailure"].as_str().unwrap().contains("/conversation/addParticipantFailure/"));
243 }
244
245 #[test]
246 fn start_and_stop_commands_differ_only_in_the_action() {
247 let start = command_body(BotAction::Start, "8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z");
248 let stop = command_body(BotAction::Stop, "8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z");
249 assert_eq!(start["action"], "start");
250 assert_eq!(stop["action"], "stop");
251 assert_eq!(start["mode"], "transcription");
252 assert_eq!(start["processingModes"], json!(["closedCaptions"]));
253 assert_eq!(start["participantLegId"], "leg-1");
254 assert!(start.get("participantSkypeToken").is_none());
255 assert_eq!(start["timestamp"], stop["timestamp"]);
256 }
257
258 #[test]
259 fn the_endpoint_metadata_switches_the_caption_preference() {
260 assert_eq!(endpoint_metadata(true)["transcriptionPrefs"]["closedCaptions"], true);
261 assert_eq!(endpoint_metadata(false)["transcriptionPrefs"]["closedCaptions"], false);
262 assert_eq!(endpoint_metadata(true)["holographicCapabilities"], 3);
263 }
264
265 #[test]
266 fn the_flow_adds_the_bot_once_then_starts_then_reports_then_stops() {
267 let mut flow = CaptionFlow::default();
268 assert_eq!(flow.next(None), CaptionStep::Wait);
269 flow.want(true);
270 assert_eq!(flow.next(None), CaptionStep::AddBot);
271 assert_eq!(flow.next(None), CaptionStep::Wait);
272 assert_eq!(flow.next(Some(&bot(false, false))), CaptionStep::Wait);
273 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
274 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Wait);
275 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);
276 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
277 flow.want(false);
278 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
279 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
280 }
281
282 #[test]
283 fn turning_captions_on_again_reuses_the_bot_in_the_roster() {
284 let mut flow = CaptionFlow::default();
285 flow.want(true);
286 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
287 flow.want(false);
288 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
289 flow.want(true);
290 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Start);
291 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);
292 }
293
294 #[test]
295 fn caption_text_proves_the_captions_are_on_even_before_the_roster_says_so() {
296 let mut flow = CaptionFlow::default();
297 assert!(!flow.text_arrived());
298 flow.want(true);
299 assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
300 assert!(flow.text_arrived());
301 assert!(!flow.text_arrived());
302 assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
303 flow.want(false);
304 assert!(!flow.text_arrived());
305 }
306
307 #[test]
308 fn a_failed_invitation_allows_another_try() {
309 let mut flow = CaptionFlow::default();
310 flow.want(true);
311 assert_eq!(flow.next(None), CaptionStep::AddBot);
312 flow.failed();
313 assert!(!flow.wanted());
314 flow.want(true);
315 assert_eq!(flow.next(None), CaptionStep::AddBot);
316 }
317}