From: Grégory Burri Date: Wed, 9 Sep 2020 09:52:56 +0000 (+0200) Subject: Implement some functions for 'Config'. X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=ff529242d51b42e72232ec0873d805e891f35760;p=rtx3080.git Implement some functions for 'Config'. --- diff --git a/src/main.rs b/src/main.rs index aeafb57..057d68b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,35 +14,45 @@ use lettre::{ } }; use lettre_email::Email; -use native_tls::{Protocol, TlsConnector}; +use native_tls::{ Protocol, TlsConnector }; use ron::{ de::from_reader, ser::to_writer }; use serde::{ Deserialize, Serialize }; +type Result = std::result::Result>; + #[derive(Debug, Deserialize, Serialize)] struct Config { smtp_login: String, smtp_password: String } -fn get_default_config() -> Config { Config { smtp_login: "login".to_string(), smtp_password: "password".to_string() } } +impl Config { + fn default() -> Self { + Config { smtp_login: "login".to_string(), smtp_password: "password".to_string() } + } + + fn read(file_path: &str) -> Result { + match File::open(file_path) { + Ok(file) => from_reader(file).map_err(|e| e.into()), + Err(_) => { + let file = File::create(file_path)?; + let default_config = Config::default(); + to_writer(file, &default_config)?; + Ok(default_config) + } + } + } +} + const FILE_CONF: &str = "config.ron"; -fn main() -> Result<(), Box> { +fn main() -> Result<()> { println!("I need a RTX 3080 right now :)"); let to_find = "RTX 3080"; let to_match = "3080"; - let config: Config = - match File::open(FILE_CONF) { - Ok(file) => match from_reader(file) { Ok(c) => c, Err(e) => panic!("Failed to load config: {}", e)}, - Err(_) => { - let file = File::create(FILE_CONF)?; - let default_config = get_default_config(); - to_writer(file, &default_config)?; - default_config - } - }; + let config = Config::read(FILE_CONF)?; let selector = Selector::parse("div.productGridElement > h2 > a:nth-child(1)").unwrap(); let url = format!("https://www.steg-electronics.ch/fr/search?suche={}", to_find); @@ -72,7 +82,7 @@ fn main() -> Result<(), Box> { ).collect(); if match_items.is_empty() { - println!("No matches..."); + println!("No matches -_-´´"); } else if send_email(&match_items[..], &config.smtp_login, &config.smtp_password) { println!("Some matches has been found! An e-mail has been sent!"); return Ok(())