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