BlueGit

ict rusty-teams

Files

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

folders.rs

folders.rs 15.1 KiB Download Raw
1use std::collections::HashMap;
2use std::future::Future;
3use std::pin::Pin;
4use std::sync::Arc;
5
6use chatsvc::{
7 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,
8 ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,
9};
10use chrono::Utc;
11use session::Session;
12use store::{ChannelLayoutRecord, ChannelTabRecord, FolderRecord, Store, TeamLayoutRecord};
13
14use crate::engine::SyncEngine;
15use crate::error::{Error, Result};
16use crate::events::CoreEvent;
17use crate::remote::Remote;
18
19pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum FolderKind {
23 Favorites,
24 UserCreated,
25 Recent,
26 Meeting,
27 Muted,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct ChatFolder {
32 pub id: String,
33 pub name: String,
34 pub kind: FolderKind,
35 pub expanded: bool,
36 pub conversation_ids: Vec<String>,
37}
38
39pub trait FolderSource: Send + Sync {
40 fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
41 fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>>;
42 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>>;
43 fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>>;
44 fn set_section_enabled(&self, section: ChatSection, enabled: bool)
45 -> BoxFuture<'_, Result<()>>;
46 fn set_folder_expanded<'a>(
47 &'a self,
48 folder_id: &'a str,
49 expanded: bool,
50 ) -> BoxFuture<'a, Result<()>>;
51 fn move_to_folder<'a>(
52 &'a self,
53 conversation_id: &'a str,
54 target_folder_id: &'a str,
55 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
56 fn remove_from_folder<'a>(
57 &'a self,
58 conversation_id: &'a str,
59 folder_id: &'a str,
60 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
61}
62
63pub struct ChatsvcFolderSource {
64 pins: Pins<SessionTransport>,
65 settings: UserSettings,
66 channel_settings: ChannelSettings,
67}
68
69impl ChatsvcFolderSource {
70 pub fn new(session: &Session) -> Self {
71 ChatsvcFolderSource {
72 pins: Pins::new(session),
73 settings: UserSettings::new(session),
74 channel_settings: ChannelSettings::new(session),
75 }
76 }
77}
78
79impl FolderSource for ChatsvcFolderSource {
80 fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>> {
81 Box::pin(async { Ok(convert(self.pins.folders().await?)) })
82 }
83
84 fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>> {
85 Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })
86 }
87
88 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
89 Box::pin(async {
90 let layout = self.pins.team_layout().await?;
91 let unknown: Vec<String> = layout
92 .iter()
93 .flat_map(|team| &team.channels)
94 .filter(|channel| channel.notifications.is_none())
95 .map(|channel| channel.channel_id.clone())
96 .collect();
97 let fallback = if unknown.is_empty() {
98 HashMap::new()
99 } else {
100 self.channel_settings
101 .fetch(&unknown)
102 .await
103 .unwrap_or_default()
104 };
105 Ok(layout
106 .into_iter()
107 .map(|team| layout_record(team, &fallback))
108 .collect())
109 })
110 }
111
112 fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> {
113 Box::pin(async { Ok(self.settings.chat_sections().await?) })
114 }
115
116 fn set_section_enabled(
117 &self,
118 section: ChatSection,
119 enabled: bool,
120 ) -> BoxFuture<'_, Result<()>> {
121 Box::pin(async move { Ok(self.settings.set_chat_section(section, enabled).await?) })
122 }
123
124 fn set_folder_expanded<'a>(
125 &'a self,
126 folder_id: &'a str,
127 expanded: bool,
128 ) -> BoxFuture<'a, Result<()>> {
129 Box::pin(async move { Ok(self.pins.set_folder_expanded(folder_id, expanded).await?) })
130 }
131
132 fn move_to_folder<'a>(
133 &'a self,
134 conversation_id: &'a str,
135 target_folder_id: &'a str,
136 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
137 Box::pin(async move {
138 Ok(convert(
139 self.pins
140 .move_to_folder(conversation_id, target_folder_id)
141 .await?,
142 ))
143 })
144 }
145
146 fn remove_from_folder<'a>(
147 &'a self,
148 conversation_id: &'a str,
149 folder_id: &'a str,
150 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> {
151 Box::pin(async move {
152 Ok(convert(
153 self.pins
154 .remove_from_folder(conversation_id, folder_id)
155 .await?,
156 ))
157 })
158 }
159}
160
161fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> {
162 folders
163 .folders
164 .into_iter()
165 .map(|folder| ChatFolder {
166 id: folder.id,
167 name: folder.name,
168 kind: match folder.kind {
169 chatsvc::FolderKind::Favorites => FolderKind::Favorites,
170 chatsvc::FolderKind::UserCreated => FolderKind::UserCreated,
171 chatsvc::FolderKind::Recent => FolderKind::Recent,
172 chatsvc::FolderKind::Meeting => FolderKind::Meeting,
173 chatsvc::FolderKind::Muted => FolderKind::Muted,
174 },
175 expanded: folder.expanded,
176 conversation_ids: folder.conversation_ids,
177 })
178 .collect()
179}
180
181fn resolve_notifications(
182 channel: &chatsvc::ChannelLayout,
183 fallback: &HashMap<String, ChannelNotifications>,
184) -> ChannelNotifications {
185 channel
186 .notifications
187 .or_else(|| fallback.get(&channel.channel_id).copied())
188 .unwrap_or_else(|| ChannelNotifications::from_followed(channel.followed))
189}
190
191fn notification_record(notifications: ChannelNotifications) -> store::ChannelNotifications {
192 store::ChannelNotifications {
193 level: match notifications.level {
194 ChannelNotificationLevel::BannerAndFeed => {
195 store::ChannelNotificationLevel::BannerAndFeed
196 }
197 ChannelNotificationLevel::Feed => store::ChannelNotificationLevel::Feed,
198 ChannelNotificationLevel::Off => store::ChannelNotificationLevel::Off,
199 },
200 include_replies: notifications.include_replies,
201 }
202}
203
204pub(crate) fn chatsvc_notifications(
205 notifications: store::ChannelNotifications,
206) -> ChannelNotifications {
207 ChannelNotifications {
208 level: match notifications.level {
209 store::ChannelNotificationLevel::BannerAndFeed => {
210 ChannelNotificationLevel::BannerAndFeed
211 }
212 store::ChannelNotificationLevel::Feed => ChannelNotificationLevel::Feed,
213 store::ChannelNotificationLevel::Off => ChannelNotificationLevel::Off,
214 },
215 include_replies: notifications.include_replies,
216 }
217}
218
219fn layout_record(
220 team: chatsvc::TeamLayout,
221 fallback: &HashMap<String, ChannelNotifications>,
222) -> TeamLayoutRecord {
223 TeamLayoutRecord {
224 team_id: team.team_id,
225 hidden: team.hidden,
226 channels: team
227 .channels
228 .into_iter()
229 .map(|channel| ChannelLayoutRecord {
230 notifications: notification_record(resolve_notifications(&channel, fallback)),
231 channel_id: channel.channel_id,
232 general: channel.general,
233 hidden: channel.hidden,
234 tabs: channel
235 .tabs
236 .into_iter()
237 .map(|tab| ChannelTabRecord {
238 tab_id: tab.id,
239 name: tab.name,
240 definition_id: tab.definition_id,
241 open_url: tab.open_url,
242 })
243 .collect(),
244 })
245 .collect(),
246 }
247}
248
249const META_TEAM_LAYOUT_AT: &str = "team_layout_refreshed_at";
250const KIND_FAVORITES: &str = "Favorites";
251const KIND_USER_CREATED: &str = "UserCreated";
252const KIND_RECENT: &str = "RecentChats";
253const KIND_MEETING: &str = "MeetingChats";
254const KIND_MUTED: &str = "MutedChats";
255const META_MUTED_SECTION: &str = "chat_section_muted";
256const META_MEETING_SECTION: &str = "chat_section_meeting";
257
258fn to_record(folder: &ChatFolder) -> FolderRecord {
259 FolderRecord {
260 id: folder.id.clone(),
261 name: folder.name.clone(),
262 kind: match folder.kind {
263 FolderKind::Favorites => KIND_FAVORITES,
264 FolderKind::UserCreated => KIND_USER_CREATED,
265 FolderKind::Recent => KIND_RECENT,
266 FolderKind::Meeting => KIND_MEETING,
267 FolderKind::Muted => KIND_MUTED,
268 }
269 .to_owned(),
270 expanded: folder.expanded,
271 conversation_ids: folder.conversation_ids.clone(),
272 }
273}
274
275fn from_record(record: FolderRecord) -> ChatFolder {
276 ChatFolder {
277 id: record.id,
278 name: record.name,
279 kind: match record.kind.as_str() {
280 KIND_FAVORITES => FolderKind::Favorites,
281 KIND_RECENT => FolderKind::Recent,
282 KIND_MEETING => FolderKind::Meeting,
283 KIND_MUTED => FolderKind::Muted,
284 _ => FolderKind::UserCreated,
285 },
286 expanded: record.expanded,
287 conversation_ids: record.conversation_ids,
288 }
289}
290
291pub fn stored_section_settings(store: &Store) -> ChatSectionSettings {
292 let read = |key: &str| {
293 store
294 .meta(key)
295 .ok()
296 .flatten()
297 .and_then(|value| value.parse().ok())
298 };
299 ChatSectionSettings {
300 muted: read(META_MUTED_SECTION),
301 meeting: read(META_MEETING_SECTION),
302 }
303}
304
305pub fn store_section_settings(store: &Store, settings: &ChatSectionSettings) -> Result<()> {
306 for (key, value) in [
307 (META_MUTED_SECTION, settings.muted),
308 (META_MEETING_SECTION, settings.meeting),
309 ] {
310 let text = value.map(|enabled| enabled.to_string()).unwrap_or_default();
311 store.set_meta(key, &text)?;
312 }
313 Ok(())
314}
315
316impl<R: Remote> SyncEngine<R> {
317 pub fn with_folder_source(mut self, source: Arc<dyn FolderSource>) -> Self {
318 self.folder_source = Some(source);
319 self
320 }
321
322 pub fn chat_folders(&self) -> Result<Vec<ChatFolder>> {
323 Ok(self.store.folders()?.into_iter().map(from_record).collect())
324 }
325
326 pub fn pinned_channels(&self) -> Result<Vec<String>> {
327 Ok(self.store.pinned_channel_ids()?)
328 }
329
330 pub async fn refresh_folders(&self) -> Result<()> {
331 let source = self.folder_source()?;
332 let (folders, channels) = tokio::try_join!(source.folders(), source.pinned_channels())?;
333 self.store_folders(&folders, &channels)?;
334 self.refresh_section_settings(source).await;
335 self.refresh_team_layout(source).await
336 }
337
338 async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {
339 let outcome = match source.section_settings().await {
340 Ok(settings) => self.apply_section_settings(&settings),
341 Err(error) => Err(error),
342 };
343 if let Err(error) = outcome {
344 self.report(format!("cannot refresh chat list settings: {error}"));
345 }
346 }
347
348 fn apply_section_settings(&self, settings: &ChatSectionSettings) -> Result<()> {
349 if stored_section_settings(&self.store) != *settings {
350 store_section_settings(&self.store, settings)?;
351 let _ = self.events.send(CoreEvent::FoldersChanged);
352 }
353 Ok(())
354 }
355
356 pub async fn set_section_enabled(&self, section: ChatSection, enabled: bool) -> Result<()> {
357 self.folder_source()?
358 .set_section_enabled(section, enabled)
359 .await
360 }
361
362 pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
363 self.folder_source()?
364 .set_folder_expanded(folder_id, expanded)
365 .await
366 }
367
368 async fn refresh_team_layout(&self, source: &Arc<dyn FolderSource>) -> Result<()> {
369 let last = self.store.meta_time(META_TEAM_LAYOUT_AT)?;
370 if last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval) {
371 return Ok(());
372 }
373 let layout = source.team_layout().await?;
374 let before = self.store.sidebar()?.teams;
375 self.store.replace_team_layout(&layout)?;
376 self.store.set_meta_time(META_TEAM_LAYOUT_AT, Utc::now())?;
377 if self.store.sidebar()?.teams != before {
378 let _ = self.events.send(CoreEvent::SidebarChanged);
379 }
380 Ok(())
381 }
382
383 pub async fn move_to_folder(
384 &self,
385 conversation_id: &str,
386 target_folder_id: &str,
387 ) -> Result<()> {
388 let folders = self
389 .folder_source()?
390 .move_to_folder(conversation_id, target_folder_id)
391 .await?;
392 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
393 }
394
395 pub async fn remove_from_folder(&self, conversation_id: &str, folder_id: &str) -> Result<()> {
396 let folders = self
397 .folder_source()?
398 .remove_from_folder(conversation_id, folder_id)
399 .await?;
400 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
401 }
402
403 fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
404 self.folder_source
405 .as_ref()
406 .ok_or(Error::Unsupported("chat folders without a folder source"))
407 }
408
409 fn store_folders(&self, folders: &[ChatFolder], channel_ids: &[String]) -> Result<()> {
410 let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);
411 let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();
412 self.store.replace_folders(&records, channel_ids)?;
413 if previous != (folders.to_vec(), channel_ids.to_vec()) {
414 let _ = self.events.send(CoreEvent::FoldersChanged);
415 }
416 Ok(())
417 }
418}
419
420#[cfg(test)]
421mod tests {
422 use super::*;
423
424 fn channel(
425 notifications: Option<ChannelNotifications>,
426 followed: bool,
427 ) -> chatsvc::ChannelLayout {
428 chatsvc::ChannelLayout {
429 channel_id: "19:a".into(),
430 general: false,
431 hidden: false,
432 tabs: Vec::new(),
433 notifications,
434 followed,
435 }
436 }
437
438 fn level(level: ChannelNotificationLevel, include_replies: bool) -> ChannelNotifications {
439 ChannelNotifications {
440 level,
441 include_replies,
442 }
443 }
444
445 #[test]
446 fn channel_value_beats_the_notification_service_beats_the_followed_flag() {
447 let off = level(ChannelNotificationLevel::Off, false);
448 let banner = level(ChannelNotificationLevel::BannerAndFeed, true);
449 let fallback = HashMap::from([("19:a".to_owned(), banner)]);
450 assert_eq!(
451 resolve_notifications(&channel(Some(off), true), &fallback),
452 off
453 );
454 assert_eq!(
455 resolve_notifications(&channel(None, false), &fallback),
456 banner
457 );
458 assert_eq!(
459 resolve_notifications(&channel(None, true), &HashMap::new()),
460 banner
461 );
462 assert_eq!(
463 resolve_notifications(&channel(None, false), &HashMap::new()),
464 ChannelNotifications::default()
465 );
466 }
467}