π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Separate native sessions from Contacts cache state
Manav Rathicc618f6084ed
diff --git a/mobile/apps/locker/lib/main.dart b/mobile/apps/locker/lib/main.dartindex ebd629d220..83dfcf1f7f 100644--- a/mobile/apps/locker/lib/main.dart+++ b/mobile/apps/locker/lib/main.dart@@ -23,6 +23,7 @@ import 'package:flutter/services.dart';import 'package:flutter_displaymode/flutter_displaymode.dart';import 'package:locker/app.dart';import 'package:locker/core/locale.dart';+import 'package:locker/service_locator.dart';import 'package:locker/services/collections/collections_api_client.dart';import 'package:locker/services/collections/collections_service.dart';import 'package:locker/services/configuration.dart';@@ -30,7 +31,6 @@ import "package:locker/services/contacts_display_service.dart";import 'package:locker/services/db/locker_db.dart';import 'package:locker/services/favorites_service.dart';import 'package:locker/services/feature_flag_service.dart';-import 'package:locker/services/files/download/service_locator.dart';import 'package:locker/services/files/links/links_client.dart';import 'package:locker/services/files/links/links_service.dart';import 'package:locker/services/files/offline/offline_files_service.dart';@@ -223,10 +223,7 @@ Future<void> _init(bool bool, {String? via}) async {UserService.instance,Configuration.instance,);- await LockerContactsDisplayService.init(- preferences: preferences,- packageInfo: packageInfo,- );+ await LockerContactsDisplayService.init(preferences: preferences);unawaited(cleanStaleLegacyKitShareFiles());unawaited(Future.delayed(diff --git a/mobile/apps/locker/lib/services/files/download/service_locator.dart b/mobile/apps/locker/lib/service_locator.dartsimilarity index 100%rename from mobile/apps/locker/lib/services/files/download/service_locator.dartrename to mobile/apps/locker/lib/service_locator.dartdiff --git a/mobile/apps/locker/lib/services/authenticated_session.dart b/mobile/apps/locker/lib/services/authenticated_session.dartindex a81fa0b1cc..f3ae4a61c7 100644--- a/mobile/apps/locker/lib/services/authenticated_session.dart+++ b/mobile/apps/locker/lib/services/authenticated_session.dart@@ -1,29 +1,42 @@-import 'package:ente_contacts/contacts.dart';+import 'package:locker/service_locator.dart';+import 'package:locker/services/configuration.dart';import 'package:locker/src/rust/third_party/ente_frb_lib/session.dart';Session? _session;String? _sessionKey;-Session authenticatedSession(ContactsSession? account) {- if (account == null) {+Session authenticatedSession() {+ final config = Configuration.instance;+ final authToken = config.getToken();+ final userId = config.getUserID();+ final masterKey = config.getKey();+ if (authToken == null || userId == null || masterKey == null) {throw StateError('Authenticated session is not available');}- final key = '${account.baseUrl}|${account.userId}';+ final baseUrl = config.getHttpEndpoint();+ final key = '$baseUrl|$userId';final current = _session;if (current != null && _sessionKey == key) {- current.updateAuthToken(authToken: account.authToken);+ current.updateAuthToken(authToken: authToken);return current;}+ final packageInfo = ServiceLocator.instance.packageInfo;final opened = openSession(- baseUrl: account.baseUrl,- authToken: account.authToken,- masterKey: account.accountKey,- userAgent: account.userAgent,- clientPackage: account.clientPackage,- clientVersion: account.clientVersion,+ baseUrl: baseUrl,+ authToken: authToken,+ masterKey: masterKey,+ clientPackage: packageInfo.packageName,+ clientVersion: packageInfo.version,);+ clearAuthenticatedSession();_session = opened;_sessionKey = key;return opened;}++void clearAuthenticatedSession() {+ _session?.dispose();+ _session = null;+ _sessionKey = null;+}diff --git a/mobile/apps/locker/lib/services/configuration.dart b/mobile/apps/locker/lib/services/configuration.dartindex 253da06b11..9191205be7 100644--- a/mobile/apps/locker/lib/services/configuration.dart+++ b/mobile/apps/locker/lib/services/configuration.dart@@ -1,6 +1,7 @@import 'package:ente_account_deletion/account_deletion.dart';import 'package:ente_configuration/base_configuration.dart';import 'package:ente_lock_screen/lock_screen_host.dart';+import 'package:locker/services/authenticated_session.dart';import 'package:locker/services/collections/collections_service.dart';import 'package:locker/services/favorites_service.dart';import 'package:locker/services/files/offline/offline_file_storage.dart';@@ -30,6 +31,7 @@ class Configuration extends BaseConfigurationCollectionService.instance.clearCache();FavoritesService.instance.clearCache();await super.logout(autoLogout: autoLogout);+ clearAuthenticatedSession();try {await clearAllOfflineFileCopies();} catch (e, s) {diff --git a/mobile/apps/locker/lib/services/contacts_display_service.dart b/mobile/apps/locker/lib/services/contacts_display_service.dartindex 64ac50478f..86fe397fa7 100644--- a/mobile/apps/locker/lib/services/contacts_display_service.dart+++ b/mobile/apps/locker/lib/services/contacts_display_service.dart@@ -5,24 +5,18 @@ import 'package:locker/services/authenticated_session.dart';import 'package:locker/services/configuration.dart';import 'package:locker/services/contacts.dart';import 'package:logging/logging.dart';-import 'package:package_info_plus/package_info_plus.dart';import 'package:shared_preferences/shared_preferences.dart';class LockerContactsDisplayService {static final Logger _logger = Logger('LockerContactsDisplayService');- static PackageInfo? _packageInfo;static Future<void> _pendingOperation = Future.value();- static Future<void> init({- required SharedPreferences preferences,- required PackageInfo packageInfo,- }) async {+ static Future<void> init({required SharedPreferences preferences}) async {contacts.ContactsDisplayService.instance.init(- contactsServiceFactory: (account) {- final session = authenticatedSession(account);+ contactsServiceFactory: () {+ final session = authenticatedSession();return contacts.ContactsService(preferences: preferences,- updateAuthToken: (token) => session.updateAuthToken(authToken: token),createContact: (key, data) => createContact(session, key, data),getDiff: (key, sinceTime, limit) =>getDiff(session, key, sinceTime, limit),@@ -38,16 +32,20 @@ class LockerContactsDisplayService {);},);- _packageInfo = packageInfo;scheduleEnsureReady();}static Future<void> ensureReady() async {- final session = buildSession();- if (session == null) {+ final config = Configuration.instance;+ final userId = config.getUserID();+ if (userId == null || !config.hasConfiguredAccount()) {return;}- await contacts.ContactsDisplayService.instance.ensureReady(session);+ authenticatedSession();+ await contacts.ContactsDisplayService.instance.ensureReady(+ baseUrl: config.getHttpEndpoint(),+ userId: userId,+ );}static Future<void> resetLocalState() {@@ -89,25 +87,4 @@ class LockerContactsDisplayService {_pendingOperation = current.catchError((_) {});return current;}-- static contacts.ContactsSession? buildSession() {- final packageInfo = _packageInfo;- final token = Configuration.instance.getToken();- final userId = Configuration.instance.getUserID();- final accountKey = Configuration.instance.getKey();- if (packageInfo == null ||- token == null ||- userId == null ||- accountKey == null) {- return null;- }- return contacts.ContactsSession(- baseUrl: Configuration.instance.getHttpEndpoint(),- authToken: token,- userId: userId,- accountKey: accountKey,- clientPackage: packageInfo.packageName,- clientVersion: packageInfo.version,- );- }}diff --git a/mobile/apps/locker/lib/services/files/download/file_downloader.dart b/mobile/apps/locker/lib/services/files/download/file_downloader.dartindex 1fc440d0f3..351b9c3070 100644--- a/mobile/apps/locker/lib/services/files/download/file_downloader.dart+++ b/mobile/apps/locker/lib/services/files/download/file_downloader.dart@@ -5,11 +5,11 @@ import 'package:dio/dio.dart';import 'package:ente_crypto_api/ente_crypto_api.dart';import 'package:ente_network/network.dart';import 'package:ente_pure_utils/ente_pure_utils.dart';+import 'package:locker/service_locator.dart';import 'package:locker/services/configuration.dart';import 'package:locker/services/db/locker_db.dart';import 'package:locker/services/files/download/file_url.dart';import 'package:locker/services/files/download/models/task.dart';-import 'package:locker/services/files/download/service_locator.dart';import 'package:locker/services/files/offline/offline_file_storage.dart';import 'package:locker/services/files/sync/models/file.dart';import 'package:logging/logging.dart';diff --git a/mobile/apps/locker/lib/ui/utils/legacy_utils.dart b/mobile/apps/locker/lib/ui/utils/legacy_utils.dartindex 71a254d4ab..7818ef634a 100644--- a/mobile/apps/locker/lib/ui/utils/legacy_utils.dart+++ b/mobile/apps/locker/lib/ui/utils/legacy_utils.dart@@ -9,7 +9,6 @@ import "package:ente_strings/ente_strings.dart";import "package:flutter/material.dart";import "package:locker/services/authenticated_session.dart";import "package:locker/services/configuration.dart";-import "package:locker/services/contacts_display_service.dart";import "package:locker/services/legacy_kit.dart" as legacy;import "package:logging/logging.dart";@@ -103,9 +102,8 @@ Future<bool?> hasLegacyKit() async {}}-Future<List<LegacyKit>> _getLegacyKits() => legacy.getLegacyKits(- authenticatedSession(LockerContactsDisplayService.buildSession()),-);+Future<List<LegacyKit>> _getLegacyKits() =>+ legacy.getLegacyKits(authenticatedSession());Future<LegacyKitCreateResult> _createLegacyKit(List<String> partNames,@@ -116,7 +114,7 @@ Future<LegacyKitCreateResult> _createLegacyKit(throw StateError("Missing account key attributes");}final result = await legacy.createLegacyKit(- authenticatedSession(LockerContactsDisplayService.buildSession()),+ authenticatedSession(),keyAttributes,partNames,noticePeriodInHours,@@ -126,30 +124,22 @@ Future<LegacyKitCreateResult> _createLegacyKit(}Future<List<LegacyKitShare>> _downloadLegacyKitShares(String kitId) =>- legacy.downloadLegacyKitShares(- authenticatedSession(LockerContactsDisplayService.buildSession()),- kitId,- );+ legacy.downloadLegacyKitShares(authenticatedSession(), kitId);Future<void> _updateLegacyKitRecoveryNotice(String kitId,int noticePeriodInHours,) => legacy.updateLegacyKitRecoveryNotice(- authenticatedSession(LockerContactsDisplayService.buildSession()),+ authenticatedSession(),kitId,noticePeriodInHours,);Future<void> _blockLegacyKitRecovery(String kitId) =>- legacy.blockLegacyKitRecovery(- authenticatedSession(LockerContactsDisplayService.buildSession()),- kitId,- );+ legacy.blockLegacyKitRecovery(authenticatedSession(), kitId);-Future<void> _deleteLegacyKit(String kitId) => legacy.deleteLegacyKit(- authenticatedSession(LockerContactsDisplayService.buildSession()),- kitId,-);+Future<void> _deleteLegacyKit(String kitId) =>+ legacy.deleteLegacyKit(authenticatedSession(), kitId);Future<bool> _authenticateForLegacyFlow(BuildContext context, String reason) {return LocalAuthenticationService.instance.requestLocalAuthentication(diff --git a/mobile/apps/photos/lib/core/configuration.dart b/mobile/apps/photos/lib/core/configuration.dartindex 1a1d2b7262..648c478d93 100644--- a/mobile/apps/photos/lib/core/configuration.dart+++ b/mobile/apps/photos/lib/core/configuration.dart@@ -38,6 +38,7 @@ import 'package:photos/gateways/users/models/key_gen_result.dart';import 'package:photos/gateways/users/models/private_key_attributes.dart';import 'package:photos/module/upload/upload_artifact.dart';import 'package:photos/service_locator.dart';+import 'package:photos/services/authenticated_session.dart';import 'package:photos/services/collections_service.dart';import 'package:photos/services/favorites_service.dart';import "package:photos/services/home_widget_service.dart";@@ -218,6 +219,7 @@ class Configuration implements LockScreenHost, AccountDeletionHost {_cachedToken = null;_secretKey = null;_volatilePassword = null;+ clearAuthenticatedSession();await NotificationService.instance.clearAllScheduledNotifications(logLines: false,diff --git a/mobile/apps/photos/lib/services/authenticated_session.dart b/mobile/apps/photos/lib/services/authenticated_session.dartindex acd746baca..de11c5dae8 100644--- a/mobile/apps/photos/lib/services/authenticated_session.dart+++ b/mobile/apps/photos/lib/services/authenticated_session.dart@@ -1,26 +1,42 @@-import 'package:ente_contacts/contacts.dart';+import 'package:photos/core/configuration.dart';+import 'package:photos/service_locator.dart';import 'package:photos/src/rust/third_party/ente_frb_lib/session.dart';Session? _session;String? _sessionKey;-Session authenticatedSession(ContactsSession account) {- final key = '${account.baseUrl}|${account.userId}';+Session authenticatedSession() {+ final config = Configuration.instance;+ final authToken = config.getToken();+ final userId = config.getUserID();+ final masterKey = config.getKey();+ if (authToken == null || userId == null || masterKey == null) {+ throw StateError('Authenticated session is not available');+ }+ final baseUrl = endpointConfig.endpoint;+ final key = '$baseUrl|$userId';final current = _session;if (current != null && _sessionKey == key) {- current.updateAuthToken(authToken: account.authToken);+ current.updateAuthToken(authToken: authToken);return current;}+ final packageInfo = ServiceLocator.instance.packageInfo;final opened = openSession(- baseUrl: account.baseUrl,- authToken: account.authToken,- masterKey: account.accountKey,- userAgent: account.userAgent,- clientPackage: account.clientPackage,- clientVersion: account.clientVersion,+ baseUrl: baseUrl,+ authToken: authToken,+ masterKey: masterKey,+ clientPackage: packageInfo.packageName,+ clientVersion: packageInfo.version,);+ clearAuthenticatedSession();_session = opened;_sessionKey = key;return opened;}++void clearAuthenticatedSession() {+ _session?.dispose();+ _session = null;+ _sessionKey = null;+}diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dartindex 313ee52d8b..a126f5ea9e 100644--- a/mobile/apps/photos/lib/services/photos_contacts_service.dart+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart@@ -13,12 +13,10 @@ import "package:photos/services/contacts.dart";class PhotosContactsService {PhotosContactsService._privateConstructor(): _store = contacts.ContactDirectory(- contactsServiceFactory: (account) {- final session = authenticatedSession(account);+ contactsServiceFactory: () {+ final session = authenticatedSession();return contacts.ContactsService(preferences: ServiceLocator.instance.prefs,- updateAuthToken: (token) =>- session.updateAuthToken(authToken: token),createContact: (key, data) => createContact(session, key, data),getDiff: (key, sinceTime, limit) =>getDiff(session, key, sinceTime, limit),@@ -63,12 +61,14 @@ class PhotosContactsService {bool get needsWarmup => _store.needsWarmup;Future<void> ensureReady() async {- final session = _buildSession();- if (session == null) {+ final config = Configuration.instance;+ final userId = config.getUserID();+ if (userId == null || !config.hasConfiguredAccount()) {_store.clearSession();return;}- await _store.ensureReady(session);+ authenticatedSession();+ await _store.ensureReady(baseUrl: endpointConfig.endpoint, userId: userId);}Future<contacts.ContactRecord?> getContact({@@ -156,8 +156,10 @@ class PhotosContactsService {}@visibleForTesting- Future<void> debugOpenAndSync(contacts.ContactsSession session) =>- _store.ensureReady(session);+ Future<void> debugOpenAndSync({+ required String baseUrl,+ required int userId,+ }) => _store.ensureReady(baseUrl: baseUrl, userId: userId);@visibleForTestingvoid debugHydrateContacts(@@ -168,25 +170,6 @@ class PhotosContactsService {@visibleForTestingvoid debugReset({bool notify = false}) => _store.clearSession(notify: notify);- contacts.ContactsSession? _buildSession() {- final config = Configuration.instance;- final userId = config.getUserID();- final accountKey = config.getKey();- final token = config.getToken();- if (token == null || userId == null || accountKey == null) {- return null;- }- final packageInfo = ServiceLocator.instance.packageInfo;- return contacts.ContactsSession(- baseUrl: endpointConfig.endpoint,- authToken: token,- userId: userId,- accountKey: accountKey,- clientPackage: packageInfo.packageName,- clientVersion: packageInfo.version,- );- }-Future<T?> _runReadSafely<T>(Future<T?> Function() task, {required String description,diff --git a/mobile/apps/photos/test/services/photos_contacts_service_test.dart b/mobile/apps/photos/test/services/photos_contacts_service_test.dartindex 6119dd86d5..1ebf874c27 100644--- a/mobile/apps/photos/test/services/photos_contacts_service_test.dart+++ b/mobile/apps/photos/test/services/photos_contacts_service_test.dart@@ -32,7 +32,7 @@ void main() {late FakeContactsService contactsService;late PhotosContactsService service;- late contacts.ContactsSession session;+ const baseUrl = 'http://localhost:8080';setUp(() {contactsService = FakeContactsService(@@ -53,16 +53,10 @@ void main() {service = PhotosContactsService.forTesting(contactsService: contactsService,);- session = contacts.ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKey: Uint8List.fromList([1, 2, 3]),- );});test('deletion tombstone evicts contact indexes', () async {- await service.debugOpenAndSync(session);+ await service.debugOpenAndSync(baseUrl: baseUrl, userId: 1);service.debugHydrateContacts(const [contacts.ContactRecord(@@ -120,16 +114,13 @@ void main() {);firstService.openBarrier = Completer<void>();- final oldOpenAndSync = service.debugOpenAndSync(session);+ final oldOpenAndSync = service.debugOpenAndSync(+ baseUrl: baseUrl,+ userId: 1,+ );await firstService.openStarted!.future;- final nextSession = contacts.ContactsSession(- baseUrl: session.baseUrl,- authToken: 'token-2',- userId: 2,- accountKey: Uint8List.fromList([9, 9, 9]),- );- await service.debugOpenAndSync(nextSession);+ await service.debugOpenAndSync(baseUrl: baseUrl, userId: 2);expect(service.getCachedSavedName(contactUserId: 9), 'Bob');expect(service.getCachedSavedName(contactUserId: 7), isNull);@@ -151,7 +142,7 @@ void main() {contactsService: contactsService,);- await service.debugOpenAndSync(session);+ await service.debugOpenAndSync(baseUrl: baseUrl, userId: 1);expect(await service.getProfilePictureBytesByUserId(7), isNull);contactsService.profilePictureBytesByContactId['ct_1'] =@@ -182,7 +173,7 @@ void main() {);test('logout event clears hydrated contact cache immediately', () async {- await service.debugOpenAndSync(session);+ await service.debugOpenAndSync(baseUrl: baseUrl, userId: 1);expect(service.getCachedSavedName(contactUserId: 7), 'Alice');@@ -213,7 +204,7 @@ class FakeContactsService extends Fake implements contacts.ContactsService {int getProfilePictureCalls = 0;@override- Future<void> open(contacts.ContactsSession session) async {+ Future<void> open({required int userId}) async {openCalls += 1;final started = openStarted ??= Completer<void>();if (!started.isCompleted) {diff --git a/mobile/packages/contacts/lib/contacts.dart b/mobile/packages/contacts/lib/contacts.dartindex fa63b05e58..0ff83ecd67 100644--- a/mobile/packages/contacts/lib/contacts.dart+++ b/mobile/packages/contacts/lib/contacts.dart@@ -4,7 +4,6 @@ export 'src/db/contacts_database.dart';export 'src/models/contact_data.dart';export 'src/models/contact_output.dart';export 'src/models/contact_record.dart';-export 'src/models/contacts_session.dart';export 'src/service/contact_directory.dart';export 'src/service/contacts_display_service.dart';export 'src/service/contacts_service.dart';diff --git a/mobile/packages/contacts/lib/src/models/contacts_session.dart b/mobile/packages/contacts/lib/src/models/contacts_session.dartdeleted file mode 100644index 87558e813f..0000000000--- a/mobile/packages/contacts/lib/src/models/contacts_session.dart+++ /dev/null@@ -1,21 +0,0 @@-import 'dart:typed_data';--class ContactsSession {- final String baseUrl;- final String authToken;- final int userId;- final Uint8List accountKey;- final String? userAgent;- final String? clientPackage;- final String? clientVersion;-- ContactsSession({- required this.baseUrl,- required this.authToken,- required this.userId,- required this.accountKey,- this.userAgent,- this.clientPackage,- this.clientVersion,- });-}diff --git a/mobile/packages/contacts/lib/src/service/contact_directory.dart b/mobile/packages/contacts/lib/src/service/contact_directory.dartindex 0ba5ccf819..84e153f53f 100644--- a/mobile/packages/contacts/lib/src/service/contact_directory.dart+++ b/mobile/packages/contacts/lib/src/service/contact_directory.dart@@ -2,13 +2,11 @@ import 'dart:async';import 'package:ente_contacts/src/models/contact_data.dart';import 'package:ente_contacts/src/models/contact_record.dart';-import 'package:ente_contacts/src/models/contacts_session.dart';import 'package:ente_contacts/src/service/contacts_service.dart';import 'package:flutter/foundation.dart';import 'package:logging/logging.dart';-typedef ContactsServiceFactory =- ContactsService Function(ContactsSession session);+typedef ContactsServiceFactory = ContactsService Function();class ContactDirectory {ContactDirectory({@@ -19,7 +17,7 @@ class ContactDirectory {Duration profilePictureFailureTtl = const Duration(minutes: 1),}) : _contactsServiceFactory =contactsServiceFactory ??- (contactsService == null ? null : (_) => contactsService),+ (contactsService == null ? null : () => contactsService),_logger = logger ?? Logger('ContactDirectory'),_profilePictureFailureTtl = profilePictureFailureTtl,_onContactsChanged = onContactsChanged;@@ -47,22 +45,21 @@ class ContactDirectory {bool get hasHydratedCache => _hasHydratedCache;bool get needsWarmup => !_hasHydratedCache || _active?.ready == null;- Future<void> ensureReady(ContactsSession session) async {- final key = _sessionKey(session);+ Future<void> ensureReady({+ required String baseUrl,+ required int userId,+ }) async {+ final key = '$baseUrl|$userId';var active = _active;if (active?.key != key) {_clear(notify: true);- active = _ActiveContacts(- key: key,- authToken: session.authToken,- service: _newContactsService(session),- );+ active = _ActiveContacts(key: key, service: _newContactsService());_active = active;}final ready = active!.ready;if (ready == null) {- final opening = _hydrate(active, session);+ final opening = _hydrate(active, userId);active.ready = opening;try {await opening;@@ -74,10 +71,6 @@ class ContactDirectory {} else {await ready;}-- if (!_isActive(active) || active.authToken == session.authToken) return;- await active.service.updateAuthToken(session.authToken);- if (_isActive(active)) active.authToken = session.authToken;}Future<void> resetLocalState() async {@@ -261,9 +254,9 @@ class ContactDirectory {_revision.value = 0;}- Future<void> _hydrate(_ActiveContacts active, ContactsSession session) async {+ Future<void> _hydrate(_ActiveContacts active, int userId) async {final service = active.service;- await service.open(session);+ await service.open(userId: userId);if (!_isActive(active)) return;final knownUserIds = _contactsByUserId.keys.toSet();@@ -463,17 +456,14 @@ class ContactDirectory {bool _isActive(_ActiveContacts active) => identical(active, _active);- ContactsService _newContactsService(ContactsSession session) {+ ContactsService _newContactsService() {final factory = _contactsServiceFactory;if (factory == null) {throw StateError('ContactDirectory requires a contacts service factory');}- return factory(session);+ return factory();}- String _sessionKey(ContactsSession session) =>- '${session.baseUrl}|${session.userId}';-String? _normalizeEmail(String? value) {final normalized = value?.trim().toLowerCase();return normalized == null || normalized.isEmpty ? null : normalized;@@ -486,14 +476,9 @@ class ContactDirectory {}class _ActiveContacts {- _ActiveContacts({- required this.key,- required this.authToken,- required this.service,- });+ _ActiveContacts({required this.key, required this.service});final String key;final ContactsService service;- String authToken;Future<void>? ready;}diff --git a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart b/mobile/packages/contacts/lib/src/service/contacts_display_service.dartindex 791017c255..2e6a7f6e8d 100644--- a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart+++ b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart@@ -1,5 +1,4 @@import 'package:ente_contacts/src/models/contact_record.dart';-import 'package:ente_contacts/src/models/contacts_session.dart';import 'package:ente_contacts/src/service/contact_directory.dart';import 'package:ente_contacts/src/service/contacts_service.dart';import 'package:flutter/foundation.dart';@@ -37,8 +36,8 @@ class ContactsDisplayService {);}- Future<void> ensureReady(ContactsSession session) =>- _store.ensureReady(session);+ Future<void> ensureReady({required String baseUrl, required int userId}) =>+ _store.ensureReady(baseUrl: baseUrl, userId: userId);Future<void> resetLocalState() => _store.resetLocalState();diff --git a/mobile/packages/contacts/lib/src/service/contacts_service.dart b/mobile/packages/contacts/lib/src/service/contacts_service.dartindex 4f9840a790..ac5fe2dbc0 100644--- a/mobile/packages/contacts/lib/src/service/contacts_service.dart+++ b/mobile/packages/contacts/lib/src/service/contacts_service.dart@@ -5,13 +5,11 @@ import 'package:ente_contacts/src/db/contacts_database.dart';import 'package:ente_contacts/src/models/contact_data.dart';import 'package:ente_contacts/src/models/contact_output.dart';import 'package:ente_contacts/src/models/contact_record.dart';-import 'package:ente_contacts/src/models/contacts_session.dart';import 'package:logging/logging.dart';import 'package:shared_preferences/shared_preferences.dart';enum ContactAttachmentType { profilePicture }-typedef UpdateAuthToken = void Function(String authToken);typedef CreateContact =Future<ContactOutput<ContactRecord>> Function(WrappedRootContactKey? wrappedRootContactKey,@@ -55,7 +53,6 @@ class ContactsService {ContactsService({required SharedPreferences preferences,- required UpdateAuthToken updateAuthToken,required CreateContact createContact,required GetContactDiff getDiff,required UpdateContact updateContact,@@ -66,7 +63,6 @@ class ContactsService {ContactsDatabase? database,}) : _preferences = preferences,_database = database ?? ContactsDatabase(),- _updateRemoteAuthToken = updateAuthToken,_createRemoteContact = createContact,_getRemoteDiff = getDiff,_updateRemoteContact = updateContact,@@ -77,7 +73,6 @@ class ContactsService {final SharedPreferences _preferences;final ContactsDatabase _database;- final UpdateAuthToken _updateRemoteAuthToken;final CreateContact _createRemoteContact;final GetContactDiff _getRemoteDiff;final UpdateContact _updateRemoteContact;@@ -88,26 +83,13 @@ class ContactsService {final Logger _logger = Logger('ContactsService');WrappedRootContactKey? _wrappedRootContactKey;- ContactsSession? _session;+ int? _userId;- Future<void> open(ContactsSession session) async {- _wrappedRootContactKey = _cachedWrappedRootContactKey(session.userId);- _session = session;- await _database.configure(userId: session.userId);- _logger.info('Opened contacts store for user ${session.userId}');- }-- Future<void> updateAuthToken(String authToken) async {- _updateRemoteAuthToken(authToken);- _session = ContactsSession(- baseUrl: _session!.baseUrl,- authToken: authToken,- userId: _session!.userId,- accountKey: _session!.accountKey,- userAgent: _session!.userAgent,- clientPackage: _session!.clientPackage,- clientVersion: _session!.clientVersion,- );+ Future<void> open({required int userId}) async {+ _wrappedRootContactKey = _cachedWrappedRootContactKey(userId);+ _userId = userId;+ await _database.configure(userId: userId);+ _logger.info('Opened contacts store for user $userId');}Future<List<ContactRecord>> sync() async {@@ -323,7 +305,7 @@ class ContactsService {}void _requireOpen() {- if (_session == null) {+ if (_userId == null) {throw StateError('ContactsService.open(...) must be called before use');}}@@ -346,11 +328,11 @@ class ContactsService {}Future<T> _value<T>(ContactOutput<T> output) async {- final session = _session;+ final userId = _userId;final key = output.wrappedRootContactKey;- if (session != null && key != null) {+ if (userId != null && key != null) {_wrappedRootContactKey = key;- await _persistWrappedRootContactKey(session.userId, key);+ await _persistWrappedRootContactKey(userId, key);}return output.value;}diff --git a/mobile/packages/contacts/test/contacts_display_service_test.dart b/mobile/packages/contacts/test/contacts_display_service_test.dartindex 7ed9db2d2d..efa07f734d 100644--- a/mobile/packages/contacts/test/contacts_display_service_test.dart+++ b/mobile/packages/contacts/test/contacts_display_service_test.dart@@ -13,11 +13,11 @@ void main() {late Directory tempDir;late SharedPreferences preferences;- late FakeContactsRustApi rustApi;+ late FakeContacts remote;late ContactsDatabase database;late ContactsService contactsService;late ContactsDisplayService displayService;- late ContactsSession session;+ const baseUrl = 'http://localhost:8080';setUp(() async {SharedPreferences.setMockInitialValues({});@@ -25,25 +25,12 @@ void main() {tempDir = await Directory.systemTemp.createTemp('ente_contacts_display_service_test',);- rustApi = FakeContactsRustApi();+ remote = FakeContacts();database = ContactsDatabase(directoryResolver: () async => tempDir);- contactsService = ContactsService(- preferences: preferences,- database: database,- rustApi: rustApi,- );+ contactsService = remote.service(preferences, database);displayService = ContactsDisplayService.instance;await displayService.debugReset(clearLocalState: false);- displayService.init(- preferences: preferences,- contactsService: contactsService,- );- session = ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKey: Uint8List.fromList([1, 2, 3]),- );+ displayService.init(contactsServiceFactory: () => contactsService);});tearDown(() async {@@ -56,7 +43,7 @@ void main() {test('ensureReady hydrates cached display data and notifies listeners',() async {- rustApi.diffPages = [+ remote.diffPages = [[_contact(attachmentID: 'att_1')],const [],];@@ -64,7 +51,7 @@ void main() {void listener() => notifications += 1;displayService.changes.addListener(listener);- await displayService.ensureReady(session);+ await displayService.ensureReady(baseUrl: baseUrl, userId: 1);expect(displayService.getCachedSavedName(contactUserId: 7), 'Alice');expect(notifications, greaterThan(0));@@ -74,26 +61,26 @@ void main() {);test('profile picture loads are single-flight per contact', () async {- rustApi.diffPages = [+ remote.diffPages = [[_contact(attachmentID: 'att_1')],const [],];- rustApi.ctx.profilePictureBarrier = Completer<void>();- rustApi.ctx.profilePictureBytesByContactId['ct_1'] = Uint8List.fromList([+ remote.profilePictureBarrier = Completer<void>();+ remote.profilePictureBytesByContactId['ct_1'] = Uint8List.fromList([1,2,3,]);- await displayService.ensureReady(session);+ await displayService.ensureReady(baseUrl: baseUrl, userId: 1);final first = displayService.getProfilePictureBytes(contactUserId: 7);final second = displayService.getProfilePictureBytes(contactUserId: 7);- rustApi.ctx.profilePictureBarrier!.complete();+ remote.profilePictureBarrier!.complete();expect(await first, Uint8List.fromList([1, 2, 3]));expect(await second, Uint8List.fromList([1, 2, 3]));- expect(rustApi.ctx.getProfilePictureCalls, 1);+ expect(remote.getProfilePictureCalls, 1);});test('positive user id does not fall back to email', () {@@ -143,13 +130,13 @@ void main() {});test('profile picture failures are briefly negative-cached', () async {- rustApi.diffPages = [+ remote.diffPages = [[_contact(attachmentID: 'att_1')],const [],];- rustApi.ctx.profilePictureError = StateError('boom');+ remote.profilePictureError = StateError('boom');- await displayService.ensureReady(session);+ await displayService.ensureReady(baseUrl: baseUrl, userId: 1);expect(await displayService.getProfilePictureBytes(contactUserId: 7),@@ -159,24 +146,24 @@ void main() {await displayService.getProfilePictureBytes(contactUserId: 7),isNull,);- expect(rustApi.ctx.getProfilePictureCalls, 1);+ expect(remote.getProfilePictureCalls, 1);});test('stale in-flight profile picture load does not overwrite newer contact',() async {- rustApi.diffPages = [+ remote.diffPages = [[_contact(attachmentID: 'att_old')],const [],];- rustApi.ctx.profilePictureBarrier = Completer<void>();- rustApi.ctx.profilePictureBytesByContactId['ct_1'] = Uint8List.fromList([+ remote.profilePictureBarrier = Completer<void>();+ remote.profilePictureBytesByContactId['ct_1'] = Uint8List.fromList([1,2,3,]);- await displayService.ensureReady(session);+ await displayService.ensureReady(baseUrl: baseUrl, userId: 1);final pending = displayService.getProfilePictureBytes(contactUserId: 7);@@ -190,7 +177,7 @@ void main() {notify: false,);- rustApi.ctx.profilePictureBarrier!.complete();+ remote.profilePictureBarrier!.complete();expect(await pending, newPicture);expect(@@ -204,52 +191,56 @@ void main() {'stale in-flight ensureReady does not repopulate cache after session switch',() async {final diffBarrier = Completer<void>();- rustApi.ctx.diffBarrier = diffBarrier;- rustApi.ctx.diffStarted = Completer<void>();- rustApi.diffPages = [+ remote.diffBarrier = diffBarrier;+ remote.diffStarted = Completer<void>();+ remote.diffPages = [[_contact(id: 'ct_old')],const [],];- final oldEnsureReady = displayService.ensureReady(session);- await rustApi.ctx.diffStarted!.future;+ final oldEnsureReady = displayService.ensureReady(+ baseUrl: baseUrl,+ userId: 1,+ );+ await remote.diffStarted!.future;- rustApi.nextOpenContext = FakeContactsRustContext();- rustApi.diffPages = [const []];- final nextSession = ContactsSession(- baseUrl: session.baseUrl,- authToken: 'token-2',- userId: 2,- accountKey: Uint8List.fromList([9, 9, 9]),+ final nextDatabase = ContactsDatabase(+ directoryResolver: () async => tempDir,);- await displayService.ensureReady(nextSession);+ contactsService = FakeContacts().service(preferences, nextDatabase);+ await displayService.ensureReady(baseUrl: baseUrl, userId: 2);diffBarrier.complete();await oldEnsureReady;expect(displayService.getCachedSavedName(contactUserId: 7), isNull);+ expect(await nextDatabase.getContacts(), isEmpty);+ expect((await database.getContacts()).single.id, 'ct_old');},);test('ensureReady keeps hydrated cache and retries later when sync fails',() async {- await contactsService.open(session);+ await contactsService.open(userId: 1);await contactsService.createContact(const ContactData(contactUserId: 7, name: 'Alice'),);- rustApi.ctx.diffError = StateError('boom');+ remote.diffError = StateError('boom');- await expectLater(displayService.ensureReady(session), completes);+ await expectLater(+ displayService.ensureReady(baseUrl: baseUrl, userId: 1),+ completes,+ );expect(displayService.getCachedSavedName(contactUserId: 7), 'Alice');- expect(rustApi.ctx.getDiffCalls, 1);+ expect(remote.getDiffCalls, 1);- rustApi.ctx.diffError = null;- rustApi.diffPages = [const []];+ remote.diffError = null;+ remote.diffPages = [const []];- await displayService.ensureReady(session);- expect(rustApi.ctx.getDiffCalls, 2);+ await displayService.ensureReady(baseUrl: baseUrl, userId: 1);+ expect(remote.getDiffCalls, 2);},);}@@ -272,30 +263,7 @@ ContactRecord _contact({updatedAt: updatedAt,);-class FakeContactsRustApi implements ContactsRustApi {- FakeContactsRustContext ctx = FakeContactsRustContext();- FakeContactsRustContext? nextOpenContext;- List<List<ContactRecord>> diffPages = const [];-- @override- Future<OpenContactsContextResult> open(OpenContactsContextInput input) async {- final context = nextOpenContext ?? ctx;- nextOpenContext = null;- context.userIdValue = input.userId;- context.diffPages = List<List<ContactRecord>>.from(diffPages);- return OpenContactsContextResult(- ctx: context,- wrappedRootContactKey: const WrappedRootContactKey(- encryptedKey: 'enc-key',- header: 'enc-header',- ),- rootKeySource: RootKeySource.cache,- );- }-}--class FakeContactsRustContext implements ContactsRustContext {- int userIdValue = 0;+class FakeContacts {final Map<String, Uint8List> profilePictureBytesByContactId = {};List<List<ContactRecord>> diffPages = [];int getProfilePictureCalls = 0;@@ -306,29 +274,44 @@ class FakeContactsRustContext implements ContactsRustContext {Object? diffError;int getDiffCalls = 0;- @override- Future<ContactRecord> createContact(ContactData data) async {- return ContactRecord(- id: 'ct_created',- contactUserId: data.contactUserId,- email: '[email protected]',- data: data,- profilePictureAttachmentId: null,- isDeleted: false,- createdAt: 1,- updatedAt: 1,+ ContactsService service(+ SharedPreferences preferences,+ ContactsDatabase database,+ ) => ContactsService(+ preferences: preferences,+ database: database,+ createContact: createContact,+ getDiff: getDiff,+ getProfilePicture: getProfilePicture,+ updateContact: (_, _, _) => throw UnimplementedError(),+ deleteContact: (_) => throw UnimplementedError(),+ setAttachment: (_, _, _, _) => throw UnimplementedError(),+ deleteAttachment: (_, _, _) => throw UnimplementedError(),+ );++ Future<ContactOutput<ContactRecord>> createContact(+ WrappedRootContactKey? wrappedRootContactKey,+ ContactData data,+ ) async {+ return _output(+ ContactRecord(+ id: 'ct_created',+ contactUserId: data.contactUserId,+ email: '[email protected]',+ data: data,+ profilePictureAttachmentId: null,+ isDeleted: false,+ createdAt: 1,+ updatedAt: 1,+ ),);}- @override- WrappedRootContactKey currentWrappedRootContactKey() =>- const WrappedRootContactKey(- encryptedKey: 'enc-key',- header: 'enc-header',- );-- @override- Future<List<ContactRecord>> getDiff(int sinceTime, int limit) async {+ Future<ContactOutput<List<ContactRecord>>> getDiff(+ WrappedRootContactKey? wrappedRootContactKey,+ int sinceTime,+ int limit,+ ) async {getDiffCalls += 1;final barrier = diffBarrier;if (barrier != null) {@@ -341,15 +324,17 @@ class FakeContactsRustContext implements ContactsRustContext {throw error;}if (diffPages.isEmpty) {- return const [];+ return _output(const []);}final first = diffPages.first;diffPages = diffPages.sublist(1);- return first;+ return _output(first);}- @override- Future<Uint8List> getProfilePicture(String contactId) async {+ Future<ContactOutput<Uint8List>> getProfilePicture(+ WrappedRootContactKey? wrappedRootContactKey,+ String contactId,+ ) async {getProfilePictureCalls += 1;final barrier = profilePictureBarrier;if (barrier != null) {@@ -359,15 +344,14 @@ class FakeContactsRustContext implements ContactsRustContext {if (error != null) {throw error;}- return profilePictureBytesByContactId[contactId]!;+ return _output(profilePictureBytesByContactId[contactId]!);}- @override- Future<void> updateAuthToken(String authToken) async {}-- @override- dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();-- @override- int userId() => userIdValue;+ ContactOutput<T> _output<T>(T value) => ContactOutput(+ value: value,+ wrappedRootContactKey: const WrappedRootContactKey(+ encryptedKey: 'enc-key',+ header: 'enc-header',+ ),+ );}diff --git a/mobile/packages/contacts/test/contacts_service_test.dart b/mobile/packages/contacts/test/contacts_service_test.dartindex 07712c6803..477e39817c 100644--- a/mobile/packages/contacts/test/contacts_service_test.dart+++ b/mobile/packages/contacts/test/contacts_service_test.dart@@ -12,7 +12,7 @@ void main() {late Directory tempDir;late SharedPreferences preferences;- late FakeContactsRustApi rustApi;+ late FakeContacts remote;late ContactsDatabase database;late ContactsService service;@@ -22,11 +22,17 @@ void main() {tempDir = await Directory.systemTemp.createTemp('ente_contacts_service_test',);- rustApi = FakeContactsRustApi();+ remote = FakeContacts();database = ContactsDatabase(directoryResolver: () async => tempDir);service = ContactsService(preferences: preferences,- rustApi: rustApi,+ createContact: remote.createContact,+ getDiff: remote.getDiff,+ updateContact: remote.updateContact,+ deleteContact: remote.deleteContact,+ setAttachment: remote.setAttachment,+ deleteAttachment: remote.deleteAttachment,+ getProfilePicture: remote.getProfilePicture,database: database,);});@@ -38,9 +44,11 @@ void main() {}});- test('open persists wrapped root key and sync caches contacts', () async {- rustApi.rootKeySource = RootKeySource.cache;- rustApi.diffPages = [+ test('sync reuses the cached root key and caches contacts', () async {+ await preferences.setString('entity_key_contact_1', 'cached-key');+ await preferences.setString('entity_key_header_contact_1', 'cached-header');++ remote.diffPages = [[const ContactRecord(id: 'ct_1',@@ -56,51 +64,24 @@ void main() {const [],];- await service.open(- ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKey: Uint8List.fromList([1, 2, 3]),- ),- );+ await service.open(userId: 1);++ final synced = await service.sync();+ expect(remote.lastWrappedRootContactKey?.encryptedKey, 'cached-key');+ expect(remote.lastWrappedRootContactKey?.header, 'cached-header');expect(preferences.getString('entity_key_contact_1'), 'enc-key');expect(preferences.getString('entity_key_header_contact_1'), 'enc-header');-- final synced = await service.sync();expect(synced, hasLength(1));final cached = await service.getContacts();expect(cached.single.email, '[email protected]');expect(cached.single.profilePictureAttachmentId, 'att_1');});- test(- 'open does not persist an unresolved wrapped root contact key',- () async {- rustApi.rootKeySource = RootKeySource.unresolved;- rustApi.openWrappedRootContactKey = null;-- await service.open(- ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKey: Uint8List.fromList([1, 2, 3]),- ),- );-- expect(preferences.getString('entity_key_contact_1'), isNull);- expect(preferences.getString('entity_key_header_contact_1'), isNull);- },- );-test('sync persists a resolved wrapped root contact key after unresolved open',() async {- rustApi.rootKeySource = RootKeySource.unresolved;- rustApi.openWrappedRootContactKey = null;- rustApi.diffPages = [+ remote.diffPages = [[const ContactRecord(id: 'ct_1',@@ -116,15 +97,9 @@ void main() {const [],];- await service.open(- ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKey: Uint8List.fromList([1, 2, 3]),- ),- );+ await service.open(userId: 1);expect(preferences.getString('entity_key_contact_1'), isNull);+ expect(preferences.getString('entity_key_header_contact_1'), isNull);await service.sync();@@ -137,16 +112,7 @@ void main() {);test('create and profile-picture changes update local cache', () async {- rustApi.rootKeySource = RootKeySource.unresolved;- rustApi.openWrappedRootContactKey = null;- await service.open(- ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKey: Uint8List.fromList([1, 2, 3]),- ),- );+ await service.open(userId: 1);expect(preferences.getString('entity_key_contact_1'), isNull);expect(preferences.getString('entity_key_header_contact_1'), isNull);@@ -180,21 +146,8 @@ void main() {expect(await database.getCachedAttachment('att_profile'), isNull);});- test('open can resolve account key from provider', () async {- await service.open(- ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKeyProvider: () async => Uint8List.fromList([9, 8, 7]),- ),- );-- expect(rustApi.lastAccountKey, Uint8List.fromList([9, 8, 7]));- });-- test('getProfilePicture caches rust response on cache miss', () async {- rustApi.diffPages = [+ test('getProfilePicture caches remote response on cache miss', () async {+ remote.diffPages = [[const ContactRecord(id: 'ct_1',@@ -209,40 +162,26 @@ void main() {],const [],];- rustApi.ctx.attachments['att_1'] = Uint8List.fromList([99, 88, 77]);- rustApi.ctx.profilePictures['ct_1'] = Uint8List.fromList([7, 8, 9]);-- await service.open(- ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKey: Uint8List.fromList([1, 2, 3]),- ),- );+ remote.attachments['att_1'] = Uint8List.fromList([99, 88, 77]);+ remote.profilePictures['ct_1'] = Uint8List.fromList([7, 8, 9]);++ await service.open(userId: 1);await service.sync();expect(await service.getProfilePicture('ct_1'),Uint8List.fromList([7, 8, 9]),);- expect(rustApi.ctx.getProfilePictureCalls, 1);+ expect(remote.getProfilePictureCalls, 1);expect(await service.getProfilePicture('ct_1'),Uint8List.fromList([7, 8, 9]),);- expect(rustApi.ctx.getProfilePictureCalls, 1);+ expect(remote.getProfilePictureCalls, 1);});test('replacing profile picture removes stale cached bytes', () async {- await service.open(- ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKey: Uint8List.fromList([1, 2, 3]),- ),- );+ await service.open(userId: 1);final created = await service.createContact(const ContactData(contactUserId: 2, name: 'B'),@@ -253,7 +192,7 @@ void main() {Uint8List.fromList([1, 2, 3]),);- rustApi.ctx.nextAttachmentId = 'att_profile_v2';+ remote.nextAttachmentId = 'att_profile_v2';final replaced = await service.setProfilePicture(created.id,Uint8List.fromList([4, 5, 6]),@@ -274,7 +213,7 @@ void main() {test('sync prunes cached attachments no longer referenced by contacts',() async {- rustApi.diffPages = [+ remote.diffPages = [[const ContactRecord(id: 'ct_1',@@ -290,14 +229,7 @@ void main() {const [],];- await service.open(- ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKey: Uint8List.fromList([1, 2, 3]),- ),- );+ await service.open(userId: 1);await database.upsertCachedAttachment('att_keep',Uint8List.fromList([1]),@@ -331,7 +263,7 @@ void main() {updatedAt: 20,),];- rustApi.ctx.diffHandler = (sinceTime, limit) async {+ remote.diffHandler = (sinceTime, limit) async {if (sinceTime == 0) {return firstPage;}@@ -341,52 +273,19 @@ void main() {return const [];};- await service.open(- ContactsSession(- baseUrl: 'http://localhost:8080',- authToken: 'token',- userId: 1,- accountKey: Uint8List.fromList([1, 2, 3]),- ),- );+ await service.open(userId: 1);await expectLater(service.sync(), throwsStateError);- expect(rustApi.ctx.diffSinceTimes.first, 0);- expect(rustApi.ctx.diffSinceTimes.skip(1), everyElement(19));- expect(rustApi.ctx.diffLimits.first, 5000);- expect(rustApi.ctx.diffLimits.where((limit) => limit == 5000), isNotEmpty);- expect(rustApi.ctx.diffLimits.every((limit) => limit <= 5000), isTrue);- expect((await service.getContact('ct_overflow'))?.data?.name, isNull);+ expect(remote.diffSinceTimes.first, 0);+ expect(remote.diffSinceTimes.skip(1), everyElement(19));+ expect(remote.diffLimits.first, 5000);+ expect(remote.diffLimits.every((limit) => limit <= 5000), isTrue);});}-class FakeContactsRustApi implements ContactsRustApi {- FakeContactsRustContext ctx = FakeContactsRustContext();- List<List<ContactRecord>> diffPages = const [];- Uint8List? lastAccountKey;- RootKeySource rootKeySource = RootKeySource.cache;- WrappedRootContactKey? openWrappedRootContactKey =- const WrappedRootContactKey(- encryptedKey: 'enc-key',- header: 'enc-header',- );-- @override- Future<OpenContactsContextResult> open(OpenContactsContextInput input) async {- ctx.userIdValue = input.userId;- ctx.diffPages = List<List<ContactRecord>>.from(diffPages);- lastAccountKey = input.accountKey;- return OpenContactsContextResult(- ctx: ctx,- wrappedRootContactKey: openWrappedRootContactKey,- rootKeySource: rootKeySource,- );- }-}--class FakeContactsRustContext implements ContactsRustContext {- int userIdValue = 0;+class FakeContacts {+ WrappedRootContactKey? lastWrappedRootContactKey;final Map<String, ContactRecord> records = {};final Map<String, Uint8List> attachments = {};final Map<String, Uint8List> profilePictures = {};@@ -397,8 +296,10 @@ class FakeContactsRustContext implements ContactsRustContext {int getProfilePictureCalls = 0;String nextAttachmentId = 'att_profile';- @override- Future<ContactRecord> createContact(ContactData data) async {+ Future<ContactOutput<ContactRecord>> createContact(+ WrappedRootContactKey? wrappedRootContactKey,+ ContactData data,+ ) async {final record = ContactRecord(id: 'ct_created',contactUserId: data.contactUserId,@@ -410,17 +311,9 @@ class FakeContactsRustContext implements ContactsRustContext {updatedAt: 1,);records[record.id] = record;- return record;+ return _output(record);}- @override- WrappedRootContactKey currentWrappedRootContactKey() =>- const WrappedRootContactKey(- encryptedKey: 'enc-key',- header: 'enc-header',- );-- @overrideFuture<void> deleteContact(String contactId) async {final existing = records[contactId];if (existing != null) {@@ -437,8 +330,8 @@ class FakeContactsRustContext implements ContactsRustContext {}}- @override- Future<ContactRecord> deleteAttachment(+ Future<ContactOutput<ContactRecord>> deleteAttachment(+ WrappedRootContactKey? wrappedRootContactKey,String contactId,ContactAttachmentType attachmentType,) async {@@ -458,15 +351,15 @@ class FakeContactsRustContext implements ContactsRustContext {if (previousAttachmentId != null) {attachments.remove(previousAttachmentId);}- return updated;+ return _output(updated);}- @override- Future<ContactRecord> getContact(String contactId) async =>- records[contactId]!;-- @override- Future<List<ContactRecord>> getDiff(int sinceTime, int limit) async {+ Future<ContactOutput<List<ContactRecord>>> getDiff(+ WrappedRootContactKey? wrappedRootContactKey,+ int sinceTime,+ int limit,+ ) async {+ lastWrappedRootContactKey = wrappedRootContactKey;diffSinceTimes.add(sinceTime);diffLimits.add(limit);final handler = diffHandler;@@ -475,32 +368,34 @@ class FakeContactsRustContext implements ContactsRustContext {for (final record in page) {records[record.id] = record;}- return page;+ return _output(page);}if (diffPages.isEmpty) {- return const [];+ return _output(const []);}final first = diffPages.first;diffPages = diffPages.sublist(1);for (final record in first) {records[record.id] = record;}- return first;+ return _output(first);}- @override- Future<Uint8List> getProfilePicture(String contactId) {+ Future<ContactOutput<Uint8List>> getProfilePicture(+ WrappedRootContactKey? wrappedRootContactKey,+ String contactId,+ ) async {getProfilePictureCalls += 1;final picture = profilePictures[contactId];if (picture != null) {- return Future.value(picture);+ return _output(picture);}final attachmentId = records[contactId]!.profilePictureAttachmentId!;- return Future.value(attachments[attachmentId]!);+ return _output(attachments[attachmentId]!);}- @override- Future<ContactRecord> setAttachment(+ Future<ContactOutput<ContactRecord>> setAttachment(+ WrappedRootContactKey? wrappedRootContactKey,String contactId,ContactAttachmentType attachmentType,Uint8List attachmentBytes,@@ -519,14 +414,11 @@ class FakeContactsRustContext implements ContactsRustContext {records[contactId] = updated;attachments[nextAttachmentId] = attachmentBytes;profilePictures[contactId] = attachmentBytes;- return updated;+ return _output(updated);}- @override- Future<void> updateAuthToken(String authToken) async {}-- @override- Future<ContactRecord> updateContact(+ Future<ContactOutput<ContactRecord>> updateContact(+ WrappedRootContactKey? wrappedRootContactKey,String contactId,ContactData data,) async {@@ -542,9 +434,14 @@ class FakeContactsRustContext implements ContactsRustContext {updatedAt: existing.updatedAt + 1,);records[contactId] = updated;- return updated;+ return _output(updated);}- @override- int userId() => userIdValue;+ ContactOutput<T> _output<T>(T value) => ContactOutput(+ value: value,+ wrappedRootContactKey: const WrappedRootContactKey(+ encryptedKey: 'enc-key',+ header: 'enc-header',+ ),+ );}