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