Line data Source code
1 : import 'dart:convert';
2 : import 'dart:typed_data';
3 :
4 : import 'package:http/http.dart';
5 :
6 : import 'package:matrix/matrix_api_lite/generated/fixed_model.dart';
7 : import 'package:matrix/matrix_api_lite/generated/internal.dart';
8 : import 'package:matrix/matrix_api_lite/generated/model.dart';
9 : import 'package:matrix/matrix_api_lite/model/auth/authentication_data.dart';
10 : import 'package:matrix/matrix_api_lite/model/auth/authentication_identifier.dart';
11 : import 'package:matrix/matrix_api_lite/model/matrix_event.dart';
12 : import 'package:matrix/matrix_api_lite/model/matrix_keys.dart';
13 : import 'package:matrix/matrix_api_lite/model/sync_update.dart';
14 :
15 : // ignore_for_file: provide_deprecation_message
16 :
17 : class Api {
18 : Client httpClient;
19 : Uri? baseUri;
20 : String? bearerToken;
21 43 : Api({Client? httpClient, this.baseUri, this.bearerToken})
22 0 : : httpClient = httpClient ?? Client();
23 1 : Never unexpectedResponse(BaseResponse response, Uint8List body) {
24 1 : throw Exception('http error response');
25 : }
26 :
27 0 : Never bodySizeExceeded(int expected, int actual) {
28 0 : throw Exception('body size $actual exceeded $expected');
29 : }
30 :
31 : /// Gets discovery information about the domain. The file may include
32 : /// additional keys, which MUST follow the Java package naming convention,
33 : /// e.g. `com.example.myapp.property`. This ensures property names are
34 : /// suitably namespaced for each application and reduces the risk of
35 : /// clashes.
36 : ///
37 : /// Note that this endpoint is not necessarily handled by the homeserver,
38 : /// but by another webserver, to be used for discovering the homeserver URL.
39 0 : Future<DiscoveryInformation> getWellknown() async {
40 0 : final requestUri = Uri(path: '.well-known/matrix/client');
41 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
42 0 : final response = await httpClient.send(request);
43 0 : final responseBody = await response.stream.toBytes();
44 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
45 0 : final responseString = utf8.decode(responseBody);
46 0 : final json = jsonDecode(responseString);
47 0 : return DiscoveryInformation.fromJson(json as Map<String, Object?>);
48 : }
49 :
50 : /// Gets server admin contact and support page of the domain.
51 : ///
52 : /// Like the [well-known discovery URI](https://spec.matrix.org/unstable/client-server-api/#well-known-uri),
53 : /// this should be accessed with the hostname of the homeserver by making a
54 : /// GET request to `https://hostname/.well-known/matrix/support`.
55 : ///
56 : /// Note that this endpoint is not necessarily handled by the homeserver.
57 : /// It may be served by another webserver, used for discovering support
58 : /// information for the homeserver.
59 0 : Future<GetWellknownSupportResponse> getWellknownSupport() async {
60 0 : final requestUri = Uri(path: '.well-known/matrix/support');
61 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
62 0 : final response = await httpClient.send(request);
63 0 : final responseBody = await response.stream.toBytes();
64 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
65 0 : final responseString = utf8.decode(responseBody);
66 0 : final json = jsonDecode(responseString);
67 0 : return GetWellknownSupportResponse.fromJson(json as Map<String, Object?>);
68 : }
69 :
70 : /// This API asks the homeserver to call the
71 : /// [`/_matrix/app/v1/ping`](https://spec.matrix.org/unstable/application-service-api/#post_matrixappv1ping) endpoint on the
72 : /// application service to ensure that the homeserver can communicate
73 : /// with the application service.
74 : ///
75 : /// This API requires the use of an application service access token (`as_token`)
76 : /// instead of a typical client's access token. This API cannot be invoked by
77 : /// users who are not identified as application services. Additionally, the
78 : /// appservice ID in the path must be the same as the appservice whose `as_token`
79 : /// is being used.
80 : ///
81 : /// [appserviceId] The appservice ID of the appservice to ping. This must be the same
82 : /// as the appservice whose `as_token` is being used to authenticate the
83 : /// request.
84 : ///
85 : /// [transactionId] An optional transaction ID that is passed through to the `/_matrix/app/v1/ping` call.
86 : ///
87 : /// returns `duration_ms`:
88 : /// The duration in milliseconds that the
89 : /// [`/_matrix/app/v1/ping`](https://spec.matrix.org/unstable/application-service-api/#post_matrixappv1ping)
90 : /// request took from the homeserver's point of view.
91 0 : Future<int> pingAppservice(
92 : String appserviceId, {
93 : String? transactionId,
94 : }) async {
95 0 : final requestUri = Uri(
96 : path:
97 0 : '_matrix/client/v1/appservice/${Uri.encodeComponent(appserviceId)}/ping',
98 : );
99 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
100 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
101 0 : request.headers['content-type'] = 'application/json';
102 0 : request.bodyBytes = utf8.encode(
103 0 : jsonEncode({
104 0 : if (transactionId != null) 'transaction_id': transactionId,
105 : }),
106 : );
107 0 : final response = await httpClient.send(request);
108 0 : final responseBody = await response.stream.toBytes();
109 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
110 0 : final responseString = utf8.decode(responseBody);
111 0 : final json = jsonDecode(responseString);
112 0 : return json['duration_ms'] as int;
113 : }
114 :
115 : /// Optional endpoint - the server is not required to implement this endpoint if it does not
116 : /// intend to use or support this functionality.
117 : ///
118 : /// This API endpoint uses the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api).
119 : ///
120 : /// An already-authenticated client can call this endpoint to generate a single-use, time-limited,
121 : /// token for an unauthenticated client to log in with, becoming logged in as the same user which
122 : /// called this endpoint. The unauthenticated client uses the generated token in a `m.login.token`
123 : /// login flow with the homeserver.
124 : ///
125 : /// Clients, both authenticated and unauthenticated, might wish to hide user interface which exposes
126 : /// this feature if the server is not offering it. Authenticated clients can check for support on
127 : /// a per-user basis with the [`m.get_login_token`](https://spec.matrix.org/unstable/client-server-api/#mget_login_token-capability) capability,
128 : /// while unauthenticated clients can detect server support by looking for an `m.login.token` login
129 : /// flow with `get_login_token: true` on [`GET /login`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3login).
130 : ///
131 : /// In v1.7 of the specification, transmission of the generated token to an unauthenticated client is
132 : /// left as an implementation detail. Future MSCs such as [MSC3906](https://github.com/matrix-org/matrix-spec-proposals/pull/3906)
133 : /// might standardise a way to transmit the token between clients.
134 : ///
135 : /// The generated token MUST only be valid for a single login, enforced by the server. Clients which
136 : /// intend to log in multiple devices must generate a token for each.
137 : ///
138 : /// With other User-Interactive Authentication (UIA)-supporting endpoints, servers sometimes do not re-prompt
139 : /// for verification if the session recently passed UIA. For this endpoint, servers MUST always re-prompt
140 : /// the user for verification to ensure explicit consent is gained for each additional client.
141 : ///
142 : /// Servers are encouraged to apply stricter than normal rate limiting to this endpoint, such as maximum
143 : /// of 1 request per minute.
144 : ///
145 : /// [auth] Additional authentication information for the user-interactive authentication API.
146 0 : Future<GenerateLoginTokenResponse> generateLoginToken({
147 : AuthenticationData? auth,
148 : }) async {
149 0 : final requestUri = Uri(path: '_matrix/client/v1/login/get_token');
150 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
151 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
152 0 : request.headers['content-type'] = 'application/json';
153 0 : request.bodyBytes = utf8.encode(
154 0 : jsonEncode({
155 0 : if (auth != null) 'auth': auth.toJson(),
156 : }),
157 : );
158 0 : final response = await httpClient.send(request);
159 0 : final responseBody = await response.stream.toBytes();
160 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
161 0 : final responseString = utf8.decode(responseBody);
162 0 : final json = jsonDecode(responseString);
163 0 : return GenerateLoginTokenResponse.fromJson(json as Map<String, Object?>);
164 : }
165 :
166 : /// This endpoint allows clients to retrieve the configuration of the content
167 : /// repository, such as upload limitations.
168 : /// Clients SHOULD use this as a guide when using content repository endpoints.
169 : /// All values are intentionally left optional. Clients SHOULD follow
170 : /// the advice given in the field description when the field is not available.
171 : ///
172 : /// {{% boxes/note %}}
173 : /// Both clients and server administrators should be aware that proxies
174 : /// between the client and the server may affect the apparent behaviour of content
175 : /// repository APIs, for example, proxies may enforce a lower upload size limit
176 : /// than is advertised by the server on this endpoint.
177 : /// {{% /boxes/note %}}
178 4 : Future<MediaConfig> getConfigAuthed() async {
179 4 : final requestUri = Uri(path: '_matrix/client/v1/media/config');
180 12 : final request = Request('GET', baseUri!.resolveUri(requestUri));
181 16 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
182 8 : final response = await httpClient.send(request);
183 8 : final responseBody = await response.stream.toBytes();
184 8 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
185 4 : final responseString = utf8.decode(responseBody);
186 4 : final json = jsonDecode(responseString);
187 4 : return MediaConfig.fromJson(json as Map<String, Object?>);
188 : }
189 :
190 : /// {{% boxes/note %}}
191 : /// Clients SHOULD NOT generate or use URLs which supply the access token in
192 : /// the query string. These URLs may be copied by users verbatim and provided
193 : /// in a chat message to another user, disclosing the sender's access token.
194 : /// {{% /boxes/note %}}
195 : ///
196 : /// Clients MAY be redirected using the 307/308 responses below to download
197 : /// the request object. This is typical when the homeserver uses a Content
198 : /// Delivery Network (CDN).
199 : ///
200 : /// [serverName] The server name from the `mxc://` URI (the authority component).
201 : ///
202 : ///
203 : /// [mediaId] The media ID from the `mxc://` URI (the path component).
204 : ///
205 : ///
206 : /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
207 : /// start receiving data, in the case that the content has not yet been
208 : /// uploaded. The default value is 20000 (20 seconds). The content
209 : /// repository SHOULD impose a maximum value for this parameter. The
210 : /// content repository MAY respond before the timeout.
211 : ///
212 0 : Future<FileResponse> getContentAuthed(
213 : String serverName,
214 : String mediaId, {
215 : int? timeoutMs,
216 : }) async {
217 0 : final requestUri = Uri(
218 : path:
219 0 : '_matrix/client/v1/media/download/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}',
220 0 : queryParameters: {
221 0 : if (timeoutMs != null) 'timeout_ms': timeoutMs.toString(),
222 : },
223 : );
224 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
225 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
226 0 : final response = await httpClient.send(request);
227 0 : final responseBody = await response.stream.toBytes();
228 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
229 0 : return FileResponse(
230 0 : contentType: response.headers['content-type'],
231 : data: responseBody,
232 : );
233 : }
234 :
235 : /// This will download content from the content repository (same as
236 : /// the previous endpoint) but replaces the target file name with the one
237 : /// provided by the caller.
238 : ///
239 : /// {{% boxes/note %}}
240 : /// Clients SHOULD NOT generate or use URLs which supply the access token in
241 : /// the query string. These URLs may be copied by users verbatim and provided
242 : /// in a chat message to another user, disclosing the sender's access token.
243 : /// {{% /boxes/note %}}
244 : ///
245 : /// Clients MAY be redirected using the 307/308 responses below to download
246 : /// the request object. This is typical when the homeserver uses a Content
247 : /// Delivery Network (CDN).
248 : ///
249 : /// [serverName] The server name from the `mxc://` URI (the authority component).
250 : ///
251 : ///
252 : /// [mediaId] The media ID from the `mxc://` URI (the path component).
253 : ///
254 : ///
255 : /// [fileName] A filename to give in the `Content-Disposition` header.
256 : ///
257 : /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
258 : /// start receiving data, in the case that the content has not yet been
259 : /// uploaded. The default value is 20000 (20 seconds). The content
260 : /// repository SHOULD impose a maximum value for this parameter. The
261 : /// content repository MAY respond before the timeout.
262 : ///
263 0 : Future<FileResponse> getContentOverrideNameAuthed(
264 : String serverName,
265 : String mediaId,
266 : String fileName, {
267 : int? timeoutMs,
268 : }) async {
269 0 : final requestUri = Uri(
270 : path:
271 0 : '_matrix/client/v1/media/download/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}/${Uri.encodeComponent(fileName)}',
272 0 : queryParameters: {
273 0 : if (timeoutMs != null) 'timeout_ms': timeoutMs.toString(),
274 : },
275 : );
276 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
277 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
278 0 : final response = await httpClient.send(request);
279 0 : final responseBody = await response.stream.toBytes();
280 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
281 0 : return FileResponse(
282 0 : contentType: response.headers['content-type'],
283 : data: responseBody,
284 : );
285 : }
286 :
287 : /// Get information about a URL for the client. Typically this is called when a
288 : /// client sees a URL in a message and wants to render a preview for the user.
289 : ///
290 : /// {{% boxes/note %}}
291 : /// Clients should consider avoiding this endpoint for URLs posted in encrypted
292 : /// rooms. Encrypted rooms often contain more sensitive information the users
293 : /// do not want to share with the homeserver, and this can mean that the URLs
294 : /// being shared should also not be shared with the homeserver.
295 : /// {{% /boxes/note %}}
296 : ///
297 : /// [url] The URL to get a preview of.
298 : ///
299 : /// [ts] The preferred point in time to return a preview for. The server may
300 : /// return a newer version if it does not have the requested version
301 : /// available.
302 0 : Future<PreviewForUrl> getUrlPreviewAuthed(Uri url, {int? ts}) async {
303 0 : final requestUri = Uri(
304 : path: '_matrix/client/v1/media/preview_url',
305 0 : queryParameters: {
306 0 : 'url': url.toString(),
307 0 : if (ts != null) 'ts': ts.toString(),
308 : },
309 : );
310 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
311 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
312 0 : final response = await httpClient.send(request);
313 0 : final responseBody = await response.stream.toBytes();
314 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
315 0 : final responseString = utf8.decode(responseBody);
316 0 : final json = jsonDecode(responseString);
317 0 : return PreviewForUrl.fromJson(json as Map<String, Object?>);
318 : }
319 :
320 : /// Download a thumbnail of content from the content repository.
321 : /// See the [Thumbnails](https://spec.matrix.org/unstable/client-server-api/#thumbnails) section for more information.
322 : ///
323 : /// {{% boxes/note %}}
324 : /// Clients SHOULD NOT generate or use URLs which supply the access token in
325 : /// the query string. These URLs may be copied by users verbatim and provided
326 : /// in a chat message to another user, disclosing the sender's access token.
327 : /// {{% /boxes/note %}}
328 : ///
329 : /// Clients MAY be redirected using the 307/308 responses below to download
330 : /// the request object. This is typical when the homeserver uses a Content
331 : /// Delivery Network (CDN).
332 : ///
333 : /// [serverName] The server name from the `mxc://` URI (the authority component).
334 : ///
335 : ///
336 : /// [mediaId] The media ID from the `mxc://` URI (the path component).
337 : ///
338 : ///
339 : /// [width] The *desired* width of the thumbnail. The actual thumbnail may be
340 : /// larger than the size specified.
341 : ///
342 : /// [height] The *desired* height of the thumbnail. The actual thumbnail may be
343 : /// larger than the size specified.
344 : ///
345 : /// [method] The desired resizing method. See the [Thumbnails](https://spec.matrix.org/unstable/client-server-api/#thumbnails)
346 : /// section for more information.
347 : ///
348 : /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
349 : /// start receiving data, in the case that the content has not yet been
350 : /// uploaded. The default value is 20000 (20 seconds). The content
351 : /// repository SHOULD impose a maximum value for this parameter. The
352 : /// content repository MAY respond before the timeout.
353 : ///
354 : ///
355 : /// [animated] Indicates preference for an animated thumbnail from the server, if possible. Animated
356 : /// thumbnails typically use the content types `image/gif`, `image/png` (with APNG format),
357 : /// `image/apng`, and `image/webp` instead of the common static `image/png` or `image/jpeg`
358 : /// content types.
359 : ///
360 : /// When `true`, the server SHOULD return an animated thumbnail if possible and supported.
361 : /// When `false`, the server MUST NOT return an animated thumbnail. For example, returning a
362 : /// static `image/png` or `image/jpeg` thumbnail. When not provided, the server SHOULD NOT
363 : /// return an animated thumbnail.
364 : ///
365 : /// Servers SHOULD prefer to return `image/webp` thumbnails when supporting animation.
366 : ///
367 : /// When `true` and the media cannot be animated, such as in the case of a JPEG or PDF, the
368 : /// server SHOULD behave as though `animated` is `false`.
369 : ///
370 0 : Future<FileResponse> getContentThumbnailAuthed(
371 : String serverName,
372 : String mediaId,
373 : int width,
374 : int height, {
375 : Method? method,
376 : int? timeoutMs,
377 : bool? animated,
378 : }) async {
379 0 : final requestUri = Uri(
380 : path:
381 0 : '_matrix/client/v1/media/thumbnail/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}',
382 0 : queryParameters: {
383 0 : 'width': width.toString(),
384 0 : 'height': height.toString(),
385 0 : if (method != null) 'method': method.name,
386 0 : if (timeoutMs != null) 'timeout_ms': timeoutMs.toString(),
387 0 : if (animated != null) 'animated': animated.toString(),
388 : },
389 : );
390 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
391 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
392 0 : final response = await httpClient.send(request);
393 0 : final responseBody = await response.stream.toBytes();
394 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
395 0 : return FileResponse(
396 0 : contentType: response.headers['content-type'],
397 : data: responseBody,
398 : );
399 : }
400 :
401 : /// Queries the server to determine if a given registration token is still
402 : /// valid at the time of request. This is a point-in-time check where the
403 : /// token might still expire by the time it is used.
404 : ///
405 : /// Servers should be sure to rate limit this endpoint to avoid brute force
406 : /// attacks.
407 : ///
408 : /// [token] The token to check validity of.
409 : ///
410 : /// returns `valid`:
411 : /// True if the token is still valid, false otherwise. This should
412 : /// additionally be false if the token is not a recognised token by
413 : /// the server.
414 0 : Future<bool> registrationTokenValidity(String token) async {
415 0 : final requestUri = Uri(
416 : path: '_matrix/client/v1/register/m.login.registration_token/validity',
417 0 : queryParameters: {
418 : 'token': token,
419 : },
420 : );
421 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
422 0 : final response = await httpClient.send(request);
423 0 : final responseBody = await response.stream.toBytes();
424 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
425 0 : final responseString = utf8.decode(responseBody);
426 0 : final json = jsonDecode(responseString);
427 0 : return json['valid'] as bool;
428 : }
429 :
430 : /// Paginates over the space tree in a depth-first manner to locate child rooms of a given space.
431 : ///
432 : /// Where a child room is unknown to the local server, federation is used to fill in the details.
433 : /// The servers listed in the `via` array should be contacted to attempt to fill in missing rooms.
434 : ///
435 : /// Only [`m.space.child`](https://spec.matrix.org/unstable/client-server-api/#mspacechild) state events of the room are considered.
436 : /// Invalid child rooms and parent events are not covered by this endpoint.
437 : ///
438 : /// [roomId] The room ID of the space to get a hierarchy for.
439 : ///
440 : /// [suggestedOnly] Optional (default `false`) flag to indicate whether or not the server should only consider
441 : /// suggested rooms. Suggested rooms are annotated in their [`m.space.child`](https://spec.matrix.org/unstable/client-server-api/#mspacechild)
442 : /// event contents.
443 : ///
444 : /// [limit] Optional limit for the maximum number of rooms to include per response. Must be an integer
445 : /// greater than zero.
446 : ///
447 : /// Servers should apply a default value, and impose a maximum value to avoid resource exhaustion.
448 : ///
449 : /// [maxDepth] Optional limit for how far to go into the space. Must be a non-negative integer.
450 : ///
451 : /// When reached, no further child rooms will be returned.
452 : ///
453 : /// Servers should apply a default value, and impose a maximum value to avoid resource exhaustion.
454 : ///
455 : /// [from] A pagination token from a previous result. If specified, `max_depth` and `suggested_only` cannot
456 : /// be changed from the first request.
457 0 : Future<GetSpaceHierarchyResponse> getSpaceHierarchy(
458 : String roomId, {
459 : bool? suggestedOnly,
460 : int? limit,
461 : int? maxDepth,
462 : String? from,
463 : }) async {
464 0 : final requestUri = Uri(
465 0 : path: '_matrix/client/v1/rooms/${Uri.encodeComponent(roomId)}/hierarchy',
466 0 : queryParameters: {
467 0 : if (suggestedOnly != null) 'suggested_only': suggestedOnly.toString(),
468 0 : if (limit != null) 'limit': limit.toString(),
469 0 : if (maxDepth != null) 'max_depth': maxDepth.toString(),
470 0 : if (from != null) 'from': from,
471 : },
472 : );
473 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
474 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
475 0 : final response = await httpClient.send(request);
476 0 : final responseBody = await response.stream.toBytes();
477 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
478 0 : final responseString = utf8.decode(responseBody);
479 0 : final json = jsonDecode(responseString);
480 0 : return GetSpaceHierarchyResponse.fromJson(json as Map<String, Object?>);
481 : }
482 :
483 : /// Retrieve all of the child events for a given parent event.
484 : ///
485 : /// Note that when paginating the `from` token should be "after" the `to` token in
486 : /// terms of topological ordering, because it is only possible to paginate "backwards"
487 : /// through events, starting at `from`.
488 : ///
489 : /// For example, passing a `from` token from page 2 of the results, and a `to` token
490 : /// from page 1, would return the empty set. The caller can use a `from` token from
491 : /// page 1 and a `to` token from page 2 to paginate over the same range, however.
492 : ///
493 : /// [roomId] The ID of the room containing the parent event.
494 : ///
495 : /// [eventId] The ID of the parent event whose child events are to be returned.
496 : ///
497 : /// [from] The pagination token to start returning results from. If not supplied, results
498 : /// start at the most recent topological event known to the server.
499 : ///
500 : /// Can be a `next_batch` or `prev_batch` token from a previous call, or a returned
501 : /// `start` token from [`/messages`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3roomsroomidmessages),
502 : /// or a `next_batch` token from [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync).
503 : ///
504 : /// [to] The pagination token to stop returning results at. If not supplied, results
505 : /// continue up to `limit` or until there are no more events.
506 : ///
507 : /// Like `from`, this can be a previous token from a prior call to this endpoint
508 : /// or from `/messages` or `/sync`.
509 : ///
510 : /// [limit] The maximum number of results to return in a single `chunk`. The server can
511 : /// and should apply a maximum value to this parameter to avoid large responses.
512 : ///
513 : /// Similarly, the server should apply a default value when not supplied.
514 : ///
515 : /// [dir] Optional (default `b`) direction to return events from. If this is set to `f`, events
516 : /// will be returned in chronological order starting at `from`. If it
517 : /// is set to `b`, events will be returned in *reverse* chronological
518 : /// order, again starting at `from`.
519 : ///
520 : /// [recurse] Whether to additionally include events which only relate indirectly to the
521 : /// given event, i.e. events related to the given event via two or more direct relationships.
522 : ///
523 : /// If set to `false`, only events which have a direct relation with the given
524 : /// event will be included.
525 : ///
526 : /// If set to `true`, events which have an indirect relation with the given event
527 : /// will be included additionally up to a certain depth level. Homeservers SHOULD traverse
528 : /// at least 3 levels of relationships. Implementations MAY perform more but MUST be careful
529 : /// to not infinitely recurse.
530 : ///
531 : /// The default value is `false`.
532 0 : Future<GetRelatingEventsResponse> getRelatingEvents(
533 : String roomId,
534 : String eventId, {
535 : String? from,
536 : String? to,
537 : int? limit,
538 : Direction? dir,
539 : bool? recurse,
540 : }) async {
541 0 : final requestUri = Uri(
542 : path:
543 0 : '_matrix/client/v1/rooms/${Uri.encodeComponent(roomId)}/relations/${Uri.encodeComponent(eventId)}',
544 0 : queryParameters: {
545 0 : if (from != null) 'from': from,
546 0 : if (to != null) 'to': to,
547 0 : if (limit != null) 'limit': limit.toString(),
548 0 : if (dir != null) 'dir': dir.name,
549 0 : if (recurse != null) 'recurse': recurse.toString(),
550 : },
551 : );
552 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
553 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
554 0 : final response = await httpClient.send(request);
555 0 : final responseBody = await response.stream.toBytes();
556 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
557 0 : final responseString = utf8.decode(responseBody);
558 0 : final json = jsonDecode(responseString);
559 0 : return GetRelatingEventsResponse.fromJson(json as Map<String, Object?>);
560 : }
561 :
562 : /// Retrieve all of the child events for a given parent event which relate to the parent
563 : /// using the given `relType`.
564 : ///
565 : /// Note that when paginating the `from` token should be "after" the `to` token in
566 : /// terms of topological ordering, because it is only possible to paginate "backwards"
567 : /// through events, starting at `from`.
568 : ///
569 : /// For example, passing a `from` token from page 2 of the results, and a `to` token
570 : /// from page 1, would return the empty set. The caller can use a `from` token from
571 : /// page 1 and a `to` token from page 2 to paginate over the same range, however.
572 : ///
573 : /// [roomId] The ID of the room containing the parent event.
574 : ///
575 : /// [eventId] The ID of the parent event whose child events are to be returned.
576 : ///
577 : /// [relType] The [relationship type](https://spec.matrix.org/unstable/client-server-api/#relationship-types) to search for.
578 : ///
579 : /// [from] The pagination token to start returning results from. If not supplied, results
580 : /// start at the most recent topological event known to the server.
581 : ///
582 : /// Can be a `next_batch` or `prev_batch` token from a previous call, or a returned
583 : /// `start` token from [`/messages`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3roomsroomidmessages),
584 : /// or a `next_batch` token from [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync).
585 : ///
586 : /// [to] The pagination token to stop returning results at. If not supplied, results
587 : /// continue up to `limit` or until there are no more events.
588 : ///
589 : /// Like `from`, this can be a previous token from a prior call to this endpoint
590 : /// or from `/messages` or `/sync`.
591 : ///
592 : /// [limit] The maximum number of results to return in a single `chunk`. The server can
593 : /// and should apply a maximum value to this parameter to avoid large responses.
594 : ///
595 : /// Similarly, the server should apply a default value when not supplied.
596 : ///
597 : /// [dir] Optional (default `b`) direction to return events from. If this is set to `f`, events
598 : /// will be returned in chronological order starting at `from`. If it
599 : /// is set to `b`, events will be returned in *reverse* chronological
600 : /// order, again starting at `from`.
601 : ///
602 : /// [recurse] Whether to additionally include events which only relate indirectly to the
603 : /// given event, i.e. events related to the given event via two or more direct relationships.
604 : ///
605 : /// If set to `false`, only events which have a direct relation with the given
606 : /// event will be included.
607 : ///
608 : /// If set to `true`, events which have an indirect relation with the given event
609 : /// will be included additionally up to a certain depth level. Homeservers SHOULD traverse
610 : /// at least 3 levels of relationships. Implementations MAY perform more but MUST be careful
611 : /// to not infinitely recurse.
612 : ///
613 : /// The default value is `false`.
614 0 : Future<GetRelatingEventsWithRelTypeResponse> getRelatingEventsWithRelType(
615 : String roomId,
616 : String eventId,
617 : String relType, {
618 : String? from,
619 : String? to,
620 : int? limit,
621 : Direction? dir,
622 : bool? recurse,
623 : }) async {
624 0 : final requestUri = Uri(
625 : path:
626 0 : '_matrix/client/v1/rooms/${Uri.encodeComponent(roomId)}/relations/${Uri.encodeComponent(eventId)}/${Uri.encodeComponent(relType)}',
627 0 : queryParameters: {
628 0 : if (from != null) 'from': from,
629 0 : if (to != null) 'to': to,
630 0 : if (limit != null) 'limit': limit.toString(),
631 0 : if (dir != null) 'dir': dir.name,
632 0 : if (recurse != null) 'recurse': recurse.toString(),
633 : },
634 : );
635 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
636 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
637 0 : final response = await httpClient.send(request);
638 0 : final responseBody = await response.stream.toBytes();
639 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
640 0 : final responseString = utf8.decode(responseBody);
641 0 : final json = jsonDecode(responseString);
642 0 : return GetRelatingEventsWithRelTypeResponse.fromJson(
643 : json as Map<String, Object?>,
644 : );
645 : }
646 :
647 : /// Retrieve all of the child events for a given parent event which relate to the parent
648 : /// using the given `relType` and have the given `eventType`.
649 : ///
650 : /// Note that when paginating the `from` token should be "after" the `to` token in
651 : /// terms of topological ordering, because it is only possible to paginate "backwards"
652 : /// through events, starting at `from`.
653 : ///
654 : /// For example, passing a `from` token from page 2 of the results, and a `to` token
655 : /// from page 1, would return the empty set. The caller can use a `from` token from
656 : /// page 1 and a `to` token from page 2 to paginate over the same range, however.
657 : ///
658 : /// [roomId] The ID of the room containing the parent event.
659 : ///
660 : /// [eventId] The ID of the parent event whose child events are to be returned.
661 : ///
662 : /// [relType] The [relationship type](https://spec.matrix.org/unstable/client-server-api/#relationship-types) to search for.
663 : ///
664 : /// [eventType] The event type of child events to search for.
665 : ///
666 : /// Note that in encrypted rooms this will typically always be `m.room.encrypted`
667 : /// regardless of the event type contained within the encrypted payload.
668 : ///
669 : /// [from] The pagination token to start returning results from. If not supplied, results
670 : /// start at the most recent topological event known to the server.
671 : ///
672 : /// Can be a `next_batch` or `prev_batch` token from a previous call, or a returned
673 : /// `start` token from [`/messages`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3roomsroomidmessages),
674 : /// or a `next_batch` token from [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync).
675 : ///
676 : /// [to] The pagination token to stop returning results at. If not supplied, results
677 : /// continue up to `limit` or until there are no more events.
678 : ///
679 : /// Like `from`, this can be a previous token from a prior call to this endpoint
680 : /// or from `/messages` or `/sync`.
681 : ///
682 : /// [limit] The maximum number of results to return in a single `chunk`. The server can
683 : /// and should apply a maximum value to this parameter to avoid large responses.
684 : ///
685 : /// Similarly, the server should apply a default value when not supplied.
686 : ///
687 : /// [dir] Optional (default `b`) direction to return events from. If this is set to `f`, events
688 : /// will be returned in chronological order starting at `from`. If it
689 : /// is set to `b`, events will be returned in *reverse* chronological
690 : /// order, again starting at `from`.
691 : ///
692 : /// [recurse] Whether to additionally include events which only relate indirectly to the
693 : /// given event, i.e. events related to the given event via two or more direct relationships.
694 : ///
695 : /// If set to `false`, only events which have a direct relation with the given
696 : /// event will be included.
697 : ///
698 : /// If set to `true`, events which have an indirect relation with the given event
699 : /// will be included additionally up to a certain depth level. Homeservers SHOULD traverse
700 : /// at least 3 levels of relationships. Implementations MAY perform more but MUST be careful
701 : /// to not infinitely recurse.
702 : ///
703 : /// The default value is `false`.
704 0 : Future<GetRelatingEventsWithRelTypeAndEventTypeResponse>
705 : getRelatingEventsWithRelTypeAndEventType(
706 : String roomId,
707 : String eventId,
708 : String relType,
709 : String eventType, {
710 : String? from,
711 : String? to,
712 : int? limit,
713 : Direction? dir,
714 : bool? recurse,
715 : }) async {
716 0 : final requestUri = Uri(
717 : path:
718 0 : '_matrix/client/v1/rooms/${Uri.encodeComponent(roomId)}/relations/${Uri.encodeComponent(eventId)}/${Uri.encodeComponent(relType)}/${Uri.encodeComponent(eventType)}',
719 0 : queryParameters: {
720 0 : if (from != null) 'from': from,
721 0 : if (to != null) 'to': to,
722 0 : if (limit != null) 'limit': limit.toString(),
723 0 : if (dir != null) 'dir': dir.name,
724 0 : if (recurse != null) 'recurse': recurse.toString(),
725 : },
726 : );
727 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
728 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
729 0 : final response = await httpClient.send(request);
730 0 : final responseBody = await response.stream.toBytes();
731 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
732 0 : final responseString = utf8.decode(responseBody);
733 0 : final json = jsonDecode(responseString);
734 0 : return GetRelatingEventsWithRelTypeAndEventTypeResponse.fromJson(
735 : json as Map<String, Object?>,
736 : );
737 : }
738 :
739 : /// This API is used to paginate through the list of the thread roots in a given room.
740 : ///
741 : /// Optionally, the returned list may be filtered according to whether the requesting
742 : /// user has participated in the thread.
743 : ///
744 : /// [roomId] The room ID where the thread roots are located.
745 : ///
746 : /// [include] Optional (default `all`) flag to denote which thread roots are of interest to the caller.
747 : /// When `all`, all thread roots found in the room are returned. When `participated`, only
748 : /// thread roots for threads the user has [participated in](https://spec.matrix.org/unstable/client-server-api/#server-side-aggregation-of-mthread-relationships)
749 : /// will be returned.
750 : ///
751 : /// [limit] Optional limit for the maximum number of thread roots to include per response. Must be an integer
752 : /// greater than zero.
753 : ///
754 : /// Servers should apply a default value, and impose a maximum value to avoid resource exhaustion.
755 : ///
756 : /// [from] A pagination token from a previous result. When not provided, the server starts paginating from
757 : /// the most recent event visible to the user (as per history visibility rules; topologically).
758 0 : Future<GetThreadRootsResponse> getThreadRoots(
759 : String roomId, {
760 : Include? include,
761 : int? limit,
762 : String? from,
763 : }) async {
764 0 : final requestUri = Uri(
765 0 : path: '_matrix/client/v1/rooms/${Uri.encodeComponent(roomId)}/threads',
766 0 : queryParameters: {
767 0 : if (include != null) 'include': include.name,
768 0 : if (limit != null) 'limit': limit.toString(),
769 0 : if (from != null) 'from': from,
770 : },
771 : );
772 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
773 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
774 0 : final response = await httpClient.send(request);
775 0 : final responseBody = await response.stream.toBytes();
776 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
777 0 : final responseString = utf8.decode(responseBody);
778 0 : final json = jsonDecode(responseString);
779 0 : return GetThreadRootsResponse.fromJson(json as Map<String, Object?>);
780 : }
781 :
782 : /// Get the ID of the event closest to the given timestamp, in the
783 : /// direction specified by the `dir` parameter.
784 : ///
785 : /// If the server does not have all of the room history and does not have
786 : /// an event suitably close to the requested timestamp, it can use the
787 : /// corresponding [federation endpoint](https://spec.matrix.org/unstable/server-server-api/#get_matrixfederationv1timestamp_to_eventroomid)
788 : /// to ask other servers for a suitable event.
789 : ///
790 : /// After calling this endpoint, clients can call
791 : /// [`/rooms/{roomId}/context/{eventId}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3roomsroomidcontexteventid)
792 : /// to obtain a pagination token to retrieve the events around the returned event.
793 : ///
794 : /// The event returned by this endpoint could be an event that the client
795 : /// cannot render, and so may need to paginate in order to locate an event
796 : /// that it can display, which may end up being outside of the client's
797 : /// suitable range. Clients can employ different strategies to display
798 : /// something reasonable to the user. For example, the client could try
799 : /// paginating in one direction for a while, while looking at the
800 : /// timestamps of the events that it is paginating through, and if it
801 : /// exceeds a certain difference from the target timestamp, it can try
802 : /// paginating in the opposite direction. The client could also simply
803 : /// paginate in one direction and inform the user that the closest event
804 : /// found in that direction is outside of the expected range.
805 : ///
806 : /// [roomId] The ID of the room to search
807 : ///
808 : /// [ts] The timestamp to search from, as given in milliseconds
809 : /// since the Unix epoch.
810 : ///
811 : /// [dir] The direction in which to search. `f` for forwards, `b` for backwards.
812 0 : Future<GetEventByTimestampResponse> getEventByTimestamp(
813 : String roomId,
814 : int ts,
815 : Direction dir,
816 : ) async {
817 0 : final requestUri = Uri(
818 : path:
819 0 : '_matrix/client/v1/rooms/${Uri.encodeComponent(roomId)}/timestamp_to_event',
820 0 : queryParameters: {
821 0 : 'ts': ts.toString(),
822 0 : 'dir': dir.name,
823 : },
824 : );
825 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
826 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
827 0 : final response = await httpClient.send(request);
828 0 : final responseBody = await response.stream.toBytes();
829 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
830 0 : final responseString = utf8.decode(responseBody);
831 0 : final json = jsonDecode(responseString);
832 0 : return GetEventByTimestampResponse.fromJson(json as Map<String, Object?>);
833 : }
834 :
835 : /// Gets a list of the third-party identifiers that the homeserver has
836 : /// associated with the user's account.
837 : ///
838 : /// This is *not* the same as the list of third-party identifiers bound to
839 : /// the user's Matrix ID in identity servers.
840 : ///
841 : /// Identifiers in this list may be used by the homeserver as, for example,
842 : /// identifiers that it will accept to reset the user's account password.
843 : ///
844 : /// returns `threepids`:
845 : ///
846 0 : Future<List<ThirdPartyIdentifier>?> getAccount3PIDs() async {
847 0 : final requestUri = Uri(path: '_matrix/client/v3/account/3pid');
848 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
849 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
850 0 : final response = await httpClient.send(request);
851 0 : final responseBody = await response.stream.toBytes();
852 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
853 0 : final responseString = utf8.decode(responseBody);
854 0 : final json = jsonDecode(responseString);
855 0 : return ((v) => v != null
856 : ? (v as List)
857 0 : .map(
858 0 : (v) => ThirdPartyIdentifier.fromJson(v as Map<String, Object?>),
859 : )
860 0 : .toList()
861 0 : : null)(json['threepids']);
862 : }
863 :
864 : /// Adds contact information to the user's account.
865 : ///
866 : /// This endpoint is deprecated in favour of the more specific `/3pid/add`
867 : /// and `/3pid/bind` endpoints.
868 : ///
869 : /// **Note:**
870 : /// Previously this endpoint supported a `bind` parameter. This parameter
871 : /// has been removed, making this endpoint behave as though it was `false`.
872 : /// This results in this endpoint being an equivalent to `/3pid/bind` rather
873 : /// than dual-purpose.
874 : ///
875 : /// [threePidCreds] The third-party credentials to associate with the account.
876 : ///
877 : /// returns `submit_url`:
878 : /// An optional field containing a URL where the client must
879 : /// submit the validation token to, with identical parameters
880 : /// to the Identity Service API's `POST
881 : /// /validate/email/submitToken` endpoint (without the requirement
882 : /// for an access token). The homeserver must send this token to the
883 : /// user (if applicable), who should then be prompted to provide it
884 : /// to the client.
885 : ///
886 : /// If this field is not present, the client can assume that
887 : /// verification will happen without the client's involvement
888 : /// provided the homeserver advertises this specification version
889 : /// in the `/versions` response (ie: r0.5.0).
890 0 : @deprecated
891 : Future<Uri?> post3PIDs(ThreePidCredentials threePidCreds) async {
892 0 : final requestUri = Uri(path: '_matrix/client/v3/account/3pid');
893 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
894 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
895 0 : request.headers['content-type'] = 'application/json';
896 0 : request.bodyBytes = utf8.encode(
897 0 : jsonEncode({
898 0 : 'three_pid_creds': threePidCreds.toJson(),
899 : }),
900 : );
901 0 : final response = await httpClient.send(request);
902 0 : final responseBody = await response.stream.toBytes();
903 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
904 0 : final responseString = utf8.decode(responseBody);
905 0 : final json = jsonDecode(responseString);
906 0 : return ((v) =>
907 0 : v != null ? Uri.parse(v as String) : null)(json['submit_url']);
908 : }
909 :
910 : /// This API endpoint uses the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api).
911 : ///
912 : /// Adds contact information to the user's account. Homeservers should use 3PIDs added
913 : /// through this endpoint for password resets instead of relying on the identity server.
914 : ///
915 : /// Homeservers should prevent the caller from adding a 3PID to their account if it has
916 : /// already been added to another user's account on the homeserver.
917 : ///
918 : /// [auth] Additional authentication information for the
919 : /// user-interactive authentication API.
920 : ///
921 : /// [clientSecret] The client secret used in the session with the homeserver.
922 : ///
923 : /// [sid] The session identifier given by the homeserver.
924 0 : Future<void> add3PID(
925 : String clientSecret,
926 : String sid, {
927 : AuthenticationData? auth,
928 : }) async {
929 0 : final requestUri = Uri(path: '_matrix/client/v3/account/3pid/add');
930 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
931 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
932 0 : request.headers['content-type'] = 'application/json';
933 0 : request.bodyBytes = utf8.encode(
934 0 : jsonEncode({
935 0 : if (auth != null) 'auth': auth.toJson(),
936 0 : 'client_secret': clientSecret,
937 0 : 'sid': sid,
938 : }),
939 : );
940 0 : final response = await httpClient.send(request);
941 0 : final responseBody = await response.stream.toBytes();
942 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
943 0 : final responseString = utf8.decode(responseBody);
944 0 : final json = jsonDecode(responseString);
945 0 : return ignore(json);
946 : }
947 :
948 : /// Binds a 3PID to the user's account through the specified identity server.
949 : ///
950 : /// Homeservers should not prevent this request from succeeding if another user
951 : /// has bound the 3PID. Homeservers should simply proxy any errors received by
952 : /// the identity server to the caller.
953 : ///
954 : /// Homeservers should track successful binds so they can be unbound later.
955 : ///
956 : /// [clientSecret] The client secret used in the session with the identity server.
957 : ///
958 : /// [idAccessToken] An access token previously registered with the identity server.
959 : ///
960 : /// [idServer] The identity server to use.
961 : ///
962 : /// [sid] The session identifier given by the identity server.
963 0 : Future<void> bind3PID(
964 : String clientSecret,
965 : String idAccessToken,
966 : String idServer,
967 : String sid,
968 : ) async {
969 0 : final requestUri = Uri(path: '_matrix/client/v3/account/3pid/bind');
970 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
971 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
972 0 : request.headers['content-type'] = 'application/json';
973 0 : request.bodyBytes = utf8.encode(
974 0 : jsonEncode({
975 : 'client_secret': clientSecret,
976 : 'id_access_token': idAccessToken,
977 : 'id_server': idServer,
978 : 'sid': sid,
979 : }),
980 : );
981 0 : final response = await httpClient.send(request);
982 0 : final responseBody = await response.stream.toBytes();
983 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
984 0 : final responseString = utf8.decode(responseBody);
985 0 : final json = jsonDecode(responseString);
986 0 : return ignore(json);
987 : }
988 :
989 : /// Removes a third-party identifier from the user's account. This might not
990 : /// cause an unbind of the identifier from the identity server.
991 : ///
992 : /// Unlike other endpoints, this endpoint does not take an `id_access_token`
993 : /// parameter because the homeserver is expected to sign the request to the
994 : /// identity server instead.
995 : ///
996 : /// [address] The third-party address being removed.
997 : ///
998 : /// [idServer] The identity server to unbind from. If not provided, the homeserver
999 : /// MUST use the `id_server` the identifier was added through. If the
1000 : /// homeserver does not know the original `id_server`, it MUST return
1001 : /// a `id_server_unbind_result` of `no-support`.
1002 : ///
1003 : /// [medium] The medium of the third-party identifier being removed.
1004 : ///
1005 : /// returns `id_server_unbind_result`:
1006 : /// An indicator as to whether or not the homeserver was able to unbind
1007 : /// the 3PID from the identity server. `success` indicates that the
1008 : /// identity server has unbound the identifier whereas `no-support`
1009 : /// indicates that the identity server refuses to support the request
1010 : /// or the homeserver was not able to determine an identity server to
1011 : /// unbind from.
1012 0 : Future<IdServerUnbindResult> delete3pidFromAccount(
1013 : String address,
1014 : ThirdPartyIdentifierMedium medium, {
1015 : String? idServer,
1016 : }) async {
1017 0 : final requestUri = Uri(path: '_matrix/client/v3/account/3pid/delete');
1018 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
1019 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1020 0 : request.headers['content-type'] = 'application/json';
1021 0 : request.bodyBytes = utf8.encode(
1022 0 : jsonEncode({
1023 0 : 'address': address,
1024 0 : if (idServer != null) 'id_server': idServer,
1025 0 : 'medium': medium.name,
1026 : }),
1027 : );
1028 0 : final response = await httpClient.send(request);
1029 0 : final responseBody = await response.stream.toBytes();
1030 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1031 0 : final responseString = utf8.decode(responseBody);
1032 0 : final json = jsonDecode(responseString);
1033 : return IdServerUnbindResult.values
1034 0 : .fromString(json['id_server_unbind_result'] as String)!;
1035 : }
1036 :
1037 : /// The homeserver must check that the given email address is **not**
1038 : /// already associated with an account on this homeserver. This API should
1039 : /// be used to request validation tokens when adding an email address to an
1040 : /// account. This API's parameters and response are identical to that of
1041 : /// the [`/register/email/requestToken`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3registeremailrequesttoken)
1042 : /// endpoint. The homeserver should validate
1043 : /// the email itself, either by sending a validation email itself or by using
1044 : /// a service it has control over.
1045 : ///
1046 : /// [clientSecret] A unique string generated by the client, and used to identify the
1047 : /// validation attempt. It must be a string consisting of the characters
1048 : /// `[0-9a-zA-Z.=_-]`. Its length must not exceed 255 characters and it
1049 : /// must not be empty.
1050 : ///
1051 : ///
1052 : /// [email] The email address to validate.
1053 : ///
1054 : /// [nextLink] Optional. When the validation is completed, the identity server will
1055 : /// redirect the user to this URL. This option is ignored when submitting
1056 : /// 3PID validation information through a POST request.
1057 : ///
1058 : /// [sendAttempt] The server will only send an email if the `send_attempt`
1059 : /// is a number greater than the most recent one which it has seen,
1060 : /// scoped to that `email` + `client_secret` pair. This is to
1061 : /// avoid repeatedly sending the same email in the case of request
1062 : /// retries between the POSTing user and the identity server.
1063 : /// The client should increment this value if they desire a new
1064 : /// email (e.g. a reminder) to be sent. If they do not, the server
1065 : /// should respond with success but not resend the email.
1066 : ///
1067 : /// [idAccessToken] An access token previously registered with the identity server. Servers
1068 : /// can treat this as optional to distinguish between r0.5-compatible clients
1069 : /// and this specification version.
1070 : ///
1071 : /// Required if an `id_server` is supplied.
1072 : ///
1073 : /// [idServer] The hostname of the identity server to communicate with. May optionally
1074 : /// include a port. This parameter is ignored when the homeserver handles
1075 : /// 3PID verification.
1076 : ///
1077 : /// This parameter is deprecated with a plan to be removed in a future specification
1078 : /// version for `/account/password` and `/register` requests.
1079 0 : Future<RequestTokenResponse> requestTokenTo3PIDEmail(
1080 : String clientSecret,
1081 : String email,
1082 : int sendAttempt, {
1083 : Uri? nextLink,
1084 : String? idAccessToken,
1085 : String? idServer,
1086 : }) async {
1087 : final requestUri =
1088 0 : Uri(path: '_matrix/client/v3/account/3pid/email/requestToken');
1089 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
1090 0 : request.headers['content-type'] = 'application/json';
1091 0 : request.bodyBytes = utf8.encode(
1092 0 : jsonEncode({
1093 0 : 'client_secret': clientSecret,
1094 0 : 'email': email,
1095 0 : if (nextLink != null) 'next_link': nextLink.toString(),
1096 0 : 'send_attempt': sendAttempt,
1097 0 : if (idAccessToken != null) 'id_access_token': idAccessToken,
1098 0 : if (idServer != null) 'id_server': idServer,
1099 : }),
1100 : );
1101 0 : final response = await httpClient.send(request);
1102 0 : final responseBody = await response.stream.toBytes();
1103 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1104 0 : final responseString = utf8.decode(responseBody);
1105 0 : final json = jsonDecode(responseString);
1106 0 : return RequestTokenResponse.fromJson(json as Map<String, Object?>);
1107 : }
1108 :
1109 : /// The homeserver must check that the given phone number is **not**
1110 : /// already associated with an account on this homeserver. This API should
1111 : /// be used to request validation tokens when adding a phone number to an
1112 : /// account. This API's parameters and response are identical to that of
1113 : /// the [`/register/msisdn/requestToken`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3registermsisdnrequesttoken)
1114 : /// endpoint. The homeserver should validate
1115 : /// the phone number itself, either by sending a validation message itself or by using
1116 : /// a service it has control over.
1117 : ///
1118 : /// [clientSecret] A unique string generated by the client, and used to identify the
1119 : /// validation attempt. It must be a string consisting of the characters
1120 : /// `[0-9a-zA-Z.=_-]`. Its length must not exceed 255 characters and it
1121 : /// must not be empty.
1122 : ///
1123 : ///
1124 : /// [country] The two-letter uppercase ISO-3166-1 alpha-2 country code that the
1125 : /// number in `phone_number` should be parsed as if it were dialled from.
1126 : ///
1127 : /// [nextLink] Optional. When the validation is completed, the identity server will
1128 : /// redirect the user to this URL. This option is ignored when submitting
1129 : /// 3PID validation information through a POST request.
1130 : ///
1131 : /// [phoneNumber] The phone number to validate.
1132 : ///
1133 : /// [sendAttempt] The server will only send an SMS if the `send_attempt` is a
1134 : /// number greater than the most recent one which it has seen,
1135 : /// scoped to that `country` + `phone_number` + `client_secret`
1136 : /// triple. This is to avoid repeatedly sending the same SMS in
1137 : /// the case of request retries between the POSTing user and the
1138 : /// identity server. The client should increment this value if
1139 : /// they desire a new SMS (e.g. a reminder) to be sent.
1140 : ///
1141 : /// [idAccessToken] An access token previously registered with the identity server. Servers
1142 : /// can treat this as optional to distinguish between r0.5-compatible clients
1143 : /// and this specification version.
1144 : ///
1145 : /// Required if an `id_server` is supplied.
1146 : ///
1147 : /// [idServer] The hostname of the identity server to communicate with. May optionally
1148 : /// include a port. This parameter is ignored when the homeserver handles
1149 : /// 3PID verification.
1150 : ///
1151 : /// This parameter is deprecated with a plan to be removed in a future specification
1152 : /// version for `/account/password` and `/register` requests.
1153 0 : Future<RequestTokenResponse> requestTokenTo3PIDMSISDN(
1154 : String clientSecret,
1155 : String country,
1156 : String phoneNumber,
1157 : int sendAttempt, {
1158 : Uri? nextLink,
1159 : String? idAccessToken,
1160 : String? idServer,
1161 : }) async {
1162 : final requestUri =
1163 0 : Uri(path: '_matrix/client/v3/account/3pid/msisdn/requestToken');
1164 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
1165 0 : request.headers['content-type'] = 'application/json';
1166 0 : request.bodyBytes = utf8.encode(
1167 0 : jsonEncode({
1168 0 : 'client_secret': clientSecret,
1169 0 : 'country': country,
1170 0 : if (nextLink != null) 'next_link': nextLink.toString(),
1171 0 : 'phone_number': phoneNumber,
1172 0 : 'send_attempt': sendAttempt,
1173 0 : if (idAccessToken != null) 'id_access_token': idAccessToken,
1174 0 : if (idServer != null) 'id_server': idServer,
1175 : }),
1176 : );
1177 0 : final response = await httpClient.send(request);
1178 0 : final responseBody = await response.stream.toBytes();
1179 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1180 0 : final responseString = utf8.decode(responseBody);
1181 0 : final json = jsonDecode(responseString);
1182 0 : return RequestTokenResponse.fromJson(json as Map<String, Object?>);
1183 : }
1184 :
1185 : /// Removes a user's third-party identifier from the provided identity server
1186 : /// without removing it from the homeserver.
1187 : ///
1188 : /// Unlike other endpoints, this endpoint does not take an `id_access_token`
1189 : /// parameter because the homeserver is expected to sign the request to the
1190 : /// identity server instead.
1191 : ///
1192 : /// [address] The third-party address being removed.
1193 : ///
1194 : /// [idServer] The identity server to unbind from. If not provided, the homeserver
1195 : /// MUST use the `id_server` the identifier was added through. If the
1196 : /// homeserver does not know the original `id_server`, it MUST return
1197 : /// a `id_server_unbind_result` of `no-support`.
1198 : ///
1199 : /// [medium] The medium of the third-party identifier being removed.
1200 : ///
1201 : /// returns `id_server_unbind_result`:
1202 : /// An indicator as to whether or not the identity server was able to unbind
1203 : /// the 3PID. `success` indicates that the identity server has unbound the
1204 : /// identifier whereas `no-support` indicates that the identity server
1205 : /// refuses to support the request or the homeserver was not able to determine
1206 : /// an identity server to unbind from.
1207 0 : Future<IdServerUnbindResult> unbind3pidFromAccount(
1208 : String address,
1209 : ThirdPartyIdentifierMedium medium, {
1210 : String? idServer,
1211 : }) async {
1212 0 : final requestUri = Uri(path: '_matrix/client/v3/account/3pid/unbind');
1213 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
1214 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1215 0 : request.headers['content-type'] = 'application/json';
1216 0 : request.bodyBytes = utf8.encode(
1217 0 : jsonEncode({
1218 0 : 'address': address,
1219 0 : if (idServer != null) 'id_server': idServer,
1220 0 : 'medium': medium.name,
1221 : }),
1222 : );
1223 0 : final response = await httpClient.send(request);
1224 0 : final responseBody = await response.stream.toBytes();
1225 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1226 0 : final responseString = utf8.decode(responseBody);
1227 0 : final json = jsonDecode(responseString);
1228 : return IdServerUnbindResult.values
1229 0 : .fromString(json['id_server_unbind_result'] as String)!;
1230 : }
1231 :
1232 : /// Deactivate the user's account, removing all ability for the user to
1233 : /// login again.
1234 : ///
1235 : /// This API endpoint uses the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api).
1236 : ///
1237 : /// An access token should be submitted to this endpoint if the client has
1238 : /// an active session.
1239 : ///
1240 : /// The homeserver may change the flows available depending on whether a
1241 : /// valid access token is provided.
1242 : ///
1243 : /// Unlike other endpoints, this endpoint does not take an `id_access_token`
1244 : /// parameter because the homeserver is expected to sign the request to the
1245 : /// identity server instead.
1246 : ///
1247 : /// [auth] Additional authentication information for the user-interactive authentication API.
1248 : ///
1249 : /// [erase] Whether the user would like their content to be erased as
1250 : /// much as possible from the server.
1251 : ///
1252 : /// Erasure means that any users (or servers) which join the
1253 : /// room after the erasure request are served redacted copies of
1254 : /// the events sent by this account. Users which had visibility
1255 : /// on those events prior to the erasure are still able to see
1256 : /// unredacted copies. No redactions are sent and the erasure
1257 : /// request is not shared over federation, so other servers
1258 : /// might still serve unredacted copies.
1259 : ///
1260 : /// The server should additionally erase any non-event data
1261 : /// associated with the user, such as [account data](https://spec.matrix.org/unstable/client-server-api/#client-config)
1262 : /// and [contact 3PIDs](https://spec.matrix.org/unstable/client-server-api/#adding-account-administrative-contact-information).
1263 : ///
1264 : /// Defaults to `false` if not present.
1265 : ///
1266 : /// [idServer] The identity server to unbind all of the user's 3PIDs from.
1267 : /// If not provided, the homeserver MUST use the `id_server`
1268 : /// that was originally use to bind each identifier. If the
1269 : /// homeserver does not know which `id_server` that was,
1270 : /// it must return an `id_server_unbind_result` of
1271 : /// `no-support`.
1272 : ///
1273 : /// returns `id_server_unbind_result`:
1274 : /// An indicator as to whether or not the homeserver was able to unbind
1275 : /// the user's 3PIDs from the identity server(s). `success` indicates
1276 : /// that all identifiers have been unbound from the identity server while
1277 : /// `no-support` indicates that one or more identifiers failed to unbind
1278 : /// due to the identity server refusing the request or the homeserver
1279 : /// being unable to determine an identity server to unbind from. This
1280 : /// must be `success` if the homeserver has no identifiers to unbind
1281 : /// for the user.
1282 0 : Future<IdServerUnbindResult> deactivateAccount({
1283 : AuthenticationData? auth,
1284 : bool? erase,
1285 : String? idServer,
1286 : }) async {
1287 0 : final requestUri = Uri(path: '_matrix/client/v3/account/deactivate');
1288 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
1289 0 : if (bearerToken != null) {
1290 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1291 : }
1292 0 : request.headers['content-type'] = 'application/json';
1293 0 : request.bodyBytes = utf8.encode(
1294 0 : jsonEncode({
1295 0 : if (auth != null) 'auth': auth.toJson(),
1296 0 : if (erase != null) 'erase': erase,
1297 0 : if (idServer != null) 'id_server': idServer,
1298 : }),
1299 : );
1300 0 : final response = await httpClient.send(request);
1301 0 : final responseBody = await response.stream.toBytes();
1302 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1303 0 : final responseString = utf8.decode(responseBody);
1304 0 : final json = jsonDecode(responseString);
1305 : return IdServerUnbindResult.values
1306 0 : .fromString(json['id_server_unbind_result'] as String)!;
1307 : }
1308 :
1309 : /// Changes the password for an account on this homeserver.
1310 : ///
1311 : /// This API endpoint uses the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api) to
1312 : /// ensure the user changing the password is actually the owner of the
1313 : /// account.
1314 : ///
1315 : /// An access token should be submitted to this endpoint if the client has
1316 : /// an active session.
1317 : ///
1318 : /// The homeserver may change the flows available depending on whether a
1319 : /// valid access token is provided. The homeserver SHOULD NOT revoke the
1320 : /// access token provided in the request. Whether other access tokens for
1321 : /// the user are revoked depends on the request parameters.
1322 : ///
1323 : /// [auth] Additional authentication information for the user-interactive authentication API.
1324 : ///
1325 : /// [logoutDevices] Whether the user's other access tokens, and their associated devices, should be
1326 : /// revoked if the request succeeds. Defaults to true.
1327 : ///
1328 : /// When `false`, the server can still take advantage of the [soft logout method](https://spec.matrix.org/unstable/client-server-api/#soft-logout)
1329 : /// for the user's remaining devices.
1330 : ///
1331 : /// [newPassword] The new password for the account.
1332 1 : Future<void> changePassword(
1333 : String newPassword, {
1334 : AuthenticationData? auth,
1335 : bool? logoutDevices,
1336 : }) async {
1337 1 : final requestUri = Uri(path: '_matrix/client/v3/account/password');
1338 3 : final request = Request('POST', baseUri!.resolveUri(requestUri));
1339 1 : if (bearerToken != null) {
1340 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1341 : }
1342 2 : request.headers['content-type'] = 'application/json';
1343 2 : request.bodyBytes = utf8.encode(
1344 2 : jsonEncode({
1345 2 : if (auth != null) 'auth': auth.toJson(),
1346 0 : if (logoutDevices != null) 'logout_devices': logoutDevices,
1347 1 : 'new_password': newPassword,
1348 : }),
1349 : );
1350 2 : final response = await httpClient.send(request);
1351 2 : final responseBody = await response.stream.toBytes();
1352 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1353 1 : final responseString = utf8.decode(responseBody);
1354 1 : final json = jsonDecode(responseString);
1355 1 : return ignore(json);
1356 : }
1357 :
1358 : /// The homeserver must check that the given email address **is
1359 : /// associated** with an account on this homeserver. This API should be
1360 : /// used to request validation tokens when authenticating for the
1361 : /// `/account/password` endpoint.
1362 : ///
1363 : /// This API's parameters and response are identical to that of the
1364 : /// [`/register/email/requestToken`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3registeremailrequesttoken)
1365 : /// endpoint, except that
1366 : /// `M_THREEPID_NOT_FOUND` may be returned if no account matching the
1367 : /// given email address could be found. The server may instead send an
1368 : /// email to the given address prompting the user to create an account.
1369 : /// `M_THREEPID_IN_USE` may not be returned.
1370 : ///
1371 : /// The homeserver should validate the email itself, either by sending a
1372 : /// validation email itself or by using a service it has control over.
1373 : ///
1374 : /// [clientSecret] A unique string generated by the client, and used to identify the
1375 : /// validation attempt. It must be a string consisting of the characters
1376 : /// `[0-9a-zA-Z.=_-]`. Its length must not exceed 255 characters and it
1377 : /// must not be empty.
1378 : ///
1379 : ///
1380 : /// [email] The email address to validate.
1381 : ///
1382 : /// [nextLink] Optional. When the validation is completed, the identity server will
1383 : /// redirect the user to this URL. This option is ignored when submitting
1384 : /// 3PID validation information through a POST request.
1385 : ///
1386 : /// [sendAttempt] The server will only send an email if the `send_attempt`
1387 : /// is a number greater than the most recent one which it has seen,
1388 : /// scoped to that `email` + `client_secret` pair. This is to
1389 : /// avoid repeatedly sending the same email in the case of request
1390 : /// retries between the POSTing user and the identity server.
1391 : /// The client should increment this value if they desire a new
1392 : /// email (e.g. a reminder) to be sent. If they do not, the server
1393 : /// should respond with success but not resend the email.
1394 : ///
1395 : /// [idAccessToken] An access token previously registered with the identity server. Servers
1396 : /// can treat this as optional to distinguish between r0.5-compatible clients
1397 : /// and this specification version.
1398 : ///
1399 : /// Required if an `id_server` is supplied.
1400 : ///
1401 : /// [idServer] The hostname of the identity server to communicate with. May optionally
1402 : /// include a port. This parameter is ignored when the homeserver handles
1403 : /// 3PID verification.
1404 : ///
1405 : /// This parameter is deprecated with a plan to be removed in a future specification
1406 : /// version for `/account/password` and `/register` requests.
1407 0 : Future<RequestTokenResponse> requestTokenToResetPasswordEmail(
1408 : String clientSecret,
1409 : String email,
1410 : int sendAttempt, {
1411 : Uri? nextLink,
1412 : String? idAccessToken,
1413 : String? idServer,
1414 : }) async {
1415 : final requestUri =
1416 0 : Uri(path: '_matrix/client/v3/account/password/email/requestToken');
1417 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
1418 0 : request.headers['content-type'] = 'application/json';
1419 0 : request.bodyBytes = utf8.encode(
1420 0 : jsonEncode({
1421 0 : 'client_secret': clientSecret,
1422 0 : 'email': email,
1423 0 : if (nextLink != null) 'next_link': nextLink.toString(),
1424 0 : 'send_attempt': sendAttempt,
1425 0 : if (idAccessToken != null) 'id_access_token': idAccessToken,
1426 0 : if (idServer != null) 'id_server': idServer,
1427 : }),
1428 : );
1429 0 : final response = await httpClient.send(request);
1430 0 : final responseBody = await response.stream.toBytes();
1431 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1432 0 : final responseString = utf8.decode(responseBody);
1433 0 : final json = jsonDecode(responseString);
1434 0 : return RequestTokenResponse.fromJson(json as Map<String, Object?>);
1435 : }
1436 :
1437 : /// The homeserver must check that the given phone number **is
1438 : /// associated** with an account on this homeserver. This API should be
1439 : /// used to request validation tokens when authenticating for the
1440 : /// `/account/password` endpoint.
1441 : ///
1442 : /// This API's parameters and response are identical to that of the
1443 : /// [`/register/msisdn/requestToken`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3registermsisdnrequesttoken)
1444 : /// endpoint, except that
1445 : /// `M_THREEPID_NOT_FOUND` may be returned if no account matching the
1446 : /// given phone number could be found. The server may instead send the SMS
1447 : /// to the given phone number prompting the user to create an account.
1448 : /// `M_THREEPID_IN_USE` may not be returned.
1449 : ///
1450 : /// The homeserver should validate the phone number itself, either by sending a
1451 : /// validation message itself or by using a service it has control over.
1452 : ///
1453 : /// [clientSecret] A unique string generated by the client, and used to identify the
1454 : /// validation attempt. It must be a string consisting of the characters
1455 : /// `[0-9a-zA-Z.=_-]`. Its length must not exceed 255 characters and it
1456 : /// must not be empty.
1457 : ///
1458 : ///
1459 : /// [country] The two-letter uppercase ISO-3166-1 alpha-2 country code that the
1460 : /// number in `phone_number` should be parsed as if it were dialled from.
1461 : ///
1462 : /// [nextLink] Optional. When the validation is completed, the identity server will
1463 : /// redirect the user to this URL. This option is ignored when submitting
1464 : /// 3PID validation information through a POST request.
1465 : ///
1466 : /// [phoneNumber] The phone number to validate.
1467 : ///
1468 : /// [sendAttempt] The server will only send an SMS if the `send_attempt` is a
1469 : /// number greater than the most recent one which it has seen,
1470 : /// scoped to that `country` + `phone_number` + `client_secret`
1471 : /// triple. This is to avoid repeatedly sending the same SMS in
1472 : /// the case of request retries between the POSTing user and the
1473 : /// identity server. The client should increment this value if
1474 : /// they desire a new SMS (e.g. a reminder) to be sent.
1475 : ///
1476 : /// [idAccessToken] An access token previously registered with the identity server. Servers
1477 : /// can treat this as optional to distinguish between r0.5-compatible clients
1478 : /// and this specification version.
1479 : ///
1480 : /// Required if an `id_server` is supplied.
1481 : ///
1482 : /// [idServer] The hostname of the identity server to communicate with. May optionally
1483 : /// include a port. This parameter is ignored when the homeserver handles
1484 : /// 3PID verification.
1485 : ///
1486 : /// This parameter is deprecated with a plan to be removed in a future specification
1487 : /// version for `/account/password` and `/register` requests.
1488 0 : Future<RequestTokenResponse> requestTokenToResetPasswordMSISDN(
1489 : String clientSecret,
1490 : String country,
1491 : String phoneNumber,
1492 : int sendAttempt, {
1493 : Uri? nextLink,
1494 : String? idAccessToken,
1495 : String? idServer,
1496 : }) async {
1497 : final requestUri =
1498 0 : Uri(path: '_matrix/client/v3/account/password/msisdn/requestToken');
1499 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
1500 0 : request.headers['content-type'] = 'application/json';
1501 0 : request.bodyBytes = utf8.encode(
1502 0 : jsonEncode({
1503 0 : 'client_secret': clientSecret,
1504 0 : 'country': country,
1505 0 : if (nextLink != null) 'next_link': nextLink.toString(),
1506 0 : 'phone_number': phoneNumber,
1507 0 : 'send_attempt': sendAttempt,
1508 0 : if (idAccessToken != null) 'id_access_token': idAccessToken,
1509 0 : if (idServer != null) 'id_server': idServer,
1510 : }),
1511 : );
1512 0 : final response = await httpClient.send(request);
1513 0 : final responseBody = await response.stream.toBytes();
1514 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1515 0 : final responseString = utf8.decode(responseBody);
1516 0 : final json = jsonDecode(responseString);
1517 0 : return RequestTokenResponse.fromJson(json as Map<String, Object?>);
1518 : }
1519 :
1520 : /// Gets information about the owner of a given access token.
1521 : ///
1522 : /// Note that, as with the rest of the Client-Server API,
1523 : /// Application Services may masquerade as users within their
1524 : /// namespace by giving a `user_id` query parameter. In this
1525 : /// situation, the server should verify that the given `user_id`
1526 : /// is registered by the appservice, and return it in the response
1527 : /// body.
1528 0 : Future<TokenOwnerInfo> getTokenOwner() async {
1529 0 : final requestUri = Uri(path: '_matrix/client/v3/account/whoami');
1530 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
1531 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1532 0 : final response = await httpClient.send(request);
1533 0 : final responseBody = await response.stream.toBytes();
1534 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1535 0 : final responseString = utf8.decode(responseBody);
1536 0 : final json = jsonDecode(responseString);
1537 0 : return TokenOwnerInfo.fromJson(json as Map<String, Object?>);
1538 : }
1539 :
1540 : /// Gets information about a particular user.
1541 : ///
1542 : /// This API may be restricted to only be called by the user being looked
1543 : /// up, or by a server admin. Server-local administrator privileges are not
1544 : /// specified in this document.
1545 : ///
1546 : /// [userId] The user to look up.
1547 0 : Future<WhoIsInfo> getWhoIs(String userId) async {
1548 0 : final requestUri = Uri(
1549 0 : path: '_matrix/client/v3/admin/whois/${Uri.encodeComponent(userId)}',
1550 : );
1551 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
1552 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1553 0 : final response = await httpClient.send(request);
1554 0 : final responseBody = await response.stream.toBytes();
1555 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1556 0 : final responseString = utf8.decode(responseBody);
1557 0 : final json = jsonDecode(responseString);
1558 0 : return WhoIsInfo.fromJson(json as Map<String, Object?>);
1559 : }
1560 :
1561 : /// Gets information about the server's supported feature set
1562 : /// and other relevant capabilities.
1563 : ///
1564 : /// returns `capabilities`:
1565 : /// The custom capabilities the server supports, using the
1566 : /// Java package naming convention.
1567 0 : Future<Capabilities> getCapabilities() async {
1568 0 : final requestUri = Uri(path: '_matrix/client/v3/capabilities');
1569 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
1570 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1571 0 : final response = await httpClient.send(request);
1572 0 : final responseBody = await response.stream.toBytes();
1573 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1574 0 : final responseString = utf8.decode(responseBody);
1575 0 : final json = jsonDecode(responseString);
1576 0 : return Capabilities.fromJson(json['capabilities'] as Map<String, Object?>);
1577 : }
1578 :
1579 : /// Create a new room with various configuration options.
1580 : ///
1581 : /// The server MUST apply the normal state resolution rules when creating
1582 : /// the new room, including checking power levels for each event. It MUST
1583 : /// apply the events implied by the request in the following order:
1584 : ///
1585 : /// 1. The `m.room.create` event itself. Must be the first event in the
1586 : /// room.
1587 : ///
1588 : /// 2. An `m.room.member` event for the creator to join the room. This is
1589 : /// needed so the remaining events can be sent.
1590 : ///
1591 : /// 3. A default `m.room.power_levels` event, giving the room creator
1592 : /// (and not other members) permission to send state events. Overridden
1593 : /// by the `power_level_content_override` parameter.
1594 : ///
1595 : /// 4. An `m.room.canonical_alias` event if `room_alias_name` is given.
1596 : ///
1597 : /// 5. Events set by the `preset`. Currently these are the `m.room.join_rules`,
1598 : /// `m.room.history_visibility`, and `m.room.guest_access` state events.
1599 : ///
1600 : /// 6. Events listed in `initial_state`, in the order that they are
1601 : /// listed.
1602 : ///
1603 : /// 7. Events implied by `name` and `topic` (`m.room.name` and `m.room.topic`
1604 : /// state events).
1605 : ///
1606 : /// 8. Invite events implied by `invite` and `invite_3pid` (`m.room.member` with
1607 : /// `membership: invite` and `m.room.third_party_invite`).
1608 : ///
1609 : /// The available presets do the following with respect to room state:
1610 : ///
1611 : /// | Preset | `join_rules` | `history_visibility` | `guest_access` | Other |
1612 : /// |------------------------|--------------|----------------------|----------------|-------|
1613 : /// | `private_chat` | `invite` | `shared` | `can_join` | |
1614 : /// | `trusted_private_chat` | `invite` | `shared` | `can_join` | All invitees are given the same power level as the room creator. |
1615 : /// | `public_chat` | `public` | `shared` | `forbidden` | |
1616 : ///
1617 : /// The server will create a `m.room.create` event in the room with the
1618 : /// requesting user as the creator, alongside other keys provided in the
1619 : /// `creation_content`.
1620 : ///
1621 : /// [creationContent] Extra keys, such as `m.federate`, to be added to the content
1622 : /// of the [`m.room.create`](https://spec.matrix.org/unstable/client-server-api/#mroomcreate) event. The server will overwrite the following
1623 : /// keys: `creator`, `room_version`. Future versions of the specification
1624 : /// may allow the server to overwrite other keys.
1625 : ///
1626 : /// [initialState] A list of state events to set in the new room. This allows
1627 : /// the user to override the default state events set in the new
1628 : /// room. The expected format of the state events are an object
1629 : /// with type, state_key and content keys set.
1630 : ///
1631 : /// Takes precedence over events set by `preset`, but gets
1632 : /// overridden by `name` and `topic` keys.
1633 : ///
1634 : /// [invite] A list of user IDs to invite to the room. This will tell the
1635 : /// server to invite everyone in the list to the newly created room.
1636 : ///
1637 : /// [invite3pid] A list of objects representing third-party IDs to invite into
1638 : /// the room.
1639 : ///
1640 : /// [isDirect] This flag makes the server set the `is_direct` flag on the
1641 : /// `m.room.member` events sent to the users in `invite` and
1642 : /// `invite_3pid`. See [Direct Messaging](https://spec.matrix.org/unstable/client-server-api/#direct-messaging) for more information.
1643 : ///
1644 : /// [name] If this is included, an `m.room.name` event will be sent
1645 : /// into the room to indicate the name of the room. See Room
1646 : /// Events for more information on `m.room.name`.
1647 : ///
1648 : /// [powerLevelContentOverride] The power level content to override in the default power level
1649 : /// event. This object is applied on top of the generated
1650 : /// [`m.room.power_levels`](https://spec.matrix.org/unstable/client-server-api/#mroompower_levels)
1651 : /// event content prior to it being sent to the room. Defaults to
1652 : /// overriding nothing.
1653 : ///
1654 : /// [preset] Convenience parameter for setting various default state events
1655 : /// based on a preset.
1656 : ///
1657 : /// If unspecified, the server should use the `visibility` to determine
1658 : /// which preset to use. A visibility of `public` equates to a preset of
1659 : /// `public_chat` and `private` visibility equates to a preset of
1660 : /// `private_chat`.
1661 : ///
1662 : /// [roomAliasName] The desired room alias **local part**. If this is included, a
1663 : /// room alias will be created and mapped to the newly created
1664 : /// room. The alias will belong on the *same* homeserver which
1665 : /// created the room. For example, if this was set to "foo" and
1666 : /// sent to the homeserver "example.com" the complete room alias
1667 : /// would be `#foo:example.com`.
1668 : ///
1669 : /// The complete room alias will become the canonical alias for
1670 : /// the room and an `m.room.canonical_alias` event will be sent
1671 : /// into the room.
1672 : ///
1673 : /// [roomVersion] The room version to set for the room. If not provided, the homeserver is
1674 : /// to use its configured default. If provided, the homeserver will return a
1675 : /// 400 error with the errcode `M_UNSUPPORTED_ROOM_VERSION` if it does not
1676 : /// support the room version.
1677 : ///
1678 : /// [topic] If this is included, an `m.room.topic` event will be sent
1679 : /// into the room to indicate the topic for the room. See Room
1680 : /// Events for more information on `m.room.topic`.
1681 : ///
1682 : /// [visibility] A `public` visibility indicates that the room will be shown
1683 : /// in the published room list. A `private` visibility will hide
1684 : /// the room from the published room list. Rooms default to
1685 : /// `private` visibility if this key is not included. NB: This
1686 : /// should not be confused with `join_rules` which also uses the
1687 : /// word `public`.
1688 : ///
1689 : /// returns `room_id`:
1690 : /// The created room's ID.
1691 6 : Future<String> createRoom({
1692 : Map<String, Object?>? creationContent,
1693 : List<StateEvent>? initialState,
1694 : List<String>? invite,
1695 : List<Invite3pid>? invite3pid,
1696 : bool? isDirect,
1697 : String? name,
1698 : Map<String, Object?>? powerLevelContentOverride,
1699 : CreateRoomPreset? preset,
1700 : String? roomAliasName,
1701 : String? roomVersion,
1702 : String? topic,
1703 : Visibility? visibility,
1704 : }) async {
1705 6 : final requestUri = Uri(path: '_matrix/client/v3/createRoom');
1706 18 : final request = Request('POST', baseUri!.resolveUri(requestUri));
1707 24 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1708 12 : request.headers['content-type'] = 'application/json';
1709 12 : request.bodyBytes = utf8.encode(
1710 12 : jsonEncode({
1711 1 : if (creationContent != null) 'creation_content': creationContent,
1712 : if (initialState != null)
1713 10 : 'initial_state': initialState.map((v) => v.toJson()).toList(),
1714 24 : if (invite != null) 'invite': invite.map((v) => v).toList(),
1715 : if (invite3pid != null)
1716 0 : 'invite_3pid': invite3pid.map((v) => v.toJson()).toList(),
1717 6 : if (isDirect != null) 'is_direct': isDirect,
1718 2 : if (name != null) 'name': name,
1719 : if (powerLevelContentOverride != null)
1720 1 : 'power_level_content_override': powerLevelContentOverride,
1721 12 : if (preset != null) 'preset': preset.name,
1722 1 : if (roomAliasName != null) 'room_alias_name': roomAliasName,
1723 1 : if (roomVersion != null) 'room_version': roomVersion,
1724 1 : if (topic != null) 'topic': topic,
1725 2 : if (visibility != null) 'visibility': visibility.name,
1726 : }),
1727 : );
1728 12 : final response = await httpClient.send(request);
1729 12 : final responseBody = await response.stream.toBytes();
1730 12 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1731 6 : final responseString = utf8.decode(responseBody);
1732 6 : final json = jsonDecode(responseString);
1733 6 : return json['room_id'] as String;
1734 : }
1735 :
1736 : /// This API endpoint uses the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api).
1737 : ///
1738 : /// Deletes the given devices, and invalidates any access token associated with them.
1739 : ///
1740 : /// [auth] Additional authentication information for the
1741 : /// user-interactive authentication API.
1742 : ///
1743 : /// [devices] The list of device IDs to delete.
1744 0 : Future<void> deleteDevices(
1745 : List<String> devices, {
1746 : AuthenticationData? auth,
1747 : }) async {
1748 0 : final requestUri = Uri(path: '_matrix/client/v3/delete_devices');
1749 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
1750 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1751 0 : request.headers['content-type'] = 'application/json';
1752 0 : request.bodyBytes = utf8.encode(
1753 0 : jsonEncode({
1754 0 : if (auth != null) 'auth': auth.toJson(),
1755 0 : 'devices': devices.map((v) => v).toList(),
1756 : }),
1757 : );
1758 0 : final response = await httpClient.send(request);
1759 0 : final responseBody = await response.stream.toBytes();
1760 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1761 0 : final responseString = utf8.decode(responseBody);
1762 0 : final json = jsonDecode(responseString);
1763 0 : return ignore(json);
1764 : }
1765 :
1766 : /// Gets information about all devices for the current user.
1767 : ///
1768 : /// returns `devices`:
1769 : /// A list of all registered devices for this user.
1770 0 : Future<List<Device>?> getDevices() async {
1771 0 : final requestUri = Uri(path: '_matrix/client/v3/devices');
1772 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
1773 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1774 0 : final response = await httpClient.send(request);
1775 0 : final responseBody = await response.stream.toBytes();
1776 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1777 0 : final responseString = utf8.decode(responseBody);
1778 0 : final json = jsonDecode(responseString);
1779 0 : return ((v) => v != null
1780 : ? (v as List)
1781 0 : .map((v) => Device.fromJson(v as Map<String, Object?>))
1782 0 : .toList()
1783 0 : : null)(json['devices']);
1784 : }
1785 :
1786 : /// This API endpoint uses the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api).
1787 : ///
1788 : /// Deletes the given device, and invalidates any access token associated with it.
1789 : ///
1790 : /// [deviceId] The device to delete.
1791 : ///
1792 : /// [auth] Additional authentication information for the
1793 : /// user-interactive authentication API.
1794 0 : Future<void> deleteDevice(String deviceId, {AuthenticationData? auth}) async {
1795 : final requestUri =
1796 0 : Uri(path: '_matrix/client/v3/devices/${Uri.encodeComponent(deviceId)}');
1797 0 : final request = Request('DELETE', baseUri!.resolveUri(requestUri));
1798 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1799 0 : request.headers['content-type'] = 'application/json';
1800 0 : request.bodyBytes = utf8.encode(
1801 0 : jsonEncode({
1802 0 : if (auth != null) 'auth': auth.toJson(),
1803 : }),
1804 : );
1805 0 : final response = await httpClient.send(request);
1806 0 : final responseBody = await response.stream.toBytes();
1807 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1808 0 : final responseString = utf8.decode(responseBody);
1809 0 : final json = jsonDecode(responseString);
1810 0 : return ignore(json);
1811 : }
1812 :
1813 : /// Gets information on a single device, by device id.
1814 : ///
1815 : /// [deviceId] The device to retrieve.
1816 0 : Future<Device> getDevice(String deviceId) async {
1817 : final requestUri =
1818 0 : Uri(path: '_matrix/client/v3/devices/${Uri.encodeComponent(deviceId)}');
1819 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
1820 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1821 0 : final response = await httpClient.send(request);
1822 0 : final responseBody = await response.stream.toBytes();
1823 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1824 0 : final responseString = utf8.decode(responseBody);
1825 0 : final json = jsonDecode(responseString);
1826 0 : return Device.fromJson(json as Map<String, Object?>);
1827 : }
1828 :
1829 : /// Updates the metadata on the given device.
1830 : ///
1831 : /// [deviceId] The device to update.
1832 : ///
1833 : /// [displayName] The new display name for this device. If not given, the
1834 : /// display name is unchanged.
1835 0 : Future<void> updateDevice(String deviceId, {String? displayName}) async {
1836 : final requestUri =
1837 0 : Uri(path: '_matrix/client/v3/devices/${Uri.encodeComponent(deviceId)}');
1838 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
1839 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1840 0 : request.headers['content-type'] = 'application/json';
1841 0 : request.bodyBytes = utf8.encode(
1842 0 : jsonEncode({
1843 0 : if (displayName != null) 'display_name': displayName,
1844 : }),
1845 : );
1846 0 : final response = await httpClient.send(request);
1847 0 : final responseBody = await response.stream.toBytes();
1848 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1849 0 : final responseString = utf8.decode(responseBody);
1850 0 : final json = jsonDecode(responseString);
1851 0 : return ignore(json);
1852 : }
1853 :
1854 : /// Updates the visibility of a given room on the application service's room
1855 : /// directory.
1856 : ///
1857 : /// This API is similar to the room directory visibility API used by clients
1858 : /// to update the homeserver's more general room directory.
1859 : ///
1860 : /// This API requires the use of an application service access token (`as_token`)
1861 : /// instead of a typical client's access_token. This API cannot be invoked by
1862 : /// users who are not identified as application services.
1863 : ///
1864 : /// [networkId] The protocol (network) ID to update the room list for. This would
1865 : /// have been provided by the application service as being listed as
1866 : /// a supported protocol.
1867 : ///
1868 : /// [roomId] The room ID to add to the directory.
1869 : ///
1870 : /// [visibility] Whether the room should be visible (public) in the directory
1871 : /// or not (private).
1872 0 : Future<Map<String, Object?>> updateAppserviceRoomDirectoryVisibility(
1873 : String networkId,
1874 : String roomId,
1875 : Visibility visibility,
1876 : ) async {
1877 0 : final requestUri = Uri(
1878 : path:
1879 0 : '_matrix/client/v3/directory/list/appservice/${Uri.encodeComponent(networkId)}/${Uri.encodeComponent(roomId)}',
1880 : );
1881 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
1882 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1883 0 : request.headers['content-type'] = 'application/json';
1884 0 : request.bodyBytes = utf8.encode(
1885 0 : jsonEncode({
1886 0 : 'visibility': visibility.name,
1887 : }),
1888 : );
1889 0 : final response = await httpClient.send(request);
1890 0 : final responseBody = await response.stream.toBytes();
1891 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1892 0 : final responseString = utf8.decode(responseBody);
1893 0 : final json = jsonDecode(responseString);
1894 : return json as Map<String, Object?>;
1895 : }
1896 :
1897 : /// Gets the visibility of a given room on the server's public room directory.
1898 : ///
1899 : /// [roomId] The room ID.
1900 : ///
1901 : /// returns `visibility`:
1902 : /// The visibility of the room in the directory.
1903 0 : Future<Visibility?> getRoomVisibilityOnDirectory(String roomId) async {
1904 0 : final requestUri = Uri(
1905 : path:
1906 0 : '_matrix/client/v3/directory/list/room/${Uri.encodeComponent(roomId)}',
1907 : );
1908 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
1909 0 : final response = await httpClient.send(request);
1910 0 : final responseBody = await response.stream.toBytes();
1911 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1912 0 : final responseString = utf8.decode(responseBody);
1913 0 : final json = jsonDecode(responseString);
1914 0 : return ((v) => v != null
1915 0 : ? Visibility.values.fromString(v as String)!
1916 0 : : null)(json['visibility']);
1917 : }
1918 :
1919 : /// Sets the visibility of a given room in the server's public room
1920 : /// directory.
1921 : ///
1922 : /// Servers may choose to implement additional access control checks
1923 : /// here, for instance that room visibility can only be changed by
1924 : /// the room creator or a server administrator.
1925 : ///
1926 : /// [roomId] The room ID.
1927 : ///
1928 : /// [visibility] The new visibility setting for the room.
1929 : /// Defaults to 'public'.
1930 0 : Future<void> setRoomVisibilityOnDirectory(
1931 : String roomId, {
1932 : Visibility? visibility,
1933 : }) async {
1934 0 : final requestUri = Uri(
1935 : path:
1936 0 : '_matrix/client/v3/directory/list/room/${Uri.encodeComponent(roomId)}',
1937 : );
1938 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
1939 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1940 0 : request.headers['content-type'] = 'application/json';
1941 0 : request.bodyBytes = utf8.encode(
1942 0 : jsonEncode({
1943 0 : if (visibility != null) 'visibility': visibility.name,
1944 : }),
1945 : );
1946 0 : final response = await httpClient.send(request);
1947 0 : final responseBody = await response.stream.toBytes();
1948 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1949 0 : final responseString = utf8.decode(responseBody);
1950 0 : final json = jsonDecode(responseString);
1951 0 : return ignore(json);
1952 : }
1953 :
1954 : /// Remove a mapping of room alias to room ID.
1955 : ///
1956 : /// Servers may choose to implement additional access control checks here, for instance that
1957 : /// room aliases can only be deleted by their creator or a server administrator.
1958 : ///
1959 : /// **Note:**
1960 : /// Servers may choose to update the `alt_aliases` for the `m.room.canonical_alias`
1961 : /// state event in the room when an alias is removed. Servers which choose to update the
1962 : /// canonical alias event are recommended to, in addition to their other relevant permission
1963 : /// checks, delete the alias and return a successful response even if the user does not
1964 : /// have permission to update the `m.room.canonical_alias` event.
1965 : ///
1966 : /// [roomAlias] The room alias to remove. Its format is defined
1967 : /// [in the appendices](https://spec.matrix.org/unstable/appendices/#room-aliases).
1968 : ///
1969 0 : Future<void> deleteRoomAlias(String roomAlias) async {
1970 0 : final requestUri = Uri(
1971 : path:
1972 0 : '_matrix/client/v3/directory/room/${Uri.encodeComponent(roomAlias)}',
1973 : );
1974 0 : final request = Request('DELETE', baseUri!.resolveUri(requestUri));
1975 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
1976 0 : final response = await httpClient.send(request);
1977 0 : final responseBody = await response.stream.toBytes();
1978 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
1979 0 : final responseString = utf8.decode(responseBody);
1980 0 : final json = jsonDecode(responseString);
1981 0 : return ignore(json);
1982 : }
1983 :
1984 : /// Requests that the server resolve a room alias to a room ID.
1985 : ///
1986 : /// The server will use the federation API to resolve the alias if the
1987 : /// domain part of the alias does not correspond to the server's own
1988 : /// domain.
1989 : ///
1990 : /// [roomAlias] The room alias. Its format is defined
1991 : /// [in the appendices](https://spec.matrix.org/unstable/appendices/#room-aliases).
1992 : ///
1993 0 : Future<GetRoomIdByAliasResponse> getRoomIdByAlias(String roomAlias) async {
1994 0 : final requestUri = Uri(
1995 : path:
1996 0 : '_matrix/client/v3/directory/room/${Uri.encodeComponent(roomAlias)}',
1997 : );
1998 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
1999 0 : final response = await httpClient.send(request);
2000 0 : final responseBody = await response.stream.toBytes();
2001 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2002 0 : final responseString = utf8.decode(responseBody);
2003 0 : final json = jsonDecode(responseString);
2004 0 : return GetRoomIdByAliasResponse.fromJson(json as Map<String, Object?>);
2005 : }
2006 :
2007 : ///
2008 : ///
2009 : /// [roomAlias] The room alias to set. Its format is defined
2010 : /// [in the appendices](https://spec.matrix.org/unstable/appendices/#room-aliases).
2011 : ///
2012 : ///
2013 : /// [roomId] The room ID to set.
2014 0 : Future<void> setRoomAlias(String roomAlias, String roomId) async {
2015 0 : final requestUri = Uri(
2016 : path:
2017 0 : '_matrix/client/v3/directory/room/${Uri.encodeComponent(roomAlias)}',
2018 : );
2019 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
2020 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2021 0 : request.headers['content-type'] = 'application/json';
2022 0 : request.bodyBytes = utf8.encode(
2023 0 : jsonEncode({
2024 : 'room_id': roomId,
2025 : }),
2026 : );
2027 0 : final response = await httpClient.send(request);
2028 0 : final responseBody = await response.stream.toBytes();
2029 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2030 0 : final responseString = utf8.decode(responseBody);
2031 0 : final json = jsonDecode(responseString);
2032 0 : return ignore(json);
2033 : }
2034 :
2035 : /// This will listen for new events and return them to the caller. This will
2036 : /// block until an event is received, or until the `timeout` is reached.
2037 : ///
2038 : /// This endpoint was deprecated in r0 of this specification. Clients
2039 : /// should instead call the [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync)
2040 : /// endpoint with a `since` parameter. See
2041 : /// the [migration guide](https://matrix.org/docs/guides/migrating-from-client-server-api-v-1#deprecated-endpoints).
2042 : ///
2043 : /// [from] The token to stream from. This token is either from a previous
2044 : /// request to this API or from the initial sync API.
2045 : ///
2046 : /// [timeout] The maximum time in milliseconds to wait for an event.
2047 0 : @deprecated
2048 : Future<GetEventsResponse> getEvents({String? from, int? timeout}) async {
2049 0 : final requestUri = Uri(
2050 : path: '_matrix/client/v3/events',
2051 0 : queryParameters: {
2052 0 : if (from != null) 'from': from,
2053 0 : if (timeout != null) 'timeout': timeout.toString(),
2054 : },
2055 : );
2056 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2057 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2058 0 : final response = await httpClient.send(request);
2059 0 : final responseBody = await response.stream.toBytes();
2060 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2061 0 : final responseString = utf8.decode(responseBody);
2062 0 : final json = jsonDecode(responseString);
2063 0 : return GetEventsResponse.fromJson(json as Map<String, Object?>);
2064 : }
2065 :
2066 : /// This will listen for new events related to a particular room and return
2067 : /// them to the caller. This will block until an event is received, or until
2068 : /// the `timeout` is reached.
2069 : ///
2070 : /// This API is the same as the normal `/events` endpoint, but can be
2071 : /// called by users who have not joined the room.
2072 : ///
2073 : /// Note that the normal `/events` endpoint has been deprecated. This
2074 : /// API will also be deprecated at some point, but its replacement is not
2075 : /// yet known.
2076 : ///
2077 : /// [from] The token to stream from. This token is either from a previous
2078 : /// request to this API or from the initial sync API.
2079 : ///
2080 : /// [timeout] The maximum time in milliseconds to wait for an event.
2081 : ///
2082 : /// [roomId] The room ID for which events should be returned.
2083 0 : Future<PeekEventsResponse> peekEvents({
2084 : String? from,
2085 : int? timeout,
2086 : String? roomId,
2087 : }) async {
2088 0 : final requestUri = Uri(
2089 : path: '_matrix/client/v3/events',
2090 0 : queryParameters: {
2091 0 : if (from != null) 'from': from,
2092 0 : if (timeout != null) 'timeout': timeout.toString(),
2093 0 : if (roomId != null) 'room_id': roomId,
2094 : },
2095 : );
2096 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2097 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2098 0 : final response = await httpClient.send(request);
2099 0 : final responseBody = await response.stream.toBytes();
2100 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2101 0 : final responseString = utf8.decode(responseBody);
2102 0 : final json = jsonDecode(responseString);
2103 0 : return PeekEventsResponse.fromJson(json as Map<String, Object?>);
2104 : }
2105 :
2106 : /// Get a single event based on `event_id`. You must have permission to
2107 : /// retrieve this event e.g. by being a member in the room for this event.
2108 : ///
2109 : /// This endpoint was deprecated in r0 of this specification. Clients
2110 : /// should instead call the
2111 : /// [/rooms/{roomId}/event/{eventId}](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3roomsroomideventeventid) API
2112 : /// or the [/rooms/{roomId}/context/{eventId](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3roomsroomidcontexteventid) API.
2113 : ///
2114 : /// [eventId] The event ID to get.
2115 0 : @deprecated
2116 : Future<MatrixEvent> getOneEvent(String eventId) async {
2117 : final requestUri =
2118 0 : Uri(path: '_matrix/client/v3/events/${Uri.encodeComponent(eventId)}');
2119 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2120 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2121 0 : final response = await httpClient.send(request);
2122 0 : final responseBody = await response.stream.toBytes();
2123 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2124 0 : final responseString = utf8.decode(responseBody);
2125 0 : final json = jsonDecode(responseString);
2126 0 : return MatrixEvent.fromJson(json as Map<String, Object?>);
2127 : }
2128 :
2129 : /// *Note that this API takes either a room ID or alias, unlike* `/rooms/{roomId}/join`.
2130 : ///
2131 : /// This API starts a user's participation in a particular room, if that user
2132 : /// is allowed to participate in that room. After this call, the client is
2133 : /// allowed to see all current state events in the room, and all subsequent
2134 : /// events associated with the room until the user leaves the room.
2135 : ///
2136 : /// After a user has joined a room, the room will appear as an entry in the
2137 : /// response of the [`/initialSync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3initialsync)
2138 : /// and [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync) APIs.
2139 : ///
2140 : /// [roomIdOrAlias] The room identifier or alias to join.
2141 : ///
2142 : /// [via] The servers to attempt to join the room through. One of the servers
2143 : /// must be participating in the room.
2144 : ///
2145 : /// [reason] Optional reason to be included as the `reason` on the subsequent
2146 : /// membership event.
2147 : ///
2148 : /// [thirdPartySigned] If a `third_party_signed` was supplied, the homeserver must verify
2149 : /// that it matches a pending `m.room.third_party_invite` event in the
2150 : /// room, and perform key validity checking if required by the event.
2151 : ///
2152 : /// returns `room_id`:
2153 : /// The joined room ID.
2154 1 : Future<String> joinRoom(
2155 : String roomIdOrAlias, {
2156 : List<String>? via,
2157 : String? reason,
2158 : ThirdPartySigned? thirdPartySigned,
2159 : }) async {
2160 1 : final requestUri = Uri(
2161 2 : path: '_matrix/client/v3/join/${Uri.encodeComponent(roomIdOrAlias)}',
2162 1 : queryParameters: {
2163 0 : if (via != null) 'via': via,
2164 : },
2165 : );
2166 3 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2167 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2168 2 : request.headers['content-type'] = 'application/json';
2169 2 : request.bodyBytes = utf8.encode(
2170 2 : jsonEncode({
2171 0 : if (reason != null) 'reason': reason,
2172 : if (thirdPartySigned != null)
2173 0 : 'third_party_signed': thirdPartySigned.toJson(),
2174 : }),
2175 : );
2176 2 : final response = await httpClient.send(request);
2177 2 : final responseBody = await response.stream.toBytes();
2178 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2179 1 : final responseString = utf8.decode(responseBody);
2180 1 : final json = jsonDecode(responseString);
2181 1 : return json['room_id'] as String;
2182 : }
2183 :
2184 : /// This API returns a list of the user's current rooms.
2185 : ///
2186 : /// returns `joined_rooms`:
2187 : /// The ID of each room in which the user has `joined` membership.
2188 0 : Future<List<String>> getJoinedRooms() async {
2189 0 : final requestUri = Uri(path: '_matrix/client/v3/joined_rooms');
2190 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2191 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2192 0 : final response = await httpClient.send(request);
2193 0 : final responseBody = await response.stream.toBytes();
2194 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2195 0 : final responseString = utf8.decode(responseBody);
2196 0 : final json = jsonDecode(responseString);
2197 0 : return (json['joined_rooms'] as List).map((v) => v as String).toList();
2198 : }
2199 :
2200 : /// Gets a list of users who have updated their device identity keys since a
2201 : /// previous sync token.
2202 : ///
2203 : /// The server should include in the results any users who:
2204 : ///
2205 : /// * currently share a room with the calling user (ie, both users have
2206 : /// membership state `join`); *and*
2207 : /// * added new device identity keys or removed an existing device with
2208 : /// identity keys, between `from` and `to`.
2209 : ///
2210 : /// [from] The desired start point of the list. Should be the `next_batch` field
2211 : /// from a response to an earlier call to [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync). Users who have not
2212 : /// uploaded new device identity keys since this point, nor deleted
2213 : /// existing devices with identity keys since then, will be excluded
2214 : /// from the results.
2215 : ///
2216 : /// [to] The desired end point of the list. Should be the `next_batch`
2217 : /// field from a recent call to [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync) - typically the most recent
2218 : /// such call. This may be used by the server as a hint to check its
2219 : /// caches are up to date.
2220 0 : Future<GetKeysChangesResponse> getKeysChanges(String from, String to) async {
2221 0 : final requestUri = Uri(
2222 : path: '_matrix/client/v3/keys/changes',
2223 0 : queryParameters: {
2224 : 'from': from,
2225 : 'to': to,
2226 : },
2227 : );
2228 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2229 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2230 0 : final response = await httpClient.send(request);
2231 0 : final responseBody = await response.stream.toBytes();
2232 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2233 0 : final responseString = utf8.decode(responseBody);
2234 0 : final json = jsonDecode(responseString);
2235 0 : return GetKeysChangesResponse.fromJson(json as Map<String, Object?>);
2236 : }
2237 :
2238 : /// Claims one-time keys for use in pre-key messages.
2239 : ///
2240 : /// The request contains the user ID, device ID and algorithm name of the
2241 : /// keys that are required. If a key matching these requirements can be
2242 : /// found, the response contains it. The returned key is a one-time key
2243 : /// if one is available, and otherwise a fallback key.
2244 : ///
2245 : /// One-time keys are given out in the order that they were uploaded via
2246 : /// [/keys/upload](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3keysupload). (All
2247 : /// keys uploaded within a given call to `/keys/upload` are considered
2248 : /// equivalent in this regard; no ordering is specified within them.)
2249 : ///
2250 : /// Servers must ensure that each one-time key is returned at most once,
2251 : /// so when a key has been returned, no other request will ever return
2252 : /// the same key.
2253 : ///
2254 : /// [oneTimeKeys] The keys to be claimed. A map from user ID, to a map from
2255 : /// device ID to algorithm name.
2256 : ///
2257 : /// [timeout] The time (in milliseconds) to wait when downloading keys from
2258 : /// remote servers. 10 seconds is the recommended default.
2259 10 : Future<ClaimKeysResponse> claimKeys(
2260 : Map<String, Map<String, String>> oneTimeKeys, {
2261 : int? timeout,
2262 : }) async {
2263 10 : final requestUri = Uri(path: '_matrix/client/v3/keys/claim');
2264 30 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2265 40 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2266 20 : request.headers['content-type'] = 'application/json';
2267 20 : request.bodyBytes = utf8.encode(
2268 20 : jsonEncode({
2269 10 : 'one_time_keys': oneTimeKeys
2270 60 : .map((k, v) => MapEntry(k, v.map((k, v) => MapEntry(k, v)))),
2271 10 : if (timeout != null) 'timeout': timeout,
2272 : }),
2273 : );
2274 20 : final response = await httpClient.send(request);
2275 20 : final responseBody = await response.stream.toBytes();
2276 20 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2277 10 : final responseString = utf8.decode(responseBody);
2278 10 : final json = jsonDecode(responseString);
2279 10 : return ClaimKeysResponse.fromJson(json as Map<String, Object?>);
2280 : }
2281 :
2282 : /// Publishes cross-signing keys for the user.
2283 : ///
2284 : /// This API endpoint uses the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api).
2285 : ///
2286 : /// User-Interactive Authentication MUST be performed, except in these cases:
2287 : /// - there is no existing cross-signing master key uploaded to the homeserver, OR
2288 : /// - there is an existing cross-signing master key and it exactly matches the
2289 : /// cross-signing master key provided in the request body. If there are any additional
2290 : /// keys provided in the request (self-signing key, user-signing key) they MUST also
2291 : /// match the existing keys stored on the server. In other words, the request contains
2292 : /// no new keys.
2293 : ///
2294 : /// This allows clients to freely upload one set of keys, but not modify/overwrite keys if
2295 : /// they already exist. Allowing clients to upload the same set of keys more than once
2296 : /// makes this endpoint idempotent in the case where the response is lost over the network,
2297 : /// which would otherwise cause a UIA challenge upon retry.
2298 : ///
2299 : /// [auth] Additional authentication information for the
2300 : /// user-interactive authentication API.
2301 : ///
2302 : /// [masterKey] Optional. The user\'s master key.
2303 : ///
2304 : /// [selfSigningKey] Optional. The user\'s self-signing key. Must be signed by
2305 : /// the accompanying master key, or by the user\'s most recently
2306 : /// uploaded master key if no master key is included in the
2307 : /// request.
2308 : ///
2309 : /// [userSigningKey] Optional. The user\'s user-signing key. Must be signed by
2310 : /// the accompanying master key, or by the user\'s most recently
2311 : /// uploaded master key if no master key is included in the
2312 : /// request.
2313 1 : Future<void> uploadCrossSigningKeys({
2314 : AuthenticationData? auth,
2315 : MatrixCrossSigningKey? masterKey,
2316 : MatrixCrossSigningKey? selfSigningKey,
2317 : MatrixCrossSigningKey? userSigningKey,
2318 : }) async {
2319 : final requestUri =
2320 1 : Uri(path: '_matrix/client/v3/keys/device_signing/upload');
2321 3 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2322 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2323 2 : request.headers['content-type'] = 'application/json';
2324 2 : request.bodyBytes = utf8.encode(
2325 2 : jsonEncode({
2326 0 : if (auth != null) 'auth': auth.toJson(),
2327 2 : if (masterKey != null) 'master_key': masterKey.toJson(),
2328 2 : if (selfSigningKey != null) 'self_signing_key': selfSigningKey.toJson(),
2329 2 : if (userSigningKey != null) 'user_signing_key': userSigningKey.toJson(),
2330 : }),
2331 : );
2332 2 : final response = await httpClient.send(request);
2333 2 : final responseBody = await response.stream.toBytes();
2334 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2335 1 : final responseString = utf8.decode(responseBody);
2336 1 : final json = jsonDecode(responseString);
2337 1 : return ignore(json);
2338 : }
2339 :
2340 : /// Returns the current devices and identity keys for the given users.
2341 : ///
2342 : /// [deviceKeys] The keys to be downloaded. A map from user ID, to a list of
2343 : /// device IDs, or to an empty list to indicate all devices for the
2344 : /// corresponding user.
2345 : ///
2346 : /// [timeout] The time (in milliseconds) to wait when downloading keys from
2347 : /// remote servers. 10 seconds is the recommended default.
2348 35 : Future<QueryKeysResponse> queryKeys(
2349 : Map<String, List<String>> deviceKeys, {
2350 : int? timeout,
2351 : }) async {
2352 35 : final requestUri = Uri(path: '_matrix/client/v3/keys/query');
2353 105 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2354 140 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2355 70 : request.headers['content-type'] = 'application/json';
2356 70 : request.bodyBytes = utf8.encode(
2357 70 : jsonEncode({
2358 35 : 'device_keys':
2359 175 : deviceKeys.map((k, v) => MapEntry(k, v.map((v) => v).toList())),
2360 35 : if (timeout != null) 'timeout': timeout,
2361 : }),
2362 : );
2363 70 : final response = await httpClient.send(request);
2364 70 : final responseBody = await response.stream.toBytes();
2365 70 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2366 35 : final responseString = utf8.decode(responseBody);
2367 35 : final json = jsonDecode(responseString);
2368 35 : return QueryKeysResponse.fromJson(json as Map<String, Object?>);
2369 : }
2370 :
2371 : /// Publishes cross-signing signatures for the user.
2372 : ///
2373 : /// The signed JSON object must match the key previously uploaded or
2374 : /// retrieved for the given key ID, with the exception of the `signatures`
2375 : /// property, which contains the new signature(s) to add.
2376 : ///
2377 : /// [body] A map from user ID to key ID to signed JSON objects containing the
2378 : /// signatures to be published.
2379 : ///
2380 : /// returns `failures`:
2381 : /// A map from user ID to key ID to an error for any signatures
2382 : /// that failed. If a signature was invalid, the `errcode` will
2383 : /// be set to `M_INVALID_SIGNATURE`.
2384 7 : Future<Map<String, Map<String, Map<String, Object?>>>?>
2385 : uploadCrossSigningSignatures(
2386 : Map<String, Map<String, Map<String, Object?>>> body,
2387 : ) async {
2388 7 : final requestUri = Uri(path: '_matrix/client/v3/keys/signatures/upload');
2389 21 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2390 28 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2391 14 : request.headers['content-type'] = 'application/json';
2392 14 : request.bodyBytes = utf8.encode(
2393 7 : jsonEncode(
2394 42 : body.map((k, v) => MapEntry(k, v.map((k, v) => MapEntry(k, v)))),
2395 : ),
2396 : );
2397 14 : final response = await httpClient.send(request);
2398 14 : final responseBody = await response.stream.toBytes();
2399 14 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2400 7 : final responseString = utf8.decode(responseBody);
2401 7 : final json = jsonDecode(responseString);
2402 7 : return ((v) => v != null
2403 7 : ? (v as Map<String, Object?>).map(
2404 0 : (k, v) => MapEntry(
2405 : k,
2406 : (v as Map<String, Object?>)
2407 0 : .map((k, v) => MapEntry(k, v as Map<String, Object?>)),
2408 : ),
2409 : )
2410 14 : : null)(json['failures']);
2411 : }
2412 :
2413 : /// Publishes end-to-end encryption keys for the device.
2414 : ///
2415 : /// [deviceKeys] Identity keys for the device. May be absent if no new
2416 : /// identity keys are required.
2417 : ///
2418 : /// [fallbackKeys] The public key which should be used if the device's one-time keys
2419 : /// are exhausted. The fallback key is not deleted once used, but should
2420 : /// be replaced when additional one-time keys are being uploaded. The
2421 : /// server will notify the client of the fallback key being used through
2422 : /// `/sync`.
2423 : ///
2424 : /// There can only be at most one key per algorithm uploaded, and the server
2425 : /// will only persist one key per algorithm.
2426 : ///
2427 : /// When uploading a signed key, an additional `fallback: true` key should
2428 : /// be included to denote that the key is a fallback key.
2429 : ///
2430 : /// May be absent if a new fallback key is not required.
2431 : ///
2432 : /// [oneTimeKeys] One-time public keys for "pre-key" messages. The names of
2433 : /// the properties should be in the format
2434 : /// `<algorithm>:<key_id>`. The format of the key is determined
2435 : /// by the [key algorithm](https://spec.matrix.org/unstable/client-server-api/#key-algorithms).
2436 : ///
2437 : /// May be absent if no new one-time keys are required.
2438 : ///
2439 : /// returns `one_time_key_counts`:
2440 : /// For each key algorithm, the number of unclaimed one-time keys
2441 : /// of that type currently held on the server for this device.
2442 : /// If an algorithm is not listed, the count for that algorithm
2443 : /// is to be assumed zero.
2444 5 : Future<Map<String, int>> uploadKeys({
2445 : MatrixDeviceKeys? deviceKeys,
2446 : Map<String, Object?>? fallbackKeys,
2447 : Map<String, Object?>? oneTimeKeys,
2448 : }) async {
2449 5 : final requestUri = Uri(path: '_matrix/client/v3/keys/upload');
2450 15 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2451 20 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2452 10 : request.headers['content-type'] = 'application/json';
2453 10 : request.bodyBytes = utf8.encode(
2454 10 : jsonEncode({
2455 10 : if (deviceKeys != null) 'device_keys': deviceKeys.toJson(),
2456 5 : if (fallbackKeys != null) 'fallback_keys': fallbackKeys,
2457 5 : if (oneTimeKeys != null) 'one_time_keys': oneTimeKeys,
2458 : }),
2459 : );
2460 10 : final response = await httpClient.send(request);
2461 10 : final responseBody = await response.stream.toBytes();
2462 10 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2463 5 : final responseString = utf8.decode(responseBody);
2464 5 : final json = jsonDecode(responseString);
2465 5 : return (json['one_time_key_counts'] as Map<String, Object?>)
2466 15 : .map((k, v) => MapEntry(k, v as int));
2467 : }
2468 :
2469 : /// *Note that this API takes either a room ID or alias, unlike other membership APIs.*
2470 : ///
2471 : /// This API "knocks" on the room to ask for permission to join, if the user
2472 : /// is allowed to knock on the room. Acceptance of the knock happens out of
2473 : /// band from this API, meaning that the client will have to watch for updates
2474 : /// regarding the acceptance/rejection of the knock.
2475 : ///
2476 : /// If the room history settings allow, the user will still be able to see
2477 : /// history of the room while being in the "knock" state. The user will have
2478 : /// to accept the invitation to join the room (acceptance of knock) to see
2479 : /// messages reliably. See the `/join` endpoints for more information about
2480 : /// history visibility to the user.
2481 : ///
2482 : /// The knock will appear as an entry in the response of the
2483 : /// [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync) API.
2484 : ///
2485 : /// [roomIdOrAlias] The room identifier or alias to knock upon.
2486 : ///
2487 : /// [via] The servers to attempt to knock on the room through. One of the servers
2488 : /// must be participating in the room.
2489 : ///
2490 : /// [reason] Optional reason to be included as the `reason` on the subsequent
2491 : /// membership event.
2492 : ///
2493 : /// returns `room_id`:
2494 : /// The knocked room ID.
2495 0 : Future<String> knockRoom(
2496 : String roomIdOrAlias, {
2497 : List<String>? via,
2498 : String? reason,
2499 : }) async {
2500 0 : final requestUri = Uri(
2501 0 : path: '_matrix/client/v3/knock/${Uri.encodeComponent(roomIdOrAlias)}',
2502 0 : queryParameters: {
2503 0 : if (via != null) 'via': via,
2504 : },
2505 : );
2506 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2507 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2508 0 : request.headers['content-type'] = 'application/json';
2509 0 : request.bodyBytes = utf8.encode(
2510 0 : jsonEncode({
2511 0 : if (reason != null) 'reason': reason,
2512 : }),
2513 : );
2514 0 : final response = await httpClient.send(request);
2515 0 : final responseBody = await response.stream.toBytes();
2516 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2517 0 : final responseString = utf8.decode(responseBody);
2518 0 : final json = jsonDecode(responseString);
2519 0 : return json['room_id'] as String;
2520 : }
2521 :
2522 : /// Gets the homeserver's supported login types to authenticate users. Clients
2523 : /// should pick one of these and supply it as the `type` when logging in.
2524 : ///
2525 : /// returns `flows`:
2526 : /// The homeserver's supported login types
2527 37 : Future<List<LoginFlow>?> getLoginFlows() async {
2528 37 : final requestUri = Uri(path: '_matrix/client/v3/login');
2529 111 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2530 74 : final response = await httpClient.send(request);
2531 74 : final responseBody = await response.stream.toBytes();
2532 74 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2533 37 : final responseString = utf8.decode(responseBody);
2534 37 : final json = jsonDecode(responseString);
2535 37 : return ((v) => v != null
2536 : ? (v as List)
2537 111 : .map((v) => LoginFlow.fromJson(v as Map<String, Object?>))
2538 37 : .toList()
2539 74 : : null)(json['flows']);
2540 : }
2541 :
2542 : /// Authenticates the user, and issues an access token they can
2543 : /// use to authorize themself in subsequent requests.
2544 : ///
2545 : /// If the client does not supply a `device_id`, the server must
2546 : /// auto-generate one.
2547 : ///
2548 : /// The returned access token must be associated with the `device_id`
2549 : /// supplied by the client or generated by the server. The server may
2550 : /// invalidate any access token previously associated with that device. See
2551 : /// [Relationship between access tokens and devices](https://spec.matrix.org/unstable/client-server-api/#relationship-between-access-tokens-and-devices).
2552 : ///
2553 : /// [address] Third-party identifier for the user. Deprecated in favour of `identifier`.
2554 : ///
2555 : /// [deviceId] ID of the client device. If this does not correspond to a
2556 : /// known client device, a new device will be created. The given
2557 : /// device ID must not be the same as a
2558 : /// [cross-signing](https://spec.matrix.org/unstable/client-server-api/#cross-signing) key ID.
2559 : /// The server will auto-generate a device_id
2560 : /// if this is not specified.
2561 : ///
2562 : /// [identifier] Identification information for a user
2563 : ///
2564 : /// [initialDeviceDisplayName] A display name to assign to the newly-created device. Ignored
2565 : /// if `device_id` corresponds to a known device.
2566 : ///
2567 : /// [medium] When logging in using a third-party identifier, the medium of the identifier. Must be 'email'. Deprecated in favour of `identifier`.
2568 : ///
2569 : /// [password] Required when `type` is `m.login.password`. The user's
2570 : /// password.
2571 : ///
2572 : /// [refreshToken] If true, the client supports refresh tokens.
2573 : ///
2574 : /// [token] Required when `type` is `m.login.token`. Part of Token-based login.
2575 : ///
2576 : /// [type] The login type being used.
2577 : ///
2578 : /// This must be a type returned in one of the flows of the
2579 : /// response of the [`GET /login`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3login)
2580 : /// endpoint, like `m.login.password` or `m.login.token`.
2581 : ///
2582 : /// [user] The fully qualified user ID or just local part of the user ID, to log in. Deprecated in favour of `identifier`.
2583 5 : Future<LoginResponse> login(
2584 : String type, {
2585 : String? address,
2586 : String? deviceId,
2587 : AuthenticationIdentifier? identifier,
2588 : String? initialDeviceDisplayName,
2589 : String? medium,
2590 : String? password,
2591 : bool? refreshToken,
2592 : String? token,
2593 : String? user,
2594 : }) async {
2595 5 : final requestUri = Uri(path: '_matrix/client/v3/login');
2596 15 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2597 10 : request.headers['content-type'] = 'application/json';
2598 10 : request.bodyBytes = utf8.encode(
2599 10 : jsonEncode({
2600 0 : if (address != null) 'address': address,
2601 1 : if (deviceId != null) 'device_id': deviceId,
2602 10 : if (identifier != null) 'identifier': identifier.toJson(),
2603 : if (initialDeviceDisplayName != null)
2604 0 : 'initial_device_display_name': initialDeviceDisplayName,
2605 0 : if (medium != null) 'medium': medium,
2606 5 : if (password != null) 'password': password,
2607 5 : if (refreshToken != null) 'refresh_token': refreshToken,
2608 1 : if (token != null) 'token': token,
2609 5 : 'type': type,
2610 0 : if (user != null) 'user': user,
2611 : }),
2612 : );
2613 10 : final response = await httpClient.send(request);
2614 10 : final responseBody = await response.stream.toBytes();
2615 10 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2616 5 : final responseString = utf8.decode(responseBody);
2617 5 : final json = jsonDecode(responseString);
2618 5 : return LoginResponse.fromJson(json as Map<String, Object?>);
2619 : }
2620 :
2621 : /// Invalidates an existing access token, so that it can no longer be used for
2622 : /// authorization. The device associated with the access token is also deleted.
2623 : /// [Device keys](https://spec.matrix.org/unstable/client-server-api/#device-keys) for the device are deleted alongside the device.
2624 12 : Future<void> logout() async {
2625 12 : final requestUri = Uri(path: '_matrix/client/v3/logout');
2626 36 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2627 48 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2628 24 : final response = await httpClient.send(request);
2629 24 : final responseBody = await response.stream.toBytes();
2630 25 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2631 12 : final responseString = utf8.decode(responseBody);
2632 12 : final json = jsonDecode(responseString);
2633 12 : return ignore(json);
2634 : }
2635 :
2636 : /// Invalidates all access tokens for a user, so that they can no longer be used for
2637 : /// authorization. This includes the access token that made this request. All devices
2638 : /// for the user are also deleted. [Device keys](https://spec.matrix.org/unstable/client-server-api/#device-keys) for the device are
2639 : /// deleted alongside the device.
2640 : ///
2641 : /// This endpoint does not use the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api) because
2642 : /// User-Interactive Authentication is designed to protect against attacks where the
2643 : /// someone gets hold of a single access token then takes over the account. This
2644 : /// endpoint invalidates all access tokens for the user, including the token used in
2645 : /// the request, and therefore the attacker is unable to take over the account in
2646 : /// this way.
2647 0 : Future<void> logoutAll() async {
2648 0 : final requestUri = Uri(path: '_matrix/client/v3/logout/all');
2649 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2650 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2651 0 : final response = await httpClient.send(request);
2652 0 : final responseBody = await response.stream.toBytes();
2653 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2654 0 : final responseString = utf8.decode(responseBody);
2655 0 : final json = jsonDecode(responseString);
2656 0 : return ignore(json);
2657 : }
2658 :
2659 : /// This API is used to paginate through the list of events that the
2660 : /// user has been, or would have been notified about.
2661 : ///
2662 : /// [from] Pagination token to continue from. This should be the `next_token`
2663 : /// returned from an earlier call to this endpoint.
2664 : ///
2665 : /// [limit] Limit on the number of events to return in this request.
2666 : ///
2667 : /// [only] Allows basic filtering of events returned. Supply `highlight`
2668 : /// to return only events where the notification had the highlight
2669 : /// tweak set.
2670 0 : Future<GetNotificationsResponse> getNotifications({
2671 : String? from,
2672 : int? limit,
2673 : String? only,
2674 : }) async {
2675 0 : final requestUri = Uri(
2676 : path: '_matrix/client/v3/notifications',
2677 0 : queryParameters: {
2678 0 : if (from != null) 'from': from,
2679 0 : if (limit != null) 'limit': limit.toString(),
2680 0 : if (only != null) 'only': only,
2681 : },
2682 : );
2683 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2684 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2685 0 : final response = await httpClient.send(request);
2686 0 : final responseBody = await response.stream.toBytes();
2687 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2688 0 : final responseString = utf8.decode(responseBody);
2689 0 : final json = jsonDecode(responseString);
2690 0 : return GetNotificationsResponse.fromJson(json as Map<String, Object?>);
2691 : }
2692 :
2693 : /// Get the given user's presence state.
2694 : ///
2695 : /// [userId] The user whose presence state to get.
2696 0 : Future<GetPresenceResponse> getPresence(String userId) async {
2697 0 : final requestUri = Uri(
2698 0 : path: '_matrix/client/v3/presence/${Uri.encodeComponent(userId)}/status',
2699 : );
2700 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2701 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2702 0 : final response = await httpClient.send(request);
2703 0 : final responseBody = await response.stream.toBytes();
2704 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2705 0 : final responseString = utf8.decode(responseBody);
2706 0 : final json = jsonDecode(responseString);
2707 0 : return GetPresenceResponse.fromJson(json as Map<String, Object?>);
2708 : }
2709 :
2710 : /// This API sets the given user's presence state. When setting the status,
2711 : /// the activity time is updated to reflect that activity; the client does
2712 : /// not need to specify the `last_active_ago` field. You cannot set the
2713 : /// presence state of another user.
2714 : ///
2715 : /// [userId] The user whose presence state to update.
2716 : ///
2717 : /// [presence] The new presence state.
2718 : ///
2719 : /// [statusMsg] The status message to attach to this state.
2720 0 : Future<void> setPresence(
2721 : String userId,
2722 : PresenceType presence, {
2723 : String? statusMsg,
2724 : }) async {
2725 0 : final requestUri = Uri(
2726 0 : path: '_matrix/client/v3/presence/${Uri.encodeComponent(userId)}/status',
2727 : );
2728 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
2729 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2730 0 : request.headers['content-type'] = 'application/json';
2731 0 : request.bodyBytes = utf8.encode(
2732 0 : jsonEncode({
2733 0 : 'presence': presence.name,
2734 0 : if (statusMsg != null) 'status_msg': statusMsg,
2735 : }),
2736 : );
2737 0 : final response = await httpClient.send(request);
2738 0 : final responseBody = await response.stream.toBytes();
2739 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2740 0 : final responseString = utf8.decode(responseBody);
2741 0 : final json = jsonDecode(responseString);
2742 0 : return ignore(json);
2743 : }
2744 :
2745 : /// Get the combined profile information for this user. This API may be used
2746 : /// to fetch the user's own profile information or other users; either
2747 : /// locally or on remote homeservers.
2748 : ///
2749 : /// [userId] The user whose profile information to get.
2750 5 : Future<ProfileInformation> getUserProfile(String userId) async {
2751 : final requestUri =
2752 15 : Uri(path: '_matrix/client/v3/profile/${Uri.encodeComponent(userId)}');
2753 11 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2754 3 : if (bearerToken != null) {
2755 12 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2756 : }
2757 6 : final response = await httpClient.send(request);
2758 6 : final responseBody = await response.stream.toBytes();
2759 7 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2760 3 : final responseString = utf8.decode(responseBody);
2761 3 : final json = jsonDecode(responseString);
2762 3 : return ProfileInformation.fromJson(json as Map<String, Object?>);
2763 : }
2764 :
2765 : /// Get the user's avatar URL. This API may be used to fetch the user's
2766 : /// own avatar URL or to query the URL of other users; either locally or
2767 : /// on remote homeservers.
2768 : ///
2769 : /// [userId] The user whose avatar URL to get.
2770 : ///
2771 : /// returns `avatar_url`:
2772 : /// The user's avatar URL if they have set one, otherwise not present.
2773 0 : Future<Uri?> getAvatarUrl(String userId) async {
2774 0 : final requestUri = Uri(
2775 : path:
2776 0 : '_matrix/client/v3/profile/${Uri.encodeComponent(userId)}/avatar_url',
2777 : );
2778 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2779 0 : if (bearerToken != null) {
2780 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2781 : }
2782 0 : final response = await httpClient.send(request);
2783 0 : final responseBody = await response.stream.toBytes();
2784 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2785 0 : final responseString = utf8.decode(responseBody);
2786 0 : final json = jsonDecode(responseString);
2787 0 : return ((v) =>
2788 0 : v != null ? Uri.parse(v as String) : null)(json['avatar_url']);
2789 : }
2790 :
2791 : /// This API sets the given user's avatar URL. You must have permission to
2792 : /// set this user's avatar URL, e.g. you need to have their `access_token`.
2793 : ///
2794 : /// [userId] The user whose avatar URL to set.
2795 : ///
2796 : /// [avatarUrl] The new avatar URL for this user.
2797 1 : Future<void> setAvatarUrl(String userId, Uri? avatarUrl) async {
2798 1 : final requestUri = Uri(
2799 : path:
2800 2 : '_matrix/client/v3/profile/${Uri.encodeComponent(userId)}/avatar_url',
2801 : );
2802 3 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
2803 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2804 2 : request.headers['content-type'] = 'application/json';
2805 2 : request.bodyBytes = utf8.encode(
2806 2 : jsonEncode({
2807 2 : if (avatarUrl != null) 'avatar_url': avatarUrl.toString(),
2808 : }),
2809 : );
2810 2 : final response = await httpClient.send(request);
2811 2 : final responseBody = await response.stream.toBytes();
2812 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2813 1 : final responseString = utf8.decode(responseBody);
2814 1 : final json = jsonDecode(responseString);
2815 1 : return ignore(json);
2816 : }
2817 :
2818 : /// Get the user's display name. This API may be used to fetch the user's
2819 : /// own displayname or to query the name of other users; either locally or
2820 : /// on remote homeservers.
2821 : ///
2822 : /// [userId] The user whose display name to get.
2823 : ///
2824 : /// returns `displayname`:
2825 : /// The user's display name if they have set one, otherwise not present.
2826 0 : Future<String?> getDisplayName(String userId) async {
2827 0 : final requestUri = Uri(
2828 : path:
2829 0 : '_matrix/client/v3/profile/${Uri.encodeComponent(userId)}/displayname',
2830 : );
2831 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2832 0 : if (bearerToken != null) {
2833 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2834 : }
2835 0 : final response = await httpClient.send(request);
2836 0 : final responseBody = await response.stream.toBytes();
2837 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2838 0 : final responseString = utf8.decode(responseBody);
2839 0 : final json = jsonDecode(responseString);
2840 0 : return ((v) => v != null ? v as String : null)(json['displayname']);
2841 : }
2842 :
2843 : /// This API sets the given user's display name. You must have permission to
2844 : /// set this user's display name, e.g. you need to have their `access_token`.
2845 : ///
2846 : /// [userId] The user whose display name to set.
2847 : ///
2848 : /// [displayname] The new display name for this user.
2849 0 : Future<void> setDisplayName(String userId, String? displayname) async {
2850 0 : final requestUri = Uri(
2851 : path:
2852 0 : '_matrix/client/v3/profile/${Uri.encodeComponent(userId)}/displayname',
2853 : );
2854 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
2855 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2856 0 : request.headers['content-type'] = 'application/json';
2857 0 : request.bodyBytes = utf8.encode(
2858 0 : jsonEncode({
2859 0 : if (displayname != null) 'displayname': displayname,
2860 : }),
2861 : );
2862 0 : final response = await httpClient.send(request);
2863 0 : final responseBody = await response.stream.toBytes();
2864 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2865 0 : final responseString = utf8.decode(responseBody);
2866 0 : final json = jsonDecode(responseString);
2867 0 : return ignore(json);
2868 : }
2869 :
2870 : /// Lists the public rooms on the server.
2871 : ///
2872 : /// This API returns paginated responses. The rooms are ordered by the number
2873 : /// of joined members, with the largest rooms first.
2874 : ///
2875 : /// [limit] Limit the number of results returned.
2876 : ///
2877 : /// [since] A pagination token from a previous request, allowing clients to
2878 : /// get the next (or previous) batch of rooms.
2879 : /// The direction of pagination is specified solely by which token
2880 : /// is supplied, rather than via an explicit flag.
2881 : ///
2882 : /// [server] The server to fetch the public room lists from. Defaults to the
2883 : /// local server. Case sensitive.
2884 0 : Future<GetPublicRoomsResponse> getPublicRooms({
2885 : int? limit,
2886 : String? since,
2887 : String? server,
2888 : }) async {
2889 0 : final requestUri = Uri(
2890 : path: '_matrix/client/v3/publicRooms',
2891 0 : queryParameters: {
2892 0 : if (limit != null) 'limit': limit.toString(),
2893 0 : if (since != null) 'since': since,
2894 0 : if (server != null) 'server': server,
2895 : },
2896 : );
2897 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2898 0 : final response = await httpClient.send(request);
2899 0 : final responseBody = await response.stream.toBytes();
2900 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2901 0 : final responseString = utf8.decode(responseBody);
2902 0 : final json = jsonDecode(responseString);
2903 0 : return GetPublicRoomsResponse.fromJson(json as Map<String, Object?>);
2904 : }
2905 :
2906 : /// Lists the public rooms on the server, with optional filter.
2907 : ///
2908 : /// This API returns paginated responses. The rooms are ordered by the number
2909 : /// of joined members, with the largest rooms first.
2910 : ///
2911 : /// [server] The server to fetch the public room lists from. Defaults to the
2912 : /// local server. Case sensitive.
2913 : ///
2914 : /// [filter] Filter to apply to the results.
2915 : ///
2916 : /// [includeAllNetworks] Whether or not to include all known networks/protocols from
2917 : /// application services on the homeserver. Defaults to false.
2918 : ///
2919 : /// [limit] Limit the number of results returned.
2920 : ///
2921 : /// [since] A pagination token from a previous request, allowing clients
2922 : /// to get the next (or previous) batch of rooms. The direction
2923 : /// of pagination is specified solely by which token is supplied,
2924 : /// rather than via an explicit flag.
2925 : ///
2926 : /// [thirdPartyInstanceId] The specific third-party network/protocol to request from the
2927 : /// homeserver. Can only be used if `include_all_networks` is false.
2928 : ///
2929 : /// This is the `instance_id` of a `Protocol Instance` returned by
2930 : /// [`GET /_matrix/client/v3/thirdparty/protocols`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3thirdpartyprotocols).
2931 0 : Future<QueryPublicRoomsResponse> queryPublicRooms({
2932 : String? server,
2933 : PublicRoomQueryFilter? filter,
2934 : bool? includeAllNetworks,
2935 : int? limit,
2936 : String? since,
2937 : String? thirdPartyInstanceId,
2938 : }) async {
2939 0 : final requestUri = Uri(
2940 : path: '_matrix/client/v3/publicRooms',
2941 0 : queryParameters: {
2942 0 : if (server != null) 'server': server,
2943 : },
2944 : );
2945 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
2946 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2947 0 : request.headers['content-type'] = 'application/json';
2948 0 : request.bodyBytes = utf8.encode(
2949 0 : jsonEncode({
2950 0 : if (filter != null) 'filter': filter.toJson(),
2951 : if (includeAllNetworks != null)
2952 0 : 'include_all_networks': includeAllNetworks,
2953 0 : if (limit != null) 'limit': limit,
2954 0 : if (since != null) 'since': since,
2955 : if (thirdPartyInstanceId != null)
2956 0 : 'third_party_instance_id': thirdPartyInstanceId,
2957 : }),
2958 : );
2959 0 : final response = await httpClient.send(request);
2960 0 : final responseBody = await response.stream.toBytes();
2961 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2962 0 : final responseString = utf8.decode(responseBody);
2963 0 : final json = jsonDecode(responseString);
2964 0 : return QueryPublicRoomsResponse.fromJson(json as Map<String, Object?>);
2965 : }
2966 :
2967 : /// Gets all currently active pushers for the authenticated user.
2968 : ///
2969 : /// returns `pushers`:
2970 : /// An array containing the current pushers for the user
2971 0 : Future<List<Pusher>?> getPushers() async {
2972 0 : final requestUri = Uri(path: '_matrix/client/v3/pushers');
2973 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2974 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2975 0 : final response = await httpClient.send(request);
2976 0 : final responseBody = await response.stream.toBytes();
2977 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2978 0 : final responseString = utf8.decode(responseBody);
2979 0 : final json = jsonDecode(responseString);
2980 0 : return ((v) => v != null
2981 : ? (v as List)
2982 0 : .map((v) => Pusher.fromJson(v as Map<String, Object?>))
2983 0 : .toList()
2984 0 : : null)(json['pushers']);
2985 : }
2986 :
2987 : /// Retrieve all push rulesets for this user. Currently the only push ruleset
2988 : /// defined is `global`.
2989 : ///
2990 : /// returns `global`:
2991 : /// The global ruleset.
2992 0 : Future<PushRuleSet> getPushRules() async {
2993 0 : final requestUri = Uri(path: '_matrix/client/v3/pushrules/');
2994 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
2995 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
2996 0 : final response = await httpClient.send(request);
2997 0 : final responseBody = await response.stream.toBytes();
2998 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
2999 0 : final responseString = utf8.decode(responseBody);
3000 0 : final json = jsonDecode(responseString);
3001 0 : return PushRuleSet.fromJson(json['global'] as Map<String, Object?>);
3002 : }
3003 :
3004 : /// Retrieve all push rules for this user.
3005 0 : Future<GetPushRulesGlobalResponse> getPushRulesGlobal() async {
3006 0 : final requestUri = Uri(path: '_matrix/client/v3/pushrules/global/');
3007 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3008 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3009 0 : final response = await httpClient.send(request);
3010 0 : final responseBody = await response.stream.toBytes();
3011 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3012 0 : final responseString = utf8.decode(responseBody);
3013 0 : final json = jsonDecode(responseString);
3014 0 : return GetPushRulesGlobalResponse.fromJson(json as Map<String, Object?>);
3015 : }
3016 :
3017 : /// This endpoint removes the push rule defined in the path.
3018 : ///
3019 : /// [kind] The kind of rule
3020 : ///
3021 : ///
3022 : /// [ruleId] The identifier for the rule.
3023 : ///
3024 2 : Future<void> deletePushRule(PushRuleKind kind, String ruleId) async {
3025 2 : final requestUri = Uri(
3026 : path:
3027 8 : '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}',
3028 : );
3029 6 : final request = Request('DELETE', baseUri!.resolveUri(requestUri));
3030 8 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3031 4 : final response = await httpClient.send(request);
3032 4 : final responseBody = await response.stream.toBytes();
3033 4 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3034 2 : final responseString = utf8.decode(responseBody);
3035 2 : final json = jsonDecode(responseString);
3036 2 : return ignore(json);
3037 : }
3038 :
3039 : /// Retrieve a single specified push rule.
3040 : ///
3041 : /// [kind] The kind of rule
3042 : ///
3043 : ///
3044 : /// [ruleId] The identifier for the rule.
3045 : ///
3046 0 : Future<PushRule> getPushRule(PushRuleKind kind, String ruleId) async {
3047 0 : final requestUri = Uri(
3048 : path:
3049 0 : '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}',
3050 : );
3051 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3052 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3053 0 : final response = await httpClient.send(request);
3054 0 : final responseBody = await response.stream.toBytes();
3055 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3056 0 : final responseString = utf8.decode(responseBody);
3057 0 : final json = jsonDecode(responseString);
3058 0 : return PushRule.fromJson(json as Map<String, Object?>);
3059 : }
3060 :
3061 : /// This endpoint allows the creation and modification of user defined push
3062 : /// rules.
3063 : ///
3064 : /// If a rule with the same `rule_id` already exists among rules of the same
3065 : /// kind, it is updated with the new parameters, otherwise a new rule is
3066 : /// created.
3067 : ///
3068 : /// If both `after` and `before` are provided, the new or updated rule must
3069 : /// be the next most important rule with respect to the rule identified by
3070 : /// `before`.
3071 : ///
3072 : /// If neither `after` nor `before` are provided and the rule is created, it
3073 : /// should be added as the most important user defined rule among rules of
3074 : /// the same kind.
3075 : ///
3076 : /// When creating push rules, they MUST be enabled by default.
3077 : ///
3078 : /// [kind] The kind of rule
3079 : ///
3080 : ///
3081 : /// [ruleId] The identifier for the rule. If the string starts with a dot ("."),
3082 : /// the request MUST be rejected as this is reserved for server-default
3083 : /// rules. Slashes ("/") and backslashes ("\\") are also not allowed.
3084 : ///
3085 : ///
3086 : /// [before] Use 'before' with a `rule_id` as its value to make the new rule the
3087 : /// next-most important rule with respect to the given user defined rule.
3088 : /// It is not possible to add a rule relative to a predefined server rule.
3089 : ///
3090 : /// [after] This makes the new rule the next-less important rule relative to the
3091 : /// given user defined rule. It is not possible to add a rule relative
3092 : /// to a predefined server rule.
3093 : ///
3094 : /// [actions] The action(s) to perform when the conditions for this rule are met.
3095 : ///
3096 : /// [conditions] The conditions that must hold true for an event in order for a
3097 : /// rule to be applied to an event. A rule with no conditions
3098 : /// always matches. Only applicable to `underride` and `override` rules.
3099 : ///
3100 : /// [pattern] Only applicable to `content` rules. The glob-style pattern to match against.
3101 2 : Future<void> setPushRule(
3102 : PushRuleKind kind,
3103 : String ruleId,
3104 : List<Object?> actions, {
3105 : String? before,
3106 : String? after,
3107 : List<PushCondition>? conditions,
3108 : String? pattern,
3109 : }) async {
3110 2 : final requestUri = Uri(
3111 : path:
3112 8 : '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}',
3113 2 : queryParameters: {
3114 0 : if (before != null) 'before': before,
3115 0 : if (after != null) 'after': after,
3116 : },
3117 : );
3118 6 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
3119 8 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3120 4 : request.headers['content-type'] = 'application/json';
3121 4 : request.bodyBytes = utf8.encode(
3122 4 : jsonEncode({
3123 6 : 'actions': actions.map((v) => v).toList(),
3124 : if (conditions != null)
3125 0 : 'conditions': conditions.map((v) => v.toJson()).toList(),
3126 0 : if (pattern != null) 'pattern': pattern,
3127 : }),
3128 : );
3129 4 : final response = await httpClient.send(request);
3130 4 : final responseBody = await response.stream.toBytes();
3131 4 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3132 2 : final responseString = utf8.decode(responseBody);
3133 2 : final json = jsonDecode(responseString);
3134 2 : return ignore(json);
3135 : }
3136 :
3137 : /// This endpoint get the actions for the specified push rule.
3138 : ///
3139 : /// [kind] The kind of rule
3140 : ///
3141 : ///
3142 : /// [ruleId] The identifier for the rule.
3143 : ///
3144 : ///
3145 : /// returns `actions`:
3146 : /// The action(s) to perform for this rule.
3147 0 : Future<List<Object?>> getPushRuleActions(
3148 : PushRuleKind kind,
3149 : String ruleId,
3150 : ) async {
3151 0 : final requestUri = Uri(
3152 : path:
3153 0 : '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}/actions',
3154 : );
3155 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3156 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3157 0 : final response = await httpClient.send(request);
3158 0 : final responseBody = await response.stream.toBytes();
3159 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3160 0 : final responseString = utf8.decode(responseBody);
3161 0 : final json = jsonDecode(responseString);
3162 0 : return (json['actions'] as List).map((v) => v as Object?).toList();
3163 : }
3164 :
3165 : /// This endpoint allows clients to change the actions of a push rule.
3166 : /// This can be used to change the actions of builtin rules.
3167 : ///
3168 : /// [kind] The kind of rule
3169 : ///
3170 : ///
3171 : /// [ruleId] The identifier for the rule.
3172 : ///
3173 : ///
3174 : /// [actions] The action(s) to perform for this rule.
3175 0 : Future<void> setPushRuleActions(
3176 : PushRuleKind kind,
3177 : String ruleId,
3178 : List<Object?> actions,
3179 : ) async {
3180 0 : final requestUri = Uri(
3181 : path:
3182 0 : '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}/actions',
3183 : );
3184 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
3185 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3186 0 : request.headers['content-type'] = 'application/json';
3187 0 : request.bodyBytes = utf8.encode(
3188 0 : jsonEncode({
3189 0 : 'actions': actions.map((v) => v).toList(),
3190 : }),
3191 : );
3192 0 : final response = await httpClient.send(request);
3193 0 : final responseBody = await response.stream.toBytes();
3194 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3195 0 : final responseString = utf8.decode(responseBody);
3196 0 : final json = jsonDecode(responseString);
3197 0 : return ignore(json);
3198 : }
3199 :
3200 : /// This endpoint gets whether the specified push rule is enabled.
3201 : ///
3202 : /// [kind] The kind of rule
3203 : ///
3204 : ///
3205 : /// [ruleId] The identifier for the rule.
3206 : ///
3207 : ///
3208 : /// returns `enabled`:
3209 : /// Whether the push rule is enabled or not.
3210 0 : Future<bool> isPushRuleEnabled(PushRuleKind kind, String ruleId) async {
3211 0 : final requestUri = Uri(
3212 : path:
3213 0 : '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}/enabled',
3214 : );
3215 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3216 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3217 0 : final response = await httpClient.send(request);
3218 0 : final responseBody = await response.stream.toBytes();
3219 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3220 0 : final responseString = utf8.decode(responseBody);
3221 0 : final json = jsonDecode(responseString);
3222 0 : return json['enabled'] as bool;
3223 : }
3224 :
3225 : /// This endpoint allows clients to enable or disable the specified push rule.
3226 : ///
3227 : /// [kind] The kind of rule
3228 : ///
3229 : ///
3230 : /// [ruleId] The identifier for the rule.
3231 : ///
3232 : ///
3233 : /// [enabled] Whether the push rule is enabled or not.
3234 1 : Future<void> setPushRuleEnabled(
3235 : PushRuleKind kind,
3236 : String ruleId,
3237 : bool enabled,
3238 : ) async {
3239 1 : final requestUri = Uri(
3240 : path:
3241 4 : '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}/enabled',
3242 : );
3243 3 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
3244 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3245 2 : request.headers['content-type'] = 'application/json';
3246 2 : request.bodyBytes = utf8.encode(
3247 2 : jsonEncode({
3248 : 'enabled': enabled,
3249 : }),
3250 : );
3251 2 : final response = await httpClient.send(request);
3252 2 : final responseBody = await response.stream.toBytes();
3253 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3254 1 : final responseString = utf8.decode(responseBody);
3255 1 : final json = jsonDecode(responseString);
3256 1 : return ignore(json);
3257 : }
3258 :
3259 : /// Refresh an access token. Clients should use the returned access token
3260 : /// when making subsequent API calls, and store the returned refresh token
3261 : /// (if given) in order to refresh the new access token when necessary.
3262 : ///
3263 : /// After an access token has been refreshed, a server can choose to
3264 : /// invalidate the old access token immediately, or can choose not to, for
3265 : /// example if the access token would expire soon anyways. Clients should
3266 : /// not make any assumptions about the old access token still being valid,
3267 : /// and should use the newly provided access token instead.
3268 : ///
3269 : /// The old refresh token remains valid until the new access token or refresh token
3270 : /// is used, at which point the old refresh token is revoked.
3271 : ///
3272 : /// Note that this endpoint does not require authentication via an
3273 : /// access token. Authentication is provided via the refresh token.
3274 : ///
3275 : /// Application Service identity assertion is disabled for this endpoint.
3276 : ///
3277 : /// [refreshToken] The refresh token
3278 0 : Future<RefreshResponse> refresh(String refreshToken) async {
3279 0 : final requestUri = Uri(path: '_matrix/client/v3/refresh');
3280 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
3281 0 : request.headers['content-type'] = 'application/json';
3282 0 : request.bodyBytes = utf8.encode(
3283 0 : jsonEncode({
3284 : 'refresh_token': refreshToken,
3285 : }),
3286 : );
3287 0 : final response = await httpClient.send(request);
3288 0 : final responseBody = await response.stream.toBytes();
3289 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3290 0 : final responseString = utf8.decode(responseBody);
3291 0 : final json = jsonDecode(responseString);
3292 0 : return RefreshResponse.fromJson(json as Map<String, Object?>);
3293 : }
3294 :
3295 : /// This API endpoint uses the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api), except in
3296 : /// the cases where a guest account is being registered.
3297 : ///
3298 : /// Register for an account on this homeserver.
3299 : ///
3300 : /// There are two kinds of user account:
3301 : ///
3302 : /// - `user` accounts. These accounts may use the full API described in this specification.
3303 : ///
3304 : /// - `guest` accounts. These accounts may have limited permissions and may not be supported by all servers.
3305 : ///
3306 : /// If registration is successful, this endpoint will issue an access token
3307 : /// the client can use to authorize itself in subsequent requests.
3308 : ///
3309 : /// If the client does not supply a `device_id`, the server must
3310 : /// auto-generate one.
3311 : ///
3312 : /// The server SHOULD register an account with a User ID based on the
3313 : /// `username` provided, if any. Note that the grammar of Matrix User ID
3314 : /// localparts is restricted, so the server MUST either map the provided
3315 : /// `username` onto a `user_id` in a logical manner, or reject any
3316 : /// `username` which does not comply to the grammar with
3317 : /// `M_INVALID_USERNAME`.
3318 : ///
3319 : /// Matrix clients MUST NOT assume that localpart of the registered
3320 : /// `user_id` matches the provided `username`.
3321 : ///
3322 : /// The returned access token must be associated with the `device_id`
3323 : /// supplied by the client or generated by the server. The server may
3324 : /// invalidate any access token previously associated with that device. See
3325 : /// [Relationship between access tokens and devices](https://spec.matrix.org/unstable/client-server-api/#relationship-between-access-tokens-and-devices).
3326 : ///
3327 : /// When registering a guest account, all parameters in the request body
3328 : /// with the exception of `initial_device_display_name` MUST BE ignored
3329 : /// by the server. The server MUST pick a `device_id` for the account
3330 : /// regardless of input.
3331 : ///
3332 : /// Any user ID returned by this API must conform to the grammar given in the
3333 : /// [Matrix specification](https://spec.matrix.org/unstable/appendices/#user-identifiers).
3334 : ///
3335 : /// [kind] The kind of account to register. Defaults to `user`.
3336 : ///
3337 : /// [auth] Additional authentication information for the
3338 : /// user-interactive authentication API. Note that this
3339 : /// information is *not* used to define how the registered user
3340 : /// should be authenticated, but is instead used to
3341 : /// authenticate the `register` call itself.
3342 : ///
3343 : /// [deviceId] ID of the client device. If this does not correspond to a
3344 : /// known client device, a new device will be created. The server
3345 : /// will auto-generate a device_id if this is not specified.
3346 : ///
3347 : /// [inhibitLogin] If true, an `access_token` and `device_id` should not be
3348 : /// returned from this call, therefore preventing an automatic
3349 : /// login. Defaults to false.
3350 : ///
3351 : /// [initialDeviceDisplayName] A display name to assign to the newly-created device. Ignored
3352 : /// if `device_id` corresponds to a known device.
3353 : ///
3354 : /// [password] The desired password for the account.
3355 : ///
3356 : /// [refreshToken] If true, the client supports refresh tokens.
3357 : ///
3358 : /// [username] The basis for the localpart of the desired Matrix ID. If omitted,
3359 : /// the homeserver MUST generate a Matrix ID local part.
3360 0 : Future<RegisterResponse> register({
3361 : AccountKind? kind,
3362 : AuthenticationData? auth,
3363 : String? deviceId,
3364 : bool? inhibitLogin,
3365 : String? initialDeviceDisplayName,
3366 : String? password,
3367 : bool? refreshToken,
3368 : String? username,
3369 : }) async {
3370 0 : final requestUri = Uri(
3371 : path: '_matrix/client/v3/register',
3372 0 : queryParameters: {
3373 0 : if (kind != null) 'kind': kind.name,
3374 : },
3375 : );
3376 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
3377 0 : request.headers['content-type'] = 'application/json';
3378 0 : request.bodyBytes = utf8.encode(
3379 0 : jsonEncode({
3380 0 : if (auth != null) 'auth': auth.toJson(),
3381 0 : if (deviceId != null) 'device_id': deviceId,
3382 0 : if (inhibitLogin != null) 'inhibit_login': inhibitLogin,
3383 : if (initialDeviceDisplayName != null)
3384 0 : 'initial_device_display_name': initialDeviceDisplayName,
3385 0 : if (password != null) 'password': password,
3386 0 : if (refreshToken != null) 'refresh_token': refreshToken,
3387 0 : if (username != null) 'username': username,
3388 : }),
3389 : );
3390 0 : final response = await httpClient.send(request);
3391 0 : final responseBody = await response.stream.toBytes();
3392 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3393 0 : final responseString = utf8.decode(responseBody);
3394 0 : final json = jsonDecode(responseString);
3395 0 : return RegisterResponse.fromJson(json as Map<String, Object?>);
3396 : }
3397 :
3398 : /// Checks to see if a username is available, and valid, for the server.
3399 : ///
3400 : /// The server should check to ensure that, at the time of the request, the
3401 : /// username requested is available for use. This includes verifying that an
3402 : /// application service has not claimed the username and that the username
3403 : /// fits the server's desired requirements (for example, a server could dictate
3404 : /// that it does not permit usernames with underscores).
3405 : ///
3406 : /// Matrix clients may wish to use this API prior to attempting registration,
3407 : /// however the clients must also be aware that using this API does not normally
3408 : /// reserve the username. This can mean that the username becomes unavailable
3409 : /// between checking its availability and attempting to register it.
3410 : ///
3411 : /// [username] The username to check the availability of.
3412 : ///
3413 : /// returns `available`:
3414 : /// A flag to indicate that the username is available. This should always
3415 : /// be `true` when the server replies with 200 OK.
3416 1 : Future<bool?> checkUsernameAvailability(String username) async {
3417 1 : final requestUri = Uri(
3418 : path: '_matrix/client/v3/register/available',
3419 1 : queryParameters: {
3420 : 'username': username,
3421 : },
3422 : );
3423 3 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3424 2 : final response = await httpClient.send(request);
3425 2 : final responseBody = await response.stream.toBytes();
3426 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3427 1 : final responseString = utf8.decode(responseBody);
3428 1 : final json = jsonDecode(responseString);
3429 3 : return ((v) => v != null ? v as bool : null)(json['available']);
3430 : }
3431 :
3432 : /// The homeserver must check that the given email address is **not**
3433 : /// already associated with an account on this homeserver. The homeserver
3434 : /// should validate the email itself, either by sending a validation email
3435 : /// itself or by using a service it has control over.
3436 : ///
3437 : /// [clientSecret] A unique string generated by the client, and used to identify the
3438 : /// validation attempt. It must be a string consisting of the characters
3439 : /// `[0-9a-zA-Z.=_-]`. Its length must not exceed 255 characters and it
3440 : /// must not be empty.
3441 : ///
3442 : ///
3443 : /// [email] The email address to validate.
3444 : ///
3445 : /// [nextLink] Optional. When the validation is completed, the identity server will
3446 : /// redirect the user to this URL. This option is ignored when submitting
3447 : /// 3PID validation information through a POST request.
3448 : ///
3449 : /// [sendAttempt] The server will only send an email if the `send_attempt`
3450 : /// is a number greater than the most recent one which it has seen,
3451 : /// scoped to that `email` + `client_secret` pair. This is to
3452 : /// avoid repeatedly sending the same email in the case of request
3453 : /// retries between the POSTing user and the identity server.
3454 : /// The client should increment this value if they desire a new
3455 : /// email (e.g. a reminder) to be sent. If they do not, the server
3456 : /// should respond with success but not resend the email.
3457 : ///
3458 : /// [idAccessToken] An access token previously registered with the identity server. Servers
3459 : /// can treat this as optional to distinguish between r0.5-compatible clients
3460 : /// and this specification version.
3461 : ///
3462 : /// Required if an `id_server` is supplied.
3463 : ///
3464 : /// [idServer] The hostname of the identity server to communicate with. May optionally
3465 : /// include a port. This parameter is ignored when the homeserver handles
3466 : /// 3PID verification.
3467 : ///
3468 : /// This parameter is deprecated with a plan to be removed in a future specification
3469 : /// version for `/account/password` and `/register` requests.
3470 0 : Future<RequestTokenResponse> requestTokenToRegisterEmail(
3471 : String clientSecret,
3472 : String email,
3473 : int sendAttempt, {
3474 : Uri? nextLink,
3475 : String? idAccessToken,
3476 : String? idServer,
3477 : }) async {
3478 : final requestUri =
3479 0 : Uri(path: '_matrix/client/v3/register/email/requestToken');
3480 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
3481 0 : request.headers['content-type'] = 'application/json';
3482 0 : request.bodyBytes = utf8.encode(
3483 0 : jsonEncode({
3484 0 : 'client_secret': clientSecret,
3485 0 : 'email': email,
3486 0 : if (nextLink != null) 'next_link': nextLink.toString(),
3487 0 : 'send_attempt': sendAttempt,
3488 0 : if (idAccessToken != null) 'id_access_token': idAccessToken,
3489 0 : if (idServer != null) 'id_server': idServer,
3490 : }),
3491 : );
3492 0 : final response = await httpClient.send(request);
3493 0 : final responseBody = await response.stream.toBytes();
3494 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3495 0 : final responseString = utf8.decode(responseBody);
3496 0 : final json = jsonDecode(responseString);
3497 0 : return RequestTokenResponse.fromJson(json as Map<String, Object?>);
3498 : }
3499 :
3500 : /// The homeserver must check that the given phone number is **not**
3501 : /// already associated with an account on this homeserver. The homeserver
3502 : /// should validate the phone number itself, either by sending a validation
3503 : /// message itself or by using a service it has control over.
3504 : ///
3505 : /// [clientSecret] A unique string generated by the client, and used to identify the
3506 : /// validation attempt. It must be a string consisting of the characters
3507 : /// `[0-9a-zA-Z.=_-]`. Its length must not exceed 255 characters and it
3508 : /// must not be empty.
3509 : ///
3510 : ///
3511 : /// [country] The two-letter uppercase ISO-3166-1 alpha-2 country code that the
3512 : /// number in `phone_number` should be parsed as if it were dialled from.
3513 : ///
3514 : /// [nextLink] Optional. When the validation is completed, the identity server will
3515 : /// redirect the user to this URL. This option is ignored when submitting
3516 : /// 3PID validation information through a POST request.
3517 : ///
3518 : /// [phoneNumber] The phone number to validate.
3519 : ///
3520 : /// [sendAttempt] The server will only send an SMS if the `send_attempt` is a
3521 : /// number greater than the most recent one which it has seen,
3522 : /// scoped to that `country` + `phone_number` + `client_secret`
3523 : /// triple. This is to avoid repeatedly sending the same SMS in
3524 : /// the case of request retries between the POSTing user and the
3525 : /// identity server. The client should increment this value if
3526 : /// they desire a new SMS (e.g. a reminder) to be sent.
3527 : ///
3528 : /// [idAccessToken] An access token previously registered with the identity server. Servers
3529 : /// can treat this as optional to distinguish between r0.5-compatible clients
3530 : /// and this specification version.
3531 : ///
3532 : /// Required if an `id_server` is supplied.
3533 : ///
3534 : /// [idServer] The hostname of the identity server to communicate with. May optionally
3535 : /// include a port. This parameter is ignored when the homeserver handles
3536 : /// 3PID verification.
3537 : ///
3538 : /// This parameter is deprecated with a plan to be removed in a future specification
3539 : /// version for `/account/password` and `/register` requests.
3540 0 : Future<RequestTokenResponse> requestTokenToRegisterMSISDN(
3541 : String clientSecret,
3542 : String country,
3543 : String phoneNumber,
3544 : int sendAttempt, {
3545 : Uri? nextLink,
3546 : String? idAccessToken,
3547 : String? idServer,
3548 : }) async {
3549 : final requestUri =
3550 0 : Uri(path: '_matrix/client/v3/register/msisdn/requestToken');
3551 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
3552 0 : request.headers['content-type'] = 'application/json';
3553 0 : request.bodyBytes = utf8.encode(
3554 0 : jsonEncode({
3555 0 : 'client_secret': clientSecret,
3556 0 : 'country': country,
3557 0 : if (nextLink != null) 'next_link': nextLink.toString(),
3558 0 : 'phone_number': phoneNumber,
3559 0 : 'send_attempt': sendAttempt,
3560 0 : if (idAccessToken != null) 'id_access_token': idAccessToken,
3561 0 : if (idServer != null) 'id_server': idServer,
3562 : }),
3563 : );
3564 0 : final response = await httpClient.send(request);
3565 0 : final responseBody = await response.stream.toBytes();
3566 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3567 0 : final responseString = utf8.decode(responseBody);
3568 0 : final json = jsonDecode(responseString);
3569 0 : return RequestTokenResponse.fromJson(json as Map<String, Object?>);
3570 : }
3571 :
3572 : /// Delete the keys from the backup.
3573 : ///
3574 : /// [version] The backup from which to delete the key
3575 0 : Future<RoomKeysUpdateResponse> deleteRoomKeys(String version) async {
3576 0 : final requestUri = Uri(
3577 : path: '_matrix/client/v3/room_keys/keys',
3578 0 : queryParameters: {
3579 : 'version': version,
3580 : },
3581 : );
3582 0 : final request = Request('DELETE', baseUri!.resolveUri(requestUri));
3583 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3584 0 : final response = await httpClient.send(request);
3585 0 : final responseBody = await response.stream.toBytes();
3586 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3587 0 : final responseString = utf8.decode(responseBody);
3588 0 : final json = jsonDecode(responseString);
3589 0 : return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
3590 : }
3591 :
3592 : /// Retrieve the keys from the backup.
3593 : ///
3594 : /// [version] The backup from which to retrieve the keys.
3595 1 : Future<RoomKeys> getRoomKeys(String version) async {
3596 1 : final requestUri = Uri(
3597 : path: '_matrix/client/v3/room_keys/keys',
3598 1 : queryParameters: {
3599 : 'version': version,
3600 : },
3601 : );
3602 3 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3603 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3604 2 : final response = await httpClient.send(request);
3605 2 : final responseBody = await response.stream.toBytes();
3606 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3607 1 : final responseString = utf8.decode(responseBody);
3608 1 : final json = jsonDecode(responseString);
3609 1 : return RoomKeys.fromJson(json as Map<String, Object?>);
3610 : }
3611 :
3612 : /// Store several keys in the backup.
3613 : ///
3614 : /// [version] The backup in which to store the keys. Must be the current backup.
3615 : ///
3616 : /// [body] The backup data.
3617 4 : Future<RoomKeysUpdateResponse> putRoomKeys(
3618 : String version,
3619 : RoomKeys body,
3620 : ) async {
3621 4 : final requestUri = Uri(
3622 : path: '_matrix/client/v3/room_keys/keys',
3623 4 : queryParameters: {
3624 : 'version': version,
3625 : },
3626 : );
3627 12 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
3628 16 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3629 8 : request.headers['content-type'] = 'application/json';
3630 16 : request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
3631 8 : final response = await httpClient.send(request);
3632 8 : final responseBody = await response.stream.toBytes();
3633 8 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3634 4 : final responseString = utf8.decode(responseBody);
3635 4 : final json = jsonDecode(responseString);
3636 4 : return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
3637 : }
3638 :
3639 : /// Delete the keys from the backup for a given room.
3640 : ///
3641 : /// [roomId] The ID of the room that the specified key is for.
3642 : ///
3643 : /// [version] The backup from which to delete the key.
3644 0 : Future<RoomKeysUpdateResponse> deleteRoomKeysByRoomId(
3645 : String roomId,
3646 : String version,
3647 : ) async {
3648 0 : final requestUri = Uri(
3649 0 : path: '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}',
3650 0 : queryParameters: {
3651 : 'version': version,
3652 : },
3653 : );
3654 0 : final request = Request('DELETE', baseUri!.resolveUri(requestUri));
3655 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3656 0 : final response = await httpClient.send(request);
3657 0 : final responseBody = await response.stream.toBytes();
3658 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3659 0 : final responseString = utf8.decode(responseBody);
3660 0 : final json = jsonDecode(responseString);
3661 0 : return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
3662 : }
3663 :
3664 : /// Retrieve the keys from the backup for a given room.
3665 : ///
3666 : /// [roomId] The ID of the room that the requested key is for.
3667 : ///
3668 : /// [version] The backup from which to retrieve the key.
3669 1 : Future<RoomKeyBackup> getRoomKeysByRoomId(
3670 : String roomId,
3671 : String version,
3672 : ) async {
3673 1 : final requestUri = Uri(
3674 2 : path: '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}',
3675 1 : queryParameters: {
3676 : 'version': version,
3677 : },
3678 : );
3679 3 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3680 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3681 2 : final response = await httpClient.send(request);
3682 2 : final responseBody = await response.stream.toBytes();
3683 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3684 1 : final responseString = utf8.decode(responseBody);
3685 1 : final json = jsonDecode(responseString);
3686 1 : return RoomKeyBackup.fromJson(json as Map<String, Object?>);
3687 : }
3688 :
3689 : /// Store several keys in the backup for a given room.
3690 : ///
3691 : /// [roomId] The ID of the room that the keys are for.
3692 : ///
3693 : /// [version] The backup in which to store the keys. Must be the current backup.
3694 : ///
3695 : /// [body] The backup data
3696 0 : Future<RoomKeysUpdateResponse> putRoomKeysByRoomId(
3697 : String roomId,
3698 : String version,
3699 : RoomKeyBackup body,
3700 : ) async {
3701 0 : final requestUri = Uri(
3702 0 : path: '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}',
3703 0 : queryParameters: {
3704 : 'version': version,
3705 : },
3706 : );
3707 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
3708 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3709 0 : request.headers['content-type'] = 'application/json';
3710 0 : request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
3711 0 : final response = await httpClient.send(request);
3712 0 : final responseBody = await response.stream.toBytes();
3713 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3714 0 : final responseString = utf8.decode(responseBody);
3715 0 : final json = jsonDecode(responseString);
3716 0 : return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
3717 : }
3718 :
3719 : /// Delete a key from the backup.
3720 : ///
3721 : /// [roomId] The ID of the room that the specified key is for.
3722 : ///
3723 : /// [sessionId] The ID of the megolm session whose key is to be deleted.
3724 : ///
3725 : /// [version] The backup from which to delete the key
3726 0 : Future<RoomKeysUpdateResponse> deleteRoomKeyBySessionId(
3727 : String roomId,
3728 : String sessionId,
3729 : String version,
3730 : ) async {
3731 0 : final requestUri = Uri(
3732 : path:
3733 0 : '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}/${Uri.encodeComponent(sessionId)}',
3734 0 : queryParameters: {
3735 : 'version': version,
3736 : },
3737 : );
3738 0 : final request = Request('DELETE', baseUri!.resolveUri(requestUri));
3739 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3740 0 : final response = await httpClient.send(request);
3741 0 : final responseBody = await response.stream.toBytes();
3742 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3743 0 : final responseString = utf8.decode(responseBody);
3744 0 : final json = jsonDecode(responseString);
3745 0 : return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
3746 : }
3747 :
3748 : /// Retrieve a key from the backup.
3749 : ///
3750 : /// [roomId] The ID of the room that the requested key is for.
3751 : ///
3752 : /// [sessionId] The ID of the megolm session whose key is requested.
3753 : ///
3754 : /// [version] The backup from which to retrieve the key.
3755 1 : Future<KeyBackupData> getRoomKeyBySessionId(
3756 : String roomId,
3757 : String sessionId,
3758 : String version,
3759 : ) async {
3760 1 : final requestUri = Uri(
3761 : path:
3762 3 : '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}/${Uri.encodeComponent(sessionId)}',
3763 1 : queryParameters: {
3764 : 'version': version,
3765 : },
3766 : );
3767 3 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3768 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3769 2 : final response = await httpClient.send(request);
3770 2 : final responseBody = await response.stream.toBytes();
3771 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3772 1 : final responseString = utf8.decode(responseBody);
3773 1 : final json = jsonDecode(responseString);
3774 1 : return KeyBackupData.fromJson(json as Map<String, Object?>);
3775 : }
3776 :
3777 : /// Store a key in the backup.
3778 : ///
3779 : /// [roomId] The ID of the room that the key is for.
3780 : ///
3781 : /// [sessionId] The ID of the megolm session that the key is for.
3782 : ///
3783 : /// [version] The backup in which to store the key. Must be the current backup.
3784 : ///
3785 : /// [body] The key data.
3786 0 : Future<RoomKeysUpdateResponse> putRoomKeyBySessionId(
3787 : String roomId,
3788 : String sessionId,
3789 : String version,
3790 : KeyBackupData body,
3791 : ) async {
3792 0 : final requestUri = Uri(
3793 : path:
3794 0 : '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}/${Uri.encodeComponent(sessionId)}',
3795 0 : queryParameters: {
3796 : 'version': version,
3797 : },
3798 : );
3799 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
3800 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3801 0 : request.headers['content-type'] = 'application/json';
3802 0 : request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
3803 0 : final response = await httpClient.send(request);
3804 0 : final responseBody = await response.stream.toBytes();
3805 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3806 0 : final responseString = utf8.decode(responseBody);
3807 0 : final json = jsonDecode(responseString);
3808 0 : return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
3809 : }
3810 :
3811 : /// Get information about the latest backup version.
3812 5 : Future<GetRoomKeysVersionCurrentResponse> getRoomKeysVersionCurrent() async {
3813 5 : final requestUri = Uri(path: '_matrix/client/v3/room_keys/version');
3814 15 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3815 20 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3816 10 : final response = await httpClient.send(request);
3817 10 : final responseBody = await response.stream.toBytes();
3818 10 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3819 5 : final responseString = utf8.decode(responseBody);
3820 5 : final json = jsonDecode(responseString);
3821 5 : return GetRoomKeysVersionCurrentResponse.fromJson(
3822 : json as Map<String, Object?>,
3823 : );
3824 : }
3825 :
3826 : /// Creates a new backup.
3827 : ///
3828 : /// [algorithm] The algorithm used for storing backups.
3829 : ///
3830 : /// [authData] Algorithm-dependent data. See the documentation for the backup
3831 : /// algorithms in [Server-side key backups](https://spec.matrix.org/unstable/client-server-api/#server-side-key-backups) for more information on the
3832 : /// expected format of the data.
3833 : ///
3834 : /// returns `version`:
3835 : /// The backup version. This is an opaque string.
3836 1 : Future<String> postRoomKeysVersion(
3837 : BackupAlgorithm algorithm,
3838 : Map<String, Object?> authData,
3839 : ) async {
3840 1 : final requestUri = Uri(path: '_matrix/client/v3/room_keys/version');
3841 3 : final request = Request('POST', baseUri!.resolveUri(requestUri));
3842 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3843 2 : request.headers['content-type'] = 'application/json';
3844 2 : request.bodyBytes = utf8.encode(
3845 2 : jsonEncode({
3846 1 : 'algorithm': algorithm.name,
3847 : 'auth_data': authData,
3848 : }),
3849 : );
3850 2 : final response = await httpClient.send(request);
3851 2 : final responseBody = await response.stream.toBytes();
3852 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3853 1 : final responseString = utf8.decode(responseBody);
3854 1 : final json = jsonDecode(responseString);
3855 1 : return json['version'] as String;
3856 : }
3857 :
3858 : /// Delete an existing key backup. Both the information about the backup,
3859 : /// as well as all key data related to the backup will be deleted.
3860 : ///
3861 : /// [version] The backup version to delete, as returned in the `version`
3862 : /// parameter in the response of
3863 : /// [`POST /_matrix/client/v3/room_keys/version`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3room_keysversion)
3864 : /// or [`GET /_matrix/client/v3/room_keys/version/{version}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3room_keysversionversion).
3865 0 : Future<void> deleteRoomKeysVersion(String version) async {
3866 0 : final requestUri = Uri(
3867 : path:
3868 0 : '_matrix/client/v3/room_keys/version/${Uri.encodeComponent(version)}',
3869 : );
3870 0 : final request = Request('DELETE', baseUri!.resolveUri(requestUri));
3871 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3872 0 : final response = await httpClient.send(request);
3873 0 : final responseBody = await response.stream.toBytes();
3874 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3875 0 : final responseString = utf8.decode(responseBody);
3876 0 : final json = jsonDecode(responseString);
3877 0 : return ignore(json);
3878 : }
3879 :
3880 : /// Get information about an existing backup.
3881 : ///
3882 : /// [version] The backup version to get, as returned in the `version` parameter
3883 : /// of the response in
3884 : /// [`POST /_matrix/client/v3/room_keys/version`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3room_keysversion)
3885 : /// or this endpoint.
3886 0 : Future<GetRoomKeysVersionResponse> getRoomKeysVersion(String version) async {
3887 0 : final requestUri = Uri(
3888 : path:
3889 0 : '_matrix/client/v3/room_keys/version/${Uri.encodeComponent(version)}',
3890 : );
3891 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3892 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3893 0 : final response = await httpClient.send(request);
3894 0 : final responseBody = await response.stream.toBytes();
3895 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3896 0 : final responseString = utf8.decode(responseBody);
3897 0 : final json = jsonDecode(responseString);
3898 0 : return GetRoomKeysVersionResponse.fromJson(json as Map<String, Object?>);
3899 : }
3900 :
3901 : /// Update information about an existing backup. Only `auth_data` can be modified.
3902 : ///
3903 : /// [version] The backup version to update, as returned in the `version`
3904 : /// parameter in the response of
3905 : /// [`POST /_matrix/client/v3/room_keys/version`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3room_keysversion)
3906 : /// or [`GET /_matrix/client/v3/room_keys/version/{version}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3room_keysversionversion).
3907 : ///
3908 : /// [algorithm] The algorithm used for storing backups. Must be the same as
3909 : /// the algorithm currently used by the backup.
3910 : ///
3911 : /// [authData] Algorithm-dependent data. See the documentation for the backup
3912 : /// algorithms in [Server-side key backups](https://spec.matrix.org/unstable/client-server-api/#server-side-key-backups) for more information on the
3913 : /// expected format of the data.
3914 0 : Future<Map<String, Object?>> putRoomKeysVersion(
3915 : String version,
3916 : BackupAlgorithm algorithm,
3917 : Map<String, Object?> authData,
3918 : ) async {
3919 0 : final requestUri = Uri(
3920 : path:
3921 0 : '_matrix/client/v3/room_keys/version/${Uri.encodeComponent(version)}',
3922 : );
3923 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
3924 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3925 0 : request.headers['content-type'] = 'application/json';
3926 0 : request.bodyBytes = utf8.encode(
3927 0 : jsonEncode({
3928 0 : 'algorithm': algorithm.name,
3929 : 'auth_data': authData,
3930 : }),
3931 : );
3932 0 : final response = await httpClient.send(request);
3933 0 : final responseBody = await response.stream.toBytes();
3934 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3935 0 : final responseString = utf8.decode(responseBody);
3936 0 : final json = jsonDecode(responseString);
3937 : return json as Map<String, Object?>;
3938 : }
3939 :
3940 : /// Get a list of aliases maintained by the local server for the
3941 : /// given room.
3942 : ///
3943 : /// This endpoint can be called by users who are in the room (external
3944 : /// users receive an `M_FORBIDDEN` error response). If the room's
3945 : /// `m.room.history_visibility` maps to `world_readable`, any
3946 : /// user can call this endpoint.
3947 : ///
3948 : /// Servers may choose to implement additional access control checks here,
3949 : /// such as allowing server administrators to view aliases regardless of
3950 : /// membership.
3951 : ///
3952 : /// **Note:**
3953 : /// Clients are recommended not to display this list of aliases prominently
3954 : /// as they are not curated, unlike those listed in the `m.room.canonical_alias`
3955 : /// state event.
3956 : ///
3957 : /// [roomId] The room ID to find local aliases of.
3958 : ///
3959 : /// returns `aliases`:
3960 : /// The server's local aliases on the room. Can be empty.
3961 0 : Future<List<String>> getLocalAliases(String roomId) async {
3962 0 : final requestUri = Uri(
3963 0 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/aliases',
3964 : );
3965 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
3966 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3967 0 : final response = await httpClient.send(request);
3968 0 : final responseBody = await response.stream.toBytes();
3969 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
3970 0 : final responseString = utf8.decode(responseBody);
3971 0 : final json = jsonDecode(responseString);
3972 0 : return (json['aliases'] as List).map((v) => v as String).toList();
3973 : }
3974 :
3975 : /// Ban a user in the room. If the user is currently in the room, also kick them.
3976 : ///
3977 : /// When a user is banned from a room, they may not join it or be invited to it until they are unbanned.
3978 : ///
3979 : /// The caller must have the required power level in order to perform this operation.
3980 : ///
3981 : /// [roomId] The room identifier (not alias) from which the user should be banned.
3982 : ///
3983 : /// [reason] The reason the user has been banned. This will be supplied as the `reason` on the target's updated [`m.room.member`](https://spec.matrix.org/unstable/client-server-api/#mroommember) event.
3984 : ///
3985 : /// [userId] The fully qualified user ID of the user being banned.
3986 5 : Future<void> ban(String roomId, String userId, {String? reason}) async {
3987 : final requestUri =
3988 15 : Uri(path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/ban');
3989 15 : final request = Request('POST', baseUri!.resolveUri(requestUri));
3990 20 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
3991 10 : request.headers['content-type'] = 'application/json';
3992 10 : request.bodyBytes = utf8.encode(
3993 10 : jsonEncode({
3994 0 : if (reason != null) 'reason': reason,
3995 5 : 'user_id': userId,
3996 : }),
3997 : );
3998 10 : final response = await httpClient.send(request);
3999 10 : final responseBody = await response.stream.toBytes();
4000 10 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4001 5 : final responseString = utf8.decode(responseBody);
4002 5 : final json = jsonDecode(responseString);
4003 5 : return ignore(json);
4004 : }
4005 :
4006 : /// This API returns a number of events that happened just before and
4007 : /// after the specified event. This allows clients to get the context
4008 : /// surrounding an event.
4009 : ///
4010 : /// *Note*: This endpoint supports lazy-loading of room member events. See
4011 : /// [Lazy-loading room members](https://spec.matrix.org/unstable/client-server-api/#lazy-loading-room-members) for more information.
4012 : ///
4013 : /// [roomId] The room to get events from.
4014 : ///
4015 : /// [eventId] The event to get context around.
4016 : ///
4017 : /// [limit] The maximum number of context events to return. The limit applies
4018 : /// to the sum of the `events_before` and `events_after` arrays. The
4019 : /// requested event ID is always returned in `event` even if `limit` is
4020 : /// 0. Defaults to 10.
4021 : ///
4022 : /// [filter] A JSON `RoomEventFilter` to filter the returned events with. The
4023 : /// filter is only applied to `events_before`, `events_after`, and
4024 : /// `state`. It is not applied to the `event` itself. The filter may
4025 : /// be applied before or/and after the `limit` parameter - whichever the
4026 : /// homeserver prefers.
4027 : ///
4028 : /// See [Filtering](https://spec.matrix.org/unstable/client-server-api/#filtering) for more information.
4029 0 : Future<EventContext> getEventContext(
4030 : String roomId,
4031 : String eventId, {
4032 : int? limit,
4033 : String? filter,
4034 : }) async {
4035 0 : final requestUri = Uri(
4036 : path:
4037 0 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/context/${Uri.encodeComponent(eventId)}',
4038 0 : queryParameters: {
4039 0 : if (limit != null) 'limit': limit.toString(),
4040 0 : if (filter != null) 'filter': filter,
4041 : },
4042 : );
4043 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
4044 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4045 0 : final response = await httpClient.send(request);
4046 0 : final responseBody = await response.stream.toBytes();
4047 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4048 0 : final responseString = utf8.decode(responseBody);
4049 0 : final json = jsonDecode(responseString);
4050 0 : return EventContext.fromJson(json as Map<String, Object?>);
4051 : }
4052 :
4053 : /// Get a single event based on `roomId/eventId`. You must have permission to
4054 : /// retrieve this event e.g. by being a member in the room for this event.
4055 : ///
4056 : /// [roomId] The ID of the room the event is in.
4057 : ///
4058 : /// [eventId] The event ID to get.
4059 5 : Future<MatrixEvent> getOneRoomEvent(String roomId, String eventId) async {
4060 5 : final requestUri = Uri(
4061 : path:
4062 15 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/event/${Uri.encodeComponent(eventId)}',
4063 : );
4064 15 : final request = Request('GET', baseUri!.resolveUri(requestUri));
4065 20 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4066 10 : final response = await httpClient.send(request);
4067 10 : final responseBody = await response.stream.toBytes();
4068 12 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4069 5 : final responseString = utf8.decode(responseBody);
4070 5 : final json = jsonDecode(responseString);
4071 5 : return MatrixEvent.fromJson(json as Map<String, Object?>);
4072 : }
4073 :
4074 : /// This API stops a user remembering about a particular room.
4075 : ///
4076 : /// In general, history is a first class citizen in Matrix. After this API
4077 : /// is called, however, a user will no longer be able to retrieve history
4078 : /// for this room. If all users on a homeserver forget a room, the room is
4079 : /// eligible for deletion from that homeserver.
4080 : ///
4081 : /// If the user is currently joined to the room, they must leave the room
4082 : /// before calling this API.
4083 : ///
4084 : /// [roomId] The room identifier to forget.
4085 0 : Future<void> forgetRoom(String roomId) async {
4086 0 : final requestUri = Uri(
4087 0 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/forget',
4088 : );
4089 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4090 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4091 0 : final response = await httpClient.send(request);
4092 0 : final responseBody = await response.stream.toBytes();
4093 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4094 0 : final responseString = utf8.decode(responseBody);
4095 0 : final json = jsonDecode(responseString);
4096 0 : return ignore(json);
4097 : }
4098 :
4099 : /// *Note that there are two forms of this API, which are documented separately.
4100 : /// This version of the API does not require that the inviter know the Matrix
4101 : /// identifier of the invitee, and instead relies on third-party identifiers.
4102 : /// The homeserver uses an identity server to perform the mapping from
4103 : /// third-party identifier to a Matrix identifier. The other is documented in the*
4104 : /// [joining rooms section](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3roomsroomidinvite).
4105 : ///
4106 : /// This API invites a user to participate in a particular room.
4107 : /// They do not start participating in the room until they actually join the
4108 : /// room.
4109 : ///
4110 : /// Only users currently in a particular room can invite other users to
4111 : /// join that room.
4112 : ///
4113 : /// If the identity server did know the Matrix user identifier for the
4114 : /// third-party identifier, the homeserver will append a `m.room.member`
4115 : /// event to the room.
4116 : ///
4117 : /// If the identity server does not know a Matrix user identifier for the
4118 : /// passed third-party identifier, the homeserver will issue an invitation
4119 : /// which can be accepted upon providing proof of ownership of the third-
4120 : /// party identifier. This is achieved by the identity server generating a
4121 : /// token, which it gives to the inviting homeserver. The homeserver will
4122 : /// add an `m.room.third_party_invite` event into the graph for the room,
4123 : /// containing that token.
4124 : ///
4125 : /// When the invitee binds the invited third-party identifier to a Matrix
4126 : /// user ID, the identity server will give the user a list of pending
4127 : /// invitations, each containing:
4128 : ///
4129 : /// - The room ID to which they were invited
4130 : ///
4131 : /// - The token given to the homeserver
4132 : ///
4133 : /// - A signature of the token, signed with the identity server's private key
4134 : ///
4135 : /// - The matrix user ID who invited them to the room
4136 : ///
4137 : /// If a token is requested from the identity server, the homeserver will
4138 : /// append a `m.room.third_party_invite` event to the room.
4139 : ///
4140 : /// [roomId] The room identifier (not alias) to which to invite the user.
4141 : ///
4142 : /// [body]
4143 0 : Future<void> inviteBy3PID(String roomId, Invite3pid body) async {
4144 0 : final requestUri = Uri(
4145 0 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/invite',
4146 : );
4147 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4148 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4149 0 : request.headers['content-type'] = 'application/json';
4150 0 : request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
4151 0 : final response = await httpClient.send(request);
4152 0 : final responseBody = await response.stream.toBytes();
4153 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4154 0 : final responseString = utf8.decode(responseBody);
4155 0 : final json = jsonDecode(responseString);
4156 0 : return ignore(json);
4157 : }
4158 :
4159 : /// *Note that there are two forms of this API, which are documented separately.
4160 : /// This version of the API requires that the inviter knows the Matrix
4161 : /// identifier of the invitee. The other is documented in the
4162 : /// [third-party invites](https://spec.matrix.org/unstable/client-server-api/#third-party-invites) section.*
4163 : ///
4164 : /// This API invites a user to participate in a particular room.
4165 : /// They do not start participating in the room until they actually join the
4166 : /// room.
4167 : ///
4168 : /// Only users currently in a particular room can invite other users to
4169 : /// join that room.
4170 : ///
4171 : /// If the user was invited to the room, the homeserver will append a
4172 : /// `m.room.member` event to the room.
4173 : ///
4174 : /// [roomId] The room identifier (not alias) to which to invite the user.
4175 : ///
4176 : /// [reason] Optional reason to be included as the `reason` on the subsequent
4177 : /// membership event.
4178 : ///
4179 : /// [userId] The fully qualified user ID of the invitee.
4180 3 : Future<void> inviteUser(
4181 : String roomId,
4182 : String userId, {
4183 : String? reason,
4184 : }) async {
4185 3 : final requestUri = Uri(
4186 6 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/invite',
4187 : );
4188 9 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4189 12 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4190 6 : request.headers['content-type'] = 'application/json';
4191 6 : request.bodyBytes = utf8.encode(
4192 6 : jsonEncode({
4193 0 : if (reason != null) 'reason': reason,
4194 3 : 'user_id': userId,
4195 : }),
4196 : );
4197 6 : final response = await httpClient.send(request);
4198 6 : final responseBody = await response.stream.toBytes();
4199 6 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4200 3 : final responseString = utf8.decode(responseBody);
4201 3 : final json = jsonDecode(responseString);
4202 3 : return ignore(json);
4203 : }
4204 :
4205 : /// *Note that this API requires a room ID, not alias.*
4206 : /// `/join/{roomIdOrAlias}` *exists if you have a room alias.*
4207 : ///
4208 : /// This API starts a user's participation in a particular room, if that user
4209 : /// is allowed to participate in that room. After this call, the client is
4210 : /// allowed to see all current state events in the room, and all subsequent
4211 : /// events associated with the room until the user leaves the room.
4212 : ///
4213 : /// After a user has joined a room, the room will appear as an entry in the
4214 : /// response of the [`/initialSync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3initialsync)
4215 : /// and [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync) APIs.
4216 : ///
4217 : /// [roomId] The room identifier (not alias) to join.
4218 : ///
4219 : /// [reason] Optional reason to be included as the `reason` on the subsequent
4220 : /// membership event.
4221 : ///
4222 : /// [thirdPartySigned] If supplied, the homeserver must verify that it matches a pending
4223 : /// `m.room.third_party_invite` event in the room, and perform
4224 : /// key validity checking if required by the event.
4225 : ///
4226 : /// returns `room_id`:
4227 : /// The joined room ID.
4228 0 : Future<String> joinRoomById(
4229 : String roomId, {
4230 : String? reason,
4231 : ThirdPartySigned? thirdPartySigned,
4232 : }) async {
4233 0 : final requestUri = Uri(
4234 0 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/join',
4235 : );
4236 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4237 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4238 0 : request.headers['content-type'] = 'application/json';
4239 0 : request.bodyBytes = utf8.encode(
4240 0 : jsonEncode({
4241 0 : if (reason != null) 'reason': reason,
4242 : if (thirdPartySigned != null)
4243 0 : 'third_party_signed': thirdPartySigned.toJson(),
4244 : }),
4245 : );
4246 0 : final response = await httpClient.send(request);
4247 0 : final responseBody = await response.stream.toBytes();
4248 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4249 0 : final responseString = utf8.decode(responseBody);
4250 0 : final json = jsonDecode(responseString);
4251 0 : return json['room_id'] as String;
4252 : }
4253 :
4254 : /// This API returns a map of MXIDs to member info objects for members of the room. The current user must be in the room for it to work, unless it is an Application Service in which case any of the AS's users must be in the room. This API is primarily for Application Services and should be faster to respond than `/members` as it can be implemented more efficiently on the server.
4255 : ///
4256 : /// [roomId] The room to get the members of.
4257 : ///
4258 : /// returns `joined`:
4259 : /// A map from user ID to a RoomMember object.
4260 0 : Future<Map<String, RoomMember>?> getJoinedMembersByRoom(String roomId) async {
4261 0 : final requestUri = Uri(
4262 : path:
4263 0 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/joined_members',
4264 : );
4265 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
4266 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4267 0 : final response = await httpClient.send(request);
4268 0 : final responseBody = await response.stream.toBytes();
4269 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4270 0 : final responseString = utf8.decode(responseBody);
4271 0 : final json = jsonDecode(responseString);
4272 0 : return ((v) => v != null
4273 0 : ? (v as Map<String, Object?>).map(
4274 0 : (k, v) =>
4275 0 : MapEntry(k, RoomMember.fromJson(v as Map<String, Object?>)),
4276 : )
4277 0 : : null)(json['joined']);
4278 : }
4279 :
4280 : /// Kick a user from the room.
4281 : ///
4282 : /// The caller must have the required power level in order to perform this operation.
4283 : ///
4284 : /// Kicking a user adjusts the target member's membership state to be `leave` with an
4285 : /// optional `reason`. Like with other membership changes, a user can directly adjust
4286 : /// the target member's state by making a request to `/rooms/<room id>/state/m.room.member/<user id>`.
4287 : ///
4288 : /// [roomId] The room identifier (not alias) from which the user should be kicked.
4289 : ///
4290 : /// [reason] The reason the user has been kicked. This will be supplied as the
4291 : /// `reason` on the target's updated [`m.room.member`](https://spec.matrix.org/unstable/client-server-api/#mroommember) event.
4292 : ///
4293 : /// [userId] The fully qualified user ID of the user being kicked.
4294 5 : Future<void> kick(String roomId, String userId, {String? reason}) async {
4295 5 : final requestUri = Uri(
4296 10 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/kick',
4297 : );
4298 15 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4299 20 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4300 10 : request.headers['content-type'] = 'application/json';
4301 10 : request.bodyBytes = utf8.encode(
4302 10 : jsonEncode({
4303 0 : if (reason != null) 'reason': reason,
4304 5 : 'user_id': userId,
4305 : }),
4306 : );
4307 10 : final response = await httpClient.send(request);
4308 10 : final responseBody = await response.stream.toBytes();
4309 10 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4310 5 : final responseString = utf8.decode(responseBody);
4311 5 : final json = jsonDecode(responseString);
4312 5 : return ignore(json);
4313 : }
4314 :
4315 : /// This API stops a user participating in a particular room.
4316 : ///
4317 : /// If the user was already in the room, they will no longer be able to see
4318 : /// new events in the room. If the room requires an invite to join, they
4319 : /// will need to be re-invited before they can re-join.
4320 : ///
4321 : /// If the user was invited to the room, but had not joined, this call
4322 : /// serves to reject the invite.
4323 : ///
4324 : /// The user will still be allowed to retrieve history from the room which
4325 : /// they were previously allowed to see.
4326 : ///
4327 : /// [roomId] The room identifier to leave.
4328 : ///
4329 : /// [reason] Optional reason to be included as the `reason` on the subsequent
4330 : /// membership event.
4331 1 : Future<void> leaveRoom(String roomId, {String? reason}) async {
4332 1 : final requestUri = Uri(
4333 2 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/leave',
4334 : );
4335 3 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4336 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4337 2 : request.headers['content-type'] = 'application/json';
4338 2 : request.bodyBytes = utf8.encode(
4339 2 : jsonEncode({
4340 0 : if (reason != null) 'reason': reason,
4341 : }),
4342 : );
4343 2 : final response = await httpClient.send(request);
4344 2 : final responseBody = await response.stream.toBytes();
4345 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4346 1 : final responseString = utf8.decode(responseBody);
4347 1 : final json = jsonDecode(responseString);
4348 1 : return ignore(json);
4349 : }
4350 :
4351 : /// Get the list of members for this room.
4352 : ///
4353 : /// [roomId] The room to get the member events for.
4354 : ///
4355 : /// [at] The point in time (pagination token) to return members for in the room.
4356 : /// This token can be obtained from a `prev_batch` token returned for
4357 : /// each room by the sync API. Defaults to the current state of the room,
4358 : /// as determined by the server.
4359 : ///
4360 : /// [membership] The kind of membership to filter for. Defaults to no filtering if
4361 : /// unspecified. When specified alongside `not_membership`, the two
4362 : /// parameters create an 'or' condition: either the membership *is*
4363 : /// the same as `membership` **or** *is not* the same as `not_membership`.
4364 : ///
4365 : /// [notMembership] The kind of membership to exclude from the results. Defaults to no
4366 : /// filtering if unspecified.
4367 : ///
4368 : /// returns `chunk`:
4369 : ///
4370 3 : Future<List<MatrixEvent>?> getMembersByRoom(
4371 : String roomId, {
4372 : String? at,
4373 : Membership? membership,
4374 : Membership? notMembership,
4375 : }) async {
4376 3 : final requestUri = Uri(
4377 6 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/members',
4378 3 : queryParameters: {
4379 0 : if (at != null) 'at': at,
4380 0 : if (membership != null) 'membership': membership.name,
4381 0 : if (notMembership != null) 'not_membership': notMembership.name,
4382 : },
4383 : );
4384 9 : final request = Request('GET', baseUri!.resolveUri(requestUri));
4385 12 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4386 6 : final response = await httpClient.send(request);
4387 6 : final responseBody = await response.stream.toBytes();
4388 6 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4389 3 : final responseString = utf8.decode(responseBody);
4390 3 : final json = jsonDecode(responseString);
4391 3 : return ((v) => v != null
4392 : ? (v as List)
4393 9 : .map((v) => MatrixEvent.fromJson(v as Map<String, Object?>))
4394 3 : .toList()
4395 6 : : null)(json['chunk']);
4396 : }
4397 :
4398 : /// This API returns a list of message and state events for a room. It uses
4399 : /// pagination query parameters to paginate history in the room.
4400 : ///
4401 : /// *Note*: This endpoint supports lazy-loading of room member events. See
4402 : /// [Lazy-loading room members](https://spec.matrix.org/unstable/client-server-api/#lazy-loading-room-members) for more information.
4403 : ///
4404 : /// [roomId] The room to get events from.
4405 : ///
4406 : /// [from] The token to start returning events from. This token can be obtained
4407 : /// from a `prev_batch` or `next_batch` token returned by the `/sync` endpoint,
4408 : /// or from an `end` token returned by a previous request to this endpoint.
4409 : ///
4410 : /// This endpoint can also accept a value returned as a `start` token
4411 : /// by a previous request to this endpoint, though servers are not
4412 : /// required to support this. Clients should not rely on the behaviour.
4413 : ///
4414 : /// If it is not provided, the homeserver shall return a list of messages
4415 : /// from the first or last (per the value of the `dir` parameter) visible
4416 : /// event in the room history for the requesting user.
4417 : ///
4418 : /// [to] The token to stop returning events at. This token can be obtained from
4419 : /// a `prev_batch` or `next_batch` token returned by the `/sync` endpoint,
4420 : /// or from an `end` token returned by a previous request to this endpoint.
4421 : ///
4422 : /// [dir] The direction to return events from. If this is set to `f`, events
4423 : /// will be returned in chronological order starting at `from`. If it
4424 : /// is set to `b`, events will be returned in *reverse* chronological
4425 : /// order, again starting at `from`.
4426 : ///
4427 : /// [limit] The maximum number of events to return. Default: 10.
4428 : ///
4429 : /// [filter] A JSON RoomEventFilter to filter returned events with.
4430 5 : Future<GetRoomEventsResponse> getRoomEvents(
4431 : String roomId,
4432 : Direction dir, {
4433 : String? from,
4434 : String? to,
4435 : int? limit,
4436 : String? filter,
4437 : }) async {
4438 5 : final requestUri = Uri(
4439 10 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/messages',
4440 5 : queryParameters: {
4441 5 : if (from != null) 'from': from,
4442 0 : if (to != null) 'to': to,
4443 10 : 'dir': dir.name,
4444 10 : if (limit != null) 'limit': limit.toString(),
4445 5 : if (filter != null) 'filter': filter,
4446 : },
4447 : );
4448 15 : final request = Request('GET', baseUri!.resolveUri(requestUri));
4449 20 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4450 10 : final response = await httpClient.send(request);
4451 10 : final responseBody = await response.stream.toBytes();
4452 10 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4453 5 : final responseString = utf8.decode(responseBody);
4454 5 : final json = jsonDecode(responseString);
4455 5 : return GetRoomEventsResponse.fromJson(json as Map<String, Object?>);
4456 : }
4457 :
4458 : /// Sets the position of the read marker for a given room, and optionally
4459 : /// the read receipt's location.
4460 : ///
4461 : /// [roomId] The room ID to set the read marker in for the user.
4462 : ///
4463 : /// [mFullyRead] The event ID the read marker should be located at. The
4464 : /// event MUST belong to the room.
4465 : ///
4466 : /// [mRead] The event ID to set the read receipt location at. This is
4467 : /// equivalent to calling `/receipt/m.read/$elsewhere:example.org`
4468 : /// and is provided here to save that extra call.
4469 : ///
4470 : /// [mReadPrivate] The event ID to set the *private* read receipt location at. This
4471 : /// equivalent to calling `/receipt/m.read.private/$elsewhere:example.org`
4472 : /// and is provided here to save that extra call.
4473 4 : Future<void> setReadMarker(
4474 : String roomId, {
4475 : String? mFullyRead,
4476 : String? mRead,
4477 : String? mReadPrivate,
4478 : }) async {
4479 4 : final requestUri = Uri(
4480 : path:
4481 8 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/read_markers',
4482 : );
4483 12 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4484 16 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4485 8 : request.headers['content-type'] = 'application/json';
4486 8 : request.bodyBytes = utf8.encode(
4487 8 : jsonEncode({
4488 4 : if (mFullyRead != null) 'm.fully_read': mFullyRead,
4489 2 : if (mRead != null) 'm.read': mRead,
4490 2 : if (mReadPrivate != null) 'm.read.private': mReadPrivate,
4491 : }),
4492 : );
4493 8 : final response = await httpClient.send(request);
4494 8 : final responseBody = await response.stream.toBytes();
4495 8 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4496 4 : final responseString = utf8.decode(responseBody);
4497 4 : final json = jsonDecode(responseString);
4498 4 : return ignore(json);
4499 : }
4500 :
4501 : /// This API updates the marker for the given receipt type to the event ID
4502 : /// specified.
4503 : ///
4504 : /// [roomId] The room in which to send the event.
4505 : ///
4506 : /// [receiptType] The type of receipt to send. This can also be `m.fully_read` as an
4507 : /// alternative to [`/read_markers`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3roomsroomidread_markers).
4508 : ///
4509 : /// Note that `m.fully_read` does not appear under `m.receipt`: this endpoint
4510 : /// effectively calls `/read_markers` internally when presented with a receipt
4511 : /// type of `m.fully_read`.
4512 : ///
4513 : /// [eventId] The event ID to acknowledge up to.
4514 : ///
4515 : /// [threadId] The root thread event's ID (or `main`) for which
4516 : /// thread this receipt is intended to be under. If
4517 : /// not specified, the read receipt is *unthreaded*
4518 : /// (default).
4519 0 : Future<void> postReceipt(
4520 : String roomId,
4521 : ReceiptType receiptType,
4522 : String eventId, {
4523 : String? threadId,
4524 : }) async {
4525 0 : final requestUri = Uri(
4526 : path:
4527 0 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/receipt/${Uri.encodeComponent(receiptType.name)}/${Uri.encodeComponent(eventId)}',
4528 : );
4529 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4530 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4531 0 : request.headers['content-type'] = 'application/json';
4532 0 : request.bodyBytes = utf8.encode(
4533 0 : jsonEncode({
4534 0 : if (threadId != null) 'thread_id': threadId,
4535 : }),
4536 : );
4537 0 : final response = await httpClient.send(request);
4538 0 : final responseBody = await response.stream.toBytes();
4539 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4540 0 : final responseString = utf8.decode(responseBody);
4541 0 : final json = jsonDecode(responseString);
4542 0 : return ignore(json);
4543 : }
4544 :
4545 : /// Strips all information out of an event which isn't critical to the
4546 : /// integrity of the server-side representation of the room.
4547 : ///
4548 : /// This cannot be undone.
4549 : ///
4550 : /// Any user with a power level greater than or equal to the `m.room.redaction`
4551 : /// event power level may send redaction events in the room. If the user's power
4552 : /// level is also greater than or equal to the `redact` power level of the room,
4553 : /// the user may redact events sent by other users.
4554 : ///
4555 : /// Server administrators may redact events sent by users on their server.
4556 : ///
4557 : /// [roomId] The room from which to redact the event.
4558 : ///
4559 : /// [eventId] The ID of the event to redact
4560 : ///
4561 : /// [txnId] The [transaction ID](https://spec.matrix.org/unstable/client-server-api/#transaction-identifiers) for this event. Clients should generate a
4562 : /// unique ID; it will be used by the server to ensure idempotency of requests.
4563 : ///
4564 : /// [reason] The reason for the event being redacted.
4565 : ///
4566 : /// returns `event_id`:
4567 : /// A unique identifier for the event.
4568 1 : Future<String?> redactEvent(
4569 : String roomId,
4570 : String eventId,
4571 : String txnId, {
4572 : String? reason,
4573 : }) async {
4574 1 : final requestUri = Uri(
4575 : path:
4576 4 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/redact/${Uri.encodeComponent(eventId)}/${Uri.encodeComponent(txnId)}',
4577 : );
4578 3 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
4579 4 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4580 2 : request.headers['content-type'] = 'application/json';
4581 2 : request.bodyBytes = utf8.encode(
4582 2 : jsonEncode({
4583 1 : if (reason != null) 'reason': reason,
4584 : }),
4585 : );
4586 2 : final response = await httpClient.send(request);
4587 2 : final responseBody = await response.stream.toBytes();
4588 2 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4589 1 : final responseString = utf8.decode(responseBody);
4590 1 : final json = jsonDecode(responseString);
4591 3 : return ((v) => v != null ? v as String : null)(json['event_id']);
4592 : }
4593 :
4594 : /// Reports a room as inappropriate to the server, which may then notify
4595 : /// the appropriate people. How such information is delivered is left up to
4596 : /// implementations. The caller is not required to be joined to the room to
4597 : /// report it.
4598 : ///
4599 : /// [roomId] The room being reported.
4600 : ///
4601 : /// [reason] The reason the room is being reported. May be blank.
4602 0 : Future<void> reportRoom(String roomId, String reason) async {
4603 0 : final requestUri = Uri(
4604 0 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/report',
4605 : );
4606 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4607 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4608 0 : request.headers['content-type'] = 'application/json';
4609 0 : request.bodyBytes = utf8.encode(
4610 0 : jsonEncode({
4611 : 'reason': reason,
4612 : }),
4613 : );
4614 0 : final response = await httpClient.send(request);
4615 0 : final responseBody = await response.stream.toBytes();
4616 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4617 0 : final responseString = utf8.decode(responseBody);
4618 0 : final json = jsonDecode(responseString);
4619 0 : return ignore(json);
4620 : }
4621 :
4622 : /// Reports an event as inappropriate to the server, which may then notify
4623 : /// the appropriate people. The caller must be joined to the room to report
4624 : /// it.
4625 : ///
4626 : /// Furthermore, it might be possible for clients to deduce whether a reported
4627 : /// event exists by timing the response. This is because only a report for an
4628 : /// existing event will require the homeserver to do further processing. To
4629 : /// combat this, homeservers MAY add a random delay when generating a response.
4630 : ///
4631 : /// [roomId] The room in which the event being reported is located.
4632 : ///
4633 : /// [eventId] The event to report.
4634 : ///
4635 : /// [reason] The reason the content is being reported.
4636 : ///
4637 : /// [score] The score to rate this content as where -100 is most offensive
4638 : /// and 0 is inoffensive.
4639 0 : Future<void> reportEvent(
4640 : String roomId,
4641 : String eventId, {
4642 : String? reason,
4643 : int? score,
4644 : }) async {
4645 0 : final requestUri = Uri(
4646 : path:
4647 0 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/report/${Uri.encodeComponent(eventId)}',
4648 : );
4649 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4650 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4651 0 : request.headers['content-type'] = 'application/json';
4652 0 : request.bodyBytes = utf8.encode(
4653 0 : jsonEncode({
4654 0 : if (reason != null) 'reason': reason,
4655 0 : if (score != null) 'score': score,
4656 : }),
4657 : );
4658 0 : final response = await httpClient.send(request);
4659 0 : final responseBody = await response.stream.toBytes();
4660 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4661 0 : final responseString = utf8.decode(responseBody);
4662 0 : final json = jsonDecode(responseString);
4663 0 : return ignore(json);
4664 : }
4665 :
4666 : /// This endpoint is used to send a message event to a room. Message events
4667 : /// allow access to historical events and pagination, making them suited
4668 : /// for "once-off" activity in a room.
4669 : ///
4670 : /// The body of the request should be the content object of the event; the
4671 : /// fields in this object will vary depending on the type of event. See
4672 : /// [Room Events](https://spec.matrix.org/unstable/client-server-api/#room-events) for the m. event specification.
4673 : ///
4674 : /// [roomId] The room to send the event to.
4675 : ///
4676 : /// [eventType] The type of event to send.
4677 : ///
4678 : /// [txnId] The [transaction ID](https://spec.matrix.org/unstable/client-server-api/#transaction-identifiers) for this event. Clients should generate an
4679 : /// ID unique across requests with the same access token; it will be
4680 : /// used by the server to ensure idempotency of requests.
4681 : ///
4682 : /// [body]
4683 : ///
4684 : /// returns `event_id`:
4685 : /// A unique identifier for the event.
4686 13 : Future<String> sendMessage(
4687 : String roomId,
4688 : String eventType,
4689 : String txnId,
4690 : Map<String, Object?> body,
4691 : ) async {
4692 13 : final requestUri = Uri(
4693 : path:
4694 52 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/send/${Uri.encodeComponent(eventType)}/${Uri.encodeComponent(txnId)}',
4695 : );
4696 39 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
4697 52 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4698 26 : request.headers['content-type'] = 'application/json';
4699 39 : request.bodyBytes = utf8.encode(jsonEncode(body));
4700 : const maxBodySize = 60000;
4701 39 : if (request.bodyBytes.length > maxBodySize) {
4702 6 : bodySizeExceeded(maxBodySize, request.bodyBytes.length);
4703 : }
4704 26 : final response = await httpClient.send(request);
4705 26 : final responseBody = await response.stream.toBytes();
4706 30 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4707 13 : final responseString = utf8.decode(responseBody);
4708 13 : final json = jsonDecode(responseString);
4709 13 : return json['event_id'] as String;
4710 : }
4711 :
4712 : /// Get the state events for the current state of a room.
4713 : ///
4714 : /// [roomId] The room to look up the state for.
4715 0 : Future<List<MatrixEvent>> getRoomState(String roomId) async {
4716 0 : final requestUri = Uri(
4717 0 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/state',
4718 : );
4719 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
4720 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4721 0 : final response = await httpClient.send(request);
4722 0 : final responseBody = await response.stream.toBytes();
4723 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4724 0 : final responseString = utf8.decode(responseBody);
4725 0 : final json = jsonDecode(responseString);
4726 : return (json as List)
4727 0 : .map((v) => MatrixEvent.fromJson(v as Map<String, Object?>))
4728 0 : .toList();
4729 : }
4730 :
4731 : /// Looks up the contents of a state event in a room. If the user is
4732 : /// joined to the room then the state is taken from the current
4733 : /// state of the room. If the user has left the room then the state is
4734 : /// taken from the state of the room when they left.
4735 : ///
4736 : /// [roomId] The room to look up the state in.
4737 : ///
4738 : /// [eventType] The type of state to look up.
4739 : ///
4740 : /// [stateKey] The key of the state to look up. Defaults to an empty string. When
4741 : /// an empty string, the trailing slash on this endpoint is optional.
4742 8 : Future<Map<String, Object?>> getRoomStateWithKey(
4743 : String roomId,
4744 : String eventType,
4745 : String stateKey,
4746 : ) async {
4747 8 : final requestUri = Uri(
4748 : path:
4749 32 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/state/${Uri.encodeComponent(eventType)}/${Uri.encodeComponent(stateKey)}',
4750 : );
4751 22 : final request = Request('GET', baseUri!.resolveUri(requestUri));
4752 28 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4753 14 : final response = await httpClient.send(request);
4754 14 : final responseBody = await response.stream.toBytes();
4755 17 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4756 7 : final responseString = utf8.decode(responseBody);
4757 7 : final json = jsonDecode(responseString);
4758 : return json as Map<String, Object?>;
4759 : }
4760 :
4761 : /// State events can be sent using this endpoint. These events will be
4762 : /// overwritten if `<room id>`, `<event type>` and `<state key>` all
4763 : /// match.
4764 : ///
4765 : /// Requests to this endpoint **cannot use transaction IDs**
4766 : /// like other `PUT` paths because they cannot be differentiated from the
4767 : /// `state_key`. Furthermore, `POST` is unsupported on state paths.
4768 : ///
4769 : /// The body of the request should be the content object of the event; the
4770 : /// fields in this object will vary depending on the type of event. See
4771 : /// [Room Events](https://spec.matrix.org/unstable/client-server-api/#room-events) for the `m.` event specification.
4772 : ///
4773 : /// If the event type being sent is `m.room.canonical_alias` servers
4774 : /// SHOULD ensure that any new aliases being listed in the event are valid
4775 : /// per their grammar/syntax and that they point to the room ID where the
4776 : /// state event is to be sent. Servers do not validate aliases which are
4777 : /// being removed or are already present in the state event.
4778 : ///
4779 : ///
4780 : /// [roomId] The room to set the state in
4781 : ///
4782 : /// [eventType] The type of event to send.
4783 : ///
4784 : /// [stateKey] The state_key for the state to send. Defaults to the empty string. When
4785 : /// an empty string, the trailing slash on this endpoint is optional.
4786 : ///
4787 : /// [body]
4788 : ///
4789 : /// returns `event_id`:
4790 : /// A unique identifier for the event.
4791 7 : Future<String> setRoomStateWithKey(
4792 : String roomId,
4793 : String eventType,
4794 : String stateKey,
4795 : Map<String, Object?> body,
4796 : ) async {
4797 7 : final requestUri = Uri(
4798 : path:
4799 28 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/state/${Uri.encodeComponent(eventType)}/${Uri.encodeComponent(stateKey)}',
4800 : );
4801 21 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
4802 28 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4803 14 : request.headers['content-type'] = 'application/json';
4804 21 : request.bodyBytes = utf8.encode(jsonEncode(body));
4805 14 : final response = await httpClient.send(request);
4806 14 : final responseBody = await response.stream.toBytes();
4807 14 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4808 7 : final responseString = utf8.decode(responseBody);
4809 7 : final json = jsonDecode(responseString);
4810 7 : return json['event_id'] as String;
4811 : }
4812 :
4813 : /// This tells the server that the user is typing for the next N
4814 : /// milliseconds where N is the value specified in the `timeout` key.
4815 : /// Alternatively, if `typing` is `false`, it tells the server that the
4816 : /// user has stopped typing.
4817 : ///
4818 : /// [userId] The user who has started to type.
4819 : ///
4820 : /// [roomId] The room in which the user is typing.
4821 : ///
4822 : /// [timeout] The length of time in milliseconds to mark this user as typing.
4823 : ///
4824 : /// [typing] Whether the user is typing or not. If `false`, the `timeout`
4825 : /// key can be omitted.
4826 0 : Future<void> setTyping(
4827 : String userId,
4828 : String roomId,
4829 : bool typing, {
4830 : int? timeout,
4831 : }) async {
4832 0 : final requestUri = Uri(
4833 : path:
4834 0 : '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/typing/${Uri.encodeComponent(userId)}',
4835 : );
4836 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
4837 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4838 0 : request.headers['content-type'] = 'application/json';
4839 0 : request.bodyBytes = utf8.encode(
4840 0 : jsonEncode({
4841 0 : if (timeout != null) 'timeout': timeout,
4842 0 : 'typing': typing,
4843 : }),
4844 : );
4845 0 : final response = await httpClient.send(request);
4846 0 : final responseBody = await response.stream.toBytes();
4847 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4848 0 : final responseString = utf8.decode(responseBody);
4849 0 : final json = jsonDecode(responseString);
4850 0 : return ignore(json);
4851 : }
4852 :
4853 : /// Unban a user from the room. This allows them to be invited to the room,
4854 : /// and join if they would otherwise be allowed to join according to its join rules.
4855 : ///
4856 : /// The caller must have the required power level in order to perform this operation.
4857 : ///
4858 : /// [roomId] The room identifier (not alias) from which the user should be unbanned.
4859 : ///
4860 : /// [reason] Optional reason to be included as the `reason` on the subsequent
4861 : /// membership event.
4862 : ///
4863 : /// [userId] The fully qualified user ID of the user being unbanned.
4864 5 : Future<void> unban(String roomId, String userId, {String? reason}) async {
4865 5 : final requestUri = Uri(
4866 10 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/unban',
4867 : );
4868 15 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4869 20 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4870 10 : request.headers['content-type'] = 'application/json';
4871 10 : request.bodyBytes = utf8.encode(
4872 10 : jsonEncode({
4873 0 : if (reason != null) 'reason': reason,
4874 5 : 'user_id': userId,
4875 : }),
4876 : );
4877 10 : final response = await httpClient.send(request);
4878 10 : final responseBody = await response.stream.toBytes();
4879 10 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4880 5 : final responseString = utf8.decode(responseBody);
4881 5 : final json = jsonDecode(responseString);
4882 5 : return ignore(json);
4883 : }
4884 :
4885 : /// Upgrades the given room to a particular room version.
4886 : ///
4887 : /// [roomId] The ID of the room to upgrade.
4888 : ///
4889 : /// [newVersion] The new version for the room.
4890 : ///
4891 : /// returns `replacement_room`:
4892 : /// The ID of the new room.
4893 0 : Future<String> upgradeRoom(String roomId, String newVersion) async {
4894 0 : final requestUri = Uri(
4895 0 : path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/upgrade',
4896 : );
4897 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4898 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4899 0 : request.headers['content-type'] = 'application/json';
4900 0 : request.bodyBytes = utf8.encode(
4901 0 : jsonEncode({
4902 : 'new_version': newVersion,
4903 : }),
4904 : );
4905 0 : final response = await httpClient.send(request);
4906 0 : final responseBody = await response.stream.toBytes();
4907 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4908 0 : final responseString = utf8.decode(responseBody);
4909 0 : final json = jsonDecode(responseString);
4910 0 : return json['replacement_room'] as String;
4911 : }
4912 :
4913 : /// Performs a full text search across different categories.
4914 : ///
4915 : /// [nextBatch] The point to return events from. If given, this should be a
4916 : /// `next_batch` result from a previous call to this endpoint.
4917 : ///
4918 : /// [searchCategories] Describes which categories to search in and their criteria.
4919 0 : Future<SearchResults> search(
4920 : Categories searchCategories, {
4921 : String? nextBatch,
4922 : }) async {
4923 0 : final requestUri = Uri(
4924 : path: '_matrix/client/v3/search',
4925 0 : queryParameters: {
4926 0 : if (nextBatch != null) 'next_batch': nextBatch,
4927 : },
4928 : );
4929 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
4930 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4931 0 : request.headers['content-type'] = 'application/json';
4932 0 : request.bodyBytes = utf8.encode(
4933 0 : jsonEncode({
4934 0 : 'search_categories': searchCategories.toJson(),
4935 : }),
4936 : );
4937 0 : final response = await httpClient.send(request);
4938 0 : final responseBody = await response.stream.toBytes();
4939 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4940 0 : final responseString = utf8.decode(responseBody);
4941 0 : final json = jsonDecode(responseString);
4942 0 : return SearchResults.fromJson(json as Map<String, Object?>);
4943 : }
4944 :
4945 : /// This endpoint is used to send send-to-device events to a set of
4946 : /// client devices.
4947 : ///
4948 : /// [eventType] The type of event to send.
4949 : ///
4950 : /// [txnId] The [transaction ID](https://spec.matrix.org/unstable/client-server-api/#transaction-identifiers) for this event. Clients should generate an
4951 : /// ID unique across requests with the same access token; it will be
4952 : /// used by the server to ensure idempotency of requests.
4953 : ///
4954 : /// [messages] The messages to send. A map from user ID, to a map from
4955 : /// device ID to message body. The device ID may also be `*`,
4956 : /// meaning all known devices for the user.
4957 10 : Future<void> sendToDevice(
4958 : String eventType,
4959 : String txnId,
4960 : Map<String, Map<String, Map<String, Object?>>> messages,
4961 : ) async {
4962 10 : final requestUri = Uri(
4963 : path:
4964 30 : '_matrix/client/v3/sendToDevice/${Uri.encodeComponent(eventType)}/${Uri.encodeComponent(txnId)}',
4965 : );
4966 30 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
4967 40 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
4968 20 : request.headers['content-type'] = 'application/json';
4969 20 : request.bodyBytes = utf8.encode(
4970 20 : jsonEncode({
4971 : 'messages': messages
4972 51 : .map((k, v) => MapEntry(k, v.map((k, v) => MapEntry(k, v)))),
4973 : }),
4974 : );
4975 20 : final response = await httpClient.send(request);
4976 20 : final responseBody = await response.stream.toBytes();
4977 21 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
4978 10 : final responseString = utf8.decode(responseBody);
4979 10 : final json = jsonDecode(responseString);
4980 10 : return ignore(json);
4981 : }
4982 :
4983 : /// Synchronise the client's state with the latest state on the server.
4984 : /// Clients use this API when they first log in to get an initial snapshot
4985 : /// of the state on the server, and then continue to call this API to get
4986 : /// incremental deltas to the state, and to receive new messages.
4987 : ///
4988 : /// *Note*: This endpoint supports lazy-loading. See [Filtering](https://spec.matrix.org/unstable/client-server-api/#filtering)
4989 : /// for more information. Lazy-loading members is only supported on the `state` part of a
4990 : /// [`RoomFilter`](#post_matrixclientv3useruseridfilter_request_roomfilter)
4991 : /// for this endpoint. When lazy-loading is enabled, servers MUST include the
4992 : /// syncing user's own membership event when they join a room, or when the
4993 : /// full state of rooms is requested, to aid discovering the user's avatar &
4994 : /// displayname.
4995 : ///
4996 : /// Further, like other members, the user's own membership event is eligible
4997 : /// for being considered redundant by the server. When a sync is `limited`,
4998 : /// the server MUST return membership events for events in the gap
4999 : /// (between `since` and the start of the returned timeline), regardless
5000 : /// as to whether or not they are redundant. This ensures that joins/leaves
5001 : /// and profile changes which occur during the gap are not lost.
5002 : ///
5003 : /// Note that the default behaviour of `state` is to include all membership
5004 : /// events, alongside other state, when lazy-loading is not enabled.
5005 : ///
5006 : /// [filter] The ID of a filter created using the filter API or a filter JSON
5007 : /// object encoded as a string. The server will detect whether it is
5008 : /// an ID or a JSON object by whether the first character is a `"{"`
5009 : /// open brace. Passing the JSON inline is best suited to one off
5010 : /// requests. Creating a filter using the filter API is recommended for
5011 : /// clients that reuse the same filter multiple times, for example in
5012 : /// long poll requests.
5013 : ///
5014 : /// See [Filtering](https://spec.matrix.org/unstable/client-server-api/#filtering) for more information.
5015 : ///
5016 : /// [since] A point in time to continue a sync from. This should be the
5017 : /// `next_batch` token returned by an earlier call to this endpoint.
5018 : ///
5019 : /// [fullState] Controls whether to include the full state for all rooms the user
5020 : /// is a member of.
5021 : ///
5022 : /// If this is set to `true`, then all state events will be returned,
5023 : /// even if `since` is non-empty. The timeline will still be limited
5024 : /// by the `since` parameter. In this case, the `timeout` parameter
5025 : /// will be ignored and the query will return immediately, possibly with
5026 : /// an empty timeline.
5027 : ///
5028 : /// If `false`, and `since` is non-empty, only state which has
5029 : /// changed since the point indicated by `since` will be returned.
5030 : ///
5031 : /// By default, this is `false`.
5032 : ///
5033 : /// [setPresence] Controls whether the client is automatically marked as online by
5034 : /// polling this API. If this parameter is omitted then the client is
5035 : /// automatically marked as online when it uses this API. Otherwise if
5036 : /// the parameter is set to "offline" then the client is not marked as
5037 : /// being online when it uses this API. When set to "unavailable", the
5038 : /// client is marked as being idle.
5039 : ///
5040 : /// [timeout] The maximum time to wait, in milliseconds, before returning this
5041 : /// request. If no events (or other data) become available before this
5042 : /// time elapses, the server will return a response with empty fields.
5043 : ///
5044 : /// By default, this is `0`, so the server will return immediately
5045 : /// even if the response is empty.
5046 35 : Future<SyncUpdate> sync({
5047 : String? filter,
5048 : String? since,
5049 : bool? fullState,
5050 : PresenceType? setPresence,
5051 : int? timeout,
5052 : }) async {
5053 35 : final requestUri = Uri(
5054 : path: '_matrix/client/v3/sync',
5055 35 : queryParameters: {
5056 35 : if (filter != null) 'filter': filter,
5057 33 : if (since != null) 'since': since,
5058 0 : if (fullState != null) 'full_state': fullState.toString(),
5059 0 : if (setPresence != null) 'set_presence': setPresence.name,
5060 70 : if (timeout != null) 'timeout': timeout.toString(),
5061 : },
5062 : );
5063 105 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5064 140 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5065 70 : final response = await httpClient.send(request);
5066 70 : final responseBody = await response.stream.toBytes();
5067 71 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5068 35 : final responseString = utf8.decode(responseBody);
5069 35 : final json = jsonDecode(responseString);
5070 35 : return SyncUpdate.fromJson(json as Map<String, Object?>);
5071 : }
5072 :
5073 : /// Retrieve an array of third-party network locations from a Matrix room
5074 : /// alias.
5075 : ///
5076 : /// [alias] The Matrix room alias to look up.
5077 0 : Future<List<Location>> queryLocationByAlias(String alias) async {
5078 0 : final requestUri = Uri(
5079 : path: '_matrix/client/v3/thirdparty/location',
5080 0 : queryParameters: {
5081 : 'alias': alias,
5082 : },
5083 : );
5084 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5085 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5086 0 : final response = await httpClient.send(request);
5087 0 : final responseBody = await response.stream.toBytes();
5088 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5089 0 : final responseString = utf8.decode(responseBody);
5090 0 : final json = jsonDecode(responseString);
5091 : return (json as List)
5092 0 : .map((v) => Location.fromJson(v as Map<String, Object?>))
5093 0 : .toList();
5094 : }
5095 :
5096 : /// Requesting this endpoint with a valid protocol name results in a list
5097 : /// of successful mapping results in a JSON array. Each result contains
5098 : /// objects to represent the Matrix room or rooms that represent a portal
5099 : /// to this third-party network. Each has the Matrix room alias string,
5100 : /// an identifier for the particular third-party network protocol, and an
5101 : /// object containing the network-specific fields that comprise this
5102 : /// identifier. It should attempt to canonicalise the identifier as much
5103 : /// as reasonably possible given the network type.
5104 : ///
5105 : /// [protocol] The protocol used to communicate to the third-party network.
5106 : ///
5107 : /// [fields] One or more custom fields to help identify the third-party
5108 : /// location.
5109 0 : Future<List<Location>> queryLocationByProtocol(
5110 : String protocol, {
5111 : Map<String, String>? fields,
5112 : }) async {
5113 0 : final requestUri = Uri(
5114 : path:
5115 0 : '_matrix/client/v3/thirdparty/location/${Uri.encodeComponent(protocol)}',
5116 0 : queryParameters: {
5117 0 : if (fields != null) ...fields,
5118 : },
5119 : );
5120 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5121 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5122 0 : final response = await httpClient.send(request);
5123 0 : final responseBody = await response.stream.toBytes();
5124 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5125 0 : final responseString = utf8.decode(responseBody);
5126 0 : final json = jsonDecode(responseString);
5127 : return (json as List)
5128 0 : .map((v) => Location.fromJson(v as Map<String, Object?>))
5129 0 : .toList();
5130 : }
5131 :
5132 : /// Fetches the metadata from the homeserver about a particular third-party protocol.
5133 : ///
5134 : /// [protocol] The name of the protocol.
5135 0 : Future<GetProtocolMetadataResponse$2> getProtocolMetadata(
5136 : String protocol,
5137 : ) async {
5138 0 : final requestUri = Uri(
5139 : path:
5140 0 : '_matrix/client/v3/thirdparty/protocol/${Uri.encodeComponent(protocol)}',
5141 : );
5142 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5143 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5144 0 : final response = await httpClient.send(request);
5145 0 : final responseBody = await response.stream.toBytes();
5146 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5147 0 : final responseString = utf8.decode(responseBody);
5148 0 : final json = jsonDecode(responseString);
5149 0 : return GetProtocolMetadataResponse$2.fromJson(json as Map<String, Object?>);
5150 : }
5151 :
5152 : /// Fetches the overall metadata about protocols supported by the
5153 : /// homeserver. Includes both the available protocols and all fields
5154 : /// required for queries against each protocol.
5155 0 : Future<Map<String, GetProtocolsResponse$2>> getProtocols() async {
5156 0 : final requestUri = Uri(path: '_matrix/client/v3/thirdparty/protocols');
5157 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5158 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5159 0 : final response = await httpClient.send(request);
5160 0 : final responseBody = await response.stream.toBytes();
5161 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5162 0 : final responseString = utf8.decode(responseBody);
5163 0 : final json = jsonDecode(responseString);
5164 0 : return (json as Map<String, Object?>).map(
5165 0 : (k, v) => MapEntry(
5166 : k,
5167 0 : GetProtocolsResponse$2.fromJson(v as Map<String, Object?>),
5168 : ),
5169 : );
5170 : }
5171 :
5172 : /// Retrieve an array of third-party users from a Matrix User ID.
5173 : ///
5174 : /// [userid] The Matrix User ID to look up.
5175 0 : Future<List<ThirdPartyUser>> queryUserByID(String userid) async {
5176 0 : final requestUri = Uri(
5177 : path: '_matrix/client/v3/thirdparty/user',
5178 0 : queryParameters: {
5179 : 'userid': userid,
5180 : },
5181 : );
5182 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5183 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5184 0 : final response = await httpClient.send(request);
5185 0 : final responseBody = await response.stream.toBytes();
5186 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5187 0 : final responseString = utf8.decode(responseBody);
5188 0 : final json = jsonDecode(responseString);
5189 : return (json as List)
5190 0 : .map((v) => ThirdPartyUser.fromJson(v as Map<String, Object?>))
5191 0 : .toList();
5192 : }
5193 :
5194 : /// Retrieve a Matrix User ID linked to a user on the third-party service, given
5195 : /// a set of user parameters.
5196 : ///
5197 : /// [protocol] The name of the protocol.
5198 : ///
5199 : /// [fields] One or more custom fields that are passed to the AS to help identify the user.
5200 0 : Future<List<ThirdPartyUser>> queryUserByProtocol(
5201 : String protocol, {
5202 : Map<String, String>? fields,
5203 : }) async {
5204 0 : final requestUri = Uri(
5205 : path:
5206 0 : '_matrix/client/v3/thirdparty/user/${Uri.encodeComponent(protocol)}',
5207 0 : queryParameters: {
5208 0 : if (fields != null) ...fields,
5209 : },
5210 : );
5211 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5212 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5213 0 : final response = await httpClient.send(request);
5214 0 : final responseBody = await response.stream.toBytes();
5215 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5216 0 : final responseString = utf8.decode(responseBody);
5217 0 : final json = jsonDecode(responseString);
5218 : return (json as List)
5219 0 : .map((v) => ThirdPartyUser.fromJson(v as Map<String, Object?>))
5220 0 : .toList();
5221 : }
5222 :
5223 : /// Get some account data for the client. This config is only visible to the user
5224 : /// that set the account data.
5225 : ///
5226 : /// [userId] The ID of the user to get account data for. The access token must be
5227 : /// authorized to make requests for this user ID.
5228 : ///
5229 : /// [type] The event type of the account data to get. Custom types should be
5230 : /// namespaced to avoid clashes.
5231 0 : Future<Map<String, Object?>> getAccountData(
5232 : String userId,
5233 : String type,
5234 : ) async {
5235 0 : final requestUri = Uri(
5236 : path:
5237 0 : '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/account_data/${Uri.encodeComponent(type)}',
5238 : );
5239 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5240 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5241 0 : final response = await httpClient.send(request);
5242 0 : final responseBody = await response.stream.toBytes();
5243 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5244 0 : final responseString = utf8.decode(responseBody);
5245 0 : final json = jsonDecode(responseString);
5246 : return json as Map<String, Object?>;
5247 : }
5248 :
5249 : /// Set some account data for the client. This config is only visible to the user
5250 : /// that set the account data. The config will be available to clients through the
5251 : /// top-level `account_data` field in the homeserver response to
5252 : /// [/sync](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync).
5253 : ///
5254 : /// [userId] The ID of the user to set account data for. The access token must be
5255 : /// authorized to make requests for this user ID.
5256 : ///
5257 : /// [type] The event type of the account data to set. Custom types should be
5258 : /// namespaced to avoid clashes.
5259 : ///
5260 : /// [body] The content of the account data.
5261 10 : Future<void> setAccountData(
5262 : String userId,
5263 : String type,
5264 : Map<String, Object?> body,
5265 : ) async {
5266 10 : final requestUri = Uri(
5267 : path:
5268 30 : '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/account_data/${Uri.encodeComponent(type)}',
5269 : );
5270 30 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
5271 40 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5272 20 : request.headers['content-type'] = 'application/json';
5273 30 : request.bodyBytes = utf8.encode(jsonEncode(body));
5274 20 : final response = await httpClient.send(request);
5275 20 : final responseBody = await response.stream.toBytes();
5276 20 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5277 10 : final responseString = utf8.decode(responseBody);
5278 10 : final json = jsonDecode(responseString);
5279 10 : return ignore(json);
5280 : }
5281 :
5282 : /// Uploads a new filter definition to the homeserver.
5283 : /// Returns a filter ID that may be used in future requests to
5284 : /// restrict which events are returned to the client.
5285 : ///
5286 : /// [userId] The id of the user uploading the filter. The access token must be authorized to make requests for this user id.
5287 : ///
5288 : /// [body] The filter to upload.
5289 : ///
5290 : /// returns `filter_id`:
5291 : /// The ID of the filter that was created. Cannot start
5292 : /// with a `{` as this character is used to determine
5293 : /// if the filter provided is inline JSON or a previously
5294 : /// declared filter by homeservers on some APIs.
5295 35 : Future<String> defineFilter(String userId, Filter body) async {
5296 35 : final requestUri = Uri(
5297 70 : path: '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/filter',
5298 : );
5299 105 : final request = Request('POST', baseUri!.resolveUri(requestUri));
5300 140 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5301 70 : request.headers['content-type'] = 'application/json';
5302 140 : request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
5303 70 : final response = await httpClient.send(request);
5304 70 : final responseBody = await response.stream.toBytes();
5305 70 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5306 35 : final responseString = utf8.decode(responseBody);
5307 35 : final json = jsonDecode(responseString);
5308 35 : return json['filter_id'] as String;
5309 : }
5310 :
5311 : ///
5312 : ///
5313 : /// [userId] The user ID to download a filter for.
5314 : ///
5315 : /// [filterId] The filter ID to download.
5316 0 : Future<Filter> getFilter(String userId, String filterId) async {
5317 0 : final requestUri = Uri(
5318 : path:
5319 0 : '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/filter/${Uri.encodeComponent(filterId)}',
5320 : );
5321 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5322 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5323 0 : final response = await httpClient.send(request);
5324 0 : final responseBody = await response.stream.toBytes();
5325 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5326 0 : final responseString = utf8.decode(responseBody);
5327 0 : final json = jsonDecode(responseString);
5328 0 : return Filter.fromJson(json as Map<String, Object?>);
5329 : }
5330 :
5331 : /// Gets an OpenID token object that the requester may supply to another
5332 : /// service to verify their identity in Matrix. The generated token is only
5333 : /// valid for exchanging for user information from the federation API for
5334 : /// OpenID.
5335 : ///
5336 : /// The access token generated is only valid for the OpenID API. It cannot
5337 : /// be used to request another OpenID access token or call `/sync`, for
5338 : /// example.
5339 : ///
5340 : /// [userId] The user to request an OpenID token for. Should be the user who
5341 : /// is authenticated for the request.
5342 : ///
5343 : /// [body] An empty object. Reserved for future expansion.
5344 0 : Future<OpenIdCredentials> requestOpenIdToken(
5345 : String userId,
5346 : Map<String, Object?> body,
5347 : ) async {
5348 0 : final requestUri = Uri(
5349 : path:
5350 0 : '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/openid/request_token',
5351 : );
5352 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
5353 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5354 0 : request.headers['content-type'] = 'application/json';
5355 0 : request.bodyBytes = utf8.encode(jsonEncode(body));
5356 0 : final response = await httpClient.send(request);
5357 0 : final responseBody = await response.stream.toBytes();
5358 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5359 0 : final responseString = utf8.decode(responseBody);
5360 0 : final json = jsonDecode(responseString);
5361 0 : return OpenIdCredentials.fromJson(json as Map<String, Object?>);
5362 : }
5363 :
5364 : /// Get some account data for the client on a given room. This config is only
5365 : /// visible to the user that set the account data.
5366 : ///
5367 : /// [userId] The ID of the user to get account data for. The access token must be
5368 : /// authorized to make requests for this user ID.
5369 : ///
5370 : /// [roomId] The ID of the room to get account data for.
5371 : ///
5372 : /// [type] The event type of the account data to get. Custom types should be
5373 : /// namespaced to avoid clashes.
5374 0 : Future<Map<String, Object?>> getAccountDataPerRoom(
5375 : String userId,
5376 : String roomId,
5377 : String type,
5378 : ) async {
5379 0 : final requestUri = Uri(
5380 : path:
5381 0 : '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/rooms/${Uri.encodeComponent(roomId)}/account_data/${Uri.encodeComponent(type)}',
5382 : );
5383 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5384 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5385 0 : final response = await httpClient.send(request);
5386 0 : final responseBody = await response.stream.toBytes();
5387 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5388 0 : final responseString = utf8.decode(responseBody);
5389 0 : final json = jsonDecode(responseString);
5390 : return json as Map<String, Object?>;
5391 : }
5392 :
5393 : /// Set some account data for the client on a given room. This config is only
5394 : /// visible to the user that set the account data. The config will be delivered to
5395 : /// clients in the per-room entries via [/sync](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync).
5396 : ///
5397 : /// [userId] The ID of the user to set account data for. The access token must be
5398 : /// authorized to make requests for this user ID.
5399 : ///
5400 : /// [roomId] The ID of the room to set account data on.
5401 : ///
5402 : /// [type] The event type of the account data to set. Custom types should be
5403 : /// namespaced to avoid clashes.
5404 : ///
5405 : /// [body] The content of the account data.
5406 3 : Future<void> setAccountDataPerRoom(
5407 : String userId,
5408 : String roomId,
5409 : String type,
5410 : Map<String, Object?> body,
5411 : ) async {
5412 3 : final requestUri = Uri(
5413 : path:
5414 12 : '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/rooms/${Uri.encodeComponent(roomId)}/account_data/${Uri.encodeComponent(type)}',
5415 : );
5416 9 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
5417 12 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5418 6 : request.headers['content-type'] = 'application/json';
5419 9 : request.bodyBytes = utf8.encode(jsonEncode(body));
5420 6 : final response = await httpClient.send(request);
5421 6 : final responseBody = await response.stream.toBytes();
5422 6 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5423 3 : final responseString = utf8.decode(responseBody);
5424 3 : final json = jsonDecode(responseString);
5425 3 : return ignore(json);
5426 : }
5427 :
5428 : /// List the tags set by a user on a room.
5429 : ///
5430 : /// [userId] The id of the user to get tags for. The access token must be
5431 : /// authorized to make requests for this user ID.
5432 : ///
5433 : /// [roomId] The ID of the room to get tags for.
5434 : ///
5435 : /// returns `tags`:
5436 : ///
5437 0 : Future<Map<String, Tag>?> getRoomTags(String userId, String roomId) async {
5438 0 : final requestUri = Uri(
5439 : path:
5440 0 : '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/rooms/${Uri.encodeComponent(roomId)}/tags',
5441 : );
5442 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5443 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5444 0 : final response = await httpClient.send(request);
5445 0 : final responseBody = await response.stream.toBytes();
5446 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5447 0 : final responseString = utf8.decode(responseBody);
5448 0 : final json = jsonDecode(responseString);
5449 0 : return ((v) => v != null
5450 : ? (v as Map<String, Object?>)
5451 0 : .map((k, v) => MapEntry(k, Tag.fromJson(v as Map<String, Object?>)))
5452 0 : : null)(json['tags']);
5453 : }
5454 :
5455 : /// Remove a tag from the room.
5456 : ///
5457 : /// [userId] The id of the user to remove a tag for. The access token must be
5458 : /// authorized to make requests for this user ID.
5459 : ///
5460 : /// [roomId] The ID of the room to remove a tag from.
5461 : ///
5462 : /// [tag] The tag to remove.
5463 2 : Future<void> deleteRoomTag(String userId, String roomId, String tag) async {
5464 2 : final requestUri = Uri(
5465 : path:
5466 8 : '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/rooms/${Uri.encodeComponent(roomId)}/tags/${Uri.encodeComponent(tag)}',
5467 : );
5468 6 : final request = Request('DELETE', baseUri!.resolveUri(requestUri));
5469 8 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5470 4 : final response = await httpClient.send(request);
5471 4 : final responseBody = await response.stream.toBytes();
5472 4 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5473 2 : final responseString = utf8.decode(responseBody);
5474 2 : final json = jsonDecode(responseString);
5475 2 : return ignore(json);
5476 : }
5477 :
5478 : /// Add a tag to the room.
5479 : ///
5480 : /// [userId] The id of the user to add a tag for. The access token must be
5481 : /// authorized to make requests for this user ID.
5482 : ///
5483 : /// [roomId] The ID of the room to add a tag to.
5484 : ///
5485 : /// [tag] The tag to add.
5486 : ///
5487 : /// [body] Extra data for the tag, e.g. ordering.
5488 2 : Future<void> setRoomTag(
5489 : String userId,
5490 : String roomId,
5491 : String tag,
5492 : Tag body,
5493 : ) async {
5494 2 : final requestUri = Uri(
5495 : path:
5496 8 : '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/rooms/${Uri.encodeComponent(roomId)}/tags/${Uri.encodeComponent(tag)}',
5497 : );
5498 6 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
5499 8 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5500 4 : request.headers['content-type'] = 'application/json';
5501 8 : request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
5502 4 : final response = await httpClient.send(request);
5503 4 : final responseBody = await response.stream.toBytes();
5504 4 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5505 2 : final responseString = utf8.decode(responseBody);
5506 2 : final json = jsonDecode(responseString);
5507 2 : return ignore(json);
5508 : }
5509 :
5510 : /// Performs a search for users. The homeserver may
5511 : /// determine which subset of users are searched, however the homeserver
5512 : /// MUST at a minimum consider the users the requesting user shares a
5513 : /// room with and those who reside in public rooms (known to the homeserver).
5514 : /// The search MUST consider local users to the homeserver, and SHOULD
5515 : /// query remote users as part of the search.
5516 : ///
5517 : /// The search is performed case-insensitively on user IDs and display
5518 : /// names preferably using a collation determined based upon the
5519 : /// `Accept-Language` header provided in the request, if present.
5520 : ///
5521 : /// [limit] The maximum number of results to return. Defaults to 10.
5522 : ///
5523 : /// [searchTerm] The term to search for
5524 0 : Future<SearchUserDirectoryResponse> searchUserDirectory(
5525 : String searchTerm, {
5526 : int? limit,
5527 : }) async {
5528 0 : final requestUri = Uri(path: '_matrix/client/v3/user_directory/search');
5529 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
5530 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5531 0 : request.headers['content-type'] = 'application/json';
5532 0 : request.bodyBytes = utf8.encode(
5533 0 : jsonEncode({
5534 0 : if (limit != null) 'limit': limit,
5535 0 : 'search_term': searchTerm,
5536 : }),
5537 : );
5538 0 : final response = await httpClient.send(request);
5539 0 : final responseBody = await response.stream.toBytes();
5540 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5541 0 : final responseString = utf8.decode(responseBody);
5542 0 : final json = jsonDecode(responseString);
5543 0 : return SearchUserDirectoryResponse.fromJson(json as Map<String, Object?>);
5544 : }
5545 :
5546 : /// Reports a user as inappropriate to the server, which may then notify
5547 : /// the appropriate people. How such information is delivered is left up to
5548 : /// implementations. The caller is not required to be joined to any rooms
5549 : /// that the reported user is joined to.
5550 : ///
5551 : /// Clients may wish to [ignore](#ignoring-users) users after reporting them.
5552 : ///
5553 : /// Clients could infer whether a reported user exists based on the 404 response.
5554 : /// Homeservers that wish to conceal this information MAY return 200 responses
5555 : /// regardless of the existence of the reported user.
5556 : ///
5557 : /// Furthermore, it might be possible for clients to deduce whether a reported
5558 : /// user exists by timing the response. This is because only a report for an
5559 : /// existing user will require the homeserver to do further processing. To
5560 : /// combat this, homeservers MAY add a random delay when generating a response.
5561 : ///
5562 : /// [userId] The user being reported.
5563 : ///
5564 : /// [reason] The reason the room is being reported. May be blank.
5565 0 : Future<Map<String, Object?>> reportUser(String userId, String reason) async {
5566 0 : final requestUri = Uri(
5567 0 : path: '_matrix/client/v3/users/${Uri.encodeComponent(userId)}/report',
5568 : );
5569 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
5570 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5571 0 : request.headers['content-type'] = 'application/json';
5572 0 : request.bodyBytes = utf8.encode(
5573 0 : jsonEncode({
5574 : 'reason': reason,
5575 : }),
5576 : );
5577 0 : final response = await httpClient.send(request);
5578 0 : final responseBody = await response.stream.toBytes();
5579 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5580 0 : final responseString = utf8.decode(responseBody);
5581 0 : final json = jsonDecode(responseString);
5582 : return json as Map<String, Object?>;
5583 : }
5584 :
5585 : /// This API provides credentials for the client to use when initiating
5586 : /// calls.
5587 0 : Future<TurnServerCredentials> getTurnServer() async {
5588 0 : final requestUri = Uri(path: '_matrix/client/v3/voip/turnServer');
5589 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5590 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5591 0 : final response = await httpClient.send(request);
5592 0 : final responseBody = await response.stream.toBytes();
5593 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5594 0 : final responseString = utf8.decode(responseBody);
5595 0 : final json = jsonDecode(responseString);
5596 0 : return TurnServerCredentials.fromJson(json as Map<String, Object?>);
5597 : }
5598 :
5599 : /// Gets the versions of the specification supported by the server.
5600 : ///
5601 : /// Values will take the form `vX.Y` or `rX.Y.Z` in historical cases. See
5602 : /// [the Specification Versioning](../#specification-versions) for more
5603 : /// information.
5604 : ///
5605 : /// The server may additionally advertise experimental features it supports
5606 : /// through `unstable_features`. These features should be namespaced and
5607 : /// may optionally include version information within their name if desired.
5608 : /// Features listed here are not for optionally toggling parts of the Matrix
5609 : /// specification and should only be used to advertise support for a feature
5610 : /// which has not yet landed in the spec. For example, a feature currently
5611 : /// undergoing the proposal process may appear here and eventually be taken
5612 : /// off this list once the feature lands in the spec and the server deems it
5613 : /// reasonable to do so. Servers can choose to enable some features only for
5614 : /// some users, so clients should include authentication in the request to
5615 : /// get all the features available for the logged-in user. If no
5616 : /// authentication is provided, the server should only return the features
5617 : /// available to all users. Servers may wish to keep advertising features
5618 : /// here after they've been released into the spec to give clients a chance
5619 : /// to upgrade appropriately. Additionally, clients should avoid using
5620 : /// unstable features in their stable releases.
5621 37 : Future<GetVersionsResponse> getVersions() async {
5622 37 : final requestUri = Uri(path: '_matrix/client/versions');
5623 111 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5624 37 : if (bearerToken != null) {
5625 24 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5626 : }
5627 74 : final response = await httpClient.send(request);
5628 74 : final responseBody = await response.stream.toBytes();
5629 75 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5630 37 : final responseString = utf8.decode(responseBody);
5631 37 : final json = jsonDecode(responseString);
5632 37 : return GetVersionsResponse.fromJson(json as Map<String, Object?>);
5633 : }
5634 :
5635 : /// Creates a new `mxc://` URI, independently of the content being uploaded. The content must be provided later
5636 : /// via [`PUT /_matrix/media/v3/upload/{serverName}/{mediaId}`](https://spec.matrix.org/unstable/client-server-api/#put_matrixmediav3uploadservernamemediaid).
5637 : ///
5638 : /// The server may optionally enforce a maximum age for unused IDs,
5639 : /// and delete media IDs when the client doesn't start the upload in time,
5640 : /// or when the upload was interrupted and not resumed in time. The server
5641 : /// should include the maximum POSIX millisecond timestamp to complete the
5642 : /// upload in the `unused_expires_at` field in the response JSON. The
5643 : /// recommended default expiration is 24 hours which should be enough time
5644 : /// to accommodate users on poor connection who find a better connection to
5645 : /// complete the upload.
5646 : ///
5647 : /// As well as limiting the rate of requests to create `mxc://` URIs, the server
5648 : /// should limit the number of concurrent *pending media uploads* a given
5649 : /// user can have. A pending media upload is a created `mxc://` URI where (a)
5650 : /// the media has not yet been uploaded, and (b) has not yet expired (the
5651 : /// `unused_expires_at` timestamp has not yet passed). In both cases, the
5652 : /// server should respond with an HTTP 429 error with an errcode of
5653 : /// `M_LIMIT_EXCEEDED`.
5654 0 : Future<CreateContentResponse> createContent() async {
5655 0 : final requestUri = Uri(path: '_matrix/media/v1/create');
5656 0 : final request = Request('POST', baseUri!.resolveUri(requestUri));
5657 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5658 0 : final response = await httpClient.send(request);
5659 0 : final responseBody = await response.stream.toBytes();
5660 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5661 0 : final responseString = utf8.decode(responseBody);
5662 0 : final json = jsonDecode(responseString);
5663 0 : return CreateContentResponse.fromJson(json as Map<String, Object?>);
5664 : }
5665 :
5666 : /// {{% boxes/note %}}
5667 : /// Replaced by [`GET /_matrix/client/v1/media/config`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv1mediaconfig).
5668 : /// {{% /boxes/note %}}
5669 : ///
5670 : /// This endpoint allows clients to retrieve the configuration of the content
5671 : /// repository, such as upload limitations.
5672 : /// Clients SHOULD use this as a guide when using content repository endpoints.
5673 : /// All values are intentionally left optional. Clients SHOULD follow
5674 : /// the advice given in the field description when the field is not available.
5675 : ///
5676 : /// **NOTE:** Both clients and server administrators should be aware that proxies
5677 : /// between the client and the server may affect the apparent behaviour of content
5678 : /// repository APIs, for example, proxies may enforce a lower upload size limit
5679 : /// than is advertised by the server on this endpoint.
5680 0 : @deprecated
5681 : Future<MediaConfig> getConfig() async {
5682 0 : final requestUri = Uri(path: '_matrix/media/v3/config');
5683 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5684 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5685 0 : final response = await httpClient.send(request);
5686 0 : final responseBody = await response.stream.toBytes();
5687 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5688 0 : final responseString = utf8.decode(responseBody);
5689 0 : final json = jsonDecode(responseString);
5690 0 : return MediaConfig.fromJson(json as Map<String, Object?>);
5691 : }
5692 :
5693 : /// {{% boxes/note %}}
5694 : /// Replaced by [`GET /_matrix/client/v1/media/download/{serverName}/{mediaId}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv1mediadownloadservernamemediaid)
5695 : /// (requires authentication).
5696 : /// {{% /boxes/note %}}
5697 : ///
5698 : /// {{% boxes/warning %}}
5699 : /// {{% changed-in v="1.11" %}} This endpoint MAY return `404 M_NOT_FOUND`
5700 : /// for media which exists, but is after the server froze unauthenticated
5701 : /// media access. See [Client Behaviour](https://spec.matrix.org/unstable/client-server-api/#content-repo-client-behaviour) for more
5702 : /// information.
5703 : /// {{% /boxes/warning %}}
5704 : ///
5705 : /// [serverName] The server name from the `mxc://` URI (the authority component).
5706 : ///
5707 : ///
5708 : /// [mediaId] The media ID from the `mxc://` URI (the path component).
5709 : ///
5710 : ///
5711 : /// [allowRemote] Indicates to the server that it should not attempt to fetch the media if
5712 : /// it is deemed remote. This is to prevent routing loops where the server
5713 : /// contacts itself.
5714 : ///
5715 : /// Defaults to `true` if not provided.
5716 : ///
5717 : /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
5718 : /// start receiving data, in the case that the content has not yet been
5719 : /// uploaded. The default value is 20000 (20 seconds). The content
5720 : /// repository SHOULD impose a maximum value for this parameter. The
5721 : /// content repository MAY respond before the timeout.
5722 : ///
5723 : ///
5724 : /// [allowRedirect] Indicates to the server that it may return a 307 or 308 redirect
5725 : /// response that points at the relevant media content. When not explicitly
5726 : /// set to `true` the server must return the media content itself.
5727 : ///
5728 0 : @deprecated
5729 : Future<FileResponse> getContent(
5730 : String serverName,
5731 : String mediaId, {
5732 : bool? allowRemote,
5733 : int? timeoutMs,
5734 : bool? allowRedirect,
5735 : }) async {
5736 0 : final requestUri = Uri(
5737 : path:
5738 0 : '_matrix/media/v3/download/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}',
5739 0 : queryParameters: {
5740 0 : if (allowRemote != null) 'allow_remote': allowRemote.toString(),
5741 0 : if (timeoutMs != null) 'timeout_ms': timeoutMs.toString(),
5742 0 : if (allowRedirect != null) 'allow_redirect': allowRedirect.toString(),
5743 : },
5744 : );
5745 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5746 0 : final response = await httpClient.send(request);
5747 0 : final responseBody = await response.stream.toBytes();
5748 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5749 0 : return FileResponse(
5750 0 : contentType: response.headers['content-type'],
5751 : data: responseBody,
5752 : );
5753 : }
5754 :
5755 : /// {{% boxes/note %}}
5756 : /// Replaced by [`GET /_matrix/client/v1/media/download/{serverName}/{mediaId}/{fileName}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv1mediadownloadservernamemediaidfilename)
5757 : /// (requires authentication).
5758 : /// {{% /boxes/note %}}
5759 : ///
5760 : /// This will download content from the content repository (same as
5761 : /// the previous endpoint) but replace the target file name with the one
5762 : /// provided by the caller.
5763 : ///
5764 : /// {{% boxes/warning %}}
5765 : /// {{% changed-in v="1.11" %}} This endpoint MAY return `404 M_NOT_FOUND`
5766 : /// for media which exists, but is after the server froze unauthenticated
5767 : /// media access. See [Client Behaviour](https://spec.matrix.org/unstable/client-server-api/#content-repo-client-behaviour) for more
5768 : /// information.
5769 : /// {{% /boxes/warning %}}
5770 : ///
5771 : /// [serverName] The server name from the `mxc://` URI (the authority component).
5772 : ///
5773 : ///
5774 : /// [mediaId] The media ID from the `mxc://` URI (the path component).
5775 : ///
5776 : ///
5777 : /// [fileName] A filename to give in the `Content-Disposition` header.
5778 : ///
5779 : /// [allowRemote] Indicates to the server that it should not attempt to fetch the media if
5780 : /// it is deemed remote. This is to prevent routing loops where the server
5781 : /// contacts itself.
5782 : ///
5783 : /// Defaults to `true` if not provided.
5784 : ///
5785 : /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
5786 : /// start receiving data, in the case that the content has not yet been
5787 : /// uploaded. The default value is 20000 (20 seconds). The content
5788 : /// repository SHOULD impose a maximum value for this parameter. The
5789 : /// content repository MAY respond before the timeout.
5790 : ///
5791 : ///
5792 : /// [allowRedirect] Indicates to the server that it may return a 307 or 308 redirect
5793 : /// response that points at the relevant media content. When not explicitly
5794 : /// set to `true` the server must return the media content itself.
5795 : ///
5796 0 : @deprecated
5797 : Future<FileResponse> getContentOverrideName(
5798 : String serverName,
5799 : String mediaId,
5800 : String fileName, {
5801 : bool? allowRemote,
5802 : int? timeoutMs,
5803 : bool? allowRedirect,
5804 : }) async {
5805 0 : final requestUri = Uri(
5806 : path:
5807 0 : '_matrix/media/v3/download/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}/${Uri.encodeComponent(fileName)}',
5808 0 : queryParameters: {
5809 0 : if (allowRemote != null) 'allow_remote': allowRemote.toString(),
5810 0 : if (timeoutMs != null) 'timeout_ms': timeoutMs.toString(),
5811 0 : if (allowRedirect != null) 'allow_redirect': allowRedirect.toString(),
5812 : },
5813 : );
5814 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5815 0 : final response = await httpClient.send(request);
5816 0 : final responseBody = await response.stream.toBytes();
5817 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5818 0 : return FileResponse(
5819 0 : contentType: response.headers['content-type'],
5820 : data: responseBody,
5821 : );
5822 : }
5823 :
5824 : /// {{% boxes/note %}}
5825 : /// Replaced by [`GET /_matrix/client/v1/media/preview_url`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv1mediapreview_url).
5826 : /// {{% /boxes/note %}}
5827 : ///
5828 : /// Get information about a URL for the client. Typically this is called when a
5829 : /// client sees a URL in a message and wants to render a preview for the user.
5830 : ///
5831 : /// **Note:**
5832 : /// Clients should consider avoiding this endpoint for URLs posted in encrypted
5833 : /// rooms. Encrypted rooms often contain more sensitive information the users
5834 : /// do not want to share with the homeserver, and this can mean that the URLs
5835 : /// being shared should also not be shared with the homeserver.
5836 : ///
5837 : /// [url] The URL to get a preview of.
5838 : ///
5839 : /// [ts] The preferred point in time to return a preview for. The server may
5840 : /// return a newer version if it does not have the requested version
5841 : /// available.
5842 0 : @deprecated
5843 : Future<PreviewForUrl> getUrlPreview(Uri url, {int? ts}) async {
5844 0 : final requestUri = Uri(
5845 : path: '_matrix/media/v3/preview_url',
5846 0 : queryParameters: {
5847 0 : 'url': url.toString(),
5848 0 : if (ts != null) 'ts': ts.toString(),
5849 : },
5850 : );
5851 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5852 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5853 0 : final response = await httpClient.send(request);
5854 0 : final responseBody = await response.stream.toBytes();
5855 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5856 0 : final responseString = utf8.decode(responseBody);
5857 0 : final json = jsonDecode(responseString);
5858 0 : return PreviewForUrl.fromJson(json as Map<String, Object?>);
5859 : }
5860 :
5861 : /// {{% boxes/note %}}
5862 : /// Replaced by [`GET /_matrix/client/v1/media/thumbnail/{serverName}/{mediaId}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv1mediathumbnailservernamemediaid)
5863 : /// (requires authentication).
5864 : /// {{% /boxes/note %}}
5865 : ///
5866 : /// Download a thumbnail of content from the content repository.
5867 : /// See the [Thumbnails](https://spec.matrix.org/unstable/client-server-api/#thumbnails) section for more information.
5868 : ///
5869 : /// {{% boxes/warning %}}
5870 : /// {{% changed-in v="1.11" %}} This endpoint MAY return `404 M_NOT_FOUND`
5871 : /// for media which exists, but is after the server froze unauthenticated
5872 : /// media access. See [Client Behaviour](https://spec.matrix.org/unstable/client-server-api/#content-repo-client-behaviour) for more
5873 : /// information.
5874 : /// {{% /boxes/warning %}}
5875 : ///
5876 : /// [serverName] The server name from the `mxc://` URI (the authority component).
5877 : ///
5878 : ///
5879 : /// [mediaId] The media ID from the `mxc://` URI (the path component).
5880 : ///
5881 : ///
5882 : /// [width] The *desired* width of the thumbnail. The actual thumbnail may be
5883 : /// larger than the size specified.
5884 : ///
5885 : /// [height] The *desired* height of the thumbnail. The actual thumbnail may be
5886 : /// larger than the size specified.
5887 : ///
5888 : /// [method] The desired resizing method. See the [Thumbnails](https://spec.matrix.org/unstable/client-server-api/#thumbnails)
5889 : /// section for more information.
5890 : ///
5891 : /// [allowRemote] Indicates to the server that it should not attempt to fetch the media if
5892 : /// it is deemed remote. This is to prevent routing loops where the server
5893 : /// contacts itself.
5894 : ///
5895 : /// Defaults to `true` if not provided.
5896 : ///
5897 : /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
5898 : /// start receiving data, in the case that the content has not yet been
5899 : /// uploaded. The default value is 20000 (20 seconds). The content
5900 : /// repository SHOULD impose a maximum value for this parameter. The
5901 : /// content repository MAY respond before the timeout.
5902 : ///
5903 : ///
5904 : /// [allowRedirect] Indicates to the server that it may return a 307 or 308 redirect
5905 : /// response that points at the relevant media content. When not explicitly
5906 : /// set to `true` the server must return the media content itself.
5907 : ///
5908 : ///
5909 : /// [animated] Indicates preference for an animated thumbnail from the server, if possible. Animated
5910 : /// thumbnails typically use the content types `image/gif`, `image/png` (with APNG format),
5911 : /// `image/apng`, and `image/webp` instead of the common static `image/png` or `image/jpeg`
5912 : /// content types.
5913 : ///
5914 : /// When `true`, the server SHOULD return an animated thumbnail if possible and supported.
5915 : /// When `false`, the server MUST NOT return an animated thumbnail. For example, returning a
5916 : /// static `image/png` or `image/jpeg` thumbnail. When not provided, the server SHOULD NOT
5917 : /// return an animated thumbnail.
5918 : ///
5919 : /// Servers SHOULD prefer to return `image/webp` thumbnails when supporting animation.
5920 : ///
5921 : /// When `true` and the media cannot be animated, such as in the case of a JPEG or PDF, the
5922 : /// server SHOULD behave as though `animated` is `false`.
5923 : ///
5924 0 : @deprecated
5925 : Future<FileResponse> getContentThumbnail(
5926 : String serverName,
5927 : String mediaId,
5928 : int width,
5929 : int height, {
5930 : Method? method,
5931 : bool? allowRemote,
5932 : int? timeoutMs,
5933 : bool? allowRedirect,
5934 : bool? animated,
5935 : }) async {
5936 0 : final requestUri = Uri(
5937 : path:
5938 0 : '_matrix/media/v3/thumbnail/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}',
5939 0 : queryParameters: {
5940 0 : 'width': width.toString(),
5941 0 : 'height': height.toString(),
5942 0 : if (method != null) 'method': method.name,
5943 0 : if (allowRemote != null) 'allow_remote': allowRemote.toString(),
5944 0 : if (timeoutMs != null) 'timeout_ms': timeoutMs.toString(),
5945 0 : if (allowRedirect != null) 'allow_redirect': allowRedirect.toString(),
5946 0 : if (animated != null) 'animated': animated.toString(),
5947 : },
5948 : );
5949 0 : final request = Request('GET', baseUri!.resolveUri(requestUri));
5950 0 : final response = await httpClient.send(request);
5951 0 : final responseBody = await response.stream.toBytes();
5952 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5953 0 : return FileResponse(
5954 0 : contentType: response.headers['content-type'],
5955 : data: responseBody,
5956 : );
5957 : }
5958 :
5959 : ///
5960 : ///
5961 : /// [filename] The name of the file being uploaded
5962 : ///
5963 : /// [body]
5964 : ///
5965 : /// [contentType] **Optional.** The content type of the file being uploaded.
5966 : ///
5967 : /// Clients SHOULD always supply this header.
5968 : ///
5969 : /// Defaults to `application/octet-stream` if it is not set.
5970 : ///
5971 : ///
5972 : /// returns `content_uri`:
5973 : /// The [`mxc://` URI](https://spec.matrix.org/unstable/client-server-api/#matrix-content-mxc-uris) to the uploaded content.
5974 4 : Future<Uri> uploadContent(
5975 : Uint8List body, {
5976 : String? filename,
5977 : String? contentType,
5978 : }) async {
5979 4 : final requestUri = Uri(
5980 : path: '_matrix/media/v3/upload',
5981 4 : queryParameters: {
5982 4 : if (filename != null) 'filename': filename,
5983 : },
5984 : );
5985 12 : final request = Request('POST', baseUri!.resolveUri(requestUri));
5986 16 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
5987 8 : if (contentType != null) request.headers['content-type'] = contentType;
5988 4 : request.bodyBytes = body;
5989 8 : final response = await httpClient.send(request);
5990 8 : final responseBody = await response.stream.toBytes();
5991 8 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
5992 4 : final responseString = utf8.decode(responseBody);
5993 4 : final json = jsonDecode(responseString);
5994 8 : return ((json['content_uri'] as String).startsWith('mxc://')
5995 8 : ? Uri.parse(json['content_uri'] as String)
5996 0 : : throw Exception('Uri not an mxc URI'));
5997 : }
5998 :
5999 : /// This endpoint permits uploading content to an `mxc://` URI that was created
6000 : /// earlier via [POST /_matrix/media/v1/create](https://spec.matrix.org/unstable/client-server-api/#post_matrixmediav1create).
6001 : ///
6002 : /// [serverName] The server name from the `mxc://` URI returned by `POST /_matrix/media/v1/create` (the authority component).
6003 : ///
6004 : ///
6005 : /// [mediaId] The media ID from the `mxc://` URI returned by `POST /_matrix/media/v1/create` (the path component).
6006 : ///
6007 : ///
6008 : /// [filename] The name of the file being uploaded
6009 : ///
6010 : /// [body]
6011 : ///
6012 : /// [contentType] **Optional.** The content type of the file being uploaded.
6013 : ///
6014 : /// Clients SHOULD always supply this header.
6015 : ///
6016 : /// Defaults to `application/octet-stream` if it is not set.
6017 : ///
6018 0 : Future<Map<String, Object?>> uploadContentToMXC(
6019 : String serverName,
6020 : String mediaId,
6021 : Uint8List body, {
6022 : String? filename,
6023 : String? contentType,
6024 : }) async {
6025 0 : final requestUri = Uri(
6026 : path:
6027 0 : '_matrix/media/v3/upload/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}',
6028 0 : queryParameters: {
6029 0 : if (filename != null) 'filename': filename,
6030 : },
6031 : );
6032 0 : final request = Request('PUT', baseUri!.resolveUri(requestUri));
6033 0 : request.headers['authorization'] = 'Bearer ${bearerToken!}';
6034 0 : if (contentType != null) request.headers['content-type'] = contentType;
6035 0 : request.bodyBytes = body;
6036 0 : final response = await httpClient.send(request);
6037 0 : final responseBody = await response.stream.toBytes();
6038 0 : if (response.statusCode != 200) unexpectedResponse(response, responseBody);
6039 0 : final responseString = utf8.decode(responseBody);
6040 0 : final json = jsonDecode(responseString);
6041 : return json as Map<String, Object?>;
6042 : }
6043 : }
|