π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][contacts] add shared contacts package
Neeraj Gupta745c2e0f0b53
diff --git a/mobile/apps/photos/lib/core/configuration.dart b/mobile/apps/photos/lib/core/configuration.dartindex 1014e1eff0..8fd74d2504 100644--- a/mobile/apps/photos/lib/core/configuration.dart+++ b/mobile/apps/photos/lib/core/configuration.dart@@ -4,6 +4,7 @@ import "dart:io";import 'package:backup_exclusion/backup_exclusion.dart';import 'package:bip39/bip39.dart' as bip39;+import 'package:ente_contacts/contacts.dart';import "package:ente_crypto/ente_crypto.dart";import "package:flutter/services.dart";import 'package:flutter_secure_storage/flutter_secure_storage.dart';@@ -240,6 +241,7 @@ class Configuration {await MLDataDB.instance.clearTable();await UploadLocksDB.instance.clearTable();await TrashDB.instance.clearTable();+ await ContactsDatabase().clearTable();// Clear all in-memory cachesThumbnailInMemoryLruCache.clearAll();diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yamlindex 4af23a32b2..e898b78520 100644--- a/mobile/apps/photos/pubspec.yaml+++ b/mobile/apps/photos/pubspec.yaml@@ -60,6 +60,8 @@ dependencies:path: plugins/ente_cryptoente_feature_flag:path: plugins/ente_feature_flag+ ente_contacts:+ path: ../../packages/contactsente_icons:path: ../../packages/ente_iconsente_photos_rust:diff --git a/mobile/packages/contacts/.gitignore b/mobile/packages/contacts/.gitignorenew file mode 100644index 0000000000..ce30456654--- /dev/null+++ b/mobile/packages/contacts/.gitignore@@ -0,0 +1,4 @@+.dart_tool/+.flutter-plugins-dependencies+build/+diff --git a/mobile/packages/contacts/lib/contacts.dart b/mobile/packages/contacts/lib/contacts.dartnew file mode 100644index 0000000000..2882322f2a--- /dev/null+++ b/mobile/packages/contacts/lib/contacts.dart@@ -0,0 +1,12 @@+library;++/// Shared contacts package for native Flutter apps.+///+/// `ContactsSession.accountKey` means the logged-in user's existing top-level+/// account key, not a contacts-specific key. The package uses it only to+/// unwrap or create the per-user root contact key.+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_service.dart';diff --git a/mobile/packages/contacts/lib/src/db/contacts_database.dart b/mobile/packages/contacts/lib/src/db/contacts_database.dartnew file mode 100644index 0000000000..a2b24810ab--- /dev/null+++ b/mobile/packages/contacts/lib/src/db/contacts_database.dart@@ -0,0 +1,297 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:ente_contacts/src/models/contact_data.dart';+import 'package:ente_contacts/src/models/contact_record.dart';+import 'package:path/path.dart' as p;+import 'package:path_provider/path_provider.dart';+import 'package:sqflite_common_ffi/sqflite_ffi.dart';++typedef ContactsDatabaseDirectoryResolver = Future<Directory> Function();++class ContactsDatabase {+ static const _databasePrefix = 'ente.contacts.';+ static const _databaseSuffix = '.db';+ static const _databaseVersion = 1;+ static const _contactsTable = 'contacts';+ static const _attachmentsTable = 'cached_attachments';+ static const _stateTable = 'contact_state';++ ContactsDatabase({ContactsDatabaseDirectoryResolver? directoryResolver})+ : _directoryResolver = directoryResolver;++ final ContactsDatabaseDirectoryResolver? _directoryResolver;++ Database? _database;+ Future<Database>? _dbFuture;+ int? _configuredUserId;++ Future<void> configure({required int userId}) async {+ if (_configuredUserId == userId && _dbFuture != null) {+ return;+ }+ if (_database != null) {+ await _database!.close();+ _database = null;+ }+ _dbFuture = null;+ _configuredUserId = userId;+ }++ Future<Database> get database async {+ final userId = _configuredUserId;+ if (userId == null) {+ throw StateError(+ 'ContactsDatabase.configure(userId: ...) must be called first',+ );+ }+ _dbFuture ??= _initDatabase(userId);+ _database ??= await _dbFuture!;+ return _database!;+ }++ Future<void> upsertContacts(List<ContactRecord> contacts) async {+ if (contacts.isEmpty) {+ return;+ }+ final db = await database;+ final batch = db.batch();+ for (final contact in contacts) {+ batch.insert(+ _contactsTable,+ {+ 'id': contact.id,+ 'contact_user_id': contact.data?.contactUserId ?? -1,+ 'data_json': contact.data == null+ ? null+ : jsonEncode(contact.data!.toJson()),+ 'profile_picture_attachment_id': contact.profilePictureAttachmentId,+ 'is_deleted': contact.isDeleted ? 1 : 0,+ 'created_at': contact.createdAt,+ 'updated_at': contact.updatedAt,+ },+ conflictAlgorithm: ConflictAlgorithm.replace,+ );+ }+ await batch.commit(noResult: true);+ }++ Future<ContactRecord?> getContact(String id) async {+ final db = await database;+ final rows = await db.query(+ _contactsTable,+ where: 'id = ?',+ whereArgs: [id],+ limit: 1,+ );+ if (rows.isEmpty) {+ return null;+ }+ return _fromRow(rows.first);+ }++ Future<List<ContactRecord>> getContacts({bool includeDeleted = false}) async {+ final db = await database;+ final rows = await db.query(+ _contactsTable,+ where: includeDeleted ? null : 'is_deleted = 0',+ orderBy: 'updated_at DESC',+ );+ return rows.map(_fromRow).toList(growable: false);+ }++ Future<int> getLastSyncedUpdatedAt() async {+ final db = await database;+ final rows = await db.query(_stateTable, limit: 1);+ if (rows.isEmpty) {+ return 0;+ }+ return (rows.first['last_synced_updated_at'] as int?) ?? 0;+ }++ Future<void> setLastSyncedUpdatedAt(int value) async {+ final db = await database;+ await db.update(+ _stateTable,+ {+ 'id': 1,+ 'last_synced_updated_at': value,+ },+ where: 'id = 1',+ );+ }++ Future<void> resetState() async {+ final db = await database;+ await db.delete(_contactsTable);+ await db.delete(_attachmentsTable);+ await setLastSyncedUpdatedAt(0);+ }++ Future<Uint8List?> getCachedAttachment(String attachmentId) async {+ final db = await database;+ final rows = await db.query(+ _attachmentsTable,+ columns: const ['bytes'],+ where: 'attachment_id = ?',+ whereArgs: [attachmentId],+ limit: 1,+ );+ if (rows.isEmpty) {+ return null;+ }+ return rows.first['bytes'] as Uint8List?;+ }++ Future<void> upsertCachedAttachment(+ String attachmentId,+ Uint8List bytes,+ ) async {+ final db = await database;+ await db.insert(+ _attachmentsTable,+ {+ 'attachment_id': attachmentId,+ 'bytes': bytes,+ 'cached_at': DateTime.now().millisecondsSinceEpoch,+ },+ conflictAlgorithm: ConflictAlgorithm.replace,+ );+ }++ Future<void> deleteCachedAttachment(String attachmentId) async {+ final db = await database;+ await db.delete(+ _attachmentsTable,+ where: 'attachment_id = ?',+ whereArgs: [attachmentId],+ );+ }++ Future<void> deleteUnreferencedCachedAttachments() async {+ final db = await database;+ await db.delete(+ _attachmentsTable,+ where:+ '''+ attachment_id NOT IN (+ SELECT profile_picture_attachment_id+ FROM $_contactsTable+ WHERE profile_picture_attachment_id IS NOT NULL+ )+ ''',+ );+ }++ Future<void> clearTable() async {+ if (_database != null) {+ await _database!.close();+ _database = null;+ _dbFuture = null;+ }+ final directory = await _resolvedDirectory();+ if (!directory.existsSync()) {+ return;+ }+ for (final entity in directory.listSync()) {+ final name = p.basename(entity.path);+ if (name.startsWith(_databasePrefix)) {+ if (entity is File) {+ await entity.delete();+ }+ }+ }+ }++ Future<Database> _initDatabase(int userId) async {+ final path = p.join(+ (await _resolvedDirectory()).path,+ '$_databasePrefix$userId$_databaseSuffix',+ );++ if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {+ sqfliteFfiInit();+ final databaseFactory = databaseFactoryFfi;+ return databaseFactory.openDatabase(+ path,+ options: OpenDatabaseOptions(+ version: _databaseVersion,+ onCreate: _onCreate,+ ),+ );+ }++ return openDatabase(path, version: _databaseVersion, onCreate: _onCreate);+ }++ Future<void> _onCreate(Database db, int version) async {+ await db.execute('''+ CREATE TABLE $_contactsTable (+ id TEXT PRIMARY KEY,+ contact_user_id INTEGER NOT NULL,+ data_json TEXT,+ profile_picture_attachment_id TEXT,+ is_deleted INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ )+ ''');+ await db.execute(+ 'CREATE UNIQUE INDEX idx_contacts_contact_user_id ON $_contactsTable(contact_user_id)',+ );+ await db.execute(+ 'CREATE INDEX idx_contacts_updated_at ON $_contactsTable(updated_at)',+ );+ await db.execute('''+ CREATE TABLE $_attachmentsTable (+ attachment_id TEXT PRIMARY KEY,+ bytes BLOB NOT NULL,+ cached_at INTEGER NOT NULL+ )+ ''');+ await db.execute('''+ CREATE TABLE $_stateTable (+ id INTEGER PRIMARY KEY CHECK (id = 1),+ last_synced_updated_at INTEGER NOT NULL DEFAULT 0+ )+ ''');+ await db.insert(_stateTable, {'id': 1, 'last_synced_updated_at': 0});+ }++ Future<Directory> _resolvedDirectory() async {+ if (_directoryResolver != null) {+ final directory = await _directoryResolver!();+ if (!directory.existsSync()) {+ await directory.create(recursive: true);+ }+ return directory;+ }+ final Directory directory;+ if (Platform.isMacOS) {+ directory = await getApplicationSupportDirectory();+ } else {+ directory = await getApplicationDocumentsDirectory();+ }+ if (!directory.existsSync()) {+ await directory.create(recursive: true);+ }+ return directory;+ }++ ContactRecord _fromRow(Map<String, Object?> row) {+ final dataJson = row['data_json'] as String?;+ return ContactRecord(+ id: row['id']! as String,+ data: dataJson == null+ ? null+ : ContactData.fromJson(jsonDecode(dataJson) as Map<String, dynamic>),+ profilePictureAttachmentId:+ row['profile_picture_attachment_id'] as String?,+ isDeleted: (row['is_deleted'] as int? ?? 0) == 1,+ createdAt: row['created_at']! as int,+ updatedAt: row['updated_at']! as int,+ );+ }+}diff --git a/mobile/packages/contacts/lib/src/models/contact_data.dart b/mobile/packages/contacts/lib/src/models/contact_data.dartnew file mode 100644index 0000000000..a51f0631f7--- /dev/null+++ b/mobile/packages/contacts/lib/src/models/contact_data.dart@@ -0,0 +1,36 @@+import 'dart:convert';++class ContactData {+ final int contactUserId;+ final String email;+ final String name;+ final String? birthDate;++ const ContactData({+ required this.contactUserId,+ required this.email,+ required this.name,+ this.birthDate,+ });++ Map<String, dynamic> toJson() => {+ 'contactUserId': contactUserId,+ 'email': email,+ 'name': name,+ if (birthDate != null) 'birthDate': birthDate,+ };++ factory ContactData.fromJson(Map<String, dynamic> json) {+ return ContactData(+ contactUserId: json['contactUserId'] as int,+ email: json['email'] as String,+ name: json['name'] as String,+ birthDate: json['birthDate'] as String?,+ );+ }++ String toEncodedJson() => jsonEncode(toJson());++ factory ContactData.fromEncodedJson(String jsonValue) =>+ ContactData.fromJson(jsonDecode(jsonValue) as Map<String, dynamic>);+}diff --git a/mobile/packages/contacts/lib/src/models/contact_record.dart b/mobile/packages/contacts/lib/src/models/contact_record.dartnew file mode 100644index 0000000000..674887635d--- /dev/null+++ b/mobile/packages/contacts/lib/src/models/contact_record.dart@@ -0,0 +1,21 @@+import 'package:ente_contacts/src/models/contact_data.dart';++class ContactRecord {+ final String id;+ final ContactData? data;+ final String? profilePictureAttachmentId;+ final bool isDeleted;+ final int createdAt;+ final int updatedAt;++ const ContactRecord({+ required this.id,+ required this.data,+ required this.profilePictureAttachmentId,+ required this.isDeleted,+ required this.createdAt,+ required this.updatedAt,+ });++ int get contactUserId => data?.contactUserId ?? -1;+}diff --git a/mobile/packages/contacts/lib/src/models/contacts_session.dart b/mobile/packages/contacts/lib/src/models/contacts_session.dartnew file mode 100644index 0000000000..b9b2b68ca2--- /dev/null+++ b/mobile/packages/contacts/lib/src/models/contacts_session.dart@@ -0,0 +1,55 @@+import 'dart:typed_data';++/// Resolves the logged-in user's existing top-level account key on demand.+typedef AccountKeyProvider = Future<Uint8List> Function();++/// Session input for opening contacts.+///+/// `accountKey` means the logged-in user's existing top-level account key.+/// It is the same conceptual key that Photos currently exposes via+/// `Configuration.instance.getKey()`. It is not a contacts-specific key.+///+/// The contacts package uses this key only to unwrap or create the per-user+/// root contact key stored under `/user-entity/key?type=contact`.+class ContactsSession {+ final String baseUrl;+ final String authToken;+ final int userId;++ /// The logged-in user's existing top-level account key.+ final Uint8List? accountKey;++ /// Lazy resolver for the logged-in user's existing top-level account key.+ final AccountKeyProvider? accountKeyProvider;+ final String? userAgent;+ final String? clientPackage;+ final String? clientVersion;++ ContactsSession({+ required this.baseUrl,+ required this.authToken,+ required this.userId,+ this.accountKey,+ this.accountKeyProvider,+ this.userAgent,+ this.clientPackage,+ this.clientVersion,+ }) : assert(+ accountKey != null || accountKeyProvider != null,+ 'ContactsSession requires accountKey or accountKeyProvider',+ );++ Future<Uint8List> resolveAccountKey() async {+ final accountKey = this.accountKey;+ if (accountKey != null) {+ return accountKey;+ }+ final provider = accountKeyProvider;+ if (provider == null) {+ throw StateError(+ 'ContactsSession requires accountKey or accountKeyProvider',+ );+ }+ return provider();+ }+}diff --git a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dartnew file mode 100644index 0000000000..5c4ec79363--- /dev/null+++ b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart@@ -0,0 +1,235 @@+import 'dart:typed_data';++import 'package:ente_contacts/src/models/contact_data.dart';+import 'package:ente_contacts/src/models/contact_record.dart';+import 'package:ente_rust/ente_rust.dart' as rust;++class WrappedRootContactKey {+ final String encryptedKey;+ final String header;++ const WrappedRootContactKey({+ required this.encryptedKey,+ required this.header,+ });+}++enum RootKeySource { cache, server, created }++class OpenContactsContextInput {+ final String baseUrl;+ final String authToken;+ final int userId;+ final Uint8List accountKey;+ final WrappedRootContactKey? cachedRootKey;+ final String? userAgent;+ final String? clientPackage;+ final String? clientVersion;++ const OpenContactsContextInput({+ required this.baseUrl,+ required this.authToken,+ required this.userId,+ required this.accountKey,+ this.cachedRootKey,+ this.userAgent,+ this.clientPackage,+ this.clientVersion,+ });+}++class OpenContactsContextResult {+ final ContactsRustContext ctx;+ final WrappedRootContactKey wrappedRootKey;+ final RootKeySource rootKeySource;++ const OpenContactsContextResult({+ required this.ctx,+ required this.wrappedRootKey,+ required this.rootKeySource,+ });+}++abstract class ContactsRustContext {+ int userId();++ Future<void> updateAuthToken(String authToken);++ WrappedRootContactKey currentWrappedRootKey();++ Future<ContactRecord> createContact(ContactData data);++ Future<ContactRecord> getContact(String contactId);++ Future<List<ContactRecord>> getDiff(int sinceTime, int limit);++ Future<ContactRecord> updateContact(String contactId, ContactData data);++ Future<void> deleteContact(String contactId);++ Future<ContactRecord> setProfilePicture(+ String contactId,+ Uint8List profilePicture,+ );++ Future<Uint8List> getProfilePicture(String contactId);++ Future<ContactRecord> deleteProfilePicture(String contactId);+}++abstract class ContactsRustApi {+ Future<OpenContactsContextResult> open(OpenContactsContextInput input);+}++class FrbContactsRustApi implements ContactsRustApi {+ const FrbContactsRustApi();++ @override+ Future<OpenContactsContextResult> open(OpenContactsContextInput input) async {+ final result = await rust.openContactsCtx(+ input: rust.OpenContactsCtxInput(+ baseUrl: input.baseUrl,+ authToken: input.authToken,+ userId: input.userId,+ masterKey: input.accountKey,+ cachedRootKey: input.cachedRootKey == null+ ? null+ : rust.WrappedRootContactKey(+ encryptedKey: input.cachedRootKey!.encryptedKey,+ header: input.cachedRootKey!.header,+ ),+ userAgent: input.userAgent,+ clientPackage: input.clientPackage,+ clientVersion: input.clientVersion,+ ),+ );++ return OpenContactsContextResult(+ ctx: _FrbContactsRustContext(result.ctx),+ wrappedRootKey: WrappedRootContactKey(+ encryptedKey: result.wrappedRootKey.encryptedKey,+ header: result.wrappedRootKey.header,+ ),+ rootKeySource: switch (result.rootKeySource) {+ rust.RootKeySource.cache => RootKeySource.cache,+ rust.RootKeySource.server => RootKeySource.server,+ rust.RootKeySource.created => RootKeySource.created,+ },+ );+ }+}++class _FrbContactsRustContext implements ContactsRustContext {+ final rust.ContactsCtx _inner;++ const _FrbContactsRustContext(this._inner);++ @override+ int userId() => _inner.userId();++ @override+ Future<void> updateAuthToken(String authToken) {+ return _inner.updateAuthToken(authToken: authToken);+ }++ @override+ WrappedRootContactKey currentWrappedRootKey() {+ final current = _inner.currentWrappedRootKey();+ return WrappedRootContactKey(+ encryptedKey: current.encryptedKey,+ header: current.header,+ );+ }++ @override+ Future<ContactRecord> createContact(ContactData data) async {+ return _fromRustRecord(+ await _inner.createContact(+ data: rust.ContactData(+ contactUserId: data.contactUserId,+ email: data.email,+ name: data.name,+ birthDate: data.birthDate,+ ),+ ),+ );+ }++ @override+ Future<ContactRecord> getContact(String contactId) async {+ return _fromRustRecord(await _inner.getContact(contactId: contactId));+ }++ @override+ Future<List<ContactRecord>> getDiff(int sinceTime, int limit) async {+ final diff = await _inner.getDiff(sinceTime: sinceTime, limit: limit);+ return diff.map(_fromRustRecord).toList(growable: false);+ }++ @override+ Future<ContactRecord> updateContact(+ String contactId,+ ContactData data,+ ) async {+ return _fromRustRecord(+ await _inner.updateContact(+ contactId: contactId,+ data: rust.ContactData(+ contactUserId: data.contactUserId,+ email: data.email,+ name: data.name,+ birthDate: data.birthDate,+ ),+ ),+ );+ }++ @override+ Future<void> deleteContact(String contactId) {+ return _inner.deleteContact(contactId: contactId);+ }++ @override+ Future<ContactRecord> setProfilePicture(+ String contactId,+ Uint8List profilePicture,+ ) async {+ return _fromRustRecord(+ await _inner.setProfilePicture(+ contactId: contactId,+ profilePicture: profilePicture,+ ),+ );+ }++ @override+ Future<Uint8List> getProfilePicture(String contactId) {+ return _inner.getProfilePicture(contactId: contactId);+ }++ @override+ Future<ContactRecord> deleteProfilePicture(String contactId) async {+ return _fromRustRecord(+ await _inner.deleteProfilePicture(contactId: contactId),+ );+ }+}++ContactRecord _fromRustRecord(rust.ContactRecord record) {+ final data = record.isDeleted+ ? null+ : ContactData(+ contactUserId: record.contactUserId,+ email: record.email!,+ name: record.name!,+ birthDate: record.birthDate,+ );+ return ContactRecord(+ id: record.id,+ data: data,+ profilePictureAttachmentId: record.profilePictureAttachmentId,+ isDeleted: record.isDeleted,+ createdAt: record.createdAt,+ updatedAt: record.updatedAt,+ );+}diff --git a/mobile/packages/contacts/lib/src/service/contacts_service.dart b/mobile/packages/contacts/lib/src/service/contacts_service.dartnew file mode 100644index 0000000000..8454909ae7--- /dev/null+++ b/mobile/packages/contacts/lib/src/service/contacts_service.dart@@ -0,0 +1,202 @@+import 'dart:math';+import 'dart:typed_data';++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_record.dart';+import 'package:ente_contacts/src/models/contacts_session.dart';+import 'package:ente_contacts/src/rust/contacts_rust_api.dart';+import 'package:logging/logging.dart';+import 'package:shared_preferences/shared_preferences.dart';++class ContactsService {+ static const _entityKeyPref = 'entity_key_contact';+ static const _entityHeaderPref = 'entity_key_header_contact';+ static const _syncLimit = 5000;++ ContactsService({+ required SharedPreferences preferences,+ ContactsDatabase? database,+ ContactsRustApi? rustApi,+ }) : _preferences = preferences,+ _database = database ?? ContactsDatabase(),+ _rustApi = rustApi ?? const FrbContactsRustApi();++ final SharedPreferences _preferences;+ final ContactsDatabase _database;+ final ContactsRustApi _rustApi;+ final Logger _logger = Logger('ContactsService');++ ContactsRustContext? _ctx;+ ContactsSession? _session;++ Future<void> open(ContactsSession session) async {+ final accountKey = await session.resolveAccountKey();+ final cachedRootKey = _cachedRootKey();+ final opened = await _rustApi.open(+ OpenContactsContextInput(+ baseUrl: session.baseUrl,+ authToken: session.authToken,+ userId: session.userId,+ accountKey: accountKey,+ cachedRootKey: cachedRootKey,+ userAgent: session.userAgent,+ clientPackage: session.clientPackage,+ clientVersion: session.clientVersion,+ ),+ );++ _ctx = opened.ctx;+ _session = session;+ await _database.configure(userId: session.userId);+ await _persistWrappedRootKey(opened.wrappedRootKey);+ _logger.info('Opened contacts context for user ${session.userId}');+ }++ Future<void> updateAuthToken(String authToken) async {+ final ctx = _requireCtx();+ await ctx.updateAuthToken(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<List<ContactRecord>> sync() async {+ final ctx = _requireCtx();+ var sinceTime = await _database.getLastSyncedUpdatedAt();+ final synced = <ContactRecord>[];+ while (true) {+ final diff = await ctx.getDiff(sinceTime, _syncLimit);+ if (diff.isEmpty) {+ break;+ }+ await _database.upsertContacts(diff);+ final maxUpdatedAt = diff.map((e) => e.updatedAt).reduce(max);+ await _database.setLastSyncedUpdatedAt(maxUpdatedAt);+ sinceTime = maxUpdatedAt;+ synced.addAll(diff);+ if (diff.length < _syncLimit) {+ break;+ }+ }+ await _database.deleteUnreferencedCachedAttachments();+ return synced;+ }++ Future<List<ContactRecord>> getContacts({bool includeDeleted = false}) {+ return _database.getContacts(includeDeleted: includeDeleted);+ }++ Future<ContactRecord?> getContact(String contactId) {+ return _database.getContact(contactId);+ }++ Future<ContactRecord> createContact(ContactData data) async {+ final created = await _requireCtx().createContact(data);+ await _database.upsertContacts([created]);+ return created;+ }++ Future<ContactRecord> updateContact(+ String contactId,+ ContactData data,+ ) async {+ final updated = await _requireCtx().updateContact(contactId, data);+ await _database.upsertContacts([updated]);+ return updated;+ }++ Future<void> deleteContact(String contactId) async {+ final ctx = _requireCtx();+ await ctx.deleteContact(contactId);+ final deleted = await ctx.getDiff(0, _syncLimit);+ final matching = deleted+ .where((element) => element.id == contactId)+ .toList();+ if (matching.isNotEmpty) {+ await _database.upsertContacts([matching.first]);+ } else {+ await sync();+ }+ }++ Future<ContactRecord> setProfilePicture(+ String contactId,+ Uint8List bytes,+ ) async {+ final previousAttachmentId = (await _database.getContact(+ contactId,+ ))?.profilePictureAttachmentId;+ final updated = await _requireCtx().setProfilePicture(contactId, bytes);+ await _database.upsertContacts([updated]);+ final nextAttachmentId = updated.profilePictureAttachmentId;+ if (nextAttachmentId != null) {+ await _database.upsertCachedAttachment(nextAttachmentId, bytes);+ }+ if (previousAttachmentId != null &&+ previousAttachmentId != nextAttachmentId) {+ await _database.deleteCachedAttachment(previousAttachmentId);+ }+ return updated;+ }++ 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 a profile picture');+ }+ final cached = await _database.getCachedAttachment(attachmentId);+ if (cached != null) {+ return cached;+ }+ final bytes = await _requireCtx().getProfilePicture(contactId);+ await _database.upsertCachedAttachment(attachmentId, bytes);+ return bytes;+ }++ Future<ContactRecord> deleteProfilePicture(String contactId) async {+ final previousAttachmentId = (await _database.getContact(+ contactId,+ ))?.profilePictureAttachmentId;+ final updated = await _requireCtx().deleteProfilePicture(contactId);+ await _database.upsertContacts([updated]);+ if (previousAttachmentId != null) {+ await _database.deleteCachedAttachment(previousAttachmentId);+ }+ return updated;+ }++ Future<void> resetLocalState() async {+ await _database.resetState();+ }++ ContactsRustContext _requireCtx() {+ final ctx = _ctx;+ if (ctx == null) {+ throw StateError('ContactsService.open(...) must be called before use');+ }+ return ctx;+ }++ WrappedRootContactKey? _cachedRootKey() {+ final encryptedKey = _preferences.getString(_entityKeyPref);+ final header = _preferences.getString(_entityHeaderPref);+ if (encryptedKey == null || header == null) {+ return null;+ }+ return WrappedRootContactKey(encryptedKey: encryptedKey, header: header);+ }++ Future<void> _persistWrappedRootKey(WrappedRootContactKey key) async {+ await _preferences.setString(_entityKeyPref, key.encryptedKey);+ await _preferences.setString(_entityHeaderPref, key.header);+ }+}diff --git a/mobile/packages/contacts/pubspec.lock b/mobile/packages/contacts/pubspec.locknew file mode 100644index 0000000000..fe7349e350--- /dev/null+++ b/mobile/packages/contacts/pubspec.lock@@ -0,0 +1,489 @@+# Generated by pub+# See https://dart.dev/tools/pub/glossary#lockfile+packages:+ args:+ dependency: transitive+ description:+ name: args+ sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04+ url: "https://pub.dev"+ source: hosted+ version: "2.7.0"+ async:+ dependency: transitive+ description:+ name: async+ sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb"+ url: "https://pub.dev"+ source: hosted+ version: "2.13.0"+ boolean_selector:+ dependency: transitive+ description:+ name: boolean_selector+ sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.2"+ build_cli_annotations:+ dependency: transitive+ description:+ name: build_cli_annotations+ sha256: e563c2e01de8974566a1998410d3f6f03521788160a02503b0b1f1a46c7b3d95+ url: "https://pub.dev"+ source: hosted+ version: "2.1.1"+ characters:+ dependency: transitive+ description:+ name: characters+ sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803+ url: "https://pub.dev"+ source: hosted+ version: "1.4.0"+ clock:+ dependency: transitive+ description:+ name: clock+ sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b+ url: "https://pub.dev"+ source: hosted+ version: "1.1.2"+ collection:+ dependency: transitive+ description:+ name: collection+ sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"+ url: "https://pub.dev"+ source: hosted+ version: "1.19.1"+ ente_rust:+ dependency: "direct main"+ description:+ path: "../rust"+ relative: true+ source: path+ version: "0.0.1"+ fake_async:+ dependency: transitive+ description:+ name: fake_async+ sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"+ url: "https://pub.dev"+ source: hosted+ version: "1.3.3"+ ffi:+ dependency: transitive+ description:+ name: ffi+ sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"+ url: "https://pub.dev"+ source: hosted+ version: "2.2.0"+ file:+ dependency: transitive+ description:+ name: file+ sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4+ url: "https://pub.dev"+ source: hosted+ version: "7.0.1"+ flutter:+ dependency: "direct main"+ description: flutter+ source: sdk+ version: "0.0.0"+ flutter_lints:+ dependency: "direct dev"+ description:+ name: flutter_lints+ sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1"+ url: "https://pub.dev"+ source: hosted+ version: "5.0.0"+ flutter_rust_bridge:+ dependency: transitive+ description:+ name: flutter_rust_bridge+ sha256: e87d6b9ee934dcd24a128ccb2bd91905d2d5fe5c06245d6a8f5477d4907a437a+ url: "https://pub.dev"+ source: hosted+ version: "2.12.0"+ flutter_test:+ dependency: "direct dev"+ description: flutter+ source: sdk+ version: "0.0.0"+ flutter_web_plugins:+ dependency: transitive+ description: flutter+ source: sdk+ version: "0.0.0"+ freezed_annotation:+ dependency: transitive+ description:+ name: freezed_annotation+ sha256: "7294967ff0a6d98638e7acb774aac3af2550777accd8149c90af5b014e6d44d8"+ url: "https://pub.dev"+ source: hosted+ version: "3.1.0"+ json_annotation:+ dependency: transitive+ description:+ name: json_annotation+ sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1"+ url: "https://pub.dev"+ source: hosted+ version: "4.9.0"+ leak_tracker:+ dependency: transitive+ description:+ name: leak_tracker+ sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0"+ url: "https://pub.dev"+ source: hosted+ version: "10.0.9"+ leak_tracker_flutter_testing:+ dependency: transitive+ description:+ name: leak_tracker_flutter_testing+ sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573+ url: "https://pub.dev"+ source: hosted+ version: "3.0.9"+ leak_tracker_testing:+ dependency: transitive+ description:+ name: leak_tracker_testing+ sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"+ url: "https://pub.dev"+ source: hosted+ version: "3.0.1"+ lints:+ dependency: transitive+ description:+ name: lints+ sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7+ url: "https://pub.dev"+ source: hosted+ version: "5.1.1"+ logging:+ dependency: "direct main"+ description:+ name: logging+ sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61+ url: "https://pub.dev"+ source: hosted+ version: "1.3.0"+ matcher:+ dependency: transitive+ description:+ name: matcher+ sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2+ url: "https://pub.dev"+ source: hosted+ version: "0.12.17"+ material_color_utilities:+ dependency: transitive+ description:+ name: material_color_utilities+ sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec+ url: "https://pub.dev"+ source: hosted+ version: "0.11.1"+ meta:+ dependency: transitive+ description:+ name: meta+ sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c+ url: "https://pub.dev"+ source: hosted+ version: "1.16.0"+ path:+ dependency: "direct main"+ description:+ name: path+ sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"+ url: "https://pub.dev"+ source: hosted+ version: "1.9.1"+ path_provider:+ dependency: "direct main"+ description:+ name: path_provider+ sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.5"+ path_provider_android:+ dependency: transitive+ description:+ name: path_provider_android+ sha256: "3b4c1fc3aa55ddc9cd4aa6759984330d5c8e66aa7702a6223c61540dc6380c37"+ url: "https://pub.dev"+ source: hosted+ version: "2.2.19"+ path_provider_foundation:+ dependency: transitive+ description:+ name: path_provider_foundation+ sha256: "16eef174aacb07e09c351502740fa6254c165757638eba1e9116b0a781201bbd"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.2"+ path_provider_linux:+ dependency: transitive+ description:+ name: path_provider_linux+ sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279+ url: "https://pub.dev"+ source: hosted+ version: "2.2.1"+ path_provider_platform_interface:+ dependency: transitive+ description:+ name: path_provider_platform_interface+ sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.2"+ path_provider_windows:+ dependency: transitive+ description:+ name: path_provider_windows+ sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7+ url: "https://pub.dev"+ source: hosted+ version: "2.3.0"+ platform:+ dependency: transitive+ description:+ name: platform+ sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984"+ url: "https://pub.dev"+ source: hosted+ version: "3.1.6"+ plugin_platform_interface:+ dependency: transitive+ description:+ name: plugin_platform_interface+ sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.8"+ shared_preferences:+ dependency: "direct main"+ description:+ name: shared_preferences+ sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5"+ url: "https://pub.dev"+ source: hosted+ version: "2.5.3"+ shared_preferences_android:+ dependency: transitive+ description:+ name: shared_preferences_android+ sha256: bd14436108211b0d4ee5038689a56d4ae3620fd72fd6036e113bf1345bc74d9e+ url: "https://pub.dev"+ source: hosted+ version: "2.4.13"+ shared_preferences_foundation:+ dependency: transitive+ description:+ name: shared_preferences_foundation+ sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03"+ url: "https://pub.dev"+ source: hosted+ version: "2.5.4"+ shared_preferences_linux:+ dependency: transitive+ description:+ name: shared_preferences_linux+ sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.1"+ shared_preferences_platform_interface:+ dependency: transitive+ description:+ name: shared_preferences_platform_interface+ sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.1"+ shared_preferences_web:+ dependency: transitive+ description:+ name: shared_preferences_web+ sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019+ url: "https://pub.dev"+ source: hosted+ version: "2.4.3"+ shared_preferences_windows:+ dependency: transitive+ description:+ name: shared_preferences_windows+ sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.1"+ sky_engine:+ dependency: transitive+ description: flutter+ source: sdk+ version: "0.0.0"+ source_span:+ dependency: transitive+ description:+ name: source_span+ sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c"+ url: "https://pub.dev"+ source: hosted+ version: "1.10.1"+ sqflite:+ dependency: "direct main"+ description:+ name: sqflite+ sha256: e2297b1da52f127bc7a3da11439985d9b536f75070f3325e62ada69a5c585d03+ url: "https://pub.dev"+ source: hosted+ version: "2.4.2"+ sqflite_android:+ dependency: transitive+ description:+ name: sqflite_android+ sha256: "2b3070c5fa881839f8b402ee4a39c1b4d561704d4ebbbcfb808a119bc2a1701b"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.1"+ sqflite_common:+ dependency: transitive+ description:+ name: sqflite_common+ sha256: "6ef422a4525ecc601db6c0a2233ff448c731307906e92cabc9ba292afaae16a6"+ url: "https://pub.dev"+ source: hosted+ version: "2.5.6"+ sqflite_common_ffi:+ dependency: "direct main"+ description:+ name: sqflite_common_ffi+ sha256: "9faa2fedc5385ef238ce772589f7718c24cdddd27419b609bb9c6f703ea27988"+ url: "https://pub.dev"+ source: hosted+ version: "2.3.6"+ sqflite_darwin:+ dependency: transitive+ description:+ name: sqflite_darwin+ sha256: "279832e5cde3fe99e8571879498c9211f3ca6391b0d818df4e17d9fff5c6ccb3"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.2"+ sqflite_platform_interface:+ dependency: transitive+ description:+ name: sqflite_platform_interface+ sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.0"+ sqlite3:+ dependency: transitive+ description:+ name: sqlite3+ sha256: "3145bd74dcdb4fd6f5c6dda4d4e4490a8087d7f286a14dee5d37087290f0f8a2"+ url: "https://pub.dev"+ source: hosted+ version: "2.9.4"+ stack_trace:+ dependency: transitive+ description:+ name: stack_trace+ sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"+ url: "https://pub.dev"+ source: hosted+ version: "1.12.1"+ stream_channel:+ dependency: transitive+ description:+ name: stream_channel+ sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.4"+ string_scanner:+ dependency: transitive+ description:+ name: string_scanner+ sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"+ url: "https://pub.dev"+ source: hosted+ version: "1.4.1"+ synchronized:+ dependency: transitive+ description:+ name: synchronized+ sha256: c254ade258ec8282947a0acbbc90b9575b4f19673533ee46f2f6e9b3aeefd7c0+ url: "https://pub.dev"+ source: hosted+ version: "3.4.0"+ term_glyph:+ dependency: transitive+ description:+ name: term_glyph+ sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"+ url: "https://pub.dev"+ source: hosted+ version: "1.2.2"+ test_api:+ dependency: transitive+ description:+ name: test_api+ sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd+ url: "https://pub.dev"+ source: hosted+ version: "0.7.4"+ typed_data:+ dependency: transitive+ description:+ name: typed_data+ sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006+ url: "https://pub.dev"+ source: hosted+ version: "1.4.0"+ vector_math:+ dependency: transitive+ description:+ name: vector_math+ sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.4"+ vm_service:+ dependency: transitive+ description:+ name: vm_service+ sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02+ url: "https://pub.dev"+ source: hosted+ version: "15.0.0"+ web:+ dependency: transitive+ description:+ name: web+ sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"+ url: "https://pub.dev"+ source: hosted+ version: "1.1.1"+ xdg_directories:+ dependency: transitive+ description:+ name: xdg_directories+ sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"+ url: "https://pub.dev"+ source: hosted+ version: "1.1.0"+sdks:+ dart: ">=3.8.0 <4.0.0"+ flutter: ">=3.29.0"diff --git a/mobile/packages/contacts/pubspec.yaml b/mobile/packages/contacts/pubspec.yamlnew file mode 100644index 0000000000..5909212ab5--- /dev/null+++ b/mobile/packages/contacts/pubspec.yaml@@ -0,0 +1,27 @@+name: ente_contacts+description: Shared contacts client, cache, and Rust orchestration for Ente apps+version: 1.0.0+publish_to: none++environment:+ sdk: ">=3.0.0 <4.0.0"+ flutter: ">=1.17.0"++dependencies:+ ente_rust:+ path: ../rust+ flutter:+ sdk: flutter+ logging: ^1.2.0+ path: ^1.9.1+ path_provider: ^2.1.5+ shared_preferences: ^2.2.3+ sqflite: ^2.4.2+ sqflite_common_ffi: ^2.3.6++dev_dependencies:+ flutter_lints: ^5.0.0+ flutter_test:+ sdk: flutter++flutter:diff --git a/mobile/packages/contacts/test/contacts_database_test.dart b/mobile/packages/contacts/test/contacts_database_test.dartnew file mode 100644index 0000000000..6258e54e4d--- /dev/null+++ b/mobile/packages/contacts/test/contacts_database_test.dart@@ -0,0 +1,124 @@+import 'dart:io';+import 'dart:typed_data';++import 'package:ente_contacts/contacts.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:sqflite_common_ffi/sqflite_ffi.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ sqfliteFfiInit();++ late Directory tempDir;+ late ContactsDatabase database;++ setUp(() async {+ tempDir = await Directory.systemTemp.createTemp('ente_contacts_db_test');+ database = ContactsDatabase(directoryResolver: () async => tempDir);+ });++ tearDown(() async {+ await database.clearTable();+ if (tempDir.existsSync()) {+ await tempDir.delete(recursive: true);+ }+ });++ test('stores contacts in user-scoped databases', () async {+ await database.configure(userId: 1);+ await database.upsertContacts([+ const ContactRecord(+ id: 'ct_1',+ data: ContactData(contactUserId: 200, email: '[email protected]', name: 'A'),+ profilePictureAttachmentId: null,+ isDeleted: false,+ createdAt: 10,+ updatedAt: 20,+ ),+ ]);++ expect((await database.getContacts()).length, 1);++ await database.configure(userId: 2);+ expect(await database.getContacts(), isEmpty);++ await database.configure(userId: 1);+ expect((await database.getContacts()).single.id, 'ct_1');+ });++ test('clearTable removes all contacts databases', () async {+ await database.configure(userId: 1);+ await database.upsertContacts([+ const ContactRecord(+ id: 'ct_1',+ data: ContactData(contactUserId: 200, email: '[email protected]', name: 'A'),+ profilePictureAttachmentId: null,+ isDeleted: false,+ createdAt: 10,+ updatedAt: 20,+ ),+ ]);+ await database.configure(userId: 2);+ await database.upsertContacts([+ const ContactRecord(+ id: 'ct_2',+ data: ContactData(contactUserId: 201, email: '[email protected]', name: 'B'),+ profilePictureAttachmentId: null,+ isDeleted: false,+ createdAt: 11,+ updatedAt: 21,+ ),+ ]);++ await database.clearTable();++ final remaining = tempDir+ .listSync()+ .map((entity) => entity.path.split(Platform.pathSeparator).last)+ .where((name) => name.startsWith('ente.contacts.'))+ .toList();+ expect(remaining, isEmpty);+ });++ test('stores, fetches, deletes, and prunes cached attachments', () async {+ await database.configure(userId: 1);+ await database.upsertContacts([+ const ContactRecord(+ id: 'ct_1',+ data: ContactData(contactUserId: 200, email: '[email protected]', name: 'A'),+ profilePictureAttachmentId: 'att_keep',+ isDeleted: false,+ createdAt: 10,+ updatedAt: 20,+ ),+ ]);+ await database.upsertCachedAttachment(+ 'att_keep',+ Uint8List.fromList([1, 2, 3]),+ );+ await database.upsertCachedAttachment(+ 'att_drop',+ Uint8List.fromList([4, 5, 6]),+ );++ expect(+ await database.getCachedAttachment('att_keep'),+ Uint8List.fromList([1, 2, 3]),+ );++ await database.deleteCachedAttachment('att_keep');+ expect(await database.getCachedAttachment('att_keep'), isNull);++ await database.upsertCachedAttachment(+ 'att_keep',+ Uint8List.fromList([1, 2, 3]),+ );+ await database.deleteUnreferencedCachedAttachments();++ expect(+ await database.getCachedAttachment('att_keep'),+ Uint8List.fromList([1, 2, 3]),+ );+ expect(await database.getCachedAttachment('att_drop'), isNull);+ });+}diff --git a/mobile/packages/contacts/test/contacts_service_test.dart b/mobile/packages/contacts/test/contacts_service_test.dartnew file mode 100644index 0000000000..3dc03f13a4--- /dev/null+++ b/mobile/packages/contacts/test/contacts_service_test.dart@@ -0,0 +1,402 @@+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 service;++ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ preferences = await SharedPreferences.getInstance();+ tempDir = await Directory.systemTemp.createTemp(+ 'ente_contacts_service_test',+ );+ rustApi = FakeContactsRustApi();+ database = ContactsDatabase(directoryResolver: () async => tempDir);+ service = ContactsService(+ preferences: preferences,+ rustApi: rustApi,+ database: database,+ );+ });++ tearDown(() async {+ await service.resetLocalState();+ if (tempDir.existsSync()) {+ await tempDir.delete(recursive: true);+ }+ });++ test('open persists wrapped root key and sync caches contacts', () async {+ rustApi.diffPages = [+ [+ const ContactRecord(+ id: 'ct_1',+ data: ContactData(+ contactUserId: 2,+ email: '[email protected]',+ name: 'B',+ birthDate: '2001-04-02',+ ),+ profilePictureAttachmentId: 'att_1',+ isDeleted: false,+ createdAt: 10,+ updatedAt: 20,+ ),+ ],+ const [],+ ];++ await service.open(+ ContactsSession(+ baseUrl: 'http://localhost:8080',+ authToken: 'token',+ userId: 1,+ accountKey: Uint8List.fromList([1, 2, 3]),+ ),+ );++ expect(preferences.getString('entity_key_contact'), 'enc-key');+ expect(preferences.getString('entity_key_header_contact'), 'enc-header');++ final synced = await service.sync();+ expect(synced, hasLength(1));+ final cached = await service.getContacts();+ expect(cached.single.data!.email, '[email protected]');+ expect(cached.single.profilePictureAttachmentId, 'att_1');+ });++ test('create and profile-picture changes update local cache', () async {+ await service.open(+ ContactsSession(+ baseUrl: 'http://localhost:8080',+ authToken: 'token',+ userId: 1,+ accountKey: Uint8List.fromList([1, 2, 3]),+ ),+ );++ final created = await service.createContact(+ const ContactData(contactUserId: 2, email: '[email protected]', name: 'B'),+ );+ expect((await service.getContact(created.id))!.data!.name, 'B');++ final updated = await service.setProfilePicture(+ created.id,+ Uint8List.fromList([1, 2, 3, 4]),+ );+ expect(updated.profilePictureAttachmentId, 'att_profile');+ expect(+ (await service.getContact(created.id))!.profilePictureAttachmentId,+ 'att_profile',+ );+ expect(+ await service.getProfilePicture(created.id),+ Uint8List.fromList([1, 2, 3, 4]),+ );+ expect(rustApi.ctx.getProfilePictureCalls, 0);++ final deletedPicture = await service.deleteProfilePicture(created.id);+ expect(deletedPicture.profilePictureAttachmentId, isNull);+ expect(+ (await service.getContact(created.id))!.profilePictureAttachmentId,+ isNull,+ );+ 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 = [+ [+ const ContactRecord(+ id: 'ct_1',+ data: ContactData(contactUserId: 2, email: '[email protected]', name: 'B'),+ profilePictureAttachmentId: 'att_1',+ isDeleted: false,+ createdAt: 10,+ updatedAt: 20,+ ),+ ],+ const [],+ ];+ rustApi.ctx.pictures['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]),+ ),+ );+ await service.sync();++ expect(+ await service.getProfilePicture('ct_1'),+ Uint8List.fromList([7, 8, 9]),+ );+ expect(rustApi.ctx.getProfilePictureCalls, 1);+ expect(+ await service.getProfilePicture('ct_1'),+ Uint8List.fromList([7, 8, 9]),+ );+ expect(rustApi.ctx.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]),+ ),+ );++ final created = await service.createContact(+ const ContactData(contactUserId: 2, email: '[email protected]', name: 'B'),+ );+ await service.setProfilePicture(created.id, Uint8List.fromList([1, 2, 3]));+ expect(+ await service.getProfilePicture(created.id),+ Uint8List.fromList([1, 2, 3]),+ );++ rustApi.ctx.nextAttachmentId = 'att_profile_v2';+ final replaced = await service.setProfilePicture(+ created.id,+ Uint8List.fromList([4, 5, 6]),+ );++ expect(replaced.profilePictureAttachmentId, 'att_profile_v2');+ expect(+ await service.getProfilePicture(created.id),+ Uint8List.fromList([4, 5, 6]),+ );+ expect(await database.getCachedAttachment('att_profile'), isNull);+ expect(+ await database.getCachedAttachment('att_profile_v2'),+ Uint8List.fromList([4, 5, 6]),+ );+ });++ test(+ 'sync prunes cached attachments no longer referenced by contacts',+ () async {+ rustApi.diffPages = [+ [+ const ContactRecord(+ id: 'ct_1',+ data: ContactData(+ contactUserId: 2,+ email: '[email protected]',+ name: 'B',+ ),+ profilePictureAttachmentId: 'att_keep',+ isDeleted: false,+ createdAt: 10,+ updatedAt: 20,+ ),+ ],+ const [],+ ];++ await service.open(+ ContactsSession(+ baseUrl: 'http://localhost:8080',+ authToken: 'token',+ userId: 1,+ accountKey: Uint8List.fromList([1, 2, 3]),+ ),+ );+ await database.upsertCachedAttachment(+ 'att_keep',+ Uint8List.fromList([1]),+ );+ await database.upsertCachedAttachment(+ 'att_drop',+ Uint8List.fromList([2]),+ );++ await service.sync();++ expect(+ await database.getCachedAttachment('att_keep'),+ Uint8List.fromList([1]),+ );+ expect(await database.getCachedAttachment('att_drop'), isNull);+ },+ );+}++class FakeContactsRustApi implements ContactsRustApi {+ FakeContactsRustContext ctx = FakeContactsRustContext();+ List<List<ContactRecord>> diffPages = const [];+ Uint8List? lastAccountKey;++ @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,+ 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> pictures = {};+ List<List<ContactRecord>> diffPages = [];+ int getProfilePictureCalls = 0;+ String nextAttachmentId = 'att_profile';++ @override+ Future<ContactRecord> createContact(ContactData data) async {+ final record = ContactRecord(+ id: 'ct_created',+ 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,+ data: null,+ profilePictureAttachmentId: null,+ isDeleted: true,+ createdAt: existing.createdAt,+ updatedAt: existing.updatedAt + 1,+ );+ }+ }++ @override+ Future<ContactRecord> deleteProfilePicture(String contactId) async {+ final existing = records[contactId]!;+ final updated = ContactRecord(+ id: existing.id,+ data: existing.data,+ profilePictureAttachmentId: null,+ isDeleted: existing.isDeleted,+ createdAt: existing.createdAt,+ updatedAt: existing.updatedAt + 1,+ );+ records[contactId] = updated;+ pictures.remove(contactId);+ return updated;+ }++ @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> getProfilePicture(String contactId) async {+ getProfilePictureCalls += 1;+ return pictures[contactId]!;+ }++ @override+ Future<ContactRecord> setProfilePicture(+ String contactId,+ Uint8List profilePicture,+ ) async {+ final existing = records[contactId]!;+ final updated = ContactRecord(+ id: existing.id,+ data: existing.data,+ profilePictureAttachmentId: nextAttachmentId,+ isDeleted: existing.isDeleted,+ createdAt: existing.createdAt,+ updatedAt: existing.updatedAt + 1,+ );+ records[contactId] = updated;+ pictures[contactId] = profilePicture;+ return updated;+ }++ @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,+ data: data,+ profilePictureAttachmentId: existing.profilePictureAttachmentId,+ isDeleted: existing.isDeleted,+ createdAt: existing.createdAt,+ updatedAt: existing.updatedAt + 1,+ );+ records[contactId] = updated;+ return updated;+ }++ @override+ int userId() => userIdValue;+}