BlueGit

ict rusty-teams

Files

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

data.rs

data.rs 29.4 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(crate) avatars: HashMap<String, AvatarState>,
133 pub(crate) presence: HashMap<String, (PresenceKind, Instant)>,
134 pub(crate) activity: HashMap<String, Activity>,
135 pub(crate) presence_cached: HashMap<String, PresenceKind>,
136 pub(crate) presence_requested: HashMap<String, Instant>,
137 pub(crate) presence_pending: HashSet<String>,
138 pub(crate) images: HashMap<String, ImageEntry>,
139 pub(crate) images_requested: HashSet<String>,
140 pub(crate) 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 self.folders
345 .iter()
346 .filter(|folder| {
347 folder.kind == FolderKind::UserCreated && !is_pending_folder(&folder.id)
348 })
349 .map(|folder| (folder.id.clone(), folder.name.clone()))
350 .collect()
351 }
352
353 pub fn apply_folder_change(&mut self, change: &FolderChange, created_id: &str) {
354 let position =
355 |folders: &[FolderInfo], id: &str| folders.iter().position(|folder| folder.id == id);
356 match change {
357 FolderChange::Create { name } => {
358 let index = position(&self.folders, created_id).unwrap_or_else(|| {
359 self.folders
360 .iter()
361 .position(|folder| folder.kind == FolderKind::Recent)
362 .unwrap_or(0)
363 });
364 self.folders.retain(|folder| folder.id != created_id);
365 self.folders.insert(
366 index.min(self.folders.len()),
367 FolderInfo {
368 id: created_id.to_owned(),
369 name: name.clone(),
370 kind: FolderKind::UserCreated,
371 expanded: None,
372 conversation_ids: Vec::new(),
373 },
374 );
375 }
376 FolderChange::Rename { folder_id, name } => {
377 if let Some(index) = position(&self.folders, folder_id) {
378 self.folders[index].name = name.clone();
379 }
380 }
381 FolderChange::Delete { folder_id } => {
382 self.folders.retain(|folder| folder.id != *folder_id)
383 }
384 FolderChange::Move {
385 folder_id,
386 target_folder_id,
387 } => {
388 if let (Some(source), Some(target)) = (
389 position(&self.folders, folder_id),
390 position(&self.folders, target_folder_id),
391 ) {
392 let moved = self.folders.remove(source);
393 self.folders.insert(target, moved);
394 }
395 }
396 }
397 }
398}
399
400pub const PENDING_FOLDER_PREFIX: &str = "pending-section:";
401
402pub fn is_pending_folder(folder_id: &str) -> bool {
403 folder_id.starts_with(PENDING_FOLDER_PREFIX)
404}
405
406pub fn image_format(content_type: &str) -> ImageFormat {
407 let lowered = content_type.to_ascii_lowercase();
408 if lowered.contains("png") {
409 ImageFormat::Png
410 } else if lowered.contains("webp") {
411 ImageFormat::Webp
412 } else if lowered.contains("gif") {
413 ImageFormat::Gif
414 } else if lowered.contains("svg") {
415 ImageFormat::Svg
416 } else {
417 ImageFormat::Jpeg
418 }
419}
420
421pub fn is_one_on_one(chat: &ChatRecord) -> bool {
422 chat.kind.eq_ignore_ascii_case("oneOnOne")
423}
424
425pub fn others(chat: &ChatRecord, me: Option<&Person>) -> Vec<(Option<String>, String)> {
426 chat.members
427 .iter()
428 .filter(|member| match (&member.user_id, me) {
429 (Some(user_id), Some(me)) => *user_id != me.user_id,
430 _ => true,
431 })
432 .map(|member| (member.user_id.clone(), member.display_name.clone()))
433 .collect()
434}
435
436pub fn face_members(chat: &ChatRecord, me: Option<&Person>) -> Vec<(Option<String>, String)> {
437 others(chat, me)
438 .into_iter()
439 .take(MEMBER_FACE_LIMIT)
440 .collect()
441}
442
443pub fn me(store: &Store) -> Option<Person> {
444 let user_id = store.meta("me_user_id").ok().flatten()?;
445 let display_name = store
446 .meta("me_display_name")
447 .ok()
448 .flatten()
449 .unwrap_or_default();
450 Some(Person {
451 user_id,
452 display_name,
453 })
454}
455
456fn folder_kind(kind: &str) -> FolderKind {
457 let lowered = kind.to_ascii_lowercase();
458 if lowered.contains(FAVORITES_KIND_MARKER) {
459 FolderKind::Favorites
460 } else if lowered.contains(RECENT_KIND_MARKER) {
461 FolderKind::Recent
462 } else if lowered.contains(MEETING_KIND_MARKER) {
463 FolderKind::Meeting
464 } else if lowered.contains(MUTED_KIND_MARKER) {
465 FolderKind::Muted
466 } else {
467 FolderKind::UserCreated
468 }
469}
470
471pub fn folders(store: &Store, pinned_ids: &[String]) -> Vec<FolderInfo> {
472 let stored: Vec<FolderInfo> = store
473 .folders()
474 .unwrap_or_default()
475 .into_iter()
476 .map(|record| FolderInfo {
477 kind: folder_kind(&record.kind),
478 expanded: Some(record.expanded),
479 id: record.id,
480 name: record.name,
481 conversation_ids: record.conversation_ids,
482 })
483 .collect();
484 if !stored.is_empty() {
485 return stored;
486 }
487 vec![FolderInfo {
488 id: "favorites".to_owned(),
489 name: String::new(),
490 kind: FolderKind::Favorites,
491 expanded: None,
492 conversation_ids: pinned_ids.to_vec(),
493 }]
494}
495
496pub fn pinned_channels(store: &Store) -> Vec<String> {
497 store.pinned_channel_ids().unwrap_or_default()
498}
499
500pub fn cached_avatar(store: &Store, user_id: &str) -> Option<Option<Arc<Image>>> {
501 let record = store.avatar(user_id).ok().flatten()?;
502 Some(
503 record
504 .bytes
505 .map(|bytes| avatar_image_from(&record.content_type, bytes)),
506 )
507}
508
509pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> {
510 match crate::avatar_image::circular_png(&bytes) {
511 Some(masked) => Arc::new(Image::from_bytes(ImageFormat::Png, masked)),
512 None => Arc::new(Image::from_bytes(image_format(content_type), bytes)),
513 }
514}
515
516pub fn unread_count(directory: &Directory, chat: &ChatRecord) -> Option<u32> {
517 directory.unread_counts.get(&chat.id).copied()
518}
519
520pub fn unread_counts(engine: &Engine, chats: &[ChatRecord]) -> HashMap<String, u32> {
521 chats
522 .iter()
523 .filter(|chat| chat.unread)
524 .map(|chat| (chat.id.clone(), engine.unread_count(&chat.id)))
525 .collect()
526}
527
528pub fn presence_kind_of(availability: Availability) -> PresenceKind {
529 match availability {
530 Availability::Available => PresenceKind::Available,
531 Availability::Busy => PresenceKind::Busy,
532 Availability::DoNotDisturb => PresenceKind::DoNotDisturb,
533 Availability::Away => PresenceKind::Away,
534 Availability::Offline => PresenceKind::Offline,
535 Availability::Unknown => PresenceKind::Unknown,
536 }
537}
538
539pub fn shown_presence(availability: Availability, activity: Option<Activity>) -> PresenceKind {
540 match activity {
541 Some(Activity::OutOfOffice) => PresenceKind::OutOfOffice,
542 _ => presence_kind_of(availability),
543 }
544}
545
546pub fn activity_label(activity: Activity) -> &'static str {
547 match activity {
548 Activity::InACall => "In a call",
549 Activity::InAConferenceCall | Activity::InAMeeting => "In a meeting",
550 Activity::Presenting => "Presenting",
551 Activity::OutOfOffice => "Out of office",
552 }
553}
554
555pub fn presence_activity(engine: &Engine, user_id: &str) -> Option<Activity> {
556 engine
557 .presence(user_id)
558 .and_then(|presence| presence.activity)
559}
560
561pub fn presence_kind(engine: &Engine, user_id: &str) -> Option<PresenceKind> {
562 engine
563 .presence(user_id)
564 .map(|presence| shown_presence(presence.availability, presence.activity))
565}
566
567pub fn in_call(engine: &Engine, user_id: &str) -> bool {
568 engine
569 .presence(user_id)
570 .is_some_and(|presence| presence.in_call())
571}
572
573pub type Done = oneshot::Receiver<Result<(), String>>;
574
575fn run<F>(future: F) -> Done
576where
577 F: std::future::Future<Output = teams_core::Result<()>> + Send + 'static,
578{
579 runtime::spawn(async move { future.await.map_err(|error| error.to_string()) })
580}
581
582pub fn fetch_image(engine: &Arc<Engine>, image: teams_core::ImageRef) -> Done {
583 let engine = engine.clone();
584 run(async move { engine.fetch_image(&image).await.map(|_| ()) })
585}
586
587pub fn fetch_avatars(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
588 let engine = engine.clone();
589 run(async move { engine.fetch_avatars(&user_ids).await })
590}
591
592pub fn refresh_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
593 let engine = engine.clone();
594 run(async move { engine.refresh_presence(&user_ids).await })
595}
596
597pub fn watch_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done {
598 let engine = engine.clone();
599 run(async move { engine.watch_presence(&user_ids).await })
600}
601
602pub fn move_to_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
603 let (engine, conversation_id, folder_id) = (
604 engine.clone(),
605 conversation_id.to_owned(),
606 folder_id.to_owned(),
607 );
608 run(async move { engine.move_to_folder(&conversation_id, &folder_id).await })
609}
610
611pub fn remove_from_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done {
612 let (engine, conversation_id, folder_id) = (
613 engine.clone(),
614 conversation_id.to_owned(),
615 folder_id.to_owned(),
616 );
617 run(async move {
618 engine
619 .remove_from_folder(&conversation_id, &folder_id)
620 .await
621 })
622}
623
624#[cfg(test)]
625mod tests {
626 use super::*;
627
628 #[test]
629 fn out_of_office_shows_over_the_availability() {
630 assert_eq!(
631 shown_presence(Availability::Offline, Some(Activity::OutOfOffice)),
632 PresenceKind::OutOfOffice
633 );
634 assert_eq!(
635 shown_presence(Availability::Available, Some(Activity::InAMeeting)),
636 PresenceKind::Available
637 );
638 }
639
640 #[test]
641 fn activity_wording_replaces_availability_only_for_live_presence() {
642 let cases = [
643 (Activity::InACall, "In a call"),
644 (Activity::InAConferenceCall, "In a meeting"),
645 (Activity::InAMeeting, "In a meeting"),
646 (Activity::Presenting, "Presenting"),
647 (Activity::OutOfOffice, "Out of office"),
648 ];
649 for (activity, label) in cases {
650 let mut directory = Directory::default();
651 directory.set_activity("ada", Some(activity));
652 let live = Presence::Live(PresenceKind::Busy);
653 assert_eq!(directory.status_label("ada", live), label);
654 assert_eq!(
655 directory.status_label("ada", Presence::Cached(PresenceKind::Busy)),
656 "Busy"
657 );
658 assert_eq!(directory.status_label("bob", live), "Busy");
659 assert!(directory.set_activity("ada", None));
660 assert_eq!(directory.status_label("ada", live), "Busy");
661 }
662 }
663
664 fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo {
665 FolderInfo {
666 id: id.into(),
667 name: id.into(),
668 kind,
669 expanded: None,
670 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
671 }
672 }
673
674 #[test]
675 fn assign_moves_a_chat_between_folders() {
676 let mut directory = Directory {
677 folders: vec![
678 folder("fav", FolderKind::Favorites, &["a"]),
679 folder("work", FolderKind::UserCreated, &["b"]),
680 ],
681 ..Default::default()
682 };
683 directory.assign("a", Some("work"));
684 assert!(directory.favorites().unwrap().conversation_ids.is_empty());
685 assert_eq!(directory.folders[1].conversation_ids, vec!["b", "a"]);
686 directory.assign("a", None);
687 assert!(directory.folder_of("a").is_none());
688 }
689
690 #[test]
691 fn folder_changes_apply_locally_like_teams() {
692 let mut directory = Directory {
693 folders: vec![
694 folder("fav", FolderKind::Favorites, &["a"]),
695 folder("work", FolderKind::UserCreated, &["b"]),
696 folder("todo", FolderKind::UserCreated, &[]),
697 folder("recent", FolderKind::Recent, &[]),
698 ],
699 ..Default::default()
700 };
701 let order = |directory: &Directory| -> Vec<String> {
702 directory
703 .folders
704 .iter()
705 .map(|folder| folder.id.clone())
706 .collect()
707 };
708 let move_folder = |folder_id: &str, target_folder_id: &str| FolderChange::Move {
709 folder_id: folder_id.into(),
710 target_folder_id: target_folder_id.into(),
711 };
712 directory.apply_folder_change(&move_folder("todo", "work"), "");
713 assert_eq!(order(&directory), ["fav", "todo", "work", "recent"]);
714 directory.apply_folder_change(&move_folder("fav", "todo"), "");
715 assert_eq!(order(&directory), ["todo", "fav", "work", "recent"]);
716 let rename = FolderChange::Rename {
717 folder_id: "work".into(),
718 name: "Job".into(),
719 };
720 directory.apply_folder_change(&rename, "");
721 assert_eq!(directory.folders[2].name, "Job");
722 let delete = FolderChange::Delete {
723 folder_id: "work".into(),
724 };
725 directory.apply_folder_change(&delete, "");
726 assert!(directory.folder_of("b").is_none());
727 }
728
729 #[test]
730 fn created_folder_lands_before_recent_and_keeps_its_place_when_reapplied() {
731 let mut directory = Directory {
732 folders: vec![
733 folder("fav", FolderKind::Favorites, &[]),
734 folder("recent", FolderKind::Recent, &[]),
735 folder("muted", FolderKind::Muted, &[]),
736 ],
737 ..Default::default()
738 };
739 let create = FolderChange::Create { name: "New".into() };
740 let pending_id = format!("{PENDING_FOLDER_PREFIX}1");
741 directory.apply_folder_change(&create, &pending_id);
742 directory.apply_folder_change(&create, &pending_id);
743 let ids: Vec<&str> = directory
744 .folders
745 .iter()
746 .map(|folder| folder.id.as_str())
747 .collect();
748 assert_eq!(ids, ["fav", pending_id.as_str(), "recent", "muted"]);
749 let mut bare = Directory::default();
750 bare.apply_folder_change(&create, "x");
751 assert_eq!(bare.folders[0].id, "x");
752 }
753
754 #[test]
755 fn pending_folders_are_no_move_targets() {
756 let directory = Directory {
757 folders: vec![
758 folder("fav", FolderKind::Favorites, &[]),
759 folder("work", FolderKind::UserCreated, &[]),
760 folder(
761 &format!("{PENDING_FOLDER_PREFIX}1"),
762 FolderKind::UserCreated,
763 &[],
764 ),
765 ],
766 ..Default::default()
767 };
768 assert_eq!(
769 directory.move_targets(),
770 [("work".to_owned(), "work".to_owned())]
771 );
772 }
773
774 #[test]
775 fn missing_avatars_skip_known_and_duplicates() {
776 let mut directory = Directory::default();
777 directory.set_avatar("known", None);
778 let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from));
779 assert_eq!(wanted, vec!["x", "y"]);
780 directory.mark_avatars_pending(&wanted);
781 assert!(directory.missing_avatars(["x".to_owned()]).is_empty());
782 assert_eq!(directory.pending_avatars().len(), 2);
783 }
784
785 #[test]
786 fn a_failed_image_is_requested_again_only_after_the_retry_delay() {
787 let mut directory = Directory::default();
788 assert_eq!(directory.images_to_request(["a".to_owned()]), vec!["a"]);
789 directory.mark_image_failed("a");
790 assert!(directory.images_to_request(["a".to_owned()]).is_empty());
791 directory
792 .images_failed
793 .insert("a".to_owned(), Instant::now() - IMAGE_RETRY_AFTER);
794 assert_eq!(directory.images_to_request(["a".to_owned()]), vec!["a"]);
795 }
796
797 #[test]
798 fn a_failed_image_is_only_failed_until_it_arrives() {
799 let mut directory = Directory::default();
800 assert!(!directory.image_failed("a"));
801 directory.mark_image_failed("a");
802 assert!(directory.image_failed("a"));
803 directory.set_image("a", Path::new("a.png"));
804 assert!(!directory.image_failed("a"));
805 }
806
807 #[test]
808 fn images_are_requested_once() {
809 let mut directory = Directory::default();
810 let wanted = directory.images_to_request(["a", "a", "b"].map(String::from));
811 assert_eq!(wanted, vec!["a", "b"]);
812 assert!(directory.images_to_request(["a".to_owned()]).is_empty());
813 }
814
815 #[test]
816 fn presence_is_refetched_after_the_max_age() {
817 let mut directory = Directory::default();
818 let start = Instant::now();
819 let wanted = directory.stale_presence(["u".to_owned()], start, false);
820 assert_eq!(wanted, vec!["u"]);
821 directory.mark_presence_requested(&wanted, start);
822 assert!(
823 directory
824 .stale_presence(["u".to_owned()], start, false)
825 .is_empty()
826 );
827 let later = start + PRESENCE_MAX_AGE + Duration::from_secs(1);
828 assert_eq!(
829 directory.stale_presence(["u".to_owned()], later, false),
830 vec!["u"]
831 );
832 assert!(
833 directory
834 .stale_presence(["u".to_owned()], later, true)
835 .is_empty()
836 );
837 let much_later = start + PUSHED_PRESENCE_MAX_AGE + Duration::from_secs(1);
838 assert_eq!(
839 directory.stale_presence(["u".to_owned()], much_later, true),
840 vec!["u"]
841 );
842 assert_eq!(directory.presence_of("u").kind(), PresenceKind::Unknown);
843 }
844
845 #[test]
846 fn presence_prefers_live_over_cached_over_loading() {
847 let mut directory = Directory::default();
848 let ids = ["a".to_owned(), "b".to_owned(), "c".to_owned()];
849 directory.mark_presence_pending(&ids);
850 directory
851 .presence_cached
852 .insert("b".into(), PresenceKind::Away);
853 directory
854 .presence_cached
855 .insert("c".into(), PresenceKind::Away);
856 directory.set_presence("c", PresenceKind::Busy);
857 assert_eq!(directory.presence_of("a"), Presence::Loading);
858 assert_eq!(
859 directory.presence_of("b"),
860 Presence::Cached(PresenceKind::Away)
861 );
862 assert_eq!(
863 directory.presence_of("c"),
864 Presence::Live(PresenceKind::Busy)
865 );
866 directory.settle_presence(&ids);
867 assert_eq!(
868 directory.presence_of("a"),
869 Presence::Live(PresenceKind::Unknown)
870 );
871 }
872
873 #[test]
874 fn presence_survives_a_restart_through_the_store() {
875 let store = Store::open_in_memory().unwrap();
876 let mut directory = Directory::default();
877 directory.set_presence("a", PresenceKind::DoNotDisturb);
878 directory.save_presence(&store, &["a".to_owned(), "missing".to_owned()]);
879 let mut restarted = Directory::default();
880 restarted.load_cached_presence(&store);
881 assert_eq!(
882 restarted.presence_of("a"),
883 Presence::Cached(PresenceKind::DoNotDisturb)
884 );
885 assert_eq!(
886 restarted.presence_of("missing"),
887 Presence::Live(PresenceKind::Unknown)
888 );
889 }
890
891 #[test]
892 fn content_types_map_to_image_formats() {
893 assert_eq!(image_format("image/png"), ImageFormat::Png);
894 assert_eq!(image_format("image/jpeg"), ImageFormat::Jpeg);
895 assert_eq!(image_format(""), ImageFormat::Jpeg);
896 }
897}