Debian Codegraph @

mtxclient/lib/http/client.cpp

raw symbols SCIP
1 #include "mtxclient/http/client.hpp"
2 #include "mtx/log.hpp"
3 #include "mtxclient/http/client_impl.hpp"
4
5 #include <nlohmann/json.hpp>
6
7 #include <coeurl/client.hpp>
8 #include <coeurl/request.hpp>
9 #include <utility>
10
11 #include "mtxclient/utils.hpp"
12
13 #include "mtx/log.hpp"
14 #include "mtx/requests.hpp"
15 #include "mtx/responses.hpp"
16
17 using namespace mtx::http;
18
19 namespace mtx::http {
20 struct ClientPrivate
21 {
22 coeurl::Client client;
23 };
24
25 void
26 UIAHandler::next(const user_interactive::Auth &auth) const
27 {
28 next_(*this, auth);
29 }
30 }
31
32 Client::Client(const std::string &server, uint16_t port)
33 : p{new ClientPrivate}
34 {
35 set_server(server);
36 set_port(port);
37
38 p->client.set_verify_peer(true);
39 p->client.connection_timeout(60);
40 }
41
42 // call destuctor of work queue and ios first!
43 Client::~Client() { p.reset(); }
44
45 void
46 Client::shutdown()
47 {
48 p->client.shutdown();
49 }
50
51 void
52 Client::alt_svc_cache_path(const std::string &path)
53 {
54 p->client.alt_svc_cache_path(path);
55 }
56
57 coeurl::Headers
58 mtx::http::Client::prepare_headers(bool requires_auth)
59 {
60 coeurl::Headers headers;
61 headers["User-Agent"] = "mtxclient v0.9.2";
62
63 if (requires_auth && !access_token_.empty())
64 headers["Authorization"] = "Bearer " + access_token();
65
66 return headers;
67 }
68
69 std::string
70 mtx::http::Client::endpoint_to_url(const std::string &endpoint, const char *endpoint_namespace)
71 {
72 return protocol_ + "://" + server_ + ":" + std::to_string(port_) + endpoint_namespace +
73 endpoint;
74 }
75
76 void
77 mtx::http::Client::post(const std::string &endpoint,
78 const std::string &req,
79 mtx::http::TypeErasedCallback cb,
80 bool requires_auth,
81 const std::string &content_type)
82 {
83 p->client.post(
84 endpoint_to_url(endpoint),
85 req,
86 content_type,
87 [cb = std::move(cb)](const coeurl::Request &r) {
88 cb(r.response_headers(), r.response(), r.error_code(), r.response_code());
89 },
90 prepare_headers(requires_auth));
91 }
92
93 void
94 mtx::http::Client::delete_(const std::string &endpoint, ErrCallback cb, bool requires_auth)
95 {
96 p->client.delete_(
97 endpoint_to_url(endpoint),
98 [cb = std::move(cb)](const coeurl::Request &r) {
99 mtx::http::ClientError client_error;
100 if (r.error_code()) {
101 client_error.error_code = r.error_code();
102 return cb(client_error);
103 }
104
105 client_error.status_code = r.response_code();
106
107 // We only count 2xx status codes as success.
108 if (client_error.status_code < 200 || client_error.status_code >= 300) {
109 // The homeserver should return an error struct.
110 try {
111 nlohmann::json json_error = nlohmann::json::parse(r.response());
112 client_error.matrix_error = json_error.get<mtx::errors::Error>();
113 } catch (const nlohmann::json::exception &e) {
114 client_error.parse_error =
115 std::string(e.what()) + ": " + std::string(r.response());
116 }
117 return cb(client_error);
118 }
119 return cb({});
120 },
121 prepare_headers(requires_auth));
122 }
123
124 void
125 mtx::http::Client::put(const std::string &endpoint,
126 const std::string &req,
127 mtx::http::TypeErasedCallback cb,
128 bool requires_auth)
129 {
130 p->client.put(
131 endpoint_to_url(endpoint),
132 req,
133 "application/json",
134 [cb = std::move(cb)](const coeurl::Request &r) {
135 cb(r.response_headers(), r.response(), r.error_code(), r.response_code());
136 },
137 prepare_headers(requires_auth));
138 }
139
140 void
141 mtx::http::Client::get(const std::string &endpoint,
142 mtx::http::TypeErasedCallback cb,
143 bool requires_auth,
144 const std::string &endpoint_namespace,
145 int num_redirects)
146 {
147 p->client.get(
148 endpoint_to_url(endpoint, endpoint_namespace.c_str()),
149 [cb = std::move(cb)](const coeurl::Request &r) {
150 cb(r.response_headers(), r.response(), r.error_code(), r.response_code());
151 },
152 prepare_headers(requires_auth),
153 num_redirects);
154 }
155
156 void
157 Client::verify_certificates(bool enabled)
158 {
159 p->client.set_verify_peer(enabled);
160 }
161
162 void
163 Client::set_server(const std::string &server)
164 {
165 std::string_view server_name = server;
166 std::uint16_t port = 443;
167 this->protocol_ = "https";
168 // Remove https prefix, if it exists
169 if (server_name.substr(0, 8) == "https://") {
170 server_name.remove_prefix(8);
171 port = 443;
172 }
173 if (server_name.substr(0, 7) == "http://") {
174 server_name.remove_prefix(7);
175 port = 80;
176 this->protocol_ = "http";
177 }
178 if (server_name.size() > 0 && server_name.back() == '/')
179 server_name.remove_suffix(1);
180
181 if (std::count(server_name.begin(), server_name.end(), ':') == 1) {
182 auto colon_offset = server_name.find(':');
183 server_ = std::string(server_name.substr(0, colon_offset));
184
185 auto tmp = std::string(server_name.substr(colon_offset + 1));
186 if (mtx::client::utils::is_number(tmp)) {
187 port_ = static_cast<std::uint16_t>(std::stoul(tmp));
188 return;
189 }
190 }
191
192 server_ = std::string(server_name);
193 port_ = port;
194 }
195
196 void
197 Client::close(bool force)
198 {
199 p->client.close(force);
200 }
201
202 //
203 // Client API endpoints
204 //
205
206 void
207 Client::login(const std::string &user,
208 const std::string &password,
209 const std::string &device_name,
210 Callback<mtx::responses::Login> callback)
211 {
212 mtx::requests::Login req;
213 req.identifier = mtx::requests::login_identifier::User{user};
214 req.password = password;
215 req.initial_device_display_name = device_name;
216
217 login(req, std::move(callback));
218 }
219
220 void
221 Client::login(const std::string &user,
222 const std::string &password,
223 Callback<mtx::responses::Login> callback)
224 {
225 mtx::requests::Login req;
226 req.identifier = mtx::requests::login_identifier::User{user};
227 req.password = password;
228
229 login(req, std::move(callback));
230 }
231
232 void
233 Client::login(const mtx::requests::Login &req, Callback<mtx::responses::Login> callback)
234 {
235 post<mtx::requests::Login, mtx::responses::Login>(
236 "/client/v3/login",
237 req,
238 [_this = shared_from_this(),
239 callback = std::move(callback)](const mtx::responses::Login &resp, RequestErr err) {
240 if (!err && resp.access_token.size()) {
241 _this->user_id_ = resp.user_id;
242 _this->device_id_ = resp.device_id;
243 _this->access_token_ = resp.access_token;
244 }
245 callback(resp, err);
246 },
247 false);
248 }
249
250 void
251 Client::get_login(Callback<mtx::responses::LoginFlows> cb)
252 {
253 get<mtx::responses::LoginFlows>(
254 "/client/v3/login",
255 [cb = std::move(cb)](const mtx::responses::LoginFlows &res, HeaderFields, RequestErr err) {
256 cb(res, err);
257 },
258 false);
259 }
260
261 std::string
262 Client::login_sso_redirect(std::string redirectUrl, const std::string &idp)
263 {
264 const std::string idp_suffix = idp.empty() ? idp : ("/" + mtx::client::utils::url_encode(idp));
265 return protocol_ + "://" + server() + ":" + std::to_string(port()) +
266 "/_matrix/client/v3/login/sso/redirect" + idp_suffix + "?" +
267 mtx::client::utils::query_params({{"redirectUrl", redirectUrl}});
268 }
269
270 void
271 Client::well_known(Callback<mtx::responses::WellKnown> callback)
272 {
273 get<mtx::responses::WellKnown>(
274 "/matrix/client",
275 [cb = std::move(callback)](
276 const mtx::responses::WellKnown &res, HeaderFields, RequestErr err) { cb(res, err); },
277 false,
278 "/.well-known",
279 30);
280 }
281
282 void
283 Client::logout(Callback<mtx::responses::Logout> callback)
284 {
285 mtx::requests::Logout req;
286
287 post<mtx::requests::Logout, mtx::responses::Logout>(
288 "/client/v3/logout",
289 req,
290 [_this = shared_from_this(),
291 callback = std::move(callback)](const mtx::responses::Logout &res, RequestErr err) {
292 if (!err) {
293 // Clear the now invalid access token when logout is successful
294 _this->clear();
295 }
296 // Pass up response and error to supplied callback
297 callback(res, err);
298 });
299 }
300
301 void
302 Client::notifications(uint64_t limit,
303 const std::string &from,
304 const std::string &only,
305 Callback<mtx::responses::Notifications> cb)
306 {
307 std::map<std::string, std::string> params;
308 params.emplace("limit", std::to_string(limit));
309
310 if (!from.empty()) {
311 params.emplace("from", from);
312 }
313
314 if (!only.empty()) {
315 params.emplace("only", only);
316 }
317
318 get<mtx::responses::Notifications>(
319 "/client/v3/notifications?" + mtx::client::utils::query_params(params),
320 [cb = std::move(cb)](const mtx::responses::Notifications &res, HeaderFields, RequestErr err) {
321 cb(res, err);
322 });
323 }
324
325 void
326 Client::get_pushrules(Callback<mtx::pushrules::GlobalRuleset> cb)
327 {
328 get<mtx::pushrules::GlobalRuleset>(
329 "/client/v3/pushrules/",
330 [cb = std::move(cb)](const mtx::pushrules::GlobalRuleset &res, HeaderFields, RequestErr err) {
331 cb(res, err);
332 });
333 }
334
335 void
336 Client::get_pushrules(const std::string &scope,
337 const std::string &kind,
338 const std::string &ruleId,
339 Callback<mtx::pushrules::PushRule> cb)
340 {
341 get<mtx::pushrules::PushRule>(
342 "/client/v3/pushrules/" + mtx::client::utils::url_encode(scope) + "/" +
343 mtx::client::utils::url_encode(kind) + "/" + mtx::client::utils::url_encode(ruleId),
344 [cb = std::move(cb)](const mtx::pushrules::PushRule &res, HeaderFields, RequestErr err) {
345 cb(res, err);
346 });
347 }
348
349 void
350 Client::delete_pushrules(const std::string &scope,
351 const std::string &kind,
352 const std::string &ruleId,
353 ErrCallback cb)
354 {
355 delete_("/client/v3/pushrules/" + mtx::client::utils::url_encode(scope) + "/" +
356 mtx::client::utils::url_encode(kind) + "/" + mtx::client::utils::url_encode(ruleId),
357 std::move(cb));
358 }
359
360 void
361 Client::put_pushrules(const std::string &scope,
362 const std::string &kind,
363 const std::string &ruleId,
364 const mtx::pushrules::PushRule &rule,
365 ErrCallback cb,
366 const std::string &before,
367 const std::string &after)
368 {
369 std::map<std::string, std::string> params;
370
371 if (!before.empty())
372 params.emplace("before", before);
373
374 if (!after.empty())
375 params.emplace("after", after);
376
377 std::string path = "/client/v3/pushrules/" + mtx::client::utils::url_encode(scope) + "/" +
378 mtx::client::utils::url_encode(kind) + "/" +
379 mtx::client::utils::url_encode(ruleId);
380 if (!params.empty())
381 path += "?" + mtx::client::utils::query_params(params);
382 put<mtx::pushrules::PushRule>(path, rule, std::move(cb));
383 }
384
385 void
386 Client::get_pushrules_enabled(const std::string &scope,
387 const std::string &kind,
388 const std::string &ruleId,
389 Callback<mtx::pushrules::Enabled> cb)
390 {
391 get<mtx::pushrules::Enabled>("/client/v3/pushrules/" + mtx::client::utils::url_encode(scope) +
392 "/" + mtx::client::utils::url_encode(kind) + "/" +
393 mtx::client::utils::url_encode(ruleId) + "/enabled",
394 [cb = std::move(cb)](const mtx::pushrules::Enabled &res,
395 HeaderFields,
396 RequestErr err) { cb(res, err); });
397 }
398
399 void
400 Client::put_pushrules_enabled(const std::string &scope,
401 const std::string &kind,
402 const std::string &ruleId,
403 bool enabled,
404 ErrCallback cb)
405 {
406 put<mtx::pushrules::Enabled>("/client/v3/pushrules/" + mtx::client::utils::url_encode(scope) +
407 "/" + mtx::client::utils::url_encode(kind) + "/" +
408 mtx::client::utils::url_encode(ruleId) + "/enabled",
409 {enabled},
410 std::move(cb));
411 }
412
413 void
414 Client::get_pushrules_actions(const std::string &scope,
415 const std::string &kind,
416 const std::string &ruleId,
417 Callback<mtx::pushrules::actions::Actions> cb)
418 {
419 get<mtx::pushrules::actions::Actions>(
420 "/client/v3/pushrules/" + mtx::client::utils::url_encode(scope) + "/" +
421 mtx::client::utils::url_encode(kind) + "/" + mtx::client::utils::url_encode(ruleId) +
422 "/actions",
423 [cb = std::move(cb)](const mtx::pushrules::actions::Actions &res,
424 HeaderFields,
425 RequestErr err) { cb(res, err); });
426 }
427
428 void
429 Client::put_pushrules_actions(const std::string &scope,
430 const std::string &kind,
431 const std::string &ruleId,
432 const mtx::pushrules::actions::Actions &actions,
433 ErrCallback cb)
434 {
435 put<mtx::pushrules::actions::Actions>("/client/v3/pushrules/" +
436 mtx::client::utils::url_encode(scope) + "/" +
437 mtx::client::utils::url_encode(kind) + "/" +
438 mtx::client::utils::url_encode(ruleId) + "/actions",
439 actions,
440 std::move(cb));
441 }
442
443 void
444 Client::set_avatar_url(const std::string &avatar_url, ErrCallback callback)
445 {
446 mtx::requests::AvatarUrl req;
447 req.avatar_url = avatar_url;
448
449 put<mtx::requests::AvatarUrl>(
450 "/client/v3/profile/" + mtx::client::utils::url_encode(user_id_.to_string()) + "/avatar_url",
451 req,
452 std::move(callback));
453 }
454
455 void
456 Client::set_displayname(const std::string &displayname, ErrCallback callback)
457 {
458 mtx::requests::DisplayName req;
459 req.displayname = displayname;
460
461 put<mtx::requests::DisplayName>(
462 "/client/v3/profile/" + mtx::client::utils::url_encode(user_id_.to_string()) + "/displayname",
463 req,
464 std::move(callback));
465 }
466
467 void
468 Client::get_profile(const std::string &user_id, Callback<mtx::responses::Profile> callback)
469 {
470 get<mtx::responses::Profile>(
471 "/client/v3/profile/" + mtx::client::utils::url_encode(user_id),
472 [callback = std::move(callback)](
473 const mtx::responses::Profile &res, HeaderFields, RequestErr err) { callback(res, err); });
474 }
475
476 void
477 Client::get_avatar_url(const std::string &user_id, Callback<mtx::responses::AvatarUrl> callback)
478 {
479 get<mtx::responses::AvatarUrl>(
480 "/client/v3/profile/" + mtx::client::utils::url_encode(user_id) + "/avatar_url",
481 [callback = std::move(callback)](const mtx::responses::AvatarUrl &res,
482 HeaderFields,
483 RequestErr err) { callback(res, err); });
484 }
485
486 void
487 Client::get_tags(const std::string &room_id, Callback<mtx::events::account_data::Tags> cb)
488 {
489 get<mtx::events::account_data::Tags>(
490 "/client/v3/user/" + mtx::client::utils::url_encode(user_id_.to_string()) + "/rooms/" +
491 mtx::client::utils::url_encode(room_id) + "/tags",
492 [cb = std::move(cb)](const mtx::events::account_data::Tags &res,
493 HeaderFields,
494 RequestErr err) { cb(res, err); });
495 }
496 void
497 Client::put_tag(const std::string &room_id,
498 const std::string &tag_name,
499 const mtx::events::account_data::Tag &tag,
500 ErrCallback cb)
501 {
502 put<mtx::events::account_data::Tag>("/client/v3/user/" +
503 mtx::client::utils::url_encode(user_id_.to_string()) +
504 "/rooms/" + mtx::client::utils::url_encode(room_id) +
505 "/tags/" + mtx::client::utils::url_encode(tag_name),
506 tag,
507 std::move(cb));
508 }
509 void
510 Client::delete_tag(const std::string &room_id, const std::string &tag_name, ErrCallback cb)
511 {
512 delete_("/client/v3/user/" + mtx::client::utils::url_encode(user_id_.to_string()) + "/rooms/" +
513 mtx::client::utils::url_encode(room_id) + "/tags/" +
514 mtx::client::utils::url_encode(tag_name),
515 std::move(cb));
516 }
517
518 void
519 Client::create_room(const mtx::requests::CreateRoom &room_options,
520 Callback<mtx::responses::CreateRoom> callback)
521 {
522 post<mtx::requests::CreateRoom, mtx::responses::CreateRoom>(
523 "/client/v3/createRoom", room_options, std::move(callback));
524 }
525
526 void
527 Client::join_room(const std::string &room, Callback<mtx::responses::RoomId> callback)
528 {
529 join_room(room, {}, std::move(callback));
530 }
531
532 void
533 Client::join_room(const std::string &room,
534 const std::vector<std::string> &via,
535 Callback<mtx::responses::RoomId> callback,
536 const std::string &reason)
537 {
538 using mtx::client::utils::url_encode;
539 std::string query;
540 if (!via.empty()) {
541 query = "?server_name=" + url_encode(via[0]);
542 for (size_t i = 1; i < via.size(); i++) {
543 query += "&server_name=" + url_encode(via[i]);
544 }
545 for (const auto &v : via) {
546 query += "&via=" + url_encode(v);
547 }
548 }
549 auto api_path = "/client/v3/join/" + url_encode(room) + query;
550
551 auto body = nlohmann::json::object();
552 if (!reason.empty())
553 body["reason"] = reason;
554
555 post<std::string, mtx::responses::RoomId>(api_path, body.dump(), std::move(callback));
556 }
557
558 void
559 Client::knock_room(const std::string &room,
560 const std::vector<std::string> &via,
561 Callback<mtx::responses::RoomId> cb,
562 const std::string &reason)
563 {
564 using mtx::client::utils::url_encode;
565 std::string query;
566 if (!via.empty()) {
567 query = "?server_name=" + url_encode(via[0]);
568 for (size_t i = 1; i < via.size(); i++) {
569 query += "&server_name=" + url_encode(via[i]);
570 }
571 for (const auto &v : via) {
572 query += "&via=" + url_encode(v);
573 }
574 }
575 auto api_path = "/client/v3/knock/" + url_encode(room) + query;
576
577 auto body = nlohmann::json::object();
578 if (!reason.empty())
579 body["reason"] = reason;
580
581 post<std::string, mtx::responses::RoomId>(api_path, body.dump(), std::move(cb));
582 }
583
584 void
585 Client::leave_room(const std::string &room_id,
586 Callback<mtx::responses::Empty> callback,
587 const std::string &reason)
588 {
589 auto api_path = "/client/v3/rooms/" + mtx::client::utils::url_encode(room_id) + "/leave";
590
591 auto body = nlohmann::json::object();
592 if (!reason.empty())
593 body["reason"] = reason;
594
595 post<std::string, mtx::responses::Empty>(api_path, body.dump(), std::move(callback));
596 }
597
598 void
599 Client::invite_user(const std::string &room_id,
600 const std::string &user_id,
601 Callback<mtx::responses::RoomInvite> callback,
602 const std::string &reason)
603 {
604 mtx::requests::RoomMembershipChange req;
605 req.user_id = user_id;
606 req.reason = reason;
607
608 auto api_path = "/client/v3/rooms/" + mtx::client::utils::url_encode(room_id) + "/invite";
609
610 post<mtx::requests::RoomMembershipChange, mtx::responses::RoomInvite>(
611 api_path, req, std::move(callback));
612 }
613
614 void
615 Client::kick_user(const std::string &room_id,
616 const std::string &user_id,
617 Callback<mtx::responses::Empty> callback,
618 const std::string &reason)
619 {
620 mtx::requests::RoomMembershipChange req;
621 req.user_id = user_id;
622 req.reason = reason;
623
624 auto api_path = "/client/v3/rooms/" + mtx::client::utils::url_encode(room_id) + "/kick";
625
626 post<mtx::requests::RoomMembershipChange, mtx::responses::Empty>(
627 api_path, req, std::move(callback));
628 }
629
630 void
631 Client::ban_user(const std::string &room_id,
632 const std::string &user_id,
633 Callback<mtx::responses::Empty> callback,
634 const std::string &reason)
635 {
636 mtx::requests::RoomMembershipChange req;
637 req.user_id = user_id;
638 req.reason = reason;
639
640 auto api_path = "/client/v3/rooms/" + mtx::client::utils::url_encode(room_id) + "/ban";
641
642 post<mtx::requests::RoomMembershipChange, mtx::responses::Empty>(
643 api_path, req, std::move(callback));
644 }
645
646 void
647 Client::unban_user(const std::string &room_id,
648 const std::string &user_id,
649 Callback<mtx::responses::Empty> callback,
650 const std::string &reason)
651 {
652 mtx::requests::RoomMembershipChange req;
653 req.user_id = user_id;
654 req.reason = reason;
655
656 auto api_path = "/client/v3/rooms/" + mtx::client::utils::url_encode(room_id) + "/unban";
657
658 post<mtx::requests::RoomMembershipChange, mtx::responses::Empty>(
659 api_path, req, std::move(callback));
660 }
661
662 void
663 Client::sync(const SyncOpts &opts, Callback<mtx::responses::Sync> callback)
664 {
665 std::map<std::string, std::string> params;
666
667 if (!opts.filter.empty())
668 params.emplace("filter", opts.filter);
669
670 if (!opts.since.empty())
671 params.emplace("since", opts.since);
672
673 if (opts.full_state)
674 params.emplace("full_state", "true");
675
676 if (opts.set_presence)
677 params.emplace("set_presence", mtx::presence::to_string(opts.set_presence.value()));
678
679 params.emplace("timeout", std::to_string(opts.timeout));
680
681 get<mtx::responses::Sync>(
682 "/client/v3/sync?" + mtx::client::utils::query_params(params),
683 [callback = std::move(callback)](
684 const mtx::responses::Sync &res, HeaderFields, RequestErr err) { callback(res, err); });
685 }
686
687 void
688 Client::versions(Callback<mtx::responses::Versions> callback)
689 {
690 get<mtx::responses::Versions>(
691 "/client/versions",
692 [callback = std::move(callback)](
693 const mtx::responses::Versions &res, HeaderFields, RequestErr err) { callback(res, err); });
694 }
695
696 void
697 Client::capabilities(Callback<mtx::responses::capabilities::Capabilities> callback)
698 {
699 get<mtx::responses::capabilities::Capabilities>(
700 "/client/v3/capabilities",
701 [callback = std::move(callback)](const mtx::responses::capabilities::Capabilities &res,
702 HeaderFields,
703 RequestErr err) { callback(res, err); });
704 }
705
706 void
707 Client::upload(const std::string &data,
708 const std::string &content_type,
709 const std::string &filename,
710 Callback<mtx::responses::ContentURI> cb)
711 {
712 std::map<std::string, std::string> params = {{"filename", filename}};
713
714 const auto api_path = "/media/v3/upload?" + client::utils::query_params(params);
715 post<std::string, mtx::responses::ContentURI>(
716 api_path, data, std::move(cb), true, content_type);
717 }
718
719 void
720 Client::download(const std::string &mxc_url,
721 std::function<void(const std::string &res,
722 const std::string &content_type,
723 const std::string &original_filename,
724 RequestErr err)> callback)
725 {
726 auto url = mtx::client::utils::parse_mxc_url(mxc_url);
727 download(url.server, url.media_id, std::move(callback));
728 }
729
730 void
731 Client::preview_url(const std::optional<std::int64_t> &timestamp,
732 const std::string &url,
733 Callback<mtx::responses::URLPreview> callback)
734 {
735 std::map<std::string, std::string> params;
736
737 if (timestamp) {
738 params.emplace("ts", std::to_string(*timestamp));
739 }
740
741 params.emplace("url", url);
742
743 const auto api_path = "/client/v1/media/preview_url?" + client::utils::query_params(params);
744 get<mtx::responses::URLPreview>(
745 api_path,
746 [callback = std::move(callback), params = std::move(params), _this = shared_from_this()](
747 const mtx::responses::URLPreview &res, HeaderFields, RequestErr err) {
748 if (!err || !(err->status_code == 404 || err->status_code == 400)) {
749 callback(res, err);
750 } else {
751 const auto api_path = "/media/v3/preview_url?" + client::utils::query_params(params);
752 _this->get<mtx::responses::URLPreview>(
753 api_path,
754 [callback](const mtx::responses::URLPreview &res, HeaderFields, RequestErr err) {
755 callback(res, err);
756 });
757 }
758 });
759 }
760
761 void
762 Client::get_thumbnail(const ThumbOpts &opts, Callback<std::string> callback, bool try_download)
763 {
764 std::map<std::string, std::string> params;
765 params.emplace("width", std::to_string(opts.width));
766 params.emplace("height", std::to_string(opts.height));
767 params.emplace("method", opts.method);
768
769 auto mxc = mtx::client::utils::parse_mxc_url(opts.mxc_url);
770 const auto api_path = "/client/v1/media/thumbnail/" + mxc.server + "/" + mxc.media_id + "?" +
771 client::utils::query_params(params);
772 auto fallback_api_path = "/media/v3/thumbnail/" + mxc.server + "/" + mxc.media_id + "?" +
773 client::utils::query_params(params);
774
775 get<std::string>(
776 api_path,
777 [callback = std::move(callback),
778 try_download,
779 mxc = std::move(mxc),
780 _this = shared_from_this(),
781 fallback_api_path =
782 std::move(fallback_api_path)](const std::string &res, HeaderFields, RequestErr err) {
783 if (!err || !(err->status_code == 404 || err->status_code == 400)) {
784 callback(res, err);
785 } else if (err && try_download && err->status_code == 404) {
786 _this->download(mxc.server,
787 mxc.media_id,
788 [callback](const std::string &res,
789 const std::string &, // content_type
790 const std::string &, // original_filename
791 RequestErr err) { callback(res, err); });
792 } else {
793 _this->get<std::string>(fallback_api_path,
794 [callback = callback, try_download, mxc, _this](
795 const std::string &res, HeaderFields, RequestErr err) {
796 if (err && try_download && err->status_code == 404) {
797 _this->download(
798 mxc.server,
799 mxc.media_id,
800 [callback](const std::string &res,
801 const std::string &, // content_type
802 const std::string &, // original_filename
803 RequestErr err) { callback(res, err); });
804 } else {
805 callback(res, err);
806 }
807 });
808 }
809 });
810 }
811
812 void
813 Client::download(const std::string &server,
814 const std::string &media_id,
815 std::function<void(const std::string &res,
816 const std::string &content_type,
817 const std::string &original_filename,
818 RequestErr err)> callback)
819 {
820 auto cb = [callback =
821 std::move(callback)](const std::string &res, HeaderFields fields, RequestErr err) {
822 std::string content_type, original_filename;
823
824 if (fields) {
825 if (fields->find("Content-Type") != fields->end())
826 content_type = fields->at("Content-Type");
827 if (fields->find("Content-Disposition") != fields->end()) {
828 auto value = fields->at("Content-Disposition");
829
830 if (auto pos = value.find("filename"); pos != std::string::npos) {
831 if (auto start = value.find('"', pos); start != std::string::npos) {
832 auto end = value.find('"', start + 1);
833 original_filename = value.substr(start + 1, end - start - 2);
834 } else if (start = value.find('='); start != std::string::npos) {
835 original_filename = value.substr(start + 1);
836 }
837 }
838 }
839 }
840
841 callback(res, content_type, original_filename, err);
842 };
843
844 const auto api_path = "/client/v1/media/download/" + client::utils::url_encode(server) + "/" +
845 client::utils::url_encode(media_id);
846 get<std::string>(
847 api_path,
848 [_this = shared_from_this(), cb = std::move(cb), server, media_id](
849 const std::string &res, HeaderFields fields, RequestErr err) {
850 if (!err || !(err->status_code == 404 || err->status_code == 400)) {
851 cb(res, fields, err);
852 } else {
853 const auto api_path = "/media/v3/download/" + client::utils::url_encode(server) +
854 "/" + client::utils::url_encode(media_id);
855 _this->get<std::string>(api_path, std::move(cb));
856 }
857 },
858 true,
859 "/_matrix",
860 3);
861 }
862
863 void
864 Client::start_typing(const std::string &room_id, uint64_t timeout, ErrCallback callback)
865 {
866 using mtx::client::utils::url_encode;
867 const auto api_path =
868 "/client/v3/rooms/" + url_encode(room_id) + "/typing/" + url_encode(user_id_.to_string());
869
870 mtx::requests::TypingNotification req;
871 req.typing = true;
872 req.timeout = timeout;
873
874 put<mtx::requests::TypingNotification>(api_path, req, std::move(callback));
875 }
876
877 void
878 Client::stop_typing(const std::string &room_id, ErrCallback callback)
879 {
880 using mtx::client::utils::url_encode;
881 const auto api_path =
882 "/client/v3/rooms/" + url_encode(room_id) + "/typing/" + url_encode(user_id_.to_string());
883
884 mtx::requests::TypingNotification req;
885 req.typing = false;
886
887 put<mtx::requests::TypingNotification>(api_path, req, std::move(callback));
888 }
889
890 void
891 Client::presence_status(const std::string &user_id,
892 Callback<mtx::events::presence::Presence> callback)
893 {
894 using mtx::client::utils::url_encode;
895 const auto api_path = "/client/v3/presence/" + url_encode(user_id) + "/status";
896 get<mtx::events::presence::Presence>(
897 api_path,
898 [callback = std::move(callback)](const mtx::events::presence::Presence &res,
899 HeaderFields,
900 RequestErr err) { callback(res, err); });
901 }
902 void
903 Client::put_presence_status(mtx::presence::PresenceState state,
904 std::optional<std::string> status_msg,
905 ErrCallback cb)
906 {
907 using mtx::client::utils::url_encode;
908 const auto api_path = "/client/v3/presence/" + url_encode(user_id_.to_string()) + "/status";
909
910 nlohmann::json body;
911 body["presence"] = mtx::presence::to_string(state);
912 if (status_msg)
913 body["status_msg"] = *status_msg;
914
915 put<nlohmann::json>(api_path, body, std::move(cb));
916 }
917
918 void
919 Client::get_event(const std::string &room_id,
920 const std::string &event_id,
921 Callback<mtx::events::collections::TimelineEvents> callback)
922 {
923 using namespace mtx::client::utils;
924 const auto api_path =
925 "/client/v3/rooms/" + url_encode(room_id) + "/event/" + url_encode(event_id);
926
927 get<mtx::events::collections::TimelineEvents>(
928 api_path,
929 [callback = std::move(callback)](const mtx::events::collections::TimelineEvents &res,
930 HeaderFields,
931 RequestErr err) { callback(res, err); });
932 }
933
934 void
935 Client::members(const std::string &room_id,
936 Callback<mtx::responses::Members> cb,
937 const std::string &at,
938 std::optional<mtx::events::state::Membership> membership,
939 std::optional<mtx::events::state::Membership> not_membership)
940 {
941 std::map<std::string, std::string> params;
942
943 std::string query;
944
945 if (!at.empty())
946 params.emplace("at", at);
947 if (membership)
948 params.emplace("membership", events::state::membershipToString(*membership));
949 if (not_membership)
950 params.emplace("not_membership", events::state::membershipToString(*not_membership));
951
952 const auto api_path = "/client/v3/rooms/" + mtx::client::utils::url_encode(room_id) +
953 "/members?" + client::utils::query_params(params);
954
955 get<mtx::responses::Members>(api_path,
956 [cb = std::move(cb)](const mtx::responses::Members &res,
957 HeaderFields,
958 RequestErr err) { cb(res, err); });
959 }
960
961 void
962 Client::messages(const MessagesOpts &opts, Callback<mtx::responses::Messages> callback)
963 {
964 std::map<std::string, std::string> params;
965
966 params.emplace("dir", to_string(opts.dir));
967
968 if (!opts.from.empty())
969 params.emplace("from", opts.from);
970 if (!opts.to.empty())
971 params.emplace("to", opts.to);
972 if (opts.limit > 0)
973 params.emplace("limit", std::to_string(opts.limit));
974 if (!opts.filter.empty())
975 params.emplace("filter", opts.filter);
976
977 const auto api_path = "/client/v3/rooms/" + mtx::client::utils::url_encode(opts.room_id) +
978 "/messages?" + client::utils::query_params(params);
979
980 get<mtx::responses::Messages>(
981 api_path,
982 [callback = std::move(callback)](
983 const mtx::responses::Messages &res, HeaderFields, RequestErr err) { callback(res, err); });
984 }
985
986 void
987 Client::upload_filter(const nlohmann::json &j, Callback<mtx::responses::FilterId> callback)
988 {
989 const auto api_path =
990 "/client/v3/user/" + mtx::client::utils::url_encode(user_id_.to_string()) + "/filter";
991
992 post<nlohmann::json, mtx::responses::FilterId>(api_path, j, std::move(callback));
993 }
994
995 void
996 Client::read_event(const std::string &room_id,
997 const std::string &event_id,
998 ErrCallback callback,
999 bool hidden)
1000 {
1001 const auto api_path =
1002 "/client/v3/rooms/" + mtx::client::utils::url_encode(room_id) + "/read_markers";
1003
1004 nlohmann::json body = {
1005 {"m.fully_read", event_id},
1006 {"org.matrix.msc2285.read.private", event_id},
1007 {"m.read.private", event_id},
1008 };
1009
1010 if (!hidden)
1011 body["m.read"] = event_id;
1012
1013 post<nlohmann::json, mtx::responses::Empty>(
1014 api_path,
1015 body,
1016 [callback = std::move(callback)](const mtx::responses::Empty, RequestErr err) {
1017 callback(err);
1018 });
1019 }
1020
1021 void
1022 Client::redact_event(const std::string &room_id,
1023 const std::string &event_id,
1024 Callback<mtx::responses::EventId> callback,
1025 const std::string &reason)
1026 {
1027 const auto api_path = "/client/v3/rooms/" + mtx::client::utils::url_encode(room_id) +
1028 "/redact/" + mtx::client::utils::url_encode(event_id) + "/" +
1029 mtx::client::utils::url_encode(mtx::client::utils::random_token());
1030
1031 nlohmann::json body = nlohmann::json::object();
1032 if (!reason.empty()) {
1033 body["reason"] = reason;
1034 }
1035
1036 put<nlohmann::json, mtx::responses::EventId>(api_path, body, std::move(callback));
1037 }
1038
1039 void
1040 Client::report_event(const std::string &room_id,
1041 const std::string &event_id,
1042 const std::string &reason,
1043 const int score)
1044 {
1045 const auto api_path = "/client/v3/rooms" + mtx::client::utils::url_encode(room_id) +
1046 "/report/" + mtx::client::utils::url_encode(event_id);
1047 nlohmann::json body = nlohmann::json::object();
1048 if (!reason.empty())
1049 body["reason"] = reason;
1050 if (score <= 0 && score >= -100)
1051 body["score"] = score;
1052
1053 put<nlohmann::json, mtx::responses::Empty>(
1054 api_path,
1055 body,
1056 [](const mtx::responses::Empty &, const std::optional<mtx::http::ClientError> &) {});
1057 }
1058
1059 void
1060 Client::registration(const std::string &user,
1061 const std::string &pass,
1062 UIAHandler uia_handler,
1063 Callback<mtx::responses::Register> cb,
1064 const std::string &initial_device_display_name)
1065 {
1066 nlohmann::json req = {{"username", user}, {"password", pass}};
1067
1068 if (!initial_device_display_name.empty())
1069 req["initial_device_display_name"] = initial_device_display_name;
1070
1071 uia_handler.next_ = [this, req, cb = std::move(cb)](const UIAHandler &h,
1072 const nlohmann::json &auth) {
1073 auto request = req;
1074 if (!auth.empty())
1075 request["auth"] = auth;
1076
1077 post<nlohmann::json, mtx::responses::Register>(
1078 "/client/v3/register",
1079 request,
1080 [this, cb, h](auto &r, RequestErr e) {
1081 if (e && e->status_code == 401) {
1082 mtx::utils::log::log()->debug("{}", e);
1083 h.prompt(h, e->matrix_error.unauthorized);
1084 } else {
1085 if (!e && !r.access_token.empty()) {
1086 this->user_id_ = r.user_id;
1087 this->device_id_ = r.device_id;
1088 this->access_token_ = r.access_token;
1089 }
1090 cb(r, e);
1091 }
1092 },
1093 false);
1094 };
1095
1096 uia_handler.next_(uia_handler, {});
1097 }
1098
1099 void
1100 Client::registration(Callback<mtx::responses::Register> cb)
1101 {
1102 post<nlohmann::json, mtx::responses::Register>(
1103 "/client/v3/register", nlohmann::json::object(), std::move(cb), false);
1104 }
1105
1106 void
1107 Client::registration_token_validity(const std::string token,
1108 Callback<mtx::responses::RegistrationTokenValidity> cb)
1109 {
1110 const auto api_path = "/client/v1/register/m.login.registration_token/validity?" +
1111 mtx::client::utils::query_params({{"token", token}});
1112
1113 get<mtx::responses::RegistrationTokenValidity>(
1114 api_path,
1115 [cb = std::move(cb)](const mtx::responses::RegistrationTokenValidity &res,
1116 HeaderFields,
1117 RequestErr err) { cb(res, err); });
1118 }
1119
1120 void
1121 Client::register_email_request_token(const requests::RequestEmailToken &r,
1122 Callback<mtx::responses::RequestToken> cb)
1123 {
1124 post("/client/v3/register/email/requestToken", r, std::move(cb));
1125 }
1126
1127 void
1128 Client::register_username_available(const std::string &username,
1129 Callback<mtx::responses::Available> cb)
1130 {
1131 get<mtx::responses::Available>(
1132 "/client/v3/register/available?username=" + mtx::client::utils::url_encode(username),
1133 [cb = std::move(cb)](const mtx::responses::Available &res, HeaderFields, RequestErr err) {
1134 cb(res, err);
1135 });
1136 }
1137
1138 void
1139 Client::verify_email_request_token(const requests::RequestEmailToken &r,
1140 Callback<mtx::responses::RequestToken> cb)
1141 {
1142 post("/client/v3/account/password/email/requestToken", r, std::move(cb));
1143 }
1144
1145 void
1146 Client::register_phone_request_token(const requests::RequestMSISDNToken &r,
1147 Callback<mtx::responses::RequestToken> cb)
1148 {
1149 post("/client/v3/register/msisdn/requestToken", r, std::move(cb));
1150 }
1151 void
1152 Client::verify_phone_request_token(const requests::RequestMSISDNToken &r,
1153 Callback<mtx::responses::RequestToken> cb)
1154 {
1155 post("/client/v3/account/password/msisdn/requestToken", r, std::move(cb));
1156 }
1157
1158 void
1159 Client::validate_submit_token(const std::string &url,
1160 const requests::IdentitySubmitToken &r,
1161 Callback<mtx::responses::Success> cb)
1162 {
1163 // some dancing to send to an arbitrary, server provided url
1164 auto callback = prepare_callback<mtx::responses::Success>(
1165 [cb = std::move(cb)](const mtx::responses::Success &res, HeaderFields, RequestErr err) {
1166 cb(res, err);
1167 });
1168 p->client.post(
1169 url,
1170 nlohmann::json(r).dump(),
1171 "application/json",
1172 [callback = std::move(callback)](const coeurl::Request &r) {
1173 callback(r.response_headers(), r.response(), r.error_code(), r.response_code());
1174 },
1175 prepare_headers(false));
1176 }
1177
1178 void
1179 Client::send_state_event(const std::string &room_id,
1180 const std::string &event_type,
1181 const std::string &state_key,
1182 const nlohmann::json &payload,
1183 Callback<mtx::responses::EventId> callback)
1184 {
1185 const auto api_path = "/client/v3/rooms/" + mtx::client::utils::url_encode(room_id) +
1186 "/state/" + mtx::client::utils::url_encode(event_type) + "/" +
1187 mtx::client::utils::url_encode(state_key);
1188
1189 put<nlohmann::json, mtx::responses::EventId>(api_path, payload, std::move(callback));
1190 }
1191
1192 void
1193 Client::send_to_device(const std::string &event_type,
1194 const std::string &txn_id,
1195 const nlohmann::json &body,
1196 ErrCallback callback)
1197 {
1198 const auto api_path = "/client/v3/sendToDevice/" + mtx::client::utils::url_encode(event_type) +
1199 "/" + mtx::client::utils::url_encode(txn_id);
1200
1201 put<nlohmann::json>(api_path, body, std::move(callback));
1202 }
1203
1204 void
1205 Client::resolve_room_alias(const std::string &alias, Callback<mtx::responses::RoomId> cb)
1206 {
1207 const auto api_path = "/client/v3/directory/room/" + mtx::client::utils::url_encode(alias);
1208
1209 get<mtx::responses::RoomId>(api_path,
1210 [cb = std::move(cb)](const mtx::responses::RoomId &res,
1211 HeaderFields,
1212 RequestErr err) { cb(res, err); });
1213 }
1214 void
1215 Client::add_room_alias(const std::string &alias, const std::string &roomid, ErrCallback cb)
1216 {
1217 const auto api_path = "/client/v3/directory/room/" + mtx::client::utils::url_encode(alias);
1218 auto body = nlohmann::json::object();
1219 body["room_id"] = roomid;
1220 put<nlohmann::json>(api_path, body, std::move(cb));
1221 }
1222
1223 void
1224 Client::delete_room_alias(const std::string &alias, ErrCallback cb)
1225 {
1226 delete_("/client/v3/directory/room/" + mtx::client::utils::url_encode(alias), std::move(cb));
1227 }
1228
1229 void
1230 Client::list_room_aliases(const std::string &room_id, Callback<mtx::responses::Aliases> cb)
1231 {
1232 const auto api_path =
1233 "/client/v3/rooms/" + mtx::client::utils::url_encode(room_id) + "/aliases";
1234
1235 get<mtx::responses::Aliases>(api_path,
1236 [cb = std::move(cb)](const mtx::responses::Aliases &res,
1237 HeaderFields,
1238 RequestErr err) { cb(res, err); });
1239 }
1240
1241 void
1242 Client::get_room_visibility(const std::string &room_id,
1243 Callback<mtx::responses::PublicRoomVisibility> cb)
1244 {
1245 const auto api_path =
1246 "/client/v3/directory/list/room/" + mtx::client::utils::url_encode(room_id);
1247
1248 get<mtx::responses::PublicRoomVisibility>(
1249 api_path,
1250 [cb = std::move(cb)](const mtx::responses::PublicRoomVisibility &res,
1251 HeaderFields,
1252 RequestErr err) { cb(res, err); });
1253 }
1254
1255 void
1256 Client::put_room_visibility(const std::string &room_id,
1257 const mtx::requests::PublicRoomVisibility &req,
1258 ErrCallback cb)
1259 {
1260 const auto api_path =
1261 "/client/v3/directory/list/room/" + mtx::client::utils::url_encode(room_id);
1262 put<mtx::requests::PublicRoomVisibility>(api_path, req, std::move(cb));
1263 }
1264
1265 void
1266 Client::post_public_rooms(const mtx::requests::PublicRooms &req,
1267 Callback<mtx::responses::PublicRooms> cb,
1268 const std::string &server)
1269 {
1270 std::string api_path = "/client/v3/publicRooms";
1271
1272 if (!server.empty())
1273 api_path += "?" + mtx::client::utils::query_params({{"server", server}});
1274 post<mtx::requests::PublicRooms, mtx::responses::PublicRooms>(api_path, req, std::move(cb));
1275 }
1276
1277 void
1278 Client::get_public_rooms(Callback<mtx::responses::PublicRooms> cb,
1279 const std::string &server,
1280 size_t limit,
1281 const std::string &since)
1282 {
1283 std::string api_path = "/client/v3/publicRooms";
1284
1285 std::map<std::string, std::string> params;
1286 if (!server.empty())
1287 params["server"] = server;
1288 if (limit > 0)
1289 params["limit"] = std::to_string(limit);
1290 if (!since.empty())
1291 params["since"] = since;
1292
1293 if (!params.empty())
1294 api_path += "?" + mtx::client::utils::query_params(params);
1295
1296 get<mtx::responses::PublicRooms>(api_path,
1297 [cb = std::move(cb)](const mtx::responses::PublicRooms &res,
1298 HeaderFields,
1299 RequestErr err) { cb(res, err); });
1300 }
1301
1302 void
1303 Client::get_hierarchy(const std::string &room_id,
1304 Callback<mtx::responses::HierarchyRooms> cb,
1305 const std::string &from,
1306 size_t limit,
1307 size_t max_depth,
1308 bool suggested_only)
1309 {
1310 std::string api_path =
1311 "/client/v1/rooms/" + mtx::client::utils::url_encode(room_id) + "/hierarchy";
1312
1313 std::map<std::string, std::string> params;
1314 if (limit > 0)
1315 params["limit"] = std::to_string(limit);
1316 if (max_depth > 0)
1317 params["max_depth"] = std::to_string(max_depth);
1318 if (suggested_only)
1319 params["suggested_only"] = "true";
1320 if (!from.empty())
1321 params["from"] = from;
1322
1323 if (!params.empty())
1324 api_path += "?" + mtx::client::utils::query_params(params);
1325
1326 get<mtx::responses::HierarchyRooms>(
1327 api_path,
1328 [cb = std::move(cb)](
1329 const mtx::responses::HierarchyRooms &res, HeaderFields, RequestErr err) { cb(res, err); });
1330 }
1331
1332 void
1333 Client::get_summary(const std::string &room_id,
1334 Callback<mtx::responses::PublicRoomsChunk> cb,
1335 std::vector<std::string> via)
1336 {
1337 std::string query;
1338 if (!via.empty()) {
1339 query = "?via=" + mtx::client::utils::url_encode(via[0]);
1340 for (size_t i = 1; i < via.size(); i++) {
1341 query += "&via=" + mtx::client::utils::url_encode(via[i]);
1342 }
1343 }
1344 std::string api_path = "/client/unstable/im.nheko.summary/rooms/" +
1345 mtx::client::utils::url_encode(room_id) + "/summary" + query;
1346
1347 get<mtx::responses::PublicRoomsChunk>(
1348 api_path,
1349 [this, room_id, cb = std::move(cb)](
1350 const mtx::responses::PublicRoomsChunk &res, HeaderFields, RequestErr err) {
1351 if (!err || !(err->status_code == 404 || err->status_code == 400))
1352 cb(res, err);
1353 else if (!room_id.empty() && room_id[0] == '#')
1354 resolve_room_alias(
1355 room_id, [this, cb](const mtx::responses::RoomId &room, RequestErr err) {
1356 if (room.room_id.empty())
1357 cb({}, err);
1358 else
1359 get_hierarchy(
1360 room.room_id,
1361 [cb](const mtx::responses::HierarchyRooms &res, RequestErr err) {
1362 if (res.rooms.empty())
1363 cb({}, err);
1364 else
1365 cb(res.rooms.front(), err);
1366 },
1367 "",
1368 1);
1369 });
1370 else
1371 get_hierarchy(
1372 room_id,
1373 [cb](const mtx::responses::HierarchyRooms &res, RequestErr err) {
1374 if (res.rooms.empty())
1375 cb({}, err);
1376 else
1377 cb(res.rooms.front(), err);
1378 },
1379 "",
1380 1);
1381 });
1382 }
1383
1384 //
1385 // Device related endpoints
1386 //
1387
1388 void
1389 Client::query_devices(Callback<mtx::responses::QueryDevices> cb)
1390 {
1391 get<mtx::responses::QueryDevices>("/client/v3/devices",
1392 [cb = std::move(cb)](const mtx::responses::QueryDevices &res,
1393 HeaderFields,
1394 RequestErr err) { cb(res, err); });
1395 }
1396
1397 void
1398 Client::get_device(const std::string &device_id, Callback<mtx::responses::Device> cb)
1399 {
1400 get<mtx::responses::Device>("/client/v3/devices/" + mtx::client::utils::url_encode(device_id),
1401 [cb = std::move(cb)](const mtx::responses::Device &res,
1402 HeaderFields,
1403 RequestErr err) { cb(res, err); });
1404 }
1405
1406 void
1407 Client::set_device_name(const std::string &device_id,
1408 const std::string &display_name,
1409 ErrCallback callback)
1410 {
1411 mtx::requests::DeviceUpdate req;
1412 req.display_name = display_name;
1413
1414 put<mtx::requests::DeviceUpdate>(
1415 "/client/v3/devices/" + mtx::client::utils::url_encode(device_id), req, std::move(callback));
1416 }
1417
1418 void
1419 Client::delete_device(const std::string &device_id, UIAHandler uia_handler, ErrCallback cb)
1420 {
1421 nlohmann::json req;
1422 req["devices"] = {device_id};
1423
1424 uia_handler.next_ = [this, req, cb = std::move(cb)](const UIAHandler &h,
1425 const nlohmann::json &auth) {
1426 auto request = req;
1427 if (!auth.empty())
1428 request["auth"] = auth;
1429
1430 post<nlohmann::json, mtx::responses::Empty>(
1431 "/client/v3/delete_devices", request, [cb, h](auto &, RequestErr e) {
1432 if (e && e->status_code == 401 && !e->matrix_error.unauthorized.flows.empty())
1433 h.prompt(h, e->matrix_error.unauthorized);
1434 else
1435 cb(e);
1436 });
1437 };
1438
1439 uia_handler.next_(uia_handler, {});
1440 }
1441
1442 void
1443 Client::delete_devices(const std::vector<std::string> &device_ids,
1444 UIAHandler uia_handler,
1445 ErrCallback cb)
1446 {
1447 nlohmann::json req;
1448 req["devices"] = device_ids;
1449
1450 uia_handler.next_ = [this, req = std::move(req), cb = std::move(cb)](
1451 const UIAHandler &h, const nlohmann::json &auth) {
1452 auto request = req;
1453 if (!auth.empty())
1454 request["auth"] = auth;
1455
1456 post<nlohmann::json, mtx::responses::Empty>(
1457 "/client/v3/delete_devices", request, [cb, h](auto &, RequestErr e) {
1458 if (e && e->status_code == 401 && !e->matrix_error.unauthorized.flows.empty())
1459 h.prompt(h, e->matrix_error.unauthorized);
1460 else
1461 cb(e);
1462 });
1463 };
1464
1465 uia_handler.next_(uia_handler, {});
1466 }
1467
1468 //
1469 // Encryption related endpoints
1470 //
1471
1472 void
1473 Client::upload_keys(const mtx::requests::UploadKeys &req,
1474 Callback<mtx::responses::UploadKeys> callback)
1475 {
1476 post<mtx::requests::UploadKeys, mtx::responses::UploadKeys>(
1477 "/client/v3/keys/upload", req, std::move(callback));
1478 }
1479
1480 void
1481 Client::keys_signatures_upload(const mtx::requests::KeySignaturesUpload &req,
1482 Callback<mtx::responses::KeySignaturesUpload> cb)
1483 {
1484 post<mtx::requests::KeySignaturesUpload, mtx::responses::KeySignaturesUpload>(
1485 "/client/v3/keys/signatures/upload", req, std::move(cb));
1486 }
1487
1488 void
1489 Client::device_signing_upload(const mtx::requests::DeviceSigningUpload &deviceKeys,
1490 UIAHandler uia_handler,
1491 ErrCallback cb)
1492 {
1493 nlohmann::json req = deviceKeys;
1494
1495 uia_handler.next_ = [this, req = std::move(req), cb = std::move(cb)](
1496 const UIAHandler &h, const nlohmann::json &auth) {
1497 auto request = req;
1498 if (!auth.empty())
1499 request["auth"] = auth;
1500
1501 post<nlohmann::json, mtx::responses::Empty>(
1502 "/client/v3/keys/device_signing/upload", request, [cb, h](auto &, RequestErr e) {
1503 if (e && e->status_code == 401 && !e->matrix_error.unauthorized.flows.empty())
1504 h.prompt(h, e->matrix_error.unauthorized);
1505 else
1506 cb(e);
1507 });
1508 };
1509
1510 uia_handler.next_(uia_handler, {});
1511 }
1512
1513 void
1514 Client::query_keys(const mtx::requests::QueryKeys &req,
1515 Callback<mtx::responses::QueryKeys> callback)
1516 {
1517 post<mtx::requests::QueryKeys, mtx::responses::QueryKeys>(
1518 "/client/v3/keys/query", req, std::move(callback));
1519 }
1520
1521 //! Claims one-time keys for use in pre-key messages.
1522 void
1523 Client::claim_keys(const mtx::requests::ClaimKeys &req, Callback<mtx::responses::ClaimKeys> cb)
1524 {
1525 post<mtx::requests::ClaimKeys, mtx::responses::ClaimKeys>(
1526 "/client/v3/keys/claim", req, std::move(cb));
1527 }
1528
1529 void
1530 Client::key_changes(const std::string &from,
1531 const std::string &to,
1532 Callback<mtx::responses::KeyChanges> callback)
1533 {
1534 std::map<std::string, std::string> params;
1535
1536 if (!from.empty())
1537 params.emplace("from", from);
1538
1539 if (!to.empty())
1540 params.emplace("to", to);
1541
1542 get<mtx::responses::KeyChanges>(
1543 "/client/v3/keys/changes?" + mtx::client::utils::query_params(params),
1544 [callback = std::move(callback)](const mtx::responses::KeyChanges &res,
1545 HeaderFields,
1546 RequestErr err) { callback(res, err); });
1547 }
1548
1549 //
1550 // Key backup endpoints
1551 //
1552 void
1553 Client::backup_version(Callback<mtx::responses::backup::BackupVersion> cb)
1554 {
1555 get<mtx::responses::backup::BackupVersion>(
1556 "/client/v3/room_keys/version",
1557 [cb = std::move(cb)](const mtx::responses::backup::BackupVersion &res,
1558 HeaderFields,
1559 RequestErr err) { cb(res, err); });
1560 }
1561 void
1562 Client::backup_version(const std::string &version,
1563 Callback<mtx::responses::backup::BackupVersion> cb)
1564 {
1565 get<mtx::responses::backup::BackupVersion>(
1566 "/client/v3/room_keys/version/" + mtx::client::utils::url_encode(version),
1567 [cb = std::move(cb)](const mtx::responses::backup::BackupVersion &res,
1568 HeaderFields,
1569 RequestErr err) { cb(res, err); });
1570 }
1571
1572 void
1573 Client::update_backup_version(const std::string &version,
1574 const mtx::responses::backup::BackupVersion &data,
1575 ErrCallback cb)
1576 {
1577 put<mtx::responses::backup::BackupVersion>("/client/v3/room_keys/version/" +
1578 mtx::client::utils::url_encode(version),
1579 data,
1580 std::move(cb));
1581 }
1582
1583 void
1584 Client::post_backup_version(const std::string &algorithm,
1585 const std::string &auth_data,
1586 Callback<mtx::responses::Version> cb)
1587 {
1588 nlohmann::json req = {{"algorithm", algorithm},
1589 {"auth_data", nlohmann::json::parse(auth_data)}};
1590 post<nlohmann::json, mtx::responses::Version>(
1591 "/client/v3/room_keys/version", req, std::move(cb));
1592 }
1593 void
1594 Client::room_keys(const std::string &version, Callback<mtx::responses::backup::KeysBackup> cb)
1595 {
1596 get<mtx::responses::backup::KeysBackup>(
1597 "/client/v3/room_keys/keys?" + mtx::client::utils::query_params({{"version", version}}),
1598 [cb = std::move(cb)](const mtx::responses::backup::KeysBackup &res,
1599 HeaderFields,
1600 RequestErr err) { cb(res, err); });
1601 }
1602 void
1603 Client::room_keys(const std::string &version,
1604 const std::string &room_id,
1605 Callback<mtx::responses::backup::RoomKeysBackup> cb)
1606 {
1607 get<mtx::responses::backup::RoomKeysBackup>(
1608 "/client/v3/room_keys/keys/" + mtx::client::utils::url_encode(room_id) + "?" +
1609 mtx::client::utils::query_params({{"version", version}}),
1610 [cb = std::move(cb)](const mtx::responses::backup::RoomKeysBackup &res,
1611 HeaderFields,
1612 RequestErr err) { cb(res, err); });
1613 }
1614 void
1615 Client::room_keys(const std::string &version,
1616 const std::string &room_id,
1617 const std::string &session_id,
1618 Callback<mtx::responses::backup::SessionBackup> cb)
1619 {
1620 get<mtx::responses::backup::SessionBackup>(
1621 "/client/v3/room_keys/keys/" + mtx::client::utils::url_encode(room_id) + "/" +
1622 mtx::client::utils::url_encode(session_id) + "?" +
1623 mtx::client::utils::query_params({{"version", version}}),
1624 [cb = std::move(cb)](const mtx::responses::backup::SessionBackup &res,
1625 HeaderFields,
1626 RequestErr err) { cb(res, err); });
1627 }
1628
1629 void
1630 Client::put_room_keys(const std::string &version,
1631 const mtx::responses::backup::KeysBackup &keys,
1632 ErrCallback cb)
1633 {
1634 put("/client/v3/room_keys/keys?" + mtx::client::utils::query_params({{"version", version}}),
1635 keys,
1636 std::move(cb));
1637 }
1638 void
1639 Client::put_room_keys(const std::string &version,
1640 const std::string &room_id,
1641 const mtx::responses::backup::RoomKeysBackup &keys,
1642 ErrCallback cb)
1643 {
1644 put("/client/v3/room_keys/keys/" + mtx::client::utils::url_encode(room_id) + "?" +
1645 mtx::client::utils::query_params({{"version", version}}),
1646 keys,
1647 std::move(cb));
1648 }
1649 void
1650 Client::put_room_keys(const std::string &version,
1651 const std::string &room_id,
1652 const std::string &session_id,
1653 const mtx::responses::backup::SessionBackup &keys,
1654 ErrCallback cb)
1655 {
1656 put("/client/v3/room_keys/keys/" + mtx::client::utils::url_encode(room_id) + "/" +
1657 mtx::client::utils::url_encode(session_id) + "?" +
1658 mtx::client::utils::query_params({{"version", version}}),
1659 keys,
1660 std::move(cb));
1661 }
1662
1663 //! Retrieve a specific secret
1664 void
1665 Client::secret_storage_secret(std::string_view secret_id, Callback<mtx::secret_storage::Secret> cb)
1666 {
1667 get<mtx::secret_storage::Secret>(
1668 "/client/v3/user/" + mtx::client::utils::url_encode(user_id_.to_string()) + "/account_data/" +
1669 mtx::client::utils::url_encode(secret_id),
1670 [cb = std::move(cb)](const mtx::secret_storage::Secret &res, HeaderFields, RequestErr err) {
1671 cb(res, err);
1672 });
1673 }
1674 //! Retrieve information about a key
1675 void
1676 Client::secret_storage_key(std::string_view key_id,
1677 Callback<mtx::secret_storage::AesHmacSha2KeyDescription> cb)
1678 {
1679 get<mtx::secret_storage::AesHmacSha2KeyDescription>(
1680 "/client/v3/user/" + mtx::client::utils::url_encode(user_id_.to_string()) +
1681 "/account_data/m.secret_storage.key." + mtx::client::utils::url_encode(key_id),
1682 [cb = std::move(cb)](const mtx::secret_storage::AesHmacSha2KeyDescription &res,
1683 HeaderFields,
1684 RequestErr err) { cb(res, err); });
1685 }
1686
1687 //! Upload a specific secret
1688 void
1689 Client::upload_secret_storage_secret(std::string_view secret_id,
1690 const mtx::secret_storage::Secret &secret,
1691 ErrCallback cb)
1692 {
1693 put("/client/v3/user/" + mtx::client::utils::url_encode(user_id_.to_string()) +
1694 "/account_data/" + mtx::client::utils::url_encode(secret_id),
1695 secret,
1696 std::move(cb));
1697 }
1698
1699 //! Upload information about a key
1700 void
1701 Client::upload_secret_storage_key(std::string_view key_id,
1702 const mtx::secret_storage::AesHmacSha2KeyDescription &desc,
1703 ErrCallback cb)
1704 {
1705 put("/client/v3/user/" + mtx::client::utils::url_encode(user_id_.to_string()) +
1706 "/account_data/m.secret_storage.key." + mtx::client::utils::url_encode(key_id),
1707 desc,
1708 std::move(cb));
1709 }
1710
1711 void
1712 Client::set_secret_storage_default_key(std::string_view key_id, ErrCallback cb)
1713 {
1714 nlohmann::json key = {{"key", key_id}};
1715 put("/client/v3/user/" + mtx::client::utils::url_encode(user_id_.to_string()) +
1716 "/account_data/m.secret_storage.default_key",
1717 key,
1718 std::move(cb));
1719 }
1720
1721 void
1722 Client::enable_encryption(const std::string &room, Callback<mtx::responses::EventId> callback)
1723 {
1724 using namespace mtx::events;
1725 state::Encryption event;
1726
1727 send_state_event<state::Encryption>(room, "", event, std::move(callback));
1728 }
1729
1730 void
1731 Client::get_turn_server(Callback<mtx::responses::TurnServer> cb)
1732 {
1733 get<mtx::responses::TurnServer>("/client/v3/voip/turnServer",
1734 [cb = std::move(cb)](const mtx::responses::TurnServer &res,
1735 HeaderFields,
1736 RequestErr err) { cb(res, err); });
1737 }
1738
1739 void
1740 Client::set_pusher(const mtx::requests::SetPusher &req, Callback<mtx::responses::Empty> cb)
1741 {
1742 post<mtx::requests::SetPusher, mtx::responses::Empty>(
1743 "/client/v3/pushers/set", req, std::move(cb));
1744 }
1745
1746 void
1747 Client::search_user_directory(const std::string &search_term,
1748 Callback<mtx::responses::Users> callback,
1749 int limit)
1750 {
1751 nlohmann::json req = {{"search_term", search_term}};
1752 if (limit >= 0)
1753 req["limit"] = limit;
1754 post<nlohmann::json, mtx::responses::Users>(
1755 "/client/v3/user_directory/search", req, std::move(callback));
1756 }
1757
1758 // Template instantiations for the various send functions
1759
1760 #define MTXCLIENT_SEND_STATE_EVENT(Content) \
1761 template void mtx::http::Client::send_state_event<mtx::events::Content>( \
1762 const std::string &, \
1763 const std::string &state_key, \
1764 const mtx::events::Content &, \
1765 Callback<mtx::responses::EventId> cb); \
1766 template void mtx::http::Client::send_state_event<mtx::events::Content>( \
1767 const std::string &, const mtx::events::Content &, Callback<mtx::responses::EventId> cb); \
1768 template void mtx::http::Client::get_state_event<mtx::events::Content>( \
1769 const std::string &room_id, \
1770 const std::string &type, \
1771 const std::string &state_key, \
1772 Callback<mtx::events::Content> cb); \
1773 template void mtx::http::Client::get_state_event<mtx::events::Content>( \
1774 const std::string &room_id, \
1775 const std::string &state_key, \
1776 Callback<mtx::events::Content> cb);
1777
1778 MTXCLIENT_SEND_STATE_EVENT(state::Aliases)
1779 MTXCLIENT_SEND_STATE_EVENT(state::Avatar)
1780 MTXCLIENT_SEND_STATE_EVENT(state::CanonicalAlias)
1781 MTXCLIENT_SEND_STATE_EVENT(state::Create)
1782 MTXCLIENT_SEND_STATE_EVENT(state::Encryption)
1783 MTXCLIENT_SEND_STATE_EVENT(state::GuestAccess)
1784 MTXCLIENT_SEND_STATE_EVENT(state::HistoryVisibility)
1785 MTXCLIENT_SEND_STATE_EVENT(state::JoinRules)
1786 MTXCLIENT_SEND_STATE_EVENT(state::Member)
1787 MTXCLIENT_SEND_STATE_EVENT(state::Name)
1788 MTXCLIENT_SEND_STATE_EVENT(state::PinnedEvents)
1789 MTXCLIENT_SEND_STATE_EVENT(state::PowerLevels)
1790 MTXCLIENT_SEND_STATE_EVENT(state::Tombstone)
1791 MTXCLIENT_SEND_STATE_EVENT(state::Topic)
1792 MTXCLIENT_SEND_STATE_EVENT(state::Widget)
1793 MTXCLIENT_SEND_STATE_EVENT(state::policy_rule::UserRule)
1794 MTXCLIENT_SEND_STATE_EVENT(state::policy_rule::RoomRule)
1795 MTXCLIENT_SEND_STATE_EVENT(state::policy_rule::ServerRule)
1796 MTXCLIENT_SEND_STATE_EVENT(state::space::Child)
1797 MTXCLIENT_SEND_STATE_EVENT(state::space::Parent)
1798 MTXCLIENT_SEND_STATE_EVENT(msc2545::ImagePack)
1799
1800 #define MTXCLIENT_SEND_ROOM_MESSAGE(Content) \
1801 template void mtx::http::Client::send_room_message<Content>( \
1802 const std::string &, \
1803 const std::string &, \
1804 const Content &, \
1805 Callback<mtx::responses::EventId> cb); \
1806 template void mtx::http::Client::send_room_message<Content>( \
1807 const std::string &, const Content &, Callback<mtx::responses::EventId> cb);
1808
1809 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::Encrypted)
1810 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::StickerImage)
1811 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::Reaction)
1812 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::Audio)
1813 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::Emote)
1814 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::File)
1815 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::Image)
1816 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::Location)
1817 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::Notice)
1818 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::Text)
1819 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::Unknown)
1820 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::Video)
1821 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::ElementEffect)
1822 // MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::KeyVerificationRequest)
1823 // MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::KeyVerificationStart)
1824 // MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::KeyVerificationReady)
1825 // MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::KeyVerificationDone)
1826 // MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::KeyVerificationAccept)
1827 // MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::KeyVerificationCancel)
1828 // MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::KeyVerificationKey)
1829 // MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::msg::KeyVerificationMac)
1830 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::voip::CallInvite)
1831 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::voip::CallCandidates)
1832 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::voip::CallAnswer)
1833 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::voip::CallHangUp)
1834 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::voip::CallSelectAnswer)
1835 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::voip::CallReject)
1836 MTXCLIENT_SEND_ROOM_MESSAGE(mtx::events::voip::CallNegotiate)
1837
1838 #define MTXCLIENT_SEND_TO_DEVICE(Content) \
1839 template void mtx::http::Client::send_to_device<Content>( \
1840 const std::string &txid, \
1841 const std::map<mtx::identifiers::User, std::map<std::string, Content>> &messages, \
1842 ErrCallback callback);
1843
1844 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::RoomKey)
1845 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::ForwardedRoomKey)
1846 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::KeyRequest)
1847 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::OlmEncrypted)
1848 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::Encrypted)
1849 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::Dummy)
1850 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::KeyVerificationRequest)
1851 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::KeyVerificationStart)
1852 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::KeyVerificationReady)
1853 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::KeyVerificationDone)
1854 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::KeyVerificationAccept)
1855 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::KeyVerificationCancel)
1856 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::KeyVerificationKey)
1857 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::KeyVerificationMac)
1858 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::SecretSend)
1859 MTXCLIENT_SEND_TO_DEVICE(mtx::events::msg::SecretRequest)
1860
1861 #define MTXCLIENT_ACCOUNT_DATA(Payload) \
1862 template void mtx::http::Client::put_room_account_data<Payload>(const std::string &room_id, \
1863 const std::string &type, \
1864 const Payload &payload, \
1865 ErrCallback cb); \
1866 template void mtx::http::Client::put_room_account_data<Payload>( \
1867 const std::string &room_id, const Payload &payload, ErrCallback cb); \
1868 template void mtx::http::Client::put_account_data<Payload>( \
1869 const std::string &type, const Payload &payload, ErrCallback cb); \
1870 template void mtx::http::Client::put_account_data<Payload>(const Payload &payload, \
1871 ErrCallback cb); \
1872 template void mtx::http::Client::get_room_account_data<Payload>( \
1873 const std::string &room_id, const std::string &type, Callback<Payload> payload); \
1874 template void mtx::http::Client::get_room_account_data<Payload>(const std::string &room_id, \
1875 Callback<Payload> cb); \
1876 template void mtx::http::Client::get_account_data<Payload>(const std::string &type, \
1877 Callback<Payload> payload); \
1878 template void mtx::http::Client::get_account_data<Payload>(Callback<Payload> cb);
1879
1880 MTXCLIENT_ACCOUNT_DATA(mtx::events::msc2545::ImagePack)
1881 MTXCLIENT_ACCOUNT_DATA(mtx::events::msc2545::ImagePackRooms)
1882 MTXCLIENT_ACCOUNT_DATA(mtx::events::account_data::nheko_extensions::HiddenEvents)
1883 MTXCLIENT_ACCOUNT_DATA(mtx::events::account_data::nheko_extensions::InvitePermissions)
1884 MTXCLIENT_ACCOUNT_DATA(mtx::events::account_data::nheko_extensions::EventExpiry)
1885 MTXCLIENT_ACCOUNT_DATA(mtx::events::account_data::Tags)
1886 MTXCLIENT_ACCOUNT_DATA(mtx::events::account_data::Direct)
1887 MTXCLIENT_ACCOUNT_DATA(mtx::events::account_data::IgnoredUsers)