BlueGit

ict rusty-teams

Files

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

hidden_chats.rs

hidden_chats.rs 9.5 KiB Download Raw
1use std::collections::HashMap;
2
3use chatsvc::ConversationState;
4use chrono::{DateTime, Duration, TimeZone, Utc};
5use graph::Chat;
6use store::Store;
7
8use crate::engine::SyncEngine;
9use crate::error::Result;
10use crate::mapping::graph_hidden;
11use crate::remote::Remote;
12
13const META_LOCALLY_HIDDEN: &str = "locally_hidden_chats";
14const HIDE_PREFIX: &str = "hide";
15const UNHIDE_PREFIX: &str = "unhide";
16
17fn unhide_override_window() -> Duration {
18 Duration::minutes(10)
19}
20
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
22pub(crate) struct LocallyHidden {
23 hidden_after: HashMap<String, DateTime<Utc>>,
24 unhidden_at: HashMap<String, DateTime<Utc>>,
25}
26
27impl LocallyHidden {
28 pub(crate) fn load(store: &Store) -> Self {
29 let text = store
30 .meta(META_LOCALLY_HIDDEN)
31 .ok()
32 .flatten()
33 .unwrap_or_default();
34 let mut locally = LocallyHidden::default();
35 for line in text.lines() {
36 let mut fields = line.splitn(3, '\t');
37 let (Some(prefix), Some(chat_id), Some(millis)) =
38 (fields.next(), fields.next(), fields.next())
39 else {
40 continue;
41 };
42 let Some(at) = millis
43 .parse()
44 .ok()
45 .and_then(|millis| Utc.timestamp_millis_opt(millis).single())
46 else {
47 continue;
48 };
49 match prefix {
50 HIDE_PREFIX => locally.hidden_after.insert(chat_id.to_owned(), at),
51 UNHIDE_PREFIX => locally.unhidden_at.insert(chat_id.to_owned(), at),
52 _ => None,
53 };
54 }
55 locally
56 }
57
58 pub(crate) fn save(&self, store: &Store) -> Result<()> {
59 let mut lines: Vec<String> = [
60 (HIDE_PREFIX, &self.hidden_after),
61 (UNHIDE_PREFIX, &self.unhidden_at),
62 ]
63 .into_iter()
64 .flat_map(|(prefix, entries)| {
65 entries
66 .iter()
67 .map(move |(chat_id, at)| format!("{prefix}\t{chat_id}\t{}", at.timestamp_millis()))
68 })
69 .collect();
70 lines.sort_unstable();
71 store.set_meta(META_LOCALLY_HIDDEN, &lines.join("\n"))?;
72 Ok(())
73 }
74
75 pub(crate) fn hide(&mut self, chat_id: &str, last_message_at: DateTime<Utc>) {
76 self.unhidden_at.remove(chat_id);
77 self.hidden_after
78 .insert(chat_id.to_owned(), last_message_at);
79 }
80
81 pub(crate) fn unhide(&mut self, chat_id: &str, now: DateTime<Utc>) {
82 self.hidden_after.remove(chat_id);
83 self.unhidden_at.insert(chat_id.to_owned(), now);
84 }
85
86 fn unhide_override_active(&self, chat_id: &str, now: DateTime<Utc>) -> bool {
87 self.unhidden_at
88 .get(chat_id)
89 .is_some_and(|at| now - *at < unhide_override_window())
90 }
91
92 pub(crate) fn reported_hidden(&mut self, chat_id: &str, now: DateTime<Utc>) -> bool {
93 if self.unhide_override_active(chat_id, now) {
94 return false;
95 }
96 self.hidden_after.remove(chat_id);
97 true
98 }
99}
100
101pub(crate) fn resolve_hidden(
102 chat: &Chat,
103 states: &HashMap<String, ConversationState>,
104 locally: &mut LocallyHidden,
105 now: DateTime<Utc>,
106) -> bool {
107 let reported = states.get(&chat.id).and_then(|state| state.hidden);
108 if locally.unhidden_at.contains_key(&chat.id) {
109 if reported == Some(false) || !locally.unhide_override_active(&chat.id, now) {
110 locally.unhidden_at.remove(&chat.id);
111 } else {
112 return false;
113 }
114 }
115 if reported == Some(true) {
116 locally.hidden_after.remove(&chat.id);
117 return true;
118 }
119 if let Some(hidden_after) = locally.hidden_after.get(&chat.id).copied() {
120 if chat
121 .last_message_time()
122 .is_some_and(|newest| newest > hidden_after)
123 {
124 locally.hidden_after.remove(&chat.id);
125 return false;
126 }
127 return true;
128 }
129 reported.unwrap_or_else(|| graph_hidden(chat))
130}
131
132impl<R: Remote> SyncEngine<R> {
133 pub(crate) fn with_locally_hidden<T>(
134 &self,
135 change: impl FnOnce(&mut LocallyHidden) -> T,
136 ) -> Result<T> {
137 let _guard = self.locally_hidden_lock.lock().unwrap();
138 let mut locally = LocallyHidden::load(&self.store);
139 let before = locally.clone();
140 let result = change(&mut locally);
141 if locally != before {
142 locally.save(&self.store)?;
143 }
144 Ok(result)
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use serde_json::json;
151
152 use super::*;
153
154 fn at(text: &str) -> DateTime<Utc> {
155 text.parse().unwrap()
156 }
157
158 fn chat(last_message: Option<&str>, graph_hidden: bool) -> Chat {
159 serde_json::from_value(json!({
160 "id": "19:a",
161 "chatType": "meeting",
162 "viewpoint": {"isHidden": graph_hidden},
163 "lastMessagePreview": last_message.map(|at| json!({"id": "1", "createdDateTime": at})),
164 }))
165 .unwrap()
166 }
167
168 fn states(hidden: Option<bool>) -> HashMap<String, ConversationState> {
169 HashMap::from([(
170 "19:a".to_owned(),
171 ConversationState {
172 id: "19:a".to_owned(),
173 muted: false,
174 hidden,
175 read: chatsvc::ReadHorizon::default(),
176 notification_settings: None,
177 },
178 )])
179 }
180
181 fn hidden_after(text: &str) -> LocallyHidden {
182 let mut locally = LocallyHidden::default();
183 locally.hide("19:a", at(text));
184 locally
185 }
186
187 fn now() -> DateTime<Utc> {
188 at("2030-01-01T12:00:00Z")
189 }
190
191 #[test]
192 fn chatsvc_visible_beats_the_graph_hidden_flag() {
193 let mut locally = LocallyHidden::default();
194 let chat = chat(None, true);
195 assert!(!resolve_hidden(
196 &chat,
197 &states(Some(false)),
198 &mut locally,
199 now()
200 ));
201 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally, now()));
202 }
203
204 #[test]
205 fn a_local_hide_survives_a_chatsvc_that_still_says_visible() {
206 let mut locally = hidden_after("2026-10-10T10:00:00Z");
207 let chat = chat(Some("2026-10-10T09:00:00Z"), false);
208 assert!(resolve_hidden(
209 &chat,
210 &states(Some(false)),
211 &mut locally,
212 now()
213 ));
214 assert_eq!(locally, hidden_after("2026-10-10T10:00:00Z"));
215 }
216
217 #[test]
218 fn only_a_strictly_newer_message_unhides() {
219 let mut locally = hidden_after("2026-10-10T10:00:00Z");
220 let same = chat(Some("2026-10-10T10:00:00Z"), false);
221 assert!(resolve_hidden(
222 &same,
223 &states(Some(false)),
224 &mut locally,
225 now()
226 ));
227 let newer = chat(Some("2026-10-10T10:00:01Z"), false);
228 assert!(!resolve_hidden(
229 &newer,
230 &states(Some(false)),
231 &mut locally,
232 now()
233 ));
234 assert_eq!(locally, LocallyHidden::default());
235 }
236
237 #[test]
238 fn the_hide_marker_is_the_servers_message_time_so_clock_skew_does_not_matter() {
239 let mut locally = hidden_after("2026-10-10T10:00:00Z");
240 let chat = chat(Some("2026-10-10T10:00:30Z"), false);
241 let skewed_now = at("2026-10-10T09:00:00Z");
242 assert!(!resolve_hidden(
243 &chat,
244 &states(Some(false)),
245 &mut locally,
246 skewed_now
247 ));
248 }
249
250 #[test]
251 fn chatsvc_reporting_hidden_takes_over_and_drops_the_local_entry() {
252 let mut locally = hidden_after("2026-10-10T10:00:00Z");
253 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
254 assert!(resolve_hidden(
255 &chat,
256 &states(Some(true)),
257 &mut locally,
258 now()
259 ));
260 assert_eq!(locally, LocallyHidden::default());
261 }
262
263 #[test]
264 fn a_local_unhide_overrides_a_reported_hide_until_chatsvc_catches_up_or_time_runs_out() {
265 let chat = chat(None, false);
266 let mut locally = LocallyHidden::default();
267 locally.unhide("19:a", now());
268 assert!(!resolve_hidden(
269 &chat,
270 &states(Some(true)),
271 &mut locally,
272 now()
273 ));
274 assert!(!resolve_hidden(
275 &chat,
276 &states(Some(true)),
277 &mut locally,
278 now() + Duration::minutes(9)
279 ));
280 assert!(resolve_hidden(
281 &chat,
282 &states(Some(true)),
283 &mut locally,
284 now() + Duration::minutes(11)
285 ));
286 assert_eq!(locally, LocallyHidden::default());
287
288 locally.unhide("19:a", now());
289 assert!(!resolve_hidden(
290 &chat,
291 &states(Some(false)),
292 &mut locally,
293 now()
294 ));
295 assert_eq!(locally, LocallyHidden::default());
296 }
297
298 #[test]
299 fn a_reported_hide_for_any_chat_drops_its_local_entry_unless_an_unhide_is_fresh() {
300 let mut locally = hidden_after("2026-10-10T10:00:00Z");
301 assert!(locally.reported_hidden("19:a", now()));
302 assert_eq!(locally, LocallyHidden::default());
303
304 locally.unhide("19:a", now());
305 assert!(!locally.reported_hidden("19:a", now()));
306 assert!(locally.reported_hidden("19:a", now() + Duration::minutes(11)));
307 }
308
309 #[test]
310 fn entries_round_trip_through_the_store() {
311 let store = Store::open_in_memory().unwrap();
312 let mut locally = hidden_after("2026-10-10T10:00:00Z");
313 locally.unhide("19:b", at("2026-10-10T11:00:00Z"));
314 locally.save(&store).unwrap();
315 assert_eq!(LocallyHidden::load(&store), locally);
316 }
317}