BlueGit

ict rusty-teams

Files

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

history.rs

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