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

Generated by: LCOV version 2.0-1