BlueGit

ict rusty-teams

Files

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

hidden_chats.rs

hidden_chats.rs 9.4 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 },
177 )])
178 }
179
180 fn hidden_after(text: &str) -> LocallyHidden {
181 let mut locally = LocallyHidden::default();
182 locally.hide("19:a", at(text));
183 locally
184 }
185
186 fn now() -> DateTime<Utc> {
187 at("2030-01-01T12:00:00Z")
188 }
189
190 #[test]
191 fn chatsvc_visible_beats_the_graph_hidden_flag() {
192 let mut locally = LocallyHidden::default();
193 let chat = chat(None, true);
194 assert!(!resolve_hidden(
195 &chat,
196 &states(Some(false)),
197 &mut locally,
198 now()
199 ));
200 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally, now()));
201 }
202
203 #[test]
204 fn a_local_hide_survives_a_chatsvc_that_still_says_visible() {
205 let mut locally = hidden_after("2026-10-10T10:00:00Z");
206 let chat = chat(Some("2026-10-10T09:00:00Z"), false);
207 assert!(resolve_hidden(
208 &chat,
209 &states(Some(false)),
210 &mut locally,
211 now()
212 ));
213 assert_eq!(locally, hidden_after("2026-10-10T10:00:00Z"));
214 }
215
216 #[test]
217 fn only_a_strictly_newer_message_unhides() {
218 let mut locally = hidden_after("2026-10-10T10:00:00Z");
219 let same = chat(Some("2026-10-10T10:00:00Z"), false);
220 assert!(resolve_hidden(
221 &same,
222 &states(Some(false)),
223 &mut locally,
224 now()
225 ));
226 let newer = chat(Some("2026-10-10T10:00:01Z"), false);
227 assert!(!resolve_hidden(
228 &newer,
229 &states(Some(false)),
230 &mut locally,
231 now()
232 ));
233 assert_eq!(locally, LocallyHidden::default());
234 }
235
236 #[test]
237 fn the_hide_marker_is_the_servers_message_time_so_clock_skew_does_not_matter() {
238 let mut locally = hidden_after("2026-10-10T10:00:00Z");
239 let chat = chat(Some("2026-10-10T10:00:30Z"), false);
240 let skewed_now = at("2026-10-10T09:00:00Z");
241 assert!(!resolve_hidden(
242 &chat,
243 &states(Some(false)),
244 &mut locally,
245 skewed_now
246 ));
247 }
248
249 #[test]
250 fn chatsvc_reporting_hidden_takes_over_and_drops_the_local_entry() {
251 let mut locally = hidden_after("2026-10-10T10:00:00Z");
252 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
253 assert!(resolve_hidden(
254 &chat,
255 &states(Some(true)),
256 &mut locally,
257 now()
258 ));
259 assert_eq!(locally, LocallyHidden::default());
260 }
261
262 #[test]
263 fn a_local_unhide_overrides_a_reported_hide_until_chatsvc_catches_up_or_time_runs_out() {
264 let chat = chat(None, false);
265 let mut locally = LocallyHidden::default();
266 locally.unhide("19:a", now());
267 assert!(!resolve_hidden(
268 &chat,
269 &states(Some(true)),
270 &mut locally,
271 now()
272 ));
273 assert!(!resolve_hidden(
274 &chat,
275 &states(Some(true)),
276 &mut locally,
277 now() + Duration::minutes(9)
278 ));
279 assert!(resolve_hidden(
280 &chat,
281 &states(Some(true)),
282 &mut locally,
283 now() + Duration::minutes(11)
284 ));
285 assert_eq!(locally, LocallyHidden::default());
286
287 locally.unhide("19:a", now());
288 assert!(!resolve_hidden(
289 &chat,
290 &states(Some(false)),
291 &mut locally,
292 now()
293 ));
294 assert_eq!(locally, LocallyHidden::default());
295 }
296
297 #[test]
298 fn a_reported_hide_for_any_chat_drops_its_local_entry_unless_an_unhide_is_fresh() {
299 let mut locally = hidden_after("2026-10-10T10:00:00Z");
300 assert!(locally.reported_hidden("19:a", now()));
301 assert_eq!(locally, LocallyHidden::default());
302
303 locally.unhide("19:a", now());
304 assert!(!locally.reported_hidden("19:a", now()));
305 assert!(locally.reported_hidden("19:a", now() + Duration::minutes(11)));
306 }
307
308 #[test]
309 fn entries_round_trip_through_the_store() {
310 let store = Store::open_in_memory().unwrap();
311 let mut locally = hidden_after("2026-10-10T10:00:00Z");
312 locally.unhide("19:b", at("2026-10-10T11:00:00Z"));
313 locally.save(&store).unwrap();
314 assert_eq!(LocallyHidden::load(&store), locally);
315 }
316}