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

Generated by: LCOV version 2.0-1