BlueGit

ict rusty-teams

Files

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

history.rs

history.rs 14.6 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!("calls: history not loaded: {}", short_error(&error))),
241 Err(_) => {}
242 })
243 .detach();
244 }
245
246 pub fn refresh_call_history_after_call(&mut self, cx: &mut Context<Self>) {
247 cx.spawn(async move |this, cx| {
248 cx.background_executor()
249 .timer(REFRESH_DELAY_AFTER_CALL)
250 .await;
251 this.update(cx, |state, cx| state.refresh_call_history(cx))
252 .ok();
253 })
254 .detach();
255 }
256
257 fn one_on_one_chat_with(&self, user_id: &str) -> Option<String> {
258 self.sidebar
259 .chats
260 .iter()
261 .find(|chat| {
262 is_one_on_one(chat)
263 && chat
264 .members
265 .iter()
266 .any(|member| member.user_id.as_deref() == Some(user_id))
267 })
268 .map(|chat| chat.id.clone())
269 }
270
271 fn chat_of_call_row(&self, row: &CallRow) -> Option<String> {
272 match (&row.thread_id, &row.user_id) {
273 (Some(thread_id), _) => self
274 .sidebar
275 .chats
276 .iter()
277 .any(|chat| &chat.id == thread_id)
278 .then(|| thread_id.clone()),
279 (None, Some(user_id)) => self.one_on_one_chat_with(user_id),
280 (None, None) => None,
281 }
282 }
283
284 pub fn call_back_from_history(&mut self, row: &CallRow, cx: &mut Context<Self>) {
285 let Some(user_id) = row.user_id.as_deref() else {
286 return;
287 };
288 match self.one_on_one_chat_with(user_id) {
289 Some(chat_id) => self.start_chat_call(&chat_id, cx),
290 None => self.raise_notice(NO_CHAT_NOTICE.to_owned(), None, cx),
291 }
292 }
293
294 pub fn open_chat_of_call_row(&mut self, row: &CallRow, cx: &mut Context<Self>) {
295 let notice = if row.meeting {
296 NO_MEETING_CHAT_NOTICE
297 } else {
298 NO_CHAT_NOTICE
299 };
300 match self.chat_of_call_row(row) {
301 Some(chat_id) => self.select(Selection::Chat(chat_id), cx),
302 None => self.raise_notice(notice.to_owned(), None, cx),
303 }
304 }
305
306 pub fn activate_call_row(&mut self, row: &CallRow, cx: &mut Context<Self>) {
307 if row.meeting {
308 self.open_chat_of_call_row(row, cx);
309 } else {
310 self.call_back_from_history(row, cx);
311 }
312 }
313
314 pub fn can_open_chat_of_call_row(&self, row: &CallRow) -> bool {
315 self.chat_of_call_row(row).is_some()
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use chrono::TimeZone;
322 use store::MemberRecord;
323
324 use super::*;
325
326 fn entry(direction: CallDirection, outcome: CallOutcome, seconds: Option<i64>) -> CallLogEntry {
327 CallLogEntry {
328 call_id: "c".into(),
329 started_at: Utc.with_ymd_and_hms(2026, 10, 9, 8, 0, 0).unwrap(),
330 duration_seconds: seconds,
331 direction,
332 outcome,
333 is_meeting: false,
334 peer_id: Some("8:orgid:bea-id".into()),
335 peer_name: None,
336 thread_id: None,
337 }
338 }
339
340 fn chat(id: &str, kind: &str, title: &str, members: &[(&str, &str)]) -> ChatRecord {
341 ChatRecord {
342 id: id.into(),
343 kind: kind.into(),
344 title: title.into(),
345 members: members
346 .iter()
347 .map(|(user_id, name)| MemberRecord {
348 user_id: Some((*user_id).to_owned()),
349 display_name: (*name).to_owned(),
350 })
351 .collect(),
352 ..Default::default()
353 }
354 }
355
356 fn rows(entries: &[CallLogEntry], chats: &[ChatRecord]) -> Vec<CallRow> {
357 let now = Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap();
358 call_rows(entries, chats, now, FixedOffset::east_opt(0).unwrap())
359 }
360
361 #[test]
362 fn durations_show_seconds_only_for_short_calls() {
363 assert_eq!(duration_label(45), "45s");
364 assert_eq!(duration_label(252), "4m 12s");
365 assert_eq!(duration_label(240), "4m");
366 assert_eq!(duration_label(720), "12m");
367 assert_eq!(duration_label(2280), "38m");
368 assert_eq!(duration_label(3600), "1h");
369 assert_eq!(duration_label(3900), "1h 5m");
370 }
371
372 #[test]
373 fn sublines_follow_direction_and_outcome() {
374 let missed = entry(CallDirection::Incoming, CallOutcome::Missed, None);
375 assert_eq!(subline(&missed), "Missed call");
376 let outgoing = entry(CallDirection::Outgoing, CallOutcome::Accepted, Some(252));
377 assert_eq!(subline(&outgoing), "Outgoing \u{b7} 4m 12s");
378 let incoming = entry(CallDirection::Incoming, CallOutcome::Accepted, Some(720));
379 assert_eq!(subline(&incoming), "Incoming \u{b7} 12m");
380 let declined = entry(CallDirection::Incoming, CallOutcome::Declined, None);
381 assert_eq!(subline(&declined), "Declined call");
382 let unanswered = entry(CallDirection::Outgoing, CallOutcome::Missed, None);
383 assert_eq!(subline(&unanswered), "Outgoing");
384 let meeting = CallLogEntry {
385 is_meeting: true,
386 ..entry(CallDirection::Incoming, CallOutcome::Accepted, Some(2280))
387 };
388 assert_eq!(subline(&meeting), "Meeting \u{b7} 38m");
389 }
390
391 #[test]
392 fn a_missing_display_name_comes_from_the_chat_members() {
393 let chats = [chat("19:a", "oneOnOne", "", &[("bea-id", "Bea")])];
394 let list = rows(
395 &[entry(
396 CallDirection::Outgoing,
397 CallOutcome::Accepted,
398 Some(60),
399 )],
400 &chats,
401 );
402 assert_eq!(list[0].title, "Bea");
403 assert_eq!(list[0].user_id.as_deref(), Some("bea-id"));
404 let unknown = rows(
405 &[entry(
406 CallDirection::Outgoing,
407 CallOutcome::Accepted,
408 Some(60),
409 )],
410 &[],
411 );
412 assert_eq!(unknown[0].title, "Unknown");
413 }
414
415 #[test]
416 fn a_meeting_takes_the_meeting_chat_title() {
417 let chats = [chat("19:meeting_x", "meeting", "Sprint retro", &[])];
418 let meeting = CallLogEntry {
419 is_meeting: true,
420 thread_id: Some("19:meeting_x".into()),
421 ..entry(CallDirection::Incoming, CallOutcome::Accepted, Some(60))
422 };
423 let list = rows(std::slice::from_ref(&meeting), &chats);
424 assert_eq!(list[0].title, "Sprint retro");
425 assert_eq!(list[0].thread_id.as_deref(), Some("19:meeting_x"));
426 assert_eq!(list[0].user_id, None);
427 assert_eq!(rows(&[meeting], &[])[0].title, "Meeting");
428 }
429
430 #[test]
431 fn rows_carry_the_chat_list_time_label_and_the_missed_flag() {
432 let missed = entry(CallDirection::Incoming, CallOutcome::Missed, None);
433 let list = rows(&[missed], &[]);
434 assert_eq!(list[0].time_label, "08:00");
435 assert!(list[0].missed);
436 }
437
438 #[test]
439 fn the_demo_history_has_every_kind_of_row() {
440 let log = demo_call_log(Utc::now());
441 assert!(log.iter().any(CallLogEntry::missed));
442 assert!(
443 log.iter()
444 .any(|entry| entry.direction == CallDirection::Outgoing)
445 );
446 assert!(log.iter().any(|entry| entry.is_meeting));
447 assert!(
448 log.iter()
449 .any(|entry| entry.direction == CallDirection::Incoming
450 && entry.outcome == CallOutcome::Accepted
451 && !entry.is_meeting)
452 );
453 }
454}