| 1 | use base64::Engine as _; |
| 2 | use base64::engine::general_purpose::URL_SAFE_NO_PAD; |
| 3 | use serde_json::{Value, json}; |
| 4 | use session::{Scope, Session}; |
| 5 | |
| 6 | use crate::chat_listing::ChatListing; |
| 7 | use crate::error::Error; |
| 8 | use crate::graph_events::graph_event_page; |
| 9 | use crate::json_id::id_text; |
| 10 | use crate::messages::encode; |
| 11 | |
| 12 | const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail"; |
| 13 | const RECORDING_SUCCESS: &str = "success"; |
| 14 | const SITE_SCOPE: &str = ".default"; |
| 15 | const MAX_MESSAGE_PAGES: usize = 40; |
| 16 | const MESSAGE_PAGE_SIZE: usize = 200; |
| 17 | const UNKNOWN_SPEAKER: &str = "?"; |
| 18 | |
| 19 | #[derive(Debug, Clone, PartialEq)] |
| 20 | pub struct TranscriptTurn { |
| 21 | pub speaker: String, |
| 22 | pub start_seconds: f64, |
| 23 | pub end_seconds: f64, |
| 24 | pub text: String, |
| 25 | } |
| 26 | |
| 27 | #[derive(Debug, Clone, PartialEq)] |
| 28 | pub struct MeetingTranscript { |
| 29 | pub meeting_thread_id: String, |
| 30 | pub recording_name: Option<String>, |
| 31 | pub created_at: Option<String>, |
| 32 | pub turns: Vec<TranscriptTurn>, |
| 33 | } |
| 34 | |
| 35 | #[derive(Debug, thiserror::Error)] |
| 36 | pub enum TranscriptError { |
| 37 | #[error("no finished recording in this meeting chat")] |
| 38 | NoRecording, |
| 39 | #[error("the recording has no transcript")] |
| 40 | NoTranscript, |
| 41 | #[error("no access to the recording or its transcript")] |
| 42 | AccessDenied, |
| 43 | #[error(transparent)] |
| 44 | Request(session::Error), |
| 45 | } |
| 46 | |
| 47 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 48 | pub struct Recording { |
| 49 | pub url: String, |
| 50 | pub name: Option<String>, |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 54 | pub struct TranscriptInfo { |
| 55 | pub id: String, |
| 56 | pub created_at: Option<String>, |
| 57 | } |
| 58 | |
| 59 | pub struct Transcripts<'a> { |
| 60 | session: &'a Session, |
| 61 | } |
| 62 | |
| 63 | impl<'a> Transcripts<'a> { |
| 64 | pub fn new(session: &'a Session) -> Self { |
| 65 | Transcripts { session } |
| 66 | } |
| 67 | |
| 68 | pub async fn for_meeting_chat( |
| 69 | &self, |
| 70 | thread_id: &str, |
| 71 | ) -> Result<MeetingTranscript, TranscriptError> { |
| 72 | let recording = self.find_recording(thread_id).await?; |
| 73 | let site = site_origin(&recording.url); |
| 74 | let site_scope = Scope::new(site.clone(), SITE_SCOPE); |
| 75 | let item_url = self.item_url(&recording.url, &site, &site_scope).await?; |
| 76 | let listing = self |
| 77 | .get( |
| 78 | &format!("{item_url}/media/transcripts"), |
| 79 | &site_scope, |
| 80 | TranscriptError::NoTranscript, |
| 81 | ) |
| 82 | .await?; |
| 83 | let transcript = newest_transcript(parse_transcript_list(&listing)) |
| 84 | .ok_or(TranscriptError::NoTranscript)?; |
| 85 | let content = self |
| 86 | .get( |
| 87 | &format!( |
| 88 | "{item_url}/media/transcripts/{}/streamContent?format=json", |
| 89 | encode(&transcript.id) |
| 90 | ), |
| 91 | &site_scope, |
| 92 | TranscriptError::NoTranscript, |
| 93 | ) |
| 94 | .await?; |
| 95 | Ok(MeetingTranscript { |
| 96 | meeting_thread_id: thread_id.to_owned(), |
| 97 | recording_name: recording.name, |
| 98 | created_at: transcript.created_at, |
| 99 | turns: parse_turns(&content), |
| 100 | }) |
| 101 | } |
| 102 | |
| 103 | async fn find_recording(&self, thread_id: &str) -> Result<Recording, TranscriptError> { |
| 104 | let mut recording = None; |
| 105 | self.visit_message_pages(thread_id, |page| { |
| 106 | recording = find_recording(&graph_event_page(thread_id, page)); |
| 107 | recording.is_some() |
| 108 | }) |
| 109 | .await?; |
| 110 | recording.ok_or(TranscriptError::NoRecording) |
| 111 | } |
| 112 | |
| 113 | /// Chat service message pages, newest arrival first, until `visit` returns true. |
| 114 | pub(crate) async fn visit_message_pages( |
| 115 | &self, |
| 116 | thread_id: &str, |
| 117 | mut visit: impl FnMut(&Value) -> bool, |
| 118 | ) -> Result<(), TranscriptError> { |
| 119 | let listing = ChatListing::new(self.session); |
| 120 | let mut before_ms = None; |
| 121 | for page_index in 0..MAX_MESSAGE_PAGES { |
| 122 | let page = match listing |
| 123 | .messages(thread_id, before_ms, MESSAGE_PAGE_SIZE) |
| 124 | .await |
| 125 | { |
| 126 | Ok(page) => page, |
| 127 | Err(error) if page_index == 0 => return Err(chatsvc_failure(error)), |
| 128 | Err(_) => break, |
| 129 | }; |
| 130 | if visit(&json!({"messages": page.messages})) { |
| 131 | break; |
| 132 | } |
| 133 | before_ms = page |
| 134 | .messages |
| 135 | .iter() |
| 136 | .filter_map(|message| id_text(&message["id"])?.parse::<i64>().ok()) |
| 137 | .min(); |
| 138 | if !page.has_older || before_ms.is_none() { |
| 139 | break; |
| 140 | } |
| 141 | } |
| 142 | Ok(()) |
| 143 | } |
| 144 | |
| 145 | async fn item_url( |
| 146 | &self, |
| 147 | recording_url: &str, |
| 148 | site: &str, |
| 149 | site_scope: &Scope, |
| 150 | ) -> Result<String, TranscriptError> { |
| 151 | let item = self |
| 152 | .get( |
| 153 | &format!( |
| 154 | "{site}/_api/v2.1/shares/{}/driveItem?$select=id,parentReference", |
| 155 | share_id(recording_url) |
| 156 | ), |
| 157 | site_scope, |
| 158 | TranscriptError::NoRecording, |
| 159 | ) |
| 160 | .await?; |
| 161 | let drive_id = item |
| 162 | .pointer("/parentReference/driveId") |
| 163 | .and_then(Value::as_str); |
| 164 | let item_id = item.get("id").and_then(Value::as_str); |
| 165 | match (drive_id, item_id) { |
| 166 | (Some(drive_id), Some(item_id)) => Ok(format!( |
| 167 | "{site}/_api/v2.1/drives/{drive_id}/items/{item_id}" |
| 168 | )), |
| 169 | _ => Err(TranscriptError::NoRecording), |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | pub(crate) async fn get( |
| 174 | &self, |
| 175 | url: &str, |
| 176 | scope: &Scope, |
| 177 | not_found: TranscriptError, |
| 178 | ) -> Result<Value, TranscriptError> { |
| 179 | match self |
| 180 | .session |
| 181 | .request(session::Method::Get, url, scope, None) |
| 182 | .await |
| 183 | { |
| 184 | Ok(answer) => Ok(answer.body), |
| 185 | Err(session::Error::Api { |
| 186 | status: 403 | 401, .. |
| 187 | }) => Err(TranscriptError::AccessDenied), |
| 188 | Err(session::Error::Api { status: 404, .. }) => Err(not_found), |
| 189 | Err(error) => Err(TranscriptError::Request(error)), |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | pub(crate) fn chatsvc_failure(error: Error) -> TranscriptError { |
| 195 | match error { |
| 196 | Error::Session(session::Error::Api { |
| 197 | status: 403 | 401, .. |
| 198 | }) => TranscriptError::AccessDenied, |
| 199 | Error::Session(session::Error::Api { status: 404, .. }) => TranscriptError::NoRecording, |
| 200 | Error::Session(error) => TranscriptError::Request(error), |
| 201 | _ => TranscriptError::NoRecording, |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | pub fn find_recording(messages_json: &Value) -> Option<Recording> { |
| 206 | messages_json |
| 207 | .get("value")? |
| 208 | .as_array()? |
| 209 | .iter() |
| 210 | .find_map(|message| { |
| 211 | let detail = message.get("eventDetail")?; |
| 212 | let matches = detail.get("@odata.type").and_then(Value::as_str) |
| 213 | == Some(RECORDING_EVENT) |
| 214 | && detail.get("callRecordingStatus").and_then(Value::as_str) |
| 215 | == Some(RECORDING_SUCCESS); |
| 216 | let url = detail.get("callRecordingUrl").and_then(Value::as_str)?; |
| 217 | if !matches || !url.starts_with("https://") { |
| 218 | return None; |
| 219 | } |
| 220 | Some(Recording { |
| 221 | url: url.to_owned(), |
| 222 | name: detail |
| 223 | .get("callRecordingDisplayName") |
| 224 | .and_then(Value::as_str) |
| 225 | .filter(|name| !name.is_empty()) |
| 226 | .map(str::to_owned), |
| 227 | }) |
| 228 | }) |
| 229 | } |
| 230 | |
| 231 | pub fn find_recording_url(messages_json: &Value) -> Option<String> { |
| 232 | find_recording(messages_json).map(|recording| recording.url) |
| 233 | } |
| 234 | |
| 235 | pub fn share_id(url: &str) -> String { |
| 236 | format!("u!{}", URL_SAFE_NO_PAD.encode(url)) |
| 237 | } |
| 238 | |
| 239 | pub fn site_origin(url: &str) -> String { |
| 240 | let (scheme, rest) = url.split_once("://").unwrap_or(("https", url)); |
| 241 | let host = rest.split(['/', '?', '#']).next().unwrap_or(rest); |
| 242 | format!("{scheme}://{host}") |
| 243 | } |
| 244 | |
| 245 | pub fn parse_transcript_list(listing_json: &Value) -> Vec<TranscriptInfo> { |
| 246 | listing_json |
| 247 | .get("value") |
| 248 | .and_then(Value::as_array) |
| 249 | .into_iter() |
| 250 | .flatten() |
| 251 | .filter(|entry| { |
| 252 | entry |
| 253 | .get("isVisible") |
| 254 | .and_then(Value::as_bool) |
| 255 | .unwrap_or(true) |
| 256 | }) |
| 257 | .filter_map(|entry| { |
| 258 | Some(TranscriptInfo { |
| 259 | id: entry |
| 260 | .get("id")? |
| 261 | .as_str() |
| 262 | .filter(|id| !id.is_empty())? |
| 263 | .to_owned(), |
| 264 | created_at: entry |
| 265 | .get("createdDateTime") |
| 266 | .and_then(Value::as_str) |
| 267 | .map(str::to_owned), |
| 268 | }) |
| 269 | }) |
| 270 | .collect() |
| 271 | } |
| 272 | |
| 273 | pub fn newest_transcript(transcripts: Vec<TranscriptInfo>) -> Option<TranscriptInfo> { |
| 274 | transcripts |
| 275 | .into_iter() |
| 276 | .max_by(|left, right| left.created_at.cmp(&right.created_at)) |
| 277 | } |
| 278 | |
| 279 | pub fn parse_turns(content_json: &Value) -> Vec<TranscriptTurn> { |
| 280 | let turns = content_json |
| 281 | .get("entries") |
| 282 | .and_then(Value::as_array) |
| 283 | .into_iter() |
| 284 | .flatten() |
| 285 | .filter_map(|entry| { |
| 286 | let text = entry.get("text").and_then(Value::as_str)?.trim(); |
| 287 | if text.is_empty() { |
| 288 | return None; |
| 289 | } |
| 290 | let speaker = entry |
| 291 | .get("speakerDisplayName") |
| 292 | .and_then(Value::as_str) |
| 293 | .filter(|name| !name.is_empty()) |
| 294 | .unwrap_or(UNKNOWN_SPEAKER); |
| 295 | Some(TranscriptTurn { |
| 296 | speaker: speaker.to_owned(), |
| 297 | start_seconds: offset_seconds(entry.get("startOffset")), |
| 298 | end_seconds: offset_seconds(entry.get("endOffset")), |
| 299 | text: text.to_owned(), |
| 300 | }) |
| 301 | }) |
| 302 | .collect(); |
| 303 | merge_consecutive_turns(turns) |
| 304 | } |
| 305 | |
| 306 | pub fn merge_consecutive_turns(turns: Vec<TranscriptTurn>) -> Vec<TranscriptTurn> { |
| 307 | let mut merged: Vec<TranscriptTurn> = Vec::new(); |
| 308 | for turn in turns { |
| 309 | match merged.last_mut() { |
| 310 | Some(last) if last.speaker == turn.speaker => { |
| 311 | last.text.push(' '); |
| 312 | last.text.push_str(&turn.text); |
| 313 | last.end_seconds = turn.end_seconds; |
| 314 | } |
| 315 | _ => merged.push(turn), |
| 316 | } |
| 317 | } |
| 318 | merged |
| 319 | } |
| 320 | |
| 321 | fn offset_seconds(offset: Option<&Value>) -> f64 { |
| 322 | offset |
| 323 | .and_then(Value::as_str) |
| 324 | .map(|text| { |
| 325 | text.split(':').fold(0.0, |total, part| { |
| 326 | total * 60.0 + part.parse::<f64>().unwrap_or(0.0) |
| 327 | }) |
| 328 | }) |
| 329 | .unwrap_or(0.0) |
| 330 | } |
| 331 | |
| 332 | #[cfg(test)] |
| 333 | mod tests { |
| 334 | use super::*; |
| 335 | |
| 336 | fn fixture(name: &str) -> Value { |
| 337 | let path = format!( |
| 338 | "{}/tests/fixtures/transcripts/{name}", |
| 339 | env!("CARGO_MANIFEST_DIR") |
| 340 | ); |
| 341 | serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() |
| 342 | } |
| 343 | |
| 344 | #[test] |
| 345 | fn finds_the_successful_recording_only() { |
| 346 | let recording = find_recording(&fixture("messages.json")).unwrap(); |
| 347 | assert!(recording.url.ends_with("Weekly%20sync.mp4")); |
| 348 | assert_eq!( |
| 349 | recording.name.as_deref(), |
| 350 | Some("Weekly sync-20260302_100000-Meeting Recording.mp4") |
| 351 | ); |
| 352 | assert_eq!( |
| 353 | find_recording_url(&fixture("messages.json")), |
| 354 | Some(recording.url) |
| 355 | ); |
| 356 | } |
| 357 | |
| 358 | #[test] |
| 359 | fn no_recording_in_chat_without_event() { |
| 360 | assert_eq!( |
| 361 | find_recording_url(&serde_json::json!({"value": [{"id": "1"}]})), |
| 362 | None |
| 363 | ); |
| 364 | assert_eq!(find_recording_url(&serde_json::json!({})), None); |
| 365 | } |
| 366 | |
| 367 | #[test] |
| 368 | fn share_id_is_unpadded_base64url() { |
| 369 | assert_eq!( |
| 370 | share_id("https://a.example/x?y=>>"), |
| 371 | "u!aHR0cHM6Ly9hLmV4YW1wbGUveD95PT4-" |
| 372 | ); |
| 373 | assert!(!share_id("https://a.example/ab").contains('=')); |
| 374 | } |
| 375 | |
| 376 | #[test] |
| 377 | fn site_origin_drops_path() { |
| 378 | assert_eq!( |
| 379 | site_origin("https://contoso-my.sharepoint.com/personal/a/b.mp4?e=1"), |
| 380 | "https://contoso-my.sharepoint.com" |
| 381 | ); |
| 382 | } |
| 383 | |
| 384 | #[test] |
| 385 | fn list_skips_hidden_and_idless_and_picks_newest() { |
| 386 | let transcripts = parse_transcript_list(&fixture("list.json")); |
| 387 | assert_eq!(transcripts.len(), 2); |
| 388 | assert_eq!(newest_transcript(transcripts).unwrap().id, "t-new"); |
| 389 | assert_eq!(newest_transcript(Vec::new()), None); |
| 390 | } |
| 391 | |
| 392 | #[test] |
| 393 | fn turns_merge_same_speaker_and_parse_offsets() { |
| 394 | let turns = parse_turns(&fixture("content.json")); |
| 395 | assert_eq!(turns.len(), 4); |
| 396 | assert_eq!(turns[0].speaker, "Alex Example"); |
| 397 | assert_eq!(turns[0].text, "Welcome everyone. Let us start."); |
| 398 | assert_eq!(turns[0].start_seconds, 1.5); |
| 399 | assert_eq!(turns[0].end_seconds, 7.0); |
| 400 | assert_eq!(turns[1].end_seconds, 69.25); |
| 401 | assert_eq!(turns[2].speaker, "?"); |
| 402 | assert_eq!(turns[2].start_seconds, 3600.0); |
| 403 | } |
| 404 | |
| 405 | #[test] |
| 406 | fn missing_entries_give_no_turns() { |
| 407 | assert!(parse_turns(&serde_json::json!({})).is_empty()); |
| 408 | } |
| 409 | } |