use std::fs::File; use std::io::prelude::*; extern crate notify_rust; extern crate toml; extern crate websocket; extern crate rustc_serialize; use notify_rust::Notification; mod message; use message::{Message, Push}; use websocket::Sender; use websocket::Receiver; use websocket::WebSocketStream; use websocket::DataFrame; use websocket::Client; struct PBClient { client: websocket::client::Client, websocket::client::receiver::Receiver> } impl PBClient { fn new(token: &str) -> PBClient { use websocket::client::request::Url; use websocket::Client; let wss_url = format!("wss://stream.pushbullet.com/websocket/{}", token); let url = Url::parse(wss_url.as_ref()).unwrap(); let request = Client::connect(url).unwrap(); let response = request.send().unwrap(); response.validate().unwrap(); PBClient { client: response.begin() } } fn process_message(message: Result) -> Option { let message = match message { Ok(m) => m, Err(e) => { println!("Error: {:?}", e); return None; } }; if let websocket::Message::Text(message) = message { Message::parse(message.as_ref()) } else { None } } fn messages<'a>(&'a mut self) -> Box + 'a> { let mut receiver = self.client.get_mut_reciever(); // there is a typo in the API Box::new(receiver.incoming_messages().filter_map(PBClient::process_message)) } } fn main() { let mut cfg_file = File::open("config.toml").expect("Could not find config.toml."); let mut s = String::new(); cfg_file.read_to_string(&mut s).expect("Could not read config.toml"); let cfg = toml::Parser::new(s.as_ref()).parse().unwrap(); let cfg_pb = cfg.get("pushbullet") .expect("Could not find [pushbullet] section in config.") .as_table() .expect("Config should contain a [pushbullet] section."); let token = cfg_pb.get("token") .expect("[pushbullet] section should contain 'token'") .as_str() .expect("'token' should be a string"); let mut client = PBClient::new(token.as_ref()); let mut receiver = client.client.get_mut_reciever(); for message in receiver.incoming_messages() { let message = match message { Ok(m) => m, Err(e) => { println!("Error: {:?}", e); return; } }; match message { websocket::Message::Close(_) => { return; } websocket::Message::Text(message) => { let msg = Message::parse(message.as_ref()); if let Some(msg) = msg { match msg { Message::Push(Push::Mirror { title, body, application_name, .. }) => { let title = format!("{}: {}", application_name, title); Notification::new() .body(body.as_ref()) .summary(title.as_ref()) .show() .unwrap(); } _ => {} } } } _ => { println!("Got {:?}", message); } } } }