Rename to imap-watch and handle errors

This commit is contained in:
2020-04-22 16:23:18 -06:00
parent 974e51f686
commit 09bf1d7d72
3 changed files with 41 additions and 21 deletions

2
Cargo.lock generated
View File

@@ -242,7 +242,7 @@ dependencies = [
]
[[package]]
name = "imap-run"
name = "imap-watch"
version = "0.1.0"
dependencies = [
"fondant",

View File

@@ -1,5 +1,5 @@
[package]
name = "imap-run"
name = "imap-watch"
version = "0.1.0"
authors = ["Dusan Maliarik <dusan@struna.me>"]
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"
serde = "1.0.106"

View File

@@ -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<native_tls::TlsStream<std::net::TcpStream>>;
fn connect(host: &str, user: &str, pass: &str)
-> Result<Session, imap::error::Error>
{
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<F>(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));
}
}