| 1 | use serde::{Deserialize, Serialize}; |
| 2 | use serde_json::Value; |
| 3 | use store::MessageRecord; |
| 4 | |
| 5 | const STARTED_TYPE: &str = "#microsoft.graph.callStartedEventMessageDetail"; |
| 6 | const ENDED_TYPE: &str = "#microsoft.graph.callEndedEventMessageDetail"; |
| 7 | const RECORDING_TYPE: &str = "#microsoft.graph.callRecordingEventMessageDetail"; |
| 8 | const TRANSCRIPT_TYPE: &str = "#microsoft.graph.callTranscriptEventMessageDetail"; |
| 9 | const UNRESOLVED_NAME_PREFIX: &str = "orgid:"; |
| 10 | const RECORDING_SUFFIX: &str = "-Meeting Recording"; |
| 11 | const GRAPH_SHARES: &str = "https://graph.microsoft.com/v1.0/shares/"; |
| 12 | const THUMBNAIL_PATH: &str = "/driveItem/thumbnails/0/large/content"; |
| 13 | const SHAREPOINT_HOST: &str = ".sharepoint.com/"; |
| 14 | const SECONDS_PER_MINUTE: u64 = 60; |
| 15 | const SECONDS_PER_HOUR: u64 = 3600; |
| 16 | const SECONDS_PER_DAY: u64 = 86_400; |
| 17 | |
| 18 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 19 | pub enum CallPhase { |
| 20 | Started, |
| 21 | Ended, |
| 22 | RecordingStarted, |
| 23 | RecordingStopped, |
| 24 | RecordingSaved, |
| 25 | TranscriptStarted, |
| 26 | } |
| 27 | |
| 28 | impl CallPhase { |
| 29 | pub fn is_call(self) -> bool { |
| 30 | matches!(self, CallPhase::Started | CallPhase::Ended) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 35 | pub enum CallType { |
| 36 | Call, |
| 37 | Meeting, |
| 38 | } |
| 39 | |
| 40 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 41 | pub struct CallEvent { |
| 42 | pub phase: CallPhase, |
| 43 | pub call_type: CallType, |
| 44 | pub call_id: String, |
| 45 | pub duration_seconds: Option<u64>, |
| 46 | pub initiator_id: Option<String>, |
| 47 | pub initiator_name: Option<String>, |
| 48 | pub participant_ids: Vec<String>, |
| 49 | #[serde(default)] |
| 50 | pub participant_names: Vec<String>, |
| 51 | #[serde(default)] |
| 52 | pub recording: Option<Recording>, |
| 53 | } |
| 54 | |
| 55 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 56 | pub struct Recording { |
| 57 | pub name: Option<String>, |
| 58 | pub url: Option<String>, |
| 59 | pub organizer_id: Option<String>, |
| 60 | } |
| 61 | |
| 62 | impl Recording { |
| 63 | pub fn title(&self) -> Option<String> { |
| 64 | let name = self.name.as_deref()?; |
| 65 | let stem = name.strip_suffix(".mp4").unwrap_or(name); |
| 66 | let stem = stem.strip_suffix(RECORDING_SUFFIX).unwrap_or(stem); |
| 67 | let title = match stem.rsplit_once('-') { |
| 68 | Some((title, stamp)) if is_recording_stamp(stamp) => title, |
| 69 | _ => stem, |
| 70 | }; |
| 71 | Some(title.trim().to_owned()).filter(|title| !title.is_empty()) |
| 72 | } |
| 73 | |
| 74 | pub fn thumbnail_url(&self) -> Option<String> { |
| 75 | let url = self |
| 76 | .url |
| 77 | .as_deref() |
| 78 | .filter(|url| url.contains(SHAREPOINT_HOST))?; |
| 79 | Some(format!( |
| 80 | "{GRAPH_SHARES}{}{THUMBNAIL_PATH}", |
| 81 | chatsvc::transcripts::share_id(url) |
| 82 | )) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | fn is_recording_stamp(stamp: &str) -> bool { |
| 87 | let digits = stamp.strip_suffix("UTC").unwrap_or(stamp); |
| 88 | digits.split_once('_').is_some_and(|(date, time)| { |
| 89 | date.len() == 8 |
| 90 | && time.len() == 6 |
| 91 | && date |
| 92 | .bytes() |
| 93 | .chain(time.bytes()) |
| 94 | .all(|byte| byte.is_ascii_digit()) |
| 95 | }) |
| 96 | } |
| 97 | |
| 98 | fn recording_phase(detail: &Value) -> Option<CallPhase> { |
| 99 | match detail.get("callRecordingStatus").and_then(Value::as_str)? { |
| 100 | "initial" => Some(CallPhase::RecordingStarted), |
| 101 | "chunkFinished" => Some(CallPhase::RecordingStopped), |
| 102 | "success" => Some(CallPhase::RecordingSaved), |
| 103 | _ => None, |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | impl CallEvent { |
| 108 | pub fn from_graph(detail: &Value) -> Option<CallEvent> { |
| 109 | let phase = match detail.get("@odata.type")?.as_str()? { |
| 110 | STARTED_TYPE => CallPhase::Started, |
| 111 | ENDED_TYPE => CallPhase::Ended, |
| 112 | RECORDING_TYPE => recording_phase(detail)?, |
| 113 | TRANSCRIPT_TYPE => CallPhase::TranscriptStarted, |
| 114 | _ => return None, |
| 115 | }; |
| 116 | let participants: Vec<(String, Option<String>)> = detail |
| 117 | .get("callParticipants") |
| 118 | .and_then(Value::as_array) |
| 119 | .map(|participants| { |
| 120 | participants |
| 121 | .iter() |
| 122 | .filter_map(|participant| identity(participant.get("participant")?)) |
| 123 | .collect() |
| 124 | }) |
| 125 | .unwrap_or_default(); |
| 126 | let recording = |
| 127 | (detail.get("@odata.type")?.as_str()? == RECORDING_TYPE).then(|| Recording { |
| 128 | name: text_at(detail, "/callRecordingDisplayName"), |
| 129 | url: text_at(detail, "/callRecordingUrl"), |
| 130 | organizer_id: text_at(detail, "/meetingOrganizer/user/id"), |
| 131 | }); |
| 132 | let call_type = match detail.get("callEventType").and_then(Value::as_str) { |
| 133 | Some("meeting") => CallType::Meeting, |
| 134 | _ => CallType::Call, |
| 135 | }; |
| 136 | Some(CallEvent { |
| 137 | phase, |
| 138 | call_type, |
| 139 | call_id: detail.get("callId")?.as_str()?.to_owned(), |
| 140 | duration_seconds: detail |
| 141 | .get("callDuration") |
| 142 | .or_else(|| detail.get("callRecordingDuration")) |
| 143 | .and_then(Value::as_str) |
| 144 | .and_then(parse_duration_seconds), |
| 145 | initiator_id: text_at(detail, "/initiator/user/id"), |
| 146 | initiator_name: person_name(detail.pointer("/initiator/user")), |
| 147 | participant_names: participants |
| 148 | .iter() |
| 149 | .map(|(_, name)| name.clone().unwrap_or_default()) |
| 150 | .collect(), |
| 151 | participant_ids: participants.into_iter().map(|(id, _)| id).collect(), |
| 152 | recording, |
| 153 | }) |
| 154 | } |
| 155 | |
| 156 | pub fn from_json(json: &str) -> Option<CallEvent> { |
| 157 | serde_json::from_str(json).ok() |
| 158 | } |
| 159 | |
| 160 | pub fn to_json(&self) -> String { |
| 161 | serde_json::to_string(self).unwrap_or_default() |
| 162 | } |
| 163 | |
| 164 | pub fn initiated_by(&self, user_id: Option<&str>) -> bool { |
| 165 | user_id.is_some() && self.initiator_id.as_deref() == user_id |
| 166 | } |
| 167 | |
| 168 | pub fn missed(&self, my_user_id: Option<&str>) -> bool { |
| 169 | my_user_id.is_some() |
| 170 | && self.phase == CallPhase::Ended |
| 171 | && self.call_type == CallType::Call |
| 172 | && self.participant_ids.len() < 2 |
| 173 | && !self.initiated_by(my_user_id) |
| 174 | } |
| 175 | |
| 176 | pub fn is_recording(&self) -> bool { |
| 177 | matches!( |
| 178 | self.phase, |
| 179 | CallPhase::RecordingStarted |
| 180 | | CallPhase::RecordingStopped |
| 181 | | CallPhase::RecordingSaved |
| 182 | | CallPhase::TranscriptStarted |
| 183 | ) |
| 184 | } |
| 185 | |
| 186 | pub fn title(&self, missed: bool) -> &'static str { |
| 187 | match (self.phase, self.call_type) { |
| 188 | _ if missed => "Missed call", |
| 189 | (CallPhase::Started, CallType::Call) => "Call started", |
| 190 | (CallPhase::Ended, CallType::Call) => "Call ended", |
| 191 | (CallPhase::Started, CallType::Meeting) => "Meeting started", |
| 192 | (CallPhase::Ended, CallType::Meeting) => "Meeting ended", |
| 193 | (CallPhase::RecordingStarted, _) => "Recording has started", |
| 194 | (CallPhase::RecordingStopped, _) => "Recording stopped", |
| 195 | (CallPhase::RecordingSaved, _) => "Recording is ready", |
| 196 | (CallPhase::TranscriptStarted, _) => "Transcription has started", |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | pub fn plain_text(&self) -> String { |
| 201 | let title = self.title(false); |
| 202 | match self.duration_seconds { |
| 203 | Some(seconds) if !self.is_recording() => { |
| 204 | format!("{title} {}", format_duration(seconds)) |
| 205 | } |
| 206 | _ => title.to_owned(), |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | pub fn call_event(record: &MessageRecord) -> Option<CallEvent> { |
| 212 | CallEvent::from_json(record.call_event_json.as_deref()?) |
| 213 | } |
| 214 | |
| 215 | fn identity(identity_set: &Value) -> Option<(String, Option<String>)> { |
| 216 | identity_set |
| 217 | .as_object()? |
| 218 | .values() |
| 219 | .find_map(|identity| Some((text_at(identity, "/id")?, person_name(Some(identity))))) |
| 220 | } |
| 221 | |
| 222 | fn person_name(identity: Option<&Value>) -> Option<String> { |
| 223 | text_at(identity?, "/displayName").filter(|name| !name.starts_with(UNRESOLVED_NAME_PREFIX)) |
| 224 | } |
| 225 | |
| 226 | fn text_at(value: &Value, pointer: &str) -> Option<String> { |
| 227 | value |
| 228 | .pointer(pointer)? |
| 229 | .as_str() |
| 230 | .filter(|text| !text.is_empty()) |
| 231 | .map(str::to_owned) |
| 232 | } |
| 233 | |
| 234 | pub fn parse_duration_seconds(text: &str) -> Option<u64> { |
| 235 | let rest = text.strip_prefix('P')?; |
| 236 | let (date_part, time_part) = match rest.split_once('T') { |
| 237 | Some((date_part, time_part)) => (date_part, time_part), |
| 238 | None => (rest, ""), |
| 239 | }; |
| 240 | if date_part.is_empty() && time_part.is_empty() { |
| 241 | return None; |
| 242 | } |
| 243 | let days = sum_components(date_part, &[('D', SECONDS_PER_DAY)])?; |
| 244 | let time = sum_components( |
| 245 | time_part, |
| 246 | &[('H', SECONDS_PER_HOUR), ('M', SECONDS_PER_MINUTE), ('S', 1)], |
| 247 | )?; |
| 248 | Some(days + time) |
| 249 | } |
| 250 | |
| 251 | fn sum_components(part: &str, units: &[(char, u64)]) -> Option<u64> { |
| 252 | let mut total = 0; |
| 253 | let mut number = String::new(); |
| 254 | for character in part.chars() { |
| 255 | if character.is_ascii_digit() || character == '.' { |
| 256 | number.push(character); |
| 257 | continue; |
| 258 | } |
| 259 | let (_, factor) = units.iter().find(|(unit, _)| *unit == character)?; |
| 260 | let value: f64 = number.parse().ok()?; |
| 261 | total += (value * *factor as f64) as u64; |
| 262 | number.clear(); |
| 263 | } |
| 264 | number.is_empty().then_some(total) |
| 265 | } |
| 266 | |
| 267 | pub fn format_duration(seconds: u64) -> String { |
| 268 | let hours = seconds / SECONDS_PER_HOUR; |
| 269 | let minutes = seconds % SECONDS_PER_HOUR / SECONDS_PER_MINUTE; |
| 270 | let remainder = seconds % SECONDS_PER_MINUTE; |
| 271 | let mut parts = Vec::new(); |
| 272 | if hours > 0 { |
| 273 | parts.push(format!("{hours}h")); |
| 274 | } |
| 275 | if minutes > 0 || (hours > 0 && remainder > 0) { |
| 276 | parts.push(format!("{minutes}m")); |
| 277 | } |
| 278 | if remainder > 0 || (hours == 0 && minutes == 0) { |
| 279 | parts.push(format!("{remainder}s")); |
| 280 | } |
| 281 | parts.join(" ") |
| 282 | } |
| 283 | |
| 284 | #[cfg(test)] |
| 285 | mod tests { |
| 286 | use super::*; |
| 287 | |
| 288 | fn fixture(name: &str) -> Value { |
| 289 | let path = format!( |
| 290 | "{}/tests/fixtures/call_events/{name}", |
| 291 | env!("CARGO_MANIFEST_DIR") |
| 292 | ); |
| 293 | serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() |
| 294 | } |
| 295 | |
| 296 | fn meeting_chat_events() -> Vec<CallEvent> { |
| 297 | fixture("meeting_chat_recording.json")["value"] |
| 298 | .as_array() |
| 299 | .unwrap() |
| 300 | .iter() |
| 301 | .rev() |
| 302 | .map(|message| CallEvent::from_graph(&message["eventDetail"]).unwrap()) |
| 303 | .collect() |
| 304 | } |
| 305 | |
| 306 | #[test] |
| 307 | fn recorded_meeting_yields_every_phase_in_order() { |
| 308 | let phases: Vec<CallPhase> = meeting_chat_events() |
| 309 | .iter() |
| 310 | .map(|event| event.phase) |
| 311 | .collect(); |
| 312 | assert_eq!( |
| 313 | phases, |
| 314 | [ |
| 315 | CallPhase::Started, |
| 316 | CallPhase::RecordingStarted, |
| 317 | CallPhase::RecordingStarted, |
| 318 | CallPhase::TranscriptStarted, |
| 319 | CallPhase::RecordingStopped, |
| 320 | CallPhase::Ended, |
| 321 | CallPhase::RecordingStopped, |
| 322 | CallPhase::RecordingSaved, |
| 323 | ] |
| 324 | ); |
| 325 | let call_ids: std::collections::HashSet<String> = meeting_chat_events() |
| 326 | .into_iter() |
| 327 | .map(|event| event.call_id) |
| 328 | .collect(); |
| 329 | assert_eq!(call_ids.len(), 1); |
| 330 | } |
| 331 | |
| 332 | #[test] |
| 333 | fn saved_recording_keeps_link_title_duration_and_owner() { |
| 334 | let saved = meeting_chat_events().pop().unwrap(); |
| 335 | let recording = saved.recording.as_ref().unwrap(); |
| 336 | assert_eq!(saved.duration_seconds, Some(814)); |
| 337 | assert_eq!(recording.title().as_deref(), Some("Weekly team meeting")); |
| 338 | assert!(recording.url.as_deref().unwrap().contains("/:v:/")); |
| 339 | assert_eq!( |
| 340 | recording.organizer_id.as_deref(), |
| 341 | Some("00000000-0000-4000-8000-000000000002") |
| 342 | ); |
| 343 | assert_eq!(saved.plain_text(), "Recording is ready"); |
| 344 | let thumbnail = recording.thumbnail_url().unwrap(); |
| 345 | assert!(thumbnail.starts_with("https://graph.microsoft.com/v1.0/shares/u!")); |
| 346 | assert!(thumbnail.ends_with("/driveItem/thumbnails/0/large/content")); |
| 347 | } |
| 348 | |
| 349 | #[test] |
| 350 | fn started_recording_has_no_link_and_names_its_initiator_by_id() { |
| 351 | let started = &meeting_chat_events()[1]; |
| 352 | assert_eq!(started.recording.as_ref().unwrap().url, None); |
| 353 | assert_eq!(started.recording.as_ref().unwrap().thumbnail_url(), None); |
| 354 | assert_eq!(started.duration_seconds, Some(0)); |
| 355 | assert!(started.initiator_id.is_some()); |
| 356 | assert_eq!(started.initiator_name, None); |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn ended_meeting_keeps_participant_names_beside_their_ids() { |
| 361 | let ended = meeting_chat_events() |
| 362 | .into_iter() |
| 363 | .find(|event| event.phase == CallPhase::Ended) |
| 364 | .unwrap(); |
| 365 | assert_eq!(ended.call_type, CallType::Meeting); |
| 366 | assert_eq!(ended.duration_seconds, Some(988)); |
| 367 | assert_eq!(ended.participant_ids.len(), ended.participant_names.len()); |
| 368 | assert_eq!(ended.participant_names[0], ""); |
| 369 | assert_eq!(ended.participant_names[1], "Person 1"); |
| 370 | assert_eq!(ended.recording, None); |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn channel_meet_now_root_is_a_started_meeting() { |
| 375 | let thread = fixture("channel_adhoc_meeting.json"); |
| 376 | let root = CallEvent::from_graph(&thread["eventDetail"]).unwrap(); |
| 377 | let ended = CallEvent::from_graph(&thread["replies"][0]["eventDetail"]).unwrap(); |
| 378 | assert_eq!(root.phase, CallPhase::Started); |
| 379 | assert_eq!(root.call_type, CallType::Meeting); |
| 380 | assert_eq!(ended.call_id, root.call_id); |
| 381 | assert_eq!(ended.duration_seconds, Some(11_975)); |
| 382 | assert_eq!(ended.initiator_name, None); |
| 383 | } |
| 384 | |
| 385 | #[test] |
| 386 | fn unknown_recording_status_is_not_an_event() { |
| 387 | let detail = serde_json::json!({ |
| 388 | "@odata.type": RECORDING_TYPE, |
| 389 | "callId": "c", |
| 390 | "callRecordingStatus": "failure", |
| 391 | }); |
| 392 | assert_eq!(CallEvent::from_graph(&detail), None); |
| 393 | } |
| 394 | |
| 395 | #[test] |
| 396 | fn events_stored_before_recordings_still_load() { |
| 397 | let stored = r#"{"phase":"Ended","call_type":"Call","call_id":"c","duration_seconds":5,"initiator_id":"u","initiator_name":null,"participant_ids":["u"]}"#; |
| 398 | let event = CallEvent::from_json(stored).unwrap(); |
| 399 | assert!(event.participant_names.is_empty()); |
| 400 | assert_eq!(event.recording, None); |
| 401 | } |
| 402 | |
| 403 | #[test] |
| 404 | fn recording_title_drops_the_stamp_only_when_it_is_one() { |
| 405 | let title = |name: &str| { |
| 406 | Recording { |
| 407 | name: Some(name.to_owned()), |
| 408 | url: None, |
| 409 | organizer_id: None, |
| 410 | } |
| 411 | .title() |
| 412 | }; |
| 413 | assert_eq!( |
| 414 | title("Sync-20261012_140227UTC-Meeting Recording.mp4").as_deref(), |
| 415 | Some("Sync") |
| 416 | ); |
| 417 | assert_eq!( |
| 418 | title("Q3-plan-Meeting Recording.mp4").as_deref(), |
| 419 | Some("Q3-plan") |
| 420 | ); |
| 421 | assert_eq!(title("demo.mp4").as_deref(), Some("demo")); |
| 422 | } |
| 423 | } |