BlueGit

ict rusty-teams

Files

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

recap.rs

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