From ff529242d51b42e72232ec0873d805e891f35760 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Gr=C3=A9gory=20Burri?= Date: Wed, 9 Sep 2020 11:52:56 +0200 Subject: [PATCH] Implement some functions for 'Config'. --- src/main.rs | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) 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(()) -- 2.45.2