forked from mujx/mtxclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.hpp
384 lines (332 loc) · 15.2 KB
/
client.hpp
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
#pragma once
#include <experimental/optional>
#include <memory>
#include <mutex>
#include <thread>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/beast.hpp>
#include <boost/thread/thread.hpp>
#include <json.hpp>
#include "errors.hpp"
#include "mtx/requests.hpp"
#include "mtx/responses.hpp"
#include "session.hpp"
#include "utils.hpp"
namespace mtx {
namespace client {
//! The main object that the user will interact.
class Client : public std::enable_shared_from_this<Client>
{
public:
Client(const std::string &server = "");
//! Wait for the client to close.
void close();
//! Cancels the request.
void cancel_request(RequestID request_id);
//! Make a new request.
void do_request(std::shared_ptr<Session> session);
//! Return the number of pending requests.
int active_sessions() const { return active_sessions_.size(); }
//! Add an access token.
void set_access_token(const std::string &token) { access_token_ = token; }
//! Retrieve the access token.
std::string access_token() const { return access_token_; }
//! Update the next batch token.
void set_next_batch_token(const std::string &token) { next_batch_token_ = token; }
//! Retrieve the current next batch token.
std::string next_batch_token() const { return next_batch_token_; }
using RequestErr = std::experimental::optional<mtx::client::errors::ClientError>;
//! Perfom login.
void login(const std::string &username,
const std::string &password,
std::function<void(const mtx::responses::Login &response, RequestErr err)>);
//! Perform logout.
void logout(std::function<void(const mtx::responses::Logout &response, RequestErr err)>);
//! Change displayname.
void set_displayname(const std::string &displayname, std::function<void(RequestErr err)>);
//! Create a room with the given options.
void create_room(
const mtx::requests::CreateRoom &room_options,
std::function<void(const mtx::responses::CreateRoom &response, RequestErr err)>);
//! Join a room by its room_id.
void join_room(const mtx::identifiers::Room &room_id,
std::function<void(const nlohmann::json &res, RequestErr err)>);
//! Join a room by an alias or a room_id.
void join_room(const std::string &room,
std::function<void(const nlohmann::json &res, RequestErr err)>);
//! Leave a room by its room_id.
void leave_room(const mtx::identifiers::Room &room_id,
std::function<void(const nlohmann::json &res, RequestErr err)>);
//! Invite a user to a room.
/* void invite_user(); */
//! Perform sync.
void sync(const std::string &filter,
const std::string &since,
bool full_state,
uint16_t timeout,
std::function<void(const mtx::responses::Sync &res, RequestErr err)>);
//! Paginate through room messages.
/* void get_messages(); */
//! Send a message into a room.
/* void send_room_message(); */
//! Get the supported versions from the server.
void versions(std::function<void(const mtx::responses::Versions &res, RequestErr err)>);
//! Upload data to the content repository.
void upload(const std::string &data,
const std::string &content_type,
const std::string &filename,
std::function<void(const mtx::responses::ContentURI &res, RequestErr err)> cb);
/* void download_room_avatar(); */
/* void download_user_avatar(); */
/* void download_media(); */
/* void upload_image(); */
/* void upload_file(); */
/* void upload_audio(); */
/* void upload_video(); */
/* void upload_filter(); */
/* void send_typing_notification(); */
/* void remove_typing_notification(); */
/* void read_event(); */
private:
template<class Request, class Response>
void post(
const std::string &endpoint,
const Request &req,
std::function<void(const Response &,
std::experimental::optional<mtx::client::errors::ClientError>)>,
bool requires_auth = true,
const std::string &content_type = "application/json");
// put function for the PUT HTTP requests that send responses
template<class Request, class Response>
void put(const std::string &endpoint,
const Request &req,
std::function<void(const Response &,
std::experimental::optional<mtx::client::errors::ClientError>)>,
bool requires_auth = true);
template<class Request>
void put(const std::string &endpoint,
const Request &req,
std::function<void(std::experimental::optional<mtx::client::errors::ClientError>)>,
bool requires_auth = true);
template<class Response>
void get(const std::string &endpoint,
std::function<void(const Response &,
std::experimental::optional<mtx::client::errors::ClientError>)>,
bool requires_auth = true);
template<class Response, class Callback>
std::shared_ptr<Session> create_session(const Callback &callback);
void remove_session(std::shared_ptr<Session> s);
void on_request_complete(std::shared_ptr<Session> s);
void on_resolve(std::shared_ptr<Session> s,
boost::system::error_code ec,
boost::asio::ip::tcp::resolver::results_type results);
void on_connect(std::shared_ptr<Session> s, boost::system::error_code ec);
void on_handshake(std::shared_ptr<Session> s, boost::system::error_code ec);
void on_write(std::shared_ptr<Session> s,
boost::system::error_code ec,
std::size_t bytes_transferred);
void on_read(std::shared_ptr<Session> s,
boost::system::error_code ec,
std::size_t bytes_transferred);
boost::asio::io_service ios_;
//! Keeps tracks for the active sessions.
std::map<RequestID, std::shared_ptr<Session>> active_sessions_;
//! Used to synchronize access to `active_sessions_`.
std::mutex active_sessions_guard_;
//! Used to prevent the event loop from shutting down.
std::unique_ptr<boost::asio::io_service::work> work_;
//! Worker threads for the requests.
boost::thread_group thread_group_;
//! Used to resolve DNS names.
boost::asio::ip::tcp::resolver resolver_;
//! The homeserver to connect to.
std::string server_;
//! The access token that would be used for authentication.
std::string access_token_;
//! The user ID associated with the client.
mtx::identifiers::User user_id_;
//! The token that will be used as the 'since' parameter on the next sync request.
std::string next_batch_token_;
};
}
}
template<class T>
inline T
deserialize(const std::string &data)
{
T res;
nlohmann::json j = json::parse(data);
res = j;
return res;
}
template<>
inline std::string
deserialize<std::string>(const std::string &data)
{
return data;
}
template<class T>
inline std::string
serialize(const T &obj)
{
nlohmann::json j = obj;
return j.dump();
}
template<>
inline std::string
serialize<std::string>(const std::string &obj)
{
return obj;
}
template<class Request, class Response>
void
mtx::client::Client::post(
const std::string &endpoint,
const Request &req,
std::function<void(const Response &,
std::experimental::optional<mtx::client::errors::ClientError>)> callback,
bool requires_auth,
const std::string &content_type)
{
using CallbackType = std::function<void(
const Response &, std::experimental::optional<mtx::client::errors::ClientError>)>;
std::shared_ptr<Session> session = create_session<Response, CallbackType>(callback);
session->request.method(boost::beast::http::verb::post);
session->request.target("/_matrix" + endpoint);
session->request.set(boost::beast::http::field::user_agent, "mtxclient v0.1.0");
session->request.set(boost::beast::http::field::content_type, content_type);
session->request.set(boost::beast::http::field::host, session->host);
if (requires_auth && !access_token_.empty())
session->request.set(boost::beast::http::field::authorization,
"Bearer " + access_token_);
session->request.body() = serialize<Request>(req);
session->request.prepare_payload();
do_request(session);
}
// put function for the PUT HTTP requests that send responses
template<class Request, class Response>
void
mtx::client::Client::put(
const std::string &endpoint,
const Request &req,
std::function<void(const Response &,
std::experimental::optional<mtx::client::errors::ClientError>)> callback,
bool requires_auth)
{
using CallbackType = std::function<void(
const Response &, std::experimental::optional<mtx::client::errors::ClientError>)>;
std::shared_ptr<Session> session = create_session<Response, CallbackType>(callback);
session->request.method(boost::beast::http::verb::put);
session->request.target("/_matrix" + endpoint);
session->request.set(boost::beast::http::field::user_agent, "mtxclient v0.1.0");
session->request.set(boost::beast::http::field::content_type, "application/json");
session->request.set(boost::beast::http::field::host, session->host);
if (requires_auth && !access_token_.empty())
session->request.set(boost::beast::http::field::authorization,
"Bearer " + access_token_);
session->request.body() = serialize<Request>(req);
session->request.prepare_payload();
do_request(session);
}
// provides PUT functionality for the endpoints which dont respond with a body
template<class Request>
void
mtx::client::Client::put(
const std::string &endpoint,
const Request &req,
std::function<void(std::experimental::optional<mtx::client::errors::ClientError>)> callback,
bool requires_auth)
{
mtx::client::Client::put<Request, mtx::responses::Empty>(
endpoint,
req,
[callback](const mtx::responses::Empty,
std::experimental::optional<mtx::client::errors::ClientError> err) {
callback(err);
},
requires_auth);
}
template<class Response>
void
mtx::client::Client::get(
const std::string &endpoint,
std::function<void(const Response &,
std::experimental::optional<mtx::client::errors::ClientError>)> callback,
bool requires_auth)
{
using CallbackType = std::function<void(
const Response &, std::experimental::optional<mtx::client::errors::ClientError>)>;
std::shared_ptr<Session> session = create_session<Response, CallbackType>(callback);
session->request.method(boost::beast::http::verb::get);
session->request.target("/_matrix" + endpoint);
session->request.set(boost::beast::http::field::user_agent, "mtxclient v0.1.0");
session->request.set(boost::beast::http::field::host, session->host);
if (requires_auth && !access_token_.empty())
session->request.set(boost::beast::http::field::authorization,
"Bearer " + access_token_);
session->request.prepare_payload();
do_request(session);
}
template<class Response, class Callback>
std::shared_ptr<mtx::client::Session>
mtx::client::Client::create_session(const Callback &callback)
{
boost::asio::ssl::context ssl_ctx{boost::asio::ssl::context::sslv23_client};
std::shared_ptr<Session> session = std::make_shared<Session>(
ios_,
ssl_ctx,
server_,
utils::random_token(),
[callback,
this](RequestID,
const boost::beast::http::response<boost::beast::http::string_body> &response,
const boost::system::error_code &err_code) {
ios_.post([callback, response, err_code]() {
Response response_data;
mtx::client::errors::ClientError client_error;
if (err_code) {
client_error.error_code = err_code;
return callback(response_data, client_error);
}
// TODO: handle http error.
if (response.result() != boost::beast::http::status::ok) {
// TODO: handle unknown error.
client_error.status_code = response.result();
try {
nlohmann::json json_error = json::parse(response.body());
mtx::errors::Error matrix_error = json_error;
client_error.matrix_error = matrix_error;
return callback(response_data, client_error);
} catch (nlohmann::json::exception &e) {
std::cout << e.what() << ": Couldn't parse response\n"
<< response.body().data() << std::endl;
// TODO: handle error
}
}
try {
response_data = deserialize<Response>(response.body().data());
} catch (nlohmann::json::exception &e) {
std::cout << e.what() << ": Couldn't parse response\n"
<< response.body().data() << std::endl;
// TODO: handle error
}
callback(response_data, {});
});
},
[callback](RequestID, const boost::system::error_code ec) {
Response response_data;
mtx::client::errors::ClientError client_error;
client_error.error_code = ec;
callback(response_data, client_error);
});
// Set SNI Hostname (many hosts need this to handshake successfully)
// TODO: handle the error
if (!SSL_set_tlsext_host_name(session->socket.native_handle(), server_.c_str())) {
boost::system::error_code ec{static_cast<int>(::ERR_get_error()),
boost::asio::error::get_ssl_category()};
std::cerr << ec.message() << "\n";
return session;
}
return session;
}