BlueGit

ict rusty-teams

Files

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

folders.rs

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