BlueGit

ict rusty-teams

Files

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

hidden_chats.rs

fix(sidebar): second review findings
metis Daniel Däschle · pushed by metis · 7 weeks ago
924c1353 History
hidden_chats.rs 8.9 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.insert(chat_id.to_owned(), last_message_at);
78 }
79
80 pub(crate) fn unhide(&mut self, chat_id: &str, now: DateTime<Utc>) {
81 self.hidden_after.remove(chat_id);
82 self.unhidden_at.insert(chat_id.to_owned(), now);
83 }
84
85 fn unhide_override_active(&self, chat_id: &str, now: DateTime<Utc>) -> bool {
86 self.unhidden_at
87 .get(chat_id)
88 .is_some_and(|at| now - *at < unhide_override_window())
89 }
90
91 pub(crate) fn reported_hidden(&mut self, chat_id: &str, now: DateTime<Utc>) -> bool {
92 if self.unhide_override_active(chat_id, now) {
93 return false;
94 }
95 self.hidden_after.remove(chat_id);
96 true
97 }
98}
99
100pub(crate) fn resolve_hidden(
101 chat: &Chat,
102 states: &HashMap<String, ConversationState>,
103 locally: &mut LocallyHidden,
104 now: DateTime<Utc>,
105) -> bool {
106 let reported = states.get(&chat.id).and_then(|state| state.hidden);
107 if locally.unhidden_at.contains_key(&chat.id) {
108 if reported == Some(false) || !locally.unhide_override_active(&chat.id, now) {
109 locally.unhidden_at.remove(&chat.id);
110 } else {
111 return false;
112 }
113 }
114 if reported == Some(true) {
115 locally.hidden_after.remove(&chat.id);
116 return true;
117 }
118 if let Some(hidden_after) = locally.hidden_after.get(&chat.id).copied() {
119 if chat
120 .last_message_time()
121 .is_some_and(|newest| newest > hidden_after)
122 {
123 locally.hidden_after.remove(&chat.id);
124 return false;
125 }
126 return true;
127 }
128 reported.unwrap_or_else(|| graph_hidden(chat))
129}
130
131impl<R: Remote> SyncEngine<R> {
132 pub(crate) fn with_locally_hidden<T>(
133 &self,
134 change: impl FnOnce(&mut LocallyHidden) -> T,
135 ) -> Result<T> {
136 let _guard = self.locally_hidden_lock.lock().unwrap();
137 let mut locally = LocallyHidden::load(&self.store);
138 let before = locally.clone();
139 let result = change(&mut locally);
140 if locally != before {
141 locally.save(&self.store)?;
142 }
143 Ok(result)
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use serde_json::json;
150
151 use super::*;
152
153 fn at(text: &str) -> DateTime<Utc> {
154 text.parse().unwrap()
155 }
156
157 fn chat(last_message: Option<&str>, graph_hidden: bool) -> Chat {
158 serde_json::from_value(json!({
159 "id": "19:a",
160 "chatType": "meeting",
161 "viewpoint": {"isHidden": graph_hidden},
162 "lastMessagePreview": last_message.map(|at| json!({"id": "1", "createdDateTime": at})),
163 }))
164 .unwrap()
165 }
166
167 fn states(hidden: Option<bool>) -> HashMap<String, ConversationState> {
168 HashMap::from([(
169 "19:a".to_owned(),
170 ConversationState {
171 id: "19:a".to_owned(),
172 muted: false,
173 hidden,
174 },
175 )])
176 }
177
178 fn hidden_after(text: &str) -> LocallyHidden {
179 let mut locally = LocallyHidden::default();
180 locally.hide("19:a", at(text));
181 locally
182 }
183
184 fn now() -> DateTime<Utc> {
185 at("2030-01-01T12:00:00Z")
186 }
187
188 #[test]
189 fn chatsvc_visible_beats_the_graph_hidden_flag() {
190 let mut locally = LocallyHidden::default();
191 let chat = chat(None, true);
192 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally, now()));
193 assert!(resolve_hidden(&chat, &HashMap::new(), &mut locally, now()));
194 }
195
196 #[test]
197 fn a_local_hide_survives_a_chatsvc_that_still_says_visible() {
198 let mut locally = hidden_after("2026-10-10T10:00:00Z");
199 let chat = chat(Some("2026-10-10T09:00:00Z"), false);
200 assert!(resolve_hidden(&chat, &states(Some(false)), &mut locally, now()));
201 assert_eq!(locally, hidden_after("2026-10-10T10:00:00Z"));
202 }
203
204 #[test]
205 fn only_a_strictly_newer_message_unhides() {
206 let mut locally = hidden_after("2026-10-10T10:00:00Z");
207 let same = chat(Some("2026-10-10T10:00:00Z"), false);
208 assert!(resolve_hidden(&same, &states(Some(false)), &mut locally, now()));
209 let newer = chat(Some("2026-10-10T10:00:01Z"), false);
210 assert!(!resolve_hidden(&newer, &states(Some(false)), &mut locally, now()));
211 assert_eq!(locally, LocallyHidden::default());
212 }
213
214 #[test]
215 fn the_hide_marker_is_the_servers_message_time_so_clock_skew_does_not_matter() {
216 let mut locally = hidden_after("2026-10-10T10:00:00Z");
217 let chat = chat(Some("2026-10-10T10:00:30Z"), false);
218 let skewed_now = at("2026-10-10T09:00:00Z");
219 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally, skewed_now));
220 }
221
222 #[test]
223 fn chatsvc_reporting_hidden_takes_over_and_drops_the_local_entry() {
224 let mut locally = hidden_after("2026-10-10T10:00:00Z");
225 let chat = chat(Some("2026-10-10T11:00:00Z"), false);
226 assert!(resolve_hidden(&chat, &states(Some(true)), &mut locally, now()));
227 assert_eq!(locally, LocallyHidden::default());
228 }
229
230 #[test]
231 fn a_local_unhide_overrides_a_reported_hide_until_chatsvc_catches_up_or_time_runs_out() {
232 let chat = chat(None, false);
233 let mut locally = LocallyHidden::default();
234 locally.unhide("19:a", now());
235 assert!(!resolve_hidden(&chat, &states(Some(true)), &mut locally, now()));
236 assert!(!resolve_hidden(
237 &chat,
238 &states(Some(true)),
239 &mut locally,
240 now() + Duration::minutes(9)
241 ));
242 assert!(resolve_hidden(
243 &chat,
244 &states(Some(true)),
245 &mut locally,
246 now() + Duration::minutes(11)
247 ));
248 assert_eq!(locally, LocallyHidden::default());
249
250 locally.unhide("19:a", now());
251 assert!(!resolve_hidden(&chat, &states(Some(false)), &mut locally, now()));
252 assert_eq!(locally, LocallyHidden::default());
253 }
254
255 #[test]
256 fn a_reported_hide_for_any_chat_drops_its_local_entry_unless_an_unhide_is_fresh() {
257 let mut locally = hidden_after("2026-10-10T10:00:00Z");
258 assert!(locally.reported_hidden("19:a", now()));
259 assert_eq!(locally, LocallyHidden::default());
260
261 locally.unhide("19:a", now());
262 assert!(!locally.reported_hidden("19:a", now()));
263 assert!(locally.reported_hidden("19:a", now() + Duration::minutes(11)));
264 }
265
266 #[test]
267 fn entries_round_trip_through_the_store() {
268 let store = Store::open_in_memory().unwrap();
269 let mut locally = hidden_after("2026-10-10T10:00:00Z");
270 locally.unhide("19:b", at("2026-10-10T11:00:00Z"));
271 locally.save(&store).unwrap();
272 assert_eq!(LocallyHidden::load(&store), locally);
273 }
274}