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
extern crate serde;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate serde_json;
extern crate hyper;
extern crate hyper_native_tls;
#[macro_use] extern crate error_chain;
pub mod errors {
error_chain! {
types {
MatrixError, MatrixErrorKind, ResultExt, MatrixResult;
}
foreign_links {
Hyper(::hyper::error::Error);
Serde(::serde_json::Error);
Io(::std::io::Error);
Ssl(::hyper_native_tls::native_tls::Error);
}
errors {
HttpCode(c: ::hyper::status::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::Method;
pub use hyper::header::ContentType;
}
pub mod types;
use errors::*;
use errors::MatrixErrorKind::*;
use types::*;
use hyper::method::Method;
use Method::*;
use hyper::client::{Response, RequestBuilder};
use hyper::header::ContentType;
use hyper::net::HttpsConnector;
use std::io::Read;
use hyper_native_tls::NativeTlsClient;
pub struct MatrixClient {
hyper: hyper::Client,
access_token: String,
user_id: String,
url: String,
last_batch: Option<String>,
set_presence: bool,
txnid: u32
}
impl MatrixClient {
pub fn login(username: &str, password: &str, url: &str) -> MatrixResult<Self> {
let ssl = NativeTlsClient::new()?;
let conn = HttpsConnector::new(ssl);
let client = hyper::Client::with_connector(conn);
let mut resp = client.post(&format!("{}/_matrix/client/r0/login", url))
.body(&json!({
"type": "m.login.password",
"user": username,
"password": password
}).to_string())
.send()?;
Self::handle_errs(&mut resp)?;
let rpl = serde_json::from_reader::<_, LoginReply>(resp)?;
Ok(MatrixClient {
hyper: client,
access_token: rpl.access_token,
user_id: rpl.user_id,
url: url.to_string(),
last_batch: None,
set_presence: true,
txnid: 0
})
}
fn handle_errs(resp: &mut Response) -> MatrixResult<()> {
if !resp.status.is_success() {
let st = resp.status.clone();
if let Ok(e) = serde_json::from_reader::<_, BadRequestReply>(resp) {
bail!(BadRequest(e));
}
else {
bail!(HttpCode(st));
}
}
Ok(())
}
pub fn join(&mut self, roomid: &str) -> MatrixResult<JoinReply> {
let mut resp = self.req(Post, &format!("/join/{}", roomid), vec![])
.send()?;
Self::handle_errs(&mut resp)?;
let rpl = serde_json::from_reader(resp)?;
Ok(rpl)
}
pub fn update_presence(&mut self, p: Presence) -> MatrixResult<()> {
let uri = format!("/presence/{}/status", self.user_id);
let mut resp = self.req(Put, &uri, vec![])
.body(&serde_json::to_string(&p)?)
.send()?;
Self::handle_errs(&mut resp)?;
Ok(())
}
pub fn read_receipt(&mut self, roomid: &str, eventid: &str) -> MatrixResult<()> {
let uri = format!("/rooms/{}/receipt/m.read/{}", roomid, eventid);
let mut resp = self.req(Post, &uri, vec![])
.send()?;
Self::handle_errs(&mut resp)?;
Ok(())
}
pub fn send(&mut self, roomid: &str, msg: Message) -> MatrixResult<SendReply> {
let body = serde_json::to_value(&msg)?;
let uri = format!("/rooms/{}/send/m.room.message/{}",
roomid,
self.txnid);
self.txnid += 1;
let mut resp = self.req(Put, &uri, vec![])
.body(&body.to_string())
.send()?;
Self::handle_errs(&mut resp)?;
let rpl = serde_json::from_reader(resp)?;
Ok(rpl)
}
pub fn send_simple<T: Into<String>>(&mut self, roomid: &str, msg: T) -> MatrixResult<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) -> MatrixResult<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: Read>(&mut self, data: &mut T, ct: ContentType) -> MatrixResult<UploadReply> {
let req = self.hyper.request(Post, &format!("{}/_matrix/media/r0/upload?access_token={}",
self.url, self.access_token))
.header(ct)
.body(data);
let mut resp = req.send()?;
Self::handle_errs(&mut resp)?;
let rpl = serde_json::from_reader(resp)?;
Ok(rpl)
}
pub fn user_id(&self) -> &str {
&self.user_id
}
pub fn set_set_presence(&mut self, v: bool) {
self.set_presence = v;
}
pub fn set_presence(&self) -> bool {
self.set_presence
}
pub fn sync(&mut self, timeout: u64) -> MatrixResult<SyncReply> {
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={}", timeout));
}
let mut resp = self.req(Get, "/sync", params).send()?;
Self::handle_errs(&mut resp)?;
let rpl = serde_json::from_reader::<_, SyncReply>(resp)?;
self.last_batch = Some(rpl.next_batch.clone());
Ok(rpl)
}
pub fn req(&mut self, meth: Method, endpoint: &str, params: Vec<String>) -> RequestBuilder {
self.hyper.request(meth,
&format!("{}/_matrix/client/r0{}?access_token={}{}{}",
self.url,
endpoint,
&self.access_token,
if params.len() == 0 { "" } else { "&" },
params.join("&")
))
}
}
impl Drop for MatrixClient {
fn drop(&mut self) {
let _ = self.update_presence(Presence::Offline);
let _ = self.req(Post, "/logout", vec![]).send();
}
}