BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / recap.rs

recap.rs

8a314dbb History
recap.rs 24.5 KiB Download Raw
1use std::collections::{BTreeSet, HashSet};
2
3use base64::Engine as _;
4use base64::engine::general_purpose::STANDARD;
5use chrono::{DateTime, Utc};
6use serde_json::Value;
7use session::{Method, Request, Scope, Session};
8
9use crate::messages::encode;
10use crate::pins::DEFAULT_REGION;
11use crate::transcripts::{
12 TranscriptError, TranscriptTurn, Transcripts, newest_transcript, parse_transcript_list,
13 parse_turns, share_id, site_origin,
14};
15
16const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail";
17const RECORDING_SUCCESS: &str = "success";
18const MESSAGES_SCOPE: &str = "Chat.Read";
19const SITE_SCOPE: &str = ".default";
20const ATTENDANCE_SCOPE: &str = "OnlineMeetingArtifact.Read.All";
21const MAX_MESSAGE_PAGES: usize = 40;
22const AUDIO_ONLY_MARKER: &str = "videoContent=\"CurtainOnly\"";
23const ORIGINAL_NAME_OPEN: &str = "<OriginalName v=\"";
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub 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)]
37pub 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)]
47pub enum TranscriptFormat {
48 Vtt,
49 Docx,
50}
51
52impl 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)]
62pub 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)]
70pub enum Attendance {
71 TurnedOff,
72 Report(Vec<AttendanceRecord>),
73}
74
75pub struct Recap<'a> {
76 session: &'a Session,
77 transcripts: Transcripts<'a>,
78}
79
80impl<'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.pointer("/value/0/id").and_then(Value::as_str) else {
348 return Ok(Attendance::TurnedOff);
349 };
350 let report = self
351 .transcripts
352 .get(
353 &format!(
354 "{reports_url}/{}?$expand=attendanceRecords",
355 encode(report_id)
356 ),
357 &scope,
358 TranscriptError::NoRecording,
359 )
360 .await?;
361 Ok(Attendance::Report(parse_attendance(&report)))
362 }
363}
364
365fn request_failure(error: session::Error) -> TranscriptError {
366 match error {
367 session::Error::Api {
368 status: 403 | 401, ..
369 } => TranscriptError::AccessDenied,
370 error => TranscriptError::Request(error),
371 }
372}
373
374fn transcript_url(item_url: &str, transcript_id: &str, format: &str) -> String {
375 format!(
376 "{item_url}/media/transcripts/{}/streamContent?format={format}",
377 encode(transcript_id)
378 )
379}
380
381fn item_url(site: &str, item: &Value) -> Option<String> {
382 let drive_id = item
383 .pointer("/parentReference/driveId")
384 .and_then(Value::as_str)?;
385 let item_id = item.get("id").and_then(Value::as_str)?;
386 Some(format!(
387 "{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"
388 ))
389}
390
391fn decode_binary(body: &Value) -> Option<Vec<u8>> {
392 STANDARD.decode(body.get("base64")?.as_str()?).ok()
393}
394
395pub fn parse_occurrences(messages_json: &Value) -> Vec<Occurrence> {
396 messages_json
397 .get("value")
398 .and_then(Value::as_array)
399 .into_iter()
400 .flatten()
401 .filter_map(|message| {
402 let detail = message.get("eventDetail")?;
403 let finished = detail.get("@odata.type").and_then(Value::as_str)
404 == Some(RECORDING_EVENT)
405 && detail.get("callRecordingStatus").and_then(Value::as_str)
406 == Some(RECORDING_SUCCESS);
407 let url = detail.get("callRecordingUrl").and_then(Value::as_str)?;
408 if !finished || !url.starts_with("https://") {
409 return None;
410 }
411 Some(Occurrence {
412 message_id: message.get("id").and_then(Value::as_str)?.to_owned(),
413 started_at: message
414 .get("createdDateTime")
415 .and_then(Value::as_str)
416 .and_then(|stamp| DateTime::parse_from_rfc3339(stamp).ok())
417 .map(|stamp| stamp.with_timezone(&Utc)),
418 recording_url: url.to_owned(),
419 recording_name: detail
420 .get("callRecordingDisplayName")
421 .and_then(Value::as_str)
422 .filter(|name| !name.is_empty())
423 .map(str::to_owned),
424 duration_seconds: detail
425 .get("callRecordingDuration")
426 .and_then(Value::as_str)
427 .and_then(parse_iso_duration),
428 organizer_id: detail
429 .pointer("/meetingOrganizer/user/id")
430 .and_then(Value::as_str)
431 .map(str::to_owned),
432 audio_only: false,
433 })
434 })
435 .collect()
436}
437
438pub fn parse_audio_only_names(chatsvc_messages_json: &Value) -> HashSet<String> {
439 chatsvc_messages_json
440 .get("messages")
441 .and_then(Value::as_array)
442 .into_iter()
443 .flatten()
444 .filter(|message| {
445 message.get("messagetype").and_then(Value::as_str)
446 == 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
458pub 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
474pub 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
480pub 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
487pub 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
507pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> {
508 let stamp = listing_json.pointer("/fields/_ExpirationDate")?.as_str()?;
509 DateTime::parse_from_rfc3339(stamp)
510 .ok()
511 .map(|stamp| stamp.with_timezone(&Utc))
512}
513
514pub fn is_audio_only(item_json: &Value) -> bool {
515 item_json
516 .get("video")
517 .and_then(|video| video.get("width"))
518 .and_then(Value::as_u64)
519 .is_none_or(|width| width == 0)
520}
521
522pub fn is_transcript_only(item_json: &Value) -> bool {
523 item_json
524 .pointer("/media/mediaSource/contentType")
525 .and_then(Value::as_str)
526 == Some("Transcript")
527}
528
529pub fn item_duration_seconds(item_json: &Value) -> Option<u64> {
530 item_json
531 .pointer("/video/duration")
532 .and_then(Value::as_u64)
533 .map(|milliseconds| milliseconds / 1000)
534}
535
536pub fn days_until_expiry(expires_at: DateTime<Utc>, now: DateTime<Utc>) -> i64 {
537 let remaining = expires_at - now;
538 (remaining.num_seconds() + 86_399).div_euclid(86_400).max(0)
539}
540
541pub fn parse_attendance(report_json: &Value) -> Vec<AttendanceRecord> {
542 let parse_stamp = |value: Option<&Value>| {
543 value
544 .and_then(Value::as_str)
545 .and_then(|stamp| DateTime::parse_from_rfc3339(stamp).ok())
546 .map(|stamp| stamp.with_timezone(&Utc))
547 };
548 report_json
549 .get("attendanceRecords")
550 .and_then(Value::as_array)
551 .into_iter()
552 .flatten()
553 .map(|record| {
554 let intervals: Vec<&Value> = record
555 .get("attendanceIntervals")
556 .and_then(Value::as_array)
557 .into_iter()
558 .flatten()
559 .collect();
560 let name = record
561 .pointer("/identity/displayName")
562 .and_then(Value::as_str)
563 .filter(|name| !name.is_empty())
564 .or_else(|| record.get("emailAddress").and_then(Value::as_str))
565 .unwrap_or("?");
566 AttendanceRecord {
567 name: name.to_owned(),
568 joined_at: intervals
569 .iter()
570 .filter_map(|interval| parse_stamp(interval.get("joinDateTime")))
571 .min(),
572 left_at: intervals
573 .iter()
574 .filter_map(|interval| parse_stamp(interval.get("leaveDateTime")))
575 .max(),
576 duration_seconds: record
577 .get("totalAttendanceInSeconds")
578 .and_then(Value::as_u64)
579 .unwrap_or(0),
580 }
581 })
582 .collect()
583}
584
585#[cfg(test)]
586mod tests {
587 use super::*;
588
589 fn fixture(name: &str) -> Value {
590 let path = format!("{}/tests/fixtures/recap/{name}", env!("CARGO_MANIFEST_DIR"));
591 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
592 }
593
594 #[test]
595 fn occurrences_keep_finished_recordings_newest_first() {
596 let occurrences = sorted_occurrences(parse_occurrences(&fixture("messages.json")));
597 assert_eq!(occurrences.len(), 2);
598 assert_eq!(occurrences[0].message_id, "2002");
599 assert_eq!(occurrences[0].duration_seconds, Some(1832));
600 assert_eq!(
601 occurrences[0].organizer_id.as_deref(),
602 Some("user-organizer")
603 );
604 assert_eq!(occurrences[1].message_id, "2001");
605 assert_eq!(occurrences[1].duration_seconds, None);
606 }
607
608 #[test]
609 fn deleted_recordings_drop_out_of_the_occurrences() {
610 let occurrences = sorted_occurrences(parse_occurrences(&fixture("messages.json")));
611 let deleted: HashSet<String> = [occurrences[0].recording_url.clone()].into();
612 let remaining = without_deleted(occurrences, &deleted);
613 assert_eq!(remaining.len(), 1);
614 assert_eq!(remaining[0].message_id, "2001");
615 }
616
617 #[test]
618 fn iso_durations_parse_to_seconds() {
619 assert_eq!(parse_iso_duration("PT1H2M3S"), Some(3723));
620 assert_eq!(parse_iso_duration("PT45M"), Some(2700));
621 assert_eq!(parse_iso_duration("PT12.5S"), Some(12));
622 assert_eq!(parse_iso_duration("1H"), None);
623 assert_eq!(parse_iso_duration("PT5"), None);
624 }
625
626 #[test]
627 fn expiration_reads_the_list_item_field() {
628 let expires_at = parse_expiration(&fixture("expiration.json")).unwrap();
629 assert_eq!(expires_at.to_rfc3339(), "2026-05-01T08:00:00+00:00");
630 assert_eq!(parse_expiration(&serde_json::json!({"fields": {}})), None);
631 }
632
633 #[test]
634 fn days_until_expiry_rounds_up_and_floors_at_zero() {
635 let now = DateTime::parse_from_rfc3339("2026-04-24T08:00:00Z")
636 .unwrap()
637 .with_timezone(&Utc);
638 let in_hours = |hours| now + chrono::Duration::hours(hours);
639 assert_eq!(days_until_expiry(in_hours(7 * 24), now), 7);
640 assert_eq!(days_until_expiry(in_hours(36), now), 2);
641 assert_eq!(days_until_expiry(in_hours(-5), now), 0);
642 }
643
644 #[test]
645 fn audio_only_when_the_item_has_no_video_size() {
646 assert!(is_audio_only(&serde_json::json!({"file": {}})));
647 assert!(!is_audio_only(
648 &serde_json::json!({"video": {"width": 1280, "duration": 90000}})
649 ));
650 assert_eq!(
651 item_duration_seconds(&serde_json::json!({"video": {"duration": 90000}})),
652 Some(90)
653 );
654 }
655
656 #[test]
657 fn audio_only_recordings_are_found_by_the_curtain_marker_in_the_chat_event() {
658 let names = parse_audio_only_names(&fixture("chatsvc_messages.json"));
659 assert_eq!(
660 names,
661 HashSet::from(["Weekly sync-20260309_100000-Meeting Recording.mp4".to_owned()])
662 );
663 let occurrences = with_audio_only(
664 sorted_occurrences(parse_occurrences(&fixture("messages.json"))),
665 &names,
666 );
667 assert!(occurrences[0].audio_only);
668 assert!(!occurrences[1].audio_only);
669 }
670
671 #[test]
672 fn transcript_only_items_are_told_apart_by_their_media_source() {
673 assert!(is_transcript_only(&fixture("drive_item_transcript.json")));
674 assert!(!is_transcript_only(&fixture("drive_item.json")));
675 assert!(!is_transcript_only(&fixture("drive_item_recording.json")));
676 }
677
678 #[test]
679 fn recording_item_gives_url_duration_and_video() {
680 let item = fixture("drive_item.json");
681 assert_eq!(
682 item_url("https://contoso-my.sharepoint.com", &item).as_deref(),
683 Some("https://contoso-my.sharepoint.com/_api/v2.1/drives/drive-1/items/item-1")
684 );
685 assert!(!is_audio_only(&item));
686 assert_eq!(item_duration_seconds(&item), Some(53));
687 }
688
689 #[test]
690 fn transcript_urls_request_the_wanted_format() {
691 assert_eq!(
692 transcript_url("https://a.example/_api/v2.1/drives/d/items/i", "t 1", "vtt"),
693 "https://a.example/_api/v2.1/drives/d/items/i/media/transcripts/t%201/streamContent?format=vtt"
694 );
695 assert_eq!(TranscriptFormat::Docx.query(), "docx");
696 }
697
698 #[test]
699 fn binary_answers_decode_from_base64() {
700 let body = serde_json::json!({"base64": "V0VCVlRU", "contentType": "text/vtt"});
701 assert_eq!(decode_binary(&body), Some(b"WEBVTT".to_vec()));
702 assert_eq!(decode_binary(&serde_json::json!({})), None);
703 }
704
705 #[test]
706 fn attendance_spans_first_join_to_last_leave() {
707 let records = parse_attendance(&fixture("attendance.json"));
708 assert_eq!(records.len(), 2);
709 assert_eq!(records[0].name, "Alex Example");
710 assert_eq!(records[0].duration_seconds, 1500);
711 assert_eq!(
712 records[0].joined_at.unwrap().to_rfc3339(),
713 "2026-03-02T10:00:00+00:00"
714 );
715 assert_eq!(
716 records[0].left_at.unwrap().to_rfc3339(),
717 "2026-03-02T10:30:00+00:00"
718 );
719 assert_eq!(records[1].name, "sam@example.com");
720 }
721}