BlueGit

ict rusty-teams

Files

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

activity_sync.rs

activity_sync.rs 2.5 KiB Download Raw
1use std::sync::atomic::Ordering;
2
3use chatsvc::{ActivitySnapshot, MentionActivity, mentions_of};
4use chrono::Utc;
5use store::Store;
6
7use crate::engine::SyncEngine;
8use crate::error::Result;
9use crate::events::CoreEvent;
10use crate::remote::Remote;
11
12const META_ACTIVITY_FEED: &str = "activity_feed";
13
14pub fn stored_activity_feed(store: &Store) -> Option<ActivitySnapshot> {
15 let text = store.meta(META_ACTIVITY_FEED).ok().flatten()?;
16 serde_json::from_str(&text).ok()
17}
18
19fn store_activity_feed(store: &Store, snapshot: &ActivitySnapshot) -> Result<bool> {
20 if stored_activity_feed(store).as_ref() == Some(snapshot) {
21 return Ok(false);
22 }
23 let Ok(text) = serde_json::to_string(snapshot) else {
24 return Ok(false);
25 };
26 store.set_meta(META_ACTIVITY_FEED, &text)?;
27 Ok(true)
28}
29
30impl<R: Remote> SyncEngine<R> {
31 /// The server feed, stored for the Activity panel; its mentions feed the channel badges.
32 pub(crate) async fn refresh_activity_feed(&self) -> Result<Vec<MentionActivity>> {
33 let snapshot = self.remote.activity_feed().await?;
34 let mentions = mentions_of(&snapshot);
35 if store_activity_feed(&self.store, &snapshot)? {
36 let _ = self.events.send(CoreEvent::ActivityChanged);
37 }
38 Ok(mentions)
39 }
40
41 /// A push on the feed conversation: one refresh at a time, later pushes in the same burst ride along.
42 pub async fn refresh_activity(&self) {
43 if self.activity_refreshing.swap(true, Ordering::AcqRel) {
44 return;
45 }
46 if let Err(error) = self.refresh_activity_feed().await {
47 self.report(format!("cannot refresh the activity feed: {error}"));
48 }
49 self.activity_refreshing.store(false, Ordering::Release);
50 }
51
52 pub async fn mark_activity_read(&self, message_id: &str) -> Result<()> {
53 self.remote.mark_activity_read(message_id).await?;
54 self.update_stored_feed(|snapshot| {
55 snapshot.mark_read(message_id);
56 })
57 }
58
59 pub async fn mark_all_activity_read(&self) -> Result<()> {
60 let now_ms = Utc::now().timestamp_millis();
61 self.remote.mark_all_activity_read(now_ms).await?;
62 self.update_stored_feed(|snapshot| snapshot.mark_all_read(now_ms))
63 }
64
65 fn update_stored_feed(&self, change: impl FnOnce(&mut ActivitySnapshot)) -> Result<()> {
66 let Some(mut snapshot) = stored_activity_feed(&self.store) else {
67 return Ok(());
68 };
69 change(&mut snapshot);
70 store_activity_feed(&self.store, &snapshot)?;
71 Ok(())
72 }
73}