BlueGit

ict rusty-teams

Files

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

data.rs

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