BlueGit

ict rusty-teams

Files

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

data.rs

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