diff options
author | fxqnlr <[email protected]> | 2022-11-05 21:53:24 +0100 |
---|---|---|
committer | fxqnlr <[email protected]> | 2022-11-05 21:53:24 +0100 |
commit | 0f5223d3d3f6aeb6bb1a0b09ad3d4ef5731774dd (patch) | |
tree | 6262c397c500834cf6a06059394ac51328de3aed /src/commands/download.rs | |
parent | 5d50f446a1a4612c0c931bdbc61f945760392f29 (diff) | |
download | modlist-0f5223d3d3f6aeb6bb1a0b09ad3d4ef5731774dd.tar modlist-0f5223d3d3f6aeb6bb1a0b09ad3d4ef5731774dd.tar.gz modlist-0f5223d3d3f6aeb6bb1a0b09ad3d4ef5731774dd.zip |
added setup & download; direct input
Diffstat (limited to 'src/commands/download.rs')
-rw-r--r-- | src/commands/download.rs | 46 |
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 @@ | |||
1 | use std::{io::Write, fs::File}; | ||
2 | |||
3 | use reqwest::Client; | ||
4 | |||
5 | use futures_util::StreamExt; | ||
6 | |||
7 | use crate::{get_current_list, config::Cfg, db::get_dl_links}; | ||
8 | |||
9 | pub 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 | |||
19 | async 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 | } | ||