BlueGit

ict rusty-teams

Files

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

folders.rs

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