Skip to content

armgit / ente

Public Imported from GitHub
0

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

Move mobile Legacy contact management to Rust

Manav Rathi46ea948b2784
diff --git a/mobile/apps/locker/lib/main.dart b/mobile/apps/locker/lib/main.dart
index 83dfcf1f7f..b0d06c25c5 100644
--- a/mobile/apps/locker/lib/main.dart
+++ b/mobile/apps/locker/lib/main.dart
@@ -219,10 +219,7 @@ Future<void> _init(bool bool, {String? via}) async {
);
await UpdateService.instance.init(preferences, packageInfo);
await TrashService.instance.init(preferences);
- await EmergencyContactService.instance.init(
- UserService.instance,
- Configuration.instance,
- );
+ EmergencyContactService.instance.init(Configuration.instance);
await LockerContactsDisplayService.init(preferences: preferences);
unawaited(cleanStaleLegacyKitShareFiles());
unawaited(
diff --git a/mobile/apps/locker/lib/services/legacy_api.dart b/mobile/apps/locker/lib/services/legacy_api.dart
new file mode 100644
index 0000000000..12e212330b
--- /dev/null
+++ b/mobile/apps/locker/lib/services/legacy_api.dart
@@ -0,0 +1,81 @@
+import "package:ente_frb/legacy.dart";
+import "package:ente_legacy/legacy_api.dart";
+import "package:locker/services/authenticated_session.dart";
+import "package:locker/src/rust/third_party/ente_frb_lib/legacy/contact.dart"
+ as contact;
+import "package:locker/src/rust/third_party/ente_frb_lib/legacy/kit.dart"
+ as kit;
+
+class LockerLegacyApi implements LegacyApi {
+ const LockerLegacyApi();
+
+ @override
+ Future<LegacyInfo> info() => contact.info(session: authenticatedSession());
+
+ @override
+ Future<void> addContact({
+ required String email,
+ required int recoveryNoticeInDays,
+ }) => contact.addContact(
+ session: authenticatedSession(),
+ email: email,
+ recoveryNoticeInDays: recoveryNoticeInDays,
+ );
+
+ @override
+ Future<void> updateContact({
+ required int userId,
+ required int emergencyContactId,
+ required LegacyContactState state,
+ }) => contact.updateContact(
+ session: authenticatedSession(),
+ userId: userId,
+ emergencyContactId: emergencyContactId,
+ state: state,
+ );
+
+ @override
+ Future<void> updateRecoveryNotice({
+ required int emergencyContactId,
+ required int recoveryNoticeInDays,
+ }) => contact.updateRecoveryNotice(
+ session: authenticatedSession(),
+ emergencyContactId: emergencyContactId,
+ recoveryNoticeInDays: recoveryNoticeInDays,
+ );
+
+ @override
+ Future<List<LegacyKit>> kits() => kit.kits(session: authenticatedSession());
+
+ @override
+ Future<LegacyKitCreateResult> createKit({
+ required List<String> partNames,
+ required int noticePeriodInHours,
+ }) => kit.createKit(
+ session: authenticatedSession(),
+ partNames: partNames,
+ noticePeriodInHours: noticePeriodInHours,
+ );
+
+ @override
+ Future<List<LegacyKitShare>> downloadKitShares({required String kitId}) =>
+ kit.downloadKitShares(session: authenticatedSession(), kitId: kitId);
+
+ @override
+ Future<void> updateKitRecoveryNotice({
+ required String kitId,
+ required int noticePeriodInHours,
+ }) => kit.updateKitRecoveryNotice(
+ session: authenticatedSession(),
+ kitId: kitId,
+ noticePeriodInHours: noticePeriodInHours,
+ );
+
+ @override
+ Future<void> blockKitRecovery({required String kitId}) =>
+ kit.blockKitRecovery(session: authenticatedSession(), kitId: kitId);
+
+ @override
+ Future<void> deleteKit({required String kitId}) =>
+ kit.deleteKit(session: authenticatedSession(), kitId: kitId);
+}
diff --git a/mobile/apps/locker/lib/ui/utils/legacy_utils.dart b/mobile/apps/locker/lib/ui/utils/legacy_utils.dart
index 80f92c1f22..51d98ce354 100644
--- a/mobile/apps/locker/lib/ui/utils/legacy_utils.dart
+++ b/mobile/apps/locker/lib/ui/utils/legacy_utils.dart
@@ -1,17 +1,15 @@
-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_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/src/rust/api/legacy.dart" as legacy;
+import "package:locker/services/legacy_api.dart";
import "package:logging/logging.dart";
+const _legacy = LockerLegacyApi();
+
final _logger = Logger("LegacyUtils");
Future<void> openLegacyPage(BuildContext context) async {
@@ -61,12 +59,7 @@ Future<void> _openLegacy(
context,
accountEmail: config.getEmail() ?? "",
isFirstLegacyKit: true,
- createKit: _createLegacyKit,
- getKits: _getLegacyKits,
- downloadShares: _downloadLegacyKitShares,
- updateRecoveryNotice: _updateLegacyKitRecoveryNotice,
- blockRecovery: _blockLegacyKitRecovery,
- deleteKit: _deleteLegacyKit,
+ legacy: _legacy,
authenticator: legacyKitAuthenticator,
);
return;
@@ -80,12 +73,7 @@ Future<void> _openLegacy(
builder: (BuildContext context) {
return EmergencyPage(
config: config,
- getLegacyKits: _getLegacyKits,
- createLegacyKit: _createLegacyKit,
- downloadLegacyKitShares: _downloadLegacyKitShares,
- updateLegacyKitRecoveryNotice: _updateLegacyKitRecoveryNotice,
- blockLegacyKitRecovery: _blockLegacyKitRecovery,
- deleteLegacyKit: _deleteLegacyKit,
+ legacy: _legacy,
legacyKitAuthenticator: legacyKitAuthenticator,
);
},
@@ -95,47 +83,13 @@ Future<void> _openLegacy(
Future<bool?> hasLegacyKit() async {
try {
- return (await _getLegacyKits()).isNotEmpty;
+ return (await _legacy.kits()).isNotEmpty;
} catch (e, s) {
_logger.warning("Failed to fetch legacy kits", e, s);
return null;
}
}
-Future<List<LegacyKit>> _getLegacyKits() =>
- legacy.kits(session: authenticatedSession());
-
-Future<LegacyKitCreateResult> _createLegacyKit(
- List<String> partNames,
- int noticePeriodInHours,
-) async {
- final result = await legacy.createKit(
- session: authenticatedSession(),
- partNames: partNames,
- noticePeriodInHours: noticePeriodInHours,
- );
- Bus.instance.fire(LegacyKitCreatedEvent());
- return result;
-}
-
-Future<List<LegacyKitShare>> _downloadLegacyKitShares(String kitId) =>
- legacy.downloadKitShares(session: authenticatedSession(), kitId: kitId);
-
-Future<void> _updateLegacyKitRecoveryNotice(
- String kitId,
- int noticePeriodInHours,
-) => legacy.updateKitRecoveryNotice(
- session: authenticatedSession(),
- kitId: kitId,
- noticePeriodInHours: noticePeriodInHours,
-);
-
-Future<void> _blockLegacyKitRecovery(String kitId) =>
- legacy.blockKitRecovery(session: authenticatedSession(), kitId: kitId);
-
-Future<void> _deleteLegacyKit(String kitId) =>
- legacy.deleteKit(session: authenticatedSession(), kitId: 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 3dec148cf3..ac97b2e652 100644
--- a/mobile/apps/photos/flutter_rust_bridge.yaml
+++ b/mobile/apps/photos/flutter_rust_bridge.yaml
@@ -1,5 +1,5 @@
rust_input: crate::api, ente-frb-lib
-rust_features: [ente-frb-lib/contacts]
+rust_features: ["ente-frb-lib/contacts,ente-frb-lib/legacy"]
rust_root: ../../../rust/bindings/frb/photos/
dart_output: lib/src/rust
dart_entrypoint_class_name: EntePhotosRust
diff --git a/mobile/apps/photos/lib/emergency/components/trusted_contact_sheet.dart b/mobile/apps/photos/lib/emergency/components/trusted_contact_sheet.dart
index dc89979a6d..459d63ffc3 100644
--- a/mobile/apps/photos/lib/emergency/components/trusted_contact_sheet.dart
+++ b/mobile/apps/photos/lib/emergency/components/trusted_contact_sheet.dart
@@ -8,7 +8,7 @@ import "package:photos/ui/components/buttons/button_widget_v2.dart";
Future<TrustedContactResult?> showTrustedContactSheet(
BuildContext context, {
- required EmergencyContact contact,
+ required LegacyContactRecord contact,
}) {
return showBaseBottomSheet<TrustedContactResult>(
context,
@@ -30,7 +30,7 @@ class TrustedContactResult {
}
class TrustedContactSheet extends StatefulWidget {
- final EmergencyContact contact;
+ final LegacyContactRecord contact;
const TrustedContactSheet({required this.contact, super.key});
diff --git a/mobile/apps/photos/lib/emergency/emergency_page.dart b/mobile/apps/photos/lib/emergency/emergency_page.dart
index 09de7de4a4..023ca4df8c 100644
--- a/mobile/apps/photos/lib/emergency/emergency_page.dart
+++ b/mobile/apps/photos/lib/emergency/emergency_page.dart
@@ -11,7 +11,10 @@ import "package:photos/emergency/emergency_service.dart";
import "package:photos/emergency/model.dart";
import "package:photos/emergency/other_contact_page.dart";
import "package:photos/emergency/select_contact_page.dart";
+import "package:photos/services/authenticated_session.dart";
import "package:photos/services/contacts/contact_identity_resolver.dart";
+import "package:photos/src/rust/third_party/ente_frb_lib/legacy/contact.dart"
+ as legacy;
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/components/alert_bottom_sheet.dart";
import "package:photos/ui/components/buttons/button_widget_v2.dart";
@@ -29,7 +32,7 @@ class EmergencyPage extends StatefulWidget {
}
class _EmergencyPageState extends State<EmergencyPage> {
- EmergencyInfo? info;
+ LegacyInfo? info;
@override
void initState() {
@@ -41,7 +44,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
Future<void> _fetchData() async {
try {
- final result = await EmergencyContactService.instance.getInfo();
+ final result = await legacy.info(session: authenticatedSession());
if (mounted) {
setState(() {
info = result;
@@ -58,9 +61,9 @@ class _EmergencyPageState extends State<EmergencyPage> {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
final l10n = context.strings;
- final List<EmergencyContact> othersTrustedContacts =
+ final List<LegacyContactRecord> othersTrustedContacts =
info?.othersEmergencyContact ?? [];
- final List<EmergencyContact> trustedContacts = info?.contacts ?? [];
+ final List<LegacyContactRecord> trustedContacts = info?.contacts ?? [];
return Scaffold(
backgroundColor: colorScheme.backgroundColour,
@@ -108,7 +111,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
final recoverSession = info!.recoverSessions[listIndex];
final isLastItem =
listIndex == info!.recoverSessions.length - 1;
- final emergencyUser = recoverSession.emergencyContact;
+ final emergencyUser = recoverSession.emergencyContact.asUser;
return _buildGroupedMenuItem(
listIndex: listIndex,
isLastItem: isLastItem,
@@ -149,7 +152,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
final listIndex = index - 1;
final contact = trustedContacts[listIndex];
final isLastItem = listIndex == trustedContacts.length - 1;
- final emergencyUser = contact.emergencyContact;
+ final emergencyUser = contact.emergencyContact.asUser;
return _buildGroupedMenuItem(
listIndex: listIndex,
isLastItem: isLastItem,
@@ -254,7 +257,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
final listIndex = index - 1;
final currentUser = othersTrustedContacts[listIndex];
final isLastItem = index == othersTrustedContacts.length;
- final emergencyUser = currentUser.user;
+ final emergencyUser = currentUser.user.asUser;
return _buildGroupedMenuItem(
listIndex: listIndex,
isLastItem: isLastItem,
@@ -348,7 +351,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
Future<void> showRevokeOrRemoveDialog(
BuildContext context,
- EmergencyContact contact,
+ LegacyContactRecord contact,
) async {
final actionResult = await showTrustedContactSheet(
context,
@@ -383,9 +386,11 @@ class _EmergencyPageState extends State<EmergencyPage> {
);
if (confirmed == true) {
- await EmergencyContactService.instance.updateContact(
- contact,
- ContactState.userRevokedContact,
+ await legacy.updateContact(
+ session: authenticatedSession(),
+ userId: contact.user.id,
+ emergencyContactId: contact.emergencyContact.id,
+ state: LegacyContactState.revoked,
);
info?.contacts.remove(contact);
if (mounted) {
@@ -403,33 +408,34 @@ class _EmergencyPageState extends State<EmergencyPage> {
}
try {
- final success = await EmergencyContactService.instance
- .updateRecoveryNotice(contact, selectedDays);
- if (success) {
- final updatedContact = contact.copyWith(
- recoveryNoticeInDays: selectedDays,
- );
- final index = info?.contacts.indexWhere(
- (element) =>
- element.user.id == contact.user.id &&
- element.emergencyContact.id == contact.emergencyContact.id,
+ await legacy.updateRecoveryNotice(
+ session: authenticatedSession(),
+ emergencyContactId: contact.emergencyContact.id,
+ recoveryNoticeInDays: selectedDays,
+ );
+ final updatedContact = contact.copyWith(
+ recoveryNoticeInDays: selectedDays,
+ );
+ final index = info?.contacts.indexWhere(
+ (element) =>
+ element.user.id == contact.user.id &&
+ element.emergencyContact.id == contact.emergencyContact.id,
+ );
+ if (index != null && index >= 0) {
+ info?.contacts[index] = updatedContact;
+ }
+ if (mounted) {
+ setState(() {});
+ }
+ } on LegacyError_ActiveRecoverySession {
+ if (mounted) {
+ if (!context.mounted) return;
+ await showAlertBottomSheet(
+ context,
+ title: context.strings.cannotUpdateRecoveryTime,
+ message: context.strings.cannotUpdateRecoveryTimeMessage,
+ assetPath: "assets/warning-grey.png",
);
- if (index != null && index >= 0) {
- info?.contacts[index] = updatedContact;
- }
- if (mounted) {
- setState(() {});
- }
- } else {
- if (mounted) {
- if (!context.mounted) return;
- await showAlertBottomSheet(
- context,
- title: context.strings.cannotUpdateRecoveryTime,
- message: context.strings.cannotUpdateRecoveryTimeMessage,
- assetPath: "assets/warning-grey.png",
- );
- }
}
} catch (e) {
if (mounted) {
@@ -441,7 +447,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
Future<void> showAcceptOrDeclineDialog(
BuildContext context,
- EmergencyContact contact,
+ LegacyContactRecord contact,
) async {
final result = await showEmailActionSheet<String>(
context,
@@ -464,12 +470,14 @@ class _EmergencyPageState extends State<EmergencyPage> {
);
if (result == "accept") {
- await EmergencyContactService.instance.updateContact(
- contact,
- ContactState.contactAccepted,
+ await legacy.updateContact(
+ session: authenticatedSession(),
+ userId: contact.user.id,
+ emergencyContactId: contact.emergencyContact.id,
+ state: LegacyContactState.accepted,
);
final updatedContact = contact.copyWith(
- state: ContactState.contactAccepted,
+ state: LegacyContactState.accepted,
);
info?.othersEmergencyContact.remove(contact);
info?.othersEmergencyContact.add(updatedContact);
@@ -480,9 +488,11 @@ class _EmergencyPageState extends State<EmergencyPage> {
}
if (result == "decline") {
- await EmergencyContactService.instance.updateContact(
- contact,
- ContactState.contactDenied,
+ await legacy.updateContact(
+ session: authenticatedSession(),
+ userId: contact.user.id,
+ emergencyContactId: contact.emergencyContact.id,
+ state: LegacyContactState.contactDenied,
);
info?.othersEmergencyContact.remove(contact);
if (mounted) {
@@ -491,7 +501,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
}
}
- Future<void> showRejectRecoveryDialog(RecoverySessions session) async {
+ Future<void> showRejectRecoveryDialog(LegacyRecoverySession session) async {
final emergencyContactEmail = session.emergencyContact.email;
final confirmed = await showEmailActionSheet<bool>(
diff --git a/mobile/apps/photos/lib/emergency/emergency_service.dart b/mobile/apps/photos/lib/emergency/emergency_service.dart
index 9f99381f9c..0f0f296a29 100644
--- a/mobile/apps/photos/lib/emergency/emergency_service.dart
+++ b/mobile/apps/photos/lib/emergency/emergency_service.dart
@@ -2,22 +2,15 @@ import "dart:convert";
import "dart:math";
import "dart:typed_data";
-import "package:dio/dio.dart";
import "package:ente_crypto/ente_crypto.dart";
-import "package:ente_strings/ente_strings.dart";
-import "package:flutter/cupertino.dart";
+import "package:ente_frb/legacy.dart";
import "package:logging/logging.dart";
import "package:photos/core/configuration.dart";
-import "package:photos/emergency/model.dart";
import "package:photos/gateways/emergency/emergency_gateway.dart";
import "package:photos/gateways/users/models/key_attributes.dart";
import "package:photos/gateways/users/models/set_keys_request.dart";
import "package:photos/gateways/users/models/srp.dart";
import "package:photos/service_locator.dart";
-import "package:photos/services/account/user_service.dart";
-import "package:photos/ui/common/user_dialogs.dart";
-import "package:photos/ui/components/alert_bottom_sheet.dart";
-import "package:photos/utils/email_util.dart";
import "package:pointycastle/pointycastle.dart";
import "package:pointycastle/random/fortuna_random.dart";
import "package:pointycastle/srp/srp6_client.dart";
@@ -27,112 +20,19 @@ import "package:pointycastle/srp/srp6_verifier_generator.dart";
import "package:uuid/uuid.dart";
class EmergencyContactService {
- late UserService _userService;
late Configuration _config;
late final Logger _logger = Logger("EmergencyContactService");
EmergencyGateway get _gateway => emergencyGateway;
EmergencyContactService._privateConstructor() {
- _userService = UserService.instance;
_config = Configuration.instance;
}
static final EmergencyContactService instance =
EmergencyContactService._privateConstructor();
- Future<bool> addContact(
- BuildContext? context,
- String email, {
- int recoveryNoticeInDays = 30,
- }) async {
- if (!isValidEmail(email)) {
- if (context == null || !context.mounted) return false;
- await showAlertBottomSheet(
- context,
- title: context.strings.letsTryThatAgain,
- message: context.strings.enterValidEmail,
- assetPath: "assets/warning-grey.png",
- );
- return false;
- } else if (email.trim() == Configuration.instance.getEmail()) {
- if (context == null || !context.mounted) return false;
- await showAlertBottomSheet(
- context,
- title: context.strings.oops,
- message: context.strings.youCannotShareWithYourself,
- assetPath: "assets/warning-grey.png",
- );
- return false;
- }
- final String? publicKey = await _userService.getPublicKey(email);
- if (publicKey == null) {
- if (context == null || !context.mounted) return false;
- await showInviteDialog(context, email);
- return false;
- }
- final Uint8List recoveryKey = Configuration.instance.getRecoveryKey();
- final encryptedKey = CryptoUtil.sealSync(
- recoveryKey,
- CryptoUtil.base642bin(publicKey),
- );
- await _gateway.addContact(
- email: email.trim(),
- encryptedKey: CryptoUtil.bin2base64(encryptedKey),
- recoveryNoticeInDays: recoveryNoticeInDays,
- );
- return true;
- }
-
- Future<EmergencyInfo> getInfo() async {
- try {
- return await _gateway.getInfo();
- } catch (e, s) {
- Logger("EmergencyContact").severe('failed to get info', e, s);
- rethrow;
- }
- }
-
- Future<void> updateContact(
- EmergencyContact contact,
- ContactState state,
- ) async {
- try {
- await _gateway.updateState(
- userID: contact.user.id,
- emergencyContactID: contact.emergencyContact.id,
- state: state.stringValue,
- );
- } catch (e, s) {
- Logger("EmergencyContact").severe('failed to update contact', e, s);
- rethrow;
- }
- }
-
- Future<bool> updateRecoveryNotice(
- EmergencyContact contact,
- int recoveryNoticeInDays,
- ) async {
- try {
- await _gateway.updateRecoveryNotice(
- emergencyContactID: contact.emergencyContact.id,
- recoveryNoticeInDays: recoveryNoticeInDays,
- );
- return true;
- } on DioException catch (e) {
- if (e.response?.statusCode == 400 &&
- e.response?.data?["code"] == "ACTIVE_RECOVERY_SESSION") {
- return false;
- }
- _logger.severe("failed to update recovery notice", e);
- rethrow;
- } catch (e, s) {
- _logger.severe("failed to update recovery notice", e, s);
- rethrow;
- }
- }
-
- Future<void> startRecovery(EmergencyContact contact) async {
+ Future<void> startRecovery(LegacyContactRecord contact) async {
try {
await _gateway.startRecovery(
userID: contact.user.id,
@@ -144,7 +44,7 @@ class EmergencyContactService {
}
}
- Future<void> stopRecovery(RecoverySessions session) async {
+ Future<void> stopRecovery(LegacyRecoverySession session) async {
try {
await _gateway.stopRecovery(
userID: session.user.id,
@@ -157,7 +57,7 @@ class EmergencyContactService {
}
}
- Future<void> rejectRecovery(RecoverySessions session) async {
+ Future<void> rejectRecovery(LegacyRecoverySession session) async {
try {
await _gateway.rejectRecovery(
userID: session.user.id,
@@ -170,7 +70,7 @@ class EmergencyContactService {
}
}
- Future<void> approveRecovery(RecoverySessions session) async {
+ Future<void> approveRecovery(LegacyRecoverySession session) async {
try {
await _gateway.approveRecovery(
userID: session.user.id,
@@ -184,7 +84,7 @@ class EmergencyContactService {
}
Future<(String, KeyAttributes)> getRecoveryInfo(
- RecoverySessions sessions,
+ LegacyRecoverySession sessions,
) async {
try {
final (encryptedKey, keyAttributes) = await _gateway.getRecoveryInfo(
@@ -206,7 +106,7 @@ class EmergencyContactService {
Future<void> changePasswordForOther(
Uint8List loginKey,
SetKeysRequest setKeysRequest,
- RecoverySessions recoverySessions,
+ LegacyRecoverySession recoverySessions,
) async {
try {
final SRP6GroupParameters kDefaultSrpGroup =
diff --git a/mobile/apps/photos/lib/emergency/model.dart b/mobile/apps/photos/lib/emergency/model.dart
index 5568165f4d..e33b00b2fc 100644
--- a/mobile/apps/photos/lib/emergency/model.dart
+++ b/mobile/apps/photos/lib/emergency/model.dart
@@ -1,145 +1,22 @@
+import "package:ente_frb/legacy.dart";
import "package:photos/models/api/collection/user.dart";
-enum ContactState {
- userInvitedContact,
- userRevokedContact,
- contactAccepted,
- contactLeft,
- contactDenied,
- unknown,
-}
-
-extension ContactStateExtension on ContactState {
- String get stringValue {
- switch (this) {
- case ContactState.userInvitedContact:
- return "INVITED";
- case ContactState.userRevokedContact:
- return "REVOKED";
- case ContactState.contactAccepted:
- return "ACCEPTED";
- case ContactState.contactLeft:
- return "CONTACT_LEFT";
- case ContactState.contactDenied:
- return "CONTACT_DENIED";
- default:
- return "UNKNOWN";
- }
- }
-
- static ContactState fromString(String value) {
- switch (value) {
- case "INVITED":
- return ContactState.userInvitedContact;
- case "REVOKED":
- return ContactState.userRevokedContact;
- case "ACCEPTED":
- return ContactState.contactAccepted;
- case "CONTACT_LEFT":
- return ContactState.contactLeft;
- case "CONTACT_DENIED":
- return ContactState.contactDenied;
- default:
- return ContactState.unknown;
- }
- }
-}
-
-class EmergencyContact {
- final User user;
- final User emergencyContact;
- final ContactState state;
- final int recoveryNoticeInDays;
+export "package:ente_frb/legacy.dart";
- EmergencyContact(
- this.user,
- this.emergencyContact,
- this.state,
- this.recoveryNoticeInDays,
- );
+extension LegacyContactExtension on LegacyContactRecord {
+ bool isPendingInvite() => state == LegacyContactState.invited;
- EmergencyContact copyWith({
- User? user,
- User? emergencyContact,
- ContactState? state,
+ LegacyContactRecord copyWith({
+ LegacyContactState? state,
int? recoveryNoticeInDays,
- }) {
- return EmergencyContact(
- user ?? this.user,
- emergencyContact ?? this.emergencyContact,
- state ?? this.state,
- recoveryNoticeInDays ?? this.recoveryNoticeInDays,
- );
- }
-
- EmergencyContact.fromJson(Map<String, dynamic> json)
- : user = User.fromMap(json['user']),
- emergencyContact = User.fromMap(json['emergencyContact']),
- state = ContactStateExtension.fromString(json['state'] as String),
- recoveryNoticeInDays = json['recoveryNoticeInDays'];
-
- bool isCurrentUserContact(int userID) {
- return user.id == userID;
- }
-
- bool isPendingInvite() {
- return state == ContactState.userInvitedContact;
- }
-}
-
-class EmergencyInfo {
- final List<EmergencyContact> contacts;
-
- final List<RecoverySessions> recoverSessions;
-
- final List<EmergencyContact> othersEmergencyContact;
-
- final List<RecoverySessions> othersRecoverySession;
-
- EmergencyInfo(
- this.contacts,
- this.recoverSessions,
- this.othersEmergencyContact,
- this.othersRecoverySession,
+ }) => LegacyContactRecord(
+ user: user,
+ emergencyContact: emergencyContact,
+ state: state ?? this.state,
+ recoveryNoticeInDays: recoveryNoticeInDays ?? this.recoveryNoticeInDays,
);
-
- EmergencyInfo.fromJson(Map<String, dynamic> json)
- : contacts = (json['contacts'] as List)
- .map((contact) => EmergencyContact.fromJson(contact))
- .toList(),
- recoverSessions = (json['recoverSessions'] as List)
- .map((session) => RecoverySessions.fromJson(session))
- .toList(),
- othersEmergencyContact = (json['othersEmergencyContact'] as List)
- .map((grantor) => EmergencyContact.fromJson(grantor))
- .toList(),
- othersRecoverySession = (json['othersRecoverySession'] as List)
- .map((session) => RecoverySessions.fromJson(session))
- .toList();
}
-class RecoverySessions {
- final String id;
- final User user;
- final User emergencyContact;
- final String status;
- final int waitTill;
- final int createdAt;
-
- RecoverySessions(
- this.id,
- this.user,
- this.emergencyContact,
- this.status,
- this.waitTill,
- this.createdAt,
- );
-
- RecoverySessions.fromJson(Map<String, dynamic> json)
- : id = json['id'],
- user = User.fromMap(json['user']),
- emergencyContact = User.fromMap(json['emergencyContact']),
- status = json['status'],
- waitTill = json['waitTill'],
- createdAt = json['createdAt'];
+extension LegacyUserDisplay on LegacyUser {
+ User get asUser => User(id: id, email: email);
}
diff --git a/mobile/apps/photos/lib/emergency/other_contact_page.dart b/mobile/apps/photos/lib/emergency/other_contact_page.dart
index 97e24a5123..5451f50968 100644
--- a/mobile/apps/photos/lib/emergency/other_contact_page.dart
+++ b/mobile/apps/photos/lib/emergency/other_contact_page.dart
@@ -8,6 +8,9 @@ import "package:photos/emergency/emergency_service.dart";
import "package:photos/emergency/model.dart";
import "package:photos/emergency/recover_others_account.dart";
import "package:photos/gateways/users/models/key_attributes.dart";
+import "package:photos/services/authenticated_session.dart";
+import "package:photos/src/rust/third_party/ente_frb_lib/legacy/contact.dart"
+ as legacy;
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/components/alert_bottom_sheet.dart";
import "package:photos/ui/components/buttons/button_widget_v2.dart";
@@ -15,8 +18,8 @@ import "package:photos/ui/components/title_bar_title_widget.dart";
import "package:photos/utils/dialog_util.dart";
class OtherContactPage extends StatefulWidget {
- final EmergencyContact contact;
- final EmergencyInfo emergencyInfo;
+ final LegacyContactRecord contact;
+ final LegacyInfo emergencyInfo;
const OtherContactPage({
required this.contact,
@@ -30,10 +33,10 @@ class OtherContactPage extends StatefulWidget {
class _OtherContactPageState extends State<OtherContactPage> {
late String accountEmail = widget.contact.user.email;
- RecoverySessions? recoverySession;
+ LegacyRecoverySession? recoverySession;
String? waitTill;
final Logger _logger = Logger("_OtherContactPageState");
- late EmergencyInfo emergencyInfo = widget.emergencyInfo;
+ late LegacyInfo emergencyInfo = widget.emergencyInfo;
@override
void initState() {
@@ -45,7 +48,7 @@ class _OtherContactPageState extends State<OtherContactPage> {
Future<void> _fetchData() async {
try {
- final result = await EmergencyContactService.instance.getInfo();
+ final result = await legacy.info(session: authenticatedSession());
if (mounted) {
setState(() {
recoverySession = result.othersRecoverySession.firstWhereOrNull(
@@ -97,12 +100,14 @@ class _OtherContactPageState extends State<OtherContactPage> {
),
style: textTheme.smallMuted,
),
- if (recoverySession != null && recoverySession!.status == "READY")
+ if (recoverySession != null &&
+ recoverySession!.status == LegacyRecoveryStatus.ready)
Text(
context.strings.recoveryReady(email: accountEmail),
style: textTheme.smallMuted,
),
- if (recoverySession != null && recoverySession!.status == "WAITING")
+ if (recoverySession != null &&
+ recoverySession!.status == LegacyRecoveryStatus.waiting)
Text(
context.strings.recoverAccountAfter(
email: accountEmail,
@@ -166,7 +171,8 @@ class _OtherContactPageState extends State<OtherContactPage> {
}
},
),
- if (recoverySession != null && recoverySession!.status == "READY")
+ if (recoverySession != null &&
+ recoverySession!.status == LegacyRecoveryStatus.ready)
ButtonWidgetV2(
buttonType: ButtonTypeV2.primary,
labelText: context.strings.recoverAccount,
@@ -191,7 +197,8 @@ class _OtherContactPageState extends State<OtherContactPage> {
}
},
),
- if (recoverySession != null && recoverySession!.status == "WAITING")
+ if (recoverySession != null &&
+ recoverySession!.status == LegacyRecoveryStatus.waiting)
ButtonWidgetV2(
buttonType: ButtonTypeV2.secondary,
labelText: context.strings.cancelRecovery,
@@ -201,7 +208,7 @@ class _OtherContactPageState extends State<OtherContactPage> {
},
),
if (recoverySession != null &&
- recoverySession!.status == "READY") ...[
+ recoverySession!.status == LegacyRecoveryStatus.ready) ...[
const SizedBox(height: 20),
ButtonWidgetV2(
buttonType: ButtonTypeV2.tertiaryCritical,
@@ -225,7 +232,7 @@ class _OtherContactPageState extends State<OtherContactPage> {
),
],
if (recoverySession == null ||
- recoverySession!.status != "READY") ...[
+ recoverySession!.status != LegacyRecoveryStatus.ready) ...[
const SizedBox(height: 20),
ButtonWidgetV2(
buttonType: ButtonTypeV2.tertiaryCritical,
@@ -285,9 +292,11 @@ class _OtherContactPageState extends State<OtherContactPage> {
);
if (confirmed == true) {
try {
- await EmergencyContactService.instance.updateContact(
- widget.contact,
- ContactState.contactLeft,
+ await legacy.updateContact(
+ session: authenticatedSession(),
+ userId: widget.contact.user.id,
+ emergencyContactId: widget.contact.emergencyContact.id,
+ state: LegacyContactState.contactLeft,
);
if (mounted) {
Navigator.of(context).pop();
diff --git a/mobile/apps/photos/lib/emergency/recover_others_account.dart b/mobile/apps/photos/lib/emergency/recover_others_account.dart
index 85518c5547..959ec518df 100644
--- a/mobile/apps/photos/lib/emergency/recover_others_account.dart
+++ b/mobile/apps/photos/lib/emergency/recover_others_account.dart
@@ -23,7 +23,7 @@ import 'package:photos/utils/dialog_util.dart';
class RecoverOthersAccount extends StatefulWidget {
final String recoveryKey;
final KeyAttributes attributes;
- final RecoverySessions sessions;
+ final LegacyRecoverySession sessions;
const RecoverOthersAccount(
this.recoveryKey,
diff --git a/mobile/apps/photos/lib/emergency/select_contact_page.dart b/mobile/apps/photos/lib/emergency/select_contact_page.dart
index 7152d6a580..dccabd3c6c 100644
--- a/mobile/apps/photos/lib/emergency/select_contact_page.dart
+++ b/mobile/apps/photos/lib/emergency/select_contact_page.dart
@@ -5,13 +5,16 @@ import 'package:flutter/material.dart';
import "package:logging/logging.dart";
import 'package:photos/core/configuration.dart';
import "package:photos/emergency/components/recovery_date_selector.dart";
-import "package:photos/emergency/emergency_service.dart";
import "package:photos/emergency/model.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/services/account/user_service.dart";
+import "package:photos/services/authenticated_session.dart";
import 'package:photos/services/collections_service.dart';
import "package:photos/services/contacts/contact_identity_resolver.dart";
+import "package:photos/src/rust/third_party/ente_frb_lib/legacy/contact.dart"
+ as legacy;
import 'package:photos/theme/ente_theme.dart';
+import "package:photos/ui/common/user_dialogs.dart";
import "package:photos/ui/components/alert_bottom_sheet.dart";
import "package:photos/ui/components/base_bottom_sheet.dart";
import "package:photos/ui/components/buttons/button_widget_v2.dart";
@@ -19,10 +22,11 @@ import "package:photos/ui/components/menu_item_widget/menu_item_widget_new.dart"
import "package:photos/ui/components/text_input_widget_v2.dart";
import 'package:photos/ui/sharing/user_avator_widget.dart';
import "package:photos/ui/sharing/verify_identity_dialog.dart";
+import "package:photos/utils/email_util.dart";
Future<bool?> showAddContactSheet(
BuildContext context, {
- required EmergencyInfo emergencyInfo,
+ required LegacyInfo emergencyInfo,
}) {
return showBaseBottomSheet<bool>(
context,
@@ -36,7 +40,7 @@ Future<bool?> showAddContactSheet(
}
class AddContactSheet extends StatefulWidget {
- final EmergencyInfo emergencyInfo;
+ final LegacyInfo emergencyInfo;
const AddContactSheet({required this.emergencyInfo, super.key});
@@ -191,8 +195,41 @@ class _AddContactSheetState extends State<AddContactSheet> {
);
}
+ Future<bool> _addContact(String email, int recoveryNoticeInDays) async {
+ if (!isValidEmail(email)) {
+ if (!mounted) return false;
+ await showAlertBottomSheet(
+ context,
+ title: context.strings.letsTryThatAgain,
+ message: context.strings.enterValidEmail,
+ assetPath: "assets/warning-grey.png",
+ );
+ return false;
+ } else if (email.trim() == Configuration.instance.getEmail()) {
+ if (!mounted) return false;
+ await showAlertBottomSheet(
+ context,
+ title: context.strings.oops,
+ message: context.strings.youCannotShareWithYourself,
+ assetPath: "assets/warning-grey.png",
+ );
+ return false;
+ }
+ try {
+ await legacy.addContact(
+ session: authenticatedSession(),
+ email: email,
+ recoveryNoticeInDays: recoveryNoticeInDays,
+ );
+ return true;
+ } on LegacyError_ContactNotOnEnte {
+ if (!mounted) return false;
+ await showInviteDialog(context, email);
+ return false;
+ }
+ }
+
Future<void> _onAddContactTap() async {
- final sheetContext = context;
final emailsToAdd = _emailsToAdd;
if (emailsToAdd.isEmpty) {
return;
@@ -209,20 +246,7 @@ class _AddContactSheetState extends State<AddContactSheet> {
var hasSuccess = false;
for (final email in emailsToAdd) {
try {
- late final bool success;
- if (sheetContext.mounted) {
- success = await EmergencyContactService.instance.addContact(
- sheetContext,
- email,
- recoveryNoticeInDays: _selectedRecoveryDays,
- );
- } else {
- success = await EmergencyContactService.instance.addContact(
- null,
- email,
- recoveryNoticeInDays: _selectedRecoveryDays,
- );
- }
+ final success = await _addContact(email, _selectedRecoveryDays);
if (success) {
hasSuccess = true;
} else {
diff --git a/mobile/apps/photos/lib/gateways/emergency/emergency_gateway.dart b/mobile/apps/photos/lib/gateways/emergency/emergency_gateway.dart
index 4b7e5bad9b..2c6ab2ff19 100644
--- a/mobile/apps/photos/lib/gateways/emergency/emergency_gateway.dart
+++ b/mobile/apps/photos/lib/gateways/emergency/emergency_gateway.dart
@@ -1,5 +1,4 @@
import "package:dio/dio.dart";
-import "package:photos/emergency/model.dart";
import "package:photos/gateways/users/models/key_attributes.dart";
import "package:photos/gateways/users/models/srp.dart";
@@ -8,54 +7,6 @@ class EmergencyGateway {
EmergencyGateway(this._enteDio);
- Future<void> addContact({
- required String email,
- required String encryptedKey,
- int? recoveryNoticeInDays,
- }) async {
- await _enteDio.post(
- "/emergency-contacts/add",
- data: {
- "email": email,
- "encryptedKey": encryptedKey,
- "recoveryNoticeInDays": ?recoveryNoticeInDays,
- },
- );
- }
-
- Future<EmergencyInfo> getInfo() async {
- final response = await _enteDio.get("/emergency-contacts/info");
- return EmergencyInfo.fromJson(response.data);
- }
-
- Future<void> updateState({
- required int? userID,
- required int? emergencyContactID,
- required String state,
- }) async {
- await _enteDio.post(
- "/emergency-contacts/update",
- data: {
- "userID": userID,
- "emergencyContactID": emergencyContactID,
- "state": state,
- },
- );
- }
-
- Future<void> updateRecoveryNotice({
- required int? emergencyContactID,
- required int recoveryNoticeInDays,
- }) async {
- await _enteDio.post(
- "/emergency-contacts/update-recovery-notice",
- data: {
- "emergencyContactID": emergencyContactID,
- "recoveryNoticeInDays": recoveryNoticeInDays,
- },
- );
- }
-
Future<void> startRecovery({
required int? userID,
required int? emergencyContactID,
diff --git a/mobile/packages/legacy/lib/components/trusted_contact_bottom_sheet.dart b/mobile/packages/legacy/lib/components/trusted_contact_bottom_sheet.dart
index 0883d9f0d6..0740a30774 100644
--- a/mobile/packages/legacy/lib/components/trusted_contact_bottom_sheet.dart
+++ b/mobile/packages/legacy/lib/components/trusted_contact_bottom_sheet.dart
@@ -8,7 +8,7 @@ import "package:flutter/material.dart";
Future<TrustedContactResult?> showTrustedContactSheet(
BuildContext context, {
- required EmergencyContact contact,
+ required LegacyContactRecord contact,
}) {
final email = contact.emergencyContact.email;
return showBaseBottomSheet<TrustedContactResult>(
@@ -29,7 +29,7 @@ class TrustedContactResult {
}
class TrustedContactSheet extends StatefulWidget {
- final EmergencyContact contact;
+ final LegacyContactRecord contact;
const TrustedContactSheet({required this.contact, super.key});
diff --git a/mobile/packages/legacy/lib/ente_legacy.dart b/mobile/packages/legacy/lib/ente_legacy.dart
index f8361b7ddf..ea14bdf36a 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 'legacy_api.dart';
export 'models/emergency_models.dart';
export 'models/legacy_kit_models.dart';
export 'pages/create_legacy_kit_sheet.dart';
diff --git a/mobile/packages/legacy/lib/legacy_api.dart b/mobile/packages/legacy/lib/legacy_api.dart
new file mode 100644
index 0000000000..dbf4a45306
--- /dev/null
+++ b/mobile/packages/legacy/lib/legacy_api.dart
@@ -0,0 +1,39 @@
+import "package:ente_frb/legacy.dart";
+
+abstract interface class LegacyApi {
+ Future<LegacyInfo> info();
+
+ Future<void> addContact({
+ required String email,
+ required int recoveryNoticeInDays,
+ });
+
+ Future<void> updateContact({
+ required int userId,
+ required int emergencyContactId,
+ required LegacyContactState state,
+ });
+
+ Future<void> updateRecoveryNotice({
+ required int emergencyContactId,
+ required int recoveryNoticeInDays,
+ });
+
+ Future<List<LegacyKit>> kits();
+
+ Future<LegacyKitCreateResult> createKit({
+ required List<String> partNames,
+ required int noticePeriodInHours,
+ });
+
+ Future<List<LegacyKitShare>> downloadKitShares({required String kitId});
+
+ Future<void> updateKitRecoveryNotice({
+ required String kitId,
+ required int noticePeriodInHours,
+ });
+
+ Future<void> blockKitRecovery({required String kitId});
+
+ Future<void> deleteKit({required String kitId});
+}
diff --git a/mobile/packages/legacy/lib/models/emergency_models.dart b/mobile/packages/legacy/lib/models/emergency_models.dart
index 4170a0ef4a..2959073362 100644
--- a/mobile/packages/legacy/lib/models/emergency_models.dart
+++ b/mobile/packages/legacy/lib/models/emergency_models.dart
@@ -1,145 +1,25 @@
+import "package:ente_frb/legacy.dart";
+import "package:ente_sharing/extensions/user_extension.dart";
import "package:ente_sharing/models/user.dart";
-enum ContactState {
- userInvitedContact,
- userRevokedContact,
- contactAccepted,
- contactLeft,
- contactDenied,
- unknown,
-}
-
-extension ContactStateExtension on ContactState {
- String get stringValue {
- switch (this) {
- case ContactState.userInvitedContact:
- return "INVITED";
- case ContactState.userRevokedContact:
- return "REVOKED";
- case ContactState.contactAccepted:
- return "ACCEPTED";
- case ContactState.contactLeft:
- return "CONTACT_LEFT";
- case ContactState.contactDenied:
- return "CONTACT_DENIED";
- default:
- return "UNKNOWN";
- }
- }
+export "package:ente_frb/legacy.dart";
- static ContactState fromString(String value) {
- switch (value) {
- case "INVITED":
- return ContactState.userInvitedContact;
- case "REVOKED":
- return ContactState.userRevokedContact;
- case "ACCEPTED":
- return ContactState.contactAccepted;
- case "CONTACT_LEFT":
- return ContactState.contactLeft;
- case "CONTACT_DENIED":
- return ContactState.contactDenied;
- default:
- return ContactState.unknown;
- }
- }
-}
+extension LegacyContactExtension on LegacyContactRecord {
+ bool isPendingInvite() => state == LegacyContactState.invited;
-class EmergencyContact {
- final User user;
- final User emergencyContact;
- final ContactState state;
- final int recoveryNoticeInDays;
-
- EmergencyContact(
- this.user,
- this.emergencyContact,
- this.state,
- this.recoveryNoticeInDays,
- );
-
- EmergencyContact copyWith({
- User? user,
- User? emergencyContact,
- ContactState? state,
+ LegacyContactRecord copyWith({
+ LegacyContactState? state,
int? recoveryNoticeInDays,
- }) {
- return EmergencyContact(
- user ?? this.user,
- emergencyContact ?? this.emergencyContact,
- state ?? this.state,
- recoveryNoticeInDays ?? this.recoveryNoticeInDays,
- );
- }
-
- EmergencyContact.fromJson(Map<String, dynamic> json)
- : user = User.fromMap(json['user']),
- emergencyContact = User.fromMap(json['emergencyContact']),
- state = ContactStateExtension.fromString(json['state'] as String),
- recoveryNoticeInDays = json['recoveryNoticeInDays'];
-
- bool isCurrentUserContact(int userID) {
- return user.id == userID;
- }
-
- bool isPendingInvite() {
- return state == ContactState.userInvitedContact;
- }
-}
-
-class EmergencyInfo {
- final List<EmergencyContact> contacts;
-
- final List<RecoverySessions> recoverSessions;
-
- final List<EmergencyContact> othersEmergencyContact;
-
- final List<RecoverySessions> othersRecoverySession;
-
- EmergencyInfo(
- this.contacts,
- this.recoverSessions,
- this.othersEmergencyContact,
- this.othersRecoverySession,
+ }) => LegacyContactRecord(
+ user: user,
+ emergencyContact: emergencyContact,
+ state: state ?? this.state,
+ recoveryNoticeInDays: recoveryNoticeInDays ?? this.recoveryNoticeInDays,
);
-
- EmergencyInfo.fromJson(Map<String, dynamic> json)
- : contacts = (json['contacts'] as List)
- .map((contact) => EmergencyContact.fromJson(contact))
- .toList(),
- recoverSessions = (json['recoverSessions'] as List)
- .map((session) => RecoverySessions.fromJson(session))
- .toList(),
- othersEmergencyContact = (json['othersEmergencyContact'] as List)
- .map((grantor) => EmergencyContact.fromJson(grantor))
- .toList(),
- othersRecoverySession = (json['othersRecoverySession'] as List)
- .map((session) => RecoverySessions.fromJson(session))
- .toList();
}
-class RecoverySessions {
- final String id;
- final User user;
- final User emergencyContact;
- final String status;
- final int waitTill;
- final int createdAt;
-
- RecoverySessions(
- this.id,
- this.user,
- this.emergencyContact,
- this.status,
- this.waitTill,
- this.createdAt,
- );
+extension LegacyUserDisplay on LegacyUser {
+ User get asUser => User(id: id, email: email);
- RecoverySessions.fromJson(Map<String, dynamic> json)
- : id = json['id'],
- user = User.fromMap(json['user']),
- emergencyContact = User.fromMap(json['emergencyContact']),
- status = json['status'],
- waitTill = json['waitTill'],
- createdAt = json['createdAt'];
+ String get resolvedDisplayName => resolveUserIdentity(id, email).displayName;
}
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 1dcca5cfae..5c36b8ec24 100644
--- a/mobile/packages/legacy/lib/pages/create_legacy_kit_sheet.dart
+++ b/mobile/packages/legacy/lib/pages/create_legacy_kit_sheet.dart
@@ -2,7 +2,10 @@ import "dart:async";
import "dart:convert";
import "package:ente_components/ente_components.dart";
+import "package:ente_events/event_bus.dart";
import "package:ente_legacy/components/legacy_kit_recovery_wait_time_sheet.dart";
+import "package:ente_legacy/events/legacy_kit_created_event.dart";
+import "package:ente_legacy/legacy_api.dart";
import "package:ente_legacy/models/legacy_kit_models.dart";
import "package:ente_legacy/pages/share_legacy_kit_page.dart";
import "package:ente_strings/ente_strings.dart";
@@ -14,22 +17,11 @@ 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,
+ required LegacyApi legacy,
LegacyKitAuthenticator? authenticator,
ValueChanged<LegacyKit>? onCreated,
VoidCallback? onChanged,
@@ -39,12 +31,7 @@ Future<void> showCreateLegacyKitPage(
builder: (context) => CreateLegacyKitPage(
accountEmail: accountEmail,
isFirstLegacyKit: isFirstLegacyKit,
- createKit: createKit,
- getKits: getKits,
- downloadShares: downloadShares,
- updateRecoveryNotice: updateRecoveryNotice,
- blockRecovery: blockRecovery,
- deleteKit: deleteKit,
+ legacy: legacy,
authenticator: authenticator,
onCreated: onCreated,
onChanged: onChanged,
@@ -56,12 +43,7 @@ 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 LegacyApi legacy;
final LegacyKitAuthenticator? authenticator;
final ValueChanged<LegacyKit>? onCreated;
final VoidCallback? onChanged;
@@ -69,12 +51,7 @@ 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,
+ required this.legacy,
this.authenticator,
this.onCreated,
this.onChanged,
@@ -232,7 +209,11 @@ class _CreateLegacyKitPageState extends State<CreateLegacyKitPage> {
if (!mounted) {
return;
}
- final result = await widget.createKit(_partNames, _selectedDays * 24);
+ final result = await widget.legacy.createKit(
+ partNames: _partNames,
+ noticePeriodInHours: _selectedDays * 24,
+ );
+ Bus.instance.fire(LegacyKitCreatedEvent());
widget.onCreated?.call(result.kit);
if (!mounted) {
return;
@@ -244,11 +225,7 @@ 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,
+ legacy: widget.legacy,
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 0dce6f4a59..f639707c38 100644
--- a/mobile/packages/legacy/lib/pages/emergency_page.dart
+++ b/mobile/packages/legacy/lib/pages/emergency_page.dart
@@ -7,6 +7,7 @@ import "package:ente_legacy/components/gradient_button.dart";
import "package:ente_legacy/components/invite_reject_bottom_sheet.dart";
import "package:ente_legacy/components/legacy_kit_icons.dart";
import "package:ente_legacy/components/trusted_contact_bottom_sheet.dart";
+import "package:ente_legacy/legacy_api.dart";
import "package:ente_legacy/models/emergency_models.dart";
import "package:ente_legacy/models/legacy_kit_models.dart";
import "package:ente_legacy/pages/create_legacy_kit_sheet.dart";
@@ -15,7 +16,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_sharing/extensions/user_extension.dart";
import "package:ente_sharing/user_avator_widget.dart";
import "package:ente_strings/ente_strings.dart";
import "package:ente_ui/components/alert_bottom_sheet.dart";
@@ -35,22 +35,12 @@ 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 LegacyApi legacy;
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,
+ required this.legacy,
this.legacyKitAuthenticator,
super.key,
});
@@ -60,7 +50,7 @@ class EmergencyPage extends StatefulWidget {
}
class _EmergencyPageState extends State<EmergencyPage> {
- EmergencyInfo? info;
+ LegacyInfo? info;
List<LegacyKit> legacyKits = [];
@override
@@ -73,7 +63,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
Future<void> _fetchData() async {
try {
- final result = await EmergencyContactService.instance.getInfo();
+ final result = await widget.legacy.info();
final kits = await _fetchLegacyKits();
if (mounted) {
setState(() {
@@ -90,7 +80,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
Future<List<LegacyKit>> _fetchLegacyKits() async {
try {
- return await widget.getLegacyKits();
+ return await widget.legacy.kits();
} catch (error, stackTrace) {
_logger.warning("Failed to fetch legacy kits", error, stackTrace);
return legacyKits;
@@ -105,9 +95,9 @@ class _EmergencyPageState extends State<EmergencyPage> {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
final colors = context.componentColors;
- final List<EmergencyContact> othersTrustedContacts =
+ final List<LegacyContactRecord> othersTrustedContacts =
info?.othersEmergencyContact ?? [];
- final List<EmergencyContact> trustedContacts = info?.contacts ?? [];
+ final List<LegacyContactRecord> trustedContacts = info?.contacts ?? [];
final hasSecondaryLegacyContent =
legacyKits.isNotEmpty || othersTrustedContacts.isNotEmpty;
final hasActiveLegacyKitRecovery = legacyKits.any(
@@ -162,7 +152,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
);
}
final listIndex = index - 1;
- final RecoverySessions recoverSession =
+ final LegacyRecoverySession recoverSession =
info!.recoverSessions[listIndex];
final isLastItem =
listIndex == info!.recoverSessions.length - 1;
@@ -175,16 +165,14 @@ class _EmergencyPageState extends State<EmergencyPage> {
.resolvedDisplayName,
textStyle: textTheme.small.copyWith(
color: colorScheme.warning500,
- fontWeight: recoverSession.status.isNotEmpty
- ? FontWeight.bold
- : null,
+ fontWeight: FontWeight.bold,
),
),
leadingIconSize: 24.0,
surfaceExecutionStates: false,
alwaysShowSuccessState: false,
leadingIconWidget: UserAvatarWidget(
- recoverSession.emergencyContact,
+ recoverSession.emergencyContact.asUser,
type: AvatarType.mini,
config: widget.config,
),
@@ -254,7 +242,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
isPending: contact.isPendingInvite(),
borderColor: rowColor,
child: UserAvatarWidget(
- contact.emergencyContact,
+ contact.emergencyContact.asUser,
type: AvatarType.small,
config: widget.config,
),
@@ -370,7 +358,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
isPending: currentUser.isPendingInvite(),
borderColor: rowColor,
child: UserAvatarWidget(
- currentUser.user,
+ currentUser.user.asUser,
type: AvatarType.small,
config: widget.config,
),
@@ -390,6 +378,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
MaterialPageRoute(
builder: (BuildContext context) {
return OtherContactPage(
+ legacy: widget.legacy,
contact: currentUser,
emergencyInfo: info!,
config: widget.config,
@@ -480,11 +469,7 @@ 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,
+ legacy: widget.legacy,
authenticator: widget.legacyKitAuthenticator,
onChanged: _refreshLegacyData,
);
@@ -514,6 +499,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
Future<void> _addTrustedContact() async {
final result = await showAddContactSheet(
context,
+ legacy: widget.legacy,
emergencyInfo: info!,
config: widget.config,
);
@@ -559,12 +545,7 @@ 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,
+ legacy: widget.legacy,
authenticator: widget.legacyKitAuthenticator,
onCreated: _onLegacyKitCreated,
onChanged: _refreshLegacyData,
@@ -593,7 +574,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
return DateFormat.yMMMd().format(dateTime);
}
- String _contactStatusText(BuildContext context, EmergencyContact contact) {
+ String _contactStatusText(BuildContext context, LegacyContactRecord contact) {
return contact.isPendingInvite()
? context.strings.trustedContactStatusPending
: context.strings.trustedContactStatusAccepted;
@@ -601,7 +582,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
Future<void> showRevokeOrRemoveDialog(
BuildContext context,
- EmergencyContact contact,
+ LegacyContactRecord contact,
) async {
final result = await showTrustedContactSheet(context, contact: contact);
@@ -635,9 +616,10 @@ class _EmergencyPageState extends State<EmergencyPage> {
);
if (confirmed == true) {
- await EmergencyContactService.instance.updateContact(
- contact,
- ContactState.userRevokedContact,
+ await widget.legacy.updateContact(
+ userId: contact.user.id,
+ emergencyContactId: contact.emergencyContact.id,
+ state: LegacyContactState.revoked,
);
info?.contacts.remove(contact);
if (mounted) {
@@ -649,28 +631,28 @@ class _EmergencyPageState extends State<EmergencyPage> {
final selectedDays = result!.selectedDays;
if (selectedDays == null) return;
try {
- final success = await EmergencyContactService.instance
- .updateRecoveryNotice(contact, selectedDays);
- if (success) {
- final updatedContact = contact.copyWith(
- recoveryNoticeInDays: selectedDays,
+ await widget.legacy.updateRecoveryNotice(
+ emergencyContactId: contact.emergencyContact.id,
+ recoveryNoticeInDays: selectedDays,
+ );
+ final updatedContact = contact.copyWith(
+ recoveryNoticeInDays: selectedDays,
+ );
+ final index = info?.contacts.indexOf(contact);
+ if (index != null && index >= 0) {
+ info?.contacts[index] = updatedContact;
+ }
+ if (mounted) {
+ setState(() {});
+ }
+ } on LegacyError_ActiveRecoverySession {
+ if (context.mounted) {
+ await showAlertBottomSheet(
+ context,
+ title: context.strings.cannotUpdateRecoveryTime,
+ message: context.strings.cannotUpdateRecoveryTimeMessage,
+ assetPath: "assets/warning-blue.png",
);
- final index = info?.contacts.indexOf(contact);
- if (index != null && index >= 0) {
- info?.contacts[index] = updatedContact;
- }
- if (mounted) {
- setState(() {});
- }
- } else {
- if (context.mounted) {
- await showAlertBottomSheet(
- context,
- title: context.strings.cannotUpdateRecoveryTime,
- message: context.strings.cannotUpdateRecoveryTimeMessage,
- assetPath: "assets/warning-blue.png",
- );
- }
}
} catch (e) {
if (context.mounted) {
@@ -682,7 +664,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
Future<void> showAcceptOrDeclineDialog(
BuildContext context,
- EmergencyContact contact,
+ LegacyContactRecord contact,
) async {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
@@ -715,12 +697,13 @@ class _EmergencyPageState extends State<EmergencyPage> {
);
if (result == "accept") {
- await EmergencyContactService.instance.updateContact(
- contact,
- ContactState.contactAccepted,
+ await widget.legacy.updateContact(
+ userId: contact.user.id,
+ emergencyContactId: contact.emergencyContact.id,
+ state: LegacyContactState.accepted,
);
final updatedContact = contact.copyWith(
- state: ContactState.contactAccepted,
+ state: LegacyContactState.accepted,
);
info?.othersEmergencyContact.remove(contact);
info?.othersEmergencyContact.add(updatedContact);
@@ -728,9 +711,10 @@ class _EmergencyPageState extends State<EmergencyPage> {
setState(() {});
}
} else if (result == "decline") {
- await EmergencyContactService.instance.updateContact(
- contact,
- ContactState.contactDenied,
+ await widget.legacy.updateContact(
+ userId: contact.user.id,
+ emergencyContactId: contact.emergencyContact.id,
+ state: LegacyContactState.contactDenied,
);
info?.othersEmergencyContact.remove(contact);
if (mounted) {
@@ -739,7 +723,7 @@ class _EmergencyPageState extends State<EmergencyPage> {
}
}
- Future<void> showRejectRecoveryDialog(RecoverySessions session) async {
+ Future<void> showRejectRecoveryDialog(LegacyRecoverySession session) async {
final String emergencyContactEmail = session.emergencyContact.email;
final colorScheme = getEnteColorScheme(context);
diff --git a/mobile/packages/legacy/lib/pages/other_contact_page.dart b/mobile/packages/legacy/lib/pages/other_contact_page.dart
index a4f2a154a9..1db9c1ebea 100644
--- a/mobile/packages/legacy/lib/pages/other_contact_page.dart
+++ b/mobile/packages/legacy/lib/pages/other_contact_page.dart
@@ -5,6 +5,7 @@ import "package:ente_base/models/key_attributes.dart";
import "package:ente_components/ente_components.dart";
import "package:ente_configuration/base_configuration.dart";
import "package:ente_legacy/components/gradient_button.dart";
+import "package:ente_legacy/legacy_api.dart";
import "package:ente_legacy/models/emergency_models.dart";
import "package:ente_legacy/pages/recover_others_account.dart";
import "package:ente_legacy/services/emergency_service.dart";
@@ -18,14 +19,16 @@ import "package:intl/intl.dart";
import "package:logging/logging.dart";
class OtherContactPage extends StatefulWidget {
- final EmergencyContact contact;
- final EmergencyInfo emergencyInfo;
+ final LegacyContactRecord contact;
+ final LegacyInfo emergencyInfo;
final BaseConfiguration config;
+ final LegacyApi legacy;
const OtherContactPage({
required this.contact,
required this.emergencyInfo,
required this.config,
+ required this.legacy,
super.key,
});
@@ -35,10 +38,10 @@ class OtherContactPage extends StatefulWidget {
class _OtherContactPageState extends State<OtherContactPage> {
late String accountEmail = widget.contact.user.email;
- RecoverySessions? recoverySession;
+ LegacyRecoverySession? recoverySession;
String? waitTill;
final Logger _logger = Logger("_OtherContactPageState");
- late EmergencyInfo emergencyInfo = widget.emergencyInfo;
+ late LegacyInfo emergencyInfo = widget.emergencyInfo;
@override
void initState() {
@@ -50,7 +53,7 @@ class _OtherContactPageState extends State<OtherContactPage> {
Future<void> _fetchData() async {
try {
- final result = await EmergencyContactService.instance.getInfo();
+ final result = await widget.legacy.info();
if (mounted) {
setState(() {
recoverySession = result.othersRecoverySession.firstWhereOrNull(
@@ -109,12 +112,14 @@ class _OtherContactPageState extends State<OtherContactPage> {
),
style: textTheme.smallMuted,
),
- if (recoverySession != null && recoverySession!.status == "READY")
+ if (recoverySession != null &&
+ recoverySession!.status == LegacyRecoveryStatus.ready)
Text(
context.strings.recoveryReady(email: accountEmail),
style: textTheme.smallMuted,
),
- if (recoverySession != null && recoverySession!.status == "WAITING")
+ if (recoverySession != null &&
+ recoverySession!.status == LegacyRecoveryStatus.waiting)
Text(
context.strings.recoverAccountAfter(
email: accountEmail,
@@ -176,7 +181,8 @@ class _OtherContactPageState extends State<OtherContactPage> {
}
},
),
- if (recoverySession != null && recoverySession!.status == "READY")
+ if (recoverySession != null &&
+ recoverySession!.status == LegacyRecoveryStatus.ready)
GradientButton(
text: context.strings.recoverAccount,
backgroundColor: colorScheme.primary700,
@@ -205,14 +211,15 @@ class _OtherContactPageState extends State<OtherContactPage> {
}
},
),
- if (recoverySession != null && recoverySession!.status == "WAITING")
+ if (recoverySession != null &&
+ recoverySession!.status == LegacyRecoveryStatus.waiting)
GradientButton(
text: context.strings.cancelRecovery,
backgroundColor: colorScheme.primary700,
onTap: () => _showCancelRecoverySheet(),
),
if (recoverySession != null &&
- recoverySession!.status == "READY") ...[
+ recoverySession!.status == LegacyRecoveryStatus.ready) ...[
const SizedBox(height: 20),
Center(
child: GestureDetector(
@@ -242,7 +249,7 @@ class _OtherContactPageState extends State<OtherContactPage> {
),
],
if (recoverySession == null ||
- recoverySession!.status != "READY") ...[
+ recoverySession!.status != LegacyRecoveryStatus.ready) ...[
const SizedBox(height: 20),
Center(
child: GestureDetector(
@@ -327,9 +334,10 @@ class _OtherContactPageState extends State<OtherContactPage> {
if (confirmed == true) {
try {
- await EmergencyContactService.instance.updateContact(
- widget.contact,
- ContactState.contactLeft,
+ await widget.legacy.updateContact(
+ userId: widget.contact.user.id,
+ emergencyContactId: widget.contact.emergencyContact.id,
+ state: LegacyContactState.contactLeft,
);
if (mounted) {
Navigator.of(context).pop();
diff --git a/mobile/packages/legacy/lib/pages/recover_others_account.dart b/mobile/packages/legacy/lib/pages/recover_others_account.dart
index d154c8ac7b..5d7d931698 100644
--- a/mobile/packages/legacy/lib/pages/recover_others_account.dart
+++ b/mobile/packages/legacy/lib/pages/recover_others_account.dart
@@ -16,7 +16,7 @@ import "package:password_strength/password_strength.dart";
class RecoverOthersAccount extends StatefulWidget {
final String recoveryKey;
final KeyAttributes attributes;
- final RecoverySessions sessions;
+ final LegacyRecoverySession sessions;
const RecoverOthersAccount(
this.recoveryKey,
diff --git a/mobile/packages/legacy/lib/pages/select_contact_page.dart b/mobile/packages/legacy/lib/pages/select_contact_page.dart
index 23d238154f..02875bf457 100644
--- a/mobile/packages/legacy/lib/pages/select_contact_page.dart
+++ b/mobile/packages/legacy/lib/pages/select_contact_page.dart
@@ -4,8 +4,10 @@ import "package:ente_configuration/base_configuration.dart";
import "package:ente_contacts/contacts.dart";
import "package:ente_legacy/components/gradient_button.dart";
import "package:ente_legacy/components/recovery_date_selector.dart";
+import "package:ente_legacy/legacy_api.dart";
import "package:ente_legacy/models/emergency_models.dart";
-import "package:ente_legacy/services/emergency_service.dart";
+import "package:ente_pure_utils/ente_pure_utils.dart";
+import "package:ente_sharing/components/invite_dialog.dart";
import "package:ente_sharing/extensions/user_extension.dart";
import "package:ente_sharing/models/user.dart";
import "package:ente_sharing/user_avator_widget.dart";
@@ -19,30 +21,38 @@ import "package:ente_ui/components/menu_item_widget_v2.dart";
import "package:ente_ui/theme/colors.dart";
import "package:ente_ui/theme/ente_theme.dart";
import "package:ente_ui/theme/text_style.dart";
+import "package:ente_ui/utils/dialog_util.dart";
import "package:flutter/material.dart";
import "package:logging/logging.dart";
Future<bool?> showAddContactSheet(
BuildContext context, {
- required EmergencyInfo emergencyInfo,
+ required LegacyInfo emergencyInfo,
required BaseConfiguration config,
+ required LegacyApi legacy,
}) {
return showBaseBottomSheet<bool>(
context,
title: context.strings.addTrustedContact,
headerSpacing: 20,
isKeyboardAware: true,
- child: AddContactSheet(emergencyInfo: emergencyInfo, config: config),
+ child: AddContactSheet(
+ emergencyInfo: emergencyInfo,
+ config: config,
+ legacy: legacy,
+ ),
);
}
class AddContactSheet extends StatefulWidget {
- final EmergencyInfo emergencyInfo;
+ final LegacyInfo emergencyInfo;
final BaseConfiguration config;
+ final LegacyApi legacy;
const AddContactSheet({
required this.emergencyInfo,
required this.config,
+ required this.legacy,
super.key,
});
@@ -325,6 +335,54 @@ class _AddContactSheetState extends State<AddContactSheet> {
);
}
+ Future<bool> _addContact(String email, int recoveryNoticeInDays) async {
+ if (!isValidEmail(email)) {
+ if (mounted) {
+ await showAlertBottomSheet(
+ context,
+ title: context.strings.letsTryThatAgain,
+ message: context.strings.enterValidEmailDetailed,
+ assetPath: "assets/warning-blue.png",
+ );
+ }
+ return false;
+ }
+ if (email.trim() == widget.config.getEmail()) {
+ if (mounted) {
+ await showAlertBottomSheet(
+ context,
+ title: context.strings.oops,
+ message: context.strings.youCannotAddYourselfAsLegacyContact,
+ assetPath: "assets/warning-blue.png",
+ );
+ }
+ return false;
+ }
+
+ final dialog = mounted
+ ? createProgressDialog(context, context.strings.pleaseWait)
+ : null;
+ await dialog?.show();
+
+ try {
+ await widget.legacy.addContact(
+ email: email,
+ recoveryNoticeInDays: recoveryNoticeInDays,
+ );
+ await dialog?.hide();
+ return true;
+ } on LegacyError_ContactNotOnEnte {
+ await dialog?.hide();
+ if (mounted) {
+ await showInviteSheet(context, email: email);
+ }
+ return false;
+ } catch (e) {
+ await dialog?.hide();
+ rethrow;
+ }
+ }
+
Future<void> _onAddContactTap() async {
final emailToAdd = selectedEmail.isNotEmpty ? selectedEmail : _email;
final confirmed = await _showAddContactConfirmationSheet(
@@ -333,11 +391,7 @@ class _AddContactSheetState extends State<AddContactSheet> {
);
if (confirmed == true) {
try {
- final success = await EmergencyContactService.instance.addContact(
- mounted ? context : null,
- emailToAdd,
- _selectedRecoveryDays,
- );
+ final success = await _addContact(emailToAdd, _selectedRecoveryDays);
if (success && mounted) {
Navigator.of(context).pop(true);
}
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 a0eb765ff5..7cf64569d3 100644
--- a/mobile/packages/legacy/lib/pages/share_legacy_kit_page.dart
+++ b/mobile/packages/legacy/lib/pages/share_legacy_kit_page.dart
@@ -6,6 +6,7 @@ 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/legacy_api.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";
@@ -24,13 +25,6 @@ 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>{};
@@ -46,11 +40,7 @@ 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 LegacyApi legacy;
final List<LegacyKitShare>? initialShares;
final String accountEmail;
final LegacyKitAuthenticator? authenticator;
@@ -61,11 +51,7 @@ 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,
+ required this.legacy,
this.initialShares,
this.authenticator,
this.onChanged,
@@ -331,7 +317,7 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
final dialog = createProgressDialog(context, context.strings.pleaseWait);
await dialog.show();
try {
- final shares = await widget.downloadShares(_kit.id);
+ final shares = await widget.legacy.downloadKitShares(kitId: _kit.id);
await dialog.hide();
if (mounted) {
setState(() {
@@ -470,7 +456,10 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
await dialog.show();
Object? updateError;
try {
- await widget.updateRecoveryNotice(_kit.id, selectedDays * 24);
+ await widget.legacy.updateKitRecoveryNotice(
+ kitId: _kit.id,
+ noticePeriodInHours: selectedDays * 24,
+ );
if (mounted) {
setState(() {
_kit = LegacyKit(
@@ -530,7 +519,7 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
return false;
}
try {
- await widget.deleteKit(_kit.id);
+ await widget.legacy.deleteKit(kitId: _kit.id);
return true;
} catch (_) {
if (mounted) {
@@ -599,7 +588,7 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
return false;
}
try {
- await widget.blockRecovery(_kit.id);
+ await widget.legacy.blockKitRecovery(kitId: _kit.id);
return true;
} catch (_) {
if (mounted) {
@@ -670,7 +659,7 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
}
Future<void> _refreshKit() async {
- final refreshed = await widget.getKits();
+ final refreshed = await widget.legacy.kits();
final current = refreshed.where((kit) => kit.id == _kit.id).firstOrNull;
if (current != null && mounted) {
setState(() {
diff --git a/mobile/packages/legacy/lib/services/emergency_service.dart b/mobile/packages/legacy/lib/services/emergency_service.dart
index 8d702ef602..1319c0ddf7 100644
--- a/mobile/packages/legacy/lib/services/emergency_service.dart
+++ b/mobile/packages/legacy/lib/services/emergency_service.dart
@@ -5,18 +5,11 @@ import "dart:typed_data";
import "package:dio/dio.dart";
import "package:ente_accounts/models/set_keys_request.dart";
import "package:ente_accounts/models/srp.dart";
-import "package:ente_accounts/services/user_service.dart";
import "package:ente_base/models/key_attributes.dart";
import "package:ente_configuration/base_configuration.dart";
import "package:ente_crypto_api/ente_crypto_api.dart";
-import "package:ente_legacy/models/emergency_models.dart";
+import "package:ente_frb/legacy.dart";
import "package:ente_network/network.dart";
-import "package:ente_pure_utils/ente_pure_utils.dart";
-import "package:ente_sharing/components/invite_dialog.dart";
-import "package:ente_strings/ente_strings.dart";
-import "package:ente_ui/components/alert_bottom_sheet.dart";
-import "package:ente_ui/utils/dialog_util.dart";
-import "package:flutter/material.dart";
import "package:logging/logging.dart";
import "package:pointycastle/pointycastle.dart";
import "package:pointycastle/random/fortuna_random.dart";
@@ -28,7 +21,6 @@ import "package:uuid/uuid.dart";
class EmergencyContactService {
final Dio _enteDio = Network.instance.enteDio;
- late UserService _userService;
late BaseConfiguration _config;
late final Logger _logger = Logger("EmergencyContactService");
@@ -36,131 +28,11 @@ class EmergencyContactService {
static final EmergencyContactService instance =
EmergencyContactService._privateConstructor();
- Future<void> init(UserService userService, BaseConfiguration config) async {
- _userService = userService;
+ void init(BaseConfiguration config) {
_config = config;
}
- Future<bool> addContact(
- BuildContext? context,
- String email,
- int recoveryNoticeInDays,
- ) async {
- if (!isValidEmail(email)) {
- if (context != null && context.mounted) {
- await showAlertBottomSheet(
- context,
- title: context.strings.letsTryThatAgain,
- message: context.strings.enterValidEmailDetailed,
- assetPath: "assets/warning-blue.png",
- );
- }
- return false;
- }
- if (email.trim() == _config.getEmail()) {
- if (context != null && context.mounted) {
- await showAlertBottomSheet(
- context,
- title: context.strings.oops,
- message: context.strings.youCannotAddYourselfAsLegacyContact,
- assetPath: "assets/warning-blue.png",
- );
- }
- return false;
- }
-
- final dialog = context != null && context.mounted
- ? createProgressDialog(context, context.strings.pleaseWait)
- : null;
- await dialog?.show();
-
- try {
- final String? publicKey = await _userService.getPublicKey(email);
- if (publicKey == null) {
- await dialog?.hide();
- if (context != null && context.mounted) {
- await showInviteSheet(context, email: email);
- }
- return false;
- }
-
- final Uint8List recoveryKey = _config.getRecoveryKey();
- final encryptedKey = CryptoUtil.sealSync(
- recoveryKey,
- CryptoUtil.base642bin(publicKey),
- );
- await _enteDio.post(
- "/emergency-contacts/add",
- data: {
- "email": email.trim(),
- "encryptedKey": CryptoUtil.bin2base64(encryptedKey),
- "recoveryNoticeInDays": recoveryNoticeInDays,
- },
- );
- await dialog?.hide();
- return true;
- } catch (e) {
- await dialog?.hide();
- rethrow;
- }
- }
-
- Future<EmergencyInfo> getInfo() async {
- try {
- final response = await _enteDio.get("/emergency-contacts/info");
- return EmergencyInfo.fromJson(response.data);
- } catch (e, s) {
- Logger("EmergencyContact").severe('failed to get info', e, s);
- rethrow;
- }
- }
-
- Future<void> updateContact(
- EmergencyContact contact,
- ContactState state,
- ) async {
- try {
- await _enteDio.post(
- "/emergency-contacts/update",
- data: {
- "userID": contact.user.id,
- "emergencyContactID": contact.emergencyContact.id,
- "state": state.stringValue,
- },
- );
- } catch (e, s) {
- _logger.severe('failed to update contact', e, s);
- rethrow;
- }
- }
-
- Future<bool> updateRecoveryNotice(
- EmergencyContact contact,
- int recoveryNoticeInDays,
- ) async {
- try {
- await _enteDio.post(
- "/emergency-contacts/update-recovery-notice",
- data: {
- "emergencyContactID": contact.emergencyContact.id,
- "recoveryNoticeInDays": recoveryNoticeInDays,
- },
- );
- return true;
- } on DioException catch (e) {
- if (e.response?.statusCode == 400 &&
- e.response?.data?['code'] == 'ACTIVE_RECOVERY_SESSION') {
- return false;
- }
- _logger.severe('failed to update recovery notice', e);
- rethrow;
- } catch (e, s) {
- _logger.severe('failed to update recovery notice', e, s);
- rethrow;
- }
- }
-
- Future<void> startRecovery(EmergencyContact contact) async {
+ Future<void> startRecovery(LegacyContactRecord contact) async {
try {
await _enteDio.post(
"/emergency-contacts/start-recovery",
@@ -175,7 +47,7 @@ class EmergencyContactService {
}
}
- Future<void> stopRecovery(RecoverySessions session) async {
+ Future<void> stopRecovery(LegacyRecoverySession session) async {
try {
await _enteDio.post(
"/emergency-contacts/stop-recovery",
@@ -191,7 +63,7 @@ class EmergencyContactService {
}
}
- Future<void> rejectRecovery(RecoverySessions session) async {
+ Future<void> rejectRecovery(LegacyRecoverySession session) async {
try {
await _enteDio.post(
"/emergency-contacts/reject-recovery",
@@ -207,7 +79,7 @@ class EmergencyContactService {
}
}
- Future<void> approveRecovery(RecoverySessions session) async {
+ Future<void> approveRecovery(LegacyRecoverySession session) async {
try {
await _enteDio.post(
"/emergency-contacts/approve-recovery",
@@ -224,7 +96,7 @@ class EmergencyContactService {
}
Future<(String, KeyAttributes)> getRecoveryInfo(
- RecoverySessions sessions,
+ LegacyRecoverySession sessions,
) async {
try {
final resp = await _enteDio.get(
@@ -250,7 +122,7 @@ class EmergencyContactService {
Future<void> changePasswordForOther(
Uint8List loginKey,
SetKeysRequest setKeysRequest,
- RecoverySessions recoverySessions,
+ LegacyRecoverySession recoverySessions,
) async {
try {
final SRP6GroupParameters kDefaultSrpGroup =
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index c0e8c447bf..54c953677b 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2659,7 +2659,6 @@ dependencies = [
"ente-core",
"ente-frb-lib",
"ente-frb-log",
- "ente-legacy",
"ente-ml",
"flutter_rust_bridge",
]
diff --git a/rust/bindings/frb/lib/src/legacy.rs b/rust/bindings/frb/lib/src/legacy.rs
index e860aea575..f1e82fe0a0 100644
--- a/rust/bindings/frb/lib/src/legacy.rs
+++ b/rust/bindings/frb/lib/src/legacy.rs
@@ -1,147 +1,3 @@
-use flutter_rust_bridge::frb;
-
-#[frb(non_opaque)]
-pub enum LegacyError {
- ActiveRecoverySession { message: String },
- Other { message: String },
-}
-
-impl From<ente_legacy::Error> for LegacyError {
- fn from(error: ente_legacy::Error) -> Self {
- let message = ente_core::error::chain(&error);
- match error {
- ente_legacy::Error::ActiveRecoverySession => Self::ActiveRecoverySession { message },
- _ => Self::Other { message },
- }
- }
-}
-
-#[frb(unignore)]
-#[derive(Clone)]
-pub struct LegacyKit {
- pub id: String,
- pub notice_period_in_hours: i32,
- pub legacy_url: String,
- pub parts: Vec<LegacyKitPart>,
- pub created_at: i64,
- pub updated_at: i64,
- pub active_recovery_session: Option<LegacyKitRecoverySession>,
-}
-
-impl From<ente_legacy::LegacyKit> for LegacyKit {
- fn from(value: ente_legacy::LegacyKit) -> Self {
- Self {
- id: value.id,
- notice_period_in_hours: value.notice_period_in_hours,
- legacy_url: value.legacy_url,
- parts: value.metadata.parts.into_iter().map(Into::into).collect(),
- created_at: value.created_at,
- updated_at: value.updated_at,
- active_recovery_session: value.active_recovery_session.map(Into::into),
- }
- }
-}
-
-#[frb(unignore)]
-#[derive(Clone)]
-pub struct LegacyKitCreateResult {
- pub kit: LegacyKit,
- pub shares: Vec<LegacyKitShare>,
-}
-
-impl TryFrom<ente_legacy::LegacyKitCreateResult> for LegacyKitCreateResult {
- type Error = LegacyError;
-
- fn try_from(value: ente_legacy::LegacyKitCreateResult) -> Result<Self, Self::Error> {
- Ok(Self {
- kit: value.kit.into(),
- shares: value
- .shares
- .into_iter()
- .map(TryInto::try_into)
- .collect::<Result<_, _>>()?,
- })
- }
-}
-
-#[frb(unignore)]
-#[derive(Clone)]
-pub struct LegacyKitShare {
- pub share_index: u8,
- pub part_name: String,
- pub qr_payload: String,
- pub copy_code: String,
-}
-
-impl TryFrom<ente_legacy::LegacyKitShare> for LegacyKitShare {
- type Error = LegacyError;
-
- fn try_from(value: ente_legacy::LegacyKitShare) -> Result<Self, Self::Error> {
- Ok(Self {
- qr_payload: value.to_qr_payload()?,
- copy_code: value.to_copy_code()?,
- share_index: value.share_index,
- part_name: value.part_name,
- })
- }
-}
-
-#[frb(unignore)]
-#[derive(Clone)]
-pub struct LegacyKitPart {
- pub index: u8,
- pub name: String,
-}
-
-impl From<ente_legacy::LegacyKitPart> for LegacyKitPart {
- fn from(value: ente_legacy::LegacyKitPart) -> Self {
- Self {
- index: value.index,
- name: value.name,
- }
- }
-}
-
-#[frb(unignore)]
-#[derive(Clone)]
-pub struct LegacyKitRecoverySession {
- pub id: String,
- pub kit_id: String,
- pub status: LegacyKitRecoveryStatus,
- pub wait_till: i64,
- pub created_at: i64,
-}
-
-impl From<ente_legacy::LegacyKitRecoverySession> for LegacyKitRecoverySession {
- fn from(value: ente_legacy::LegacyKitRecoverySession) -> Self {
- Self {
- id: value.id,
- kit_id: value.kit_id,
- status: value.status.into(),
- wait_till: value.wait_till,
- created_at: value.created_at,
- }
- }
-}
-
-#[frb(unignore)]
-#[derive(Clone, Copy)]
-pub enum LegacyKitRecoveryStatus {
- Waiting,
- Ready,
- Blocked,
- Cancelled,
- Recovered,
-}
-
-impl From<ente_legacy::LegacyKitRecoveryStatus> for LegacyKitRecoveryStatus {
- fn from(value: ente_legacy::LegacyKitRecoveryStatus) -> Self {
- match value {
- ente_legacy::LegacyKitRecoveryStatus::Waiting => Self::Waiting,
- ente_legacy::LegacyKitRecoveryStatus::Ready => Self::Ready,
- ente_legacy::LegacyKitRecoveryStatus::Blocked => Self::Blocked,
- ente_legacy::LegacyKitRecoveryStatus::Cancelled => Self::Cancelled,
- ente_legacy::LegacyKitRecoveryStatus::Recovered => Self::Recovered,
- }
- }
-}
+pub mod contact;
+pub mod kit;
+pub mod types;
diff --git a/rust/bindings/frb/lib/src/legacy/contact.rs b/rust/bindings/frb/lib/src/legacy/contact.rs
new file mode 100644
index 0000000000..f599ee76d8
--- /dev/null
+++ b/rust/bindings/frb/lib/src/legacy/contact.rs
@@ -0,0 +1,47 @@
+use crate::session::Session;
+
+use super::types::{LegacyContactState, LegacyError, LegacyInfo};
+
+pub async fn info(session: &Session) -> Result<LegacyInfo, LegacyError> {
+ Ok(ente_legacy::info(session.as_ref()).await?.into())
+}
+
+pub async fn add_contact(
+ session: &Session,
+ email: String,
+ recovery_notice_in_days: i32,
+) -> Result<(), LegacyError> {
+ ente_legacy::add_contact(session.as_ref(), &email, Some(recovery_notice_in_days))
+ .await
+ .map_err(Into::into)
+}
+
+pub async fn update_contact(
+ session: &Session,
+ user_id: i64,
+ emergency_contact_id: i64,
+ state: LegacyContactState,
+) -> Result<(), LegacyError> {
+ ente_legacy::update_contact(
+ session.as_ref(),
+ user_id,
+ emergency_contact_id,
+ state.into(),
+ )
+ .await
+ .map_err(Into::into)
+}
+
+pub async fn update_recovery_notice(
+ session: &Session,
+ emergency_contact_id: i64,
+ recovery_notice_in_days: i32,
+) -> Result<(), LegacyError> {
+ ente_legacy::update_recovery_notice(
+ session.as_ref(),
+ emergency_contact_id,
+ recovery_notice_in_days,
+ )
+ .await
+ .map_err(Into::into)
+}
diff --git a/rust/bindings/frb/locker/src/api/legacy.rs b/rust/bindings/frb/lib/src/legacy/kit.rs
similarity index 92%
rename from rust/bindings/frb/locker/src/api/legacy.rs
rename to rust/bindings/frb/lib/src/legacy/kit.rs
index 45068dffc8..a19252679f 100644
--- a/rust/bindings/frb/locker/src/api/legacy.rs
+++ b/rust/bindings/frb/lib/src/legacy/kit.rs
@@ -1,5 +1,5 @@
-use ente_frb_lib::legacy::{LegacyError, LegacyKit, LegacyKitCreateResult, LegacyKitShare};
-use ente_frb_lib::session::Session;
+use super::types::{LegacyError, LegacyKit, LegacyKitCreateResult, LegacyKitShare};
+use crate::session::Session;
pub async fn kits(session: &Session) -> Result<Vec<LegacyKit>, LegacyError> {
ente_legacy::kits(session.as_ref())
diff --git a/rust/bindings/frb/lib/src/legacy/types.rs b/rust/bindings/frb/lib/src/legacy/types.rs
new file mode 100644
index 0000000000..40abe95d9d
--- /dev/null
+++ b/rust/bindings/frb/lib/src/legacy/types.rs
@@ -0,0 +1,295 @@
+use flutter_rust_bridge::frb;
+
+#[frb(non_opaque)]
+pub enum LegacyError {
+ ContactNotOnEnte { message: String },
+ ActiveRecoverySession { message: String },
+ Other { message: String },
+}
+
+impl From<ente_legacy::Error> for LegacyError {
+ fn from(error: ente_legacy::Error) -> Self {
+ let message = ente_core::error::chain(&error);
+ match error {
+ ente_legacy::Error::ContactNotOnEnte => Self::ContactNotOnEnte { message },
+ ente_legacy::Error::ActiveRecoverySession => Self::ActiveRecoverySession { message },
+ _ => Self::Other { message },
+ }
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone)]
+pub struct LegacyUser {
+ pub id: i64,
+ pub email: String,
+}
+
+impl From<ente_legacy::LegacyUser> for LegacyUser {
+ fn from(value: ente_legacy::LegacyUser) -> Self {
+ Self {
+ id: value.id,
+ email: value.email,
+ }
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone)]
+pub struct LegacyContactRecord {
+ pub user: LegacyUser,
+ pub emergency_contact: LegacyUser,
+ pub state: LegacyContactState,
+ pub recovery_notice_in_days: i32,
+}
+
+impl From<ente_legacy::LegacyContactRecord> for LegacyContactRecord {
+ fn from(value: ente_legacy::LegacyContactRecord) -> Self {
+ Self {
+ user: value.user.into(),
+ emergency_contact: value.emergency_contact.into(),
+ state: value.state.into(),
+ recovery_notice_in_days: value.recovery_notice_in_days,
+ }
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone)]
+pub struct LegacyRecoverySession {
+ pub id: String,
+ pub user: LegacyUser,
+ pub emergency_contact: LegacyUser,
+ pub status: LegacyRecoveryStatus,
+ pub wait_till: i64,
+ pub created_at: i64,
+}
+
+impl From<ente_legacy::LegacyRecoverySession> for LegacyRecoverySession {
+ fn from(value: ente_legacy::LegacyRecoverySession) -> Self {
+ Self {
+ id: value.id,
+ user: value.user.into(),
+ emergency_contact: value.emergency_contact.into(),
+ status: value.status.into(),
+ wait_till: value.wait_till,
+ created_at: value.created_at,
+ }
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone)]
+pub struct LegacyInfo {
+ pub contacts: Vec<LegacyContactRecord>,
+ pub recover_sessions: Vec<LegacyRecoverySession>,
+ pub others_emergency_contact: Vec<LegacyContactRecord>,
+ pub others_recovery_session: Vec<LegacyRecoverySession>,
+}
+
+impl From<ente_legacy::LegacyInfo> for LegacyInfo {
+ fn from(value: ente_legacy::LegacyInfo) -> Self {
+ Self {
+ contacts: value.contacts.into_iter().map(Into::into).collect(),
+ recover_sessions: value.recover_sessions.into_iter().map(Into::into).collect(),
+ others_emergency_contact: value
+ .others_emergency_contact
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ others_recovery_session: value
+ .others_recovery_session
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ }
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone, Copy)]
+pub enum LegacyContactState {
+ Invited,
+ Revoked,
+ Accepted,
+ ContactLeft,
+ ContactDenied,
+}
+
+impl From<ente_legacy::LegacyContactState> for LegacyContactState {
+ fn from(value: ente_legacy::LegacyContactState) -> Self {
+ match value {
+ ente_legacy::LegacyContactState::Invited => Self::Invited,
+ ente_legacy::LegacyContactState::Revoked => Self::Revoked,
+ ente_legacy::LegacyContactState::Accepted => Self::Accepted,
+ ente_legacy::LegacyContactState::ContactLeft => Self::ContactLeft,
+ ente_legacy::LegacyContactState::ContactDenied => Self::ContactDenied,
+ }
+ }
+}
+
+impl From<LegacyContactState> for ente_legacy::LegacyContactState {
+ fn from(value: LegacyContactState) -> Self {
+ match value {
+ LegacyContactState::Invited => Self::Invited,
+ LegacyContactState::Revoked => Self::Revoked,
+ LegacyContactState::Accepted => Self::Accepted,
+ LegacyContactState::ContactLeft => Self::ContactLeft,
+ LegacyContactState::ContactDenied => Self::ContactDenied,
+ }
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone, Copy)]
+pub enum LegacyRecoveryStatus {
+ Initiated,
+ Waiting,
+ Rejected,
+ Recovered,
+ Stopped,
+ Ready,
+}
+
+impl From<ente_legacy::LegacyRecoveryStatus> for LegacyRecoveryStatus {
+ fn from(value: ente_legacy::LegacyRecoveryStatus) -> Self {
+ match value {
+ ente_legacy::LegacyRecoveryStatus::Initiated => Self::Initiated,
+ ente_legacy::LegacyRecoveryStatus::Waiting => Self::Waiting,
+ ente_legacy::LegacyRecoveryStatus::Rejected => Self::Rejected,
+ ente_legacy::LegacyRecoveryStatus::Recovered => Self::Recovered,
+ ente_legacy::LegacyRecoveryStatus::Stopped => Self::Stopped,
+ ente_legacy::LegacyRecoveryStatus::Ready => Self::Ready,
+ }
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone)]
+pub struct LegacyKit {
+ pub id: String,
+ pub notice_period_in_hours: i32,
+ pub legacy_url: String,
+ pub parts: Vec<LegacyKitPart>,
+ pub created_at: i64,
+ pub updated_at: i64,
+ pub active_recovery_session: Option<LegacyKitRecoverySession>,
+}
+
+impl From<ente_legacy::LegacyKit> for LegacyKit {
+ fn from(value: ente_legacy::LegacyKit) -> Self {
+ Self {
+ id: value.id,
+ notice_period_in_hours: value.notice_period_in_hours,
+ legacy_url: value.legacy_url,
+ parts: value.metadata.parts.into_iter().map(Into::into).collect(),
+ created_at: value.created_at,
+ updated_at: value.updated_at,
+ active_recovery_session: value.active_recovery_session.map(Into::into),
+ }
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone)]
+pub struct LegacyKitCreateResult {
+ pub kit: LegacyKit,
+ pub shares: Vec<LegacyKitShare>,
+}
+
+impl TryFrom<ente_legacy::LegacyKitCreateResult> for LegacyKitCreateResult {
+ type Error = LegacyError;
+
+ fn try_from(value: ente_legacy::LegacyKitCreateResult) -> Result<Self, Self::Error> {
+ Ok(Self {
+ kit: value.kit.into(),
+ shares: value
+ .shares
+ .into_iter()
+ .map(TryInto::try_into)
+ .collect::<Result<_, _>>()?,
+ })
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone)]
+pub struct LegacyKitShare {
+ pub share_index: u8,
+ pub part_name: String,
+ pub qr_payload: String,
+ pub copy_code: String,
+}
+
+impl TryFrom<ente_legacy::LegacyKitShare> for LegacyKitShare {
+ type Error = LegacyError;
+
+ fn try_from(value: ente_legacy::LegacyKitShare) -> Result<Self, Self::Error> {
+ Ok(Self {
+ qr_payload: value.to_qr_payload()?,
+ copy_code: value.to_copy_code()?,
+ share_index: value.share_index,
+ part_name: value.part_name,
+ })
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone)]
+pub struct LegacyKitPart {
+ pub index: u8,
+ pub name: String,
+}
+
+impl From<ente_legacy::LegacyKitPart> for LegacyKitPart {
+ fn from(value: ente_legacy::LegacyKitPart) -> Self {
+ Self {
+ index: value.index,
+ name: value.name,
+ }
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone)]
+pub struct LegacyKitRecoverySession {
+ pub id: String,
+ pub kit_id: String,
+ pub status: LegacyKitRecoveryStatus,
+ pub wait_till: i64,
+ pub created_at: i64,
+}
+
+impl From<ente_legacy::LegacyKitRecoverySession> for LegacyKitRecoverySession {
+ fn from(value: ente_legacy::LegacyKitRecoverySession) -> Self {
+ Self {
+ id: value.id,
+ kit_id: value.kit_id,
+ status: value.status.into(),
+ wait_till: value.wait_till,
+ created_at: value.created_at,
+ }
+ }
+}
+
+#[frb(unignore)]
+#[derive(Clone, Copy)]
+pub enum LegacyKitRecoveryStatus {
+ Waiting,
+ Ready,
+ Blocked,
+ Cancelled,
+ Recovered,
+}
+
+impl From<ente_legacy::LegacyKitRecoveryStatus> for LegacyKitRecoveryStatus {
+ fn from(value: ente_legacy::LegacyKitRecoveryStatus) -> Self {
+ match value {
+ ente_legacy::LegacyKitRecoveryStatus::Waiting => Self::Waiting,
+ ente_legacy::LegacyKitRecoveryStatus::Ready => Self::Ready,
+ ente_legacy::LegacyKitRecoveryStatus::Blocked => Self::Blocked,
+ ente_legacy::LegacyKitRecoveryStatus::Cancelled => Self::Cancelled,
+ ente_legacy::LegacyKitRecoveryStatus::Recovered => Self::Recovered,
+ }
+ }
+}
diff --git a/rust/bindings/frb/locker/Cargo.toml b/rust/bindings/frb/locker/Cargo.toml
index cfa26b0945..28aad398c4 100644
--- a/rust/bindings/frb/locker/Cargo.toml
+++ b/rust/bindings/frb/locker/Cargo.toml
@@ -10,7 +10,6 @@ ente-assets.workspace = true
ente-core.workspace = true
ente-frb-lib = { workspace = true, features = ["contacts", "legacy", "locker"] }
ente-frb-log.workspace = true
-ente-legacy.workspace = true
ente-ml.workspace = true
flutter_rust_bridge.workspace = true
diff --git a/rust/bindings/frb/locker/src/api/mod.rs b/rust/bindings/frb/locker/src/api/mod.rs
index c03f89bfdb..beca7753a6 100644
--- a/rust/bindings/frb/locker/src/api/mod.rs
+++ b/rust/bindings/frb/locker/src/api/mod.rs
@@ -1,5 +1,4 @@
pub mod document_scanner_api;
pub mod init;
-pub mod legacy;
#[cfg(any(feature = "flutter", frb_expand))]
pub mod log;
diff --git a/rust/bindings/frb/photos/Cargo.toml b/rust/bindings/frb/photos/Cargo.toml
index a9d853ef89..216fcf747a 100644
--- a/rust/bindings/frb/photos/Cargo.toml
+++ b/rust/bindings/frb/photos/Cargo.toml
@@ -9,7 +9,7 @@ crate-type = ["cdylib", "staticlib"]
ente-assets.workspace = true
ente-cast.workspace = true
ente-core.workspace = true
-ente-frb-lib = { workspace = true, features = ["contacts"] }
+ente-frb-lib = { workspace = true, features = ["contacts", "legacy"] }
ente-frb-log.workspace = true
ente-image.workspace = true
ente-location.workspace = true
diff --git a/rust/tools/codegen/src/main.rs b/rust/tools/codegen/src/main.rs
index 7be6837655..86b8b74de8 100644
--- a/rust/tools/codegen/src/main.rs
+++ b/rust/tools/codegen/src/main.rs
@@ -175,16 +175,20 @@ fn generate_frb(target: FrbTarget) -> Result<(), DynError> {
let mut shared_types = HashMap::new();
for app in apps {
let package_dir = repo_root.join("mobile/apps").join(app);
- generate_frb_package(&package_dir)?;
- let mut modules = vec![("contacts", "contacts/types")];
- if *app == "locker" {
- modules.push(("legacy", "legacy"));
+ let generated_dir = package_dir.join("lib/src/rust");
+ if generated_dir.exists() {
+ fs::remove_dir_all(&generated_dir)?;
}
- for (name, module) in modules {
+ generate_frb_package(&package_dir)?;
+ for name in ["contacts", "legacy"] {
let types_path = package_dir
.join("lib/src/rust/third_party/ente_frb_lib")
- .join(format!("{module}.dart"));
+ .join(format!("{name}/types.dart"));
let types = fs::read_to_string(&types_path)?
+ .replace(
+ "part 'types.freezed.dart';",
+ &format!("part '{name}.freezed.dart';"),
+ )
.lines()
.filter(|line| !line.ends_with("/frb_generated.dart';"))
.collect::<Vec<_>>()
@@ -198,10 +202,11 @@ fn generate_frb(target: FrbTarget) -> Result<(), DynError> {
}
let freezed_file = format!("{name}.freezed.dart");
if types.contains(&format!("part '{freezed_file}';")) {
- fs::rename(
- types_path.with_extension("freezed.dart"),
- shared_dir.join(freezed_file),
- )?;
+ let freezed_path = types_path.with_extension("freezed.dart");
+ let freezed = fs::read_to_string(&freezed_path)?
+ .replace("part of 'types.dart';", &format!("part of '{name}.dart';"));
+ fs::write(shared_dir.join(freezed_file), freezed)?;
+ fs::remove_file(freezed_path)?;
}
fs::write(shared_dir.join(format!("{name}.dart")), &types)?;
fs::write(