BlueGit

ict rusty-teams

Files

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

hidden_chats.rs

hidden_chats.rs 9.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 if reported == Some(true) {
116 locally.hidden_after.remove(&chat.id);
117 return true;
118 }
119 if let Some(hidden_after) = locally.hidden_after.get(&chat.id).copied() {
120 if chat
121 .last_message_time()
122 .is_some_and(|newest| newest > hidden_after)
123 {
124 locally.hidden_after.remove(&chat.id);
125 return false;
126 }
127 return true;
128 }
129 reported.unwrap_or_else(|| graph_hidden(chat))
130}
131
132impl<R: Remote> SyncEngine<R> {
133 pub(crate) fn with_locally_hidden<T>(
134 &self,
135 change: impl FnOnce(&mut LocallyHidden) -> T,
136 ) -> Result<T> {
137 let _guard = self.locally_hidden_lock.lock().unwrap();
138 let mut locally = LocallyHidden::load(&self.store);
139 let before = locally.clone();
140 let result = change(&mut locally);
141 if locally != before {
142 locally.save(&self.store)?;
143 }
144 Ok(result)
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use serde_json::json;
151
152 use super::*;
153
154 fn at(text: &str) -> DateTime<Utc> {
155 text.parse().unwrap()
156 }
157
158 fn chat(last_message: Option<&str>, graph_hidden: bool) -> Chat {
159 serde_json::from_value(json!({
160 "id": "19:a",
161 "chatType": "meeting",
162 "viewpoint": {"isHidden": graph_hidden},
163 "lastMessagePreview": last_message.map(|at| json!({"id": "1", "createdDateTime": at})),
164 }))
165 .unwrap()
166 }
167
168 fn states(hidden: Option<bool>) -> HashMap<String, ConversationState> {
169 HashMap::from([(
170 "19:a".to_owned(),
171 ConversationState {
172 id: "19:a".to_owned(),
173 muted: false,
174 hidden,
175 },
176 )])
177 }
178
179 fn hidden_after(text: &str) -> LocallyHidden {
180 let mut locally = LocallyHidden::default();
181 locally.hide("19:a", at(text));
182 locally
183 }
184
185 fn now() -> DateTime<Utc> {
186 at("2030-01-01T12:00:00Z")
187 }
188
189 #[test]
190 fn chatsvc_visible_beats_the_graph_hidden_flag() {
191 let mut locally = LocallyHidden::default();
192 let chat = chat(None, true);
193 assert!(!resolve_hidden(
194 &chat,
195 &states(Some(false)),
196 &mut locally,
197 now()
198 ));
199 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally, now()));
200 }
201
202 #[test]
203 fn a_local_hide_survives_a_chatsvc_that_still_says_visible() {
204 let mut locally = hidden_after("2026-10-10T10:00:00Z");
205 let chat = chat(Some("2026-10-10T09:00:00Z"), false);
206 assert!(resolve_hidden(
207 &chat,
208 &states(Some(false)),
209 &mut locally,
210 now()
211 ));
212 assert_eq!(locally, hidden_after("2026-10-10T10:00:00Z"));
213 }
214
215 #[test]
216 fn only_a_strictly_newer_message_unhides() {
217 let mut locally = hidden_after("2026-10-10T10:00:00Z");
218 let same = chat(Some("2026-10-10T10:00:00Z"), false);
219 assert!(resolve_hidden(
220 &same,
221 &states(Some(false)),
222 &mut locally,
223 now()
224 ));
225 let newer = chat(Some("2026-10-10T10:00:01Z"), false);
226 assert!(!resolve_hidden(
227 &newer,
228 &states(Some(false)),
229 &mut locally,
230 now()
231 ));
232 assert_eq!(locally, LocallyHidden::default());
233 }
234
235 #[test]
236 fn the_hide_marker_is_the_servers_message_time_so_clock_skew_does_not_matter() {
237 let mut locally = hidden_after("2026-10-10T10:00:00Z");
238 let chat = chat(Some("2026-10-10T10:00:30Z"), false);
239 let skewed_now = at("2026-10-10T09:00:00Z");
240 assert!(!resolve_hidden(
241 &chat,
242 &states(Some(false)),
243 &mut locally,
244 skewed_now
245 ));
246 }
247
248 #[test]
249 fn chatsvc_reporting_hidden_takes_over_and_drops_the_local_entry() {
250 let mut locally = hidden_after("2026-10-10T10:00:00Z");
251 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
252 assert!(resolve_hidden(
253 &chat,
254 &states(Some(true)),
255 &mut locally,
256 now()
257 ));
258 assert_eq!(locally, LocallyHidden::default());
259 }
260
261 #[test]
262 fn a_local_unhide_overrides_a_reported_hide_until_chatsvc_catches_up_or_time_runs_out() {
263 let chat = chat(None, false);
264 let mut locally = LocallyHidden::default();
265 locally.unhide("19:a", now());
266 assert!(!resolve_hidden(
267 &chat,
268 &states(Some(true)),
269 &mut locally,
270 now()
271 ));
272 assert!(!resolve_hidden(
273 &chat,
274 &states(Some(true)),
275 &mut locally,
276 now() + Duration::minutes(9)
277 ));
278 assert!(resolve_hidden(
279 &chat,
280 &states(Some(true)),
281 &mut locally,
282 now() + Duration::minutes(11)
283 ));
284 assert_eq!(locally, LocallyHidden::default());
285
286 locally.unhide("19:a", now());
287 assert!(!resolve_hidden(
288 &chat,
289 &states(Some(false)),
290 &mut locally,
291 now()
292 ));
293 assert_eq!(locally, LocallyHidden::default());
294 }
295
296 #[test]
297 fn a_reported_hide_for_any_chat_drops_its_local_entry_unless_an_unhide_is_fresh() {
298 let mut locally = hidden_after("2026-10-10T10:00:00Z");
299 assert!(locally.reported_hidden("19:a", now()));
300 assert_eq!(locally, LocallyHidden::default());
301
302 locally.unhide("19:a", now());
303 assert!(!locally.reported_hidden("19:a", now()));
304 assert!(locally.reported_hidden("19:a", now() + Duration::minutes(11)));
305 }
306
307 #[test]
308 fn entries_round_trip_through_the_store() {
309 let store = Store::open_in_memory().unwrap();
310 let mut locally = hidden_after("2026-10-10T10:00:00Z");
311 locally.unhide("19:b", at("2026-10-10T11:00:00Z"));
312 locally.save(&store).unwrap();
313 assert_eq!(LocallyHidden::load(&store), locally);
314 }
315}