aboutsummaryrefslogtreecommitdiff
path: root/src/pushbullet/mod.rs
blob: 6eff8caee2813c8d6f9fe8223f967bf6e9e14acd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
extern crate hyper;
extern crate rustc_serialize;
extern crate websocket;

use message::Message;
pub mod user;

use std::io::Read;

use websocket::Sender;
use websocket::Receiver;
use websocket::WebSocketStream;
use websocket::DataFrame;
use websocket::Client;
use websocket::client::request::Url;

header! { (AccessToken, "Access-Token") => [String] }

pub type Result<T> = ::std::result::Result<T, Error>;

#[derive(Debug)]
pub enum Error {
    RequestError(hyper::Error),
    JsonError(rustc_serialize::json::DecoderError),
}

pub struct PBClient {
    token: String,
    client: websocket::client::Client<websocket::dataframe::DataFrame,
                                      websocket::client::sender::Sender<websocket::stream::WebSocketStream>,
                                      websocket::client::receiver::Receiver<websocket::stream::WebSocketStream>>
}

impl PBClient {
    pub fn new(token: &str) -> PBClient {

        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 {
            token: token.to_string(),
            client: response.begin()
        }
    }

    fn process_message(message: ::std::result::Result<websocket::Message, websocket::result::WebSocketError>) -> Option<Message> {
        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
        }
    }

    pub fn messages<'a>(&'a mut self) -> Box<Iterator<Item=Message> + '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))
    }

    pub fn get_user(&self) -> Result<user::User> {
        let mut client = hyper::Client::new();

        let request = client.get("https://api.pushbullet.com/v2/users/me")
            .header(AccessToken(self.token.clone()))
            .send();

        // TODO: implement From and use try!
        let mut res = match request {
            Ok(r) => r,
            Err(e) => return Err(Error::RequestError(e))
        };

        let mut body = String::new();
        res.read_to_string(&mut body).unwrap();

        match user::User::parse(body.as_ref()) {
            Ok(user) => Ok(user),
            Err(e) => Err(Error::JsonError(e))
        }
    }
}