BlueGit

ict rusty-teams

Files

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

hidden_chats.rs

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