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

Generated by: LCOV version 1.14