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