BlueGit

ict rusty-teams

Files

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

hidden_chats.rs

hidden_chats.rs 12.2 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 pub(crate) 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 let cleared_until_ms = states
116 .get(&chat.id)
117 .and_then(|state| state.history_cleared_ms);
118 let hidden_at_ms = states.get(&chat.id).and_then(|state| state.hidden_at_ms);
119 if history_cleared(chat, cleared_until_ms) || history_cleared(chat, hidden_at_ms) {
120 return true;
121 }
122 if reported == Some(true) {
123 locally.hidden_after.remove(&chat.id);
124 return true;
125 }
126 if let Some(hidden_after) = locally.hidden_after.get(&chat.id).copied() {
127 if chat
128 .last_message_time()
129 .is_some_and(|newest| newest > hidden_after)
130 {
131 locally.hidden_after.remove(&chat.id);
132 return false;
133 }
134 return true;
135 }
136 reported.unwrap_or_else(|| graph_hidden(chat))
137}
138
139/// Teams stores the last message time plus one millisecond, or now when the chat has no message.
140pub(crate) fn cleared_until_ms(last_message_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> i64 {
141 last_message_at.map_or(now.timestamp_millis(), |last| last.timestamp_millis() + 1)
142}
143
144/// Teams hides a chat whose history was removed until a newer message arrives.
145pub(crate) fn history_cleared(chat: &Chat, cleared_until_ms: Option<i64>) -> bool {
146 cleared_until_ms.is_some_and(|cleared_until_ms| {
147 chat.last_message_time()
148 .is_none_or(|newest| newest.timestamp_millis() <= cleared_until_ms)
149 })
150}
151
152impl<R: Remote> SyncEngine<R> {
153 pub(crate) fn with_locally_hidden<T>(
154 &self,
155 change: impl FnOnce(&mut LocallyHidden) -> T,
156 ) -> Result<T> {
157 let _guard = self.locally_hidden_lock.lock().unwrap();
158 let mut locally = LocallyHidden::load(&self.store);
159 let before = locally.clone();
160 let result = change(&mut locally);
161 if locally != before {
162 locally.save(&self.store)?;
163 }
164 Ok(result)
165 }
166}
167
168#[cfg(test)]
169mod tests {
170 use serde_json::json;
171
172 use super::*;
173
174 fn at(text: &str) -> DateTime<Utc> {
175 text.parse().unwrap()
176 }
177
178 fn chat(last_message: Option<&str>, graph_hidden: bool) -> Chat {
179 serde_json::from_value(json!({
180 "id": "19:a",
181 "chatType": "meeting",
182 "viewpoint": {"isHidden": graph_hidden},
183 "lastMessagePreview": last_message.map(|at| json!({"id": "1", "createdDateTime": at})),
184 }))
185 .unwrap()
186 }
187
188 fn states(hidden: Option<bool>) -> HashMap<String, ConversationState> {
189 HashMap::from([(
190 "19:a".to_owned(),
191 ConversationState {
192 id: "19:a".to_owned(),
193 muted: false,
194 hidden,
195 read: chatsvc::ReadHorizon::default(),
196 notification_settings: None,
197 history_cleared_ms: None,
198 hidden_at_ms: None,
199 },
200 )])
201 }
202
203 #[test]
204 fn removed_history_ends_one_millisecond_after_the_last_message() {
205 let last = at("2026-10-01T10:00:00Z");
206 assert_eq!(
207 cleared_until_ms(Some(last), now()),
208 last.timestamp_millis() + 1
209 );
210 assert_eq!(cleared_until_ms(None, now()), now().timestamp_millis());
211 }
212
213 #[test]
214 fn removed_history_hides_the_chat_until_a_newer_message() {
215 let mut locally = LocallyHidden::default();
216 let cleared_ms = at("2026-10-01T10:00:00Z").timestamp_millis() + 1;
217 let mut cleared = states(Some(false));
218 cleared.get_mut("19:a").unwrap().history_cleared_ms = Some(cleared_ms);
219 assert!(resolve_hidden(
220 &chat(Some("2026-10-01T10:00:00Z"), false),
221 &cleared,
222 &mut locally,
223 now()
224 ));
225 assert!(resolve_hidden(
226 &chat(None, false),
227 &cleared,
228 &mut locally,
229 now()
230 ));
231 assert!(!resolve_hidden(
232 &chat(Some("2026-10-02T08:00:00Z"), false),
233 &cleared,
234 &mut locally,
235 now()
236 ));
237 }
238
239 #[test]
240 fn a_hidden_time_hides_the_chat_although_chatsvc_says_visible() {
241 let mut locally = LocallyHidden::default();
242 let mut hidden = states(Some(false));
243 hidden.get_mut("19:a").unwrap().hidden_at_ms = Some(at("2026-10-01T10:00:00Z").timestamp_millis());
244 assert!(resolve_hidden(
245 &chat(Some("2026-10-01T09:00:00Z"), true),
246 &hidden,
247 &mut locally,
248 now()
249 ));
250 assert!(!resolve_hidden(
251 &chat(Some("2026-10-02T08:00:00Z"), true),
252 &hidden,
253 &mut locally,
254 now()
255 ));
256 }
257
258 fn hidden_after(text: &str) -> LocallyHidden {
259 let mut locally = LocallyHidden::default();
260 locally.hide("19:a", at(text));
261 locally
262 }
263
264 fn now() -> DateTime<Utc> {
265 at("2030-01-01T12:00:00Z")
266 }
267
268 #[test]
269 fn chatsvc_visible_beats_the_graph_hidden_flag() {
270 let mut locally = LocallyHidden::default();
271 let chat = chat(None, true);
272 assert!(!resolve_hidden(
273 &chat,
274 &states(Some(false)),
275 &mut locally,
276 now()
277 ));
278 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally, now()));
279 }
280
281 #[test]
282 fn a_local_hide_survives_a_chatsvc_that_still_says_visible() {
283 let mut locally = hidden_after("2026-10-10T10:00:00Z");
284 let chat = chat(Some("2026-10-10T09:00:00Z"), false);
285 assert!(resolve_hidden(
286 &chat,
287 &states(Some(false)),
288 &mut locally,
289 now()
290 ));
291 assert_eq!(locally, hidden_after("2026-10-10T10:00:00Z"));
292 }
293
294 #[test]
295 fn only_a_strictly_newer_message_unhides() {
296 let mut locally = hidden_after("2026-10-10T10:00:00Z");
297 let same = chat(Some("2026-10-10T10:00:00Z"), false);
298 assert!(resolve_hidden(
299 &same,
300 &states(Some(false)),
301 &mut locally,
302 now()
303 ));
304 let newer = chat(Some("2026-10-10T10:00:01Z"), false);
305 assert!(!resolve_hidden(
306 &newer,
307 &states(Some(false)),
308 &mut locally,
309 now()
310 ));
311 assert_eq!(locally, LocallyHidden::default());
312 }
313
314 #[test]
315 fn the_hide_marker_is_the_servers_message_time_so_clock_skew_does_not_matter() {
316 let mut locally = hidden_after("2026-10-10T10:00:00Z");
317 let chat = chat(Some("2026-10-10T10:00:30Z"), false);
318 let skewed_now = at("2026-10-10T09:00:00Z");
319 assert!(!resolve_hidden(
320 &chat,
321 &states(Some(false)),
322 &mut locally,
323 skewed_now
324 ));
325 }
326
327 #[test]
328 fn chatsvc_reporting_hidden_takes_over_and_drops_the_local_entry() {
329 let mut locally = hidden_after("2026-10-10T10:00:00Z");
330 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
331 assert!(resolve_hidden(
332 &chat,
333 &states(Some(true)),
334 &mut locally,
335 now()
336 ));
337 assert_eq!(locally, LocallyHidden::default());
338 }
339
340 #[test]
341 fn a_local_unhide_overrides_a_reported_hide_until_chatsvc_catches_up_or_time_runs_out() {
342 let chat = chat(None, false);
343 let mut locally = LocallyHidden::default();
344 locally.unhide("19:a", now());
345 assert!(!resolve_hidden(
346 &chat,
347 &states(Some(true)),
348 &mut locally,
349 now()
350 ));
351 assert!(!resolve_hidden(
352 &chat,
353 &states(Some(true)),
354 &mut locally,
355 now() + Duration::minutes(9)
356 ));
357 assert!(resolve_hidden(
358 &chat,
359 &states(Some(true)),
360 &mut locally,
361 now() + Duration::minutes(11)
362 ));
363 assert_eq!(locally, LocallyHidden::default());
364
365 locally.unhide("19:a", now());
366 assert!(!resolve_hidden(
367 &chat,
368 &states(Some(false)),
369 &mut locally,
370 now()
371 ));
372 assert_eq!(locally, LocallyHidden::default());
373 }
374
375 #[test]
376 fn a_reported_hide_for_any_chat_drops_its_local_entry_unless_an_unhide_is_fresh() {
377 let mut locally = hidden_after("2026-10-10T10:00:00Z");
378 assert!(locally.reported_hidden("19:a", now()));
379 assert_eq!(locally, LocallyHidden::default());
380
381 locally.unhide("19:a", now());
382 assert!(!locally.reported_hidden("19:a", now()));
383 assert!(locally.reported_hidden("19:a", now() + Duration::minutes(11)));
384 }
385
386 #[test]
387 fn entries_round_trip_through_the_store() {
388 let store = Store::open_in_memory().unwrap();
389 let mut locally = hidden_after("2026-10-10T10:00:00Z");
390 locally.unhide("19:b", at("2026-10-10T11:00:00Z"));
391 locally.save(&store).unwrap();
392 assert_eq!(LocallyHidden::load(&store), locally);
393 }
394}