diff --git a/src/http.rs b/src/http.rs index bec9408..63d97af 100644 --- a/src/http.rs +++ b/src/http.rs @@ -1,20 +1,35 @@ +use crate::misc; use std::{fs, io::Write, path::Path, str}; pub fn get_body(url: &str) -> Vec { let mut res: Vec = Vec::new(); - let req = http_req::request::Request::new(&url.try_into().unwrap()) + + match http_req::request::Request::new(&url.try_into().unwrap()) .header( "User-Agent", "AlterWare Launcher | github.com/mxve/alterware-launcher", ) .send(&mut res) - .unwrap_or_else(|error| { - panic!("\n\n{}:\n{:?}", "Error", error); - }); + { + Ok(req) => { + if req.status_code() == http_req::response::StatusCode::new(302) + || req.status_code() == http_req::response::StatusCode::new(301) + { + let location = req.headers().get("Location").unwrap().as_str(); + return get_body(location); + } - if req.status_code() == http_req::response::StatusCode::new(302) { - let location = req.headers().get("Location").unwrap().as_str(); - return get_body(location); + if req.status_code() != http_req::response::StatusCode::new(200) { + misc::fatal_error(&format!( + "Could not get body from {}, got {}", + url, + req.status_code() + )); + } + } + Err(e) => { + misc::fatal_error(&format!("Could not get body from {}, got:\n{}", url, e)); + } } res @@ -27,10 +42,23 @@ pub fn get_body_string(url: &str) -> String { pub fn download_file(url: &str, file_path: &Path) { let body = get_body(url); - let mut f = fs::File::create(file_path).unwrap_or_else(|error| { - panic!("\n\n{}:\n{:?}", "Error", error); - }); - f.write_all(&body).unwrap_or_else(|error| { - panic!("\n\n{}:\n{:?}", "Error", error); - }); + match fs::File::create(file_path) { + Ok(mut file) => match file.write_all(&body) { + Ok(_) => (), + Err(e) => { + misc::fatal_error(&format!( + "Could not write to file {}, got:\n{}", + file_path.to_str().unwrap(), + e + )); + } + }, + Err(e) => { + misc::fatal_error(&format!( + "Could not create file {}, got:\n{}", + file_path.to_str().unwrap(), + e + )); + } + } } diff --git a/src/misc.rs b/src/misc.rs index 78fab2c..28af4fc 100644 --- a/src/misc.rs +++ b/src/misc.rs @@ -1,5 +1,7 @@ use std::{fs, path::PathBuf}; +use colored::Colorize; + pub fn get_file_sha1(path: &PathBuf) -> String { let mut sha1 = sha1_smol::Sha1::new(); sha1.update(&fs::read(path).unwrap()); @@ -18,3 +20,9 @@ pub fn rev_to_int(rev: &str) -> u16 { .parse::() .unwrap_or(0) } + +pub fn fatal_error(error: &str) { + println!("\n\n{}:\n{}", "Error".bright_red(), error); + stdin(); + std::process::exit(1); +}