BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / find_in_chat.rs

find_in_chat.rs

find_in_chat.rs 14.2 KiB Download Raw
1use std::collections::HashSet;
2use std::ops::Range;
3
4use chatsvc::substrate_search::{MessageFilter, SearchMessage, split_highlights};
5use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, Utc};
6use store::{HIGHLIGHT_END, HIGHLIGHT_START, MessageRecord, SearchHit};
7
8pub const FIND_IN_CHAT: &str = "Find in chat";
9pub const FIND_IN_CHANNEL: &str = "Find in channel";
10pub const EMPTY_HINT: &str = "Find messages and links shared in this chat.";
11pub const NO_RESULTS_CHAT: &str = "We couldn't find any results in this chat";
12pub const NO_RESULTS_CHANNEL: &str = "We couldn't find any results in this channel";
13pub const LOAD_ERROR: &str = "Something went wrong while loading the results.";
14pub const LOADING: &str = "Fetching Data...";
15pub const FROM_LABEL: &str = "From";
16pub const DATE_LABEL: &str = "Date";
17pub const HAS_ATTACHMENT_LABEL: &str = "Has attachment";
18pub const MENTIONS_LABEL: &str = "@Mentions";
19pub const THIS_MONTH: &str = "This month";
20pub const LAST_MONTH: &str = "Last month";
21const ORG_PREFIX: &str = "8:orgid:";
22
23pub fn no_results_with_filters(search_term: &str) -> String {
24 format!("We couldn't find any results for '{search_term}' with the applied filters.")
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct FindHit {
29 pub message_id: String,
30 pub sent_at: DateTime<Utc>,
31 pub sender_name: String,
32 pub sender_id: Option<String>,
33 pub text: String,
34 pub highlights: Vec<Range<usize>>,
35 pub mentions_me: bool,
36 pub has_attachment: bool,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum DateRange {
41 Today,
42 Yesterday,
43 ThisWeek,
44 ThisMonth,
45}
46
47impl DateRange {
48 pub const ALL: [DateRange; 4] = [
49 DateRange::Today,
50 DateRange::Yesterday,
51 DateRange::ThisWeek,
52 DateRange::ThisMonth,
53 ];
54
55 pub fn label(self) -> &'static str {
56 match self {
57 DateRange::Today => "Today",
58 DateRange::Yesterday => "Yesterday",
59 DateRange::ThisWeek => "This week",
60 DateRange::ThisMonth => "This month",
61 }
62 }
63
64 pub fn contains(self, date: NaiveDate, today: NaiveDate) -> bool {
65 match self {
66 DateRange::Today => date == today,
67 DateRange::Yesterday => Some(date) == today.pred_opt(),
68 DateRange::ThisWeek => {
69 let week_start =
70 today - Duration::days(i64::from(today.weekday().num_days_from_monday()));
71 date >= week_start && date <= today
72 }
73 DateRange::ThisMonth => date.year() == today.year() && date.month() == today.month(),
74 }
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Sender {
80 pub user_id: String,
81 pub name: String,
82}
83
84#[derive(Debug, Clone, Default, PartialEq, Eq)]
85pub struct FindFilters {
86 pub from: Option<Sender>,
87 pub date: Option<DateRange>,
88 pub has_attachment: bool,
89 pub mentions_me: bool,
90}
91
92impl FindFilters {
93 pub fn is_active(&self) -> bool {
94 self.from.is_some() || self.date.is_some() || self.has_attachment || self.mentions_me
95 }
96
97 pub fn admits(&self, hit: &FindHit, today: NaiveDate, offset: FixedOffset) -> bool {
98 let from_holds = self.from.as_ref().is_none_or(|sender| {
99 hit.sender_id
100 .as_deref()
101 .is_some_and(|sender_id| same_user(sender_id, &sender.user_id))
102 });
103 let date_holds = self.date.is_none_or(|range| {
104 range.contains(hit.sent_at.with_timezone(&offset).date_naive(), today)
105 });
106 from_holds
107 && date_holds
108 && (!self.has_attachment || hit.has_attachment)
109 && (!self.mentions_me || hit.mentions_me)
110 }
111
112 pub fn server_filters(&self, thread_id: &str) -> Vec<MessageFilter> {
113 let mut filters = vec![MessageFilter::InChat {
114 thread_id: thread_id.to_owned(),
115 }];
116 if let Some(sender) = &self.from {
117 filters.push(MessageFilter::FromSender {
118 mri: user_mri(&sender.user_id),
119 });
120 }
121 if self.has_attachment {
122 filters.push(MessageFilter::HasAttachment);
123 }
124 if self.mentions_me {
125 filters.push(MessageFilter::MentionsMe);
126 }
127 filters
128 }
129}
130
131fn bare_user_id(user_id: &str) -> String {
132 user_id
133 .strip_prefix(ORG_PREFIX)
134 .unwrap_or(user_id)
135 .to_ascii_lowercase()
136}
137
138pub fn same_user(first: &str, second: &str) -> bool {
139 bare_user_id(first) == bare_user_id(second)
140}
141
142pub fn user_mri(user_id: &str) -> String {
143 if user_id.contains(':') {
144 user_id.to_owned()
145 } else {
146 format!("{ORG_PREFIX}{user_id}")
147 }
148}
149
150fn parse_local_snippet(snippet: &str) -> (String, Vec<Range<usize>>) {
151 let mut text = String::with_capacity(snippet.len());
152 let mut highlights = Vec::new();
153 let mut start = None;
154 for character in snippet.chars() {
155 match character {
156 HIGHLIGHT_START => start = Some(text.len()),
157 HIGHLIGHT_END => {
158 if let Some(begin) = start.take() {
159 highlights.push(begin..text.len());
160 }
161 }
162 _ => text.push(character),
163 }
164 }
165 (text, highlights)
166}
167
168pub fn from_local(hit: &SearchHit, record: Option<&MessageRecord>, my_id: Option<&str>) -> FindHit {
169 let (text, highlights) = parse_local_snippet(&hit.snippet);
170 FindHit {
171 message_id: hit.message_id.clone(),
172 sent_at: hit.created_at,
173 sender_name: hit.sender_name.clone().unwrap_or_default(),
174 sender_id: record.and_then(|record| record.sender_id.clone()),
175 text,
176 highlights,
177 mentions_me: record.is_some_and(|record| mentions_user(record, my_id)),
178 has_attachment: record.is_some_and(has_attachment),
179 }
180}
181
182pub fn from_record(record: &MessageRecord, my_id: Option<&str>) -> FindHit {
183 FindHit {
184 message_id: record.message_id.clone(),
185 sent_at: record.created_at,
186 sender_name: record.sender_name.clone().unwrap_or_default(),
187 sender_id: record.sender_id.clone(),
188 text: teams_core::preview_text(&record.body_html).unwrap_or_default(),
189 highlights: Vec::new(),
190 mentions_me: mentions_user(record, my_id),
191 has_attachment: has_attachment(record),
192 }
193}
194
195pub fn from_server(message: &SearchMessage) -> Option<FindHit> {
196 let sent_at = message.sent_at?;
197 let highlighted = split_highlights(
198 message
199 .highlighted_summary
200 .as_deref()
201 .unwrap_or(&message.preview),
202 );
203 Some(FindHit {
204 message_id: message.message_id.clone(),
205 sent_at,
206 sender_name: message.sender_name.clone().unwrap_or_default(),
207 sender_id: message.sender_mri.clone(),
208 text: highlighted.text,
209 highlights: highlighted.hits,
210 mentions_me: message.is_mentioned,
211 has_attachment: message.has_attachments,
212 })
213}
214
215fn mentions_user(record: &MessageRecord, my_id: Option<&str>) -> bool {
216 let Some(my_id) = my_id else {
217 return false;
218 };
219 teams_core::mentions(record).iter().any(|mention| {
220 mention
221 .user_id
222 .as_deref()
223 .is_some_and(|user_id| same_user(user_id, my_id))
224 })
225}
226
227fn has_attachment(record: &MessageRecord) -> bool {
228 !teams_core::files(record).is_empty() || !teams_core::images(record).is_empty()
229}
230
231pub fn merge(local: Vec<FindHit>, server: Vec<FindHit>) -> Vec<FindHit> {
232 let mut seen = HashSet::new();
233 let mut hits: Vec<FindHit> = local
234 .into_iter()
235 .chain(server)
236 .filter(|hit| seen.insert(hit.message_id.clone()))
237 .collect();
238 hits.sort_by(|first, second| {
239 second
240 .sent_at
241 .cmp(&first.sent_at)
242 .then_with(|| second.message_id.cmp(&first.message_id))
243 });
244 hits
245}
246
247pub fn month_label(date: NaiveDate, today: NaiveDate) -> String {
248 let months = |date: NaiveDate| date.year() * 12 + date.month0() as i32;
249 match months(today) - months(date) {
250 0 => THIS_MONTH.to_owned(),
251 1 => LAST_MONTH.to_owned(),
252 _ => date.format("%B %Y").to_string(),
253 }
254}
255
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct MonthGroup {
258 pub label: String,
259 pub hits: Vec<FindHit>,
260}
261
262pub fn group_by_month(hits: &[FindHit], today: NaiveDate, offset: FixedOffset) -> Vec<MonthGroup> {
263 let mut groups: Vec<MonthGroup> = Vec::new();
264 for hit in hits {
265 let label = month_label(hit.sent_at.with_timezone(&offset).date_naive(), today);
266 match groups.last_mut() {
267 Some(group) if group.label == label => group.hits.push(hit.clone()),
268 _ => groups.push(MonthGroup {
269 label,
270 hits: vec![hit.clone()],
271 }),
272 }
273 }
274 groups
275}
276
277pub fn step_index(current: Option<usize>, count: usize, backwards: bool) -> Option<usize> {
278 if count == 0 {
279 return None;
280 }
281 Some(match (current, backwards) {
282 (None, false) => 0,
283 (None, true) => count - 1,
284 (Some(index), false) => (index + 1) % count,
285 (Some(index), true) => (index + count - 1) % count,
286 })
287}
288
289#[cfg(test)]
290mod tests {
291 use chrono::TimeZone;
292
293 use super::*;
294
295 fn utc() -> FixedOffset {
296 FixedOffset::east_opt(0).unwrap()
297 }
298
299 fn hit(message_id: &str, day: u32, month: u32) -> FindHit {
300 FindHit {
301 message_id: message_id.into(),
302 sent_at: Utc.with_ymd_and_hms(2026, month, day, 10, 0, 0).unwrap(),
303 sender_name: "Lea".into(),
304 sender_id: Some("8:orgid:ABC".into()),
305 text: message_id.into(),
306 highlights: Vec::new(),
307 mentions_me: false,
308 has_attachment: false,
309 }
310 }
311
312 fn today() -> NaiveDate {
313 NaiveDate::from_ymd_opt(2026, 10, 17).unwrap()
314 }
315
316 #[test]
317 fn merge_dedupes_by_message_id_and_sorts_newest_first() {
318 let local = vec![hit("a", 1, 10), hit("b", 5, 10)];
319 let mut server_copy = hit("a", 1, 10);
320 server_copy.text = "server".into();
321 let server = vec![server_copy, hit("c", 3, 10)];
322 let merged = merge(local, server);
323 let ids: Vec<&str> = merged.iter().map(|hit| hit.message_id.as_str()).collect();
324 assert_eq!(ids, ["b", "c", "a"]);
325 assert_eq!(merged[2].text, "a");
326 }
327
328 #[test]
329 fn groups_follow_teams_month_labels() {
330 let hits = vec![
331 hit("a", 16, 10),
332 hit("b", 2, 10),
333 hit("c", 30, 9),
334 hit("d", 1, 7),
335 ];
336 let groups = group_by_month(&hits, today(), utc());
337 let labels: Vec<(&str, usize)> = groups
338 .iter()
339 .map(|group| (group.label.as_str(), group.hits.len()))
340 .collect();
341 assert_eq!(labels, [(THIS_MONTH, 2), (LAST_MONTH, 1), ("July 2026", 1)]);
342 assert_eq!(
343 month_label(NaiveDate::from_ymd_opt(2025, 10, 3).unwrap(), today()),
344 "October 2025"
345 );
346 }
347
348 #[test]
349 fn date_ranges_use_the_local_calendar() {
350 let saturday = today();
351 let day = |day: u32| NaiveDate::from_ymd_opt(2026, 10, day).unwrap();
352 assert!(DateRange::Today.contains(day(17), saturday));
353 assert!(DateRange::Yesterday.contains(day(16), saturday));
354 assert!(!DateRange::Yesterday.contains(day(17), saturday));
355 assert!(DateRange::ThisWeek.contains(day(12), saturday));
356 assert!(!DateRange::ThisWeek.contains(day(11), saturday));
357 assert!(DateRange::ThisMonth.contains(day(1), saturday));
358 assert!(
359 !DateRange::ThisMonth.contains(NaiveDate::from_ymd_opt(2026, 9, 30).unwrap(), saturday)
360 );
361 }
362
363 #[test]
364 fn filters_admit_matching_hits_only() {
365 let mut matching = hit("a", 17, 10);
366 matching.has_attachment = true;
367 matching.mentions_me = true;
368 let plain = hit("b", 1, 10);
369 let filters = FindFilters {
370 from: Some(Sender {
371 user_id: "abc".into(),
372 name: "Lea".into(),
373 }),
374 date: Some(DateRange::Today),
375 has_attachment: true,
376 mentions_me: true,
377 };
378 assert!(filters.admits(&matching, today(), utc()));
379 assert!(!filters.admits(&plain, today(), utc()));
380 assert!(FindFilters::default().admits(&plain, today(), utc()));
381 let other_sender = FindFilters {
382 from: Some(Sender {
383 user_id: "8:orgid:other".into(),
384 name: "Other".into(),
385 }),
386 ..Default::default()
387 };
388 assert!(!other_sender.admits(&matching, today(), utc()));
389 }
390
391 #[test]
392 fn server_filters_scope_to_the_chat_and_map_chips() {
393 let filters = FindFilters {
394 from: Some(Sender {
395 user_id: "abc".into(),
396 name: "Lea".into(),
397 }),
398 date: Some(DateRange::Today),
399 has_attachment: true,
400 mentions_me: true,
401 };
402 assert_eq!(
403 filters.server_filters("19:chat@thread.v2"),
404 [
405 MessageFilter::InChat {
406 thread_id: "19:chat@thread.v2".into()
407 },
408 MessageFilter::FromSender {
409 mri: "8:orgid:abc".into()
410 },
411 MessageFilter::HasAttachment,
412 MessageFilter::MentionsMe,
413 ]
414 );
415 }
416
417 #[test]
418 fn local_snippet_markers_become_highlight_ranges() {
419 let search_hit = SearchHit {
420 conversation_id: "c".into(),
421 message_id: "m".into(),
422 sender_name: Some("Lea".into()),
423 created_at: Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap(),
424 snippet: format!("access is {HIGHLIGHT_START}ready{HIGHLIGHT_END} now"),
425 };
426 let found = from_local(&search_hit, None, None);
427 assert_eq!(found.text, "access is ready now");
428 assert_eq!(&found.text[found.highlights[0].clone()], "ready");
429 }
430
431 #[test]
432 fn stepping_wraps_in_both_directions() {
433 assert_eq!(step_index(None, 0, false), None);
434 assert_eq!(step_index(None, 3, false), Some(0));
435 assert_eq!(step_index(None, 3, true), Some(2));
436 assert_eq!(step_index(Some(2), 3, false), Some(0));
437 assert_eq!(step_index(Some(0), 3, true), Some(2));
438 }
439}