Skip to content

armgit / ente

Public Imported from GitHub
0

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

Share sessions and domain projections across clients

Manav Rathic0883a01e7e7
diff --git a/mobile/apps/locker/flutter_rust_bridge.yaml b/mobile/apps/locker/flutter_rust_bridge.yaml
index cf324bf3c8..96edd2ee87 100644
--- a/mobile/apps/locker/flutter_rust_bridge.yaml
+++ b/mobile/apps/locker/flutter_rust_bridge.yaml
@@ -1,4 +1,4 @@
-rust_input: crate::api
+rust_input: crate::api, ente-frb-contacts, ente-frb-core
rust_root: ../../../rust/bindings/frb/locker/
dart_output: lib/src/rust
dart_entrypoint_class_name: EnteLockerRust
diff --git a/mobile/apps/locker/lib/main.dart b/mobile/apps/locker/lib/main.dart
index e2e9c83e80..ebd629d220 100644
--- a/mobile/apps/locker/lib/main.dart
+++ b/mobile/apps/locker/lib/main.dart
@@ -10,7 +10,7 @@ import 'package:ente_crypto_api/ente_crypto_api.dart';
import 'package:ente_crypto_dart_adapter/ente_crypto_dart_adapter.dart';
import 'package:ente_install_source/ente_install_source.dart';
import "package:ente_legacy/services/emergency_service.dart";
-import "package:ente_legacy/services/legacy_kit_service.dart";
+import "package:ente_legacy/services/legacy_kit_share_file_service.dart";
import 'package:ente_lock_screen/lock_screen_settings.dart';
import 'package:ente_lock_screen/ui/app_lock.dart';
import 'package:ente_lock_screen/ui/lock_screen.dart';
@@ -34,7 +34,6 @@ 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';
-import 'package:locker/services/frb_legacy_kit_rust_api.dart';
import 'package:locker/services/local_settings.dart';
import 'package:locker/services/trash/trash_service.dart';
import 'package:locker/services/update_service.dart';
@@ -228,11 +227,7 @@ Future<void> _init(bool bool, {String? via}) async {
preferences: preferences,
packageInfo: packageInfo,
);
- await LegacyKitService.instance.init(
- config: Configuration.instance,
- sessionProvider: LockerContactsDisplayService.buildSession,
- rustApi: const FrbLegacyKitRustApi(),
- );
+ unawaited(cleanStaleLegacyKitShareFiles());
unawaited(
Future.delayed(
const Duration(seconds: 5),
diff --git a/mobile/apps/locker/lib/services/authenticated_session.dart b/mobile/apps/locker/lib/services/authenticated_session.dart
new file mode 100644
index 0000000000..e419b49ec7
--- /dev/null
+++ b/mobile/apps/locker/lib/services/authenticated_session.dart
@@ -0,0 +1,29 @@
+import 'package:ente_contacts/contacts.dart';
+import 'package:locker/src/rust/third_party/ente_frb_core.dart';
+
+Session? _session;
+String? _sessionKey;
+
+Session authenticatedSession(ContactsSession? account) {
+ if (account == null) {
+ throw StateError('Authenticated session is not available');
+ }
+ final key = '${account.baseUrl}|${account.userId}';
+ final current = _session;
+ if (current != null && _sessionKey == key) {
+ current.updateAuthToken(authToken: account.authToken);
+ return current;
+ }
+
+ final opened = openSession(
+ baseUrl: account.baseUrl,
+ authToken: account.authToken,
+ masterKey: account.accountKey,
+ userAgent: account.userAgent,
+ clientPackage: account.clientPackage,
+ clientVersion: account.clientVersion,
+ );
+ _session = opened;
+ _sessionKey = key;
+ return opened;
+}
diff --git a/mobile/apps/locker/lib/services/contacts.dart b/mobile/apps/locker/lib/services/contacts.dart
new file mode 100644
index 0000000000..aa1467ad44
--- /dev/null
+++ b/mobile/apps/locker/lib/services/contacts.dart
@@ -0,0 +1,137 @@
+import 'dart:typed_data';
+
+import 'package:ente_contacts/contacts.dart';
+import 'package:locker/src/rust/third_party/ente_frb_contacts.dart' as rust;
+import 'package:locker/src/rust/third_party/ente_frb_core.dart';
+
+Future<ContactOutput<ContactRecord>> createContact(
+ Session session,
+ WrappedRootContactKey? key,
+ ContactData data,
+) async {
+ final output = await rust.createContact(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ data: rust.ContactData(contactUserId: data.contactUserId, name: data.name),
+ );
+ return _output(_fromRustRecord(output.record), output.wrappedRootContactKey);
+}
+
+Future<ContactOutput<List<ContactRecord>>> getDiff(
+ Session session,
+ WrappedRootContactKey? key,
+ int sinceTime,
+ int limit,
+) async {
+ final output = await rust.getDiff(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ sinceTime: sinceTime,
+ limit: limit,
+ );
+ return _output(
+ output.records.map(_fromRustRecord).toList(growable: false),
+ output.wrappedRootContactKey,
+ );
+}
+
+Future<ContactOutput<ContactRecord>> updateContact(
+ Session session,
+ WrappedRootContactKey? key,
+ String contactId,
+ ContactData data,
+) async {
+ final output = await rust.updateContact(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ contactId: contactId,
+ data: rust.ContactData(contactUserId: data.contactUserId, name: data.name),
+ );
+ return _output(_fromRustRecord(output.record), output.wrappedRootContactKey);
+}
+
+Future<void> deleteContact(Session session, String contactId) =>
+ rust.deleteContact(session: session, contactId: contactId);
+
+Future<ContactOutput<ContactRecord>> setAttachment(
+ Session session,
+ WrappedRootContactKey? key,
+ String contactId,
+ ContactAttachmentType attachmentType,
+ Uint8List bytes,
+) async {
+ final output = await rust.setAttachment(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ contactId: contactId,
+ attachmentType: _toRustAttachmentType(attachmentType),
+ attachmentBytes: bytes,
+ );
+ return _output(_fromRustRecord(output.record), output.wrappedRootContactKey);
+}
+
+Future<ContactOutput<ContactRecord>> deleteAttachment(
+ Session session,
+ WrappedRootContactKey? key,
+ String contactId,
+ ContactAttachmentType attachmentType,
+) async {
+ final output = await rust.deleteAttachment(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ contactId: contactId,
+ attachmentType: _toRustAttachmentType(attachmentType),
+ );
+ return _output(_fromRustRecord(output.record), output.wrappedRootContactKey);
+}
+
+Future<ContactOutput<Uint8List>> getProfilePicture(
+ Session session,
+ WrappedRootContactKey? key,
+ String contactId,
+) async {
+ final output = await rust.getProfilePicture(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ contactId: contactId,
+ );
+ return _output(output.bytes, output.wrappedRootContactKey);
+}
+
+ContactOutput<T> _output<T>(T value, rust.WrappedRootContactKey? key) =>
+ ContactOutput(value: value, wrappedRootContactKey: _fromRustKey(key));
+
+rust.WrappedRootContactKey? _toRustKey(WrappedRootContactKey? key) =>
+ key == null
+ ? null
+ : rust.WrappedRootContactKey(
+ encryptedKey: key.encryptedKey,
+ header: key.header,
+ );
+
+WrappedRootContactKey? _fromRustKey(rust.WrappedRootContactKey? key) =>
+ key == null
+ ? null
+ : WrappedRootContactKey(encryptedKey: key.encryptedKey, header: key.header);
+
+rust.AttachmentType _toRustAttachmentType(
+ ContactAttachmentType attachmentType,
+) => switch (attachmentType) {
+ ContactAttachmentType.profilePicture => rust.AttachmentType.profilePicture,
+};
+
+ContactRecord _fromRustRecord(rust.ContactRecord record) {
+ final data = record.isDeleted
+ ? null
+ : ContactData(contactUserId: record.contactUserId, name: record.name!);
+ return ContactRecord(
+ id: record.id,
+ contactUserId: record.contactUserId,
+ email: record.email,
+ data: data,
+ profilePictureAttachmentId: record.profilePictureAttachmentId,
+ isDeleted: record.isDeleted,
+ createdAt: record.createdAt,
+ updatedAt: record.updatedAt,
+ );
+}
diff --git a/mobile/apps/locker/lib/services/contacts_display_service.dart b/mobile/apps/locker/lib/services/contacts_display_service.dart
index 5368c08712..64ac50478f 100644
--- a/mobile/apps/locker/lib/services/contacts_display_service.dart
+++ b/mobile/apps/locker/lib/services/contacts_display_service.dart
@@ -1,8 +1,9 @@
import 'dart:async';
import 'package:ente_contacts/contacts.dart' as contacts;
+import 'package:locker/services/authenticated_session.dart';
import 'package:locker/services/configuration.dart';
-import 'package:locker/services/frb_contacts_rust_api.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';
@@ -17,8 +18,25 @@ class LockerContactsDisplayService {
required PackageInfo packageInfo,
}) async {
contacts.ContactsDisplayService.instance.init(
- preferences: preferences,
- rustApi: const FrbContactsRustApi(),
+ contactsServiceFactory: (account) {
+ final session = authenticatedSession(account);
+ 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),
+ updateContact: (key, contactId, data) =>
+ updateContact(session, key, contactId, data),
+ deleteContact: (contactId) => deleteContact(session, contactId),
+ setAttachment: (key, contactId, type, bytes) =>
+ setAttachment(session, key, contactId, type, bytes),
+ deleteAttachment: (key, contactId, type) =>
+ deleteAttachment(session, key, contactId, type),
+ getProfilePicture: (key, contactId) =>
+ getProfilePicture(session, key, contactId),
+ );
+ },
);
_packageInfo = packageInfo;
scheduleEnsureReady();
diff --git a/mobile/apps/locker/lib/services/frb_contacts_rust_api.dart b/mobile/apps/locker/lib/services/frb_contacts_rust_api.dart
deleted file mode 100644
index 474ca8ed66..0000000000
--- a/mobile/apps/locker/lib/services/frb_contacts_rust_api.dart
+++ /dev/null
@@ -1,170 +0,0 @@
-import 'dart:typed_data';
-
-import 'package:ente_contacts/contacts.dart';
-import 'package:locker/src/rust/api/contacts.dart' as rust;
-
-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,
- cachedWrappedRootContactKey: input.cachedWrappedRootContactKey == null
- ? null
- : rust.WrappedRootContactKey(
- encryptedKey: input.cachedWrappedRootContactKey!.encryptedKey,
- header: input.cachedWrappedRootContactKey!.header,
- ),
- userAgent: input.userAgent,
- clientPackage: input.clientPackage,
- clientVersion: input.clientVersion,
- ),
- );
-
- return OpenContactsContextResult(
- ctx: _FrbContactsRustContext(result.ctx),
- wrappedRootContactKey: result.wrappedRootContactKey == null
- ? null
- : WrappedRootContactKey(
- encryptedKey: result.wrappedRootContactKey!.encryptedKey,
- header: result.wrappedRootContactKey!.header,
- ),
- rootKeySource: switch (result.rootKeySource) {
- rust.RootKeySource.cache => RootKeySource.cache,
- rust.RootKeySource.unresolved => RootKeySource.unresolved,
- },
- );
- }
-}
-
-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? currentWrappedRootContactKey() {
- final current = _inner.currentWrappedRootContactKey();
- if (current == null) {
- return null;
- }
- 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,
- name: data.name,
- ),
- ),
- );
- }
-
- @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,
- name: data.name,
- ),
- ),
- );
- }
-
- @override
- Future<void> deleteContact(String contactId) {
- return _inner.deleteContact(contactId: contactId);
- }
-
- @override
- Future<ContactRecord> setAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- Uint8List attachmentBytes,
- ) async {
- return _fromRustRecord(
- await _inner.setAttachment(
- contactId: contactId,
- attachmentType: _toRustAttachmentType(attachmentType),
- attachmentBytes: attachmentBytes,
- ),
- );
- }
-
- @override
- Future<ContactRecord> deleteAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- ) async {
- return _fromRustRecord(
- await _inner.deleteAttachment(
- contactId: contactId,
- attachmentType: _toRustAttachmentType(attachmentType),
- ),
- );
- }
-
- @override
- Future<Uint8List> getProfilePicture(String contactId) {
- return _inner.getProfilePicture(contactId: contactId);
- }
-}
-
-rust.AttachmentType _toRustAttachmentType(
- ContactAttachmentType attachmentType,
-) {
- return switch (attachmentType) {
- ContactAttachmentType.profilePicture => rust.AttachmentType.profilePicture,
- };
-}
-
-ContactRecord _fromRustRecord(rust.ContactRecord record) {
- final data = record.isDeleted
- ? null
- : ContactData(contactUserId: record.contactUserId, name: record.name!);
- return ContactRecord(
- id: record.id,
- contactUserId: record.contactUserId,
- email: record.email,
- data: data,
- profilePictureAttachmentId: record.profilePictureAttachmentId,
- isDeleted: record.isDeleted,
- createdAt: record.createdAt,
- updatedAt: record.updatedAt,
- );
-}
diff --git a/mobile/apps/locker/lib/services/frb_legacy_kit_rust_api.dart b/mobile/apps/locker/lib/services/frb_legacy_kit_rust_api.dart
deleted file mode 100644
index 1ff3e4b62e..0000000000
--- a/mobile/apps/locker/lib/services/frb_legacy_kit_rust_api.dart
+++ /dev/null
@@ -1,197 +0,0 @@
-import "dart:typed_data";
-
-import "package:ente_base/models/key_attributes.dart";
-import "package:ente_contacts/contacts.dart" as contacts;
-import "package:ente_legacy/models/legacy_kit_models.dart";
-import "package:ente_legacy/services/legacy_kit_rust_api.dart";
-import "package:locker/src/rust/api/legacy.dart" as rust;
-import "package:locker/src/rust/api/session.dart" as rust_session;
-
-class FrbLegacyKitRustApi implements LegacyKitRustApi {
- const FrbLegacyKitRustApi();
-
- @override
- Future<LegacyKitRustContext> open(
- contacts.ContactsSession session,
- Uint8List accountKey,
- ) async {
- final opened = rust_session.openSession(
- baseUrl: session.baseUrl,
- authToken: session.authToken,
- masterKey: accountKey,
- userAgent: session.userAgent,
- clientPackage: session.clientPackage,
- clientVersion: session.clientVersion,
- );
- return _FrbLegacyKitRustContext(opened);
- }
-}
-
-class _FrbLegacyKitRustContext implements LegacyKitRustContext {
- final rust_session.Session _session;
-
- const _FrbLegacyKitRustContext(this._session);
-
- @override
- Future<void> updateAuthToken(String authToken) {
- return _session.updateAuthToken(authToken: authToken);
- }
-
- @override
- Future<List<LegacyKit>> legacyKits() async {
- final kits = await _run(() => rust.kits(session: _session));
- return kits.map(_fromRustKit).toList(growable: false);
- }
-
- @override
- Future<LegacyKitCreateResult> legacyKitCreate({
- required KeyAttributes currentUserKeyAttrs,
- required List<String> partNames,
- required int noticePeriodInHours,
- }) async {
- final result = await _run(
- () => rust.createKit(
- session: _session,
- currentUserKeyAttrs: _toRustKeyAttributes(currentUserKeyAttrs),
- partNames: partNames,
- noticePeriodInHours: noticePeriodInHours,
- ),
- );
- return LegacyKitCreateResult(
- kit: _fromRustKit(result.kit),
- shares: result.shares.map(_fromRustShare).toList(growable: false),
- );
- }
-
- @override
- Future<List<LegacyKitShare>> legacyKitDownloadShares(String kitId) async {
- final shares = await _run(
- () => rust.downloadKitShares(session: _session, kitId: kitId),
- );
- return shares.map(_fromRustShare).toList(growable: false);
- }
-
- @override
- Future<LegacyKitOwnerRecoverySessionDetails> legacyKitRecoverySession(
- String kitId,
- ) async {
- final details = await _run(
- () => rust.kitRecoverySession(session: _session, kitId: kitId),
- );
- return LegacyKitOwnerRecoverySessionDetails(
- session: details.session == null
- ? null
- : _fromRustRecoverySession(details.session!),
- initiators: details.initiators
- .map(
- (hint) => LegacyKitRecoveryInitiatorHint(
- usedPartIndexes: hint.usedPartIndexes,
- ip: hint.ip,
- userAgent: hint.userAgent,
- ),
- )
- .toList(growable: false),
- );
- }
-
- @override
- Future<void> legacyKitUpdateRecoveryNotice({
- required String kitId,
- required int noticePeriodInHours,
- }) {
- return _run(
- () => rust.updateKitRecoveryNotice(
- session: _session,
- kitId: kitId,
- noticePeriodInHours: noticePeriodInHours,
- ),
- );
- }
-
- @override
- Future<void> legacyKitBlockRecovery(String kitId) {
- return _run(() => rust.blockKitRecovery(session: _session, kitId: kitId));
- }
-
- @override
- Future<void> legacyKitDelete(String kitId) {
- return _run(() => rust.deleteKit(session: _session, kitId: kitId));
- }
-}
-
-Future<T> _run<T>(Future<T> Function() action) async {
- try {
- return await action();
- } on rust.LegacyError_ActiveRecoverySession {
- throw LegacyKitActiveRecoverySessionException();
- }
-}
-
-rust.AccountKeyAttributes _toRustKeyAttributes(KeyAttributes attributes) {
- return rust.AccountKeyAttributes(
- kekSalt: attributes.kekSalt,
- encryptedKey: attributes.encryptedKey,
- keyDecryptionNonce: attributes.keyDecryptionNonce,
- publicKey: attributes.publicKey,
- encryptedSecretKey: attributes.encryptedSecretKey,
- secretKeyDecryptionNonce: attributes.secretKeyDecryptionNonce,
- memLimit: attributes.memLimit,
- opsLimit: attributes.opsLimit,
- masterKeyEncryptedWithRecoveryKey:
- attributes.masterKeyEncryptedWithRecoveryKey,
- masterKeyDecryptionNonce: attributes.masterKeyDecryptionNonce,
- recoveryKeyEncryptedWithMasterKey:
- attributes.recoveryKeyEncryptedWithMasterKey,
- recoveryKeyDecryptionNonce: attributes.recoveryKeyDecryptionNonce,
- );
-}
-
-LegacyKit _fromRustKit(rust.LegacyKit kit) {
- return LegacyKit(
- id: kit.id,
- noticePeriodInHours: kit.noticePeriodInHours,
- legacyUrl: kit.legacyUrl,
- parts: kit.metadata.parts
- .map((part) => LegacyKitPart(index: part.index, name: part.name))
- .toList(growable: false),
- createdAt: kit.createdAt,
- updatedAt: kit.updatedAt,
- activeRecoverySession: kit.activeRecoverySession == null
- ? null
- : _fromRustRecoverySession(kit.activeRecoverySession!),
- );
-}
-
-LegacyKitRecoverySession _fromRustRecoverySession(
- rust.LegacyKitRecoverySession session,
-) {
- return LegacyKitRecoverySession(
- id: session.id,
- kitId: session.kitId,
- status: switch (session.status) {
- rust.LegacyKitRecoveryStatus.waiting => LegacyKitRecoveryStatus.waiting,
- rust.LegacyKitRecoveryStatus.ready => LegacyKitRecoveryStatus.ready,
- rust.LegacyKitRecoveryStatus.blocked => LegacyKitRecoveryStatus.blocked,
- rust.LegacyKitRecoveryStatus.cancelled =>
- LegacyKitRecoveryStatus.cancelled,
- rust.LegacyKitRecoveryStatus.recovered =>
- LegacyKitRecoveryStatus.recovered,
- },
- waitTill: session.waitTill,
- createdAt: session.createdAt,
- );
-}
-
-LegacyKitShare _fromRustShare(rust.LegacyKitShare share) {
- return LegacyKitShare(
- payloadVersion: share.payloadVersion,
- variant: switch (share.variant) {
- rust.LegacyKitVariant.twoOfThree => 1,
- },
- kitId: share.kitId,
- shareIndex: share.shareIndex,
- share: share.share,
- checksum: share.checksum,
- partName: share.partName,
- );
-}
diff --git a/mobile/apps/locker/lib/services/legacy_kit.dart b/mobile/apps/locker/lib/services/legacy_kit.dart
new file mode 100644
index 0000000000..db5423708a
--- /dev/null
+++ b/mobile/apps/locker/lib/services/legacy_kit.dart
@@ -0,0 +1,129 @@
+import 'package:ente_base/models/key_attributes.dart';
+import 'package:ente_legacy/errors.dart';
+import 'package:ente_legacy/models/legacy_kit_models.dart';
+import 'package:locker/src/rust/api/legacy.dart' as rust;
+import 'package:locker/src/rust/third_party/ente_frb_core.dart';
+
+Future<List<LegacyKit>> getLegacyKits(Session session) async {
+ final kits = await rust.kits(session: session);
+ return kits.map(_fromRustKit).toList(growable: false);
+}
+
+Future<LegacyKitCreateResult> createLegacyKit(
+ Session session,
+ KeyAttributes currentUserKeyAttrs,
+ List<String> partNames,
+ int noticePeriodInHours,
+) async {
+ final result = await rust.createKit(
+ session: session,
+ currentUserKeyAttrs: _toRustKeyAttributes(currentUserKeyAttrs),
+ partNames: partNames,
+ noticePeriodInHours: noticePeriodInHours,
+ );
+ return LegacyKitCreateResult(
+ kit: _fromRustKit(result.kit),
+ shares: result.shares.map(_fromRustShare).toList(growable: false),
+ );
+}
+
+Future<List<LegacyKitShare>> downloadLegacyKitShares(
+ Session session,
+ String kitId,
+) async {
+ final shares = await rust.downloadKitShares(session: session, kitId: kitId);
+ return shares.map(_fromRustShare).toList(growable: false);
+}
+
+Future<void> updateLegacyKitRecoveryNotice(
+ Session session,
+ String kitId,
+ int noticePeriodInHours,
+) async {
+ try {
+ await rust.updateKitRecoveryNotice(
+ session: session,
+ kitId: kitId,
+ noticePeriodInHours: noticePeriodInHours,
+ );
+ } on rust.LegacyError_ActiveRecoverySession {
+ throw LegacyKitActiveRecoverySessionException();
+ }
+}
+
+Future<void> blockLegacyKitRecovery(Session session, String kitId) async {
+ await rust.blockKitRecovery(session: session, kitId: kitId);
+}
+
+Future<void> deleteLegacyKit(Session session, String kitId) async {
+ await rust.deleteKit(session: session, kitId: kitId);
+}
+
+rust.AccountKeyAttributes _toRustKeyAttributes(KeyAttributes attributes) {
+ return rust.AccountKeyAttributes(
+ kekSalt: attributes.kekSalt,
+ encryptedKey: attributes.encryptedKey,
+ keyDecryptionNonce: attributes.keyDecryptionNonce,
+ publicKey: attributes.publicKey,
+ encryptedSecretKey: attributes.encryptedSecretKey,
+ secretKeyDecryptionNonce: attributes.secretKeyDecryptionNonce,
+ memLimit: attributes.memLimit,
+ opsLimit: attributes.opsLimit,
+ masterKeyEncryptedWithRecoveryKey:
+ attributes.masterKeyEncryptedWithRecoveryKey,
+ masterKeyDecryptionNonce: attributes.masterKeyDecryptionNonce,
+ recoveryKeyEncryptedWithMasterKey:
+ attributes.recoveryKeyEncryptedWithMasterKey,
+ recoveryKeyDecryptionNonce: attributes.recoveryKeyDecryptionNonce,
+ );
+}
+
+LegacyKit _fromRustKit(rust.LegacyKit kit) {
+ return LegacyKit(
+ id: kit.id,
+ noticePeriodInHours: kit.noticePeriodInHours,
+ legacyUrl: kit.legacyUrl,
+ parts: kit.metadata.parts
+ .map((part) => LegacyKitPart(index: part.index, name: part.name))
+ .toList(growable: false),
+ createdAt: kit.createdAt,
+ updatedAt: kit.updatedAt,
+ activeRecoverySession: kit.activeRecoverySession == null
+ ? null
+ : _fromRustRecoverySession(kit.activeRecoverySession!),
+ );
+}
+
+LegacyKitRecoverySession _fromRustRecoverySession(
+ rust.LegacyKitRecoverySession session,
+) {
+ return LegacyKitRecoverySession(
+ id: session.id,
+ kitId: session.kitId,
+ status: switch (session.status) {
+ rust.LegacyKitRecoveryStatus.waiting => LegacyKitRecoveryStatus.waiting,
+ rust.LegacyKitRecoveryStatus.ready => LegacyKitRecoveryStatus.ready,
+ rust.LegacyKitRecoveryStatus.blocked => LegacyKitRecoveryStatus.blocked,
+ rust.LegacyKitRecoveryStatus.cancelled =>
+ LegacyKitRecoveryStatus.cancelled,
+ rust.LegacyKitRecoveryStatus.recovered =>
+ LegacyKitRecoveryStatus.recovered,
+ },
+ waitTill: session.waitTill,
+ createdAt: session.createdAt,
+ );
+}
+
+LegacyKitShare _fromRustShare(rust.LegacyKitShare share) {
+ return LegacyKitShare(
+ payloadVersion: share.payloadVersion,
+ variant: switch (share.variant) {
+ rust.LegacyKitVariant.twoOfThree => 1,
+ },
+ kitId: share.kitId,
+ shareIndex: share.shareIndex,
+ share: share.share,
+ checksum: share.checksum,
+ partName: share.partName,
+ );
+}
diff --git a/mobile/apps/locker/lib/ui/utils/legacy_utils.dart b/mobile/apps/locker/lib/ui/utils/legacy_utils.dart
index 75edcc197e..71a254d4ab 100644
--- a/mobile/apps/locker/lib/ui/utils/legacy_utils.dart
+++ b/mobile/apps/locker/lib/ui/utils/legacy_utils.dart
@@ -1,11 +1,16 @@
+import "package:ente_events/event_bus.dart";
+import "package:ente_legacy/events/legacy_kit_created_event.dart";
+import "package:ente_legacy/models/legacy_kit_models.dart";
import "package:ente_legacy/pages/create_legacy_kit_sheet.dart";
import "package:ente_legacy/pages/emergency_page.dart";
import "package:ente_legacy/pages/legacy_kit_intro_page.dart";
-import "package:ente_legacy/services/legacy_kit_service.dart";
import "package:ente_lock_screen/local_authentication_service.dart";
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";
final _logger = Logger("LegacyUtils");
@@ -57,6 +62,12 @@ Future<void> _openLegacy(
context,
accountEmail: config.getEmail() ?? "",
isFirstLegacyKit: true,
+ createKit: _createLegacyKit,
+ getKits: _getLegacyKits,
+ downloadShares: _downloadLegacyKitShares,
+ updateRecoveryNotice: _updateLegacyKitRecoveryNotice,
+ blockRecovery: _blockLegacyKitRecovery,
+ deleteKit: _deleteLegacyKit,
authenticator: legacyKitAuthenticator,
);
return;
@@ -70,6 +81,12 @@ Future<void> _openLegacy(
builder: (BuildContext context) {
return EmergencyPage(
config: config,
+ getLegacyKits: _getLegacyKits,
+ createLegacyKit: _createLegacyKit,
+ downloadLegacyKitShares: _downloadLegacyKitShares,
+ updateLegacyKitRecoveryNotice: _updateLegacyKitRecoveryNotice,
+ blockLegacyKitRecovery: _blockLegacyKitRecovery,
+ deleteLegacyKit: _deleteLegacyKit,
legacyKitAuthenticator: legacyKitAuthenticator,
);
},
@@ -78,17 +95,62 @@ Future<void> _openLegacy(
}
Future<bool?> hasLegacyKit() async {
- if (!LegacyKitService.instance.isInitialized) {
- return null;
- }
try {
- return (await LegacyKitService.instance.getKits()).isNotEmpty;
+ return (await _getLegacyKits()).isNotEmpty;
} catch (e, s) {
_logger.warning("Failed to fetch legacy kits", e, s);
return null;
}
}
+Future<List<LegacyKit>> _getLegacyKits() => legacy.getLegacyKits(
+ authenticatedSession(LockerContactsDisplayService.buildSession()),
+);
+
+Future<LegacyKitCreateResult> _createLegacyKit(
+ List<String> partNames,
+ int noticePeriodInHours,
+) async {
+ final keyAttributes = Configuration.instance.getKeyAttributes();
+ if (keyAttributes == null) {
+ throw StateError("Missing account key attributes");
+ }
+ final result = await legacy.createLegacyKit(
+ authenticatedSession(LockerContactsDisplayService.buildSession()),
+ keyAttributes,
+ partNames,
+ noticePeriodInHours,
+ );
+ Bus.instance.fire(LegacyKitCreatedEvent());
+ return result;
+}
+
+Future<List<LegacyKitShare>> _downloadLegacyKitShares(String kitId) =>
+ legacy.downloadLegacyKitShares(
+ authenticatedSession(LockerContactsDisplayService.buildSession()),
+ kitId,
+ );
+
+Future<void> _updateLegacyKitRecoveryNotice(
+ String kitId,
+ int noticePeriodInHours,
+) => legacy.updateLegacyKitRecoveryNotice(
+ authenticatedSession(LockerContactsDisplayService.buildSession()),
+ kitId,
+ noticePeriodInHours,
+);
+
+Future<void> _blockLegacyKitRecovery(String kitId) =>
+ legacy.blockLegacyKitRecovery(
+ authenticatedSession(LockerContactsDisplayService.buildSession()),
+ kitId,
+ );
+
+Future<void> _deleteLegacyKit(String kitId) => legacy.deleteLegacyKit(
+ authenticatedSession(LockerContactsDisplayService.buildSession()),
+ kitId,
+);
+
Future<bool> _authenticateForLegacyFlow(BuildContext context, String reason) {
return LocalAuthenticationService.instance.requestLocalAuthentication(
context,
diff --git a/mobile/apps/photos/flutter_rust_bridge.yaml b/mobile/apps/photos/flutter_rust_bridge.yaml
index 616e1bcac4..952d6e0d5f 100644
--- a/mobile/apps/photos/flutter_rust_bridge.yaml
+++ b/mobile/apps/photos/flutter_rust_bridge.yaml
@@ -1,4 +1,4 @@
-rust_input: crate::api
+rust_input: crate::api, ente-frb-contacts, ente-frb-core
rust_root: ../../../rust/bindings/frb/photos/
dart_output: lib/src/rust
dart_entrypoint_class_name: EntePhotosRust
diff --git a/mobile/apps/photos/lib/services/authenticated_session.dart b/mobile/apps/photos/lib/services/authenticated_session.dart
new file mode 100644
index 0000000000..698fb062c7
--- /dev/null
+++ b/mobile/apps/photos/lib/services/authenticated_session.dart
@@ -0,0 +1,26 @@
+import 'package:ente_contacts/contacts.dart';
+import 'package:photos/src/rust/third_party/ente_frb_core.dart';
+
+Session? _session;
+String? _sessionKey;
+
+Session authenticatedSession(ContactsSession account) {
+ final key = '${account.baseUrl}|${account.userId}';
+ final current = _session;
+ if (current != null && _sessionKey == key) {
+ current.updateAuthToken(authToken: account.authToken);
+ return current;
+ }
+
+ final opened = openSession(
+ baseUrl: account.baseUrl,
+ authToken: account.authToken,
+ masterKey: account.accountKey,
+ userAgent: account.userAgent,
+ clientPackage: account.clientPackage,
+ clientVersion: account.clientVersion,
+ );
+ _session = opened;
+ _sessionKey = key;
+ return opened;
+}
diff --git a/mobile/apps/photos/lib/services/contacts.dart b/mobile/apps/photos/lib/services/contacts.dart
new file mode 100644
index 0000000000..f23e212394
--- /dev/null
+++ b/mobile/apps/photos/lib/services/contacts.dart
@@ -0,0 +1,137 @@
+import 'dart:typed_data';
+
+import 'package:ente_contacts/contacts.dart';
+import 'package:photos/src/rust/third_party/ente_frb_contacts.dart' as rust;
+import 'package:photos/src/rust/third_party/ente_frb_core.dart';
+
+Future<ContactOutput<ContactRecord>> createContact(
+ Session session,
+ WrappedRootContactKey? key,
+ ContactData data,
+) async {
+ final output = await rust.createContact(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ data: rust.ContactData(contactUserId: data.contactUserId, name: data.name),
+ );
+ return _output(_fromRustRecord(output.record), output.wrappedRootContactKey);
+}
+
+Future<ContactOutput<List<ContactRecord>>> getDiff(
+ Session session,
+ WrappedRootContactKey? key,
+ int sinceTime,
+ int limit,
+) async {
+ final output = await rust.getDiff(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ sinceTime: sinceTime,
+ limit: limit,
+ );
+ return _output(
+ output.records.map(_fromRustRecord).toList(growable: false),
+ output.wrappedRootContactKey,
+ );
+}
+
+Future<ContactOutput<ContactRecord>> updateContact(
+ Session session,
+ WrappedRootContactKey? key,
+ String contactId,
+ ContactData data,
+) async {
+ final output = await rust.updateContact(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ contactId: contactId,
+ data: rust.ContactData(contactUserId: data.contactUserId, name: data.name),
+ );
+ return _output(_fromRustRecord(output.record), output.wrappedRootContactKey);
+}
+
+Future<void> deleteContact(Session session, String contactId) =>
+ rust.deleteContact(session: session, contactId: contactId);
+
+Future<ContactOutput<ContactRecord>> setAttachment(
+ Session session,
+ WrappedRootContactKey? key,
+ String contactId,
+ ContactAttachmentType attachmentType,
+ Uint8List bytes,
+) async {
+ final output = await rust.setAttachment(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ contactId: contactId,
+ attachmentType: _toRustAttachmentType(attachmentType),
+ attachmentBytes: bytes,
+ );
+ return _output(_fromRustRecord(output.record), output.wrappedRootContactKey);
+}
+
+Future<ContactOutput<ContactRecord>> deleteAttachment(
+ Session session,
+ WrappedRootContactKey? key,
+ String contactId,
+ ContactAttachmentType attachmentType,
+) async {
+ final output = await rust.deleteAttachment(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ contactId: contactId,
+ attachmentType: _toRustAttachmentType(attachmentType),
+ );
+ return _output(_fromRustRecord(output.record), output.wrappedRootContactKey);
+}
+
+Future<ContactOutput<Uint8List>> getProfilePicture(
+ Session session,
+ WrappedRootContactKey? key,
+ String contactId,
+) async {
+ final output = await rust.getProfilePicture(
+ session: session,
+ wrappedRootContactKey: _toRustKey(key),
+ contactId: contactId,
+ );
+ return _output(output.bytes, output.wrappedRootContactKey);
+}
+
+ContactOutput<T> _output<T>(T value, rust.WrappedRootContactKey? key) =>
+ ContactOutput(value: value, wrappedRootContactKey: _fromRustKey(key));
+
+rust.WrappedRootContactKey? _toRustKey(WrappedRootContactKey? key) =>
+ key == null
+ ? null
+ : rust.WrappedRootContactKey(
+ encryptedKey: key.encryptedKey,
+ header: key.header,
+ );
+
+WrappedRootContactKey? _fromRustKey(rust.WrappedRootContactKey? key) =>
+ key == null
+ ? null
+ : WrappedRootContactKey(encryptedKey: key.encryptedKey, header: key.header);
+
+rust.AttachmentType _toRustAttachmentType(
+ ContactAttachmentType attachmentType,
+) => switch (attachmentType) {
+ ContactAttachmentType.profilePicture => rust.AttachmentType.profilePicture,
+};
+
+ContactRecord _fromRustRecord(rust.ContactRecord record) {
+ final data = record.isDeleted
+ ? null
+ : ContactData(contactUserId: record.contactUserId, name: record.name!);
+ return ContactRecord(
+ id: record.id,
+ contactUserId: record.contactUserId,
+ email: record.email,
+ data: data,
+ profilePictureAttachmentId: record.profilePictureAttachmentId,
+ isDeleted: record.isDeleted,
+ createdAt: record.createdAt,
+ updatedAt: record.updatedAt,
+ );
+}
diff --git a/mobile/apps/photos/lib/services/frb_contacts_rust_api.dart b/mobile/apps/photos/lib/services/frb_contacts_rust_api.dart
deleted file mode 100644
index b1d0affde7..0000000000
--- a/mobile/apps/photos/lib/services/frb_contacts_rust_api.dart
+++ /dev/null
@@ -1,170 +0,0 @@
-import 'dart:typed_data';
-
-import 'package:ente_contacts/contacts.dart';
-import 'package:photos/src/rust/api/contacts.dart' as rust;
-
-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,
- cachedWrappedRootContactKey: input.cachedWrappedRootContactKey == null
- ? null
- : rust.WrappedRootContactKey(
- encryptedKey: input.cachedWrappedRootContactKey!.encryptedKey,
- header: input.cachedWrappedRootContactKey!.header,
- ),
- userAgent: input.userAgent,
- clientPackage: input.clientPackage,
- clientVersion: input.clientVersion,
- ),
- );
-
- return OpenContactsContextResult(
- ctx: _FrbContactsRustContext(result.ctx),
- wrappedRootContactKey: result.wrappedRootContactKey == null
- ? null
- : WrappedRootContactKey(
- encryptedKey: result.wrappedRootContactKey!.encryptedKey,
- header: result.wrappedRootContactKey!.header,
- ),
- rootKeySource: switch (result.rootKeySource) {
- rust.RootKeySource.cache => RootKeySource.cache,
- rust.RootKeySource.unresolved => RootKeySource.unresolved,
- },
- );
- }
-}
-
-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? currentWrappedRootContactKey() {
- final current = _inner.currentWrappedRootContactKey();
- if (current == null) {
- return null;
- }
- 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,
- name: data.name,
- ),
- ),
- );
- }
-
- @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,
- name: data.name,
- ),
- ),
- );
- }
-
- @override
- Future<void> deleteContact(String contactId) {
- return _inner.deleteContact(contactId: contactId);
- }
-
- @override
- Future<ContactRecord> setAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- Uint8List attachmentBytes,
- ) async {
- return _fromRustRecord(
- await _inner.setAttachment(
- contactId: contactId,
- attachmentType: _toRustAttachmentType(attachmentType),
- attachmentBytes: attachmentBytes,
- ),
- );
- }
-
- @override
- Future<ContactRecord> deleteAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- ) async {
- return _fromRustRecord(
- await _inner.deleteAttachment(
- contactId: contactId,
- attachmentType: _toRustAttachmentType(attachmentType),
- ),
- );
- }
-
- @override
- Future<Uint8List> getProfilePicture(String contactId) {
- return _inner.getProfilePicture(contactId: contactId);
- }
-}
-
-rust.AttachmentType _toRustAttachmentType(
- ContactAttachmentType attachmentType,
-) {
- return switch (attachmentType) {
- ContactAttachmentType.profilePicture => rust.AttachmentType.profilePicture,
- };
-}
-
-ContactRecord _fromRustRecord(rust.ContactRecord record) {
- final data = record.isDeleted
- ? null
- : ContactData(contactUserId: record.contactUserId, name: record.name!);
- return ContactRecord(
- id: record.id,
- contactUserId: record.contactUserId,
- email: record.email,
- data: data,
- profilePictureAttachmentId: record.profilePictureAttachmentId,
- isDeleted: record.isDeleted,
- createdAt: record.createdAt,
- updatedAt: record.updatedAt,
- );
-}
diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dart
index fe5bf59225..313ee52d8b 100644
--- a/mobile/apps/photos/lib/services/photos_contacts_service.dart
+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart
@@ -6,16 +6,33 @@ import "package:photos/core/event_bus.dart";
import "package:photos/events/contacts_changed_event.dart";
import "package:photos/events/user_logged_out_event.dart";
import "package:photos/service_locator.dart";
-import "package:photos/services/frb_contacts_rust_api.dart";
+import "package:photos/services/authenticated_session.dart";
+import "package:photos/services/contacts.dart";
// Photos-specific session and event adapter for the shared contact directory.
class PhotosContactsService {
PhotosContactsService._privateConstructor()
: _store = contacts.ContactDirectory(
- contactsServiceFactory: () => contacts.ContactsService(
- preferences: ServiceLocator.instance.prefs,
- rustApi: const FrbContactsRustApi(),
- ),
+ contactsServiceFactory: (account) {
+ final session = authenticatedSession(account);
+ 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),
+ updateContact: (key, contactId, data) =>
+ updateContact(session, key, contactId, data),
+ deleteContact: (contactId) => deleteContact(session, contactId),
+ setAttachment: (key, contactId, type, bytes) =>
+ setAttachment(session, key, contactId, type, bytes),
+ deleteAttachment: (key, contactId, type) =>
+ deleteAttachment(session, key, contactId, type),
+ getProfilePicture: (key, contactId) =>
+ getProfilePicture(session, key, contactId),
+ );
+ },
onContactsChanged: _notifyContactsChanged,
profilePictureFailureTtl: Duration.zero,
) {
@@ -25,7 +42,7 @@ class PhotosContactsService {
@visibleForTesting
PhotosContactsService.forTesting({
contacts.ContactsService? contactsService,
- contacts.ContactsService Function()? contactsServiceFactory,
+ contacts.ContactsServiceFactory? contactsServiceFactory,
}) : _store = contacts.ContactDirectory(
contactsService: contactsService,
contactsServiceFactory: contactsServiceFactory,
diff --git a/mobile/packages/contacts/lib/contacts.dart b/mobile/packages/contacts/lib/contacts.dart
index 5c70e8e384..fa63b05e58 100644
--- a/mobile/packages/contacts/lib/contacts.dart
+++ b/mobile/packages/contacts/lib/contacts.dart
@@ -2,9 +2,9 @@ library;
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/rust/contacts_rust_api.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/contact_output.dart b/mobile/packages/contacts/lib/src/models/contact_output.dart
new file mode 100644
index 0000000000..ad1efa02a0
--- /dev/null
+++ b/mobile/packages/contacts/lib/src/models/contact_output.dart
@@ -0,0 +1,19 @@
+class WrappedRootContactKey {
+ final String encryptedKey;
+ final String header;
+
+ const WrappedRootContactKey({
+ required this.encryptedKey,
+ required this.header,
+ });
+}
+
+class ContactOutput<T> {
+ final T value;
+ final WrappedRootContactKey? wrappedRootContactKey;
+
+ const ContactOutput({
+ required this.value,
+ required this.wrappedRootContactKey,
+ });
+}
diff --git a/mobile/packages/contacts/lib/src/models/contacts_session.dart b/mobile/packages/contacts/lib/src/models/contacts_session.dart
index 374f8f447c..87558e813f 100644
--- a/mobile/packages/contacts/lib/src/models/contacts_session.dart
+++ b/mobile/packages/contacts/lib/src/models/contacts_session.dart
@@ -1,17 +1,10 @@
import 'dart:typed_data';
-typedef AccountKeyProvider = Future<Uint8List> Function();
-
-// accountKey is the existing top-level account key. Contacts uses it only to
-// unwrap or create the per-user contact root key.
class ContactsSession {
final String baseUrl;
final String authToken;
final int userId;
-
- final Uint8List? accountKey;
-
- final AccountKeyProvider? accountKeyProvider;
+ final Uint8List accountKey;
final String? userAgent;
final String? clientPackage;
final String? clientVersion;
@@ -20,27 +13,9 @@ class ContactsSession {
required this.baseUrl,
required this.authToken,
required this.userId,
- this.accountKey,
- this.accountKeyProvider,
+ required this.accountKey,
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.dart
deleted file mode 100644
index c5daf4a11f..0000000000
--- a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
+++ /dev/null
@@ -1,87 +0,0 @@
-import 'dart:typed_data';
-
-import 'package:ente_contacts/src/models/contact_data.dart';
-import 'package:ente_contacts/src/models/contact_record.dart';
-
-class WrappedRootContactKey {
- final String encryptedKey;
- final String header;
-
- const WrappedRootContactKey({
- required this.encryptedKey,
- required this.header,
- });
-}
-
-enum ContactAttachmentType { profilePicture }
-
-enum RootKeySource { cache, unresolved }
-
-class OpenContactsContextInput {
- final String baseUrl;
- final String authToken;
- final int userId;
- final Uint8List accountKey;
- final WrappedRootContactKey? cachedWrappedRootContactKey;
- final String? userAgent;
- final String? clientPackage;
- final String? clientVersion;
-
- const OpenContactsContextInput({
- required this.baseUrl,
- required this.authToken,
- required this.userId,
- required this.accountKey,
- this.cachedWrappedRootContactKey,
- this.userAgent,
- this.clientPackage,
- this.clientVersion,
- });
-}
-
-class OpenContactsContextResult {
- final ContactsRustContext ctx;
- final WrappedRootContactKey? wrappedRootContactKey;
- final RootKeySource rootKeySource;
-
- const OpenContactsContextResult({
- required this.ctx,
- required this.wrappedRootContactKey,
- required this.rootKeySource,
- });
-}
-
-abstract class ContactsRustContext {
- int userId();
-
- Future<void> updateAuthToken(String authToken);
-
- WrappedRootContactKey? currentWrappedRootContactKey();
-
- 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> setAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- Uint8List attachmentBytes,
- );
-
- Future<ContactRecord> deleteAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- );
-
- Future<Uint8List> getProfilePicture(String contactId);
-}
-
-abstract class ContactsRustApi {
- Future<OpenContactsContextResult> open(OpenContactsContextInput input);
-}
diff --git a/mobile/packages/contacts/lib/src/service/contact_directory.dart b/mobile/packages/contacts/lib/src/service/contact_directory.dart
index 8d41092609..0ba5ccf819 100644
--- a/mobile/packages/contacts/lib/src/service/contact_directory.dart
+++ b/mobile/packages/contacts/lib/src/service/contact_directory.dart
@@ -7,7 +7,8 @@ import 'package:ente_contacts/src/service/contacts_service.dart';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
-typedef ContactsServiceFactory = ContactsService Function();
+typedef ContactsServiceFactory =
+ ContactsService Function(ContactsSession session);
class ContactDirectory {
ContactDirectory({
@@ -18,7 +19,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;
@@ -54,7 +55,7 @@ class ContactDirectory {
active = _ActiveContacts(
key: key,
authToken: session.authToken,
- service: _newContactsService(),
+ service: _newContactsService(session),
);
_active = active;
}
@@ -160,15 +161,16 @@ class ContactDirectory {
required String name,
}) async {
final active = _requireActive();
- final existing = await active.service.getContactByUserId(
+ final service = active.service;
+ final existing = await service.getContactByUserId(
contactUserId,
includeDeleted: true,
);
_requireActiveSession(active);
final data = ContactData(contactUserId: contactUserId, name: name.trim());
final contact = existing == null
- ? await active.service.createContact(data)
- : await active.service.updateContact(existing.id, data);
+ ? await service.createContact(data)
+ : await service.updateContact(existing.id, data);
_requireActiveSession(active);
_cacheAndNotify(contact);
return contact;
@@ -180,7 +182,8 @@ class ContactDirectory {
required Uint8List bytes,
}) async {
final active = _requireActive();
- final existing = await active.service.getContactByUserId(
+ final service = active.service;
+ final existing = await service.getContactByUserId(
contactUserId,
includeDeleted: true,
);
@@ -190,16 +193,16 @@ class ContactDirectory {
return existing.isDeleted ? null : existing;
}
- final created = await active.service.createContact(
+ final created = await service.createContact(
ContactData(contactUserId: contactUserId, name: name.trim()),
);
if (!_isActive(active)) return null;
late ContactRecord updated;
try {
- updated = await active.service.setProfilePicture(created.id, bytes);
+ updated = await service.setProfilePicture(created.id, bytes);
} catch (_) {
if (!_isActive(active)) rethrow;
- updated = await active.service.setProfilePicture(created.id, bytes);
+ updated = await service.setProfilePicture(created.id, bytes);
}
if (!_isActive(active)) return null;
_cachePicture(updated, bytes);
@@ -259,11 +262,12 @@ class ContactDirectory {
}
Future<void> _hydrate(_ActiveContacts active, ContactsSession session) async {
- await active.service.open(session);
+ final service = active.service;
+ await service.open(session);
if (!_isActive(active)) return;
final knownUserIds = _contactsByUserId.keys.toSet();
- final local = await active.service.getContacts();
+ final local = await service.getContacts();
if (!_isActive(active)) return;
final localChanged = _cacheAll(local);
_hasHydratedCache = true;
@@ -277,7 +281,7 @@ class ContactDirectory {
.toSet();
try {
- final diff = await active.service.sync();
+ final diff = await service.sync();
if (!_isActive(active)) return;
final diffChanged = _cacheAll(diff);
if (diffChanged.isNotEmpty) {
@@ -459,12 +463,12 @@ class ContactDirectory {
bool _isActive(_ActiveContacts active) => identical(active, _active);
- ContactsService _newContactsService() {
+ ContactsService _newContactsService(ContactsSession session) {
final factory = _contactsServiceFactory;
if (factory == null) {
throw StateError('ContactDirectory requires a contacts service factory');
}
- return factory();
+ return factory(session);
}
String _sessionKey(ContactsSession session) =>
diff --git a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
index 251096ae33..791017c255 100644
--- a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
+++ b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
@@ -1,10 +1,8 @@
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:ente_contacts/src/service/contact_directory.dart';
import 'package:ente_contacts/src/service/contacts_service.dart';
import 'package:flutter/foundation.dart';
-import 'package:shared_preferences/shared_preferences.dart';
class ContactsDisplayService {
ContactsDisplayService._privateConstructor() : _store = ContactDirectory();
@@ -27,26 +25,15 @@ class ContactsDisplayService {
}
void init({
- required SharedPreferences preferences,
ContactsService? contactsService,
- ContactsService Function()? contactsServiceFactory,
- ContactsRustApi? rustApi,
+ ContactsServiceFactory? contactsServiceFactory,
}) {
- if (contactsService == null &&
- contactsServiceFactory == null &&
- rustApi == null) {
- throw ArgumentError(
- 'rustApi is required when no contacts service or factory is given',
- );
+ if (contactsService == null && contactsServiceFactory == null) {
+ throw ArgumentError('A contacts service or factory is required');
}
_store = ContactDirectory(
contactsService: contactsService,
- contactsServiceFactory:
- contactsServiceFactory ??
- (contactsService == null
- ? () =>
- ContactsService(preferences: preferences, rustApi: rustApi!)
- : null),
+ contactsServiceFactory: contactsServiceFactory,
);
}
diff --git a/mobile/packages/contacts/lib/src/service/contacts_service.dart b/mobile/packages/contacts/lib/src/service/contacts_service.dart
index 0f0f3d473a..4f9840a790 100644
--- a/mobile/packages/contacts/lib/src/service/contacts_service.dart
+++ b/mobile/packages/contacts/lib/src/service/contacts_service.dart
@@ -3,81 +3,107 @@ 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_output.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';
+enum ContactAttachmentType { profilePicture }
+
+typedef UpdateAuthToken = void Function(String authToken);
+typedef CreateContact =
+ Future<ContactOutput<ContactRecord>> Function(
+ WrappedRootContactKey? wrappedRootContactKey,
+ ContactData data,
+ );
+typedef GetContactDiff =
+ Future<ContactOutput<List<ContactRecord>>> Function(
+ WrappedRootContactKey? wrappedRootContactKey,
+ int sinceTime,
+ int limit,
+ );
+typedef UpdateContact =
+ Future<ContactOutput<ContactRecord>> Function(
+ WrappedRootContactKey? wrappedRootContactKey,
+ String contactId,
+ ContactData data,
+ );
+typedef DeleteContact = Future<void> Function(String contactId);
+typedef SetContactAttachment =
+ Future<ContactOutput<ContactRecord>> Function(
+ WrappedRootContactKey? wrappedRootContactKey,
+ String contactId,
+ ContactAttachmentType attachmentType,
+ Uint8List attachmentBytes,
+ );
+typedef DeleteContactAttachment =
+ Future<ContactOutput<ContactRecord>> Function(
+ WrappedRootContactKey? wrappedRootContactKey,
+ String contactId,
+ ContactAttachmentType attachmentType,
+ );
+typedef GetContactProfilePicture =
+ Future<ContactOutput<Uint8List>> Function(
+ WrappedRootContactKey? wrappedRootContactKey,
+ String contactId,
+ );
+
class ContactsService {
static const _serverMaxSyncLimit = 5000;
static const _syncLimit = _serverMaxSyncLimit;
ContactsService({
required SharedPreferences preferences,
- required ContactsRustApi rustApi,
+ required UpdateAuthToken updateAuthToken,
+ required CreateContact createContact,
+ required GetContactDiff getDiff,
+ required UpdateContact updateContact,
+ required DeleteContact deleteContact,
+ required SetContactAttachment setAttachment,
+ required DeleteContactAttachment deleteAttachment,
+ required GetContactProfilePicture getProfilePicture,
ContactsDatabase? database,
}) : _preferences = preferences,
_database = database ?? ContactsDatabase(),
- _rustApi = rustApi;
+ _updateRemoteAuthToken = updateAuthToken,
+ _createRemoteContact = createContact,
+ _getRemoteDiff = getDiff,
+ _updateRemoteContact = updateContact,
+ _deleteRemoteContact = deleteContact,
+ _setRemoteAttachment = setAttachment,
+ _deleteRemoteAttachment = deleteAttachment,
+ _getRemoteProfilePicture = getProfilePicture;
final SharedPreferences _preferences;
final ContactsDatabase _database;
- final ContactsRustApi _rustApi;
+ final UpdateAuthToken _updateRemoteAuthToken;
+ final CreateContact _createRemoteContact;
+ final GetContactDiff _getRemoteDiff;
+ final UpdateContact _updateRemoteContact;
+ final DeleteContact _deleteRemoteContact;
+ final SetContactAttachment _setRemoteAttachment;
+ final DeleteContactAttachment _deleteRemoteAttachment;
+ final GetContactProfilePicture _getRemoteProfilePicture;
final Logger _logger = Logger('ContactsService');
- ContactsRustContext? _ctx;
+ WrappedRootContactKey? _wrappedRootContactKey;
ContactsSession? _session;
Future<void> open(ContactsSession session) async {
- final accountKey = await session.resolveAccountKey();
- final cachedWrappedRootContactKey = _cachedWrappedRootContactKey(
- session.userId,
- );
- final opened = await _rustApi
- .open(
- OpenContactsContextInput(
- baseUrl: session.baseUrl,
- authToken: session.authToken,
- userId: session.userId,
- accountKey: accountKey,
- cachedWrappedRootContactKey: cachedWrappedRootContactKey,
- userAgent: session.userAgent,
- clientPackage: session.clientPackage,
- clientVersion: session.clientVersion,
- ),
- )
- .catchError((Object error, StackTrace stackTrace) {
- _logger.warning(
- "Failed to open contacts context for account user ${session.userId} "
- "at ${session.baseUrl} (hasCachedRootKey: ${cachedWrappedRootContactKey != null})",
- error,
- stackTrace,
- );
- throw error;
- });
-
- _ctx = opened.ctx;
+ _wrappedRootContactKey = _cachedWrappedRootContactKey(session.userId);
_session = session;
await _database.configure(userId: session.userId);
- if (opened.wrappedRootContactKey != null) {
- await _persistWrappedRootContactKey(
- session.userId,
- opened.wrappedRootContactKey!,
- );
- }
- _logger.info('Opened contacts context for user ${session.userId}');
+ _logger.info('Opened contacts store for user ${session.userId}');
}
Future<void> updateAuthToken(String authToken) async {
- final ctx = _requireCtx();
- await ctx.updateAuthToken(authToken);
+ _updateRemoteAuthToken(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,
@@ -85,7 +111,7 @@ class ContactsService {
}
Future<List<ContactRecord>> sync() async {
- final ctx = _requireCtx();
+ _requireOpen();
var sinceTime = await _database.getLastSyncedUpdatedAt();
var limit = _syncLimit;
final synced = <ContactRecord>[];
@@ -93,7 +119,9 @@ class ContactsService {
var previousSinceTime = -1;
List<String>? previousPageIds;
while (true) {
- final diff = await ctx.getDiff(sinceTime, limit);
+ final diff = await _value(
+ await _getRemoteDiff(_wrappedRootContactKey, sinceTime, limit),
+ );
if (diff.isEmpty) {
break;
}
@@ -125,7 +153,6 @@ class ContactsService {
break;
}
}
- await _persistConfirmedWrappedRootKey();
await _database.deleteUnreferencedCachedAttachments();
return synced;
}
@@ -149,9 +176,10 @@ class ContactsService {
}
Future<ContactRecord> createContact(ContactData data) async {
- final ctx = _requireCtx();
- final created = await ctx.createContact(data);
- await _persistConfirmedWrappedRootKey();
+ _requireOpen();
+ final created = await _value(
+ await _createRemoteContact(_wrappedRootContactKey, data),
+ );
await _database.upsertContacts([created]);
return created;
}
@@ -160,18 +188,20 @@ class ContactsService {
String contactId,
ContactData data,
) async {
- final ctx = _requireCtx();
- final updated = await ctx.updateContact(contactId, data);
- await _persistConfirmedWrappedRootKey();
+ _requireOpen();
+ final updated = await _value(
+ await _updateRemoteContact(_wrappedRootContactKey, contactId, data),
+ );
await _database.upsertContacts([updated]);
return updated;
}
Future<void> deleteContact(String contactId) async {
- final ctx = _requireCtx();
- await ctx.deleteContact(contactId);
- await _persistConfirmedWrappedRootKey();
- final deleted = await ctx.getDiff(0, _syncLimit);
+ _requireOpen();
+ await _deleteRemoteContact(contactId);
+ final deleted = await _value(
+ await _getRemoteDiff(_wrappedRootContactKey, 0, _syncLimit),
+ );
final matching = deleted
.where((element) => element.id == contactId)
.toList();
@@ -206,12 +236,15 @@ class ContactsService {
final previousAttachmentId = (await _database.getContact(
contactId,
))?.profilePictureAttachmentId;
- final updated = await _requireCtx().setAttachment(
- contactId,
- attachmentType,
- bytes,
+ _requireOpen();
+ final updated = await _value(
+ await _setRemoteAttachment(
+ _wrappedRootContactKey,
+ contactId,
+ attachmentType,
+ bytes,
+ ),
);
- await _persistConfirmedWrappedRootKey();
await _database.upsertContacts([updated]);
final nextAttachmentId = updated.profilePictureAttachmentId;
if (nextAttachmentId != null) {
@@ -234,7 +267,10 @@ class ContactsService {
if (cached != null) {
return cached;
}
- final bytes = await _requireCtx().getProfilePicture(contactId);
+ _requireOpen();
+ final bytes = await _value(
+ await _getRemoteProfilePicture(_wrappedRootContactKey, contactId),
+ );
await _database.upsertCachedAttachment(attachmentId, bytes);
return bytes;
}
@@ -246,11 +282,14 @@ class ContactsService {
final previousAttachmentId = (await _database.getContact(
contactId,
))?.profilePictureAttachmentId;
- final updated = await _requireCtx().deleteAttachment(
- contactId,
- attachmentType,
+ _requireOpen();
+ final updated = await _value(
+ await _deleteRemoteAttachment(
+ _wrappedRootContactKey,
+ contactId,
+ attachmentType,
+ ),
);
- await _persistConfirmedWrappedRootKey();
await _database.upsertContacts([updated]);
if (previousAttachmentId != null) {
await _database.deleteCachedAttachment(previousAttachmentId);
@@ -283,12 +322,10 @@ class ContactsService {
return true;
}
- ContactsRustContext _requireCtx() {
- final ctx = _ctx;
- if (ctx == null) {
+ void _requireOpen() {
+ if (_session == null) {
throw StateError('ContactsService.open(...) must be called before use');
}
- return ctx;
}
WrappedRootContactKey? _cachedWrappedRootContactKey(int userId) {
@@ -308,20 +345,14 @@ class ContactsService {
await _preferences.setString(_entityHeaderPref(userId), key.header);
}
- Future<void> _persistConfirmedWrappedRootKey() async {
+ Future<T> _value<T>(ContactOutput<T> output) async {
final session = _session;
- final ctx = _ctx;
- if (session == null || ctx == null) {
- return;
+ final key = output.wrappedRootContactKey;
+ if (session != null && key != null) {
+ _wrappedRootContactKey = key;
+ await _persistWrappedRootContactKey(session.userId, key);
}
- final currentWrappedRootContactKey = ctx.currentWrappedRootContactKey();
- if (currentWrappedRootContactKey == null) {
- return;
- }
- await _persistWrappedRootContactKey(
- session.userId,
- currentWrappedRootContactKey,
- );
+ return output.value;
}
String _entityKeyPref(int userId) => 'entity_key_contact_$userId';
diff --git a/mobile/packages/legacy/lib/ente_legacy.dart b/mobile/packages/legacy/lib/ente_legacy.dart
index cc4878f40c..6ee8a2b93f 100644
--- a/mobile/packages/legacy/lib/ente_legacy.dart
+++ b/mobile/packages/legacy/lib/ente_legacy.dart
@@ -1,4 +1,5 @@
export 'components/legacy_kit_recovery_wait_time_sheet.dart';
+export 'errors.dart';
export 'models/emergency_models.dart';
export 'models/legacy_kit_models.dart';
export 'pages/create_legacy_kit_sheet.dart';
@@ -8,4 +9,3 @@ export 'pages/other_contact_page.dart';
export 'pages/recover_others_account.dart';
export 'pages/share_legacy_kit_page.dart';
export 'services/emergency_service.dart';
-export 'services/legacy_kit_service.dart';
diff --git a/mobile/packages/legacy/lib/errors.dart b/mobile/packages/legacy/lib/errors.dart
new file mode 100644
index 0000000000..c6b7a11309
--- /dev/null
+++ b/mobile/packages/legacy/lib/errors.dart
@@ -0,0 +1 @@
+class LegacyKitActiveRecoverySessionException implements Exception {}
diff --git a/mobile/packages/legacy/lib/models/legacy_kit_models.dart b/mobile/packages/legacy/lib/models/legacy_kit_models.dart
index 85e23f36fa..09c041eb84 100644
--- a/mobile/packages/legacy/lib/models/legacy_kit_models.dart
+++ b/mobile/packages/legacy/lib/models/legacy_kit_models.dart
@@ -20,28 +20,6 @@ class LegacyKitRecoverySession {
});
}
-class LegacyKitRecoveryInitiatorHint {
- final List<int> usedPartIndexes;
- final String ip;
- final String userAgent;
-
- const LegacyKitRecoveryInitiatorHint({
- required this.usedPartIndexes,
- required this.ip,
- required this.userAgent,
- });
-}
-
-class LegacyKitOwnerRecoverySessionDetails {
- final LegacyKitRecoverySession? session;
- final List<LegacyKitRecoveryInitiatorHint> initiators;
-
- const LegacyKitOwnerRecoverySessionDetails({
- required this.session,
- required this.initiators,
- });
-}
-
class LegacyKitPart {
final int index;
final String name;
diff --git a/mobile/packages/legacy/lib/pages/create_legacy_kit_sheet.dart b/mobile/packages/legacy/lib/pages/create_legacy_kit_sheet.dart
index 179f76300a..1dcca5cfae 100644
--- a/mobile/packages/legacy/lib/pages/create_legacy_kit_sheet.dart
+++ b/mobile/packages/legacy/lib/pages/create_legacy_kit_sheet.dart
@@ -5,7 +5,6 @@ import "package:ente_components/ente_components.dart";
import "package:ente_legacy/components/legacy_kit_recovery_wait_time_sheet.dart";
import "package:ente_legacy/models/legacy_kit_models.dart";
import "package:ente_legacy/pages/share_legacy_kit_page.dart";
-import "package:ente_legacy/services/legacy_kit_service.dart";
import "package:ente_strings/ente_strings.dart";
import "package:ente_ui/components/buttons/dynamic_fab.dart";
import "package:ente_ui/utils/toast_util.dart";
@@ -15,10 +14,22 @@ import "package:hugeicons/hugeicons.dart";
const _legacyKitPartNameMaxBytes = 50;
+typedef CreateLegacyKit =
+ Future<LegacyKitCreateResult> Function(
+ List<String> partNames,
+ int noticePeriodInHours,
+ );
+
Future<void> showCreateLegacyKitPage(
BuildContext context, {
required String accountEmail,
required bool isFirstLegacyKit,
+ required CreateLegacyKit createKit,
+ required GetLegacyKits getKits,
+ required DownloadLegacyKitShares downloadShares,
+ required UpdateLegacyKitRecoveryNotice updateRecoveryNotice,
+ required BlockLegacyKitRecovery blockRecovery,
+ required DeleteLegacyKit deleteKit,
LegacyKitAuthenticator? authenticator,
ValueChanged<LegacyKit>? onCreated,
VoidCallback? onChanged,
@@ -28,6 +39,12 @@ Future<void> showCreateLegacyKitPage(
builder: (context) => CreateLegacyKitPage(
accountEmail: accountEmail,
isFirstLegacyKit: isFirstLegacyKit,
+ createKit: createKit,
+ getKits: getKits,
+ downloadShares: downloadShares,
+ updateRecoveryNotice: updateRecoveryNotice,
+ blockRecovery: blockRecovery,
+ deleteKit: deleteKit,
authenticator: authenticator,
onCreated: onCreated,
onChanged: onChanged,
@@ -39,6 +56,12 @@ Future<void> showCreateLegacyKitPage(
class CreateLegacyKitPage extends StatefulWidget {
final String accountEmail;
final bool isFirstLegacyKit;
+ final CreateLegacyKit createKit;
+ final GetLegacyKits getKits;
+ final DownloadLegacyKitShares downloadShares;
+ final UpdateLegacyKitRecoveryNotice updateRecoveryNotice;
+ final BlockLegacyKitRecovery blockRecovery;
+ final DeleteLegacyKit deleteKit;
final LegacyKitAuthenticator? authenticator;
final ValueChanged<LegacyKit>? onCreated;
final VoidCallback? onChanged;
@@ -46,6 +69,12 @@ class CreateLegacyKitPage extends StatefulWidget {
const CreateLegacyKitPage({
required this.accountEmail,
required this.isFirstLegacyKit,
+ required this.createKit,
+ required this.getKits,
+ required this.downloadShares,
+ required this.updateRecoveryNotice,
+ required this.blockRecovery,
+ required this.deleteKit,
this.authenticator,
this.onCreated,
this.onChanged,
@@ -203,10 +232,7 @@ class _CreateLegacyKitPageState extends State<CreateLegacyKitPage> {
if (!mounted) {
return;
}
- final result = await LegacyKitService.instance.createKit(
- partNames: _partNames,
- noticePeriodInHours: _selectedDays * 24,
- );
+ final result = await widget.createKit(_partNames, _selectedDays * 24);
widget.onCreated?.call(result.kit);
if (!mounted) {
return;
@@ -218,6 +244,11 @@ class _CreateLegacyKitPageState extends State<CreateLegacyKitPage> {
kit: result.kit,
initialShares: result.shares,
accountEmail: widget.accountEmail,
+ getKits: widget.getKits,
+ downloadShares: widget.downloadShares,
+ updateRecoveryNotice: widget.updateRecoveryNotice,
+ blockRecovery: widget.blockRecovery,
+ deleteKit: widget.deleteKit,
authenticator: widget.authenticator,
onChanged: widget.onChanged,
isCreationFlow: true,
diff --git a/mobile/packages/legacy/lib/pages/emergency_page.dart b/mobile/packages/legacy/lib/pages/emergency_page.dart
index a63fda4c72..0dce6f4a59 100644
--- a/mobile/packages/legacy/lib/pages/emergency_page.dart
+++ b/mobile/packages/legacy/lib/pages/emergency_page.dart
@@ -15,7 +15,6 @@ import "package:ente_legacy/pages/other_contact_page.dart";
import "package:ente_legacy/pages/select_contact_page.dart";
import "package:ente_legacy/pages/share_legacy_kit_page.dart";
import "package:ente_legacy/services/emergency_service.dart";
-import "package:ente_legacy/services/legacy_kit_service.dart";
import "package:ente_sharing/extensions/user_extension.dart";
import "package:ente_sharing/user_avator_widget.dart";
import "package:ente_strings/ente_strings.dart";
@@ -36,10 +35,22 @@ final _logger = Logger("EmergencyPage");
class EmergencyPage extends StatefulWidget {
final BaseConfiguration config;
+ final GetLegacyKits getLegacyKits;
+ final CreateLegacyKit createLegacyKit;
+ final DownloadLegacyKitShares downloadLegacyKitShares;
+ final UpdateLegacyKitRecoveryNotice updateLegacyKitRecoveryNotice;
+ final BlockLegacyKitRecovery blockLegacyKitRecovery;
+ final DeleteLegacyKit deleteLegacyKit;
final LegacyKitAuthenticator? legacyKitAuthenticator;
const EmergencyPage({
required this.config,
+ required this.getLegacyKits,
+ required this.createLegacyKit,
+ required this.downloadLegacyKitShares,
+ required this.updateLegacyKitRecoveryNotice,
+ required this.blockLegacyKitRecovery,
+ required this.deleteLegacyKit,
this.legacyKitAuthenticator,
super.key,
});
@@ -78,11 +89,8 @@ class _EmergencyPageState extends State<EmergencyPage> {
}
Future<List<LegacyKit>> _fetchLegacyKits() async {
- if (!LegacyKitService.instance.isInitialized) {
- return <LegacyKit>[];
- }
try {
- return await LegacyKitService.instance.getKits();
+ return await widget.getLegacyKits();
} catch (error, stackTrace) {
_logger.warning("Failed to fetch legacy kits", error, stackTrace);
return legacyKits;
@@ -132,9 +140,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
hasScrollBody: false,
child: _FullLegacyEmptyState(
onAddContact: _addTrustedContact,
- onCreateLegacyKit: LegacyKitService.instance.isInitialized
- ? _createLegacyKit
- : null,
+ onCreateLegacyKit: _createLegacyKit,
),
),
if (info == null)
@@ -205,7 +211,6 @@ class _EmergencyPageState extends State<EmergencyPage> {
),
if (info != null &&
!showFullEmptyState &&
- LegacyKitService.instance.isInitialized &&
(legacyKits.isNotEmpty ||
trustedContacts.isNotEmpty ||
othersTrustedContacts.isNotEmpty))
@@ -295,8 +300,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
const SizedBox(height: 16),
],
_buildAddTrustedContactButton(),
- if (LegacyKitService.instance.isInitialized &&
- legacyKits.isEmpty) ...[
+ if (legacyKits.isEmpty) ...[
const SizedBox(height: 12),
GradientButton(
text: context.strings.createLegacyKit,
@@ -476,6 +480,11 @@ class _EmergencyPageState extends State<EmergencyPage> {
return ShareLegacyKitPage(
kit: legacyKits[index],
accountEmail: widget.config.getEmail() ?? "",
+ getKits: widget.getLegacyKits,
+ downloadShares: widget.downloadLegacyKitShares,
+ updateRecoveryNotice: widget.updateLegacyKitRecoveryNotice,
+ blockRecovery: widget.blockLegacyKitRecovery,
+ deleteKit: widget.deleteLegacyKit,
authenticator: widget.legacyKitAuthenticator,
onChanged: _refreshLegacyData,
);
@@ -550,6 +559,12 @@ class _EmergencyPageState extends State<EmergencyPage> {
context,
accountEmail: widget.config.getEmail() ?? "",
isFirstLegacyKit: isFirstLegacyKit,
+ createKit: widget.createLegacyKit,
+ getKits: widget.getLegacyKits,
+ downloadShares: widget.downloadLegacyKitShares,
+ updateRecoveryNotice: widget.updateLegacyKitRecoveryNotice,
+ blockRecovery: widget.blockLegacyKitRecovery,
+ deleteKit: widget.deleteLegacyKit,
authenticator: widget.legacyKitAuthenticator,
onCreated: _onLegacyKitCreated,
onChanged: _refreshLegacyData,
diff --git a/mobile/packages/legacy/lib/pages/share_legacy_kit_page.dart b/mobile/packages/legacy/lib/pages/share_legacy_kit_page.dart
index cfeb3910d3..e5a856b0df 100644
--- a/mobile/packages/legacy/lib/pages/share_legacy_kit_page.dart
+++ b/mobile/packages/legacy/lib/pages/share_legacy_kit_page.dart
@@ -6,12 +6,11 @@ import "package:collection/collection.dart";
import "package:ente_components/ente_components.dart";
import "package:ente_legacy/components/legacy_kit_card_preview.dart";
import "package:ente_legacy/components/legacy_kit_recovery_wait_time_sheet.dart";
+import "package:ente_legacy/errors.dart";
import "package:ente_legacy/models/legacy_kit_models.dart";
import "package:ente_legacy/pages/legacy_congratulations_page.dart";
import "package:ente_legacy/services/legacy_kit_local_settings.dart";
import "package:ente_legacy/services/legacy_kit_pdf_service.dart";
-import "package:ente_legacy/services/legacy_kit_rust_api.dart";
-import "package:ente_legacy/services/legacy_kit_service.dart";
import "package:ente_legacy/services/legacy_kit_share_file_service.dart";
import "package:ente_strings/ente_strings.dart";
import "package:ente_ui/components/alert_bottom_sheet.dart";
@@ -26,6 +25,13 @@ import "package:share_plus/share_plus.dart";
typedef LegacyKitAuthenticator =
Future<bool> Function(BuildContext context, String reason);
+typedef GetLegacyKits = Future<List<LegacyKit>> Function();
+typedef DownloadLegacyKitShares =
+ Future<List<LegacyKitShare>> Function(String kitId);
+typedef UpdateLegacyKitRecoveryNotice =
+ Future<void> Function(String kitId, int noticePeriodInHours);
+typedef BlockLegacyKitRecovery = Future<void> Function(String kitId);
+typedef DeleteLegacyKit = Future<void> Function(String kitId);
final _legacyKitShareTokens = <String, Object>{};
@@ -41,6 +47,11 @@ enum _KitMenuAction { revoke }
class ShareLegacyKitPage extends StatefulWidget {
final LegacyKit kit;
+ final GetLegacyKits getKits;
+ final DownloadLegacyKitShares downloadShares;
+ final UpdateLegacyKitRecoveryNotice updateRecoveryNotice;
+ final BlockLegacyKitRecovery blockRecovery;
+ final DeleteLegacyKit deleteKit;
final List<LegacyKitShare>? initialShares;
final String accountEmail;
final LegacyKitAuthenticator? authenticator;
@@ -51,6 +62,11 @@ class ShareLegacyKitPage extends StatefulWidget {
const ShareLegacyKitPage({
required this.kit,
required this.accountEmail,
+ required this.getKits,
+ required this.downloadShares,
+ required this.updateRecoveryNotice,
+ required this.blockRecovery,
+ required this.deleteKit,
this.initialShares,
this.authenticator,
this.onChanged,
@@ -316,7 +332,7 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
final dialog = createProgressDialog(context, context.strings.pleaseWait);
await dialog.show();
try {
- final shares = await LegacyKitService.instance.downloadShares(_kit.id);
+ final shares = await widget.downloadShares(_kit.id);
await dialog.hide();
if (mounted) {
setState(() {
@@ -455,10 +471,7 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
await dialog.show();
Object? updateError;
try {
- await LegacyKitService.instance.updateRecoveryNotice(
- kitId: _kit.id,
- noticePeriodInHours: selectedDays * 24,
- );
+ await widget.updateRecoveryNotice(_kit.id, selectedDays * 24);
if (mounted) {
setState(() {
_kit = LegacyKit(
@@ -518,7 +531,7 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
return false;
}
try {
- await LegacyKitService.instance.deleteKit(_kit.id);
+ await widget.deleteKit(_kit.id);
return true;
} catch (_) {
if (mounted) {
@@ -587,7 +600,7 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
return false;
}
try {
- await LegacyKitService.instance.blockRecovery(_kit.id);
+ await widget.blockRecovery(_kit.id);
return true;
} catch (_) {
if (mounted) {
@@ -658,7 +671,7 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
}
Future<void> _refreshKit() async {
- final refreshed = await LegacyKitService.instance.getKits();
+ final refreshed = await widget.getKits();
final current = refreshed.where((kit) => kit.id == _kit.id).firstOrNull;
if (current != null && mounted) {
setState(() {
diff --git a/mobile/packages/legacy/lib/services/legacy_kit_rust_api.dart b/mobile/packages/legacy/lib/services/legacy_kit_rust_api.dart
deleted file mode 100644
index 85e396211e..0000000000
--- a/mobile/packages/legacy/lib/services/legacy_kit_rust_api.dart
+++ /dev/null
@@ -1,41 +0,0 @@
-import "dart:typed_data";
-
-import "package:ente_base/models/key_attributes.dart";
-import "package:ente_contacts/contacts.dart" as contacts;
-import "package:ente_legacy/models/legacy_kit_models.dart";
-
-class LegacyKitActiveRecoverySessionException implements Exception {}
-
-abstract class LegacyKitRustContext {
- Future<void> updateAuthToken(String authToken);
-
- Future<List<LegacyKit>> legacyKits();
-
- Future<LegacyKitCreateResult> legacyKitCreate({
- required KeyAttributes currentUserKeyAttrs,
- required List<String> partNames,
- required int noticePeriodInHours,
- });
-
- Future<List<LegacyKitShare>> legacyKitDownloadShares(String kitId);
-
- Future<LegacyKitOwnerRecoverySessionDetails> legacyKitRecoverySession(
- String kitId,
- );
-
- Future<void> legacyKitUpdateRecoveryNotice({
- required String kitId,
- required int noticePeriodInHours,
- });
-
- Future<void> legacyKitBlockRecovery(String kitId);
-
- Future<void> legacyKitDelete(String kitId);
-}
-
-abstract class LegacyKitRustApi {
- Future<LegacyKitRustContext> open(
- contacts.ContactsSession session,
- Uint8List accountKey,
- );
-}
diff --git a/mobile/packages/legacy/lib/services/legacy_kit_service.dart b/mobile/packages/legacy/lib/services/legacy_kit_service.dart
deleted file mode 100644
index 9d5c13d897..0000000000
--- a/mobile/packages/legacy/lib/services/legacy_kit_service.dart
+++ /dev/null
@@ -1,145 +0,0 @@
-import "dart:async";
-
-import "package:ente_configuration/base_configuration.dart";
-import "package:ente_contacts/contacts.dart" as contacts;
-import "package:ente_events/event_bus.dart";
-import "package:ente_legacy/events/legacy_kit_created_event.dart";
-import "package:ente_legacy/models/legacy_kit_models.dart";
-import "package:ente_legacy/services/legacy_kit_rust_api.dart";
-import "package:ente_legacy/services/legacy_kit_share_file_service.dart";
-import "package:logging/logging.dart";
-
-typedef LegacyKitSessionProvider = contacts.ContactsSession? Function();
-
-class LegacyKitService {
- LegacyKitService._privateConstructor();
-
- static final LegacyKitService instance =
- LegacyKitService._privateConstructor();
-
- final Logger _logger = Logger("LegacyKitService");
-
- BaseConfiguration? _config;
- LegacyKitSessionProvider? _sessionProvider;
- LegacyKitRustApi? _rustApi;
- LegacyKitRustContext? _ctx;
- String? _ctxBaseUrl;
- int? _ctxUserId;
- String? _ctxAuthToken;
-
- bool get isInitialized =>
- _config != null && _sessionProvider != null && _rustApi != null;
-
- Future<void> init({
- required BaseConfiguration config,
- required LegacyKitSessionProvider sessionProvider,
- required LegacyKitRustApi rustApi,
- }) async {
- _config = config;
- _sessionProvider = sessionProvider;
- _rustApi = rustApi;
- unawaited(cleanStaleLegacyKitShareFiles());
- }
-
- Future<List<LegacyKit>> getKits() async {
- final ctx = await _requireCtx();
- return ctx.legacyKits();
- }
-
- Future<LegacyKitCreateResult> createKit({
- required List<String> partNames,
- required int noticePeriodInHours,
- }) async {
- if (partNames.length != 3) {
- throw ArgumentError.value(
- partNames,
- "partNames",
- "Legacy kit requires exactly three part names",
- );
- }
- final keyAttributes = _requireConfig().getKeyAttributes();
- if (keyAttributes == null) {
- throw StateError("Missing account key attributes");
- }
- final ctx = await _requireCtx();
- final createdKit = await ctx.legacyKitCreate(
- currentUserKeyAttrs: keyAttributes,
- partNames: partNames,
- noticePeriodInHours: noticePeriodInHours,
- );
- Bus.instance.fire(LegacyKitCreatedEvent());
- return createdKit;
- }
-
- Future<List<LegacyKitShare>> downloadShares(String kitId) async {
- final ctx = await _requireCtx();
- return ctx.legacyKitDownloadShares(kitId);
- }
-
- Future<LegacyKitOwnerRecoverySessionDetails> getRecoverySession(
- String kitId,
- ) async {
- final ctx = await _requireCtx();
- return ctx.legacyKitRecoverySession(kitId);
- }
-
- Future<void> updateRecoveryNotice({
- required String kitId,
- required int noticePeriodInHours,
- }) async {
- final ctx = await _requireCtx();
- await ctx.legacyKitUpdateRecoveryNotice(
- kitId: kitId,
- noticePeriodInHours: noticePeriodInHours,
- );
- }
-
- Future<void> blockRecovery(String kitId) async {
- final ctx = await _requireCtx();
- await ctx.legacyKitBlockRecovery(kitId);
- }
-
- Future<void> deleteKit(String kitId) async {
- final ctx = await _requireCtx();
- await ctx.legacyKitDelete(kitId);
- }
-
- BaseConfiguration _requireConfig() {
- final config = _config;
- if (config == null) {
- throw StateError("LegacyKitService has not been initialized");
- }
- return config;
- }
-
- Future<LegacyKitRustContext> _requireCtx() async {
- final provider = _sessionProvider;
- final rustApi = _rustApi;
- if (provider == null || rustApi == null) {
- throw StateError("LegacyKitService has not been initialized");
- }
- final session = provider();
- if (session == null) {
- throw StateError("Legacy kit session is not available");
- }
- final existing = _ctx;
- if (existing != null &&
- _ctxBaseUrl == session.baseUrl &&
- _ctxUserId == session.userId) {
- if (_ctxAuthToken != session.authToken) {
- await existing.updateAuthToken(session.authToken);
- _ctxAuthToken = session.authToken;
- }
- return existing;
- }
-
- final accountKey = await session.resolveAccountKey();
- _logger.info("Opening legacy kit Rust context for user ${session.userId}");
- final opened = await rustApi.open(session, accountKey);
- _ctx = opened;
- _ctxBaseUrl = session.baseUrl;
- _ctxUserId = session.userId;
- _ctxAuthToken = session.authToken;
- return opened;
- }
-}
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 1f9ef338ec..a3c10ecab2 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2567,6 +2567,24 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "ente-frb-contacts"
+version = "0.0.0"
+dependencies = [
+ "ente-contacts",
+ "ente-core",
+ "ente-frb-core",
+ "flutter_rust_bridge",
+]
+
+[[package]]
+name = "ente-frb-core"
+version = "0.0.0"
+dependencies = [
+ "ente-core",
+ "flutter_rust_bridge",
+]
+
[[package]]
name = "ente-frb-log"
version = "0.0.0"
@@ -2632,8 +2650,9 @@ version = "0.0.0"
dependencies = [
"ente-accounts",
"ente-assets",
- "ente-contacts",
"ente-core",
+ "ente-frb-contacts",
+ "ente-frb-core",
"ente-frb-log",
"ente-legacy",
"ente-ml",
@@ -2644,16 +2663,9 @@ dependencies = [
name = "ente-locker-wasm"
version = "0.0.0"
dependencies = [
- "ente-contacts",
- "ente-core",
+ "ente-wasm-contacts",
"ente-wasm-core",
"ente-wasm-log",
- "js-sys",
- "serde",
- "serde-wasm-bindgen",
- "thiserror 2.0.18",
- "wasm-bindgen",
- "wasm-bindgen-futures",
]
[[package]]
@@ -2726,8 +2738,8 @@ name = "ente-photos-frb"
version = "0.0.0"
dependencies = [
"ente-cast",
- "ente-contacts",
- "ente-core",
+ "ente-frb-contacts",
+ "ente-frb-core",
"ente-frb-log",
"ente-image",
"ente-location",
@@ -2753,16 +2765,9 @@ dependencies = [
name = "ente-photos-wasm"
version = "0.0.0"
dependencies = [
- "ente-contacts",
- "ente-core",
+ "ente-wasm-contacts",
"ente-wasm-core",
"ente-wasm-log",
- "js-sys",
- "serde",
- "serde-wasm-bindgen",
- "thiserror 2.0.18",
- "wasm-bindgen",
- "wasm-bindgen-futures",
]
[[package]]
@@ -2852,6 +2857,21 @@ dependencies = [
"log",
]
+[[package]]
+name = "ente-wasm-contacts"
+version = "0.0.0"
+dependencies = [
+ "ente-contacts",
+ "ente-core",
+ "ente-wasm-core",
+ "js-sys",
+ "serde",
+ "serde-wasm-bindgen",
+ "thiserror 2.0.18",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+]
+
[[package]]
name = "ente-wasm-core"
version = "0.0.0"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index ceaa6648c5..450626a65d 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -4,6 +4,8 @@ members = [
"apps/cli",
"apps/codegen",
"apps/ensu/src-tauri",
+ "bindings/frb/contacts",
+ "bindings/frb/core",
"bindings/frb/locker",
"bindings/frb/log",
"bindings/frb/photos",
@@ -12,6 +14,7 @@ members = [
"bindings/uniffi/ensu",
"bindings/uniffi/log",
"bindings/wasm/cast",
+ "bindings/wasm/contacts",
"bindings/wasm/core",
"bindings/wasm/core-wasm",
"bindings/wasm/ensu",
@@ -46,6 +49,8 @@ ente-contacts = { path = "crates/contacts" }
ente-core = { path = "crates/core" }
ente-ensu = { path = "crates/ensu" }
ente-ensu-crypto = { path = "crates/ensu-crypto" }
+ente-frb-contacts = { path = "bindings/frb/contacts" }
+ente-frb-core = { path = "bindings/frb/core" }
ente-frb-log = { path = "bindings/frb/log" }
ente-image = { path = "crates/image" }
ente-legacy = { path = "crates/legacy" }
@@ -57,6 +62,7 @@ ente-space = { path = "crates/space" }
ente-test-support = { path = "crates/test-support" }
ente-uniffi-log = { path = "bindings/uniffi/log" }
ente-wasm-core = { path = "bindings/wasm/core" }
+ente-wasm-contacts = { path = "bindings/wasm/contacts" }
ente-wasm-log = { path = "bindings/wasm/log" }
flutter_rust_bridge = "=2.12.0"
flutter_rust_bridge_codegen = "=2.12.0"
diff --git a/rust/bindings/frb/contacts/Cargo.toml b/rust/bindings/frb/contacts/Cargo.toml
new file mode 100644
index 0000000000..482b3acf54
--- /dev/null
+++ b/rust/bindings/frb/contacts/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "ente-frb-contacts"
+edition = "2024"
+
+[dependencies]
+ente-contacts.workspace = true
+ente-core.workspace = true
+ente-frb-core.workspace = true
+flutter_rust_bridge.workspace = true
+
+[lints.rust]
+unexpected_cfgs = { level = "warn", check-cfg = ['cfg(frb_expand)'] }
diff --git a/rust/bindings/frb/contacts/src/lib.rs b/rust/bindings/frb/contacts/src/lib.rs
new file mode 100644
index 0000000000..7080ff94f8
--- /dev/null
+++ b/rust/bindings/frb/contacts/src/lib.rs
@@ -0,0 +1,222 @@
+use flutter_rust_bridge::frb;
+
+use ente_frb_core::Session;
+
+#[frb(non_opaque)]
+pub enum ContactsError {
+ Other { message: String },
+}
+
+impl From<ente_contacts::Error> for ContactsError {
+ fn from(error: ente_contacts::Error) -> Self {
+ Self::Other {
+ message: ente_core::error::chain(&error),
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct WrappedRootContactKey {
+ pub encrypted_key: String,
+ pub header: String,
+}
+
+impl From<ente_contacts::WrappedRootContactKey> for WrappedRootContactKey {
+ fn from(value: ente_contacts::WrappedRootContactKey) -> Self {
+ Self {
+ encrypted_key: value.encrypted_key,
+ header: value.header,
+ }
+ }
+}
+
+impl From<WrappedRootContactKey> for ente_contacts::WrappedRootContactKey {
+ fn from(value: WrappedRootContactKey) -> Self {
+ Self {
+ encrypted_key: value.encrypted_key,
+ header: value.header,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct ContactData {
+ pub contact_user_id: i64,
+ pub name: String,
+}
+
+impl From<ContactData> for ente_contacts::ContactData {
+ fn from(value: ContactData) -> Self {
+ Self {
+ contact_user_id: value.contact_user_id,
+ name: value.name,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct ContactRecord {
+ pub id: String,
+ pub contact_user_id: i64,
+ pub email: Option<String>,
+ pub name: Option<String>,
+ pub profile_picture_attachment_id: Option<String>,
+ pub is_deleted: bool,
+ pub created_at: i64,
+ pub updated_at: i64,
+}
+
+impl From<ente_contacts::ContactRecord> for ContactRecord {
+ fn from(value: ente_contacts::ContactRecord) -> Self {
+ Self {
+ id: value.id,
+ contact_user_id: value.contact_user_id,
+ email: value.email,
+ name: value.name,
+ profile_picture_attachment_id: value.profile_picture_attachment_id,
+ is_deleted: value.is_deleted,
+ created_at: value.created_at,
+ updated_at: value.updated_at,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone, Copy)]
+pub enum AttachmentType {
+ ProfilePicture,
+}
+
+impl From<AttachmentType> for ente_contacts::AttachmentType {
+ fn from(value: AttachmentType) -> Self {
+ match value {
+ AttachmentType::ProfilePicture => ente_contacts::AttachmentType::ProfilePicture,
+ }
+ }
+}
+
+#[frb]
+pub struct ContactRecordOutput {
+ pub record: ContactRecord,
+ pub wrapped_root_contact_key: Option<WrappedRootContactKey>,
+}
+
+#[frb]
+pub struct ContactDiffOutput {
+ pub records: Vec<ContactRecord>,
+ pub wrapped_root_contact_key: Option<WrappedRootContactKey>,
+}
+
+#[frb]
+pub struct ProfilePictureOutput {
+ pub bytes: Vec<u8>,
+ pub wrapped_root_contact_key: Option<WrappedRootContactKey>,
+}
+
+pub async fn create_contact(
+ session: &Session,
+ wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ data: ContactData,
+) -> Result<ContactRecordOutput, ContactsError> {
+ let key = wrapped_root_contact_key.map(Into::into);
+ let output = ente_contacts::create_contact(session.as_ref(), key.as_ref(), &data.into()).await?;
+ Ok(ContactRecordOutput {
+ record: output.value.into(),
+ wrapped_root_contact_key: output.wrapped_root_contact_key.map(Into::into),
+ })
+}
+
+pub async fn get_diff(
+ session: &Session,
+ wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ since_time: i64,
+ limit: u16,
+) -> Result<ContactDiffOutput, ContactsError> {
+ let key = wrapped_root_contact_key.map(Into::into);
+ let output = ente_contacts::get_diff(session.as_ref(), key.as_ref(), since_time, limit).await?;
+ Ok(ContactDiffOutput {
+ records: output.value.into_iter().map(Into::into).collect(),
+ wrapped_root_contact_key: output.wrapped_root_contact_key.map(Into::into),
+ })
+}
+
+pub async fn update_contact(
+ session: &Session,
+ wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ contact_id: String,
+ data: ContactData,
+) -> Result<ContactRecordOutput, ContactsError> {
+ let key = wrapped_root_contact_key.map(Into::into);
+ let output =
+ ente_contacts::update_contact(session.as_ref(), key.as_ref(), &contact_id, &data.into())
+ .await?;
+ Ok(ContactRecordOutput {
+ record: output.value.into(),
+ wrapped_root_contact_key: output.wrapped_root_contact_key.map(Into::into),
+ })
+}
+
+pub async fn delete_contact(session: &Session, contact_id: String) -> Result<(), ContactsError> {
+ ente_contacts::delete_contact(session.as_ref(), &contact_id)
+ .await
+ .map_err(Into::into)
+}
+
+pub async fn set_attachment(
+ session: &Session,
+ wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ contact_id: String,
+ attachment_type: AttachmentType,
+ attachment_bytes: Vec<u8>,
+) -> Result<ContactRecordOutput, ContactsError> {
+ let key = wrapped_root_contact_key.map(Into::into);
+ let output = ente_contacts::set_attachment(
+ session.as_ref(),
+ key.as_ref(),
+ &contact_id,
+ attachment_type.into(),
+ &attachment_bytes,
+ )
+ .await?;
+ Ok(ContactRecordOutput {
+ record: output.value.into(),
+ wrapped_root_contact_key: output.wrapped_root_contact_key.map(Into::into),
+ })
+}
+
+pub async fn delete_attachment(
+ session: &Session,
+ wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ contact_id: String,
+ attachment_type: AttachmentType,
+) -> Result<ContactRecordOutput, ContactsError> {
+ let key = wrapped_root_contact_key.map(Into::into);
+ let output = ente_contacts::delete_attachment(
+ session.as_ref(),
+ key.as_ref(),
+ &contact_id,
+ attachment_type.into(),
+ )
+ .await?;
+ Ok(ContactRecordOutput {
+ record: output.value.into(),
+ wrapped_root_contact_key: output.wrapped_root_contact_key.map(Into::into),
+ })
+}
+
+pub async fn get_profile_picture(
+ session: &Session,
+ wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ contact_id: String,
+) -> Result<ProfilePictureOutput, ContactsError> {
+ let key = wrapped_root_contact_key.map(Into::into);
+ let output =
+ ente_contacts::get_profile_picture(session.as_ref(), key.as_ref(), &contact_id).await?;
+ Ok(ProfilePictureOutput {
+ bytes: output.value,
+ wrapped_root_contact_key: output.wrapped_root_contact_key.map(Into::into),
+ })
+}
diff --git a/rust/bindings/frb/core/Cargo.toml b/rust/bindings/frb/core/Cargo.toml
new file mode 100644
index 0000000000..f5216a1eca
--- /dev/null
+++ b/rust/bindings/frb/core/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "ente-frb-core"
+edition = "2024"
+
+[dependencies]
+ente-core.workspace = true
+flutter_rust_bridge.workspace = true
+
+[lints.rust]
+unexpected_cfgs = { level = "warn", check-cfg = ['cfg(frb_expand)'] }
diff --git a/rust/bindings/frb/locker/src/api/session.rs b/rust/bindings/frb/core/src/lib.rs
similarity index 90%
rename from rust/bindings/frb/locker/src/api/session.rs
rename to rust/bindings/frb/core/src/lib.rs
index b811d5d53a..fc7c282297 100644
--- a/rust/bindings/frb/locker/src/api/session.rs
+++ b/rust/bindings/frb/core/src/lib.rs
@@ -7,7 +7,7 @@ use ente_core::{
};
use flutter_rust_bridge::frb;
-#[frb]
+#[frb(non_opaque)]
pub enum SessionError {
Other { message: String },
}
@@ -46,11 +46,14 @@ pub fn open_session(
}
impl Session {
- pub(crate) fn inner(&self) -> &InnerSession {
- &self.0
- }
-
+ #[frb(sync)]
pub fn update_auth_token(&self, auth_token: String) {
self.0.api.set_auth(Some(Auth::User(auth_token)));
}
}
+
+impl AsRef<InnerSession> for Session {
+ fn as_ref(&self) -> &InnerSession {
+ &self.0
+ }
+}
diff --git a/rust/bindings/frb/locker/Cargo.toml b/rust/bindings/frb/locker/Cargo.toml
index 59e37cc067..0a22ef0ddd 100644
--- a/rust/bindings/frb/locker/Cargo.toml
+++ b/rust/bindings/frb/locker/Cargo.toml
@@ -8,8 +8,9 @@ crate-type = ["cdylib", "staticlib"]
[dependencies]
ente-accounts.workspace = true
ente-assets.workspace = true
-ente-contacts.workspace = true
ente-core.workspace = true
+ente-frb-contacts.workspace = true
+ente-frb-core.workspace = true
ente-frb-log.workspace = true
ente-legacy.workspace = true
ente-ml.workspace = true
diff --git a/rust/bindings/frb/locker/src/api/contacts.rs b/rust/bindings/frb/locker/src/api/contacts.rs
deleted file mode 100644
index 19acf869fd..0000000000
--- a/rust/bindings/frb/locker/src/api/contacts.rs
+++ /dev/null
@@ -1,277 +0,0 @@
-use std::sync::Arc;
-
-use ente_core::{
- Session,
- crypto::SecretVec,
- http::{ApiConfig, Auth},
-};
-use flutter_rust_bridge::frb;
-
-#[frb]
-pub enum ContactsError {
- Other { message: String },
-}
-
-impl From<ente_contacts::Error> for ContactsError {
- fn from(e: ente_contacts::Error) -> Self {
- Self::Other {
- message: ente_core::error::chain(&e),
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct WrappedRootContactKey {
- pub encrypted_key: String,
- pub header: String,
-}
-
-impl From<ente_contacts::WrappedRootContactKey> for WrappedRootContactKey {
- fn from(value: ente_contacts::WrappedRootContactKey) -> Self {
- Self {
- encrypted_key: value.encrypted_key,
- header: value.header,
- }
- }
-}
-
-impl From<WrappedRootContactKey> for ente_contacts::WrappedRootContactKey {
- fn from(value: WrappedRootContactKey) -> Self {
- Self {
- encrypted_key: value.encrypted_key,
- header: value.header,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct ContactData {
- pub contact_user_id: i64,
- pub name: String,
-}
-
-impl From<ContactData> for ente_contacts::ContactData {
- fn from(value: ContactData) -> Self {
- Self {
- contact_user_id: value.contact_user_id,
- name: value.name,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct ContactRecord {
- pub id: String,
- pub contact_user_id: i64,
- pub email: Option<String>,
- pub name: Option<String>,
- pub profile_picture_attachment_id: Option<String>,
- pub is_deleted: bool,
- pub created_at: i64,
- pub updated_at: i64,
-}
-
-impl From<ente_contacts::ContactRecord> for ContactRecord {
- fn from(value: ente_contacts::ContactRecord) -> Self {
- Self {
- id: value.id,
- contact_user_id: value.contact_user_id,
- email: value.email,
- name: value.name,
- profile_picture_attachment_id: value.profile_picture_attachment_id,
- is_deleted: value.is_deleted,
- created_at: value.created_at,
- updated_at: value.updated_at,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub enum RootKeySource {
- Cache,
- Unresolved,
-}
-
-impl From<ente_contacts::RootKeySource> for RootKeySource {
- fn from(value: ente_contacts::RootKeySource) -> Self {
- match value {
- ente_contacts::RootKeySource::Cache => RootKeySource::Cache,
- ente_contacts::RootKeySource::Unresolved => RootKeySource::Unresolved,
- }
- }
-}
-
-#[frb]
-#[derive(Clone, Copy)]
-pub enum AttachmentType {
- ProfilePicture,
-}
-
-impl From<AttachmentType> for ente_contacts::AttachmentType {
- fn from(value: AttachmentType) -> Self {
- match value {
- AttachmentType::ProfilePicture => ente_contacts::AttachmentType::ProfilePicture,
- }
- }
-}
-
-#[frb]
-pub struct OpenContactsCtxInput {
- pub base_url: String,
- pub auth_token: String,
- pub user_id: i64,
- pub master_key: Vec<u8>,
- pub cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,
- pub user_agent: Option<String>,
- pub client_package: Option<String>,
- pub client_version: Option<String>,
-}
-
-#[frb]
-pub struct OpenContactsCtxResult {
- pub ctx: ContactsCtx,
- pub wrapped_root_contact_key: Option<WrappedRootContactKey>,
- pub root_key_source: RootKeySource,
-}
-
-#[frb(opaque)]
-#[derive(Clone)]
-pub struct ContactsCtx {
- session: Arc<Session>,
- contacts: Arc<ente_contacts::ContactsClient>,
-}
-
-#[frb]
-pub async fn open_contacts_ctx(
- input: OpenContactsCtxInput,
-) -> Result<OpenContactsCtxResult, ContactsError> {
- let session = Arc::new(
- Session::new(
- ApiConfig {
- origin: input.base_url,
- client_package: input.client_package,
- client_version: input.client_version,
- user_agent: input.user_agent,
- auth: Some(Auth::User(input.auth_token)),
- },
- SecretVec::new(input.master_key),
- )
- .map_err(ente_contacts::Error::from)?,
- );
- let opened = ente_contacts::ContactsClient::open(
- Arc::clone(&session),
- ente_contacts::OpenContactsInput {
- user_id: input.user_id,
- cached_wrapped_root_contact_key: input.cached_wrapped_root_contact_key.map(Into::into),
- },
- )?;
- Ok(OpenContactsCtxResult {
- ctx: ContactsCtx {
- session,
- contacts: Arc::new(opened.client),
- },
- wrapped_root_contact_key: opened.wrapped_root_contact_key.map(Into::into),
- root_key_source: opened.root_key_source.into(),
- })
-}
-
-impl ContactsCtx {
- #[frb(sync)]
- pub fn user_id(&self) -> i64 {
- self.contacts.user_id()
- }
-
- pub fn update_auth_token(&self, auth_token: String) {
- self.session.api.set_auth(Some(Auth::User(auth_token)));
- }
-
- #[frb(sync)]
- pub fn current_wrapped_root_contact_key(&self) -> Option<WrappedRootContactKey> {
- self.contacts
- .current_wrapped_root_contact_key()
- .map(Into::into)
- }
-
- pub async fn create_contact(&self, data: ContactData) -> Result<ContactRecord, ContactsError> {
- self.contacts
- .create_contact(&data.into())
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn get_contact(&self, contact_id: String) -> Result<ContactRecord, ContactsError> {
- self.contacts
- .get_contact(&contact_id)
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn get_diff(
- &self,
- since_time: i64,
- limit: u16,
- ) -> Result<Vec<ContactRecord>, ContactsError> {
- self.contacts
- .get_diff(since_time, limit)
- .await
- .map(|records| records.into_iter().map(Into::into).collect())
- .map_err(Into::into)
- }
-
- pub async fn update_contact(
- &self,
- contact_id: String,
- data: ContactData,
- ) -> Result<ContactRecord, ContactsError> {
- self.contacts
- .update_contact(&contact_id, &data.into())
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn delete_contact(&self, contact_id: String) -> Result<(), ContactsError> {
- self.contacts
- .delete_contact(&contact_id)
- .await
- .map_err(Into::into)
- }
-
- pub async fn set_attachment(
- &self,
- contact_id: String,
- attachment_type: AttachmentType,
- attachment_bytes: Vec<u8>,
- ) -> Result<ContactRecord, ContactsError> {
- self.contacts
- .set_attachment(&contact_id, attachment_type.into(), &attachment_bytes)
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn delete_attachment(
- &self,
- contact_id: String,
- attachment_type: AttachmentType,
- ) -> Result<ContactRecord, ContactsError> {
- self.contacts
- .delete_attachment(&contact_id, attachment_type.into())
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn get_profile_picture(&self, contact_id: String) -> Result<Vec<u8>, ContactsError> {
- self.contacts
- .get_profile_picture(&contact_id)
- .await
- .map_err(Into::into)
- }
-}
diff --git a/rust/bindings/frb/locker/src/api/legacy.rs b/rust/bindings/frb/locker/src/api/legacy.rs
index 5b8c96ab8b..7909662c7d 100644
--- a/rust/bindings/frb/locker/src/api/legacy.rs
+++ b/rust/bindings/frb/locker/src/api/legacy.rs
@@ -1,7 +1,6 @@
-use ente_legacy::{LegacyKitOwnerRecoverySession, LegacyKitRecoveryInitiator};
use flutter_rust_bridge::frb;
-use super::session::Session;
+use ente_frb_core::Session;
#[frb]
pub enum LegacyError {
@@ -114,40 +113,6 @@ impl From<ente_legacy::LegacyKitRecoverySession> for LegacyKitRecoverySession {
}
}
-#[frb]
-#[derive(Clone)]
-pub struct LegacyKitRecoveryInitiatorHint {
- pub used_part_indexes: Vec<u8>,
- pub ip: String,
- pub user_agent: String,
-}
-
-impl From<LegacyKitRecoveryInitiator> for LegacyKitRecoveryInitiatorHint {
- fn from(value: LegacyKitRecoveryInitiator) -> Self {
- Self {
- used_part_indexes: value.used_part_indexes,
- ip: value.ip,
- user_agent: value.user_agent,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct LegacyKitOwnerRecoverySessionDetails {
- pub session: Option<LegacyKitRecoverySession>,
- pub initiators: Vec<LegacyKitRecoveryInitiatorHint>,
-}
-
-impl From<LegacyKitOwnerRecoverySession> for LegacyKitOwnerRecoverySessionDetails {
- fn from(value: LegacyKitOwnerRecoverySession) -> Self {
- Self {
- session: value.session.map(Into::into),
- initiators: value.initiators.into_iter().map(Into::into).collect(),
- }
- }
-}
-
#[frb]
#[derive(Clone)]
pub struct LegacyKitPart {
@@ -249,7 +214,7 @@ impl From<ente_legacy::LegacyKitCreateResult> for LegacyKitCreateResult {
}
pub async fn kits(session: &Session) -> Result<Vec<LegacyKit>, LegacyError> {
- ente_legacy::kits(session.inner())
+ ente_legacy::kits(session.as_ref())
.await
.map(|kits| kits.into_iter().map(Into::into).collect())
.map_err(Into::into)
@@ -265,7 +230,7 @@ pub async fn create_kit(
message: "legacy kit requires exactly three part names".into(),
})?;
ente_legacy::create_kit(
- session.inner(),
+ session.as_ref(),
&current_user_key_attrs.into(),
part_names,
notice_period_in_hours,
@@ -279,40 +244,30 @@ pub async fn download_kit_shares(
session: &Session,
kit_id: String,
) -> Result<Vec<LegacyKitShare>, LegacyError> {
- ente_legacy::download_kit_shares(session.inner(), &kit_id)
+ ente_legacy::download_kit_shares(session.as_ref(), &kit_id)
.await
.map(|shares| shares.into_iter().map(Into::into).collect())
.map_err(Into::into)
}
-pub async fn kit_recovery_session(
- session: &Session,
- kit_id: String,
-) -> Result<LegacyKitOwnerRecoverySessionDetails, LegacyError> {
- ente_legacy::kit_recovery_session(session.inner(), &kit_id)
- .await
- .map(Into::into)
- .map_err(Into::into)
-}
-
pub async fn update_kit_recovery_notice(
session: &Session,
kit_id: String,
notice_period_in_hours: i32,
) -> Result<(), LegacyError> {
- ente_legacy::update_kit_recovery_notice(session.inner(), &kit_id, notice_period_in_hours)
+ ente_legacy::update_kit_recovery_notice(session.as_ref(), &kit_id, notice_period_in_hours)
.await
.map_err(Into::into)
}
pub async fn block_kit_recovery(session: &Session, kit_id: String) -> Result<(), LegacyError> {
- ente_legacy::block_kit_recovery(session.inner(), &kit_id)
+ ente_legacy::block_kit_recovery(session.as_ref(), &kit_id)
.await
.map_err(Into::into)
}
pub async fn delete_kit(session: &Session, kit_id: String) -> Result<(), LegacyError> {
- ente_legacy::delete_kit(session.inner(), &kit_id)
+ ente_legacy::delete_kit(session.as_ref(), &kit_id)
.await
.map_err(Into::into)
}
diff --git a/rust/bindings/frb/locker/src/api/mod.rs b/rust/bindings/frb/locker/src/api/mod.rs
index 2489114aca..c03f89bfdb 100644
--- a/rust/bindings/frb/locker/src/api/mod.rs
+++ b/rust/bindings/frb/locker/src/api/mod.rs
@@ -1,7 +1,5 @@
-pub mod contacts;
pub mod document_scanner_api;
pub mod init;
pub mod legacy;
#[cfg(any(feature = "flutter", frb_expand))]
pub mod log;
-pub mod session;
diff --git a/rust/bindings/frb/photos/Cargo.toml b/rust/bindings/frb/photos/Cargo.toml
index 4fba03dc39..6373797f01 100644
--- a/rust/bindings/frb/photos/Cargo.toml
+++ b/rust/bindings/frb/photos/Cargo.toml
@@ -7,8 +7,8 @@ crate-type = ["cdylib", "staticlib"]
[dependencies]
ente-cast.workspace = true
-ente-contacts.workspace = true
-ente-core.workspace = true
+ente-frb-contacts.workspace = true
+ente-frb-core.workspace = true
ente-frb-log.workspace = true
ente-image.workspace = true
ente-location.workspace = true
diff --git a/rust/bindings/frb/photos/src/api/contacts.rs b/rust/bindings/frb/photos/src/api/contacts.rs
deleted file mode 100644
index af15c54158..0000000000
--- a/rust/bindings/frb/photos/src/api/contacts.rs
+++ /dev/null
@@ -1,278 +0,0 @@
-use std::sync::Arc;
-
-use ente_core::{
- Session,
- crypto::SecretVec,
- http::{ApiConfig, Auth},
-};
-use flutter_rust_bridge::frb;
-
-#[frb]
-pub enum ContactsError {
- Other { message: String },
-}
-
-impl From<ente_contacts::Error> for ContactsError {
- fn from(e: ente_contacts::Error) -> Self {
- Self::Other {
- message: ente_core::error::chain(&e),
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct WrappedRootContactKey {
- pub encrypted_key: String,
- pub header: String,
-}
-
-impl From<ente_contacts::WrappedRootContactKey> for WrappedRootContactKey {
- fn from(value: ente_contacts::WrappedRootContactKey) -> Self {
- Self {
- encrypted_key: value.encrypted_key,
- header: value.header,
- }
- }
-}
-
-impl From<WrappedRootContactKey> for ente_contacts::WrappedRootContactKey {
- fn from(value: WrappedRootContactKey) -> Self {
- Self {
- encrypted_key: value.encrypted_key,
- header: value.header,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct ContactData {
- pub contact_user_id: i64,
- pub name: String,
-}
-
-impl From<ContactData> for ente_contacts::ContactData {
- fn from(value: ContactData) -> Self {
- Self {
- contact_user_id: value.contact_user_id,
- name: value.name,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct ContactRecord {
- pub id: String,
- pub contact_user_id: i64,
- pub email: Option<String>,
- pub name: Option<String>,
- pub profile_picture_attachment_id: Option<String>,
- pub is_deleted: bool,
- pub created_at: i64,
- pub updated_at: i64,
-}
-
-impl From<ente_contacts::ContactRecord> for ContactRecord {
- fn from(value: ente_contacts::ContactRecord) -> Self {
- Self {
- id: value.id,
- contact_user_id: value.contact_user_id,
- email: value.email,
- name: value.name,
- profile_picture_attachment_id: value.profile_picture_attachment_id,
- is_deleted: value.is_deleted,
- created_at: value.created_at,
- updated_at: value.updated_at,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub enum RootKeySource {
- Cache,
- Unresolved,
-}
-
-impl From<ente_contacts::RootKeySource> for RootKeySource {
- fn from(value: ente_contacts::RootKeySource) -> Self {
- match value {
- ente_contacts::RootKeySource::Cache => RootKeySource::Cache,
- ente_contacts::RootKeySource::Unresolved => RootKeySource::Unresolved,
- }
- }
-}
-
-#[frb]
-#[derive(Clone, Copy)]
-pub enum AttachmentType {
- ProfilePicture,
-}
-
-impl From<AttachmentType> for ente_contacts::AttachmentType {
- fn from(value: AttachmentType) -> Self {
- match value {
- AttachmentType::ProfilePicture => ente_contacts::AttachmentType::ProfilePicture,
- }
- }
-}
-
-#[frb]
-pub struct OpenContactsCtxInput {
- pub base_url: String,
- pub auth_token: String,
- pub user_id: i64,
- pub master_key: Vec<u8>,
- pub cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,
- pub user_agent: Option<String>,
- pub client_package: Option<String>,
- pub client_version: Option<String>,
-}
-
-#[frb]
-pub struct OpenContactsCtxResult {
- pub ctx: ContactsCtx,
- pub wrapped_root_contact_key: Option<WrappedRootContactKey>,
- pub root_key_source: RootKeySource,
-}
-
-#[frb(opaque)]
-#[derive(Clone)]
-pub struct ContactsCtx {
- session: Arc<Session>,
- contacts: Arc<ente_contacts::ContactsClient>,
-}
-
-#[frb]
-pub async fn open_contacts_ctx(
- input: OpenContactsCtxInput,
-) -> Result<OpenContactsCtxResult, ContactsError> {
- let session = Arc::new(
- Session::new(
- ApiConfig {
- origin: input.base_url,
- client_package: input.client_package,
- client_version: input.client_version,
- user_agent: input.user_agent,
- auth: Some(Auth::User(input.auth_token)),
- },
- SecretVec::new(input.master_key),
- )
- .map_err(ente_contacts::Error::from)?,
- );
- let opened = ente_contacts::ContactsClient::open(
- Arc::clone(&session),
- ente_contacts::OpenContactsInput {
- user_id: input.user_id,
- cached_wrapped_root_contact_key: input.cached_wrapped_root_contact_key.map(Into::into),
- },
- )?;
-
- Ok(OpenContactsCtxResult {
- ctx: ContactsCtx {
- session,
- contacts: Arc::new(opened.client),
- },
- wrapped_root_contact_key: opened.wrapped_root_contact_key.map(Into::into),
- root_key_source: opened.root_key_source.into(),
- })
-}
-
-impl ContactsCtx {
- #[frb(sync)]
- pub fn user_id(&self) -> i64 {
- self.contacts.user_id()
- }
-
- pub fn update_auth_token(&self, auth_token: String) {
- self.session.api.set_auth(Some(Auth::User(auth_token)));
- }
-
- #[frb(sync)]
- pub fn current_wrapped_root_contact_key(&self) -> Option<WrappedRootContactKey> {
- self.contacts
- .current_wrapped_root_contact_key()
- .map(Into::into)
- }
-
- pub async fn create_contact(&self, data: ContactData) -> Result<ContactRecord, ContactsError> {
- self.contacts
- .create_contact(&data.into())
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn get_contact(&self, contact_id: String) -> Result<ContactRecord, ContactsError> {
- self.contacts
- .get_contact(&contact_id)
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn get_diff(
- &self,
- since_time: i64,
- limit: u16,
- ) -> Result<Vec<ContactRecord>, ContactsError> {
- self.contacts
- .get_diff(since_time, limit)
- .await
- .map(|records| records.into_iter().map(Into::into).collect())
- .map_err(Into::into)
- }
-
- pub async fn update_contact(
- &self,
- contact_id: String,
- data: ContactData,
- ) -> Result<ContactRecord, ContactsError> {
- self.contacts
- .update_contact(&contact_id, &data.into())
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn delete_contact(&self, contact_id: String) -> Result<(), ContactsError> {
- self.contacts
- .delete_contact(&contact_id)
- .await
- .map_err(Into::into)
- }
-
- pub async fn set_attachment(
- &self,
- contact_id: String,
- attachment_type: AttachmentType,
- attachment_bytes: Vec<u8>,
- ) -> Result<ContactRecord, ContactsError> {
- self.contacts
- .set_attachment(&contact_id, attachment_type.into(), &attachment_bytes)
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn delete_attachment(
- &self,
- contact_id: String,
- attachment_type: AttachmentType,
- ) -> Result<ContactRecord, ContactsError> {
- self.contacts
- .delete_attachment(&contact_id, attachment_type.into())
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn get_profile_picture(&self, contact_id: String) -> Result<Vec<u8>, ContactsError> {
- self.contacts
- .get_profile_picture(&contact_id)
- .await
- .map_err(Into::into)
- }
-}
diff --git a/rust/bindings/frb/photos/src/api/mod.rs b/rust/bindings/frb/photos/src/api/mod.rs
index 459be57658..4e197eeb58 100644
--- a/rust/bindings/frb/photos/src/api/mod.rs
+++ b/rust/bindings/frb/photos/src/api/mod.rs
@@ -1,5 +1,4 @@
pub mod cast_api;
-pub mod contacts;
pub mod image_processing_api;
pub mod init;
pub mod location_api;
diff --git a/rust/bindings/wasm/contacts/Cargo.toml b/rust/bindings/wasm/contacts/Cargo.toml
new file mode 100644
index 0000000000..5e39ad53f5
--- /dev/null
+++ b/rust/bindings/wasm/contacts/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "ente-wasm-contacts"
+edition = "2024"
+
+[dependencies]
+ente-contacts.workspace = true
+ente-core.workspace = true
+ente-wasm-core.workspace = true
+js-sys.workspace = true
+serde.workspace = true
+serde-wasm-bindgen.workspace = true
+thiserror.workspace = true
+wasm-bindgen.workspace = true
+wasm-bindgen-futures.workspace = true
diff --git a/rust/bindings/wasm/contacts/src/lib.rs b/rust/bindings/wasm/contacts/src/lib.rs
new file mode 100644
index 0000000000..51c8eaa881
--- /dev/null
+++ b/rust/bindings/wasm/contacts/src/lib.rs
@@ -0,0 +1,129 @@
+use ente_contacts::WrappedRootContactKey;
+use ente_wasm_core::Session;
+use serde::{Serialize, Serializer};
+use serde_wasm_bindgen as swb;
+use wasm_bindgen::prelude::*;
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error(transparent)]
+ Contacts(#[from] ente_contacts::Error),
+ #[error(transparent)]
+ Serde(#[from] swb::Error),
+}
+
+impl Error {
+ fn name(&self) -> Option<&'static str> {
+ None
+ }
+
+ fn message(&self) -> String {
+ ente_core::error::chain(self)
+ }
+}
+
+impl From<Error> for JsValue {
+ fn from(error: Error) -> Self {
+ let js_error = js_sys::Error::new(&error.message());
+ if let Some(name) = error.name() {
+ js_error.set_name(name);
+ }
+ js_error.into()
+ }
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ContactRecordJs {
+ id: String,
+ contact_user_id: i64,
+ email: Option<String>,
+ name: Option<String>,
+ #[serde(rename = "profilePictureAttachmentID")]
+ profile_picture_attachment_id: Option<String>,
+ is_deleted: bool,
+ updated_at: i64,
+}
+
+impl From<ente_contacts::ContactRecord> for ContactRecordJs {
+ fn from(value: ente_contacts::ContactRecord) -> Self {
+ Self {
+ id: value.id,
+ contact_user_id: value.contact_user_id,
+ email: value.email,
+ name: value.name,
+ profile_picture_attachment_id: value.profile_picture_attachment_id,
+ is_deleted: value.is_deleted,
+ updated_at: value.updated_at,
+ }
+ }
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ContactsDiffJs {
+ records: Vec<ContactRecordJs>,
+ wrapped_root_contact_key: Option<WrappedRootContactKey>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ProfilePictureJs {
+ #[serde(serialize_with = "serialize_bytes")]
+ bytes: Vec<u8>,
+ wrapped_root_contact_key: Option<WrappedRootContactKey>,
+}
+
+#[wasm_bindgen(js_name = contactsGetDiff)]
+pub async fn contacts_get_diff(
+ session: &Session,
+ cached_encrypted_key: Option<String>,
+ cached_header: Option<String>,
+ since_time: i64,
+ limit: u16,
+) -> Result<JsValue, Error> {
+ let cached = wrapped_root_contact_key(cached_encrypted_key, cached_header);
+ let output =
+ ente_contacts::get_diff(session.inner(), cached.as_ref(), since_time, limit).await?;
+ let output = ContactsDiffJs {
+ records: output.value.into_iter().map(Into::into).collect(),
+ wrapped_root_contact_key: output.wrapped_root_contact_key,
+ };
+ swb::to_value(&output).map_err(Into::into)
+}
+
+#[wasm_bindgen(js_name = contactsGetProfilePicture)]
+pub async fn contacts_get_profile_picture(
+ session: &Session,
+ cached_encrypted_key: Option<String>,
+ cached_header: Option<String>,
+ contact_id: &str,
+) -> Result<JsValue, Error> {
+ let cached = wrapped_root_contact_key(cached_encrypted_key, cached_header);
+ let output =
+ ente_contacts::get_profile_picture(session.inner(), cached.as_ref(), contact_id).await?;
+ swb::to_value(&ProfilePictureJs {
+ bytes: output.value,
+ wrapped_root_contact_key: output.wrapped_root_contact_key,
+ })
+ .map_err(Into::into)
+}
+
+fn wrapped_root_contact_key(
+ encrypted_key: Option<String>,
+ header: Option<String>,
+) -> Option<WrappedRootContactKey> {
+ encrypted_key
+ .zip(header)
+ .map(|(encrypted_key, header)| WrappedRootContactKey {
+ encrypted_key,
+ header,
+ })
+}
+
+fn serialize_bytes<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
+where
+ S: Serializer,
+{
+ serializer.serialize_bytes(bytes)
+}
diff --git a/rust/bindings/wasm/core/src/lib.rs b/rust/bindings/wasm/core/src/lib.rs
index 97f450b133..9d9d072355 100644
--- a/rust/bindings/wasm/core/src/lib.rs
+++ b/rust/bindings/wasm/core/src/lib.rs
@@ -34,10 +34,6 @@ impl Session {
pub fn inner(&self) -> &InnerSession {
&self.0
}
-
- pub fn clone_inner(&self) -> Arc<InnerSession> {
- Arc::clone(&self.0)
- }
}
#[wasm_bindgen]
diff --git a/rust/bindings/wasm/locker/Cargo.toml b/rust/bindings/wasm/locker/Cargo.toml
index 2d0c29d4a7..3403638076 100644
--- a/rust/bindings/wasm/locker/Cargo.toml
+++ b/rust/bindings/wasm/locker/Cargo.toml
@@ -6,13 +6,6 @@ edition = "2024"
crate-type = ["cdylib"]
[dependencies]
-ente-contacts.workspace = true
-ente-core.workspace = true
+ente-wasm-contacts.workspace = true
ente-wasm-core.workspace = true
ente-wasm-log.workspace = true
-js-sys.workspace = true
-serde.workspace = true
-serde-wasm-bindgen.workspace = true
-thiserror.workspace = true
-wasm-bindgen.workspace = true
-wasm-bindgen-futures.workspace = true
diff --git a/rust/bindings/wasm/locker/src/lib.rs b/rust/bindings/wasm/locker/src/lib.rs
index b9f44dbc3d..e1f5565a08 100644
--- a/rust/bindings/wasm/locker/src/lib.rs
+++ b/rust/bindings/wasm/locker/src/lib.rs
@@ -1,116 +1,3 @@
-use ente_contacts::{OpenContactsInput, WrappedRootContactKey};
-use ente_wasm_core::Session;
-use serde::Serialize;
-use serde_wasm_bindgen as swb;
-use wasm_bindgen::prelude::*;
-
+pub use ente_wasm_contacts::{contacts_get_diff, contacts_get_profile_picture};
+pub use ente_wasm_core::{Session, open_session};
use ente_wasm_log as _;
-
-#[derive(Debug, thiserror::Error)]
-pub enum Error {
- #[error(transparent)]
- Contacts(#[from] ente_contacts::Error),
- #[error(transparent)]
- Serde(#[from] swb::Error),
-}
-
-impl Error {
- fn name(&self) -> Option<&'static str> {
- None
- }
-
- fn message(&self) -> String {
- ente_core::error::chain(self)
- }
-}
-
-impl From<Error> for JsValue {
- fn from(error: Error) -> Self {
- let js_error = js_sys::Error::new(&error.message());
- if let Some(name) = error.name() {
- js_error.set_name(name);
- }
- js_error.into()
- }
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct ContactRecordJs {
- id: String,
- contact_user_id: i64,
- email: Option<String>,
- name: Option<String>,
- #[serde(rename = "profilePictureAttachmentID")]
- profile_picture_attachment_id: Option<String>,
- is_deleted: bool,
- updated_at: i64,
-}
-
-impl From<ente_contacts::ContactRecord> for ContactRecordJs {
- fn from(value: ente_contacts::ContactRecord) -> Self {
- Self {
- id: value.id,
- contact_user_id: value.contact_user_id,
- email: value.email,
- name: value.name,
- profile_picture_attachment_id: value.profile_picture_attachment_id,
- is_deleted: value.is_deleted,
- updated_at: value.updated_at,
- }
- }
-}
-
-#[wasm_bindgen(js_name = openContacts)]
-pub fn open_contacts(
- session: &Session,
- user_id: i64,
- cached_encrypted_key: Option<String>,
- cached_header: Option<String>,
-) -> Result<ContactsClient, Error> {
- let opened = ente_contacts::ContactsClient::open(
- session.clone_inner(),
- OpenContactsInput {
- user_id,
- cached_wrapped_root_contact_key: cached_encrypted_key.zip(cached_header).map(
- |(encrypted_key, header)| WrappedRootContactKey {
- encrypted_key,
- header,
- },
- ),
- },
- )?;
-
- Ok(ContactsClient(opened.client))
-}
-
-#[wasm_bindgen]
-pub struct ContactsClient(ente_contacts::ContactsClient);
-
-#[wasm_bindgen]
-impl ContactsClient {
- #[wasm_bindgen(js_name = currentWrappedRootContactKey)]
- pub fn current_wrapped_root_contact_key(&self) -> Result<JsValue, Error> {
- swb::to_value(&self.0.current_wrapped_root_contact_key()).map_err(Into::into)
- }
-
- #[wasm_bindgen(js_name = getDiff)]
- pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<JsValue, Error> {
- let diff: Vec<ContactRecordJs> = self
- .0
- .get_diff(since_time, limit)
- .await?
- .into_iter()
- .map(Into::into)
- .collect();
- swb::to_value(&diff).map_err(Into::into)
- }
-
- #[wasm_bindgen(js_name = getProfilePicture)]
- pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>, Error> {
- self.0
- .get_profile_picture(contact_id)
- .await
- .map_err(Into::into)
- }
-}
diff --git a/rust/bindings/wasm/photos/Cargo.toml b/rust/bindings/wasm/photos/Cargo.toml
index 2a6cef7cbf..97a7609160 100644
--- a/rust/bindings/wasm/photos/Cargo.toml
+++ b/rust/bindings/wasm/photos/Cargo.toml
@@ -6,13 +6,6 @@ edition = "2024"
crate-type = ["cdylib"]
[dependencies]
-ente-contacts.workspace = true
-ente-core.workspace = true
+ente-wasm-contacts.workspace = true
ente-wasm-core.workspace = true
ente-wasm-log.workspace = true
-js-sys.workspace = true
-serde.workspace = true
-serde-wasm-bindgen.workspace = true
-thiserror.workspace = true
-wasm-bindgen.workspace = true
-wasm-bindgen-futures.workspace = true
diff --git a/rust/bindings/wasm/photos/src/lib.rs b/rust/bindings/wasm/photos/src/lib.rs
index b9f44dbc3d..e1f5565a08 100644
--- a/rust/bindings/wasm/photos/src/lib.rs
+++ b/rust/bindings/wasm/photos/src/lib.rs
@@ -1,116 +1,3 @@
-use ente_contacts::{OpenContactsInput, WrappedRootContactKey};
-use ente_wasm_core::Session;
-use serde::Serialize;
-use serde_wasm_bindgen as swb;
-use wasm_bindgen::prelude::*;
-
+pub use ente_wasm_contacts::{contacts_get_diff, contacts_get_profile_picture};
+pub use ente_wasm_core::{Session, open_session};
use ente_wasm_log as _;
-
-#[derive(Debug, thiserror::Error)]
-pub enum Error {
- #[error(transparent)]
- Contacts(#[from] ente_contacts::Error),
- #[error(transparent)]
- Serde(#[from] swb::Error),
-}
-
-impl Error {
- fn name(&self) -> Option<&'static str> {
- None
- }
-
- fn message(&self) -> String {
- ente_core::error::chain(self)
- }
-}
-
-impl From<Error> for JsValue {
- fn from(error: Error) -> Self {
- let js_error = js_sys::Error::new(&error.message());
- if let Some(name) = error.name() {
- js_error.set_name(name);
- }
- js_error.into()
- }
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct ContactRecordJs {
- id: String,
- contact_user_id: i64,
- email: Option<String>,
- name: Option<String>,
- #[serde(rename = "profilePictureAttachmentID")]
- profile_picture_attachment_id: Option<String>,
- is_deleted: bool,
- updated_at: i64,
-}
-
-impl From<ente_contacts::ContactRecord> for ContactRecordJs {
- fn from(value: ente_contacts::ContactRecord) -> Self {
- Self {
- id: value.id,
- contact_user_id: value.contact_user_id,
- email: value.email,
- name: value.name,
- profile_picture_attachment_id: value.profile_picture_attachment_id,
- is_deleted: value.is_deleted,
- updated_at: value.updated_at,
- }
- }
-}
-
-#[wasm_bindgen(js_name = openContacts)]
-pub fn open_contacts(
- session: &Session,
- user_id: i64,
- cached_encrypted_key: Option<String>,
- cached_header: Option<String>,
-) -> Result<ContactsClient, Error> {
- let opened = ente_contacts::ContactsClient::open(
- session.clone_inner(),
- OpenContactsInput {
- user_id,
- cached_wrapped_root_contact_key: cached_encrypted_key.zip(cached_header).map(
- |(encrypted_key, header)| WrappedRootContactKey {
- encrypted_key,
- header,
- },
- ),
- },
- )?;
-
- Ok(ContactsClient(opened.client))
-}
-
-#[wasm_bindgen]
-pub struct ContactsClient(ente_contacts::ContactsClient);
-
-#[wasm_bindgen]
-impl ContactsClient {
- #[wasm_bindgen(js_name = currentWrappedRootContactKey)]
- pub fn current_wrapped_root_contact_key(&self) -> Result<JsValue, Error> {
- swb::to_value(&self.0.current_wrapped_root_contact_key()).map_err(Into::into)
- }
-
- #[wasm_bindgen(js_name = getDiff)]
- pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<JsValue, Error> {
- let diff: Vec<ContactRecordJs> = self
- .0
- .get_diff(since_time, limit)
- .await?
- .into_iter()
- .map(Into::into)
- .collect();
- swb::to_value(&diff).map_err(Into::into)
- }
-
- #[wasm_bindgen(js_name = getProfilePicture)]
- pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>, Error> {
- self.0
- .get_profile_picture(contact_id)
- .await
- .map_err(Into::into)
- }
-}
diff --git a/rust/crates/contacts/src/client/attachment.rs b/rust/crates/contacts/src/client/attachment.rs
index df55974d9a..2919c3fcc4 100644
--- a/rust/crates/contacts/src/client/attachment.rs
+++ b/rust/crates/contacts/src/client/attachment.rs
@@ -1,11 +1,12 @@
use md5::{Digest, Md5};
+use ente_core::Session;
use ente_core::b64;
use ente_core::crypto::{self, blob};
use serde::{Deserialize, Serialize};
-use super::contact::ContactEntityResponse;
-use super::{ContactRecord, ContactsClient};
+use super::contact::{ContactEntityResponse, decode_contact};
+use super::{ContactOutput, ContactRecord, WrappedRootContactKey, root_contact_key};
use crate::{Error, Result};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
@@ -22,165 +23,187 @@ impl AttachmentType {
}
}
-impl ContactsClient {
- pub async fn set_profile_picture(
- &self,
- contact_id: &str,
- profile_picture: &[u8],
- ) -> Result<ContactRecord> {
- self.set_attachment(contact_id, AttachmentType::ProfilePicture, profile_picture)
- .await
- }
+pub async fn set_profile_picture(
+ session: &Session,
+ wrapped_root_contact_key: Option<&WrappedRootContactKey>,
+ contact_id: &str,
+ profile_picture: &[u8],
+) -> Result<ContactOutput<ContactRecord>> {
+ set_attachment(
+ session,
+ wrapped_root_contact_key,
+ contact_id,
+ AttachmentType::ProfilePicture,
+ profile_picture,
+ )
+ .await
+}
- pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>> {
- let current = self
- .api()
- .get(&format!("/contacts/{contact_id}"))
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
- if current.is_deleted {
- return Err(Error::ProfilePictureNotFound);
- }
- let attachment_id = current
- .profile_picture_attachment_id
- .as_deref()
- .ok_or(Error::ProfilePictureNotFound)?;
- self.ensure_confirmed_root_contact_key().await?;
-
- let encrypted_key = current
- .encrypted_key
- .as_deref()
- .ok_or(Error::MissingEncryptedKey)?;
- let contact_key = self.decrypt_contact_key(encrypted_key)?;
- let encrypted_picture = self
- .get_attachment_encrypted(AttachmentType::ProfilePicture, attachment_id)
- .await?;
- decrypt_attachment(&encrypted_picture, &contact_key)
+pub async fn get_profile_picture(
+ session: &Session,
+ wrapped_root_contact_key: Option<&WrappedRootContactKey>,
+ contact_id: &str,
+) -> Result<ContactOutput<Vec<u8>>> {
+ let current = session
+ .api
+ .get(&format!("/contacts/{contact_id}"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ if current.is_deleted {
+ return Err(Error::ProfilePictureNotFound);
}
+ let attachment_id = current
+ .profile_picture_attachment_id
+ .as_deref()
+ .ok_or(Error::ProfilePictureNotFound)?;
+ let root_contact_key = root_contact_key(session, wrapped_root_contact_key).await?;
+ let encrypted_key = current
+ .encrypted_key
+ .as_deref()
+ .ok_or(Error::MissingEncryptedKey)?;
+ let contact_key = root_contact_key.decrypt_contact_key(encrypted_key)?;
+ let encrypted_picture =
+ get_attachment_encrypted(session, AttachmentType::ProfilePicture, attachment_id).await?;
+ let picture = decrypt_attachment(&encrypted_picture, &contact_key)?;
+
+ Ok(ContactOutput::new(picture, Some(root_contact_key)))
+}
- pub async fn delete_profile_picture(&self, contact_id: &str) -> Result<ContactRecord> {
- self.delete_attachment(contact_id, AttachmentType::ProfilePicture)
- .await
- }
+pub async fn delete_profile_picture(
+ session: &Session,
+ wrapped_root_contact_key: Option<&WrappedRootContactKey>,
+ contact_id: &str,
+) -> Result<ContactOutput<ContactRecord>> {
+ delete_attachment(
+ session,
+ wrapped_root_contact_key,
+ contact_id,
+ AttachmentType::ProfilePicture,
+ )
+ .await
+}
- pub async fn set_attachment(
- &self,
- contact_id: &str,
- attachment_type: AttachmentType,
- attachment_bytes: &[u8],
- ) -> Result<ContactRecord> {
- self.ensure_confirmed_root_contact_key().await?;
-
- let current = self
- .api()
- .get(&format!("/contacts/{contact_id}"))
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
- let encrypted_key = current
- .encrypted_key
- .as_deref()
- .ok_or(Error::MissingEncryptedKey)?;
- let contact_key = self.decrypt_contact_key(encrypted_key)?;
- let encrypted_attachment = encrypt_attachment(attachment_bytes, &contact_key)?;
- let content_md5 = content_md5_base64(&encrypted_attachment);
- let size = encrypted_attachment.len() as i64;
-
- let upload = self
- .api()
- .post(&format!(
- "/attachments/{}/upload-url",
- attachment_type.as_str()
- ))
- .json(&AttachmentUploadUrlRequest {
- content_length: size,
- content_md5: content_md5.clone(),
- })
- .send()
- .await?
- .error_for_status()?
- .json::<AttachmentUploadUrlResponse>()
- .await?;
-
- self.api()
- .http()
- .put(&upload.url)
- .header("Content-MD5", &content_md5)
- .body(encrypted_attachment)
- .send()
- .await?
- .error_for_status()?;
-
- let response = self
- .api()
- .put(&format!(
- "/contacts/{contact_id}/attachments/{}",
- attachment_type.as_str()
- ))
- .json(&CommitAttachmentRequest {
- attachment_id: &upload.attachment_id,
- size,
- })
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
-
- self.decode_contact(response)
- }
+pub async fn set_attachment(
+ session: &Session,
+ wrapped_root_contact_key: Option<&WrappedRootContactKey>,
+ contact_id: &str,
+ attachment_type: AttachmentType,
+ attachment_bytes: &[u8],
+) -> Result<ContactOutput<ContactRecord>> {
+ let root_contact_key = root_contact_key(session, wrapped_root_contact_key).await?;
+ let current = session
+ .api
+ .get(&format!("/contacts/{contact_id}"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ let encrypted_key = current
+ .encrypted_key
+ .as_deref()
+ .ok_or(Error::MissingEncryptedKey)?;
+ let contact_key = root_contact_key.decrypt_contact_key(encrypted_key)?;
+ let encrypted_attachment = encrypt_attachment(attachment_bytes, &contact_key)?;
+ let content_md5 = content_md5_base64(&encrypted_attachment);
+ let size = encrypted_attachment.len() as i64;
+ let upload = session
+ .api
+ .post(&format!(
+ "/attachments/{}/upload-url",
+ attachment_type.as_str()
+ ))
+ .json(&AttachmentUploadUrlRequest {
+ content_length: size,
+ content_md5: content_md5.clone(),
+ })
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<AttachmentUploadUrlResponse>()
+ .await?;
+
+ session
+ .api
+ .http()
+ .put(&upload.url)
+ .header("Content-MD5", &content_md5)
+ .body(encrypted_attachment)
+ .send()
+ .await?
+ .error_for_status()?;
+
+ let response = session
+ .api
+ .put(&format!(
+ "/contacts/{contact_id}/attachments/{}",
+ attachment_type.as_str()
+ ))
+ .json(&CommitAttachmentRequest {
+ attachment_id: &upload.attachment_id,
+ size,
+ })
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ let record = decode_contact(response, Some(&root_contact_key))?;
+
+ Ok(ContactOutput::new(record, Some(root_contact_key)))
+}
- pub async fn get_attachment_encrypted(
- &self,
- attachment_type: AttachmentType,
- attachment_id: &str,
- ) -> Result<Vec<u8>> {
- let download = self
- .api()
- .get(&format!(
- "/attachments/{}/{attachment_id}",
- attachment_type.as_str()
- ))
- .send()
- .await?
- .error_for_status()?
- .json::<SignedUrlResponse>()
- .await?;
- Ok(self
- .api()
- .http()
- .get(&download.url)
- .send()
- .await?
- .error_for_status()?
- .bytes()
- .await?)
- }
+pub async fn get_attachment_encrypted(
+ session: &Session,
+ attachment_type: AttachmentType,
+ attachment_id: &str,
+) -> Result<Vec<u8>> {
+ let download = session
+ .api
+ .get(&format!(
+ "/attachments/{}/{attachment_id}",
+ attachment_type.as_str()
+ ))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<SignedUrlResponse>()
+ .await?;
+ Ok(session
+ .api
+ .http()
+ .get(&download.url)
+ .send()
+ .await?
+ .error_for_status()?
+ .bytes()
+ .await?)
+}
- pub async fn delete_attachment(
- &self,
- contact_id: &str,
- attachment_type: AttachmentType,
- ) -> Result<ContactRecord> {
- self.ensure_confirmed_root_contact_key().await?;
- let response = self
- .api()
- .delete(&format!(
- "/contacts/{contact_id}/attachments/{}",
- attachment_type.as_str()
- ))
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
- self.decode_contact(response)
- }
+pub async fn delete_attachment(
+ session: &Session,
+ wrapped_root_contact_key: Option<&WrappedRootContactKey>,
+ contact_id: &str,
+ attachment_type: AttachmentType,
+) -> Result<ContactOutput<ContactRecord>> {
+ let root_contact_key = root_contact_key(session, wrapped_root_contact_key).await?;
+ let response = session
+ .api
+ .delete(&format!(
+ "/contacts/{contact_id}/attachments/{}",
+ attachment_type.as_str()
+ ))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ let record = decode_contact(response, Some(&root_contact_key))?;
+
+ Ok(ContactOutput::new(record, Some(root_contact_key)))
}
fn encrypt_attachment(bytes: &[u8], contact_key: &[u8]) -> Result<Vec<u8>> {
diff --git a/rust/crates/contacts/src/client/contact.rs b/rust/crates/contacts/src/client/contact.rs
index 7d7ebad1ba..5dfc4e6240 100644
--- a/rust/crates/contacts/src/client/contact.rs
+++ b/rust/crates/contacts/src/client/contact.rs
@@ -1,8 +1,9 @@
+use ente_core::Session;
use ente_core::b64;
use ente_core::crypto::{self, SecretVec, blob};
use serde::{Deserialize, Serialize};
-use super::ContactsClient;
+use super::{ContactOutput, RootContactKey, WrappedRootContactKey, root_contact_key};
use crate::{Error, Result};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
@@ -24,154 +25,178 @@ pub struct ContactRecord {
pub updated_at: i64,
}
-impl ContactsClient {
- pub async fn create_contact(&self, data: &ContactData) -> Result<ContactRecord> {
- validate_contact_data(data)?;
- self.ensure_confirmed_root_contact_key().await?;
-
- let contact_key = SecretVec::new(crypto::random_bytes(32));
- let wrapped_contact_key = self.encrypt_contact_key(&contact_key)?;
- let encrypted_data = encrypt_contact_data(data, &contact_key)?;
- let response = self
- .api()
- .post("/contacts")
- .json(&CreateContactRequest {
- contact_user_id: data.contact_user_id,
- encrypted_key: &wrapped_contact_key,
- encrypted_data: &encrypted_data,
- })
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
-
- self.decode_contact(response)
- }
+pub async fn create_contact(
+ session: &Session,
+ wrapped_root_contact_key: Option<&WrappedRootContactKey>,
+ data: &ContactData,
+) -> Result<ContactOutput<ContactRecord>> {
+ validate_contact_data(data)?;
+ let root_contact_key = root_contact_key(session, wrapped_root_contact_key).await?;
+ let contact_key = SecretVec::new(crypto::random_bytes(32));
+ let wrapped_contact_key = root_contact_key.encrypt_contact_key(&contact_key)?;
+ let encrypted_data = encrypt_contact_data(data, &contact_key)?;
+ let response = session
+ .api
+ .post("/contacts")
+ .json(&CreateContactRequest {
+ contact_user_id: data.contact_user_id,
+ encrypted_key: &wrapped_contact_key,
+ encrypted_data: &encrypted_data,
+ })
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ let record = decode_contact(response, Some(&root_contact_key))?;
- pub async fn get_contact(&self, contact_id: &str) -> Result<ContactRecord> {
- let response = self
- .api()
- .get(&format!("/contacts/{contact_id}"))
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
- if !response.is_deleted {
- self.ensure_confirmed_root_contact_key().await?;
- }
- self.decode_contact(response)
- }
+ Ok(ContactOutput::new(record, Some(root_contact_key)))
+}
- pub async fn update_contact(
- &self,
- contact_id: &str,
- data: &ContactData,
- ) -> Result<ContactRecord> {
- validate_contact_data(data)?;
- self.ensure_confirmed_root_contact_key().await?;
-
- let current = self
- .api()
- .get(&format!("/contacts/{contact_id}"))
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
- let encrypted_key = current
- .encrypted_key
- .as_deref()
- .ok_or(Error::MissingEncryptedKey)?;
- let contact_key = self.decrypt_contact_key(encrypted_key)?;
- let encrypted_data = encrypt_contact_data(data, &contact_key)?;
-
- let response = self
- .api()
- .put(&format!("/contacts/{contact_id}"))
- .json(&UpdateContactRequest {
- contact_user_id: data.contact_user_id,
- encrypted_data: &encrypted_data,
- })
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
-
- self.decode_contact(response)
- }
+pub async fn get_contact(
+ session: &Session,
+ wrapped_root_contact_key: Option<&WrappedRootContactKey>,
+ contact_id: &str,
+) -> Result<ContactOutput<ContactRecord>> {
+ let response = session
+ .api
+ .get(&format!("/contacts/{contact_id}"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ let root_contact_key = if response.is_deleted {
+ None
+ } else {
+ Some(root_contact_key(session, wrapped_root_contact_key).await?)
+ };
+ let record = decode_contact(response, root_contact_key.as_ref())?;
- pub async fn delete_contact(&self, contact_id: &str) -> Result<()> {
- self.api()
- .delete(&format!("/contacts/{contact_id}"))
- .send()
- .await?
- .error_for_status()?;
- Ok(())
- }
+ Ok(ContactOutput::new(record, root_contact_key))
+}
- pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<Vec<ContactRecord>> {
- let response = self
- .api()
- .get("/contacts/diff")
- .query(&[
- ("sinceTime", since_time.to_string()),
- ("limit", limit.to_string()),
- ])
- .send()
- .await?
- .error_for_status()?
- .json::<ContactDiffResponse>()
- .await?;
- if response.diff.iter().any(|entity| !entity.is_deleted) {
- self.ensure_confirmed_root_contact_key().await?;
- }
-
- response
- .diff
- .into_iter()
- .map(|entity| self.decode_contact(entity))
- .collect()
- }
+pub async fn update_contact(
+ session: &Session,
+ wrapped_root_contact_key: Option<&WrappedRootContactKey>,
+ contact_id: &str,
+ data: &ContactData,
+) -> Result<ContactOutput<ContactRecord>> {
+ validate_contact_data(data)?;
+ let root_contact_key = root_contact_key(session, wrapped_root_contact_key).await?;
+ let current = session
+ .api
+ .get(&format!("/contacts/{contact_id}"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ let encrypted_key = current
+ .encrypted_key
+ .as_deref()
+ .ok_or(Error::MissingEncryptedKey)?;
+ let contact_key = root_contact_key.decrypt_contact_key(encrypted_key)?;
+ let encrypted_data = encrypt_contact_data(data, &contact_key)?;
+ let response = session
+ .api
+ .put(&format!("/contacts/{contact_id}"))
+ .json(&UpdateContactRequest {
+ contact_user_id: data.contact_user_id,
+ encrypted_data: &encrypted_data,
+ })
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ let record = decode_contact(response, Some(&root_contact_key))?;
+
+ Ok(ContactOutput::new(record, Some(root_contact_key)))
+}
+
+pub async fn delete_contact(session: &Session, contact_id: &str) -> Result<()> {
+ session
+ .api
+ .delete(&format!("/contacts/{contact_id}"))
+ .send()
+ .await?
+ .error_for_status()?;
+ Ok(())
+}
+
+pub async fn get_diff(
+ session: &Session,
+ wrapped_root_contact_key: Option<&WrappedRootContactKey>,
+ since_time: i64,
+ limit: u16,
+) -> Result<ContactOutput<Vec<ContactRecord>>> {
+ let response = session
+ .api
+ .get("/contacts/diff")
+ .query(&[
+ ("sinceTime", since_time.to_string()),
+ ("limit", limit.to_string()),
+ ])
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactDiffResponse>()
+ .await?;
+ let root_contact_key = if response.diff.iter().any(|entity| !entity.is_deleted) {
+ Some(root_contact_key(session, wrapped_root_contact_key).await?)
+ } else {
+ None
+ };
+ let records = response
+ .diff
+ .into_iter()
+ .map(|entity| decode_contact(entity, root_contact_key.as_ref()))
+ .collect::<Result<_>>()?;
- pub(super) fn decode_contact(&self, entity: ContactEntityResponse) -> Result<ContactRecord> {
- if entity.is_deleted {
- return Ok(ContactRecord {
- id: entity.id,
- contact_user_id: entity.contact_user_id,
- email: None,
- name: None,
- profile_picture_attachment_id: None,
- is_deleted: true,
- created_at: entity.created_at,
- updated_at: entity.updated_at,
- });
- }
-
- let encrypted_key = entity
- .encrypted_key
- .as_deref()
- .ok_or(Error::MissingEncryptedKey)?;
- let encrypted_data = entity
- .encrypted_data
- .as_deref()
- .ok_or(Error::MissingEncryptedData)?;
- let contact_key = self.decrypt_contact_key(encrypted_key)?;
- let data = decrypt_contact_data(encrypted_data, &contact_key)?;
-
- Ok(ContactRecord {
+ Ok(ContactOutput::new(records, root_contact_key))
+}
+
+pub(super) fn decode_contact(
+ entity: ContactEntityResponse,
+ root_contact_key: Option<&RootContactKey>,
+) -> Result<ContactRecord> {
+ if entity.is_deleted {
+ return Ok(ContactRecord {
id: entity.id,
contact_user_id: entity.contact_user_id,
- email: entity.email,
- name: Some(data.name),
- profile_picture_attachment_id: entity.profile_picture_attachment_id,
- is_deleted: false,
+ email: None,
+ name: None,
+ profile_picture_attachment_id: None,
+ is_deleted: true,
created_at: entity.created_at,
updated_at: entity.updated_at,
- })
+ });
}
+
+ let root_contact_key = root_contact_key
+ .ok_or_else(|| Error::InvalidInput("contacts root key is unresolved".into()))?;
+ let encrypted_key = entity
+ .encrypted_key
+ .as_deref()
+ .ok_or(Error::MissingEncryptedKey)?;
+ let encrypted_data = entity
+ .encrypted_data
+ .as_deref()
+ .ok_or(Error::MissingEncryptedData)?;
+ let contact_key = root_contact_key.decrypt_contact_key(encrypted_key)?;
+ let data = decrypt_contact_data(encrypted_data, &contact_key)?;
+
+ Ok(ContactRecord {
+ id: entity.id,
+ contact_user_id: entity.contact_user_id,
+ email: entity.email,
+ name: Some(data.name),
+ profile_picture_attachment_id: entity.profile_picture_attachment_id,
+ is_deleted: false,
+ created_at: entity.created_at,
+ updated_at: entity.updated_at,
+ })
}
fn validate_contact_data(data: &ContactData) -> Result<()> {
diff --git a/rust/crates/contacts/src/client/mod.rs b/rust/crates/contacts/src/client/mod.rs
index 0bed0f2c1e..9fd9a1f573 100644
--- a/rust/crates/contacts/src/client/mod.rs
+++ b/rust/crates/contacts/src/client/mod.rs
@@ -1,10 +1,14 @@
mod attachment;
mod contact;
-pub use attachment::AttachmentType;
-pub use contact::{ContactData, ContactRecord};
-
-use std::sync::{Arc, RwLock};
+pub use attachment::{
+ AttachmentType, delete_attachment, delete_profile_picture, get_attachment_encrypted,
+ get_profile_picture, set_attachment, set_profile_picture,
+};
+pub use contact::{
+ ContactData, ContactRecord, create_contact, delete_contact, get_contact, get_diff,
+ update_contact,
+};
use ente_core::Session;
use ente_core::b64;
@@ -12,16 +16,10 @@ use ente_core::crypto::{self, SecretVec, secretbox};
use ente_core::http::Api;
use serde::{Deserialize, Serialize};
-use crate::{Error, Result};
+use crate::Result;
const CONTACT_TYPE: &str = "contact";
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum RootKeySource {
- Cache,
- Unresolved,
-}
-
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct WrappedRootContactKey {
@@ -29,144 +27,65 @@ pub struct WrappedRootContactKey {
pub header: String,
}
-pub struct OpenContactsInput {
- pub user_id: i64,
- pub cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,
-}
-
-pub struct OpenContactsResult {
- pub client: ContactsClient,
+pub struct ContactOutput<T> {
+ pub value: T,
pub wrapped_root_contact_key: Option<WrappedRootContactKey>,
- pub root_key_source: RootKeySource,
}
-pub struct ContactsClient {
- user_id: i64,
- session: Arc<Session>,
- root_contact_key: Arc<RwLock<Option<SecretVec>>>,
- wrapped_root_contact_key: Arc<RwLock<Option<WrappedRootContactKey>>>,
+struct RootContactKey {
+ key: SecretVec,
+ wrapped: WrappedRootContactKey,
}
-impl ContactsClient {
- pub fn open(session: Arc<Session>, input: OpenContactsInput) -> Result<OpenContactsResult> {
- let (root_contact_key, wrapped_root_contact_key, root_key_source) =
- if let Some(cached_wrapped_root_contact_key) = input.cached_wrapped_root_contact_key {
- let root_contact_key = decrypt_root_contact_key(
- &cached_wrapped_root_contact_key,
- &session.master_key,
- )?;
- (
- Some(root_contact_key),
- Some(cached_wrapped_root_contact_key),
- RootKeySource::Cache,
- )
- } else {
- (None, None, RootKeySource::Unresolved)
- };
- let client = Self {
- user_id: input.user_id,
- session,
- root_contact_key: Arc::new(RwLock::new(root_contact_key)),
- wrapped_root_contact_key: Arc::new(RwLock::new(wrapped_root_contact_key.clone())),
- };
-
- Ok(OpenContactsResult {
- client,
- wrapped_root_contact_key,
- root_key_source,
- })
- }
-
- pub fn user_id(&self) -> i64 {
- self.user_id
- }
-
- pub fn current_wrapped_root_contact_key(&self) -> Option<WrappedRootContactKey> {
- self.wrapped_root_contact_key
- .read()
- .expect("wrapped root key lock poisoned")
- .clone()
- }
-
- fn api(&self) -> &Api {
- &self.session.api
+impl RootContactKey {
+ fn from_wrapped(wrapped: WrappedRootContactKey, master_key: &[u8]) -> Result<Self> {
+ let key = decrypt_root_contact_key(&wrapped, master_key)?;
+ Ok(Self { key, wrapped })
}
fn encrypt_contact_key(&self, contact_key: &[u8]) -> Result<String> {
- let root_contact_key = self
- .root_contact_key
- .read()
- .expect("root contact key lock poisoned");
- let root_contact_key = root_contact_key
- .as_ref()
- .ok_or_else(|| Error::InvalidInput("contacts root key is unresolved".into()))?;
- let encrypted = secretbox::encrypt_combined(
- contact_key,
- &crypto::Key::try_from_slice(root_contact_key)?,
- );
+ let encrypted =
+ secretbox::encrypt_combined(contact_key, &crypto::Key::try_from_slice(&self.key)?);
Ok(b64::encode(&encrypted))
}
fn decrypt_contact_key(&self, encrypted_key: &str) -> Result<SecretVec> {
- let root_contact_key = self
- .root_contact_key
- .read()
- .expect("root contact key lock poisoned");
- let root_contact_key = root_contact_key
- .as_ref()
- .ok_or_else(|| Error::InvalidInput("contacts root key is unresolved".into()))?;
let encrypted_key = b64::decode(encrypted_key)?;
- let contact_key = secretbox::decrypt_combined(
- &encrypted_key,
- &crypto::Key::try_from_slice(root_contact_key)?,
- )?;
+ let contact_key =
+ secretbox::decrypt_combined(&encrypted_key, &crypto::Key::try_from_slice(&self.key)?)?;
Ok(SecretVec::new(contact_key))
}
+}
- async fn ensure_confirmed_root_contact_key(&self) -> Result<()> {
- if self
- .root_contact_key
- .read()
- .expect("root contact key lock poisoned")
- .is_some()
- {
- return Ok(());
- }
-
- if let Some(remote_root_key) = fetch_root_key(self.api()).await? {
- self.apply_wrapped_root_contact_key(remote_root_key.into())?;
- } else {
- let generated_root_contact_key = SecretVec::new(crypto::random_bytes(32));
- let generated_wrapped_root_contact_key =
- encrypt_root_contact_key(&generated_root_contact_key, &self.session.master_key)?;
- if let Some(remote_root_key) =
- create_root_key(self.api(), &generated_wrapped_root_contact_key).await?
- {
- self.apply_wrapped_root_contact_key(remote_root_key.into())?;
- } else {
- self.apply_wrapped_root_contact_key(generated_wrapped_root_contact_key)?;
- }
+impl<T> ContactOutput<T> {
+ fn new(value: T, root_contact_key: Option<RootContactKey>) -> Self {
+ Self {
+ value,
+ wrapped_root_contact_key: root_contact_key.map(|key| key.wrapped),
}
-
- Ok(())
}
+}
- fn apply_wrapped_root_contact_key(
- &self,
- wrapped_root_contact_key: WrappedRootContactKey,
- ) -> Result<()> {
- let decrypted_root_key =
- decrypt_root_contact_key(&wrapped_root_contact_key, &self.session.master_key)?;
- *self
- .root_contact_key
- .write()
- .expect("root contact key lock poisoned") = Some(decrypted_root_key);
- *self
- .wrapped_root_contact_key
- .write()
- .expect("wrapped root key lock poisoned") = Some(wrapped_root_contact_key);
- Ok(())
+async fn root_contact_key(
+ session: &Session,
+ cached: Option<&WrappedRootContactKey>,
+) -> Result<RootContactKey> {
+ if let Some(cached) = cached {
+ return RootContactKey::from_wrapped(cached.clone(), &session.master_key);
}
+
+ let wrapped = if let Some(remote) = fetch_root_key(&session.api).await? {
+ remote.into()
+ } else {
+ let key = SecretVec::new(crypto::random_bytes(32));
+ let wrapped = encrypt_root_contact_key(&key, &session.master_key)?;
+ create_root_key(&session.api, &wrapped)
+ .await?
+ .map(Into::into)
+ .unwrap_or(wrapped)
+ };
+
+ RootContactKey::from_wrapped(wrapped, &session.master_key)
}
fn encrypt_root_contact_key(
diff --git a/rust/crates/contacts/src/lib.rs b/rust/crates/contacts/src/lib.rs
index 8a9291b908..47f6475f12 100644
--- a/rust/crates/contacts/src/lib.rs
+++ b/rust/crates/contacts/src/lib.rs
@@ -2,7 +2,9 @@ mod client;
mod error;
pub use client::{
- AttachmentType, ContactData, ContactRecord, ContactsClient, OpenContactsInput,
- OpenContactsResult, RootKeySource, WrappedRootContactKey,
+ AttachmentType, ContactData, ContactOutput, ContactRecord, WrappedRootContactKey,
+ create_contact, delete_attachment, delete_contact, delete_profile_picture,
+ get_attachment_encrypted, get_contact, get_diff, get_profile_picture, set_attachment,
+ set_profile_picture, update_contact,
};
pub use error::{Error, Result};
diff --git a/rust/crates/contacts/tests/contacts_mock.rs b/rust/crates/contacts/tests/contacts_mock.rs
index b3f7c9a8fb..d534de5ad1 100644
--- a/rust/crates/contacts/tests/contacts_mock.rs
+++ b/rust/crates/contacts/tests/contacts_mock.rs
@@ -1,8 +1,7 @@
-use std::sync::Arc;
+use std::sync::RwLock;
use ente_contacts::{
- AttachmentType, ContactData, ContactsClient, OpenContactsInput, OpenContactsResult,
- RootKeySource, WrappedRootContactKey,
+ AttachmentType, ContactData, ContactOutput, ContactRecord, WrappedRootContactKey,
};
use ente_core::{
Session, b64,
@@ -22,7 +21,7 @@ fn open(
base_url: String,
master_key: Vec<u8>,
cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,
-) -> ente_contacts::Result<OpenContactsResult> {
+) -> ente_contacts::Result<Client> {
let api = Api::new(
Http::new()?,
ApiConfig {
@@ -33,16 +32,91 @@ fn open(
auth: Some(Auth::User("auth-token".to_string())),
},
);
- ContactsClient::open(
- Arc::new(Session {
+ Ok(Client {
+ session: Session {
api,
master_key: SecretVec::new(master_key),
- }),
- OpenContactsInput {
- user_id: 7,
- cached_wrapped_root_contact_key,
},
- )
+ wrapped_root_contact_key: RwLock::new(cached_wrapped_root_contact_key),
+ })
+}
+
+struct Client {
+ session: Session,
+ wrapped_root_contact_key: RwLock<Option<WrappedRootContactKey>>,
+}
+
+impl Client {
+ fn cached_root_key(&self) -> Option<WrappedRootContactKey> {
+ self.wrapped_root_contact_key.read().unwrap().clone()
+ }
+
+ fn value<T>(&self, output: ContactOutput<T>) -> T {
+ if let Some(key) = output.wrapped_root_contact_key {
+ *self.wrapped_root_contact_key.write().unwrap() = Some(key);
+ }
+ output.value
+ }
+
+ async fn create_contact(&self, data: &ContactData) -> ente_contacts::Result<ContactRecord> {
+ let cached = self.cached_root_key();
+ Ok(self.value(ente_contacts::create_contact(&self.session, cached.as_ref(), data).await?))
+ }
+
+ async fn get_contact(&self, contact_id: &str) -> ente_contacts::Result<ContactRecord> {
+ let cached = self.cached_root_key();
+ Ok(self
+ .value(ente_contacts::get_contact(&self.session, cached.as_ref(), contact_id).await?))
+ }
+
+ async fn get_diff(
+ &self,
+ since_time: i64,
+ limit: u16,
+ ) -> ente_contacts::Result<Vec<ContactRecord>> {
+ let cached = self.cached_root_key();
+ Ok(self.value(
+ ente_contacts::get_diff(&self.session, cached.as_ref(), since_time, limit).await?,
+ ))
+ }
+
+ async fn set_profile_picture(
+ &self,
+ contact_id: &str,
+ bytes: &[u8],
+ ) -> ente_contacts::Result<ContactRecord> {
+ let cached = self.cached_root_key();
+ Ok(self.value(
+ ente_contacts::set_profile_picture(&self.session, cached.as_ref(), contact_id, bytes)
+ .await?,
+ ))
+ }
+
+ async fn get_profile_picture(&self, contact_id: &str) -> ente_contacts::Result<Vec<u8>> {
+ let cached = self.cached_root_key();
+ Ok(self.value(
+ ente_contacts::get_profile_picture(&self.session, cached.as_ref(), contact_id).await?,
+ ))
+ }
+
+ async fn delete_profile_picture(
+ &self,
+ contact_id: &str,
+ ) -> ente_contacts::Result<ContactRecord> {
+ let cached = self.cached_root_key();
+ Ok(self.value(
+ ente_contacts::delete_profile_picture(&self.session, cached.as_ref(), contact_id)
+ .await?,
+ ))
+ }
+
+ async fn get_attachment_encrypted(
+ &self,
+ attachment_type: AttachmentType,
+ attachment_id: &str,
+ ) -> ente_contacts::Result<Vec<u8>> {
+ ente_contacts::get_attachment_encrypted(&self.session, attachment_type, attachment_id).await
+ }
}
fn wrap_root(root_key: &[u8], master_key: &[u8]) -> WrappedRootContactKey {
@@ -82,38 +156,6 @@ fn live_entity_json(
})
}
-#[tokio::test]
-async fn open_without_cached_wrapped_root_contact_key_is_unresolved() {
- let mut server = Server::new_async().await;
- let master_key = Key::generate().as_bytes().to_vec();
- let root_key = Key::generate().as_bytes().to_vec();
- let wrapped_root = wrap_root(&root_key, &master_key);
-
- let root_mock = server
- .mock("GET", "/user-entity/key")
- .match_query(Matcher::UrlEncoded("type".into(), "contact".into()))
- .with_status(200)
- .with_body(
- serde_json::json!({
- "userID": 7,
- "type": "contact",
- "encryptedKey": wrapped_root.encrypted_key,
- "header": wrapped_root.header,
- "createdAt": 1
- })
- .to_string(),
- )
- .expect(0)
- .create_async()
- .await;
-
- let opened = open(server.url(), master_key.clone(), None).unwrap();
-
- root_mock.assert_async().await;
- assert_eq!(opened.root_key_source, RootKeySource::Unresolved);
- assert_eq!(opened.wrapped_root_contact_key, None);
-}
-
#[tokio::test]
async fn get_contact_fetches_root_key_when_unresolved_context_reads_live_contact() {
let mut server = Server::new_async().await;
@@ -157,16 +199,12 @@ async fn get_contact_fetches_root_key_when_unresolved_context_reads_live_contact
.create_async()
.await;
- let opened = open(server.url(), master_key, None).unwrap();
- let fetched = opened.client.get_contact("ct_contact1").await.unwrap();
+ let client = open(server.url(), master_key, None).unwrap();
+ let fetched = client.get_contact("ct_contact1").await.unwrap();
root_fetch_mock.assert_async().await;
get_contact_mock.assert_async().await;
- assert_eq!(opened.root_key_source, RootKeySource::Unresolved);
- assert_eq!(
- opened.client.current_wrapped_root_contact_key(),
- Some(server_wrapped_root)
- );
+ assert_eq!(client.cached_root_key(), Some(server_wrapped_root));
assert_eq!(fetched.name.as_deref(), Some(contact.name.as_str()));
}
@@ -218,9 +256,7 @@ async fn create_contact_uses_cached_wrapped_root_contact_key_without_fetching_re
.create_async()
.await;
- let ctx = open(server.url(), master_key, Some(wrapped_root))
- .unwrap()
- .client;
+ let ctx = open(server.url(), master_key, Some(wrapped_root)).unwrap();
let created = ctx.create_contact(&contact).await.unwrap();
@@ -319,7 +355,7 @@ async fn set_profile_picture_uses_signed_upload_url_and_commit() {
.create_async()
.await;
- let ctx = open(server.url(), master_key, None).unwrap().client;
+ let ctx = open(server.url(), master_key, None).unwrap();
let updated = ctx
.set_profile_picture("ct_picture1", &picture_bytes)
@@ -414,7 +450,7 @@ async fn get_profile_picture_uses_signed_download_url() {
.create_async()
.await;
- let ctx = open(server.url(), master_key, None).unwrap().client;
+ let ctx = open(server.url(), master_key, None).unwrap();
let downloaded = ctx.get_profile_picture("ct_picture1").await.unwrap();
@@ -470,7 +506,7 @@ async fn delete_profile_picture_fetches_root_key_when_unresolved_context_decodes
.create_async()
.await;
- let ctx = open(server.url(), master_key, None).unwrap().client;
+ let ctx = open(server.url(), master_key, None).unwrap();
let updated = ctx.delete_profile_picture("ct_picture1").await.unwrap();
@@ -532,7 +568,7 @@ async fn get_attachment_uses_generic_signed_download_url() {
.create_async()
.await;
- let ctx = open(server.url(), master_key, None).unwrap().client;
+ let ctx = open(server.url(), master_key, None).unwrap();
let downloaded = ctx
.get_attachment_encrypted(AttachmentType::ProfilePicture, "ua_generic1")
@@ -596,7 +632,7 @@ async fn deleted_contacts_surface_as_tombstones() {
.create_async()
.await;
- let ctx = open(server.url(), master_key, None).unwrap().client;
+ let ctx = open(server.url(), master_key, None).unwrap();
let diff = ctx.get_diff(0, 10).await.unwrap();
root_mock.assert_async().await;
@@ -647,9 +683,7 @@ async fn get_diff_uses_cached_wrapped_root_contact_key_for_reads_without_fetchin
.create_async()
.await;
- let ctx = open(server.url(), master_key, Some(cached_wrapped_root))
- .unwrap()
- .client;
+ let ctx = open(server.url(), master_key, Some(cached_wrapped_root)).unwrap();
let diff = ctx.get_diff(0, 10).await.unwrap();
diff --git a/rust/crates/contacts/tests/support/contacts.rs b/rust/crates/contacts/tests/support/contacts.rs
index f30cb70cc4..3d4c48ae0b 100644
--- a/rust/crates/contacts/tests/support/contacts.rs
+++ b/rust/crates/contacts/tests/support/contacts.rs
@@ -1,6 +1,6 @@
-use std::sync::Arc;
+use std::sync::RwLock;
-use ente_contacts::{ContactsClient, OpenContactsInput};
+use ente_contacts::{ContactData, ContactOutput, ContactRecord, WrappedRootContactKey};
use ente_core::{
Session,
crypto::SecretVec,
@@ -10,7 +10,62 @@ use ente_core::{
use crate::CLIENT_PACKAGE;
use crate::support::auth::TestAccount;
-pub fn open_client(endpoint: &str, account: &TestAccount) -> ContactsClient {
+pub struct Client {
+ session: Session,
+ wrapped_root_contact_key: RwLock<Option<WrappedRootContactKey>>,
+}
+
+impl Client {
+ pub async fn create_contact(&self, data: &ContactData) -> ente_contacts::Result<ContactRecord> {
+ let cached = self.wrapped_root_contact_key();
+ Ok(self.value(ente_contacts::create_contact(&self.session, cached.as_ref(), data).await?))
+ }
+
+ pub async fn get_contact(&self, contact_id: &str) -> ente_contacts::Result<ContactRecord> {
+ let cached = self.wrapped_root_contact_key();
+ Ok(self
+ .value(ente_contacts::get_contact(&self.session, cached.as_ref(), contact_id).await?))
+ }
+
+ pub async fn update_contact(
+ &self,
+ contact_id: &str,
+ data: &ContactData,
+ ) -> ente_contacts::Result<ContactRecord> {
+ let cached = self.wrapped_root_contact_key();
+ Ok(self.value(
+ ente_contacts::update_contact(&self.session, cached.as_ref(), contact_id, data).await?,
+ ))
+ }
+
+ pub async fn delete_contact(&self, contact_id: &str) -> ente_contacts::Result<()> {
+ ente_contacts::delete_contact(&self.session, contact_id).await
+ }
+
+ pub async fn get_diff(
+ &self,
+ since_time: i64,
+ limit: u16,
+ ) -> ente_contacts::Result<Vec<ContactRecord>> {
+ let cached = self.wrapped_root_contact_key();
+ Ok(self.value(
+ ente_contacts::get_diff(&self.session, cached.as_ref(), since_time, limit).await?,
+ ))
+ }
+
+ fn wrapped_root_contact_key(&self) -> Option<WrappedRootContactKey> {
+ self.wrapped_root_contact_key.read().unwrap().clone()
+ }
+
+ fn value<T>(&self, output: ContactOutput<T>) -> T {
+ if let Some(key) = output.wrapped_root_contact_key {
+ *self.wrapped_root_contact_key.write().unwrap() = Some(key);
+ }
+ output.value
+ }
+}
+
+pub fn open_client(endpoint: &str, account: &TestAccount) -> Client {
let api = Api::new(
Http::new().unwrap(),
ApiConfig {
@@ -21,16 +76,11 @@ pub fn open_client(endpoint: &str, account: &TestAccount) -> ContactsClient {
auth: Some(Auth::User(account.auth_token.clone())),
},
);
- ContactsClient::open(
- Arc::new(Session {
+ Client {
+ session: Session {
api,
master_key: SecretVec::new(account.master_key.clone()),
- }),
- OpenContactsInput {
- user_id: account.user_id,
- cached_wrapped_root_contact_key: None,
},
- )
- .unwrap()
- .client
+ wrapped_root_contact_key: RwLock::new(None),
+ }
}
diff --git a/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx b/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
index c385e639c7..f5555b0250 100644
--- a/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
+++ b/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
@@ -21,7 +21,6 @@ import {
Typography,
} from "@mui/material";
import { savedLocalUser } from "ente-accounts/services/accounts-db";
-import { masterKeyFromSession } from "ente-accounts/services/session-storage";
import {
OverflowMenu,
OverflowMenuOption,
@@ -31,11 +30,9 @@ import { useBaseContext } from "ente-base/context";
import { isHTTPErrorWithStatus } from "ente-base/http";
import log from "ente-base/log";
import {
- ensureContactsReady,
useResolvedContactAvatar,
useResolvedContactDisplay,
} from "ente-contacts";
-import { openContacts } from "ente-locker-wasm";
import { t } from "i18next";
import React, { useCallback, useEffect, useMemo, useState } from "react";
@@ -49,6 +46,7 @@ interface LockerCollectionShareDrawerProps {
onRefreshSharees?: (
collectionID: number,
) => Promise<LockerCollectionParticipant[]>;
+ warmContacts: () => Promise<void>;
}
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
@@ -63,6 +61,7 @@ export const LockerCollectionShareDrawer: React.FC<
onUnshareCollection,
onLeaveCollection,
onRefreshSharees,
+ warmContacts,
}) => {
const { showMiniDialog } = useBaseContext();
const currentUser = savedLocalUser() ?? { id: Number.NaN, email: "" };
@@ -139,24 +138,13 @@ export const LockerCollectionShareDrawer: React.FC<
return;
}
- void (async () => {
- try {
- const masterKeyB64 = await masterKeyFromSession();
- if (!masterKeyB64) {
- return;
- }
- await ensureContactsReady(
- { userID: currentUser.id, masterKeyB64 },
- openContacts,
- );
- } catch (error) {
- log.warn(
- "[LockerCollectionShareDrawer] Failed to warm contacts display cache",
- error,
- );
- }
- })();
- }, [currentUser.id, open]);
+ void warmContacts().catch((error: unknown) => {
+ log.warn(
+ "[LockerCollectionShareDrawer] Failed to warm contacts display cache",
+ error,
+ );
+ });
+ }, [open, warmContacts]);
const sortedSharees = useMemo(
() =>
diff --git a/web/apps/locker/src/components/lockerPage/use-locker-data.ts b/web/apps/locker/src/components/lockerPage/use-locker-data.ts
index c82c7b171f..4ddfc5b711 100644
--- a/web/apps/locker/src/components/lockerPage/use-locker-data.ts
+++ b/web/apps/locker/src/components/lockerPage/use-locker-data.ts
@@ -1,3 +1,7 @@
+import {
+ authenticatedSession,
+ openAuthenticatedSession,
+} from "@/services/authenticated-session";
import {
LOCKER_FILE_LIMIT_FREE,
LOCKER_FILE_LIMIT_PAID,
@@ -24,7 +28,7 @@ import log from "ente-base/log";
import { apiURL } from "ente-base/origins";
import { savedAuthToken } from "ente-base/token";
import { ensureContactsReady } from "ente-contacts";
-import { openContacts } from "ente-locker-wasm";
+import { contactsGetDiff, contactsGetProfilePicture } from "ente-locker-wasm";
import { t } from "i18next";
import type { NextRouter } from "next/router";
import { useCallback, useEffect, useRef, useState } from "react";
@@ -106,6 +110,20 @@ export const useLockerData = ({
userDetailsRef.current = userDetails;
}, [userDetails]);
+ const warmContacts = useCallback(async () => {
+ const authToken = await savedAuthToken();
+ if (!authToken) return;
+
+ const session = authenticatedSession();
+ session.updateAuthToken(authToken);
+ await ensureContactsReady(
+ ensureLocalUser().id,
+ session,
+ contactsGetDiff,
+ contactsGetProfilePicture,
+ );
+ }, []);
+
const loadLockerUsage = useCallback(
async (
headers?: Awaited<ReturnType<typeof authenticatedRequestHeaders>>,
@@ -315,10 +333,8 @@ export const useLockerData = ({
}
setMasterKey(mk);
- void ensureContactsReady(
- { userID: ensureLocalUser().id, masterKeyB64: mk },
- openContacts,
- ).catch((error: unknown) => {
+ await openAuthenticatedSession(ensureLocalUser().id, token, mk);
+ void warmContacts().catch((error: unknown) => {
log.warn(
"[locker] Failed to warm contacts display cache",
error,
@@ -362,7 +378,7 @@ export const useLockerData = ({
return () => {
cancelled = true;
};
- }, [fetchAndStoreLockerData, logout, router, showMiniDialog]);
+ }, [fetchAndStoreLockerData, logout, router, showMiniDialog, warmContacts]);
const removeCollectionFromState = useCallback((collectionID: number) => {
setCollections((current) =>
@@ -381,5 +397,6 @@ export const useLockerData = ({
trashLastUpdatedAt,
userDetails,
ensureUploadLimitState,
+ warmContacts,
};
};
diff --git a/web/apps/locker/src/pages/locker.tsx b/web/apps/locker/src/pages/locker.tsx
index 56e8482725..0ea4cb9ddf 100644
--- a/web/apps/locker/src/pages/locker.tsx
+++ b/web/apps/locker/src/pages/locker.tsx
@@ -53,6 +53,7 @@ export const LockerPage: React.FC = () => {
trashItems,
trashLastUpdatedAt,
userDetails,
+ warmContacts,
} = useLockerData({ router, logout, showMiniDialog });
const {
@@ -230,6 +231,7 @@ export const LockerPage: React.FC = () => {
onUnshareCollection={handleUnshareCollection}
onLeaveCollection={handleLeaveCollection}
onRefreshSharees={fetchCollectionSharees}
+ warmContacts={warmContacts}
/>
<DeleteCollectionDialog
dialogState={deleteCollectionDialog}
diff --git a/web/apps/locker/src/services/authenticated-session.ts b/web/apps/locker/src/services/authenticated-session.ts
new file mode 100644
index 0000000000..f36a6988f5
--- /dev/null
+++ b/web/apps/locker/src/services/authenticated-session.ts
@@ -0,0 +1,33 @@
+import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
+import { apiOrigin } from "ente-base/origins";
+import { openSession, type Session } from "ente-locker-wasm";
+
+let current: { key: string; session: Session } | undefined;
+
+export const openAuthenticatedSession = async (
+ userID: number,
+ authToken: string,
+ masterKeyB64: string,
+) => {
+ const baseUrl = await apiOrigin();
+ const key = `${baseUrl}:${userID}`;
+ if (current?.key === key) {
+ current.session.updateAuthToken(authToken);
+ return current.session;
+ }
+
+ const session = await openSession({
+ baseUrl,
+ authToken,
+ masterKeyB64,
+ clientPackage: clientPackageName,
+ clientVersion: isDesktop ? desktopAppVersion : undefined,
+ });
+ current = { key, session };
+ return session;
+};
+
+export const authenticatedSession = () => {
+ if (!current) throw new Error("Authenticated session is not open");
+ return current.session;
+};
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 8ea3467a77..adfcd89a96 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -131,8 +131,9 @@ import {
addManualFileAssignmentsToPerson,
isMLEnabled,
} from "ente-new/photos/services/ml";
-import { openContacts } from "ente-photos-wasm";
+import { contactsGetDiff, contactsGetProfilePicture } from "ente-photos-wasm";
+import { openAuthenticatedSession } from "@/services/authenticated-session";
import { postPullFiles, prePullFiles, pullFiles } from "@/services/pull";
import { uploadManager } from "@/services/upload-manager";
import watcher from "@/services/watch";
@@ -484,7 +485,8 @@ const Page: React.FC = () => {
let unsubscribeMainWindowFocus: (() => void) | undefined;
void (async () => {
- if (!haveMasterKeyInSession() || !(await savedAuthToken())) {
+ const authToken = await savedAuthToken();
+ if (!haveMasterKeyInSession() || !authToken) {
stashRedirect("/gallery");
void router.push("/");
return;
@@ -510,9 +512,16 @@ const Page: React.FC = () => {
const user = ensureLocalUser();
const masterKey = await masterKeyFromSession();
if (masterKey) {
+ const session = await openAuthenticatedSession(
+ user.id,
+ authToken,
+ masterKey,
+ );
void ensureContactsReady(
- { userID: user.id, masterKeyB64: masterKey },
- openContacts,
+ user.id,
+ session,
+ contactsGetDiff,
+ contactsGetProfilePicture,
).catch((error: unknown) => {
log.warn(
"[gallery] Failed to warm contacts display cache",
diff --git a/web/apps/photos/src/services/authenticated-session.ts b/web/apps/photos/src/services/authenticated-session.ts
new file mode 100644
index 0000000000..d7fde899b7
--- /dev/null
+++ b/web/apps/photos/src/services/authenticated-session.ts
@@ -0,0 +1,33 @@
+import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
+import { apiOrigin } from "ente-base/origins";
+import { openSession, type Session } from "ente-photos-wasm";
+
+let current: { key: string; session: Session } | undefined;
+
+export const openAuthenticatedSession = async (
+ userID: number,
+ authToken: string,
+ masterKeyB64: string,
+) => {
+ const baseUrl = await apiOrigin();
+ const key = `${baseUrl}:${userID}`;
+ if (current?.key === key) {
+ current.session.updateAuthToken(authToken);
+ return current.session;
+ }
+
+ const session = await openSession({
+ baseUrl,
+ authToken,
+ masterKeyB64,
+ clientPackage: clientPackageName,
+ clientVersion: isDesktop ? desktopAppVersion : undefined,
+ });
+ current = { key, session };
+ return session;
+};
+
+export const authenticatedSession = () => {
+ if (!current) throw new Error("Authenticated session is not open");
+ return current.session;
+};
diff --git a/web/packages/contacts/index.test.ts b/web/packages/contacts/index.test.ts
index 0336877b74..04620b42e3 100644
--- a/web/packages/contacts/index.test.ts
+++ b/web/packages/contacts/index.test.ts
@@ -1,5 +1,7 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
+const session = {};
+
beforeEach(() => {
vi.resetModules();
vi.restoreAllMocks();
@@ -11,9 +13,7 @@ interface SetupOptions {
diff?: object[];
getProfilePictureError?: Error;
getProfilePictureBytes?: Uint8Array;
- rootKeySource?: "cache" | "unresolved";
- wrappedRootContactKey?: { encryptedKey: string; header: string };
- currentWrappedRootContactKey?: { encryptedKey: string; header: string };
+ rootKeyResolved?: boolean;
}
const setupContactsModule = async (options: SetupOptions = {}) => {
@@ -32,17 +32,11 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
const info = vi.fn();
const warn = vi.fn();
const error = vi.fn();
- const updateAuthToken = vi.fn();
- let isRootKeyResolved = options.rootKeySource !== "unresolved";
- const currentWrappedRootContactKey = vi.fn(() =>
- isRootKeyResolved
- ? (options.currentWrappedRootContactKey ??
- options.wrappedRootContactKey ?? {
- encryptedKey: "wrapped-root-key",
- header: "wrapped-header",
- })
- : undefined,
- );
+ let isRootKeyResolved = options.rootKeyResolved ?? true;
+ const wrappedRootContactKey = {
+ encryptedKey: "wrapped-root-key",
+ header: "wrapped-header",
+ };
const diff = options.diff ?? [
{
id: "ct_1",
@@ -59,12 +53,25 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
.fn()
.mockImplementationOnce(() => {
if (diff.length > 0) isRootKeyResolved = true;
- return Promise.resolve(diff);
+ return Promise.resolve({
+ records: diff,
+ wrappedRootContactKey: isRootKeyResolved
+ ? wrappedRootContactKey
+ : undefined,
+ });
})
- .mockResolvedValueOnce([]);
+ .mockResolvedValueOnce({
+ records: [],
+ wrappedRootContactKey: isRootKeyResolved
+ ? wrappedRootContactKey
+ : undefined,
+ });
const getProfilePicture = vi.fn(() => {
if (options.getProfilePictureBytes) {
- return Promise.resolve(options.getProfilePictureBytes);
+ return Promise.resolve({
+ bytes: options.getProfilePictureBytes,
+ wrappedRootContactKey,
+ });
}
return Promise.reject(
options.getProfilePictureError ?? new Error("boom"),
@@ -77,33 +84,12 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
default: { info, warn, error },
logToDisk: vi.fn(),
}));
- vi.doMock("ente-accounts/services/session-storage", () => ({
- masterKeyFromSession: vi.fn(() => "MASTER_KEY"),
- }));
- vi.doMock("ente-accounts/services/user", () => ({
- ensureLocalUser: vi.fn(() => ({ id: 101 })),
- }));
- vi.doMock("ente-base/app", () => ({
- appName: "photos",
- clientPackageName: "io.ente.photos.web",
- desktopAppVersion: undefined,
- isDesktop: false,
- }));
const contacts = await import("./index");
- const openContacts = () =>
- Promise.resolve({
- updateAuthToken,
- currentWrappedRootContactKey,
- getDiff,
- getProfilePicture,
- });
return {
contacts,
- openContacts,
setKV,
savedAuthToken,
- updateAuthToken,
getDiff,
getProfilePicture,
info,
@@ -111,12 +97,15 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
};
describe("ensureContactsReady", () => {
- test("does not persist auth token or master key in contacts kv", async () => {
- const { contacts, openContacts, setKV } = await setupContactsModule();
+ test("does not persist the auth token in contacts kv", async () => {
+ const { contacts, getDiff, getProfilePicture, setKV } =
+ await setupContactsModule();
await contacts.ensureContactsReady(
- { userID: 101, masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST" },
- openContacts,
+ 101,
+ session,
+ getDiff,
+ getProfilePicture,
);
const persisted = setKV.mock.calls
@@ -126,7 +115,6 @@ describe("ensureContactsReady", () => {
expect(persisted).toContain("contacts/");
expect(persisted).toContain("wrapped-root-key");
expect(persisted).toContain("Set");
- expect(persisted).not.toContain("MASTER_KEY_SHOULD_NOT_PERSIST");
expect(persisted).not.toContain("auth-token-secret");
const resolved = contacts.resolveContactDisplay({ userID: 101 });
@@ -134,14 +122,17 @@ describe("ensureContactsReady", () => {
});
test("does not persist an unresolved wrapped root contact key", async () => {
- const { contacts, openContacts, setKV } = await setupContactsModule({
- rootKeySource: "unresolved",
- diff: [],
- });
+ const { contacts, getDiff, getProfilePicture, setKV } =
+ await setupContactsModule({
+ rootKeyResolved: false,
+ diff: [],
+ });
await contacts.ensureContactsReady(
- { userID: 101, masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST" },
- openContacts,
+ 101,
+ session,
+ getDiff,
+ getProfilePicture,
);
const persisted = setKV.mock.calls
@@ -152,13 +143,14 @@ describe("ensureContactsReady", () => {
});
test("persists a resolved wrapped root contact key after non-empty diff", async () => {
- const { contacts, openContacts, setKV } = await setupContactsModule({
- rootKeySource: "unresolved",
- });
+ const { contacts, getDiff, getProfilePicture, setKV } =
+ await setupContactsModule({ rootKeyResolved: false });
await contacts.ensureContactsReady(
- { userID: 101, masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST" },
- openContacts,
+ 101,
+ session,
+ getDiff,
+ getProfilePicture,
);
const persisted = setKV.mock.calls
@@ -171,14 +163,16 @@ describe("ensureContactsReady", () => {
describe("profile picture loading", () => {
test("negative-caches failed profile picture fetches and logs at info", async () => {
- const { contacts, getProfilePicture, info, openContacts } =
+ const { contacts, getDiff, getProfilePicture, info } =
await setupContactsModule({
getProfilePictureError: new Error("network failure"),
});
await contacts.ensureContactsReady(
- { userID: 101, masterKeyB64: "ignored" },
- openContacts,
+ 101,
+ session,
+ getDiff,
+ getProfilePicture,
);
await contacts.__testing.preloadResolvedContactAvatar({
@@ -205,13 +199,14 @@ describe("profile picture loading", () => {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00,
0x0d,
]);
- const { contacts, openContacts } = await setupContactsModule({
- getProfilePictureBytes: pngBytes,
- });
+ const { contacts, getDiff, getProfilePicture } =
+ await setupContactsModule({ getProfilePictureBytes: pngBytes });
await contacts.ensureContactsReady(
- { userID: 101, masterKeyB64: "ignored" },
- openContacts,
+ 101,
+ session,
+ getDiff,
+ getProfilePicture,
);
await contacts.__testing.preloadResolvedContactAvatar({ userID: 101 });
@@ -223,26 +218,33 @@ describe("profile picture loading", () => {
describe("retry after warm-up failure", () => {
test("recovers from a transient failure with bounded background retry", async () => {
vi.useFakeTimers();
- const { contacts, getDiff, openContacts } = await setupContactsModule();
+ const { contacts, getDiff, getProfilePicture } =
+ await setupContactsModule();
getDiff.mockReset();
getDiff
.mockRejectedValueOnce(new Error("transient"))
- .mockResolvedValueOnce([
- {
- id: "ct_1",
- contactUserId: 101,
- email: "[email protected]",
- name: "Set",
- profilePictureAttachmentID: "ua_1",
- isDeleted: false,
- updatedAt: 1,
- },
- ])
- .mockResolvedValueOnce([]);
+ .mockResolvedValueOnce({
+ records: [
+ {
+ id: "ct_1",
+ contactUserId: 101,
+ email: "[email protected]",
+ name: "Set",
+ profilePictureAttachmentID: "ua_1",
+ isDeleted: false,
+ updatedAt: 1,
+ },
+ ],
+ })
+ .mockResolvedValueOnce({
+ records: [],
+ });
const ready = contacts.ensureContactsReady(
- { userID: 101, masterKeyB64: "ignored" },
- openContacts,
+ 101,
+ session,
+ getDiff,
+ getProfilePicture,
);
await vi.advanceTimersByTimeAsync(10_001);
await expect(ready).resolves.toBeUndefined();
@@ -252,14 +254,17 @@ describe("retry after warm-up failure", () => {
test("stops after bounded background retries keep failing", async () => {
vi.useFakeTimers();
- const { contacts, getDiff, openContacts } = await setupContactsModule();
+ const { contacts, getDiff, getProfilePicture } =
+ await setupContactsModule();
getDiff.mockReset();
getDiff.mockRejectedValue(new Error("down"));
const ready = expect(
contacts.ensureContactsReady(
- { userID: 101, masterKeyB64: "ignored" },
- openContacts,
+ 101,
+ session,
+ getDiff,
+ getProfilePicture,
),
).rejects.toThrow("down");
@@ -273,15 +278,10 @@ describe("retry after warm-up failure", () => {
expect(getDiff).toHaveBeenCalledTimes(4);
});
- test("stale retry does not update a newer generation context token", async () => {
+ test("a stale retry does not update a newer session", async () => {
vi.useFakeTimers();
- const {
- contacts,
- savedAuthToken,
- updateAuthToken,
- getDiff,
- openContacts,
- } = await setupContactsModule();
+ const { contacts, savedAuthToken, getDiff, getProfilePicture } =
+ await setupContactsModule();
savedAuthToken
.mockReturnValueOnce("old-token")
.mockReturnValueOnce(undefined)
@@ -289,31 +289,35 @@ describe("retry after warm-up failure", () => {
getDiff.mockReset();
getDiff
.mockRejectedValueOnce(new Error("transient"))
- .mockResolvedValueOnce([])
- .mockResolvedValueOnce([]);
+ .mockResolvedValue({ records: [] });
const staleReady = contacts.ensureContactsReady(
- { userID: 101, masterKeyB64: "old-master-key" },
- openContacts,
+ 101,
+ session,
+ getDiff,
+ getProfilePicture,
);
await vi.advanceTimersByTimeAsync(0);
expect(getDiff).toHaveBeenCalledTimes(1);
await contacts.ensureContactsReady(
- { userID: 101, masterKeyB64: "clearing-master-key" },
- openContacts,
+ 101,
+ session,
+ getDiff,
+ getProfilePicture,
);
expect(getDiff).toHaveBeenCalledTimes(1);
await contacts.ensureContactsReady(
- { userID: 101, masterKeyB64: "new-master-key" },
- openContacts,
+ 101,
+ session,
+ getDiff,
+ getProfilePicture,
);
expect(getDiff).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(10_001);
await expect(staleReady).resolves.toBeUndefined();
- expect(updateAuthToken).not.toHaveBeenCalled();
expect(getDiff).toHaveBeenCalledTimes(2);
});
});
diff --git a/web/packages/contacts/index.ts b/web/packages/contacts/index.ts
index 5afa205eb6..a7619d9cb3 100644
--- a/web/packages/contacts/index.ts
+++ b/web/packages/contacts/index.ts
@@ -1,4 +1,3 @@
-import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
import { ensureArrayBufferBacked } from "ente-base/bytes";
import { retryAsyncOperation } from "ente-base/http";
import log from "ente-base/log";
@@ -55,50 +54,28 @@ export interface RemoteContactRecord {
updatedAt: number;
}
-export interface ContactsReadyInput {
- userID: number;
- masterKeyB64: string;
+interface ContactsDiffOutput {
+ records: RemoteContactRecord[];
+ wrappedRootContactKey?: WrappedRootContactKey;
}
-type ContactsSessionInput = ContactsReadyInput & {
- sessionKey: string;
- baseURL: string;
- authToken: string;
- generation: number;
- openContacts: OpenContacts;
-};
-
-export interface ContactsClient {
- updateAuthToken: (authToken: string) => void;
- currentWrappedRootContactKey: () => WrappedRootContactKey | undefined;
- getDiff: (
- sinceTime: number,
- limit: number,
- ) => Promise<RemoteContactRecord[]>;
- getProfilePicture: (contactID: string) => Promise<Uint8Array>;
+interface ProfilePictureOutput {
+ bytes: Uint8Array;
+ wrappedRootContactKey?: WrappedRootContactKey;
}
-export interface OpenContactsInput {
- baseUrl: string;
- authToken: string;
- userId: number;
- masterKeyB64: string;
- cachedWrappedRootContactKey?: WrappedRootContactKey;
- clientPackage?: string;
- clientVersion?: string;
-}
-
-export type OpenContacts = (
- input: OpenContactsInput,
-) => Promise<ContactsClient>;
+type LoadProfilePicture = (
+ wrappedRootContactKey: WrappedRootContactKey | undefined,
+ contactID: string,
+) => Promise<ProfilePictureOutput>;
interface ContactsState {
snapshot: ContactsDisplaySnapshot;
listeners: Set<() => void>;
currentSessionKey: string | undefined;
sessionGeneration: number;
- currentAuthToken: string | undefined;
- client: ContactsClient | undefined;
+ getProfilePicture: LoadProfilePicture | undefined;
+ wrappedRootContactKey: WrappedRootContactKey | undefined;
readyPromise: Promise<void> | undefined;
contactsByID: Map<string, ContactDisplayRecord>;
contactIDByUserID: Map<number, string>;
@@ -121,8 +98,8 @@ const state: ContactsState = {
listeners: new Set(),
currentSessionKey: undefined,
sessionGeneration: 0,
- currentAuthToken: undefined,
- client: undefined,
+ getProfilePicture: undefined,
+ wrappedRootContactKey: undefined,
readyPromise: undefined,
contactsByID: new Map(),
contactIDByUserID: new Map(),
@@ -167,8 +144,8 @@ const clearInMemoryState = () => {
for (const avatarURL of state.avatarURLByContactID.values()) {
URL.revokeObjectURL(avatarURL);
}
- state.client = undefined;
- state.currentAuthToken = undefined;
+ state.getProfilePicture = undefined;
+ state.wrappedRootContactKey = undefined;
state.readyPromise = undefined;
state.contactsByID = new Map();
state.contactIDByUserID = new Map();
@@ -330,90 +307,42 @@ const ensureSessionLoaded = async (sessionKey: string) =>
? state.sessionGeneration
: loadLocalSessionState(sessionKey);
-const ensureContactsClientOpen = async ({
- sessionKey,
- baseURL,
- authToken,
- userID,
- masterKeyB64,
- generation,
- openContacts,
-}: ContactsSessionInput) => {
+const syncContacts = async (
+ sessionKey: string,
+ generation: number,
+ getDiff: (
+ wrappedRootContactKey: WrappedRootContactKey | undefined,
+ sinceTime: number,
+ limit: number,
+ ) => Promise<ContactsDiffOutput>,
+) => {
if (!isCurrentSession(sessionKey, generation)) {
return;
}
-
- let client = state.client;
-
- if (!client) {
- const cachedWrappedRootContactKey =
- await savedWrappedRootContactKey(sessionKey);
- if (!isCurrentSession(sessionKey, generation)) {
- return;
- }
- const openedClient = await openContacts({
- baseUrl: baseURL,
- authToken,
- userId: userID,
- masterKeyB64,
- cachedWrappedRootContactKey,
- clientPackage: clientPackageName,
- clientVersion: isDesktop ? desktopAppVersion : undefined,
- });
- if (!isCurrentSession(sessionKey, generation)) {
- return;
- }
- state.client = openedClient;
- client = openedClient;
- const wrappedRootContactKey = client.currentWrappedRootContactKey();
- if (wrappedRootContactKey) {
- await saveWrappedRootContactKey(sessionKey, wrappedRootContactKey);
- if (!isCurrentSession(sessionKey, generation)) {
- return;
- }
- }
- } else if (state.currentAuthToken !== authToken) {
- client.updateAuthToken(authToken);
- }
-
+ const cachedWrappedRootContactKey =
+ state.wrappedRootContactKey ??
+ (await savedWrappedRootContactKey(sessionKey));
if (!isCurrentSession(sessionKey, generation)) {
return;
}
-
- state.currentAuthToken = authToken;
- return client;
-};
-
-const syncContacts = async ({
- sessionKey,
- baseURL,
- authToken,
- userID,
- masterKeyB64,
- generation,
- openContacts,
-}: ContactsSessionInput) => {
- const client = await ensureContactsClientOpen({
- sessionKey,
- baseURL,
- authToken,
- userID,
- masterKeyB64,
- generation,
- openContacts,
- });
- if (!client) {
- return;
- }
+ state.wrappedRootContactKey = cachedWrappedRootContactKey;
let sinceTime = (await savedContactsSinceTime(sessionKey)) ?? 0;
let didChange = false;
while (true) {
- const diff = await client.getDiff(sinceTime, CONTACT_DIFF_LIMIT);
+ const output = await getDiff(
+ state.wrappedRootContactKey,
+ sinceTime,
+ CONTACT_DIFF_LIMIT,
+ );
if (!isCurrentSession(sessionKey, generation)) {
return;
}
+ if (output.wrappedRootContactKey) {
+ state.wrappedRootContactKey = output.wrappedRootContactKey;
+ }
+ const diff = output.records;
if (diff.length === 0) {
break;
}
@@ -433,7 +362,7 @@ const syncContacts = async ({
if (!isCurrentSession(sessionKey, generation)) {
return;
}
- const wrappedRootContactKey = client.currentWrappedRootContactKey();
+ const wrappedRootContactKey = state.wrappedRootContactKey;
if (wrappedRootContactKey) {
await saveWrappedRootContactKey(sessionKey, wrappedRootContactKey);
if (!isCurrentSession(sessionKey, generation)) {
@@ -448,12 +377,22 @@ const syncContacts = async ({
}
};
-export const ensureContactsReady = async (
- { userID, masterKeyB64 }: ContactsReadyInput,
- openContacts: OpenContacts,
+export const ensureContactsReady = async <Session>(
+ userID: number,
+ session: Session,
+ getDiff: (
+ session: Session,
+ wrappedRootContactKey: WrappedRootContactKey | undefined,
+ sinceTime: number,
+ limit: number,
+ ) => Promise<ContactsDiffOutput>,
+ getProfilePicture: (
+ session: Session,
+ wrappedRootContactKey: WrappedRootContactKey | undefined,
+ contactID: string,
+ ) => Promise<ProfilePictureOutput>,
) => {
- const authToken = await savedAuthToken();
- if (!authToken) {
+ if (!(await savedAuthToken())) {
state.sessionGeneration += 1;
state.currentSessionKey = undefined;
clearInMemoryState();
@@ -473,17 +412,13 @@ export const ensureContactsReady = async (
return state.readyPromise;
}
+ state.getProfilePicture = (key, contactID) =>
+ getProfilePicture(session, key, contactID);
const readyPromise = retryAsyncOperation(
() =>
- syncContacts({
- sessionKey,
- baseURL,
- authToken,
- userID,
- masterKeyB64,
- generation,
- openContacts,
- }),
+ syncContacts(sessionKey, generation, (key, sinceTime, limit) =>
+ getDiff(session, key, sinceTime, limit),
+ ),
{ retryProfile: "background" },
).finally(() => {
if (state.readyPromise === readyPromise) {
@@ -545,10 +480,14 @@ const inferImageMimeType = (bytes: Uint8Array) => {
const ensureProfilePictureLoaded = async (contactID: string) => {
const contact = state.contactsByID.get(contactID);
- const client = state.client;
+ const getProfilePicture = state.getProfilePicture;
const sessionKey = state.currentSessionKey;
const generation = state.sessionGeneration;
- if (!contact?.profilePictureAttachmentID || !client || !sessionKey) {
+ if (
+ !contact?.profilePictureAttachmentID ||
+ !getProfilePicture ||
+ !sessionKey
+ ) {
return;
}
@@ -567,15 +506,18 @@ const ensureProfilePictureLoaded = async (contactID: string) => {
return;
}
- const load = client
- .getProfilePicture(contactID)
- .then((bytes: Uint8Array) => {
+ const load = getProfilePicture(state.wrappedRootContactKey, contactID)
+ .then((output) => {
if (
!isCurrentSession(sessionKey, generation) ||
- state.client !== client
+ state.getProfilePicture !== getProfilePicture
) {
return;
}
+ if (output.wrappedRootContactKey) {
+ state.wrappedRootContactKey = output.wrappedRootContactKey;
+ }
+ const bytes = output.bytes;
const blob = new Blob([ensureArrayBufferBacked(bytes)], {
type: inferImageMimeType(bytes),
});
@@ -588,7 +530,7 @@ const ensureProfilePictureLoaded = async (contactID: string) => {
.catch((error: unknown) => {
if (
!isCurrentSession(sessionKey, generation) ||
- state.client !== client
+ state.getProfilePicture !== getProfilePicture
) {
return;
}
diff --git a/web/packages/wasm/locker/index.ts b/web/packages/wasm/locker/index.ts
index db24c45cfd..666245655f 100644
--- a/web/packages/wasm/locker/index.ts
+++ b/web/packages/wasm/locker/index.ts
@@ -3,12 +3,10 @@ interface WrappedRootContactKey {
header: string;
}
-interface OpenContactsInput {
+interface OpenSessionInput {
baseUrl: string;
authToken: string;
- userId: number;
masterKeyB64: string;
- cachedWrappedRootContactKey?: WrappedRootContactKey;
clientPackage?: string;
clientVersion?: string;
}
@@ -23,42 +21,57 @@ interface ContactRecord {
updatedAt: number;
}
-export const openContacts = async ({
+interface ContactsDiffOutput {
+ records: ContactRecord[];
+ wrappedRootContactKey?: WrappedRootContactKey;
+}
+
+interface ProfilePictureOutput {
+ bytes: Uint8Array;
+ wrappedRootContactKey?: WrappedRootContactKey;
+}
+
+const wasm = () => import("./pkg/ente_locker_wasm");
+
+export type Session = import("./pkg/ente_locker_wasm").Session;
+
+export const openSession = async ({
baseUrl,
authToken,
- userId,
masterKeyB64,
- cachedWrappedRootContactKey,
clientPackage,
clientVersion,
-}: OpenContactsInput) => {
- const wasm = await import("./pkg/ente_locker_wasm");
- const session = wasm.openSession(
+}: OpenSessionInput): Promise<Session> =>
+ (await wasm()).openSession(
baseUrl,
authToken,
masterKeyB64,
clientPackage,
clientVersion,
);
- const client = wasm.openContacts(
+
+export const contactsGetDiff = async (
+ session: Session,
+ wrappedRootContactKey: WrappedRootContactKey | undefined,
+ sinceTime: number,
+ limit: number,
+): Promise<ContactsDiffOutput> =>
+ (await wasm()).contactsGetDiff(
session,
- BigInt(userId),
- cachedWrappedRootContactKey?.encryptedKey,
- cachedWrappedRootContactKey?.header,
+ wrappedRootContactKey?.encryptedKey,
+ wrappedRootContactKey?.header,
+ BigInt(sinceTime),
+ limit,
);
- return {
- updateAuthToken: (authToken: string) =>
- session.updateAuthToken(authToken),
- currentWrappedRootContactKey: () =>
- client.currentWrappedRootContactKey() as
- | WrappedRootContactKey
- | undefined,
- getDiff: (sinceTime: number, limit: number) =>
- client.getDiff(BigInt(sinceTime), limit) as Promise<
- ContactRecord[]
- >,
- getProfilePicture: (contactID: string) =>
- client.getProfilePicture(contactID),
- };
-};
+export const contactsGetProfilePicture = async (
+ session: Session,
+ wrappedRootContactKey: WrappedRootContactKey | undefined,
+ contactID: string,
+): Promise<ProfilePictureOutput> =>
+ (await wasm()).contactsGetProfilePicture(
+ session,
+ wrappedRootContactKey?.encryptedKey,
+ wrappedRootContactKey?.header,
+ contactID,
+ );
diff --git a/web/packages/wasm/photos/index.ts b/web/packages/wasm/photos/index.ts
index 552e15f3e1..4cc6843bf0 100644
--- a/web/packages/wasm/photos/index.ts
+++ b/web/packages/wasm/photos/index.ts
@@ -3,12 +3,10 @@ interface WrappedRootContactKey {
header: string;
}
-interface OpenContactsInput {
+interface OpenSessionInput {
baseUrl: string;
authToken: string;
- userId: number;
masterKeyB64: string;
- cachedWrappedRootContactKey?: WrappedRootContactKey;
clientPackage?: string;
clientVersion?: string;
}
@@ -23,42 +21,57 @@ interface ContactRecord {
updatedAt: number;
}
-export const openContacts = async ({
+interface ContactsDiffOutput {
+ records: ContactRecord[];
+ wrappedRootContactKey?: WrappedRootContactKey;
+}
+
+interface ProfilePictureOutput {
+ bytes: Uint8Array;
+ wrappedRootContactKey?: WrappedRootContactKey;
+}
+
+const wasm = () => import("./pkg/ente_photos_wasm");
+
+export type Session = import("./pkg/ente_photos_wasm").Session;
+
+export const openSession = async ({
baseUrl,
authToken,
- userId,
masterKeyB64,
- cachedWrappedRootContactKey,
clientPackage,
clientVersion,
-}: OpenContactsInput) => {
- const wasm = await import("./pkg/ente_photos_wasm");
- const session = wasm.openSession(
+}: OpenSessionInput): Promise<Session> =>
+ (await wasm()).openSession(
baseUrl,
authToken,
masterKeyB64,
clientPackage,
clientVersion,
);
- const client = wasm.openContacts(
+
+export const contactsGetDiff = async (
+ session: Session,
+ wrappedRootContactKey: WrappedRootContactKey | undefined,
+ sinceTime: number,
+ limit: number,
+): Promise<ContactsDiffOutput> =>
+ (await wasm()).contactsGetDiff(
session,
- BigInt(userId),
- cachedWrappedRootContactKey?.encryptedKey,
- cachedWrappedRootContactKey?.header,
+ wrappedRootContactKey?.encryptedKey,
+ wrappedRootContactKey?.header,
+ BigInt(sinceTime),
+ limit,
);
- return {
- updateAuthToken: (authToken: string) =>
- session.updateAuthToken(authToken),
- currentWrappedRootContactKey: () =>
- client.currentWrappedRootContactKey() as
- | WrappedRootContactKey
- | undefined,
- getDiff: (sinceTime: number, limit: number) =>
- client.getDiff(BigInt(sinceTime), limit) as Promise<
- ContactRecord[]
- >,
- getProfilePicture: (contactID: string) =>
- client.getProfilePicture(contactID),
- };
-};
+export const contactsGetProfilePicture = async (
+ session: Session,
+ wrappedRootContactKey: WrappedRootContactKey | undefined,
+ contactID: string,
+): Promise<ProfilePictureOutput> =>
+ (await wasm()).contactsGetProfilePicture(
+ session,
+ wrappedRootContactKey?.encryptedKey,
+ wrappedRootContactKey?.header,
+ contactID,
+ );