BlueGit

ict rusty-teams

Files

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

recap.rs

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