BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / call / history.rs

history.rs

history.rs 14.7 KiB Download Raw
1use std::collections::HashMap;
2
3use chrono::{DateTime, Duration, FixedOffset, Utc};
4use gpui_kit::Context;
5use store::ChatRecord;
6use teams_core::{CallDirection, CallLogEntry, CallOutcome};
7
8use crate::app_state::{AppEvent, AppState, Selection, chat_title};
9use crate::data::is_one_on_one;
10use crate::format;
11use crate::notice::short_error;
12use crate::runtime;
13
14const ORGID_PREFIX: &str = "8:orgid:";
15const UNKNOWN_NAME: &str = "Unknown";
16const MEETING_TITLE: &str = "Meeting";
17const NO_CHAT_NOTICE: &str = "No chat with this person yet";
18const NO_MEETING_CHAT_NOTICE: &str = "This meeting chat is not available";
19const REFRESH_DELAY_AFTER_CALL: std::time::Duration = std::time::Duration::from_secs(4);
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct CallRow {
23 pub key: String,
24 pub title: String,
25 pub subline: String,
26 pub time_label: String,
27 pub missed: bool,
28 pub meeting: bool,
29 pub user_id: Option<String>,
30 pub thread_id: Option<String>,
31}
32
33pub fn duration_label(seconds: i64) -> String {
34 let seconds = seconds.max(0);
35 let (hours, minutes, rest) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
36 match (hours, minutes, rest) {
37 (0, 0, _) => format!("{rest}s"),
38 (0, minutes, 0) => format!("{minutes}m"),
39 (0, minutes, rest) if minutes < 10 => format!("{minutes}m {rest}s"),
40 (0, minutes, _) => format!("{minutes}m"),
41 (hours, 0, _) => format!("{hours}h"),
42 (hours, minutes, _) => format!("{hours}h {minutes}m"),
43 }
44}
45
46pub fn subline(entry: &CallLogEntry) -> String {
47 if entry.missed() {
48 return "Missed call".to_owned();
49 }
50 let kind = if entry.is_meeting {
51 "Meeting"
52 } else {
53 match (entry.direction, entry.outcome) {
54 (CallDirection::Incoming, CallOutcome::Declined) => return "Declined call".to_owned(),
55 (CallDirection::Incoming, _) => "Incoming",
56 (CallDirection::Outgoing, _) => "Outgoing",
57 }
58 };
59 match entry.duration_seconds {
60 Some(seconds) => format!("{kind} \u{b7} {}", duration_label(seconds)),
61 None => kind.to_owned(),
62 }
63}
64
65fn user_id_of(mri: &str) -> Option<String> {
66 mri.strip_prefix(ORGID_PREFIX).map(str::to_owned)
67}
68
69fn known_names(chats: &[ChatRecord]) -> HashMap<&str, &str> {
70 chats
71 .iter()
72 .flat_map(|chat| chat.members.iter())
73 .filter_map(|member| Some((member.user_id.as_deref()?, member.display_name.as_str())))
74 .filter(|(_, name)| !name.is_empty())
75 .collect()
76}
77
78pub fn call_rows(
79 entries: &[CallLogEntry],
80 chats: &[ChatRecord],
81 now: DateTime<Utc>,
82 offset: FixedOffset,
83) -> Vec<CallRow> {
84 let names = known_names(chats);
85 let chats_by_id: HashMap<&str, &ChatRecord> =
86 chats.iter().map(|chat| (chat.id.as_str(), chat)).collect();
87 let today = now.with_timezone(&offset).date_naive();
88 entries
89 .iter()
90 .map(|entry| {
91 let user_id = entry
92 .peer_id
93 .as_deref()
94 .and_then(user_id_of)
95 .filter(|_| !entry.is_meeting);
96 let thread_chat = entry
97 .thread_id
98 .as_deref()
99 .and_then(|thread_id| chats_by_id.get(thread_id).copied());
100 let title = if entry.is_meeting {
101 thread_chat.map_or_else(|| MEETING_TITLE.to_owned(), chat_title)
102 } else {
103 entry
104 .peer_name
105 .clone()
106 .or_else(|| {
107 let user_id = user_id.as_deref()?;
108 names.get(user_id).map(|name| (*name).to_owned())
109 })
110 .unwrap_or_else(|| UNKNOWN_NAME.to_owned())
111 };
112 CallRow {
113 key: entry.call_id.clone(),
114 title,
115 subline: subline(entry),
116 time_label: format::list_time_label(entry.started_at, today, offset),
117 missed: entry.missed(),
118 meeting: entry.is_meeting,
119 user_id,
120 thread_id: entry.thread_id.clone().filter(|_| entry.is_meeting),
121 }
122 })
123 .collect()
124}
125
126pub fn demo_call_log(now: DateTime<Utc>) -> Vec<CallLogEntry> {
127 let entry = |id: &str,
128 minutes_ago: i64,
129 direction: CallDirection,
130 outcome: CallOutcome,
131 duration_seconds: Option<i64>,
132 peer: Option<(&str, &str)>,
133 thread_id: Option<&str>| CallLogEntry {
134 call_id: id.to_owned(),
135 started_at: now - Duration::minutes(minutes_ago),
136 duration_seconds,
137 direction,
138 outcome,
139 is_meeting: thread_id.is_some(),
140 peer_id: peer.map(|(user_id, _)| format!("{ORGID_PREFIX}{user_id}")),
141 peer_name: peer.map(|(_, name)| name.to_owned()),
142 thread_id: thread_id.map(str::to_owned),
143 };
144 let incoming = CallDirection::Incoming;
145 let outgoing = CallDirection::Outgoing;
146 let accepted = CallOutcome::Accepted;
147 let mara = Some(("demo-mara", "Mara Lindqvist"));
148 let jonas = Some(("demo-jonas", "Jonas Ortega"));
149 let priya = Some(("demo-priya", "Priya Nair"));
150 vec![
151 entry(
152 "demo-call-1",
153 35,
154 incoming,
155 CallOutcome::Missed,
156 None,
157 mara,
158 None,
159 ),
160 entry(
161 "demo-call-2",
162 190,
163 outgoing,
164 accepted,
165 Some(252),
166 jonas,
167 None,
168 ),
169 entry(
170 "demo-call-3",
171 1500,
172 incoming,
173 accepted,
174 Some(720),
175 priya,
176 None,
177 ),
178 entry(
179 "demo-call-4",
180 1620,
181 incoming,
182 accepted,
183 Some(2280),
184 None,
185 Some("demo-chat-meeting-standup"),
186 ),
187 entry(
188 "demo-call-5",
189 4400,
190 incoming,
191 CallOutcome::Missed,
192 None,
193 jonas,
194 None,
195 ),
196 entry(
197 "demo-call-6",
198 8200,
199 outgoing,
200 accepted,
201 Some(95),
202 mara,
203 None,
204 ),
205 entry(
206 "demo-call-7",
207 11000,
208 incoming,
209 accepted,
210 Some(3900),
211 None,
212 Some("demo-chat-meeting-retro"),
213 ),
214 ]
215}
216
217impl AppState {
218 pub fn refresh_call_history(&mut self, cx: &mut Context<Self>) {
219 if self.mode.demo {
220 self.call_history = demo_call_log(Utc::now());
221 self.calls_list.invalidate();
222 cx.emit(AppEvent::CallHistory);
223 cx.notify();
224 return;
225 }
226 let Some(engine) = self.engine.clone() else {
227 return;
228 };
229 let receiver = runtime::spawn(async move { engine.list_call_logs().await });
230 cx.spawn(async move |this, cx| match receiver.await {
231 Ok(Ok(entries)) => {
232 this.update(cx, |state, cx| {
233 state.call_history = entries;
234 state.calls_list.invalidate();
235 cx.emit(AppEvent::CallHistory);
236 cx.notify();
237 })
238 .ok();
239 }
240 Ok(Err(error)) => crate::diagnostics::record(format!(
241 "calls: history not loaded: {}",
242 short_error(&error)
243 )),
244 Err(_) => {}
245 })
246 .detach();
247 }
248
249 pub fn refresh_call_history_after_call(&mut self, cx: &mut Context<Self>) {
250 cx.spawn(async move |this, cx| {
251 cx.background_executor()
252 .timer(REFRESH_DELAY_AFTER_CALL)
253 .await;
254 this.update(cx, |state, cx| state.refresh_call_history(cx))
255 .ok();
256 })
257 .detach();
258 }
259
260 fn one_on_one_chat_with(&self, user_id: &str) -> Option<String> {
261 self.sidebar
262 .chats
263 .iter()
264 .find(|chat| {
265 is_one_on_one(chat)
266 && chat
267 .members
268 .iter()
269 .any(|member| member.user_id.as_deref() == Some(user_id))
270 })
271 .map(|chat| chat.id.clone())
272 }
273
274 fn chat_of_call_row(&self, row: &CallRow) -> Option<String> {
275 match (&row.thread_id, &row.user_id) {
276 (Some(thread_id), _) => self
277 .sidebar
278 .chats
279 .iter()
280 .any(|chat| &chat.id == thread_id)
281 .then(|| thread_id.clone()),
282 (None, Some(user_id)) => self.one_on_one_chat_with(user_id),
283 (None, None) => None,
284 }
285 }
286
287 pub fn call_back_from_history(&mut self, row: &CallRow, cx: &mut Context<Self>) {
288 let Some(user_id) = row.user_id.as_deref() else {
289 return;
290 };
291 match self.one_on_one_chat_with(user_id) {
292 Some(chat_id) => self.start_chat_call(&chat_id, cx),
293 None => self.raise_notice(NO_CHAT_NOTICE.to_owned(), None, cx),
294 }
295 }
296
297 pub fn open_chat_of_call_row(&mut self, row: &CallRow, cx: &mut Context<Self>) {
298 let notice = if row.meeting {
299 NO_MEETING_CHAT_NOTICE
300 } else {
301 NO_CHAT_NOTICE
302 };
303 match self.chat_of_call_row(row) {
304 Some(chat_id) => self.select(Selection::Chat(chat_id), cx),
305 None => self.raise_notice(notice.to_owned(), None, cx),
306 }
307 }
308
309 pub fn activate_call_row(&mut self, row: &CallRow, cx: &mut Context<Self>) {
310 if row.meeting {
311 self.open_chat_of_call_row(row, cx);
312 } else {
313 self.call_back_from_history(row, cx);
314 }
315 }
316
317 pub fn can_open_chat_of_call_row(&self, row: &CallRow) -> bool {
318 self.chat_of_call_row(row).is_some()
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use chrono::TimeZone;
325 use store::MemberRecord;
326
327 use super::*;
328
329 fn entry(direction: CallDirection, outcome: CallOutcome, seconds: Option<i64>) -> CallLogEntry {
330 CallLogEntry {
331 call_id: "c".into(),
332 started_at: Utc.with_ymd_and_hms(2026, 10, 9, 8, 0, 0).unwrap(),
333 duration_seconds: seconds,
334 direction,
335 outcome,
336 is_meeting: false,
337 peer_id: Some("8:orgid:bea-id".into()),
338 peer_name: None,
339 thread_id: None,
340 }
341 }
342
343 fn chat(id: &str, kind: &str, title: &str, members: &[(&str, &str)]) -> ChatRecord {
344 ChatRecord {
345 id: id.into(),
346 kind: kind.into(),
347 title: title.into(),
348 members: members
349 .iter()
350 .map(|(user_id, name)| MemberRecord {
351 user_id: Some((*user_id).to_owned()),
352 display_name: (*name).to_owned(),
353 })
354 .collect(),
355 ..Default::default()
356 }
357 }
358
359 fn rows(entries: &[CallLogEntry], chats: &[ChatRecord]) -> Vec<CallRow> {
360 let now = Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap();
361 call_rows(entries, chats, now, FixedOffset::east_opt(0).unwrap())
362 }
363
364 #[test]
365 fn durations_show_seconds_only_for_short_calls() {
366 assert_eq!(duration_label(45), "45s");
367 assert_eq!(duration_label(252), "4m 12s");
368 assert_eq!(duration_label(240), "4m");
369 assert_eq!(duration_label(720), "12m");
370 assert_eq!(duration_label(2280), "38m");
371 assert_eq!(duration_label(3600), "1h");
372 assert_eq!(duration_label(3900), "1h 5m");
373 }
374
375 #[test]
376 fn sublines_follow_direction_and_outcome() {
377 let missed = entry(CallDirection::Incoming, CallOutcome::Missed, None);
378 assert_eq!(subline(&missed), "Missed call");
379 let outgoing = entry(CallDirection::Outgoing, CallOutcome::Accepted, Some(252));
380 assert_eq!(subline(&outgoing), "Outgoing \u{b7} 4m 12s");
381 let incoming = entry(CallDirection::Incoming, CallOutcome::Accepted, Some(720));
382 assert_eq!(subline(&incoming), "Incoming \u{b7} 12m");
383 let declined = entry(CallDirection::Incoming, CallOutcome::Declined, None);
384 assert_eq!(subline(&declined), "Declined call");
385 let unanswered = entry(CallDirection::Outgoing, CallOutcome::Missed, None);
386 assert_eq!(subline(&unanswered), "Outgoing");
387 let meeting = CallLogEntry {
388 is_meeting: true,
389 ..entry(CallDirection::Incoming, CallOutcome::Accepted, Some(2280))
390 };
391 assert_eq!(subline(&meeting), "Meeting \u{b7} 38m");
392 }
393
394 #[test]
395 fn a_missing_display_name_comes_from_the_chat_members() {
396 let chats = [chat("19:a", "oneOnOne", "", &[("bea-id", "Bea")])];
397 let list = rows(
398 &[entry(
399 CallDirection::Outgoing,
400 CallOutcome::Accepted,
401 Some(60),
402 )],
403 &chats,
404 );
405 assert_eq!(list[0].title, "Bea");
406 assert_eq!(list[0].user_id.as_deref(), Some("bea-id"));
407 let unknown = rows(
408 &[entry(
409 CallDirection::Outgoing,
410 CallOutcome::Accepted,
411 Some(60),
412 )],
413 &[],
414 );
415 assert_eq!(unknown[0].title, "Unknown");
416 }
417
418 #[test]
419 fn a_meeting_takes_the_meeting_chat_title() {
420 let chats = [chat("19:meeting_x", "meeting", "Sprint retro", &[])];
421 let meeting = CallLogEntry {
422 is_meeting: true,
423 thread_id: Some("19:meeting_x".into()),
424 ..entry(CallDirection::Incoming, CallOutcome::Accepted, Some(60))
425 };
426 let list = rows(std::slice::from_ref(&meeting), &chats);
427 assert_eq!(list[0].title, "Sprint retro");
428 assert_eq!(list[0].thread_id.as_deref(), Some("19:meeting_x"));
429 assert_eq!(list[0].user_id, None);
430 assert_eq!(rows(&[meeting], &[])[0].title, "Meeting");
431 }
432
433 #[test]
434 fn rows_carry_the_chat_list_time_label_and_the_missed_flag() {
435 let missed = entry(CallDirection::Incoming, CallOutcome::Missed, None);
436 let list = rows(&[missed], &[]);
437 assert_eq!(list[0].time_label, "08:00");
438 assert!(list[0].missed);
439 }
440
441 #[test]
442 fn the_demo_history_has_every_kind_of_row() {
443 let log = demo_call_log(Utc::now());
444 assert!(log.iter().any(CallLogEntry::missed));
445 assert!(
446 log.iter()
447 .any(|entry| entry.direction == CallDirection::Outgoing)
448 );
449 assert!(log.iter().any(|entry| entry.is_meeting));
450 assert!(
451 log.iter()
452 .any(|entry| entry.direction == CallDirection::Incoming
453 && entry.outcome == CallOutcome::Accepted
454 && !entry.is_meeting)
455 );
456 }
457}