BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / folders.rs

folders.rs

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