BlueGit

ict rusty-teams

Files

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

download.rs

download.rs 2.7 KiB Download Raw
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
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct LibraryFile {
9 pub drive_id: String,
10 pub item_id: String,
11 pub name: String,
12 pub size: u64,
13 pub cached_url: Option<String>,
14}
15
16impl<R: Remote> SyncEngine<R> {
17 /// Streams the file behind a OneDrive or SharePoint link chunk by chunk into `write`.
18 pub async fn download_file(
19 &self,
20 open_url: &str,
21 mut write: impl FnMut(&[u8]) -> std::io::Result<()> + Send,
22 progress: impl Fn(u8) + Send + Sync,
23 ) -> Result<SharedFile> {
24 let shared = self.remote.resolve_share(open_url).await?;
25 self.stream_file(shared, &mut write, &progress).await
26 }
27
28 /// Like `download_file` for a library entry. A `cached_url` from the listing skips the lookup.
29 pub async fn download_library_file(
30 &self,
31 file: &LibraryFile,
32 mut write: impl FnMut(&[u8]) -> std::io::Result<()> + Send,
33 progress: impl Fn(u8) + Send + Sync,
34 ) -> Result<SharedFile> {
35 let shared = match &file.cached_url {
36 Some(download_url) => SharedFile {
37 name: file.name.clone(),
38 size: file.size,
39 download_url: download_url.clone(),
40 },
41 None => {
42 self.remote
43 .resolve_drive_item(&file.drive_id, &file.item_id)
44 .await?
45 }
46 };
47 self.stream_file(shared, &mut write, &progress).await
48 }
49
50 async fn stream_file(
51 &self,
52 shared: SharedFile,
53 write: &mut (impl FnMut(&[u8]) -> std::io::Result<()> + Send),
54 progress: &(impl Fn(u8) + Send + Sync),
55 ) -> Result<SharedFile> {
56 progress(0);
57 let ranges = download_ranges(shared.size, DOWNLOAD_CHUNK_BYTES);
58 let last = ranges.len().saturating_sub(1);
59 for (position, (start, end)) in ranges.into_iter().enumerate() {
60 let is_last = position == last;
61 let bytes = self
62 .remote
63 .download_range(&shared.download_url, start, (!is_last).then_some(end))
64 .await?;
65 let expected = end - start + 1;
66 let received = bytes.len() as u64;
67 if received < expected || (!is_last && received != expected) {
68 return Err(GraphError::Download(format!(
69 "expected {expected} bytes, got {received}"
70 ))
71 .into());
72 }
73 write(&bytes)?;
74 progress(percent_done(start + received, shared.size));
75 }
76 progress(100);
77 Ok(shared)
78 }
79}