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