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 : // If we are receiving states when fetching history we need to check if
2669 : // we are not overwriting a newer state.
2670 33 : if (direction == Direction.b) {
2671 2 : await room.postLoad();
2672 3 : state?.removeWhere((state) {
2673 : final existingState =
2674 3 : room.getState(state.type, state.stateKey ?? '');
2675 : if (existingState == null) return false;
2676 1 : if (existingState is User) {
2677 1 : return existingState.originServerTs
2678 2 : ?.isAfter(state.originServerTs) ??
2679 : true;
2680 : }
2681 0 : if (existingState is MatrixEvent) {
2682 0 : return existingState.originServerTs.isAfter(state.originServerTs);
2683 : }
2684 : return true;
2685 : });
2686 : }
2687 :
2688 33 : if (state != null && state.isNotEmpty) {
2689 33 : await _handleRoomEvents(
2690 : room,
2691 : state,
2692 : EventUpdateType.state,
2693 : );
2694 : }
2695 :
2696 66 : final timelineEvents = syncRoomUpdate.timeline?.events;
2697 33 : if (timelineEvents != null && timelineEvents.isNotEmpty) {
2698 33 : await _handleRoomEvents(room, timelineEvents, timelineUpdateType);
2699 : }
2700 :
2701 33 : final ephemeral = syncRoomUpdate.ephemeral;
2702 33 : if (ephemeral != null && ephemeral.isNotEmpty) {
2703 : // TODO: This method seems to be comperatively slow for some updates
2704 33 : await _handleEphemerals(
2705 : room,
2706 : ephemeral,
2707 : );
2708 : }
2709 :
2710 33 : final accountData = syncRoomUpdate.accountData;
2711 33 : if (accountData != null && accountData.isNotEmpty) {
2712 66 : for (final event in accountData) {
2713 95 : await database?.storeRoomAccountData(room.id, event);
2714 99 : room.roomAccountData[event.type] = event;
2715 : }
2716 : }
2717 : }
2718 :
2719 33 : if (syncRoomUpdate is LeftRoomUpdate) {
2720 66 : final timelineEvents = syncRoomUpdate.timeline?.events;
2721 33 : if (timelineEvents != null && timelineEvents.isNotEmpty) {
2722 33 : await _handleRoomEvents(
2723 : room,
2724 : timelineEvents,
2725 : timelineUpdateType,
2726 : store: false,
2727 : );
2728 : }
2729 33 : final accountData = syncRoomUpdate.accountData;
2730 33 : if (accountData != null && accountData.isNotEmpty) {
2731 66 : for (final event in accountData) {
2732 99 : room.roomAccountData[event.type] = event;
2733 : }
2734 : }
2735 33 : final state = syncRoomUpdate.state;
2736 33 : if (state != null && state.isNotEmpty) {
2737 33 : await _handleRoomEvents(
2738 : room,
2739 : state,
2740 : EventUpdateType.state,
2741 : store: false,
2742 : );
2743 : }
2744 : }
2745 :
2746 33 : if (syncRoomUpdate is InvitedRoomUpdate) {
2747 33 : final state = syncRoomUpdate.inviteState;
2748 33 : if (state != null && state.isNotEmpty) {
2749 33 : await _handleRoomEvents(room, state, EventUpdateType.inviteState);
2750 : }
2751 : }
2752 95 : await database?.storeRoomUpdate(id, syncRoomUpdate, room.lastEvent, this);
2753 : }
2754 : }
2755 :
2756 33 : Future<void> _handleEphemerals(Room room, List<BasicEvent> events) async {
2757 33 : final List<ReceiptEventContent> receipts = [];
2758 :
2759 66 : for (final event in events) {
2760 33 : room.setEphemeral(event);
2761 :
2762 : // Receipt events are deltas between two states. We will create a
2763 : // fake room account data event for this and store the difference
2764 : // there.
2765 66 : if (event.type != 'm.receipt') continue;
2766 :
2767 99 : receipts.add(ReceiptEventContent.fromJson(event.content));
2768 : }
2769 :
2770 33 : if (receipts.isNotEmpty) {
2771 33 : final receiptStateContent = room.receiptState;
2772 :
2773 66 : for (final e in receipts) {
2774 33 : await receiptStateContent.update(e, room);
2775 : }
2776 :
2777 33 : final event = BasicEvent(
2778 : type: LatestReceiptState.eventType,
2779 33 : content: receiptStateContent.toJson(),
2780 : );
2781 95 : await database?.storeRoomAccountData(room.id, event);
2782 99 : room.roomAccountData[event.type] = event;
2783 : }
2784 : }
2785 :
2786 : /// Stores event that came down /sync but didn't get decrypted because of missing keys yet.
2787 : final List<_EventPendingDecryption> _eventsPendingDecryption = [];
2788 :
2789 33 : Future<void> _handleRoomEvents(
2790 : Room room,
2791 : List<StrippedStateEvent> events,
2792 : EventUpdateType type, {
2793 : bool store = true,
2794 : }) async {
2795 : // Calling events can be omitted if they are outdated from the same sync. So
2796 : // we collect them first before we handle them.
2797 33 : final callEvents = <Event>[];
2798 :
2799 66 : for (var event in events) {
2800 : // The client must ignore any new m.room.encryption event to prevent
2801 : // man-in-the-middle attacks!
2802 66 : if ((event.type == EventTypes.Encryption &&
2803 33 : room.encrypted &&
2804 3 : event.content.tryGet<String>('algorithm') !=
2805 : room
2806 1 : .getState(EventTypes.Encryption)
2807 1 : ?.content
2808 1 : .tryGet<String>('algorithm'))) {
2809 : continue;
2810 : }
2811 :
2812 33 : if (event is MatrixEvent &&
2813 66 : event.type == EventTypes.Encrypted &&
2814 3 : encryptionEnabled) {
2815 4 : event = await encryption!.decryptRoomEvent(
2816 2 : Event.fromMatrixEvent(event, room),
2817 : updateType: type,
2818 : );
2819 :
2820 4 : if (event.type == EventTypes.Encrypted) {
2821 : // if the event failed to decrypt, add it to the queue
2822 4 : _eventsPendingDecryption.add(
2823 4 : _EventPendingDecryption(Event.fromMatrixEvent(event, room)),
2824 : );
2825 : }
2826 : }
2827 :
2828 : // Any kind of member change? We should invalidate the profile then:
2829 66 : if (event.type == EventTypes.RoomMember) {
2830 33 : final userId = event.stateKey;
2831 : if (userId != null) {
2832 : // We do not re-request the profile here as this would lead to
2833 : // an unknown amount of network requests as we never know how many
2834 : // member change events can come down in a single sync update.
2835 64 : await database?.markUserProfileAsOutdated(userId);
2836 66 : onUserProfileUpdate.add(userId);
2837 : }
2838 : }
2839 :
2840 66 : if (event.type == EventTypes.Message &&
2841 33 : !room.isDirectChat &&
2842 33 : database != null &&
2843 31 : event is MatrixEvent &&
2844 62 : room.getState(EventTypes.RoomMember, event.senderId) == null) {
2845 : // In order to correctly render room list previews we need to fetch the member from the database
2846 93 : final user = await database?.getUser(event.senderId, room);
2847 : if (user != null) {
2848 31 : room.setState(user);
2849 : }
2850 : }
2851 33 : _updateRoomsByEventUpdate(room, event, type);
2852 : if (store) {
2853 95 : await database?.storeEventUpdate(room.id, event, type, this);
2854 : }
2855 66 : if (event is MatrixEvent && encryptionEnabled) {
2856 48 : await encryption?.handleEventUpdate(
2857 24 : Event.fromMatrixEvent(event, room),
2858 : type,
2859 : );
2860 : }
2861 :
2862 : // ignore: deprecated_member_use_from_same_package
2863 66 : onEvent.add(
2864 : // ignore: deprecated_member_use_from_same_package
2865 33 : EventUpdate(
2866 33 : roomID: room.id,
2867 : type: type,
2868 33 : content: event.toJson(),
2869 : ),
2870 : );
2871 33 : if (event is MatrixEvent) {
2872 33 : final timelineEvent = Event.fromMatrixEvent(event, room);
2873 : switch (type) {
2874 33 : case EventUpdateType.timeline:
2875 66 : onTimelineEvent.add(timelineEvent);
2876 33 : if (prevBatch != null &&
2877 45 : timelineEvent.senderId != userID &&
2878 20 : room.notificationCount > 0 &&
2879 0 : pushruleEvaluator.match(timelineEvent).notify) {
2880 0 : onNotification.add(timelineEvent);
2881 : }
2882 : break;
2883 33 : case EventUpdateType.history:
2884 6 : onHistoryEvent.add(timelineEvent);
2885 : break;
2886 : default:
2887 : break;
2888 : }
2889 : }
2890 :
2891 : // Trigger local notification for a new invite:
2892 33 : if (prevBatch != null &&
2893 15 : type == EventUpdateType.inviteState &&
2894 2 : event.type == EventTypes.RoomMember &&
2895 3 : event.stateKey == userID) {
2896 2 : onNotification.add(
2897 1 : Event(
2898 1 : type: event.type,
2899 2 : eventId: 'invite_for_${room.id}',
2900 1 : senderId: event.senderId,
2901 1 : originServerTs: DateTime.now(),
2902 1 : stateKey: event.stateKey,
2903 1 : content: event.content,
2904 : room: room,
2905 : ),
2906 : );
2907 : }
2908 :
2909 33 : if (prevBatch != null &&
2910 15 : (type == EventUpdateType.timeline ||
2911 4 : type == EventUpdateType.decryptedTimelineQueue)) {
2912 15 : if (event is MatrixEvent &&
2913 45 : (event.type.startsWith(CallConstants.callEventsRegxp))) {
2914 2 : final callEvent = Event.fromMatrixEvent(event, room);
2915 2 : callEvents.add(callEvent);
2916 : }
2917 : }
2918 : }
2919 33 : if (callEvents.isNotEmpty) {
2920 4 : onCallEvents.add(callEvents);
2921 : }
2922 : }
2923 :
2924 : /// stores when we last checked for stale calls
2925 : DateTime lastStaleCallRun = DateTime(0);
2926 :
2927 33 : Future<Room> _updateRoomsByRoomUpdate(
2928 : String roomId,
2929 : SyncRoomUpdate chatUpdate,
2930 : ) async {
2931 : // Update the chat list item.
2932 : // Search the room in the rooms
2933 165 : final roomIndex = rooms.indexWhere((r) => r.id == roomId);
2934 66 : final found = roomIndex != -1;
2935 33 : final membership = chatUpdate is LeftRoomUpdate
2936 : ? Membership.leave
2937 33 : : chatUpdate is InvitedRoomUpdate
2938 : ? Membership.invite
2939 : : Membership.join;
2940 :
2941 : final room = found
2942 26 : ? rooms[roomIndex]
2943 33 : : (chatUpdate is JoinedRoomUpdate
2944 33 : ? Room(
2945 : id: roomId,
2946 : membership: membership,
2947 66 : prev_batch: chatUpdate.timeline?.prevBatch,
2948 : highlightCount:
2949 66 : chatUpdate.unreadNotifications?.highlightCount ?? 0,
2950 : notificationCount:
2951 66 : chatUpdate.unreadNotifications?.notificationCount ?? 0,
2952 33 : summary: chatUpdate.summary,
2953 : client: this,
2954 : )
2955 33 : : Room(id: roomId, membership: membership, client: this));
2956 :
2957 : // Does the chat already exist in the list rooms?
2958 33 : if (!found && membership != Membership.leave) {
2959 : // Check if the room is not in the rooms in the invited list
2960 66 : if (_archivedRooms.isNotEmpty) {
2961 12 : _archivedRooms.removeWhere((archive) => archive.room.id == roomId);
2962 : }
2963 99 : final position = membership == Membership.invite ? 0 : rooms.length;
2964 : // Add the new chat to the list
2965 66 : rooms.insert(position, room);
2966 : }
2967 : // If the membership is "leave" then remove the item and stop here
2968 13 : else if (found && membership == Membership.leave) {
2969 0 : rooms.removeAt(roomIndex);
2970 :
2971 : // in order to keep the archive in sync, add left room to archive
2972 0 : if (chatUpdate is LeftRoomUpdate) {
2973 0 : await _storeArchivedRoom(room.id, chatUpdate, leftRoom: room);
2974 : }
2975 : }
2976 : // Update notification, highlight count and/or additional information
2977 : else if (found &&
2978 13 : chatUpdate is JoinedRoomUpdate &&
2979 52 : (rooms[roomIndex].membership != membership ||
2980 52 : rooms[roomIndex].notificationCount !=
2981 13 : (chatUpdate.unreadNotifications?.notificationCount ?? 0) ||
2982 52 : rooms[roomIndex].highlightCount !=
2983 13 : (chatUpdate.unreadNotifications?.highlightCount ?? 0) ||
2984 13 : chatUpdate.summary != null ||
2985 26 : chatUpdate.timeline?.prevBatch != null)) {
2986 12 : rooms[roomIndex].membership = membership;
2987 12 : rooms[roomIndex].notificationCount =
2988 5 : chatUpdate.unreadNotifications?.notificationCount ?? 0;
2989 12 : rooms[roomIndex].highlightCount =
2990 5 : chatUpdate.unreadNotifications?.highlightCount ?? 0;
2991 8 : if (chatUpdate.timeline?.prevBatch != null) {
2992 10 : rooms[roomIndex].prev_batch = chatUpdate.timeline?.prevBatch;
2993 : }
2994 :
2995 4 : final summary = chatUpdate.summary;
2996 : if (summary != null) {
2997 4 : final roomSummaryJson = rooms[roomIndex].summary.toJson()
2998 2 : ..addAll(summary.toJson());
2999 4 : rooms[roomIndex].summary = RoomSummary.fromJson(roomSummaryJson);
3000 : }
3001 : // ignore: deprecated_member_use_from_same_package
3002 28 : rooms[roomIndex].onUpdate.add(rooms[roomIndex].id);
3003 8 : if ((chatUpdate.timeline?.limited ?? false) &&
3004 1 : requestHistoryOnLimitedTimeline) {
3005 0 : Logs().v(
3006 0 : 'Limited timeline for ${rooms[roomIndex].id} request history now',
3007 : );
3008 0 : runInRoot(rooms[roomIndex].requestHistory);
3009 : }
3010 : }
3011 : return room;
3012 : }
3013 :
3014 33 : void _updateRoomsByEventUpdate(
3015 : Room room,
3016 : StrippedStateEvent eventUpdate,
3017 : EventUpdateType type,
3018 : ) {
3019 33 : if (type == EventUpdateType.history) return;
3020 :
3021 : switch (type) {
3022 33 : case EventUpdateType.inviteState:
3023 33 : room.setState(eventUpdate);
3024 : break;
3025 33 : case EventUpdateType.state:
3026 33 : case EventUpdateType.timeline:
3027 33 : if (eventUpdate is! MatrixEvent) {
3028 0 : Logs().wtf(
3029 0 : 'Passed in a ${eventUpdate.runtimeType} with $type to _updateRoomsByEventUpdate(). This should never happen!',
3030 : );
3031 0 : assert(eventUpdate is! MatrixEvent);
3032 : return;
3033 : }
3034 33 : final event = Event.fromMatrixEvent(eventUpdate, room);
3035 :
3036 : // Update the room state:
3037 33 : if (event.stateKey != null &&
3038 132 : (!room.partial || importantStateEvents.contains(event.type))) {
3039 33 : room.setState(event);
3040 : }
3041 33 : if (type != EventUpdateType.timeline) break;
3042 :
3043 : // If last event is null or not a valid room preview event anyway,
3044 : // just use this:
3045 33 : if (room.lastEvent == null) {
3046 33 : room.lastEvent = event;
3047 : break;
3048 : }
3049 :
3050 : // Is this event redacting the last event?
3051 66 : if (event.type == EventTypes.Redaction &&
3052 : ({
3053 4 : room.lastEvent?.eventId,
3054 4 : room.lastEvent?.relationshipEventId,
3055 2 : }.contains(
3056 6 : event.redacts ?? event.content.tryGet<String>('redacts'),
3057 : ))) {
3058 4 : room.lastEvent?.setRedactionEvent(event);
3059 : break;
3060 : }
3061 :
3062 : // Is this event an edit of the last event? Otherwise ignore it.
3063 66 : if (event.relationshipType == RelationshipTypes.edit) {
3064 12 : if (event.relationshipEventId == room.lastEvent?.eventId ||
3065 9 : (room.lastEvent?.relationshipType == RelationshipTypes.edit &&
3066 6 : event.relationshipEventId ==
3067 6 : room.lastEvent?.relationshipEventId)) {
3068 3 : room.lastEvent = event;
3069 : }
3070 : break;
3071 : }
3072 :
3073 : // Is this event of an important type for the last event?
3074 99 : if (!roomPreviewLastEvents.contains(event.type)) break;
3075 :
3076 : // Event is a valid new lastEvent:
3077 33 : room.lastEvent = event;
3078 :
3079 : break;
3080 0 : case EventUpdateType.history:
3081 0 : case EventUpdateType.decryptedTimelineQueue:
3082 : break;
3083 : }
3084 : // ignore: deprecated_member_use_from_same_package
3085 99 : room.onUpdate.add(room.id);
3086 : }
3087 :
3088 : bool _sortLock = false;
3089 :
3090 : /// If `true` then unread rooms are pinned at the top of the room list.
3091 : bool pinUnreadRooms;
3092 :
3093 : /// If `true` then unread rooms are pinned at the top of the room list.
3094 : bool pinInvitedRooms;
3095 :
3096 : /// The compare function how the rooms should be sorted internally. By default
3097 : /// rooms are sorted by timestamp of the last m.room.message event or the last
3098 : /// event if there is no known message.
3099 66 : RoomSorter get sortRoomsBy => (a, b) {
3100 33 : if (pinInvitedRooms &&
3101 99 : a.membership != b.membership &&
3102 198 : [a.membership, b.membership].any((m) => m == Membership.invite)) {
3103 99 : return a.membership == Membership.invite ? -1 : 1;
3104 99 : } else if (a.isFavourite != b.isFavourite) {
3105 4 : return a.isFavourite ? -1 : 1;
3106 33 : } else if (pinUnreadRooms &&
3107 0 : a.notificationCount != b.notificationCount) {
3108 0 : return b.notificationCount.compareTo(a.notificationCount);
3109 : } else {
3110 66 : return b.latestEventReceivedTime.millisecondsSinceEpoch
3111 99 : .compareTo(a.latestEventReceivedTime.millisecondsSinceEpoch);
3112 : }
3113 : };
3114 :
3115 33 : void _sortRooms() {
3116 132 : if (_sortLock || rooms.length < 2) return;
3117 33 : _sortLock = true;
3118 99 : rooms.sort(sortRoomsBy);
3119 33 : _sortLock = false;
3120 : }
3121 :
3122 : Future? userDeviceKeysLoading;
3123 : Future? roomsLoading;
3124 : Future? _accountDataLoading;
3125 : Future? _discoveryDataLoading;
3126 : Future? firstSyncReceived;
3127 :
3128 46 : Future? get accountDataLoading => _accountDataLoading;
3129 :
3130 0 : Future? get wellKnownLoading => _discoveryDataLoading;
3131 :
3132 : /// A map of known device keys per user.
3133 50 : Map<String, DeviceKeysList> get userDeviceKeys => _userDeviceKeys;
3134 : Map<String, DeviceKeysList> _userDeviceKeys = {};
3135 :
3136 : /// A list of all not verified and not blocked device keys. Clients should
3137 : /// display a warning if this list is not empty and suggest the user to
3138 : /// verify or block those devices.
3139 0 : List<DeviceKeys> get unverifiedDevices {
3140 0 : final userId = userID;
3141 0 : if (userId == null) return [];
3142 0 : return userDeviceKeys[userId]
3143 0 : ?.deviceKeys
3144 0 : .values
3145 0 : .where((deviceKey) => !deviceKey.verified && !deviceKey.blocked)
3146 0 : .toList() ??
3147 0 : [];
3148 : }
3149 :
3150 : /// Gets user device keys by its curve25519 key. Returns null if it isn't found
3151 23 : DeviceKeys? getUserDeviceKeysByCurve25519Key(String senderKey) {
3152 56 : for (final user in userDeviceKeys.values) {
3153 20 : final device = user.deviceKeys.values
3154 40 : .firstWhereOrNull((e) => e.curve25519Key == senderKey);
3155 : if (device != null) {
3156 : return device;
3157 : }
3158 : }
3159 : return null;
3160 : }
3161 :
3162 31 : Future<Set<String>> _getUserIdsInEncryptedRooms() async {
3163 : final userIds = <String>{};
3164 62 : for (final room in rooms) {
3165 93 : if (room.encrypted && room.membership == Membership.join) {
3166 : try {
3167 31 : final userList = await room.requestParticipants();
3168 62 : for (final user in userList) {
3169 31 : if ([Membership.join, Membership.invite]
3170 62 : .contains(user.membership)) {
3171 62 : userIds.add(user.id);
3172 : }
3173 : }
3174 : } catch (e, s) {
3175 0 : Logs().e('[E2EE] Failed to fetch participants', e, s);
3176 : }
3177 : }
3178 : }
3179 : return userIds;
3180 : }
3181 :
3182 : final Map<String, DateTime> _keyQueryFailures = {};
3183 :
3184 33 : Future<void> updateUserDeviceKeys({Set<String>? additionalUsers}) async {
3185 : try {
3186 33 : final database = this.database;
3187 33 : if (!isLogged() || database == null) return;
3188 31 : final dbActions = <Future<dynamic> Function()>[];
3189 31 : final trackedUserIds = await _getUserIdsInEncryptedRooms();
3190 31 : if (!isLogged()) return;
3191 62 : trackedUserIds.add(userID!);
3192 1 : if (additionalUsers != null) trackedUserIds.addAll(additionalUsers);
3193 :
3194 : // Remove all userIds we no longer need to track the devices of.
3195 31 : _userDeviceKeys
3196 39 : .removeWhere((String userId, v) => !trackedUserIds.contains(userId));
3197 :
3198 : // Check if there are outdated device key lists. Add it to the set.
3199 31 : final outdatedLists = <String, List<String>>{};
3200 63 : for (final userId in (additionalUsers ?? <String>[])) {
3201 2 : outdatedLists[userId] = [];
3202 : }
3203 62 : for (final userId in trackedUserIds) {
3204 : final deviceKeysList =
3205 93 : _userDeviceKeys[userId] ??= DeviceKeysList(userId, this);
3206 93 : final failure = _keyQueryFailures[userId.domain];
3207 :
3208 : // deviceKeysList.outdated is not nullable but we have seen this error
3209 : // in production: `Failed assertion: boolean expression must not be null`
3210 : // So this could either be a null safety bug in Dart or a result of
3211 : // using unsound null safety. The extra equal check `!= false` should
3212 : // save us here.
3213 62 : if (deviceKeysList.outdated != false &&
3214 : (failure == null ||
3215 0 : DateTime.now()
3216 0 : .subtract(Duration(minutes: 5))
3217 0 : .isAfter(failure))) {
3218 62 : outdatedLists[userId] = [];
3219 : }
3220 : }
3221 :
3222 31 : if (outdatedLists.isNotEmpty) {
3223 : // Request the missing device key lists from the server.
3224 31 : final response = await queryKeys(outdatedLists, timeout: 10000);
3225 31 : if (!isLogged()) return;
3226 :
3227 31 : final deviceKeys = response.deviceKeys;
3228 : if (deviceKeys != null) {
3229 62 : for (final rawDeviceKeyListEntry in deviceKeys.entries) {
3230 31 : final userId = rawDeviceKeyListEntry.key;
3231 : final userKeys =
3232 93 : _userDeviceKeys[userId] ??= DeviceKeysList(userId, this);
3233 62 : final oldKeys = Map<String, DeviceKeys>.from(userKeys.deviceKeys);
3234 62 : userKeys.deviceKeys = {};
3235 : for (final rawDeviceKeyEntry
3236 93 : in rawDeviceKeyListEntry.value.entries) {
3237 31 : final deviceId = rawDeviceKeyEntry.key;
3238 :
3239 : // Set the new device key for this device
3240 31 : final entry = DeviceKeys.fromMatrixDeviceKeys(
3241 31 : rawDeviceKeyEntry.value,
3242 : this,
3243 34 : oldKeys[deviceId]?.lastActive,
3244 : );
3245 31 : final ed25519Key = entry.ed25519Key;
3246 31 : final curve25519Key = entry.curve25519Key;
3247 31 : if (entry.isValid &&
3248 62 : deviceId == entry.deviceId &&
3249 : ed25519Key != null &&
3250 : curve25519Key != null) {
3251 : // Check if deviceId or deviceKeys are known
3252 31 : if (!oldKeys.containsKey(deviceId)) {
3253 : final oldPublicKeys =
3254 31 : await database.deviceIdSeen(userId, deviceId);
3255 : if (oldPublicKeys != null &&
3256 4 : oldPublicKeys != curve25519Key + ed25519Key) {
3257 2 : Logs().w(
3258 : 'Already seen Device ID has been added again. This might be an attack!',
3259 : );
3260 : continue;
3261 : }
3262 31 : final oldDeviceId = await database.publicKeySeen(ed25519Key);
3263 2 : if (oldDeviceId != null && oldDeviceId != deviceId) {
3264 0 : Logs().w(
3265 : 'Already seen ED25519 has been added again. This might be an attack!',
3266 : );
3267 : continue;
3268 : }
3269 : final oldDeviceId2 =
3270 31 : await database.publicKeySeen(curve25519Key);
3271 2 : if (oldDeviceId2 != null && oldDeviceId2 != deviceId) {
3272 0 : Logs().w(
3273 : 'Already seen Curve25519 has been added again. This might be an attack!',
3274 : );
3275 : continue;
3276 : }
3277 31 : await database.addSeenDeviceId(
3278 : userId,
3279 : deviceId,
3280 31 : curve25519Key + ed25519Key,
3281 : );
3282 31 : await database.addSeenPublicKey(ed25519Key, deviceId);
3283 31 : await database.addSeenPublicKey(curve25519Key, deviceId);
3284 : }
3285 :
3286 : // is this a new key or the same one as an old one?
3287 : // better store an update - the signatures might have changed!
3288 31 : final oldKey = oldKeys[deviceId];
3289 : if (oldKey == null ||
3290 9 : (oldKey.ed25519Key == entry.ed25519Key &&
3291 9 : oldKey.curve25519Key == entry.curve25519Key)) {
3292 : if (oldKey != null) {
3293 : // be sure to save the verified status
3294 6 : entry.setDirectVerified(oldKey.directVerified);
3295 6 : entry.blocked = oldKey.blocked;
3296 6 : entry.validSignatures = oldKey.validSignatures;
3297 : }
3298 62 : userKeys.deviceKeys[deviceId] = entry;
3299 62 : if (deviceId == deviceID &&
3300 93 : entry.ed25519Key == fingerprintKey) {
3301 : // Always trust the own device
3302 23 : entry.setDirectVerified(true);
3303 : }
3304 31 : dbActions.add(
3305 62 : () => database.storeUserDeviceKey(
3306 : userId,
3307 : deviceId,
3308 62 : json.encode(entry.toJson()),
3309 31 : entry.directVerified,
3310 31 : entry.blocked,
3311 62 : entry.lastActive.millisecondsSinceEpoch,
3312 : ),
3313 : );
3314 0 : } else if (oldKeys.containsKey(deviceId)) {
3315 : // This shouldn't ever happen. The same device ID has gotten
3316 : // a new public key. So we ignore the update. TODO: ask krille
3317 : // if we should instead use the new key with unknown verified / blocked status
3318 0 : userKeys.deviceKeys[deviceId] = oldKeys[deviceId]!;
3319 : }
3320 : } else {
3321 0 : Logs().w('Invalid device ${entry.userId}:${entry.deviceId}');
3322 : }
3323 : }
3324 : // delete old/unused entries
3325 34 : for (final oldDeviceKeyEntry in oldKeys.entries) {
3326 3 : final deviceId = oldDeviceKeyEntry.key;
3327 6 : if (!userKeys.deviceKeys.containsKey(deviceId)) {
3328 : // we need to remove an old key
3329 : dbActions
3330 3 : .add(() => database.removeUserDeviceKey(userId, deviceId));
3331 : }
3332 : }
3333 31 : userKeys.outdated = false;
3334 : dbActions
3335 93 : .add(() => database.storeUserDeviceKeysInfo(userId, false));
3336 : }
3337 : }
3338 : // next we parse and persist the cross signing keys
3339 31 : final crossSigningTypes = {
3340 31 : 'master': response.masterKeys,
3341 31 : 'self_signing': response.selfSigningKeys,
3342 31 : 'user_signing': response.userSigningKeys,
3343 : };
3344 62 : for (final crossSigningKeysEntry in crossSigningTypes.entries) {
3345 31 : final keyType = crossSigningKeysEntry.key;
3346 31 : final keys = crossSigningKeysEntry.value;
3347 : if (keys == null) {
3348 : continue;
3349 : }
3350 62 : for (final crossSigningKeyListEntry in keys.entries) {
3351 31 : final userId = crossSigningKeyListEntry.key;
3352 : final userKeys =
3353 62 : _userDeviceKeys[userId] ??= DeviceKeysList(userId, this);
3354 : final oldKeys =
3355 62 : Map<String, CrossSigningKey>.from(userKeys.crossSigningKeys);
3356 62 : userKeys.crossSigningKeys = {};
3357 : // add the types we aren't handling atm back
3358 62 : for (final oldEntry in oldKeys.entries) {
3359 93 : if (!oldEntry.value.usage.contains(keyType)) {
3360 124 : userKeys.crossSigningKeys[oldEntry.key] = oldEntry.value;
3361 : } else {
3362 : // There is a previous cross-signing key with this usage, that we no
3363 : // longer need/use. Clear it from the database.
3364 3 : dbActions.add(
3365 3 : () =>
3366 6 : database.removeUserCrossSigningKey(userId, oldEntry.key),
3367 : );
3368 : }
3369 : }
3370 31 : final entry = CrossSigningKey.fromMatrixCrossSigningKey(
3371 31 : crossSigningKeyListEntry.value,
3372 : this,
3373 : );
3374 31 : final publicKey = entry.publicKey;
3375 31 : if (entry.isValid && publicKey != null) {
3376 31 : final oldKey = oldKeys[publicKey];
3377 9 : if (oldKey == null || oldKey.ed25519Key == entry.ed25519Key) {
3378 : if (oldKey != null) {
3379 : // be sure to save the verification status
3380 6 : entry.setDirectVerified(oldKey.directVerified);
3381 6 : entry.blocked = oldKey.blocked;
3382 6 : entry.validSignatures = oldKey.validSignatures;
3383 : }
3384 62 : userKeys.crossSigningKeys[publicKey] = entry;
3385 : } else {
3386 : // This shouldn't ever happen. The same device ID has gotten
3387 : // a new public key. So we ignore the update. TODO: ask krille
3388 : // if we should instead use the new key with unknown verified / blocked status
3389 0 : userKeys.crossSigningKeys[publicKey] = oldKey;
3390 : }
3391 31 : dbActions.add(
3392 62 : () => database.storeUserCrossSigningKey(
3393 : userId,
3394 : publicKey,
3395 62 : json.encode(entry.toJson()),
3396 31 : entry.directVerified,
3397 31 : entry.blocked,
3398 : ),
3399 : );
3400 : }
3401 93 : _userDeviceKeys[userId]?.outdated = false;
3402 : dbActions
3403 93 : .add(() => database.storeUserDeviceKeysInfo(userId, false));
3404 : }
3405 : }
3406 :
3407 : // now process all the failures
3408 31 : if (response.failures != null) {
3409 93 : for (final failureDomain in response.failures?.keys ?? <String>[]) {
3410 0 : _keyQueryFailures[failureDomain] = DateTime.now();
3411 : }
3412 : }
3413 : }
3414 :
3415 31 : if (dbActions.isNotEmpty) {
3416 31 : if (!isLogged()) return;
3417 62 : await database.transaction(() async {
3418 62 : for (final f in dbActions) {
3419 31 : await f();
3420 : }
3421 : });
3422 : }
3423 : } catch (e, s) {
3424 0 : Logs().e('[LibOlm] Unable to update user device keys', e, s);
3425 : }
3426 : }
3427 :
3428 : bool _toDeviceQueueNeedsProcessing = true;
3429 :
3430 : /// Processes the to_device queue and tries to send every entry.
3431 : /// This function MAY throw an error, which just means the to_device queue wasn't
3432 : /// proccessed all the way.
3433 33 : Future<void> processToDeviceQueue() async {
3434 33 : final database = this.database;
3435 31 : if (database == null || !_toDeviceQueueNeedsProcessing) {
3436 : return;
3437 : }
3438 31 : final entries = await database.getToDeviceEventQueue();
3439 31 : if (entries.isEmpty) {
3440 31 : _toDeviceQueueNeedsProcessing = false;
3441 : return;
3442 : }
3443 2 : for (final entry in entries) {
3444 : // Convert the Json Map to the correct format regarding
3445 : // https: //matrix.org/docs/spec/client_server/r0.6.1#put-matrix-client-r0-sendtodevice-eventtype-txnid
3446 2 : final data = entry.content.map(
3447 2 : (k, v) => MapEntry<String, Map<String, Map<String, dynamic>>>(
3448 : k,
3449 1 : (v as Map).map(
3450 2 : (k, v) => MapEntry<String, Map<String, dynamic>>(
3451 : k,
3452 1 : Map<String, dynamic>.from(v),
3453 : ),
3454 : ),
3455 : ),
3456 : );
3457 :
3458 : try {
3459 3 : await super.sendToDevice(entry.type, entry.txnId, data);
3460 1 : } on MatrixException catch (e) {
3461 0 : Logs().w(
3462 0 : '[To-Device] failed to to_device message from the queue to the server. Ignoring error: $e',
3463 : );
3464 0 : Logs().w('Payload: $data');
3465 : }
3466 2 : await database.deleteFromToDeviceQueue(entry.id);
3467 : }
3468 : }
3469 :
3470 : /// Sends a raw to_device event with a [eventType], a [txnId] and a content
3471 : /// [messages]. Before sending, it tries to re-send potentially queued
3472 : /// to_device events and adds the current one to the queue, should it fail.
3473 10 : @override
3474 : Future<void> sendToDevice(
3475 : String eventType,
3476 : String txnId,
3477 : Map<String, Map<String, Map<String, dynamic>>> messages,
3478 : ) async {
3479 : try {
3480 10 : await processToDeviceQueue();
3481 10 : await super.sendToDevice(eventType, txnId, messages);
3482 : } catch (e, s) {
3483 2 : Logs().w(
3484 : '[Client] Problem while sending to_device event, retrying later...',
3485 : e,
3486 : s,
3487 : );
3488 1 : final database = this.database;
3489 : if (database != null) {
3490 1 : _toDeviceQueueNeedsProcessing = true;
3491 1 : await database.insertIntoToDeviceQueue(
3492 : eventType,
3493 : txnId,
3494 1 : json.encode(messages),
3495 : );
3496 : }
3497 : rethrow;
3498 : }
3499 : }
3500 :
3501 : /// Send an (unencrypted) to device [message] of a specific [eventType] to all
3502 : /// devices of a set of [users].
3503 2 : Future<void> sendToDevicesOfUserIds(
3504 : Set<String> users,
3505 : String eventType,
3506 : Map<String, dynamic> message, {
3507 : String? messageId,
3508 : }) async {
3509 : // Send with send-to-device messaging
3510 2 : final data = <String, Map<String, Map<String, dynamic>>>{};
3511 3 : for (final user in users) {
3512 2 : data[user] = {'*': message};
3513 : }
3514 2 : await sendToDevice(
3515 : eventType,
3516 2 : messageId ?? generateUniqueTransactionId(),
3517 : data,
3518 : );
3519 : return;
3520 : }
3521 :
3522 : final MultiLock<DeviceKeys> _sendToDeviceEncryptedLock = MultiLock();
3523 :
3524 : /// Sends an encrypted [message] of this [eventType] to these [deviceKeys].
3525 9 : Future<void> sendToDeviceEncrypted(
3526 : List<DeviceKeys> deviceKeys,
3527 : String eventType,
3528 : Map<String, dynamic> message, {
3529 : String? messageId,
3530 : bool onlyVerified = false,
3531 : }) async {
3532 9 : final encryption = this.encryption;
3533 9 : if (!encryptionEnabled || encryption == null) return;
3534 : // Don't send this message to blocked devices, and if specified onlyVerified
3535 : // then only send it to verified devices
3536 9 : if (deviceKeys.isNotEmpty) {
3537 9 : deviceKeys.removeWhere(
3538 9 : (DeviceKeys deviceKeys) =>
3539 9 : deviceKeys.blocked ||
3540 42 : (deviceKeys.userId == userID && deviceKeys.deviceId == deviceID) ||
3541 0 : (onlyVerified && !deviceKeys.verified),
3542 : );
3543 9 : if (deviceKeys.isEmpty) return;
3544 : }
3545 :
3546 : // So that we can guarantee order of encrypted to_device messages to be preserved we
3547 : // must ensure that we don't attempt to encrypt multiple concurrent to_device messages
3548 : // to the same device at the same time.
3549 : // A failure to do so can result in edge-cases where encryption and sending order of
3550 : // said to_device messages does not match up, resulting in an olm session corruption.
3551 : // As we send to multiple devices at the same time, we may only proceed here if the lock for
3552 : // *all* of them is freed and lock *all* of them while sending.
3553 :
3554 : try {
3555 18 : await _sendToDeviceEncryptedLock.lock(deviceKeys);
3556 :
3557 : // Send with send-to-device messaging
3558 9 : final data = await encryption.encryptToDeviceMessage(
3559 : deviceKeys,
3560 : eventType,
3561 : message,
3562 : );
3563 : eventType = EventTypes.Encrypted;
3564 9 : await sendToDevice(
3565 : eventType,
3566 9 : messageId ?? generateUniqueTransactionId(),
3567 : data,
3568 : );
3569 : } finally {
3570 18 : _sendToDeviceEncryptedLock.unlock(deviceKeys);
3571 : }
3572 : }
3573 :
3574 : /// Sends an encrypted [message] of this [eventType] to these [deviceKeys].
3575 : /// This request happens partly in the background and partly in the
3576 : /// foreground. It automatically chunks sending to device keys based on
3577 : /// activity.
3578 6 : Future<void> sendToDeviceEncryptedChunked(
3579 : List<DeviceKeys> deviceKeys,
3580 : String eventType,
3581 : Map<String, dynamic> message,
3582 : ) async {
3583 6 : if (!encryptionEnabled) return;
3584 : // be sure to copy our device keys list
3585 6 : deviceKeys = List<DeviceKeys>.from(deviceKeys);
3586 6 : deviceKeys.removeWhere(
3587 4 : (DeviceKeys k) =>
3588 19 : k.blocked || (k.userId == userID && k.deviceId == deviceID),
3589 : );
3590 6 : if (deviceKeys.isEmpty) return;
3591 4 : message = message.copy(); // make sure we deep-copy the message
3592 : // make sure all the olm sessions are loaded from database
3593 16 : Logs().v('Sending to device chunked... (${deviceKeys.length} devices)');
3594 : // sort so that devices we last received messages from get our message first
3595 16 : deviceKeys.sort((keyA, keyB) => keyB.lastActive.compareTo(keyA.lastActive));
3596 : // and now send out in chunks of 20
3597 : const chunkSize = 20;
3598 :
3599 : // first we send out all the chunks that we await
3600 : var i = 0;
3601 : // we leave this in a for-loop for now, so that we can easily adjust the break condition
3602 : // based on other things, if we want to hard-`await` more devices in the future
3603 16 : for (; i < deviceKeys.length && i <= 0; i += chunkSize) {
3604 12 : Logs().v('Sending chunk $i...');
3605 4 : final chunk = deviceKeys.sublist(
3606 : i,
3607 17 : i + chunkSize > deviceKeys.length ? deviceKeys.length : i + chunkSize,
3608 : );
3609 : // and send
3610 4 : await sendToDeviceEncrypted(chunk, eventType, message);
3611 : }
3612 : // now send out the background chunks
3613 8 : if (i < deviceKeys.length) {
3614 : // ignore: unawaited_futures
3615 1 : () async {
3616 3 : for (; i < deviceKeys.length; i += chunkSize) {
3617 : // wait 50ms to not freeze the UI
3618 2 : await Future.delayed(Duration(milliseconds: 50));
3619 3 : Logs().v('Sending chunk $i...');
3620 1 : final chunk = deviceKeys.sublist(
3621 : i,
3622 3 : i + chunkSize > deviceKeys.length
3623 1 : ? deviceKeys.length
3624 0 : : i + chunkSize,
3625 : );
3626 : // and send
3627 1 : await sendToDeviceEncrypted(chunk, eventType, message);
3628 : }
3629 1 : }();
3630 : }
3631 : }
3632 :
3633 : /// Whether all push notifications are muted using the [.m.rule.master]
3634 : /// rule of the push rules: https://matrix.org/docs/spec/client_server/r0.6.0#m-rule-master
3635 0 : bool get allPushNotificationsMuted {
3636 : final Map<String, Object?>? globalPushRules =
3637 0 : _accountData[EventTypes.PushRules]
3638 0 : ?.content
3639 0 : .tryGetMap<String, Object?>('global');
3640 : if (globalPushRules == null) return false;
3641 :
3642 0 : final globalPushRulesOverride = globalPushRules.tryGetList('override');
3643 : if (globalPushRulesOverride != null) {
3644 0 : for (final pushRule in globalPushRulesOverride) {
3645 0 : if (pushRule['rule_id'] == '.m.rule.master') {
3646 0 : return pushRule['enabled'];
3647 : }
3648 : }
3649 : }
3650 : return false;
3651 : }
3652 :
3653 1 : Future<void> setMuteAllPushNotifications(bool muted) async {
3654 1 : await setPushRuleEnabled(
3655 : PushRuleKind.override,
3656 : '.m.rule.master',
3657 : muted,
3658 : );
3659 : return;
3660 : }
3661 :
3662 : /// preference is always given to via over serverName, irrespective of what field
3663 : /// you are trying to use
3664 1 : @override
3665 : Future<String> joinRoom(
3666 : String roomIdOrAlias, {
3667 : List<String>? serverName,
3668 : List<String>? via,
3669 : String? reason,
3670 : ThirdPartySigned? thirdPartySigned,
3671 : }) =>
3672 1 : super.joinRoom(
3673 : roomIdOrAlias,
3674 : serverName: via ?? serverName,
3675 : via: via ?? serverName,
3676 : reason: reason,
3677 : thirdPartySigned: thirdPartySigned,
3678 : );
3679 :
3680 : /// Changes the password. You should either set oldPasswort or another authentication flow.
3681 1 : @override
3682 : Future<void> changePassword(
3683 : String newPassword, {
3684 : String? oldPassword,
3685 : AuthenticationData? auth,
3686 : bool? logoutDevices,
3687 : }) async {
3688 1 : final userID = this.userID;
3689 : try {
3690 : if (oldPassword != null && userID != null) {
3691 1 : auth = AuthenticationPassword(
3692 1 : identifier: AuthenticationUserIdentifier(user: userID),
3693 : password: oldPassword,
3694 : );
3695 : }
3696 1 : await super.changePassword(
3697 : newPassword,
3698 : auth: auth,
3699 : logoutDevices: logoutDevices,
3700 : );
3701 0 : } on MatrixException catch (matrixException) {
3702 0 : if (!matrixException.requireAdditionalAuthentication) {
3703 : rethrow;
3704 : }
3705 0 : if (matrixException.authenticationFlows?.length != 1 ||
3706 0 : !(matrixException.authenticationFlows?.first.stages
3707 0 : .contains(AuthenticationTypes.password) ??
3708 : false)) {
3709 : rethrow;
3710 : }
3711 : if (oldPassword == null || userID == null) {
3712 : rethrow;
3713 : }
3714 0 : return changePassword(
3715 : newPassword,
3716 0 : auth: AuthenticationPassword(
3717 0 : identifier: AuthenticationUserIdentifier(user: userID),
3718 : password: oldPassword,
3719 0 : session: matrixException.session,
3720 : ),
3721 : logoutDevices: logoutDevices,
3722 : );
3723 : } catch (_) {
3724 : rethrow;
3725 : }
3726 : }
3727 :
3728 : /// Clear all local cached messages, room information and outbound group
3729 : /// sessions and perform a new clean sync.
3730 2 : Future<void> clearCache() async {
3731 2 : await abortSync();
3732 2 : _prevBatch = null;
3733 4 : rooms.clear();
3734 4 : await database?.clearCache();
3735 6 : encryption?.keyManager.clearOutboundGroupSessions();
3736 4 : _eventsPendingDecryption.clear();
3737 4 : onCacheCleared.add(true);
3738 : // Restart the syncloop
3739 2 : backgroundSync = true;
3740 : }
3741 :
3742 : /// A list of mxids of users who are ignored.
3743 2 : List<String> get ignoredUsers => List<String>.from(
3744 2 : _accountData['m.ignored_user_list']
3745 1 : ?.content
3746 1 : .tryGetMap<String, Object?>('ignored_users')
3747 1 : ?.keys ??
3748 1 : <String>[],
3749 : );
3750 :
3751 : /// Ignore another user. This will clear the local cached messages to
3752 : /// hide all previous messages from this user.
3753 1 : Future<void> ignoreUser(String userId) async {
3754 1 : if (!userId.isValidMatrixId) {
3755 0 : throw Exception('$userId is not a valid mxid!');
3756 : }
3757 3 : await setAccountData(userID!, 'm.ignored_user_list', {
3758 1 : 'ignored_users': Map.fromEntries(
3759 6 : (ignoredUsers..add(userId)).map((key) => MapEntry(key, {})),
3760 : ),
3761 : });
3762 1 : await clearCache();
3763 : return;
3764 : }
3765 :
3766 : /// Unignore a user. This will clear the local cached messages and request
3767 : /// them again from the server to avoid gaps in the timeline.
3768 1 : Future<void> unignoreUser(String userId) async {
3769 1 : if (!userId.isValidMatrixId) {
3770 0 : throw Exception('$userId is not a valid mxid!');
3771 : }
3772 2 : if (!ignoredUsers.contains(userId)) {
3773 0 : throw Exception('$userId is not in the ignore list!');
3774 : }
3775 3 : await setAccountData(userID!, 'm.ignored_user_list', {
3776 1 : 'ignored_users': Map.fromEntries(
3777 3 : (ignoredUsers..remove(userId)).map((key) => MapEntry(key, {})),
3778 : ),
3779 : });
3780 1 : await clearCache();
3781 : return;
3782 : }
3783 :
3784 : /// The newest presence of this user if there is any. Fetches it from the
3785 : /// database first and then from the server if necessary or returns offline.
3786 2 : Future<CachedPresence> fetchCurrentPresence(
3787 : String userId, {
3788 : bool fetchOnlyFromCached = false,
3789 : }) async {
3790 : // ignore: deprecated_member_use_from_same_package
3791 4 : final cachedPresence = presences[userId];
3792 : if (cachedPresence != null) {
3793 : return cachedPresence;
3794 : }
3795 :
3796 0 : final dbPresence = await database?.getPresence(userId);
3797 : // ignore: deprecated_member_use_from_same_package
3798 0 : if (dbPresence != null) return presences[userId] = dbPresence;
3799 :
3800 0 : if (fetchOnlyFromCached) return CachedPresence.neverSeen(userId);
3801 :
3802 : try {
3803 0 : final result = await getPresence(userId);
3804 0 : final presence = CachedPresence.fromPresenceResponse(result, userId);
3805 0 : await database?.storePresence(userId, presence);
3806 : // ignore: deprecated_member_use_from_same_package
3807 0 : return presences[userId] = presence;
3808 : } catch (e) {
3809 0 : final presence = CachedPresence.neverSeen(userId);
3810 0 : await database?.storePresence(userId, presence);
3811 : // ignore: deprecated_member_use_from_same_package
3812 0 : return presences[userId] = presence;
3813 : }
3814 : }
3815 :
3816 : bool _disposed = false;
3817 : bool _aborted = false;
3818 78 : Future _currentTransaction = Future.sync(() => {});
3819 :
3820 : /// Blackholes any ongoing sync call. Currently ongoing sync *processing* is
3821 : /// still going to be finished, new data is ignored.
3822 33 : Future<void> abortSync() async {
3823 33 : _aborted = true;
3824 33 : backgroundSync = false;
3825 66 : _currentSyncId = -1;
3826 : try {
3827 33 : await _currentTransaction;
3828 : } catch (_) {
3829 : // No-OP
3830 : }
3831 33 : _currentSync = null;
3832 : // reset _aborted for being able to restart the sync.
3833 33 : _aborted = false;
3834 : }
3835 :
3836 : /// Stops the synchronization and closes the database. After this
3837 : /// you can safely make this Client instance null.
3838 24 : Future<void> dispose({bool closeDatabase = true}) async {
3839 24 : _disposed = true;
3840 24 : await abortSync();
3841 44 : await encryption?.dispose();
3842 24 : _encryption = null;
3843 : try {
3844 : if (closeDatabase) {
3845 22 : final database = _database;
3846 22 : _database = null;
3847 : await database
3848 20 : ?.close()
3849 20 : .catchError((e, s) => Logs().w('Failed to close database: ', e, s));
3850 : }
3851 : } catch (error, stacktrace) {
3852 0 : Logs().w('Failed to close database: ', error, stacktrace);
3853 : }
3854 : return;
3855 : }
3856 :
3857 1 : Future<void> _migrateFromLegacyDatabase({
3858 : void Function(InitState)? onInitStateChanged,
3859 : void Function()? onMigration,
3860 : }) async {
3861 2 : Logs().i('Check legacy database for migration data...');
3862 2 : final legacyDatabase = await legacyDatabaseBuilder?.call(this);
3863 2 : final migrateClient = await legacyDatabase?.getClient(clientName);
3864 1 : final database = this.database;
3865 :
3866 : if (migrateClient == null || legacyDatabase == null || database == null) {
3867 0 : await legacyDatabase?.close();
3868 0 : _initLock = false;
3869 : return;
3870 : }
3871 2 : Logs().i('Found data in the legacy database!');
3872 1 : onInitStateChanged?.call(InitState.migratingDatabase);
3873 0 : onMigration?.call();
3874 2 : _id = migrateClient['client_id'];
3875 : final tokenExpiresAtMs =
3876 2 : int.tryParse(migrateClient.tryGet<String>('token_expires_at') ?? '');
3877 1 : await database.insertClient(
3878 1 : clientName,
3879 1 : migrateClient['homeserver_url'],
3880 1 : migrateClient['token'],
3881 : tokenExpiresAtMs == null
3882 : ? null
3883 0 : : DateTime.fromMillisecondsSinceEpoch(tokenExpiresAtMs),
3884 1 : migrateClient['refresh_token'],
3885 1 : migrateClient['user_id'],
3886 1 : migrateClient['device_id'],
3887 1 : migrateClient['device_name'],
3888 : null,
3889 1 : migrateClient['olm_account'],
3890 : );
3891 2 : Logs().d('Migrate SSSSCache...');
3892 2 : for (final type in cacheTypes) {
3893 1 : final ssssCache = await legacyDatabase.getSSSSCache(type);
3894 : if (ssssCache != null) {
3895 0 : Logs().d('Migrate $type...');
3896 0 : await database.storeSSSSCache(
3897 : type,
3898 0 : ssssCache.keyId ?? '',
3899 0 : ssssCache.ciphertext ?? '',
3900 0 : ssssCache.content ?? '',
3901 : );
3902 : }
3903 : }
3904 2 : Logs().d('Migrate OLM sessions...');
3905 : try {
3906 1 : final olmSessions = await legacyDatabase.getAllOlmSessions();
3907 2 : for (final identityKey in olmSessions.keys) {
3908 1 : final sessions = olmSessions[identityKey]!;
3909 2 : for (final sessionId in sessions.keys) {
3910 1 : final session = sessions[sessionId]!;
3911 1 : await database.storeOlmSession(
3912 : identityKey,
3913 1 : session['session_id'] as String,
3914 1 : session['pickle'] as String,
3915 1 : session['last_received'] as int,
3916 : );
3917 : }
3918 : }
3919 : } catch (e, s) {
3920 0 : Logs().e('Unable to migrate OLM sessions!', e, s);
3921 : }
3922 2 : Logs().d('Migrate Device Keys...');
3923 1 : final userDeviceKeys = await legacyDatabase.getUserDeviceKeys(this);
3924 2 : for (final userId in userDeviceKeys.keys) {
3925 3 : Logs().d('Migrate Device Keys of user $userId...');
3926 1 : final deviceKeysList = userDeviceKeys[userId];
3927 : for (final crossSigningKey
3928 4 : in deviceKeysList?.crossSigningKeys.values ?? <CrossSigningKey>[]) {
3929 1 : final pubKey = crossSigningKey.publicKey;
3930 : if (pubKey != null) {
3931 2 : Logs().d(
3932 3 : 'Migrate cross signing key with usage ${crossSigningKey.usage} and verified ${crossSigningKey.directVerified}...',
3933 : );
3934 1 : await database.storeUserCrossSigningKey(
3935 : userId,
3936 : pubKey,
3937 2 : jsonEncode(crossSigningKey.toJson()),
3938 1 : crossSigningKey.directVerified,
3939 1 : crossSigningKey.blocked,
3940 : );
3941 : }
3942 : }
3943 :
3944 : if (deviceKeysList != null) {
3945 3 : for (final deviceKeys in deviceKeysList.deviceKeys.values) {
3946 1 : final deviceId = deviceKeys.deviceId;
3947 : if (deviceId != null) {
3948 4 : Logs().d('Migrate device keys for ${deviceKeys.deviceId}...');
3949 1 : await database.storeUserDeviceKey(
3950 : userId,
3951 : deviceId,
3952 2 : jsonEncode(deviceKeys.toJson()),
3953 1 : deviceKeys.directVerified,
3954 1 : deviceKeys.blocked,
3955 2 : deviceKeys.lastActive.millisecondsSinceEpoch,
3956 : );
3957 : }
3958 : }
3959 2 : Logs().d('Migrate user device keys info...');
3960 2 : await database.storeUserDeviceKeysInfo(userId, deviceKeysList.outdated);
3961 : }
3962 : }
3963 2 : Logs().d('Migrate inbound group sessions...');
3964 : try {
3965 1 : final sessions = await legacyDatabase.getAllInboundGroupSessions();
3966 3 : for (var i = 0; i < sessions.length; i++) {
3967 4 : Logs().d('$i / ${sessions.length}');
3968 1 : final session = sessions[i];
3969 1 : await database.storeInboundGroupSession(
3970 1 : session.roomId,
3971 1 : session.sessionId,
3972 1 : session.pickle,
3973 1 : session.content,
3974 1 : session.indexes,
3975 1 : session.allowedAtIndex,
3976 1 : session.senderKey,
3977 1 : session.senderClaimedKeys,
3978 : );
3979 : }
3980 : } catch (e, s) {
3981 0 : Logs().e('Unable to migrate inbound group sessions!', e, s);
3982 : }
3983 :
3984 1 : await legacyDatabase.clear();
3985 1 : await legacyDatabase.delete();
3986 :
3987 1 : _initLock = false;
3988 1 : return init(
3989 : waitForFirstSync: false,
3990 : waitUntilLoadCompletedLoaded: false,
3991 : onInitStateChanged: onInitStateChanged,
3992 : );
3993 : }
3994 : }
3995 :
3996 : class SdkError {
3997 : dynamic exception;
3998 : StackTrace? stackTrace;
3999 :
4000 6 : SdkError({this.exception, this.stackTrace});
4001 : }
4002 :
4003 : class SyncConnectionException implements Exception {
4004 : final Object originalException;
4005 :
4006 0 : SyncConnectionException(this.originalException);
4007 : }
4008 :
4009 : class SyncStatusUpdate {
4010 : final SyncStatus status;
4011 : final SdkError? error;
4012 : final double? progress;
4013 :
4014 33 : const SyncStatusUpdate(this.status, {this.error, this.progress});
4015 : }
4016 :
4017 : enum SyncStatus {
4018 : waitingForResponse,
4019 : processing,
4020 : cleaningUp,
4021 : finished,
4022 : error,
4023 : }
4024 :
4025 : class BadServerLoginTypesException implements Exception {
4026 : final Set<String> serverLoginTypes, supportedLoginTypes;
4027 :
4028 0 : BadServerLoginTypesException(this.serverLoginTypes, this.supportedLoginTypes);
4029 :
4030 0 : @override
4031 : String toString() =>
4032 0 : 'Server supports the Login Types: ${serverLoginTypes.toString()} but this application is only compatible with ${supportedLoginTypes.toString()}.';
4033 : }
4034 :
4035 : class FileTooBigMatrixException extends MatrixException {
4036 : int actualFileSize;
4037 : int maxFileSize;
4038 :
4039 0 : static String _formatFileSize(int size) {
4040 0 : if (size < 1000) return '$size B';
4041 0 : final i = (log(size) / log(1000)).floor();
4042 0 : final num = (size / pow(1000, i));
4043 0 : final round = num.round();
4044 0 : final numString = round < 10
4045 0 : ? num.toStringAsFixed(2)
4046 0 : : round < 100
4047 0 : ? num.toStringAsFixed(1)
4048 0 : : round.toString();
4049 0 : return '$numString ${'kMGTPEZY'[i - 1]}B';
4050 : }
4051 :
4052 0 : FileTooBigMatrixException(this.actualFileSize, this.maxFileSize)
4053 0 : : super.fromJson({
4054 : 'errcode': MatrixError.M_TOO_LARGE,
4055 : 'error':
4056 0 : 'File size ${_formatFileSize(actualFileSize)} exceeds allowed maximum of ${_formatFileSize(maxFileSize)}',
4057 : });
4058 :
4059 0 : @override
4060 : String toString() =>
4061 0 : 'File size ${_formatFileSize(actualFileSize)} exceeds allowed maximum of ${_formatFileSize(maxFileSize)}';
4062 : }
4063 :
4064 : class ArchivedRoom {
4065 : final Room room;
4066 : final Timeline timeline;
4067 :
4068 3 : ArchivedRoom({required this.room, required this.timeline});
4069 : }
4070 :
4071 : /// An event that is waiting for a key to arrive to decrypt. Times out after some time.
4072 : class _EventPendingDecryption {
4073 : DateTime addedAt = DateTime.now();
4074 :
4075 : Event event;
4076 :
4077 0 : bool get timedOut =>
4078 0 : addedAt.add(Duration(minutes: 5)).isBefore(DateTime.now());
4079 :
4080 2 : _EventPendingDecryption(this.event);
4081 : }
4082 :
4083 : enum InitState {
4084 : /// Initialization has been started. Client fetches information from the database.
4085 : initializing,
4086 :
4087 : /// The database has been updated. A migration is in progress.
4088 : migratingDatabase,
4089 :
4090 : /// The encryption module will be set up now. For the first login this also
4091 : /// includes uploading keys to the server.
4092 : settingUpEncryption,
4093 :
4094 : /// The client is loading rooms, device keys and account data from the
4095 : /// database.
4096 : loadingData,
4097 :
4098 : /// The client waits now for the first sync before procceeding. Get more
4099 : /// information from `Client.onSyncUpdate`.
4100 : waitingForFirstSync,
4101 :
4102 : /// Initialization is complete without errors. The client is now either
4103 : /// logged in or no active session was found.
4104 : finished,
4105 :
4106 : /// Initialization has been completed with an error.
4107 : error,
4108 : }
4109 :
4110 : /// Sets the security level with which devices keys should be shared with
4111 : enum ShareKeysWith {
4112 : /// Keys are shared with all devices if they are not explicitely blocked
4113 : all,
4114 :
4115 : /// Once a user has enabled cross signing, keys are no longer shared with
4116 : /// devices which are not cross verified by the cross signing keys of this
4117 : /// user. This does not require that the user needs to be verified.
4118 : crossVerifiedIfEnabled,
4119 :
4120 : /// Keys are only shared with cross verified devices. If a user has not
4121 : /// enabled cross signing, then all devices must be verified manually first.
4122 : /// This does not require that the user needs to be verified.
4123 : crossVerified,
4124 :
4125 : /// Keys are only shared with direct verified devices. So either the device
4126 : /// or the user must be manually verified first, before keys are shared. By
4127 : /// using cross signing, it is enough to verify the user and then the user
4128 : /// can verify their devices.
4129 : directlyVerifiedOnly,
4130 : }
|