BlueGit

ict rusty-teams

Files

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

folders.rs

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