BlueGit

ict rusty-teams

Files

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

hidden_chats.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
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 =
244 Some(at("2026-10-01T10:00:00Z").timestamp_millis());
245 assert!(resolve_hidden(
246 &chat(Some("2026-10-01T09:00:00Z"), true),
247 &hidden,
248 &mut locally,
249 now()
250 ));
251 assert!(!resolve_hidden(
252 &chat(Some("2026-10-02T08:00:00Z"), true),
253 &hidden,
254 &mut locally,
255 now()
256 ));
257 }
258
259 fn hidden_after(text: &str) -> LocallyHidden {
260 let mut locally = LocallyHidden::default();
261 locally.hide("19:a", at(text));
262 locally
263 }
264
265 fn now() -> DateTime<Utc> {
266 at("2030-01-01T12:00:00Z")
267 }
268
269 #[test]
270 fn chatsvc_visible_beats_the_graph_hidden_flag() {
271 let mut locally = LocallyHidden::default();
272 let chat = chat(None, true);
273 assert!(!resolve_hidden(
274 &chat,
275 &states(Some(false)),
276 &mut locally,
277 now()
278 ));
279 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally, now()));
280 }
281
282 #[test]
283 fn a_local_hide_survives_a_chatsvc_that_still_says_visible() {
284 let mut locally = hidden_after("2026-10-10T10:00:00Z");
285 let chat = chat(Some("2026-10-10T09:00:00Z"), false);
286 assert!(resolve_hidden(
287 &chat,
288 &states(Some(false)),
289 &mut locally,
290 now()
291 ));
292 assert_eq!(locally, hidden_after("2026-10-10T10:00:00Z"));
293 }
294
295 #[test]
296 fn only_a_strictly_newer_message_unhides() {
297 let mut locally = hidden_after("2026-10-10T10:00:00Z");
298 let same = chat(Some("2026-10-10T10:00:00Z"), false);
299 assert!(resolve_hidden(
300 &same,
301 &states(Some(false)),
302 &mut locally,
303 now()
304 ));
305 let newer = chat(Some("2026-10-10T10:00:01Z"), false);
306 assert!(!resolve_hidden(
307 &newer,
308 &states(Some(false)),
309 &mut locally,
310 now()
311 ));
312 assert_eq!(locally, LocallyHidden::default());
313 }
314
315 #[test]
316 fn the_hide_marker_is_the_servers_message_time_so_clock_skew_does_not_matter() {
317 let mut locally = hidden_after("2026-10-10T10:00:00Z");
318 let chat = chat(Some("2026-10-10T10:00:30Z"), false);
319 let skewed_now = at("2026-10-10T09:00:00Z");
320 assert!(!resolve_hidden(
321 &chat,
322 &states(Some(false)),
323 &mut locally,
324 skewed_now
325 ));
326 }
327
328 #[test]
329 fn chatsvc_reporting_hidden_takes_over_and_drops_the_local_entry() {
330 let mut locally = hidden_after("2026-10-10T10:00:00Z");
331 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
332 assert!(resolve_hidden(
333 &chat,
334 &states(Some(true)),
335 &mut locally,
336 now()
337 ));
338 assert_eq!(locally, LocallyHidden::default());
339 }
340
341 #[test]
342 fn a_local_unhide_overrides_a_reported_hide_until_chatsvc_catches_up_or_time_runs_out() {
343 let chat = chat(None, false);
344 let mut locally = LocallyHidden::default();
345 locally.unhide("19:a", now());
346 assert!(!resolve_hidden(
347 &chat,
348 &states(Some(true)),
349 &mut locally,
350 now()
351 ));
352 assert!(!resolve_hidden(
353 &chat,
354 &states(Some(true)),
355 &mut locally,
356 now() + Duration::minutes(9)
357 ));
358 assert!(resolve_hidden(
359 &chat,
360 &states(Some(true)),
361 &mut locally,
362 now() + Duration::minutes(11)
363 ));
364 assert_eq!(locally, LocallyHidden::default());
365
366 locally.unhide("19:a", now());
367 assert!(!resolve_hidden(
368 &chat,
369 &states(Some(false)),
370 &mut locally,
371 now()
372 ));
373 assert_eq!(locally, LocallyHidden::default());
374 }
375
376 #[test]
377 fn a_reported_hide_for_any_chat_drops_its_local_entry_unless_an_unhide_is_fresh() {
378 let mut locally = hidden_after("2026-10-10T10:00:00Z");
379 assert!(locally.reported_hidden("19:a", now()));
380 assert_eq!(locally, LocallyHidden::default());
381
382 locally.unhide("19:a", now());
383 assert!(!locally.reported_hidden("19:a", now()));
384 assert!(locally.reported_hidden("19:a", now() + Duration::minutes(11)));
385 }
386
387 #[test]
388 fn entries_round_trip_through_the_store() {
389 let store = Store::open_in_memory().unwrap();
390 let mut locally = hidden_after("2026-10-10T10:00:00Z");
391 locally.unhide("19:b", at("2026-10-10T11:00:00Z"));
392 locally.save(&store).unwrap();
393 assert_eq!(LocallyHidden::load(&store), locally);
394 }
395}