BlueGit

ict rusty-teams

Files

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

hidden_chats.rs

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