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

Generated by: LCOV version 1.14