1 | |
#[macro_use] extern crate failure;
|
| 1 |
extern crate failure;
|
| 2 |
#[macro_use] extern crate failure_derive;
|
2 | 3 |
#[macro_use] extern crate serde_derive;
|
3 | 4 |
|
4 | 5 |
use reqwest as req;
|
| 6 |
|
| 7 |
pub mod mm {
|
| 8 |
#[derive(Fail, Debug)]
|
| 9 |
pub enum Error {
|
| 10 |
#[fail(display = "HTTP error: {}", err)]
|
| 11 |
HTTPError { err: reqwest::Error },
|
| 12 |
|
| 13 |
#[fail(display = "Error reading header: {}", err)]
|
| 14 |
EncodingError { err: http::header::ToStrError },
|
| 15 |
|
| 16 |
#[fail(display = "Missing header in response: {}", name)]
|
| 17 |
HeaderMissingError { name: String },
|
| 18 |
}
|
| 19 |
|
| 20 |
impl From<reqwest::Error> for Error {
|
| 21 |
fn from(err: reqwest::Error) -> Error {
|
| 22 |
Error::HTTPError { err }
|
| 23 |
}
|
| 24 |
}
|
| 25 |
|
| 26 |
impl From<http::header::ToStrError> for Error {
|
| 27 |
fn from(err: http::header::ToStrError) -> Error {
|
| 28 |
Error::EncodingError { err }
|
| 29 |
}
|
| 30 |
}
|
| 31 |
|
| 32 |
pub type Result<T> = core::result::Result<T, Error>;
|
| 33 |
}
|
5 | 34 |
|
6 | 35 |
#[derive(Serialize, Deserialize)]
|
7 | 36 |
struct Login {
|
|
52 | 81 |
}
|
53 | 82 |
|
54 | 83 |
impl Session {
|
55 | |
fn login(login: &Login, server: &str) -> Result<Session, failure::Error> {
|
| 84 |
fn login(login: &Login, server: &str) -> mm::Result<Session> {
|
56 | 85 |
let uri = format!("{}/api/v4", server);
|
57 | 86 |
let client = req::Client::new();
|
58 | 87 |
let mut res = client.post(&format!("{}/users/login", uri))
|
59 | 88 |
.json(login)
|
60 | 89 |
.send()?;
|
61 | 90 |
let token_val = res.headers().get("token")
|
62 | |
.ok_or(format_err!("No token present in response"))?;
|
| 91 |
.ok_or(mm::Error::HeaderMissingError { name: "token".to_string() })?;
|
63 | 92 |
let token = format!("Bearer {}", token_val.to_str()?);
|
64 | 93 |
let user = res.json()?;
|
65 | 94 |
Ok(Session {
|
|
70 | 99 |
})
|
71 | 100 |
}
|
72 | 101 |
|
73 | |
fn get<T: for<'t> serde::Deserialize<'t>>(&self, path: String) -> Result<T, failure::Error> {
|
| 102 |
fn get<T: for<'t> serde::Deserialize<'t>>(&self, path: String) -> mm::Result<T> {
|
74 | 103 |
Ok(self.client.get(&format!("{}/{}", self.uri, path))
|
75 | 104 |
.header("Content-Type", "application/json")
|
76 | 105 |
.header("Authorization", self.token.clone())
|
|
82 | 111 |
&self.user
|
83 | 112 |
}
|
84 | 113 |
|
85 | |
fn get_teams(&self) -> Result<Vec<Team>, failure::Error> {
|
| 114 |
fn get_teams(&self) -> mm::Result<Vec<Team>> {
|
86 | 115 |
self.get(format!("users/{}/teams", self.user.id))
|
87 | 116 |
}
|
88 | 117 |
|
89 | |
fn get_channels_for_user(&self, user_id: &str, team_id: &str) -> Result<Vec<Channel>, failure::Error> {
|
| 118 |
fn get_channels_for_user(&self, user_id: &str, team_id: &str) -> mm::Result<Vec<Channel>> {
|
90 | 119 |
self.get(format!("users/{}/teams/{}/channels", user_id, team_id))
|
91 | 120 |
}
|
92 | 121 |
}
|