| 1 | use std::collections::HashMap; |
| 2 | use std::future::Future; |
| 3 | use std::pin::Pin; |
| 4 | use std::sync::{Arc, Mutex}; |
| 5 | |
| 6 | use chatsvc::settings::{parse_chat_sections, parse_skin_tone, parse_teams_order}; |
| 7 | use chatsvc::{ |
| 8 | ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection, |
| 9 | ChatSectionSettings, Pins, UserSettings, pins::SessionTransport, |
| 10 | }; |
| 11 | use chrono::Utc; |
| 12 | use serde_json::Value; |
| 13 | use session::Session; |
| 14 | use store::{ChannelLayoutRecord, ChannelTabRecord, FolderRecord, Store, TeamLayoutRecord}; |
| 15 | |
| 16 | use crate::engine::SyncEngine; |
| 17 | use crate::error::{Error, Result}; |
| 18 | use crate::events::CoreEvent; |
| 19 | use crate::remote::Remote; |
| 20 | |
| 21 | pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>; |
| 22 | |
| 23 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 24 | pub enum FolderKind { |
| 25 | Favorites, |
| 26 | UserCreated, |
| 27 | Recent, |
| 28 | Meeting, |
| 29 | Muted, |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 33 | pub struct ChatFolder { |
| 34 | pub id: String, |
| 35 | pub name: String, |
| 36 | pub kind: FolderKind, |
| 37 | pub expanded: bool, |
| 38 | pub conversation_ids: Vec<String>, |
| 39 | } |
| 40 | |
| 41 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 42 | pub enum FolderChange { |
| 43 | Create { |
| 44 | name: String, |
| 45 | }, |
| 46 | Rename { |
| 47 | folder_id: String, |
| 48 | name: String, |
| 49 | }, |
| 50 | Delete { |
| 51 | folder_id: String, |
| 52 | }, |
| 53 | Move { |
| 54 | folder_id: String, |
| 55 | target_folder_id: String, |
| 56 | }, |
| 57 | } |
| 58 | |
| 59 | pub trait FolderSource: Send + Sync { |
| 60 | fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>>; |
| 61 | fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>>; |
| 62 | fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>>; |
| 63 | fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>>; |
| 64 | fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> { |
| 65 | Box::pin(async { Ok(Vec::new()) }) |
| 66 | } |
| 67 | fn preferred_skin_tone(&self) -> Option<u8> { |
| 68 | None |
| 69 | } |
| 70 | fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> { |
| 71 | Box::pin(async { Ok(()) }) |
| 72 | } |
| 73 | fn set_section_enabled(&self, section: ChatSection, enabled: bool) |
| 74 | -> BoxFuture<'_, Result<()>>; |
| 75 | fn set_folder_expanded<'a>( |
| 76 | &'a self, |
| 77 | folder_id: &'a str, |
| 78 | expanded: bool, |
| 79 | ) -> BoxFuture<'a, Result<()>>; |
| 80 | fn move_to_folder<'a>( |
| 81 | &'a self, |
| 82 | conversation_id: &'a str, |
| 83 | target_folder_id: &'a str, |
| 84 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>; |
| 85 | fn remove_from_folder<'a>( |
| 86 | &'a self, |
| 87 | conversation_id: &'a str, |
| 88 | folder_id: &'a str, |
| 89 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>; |
| 90 | fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>; |
| 91 | } |
| 92 | |
| 93 | pub struct ChatsvcFolderSource { |
| 94 | pins: Pins<SessionTransport>, |
| 95 | settings: UserSettings, |
| 96 | channel_settings: ChannelSettings, |
| 97 | properties: Mutex<Option<Value>>, |
| 98 | skin_tone: Mutex<Option<u8>>, |
| 99 | group_ids: Mutex<HashMap<String, String>>, |
| 100 | } |
| 101 | |
| 102 | impl ChatsvcFolderSource { |
| 103 | pub fn new(session: &Session) -> Self { |
| 104 | ChatsvcFolderSource { |
| 105 | pins: Pins::new(session), |
| 106 | settings: UserSettings::new(session), |
| 107 | channel_settings: ChannelSettings::new(session), |
| 108 | properties: Mutex::new(None), |
| 109 | skin_tone: Mutex::new(None), |
| 110 | group_ids: Mutex::new(HashMap::new()), |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | impl FolderSource for ChatsvcFolderSource { |
| 116 | fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>> { |
| 117 | Box::pin(async { Ok(convert(self.pins.folders().await?)) }) |
| 118 | } |
| 119 | |
| 120 | fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>> { |
| 121 | Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) }) |
| 122 | } |
| 123 | |
| 124 | fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> { |
| 125 | Box::pin(async { |
| 126 | let layout = self.pins.team_layout().await?; |
| 127 | *self.group_ids.lock().unwrap() = group_ids_by_thread(&layout); |
| 128 | let unknown: Vec<String> = layout |
| 129 | .iter() |
| 130 | .flat_map(|team| &team.channels) |
| 131 | .filter(|channel| channel.notifications.is_none()) |
| 132 | .map(|channel| channel.channel_id.clone()) |
| 133 | .collect(); |
| 134 | let fallback = if unknown.is_empty() { |
| 135 | HashMap::new() |
| 136 | } else { |
| 137 | self.channel_settings |
| 138 | .fetch(&unknown) |
| 139 | .await |
| 140 | .unwrap_or_default() |
| 141 | }; |
| 142 | Ok(layout |
| 143 | .into_iter() |
| 144 | .map(|team| layout_record(team, &fallback)) |
| 145 | .collect()) |
| 146 | }) |
| 147 | } |
| 148 | |
| 149 | fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> { |
| 150 | Box::pin(async { |
| 151 | let properties = self.settings.properties().await?; |
| 152 | let sections = parse_chat_sections(&properties); |
| 153 | *self.skin_tone.lock().unwrap() = parse_skin_tone(&properties); |
| 154 | *self.properties.lock().unwrap() = Some(properties); |
| 155 | Ok(sections) |
| 156 | }) |
| 157 | } |
| 158 | |
| 159 | fn preferred_skin_tone(&self) -> Option<u8> { |
| 160 | *self.skin_tone.lock().unwrap() |
| 161 | } |
| 162 | |
| 163 | fn set_skin_tone(&self, tone: u8) -> BoxFuture<'_, Result<()>> { |
| 164 | Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) }) |
| 165 | } |
| 166 | |
| 167 | fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> { |
| 168 | Box::pin(async { |
| 169 | let cached = self.properties.lock().unwrap().take(); |
| 170 | let properties = match cached { |
| 171 | Some(properties) => properties, |
| 172 | None => self.settings.properties().await?, |
| 173 | }; |
| 174 | let known = self.group_ids.lock().unwrap().clone(); |
| 175 | let group_ids = if known.is_empty() { |
| 176 | group_ids_by_thread(&self.pins.team_layout().await?) |
| 177 | } else { |
| 178 | known |
| 179 | }; |
| 180 | Ok(order_by_group_id( |
| 181 | parse_teams_order(&properties), |
| 182 | &group_ids, |
| 183 | )) |
| 184 | }) |
| 185 | } |
| 186 | |
| 187 | fn set_section_enabled( |
| 188 | &self, |
| 189 | section: ChatSection, |
| 190 | enabled: bool, |
| 191 | ) -> BoxFuture<'_, Result<()>> { |
| 192 | Box::pin(async move { Ok(self.settings.set_chat_section(section, enabled).await?) }) |
| 193 | } |
| 194 | |
| 195 | fn set_folder_expanded<'a>( |
| 196 | &'a self, |
| 197 | folder_id: &'a str, |
| 198 | expanded: bool, |
| 199 | ) -> BoxFuture<'a, Result<()>> { |
| 200 | Box::pin(async move { Ok(self.pins.set_folder_expanded(folder_id, expanded).await?) }) |
| 201 | } |
| 202 | |
| 203 | fn move_to_folder<'a>( |
| 204 | &'a self, |
| 205 | conversation_id: &'a str, |
| 206 | target_folder_id: &'a str, |
| 207 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> { |
| 208 | Box::pin(async move { |
| 209 | Ok(convert( |
| 210 | self.pins |
| 211 | .move_to_folder(conversation_id, target_folder_id) |
| 212 | .await?, |
| 213 | )) |
| 214 | }) |
| 215 | } |
| 216 | |
| 217 | fn remove_from_folder<'a>( |
| 218 | &'a self, |
| 219 | conversation_id: &'a str, |
| 220 | folder_id: &'a str, |
| 221 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> { |
| 222 | Box::pin(async move { |
| 223 | Ok(convert( |
| 224 | self.pins |
| 225 | .remove_from_folder(conversation_id, folder_id) |
| 226 | .await?, |
| 227 | )) |
| 228 | }) |
| 229 | } |
| 230 | |
| 231 | fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>> { |
| 232 | Box::pin(async move { |
| 233 | let folders = match &change { |
| 234 | FolderChange::Create { name } => self.pins.create_folder(name).await?, |
| 235 | FolderChange::Rename { folder_id, name } => { |
| 236 | self.pins.rename_folder(folder_id, name).await? |
| 237 | } |
| 238 | FolderChange::Delete { folder_id } => self.pins.delete_folder(folder_id).await?, |
| 239 | FolderChange::Move { |
| 240 | folder_id, |
| 241 | target_folder_id, |
| 242 | } => self.pins.move_folder(folder_id, target_folder_id).await?, |
| 243 | }; |
| 244 | Ok(convert(folders)) |
| 245 | }) |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> { |
| 250 | folders |
| 251 | .folders |
| 252 | .into_iter() |
| 253 | .map(|folder| ChatFolder { |
| 254 | id: folder.id, |
| 255 | name: folder.name, |
| 256 | kind: match folder.kind { |
| 257 | chatsvc::FolderKind::Favorites => FolderKind::Favorites, |
| 258 | chatsvc::FolderKind::UserCreated => FolderKind::UserCreated, |
| 259 | chatsvc::FolderKind::Recent => FolderKind::Recent, |
| 260 | chatsvc::FolderKind::Meeting => FolderKind::Meeting, |
| 261 | chatsvc::FolderKind::Muted => FolderKind::Muted, |
| 262 | }, |
| 263 | expanded: folder.expanded, |
| 264 | conversation_ids: folder.conversation_ids, |
| 265 | }) |
| 266 | .collect() |
| 267 | } |
| 268 | |
| 269 | fn stored_team_order(teams: &[store::SidebarTeam]) -> Vec<(String, i64)> { |
| 270 | teams |
| 271 | .iter() |
| 272 | .enumerate() |
| 273 | .map(|(position, team)| (team.team.id.clone(), position as i64)) |
| 274 | .collect() |
| 275 | } |
| 276 | |
| 277 | fn group_ids_by_thread(layout: &[chatsvc::TeamLayout]) -> HashMap<String, String> { |
| 278 | layout |
| 279 | .iter() |
| 280 | .filter_map(|team| Some((team.team_id.clone(), team.group_id.clone()?))) |
| 281 | .collect() |
| 282 | } |
| 283 | |
| 284 | fn order_by_group_id( |
| 285 | order: Vec<(String, i64)>, |
| 286 | group_ids: &HashMap<String, String>, |
| 287 | ) -> Vec<(String, i64)> { |
| 288 | order |
| 289 | .into_iter() |
| 290 | .map(|(team_id, position)| match group_ids.get(&team_id) { |
| 291 | Some(group_id) => (group_id.clone(), position), |
| 292 | None => (team_id, position), |
| 293 | }) |
| 294 | .collect() |
| 295 | } |
| 296 | |
| 297 | fn sort_teams_by_order(teams: &mut [TeamLayoutRecord], order: &[(String, i64)]) { |
| 298 | let positions: HashMap<&str, i64> = order |
| 299 | .iter() |
| 300 | .map(|(team_id, position)| (team_id.as_str(), *position)) |
| 301 | .collect(); |
| 302 | teams.sort_by_key(|team| { |
| 303 | positions |
| 304 | .get(team.team_id.as_str()) |
| 305 | .copied() |
| 306 | .unwrap_or(i64::MAX) |
| 307 | }); |
| 308 | } |
| 309 | |
| 310 | fn resolve_notifications( |
| 311 | channel: &chatsvc::ChannelLayout, |
| 312 | fallback: &HashMap<String, ChannelNotifications>, |
| 313 | ) -> ChannelNotifications { |
| 314 | channel |
| 315 | .notifications |
| 316 | .or_else(|| fallback.get(&channel.channel_id).copied()) |
| 317 | .unwrap_or_else(|| ChannelNotifications::from_followed(channel.followed)) |
| 318 | } |
| 319 | |
| 320 | fn notification_record(notifications: ChannelNotifications) -> store::ChannelNotifications { |
| 321 | store::ChannelNotifications { |
| 322 | level: match notifications.level { |
| 323 | ChannelNotificationLevel::BannerAndFeed => { |
| 324 | store::ChannelNotificationLevel::BannerAndFeed |
| 325 | } |
| 326 | ChannelNotificationLevel::Feed => store::ChannelNotificationLevel::Feed, |
| 327 | ChannelNotificationLevel::Off => store::ChannelNotificationLevel::Off, |
| 328 | }, |
| 329 | include_replies: notifications.include_replies, |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | pub(crate) fn chatsvc_notifications( |
| 334 | notifications: store::ChannelNotifications, |
| 335 | ) -> ChannelNotifications { |
| 336 | ChannelNotifications { |
| 337 | level: match notifications.level { |
| 338 | store::ChannelNotificationLevel::BannerAndFeed => { |
| 339 | ChannelNotificationLevel::BannerAndFeed |
| 340 | } |
| 341 | store::ChannelNotificationLevel::Feed => ChannelNotificationLevel::Feed, |
| 342 | store::ChannelNotificationLevel::Off => ChannelNotificationLevel::Off, |
| 343 | }, |
| 344 | include_replies: notifications.include_replies, |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | fn layout_record( |
| 349 | team: chatsvc::TeamLayout, |
| 350 | fallback: &HashMap<String, ChannelNotifications>, |
| 351 | ) -> TeamLayoutRecord { |
| 352 | TeamLayoutRecord { |
| 353 | team_id: team.group_id.unwrap_or(team.team_id), |
| 354 | hidden: team.hidden, |
| 355 | channels: team |
| 356 | .channels |
| 357 | .into_iter() |
| 358 | .map(|channel| ChannelLayoutRecord { |
| 359 | notifications: notification_record(resolve_notifications(&channel, fallback)), |
| 360 | channel_id: channel.channel_id, |
| 361 | general: channel.general, |
| 362 | hidden: channel.hidden, |
| 363 | tabs: channel |
| 364 | .tabs |
| 365 | .into_iter() |
| 366 | .map(|tab| ChannelTabRecord { |
| 367 | tab_id: tab.id, |
| 368 | name: tab.name, |
| 369 | definition_id: tab.definition_id, |
| 370 | open_url: tab.open_url, |
| 371 | }) |
| 372 | .collect(), |
| 373 | }) |
| 374 | .collect(), |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | const META_TEAM_LAYOUT_AT: &str = "team_layout_refreshed_at"; |
| 379 | const KIND_FAVORITES: &str = "Favorites"; |
| 380 | const KIND_USER_CREATED: &str = "UserCreated"; |
| 381 | const KIND_RECENT: &str = "RecentChats"; |
| 382 | const KIND_MEETING: &str = "MeetingChats"; |
| 383 | const KIND_MUTED: &str = "MutedChats"; |
| 384 | const META_MUTED_SECTION: &str = "chat_section_muted"; |
| 385 | const META_MEETING_SECTION: &str = "chat_section_meeting"; |
| 386 | const META_ADAPTIVE_RAIL: &str = "adaptive_rail"; |
| 387 | |
| 388 | fn to_record(folder: &ChatFolder) -> FolderRecord { |
| 389 | FolderRecord { |
| 390 | id: folder.id.clone(), |
| 391 | name: folder.name.clone(), |
| 392 | kind: match folder.kind { |
| 393 | FolderKind::Favorites => KIND_FAVORITES, |
| 394 | FolderKind::UserCreated => KIND_USER_CREATED, |
| 395 | FolderKind::Recent => KIND_RECENT, |
| 396 | FolderKind::Meeting => KIND_MEETING, |
| 397 | FolderKind::Muted => KIND_MUTED, |
| 398 | } |
| 399 | .to_owned(), |
| 400 | expanded: folder.expanded, |
| 401 | conversation_ids: folder.conversation_ids.clone(), |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | fn from_record(record: FolderRecord) -> ChatFolder { |
| 406 | ChatFolder { |
| 407 | id: record.id, |
| 408 | name: record.name, |
| 409 | kind: match record.kind.as_str() { |
| 410 | KIND_FAVORITES => FolderKind::Favorites, |
| 411 | KIND_RECENT => FolderKind::Recent, |
| 412 | KIND_MEETING => FolderKind::Meeting, |
| 413 | KIND_MUTED => FolderKind::Muted, |
| 414 | _ => FolderKind::UserCreated, |
| 415 | }, |
| 416 | expanded: record.expanded, |
| 417 | conversation_ids: record.conversation_ids, |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | pub fn stored_section_settings(store: &Store) -> ChatSectionSettings { |
| 422 | let read = |key: &str| { |
| 423 | store |
| 424 | .meta(key) |
| 425 | .ok() |
| 426 | .flatten() |
| 427 | .and_then(|value| value.parse().ok()) |
| 428 | }; |
| 429 | ChatSectionSettings { |
| 430 | muted: read(META_MUTED_SECTION), |
| 431 | meeting: read(META_MEETING_SECTION), |
| 432 | adaptive_rail: read(META_ADAPTIVE_RAIL), |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | pub fn store_section_settings(store: &Store, settings: &ChatSectionSettings) -> Result<()> { |
| 437 | for (key, value) in [ |
| 438 | (META_MUTED_SECTION, settings.muted), |
| 439 | (META_MEETING_SECTION, settings.meeting), |
| 440 | (META_ADAPTIVE_RAIL, settings.adaptive_rail), |
| 441 | ] { |
| 442 | let text = value.map(|enabled| enabled.to_string()).unwrap_or_default(); |
| 443 | store.set_meta(key, &text)?; |
| 444 | } |
| 445 | Ok(()) |
| 446 | } |
| 447 | |
| 448 | impl<R: Remote> SyncEngine<R> { |
| 449 | pub fn with_folder_source(mut self, source: Arc<dyn FolderSource>) -> Self { |
| 450 | self.folder_source = Some(source); |
| 451 | self |
| 452 | } |
| 453 | |
| 454 | pub fn chat_folders(&self) -> Result<Vec<ChatFolder>> { |
| 455 | Ok(self.store.folders()?.into_iter().map(from_record).collect()) |
| 456 | } |
| 457 | |
| 458 | pub fn pinned_channels(&self) -> Result<Vec<String>> { |
| 459 | Ok(self.store.pinned_channel_ids()?) |
| 460 | } |
| 461 | |
| 462 | pub async fn refresh_folders(&self) -> Result<()> { |
| 463 | let source = self.folder_source()?; |
| 464 | let folders = match tokio::try_join!(source.folders(), source.pinned_channels()) { |
| 465 | Ok((folders, channels)) => self.store_folders(&folders, &channels), |
| 466 | Err(error) => Err(error), |
| 467 | }; |
| 468 | self.refresh_section_settings(source).await; |
| 469 | let layout = self.refresh_team_layout(source).await; |
| 470 | match (folders, layout) { |
| 471 | (Err(folders_error), Err(layout_error)) => { |
| 472 | Err(Error::Folders(format!("{folders_error}; {layout_error}"))) |
| 473 | } |
| 474 | (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error), |
| 475 | (Ok(()), Ok(())) => Ok(()), |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) { |
| 480 | let outcome = match source.section_settings().await { |
| 481 | Ok(settings) => self.apply_section_settings(&settings).and_then(|()| { |
| 482 | match source.preferred_skin_tone() { |
| 483 | Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone), |
| 484 | None => Ok(()), |
| 485 | } |
| 486 | }), |
| 487 | Err(error) => Err(error), |
| 488 | }; |
| 489 | if let Err(error) = outcome { |
| 490 | self.report(format!("cannot refresh chat list settings: {error}")); |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | fn apply_section_settings(&self, settings: &ChatSectionSettings) -> Result<()> { |
| 495 | if stored_section_settings(&self.store) != *settings { |
| 496 | store_section_settings(&self.store, settings)?; |
| 497 | let _ = self.events.send(CoreEvent::FoldersChanged); |
| 498 | } |
| 499 | Ok(()) |
| 500 | } |
| 501 | |
| 502 | pub async fn set_section_enabled(&self, section: ChatSection, enabled: bool) -> Result<()> { |
| 503 | self.folder_source()? |
| 504 | .set_section_enabled(section, enabled) |
| 505 | .await |
| 506 | } |
| 507 | |
| 508 | pub async fn set_skin_tone(&self, tone: u8) -> Result<()> { |
| 509 | self.folder_source()?.set_skin_tone(tone).await?; |
| 510 | crate::skin_tone::store_account_skin_tone(&self.store, tone) |
| 511 | } |
| 512 | |
| 513 | pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> { |
| 514 | self.folder_source()? |
| 515 | .set_folder_expanded(folder_id, expanded) |
| 516 | .await |
| 517 | } |
| 518 | |
| 519 | async fn refresh_team_layout(&self, source: &Arc<dyn FolderSource>) -> Result<()> { |
| 520 | let last = self.store.meta_time(META_TEAM_LAYOUT_AT)?; |
| 521 | if last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval) { |
| 522 | return Ok(()); |
| 523 | } |
| 524 | let mut layout = source.team_layout().await?; |
| 525 | let before = self.store.sidebar()?.teams; |
| 526 | let order = match source.teams_order().await { |
| 527 | Ok(order) => order, |
| 528 | Err(error) => { |
| 529 | self.report(format!("cannot read the team order: {error}")); |
| 530 | stored_team_order(&before) |
| 531 | } |
| 532 | }; |
| 533 | sort_teams_by_order(&mut layout, &order); |
| 534 | self.store.replace_team_layout(&layout)?; |
| 535 | self.store.set_meta_time(META_TEAM_LAYOUT_AT, Utc::now())?; |
| 536 | if self.store.sidebar()?.teams != before { |
| 537 | let _ = self.events.send(CoreEvent::SidebarChanged); |
| 538 | } |
| 539 | Ok(()) |
| 540 | } |
| 541 | |
| 542 | pub async fn move_to_folder( |
| 543 | &self, |
| 544 | conversation_id: &str, |
| 545 | target_folder_id: &str, |
| 546 | ) -> Result<()> { |
| 547 | let folders = self |
| 548 | .folder_source()? |
| 549 | .move_to_folder(conversation_id, target_folder_id) |
| 550 | .await?; |
| 551 | self.store_folders(&folders, &self.store.pinned_channel_ids()?) |
| 552 | } |
| 553 | |
| 554 | pub async fn remove_from_folder(&self, conversation_id: &str, folder_id: &str) -> Result<()> { |
| 555 | let folders = self |
| 556 | .folder_source()? |
| 557 | .remove_from_folder(conversation_id, folder_id) |
| 558 | .await?; |
| 559 | self.store_folders(&folders, &self.store.pinned_channel_ids()?) |
| 560 | } |
| 561 | |
| 562 | pub async fn change_folders(&self, change: FolderChange) -> Result<()> { |
| 563 | let folders = self.folder_source()?.change_folders(change).await?; |
| 564 | self.store_folders(&folders, &self.store.pinned_channel_ids()?) |
| 565 | } |
| 566 | |
| 567 | fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> { |
| 568 | self.folder_source |
| 569 | .as_ref() |
| 570 | .ok_or(Error::Unsupported("chat folders without a folder source")) |
| 571 | } |
| 572 | |
| 573 | fn store_folders(&self, folders: &[ChatFolder], channel_ids: &[String]) -> Result<()> { |
| 574 | let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?); |
| 575 | let records: Vec<FolderRecord> = folders.iter().map(to_record).collect(); |
| 576 | self.store.replace_folders(&records, channel_ids)?; |
| 577 | if previous != (folders.to_vec(), channel_ids.to_vec()) { |
| 578 | let _ = self.events.send(CoreEvent::FoldersChanged); |
| 579 | } |
| 580 | Ok(()) |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | #[cfg(test)] |
| 585 | mod tests { |
| 586 | use super::*; |
| 587 | |
| 588 | fn channel( |
| 589 | notifications: Option<ChannelNotifications>, |
| 590 | followed: bool, |
| 591 | ) -> chatsvc::ChannelLayout { |
| 592 | chatsvc::ChannelLayout { |
| 593 | channel_id: "19:a".into(), |
| 594 | general: false, |
| 595 | hidden: false, |
| 596 | tabs: Vec::new(), |
| 597 | notifications, |
| 598 | followed, |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | fn level(level: ChannelNotificationLevel, include_replies: bool) -> ChannelNotifications { |
| 603 | ChannelNotifications { |
| 604 | level, |
| 605 | include_replies, |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | fn team(team_id: &str) -> TeamLayoutRecord { |
| 610 | TeamLayoutRecord { |
| 611 | team_id: team_id.into(), |
| 612 | hidden: false, |
| 613 | channels: Vec::new(), |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | fn team_ids(teams: &[TeamLayoutRecord]) -> Vec<&str> { |
| 618 | teams.iter().map(|team| team.team_id.as_str()).collect() |
| 619 | } |
| 620 | |
| 621 | #[test] |
| 622 | fn listed_teams_come_first_by_order_and_unlisted_follow_in_server_order() { |
| 623 | let mut teams = vec![team("x"), team("b"), team("y"), team("a"), team("z")]; |
| 624 | let order = vec![ |
| 625 | ("a".to_owned(), 0), |
| 626 | ("b".to_owned(), 1), |
| 627 | ("gone".to_owned(), 2), |
| 628 | ]; |
| 629 | sort_teams_by_order(&mut teams, &order); |
| 630 | assert_eq!(team_ids(&teams), ["a", "b", "x", "y", "z"]); |
| 631 | } |
| 632 | |
| 633 | #[test] |
| 634 | fn real_payloads_give_the_team_order_teams_web_shows() { |
| 635 | let fixture: Value = |
| 636 | serde_json::from_str(include_str!("../tests/fixtures/team_order.json")).unwrap(); |
| 637 | let layout = chatsvc::pins::parse_team_layout(&fixture["csaTeams"]).unwrap(); |
| 638 | let group_ids = group_ids_by_thread(&layout); |
| 639 | let order = order_by_group_id(parse_teams_order(&fixture["userProperties"]), &group_ids); |
| 640 | let mut records: Vec<TeamLayoutRecord> = layout |
| 641 | .into_iter() |
| 642 | .map(|team| layout_record(team, &HashMap::new())) |
| 643 | .collect(); |
| 644 | sort_teams_by_order(&mut records, &order); |
| 645 | let store = Store::open_in_memory().unwrap(); |
| 646 | let names: HashMap<String, String> = fixture["csaTeams"]["teams"] |
| 647 | .as_array() |
| 648 | .unwrap() |
| 649 | .iter() |
| 650 | .map(|team| { |
| 651 | let group_id = team["teamSiteInformation"]["groupId"].as_str().unwrap(); |
| 652 | let name = team["displayName"].as_str().unwrap(); |
| 653 | (group_id.to_owned(), name.to_owned()) |
| 654 | }) |
| 655 | .collect(); |
| 656 | let graph_teams: Vec<store::TeamRecord> = names |
| 657 | .iter() |
| 658 | .map(|(group_id, name)| store::TeamRecord { |
| 659 | id: group_id.clone(), |
| 660 | name: name.clone(), |
| 661 | }) |
| 662 | .collect(); |
| 663 | store.upsert_teams(&graph_teams).unwrap(); |
| 664 | store.replace_team_layout(&records).unwrap(); |
| 665 | |
| 666 | let shown: Vec<String> = store |
| 667 | .sidebar() |
| 668 | .unwrap() |
| 669 | .teams |
| 670 | .into_iter() |
| 671 | .filter(|team| !team.hidden) |
| 672 | .map(|team| team.team.id) |
| 673 | .collect(); |
| 674 | let expected: Vec<String> = fixture["teamsWebShownTeams"] |
| 675 | .as_array() |
| 676 | .unwrap() |
| 677 | .iter() |
| 678 | .map(|team| team["groupId"].as_str().unwrap().to_owned()) |
| 679 | .collect(); |
| 680 | assert_eq!(shown, expected); |
| 681 | } |
| 682 | |
| 683 | #[test] |
| 684 | fn an_empty_order_keeps_the_server_order() { |
| 685 | let mut teams = vec![team("c"), team("a"), team("b")]; |
| 686 | sort_teams_by_order(&mut teams, &[]); |
| 687 | assert_eq!(team_ids(&teams), ["c", "a", "b"]); |
| 688 | } |
| 689 | |
| 690 | #[test] |
| 691 | fn channel_value_beats_the_notification_service_beats_the_followed_flag() { |
| 692 | let off = level(ChannelNotificationLevel::Off, false); |
| 693 | let banner = level(ChannelNotificationLevel::BannerAndFeed, true); |
| 694 | let fallback = HashMap::from([("19:a".to_owned(), banner)]); |
| 695 | assert_eq!( |
| 696 | resolve_notifications(&channel(Some(off), true), &fallback), |
| 697 | off |
| 698 | ); |
| 699 | assert_eq!( |
| 700 | resolve_notifications(&channel(None, false), &fallback), |
| 701 | banner |
| 702 | ); |
| 703 | assert_eq!( |
| 704 | resolve_notifications(&channel(None, true), &HashMap::new()), |
| 705 | banner |
| 706 | ); |
| 707 | assert_eq!( |
| 708 | resolve_notifications(&channel(None, false), &HashMap::new()), |
| 709 | ChannelNotifications::default() |
| 710 | ); |
| 711 | } |
| 712 | } |