instapi360_cloud/
download.rs1use futures::StreamExt;
8use tokio::io::{AsyncWrite, AsyncWriteExt};
9
10use crate::client::Client;
11use crate::error::{Error, Result};
12use crate::model::FilePart;
13
14pub trait ProgressSink: FnMut(u64, Option<u64>) {}
16impl<T: FnMut(u64, Option<u64>)> ProgressSink for T {}
17
18impl Client {
19 pub async fn download_part<W, P>(
28 &self,
29 part: &FilePart,
30 mut sink: W,
31 from: u64,
32 mut progress: P,
33 ) -> Result<()>
34 where
35 W: AsyncWrite + Unpin,
36 P: ProgressSink,
37 {
38 let mut req = self.http().get(&part.url);
39 if from > 0 {
40 req = req.header(reqwest::header::RANGE, format!("bytes={from}-"));
41 }
42 let resp = req.send().await?;
43 let status = resp.status();
44 if status == reqwest::StatusCode::FORBIDDEN {
45 return Err(Error::Auth(
46 "OSS url expired (403) — re-resolve download".into(),
47 ));
48 }
49 let resp = resp.error_for_status()?;
50
51 let content_len = resp.content_length();
53 let total = if part.size > 0 {
54 Some(part.size)
55 } else {
56 content_len.map(|c| c + from)
57 };
58
59 let mut done = from;
60 progress(done, total);
61
62 let mut stream = resp.bytes_stream();
63 while let Some(chunk) = stream.next().await {
64 let chunk = chunk?;
65 sink.write_all(&chunk).await?;
66 done += chunk.len() as u64;
67 progress(done, total);
68 }
69 sink.flush().await?;
70
71 if let Some(t) = total {
72 if done < t {
73 return Err(Error::Partial {
74 got: done,
75 expected: t,
76 });
77 }
78 }
79 Ok(())
80 }
81}