BlueGit

ict rusty-teams

Files

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

data.rs

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