-
Notifications
You must be signed in to change notification settings - Fork 5
/
r0.rs
264 lines (229 loc) · 11.4 KB
/
r0.rs
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
use std::collections::HashMap;
use pulldown_cmark::{Options, Parser, html};
use reqwest::StatusCode;
use ruma_client_api::Endpoint;
use ruma_client_api::r0::account::register::{self, Endpoint as RegisterEndpoint};
use ruma_client_api::r0::membership::forget_room::{self, Endpoint as ForgetRoomEndpoint};
use ruma_client_api::r0::membership::invite_user::{self, Endpoint as InviteUserEndpoint};
use ruma_client_api::r0::membership::join_room_by_id::{self, Endpoint as JoinRoomByIdEndpoint};
use ruma_client_api::r0::membership::leave_room::{self, Endpoint as LeaveRoomEndpoint};
use ruma_client_api::r0::room::create_room::{self, Endpoint as CreateRoomEndpoint, RoomPreset};
use ruma_client_api::r0::send::send_message_event::{self, Endpoint as SendMessageEventEndpoint};
use ruma_client_api::r0::send::send_state_event_for_empty_key::{self, Endpoint as SendStateEventForEmptyKeyEndpoint};
use ruma_client_api::r0::sync::get_member_events::{self, Endpoint as GetMemberEventsEndpoint};
use ruma_events::EventType;
use ruma_events::room::member::MemberEvent;
use ruma_events::room::message::MessageType;
use ruma_identifiers::{EventId, RoomId, UserId};
use serde_json::Map;
use slog::Logger;
use serde_json;
use api::RestApi;
use config::Config;
use errors::*;
#[derive(Clone)]
/// Rocket.Chat REST API v0
pub struct MatrixApi {
/// URL to call the API
pub base_url: String,
/// Access token for authentication
pub access_token: String,
/// Logger passed to the Matrix API
logger: Logger,
}
impl MatrixApi {
/// Create a new MatrixApi.
pub fn new(config: &Config, logger: Logger) -> MatrixApi {
MatrixApi {
base_url: config.hs_url.to_string(),
access_token: config.as_token.to_string(),
logger: logger,
}
}
fn params_hash(&self) -> HashMap<&str, &str> {
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("access_token", &self.access_token);
params
}
}
impl super::MatrixApi for MatrixApi {
fn create_room(&self, room_name: String, matrix_user_id: UserId) -> Result<RoomId> {
let endpoint = self.base_url.clone() + &CreateRoomEndpoint::request_path(());
let body_params = create_room::BodyParams {
creation_content: None,
invite: vec![matrix_user_id],
name: Some(room_name),
preset: Some(RoomPreset::PrivateChat),
room_alias_name: None,
topic: None,
visibility: Some("private".to_string()),
};
let payload = serde_json::to_string(&body_params).chain_err(|| ErrorKind::InvalidJSON("Could not serialize create_room body params".to_string()))?;
let params = self.params_hash();
let (body, status_code) = RestApi::call_matrix(CreateRoomEndpoint::method(), &endpoint, &payload, ¶ms)?;
if !status_code.is_success() {
return Err(build_error(&endpoint, &body, &status_code));
}
let create_room_response: create_room::Response = serde_json::from_str(&body).chain_err(|| {
ErrorKind::InvalidJSON(format!("Could not deserialize response from Matrix create_room API endpoint: \
`{}`",
body))
})?;
Ok(create_room_response.room_id)
}
fn forget_room(&self, matrix_room_id: RoomId) -> Result<()> {
let path_params = forget_room::PathParams { room_id: matrix_room_id };
let endpoint = self.base_url.clone() + &ForgetRoomEndpoint::request_path(path_params);
let params = self.params_hash();
let (body, status_code) = RestApi::call_matrix(ForgetRoomEndpoint::method(), &endpoint, "{}", ¶ms)?;
if !status_code.is_success() {
return Err(build_error(&endpoint, &body, &status_code));
}
Ok(())
}
fn get_room_members(&self, matrix_room_id: RoomId) -> Result<Vec<MemberEvent>> {
let path_params = get_member_events::PathParams { room_id: matrix_room_id.clone() };
let endpoint = self.base_url.clone() + &GetMemberEventsEndpoint::request_path(path_params);
let params = self.params_hash();
let (body, status_code) = RestApi::call_matrix(GetMemberEventsEndpoint::method(), &endpoint, "{}", ¶ms)?;
if !status_code.is_success() {
return Err(build_error(&endpoint, &body, &status_code));
}
debug!(self.logger,
format!("List of room members for room {} successfully received", matrix_room_id));
let room_member_events: get_member_events::Response = serde_json::from_str(&body).chain_err(|| {
ErrorKind::InvalidJSON(format!("Could not deserialize response from Matrix members API endpoint: `{}`",
body))
})?;
Ok(room_member_events.chunk)
}
fn invite(&self, matrix_room_id: RoomId, matrix_user_id: UserId) -> Result<()> {
let path_params = invite_user::PathParams { room_id: matrix_room_id.clone() };
let endpoint = self.base_url.clone() + &InviteUserEndpoint::request_path(path_params);
let params = self.params_hash();
let body_params = invite_user::BodyParams { user_id: matrix_user_id.clone() };
let payload = serde_json::to_string(&body_params).chain_err(|| ErrorKind::InvalidJSON("Could not serialize invite user params".to_string()))?;
let (body, status_code) = RestApi::call_matrix(InviteUserEndpoint::method(), &endpoint, &payload, ¶ms)?;
if !status_code.is_success() {
return Err(build_error(&endpoint, &body, &status_code));
}
debug!(self.logger,
"User {} successfully invited into room {}",
matrix_user_id,
matrix_room_id);
Ok(())
}
fn join(&self, matrix_room_id: RoomId, matrix_user_id: UserId) -> Result<()> {
let path_params = join_room_by_id::PathParams { room_id: matrix_room_id.clone() };
let endpoint = self.base_url.clone() + &JoinRoomByIdEndpoint::request_path(path_params);
let user_id = matrix_user_id.to_string();
let mut params = self.params_hash();
params.insert("user_id", &user_id);
let (body, status_code) = RestApi::call_matrix(JoinRoomByIdEndpoint::method(), &endpoint, "{}", ¶ms)?;
if !status_code.is_success() {
return Err(build_error(&endpoint, &body, &status_code));
}
debug!(self.logger,
"User {} successfully joined room {}",
matrix_room_id,
matrix_user_id);
Ok(())
}
fn leave_room(&self, matrix_room_id: RoomId) -> Result<()> {
let path_params = leave_room::PathParams { room_id: matrix_room_id };
let endpoint = self.base_url.clone() + &LeaveRoomEndpoint::request_path(path_params);
let params = self.params_hash();
let (body, status_code) = RestApi::call_matrix(LeaveRoomEndpoint::method(), &endpoint, "{}", ¶ms)?;
if !status_code.is_success() {
return Err(build_error(&endpoint, &body, &status_code));
}
Ok(())
}
fn register(&self, user_id_local_part: String) -> Result<()> {
let endpoint = self.base_url.clone() + &RegisterEndpoint::request_path(());
let params = self.params_hash();
let body_params = register::BodyParams {
bind_email: None,
password: None,
username: Some(user_id_local_part.to_lowercase()),
device_id: None,
initial_device_display_name: None,
auth: None,
};
let payload = serde_json::to_string(&body_params).chain_err(|| ErrorKind::InvalidJSON("Could not serialize account body params".to_string()))?;
let (body, status_code) = RestApi::call_matrix(RegisterEndpoint::method(), &endpoint, &payload, ¶ms)?;
if !status_code.is_success() {
return Err(build_error(&endpoint, &body, &status_code));
}
Ok(())
}
fn send_text_message_event(&self, matrix_room_id: RoomId, matrix_user_id: UserId, body: String) -> Result<()> {
let formatted_body = render_markdown(&body);
let mut message = Map::new();
message.insert("body", body);
message.insert("formatted_body", formatted_body);
message.insert("msgtype", MessageType::Text.to_string());
message.insert("format", "org.matrix.custom.html".to_string());
let payload =
serde_json::to_string(&message).chain_err(|| ErrorKind::InvalidJSON("Could not serialize message".to_string()))?;
let txn_id = EventId::new(&self.base_url).chain_err(|| ErrorKind::EventIdGenerationFailed)?;
let path_params = send_message_event::PathParams {
room_id: matrix_room_id.clone(),
event_type: EventType::RoomMessage,
txn_id: txn_id.to_string(),
};
let endpoint = self.base_url.clone() + &SendMessageEventEndpoint::request_path(path_params);
let user_id = matrix_user_id.to_string();
let mut params = self.params_hash();
params.insert("user_id", &user_id);
let (body, status_code) = RestApi::call_matrix(SendMessageEventEndpoint::method(), &endpoint, &payload, ¶ms)?;
if !status_code.is_success() {
return Err(build_error(&endpoint, &body, &status_code));
}
debug!(self.logger,
"User {} successfully sent a message to room {}",
matrix_user_id,
matrix_room_id);
Ok(())
}
fn set_room_name(&self, matrix_room_id: RoomId, name: String) -> Result<()> {
let path_params = send_state_event_for_empty_key::PathParams {
room_id: matrix_room_id,
event_type: EventType::RoomName,
};
let endpoint = self.base_url.clone() + &SendStateEventForEmptyKeyEndpoint::request_path(path_params);
let params = self.params_hash();
let mut body_params = serde_json::Map::new();
body_params.insert("name", name);
let payload = serde_json::to_string(&body_params).chain_err(|| ErrorKind::InvalidJSON("Could not serialize account body params".to_string()))?;
let (body, status_code) =
RestApi::call_matrix(SendStateEventForEmptyKeyEndpoint::method(), &endpoint, &payload, ¶ms)?;
if !status_code.is_success() {
return Err(build_error(&endpoint, &body, &status_code));
}
Ok(())
}
}
fn build_error(endpoint: &str, body: &str, status_code: &StatusCode) -> Error {
let json_error_msg = format!("Could not deserialize error from Matrix API endpoint {} with status code {}: `{}`",
endpoint,
status_code,
body);
let json_error = ErrorKind::InvalidJSON(json_error_msg);
let matrix_error_resp: MatrixErrorResponse =
match serde_json::from_str(body).chain_err(|| json_error).map_err(Error::from) {
Ok(matrix_error_resp) => matrix_error_resp,
Err(err) => {
return err;
}
};
Error::from(ErrorKind::MatrixError(matrix_error_resp.error))
}
fn render_markdown(input: &str) -> String {
// The html will not have the same length as the msg, but it's a good starting point
let mut output = String::with_capacity(input.len());
let opts = Options::empty();
let parser = Parser::new_ext(input, opts);
html::push_html(&mut output, parser);
output
}