From 0f5223d3d3f6aeb6bb1a0b09ad3d4ef5731774dd Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Sat, 5 Nov 2022 21:53:24 +0100 Subject: added setup & download; direct input --- src/commands/download.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/commands/download.rs (limited to 'src/commands/download.rs') 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 @@ +use std::{io::Write, fs::File}; + +use reqwest::Client; + +use futures_util::StreamExt; + +use crate::{get_current_list, config::Cfg, db::get_dl_links}; + +pub async fn download(config: Cfg) -> Result<(), Box> { + let list = get_current_list(config.clone())?; + + let links = get_dl_links(config.clone(), list)?; + + download_links(config, links).await?; + + Ok(()) +} + +async fn download_links(config: Cfg, links: Vec) -> Result> { + + let dl_path = String::from(&config.downloads); + + for link in links { + let filename = link.split('/').last().unwrap(); + let dl_path_file = format!("{}/{}", config.downloads, filename); + println!("Downloading {}", link); + + let res = Client::new() + .get(String::from(&link)) + .send() + .await + .or(Err(format!("Failed to GET from '{}'", &link)))?; + + // download chunks + let mut file = File::create(String::from(&dl_path_file)).or(Err(format!("Failed to create file '{}'", dl_path_file)))?; + let mut stream = res.bytes_stream(); + + while let Some(item) = stream.next().await { + let chunk = item.or(Err("Error while downloading file"))?; + file.write_all(&chunk) + .or(Err("Error while writing to file"))?; + } + } + + Ok(dl_path) +} -- cgit v1.2.3