BlueGit

ict rusty-teams

Files

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

folders.rs

folders.rs 20.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::{parse_chat_sections, parse_skin_tone, parse_teams_order};
7use chatsvc::{
8 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,
9 ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,
10};
11use chrono::Utc;
12use serde_json::Value;
13use session::Session;
14use store::{ChannelLayoutRecord, ChannelTabRecord, FolderRecord, Store, TeamLayoutRecord};
15
16use crate::engine::SyncEngine;
17use crate::error::{Error, Result};
18use crate::events::CoreEvent;
19use crate::remote::Remote;
20
21pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum FolderKind {
25 Favorites,
26 UserCreated,
27 Recent,
28 Meeting,
29 Muted,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct ChatFolder {
34 pub id: String,
35 pub name: String,
36 pub kind: FolderKind,
37 pub expanded: bool,
38 pub conversation_ids: Vec<String>,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum FolderChange {
43 Create {
44 name: String,
45 },
46 Rename {
47 folder_id: String,
48 name: String,
49 },
50 Delete {
51 folder_id: String,
52 },
53 Move {
54 folder_id: String,
55 target_folder_id: String,
56 },
57}
58
59pub trait FolderSource: Send + Sync {
60 fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
61 fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>>;
62 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>>;
63 fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>>;
64 fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {
65 Box::pin(async { Ok(Vec::new()) })
66 }
67 fn preferred_skin_tone(&self) -> Option<u8> {
68 None
69 }
70 fn set_section_enabled(&self, section: ChatSection, enabled: bool)
71 -> BoxFuture<'_, Result<()>>;
72 fn set_folder_expanded<'a>(
73 &'a self,
74 folder_id: &'a str,
75 expanded: bool,
76 ) -> BoxFuture<'a, Result<()>>;
77 fn move_to_folder<'a>(
78 &'a self,
79 conversation_id: &'a str,
80 target_folder_id: &'a str,
81 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
82 fn remove_from_folder<'a>(
83 &'a self,
84 conversation_id: &'a str,
85 folder_id: &'a str,
86 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
87 fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
88}
89
90pub struct ChatsvcFolderSource {
91 pins: Pins<SessionTransport>,
92 settings: UserSettings,
93 channel_settings: ChannelSettings,
94 properties: Mutex<Option<Value>>,
95 skin_tone: Mutex<Option<u8>>,
96}
97
98impl ChatsvcFolderSource {
99 pub fn new(session: &Session) -> Self {
100 ChatsvcFolderSource {
101 pins: Pins::new(session),
102 settings: UserSettings::new(session),
103 channel_settings: ChannelSettings::new(session),
104 properties: Mutex::new(None),
105 skin_tone: Mutex::new(None),
106 }
107 }
108}
109
110impl FolderSource for ChatsvcFolderSource {
111 fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>> {
112 Box::pin(async { Ok(convert(self.pins.folders().await?)) })
113 }
114
115 fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>> {
116 Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })
117 }
118
119 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
120 Box::pin(async {
121 let layout = self.pins.team_layout().await?;
122 let unknown: Vec<String> = layout
123 .iter()
124 .flat_map(|team| &team.channels)
125 .filter(|channel| channel.notifications.is_none())
126 .map(|channel| channel.channel_id.clone())
127 .collect();
128 let fallback = if unknown.is_empty() {
129 HashMap::new()
130 } else {
131 self.channel_settings
132 .fetch(&unknown)
133 .await
134 .unwrap_or_default()
135 };
136 Ok(layout
137 .into_iter()
138 .map(|team| layout_record(team, &fallback))
139 .collect())
140 })
141 }
142
143 fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> {
144 Box::pin(async {
145 let properties = self.settings.properties().await?;
146 let sections = parse_chat_sections(&properties);
147 *self.skin_tone.lock().unwrap() = parse_skin_tone(&properties);
148 *self.properties.lock().unwrap() = Some(properties);
149 Ok(sections)
150 })
151 }
152
153 fn preferred_skin_tone(&self) -> Option<u8> {
154 *self.skin_tone.lock().unwrap()
155 }
156
157 fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {
158 Box::pin(async {
159 let cached = self.properties.lock().unwrap().take();
160 let properties = match cached {
161 Some(properties) => properties,
162 None => self.settings.properties().await?,
163 };
164 Ok(parse_teams_order(&properties))
165 })
166 }
167
168 fn set_section_enabled(
169 &self,
170 section: ChatSection,
171 enabled: bool,
172 ) -> BoxFuture<'_, Result<()>> {
173 Box::pin(async move { Ok(self.settings.set_chat_section(section, enabled).await?) })
174 }
175
176 fn set_folder_expanded<'a>(
177 &'a self,
178 folder_id: &'a str,
179 expanded: bool,
180 ) -> BoxFuture<'a, Result<()>> {
181 Box::pin(async move { Ok(self.pins.set_folder_expanded(folder_id, expanded).await?) })
182 }
183
184 fn move_to_folder<'a>(
185 &'a self,
186 conversation_id: &'a str,
187 target_folder_id: &'a str,
188 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
189 Box::pin(async move {
190 Ok(convert(
191 self.pins
192 .move_to_folder(conversation_id, target_folder_id)
193 .await?,
194 ))
195 })
196 }
197
198 fn remove_from_folder<'a>(
199 &'a self,
200 conversation_id: &'a str,
201 folder_id: &'a str,
202 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
203 Box::pin(async move {
204 Ok(convert(
205 self.pins
206 .remove_from_folder(conversation_id, folder_id)
207 .await?,
208 ))
209 })
210 }
211
212 fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>> {
213 Box::pin(async move {
214 let folders = match &change {
215 FolderChange::Create { name } => self.pins.create_folder(name).await?,
216 FolderChange::Rename { folder_id, name } => {
217 self.pins.rename_folder(folder_id, name).await?
218 }
219 FolderChange::Delete { folder_id } => self.pins.delete_folder(folder_id).await?,
220 FolderChange::Move {
221 folder_id,
222 target_folder_id,
223 } => self.pins.move_folder(folder_id, target_folder_id).await?,
224 };
225 Ok(convert(folders))
226 })
227 }
228}
229
230fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> {
231 folders
232 .folders
233 .into_iter()
234 .map(|folder| ChatFolder {
235 id: folder.id,
236 name: folder.name,
237 kind: match folder.kind {
238 chatsvc::FolderKind::Favorites => FolderKind::Favorites,
239 chatsvc::FolderKind::UserCreated => FolderKind::UserCreated,
240 chatsvc::FolderKind::Recent => FolderKind::Recent,
241 chatsvc::FolderKind::Meeting => FolderKind::Meeting,
242 chatsvc::FolderKind::Muted => FolderKind::Muted,
243 },
244 expanded: folder.expanded,
245 conversation_ids: folder.conversation_ids,
246 })
247 .collect()
248}
249
250fn stored_team_order(teams: &[store::SidebarTeam]) -> Vec<(String, i64)> {
251 teams
252 .iter()
253 .enumerate()
254 .map(|(position, team)| (team.team.id.clone(), position as i64))
255 .collect()
256}
257
258fn sort_teams_by_order(teams: &mut [TeamLayoutRecord], order: &[(String, i64)]) {
259 let positions: HashMap<&str, i64> = order
260 .iter()
261 .map(|(team_id, position)| (team_id.as_str(), *position))
262 .collect();
263 teams.sort_by_key(|team| {
264 positions
265 .get(team.team_id.as_str())
266 .copied()
267 .unwrap_or(i64::MAX)
268 });
269}
270
271fn resolve_notifications(
272 channel: &chatsvc::ChannelLayout,
273 fallback: &HashMap<String, ChannelNotifications>,
274) -> ChannelNotifications {
275 channel
276 .notifications
277 .or_else(|| fallback.get(&channel.channel_id).copied())
278 .unwrap_or_else(|| ChannelNotifications::from_followed(channel.followed))
279}
280
281fn notification_record(notifications: ChannelNotifications) -> store::ChannelNotifications {
282 store::ChannelNotifications {
283 level: match notifications.level {
284 ChannelNotificationLevel::BannerAndFeed => {
285 store::ChannelNotificationLevel::BannerAndFeed
286 }
287 ChannelNotificationLevel::Feed => store::ChannelNotificationLevel::Feed,
288 ChannelNotificationLevel::Off => store::ChannelNotificationLevel::Off,
289 },
290 include_replies: notifications.include_replies,
291 }
292}
293
294pub(crate) fn chatsvc_notifications(
295 notifications: store::ChannelNotifications,
296) -> ChannelNotifications {
297 ChannelNotifications {
298 level: match notifications.level {
299 store::ChannelNotificationLevel::BannerAndFeed => {
300 ChannelNotificationLevel::BannerAndFeed
301 }
302 store::ChannelNotificationLevel::Feed => ChannelNotificationLevel::Feed,
303 store::ChannelNotificationLevel::Off => ChannelNotificationLevel::Off,
304 },
305 include_replies: notifications.include_replies,
306 }
307}
308
309fn layout_record(
310 team: chatsvc::TeamLayout,
311 fallback: &HashMap<String, ChannelNotifications>,
312) -> TeamLayoutRecord {
313 TeamLayoutRecord {
314 team_id: team.team_id,
315 hidden: team.hidden,
316 channels: team
317 .channels
318 .into_iter()
319 .map(|channel| ChannelLayoutRecord {
320 notifications: notification_record(resolve_notifications(&channel, fallback)),
321 channel_id: channel.channel_id,
322 general: channel.general,
323 hidden: channel.hidden,
324 tabs: channel
325 .tabs
326 .into_iter()
327 .map(|tab| ChannelTabRecord {
328 tab_id: tab.id,
329 name: tab.name,
330 definition_id: tab.definition_id,
331 open_url: tab.open_url,
332 })
333 .collect(),
334 })
335 .collect(),
336 }
337}
338
339const META_TEAM_LAYOUT_AT: &str = "team_layout_refreshed_at";
340const KIND_FAVORITES: &str = "Favorites";
341const KIND_USER_CREATED: &str = "UserCreated";
342const KIND_RECENT: &str = "RecentChats";
343const KIND_MEETING: &str = "MeetingChats";
344const KIND_MUTED: &str = "MutedChats";
345const META_MUTED_SECTION: &str = "chat_section_muted";
346const META_MEETING_SECTION: &str = "chat_section_meeting";
347
348fn to_record(folder: &ChatFolder) -> FolderRecord {
349 FolderRecord {
350 id: folder.id.clone(),
351 name: folder.name.clone(),
352 kind: match folder.kind {
353 FolderKind::Favorites => KIND_FAVORITES,
354 FolderKind::UserCreated => KIND_USER_CREATED,
355 FolderKind::Recent => KIND_RECENT,
356 FolderKind::Meeting => KIND_MEETING,
357 FolderKind::Muted => KIND_MUTED,
358 }
359 .to_owned(),
360 expanded: folder.expanded,
361 conversation_ids: folder.conversation_ids.clone(),
362 }
363}
364
365fn from_record(record: FolderRecord) -> ChatFolder {
366 ChatFolder {
367 id: record.id,
368 name: record.name,
369 kind: match record.kind.as_str() {
370 KIND_FAVORITES => FolderKind::Favorites,
371 KIND_RECENT => FolderKind::Recent,
372 KIND_MEETING => FolderKind::Meeting,
373 KIND_MUTED => FolderKind::Muted,
374 _ => FolderKind::UserCreated,
375 },
376 expanded: record.expanded,
377 conversation_ids: record.conversation_ids,
378 }
379}
380
381pub fn stored_section_settings(store: &Store) -> ChatSectionSettings {
382 let read = |key: &str| {
383 store
384 .meta(key)
385 .ok()
386 .flatten()
387 .and_then(|value| value.parse().ok())
388 };
389 ChatSectionSettings {
390 muted: read(META_MUTED_SECTION),
391 meeting: read(META_MEETING_SECTION),
392 }
393}
394
395pub fn store_section_settings(store: &Store, settings: &ChatSectionSettings) -> Result<()> {
396 for (key, value) in [
397 (META_MUTED_SECTION, settings.muted),
398 (META_MEETING_SECTION, settings.meeting),
399 ] {
400 let text = value.map(|enabled| enabled.to_string()).unwrap_or_default();
401 store.set_meta(key, &text)?;
402 }
403 Ok(())
404}
405
406impl<R: Remote> SyncEngine<R> {
407 pub fn with_folder_source(mut self, source: Arc<dyn FolderSource>) -> Self {
408 self.folder_source = Some(source);
409 self
410 }
411
412 pub fn chat_folders(&self) -> Result<Vec<ChatFolder>> {
413 Ok(self.store.folders()?.into_iter().map(from_record).collect())
414 }
415
416 pub fn pinned_channels(&self) -> Result<Vec<String>> {
417 Ok(self.store.pinned_channel_ids()?)
418 }
419
420 pub async fn refresh_folders(&self) -> Result<()> {
421 let source = self.folder_source()?;
422 let folders = match tokio::try_join!(source.folders(), source.pinned_channels()) {
423 Ok((folders, channels)) => self.store_folders(&folders, &channels),
424 Err(error) => Err(error),
425 };
426 self.refresh_section_settings(source).await;
427 let layout = self.refresh_team_layout(source).await;
428 match (folders, layout) {
429 (Err(folders_error), Err(layout_error)) => {
430 Err(Error::Folders(format!("{folders_error}; {layout_error}")))
431 }
432 (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
433 (Ok(()), Ok(())) => Ok(()),
434 }
435 }
436
437 async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {
438 let outcome = match source.section_settings().await {
439 Ok(settings) => self.apply_section_settings(&settings).and_then(|()| {
440 match source.preferred_skin_tone() {
441 Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone),
442 None => Ok(()),
443 }
444 }),
445 Err(error) => Err(error),
446 };
447 if let Err(error) = outcome {
448 self.report(format!("cannot refresh chat list settings: {error}"));
449 }
450 }
451
452 fn apply_section_settings(&self, settings: &ChatSectionSettings) -> Result<()> {
453 if stored_section_settings(&self.store) != *settings {
454 store_section_settings(&self.store, settings)?;
455 let _ = self.events.send(CoreEvent::FoldersChanged);
456 }
457 Ok(())
458 }
459
460 pub async fn set_section_enabled(&self, section: ChatSection, enabled: bool) -> Result<()> {
461 self.folder_source()?
462 .set_section_enabled(section, enabled)
463 .await
464 }
465
466 pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
467 self.folder_source()?
468 .set_folder_expanded(folder_id, expanded)
469 .await
470 }
471
472 async fn refresh_team_layout(&self, source: &Arc<dyn FolderSource>) -> Result<()> {
473 let last = self.store.meta_time(META_TEAM_LAYOUT_AT)?;
474 if last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval) {
475 return Ok(());
476 }
477 let mut layout = source.team_layout().await?;
478 let before = self.store.sidebar()?.teams;
479 let order = match source.teams_order().await {
480 Ok(order) => order,
481 Err(error) => {
482 self.report(format!("cannot read the team order: {error}"));
483 stored_team_order(&before)
484 }
485 };
486 sort_teams_by_order(&mut layout, &order);
487 self.store.replace_team_layout(&layout)?;
488 self.store.set_meta_time(META_TEAM_LAYOUT_AT, Utc::now())?;
489 if self.store.sidebar()?.teams != before {
490 let _ = self.events.send(CoreEvent::SidebarChanged);
491 }
492 Ok(())
493 }
494
495 pub async fn move_to_folder(
496 &self,
497 conversation_id: &str,
498 target_folder_id: &str,
499 ) -> Result<()> {
500 let folders = self
501 .folder_source()?
502 .move_to_folder(conversation_id, target_folder_id)
503 .await?;
504 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
505 }
506
507 pub async fn remove_from_folder(&self, conversation_id: &str, folder_id: &str) -> Result<()> {
508 let folders = self
509 .folder_source()?
510 .remove_from_folder(conversation_id, folder_id)
511 .await?;
512 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
513 }
514
515 pub async fn change_folders(&self, change: FolderChange) -> Result<()> {
516 let folders = self.folder_source()?.change_folders(change).await?;
517 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
518 }
519
520 fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
521 self.folder_source
522 .as_ref()
523 .ok_or(Error::Unsupported("chat folders without a folder source"))
524 }
525
526 fn store_folders(&self, folders: &[ChatFolder], channel_ids: &[String]) -> Result<()> {
527 let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);
528 let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();
529 self.store.replace_folders(&records, channel_ids)?;
530 if previous != (folders.to_vec(), channel_ids.to_vec()) {
531 let _ = self.events.send(CoreEvent::FoldersChanged);
532 }
533 Ok(())
534 }
535}
536
537#[cfg(test)]
538mod tests {
539 use super::*;
540
541 fn channel(
542 notifications: Option<ChannelNotifications>,
543 followed: bool,
544 ) -> chatsvc::ChannelLayout {
545 chatsvc::ChannelLayout {
546 channel_id: "19:a".into(),
547 general: false,
548 hidden: false,
549 tabs: Vec::new(),
550 notifications,
551 followed,
552 }
553 }
554
555 fn level(level: ChannelNotificationLevel, include_replies: bool) -> ChannelNotifications {
556 ChannelNotifications {
557 level,
558 include_replies,
559 }
560 }
561
562 fn team(team_id: &str) -> TeamLayoutRecord {
563 TeamLayoutRecord {
564 team_id: team_id.into(),
565 hidden: false,
566 channels: Vec::new(),
567 }
568 }
569
570 fn team_ids(teams: &[TeamLayoutRecord]) -> Vec<&str> {
571 teams.iter().map(|team| team.team_id.as_str()).collect()
572 }
573
574 #[test]
575 fn listed_teams_come_first_by_order_and_unlisted_follow_in_server_order() {
576 let mut teams = vec![team("x"), team("b"), team("y"), team("a"), team("z")];
577 let order = vec![
578 ("a".to_owned(), 0),
579 ("b".to_owned(), 1),
580 ("gone".to_owned(), 2),
581 ];
582 sort_teams_by_order(&mut teams, &order);
583 assert_eq!(team_ids(&teams), ["a", "b", "x", "y", "z"]);
584 }
585
586 #[test]
587 fn an_empty_order_keeps_the_server_order() {
588 let mut teams = vec![team("c"), team("a"), team("b")];
589 sort_teams_by_order(&mut teams, &[]);
590 assert_eq!(team_ids(&teams), ["c", "a", "b"]);
591 }
592
593 #[test]
594 fn channel_value_beats_the_notification_service_beats_the_followed_flag() {
595 let off = level(ChannelNotificationLevel::Off, false);
596 let banner = level(ChannelNotificationLevel::BannerAndFeed, true);
597 let fallback = HashMap::from([("19:a".to_owned(), banner)]);
598 assert_eq!(
599 resolve_notifications(&channel(Some(off), true), &fallback),
600 off
601 );
602 assert_eq!(
603 resolve_notifications(&channel(None, false), &fallback),
604 banner
605 );
606 assert_eq!(
607 resolve_notifications(&channel(None, true), &HashMap::new()),
608 banner
609 );
610 assert_eq!(
611 resolve_notifications(&channel(None, false), &HashMap::new()),
612 ChannelNotifications::default()
613 );
614 }
615}