stem_splitter_core/io/
net.rs1use crate::{error::Result, io::progress::emit_download_progress};
2use reqwest::blocking::Client;
3use std::{
4 fs,
5 fs::File,
6 io::{Read, Write},
7 path::Path,
8 time::Duration,
9};
10
11pub fn http_client() -> Client {
12 Client::builder()
13 .connect_timeout(Duration::from_secs(10))
14 .timeout(Duration::from_secs(60 * 60))
15 .build()
16 .expect("reqwest client build failed")
17}
18
19pub fn download_with_progress(client: &Client, url: &str, dest: &Path) -> Result<()> {
20 let tmp = dest.with_extension("part");
21
22 let mut resp = client.get(url).send()?.error_for_status()?; let total = resp.content_length().unwrap_or(0);
25
26 emit_download_progress(0, total);
27
28 let mut file = File::create(&tmp)?;
29 let mut downloaded: u64 = 0;
30 let mut buf = [0u8; 64 * 1024];
31 loop {
32 let n = resp.read(&mut buf)?;
33 if n == 0 {
34 break;
35 }
36 file.write_all(&buf[..n])?;
37 downloaded += n as u64;
38 emit_download_progress(downloaded, total);
39 }
40 file.flush()?;
41
42 if dest.exists() {
43 fs::remove_file(dest).ok();
44 }
45
46 fs::rename(&tmp, dest)?;
47
48 emit_download_progress(total.max(downloaded), total.max(downloaded));
49
50 Ok(())
51}