| 1 | use std::collections::{BTreeSet, HashSet}; |
| 2 | |
| 3 | use base64::Engine as _; |
| 4 | use base64::engine::general_purpose::STANDARD; |
| 5 | use chrono::{DateTime, Utc}; |
| 6 | use serde_json::Value; |
| 7 | use session::{Method, Request, Scope, Session}; |
| 8 | |
| 9 | use crate::messages::encode; |
| 10 | use crate::pins::DEFAULT_REGION; |
| 11 | use crate::transcripts::{ |
| 12 | TranscriptError, TranscriptTurn, Transcripts, newest_transcript, parse_transcript_list, |
| 13 | parse_turns, share_id, site_origin, |
| 14 | }; |
| 15 | |
| 16 | const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail"; |
| 17 | const RECORDING_SUCCESS: &str = "success"; |
| 18 | const MESSAGES_SCOPE: &str = "Chat.Read"; |
| 19 | const SITE_SCOPE: &str = ".default"; |
| 20 | const ATTENDANCE_SCOPE: &str = "OnlineMeetingArtifact.Read.All"; |
| 21 | const MAX_MESSAGE_PAGES: usize = 40; |
| 22 | const AUDIO_ONLY_MARKER: &str = "videoContent=\"CurtainOnly\""; |
| 23 | const ORIGINAL_NAME_OPEN: &str = "<OriginalName v=\""; |
| 24 | |
| 25 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 26 | pub struct Occurrence { |
| 27 | pub message_id: String, |
| 28 | pub started_at: Option<DateTime<Utc>>, |
| 29 | pub recording_url: String, |
| 30 | pub recording_name: Option<String>, |
| 31 | pub duration_seconds: Option<u64>, |
| 32 | pub organizer_id: Option<String>, |
| 33 | pub audio_only: bool, |
| 34 | } |
| 35 | |
| 36 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 37 | pub struct RecordingDetails { |
| 38 | pub item_url: String, |
| 39 | pub audio_only: bool, |
| 40 | pub transcript_only: bool, |
| 41 | pub duration_seconds: Option<u64>, |
| 42 | pub expires_at: Option<DateTime<Utc>>, |
| 43 | pub transcript_id: Option<String>, |
| 44 | } |
| 45 | |
| 46 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 47 | pub enum TranscriptFormat { |
| 48 | Vtt, |
| 49 | Docx, |
| 50 | } |
| 51 | |
| 52 | impl TranscriptFormat { |
| 53 | pub fn query(self) -> &'static str { |
| 54 | match self { |
| 55 | TranscriptFormat::Vtt => "vtt", |
| 56 | TranscriptFormat::Docx => "docx", |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 62 | pub struct AttendanceRecord { |
| 63 | pub name: String, |
| 64 | pub joined_at: Option<DateTime<Utc>>, |
| 65 | pub left_at: Option<DateTime<Utc>>, |
| 66 | pub duration_seconds: u64, |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 70 | pub enum Attendance { |
| 71 | TurnedOff, |
| 72 | Report(Vec<AttendanceRecord>), |
| 73 | } |
| 74 | |
| 75 | pub struct Recap<'a> { |
| 76 | session: &'a Session, |
| 77 | transcripts: Transcripts<'a>, |
| 78 | } |
| 79 | |
| 80 | impl<'a> Recap<'a> { |
| 81 | pub fn new(session: &'a Session) -> Self { |
| 82 | Recap { |
| 83 | session, |
| 84 | transcripts: Transcripts::new(session), |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | pub async fn occurrences(&self, thread_id: &str) -> Result<Vec<Occurrence>, TranscriptError> { |
| 89 | let scope = Scope::graph(MESSAGES_SCOPE); |
| 90 | let mut url = format!( |
| 91 | "{}/v1.0/chats/{}/messages?$top=50&$orderby=createdDateTime desc", |
| 92 | session::GRAPH, |
| 93 | encode(thread_id) |
| 94 | ); |
| 95 | let mut found = Vec::new(); |
| 96 | for _ in 0..MAX_MESSAGE_PAGES { |
| 97 | let page = self |
| 98 | .transcripts |
| 99 | .get(&url, &scope, TranscriptError::NoRecording) |
| 100 | .await?; |
| 101 | found.extend(parse_occurrences(&page)); |
| 102 | match page.get("@odata.nextLink").and_then(Value::as_str) { |
| 103 | Some(next) => url = next.to_owned(), |
| 104 | None => break, |
| 105 | } |
| 106 | } |
| 107 | let audio_only_names = self.audio_only_names(thread_id).await; |
| 108 | let occurrences = sorted_occurrences(with_audio_only(found, &audio_only_names)); |
| 109 | let deleted = self.deleted_recordings(&occurrences).await; |
| 110 | Ok(without_deleted(occurrences, &deleted)) |
| 111 | } |
| 112 | |
| 113 | async fn audio_only_names(&self, thread_id: &str) -> HashSet<String> { |
| 114 | let scope = Scope::new(session::IC3, "Teams.AccessAsUser.All"); |
| 115 | let mut url = format!( |
| 116 | "https://teams.cloud.microsoft/api/chatsvc/{DEFAULT_REGION}/v1/users/ME/conversations/{}/messages?view=msnp24Equivalent&pageSize=200", |
| 117 | encode(thread_id) |
| 118 | ); |
| 119 | let mut names = HashSet::new(); |
| 120 | for _ in 0..MAX_MESSAGE_PAGES { |
| 121 | let Ok(page) = self |
| 122 | .transcripts |
| 123 | .get(&url, &scope, TranscriptError::NoRecording) |
| 124 | .await |
| 125 | else { |
| 126 | break; |
| 127 | }; |
| 128 | names.extend(parse_audio_only_names(&page)); |
| 129 | match page |
| 130 | .pointer("/_metadata/backwardLink") |
| 131 | .and_then(Value::as_str) |
| 132 | .filter(|link| !link.is_empty() && *link != url) |
| 133 | { |
| 134 | Some(next) => url = next.to_owned(), |
| 135 | None => break, |
| 136 | } |
| 137 | } |
| 138 | names |
| 139 | } |
| 140 | |
| 141 | async fn deleted_recordings(&self, occurrences: &[Occurrence]) -> HashSet<String> { |
| 142 | let mut deleted = HashSet::new(); |
| 143 | let sites: BTreeSet<String> = occurrences |
| 144 | .iter() |
| 145 | .map(|occurrence| site_origin(&occurrence.recording_url)) |
| 146 | .collect(); |
| 147 | for site in sites { |
| 148 | let urls: Vec<&str> = occurrences |
| 149 | .iter() |
| 150 | .map(|occurrence| occurrence.recording_url.as_str()) |
| 151 | .filter(|url| site_origin(url) == site) |
| 152 | .collect(); |
| 153 | let requests: Vec<Request> = urls |
| 154 | .iter() |
| 155 | .map(|url| { |
| 156 | Request::get(format!( |
| 157 | "{site}/_api/v2.1/shares/{}/driveItem?$select=id", |
| 158 | share_id(url) |
| 159 | )) |
| 160 | }) |
| 161 | .collect(); |
| 162 | let Ok(answers) = self |
| 163 | .session |
| 164 | .batch(&requests, &Scope::new(site.clone(), SITE_SCOPE)) |
| 165 | .await |
| 166 | else { |
| 167 | continue; |
| 168 | }; |
| 169 | deleted.extend( |
| 170 | urls.iter() |
| 171 | .zip(answers) |
| 172 | .filter(|(_, answer)| answer.status == 404) |
| 173 | .map(|(url, _)| (*url).to_owned()), |
| 174 | ); |
| 175 | } |
| 176 | deleted |
| 177 | } |
| 178 | |
| 179 | pub async fn details( |
| 180 | &self, |
| 181 | occurrence: &Occurrence, |
| 182 | ) -> Result<RecordingDetails, TranscriptError> { |
| 183 | let site = site_origin(&occurrence.recording_url); |
| 184 | let site_scope = Scope::new(site.clone(), SITE_SCOPE); |
| 185 | let item = self |
| 186 | .transcripts |
| 187 | .get( |
| 188 | &format!( |
| 189 | "{site}/_api/v2.1/shares/{}/driveItem?$select=id,parentReference,video,file,media", |
| 190 | share_id(&occurrence.recording_url) |
| 191 | ), |
| 192 | &site_scope, |
| 193 | TranscriptError::NoRecording, |
| 194 | ) |
| 195 | .await?; |
| 196 | let item_url = item_url(&site, &item).ok_or(TranscriptError::NoRecording)?; |
| 197 | let expiration = self |
| 198 | .transcripts |
| 199 | .get( |
| 200 | &format!("{item_url}/listItem?$expand=fields($select=_ExpirationDate)"), |
| 201 | &site_scope, |
| 202 | TranscriptError::NoRecording, |
| 203 | ) |
| 204 | .await |
| 205 | .ok(); |
| 206 | let listing = self |
| 207 | .transcripts |
| 208 | .get( |
| 209 | &format!("{item_url}/media/transcripts"), |
| 210 | &site_scope, |
| 211 | TranscriptError::NoTranscript, |
| 212 | ) |
| 213 | .await |
| 214 | .ok(); |
| 215 | Ok(RecordingDetails { |
| 216 | audio_only: occurrence.audio_only || is_audio_only(&item), |
| 217 | transcript_only: is_transcript_only(&item), |
| 218 | duration_seconds: item_duration_seconds(&item).or(occurrence.duration_seconds), |
| 219 | expires_at: expiration.as_ref().and_then(parse_expiration), |
| 220 | transcript_id: listing |
| 221 | .as_ref() |
| 222 | .and_then(|listing| newest_transcript(parse_transcript_list(listing))) |
| 223 | .map(|transcript| transcript.id), |
| 224 | item_url, |
| 225 | }) |
| 226 | } |
| 227 | |
| 228 | pub async fn transcript( |
| 229 | &self, |
| 230 | details: &RecordingDetails, |
| 231 | ) -> Result<Vec<TranscriptTurn>, TranscriptError> { |
| 232 | let transcript_id = details |
| 233 | .transcript_id |
| 234 | .as_deref() |
| 235 | .ok_or(TranscriptError::NoTranscript)?; |
| 236 | let site_scope = Scope::new(site_origin(&details.item_url), SITE_SCOPE); |
| 237 | let content = self |
| 238 | .transcripts |
| 239 | .get( |
| 240 | &transcript_url(&details.item_url, transcript_id, "json"), |
| 241 | &site_scope, |
| 242 | TranscriptError::NoTranscript, |
| 243 | ) |
| 244 | .await?; |
| 245 | Ok(parse_turns(&content)) |
| 246 | } |
| 247 | |
| 248 | pub async fn transcript_file( |
| 249 | &self, |
| 250 | details: &RecordingDetails, |
| 251 | format: TranscriptFormat, |
| 252 | ) -> Result<Vec<u8>, TranscriptError> { |
| 253 | let transcript_id = details |
| 254 | .transcript_id |
| 255 | .as_deref() |
| 256 | .ok_or(TranscriptError::NoTranscript)?; |
| 257 | let site_scope = Scope::new(site_origin(&details.item_url), SITE_SCOPE); |
| 258 | let request = Request::binary_get(transcript_url( |
| 259 | &details.item_url, |
| 260 | transcript_id, |
| 261 | format.query(), |
| 262 | )); |
| 263 | let answer = self |
| 264 | .session |
| 265 | .send(request, &site_scope) |
| 266 | .await |
| 267 | .map_err(request_failure)?; |
| 268 | decode_binary(&answer.body).ok_or(TranscriptError::NoTranscript) |
| 269 | } |
| 270 | |
| 271 | pub async fn delete_recording( |
| 272 | &self, |
| 273 | details: &RecordingDetails, |
| 274 | ) -> Result<(), TranscriptError> { |
| 275 | let site_scope = Scope::new(site_origin(&details.item_url), SITE_SCOPE); |
| 276 | self.session |
| 277 | .request(Method::Delete, &details.item_url, &site_scope, None) |
| 278 | .await |
| 279 | .map(|_| ()) |
| 280 | .map_err(request_failure) |
| 281 | } |
| 282 | |
| 283 | pub async fn attendance(&self, thread_id: &str) -> Result<Attendance, TranscriptError> { |
| 284 | let graph_scope = Scope::graph(MESSAGES_SCOPE); |
| 285 | let chat = match self |
| 286 | .transcripts |
| 287 | .get( |
| 288 | &format!( |
| 289 | "{}/v1.0/chats/{}?$select=onlineMeetingInfo", |
| 290 | session::GRAPH, |
| 291 | encode(thread_id) |
| 292 | ), |
| 293 | &graph_scope, |
| 294 | TranscriptError::NoRecording, |
| 295 | ) |
| 296 | .await |
| 297 | { |
| 298 | Ok(chat) => chat, |
| 299 | Err(TranscriptError::NoRecording | TranscriptError::AccessDenied) => { |
| 300 | return Ok(Attendance::TurnedOff); |
| 301 | } |
| 302 | Err(error) => return Err(error), |
| 303 | }; |
| 304 | let Some(join_url) = chat |
| 305 | .pointer("/onlineMeetingInfo/joinWebUrl") |
| 306 | .and_then(Value::as_str) |
| 307 | else { |
| 308 | return Ok(Attendance::TurnedOff); |
| 309 | }; |
| 310 | let scope = Scope::graph(ATTENDANCE_SCOPE); |
| 311 | let lookup = format!( |
| 312 | "{}/v1.0/me/onlineMeetings?$filter={}&$select=id", |
| 313 | session::GRAPH, |
| 314 | encode(&format!("JoinWebUrl eq '{}'", join_url.replace('\'', "''"))) |
| 315 | ); |
| 316 | let meeting_id = match self |
| 317 | .transcripts |
| 318 | .get(&lookup, &scope, TranscriptError::NoRecording) |
| 319 | .await |
| 320 | { |
| 321 | Ok(found) => found |
| 322 | .pointer("/value/0/id") |
| 323 | .and_then(Value::as_str) |
| 324 | .map(str::to_owned), |
| 325 | Err(TranscriptError::NoRecording | TranscriptError::AccessDenied) => None, |
| 326 | Err(error) => return Err(error), |
| 327 | }; |
| 328 | let Some(meeting_id) = meeting_id else { |
| 329 | return Ok(Attendance::TurnedOff); |
| 330 | }; |
| 331 | let reports_url = format!( |
| 332 | "{}/v1.0/me/onlineMeetings/{}/attendanceReports", |
| 333 | session::GRAPH, |
| 334 | encode(&meeting_id) |
| 335 | ); |
| 336 | let reports = match self |
| 337 | .transcripts |
| 338 | .get(&reports_url, &scope, TranscriptError::NoRecording) |
| 339 | .await |
| 340 | { |
| 341 | Ok(reports) => reports, |
| 342 | Err(TranscriptError::NoRecording | TranscriptError::AccessDenied) => { |
| 343 | return Ok(Attendance::TurnedOff); |
| 344 | } |
| 345 | Err(error) => return Err(error), |
| 346 | }; |
| 347 | let Some(report_id) = reports |
| 348 | .pointer("/value/0/id") |
| 349 | .and_then(Value::as_str) |
| 350 | else { |
| 351 | return Ok(Attendance::TurnedOff); |
| 352 | }; |
| 353 | let report = self |
| 354 | .transcripts |
| 355 | .get( |
| 356 | &format!( |
| 357 | "{reports_url}/{}?$expand=attendanceRecords", |
| 358 | encode(report_id) |
| 359 | ), |
| 360 | &scope, |
| 361 | TranscriptError::NoRecording, |
| 362 | ) |
| 363 | .await?; |
| 364 | Ok(Attendance::Report(parse_attendance(&report))) |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | fn request_failure(error: session::Error) -> TranscriptError { |
| 369 | match error { |
| 370 | session::Error::Api { |
| 371 | status: 403 | 401, .. |
| 372 | } => TranscriptError::AccessDenied, |
| 373 | error => TranscriptError::Request(error), |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | fn transcript_url(item_url: &str, transcript_id: &str, format: &str) -> String { |
| 378 | format!( |
| 379 | "{item_url}/media/transcripts/{}/streamContent?format={format}", |
| 380 | encode(transcript_id) |
| 381 | ) |
| 382 | } |
| 383 | |
| 384 | fn item_url(site: &str, item: &Value) -> Option<String> { |
| 385 | let drive_id = item |
| 386 | .pointer("/parentReference/driveId") |
| 387 | .and_then(Value::as_str)?; |
| 388 | let item_id = item.get("id").and_then(Value::as_str)?; |
| 389 | Some(format!("{site}/_api/v2.1/drives/{drive_id}/items/{item_id}")) |
| 390 | } |
| 391 | |
| 392 | fn decode_binary(body: &Value) -> Option<Vec<u8>> { |
| 393 | STANDARD.decode(body.get("base64")?.as_str()?).ok() |
| 394 | } |
| 395 | |
| 396 | pub fn parse_occurrences(messages_json: &Value) -> Vec<Occurrence> { |
| 397 | messages_json |
| 398 | .get("value") |
| 399 | .and_then(Value::as_array) |
| 400 | .into_iter() |
| 401 | .flatten() |
| 402 | .filter_map(|message| { |
| 403 | let detail = message.get("eventDetail")?; |
| 404 | let finished = detail.get("@odata.type").and_then(Value::as_str) |
| 405 | == Some(RECORDING_EVENT) |
| 406 | && detail.get("callRecordingStatus").and_then(Value::as_str) |
| 407 | == Some(RECORDING_SUCCESS); |
| 408 | let url = detail.get("callRecordingUrl").and_then(Value::as_str)?; |
| 409 | if !finished || !url.starts_with("https://") { |
| 410 | return None; |
| 411 | } |
| 412 | Some(Occurrence { |
| 413 | message_id: message.get("id").and_then(Value::as_str)?.to_owned(), |
| 414 | started_at: message |
| 415 | .get("createdDateTime") |
| 416 | .and_then(Value::as_str) |
| 417 | .and_then(|stamp| DateTime::parse_from_rfc3339(stamp).ok()) |
| 418 | .map(|stamp| stamp.with_timezone(&Utc)), |
| 419 | recording_url: url.to_owned(), |
| 420 | recording_name: detail |
| 421 | .get("callRecordingDisplayName") |
| 422 | .and_then(Value::as_str) |
| 423 | .filter(|name| !name.is_empty()) |
| 424 | .map(str::to_owned), |
| 425 | duration_seconds: detail |
| 426 | .get("callRecordingDuration") |
| 427 | .and_then(Value::as_str) |
| 428 | .and_then(parse_iso_duration), |
| 429 | organizer_id: detail |
| 430 | .pointer("/meetingOrganizer/user/id") |
| 431 | .and_then(Value::as_str) |
| 432 | .map(str::to_owned), |
| 433 | audio_only: false, |
| 434 | }) |
| 435 | }) |
| 436 | .collect() |
| 437 | } |
| 438 | |
| 439 | pub fn parse_audio_only_names(chatsvc_messages_json: &Value) -> HashSet<String> { |
| 440 | chatsvc_messages_json |
| 441 | .get("messages") |
| 442 | .and_then(Value::as_array) |
| 443 | .into_iter() |
| 444 | .flatten() |
| 445 | .filter(|message| { |
| 446 | message.get("messagetype").and_then(Value::as_str) == Some("RichText/Media_CallRecording") |
| 447 | }) |
| 448 | .filter_map(|message| message.get("content").and_then(Value::as_str)) |
| 449 | .filter(|content| content.contains(AUDIO_ONLY_MARKER)) |
| 450 | .filter_map(|content| { |
| 451 | let start = content.find(ORIGINAL_NAME_OPEN)? + ORIGINAL_NAME_OPEN.len(); |
| 452 | let length = content[start..].find('"')?; |
| 453 | Some(content[start..start + length].to_owned()) |
| 454 | }) |
| 455 | .collect() |
| 456 | } |
| 457 | |
| 458 | pub fn with_audio_only( |
| 459 | occurrences: Vec<Occurrence>, |
| 460 | audio_only_names: &HashSet<String>, |
| 461 | ) -> Vec<Occurrence> { |
| 462 | occurrences |
| 463 | .into_iter() |
| 464 | .map(|occurrence| Occurrence { |
| 465 | audio_only: occurrence |
| 466 | .recording_name |
| 467 | .as_ref() |
| 468 | .is_some_and(|name| audio_only_names.contains(name)), |
| 469 | ..occurrence |
| 470 | }) |
| 471 | .collect() |
| 472 | } |
| 473 | |
| 474 | pub fn sorted_occurrences(mut occurrences: Vec<Occurrence>) -> Vec<Occurrence> { |
| 475 | occurrences.sort_by_key(|occurrence| std::cmp::Reverse(occurrence.started_at)); |
| 476 | occurrences.dedup_by(|left, right| left.recording_url == right.recording_url); |
| 477 | occurrences |
| 478 | } |
| 479 | |
| 480 | pub fn without_deleted(occurrences: Vec<Occurrence>, deleted: &HashSet<String>) -> Vec<Occurrence> { |
| 481 | occurrences |
| 482 | .into_iter() |
| 483 | .filter(|occurrence| !deleted.contains(&occurrence.recording_url)) |
| 484 | .collect() |
| 485 | } |
| 486 | |
| 487 | pub fn parse_iso_duration(text: &str) -> Option<u64> { |
| 488 | let time = text.strip_prefix("PT")?; |
| 489 | let mut total = 0.0; |
| 490 | let mut number = String::new(); |
| 491 | for character in time.chars() { |
| 492 | let unit = match character { |
| 493 | 'H' => 3600.0, |
| 494 | 'M' => 60.0, |
| 495 | 'S' => 1.0, |
| 496 | digit => { |
| 497 | number.push(digit); |
| 498 | continue; |
| 499 | } |
| 500 | }; |
| 501 | total += number.parse::<f64>().ok()? * unit; |
| 502 | number.clear(); |
| 503 | } |
| 504 | number.is_empty().then_some(total as u64) |
| 505 | } |
| 506 | |
| 507 | pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> { |
| 508 | let stamp = listing_json |
| 509 | .pointer("/fields/_ExpirationDate")? |
| 510 | .as_str()?; |
| 511 | DateTime::parse_from_rfc3339(stamp) |
| 512 | .ok() |
| 513 | .map(|stamp| stamp.with_timezone(&Utc)) |
| 514 | } |
| 515 | |
| 516 | pub fn is_audio_only(item_json: &Value) -> bool { |
| 517 | item_json |
| 518 | .get("video") |
| 519 | .and_then(|video| video.get("width")) |
| 520 | .and_then(Value::as_u64) |
| 521 | .is_none_or(|width| width == 0) |
| 522 | } |
| 523 | |
| 524 | pub fn is_transcript_only(item_json: &Value) -> bool { |
| 525 | item_json |
| 526 | .pointer("/media/mediaSource/contentType") |
| 527 | .and_then(Value::as_str) |
| 528 | == Some("Transcript") |
| 529 | } |
| 530 | |
| 531 | pub fn item_duration_seconds(item_json: &Value) -> Option<u64> { |
| 532 | item_json |
| 533 | .pointer("/video/duration") |
| 534 | .and_then(Value::as_u64) |
| 535 | .map(|milliseconds| milliseconds / 1000) |
| 536 | } |
| 537 | |
| 538 | pub fn days_until_expiry(expires_at: DateTime<Utc>, now: DateTime<Utc>) -> i64 { |
| 539 | let remaining = expires_at - now; |
| 540 | (remaining.num_seconds() + 86_399).div_euclid(86_400).max(0) |
| 541 | } |
| 542 | |
| 543 | pub fn parse_attendance(report_json: &Value) -> Vec<AttendanceRecord> { |
| 544 | let parse_stamp = |value: Option<&Value>| { |
| 545 | value |
| 546 | .and_then(Value::as_str) |
| 547 | .and_then(|stamp| DateTime::parse_from_rfc3339(stamp).ok()) |
| 548 | .map(|stamp| stamp.with_timezone(&Utc)) |
| 549 | }; |
| 550 | report_json |
| 551 | .get("attendanceRecords") |
| 552 | .and_then(Value::as_array) |
| 553 | .into_iter() |
| 554 | .flatten() |
| 555 | .map(|record| { |
| 556 | let intervals: Vec<&Value> = record |
| 557 | .get("attendanceIntervals") |
| 558 | .and_then(Value::as_array) |
| 559 | .into_iter() |
| 560 | .flatten() |
| 561 | .collect(); |
| 562 | let name = record |
| 563 | .pointer("/identity/displayName") |
| 564 | .and_then(Value::as_str) |
| 565 | .filter(|name| !name.is_empty()) |
| 566 | .or_else(|| record.get("emailAddress").and_then(Value::as_str)) |
| 567 | .unwrap_or("?"); |
| 568 | AttendanceRecord { |
| 569 | name: name.to_owned(), |
| 570 | joined_at: intervals |
| 571 | .iter() |
| 572 | .filter_map(|interval| parse_stamp(interval.get("joinDateTime"))) |
| 573 | .min(), |
| 574 | left_at: intervals |
| 575 | .iter() |
| 576 | .filter_map(|interval| parse_stamp(interval.get("leaveDateTime"))) |
| 577 | .max(), |
| 578 | duration_seconds: record |
| 579 | .get("totalAttendanceInSeconds") |
| 580 | .and_then(Value::as_u64) |
| 581 | .unwrap_or(0), |
| 582 | } |
| 583 | }) |
| 584 | .collect() |
| 585 | } |
| 586 | |
| 587 | #[cfg(test)] |
| 588 | mod tests { |
| 589 | use super::*; |
| 590 | |
| 591 | fn fixture(name: &str) -> Value { |
| 592 | let path = format!( |
| 593 | "{}/tests/fixtures/recap/{name}", |
| 594 | env!("CARGO_MANIFEST_DIR") |
| 595 | ); |
| 596 | serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() |
| 597 | } |
| 598 | |
| 599 | #[test] |
| 600 | fn occurrences_keep_finished_recordings_newest_first() { |
| 601 | let occurrences = sorted_occurrences(parse_occurrences(&fixture("messages.json"))); |
| 602 | assert_eq!(occurrences.len(), 2); |
| 603 | assert_eq!(occurrences[0].message_id, "2002"); |
| 604 | assert_eq!(occurrences[0].duration_seconds, Some(1832)); |
| 605 | assert_eq!(occurrences[0].organizer_id.as_deref(), Some("user-organizer")); |
| 606 | assert_eq!(occurrences[1].message_id, "2001"); |
| 607 | assert_eq!(occurrences[1].duration_seconds, None); |
| 608 | } |
| 609 | |
| 610 | #[test] |
| 611 | fn deleted_recordings_drop_out_of_the_occurrences() { |
| 612 | let occurrences = sorted_occurrences(parse_occurrences(&fixture("messages.json"))); |
| 613 | let deleted: HashSet<String> = [occurrences[0].recording_url.clone()].into(); |
| 614 | let remaining = without_deleted(occurrences, &deleted); |
| 615 | assert_eq!(remaining.len(), 1); |
| 616 | assert_eq!(remaining[0].message_id, "2001"); |
| 617 | } |
| 618 | |
| 619 | #[test] |
| 620 | fn iso_durations_parse_to_seconds() { |
| 621 | assert_eq!(parse_iso_duration("PT1H2M3S"), Some(3723)); |
| 622 | assert_eq!(parse_iso_duration("PT45M"), Some(2700)); |
| 623 | assert_eq!(parse_iso_duration("PT12.5S"), Some(12)); |
| 624 | assert_eq!(parse_iso_duration("1H"), None); |
| 625 | assert_eq!(parse_iso_duration("PT5"), None); |
| 626 | } |
| 627 | |
| 628 | #[test] |
| 629 | fn expiration_reads_the_list_item_field() { |
| 630 | let expires_at = parse_expiration(&fixture("expiration.json")).unwrap(); |
| 631 | assert_eq!(expires_at.to_rfc3339(), "2026-05-01T08:00:00+00:00"); |
| 632 | assert_eq!(parse_expiration(&serde_json::json!({"fields": {}})), None); |
| 633 | } |
| 634 | |
| 635 | #[test] |
| 636 | fn days_until_expiry_rounds_up_and_floors_at_zero() { |
| 637 | let now = DateTime::parse_from_rfc3339("2026-04-24T08:00:00Z") |
| 638 | .unwrap() |
| 639 | .with_timezone(&Utc); |
| 640 | let in_hours = |hours| now + chrono::Duration::hours(hours); |
| 641 | assert_eq!(days_until_expiry(in_hours(7 * 24), now), 7); |
| 642 | assert_eq!(days_until_expiry(in_hours(36), now), 2); |
| 643 | assert_eq!(days_until_expiry(in_hours(-5), now), 0); |
| 644 | } |
| 645 | |
| 646 | #[test] |
| 647 | fn audio_only_when_the_item_has_no_video_size() { |
| 648 | assert!(is_audio_only(&serde_json::json!({"file": {}}))); |
| 649 | assert!(!is_audio_only( |
| 650 | &serde_json::json!({"video": {"width": 1280, "duration": 90000}}) |
| 651 | )); |
| 652 | assert_eq!( |
| 653 | item_duration_seconds(&serde_json::json!({"video": {"duration": 90000}})), |
| 654 | Some(90) |
| 655 | ); |
| 656 | } |
| 657 | |
| 658 | #[test] |
| 659 | fn audio_only_recordings_are_found_by_the_curtain_marker_in_the_chat_event() { |
| 660 | let names = parse_audio_only_names(&fixture("chatsvc_messages.json")); |
| 661 | assert_eq!( |
| 662 | names, |
| 663 | HashSet::from(["Weekly sync-20260309_100000-Meeting Recording.mp4".to_owned()]) |
| 664 | ); |
| 665 | let occurrences = with_audio_only( |
| 666 | sorted_occurrences(parse_occurrences(&fixture("messages.json"))), |
| 667 | &names, |
| 668 | ); |
| 669 | assert!(occurrences[0].audio_only); |
| 670 | assert!(!occurrences[1].audio_only); |
| 671 | } |
| 672 | |
| 673 | #[test] |
| 674 | fn transcript_only_items_are_told_apart_by_their_media_source() { |
| 675 | assert!(is_transcript_only(&fixture("drive_item_transcript.json"))); |
| 676 | assert!(!is_transcript_only(&fixture("drive_item.json"))); |
| 677 | assert!(!is_transcript_only(&fixture("drive_item_recording.json"))); |
| 678 | } |
| 679 | |
| 680 | #[test] |
| 681 | fn recording_item_gives_url_duration_and_video() { |
| 682 | let item = fixture("drive_item.json"); |
| 683 | assert_eq!( |
| 684 | item_url("https://contoso-my.sharepoint.com", &item).as_deref(), |
| 685 | Some("https://contoso-my.sharepoint.com/_api/v2.1/drives/drive-1/items/item-1") |
| 686 | ); |
| 687 | assert!(!is_audio_only(&item)); |
| 688 | assert_eq!(item_duration_seconds(&item), Some(53)); |
| 689 | } |
| 690 | |
| 691 | #[test] |
| 692 | fn transcript_urls_request_the_wanted_format() { |
| 693 | assert_eq!( |
| 694 | transcript_url("https://a.example/_api/v2.1/drives/d/items/i", "t 1", "vtt"), |
| 695 | "https://a.example/_api/v2.1/drives/d/items/i/media/transcripts/t%201/streamContent?format=vtt" |
| 696 | ); |
| 697 | assert_eq!(TranscriptFormat::Docx.query(), "docx"); |
| 698 | } |
| 699 | |
| 700 | #[test] |
| 701 | fn binary_answers_decode_from_base64() { |
| 702 | let body = serde_json::json!({"base64": "V0VCVlRU", "contentType": "text/vtt"}); |
| 703 | assert_eq!(decode_binary(&body), Some(b"WEBVTT".to_vec())); |
| 704 | assert_eq!(decode_binary(&serde_json::json!({})), None); |
| 705 | } |
| 706 | |
| 707 | #[test] |
| 708 | fn attendance_spans_first_join_to_last_leave() { |
| 709 | let records = parse_attendance(&fixture("attendance.json")); |
| 710 | assert_eq!(records.len(), 2); |
| 711 | assert_eq!(records[0].name, "Alex Example"); |
| 712 | assert_eq!(records[0].duration_seconds, 1500); |
| 713 | assert_eq!( |
| 714 | records[0].joined_at.unwrap().to_rfc3339(), |
| 715 | "2026-03-02T10:00:00+00:00" |
| 716 | ); |
| 717 | assert_eq!( |
| 718 | records[0].left_at.unwrap().to_rfc3339(), |
| 719 | "2026-03-02T10:30:00+00:00" |
| 720 | ); |
| 721 | assert_eq!(records[1].name, "sam@example.com"); |
| 722 | } |
| 723 | } |