BlueGit

ict rusty-teams

Files

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

calllog.rs

calllog.rs 10.8 KiB Download Raw
1use std::cmp::Reverse;
2use std::collections::HashSet;
3
4use chrono::{DateTime, Utc};
5use serde_json::Value;
6use session::Request;
7
8use crate::error::{Error, Result};
9use crate::messages::{MessageTransport, Messages, encode, ensure_success};
10
11const CALL_LOG_CONVERSATION: &str = "48:calllogs";
12const LIST_QUERY: &str = "view=msnp24Equivalent&pageSize=200";
13const MULTI_PARTY: &str = "multiParty";
14const VOICEMAIL_TYPE: &str = "voicemail";
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum CallDirection {
18 Incoming,
19 Outgoing,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum CallOutcome {
24 Accepted,
25 Missed,
26 Declined,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct CallLogEntry {
31 pub call_id: String,
32 pub started_at: DateTime<Utc>,
33 pub duration_seconds: Option<i64>,
34 pub direction: CallDirection,
35 pub outcome: CallOutcome,
36 pub is_meeting: bool,
37 pub peer_id: Option<String>,
38 pub peer_name: Option<String>,
39 pub thread_id: Option<String>,
40}
41
42impl CallLogEntry {
43 pub fn missed(&self) -> bool {
44 self.direction == CallDirection::Incoming && self.outcome == CallOutcome::Missed
45 }
46}
47
48fn text(value: &Value, key: &str) -> Option<String> {
49 value
50 .get(key)?
51 .as_str()
52 .filter(|text| !text.is_empty())
53 .map(str::to_owned)
54}
55
56fn time(value: &Value, key: &str) -> Option<DateTime<Utc>> {
57 DateTime::parse_from_rfc3339(value.get(key)?.as_str()?)
58 .ok()
59 .map(|time| time.with_timezone(&Utc))
60}
61
62fn log_of(message: &Value) -> Option<Value> {
63 match message.pointer("/properties/call-log")? {
64 Value::String(text) => serde_json::from_str(text).ok(),
65 object @ Value::Object(_) => Some(object.clone()),
66 _ => None,
67 }
68}
69
70fn direction_of(log: &Value) -> Option<CallDirection> {
71 match log.get("callDirection")?.as_str()? {
72 "incoming" => Some(CallDirection::Incoming),
73 "outgoing" => Some(CallDirection::Outgoing),
74 _ => None,
75 }
76}
77
78fn outcome_of(log: &Value, connected: bool) -> CallOutcome {
79 match log.get("callState").and_then(Value::as_str) {
80 Some("accepted") => CallOutcome::Accepted,
81 Some("declined") => CallOutcome::Declined,
82 Some("missed") => CallOutcome::Missed,
83 _ if connected => CallOutcome::Accepted,
84 _ => CallOutcome::Missed,
85 }
86}
87
88fn peer_of(log: &Value, direction: CallDirection) -> (Option<String>, Option<String>) {
89 let (participant_key, id_key) = match direction {
90 CallDirection::Incoming => ("originatorParticipant", "originator"),
91 CallDirection::Outgoing => ("targetParticipant", "target"),
92 };
93 let participant = log.get(participant_key).unwrap_or(&Value::Null);
94 if participant.get("type").and_then(Value::as_str) == Some(VOICEMAIL_TYPE) {
95 return (None, None);
96 }
97 let peer_id = text(participant, "id").or_else(|| text(log, id_key));
98 (peer_id, text(participant, "displayName"))
99}
100
101fn call_log_entry(message: &Value) -> Option<CallLogEntry> {
102 let log = log_of(message)?;
103 let direction = direction_of(&log)?;
104 let started_at = time(&log, "startTime")?;
105 let connected_at = time(&log, "connectTime");
106 let duration_seconds = connected_at
107 .zip(time(&log, "endTime"))
108 .map(|(connected, ended)| (ended - connected).num_seconds().max(0));
109 let (peer_id, peer_name) = peer_of(&log, direction);
110 Some(CallLogEntry {
111 call_id: text(&log, "callId").or_else(|| text(message, "id"))?,
112 started_at,
113 duration_seconds,
114 direction,
115 outcome: outcome_of(&log, connected_at.is_some()),
116 is_meeting: log.get("callType").and_then(Value::as_str) == Some(MULTI_PARTY),
117 peer_id,
118 peer_name,
119 thread_id: text(&log, "threadId"),
120 })
121}
122
123pub fn parse_call_logs(body: &Value) -> Result<Vec<CallLogEntry>> {
124 let messages = body
125 .get("messages")
126 .and_then(Value::as_array)
127 .ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?;
128 let mut seen = HashSet::new();
129 let mut entries: Vec<CallLogEntry> = messages
130 .iter()
131 .filter_map(call_log_entry)
132 .filter(|entry| seen.insert(entry.call_id.clone()))
133 .collect();
134 entries.sort_by_key(|entry| Reverse(entry.started_at));
135 Ok(entries)
136}
137
138impl<T: MessageTransport> Messages<T> {
139 pub fn call_logs_url(&self) -> String {
140 format!(
141 "{}/{}/messages?{LIST_QUERY}",
142 self.base_url,
143 encode(CALL_LOG_CONVERSATION)
144 )
145 }
146
147 pub async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
148 let answer = self
149 .transport
150 .send(Request::get(self.call_logs_url()))
151 .await?;
152 ensure_success(&answer)?;
153 parse_call_logs(&answer.body)
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use std::sync::Mutex;
160
161 use serde_json::json;
162 use session::{ApiResponse, Method};
163
164 use super::*;
165
166 struct Canned {
167 body: Value,
168 requests: Mutex<Vec<Request>>,
169 }
170
171 impl MessageTransport for Canned {
172 async fn send(&self, request: Request) -> Result<ApiResponse> {
173 self.requests.lock().unwrap().push(request);
174 Ok(ApiResponse {
175 status: 200,
176 body: self.body.clone(),
177 retry_after: None,
178 })
179 }
180 }
181
182 fn message(log: Value) -> Value {
183 json!({"messagetype": "Text", "properties": {"call-log": log.to_string()}})
184 }
185
186 fn log(direction: &str, state: &str, connect: Option<&str>, end: &str) -> Value {
187 json!({
188 "callId": format!("{direction}-{state}-{end}"),
189 "startTime": "2026-10-09T08:00:00.000Z",
190 "connectTime": connect,
191 "endTime": end,
192 "callDirection": direction,
193 "callType": "twoParty",
194 "callState": state,
195 "originator": "8:orgid:caller",
196 "target": "8:orgid:callee",
197 "originatorParticipant": {"id": "8:orgid:caller", "displayName": "Ada", "type": "user"},
198 "targetParticipant": {"id": "8:orgid:callee", "displayName": null, "type": "user"},
199 })
200 }
201
202 fn parse(logs: Vec<Value>) -> Vec<CallLogEntry> {
203 let messages: Vec<Value> = logs.into_iter().map(message).collect();
204 parse_call_logs(&json!({"messages": messages})).unwrap()
205 }
206
207 #[test]
208 fn an_accepted_incoming_call_has_the_caller_and_a_duration() {
209 let entries = parse(vec![log(
210 "incoming",
211 "accepted",
212 Some("2026-10-09T08:00:05.000Z"),
213 "2026-10-09T08:12:05.000Z",
214 )]);
215 let entry = &entries[0];
216 assert_eq!(entry.direction, CallDirection::Incoming);
217 assert_eq!(entry.outcome, CallOutcome::Accepted);
218 assert_eq!(entry.duration_seconds, Some(720));
219 assert_eq!(entry.peer_id.as_deref(), Some("8:orgid:caller"));
220 assert_eq!(entry.peer_name.as_deref(), Some("Ada"));
221 assert!(!entry.missed());
222 assert!(!entry.is_meeting);
223 }
224
225 #[test]
226 fn an_outgoing_call_names_the_target_even_without_a_display_name() {
227 let entries = parse(vec![log(
228 "outgoing",
229 "accepted",
230 Some("2026-10-09T08:00:05.000Z"),
231 "2026-10-09T08:04:17.000Z",
232 )]);
233 assert_eq!(entries[0].direction, CallDirection::Outgoing);
234 assert_eq!(entries[0].duration_seconds, Some(252));
235 assert_eq!(entries[0].peer_id.as_deref(), Some("8:orgid:callee"));
236 assert_eq!(entries[0].peer_name, None);
237 }
238
239 #[test]
240 fn a_missed_incoming_call_has_no_connect_time_and_no_duration() {
241 let entries = parse(vec![log(
242 "incoming",
243 "missed",
244 None,
245 "2026-10-09T08:00:30.000Z",
246 )]);
247 assert!(entries[0].missed());
248 assert_eq!(entries[0].duration_seconds, None);
249 }
250
251 #[test]
252 fn a_declined_call_and_an_unanswered_outgoing_call_are_not_missed_calls() {
253 let entries = parse(vec![
254 log("incoming", "declined", None, "2026-10-09T08:00:10.000Z"),
255 log("outgoing", "missed", None, "2026-10-09T08:00:40.000Z"),
256 ]);
257 assert!(entries.iter().all(|entry| !entry.missed()));
258 assert_eq!(entries[0].outcome, CallOutcome::Declined);
259 }
260
261 #[test]
262 fn a_multi_party_call_is_a_meeting_with_its_thread() {
263 let mut meeting = log(
264 "incoming",
265 "accepted",
266 Some("2026-10-09T08:00:05.000Z"),
267 "2026-10-09T08:38:05.000Z",
268 );
269 meeting["callType"] = json!("multiParty");
270 meeting["threadId"] = json!("19:meeting_x@thread.v2");
271 let entries = parse(vec![meeting]);
272 assert!(entries[0].is_meeting);
273 assert_eq!(
274 entries[0].thread_id.as_deref(),
275 Some("19:meeting_x@thread.v2")
276 );
277 assert_eq!(entries[0].duration_seconds, Some(2280));
278 }
279
280 #[test]
281 fn a_voicemail_target_is_no_peer() {
282 let mut forwarded = log("outgoing", "missed", None, "2026-10-09T08:00:40.000Z");
283 forwarded["targetParticipant"]["type"] = json!("voicemail");
284 let entries = parse(vec![forwarded]);
285 assert_eq!(entries[0].peer_id, None);
286 }
287
288 #[test]
289 fn entries_sort_newest_first_and_skip_other_messages_and_duplicates() {
290 let mut older = log("incoming", "missed", None, "2026-10-08T08:00:30.000Z");
291 older["callId"] = json!("older");
292 older["startTime"] = json!("2026-10-08T08:00:00.000Z");
293 let newer = log("incoming", "missed", None, "2026-10-09T08:00:30.000Z");
294 let body = json!({"messages": [
295 message(older),
296 message(newer.clone()),
297 message(newer),
298 {"messagetype": "RichText/Media_CallLogRecording", "properties": {}},
299 {"messagetype": "Text", "properties": {"call-log": "not json"}},
300 ]});
301 let entries = parse_call_logs(&body).unwrap();
302 assert_eq!(entries.len(), 2);
303 assert_eq!(entries[1].call_id, "older");
304 assert!(entries[0].started_at > entries[1].started_at);
305 }
306
307 #[test]
308 fn a_body_without_messages_is_unexpected() {
309 assert!(matches!(
310 parse_call_logs(&json!({})),
311 Err(Error::UnexpectedAnswer(_))
312 ));
313 }
314
315 #[tokio::test]
316 async fn the_list_reads_the_calllogs_conversation() {
317 let messages = Messages::with_transport(
318 Canned {
319 body: json!({"messages": []}),
320 requests: Mutex::new(Vec::new()),
321 },
322 "emea",
323 );
324 assert!(messages.list_call_logs().await.unwrap().is_empty());
325 let requests = messages.transport.requests.lock().unwrap();
326 assert_eq!(requests[0].method, Method::Get);
327 assert_eq!(
328 requests[0].url,
329 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/48%3Acalllogs/messages?view=msnp24Equivalent&pageSize=200"
330 );
331 }
332}