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