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

Generated by: LCOV version 1.14