LCOV - code coverage report
Current view: top level - lib/matrix_api_lite/generated - api.dart (source / functions) Coverage Total Hit
Test: merged.info Lines: 30.7 % 2114 650
Test Date: 2025-01-14 13:39:53 Functions: - 0 0

            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           39 :   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            1 :   Future<DiscoveryInformation> getWellknown() async {
      40            1 :     final requestUri = Uri(path: '.well-known/matrix/client');
      41            3 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
      42            2 :     final response = await httpClient.send(request);
      43            2 :     final responseBody = await response.stream.toBytes();
      44            3 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
      45            1 :     final responseString = utf8.decode(responseBody);
      46            1 :     final json = jsonDecode(responseString);
      47            1 :     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              :     String? 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,
    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              :     String? 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,
    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              :     String? 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,
    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              :     String? 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,
    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            1 :         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 participating 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              :   /// [serverName] The servers to attempt to join the room through. One of the servers
    2143              :   /// must be participating in the room.
    2144              :   ///
    2145              :   /// [via] The servers to attempt to join the room through. One of the servers
    2146              :   /// must be participating in the room.
    2147              :   ///
    2148              :   /// [reason] Optional reason to be included as the `reason` on the subsequent
    2149              :   /// membership event.
    2150              :   ///
    2151              :   /// [thirdPartySigned] If a `third_party_signed` was supplied, the homeserver must verify
    2152              :   /// that it matches a pending `m.room.third_party_invite` event in the
    2153              :   /// room, and perform key validity checking if required by the event.
    2154              :   ///
    2155              :   /// returns `room_id`:
    2156              :   /// The joined room ID.
    2157            1 :   Future<String> joinRoom(
    2158              :     String roomIdOrAlias, {
    2159              :     List<String>? serverName,
    2160              :     List<String>? via,
    2161              :     String? reason,
    2162              :     ThirdPartySigned? thirdPartySigned,
    2163              :   }) async {
    2164            1 :     final requestUri = Uri(
    2165            2 :       path: '_matrix/client/v3/join/${Uri.encodeComponent(roomIdOrAlias)}',
    2166            1 :       queryParameters: {
    2167            0 :         if (serverName != null) 'server_name': serverName,
    2168            0 :         if (via != null) 'via': via,
    2169              :       },
    2170              :     );
    2171            3 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2172            4 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2173            2 :     request.headers['content-type'] = 'application/json';
    2174            2 :     request.bodyBytes = utf8.encode(
    2175            2 :       jsonEncode({
    2176            0 :         if (reason != null) 'reason': reason,
    2177              :         if (thirdPartySigned != null)
    2178            0 :           'third_party_signed': thirdPartySigned.toJson(),
    2179              :       }),
    2180              :     );
    2181            2 :     final response = await httpClient.send(request);
    2182            2 :     final responseBody = await response.stream.toBytes();
    2183            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2184            1 :     final responseString = utf8.decode(responseBody);
    2185            1 :     final json = jsonDecode(responseString);
    2186            1 :     return json['room_id'] as String;
    2187              :   }
    2188              : 
    2189              :   /// This API returns a list of the user's current rooms.
    2190              :   ///
    2191              :   /// returns `joined_rooms`:
    2192              :   /// The ID of each room in which the user has `joined` membership.
    2193            0 :   Future<List<String>> getJoinedRooms() async {
    2194            0 :     final requestUri = Uri(path: '_matrix/client/v3/joined_rooms');
    2195            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    2196            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2197            0 :     final response = await httpClient.send(request);
    2198            0 :     final responseBody = await response.stream.toBytes();
    2199            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2200            0 :     final responseString = utf8.decode(responseBody);
    2201            0 :     final json = jsonDecode(responseString);
    2202            0 :     return (json['joined_rooms'] as List).map((v) => v as String).toList();
    2203              :   }
    2204              : 
    2205              :   /// Gets a list of users who have updated their device identity keys since a
    2206              :   /// previous sync token.
    2207              :   ///
    2208              :   /// The server should include in the results any users who:
    2209              :   ///
    2210              :   /// * currently share a room with the calling user (ie, both users have
    2211              :   ///   membership state `join`); *and*
    2212              :   /// * added new device identity keys or removed an existing device with
    2213              :   ///   identity keys, between `from` and `to`.
    2214              :   ///
    2215              :   /// [from] The desired start point of the list. Should be the `next_batch` field
    2216              :   /// from a response to an earlier call to [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync). Users who have not
    2217              :   /// uploaded new device identity keys since this point, nor deleted
    2218              :   /// existing devices with identity keys since then, will be excluded
    2219              :   /// from the results.
    2220              :   ///
    2221              :   /// [to] The desired end point of the list. Should be the `next_batch`
    2222              :   /// field from a recent call to [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync) - typically the most recent
    2223              :   /// such call. This may be used by the server as a hint to check its
    2224              :   /// caches are up to date.
    2225            0 :   Future<GetKeysChangesResponse> getKeysChanges(String from, String to) async {
    2226            0 :     final requestUri = Uri(
    2227              :       path: '_matrix/client/v3/keys/changes',
    2228            0 :       queryParameters: {
    2229              :         'from': from,
    2230              :         'to': to,
    2231              :       },
    2232              :     );
    2233            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    2234            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2235            0 :     final response = await httpClient.send(request);
    2236            0 :     final responseBody = await response.stream.toBytes();
    2237            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2238            0 :     final responseString = utf8.decode(responseBody);
    2239            0 :     final json = jsonDecode(responseString);
    2240            0 :     return GetKeysChangesResponse.fromJson(json as Map<String, Object?>);
    2241              :   }
    2242              : 
    2243              :   /// Claims one-time keys for use in pre-key messages.
    2244              :   ///
    2245              :   /// The request contains the user ID, device ID and algorithm name of the
    2246              :   /// keys that are required. If a key matching these requirements can be
    2247              :   /// found, the response contains it. The returned key is a one-time key
    2248              :   /// if one is available, and otherwise a fallback key.
    2249              :   ///
    2250              :   /// One-time keys are given out in the order that they were uploaded via
    2251              :   /// [/keys/upload](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3keysupload). (All
    2252              :   /// keys uploaded within a given call to `/keys/upload` are considered
    2253              :   /// equivalent in this regard; no ordering is specified within them.)
    2254              :   ///
    2255              :   /// Servers must ensure that each one-time key is returned at most once,
    2256              :   /// so when a key has been returned, no other request will ever return
    2257              :   /// the same key.
    2258              :   ///
    2259              :   /// [oneTimeKeys] The keys to be claimed. A map from user ID, to a map from
    2260              :   /// device ID to algorithm name.
    2261              :   ///
    2262              :   /// [timeout] The time (in milliseconds) to wait when downloading keys from
    2263              :   /// remote servers. 10 seconds is the recommended default.
    2264           10 :   Future<ClaimKeysResponse> claimKeys(
    2265              :     Map<String, Map<String, String>> oneTimeKeys, {
    2266              :     int? timeout,
    2267              :   }) async {
    2268           10 :     final requestUri = Uri(path: '_matrix/client/v3/keys/claim');
    2269           30 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2270           40 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2271           20 :     request.headers['content-type'] = 'application/json';
    2272           20 :     request.bodyBytes = utf8.encode(
    2273           20 :       jsonEncode({
    2274           10 :         'one_time_keys': oneTimeKeys
    2275           60 :             .map((k, v) => MapEntry(k, v.map((k, v) => MapEntry(k, v)))),
    2276           10 :         if (timeout != null) 'timeout': timeout,
    2277              :       }),
    2278              :     );
    2279           20 :     final response = await httpClient.send(request);
    2280           20 :     final responseBody = await response.stream.toBytes();
    2281           20 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2282           10 :     final responseString = utf8.decode(responseBody);
    2283           10 :     final json = jsonDecode(responseString);
    2284           10 :     return ClaimKeysResponse.fromJson(json as Map<String, Object?>);
    2285              :   }
    2286              : 
    2287              :   /// Publishes cross-signing keys for the user.
    2288              :   ///
    2289              :   /// This API endpoint uses the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api).
    2290              :   ///
    2291              :   /// User-Interactive Authentication MUST be performed, except in these cases:
    2292              :   /// - there is no existing cross-signing master key uploaded to the homeserver, OR
    2293              :   /// - there is an existing cross-signing master key and it exactly matches the
    2294              :   ///   cross-signing master key provided in the request body. If there are any additional
    2295              :   ///   keys provided in the request (self-signing key, user-signing key) they MUST also
    2296              :   ///   match the existing keys stored on the server. In other words, the request contains
    2297              :   ///   no new keys.
    2298              :   ///
    2299              :   /// This allows clients to freely upload one set of keys, but not modify/overwrite keys if
    2300              :   /// they already exist. Allowing clients to upload the same set of keys more than once
    2301              :   /// makes this endpoint idempotent in the case where the response is lost over the network,
    2302              :   /// which would otherwise cause a UIA challenge upon retry.
    2303              :   ///
    2304              :   /// [auth] Additional authentication information for the
    2305              :   /// user-interactive authentication API.
    2306              :   ///
    2307              :   /// [masterKey] Optional. The user\'s master key.
    2308              :   ///
    2309              :   /// [selfSigningKey] Optional. The user\'s self-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              :   ///
    2314              :   /// [userSigningKey] Optional. The user\'s user-signing key. Must be signed by
    2315              :   /// the accompanying master key, or by the user\'s most recently
    2316              :   /// uploaded master key if no master key is included in the
    2317              :   /// request.
    2318            1 :   Future<void> uploadCrossSigningKeys({
    2319              :     AuthenticationData? auth,
    2320              :     MatrixCrossSigningKey? masterKey,
    2321              :     MatrixCrossSigningKey? selfSigningKey,
    2322              :     MatrixCrossSigningKey? userSigningKey,
    2323              :   }) async {
    2324              :     final requestUri =
    2325            1 :         Uri(path: '_matrix/client/v3/keys/device_signing/upload');
    2326            3 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2327            4 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2328            2 :     request.headers['content-type'] = 'application/json';
    2329            2 :     request.bodyBytes = utf8.encode(
    2330            2 :       jsonEncode({
    2331            0 :         if (auth != null) 'auth': auth.toJson(),
    2332            2 :         if (masterKey != null) 'master_key': masterKey.toJson(),
    2333            2 :         if (selfSigningKey != null) 'self_signing_key': selfSigningKey.toJson(),
    2334            2 :         if (userSigningKey != null) 'user_signing_key': userSigningKey.toJson(),
    2335              :       }),
    2336              :     );
    2337            2 :     final response = await httpClient.send(request);
    2338            2 :     final responseBody = await response.stream.toBytes();
    2339            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2340            1 :     final responseString = utf8.decode(responseBody);
    2341            1 :     final json = jsonDecode(responseString);
    2342            1 :     return ignore(json);
    2343              :   }
    2344              : 
    2345              :   /// Returns the current devices and identity keys for the given users.
    2346              :   ///
    2347              :   /// [deviceKeys] The keys to be downloaded. A map from user ID, to a list of
    2348              :   /// device IDs, or to an empty list to indicate all devices for the
    2349              :   /// corresponding user.
    2350              :   ///
    2351              :   /// [timeout] The time (in milliseconds) to wait when downloading keys from
    2352              :   /// remote servers. 10 seconds is the recommended default.
    2353           32 :   Future<QueryKeysResponse> queryKeys(
    2354              :     Map<String, List<String>> deviceKeys, {
    2355              :     int? timeout,
    2356              :   }) async {
    2357           32 :     final requestUri = Uri(path: '_matrix/client/v3/keys/query');
    2358           96 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2359          128 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2360           64 :     request.headers['content-type'] = 'application/json';
    2361           64 :     request.bodyBytes = utf8.encode(
    2362           64 :       jsonEncode({
    2363           32 :         'device_keys':
    2364          160 :             deviceKeys.map((k, v) => MapEntry(k, v.map((v) => v).toList())),
    2365           31 :         if (timeout != null) 'timeout': timeout,
    2366              :       }),
    2367              :     );
    2368           64 :     final response = await httpClient.send(request);
    2369           64 :     final responseBody = await response.stream.toBytes();
    2370           64 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2371           32 :     final responseString = utf8.decode(responseBody);
    2372           32 :     final json = jsonDecode(responseString);
    2373           32 :     return QueryKeysResponse.fromJson(json as Map<String, Object?>);
    2374              :   }
    2375              : 
    2376              :   /// Publishes cross-signing signatures for the user.
    2377              :   ///
    2378              :   /// The signed JSON object must match the key previously uploaded or
    2379              :   /// retrieved for the given key ID, with the exception of the `signatures`
    2380              :   /// property, which contains the new signature(s) to add.
    2381              :   ///
    2382              :   /// [body] A map from user ID to key ID to signed JSON objects containing the
    2383              :   /// signatures to be published.
    2384              :   ///
    2385              :   /// returns `failures`:
    2386              :   /// A map from user ID to key ID to an error for any signatures
    2387              :   /// that failed.  If a signature was invalid, the `errcode` will
    2388              :   /// be set to `M_INVALID_SIGNATURE`.
    2389            7 :   Future<Map<String, Map<String, Map<String, Object?>>>?>
    2390              :       uploadCrossSigningSignatures(
    2391              :     Map<String, Map<String, Map<String, Object?>>> body,
    2392              :   ) async {
    2393            7 :     final requestUri = Uri(path: '_matrix/client/v3/keys/signatures/upload');
    2394           21 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2395           28 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2396           14 :     request.headers['content-type'] = 'application/json';
    2397           14 :     request.bodyBytes = utf8.encode(
    2398            7 :       jsonEncode(
    2399           42 :         body.map((k, v) => MapEntry(k, v.map((k, v) => MapEntry(k, v)))),
    2400              :       ),
    2401              :     );
    2402           14 :     final response = await httpClient.send(request);
    2403           14 :     final responseBody = await response.stream.toBytes();
    2404           14 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2405            7 :     final responseString = utf8.decode(responseBody);
    2406            7 :     final json = jsonDecode(responseString);
    2407            7 :     return ((v) => v != null
    2408            7 :         ? (v as Map<String, Object?>).map(
    2409            0 :             (k, v) => MapEntry(
    2410              :               k,
    2411              :               (v as Map<String, Object?>)
    2412            0 :                   .map((k, v) => MapEntry(k, v as Map<String, Object?>)),
    2413              :             ),
    2414              :           )
    2415           14 :         : null)(json['failures']);
    2416              :   }
    2417              : 
    2418              :   /// Publishes end-to-end encryption keys for the device.
    2419              :   ///
    2420              :   /// [deviceKeys] Identity keys for the device. May be absent if no new
    2421              :   /// identity keys are required.
    2422              :   ///
    2423              :   /// [fallbackKeys] The public key which should be used if the device's one-time keys
    2424              :   /// are exhausted. The fallback key is not deleted once used, but should
    2425              :   /// be replaced when additional one-time keys are being uploaded. The
    2426              :   /// server will notify the client of the fallback key being used through
    2427              :   /// `/sync`.
    2428              :   ///
    2429              :   /// There can only be at most one key per algorithm uploaded, and the server
    2430              :   /// will only persist one key per algorithm.
    2431              :   ///
    2432              :   /// When uploading a signed key, an additional `fallback: true` key should
    2433              :   /// be included to denote that the key is a fallback key.
    2434              :   ///
    2435              :   /// May be absent if a new fallback key is not required.
    2436              :   ///
    2437              :   /// [oneTimeKeys] One-time public keys for "pre-key" messages.  The names of
    2438              :   /// the properties should be in the format
    2439              :   /// `<algorithm>:<key_id>`. The format of the key is determined
    2440              :   /// by the [key algorithm](https://spec.matrix.org/unstable/client-server-api/#key-algorithms).
    2441              :   ///
    2442              :   /// May be absent if no new one-time keys are required.
    2443              :   ///
    2444              :   /// returns `one_time_key_counts`:
    2445              :   /// For each key algorithm, the number of unclaimed one-time keys
    2446              :   /// of that type currently held on the server for this device.
    2447              :   /// If an algorithm is not listed, the count for that algorithm
    2448              :   /// is to be assumed zero.
    2449            5 :   Future<Map<String, int>> uploadKeys({
    2450              :     MatrixDeviceKeys? deviceKeys,
    2451              :     Map<String, Object?>? fallbackKeys,
    2452              :     Map<String, Object?>? oneTimeKeys,
    2453              :   }) async {
    2454            5 :     final requestUri = Uri(path: '_matrix/client/v3/keys/upload');
    2455           15 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2456           20 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2457           10 :     request.headers['content-type'] = 'application/json';
    2458           10 :     request.bodyBytes = utf8.encode(
    2459           10 :       jsonEncode({
    2460           10 :         if (deviceKeys != null) 'device_keys': deviceKeys.toJson(),
    2461            5 :         if (fallbackKeys != null) 'fallback_keys': fallbackKeys,
    2462            5 :         if (oneTimeKeys != null) 'one_time_keys': oneTimeKeys,
    2463              :       }),
    2464              :     );
    2465           10 :     final response = await httpClient.send(request);
    2466           10 :     final responseBody = await response.stream.toBytes();
    2467           10 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2468            5 :     final responseString = utf8.decode(responseBody);
    2469            5 :     final json = jsonDecode(responseString);
    2470            5 :     return (json['one_time_key_counts'] as Map<String, Object?>)
    2471           15 :         .map((k, v) => MapEntry(k, v as int));
    2472              :   }
    2473              : 
    2474              :   /// *Note that this API takes either a room ID or alias, unlike other membership APIs.*
    2475              :   ///
    2476              :   /// This API "knocks" on the room to ask for permission to join, if the user
    2477              :   /// is allowed to knock on the room. Acceptance of the knock happens out of
    2478              :   /// band from this API, meaning that the client will have to watch for updates
    2479              :   /// regarding the acceptance/rejection of the knock.
    2480              :   ///
    2481              :   /// If the room history settings allow, the user will still be able to see
    2482              :   /// history of the room while being in the "knock" state. The user will have
    2483              :   /// to accept the invitation to join the room (acceptance of knock) to see
    2484              :   /// messages reliably. See the `/join` endpoints for more information about
    2485              :   /// history visibility to the user.
    2486              :   ///
    2487              :   /// The knock will appear as an entry in the response of the
    2488              :   /// [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync) API.
    2489              :   ///
    2490              :   /// [roomIdOrAlias] The room identifier or alias to knock upon.
    2491              :   ///
    2492              :   /// [serverName] The servers to attempt to knock on the room through. One of the servers
    2493              :   /// must be participating in the room.
    2494              :   ///
    2495              :   /// [via] The servers to attempt to knock on the room through. One of the servers
    2496              :   /// must be participating in the room.
    2497              :   ///
    2498              :   /// [reason] Optional reason to be included as the `reason` on the subsequent
    2499              :   /// membership event.
    2500              :   ///
    2501              :   /// returns `room_id`:
    2502              :   /// The knocked room ID.
    2503            0 :   Future<String> knockRoom(
    2504              :     String roomIdOrAlias, {
    2505              :     List<String>? serverName,
    2506              :     List<String>? via,
    2507              :     String? reason,
    2508              :   }) async {
    2509            0 :     final requestUri = Uri(
    2510            0 :       path: '_matrix/client/v3/knock/${Uri.encodeComponent(roomIdOrAlias)}',
    2511            0 :       queryParameters: {
    2512            0 :         if (serverName != null) 'server_name': serverName,
    2513            0 :         if (via != null) 'via': via,
    2514              :       },
    2515              :     );
    2516            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2517            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2518            0 :     request.headers['content-type'] = 'application/json';
    2519            0 :     request.bodyBytes = utf8.encode(
    2520            0 :       jsonEncode({
    2521            0 :         if (reason != null) 'reason': reason,
    2522              :       }),
    2523              :     );
    2524            0 :     final response = await httpClient.send(request);
    2525            0 :     final responseBody = await response.stream.toBytes();
    2526            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2527            0 :     final responseString = utf8.decode(responseBody);
    2528            0 :     final json = jsonDecode(responseString);
    2529            0 :     return json['room_id'] as String;
    2530              :   }
    2531              : 
    2532              :   /// Gets the homeserver's supported login types to authenticate users. Clients
    2533              :   /// should pick one of these and supply it as the `type` when logging in.
    2534              :   ///
    2535              :   /// returns `flows`:
    2536              :   /// The homeserver's supported login types
    2537           35 :   Future<List<LoginFlow>?> getLoginFlows() async {
    2538           35 :     final requestUri = Uri(path: '_matrix/client/v3/login');
    2539          105 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    2540           70 :     final response = await httpClient.send(request);
    2541           70 :     final responseBody = await response.stream.toBytes();
    2542           70 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2543           35 :     final responseString = utf8.decode(responseBody);
    2544           35 :     final json = jsonDecode(responseString);
    2545           35 :     return ((v) => v != null
    2546              :         ? (v as List)
    2547          105 :             .map((v) => LoginFlow.fromJson(v as Map<String, Object?>))
    2548           35 :             .toList()
    2549           70 :         : null)(json['flows']);
    2550              :   }
    2551              : 
    2552              :   /// Authenticates the user, and issues an access token they can
    2553              :   /// use to authorize themself in subsequent requests.
    2554              :   ///
    2555              :   /// If the client does not supply a `device_id`, the server must
    2556              :   /// auto-generate one.
    2557              :   ///
    2558              :   /// The returned access token must be associated with the `device_id`
    2559              :   /// supplied by the client or generated by the server. The server may
    2560              :   /// invalidate any access token previously associated with that device. See
    2561              :   /// [Relationship between access tokens and devices](https://spec.matrix.org/unstable/client-server-api/#relationship-between-access-tokens-and-devices).
    2562              :   ///
    2563              :   /// [address] Third-party identifier for the user.  Deprecated in favour of `identifier`.
    2564              :   ///
    2565              :   /// [deviceId] ID of the client device. If this does not correspond to a
    2566              :   /// known client device, a new device will be created. The given
    2567              :   /// device ID must not be the same as a
    2568              :   /// [cross-signing](https://spec.matrix.org/unstable/client-server-api/#cross-signing) key ID.
    2569              :   /// The server will auto-generate a device_id
    2570              :   /// if this is not specified.
    2571              :   ///
    2572              :   /// [identifier] Identification information for a user
    2573              :   ///
    2574              :   /// [initialDeviceDisplayName] A display name to assign to the newly-created device. Ignored
    2575              :   /// if `device_id` corresponds to a known device.
    2576              :   ///
    2577              :   /// [medium] When logging in using a third-party identifier, the medium of the identifier. Must be 'email'.  Deprecated in favour of `identifier`.
    2578              :   ///
    2579              :   /// [password] Required when `type` is `m.login.password`. The user's
    2580              :   /// password.
    2581              :   ///
    2582              :   /// [refreshToken] If true, the client supports refresh tokens.
    2583              :   ///
    2584              :   /// [token] Required when `type` is `m.login.token`. Part of Token-based login.
    2585              :   ///
    2586              :   /// [type] The login type being used.
    2587              :   ///
    2588              :   /// This must be a type returned in one of the flows of the
    2589              :   /// response of the [`GET /login`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3login)
    2590              :   /// endpoint, like `m.login.password` or `m.login.token`.
    2591              :   ///
    2592              :   /// [user] The fully qualified user ID or just local part of the user ID, to log in.  Deprecated in favour of `identifier`.
    2593            5 :   Future<LoginResponse> login(
    2594              :     String type, {
    2595              :     String? address,
    2596              :     String? deviceId,
    2597              :     AuthenticationIdentifier? identifier,
    2598              :     String? initialDeviceDisplayName,
    2599              :     String? medium,
    2600              :     String? password,
    2601              :     bool? refreshToken,
    2602              :     String? token,
    2603              :     String? user,
    2604              :   }) async {
    2605            5 :     final requestUri = Uri(path: '_matrix/client/v3/login');
    2606           15 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2607           10 :     request.headers['content-type'] = 'application/json';
    2608           10 :     request.bodyBytes = utf8.encode(
    2609           10 :       jsonEncode({
    2610            0 :         if (address != null) 'address': address,
    2611            1 :         if (deviceId != null) 'device_id': deviceId,
    2612           10 :         if (identifier != null) 'identifier': identifier.toJson(),
    2613              :         if (initialDeviceDisplayName != null)
    2614            0 :           'initial_device_display_name': initialDeviceDisplayName,
    2615            0 :         if (medium != null) 'medium': medium,
    2616            5 :         if (password != null) 'password': password,
    2617            5 :         if (refreshToken != null) 'refresh_token': refreshToken,
    2618            1 :         if (token != null) 'token': token,
    2619            5 :         'type': type,
    2620            0 :         if (user != null) 'user': user,
    2621              :       }),
    2622              :     );
    2623           10 :     final response = await httpClient.send(request);
    2624           10 :     final responseBody = await response.stream.toBytes();
    2625           10 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2626            5 :     final responseString = utf8.decode(responseBody);
    2627            5 :     final json = jsonDecode(responseString);
    2628            5 :     return LoginResponse.fromJson(json as Map<String, Object?>);
    2629              :   }
    2630              : 
    2631              :   /// Invalidates an existing access token, so that it can no longer be used for
    2632              :   /// authorization. The device associated with the access token is also deleted.
    2633              :   /// [Device keys](https://spec.matrix.org/unstable/client-server-api/#device-keys) for the device are deleted alongside the device.
    2634           10 :   Future<void> logout() async {
    2635           10 :     final requestUri = Uri(path: '_matrix/client/v3/logout');
    2636           30 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2637           40 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2638           20 :     final response = await httpClient.send(request);
    2639           20 :     final responseBody = await response.stream.toBytes();
    2640           21 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2641           10 :     final responseString = utf8.decode(responseBody);
    2642           10 :     final json = jsonDecode(responseString);
    2643           10 :     return ignore(json);
    2644              :   }
    2645              : 
    2646              :   /// Invalidates all access tokens for a user, so that they can no longer be used for
    2647              :   /// authorization. This includes the access token that made this request. All devices
    2648              :   /// for the user are also deleted. [Device keys](https://spec.matrix.org/unstable/client-server-api/#device-keys) for the device are
    2649              :   /// deleted alongside the device.
    2650              :   ///
    2651              :   /// This endpoint does not use the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api) because
    2652              :   /// User-Interactive Authentication is designed to protect against attacks where the
    2653              :   /// someone gets hold of a single access token then takes over the account. This
    2654              :   /// endpoint invalidates all access tokens for the user, including the token used in
    2655              :   /// the request, and therefore the attacker is unable to take over the account in
    2656              :   /// this way.
    2657            0 :   Future<void> logoutAll() async {
    2658            0 :     final requestUri = Uri(path: '_matrix/client/v3/logout/all');
    2659            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2660            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2661            0 :     final response = await httpClient.send(request);
    2662            0 :     final responseBody = await response.stream.toBytes();
    2663            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2664            0 :     final responseString = utf8.decode(responseBody);
    2665            0 :     final json = jsonDecode(responseString);
    2666            0 :     return ignore(json);
    2667              :   }
    2668              : 
    2669              :   /// This API is used to paginate through the list of events that the
    2670              :   /// user has been, or would have been notified about.
    2671              :   ///
    2672              :   /// [from] Pagination token to continue from. This should be the `next_token`
    2673              :   /// returned from an earlier call to this endpoint.
    2674              :   ///
    2675              :   /// [limit] Limit on the number of events to return in this request.
    2676              :   ///
    2677              :   /// [only] Allows basic filtering of events returned. Supply `highlight`
    2678              :   /// to return only events where the notification had the highlight
    2679              :   /// tweak set.
    2680            0 :   Future<GetNotificationsResponse> getNotifications({
    2681              :     String? from,
    2682              :     int? limit,
    2683              :     String? only,
    2684              :   }) async {
    2685            0 :     final requestUri = Uri(
    2686              :       path: '_matrix/client/v3/notifications',
    2687            0 :       queryParameters: {
    2688            0 :         if (from != null) 'from': from,
    2689            0 :         if (limit != null) 'limit': limit.toString(),
    2690            0 :         if (only != null) 'only': only,
    2691              :       },
    2692              :     );
    2693            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    2694            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2695            0 :     final response = await httpClient.send(request);
    2696            0 :     final responseBody = await response.stream.toBytes();
    2697            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2698            0 :     final responseString = utf8.decode(responseBody);
    2699            0 :     final json = jsonDecode(responseString);
    2700            0 :     return GetNotificationsResponse.fromJson(json as Map<String, Object?>);
    2701              :   }
    2702              : 
    2703              :   /// Get the given user's presence state.
    2704              :   ///
    2705              :   /// [userId] The user whose presence state to get.
    2706            0 :   Future<GetPresenceResponse> getPresence(String userId) async {
    2707            0 :     final requestUri = Uri(
    2708            0 :       path: '_matrix/client/v3/presence/${Uri.encodeComponent(userId)}/status',
    2709              :     );
    2710            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    2711            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2712            0 :     final response = await httpClient.send(request);
    2713            0 :     final responseBody = await response.stream.toBytes();
    2714            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2715            0 :     final responseString = utf8.decode(responseBody);
    2716            0 :     final json = jsonDecode(responseString);
    2717            0 :     return GetPresenceResponse.fromJson(json as Map<String, Object?>);
    2718              :   }
    2719              : 
    2720              :   /// This API sets the given user's presence state. When setting the status,
    2721              :   /// the activity time is updated to reflect that activity; the client does
    2722              :   /// not need to specify the `last_active_ago` field. You cannot set the
    2723              :   /// presence state of another user.
    2724              :   ///
    2725              :   /// [userId] The user whose presence state to update.
    2726              :   ///
    2727              :   /// [presence] The new presence state.
    2728              :   ///
    2729              :   /// [statusMsg] The status message to attach to this state.
    2730            0 :   Future<void> setPresence(
    2731              :     String userId,
    2732              :     PresenceType presence, {
    2733              :     String? statusMsg,
    2734              :   }) async {
    2735            0 :     final requestUri = Uri(
    2736            0 :       path: '_matrix/client/v3/presence/${Uri.encodeComponent(userId)}/status',
    2737              :     );
    2738            0 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    2739            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2740            0 :     request.headers['content-type'] = 'application/json';
    2741            0 :     request.bodyBytes = utf8.encode(
    2742            0 :       jsonEncode({
    2743            0 :         'presence': presence.name,
    2744            0 :         if (statusMsg != null) 'status_msg': statusMsg,
    2745              :       }),
    2746              :     );
    2747            0 :     final response = await httpClient.send(request);
    2748            0 :     final responseBody = await response.stream.toBytes();
    2749            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2750            0 :     final responseString = utf8.decode(responseBody);
    2751            0 :     final json = jsonDecode(responseString);
    2752            0 :     return ignore(json);
    2753              :   }
    2754              : 
    2755              :   /// Get the combined profile information for this user. This API may be used
    2756              :   /// to fetch the user's own profile information or other users; either
    2757              :   /// locally or on remote homeservers.
    2758              :   ///
    2759              :   /// [userId] The user whose profile information to get.
    2760            5 :   Future<ProfileInformation> getUserProfile(String userId) async {
    2761              :     final requestUri =
    2762           15 :         Uri(path: '_matrix/client/v3/profile/${Uri.encodeComponent(userId)}');
    2763           11 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    2764            3 :     if (bearerToken != null) {
    2765           12 :       request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2766              :     }
    2767            6 :     final response = await httpClient.send(request);
    2768            6 :     final responseBody = await response.stream.toBytes();
    2769            7 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2770            3 :     final responseString = utf8.decode(responseBody);
    2771            3 :     final json = jsonDecode(responseString);
    2772            3 :     return ProfileInformation.fromJson(json as Map<String, Object?>);
    2773              :   }
    2774              : 
    2775              :   /// Get the user's avatar URL. This API may be used to fetch the user's
    2776              :   /// own avatar URL or to query the URL of other users; either locally or
    2777              :   /// on remote homeservers.
    2778              :   ///
    2779              :   /// [userId] The user whose avatar URL to get.
    2780              :   ///
    2781              :   /// returns `avatar_url`:
    2782              :   /// The user's avatar URL if they have set one, otherwise not present.
    2783            0 :   Future<Uri?> getAvatarUrl(String userId) async {
    2784            0 :     final requestUri = Uri(
    2785              :       path:
    2786            0 :           '_matrix/client/v3/profile/${Uri.encodeComponent(userId)}/avatar_url',
    2787              :     );
    2788            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    2789            0 :     if (bearerToken != null) {
    2790            0 :       request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2791              :     }
    2792            0 :     final response = await httpClient.send(request);
    2793            0 :     final responseBody = await response.stream.toBytes();
    2794            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2795            0 :     final responseString = utf8.decode(responseBody);
    2796            0 :     final json = jsonDecode(responseString);
    2797            0 :     return ((v) =>
    2798            0 :         v != null ? Uri.parse(v as String) : null)(json['avatar_url']);
    2799              :   }
    2800              : 
    2801              :   /// This API sets the given user's avatar URL. You must have permission to
    2802              :   /// set this user's avatar URL, e.g. you need to have their `access_token`.
    2803              :   ///
    2804              :   /// [userId] The user whose avatar URL to set.
    2805              :   ///
    2806              :   /// [avatarUrl] The new avatar URL for this user.
    2807            1 :   Future<void> setAvatarUrl(String userId, Uri? avatarUrl) async {
    2808            1 :     final requestUri = Uri(
    2809              :       path:
    2810            2 :           '_matrix/client/v3/profile/${Uri.encodeComponent(userId)}/avatar_url',
    2811              :     );
    2812            3 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    2813            4 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2814            2 :     request.headers['content-type'] = 'application/json';
    2815            2 :     request.bodyBytes = utf8.encode(
    2816            2 :       jsonEncode({
    2817            2 :         if (avatarUrl != null) 'avatar_url': avatarUrl.toString(),
    2818              :       }),
    2819              :     );
    2820            2 :     final response = await httpClient.send(request);
    2821            2 :     final responseBody = await response.stream.toBytes();
    2822            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2823            1 :     final responseString = utf8.decode(responseBody);
    2824            1 :     final json = jsonDecode(responseString);
    2825            1 :     return ignore(json);
    2826              :   }
    2827              : 
    2828              :   /// Get the user's display name. This API may be used to fetch the user's
    2829              :   /// own displayname or to query the name of other users; either locally or
    2830              :   /// on remote homeservers.
    2831              :   ///
    2832              :   /// [userId] The user whose display name to get.
    2833              :   ///
    2834              :   /// returns `displayname`:
    2835              :   /// The user's display name if they have set one, otherwise not present.
    2836            0 :   Future<String?> getDisplayName(String userId) async {
    2837            0 :     final requestUri = Uri(
    2838              :       path:
    2839            0 :           '_matrix/client/v3/profile/${Uri.encodeComponent(userId)}/displayname',
    2840              :     );
    2841            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    2842            0 :     if (bearerToken != null) {
    2843            0 :       request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2844              :     }
    2845            0 :     final response = await httpClient.send(request);
    2846            0 :     final responseBody = await response.stream.toBytes();
    2847            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2848            0 :     final responseString = utf8.decode(responseBody);
    2849            0 :     final json = jsonDecode(responseString);
    2850            0 :     return ((v) => v != null ? v as String : null)(json['displayname']);
    2851              :   }
    2852              : 
    2853              :   /// This API sets the given user's display name. You must have permission to
    2854              :   /// set this user's display name, e.g. you need to have their `access_token`.
    2855              :   ///
    2856              :   /// [userId] The user whose display name to set.
    2857              :   ///
    2858              :   /// [displayname] The new display name for this user.
    2859            0 :   Future<void> setDisplayName(String userId, String? displayname) async {
    2860            0 :     final requestUri = Uri(
    2861              :       path:
    2862            0 :           '_matrix/client/v3/profile/${Uri.encodeComponent(userId)}/displayname',
    2863              :     );
    2864            0 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    2865            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2866            0 :     request.headers['content-type'] = 'application/json';
    2867            0 :     request.bodyBytes = utf8.encode(
    2868            0 :       jsonEncode({
    2869            0 :         if (displayname != null) 'displayname': displayname,
    2870              :       }),
    2871              :     );
    2872            0 :     final response = await httpClient.send(request);
    2873            0 :     final responseBody = await response.stream.toBytes();
    2874            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2875            0 :     final responseString = utf8.decode(responseBody);
    2876            0 :     final json = jsonDecode(responseString);
    2877            0 :     return ignore(json);
    2878              :   }
    2879              : 
    2880              :   /// Lists the public rooms on the server.
    2881              :   ///
    2882              :   /// This API returns paginated responses. The rooms are ordered by the number
    2883              :   /// of joined members, with the largest rooms first.
    2884              :   ///
    2885              :   /// [limit] Limit the number of results returned.
    2886              :   ///
    2887              :   /// [since] A pagination token from a previous request, allowing clients to
    2888              :   /// get the next (or previous) batch of rooms.
    2889              :   /// The direction of pagination is specified solely by which token
    2890              :   /// is supplied, rather than via an explicit flag.
    2891              :   ///
    2892              :   /// [server] The server to fetch the public room lists from. Defaults to the
    2893              :   /// local server. Case sensitive.
    2894            0 :   Future<GetPublicRoomsResponse> getPublicRooms({
    2895              :     int? limit,
    2896              :     String? since,
    2897              :     String? server,
    2898              :   }) async {
    2899            0 :     final requestUri = Uri(
    2900              :       path: '_matrix/client/v3/publicRooms',
    2901            0 :       queryParameters: {
    2902            0 :         if (limit != null) 'limit': limit.toString(),
    2903            0 :         if (since != null) 'since': since,
    2904            0 :         if (server != null) 'server': server,
    2905              :       },
    2906              :     );
    2907            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    2908            0 :     final response = await httpClient.send(request);
    2909            0 :     final responseBody = await response.stream.toBytes();
    2910            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2911            0 :     final responseString = utf8.decode(responseBody);
    2912            0 :     final json = jsonDecode(responseString);
    2913            0 :     return GetPublicRoomsResponse.fromJson(json as Map<String, Object?>);
    2914              :   }
    2915              : 
    2916              :   /// Lists the public rooms on the server, with optional filter.
    2917              :   ///
    2918              :   /// This API returns paginated responses. The rooms are ordered by the number
    2919              :   /// of joined members, with the largest rooms first.
    2920              :   ///
    2921              :   /// [server] The server to fetch the public room lists from. Defaults to the
    2922              :   /// local server. Case sensitive.
    2923              :   ///
    2924              :   /// [filter] Filter to apply to the results.
    2925              :   ///
    2926              :   /// [includeAllNetworks] Whether or not to include all known networks/protocols from
    2927              :   /// application services on the homeserver. Defaults to false.
    2928              :   ///
    2929              :   /// [limit] Limit the number of results returned.
    2930              :   ///
    2931              :   /// [since] A pagination token from a previous request, allowing clients
    2932              :   /// to get the next (or previous) batch of rooms.  The direction
    2933              :   /// of pagination is specified solely by which token is supplied,
    2934              :   /// rather than via an explicit flag.
    2935              :   ///
    2936              :   /// [thirdPartyInstanceId] The specific third-party network/protocol to request from the
    2937              :   /// homeserver. Can only be used if `include_all_networks` is false.
    2938            0 :   Future<QueryPublicRoomsResponse> queryPublicRooms({
    2939              :     String? server,
    2940              :     PublicRoomQueryFilter? filter,
    2941              :     bool? includeAllNetworks,
    2942              :     int? limit,
    2943              :     String? since,
    2944              :     String? thirdPartyInstanceId,
    2945              :   }) async {
    2946            0 :     final requestUri = Uri(
    2947              :       path: '_matrix/client/v3/publicRooms',
    2948            0 :       queryParameters: {
    2949            0 :         if (server != null) 'server': server,
    2950              :       },
    2951              :     );
    2952            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    2953            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2954            0 :     request.headers['content-type'] = 'application/json';
    2955            0 :     request.bodyBytes = utf8.encode(
    2956            0 :       jsonEncode({
    2957            0 :         if (filter != null) 'filter': filter.toJson(),
    2958              :         if (includeAllNetworks != null)
    2959            0 :           'include_all_networks': includeAllNetworks,
    2960            0 :         if (limit != null) 'limit': limit,
    2961            0 :         if (since != null) 'since': since,
    2962              :         if (thirdPartyInstanceId != null)
    2963            0 :           'third_party_instance_id': thirdPartyInstanceId,
    2964              :       }),
    2965              :     );
    2966            0 :     final response = await httpClient.send(request);
    2967            0 :     final responseBody = await response.stream.toBytes();
    2968            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2969            0 :     final responseString = utf8.decode(responseBody);
    2970            0 :     final json = jsonDecode(responseString);
    2971            0 :     return QueryPublicRoomsResponse.fromJson(json as Map<String, Object?>);
    2972              :   }
    2973              : 
    2974              :   /// Gets all currently active pushers for the authenticated user.
    2975              :   ///
    2976              :   /// returns `pushers`:
    2977              :   /// An array containing the current pushers for the user
    2978            0 :   Future<List<Pusher>?> getPushers() async {
    2979            0 :     final requestUri = Uri(path: '_matrix/client/v3/pushers');
    2980            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    2981            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    2982            0 :     final response = await httpClient.send(request);
    2983            0 :     final responseBody = await response.stream.toBytes();
    2984            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    2985            0 :     final responseString = utf8.decode(responseBody);
    2986            0 :     final json = jsonDecode(responseString);
    2987            0 :     return ((v) => v != null
    2988              :         ? (v as List)
    2989            0 :             .map((v) => Pusher.fromJson(v as Map<String, Object?>))
    2990            0 :             .toList()
    2991            0 :         : null)(json['pushers']);
    2992              :   }
    2993              : 
    2994              :   /// Retrieve all push rulesets for this user. Currently the only push ruleset
    2995              :   /// defined is `global`.
    2996              :   ///
    2997              :   /// returns `global`:
    2998              :   /// The global ruleset.
    2999            0 :   Future<PushRuleSet> getPushRules() async {
    3000            0 :     final requestUri = Uri(path: '_matrix/client/v3/pushrules/');
    3001            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3002            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3003            0 :     final response = await httpClient.send(request);
    3004            0 :     final responseBody = await response.stream.toBytes();
    3005            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3006            0 :     final responseString = utf8.decode(responseBody);
    3007            0 :     final json = jsonDecode(responseString);
    3008            0 :     return PushRuleSet.fromJson(json['global'] as Map<String, Object?>);
    3009              :   }
    3010              : 
    3011              :   /// Retrieve all push rules for this user.
    3012            0 :   Future<GetPushRulesGlobalResponse> getPushRulesGlobal() async {
    3013            0 :     final requestUri = Uri(path: '_matrix/client/v3/pushrules/global/');
    3014            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3015            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3016            0 :     final response = await httpClient.send(request);
    3017            0 :     final responseBody = await response.stream.toBytes();
    3018            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3019            0 :     final responseString = utf8.decode(responseBody);
    3020            0 :     final json = jsonDecode(responseString);
    3021            0 :     return GetPushRulesGlobalResponse.fromJson(json as Map<String, Object?>);
    3022              :   }
    3023              : 
    3024              :   /// This endpoint removes the push rule defined in the path.
    3025              :   ///
    3026              :   /// [kind] The kind of rule
    3027              :   ///
    3028              :   ///
    3029              :   /// [ruleId] The identifier for the rule.
    3030              :   ///
    3031            2 :   Future<void> deletePushRule(PushRuleKind kind, String ruleId) async {
    3032            2 :     final requestUri = Uri(
    3033              :       path:
    3034            8 :           '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}',
    3035              :     );
    3036            6 :     final request = Request('DELETE', baseUri!.resolveUri(requestUri));
    3037            8 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3038            4 :     final response = await httpClient.send(request);
    3039            4 :     final responseBody = await response.stream.toBytes();
    3040            4 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3041            2 :     final responseString = utf8.decode(responseBody);
    3042            2 :     final json = jsonDecode(responseString);
    3043            2 :     return ignore(json);
    3044              :   }
    3045              : 
    3046              :   /// Retrieve a single specified push rule.
    3047              :   ///
    3048              :   /// [kind] The kind of rule
    3049              :   ///
    3050              :   ///
    3051              :   /// [ruleId] The identifier for the rule.
    3052              :   ///
    3053            0 :   Future<PushRule> getPushRule(PushRuleKind kind, String ruleId) async {
    3054            0 :     final requestUri = Uri(
    3055              :       path:
    3056            0 :           '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}',
    3057              :     );
    3058            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3059            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3060            0 :     final response = await httpClient.send(request);
    3061            0 :     final responseBody = await response.stream.toBytes();
    3062            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3063            0 :     final responseString = utf8.decode(responseBody);
    3064            0 :     final json = jsonDecode(responseString);
    3065            0 :     return PushRule.fromJson(json as Map<String, Object?>);
    3066              :   }
    3067              : 
    3068              :   /// This endpoint allows the creation and modification of user defined push
    3069              :   /// rules.
    3070              :   ///
    3071              :   /// If a rule with the same `rule_id` already exists among rules of the same
    3072              :   /// kind, it is updated with the new parameters, otherwise a new rule is
    3073              :   /// created.
    3074              :   ///
    3075              :   /// If both `after` and `before` are provided, the new or updated rule must
    3076              :   /// be the next most important rule with respect to the rule identified by
    3077              :   /// `before`.
    3078              :   ///
    3079              :   /// If neither `after` nor `before` are provided and the rule is created, it
    3080              :   /// should be added as the most important user defined rule among rules of
    3081              :   /// the same kind.
    3082              :   ///
    3083              :   /// When creating push rules, they MUST be enabled by default.
    3084              :   ///
    3085              :   /// [kind] The kind of rule
    3086              :   ///
    3087              :   ///
    3088              :   /// [ruleId] The identifier for the rule. If the string starts with a dot ("."),
    3089              :   /// the request MUST be rejected as this is reserved for server-default
    3090              :   /// rules. Slashes ("/") and backslashes ("\\") are also not allowed.
    3091              :   ///
    3092              :   ///
    3093              :   /// [before] Use 'before' with a `rule_id` as its value to make the new rule the
    3094              :   /// next-most important rule with respect to the given user defined rule.
    3095              :   /// It is not possible to add a rule relative to a predefined server rule.
    3096              :   ///
    3097              :   /// [after] This makes the new rule the next-less important rule relative to the
    3098              :   /// given user defined rule. It is not possible to add a rule relative
    3099              :   /// to a predefined server rule.
    3100              :   ///
    3101              :   /// [actions] The action(s) to perform when the conditions for this rule are met.
    3102              :   ///
    3103              :   /// [conditions] The conditions that must hold true for an event in order for a
    3104              :   /// rule to be applied to an event. A rule with no conditions
    3105              :   /// always matches. Only applicable to `underride` and `override` rules.
    3106              :   ///
    3107              :   /// [pattern] Only applicable to `content` rules. The glob-style pattern to match against.
    3108            2 :   Future<void> setPushRule(
    3109              :     PushRuleKind kind,
    3110              :     String ruleId,
    3111              :     List<Object?> actions, {
    3112              :     String? before,
    3113              :     String? after,
    3114              :     List<PushCondition>? conditions,
    3115              :     String? pattern,
    3116              :   }) async {
    3117            2 :     final requestUri = Uri(
    3118              :       path:
    3119            8 :           '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}',
    3120            2 :       queryParameters: {
    3121            0 :         if (before != null) 'before': before,
    3122            0 :         if (after != null) 'after': after,
    3123              :       },
    3124              :     );
    3125            6 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    3126            8 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3127            4 :     request.headers['content-type'] = 'application/json';
    3128            4 :     request.bodyBytes = utf8.encode(
    3129            4 :       jsonEncode({
    3130            6 :         'actions': actions.map((v) => v).toList(),
    3131              :         if (conditions != null)
    3132            0 :           'conditions': conditions.map((v) => v.toJson()).toList(),
    3133            0 :         if (pattern != null) 'pattern': pattern,
    3134              :       }),
    3135              :     );
    3136            4 :     final response = await httpClient.send(request);
    3137            4 :     final responseBody = await response.stream.toBytes();
    3138            4 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3139            2 :     final responseString = utf8.decode(responseBody);
    3140            2 :     final json = jsonDecode(responseString);
    3141            2 :     return ignore(json);
    3142              :   }
    3143              : 
    3144              :   /// This endpoint get the actions for the specified push rule.
    3145              :   ///
    3146              :   /// [kind] The kind of rule
    3147              :   ///
    3148              :   ///
    3149              :   /// [ruleId] The identifier for the rule.
    3150              :   ///
    3151              :   ///
    3152              :   /// returns `actions`:
    3153              :   /// The action(s) to perform for this rule.
    3154            0 :   Future<List<Object?>> getPushRuleActions(
    3155              :     PushRuleKind kind,
    3156              :     String ruleId,
    3157              :   ) async {
    3158            0 :     final requestUri = Uri(
    3159              :       path:
    3160            0 :           '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}/actions',
    3161              :     );
    3162            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3163            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3164            0 :     final response = await httpClient.send(request);
    3165            0 :     final responseBody = await response.stream.toBytes();
    3166            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3167            0 :     final responseString = utf8.decode(responseBody);
    3168            0 :     final json = jsonDecode(responseString);
    3169            0 :     return (json['actions'] as List).map((v) => v as Object?).toList();
    3170              :   }
    3171              : 
    3172              :   /// This endpoint allows clients to change the actions of a push rule.
    3173              :   /// This can be used to change the actions of builtin rules.
    3174              :   ///
    3175              :   /// [kind] The kind of rule
    3176              :   ///
    3177              :   ///
    3178              :   /// [ruleId] The identifier for the rule.
    3179              :   ///
    3180              :   ///
    3181              :   /// [actions] The action(s) to perform for this rule.
    3182            0 :   Future<void> setPushRuleActions(
    3183              :     PushRuleKind kind,
    3184              :     String ruleId,
    3185              :     List<Object?> actions,
    3186              :   ) async {
    3187            0 :     final requestUri = Uri(
    3188              :       path:
    3189            0 :           '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}/actions',
    3190              :     );
    3191            0 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    3192            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3193            0 :     request.headers['content-type'] = 'application/json';
    3194            0 :     request.bodyBytes = utf8.encode(
    3195            0 :       jsonEncode({
    3196            0 :         'actions': actions.map((v) => v).toList(),
    3197              :       }),
    3198              :     );
    3199            0 :     final response = await httpClient.send(request);
    3200            0 :     final responseBody = await response.stream.toBytes();
    3201            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3202            0 :     final responseString = utf8.decode(responseBody);
    3203            0 :     final json = jsonDecode(responseString);
    3204            0 :     return ignore(json);
    3205              :   }
    3206              : 
    3207              :   /// This endpoint gets whether the specified push rule is enabled.
    3208              :   ///
    3209              :   /// [kind] The kind of rule
    3210              :   ///
    3211              :   ///
    3212              :   /// [ruleId] The identifier for the rule.
    3213              :   ///
    3214              :   ///
    3215              :   /// returns `enabled`:
    3216              :   /// Whether the push rule is enabled or not.
    3217            0 :   Future<bool> isPushRuleEnabled(PushRuleKind kind, String ruleId) async {
    3218            0 :     final requestUri = Uri(
    3219              :       path:
    3220            0 :           '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}/enabled',
    3221              :     );
    3222            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3223            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3224            0 :     final response = await httpClient.send(request);
    3225            0 :     final responseBody = await response.stream.toBytes();
    3226            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3227            0 :     final responseString = utf8.decode(responseBody);
    3228            0 :     final json = jsonDecode(responseString);
    3229            0 :     return json['enabled'] as bool;
    3230              :   }
    3231              : 
    3232              :   /// This endpoint allows clients to enable or disable the specified push rule.
    3233              :   ///
    3234              :   /// [kind] The kind of rule
    3235              :   ///
    3236              :   ///
    3237              :   /// [ruleId] The identifier for the rule.
    3238              :   ///
    3239              :   ///
    3240              :   /// [enabled] Whether the push rule is enabled or not.
    3241            1 :   Future<void> setPushRuleEnabled(
    3242              :     PushRuleKind kind,
    3243              :     String ruleId,
    3244              :     bool enabled,
    3245              :   ) async {
    3246            1 :     final requestUri = Uri(
    3247              :       path:
    3248            4 :           '_matrix/client/v3/pushrules/global/${Uri.encodeComponent(kind.name)}/${Uri.encodeComponent(ruleId)}/enabled',
    3249              :     );
    3250            3 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    3251            4 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3252            2 :     request.headers['content-type'] = 'application/json';
    3253            2 :     request.bodyBytes = utf8.encode(
    3254            2 :       jsonEncode({
    3255              :         'enabled': enabled,
    3256              :       }),
    3257              :     );
    3258            2 :     final response = await httpClient.send(request);
    3259            2 :     final responseBody = await response.stream.toBytes();
    3260            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3261            1 :     final responseString = utf8.decode(responseBody);
    3262            1 :     final json = jsonDecode(responseString);
    3263            1 :     return ignore(json);
    3264              :   }
    3265              : 
    3266              :   /// Refresh an access token. Clients should use the returned access token
    3267              :   /// when making subsequent API calls, and store the returned refresh token
    3268              :   /// (if given) in order to refresh the new access token when necessary.
    3269              :   ///
    3270              :   /// After an access token has been refreshed, a server can choose to
    3271              :   /// invalidate the old access token immediately, or can choose not to, for
    3272              :   /// example if the access token would expire soon anyways. Clients should
    3273              :   /// not make any assumptions about the old access token still being valid,
    3274              :   /// and should use the newly provided access token instead.
    3275              :   ///
    3276              :   /// The old refresh token remains valid until the new access token or refresh token
    3277              :   /// is used, at which point the old refresh token is revoked.
    3278              :   ///
    3279              :   /// Note that this endpoint does not require authentication via an
    3280              :   /// access token. Authentication is provided via the refresh token.
    3281              :   ///
    3282              :   /// Application Service identity assertion is disabled for this endpoint.
    3283              :   ///
    3284              :   /// [refreshToken] The refresh token
    3285            0 :   Future<RefreshResponse> refresh(String refreshToken) async {
    3286            0 :     final requestUri = Uri(path: '_matrix/client/v3/refresh');
    3287            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    3288            0 :     request.headers['content-type'] = 'application/json';
    3289            0 :     request.bodyBytes = utf8.encode(
    3290            0 :       jsonEncode({
    3291              :         'refresh_token': refreshToken,
    3292              :       }),
    3293              :     );
    3294            0 :     final response = await httpClient.send(request);
    3295            0 :     final responseBody = await response.stream.toBytes();
    3296            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3297            0 :     final responseString = utf8.decode(responseBody);
    3298            0 :     final json = jsonDecode(responseString);
    3299            0 :     return RefreshResponse.fromJson(json as Map<String, Object?>);
    3300              :   }
    3301              : 
    3302              :   /// This API endpoint uses the [User-Interactive Authentication API](https://spec.matrix.org/unstable/client-server-api/#user-interactive-authentication-api), except in
    3303              :   /// the cases where a guest account is being registered.
    3304              :   ///
    3305              :   /// Register for an account on this homeserver.
    3306              :   ///
    3307              :   /// There are two kinds of user account:
    3308              :   ///
    3309              :   /// - `user` accounts. These accounts may use the full API described in this specification.
    3310              :   ///
    3311              :   /// - `guest` accounts. These accounts may have limited permissions and may not be supported by all servers.
    3312              :   ///
    3313              :   /// If registration is successful, this endpoint will issue an access token
    3314              :   /// the client can use to authorize itself in subsequent requests.
    3315              :   ///
    3316              :   /// If the client does not supply a `device_id`, the server must
    3317              :   /// auto-generate one.
    3318              :   ///
    3319              :   /// The server SHOULD register an account with a User ID based on the
    3320              :   /// `username` provided, if any. Note that the grammar of Matrix User ID
    3321              :   /// localparts is restricted, so the server MUST either map the provided
    3322              :   /// `username` onto a `user_id` in a logical manner, or reject any
    3323              :   /// `username` which does not comply to the grammar with
    3324              :   /// `M_INVALID_USERNAME`.
    3325              :   ///
    3326              :   /// Matrix clients MUST NOT assume that localpart of the registered
    3327              :   /// `user_id` matches the provided `username`.
    3328              :   ///
    3329              :   /// The returned access token must be associated with the `device_id`
    3330              :   /// supplied by the client or generated by the server. The server may
    3331              :   /// invalidate any access token previously associated with that device. See
    3332              :   /// [Relationship between access tokens and devices](https://spec.matrix.org/unstable/client-server-api/#relationship-between-access-tokens-and-devices).
    3333              :   ///
    3334              :   /// When registering a guest account, all parameters in the request body
    3335              :   /// with the exception of `initial_device_display_name` MUST BE ignored
    3336              :   /// by the server. The server MUST pick a `device_id` for the account
    3337              :   /// regardless of input.
    3338              :   ///
    3339              :   /// Any user ID returned by this API must conform to the grammar given in the
    3340              :   /// [Matrix specification](https://spec.matrix.org/unstable/appendices/#user-identifiers).
    3341              :   ///
    3342              :   /// [kind] The kind of account to register. Defaults to `user`.
    3343              :   ///
    3344              :   /// [auth] Additional authentication information for the
    3345              :   /// user-interactive authentication API. Note that this
    3346              :   /// information is *not* used to define how the registered user
    3347              :   /// should be authenticated, but is instead used to
    3348              :   /// authenticate the `register` call itself.
    3349              :   ///
    3350              :   /// [deviceId] ID of the client device. If this does not correspond to a
    3351              :   /// known client device, a new device will be created. The server
    3352              :   /// will auto-generate a device_id if this is not specified.
    3353              :   ///
    3354              :   /// [inhibitLogin] If true, an `access_token` and `device_id` should not be
    3355              :   /// returned from this call, therefore preventing an automatic
    3356              :   /// login. Defaults to false.
    3357              :   ///
    3358              :   /// [initialDeviceDisplayName] A display name to assign to the newly-created device. Ignored
    3359              :   /// if `device_id` corresponds to a known device.
    3360              :   ///
    3361              :   /// [password] The desired password for the account.
    3362              :   ///
    3363              :   /// [refreshToken] If true, the client supports refresh tokens.
    3364              :   ///
    3365              :   /// [username] The basis for the localpart of the desired Matrix ID. If omitted,
    3366              :   /// the homeserver MUST generate a Matrix ID local part.
    3367            0 :   Future<RegisterResponse> register({
    3368              :     AccountKind? kind,
    3369              :     AuthenticationData? auth,
    3370              :     String? deviceId,
    3371              :     bool? inhibitLogin,
    3372              :     String? initialDeviceDisplayName,
    3373              :     String? password,
    3374              :     bool? refreshToken,
    3375              :     String? username,
    3376              :   }) async {
    3377            0 :     final requestUri = Uri(
    3378              :       path: '_matrix/client/v3/register',
    3379            0 :       queryParameters: {
    3380            0 :         if (kind != null) 'kind': kind.name,
    3381              :       },
    3382              :     );
    3383            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    3384            0 :     request.headers['content-type'] = 'application/json';
    3385            0 :     request.bodyBytes = utf8.encode(
    3386            0 :       jsonEncode({
    3387            0 :         if (auth != null) 'auth': auth.toJson(),
    3388            0 :         if (deviceId != null) 'device_id': deviceId,
    3389            0 :         if (inhibitLogin != null) 'inhibit_login': inhibitLogin,
    3390              :         if (initialDeviceDisplayName != null)
    3391            0 :           'initial_device_display_name': initialDeviceDisplayName,
    3392            0 :         if (password != null) 'password': password,
    3393            0 :         if (refreshToken != null) 'refresh_token': refreshToken,
    3394            0 :         if (username != null) 'username': username,
    3395              :       }),
    3396              :     );
    3397            0 :     final response = await httpClient.send(request);
    3398            0 :     final responseBody = await response.stream.toBytes();
    3399            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3400            0 :     final responseString = utf8.decode(responseBody);
    3401            0 :     final json = jsonDecode(responseString);
    3402            0 :     return RegisterResponse.fromJson(json as Map<String, Object?>);
    3403              :   }
    3404              : 
    3405              :   /// Checks to see if a username is available, and valid, for the server.
    3406              :   ///
    3407              :   /// The server should check to ensure that, at the time of the request, the
    3408              :   /// username requested is available for use. This includes verifying that an
    3409              :   /// application service has not claimed the username and that the username
    3410              :   /// fits the server's desired requirements (for example, a server could dictate
    3411              :   /// that it does not permit usernames with underscores).
    3412              :   ///
    3413              :   /// Matrix clients may wish to use this API prior to attempting registration,
    3414              :   /// however the clients must also be aware that using this API does not normally
    3415              :   /// reserve the username. This can mean that the username becomes unavailable
    3416              :   /// between checking its availability and attempting to register it.
    3417              :   ///
    3418              :   /// [username] The username to check the availability of.
    3419              :   ///
    3420              :   /// returns `available`:
    3421              :   /// A flag to indicate that the username is available. This should always
    3422              :   /// be `true` when the server replies with 200 OK.
    3423            1 :   Future<bool?> checkUsernameAvailability(String username) async {
    3424            1 :     final requestUri = Uri(
    3425              :       path: '_matrix/client/v3/register/available',
    3426            1 :       queryParameters: {
    3427              :         'username': username,
    3428              :       },
    3429              :     );
    3430            3 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3431            2 :     final response = await httpClient.send(request);
    3432            2 :     final responseBody = await response.stream.toBytes();
    3433            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3434            1 :     final responseString = utf8.decode(responseBody);
    3435            1 :     final json = jsonDecode(responseString);
    3436            3 :     return ((v) => v != null ? v as bool : null)(json['available']);
    3437              :   }
    3438              : 
    3439              :   /// The homeserver must check that the given email address is **not**
    3440              :   /// already associated with an account on this homeserver. The homeserver
    3441              :   /// should validate the email itself, either by sending a validation email
    3442              :   /// itself or by using a service it has control over.
    3443              :   ///
    3444              :   /// [clientSecret] A unique string generated by the client, and used to identify the
    3445              :   /// validation attempt. It must be a string consisting of the characters
    3446              :   /// `[0-9a-zA-Z.=_-]`. Its length must not exceed 255 characters and it
    3447              :   /// must not be empty.
    3448              :   ///
    3449              :   ///
    3450              :   /// [email] The email address to validate.
    3451              :   ///
    3452              :   /// [nextLink] Optional. When the validation is completed, the identity server will
    3453              :   /// redirect the user to this URL. This option is ignored when submitting
    3454              :   /// 3PID validation information through a POST request.
    3455              :   ///
    3456              :   /// [sendAttempt] The server will only send an email if the `send_attempt`
    3457              :   /// is a number greater than the most recent one which it has seen,
    3458              :   /// scoped to that `email` + `client_secret` pair. This is to
    3459              :   /// avoid repeatedly sending the same email in the case of request
    3460              :   /// retries between the POSTing user and the identity server.
    3461              :   /// The client should increment this value if they desire a new
    3462              :   /// email (e.g. a reminder) to be sent. If they do not, the server
    3463              :   /// should respond with success but not resend the email.
    3464              :   ///
    3465              :   /// [idAccessToken] An access token previously registered with the identity server. Servers
    3466              :   /// can treat this as optional to distinguish between r0.5-compatible clients
    3467              :   /// and this specification version.
    3468              :   ///
    3469              :   /// Required if an `id_server` is supplied.
    3470              :   ///
    3471              :   /// [idServer] The hostname of the identity server to communicate with. May optionally
    3472              :   /// include a port. This parameter is ignored when the homeserver handles
    3473              :   /// 3PID verification.
    3474              :   ///
    3475              :   /// This parameter is deprecated with a plan to be removed in a future specification
    3476              :   /// version for `/account/password` and `/register` requests.
    3477            0 :   Future<RequestTokenResponse> requestTokenToRegisterEmail(
    3478              :     String clientSecret,
    3479              :     String email,
    3480              :     int sendAttempt, {
    3481              :     String? nextLink,
    3482              :     String? idAccessToken,
    3483              :     String? idServer,
    3484              :   }) async {
    3485              :     final requestUri =
    3486            0 :         Uri(path: '_matrix/client/v3/register/email/requestToken');
    3487            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    3488            0 :     request.headers['content-type'] = 'application/json';
    3489            0 :     request.bodyBytes = utf8.encode(
    3490            0 :       jsonEncode({
    3491            0 :         'client_secret': clientSecret,
    3492            0 :         'email': email,
    3493            0 :         if (nextLink != null) 'next_link': nextLink,
    3494            0 :         'send_attempt': sendAttempt,
    3495            0 :         if (idAccessToken != null) 'id_access_token': idAccessToken,
    3496            0 :         if (idServer != null) 'id_server': idServer,
    3497              :       }),
    3498              :     );
    3499            0 :     final response = await httpClient.send(request);
    3500            0 :     final responseBody = await response.stream.toBytes();
    3501            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3502            0 :     final responseString = utf8.decode(responseBody);
    3503            0 :     final json = jsonDecode(responseString);
    3504            0 :     return RequestTokenResponse.fromJson(json as Map<String, Object?>);
    3505              :   }
    3506              : 
    3507              :   /// The homeserver must check that the given phone number is **not**
    3508              :   /// already associated with an account on this homeserver. The homeserver
    3509              :   /// should validate the phone number itself, either by sending a validation
    3510              :   /// message itself or by using a service it has control over.
    3511              :   ///
    3512              :   /// [clientSecret] A unique string generated by the client, and used to identify the
    3513              :   /// validation attempt. It must be a string consisting of the characters
    3514              :   /// `[0-9a-zA-Z.=_-]`. Its length must not exceed 255 characters and it
    3515              :   /// must not be empty.
    3516              :   ///
    3517              :   ///
    3518              :   /// [country] The two-letter uppercase ISO-3166-1 alpha-2 country code that the
    3519              :   /// number in `phone_number` should be parsed as if it were dialled from.
    3520              :   ///
    3521              :   /// [nextLink] Optional. When the validation is completed, the identity server will
    3522              :   /// redirect the user to this URL. This option is ignored when submitting
    3523              :   /// 3PID validation information through a POST request.
    3524              :   ///
    3525              :   /// [phoneNumber] The phone number to validate.
    3526              :   ///
    3527              :   /// [sendAttempt] The server will only send an SMS if the `send_attempt` is a
    3528              :   /// number greater than the most recent one which it has seen,
    3529              :   /// scoped to that `country` + `phone_number` + `client_secret`
    3530              :   /// triple. This is to avoid repeatedly sending the same SMS in
    3531              :   /// the case of request retries between the POSTing user and the
    3532              :   /// identity server. The client should increment this value if
    3533              :   /// they desire a new SMS (e.g. a reminder) to be sent.
    3534              :   ///
    3535              :   /// [idAccessToken] An access token previously registered with the identity server. Servers
    3536              :   /// can treat this as optional to distinguish between r0.5-compatible clients
    3537              :   /// and this specification version.
    3538              :   ///
    3539              :   /// Required if an `id_server` is supplied.
    3540              :   ///
    3541              :   /// [idServer] The hostname of the identity server to communicate with. May optionally
    3542              :   /// include a port. This parameter is ignored when the homeserver handles
    3543              :   /// 3PID verification.
    3544              :   ///
    3545              :   /// This parameter is deprecated with a plan to be removed in a future specification
    3546              :   /// version for `/account/password` and `/register` requests.
    3547            0 :   Future<RequestTokenResponse> requestTokenToRegisterMSISDN(
    3548              :     String clientSecret,
    3549              :     String country,
    3550              :     String phoneNumber,
    3551              :     int sendAttempt, {
    3552              :     String? nextLink,
    3553              :     String? idAccessToken,
    3554              :     String? idServer,
    3555              :   }) async {
    3556              :     final requestUri =
    3557            0 :         Uri(path: '_matrix/client/v3/register/msisdn/requestToken');
    3558            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    3559            0 :     request.headers['content-type'] = 'application/json';
    3560            0 :     request.bodyBytes = utf8.encode(
    3561            0 :       jsonEncode({
    3562            0 :         'client_secret': clientSecret,
    3563            0 :         'country': country,
    3564            0 :         if (nextLink != null) 'next_link': nextLink,
    3565            0 :         'phone_number': phoneNumber,
    3566            0 :         'send_attempt': sendAttempt,
    3567            0 :         if (idAccessToken != null) 'id_access_token': idAccessToken,
    3568            0 :         if (idServer != null) 'id_server': idServer,
    3569              :       }),
    3570              :     );
    3571            0 :     final response = await httpClient.send(request);
    3572            0 :     final responseBody = await response.stream.toBytes();
    3573            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3574            0 :     final responseString = utf8.decode(responseBody);
    3575            0 :     final json = jsonDecode(responseString);
    3576            0 :     return RequestTokenResponse.fromJson(json as Map<String, Object?>);
    3577              :   }
    3578              : 
    3579              :   /// Delete the keys from the backup.
    3580              :   ///
    3581              :   /// [version] The backup from which to delete the key
    3582            0 :   Future<RoomKeysUpdateResponse> deleteRoomKeys(String version) async {
    3583            0 :     final requestUri = Uri(
    3584              :       path: '_matrix/client/v3/room_keys/keys',
    3585            0 :       queryParameters: {
    3586              :         'version': version,
    3587              :       },
    3588              :     );
    3589            0 :     final request = Request('DELETE', baseUri!.resolveUri(requestUri));
    3590            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3591            0 :     final response = await httpClient.send(request);
    3592            0 :     final responseBody = await response.stream.toBytes();
    3593            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3594            0 :     final responseString = utf8.decode(responseBody);
    3595            0 :     final json = jsonDecode(responseString);
    3596            0 :     return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
    3597              :   }
    3598              : 
    3599              :   /// Retrieve the keys from the backup.
    3600              :   ///
    3601              :   /// [version] The backup from which to retrieve the keys.
    3602            1 :   Future<RoomKeys> getRoomKeys(String version) async {
    3603            1 :     final requestUri = Uri(
    3604              :       path: '_matrix/client/v3/room_keys/keys',
    3605            1 :       queryParameters: {
    3606              :         'version': version,
    3607              :       },
    3608              :     );
    3609            3 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3610            4 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3611            2 :     final response = await httpClient.send(request);
    3612            2 :     final responseBody = await response.stream.toBytes();
    3613            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3614            1 :     final responseString = utf8.decode(responseBody);
    3615            1 :     final json = jsonDecode(responseString);
    3616            1 :     return RoomKeys.fromJson(json as Map<String, Object?>);
    3617              :   }
    3618              : 
    3619              :   /// Store several keys in the backup.
    3620              :   ///
    3621              :   /// [version] The backup in which to store the keys. Must be the current backup.
    3622              :   ///
    3623              :   /// [body] The backup data.
    3624            4 :   Future<RoomKeysUpdateResponse> putRoomKeys(
    3625              :     String version,
    3626              :     RoomKeys body,
    3627              :   ) async {
    3628            4 :     final requestUri = Uri(
    3629              :       path: '_matrix/client/v3/room_keys/keys',
    3630            4 :       queryParameters: {
    3631              :         'version': version,
    3632              :       },
    3633              :     );
    3634           12 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    3635           16 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3636            8 :     request.headers['content-type'] = 'application/json';
    3637           16 :     request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
    3638            8 :     final response = await httpClient.send(request);
    3639            8 :     final responseBody = await response.stream.toBytes();
    3640            8 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3641            4 :     final responseString = utf8.decode(responseBody);
    3642            4 :     final json = jsonDecode(responseString);
    3643            4 :     return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
    3644              :   }
    3645              : 
    3646              :   /// Delete the keys from the backup for a given room.
    3647              :   ///
    3648              :   /// [roomId] The ID of the room that the specified key is for.
    3649              :   ///
    3650              :   /// [version] The backup from which to delete the key.
    3651            0 :   Future<RoomKeysUpdateResponse> deleteRoomKeysByRoomId(
    3652              :     String roomId,
    3653              :     String version,
    3654              :   ) async {
    3655            0 :     final requestUri = Uri(
    3656            0 :       path: '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}',
    3657            0 :       queryParameters: {
    3658              :         'version': version,
    3659              :       },
    3660              :     );
    3661            0 :     final request = Request('DELETE', baseUri!.resolveUri(requestUri));
    3662            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3663            0 :     final response = await httpClient.send(request);
    3664            0 :     final responseBody = await response.stream.toBytes();
    3665            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3666            0 :     final responseString = utf8.decode(responseBody);
    3667            0 :     final json = jsonDecode(responseString);
    3668            0 :     return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
    3669              :   }
    3670              : 
    3671              :   /// Retrieve the keys from the backup for a given room.
    3672              :   ///
    3673              :   /// [roomId] The ID of the room that the requested key is for.
    3674              :   ///
    3675              :   /// [version] The backup from which to retrieve the key.
    3676            1 :   Future<RoomKeyBackup> getRoomKeysByRoomId(
    3677              :     String roomId,
    3678              :     String version,
    3679              :   ) async {
    3680            1 :     final requestUri = Uri(
    3681            2 :       path: '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}',
    3682            1 :       queryParameters: {
    3683              :         'version': version,
    3684              :       },
    3685              :     );
    3686            3 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3687            4 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3688            2 :     final response = await httpClient.send(request);
    3689            2 :     final responseBody = await response.stream.toBytes();
    3690            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3691            1 :     final responseString = utf8.decode(responseBody);
    3692            1 :     final json = jsonDecode(responseString);
    3693            1 :     return RoomKeyBackup.fromJson(json as Map<String, Object?>);
    3694              :   }
    3695              : 
    3696              :   /// Store several keys in the backup for a given room.
    3697              :   ///
    3698              :   /// [roomId] The ID of the room that the keys are for.
    3699              :   ///
    3700              :   /// [version] The backup in which to store the keys. Must be the current backup.
    3701              :   ///
    3702              :   /// [body] The backup data
    3703            0 :   Future<RoomKeysUpdateResponse> putRoomKeysByRoomId(
    3704              :     String roomId,
    3705              :     String version,
    3706              :     RoomKeyBackup body,
    3707              :   ) async {
    3708            0 :     final requestUri = Uri(
    3709            0 :       path: '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}',
    3710            0 :       queryParameters: {
    3711              :         'version': version,
    3712              :       },
    3713              :     );
    3714            0 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    3715            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3716            0 :     request.headers['content-type'] = 'application/json';
    3717            0 :     request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
    3718            0 :     final response = await httpClient.send(request);
    3719            0 :     final responseBody = await response.stream.toBytes();
    3720            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3721            0 :     final responseString = utf8.decode(responseBody);
    3722            0 :     final json = jsonDecode(responseString);
    3723            0 :     return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
    3724              :   }
    3725              : 
    3726              :   /// Delete a key from the backup.
    3727              :   ///
    3728              :   /// [roomId] The ID of the room that the specified key is for.
    3729              :   ///
    3730              :   /// [sessionId] The ID of the megolm session whose key is to be deleted.
    3731              :   ///
    3732              :   /// [version] The backup from which to delete the key
    3733            0 :   Future<RoomKeysUpdateResponse> deleteRoomKeyBySessionId(
    3734              :     String roomId,
    3735              :     String sessionId,
    3736              :     String version,
    3737              :   ) async {
    3738            0 :     final requestUri = Uri(
    3739              :       path:
    3740            0 :           '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}/${Uri.encodeComponent(sessionId)}',
    3741            0 :       queryParameters: {
    3742              :         'version': version,
    3743              :       },
    3744              :     );
    3745            0 :     final request = Request('DELETE', baseUri!.resolveUri(requestUri));
    3746            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3747            0 :     final response = await httpClient.send(request);
    3748            0 :     final responseBody = await response.stream.toBytes();
    3749            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3750            0 :     final responseString = utf8.decode(responseBody);
    3751            0 :     final json = jsonDecode(responseString);
    3752            0 :     return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
    3753              :   }
    3754              : 
    3755              :   /// Retrieve a key from the backup.
    3756              :   ///
    3757              :   /// [roomId] The ID of the room that the requested key is for.
    3758              :   ///
    3759              :   /// [sessionId] The ID of the megolm session whose key is requested.
    3760              :   ///
    3761              :   /// [version] The backup from which to retrieve the key.
    3762            1 :   Future<KeyBackupData> getRoomKeyBySessionId(
    3763              :     String roomId,
    3764              :     String sessionId,
    3765              :     String version,
    3766              :   ) async {
    3767            1 :     final requestUri = Uri(
    3768              :       path:
    3769            3 :           '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}/${Uri.encodeComponent(sessionId)}',
    3770            1 :       queryParameters: {
    3771              :         'version': version,
    3772              :       },
    3773              :     );
    3774            3 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3775            4 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3776            2 :     final response = await httpClient.send(request);
    3777            2 :     final responseBody = await response.stream.toBytes();
    3778            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3779            1 :     final responseString = utf8.decode(responseBody);
    3780            1 :     final json = jsonDecode(responseString);
    3781            1 :     return KeyBackupData.fromJson(json as Map<String, Object?>);
    3782              :   }
    3783              : 
    3784              :   /// Store a key in the backup.
    3785              :   ///
    3786              :   /// [roomId] The ID of the room that the key is for.
    3787              :   ///
    3788              :   /// [sessionId] The ID of the megolm session that the key is for.
    3789              :   ///
    3790              :   /// [version] The backup in which to store the key. Must be the current backup.
    3791              :   ///
    3792              :   /// [body] The key data.
    3793            0 :   Future<RoomKeysUpdateResponse> putRoomKeyBySessionId(
    3794              :     String roomId,
    3795              :     String sessionId,
    3796              :     String version,
    3797              :     KeyBackupData body,
    3798              :   ) async {
    3799            0 :     final requestUri = Uri(
    3800              :       path:
    3801            0 :           '_matrix/client/v3/room_keys/keys/${Uri.encodeComponent(roomId)}/${Uri.encodeComponent(sessionId)}',
    3802            0 :       queryParameters: {
    3803              :         'version': version,
    3804              :       },
    3805              :     );
    3806            0 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    3807            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3808            0 :     request.headers['content-type'] = 'application/json';
    3809            0 :     request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
    3810            0 :     final response = await httpClient.send(request);
    3811            0 :     final responseBody = await response.stream.toBytes();
    3812            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3813            0 :     final responseString = utf8.decode(responseBody);
    3814            0 :     final json = jsonDecode(responseString);
    3815            0 :     return RoomKeysUpdateResponse.fromJson(json as Map<String, Object?>);
    3816              :   }
    3817              : 
    3818              :   /// Get information about the latest backup version.
    3819            5 :   Future<GetRoomKeysVersionCurrentResponse> getRoomKeysVersionCurrent() async {
    3820            5 :     final requestUri = Uri(path: '_matrix/client/v3/room_keys/version');
    3821           15 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3822           20 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3823           10 :     final response = await httpClient.send(request);
    3824           10 :     final responseBody = await response.stream.toBytes();
    3825           10 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3826            5 :     final responseString = utf8.decode(responseBody);
    3827            5 :     final json = jsonDecode(responseString);
    3828            5 :     return GetRoomKeysVersionCurrentResponse.fromJson(
    3829              :       json as Map<String, Object?>,
    3830              :     );
    3831              :   }
    3832              : 
    3833              :   /// Creates a new backup.
    3834              :   ///
    3835              :   /// [algorithm] The algorithm used for storing backups.
    3836              :   ///
    3837              :   /// [authData] Algorithm-dependent data. See the documentation for the backup
    3838              :   /// algorithms in [Server-side key backups](https://spec.matrix.org/unstable/client-server-api/#server-side-key-backups) for more information on the
    3839              :   /// expected format of the data.
    3840              :   ///
    3841              :   /// returns `version`:
    3842              :   /// The backup version. This is an opaque string.
    3843            1 :   Future<String> postRoomKeysVersion(
    3844              :     BackupAlgorithm algorithm,
    3845              :     Map<String, Object?> authData,
    3846              :   ) async {
    3847            1 :     final requestUri = Uri(path: '_matrix/client/v3/room_keys/version');
    3848            3 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    3849            4 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3850            2 :     request.headers['content-type'] = 'application/json';
    3851            2 :     request.bodyBytes = utf8.encode(
    3852            2 :       jsonEncode({
    3853            1 :         'algorithm': algorithm.name,
    3854              :         'auth_data': authData,
    3855              :       }),
    3856              :     );
    3857            2 :     final response = await httpClient.send(request);
    3858            2 :     final responseBody = await response.stream.toBytes();
    3859            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3860            1 :     final responseString = utf8.decode(responseBody);
    3861            1 :     final json = jsonDecode(responseString);
    3862            1 :     return json['version'] as String;
    3863              :   }
    3864              : 
    3865              :   /// Delete an existing key backup. Both the information about the backup,
    3866              :   /// as well as all key data related to the backup will be deleted.
    3867              :   ///
    3868              :   /// [version] The backup version to delete, as returned in the `version`
    3869              :   /// parameter in the response of
    3870              :   /// [`POST /_matrix/client/v3/room_keys/version`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3room_keysversion)
    3871              :   /// or [`GET /_matrix/client/v3/room_keys/version/{version}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3room_keysversionversion).
    3872            0 :   Future<void> deleteRoomKeysVersion(String version) async {
    3873            0 :     final requestUri = Uri(
    3874              :       path:
    3875            0 :           '_matrix/client/v3/room_keys/version/${Uri.encodeComponent(version)}',
    3876              :     );
    3877            0 :     final request = Request('DELETE', baseUri!.resolveUri(requestUri));
    3878            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3879            0 :     final response = await httpClient.send(request);
    3880            0 :     final responseBody = await response.stream.toBytes();
    3881            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3882            0 :     final responseString = utf8.decode(responseBody);
    3883            0 :     final json = jsonDecode(responseString);
    3884            0 :     return ignore(json);
    3885              :   }
    3886              : 
    3887              :   /// Get information about an existing backup.
    3888              :   ///
    3889              :   /// [version] The backup version to get, as returned in the `version` parameter
    3890              :   /// of the response in
    3891              :   /// [`POST /_matrix/client/v3/room_keys/version`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3room_keysversion)
    3892              :   /// or this endpoint.
    3893            0 :   Future<GetRoomKeysVersionResponse> getRoomKeysVersion(String version) async {
    3894            0 :     final requestUri = Uri(
    3895              :       path:
    3896            0 :           '_matrix/client/v3/room_keys/version/${Uri.encodeComponent(version)}',
    3897              :     );
    3898            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3899            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3900            0 :     final response = await httpClient.send(request);
    3901            0 :     final responseBody = await response.stream.toBytes();
    3902            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3903            0 :     final responseString = utf8.decode(responseBody);
    3904            0 :     final json = jsonDecode(responseString);
    3905            0 :     return GetRoomKeysVersionResponse.fromJson(json as Map<String, Object?>);
    3906              :   }
    3907              : 
    3908              :   /// Update information about an existing backup.  Only `auth_data` can be modified.
    3909              :   ///
    3910              :   /// [version] The backup version to update, as returned in the `version`
    3911              :   /// parameter in the response of
    3912              :   /// [`POST /_matrix/client/v3/room_keys/version`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3room_keysversion)
    3913              :   /// or [`GET /_matrix/client/v3/room_keys/version/{version}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3room_keysversionversion).
    3914              :   ///
    3915              :   /// [algorithm] The algorithm used for storing backups.  Must be the same as
    3916              :   /// the algorithm currently used by the backup.
    3917              :   ///
    3918              :   /// [authData] Algorithm-dependent data. See the documentation for the backup
    3919              :   /// algorithms in [Server-side key backups](https://spec.matrix.org/unstable/client-server-api/#server-side-key-backups) for more information on the
    3920              :   /// expected format of the data.
    3921            0 :   Future<Map<String, Object?>> putRoomKeysVersion(
    3922              :     String version,
    3923              :     BackupAlgorithm algorithm,
    3924              :     Map<String, Object?> authData,
    3925              :   ) async {
    3926            0 :     final requestUri = Uri(
    3927              :       path:
    3928            0 :           '_matrix/client/v3/room_keys/version/${Uri.encodeComponent(version)}',
    3929              :     );
    3930            0 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    3931            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3932            0 :     request.headers['content-type'] = 'application/json';
    3933            0 :     request.bodyBytes = utf8.encode(
    3934            0 :       jsonEncode({
    3935            0 :         'algorithm': algorithm.name,
    3936              :         'auth_data': authData,
    3937              :       }),
    3938              :     );
    3939            0 :     final response = await httpClient.send(request);
    3940            0 :     final responseBody = await response.stream.toBytes();
    3941            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3942            0 :     final responseString = utf8.decode(responseBody);
    3943            0 :     final json = jsonDecode(responseString);
    3944              :     return json as Map<String, Object?>;
    3945              :   }
    3946              : 
    3947              :   /// Get a list of aliases maintained by the local server for the
    3948              :   /// given room.
    3949              :   ///
    3950              :   /// This endpoint can be called by users who are in the room (external
    3951              :   /// users receive an `M_FORBIDDEN` error response). If the room's
    3952              :   /// `m.room.history_visibility` maps to `world_readable`, any
    3953              :   /// user can call this endpoint.
    3954              :   ///
    3955              :   /// Servers may choose to implement additional access control checks here,
    3956              :   /// such as allowing server administrators to view aliases regardless of
    3957              :   /// membership.
    3958              :   ///
    3959              :   /// **Note:**
    3960              :   /// Clients are recommended not to display this list of aliases prominently
    3961              :   /// as they are not curated, unlike those listed in the `m.room.canonical_alias`
    3962              :   /// state event.
    3963              :   ///
    3964              :   /// [roomId] The room ID to find local aliases of.
    3965              :   ///
    3966              :   /// returns `aliases`:
    3967              :   /// The server's local aliases on the room. Can be empty.
    3968            0 :   Future<List<String>> getLocalAliases(String roomId) async {
    3969            0 :     final requestUri = Uri(
    3970            0 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/aliases',
    3971              :     );
    3972            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    3973            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3974            0 :     final response = await httpClient.send(request);
    3975            0 :     final responseBody = await response.stream.toBytes();
    3976            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    3977            0 :     final responseString = utf8.decode(responseBody);
    3978            0 :     final json = jsonDecode(responseString);
    3979            0 :     return (json['aliases'] as List).map((v) => v as String).toList();
    3980              :   }
    3981              : 
    3982              :   /// Ban a user in the room. If the user is currently in the room, also kick them.
    3983              :   ///
    3984              :   /// When a user is banned from a room, they may not join it or be invited to it until they are unbanned.
    3985              :   ///
    3986              :   /// The caller must have the required power level in order to perform this operation.
    3987              :   ///
    3988              :   /// [roomId] The room identifier (not alias) from which the user should be banned.
    3989              :   ///
    3990              :   /// [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.
    3991              :   ///
    3992              :   /// [userId] The fully qualified user ID of the user being banned.
    3993            5 :   Future<void> ban(String roomId, String userId, {String? reason}) async {
    3994              :     final requestUri =
    3995           15 :         Uri(path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/ban');
    3996           15 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    3997           20 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    3998           10 :     request.headers['content-type'] = 'application/json';
    3999           10 :     request.bodyBytes = utf8.encode(
    4000           10 :       jsonEncode({
    4001            0 :         if (reason != null) 'reason': reason,
    4002            5 :         'user_id': userId,
    4003              :       }),
    4004              :     );
    4005           10 :     final response = await httpClient.send(request);
    4006           10 :     final responseBody = await response.stream.toBytes();
    4007           10 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4008            5 :     final responseString = utf8.decode(responseBody);
    4009            5 :     final json = jsonDecode(responseString);
    4010            5 :     return ignore(json);
    4011              :   }
    4012              : 
    4013              :   /// This API returns a number of events that happened just before and
    4014              :   /// after the specified event. This allows clients to get the context
    4015              :   /// surrounding an event.
    4016              :   ///
    4017              :   /// *Note*: This endpoint supports lazy-loading of room member events. See
    4018              :   /// [Lazy-loading room members](https://spec.matrix.org/unstable/client-server-api/#lazy-loading-room-members) for more information.
    4019              :   ///
    4020              :   /// [roomId] The room to get events from.
    4021              :   ///
    4022              :   /// [eventId] The event to get context around.
    4023              :   ///
    4024              :   /// [limit] The maximum number of context events to return. The limit applies
    4025              :   /// to the sum of the `events_before` and `events_after` arrays. The
    4026              :   /// requested event ID is always returned in `event` even if `limit` is
    4027              :   /// 0. Defaults to 10.
    4028              :   ///
    4029              :   /// [filter] A JSON `RoomEventFilter` to filter the returned events with. The
    4030              :   /// filter is only applied to `events_before`, `events_after`, and
    4031              :   /// `state`. It is not applied to the `event` itself. The filter may
    4032              :   /// be applied before or/and after the `limit` parameter - whichever the
    4033              :   /// homeserver prefers.
    4034              :   ///
    4035              :   /// See [Filtering](https://spec.matrix.org/unstable/client-server-api/#filtering) for more information.
    4036            0 :   Future<EventContext> getEventContext(
    4037              :     String roomId,
    4038              :     String eventId, {
    4039              :     int? limit,
    4040              :     String? filter,
    4041              :   }) async {
    4042            0 :     final requestUri = Uri(
    4043              :       path:
    4044            0 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/context/${Uri.encodeComponent(eventId)}',
    4045            0 :       queryParameters: {
    4046            0 :         if (limit != null) 'limit': limit.toString(),
    4047            0 :         if (filter != null) 'filter': filter,
    4048              :       },
    4049              :     );
    4050            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    4051            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4052            0 :     final response = await httpClient.send(request);
    4053            0 :     final responseBody = await response.stream.toBytes();
    4054            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4055            0 :     final responseString = utf8.decode(responseBody);
    4056            0 :     final json = jsonDecode(responseString);
    4057            0 :     return EventContext.fromJson(json as Map<String, Object?>);
    4058              :   }
    4059              : 
    4060              :   /// Get a single event based on `roomId/eventId`. You must have permission to
    4061              :   /// retrieve this event e.g. by being a member in the room for this event.
    4062              :   ///
    4063              :   /// [roomId] The ID of the room the event is in.
    4064              :   ///
    4065              :   /// [eventId] The event ID to get.
    4066            5 :   Future<MatrixEvent> getOneRoomEvent(String roomId, String eventId) async {
    4067            5 :     final requestUri = Uri(
    4068              :       path:
    4069           15 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/event/${Uri.encodeComponent(eventId)}',
    4070              :     );
    4071           15 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    4072           20 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4073           10 :     final response = await httpClient.send(request);
    4074           10 :     final responseBody = await response.stream.toBytes();
    4075           12 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4076            5 :     final responseString = utf8.decode(responseBody);
    4077            5 :     final json = jsonDecode(responseString);
    4078            5 :     return MatrixEvent.fromJson(json as Map<String, Object?>);
    4079              :   }
    4080              : 
    4081              :   /// This API stops a user remembering about a particular room.
    4082              :   ///
    4083              :   /// In general, history is a first class citizen in Matrix. After this API
    4084              :   /// is called, however, a user will no longer be able to retrieve history
    4085              :   /// for this room. If all users on a homeserver forget a room, the room is
    4086              :   /// eligible for deletion from that homeserver.
    4087              :   ///
    4088              :   /// If the user is currently joined to the room, they must leave the room
    4089              :   /// before calling this API.
    4090              :   ///
    4091              :   /// [roomId] The room identifier to forget.
    4092            0 :   Future<void> forgetRoom(String roomId) async {
    4093            0 :     final requestUri = Uri(
    4094            0 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/forget',
    4095              :     );
    4096            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4097            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4098            0 :     final response = await httpClient.send(request);
    4099            0 :     final responseBody = await response.stream.toBytes();
    4100            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4101            0 :     final responseString = utf8.decode(responseBody);
    4102            0 :     final json = jsonDecode(responseString);
    4103            0 :     return ignore(json);
    4104              :   }
    4105              : 
    4106              :   /// *Note that there are two forms of this API, which are documented separately.
    4107              :   /// This version of the API does not require that the inviter know the Matrix
    4108              :   /// identifier of the invitee, and instead relies on third-party identifiers.
    4109              :   /// The homeserver uses an identity server to perform the mapping from
    4110              :   /// third-party identifier to a Matrix identifier. The other is documented in the*
    4111              :   /// [joining rooms section](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3roomsroomidinvite).
    4112              :   ///
    4113              :   /// This API invites a user to participate in a particular room.
    4114              :   /// They do not start participating in the room until they actually join the
    4115              :   /// room.
    4116              :   ///
    4117              :   /// Only users currently in a particular room can invite other users to
    4118              :   /// join that room.
    4119              :   ///
    4120              :   /// If the identity server did know the Matrix user identifier for the
    4121              :   /// third-party identifier, the homeserver will append a `m.room.member`
    4122              :   /// event to the room.
    4123              :   ///
    4124              :   /// If the identity server does not know a Matrix user identifier for the
    4125              :   /// passed third-party identifier, the homeserver will issue an invitation
    4126              :   /// which can be accepted upon providing proof of ownership of the third-
    4127              :   /// party identifier. This is achieved by the identity server generating a
    4128              :   /// token, which it gives to the inviting homeserver. The homeserver will
    4129              :   /// add an `m.room.third_party_invite` event into the graph for the room,
    4130              :   /// containing that token.
    4131              :   ///
    4132              :   /// When the invitee binds the invited third-party identifier to a Matrix
    4133              :   /// user ID, the identity server will give the user a list of pending
    4134              :   /// invitations, each containing:
    4135              :   ///
    4136              :   /// - The room ID to which they were invited
    4137              :   ///
    4138              :   /// - The token given to the homeserver
    4139              :   ///
    4140              :   /// - A signature of the token, signed with the identity server's private key
    4141              :   ///
    4142              :   /// - The matrix user ID who invited them to the room
    4143              :   ///
    4144              :   /// If a token is requested from the identity server, the homeserver will
    4145              :   /// append a `m.room.third_party_invite` event to the room.
    4146              :   ///
    4147              :   /// [roomId] The room identifier (not alias) to which to invite the user.
    4148              :   ///
    4149              :   /// [address] The invitee's third-party identifier.
    4150              :   ///
    4151              :   /// [idAccessToken] An access token previously registered with the identity server. Servers
    4152              :   /// can treat this as optional to distinguish between r0.5-compatible clients
    4153              :   /// and this specification version.
    4154              :   ///
    4155              :   /// [idServer] The hostname+port of the identity server which should be used for third-party identifier lookups.
    4156              :   ///
    4157              :   /// [medium] The kind of address being passed in the address field, for example
    4158              :   /// `email` (see [the list of recognised values](https://spec.matrix.org/unstable/appendices/#3pid-types)).
    4159            0 :   Future<void> inviteBy3PID(
    4160              :     String roomId,
    4161              :     String address,
    4162              :     String idAccessToken,
    4163              :     String idServer,
    4164              :     String medium,
    4165              :   ) async {
    4166            0 :     final requestUri = Uri(
    4167            0 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/invite',
    4168              :     );
    4169            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4170            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4171            0 :     request.headers['content-type'] = 'application/json';
    4172            0 :     request.bodyBytes = utf8.encode(
    4173            0 :       jsonEncode({
    4174              :         'address': address,
    4175              :         'id_access_token': idAccessToken,
    4176              :         'id_server': idServer,
    4177              :         'medium': medium,
    4178              :       }),
    4179              :     );
    4180            0 :     final response = await httpClient.send(request);
    4181            0 :     final responseBody = await response.stream.toBytes();
    4182            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4183            0 :     final responseString = utf8.decode(responseBody);
    4184            0 :     final json = jsonDecode(responseString);
    4185            0 :     return ignore(json);
    4186              :   }
    4187              : 
    4188              :   /// *Note that there are two forms of this API, which are documented separately.
    4189              :   /// This version of the API requires that the inviter knows the Matrix
    4190              :   /// identifier of the invitee. The other is documented in the
    4191              :   /// [third-party invites](https://spec.matrix.org/unstable/client-server-api/#third-party-invites) section.*
    4192              :   ///
    4193              :   /// This API invites a user to participate in a particular room.
    4194              :   /// They do not start participating in the room until they actually join the
    4195              :   /// room.
    4196              :   ///
    4197              :   /// Only users currently in a particular room can invite other users to
    4198              :   /// join that room.
    4199              :   ///
    4200              :   /// If the user was invited to the room, the homeserver will append a
    4201              :   /// `m.room.member` event to the room.
    4202              :   ///
    4203              :   /// [roomId] The room identifier (not alias) to which to invite the user.
    4204              :   ///
    4205              :   /// [reason] Optional reason to be included as the `reason` on the subsequent
    4206              :   /// membership event.
    4207              :   ///
    4208              :   /// [userId] The fully qualified user ID of the invitee.
    4209            3 :   Future<void> inviteUser(
    4210              :     String roomId,
    4211              :     String userId, {
    4212              :     String? reason,
    4213              :   }) async {
    4214            3 :     final requestUri = Uri(
    4215            6 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/invite',
    4216              :     );
    4217            9 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4218           12 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4219            6 :     request.headers['content-type'] = 'application/json';
    4220            6 :     request.bodyBytes = utf8.encode(
    4221            6 :       jsonEncode({
    4222            0 :         if (reason != null) 'reason': reason,
    4223            3 :         'user_id': userId,
    4224              :       }),
    4225              :     );
    4226            6 :     final response = await httpClient.send(request);
    4227            6 :     final responseBody = await response.stream.toBytes();
    4228            6 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4229            3 :     final responseString = utf8.decode(responseBody);
    4230            3 :     final json = jsonDecode(responseString);
    4231            3 :     return ignore(json);
    4232              :   }
    4233              : 
    4234              :   /// *Note that this API requires a room ID, not alias.*
    4235              :   /// `/join/{roomIdOrAlias}` *exists if you have a room alias.*
    4236              :   ///
    4237              :   /// This API starts a user participating in a particular room, if that user
    4238              :   /// is allowed to participate in that room. After this call, the client is
    4239              :   /// allowed to see all current state events in the room, and all subsequent
    4240              :   /// events associated with the room until the user leaves the room.
    4241              :   ///
    4242              :   /// After a user has joined a room, the room will appear as an entry in the
    4243              :   /// response of the [`/initialSync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3initialsync)
    4244              :   /// and [`/sync`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync) APIs.
    4245              :   ///
    4246              :   /// [roomId] The room identifier (not alias) to join.
    4247              :   ///
    4248              :   /// [reason] Optional reason to be included as the `reason` on the subsequent
    4249              :   /// membership event.
    4250              :   ///
    4251              :   /// [thirdPartySigned] If supplied, the homeserver must verify that it matches a pending
    4252              :   /// `m.room.third_party_invite` event in the room, and perform
    4253              :   /// key validity checking if required by the event.
    4254              :   ///
    4255              :   /// returns `room_id`:
    4256              :   /// The joined room ID.
    4257            0 :   Future<String> joinRoomById(
    4258              :     String roomId, {
    4259              :     String? reason,
    4260              :     ThirdPartySigned? thirdPartySigned,
    4261              :   }) async {
    4262            0 :     final requestUri = Uri(
    4263            0 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/join',
    4264              :     );
    4265            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4266            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4267            0 :     request.headers['content-type'] = 'application/json';
    4268            0 :     request.bodyBytes = utf8.encode(
    4269            0 :       jsonEncode({
    4270            0 :         if (reason != null) 'reason': reason,
    4271              :         if (thirdPartySigned != null)
    4272            0 :           'third_party_signed': thirdPartySigned.toJson(),
    4273              :       }),
    4274              :     );
    4275            0 :     final response = await httpClient.send(request);
    4276            0 :     final responseBody = await response.stream.toBytes();
    4277            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4278            0 :     final responseString = utf8.decode(responseBody);
    4279            0 :     final json = jsonDecode(responseString);
    4280            0 :     return json['room_id'] as String;
    4281              :   }
    4282              : 
    4283              :   /// 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.
    4284              :   ///
    4285              :   /// [roomId] The room to get the members of.
    4286              :   ///
    4287              :   /// returns `joined`:
    4288              :   /// A map from user ID to a RoomMember object.
    4289            0 :   Future<Map<String, RoomMember>?> getJoinedMembersByRoom(String roomId) async {
    4290            0 :     final requestUri = Uri(
    4291              :       path:
    4292            0 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/joined_members',
    4293              :     );
    4294            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    4295            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4296            0 :     final response = await httpClient.send(request);
    4297            0 :     final responseBody = await response.stream.toBytes();
    4298            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4299            0 :     final responseString = utf8.decode(responseBody);
    4300            0 :     final json = jsonDecode(responseString);
    4301            0 :     return ((v) => v != null
    4302            0 :         ? (v as Map<String, Object?>).map(
    4303            0 :             (k, v) =>
    4304            0 :                 MapEntry(k, RoomMember.fromJson(v as Map<String, Object?>)),
    4305              :           )
    4306            0 :         : null)(json['joined']);
    4307              :   }
    4308              : 
    4309              :   /// Kick a user from the room.
    4310              :   ///
    4311              :   /// The caller must have the required power level in order to perform this operation.
    4312              :   ///
    4313              :   /// Kicking a user adjusts the target member's membership state to be `leave` with an
    4314              :   /// optional `reason`. Like with other membership changes, a user can directly adjust
    4315              :   /// the target member's state by making a request to `/rooms/<room id>/state/m.room.member/<user id>`.
    4316              :   ///
    4317              :   /// [roomId] The room identifier (not alias) from which the user should be kicked.
    4318              :   ///
    4319              :   /// [reason] The reason the user has been kicked. This will be supplied as the
    4320              :   /// `reason` on the target's updated [`m.room.member`](https://spec.matrix.org/unstable/client-server-api/#mroommember) event.
    4321              :   ///
    4322              :   /// [userId] The fully qualified user ID of the user being kicked.
    4323            5 :   Future<void> kick(String roomId, String userId, {String? reason}) async {
    4324            5 :     final requestUri = Uri(
    4325           10 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/kick',
    4326              :     );
    4327           15 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4328           20 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4329           10 :     request.headers['content-type'] = 'application/json';
    4330           10 :     request.bodyBytes = utf8.encode(
    4331           10 :       jsonEncode({
    4332            0 :         if (reason != null) 'reason': reason,
    4333            5 :         'user_id': userId,
    4334              :       }),
    4335              :     );
    4336           10 :     final response = await httpClient.send(request);
    4337           10 :     final responseBody = await response.stream.toBytes();
    4338           10 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4339            5 :     final responseString = utf8.decode(responseBody);
    4340            5 :     final json = jsonDecode(responseString);
    4341            5 :     return ignore(json);
    4342              :   }
    4343              : 
    4344              :   /// This API stops a user participating in a particular room.
    4345              :   ///
    4346              :   /// If the user was already in the room, they will no longer be able to see
    4347              :   /// new events in the room. If the room requires an invite to join, they
    4348              :   /// will need to be re-invited before they can re-join.
    4349              :   ///
    4350              :   /// If the user was invited to the room, but had not joined, this call
    4351              :   /// serves to reject the invite.
    4352              :   ///
    4353              :   /// The user will still be allowed to retrieve history from the room which
    4354              :   /// they were previously allowed to see.
    4355              :   ///
    4356              :   /// [roomId] The room identifier to leave.
    4357              :   ///
    4358              :   /// [reason] Optional reason to be included as the `reason` on the subsequent
    4359              :   /// membership event.
    4360            1 :   Future<void> leaveRoom(String roomId, {String? reason}) async {
    4361            1 :     final requestUri = Uri(
    4362            2 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/leave',
    4363              :     );
    4364            3 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4365            4 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4366            2 :     request.headers['content-type'] = 'application/json';
    4367            2 :     request.bodyBytes = utf8.encode(
    4368            2 :       jsonEncode({
    4369            0 :         if (reason != null) 'reason': reason,
    4370              :       }),
    4371              :     );
    4372            2 :     final response = await httpClient.send(request);
    4373            2 :     final responseBody = await response.stream.toBytes();
    4374            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4375            1 :     final responseString = utf8.decode(responseBody);
    4376            1 :     final json = jsonDecode(responseString);
    4377            1 :     return ignore(json);
    4378              :   }
    4379              : 
    4380              :   /// Get the list of members for this room.
    4381              :   ///
    4382              :   /// [roomId] The room to get the member events for.
    4383              :   ///
    4384              :   /// [at] The point in time (pagination token) to return members for in the room.
    4385              :   /// This token can be obtained from a `prev_batch` token returned for
    4386              :   /// each room by the sync API. Defaults to the current state of the room,
    4387              :   /// as determined by the server.
    4388              :   ///
    4389              :   /// [membership] The kind of membership to filter for. Defaults to no filtering if
    4390              :   /// unspecified. When specified alongside `not_membership`, the two
    4391              :   /// parameters create an 'or' condition: either the membership *is*
    4392              :   /// the same as `membership` **or** *is not* the same as `not_membership`.
    4393              :   ///
    4394              :   /// [notMembership] The kind of membership to exclude from the results. Defaults to no
    4395              :   /// filtering if unspecified.
    4396              :   ///
    4397              :   /// returns `chunk`:
    4398              :   ///
    4399            3 :   Future<List<MatrixEvent>?> getMembersByRoom(
    4400              :     String roomId, {
    4401              :     String? at,
    4402              :     Membership? membership,
    4403              :     Membership? notMembership,
    4404              :   }) async {
    4405            3 :     final requestUri = Uri(
    4406            6 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/members',
    4407            3 :       queryParameters: {
    4408            0 :         if (at != null) 'at': at,
    4409            0 :         if (membership != null) 'membership': membership.name,
    4410            0 :         if (notMembership != null) 'not_membership': notMembership.name,
    4411              :       },
    4412              :     );
    4413            9 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    4414           12 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4415            6 :     final response = await httpClient.send(request);
    4416            6 :     final responseBody = await response.stream.toBytes();
    4417            6 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4418            3 :     final responseString = utf8.decode(responseBody);
    4419            3 :     final json = jsonDecode(responseString);
    4420            3 :     return ((v) => v != null
    4421              :         ? (v as List)
    4422            9 :             .map((v) => MatrixEvent.fromJson(v as Map<String, Object?>))
    4423            3 :             .toList()
    4424            6 :         : null)(json['chunk']);
    4425              :   }
    4426              : 
    4427              :   /// This API returns a list of message and state events for a room. It uses
    4428              :   /// pagination query parameters to paginate history in the room.
    4429              :   ///
    4430              :   /// *Note*: This endpoint supports lazy-loading of room member events. See
    4431              :   /// [Lazy-loading room members](https://spec.matrix.org/unstable/client-server-api/#lazy-loading-room-members) for more information.
    4432              :   ///
    4433              :   /// [roomId] The room to get events from.
    4434              :   ///
    4435              :   /// [from] The token to start returning events from. This token can be obtained
    4436              :   /// from a `prev_batch` or `next_batch` token returned by the `/sync` endpoint,
    4437              :   /// or from an `end` token returned by a previous request to this endpoint.
    4438              :   ///
    4439              :   /// This endpoint can also accept a value returned as a `start` token
    4440              :   /// by a previous request to this endpoint, though servers are not
    4441              :   /// required to support this. Clients should not rely on the behaviour.
    4442              :   ///
    4443              :   /// If it is not provided, the homeserver shall return a list of messages
    4444              :   /// from the first or last (per the value of the `dir` parameter) visible
    4445              :   /// event in the room history for the requesting user.
    4446              :   ///
    4447              :   /// [to] The token to stop returning events at. This token can be obtained from
    4448              :   /// a `prev_batch` or `next_batch` token returned by the `/sync` endpoint,
    4449              :   /// or from an `end` token returned by a previous request to this endpoint.
    4450              :   ///
    4451              :   /// [dir] The direction to return events from. If this is set to `f`, events
    4452              :   /// will be returned in chronological order starting at `from`. If it
    4453              :   /// is set to `b`, events will be returned in *reverse* chronological
    4454              :   /// order, again starting at `from`.
    4455              :   ///
    4456              :   /// [limit] The maximum number of events to return. Default: 10.
    4457              :   ///
    4458              :   /// [filter] A JSON RoomEventFilter to filter returned events with.
    4459            4 :   Future<GetRoomEventsResponse> getRoomEvents(
    4460              :     String roomId,
    4461              :     Direction dir, {
    4462              :     String? from,
    4463              :     String? to,
    4464              :     int? limit,
    4465              :     String? filter,
    4466              :   }) async {
    4467            4 :     final requestUri = Uri(
    4468            8 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/messages',
    4469            4 :       queryParameters: {
    4470            4 :         if (from != null) 'from': from,
    4471            0 :         if (to != null) 'to': to,
    4472            8 :         'dir': dir.name,
    4473            8 :         if (limit != null) 'limit': limit.toString(),
    4474            4 :         if (filter != null) 'filter': filter,
    4475              :       },
    4476              :     );
    4477           12 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    4478           16 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4479            8 :     final response = await httpClient.send(request);
    4480            8 :     final responseBody = await response.stream.toBytes();
    4481            8 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4482            4 :     final responseString = utf8.decode(responseBody);
    4483            4 :     final json = jsonDecode(responseString);
    4484            4 :     return GetRoomEventsResponse.fromJson(json as Map<String, Object?>);
    4485              :   }
    4486              : 
    4487              :   /// Sets the position of the read marker for a given room, and optionally
    4488              :   /// the read receipt's location.
    4489              :   ///
    4490              :   /// [roomId] The room ID to set the read marker in for the user.
    4491              :   ///
    4492              :   /// [mFullyRead] The event ID the read marker should be located at. The
    4493              :   /// event MUST belong to the room.
    4494              :   ///
    4495              :   /// [mRead] The event ID to set the read receipt location at. This is
    4496              :   /// equivalent to calling `/receipt/m.read/$elsewhere:example.org`
    4497              :   /// and is provided here to save that extra call.
    4498              :   ///
    4499              :   /// [mReadPrivate] The event ID to set the *private* read receipt location at. This
    4500              :   /// equivalent to calling `/receipt/m.read.private/$elsewhere:example.org`
    4501              :   /// and is provided here to save that extra call.
    4502            4 :   Future<void> setReadMarker(
    4503              :     String roomId, {
    4504              :     String? mFullyRead,
    4505              :     String? mRead,
    4506              :     String? mReadPrivate,
    4507              :   }) async {
    4508            4 :     final requestUri = Uri(
    4509              :       path:
    4510            8 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/read_markers',
    4511              :     );
    4512           12 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4513           16 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4514            8 :     request.headers['content-type'] = 'application/json';
    4515            8 :     request.bodyBytes = utf8.encode(
    4516            8 :       jsonEncode({
    4517            4 :         if (mFullyRead != null) 'm.fully_read': mFullyRead,
    4518            2 :         if (mRead != null) 'm.read': mRead,
    4519            2 :         if (mReadPrivate != null) 'm.read.private': mReadPrivate,
    4520              :       }),
    4521              :     );
    4522            8 :     final response = await httpClient.send(request);
    4523            8 :     final responseBody = await response.stream.toBytes();
    4524            8 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4525            4 :     final responseString = utf8.decode(responseBody);
    4526            4 :     final json = jsonDecode(responseString);
    4527            4 :     return ignore(json);
    4528              :   }
    4529              : 
    4530              :   /// This API updates the marker for the given receipt type to the event ID
    4531              :   /// specified.
    4532              :   ///
    4533              :   /// [roomId] The room in which to send the event.
    4534              :   ///
    4535              :   /// [receiptType] The type of receipt to send. This can also be `m.fully_read` as an
    4536              :   /// alternative to [`/read_markers`](https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3roomsroomidread_markers).
    4537              :   ///
    4538              :   /// Note that `m.fully_read` does not appear under `m.receipt`: this endpoint
    4539              :   /// effectively calls `/read_markers` internally when presented with a receipt
    4540              :   /// type of `m.fully_read`.
    4541              :   ///
    4542              :   /// [eventId] The event ID to acknowledge up to.
    4543              :   ///
    4544              :   /// [threadId] The root thread event's ID (or `main`) for which
    4545              :   /// thread this receipt is intended to be under. If
    4546              :   /// not specified, the read receipt is *unthreaded*
    4547              :   /// (default).
    4548            0 :   Future<void> postReceipt(
    4549              :     String roomId,
    4550              :     ReceiptType receiptType,
    4551              :     String eventId, {
    4552              :     String? threadId,
    4553              :   }) async {
    4554            0 :     final requestUri = Uri(
    4555              :       path:
    4556            0 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/receipt/${Uri.encodeComponent(receiptType.name)}/${Uri.encodeComponent(eventId)}',
    4557              :     );
    4558            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4559            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4560            0 :     request.headers['content-type'] = 'application/json';
    4561            0 :     request.bodyBytes = utf8.encode(
    4562            0 :       jsonEncode({
    4563            0 :         if (threadId != null) 'thread_id': threadId,
    4564              :       }),
    4565              :     );
    4566            0 :     final response = await httpClient.send(request);
    4567            0 :     final responseBody = await response.stream.toBytes();
    4568            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4569            0 :     final responseString = utf8.decode(responseBody);
    4570            0 :     final json = jsonDecode(responseString);
    4571            0 :     return ignore(json);
    4572              :   }
    4573              : 
    4574              :   /// Strips all information out of an event which isn't critical to the
    4575              :   /// integrity of the server-side representation of the room.
    4576              :   ///
    4577              :   /// This cannot be undone.
    4578              :   ///
    4579              :   /// Any user with a power level greater than or equal to the `m.room.redaction`
    4580              :   /// event power level may send redaction events in the room. If the user's power
    4581              :   /// level greater is also greater than or equal to the `redact` power level
    4582              :   /// of the room, the user may redact events sent by other users.
    4583              :   ///
    4584              :   /// Server administrators may redact events sent by users on their server.
    4585              :   ///
    4586              :   /// [roomId] The room from which to redact the event.
    4587              :   ///
    4588              :   /// [eventId] The ID of the event to redact
    4589              :   ///
    4590              :   /// [txnId] The [transaction ID](https://spec.matrix.org/unstable/client-server-api/#transaction-identifiers) for this event. Clients should generate a
    4591              :   /// unique ID; it will be used by the server to ensure idempotency of requests.
    4592              :   ///
    4593              :   /// [reason] The reason for the event being redacted.
    4594              :   ///
    4595              :   /// returns `event_id`:
    4596              :   /// A unique identifier for the event.
    4597            1 :   Future<String?> redactEvent(
    4598              :     String roomId,
    4599              :     String eventId,
    4600              :     String txnId, {
    4601              :     String? reason,
    4602              :   }) async {
    4603            1 :     final requestUri = Uri(
    4604              :       path:
    4605            4 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/redact/${Uri.encodeComponent(eventId)}/${Uri.encodeComponent(txnId)}',
    4606              :     );
    4607            3 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    4608            4 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4609            2 :     request.headers['content-type'] = 'application/json';
    4610            2 :     request.bodyBytes = utf8.encode(
    4611            2 :       jsonEncode({
    4612            1 :         if (reason != null) 'reason': reason,
    4613              :       }),
    4614              :     );
    4615            2 :     final response = await httpClient.send(request);
    4616            2 :     final responseBody = await response.stream.toBytes();
    4617            2 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4618            1 :     final responseString = utf8.decode(responseBody);
    4619            1 :     final json = jsonDecode(responseString);
    4620            3 :     return ((v) => v != null ? v as String : null)(json['event_id']);
    4621              :   }
    4622              : 
    4623              :   /// Reports a room as inappropriate to the server, which may then notify
    4624              :   /// the appropriate people. How such information is delivered is left up to
    4625              :   /// implementations. The caller is not required to be joined to the room to
    4626              :   /// report it.
    4627              :   ///
    4628              :   /// [roomId] The room being reported.
    4629              :   ///
    4630              :   /// [reason] The reason the room is being reported.
    4631            0 :   Future<void> reportRoom(String roomId, {String? reason}) async {
    4632            0 :     final requestUri = Uri(
    4633            0 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/report',
    4634              :     );
    4635            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4636            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4637            0 :     request.headers['content-type'] = 'application/json';
    4638            0 :     request.bodyBytes = utf8.encode(
    4639            0 :       jsonEncode({
    4640            0 :         if (reason != null) 'reason': reason,
    4641              :       }),
    4642              :     );
    4643            0 :     final response = await httpClient.send(request);
    4644            0 :     final responseBody = await response.stream.toBytes();
    4645            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4646            0 :     final responseString = utf8.decode(responseBody);
    4647            0 :     final json = jsonDecode(responseString);
    4648            0 :     return ignore(json);
    4649              :   }
    4650              : 
    4651              :   /// Reports an event as inappropriate to the server, which may then notify
    4652              :   /// the appropriate people. The caller must be joined to the room to report
    4653              :   /// it.
    4654              :   ///
    4655              :   /// It might be possible for clients to deduce whether an event exists by
    4656              :   /// timing the response, as only a report for an event that does exist
    4657              :   /// will require the homeserver to check whether a user is joined to
    4658              :   /// the room. To combat this, homeserver implementations should add
    4659              :   /// a random delay when generating a response.
    4660              :   ///
    4661              :   /// [roomId] The room in which the event being reported is located.
    4662              :   ///
    4663              :   /// [eventId] The event to report.
    4664              :   ///
    4665              :   /// [reason] The reason the content is being reported.
    4666              :   ///
    4667              :   /// [score] The score to rate this content as where -100 is most offensive
    4668              :   /// and 0 is inoffensive.
    4669            0 :   Future<void> reportEvent(
    4670              :     String roomId,
    4671              :     String eventId, {
    4672              :     String? reason,
    4673              :     int? score,
    4674              :   }) async {
    4675            0 :     final requestUri = Uri(
    4676              :       path:
    4677            0 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/report/${Uri.encodeComponent(eventId)}',
    4678              :     );
    4679            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4680            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4681            0 :     request.headers['content-type'] = 'application/json';
    4682            0 :     request.bodyBytes = utf8.encode(
    4683            0 :       jsonEncode({
    4684            0 :         if (reason != null) 'reason': reason,
    4685            0 :         if (score != null) 'score': score,
    4686              :       }),
    4687              :     );
    4688            0 :     final response = await httpClient.send(request);
    4689            0 :     final responseBody = await response.stream.toBytes();
    4690            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4691            0 :     final responseString = utf8.decode(responseBody);
    4692            0 :     final json = jsonDecode(responseString);
    4693            0 :     return ignore(json);
    4694              :   }
    4695              : 
    4696              :   /// This endpoint is used to send a message event to a room. Message events
    4697              :   /// allow access to historical events and pagination, making them suited
    4698              :   /// for "once-off" activity in a room.
    4699              :   ///
    4700              :   /// The body of the request should be the content object of the event; the
    4701              :   /// fields in this object will vary depending on the type of event. See
    4702              :   /// [Room Events](https://spec.matrix.org/unstable/client-server-api/#room-events) for the m. event specification.
    4703              :   ///
    4704              :   /// [roomId] The room to send the event to.
    4705              :   ///
    4706              :   /// [eventType] The type of event to send.
    4707              :   ///
    4708              :   /// [txnId] The [transaction ID](https://spec.matrix.org/unstable/client-server-api/#transaction-identifiers) for this event. Clients should generate an
    4709              :   /// ID unique across requests with the same access token; it will be
    4710              :   /// used by the server to ensure idempotency of requests.
    4711              :   ///
    4712              :   /// [body]
    4713              :   ///
    4714              :   /// returns `event_id`:
    4715              :   /// A unique identifier for the event.
    4716           11 :   Future<String> sendMessage(
    4717              :     String roomId,
    4718              :     String eventType,
    4719              :     String txnId,
    4720              :     Map<String, Object?> body,
    4721              :   ) async {
    4722           11 :     final requestUri = Uri(
    4723              :       path:
    4724           44 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/send/${Uri.encodeComponent(eventType)}/${Uri.encodeComponent(txnId)}',
    4725              :     );
    4726           33 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    4727           44 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4728           22 :     request.headers['content-type'] = 'application/json';
    4729           33 :     request.bodyBytes = utf8.encode(jsonEncode(body));
    4730              :     const maxBodySize = 60000;
    4731           33 :     if (request.bodyBytes.length > maxBodySize) {
    4732            6 :       bodySizeExceeded(maxBodySize, request.bodyBytes.length);
    4733              :     }
    4734           22 :     final response = await httpClient.send(request);
    4735           22 :     final responseBody = await response.stream.toBytes();
    4736           26 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4737           11 :     final responseString = utf8.decode(responseBody);
    4738           11 :     final json = jsonDecode(responseString);
    4739           11 :     return json['event_id'] as String;
    4740              :   }
    4741              : 
    4742              :   /// Get the state events for the current state of a room.
    4743              :   ///
    4744              :   /// [roomId] The room to look up the state for.
    4745            0 :   Future<List<MatrixEvent>> getRoomState(String roomId) async {
    4746            0 :     final requestUri = Uri(
    4747            0 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/state',
    4748              :     );
    4749            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    4750            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4751            0 :     final response = await httpClient.send(request);
    4752            0 :     final responseBody = await response.stream.toBytes();
    4753            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4754            0 :     final responseString = utf8.decode(responseBody);
    4755            0 :     final json = jsonDecode(responseString);
    4756              :     return (json as List)
    4757            0 :         .map((v) => MatrixEvent.fromJson(v as Map<String, Object?>))
    4758            0 :         .toList();
    4759              :   }
    4760              : 
    4761              :   /// Looks up the contents of a state event in a room. If the user is
    4762              :   /// joined to the room then the state is taken from the current
    4763              :   /// state of the room. If the user has left the room then the state is
    4764              :   /// taken from the state of the room when they left.
    4765              :   ///
    4766              :   /// [roomId] The room to look up the state in.
    4767              :   ///
    4768              :   /// [eventType] The type of state to look up.
    4769              :   ///
    4770              :   /// [stateKey] The key of the state to look up. Defaults to an empty string. When
    4771              :   /// an empty string, the trailing slash on this endpoint is optional.
    4772            8 :   Future<Map<String, Object?>> getRoomStateWithKey(
    4773              :     String roomId,
    4774              :     String eventType,
    4775              :     String stateKey,
    4776              :   ) async {
    4777            8 :     final requestUri = Uri(
    4778              :       path:
    4779           32 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/state/${Uri.encodeComponent(eventType)}/${Uri.encodeComponent(stateKey)}',
    4780              :     );
    4781           20 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    4782           24 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4783           12 :     final response = await httpClient.send(request);
    4784           12 :     final responseBody = await response.stream.toBytes();
    4785           15 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4786            6 :     final responseString = utf8.decode(responseBody);
    4787            6 :     final json = jsonDecode(responseString);
    4788              :     return json as Map<String, Object?>;
    4789              :   }
    4790              : 
    4791              :   /// State events can be sent using this endpoint.  These events will be
    4792              :   /// overwritten if `<room id>`, `<event type>` and `<state key>` all
    4793              :   /// match.
    4794              :   ///
    4795              :   /// Requests to this endpoint **cannot use transaction IDs**
    4796              :   /// like other `PUT` paths because they cannot be differentiated from the
    4797              :   /// `state_key`. Furthermore, `POST` is unsupported on state paths.
    4798              :   ///
    4799              :   /// The body of the request should be the content object of the event; the
    4800              :   /// fields in this object will vary depending on the type of event. See
    4801              :   /// [Room Events](https://spec.matrix.org/unstable/client-server-api/#room-events) for the `m.` event specification.
    4802              :   ///
    4803              :   /// If the event type being sent is `m.room.canonical_alias` servers
    4804              :   /// SHOULD ensure that any new aliases being listed in the event are valid
    4805              :   /// per their grammar/syntax and that they point to the room ID where the
    4806              :   /// state event is to be sent. Servers do not validate aliases which are
    4807              :   /// being removed or are already present in the state event.
    4808              :   ///
    4809              :   ///
    4810              :   /// [roomId] The room to set the state in
    4811              :   ///
    4812              :   /// [eventType] The type of event to send.
    4813              :   ///
    4814              :   /// [stateKey] The state_key for the state to send. Defaults to the empty string. When
    4815              :   /// an empty string, the trailing slash on this endpoint is optional.
    4816              :   ///
    4817              :   /// [body]
    4818              :   ///
    4819              :   /// returns `event_id`:
    4820              :   /// A unique identifier for the event.
    4821            7 :   Future<String> setRoomStateWithKey(
    4822              :     String roomId,
    4823              :     String eventType,
    4824              :     String stateKey,
    4825              :     Map<String, Object?> body,
    4826              :   ) async {
    4827            7 :     final requestUri = Uri(
    4828              :       path:
    4829           28 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/state/${Uri.encodeComponent(eventType)}/${Uri.encodeComponent(stateKey)}',
    4830              :     );
    4831           21 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    4832           28 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4833           14 :     request.headers['content-type'] = 'application/json';
    4834           21 :     request.bodyBytes = utf8.encode(jsonEncode(body));
    4835           14 :     final response = await httpClient.send(request);
    4836           14 :     final responseBody = await response.stream.toBytes();
    4837           14 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4838            7 :     final responseString = utf8.decode(responseBody);
    4839            7 :     final json = jsonDecode(responseString);
    4840            7 :     return json['event_id'] as String;
    4841              :   }
    4842              : 
    4843              :   /// This tells the server that the user is typing for the next N
    4844              :   /// milliseconds where N is the value specified in the `timeout` key.
    4845              :   /// Alternatively, if `typing` is `false`, it tells the server that the
    4846              :   /// user has stopped typing.
    4847              :   ///
    4848              :   /// [userId] The user who has started to type.
    4849              :   ///
    4850              :   /// [roomId] The room in which the user is typing.
    4851              :   ///
    4852              :   /// [timeout] The length of time in milliseconds to mark this user as typing.
    4853              :   ///
    4854              :   /// [typing] Whether the user is typing or not. If `false`, the `timeout`
    4855              :   /// key can be omitted.
    4856            0 :   Future<void> setTyping(
    4857              :     String userId,
    4858              :     String roomId,
    4859              :     bool typing, {
    4860              :     int? timeout,
    4861              :   }) async {
    4862            0 :     final requestUri = Uri(
    4863              :       path:
    4864            0 :           '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/typing/${Uri.encodeComponent(userId)}',
    4865              :     );
    4866            0 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    4867            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4868            0 :     request.headers['content-type'] = 'application/json';
    4869            0 :     request.bodyBytes = utf8.encode(
    4870            0 :       jsonEncode({
    4871            0 :         if (timeout != null) 'timeout': timeout,
    4872            0 :         'typing': typing,
    4873              :       }),
    4874              :     );
    4875            0 :     final response = await httpClient.send(request);
    4876            0 :     final responseBody = await response.stream.toBytes();
    4877            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4878            0 :     final responseString = utf8.decode(responseBody);
    4879            0 :     final json = jsonDecode(responseString);
    4880            0 :     return ignore(json);
    4881              :   }
    4882              : 
    4883              :   /// Unban a user from the room. This allows them to be invited to the room,
    4884              :   /// and join if they would otherwise be allowed to join according to its join rules.
    4885              :   ///
    4886              :   /// The caller must have the required power level in order to perform this operation.
    4887              :   ///
    4888              :   /// [roomId] The room identifier (not alias) from which the user should be unbanned.
    4889              :   ///
    4890              :   /// [reason] Optional reason to be included as the `reason` on the subsequent
    4891              :   /// membership event.
    4892              :   ///
    4893              :   /// [userId] The fully qualified user ID of the user being unbanned.
    4894            5 :   Future<void> unban(String roomId, String userId, {String? reason}) async {
    4895            5 :     final requestUri = Uri(
    4896           10 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/unban',
    4897              :     );
    4898           15 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4899           20 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4900           10 :     request.headers['content-type'] = 'application/json';
    4901           10 :     request.bodyBytes = utf8.encode(
    4902           10 :       jsonEncode({
    4903            0 :         if (reason != null) 'reason': reason,
    4904            5 :         'user_id': userId,
    4905              :       }),
    4906              :     );
    4907           10 :     final response = await httpClient.send(request);
    4908           10 :     final responseBody = await response.stream.toBytes();
    4909           10 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4910            5 :     final responseString = utf8.decode(responseBody);
    4911            5 :     final json = jsonDecode(responseString);
    4912            5 :     return ignore(json);
    4913              :   }
    4914              : 
    4915              :   /// Upgrades the given room to a particular room version.
    4916              :   ///
    4917              :   /// [roomId] The ID of the room to upgrade.
    4918              :   ///
    4919              :   /// [newVersion] The new version for the room.
    4920              :   ///
    4921              :   /// returns `replacement_room`:
    4922              :   /// The ID of the new room.
    4923            0 :   Future<String> upgradeRoom(String roomId, String newVersion) async {
    4924            0 :     final requestUri = Uri(
    4925            0 :       path: '_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/upgrade',
    4926              :     );
    4927            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4928            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4929            0 :     request.headers['content-type'] = 'application/json';
    4930            0 :     request.bodyBytes = utf8.encode(
    4931            0 :       jsonEncode({
    4932              :         'new_version': newVersion,
    4933              :       }),
    4934              :     );
    4935            0 :     final response = await httpClient.send(request);
    4936            0 :     final responseBody = await response.stream.toBytes();
    4937            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4938            0 :     final responseString = utf8.decode(responseBody);
    4939            0 :     final json = jsonDecode(responseString);
    4940            0 :     return json['replacement_room'] as String;
    4941              :   }
    4942              : 
    4943              :   /// Performs a full text search across different categories.
    4944              :   ///
    4945              :   /// [nextBatch] The point to return events from. If given, this should be a
    4946              :   /// `next_batch` result from a previous call to this endpoint.
    4947              :   ///
    4948              :   /// [searchCategories] Describes which categories to search in and their criteria.
    4949            0 :   Future<SearchResults> search(
    4950              :     Categories searchCategories, {
    4951              :     String? nextBatch,
    4952              :   }) async {
    4953            0 :     final requestUri = Uri(
    4954              :       path: '_matrix/client/v3/search',
    4955            0 :       queryParameters: {
    4956            0 :         if (nextBatch != null) 'next_batch': nextBatch,
    4957              :       },
    4958              :     );
    4959            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    4960            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4961            0 :     request.headers['content-type'] = 'application/json';
    4962            0 :     request.bodyBytes = utf8.encode(
    4963            0 :       jsonEncode({
    4964            0 :         'search_categories': searchCategories.toJson(),
    4965              :       }),
    4966              :     );
    4967            0 :     final response = await httpClient.send(request);
    4968            0 :     final responseBody = await response.stream.toBytes();
    4969            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    4970            0 :     final responseString = utf8.decode(responseBody);
    4971            0 :     final json = jsonDecode(responseString);
    4972            0 :     return SearchResults.fromJson(json as Map<String, Object?>);
    4973              :   }
    4974              : 
    4975              :   /// This endpoint is used to send send-to-device events to a set of
    4976              :   /// client devices.
    4977              :   ///
    4978              :   /// [eventType] The type of event to send.
    4979              :   ///
    4980              :   /// [txnId] The [transaction ID](https://spec.matrix.org/unstable/client-server-api/#transaction-identifiers) for this event. Clients should generate an
    4981              :   /// ID unique across requests with the same access token; it will be
    4982              :   /// used by the server to ensure idempotency of requests.
    4983              :   ///
    4984              :   /// [messages] The messages to send. A map from user ID, to a map from
    4985              :   /// device ID to message body. The device ID may also be `*`,
    4986              :   /// meaning all known devices for the user.
    4987           10 :   Future<void> sendToDevice(
    4988              :     String eventType,
    4989              :     String txnId,
    4990              :     Map<String, Map<String, Map<String, Object?>>> messages,
    4991              :   ) async {
    4992           10 :     final requestUri = Uri(
    4993              :       path:
    4994           30 :           '_matrix/client/v3/sendToDevice/${Uri.encodeComponent(eventType)}/${Uri.encodeComponent(txnId)}',
    4995              :     );
    4996           30 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    4997           40 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    4998           20 :     request.headers['content-type'] = 'application/json';
    4999           20 :     request.bodyBytes = utf8.encode(
    5000           20 :       jsonEncode({
    5001              :         'messages': messages
    5002           51 :             .map((k, v) => MapEntry(k, v.map((k, v) => MapEntry(k, v)))),
    5003              :       }),
    5004              :     );
    5005           20 :     final response = await httpClient.send(request);
    5006           20 :     final responseBody = await response.stream.toBytes();
    5007           21 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5008           10 :     final responseString = utf8.decode(responseBody);
    5009           10 :     final json = jsonDecode(responseString);
    5010           10 :     return ignore(json);
    5011              :   }
    5012              : 
    5013              :   /// Synchronise the client's state with the latest state on the server.
    5014              :   /// Clients use this API when they first log in to get an initial snapshot
    5015              :   /// of the state on the server, and then continue to call this API to get
    5016              :   /// incremental deltas to the state, and to receive new messages.
    5017              :   ///
    5018              :   /// *Note*: This endpoint supports lazy-loading. See [Filtering](https://spec.matrix.org/unstable/client-server-api/#filtering)
    5019              :   /// for more information. Lazy-loading members is only supported on the `state` part of a
    5020              :   /// [`RoomFilter`](#post_matrixclientv3useruseridfilter_request_roomfilter)
    5021              :   /// for this endpoint. When lazy-loading is enabled, servers MUST include the
    5022              :   /// syncing user's own membership event when they join a room, or when the
    5023              :   /// full state of rooms is requested, to aid discovering the user's avatar &
    5024              :   /// displayname.
    5025              :   ///
    5026              :   /// Further, like other members, the user's own membership event is eligible
    5027              :   /// for being considered redundant by the server. When a sync is `limited`,
    5028              :   /// the server MUST return membership events for events in the gap
    5029              :   /// (between `since` and the start of the returned timeline), regardless
    5030              :   /// as to whether or not they are redundant. This ensures that joins/leaves
    5031              :   /// and profile changes which occur during the gap are not lost.
    5032              :   ///
    5033              :   /// Note that the default behaviour of `state` is to include all membership
    5034              :   /// events, alongside other state, when lazy-loading is not enabled.
    5035              :   ///
    5036              :   /// [filter] The ID of a filter created using the filter API or a filter JSON
    5037              :   /// object encoded as a string. The server will detect whether it is
    5038              :   /// an ID or a JSON object by whether the first character is a `"{"`
    5039              :   /// open brace. Passing the JSON inline is best suited to one off
    5040              :   /// requests. Creating a filter using the filter API is recommended for
    5041              :   /// clients that reuse the same filter multiple times, for example in
    5042              :   /// long poll requests.
    5043              :   ///
    5044              :   /// See [Filtering](https://spec.matrix.org/unstable/client-server-api/#filtering) for more information.
    5045              :   ///
    5046              :   /// [since] A point in time to continue a sync from. This should be the
    5047              :   /// `next_batch` token returned by an earlier call to this endpoint.
    5048              :   ///
    5049              :   /// [fullState] Controls whether to include the full state for all rooms the user
    5050              :   /// is a member of.
    5051              :   ///
    5052              :   /// If this is set to `true`, then all state events will be returned,
    5053              :   /// even if `since` is non-empty. The timeline will still be limited
    5054              :   /// by the `since` parameter. In this case, the `timeout` parameter
    5055              :   /// will be ignored and the query will return immediately, possibly with
    5056              :   /// an empty timeline.
    5057              :   ///
    5058              :   /// If `false`, and `since` is non-empty, only state which has
    5059              :   /// changed since the point indicated by `since` will be returned.
    5060              :   ///
    5061              :   /// By default, this is `false`.
    5062              :   ///
    5063              :   /// [setPresence] Controls whether the client is automatically marked as online by
    5064              :   /// polling this API. If this parameter is omitted then the client is
    5065              :   /// automatically marked as online when it uses this API. Otherwise if
    5066              :   /// the parameter is set to "offline" then the client is not marked as
    5067              :   /// being online when it uses this API. When set to "unavailable", the
    5068              :   /// client is marked as being idle.
    5069              :   ///
    5070              :   /// [timeout] The maximum time to wait, in milliseconds, before returning this
    5071              :   /// request. If no events (or other data) become available before this
    5072              :   /// time elapses, the server will return a response with empty fields.
    5073              :   ///
    5074              :   /// By default, this is `0`, so the server will return immediately
    5075              :   /// even if the response is empty.
    5076           33 :   Future<SyncUpdate> sync({
    5077              :     String? filter,
    5078              :     String? since,
    5079              :     bool? fullState,
    5080              :     PresenceType? setPresence,
    5081              :     int? timeout,
    5082              :   }) async {
    5083           33 :     final requestUri = Uri(
    5084              :       path: '_matrix/client/v3/sync',
    5085           33 :       queryParameters: {
    5086           33 :         if (filter != null) 'filter': filter,
    5087           31 :         if (since != null) 'since': since,
    5088            0 :         if (fullState != null) 'full_state': fullState.toString(),
    5089            0 :         if (setPresence != null) 'set_presence': setPresence.name,
    5090           66 :         if (timeout != null) 'timeout': timeout.toString(),
    5091              :       },
    5092              :     );
    5093           99 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5094          132 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5095           66 :     final response = await httpClient.send(request);
    5096           66 :     final responseBody = await response.stream.toBytes();
    5097           67 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5098           33 :     final responseString = utf8.decode(responseBody);
    5099           33 :     final json = jsonDecode(responseString);
    5100           33 :     return SyncUpdate.fromJson(json as Map<String, Object?>);
    5101              :   }
    5102              : 
    5103              :   /// Retrieve an array of third-party network locations from a Matrix room
    5104              :   /// alias.
    5105              :   ///
    5106              :   /// [alias] The Matrix room alias to look up.
    5107            0 :   Future<List<Location>> queryLocationByAlias(String alias) async {
    5108            0 :     final requestUri = Uri(
    5109              :       path: '_matrix/client/v3/thirdparty/location',
    5110            0 :       queryParameters: {
    5111              :         'alias': alias,
    5112              :       },
    5113              :     );
    5114            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5115            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5116            0 :     final response = await httpClient.send(request);
    5117            0 :     final responseBody = await response.stream.toBytes();
    5118            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5119            0 :     final responseString = utf8.decode(responseBody);
    5120            0 :     final json = jsonDecode(responseString);
    5121              :     return (json as List)
    5122            0 :         .map((v) => Location.fromJson(v as Map<String, Object?>))
    5123            0 :         .toList();
    5124              :   }
    5125              : 
    5126              :   /// Requesting this endpoint with a valid protocol name results in a list
    5127              :   /// of successful mapping results in a JSON array. Each result contains
    5128              :   /// objects to represent the Matrix room or rooms that represent a portal
    5129              :   /// to this third-party network. Each has the Matrix room alias string,
    5130              :   /// an identifier for the particular third-party network protocol, and an
    5131              :   /// object containing the network-specific fields that comprise this
    5132              :   /// identifier. It should attempt to canonicalise the identifier as much
    5133              :   /// as reasonably possible given the network type.
    5134              :   ///
    5135              :   /// [protocol] The protocol used to communicate to the third-party network.
    5136              :   ///
    5137              :   /// [fields] One or more custom fields to help identify the third-party
    5138              :   /// location.
    5139            0 :   Future<List<Location>> queryLocationByProtocol(
    5140              :     String protocol, {
    5141              :     Map<String, String>? fields,
    5142              :   }) async {
    5143            0 :     final requestUri = Uri(
    5144              :       path:
    5145            0 :           '_matrix/client/v3/thirdparty/location/${Uri.encodeComponent(protocol)}',
    5146            0 :       queryParameters: {
    5147            0 :         if (fields != null) ...fields,
    5148              :       },
    5149              :     );
    5150            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5151            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5152            0 :     final response = await httpClient.send(request);
    5153            0 :     final responseBody = await response.stream.toBytes();
    5154            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5155            0 :     final responseString = utf8.decode(responseBody);
    5156            0 :     final json = jsonDecode(responseString);
    5157              :     return (json as List)
    5158            0 :         .map((v) => Location.fromJson(v as Map<String, Object?>))
    5159            0 :         .toList();
    5160              :   }
    5161              : 
    5162              :   /// Fetches the metadata from the homeserver about a particular third-party protocol.
    5163              :   ///
    5164              :   /// [protocol] The name of the protocol.
    5165            0 :   Future<Protocol> getProtocolMetadata(String protocol) async {
    5166            0 :     final requestUri = Uri(
    5167              :       path:
    5168            0 :           '_matrix/client/v3/thirdparty/protocol/${Uri.encodeComponent(protocol)}',
    5169              :     );
    5170            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5171            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5172            0 :     final response = await httpClient.send(request);
    5173            0 :     final responseBody = await response.stream.toBytes();
    5174            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5175            0 :     final responseString = utf8.decode(responseBody);
    5176            0 :     final json = jsonDecode(responseString);
    5177            0 :     return Protocol.fromJson(json as Map<String, Object?>);
    5178              :   }
    5179              : 
    5180              :   /// Fetches the overall metadata about protocols supported by the
    5181              :   /// homeserver. Includes both the available protocols and all fields
    5182              :   /// required for queries against each protocol.
    5183            0 :   Future<Map<String, Protocol>> getProtocols() async {
    5184            0 :     final requestUri = Uri(path: '_matrix/client/v3/thirdparty/protocols');
    5185            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5186            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5187            0 :     final response = await httpClient.send(request);
    5188            0 :     final responseBody = await response.stream.toBytes();
    5189            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5190            0 :     final responseString = utf8.decode(responseBody);
    5191            0 :     final json = jsonDecode(responseString);
    5192            0 :     return (json as Map<String, Object?>).map(
    5193            0 :       (k, v) => MapEntry(k, Protocol.fromJson(v as Map<String, Object?>)),
    5194              :     );
    5195              :   }
    5196              : 
    5197              :   /// Retrieve an array of third-party users from a Matrix User ID.
    5198              :   ///
    5199              :   /// [userid] The Matrix User ID to look up.
    5200            0 :   Future<List<ThirdPartyUser>> queryUserByID(String userid) async {
    5201            0 :     final requestUri = Uri(
    5202              :       path: '_matrix/client/v3/thirdparty/user',
    5203            0 :       queryParameters: {
    5204              :         'userid': userid,
    5205              :       },
    5206              :     );
    5207            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5208            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5209            0 :     final response = await httpClient.send(request);
    5210            0 :     final responseBody = await response.stream.toBytes();
    5211            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5212            0 :     final responseString = utf8.decode(responseBody);
    5213            0 :     final json = jsonDecode(responseString);
    5214              :     return (json as List)
    5215            0 :         .map((v) => ThirdPartyUser.fromJson(v as Map<String, Object?>))
    5216            0 :         .toList();
    5217              :   }
    5218              : 
    5219              :   /// Retrieve a Matrix User ID linked to a user on the third-party service, given
    5220              :   /// a set of user parameters.
    5221              :   ///
    5222              :   /// [protocol] The name of the protocol.
    5223              :   ///
    5224              :   /// [fields] One or more custom fields that are passed to the AS to help identify the user.
    5225            0 :   Future<List<ThirdPartyUser>> queryUserByProtocol(
    5226              :     String protocol, {
    5227              :     Map<String, String>? fields,
    5228              :   }) async {
    5229            0 :     final requestUri = Uri(
    5230              :       path:
    5231            0 :           '_matrix/client/v3/thirdparty/user/${Uri.encodeComponent(protocol)}',
    5232            0 :       queryParameters: {
    5233            0 :         if (fields != null) ...fields,
    5234              :       },
    5235              :     );
    5236            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5237            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5238            0 :     final response = await httpClient.send(request);
    5239            0 :     final responseBody = await response.stream.toBytes();
    5240            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5241            0 :     final responseString = utf8.decode(responseBody);
    5242            0 :     final json = jsonDecode(responseString);
    5243              :     return (json as List)
    5244            0 :         .map((v) => ThirdPartyUser.fromJson(v as Map<String, Object?>))
    5245            0 :         .toList();
    5246              :   }
    5247              : 
    5248              :   /// Get some account data for the client. This config is only visible to the user
    5249              :   /// that set the account data.
    5250              :   ///
    5251              :   /// [userId] The ID of the user to get account data for. The access token must be
    5252              :   /// authorized to make requests for this user ID.
    5253              :   ///
    5254              :   /// [type] The event type of the account data to get. Custom types should be
    5255              :   /// namespaced to avoid clashes.
    5256            0 :   Future<Map<String, Object?>> getAccountData(
    5257              :     String userId,
    5258              :     String type,
    5259              :   ) async {
    5260            0 :     final requestUri = Uri(
    5261              :       path:
    5262            0 :           '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/account_data/${Uri.encodeComponent(type)}',
    5263              :     );
    5264            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5265            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5266            0 :     final response = await httpClient.send(request);
    5267            0 :     final responseBody = await response.stream.toBytes();
    5268            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5269            0 :     final responseString = utf8.decode(responseBody);
    5270            0 :     final json = jsonDecode(responseString);
    5271              :     return json as Map<String, Object?>;
    5272              :   }
    5273              : 
    5274              :   /// Set some account data for the client. This config is only visible to the user
    5275              :   /// that set the account data. The config will be available to clients through the
    5276              :   /// top-level `account_data` field in the homeserver response to
    5277              :   /// [/sync](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync).
    5278              :   ///
    5279              :   /// [userId] The ID of the user to set account data for. The access token must be
    5280              :   /// authorized to make requests for this user ID.
    5281              :   ///
    5282              :   /// [type] The event type of the account data to set. Custom types should be
    5283              :   /// namespaced to avoid clashes.
    5284              :   ///
    5285              :   /// [body] The content of the account data.
    5286           10 :   Future<void> setAccountData(
    5287              :     String userId,
    5288              :     String type,
    5289              :     Map<String, Object?> body,
    5290              :   ) async {
    5291           10 :     final requestUri = Uri(
    5292              :       path:
    5293           30 :           '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/account_data/${Uri.encodeComponent(type)}',
    5294              :     );
    5295           30 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    5296           40 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5297           20 :     request.headers['content-type'] = 'application/json';
    5298           30 :     request.bodyBytes = utf8.encode(jsonEncode(body));
    5299           20 :     final response = await httpClient.send(request);
    5300           20 :     final responseBody = await response.stream.toBytes();
    5301           20 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5302           10 :     final responseString = utf8.decode(responseBody);
    5303           10 :     final json = jsonDecode(responseString);
    5304           10 :     return ignore(json);
    5305              :   }
    5306              : 
    5307              :   /// Uploads a new filter definition to the homeserver.
    5308              :   /// Returns a filter ID that may be used in future requests to
    5309              :   /// restrict which events are returned to the client.
    5310              :   ///
    5311              :   /// [userId] The id of the user uploading the filter. The access token must be authorized to make requests for this user id.
    5312              :   ///
    5313              :   /// [body] The filter to upload.
    5314              :   ///
    5315              :   /// returns `filter_id`:
    5316              :   /// The ID of the filter that was created. Cannot start
    5317              :   /// with a `{` as this character is used to determine
    5318              :   /// if the filter provided is inline JSON or a previously
    5319              :   /// declared filter by homeservers on some APIs.
    5320           33 :   Future<String> defineFilter(String userId, Filter body) async {
    5321           33 :     final requestUri = Uri(
    5322           66 :       path: '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/filter',
    5323              :     );
    5324           99 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    5325          132 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5326           66 :     request.headers['content-type'] = 'application/json';
    5327          132 :     request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
    5328           66 :     final response = await httpClient.send(request);
    5329           66 :     final responseBody = await response.stream.toBytes();
    5330           66 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5331           33 :     final responseString = utf8.decode(responseBody);
    5332           33 :     final json = jsonDecode(responseString);
    5333           33 :     return json['filter_id'] as String;
    5334              :   }
    5335              : 
    5336              :   ///
    5337              :   ///
    5338              :   /// [userId] The user ID to download a filter for.
    5339              :   ///
    5340              :   /// [filterId] The filter ID to download.
    5341            0 :   Future<Filter> getFilter(String userId, String filterId) async {
    5342            0 :     final requestUri = Uri(
    5343              :       path:
    5344            0 :           '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/filter/${Uri.encodeComponent(filterId)}',
    5345              :     );
    5346            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5347            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5348            0 :     final response = await httpClient.send(request);
    5349            0 :     final responseBody = await response.stream.toBytes();
    5350            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5351            0 :     final responseString = utf8.decode(responseBody);
    5352            0 :     final json = jsonDecode(responseString);
    5353            0 :     return Filter.fromJson(json as Map<String, Object?>);
    5354              :   }
    5355              : 
    5356              :   /// Gets an OpenID token object that the requester may supply to another
    5357              :   /// service to verify their identity in Matrix. The generated token is only
    5358              :   /// valid for exchanging for user information from the federation API for
    5359              :   /// OpenID.
    5360              :   ///
    5361              :   /// The access token generated is only valid for the OpenID API. It cannot
    5362              :   /// be used to request another OpenID access token or call `/sync`, for
    5363              :   /// example.
    5364              :   ///
    5365              :   /// [userId] The user to request an OpenID token for. Should be the user who
    5366              :   /// is authenticated for the request.
    5367              :   ///
    5368              :   /// [body] An empty object. Reserved for future expansion.
    5369            0 :   Future<OpenIdCredentials> requestOpenIdToken(
    5370              :     String userId,
    5371              :     Map<String, Object?> body,
    5372              :   ) async {
    5373            0 :     final requestUri = Uri(
    5374              :       path:
    5375            0 :           '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/openid/request_token',
    5376              :     );
    5377            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    5378            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5379            0 :     request.headers['content-type'] = 'application/json';
    5380            0 :     request.bodyBytes = utf8.encode(jsonEncode(body));
    5381            0 :     final response = await httpClient.send(request);
    5382            0 :     final responseBody = await response.stream.toBytes();
    5383            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5384            0 :     final responseString = utf8.decode(responseBody);
    5385            0 :     final json = jsonDecode(responseString);
    5386            0 :     return OpenIdCredentials.fromJson(json as Map<String, Object?>);
    5387              :   }
    5388              : 
    5389              :   /// Get some account data for the client on a given room. This config is only
    5390              :   /// visible to the user that set the account data.
    5391              :   ///
    5392              :   /// [userId] The ID of the user to get account data for. The access token must be
    5393              :   /// authorized to make requests for this user ID.
    5394              :   ///
    5395              :   /// [roomId] The ID of the room to get account data for.
    5396              :   ///
    5397              :   /// [type] The event type of the account data to get. Custom types should be
    5398              :   /// namespaced to avoid clashes.
    5399            0 :   Future<Map<String, Object?>> getAccountDataPerRoom(
    5400              :     String userId,
    5401              :     String roomId,
    5402              :     String type,
    5403              :   ) async {
    5404            0 :     final requestUri = Uri(
    5405              :       path:
    5406            0 :           '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/rooms/${Uri.encodeComponent(roomId)}/account_data/${Uri.encodeComponent(type)}',
    5407              :     );
    5408            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5409            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5410            0 :     final response = await httpClient.send(request);
    5411            0 :     final responseBody = await response.stream.toBytes();
    5412            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5413            0 :     final responseString = utf8.decode(responseBody);
    5414            0 :     final json = jsonDecode(responseString);
    5415              :     return json as Map<String, Object?>;
    5416              :   }
    5417              : 
    5418              :   /// Set some account data for the client on a given room. This config is only
    5419              :   /// visible to the user that set the account data. The config will be delivered to
    5420              :   /// clients in the per-room entries via [/sync](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv3sync).
    5421              :   ///
    5422              :   /// [userId] The ID of the user to set account data for. The access token must be
    5423              :   /// authorized to make requests for this user ID.
    5424              :   ///
    5425              :   /// [roomId] The ID of the room to set account data on.
    5426              :   ///
    5427              :   /// [type] The event type of the account data to set. Custom types should be
    5428              :   /// namespaced to avoid clashes.
    5429              :   ///
    5430              :   /// [body] The content of the account data.
    5431            3 :   Future<void> setAccountDataPerRoom(
    5432              :     String userId,
    5433              :     String roomId,
    5434              :     String type,
    5435              :     Map<String, Object?> body,
    5436              :   ) async {
    5437            3 :     final requestUri = Uri(
    5438              :       path:
    5439           12 :           '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/rooms/${Uri.encodeComponent(roomId)}/account_data/${Uri.encodeComponent(type)}',
    5440              :     );
    5441            9 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    5442           12 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5443            6 :     request.headers['content-type'] = 'application/json';
    5444            9 :     request.bodyBytes = utf8.encode(jsonEncode(body));
    5445            6 :     final response = await httpClient.send(request);
    5446            6 :     final responseBody = await response.stream.toBytes();
    5447            6 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5448            3 :     final responseString = utf8.decode(responseBody);
    5449            3 :     final json = jsonDecode(responseString);
    5450            3 :     return ignore(json);
    5451              :   }
    5452              : 
    5453              :   /// List the tags set by a user on a room.
    5454              :   ///
    5455              :   /// [userId] The id of the user to get tags for. The access token must be
    5456              :   /// authorized to make requests for this user ID.
    5457              :   ///
    5458              :   /// [roomId] The ID of the room to get tags for.
    5459              :   ///
    5460              :   /// returns `tags`:
    5461              :   ///
    5462            0 :   Future<Map<String, Tag>?> getRoomTags(String userId, String roomId) async {
    5463            0 :     final requestUri = Uri(
    5464              :       path:
    5465            0 :           '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/rooms/${Uri.encodeComponent(roomId)}/tags',
    5466              :     );
    5467            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5468            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5469            0 :     final response = await httpClient.send(request);
    5470            0 :     final responseBody = await response.stream.toBytes();
    5471            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5472            0 :     final responseString = utf8.decode(responseBody);
    5473            0 :     final json = jsonDecode(responseString);
    5474            0 :     return ((v) => v != null
    5475              :         ? (v as Map<String, Object?>)
    5476            0 :             .map((k, v) => MapEntry(k, Tag.fromJson(v as Map<String, Object?>)))
    5477            0 :         : null)(json['tags']);
    5478              :   }
    5479              : 
    5480              :   /// Remove a tag from the room.
    5481              :   ///
    5482              :   /// [userId] The id of the user to remove a tag for. The access token must be
    5483              :   /// authorized to make requests for this user ID.
    5484              :   ///
    5485              :   /// [roomId] The ID of the room to remove a tag from.
    5486              :   ///
    5487              :   /// [tag] The tag to remove.
    5488            2 :   Future<void> deleteRoomTag(String userId, String roomId, String tag) async {
    5489            2 :     final requestUri = Uri(
    5490              :       path:
    5491            8 :           '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/rooms/${Uri.encodeComponent(roomId)}/tags/${Uri.encodeComponent(tag)}',
    5492              :     );
    5493            6 :     final request = Request('DELETE', baseUri!.resolveUri(requestUri));
    5494            8 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5495            4 :     final response = await httpClient.send(request);
    5496            4 :     final responseBody = await response.stream.toBytes();
    5497            4 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5498            2 :     final responseString = utf8.decode(responseBody);
    5499            2 :     final json = jsonDecode(responseString);
    5500            2 :     return ignore(json);
    5501              :   }
    5502              : 
    5503              :   /// Add a tag to the room.
    5504              :   ///
    5505              :   /// [userId] The id of the user to add a tag for. The access token must be
    5506              :   /// authorized to make requests for this user ID.
    5507              :   ///
    5508              :   /// [roomId] The ID of the room to add a tag to.
    5509              :   ///
    5510              :   /// [tag] The tag to add.
    5511              :   ///
    5512              :   /// [body] Extra data for the tag, e.g. ordering.
    5513            2 :   Future<void> setRoomTag(
    5514              :     String userId,
    5515              :     String roomId,
    5516              :     String tag,
    5517              :     Tag body,
    5518              :   ) async {
    5519            2 :     final requestUri = Uri(
    5520              :       path:
    5521            8 :           '_matrix/client/v3/user/${Uri.encodeComponent(userId)}/rooms/${Uri.encodeComponent(roomId)}/tags/${Uri.encodeComponent(tag)}',
    5522              :     );
    5523            6 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    5524            8 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5525            4 :     request.headers['content-type'] = 'application/json';
    5526            8 :     request.bodyBytes = utf8.encode(jsonEncode(body.toJson()));
    5527            4 :     final response = await httpClient.send(request);
    5528            4 :     final responseBody = await response.stream.toBytes();
    5529            4 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5530            2 :     final responseString = utf8.decode(responseBody);
    5531            2 :     final json = jsonDecode(responseString);
    5532            2 :     return ignore(json);
    5533              :   }
    5534              : 
    5535              :   /// Performs a search for users. The homeserver may
    5536              :   /// determine which subset of users are searched, however the homeserver
    5537              :   /// MUST at a minimum consider the users the requesting user shares a
    5538              :   /// room with and those who reside in public rooms (known to the homeserver).
    5539              :   /// The search MUST consider local users to the homeserver, and SHOULD
    5540              :   /// query remote users as part of the search.
    5541              :   ///
    5542              :   /// The search is performed case-insensitively on user IDs and display
    5543              :   /// names preferably using a collation determined based upon the
    5544              :   /// `Accept-Language` header provided in the request, if present.
    5545              :   ///
    5546              :   /// [limit] The maximum number of results to return. Defaults to 10.
    5547              :   ///
    5548              :   /// [searchTerm] The term to search for
    5549            0 :   Future<SearchUserDirectoryResponse> searchUserDirectory(
    5550              :     String searchTerm, {
    5551              :     int? limit,
    5552              :   }) async {
    5553            0 :     final requestUri = Uri(path: '_matrix/client/v3/user_directory/search');
    5554            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    5555            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5556            0 :     request.headers['content-type'] = 'application/json';
    5557            0 :     request.bodyBytes = utf8.encode(
    5558            0 :       jsonEncode({
    5559            0 :         if (limit != null) 'limit': limit,
    5560            0 :         'search_term': searchTerm,
    5561              :       }),
    5562              :     );
    5563            0 :     final response = await httpClient.send(request);
    5564            0 :     final responseBody = await response.stream.toBytes();
    5565            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5566            0 :     final responseString = utf8.decode(responseBody);
    5567            0 :     final json = jsonDecode(responseString);
    5568            0 :     return SearchUserDirectoryResponse.fromJson(json as Map<String, Object?>);
    5569              :   }
    5570              : 
    5571              :   /// This API provides credentials for the client to use when initiating
    5572              :   /// calls.
    5573            0 :   Future<TurnServerCredentials> getTurnServer() async {
    5574            0 :     final requestUri = Uri(path: '_matrix/client/v3/voip/turnServer');
    5575            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5576            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    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            0 :     return TurnServerCredentials.fromJson(json as Map<String, Object?>);
    5583              :   }
    5584              : 
    5585              :   /// Gets the versions of the specification supported by the server.
    5586              :   ///
    5587              :   /// Values will take the form `vX.Y` or `rX.Y.Z` in historical cases. See
    5588              :   /// [the Specification Versioning](../#specification-versions) for more
    5589              :   /// information.
    5590              :   ///
    5591              :   /// The server may additionally advertise experimental features it supports
    5592              :   /// through `unstable_features`. These features should be namespaced and
    5593              :   /// may optionally include version information within their name if desired.
    5594              :   /// Features listed here are not for optionally toggling parts of the Matrix
    5595              :   /// specification and should only be used to advertise support for a feature
    5596              :   /// which has not yet landed in the spec. For example, a feature currently
    5597              :   /// undergoing the proposal process may appear here and eventually be taken
    5598              :   /// off this list once the feature lands in the spec and the server deems it
    5599              :   /// reasonable to do so. Servers can choose to enable some features only for
    5600              :   /// some users, so clients should include authentication in the request to
    5601              :   /// get all the features available for the logged-in user. If no
    5602              :   /// authentication is provided, the server should only return the features
    5603              :   /// available to all users. Servers may wish to keep advertising features
    5604              :   /// here after they've been released into the spec to give clients a chance
    5605              :   /// to upgrade appropriately. Additionally, clients should avoid using
    5606              :   /// unstable features in their stable releases.
    5607           35 :   Future<GetVersionsResponse> getVersions() async {
    5608           35 :     final requestUri = Uri(path: '_matrix/client/versions');
    5609          105 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5610           35 :     if (bearerToken != null) {
    5611           24 :       request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5612              :     }
    5613           70 :     final response = await httpClient.send(request);
    5614           70 :     final responseBody = await response.stream.toBytes();
    5615           71 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5616           35 :     final responseString = utf8.decode(responseBody);
    5617           35 :     final json = jsonDecode(responseString);
    5618           35 :     return GetVersionsResponse.fromJson(json as Map<String, Object?>);
    5619              :   }
    5620              : 
    5621              :   /// Creates a new `mxc://` URI, independently of the content being uploaded. The content must be provided later
    5622              :   /// via [`PUT /_matrix/media/v3/upload/{serverName}/{mediaId}`](https://spec.matrix.org/unstable/client-server-api/#put_matrixmediav3uploadservernamemediaid).
    5623              :   ///
    5624              :   /// The server may optionally enforce a maximum age for unused IDs,
    5625              :   /// and delete media IDs when the client doesn't start the upload in time,
    5626              :   /// or when the upload was interrupted and not resumed in time. The server
    5627              :   /// should include the maximum POSIX millisecond timestamp to complete the
    5628              :   /// upload in the `unused_expires_at` field in the response JSON. The
    5629              :   /// recommended default expiration is 24 hours which should be enough time
    5630              :   /// to accommodate users on poor connection who find a better connection to
    5631              :   /// complete the upload.
    5632              :   ///
    5633              :   /// As well as limiting the rate of requests to create `mxc://` URIs, the server
    5634              :   /// should limit the number of concurrent *pending media uploads* a given
    5635              :   /// user can have. A pending media upload is a created `mxc://` URI where (a)
    5636              :   /// the media has not yet been uploaded, and (b) has not yet expired (the
    5637              :   /// `unused_expires_at` timestamp has not yet passed). In both cases, the
    5638              :   /// server should respond with an HTTP 429 error with an errcode of
    5639              :   /// `M_LIMIT_EXCEEDED`.
    5640            0 :   Future<CreateContentResponse> createContent() async {
    5641            0 :     final requestUri = Uri(path: '_matrix/media/v1/create');
    5642            0 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    5643            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5644            0 :     final response = await httpClient.send(request);
    5645            0 :     final responseBody = await response.stream.toBytes();
    5646            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5647            0 :     final responseString = utf8.decode(responseBody);
    5648            0 :     final json = jsonDecode(responseString);
    5649            0 :     return CreateContentResponse.fromJson(json as Map<String, Object?>);
    5650              :   }
    5651              : 
    5652              :   /// {{% boxes/note %}}
    5653              :   /// Replaced by [`GET /_matrix/client/v1/media/config`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv1mediaconfig).
    5654              :   /// {{% /boxes/note %}}
    5655              :   ///
    5656              :   /// This endpoint allows clients to retrieve the configuration of the content
    5657              :   /// repository, such as upload limitations.
    5658              :   /// Clients SHOULD use this as a guide when using content repository endpoints.
    5659              :   /// All values are intentionally left optional. Clients SHOULD follow
    5660              :   /// the advice given in the field description when the field is not available.
    5661              :   ///
    5662              :   /// **NOTE:** Both clients and server administrators should be aware that proxies
    5663              :   /// between the client and the server may affect the apparent behaviour of content
    5664              :   /// repository APIs, for example, proxies may enforce a lower upload size limit
    5665              :   /// than is advertised by the server on this endpoint.
    5666            0 :   @deprecated
    5667              :   Future<MediaConfig> getConfig() async {
    5668            0 :     final requestUri = Uri(path: '_matrix/media/v3/config');
    5669            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5670            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5671            0 :     final response = await httpClient.send(request);
    5672            0 :     final responseBody = await response.stream.toBytes();
    5673            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5674            0 :     final responseString = utf8.decode(responseBody);
    5675            0 :     final json = jsonDecode(responseString);
    5676            0 :     return MediaConfig.fromJson(json as Map<String, Object?>);
    5677              :   }
    5678              : 
    5679              :   /// {{% boxes/note %}}
    5680              :   /// Replaced by [`GET /_matrix/client/v1/media/download/{serverName}/{mediaId}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv1mediadownloadservernamemediaid)
    5681              :   /// (requires authentication).
    5682              :   /// {{% /boxes/note %}}
    5683              :   ///
    5684              :   /// {{% boxes/warning %}}
    5685              :   /// {{% changed-in v="1.11" %}} This endpoint MAY return `404 M_NOT_FOUND`
    5686              :   /// for media which exists, but is after the server froze unauthenticated
    5687              :   /// media access. See [Client Behaviour](https://spec.matrix.org/unstable/client-server-api/#content-repo-client-behaviour) for more
    5688              :   /// information.
    5689              :   /// {{% /boxes/warning %}}
    5690              :   ///
    5691              :   /// [serverName] The server name from the `mxc://` URI (the authority component).
    5692              :   ///
    5693              :   ///
    5694              :   /// [mediaId] The media ID from the `mxc://` URI (the path component).
    5695              :   ///
    5696              :   ///
    5697              :   /// [allowRemote] Indicates to the server that it should not attempt to fetch the media if
    5698              :   /// it is deemed remote. This is to prevent routing loops where the server
    5699              :   /// contacts itself.
    5700              :   ///
    5701              :   /// Defaults to `true` if not provided.
    5702              :   ///
    5703              :   /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
    5704              :   /// start receiving data, in the case that the content has not yet been
    5705              :   /// uploaded. The default value is 20000 (20 seconds). The content
    5706              :   /// repository SHOULD impose a maximum value for this parameter. The
    5707              :   /// content repository MAY respond before the timeout.
    5708              :   ///
    5709              :   ///
    5710              :   /// [allowRedirect] Indicates to the server that it may return a 307 or 308 redirect
    5711              :   /// response that points at the relevant media content. When not explicitly
    5712              :   /// set to `true` the server must return the media content itself.
    5713              :   ///
    5714            0 :   @deprecated
    5715              :   Future<FileResponse> getContent(
    5716              :     String serverName,
    5717              :     String mediaId, {
    5718              :     bool? allowRemote,
    5719              :     int? timeoutMs,
    5720              :     bool? allowRedirect,
    5721              :   }) async {
    5722            0 :     final requestUri = Uri(
    5723              :       path:
    5724            0 :           '_matrix/media/v3/download/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}',
    5725            0 :       queryParameters: {
    5726            0 :         if (allowRemote != null) 'allow_remote': allowRemote.toString(),
    5727            0 :         if (timeoutMs != null) 'timeout_ms': timeoutMs.toString(),
    5728            0 :         if (allowRedirect != null) 'allow_redirect': allowRedirect.toString(),
    5729              :       },
    5730              :     );
    5731            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5732            0 :     final response = await httpClient.send(request);
    5733            0 :     final responseBody = await response.stream.toBytes();
    5734            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5735            0 :     return FileResponse(
    5736            0 :       contentType: response.headers['content-type'],
    5737              :       data: responseBody,
    5738              :     );
    5739              :   }
    5740              : 
    5741              :   /// {{% boxes/note %}}
    5742              :   /// Replaced by [`GET /_matrix/client/v1/media/download/{serverName}/{mediaId}/{fileName}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv1mediadownloadservernamemediaidfilename)
    5743              :   /// (requires authentication).
    5744              :   /// {{% /boxes/note %}}
    5745              :   ///
    5746              :   /// This will download content from the content repository (same as
    5747              :   /// the previous endpoint) but replace the target file name with the one
    5748              :   /// provided by the caller.
    5749              :   ///
    5750              :   /// {{% boxes/warning %}}
    5751              :   /// {{% changed-in v="1.11" %}} This endpoint MAY return `404 M_NOT_FOUND`
    5752              :   /// for media which exists, but is after the server froze unauthenticated
    5753              :   /// media access. See [Client Behaviour](https://spec.matrix.org/unstable/client-server-api/#content-repo-client-behaviour) for more
    5754              :   /// information.
    5755              :   /// {{% /boxes/warning %}}
    5756              :   ///
    5757              :   /// [serverName] The server name from the `mxc://` URI (the authority component).
    5758              :   ///
    5759              :   ///
    5760              :   /// [mediaId] The media ID from the `mxc://` URI (the path component).
    5761              :   ///
    5762              :   ///
    5763              :   /// [fileName] A filename to give in the `Content-Disposition` header.
    5764              :   ///
    5765              :   /// [allowRemote] Indicates to the server that it should not attempt to fetch the media if
    5766              :   /// it is deemed remote. This is to prevent routing loops where the server
    5767              :   /// contacts itself.
    5768              :   ///
    5769              :   /// Defaults to `true` if not provided.
    5770              :   ///
    5771              :   /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
    5772              :   /// start receiving data, in the case that the content has not yet been
    5773              :   /// uploaded. The default value is 20000 (20 seconds). The content
    5774              :   /// repository SHOULD impose a maximum value for this parameter. The
    5775              :   /// content repository MAY respond before the timeout.
    5776              :   ///
    5777              :   ///
    5778              :   /// [allowRedirect] Indicates to the server that it may return a 307 or 308 redirect
    5779              :   /// response that points at the relevant media content. When not explicitly
    5780              :   /// set to `true` the server must return the media content itself.
    5781              :   ///
    5782            0 :   @deprecated
    5783              :   Future<FileResponse> getContentOverrideName(
    5784              :     String serverName,
    5785              :     String mediaId,
    5786              :     String fileName, {
    5787              :     bool? allowRemote,
    5788              :     int? timeoutMs,
    5789              :     bool? allowRedirect,
    5790              :   }) async {
    5791            0 :     final requestUri = Uri(
    5792              :       path:
    5793            0 :           '_matrix/media/v3/download/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}/${Uri.encodeComponent(fileName)}',
    5794            0 :       queryParameters: {
    5795            0 :         if (allowRemote != null) 'allow_remote': allowRemote.toString(),
    5796            0 :         if (timeoutMs != null) 'timeout_ms': timeoutMs.toString(),
    5797            0 :         if (allowRedirect != null) 'allow_redirect': allowRedirect.toString(),
    5798              :       },
    5799              :     );
    5800            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5801            0 :     final response = await httpClient.send(request);
    5802            0 :     final responseBody = await response.stream.toBytes();
    5803            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5804            0 :     return FileResponse(
    5805            0 :       contentType: response.headers['content-type'],
    5806              :       data: responseBody,
    5807              :     );
    5808              :   }
    5809              : 
    5810              :   /// {{% boxes/note %}}
    5811              :   /// Replaced by [`GET /_matrix/client/v1/media/preview_url`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv1mediapreview_url).
    5812              :   /// {{% /boxes/note %}}
    5813              :   ///
    5814              :   /// Get information about a URL for the client. Typically this is called when a
    5815              :   /// client sees a URL in a message and wants to render a preview for the user.
    5816              :   ///
    5817              :   /// **Note:**
    5818              :   /// Clients should consider avoiding this endpoint for URLs posted in encrypted
    5819              :   /// rooms. Encrypted rooms often contain more sensitive information the users
    5820              :   /// do not want to share with the homeserver, and this can mean that the URLs
    5821              :   /// being shared should also not be shared with the homeserver.
    5822              :   ///
    5823              :   /// [url] The URL to get a preview of.
    5824              :   ///
    5825              :   /// [ts] The preferred point in time to return a preview for. The server may
    5826              :   /// return a newer version if it does not have the requested version
    5827              :   /// available.
    5828            0 :   @deprecated
    5829              :   Future<PreviewForUrl> getUrlPreview(Uri url, {int? ts}) async {
    5830            0 :     final requestUri = Uri(
    5831              :       path: '_matrix/media/v3/preview_url',
    5832            0 :       queryParameters: {
    5833            0 :         'url': url.toString(),
    5834            0 :         if (ts != null) 'ts': ts.toString(),
    5835              :       },
    5836              :     );
    5837            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5838            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5839            0 :     final response = await httpClient.send(request);
    5840            0 :     final responseBody = await response.stream.toBytes();
    5841            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5842            0 :     final responseString = utf8.decode(responseBody);
    5843            0 :     final json = jsonDecode(responseString);
    5844            0 :     return PreviewForUrl.fromJson(json as Map<String, Object?>);
    5845              :   }
    5846              : 
    5847              :   /// {{% boxes/note %}}
    5848              :   /// Replaced by [`GET /_matrix/client/v1/media/thumbnail/{serverName}/{mediaId}`](https://spec.matrix.org/unstable/client-server-api/#get_matrixclientv1mediathumbnailservernamemediaid)
    5849              :   /// (requires authentication).
    5850              :   /// {{% /boxes/note %}}
    5851              :   ///
    5852              :   /// Download a thumbnail of content from the content repository.
    5853              :   /// See the [Thumbnails](https://spec.matrix.org/unstable/client-server-api/#thumbnails) section for more information.
    5854              :   ///
    5855              :   /// {{% boxes/warning %}}
    5856              :   /// {{% changed-in v="1.11" %}} This endpoint MAY return `404 M_NOT_FOUND`
    5857              :   /// for media which exists, but is after the server froze unauthenticated
    5858              :   /// media access. See [Client Behaviour](https://spec.matrix.org/unstable/client-server-api/#content-repo-client-behaviour) for more
    5859              :   /// information.
    5860              :   /// {{% /boxes/warning %}}
    5861              :   ///
    5862              :   /// [serverName] The server name from the `mxc://` URI (the authority component).
    5863              :   ///
    5864              :   ///
    5865              :   /// [mediaId] The media ID from the `mxc://` URI (the path component).
    5866              :   ///
    5867              :   ///
    5868              :   /// [width] The *desired* width of the thumbnail. The actual thumbnail may be
    5869              :   /// larger than the size specified.
    5870              :   ///
    5871              :   /// [height] The *desired* height of the thumbnail. The actual thumbnail may be
    5872              :   /// larger than the size specified.
    5873              :   ///
    5874              :   /// [method] The desired resizing method. See the [Thumbnails](https://spec.matrix.org/unstable/client-server-api/#thumbnails)
    5875              :   /// section for more information.
    5876              :   ///
    5877              :   /// [allowRemote] Indicates to the server that it should not attempt to fetch the media if
    5878              :   /// it is deemed remote. This is to prevent routing loops where the server
    5879              :   /// contacts itself.
    5880              :   ///
    5881              :   /// Defaults to `true` if not provided.
    5882              :   ///
    5883              :   /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
    5884              :   /// start receiving data, in the case that the content has not yet been
    5885              :   /// uploaded. The default value is 20000 (20 seconds). The content
    5886              :   /// repository SHOULD impose a maximum value for this parameter. The
    5887              :   /// content repository MAY respond before the timeout.
    5888              :   ///
    5889              :   ///
    5890              :   /// [allowRedirect] Indicates to the server that it may return a 307 or 308 redirect
    5891              :   /// response that points at the relevant media content. When not explicitly
    5892              :   /// set to `true` the server must return the media content itself.
    5893              :   ///
    5894              :   ///
    5895              :   /// [animated] Indicates preference for an animated thumbnail from the server, if possible. Animated
    5896              :   /// thumbnails typically use the content types `image/gif`, `image/png` (with APNG format),
    5897              :   /// `image/apng`, and `image/webp` instead of the common static `image/png` or `image/jpeg`
    5898              :   /// content types.
    5899              :   ///
    5900              :   /// When `true`, the server SHOULD return an animated thumbnail if possible and supported.
    5901              :   /// When `false`, the server MUST NOT return an animated thumbnail. For example, returning a
    5902              :   /// static `image/png` or `image/jpeg` thumbnail. When not provided, the server SHOULD NOT
    5903              :   /// return an animated thumbnail.
    5904              :   ///
    5905              :   /// Servers SHOULD prefer to return `image/webp` thumbnails when supporting animation.
    5906              :   ///
    5907              :   /// When `true` and the media cannot be animated, such as in the case of a JPEG or PDF, the
    5908              :   /// server SHOULD behave as though `animated` is `false`.
    5909              :   ///
    5910            0 :   @deprecated
    5911              :   Future<FileResponse> getContentThumbnail(
    5912              :     String serverName,
    5913              :     String mediaId,
    5914              :     int width,
    5915              :     int height, {
    5916              :     Method? method,
    5917              :     bool? allowRemote,
    5918              :     int? timeoutMs,
    5919              :     bool? allowRedirect,
    5920              :     bool? animated,
    5921              :   }) async {
    5922            0 :     final requestUri = Uri(
    5923              :       path:
    5924            0 :           '_matrix/media/v3/thumbnail/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}',
    5925            0 :       queryParameters: {
    5926            0 :         'width': width.toString(),
    5927            0 :         'height': height.toString(),
    5928            0 :         if (method != null) 'method': method.name,
    5929            0 :         if (allowRemote != null) 'allow_remote': allowRemote.toString(),
    5930            0 :         if (timeoutMs != null) 'timeout_ms': timeoutMs.toString(),
    5931            0 :         if (allowRedirect != null) 'allow_redirect': allowRedirect.toString(),
    5932            0 :         if (animated != null) 'animated': animated.toString(),
    5933              :       },
    5934              :     );
    5935            0 :     final request = Request('GET', baseUri!.resolveUri(requestUri));
    5936            0 :     final response = await httpClient.send(request);
    5937            0 :     final responseBody = await response.stream.toBytes();
    5938            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5939            0 :     return FileResponse(
    5940            0 :       contentType: response.headers['content-type'],
    5941              :       data: responseBody,
    5942              :     );
    5943              :   }
    5944              : 
    5945              :   ///
    5946              :   ///
    5947              :   /// [filename] The name of the file being uploaded
    5948              :   ///
    5949              :   /// [body]
    5950              :   ///
    5951              :   /// [contentType] **Optional.** The content type of the file being uploaded.
    5952              :   ///
    5953              :   /// Clients SHOULD always supply this header.
    5954              :   ///
    5955              :   /// Defaults to `application/octet-stream` if it is not set.
    5956              :   ///
    5957              :   ///
    5958              :   /// returns `content_uri`:
    5959              :   /// The [`mxc://` URI](https://spec.matrix.org/unstable/client-server-api/#matrix-content-mxc-uris) to the uploaded content.
    5960            4 :   Future<Uri> uploadContent(
    5961              :     Uint8List body, {
    5962              :     String? filename,
    5963              :     String? contentType,
    5964              :   }) async {
    5965            4 :     final requestUri = Uri(
    5966              :       path: '_matrix/media/v3/upload',
    5967            4 :       queryParameters: {
    5968            4 :         if (filename != null) 'filename': filename,
    5969              :       },
    5970              :     );
    5971           12 :     final request = Request('POST', baseUri!.resolveUri(requestUri));
    5972           16 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    5973            8 :     if (contentType != null) request.headers['content-type'] = contentType;
    5974            4 :     request.bodyBytes = body;
    5975            8 :     final response = await httpClient.send(request);
    5976            8 :     final responseBody = await response.stream.toBytes();
    5977            8 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    5978            4 :     final responseString = utf8.decode(responseBody);
    5979            4 :     final json = jsonDecode(responseString);
    5980            8 :     return ((json['content_uri'] as String).startsWith('mxc://')
    5981            8 :         ? Uri.parse(json['content_uri'] as String)
    5982            0 :         : throw Exception('Uri not an mxc URI'));
    5983              :   }
    5984              : 
    5985              :   /// This endpoint permits uploading content to an `mxc://` URI that was created
    5986              :   /// earlier via [POST /_matrix/media/v1/create](https://spec.matrix.org/unstable/client-server-api/#post_matrixmediav1create).
    5987              :   ///
    5988              :   /// [serverName] The server name from the `mxc://` URI returned by `POST /_matrix/media/v1/create` (the authority component).
    5989              :   ///
    5990              :   ///
    5991              :   /// [mediaId] The media ID from the `mxc://` URI returned by `POST /_matrix/media/v1/create` (the path component).
    5992              :   ///
    5993              :   ///
    5994              :   /// [filename] The name of the file being uploaded
    5995              :   ///
    5996              :   /// [body]
    5997              :   ///
    5998              :   /// [contentType] **Optional.** The content type of the file being uploaded.
    5999              :   ///
    6000              :   /// Clients SHOULD always supply this header.
    6001              :   ///
    6002              :   /// Defaults to `application/octet-stream` if it is not set.
    6003              :   ///
    6004            0 :   Future<Map<String, Object?>> uploadContentToMXC(
    6005              :     String serverName,
    6006              :     String mediaId,
    6007              :     Uint8List body, {
    6008              :     String? filename,
    6009              :     String? contentType,
    6010              :   }) async {
    6011            0 :     final requestUri = Uri(
    6012              :       path:
    6013            0 :           '_matrix/media/v3/upload/${Uri.encodeComponent(serverName)}/${Uri.encodeComponent(mediaId)}',
    6014            0 :       queryParameters: {
    6015            0 :         if (filename != null) 'filename': filename,
    6016              :       },
    6017              :     );
    6018            0 :     final request = Request('PUT', baseUri!.resolveUri(requestUri));
    6019            0 :     request.headers['authorization'] = 'Bearer ${bearerToken!}';
    6020            0 :     if (contentType != null) request.headers['content-type'] = contentType;
    6021            0 :     request.bodyBytes = body;
    6022            0 :     final response = await httpClient.send(request);
    6023            0 :     final responseBody = await response.stream.toBytes();
    6024            0 :     if (response.statusCode != 200) unexpectedResponse(response, responseBody);
    6025            0 :     final responseString = utf8.decode(responseBody);
    6026            0 :     final json = jsonDecode(responseString);
    6027              :     return json as Map<String, Object?>;
    6028              :   }
    6029              : }
        

Generated by: LCOV version 2.0-1