From 1367f2d6847a8ed6d481f1b10464660d0dea7f0b Mon Sep 17 00:00:00 2001 From: SadlyNotSappho Date: Tue, 29 Aug 2023 11:59:02 -0700 Subject: [PATCH] add image downloading (nightmare nightmare nightmare i hate reqwest aaaaaaaaaaaaAA) --- Cargo.toml | 2 +- src/cache.rs | 31 +++++++++++++++++++++++++++++++ src/main.rs | 4 +++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 809692c..1ffb3e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ edition = "2021" clap = { version = "4.3.3", features = ["derive"] } iced = "0.9.0" regex = "1.8.4" -reqwest = "0.11.18" +reqwest = {version="0.11.18",features=["blocking"]} scraper = "0.16.0" serde = { version = "1.0.164", features = ["derive"] } serde_json = "1.0.97" diff --git a/src/cache.rs b/src/cache.rs index e69de29..7672591 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -0,0 +1,31 @@ +use std::{fs, process}; + +pub async fn download_image(cache_path: &String, image_url: String, file_name: String) { + let replaced = cache_path.replace('~', &crate::get_home()[..]); // replace ~ with $HOME + crate::ensure_exists(&replaced); + + let image = match reqwest::get(image_url).await { + Ok(image) => match image.bytes().await { + Ok(bytes) => bytes, + Err(why) => { + eprintln!("cache::download_image: Couldn't get the bytes of the current page's image: {why:?}"); + process::exit(1); + } + }, + Err(why) => { + eprintln!("cache::download_image: Couldn't get the current image: {why:?}"); + process::exit(1); + } + }; + // println!("{image:?}"); + + // println!("{}", yansi::Color::Magenta.paint(filename.clone())); + + // println!("{}", yansi::Color::Magenta.paint(filepath.clone())); + println!("{replaced}/{file_name}"); + let wrote = fs::write(format!("{replaced}/{file_name}"), image); + if let Err(why) = wrote { + eprintln!("cache::download_image: Couldn't save the image to `{replaced}/{file_name}`: {why:?}"); + process::exit(1); + } +} diff --git a/src/main.rs b/src/main.rs index 1f8eb6f..d90aaee 100755 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ use clap::Parser; +use ggg::cache; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] @@ -20,5 +21,6 @@ async fn main() { let current_page = ggg::get_page(&config.latest_date).await; - println!("{:?}", &config); + println!("image url: {}\ncache folder: {}", ¤t_page.image, &config.cache_folder); + cache::download_image(&config.cache_folder, current_page.image, format!("{}.jpg", current_page.date)).await; }