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 history_cleared_ms: None,
196 },
197 )])
198 }
199
200 #[test]
201 fn removed_history_ends_one_millisecond_after_the_last_message() {
202 let last = at("2026-10-01T10:00:00Z");
203 assert_eq!(
204 cleared_until_ms(Some(last), now()),
205 last.timestamp_millis() + 1
206 );
207 assert_eq!(cleared_until_ms(None, now()), now().timestamp_millis());
208 }
209
210 #[test]
211 fn removed_history_hides_the_chat_until_a_newer_message() {
212 let mut locally = LocallyHidden::default();
213 let cleared_ms = at("2026-10-01T10:00:00Z").timestamp_millis() + 1;
214 let mut cleared = states(Some(false));
215 cleared.get_mut("19:a").unwrap().history_cleared_ms = Some(cleared_ms);
216 assert!(resolve_hidden(
217 &chat(Some("2026-10-01T10:00:00Z"), false),
218 &cleared,
219 &mut locally,
220 now()
221 ));
222 assert!(resolve_hidden(
223 &chat(None, false),
224 &cleared,
225 &mut locally,
226 now()
227 ));
228 assert!(!resolve_hidden(
229 &chat(Some("2026-10-02T08:00:00Z"), false),
230 &cleared,
231 &mut locally,
232 now()
233 ));
234 }
235
236 fn hidden_after(text: &str) -> LocallyHidden {
237 let mut locally = LocallyHidden::default();
238 locally.hide("19:a", at(text));
239 locally
240 }
241
242 fn now() -> DateTime<Utc> {
243 at("2030-01-01T12:00:00Z")
244 }
245
246 #[test]
247 fn chatsvc_visible_beats_the_graph_hidden_flag() {
248 let mut locally = LocallyHidden::default();
249 let chat = chat(None, true);
250 assert!(!resolve_hidden(
251 &chat,
252 &states(Some(false)),
253 &mut locally,
254 now()
255 ));
256 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally, now()));
257 }
258
259 #[test]
260 fn a_local_hide_survives_a_chatsvc_that_still_says_visible() {
261 let mut locally = hidden_after("2026-10-10T10:00:00Z");
262 let chat = chat(Some("2026-10-10T09:00:00Z"), false);
263 assert!(resolve_hidden(
264 &chat,
265 &states(Some(false)),
266 &mut locally,
267 now()
268 ));
269 assert_eq!(locally, hidden_after("2026-10-10T10:00:00Z"));
270 }
271
272 #[test]
273 fn only_a_strictly_newer_message_unhides() {
274 let mut locally = hidden_after("2026-10-10T10:00:00Z");
275 let same = chat(Some("2026-10-10T10:00:00Z"), false);
276 assert!(resolve_hidden(
277 &same,
278 &states(Some(false)),
279 &mut locally,
280 now()
281 ));
282 let newer = chat(Some("2026-10-10T10:00:01Z"), false);
283 assert!(!resolve_hidden(
284 &newer,
285 &states(Some(false)),
286 &mut locally,
287 now()
288 ));
289 assert_eq!(locally, LocallyHidden::default());
290 }
291
292 #[test]
293 fn the_hide_marker_is_the_servers_message_time_so_clock_skew_does_not_matter() {
294 let mut locally = hidden_after("2026-10-10T10:00:00Z");
295 let chat = chat(Some("2026-10-10T10:00:30Z"), false);
296 let skewed_now = at("2026-10-10T09:00:00Z");
297 assert!(!resolve_hidden(
298 &chat,
299 &states(Some(false)),
300 &mut locally,
301 skewed_now
302 ));
303 }
304
305 #[test]
306 fn chatsvc_reporting_hidden_takes_over_and_drops_the_local_entry() {
307 let mut locally = hidden_after("2026-10-10T10:00:00Z");
308 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
309 assert!(resolve_hidden(
310 &chat,
311 &states(Some(true)),
312 &mut locally,
313 now()
314 ));
315 assert_eq!(locally, LocallyHidden::default());
316 }
317
318 #[test]
319 fn a_local_unhide_overrides_a_reported_hide_until_chatsvc_catches_up_or_time_runs_out() {
320 let chat = chat(None, false);
321 let mut locally = LocallyHidden::default();
322 locally.unhide("19:a", now());
323 assert!(!resolve_hidden(
324 &chat,
325 &states(Some(true)),
326 &mut locally,
327 now()
328 ));
329 assert!(!resolve_hidden(
330 &chat,
331 &states(Some(true)),
332 &mut locally,
333 now() + Duration::minutes(9)
334 ));
335 assert!(resolve_hidden(
336 &chat,
337 &states(Some(true)),
338 &mut locally,
339 now() + Duration::minutes(11)
340 ));
341 assert_eq!(locally, LocallyHidden::default());
342
343 locally.unhide("19:a", now());
344 assert!(!resolve_hidden(
345 &chat,
346 &states(Some(false)),
347 &mut locally,
348 now()
349 ));
350 assert_eq!(locally, LocallyHidden::default());
351 }
352
353 #[test]
354 fn a_reported_hide_for_any_chat_drops_its_local_entry_unless_an_unhide_is_fresh() {
355 let mut locally = hidden_after("2026-10-10T10:00:00Z");
356 assert!(locally.reported_hidden("19:a", now()));
357 assert_eq!(locally, LocallyHidden::default());
358
359 locally.unhide("19:a", now());
360 assert!(!locally.reported_hidden("19:a", now()));
361 assert!(locally.reported_hidden("19:a", now() + Duration::minutes(11)));
362 }
363
364 #[test]
365 fn entries_round_trip_through_the_store() {
366 let store = Store::open_in_memory().unwrap();
367 let mut locally = hidden_after("2026-10-10T10:00:00Z");
368 locally.unhide("19:b", at("2026-10-10T11:00:00Z"));
369 locally.save(&store).unwrap();
370 assert_eq!(LocallyHidden::load(&store), locally);
371 }
372}