diff --git a/Cargo.lock b/Cargo.lock index 15f2231..423d5e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -242,7 +242,7 @@ dependencies = [ ] [[package]] -name = "imap-run" +name = "imap-watch" version = "0.1.0" dependencies = [ "fondant", diff --git a/Cargo.toml b/Cargo.toml index 9ab4cea..fefd7e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "imap-run" +name = "imap-watch" version = "0.1.0" authors = ["Dusan Maliarik "] edition = "2018" @@ -8,4 +8,4 @@ edition = "2018" imap = "2.0.1" native-tls = "0.2.4" fondant = "0.1.0" -serde = "1.0.106" \ No newline at end of file +serde = "1.0.106" diff --git a/src/main.rs b/src/main.rs index 7a0d766..05c40c6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ extern crate native_tls; extern crate serde; extern crate fondant; +use std::{thread, time}; use fondant::Configure; use serde::{Serialize, Deserialize}; @@ -21,14 +22,15 @@ type Session = imap::Session>; fn connect(host: &str, user: &str, pass: &str) -> Result { - let tls = native_tls::TlsConnector::builder().build().unwrap(); - let client = imap::connect((host, 993), host, &tls).unwrap(); + let tls = native_tls::TlsConnector::builder().build()?; + let client = imap::connect((host, 993), host, &tls)?; let mut imap_session = client .login(user, pass) .map_err(|e| e.0)?; imap_session.select("INBOX")?; + println!("connected to {}", host); Ok(imap_session) } @@ -38,9 +40,32 @@ fn get_pass(eval: &str) -> String { .args(&["-c", eval]) .output().unwrap().stdout.as_ref() ).unwrap()).split("\n").next().unwrap().to_string() - } +fn loop_session(user: &str, pass: &str, host: &str, hook: F) +where F: Fn() -> () +{ + match connect(host, user, pass) { + Ok(mut sess) => { + loop { + match sess.idle() { + Ok(idle) => { + match idle.wait_keepalive() { + Ok(()) => { + hook(); + }, + _ => { + eprintln!("failed-idle-wait"); + break; + }}}, + _ => { + eprintln!("failed-idle"); + break; + }}}}, + _ => { + eprintln!("connect-failed"); + }}} + fn main() { let conf = Config::load().unwrap(); let pass = match (conf.pass.len(), conf.pass_eval.len()) { @@ -52,21 +77,16 @@ fn main() { (_p, 0) => conf.pass, (_p, _e) => get_pass(&conf.pass_eval), }; - let mut sess = connect(&conf.host, &conf.user, &pass).unwrap(); - println!("connected to {}", &conf.host); + let hook = &conf.hook; loop { - match sess.idle().unwrap().wait_keepalive() { - Ok(()) => { - println!("got message!"); - std::process::Command::new("sh") - .args(&["-c", &conf.hook]) - .status() - .expect("failed to execute process"); - }, - _ => { - eprintln!("Failed to wait on PUSH"); - break; - } - } + loop_session(&conf.user, &pass, &conf.host, || { + std::process::Command::new("sh") + .args(&["-c", hook]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .expect("failed-to-execute-process"); + }); + thread::sleep(time::Duration::from_millis(1000)); } }