Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mob][contacts] add shared contact display integration

Neeraj Guptac2e96741ca3d
diff --git a/mobile/packages/contacts/lib/contacts.dart b/mobile/packages/contacts/lib/contacts.dart
index 2882322f2a..c502ece7d0 100644
--- a/mobile/packages/contacts/lib/contacts.dart
+++ b/mobile/packages/contacts/lib/contacts.dart
@@ -9,4 +9,5 @@ export 'src/db/contacts_database.dart';
export 'src/models/contact_data.dart';
export 'src/models/contact_record.dart';
export 'src/models/contacts_session.dart';
+export 'src/service/contacts_display_service.dart';
export 'src/service/contacts_service.dart';
diff --git a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
index 4e8f2a0b1b..06467ca6ac 100644
--- a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
+++ b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
@@ -257,7 +257,7 @@ class _FrbContactsRustContext implements ContactsRustContext {
}
@override
- Future<Uint8List> getProfilePicture(String contactId) async {
+ Future<Uint8List> getProfilePicture(String contactId) {
return _inner.getProfilePicture(contactId: contactId);
}
diff --git a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
new file mode 100644
index 0000000000..bbac0e513c
--- /dev/null
+++ b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
@@ -0,0 +1,456 @@
+import 'dart:async';
+
+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';
+import 'package:shared_preferences/shared_preferences.dart';
+
+class ContactsDisplayService {
+ ContactsDisplayService._privateConstructor();
+
+ static final ContactsDisplayService instance =
+ ContactsDisplayService._privateConstructor();
+
+ static const Duration _profilePictureFailureTtl = Duration(minutes: 1);
+
+ final Logger _logger = Logger('ContactsDisplayService');
+ final ValueNotifier<int> _changes = ValueNotifier<int>(0);
+ final Map<int, ContactRecord> _contactsByUserId = {};
+ final Map<String, ContactRecord> _contactsByNormalizedEmail = {};
+ final Map<int, String?> _normalizedEmailByUserId = {};
+ final Map<int, Uint8List?> _profilePictureBytesByUserId = {};
+ final Set<int> _resolvedProfilePictureUserIds = {};
+ final Map<int, Future<Uint8List?>> _profilePictureLoadsByUserId = {};
+ final Map<int, DateTime> _profilePictureFailureUntilByUserId = {};
+
+ ContactsService? _contacts;
+ ContactsSession? _session;
+ String? _sessionKey;
+ String? _sessionAuthToken;
+ Future<void>? _readyFuture;
+ bool _hasHydratedCache = false;
+
+ ValueListenable<int> get changes => _changes;
+
+ bool get hasHydratedCache => _hasHydratedCache;
+
+ void init({
+ required SharedPreferences preferences,
+ ContactsService? contactsService,
+ }) {
+ _contacts ??= contactsService ?? ContactsService(preferences: preferences);
+ }
+
+ Future<void> ensureReady(ContactsSession session) async {
+ final contacts = _requireContacts();
+ final sessionKey = _buildSessionKey(session);
+ if (_readyFuture != null && _sessionKey == sessionKey) {
+ await _readyFuture;
+ if (_sessionAuthToken != session.authToken) {
+ await contacts.updateAuthToken(session.authToken);
+ _sessionAuthToken = session.authToken;
+ _session = session;
+ }
+ return;
+ }
+
+ if (_sessionKey != sessionKey) {
+ _clearCachedState(notify: true);
+ }
+
+ _session = session;
+ _sessionKey = sessionKey;
+ _sessionAuthToken = session.authToken;
+
+ late final Future<void> readyFuture;
+ readyFuture = _openAndSync(session).catchError((
+ Object error,
+ StackTrace stackTrace,
+ ) {
+ if (identical(_readyFuture, readyFuture)) {
+ _readyFuture = null;
+ }
+ _logger.warning(
+ 'Failed to hydrate shared contacts display cache',
+ error,
+ stackTrace,
+ );
+ throw error;
+ });
+ _readyFuture = readyFuture;
+ await readyFuture;
+ }
+
+ Future<void> updateAuthToken(String authToken) async {
+ final contacts = _contacts;
+ final session = _session;
+ if (contacts == null || session == null) {
+ return;
+ }
+ if (_sessionAuthToken == authToken) {
+ return;
+ }
+ await contacts.updateAuthToken(authToken);
+ _sessionAuthToken = authToken;
+ _session = ContactsSession(
+ baseUrl: session.baseUrl,
+ authToken: authToken,
+ userId: session.userId,
+ accountKey: session.accountKey,
+ accountKeyProvider: session.accountKeyProvider,
+ userAgent: session.userAgent,
+ clientPackage: session.clientPackage,
+ clientVersion: session.clientVersion,
+ );
+ }
+
+ Future<void> resetLocalState() async {
+ await _contacts?.resetLocalState();
+ _clearCachedState(notify: true);
+ }
+
+ ContactRecord? getCachedContact({
+ int? contactUserId,
+ String? email,
+ }) {
+ final cachedByUserId = _contactByUserIdOrNull(contactUserId);
+ if (cachedByUserId != null) {
+ return cachedByUserId;
+ }
+ return _contactByEmailOrNull(email);
+ }
+
+ String? getCachedSavedName({
+ int? contactUserId,
+ String? email,
+ }) {
+ final savedName = getCachedContact(
+ contactUserId: contactUserId,
+ email: email,
+ )?.data?.name;
+ if (savedName == null) {
+ return null;
+ }
+ final trimmed = savedName.trim();
+ return trimmed.isEmpty ? null : trimmed;
+ }
+
+ String? getCachedResolvedEmail({
+ int? contactUserId,
+ String? email,
+ }) {
+ final resolved = getCachedContact(
+ contactUserId: contactUserId,
+ email: email,
+ )?.email;
+ if (resolved == null) {
+ return null;
+ }
+ final trimmed = resolved.trim();
+ return trimmed.isEmpty ? null : trimmed;
+ }
+
+ Uint8List? getCachedProfilePictureBytes({
+ int? contactUserId,
+ String? email,
+ }) {
+ final resolvedUserId = _resolvedContactUserId(
+ contactUserId: contactUserId,
+ email: email,
+ );
+ if (resolvedUserId == null ||
+ !_resolvedProfilePictureUserIds.contains(resolvedUserId)) {
+ return null;
+ }
+ return _profilePictureBytesByUserId[resolvedUserId];
+ }
+
+ bool hasResolvedProfilePicture({
+ int? contactUserId,
+ String? email,
+ }) {
+ final resolvedUserId = _resolvedContactUserId(
+ contactUserId: contactUserId,
+ email: email,
+ );
+ return resolvedUserId != null &&
+ _resolvedProfilePictureUserIds.contains(resolvedUserId);
+ }
+
+ Future<Uint8List?> getProfilePictureBytes({
+ int? contactUserId,
+ String? email,
+ }) async {
+ final contact = getCachedContact(
+ contactUserId: contactUserId,
+ email: email,
+ );
+ if (contact == null) {
+ if (_hasHydratedCache) {
+ final resolvedUserId = contactUserId;
+ if (resolvedUserId != null) {
+ _profilePictureBytesByUserId.remove(resolvedUserId);
+ _resolvedProfilePictureUserIds.add(resolvedUserId);
+ }
+ }
+ return null;
+ }
+
+ final contactUserIdValue = contact.contactUserId;
+ if (_resolvedProfilePictureUserIds.contains(contactUserIdValue)) {
+ return _profilePictureBytesByUserId[contactUserIdValue];
+ }
+
+ final failureUntil =
+ _profilePictureFailureUntilByUserId[contactUserIdValue];
+ final now = DateTime.now();
+ if (failureUntil != null && failureUntil.isAfter(now)) {
+ return null;
+ }
+
+ final inflightLoad = _profilePictureLoadsByUserId[contactUserIdValue];
+ if (inflightLoad != null) {
+ return inflightLoad;
+ }
+
+ final load = _loadProfilePictureBytes(contact);
+ _profilePictureLoadsByUserId[contactUserIdValue] = load;
+ return load.whenComplete(() {
+ _profilePictureLoadsByUserId.remove(contactUserIdValue);
+ });
+ }
+
+ @visibleForTesting
+ Future<void> debugReset({bool clearLocalState = true}) async {
+ if (clearLocalState) {
+ await _contacts?.resetLocalState();
+ }
+ _clearCachedState(notify: false);
+ _contacts = null;
+ _session = null;
+ _sessionKey = null;
+ _sessionAuthToken = null;
+ if (_changes.value != 0) {
+ _changes.value = 0;
+ }
+ }
+
+ @visibleForTesting
+ void debugHydrateContacts(
+ List<ContactRecord> contacts, {
+ bool notify = true,
+ }) {
+ final changedUserIds = _cacheContacts(contacts);
+ _hasHydratedCache = true;
+ if (notify && changedUserIds.isNotEmpty) {
+ _notifyChanged();
+ }
+ }
+
+ @visibleForTesting
+ void debugSetProfilePictureBytes({
+ required int contactUserId,
+ Uint8List? bytes,
+ bool notify = true,
+ }) {
+ if (bytes == null) {
+ _profilePictureBytesByUserId.remove(contactUserId);
+ } else {
+ _profilePictureBytesByUserId[contactUserId] = bytes;
+ }
+ _resolvedProfilePictureUserIds.add(contactUserId);
+ _profilePictureFailureUntilByUserId.remove(contactUserId);
+ _profilePictureLoadsByUserId.remove(contactUserId);
+ if (notify) {
+ _notifyChanged();
+ }
+ }
+
+ Future<void> _openAndSync(ContactsSession session) async {
+ final contacts = _requireContacts();
+ await contacts.open(session);
+
+ final localContacts = await contacts.getContacts();
+ final localChanged = _cacheContacts(localContacts);
+ _hasHydratedCache = true;
+ if (localChanged.isNotEmpty) {
+ _notifyChanged();
+ }
+
+ final diff = await contacts.sync();
+ final diffChanged = _cacheContacts(diff, invalidateProfilePictures: true);
+ if (diffChanged.isNotEmpty) {
+ _notifyChanged();
+ }
+ }
+
+ Future<Uint8List?> _loadProfilePictureBytes(ContactRecord contact) async {
+ final attachmentId = contact.profilePictureAttachmentId;
+ if (attachmentId == null) {
+ _profilePictureBytesByUserId.remove(contact.contactUserId);
+ _resolvedProfilePictureUserIds.add(contact.contactUserId);
+ return null;
+ }
+
+ try {
+ final bytes = await _requireContacts().getProfilePicture(contact.id);
+ final latestContact = _contactsByUserId[contact.contactUserId];
+ if (latestContact == null ||
+ latestContact.isDeleted ||
+ latestContact.id != contact.id ||
+ latestContact.profilePictureAttachmentId != attachmentId) {
+ return _profilePictureBytesByUserId[contact.contactUserId];
+ }
+ _profilePictureBytesByUserId[contact.contactUserId] = bytes;
+ _resolvedProfilePictureUserIds.add(contact.contactUserId);
+ _profilePictureFailureUntilByUserId.remove(contact.contactUserId);
+ _notifyChanged();
+ return bytes;
+ } catch (error, stackTrace) {
+ _profilePictureFailureUntilByUserId[contact.contactUserId] =
+ DateTime.now().add(_profilePictureFailureTtl);
+ _logger.info(
+ 'Failed to load shared contact profile picture for user ${contact.contactUserId}',
+ error,
+ stackTrace,
+ );
+ return null;
+ }
+ }
+
+ Set<int> _cacheContacts(
+ List<ContactRecord> contacts, {
+ bool invalidateProfilePictures = false,
+ }) {
+ final changedUserIds = <int>{};
+ for (final contact in contacts) {
+ if (_cacheContact(
+ contact,
+ invalidateProfilePicture: invalidateProfilePictures,
+ )) {
+ changedUserIds.add(contact.contactUserId);
+ }
+ }
+ return changedUserIds;
+ }
+
+ bool _cacheContact(
+ ContactRecord contact, {
+ required bool invalidateProfilePicture,
+ }) {
+ final existing = _contactsByUserId[contact.contactUserId];
+ final previousEmail = _normalizedEmailByUserId[contact.contactUserId];
+ if (previousEmail != null) {
+ _contactsByNormalizedEmail.remove(previousEmail);
+ }
+
+ if (contact.isDeleted) {
+ final wasCached = existing != null;
+ _contactsByUserId.remove(contact.contactUserId);
+ _normalizedEmailByUserId.remove(contact.contactUserId);
+ if (invalidateProfilePicture || wasCached) {
+ _invalidateProfilePictureCache(contact.contactUserId);
+ }
+ return wasCached;
+ }
+
+ final normalizedEmail = _normalizeEmail(contact.email);
+ if (normalizedEmail != null) {
+ _contactsByNormalizedEmail[normalizedEmail] = contact;
+ }
+ _normalizedEmailByUserId[contact.contactUserId] = normalizedEmail;
+ _contactsByUserId[contact.contactUserId] = contact;
+ if (invalidateProfilePicture) {
+ _invalidateProfilePictureCache(contact.contactUserId);
+ }
+ return existing != contact;
+ }
+
+ ContactRecord? _contactByUserIdOrNull(int? contactUserId) {
+ if (contactUserId == null) {
+ return null;
+ }
+ final contact = _contactsByUserId[contactUserId];
+ if (contact == null || contact.isDeleted) {
+ return null;
+ }
+ return contact;
+ }
+
+ ContactRecord? _contactByEmailOrNull(String? email) {
+ final normalizedEmail = _normalizeEmail(email);
+ if (normalizedEmail == null) {
+ return null;
+ }
+ final contact = _contactsByNormalizedEmail[normalizedEmail];
+ if (contact == null || contact.isDeleted) {
+ return null;
+ }
+ return contact;
+ }
+
+ int? _resolvedContactUserId({
+ int? contactUserId,
+ String? email,
+ }) {
+ return getCachedContact(contactUserId: contactUserId, email: email)
+ ?.contactUserId;
+ }
+
+ String _buildSessionKey(ContactsSession session) {
+ return '${session.baseUrl}|${session.userId}';
+ }
+
+ String? _normalizeEmail(String? email) {
+ if (email == null) {
+ return null;
+ }
+ final trimmed = email.trim().toLowerCase();
+ return trimmed.isEmpty ? null : trimmed;
+ }
+
+ ContactsService _requireContacts() {
+ final contacts = _contacts;
+ if (contacts == null) {
+ throw StateError(
+ 'ContactsDisplayService.init(preferences: ...) must be called before use',
+ );
+ }
+ return contacts;
+ }
+
+ void _clearCachedState({required bool notify}) {
+ final hadCachedState = _contactsByUserId.isNotEmpty ||
+ _contactsByNormalizedEmail.isNotEmpty ||
+ _profilePictureBytesByUserId.isNotEmpty ||
+ _resolvedProfilePictureUserIds.isNotEmpty;
+ _contactsByUserId.clear();
+ _contactsByNormalizedEmail.clear();
+ _normalizedEmailByUserId.clear();
+ _profilePictureBytesByUserId.clear();
+ _resolvedProfilePictureUserIds.clear();
+ _profilePictureLoadsByUserId.clear();
+ _profilePictureFailureUntilByUserId.clear();
+ _readyFuture = null;
+ _session = null;
+ _sessionKey = null;
+ _sessionAuthToken = null;
+ _hasHydratedCache = false;
+ if (notify && hadCachedState) {
+ _notifyChanged();
+ }
+ }
+
+ void _invalidateProfilePictureCache(int contactUserId) {
+ _profilePictureBytesByUserId.remove(contactUserId);
+ _resolvedProfilePictureUserIds.remove(contactUserId);
+ _profilePictureLoadsByUserId.remove(contactUserId);
+ _profilePictureFailureUntilByUserId.remove(contactUserId);
+ }
+
+ void _notifyChanged() {
+ _changes.value += 1;
+ }
+}
diff --git a/mobile/packages/contacts/lib/src/service/contacts_service.dart b/mobile/packages/contacts/lib/src/service/contacts_service.dart
index 2dedd21649..c08f366a9b 100644
--- a/mobile/packages/contacts/lib/src/service/contacts_service.dart
+++ b/mobile/packages/contacts/lib/src/service/contacts_service.dart
@@ -170,7 +170,7 @@ class ContactsService {
}
Future<Uint8List> getProfilePicture(String contactId) {
- return _getAttachment(contactId, ContactAttachmentType.profilePicture);
+ return _getProfilePicture(contactId);
}
Future<ContactRecord> deleteProfilePicture(String contactId) {
@@ -203,27 +203,17 @@ class ContactsService {
return updated;
}
- Future<Uint8List> _getAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- ) async {
+ Future<Uint8List> _getProfilePicture(String contactId) async {
final contact = await _database.getContact(contactId);
final attachmentId = contact?.profilePictureAttachmentId;
if (attachmentId == null) {
- throw StateError(
- 'Contact $contactId does not have attachment $attachmentType',
- );
+ throw StateError('Contact $contactId does not have a profile picture');
}
final cached = await _database.getCachedAttachment(attachmentId);
if (cached != null) {
return cached;
}
- final ctx = _requireCtx();
- final bytes = switch (attachmentType) {
- ContactAttachmentType.profilePicture => await ctx.getProfilePicture(
- contactId,
- ),
- };
+ final bytes = await _requireCtx().getProfilePicture(contactId);
await _database.upsertCachedAttachment(attachmentId, bytes);
return bytes;
}
diff --git a/mobile/packages/contacts/test/contacts_display_service_test.dart b/mobile/packages/contacts/test/contacts_display_service_test.dart
new file mode 100644
index 0000000000..170ba6d786
--- /dev/null
+++ b/mobile/packages/contacts/test/contacts_display_service_test.dart
@@ -0,0 +1,408 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:ente_contacts/contacts.dart';
+import 'package:ente_contacts/src/rust/contacts_rust_api.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'package:sqflite_common_ffi/sqflite_ffi.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ sqfliteFfiInit();
+
+ late Directory tempDir;
+ late SharedPreferences preferences;
+ late FakeContactsRustApi rustApi;
+ late ContactsDatabase database;
+ late ContactsService contactsService;
+ late ContactsDisplayService displayService;
+ late ContactsSession session;
+
+ setUp(() async {
+ SharedPreferences.setMockInitialValues({});
+ preferences = await SharedPreferences.getInstance();
+ tempDir = await Directory.systemTemp.createTemp(
+ 'ente_contacts_display_service_test',
+ );
+ rustApi = FakeContactsRustApi();
+ database = ContactsDatabase(directoryResolver: () async => tempDir);
+ contactsService = ContactsService(
+ preferences: preferences,
+ database: database,
+ rustApi: rustApi,
+ );
+ 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]),
+ );
+ });
+
+ tearDown(() async {
+ await displayService.debugReset();
+ if (tempDir.existsSync()) {
+ await tempDir.delete(recursive: true);
+ }
+ });
+
+ test('ensureReady hydrates cached display data and notifies listeners',
+ () async {
+ rustApi.diffPages = [
+ [
+ const ContactRecord(
+ id: 'ct_1',
+ contactUserId: 7,
+ email: '[email protected]',
+ data: ContactData(contactUserId: 7, name: 'Alice'),
+ profilePictureAttachmentId: 'att_1',
+ isDeleted: false,
+ createdAt: 1,
+ updatedAt: 2,
+ ),
+ ],
+ const [],
+ ];
+ var notifications = 0;
+ void listener() => notifications += 1;
+ displayService.changes.addListener(listener);
+
+ await displayService.ensureReady(session);
+
+ expect(
+ displayService.getCachedSavedName(contactUserId: 7),
+ 'Alice',
+ );
+ expect(
+ displayService.getCachedResolvedEmail(email: '[email protected]'),
+ );
+ expect(notifications, greaterThan(0));
+
+ displayService.changes.removeListener(listener);
+ });
+
+ test('profile picture loads are single-flight per contact', () async {
+ rustApi.diffPages = [
+ [
+ const ContactRecord(
+ id: 'ct_1',
+ contactUserId: 7,
+ email: '[email protected]',
+ data: ContactData(contactUserId: 7, name: 'Alice'),
+ profilePictureAttachmentId: 'att_1',
+ isDeleted: false,
+ createdAt: 1,
+ updatedAt: 2,
+ ),
+ ],
+ const [],
+ ];
+ rustApi.ctx.profilePictureBarrier = Completer<void>();
+ rustApi.ctx.profilePictureBytesByContactId['ct_1'] = Uint8List.fromList([
+ 1,
+ 2,
+ 3,
+ ]);
+
+ await displayService.ensureReady(session);
+
+ final first = displayService.getProfilePictureBytes(contactUserId: 7);
+ final second = displayService.getProfilePictureBytes(contactUserId: 7);
+
+ rustApi.ctx.profilePictureBarrier!.complete();
+ expect(await first, Uint8List.fromList([1, 2, 3]));
+ expect(await second, Uint8List.fromList([1, 2, 3]));
+ expect(rustApi.ctx.getProfilePictureCalls, 1);
+ });
+
+ test('profile picture failures are briefly negative-cached', () async {
+ rustApi.diffPages = [
+ [
+ const ContactRecord(
+ id: 'ct_1',
+ contactUserId: 7,
+ email: '[email protected]',
+ data: ContactData(contactUserId: 7, name: 'Alice'),
+ profilePictureAttachmentId: 'att_1',
+ isDeleted: false,
+ createdAt: 1,
+ updatedAt: 2,
+ ),
+ ],
+ const [],
+ ];
+ rustApi.ctx.profilePictureError = StateError('boom');
+
+ await displayService.ensureReady(session);
+
+ expect(
+ await displayService.getProfilePictureBytes(contactUserId: 7),
+ isNull,
+ );
+ expect(rustApi.ctx.getProfilePictureCalls, 1);
+ expect(
+ await displayService.getProfilePictureBytes(contactUserId: 7),
+ isNull,
+ );
+ expect(rustApi.ctx.getProfilePictureCalls, 1);
+ });
+
+ test('stale in-flight profile picture load does not overwrite newer contact',
+ () async {
+ rustApi.diffPages = [
+ [
+ const ContactRecord(
+ id: 'ct_1',
+ contactUserId: 7,
+ email: '[email protected]',
+ data: ContactData(contactUserId: 7, name: 'Alice'),
+ profilePictureAttachmentId: 'att_old',
+ isDeleted: false,
+ createdAt: 1,
+ updatedAt: 2,
+ ),
+ ],
+ const [],
+ ];
+ rustApi.ctx.profilePictureBarrier = Completer<void>();
+ rustApi.ctx.profilePictureBytesByContactId['ct_1'] = Uint8List.fromList([
+ 1,
+ 2,
+ 3,
+ ]);
+
+ await displayService.ensureReady(session);
+
+ final pending = displayService.getProfilePictureBytes(contactUserId: 7);
+
+ displayService.debugHydrateContacts([
+ const ContactRecord(
+ id: 'ct_1',
+ contactUserId: 7,
+ email: '[email protected]',
+ data: ContactData(contactUserId: 7, name: 'Alice'),
+ profilePictureAttachmentId: 'att_new',
+ isDeleted: false,
+ createdAt: 1,
+ updatedAt: 3,
+ ),
+ ], notify: false,);
+
+ rustApi.ctx.profilePictureBarrier!.complete();
+
+ expect(await pending, isNull);
+ expect(
+ displayService.getCachedProfilePictureBytes(contactUserId: 7),
+ isNull,
+ );
+ });
+}
+
+class FakeContactsRustApi implements ContactsRustApi {
+ FakeContactsRustContext ctx = FakeContactsRustContext();
+ List<List<ContactRecord>> diffPages = const [];
+
+ @override
+ Future<OpenContactsContextResult> open(OpenContactsContextInput input) async {
+ ctx.userIdValue = input.userId;
+ ctx.diffPages = List<List<ContactRecord>>.from(diffPages);
+ return OpenContactsContextResult(
+ ctx: ctx,
+ wrappedRootKey: const WrappedRootContactKey(
+ encryptedKey: 'enc-key',
+ header: 'enc-header',
+ ),
+ rootKeySource: RootKeySource.created,
+ );
+ }
+}
+
+class FakeContactsRustContext implements ContactsRustContext {
+ int userIdValue = 0;
+ final Map<String, ContactRecord> records = {};
+ final Map<String, Uint8List> attachments = {};
+ final Map<String, Uint8List> profilePictureBytesByContactId = {};
+ List<List<ContactRecord>> diffPages = [];
+ int getAttachmentCalls = 0;
+ int getProfilePictureCalls = 0;
+ String nextAttachmentId = 'att_profile';
+ Completer<void>? profilePictureBarrier;
+ Object? profilePictureError;
+
+ @override
+ Future<ContactRecord> createContact(ContactData data) async {
+ final record = ContactRecord(
+ id: 'ct_created',
+ contactUserId: data.contactUserId,
+ email: '[email protected]',
+ data: data,
+ profilePictureAttachmentId: null,
+ isDeleted: false,
+ createdAt: 1,
+ updatedAt: 1,
+ );
+ records[record.id] = record;
+ return record;
+ }
+
+ @override
+ WrappedRootContactKey currentWrappedRootKey() => const WrappedRootContactKey(
+ encryptedKey: 'enc-key',
+ header: 'enc-header',
+ );
+
+ @override
+ Future<void> deleteContact(String contactId) async {
+ final existing = records[contactId];
+ if (existing != null) {
+ records[contactId] = ContactRecord(
+ id: existing.id,
+ contactUserId: existing.contactUserId,
+ email: existing.email,
+ data: null,
+ profilePictureAttachmentId: null,
+ isDeleted: true,
+ createdAt: existing.createdAt,
+ updatedAt: existing.updatedAt + 1,
+ );
+ }
+ }
+
+ @override
+ Future<ContactRecord> deleteAttachment(
+ String contactId,
+ ContactAttachmentType attachmentType,
+ ) async {
+ final existing = records[contactId]!;
+ final updated = ContactRecord(
+ id: existing.id,
+ contactUserId: existing.contactUserId,
+ email: existing.email,
+ data: existing.data,
+ profilePictureAttachmentId: null,
+ isDeleted: existing.isDeleted,
+ createdAt: existing.createdAt,
+ updatedAt: existing.updatedAt + 1,
+ );
+ records[contactId] = updated;
+ final previousAttachmentId = existing.profilePictureAttachmentId;
+ if (previousAttachmentId != null) {
+ attachments.remove(previousAttachmentId);
+ }
+ return updated;
+ }
+
+ @override
+ Future<ContactRecord> deleteProfilePicture(String contactId) {
+ return deleteAttachment(contactId, ContactAttachmentType.profilePicture);
+ }
+
+ @override
+ Future<ContactRecord> getContact(String contactId) async =>
+ records[contactId]!;
+
+ @override
+ Future<List<ContactRecord>> getDiff(int sinceTime, int limit) async {
+ if (diffPages.isEmpty) {
+ return const [];
+ }
+ final first = diffPages.first;
+ diffPages = diffPages.sublist(1);
+ for (final record in first) {
+ records[record.id] = record;
+ }
+ return first;
+ }
+
+ @override
+ Future<Uint8List> getAttachment(
+ ContactAttachmentType attachmentType,
+ String attachmentId,
+ ) async {
+ getAttachmentCalls += 1;
+ return attachments[attachmentId]!;
+ }
+
+ @override
+ Future<Uint8List> getProfilePicture(String contactId) async {
+ getProfilePictureCalls += 1;
+ final barrier = profilePictureBarrier;
+ if (barrier != null) {
+ await barrier.future;
+ }
+ final error = profilePictureError;
+ if (error != null) {
+ throw error;
+ }
+ return profilePictureBytesByContactId[contactId]!;
+ }
+
+ @override
+ Future<ContactRecord> setAttachment(
+ String contactId,
+ ContactAttachmentType attachmentType,
+ Uint8List attachmentBytes,
+ ) async {
+ final existing = records[contactId]!;
+ final updated = ContactRecord(
+ id: existing.id,
+ contactUserId: existing.contactUserId,
+ email: existing.email,
+ data: existing.data,
+ profilePictureAttachmentId: nextAttachmentId,
+ isDeleted: existing.isDeleted,
+ createdAt: existing.createdAt,
+ updatedAt: existing.updatedAt + 1,
+ );
+ records[contactId] = updated;
+ attachments[nextAttachmentId] = attachmentBytes;
+ return updated;
+ }
+
+ @override
+ Future<ContactRecord> setProfilePicture(
+ String contactId,
+ Uint8List profilePicture,
+ ) {
+ return setAttachment(
+ contactId,
+ ContactAttachmentType.profilePicture,
+ profilePicture,
+ );
+ }
+
+ @override
+ Future<void> updateAuthToken(String authToken) async {}
+
+ @override
+ Future<ContactRecord> updateContact(
+ String contactId,
+ ContactData data,
+ ) async {
+ final existing = records[contactId]!;
+ final updated = ContactRecord(
+ id: existing.id,
+ contactUserId: existing.contactUserId,
+ email: existing.email,
+ data: data,
+ profilePictureAttachmentId: existing.profilePictureAttachmentId,
+ isDeleted: existing.isDeleted,
+ createdAt: existing.createdAt,
+ updatedAt: existing.updatedAt + 1,
+ );
+ records[contactId] = updated;
+ return updated;
+ }
+
+ @override
+ int userId() => userIdValue;
+}
diff --git a/mobile/packages/rust/rust/src/api/contacts.rs b/mobile/packages/rust/rust/src/api/contacts.rs
index 2adb9f5af0..095722e5c1 100644
--- a/mobile/packages/rust/rust/src/api/contacts.rs
+++ b/mobile/packages/rust/rust/src/api/contacts.rs
@@ -343,7 +343,7 @@ impl ContactsCtx {
.map_err(Into::into)
}
- /// Encrypt and upload a new contact profile picture.
+ /// Encrypt and upload a new attachment for the contact.
pub async fn set_attachment(
&self,
contact_id: String,
diff --git a/mobile/packages/rust/rust/src/api/http.rs b/mobile/packages/rust/rust/src/api/http.rs
index e44131cb20..5faff360fb 100644
--- a/mobile/packages/rust/rust/src/api/http.rs
+++ b/mobile/packages/rust/rust/src/api/http.rs
@@ -6,11 +6,6 @@ use flutter_rust_bridge::frb;
/// HTTP client errors.
#[frb]
pub enum HttpError {
- /// Invalid base URL or request path.
- InvalidUrl {
- /// Error message.
- message: String,
- },
/// Network error - connection failed, timeout, etc.
Network {
/// Error message.
@@ -28,15 +23,20 @@ pub enum HttpError {
/// Error message.
message: String,
},
+ /// Invalid base URL or request path.
+ InvalidUrl {
+ /// Error message.
+ message: String,
+ },
}
impl From<CoreError> for HttpError {
fn from(e: CoreError) -> Self {
match e {
- CoreError::InvalidUrl(message) => HttpError::InvalidUrl { message },
CoreError::Network(message) => HttpError::Network { message },
CoreError::Http { status, message } => HttpError::Http { status, message },
CoreError::Parse(message) => HttpError::Parse { message },
+ CoreError::InvalidUrl(message) => HttpError::InvalidUrl { message },
}
}
}