| 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; |
| 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 PRESENCE_MAX_AGE: Duration = Duration::from_secs(60); |
| 17 | const MEMBER_FACE_LIMIT: usize = 2; |
| 18 | |
| 19 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 20 | pub struct Person { |
| 21 | pub user_id: String, |
| 22 | pub display_name: String, |
| 23 | } |
| 24 | |
| 25 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 26 | pub enum FolderKind { |
| 27 | Favorites, |
| 28 | UserCreated, |
| 29 | } |
| 30 | |
| 31 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 32 | pub struct FolderInfo { |
| 33 | pub id: String, |
| 34 | pub name: String, |
| 35 | pub kind: FolderKind, |
| 36 | pub conversation_ids: Vec<String>, |
| 37 | } |
| 38 | |
| 39 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 40 | pub enum PresenceKind { |
| 41 | Available, |
| 42 | Busy, |
| 43 | DoNotDisturb, |
| 44 | Away, |
| 45 | Offline, |
| 46 | Unknown, |
| 47 | } |
| 48 | |
| 49 | impl PresenceKind { |
| 50 | pub fn label(self) -> &'static str { |
| 51 | match self { |
| 52 | PresenceKind::Available => "Available", |
| 53 | PresenceKind::Busy => "Busy", |
| 54 | PresenceKind::DoNotDisturb => "Do not disturb", |
| 55 | PresenceKind::Away => "Away", |
| 56 | PresenceKind::Offline => "Offline", |
| 57 | PresenceKind::Unknown => "", |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | #[derive(Clone)] |
| 63 | pub enum AvatarState { |
| 64 | Pending, |
| 65 | Missing, |
| 66 | Ready(Arc<Image>), |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone)] |
| 70 | pub struct ImageEntry { |
| 71 | pub path: PathBuf, |
| 72 | pub size: Option<(u32, u32)>, |
| 73 | } |
| 74 | |
| 75 | #[derive(Default)] |
| 76 | pub struct Directory { |
| 77 | pub me: Option<Person>, |
| 78 | pub folders: Vec<FolderInfo>, |
| 79 | pub pinned_channels: Vec<String>, |
| 80 | pub unread_counts: HashMap<String, u32>, |
| 81 | pub(crate) avatars: HashMap<String, AvatarState>, |
| 82 | pub(crate) presence: HashMap<String, (PresenceKind, Instant)>, |
| 83 | pub(crate) presence_requested: HashMap<String, Instant>, |
| 84 | pub(crate) images: HashMap<String, ImageEntry>, |
| 85 | pub(crate) images_requested: HashSet<String>, |
| 86 | } |
| 87 | |
| 88 | impl Directory { |
| 89 | pub fn avatar(&self, user_id: &str) -> Option<&AvatarState> { |
| 90 | self.avatars.get(user_id) |
| 91 | } |
| 92 | |
| 93 | pub fn image(&self, key: &str) -> Option<&ImageEntry> { |
| 94 | self.images.get(key) |
| 95 | } |
| 96 | |
| 97 | pub fn set_image(&mut self, key: &str, path: &Path) { |
| 98 | let size = image::image_dimensions(path).ok(); |
| 99 | self.images.insert( |
| 100 | key.to_owned(), |
| 101 | ImageEntry { |
| 102 | path: path.to_path_buf(), |
| 103 | size, |
| 104 | }, |
| 105 | ); |
| 106 | } |
| 107 | |
| 108 | pub fn images_to_request(&mut self, keys: impl IntoIterator<Item = String>) -> Vec<String> { |
| 109 | keys.into_iter() |
| 110 | .filter(|key| { |
| 111 | !self.images.contains_key(key) && self.images_requested.insert(key.clone()) |
| 112 | }) |
| 113 | .collect() |
| 114 | } |
| 115 | |
| 116 | pub fn missing_avatars(&self, user_ids: impl IntoIterator<Item = String>) -> Vec<String> { |
| 117 | let mut seen = HashSet::new(); |
| 118 | user_ids |
| 119 | .into_iter() |
| 120 | .filter(|user_id| !self.avatars.contains_key(user_id) && seen.insert(user_id.clone())) |
| 121 | .collect() |
| 122 | } |
| 123 | |
| 124 | pub fn mark_avatars_pending(&mut self, user_ids: &[String]) { |
| 125 | for user_id in user_ids { |
| 126 | self.avatars |
| 127 | .entry(user_id.clone()) |
| 128 | .or_insert(AvatarState::Pending); |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | pub fn set_avatar(&mut self, user_id: &str, image: Option<Arc<Image>>) { |
| 133 | let state = image.map_or(AvatarState::Missing, AvatarState::Ready); |
| 134 | self.avatars.insert(user_id.to_owned(), state); |
| 135 | } |
| 136 | |
| 137 | pub fn pending_avatars(&self) -> Vec<String> { |
| 138 | self.avatars |
| 139 | .iter() |
| 140 | .filter(|(_, state)| matches!(state, AvatarState::Pending)) |
| 141 | .map(|(user_id, _)| user_id.clone()) |
| 142 | .collect() |
| 143 | } |
| 144 | |
| 145 | pub fn presence_of(&self, user_id: &str) -> PresenceKind { |
| 146 | self.presence |
| 147 | .get(user_id) |
| 148 | .map_or(PresenceKind::Unknown, |(kind, _)| *kind) |
| 149 | } |
| 150 | |
| 151 | pub fn set_presence(&mut self, user_id: &str, kind: PresenceKind) { |
| 152 | self.presence |
| 153 | .insert(user_id.to_owned(), (kind, Instant::now())); |
| 154 | } |
| 155 | |
| 156 | pub fn stale_presence( |
| 157 | &self, |
| 158 | user_ids: impl IntoIterator<Item = String>, |
| 159 | now: Instant, |
| 160 | ) -> Vec<String> { |
| 161 | let mut seen = HashSet::new(); |
| 162 | user_ids |
| 163 | .into_iter() |
| 164 | .filter(|user_id| { |
| 165 | let fresh = |at: &Instant| now.duration_since(*at) < PRESENCE_MAX_AGE; |
| 166 | let known_fresh = self.presence.get(user_id).is_some_and(|(_, at)| fresh(at)); |
| 167 | let asked_fresh = self.presence_requested.get(user_id).is_some_and(fresh); |
| 168 | !known_fresh && !asked_fresh && seen.insert(user_id.clone()) |
| 169 | }) |
| 170 | .collect() |
| 171 | } |
| 172 | |
| 173 | pub fn requested_presence_ids(&self) -> Vec<String> { |
| 174 | self.presence_requested.keys().cloned().collect() |
| 175 | } |
| 176 | |
| 177 | pub fn mark_presence_requested(&mut self, user_ids: &[String], now: Instant) { |
| 178 | for user_id in user_ids { |
| 179 | self.presence_requested.insert(user_id.clone(), now); |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | pub fn favorites(&self) -> Option<&FolderInfo> { |
| 184 | self.folders |
| 185 | .iter() |
| 186 | .find(|folder| folder.kind == FolderKind::Favorites) |
| 187 | } |
| 188 | |
| 189 | pub fn folder_of(&self, conversation_id: &str) -> Option<&FolderInfo> { |
| 190 | self.folders.iter().find(|folder| { |
| 191 | folder |
| 192 | .conversation_ids |
| 193 | .iter() |
| 194 | .any(|id| id == conversation_id) |
| 195 | }) |
| 196 | } |
| 197 | |
| 198 | pub fn assign(&mut self, conversation_id: &str, folder_id: Option<&str>) { |
| 199 | for folder in &mut self.folders { |
| 200 | folder.conversation_ids.retain(|id| id != conversation_id); |
| 201 | } |
| 202 | if let Some(folder) = |
| 203 | folder_id.and_then(|id| self.folders.iter_mut().find(|folder| folder.id == id)) |
| 204 | { |
| 205 | folder.conversation_ids.push(conversation_id.to_owned()); |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | pub fn image_format(content_type: &str) -> ImageFormat { |
| 211 | let lowered = content_type.to_ascii_lowercase(); |
| 212 | if lowered.contains("png") { |
| 213 | ImageFormat::Png |
| 214 | } else if lowered.contains("webp") { |
| 215 | ImageFormat::Webp |
| 216 | } else if lowered.contains("gif") { |
| 217 | ImageFormat::Gif |
| 218 | } else if lowered.contains("svg") { |
| 219 | ImageFormat::Svg |
| 220 | } else { |
| 221 | ImageFormat::Jpeg |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | pub fn is_one_on_one(chat: &ChatRecord) -> bool { |
| 226 | chat.kind.eq_ignore_ascii_case("oneOnOne") |
| 227 | } |
| 228 | |
| 229 | pub fn others(chat: &ChatRecord, me: Option<&Person>) -> Vec<(Option<String>, String)> { |
| 230 | chat.members |
| 231 | .iter() |
| 232 | .filter(|member| match (&member.user_id, me) { |
| 233 | (Some(user_id), Some(me)) => *user_id != me.user_id, |
| 234 | _ => true, |
| 235 | }) |
| 236 | .map(|member| (member.user_id.clone(), member.display_name.clone())) |
| 237 | .collect() |
| 238 | } |
| 239 | |
| 240 | pub fn face_members(chat: &ChatRecord, me: Option<&Person>) -> Vec<(Option<String>, String)> { |
| 241 | others(chat, me) |
| 242 | .into_iter() |
| 243 | .take(MEMBER_FACE_LIMIT) |
| 244 | .collect() |
| 245 | } |
| 246 | |
| 247 | pub fn me(store: &Store) -> Option<Person> { |
| 248 | let user_id = store.meta("me_user_id").ok().flatten()?; |
| 249 | let display_name = store |
| 250 | .meta("me_display_name") |
| 251 | .ok() |
| 252 | .flatten() |
| 253 | .unwrap_or_default(); |
| 254 | Some(Person { |
| 255 | user_id, |
| 256 | display_name, |
| 257 | }) |
| 258 | } |
| 259 | |
| 260 | pub fn folders(store: &Store, pinned_ids: &[String]) -> Vec<FolderInfo> { |
| 261 | let stored: Vec<FolderInfo> = store |
| 262 | .folders() |
| 263 | .unwrap_or_default() |
| 264 | .into_iter() |
| 265 | .map(|record| FolderInfo { |
| 266 | kind: if record |
| 267 | .kind |
| 268 | .to_ascii_lowercase() |
| 269 | .contains(FAVORITES_KIND_MARKER) |
| 270 | { |
| 271 | FolderKind::Favorites |
| 272 | } else { |
| 273 | FolderKind::UserCreated |
| 274 | }, |
| 275 | id: record.id, |
| 276 | name: record.name, |
| 277 | conversation_ids: record.conversation_ids, |
| 278 | }) |
| 279 | .collect(); |
| 280 | if !stored.is_empty() { |
| 281 | return stored; |
| 282 | } |
| 283 | vec![FolderInfo { |
| 284 | id: "favorites".to_owned(), |
| 285 | name: String::new(), |
| 286 | kind: FolderKind::Favorites, |
| 287 | conversation_ids: pinned_ids.to_vec(), |
| 288 | }] |
| 289 | } |
| 290 | |
| 291 | pub fn pinned_channels(store: &Store) -> Vec<String> { |
| 292 | store.pinned_channel_ids().unwrap_or_default() |
| 293 | } |
| 294 | |
| 295 | pub fn cached_avatar(store: &Store, user_id: &str) -> Option<Option<Arc<Image>>> { |
| 296 | let record = store.avatar(user_id).ok().flatten()?; |
| 297 | Some( |
| 298 | record |
| 299 | .bytes |
| 300 | .map(|bytes| avatar_image_from(&record.content_type, bytes)), |
| 301 | ) |
| 302 | } |
| 303 | |
| 304 | pub fn avatar_image_from(content_type: &str, bytes: Vec<u8>) -> Arc<Image> { |
| 305 | match crate::avatar_image::circular_png(&bytes) { |
| 306 | Some(masked) => Arc::new(Image::from_bytes(ImageFormat::Png, masked)), |
| 307 | None => Arc::new(Image::from_bytes(image_format(content_type), bytes)), |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | pub fn unread_count(directory: &Directory, chat: &ChatRecord) -> Option<u32> { |
| 312 | directory.unread_counts.get(&chat.id).copied() |
| 313 | } |
| 314 | |
| 315 | pub fn unread_counts(engine: &Engine, chats: &[ChatRecord]) -> HashMap<String, u32> { |
| 316 | chats |
| 317 | .iter() |
| 318 | .filter(|chat| chat.unread) |
| 319 | .map(|chat| (chat.id.clone(), engine.unread_count(&chat.id))) |
| 320 | .collect() |
| 321 | } |
| 322 | |
| 323 | pub fn presence_kind(engine: &Engine, user_id: &str) -> Option<PresenceKind> { |
| 324 | engine |
| 325 | .presence(user_id) |
| 326 | .map(|presence| match presence.availability { |
| 327 | Availability::Available => PresenceKind::Available, |
| 328 | Availability::Busy => PresenceKind::Busy, |
| 329 | Availability::DoNotDisturb => PresenceKind::DoNotDisturb, |
| 330 | Availability::Away => PresenceKind::Away, |
| 331 | Availability::Offline => PresenceKind::Offline, |
| 332 | Availability::Unknown => PresenceKind::Unknown, |
| 333 | }) |
| 334 | } |
| 335 | |
| 336 | pub type Done = oneshot::Receiver<Result<(), String>>; |
| 337 | |
| 338 | fn run<F>(future: F) -> Done |
| 339 | where |
| 340 | F: std::future::Future<Output = teams_core::Result<()>> + Send + 'static, |
| 341 | { |
| 342 | runtime::spawn(async move { future.await.map_err(|error| error.to_string()) }) |
| 343 | } |
| 344 | |
| 345 | pub fn fetch_image(engine: &Arc<Engine>, image: teams_core::ImageRef) -> Done { |
| 346 | let engine = engine.clone(); |
| 347 | run(async move { engine.fetch_image(&image).await.map(|_| ()) }) |
| 348 | } |
| 349 | |
| 350 | pub fn fetch_avatars(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done { |
| 351 | let engine = engine.clone(); |
| 352 | run(async move { engine.fetch_avatars(&user_ids).await }) |
| 353 | } |
| 354 | |
| 355 | pub fn refresh_presence(engine: &Arc<Engine>, user_ids: Vec<String>) -> Done { |
| 356 | let engine = engine.clone(); |
| 357 | run(async move { engine.refresh_presence(&user_ids).await }) |
| 358 | } |
| 359 | |
| 360 | pub fn move_to_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done { |
| 361 | let (engine, conversation_id, folder_id) = ( |
| 362 | engine.clone(), |
| 363 | conversation_id.to_owned(), |
| 364 | folder_id.to_owned(), |
| 365 | ); |
| 366 | run(async move { engine.move_to_folder(&conversation_id, &folder_id).await }) |
| 367 | } |
| 368 | |
| 369 | pub fn remove_from_folder(engine: &Arc<Engine>, conversation_id: &str, folder_id: &str) -> Done { |
| 370 | let (engine, conversation_id, folder_id) = ( |
| 371 | engine.clone(), |
| 372 | conversation_id.to_owned(), |
| 373 | folder_id.to_owned(), |
| 374 | ); |
| 375 | run(async move { |
| 376 | engine |
| 377 | .remove_from_folder(&conversation_id, &folder_id) |
| 378 | .await |
| 379 | }) |
| 380 | } |
| 381 | |
| 382 | #[cfg(test)] |
| 383 | mod tests { |
| 384 | use super::*; |
| 385 | |
| 386 | fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo { |
| 387 | FolderInfo { |
| 388 | id: id.into(), |
| 389 | name: id.into(), |
| 390 | kind, |
| 391 | conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(), |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | #[test] |
| 396 | fn assign_moves_a_chat_between_folders() { |
| 397 | let mut directory = Directory { |
| 398 | folders: vec![ |
| 399 | folder("fav", FolderKind::Favorites, &["a"]), |
| 400 | folder("work", FolderKind::UserCreated, &["b"]), |
| 401 | ], |
| 402 | ..Default::default() |
| 403 | }; |
| 404 | directory.assign("a", Some("work")); |
| 405 | assert!(directory.favorites().unwrap().conversation_ids.is_empty()); |
| 406 | assert_eq!(directory.folders[1].conversation_ids, vec!["b", "a"]); |
| 407 | directory.assign("a", None); |
| 408 | assert!(directory.folder_of("a").is_none()); |
| 409 | } |
| 410 | |
| 411 | #[test] |
| 412 | fn missing_avatars_skip_known_and_duplicates() { |
| 413 | let mut directory = Directory::default(); |
| 414 | directory.set_avatar("known", None); |
| 415 | let wanted = directory.missing_avatars(["known", "x", "x", "y"].map(String::from)); |
| 416 | assert_eq!(wanted, vec!["x", "y"]); |
| 417 | directory.mark_avatars_pending(&wanted); |
| 418 | assert!(directory.missing_avatars(["x".to_owned()]).is_empty()); |
| 419 | assert_eq!(directory.pending_avatars().len(), 2); |
| 420 | } |
| 421 | |
| 422 | #[test] |
| 423 | fn images_are_requested_once() { |
| 424 | let mut directory = Directory::default(); |
| 425 | let wanted = directory.images_to_request(["a", "a", "b"].map(String::from)); |
| 426 | assert_eq!(wanted, vec!["a", "b"]); |
| 427 | assert!(directory.images_to_request(["a".to_owned()]).is_empty()); |
| 428 | } |
| 429 | |
| 430 | #[test] |
| 431 | fn presence_is_refetched_after_a_minute() { |
| 432 | let mut directory = Directory::default(); |
| 433 | let start = Instant::now(); |
| 434 | let wanted = directory.stale_presence(["u".to_owned()], start); |
| 435 | assert_eq!(wanted, vec!["u"]); |
| 436 | directory.mark_presence_requested(&wanted, start); |
| 437 | assert!(directory.stale_presence(["u".to_owned()], start).is_empty()); |
| 438 | let later = start + PRESENCE_MAX_AGE + Duration::from_secs(1); |
| 439 | assert_eq!(directory.stale_presence(["u".to_owned()], later), vec!["u"]); |
| 440 | assert_eq!(directory.presence_of("u"), PresenceKind::Unknown); |
| 441 | } |
| 442 | |
| 443 | #[test] |
| 444 | fn content_types_map_to_image_formats() { |
| 445 | assert_eq!(image_format("image/png"), ImageFormat::Png); |
| 446 | assert_eq!(image_format("image/jpeg"), ImageFormat::Jpeg); |
| 447 | assert_eq!(image_format(""), ImageFormat::Jpeg); |
| 448 | } |
| 449 | } |