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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
extern crate serde;
#[macro_use] extern crate serde_derive;
#[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;
pub mod errors {
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::BadRequestReply) {
display("Bad request: {:?}", e)
}
}
}
}
pub mod http {
pub use hyper::Method;
pub use hyper::Body;
pub use hyper::header::ContentType;
}
pub mod types;
use errors::*;
use errors::MatrixErrorKind::*;
use types::*;
use hyper::{Method, Body, StatusCode};
use Method::*;
use hyper::client::{Response, HttpConnector, Request};
use hyper_openssl::HttpsConnector;
use hyper::header::ContentType;
use serde::Deserialize;
use tokio_core::reactor::Handle;
use futures::*;
use std::marker::PhantomData;
use futures::stream::Concat2;
pub type MatrixFuture<T> = Box<Future<Item=T, Error=MatrixError>>;
struct ResponseWrapper<T> {
inner: Concat2<Body>,
sc: StatusCode,
_ph: PhantomData<T>,
}
struct UnitaryResponseWrapper {
inner: ResponseWrapper<()>
}
impl<T: Deserialize> ResponseWrapper<T> {
fn wrap(r: Response) -> Self {
let sc = r.status();
let inner = r.body().concat2();
let _ph = PhantomData;
Self { sc, inner, _ph, }
}
fn _poll(&mut self) -> Poll<hyper::Chunk, MatrixError> {
let resp = try_ready!(self.inner.poll());
if !self.sc.is_success() {
if let Ok(e) = serde_json::from_slice::<BadRequestReply>(&resp) {
bail!(BadRequest(e));
}
else {
bail!(HttpCode(self.sc.clone()));
}
}
Ok(Async::Ready(resp))
}
}
impl UnitaryResponseWrapper {
fn wrap(r: Response) -> Self {
Self {
inner: ResponseWrapper::<()>::wrap(r)
}
}
}
impl<T: Deserialize> Future for ResponseWrapper<T> {
type Item = T;
type Error = MatrixError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let resp = try_ready!(self._poll());
let data = serde_json::from_slice::<T>(&resp)?;
Ok(Async::Ready(data))
}
}
impl Future for UnitaryResponseWrapper {
type Item = ();
type Error = MatrixError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
try_ready!(self.inner._poll());
Ok(Async::Ready(()))
}
}
pub struct SyncStream {
hyper: hyper::Client<HttpsConnector<HttpConnector>>,
last_batch: Option<String>,
set_presence: bool,
access_token: String,
url: String,
timeout: u64,
cur_req: Option<MatrixFuture<SyncReply>>
}
impl SyncStream {
pub fn set_sync_sets_presence(&mut self, v: bool) {
self.set_presence = v;
}
pub fn sync_sets_presence(&self) -> bool {
self.set_presence
}
pub fn timeout(&self) -> u64 {
self.timeout
}
pub fn set_timeout(&mut self, timeout: u64) {
self.timeout = timeout;
}
fn req(&mut self) -> Request {
let mut params = vec![];
params.push(format!("set_presence={}", if self.set_presence {
"online"
} else { "offline" }));
if let Some(ref b) = self.last_batch {
params.push(format!("since={}", b));
params.push(format!("timeout={}", self.timeout));
}
Request::new(Get, format!("{}/_matrix/client/r0/sync?access_token={}&{}",
self.url,
&self.access_token,
params.join("&")
).parse().unwrap())
}
}
impl Stream for SyncStream {
type Item = SyncReply;
type Error = MatrixError;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
loop {
if self.cur_req.is_some() {
match self.cur_req.as_mut().unwrap().poll() {
Ok(Async::Ready(rpl)) => {
self.last_batch = Some(rpl.next_batch.clone());
self.cur_req = None;
return Ok(Async::Ready(Some(rpl)));
},
Ok(Async::NotReady) => {
return Ok(Async::NotReady);
},
Err(e) => {
return Err(e);
}
}
}
let req = self.req();
self.cur_req = Some(Box::new(self.hyper.request(req)
.map_err(|e| e.into())
.and_then(ResponseWrapper::<SyncReply>::wrap)))
}
}
}
pub struct MatrixClient {
hyper: hyper::Client<HttpsConnector<HttpConnector>>,
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> {
self.req(Post, &format!("/join/{}", roomid), vec![], None)
}
pub fn update_presence(&mut self, p: Presence) -> MatrixFuture<()> {
let uri = format!("/presence/{}/status", self.user_id);
let pres = match serde_json::to_string(&p) {
Ok(x) => x,
Err(e) => return Box::new(futures::future::err(e.into()))
};
self.discarding_req(Put, &uri, vec![], Some(pres.into()))
}
pub fn read_receipt(&mut self, roomid: &str, eventid: &str) -> MatrixFuture<()> {
let uri = format!("/rooms/{}/receipt/m.read/{}", roomid, eventid);
self.discarding_req(Post, &uri, vec![], None)
}
pub fn send(&mut self, roomid: &str, msg: Message) -> MatrixFuture<SendReply> {
let body = match serde_json::to_string(&msg) {
Ok(x) => x,
Err(e) => return Box::new(futures::future::err(e.into()))
};
let uri = format!("/rooms/{}/send/m.room.message/{}",
roomid,
self.txnid);
self.txnid += 1;
self.req(Put, &uri, vec![], Some(body.into()))
}
pub fn send_simple<T: Into<String>>(&mut self, roomid: &str, msg: T) -> MatrixFuture<SendReply> {
let msg = Message::Notice { body: msg.into(), formatted_body: None, format: None };
self.send(roomid, msg)
}
pub fn send_html<T: Into<String>, U: Into<Option<String>>>(&mut self, roomid: &str, msg: T, unformatted: U) -> MatrixFuture<SendReply> {
let m = msg.into();
let msg = Message::Notice { body: unformatted.into().unwrap_or(m.clone()), formatted_body: Some(m), format: Some("org.matrix.custom.html".into()) };
self.send(roomid, msg)
}
pub fn upload<T: Into<Body>>(&mut self, data: T, ct: ContentType) -> MatrixFuture<UploadReply> {
let req = self.get_request_for(Post, &format!("{}/_matrix/media/r0/upload?access_token={}",
self.url, self.access_token), vec![], Some(data.into()));
let mut req = match req {
Ok(r) => r,
Err(e) => return Box::new(futures::future::err(e.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 req<T>(&mut self, meth: Method, endpoint: &str, params: Vec<String>, body: Option<Body>) -> MatrixFuture<T> where T: Deserialize + 'static {
let req = match self.get_request_for(meth, endpoint, params, body) {
Ok(r) => r,
Err(e) => return Box::new(futures::future::err(e.into()))
};
self.send_request(req)
}
pub fn discarding_req(&mut self, meth: Method, endpoint: &str, params: Vec<String>, body: Option<Body>) -> MatrixFuture<()> {
let req = match self.get_request_for(meth, endpoint, params, body) {
Ok(r) => r,
Err(e) => return Box::new(futures::future::err(e.into()))
};
self.send_discarding_request(req)
}
pub fn get_request_for(&self, meth: Method, endpoint: &str, params: Vec<String>, body: Option<Body>) -> MatrixResult<Request> {
let mut req = Request::new(meth, format!("{}/_matrix/client/r0{}?access_token={}{}{}",
self.url,
endpoint,
&self.access_token,
if params.len() == 0 { "" } else { "&" },
params.join("&")
).parse()?);
if let Some(b) = body {
req.set_body(b);
}
Ok(req)
}
pub fn send_request<T>(&mut self, req: Request) -> MatrixFuture<T> where T: Deserialize + '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))
}
}
impl Drop for MatrixClient {
fn drop(&mut self) {
let fut = self.req::<()>(Post, "/logout", vec![], None).map_err(|_| ()).map(|_| ());
self.hdl.spawn(fut);
}
}