BlueGit

ict rusty-teams

Files

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

folders.rs

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