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

Generated by: LCOV version 1.14