LCOV - code coverage report
Current view: top level - lib/matrix_api_lite - matrix_api.dart (source / functions) Hit Total Coverage
Test: merged.info Lines: 49 70 70.0 %
Date: 2024-05-13 12:56:47 Functions: 0 0 -

          Line data    Source code
       1             : /* MIT License
       2             : *
       3             : * Copyright (C) 2019, 2020, 2021 Famedly GmbH
       4             : *
       5             : * Permission is hereby granted, free of charge, to any person obtaining a copy
       6             : * of this software and associated documentation files (the "Software"), to deal
       7             : * in the Software without restriction, including without limitation the rights
       8             : * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
       9             : * copies of the Software, and to permit persons to whom the Software is
      10             : * furnished to do so, subject to the following conditions:
      11             : *
      12             : * The above copyright notice and this permission notice shall be included in all
      13             : * copies or substantial portions of the Software.
      14             : *
      15             : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      16             : * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      17             : * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      18             : * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      19             : * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      20             : * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      21             : * SOFTWARE.
      22             : */
      23             : 
      24             : import 'dart:async';
      25             : import 'dart:convert';
      26             : import 'dart:typed_data';
      27             : 
      28             : import 'package:http/http.dart' as http;
      29             : 
      30             : import 'package:matrix/matrix_api_lite.dart';
      31             : import 'package:matrix/matrix_api_lite/generated/api.dart';
      32             : 
      33             : // ignore: constant_identifier_names
      34             : enum RequestType { GET, POST, PUT, DELETE }
      35             : 
      36             : class MatrixApi extends Api {
      37             :   /// The homeserver this client is communicating with.
      38          66 :   Uri? get homeserver => baseUri;
      39             : 
      40          66 :   set homeserver(Uri? uri) => baseUri = uri;
      41             : 
      42             :   /// This is the access token for the matrix client. When it is undefined, then
      43             :   /// the user needs to sign in first.
      44          62 :   String? get accessToken => bearerToken;
      45             : 
      46          62 :   set accessToken(String? token) => bearerToken = token;
      47             : 
      48           3 :   @override
      49             :   Never unexpectedResponse(http.BaseResponse response, Uint8List body) {
      50          12 :     if (response.statusCode >= 400 && response.statusCode < 500) {
      51           6 :       final resp = json.decode(utf8.decode(body));
      52           3 :       if (resp is Map<String, Object?>) {
      53           3 :         throw MatrixException.fromJson(resp);
      54             :       }
      55             :     }
      56           1 :     super.unexpectedResponse(response, body);
      57             :   }
      58             : 
      59          38 :   MatrixApi({
      60             :     Uri? homeserver,
      61             :     String? accessToken,
      62             :     super.httpClient,
      63          38 :   }) : super(baseUri: homeserver, bearerToken: accessToken);
      64             : 
      65             :   /// Used for all Matrix json requests using the [c2s API](https://matrix.org/docs/spec/client_server/r0.6.0.html).
      66             :   ///
      67             :   /// Throws: FormatException, MatrixException
      68             :   ///
      69             :   /// You must first set [this.homeserver] and for some endpoints also
      70             :   /// [this.accessToken] before you can use this! For example to send a
      71             :   /// message to a Matrix room with the id '!fjd823j:example.com' you call:
      72             :   /// ```
      73             :   /// final resp = await request(
      74             :   ///   RequestType.PUT,
      75             :   ///   '/r0/rooms/!fjd823j:example.com/send/m.room.message/$txnId',
      76             :   ///   data: {
      77             :   ///     'msgtype': 'm.text',
      78             :   ///     'body': 'hello'
      79             :   ///   }
      80             :   ///  );
      81             :   /// ```
      82             :   ///
      83          26 :   Future<Map<String, Object?>> request(
      84             :     RequestType type,
      85             :     String action, {
      86             :     dynamic data = '',
      87             :     String contentType = 'application/json',
      88             :     Map<String, Object?>? query,
      89             :   }) async {
      90          26 :     if (homeserver == null) {
      91             :       throw ('No homeserver specified.');
      92             :     }
      93             :     dynamic json;
      94          51 :     (data is! String) ? json = jsonEncode(data) : json = data;
      95          52 :     if (data is List<int> || action.startsWith('/media/v3/upload')) json = data;
      96             : 
      97          26 :     final url = homeserver!
      98          78 :         .resolveUri(Uri(path: '_matrix$action', queryParameters: query));
      99             : 
     100          26 :     final headers = <String, String>{};
     101          52 :     if (type == RequestType.PUT || type == RequestType.POST) {
     102          25 :       headers['Content-Type'] = contentType;
     103             :     }
     104          26 :     if (accessToken != null) {
     105          78 :       headers['Authorization'] = 'Bearer $accessToken';
     106             :     }
     107             : 
     108             :     late http.Response resp;
     109          26 :     Map<String, Object?>? jsonResp = <String, Object?>{};
     110             :     try {
     111             :       switch (type) {
     112          26 :         case RequestType.GET:
     113           8 :           resp = await httpClient.get(url, headers: headers);
     114             :           break;
     115          25 :         case RequestType.POST:
     116          50 :           resp = await httpClient.post(url, body: json, headers: headers);
     117             :           break;
     118           2 :         case RequestType.PUT:
     119           4 :           resp = await httpClient.put(url, body: json, headers: headers);
     120             :           break;
     121           0 :         case RequestType.DELETE:
     122           0 :           resp = await httpClient.delete(url, headers: headers);
     123             :           break;
     124             :       }
     125          26 :       var respBody = resp.body;
     126             :       try {
     127          52 :         respBody = utf8.decode(resp.bodyBytes);
     128             :       } catch (_) {
     129             :         // No-OP
     130             :       }
     131          52 :       if (resp.statusCode >= 500 && resp.statusCode < 600) {
     132           0 :         throw Exception(respBody);
     133             :       }
     134          52 :       var jsonString = String.fromCharCodes(respBody.runes);
     135          26 :       if (jsonString.startsWith('[') && jsonString.endsWith(']')) {
     136           0 :         jsonString = '{"chunk":$jsonString}';
     137             :       }
     138          26 :       jsonResp = jsonDecode(jsonString)
     139             :           as Map<String, Object?>?; // May throw FormatException
     140             :     } catch (e, s) {
     141           0 :       throw MatrixConnectionException(e, s);
     142             :     }
     143          52 :     if (resp.statusCode >= 400 && resp.statusCode < 500) {
     144           0 :       throw MatrixException(resp);
     145             :     }
     146             : 
     147             :     return jsonResp!;
     148             :   }
     149             : 
     150             :   /// Publishes end-to-end encryption keys for the device.
     151             :   /// https://matrix.org/docs/spec/client_server/r0.6.1#post-matrix-client-r0-keys-query
     152          24 :   Future<Map<String, int>> uploadKeys(
     153             :       {MatrixDeviceKeys? deviceKeys,
     154             :       Map<String, Object?>? oneTimeKeys,
     155             :       Map<String, Object?>? fallbackKeys}) async {
     156          24 :     final response = await request(
     157             :       RequestType.POST,
     158             :       '/client/v3/keys/upload',
     159          24 :       data: {
     160          10 :         if (deviceKeys != null) 'device_keys': deviceKeys.toJson(),
     161          24 :         if (oneTimeKeys != null) 'one_time_keys': oneTimeKeys,
     162          24 :         if (fallbackKeys != null) ...{
     163             :           'fallback_keys': fallbackKeys,
     164             :           'org.matrix.msc2732.fallback_keys': fallbackKeys,
     165             :         },
     166             :       },
     167             :     );
     168          48 :     return Map<String, int>.from(response['one_time_key_counts'] as Map);
     169             :   }
     170             : 
     171             :   /// This endpoint allows the creation, modification and deletion of pushers
     172             :   /// for this user ID. The behaviour of this endpoint varies depending on the
     173             :   /// values in the JSON body.
     174             :   ///
     175             :   /// See [deletePusher] to issue requests with `kind: null`.
     176             :   ///
     177             :   /// https://matrix.org/docs/spec/client_server/r0.6.1#post-matrix-client-r0-pushers-set
     178           0 :   Future<void> postPusher(Pusher pusher, {bool? append}) async {
     179           0 :     final data = pusher.toJson();
     180             :     if (append != null) {
     181           0 :       data['append'] = append;
     182             :     }
     183           0 :     await request(
     184             :       RequestType.POST,
     185             :       '/client/v3/pushers/set',
     186             :       data: data,
     187             :     );
     188             :     return;
     189             :   }
     190             : 
     191             :   /// Variant of postPusher operation that deletes pushers by setting `kind: null`.
     192             :   ///
     193             :   /// https://matrix.org/docs/spec/client_server/r0.6.1#post-matrix-client-r0-pushers-set
     194           0 :   Future<void> deletePusher(PusherId pusher) async {
     195           0 :     final data = PusherData.fromJson(pusher.toJson()).toJson();
     196           0 :     data['kind'] = null;
     197           0 :     await request(
     198             :       RequestType.POST,
     199             :       '/client/v3/pushers/set',
     200             :       data: data,
     201             :     );
     202             :     return;
     203             :   }
     204             : 
     205             :   /// This API provides credentials for the client to use when initiating
     206             :   /// calls.
     207           2 :   @override
     208             :   Future<TurnServerCredentials> getTurnServer() async {
     209           2 :     final json = await request(RequestType.GET, '/client/v3/voip/turnServer');
     210             : 
     211             :     // fix invalid responses from synapse
     212             :     // https://github.com/matrix-org/synapse/pull/10922
     213           2 :     final ttl = json['ttl'];
     214           2 :     if (ttl is double) {
     215           0 :       json['ttl'] = ttl.toInt();
     216             :     }
     217             : 
     218           2 :     return TurnServerCredentials.fromJson(json);
     219             :   }
     220             : 
     221           0 :   @Deprecated('Use [deleteRoomKeyBySessionId] instead')
     222             :   Future<RoomKeysUpdateResponse> deleteRoomKeysBySessionId(
     223             :       String roomId, String sessionId, String version) async {
     224           0 :     return deleteRoomKeyBySessionId(roomId, sessionId, version);
     225             :   }
     226             : 
     227           0 :   @Deprecated('Use [deleteRoomKeyBySessionId] instead')
     228             :   Future<RoomKeysUpdateResponse> putRoomKeysBySessionId(String roomId,
     229             :       String sessionId, String version, KeyBackupData data) async {
     230           0 :     return putRoomKeyBySessionId(roomId, sessionId, version, data);
     231             :   }
     232             : 
     233           0 :   @Deprecated('Use [getRoomKeyBySessionId] instead')
     234             :   Future<KeyBackupData> getRoomKeysBySessionId(
     235             :       String roomId, String sessionId, String version) async {
     236           0 :     return getRoomKeyBySessionId(roomId, sessionId, version);
     237             :   }
     238             : }

Generated by: LCOV version 1.14