BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / data.rs

data.rs

data.rs 18.8 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use gpui_kit::{Image, ImageFormat};
7use store::{ChatRecord, Store};
8
9use teams_core::Availability;
10use tokio::sync::oneshot;
11
12use crate::backend::Engine;
13use crate::runtime;
14
15const FAVORITES_KIND_MARKER: &str = "favorite";
16const PRESENCE_MAX_AGE: Duration = Duration::from_secs(60);
17const PUSHED_PRESENCE_MAX_AGE: Duration = Duration::from_secs(5 * 60);
18const MEMBER_FACE_LIMIT: usize = 2;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Person {
22 pub user_id: String,
23 pub display_name: String,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum FolderKind {
28 Favorites,
29 UserCreated,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct FolderInfo {
34 pub id: String,
35 pub name: String,
36 pub kind: FolderKind,
37 pub conversation_ids: Vec<String>,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum PresenceKind {
42 Available,
43 Busy,
44 DoNotDisturb,
45 Away,
46 Offline,
47 Unknown,
48}
49
50impl PresenceKind {
51 pub fn label(self) -> &'static str {
52 match self {
53 PresenceKind::Available => "Available",
54 PresenceKind::Busy => "Busy",
55 PresenceKind::DoNotDisturb => "Do not disturb",
56 PresenceKind::Away => "Away",
57 PresenceKind::Offline => "Offline",
58 PresenceKind::Unknown => "",
59 }
60 }
61
62 fn code(self) -> &'static str {
63 match self {
64 PresenceKind::Available => "Available",
65 PresenceKind::Busy => "Busy",
66 PresenceKind::DoNotDisturb => "DoNotDisturb",
67 PresenceKind::Away => "Away",
68 PresenceKind::Offline => "Offline",
69 PresenceKind::Unknown => "Unknown",
70 }
71 }
72
73 fn from_code(code: &str) -> PresenceKind {
74 match code {
75 "Available" => PresenceKind::Available,
76 "Busy" => PresenceKind::Busy,
77 "DoNotDisturb" => PresenceKind::DoNotDisturb,
78 "Away" => PresenceKind::Away,
79 "Offline" => PresenceKind::Offline,
80 _ => PresenceKind::Unknown,
81 }
82 }
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum Presence {
87 Live(PresenceKind),
88 Cached(PresenceKind),
89 Loading,
90}
91
92impl Presence {
93 pub fn kind(self) -> PresenceKind {
94 match self {
95 Presence::Live(kind) | Presence::Cached(kind) => kind,
96 Presence::Loading => PresenceKind::Unknown,
97 }
98 }
99}
100
101#[derive(Clone)]
102pub enum AvatarState {
103 Pending,
104 Missing,
105 Ready(Arc<Image>),
106}
107
108#[derive(Debug, Clone)]
109pub struct ImageEntry {
110 pub path: PathBuf,
111 pub size: Option<(u32, u32)>,
112}
113
114#[derive(Default)]
115pub struct Directory {
116 pub me: Option<Person>,
117 pub folders: Vec<FolderInfo>,
118 pub pinned_channels: Vec<String>,
119 pub unread_counts: HashMap<String, u32>,
120 pub(crate) avatars: HashMap<String, AvatarState>,
121 pub(crate) presence: HashMap<String, (PresenceKind, Instant)>,
122 pub(crate) presence_cached: HashMap<String, PresenceKind>,
123 pub(crate) presence_requested: HashMap<String, Instant>,
124 pub(crate) presence_pending: HashSet<String>,
125 pub(crate) images: HashMap<String, ImageEntry>,
126 pub(crate) images_requested: HashSet<String>,
127}
128
129impl Directory {
130 pub fn avatar(&self, user_id: &str) -> Option<&AvatarState> {
131 self.avatars.get(user_id)
132 }
133
134 pub fn image(&self, key: &str) -> Option<&ImageEntry> {
135 self.images.get(key)
136 }
137
138 pub fn set_image(&mut self, key: &str, path: &Path) {
139 let size = image::image_dimensions(path).ok();
140 self.images.insert(
141 key.to_owned(),
142 ImageEntry {
143 path: path.to_path_buf(),
144 size,
145 },
146 );
147 }
148
149 pub fn images_to_request(&mut self, keys: impl IntoIterator<Item = String>) -> Vec<String> {
150 keys.into_iter()
151 .filter(|key| {
152 !self.images.contains_key(key) && self.images_requested.insert(key.clone())
153 })
154 .collect()
155 }
156
157 pub fn missing_avatars(&self, user_ids: impl IntoIterator<Item = String>) -> Vec<String> {
158 let mut seen = HashSet::new();
159 user_ids
160 .into_iter()
161 .filter(|user_id| !self.avatars.contains_key(user_id) && seen.insert(user_id.clone()))
162 .collect()
163 }
164
165 pub fn mark_avatars_pending(&mut self, user_ids: &[String]) {
166 for user_id in user_ids {
167 self.avatars
168 .entry(user_id.clone())
169 .or_insert(AvatarState::Pending);
170 }
171 }
172
173 pub fn set_avatar(&mut self, user_id: &str, image: Option<Arc<Image>>) {
174 let state = image.map_or(AvatarState::Missing, AvatarState::Ready);
175 self.avatars.insert(user_id.to_owned(), state);
176 }
177
178 pub fn pending_avatars(&self) -> Vec<String> {
179 self.avatars
180 .iter()
181 .filter(|(_, state)| matches!(state, AvatarState::Pending))
182 .map(|(user_id, _)| user_id.clone())
183 .collect()
184 }
185
186 pub fn presence_of(&self, user_id: &str) -> Presence {
187 if let Some((kind, _)) = self.presence.get(user_id) {
188 return Presence::Live(*kind);
189 }
190 match self.presence_cached.get(user_id) {
191 Some(kind) => Presence::Cached(*kind),
192 None if self.presence_pending.contains(user_id) => Presence::Loading,
193 None => Presence::Live(PresenceKind::Unknown),
194 }
195 }
196
197 pub fn load_cached_presence(&mut self, store: &Store) {
198 self.presence_cached = store
199 .presences()
200 .unwrap_or_default()
201 .into_iter()
202 .map(|(user_id, code)| (user_id, PresenceKind::from_code(&code)))
203 .collect();
204 }
205
206 pub fn save_presence(&self, store: &Store, user_ids: &[String]) {
207 let rows: Vec<(String, String)> = user_ids
208 .iter()
209 .filter_map(|user_id| {
210 let (kind, _) = self.presence.get(user_id)?;
211 Some((user_id.clone(), kind.code().to_owned()))
212 })
213 .collect();
214 if !rows.is_empty() {
215 let _ = store.upsert_presences(&rows, chrono::Utc::now());
216 }
217 }
218
219 pub fn mark_presence_pending(&mut self, user_ids: &[String]) {
220 self.presence_pending.extend(user_ids.iter().cloned());
221 }
222
223 pub fn settle_presence(&mut self, user_ids: &[String]) {
224 for user_id in user_ids {
225 self.presence_pending.remove(user_id);
226 }
227 }
228
229 pub fn waiting_presence_ids(&self) -> Vec<String> {
230 self.presence_pending.iter().cloned().collect()
231 }
232
233 pub fn set_presence(&mut self, user_id: &str, kind: PresenceKind) -> bool {
234 self.presence
235 .insert(user_id.to_owned(), (kind, Instant::now()))
236 .is_none_or(|(previous, _)| previous != kind)
237 }
238
239 pub fn stale_presence(
240 &self,
241 user_ids: impl IntoIterator<Item = String>,
242 now: Instant,
243 pushed: bool,
244 ) -> Vec<String> {
245 let max_age = if pushed {
246 PUSHED_PRESENCE_MAX_AGE
247 } else {
248 PRESENCE_MAX_AGE
249 };
250 let mut seen = HashSet::new();
251 user_ids
252 .into_iter()
253 .filter(|user_id| {
254 let fresh = |at: &Instant| now.duration_since(*at) < max_age;
255 let known_fresh = self.presence.get(user_id).is_some_and(|(_, at)| fresh(at));
256 let asked_fresh = self.presence_requested.get(user_id).is_some_and(fresh);
257 !known_fresh && !asked_fresh && seen.insert(user_id.clone())
258 })
259 .collect()
260 }
261
262 pub fn requested_presence_ids(&self) -> Vec<String> {
263 self.presence_requested.keys().cloned().collect()
264 }
265
266 pub fn mark_presence_requested(&mut self, user_ids: &[String], now: Instant) {
267 for user_id in user_ids {
268 self.presence_requested.insert(user_id.clone(), now);
269 }
270 }
271
272 pub fn favorites(&self) -> Option<&FolderInfo> {
273 self.folders
274 .iter()
275 .find(|folder| folder.kind == FolderKind::Favorites)
276 }
277
278 pub fn folder_of(&self, conversation_id: &str) -> Option<&FolderInfo> {
279 self.folders.iter().find(|folder| {
280 folder
281 .conversation_ids
282 .iter()
283 .any(|id| id == conversation_id)
284 })
285 }
286
287 pub fn assign(&mut self, conversation_id: &str, folder_id: Option<&str>) {
288 for folder in &mut self.folders {
289 folder.conversation_ids.retain(|id| id != conversation_id);
290 }
291 if let Some(folder) =
292 folder_id.and_then(|id| self.folders.iter_mut().find(|folder| folder.id == id))
293 {
294 folder.conversation_ids.push(conversation_id.to_owned());
295 }
296 }
297}
298
299pub fn image_format(content_type: &str) -> ImageFormat {
300 let lowered = content_type.to_ascii_lowercase();
301 if lowered.contains("png") {
302 ImageFormat::Png
303 } else if lowered.contains("webp") {
304 ImageFormat::Webp
305 } else if lowered.contains("gif") {
306 ImageFormat::Gif
307 } else if lowered.contains("svg") {
308 ImageFormat::Svg
309 } else {
310 ImageFormat::Jpeg
311 }
312}
313
314pub fn is_one_on_one(chat: &ChatRecord) -> bool {
315 chat.kind.eq_ignore_ascii_case("oneOnOne")
316}
317
318pub fn others(chat: &ChatRecord, me: Option<&Person>) -> Vec<(Option<String>, String)> {
319 chat.members
320 .iter()
321 .filter(|member| match (&member.user_id, me) {
322 (Some(user_id), Some(me)) => *user_id != me.user_id,
323 _ => true,
324 })
325 .map(|member| (member.user_id.clone(), member.display_name.clone()))
326 .collect()
327}
328
329pub fn face_members(chat: &ChatRecord, me: Option<&Person>) -> Vec<(Option<String>, String)> {
330 others(chat, me)
331 .into_iter()
332 .take(MEMBER_FACE_LIMIT)
333 .collect()
334}
335
336pub fn me(store: &Store) -> Option<Person> {
337 let user_id = store.meta("me_user_id").ok().flatten()?;
338 let display_name = store
339 .meta("me_display_name")
340 .ok()
341 .flatten()
342 .unwrap_or_default();
343 Some(Person {
344 user_id,
345 display_name,
346 })
347}
348
349pub fn folders(store: &Store, pinned_ids: &[String]) -> Vec<FolderInfo> {
350 let stored: Vec<FolderInfo> = store
351 .folders()
352 .unwrap_or_default()
353 .into_iter()
354 .map(|record| FolderInfo {
355 kind: if record
356 .kind
357 .to_ascii_lowercase()
358 .contains(FAVORITES_KIND_MARKER)
359 {
360 FolderKind::Favorites
361 } else {
362 FolderKind::UserCreated
363 },
364 id: record.id,
365 name: record.name,
366 conversation_ids: record.conversation_ids,
367 })
368 .collect();
369 if !stored.is_empty() {
370 return stored;
371 }
372 vec![FolderInfo {
373 id: "favorites".to_owned(),
374 name: String::new(),
375 kind: FolderKind::Favorites,
376 conversation_ids: pinned_ids.to_vec(),
377 }]
378}
379
380pub fn pinned_channels(store: &Store) -> Vec<String> {
381 store.pinned_channel_ids().unwrap_or_default()
382}
383
384pub fn cached_avatar(store: &Store, user_id: &str) -> Option<Option<Arc<Image>>> {
385 let record = store.avatar(user_id).ok().flatten()?;
386 Some(
387 record
388 .bytes
389 .map(|bytes| avatar_image_from(&record.content_type, bytes)),
390 )
391}
392
393pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {
394 match crate::avatar_image::circular_png(&bytes) {
395 Some(masked) => Arc::new(Image::from_bytes(ImageFormat::Png, masked)),
396 None => Arc::new(Image::from_bytes(image_format(content_type), bytes)),
397 }
398}
399
400pub fn unread_count(directory: &Directory, chat: &ChatRecord) -> Option<u32> {
401 directory.unread_counts.get(&chat.id).copied()
402}
403
404pub fn unread_counts(engine: &Engine, chats: &[ChatRecord]) -> HashMap<String, u32> {
405 chats
406 .iter()
407 .filter(|chat| chat.unread)
408 .map(|chat| (chat.id.clone(), engine.unread_count(&chat.id)))
409 .collect()
410}
411
412pub fn presence_kind(engine: &Engine, user_id: &str) -> Option<PresenceKind> {
413 engine
414 .presence(user_id)
415 .map(|presence| match presence.availability {
416 Availability::Available => PresenceKind::Available,
417 Availability::Busy => PresenceKind::Busy,
418 Availability::DoNotDisturb => PresenceKind::DoNotDisturb,
419 Availability::Away => PresenceKind::Away,
420 Availability::Offline => PresenceKind::Offline,
421 Availability::Unknown => PresenceKind::Unknown,
422 })
423}
424
425pub fn in_call(engine: &Engine, user_id: &str) -> bool {
426 engine
427 .presence(user_id)
428 .is_some_and(|presence| presence.in_call)
429}
430
431pub type Done = oneshot::Receiver<Result<(), String>>;
432
433fn run<F>(future: F) -> Done
434where
435 F: std::future::Future<Output = teams_core::Result<()>> + Send + 'static,
436{
437 runtime::spawn(async move { future.await.map_err(|error| error.to_string()) })
438}
439
440pub fn fetch_image(engine: &Arc<Engine>, image: teams_core::ImageRef) -> Done {
441 let engine = engine.clone();
442 run(async move { engine.fetch_image(&image).await.map(|_| ()) })
443}
444
445pub fn fetch_avatars(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
446 let engine = engine.clone();
447 run(async move { engine.fetch_avatars(&user_ids).await })
448}
449
450pub fn refresh_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
451 let engine = engine.clone();
452 run(async move { engine.refresh_presence(&user_ids).await })
453}
454
455pub fn watch_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
456 let engine = engine.clone();
457 run(async move { engine.watch_presence(&user_ids).await })
458}
459
460pub fn move_to_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
461 let (engine, conversation_id, folder_id) = (
462 engine.clone(),
463 conversation_id.to_owned(),
464 folder_id.to_owned(),
465 );
466 run(async move { engine.move_to_folder(&conversation_id, &folder_id).await })
467}
468
469pub fn remove_from_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
470 let (engine, conversation_id, folder_id) = (
471 engine.clone(),
472 conversation_id.to_owned(),
473 folder_id.to_owned(),
474 );
475 run(async move {
476 engine
477 .remove_from_folder(&conversation_id, &folder_id)
478 .await
479 })
480}
481
482#[cfg(test)]
483mod tests {
484 use super::*;
485
486 fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo {
487 FolderInfo {
488 id: id.into(),
489 name: id.into(),
490 kind,
491 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
492 }
493 }
494
495 #[test]
496 fn assign_moves_a_chat_between_folders() {
497 let mut directory = Directory {
498 folders: vec![
499 folder("fav", FolderKind::Favorites, &["a"]),
500 folder("work", FolderKind::UserCreated, &["b"]),
501 ],
502 ..Default::default()
503 };
504 directory.assign("a", Some("work"));
505 assert!(directory.favorites().unwrap().conversation_ids.is_empty());
506 assert_eq!(directory.folders[1].conversation_ids, vec!["b", "a"]);
507 directory.assign("a", None);
508 assert!(directory.folder_of("a").is_none());
509 }
510
511 #[test]
512 fn missing_avatars_skip_known_and_duplicates() {
513 let mut directory = Directory::default();
514 directory.set_avatar("known", None);
515 let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from));
516 assert_eq!(wanted, vec!["x", "y"]);
517 directory.mark_avatars_pending(&wanted);
518 assert!(directory.missing_avatars(["x".to_owned()]).is_empty());
519 assert_eq!(directory.pending_avatars().len(), 2);
520 }
521
522 #[test]
523 fn images_are_requested_once() {
524 let mut directory = Directory::default();
525 let wanted = directory.images_to_request(["a", "a", "b"].map(String::from));
526 assert_eq!(wanted, vec!["a", "b"]);
527 assert!(directory.images_to_request(["a".to_owned()]).is_empty());
528 }
529
530 #[test]
531 fn presence_is_refetched_after_the_max_age() {
532 let mut directory = Directory::default();
533 let start = Instant::now();
534 let wanted = directory.stale_presence(["u".to_owned()], start, false);
535 assert_eq!(wanted, vec!["u"]);
536 directory.mark_presence_requested(&wanted, start);
537 assert!(
538 directory
539 .stale_presence(["u".to_owned()], start, false)
540 .is_empty()
541 );
542 let later = start + PRESENCE_MAX_AGE + Duration::from_secs(1);
543 assert_eq!(
544 directory.stale_presence(["u".to_owned()], later, false),
545 vec!["u"]
546 );
547 assert!(
548 directory
549 .stale_presence(["u".to_owned()], later, true)
550 .is_empty()
551 );
552 let much_later = start + PUSHED_PRESENCE_MAX_AGE + Duration::from_secs(1);
553 assert_eq!(
554 directory.stale_presence(["u".to_owned()], much_later, true),
555 vec!["u"]
556 );
557 assert_eq!(directory.presence_of("u").kind(), PresenceKind::Unknown);
558 }
559
560 #[test]
561 fn presence_prefers_live_over_cached_over_loading() {
562 let mut directory = Directory::default();
563 let ids = ["a".to_owned(), "b".to_owned(), "c".to_owned()];
564 directory.mark_presence_pending(&ids);
565 directory
566 .presence_cached
567 .insert("b".into(), PresenceKind::Away);
568 directory
569 .presence_cached
570 .insert("c".into(), PresenceKind::Away);
571 directory.set_presence("c", PresenceKind::Busy);
572 assert_eq!(directory.presence_of("a"), Presence::Loading);
573 assert_eq!(
574 directory.presence_of("b"),
575 Presence::Cached(PresenceKind::Away)
576 );
577 assert_eq!(
578 directory.presence_of("c"),
579 Presence::Live(PresenceKind::Busy)
580 );
581 directory.settle_presence(&ids);
582 assert_eq!(
583 directory.presence_of("a"),
584 Presence::Live(PresenceKind::Unknown)
585 );
586 }
587
588 #[test]
589 fn presence_survives_a_restart_through_the_store() {
590 let store = Store::open_in_memory().unwrap();
591 let mut directory = Directory::default();
592 directory.set_presence("a", PresenceKind::DoNotDisturb);
593 directory.save_presence(&store, &["a".to_owned(), "missing".to_owned()]);
594 let mut restarted = Directory::default();
595 restarted.load_cached_presence(&store);
596 assert_eq!(
597 restarted.presence_of("a"),
598 Presence::Cached(PresenceKind::DoNotDisturb)
599 );
600 assert_eq!(
601 restarted.presence_of("missing"),
602 Presence::Live(PresenceKind::Unknown)
603 );
604 }
605
606 #[test]
607 fn content_types_map_to_image_formats() {
608 assert_eq!(image_format("image/png"), ImageFormat::Png);
609 assert_eq!(image_format("image/jpeg"), ImageFormat::Jpeg);
610 assert_eq!(image_format(""), ImageFormat::Jpeg);
611 }
612}