LCOV - code coverage report
Current view: top level - lib/src - client.dart (source / functions) Hit Total Coverage
Test: merged.info Lines: 1060 1392 76.1 %
Date: 2024-09-27 11:38:01 Functions: 0 0 -

          Line data    Source code
       1             : /*
       2             :  *   Famedly Matrix SDK
       3             :  *   Copyright (C) 2019, 2020, 2021 Famedly GmbH
       4             :  *
       5             :  *   This program is free software: you can redistribute it and/or modify
       6             :  *   it under the terms of the GNU Affero General Public License as
       7             :  *   published by the Free Software Foundation, either version 3 of the
       8             :  *   License, or (at your option) any later version.
       9             :  *
      10             :  *   This program is distributed in the hope that it will be useful,
      11             :  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
      12             :  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
      13             :  *   GNU Affero General Public License for more details.
      14             :  *
      15             :  *   You should have received a copy of the GNU Affero General Public License
      16             :  *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
      17             :  */
      18             : 
      19             : import 'dart:async';
      20             : import 'dart:convert';
      21             : import 'dart:core';
      22             : import 'dart:math';
      23             : import 'dart:typed_data';
      24             : 
      25             : import 'package:async/async.dart';
      26             : import 'package:collection/collection.dart' show IterableExtension;
      27             : import 'package:http/http.dart' as http;
      28             : import 'package:mime/mime.dart';
      29             : import 'package:olm/olm.dart' as olm;
      30             : import 'package:random_string/random_string.dart';
      31             : 
      32             : import 'package:matrix/encryption.dart';
      33             : import 'package:matrix/matrix.dart';
      34             : import 'package:matrix/matrix_api_lite/generated/fixed_model.dart';
      35             : import 'package:matrix/msc_extensions/msc_unpublished_custom_refresh_token_lifetime/msc_unpublished_custom_refresh_token_lifetime.dart';
      36             : import 'package:matrix/src/models/timeline_chunk.dart';
      37             : import 'package:matrix/src/utils/cached_stream_controller.dart';
      38             : import 'package:matrix/src/utils/client_init_exception.dart';
      39             : import 'package:matrix/src/utils/compute_callback.dart';
      40             : import 'package:matrix/src/utils/multilock.dart';
      41             : import 'package:matrix/src/utils/run_benchmarked.dart';
      42             : import 'package:matrix/src/utils/run_in_root.dart';
      43             : import 'package:matrix/src/utils/sync_update_item_count.dart';
      44             : import 'package:matrix/src/utils/try_get_push_rule.dart';
      45             : import 'package:matrix/src/utils/versions_comparator.dart';
      46             : 
      47             : typedef RoomSorter = int Function(Room a, Room b);
      48             : 
      49             : enum LoginState { loggedIn, loggedOut, softLoggedOut }
      50             : 
      51             : extension TrailingSlash on Uri {
      52         102 :   Uri stripTrailingSlash() => path.endsWith('/')
      53           0 :       ? replace(path: path.substring(0, path.length - 1))
      54             :       : this;
      55             : }
      56             : 
      57             : /// Represents a Matrix client to communicate with a
      58             : /// [Matrix](https://matrix.org) homeserver and is the entry point for this
      59             : /// SDK.
      60             : class Client extends MatrixApi {
      61             :   int? _id;
      62             : 
      63             :   // Keeps track of the currently ongoing syncRequest
      64             :   // in case we want to cancel it.
      65             :   int _currentSyncId = -1;
      66             : 
      67          60 :   int? get id => _id;
      68             : 
      69             :   final FutureOr<DatabaseApi> Function(Client)? databaseBuilder;
      70             :   final FutureOr<DatabaseApi> Function(Client)? legacyDatabaseBuilder;
      71             :   DatabaseApi? _database;
      72             : 
      73          72 :   DatabaseApi? get database => _database;
      74             : 
      75          64 :   Encryption? get encryption => _encryption;
      76             :   Encryption? _encryption;
      77             : 
      78             :   Set<KeyVerificationMethod> verificationMethods;
      79             : 
      80             :   Set<String> importantStateEvents;
      81             : 
      82             :   Set<String> roomPreviewLastEvents;
      83             : 
      84             :   Set<String> supportedLoginTypes;
      85             : 
      86             :   bool requestHistoryOnLimitedTimeline;
      87             : 
      88             :   final bool formatLocalpart;
      89             : 
      90             :   final bool mxidLocalPartFallback;
      91             : 
      92             :   bool shareKeysWithUnverifiedDevices;
      93             : 
      94             :   Future<void> Function(Client client)? onSoftLogout;
      95             : 
      96          64 :   DateTime? get accessTokenExpiresAt => _accessTokenExpiresAt;
      97             :   DateTime? _accessTokenExpiresAt;
      98             : 
      99             :   // For CommandsClientExtension
     100             :   final Map<String, FutureOr<String?> Function(CommandArgs)> commands = {};
     101             :   final Filter syncFilter;
     102             : 
     103             :   final NativeImplementations nativeImplementations;
     104             : 
     105             :   String? _syncFilterId;
     106             : 
     107          64 :   String? get syncFilterId => _syncFilterId;
     108             : 
     109             :   final ComputeCallback? compute;
     110             : 
     111           0 :   @Deprecated('Use [nativeImplementations] instead')
     112             :   Future<T> runInBackground<T, U>(
     113             :       FutureOr<T> Function(U arg) function, U arg) async {
     114           0 :     final compute = this.compute;
     115             :     if (compute != null) {
     116           0 :       return await compute(function, arg);
     117             :     }
     118           0 :     return await function(arg);
     119             :   }
     120             : 
     121             :   final Duration sendTimelineEventTimeout;
     122             : 
     123             :   /// The timeout until a typing indicator gets removed automatically.
     124             :   final Duration typingIndicatorTimeout;
     125             : 
     126             :   DiscoveryInformation? _wellKnown;
     127             : 
     128             :   /// the cached .well-known file updated using [getWellknown]
     129           2 :   DiscoveryInformation? get wellKnown => _wellKnown;
     130             : 
     131             :   /// The homeserver this client is communicating with.
     132             :   ///
     133             :   /// In case the [homeserver]'s host differs from the previous value, the
     134             :   /// [wellKnown] cache will be invalidated.
     135          34 :   @override
     136             :   set homeserver(Uri? homeserver) {
     137         136 :     if (homeserver?.host != this.homeserver?.host) {
     138          34 :       _wellKnown = null;
     139          69 :       unawaited(database?.storeWellKnown(null));
     140             :     }
     141          34 :     super.homeserver = homeserver;
     142             :   }
     143             : 
     144             :   Future<MatrixImageFileResizedResponse?> Function(
     145             :       MatrixImageFileResizeArguments)? customImageResizer;
     146             : 
     147             :   /// Create a client
     148             :   /// [clientName] = unique identifier of this client
     149             :   /// [databaseBuilder]: A function that creates the database instance, that will be used.
     150             :   /// [legacyDatabaseBuilder]: Use this for your old database implementation to perform an automatic migration
     151             :   /// [databaseDestroyer]: A function that can be used to destroy a database instance, for example by deleting files from disk.
     152             :   /// [verificationMethods]: A set of all the verification methods this client can handle. Includes:
     153             :   ///    KeyVerificationMethod.numbers: Compare numbers. Most basic, should be supported
     154             :   ///    KeyVerificationMethod.emoji: Compare emojis
     155             :   /// [importantStateEvents]: A set of all the important state events to load when the client connects.
     156             :   ///    To speed up performance only a set of state events is loaded on startup, those that are
     157             :   ///    needed to display a room list. All the remaining state events are automatically post-loaded
     158             :   ///    when opening the timeline of a room or manually by calling `room.postLoad()`.
     159             :   ///    This set will always include the following state events:
     160             :   ///     - m.room.name
     161             :   ///     - m.room.avatar
     162             :   ///     - m.room.message
     163             :   ///     - m.room.encrypted
     164             :   ///     - m.room.encryption
     165             :   ///     - m.room.canonical_alias
     166             :   ///     - m.room.tombstone
     167             :   ///     - *some* m.room.member events, where needed
     168             :   /// [roomPreviewLastEvents]: The event types that should be used to calculate the last event
     169             :   ///     in a room for the room list.
     170             :   /// Set [requestHistoryOnLimitedTimeline] to controll the automatic behaviour if the client
     171             :   /// receives a limited timeline flag for a room.
     172             :   /// If [mxidLocalPartFallback] is true, then the local part of the mxid will be shown
     173             :   /// if there is no other displayname available. If not then this will return "Unknown user".
     174             :   /// If [formatLocalpart] is true, then the localpart of an mxid will
     175             :   /// be formatted in the way, that all "_" characters are becomming white spaces and
     176             :   /// the first character of each word becomes uppercase.
     177             :   /// If your client supports more login types like login with token or SSO, then add this to
     178             :   /// [supportedLoginTypes]. Set a custom [syncFilter] if you like. By default the app
     179             :   /// will use lazy_load_members.
     180             :   /// Set [nativeImplementations] to [NativeImplementationsIsolate] in order to
     181             :   /// enable the SDK to compute some code in background.
     182             :   /// Set [timelineEventTimeout] to the preferred time the Client should retry
     183             :   /// sending events on connection problems or to `Duration.zero` to disable it.
     184             :   /// Set [customImageResizer] to your own implementation for a more advanced
     185             :   /// and faster image resizing experience.
     186             :   /// Set [enableDehydratedDevices] to enable experimental support for enabling MSC3814 dehydrated devices.
     187          39 :   Client(
     188             :     this.clientName, {
     189             :     this.databaseBuilder,
     190             :     this.legacyDatabaseBuilder,
     191             :     Set<KeyVerificationMethod>? verificationMethods,
     192             :     http.Client? httpClient,
     193             :     Set<String>? importantStateEvents,
     194             : 
     195             :     /// You probably don't want to add state events which are also
     196             :     /// in important state events to this list, or get ready to face
     197             :     /// only having one event of that particular type in preLoad because
     198             :     /// previewEvents are stored with stateKey '' not the actual state key
     199             :     /// of your state event
     200             :     Set<String>? roomPreviewLastEvents,
     201             :     this.pinUnreadRooms = false,
     202             :     this.pinInvitedRooms = true,
     203             :     @Deprecated('Use [sendTimelineEventTimeout] instead.')
     204             :     int? sendMessageTimeoutSeconds,
     205             :     this.requestHistoryOnLimitedTimeline = false,
     206             :     Set<String>? supportedLoginTypes,
     207             :     this.mxidLocalPartFallback = true,
     208             :     this.formatLocalpart = true,
     209             :     @Deprecated('Use [nativeImplementations] instead') this.compute,
     210             :     NativeImplementations nativeImplementations = NativeImplementations.dummy,
     211             :     Level? logLevel,
     212             :     Filter? syncFilter,
     213             :     Duration defaultNetworkRequestTimeout = const Duration(seconds: 35),
     214             :     this.sendTimelineEventTimeout = const Duration(minutes: 1),
     215             :     this.customImageResizer,
     216             :     this.shareKeysWithUnverifiedDevices = true,
     217             :     this.enableDehydratedDevices = false,
     218             :     this.receiptsPublicByDefault = true,
     219             : 
     220             :     /// Implement your https://spec.matrix.org/v1.9/client-server-api/#soft-logout
     221             :     /// logic here.
     222             :     /// Set this to `refreshAccessToken()` for the easiest way to handle the
     223             :     /// most common reason for soft logouts.
     224             :     /// You can also perform a new login here by passing the existing deviceId.
     225             :     this.onSoftLogout,
     226             : 
     227             :     /// Experimental feature which allows to send a custom refresh token
     228             :     /// lifetime to the server which overrides the default one. Needs server
     229             :     /// support.
     230             :     this.customRefreshTokenLifetime,
     231             :     this.typingIndicatorTimeout = const Duration(seconds: 30),
     232             :   })  : syncFilter = syncFilter ??
     233          39 :             Filter(
     234          39 :               room: RoomFilter(
     235          39 :                 state: StateFilter(lazyLoadMembers: true),
     236             :               ),
     237             :             ),
     238             :         importantStateEvents = importantStateEvents ??= {},
     239             :         roomPreviewLastEvents = roomPreviewLastEvents ??= {},
     240             :         supportedLoginTypes =
     241          39 :             supportedLoginTypes ?? {AuthenticationTypes.password},
     242             :         verificationMethods = verificationMethods ?? <KeyVerificationMethod>{},
     243             :         nativeImplementations = compute != null
     244           0 :             ? NativeImplementationsIsolate(compute)
     245             :             : nativeImplementations,
     246          39 :         super(
     247          39 :             httpClient: FixedTimeoutHttpClient(
     248           5 :                 httpClient ?? http.Client(), defaultNetworkRequestTimeout)) {
     249          60 :     if (logLevel != null) Logs().level = logLevel;
     250          78 :     importantStateEvents.addAll([
     251             :       EventTypes.RoomName,
     252             :       EventTypes.RoomAvatar,
     253             :       EventTypes.Encryption,
     254             :       EventTypes.RoomCanonicalAlias,
     255             :       EventTypes.RoomTombstone,
     256             :       EventTypes.SpaceChild,
     257             :       EventTypes.SpaceParent,
     258             :       EventTypes.RoomCreate,
     259             :     ]);
     260          78 :     roomPreviewLastEvents.addAll([
     261             :       EventTypes.Message,
     262             :       EventTypes.Encrypted,
     263             :       EventTypes.Sticker,
     264             :       EventTypes.CallInvite,
     265             :       EventTypes.CallAnswer,
     266             :       EventTypes.CallReject,
     267             :       EventTypes.CallHangup,
     268             :       EventTypes.GroupCallMember,
     269             :     ]);
     270             : 
     271             :     // register all the default commands
     272          39 :     registerDefaultCommands();
     273             :   }
     274             : 
     275             :   Duration? customRefreshTokenLifetime;
     276             : 
     277             :   /// Fetches the refreshToken from the database and tries to get a new
     278             :   /// access token from the server and then stores it correctly. Unlike the
     279             :   /// pure API call of `Client.refresh()` this handles the complete soft
     280             :   /// logout case.
     281             :   /// Throws an Exception if there is no refresh token available or the
     282             :   /// client is not logged in.
     283           1 :   Future<void> refreshAccessToken() async {
     284           3 :     final storedClient = await database?.getClient(clientName);
     285           1 :     final refreshToken = storedClient?.tryGet<String>('refresh_token');
     286             :     if (refreshToken == null) {
     287           0 :       throw Exception('No refresh token available');
     288             :     }
     289           2 :     final homeserverUrl = homeserver?.toString();
     290           1 :     final userId = userID;
     291           1 :     final deviceId = deviceID;
     292             :     if (homeserverUrl == null || userId == null || deviceId == null) {
     293           0 :       throw Exception('Cannot refresh access token when not logged in');
     294             :     }
     295             : 
     296           1 :     final tokenResponse = await refreshWithCustomRefreshTokenLifetime(
     297             :       refreshToken,
     298           1 :       refreshTokenLifetimeMs: customRefreshTokenLifetime?.inMilliseconds,
     299             :     );
     300             : 
     301           2 :     accessToken = tokenResponse.accessToken;
     302           1 :     final expiresInMs = tokenResponse.expiresInMs;
     303             :     final tokenExpiresAt = expiresInMs == null
     304             :         ? null
     305           3 :         : DateTime.now().add(Duration(milliseconds: expiresInMs));
     306           1 :     _accessTokenExpiresAt = tokenExpiresAt;
     307           2 :     await database?.updateClient(
     308             :       homeserverUrl,
     309           1 :       tokenResponse.accessToken,
     310             :       tokenExpiresAt,
     311           1 :       tokenResponse.refreshToken,
     312             :       userId,
     313             :       deviceId,
     314           1 :       deviceName,
     315           1 :       prevBatch,
     316           2 :       encryption?.pickledOlmAccount,
     317             :     );
     318             :   }
     319             : 
     320             :   /// The required name for this client.
     321             :   final String clientName;
     322             : 
     323             :   /// The Matrix ID of the current logged user.
     324          66 :   String? get userID => _userID;
     325             :   String? _userID;
     326             : 
     327             :   /// This points to the position in the synchronization history.
     328          64 :   String? get prevBatch => _prevBatch;
     329             :   String? _prevBatch;
     330             : 
     331             :   /// The device ID is an unique identifier for this device.
     332          62 :   String? get deviceID => _deviceID;
     333             :   String? _deviceID;
     334             : 
     335             :   /// The device name is a human readable identifier for this device.
     336           2 :   String? get deviceName => _deviceName;
     337             :   String? _deviceName;
     338             : 
     339             :   // for group calls
     340             :   // A unique identifier used for resolving duplicate group call
     341             :   // sessions from a given device. When the session_id field changes from
     342             :   // an incoming m.call.member event, any existing calls from this device in
     343             :   // this call should be terminated. The id is generated once per client load.
     344           0 :   String? get groupCallSessionId => _groupCallSessionId;
     345             :   String? _groupCallSessionId;
     346             : 
     347             :   /// Returns the current login state.
     348           0 :   @Deprecated('Use [onLoginStateChanged.value] instead')
     349             :   LoginState get loginState =>
     350           0 :       onLoginStateChanged.value ?? LoginState.loggedOut;
     351             : 
     352          64 :   bool isLogged() => accessToken != null;
     353             : 
     354             :   /// A list of all rooms the user is participating or invited.
     355          70 :   List<Room> get rooms => _rooms;
     356             :   List<Room> _rooms = [];
     357             : 
     358             :   /// Get a list of the archived rooms
     359             :   ///
     360             :   /// Attention! Archived rooms are only returned if [loadArchive()] was called
     361             :   /// beforehand! The state refers to the last retrieval via [loadArchive()]!
     362           2 :   List<ArchivedRoom> get archivedRooms => _archivedRooms;
     363             : 
     364             :   bool enableDehydratedDevices = false;
     365             : 
     366             :   /// Whether read receipts are sent as public receipts by default or just as private receipts.
     367             :   bool receiptsPublicByDefault = true;
     368             : 
     369             :   /// Whether this client supports end-to-end encryption using olm.
     370         120 :   bool get encryptionEnabled => encryption?.enabled == true;
     371             : 
     372             :   /// Whether this client is able to encrypt and decrypt files.
     373           0 :   bool get fileEncryptionEnabled => encryptionEnabled;
     374             : 
     375          18 :   String get identityKey => encryption?.identityKey ?? '';
     376             : 
     377          83 :   String get fingerprintKey => encryption?.fingerprintKey ?? '';
     378             : 
     379             :   /// Whether this session is unknown to others
     380          24 :   bool get isUnknownSession =>
     381         136 :       userDeviceKeys[userID]?.deviceKeys[deviceID]?.signed != true;
     382             : 
     383             :   /// Warning! This endpoint is for testing only!
     384           0 :   set rooms(List<Room> newList) {
     385           0 :     Logs().w('Warning! This endpoint is for testing only!');
     386           0 :     _rooms = newList;
     387             :   }
     388             : 
     389             :   /// Key/Value store of account data.
     390             :   Map<String, BasicEvent> _accountData = {};
     391             : 
     392          64 :   Map<String, BasicEvent> get accountData => _accountData;
     393             : 
     394             :   /// Evaluate if an event should notify quickly
     395           0 :   PushruleEvaluator get pushruleEvaluator =>
     396           0 :       _pushruleEvaluator ?? PushruleEvaluator.fromRuleset(PushRuleSet());
     397             :   PushruleEvaluator? _pushruleEvaluator;
     398             : 
     399          32 :   void _updatePushrules() {
     400          32 :     final ruleset = TryGetPushRule.tryFromJson(
     401          64 :         _accountData[EventTypes.PushRules]
     402          32 :                 ?.content
     403          32 :                 .tryGetMap<String, Object?>('global') ??
     404          30 :             {});
     405          64 :     _pushruleEvaluator = PushruleEvaluator.fromRuleset(ruleset);
     406             :   }
     407             : 
     408             :   /// Presences of users by a given matrix ID
     409             :   @Deprecated('Use `fetchCurrentPresence(userId)` instead.')
     410             :   Map<String, CachedPresence> presences = {};
     411             : 
     412             :   int _transactionCounter = 0;
     413             : 
     414          12 :   String generateUniqueTransactionId() {
     415          24 :     _transactionCounter++;
     416          60 :     return '$clientName-$_transactionCounter-${DateTime.now().millisecondsSinceEpoch}';
     417             :   }
     418             : 
     419           1 :   Room? getRoomByAlias(String alias) {
     420           2 :     for (final room in rooms) {
     421           2 :       if (room.canonicalAlias == alias) return room;
     422             :     }
     423             :     return null;
     424             :   }
     425             : 
     426             :   /// Searches in the local cache for the given room and returns null if not
     427             :   /// found. If you have loaded the [loadArchive()] before, it can also return
     428             :   /// archived rooms.
     429          33 :   Room? getRoomById(String id) {
     430         166 :     for (final room in <Room>[...rooms, ..._archivedRooms.map((e) => e.room)]) {
     431          60 :       if (room.id == id) return room;
     432             :     }
     433             : 
     434             :     return null;
     435             :   }
     436             : 
     437          33 :   Map<String, dynamic> get directChats =>
     438         114 :       _accountData['m.direct']?.content ?? {};
     439             : 
     440             :   /// Returns the (first) room ID from the store which is a private chat with the user [userId].
     441             :   /// Returns null if there is none.
     442           6 :   String? getDirectChatFromUserId(String userId) {
     443          24 :     final directChats = _accountData['m.direct']?.content[userId];
     444           7 :     if (directChats is List<dynamic> && directChats.isNotEmpty) {
     445             :       final potentialRooms = directChats
     446           1 :           .cast<String>()
     447           2 :           .map(getRoomById)
     448           4 :           .where((room) => room != null && room.membership == Membership.join);
     449           1 :       if (potentialRooms.isNotEmpty) {
     450           2 :         return potentialRooms.fold<Room>(potentialRooms.first!,
     451           1 :             (Room prev, Room? r) {
     452             :           if (r == null) {
     453             :             return prev;
     454             :           }
     455           2 :           final prevLast = prev.lastEvent?.originServerTs ?? DateTime(0);
     456           2 :           final rLast = r.lastEvent?.originServerTs ?? DateTime(0);
     457             : 
     458           1 :           return rLast.isAfter(prevLast) ? r : prev;
     459           1 :         }).id;
     460             :       }
     461             :     }
     462          10 :     for (final room in rooms) {
     463           8 :       if (room.membership == Membership.invite &&
     464          12 :           room.getState(EventTypes.RoomMember, userID!)?.senderId == userId &&
     465           0 :           room.getState(EventTypes.RoomMember, userID!)?.content['is_direct'] ==
     466             :               true) {
     467           0 :         return room.id;
     468             :       }
     469             :     }
     470             :     return null;
     471             :   }
     472             : 
     473             :   /// Gets discovery information about the domain. The file may include additional keys.
     474           0 :   Future<DiscoveryInformation> getDiscoveryInformationsByUserId(
     475             :     String MatrixIdOrDomain,
     476             :   ) async {
     477             :     try {
     478           0 :       final response = await httpClient.get(Uri.https(
     479           0 :           MatrixIdOrDomain.domain ?? '', '/.well-known/matrix/client'));
     480           0 :       var respBody = response.body;
     481             :       try {
     482           0 :         respBody = utf8.decode(response.bodyBytes);
     483             :       } catch (_) {
     484             :         // No-OP
     485             :       }
     486           0 :       final rawJson = json.decode(respBody);
     487           0 :       return DiscoveryInformation.fromJson(rawJson);
     488             :     } catch (_) {
     489             :       // we got an error processing or fetching the well-known information, let's
     490             :       // provide a reasonable fallback.
     491           0 :       return DiscoveryInformation(
     492           0 :         mHomeserver: HomeserverInformation(
     493           0 :             baseUrl: Uri.https(MatrixIdOrDomain.domain ?? '', '')),
     494             :       );
     495             :     }
     496             :   }
     497             : 
     498             :   /// Checks the supported versions of the Matrix protocol and the supported
     499             :   /// login types. Throws an exception if the server is not compatible with the
     500             :   /// client and sets [homeserver] to [homeserverUrl] if it is. Supports the
     501             :   /// types `Uri` and `String`.
     502          34 :   Future<
     503             :       (
     504             :         DiscoveryInformation?,
     505             :         GetVersionsResponse versions,
     506             :         List<LoginFlow>,
     507             :       )> checkHomeserver(
     508             :     Uri homeserverUrl, {
     509             :     bool checkWellKnown = true,
     510             :     Set<String>? overrideSupportedVersions,
     511             :   }) async {
     512             :     final supportedVersions =
     513             :         overrideSupportedVersions ?? Client.supportedVersions;
     514             :     try {
     515          68 :       homeserver = homeserverUrl.stripTrailingSlash();
     516             : 
     517             :       // Look up well known
     518             :       DiscoveryInformation? wellKnown;
     519             :       if (checkWellKnown) {
     520             :         try {
     521           1 :           wellKnown = await getWellknown();
     522           4 :           homeserver = wellKnown.mHomeserver.baseUrl.stripTrailingSlash();
     523             :         } catch (e) {
     524           2 :           Logs().v('Found no well known information', e);
     525             :         }
     526             :       }
     527             : 
     528             :       // Check if server supports at least one supported version
     529          34 :       final versions = await getVersions();
     530          34 :       if (!versions.versions
     531         102 :           .any((version) => supportedVersions.contains(version))) {
     532           0 :         throw BadServerVersionsException(
     533           0 :           versions.versions.toSet(),
     534             :           supportedVersions,
     535             :         );
     536             :       }
     537             : 
     538          34 :       final loginTypes = await getLoginFlows() ?? [];
     539         170 :       if (!loginTypes.any((f) => supportedLoginTypes.contains(f.type))) {
     540           0 :         throw BadServerLoginTypesException(
     541           0 :             loginTypes.map((f) => f.type).toSet(), supportedLoginTypes);
     542             :       }
     543             : 
     544             :       return (wellKnown, versions, loginTypes);
     545             :     } catch (_) {
     546           1 :       homeserver = null;
     547             :       rethrow;
     548             :     }
     549             :   }
     550             : 
     551             :   /// Gets discovery information about the domain. The file may include
     552             :   /// additional keys, which MUST follow the Java package naming convention,
     553             :   /// e.g. `com.example.myapp.property`. This ensures property names are
     554             :   /// suitably namespaced for each application and reduces the risk of
     555             :   /// clashes.
     556             :   ///
     557             :   /// Note that this endpoint is not necessarily handled by the homeserver,
     558             :   /// but by another webserver, to be used for discovering the homeserver URL.
     559             :   ///
     560             :   /// The result of this call is stored in [wellKnown] for later use at runtime.
     561           1 :   @override
     562             :   Future<DiscoveryInformation> getWellknown() async {
     563           1 :     final wellKnown = await super.getWellknown();
     564             : 
     565             :     // do not reset the well known here, so super call
     566           4 :     super.homeserver = wellKnown.mHomeserver.baseUrl.stripTrailingSlash();
     567           1 :     _wellKnown = wellKnown;
     568           2 :     await database?.storeWellKnown(wellKnown);
     569             :     return wellKnown;
     570             :   }
     571             : 
     572             :   /// Checks to see if a username is available, and valid, for the server.
     573             :   /// Returns the fully-qualified Matrix user ID (MXID) that has been registered.
     574             :   /// You have to call [checkHomeserver] first to set a homeserver.
     575           0 :   @override
     576             :   Future<RegisterResponse> register({
     577             :     String? username,
     578             :     String? password,
     579             :     String? deviceId,
     580             :     String? initialDeviceDisplayName,
     581             :     bool? inhibitLogin,
     582             :     bool? refreshToken,
     583             :     AuthenticationData? auth,
     584             :     AccountKind? kind,
     585             :   }) async {
     586           0 :     final response = await super.register(
     587             :       kind: kind,
     588             :       username: username,
     589             :       password: password,
     590             :       auth: auth,
     591             :       deviceId: deviceId,
     592             :       initialDeviceDisplayName: initialDeviceDisplayName,
     593             :       inhibitLogin: inhibitLogin,
     594           0 :       refreshToken: refreshToken ?? onSoftLogout != null,
     595             :     );
     596             : 
     597             :     // Connect if there is an access token in the response.
     598           0 :     final accessToken = response.accessToken;
     599           0 :     final deviceId_ = response.deviceId;
     600           0 :     final userId = response.userId;
     601           0 :     final homeserver = this.homeserver;
     602             :     if (accessToken == null || deviceId_ == null || homeserver == null) {
     603           0 :       throw Exception(
     604             :           'Registered but token, device ID, user ID or homeserver is null.');
     605             :     }
     606           0 :     final expiresInMs = response.expiresInMs;
     607             :     final tokenExpiresAt = expiresInMs == null
     608             :         ? null
     609           0 :         : DateTime.now().add(Duration(milliseconds: expiresInMs));
     610             : 
     611           0 :     await init(
     612             :         newToken: accessToken,
     613             :         newTokenExpiresAt: tokenExpiresAt,
     614           0 :         newRefreshToken: response.refreshToken,
     615             :         newUserID: userId,
     616             :         newHomeserver: homeserver,
     617             :         newDeviceName: initialDeviceDisplayName ?? '',
     618             :         newDeviceID: deviceId_);
     619             :     return response;
     620             :   }
     621             : 
     622             :   /// Handles the login and allows the client to call all APIs which require
     623             :   /// authentication. Returns false if the login was not successful. Throws
     624             :   /// MatrixException if login was not successful.
     625             :   /// To just login with the username 'alice' you set [identifier] to:
     626             :   /// `AuthenticationUserIdentifier(user: 'alice')`
     627             :   /// Maybe you want to set [user] to the same String to stay compatible with
     628             :   /// older server versions.
     629           4 :   @override
     630             :   Future<LoginResponse> login(
     631             :     String type, {
     632             :     AuthenticationIdentifier? identifier,
     633             :     String? password,
     634             :     String? token,
     635             :     String? deviceId,
     636             :     String? initialDeviceDisplayName,
     637             :     bool? refreshToken,
     638             :     @Deprecated('Deprecated in favour of identifier.') String? user,
     639             :     @Deprecated('Deprecated in favour of identifier.') String? medium,
     640             :     @Deprecated('Deprecated in favour of identifier.') String? address,
     641             :   }) async {
     642           4 :     if (homeserver == null) {
     643           1 :       final domain = identifier is AuthenticationUserIdentifier
     644           2 :           ? identifier.user.domain
     645             :           : null;
     646             :       if (domain != null) {
     647           2 :         await checkHomeserver(Uri.https(domain, ''));
     648             :       } else {
     649           0 :         throw Exception('No homeserver specified!');
     650             :       }
     651             :     }
     652           4 :     final response = await super.login(
     653             :       type,
     654             :       identifier: identifier,
     655             :       password: password,
     656             :       token: token,
     657             :       deviceId: deviceId,
     658             :       initialDeviceDisplayName: initialDeviceDisplayName,
     659             :       // ignore: deprecated_member_use
     660             :       user: user,
     661             :       // ignore: deprecated_member_use
     662             :       medium: medium,
     663             :       // ignore: deprecated_member_use
     664             :       address: address,
     665           4 :       refreshToken: refreshToken ?? onSoftLogout != null,
     666             :     );
     667             : 
     668             :     // Connect if there is an access token in the response.
     669           4 :     final accessToken = response.accessToken;
     670           4 :     final deviceId_ = response.deviceId;
     671           4 :     final userId = response.userId;
     672           4 :     final homeserver_ = homeserver;
     673             :     if (homeserver_ == null) {
     674           0 :       throw Exception('Registered but homerserver is null.');
     675             :     }
     676             : 
     677           4 :     final expiresInMs = response.expiresInMs;
     678             :     final tokenExpiresAt = expiresInMs == null
     679             :         ? null
     680           0 :         : DateTime.now().add(Duration(milliseconds: expiresInMs));
     681             : 
     682           4 :     await init(
     683             :       newToken: accessToken,
     684             :       newTokenExpiresAt: tokenExpiresAt,
     685           4 :       newRefreshToken: response.refreshToken,
     686             :       newUserID: userId,
     687             :       newHomeserver: homeserver_,
     688             :       newDeviceName: initialDeviceDisplayName ?? '',
     689             :       newDeviceID: deviceId_,
     690             :     );
     691             :     return response;
     692             :   }
     693             : 
     694             :   /// Sends a logout command to the homeserver and clears all local data,
     695             :   /// including all persistent data from the store.
     696          10 :   @override
     697             :   Future<void> logout() async {
     698             :     try {
     699             :       // Upload keys to make sure all are cached on the next login.
     700          22 :       await encryption?.keyManager.uploadInboundGroupSessions();
     701          10 :       await super.logout();
     702             :     } catch (e, s) {
     703           2 :       Logs().e('Logout failed', e, s);
     704             :       rethrow;
     705             :     } finally {
     706          10 :       await clear();
     707             :     }
     708             :   }
     709             : 
     710             :   /// Sends a logout command to the homeserver and clears all local data,
     711             :   /// including all persistent data from the store.
     712           0 :   @override
     713             :   Future<void> logoutAll() async {
     714             :     // Upload keys to make sure all are cached on the next login.
     715           0 :     await encryption?.keyManager.uploadInboundGroupSessions();
     716             : 
     717           0 :     final futures = <Future>[];
     718           0 :     futures.add(super.logoutAll());
     719           0 :     futures.add(clear());
     720           0 :     await Future.wait(futures).catchError((e, s) {
     721           0 :       Logs().e('Logout all failed', e, s);
     722             :       throw e;
     723             :     });
     724             :   }
     725             : 
     726             :   /// Run any request and react on user interactive authentication flows here.
     727           1 :   Future<T> uiaRequestBackground<T>(
     728             :       Future<T> Function(AuthenticationData? auth) request) {
     729           1 :     final completer = Completer<T>();
     730             :     UiaRequest? uia;
     731           1 :     uia = UiaRequest(
     732             :       request: request,
     733           1 :       onUpdate: (state) {
     734             :         if (uia != null) {
     735           1 :           if (state == UiaRequestState.done) {
     736           2 :             completer.complete(uia.result);
     737           0 :           } else if (state == UiaRequestState.fail) {
     738           0 :             completer.completeError(uia.error!);
     739             :           } else {
     740           0 :             onUiaRequest.add(uia);
     741             :           }
     742             :         }
     743             :       },
     744             :     );
     745           1 :     return completer.future;
     746             :   }
     747             : 
     748             :   /// Returns an existing direct room ID with this user or creates a new one.
     749             :   /// By default encryption will be enabled if the client supports encryption
     750             :   /// and the other user has uploaded any encryption keys.
     751           6 :   Future<String> startDirectChat(
     752             :     String mxid, {
     753             :     bool? enableEncryption,
     754             :     List<StateEvent>? initialState,
     755             :     bool waitForSync = true,
     756             :     Map<String, dynamic>? powerLevelContentOverride,
     757             :     CreateRoomPreset? preset = CreateRoomPreset.trustedPrivateChat,
     758             :   }) async {
     759             :     // Try to find an existing direct chat
     760           6 :     final directChatRoomId = getDirectChatFromUserId(mxid);
     761             :     if (directChatRoomId != null) {
     762           0 :       final room = getRoomById(directChatRoomId);
     763             :       if (room != null) {
     764           0 :         if (room.membership == Membership.join) {
     765             :           return directChatRoomId;
     766           0 :         } else if (room.membership == Membership.invite) {
     767             :           // we might already have an invite into a DM room. If that is the case, we should try to join. If the room is
     768             :           // unjoinable, that will automatically leave the room, so in that case we need to continue creating a new
     769             :           // room. (This implicitly also prevents the room from being returned as a DM room by getDirectChatFromUserId,
     770             :           // because it only returns joined or invited rooms atm.)
     771           0 :           await room.join();
     772           0 :           if (room.membership != Membership.leave) {
     773             :             if (waitForSync) {
     774           0 :               if (room.membership != Membership.join) {
     775             :                 // Wait for room actually appears in sync with the right membership
     776           0 :                 await waitForRoomInSync(directChatRoomId, join: true);
     777             :               }
     778             :             }
     779             :             return directChatRoomId;
     780             :           }
     781             :         }
     782             :       }
     783             :     }
     784             : 
     785             :     enableEncryption ??=
     786           5 :         encryptionEnabled && await userOwnsEncryptionKeys(mxid);
     787             :     if (enableEncryption) {
     788           2 :       initialState ??= [];
     789           2 :       if (!initialState.any((s) => s.type == EventTypes.Encryption)) {
     790           4 :         initialState.add(StateEvent(
     791           2 :           content: {
     792           2 :             'algorithm': supportedGroupEncryptionAlgorithms.first,
     793             :           },
     794             :           type: EventTypes.Encryption,
     795             :         ));
     796             :       }
     797             :     }
     798             : 
     799             :     // Start a new direct chat
     800           6 :     final roomId = await createRoom(
     801           6 :       invite: [mxid],
     802             :       isDirect: true,
     803             :       preset: preset,
     804             :       initialState: initialState,
     805             :       powerLevelContentOverride: powerLevelContentOverride,
     806             :     );
     807             : 
     808             :     if (waitForSync) {
     809           1 :       final room = getRoomById(roomId);
     810           2 :       if (room == null || room.membership != Membership.join) {
     811             :         // Wait for room actually appears in sync
     812           0 :         await waitForRoomInSync(roomId, join: true);
     813             :       }
     814             :     }
     815             : 
     816          12 :     await Room(id: roomId, client: this).addToDirectChat(mxid);
     817             : 
     818             :     return roomId;
     819             :   }
     820             : 
     821             :   /// Simplified method to create a new group chat. By default it is a private
     822             :   /// chat. The encryption is enabled if this client supports encryption and
     823             :   /// the preset is not a public chat.
     824           2 :   Future<String> createGroupChat({
     825             :     String? groupName,
     826             :     bool? enableEncryption,
     827             :     List<String>? invite,
     828             :     CreateRoomPreset preset = CreateRoomPreset.privateChat,
     829             :     List<StateEvent>? initialState,
     830             :     Visibility? visibility,
     831             :     HistoryVisibility? historyVisibility,
     832             :     bool waitForSync = true,
     833             :     bool groupCall = false,
     834             :     bool federated = true,
     835             :     Map<String, dynamic>? powerLevelContentOverride,
     836             :   }) async {
     837             :     enableEncryption ??=
     838           2 :         encryptionEnabled && preset != CreateRoomPreset.publicChat;
     839             :     if (enableEncryption) {
     840           1 :       initialState ??= [];
     841           1 :       if (!initialState.any((s) => s.type == EventTypes.Encryption)) {
     842           2 :         initialState.add(StateEvent(
     843           1 :           content: {
     844           1 :             'algorithm': supportedGroupEncryptionAlgorithms.first,
     845             :           },
     846             :           type: EventTypes.Encryption,
     847             :         ));
     848             :       }
     849             :     }
     850             :     if (historyVisibility != null) {
     851           0 :       initialState ??= [];
     852           0 :       if (!initialState.any((s) => s.type == EventTypes.HistoryVisibility)) {
     853           0 :         initialState.add(StateEvent(
     854           0 :           content: {
     855           0 :             'history_visibility': historyVisibility.text,
     856             :           },
     857             :           type: EventTypes.HistoryVisibility,
     858             :         ));
     859             :       }
     860             :     }
     861             :     if (groupCall) {
     862           1 :       powerLevelContentOverride ??= {};
     863           2 :       powerLevelContentOverride['events'] ??= {};
     864           2 :       powerLevelContentOverride['events'][EventTypes.GroupCallMember] ??=
     865           1 :           powerLevelContentOverride['events_default'] ?? 0;
     866             :     }
     867             : 
     868           2 :     final roomId = await createRoom(
     869           0 :       creationContent: federated ? null : {'m.federate': false},
     870             :       invite: invite,
     871             :       preset: preset,
     872             :       name: groupName,
     873             :       initialState: initialState,
     874             :       visibility: visibility,
     875             :       powerLevelContentOverride: powerLevelContentOverride,
     876             :     );
     877             : 
     878             :     if (waitForSync) {
     879           1 :       if (getRoomById(roomId) == null) {
     880             :         // Wait for room actually appears in sync
     881           0 :         await waitForRoomInSync(roomId, join: true);
     882             :       }
     883             :     }
     884             :     return roomId;
     885             :   }
     886             : 
     887             :   /// Wait for the room to appear into the enabled section of the room sync.
     888             :   /// By default, the function will listen for room in invite, join and leave
     889             :   /// sections of the sync.
     890           0 :   Future<SyncUpdate> waitForRoomInSync(String roomId,
     891             :       {bool join = false, bool invite = false, bool leave = false}) async {
     892             :     if (!join && !invite && !leave) {
     893             :       join = true;
     894             :       invite = true;
     895             :       leave = true;
     896             :     }
     897             : 
     898             :     // Wait for the next sync where this room appears.
     899           0 :     final syncUpdate = await onSync.stream.firstWhere((sync) =>
     900           0 :         invite && (sync.rooms?.invite?.containsKey(roomId) ?? false) ||
     901           0 :         join && (sync.rooms?.join?.containsKey(roomId) ?? false) ||
     902           0 :         leave && (sync.rooms?.leave?.containsKey(roomId) ?? false));
     903             : 
     904             :     // Wait for this sync to be completely processed.
     905           0 :     await onSyncStatus.stream.firstWhere(
     906           0 :       (syncStatus) => syncStatus.status == SyncStatus.finished,
     907             :     );
     908             :     return syncUpdate;
     909             :   }
     910             : 
     911             :   /// Checks if the given user has encryption keys. May query keys from the
     912             :   /// server to answer this.
     913           2 :   Future<bool> userOwnsEncryptionKeys(String userId) async {
     914           4 :     if (userId == userID) return encryptionEnabled;
     915           6 :     if (_userDeviceKeys[userId]?.deviceKeys.isNotEmpty ?? false) {
     916             :       return true;
     917             :     }
     918           3 :     final keys = await queryKeys({userId: []});
     919           3 :     return keys.deviceKeys?[userId]?.isNotEmpty ?? false;
     920             :   }
     921             : 
     922             :   /// Creates a new space and returns the Room ID. The parameters are mostly
     923             :   /// the same like in [createRoom()].
     924             :   /// Be aware that spaces appear in the [rooms] list. You should check if a
     925             :   /// room is a space by using the `room.isSpace` getter and then just use the
     926             :   /// room as a space with `room.toSpace()`.
     927             :   ///
     928             :   /// https://github.com/matrix-org/matrix-doc/blob/matthew/msc1772/proposals/1772-groups-as-rooms.md
     929           1 :   Future<String> createSpace(
     930             :       {String? name,
     931             :       String? topic,
     932             :       Visibility visibility = Visibility.public,
     933             :       String? spaceAliasName,
     934             :       List<String>? invite,
     935             :       List<Invite3pid>? invite3pid,
     936             :       String? roomVersion,
     937             :       bool waitForSync = false}) async {
     938           1 :     final id = await createRoom(
     939             :       name: name,
     940             :       topic: topic,
     941             :       visibility: visibility,
     942             :       roomAliasName: spaceAliasName,
     943           1 :       creationContent: {'type': 'm.space'},
     944           1 :       powerLevelContentOverride: {'events_default': 100},
     945             :       invite: invite,
     946             :       invite3pid: invite3pid,
     947             :       roomVersion: roomVersion,
     948             :     );
     949             : 
     950             :     if (waitForSync) {
     951           0 :       await waitForRoomInSync(id, join: true);
     952             :     }
     953             : 
     954             :     return id;
     955             :   }
     956             : 
     957           0 :   @Deprecated('Use getUserProfile(userID) instead')
     958           0 :   Future<Profile> get ownProfile => fetchOwnProfile();
     959             : 
     960             :   /// Returns the user's own displayname and avatar url. In Matrix it is possible that
     961             :   /// one user can have different displaynames and avatar urls in different rooms.
     962             :   /// Tries to get the profile from homeserver first, if failed, falls back to a profile
     963             :   /// from a room where the user exists. Set `useServerCache` to true to get any
     964             :   /// prior value from this function
     965           0 :   @Deprecated('Use fetchOwnProfile() instead')
     966             :   Future<Profile> fetchOwnProfileFromServer(
     967             :       {bool useServerCache = false}) async {
     968             :     try {
     969           0 :       return await getProfileFromUserId(
     970           0 :         userID!,
     971             :         getFromRooms: false,
     972             :         cache: useServerCache,
     973             :       );
     974             :     } catch (e) {
     975           0 :       Logs().w(
     976             :           '[Matrix] getting profile from homeserver failed, falling back to first room with required profile');
     977           0 :       return await getProfileFromUserId(
     978           0 :         userID!,
     979             :         getFromRooms: true,
     980             :         cache: true,
     981             :       );
     982             :     }
     983             :   }
     984             : 
     985             :   /// Returns the user's own displayname and avatar url. In Matrix it is possible that
     986             :   /// one user can have different displaynames and avatar urls in different rooms.
     987             :   /// This returns the profile from the first room by default, override `getFromRooms`
     988             :   /// to false to fetch from homeserver.
     989           0 :   Future<Profile> fetchOwnProfile({
     990             :     @Deprecated('No longer supported') bool getFromRooms = true,
     991             :     @Deprecated('No longer supported') bool cache = true,
     992             :   }) =>
     993           0 :       getProfileFromUserId(userID!);
     994             : 
     995             :   /// Get the combined profile information for this user. First checks for a
     996             :   /// non outdated cached profile before requesting from the server. Cached
     997             :   /// profiles are outdated if they have been cached in a time older than the
     998             :   /// [maxCacheAge] or they have been marked as outdated by an event in the
     999             :   /// sync loop.
    1000             :   /// In case of an
    1001             :   ///
    1002             :   /// [userId] The user whose profile information to get.
    1003           4 :   @override
    1004             :   Future<CachedProfileInformation> getUserProfile(
    1005             :     String userId, {
    1006             :     Duration timeout = const Duration(seconds: 30),
    1007             :     Duration maxCacheAge = const Duration(days: 1),
    1008             :   }) async {
    1009           7 :     final cachedProfile = await database?.getUserProfile(userId);
    1010             :     if (cachedProfile != null &&
    1011           1 :         !cachedProfile.outdated &&
    1012           4 :         DateTime.now().difference(cachedProfile.updated) < maxCacheAge) {
    1013             :       return cachedProfile;
    1014             :     }
    1015             : 
    1016             :     final ProfileInformation profile;
    1017             :     try {
    1018           8 :       profile = await (_userProfileRequests[userId] ??=
    1019           8 :           super.getUserProfile(userId).timeout(timeout));
    1020             :     } catch (e) {
    1021           4 :       Logs().d('Unable to fetch profile from server', e);
    1022             :       if (cachedProfile == null) rethrow;
    1023             :       return cachedProfile;
    1024             :     } finally {
    1025          12 :       unawaited(_userProfileRequests.remove(userId));
    1026             :     }
    1027             : 
    1028           3 :     final newCachedProfile = CachedProfileInformation.fromProfile(
    1029             :       profile,
    1030             :       outdated: false,
    1031           3 :       updated: DateTime.now(),
    1032             :     );
    1033             : 
    1034           6 :     await database?.storeUserProfile(userId, newCachedProfile);
    1035             : 
    1036             :     return newCachedProfile;
    1037             :   }
    1038             : 
    1039             :   final Map<String, Future<ProfileInformation>> _userProfileRequests = {};
    1040             : 
    1041             :   final CachedStreamController<String> onUserProfileUpdate =
    1042             :       CachedStreamController<String>();
    1043             : 
    1044             :   /// Get the combined profile information for this user from the server or
    1045             :   /// from the cache depending on the cache value. Returns a `Profile` object
    1046             :   /// including the given userId but without information about how outdated
    1047             :   /// the profile is. If you need those, try using `getUserProfile()` instead.
    1048           1 :   Future<Profile> getProfileFromUserId(
    1049             :     String userId, {
    1050             :     @Deprecated('No longer supported') bool? getFromRooms,
    1051             :     @Deprecated('No longer supported') bool? cache,
    1052             :     Duration timeout = const Duration(seconds: 30),
    1053             :     Duration maxCacheAge = const Duration(days: 1),
    1054             :   }) async {
    1055             :     CachedProfileInformation? cachedProfileInformation;
    1056             :     try {
    1057           1 :       cachedProfileInformation = await getUserProfile(
    1058             :         userId,
    1059             :         timeout: timeout,
    1060             :         maxCacheAge: maxCacheAge,
    1061             :       );
    1062             :     } catch (e) {
    1063           0 :       Logs().d('Unable to fetch profile for $userId', e);
    1064             :     }
    1065             : 
    1066           1 :     return Profile(
    1067             :       userId: userId,
    1068           1 :       displayName: cachedProfileInformation?.displayname,
    1069           1 :       avatarUrl: cachedProfileInformation?.avatarUrl,
    1070             :     );
    1071             :   }
    1072             : 
    1073             :   final List<ArchivedRoom> _archivedRooms = [];
    1074             : 
    1075             :   /// Return an archive room containing the room and the timeline for a specific archived room.
    1076           2 :   ArchivedRoom? getArchiveRoomFromCache(String roomId) {
    1077           8 :     for (var i = 0; i < _archivedRooms.length; i++) {
    1078           4 :       final archive = _archivedRooms[i];
    1079           6 :       if (archive.room.id == roomId) return archive;
    1080             :     }
    1081             :     return null;
    1082             :   }
    1083             : 
    1084             :   /// Remove all the archives stored in cache.
    1085           2 :   void clearArchivesFromCache() {
    1086           4 :     _archivedRooms.clear();
    1087             :   }
    1088             : 
    1089           0 :   @Deprecated('Use [loadArchive()] instead.')
    1090           0 :   Future<List<Room>> get archive => loadArchive();
    1091             : 
    1092             :   /// Fetch all the archived rooms from the server and return the list of the
    1093             :   /// room. If you want to have the Timelines bundled with it, use
    1094             :   /// loadArchiveWithTimeline instead.
    1095           1 :   Future<List<Room>> loadArchive() async {
    1096           5 :     return (await loadArchiveWithTimeline()).map((e) => e.room).toList();
    1097             :   }
    1098             : 
    1099             :   // Synapse caches sync responses. Documentation:
    1100             :   // https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#caches-and-associated-values
    1101             :   // At the time of writing, the cache key consists of the following fields:  user, timeout, since, filter_id,
    1102             :   // full_state, device_id, last_ignore_accdata_streampos.
    1103             :   // Since we can't pass a since token, the easiest field to vary is the timeout to bust through the synapse cache and
    1104             :   // give us the actual currently left rooms. Since the timeout doesn't matter for initial sync, this should actually
    1105             :   // not make any visible difference apart from properly fetching the cached rooms.
    1106             :   int _archiveCacheBusterTimeout = 0;
    1107             : 
    1108             :   /// Fetch the archived rooms from the server and return them as a list of
    1109             :   /// [ArchivedRoom] objects containing the [Room] and the associated [Timeline].
    1110           3 :   Future<List<ArchivedRoom>> loadArchiveWithTimeline() async {
    1111           6 :     _archivedRooms.clear();
    1112             : 
    1113           6 :     final filter = jsonEncode(Filter(
    1114           3 :       room: RoomFilter(
    1115           3 :         state: StateFilter(lazyLoadMembers: true),
    1116             :         includeLeave: true,
    1117           3 :         timeline: StateFilter(limit: 10),
    1118             :       ),
    1119           3 :     ).toJson());
    1120             : 
    1121           3 :     final syncResp = await sync(
    1122             :       filter: filter,
    1123           3 :       timeout: _archiveCacheBusterTimeout,
    1124           3 :       setPresence: syncPresence,
    1125             :     );
    1126             :     // wrap around and hope there are not more than 30 leaves in 2 minutes :)
    1127          12 :     _archiveCacheBusterTimeout = (_archiveCacheBusterTimeout + 1) % 30;
    1128             : 
    1129           6 :     final leave = syncResp.rooms?.leave;
    1130             :     if (leave != null) {
    1131           6 :       for (final entry in leave.entries) {
    1132           9 :         await _storeArchivedRoom(entry.key, entry.value);
    1133             :       }
    1134             :     }
    1135             : 
    1136             :     // Sort the archived rooms by last event originServerTs as this is the
    1137             :     // best indicator we have to sort them. For archived rooms where we don't
    1138             :     // have any, we move them to the bottom.
    1139           3 :     final beginningOfTime = DateTime.fromMillisecondsSinceEpoch(0);
    1140           9 :     _archivedRooms.sort((b, a) =>
    1141           6 :         (a.room.lastEvent?.originServerTs ?? beginningOfTime)
    1142          12 :             .compareTo(b.room.lastEvent?.originServerTs ?? beginningOfTime));
    1143             : 
    1144           3 :     return _archivedRooms;
    1145             :   }
    1146             : 
    1147             :   /// [_storeArchivedRoom]
    1148             :   /// @leftRoom we can pass a room which was left so that we don't loose states
    1149           3 :   Future<void> _storeArchivedRoom(
    1150             :     String id,
    1151             :     LeftRoomUpdate update, {
    1152             :     Room? leftRoom,
    1153             :   }) async {
    1154             :     final roomUpdate = update;
    1155             :     final archivedRoom = leftRoom ??
    1156           3 :         Room(
    1157             :           id: id,
    1158             :           membership: Membership.leave,
    1159             :           client: this,
    1160           3 :           roomAccountData: roomUpdate.accountData
    1161           3 :                   ?.asMap()
    1162          12 :                   .map((k, v) => MapEntry(v.type, v)) ??
    1163           3 :               <String, BasicRoomEvent>{},
    1164             :         );
    1165             :     // Set membership of room to leave, in the case we got a left room passed, otherwise
    1166             :     // the left room would have still membership join, which would be wrong for the setState later
    1167           3 :     archivedRoom.membership = Membership.leave;
    1168           3 :     final timeline = Timeline(
    1169             :         room: archivedRoom,
    1170           3 :         chunk: TimelineChunk(
    1171           9 :             events: roomUpdate.timeline?.events?.reversed
    1172           3 :                     .toList() // we display the event in the other sence
    1173           9 :                     .map((e) => Event.fromMatrixEvent(e, archivedRoom))
    1174           3 :                     .toList() ??
    1175           0 :                 []));
    1176             : 
    1177           9 :     archivedRoom.prev_batch = update.timeline?.prevBatch;
    1178             : 
    1179           3 :     final stateEvents = roomUpdate.state;
    1180             :     if (stateEvents != null) {
    1181           3 :       await _handleRoomEvents(archivedRoom, stateEvents, EventUpdateType.state,
    1182             :           store: false);
    1183             :     }
    1184             : 
    1185           6 :     final timelineEvents = roomUpdate.timeline?.events;
    1186             :     if (timelineEvents != null) {
    1187           9 :       await _handleRoomEvents(archivedRoom, timelineEvents.reversed.toList(),
    1188             :           EventUpdateType.timeline,
    1189             :           store: false);
    1190             :     }
    1191             : 
    1192          12 :     for (var i = 0; i < timeline.events.length; i++) {
    1193             :       // Try to decrypt encrypted events but don't update the database.
    1194           3 :       if (archivedRoom.encrypted && archivedRoom.client.encryptionEnabled) {
    1195           0 :         if (timeline.events[i].type == EventTypes.Encrypted) {
    1196           0 :           await archivedRoom.client.encryption!
    1197           0 :               .decryptRoomEvent(
    1198           0 :                 archivedRoom.id,
    1199           0 :                 timeline.events[i],
    1200             :               )
    1201           0 :               .then(
    1202           0 :                 (decrypted) => timeline.events[i] = decrypted,
    1203             :               );
    1204             :         }
    1205             :       }
    1206             :     }
    1207             : 
    1208           9 :     _archivedRooms.add(ArchivedRoom(room: archivedRoom, timeline: timeline));
    1209             :   }
    1210             : 
    1211             :   final _versionsCache =
    1212             :       AsyncCache<GetVersionsResponse>(const Duration(hours: 1));
    1213             : 
    1214           7 :   Future<bool> authenticatedMediaSupported() async {
    1215          28 :     final versionsResponse = await _versionsCache.fetch(() => getVersions());
    1216          14 :     return versionsResponse.versions.any(
    1217          14 :           (v) => isVersionGreaterThanOrEqualTo(v, 'v1.11'),
    1218             :         ) ||
    1219           6 :         versionsResponse.unstableFeatures?['org.matrix.msc3916.stable'] == true;
    1220             :   }
    1221             : 
    1222             :   final _serverConfigCache = AsyncCache<MediaConfig>(const Duration(hours: 1));
    1223             : 
    1224             :   /// This endpoint allows clients to retrieve the configuration of the content
    1225             :   /// repository, such as upload limitations.
    1226             :   /// Clients SHOULD use this as a guide when using content repository endpoints.
    1227             :   /// All values are intentionally left optional. Clients SHOULD follow
    1228             :   /// the advice given in the field description when the field is not available.
    1229             :   ///
    1230             :   /// **NOTE:** Both clients and server administrators should be aware that proxies
    1231             :   /// between the client and the server may affect the apparent behaviour of content
    1232             :   /// repository APIs, for example, proxies may enforce a lower upload size limit
    1233             :   /// than is advertised by the server on this endpoint.
    1234           4 :   @override
    1235             :   Future<MediaConfig> getConfig() =>
    1236          16 :       _serverConfigCache.fetch(() async => (await authenticatedMediaSupported())
    1237           4 :           ? getConfigAuthed()
    1238             :           // ignore: deprecated_member_use_from_same_package
    1239           0 :           : super.getConfig());
    1240             : 
    1241             :   ///
    1242             :   ///
    1243             :   /// [serverName] The server name from the `mxc://` URI (the authoritory component)
    1244             :   ///
    1245             :   ///
    1246             :   /// [mediaId] The media ID from the `mxc://` URI (the path component)
    1247             :   ///
    1248             :   ///
    1249             :   /// [allowRemote] Indicates to the server that it should not attempt to fetch the media if
    1250             :   /// it is deemed remote. This is to prevent routing loops where the server
    1251             :   /// contacts itself.
    1252             :   ///
    1253             :   /// Defaults to `true` if not provided.
    1254             :   ///
    1255             :   /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
    1256             :   /// start receiving data, in the case that the content has not yet been
    1257             :   /// uploaded. The default value is 20000 (20 seconds). The content
    1258             :   /// repository SHOULD impose a maximum value for this parameter. The
    1259             :   /// content repository MAY respond before the timeout.
    1260             :   ///
    1261             :   ///
    1262             :   /// [allowRedirect] Indicates to the server that it may return a 307 or 308 redirect
    1263             :   /// response that points at the relevant media content. When not explicitly
    1264             :   /// set to `true` the server must return the media content itself.
    1265             :   ///
    1266           0 :   @override
    1267             :   Future<FileResponse> getContent(
    1268             :     String serverName,
    1269             :     String mediaId, {
    1270             :     bool? allowRemote,
    1271             :     int? timeoutMs,
    1272             :     bool? allowRedirect,
    1273             :   }) async {
    1274           0 :     return (await authenticatedMediaSupported())
    1275           0 :         ? getContentAuthed(
    1276             :             serverName,
    1277             :             mediaId,
    1278             :             timeoutMs: timeoutMs,
    1279             :           )
    1280             :         // ignore: deprecated_member_use_from_same_package
    1281           0 :         : super.getContent(
    1282             :             serverName,
    1283             :             mediaId,
    1284             :             allowRemote: allowRemote,
    1285             :             timeoutMs: timeoutMs,
    1286             :             allowRedirect: allowRedirect,
    1287             :           );
    1288             :   }
    1289             : 
    1290             :   /// This will download content from the content repository (same as
    1291             :   /// the previous endpoint) but replace the target file name with the one
    1292             :   /// provided by the caller.
    1293             :   ///
    1294             :   /// {{% boxes/warning %}}
    1295             :   /// {{< changed-in v="1.11" >}} This endpoint MAY return `404 M_NOT_FOUND`
    1296             :   /// for media which exists, but is after the server froze unauthenticated
    1297             :   /// media access. See [Client Behaviour](https://spec.matrix.org/unstable/client-server-api/#content-repo-client-behaviour) for more
    1298             :   /// information.
    1299             :   /// {{% /boxes/warning %}}
    1300             :   ///
    1301             :   /// [serverName] The server name from the `mxc://` URI (the authority component).
    1302             :   ///
    1303             :   ///
    1304             :   /// [mediaId] The media ID from the `mxc://` URI (the path component).
    1305             :   ///
    1306             :   ///
    1307             :   /// [fileName] A filename to give in the `Content-Disposition` header.
    1308             :   ///
    1309             :   /// [allowRemote] Indicates to the server that it should not attempt to fetch the media if
    1310             :   /// it is deemed remote. This is to prevent routing loops where the server
    1311             :   /// contacts itself.
    1312             :   ///
    1313             :   /// Defaults to `true` if not provided.
    1314             :   ///
    1315             :   /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
    1316             :   /// start receiving data, in the case that the content has not yet been
    1317             :   /// uploaded. The default value is 20000 (20 seconds). The content
    1318             :   /// repository SHOULD impose a maximum value for this parameter. The
    1319             :   /// content repository MAY respond before the timeout.
    1320             :   ///
    1321             :   ///
    1322             :   /// [allowRedirect] Indicates to the server that it may return a 307 or 308 redirect
    1323             :   /// response that points at the relevant media content. When not explicitly
    1324             :   /// set to `true` the server must return the media content itself.
    1325           0 :   @override
    1326             :   Future<FileResponse> getContentOverrideName(
    1327             :     String serverName,
    1328             :     String mediaId,
    1329             :     String fileName, {
    1330             :     bool? allowRemote,
    1331             :     int? timeoutMs,
    1332             :     bool? allowRedirect,
    1333             :   }) async {
    1334           0 :     return (await authenticatedMediaSupported())
    1335           0 :         ? getContentOverrideNameAuthed(
    1336             :             serverName,
    1337             :             mediaId,
    1338             :             fileName,
    1339             :             timeoutMs: timeoutMs,
    1340             :           )
    1341             :         // ignore: deprecated_member_use_from_same_package
    1342           0 :         : super.getContentOverrideName(
    1343             :             serverName,
    1344             :             mediaId,
    1345             :             fileName,
    1346             :             allowRemote: allowRemote,
    1347             :             timeoutMs: timeoutMs,
    1348             :             allowRedirect: allowRedirect,
    1349             :           );
    1350             :   }
    1351             : 
    1352             :   /// Download a thumbnail of content from the content repository.
    1353             :   /// See the [Thumbnails](https://spec.matrix.org/unstable/client-server-api/#thumbnails) section for more information.
    1354             :   ///
    1355             :   /// {{% boxes/note %}}
    1356             :   /// Clients SHOULD NOT generate or use URLs which supply the access token in
    1357             :   /// the query string. These URLs may be copied by users verbatim and provided
    1358             :   /// in a chat message to another user, disclosing the sender's access token.
    1359             :   /// {{% /boxes/note %}}
    1360             :   ///
    1361             :   /// Clients MAY be redirected using the 307/308 responses below to download
    1362             :   /// the request object. This is typical when the homeserver uses a Content
    1363             :   /// Delivery Network (CDN).
    1364             :   ///
    1365             :   /// [serverName] The server name from the `mxc://` URI (the authority component).
    1366             :   ///
    1367             :   ///
    1368             :   /// [mediaId] The media ID from the `mxc://` URI (the path component).
    1369             :   ///
    1370             :   ///
    1371             :   /// [width] The *desired* width of the thumbnail. The actual thumbnail may be
    1372             :   /// larger than the size specified.
    1373             :   ///
    1374             :   /// [height] The *desired* height of the thumbnail. The actual thumbnail may be
    1375             :   /// larger than the size specified.
    1376             :   ///
    1377             :   /// [method] The desired resizing method. See the [Thumbnails](https://spec.matrix.org/unstable/client-server-api/#thumbnails)
    1378             :   /// section for more information.
    1379             :   ///
    1380             :   /// [timeoutMs] The maximum number of milliseconds that the client is willing to wait to
    1381             :   /// start receiving data, in the case that the content has not yet been
    1382             :   /// uploaded. The default value is 20000 (20 seconds). The content
    1383             :   /// repository SHOULD impose a maximum value for this parameter. The
    1384             :   /// content repository MAY respond before the timeout.
    1385             :   ///
    1386             :   ///
    1387             :   /// [animated] Indicates preference for an animated thumbnail from the server, if possible. Animated
    1388             :   /// thumbnails typically use the content types `image/gif`, `image/png` (with APNG format),
    1389             :   /// `image/apng`, and `image/webp` instead of the common static `image/png` or `image/jpeg`
    1390             :   /// content types.
    1391             :   ///
    1392             :   /// When `true`, the server SHOULD return an animated thumbnail if possible and supported.
    1393             :   /// When `false`, the server MUST NOT return an animated thumbnail. For example, returning a
    1394             :   /// static `image/png` or `image/jpeg` thumbnail. When not provided, the server SHOULD NOT
    1395             :   /// return an animated thumbnail.
    1396             :   ///
    1397             :   /// Servers SHOULD prefer to return `image/webp` thumbnails when supporting animation.
    1398             :   ///
    1399             :   /// When `true` and the media cannot be animated, such as in the case of a JPEG or PDF, the
    1400             :   /// server SHOULD behave as though `animated` is `false`.
    1401           0 :   @override
    1402             :   Future<FileResponse> getContentThumbnail(
    1403             :     String serverName,
    1404             :     String mediaId,
    1405             :     int width,
    1406             :     int height, {
    1407             :     Method? method,
    1408             :     bool? allowRemote,
    1409             :     int? timeoutMs,
    1410             :     bool? allowRedirect,
    1411             :     bool? animated,
    1412             :   }) async {
    1413           0 :     return (await authenticatedMediaSupported())
    1414           0 :         ? getContentThumbnailAuthed(
    1415             :             serverName,
    1416             :             mediaId,
    1417             :             width,
    1418             :             height,
    1419             :             method: method,
    1420             :             timeoutMs: timeoutMs,
    1421             :             animated: animated,
    1422             :           )
    1423             :         // ignore: deprecated_member_use_from_same_package
    1424           0 :         : super.getContentThumbnail(
    1425             :             serverName,
    1426             :             mediaId,
    1427             :             width,
    1428             :             height,
    1429             :             method: method,
    1430             :             timeoutMs: timeoutMs,
    1431             :             animated: animated,
    1432             :           );
    1433             :   }
    1434             : 
    1435             :   /// Get information about a URL for the client. Typically this is called when a
    1436             :   /// client sees a URL in a message and wants to render a preview for the user.
    1437             :   ///
    1438             :   /// {{% boxes/note %}}
    1439             :   /// Clients should consider avoiding this endpoint for URLs posted in encrypted
    1440             :   /// rooms. Encrypted rooms often contain more sensitive information the users
    1441             :   /// do not want to share with the homeserver, and this can mean that the URLs
    1442             :   /// being shared should also not be shared with the homeserver.
    1443             :   /// {{% /boxes/note %}}
    1444             :   ///
    1445             :   /// [url] The URL to get a preview of.
    1446             :   ///
    1447             :   /// [ts] The preferred point in time to return a preview for. The server may
    1448             :   /// return a newer version if it does not have the requested version
    1449             :   /// available.
    1450           0 :   @override
    1451             :   Future<PreviewForUrl> getUrlPreview(Uri url, {int? ts}) async {
    1452           0 :     return (await authenticatedMediaSupported())
    1453           0 :         ? getUrlPreviewAuthed(url, ts: ts)
    1454             :         // ignore: deprecated_member_use_from_same_package
    1455           0 :         : super.getUrlPreview(url, ts: ts);
    1456             :   }
    1457             : 
    1458             :   /// Uploads a file and automatically caches it in the database, if it is small enough
    1459             :   /// and returns the mxc url.
    1460           4 :   @override
    1461             :   Future<Uri> uploadContent(Uint8List file,
    1462             :       {String? filename, String? contentType}) async {
    1463           4 :     final mediaConfig = await getConfig();
    1464           4 :     final maxMediaSize = mediaConfig.mUploadSize;
    1465           8 :     if (maxMediaSize != null && maxMediaSize < file.lengthInBytes) {
    1466           0 :       throw FileTooBigMatrixException(file.lengthInBytes, maxMediaSize);
    1467             :     }
    1468             : 
    1469           3 :     contentType ??= lookupMimeType(filename ?? '', headerBytes: file);
    1470             :     final mxc = await super
    1471           4 :         .uploadContent(file, filename: filename, contentType: contentType);
    1472             : 
    1473           4 :     final database = this.database;
    1474          12 :     if (database != null && file.length <= database.maxFileSize) {
    1475           4 :       await database.storeFile(
    1476           8 :           mxc, file, DateTime.now().millisecondsSinceEpoch);
    1477             :     }
    1478             :     return mxc;
    1479             :   }
    1480             : 
    1481             :   /// Sends a typing notification and initiates a megolm session, if needed
    1482           0 :   @override
    1483             :   Future<void> setTyping(
    1484             :     String userId,
    1485             :     String roomId,
    1486             :     bool typing, {
    1487             :     int? timeout,
    1488             :   }) async {
    1489           0 :     await super.setTyping(userId, roomId, typing, timeout: timeout);
    1490           0 :     final room = getRoomById(roomId);
    1491           0 :     if (typing && room != null && encryptionEnabled && room.encrypted) {
    1492             :       // ignore: unawaited_futures
    1493           0 :       encryption?.keyManager.prepareOutboundGroupSession(roomId);
    1494             :     }
    1495             :   }
    1496             : 
    1497             :   /// dumps the local database and exports it into a String.
    1498             :   ///
    1499             :   /// WARNING: never re-import the dump twice
    1500             :   ///
    1501             :   /// This can be useful to migrate a session from one device to a future one.
    1502           0 :   Future<String?> exportDump() async {
    1503           0 :     if (database != null) {
    1504           0 :       await abortSync();
    1505           0 :       await dispose(closeDatabase: false);
    1506             : 
    1507           0 :       final export = await database!.exportDump();
    1508             : 
    1509           0 :       await clear();
    1510             :       return export;
    1511             :     }
    1512             :     return null;
    1513             :   }
    1514             : 
    1515             :   /// imports a dumped session
    1516             :   ///
    1517             :   /// WARNING: never re-import the dump twice
    1518           0 :   Future<bool> importDump(String export) async {
    1519             :     try {
    1520             :       // stopping sync loop and subscriptions while keeping DB open
    1521           0 :       await dispose(closeDatabase: false);
    1522             :     } catch (_) {
    1523             :       // Client was probably not initialized yet.
    1524             :     }
    1525             : 
    1526           0 :     _database ??= await databaseBuilder!.call(this);
    1527             : 
    1528           0 :     final success = await database!.importDump(export);
    1529             : 
    1530             :     if (success) {
    1531             :       // closing including DB
    1532           0 :       await dispose();
    1533             : 
    1534             :       try {
    1535           0 :         bearerToken = null;
    1536             : 
    1537           0 :         await init(
    1538             :           waitForFirstSync: false,
    1539             :           waitUntilLoadCompletedLoaded: false,
    1540             :         );
    1541             :       } catch (e) {
    1542             :         return false;
    1543             :       }
    1544             :     }
    1545             :     return success;
    1546             :   }
    1547             : 
    1548             :   /// Uploads a new user avatar for this user. Leave file null to remove the
    1549             :   /// current avatar.
    1550           1 :   Future<void> setAvatar(MatrixFile? file) async {
    1551             :     if (file == null) {
    1552             :       // We send an empty String to remove the avatar. Sending Null **should**
    1553             :       // work but it doesn't with Synapse. See:
    1554             :       // https://gitlab.com/famedly/company/frontend/famedlysdk/-/issues/254
    1555           0 :       return setAvatarUrl(userID!, Uri.parse(''));
    1556             :     }
    1557           1 :     final uploadResp = await uploadContent(
    1558           1 :       file.bytes,
    1559           1 :       filename: file.name,
    1560           1 :       contentType: file.mimeType,
    1561             :     );
    1562           2 :     await setAvatarUrl(userID!, uploadResp);
    1563             :     return;
    1564             :   }
    1565             : 
    1566             :   /// Returns the global push rules for the logged in user.
    1567           0 :   PushRuleSet? get globalPushRules {
    1568           0 :     final pushrules = _accountData['m.push_rules']
    1569           0 :         ?.content
    1570           0 :         .tryGetMap<String, Object?>('global');
    1571           0 :     return pushrules != null ? TryGetPushRule.tryFromJson(pushrules) : null;
    1572             :   }
    1573             : 
    1574             :   /// Returns the device push rules for the logged in user.
    1575           0 :   PushRuleSet? get devicePushRules {
    1576           0 :     final pushrules = _accountData['m.push_rules']
    1577           0 :         ?.content
    1578           0 :         .tryGetMap<String, Object?>('device');
    1579           0 :     return pushrules != null ? TryGetPushRule.tryFromJson(pushrules) : null;
    1580             :   }
    1581             : 
    1582             :   static const Set<String> supportedVersions = {'v1.1', 'v1.2'};
    1583             :   static const List<String> supportedDirectEncryptionAlgorithms = [
    1584             :     AlgorithmTypes.olmV1Curve25519AesSha2
    1585             :   ];
    1586             :   static const List<String> supportedGroupEncryptionAlgorithms = [
    1587             :     AlgorithmTypes.megolmV1AesSha2
    1588             :   ];
    1589             :   static const int defaultThumbnailSize = 800;
    1590             : 
    1591             :   /// The newEvent signal is the most important signal in this concept. Every time
    1592             :   /// the app receives a new synchronization, this event is called for every signal
    1593             :   /// to update the GUI. For example, for a new message, it is called:
    1594             :   /// onRoomEvent( "m.room.message", "!chat_id:server.com", "timeline", {sender: "@bob:server.com", body: "Hello world"} )
    1595             :   final CachedStreamController<EventUpdate> onEvent = CachedStreamController();
    1596             : 
    1597             :   /// The onToDeviceEvent is called when there comes a new to device event. It is
    1598             :   /// already decrypted if necessary.
    1599             :   final CachedStreamController<ToDeviceEvent> onToDeviceEvent =
    1600             :       CachedStreamController();
    1601             : 
    1602             :   /// Tells you about to-device and room call specific events in sync
    1603             :   final CachedStreamController<List<BasicEventWithSender>> onCallEvents =
    1604             :       CachedStreamController();
    1605             : 
    1606             :   /// Called when the login state e.g. user gets logged out.
    1607             :   final CachedStreamController<LoginState> onLoginStateChanged =
    1608             :       CachedStreamController();
    1609             : 
    1610             :   /// Called when the local cache is reset
    1611             :   final CachedStreamController<bool> onCacheCleared = CachedStreamController();
    1612             : 
    1613             :   /// Encryption errors are coming here.
    1614             :   final CachedStreamController<SdkError> onEncryptionError =
    1615             :       CachedStreamController();
    1616             : 
    1617             :   /// When a new sync response is coming in, this gives the complete payload.
    1618             :   final CachedStreamController<SyncUpdate> onSync = CachedStreamController();
    1619             : 
    1620             :   /// This gives the current status of the synchronization
    1621             :   final CachedStreamController<SyncStatusUpdate> onSyncStatus =
    1622             :       CachedStreamController();
    1623             : 
    1624             :   /// Callback will be called on presences.
    1625             :   @Deprecated(
    1626             :       'Deprecated, use onPresenceChanged instead which has a timestamp.')
    1627             :   final CachedStreamController<Presence> onPresence = CachedStreamController();
    1628             : 
    1629             :   /// Callback will be called on presence updates.
    1630             :   final CachedStreamController<CachedPresence> onPresenceChanged =
    1631             :       CachedStreamController();
    1632             : 
    1633             :   /// Callback will be called on account data updates.
    1634             :   @Deprecated('Use `client.onSync` instead')
    1635             :   final CachedStreamController<BasicEvent> onAccountData =
    1636             :       CachedStreamController();
    1637             : 
    1638             :   /// Will be called when another device is requesting session keys for a room.
    1639             :   final CachedStreamController<RoomKeyRequest> onRoomKeyRequest =
    1640             :       CachedStreamController();
    1641             : 
    1642             :   /// Will be called when another device is requesting verification with this device.
    1643             :   final CachedStreamController<KeyVerification> onKeyVerificationRequest =
    1644             :       CachedStreamController();
    1645             : 
    1646             :   /// When the library calls an endpoint that needs UIA the `UiaRequest` is passed down this stream.
    1647             :   /// The client can open a UIA prompt based on this.
    1648             :   final CachedStreamController<UiaRequest> onUiaRequest =
    1649             :       CachedStreamController();
    1650             : 
    1651             :   @Deprecated('This is not in use anywhere anymore')
    1652             :   final CachedStreamController<Event> onGroupMember = CachedStreamController();
    1653             : 
    1654             :   final CachedStreamController<String> onCancelSendEvent =
    1655             :       CachedStreamController();
    1656             : 
    1657             :   /// When a state in a room has been updated this will return the room ID
    1658             :   /// and the state event.
    1659             :   final CachedStreamController<({String roomId, StrippedStateEvent state})>
    1660             :       onRoomState = CachedStreamController();
    1661             : 
    1662             :   /// How long should the app wait until it retrys the synchronisation after
    1663             :   /// an error?
    1664             :   int syncErrorTimeoutSec = 3;
    1665             : 
    1666             :   bool _initLock = false;
    1667             : 
    1668             :   /// Fetches the corresponding Event object from a notification including a
    1669             :   /// full Room object with the sender User object in it. Returns null if this
    1670             :   /// push notification is not corresponding to an existing event.
    1671             :   /// The client does **not** need to be initialized first. If it is not
    1672             :   /// initialized, it will only fetch the necessary parts of the database. This
    1673             :   /// should make it possible to run this parallel to another client with the
    1674             :   /// same client name.
    1675             :   /// This also checks if the given event has a readmarker and returns null
    1676             :   /// in this case.
    1677           1 :   Future<Event?> getEventByPushNotification(
    1678             :     PushNotification notification, {
    1679             :     bool storeInDatabase = true,
    1680             :     Duration timeoutForServerRequests = const Duration(seconds: 8),
    1681             :     bool returnNullIfSeen = true,
    1682             :   }) async {
    1683             :     // Get access token if necessary:
    1684           3 :     final database = _database ??= await databaseBuilder?.call(this);
    1685           1 :     if (!isLogged()) {
    1686             :       if (database == null) {
    1687           0 :         throw Exception(
    1688             :             'Can not execute getEventByPushNotification() without a database');
    1689             :       }
    1690           0 :       final clientInfoMap = await database.getClient(clientName);
    1691           0 :       final token = clientInfoMap?.tryGet<String>('token');
    1692             :       if (token == null) {
    1693           0 :         throw Exception('Client is not logged in.');
    1694             :       }
    1695           0 :       accessToken = token;
    1696             :     }
    1697             : 
    1698           1 :     await ensureNotSoftLoggedOut();
    1699             : 
    1700             :     // Check if the notification contains an event at all:
    1701           1 :     final eventId = notification.eventId;
    1702           1 :     final roomId = notification.roomId;
    1703             :     if (eventId == null || roomId == null) return null;
    1704             : 
    1705             :     // Create the room object:
    1706           1 :     final room = getRoomById(roomId) ??
    1707           1 :         await database?.getSingleRoom(this, roomId) ??
    1708           1 :         Room(
    1709             :           id: roomId,
    1710             :           client: this,
    1711             :         );
    1712           1 :     final roomName = notification.roomName;
    1713           1 :     final roomAlias = notification.roomAlias;
    1714             :     if (roomName != null) {
    1715           2 :       room.setState(Event(
    1716             :         eventId: 'TEMP',
    1717             :         stateKey: '',
    1718             :         type: EventTypes.RoomName,
    1719           1 :         content: {'name': roomName},
    1720             :         room: room,
    1721             :         senderId: 'UNKNOWN',
    1722           1 :         originServerTs: DateTime.now(),
    1723             :       ));
    1724             :     }
    1725             :     if (roomAlias != null) {
    1726           2 :       room.setState(Event(
    1727             :         eventId: 'TEMP',
    1728             :         stateKey: '',
    1729             :         type: EventTypes.RoomCanonicalAlias,
    1730           1 :         content: {'alias': roomAlias},
    1731             :         room: room,
    1732             :         senderId: 'UNKNOWN',
    1733           1 :         originServerTs: DateTime.now(),
    1734             :       ));
    1735             :     }
    1736             : 
    1737             :     // Load the event from the notification or from the database or from server:
    1738             :     MatrixEvent? matrixEvent;
    1739           1 :     final content = notification.content;
    1740           1 :     final sender = notification.sender;
    1741           1 :     final type = notification.type;
    1742             :     if (content != null && sender != null && type != null) {
    1743           1 :       matrixEvent = MatrixEvent(
    1744             :         content: content,
    1745             :         senderId: sender,
    1746             :         type: type,
    1747           1 :         originServerTs: DateTime.now(),
    1748             :         eventId: eventId,
    1749             :         roomId: roomId,
    1750             :       );
    1751             :     }
    1752             :     matrixEvent ??= await database
    1753           1 :         ?.getEventById(eventId, room)
    1754           1 :         .timeout(timeoutForServerRequests);
    1755             : 
    1756             :     try {
    1757           1 :       matrixEvent ??= await getOneRoomEvent(roomId, eventId)
    1758           1 :           .timeout(timeoutForServerRequests);
    1759           0 :     } on MatrixException catch (_) {
    1760             :       // No access to the MatrixEvent. Search in /notifications
    1761           0 :       final notificationsResponse = await getNotifications();
    1762           0 :       matrixEvent ??= notificationsResponse.notifications
    1763           0 :           .firstWhereOrNull((notification) =>
    1764           0 :               notification.roomId == roomId &&
    1765           0 :               notification.event.eventId == eventId)
    1766           0 :           ?.event;
    1767             :     }
    1768             : 
    1769             :     if (matrixEvent == null) {
    1770           0 :       throw Exception('Unable to find event for this push notification!');
    1771             :     }
    1772             : 
    1773             :     // If the event was already in database, check if it has a read marker
    1774             :     // before displaying it.
    1775             :     if (returnNullIfSeen) {
    1776           3 :       if (room.fullyRead == matrixEvent.eventId) {
    1777             :         return null;
    1778             :       }
    1779             :       final readMarkerEvent = await database
    1780           2 :           ?.getEventById(room.fullyRead, room)
    1781           1 :           .timeout(timeoutForServerRequests);
    1782             :       if (readMarkerEvent != null &&
    1783           0 :           readMarkerEvent.originServerTs.isAfter(
    1784           0 :             matrixEvent.originServerTs
    1785             :               // As origin server timestamps are not always correct data in
    1786             :               // a federated environment, we add 10 minutes to the calculation
    1787             :               // to reduce the possibility that an event is marked as read which
    1788             :               // isn't.
    1789           0 :               ..add(Duration(minutes: 10)),
    1790             :           )) {
    1791             :         return null;
    1792             :       }
    1793             :     }
    1794             : 
    1795             :     // Load the sender of this event
    1796             :     try {
    1797             :       await room
    1798           2 :           .requestUser(matrixEvent.senderId)
    1799           1 :           .timeout(timeoutForServerRequests);
    1800             :     } catch (e, s) {
    1801           2 :       Logs().w('Unable to request user for push helper', e, s);
    1802           1 :       final senderDisplayName = notification.senderDisplayName;
    1803             :       if (senderDisplayName != null && sender != null) {
    1804           2 :         room.setState(User(sender, displayName: senderDisplayName, room: room));
    1805             :       }
    1806             :     }
    1807             : 
    1808             :     // Create Event object and decrypt if necessary
    1809           1 :     var event = Event.fromMatrixEvent(
    1810             :       matrixEvent,
    1811             :       room,
    1812             :       status: EventStatus.sent,
    1813             :     );
    1814             : 
    1815           1 :     final encryption = this.encryption;
    1816           2 :     if (event.type == EventTypes.Encrypted && encryption != null) {
    1817           0 :       var decrypted = await encryption.decryptRoomEvent(roomId, event);
    1818           0 :       if (decrypted.messageType == MessageTypes.BadEncrypted &&
    1819           0 :           prevBatch != null) {
    1820           0 :         await oneShotSync();
    1821           0 :         decrypted = await encryption.decryptRoomEvent(roomId, event);
    1822             :       }
    1823             :       event = decrypted;
    1824             :     }
    1825             : 
    1826             :     if (storeInDatabase) {
    1827           2 :       await database?.transaction(() async {
    1828           1 :         await database.storeEventUpdate(
    1829           1 :             EventUpdate(
    1830             :               roomID: roomId,
    1831             :               type: EventUpdateType.timeline,
    1832           1 :               content: event.toJson(),
    1833             :             ),
    1834             :             this);
    1835             :       });
    1836             :     }
    1837             : 
    1838             :     return event;
    1839             :   }
    1840             : 
    1841             :   /// Sets the user credentials and starts the synchronisation.
    1842             :   ///
    1843             :   /// Before you can connect you need at least an [accessToken], a [homeserver],
    1844             :   /// a [userID], a [deviceID], and a [deviceName].
    1845             :   ///
    1846             :   /// Usually you don't need to call this method yourself because [login()], [register()]
    1847             :   /// and even the constructor calls it.
    1848             :   ///
    1849             :   /// Sends [LoginState.loggedIn] to [onLoginStateChanged].
    1850             :   ///
    1851             :   /// If one of [newToken], [newUserID], [newDeviceID], [newDeviceName] is set then
    1852             :   /// all of them must be set! If you don't set them, this method will try to
    1853             :   /// get them from the database.
    1854             :   ///
    1855             :   /// Set [waitForFirstSync] and [waitUntilLoadCompletedLoaded] to false to speed this
    1856             :   /// up. You can then wait for `roomsLoading`, `_accountDataLoading` and
    1857             :   /// `userDeviceKeysLoading` where it is necessary.
    1858          32 :   Future<void> init({
    1859             :     String? newToken,
    1860             :     DateTime? newTokenExpiresAt,
    1861             :     String? newRefreshToken,
    1862             :     Uri? newHomeserver,
    1863             :     String? newUserID,
    1864             :     String? newDeviceName,
    1865             :     String? newDeviceID,
    1866             :     String? newOlmAccount,
    1867             :     bool waitForFirstSync = true,
    1868             :     bool waitUntilLoadCompletedLoaded = true,
    1869             : 
    1870             :     /// Will be called if the app performs a migration task from the [legacyDatabaseBuilder]
    1871             :     void Function()? onMigration,
    1872             :   }) async {
    1873             :     if ((newToken != null ||
    1874             :             newUserID != null ||
    1875             :             newDeviceID != null ||
    1876             :             newDeviceName != null) &&
    1877             :         (newToken == null ||
    1878             :             newUserID == null ||
    1879             :             newDeviceID == null ||
    1880             :             newDeviceName == null)) {
    1881           0 :       throw ClientInitPreconditionError(
    1882             :         'If one of [newToken, newUserID, newDeviceID, newDeviceName] is set then all of them must be set!',
    1883             :       );
    1884             :     }
    1885             : 
    1886          32 :     if (_initLock) {
    1887           0 :       throw ClientInitPreconditionError(
    1888             :         '[init()] has been called multiple times!',
    1889             :       );
    1890             :     }
    1891          32 :     _initLock = true;
    1892             :     String? olmAccount;
    1893             :     String? accessToken;
    1894             :     String? userID;
    1895             :     try {
    1896         128 :       Logs().i('Initialize client $clientName');
    1897          96 :       if (onLoginStateChanged.value == LoginState.loggedIn) {
    1898           0 :         throw ClientInitPreconditionError(
    1899             :           'User is already logged in! Call [logout()] first!',
    1900             :         );
    1901             :       }
    1902             : 
    1903          32 :       final databaseBuilder = this.databaseBuilder;
    1904             :       if (databaseBuilder != null) {
    1905          60 :         _database ??= await runBenchmarked<DatabaseApi>(
    1906             :           'Build database',
    1907          60 :           () async => await databaseBuilder(this),
    1908             :         );
    1909             :       }
    1910             : 
    1911          64 :       _groupCallSessionId = randomAlpha(12);
    1912             : 
    1913             :       /// while I would like to move these to a onLoginStateChanged stream listener
    1914             :       /// that might be too much overhead and you don't have any use of these
    1915             :       /// when you are logged out anyway. So we just invalidate them on next login
    1916          64 :       _serverConfigCache.invalidate();
    1917          64 :       _versionsCache.invalidate();
    1918             : 
    1919          92 :       final account = await this.database?.getClient(clientName);
    1920           1 :       newRefreshToken ??= account?.tryGet<String>('refresh_token');
    1921             :       // can have discovery_information so make sure it also has the proper
    1922             :       // account creds
    1923             :       if (account != null &&
    1924           1 :           account['homeserver_url'] != null &&
    1925           1 :           account['user_id'] != null &&
    1926           1 :           account['token'] != null) {
    1927           2 :         _id = account['client_id'];
    1928           3 :         homeserver = Uri.parse(account['homeserver_url']);
    1929           2 :         accessToken = this.accessToken = account['token'];
    1930             :         final tokenExpiresAtMs =
    1931           2 :             int.tryParse(account.tryGet<String>('token_expires_at') ?? '');
    1932           1 :         _accessTokenExpiresAt = tokenExpiresAtMs == null
    1933             :             ? null
    1934           0 :             : DateTime.fromMillisecondsSinceEpoch(tokenExpiresAtMs);
    1935           2 :         userID = _userID = account['user_id'];
    1936           2 :         _deviceID = account['device_id'];
    1937           2 :         _deviceName = account['device_name'];
    1938           2 :         _syncFilterId = account['sync_filter_id'];
    1939           2 :         _prevBatch = account['prev_batch'];
    1940           1 :         olmAccount = account['olm_account'];
    1941             :       }
    1942             :       if (newToken != null) {
    1943          32 :         accessToken = this.accessToken = newToken;
    1944          32 :         _accessTokenExpiresAt = newTokenExpiresAt;
    1945          32 :         homeserver = newHomeserver;
    1946          32 :         userID = _userID = newUserID;
    1947          32 :         _deviceID = newDeviceID;
    1948          32 :         _deviceName = newDeviceName;
    1949             :         olmAccount = newOlmAccount;
    1950             :       } else {
    1951           1 :         accessToken = this.accessToken = newToken ?? accessToken;
    1952           2 :         _accessTokenExpiresAt = newTokenExpiresAt ?? accessTokenExpiresAt;
    1953           2 :         homeserver = newHomeserver ?? homeserver;
    1954           1 :         userID = _userID = newUserID ?? userID;
    1955           2 :         _deviceID = newDeviceID ?? _deviceID;
    1956           2 :         _deviceName = newDeviceName ?? _deviceName;
    1957             :         olmAccount = newOlmAccount ?? olmAccount;
    1958             :       }
    1959             : 
    1960             :       // If we are refreshing the session, we are done here:
    1961          96 :       if (onLoginStateChanged.value == LoginState.softLoggedOut) {
    1962             :         if (newRefreshToken != null && accessToken != null && userID != null) {
    1963             :           // Store the new tokens:
    1964           0 :           await _database?.updateClient(
    1965           0 :             homeserver.toString(),
    1966             :             accessToken,
    1967           0 :             accessTokenExpiresAt,
    1968             :             newRefreshToken,
    1969             :             userID,
    1970           0 :             _deviceID,
    1971           0 :             _deviceName,
    1972           0 :             prevBatch,
    1973           0 :             encryption?.pickledOlmAccount,
    1974             :           );
    1975             :         }
    1976           0 :         onLoginStateChanged.add(LoginState.loggedIn);
    1977             :         return;
    1978             :       }
    1979             : 
    1980          32 :       if (accessToken == null || homeserver == null || userID == null) {
    1981           1 :         if (legacyDatabaseBuilder != null) {
    1982           1 :           await _migrateFromLegacyDatabase(onMigration: onMigration);
    1983           1 :           if (isLogged()) return;
    1984             :         }
    1985             :         // we aren't logged in
    1986           1 :         await encryption?.dispose();
    1987           1 :         _encryption = null;
    1988           2 :         onLoginStateChanged.add(LoginState.loggedOut);
    1989           2 :         Logs().i('User is not logged in.');
    1990           1 :         _initLock = false;
    1991             :         return;
    1992             :       }
    1993             : 
    1994          32 :       await encryption?.dispose();
    1995             :       try {
    1996             :         // make sure to throw an exception if libolm doesn't exist
    1997          32 :         await olm.init();
    1998          24 :         olm.get_library_version();
    1999          48 :         _encryption = Encryption(client: this);
    2000             :       } catch (e) {
    2001          24 :         Logs().e('Error initializing encryption $e');
    2002           8 :         await encryption?.dispose();
    2003           8 :         _encryption = null;
    2004             :       }
    2005          56 :       await encryption?.init(olmAccount);
    2006             : 
    2007          32 :       final database = this.database;
    2008             :       if (database != null) {
    2009          30 :         if (id != null) {
    2010           0 :           await database.updateClient(
    2011           0 :             homeserver.toString(),
    2012             :             accessToken,
    2013           0 :             accessTokenExpiresAt,
    2014             :             newRefreshToken,
    2015             :             userID,
    2016           0 :             _deviceID,
    2017           0 :             _deviceName,
    2018           0 :             prevBatch,
    2019           0 :             encryption?.pickledOlmAccount,
    2020             :           );
    2021             :         } else {
    2022          60 :           _id = await database.insertClient(
    2023          30 :             clientName,
    2024          60 :             homeserver.toString(),
    2025             :             accessToken,
    2026          30 :             accessTokenExpiresAt,
    2027             :             newRefreshToken,
    2028             :             userID,
    2029          30 :             _deviceID,
    2030          30 :             _deviceName,
    2031          30 :             prevBatch,
    2032          53 :             encryption?.pickledOlmAccount,
    2033             :           );
    2034             :         }
    2035          30 :         userDeviceKeysLoading = database
    2036          30 :             .getUserDeviceKeys(this)
    2037          90 :             .then((keys) => _userDeviceKeys = keys);
    2038         120 :         roomsLoading = database.getRoomList(this).then((rooms) {
    2039          30 :           _rooms = rooms;
    2040          30 :           _sortRooms();
    2041             :         });
    2042         120 :         _accountDataLoading = database.getAccountData().then((data) {
    2043          30 :           _accountData = data;
    2044          30 :           _updatePushrules();
    2045             :         });
    2046         120 :         _discoveryDataLoading = database.getWellKnown().then((data) {
    2047          30 :           _wellKnown = data;
    2048             :         });
    2049             :         // ignore: deprecated_member_use_from_same_package
    2050          60 :         presences.clear();
    2051             :         if (waitUntilLoadCompletedLoaded) {
    2052          30 :           await userDeviceKeysLoading;
    2053          30 :           await roomsLoading;
    2054          30 :           await _accountDataLoading;
    2055          30 :           await _discoveryDataLoading;
    2056             :         }
    2057             :       }
    2058          32 :       _initLock = false;
    2059          64 :       onLoginStateChanged.add(LoginState.loggedIn);
    2060          64 :       Logs().i(
    2061         128 :         'Successfully connected as ${userID.localpart} with ${homeserver.toString()}',
    2062             :       );
    2063             : 
    2064             :       /// Timeout of 0, so that we don't see a spinner for 30 seconds.
    2065          64 :       firstSyncReceived = _sync(timeout: Duration.zero);
    2066             :       if (waitForFirstSync) {
    2067          32 :         await firstSyncReceived;
    2068             :       }
    2069             :       return;
    2070           1 :     } on ClientInitPreconditionError {
    2071             :       rethrow;
    2072             :     } catch (e, s) {
    2073           2 :       Logs().wtf('Client initialization failed', e, s);
    2074           2 :       onLoginStateChanged.addError(e, s);
    2075           1 :       final clientInitException = ClientInitException(
    2076             :         e,
    2077           1 :         homeserver: homeserver,
    2078             :         accessToken: accessToken,
    2079             :         userId: userID,
    2080           1 :         deviceId: deviceID,
    2081           1 :         deviceName: deviceName,
    2082             :         olmAccount: olmAccount,
    2083             :       );
    2084           1 :       await clear();
    2085             :       throw clientInitException;
    2086             :     } finally {
    2087          32 :       _initLock = false;
    2088             :     }
    2089             :   }
    2090             : 
    2091             :   /// Used for testing only
    2092           1 :   void setUserId(String s) {
    2093           1 :     _userID = s;
    2094             :   }
    2095             : 
    2096             :   /// Resets all settings and stops the synchronisation.
    2097          10 :   Future<void> clear() async {
    2098          30 :     Logs().outputEvents.clear();
    2099             :     try {
    2100          10 :       await abortSync();
    2101          18 :       await database?.clear();
    2102          10 :       _backgroundSync = true;
    2103             :     } catch (e, s) {
    2104           2 :       Logs().e('Unable to clear database', e, s);
    2105             :     } finally {
    2106          18 :       await database?.delete();
    2107          10 :       _database = null;
    2108             :     }
    2109             : 
    2110          30 :     _id = accessToken = _syncFilterId =
    2111          50 :         homeserver = _userID = _deviceID = _deviceName = _prevBatch = null;
    2112          20 :     _rooms = [];
    2113          20 :     _eventsPendingDecryption.clear();
    2114          16 :     await encryption?.dispose();
    2115          10 :     _encryption = null;
    2116          20 :     onLoginStateChanged.add(LoginState.loggedOut);
    2117             :   }
    2118             : 
    2119             :   bool _backgroundSync = true;
    2120             :   Future<void>? _currentSync;
    2121             :   Future<void> _retryDelay = Future.value();
    2122             : 
    2123           0 :   bool get syncPending => _currentSync != null;
    2124             : 
    2125             :   /// Controls the background sync (automatically looping forever if turned on).
    2126             :   /// If you use soft logout, you need to manually call
    2127             :   /// `ensureNotSoftLoggedOut()` before doing any API request after setting
    2128             :   /// the background sync to false, as the soft logout is handeld automatically
    2129             :   /// in the sync loop.
    2130          26 :   set backgroundSync(bool enabled) {
    2131          26 :     _backgroundSync = enabled;
    2132          26 :     if (_backgroundSync) {
    2133           6 :       runInRoot(() async => _sync());
    2134             :     }
    2135             :   }
    2136             : 
    2137             :   /// Immediately start a sync and wait for completion.
    2138             :   /// If there is an active sync already, wait for the active sync instead.
    2139           1 :   Future<void> oneShotSync() {
    2140           1 :     return _sync();
    2141             :   }
    2142             : 
    2143             :   /// Pass a timeout to set how long the server waits before sending an empty response.
    2144             :   /// (Corresponds to the timeout param on the /sync request.)
    2145          32 :   Future<void> _sync({Duration? timeout}) {
    2146             :     final currentSync =
    2147         128 :         _currentSync ??= _innerSync(timeout: timeout).whenComplete(() {
    2148          32 :       _currentSync = null;
    2149          96 :       if (_backgroundSync && isLogged() && !_disposed) {
    2150          32 :         _sync();
    2151             :       }
    2152             :     });
    2153             :     return currentSync;
    2154             :   }
    2155             : 
    2156             :   /// Presence that is set on sync.
    2157             :   PresenceType? syncPresence;
    2158             : 
    2159          32 :   Future<void> _checkSyncFilter() async {
    2160          32 :     final userID = this.userID;
    2161          32 :     if (syncFilterId == null && userID != null) {
    2162             :       final syncFilterId =
    2163          96 :           _syncFilterId = await defineFilter(userID, syncFilter);
    2164          62 :       await database?.storeSyncFilterId(syncFilterId);
    2165             :     }
    2166             :     return;
    2167             :   }
    2168             : 
    2169             :   Future<void>? _handleSoftLogoutFuture;
    2170             : 
    2171           1 :   Future<void> _handleSoftLogout() async {
    2172           1 :     final onSoftLogout = this.onSoftLogout;
    2173             :     if (onSoftLogout == null) {
    2174           0 :       await logout();
    2175             :       return;
    2176             :     }
    2177             : 
    2178           2 :     _handleSoftLogoutFuture ??= () async {
    2179           2 :       onLoginStateChanged.add(LoginState.softLoggedOut);
    2180             :       try {
    2181           1 :         await onSoftLogout(this);
    2182           2 :         onLoginStateChanged.add(LoginState.loggedIn);
    2183             :       } catch (e, s) {
    2184           0 :         Logs().w('Unable to refresh session after soft logout', e, s);
    2185           0 :         await logout();
    2186             :         rethrow;
    2187             :       }
    2188           1 :     }();
    2189           1 :     await _handleSoftLogoutFuture;
    2190           1 :     _handleSoftLogoutFuture = null;
    2191             :   }
    2192             : 
    2193             :   /// Checks if the token expires in under [expiresIn] time and calls the
    2194             :   /// given `onSoftLogout()` if so. You have to provide `onSoftLogout` in the
    2195             :   /// Client constructor. Otherwise this will do nothing.
    2196          32 :   Future<void> ensureNotSoftLoggedOut(
    2197             :       [Duration expiresIn = const Duration(minutes: 1)]) async {
    2198          32 :     final tokenExpiresAt = accessTokenExpiresAt;
    2199          32 :     if (onSoftLogout != null &&
    2200             :         tokenExpiresAt != null &&
    2201           3 :         tokenExpiresAt.difference(DateTime.now()) <= expiresIn) {
    2202           0 :       await _handleSoftLogout();
    2203             :     }
    2204             :   }
    2205             : 
    2206             :   /// Pass a timeout to set how long the server waits before sending an empty response.
    2207             :   /// (Corresponds to the timeout param on the /sync request.)
    2208          32 :   Future<void> _innerSync({Duration? timeout}) async {
    2209          32 :     await _retryDelay;
    2210         128 :     _retryDelay = Future.delayed(Duration(seconds: syncErrorTimeoutSec));
    2211          96 :     if (!isLogged() || _disposed || _aborted) return;
    2212             :     try {
    2213          32 :       if (_initLock) {
    2214           0 :         Logs().d('Running sync while init isn\'t done yet, dropping request');
    2215             :         return;
    2216             :       }
    2217             :       Object? syncError;
    2218             : 
    2219             :       // The timeout we send to the server for the sync loop. It says to the
    2220             :       // server that we want to receive an empty sync response after this
    2221             :       // amount of time if nothing happens.
    2222             :       timeout ??= const Duration(seconds: 30);
    2223             : 
    2224          64 :       await ensureNotSoftLoggedOut(timeout * 2);
    2225             : 
    2226          32 :       await _checkSyncFilter();
    2227             : 
    2228          32 :       final syncRequest = sync(
    2229          32 :         filter: syncFilterId,
    2230          32 :         since: prevBatch,
    2231          32 :         timeout: timeout.inMilliseconds,
    2232          32 :         setPresence: syncPresence,
    2233         129 :       ).then((v) => Future<SyncUpdate?>.value(v)).catchError((e) {
    2234           1 :         if (e is MatrixException) {
    2235             :           syncError = e;
    2236             :         } else {
    2237           0 :           syncError = SyncConnectionException(e);
    2238             :         }
    2239             :         return null;
    2240             :       });
    2241          64 :       _currentSyncId = syncRequest.hashCode;
    2242          96 :       onSyncStatus.add(SyncStatusUpdate(SyncStatus.waitingForResponse));
    2243             : 
    2244             :       // The timeout for the response from the server. If we do not set a sync
    2245             :       // timeout (for initial sync) we give the server a longer time to
    2246             :       // responde.
    2247          32 :       final responseTimeout = timeout == Duration.zero
    2248             :           ? const Duration(minutes: 2)
    2249          32 :           : timeout + const Duration(seconds: 10);
    2250             : 
    2251          32 :       final syncResp = await syncRequest.timeout(responseTimeout);
    2252          96 :       onSyncStatus.add(SyncStatusUpdate(SyncStatus.processing));
    2253             :       if (syncResp == null) throw syncError ?? 'Unknown sync error';
    2254          96 :       if (_currentSyncId != syncRequest.hashCode) {
    2255          12 :         Logs()
    2256          12 :             .w('Current sync request ID has changed. Dropping this sync loop!');
    2257             :         return;
    2258             :       }
    2259             : 
    2260          32 :       final database = this.database;
    2261             :       if (database != null) {
    2262          30 :         await userDeviceKeysLoading;
    2263          30 :         await roomsLoading;
    2264          30 :         await _accountDataLoading;
    2265          90 :         _currentTransaction = database.transaction(() async {
    2266          30 :           await _handleSync(syncResp, direction: Direction.f);
    2267          90 :           if (prevBatch != syncResp.nextBatch) {
    2268          60 :             await database.storePrevBatch(syncResp.nextBatch);
    2269             :           }
    2270             :         });
    2271          30 :         await runBenchmarked(
    2272             :           'Process sync',
    2273          60 :           () async => await _currentTransaction,
    2274          30 :           syncResp.itemCount,
    2275             :         );
    2276             :       } else {
    2277           4 :         await _handleSync(syncResp, direction: Direction.f);
    2278             :       }
    2279          64 :       if (_disposed || _aborted) return;
    2280          64 :       _prevBatch = syncResp.nextBatch;
    2281          96 :       onSyncStatus.add(SyncStatusUpdate(SyncStatus.cleaningUp));
    2282             :       // ignore: unawaited_futures
    2283          30 :       database?.deleteOldFiles(
    2284         120 :           DateTime.now().subtract(Duration(days: 30)).millisecondsSinceEpoch);
    2285          32 :       await updateUserDeviceKeys();
    2286          32 :       if (encryptionEnabled) {
    2287          48 :         encryption?.onSync();
    2288             :       }
    2289             : 
    2290             :       // try to process the to_device queue
    2291             :       try {
    2292          32 :         await processToDeviceQueue();
    2293             :       } catch (_) {} // we want to dispose any errors this throws
    2294             : 
    2295          64 :       _retryDelay = Future.value();
    2296          96 :       onSyncStatus.add(SyncStatusUpdate(SyncStatus.finished));
    2297           1 :     } on MatrixException catch (e, s) {
    2298           3 :       onSyncStatus.add(SyncStatusUpdate(SyncStatus.error,
    2299           1 :           error: SdkError(exception: e, stackTrace: s)));
    2300           2 :       if (e.error == MatrixError.M_UNKNOWN_TOKEN) {
    2301           3 :         if (e.raw.tryGet<bool>('soft_logout') == true) {
    2302           2 :           Logs().w(
    2303             :             'The user has been soft logged out! Calling client.onSoftLogout() if present.',
    2304             :           );
    2305           1 :           await _handleSoftLogout();
    2306             :         } else {
    2307           0 :           Logs().w('The user has been logged out!');
    2308           0 :           await clear();
    2309             :         }
    2310             :       }
    2311           0 :     } on SyncConnectionException catch (e, s) {
    2312           0 :       Logs().w('Syncloop failed: Client has not connection to the server');
    2313           0 :       onSyncStatus.add(SyncStatusUpdate(SyncStatus.error,
    2314           0 :           error: SdkError(exception: e, stackTrace: s)));
    2315             :     } catch (e, s) {
    2316           0 :       if (!isLogged() || _disposed || _aborted) return;
    2317           0 :       Logs().e('Error during processing events', e, s);
    2318           0 :       onSyncStatus.add(SyncStatusUpdate(SyncStatus.error,
    2319           0 :           error: SdkError(
    2320           0 :               exception: e is Exception ? e : Exception(e), stackTrace: s)));
    2321             :     }
    2322             :   }
    2323             : 
    2324             :   /// Use this method only for testing utilities!
    2325          18 :   Future<void> handleSync(SyncUpdate sync, {Direction? direction}) async {
    2326             :     // ensure we don't upload keys because someone forgot to set a key count
    2327          36 :     sync.deviceOneTimeKeysCount ??= {
    2328          46 :       'signed_curve25519': encryption?.olmManager.maxNumberOfOneTimeKeys ?? 100,
    2329             :     };
    2330          18 :     await _handleSync(sync, direction: direction);
    2331             :   }
    2332             : 
    2333          32 :   Future<void> _handleSync(SyncUpdate sync, {Direction? direction}) async {
    2334          32 :     final syncToDevice = sync.toDevice;
    2335             :     if (syncToDevice != null) {
    2336          32 :       await _handleToDeviceEvents(syncToDevice);
    2337             :     }
    2338             : 
    2339          32 :     if (sync.rooms != null) {
    2340          64 :       final join = sync.rooms?.join;
    2341             :       if (join != null) {
    2342          32 :         await _handleRooms(join, direction: direction);
    2343             :       }
    2344             :       // We need to handle leave before invite. If you decline an invite and
    2345             :       // then get another invite to the same room, Synapse will include the
    2346             :       // room both in invite and leave. If you get an invite and then leave, it
    2347             :       // will only be included in leave.
    2348          64 :       final leave = sync.rooms?.leave;
    2349             :       if (leave != null) {
    2350          32 :         await _handleRooms(leave, direction: direction);
    2351             :       }
    2352          64 :       final invite = sync.rooms?.invite;
    2353             :       if (invite != null) {
    2354          32 :         await _handleRooms(invite, direction: direction);
    2355             :       }
    2356             :     }
    2357         114 :     for (final newPresence in sync.presence ?? <Presence>[]) {
    2358          32 :       final cachedPresence = CachedPresence.fromMatrixEvent(newPresence);
    2359             :       // ignore: deprecated_member_use_from_same_package
    2360          96 :       presences[newPresence.senderId] = cachedPresence;
    2361             :       // ignore: deprecated_member_use_from_same_package
    2362          64 :       onPresence.add(newPresence);
    2363          64 :       onPresenceChanged.add(cachedPresence);
    2364          92 :       await database?.storePresence(newPresence.senderId, cachedPresence);
    2365             :     }
    2366         115 :     for (final newAccountData in sync.accountData ?? []) {
    2367          62 :       await database?.storeAccountData(
    2368          30 :         newAccountData.type,
    2369          60 :         jsonEncode(newAccountData.content),
    2370             :       );
    2371          96 :       accountData[newAccountData.type] = newAccountData;
    2372             :       // ignore: deprecated_member_use_from_same_package
    2373          64 :       onAccountData.add(newAccountData);
    2374             : 
    2375          64 :       if (newAccountData.type == EventTypes.PushRules) {
    2376          32 :         _updatePushrules();
    2377             :       }
    2378             :     }
    2379             : 
    2380          32 :     final syncDeviceLists = sync.deviceLists;
    2381             :     if (syncDeviceLists != null) {
    2382          32 :       await _handleDeviceListsEvents(syncDeviceLists);
    2383             :     }
    2384          32 :     if (encryptionEnabled) {
    2385          48 :       encryption?.handleDeviceOneTimeKeysCount(
    2386          48 :           sync.deviceOneTimeKeysCount, sync.deviceUnusedFallbackKeyTypes);
    2387             :     }
    2388          32 :     _sortRooms();
    2389          64 :     onSync.add(sync);
    2390             :   }
    2391             : 
    2392          32 :   Future<void> _handleDeviceListsEvents(DeviceListsUpdate deviceLists) async {
    2393          64 :     if (deviceLists.changed is List) {
    2394          96 :       for (final userId in deviceLists.changed ?? []) {
    2395          64 :         final userKeys = _userDeviceKeys[userId];
    2396             :         if (userKeys != null) {
    2397           1 :           userKeys.outdated = true;
    2398           2 :           await database?.storeUserDeviceKeysInfo(userId, true);
    2399             :         }
    2400             :       }
    2401          96 :       for (final userId in deviceLists.left ?? []) {
    2402          64 :         if (_userDeviceKeys.containsKey(userId)) {
    2403           0 :           _userDeviceKeys.remove(userId);
    2404             :         }
    2405             :       }
    2406             :     }
    2407             :   }
    2408             : 
    2409          32 :   Future<void> _handleToDeviceEvents(List<BasicEventWithSender> events) async {
    2410          32 :     final Map<String, List<String>> roomsWithNewKeyToSessionId = {};
    2411          32 :     final List<ToDeviceEvent> callToDeviceEvents = [];
    2412          64 :     for (final event in events) {
    2413          64 :       var toDeviceEvent = ToDeviceEvent.fromJson(event.toJson());
    2414         128 :       Logs().v('Got to_device event of type ${toDeviceEvent.type}');
    2415          32 :       if (encryptionEnabled) {
    2416          48 :         if (toDeviceEvent.type == EventTypes.Encrypted) {
    2417          48 :           toDeviceEvent = await encryption!.decryptToDeviceEvent(toDeviceEvent);
    2418          96 :           Logs().v('Decrypted type is: ${toDeviceEvent.type}');
    2419             : 
    2420             :           /// collect new keys so that we can find those events in the decryption queue
    2421          48 :           if (toDeviceEvent.type == EventTypes.ForwardedRoomKey ||
    2422          48 :               toDeviceEvent.type == EventTypes.RoomKey) {
    2423          46 :             final roomId = event.content['room_id'];
    2424          46 :             final sessionId = event.content['session_id'];
    2425          23 :             if (roomId is String && sessionId is String) {
    2426           0 :               (roomsWithNewKeyToSessionId[roomId] ??= []).add(sessionId);
    2427             :             }
    2428             :           }
    2429             :         }
    2430          48 :         await encryption?.handleToDeviceEvent(toDeviceEvent);
    2431             :       }
    2432          96 :       if (toDeviceEvent.type.startsWith(CallConstants.callEventsRegxp)) {
    2433           0 :         callToDeviceEvents.add(toDeviceEvent);
    2434             :       }
    2435          64 :       onToDeviceEvent.add(toDeviceEvent);
    2436             :     }
    2437             : 
    2438          32 :     if (callToDeviceEvents.isNotEmpty) {
    2439           0 :       onCallEvents.add(callToDeviceEvents);
    2440             :     }
    2441             : 
    2442             :     // emit updates for all events in the queue
    2443          32 :     for (final entry in roomsWithNewKeyToSessionId.entries) {
    2444           0 :       final roomId = entry.key;
    2445           0 :       final sessionIds = entry.value;
    2446             : 
    2447           0 :       final room = getRoomById(roomId);
    2448             :       if (room != null) {
    2449           0 :         final List<BasicEvent> events = [];
    2450           0 :         for (final event in _eventsPendingDecryption) {
    2451           0 :           if (event.event.roomID != roomId) continue;
    2452           0 :           if (!sessionIds.contains(
    2453           0 :               event.event.content['content']?['session_id'])) continue;
    2454             : 
    2455           0 :           final decryptedEvent = await event.event.decrypt(room);
    2456           0 :           if (decryptedEvent.content.tryGet<String>('type') !=
    2457             :               EventTypes.Encrypted) {
    2458           0 :             events.add(BasicEvent.fromJson(decryptedEvent.content));
    2459             :           }
    2460             :         }
    2461             : 
    2462           0 :         await _handleRoomEvents(
    2463             :             room, events, EventUpdateType.decryptedTimelineQueue);
    2464             : 
    2465           0 :         _eventsPendingDecryption.removeWhere((e) => events.any(
    2466           0 :             (decryptedEvent) =>
    2467           0 :                 decryptedEvent.content['event_id'] ==
    2468           0 :                 e.event.content['event_id']));
    2469             :       }
    2470             :     }
    2471          64 :     _eventsPendingDecryption.removeWhere((e) => e.timedOut);
    2472             :   }
    2473             : 
    2474          32 :   Future<void> _handleRooms(Map<String, SyncRoomUpdate> rooms,
    2475             :       {Direction? direction}) async {
    2476             :     var handledRooms = 0;
    2477          64 :     for (final entry in rooms.entries) {
    2478          96 :       onSyncStatus.add(SyncStatusUpdate(
    2479             :         SyncStatus.processing,
    2480          96 :         progress: ++handledRooms / rooms.length,
    2481             :       ));
    2482          32 :       final id = entry.key;
    2483          32 :       final syncRoomUpdate = entry.value;
    2484             : 
    2485             :       // Is the timeline limited? Then all previous messages should be
    2486             :       // removed from the database!
    2487          32 :       if (syncRoomUpdate is JoinedRoomUpdate &&
    2488          96 :           syncRoomUpdate.timeline?.limited == true) {
    2489          62 :         await database?.deleteTimelineForRoom(id);
    2490             :       }
    2491          32 :       final room = await _updateRoomsByRoomUpdate(id, syncRoomUpdate);
    2492             : 
    2493             :       final timelineUpdateType = direction != null
    2494          32 :           ? (direction == Direction.b
    2495             :               ? EventUpdateType.history
    2496             :               : EventUpdateType.timeline)
    2497             :           : EventUpdateType.timeline;
    2498             : 
    2499             :       /// Handle now all room events and save them in the database
    2500          32 :       if (syncRoomUpdate is JoinedRoomUpdate) {
    2501          32 :         final state = syncRoomUpdate.state;
    2502             : 
    2503          32 :         if (state != null && state.isNotEmpty) {
    2504             :           // TODO: This method seems to be comperatively slow for some updates
    2505          32 :           await _handleRoomEvents(
    2506             :             room,
    2507             :             state,
    2508             :             EventUpdateType.state,
    2509             :           );
    2510             :         }
    2511             : 
    2512          64 :         final timelineEvents = syncRoomUpdate.timeline?.events;
    2513          32 :         if (timelineEvents != null && timelineEvents.isNotEmpty) {
    2514          32 :           await _handleRoomEvents(room, timelineEvents, timelineUpdateType);
    2515             :         }
    2516             : 
    2517          32 :         final ephemeral = syncRoomUpdate.ephemeral;
    2518          32 :         if (ephemeral != null && ephemeral.isNotEmpty) {
    2519             :           // TODO: This method seems to be comperatively slow for some updates
    2520          32 :           await _handleEphemerals(
    2521             :             room,
    2522             :             ephemeral,
    2523             :           );
    2524             :         }
    2525             : 
    2526          32 :         final accountData = syncRoomUpdate.accountData;
    2527          32 :         if (accountData != null && accountData.isNotEmpty) {
    2528          32 :           await _handleRoomEvents(
    2529             :             room,
    2530             :             accountData,
    2531             :             EventUpdateType.accountData,
    2532             :           );
    2533             :         }
    2534             :       }
    2535             : 
    2536          32 :       if (syncRoomUpdate is LeftRoomUpdate) {
    2537          64 :         final timelineEvents = syncRoomUpdate.timeline?.events;
    2538          32 :         if (timelineEvents != null && timelineEvents.isNotEmpty) {
    2539          32 :           await _handleRoomEvents(room, timelineEvents, timelineUpdateType,
    2540             :               store: false);
    2541             :         }
    2542          32 :         final accountData = syncRoomUpdate.accountData;
    2543          32 :         if (accountData != null && accountData.isNotEmpty) {
    2544          32 :           await _handleRoomEvents(
    2545             :               room, accountData, EventUpdateType.accountData,
    2546             :               store: false);
    2547             :         }
    2548          32 :         final state = syncRoomUpdate.state;
    2549          32 :         if (state != null && state.isNotEmpty) {
    2550          32 :           await _handleRoomEvents(room, state, EventUpdateType.state,
    2551             :               store: false);
    2552             :         }
    2553             :       }
    2554             : 
    2555          32 :       if (syncRoomUpdate is InvitedRoomUpdate) {
    2556          32 :         final state = syncRoomUpdate.inviteState;
    2557          32 :         if (state != null && state.isNotEmpty) {
    2558          32 :           await _handleRoomEvents(room, state, EventUpdateType.inviteState);
    2559             :         }
    2560             :       }
    2561          92 :       await database?.storeRoomUpdate(id, syncRoomUpdate, room.lastEvent, this);
    2562             :     }
    2563             :   }
    2564             : 
    2565          32 :   Future<void> _handleEphemerals(Room room, List<BasicRoomEvent> events) async {
    2566          32 :     final List<ReceiptEventContent> receipts = [];
    2567             : 
    2568          64 :     for (final event in events) {
    2569          64 :       await _handleRoomEvents(room, [event], EventUpdateType.ephemeral);
    2570             : 
    2571             :       // Receipt events are deltas between two states. We will create a
    2572             :       // fake room account data event for this and store the difference
    2573             :       // there.
    2574          64 :       if (event.type != 'm.receipt') continue;
    2575             : 
    2576          96 :       receipts.add(ReceiptEventContent.fromJson(event.content));
    2577             :     }
    2578             : 
    2579          32 :     if (receipts.isNotEmpty) {
    2580          32 :       final receiptStateContent = room.receiptState;
    2581             : 
    2582          64 :       for (final e in receipts) {
    2583          32 :         await receiptStateContent.update(e, room);
    2584             :       }
    2585             : 
    2586          32 :       await _handleRoomEvents(
    2587             :           room,
    2588          32 :           [
    2589          32 :             BasicRoomEvent(
    2590             :               type: LatestReceiptState.eventType,
    2591          32 :               roomId: room.id,
    2592          32 :               content: receiptStateContent.toJson(),
    2593             :             )
    2594             :           ],
    2595             :           EventUpdateType.accountData);
    2596             :     }
    2597             :   }
    2598             : 
    2599             :   /// Stores event that came down /sync but didn't get decrypted because of missing keys yet.
    2600             :   final List<_EventPendingDecryption> _eventsPendingDecryption = [];
    2601             : 
    2602          32 :   Future<void> _handleRoomEvents(
    2603             :       Room room, List<BasicEvent> events, EventUpdateType type,
    2604             :       {bool store = true}) async {
    2605             :     // Calling events can be omitted if they are outdated from the same sync. So
    2606             :     // we collect them first before we handle them.
    2607          32 :     final callEvents = <Event>[];
    2608             : 
    2609          64 :     for (final event in events) {
    2610             :       // The client must ignore any new m.room.encryption event to prevent
    2611             :       // man-in-the-middle attacks!
    2612          64 :       if ((event.type == EventTypes.Encryption &&
    2613          32 :           room.encrypted &&
    2614           3 :           event.content.tryGet<String>('algorithm') !=
    2615             :               room
    2616           1 :                   .getState(EventTypes.Encryption)
    2617           1 :                   ?.content
    2618           1 :                   .tryGet<String>('algorithm'))) {
    2619             :         continue;
    2620             :       }
    2621             : 
    2622             :       var update =
    2623          96 :           EventUpdate(roomID: room.id, type: type, content: event.toJson());
    2624          67 :       if (event.type == EventTypes.Encrypted && encryptionEnabled) {
    2625           2 :         update = await update.decrypt(room);
    2626             : 
    2627             :         // if the event failed to decrypt, add it to the queue
    2628           6 :         if (update.content.tryGet<String>('type') == EventTypes.Encrypted) {
    2629           8 :           _eventsPendingDecryption.add(_EventPendingDecryption(EventUpdate(
    2630           2 :               roomID: update.roomID,
    2631             :               type: EventUpdateType.decryptedTimelineQueue,
    2632           2 :               content: update.content)));
    2633             :         }
    2634             :       }
    2635             : 
    2636             :       // Any kind of member change? We should invalidate the profile then:
    2637          96 :       if (event is StrippedStateEvent && event.type == EventTypes.RoomMember) {
    2638          32 :         final userId = event.stateKey;
    2639             :         if (userId != null) {
    2640             :           // We do not re-request the profile here as this would lead to
    2641             :           // an unknown amount of network requests as we never know how many
    2642             :           // member change events can come down in a single sync update.
    2643          62 :           await database?.markUserProfileAsOutdated(userId);
    2644          64 :           onUserProfileUpdate.add(userId);
    2645             :         }
    2646             :       }
    2647             : 
    2648          64 :       if (event.type == EventTypes.Message &&
    2649          32 :           !room.isDirectChat &&
    2650          32 :           database != null &&
    2651          30 :           event is MatrixEvent &&
    2652          60 :           room.getState(EventTypes.RoomMember, event.senderId) == null) {
    2653             :         // In order to correctly render room list previews we need to fetch the member from the database
    2654          90 :         final user = await database?.getUser(event.senderId, room);
    2655             :         if (user != null) {
    2656          30 :           room.setState(user);
    2657             :         }
    2658             :       }
    2659          32 :       _updateRoomsByEventUpdate(room, update);
    2660          32 :       if (type != EventUpdateType.ephemeral && store) {
    2661          62 :         await database?.storeEventUpdate(update, this);
    2662             :       }
    2663          32 :       if (encryptionEnabled) {
    2664          48 :         await encryption?.handleEventUpdate(update);
    2665             :       }
    2666          64 :       onEvent.add(update);
    2667             : 
    2668          32 :       if (prevBatch != null &&
    2669          14 :           (type == EventUpdateType.timeline ||
    2670           6 :               type == EventUpdateType.decryptedTimelineQueue)) {
    2671          14 :         if ((update.content
    2672          14 :                 .tryGet<String>('type')
    2673          28 :                 ?.startsWith(CallConstants.callEventsRegxp) ??
    2674             :             false)) {
    2675           4 :           final callEvent = Event.fromJson(update.content, room);
    2676           2 :           callEvents.add(callEvent);
    2677             :         }
    2678             :       }
    2679             :     }
    2680          32 :     if (callEvents.isNotEmpty) {
    2681           4 :       onCallEvents.add(callEvents);
    2682             :     }
    2683             :   }
    2684             : 
    2685             :   /// stores when we last checked for stale calls
    2686             :   DateTime lastStaleCallRun = DateTime(0);
    2687             : 
    2688          32 :   Future<Room> _updateRoomsByRoomUpdate(
    2689             :       String roomId, SyncRoomUpdate chatUpdate) async {
    2690             :     // Update the chat list item.
    2691             :     // Search the room in the rooms
    2692         160 :     final roomIndex = rooms.indexWhere((r) => r.id == roomId);
    2693          64 :     final found = roomIndex != -1;
    2694          32 :     final membership = chatUpdate is LeftRoomUpdate
    2695             :         ? Membership.leave
    2696          32 :         : chatUpdate is InvitedRoomUpdate
    2697             :             ? Membership.invite
    2698             :             : Membership.join;
    2699             : 
    2700             :     final room = found
    2701          24 :         ? rooms[roomIndex]
    2702          32 :         : (chatUpdate is JoinedRoomUpdate
    2703          32 :             ? Room(
    2704             :                 id: roomId,
    2705             :                 membership: membership,
    2706          64 :                 prev_batch: chatUpdate.timeline?.prevBatch,
    2707             :                 highlightCount:
    2708          64 :                     chatUpdate.unreadNotifications?.highlightCount ?? 0,
    2709             :                 notificationCount:
    2710          64 :                     chatUpdate.unreadNotifications?.notificationCount ?? 0,
    2711          32 :                 summary: chatUpdate.summary,
    2712             :                 client: this,
    2713             :               )
    2714          32 :             : Room(id: roomId, membership: membership, client: this));
    2715             : 
    2716             :     // Does the chat already exist in the list rooms?
    2717          32 :     if (!found && membership != Membership.leave) {
    2718             :       // Check if the room is not in the rooms in the invited list
    2719          64 :       if (_archivedRooms.isNotEmpty) {
    2720          12 :         _archivedRooms.removeWhere((archive) => archive.room.id == roomId);
    2721             :       }
    2722          96 :       final position = membership == Membership.invite ? 0 : rooms.length;
    2723             :       // Add the new chat to the list
    2724          64 :       rooms.insert(position, room);
    2725             :     }
    2726             :     // If the membership is "leave" then remove the item and stop here
    2727          12 :     else if (found && membership == Membership.leave) {
    2728           0 :       rooms.removeAt(roomIndex);
    2729             : 
    2730             :       // in order to keep the archive in sync, add left room to archive
    2731           0 :       if (chatUpdate is LeftRoomUpdate) {
    2732           0 :         await _storeArchivedRoom(room.id, chatUpdate, leftRoom: room);
    2733             :       }
    2734             :     }
    2735             :     // Update notification, highlight count and/or additional information
    2736             :     else if (found &&
    2737          12 :         chatUpdate is JoinedRoomUpdate &&
    2738          48 :         (rooms[roomIndex].membership != membership ||
    2739          48 :             rooms[roomIndex].notificationCount !=
    2740          12 :                 (chatUpdate.unreadNotifications?.notificationCount ?? 0) ||
    2741          48 :             rooms[roomIndex].highlightCount !=
    2742          12 :                 (chatUpdate.unreadNotifications?.highlightCount ?? 0) ||
    2743          12 :             chatUpdate.summary != null ||
    2744          24 :             chatUpdate.timeline?.prevBatch != null)) {
    2745          12 :       rooms[roomIndex].membership = membership;
    2746          12 :       rooms[roomIndex].notificationCount =
    2747           5 :           chatUpdate.unreadNotifications?.notificationCount ?? 0;
    2748          12 :       rooms[roomIndex].highlightCount =
    2749           5 :           chatUpdate.unreadNotifications?.highlightCount ?? 0;
    2750           8 :       if (chatUpdate.timeline?.prevBatch != null) {
    2751          10 :         rooms[roomIndex].prev_batch = chatUpdate.timeline?.prevBatch;
    2752             :       }
    2753             : 
    2754           4 :       final summary = chatUpdate.summary;
    2755             :       if (summary != null) {
    2756           4 :         final roomSummaryJson = rooms[roomIndex].summary.toJson()
    2757           2 :           ..addAll(summary.toJson());
    2758           4 :         rooms[roomIndex].summary = RoomSummary.fromJson(roomSummaryJson);
    2759             :       }
    2760             :       // ignore: deprecated_member_use_from_same_package
    2761          28 :       rooms[roomIndex].onUpdate.add(rooms[roomIndex].id);
    2762           8 :       if ((chatUpdate.timeline?.limited ?? false) &&
    2763           1 :           requestHistoryOnLimitedTimeline) {
    2764           0 :         Logs().v(
    2765           0 :             'Limited timeline for ${rooms[roomIndex].id} request history now');
    2766           0 :         runInRoot(rooms[roomIndex].requestHistory);
    2767             :       }
    2768             :     }
    2769             :     return room;
    2770             :   }
    2771             : 
    2772          32 :   void _updateRoomsByEventUpdate(Room room, EventUpdate eventUpdate) {
    2773          64 :     if (eventUpdate.type == EventUpdateType.history) return;
    2774             : 
    2775          32 :     switch (eventUpdate.type) {
    2776          32 :       case EventUpdateType.inviteState:
    2777          96 :         room.setState(StrippedStateEvent.fromJson(eventUpdate.content));
    2778             :         break;
    2779          32 :       case EventUpdateType.state:
    2780          32 :       case EventUpdateType.timeline:
    2781          64 :         final event = Event.fromJson(eventUpdate.content, room);
    2782             : 
    2783             :         // Update the room state:
    2784          32 :         if (event.stateKey != null &&
    2785         128 :             (!room.partial || importantStateEvents.contains(event.type))) {
    2786          32 :           room.setState(event);
    2787             :         }
    2788          64 :         if (eventUpdate.type != EventUpdateType.timeline) break;
    2789             : 
    2790             :         // If last event is null or not a valid room preview event anyway,
    2791             :         // just use this:
    2792          32 :         if (room.lastEvent == null) {
    2793          32 :           room.lastEvent = event;
    2794             :           break;
    2795             :         }
    2796             : 
    2797             :         // Is this event redacting the last event?
    2798          64 :         if (event.type == EventTypes.Redaction &&
    2799             :             ({
    2800           4 :               room.lastEvent?.eventId,
    2801           4 :               room.lastEvent?.relationshipEventId
    2802           2 :             }.contains(
    2803           6 :                 event.redacts ?? event.content.tryGet<String>('redacts')))) {
    2804           4 :           room.lastEvent?.setRedactionEvent(event);
    2805             :           break;
    2806             :         }
    2807             : 
    2808             :         // Is this event an edit of the last event? Otherwise ignore it.
    2809          64 :         if (event.relationshipType == RelationshipTypes.edit) {
    2810          12 :           if (event.relationshipEventId == room.lastEvent?.eventId ||
    2811           9 :               (room.lastEvent?.relationshipType == RelationshipTypes.edit &&
    2812           6 :                   event.relationshipEventId ==
    2813           6 :                       room.lastEvent?.relationshipEventId)) {
    2814           3 :             room.lastEvent = event;
    2815             :           }
    2816             :           break;
    2817             :         }
    2818             : 
    2819             :         // Is this event of an important type for the last event?
    2820          96 :         if (!roomPreviewLastEvents.contains(event.type)) break;
    2821             : 
    2822             :         // Event is a valid new lastEvent:
    2823          32 :         room.lastEvent = event;
    2824             : 
    2825             :         break;
    2826          32 :       case EventUpdateType.accountData:
    2827         128 :         room.roomAccountData[eventUpdate.content['type']] =
    2828          64 :             BasicRoomEvent.fromJson(eventUpdate.content);
    2829             :         break;
    2830          32 :       case EventUpdateType.ephemeral:
    2831          96 :         room.setEphemeral(BasicRoomEvent.fromJson(eventUpdate.content));
    2832             :         break;
    2833           0 :       case EventUpdateType.history:
    2834           0 :       case EventUpdateType.decryptedTimelineQueue:
    2835             :         break;
    2836             :     }
    2837             :     // ignore: deprecated_member_use_from_same_package
    2838          96 :     room.onUpdate.add(room.id);
    2839             :   }
    2840             : 
    2841             :   bool _sortLock = false;
    2842             : 
    2843             :   /// If `true` then unread rooms are pinned at the top of the room list.
    2844             :   bool pinUnreadRooms;
    2845             : 
    2846             :   /// If `true` then unread rooms are pinned at the top of the room list.
    2847             :   bool pinInvitedRooms;
    2848             : 
    2849             :   /// The compare function how the rooms should be sorted internally. By default
    2850             :   /// rooms are sorted by timestamp of the last m.room.message event or the last
    2851             :   /// event if there is no known message.
    2852          64 :   RoomSorter get sortRoomsBy => (a, b) {
    2853          32 :         if (pinInvitedRooms &&
    2854          96 :             a.membership != b.membership &&
    2855         192 :             [a.membership, b.membership].any((m) => m == Membership.invite)) {
    2856          96 :           return a.membership == Membership.invite ? -1 : 1;
    2857          96 :         } else if (a.isFavourite != b.isFavourite) {
    2858           4 :           return a.isFavourite ? -1 : 1;
    2859          32 :         } else if (pinUnreadRooms &&
    2860           0 :             a.notificationCount != b.notificationCount) {
    2861           0 :           return b.notificationCount.compareTo(a.notificationCount);
    2862             :         } else {
    2863          64 :           return b.timeCreated.millisecondsSinceEpoch
    2864          96 :               .compareTo(a.timeCreated.millisecondsSinceEpoch);
    2865             :         }
    2866             :       };
    2867             : 
    2868          32 :   void _sortRooms() {
    2869         128 :     if (_sortLock || rooms.length < 2) return;
    2870          32 :     _sortLock = true;
    2871          96 :     rooms.sort(sortRoomsBy);
    2872          32 :     _sortLock = false;
    2873             :   }
    2874             : 
    2875             :   Future? userDeviceKeysLoading;
    2876             :   Future? roomsLoading;
    2877             :   Future? _accountDataLoading;
    2878             :   Future? _discoveryDataLoading;
    2879             :   Future? firstSyncReceived;
    2880             : 
    2881          46 :   Future? get accountDataLoading => _accountDataLoading;
    2882             : 
    2883           0 :   Future? get wellKnownLoading => _discoveryDataLoading;
    2884             : 
    2885             :   /// A map of known device keys per user.
    2886          50 :   Map<String, DeviceKeysList> get userDeviceKeys => _userDeviceKeys;
    2887             :   Map<String, DeviceKeysList> _userDeviceKeys = {};
    2888             : 
    2889             :   /// A list of all not verified and not blocked device keys. Clients should
    2890             :   /// display a warning if this list is not empty and suggest the user to
    2891             :   /// verify or block those devices.
    2892           0 :   List<DeviceKeys> get unverifiedDevices {
    2893           0 :     final userId = userID;
    2894           0 :     if (userId == null) return [];
    2895           0 :     return userDeviceKeys[userId]
    2896           0 :             ?.deviceKeys
    2897           0 :             .values
    2898           0 :             .where((deviceKey) => !deviceKey.verified && !deviceKey.blocked)
    2899           0 :             .toList() ??
    2900           0 :         [];
    2901             :   }
    2902             : 
    2903             :   /// Gets user device keys by its curve25519 key. Returns null if it isn't found
    2904          23 :   DeviceKeys? getUserDeviceKeysByCurve25519Key(String senderKey) {
    2905          56 :     for (final user in userDeviceKeys.values) {
    2906          20 :       final device = user.deviceKeys.values
    2907          40 :           .firstWhereOrNull((e) => e.curve25519Key == senderKey);
    2908             :       if (device != null) {
    2909             :         return device;
    2910             :       }
    2911             :     }
    2912             :     return null;
    2913             :   }
    2914             : 
    2915          30 :   Future<Set<String>> _getUserIdsInEncryptedRooms() async {
    2916             :     final userIds = <String>{};
    2917          60 :     for (final room in rooms) {
    2918          90 :       if (room.encrypted && room.membership == Membership.join) {
    2919             :         try {
    2920          30 :           final userList = await room.requestParticipants();
    2921          60 :           for (final user in userList) {
    2922          30 :             if ([Membership.join, Membership.invite]
    2923          60 :                 .contains(user.membership)) {
    2924          60 :               userIds.add(user.id);
    2925             :             }
    2926             :           }
    2927             :         } catch (e, s) {
    2928           0 :           Logs().e('[E2EE] Failed to fetch participants', e, s);
    2929             :         }
    2930             :       }
    2931             :     }
    2932             :     return userIds;
    2933             :   }
    2934             : 
    2935             :   final Map<String, DateTime> _keyQueryFailures = {};
    2936             : 
    2937          32 :   Future<void> updateUserDeviceKeys({Set<String>? additionalUsers}) async {
    2938             :     try {
    2939          32 :       final database = this.database;
    2940          32 :       if (!isLogged() || database == null) return;
    2941          30 :       final dbActions = <Future<dynamic> Function()>[];
    2942          30 :       final trackedUserIds = await _getUserIdsInEncryptedRooms();
    2943          30 :       if (!isLogged()) return;
    2944          60 :       trackedUserIds.add(userID!);
    2945           1 :       if (additionalUsers != null) trackedUserIds.addAll(additionalUsers);
    2946             : 
    2947             :       // Remove all userIds we no longer need to track the devices of.
    2948          30 :       _userDeviceKeys
    2949          48 :           .removeWhere((String userId, v) => !trackedUserIds.contains(userId));
    2950             : 
    2951             :       // Check if there are outdated device key lists. Add it to the set.
    2952          30 :       final outdatedLists = <String, List<String>>{};
    2953          61 :       for (final userId in (additionalUsers ?? <String>[])) {
    2954           2 :         outdatedLists[userId] = [];
    2955             :       }
    2956          60 :       for (final userId in trackedUserIds) {
    2957             :         final deviceKeysList =
    2958          90 :             _userDeviceKeys[userId] ??= DeviceKeysList(userId, this);
    2959          90 :         final failure = _keyQueryFailures[userId.domain];
    2960             : 
    2961             :         // deviceKeysList.outdated is not nullable but we have seen this error
    2962             :         // in production: `Failed assertion: boolean expression must not be null`
    2963             :         // So this could either be a null safety bug in Dart or a result of
    2964             :         // using unsound null safety. The extra equal check `!= false` should
    2965             :         // save us here.
    2966          60 :         if (deviceKeysList.outdated != false &&
    2967             :             (failure == null ||
    2968           0 :                 DateTime.now()
    2969           0 :                     .subtract(Duration(minutes: 5))
    2970           0 :                     .isAfter(failure))) {
    2971          60 :           outdatedLists[userId] = [];
    2972             :         }
    2973             :       }
    2974             : 
    2975          30 :       if (outdatedLists.isNotEmpty) {
    2976             :         // Request the missing device key lists from the server.
    2977          30 :         final response = await queryKeys(outdatedLists, timeout: 10000);
    2978          30 :         if (!isLogged()) return;
    2979             : 
    2980          30 :         final deviceKeys = response.deviceKeys;
    2981             :         if (deviceKeys != null) {
    2982          60 :           for (final rawDeviceKeyListEntry in deviceKeys.entries) {
    2983          30 :             final userId = rawDeviceKeyListEntry.key;
    2984             :             final userKeys =
    2985          90 :                 _userDeviceKeys[userId] ??= DeviceKeysList(userId, this);
    2986          60 :             final oldKeys = Map<String, DeviceKeys>.from(userKeys.deviceKeys);
    2987          60 :             userKeys.deviceKeys = {};
    2988             :             for (final rawDeviceKeyEntry
    2989          90 :                 in rawDeviceKeyListEntry.value.entries) {
    2990          30 :               final deviceId = rawDeviceKeyEntry.key;
    2991             : 
    2992             :               // Set the new device key for this device
    2993          30 :               final entry = DeviceKeys.fromMatrixDeviceKeys(
    2994          63 :                   rawDeviceKeyEntry.value, this, oldKeys[deviceId]?.lastActive);
    2995          30 :               final ed25519Key = entry.ed25519Key;
    2996          30 :               final curve25519Key = entry.curve25519Key;
    2997          30 :               if (entry.isValid &&
    2998          60 :                   deviceId == entry.deviceId &&
    2999             :                   ed25519Key != null &&
    3000             :                   curve25519Key != null) {
    3001             :                 // Check if deviceId or deviceKeys are known
    3002          30 :                 if (!oldKeys.containsKey(deviceId)) {
    3003             :                   final oldPublicKeys =
    3004          30 :                       await database.deviceIdSeen(userId, deviceId);
    3005             :                   if (oldPublicKeys != null &&
    3006           4 :                       oldPublicKeys != curve25519Key + ed25519Key) {
    3007           2 :                     Logs().w(
    3008             :                         'Already seen Device ID has been added again. This might be an attack!');
    3009             :                     continue;
    3010             :                   }
    3011          30 :                   final oldDeviceId = await database.publicKeySeen(ed25519Key);
    3012           2 :                   if (oldDeviceId != null && oldDeviceId != deviceId) {
    3013           0 :                     Logs().w(
    3014             :                         'Already seen ED25519 has been added again. This might be an attack!');
    3015             :                     continue;
    3016             :                   }
    3017             :                   final oldDeviceId2 =
    3018          30 :                       await database.publicKeySeen(curve25519Key);
    3019           2 :                   if (oldDeviceId2 != null && oldDeviceId2 != deviceId) {
    3020           0 :                     Logs().w(
    3021             :                         'Already seen Curve25519 has been added again. This might be an attack!');
    3022             :                     continue;
    3023             :                   }
    3024          30 :                   await database.addSeenDeviceId(
    3025          30 :                       userId, deviceId, curve25519Key + ed25519Key);
    3026          30 :                   await database.addSeenPublicKey(ed25519Key, deviceId);
    3027          30 :                   await database.addSeenPublicKey(curve25519Key, deviceId);
    3028             :                 }
    3029             : 
    3030             :                 // is this a new key or the same one as an old one?
    3031             :                 // better store an update - the signatures might have changed!
    3032          30 :                 final oldKey = oldKeys[deviceId];
    3033             :                 if (oldKey == null ||
    3034           9 :                     (oldKey.ed25519Key == entry.ed25519Key &&
    3035           9 :                         oldKey.curve25519Key == entry.curve25519Key)) {
    3036             :                   if (oldKey != null) {
    3037             :                     // be sure to save the verified status
    3038           6 :                     entry.setDirectVerified(oldKey.directVerified);
    3039           6 :                     entry.blocked = oldKey.blocked;
    3040           6 :                     entry.validSignatures = oldKey.validSignatures;
    3041             :                   }
    3042          60 :                   userKeys.deviceKeys[deviceId] = entry;
    3043          60 :                   if (deviceId == deviceID &&
    3044          90 :                       entry.ed25519Key == fingerprintKey) {
    3045             :                     // Always trust the own device
    3046          23 :                     entry.setDirectVerified(true);
    3047             :                   }
    3048          90 :                   dbActions.add(() => database.storeUserDeviceKey(
    3049             :                         userId,
    3050             :                         deviceId,
    3051          60 :                         json.encode(entry.toJson()),
    3052          30 :                         entry.directVerified,
    3053          30 :                         entry.blocked,
    3054          60 :                         entry.lastActive.millisecondsSinceEpoch,
    3055             :                       ));
    3056           0 :                 } else if (oldKeys.containsKey(deviceId)) {
    3057             :                   // This shouldn't ever happen. The same device ID has gotten
    3058             :                   // a new public key. So we ignore the update. TODO: ask krille
    3059             :                   // if we should instead use the new key with unknown verified / blocked status
    3060           0 :                   userKeys.deviceKeys[deviceId] = oldKeys[deviceId]!;
    3061             :                 }
    3062             :               } else {
    3063           0 :                 Logs().w('Invalid device ${entry.userId}:${entry.deviceId}');
    3064             :               }
    3065             :             }
    3066             :             // delete old/unused entries
    3067          33 :             for (final oldDeviceKeyEntry in oldKeys.entries) {
    3068           3 :               final deviceId = oldDeviceKeyEntry.key;
    3069           6 :               if (!userKeys.deviceKeys.containsKey(deviceId)) {
    3070             :                 // we need to remove an old key
    3071             :                 dbActions
    3072           3 :                     .add(() => database.removeUserDeviceKey(userId, deviceId));
    3073             :               }
    3074             :             }
    3075          30 :             userKeys.outdated = false;
    3076             :             dbActions
    3077          90 :                 .add(() => database.storeUserDeviceKeysInfo(userId, false));
    3078             :           }
    3079             :         }
    3080             :         // next we parse and persist the cross signing keys
    3081          30 :         final crossSigningTypes = {
    3082          30 :           'master': response.masterKeys,
    3083          30 :           'self_signing': response.selfSigningKeys,
    3084          30 :           'user_signing': response.userSigningKeys,
    3085             :         };
    3086          60 :         for (final crossSigningKeysEntry in crossSigningTypes.entries) {
    3087          30 :           final keyType = crossSigningKeysEntry.key;
    3088          30 :           final keys = crossSigningKeysEntry.value;
    3089             :           if (keys == null) {
    3090             :             continue;
    3091             :           }
    3092          60 :           for (final crossSigningKeyListEntry in keys.entries) {
    3093          30 :             final userId = crossSigningKeyListEntry.key;
    3094             :             final userKeys =
    3095          60 :                 _userDeviceKeys[userId] ??= DeviceKeysList(userId, this);
    3096             :             final oldKeys =
    3097          60 :                 Map<String, CrossSigningKey>.from(userKeys.crossSigningKeys);
    3098          60 :             userKeys.crossSigningKeys = {};
    3099             :             // add the types we aren't handling atm back
    3100          60 :             for (final oldEntry in oldKeys.entries) {
    3101          90 :               if (!oldEntry.value.usage.contains(keyType)) {
    3102         120 :                 userKeys.crossSigningKeys[oldEntry.key] = oldEntry.value;
    3103             :               } else {
    3104             :                 // There is a previous cross-signing key with  this usage, that we no
    3105             :                 // longer need/use. Clear it from the database.
    3106           6 :                 dbActions.add(() =>
    3107           6 :                     database.removeUserCrossSigningKey(userId, oldEntry.key));
    3108             :               }
    3109             :             }
    3110          30 :             final entry = CrossSigningKey.fromMatrixCrossSigningKey(
    3111          30 :                 crossSigningKeyListEntry.value, this);
    3112          30 :             final publicKey = entry.publicKey;
    3113          30 :             if (entry.isValid && publicKey != null) {
    3114          30 :               final oldKey = oldKeys[publicKey];
    3115           9 :               if (oldKey == null || oldKey.ed25519Key == entry.ed25519Key) {
    3116             :                 if (oldKey != null) {
    3117             :                   // be sure to save the verification status
    3118           6 :                   entry.setDirectVerified(oldKey.directVerified);
    3119           6 :                   entry.blocked = oldKey.blocked;
    3120           6 :                   entry.validSignatures = oldKey.validSignatures;
    3121             :                 }
    3122          60 :                 userKeys.crossSigningKeys[publicKey] = entry;
    3123             :               } else {
    3124             :                 // This shouldn't ever happen. The same device ID has gotten
    3125             :                 // a new public key. So we ignore the update. TODO: ask krille
    3126             :                 // if we should instead use the new key with unknown verified / blocked status
    3127           0 :                 userKeys.crossSigningKeys[publicKey] = oldKey;
    3128             :               }
    3129          90 :               dbActions.add(() => database.storeUserCrossSigningKey(
    3130             :                     userId,
    3131             :                     publicKey,
    3132          60 :                     json.encode(entry.toJson()),
    3133          30 :                     entry.directVerified,
    3134          30 :                     entry.blocked,
    3135             :                   ));
    3136             :             }
    3137          90 :             _userDeviceKeys[userId]?.outdated = false;
    3138             :             dbActions
    3139          90 :                 .add(() => database.storeUserDeviceKeysInfo(userId, false));
    3140             :           }
    3141             :         }
    3142             : 
    3143             :         // now process all the failures
    3144          30 :         if (response.failures != null) {
    3145          90 :           for (final failureDomain in response.failures?.keys ?? <String>[]) {
    3146           0 :             _keyQueryFailures[failureDomain] = DateTime.now();
    3147             :           }
    3148             :         }
    3149             :       }
    3150             : 
    3151          30 :       if (dbActions.isNotEmpty) {
    3152          30 :         if (!isLogged()) return;
    3153          60 :         await database.transaction(() async {
    3154          60 :           for (final f in dbActions) {
    3155          30 :             await f();
    3156             :           }
    3157             :         });
    3158             :       }
    3159             :     } catch (e, s) {
    3160           0 :       Logs().e('[LibOlm] Unable to update user device keys', e, s);
    3161             :     }
    3162             :   }
    3163             : 
    3164             :   bool _toDeviceQueueNeedsProcessing = true;
    3165             : 
    3166             :   /// Processes the to_device queue and tries to send every entry.
    3167             :   /// This function MAY throw an error, which just means the to_device queue wasn't
    3168             :   /// proccessed all the way.
    3169          32 :   Future<void> processToDeviceQueue() async {
    3170          32 :     final database = this.database;
    3171          30 :     if (database == null || !_toDeviceQueueNeedsProcessing) {
    3172             :       return;
    3173             :     }
    3174          30 :     final entries = await database.getToDeviceEventQueue();
    3175          30 :     if (entries.isEmpty) {
    3176          30 :       _toDeviceQueueNeedsProcessing = false;
    3177             :       return;
    3178             :     }
    3179           2 :     for (final entry in entries) {
    3180             :       // Convert the Json Map to the correct format regarding
    3181             :       // https: //matrix.org/docs/spec/client_server/r0.6.1#put-matrix-client-r0-sendtodevice-eventtype-txnid
    3182           3 :       final data = entry.content.map((k, v) =>
    3183           1 :           MapEntry<String, Map<String, Map<String, dynamic>>>(
    3184             :               k,
    3185           3 :               (v as Map).map((k, v) => MapEntry<String, Map<String, dynamic>>(
    3186           1 :                   k, Map<String, dynamic>.from(v)))));
    3187             : 
    3188             :       try {
    3189           3 :         await super.sendToDevice(entry.type, entry.txnId, data);
    3190           1 :       } on MatrixException catch (e) {
    3191           0 :         Logs().w(
    3192           0 :             '[To-Device] failed to to_device message from the queue to the server. Ignoring error: $e');
    3193           0 :         Logs().w('Payload: $data');
    3194             :       }
    3195           2 :       await database.deleteFromToDeviceQueue(entry.id);
    3196             :     }
    3197             :   }
    3198             : 
    3199             :   /// Sends a raw to_device event with a [eventType], a [txnId] and a content
    3200             :   /// [messages]. Before sending, it tries to re-send potentially queued
    3201             :   /// to_device events and adds the current one to the queue, should it fail.
    3202          10 :   @override
    3203             :   Future<void> sendToDevice(
    3204             :     String eventType,
    3205             :     String txnId,
    3206             :     Map<String, Map<String, Map<String, dynamic>>> messages,
    3207             :   ) async {
    3208             :     try {
    3209          10 :       await processToDeviceQueue();
    3210          10 :       await super.sendToDevice(eventType, txnId, messages);
    3211             :     } catch (e, s) {
    3212           2 :       Logs().w(
    3213             :           '[Client] Problem while sending to_device event, retrying later...',
    3214             :           e,
    3215             :           s);
    3216           1 :       final database = this.database;
    3217             :       if (database != null) {
    3218           1 :         _toDeviceQueueNeedsProcessing = true;
    3219           1 :         await database.insertIntoToDeviceQueue(
    3220           1 :             eventType, txnId, json.encode(messages));
    3221             :       }
    3222             :       rethrow;
    3223             :     }
    3224             :   }
    3225             : 
    3226             :   /// Send an (unencrypted) to device [message] of a specific [eventType] to all
    3227             :   /// devices of a set of [users].
    3228           2 :   Future<void> sendToDevicesOfUserIds(
    3229             :     Set<String> users,
    3230             :     String eventType,
    3231             :     Map<String, dynamic> message, {
    3232             :     String? messageId,
    3233             :   }) async {
    3234             :     // Send with send-to-device messaging
    3235           2 :     final data = <String, Map<String, Map<String, dynamic>>>{};
    3236           3 :     for (final user in users) {
    3237           2 :       data[user] = {'*': message};
    3238             :     }
    3239           2 :     await sendToDevice(
    3240           2 :         eventType, messageId ?? generateUniqueTransactionId(), data);
    3241             :     return;
    3242             :   }
    3243             : 
    3244             :   final MultiLock<DeviceKeys> _sendToDeviceEncryptedLock = MultiLock();
    3245             : 
    3246             :   /// Sends an encrypted [message] of this [eventType] to these [deviceKeys].
    3247           9 :   Future<void> sendToDeviceEncrypted(
    3248             :     List<DeviceKeys> deviceKeys,
    3249             :     String eventType,
    3250             :     Map<String, dynamic> message, {
    3251             :     String? messageId,
    3252             :     bool onlyVerified = false,
    3253             :   }) async {
    3254           9 :     final encryption = this.encryption;
    3255           9 :     if (!encryptionEnabled || encryption == null) return;
    3256             :     // Don't send this message to blocked devices, and if specified onlyVerified
    3257             :     // then only send it to verified devices
    3258           9 :     if (deviceKeys.isNotEmpty) {
    3259          18 :       deviceKeys.removeWhere((DeviceKeys deviceKeys) =>
    3260           9 :           deviceKeys.blocked ||
    3261          42 :           (deviceKeys.userId == userID && deviceKeys.deviceId == deviceID) ||
    3262           0 :           (onlyVerified && !deviceKeys.verified));
    3263           9 :       if (deviceKeys.isEmpty) return;
    3264             :     }
    3265             : 
    3266             :     // So that we can guarantee order of encrypted to_device messages to be preserved we
    3267             :     // must ensure that we don't attempt to encrypt multiple concurrent to_device messages
    3268             :     // to the same device at the same time.
    3269             :     // A failure to do so can result in edge-cases where encryption and sending order of
    3270             :     // said to_device messages does not match up, resulting in an olm session corruption.
    3271             :     // As we send to multiple devices at the same time, we may only proceed here if the lock for
    3272             :     // *all* of them is freed and lock *all* of them while sending.
    3273             : 
    3274             :     try {
    3275          18 :       await _sendToDeviceEncryptedLock.lock(deviceKeys);
    3276             : 
    3277             :       // Send with send-to-device messaging
    3278           9 :       final data = await encryption.encryptToDeviceMessage(
    3279             :         deviceKeys,
    3280             :         eventType,
    3281             :         message,
    3282             :       );
    3283             :       eventType = EventTypes.Encrypted;
    3284           9 :       await sendToDevice(
    3285           9 :           eventType, messageId ?? generateUniqueTransactionId(), data);
    3286             :     } finally {
    3287          18 :       _sendToDeviceEncryptedLock.unlock(deviceKeys);
    3288             :     }
    3289             :   }
    3290             : 
    3291             :   /// Sends an encrypted [message] of this [eventType] to these [deviceKeys].
    3292             :   /// This request happens partly in the background and partly in the
    3293             :   /// foreground. It automatically chunks sending to device keys based on
    3294             :   /// activity.
    3295           6 :   Future<void> sendToDeviceEncryptedChunked(
    3296             :     List<DeviceKeys> deviceKeys,
    3297             :     String eventType,
    3298             :     Map<String, dynamic> message,
    3299             :   ) async {
    3300           6 :     if (!encryptionEnabled) return;
    3301             :     // be sure to copy our device keys list
    3302           6 :     deviceKeys = List<DeviceKeys>.from(deviceKeys);
    3303          10 :     deviceKeys.removeWhere((DeviceKeys k) =>
    3304          19 :         k.blocked || (k.userId == userID && k.deviceId == deviceID));
    3305           6 :     if (deviceKeys.isEmpty) return;
    3306           4 :     message = message.copy(); // make sure we deep-copy the message
    3307             :     // make sure all the olm sessions are loaded from database
    3308          16 :     Logs().v('Sending to device chunked... (${deviceKeys.length} devices)');
    3309             :     // sort so that devices we last received messages from get our message first
    3310          16 :     deviceKeys.sort((keyA, keyB) => keyB.lastActive.compareTo(keyA.lastActive));
    3311             :     // and now send out in chunks of 20
    3312             :     const chunkSize = 20;
    3313             : 
    3314             :     // first we send out all the chunks that we await
    3315             :     var i = 0;
    3316             :     // we leave this in a for-loop for now, so that we can easily adjust the break condition
    3317             :     // based on other things, if we want to hard-`await` more devices in the future
    3318          16 :     for (; i < deviceKeys.length && i <= 0; i += chunkSize) {
    3319          12 :       Logs().v('Sending chunk $i...');
    3320           4 :       final chunk = deviceKeys.sublist(
    3321             :           i,
    3322          12 :           i + chunkSize > deviceKeys.length
    3323           4 :               ? deviceKeys.length
    3324           1 :               : i + chunkSize);
    3325             :       // and send
    3326           4 :       await sendToDeviceEncrypted(chunk, eventType, message);
    3327             :     }
    3328             :     // now send out the background chunks
    3329           8 :     if (i < deviceKeys.length) {
    3330             :       // ignore: unawaited_futures
    3331           1 :       () async {
    3332           3 :         for (; i < deviceKeys.length; i += chunkSize) {
    3333             :           // wait 50ms to not freeze the UI
    3334           2 :           await Future.delayed(Duration(milliseconds: 50));
    3335           3 :           Logs().v('Sending chunk $i...');
    3336           1 :           final chunk = deviceKeys.sublist(
    3337             :               i,
    3338           3 :               i + chunkSize > deviceKeys.length
    3339           1 :                   ? deviceKeys.length
    3340           0 :                   : i + chunkSize);
    3341             :           // and send
    3342           1 :           await sendToDeviceEncrypted(chunk, eventType, message);
    3343             :         }
    3344           1 :       }();
    3345             :     }
    3346             :   }
    3347             : 
    3348             :   /// Whether all push notifications are muted using the [.m.rule.master]
    3349             :   /// rule of the push rules: https://matrix.org/docs/spec/client_server/r0.6.0#m-rule-master
    3350           0 :   bool get allPushNotificationsMuted {
    3351             :     final Map<String, Object?>? globalPushRules =
    3352           0 :         _accountData[EventTypes.PushRules]
    3353           0 :             ?.content
    3354           0 :             .tryGetMap<String, Object?>('global');
    3355             :     if (globalPushRules == null) return false;
    3356             : 
    3357           0 :     final globalPushRulesOverride = globalPushRules.tryGetList('override');
    3358             :     if (globalPushRulesOverride != null) {
    3359           0 :       for (final pushRule in globalPushRulesOverride) {
    3360           0 :         if (pushRule['rule_id'] == '.m.rule.master') {
    3361           0 :           return pushRule['enabled'];
    3362             :         }
    3363             :       }
    3364             :     }
    3365             :     return false;
    3366             :   }
    3367             : 
    3368           1 :   Future<void> setMuteAllPushNotifications(bool muted) async {
    3369           1 :     await setPushRuleEnabled(
    3370             :       'global',
    3371             :       PushRuleKind.override,
    3372             :       '.m.rule.master',
    3373             :       muted,
    3374             :     );
    3375             :     return;
    3376             :   }
    3377             : 
    3378             :   /// Changes the password. You should either set oldPasswort or another authentication flow.
    3379           1 :   @override
    3380             :   Future<void> changePassword(
    3381             :     String newPassword, {
    3382             :     String? oldPassword,
    3383             :     AuthenticationData? auth,
    3384             :     bool? logoutDevices,
    3385             :   }) async {
    3386           1 :     final userID = this.userID;
    3387             :     try {
    3388             :       if (oldPassword != null && userID != null) {
    3389           1 :         auth = AuthenticationPassword(
    3390           1 :           identifier: AuthenticationUserIdentifier(user: userID),
    3391             :           password: oldPassword,
    3392             :         );
    3393             :       }
    3394           1 :       await super.changePassword(newPassword,
    3395             :           auth: auth, logoutDevices: logoutDevices);
    3396           0 :     } on MatrixException catch (matrixException) {
    3397           0 :       if (!matrixException.requireAdditionalAuthentication) {
    3398             :         rethrow;
    3399             :       }
    3400           0 :       if (matrixException.authenticationFlows?.length != 1 ||
    3401           0 :           !(matrixException.authenticationFlows?.first.stages
    3402           0 :                   .contains(AuthenticationTypes.password) ??
    3403             :               false)) {
    3404             :         rethrow;
    3405             :       }
    3406             :       if (oldPassword == null || userID == null) {
    3407             :         rethrow;
    3408             :       }
    3409           0 :       return changePassword(
    3410             :         newPassword,
    3411           0 :         auth: AuthenticationPassword(
    3412           0 :           identifier: AuthenticationUserIdentifier(user: userID),
    3413             :           password: oldPassword,
    3414           0 :           session: matrixException.session,
    3415             :         ),
    3416             :         logoutDevices: logoutDevices,
    3417             :       );
    3418             :     } catch (_) {
    3419             :       rethrow;
    3420             :     }
    3421             :   }
    3422             : 
    3423             :   /// Clear all local cached messages, room information and outbound group
    3424             :   /// sessions and perform a new clean sync.
    3425           2 :   Future<void> clearCache() async {
    3426           2 :     await abortSync();
    3427           2 :     _prevBatch = null;
    3428           4 :     rooms.clear();
    3429           4 :     await database?.clearCache();
    3430           6 :     encryption?.keyManager.clearOutboundGroupSessions();
    3431           4 :     _eventsPendingDecryption.clear();
    3432           4 :     onCacheCleared.add(true);
    3433             :     // Restart the syncloop
    3434           2 :     backgroundSync = true;
    3435             :   }
    3436             : 
    3437             :   /// A list of mxids of users who are ignored.
    3438           1 :   List<String> get ignoredUsers =>
    3439           3 :       List<String>.from(_accountData['m.ignored_user_list']
    3440           1 :               ?.content
    3441           1 :               .tryGetMap<String, Object?>('ignored_users')
    3442           1 :               ?.keys ??
    3443           1 :           <String>[]);
    3444             : 
    3445             :   /// Ignore another user. This will clear the local cached messages to
    3446             :   /// hide all previous messages from this user.
    3447           1 :   Future<void> ignoreUser(String userId) async {
    3448           1 :     if (!userId.isValidMatrixId) {
    3449           0 :       throw Exception('$userId is not a valid mxid!');
    3450             :     }
    3451           3 :     await setAccountData(userID!, 'm.ignored_user_list', {
    3452           1 :       'ignored_users': Map.fromEntries(
    3453           6 :           (ignoredUsers..add(userId)).map((key) => MapEntry(key, {}))),
    3454             :     });
    3455           1 :     await clearCache();
    3456             :     return;
    3457             :   }
    3458             : 
    3459             :   /// Unignore a user. This will clear the local cached messages and request
    3460             :   /// them again from the server to avoid gaps in the timeline.
    3461           1 :   Future<void> unignoreUser(String userId) async {
    3462           1 :     if (!userId.isValidMatrixId) {
    3463           0 :       throw Exception('$userId is not a valid mxid!');
    3464             :     }
    3465           2 :     if (!ignoredUsers.contains(userId)) {
    3466           0 :       throw Exception('$userId is not in the ignore list!');
    3467             :     }
    3468           3 :     await setAccountData(userID!, 'm.ignored_user_list', {
    3469           1 :       'ignored_users': Map.fromEntries(
    3470           3 :           (ignoredUsers..remove(userId)).map((key) => MapEntry(key, {}))),
    3471             :     });
    3472           1 :     await clearCache();
    3473             :     return;
    3474             :   }
    3475             : 
    3476             :   /// The newest presence of this user if there is any. Fetches it from the
    3477             :   /// database first and then from the server if necessary or returns offline.
    3478           2 :   Future<CachedPresence> fetchCurrentPresence(
    3479             :     String userId, {
    3480             :     bool fetchOnlyFromCached = false,
    3481             :   }) async {
    3482             :     // ignore: deprecated_member_use_from_same_package
    3483           4 :     final cachedPresence = presences[userId];
    3484             :     if (cachedPresence != null) {
    3485             :       return cachedPresence;
    3486             :     }
    3487             : 
    3488           0 :     final dbPresence = await database?.getPresence(userId);
    3489             :     // ignore: deprecated_member_use_from_same_package
    3490           0 :     if (dbPresence != null) return presences[userId] = dbPresence;
    3491             : 
    3492           0 :     if (fetchOnlyFromCached) return CachedPresence.neverSeen(userId);
    3493             : 
    3494             :     try {
    3495           0 :       final result = await getPresence(userId);
    3496           0 :       final presence = CachedPresence.fromPresenceResponse(result, userId);
    3497           0 :       await database?.storePresence(userId, presence);
    3498             :       // ignore: deprecated_member_use_from_same_package
    3499           0 :       return presences[userId] = presence;
    3500             :     } catch (e) {
    3501           0 :       final presence = CachedPresence.neverSeen(userId);
    3502           0 :       await database?.storePresence(userId, presence);
    3503             :       // ignore: deprecated_member_use_from_same_package
    3504           0 :       return presences[userId] = presence;
    3505             :     }
    3506             :   }
    3507             : 
    3508             :   bool _disposed = false;
    3509             :   bool _aborted = false;
    3510          78 :   Future _currentTransaction = Future.sync(() => {});
    3511             : 
    3512             :   /// Blackholes any ongoing sync call. Currently ongoing sync *processing* is
    3513             :   /// still going to be finished, new data is ignored.
    3514          26 :   Future<void> abortSync() async {
    3515          26 :     _aborted = true;
    3516          26 :     backgroundSync = false;
    3517          52 :     _currentSyncId = -1;
    3518             :     try {
    3519          26 :       await _currentTransaction;
    3520             :     } catch (_) {
    3521             :       // No-OP
    3522             :     }
    3523          26 :     _currentSync = null;
    3524             :     // reset _aborted for being able to restart the sync.
    3525          26 :     _aborted = false;
    3526             :   }
    3527             : 
    3528             :   /// Stops the synchronization and closes the database. After this
    3529             :   /// you can safely make this Client instance null.
    3530          23 :   Future<void> dispose({bool closeDatabase = true}) async {
    3531          23 :     _disposed = true;
    3532          23 :     await abortSync();
    3533          43 :     await encryption?.dispose();
    3534          23 :     _encryption = null;
    3535             :     try {
    3536             :       if (closeDatabase) {
    3537          21 :         final database = _database;
    3538          21 :         _database = null;
    3539             :         await database
    3540          19 :             ?.close()
    3541          19 :             .catchError((e, s) => Logs().w('Failed to close database: ', e, s));
    3542             :       }
    3543             :     } catch (error, stacktrace) {
    3544           0 :       Logs().w('Failed to close database: ', error, stacktrace);
    3545             :     }
    3546             :     return;
    3547             :   }
    3548             : 
    3549           1 :   Future<void> _migrateFromLegacyDatabase({
    3550             :     void Function()? onMigration,
    3551             :   }) async {
    3552           2 :     Logs().i('Check legacy database for migration data...');
    3553           2 :     final legacyDatabase = await legacyDatabaseBuilder?.call(this);
    3554           2 :     final migrateClient = await legacyDatabase?.getClient(clientName);
    3555           1 :     final database = this.database;
    3556             : 
    3557             :     if (migrateClient == null || legacyDatabase == null || database == null) {
    3558           0 :       await legacyDatabase?.close();
    3559           0 :       _initLock = false;
    3560             :       return;
    3561             :     }
    3562           2 :     Logs().i('Found data in the legacy database!');
    3563           0 :     onMigration?.call();
    3564           2 :     _id = migrateClient['client_id'];
    3565             :     final tokenExpiresAtMs =
    3566           2 :         int.tryParse(migrateClient.tryGet<String>('token_expires_at') ?? '');
    3567           1 :     await database.insertClient(
    3568           1 :       clientName,
    3569           1 :       migrateClient['homeserver_url'],
    3570           1 :       migrateClient['token'],
    3571             :       tokenExpiresAtMs == null
    3572             :           ? null
    3573           0 :           : DateTime.fromMillisecondsSinceEpoch(tokenExpiresAtMs),
    3574           1 :       migrateClient['refresh_token'],
    3575           1 :       migrateClient['user_id'],
    3576           1 :       migrateClient['device_id'],
    3577           1 :       migrateClient['device_name'],
    3578             :       null,
    3579           1 :       migrateClient['olm_account'],
    3580             :     );
    3581           2 :     Logs().d('Migrate SSSSCache...');
    3582           2 :     for (final type in cacheTypes) {
    3583           1 :       final ssssCache = await legacyDatabase.getSSSSCache(type);
    3584             :       if (ssssCache != null) {
    3585           0 :         Logs().d('Migrate $type...');
    3586           0 :         await database.storeSSSSCache(
    3587             :           type,
    3588           0 :           ssssCache.keyId ?? '',
    3589           0 :           ssssCache.ciphertext ?? '',
    3590           0 :           ssssCache.content ?? '',
    3591             :         );
    3592             :       }
    3593             :     }
    3594           2 :     Logs().d('Migrate OLM sessions...');
    3595             :     try {
    3596           1 :       final olmSessions = await legacyDatabase.getAllOlmSessions();
    3597           2 :       for (final identityKey in olmSessions.keys) {
    3598           1 :         final sessions = olmSessions[identityKey]!;
    3599           2 :         for (final sessionId in sessions.keys) {
    3600           1 :           final session = sessions[sessionId]!;
    3601           1 :           await database.storeOlmSession(
    3602             :             identityKey,
    3603           1 :             session['session_id'] as String,
    3604           1 :             session['pickle'] as String,
    3605           1 :             session['last_received'] as int,
    3606             :           );
    3607             :         }
    3608             :       }
    3609             :     } catch (e, s) {
    3610           0 :       Logs().e('Unable to migrate OLM sessions!', e, s);
    3611             :     }
    3612           2 :     Logs().d('Migrate Device Keys...');
    3613           1 :     final userDeviceKeys = await legacyDatabase.getUserDeviceKeys(this);
    3614           2 :     for (final userId in userDeviceKeys.keys) {
    3615           3 :       Logs().d('Migrate Device Keys of user $userId...');
    3616           1 :       final deviceKeysList = userDeviceKeys[userId];
    3617             :       for (final crossSigningKey
    3618           4 :           in deviceKeysList?.crossSigningKeys.values ?? <CrossSigningKey>[]) {
    3619           1 :         final pubKey = crossSigningKey.publicKey;
    3620             :         if (pubKey != null) {
    3621           2 :           Logs().d(
    3622           3 :               'Migrate cross signing key with usage ${crossSigningKey.usage} and verified ${crossSigningKey.directVerified}...');
    3623           1 :           await database.storeUserCrossSigningKey(
    3624             :             userId,
    3625             :             pubKey,
    3626           2 :             jsonEncode(crossSigningKey.toJson()),
    3627           1 :             crossSigningKey.directVerified,
    3628           1 :             crossSigningKey.blocked,
    3629             :           );
    3630             :         }
    3631             :       }
    3632             : 
    3633             :       if (deviceKeysList != null) {
    3634           3 :         for (final deviceKeys in deviceKeysList.deviceKeys.values) {
    3635           1 :           final deviceId = deviceKeys.deviceId;
    3636             :           if (deviceId != null) {
    3637           4 :             Logs().d('Migrate device keys for ${deviceKeys.deviceId}...');
    3638           1 :             await database.storeUserDeviceKey(
    3639             :               userId,
    3640             :               deviceId,
    3641           2 :               jsonEncode(deviceKeys.toJson()),
    3642           1 :               deviceKeys.directVerified,
    3643           1 :               deviceKeys.blocked,
    3644           2 :               deviceKeys.lastActive.millisecondsSinceEpoch,
    3645             :             );
    3646             :           }
    3647             :         }
    3648           2 :         Logs().d('Migrate user device keys info...');
    3649           2 :         await database.storeUserDeviceKeysInfo(userId, deviceKeysList.outdated);
    3650             :       }
    3651             :     }
    3652           2 :     Logs().d('Migrate inbound group sessions...');
    3653             :     try {
    3654           1 :       final sessions = await legacyDatabase.getAllInboundGroupSessions();
    3655           3 :       for (var i = 0; i < sessions.length; i++) {
    3656           4 :         Logs().d('$i / ${sessions.length}');
    3657           1 :         final session = sessions[i];
    3658           1 :         await database.storeInboundGroupSession(
    3659           1 :           session.roomId,
    3660           1 :           session.sessionId,
    3661           1 :           session.pickle,
    3662           1 :           session.content,
    3663           1 :           session.indexes,
    3664           1 :           session.allowedAtIndex,
    3665           1 :           session.senderKey,
    3666           1 :           session.senderClaimedKeys,
    3667             :         );
    3668             :       }
    3669             :     } catch (e, s) {
    3670           0 :       Logs().e('Unable to migrate inbound group sessions!', e, s);
    3671             :     }
    3672             : 
    3673           1 :     await legacyDatabase.delete();
    3674             : 
    3675           1 :     _initLock = false;
    3676           1 :     return init(
    3677             :       waitForFirstSync: false,
    3678             :       waitUntilLoadCompletedLoaded: false,
    3679             :     );
    3680             :   }
    3681             : }
    3682             : 
    3683             : class SdkError {
    3684             :   dynamic exception;
    3685             :   StackTrace? stackTrace;
    3686             : 
    3687           6 :   SdkError({this.exception, this.stackTrace});
    3688             : }
    3689             : 
    3690             : class SyncConnectionException implements Exception {
    3691             :   final Object originalException;
    3692             : 
    3693           0 :   SyncConnectionException(this.originalException);
    3694             : }
    3695             : 
    3696             : class SyncStatusUpdate {
    3697             :   final SyncStatus status;
    3698             :   final SdkError? error;
    3699             :   final double? progress;
    3700             : 
    3701          32 :   const SyncStatusUpdate(this.status, {this.error, this.progress});
    3702             : }
    3703             : 
    3704             : enum SyncStatus {
    3705             :   waitingForResponse,
    3706             :   processing,
    3707             :   cleaningUp,
    3708             :   finished,
    3709             :   error,
    3710             : }
    3711             : 
    3712             : class BadServerVersionsException implements Exception {
    3713             :   final Set<String> serverVersions, supportedVersions;
    3714             : 
    3715           0 :   BadServerVersionsException(this.serverVersions, this.supportedVersions);
    3716             : 
    3717           0 :   @override
    3718             :   String toString() =>
    3719           0 :       'Server supports the versions: ${serverVersions.toString()} but this application is only compatible with ${supportedVersions.toString()}.';
    3720             : }
    3721             : 
    3722             : class BadServerLoginTypesException implements Exception {
    3723             :   final Set<String> serverLoginTypes, supportedLoginTypes;
    3724             : 
    3725           0 :   BadServerLoginTypesException(this.serverLoginTypes, this.supportedLoginTypes);
    3726             : 
    3727           0 :   @override
    3728             :   String toString() =>
    3729           0 :       'Server supports the Login Types: ${serverLoginTypes.toString()} but this application is only compatible with ${supportedLoginTypes.toString()}.';
    3730             : }
    3731             : 
    3732             : class FileTooBigMatrixException extends MatrixException {
    3733             :   int actualFileSize;
    3734             :   int maxFileSize;
    3735             : 
    3736           0 :   static String _formatFileSize(int size) {
    3737           0 :     if (size < 1024) return '$size B';
    3738           0 :     final i = (log(size) / log(1024)).floor();
    3739           0 :     final num = (size / pow(1024, i));
    3740           0 :     final round = num.round();
    3741           0 :     final numString = round < 10
    3742           0 :         ? num.toStringAsFixed(2)
    3743           0 :         : round < 100
    3744           0 :             ? num.toStringAsFixed(1)
    3745           0 :             : round.toString();
    3746           0 :     return '$numString ${'kMGTPEZY'[i - 1]}B';
    3747             :   }
    3748             : 
    3749           0 :   FileTooBigMatrixException(this.actualFileSize, this.maxFileSize)
    3750           0 :       : super.fromJson({
    3751             :           'errcode': MatrixError.M_TOO_LARGE,
    3752             :           'error':
    3753           0 :               'File size ${_formatFileSize(actualFileSize)} exceeds allowed maximum of ${_formatFileSize(maxFileSize)}'
    3754           0 :         });
    3755             : 
    3756           0 :   @override
    3757             :   String toString() =>
    3758           0 :       'File size ${_formatFileSize(actualFileSize)} exceeds allowed maximum of ${_formatFileSize(maxFileSize)}';
    3759             : }
    3760             : 
    3761             : class ArchivedRoom {
    3762             :   final Room room;
    3763             :   final Timeline timeline;
    3764             : 
    3765           3 :   ArchivedRoom({required this.room, required this.timeline});
    3766             : }
    3767             : 
    3768             : /// An event that is waiting for a key to arrive to decrypt. Times out after some time.
    3769             : class _EventPendingDecryption {
    3770             :   DateTime addedAt = DateTime.now();
    3771             : 
    3772             :   EventUpdate event;
    3773             : 
    3774           0 :   bool get timedOut =>
    3775           0 :       addedAt.add(Duration(minutes: 5)).isBefore(DateTime.now());
    3776             : 
    3777           2 :   _EventPendingDecryption(this.event);
    3778             : }

Generated by: LCOV version 1.14