BlueGit

ict rusty-teams

Files

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

data.rs

data.rs 34.3 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, MessageImportance, Store, is_bot_id};
8
9use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};
10use tokio::sync::oneshot;
11
12use crate::avatar_image::AvatarPhoto;
13use crate::backend::Engine;
14use crate::runtime;
15
16const FAVORITES_KIND_MARKER: &str = "favorite";
17const RECENT_KIND_MARKER: &str = "recent";
18const MEETING_KIND_MARKER: &str = "meeting";
19const MUTED_KIND_MARKER: &str = "muted";
20const PRESENCE_MAX_AGE: Duration = Duration::from_secs(60);
21const PUSHED_PRESENCE_MAX_AGE: Duration = Duration::from_secs(5 * 60);
22const MEMBER_FACE_LIMIT: usize = 2;
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Person {
26 pub user_id: String,
27 pub display_name: String,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum FolderKind {
32 Favorites,
33 UserCreated,
34 Recent,
35 Meeting,
36 Muted,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct FolderInfo {
41 pub id: String,
42 pub name: String,
43 pub kind: FolderKind,
44 pub expanded: Option<bool>,
45 pub conversation_ids: Vec<String>,
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum PresenceKind {
50 Available,
51 Busy,
52 DoNotDisturb,
53 Away,
54 OutOfOffice,
55 Offline,
56 Unknown,
57}
58
59impl PresenceKind {
60 pub fn label(self) -> &'static str {
61 match self {
62 PresenceKind::Available => "Available",
63 PresenceKind::Busy => "Busy",
64 PresenceKind::DoNotDisturb => "Do not disturb",
65 PresenceKind::Away => "Away",
66 PresenceKind::OutOfOffice => "Out of office",
67 PresenceKind::Offline => "Offline",
68 PresenceKind::Unknown => "",
69 }
70 }
71
72 fn code(self) -> &'static str {
73 match self {
74 PresenceKind::Available => "Available",
75 PresenceKind::Busy => "Busy",
76 PresenceKind::DoNotDisturb => "DoNotDisturb",
77 PresenceKind::Away => "Away",
78 PresenceKind::OutOfOffice => "OutOfOffice",
79 PresenceKind::Offline => "Offline",
80 PresenceKind::Unknown => "Unknown",
81 }
82 }
83
84 fn from_code(code: &str) -> PresenceKind {
85 match code {
86 "Available" => PresenceKind::Available,
87 "Busy" => PresenceKind::Busy,
88 "DoNotDisturb" => PresenceKind::DoNotDisturb,
89 "Away" => PresenceKind::Away,
90 "OutOfOffice" => PresenceKind::OutOfOffice,
91 "Offline" => PresenceKind::Offline,
92 _ => PresenceKind::Unknown,
93 }
94 }
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum Presence {
99 Live(PresenceKind),
100 Cached(PresenceKind),
101 Loading,
102}
103
104impl Presence {
105 pub fn kind(self) -> PresenceKind {
106 match self {
107 Presence::Live(kind) | Presence::Cached(kind) => kind,
108 Presence::Loading => PresenceKind::Unknown,
109 }
110 }
111}
112
113#[derive(Clone)]
114pub enum AvatarState {
115 Pending,
116 Missing,
117 Ready(Arc<AvatarPhoto>),
118 Icon(Arc<Image>),
119}
120
121#[derive(Debug, Clone)]
122pub struct ImageEntry {
123 pub path: PathBuf,
124 pub size: Option<(u32, u32)>,
125}
126
127#[derive(Default)]
128pub struct Directory {
129 pub me: Option<Person>,
130 pub folders: Vec<FolderInfo>,
131 pub section_settings: ChatSectionSettings,
132 pub pinned_channels: Vec<String>,
133 pub unread_counts: HashMap<String, u32>,
134 pub unread_importance: HashMap<String, MessageImportance>,
135 pub avatars: HashMap<String, AvatarState>,
136 pub presence: HashMap<String, (PresenceKind, Instant)>,
137 pub activity: HashMap<String, Activity>,
138 pub presence_cached: HashMap<String, PresenceKind>,
139 pub presence_requested: HashMap<String, Instant>,
140 pub presence_pending: HashSet<String>,
141 pub images: HashMap<String, ImageEntry>,
142 pub images_requested: HashSet<String>,
143 pub images_failed: HashMap<String, Instant>,
144 pub avatars_failed: HashMap<String, Instant>,
145}
146
147const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
148
149impl Directory {
150 pub fn avatar(&self, user_id: &str) -> Option<&AvatarState> {
151 self.avatars.get(user_id)
152 }
153
154 pub fn image(&self, key: &str) -> Option<&ImageEntry> {
155 self.images.get(key)
156 }
157
158 pub fn image_failed(&self, key: &str) -> bool {
159 self.images_failed.contains_key(key) && !self.images.contains_key(key)
160 }
161
162 pub fn mark_image_failed(&mut self, key: &str) {
163 self.images_failed.insert(key.to_owned(), Instant::now());
164 self.images_requested.remove(key);
165 }
166
167 pub fn set_image(&mut self, key: &str, path: &Path) {
168 let size = image::image_dimensions(path).ok();
169 self.images.insert(
170 key.to_owned(),
171 ImageEntry {
172 path: path.to_path_buf(),
173 size,
174 },
175 );
176 }
177
178 pub fn images_to_request(&mut self, keys: impl IntoIterator<Item = String>) -> Vec<String> {
179 keys.into_iter()
180 .filter(|key| {
181 let failed_recently = self
182 .images_failed
183 .get(key)
184 .is_some_and(|failed| failed.elapsed() < IMAGE_RETRY_AFTER);
185 !self.images.contains_key(key)
186 && !failed_recently
187 && self.images_requested.insert(key.clone())
188 })
189 .collect()
190 }
191
192 pub fn missing_avatars(&self, user_ids: impl IntoIterator<Item = String>) -> Vec<String> {
193 let mut seen = HashSet::new();
194 user_ids
195 .into_iter()
196 .filter(|user_id| {
197 let failed_recently = self
198 .avatars_failed
199 .get(user_id)
200 .is_some_and(|failed| failed.elapsed() < IMAGE_RETRY_AFTER);
201 !self.avatars.contains_key(user_id)
202 && !failed_recently
203 && seen.insert(user_id.clone())
204 })
205 .collect()
206 }
207
208 pub fn mark_avatar_failed(&mut self, user_id: &str) {
209 if matches!(self.avatars.get(user_id), Some(AvatarState::Pending)) {
210 self.avatars.remove(user_id);
211 self.avatars_failed
212 .insert(user_id.to_owned(), Instant::now());
213 }
214 }
215
216 pub fn mark_avatars_pending(&mut self, user_ids: &[String]) {
217 for user_id in user_ids {
218 self.avatars
219 .entry(user_id.clone())
220 .or_insert(AvatarState::Pending);
221 }
222 }
223
224 pub fn set_avatar(&mut self, user_id: &str, state: AvatarState) {
225 self.avatars.insert(user_id.to_owned(), state);
226 }
227
228 pub fn pending_avatars(&self) -> Vec<String> {
229 self.avatars
230 .iter()
231 .filter(|(_, state)| matches!(state, AvatarState::Pending))
232 .map(|(user_id, _)| user_id.clone())
233 .collect()
234 }
235
236 pub fn presence_of(&self, user_id: &str) -> Presence {
237 if let Some((kind, _)) = self.presence.get(user_id) {
238 return Presence::Live(*kind);
239 }
240 match self.presence_cached.get(user_id) {
241 Some(kind) => Presence::Cached(*kind),
242 None if self.presence_pending.contains(user_id) => Presence::Loading,
243 None => Presence::Live(PresenceKind::Unknown),
244 }
245 }
246
247 pub fn set_activity(&mut self, user_id: &str, activity: Option<Activity>) -> bool {
248 match activity {
249 Some(activity) => self.activity.insert(user_id.to_owned(), activity) != Some(activity),
250 None => self.activity.remove(user_id).is_some(),
251 }
252 }
253
254 pub fn status_label(&self, user_id: &str, presence: Presence) -> &'static str {
255 match self.activity.get(user_id) {
256 Some(activity) if matches!(presence, Presence::Live(_)) => activity_label(*activity),
257 _ => presence.kind().label(),
258 }
259 }
260
261 pub fn load_cached_presence(&mut self, store: &Store) {
262 self.presence_cached = store
263 .presences()
264 .unwrap_or_default()
265 .into_iter()
266 .map(|(user_id, code)| (user_id, PresenceKind::from_code(&code)))
267 .collect();
268 }
269
270 pub fn save_presence(&self, store: &Store, user_ids: &[String]) {
271 let rows: Vec<(String, String)> = user_ids
272 .iter()
273 .filter_map(|user_id| {
274 let (kind, _) = self.presence.get(user_id)?;
275 Some((user_id.clone(), kind.code().to_owned()))
276 })
277 .collect();
278 if !rows.is_empty() {
279 let _ = store.upsert_presences(&rows, chrono::Utc::now());
280 }
281 }
282
283 pub fn mark_presence_pending(&mut self, user_ids: &[String]) {
284 self.presence_pending.extend(user_ids.iter().cloned());
285 }
286
287 pub fn settle_presence(&mut self, user_ids: &[String]) {
288 for user_id in user_ids {
289 self.presence_pending.remove(user_id);
290 }
291 }
292
293 pub fn waiting_presence_ids(&self) -> Vec<String> {
294 self.presence_pending.iter().cloned().collect()
295 }
296
297 pub fn set_presence(&mut self, user_id: &str, kind: PresenceKind) -> bool {
298 self.presence
299 .insert(user_id.to_owned(), (kind, Instant::now()))
300 .is_none_or(|(previous, _)| previous != kind)
301 }
302
303 pub fn stale_presence(
304 &self,
305 user_ids: impl IntoIterator<Item = String>,
306 now: Instant,
307 pushed: bool,
308 ) -> Vec<String> {
309 let max_age = if pushed {
310 PUSHED_PRESENCE_MAX_AGE
311 } else {
312 PRESENCE_MAX_AGE
313 };
314 let mut seen = HashSet::new();
315 user_ids
316 .into_iter()
317 .filter(|user_id| {
318 let fresh = |at: &Instant| now.duration_since(*at) < max_age;
319 let known_fresh = self.presence.get(user_id).is_some_and(|(_, at)| fresh(at));
320 let asked_fresh = self.presence_requested.get(user_id).is_some_and(fresh);
321 !known_fresh && !asked_fresh && seen.insert(user_id.clone())
322 })
323 .collect()
324 }
325
326 pub fn requested_presence_ids(&self) -> Vec<String> {
327 self.presence_requested.keys().cloned().collect()
328 }
329
330 pub fn mark_presence_requested(&mut self, user_ids: &[String], now: Instant) {
331 for user_id in user_ids {
332 self.presence_requested.insert(user_id.clone(), now);
333 }
334 }
335
336 pub fn favorites(&self) -> Option<&FolderInfo> {
337 self.folders
338 .iter()
339 .find(|folder| folder.kind == FolderKind::Favorites)
340 }
341
342 pub fn folder_of(&self, conversation_id: &str) -> Option<&FolderInfo> {
343 self.folders.iter().find(|folder| {
344 folder
345 .conversation_ids
346 .iter()
347 .any(|id| id == conversation_id)
348 })
349 }
350
351 pub fn assign(&mut self, conversation_id: &str, folder_id: Option<&str>) {
352 self.place(conversation_id, folder_id, None);
353 }
354
355 pub fn place(&mut self, conversation_id: &str, folder_id: Option<&str>, index: Option<usize>) {
356 for folder in &mut self.folders {
357 folder.conversation_ids.retain(|id| id != conversation_id);
358 }
359 if let Some(folder) =
360 folder_id.and_then(|id| self.folders.iter_mut().find(|folder| folder.id == id))
361 {
362 let position = index.map_or(folder.conversation_ids.len(), |index| {
363 index.min(folder.conversation_ids.len())
364 });
365 folder
366 .conversation_ids
367 .insert(position, conversation_id.to_owned());
368 }
369 }
370
371 pub fn slot_of(&self, folder_id: &str, conversation_id: &str) -> Option<usize> {
372 self.folders
373 .iter()
374 .find(|folder| folder.id == folder_id)?
375 .conversation_ids
376 .iter()
377 .position(|id| id == conversation_id)
378 }
379
380 pub fn move_targets(&self) -> Vec<(String, String)> {
381 let favorites = self.favorites().map(|folder| {
382 let name = folder.name.trim();
383 let name = if name.is_empty() {
384 crate::sidebar_model::FAVORITES_FALLBACK_NAME
385 } else {
386 name
387 };
388 (folder.id.clone(), name.to_owned())
389 });
390 favorites
391 .into_iter()
392 .chain(
393 self.folders
394 .iter()
395 .filter(|folder| {
396 folder.kind == FolderKind::UserCreated && !is_pending_folder(&folder.id)
397 })
398 .map(|folder| (folder.id.clone(), folder.name.clone())),
399 )
400 .collect()
401 }
402
403 pub fn apply_folder_change(&mut self, change: &FolderChange, created_id: &str) {
404 let position =
405 |folders: &[FolderInfo], id: &str| folders.iter().position(|folder| folder.id == id);
406 match change {
407 FolderChange::Create { name } => {
408 let index = position(&self.folders, created_id).unwrap_or_else(|| {
409 self.folders
410 .iter()
411 .position(|folder| folder.kind == FolderKind::Recent)
412 .unwrap_or(0)
413 });
414 self.folders.retain(|folder| folder.id != created_id);
415 self.folders.insert(
416 index.min(self.folders.len()),
417 FolderInfo {
418 id: created_id.to_owned(),
419 name: name.clone(),
420 kind: FolderKind::UserCreated,
421 expanded: None,
422 conversation_ids: Vec::new(),
423 },
424 );
425 }
426 FolderChange::Rename { folder_id, name } => {
427 if let Some(index) = position(&self.folders, folder_id) {
428 self.folders[index].name = name.clone();
429 }
430 }
431 FolderChange::Delete { folder_id } => {
432 self.folders.retain(|folder| folder.id != *folder_id)
433 }
434 FolderChange::Move {
435 folder_id,
436 target_folder_id,
437 } => {
438 if let (Some(source), Some(target)) = (
439 position(&self.folders, folder_id),
440 position(&self.folders, target_folder_id),
441 ) {
442 let moved = self.folders.remove(source);
443 self.folders.insert(target, moved);
444 }
445 }
446 }
447 }
448}
449
450pub const PENDING_FOLDER_PREFIX: &str = "pending-section:";
451
452pub fn is_pending_folder(folder_id: &str) -> bool {
453 folder_id.starts_with(PENDING_FOLDER_PREFIX)
454}
455
456pub fn image_format(content_type: &str) -> ImageFormat {
457 let lowered = content_type.to_ascii_lowercase();
458 if lowered.contains("png") {
459 ImageFormat::Png
460 } else if lowered.contains("webp") {
461 ImageFormat::Webp
462 } else if lowered.contains("gif") {
463 ImageFormat::Gif
464 } else if lowered.contains("svg") {
465 ImageFormat::Svg
466 } else {
467 ImageFormat::Jpeg
468 }
469}
470
471pub fn is_one_on_one(chat: &ChatRecord) -> bool {
472 chat.kind.eq_ignore_ascii_case("oneOnOne")
473}
474
475pub fn others(chat: &ChatRecord, me: Option<&Person>) -> Vec<(Option<String>, String)> {
476 let notes = is_notes_chat(&chat.id);
477 chat.members
478 .iter()
479 .filter(|member| {
480 notes
481 || match (&member.user_id, me) {
482 (Some(user_id), Some(me)) => *user_id != me.user_id,
483 _ => true,
484 }
485 })
486 .map(|member| (member.user_id.clone(), member.display_name.clone()))
487 .collect()
488}
489
490pub fn one_on_one_bot(chat: &ChatRecord, me: Option<&Person>) -> Option<(Option<String>, String)> {
491 if !is_one_on_one(chat) {
492 return None;
493 }
494 match others(chat, me).as_slice() {
495 [(Some(user_id), name)] if is_bot_id(user_id) => {
496 Some((Some(user_id.clone()), name.clone()))
497 }
498 _ => None,
499 }
500}
501
502pub fn existing_one_on_one<'chats>(
503 chats: &'chats [ChatRecord],
504 me: Option<&Person>,
505 user_id: &str,
506) -> Option<&'chats ChatRecord> {
507 chats.iter().find(|chat| {
508 is_one_on_one(chat)
509 && others(chat, me)
510 .iter()
511 .any(|(member_id, _)| member_id.as_deref() == Some(user_id))
512 })
513}
514
515pub fn face_members(chat: &ChatRecord, me: Option<&Person>) -> Vec<(Option<String>, String)> {
516 others(chat, me)
517 .into_iter()
518 .take(MEMBER_FACE_LIMIT)
519 .collect()
520}
521
522pub fn me(store: &Store) -> Option<Person> {
523 let user_id = store.meta("me_user_id").ok().flatten()?;
524 let display_name = store
525 .meta("me_display_name")
526 .ok()
527 .flatten()
528 .unwrap_or_default();
529 Some(Person {
530 user_id,
531 display_name,
532 })
533}
534
535fn folder_kind(kind: &str) -> FolderKind {
536 let lowered = kind.to_ascii_lowercase();
537 if lowered.contains(FAVORITES_KIND_MARKER) {
538 FolderKind::Favorites
539 } else if lowered.contains(RECENT_KIND_MARKER) {
540 FolderKind::Recent
541 } else if lowered.contains(MEETING_KIND_MARKER) {
542 FolderKind::Meeting
543 } else if lowered.contains(MUTED_KIND_MARKER) {
544 FolderKind::Muted
545 } else {
546 FolderKind::UserCreated
547 }
548}
549
550pub fn folders(store: &Store, pinned_ids: &[String]) -> Vec<FolderInfo> {
551 let stored: Vec<FolderInfo> = store
552 .folders()
553 .unwrap_or_default()
554 .into_iter()
555 .map(|record| FolderInfo {
556 kind: folder_kind(&record.kind),
557 expanded: Some(record.expanded),
558 id: record.id,
559 name: record.name,
560 conversation_ids: record.conversation_ids,
561 })
562 .collect();
563 if !stored.is_empty() {
564 return stored;
565 }
566 vec![FolderInfo {
567 id: "favorites".to_owned(),
568 name: String::new(),
569 kind: FolderKind::Favorites,
570 expanded: None,
571 conversation_ids: pinned_ids.to_vec(),
572 }]
573}
574
575pub fn pinned_channels(store: &Store) -> Vec<String> {
576 store.pinned_channel_ids().unwrap_or_default()
577}
578
579pub fn cached_avatar(store: &Store, user_id: &str) -> Option<AvatarState> {
580 let record = store.avatar(user_id).ok().flatten()?;
581 Some(match record.bytes {
582 Some(bytes) => avatar_state_from(&record.content_type, bytes, is_bot_id(user_id)),
583 None => AvatarState::Missing,
584 })
585}
586
587pub fn avatar_state_from(content_type: &str, bytes: Vec<u8>, is_bot: bool) -> AvatarState {
588 if image_format(content_type) == ImageFormat::Svg {
589 if is_bot {
590 return AvatarState::Icon(Arc::new(Image::from_bytes(ImageFormat::Svg, bytes)));
591 }
592 return AvatarState::Missing;
593 }
594 match AvatarPhoto::from_bytes(bytes) {
595 Some(photo) => AvatarState::Ready(Arc::new(photo)),
596 None => AvatarState::Missing,
597 }
598}
599
600pub fn unread_count(directory: &Directory, chat: &ChatRecord) -> Option<u32> {
601 directory.unread_counts.get(&chat.id).copied()
602}
603
604pub fn unread_counts(engine: &Engine, chats: &[ChatRecord]) -> HashMap<String, u32> {
605 chats
606 .iter()
607 .filter(|chat| chat.unread)
608 .map(|chat| (chat.id.clone(), engine.unread_count(&chat.id)))
609 .collect()
610}
611
612pub fn unread_importance_of(directory: &Directory, chat: &ChatRecord) -> MessageImportance {
613 directory
614 .unread_importance
615 .get(&chat.id)
616 .copied()
617 .unwrap_or_default()
618}
619
620pub fn unread_importance(
621 engine: &Engine,
622 chats: &[ChatRecord],
623) -> HashMap<String, MessageImportance> {
624 chats
625 .iter()
626 .filter(|chat| chat.unread)
627 .map(|chat| (chat.id.clone(), engine.unread_importance(&chat.id)))
628 .filter(|(_, importance)| importance.is_marked())
629 .collect()
630}
631
632pub fn presence_kind_of(availability: Availability) -> PresenceKind {
633 match availability {
634 Availability::Available => PresenceKind::Available,
635 Availability::Busy => PresenceKind::Busy,
636 Availability::DoNotDisturb => PresenceKind::DoNotDisturb,
637 Availability::Away => PresenceKind::Away,
638 Availability::Offline => PresenceKind::Offline,
639 Availability::Unknown => PresenceKind::Unknown,
640 }
641}
642
643pub fn shown_presence(availability: Availability, activity: Option<Activity>) -> PresenceKind {
644 match activity {
645 Some(Activity::OutOfOffice) => PresenceKind::OutOfOffice,
646 _ => presence_kind_of(availability),
647 }
648}
649
650pub fn activity_label(activity: Activity) -> &'static str {
651 match activity {
652 Activity::InACall => "In a call",
653 Activity::InAConferenceCall | Activity::InAMeeting => "In a meeting",
654 Activity::Presenting => "Presenting",
655 Activity::OutOfOffice => "Out of office",
656 }
657}
658
659pub fn presence_activity(engine: &Engine, user_id: &str) -> Option<Activity> {
660 engine
661 .presence(user_id)
662 .and_then(|presence| presence.activity)
663}
664
665pub fn presence_kind(engine: &Engine, user_id: &str) -> Option<PresenceKind> {
666 engine
667 .presence(user_id)
668 .map(|presence| shown_presence(presence.availability, presence.activity))
669}
670
671pub fn in_call(engine: &Engine, user_id: &str) -> bool {
672 engine
673 .presence(user_id)
674 .is_some_and(|presence| presence.in_call())
675}
676
677pub type Done = oneshot::Receiver<Result<(), String>>;
678
679fn run<F>(future: F) -> Done
680where
681 F: std::future::Future<Output = teams_core::Result<()>> + Send + 'static,
682{
683 runtime::spawn(async move { future.await.map_err(|error| error.to_string()) })
684}
685
686pub fn fetch_image(engine: &Arc<Engine>, image: teams_core::ImageRef) -> Done {
687 let engine = engine.clone();
688 run(async move { engine.fetch_image(&image).await.map(|_| ()) })
689}
690
691pub fn fetch_avatars(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
692 let engine = engine.clone();
693 run(async move { engine.fetch_avatars(&user_ids).await })
694}
695
696pub fn refresh_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
697 let engine = engine.clone();
698 run(async move { engine.refresh_presence(&user_ids).await })
699}
700
701pub fn watch_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
702 let engine = engine.clone();
703 run(async move { engine.watch_presence(&user_ids).await })
704}
705
706pub fn move_to_folder(
707 engine: &Arc<Engine>,
708 conversation_id: &str,
709 folder_id: &str,
710 index: Option<usize>,
711) -> Done {
712 let (engine, conversation_id, folder_id) = (
713 engine.clone(),
714 conversation_id.to_owned(),
715 folder_id.to_owned(),
716 );
717 run(async move {
718 engine
719 .move_to_folder(&conversation_id, &folder_id, index)
720 .await
721 })
722}
723
724pub fn remove_from_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
725 let (engine, conversation_id, folder_id) = (
726 engine.clone(),
727 conversation_id.to_owned(),
728 folder_id.to_owned(),
729 );
730 run(async move {
731 engine
732 .remove_from_folder(&conversation_id, &folder_id)
733 .await
734 })
735}
736
737#[cfg(test)]
738mod tests {
739 use super::*;
740
741 #[test]
742 fn out_of_office_shows_over_the_availability() {
743 assert_eq!(
744 shown_presence(Availability::Offline, Some(Activity::OutOfOffice)),
745 PresenceKind::OutOfOffice
746 );
747 assert_eq!(
748 shown_presence(Availability::Available, Some(Activity::InAMeeting)),
749 PresenceKind::Available
750 );
751 }
752
753 #[test]
754 fn activity_wording_replaces_availability_only_for_live_presence() {
755 let cases = [
756 (Activity::InACall, "In a call"),
757 (Activity::InAConferenceCall, "In a meeting"),
758 (Activity::InAMeeting, "In a meeting"),
759 (Activity::Presenting, "Presenting"),
760 (Activity::OutOfOffice, "Out of office"),
761 ];
762 for (activity, label) in cases {
763 let mut directory = Directory::default();
764 directory.set_activity("ada", Some(activity));
765 let live = Presence::Live(PresenceKind::Busy);
766 assert_eq!(directory.status_label("ada", live), label);
767 assert_eq!(
768 directory.status_label("ada", Presence::Cached(PresenceKind::Busy)),
769 "Busy"
770 );
771 assert_eq!(directory.status_label("bob", live), "Busy");
772 assert!(directory.set_activity("ada", None));
773 assert_eq!(directory.status_label("ada", live), "Busy");
774 }
775 }
776
777 fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo {
778 FolderInfo {
779 id: id.into(),
780 name: id.into(),
781 kind,
782 expanded: None,
783 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
784 }
785 }
786
787 #[test]
788 fn place_puts_a_chat_at_the_slot_inside_and_across_folders() {
789 let mut directory = Directory {
790 folders: vec![
791 folder("fav", FolderKind::Favorites, &["a", "b", "c"]),
792 folder("work", FolderKind::UserCreated, &["d"]),
793 ],
794 ..Default::default()
795 };
796 directory.place("a", Some("fav"), Some(2));
797 assert_eq!(directory.folders[0].conversation_ids, vec!["b", "c", "a"]);
798 directory.place("d", Some("fav"), Some(0));
799 assert_eq!(
800 directory.folders[0].conversation_ids,
801 vec!["d", "b", "c", "a"]
802 );
803 assert!(directory.folders[1].conversation_ids.is_empty());
804 directory.place("b", Some("work"), Some(9));
805 assert_eq!(directory.folders[1].conversation_ids, vec!["b"]);
806 assert_eq!(directory.slot_of("fav", "c"), Some(1));
807 assert_eq!(directory.slot_of("work", "c"), None);
808 }
809
810 #[test]
811 fn assign_moves_a_chat_between_folders() {
812 let mut directory = Directory {
813 folders: vec![
814 folder("fav", FolderKind::Favorites, &["a"]),
815 folder("work", FolderKind::UserCreated, &["b"]),
816 ],
817 ..Default::default()
818 };
819 directory.assign("a", Some("work"));
820 assert!(directory.favorites().unwrap().conversation_ids.is_empty());
821 assert_eq!(directory.folders[1].conversation_ids, vec!["b", "a"]);
822 directory.assign("a", None);
823 assert!(directory.folder_of("a").is_none());
824 }
825
826 #[test]
827 fn folder_changes_apply_locally_like_teams() {
828 let mut directory = Directory {
829 folders: vec![
830 folder("fav", FolderKind::Favorites, &["a"]),
831 folder("work", FolderKind::UserCreated, &["b"]),
832 folder("todo", FolderKind::UserCreated, &[]),
833 folder("recent", FolderKind::Recent, &[]),
834 ],
835 ..Default::default()
836 };
837 let order = |directory: &Directory| -> Vec<String> {
838 directory
839 .folders
840 .iter()
841 .map(|folder| folder.id.clone())
842 .collect()
843 };
844 let move_folder = |folder_id: &str, target_folder_id: &str| FolderChange::Move {
845 folder_id: folder_id.into(),
846 target_folder_id: target_folder_id.into(),
847 };
848 directory.apply_folder_change(&move_folder("todo", "work"), "");
849 assert_eq!(order(&directory), ["fav", "todo", "work", "recent"]);
850 directory.apply_folder_change(&move_folder("fav", "todo"), "");
851 assert_eq!(order(&directory), ["todo", "fav", "work", "recent"]);
852 let rename = FolderChange::Rename {
853 folder_id: "work".into(),
854 name: "Job".into(),
855 };
856 directory.apply_folder_change(&rename, "");
857 assert_eq!(directory.folders[2].name, "Job");
858 let delete = FolderChange::Delete {
859 folder_id: "work".into(),
860 };
861 directory.apply_folder_change(&delete, "");
862 assert!(directory.folder_of("b").is_none());
863 }
864
865 #[test]
866 fn created_folder_lands_before_recent_and_keeps_its_place_when_reapplied() {
867 let mut directory = Directory {
868 folders: vec![
869 folder("fav", FolderKind::Favorites, &[]),
870 folder("recent", FolderKind::Recent, &[]),
871 folder("muted", FolderKind::Muted, &[]),
872 ],
873 ..Default::default()
874 };
875 let create = FolderChange::Create { name: "New".into() };
876 let pending_id = format!("{PENDING_FOLDER_PREFIX}1");
877 directory.apply_folder_change(&create, &pending_id);
878 directory.apply_folder_change(&create, &pending_id);
879 let ids: Vec<&str> = directory
880 .folders
881 .iter()
882 .map(|folder| folder.id.as_str())
883 .collect();
884 assert_eq!(ids, ["fav", pending_id.as_str(), "recent", "muted"]);
885 let mut bare = Directory::default();
886 bare.apply_folder_change(&create, "x");
887 assert_eq!(bare.folders[0].id, "x");
888 }
889
890 #[test]
891 fn favorites_come_first_and_pending_folders_are_no_move_targets() {
892 let directory = Directory {
893 folders: vec![
894 folder("fav", FolderKind::Favorites, &[]),
895 folder("work", FolderKind::UserCreated, &[]),
896 folder(
897 &format!("{PENDING_FOLDER_PREFIX}1"),
898 FolderKind::UserCreated,
899 &[],
900 ),
901 ],
902 ..Default::default()
903 };
904 assert_eq!(
905 directory.move_targets(),
906 [
907 ("fav".to_owned(), "fav".to_owned()),
908 ("work".to_owned(), "work".to_owned())
909 ]
910 );
911 }
912
913 #[test]
914 fn missing_avatars_skip_known_and_duplicates() {
915 let mut directory = Directory::default();
916 directory.set_avatar("known", AvatarState::Missing);
917 let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from));
918 assert_eq!(wanted, vec!["x", "y"]);
919 directory.mark_avatars_pending(&wanted);
920 assert!(directory.missing_avatars(["x".to_owned()]).is_empty());
921 assert_eq!(directory.pending_avatars().len(), 2);
922 }
923
924 #[test]
925 fn a_failed_avatar_is_requested_again_only_after_the_retry_delay() {
926 let mut directory = Directory::default();
927 directory.mark_avatars_pending(&["a".to_owned()]);
928 directory.mark_avatar_failed("a");
929 assert!(directory.pending_avatars().is_empty());
930 assert!(directory.missing_avatars(["a".to_owned()]).is_empty());
931 directory
932 .avatars_failed
933 .insert("a".to_owned(), Instant::now() - IMAGE_RETRY_AFTER);
934 assert_eq!(directory.missing_avatars(["a".to_owned()]), vec!["a"]);
935 }
936
937 #[test]
938 fn a_failed_image_is_requested_again_only_after_the_retry_delay() {
939 let mut directory = Directory::default();
940 assert_eq!(directory.images_to_request(["a".to_owned()]), vec!["a"]);
941 directory.mark_image_failed("a");
942 assert!(directory.images_to_request(["a".to_owned()]).is_empty());
943 directory
944 .images_failed
945 .insert("a".to_owned(), Instant::now() - IMAGE_RETRY_AFTER);
946 assert_eq!(directory.images_to_request(["a".to_owned()]), vec!["a"]);
947 }
948
949 #[test]
950 fn a_failed_image_is_only_failed_until_it_arrives() {
951 let mut directory = Directory::default();
952 assert!(!directory.image_failed("a"));
953 directory.mark_image_failed("a");
954 assert!(directory.image_failed("a"));
955 directory.set_image("a", Path::new("a.png"));
956 assert!(!directory.image_failed("a"));
957 }
958
959 #[test]
960 fn images_are_requested_once() {
961 let mut directory = Directory::default();
962 let wanted = directory.images_to_request(["a", "a", "b"].map(String::from));
963 assert_eq!(wanted, vec!["a", "b"]);
964 assert!(directory.images_to_request(["a".to_owned()]).is_empty());
965 }
966
967 #[test]
968 fn presence_is_refetched_after_the_max_age() {
969 let mut directory = Directory::default();
970 let start = Instant::now();
971 let wanted = directory.stale_presence(["u".to_owned()], start, false);
972 assert_eq!(wanted, vec!["u"]);
973 directory.mark_presence_requested(&wanted, start);
974 assert!(
975 directory
976 .stale_presence(["u".to_owned()], start, false)
977 .is_empty()
978 );
979 let later = start + PRESENCE_MAX_AGE + Duration::from_secs(1);
980 assert_eq!(
981 directory.stale_presence(["u".to_owned()], later, false),
982 vec!["u"]
983 );
984 assert!(
985 directory
986 .stale_presence(["u".to_owned()], later, true)
987 .is_empty()
988 );
989 let much_later = start + PUSHED_PRESENCE_MAX_AGE + Duration::from_secs(1);
990 assert_eq!(
991 directory.stale_presence(["u".to_owned()], much_later, true),
992 vec!["u"]
993 );
994 assert_eq!(directory.presence_of("u").kind(), PresenceKind::Unknown);
995 }
996
997 #[test]
998 fn presence_prefers_live_over_cached_over_loading() {
999 let mut directory = Directory::default();
1000 let ids = ["a".to_owned(), "b".to_owned(), "c".to_owned()];
1001 directory.mark_presence_pending(&ids);
1002 directory
1003 .presence_cached
1004 .insert("b".into(), PresenceKind::Away);
1005 directory
1006 .presence_cached
1007 .insert("c".into(), PresenceKind::Away);
1008 directory.set_presence("c", PresenceKind::Busy);
1009 assert_eq!(directory.presence_of("a"), Presence::Loading);
1010 assert_eq!(
1011 directory.presence_of("b"),
1012 Presence::Cached(PresenceKind::Away)
1013 );
1014 assert_eq!(
1015 directory.presence_of("c"),
1016 Presence::Live(PresenceKind::Busy)
1017 );
1018 directory.settle_presence(&ids);
1019 assert_eq!(
1020 directory.presence_of("a"),
1021 Presence::Live(PresenceKind::Unknown)
1022 );
1023 }
1024
1025 #[test]
1026 fn presence_survives_a_restart_through_the_store() {
1027 let store = Store::open_in_memory().unwrap();
1028 let mut directory = Directory::default();
1029 directory.set_presence("a", PresenceKind::DoNotDisturb);
1030 directory.save_presence(&store, &["a".to_owned(), "missing".to_owned()]);
1031 let mut restarted = Directory::default();
1032 restarted.load_cached_presence(&store);
1033 assert_eq!(
1034 restarted.presence_of("a"),
1035 Presence::Cached(PresenceKind::DoNotDisturb)
1036 );
1037 assert_eq!(
1038 restarted.presence_of("missing"),
1039 Presence::Live(PresenceKind::Unknown)
1040 );
1041 }
1042
1043 #[test]
1044 fn content_types_map_to_image_formats() {
1045 assert_eq!(image_format("image/png"), ImageFormat::Png);
1046 assert_eq!(image_format("image/jpeg"), ImageFormat::Jpeg);
1047 assert_eq!(image_format(""), ImageFormat::Jpeg);
1048 }
1049}