| 1 | use std::collections::HashMap; |
| 2 | use std::time::{Duration, Instant}; |
| 3 | |
| 4 | use chrono::{DateTime, FixedOffset, NaiveDate, Utc}; |
| 5 | use store::MessageRecord; |
| 6 | use teams_core::{ |
| 7 | DriveEntry, DriveFolder, FileCard, LibraryFile, files, preview_text, public_links, |
| 8 | }; |
| 9 | |
| 10 | use crate::format; |
| 11 | |
| 12 | const WEEK_DAYS: i64 = 6; |
| 13 | const EXCERPT_WORDS: usize = 6; |
| 14 | const DOWNLOAD_URL_LIFETIME: Duration = Duration::from_secs(50 * 60); |
| 15 | |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub enum DownloadSource { |
| 18 | Share, |
| 19 | Library(LibraryFile), |
| 20 | } |
| 21 | |
| 22 | pub fn library_file(entry: &DriveEntry, listed_at: Option<Instant>, now: Instant) -> LibraryFile { |
| 23 | let fresh = listed_at |
| 24 | .is_some_and(|listed_at| now.saturating_duration_since(listed_at) < DOWNLOAD_URL_LIFETIME); |
| 25 | LibraryFile { |
| 26 | drive_id: entry.drive_id.clone(), |
| 27 | item_id: entry.id.clone(), |
| 28 | name: entry.name.clone(), |
| 29 | size: entry.size, |
| 30 | cached_url: entry.download_url.clone().filter(|_| fresh), |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 35 | pub struct Crumb { |
| 36 | pub name: String, |
| 37 | pub folder: DriveFolder, |
| 38 | pub web_url: String, |
| 39 | } |
| 40 | |
| 41 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 42 | pub struct LibraryPath { |
| 43 | crumbs: Vec<Crumb>, |
| 44 | } |
| 45 | |
| 46 | impl LibraryPath { |
| 47 | pub fn new(root: Crumb) -> Self { |
| 48 | LibraryPath { crumbs: vec![root] } |
| 49 | } |
| 50 | |
| 51 | pub fn crumbs(&self) -> &[Crumb] { |
| 52 | &self.crumbs |
| 53 | } |
| 54 | |
| 55 | pub fn current(&self) -> &DriveFolder { |
| 56 | &self.crumbs[self.crumbs.len() - 1].folder |
| 57 | } |
| 58 | |
| 59 | pub fn current_web_url(&self) -> &str { |
| 60 | &self.crumbs[self.crumbs.len() - 1].web_url |
| 61 | } |
| 62 | |
| 63 | pub fn enter(&mut self, entry: &DriveEntry) { |
| 64 | self.crumbs.push(Crumb { |
| 65 | name: entry.name.clone(), |
| 66 | folder: entry.folder(), |
| 67 | web_url: entry.web_url.clone(), |
| 68 | }); |
| 69 | } |
| 70 | |
| 71 | pub fn go_to(&mut self, index: usize) { |
| 72 | self.crumbs.truncate(index + 1); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | pub fn count_label(child_count: u64) -> String { |
| 77 | match child_count { |
| 78 | 1 => "1 item".to_owned(), |
| 79 | count => format!("{count} items"), |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | pub fn size_label(entry: &DriveEntry) -> String { |
| 84 | match entry.child_count { |
| 85 | Some(count) => count_label(count), |
| 86 | None => format::file_size_label(entry.size), |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | pub fn sorted_entries(mut entries: Vec<DriveEntry>) -> Vec<DriveEntry> { |
| 91 | entries.sort_by_cached_key(|entry| (!entry.is_folder(), entry.name.to_lowercase())); |
| 92 | entries |
| 93 | } |
| 94 | |
| 95 | pub fn file_card(entry: &DriveEntry) -> FileCard { |
| 96 | FileCard { |
| 97 | kind: teams_core::FileKind::from_name(&entry.name), |
| 98 | name: entry.name.clone(), |
| 99 | content_type: None, |
| 100 | size: Some(entry.size), |
| 101 | open_url: entry.web_url.clone(), |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 106 | pub enum MessageFilter { |
| 107 | All, |
| 108 | Files, |
| 109 | Links, |
| 110 | } |
| 111 | |
| 112 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 113 | pub enum SharedContent { |
| 114 | File(FileCard), |
| 115 | Link(String), |
| 116 | } |
| 117 | |
| 118 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 119 | pub struct SharedItem { |
| 120 | pub content: SharedContent, |
| 121 | pub author: String, |
| 122 | pub post_label: String, |
| 123 | pub message_id: String, |
| 124 | pub created_at: DateTime<Utc>, |
| 125 | } |
| 126 | |
| 127 | impl SharedItem { |
| 128 | pub fn name(&self) -> &str { |
| 129 | match &self.content { |
| 130 | SharedContent::File(card) => &card.name, |
| 131 | SharedContent::Link(url) => url, |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | fn matches(&self, filter: MessageFilter) -> bool { |
| 136 | matches!( |
| 137 | (filter, &self.content), |
| 138 | (MessageFilter::All, _) |
| 139 | | (MessageFilter::Files, SharedContent::File(_)) |
| 140 | | (MessageFilter::Links, SharedContent::Link(_)) |
| 141 | ) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 146 | pub enum SharedGroup { |
| 147 | ThisWeek, |
| 148 | Earlier, |
| 149 | } |
| 150 | |
| 151 | impl SharedGroup { |
| 152 | pub fn label(self) -> &'static str { |
| 153 | match self { |
| 154 | SharedGroup::ThisWeek => "This week", |
| 155 | SharedGroup::Earlier => "Earlier", |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | fn post_label(root: Option<&MessageRecord>) -> String { |
| 161 | let Some(root) = root else { |
| 162 | return String::new(); |
| 163 | }; |
| 164 | if let Some(subject) = root |
| 165 | .subject |
| 166 | .as_deref() |
| 167 | .filter(|subject| !subject.is_empty()) |
| 168 | { |
| 169 | return subject.to_owned(); |
| 170 | } |
| 171 | let text = preview_text(&root.body_html).unwrap_or_default(); |
| 172 | let words: Vec<&str> = text.split_whitespace().collect(); |
| 173 | let shown = words[..words.len().min(EXCERPT_WORDS)].join(" "); |
| 174 | if words.len() > EXCERPT_WORDS { |
| 175 | format!("{shown} ...") |
| 176 | } else { |
| 177 | shown |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | pub fn shared_items(records: &[MessageRecord]) -> Vec<SharedItem> { |
| 182 | let roots: HashMap<&str, &MessageRecord> = records |
| 183 | .iter() |
| 184 | .filter(|record| record.reply_to_id.is_none()) |
| 185 | .map(|record| (record.message_id.as_str(), record)) |
| 186 | .collect(); |
| 187 | let mut items = Vec::new(); |
| 188 | for record in records.iter().filter(|record| !record.deleted) { |
| 189 | let root = match record.reply_to_id.as_deref() { |
| 190 | Some(root_id) => roots.get(root_id).copied(), |
| 191 | None => Some(record), |
| 192 | }; |
| 193 | let label = post_label(root); |
| 194 | let author = record.sender_name.clone().unwrap_or_default(); |
| 195 | let contents = files(record) |
| 196 | .into_iter() |
| 197 | .map(SharedContent::File) |
| 198 | .chain(public_links(record).into_iter().map(SharedContent::Link)); |
| 199 | items.extend(contents.map(|content| SharedItem { |
| 200 | content, |
| 201 | author: author.clone(), |
| 202 | post_label: label.clone(), |
| 203 | message_id: record.message_id.clone(), |
| 204 | created_at: record.created_at, |
| 205 | })); |
| 206 | } |
| 207 | items.sort_by_key(|item| std::cmp::Reverse(item.created_at)); |
| 208 | items |
| 209 | } |
| 210 | |
| 211 | pub fn group_of(created_at: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> SharedGroup { |
| 212 | let day = created_at.with_timezone(&offset).date_naive(); |
| 213 | if (today - day).num_days() <= WEEK_DAYS { |
| 214 | SharedGroup::ThisWeek |
| 215 | } else { |
| 216 | SharedGroup::Earlier |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | pub fn grouped_items( |
| 221 | items: &[SharedItem], |
| 222 | filter: MessageFilter, |
| 223 | today: NaiveDate, |
| 224 | offset: FixedOffset, |
| 225 | ) -> Vec<(SharedGroup, Vec<usize>)> { |
| 226 | let mut groups: Vec<(SharedGroup, Vec<usize>)> = Vec::new(); |
| 227 | for (index, item) in items |
| 228 | .iter() |
| 229 | .enumerate() |
| 230 | .filter(|(_, item)| item.matches(filter)) |
| 231 | { |
| 232 | let group = group_of(item.created_at, today, offset); |
| 233 | match groups.iter_mut().find(|(known, _)| *known == group) { |
| 234 | Some((_, members)) => members.push(index), |
| 235 | None => groups.push((group, vec![index])), |
| 236 | } |
| 237 | } |
| 238 | groups.sort_by_key(|(group, _)| *group as u8); |
| 239 | groups |
| 240 | } |
| 241 | |
| 242 | #[cfg(test)] |
| 243 | mod tests { |
| 244 | use chrono::TimeZone; |
| 245 | |
| 246 | use super::*; |
| 247 | |
| 248 | fn folder(id: &str) -> DriveFolder { |
| 249 | DriveFolder { |
| 250 | drive_id: "drive".to_owned(), |
| 251 | item_id: id.to_owned(), |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | fn entry(name: &str, child_count: Option<u64>, size: u64) -> DriveEntry { |
| 256 | DriveEntry { |
| 257 | drive_id: "drive".to_owned(), |
| 258 | id: format!("id-{name}"), |
| 259 | name: name.to_owned(), |
| 260 | web_url: format!("https://x/{name}"), |
| 261 | size, |
| 262 | modified_at: None, |
| 263 | modified_by: None, |
| 264 | child_count, |
| 265 | download_url: None, |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | fn record(id: &str, reply_to: Option<&str>, days_ago: i64, html: &str) -> MessageRecord { |
| 270 | MessageRecord { |
| 271 | conversation_id: "channel".to_owned(), |
| 272 | message_id: id.to_owned(), |
| 273 | reply_to_id: reply_to.map(str::to_owned), |
| 274 | sender_id: None, |
| 275 | sender_name: Some("Mara".to_owned()), |
| 276 | created_at: Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap() |
| 277 | - chrono::Duration::days(days_ago), |
| 278 | edited_at: None, |
| 279 | deleted: false, |
| 280 | body_html: html.to_owned(), |
| 281 | attachments_json: "[]".to_owned(), |
| 282 | reactions_json: "[]".to_owned(), |
| 283 | mentions_json: "[]".to_owned(), |
| 284 | sender_application_id: None, |
| 285 | links_json: "[]".to_owned(), |
| 286 | subject: None, |
| 287 | call_event_json: None, |
| 288 | importance: Default::default(), |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | fn with_file(mut record: MessageRecord, name: &str) -> MessageRecord { |
| 293 | record.attachments_json = format!( |
| 294 | r#"[{{"content_type":"reference","name":"{name}","url":"https://x/{name}","text":null,"size":10}}]"# |
| 295 | ); |
| 296 | record |
| 297 | } |
| 298 | |
| 299 | fn today() -> (NaiveDate, FixedOffset) { |
| 300 | let offset = FixedOffset::east_opt(0).unwrap(); |
| 301 | (NaiveDate::from_ymd_opt(2026, 10, 9).unwrap(), offset) |
| 302 | } |
| 303 | |
| 304 | #[test] |
| 305 | fn a_listed_download_url_is_used_until_it_is_about_to_expire() { |
| 306 | let mut listed = entry("a.pdf", None, 5); |
| 307 | listed.download_url = Some("https://dl.example/a".to_owned()); |
| 308 | let start = Instant::now(); |
| 309 | let url = |age_minutes: u64| { |
| 310 | library_file( |
| 311 | &listed, |
| 312 | Some(start), |
| 313 | start + Duration::from_secs(age_minutes * 60), |
| 314 | ) |
| 315 | .cached_url |
| 316 | }; |
| 317 | assert_eq!(url(10).as_deref(), Some("https://dl.example/a")); |
| 318 | assert_eq!(url(49).as_deref(), Some("https://dl.example/a")); |
| 319 | assert_eq!(url(51), None); |
| 320 | assert_eq!(library_file(&listed, None, start).cached_url, None); |
| 321 | let without = entry("b.pdf", None, 5); |
| 322 | assert_eq!(library_file(&without, Some(start), start).cached_url, None); |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn breadcrumb_path_grows_and_shrinks() { |
| 327 | let mut path = LibraryPath::new(Crumb { |
| 328 | name: "Channel".to_owned(), |
| 329 | folder: folder("root"), |
| 330 | web_url: "https://x/root".to_owned(), |
| 331 | }); |
| 332 | path.enter(&entry("Specs", Some(2), 0)); |
| 333 | path.enter(&entry("2026", Some(0), 0)); |
| 334 | let names: Vec<&str> = path |
| 335 | .crumbs() |
| 336 | .iter() |
| 337 | .map(|crumb| crumb.name.as_str()) |
| 338 | .collect(); |
| 339 | assert_eq!(names, ["Channel", "Specs", "2026"]); |
| 340 | assert_eq!(path.current().item_id, "id-2026"); |
| 341 | path.go_to(1); |
| 342 | assert_eq!(path.current().item_id, "id-Specs"); |
| 343 | path.go_to(0); |
| 344 | assert_eq!(path.current(), &folder("root")); |
| 345 | assert_eq!(path.current_web_url(), "https://x/root"); |
| 346 | } |
| 347 | |
| 348 | #[test] |
| 349 | fn sizes_and_item_counts_read_like_teams() { |
| 350 | assert_eq!(size_label(&entry("a", Some(0), 0)), "0 items"); |
| 351 | assert_eq!(size_label(&entry("a", Some(1), 0)), "1 item"); |
| 352 | assert_eq!(size_label(&entry("a", Some(12), 0)), "12 items"); |
| 353 | assert_eq!(size_label(&entry("a.pdf", None, 48_213)), "47 KB"); |
| 354 | } |
| 355 | |
| 356 | #[test] |
| 357 | fn folders_sort_before_files_by_name() { |
| 358 | let sorted = sorted_entries(vec![ |
| 359 | entry("b.pdf", None, 1), |
| 360 | entry("Zeta", Some(0), 0), |
| 361 | entry("a.pdf", None, 1), |
| 362 | entry("alpha", Some(0), 0), |
| 363 | ]); |
| 364 | let names: Vec<&str> = sorted.iter().map(|entry| entry.name.as_str()).collect(); |
| 365 | assert_eq!(names, ["alpha", "Zeta", "a.pdf", "b.pdf"]); |
| 366 | } |
| 367 | |
| 368 | #[test] |
| 369 | fn messages_group_into_this_week_and_earlier() { |
| 370 | let records = vec![ |
| 371 | with_file(record("old", None, 20, "<p>Old plan</p>"), "Old.pdf"), |
| 372 | with_file(record("new", None, 1, "<p>New plan</p>"), "New.xlsx"), |
| 373 | record( |
| 374 | "link", |
| 375 | None, |
| 376 | 2, |
| 377 | "<p><a href=\"https://a.example/x\">x</a></p>", |
| 378 | ), |
| 379 | ]; |
| 380 | let items = shared_items(&records); |
| 381 | let (day, offset) = today(); |
| 382 | let groups = grouped_items(&items, MessageFilter::All, day, offset); |
| 383 | assert_eq!(groups.len(), 2); |
| 384 | assert_eq!(groups[0].0, SharedGroup::ThisWeek); |
| 385 | let week: Vec<&str> = groups[0] |
| 386 | .1 |
| 387 | .iter() |
| 388 | .map(|index| items[*index].name()) |
| 389 | .collect(); |
| 390 | assert_eq!(week, ["New.xlsx", "https://a.example/x"]); |
| 391 | assert_eq!(groups[1].0, SharedGroup::Earlier); |
| 392 | assert_eq!(items[groups[1].1[0]].name(), "Old.pdf"); |
| 393 | } |
| 394 | |
| 395 | #[test] |
| 396 | fn filter_chips_split_files_from_links() { |
| 397 | let records = vec![ |
| 398 | with_file(record("a", None, 1, "<p>Plan</p>"), "Plan.pdf"), |
| 399 | record("b", None, 1, "<p><a href=\"https://a.example\">a</a></p>"), |
| 400 | ]; |
| 401 | let items = shared_items(&records); |
| 402 | let (day, offset) = today(); |
| 403 | let count = |filter| -> usize { |
| 404 | grouped_items(&items, filter, day, offset) |
| 405 | .iter() |
| 406 | .map(|(_, members)| members.len()) |
| 407 | .sum() |
| 408 | }; |
| 409 | assert_eq!(count(MessageFilter::All), 2); |
| 410 | assert_eq!(count(MessageFilter::Files), 1); |
| 411 | assert_eq!(count(MessageFilter::Links), 1); |
| 412 | } |
| 413 | |
| 414 | #[test] |
| 415 | fn replies_name_their_post_by_subject_or_first_words() { |
| 416 | let mut root = record( |
| 417 | "root", |
| 418 | None, |
| 419 | 1, |
| 420 | "<p>One two three four five six seven eight</p>", |
| 421 | ); |
| 422 | let reply = with_file(record("reply", Some("root"), 1, "<p>See file</p>"), "A.pdf"); |
| 423 | let subject_root = { |
| 424 | let mut other = record("other", None, 1, "<p>Body</p>"); |
| 425 | other.subject = Some("Release 42".to_owned()); |
| 426 | other |
| 427 | }; |
| 428 | let other_reply = with_file(record("r2", Some("other"), 1, "<p>x</p>"), "B.pdf"); |
| 429 | root.sender_name = Some("Tobias".to_owned()); |
| 430 | let items = shared_items(&[root, reply, subject_root, other_reply]); |
| 431 | let label_of = |name: &str| { |
| 432 | items |
| 433 | .iter() |
| 434 | .find(|item| item.name() == name) |
| 435 | .map(|item| item.post_label.clone()) |
| 436 | }; |
| 437 | assert_eq!( |
| 438 | label_of("A.pdf").as_deref(), |
| 439 | Some("One two three four five six ...") |
| 440 | ); |
| 441 | assert_eq!(label_of("B.pdf").as_deref(), Some("Release 42")); |
| 442 | assert_eq!( |
| 443 | items |
| 444 | .iter() |
| 445 | .find(|item| item.name() == "A.pdf") |
| 446 | .unwrap() |
| 447 | .message_id, |
| 448 | "reply" |
| 449 | ); |
| 450 | } |
| 451 | } |