http.rs
1 use log; 2 3 use std::{ 4 fs::File, 5 io::Write, 6 path::PathBuf 7 }; 8 9 10 #[allow(dead_code)] 11 #[derive(Clone, Default)] 12 pub struct ViaHTTP { 13 pub title: String, 14 pub url: String, 15 pub format: String, 16 pub needs_ocr: bool, 17 pub start_page: Option<i64>, 18 pub end_page: Option<i64> 19 } 20 21 22 impl ViaHTTP { 23 24 pub fn get_file_name(&self) -> String { 25 self.title.replace(" ", "_").to_string() + &self.format 26 } 27 28 pub fn has_skippable_pages(&self) -> bool{ 29 self.start_page.is_some() && self.end_page.is_some() 30 } 31 32 pub fn page_is_skippable(&self, page: usize) -> bool { 33 let end_page = self.end_page.unwrap() as usize; 34 let start_page = self.start_page.unwrap() as usize; 35 (page <= start_page) && (page >= end_page) 36 } 37 38 pub async fn download(&self, download_path: &PathBuf) { 39 if !download_path.exists() { 40 log::info!("Downloading {}", self.title); 41 let response: Result<reqwest::Response, reqwest::Error> = reqwest::get(&self.url).await; 42 43 match response.as_ref().unwrap().status() { 44 reqwest::StatusCode::OK => { 45 let bytes = response.unwrap().bytes(); 46 let file: Result<File, std::io::Error> = File::create(download_path); 47 _ = file.unwrap().write_all(&bytes.await.unwrap()); 48 } 49 _ => log::error!("Unable to download {}", self.title) 50 }; 51 } else { 52 log::info!("{} is already present", &self.title) 53 } 54 } 55 } 56