BlueGit

ict rusty-teams

Files

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

folders.rs

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