summaryrefslogtreecommitdiff
path: root/src/commands/download.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/commands/download.rs')
-rw-r--r--src/commands/download.rs46
1 files changed, 46 insertions, 0 deletions
diff --git a/src/commands/download.rs b/src/commands/download.rs
new file mode 100644
index 0000000..05c54cb
--- /dev/null
+++ b/src/commands/download.rs
@@ -0,0 +1,46 @@
1use std::{io::Write, fs::File};
2
3use reqwest::Client;
4
5use futures_util::StreamExt;
6
7use crate::{get_current_list, config::Cfg, db::get_dl_links};
8
9pub async fn download(config: Cfg) -> Result<(), Box<dyn std::error::Error>> {
10 let list = get_current_list(config.clone())?;
11
12 let links = get_dl_links(config.clone(), list)?;
13
14 download_links(config, links).await?;
15
16 Ok(())
17}
18
19async fn download_links(config: Cfg, links: Vec<String>) -> Result<String, Box<dyn std::error::Error>> {
20
21 let dl_path = String::from(&config.downloads);
22
23 for link in links {
24 let filename = link.split('/').last().unwrap();
25 let dl_path_file = format!("{}/{}", config.downloads, filename);
26 println!("Downloading {}", link);
27
28 let res = Client::new()
29 .get(String::from(&link))
30 .send()
31 .await
32 .or(Err(format!("Failed to GET from '{}'", &link)))?;
33
34 // download chunks
35 let mut file = File::create(String::from(&dl_path_file)).or(Err(format!("Failed to create file '{}'", dl_path_file)))?;
36 let mut stream = res.bytes_stream();
37
38 while let Some(item) = stream.next().await {
39 let chunk = item.or(Err("Error while downloading file"))?;
40 file.write_all(&chunk)
41 .or(Err("Error while writing to file"))?;
42 }
43 }
44
45 Ok(dl_path)
46}