BlueGit

ict rusty-teams

feat(app): save received files and show them in the folder

- File cards get a Save button: the file goes to Downloads, a same-named
  file gets "name (1).ext", never overwritten
- Progress on the card; when done the button opens the folder with the
  file selected; failure offers a retry
- Download via the Graph shares API and 4 MiB range requests into a
  .part file that is renamed on success
- Unsafe remote names are cleaned (traversal, reserved Windows names,
  bidi controls, length)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
3d6742125150bd1ce5266e7939f875499ec6aeba
Parent
2fe8e154
19 files changed +1300 −19
crates/app/assets/symbols/download.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/></svg>
crates/app/assets/symbols/folder_open.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/></svg>
crates/app/assets/symbols/refresh.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></svg>
crates/app/src/assets.rs +4 −1
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 15] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 18] = symbols![
12 12 "done",
13 13 "done_all",
14 14 "keyboard_return",
@@ -24,6 +24,9 @@ const SYMBOLS: [(&str, &[u8]); 15] = symbols![
24 24 "content_copy",
25 25 "attach_file",
26 26 "upload",
27 "download",
28 "folder_open",
29 "refresh",
27 30 ];
28 31
29 32 pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 15] = symbols![
11const SYMBOLS: [(&str, &[u8]); 18] = symbols![
12 "done",
12 "done",
13 "done_all",
13 "done_all",
14 "keyboard_return",
14 "keyboard_return",
@@ -24,6 +24,9 @@ const SYMBOLS: [(&str, &[u8]); 15] = symbols![
24 "content_copy",
24 "content_copy",
25 "attach_file",
25 "attach_file",
26 "upload",
26 "upload",
27 "download",
28 "folder_open",
29 "refresh",
27];
30];
28
31
29pub struct AppAssets;
32pub struct AppAssets;
crates/app/src/downloads.rs added +670 −0
@@ -0,0 +1,670 @@
1 use std::collections::HashMap;
2 use std::fs::{File, OpenOptions};
3 use std::io::Write;
4 use std::path::{Path, PathBuf};
5
6 const FALLBACK_FILE_NAME: &str = "file";
7 const PART_SUFFIX: &str = ".part";
8 const MAX_NAME_BYTES: usize = 255;
9 const MAX_EXTENSION_BYTES: usize = 32;
10 const DEMO_DIRECTORY: &str = "rusty-teams-demo";
11 const DEMO_CONTENT: &[u8] = b"Rusty Teams demo file\n";
12
13 #[derive(Debug, Clone, PartialEq, Eq)]
14 pub enum DownloadState {
15 Saving(u8),
16 Saved(PathBuf),
17 Failed(String),
18 }
19
20 #[derive(Debug, Clone, PartialEq, Eq)]
21 pub enum ClickAction {
22 Start,
23 Reveal(PathBuf),
24 Ignore,
25 }
26
27 pub fn click_action(state: Option<&DownloadState>) -> ClickAction {
28 match state {
29 None | Some(DownloadState::Failed(_)) => ClickAction::Start,
30 Some(DownloadState::Saved(path)) => ClickAction::Reveal(path.clone()),
31 Some(DownloadState::Saving(_)) => ClickAction::Ignore,
32 }
33 }
34
35 #[derive(Debug, Clone, PartialEq, Eq)]
36 pub struct ButtonLook {
37 pub symbol: &'static str,
38 pub percent: Option<u8>,
39 pub tooltip: String,
40 pub clickable: bool,
41 }
42
43 pub fn button_look(state: Option<&DownloadState>) -> ButtonLook {
44 match state {
45 None => ButtonLook {
46 symbol: "download",
47 percent: None,
48 tooltip: "Save to Downloads".to_owned(),
49 clickable: true,
50 },
51 Some(DownloadState::Saving(percent)) => ButtonLook {
52 symbol: "download",
53 percent: Some(*percent),
54 tooltip: "Saving".to_owned(),
55 clickable: false,
56 },
57 Some(DownloadState::Saved(_)) => ButtonLook {
58 symbol: "folder_open",
59 percent: None,
60 tooltip: "Show in folder".to_owned(),
61 clickable: true,
62 },
63 Some(DownloadState::Failed(reason)) => ButtonLook {
64 symbol: "refresh",
65 percent: None,
66 tooltip: format!("Save failed: {reason}. Click to retry"),
67 clickable: true,
68 },
69 }
70 }
71
72 pub fn percent_label(percent: u8) -> String {
73 format!("{percent} %")
74 }
75
76 pub fn progress_fraction(state: Option<&DownloadState>) -> Option<f32> {
77 match state {
78 Some(DownloadState::Saving(percent)) => Some(f32::from((*percent).min(100)) / 100.),
79 _ => None,
80 }
81 }
82
83 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
84 pub struct DownloadKey {
85 pub conversation_id: String,
86 pub message_key: String,
87 pub open_url: String,
88 }
89
90 impl DownloadKey {
91 pub fn new(conversation_id: &str, message_key: &str, open_url: &str) -> Self {
92 DownloadKey {
93 conversation_id: conversation_id.to_owned(),
94 message_key: message_key.to_owned(),
95 open_url: open_url.to_owned(),
96 }
97 }
98 }
99
100 #[derive(Default)]
101 pub struct Downloads {
102 states: HashMap<DownloadKey, DownloadState>,
103 }
104
105 impl Downloads {
106 pub fn state(&self, key: &DownloadKey) -> Option<&DownloadState> {
107 self.states.get(key)
108 }
109
110 pub fn states_for(
111 &self,
112 conversation_id: &str,
113 message_key: &str,
114 open_urls: &[&str],
115 ) -> Vec<Option<DownloadState>> {
116 open_urls
117 .iter()
118 .map(|open_url| {
119 self.state(&DownloadKey::new(conversation_id, message_key, open_url))
120 .cloned()
121 })
122 .collect()
123 }
124
125 pub fn begin(&mut self, key: &DownloadKey) -> bool {
126 if matches!(self.state(key), Some(DownloadState::Saving(_))) {
127 return false;
128 }
129 self.states.insert(key.clone(), DownloadState::Saving(0));
130 true
131 }
132
133 pub fn set_progress(&mut self, key: &DownloadKey, percent: u8) {
134 if let Some(state @ DownloadState::Saving(_)) = self.states.get_mut(key) {
135 *state = DownloadState::Saving(percent.min(100));
136 }
137 }
138
139 pub fn finish(&mut self, key: &DownloadKey, outcome: Result<PathBuf, String>) {
140 if !matches!(self.state(key), Some(DownloadState::Saving(_))) {
141 return;
142 }
143 let state = match outcome {
144 Ok(path) => DownloadState::Saved(path),
145 Err(reason) => DownloadState::Failed(reason),
146 };
147 self.states.insert(key.clone(), state);
148 }
149 }
150
151 fn is_format_character(character: char) -> bool {
152 matches!(
153 character,
154 '\u{ad}'
155 | '\u{61c}'
156 | '\u{200b}'..='\u{200f}'
157 | '\u{202a}'..='\u{202e}'
158 | '\u{2060}'..='\u{2064}'
159 | '\u{2066}'..='\u{2069}'
160 | '\u{feff}'
161 )
162 }
163
164 fn is_reserved_windows_name(name: &str) -> bool {
165 let stem = name.split('.').next().unwrap_or_default().trim_end();
166 let upper = stem.to_ascii_uppercase();
167 matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
168 || ["COM", "LPT"].iter().any(|prefix| {
169 upper
170 .strip_prefix(prefix)
171 .is_some_and(|number| matches!(number.as_bytes(), [b'1'..=b'9']))
172 })
173 }
174
175 pub fn safe_file_name(name: &str) -> String {
176 let cleaned: String = name
177 .chars()
178 .filter(|character| !is_format_character(*character))
179 .map(|character| {
180 if character.is_control() || "/\\:*?\"<>|".contains(character) {
181 '_'
182 } else {
183 character
184 }
185 })
186 .collect();
187 let trimmed = cleaned.trim_start().trim_end_matches([' ', '.']);
188 if trimmed.is_empty() {
189 FALLBACK_FILE_NAME.to_owned()
190 } else if is_reserved_windows_name(trimmed) {
191 format!("_{trimmed}")
192 } else {
193 trimmed.to_owned()
194 }
195 }
196
197 fn split_extension(file_name: &str) -> (&str, &str) {
198 match file_name.rfind('.') {
199 Some(dot) if dot > 0 && file_name.len() - dot <= MAX_EXTENSION_BYTES => {
200 file_name.split_at(dot)
201 }
202 _ => (file_name, ""),
203 }
204 }
205
206 fn truncate_on_boundary(text: &str, max_bytes: usize) -> &str {
207 let mut end = max_bytes.min(text.len());
208 while !text.is_char_boundary(end) {
209 end -= 1;
210 }
211 &text[..end]
212 }
213
214 pub fn numbered_name(file_name: &str, number: usize) -> String {
215 let (stem, extension) = split_extension(file_name);
216 let suffix = if number == 0 {
217 String::new()
218 } else {
219 format!(" ({number})")
220 };
221 let budget = MAX_NAME_BYTES.saturating_sub(PART_SUFFIX.len() + suffix.len() + extension.len());
222 format!("{}{suffix}{extension}", truncate_on_boundary(stem, budget))
223 }
224
225 pub fn pick_downloads_directory(download: Option<PathBuf>, home: Option<PathBuf>) -> PathBuf {
226 download.or(home).unwrap_or_else(std::env::temp_dir)
227 }
228
229 pub fn downloads_directory() -> PathBuf {
230 let directories = directories::UserDirs::new();
231 pick_downloads_directory(
232 directories
233 .as_ref()
234 .and_then(|directories| directories.download_dir().map(Path::to_path_buf)),
235 directories
236 .as_ref()
237 .map(|directories| directories.home_dir().to_path_buf()),
238 )
239 }
240
241 pub fn demo_directory() -> PathBuf {
242 std::env::temp_dir().join(DEMO_DIRECTORY)
243 }
244
245 #[derive(Debug, Clone, PartialEq, Eq)]
246 pub enum RevealTarget {
247 File(PathBuf),
248 Folder(PathBuf),
249 }
250
251 pub fn reveal_target(path: &Path, exists: bool, fallback_folder: PathBuf) -> RevealTarget {
252 if exists {
253 RevealTarget::File(path.to_path_buf())
254 } else {
255 RevealTarget::Folder(fallback_folder)
256 }
257 }
258
259 #[cfg_attr(not(windows), allow(dead_code))]
260 pub fn explorer_select_argument(path: &Path) -> String {
261 format!("/select,\"{}\"", path.display())
262 }
263
264 pub fn reveal_in_file_manager(path: &Path) {
265 let mut command = reveal_command(path);
266 if let Ok(mut child) = command.spawn() {
267 std::thread::spawn(move || {
268 let _ = child.wait();
269 });
270 }
271 }
272
273 #[cfg(windows)]
274 fn reveal_command(path: &Path) -> std::process::Command {
275 use std::os::windows::process::CommandExt as _;
276 let mut command = std::process::Command::new("explorer.exe");
277 command.raw_arg(explorer_select_argument(path));
278 command
279 }
280
281 #[cfg(target_os = "macos")]
282 fn reveal_command(path: &Path) -> std::process::Command {
283 let mut command = std::process::Command::new("open");
284 command.arg("-R").arg(path);
285 command
286 }
287
288 #[cfg(not(any(windows, target_os = "macos")))]
289 fn reveal_command(path: &Path) -> std::process::Command {
290 let mut command = std::process::Command::new("xdg-open");
291 command.arg(path.parent().unwrap_or(path));
292 command
293 }
294
295 pub struct PartFile {
296 file: Option<File>,
297 part: PathBuf,
298 target: PathBuf,
299 finished: bool,
300 }
301
302 fn part_path(target: &Path) -> PathBuf {
303 let mut name = target.as_os_str().to_owned();
304 name.push(PART_SUFFIX);
305 PathBuf::from(name)
306 }
307
308 fn reserve_name(directory: &Path, file_name: &str) -> std::io::Result<(PathBuf, File)> {
309 let create_new = |path: &Path| OpenOptions::new().write(true).create_new(true).open(path);
310 for number in 0usize.. {
311 let candidate = directory.join(numbered_name(file_name, number));
312 match create_new(&candidate) {
313 Ok(_) => {}
314 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
315 Err(error) => return Err(error),
316 }
317 match create_new(&part_path(&candidate)) {
318 Ok(part) => return Ok((candidate, part)),
319 Err(error) => {
320 let _ = std::fs::remove_file(&candidate);
321 if error.kind() != std::io::ErrorKind::AlreadyExists {
322 return Err(error);
323 }
324 }
325 }
326 }
327 unreachable!("the numbering loop only returns")
328 }
329
330 impl PartFile {
331 pub fn create(directory: &Path, file_name: &str) -> std::io::Result<Self> {
332 std::fs::create_dir_all(directory)?;
333 let (target, file) = reserve_name(directory, &safe_file_name(file_name))?;
334 Ok(PartFile {
335 file: Some(file),
336 part: part_path(&target),
337 target,
338 finished: false,
339 })
340 }
341
342 pub fn write(&mut self, bytes: &[u8]) -> std::io::Result<()> {
343 match self.file.as_mut() {
344 Some(file) => file.write_all(bytes),
345 None => Err(std::io::Error::other("the file is already closed")),
346 }
347 }
348
349 pub fn finish(mut self) -> std::io::Result<PathBuf> {
350 if let Some(mut file) = self.file.take() {
351 file.flush()?;
352 }
353 std::fs::rename(&self.part, &self.target)?;
354 self.finished = true;
355 Ok(self.target.clone())
356 }
357 }
358
359 impl Drop for PartFile {
360 fn drop(&mut self) {
361 if !self.finished {
362 self.file.take();
363 let _ = std::fs::remove_file(&self.part);
364 let _ = std::fs::remove_file(&self.target);
365 }
366 }
367 }
368
369 pub fn write_demo_file(file_name: &str) -> std::io::Result<PathBuf> {
370 let mut part = PartFile::create(&demo_directory(), file_name)?;
371 part.write(DEMO_CONTENT)?;
372 part.finish()
373 }
374
375 #[cfg(test)]
376 mod tests {
377 use super::*;
378
379 #[test]
380 fn numbering_goes_before_the_extension_in_brackets() {
381 assert_eq!(numbered_name("plan.pdf", 0), "plan.pdf");
382 assert_eq!(numbered_name("plan.pdf", 1), "plan (1).pdf");
383 assert_eq!(numbered_name("plan.pdf", 12), "plan (12).pdf");
384 assert_eq!(numbered_name("a.tar.gz", 2), "a.tar (2).gz");
385 assert_eq!(numbered_name("README", 3), "README (3)");
386 assert_eq!(numbered_name(".env", 1), ".env (1)");
387 }
388
389 #[test]
390 fn numbering_skips_names_that_exist() {
391 let directory = tempfile::tempdir().unwrap();
392 std::fs::write(directory.path().join("plan.pdf"), b"").unwrap();
393 std::fs::write(directory.path().join("plan (1).pdf"), b"").unwrap();
394 let (path, _) = reserve_name(directory.path(), "plan.pdf").unwrap();
395 assert_eq!(path, directory.path().join("plan (2).pdf"));
396 let (next, _) = reserve_name(directory.path(), "plan.pdf").unwrap();
397 assert_eq!(next, directory.path().join("plan (3).pdf"));
398 assert_eq!(
399 reserve_name(directory.path(), "new.pdf").unwrap().0,
400 directory.path().join("new.pdf")
401 );
402 }
403
404 #[test]
405 fn a_stale_part_file_is_left_alone() {
406 let directory = tempfile::tempdir().unwrap();
407 std::fs::write(directory.path().join("plan.pdf.part"), b"old").unwrap();
408 let (path, _) = reserve_name(directory.path(), "plan.pdf").unwrap();
409 assert_eq!(path, directory.path().join("plan (1).pdf"));
410 assert!(!directory.path().join("plan.pdf").exists());
411 assert_eq!(
412 std::fs::read(directory.path().join("plan.pdf.part")).unwrap(),
413 b"old"
414 );
415 }
416
417 #[test]
418 fn concurrent_saves_of_one_name_get_separate_files() {
419 let directory = tempfile::tempdir().unwrap();
420 let mut first = PartFile::create(directory.path(), "a.txt").unwrap();
421 let mut second = PartFile::create(directory.path(), "a.txt").unwrap();
422 first.write(b"1").unwrap();
423 second.write(b"2").unwrap();
424 let first_path = first.finish().unwrap();
425 let second_path = second.finish().unwrap();
426 assert_eq!(std::fs::read(first_path).unwrap(), b"1");
427 assert_eq!(std::fs::read(second_path).unwrap(), b"2");
428 }
429
430 #[test]
431 fn names_are_cut_so_the_part_file_fits_255_bytes() {
432 let long = format!("{}.pdf", "x".repeat(400));
433 for number in [0, 1, 123] {
434 let name = numbered_name(&long, number);
435 assert!(name.len() + PART_SUFFIX.len() <= 255, "{}", name.len());
436 assert!(name.ends_with(".pdf"));
437 }
438 assert!(numbered_name(&long, 12).ends_with(" (12).pdf"));
439 let wide = format!("{}.txt", "\u{e4}".repeat(200));
440 let name = numbered_name(&wide, 1);
441 assert!(name.len() + PART_SUFFIX.len() <= 255);
442 assert!(name.ends_with(" (1).txt"));
443 let huge_extension = format!("a.{}", "e".repeat(400));
444 assert!(numbered_name(&huge_extension, 0).len() + PART_SUFFIX.len() <= 255);
445 }
446
447 #[test]
448 fn trailing_spaces_and_dots_go_together() {
449 assert_eq!(safe_file_name("report ."), "report");
450 assert_eq!(safe_file_name("report. . "), "report");
451 assert_eq!(safe_file_name(" a.txt"), "a.txt");
452 }
453
454 #[test]
455 fn windows_reserved_names_get_a_prefix() {
456 assert_eq!(safe_file_name("CON"), "_CON");
457 assert_eq!(safe_file_name("nul.txt"), "_nul.txt");
458 assert_eq!(safe_file_name("Com1.tar.gz"), "_Com1.tar.gz");
459 assert_eq!(safe_file_name("lpt9"), "_lpt9");
460 assert_eq!(safe_file_name("COM0"), "COM0");
461 assert_eq!(safe_file_name("console.txt"), "console.txt");
462 }
463
464 #[test]
465 fn direction_overrides_and_format_characters_are_removed() {
466 assert_eq!(safe_file_name("a\u{202e}fdp.exe"), "afdp.exe");
467 assert_eq!(safe_file_name("\u{2066}b\u{2069}.txt\u{200f}"), "b.txt");
468 assert_eq!(safe_file_name("\u{feff}c.txt"), "c.txt");
469 }
470
471 #[test]
472 fn file_names_lose_path_parts_and_reserved_characters() {
473 assert_eq!(safe_file_name("../a/b.pdf"), ".._a_b.pdf");
474 assert_eq!(safe_file_name("q: 1?.txt"), "q_ 1_.txt");
475 assert_eq!(safe_file_name(" "), "file");
476 assert_eq!(safe_file_name("..."), "file");
477 }
478
479 #[test]
480 fn downloads_directory_falls_back_to_home_then_temp() {
481 let download = Some(PathBuf::from("/dl"));
482 let home = Some(PathBuf::from("/home/me"));
483 assert_eq!(
484 pick_downloads_directory(download.clone(), home.clone()),
485 PathBuf::from("/dl")
486 );
487 assert_eq!(
488 pick_downloads_directory(None, home),
489 PathBuf::from("/home/me")
490 );
491 assert_eq!(pick_downloads_directory(None, None), std::env::temp_dir());
492 }
493
494 #[test]
495 fn click_starts_reveals_or_waits_by_state() {
496 let path = PathBuf::from("/d/a.pdf");
497 assert_eq!(click_action(None), ClickAction::Start);
498 assert_eq!(
499 click_action(Some(&DownloadState::Failed("x".into()))),
500 ClickAction::Start
501 );
502 assert_eq!(
503 click_action(Some(&DownloadState::Saving(5))),
504 ClickAction::Ignore
505 );
506 assert_eq!(
507 click_action(Some(&DownloadState::Saved(path.clone()))),
508 ClickAction::Reveal(path)
509 );
510 }
511
512 fn key(message: &str, url: &str) -> DownloadKey {
513 DownloadKey::new("chat", message, url)
514 }
515
516 #[test]
517 fn states_move_from_saving_to_saved_or_failed() {
518 let mut downloads = Downloads::default();
519 let key = key("m1", "u");
520 assert!(downloads.begin(&key));
521 assert!(!downloads.begin(&key));
522 downloads.set_progress(&key, 42);
523 assert_eq!(downloads.state(&key), Some(&DownloadState::Saving(42)));
524 downloads.finish(&key, Err("offline".into()));
525 assert_eq!(
526 downloads.state(&key),
527 Some(&DownloadState::Failed("offline".into()))
528 );
529 assert!(downloads.begin(&key));
530 assert_eq!(downloads.state(&key), Some(&DownloadState::Saving(0)));
531 downloads.finish(&key, Ok(PathBuf::from("/d/a.pdf")));
532 assert_eq!(
533 downloads.state(&key),
534 Some(&DownloadState::Saved(PathBuf::from("/d/a.pdf")))
535 );
536 }
537
538 #[test]
539 fn late_progress_and_results_do_not_change_settled_states() {
540 let mut downloads = Downloads::default();
541 let key = key("m1", "u");
542 downloads.set_progress(&key, 10);
543 downloads.finish(&key, Ok(PathBuf::from("/x")));
544 assert_eq!(downloads.state(&key), None);
545 downloads.begin(&key);
546 downloads.finish(&key, Ok(PathBuf::from("/d/a.pdf")));
547 downloads.set_progress(&key, 50);
548 assert!(matches!(
549 downloads.state(&key),
550 Some(DownloadState::Saved(_))
551 ));
552 }
553
554 #[test]
555 fn states_are_kept_per_conversation_message_and_url() {
556 let mut downloads = Downloads::default();
557 downloads.begin(&DownloadKey::new("chat", "m1", "u2"));
558 downloads.begin(&DownloadKey::new("chat", "m2", "u1"));
559 downloads.begin(&DownloadKey::new("other", "m1", "u1"));
560 let states = downloads.states_for("chat", "m1", &["u1", "u2"]);
561 assert_eq!(states, vec![None, Some(DownloadState::Saving(0))]);
562 }
563
564 #[test]
565 fn button_follows_the_state() {
566 let idle = button_look(None);
567 assert_eq!(
568 (idle.symbol, idle.tooltip.as_str()),
569 ("download", "Save to Downloads")
570 );
571 assert!(idle.clickable);
572 let saving = button_look(Some(&DownloadState::Saving(42)));
573 assert_eq!(saving.percent, Some(42));
574 assert!(!saving.clickable);
575 let saved = button_look(Some(&DownloadState::Saved(PathBuf::from("/a"))));
576 assert_eq!(
577 (saved.symbol, saved.tooltip.as_str()),
578 ("folder_open", "Show in folder")
579 );
580 let failed = button_look(Some(&DownloadState::Failed("HTTP 404".into())));
581 assert_eq!(failed.symbol, "refresh");
582 assert_eq!(failed.tooltip, "Save failed: HTTP 404. Click to retry");
583 assert_eq!(percent_label(42), "42 %");
584 }
585
586 #[test]
587 fn progress_bar_only_while_saving() {
588 assert_eq!(
589 progress_fraction(Some(&DownloadState::Saving(50))),
590 Some(0.5)
591 );
592 assert_eq!(progress_fraction(None), None);
593 assert_eq!(
594 progress_fraction(Some(&DownloadState::Saved(PathBuf::new()))),
595 None
596 );
597 }
598
599 #[test]
600 fn missing_file_falls_back_to_the_folder() {
601 let path = Path::new("/d/a.pdf");
602 assert_eq!(
603 reveal_target(path, true, PathBuf::from("/d")),
604 RevealTarget::File(path.to_path_buf())
605 );
606 assert_eq!(
607 reveal_target(path, false, PathBuf::from("/d")),
608 RevealTarget::Folder(PathBuf::from("/d"))
609 );
610 }
611
612 #[test]
613 fn explorer_gets_the_path_quoted_after_select() {
614 assert_eq!(
615 explorer_select_argument(Path::new("C:\\Users\\me\\Downloads\\a b.pdf")),
616 "/select,\"C:\\Users\\me\\Downloads\\a b.pdf\""
617 );
618 }
619
620 #[test]
621 fn part_file_is_renamed_on_finish() {
622 let directory = tempfile::tempdir().unwrap();
623 let mut part = PartFile::create(directory.path(), "a.txt").unwrap();
624 part.write(b"hi").unwrap();
625 assert!(directory.path().join("a.txt.part").exists());
626 let path = part.finish().unwrap();
627 assert_eq!(path, directory.path().join("a.txt"));
628 assert_eq!(std::fs::read(&path).unwrap(), b"hi");
629 assert!(!directory.path().join("a.txt.part").exists());
630 }
631
632 #[test]
633 fn part_file_is_removed_when_dropped_unfinished() {
634 let directory = tempfile::tempdir().unwrap();
635 let mut part = PartFile::create(directory.path(), "a.txt").unwrap();
636 part.write(b"hi").unwrap();
637 drop(part);
638 assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0);
639 }
640
641 #[test]
642 fn a_file_that_appears_meanwhile_is_not_replaced() {
643 let directory = tempfile::tempdir().unwrap();
644 let part = PartFile::create(directory.path(), "a.txt").unwrap();
645 let other = PartFile::create(directory.path(), "a.txt").unwrap();
646 drop(part);
647 std::fs::write(directory.path().join("a.txt"), b"browser").unwrap();
648 let mut other = other;
649 other.write(b"ours").unwrap();
650 assert_eq!(other.finish().unwrap(), directory.path().join("a (1).txt"));
651 assert_eq!(
652 std::fs::read(directory.path().join("a.txt")).unwrap(),
653 b"browser"
654 );
655 }
656
657 #[test]
658 fn existing_files_are_never_overwritten() {
659 let directory = tempfile::tempdir().unwrap();
660 std::fs::write(directory.path().join("a.txt"), b"old").unwrap();
661 let mut part = PartFile::create(directory.path(), "a.txt").unwrap();
662 part.write(b"new").unwrap();
663 let path = part.finish().unwrap();
664 assert_eq!(path, directory.path().join("a (1).txt"));
665 assert_eq!(
666 std::fs::read(directory.path().join("a.txt")).unwrap(),
667 b"old"
668 );
669 }
670 }
@@ -0,0 +1,670 @@
1use std::collections::HashMap;
2use std::fs::{File, OpenOptions};
3use std::io::Write;
4use std::path::{Path, PathBuf};
5
6const FALLBACK_FILE_NAME: &str = "file";
7const PART_SUFFIX: &str = ".part";
8const MAX_NAME_BYTES: usize = 255;
9const MAX_EXTENSION_BYTES: usize = 32;
10const DEMO_DIRECTORY: &str = "rusty-teams-demo";
11const DEMO_CONTENT: &[u8] = b"Rusty Teams demo file\n";
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum DownloadState {
15 Saving(u8),
16 Saved(PathBuf),
17 Failed(String),
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum ClickAction {
22 Start,
23 Reveal(PathBuf),
24 Ignore,
25}
26
27pub fn click_action(state: Option<&DownloadState>) -> ClickAction {
28 match state {
29 None | Some(DownloadState::Failed(_)) => ClickAction::Start,
30 Some(DownloadState::Saved(path)) => ClickAction::Reveal(path.clone()),
31 Some(DownloadState::Saving(_)) => ClickAction::Ignore,
32 }
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct ButtonLook {
37 pub symbol: &'static str,
38 pub percent: Option<u8>,
39 pub tooltip: String,
40 pub clickable: bool,
41}
42
43pub fn button_look(state: Option<&DownloadState>) -> ButtonLook {
44 match state {
45 None => ButtonLook {
46 symbol: "download",
47 percent: None,
48 tooltip: "Save to Downloads".to_owned(),
49 clickable: true,
50 },
51 Some(DownloadState::Saving(percent)) => ButtonLook {
52 symbol: "download",
53 percent: Some(*percent),
54 tooltip: "Saving".to_owned(),
55 clickable: false,
56 },
57 Some(DownloadState::Saved(_)) => ButtonLook {
58 symbol: "folder_open",
59 percent: None,
60 tooltip: "Show in folder".to_owned(),
61 clickable: true,
62 },
63 Some(DownloadState::Failed(reason)) => ButtonLook {
64 symbol: "refresh",
65 percent: None,
66 tooltip: format!("Save failed: {reason}. Click to retry"),
67 clickable: true,
68 },
69 }
70}
71
72pub fn percent_label(percent: u8) -> String {
73 format!("{percent} %")
74}
75
76pub fn progress_fraction(state: Option<&DownloadState>) -> Option<f32> {
77 match state {
78 Some(DownloadState::Saving(percent)) => Some(f32::from((*percent).min(100)) / 100.),
79 _ => None,
80 }
81}
82
83#[derive(Debug, Clone, PartialEq, Eq, Hash)]
84pub struct DownloadKey {
85 pub conversation_id: String,
86 pub message_key: String,
87 pub open_url: String,
88}
89
90impl DownloadKey {
91 pub fn new(conversation_id: &str, message_key: &str, open_url: &str) -> Self {
92 DownloadKey {
93 conversation_id: conversation_id.to_owned(),
94 message_key: message_key.to_owned(),
95 open_url: open_url.to_owned(),
96 }
97 }
98}
99
100#[derive(Default)]
101pub struct Downloads {
102 states: HashMap<DownloadKey, DownloadState>,
103}
104
105impl Downloads {
106 pub fn state(&self, key: &DownloadKey) -> Option<&DownloadState> {
107 self.states.get(key)
108 }
109
110 pub fn states_for(
111 &self,
112 conversation_id: &str,
113 message_key: &str,
114 open_urls: &[&str],
115 ) -> Vec<Option<DownloadState>> {
116 open_urls
117 .iter()
118 .map(|open_url| {
119 self.state(&DownloadKey::new(conversation_id, message_key, open_url))
120 .cloned()
121 })
122 .collect()
123 }
124
125 pub fn begin(&mut self, key: &DownloadKey) -> bool {
126 if matches!(self.state(key), Some(DownloadState::Saving(_))) {
127 return false;
128 }
129 self.states.insert(key.clone(), DownloadState::Saving(0));
130 true
131 }
132
133 pub fn set_progress(&mut self, key: &DownloadKey, percent: u8) {
134 if let Some(state @ DownloadState::Saving(_)) = self.states.get_mut(key) {
135 *state = DownloadState::Saving(percent.min(100));
136 }
137 }
138
139 pub fn finish(&mut self, key: &DownloadKey, outcome: Result<PathBuf, String>) {
140 if !matches!(self.state(key), Some(DownloadState::Saving(_))) {
141 return;
142 }
143 let state = match outcome {
144 Ok(path) => DownloadState::Saved(path),
145 Err(reason) => DownloadState::Failed(reason),
146 };
147 self.states.insert(key.clone(), state);
148 }
149}
150
151fn is_format_character(character: char) -> bool {
152 matches!(
153 character,
154 '\u{ad}'
155 | '\u{61c}'
156 | '\u{200b}'..='\u{200f}'
157 | '\u{202a}'..='\u{202e}'
158 | '\u{2060}'..='\u{2064}'
159 | '\u{2066}'..='\u{2069}'
160 | '\u{feff}'
161 )
162}
163
164fn is_reserved_windows_name(name: &str) -> bool {
165 let stem = name.split('.').next().unwrap_or_default().trim_end();
166 let upper = stem.to_ascii_uppercase();
167 matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
168 || ["COM", "LPT"].iter().any(|prefix| {
169 upper
170 .strip_prefix(prefix)
171 .is_some_and(|number| matches!(number.as_bytes(), [b'1'..=b'9']))
172 })
173}
174
175pub fn safe_file_name(name: &str) -> String {
176 let cleaned: String = name
177 .chars()
178 .filter(|character| !is_format_character(*character))
179 .map(|character| {
180 if character.is_control() || "/\\:*?\"<>|".contains(character) {
181 '_'
182 } else {
183 character
184 }
185 })
186 .collect();
187 let trimmed = cleaned.trim_start().trim_end_matches([' ', '.']);
188 if trimmed.is_empty() {
189 FALLBACK_FILE_NAME.to_owned()
190 } else if is_reserved_windows_name(trimmed) {
191 format!("_{trimmed}")
192 } else {
193 trimmed.to_owned()
194 }
195}
196
197fn split_extension(file_name: &str) -> (&str, &str) {
198 match file_name.rfind('.') {
199 Some(dot) if dot > 0 && file_name.len() - dot <= MAX_EXTENSION_BYTES => {
200 file_name.split_at(dot)
201 }
202 _ => (file_name, ""),
203 }
204}
205
206fn truncate_on_boundary(text: &str, max_bytes: usize) -> &str {
207 let mut end = max_bytes.min(text.len());
208 while !text.is_char_boundary(end) {
209 end -= 1;
210 }
211 &text[..end]
212}
213
214pub fn numbered_name(file_name: &str, number: usize) -> String {
215 let (stem, extension) = split_extension(file_name);
216 let suffix = if number == 0 {
217 String::new()
218 } else {
219 format!(" ({number})")
220 };
221 let budget = MAX_NAME_BYTES.saturating_sub(PART_SUFFIX.len() + suffix.len() + extension.len());
222 format!("{}{suffix}{extension}", truncate_on_boundary(stem, budget))
223}
224
225pub fn pick_downloads_directory(download: Option<PathBuf>, home: Option<PathBuf>) -> PathBuf {
226 download.or(home).unwrap_or_else(std::env::temp_dir)
227}
228
229pub fn downloads_directory() -> PathBuf {
230 let directories = directories::UserDirs::new();
231 pick_downloads_directory(
232 directories
233 .as_ref()
234 .and_then(|directories| directories.download_dir().map(Path::to_path_buf)),
235 directories
236 .as_ref()
237 .map(|directories| directories.home_dir().to_path_buf()),
238 )
239}
240
241pub fn demo_directory() -> PathBuf {
242 std::env::temp_dir().join(DEMO_DIRECTORY)
243}
244
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub enum RevealTarget {
247 File(PathBuf),
248 Folder(PathBuf),
249}
250
251pub fn reveal_target(path: &Path, exists: bool, fallback_folder: PathBuf) -> RevealTarget {
252 if exists {
253 RevealTarget::File(path.to_path_buf())
254 } else {
255 RevealTarget::Folder(fallback_folder)
256 }
257}
258
259#[cfg_attr(not(windows), allow(dead_code))]
260pub fn explorer_select_argument(path: &Path) -> String {
261 format!("/select,\"{}\"", path.display())
262}
263
264pub fn reveal_in_file_manager(path: &Path) {
265 let mut command = reveal_command(path);
266 if let Ok(mut child) = command.spawn() {
267 std::thread::spawn(move || {
268 let _ = child.wait();
269 });
270 }
271}
272
273#[cfg(windows)]
274fn reveal_command(path: &Path) -> std::process::Command {
275 use std::os::windows::process::CommandExt as _;
276 let mut command = std::process::Command::new("explorer.exe");
277 command.raw_arg(explorer_select_argument(path));
278 command
279}
280
281#[cfg(target_os = "macos")]
282fn reveal_command(path: &Path) -> std::process::Command {
283 let mut command = std::process::Command::new("open");
284 command.arg("-R").arg(path);
285 command
286}
287
288#[cfg(not(any(windows, target_os = "macos")))]
289fn reveal_command(path: &Path) -> std::process::Command {
290 let mut command = std::process::Command::new("xdg-open");
291 command.arg(path.parent().unwrap_or(path));
292 command
293}
294
295pub struct PartFile {
296 file: Option<File>,
297 part: PathBuf,
298 target: PathBuf,
299 finished: bool,
300}
301
302fn part_path(target: &Path) -> PathBuf {
303 let mut name = target.as_os_str().to_owned();
304 name.push(PART_SUFFIX);
305 PathBuf::from(name)
306}
307
308fn reserve_name(directory: &Path, file_name: &str) -> std::io::Result<(PathBuf, File)> {
309 let create_new = |path: &Path| OpenOptions::new().write(true).create_new(true).open(path);
310 for number in 0usize.. {
311 let candidate = directory.join(numbered_name(file_name, number));
312 match create_new(&candidate) {
313 Ok(_) => {}
314 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
315 Err(error) => return Err(error),
316 }
317 match create_new(&part_path(&candidate)) {
318 Ok(part) => return Ok((candidate, part)),
319 Err(error) => {
320 let _ = std::fs::remove_file(&candidate);
321 if error.kind() != std::io::ErrorKind::AlreadyExists {
322 return Err(error);
323 }
324 }
325 }
326 }
327 unreachable!("the numbering loop only returns")
328}
329
330impl PartFile {
331 pub fn create(directory: &Path, file_name: &str) -> std::io::Result<Self> {
332 std::fs::create_dir_all(directory)?;
333 let (target, file) = reserve_name(directory, &safe_file_name(file_name))?;
334 Ok(PartFile {
335 file: Some(file),
336 part: part_path(&target),
337 target,
338 finished: false,
339 })
340 }
341
342 pub fn write(&mut self, bytes: &[u8]) -> std::io::Result<()> {
343 match self.file.as_mut() {
344 Some(file) => file.write_all(bytes),
345 None => Err(std::io::Error::other("the file is already closed")),
346 }
347 }
348
349 pub fn finish(mut self) -> std::io::Result<PathBuf> {
350 if let Some(mut file) = self.file.take() {
351 file.flush()?;
352 }
353 std::fs::rename(&self.part, &self.target)?;
354 self.finished = true;
355 Ok(self.target.clone())
356 }
357}
358
359impl Drop for PartFile {
360 fn drop(&mut self) {
361 if !self.finished {
362 self.file.take();
363 let _ = std::fs::remove_file(&self.part);
364 let _ = std::fs::remove_file(&self.target);
365 }
366 }
367}
368
369pub fn write_demo_file(file_name: &str) -> std::io::Result<PathBuf> {
370 let mut part = PartFile::create(&demo_directory(), file_name)?;
371 part.write(DEMO_CONTENT)?;
372 part.finish()
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378
379 #[test]
380 fn numbering_goes_before_the_extension_in_brackets() {
381 assert_eq!(numbered_name("plan.pdf", 0), "plan.pdf");
382 assert_eq!(numbered_name("plan.pdf", 1), "plan (1).pdf");
383 assert_eq!(numbered_name("plan.pdf", 12), "plan (12).pdf");
384 assert_eq!(numbered_name("a.tar.gz", 2), "a.tar (2).gz");
385 assert_eq!(numbered_name("README", 3), "README (3)");
386 assert_eq!(numbered_name(".env", 1), ".env (1)");
387 }
388
389 #[test]
390 fn numbering_skips_names_that_exist() {
391 let directory = tempfile::tempdir().unwrap();
392 std::fs::write(directory.path().join("plan.pdf"), b"").unwrap();
393 std::fs::write(directory.path().join("plan (1).pdf"), b"").unwrap();
394 let (path, _) = reserve_name(directory.path(), "plan.pdf").unwrap();
395 assert_eq!(path, directory.path().join("plan (2).pdf"));
396 let (next, _) = reserve_name(directory.path(), "plan.pdf").unwrap();
397 assert_eq!(next, directory.path().join("plan (3).pdf"));
398 assert_eq!(
399 reserve_name(directory.path(), "new.pdf").unwrap().0,
400 directory.path().join("new.pdf")
401 );
402 }
403
404 #[test]
405 fn a_stale_part_file_is_left_alone() {
406 let directory = tempfile::tempdir().unwrap();
407 std::fs::write(directory.path().join("plan.pdf.part"), b"old").unwrap();
408 let (path, _) = reserve_name(directory.path(), "plan.pdf").unwrap();
409 assert_eq!(path, directory.path().join("plan (1).pdf"));
410 assert!(!directory.path().join("plan.pdf").exists());
411 assert_eq!(
412 std::fs::read(directory.path().join("plan.pdf.part")).unwrap(),
413 b"old"
414 );
415 }
416
417 #[test]
418 fn concurrent_saves_of_one_name_get_separate_files() {
419 let directory = tempfile::tempdir().unwrap();
420 let mut first = PartFile::create(directory.path(), "a.txt").unwrap();
421 let mut second = PartFile::create(directory.path(), "a.txt").unwrap();
422 first.write(b"1").unwrap();
423 second.write(b"2").unwrap();
424 let first_path = first.finish().unwrap();
425 let second_path = second.finish().unwrap();
426 assert_eq!(std::fs::read(first_path).unwrap(), b"1");
427 assert_eq!(std::fs::read(second_path).unwrap(), b"2");
428 }
429
430 #[test]
431 fn names_are_cut_so_the_part_file_fits_255_bytes() {
432 let long = format!("{}.pdf", "x".repeat(400));
433 for number in [0, 1, 123] {
434 let name = numbered_name(&long, number);
435 assert!(name.len() + PART_SUFFIX.len() <= 255, "{}", name.len());
436 assert!(name.ends_with(".pdf"));
437 }
438 assert!(numbered_name(&long, 12).ends_with(" (12).pdf"));
439 let wide = format!("{}.txt", "\u{e4}".repeat(200));
440 let name = numbered_name(&wide, 1);
441 assert!(name.len() + PART_SUFFIX.len() <= 255);
442 assert!(name.ends_with(" (1).txt"));
443 let huge_extension = format!("a.{}", "e".repeat(400));
444 assert!(numbered_name(&huge_extension, 0).len() + PART_SUFFIX.len() <= 255);
445 }
446
447 #[test]
448 fn trailing_spaces_and_dots_go_together() {
449 assert_eq!(safe_file_name("report ."), "report");
450 assert_eq!(safe_file_name("report. . "), "report");
451 assert_eq!(safe_file_name(" a.txt"), "a.txt");
452 }
453
454 #[test]
455 fn windows_reserved_names_get_a_prefix() {
456 assert_eq!(safe_file_name("CON"), "_CON");
457 assert_eq!(safe_file_name("nul.txt"), "_nul.txt");
458 assert_eq!(safe_file_name("Com1.tar.gz"), "_Com1.tar.gz");
459 assert_eq!(safe_file_name("lpt9"), "_lpt9");
460 assert_eq!(safe_file_name("COM0"), "COM0");
461 assert_eq!(safe_file_name("console.txt"), "console.txt");
462 }
463
464 #[test]
465 fn direction_overrides_and_format_characters_are_removed() {
466 assert_eq!(safe_file_name("a\u{202e}fdp.exe"), "afdp.exe");
467 assert_eq!(safe_file_name("\u{2066}b\u{2069}.txt\u{200f}"), "b.txt");
468 assert_eq!(safe_file_name("\u{feff}c.txt"), "c.txt");
469 }
470
471 #[test]
472 fn file_names_lose_path_parts_and_reserved_characters() {
473 assert_eq!(safe_file_name("../a/b.pdf"), ".._a_b.pdf");
474 assert_eq!(safe_file_name("q: 1?.txt"), "q_ 1_.txt");
475 assert_eq!(safe_file_name(" "), "file");
476 assert_eq!(safe_file_name("..."), "file");
477 }
478
479 #[test]
480 fn downloads_directory_falls_back_to_home_then_temp() {
481 let download = Some(PathBuf::from("/dl"));
482 let home = Some(PathBuf::from("/home/me"));
483 assert_eq!(
484 pick_downloads_directory(download.clone(), home.clone()),
485 PathBuf::from("/dl")
486 );
487 assert_eq!(
488 pick_downloads_directory(None, home),
489 PathBuf::from("/home/me")
490 );
491 assert_eq!(pick_downloads_directory(None, None), std::env::temp_dir());
492 }
493
494 #[test]
495 fn click_starts_reveals_or_waits_by_state() {
496 let path = PathBuf::from("/d/a.pdf");
497 assert_eq!(click_action(None), ClickAction::Start);
498 assert_eq!(
499 click_action(Some(&DownloadState::Failed("x".into()))),
500 ClickAction::Start
501 );
502 assert_eq!(
503 click_action(Some(&DownloadState::Saving(5))),
504 ClickAction::Ignore
505 );
506 assert_eq!(
507 click_action(Some(&DownloadState::Saved(path.clone()))),
508 ClickAction::Reveal(path)
509 );
510 }
511
512 fn key(message: &str, url: &str) -> DownloadKey {
513 DownloadKey::new("chat", message, url)
514 }
515
516 #[test]
517 fn states_move_from_saving_to_saved_or_failed() {
518 let mut downloads = Downloads::default();
519 let key = key("m1", "u");
520 assert!(downloads.begin(&key));
521 assert!(!downloads.begin(&key));
522 downloads.set_progress(&key, 42);
523 assert_eq!(downloads.state(&key), Some(&DownloadState::Saving(42)));
524 downloads.finish(&key, Err("offline".into()));
525 assert_eq!(
526 downloads.state(&key),
527 Some(&DownloadState::Failed("offline".into()))
528 );
529 assert!(downloads.begin(&key));
530 assert_eq!(downloads.state(&key), Some(&DownloadState::Saving(0)));
531 downloads.finish(&key, Ok(PathBuf::from("/d/a.pdf")));
532 assert_eq!(
533 downloads.state(&key),
534 Some(&DownloadState::Saved(PathBuf::from("/d/a.pdf")))
535 );
536 }
537
538 #[test]
539 fn late_progress_and_results_do_not_change_settled_states() {
540 let mut downloads = Downloads::default();
541 let key = key("m1", "u");
542 downloads.set_progress(&key, 10);
543 downloads.finish(&key, Ok(PathBuf::from("/x")));
544 assert_eq!(downloads.state(&key), None);
545 downloads.begin(&key);
546 downloads.finish(&key, Ok(PathBuf::from("/d/a.pdf")));
547 downloads.set_progress(&key, 50);
548 assert!(matches!(
549 downloads.state(&key),
550 Some(DownloadState::Saved(_))
551 ));
552 }
553
554 #[test]
555 fn states_are_kept_per_conversation_message_and_url() {
556 let mut downloads = Downloads::default();
557 downloads.begin(&DownloadKey::new("chat", "m1", "u2"));
558 downloads.begin(&DownloadKey::new("chat", "m2", "u1"));
559 downloads.begin(&DownloadKey::new("other", "m1", "u1"));
560 let states = downloads.states_for("chat", "m1", &["u1", "u2"]);
561 assert_eq!(states, vec![None, Some(DownloadState::Saving(0))]);
562 }
563
564 #[test]
565 fn button_follows_the_state() {
566 let idle = button_look(None);
567 assert_eq!(
568 (idle.symbol, idle.tooltip.as_str()),
569 ("download", "Save to Downloads")
570 );
571 assert!(idle.clickable);
572 let saving = button_look(Some(&DownloadState::Saving(42)));
573 assert_eq!(saving.percent, Some(42));
574 assert!(!saving.clickable);
575 let saved = button_look(Some(&DownloadState::Saved(PathBuf::from("/a"))));
576 assert_eq!(
577 (saved.symbol, saved.tooltip.as_str()),
578 ("folder_open", "Show in folder")
579 );
580 let failed = button_look(Some(&DownloadState::Failed("HTTP 404".into())));
581 assert_eq!(failed.symbol, "refresh");
582 assert_eq!(failed.tooltip, "Save failed: HTTP 404. Click to retry");
583 assert_eq!(percent_label(42), "42 %");
584 }
585
586 #[test]
587 fn progress_bar_only_while_saving() {
588 assert_eq!(
589 progress_fraction(Some(&DownloadState::Saving(50))),
590 Some(0.5)
591 );
592 assert_eq!(progress_fraction(None), None);
593 assert_eq!(
594 progress_fraction(Some(&DownloadState::Saved(PathBuf::new()))),
595 None
596 );
597 }
598
599 #[test]
600 fn missing_file_falls_back_to_the_folder() {
601 let path = Path::new("/d/a.pdf");
602 assert_eq!(
603 reveal_target(path, true, PathBuf::from("/d")),
604 RevealTarget::File(path.to_path_buf())
605 );
606 assert_eq!(
607 reveal_target(path, false, PathBuf::from("/d")),
608 RevealTarget::Folder(PathBuf::from("/d"))
609 );
610 }
611
612 #[test]
613 fn explorer_gets_the_path_quoted_after_select() {
614 assert_eq!(
615 explorer_select_argument(Path::new("C:\\Users\\me\\Downloads\\a b.pdf")),
616 "/select,\"C:\\Users\\me\\Downloads\\a b.pdf\""
617 );
618 }
619
620 #[test]
621 fn part_file_is_renamed_on_finish() {
622 let directory = tempfile::tempdir().unwrap();
623 let mut part = PartFile::create(directory.path(), "a.txt").unwrap();
624 part.write(b"hi").unwrap();
625 assert!(directory.path().join("a.txt.part").exists());
626 let path = part.finish().unwrap();
627 assert_eq!(path, directory.path().join("a.txt"));
628 assert_eq!(std::fs::read(&path).unwrap(), b"hi");
629 assert!(!directory.path().join("a.txt.part").exists());
630 }
631
632 #[test]
633 fn part_file_is_removed_when_dropped_unfinished() {
634 let directory = tempfile::tempdir().unwrap();
635 let mut part = PartFile::create(directory.path(), "a.txt").unwrap();
636 part.write(b"hi").unwrap();
637 drop(part);
638 assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0);
639 }
640
641 #[test]
642 fn a_file_that_appears_meanwhile_is_not_replaced() {
643 let directory = tempfile::tempdir().unwrap();
644 let part = PartFile::create(directory.path(), "a.txt").unwrap();
645 let other = PartFile::create(directory.path(), "a.txt").unwrap();
646 drop(part);
647 std::fs::write(directory.path().join("a.txt"), b"browser").unwrap();
648 let mut other = other;
649 other.write(b"ours").unwrap();
650 assert_eq!(other.finish().unwrap(), directory.path().join("a (1).txt"));
651 assert_eq!(
652 std::fs::read(directory.path().join("a.txt")).unwrap(),
653 b"browser"
654 );
655 }
656
657 #[test]
658 fn existing_files_are_never_overwritten() {
659 let directory = tempfile::tempdir().unwrap();
660 std::fs::write(directory.path().join("a.txt"), b"old").unwrap();
661 let mut part = PartFile::create(directory.path(), "a.txt").unwrap();
662 part.write(b"new").unwrap();
663 let path = part.finish().unwrap();
664 assert_eq!(path, directory.path().join("a (1).txt"));
665 assert_eq!(
666 std::fs::read(directory.path().join("a.txt")).unwrap(),
667 b"old"
668 );
669 }
670}
crates/app/src/main.rs +1 −0
@@ -9,6 +9,7 @@ mod avatar_image;
9 9 mod backend;
10 10 mod data;
11 11 mod demo;
12 mod downloads;
12 13 mod emoji;
13 14 mod format;
14 15 mod frame_log;
@@ -9,6 +9,7 @@ mod avatar_image;
9mod backend;
9mod backend;
10mod data;
10mod data;
11mod demo;
11mod demo;
12mod downloads;
12mod emoji;
13mod emoji;
13mod format;
14mod format;
14mod frame_log;
15mod frame_log;
crates/app/src/views/attachments.rs +87 −9
@@ -1,11 +1,14 @@
1 use std::rc::Rc;
2
1 3 use gpui_kit::assets::IconName;
2 use gpui_kit::component::{h_flex, v_flex};
4 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
3 5 use gpui_kit::prelude::FluentBuilder as _;
4 6 use gpui_kit::*;
5 7 use teams_core::{FileCard, FileKind, ImageRef};
6 8
7 use super::widgets::icon;
9 use super::widgets::{icon, symbol};
8 10 use crate::data::Directory;
11 use crate::downloads::{self, DownloadState};
9 12 use crate::format;
10 13 use crate::rows::LocalImage;
11 14 use crate::theme;
@@ -17,6 +20,17 @@ const IMAGE_FALLBACK: (f32, f32) = (240., 160.);
17 20 const IMAGE_RADIUS: f32 = 10.;
18 21 const FILE_CARD_WIDTH: f32 = 300.;
19 22 const FILE_BADGE_SIZE: f32 = 34.;
23 const SAVE_BUTTON_SIZE: f32 = 28.;
24 const SAVE_BUTTON_RADIUS: f32 = 6.;
25 const SAVE_PROGRESS_HEIGHT: f32 = 2.;
26
27 pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
28
29 #[derive(Clone)]
30 pub struct FileActions {
31 pub states: Vec<Option<DownloadState>>,
32 pub activate: FileActivate,
33 }
20 34
21 35 pub fn fit_image(size: Option<(u32, u32)>) -> (f32, f32) {
22 36 let Some((width, height)) = size.filter(|(width, height)| *width > 0 && *height > 0) else {
@@ -158,11 +172,65 @@ fn local_image_view(image: &LocalImage, id: String) -> AnyElement {
158 172 .into_any_element()
159 173 }
160 174
161 fn file_view(card: &FileCard, id: String) -> AnyElement {
175 fn save_button(
176 state: Option<&DownloadState>,
177 id: String,
178 index: usize,
179 activate: FileActivate,
180 ) -> Stateful<Div> {
181 let look = downloads::button_look(state);
182 let tooltip = look.tooltip.clone();
183 let clickable = look.clickable;
184 let button = div()
185 .id(ElementId::Name(id.into()))
186 .size(px(SAVE_BUTTON_SIZE))
187 .flex_none()
188 .flex()
189 .items_center()
190 .justify_center()
191 .rounded(px(SAVE_BUTTON_RADIUS))
192 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
193 .when(look.clickable, |button| {
194 button
195 .cursor_pointer()
196 .hover(|button| button.bg(theme::row_hover()))
197 })
198 .on_click(move |_, _, cx| {
199 cx.stop_propagation();
200 if clickable {
201 activate(index, cx);
202 }
203 });
204 match look.percent {
205 Some(percent) => button.child(
206 div()
207 .text_size(px(11.))
208 .text_color(theme::text_muted())
209 .child(downloads::percent_label(percent)),
210 ),
211 None => button.child(symbol(look.symbol, 16., theme::text_muted())),
212 }
213 }
214
215 fn file_view(
216 card: &FileCard,
217 id: String,
218 index: usize,
219 actions: Option<&FileActions>,
220 ) -> AnyElement {
162 221 let badge = file_badge(card.kind, FILE_BADGE_SIZE);
163 222 let url = card.open_url.clone();
223 let state = actions
224 .and_then(|actions| actions.states.get(index))
225 .and_then(Option::as_ref);
226 let progress = downloads::progress_fraction(state);
227 let button = actions
228 .filter(|_| !card.open_url.is_empty())
229 .map(|actions| save_button(state, format!("{id}-save"), index, actions.activate.clone()));
164 230 h_flex()
165 231 .id(ElementId::Name(id.into()))
232 .relative()
233 .overflow_hidden()
166 234 .w(px(FILE_CARD_WIDTH))
167 235 .max_w(relative(1.))
168 236 .gap(px(10.))
@@ -196,6 +264,18 @@ fn file_view(card: &FileCard, id: String) -> AnyElement {
196 264 ),
197 265 )
198 266 .child(icon(IconName::ExternalLink, 14., theme::text_muted()))
267 .children(button)
268 .when_some(progress, |card, fraction| {
269 card.child(
270 div()
271 .absolute()
272 .left_0()
273 .bottom_0()
274 .h(px(SAVE_PROGRESS_HEIGHT))
275 .w(relative(fraction))
276 .bg(theme::accent()),
277 )
278 })
199 279 .on_click(move |_, _, cx| cx.open_url(&url))
200 280 .into_any_element()
201 281 }
@@ -206,6 +286,7 @@ pub fn attachments_view(
206 286 files: &[FileCard],
207 287 id: &str,
208 288 directory: &Directory,
289 file_actions: Option<&FileActions>,
209 290 ) -> Option<Div> {
210 291 if images.is_empty() && local_images.is_empty() && files.is_empty() {
211 292 return None;
@@ -224,12 +305,9 @@ pub fn attachments_view(
224 305 local_image_view(image, format!("{id}-local-image-{index}"))
225 306 }),
226 307 )
227 .children(
228 files
229 .iter()
230 .enumerate()
231 .map(|(index, card)| file_view(card, format!("{id}-file-{index}"))),
232 ),
308 .children(files.iter().enumerate().map(|(index, card)| {
309 file_view(card, format!("{id}-file-{index}"), index, file_actions)
310 })),
233 311 )
234 312 }
235 313
@@ -1,11 +1,14 @@
1use std::rc::Rc;
2
1use gpui_kit::assets::IconName;
3use gpui_kit::assets::IconName;
2use gpui_kit::component::{h_flex, v_flex};
4use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
3use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
6use gpui_kit::*;
5use teams_core::{FileCard, FileKind, ImageRef};
7use teams_core::{FileCard, FileKind, ImageRef};
6
8
7use super::widgets::icon;
9use super::widgets::{icon, symbol};
8use crate::data::Directory;
10use crate::data::Directory;
11use crate::downloads::{self, DownloadState};
9use crate::format;
12use crate::format;
10use crate::rows::LocalImage;
13use crate::rows::LocalImage;
11use crate::theme;
14use crate::theme;
@@ -17,6 +20,17 @@ const IMAGE_FALLBACK: (f32, f32) = (240., 160.);
17const IMAGE_RADIUS: f32 = 10.;
20const IMAGE_RADIUS: f32 = 10.;
18const FILE_CARD_WIDTH: f32 = 300.;
21const FILE_CARD_WIDTH: f32 = 300.;
19const FILE_BADGE_SIZE: f32 = 34.;
22const FILE_BADGE_SIZE: f32 = 34.;
23const SAVE_BUTTON_SIZE: f32 = 28.;
24const SAVE_BUTTON_RADIUS: f32 = 6.;
25const SAVE_PROGRESS_HEIGHT: f32 = 2.;
26
27pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
28
29#[derive(Clone)]
30pub struct FileActions {
31 pub states: Vec<Option<DownloadState>>,
32 pub activate: FileActivate,
33}
20
34
21pub fn fit_image(size: Option<(u32, u32)>) -> (f32, f32) {
35pub fn fit_image(size: Option<(u32, u32)>) -> (f32, f32) {
22 let Some((width, height)) = size.filter(|(width, height)| *width > 0 && *height > 0) else {
36 let Some((width, height)) = size.filter(|(width, height)| *width > 0 && *height > 0) else {
@@ -158,11 +172,65 @@ fn local_image_view(image: &LocalImage, id: String) -> AnyElement {
158 .into_any_element()
172 .into_any_element()
159}
173}
160
174
161fn file_view(card: &FileCard, id: String) -> AnyElement {
175fn save_button(
176 state: Option<&DownloadState>,
177 id: String,
178 index: usize,
179 activate: FileActivate,
180) -> Stateful<Div> {
181 let look = downloads::button_look(state);
182 let tooltip = look.tooltip.clone();
183 let clickable = look.clickable;
184 let button = div()
185 .id(ElementId::Name(id.into()))
186 .size(px(SAVE_BUTTON_SIZE))
187 .flex_none()
188 .flex()
189 .items_center()
190 .justify_center()
191 .rounded(px(SAVE_BUTTON_RADIUS))
192 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
193 .when(look.clickable, |button| {
194 button
195 .cursor_pointer()
196 .hover(|button| button.bg(theme::row_hover()))
197 })
198 .on_click(move |_, _, cx| {
199 cx.stop_propagation();
200 if clickable {
201 activate(index, cx);
202 }
203 });
204 match look.percent {
205 Some(percent) => button.child(
206 div()
207 .text_size(px(11.))
208 .text_color(theme::text_muted())
209 .child(downloads::percent_label(percent)),
210 ),
211 None => button.child(symbol(look.symbol, 16., theme::text_muted())),
212 }
213}
214
215fn file_view(
216 card: &FileCard,
217 id: String,
218 index: usize,
219 actions: Option<&FileActions>,
220) -> AnyElement {
162 let badge = file_badge(card.kind, FILE_BADGE_SIZE);
221 let badge = file_badge(card.kind, FILE_BADGE_SIZE);
163 let url = card.open_url.clone();
222 let url = card.open_url.clone();
223 let state = actions
224 .and_then(|actions| actions.states.get(index))
225 .and_then(Option::as_ref);
226 let progress = downloads::progress_fraction(state);
227 let button = actions
228 .filter(|_| !card.open_url.is_empty())
229 .map(|actions| save_button(state, format!("{id}-save"), index, actions.activate.clone()));
164 h_flex()
230 h_flex()
165 .id(ElementId::Name(id.into()))
231 .id(ElementId::Name(id.into()))
232 .relative()
233 .overflow_hidden()
166 .w(px(FILE_CARD_WIDTH))
234 .w(px(FILE_CARD_WIDTH))
167 .max_w(relative(1.))
235 .max_w(relative(1.))
168 .gap(px(10.))
236 .gap(px(10.))
@@ -196,6 +264,18 @@ fn file_view(card: &FileCard, id: String) -> AnyElement {
196 ),
264 ),
197 )
265 )
198 .child(icon(IconName::ExternalLink, 14., theme::text_muted()))
266 .child(icon(IconName::ExternalLink, 14., theme::text_muted()))
267 .children(button)
268 .when_some(progress, |card, fraction| {
269 card.child(
270 div()
271 .absolute()
272 .left_0()
273 .bottom_0()
274 .h(px(SAVE_PROGRESS_HEIGHT))
275 .w(relative(fraction))
276 .bg(theme::accent()),
277 )
278 })
199 .on_click(move |_, _, cx| cx.open_url(&url))
279 .on_click(move |_, _, cx| cx.open_url(&url))
200 .into_any_element()
280 .into_any_element()
201}
281}
@@ -206,6 +286,7 @@ pub fn attachments_view(
206 files: &[FileCard],
286 files: &[FileCard],
207 id: &str,
287 id: &str,
208 directory: &Directory,
288 directory: &Directory,
289 file_actions: Option<&FileActions>,
209) -> Option<Div> {
290) -> Option<Div> {
210 if images.is_empty() && local_images.is_empty() && files.is_empty() {
291 if images.is_empty() && local_images.is_empty() && files.is_empty() {
211 return None;
292 return None;
@@ -224,12 +305,9 @@ pub fn attachments_view(
224 local_image_view(image, format!("{id}-local-image-{index}"))
305 local_image_view(image, format!("{id}-local-image-{index}"))
225 }),
306 }),
226 )
307 )
227 .children(
308 .children(files.iter().enumerate().map(|(index, card)| {
228 files
309 file_view(card, format!("{id}-file-{index}"), index, file_actions)
229 .iter()
310 })),
230 .enumerate()
231 .map(|(index, card)| file_view(card, format!("{id}-file-{index}"))),
232 ),
233 )
311 )
234}
312}
235
313
crates/app/src/views/conversation.rs +154 −0
@@ -1,5 +1,6 @@
1 1 use std::cell::RefCell;
2 2 use std::collections::HashMap;
3 use std::path::{Path, PathBuf};
3 4 use std::rc::Rc;
4 5 use std::time::{Duration, Instant};
5 6
@@ -17,6 +18,7 @@ use gpui_kit::*;
17 18 use store::MessageRecord;
18 19 use teams_core::{FileCard, ImageRef, MentionInput};
19 20
21 use super::attachments::FileActions;
20 22 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
21 23 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
22 24 use super::message_actions::{Action, MessageMenu};
@@ -26,7 +28,9 @@ use super::reaction_picker::{PickHandler, ReactionPicker};
26 28 use super::reaction_pills::{ReactionControls, ReactionPopover};
27 29 use super::widgets::{icon, symbol};
28 30 use crate::app_state::{AppEvent, AppState, Selection, selection_title};
31 use crate::backend::Engine;
29 32 use crate::data::{is_one_on_one, others};
33 use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
30 34 use crate::reaction_model::UNKNOWN_REACTOR;
31 35 use crate::read_state::{ReadTrigger, plan_read};
32 36 use crate::render::Block;
@@ -47,6 +51,8 @@ const GROWTH_HEADROOM: usize = 20;
47 51 const META_USER_ID: &str = "me_user_id";
48 52 const PENDING_KEY_PREFIX: &str = "pending-";
49 53 const MAX_NOTICE_CHARS: usize = 140;
54 const DEMO_DOWNLOAD_STEPS: u8 = 10;
55 const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);
50 56 const JUMP_SCAN_LIMIT: usize = 5000;
51 57 const JUMP_CONTEXT_MESSAGES: usize = 12;
52 58 const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
@@ -123,6 +129,7 @@ pub struct ConversationView {
123 129 pending: Vec<MessageRow>,
124 130 pending_counter: usize,
125 131 pending_outgoing: HashMap<String, Outgoing>,
132 downloads: Downloads,
126 133 hovered_message: Option<String>,
127 134 toolbar_hovered: Option<String>,
128 135 toolbar_pinned: Option<String>,
@@ -178,7 +185,142 @@ fn short_error(error: &dyn std::fmt::Display) -> String {
178 185 error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
179 186 }
180 187
188 enum DownloadEvent {
189 Progress(u8),
190 Finished(Result<PathBuf, String>),
191 }
192
193 async fn save_file(
194 engine: &Engine,
195 card: &FileCard,
196 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
197 ) -> Result<PathBuf, String> {
198 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
199 .map_err(|error| short_error(&error))?;
200 engine
201 .download_file(
202 &card.open_url,
203 |bytes| part.write(bytes),
204 |percent| {
205 let _ = events.send(DownloadEvent::Progress(percent));
206 },
207 )
208 .await
209 .map_err(|error| short_error(&error))?;
210 part.finish().map_err(|error| short_error(&error))
211 }
212
181 213 impl ConversationView {
214 fn file_actions(
215 &self,
216 message_key: &str,
217 files: &[FileCard],
218 view: WeakEntity<Self>,
219 ) -> FileActions {
220 let conversation_id = self.conversation_id().unwrap_or_default();
221 let (key, cards) = (message_key.to_owned(), files.to_vec());
222 let open_urls: Vec<&str> = files.iter().map(|card| card.open_url.as_str()).collect();
223 FileActions {
224 states: self
225 .downloads
226 .states_for(&conversation_id, message_key, &open_urls),
227 activate: Rc::new(move |index, cx| {
228 let Some(card) = cards.get(index).cloned() else {
229 return;
230 };
231 let key = key.clone();
232 let conversation_id = conversation_id.clone();
233 view.update(cx, |this, cx| {
234 this.activate_file(&conversation_id, &key, card, cx)
235 })
236 .ok();
237 }),
238 }
239 }
240
241 fn activate_file(
242 &mut self,
243 conversation_id: &str,
244 message_key: &str,
245 card: FileCard,
246 cx: &mut Context<Self>,
247 ) {
248 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
249 match downloads::click_action(self.downloads.state(&key)) {
250 ClickAction::Ignore => {}
251 ClickAction::Start => self.start_download(key, card, cx),
252 ClickAction::Reveal(path) => {
253 let folder = path
254 .parent()
255 .map(Path::to_path_buf)
256 .unwrap_or_else(downloads::downloads_directory);
257 match downloads::reveal_target(&path, path.exists(), folder) {
258 RevealTarget::File(path) => downloads::reveal_in_file_manager(&path),
259 RevealTarget::Folder(folder) => cx.open_with_system(&folder),
260 }
261 }
262 }
263 }
264
265 fn start_download(&mut self, key: DownloadKey, card: FileCard, cx: &mut Context<Self>) {
266 if !self.downloads.begin(&key) {
267 return;
268 }
269 cx.notify();
270 let state = self.app.read(cx);
271 let (demo, engine) = (state.mode.demo, state.engine.clone());
272 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<DownloadEvent>();
273 if demo {
274 cx.spawn(async move |this, cx| {
275 for step in 1..=DEMO_DOWNLOAD_STEPS {
276 cx.background_executor().timer(DEMO_DOWNLOAD_STEP).await;
277 let percent = (u32::from(step) * 100 / u32::from(DEMO_DOWNLOAD_STEPS)) as u8;
278 let progressed = this.update(cx, |this, cx| {
279 this.downloads.set_progress(&key, percent);
280 cx.notify();
281 });
282 if progressed.is_err() {
283 return;
284 }
285 }
286 let outcome =
287 downloads::write_demo_file(&card.name).map_err(|error| short_error(&error));
288 this.update(cx, |this, cx| {
289 this.downloads.finish(&key, outcome);
290 cx.notify();
291 })
292 .ok();
293 })
294 .detach();
295 return;
296 }
297 let Some(engine) = engine else {
298 self.downloads.finish(&key, Err("not connected".to_owned()));
299 return;
300 };
301 drop(runtime::spawn(async move {
302 let outcome = save_file(&engine, &card, &sender).await;
303 let _ = sender.send(DownloadEvent::Finished(outcome));
304 }));
305 cx.spawn(async move |this, cx| {
306 while let Some(event) = receiver.recv().await {
307 let updated = this.update(cx, |this, cx| {
308 match event {
309 DownloadEvent::Progress(percent) => {
310 this.downloads.set_progress(&key, percent)
311 }
312 DownloadEvent::Finished(outcome) => this.downloads.finish(&key, outcome),
313 }
314 cx.notify();
315 });
316 if updated.is_err() {
317 break;
318 }
319 }
320 })
321 .detach();
322 }
323
182 324 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
183 325 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
184 326 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
@@ -208,6 +350,7 @@ impl ConversationView {
208 350 pending: Vec::new(),
209 351 pending_counter: 0,
210 352 pending_outgoing: HashMap::new(),
353 downloads: Downloads::default(),
211 354 hovered_message: None,
212 355 toolbar_hovered: None,
213 356 toolbar_pinned: None,
@@ -2372,6 +2515,16 @@ impl Render for ConversationView {
2372 2515 .ok();
2373 2516 }) as Box<dyn Fn(&mut App)>
2374 2517 });
2518 let files = (is_real && !message.deleted && !message.files.is_empty())
2519 .then(|| view.upgrade())
2520 .flatten()
2521 .map(|entity| {
2522 entity.read(cx).file_actions(
2523 &message.key,
2524 &message.files,
2525 view.clone(),
2526 )
2527 });
2375 2528 let state = app.read(cx);
2376 2529 render_message_row(
2377 2530 message,
@@ -2384,6 +2537,7 @@ impl Render for ConversationView {
2384 2537 menu,
2385 2538 react,
2386 2539 reaction_controls,
2540 files,
2387 2541 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
2388 2542 },
2389 2543 &state.directory,
@@ -1,5 +1,6 @@
1use std::cell::RefCell;
1use std::cell::RefCell;
2use std::collections::HashMap;
2use std::collections::HashMap;
3use std::path::{Path, PathBuf};
3use std::rc::Rc;
4use std::rc::Rc;
4use std::time::{Duration, Instant};
5use std::time::{Duration, Instant};
5
6
@@ -17,6 +18,7 @@ use gpui_kit::*;
17use store::MessageRecord;
18use store::MessageRecord;
18use teams_core::{FileCard, ImageRef, MentionInput};
19use teams_core::{FileCard, ImageRef, MentionInput};
19
20
21use super::attachments::FileActions;
20use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
22use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
21use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
23use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
22use super::message_actions::{Action, MessageMenu};
24use super::message_actions::{Action, MessageMenu};
@@ -26,7 +28,9 @@ use super::reaction_picker::{PickHandler, ReactionPicker};
26use super::reaction_pills::{ReactionControls, ReactionPopover};
28use super::reaction_pills::{ReactionControls, ReactionPopover};
27use super::widgets::{icon, symbol};
29use super::widgets::{icon, symbol};
28use crate::app_state::{AppEvent, AppState, Selection, selection_title};
30use crate::app_state::{AppEvent, AppState, Selection, selection_title};
31use crate::backend::Engine;
29use crate::data::{is_one_on_one, others};
32use crate::data::{is_one_on_one, others};
33use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
30use crate::reaction_model::UNKNOWN_REACTOR;
34use crate::reaction_model::UNKNOWN_REACTOR;
31use crate::read_state::{ReadTrigger, plan_read};
35use crate::read_state::{ReadTrigger, plan_read};
32use crate::render::Block;
36use crate::render::Block;
@@ -47,6 +51,8 @@ const GROWTH_HEADROOM: usize = 20;
47const META_USER_ID: &str = "me_user_id";
51const META_USER_ID: &str = "me_user_id";
48const PENDING_KEY_PREFIX: &str = "pending-";
52const PENDING_KEY_PREFIX: &str = "pending-";
49const MAX_NOTICE_CHARS: usize = 140;
53const MAX_NOTICE_CHARS: usize = 140;
54const DEMO_DOWNLOAD_STEPS: u8 = 10;
55const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);
50const JUMP_SCAN_LIMIT: usize = 5000;
56const JUMP_SCAN_LIMIT: usize = 5000;
51const JUMP_CONTEXT_MESSAGES: usize = 12;
57const JUMP_CONTEXT_MESSAGES: usize = 12;
52const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
58const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
@@ -123,6 +129,7 @@ pub struct ConversationView {
123 pending: Vec<MessageRow>,
129 pending: Vec<MessageRow>,
124 pending_counter: usize,
130 pending_counter: usize,
125 pending_outgoing: HashMap<String, Outgoing>,
131 pending_outgoing: HashMap<String, Outgoing>,
132 downloads: Downloads,
126 hovered_message: Option<String>,
133 hovered_message: Option<String>,
127 toolbar_hovered: Option<String>,
134 toolbar_hovered: Option<String>,
128 toolbar_pinned: Option<String>,
135 toolbar_pinned: Option<String>,
@@ -178,7 +185,142 @@ fn short_error(error: &dyn std::fmt::Display) -> String {
178 error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
185 error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
179}
186}
180
187
188enum DownloadEvent {
189 Progress(u8),
190 Finished(Result<PathBuf, String>),
191}
192
193async fn save_file(
194 engine: &Engine,
195 card: &FileCard,
196 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
197) -> Result<PathBuf, String> {
198 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
199 .map_err(|error| short_error(&error))?;
200 engine
201 .download_file(
202 &card.open_url,
203 |bytes| part.write(bytes),
204 |percent| {
205 let _ = events.send(DownloadEvent::Progress(percent));
206 },
207 )
208 .await
209 .map_err(|error| short_error(&error))?;
210 part.finish().map_err(|error| short_error(&error))
211}
212
181impl ConversationView {
213impl ConversationView {
214 fn file_actions(
215 &self,
216 message_key: &str,
217 files: &[FileCard],
218 view: WeakEntity<Self>,
219 ) -> FileActions {
220 let conversation_id = self.conversation_id().unwrap_or_default();
221 let (key, cards) = (message_key.to_owned(), files.to_vec());
222 let open_urls: Vec<&str> = files.iter().map(|card| card.open_url.as_str()).collect();
223 FileActions {
224 states: self
225 .downloads
226 .states_for(&conversation_id, message_key, &open_urls),
227 activate: Rc::new(move |index, cx| {
228 let Some(card) = cards.get(index).cloned() else {
229 return;
230 };
231 let key = key.clone();
232 let conversation_id = conversation_id.clone();
233 view.update(cx, |this, cx| {
234 this.activate_file(&conversation_id, &key, card, cx)
235 })
236 .ok();
237 }),
238 }
239 }
240
241 fn activate_file(
242 &mut self,
243 conversation_id: &str,
244 message_key: &str,
245 card: FileCard,
246 cx: &mut Context<Self>,
247 ) {
248 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
249 match downloads::click_action(self.downloads.state(&key)) {
250 ClickAction::Ignore => {}
251 ClickAction::Start => self.start_download(key, card, cx),
252 ClickAction::Reveal(path) => {
253 let folder = path
254 .parent()
255 .map(Path::to_path_buf)
256 .unwrap_or_else(downloads::downloads_directory);
257 match downloads::reveal_target(&path, path.exists(), folder) {
258 RevealTarget::File(path) => downloads::reveal_in_file_manager(&path),
259 RevealTarget::Folder(folder) => cx.open_with_system(&folder),
260 }
261 }
262 }
263 }
264
265 fn start_download(&mut self, key: DownloadKey, card: FileCard, cx: &mut Context<Self>) {
266 if !self.downloads.begin(&key) {
267 return;
268 }
269 cx.notify();
270 let state = self.app.read(cx);
271 let (demo, engine) = (state.mode.demo, state.engine.clone());
272 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<DownloadEvent>();
273 if demo {
274 cx.spawn(async move |this, cx| {
275 for step in 1..=DEMO_DOWNLOAD_STEPS {
276 cx.background_executor().timer(DEMO_DOWNLOAD_STEP).await;
277 let percent = (u32::from(step) * 100 / u32::from(DEMO_DOWNLOAD_STEPS)) as u8;
278 let progressed = this.update(cx, |this, cx| {
279 this.downloads.set_progress(&key, percent);
280 cx.notify();
281 });
282 if progressed.is_err() {
283 return;
284 }
285 }
286 let outcome =
287 downloads::write_demo_file(&card.name).map_err(|error| short_error(&error));
288 this.update(cx, |this, cx| {
289 this.downloads.finish(&key, outcome);
290 cx.notify();
291 })
292 .ok();
293 })
294 .detach();
295 return;
296 }
297 let Some(engine) = engine else {
298 self.downloads.finish(&key, Err("not connected".to_owned()));
299 return;
300 };
301 drop(runtime::spawn(async move {
302 let outcome = save_file(&engine, &card, &sender).await;
303 let _ = sender.send(DownloadEvent::Finished(outcome));
304 }));
305 cx.spawn(async move |this, cx| {
306 while let Some(event) = receiver.recv().await {
307 let updated = this.update(cx, |this, cx| {
308 match event {
309 DownloadEvent::Progress(percent) => {
310 this.downloads.set_progress(&key, percent)
311 }
312 DownloadEvent::Finished(outcome) => this.downloads.finish(&key, outcome),
313 }
314 cx.notify();
315 });
316 if updated.is_err() {
317 break;
318 }
319 }
320 })
321 .detach();
322 }
323
182 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
324 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
183 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
325 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
184 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
326 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
@@ -208,6 +350,7 @@ impl ConversationView {
208 pending: Vec::new(),
350 pending: Vec::new(),
209 pending_counter: 0,
351 pending_counter: 0,
210 pending_outgoing: HashMap::new(),
352 pending_outgoing: HashMap::new(),
353 downloads: Downloads::default(),
211 hovered_message: None,
354 hovered_message: None,
212 toolbar_hovered: None,
355 toolbar_hovered: None,
213 toolbar_pinned: None,
356 toolbar_pinned: None,
@@ -2372,6 +2515,16 @@ impl Render for ConversationView {
2372 .ok();
2515 .ok();
2373 }) as Box<dyn Fn(&mut App)>
2516 }) as Box<dyn Fn(&mut App)>
2374 });
2517 });
2518 let files = (is_real && !message.deleted && !message.files.is_empty())
2519 .then(|| view.upgrade())
2520 .flatten()
2521 .map(|entity| {
2522 entity.read(cx).file_actions(
2523 &message.key,
2524 &message.files,
2525 view.clone(),
2526 )
2527 });
2375 let state = app.read(cx);
2528 let state = app.read(cx);
2376 render_message_row(
2529 render_message_row(
2377 message,
2530 message,
@@ -2384,6 +2537,7 @@ impl Render for ConversationView {
2384 menu,
2537 menu,
2385 react,
2538 react,
2386 reaction_controls,
2539 reaction_controls,
2540 files,
2387 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
2541 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
2388 },
2542 },
2389 &state.directory,
2543 &state.directory,
crates/app/src/views/message_row.rs +15 −3
@@ -5,7 +5,7 @@ use gpui_kit::prelude::FluentBuilder as _;
5 5 use gpui_kit::*;
6 6 use std::time::Duration;
7 7
8 use super::attachments::attachments_view;
8 use super::attachments::{FileActions, attachments_view};
9 9 use super::avatar::{member_stack, person_avatar};
10 10 use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11 11 use super::reaction_picker::PickHandler;
@@ -42,6 +42,7 @@ pub struct RowActions {
42 42 pub menu: Option<MessageMenu>,
43 43 pub react: Option<PickHandler>,
44 44 pub reaction_controls: Option<ReactionControls>,
45 pub files: Option<FileActions>,
45 46 pub highlighted: bool,
46 47 }
47 48
@@ -137,6 +138,7 @@ fn bubble(
137 138 &row.files,
138 139 &format!("message-{index}"),
139 140 directory,
141 extras.files.as_ref(),
140 142 ));
141 143 if has_reactions {
142 144 content = content.child(
@@ -192,6 +194,7 @@ struct BubbleExtras {
192 194 menu: Option<MessageMenu>,
193 195 react: Option<PickHandler>,
194 196 controls: Option<ReactionControls>,
197 files: Option<FileActions>,
195 198 }
196 199
197 200 fn bubble_meta(row: &MessageRow, own: bool) -> Div {
@@ -349,7 +352,13 @@ fn edited_marker() -> Div {
349 352 .child("Edited")
350 353 }
351 354
352 fn post_card(row: &MessageRow, index: usize, directory: &Directory, cx: &App) -> Div {
355 fn post_card(
356 row: &MessageRow,
357 index: usize,
358 directory: &Directory,
359 files: Option<&FileActions>,
360 cx: &App,
361 ) -> Div {
353 362 let header = h_flex()
354 363 .gap(px(10.))
355 364 .items_center()
@@ -453,6 +462,7 @@ fn post_card(row: &MessageRow, index: usize, directory: &Directory, cx: &App) ->
453 462 &row.files,
454 463 &format!("message-{index}"),
455 464 directory,
465 files,
456 466 ));
457 467 if !row.reactions.is_empty() {
458 468 body = body.child(reaction_pills(
@@ -562,12 +572,14 @@ pub fn render_message_row(
562 572 menu,
563 573 react,
564 574 reaction_controls,
575 files,
565 576 highlighted,
566 577 } = actions;
567 578 let extras = BubbleExtras {
568 579 menu,
569 580 react,
570 581 controls: reaction_controls,
582 files,
571 583 };
572 584 let own = row.own && !row.card;
573 585 let spacing = if row.card {
@@ -585,7 +597,7 @@ pub fn render_message_row(
585 597 container = container.child(new_marker());
586 598 }
587 599 let body = if row.card {
588 post_card(row, index, directory, cx)
600 post_card(row, index, directory, extras.files.as_ref(), cx)
589 601 } else if own {
590 602 own_row(row, index, directory, retry, extras, cx)
591 603 } else {
@@ -5,7 +5,7 @@ use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
5use gpui_kit::*;
6use std::time::Duration;
6use std::time::Duration;
7
7
8use super::attachments::attachments_view;
8use super::attachments::{FileActions, attachments_view};
9use super::avatar::{member_stack, person_avatar};
9use super::avatar::{member_stack, person_avatar};
10use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
10use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11use super::reaction_picker::PickHandler;
11use super::reaction_picker::PickHandler;
@@ -42,6 +42,7 @@ pub struct RowActions {
42 pub menu: Option<MessageMenu>,
42 pub menu: Option<MessageMenu>,
43 pub react: Option<PickHandler>,
43 pub react: Option<PickHandler>,
44 pub reaction_controls: Option<ReactionControls>,
44 pub reaction_controls: Option<ReactionControls>,
45 pub files: Option<FileActions>,
45 pub highlighted: bool,
46 pub highlighted: bool,
46}
47}
47
48
@@ -137,6 +138,7 @@ fn bubble(
137 &row.files,
138 &row.files,
138 &format!("message-{index}"),
139 &format!("message-{index}"),
139 directory,
140 directory,
141 extras.files.as_ref(),
140 ));
142 ));
141 if has_reactions {
143 if has_reactions {
142 content = content.child(
144 content = content.child(
@@ -192,6 +194,7 @@ struct BubbleExtras {
192 menu: Option<MessageMenu>,
194 menu: Option<MessageMenu>,
193 react: Option<PickHandler>,
195 react: Option<PickHandler>,
194 controls: Option<ReactionControls>,
196 controls: Option<ReactionControls>,
197 files: Option<FileActions>,
195}
198}
196
199
197fn bubble_meta(row: &MessageRow, own: bool) -> Div {
200fn bubble_meta(row: &MessageRow, own: bool) -> Div {
@@ -349,7 +352,13 @@ fn edited_marker() -> Div {
349 .child("Edited")
352 .child("Edited")
350}
353}
351
354
352fn post_card(row: &MessageRow, index: usize, directory: &Directory, cx: &App) -> Div {
355fn post_card(
356 row: &MessageRow,
357 index: usize,
358 directory: &Directory,
359 files: Option<&FileActions>,
360 cx: &App,
361) -> Div {
353 let header = h_flex()
362 let header = h_flex()
354 .gap(px(10.))
363 .gap(px(10.))
355 .items_center()
364 .items_center()
@@ -453,6 +462,7 @@ fn post_card(row: &MessageRow, index: usize, directory: &Directory, cx: &App) ->
453 &row.files,
462 &row.files,
454 &format!("message-{index}"),
463 &format!("message-{index}"),
455 directory,
464 directory,
465 files,
456 ));
466 ));
457 if !row.reactions.is_empty() {
467 if !row.reactions.is_empty() {
458 body = body.child(reaction_pills(
468 body = body.child(reaction_pills(
@@ -562,12 +572,14 @@ pub fn render_message_row(
562 menu,
572 menu,
563 react,
573 react,
564 reaction_controls,
574 reaction_controls,
575 files,
565 highlighted,
576 highlighted,
566 } = actions;
577 } = actions;
567 let extras = BubbleExtras {
578 let extras = BubbleExtras {
568 menu,
579 menu,
569 react,
580 react,
570 controls: reaction_controls,
581 controls: reaction_controls,
582 files,
571 };
583 };
572 let own = row.own && !row.card;
584 let own = row.own && !row.card;
573 let spacing = if row.card {
585 let spacing = if row.card {
@@ -585,7 +597,7 @@ pub fn render_message_row(
585 container = container.child(new_marker());
597 container = container.child(new_marker());
586 }
598 }
587 let body = if row.card {
599 let body = if row.card {
588 post_card(row, index, directory, cx)
600 post_card(row, index, directory, extras.files.as_ref(), cx)
589 } else if own {
601 } else if own {
590 own_row(row, index, directory, retry, extras, cx)
602 own_row(row, index, directory, retry, extras, cx)
591 } else {
603 } else {
crates/core/src/download.rs added +39 −0
@@ -0,0 +1,39 @@
1 use graph::{DOWNLOAD_CHUNK_BYTES, Error as GraphError, SharedFile, download_ranges, percent_done};
2
3 use crate::engine::SyncEngine;
4 use crate::error::Result;
5 use crate::remote::Remote;
6
7 impl<R: Remote> SyncEngine<R> {
8 /// Streams the file behind a OneDrive or SharePoint link chunk by chunk into `write`.
9 pub async fn download_file(
10 &self,
11 open_url: &str,
12 mut write: impl FnMut(&[u8]) -> std::io::Result<()> + Send,
13 progress: impl Fn(u8) + Send + Sync,
14 ) -> Result<SharedFile> {
15 let shared = self.remote.resolve_share(open_url).await?;
16 progress(0);
17 let ranges = download_ranges(shared.size, DOWNLOAD_CHUNK_BYTES);
18 let last = ranges.len().saturating_sub(1);
19 for (position, (start, end)) in ranges.into_iter().enumerate() {
20 let is_last = position == last;
21 let bytes = self
22 .remote
23 .download_range(&shared.download_url, start, (!is_last).then_some(end))
24 .await?;
25 let expected = end - start + 1;
26 let received = bytes.len() as u64;
27 if received < expected || (!is_last && received != expected) {
28 return Err(GraphError::Download(format!(
29 "expected {expected} bytes, got {received}"
30 ))
31 .into());
32 }
33 write(&bytes)?;
34 progress(percent_done(start + received, shared.size));
35 }
36 progress(100);
37 Ok(shared)
38 }
39 }
@@ -0,0 +1,39 @@
1use graph::{DOWNLOAD_CHUNK_BYTES, Error as GraphError, SharedFile, download_ranges, percent_done};
2
3use crate::engine::SyncEngine;
4use crate::error::Result;
5use crate::remote::Remote;
6
7impl<R: Remote> SyncEngine<R> {
8 /// Streams the file behind a OneDrive or SharePoint link chunk by chunk into `write`.
9 pub async fn download_file(
10 &self,
11 open_url: &str,
12 mut write: impl FnMut(&[u8]) -> std::io::Result<()> + Send,
13 progress: impl Fn(u8) + Send + Sync,
14 ) -> Result<SharedFile> {
15 let shared = self.remote.resolve_share(open_url).await?;
16 progress(0);
17 let ranges = download_ranges(shared.size, DOWNLOAD_CHUNK_BYTES);
18 let last = ranges.len().saturating_sub(1);
19 for (position, (start, end)) in ranges.into_iter().enumerate() {
20 let is_last = position == last;
21 let bytes = self
22 .remote
23 .download_range(&shared.download_url, start, (!is_last).then_some(end))
24 .await?;
25 let expected = end - start + 1;
26 let received = bytes.len() as u64;
27 if received < expected || (!is_last && received != expected) {
28 return Err(GraphError::Download(format!(
29 "expected {expected} bytes, got {received}"
30 ))
31 .into());
32 }
33 write(&bytes)?;
34 progress(percent_done(start + received, shared.size));
35 }
36 progress(100);
37 Ok(shared)
38 }
39}
crates/core/src/error.rs +2 −0
@@ -6,6 +6,8 @@ pub enum Error {
6 6 Graph(#[from] graph::Error),
7 7 #[error(transparent)]
8 8 Store(#[from] store::Error),
9 #[error("cannot write the file: {0}")]
10 Io(#[from] std::io::Error),
9 11 #[error("folder service: {0}")]
10 12 Folders(String),
11 13 #[error("unknown conversation {0}")]
@@ -6,6 +6,8 @@ pub enum Error {
6 Graph(#[from] graph::Error),
6 Graph(#[from] graph::Error),
7 #[error(transparent)]
7 #[error(transparent)]
8 Store(#[from] store::Error),
8 Store(#[from] store::Error),
9 #[error("cannot write the file: {0}")]
10 Io(#[from] std::io::Error),
9 #[error("folder service: {0}")]
11 #[error("folder service: {0}")]
10 Folders(String),
12 Folders(String),
11 #[error("unknown conversation {0}")]
13 #[error("unknown conversation {0}")]
crates/core/src/lib.rs +3 −1
@@ -2,6 +2,7 @@ mod actions;
2 2 mod avatars;
3 3 mod card;
4 4 mod channel_sync;
5 mod download;
5 6 mod engine;
6 7 mod error;
7 8 mod events;
@@ -28,7 +29,8 @@ pub use error::{Error, Result};
28 29 pub use events::CoreEvent;
29 30 pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};
30 31 pub use graph::{
31 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, UploadedFile,
32 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,
33 UploadedFile,
32 34 };
33 35 pub use images::StoredImage;
34 36 pub use mapping::{chat_record, message_record};
@@ -2,6 +2,7 @@ mod actions;
2mod avatars;
2mod avatars;
3mod card;
3mod card;
4mod channel_sync;
4mod channel_sync;
5mod download;
5mod engine;
6mod engine;
6mod error;
7mod error;
7mod events;
8mod events;
@@ -28,7 +29,8 @@ pub use error::{Error, Result};
28pub use events::CoreEvent;
29pub use events::CoreEvent;
29pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};
30pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};
30pub use graph::{
31pub use graph::{
31 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, UploadedFile,
32 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,
33 UploadedFile,
32};
34};
33pub use images::StoredImage;
35pub use images::StoredImage;
34pub use mapping::{chat_record, message_record};
36pub use mapping::{chat_record, message_record};
crates/core/src/remote.rs +27 −1
@@ -2,7 +2,7 @@ use chatsvc::{ConversationRef, MemberHorizon, Messages, Receipts};
2 2 use chrono::{DateTime, Utc};
3 3 use graph::{
4 4 Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
5 OutgoingMention, Photo, Presence, Team, UploadDestination, UploadedFile, User,
5 OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
6 6 };
7 7
8 8 use crate::error::{Error, Result};
@@ -155,6 +155,19 @@ pub trait Remote {
155 155 Err(Error::Unsupported("deleting a file"))
156 156 }
157 157
158 async fn resolve_share(&self, _open_url: &str) -> Result<SharedFile> {
159 Err(Error::Unsupported("resolving a shared file"))
160 }
161
162 async fn download_range(
163 &self,
164 _download_url: &str,
165 _start: u64,
166 _end: Option<u64>,
167 ) -> Result<Vec<u8>> {
168 Err(Error::Unsupported("a file download"))
169 }
170
158 171 async fn hosted_content(&self, _url: &str) -> Result<Photo> {
159 172 Err(Error::Unsupported("hosted content"))
160 173 }
@@ -419,6 +432,19 @@ impl Remote for Graph {
419 432 Ok(Graph::delete_drive_item(self, &file.drive_id, &file.item_id).await?)
420 433 }
421 434
435 async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
436 Ok(Graph::resolve_share(self, open_url).await?)
437 }
438
439 async fn download_range(
440 &self,
441 download_url: &str,
442 start: u64,
443 end: Option<u64>,
444 ) -> Result<Vec<u8>> {
445 Ok(Graph::download_range(self, download_url, start, end).await?)
446 }
447
422 448 async fn hosted_content(&self, url: &str) -> Result<Photo> {
423 449 Ok(Graph::download_hosted_content(self, url).await?)
424 450 }
@@ -2,7 +2,7 @@ use chatsvc::{ConversationRef, MemberHorizon, Messages, Receipts};
2use chrono::{DateTime, Utc};
2use chrono::{DateTime, Utc};
3use graph::{
3use graph::{
4 Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
4 Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
5 OutgoingMention, Photo, Presence, Team, UploadDestination, UploadedFile, User,
5 OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
6};
6};
7
7
8use crate::error::{Error, Result};
8use crate::error::{Error, Result};
@@ -155,6 +155,19 @@ pub trait Remote {
155 Err(Error::Unsupported("deleting a file"))
155 Err(Error::Unsupported("deleting a file"))
156 }
156 }
157
157
158 async fn resolve_share(&self, _open_url: &str) -> Result<SharedFile> {
159 Err(Error::Unsupported("resolving a shared file"))
160 }
161
162 async fn download_range(
163 &self,
164 _download_url: &str,
165 _start: u64,
166 _end: Option<u64>,
167 ) -> Result<Vec<u8>> {
168 Err(Error::Unsupported("a file download"))
169 }
170
158 async fn hosted_content(&self, _url: &str) -> Result<Photo> {
171 async fn hosted_content(&self, _url: &str) -> Result<Photo> {
159 Err(Error::Unsupported("hosted content"))
172 Err(Error::Unsupported("hosted content"))
160 }
173 }
@@ -419,6 +432,19 @@ impl Remote for Graph {
419 Ok(Graph::delete_drive_item(self, &file.drive_id, &file.item_id).await?)
432 Ok(Graph::delete_drive_item(self, &file.drive_id, &file.item_id).await?)
420 }
433 }
421
434
435 async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
436 Ok(Graph::resolve_share(self, open_url).await?)
437 }
438
439 async fn download_range(
440 &self,
441 download_url: &str,
442 start: u64,
443 end: Option<u64>,
444 ) -> Result<Vec<u8>> {
445 Ok(Graph::download_range(self, download_url, start, end).await?)
446 }
447
422 async fn hosted_content(&self, url: &str) -> Result<Photo> {
448 async fn hosted_content(&self, url: &str) -> Result<Photo> {
423 Ok(Graph::download_hosted_content(self, url).await?)
449 Ok(Graph::download_hosted_content(self, url).await?)
424 }
450 }
crates/core/tests/engine.rs +129 −1
@@ -4,7 +4,7 @@ use std::sync::{Arc, Mutex};
4 4 use chrono::{DateTime, Duration, TimeZone, Utc};
5 5 use graph::{
6 6 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
7 OutgoingMention, Photo, Presence, Team, UploadDestination, UploadedFile, User,
7 OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
8 8 };
9 9 use serde_json::json;
10 10 use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};
@@ -478,6 +478,39 @@ impl Remote for Handle {
478 478 })
479 479 }
480 480
481 async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
482 self.record(format!("resolve {open_url}"));
483 Ok(SharedFile {
484 name: "big.bin".into(),
485 size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3,
486 download_url: if open_url.contains("short") {
487 "https://dl.example/short".into()
488 } else if open_url.contains("grown") {
489 "https://dl.example/grown".into()
490 } else {
491 "https://dl.example/big".into()
492 },
493 })
494 }
495
496 async fn download_range(
497 &self,
498 download_url: &str,
499 start: u64,
500 end: Option<u64>,
501 ) -> Result<Vec<u8>> {
502 let total = 2 * graph::DOWNLOAD_CHUNK_BYTES + 3;
503 let shown_end = end.map_or(String::new(), |end| end.to_string());
504 self.record(format!("range {download_url} {start}-{shown_end}"));
505 let length = match end {
506 _ if download_url.contains("short") => 1,
507 Some(end) => end - start + 1,
508 None if download_url.contains("grown") => total - start + 10,
509 None => total - start,
510 };
511 Ok(vec![7; length as usize])
512 }
513
481 514 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
482 515 self.record(format!("share {} {}", file.item_id, user_ids.join(",")));
483 516 Ok(())
@@ -1169,6 +1202,101 @@ async fn an_edit_keeps_the_images_and_files_of_the_original() {
1169 1202 assert_eq!(extras[0].files[0].content_url, "https://x/a.pdf");
1170 1203 }
1171 1204
1205 #[tokio::test]
1206 async fn download_streams_every_chunk_and_reports_progress() {
1207 let fake = Arc::new(Fake::default());
1208 let engine = chat_engine(&fake, small_pages()).await;
1209 let written = Mutex::new(0usize);
1210 let percents = Mutex::new(Vec::new());
1211 let shared = engine
1212 .download_file(
1213 "https://files.example/doc",
1214 |bytes| {
1215 *written.lock().unwrap() += bytes.len();
1216 Ok(())
1217 },
1218 |percent| percents.lock().unwrap().push(percent),
1219 )
1220 .await
1221 .unwrap();
1222 assert_eq!(*written.lock().unwrap() as u64, shared.size);
1223 let chunk = graph::DOWNLOAD_CHUNK_BYTES;
1224 let ranges: Vec<String> = fake
1225 .calls()
1226 .into_iter()
1227 .filter(|call| call.starts_with("range"))
1228 .collect();
1229 assert_eq!(
1230 ranges,
1231 vec![
1232 format!("range https://dl.example/big 0-{}", chunk - 1),
1233 format!("range https://dl.example/big {chunk}-{}", 2 * chunk - 1),
1234 format!("range https://dl.example/big {}-", 2 * chunk),
1235 ]
1236 );
1237 let percents = percents.lock().unwrap();
1238 assert_eq!(percents.first(), Some(&0));
1239 assert_eq!(percents.last(), Some(&100));
1240 assert!(percents.windows(2).all(|pair| pair[0] <= pair[1]));
1241 }
1242
1243 #[tokio::test]
1244 async fn download_keeps_a_file_that_grew_past_the_reported_size() {
1245 let fake = Arc::new(Fake::default());
1246 let engine = chat_engine(&fake, small_pages()).await;
1247 let written = Mutex::new(0usize);
1248 let percents = Mutex::new(Vec::new());
1249 let shared = engine
1250 .download_file(
1251 "https://files.example/grown",
1252 |bytes| {
1253 *written.lock().unwrap() += bytes.len();
1254 Ok(())
1255 },
1256 |percent| percents.lock().unwrap().push(percent),
1257 )
1258 .await
1259 .unwrap();
1260 assert_eq!(*written.lock().unwrap() as u64, shared.size + 10);
1261 assert!(
1262 percents
1263 .lock()
1264 .unwrap()
1265 .iter()
1266 .all(|percent| *percent <= 100)
1267 );
1268 }
1269
1270 #[tokio::test]
1271 async fn download_rejects_a_short_chunk() {
1272 let fake = Arc::new(Fake::default());
1273 let engine = chat_engine(&fake, small_pages()).await;
1274 let result = engine
1275 .download_file("https://files.example/short", |_| Ok(()), |_| {})
1276 .await;
1277 assert!(result.is_err());
1278 }
1279
1280 #[tokio::test]
1281 async fn download_stops_when_the_writer_fails() {
1282 let fake = Arc::new(Fake::default());
1283 let engine = chat_engine(&fake, small_pages()).await;
1284 let result = engine
1285 .download_file(
1286 "https://files.example/doc",
1287 |_| Err(std::io::Error::other("disk full")),
1288 |_| {},
1289 )
1290 .await;
1291 assert!(matches!(result, Err(Error::Io(_))));
1292 let ranges = fake
1293 .calls()
1294 .into_iter()
1295 .filter(|call| call.starts_with("range"))
1296 .count();
1297 assert_eq!(ranges, 1);
1298 }
1299
1172 1300 #[tokio::test]
1173 1301 async fn upload_to_an_unknown_conversation_fails() {
1174 1302 let fake = Arc::new(Fake::default());
@@ -4,7 +4,7 @@ use std::sync::{Arc, Mutex};
4use chrono::{DateTime, Duration, TimeZone, Utc};
4use chrono::{DateTime, Duration, TimeZone, Utc};
5use graph::{
5use graph::{
6 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
6 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
7 OutgoingMention, Photo, Presence, Team, UploadDestination, UploadedFile, User,
7 OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
8};
8};
9use serde_json::json;
9use serde_json::json;
10use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};
10use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};
@@ -478,6 +478,39 @@ impl Remote for Handle {
478 })
478 })
479 }
479 }
480
480
481 async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
482 self.record(format!("resolve {open_url}"));
483 Ok(SharedFile {
484 name: "big.bin".into(),
485 size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3,
486 download_url: if open_url.contains("short") {
487 "https://dl.example/short".into()
488 } else if open_url.contains("grown") {
489 "https://dl.example/grown".into()
490 } else {
491 "https://dl.example/big".into()
492 },
493 })
494 }
495
496 async fn download_range(
497 &self,
498 download_url: &str,
499 start: u64,
500 end: Option<u64>,
501 ) -> Result<Vec<u8>> {
502 let total = 2 * graph::DOWNLOAD_CHUNK_BYTES + 3;
503 let shown_end = end.map_or(String::new(), |end| end.to_string());
504 self.record(format!("range {download_url} {start}-{shown_end}"));
505 let length = match end {
506 _ if download_url.contains("short") => 1,
507 Some(end) => end - start + 1,
508 None if download_url.contains("grown") => total - start + 10,
509 None => total - start,
510 };
511 Ok(vec![7; length as usize])
512 }
513
481 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
514 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
482 self.record(format!("share {} {}", file.item_id, user_ids.join(",")));
515 self.record(format!("share {} {}", file.item_id, user_ids.join(",")));
483 Ok(())
516 Ok(())
@@ -1169,6 +1202,101 @@ async fn an_edit_keeps_the_images_and_files_of_the_original() {
1169 assert_eq!(extras[0].files[0].content_url, "https://x/a.pdf");
1202 assert_eq!(extras[0].files[0].content_url, "https://x/a.pdf");
1170}
1203}
1171
1204
1205#[tokio::test]
1206async fn download_streams_every_chunk_and_reports_progress() {
1207 let fake = Arc::new(Fake::default());
1208 let engine = chat_engine(&fake, small_pages()).await;
1209 let written = Mutex::new(0usize);
1210 let percents = Mutex::new(Vec::new());
1211 let shared = engine
1212 .download_file(
1213 "https://files.example/doc",
1214 |bytes| {
1215 *written.lock().unwrap() += bytes.len();
1216 Ok(())
1217 },
1218 |percent| percents.lock().unwrap().push(percent),
1219 )
1220 .await
1221 .unwrap();
1222 assert_eq!(*written.lock().unwrap() as u64, shared.size);
1223 let chunk = graph::DOWNLOAD_CHUNK_BYTES;
1224 let ranges: Vec<String> = fake
1225 .calls()
1226 .into_iter()
1227 .filter(|call| call.starts_with("range"))
1228 .collect();
1229 assert_eq!(
1230 ranges,
1231 vec![
1232 format!("range https://dl.example/big 0-{}", chunk - 1),
1233 format!("range https://dl.example/big {chunk}-{}", 2 * chunk - 1),
1234 format!("range https://dl.example/big {}-", 2 * chunk),
1235 ]
1236 );
1237 let percents = percents.lock().unwrap();
1238 assert_eq!(percents.first(), Some(&0));
1239 assert_eq!(percents.last(), Some(&100));
1240 assert!(percents.windows(2).all(|pair| pair[0] <= pair[1]));
1241}
1242
1243#[tokio::test]
1244async fn download_keeps_a_file_that_grew_past_the_reported_size() {
1245 let fake = Arc::new(Fake::default());
1246 let engine = chat_engine(&fake, small_pages()).await;
1247 let written = Mutex::new(0usize);
1248 let percents = Mutex::new(Vec::new());
1249 let shared = engine
1250 .download_file(
1251 "https://files.example/grown",
1252 |bytes| {
1253 *written.lock().unwrap() += bytes.len();
1254 Ok(())
1255 },
1256 |percent| percents.lock().unwrap().push(percent),
1257 )
1258 .await
1259 .unwrap();
1260 assert_eq!(*written.lock().unwrap() as u64, shared.size + 10);
1261 assert!(
1262 percents
1263 .lock()
1264 .unwrap()
1265 .iter()
1266 .all(|percent| *percent <= 100)
1267 );
1268}
1269
1270#[tokio::test]
1271async fn download_rejects_a_short_chunk() {
1272 let fake = Arc::new(Fake::default());
1273 let engine = chat_engine(&fake, small_pages()).await;
1274 let result = engine
1275 .download_file("https://files.example/short", |_| Ok(()), |_| {})
1276 .await;
1277 assert!(result.is_err());
1278}
1279
1280#[tokio::test]
1281async fn download_stops_when_the_writer_fails() {
1282 let fake = Arc::new(Fake::default());
1283 let engine = chat_engine(&fake, small_pages()).await;
1284 let result = engine
1285 .download_file(
1286 "https://files.example/doc",
1287 |_| Err(std::io::Error::other("disk full")),
1288 |_| {},
1289 )
1290 .await;
1291 assert!(matches!(result, Err(Error::Io(_))));
1292 let ranges = fake
1293 .calls()
1294 .into_iter()
1295 .filter(|call| call.starts_with("range"))
1296 .count();
1297 assert_eq!(ranges, 1);
1298}
1299
1172#[tokio::test]
1300#[tokio::test]
1173async fn upload_to_an_unknown_conversation_fails() {
1301async fn upload_to_an_unknown_conversation_fails() {
1174 let fake = Arc::new(Fake::default());
1302 let fake = Arc::new(Fake::default());
crates/graph/src/error.rs +2 −0
@@ -14,4 +14,6 @@ pub enum Error {
14 14 EmptyUpload,
15 15 #[error("upload failed: {0}")]
16 16 Upload(String),
17 #[error("download failed: {0}")]
18 Download(String),
17 19 }
@@ -14,4 +14,6 @@ pub enum Error {
14 EmptyUpload,
14 EmptyUpload,
15 #[error("upload failed: {0}")]
15 #[error("upload failed: {0}")]
16 Upload(String),
16 Upload(String),
17 #[error("download failed: {0}")]
18 Download(String),
17}
19}
crates/graph/src/files.rs +134 −1
@@ -1,5 +1,5 @@
1 1 use base64::Engine as _;
2 use base64::engine::general_purpose::STANDARD;
2 use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
3 3 use serde::Deserialize;
4 4 use serde_json::{Value, json};
5 5 use session::{Method, Request, Scope, Session};
@@ -7,11 +7,13 @@ use session::{Method, Request, Scope, Session};
7 7 use crate::client::Graph;
8 8 use crate::error::{Error, Result};
9 9 use crate::outgoing::FileReference;
10 use crate::people::decode_binary;
10 11 use crate::urls;
11 12
12 13 const FILES_SCOPE: &str = "Files.ReadWrite";
13 14 const CHUNK_UNIT_BYTES: u64 = 327_680;
14 15 pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;
16 pub const DOWNLOAD_CHUNK_BYTES: u64 = 4 * 1024 * 1024;
15 17 const MAX_CHUNK_RETRIES: usize = 3;
16 18 const MAX_NAME_ATTEMPTS: usize = 50;
17 19
@@ -27,6 +29,13 @@ pub enum UploadDestination {
27 29 Folder(DriveFolder),
28 30 }
29 31
32 #[derive(Debug, Clone, PartialEq, Eq)]
33 pub struct SharedFile {
34 pub name: String,
35 pub size: u64,
36 pub download_url: String,
37 }
38
30 39 #[derive(Debug, Clone, PartialEq, Eq)]
31 40 pub struct UploadedFile {
32 41 pub drive_id: String,
@@ -63,6 +72,14 @@ struct DriveItem {
63 72 parent_reference: Option<ParentReference>,
64 73 }
65 74
75 #[derive(Debug, Deserialize)]
76 struct SharedItem {
77 name: String,
78 size: Option<u64>,
79 #[serde(default, rename = "@microsoft.graph.downloadUrl")]
80 download_url: Option<String>,
81 }
82
66 83 #[derive(Debug, Deserialize)]
67 84 #[serde(rename_all = "camelCase")]
68 85 struct ParentReference {
@@ -99,6 +116,30 @@ pub fn chunk_ranges(total: u64) -> Vec<(u64, u64)> {
99 116 ranges
100 117 }
101 118
119 /// The `u!` sharing token for a file URL: base64url without padding.
120 pub fn share_id(url: &str) -> String {
121 format!("u!{}", URL_SAFE_NO_PAD.encode(url))
122 }
123
124 /// Inclusive ranges of at most `chunk` bytes that cover `total` bytes.
125 pub fn download_ranges(total: u64, chunk: u64) -> Vec<(u64, u64)> {
126 let mut ranges = Vec::new();
127 let mut start = 0;
128 while start < total {
129 let end = (start + chunk).min(total) - 1;
130 ranges.push((start, end));
131 start = end + 1;
132 }
133 ranges
134 }
135
136 fn range_header(start: u64, end: Option<u64>) -> String {
137 match end {
138 Some(end) => format!("bytes={start}-{end}"),
139 None => format!("bytes={start}-"),
140 }
141 }
142
102 143 /// First byte the server still wants, from `nextExpectedRanges` (`["1310720-"]`).
103 144 pub fn next_expected_start(body: &Value) -> Option<u64> {
104 145 let range = body
@@ -300,6 +341,54 @@ impl Graph {
300 341 next_expected_start(&answer.body)
301 342 }
302 343
344 pub async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
345 let answer = self
346 .session()
347 .request(
348 Method::Get,
349 &urls::shared_drive_item(&share_id(open_url)),
350 &Scope::graph(FILES_SCOPE),
351 None,
352 )
353 .await?;
354 let item: SharedItem = serde_json::from_value(answer.body)?;
355 let download_url = item
356 .download_url
357 .filter(|url| !url.is_empty())
358 .ok_or_else(|| Error::Download("the file has no download link".into()))?;
359 let size = item
360 .size
361 .ok_or_else(|| Error::Download("size unknown".into()))?;
362 Ok(SharedFile {
363 name: item.name,
364 size,
365 download_url,
366 })
367 }
368
369 pub async fn download_range(
370 &self,
371 download_url: &str,
372 start: u64,
373 end: Option<u64>,
374 ) -> Result<Vec<u8>> {
375 let request = Request::anonymous_binary_get(
376 download_url,
377 vec![("Range".to_owned(), range_header(start, end))],
378 );
379 let answer = self
380 .session()
381 .send(request, &Scope::graph(FILES_SCOPE))
382 .await?;
383 if start > 0 && answer.status != 206 {
384 return Err(Error::Download(format!(
385 "range ignored (HTTP {})",
386 answer.status
387 )));
388 }
389 Ok(decode_binary(download_url, answer)?.bytes)
390 }
391
303 392 pub async fn delete_drive_item(&self, drive_id: &str, item_id: &str) -> Result<()> {
304 393 self.session()
305 394 .request(
@@ -379,6 +468,50 @@ mod tests {
379 468 assert_eq!(etag_guid(""), None);
380 469 }
381 470
471 #[test]
472 fn share_id_is_base64url_without_padding() {
473 assert_eq!(share_id("a"), "u!YQ");
474 assert_eq!(share_id("ab"), "u!YWI");
475 assert_eq!(share_id("abc"), "u!YWJj");
476 assert_eq!(share_id("a?>"), "u!YT8-");
477 let id = share_id("https://contoso.sharepoint.com/:w:/r/sites/x/Doc.docx?d=w1&csf=1");
478 assert!(id.starts_with("u!") && !id.contains(['=', '+', '/']));
479 }
480
481 #[test]
482 fn download_ranges_cover_the_file_in_order() {
483 assert!(download_ranges(0, 10).is_empty());
484 assert_eq!(download_ranges(1, 10), vec![(0, 0)]);
485 assert_eq!(download_ranges(10, 10), vec![(0, 9)]);
486 assert_eq!(download_ranges(25, 10), vec![(0, 9), (10, 19), (20, 24)]);
487 let ranges = download_ranges(2 * DOWNLOAD_CHUNK_BYTES + 5, DOWNLOAD_CHUNK_BYTES);
488 assert_eq!(ranges.len(), 3);
489 assert_eq!(
490 ranges[2],
491 (2 * DOWNLOAD_CHUNK_BYTES, 2 * DOWNLOAD_CHUNK_BYTES + 4)
492 );
493 }
494
495 #[test]
496 fn range_header_is_inclusive() {
497 assert_eq!(range_header(0, Some(4_194_303)), "bytes=0-4194303");
498 assert_eq!(range_header(8_388_608, None), "bytes=8388608-");
499 }
500
501 #[test]
502 fn shared_item_reads_the_download_url() {
503 let item: SharedItem = serde_json::from_value(json!({
504 "id": "1", "name": "plan.pdf", "size": 12,
505 "@microsoft.graph.downloadUrl": "https://dl.example/x"
506 }))
507 .unwrap();
508 assert_eq!(item.download_url.as_deref(), Some("https://dl.example/x"));
509 assert_eq!(item.size, Some(12));
510 let without_size: SharedItem =
511 serde_json::from_value(json!({"id": "1", "name": "a"})).unwrap();
512 assert_eq!(without_size.size, None);
513 }
514
382 515 #[test]
383 516 fn small_files_are_one_chunk() {
384 517 assert_eq!(chunk_ranges(1), vec![(0, 0)]);
@@ -1,5 +1,5 @@
1use base64::Engine as _;
1use base64::Engine as _;
2use base64::engine::general_purpose::STANDARD;
2use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
3use serde::Deserialize;
3use serde::Deserialize;
4use serde_json::{Value, json};
4use serde_json::{Value, json};
5use session::{Method, Request, Scope, Session};
5use session::{Method, Request, Scope, Session};
@@ -7,11 +7,13 @@ use session::{Method, Request, Scope, Session};
7use crate::client::Graph;
7use crate::client::Graph;
8use crate::error::{Error, Result};
8use crate::error::{Error, Result};
9use crate::outgoing::FileReference;
9use crate::outgoing::FileReference;
10use crate::people::decode_binary;
10use crate::urls;
11use crate::urls;
11
12
12const FILES_SCOPE: &str = "Files.ReadWrite";
13const FILES_SCOPE: &str = "Files.ReadWrite";
13const CHUNK_UNIT_BYTES: u64 = 327_680;
14const CHUNK_UNIT_BYTES: u64 = 327_680;
14pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;
15pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;
16pub const DOWNLOAD_CHUNK_BYTES: u64 = 4 * 1024 * 1024;
15const MAX_CHUNK_RETRIES: usize = 3;
17const MAX_CHUNK_RETRIES: usize = 3;
16const MAX_NAME_ATTEMPTS: usize = 50;
18const MAX_NAME_ATTEMPTS: usize = 50;
17
19
@@ -27,6 +29,13 @@ pub enum UploadDestination {
27 Folder(DriveFolder),
29 Folder(DriveFolder),
28}
30}
29
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct SharedFile {
34 pub name: String,
35 pub size: u64,
36 pub download_url: String,
37}
38
30#[derive(Debug, Clone, PartialEq, Eq)]
39#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct UploadedFile {
40pub struct UploadedFile {
32 pub drive_id: String,
41 pub drive_id: String,
@@ -63,6 +72,14 @@ struct DriveItem {
63 parent_reference: Option<ParentReference>,
72 parent_reference: Option<ParentReference>,
64}
73}
65
74
75#[derive(Debug, Deserialize)]
76struct SharedItem {
77 name: String,
78 size: Option<u64>,
79 #[serde(default, rename = "@microsoft.graph.downloadUrl")]
80 download_url: Option<String>,
81}
82
66#[derive(Debug, Deserialize)]
83#[derive(Debug, Deserialize)]
67#[serde(rename_all = "camelCase")]
84#[serde(rename_all = "camelCase")]
68struct ParentReference {
85struct ParentReference {
@@ -99,6 +116,30 @@ pub fn chunk_ranges(total: u64) -> Vec<(u64, u64)> {
99 ranges
116 ranges
100}
117}
101
118
119/// The `u!` sharing token for a file URL: base64url without padding.
120pub fn share_id(url: &str) -> String {
121 format!("u!{}", URL_SAFE_NO_PAD.encode(url))
122}
123
124/// Inclusive ranges of at most `chunk` bytes that cover `total` bytes.
125pub fn download_ranges(total: u64, chunk: u64) -> Vec<(u64, u64)> {
126 let mut ranges = Vec::new();
127 let mut start = 0;
128 while start < total {
129 let end = (start + chunk).min(total) - 1;
130 ranges.push((start, end));
131 start = end + 1;
132 }
133 ranges
134}
135
136fn range_header(start: u64, end: Option<u64>) -> String {
137 match end {
138 Some(end) => format!("bytes={start}-{end}"),
139 None => format!("bytes={start}-"),
140 }
141}
142
102/// First byte the server still wants, from `nextExpectedRanges` (`["1310720-"]`).
143/// First byte the server still wants, from `nextExpectedRanges` (`["1310720-"]`).
103pub fn next_expected_start(body: &Value) -> Option<u64> {
144pub fn next_expected_start(body: &Value) -> Option<u64> {
104 let range = body
145 let range = body
@@ -300,6 +341,54 @@ impl Graph {
300 next_expected_start(&answer.body)
341 next_expected_start(&answer.body)
301 }
342 }
302
343
344 pub async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
345 let answer = self
346 .session()
347 .request(
348 Method::Get,
349 &urls::shared_drive_item(&share_id(open_url)),
350 &Scope::graph(FILES_SCOPE),
351 None,
352 )
353 .await?;
354 let item: SharedItem = serde_json::from_value(answer.body)?;
355 let download_url = item
356 .download_url
357 .filter(|url| !url.is_empty())
358 .ok_or_else(|| Error::Download("the file has no download link".into()))?;
359 let size = item
360 .size
361 .ok_or_else(|| Error::Download("size unknown".into()))?;
362 Ok(SharedFile {
363 name: item.name,
364 size,
365 download_url,
366 })
367 }
368
369 pub async fn download_range(
370 &self,
371 download_url: &str,
372 start: u64,
373 end: Option<u64>,
374 ) -> Result<Vec<u8>> {
375 let request = Request::anonymous_binary_get(
376 download_url,
377 vec![("Range".to_owned(), range_header(start, end))],
378 );
379 let answer = self
380 .session()
381 .send(request, &Scope::graph(FILES_SCOPE))
382 .await?;
383 if start > 0 && answer.status != 206 {
384 return Err(Error::Download(format!(
385 "range ignored (HTTP {})",
386 answer.status
387 )));
388 }
389 Ok(decode_binary(download_url, answer)?.bytes)
390 }
391
303 pub async fn delete_drive_item(&self, drive_id: &str, item_id: &str) -> Result<()> {
392 pub async fn delete_drive_item(&self, drive_id: &str, item_id: &str) -> Result<()> {
304 self.session()
393 self.session()
305 .request(
394 .request(
@@ -379,6 +468,50 @@ mod tests {
379 assert_eq!(etag_guid(""), None);
468 assert_eq!(etag_guid(""), None);
380 }
469 }
381
470
471 #[test]
472 fn share_id_is_base64url_without_padding() {
473 assert_eq!(share_id("a"), "u!YQ");
474 assert_eq!(share_id("ab"), "u!YWI");
475 assert_eq!(share_id("abc"), "u!YWJj");
476 assert_eq!(share_id("a?>"), "u!YT8-");
477 let id = share_id("https://contoso.sharepoint.com/:w:/r/sites/x/Doc.docx?d=w1&csf=1");
478 assert!(id.starts_with("u!") && !id.contains(['=', '+', '/']));
479 }
480
481 #[test]
482 fn download_ranges_cover_the_file_in_order() {
483 assert!(download_ranges(0, 10).is_empty());
484 assert_eq!(download_ranges(1, 10), vec![(0, 0)]);
485 assert_eq!(download_ranges(10, 10), vec![(0, 9)]);
486 assert_eq!(download_ranges(25, 10), vec![(0, 9), (10, 19), (20, 24)]);
487 let ranges = download_ranges(2 * DOWNLOAD_CHUNK_BYTES + 5, DOWNLOAD_CHUNK_BYTES);
488 assert_eq!(ranges.len(), 3);
489 assert_eq!(
490 ranges[2],
491 (2 * DOWNLOAD_CHUNK_BYTES, 2 * DOWNLOAD_CHUNK_BYTES + 4)
492 );
493 }
494
495 #[test]
496 fn range_header_is_inclusive() {
497 assert_eq!(range_header(0, Some(4_194_303)), "bytes=0-4194303");
498 assert_eq!(range_header(8_388_608, None), "bytes=8388608-");
499 }
500
501 #[test]
502 fn shared_item_reads_the_download_url() {
503 let item: SharedItem = serde_json::from_value(json!({
504 "id": "1", "name": "plan.pdf", "size": 12,
505 "@microsoft.graph.downloadUrl": "https://dl.example/x"
506 }))
507 .unwrap();
508 assert_eq!(item.download_url.as_deref(), Some("https://dl.example/x"));
509 assert_eq!(item.size, Some(12));
510 let without_size: SharedItem =
511 serde_json::from_value(json!({"id": "1", "name": "a"})).unwrap();
512 assert_eq!(without_size.size, None);
513 }
514
382 #[test]
515 #[test]
383 fn small_files_are_one_chunk() {
516 fn small_files_are_one_chunk() {
384 assert_eq!(chunk_ranges(1), vec![(0, 0)]);
517 assert_eq!(chunk_ranges(1), vec![(0, 0)]);
crates/graph/src/lib.rs +3 −2
@@ -13,8 +13,9 @@ mod writes;
13 13 pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
14 14 pub use error::{Error, Result};
15 15 pub use files::{
16 DriveFolder, UPLOAD_CHUNK_BYTES, UploadDestination, UploadedFile, chunk_range_at, chunk_ranges,
17 etag_guid, next_expected_start,
16 DOWNLOAD_CHUNK_BYTES, DriveFolder, SharedFile, UPLOAD_CHUNK_BYTES, UploadDestination,
17 UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid, next_expected_start,
18 percent_done, share_id,
18 19 };
19 20 pub use models::{
20 21 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
@@ -13,8 +13,9 @@ mod writes;
13pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
13pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
14pub use error::{Error, Result};
14pub use error::{Error, Result};
15pub use files::{
15pub use files::{
16 DriveFolder, UPLOAD_CHUNK_BYTES, UploadDestination, UploadedFile, chunk_range_at, chunk_ranges,
16 DOWNLOAD_CHUNK_BYTES, DriveFolder, SharedFile, UPLOAD_CHUNK_BYTES, UploadDestination,
17 etag_guid, next_expected_start,
17 UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid, next_expected_start,
18 percent_done, share_id,
18};
19};
19pub use models::{
20pub use models::{
20 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
21 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
crates/graph/src/urls.rs +7 −0
@@ -140,6 +140,13 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
140 140 )
141 141 }
142 142
143 pub fn shared_drive_item(share_id: &str) -> String {
144 format!(
145 "{GRAPH}/v1.0/shares/{}/driveItem?$select=id,name,size,@microsoft.graph.downloadUrl",
146 segment(share_id)
147 )
148 }
149
143 150 pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
144 151 format!(
145 152 "{GRAPH}/v1.0/drives/{}/items/{}/invite",
@@ -140,6 +140,13 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
140 )
140 )
141}
141}
142
142
143pub fn shared_drive_item(share_id: &str) -> String {
144 format!(
145 "{GRAPH}/v1.0/shares/{}/driveItem?$select=id,name,size,@microsoft.graph.downloadUrl",
146 segment(share_id)
147 )
148}
149
143pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
150pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
144 format!(
151 format!(
145 "{GRAPH}/v1.0/drives/{}/items/{}/invite",
152 "{GRAPH}/v1.0/drives/{}/items/{}/invite",
crates/session/src/request.rs +20 −0
@@ -65,6 +65,15 @@ impl Request {
65 65 }
66 66 }
67 67
68 /// Sent without an Authorization header; a successful answer carries `{"base64": .., "contentType": ..}`.
69 pub fn anonymous_binary_get(url: impl Into<String>, headers: Vec<(String, String)>) -> Self {
70 Request {
71 headers,
72 anonymous: true,
73 ..Request::binary_get(url)
74 }
75 }
76
68 77 pub fn delete(url: impl Into<String>) -> Self {
69 78 Request {
70 79 method: Method::Delete,
@@ -205,6 +214,17 @@ mod tests {
205 214 assert_eq!(wire["headers"]["Content-Range"], "bytes 0-2/3");
206 215 }
207 216
217 #[test]
218 fn anonymous_binary_get_keeps_range_header_and_flags() {
219 let request = Request::anonymous_binary_get("https://download.example/file", vec![("Range".into(), "bytes=0-9".into())]);
220 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
221 assert_eq!(wire["method"], "GET");
222 assert_eq!(wire["anonymous"], true);
223 assert_eq!(wire["binary"], true);
224 assert_eq!(wire["bodyBase64"], Value::Null);
225 assert_eq!(wire["headers"]["Range"], "bytes=0-9");
226 }
227
208 228 #[test]
209 229 fn get_has_no_body() {
210 230 let request = Request::get("u");
@@ -65,6 +65,15 @@ impl Request {
65 }
65 }
66 }
66 }
67
67
68 /// Sent without an Authorization header; a successful answer carries `{"base64": .., "contentType": ..}`.
69 pub fn anonymous_binary_get(url: impl Into<String>, headers: Vec<(String, String)>) -> Self {
70 Request {
71 headers,
72 anonymous: true,
73 ..Request::binary_get(url)
74 }
75 }
76
68 pub fn delete(url: impl Into<String>) -> Self {
77 pub fn delete(url: impl Into<String>) -> Self {
69 Request {
78 Request {
70 method: Method::Delete,
79 method: Method::Delete,
@@ -205,6 +214,17 @@ mod tests {
205 assert_eq!(wire["headers"]["Content-Range"], "bytes 0-2/3");
214 assert_eq!(wire["headers"]["Content-Range"], "bytes 0-2/3");
206 }
215 }
207
216
217 #[test]
218 fn anonymous_binary_get_keeps_range_header_and_flags() {
219 let request = Request::anonymous_binary_get("https://download.example/file", vec![("Range".into(), "bytes=0-9".into())]);
220 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
221 assert_eq!(wire["method"], "GET");
222 assert_eq!(wire["anonymous"], true);
223 assert_eq!(wire["binary"], true);
224 assert_eq!(wire["bodyBase64"], Value::Null);
225 assert_eq!(wire["headers"]["Range"], "bytes=0-9");
226 }
227
208 #[test]
228 #[test]
209 fn get_has_no_body() {
229 fn get_has_no_body() {
210 let request = Request::get("u");
230 let request = Request::get("u");