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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
extern crate serde;
#[macro_use] extern crate serde_json;
extern crate hyper;
extern crate hyper_openssl;
#[macro_use] extern crate error_chain;
extern crate tokio_core;
#[macro_use] extern crate futures;
extern crate percent_encoding;
pub extern crate gm_types as types;
pub mod errors {
#![allow(unused_doc_comment)]
error_chain! {
types {
MatrixError, MatrixErrorKind, ResultExt, MatrixResult;
}
foreign_links {
Hyper(::hyper::error::Error);
Serde(::serde_json::Error);
UriError(::hyper::error::UriError);
Io(::std::io::Error);
Openssl(::hyper_openssl::openssl::error::ErrorStack);
}
errors {
HttpCode(c: ::hyper::StatusCode) {
display("HTTP error: {}", c.canonical_reason().unwrap_or("unknown"))
}
BadRequest(e: super::types::replies::BadRequestReply) {
display("Bad request: {:?}", e)
}
}
}
}
pub mod http {
pub use hyper::Method;
pub use hyper::Body;
pub use hyper::header::ContentType;
pub use hyper::StatusCode;
pub use hyper::Client;
pub use hyper_openssl::HttpsConnector;
pub use hyper::client::HttpConnector;
pub type MatrixHyper = Client<HttpsConnector<HttpConnector>>;
}
pub mod room;
pub mod request;
pub mod sync;
mod util;
use util::*;
use errors::*;
use types::replies::*;
use types::content::root::types::Presence;
use hyper::{Method, Body};
use Method::*;
use hyper::client::Request;
use hyper_openssl::HttpsConnector;
use hyper::header::ContentType;
use serde::de::DeserializeOwned;
use tokio_core::reactor::Handle;
use futures::*;
use request::MatrixRequest;
use sync::SyncStream;
use std::collections::HashMap;
pub type MatrixFuture<T> = Box<Future<Item=T, Error=MatrixError>>;
pub struct MatrixClient {
hyper: http::MatrixHyper,
access_token: String,
hdl: Handle,
user_id: String,
url: String,
txnid: u32
}
impl MatrixClient {
pub fn login(username: &str, password: &str, url: &str, hdl: &Handle) -> MatrixFuture<Self> {
let conn = match HttpsConnector::new(4, hdl) {
Ok(c) => c,
Err(e) => return Box::new(futures::future::err(e.into()))
};
let client = hyper::Client::configure()
.connector(conn)
.build(hdl);
let uri: hyper::Uri = match format!("{}/_matrix/client/r0/login", url).parse() {
Ok(u) => u,
Err(e) => return Box::new(futures::future::err(e.into()))
};
let mut req = Request::new(Post, uri);
req.set_body(json!({
"type": "m.login.password",
"user": username,
"password": password
}).to_string());
let resp = client.request(req).map_err(|e| e.into()).and_then(ResponseWrapper::<LoginReply>::wrap);
let hdl = hdl.clone();
let url = url.to_string();
Box::new(resp.map(move |rpl| {
MatrixClient {
hyper: client,
access_token: rpl.access_token,
user_id: rpl.user_id,
url: url,
hdl: hdl,
txnid: 0
}
}))
}
pub fn join(&mut self, roomid: &str) -> MatrixFuture<JoinReply> {
MatrixRequest::new_basic(Post, format!("/join/{}", roomid))
.send(self)
}
pub fn update_presence(&mut self, p: Presence) -> MatrixFuture<()> {
MatrixRequest::new_with_body_ser(
Put,
format!("/presence/{}/status", self.user_id),
json!({
"presence": p
})
).discarding_send(self)
}
pub fn upload<T: Into<Body>>(&mut self, data: T, ct: ContentType) -> MatrixFuture<UploadReply> {
let req = MatrixRequest {
meth: Post,
endpoint: "/upload".into(),
params: HashMap::new(),
body: (),
typ: request::apis::r0::MediaApi
}.make_hyper(self);
let mut req = match req {
Ok(r) => r,
Err(e) => return Box::new(futures::future::err(e.into()))
};
req.set_body(data.into());
req.headers_mut().set(ct);
self.send_request(req)
}
pub fn user_id(&self) -> &str {
&self.user_id
}
pub fn get_sync_stream(&self) -> SyncStream {
SyncStream {
hyper: self.hyper.clone(),
last_batch: None,
set_presence: true,
access_token: self.access_token.clone(),
url: self.url.clone(),
timeout: 30000,
cur_req: None
}
}
pub fn send_request<T>(&mut self, req: Request) -> MatrixFuture<T> where T: DeserializeOwned + 'static {
Box::new(self.hyper.request(req)
.map_err(|e| e.into())
.and_then(ResponseWrapper::<T>::wrap))
}
pub fn send_discarding_request(&mut self, req: Request) -> MatrixFuture<()> {
Box::new(self.hyper.request(req)
.map_err(|e| e.into())
.and_then(UnitaryResponseWrapper::wrap))
}
pub fn get_hyper(&mut self) -> &mut http::MatrixHyper {
&mut self.hyper
}
}
impl Drop for MatrixClient {
fn drop(&mut self) {
let fut = MatrixRequest::new_basic(Post, "/logout")
.discarding_send(self).map_err(|_| ()).map(|_| ());
self.hdl.spawn(fut);
}
}