| 1 | use std::collections::HashMap; |
| 2 | use std::future::Future; |
| 3 | use std::pin::Pin; |
| 4 | use std::sync::Arc; |
| 5 | |
| 6 | use chatsvc::{ |
| 7 | ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection, |
| 8 | ChatSectionSettings, Pins, UserSettings, pins::SessionTransport, |
| 9 | }; |
| 10 | use chrono::Utc; |
| 11 | use session::Session; |
| 12 | use store::{ChannelLayoutRecord, ChannelTabRecord, FolderRecord, Store, TeamLayoutRecord}; |
| 13 | |
| 14 | use crate::engine::SyncEngine; |
| 15 | use crate::error::{Error, Result}; |
| 16 | use crate::events::CoreEvent; |
| 17 | use crate::remote::Remote; |
| 18 | |
| 19 | pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>; |
| 20 | |
| 21 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 22 | pub enum FolderKind { |
| 23 | Favorites, |
| 24 | UserCreated, |
| 25 | Recent, |
| 26 | Meeting, |
| 27 | Muted, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub struct ChatFolder { |
| 32 | pub id: String, |
| 33 | pub name: String, |
| 34 | pub kind: FolderKind, |
| 35 | pub expanded: bool, |
| 36 | pub conversation_ids: Vec<String>, |
| 37 | } |
| 38 | |
| 39 | pub trait FolderSource: Send + Sync { |
| 40 | fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>>; |
| 41 | fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>>; |
| 42 | fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>>; |
| 43 | fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>>; |
| 44 | fn set_section_enabled(&self, section: ChatSection, enabled: bool) |
| 45 | -> BoxFuture<'_, Result<()>>; |
| 46 | fn set_folder_expanded<'a>( |
| 47 | &'a self, |
| 48 | folder_id: &'a str, |
| 49 | expanded: bool, |
| 50 | ) -> BoxFuture<'a, Result<()>>; |
| 51 | fn move_to_folder<'a>( |
| 52 | &'a self, |
| 53 | conversation_id: &'a str, |
| 54 | target_folder_id: &'a str, |
| 55 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>; |
| 56 | fn remove_from_folder<'a>( |
| 57 | &'a self, |
| 58 | conversation_id: &'a str, |
| 59 | folder_id: &'a str, |
| 60 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>; |
| 61 | } |
| 62 | |
| 63 | pub struct ChatsvcFolderSource { |
| 64 | pins: Pins<SessionTransport>, |
| 65 | settings: UserSettings, |
| 66 | channel_settings: ChannelSettings, |
| 67 | } |
| 68 | |
| 69 | impl ChatsvcFolderSource { |
| 70 | pub fn new(session: &Session) -> Self { |
| 71 | ChatsvcFolderSource { |
| 72 | pins: Pins::new(session), |
| 73 | settings: UserSettings::new(session), |
| 74 | channel_settings: ChannelSettings::new(session), |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl FolderSource for ChatsvcFolderSource { |
| 80 | fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>> { |
| 81 | Box::pin(async { Ok(convert(self.pins.folders().await?)) }) |
| 82 | } |
| 83 | |
| 84 | fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>> { |
| 85 | Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) }) |
| 86 | } |
| 87 | |
| 88 | fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> { |
| 89 | Box::pin(async { |
| 90 | let layout = self.pins.team_layout().await?; |
| 91 | let unknown: Vec<String> = layout |
| 92 | .iter() |
| 93 | .flat_map(|team| &team.channels) |
| 94 | .filter(|channel| channel.notifications.is_none()) |
| 95 | .map(|channel| channel.channel_id.clone()) |
| 96 | .collect(); |
| 97 | let fallback = if unknown.is_empty() { |
| 98 | HashMap::new() |
| 99 | } else { |
| 100 | self.channel_settings |
| 101 | .fetch(&unknown) |
| 102 | .await |
| 103 | .unwrap_or_default() |
| 104 | }; |
| 105 | Ok(layout |
| 106 | .into_iter() |
| 107 | .map(|team| layout_record(team, &fallback)) |
| 108 | .collect()) |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> { |
| 113 | Box::pin(async { Ok(self.settings.chat_sections().await?) }) |
| 114 | } |
| 115 | |
| 116 | fn set_section_enabled( |
| 117 | &self, |
| 118 | section: ChatSection, |
| 119 | enabled: bool, |
| 120 | ) -> BoxFuture<'_, Result<()>> { |
| 121 | Box::pin(async move { Ok(self.settings.set_chat_section(section, enabled).await?) }) |
| 122 | } |
| 123 | |
| 124 | fn set_folder_expanded<'a>( |
| 125 | &'a self, |
| 126 | folder_id: &'a str, |
| 127 | expanded: bool, |
| 128 | ) -> BoxFuture<'a, Result<()>> { |
| 129 | Box::pin(async move { Ok(self.pins.set_folder_expanded(folder_id, expanded).await?) }) |
| 130 | } |
| 131 | |
| 132 | fn move_to_folder<'a>( |
| 133 | &'a self, |
| 134 | conversation_id: &'a str, |
| 135 | target_folder_id: &'a str, |
| 136 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> { |
| 137 | Box::pin(async move { |
| 138 | Ok(convert( |
| 139 | self.pins |
| 140 | .move_to_folder(conversation_id, target_folder_id) |
| 141 | .await?, |
| 142 | )) |
| 143 | }) |
| 144 | } |
| 145 | |
| 146 | fn remove_from_folder<'a>( |
| 147 | &'a self, |
| 148 | conversation_id: &'a str, |
| 149 | folder_id: &'a str, |
| 150 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> { |
| 151 | Box::pin(async move { |
| 152 | Ok(convert( |
| 153 | self.pins |
| 154 | .remove_from_folder(conversation_id, folder_id) |
| 155 | .await?, |
| 156 | )) |
| 157 | }) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> { |
| 162 | folders |
| 163 | .folders |
| 164 | .into_iter() |
| 165 | .map(|folder| ChatFolder { |
| 166 | id: folder.id, |
| 167 | name: folder.name, |
| 168 | kind: match folder.kind { |
| 169 | chatsvc::FolderKind::Favorites => FolderKind::Favorites, |
| 170 | chatsvc::FolderKind::UserCreated => FolderKind::UserCreated, |
| 171 | chatsvc::FolderKind::Recent => FolderKind::Recent, |
| 172 | chatsvc::FolderKind::Meeting => FolderKind::Meeting, |
| 173 | chatsvc::FolderKind::Muted => FolderKind::Muted, |
| 174 | }, |
| 175 | expanded: folder.expanded, |
| 176 | conversation_ids: folder.conversation_ids, |
| 177 | }) |
| 178 | .collect() |
| 179 | } |
| 180 | |
| 181 | fn resolve_notifications( |
| 182 | channel: &chatsvc::ChannelLayout, |
| 183 | fallback: &HashMap<String, ChannelNotifications>, |
| 184 | ) -> ChannelNotifications { |
| 185 | channel |
| 186 | .notifications |
| 187 | .or_else(|| fallback.get(&channel.channel_id).copied()) |
| 188 | .unwrap_or_else(|| ChannelNotifications::from_followed(channel.followed)) |
| 189 | } |
| 190 | |
| 191 | fn notification_record(notifications: ChannelNotifications) -> store::ChannelNotifications { |
| 192 | store::ChannelNotifications { |
| 193 | level: match notifications.level { |
| 194 | ChannelNotificationLevel::BannerAndFeed => { |
| 195 | store::ChannelNotificationLevel::BannerAndFeed |
| 196 | } |
| 197 | ChannelNotificationLevel::Feed => store::ChannelNotificationLevel::Feed, |
| 198 | ChannelNotificationLevel::Off => store::ChannelNotificationLevel::Off, |
| 199 | }, |
| 200 | include_replies: notifications.include_replies, |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | pub(crate) fn chatsvc_notifications( |
| 205 | notifications: store::ChannelNotifications, |
| 206 | ) -> ChannelNotifications { |
| 207 | ChannelNotifications { |
| 208 | level: match notifications.level { |
| 209 | store::ChannelNotificationLevel::BannerAndFeed => { |
| 210 | ChannelNotificationLevel::BannerAndFeed |
| 211 | } |
| 212 | store::ChannelNotificationLevel::Feed => ChannelNotificationLevel::Feed, |
| 213 | store::ChannelNotificationLevel::Off => ChannelNotificationLevel::Off, |
| 214 | }, |
| 215 | include_replies: notifications.include_replies, |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | fn layout_record( |
| 220 | team: chatsvc::TeamLayout, |
| 221 | fallback: &HashMap<String, ChannelNotifications>, |
| 222 | ) -> TeamLayoutRecord { |
| 223 | TeamLayoutRecord { |
| 224 | team_id: team.team_id, |
| 225 | hidden: team.hidden, |
| 226 | channels: team |
| 227 | .channels |
| 228 | .into_iter() |
| 229 | .map(|channel| ChannelLayoutRecord { |
| 230 | notifications: notification_record(resolve_notifications(&channel, fallback)), |
| 231 | channel_id: channel.channel_id, |
| 232 | general: channel.general, |
| 233 | hidden: channel.hidden, |
| 234 | tabs: channel |
| 235 | .tabs |
| 236 | .into_iter() |
| 237 | .map(|tab| ChannelTabRecord { |
| 238 | tab_id: tab.id, |
| 239 | name: tab.name, |
| 240 | definition_id: tab.definition_id, |
| 241 | open_url: tab.open_url, |
| 242 | }) |
| 243 | .collect(), |
| 244 | }) |
| 245 | .collect(), |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | const META_TEAM_LAYOUT_AT: &str = "team_layout_refreshed_at"; |
| 250 | const KIND_FAVORITES: &str = "Favorites"; |
| 251 | const KIND_USER_CREATED: &str = "UserCreated"; |
| 252 | const KIND_RECENT: &str = "RecentChats"; |
| 253 | const KIND_MEETING: &str = "MeetingChats"; |
| 254 | const KIND_MUTED: &str = "MutedChats"; |
| 255 | const META_MUTED_SECTION: &str = "chat_section_muted"; |
| 256 | const META_MEETING_SECTION: &str = "chat_section_meeting"; |
| 257 | |
| 258 | fn to_record(folder: &ChatFolder) -> FolderRecord { |
| 259 | FolderRecord { |
| 260 | id: folder.id.clone(), |
| 261 | name: folder.name.clone(), |
| 262 | kind: match folder.kind { |
| 263 | FolderKind::Favorites => KIND_FAVORITES, |
| 264 | FolderKind::UserCreated => KIND_USER_CREATED, |
| 265 | FolderKind::Recent => KIND_RECENT, |
| 266 | FolderKind::Meeting => KIND_MEETING, |
| 267 | FolderKind::Muted => KIND_MUTED, |
| 268 | } |
| 269 | .to_owned(), |
| 270 | expanded: folder.expanded, |
| 271 | conversation_ids: folder.conversation_ids.clone(), |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | fn from_record(record: FolderRecord) -> ChatFolder { |
| 276 | ChatFolder { |
| 277 | id: record.id, |
| 278 | name: record.name, |
| 279 | kind: match record.kind.as_str() { |
| 280 | KIND_FAVORITES => FolderKind::Favorites, |
| 281 | KIND_RECENT => FolderKind::Recent, |
| 282 | KIND_MEETING => FolderKind::Meeting, |
| 283 | KIND_MUTED => FolderKind::Muted, |
| 284 | _ => FolderKind::UserCreated, |
| 285 | }, |
| 286 | expanded: record.expanded, |
| 287 | conversation_ids: record.conversation_ids, |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | pub fn stored_section_settings(store: &Store) -> ChatSectionSettings { |
| 292 | let read = |key: &str| { |
| 293 | store |
| 294 | .meta(key) |
| 295 | .ok() |
| 296 | .flatten() |
| 297 | .and_then(|value| value.parse().ok()) |
| 298 | }; |
| 299 | ChatSectionSettings { |
| 300 | muted: read(META_MUTED_SECTION), |
| 301 | meeting: read(META_MEETING_SECTION), |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | pub fn store_section_settings(store: &Store, settings: &ChatSectionSettings) -> Result<()> { |
| 306 | for (key, value) in [ |
| 307 | (META_MUTED_SECTION, settings.muted), |
| 308 | (META_MEETING_SECTION, settings.meeting), |
| 309 | ] { |
| 310 | let text = value.map(|enabled| enabled.to_string()).unwrap_or_default(); |
| 311 | store.set_meta(key, &text)?; |
| 312 | } |
| 313 | Ok(()) |
| 314 | } |
| 315 | |
| 316 | impl<R: Remote> SyncEngine<R> { |
| 317 | pub fn with_folder_source(mut self, source: Arc<dyn FolderSource>) -> Self { |
| 318 | self.folder_source = Some(source); |
| 319 | self |
| 320 | } |
| 321 | |
| 322 | pub fn chat_folders(&self) -> Result<Vec<ChatFolder>> { |
| 323 | Ok(self.store.folders()?.into_iter().map(from_record).collect()) |
| 324 | } |
| 325 | |
| 326 | pub fn pinned_channels(&self) -> Result<Vec<String>> { |
| 327 | Ok(self.store.pinned_channel_ids()?) |
| 328 | } |
| 329 | |
| 330 | pub async fn refresh_folders(&self) -> Result<()> { |
| 331 | let source = self.folder_source()?; |
| 332 | let folders = match tokio::try_join!(source.folders(), source.pinned_channels()) { |
| 333 | Ok((folders, channels)) => self.store_folders(&folders, &channels), |
| 334 | Err(error) => Err(error), |
| 335 | }; |
| 336 | self.refresh_section_settings(source).await; |
| 337 | let layout = self.refresh_team_layout(source).await; |
| 338 | match (folders, layout) { |
| 339 | (Err(folders_error), Err(layout_error)) => { |
| 340 | Err(Error::Folders(format!("{folders_error}; {layout_error}"))) |
| 341 | } |
| 342 | (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error), |
| 343 | (Ok(()), Ok(())) => Ok(()), |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) { |
| 348 | let outcome = match source.section_settings().await { |
| 349 | Ok(settings) => self.apply_section_settings(&settings), |
| 350 | Err(error) => Err(error), |
| 351 | }; |
| 352 | if let Err(error) = outcome { |
| 353 | self.report(format!("cannot refresh chat list settings: {error}")); |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | fn apply_section_settings(&self, settings: &ChatSectionSettings) -> Result<()> { |
| 358 | if stored_section_settings(&self.store) != *settings { |
| 359 | store_section_settings(&self.store, settings)?; |
| 360 | let _ = self.events.send(CoreEvent::FoldersChanged); |
| 361 | } |
| 362 | Ok(()) |
| 363 | } |
| 364 | |
| 365 | pub async fn set_section_enabled(&self, section: ChatSection, enabled: bool) -> Result<()> { |
| 366 | self.folder_source()? |
| 367 | .set_section_enabled(section, enabled) |
| 368 | .await |
| 369 | } |
| 370 | |
| 371 | pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> { |
| 372 | self.folder_source()? |
| 373 | .set_folder_expanded(folder_id, expanded) |
| 374 | .await |
| 375 | } |
| 376 | |
| 377 | async fn refresh_team_layout(&self, source: &Arc<dyn FolderSource>) -> Result<()> { |
| 378 | let last = self.store.meta_time(META_TEAM_LAYOUT_AT)?; |
| 379 | if last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval) { |
| 380 | return Ok(()); |
| 381 | } |
| 382 | let layout = source.team_layout().await?; |
| 383 | let before = self.store.sidebar()?.teams; |
| 384 | self.store.replace_team_layout(&layout)?; |
| 385 | self.store.set_meta_time(META_TEAM_LAYOUT_AT, Utc::now())?; |
| 386 | if self.store.sidebar()?.teams != before { |
| 387 | let _ = self.events.send(CoreEvent::SidebarChanged); |
| 388 | } |
| 389 | Ok(()) |
| 390 | } |
| 391 | |
| 392 | pub async fn move_to_folder( |
| 393 | &self, |
| 394 | conversation_id: &str, |
| 395 | target_folder_id: &str, |
| 396 | ) -> Result<()> { |
| 397 | let folders = self |
| 398 | .folder_source()? |
| 399 | .move_to_folder(conversation_id, target_folder_id) |
| 400 | .await?; |
| 401 | self.store_folders(&folders, &self.store.pinned_channel_ids()?) |
| 402 | } |
| 403 | |
| 404 | pub async fn remove_from_folder(&self, conversation_id: &str, folder_id: &str) -> Result<()> { |
| 405 | let folders = self |
| 406 | .folder_source()? |
| 407 | .remove_from_folder(conversation_id, folder_id) |
| 408 | .await?; |
| 409 | self.store_folders(&folders, &self.store.pinned_channel_ids()?) |
| 410 | } |
| 411 | |
| 412 | fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> { |
| 413 | self.folder_source |
| 414 | .as_ref() |
| 415 | .ok_or(Error::Unsupported("chat folders without a folder source")) |
| 416 | } |
| 417 | |
| 418 | fn store_folders(&self, folders: &[ChatFolder], channel_ids: &[String]) -> Result<()> { |
| 419 | let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?); |
| 420 | let records: Vec<FolderRecord> = folders.iter().map(to_record).collect(); |
| 421 | self.store.replace_folders(&records, channel_ids)?; |
| 422 | if previous != (folders.to_vec(), channel_ids.to_vec()) { |
| 423 | let _ = self.events.send(CoreEvent::FoldersChanged); |
| 424 | } |
| 425 | Ok(()) |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | #[cfg(test)] |
| 430 | mod tests { |
| 431 | use super::*; |
| 432 | |
| 433 | fn channel( |
| 434 | notifications: Option<ChannelNotifications>, |
| 435 | followed: bool, |
| 436 | ) -> chatsvc::ChannelLayout { |
| 437 | chatsvc::ChannelLayout { |
| 438 | channel_id: "19:a".into(), |
| 439 | general: false, |
| 440 | hidden: false, |
| 441 | tabs: Vec::new(), |
| 442 | notifications, |
| 443 | followed, |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | fn level(level: ChannelNotificationLevel, include_replies: bool) -> ChannelNotifications { |
| 448 | ChannelNotifications { |
| 449 | level, |
| 450 | include_replies, |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | #[test] |
| 455 | fn channel_value_beats_the_notification_service_beats_the_followed_flag() { |
| 456 | let off = level(ChannelNotificationLevel::Off, false); |
| 457 | let banner = level(ChannelNotificationLevel::BannerAndFeed, true); |
| 458 | let fallback = HashMap::from([("19:a".to_owned(), banner)]); |
| 459 | assert_eq!( |
| 460 | resolve_notifications(&channel(Some(off), true), &fallback), |
| 461 | off |
| 462 | ); |
| 463 | assert_eq!( |
| 464 | resolve_notifications(&channel(None, false), &fallback), |
| 465 | banner |
| 466 | ); |
| 467 | assert_eq!( |
| 468 | resolve_notifications(&channel(None, true), &HashMap::new()), |
| 469 | banner |
| 470 | ); |
| 471 | assert_eq!( |
| 472 | resolve_notifications(&channel(None, false), &HashMap::new()), |
| 473 | ChannelNotifications::default() |
| 474 | ); |
| 475 | } |
| 476 | } |