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

Generated by: LCOV version 2.0-1