BlueGit

ict rusty-teams

Files

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

data.rs

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