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