Skip to content

armgit / ente

Public Imported from GitHub
0

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

[rust][mobile] Fold shared FRB bridge into app-specific crates

laurenspriem9ee19077ed9b
diff --git a/.github/workflows/locker-build.yml b/.github/workflows/locker-build.yml
index 481963c6ad..c4f747ecc1 100644
--- a/.github/workflows/locker-build.yml
+++ b/.github/workflows/locker-build.yml
@@ -121,9 +121,7 @@ jobs:
- run: flutter pub get --enforce-lockfile
- - run: |
- cargo codegen frb shared
- cargo codegen frb locker
+ - run: cargo codegen frb locker
working-directory: rust
- name: Prepare whatsnew
@@ -243,9 +241,7 @@ jobs:
- name: Set up Rive iOS binaries
run: dart run rive_native:setup --clean --platform ios
- - run: |
- cargo codegen frb shared
- cargo codegen frb locker
+ - run: cargo codegen frb locker
working-directory: rust
- name: Install iOS pods
diff --git a/.github/workflows/mobile-lint.yml b/.github/workflows/mobile-lint.yml
index 79f63b40f2..2928d48f00 100644
--- a/.github/workflows/mobile-lint.yml
+++ b/.github/workflows/mobile-lint.yml
@@ -84,7 +84,7 @@ jobs:
- run: cargo clippy -p ente_photos_rust --features flutter --all-targets --locked
working-directory: rust
- - run: cargo clippy -p ente_rust --features flutter --all-targets --locked
+ - run: cargo clippy -p ente_locker_rust --features flutter --all-targets --locked
working-directory: rust
- run: flutter pub get --enforce-lockfile
diff --git a/.github/workflows/photos-build.yml b/.github/workflows/photos-build.yml
index 04db1e2b96..765523ce1f 100644
--- a/.github/workflows/photos-build.yml
+++ b/.github/workflows/photos-build.yml
@@ -121,7 +121,7 @@ jobs:
- run: flutter pub get --enforce-lockfile
- - run: cargo codegen frb
+ - run: cargo codegen frb photos
working-directory: rust
- name: Free runner disk space
@@ -244,7 +244,7 @@ jobs:
- name: Set up Rive iOS binaries
run: dart run rive_native:setup --clean --platform ios
- - run: cargo codegen frb
+ - run: cargo codegen frb photos
working-directory: rust
- name: Install iOS pods
diff --git a/.github/workflows/warm-caches.yml b/.github/workflows/warm-caches.yml
index 86aa9443c7..ebf8cc8aab 100644
--- a/.github/workflows/warm-caches.yml
+++ b/.github/workflows/warm-caches.yml
@@ -85,7 +85,7 @@ jobs:
- run: cargo clippy -p ente_photos_rust --features flutter --all-targets --locked
- - run: cargo clippy -p ente_rust --features flutter --all-targets --locked
+ - run: cargo clippy -p ente_locker_rust --features flutter --all-targets --locked
rust-wasm:
# For web-lint.yml's WASM builds.
diff --git a/mobile/apps/locker/ios/Podfile b/mobile/apps/locker/ios/Podfile
index 219b124ae0..27deb8fb97 100644
--- a/mobile/apps/locker/ios/Podfile
+++ b/mobile/apps/locker/ios/Podfile
@@ -46,7 +46,7 @@ post_install do |installer|
target.build_configurations.each do |config|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '13.0'
- if ['ente_locker_rust', 'ente_rust'].include?(target.name) && config.name == 'Debug'
+ if target.name == 'ente_locker_rust' && config.name == 'Debug'
config.build_settings['ONLY_ACTIVE_ARCH[sdk=iphonesimulator*]'] = 'YES'
end
diff --git a/mobile/apps/locker/ios/Podfile.lock b/mobile/apps/locker/ios/Podfile.lock
index 2b86769b69..68b75111d1 100644
--- a/mobile/apps/locker/ios/Podfile.lock
+++ b/mobile/apps/locker/ios/Podfile.lock
@@ -41,8 +41,6 @@ PODS:
- Flutter
- ente_mail (0.0.1):
- Flutter
- - ente_rust (0.0.1):
- - Flutter
- ente_screen_cover (0.0.1):
- Flutter
- file_picker (0.0.1):
@@ -99,7 +97,6 @@ DEPENDENCIES:
- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)
- ente_locker_rust (from `.symlinks/plugins/ente_locker_rust/ios`)
- ente_mail (from `.symlinks/plugins/ente_mail/ios`)
- - ente_rust (from `.symlinks/plugins/ente_rust/ios`)
- ente_screen_cover (from `.symlinks/plugins/ente_screen_cover/ios`)
- file_picker (from `.symlinks/plugins/file_picker/ios`)
- file_saver (from `.symlinks/plugins/file_saver/ios`)
@@ -139,8 +136,6 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/ente_locker_rust/ios"
ente_mail:
:path: ".symlinks/plugins/ente_mail/ios"
- ente_rust:
- :path: ".symlinks/plugins/ente_rust/ios"
ente_screen_cover:
:path: ".symlinks/plugins/ente_screen_cover/ios"
file_picker:
@@ -188,7 +183,6 @@ SPEC CHECKSUMS:
DKPhotoGallery: b3834fecb755ee09a593d7c9e389d8b5d6deed60
ente_locker_rust: a299b4450d8ed041499171ddb182a42107719e74
ente_mail: 90753dd584f49ee092759a32d4143ca51db69641
- ente_rust: d0197ebd5460e8f67576579452b073d698404abe
ente_screen_cover: 6792566774f1c83939f9c1d03ed0a1f1ded45ae4
file_picker: a0560bc09d61de87f12d246fc47d2119e6ef37be
file_saver: 6cdbcddd690cb02b0c1a0c225b37cd805c2bf8b6
@@ -212,6 +206,6 @@ SPEC CHECKSUMS:
ua_client_hints: 92fe0d139619b73ec9fcb46cc7e079a26178f586
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
-PODFILE CHECKSUM: 5705e3b102f97037a25602dd270df9935079a3ca
+PODFILE CHECKSUM: 495363c75992d6c5907a1fcc1bedd27d99f697bb
COCOAPODS: 1.17.0
diff --git a/mobile/apps/locker/lib/main.dart b/mobile/apps/locker/lib/main.dart
index e4ed8691c7..fe4c5cc10e 100644
--- a/mobile/apps/locker/lib/main.dart
+++ b/mobile/apps/locker/lib/main.dart
@@ -16,7 +16,6 @@ import 'package:ente_lock_screen/ui/app_lock.dart';
import 'package:ente_lock_screen/ui/lock_screen.dart';
import 'package:ente_logging/logging.dart';
import 'package:ente_network/network.dart';
-import 'package:ente_rust/ente_rust.dart';
import "package:ente_strings/ente_strings.dart";
import "package:ente_ui/theme/theme_config.dart";
import "package:flutter/material.dart";
@@ -34,10 +33,11 @@ import 'package:locker/services/files/download/service_locator.dart';
import 'package:locker/services/files/links/links_client.dart';
import 'package:locker/services/files/links/links_service.dart';
import 'package:locker/services/files/offline/offline_files_service.dart';
+import 'package:locker/services/frb_legacy_kit_rust_api.dart';
import 'package:locker/services/local_settings.dart';
import 'package:locker/services/trash/trash_service.dart';
import 'package:locker/services/update_service.dart';
-import 'package:locker/src/rust/api/log.dart' as locker_rust_log;
+import 'package:locker/src/rust/api/log.dart';
import 'package:locker/src/rust/frb_generated.dart';
import 'package:locker/ui/pages/home_page.dart';
import 'package:package_info_plus/package_info_plus.dart';
@@ -49,7 +49,6 @@ final _logger = Logger("main");
bool _isRustInitialized = false;
Future<void>? _rustInitFuture;
late final LogSinkGuard _rustLogSinkGuard;
-late final locker_rust_log.LogSinkGuard _lockerRustLogSinkGuard;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
@@ -118,7 +117,7 @@ Future<void> _ensureRustInitialized() async {
await inFlightInit;
return;
}
- final initFuture = Future.wait([EnteLockerRust.init(), EnteRust.init()]);
+ final initFuture = EnteLockerRust.init();
_rustInitFuture = initFuture;
try {
await initFuture;
@@ -133,26 +132,18 @@ void _attachRustLogStream() {
final logger = Logger("rust");
_rustLogSinkGuard = LogSinkGuard();
_rustLogSinkGuard.attachLogStream().listen((entry) {
- _logRustEntry(logger, entry.level.name, entry.target, entry.message);
- });
- _lockerRustLogSinkGuard = locker_rust_log.LogSinkGuard();
- _lockerRustLogSinkGuard.attachLogStream().listen((entry) {
- _logRustEntry(logger, entry.level.name, entry.target, entry.message);
+ final message = "[${entry.target}] ${entry.message}";
+ switch (entry.level) {
+ case LogLevel.error:
+ logger.severe(message);
+ case LogLevel.warn:
+ logger.warning(message);
+ case LogLevel.info:
+ logger.info(message);
+ }
});
}
-void _logRustEntry(Logger logger, String level, String target, String body) {
- final message = "[$target] $body";
- switch (level) {
- case "error":
- logger.severe(message);
- case "warn":
- logger.warning(message);
- case "info":
- logger.info(message);
- }
-}
-
ThemeMode _themeMode(AdaptiveThemeMode? savedThemeMode) {
if (savedThemeMode == null) return ThemeMode.system;
if (savedThemeMode.isLight) return ThemeMode.light;
@@ -238,6 +229,7 @@ Future<void> _init(bool bool, {String? via}) async {
await LegacyKitService.instance.init(
config: Configuration.instance,
sessionProvider: LockerContactsDisplayService.buildSession,
+ rustApi: const FrbLegacyKitRustApi(),
);
unawaited(
Future.delayed(
diff --git a/mobile/apps/locker/lib/services/contacts_display_service.dart b/mobile/apps/locker/lib/services/contacts_display_service.dart
index c1ec0fcf98..5368c08712 100644
--- a/mobile/apps/locker/lib/services/contacts_display_service.dart
+++ b/mobile/apps/locker/lib/services/contacts_display_service.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'package:ente_contacts/contacts.dart' as contacts;
import 'package:locker/services/configuration.dart';
+import 'package:locker/services/frb_contacts_rust_api.dart';
import 'package:logging/logging.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -15,7 +16,10 @@ class LockerContactsDisplayService {
required SharedPreferences preferences,
required PackageInfo packageInfo,
}) async {
- contacts.ContactsDisplayService.instance.init(preferences: preferences);
+ contacts.ContactsDisplayService.instance.init(
+ preferences: preferences,
+ rustApi: const FrbContactsRustApi(),
+ );
_packageInfo = packageInfo;
scheduleEnsureReady();
}
diff --git a/mobile/apps/locker/lib/services/frb_contacts_rust_api.dart b/mobile/apps/locker/lib/services/frb_contacts_rust_api.dart
new file mode 100644
index 0000000000..7af8caf892
--- /dev/null
+++ b/mobile/apps/locker/lib/services/frb_contacts_rust_api.dart
@@ -0,0 +1,198 @@
+import 'dart:typed_data';
+
+import 'package:ente_contacts/contacts.dart';
+import 'package:locker/src/rust/api/contacts.dart' as rust;
+
+class FrbContactsRustApi implements ContactsRustApi {
+ const FrbContactsRustApi();
+
+ @override
+ Future<OpenContactsContextResult> open(OpenContactsContextInput input) async {
+ final result = await rust.openContactsCtx(
+ input: rust.OpenContactsCtxInput(
+ baseUrl: input.baseUrl,
+ authToken: input.authToken,
+ userId: input.userId,
+ masterKey: input.accountKey,
+ cachedWrappedRootContactKey: input.cachedWrappedRootContactKey == null
+ ? null
+ : rust.WrappedRootContactKey(
+ encryptedKey: input.cachedWrappedRootContactKey!.encryptedKey,
+ header: input.cachedWrappedRootContactKey!.header,
+ ),
+ userAgent: input.userAgent,
+ clientPackage: input.clientPackage,
+ clientVersion: input.clientVersion,
+ ),
+ );
+
+ return OpenContactsContextResult(
+ ctx: _FrbContactsRustContext(result.ctx),
+ wrappedRootContactKey: result.wrappedRootContactKey == null
+ ? null
+ : WrappedRootContactKey(
+ encryptedKey: result.wrappedRootContactKey!.encryptedKey,
+ header: result.wrappedRootContactKey!.header,
+ ),
+ rootKeySource: switch (result.rootKeySource) {
+ rust.RootKeySource.cache => RootKeySource.cache,
+ rust.RootKeySource.unresolved => RootKeySource.unresolved,
+ },
+ );
+ }
+}
+
+class _FrbContactsRustContext implements ContactsRustContext {
+ final rust.ContactsCtx _inner;
+
+ const _FrbContactsRustContext(this._inner);
+
+ @override
+ int userId() => _inner.userId();
+
+ @override
+ Future<void> updateAuthToken(String authToken) {
+ return _inner.updateAuthToken(authToken: authToken);
+ }
+
+ @override
+ WrappedRootContactKey? currentWrappedRootContactKey() {
+ final current = _inner.currentWrappedRootContactKey();
+ if (current == null) {
+ return null;
+ }
+ return WrappedRootContactKey(
+ encryptedKey: current.encryptedKey,
+ header: current.header,
+ );
+ }
+
+ @override
+ Future<ContactRecord> createContact(ContactData data) async {
+ return _fromRustRecord(
+ await _inner.createContact(
+ data: rust.ContactData(
+ contactUserId: data.contactUserId,
+ name: data.name,
+ ),
+ ),
+ );
+ }
+
+ @override
+ Future<ContactRecord> getContact(String contactId) async {
+ return _fromRustRecord(await _inner.getContact(contactId: contactId));
+ }
+
+ @override
+ Future<List<ContactRecord>> getDiff(int sinceTime, int limit) async {
+ final diff = await _inner.getDiff(sinceTime: sinceTime, limit: limit);
+ return diff.map(_fromRustRecord).toList(growable: false);
+ }
+
+ @override
+ Future<ContactRecord> updateContact(
+ String contactId,
+ ContactData data,
+ ) async {
+ return _fromRustRecord(
+ await _inner.updateContact(
+ contactId: contactId,
+ data: rust.ContactData(
+ contactUserId: data.contactUserId,
+ name: data.name,
+ ),
+ ),
+ );
+ }
+
+ @override
+ Future<void> deleteContact(String contactId) {
+ return _inner.deleteContact(contactId: contactId);
+ }
+
+ @override
+ Future<ContactRecord> setAttachment(
+ String contactId,
+ ContactAttachmentType attachmentType,
+ Uint8List attachmentBytes,
+ ) async {
+ return _fromRustRecord(
+ await _inner.setAttachment(
+ contactId: contactId,
+ attachmentType: _toRustAttachmentType(attachmentType),
+ attachmentBytes: attachmentBytes,
+ ),
+ );
+ }
+
+ @override
+ Future<Uint8List> getAttachment(
+ ContactAttachmentType attachmentType,
+ String attachmentId,
+ ) {
+ return _inner.getAttachmentEncrypted(
+ attachmentType: _toRustAttachmentType(attachmentType),
+ attachmentId: attachmentId,
+ );
+ }
+
+ @override
+ Future<ContactRecord> deleteAttachment(
+ String contactId,
+ ContactAttachmentType attachmentType,
+ ) async {
+ return _fromRustRecord(
+ await _inner.deleteAttachment(
+ contactId: contactId,
+ attachmentType: _toRustAttachmentType(attachmentType),
+ ),
+ );
+ }
+
+ @override
+ Future<ContactRecord> setProfilePicture(
+ String contactId,
+ Uint8List profilePicture,
+ ) async {
+ return setAttachment(
+ contactId,
+ ContactAttachmentType.profilePicture,
+ profilePicture,
+ );
+ }
+
+ @override
+ Future<Uint8List> getProfilePicture(String contactId) {
+ return _inner.getProfilePicture(contactId: contactId);
+ }
+
+ @override
+ Future<ContactRecord> deleteProfilePicture(String contactId) async {
+ return deleteAttachment(contactId, ContactAttachmentType.profilePicture);
+ }
+}
+
+rust.AttachmentType _toRustAttachmentType(
+ ContactAttachmentType attachmentType,
+) {
+ return switch (attachmentType) {
+ ContactAttachmentType.profilePicture => rust.AttachmentType.profilePicture,
+ };
+}
+
+ContactRecord _fromRustRecord(rust.ContactRecord record) {
+ final data = record.isDeleted
+ ? null
+ : ContactData(contactUserId: record.contactUserId, name: record.name!);
+ return ContactRecord(
+ id: record.id,
+ contactUserId: record.contactUserId,
+ email: record.email,
+ data: data,
+ profilePictureAttachmentId: record.profilePictureAttachmentId,
+ isDeleted: record.isDeleted,
+ createdAt: record.createdAt,
+ updatedAt: record.updatedAt,
+ );
+}
diff --git a/mobile/apps/locker/lib/services/frb_legacy_kit_rust_api.dart b/mobile/apps/locker/lib/services/frb_legacy_kit_rust_api.dart
new file mode 100644
index 0000000000..40871a376c
--- /dev/null
+++ b/mobile/apps/locker/lib/services/frb_legacy_kit_rust_api.dart
@@ -0,0 +1,197 @@
+import "dart:typed_data";
+
+import "package:ente_base/models/key_attributes.dart";
+import "package:ente_contacts/contacts.dart" as contacts;
+import "package:ente_legacy/models/legacy_kit_models.dart";
+import "package:ente_legacy/services/legacy_kit_rust_api.dart";
+import "package:locker/src/rust/api/contacts.dart" as rust;
+
+class FrbLegacyKitRustApi implements LegacyKitRustApi {
+ const FrbLegacyKitRustApi();
+
+ @override
+ Future<LegacyKitRustContext> open(
+ contacts.ContactsSession session,
+ Uint8List accountKey,
+ ) async {
+ final opened = await rust.openContactsCtx(
+ input: rust.OpenContactsCtxInput(
+ baseUrl: session.baseUrl,
+ authToken: session.authToken,
+ userId: session.userId,
+ masterKey: accountKey,
+ userAgent: session.userAgent,
+ clientPackage: session.clientPackage,
+ clientVersion: session.clientVersion,
+ ),
+ );
+ return _FrbLegacyKitRustContext(opened.ctx);
+ }
+}
+
+class _FrbLegacyKitRustContext implements LegacyKitRustContext {
+ final rust.ContactsCtx _inner;
+
+ const _FrbLegacyKitRustContext(this._inner);
+
+ @override
+ Future<void> updateAuthToken(String authToken) {
+ return _run(() => _inner.updateAuthToken(authToken: authToken));
+ }
+
+ @override
+ Future<List<LegacyKit>> legacyKits() async {
+ final kits = await _run(_inner.legacyKits);
+ return kits.map(_fromRustKit).toList(growable: false);
+ }
+
+ @override
+ Future<LegacyKitCreateResult> legacyKitCreate({
+ required KeyAttributes currentUserKeyAttrs,
+ required List<String> partNames,
+ required int noticePeriodInHours,
+ }) async {
+ final result = await _run(
+ () => _inner.legacyKitCreate(
+ currentUserKeyAttrs: _toRustKeyAttributes(currentUserKeyAttrs),
+ partNames: partNames,
+ noticePeriodInHours: noticePeriodInHours,
+ ),
+ );
+ return LegacyKitCreateResult(
+ kit: _fromRustKit(result.kit),
+ shares: result.shares.map(_fromRustShare).toList(growable: false),
+ );
+ }
+
+ @override
+ Future<List<LegacyKitShare>> legacyKitDownloadShares(String kitId) async {
+ final shares = await _run(
+ () => _inner.legacyKitDownloadShares(kitId: kitId),
+ );
+ return shares.map(_fromRustShare).toList(growable: false);
+ }
+
+ @override
+ Future<LegacyKitOwnerRecoverySessionDetails> legacyKitRecoverySession(
+ String kitId,
+ ) async {
+ final details = await _run(
+ () => _inner.legacyKitRecoverySession(kitId: kitId),
+ );
+ return LegacyKitOwnerRecoverySessionDetails(
+ session: details.session == null
+ ? null
+ : _fromRustRecoverySession(details.session!),
+ initiators: details.initiators
+ .map(
+ (hint) => LegacyKitRecoveryInitiatorHint(
+ usedPartIndexes: hint.usedPartIndexes,
+ ip: hint.ip,
+ userAgent: hint.userAgent,
+ ),
+ )
+ .toList(growable: false),
+ );
+ }
+
+ @override
+ Future<void> legacyKitUpdateRecoveryNotice({
+ required String kitId,
+ required int noticePeriodInHours,
+ }) {
+ return _run(
+ () => _inner.legacyKitUpdateRecoveryNotice(
+ kitId: kitId,
+ noticePeriodInHours: noticePeriodInHours,
+ ),
+ );
+ }
+
+ @override
+ Future<void> legacyKitBlockRecovery(String kitId) {
+ return _run(() => _inner.legacyKitBlockRecovery(kitId: kitId));
+ }
+
+ @override
+ Future<void> legacyKitDelete(String kitId) {
+ return _run(() => _inner.legacyKitDelete(kitId: kitId));
+ }
+}
+
+Future<T> _run<T>(Future<T> Function() action) async {
+ try {
+ return await action();
+ } on rust.ContactsError_ActiveRecoverySession {
+ throw LegacyKitActiveRecoverySessionException();
+ }
+}
+
+rust.AccountKeyAttributes _toRustKeyAttributes(KeyAttributes attributes) {
+ return rust.AccountKeyAttributes(
+ kekSalt: attributes.kekSalt,
+ encryptedKey: attributes.encryptedKey,
+ keyDecryptionNonce: attributes.keyDecryptionNonce,
+ publicKey: attributes.publicKey,
+ encryptedSecretKey: attributes.encryptedSecretKey,
+ secretKeyDecryptionNonce: attributes.secretKeyDecryptionNonce,
+ memLimit: attributes.memLimit,
+ opsLimit: attributes.opsLimit,
+ masterKeyEncryptedWithRecoveryKey:
+ attributes.masterKeyEncryptedWithRecoveryKey,
+ masterKeyDecryptionNonce: attributes.masterKeyDecryptionNonce,
+ recoveryKeyEncryptedWithMasterKey:
+ attributes.recoveryKeyEncryptedWithMasterKey,
+ recoveryKeyDecryptionNonce: attributes.recoveryKeyDecryptionNonce,
+ );
+}
+
+LegacyKit _fromRustKit(rust.LegacyKit kit) {
+ return LegacyKit(
+ id: kit.id,
+ noticePeriodInHours: kit.noticePeriodInHours,
+ legacyUrl: kit.legacyUrl,
+ parts: kit.metadata.parts
+ .map((part) => LegacyKitPart(index: part.index, name: part.name))
+ .toList(growable: false),
+ createdAt: kit.createdAt,
+ updatedAt: kit.updatedAt,
+ activeRecoverySession: kit.activeRecoverySession == null
+ ? null
+ : _fromRustRecoverySession(kit.activeRecoverySession!),
+ );
+}
+
+LegacyKitRecoverySession _fromRustRecoverySession(
+ rust.LegacyKitRecoverySession session,
+) {
+ return LegacyKitRecoverySession(
+ id: session.id,
+ kitId: session.kitId,
+ status: switch (session.status) {
+ rust.LegacyKitRecoveryStatus.waiting => LegacyKitRecoveryStatus.waiting,
+ rust.LegacyKitRecoveryStatus.ready => LegacyKitRecoveryStatus.ready,
+ rust.LegacyKitRecoveryStatus.blocked => LegacyKitRecoveryStatus.blocked,
+ rust.LegacyKitRecoveryStatus.cancelled =>
+ LegacyKitRecoveryStatus.cancelled,
+ rust.LegacyKitRecoveryStatus.recovered =>
+ LegacyKitRecoveryStatus.recovered,
+ },
+ waitTill: session.waitTill,
+ createdAt: session.createdAt,
+ );
+}
+
+LegacyKitShare _fromRustShare(rust.LegacyKitShare share) {
+ return LegacyKitShare(
+ payloadVersion: share.payloadVersion,
+ variant: switch (share.variant) {
+ rust.LegacyKitVariant.twoOfThree => 1,
+ },
+ kitId: share.kitId,
+ shareIndex: share.shareIndex,
+ share: share.share,
+ checksum: share.checksum,
+ partName: share.partName,
+ );
+}
diff --git a/mobile/apps/locker/pubspec.yaml b/mobile/apps/locker/pubspec.yaml
index d8484e8276..030733c1eb 100644
--- a/mobile/apps/locker/pubspec.yaml
+++ b/mobile/apps/locker/pubspec.yaml
@@ -52,8 +52,6 @@ dependencies:
path: ../../packages/network
ente_pure_utils:
path: ../../packages/ente_pure_utils
- ente_rust:
- path: ../../packages/rust
ente_sharing:
path: ../../packages/sharing
ente_strings:
@@ -74,6 +72,7 @@ dependencies:
sdk: flutter
flutter_rust_bridge: 2.12.0
flutter_svg: 2.3.0
+ freezed_annotation: 3.1.0
hugeicons: 1.1.7
intl: 0.20.2
listen_sharing_intent: 1.9.2
@@ -91,11 +90,13 @@ dependencies:
uuid: 4.5.3
dev_dependencies:
+ build_runner: 2.13.1
flutter_launcher_icons: 0.14.4
flutter_lints: 6.0.0
flutter_native_splash: 2.4.7
flutter_test:
sdk: flutter
+ freezed: 3.2.3
flutter:
uses-material-design: true
diff --git a/mobile/apps/photos/integration_test/ente_rust_test.dart b/mobile/apps/photos/integration_test/photos_rust_test.dart
similarity index 76%
rename from mobile/apps/photos/integration_test/ente_rust_test.dart
rename to mobile/apps/photos/integration_test/photos_rust_test.dart
index c6de7ddfc9..b8a871e91a 100644
--- a/mobile/apps/photos/integration_test/ente_rust_test.dart
+++ b/mobile/apps/photos/integration_test/photos_rust_test.dart
@@ -1,13 +1,13 @@
-import 'package:ente_rust/ente_rust.dart';
-import 'package:ente_rust/src/rust/api/urls.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
+import 'package:photos/src/rust/api/urls.dart';
+import 'package:photos/src/rust/frb_generated.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
- await EnteRust.init();
+ await EntePhotosRust.init();
});
test('file_download_url integration smoke test', () {
diff --git a/mobile/apps/photos/ios/Podfile b/mobile/apps/photos/ios/Podfile
index 62398c9a39..98f19a79ee 100644
--- a/mobile/apps/photos/ios/Podfile
+++ b/mobile/apps/photos/ios/Podfile
@@ -51,7 +51,7 @@ post_install do |installer|
target.build_configurations.each do |config|
config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
- if ['ente_photos_rust', 'ente_rust'].include?(target.name) && config.name == 'Debug'
+ if target.name == 'ente_photos_rust' && config.name == 'Debug'
config.build_settings['ONLY_ACTIVE_ARCH[sdk=iphonesimulator*]'] = 'YES'
end
end
diff --git a/mobile/apps/photos/ios/Podfile.lock b/mobile/apps/photos/ios/Podfile.lock
index c0068c4246..50d423e5ce 100644
--- a/mobile/apps/photos/ios/Podfile.lock
+++ b/mobile/apps/photos/ios/Podfile.lock
@@ -26,8 +26,6 @@ PODS:
- Flutter
- ente_qr (0.0.1):
- Flutter
- - ente_rust (0.0.1):
- - Flutter
- ente_screen_brightness (0.0.1):
- Flutter
- ente_screen_cover (0.0.1):
@@ -257,7 +255,6 @@ DEPENDENCIES:
- ente_photos_platform (from `.symlinks/plugins/ente_photos_platform/ios`)
- ente_photos_rust (from `.symlinks/plugins/ente_photos_rust/ios`)
- ente_qr (from `.symlinks/plugins/ente_qr/ios`)
- - ente_rust (from `.symlinks/plugins/ente_rust/ios`)
- ente_screen_brightness (from `.symlinks/plugins/ente_screen_brightness/ios`)
- ente_screen_cover (from `.symlinks/plugins/ente_screen_cover/ios`)
- EnteOnnxRuntime (from `../../../../apple/packages/EnteOnnxRuntime/EnteOnnxRuntime.podspec`)
@@ -352,8 +349,6 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/ente_photos_rust/ios"
ente_qr:
:path: ".symlinks/plugins/ente_qr/ios"
- ente_rust:
- :path: ".symlinks/plugins/ente_rust/ios"
ente_screen_brightness:
:path: ".symlinks/plugins/ente_screen_brightness/ios"
ente_screen_cover:
@@ -457,9 +452,8 @@ SPEC CHECKSUMS:
ente_mail: 90753dd584f49ee092759a32d4143ca51db69641
ente_panorama_viewer: 87bb22e7868c3005314f80c05ee0787aa07edcd8
ente_photos_platform: 08757c7e4977863732f75ce0f85cc6144600e3d2
- ente_photos_rust: 2db1f31cbe3f13ef0f52909a52b1f885b880a6ec
+ ente_photos_rust: e217348178d710d624852c9a9ae8872c00b30366
ente_qr: 86beaf5d2644705db9b565b32dd8b82c05fb36af
- ente_rust: d0197ebd5460e8f67576579452b073d698404abe
ente_screen_brightness: 7dd13c361508ee6098a2578908ebf35e9f567e28
ente_screen_cover: 6792566774f1c83939f9c1d03ed0a1f1ded45ae4
EnteOnnxRuntime: c994300f7ef809dd318664cfd85868ca69b3cd1a
@@ -523,6 +517,6 @@ SPEC CHECKSUMS:
wakelock_plus: e29112ab3ef0b318e58cfa5c32326458be66b556
workmanager_apple: 904529ae31e97fc5be632cf628507652294a0778
-PODFILE CHECKSUM: fa8e5234255a5099bd36458ef38bf672d15117ff
+PODFILE CHECKSUM: 4450cf498e634fde2a46bbe657d08e05214be7b8
COCOAPODS: 1.17.0
diff --git a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
index c84b2aaeb3..a5fa37d398 100644
--- a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
+++ b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
@@ -640,7 +640,6 @@
"${BUILT_PRODUCTS_DIR}/ente_photos_platform/ente_photos_platform.framework",
"${BUILT_PRODUCTS_DIR}/ente_photos_rust/ente_photos_rust.framework",
"${BUILT_PRODUCTS_DIR}/ente_qr/ente_qr.framework",
- "${BUILT_PRODUCTS_DIR}/ente_rust/ente_rust.framework",
"${BUILT_PRODUCTS_DIR}/ente_screen_brightness/ente_screen_brightness.framework",
"${BUILT_PRODUCTS_DIR}/ente_screen_cover/ente_screen_cover.framework",
"${BUILT_PRODUCTS_DIR}/file_saver/file_saver.framework",
@@ -737,7 +736,6 @@
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_photos_platform.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_photos_rust.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_qr.framework",
- "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_rust.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_screen_brightness.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_screen_cover.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/file_saver.framework",
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index 5d019047f8..e4e445b94e 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -11,7 +11,6 @@ import "package:ente_lock_screen/lock_screen_settings.dart";
import "package:ente_lock_screen/ui/app_lock.dart";
import "package:ente_lock_screen/ui/lock_screen.dart";
import "package:ente_pure_utils/ente_pure_utils.dart";
-import "package:ente_rust/ente_rust.dart";
import "package:ente_strings/ente_strings.dart";
import "package:ente_ui/theme/theme_config.dart" as ente_ui;
import "package:ffmpeg_kit_flutter/ffmpeg_kit_config.dart";
@@ -87,7 +86,6 @@ bool _stopHearBeat = false;
bool _isSyncInitialized = false;
bool _isRustInitialized = false;
Future<void>? _rustInitFuture;
-late final LogSinkGuard _enteRustLogSinkGuard;
late final photos_rust_log.LogSinkGuard _photosRustLogSinkGuard;
enum ForegroundStartupMode { normal, picker }
@@ -570,7 +568,7 @@ Future<void> _ensureRustInitialized({required String via}) async {
return;
}
- final initFuture = Future.wait([EntePhotosRust.init(), EnteRust.init()]);
+ final initFuture = EntePhotosRust.init();
_rustInitFuture = initFuture;
try {
await initFuture;
@@ -583,10 +581,6 @@ Future<void> _ensureRustInitialized({required String via}) async {
void _attachRustLogStream() {
final logger = Logger("rust");
- _enteRustLogSinkGuard = LogSinkGuard();
- _enteRustLogSinkGuard.attachLogStream().listen((entry) {
- _logRustEntry(logger, entry.level.name, entry.target, entry.message);
- });
_photosRustLogSinkGuard = photos_rust_log.LogSinkGuard();
_photosRustLogSinkGuard.attachLogStream().listen((entry) {
_logRustEntry(logger, entry.level.name, entry.target, entry.message);
diff --git a/mobile/apps/photos/lib/services/frb_contacts_rust_api.dart b/mobile/apps/photos/lib/services/frb_contacts_rust_api.dart
new file mode 100644
index 0000000000..5efe8e7a2b
--- /dev/null
+++ b/mobile/apps/photos/lib/services/frb_contacts_rust_api.dart
@@ -0,0 +1,198 @@
+import 'dart:typed_data';
+
+import 'package:ente_contacts/contacts.dart';
+import 'package:photos/src/rust/api/contacts.dart' as rust;
+
+class FrbContactsRustApi implements ContactsRustApi {
+ const FrbContactsRustApi();
+
+ @override
+ Future<OpenContactsContextResult> open(OpenContactsContextInput input) async {
+ final result = await rust.openContactsCtx(
+ input: rust.OpenContactsCtxInput(
+ baseUrl: input.baseUrl,
+ authToken: input.authToken,
+ userId: input.userId,
+ masterKey: input.accountKey,
+ cachedWrappedRootContactKey: input.cachedWrappedRootContactKey == null
+ ? null
+ : rust.WrappedRootContactKey(
+ encryptedKey: input.cachedWrappedRootContactKey!.encryptedKey,
+ header: input.cachedWrappedRootContactKey!.header,
+ ),
+ userAgent: input.userAgent,
+ clientPackage: input.clientPackage,
+ clientVersion: input.clientVersion,
+ ),
+ );
+
+ return OpenContactsContextResult(
+ ctx: _FrbContactsRustContext(result.ctx),
+ wrappedRootContactKey: result.wrappedRootContactKey == null
+ ? null
+ : WrappedRootContactKey(
+ encryptedKey: result.wrappedRootContactKey!.encryptedKey,
+ header: result.wrappedRootContactKey!.header,
+ ),
+ rootKeySource: switch (result.rootKeySource) {
+ rust.RootKeySource.cache => RootKeySource.cache,
+ rust.RootKeySource.unresolved => RootKeySource.unresolved,
+ },
+ );
+ }
+}
+
+class _FrbContactsRustContext implements ContactsRustContext {
+ final rust.ContactsCtx _inner;
+
+ const _FrbContactsRustContext(this._inner);
+
+ @override
+ int userId() => _inner.userId();
+
+ @override
+ Future<void> updateAuthToken(String authToken) {
+ return _inner.updateAuthToken(authToken: authToken);
+ }
+
+ @override
+ WrappedRootContactKey? currentWrappedRootContactKey() {
+ final current = _inner.currentWrappedRootContactKey();
+ if (current == null) {
+ return null;
+ }
+ return WrappedRootContactKey(
+ encryptedKey: current.encryptedKey,
+ header: current.header,
+ );
+ }
+
+ @override
+ Future<ContactRecord> createContact(ContactData data) async {
+ return _fromRustRecord(
+ await _inner.createContact(
+ data: rust.ContactData(
+ contactUserId: data.contactUserId,
+ name: data.name,
+ ),
+ ),
+ );
+ }
+
+ @override
+ Future<ContactRecord> getContact(String contactId) async {
+ return _fromRustRecord(await _inner.getContact(contactId: contactId));
+ }
+
+ @override
+ Future<List<ContactRecord>> getDiff(int sinceTime, int limit) async {
+ final diff = await _inner.getDiff(sinceTime: sinceTime, limit: limit);
+ return diff.map(_fromRustRecord).toList(growable: false);
+ }
+
+ @override
+ Future<ContactRecord> updateContact(
+ String contactId,
+ ContactData data,
+ ) async {
+ return _fromRustRecord(
+ await _inner.updateContact(
+ contactId: contactId,
+ data: rust.ContactData(
+ contactUserId: data.contactUserId,
+ name: data.name,
+ ),
+ ),
+ );
+ }
+
+ @override
+ Future<void> deleteContact(String contactId) {
+ return _inner.deleteContact(contactId: contactId);
+ }
+
+ @override
+ Future<ContactRecord> setAttachment(
+ String contactId,
+ ContactAttachmentType attachmentType,
+ Uint8List attachmentBytes,
+ ) async {
+ return _fromRustRecord(
+ await _inner.setAttachment(
+ contactId: contactId,
+ attachmentType: _toRustAttachmentType(attachmentType),
+ attachmentBytes: attachmentBytes,
+ ),
+ );
+ }
+
+ @override
+ Future<Uint8List> getAttachment(
+ ContactAttachmentType attachmentType,
+ String attachmentId,
+ ) {
+ return _inner.getAttachmentEncrypted(
+ attachmentType: _toRustAttachmentType(attachmentType),
+ attachmentId: attachmentId,
+ );
+ }
+
+ @override
+ Future<ContactRecord> deleteAttachment(
+ String contactId,
+ ContactAttachmentType attachmentType,
+ ) async {
+ return _fromRustRecord(
+ await _inner.deleteAttachment(
+ contactId: contactId,
+ attachmentType: _toRustAttachmentType(attachmentType),
+ ),
+ );
+ }
+
+ @override
+ Future<ContactRecord> setProfilePicture(
+ String contactId,
+ Uint8List profilePicture,
+ ) async {
+ return setAttachment(
+ contactId,
+ ContactAttachmentType.profilePicture,
+ profilePicture,
+ );
+ }
+
+ @override
+ Future<Uint8List> getProfilePicture(String contactId) {
+ return _inner.getProfilePicture(contactId: contactId);
+ }
+
+ @override
+ Future<ContactRecord> deleteProfilePicture(String contactId) async {
+ return deleteAttachment(contactId, ContactAttachmentType.profilePicture);
+ }
+}
+
+rust.AttachmentType _toRustAttachmentType(
+ ContactAttachmentType attachmentType,
+) {
+ return switch (attachmentType) {
+ ContactAttachmentType.profilePicture => rust.AttachmentType.profilePicture,
+ };
+}
+
+ContactRecord _fromRustRecord(rust.ContactRecord record) {
+ final data = record.isDeleted
+ ? null
+ : ContactData(contactUserId: record.contactUserId, name: record.name!);
+ return ContactRecord(
+ id: record.id,
+ contactUserId: record.contactUserId,
+ email: record.email,
+ data: data,
+ profilePictureAttachmentId: record.profilePictureAttachmentId,
+ isDeleted: record.isDeleted,
+ createdAt: record.createdAt,
+ updatedAt: record.updatedAt,
+ );
+}
diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dart
index a981f08017..fe5bf59225 100644
--- a/mobile/apps/photos/lib/services/photos_contacts_service.dart
+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart
@@ -6,6 +6,7 @@ import "package:photos/core/event_bus.dart";
import "package:photos/events/contacts_changed_event.dart";
import "package:photos/events/user_logged_out_event.dart";
import "package:photos/service_locator.dart";
+import "package:photos/services/frb_contacts_rust_api.dart";
// Photos-specific session and event adapter for the shared contact directory.
class PhotosContactsService {
@@ -13,6 +14,7 @@ class PhotosContactsService {
: _store = contacts.ContactDirectory(
contactsServiceFactory: () => contacts.ContactsService(
preferences: ServiceLocator.instance.prefs,
+ rustApi: const FrbContactsRustApi(),
),
onContactsChanged: _notifyContactsChanged,
profilePictureFailureTtl: Duration.zero,
@@ -177,7 +179,7 @@ class PhotosContactsService {
} on StateError catch (error, stackTrace) {
if (_isRustInitializationError(error)) {
_logger.warning(
- "Contacts integration unavailable while Rust bindings are not initialized during $description. Photos initializes EntePhotosRust in main.dart, but ente_contacts calls into package:ente_rust.",
+ "Contacts integration unavailable while Rust bindings are not initialized during $description. Photos initializes EntePhotosRust in main.dart.",
error,
stackTrace,
);
diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yaml
index 93c4ab5047..f28899aa41 100644
--- a/mobile/apps/photos/pubspec.yaml
+++ b/mobile/apps/photos/pubspec.yaml
@@ -69,8 +69,6 @@ dependencies:
path: ../../packages/ente_qr
ente_qr_ui:
path: ../../packages/qr
- ente_rust:
- path: ../../packages/rust
ente_screen_brightness:
path: ../../packages/ente_screen_brightness
ente_strings:
diff --git a/mobile/packages/contacts/lib/contacts.dart b/mobile/packages/contacts/lib/contacts.dart
index 1af6c3fed9..5c70e8e384 100644
--- a/mobile/packages/contacts/lib/contacts.dart
+++ b/mobile/packages/contacts/lib/contacts.dart
@@ -4,6 +4,7 @@ export 'src/db/contacts_database.dart';
export 'src/models/contact_data.dart';
export 'src/models/contact_record.dart';
export 'src/models/contacts_session.dart';
+export 'src/rust/contacts_rust_api.dart';
export 'src/service/contact_directory.dart';
export 'src/service/contacts_display_service.dart';
export 'src/service/contacts_service.dart';
diff --git a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
index 7247cd0007..a260c61dea 100644
--- a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
+++ b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
@@ -2,7 +2,6 @@ import 'dart:typed_data';
import 'package:ente_contacts/src/models/contact_data.dart';
import 'package:ente_contacts/src/models/contact_record.dart';
-import 'package:ente_rust/ente_rust.dart' as rust;
class WrappedRootContactKey {
final String encryptedKey;
@@ -98,197 +97,3 @@ abstract class ContactsRustContext {
abstract class ContactsRustApi {
Future<OpenContactsContextResult> open(OpenContactsContextInput input);
}
-
-class FrbContactsRustApi implements ContactsRustApi {
- const FrbContactsRustApi();
-
- @override
- Future<OpenContactsContextResult> open(OpenContactsContextInput input) async {
- final result = await rust.openContactsCtx(
- input: rust.OpenContactsCtxInput(
- baseUrl: input.baseUrl,
- authToken: input.authToken,
- userId: input.userId,
- masterKey: input.accountKey,
- cachedWrappedRootContactKey: input.cachedWrappedRootContactKey == null
- ? null
- : rust.WrappedRootContactKey(
- encryptedKey: input.cachedWrappedRootContactKey!.encryptedKey,
- header: input.cachedWrappedRootContactKey!.header,
- ),
- userAgent: input.userAgent,
- clientPackage: input.clientPackage,
- clientVersion: input.clientVersion,
- ),
- );
-
- return OpenContactsContextResult(
- ctx: _FrbContactsRustContext(result.ctx),
- wrappedRootContactKey: result.wrappedRootContactKey == null
- ? null
- : WrappedRootContactKey(
- encryptedKey: result.wrappedRootContactKey!.encryptedKey,
- header: result.wrappedRootContactKey!.header,
- ),
- rootKeySource: switch (result.rootKeySource) {
- rust.RootKeySource.cache => RootKeySource.cache,
- rust.RootKeySource.unresolved => RootKeySource.unresolved,
- },
- );
- }
-}
-
-class _FrbContactsRustContext implements ContactsRustContext {
- final rust.ContactsCtx _inner;
-
- const _FrbContactsRustContext(this._inner);
-
- @override
- int userId() => _inner.userId();
-
- @override
- Future<void> updateAuthToken(String authToken) {
- return _inner.updateAuthToken(authToken: authToken);
- }
-
- @override
- WrappedRootContactKey? currentWrappedRootContactKey() {
- final current = _inner.currentWrappedRootContactKey();
- if (current == null) {
- return null;
- }
- return WrappedRootContactKey(
- encryptedKey: current.encryptedKey,
- header: current.header,
- );
- }
-
- @override
- Future<ContactRecord> createContact(ContactData data) async {
- return _fromRustRecord(
- await _inner.createContact(
- data: rust.ContactData(
- contactUserId: data.contactUserId,
- name: data.name,
- ),
- ),
- );
- }
-
- @override
- Future<ContactRecord> getContact(String contactId) async {
- return _fromRustRecord(await _inner.getContact(contactId: contactId));
- }
-
- @override
- Future<List<ContactRecord>> getDiff(int sinceTime, int limit) async {
- final diff = await _inner.getDiff(sinceTime: sinceTime, limit: limit);
- return diff.map(_fromRustRecord).toList(growable: false);
- }
-
- @override
- Future<ContactRecord> updateContact(
- String contactId,
- ContactData data,
- ) async {
- return _fromRustRecord(
- await _inner.updateContact(
- contactId: contactId,
- data: rust.ContactData(
- contactUserId: data.contactUserId,
- name: data.name,
- ),
- ),
- );
- }
-
- @override
- Future<void> deleteContact(String contactId) {
- return _inner.deleteContact(contactId: contactId);
- }
-
- @override
- Future<ContactRecord> setAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- Uint8List attachmentBytes,
- ) async {
- return _fromRustRecord(
- await _inner.setAttachment(
- contactId: contactId,
- attachmentType: _toRustAttachmentType(attachmentType),
- attachmentBytes: attachmentBytes,
- ),
- );
- }
-
- @override
- Future<Uint8List> getAttachment(
- ContactAttachmentType attachmentType,
- String attachmentId,
- ) {
- return _inner.getAttachmentEncrypted(
- attachmentType: _toRustAttachmentType(attachmentType),
- attachmentId: attachmentId,
- );
- }
-
- @override
- Future<ContactRecord> deleteAttachment(
- String contactId,
- ContactAttachmentType attachmentType,
- ) async {
- return _fromRustRecord(
- await _inner.deleteAttachment(
- contactId: contactId,
- attachmentType: _toRustAttachmentType(attachmentType),
- ),
- );
- }
-
- @override
- Future<ContactRecord> setProfilePicture(
- String contactId,
- Uint8List profilePicture,
- ) async {
- return setAttachment(
- contactId,
- ContactAttachmentType.profilePicture,
- profilePicture,
- );
- }
-
- @override
- Future<Uint8List> getProfilePicture(String contactId) {
- return _inner.getProfilePicture(contactId: contactId);
- }
-
- @override
- Future<ContactRecord> deleteProfilePicture(String contactId) async {
- return deleteAttachment(contactId, ContactAttachmentType.profilePicture);
- }
-}
-
-rust.AttachmentType _toRustAttachmentType(
- ContactAttachmentType attachmentType,
-) {
- return switch (attachmentType) {
- ContactAttachmentType.profilePicture => rust.AttachmentType.profilePicture,
- };
-}
-
-ContactRecord _fromRustRecord(rust.ContactRecord record) {
- final data = record.isDeleted
- ? null
- : ContactData(contactUserId: record.contactUserId, name: record.name!);
- return ContactRecord(
- id: record.id,
- contactUserId: record.contactUserId,
- email: record.email,
- data: data,
- profilePictureAttachmentId: record.profilePictureAttachmentId,
- isDeleted: record.isDeleted,
- createdAt: record.createdAt,
- updatedAt: record.updatedAt,
- );
-}
diff --git a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
index 12c531989c..251096ae33 100644
--- a/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
+++ b/mobile/packages/contacts/lib/src/service/contacts_display_service.dart
@@ -1,5 +1,6 @@
import 'package:ente_contacts/src/models/contact_record.dart';
import 'package:ente_contacts/src/models/contacts_session.dart';
+import 'package:ente_contacts/src/rust/contacts_rust_api.dart';
import 'package:ente_contacts/src/service/contact_directory.dart';
import 'package:ente_contacts/src/service/contacts_service.dart';
import 'package:flutter/foundation.dart';
@@ -29,13 +30,22 @@ class ContactsDisplayService {
required SharedPreferences preferences,
ContactsService? contactsService,
ContactsService Function()? contactsServiceFactory,
+ ContactsRustApi? rustApi,
}) {
+ if (contactsService == null &&
+ contactsServiceFactory == null &&
+ rustApi == null) {
+ throw ArgumentError(
+ 'rustApi is required when no contacts service or factory is given',
+ );
+ }
_store = ContactDirectory(
contactsService: contactsService,
contactsServiceFactory:
contactsServiceFactory ??
(contactsService == null
- ? () => ContactsService(preferences: preferences)
+ ? () =>
+ ContactsService(preferences: preferences, rustApi: rustApi!)
: null),
);
}
diff --git a/mobile/packages/contacts/lib/src/service/contacts_service.dart b/mobile/packages/contacts/lib/src/service/contacts_service.dart
index 49ffa2575d..0f0f3d473a 100644
--- a/mobile/packages/contacts/lib/src/service/contacts_service.dart
+++ b/mobile/packages/contacts/lib/src/service/contacts_service.dart
@@ -15,11 +15,11 @@ class ContactsService {
ContactsService({
required SharedPreferences preferences,
+ required ContactsRustApi rustApi,
ContactsDatabase? database,
- ContactsRustApi? rustApi,
}) : _preferences = preferences,
_database = database ?? ContactsDatabase(),
- _rustApi = rustApi ?? const FrbContactsRustApi();
+ _rustApi = rustApi;
final SharedPreferences _preferences;
final ContactsDatabase _database;
diff --git a/mobile/packages/contacts/pubspec.yaml b/mobile/packages/contacts/pubspec.yaml
index 1ed5476ba5..43ed7db54e 100644
--- a/mobile/packages/contacts/pubspec.yaml
+++ b/mobile/packages/contacts/pubspec.yaml
@@ -7,8 +7,6 @@ environment:
flutter: ">=1.17.0"
dependencies:
- ente_rust:
- path: ../rust
flutter:
sdk: flutter
logging: 1.3.0
diff --git a/mobile/packages/contacts/test/contacts_display_service_test.dart b/mobile/packages/contacts/test/contacts_display_service_test.dart
index 7fca86a140..7ed9db2d2d 100644
--- a/mobile/packages/contacts/test/contacts_display_service_test.dart
+++ b/mobile/packages/contacts/test/contacts_display_service_test.dart
@@ -3,7 +3,6 @@ import 'dart:io';
import 'dart:typed_data';
import 'package:ente_contacts/contacts.dart';
-import 'package:ente_contacts/src/rust/contacts_rust_api.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
diff --git a/mobile/packages/contacts/test/contacts_service_test.dart b/mobile/packages/contacts/test/contacts_service_test.dart
index fc017577e5..db4efa2529 100644
--- a/mobile/packages/contacts/test/contacts_service_test.dart
+++ b/mobile/packages/contacts/test/contacts_service_test.dart
@@ -2,7 +2,6 @@ import 'dart:io';
import 'dart:typed_data';
import 'package:ente_contacts/contacts.dart';
-import 'package:ente_contacts/src/rust/contacts_rust_api.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
diff --git a/mobile/packages/legacy/lib/models/legacy_kit_models.dart b/mobile/packages/legacy/lib/models/legacy_kit_models.dart
index 2e0257cf3d..85e23f36fa 100644
--- a/mobile/packages/legacy/lib/models/legacy_kit_models.dart
+++ b/mobile/packages/legacy/lib/models/legacy_kit_models.dart
@@ -1,7 +1,5 @@
import "dart:convert";
-import "package:ente_rust/ente_rust.dart" as rust;
-
enum LegacyKitRecoveryStatus { waiting, ready, blocked, cancelled, recovered }
class LegacyKitRecoverySession {
@@ -20,18 +18,6 @@ class LegacyKitRecoverySession {
required this.waitTill,
required this.createdAt,
});
-
- factory LegacyKitRecoverySession.fromRust(
- rust.LegacyKitRecoverySession session,
- ) {
- return LegacyKitRecoverySession(
- id: session.id,
- kitId: session.kitId,
- status: _statusFromRust(session.status),
- waitTill: session.waitTill,
- createdAt: session.createdAt,
- );
- }
}
class LegacyKitRecoveryInitiatorHint {
@@ -44,16 +30,6 @@ class LegacyKitRecoveryInitiatorHint {
required this.ip,
required this.userAgent,
});
-
- factory LegacyKitRecoveryInitiatorHint.fromRust(
- rust.LegacyKitRecoveryInitiatorHint hint,
- ) {
- return LegacyKitRecoveryInitiatorHint(
- usedPartIndexes: hint.usedPartIndexes,
- ip: hint.ip,
- userAgent: hint.userAgent,
- );
- }
}
class LegacyKitOwnerRecoverySessionDetails {
@@ -64,19 +40,6 @@ class LegacyKitOwnerRecoverySessionDetails {
required this.session,
required this.initiators,
});
-
- factory LegacyKitOwnerRecoverySessionDetails.fromRust(
- rust.LegacyKitOwnerRecoverySessionDetails details,
- ) {
- return LegacyKitOwnerRecoverySessionDetails(
- session: details.session == null
- ? null
- : LegacyKitRecoverySession.fromRust(details.session!),
- initiators: details.initiators
- .map(LegacyKitRecoveryInitiatorHint.fromRust)
- .toList(growable: false),
- );
- }
}
class LegacyKitPart {
@@ -84,10 +47,6 @@ class LegacyKitPart {
final String name;
const LegacyKitPart({required this.index, required this.name});
-
- factory LegacyKitPart.fromRust(rust.LegacyKitPart part) {
- return LegacyKitPart(index: part.index, name: part.name);
- }
}
class LegacyKit {
@@ -109,22 +68,6 @@ class LegacyKit {
required this.activeRecoverySession,
});
- factory LegacyKit.fromRust(rust.LegacyKit kit) {
- return LegacyKit(
- id: kit.id,
- noticePeriodInHours: kit.noticePeriodInHours,
- legacyUrl: kit.legacyUrl,
- parts: kit.metadata.parts
- .map(LegacyKitPart.fromRust)
- .toList(growable: false),
- createdAt: kit.createdAt,
- updatedAt: kit.updatedAt,
- activeRecoverySession: kit.activeRecoverySession == null
- ? null
- : LegacyKitRecoverySession.fromRust(kit.activeRecoverySession!),
- );
- }
-
String get displayName => parts.map((part) => part.name).join(" Β· ");
bool get hasActiveRecoverySession => activeRecoverySession != null;
@@ -149,18 +92,6 @@ class LegacyKitShare {
required this.partName,
});
- factory LegacyKitShare.fromRust(rust.LegacyKitShare share) {
- return LegacyKitShare(
- payloadVersion: share.payloadVersion,
- variant: _variantToCode(share.variant),
- kitId: share.kitId,
- shareIndex: share.shareIndex,
- share: share.share,
- checksum: share.checksum,
- partName: share.partName,
- );
- }
-
String toQrPayload() {
return jsonEncode({
"pv": payloadVersion,
@@ -187,29 +118,4 @@ class LegacyKitCreateResult {
final List<LegacyKitShare> shares;
const LegacyKitCreateResult({required this.kit, required this.shares});
-
- factory LegacyKitCreateResult.fromRust(rust.LegacyKitCreateResult result) {
- return LegacyKitCreateResult(
- kit: LegacyKit.fromRust(result.kit),
- shares: result.shares
- .map(LegacyKitShare.fromRust)
- .toList(growable: false),
- );
- }
-}
-
-LegacyKitRecoveryStatus _statusFromRust(rust.LegacyKitRecoveryStatus status) {
- return switch (status) {
- rust.LegacyKitRecoveryStatus.waiting => LegacyKitRecoveryStatus.waiting,
- rust.LegacyKitRecoveryStatus.ready => LegacyKitRecoveryStatus.ready,
- rust.LegacyKitRecoveryStatus.blocked => LegacyKitRecoveryStatus.blocked,
- rust.LegacyKitRecoveryStatus.cancelled => LegacyKitRecoveryStatus.cancelled,
- rust.LegacyKitRecoveryStatus.recovered => LegacyKitRecoveryStatus.recovered,
- };
-}
-
-int _variantToCode(rust.LegacyKitVariant variant) {
- return switch (variant) {
- rust.LegacyKitVariant.twoOfThree => 1,
- };
}
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 84cf4865e8..cfeb3910d3 100644
--- a/mobile/packages/legacy/lib/pages/share_legacy_kit_page.dart
+++ b/mobile/packages/legacy/lib/pages/share_legacy_kit_page.dart
@@ -10,9 +10,9 @@ import "package:ente_legacy/models/legacy_kit_models.dart";
import "package:ente_legacy/pages/legacy_congratulations_page.dart";
import "package:ente_legacy/services/legacy_kit_local_settings.dart";
import "package:ente_legacy/services/legacy_kit_pdf_service.dart";
+import "package:ente_legacy/services/legacy_kit_rust_api.dart";
import "package:ente_legacy/services/legacy_kit_service.dart";
import "package:ente_legacy/services/legacy_kit_share_file_service.dart";
-import "package:ente_rust/ente_rust.dart" as rust;
import "package:ente_strings/ente_strings.dart";
import "package:ente_ui/components/alert_bottom_sheet.dart";
import "package:ente_ui/utils/dialog_util.dart";
@@ -488,7 +488,7 @@ class _ShareLegacyKitPageState extends State<ShareLegacyKitPage> {
}
if (updateError == null) {
showShortToast(context, context.strings.recoveryTimeUpdated);
- } else if (updateError is rust.ContactsError_ActiveRecoverySession) {
+ } else if (updateError is LegacyKitActiveRecoverySessionException) {
try {
await _refreshKit();
} catch (_) {
diff --git a/mobile/packages/legacy/lib/services/legacy_kit_rust_api.dart b/mobile/packages/legacy/lib/services/legacy_kit_rust_api.dart
new file mode 100644
index 0000000000..85e396211e
--- /dev/null
+++ b/mobile/packages/legacy/lib/services/legacy_kit_rust_api.dart
@@ -0,0 +1,41 @@
+import "dart:typed_data";
+
+import "package:ente_base/models/key_attributes.dart";
+import "package:ente_contacts/contacts.dart" as contacts;
+import "package:ente_legacy/models/legacy_kit_models.dart";
+
+class LegacyKitActiveRecoverySessionException implements Exception {}
+
+abstract class LegacyKitRustContext {
+ Future<void> updateAuthToken(String authToken);
+
+ Future<List<LegacyKit>> legacyKits();
+
+ Future<LegacyKitCreateResult> legacyKitCreate({
+ required KeyAttributes currentUserKeyAttrs,
+ required List<String> partNames,
+ required int noticePeriodInHours,
+ });
+
+ Future<List<LegacyKitShare>> legacyKitDownloadShares(String kitId);
+
+ Future<LegacyKitOwnerRecoverySessionDetails> legacyKitRecoverySession(
+ String kitId,
+ );
+
+ Future<void> legacyKitUpdateRecoveryNotice({
+ required String kitId,
+ required int noticePeriodInHours,
+ });
+
+ Future<void> legacyKitBlockRecovery(String kitId);
+
+ Future<void> legacyKitDelete(String kitId);
+}
+
+abstract class LegacyKitRustApi {
+ Future<LegacyKitRustContext> open(
+ contacts.ContactsSession session,
+ Uint8List accountKey,
+ );
+}
diff --git a/mobile/packages/legacy/lib/services/legacy_kit_service.dart b/mobile/packages/legacy/lib/services/legacy_kit_service.dart
index 4b1f25e36a..9d5c13d897 100644
--- a/mobile/packages/legacy/lib/services/legacy_kit_service.dart
+++ b/mobile/packages/legacy/lib/services/legacy_kit_service.dart
@@ -1,13 +1,12 @@
import "dart:async";
-import "package:ente_base/models/key_attributes.dart" as base;
import "package:ente_configuration/base_configuration.dart";
import "package:ente_contacts/contacts.dart" as contacts;
import "package:ente_events/event_bus.dart";
import "package:ente_legacy/events/legacy_kit_created_event.dart";
import "package:ente_legacy/models/legacy_kit_models.dart";
+import "package:ente_legacy/services/legacy_kit_rust_api.dart";
import "package:ente_legacy/services/legacy_kit_share_file_service.dart";
-import "package:ente_rust/ente_rust.dart" as rust;
import "package:logging/logging.dart";
typedef LegacyKitSessionProvider = contacts.ContactsSession? Function();
@@ -22,26 +21,29 @@ class LegacyKitService {
BaseConfiguration? _config;
LegacyKitSessionProvider? _sessionProvider;
- rust.ContactsCtx? _ctx;
+ LegacyKitRustApi? _rustApi;
+ LegacyKitRustContext? _ctx;
String? _ctxBaseUrl;
int? _ctxUserId;
String? _ctxAuthToken;
- bool get isInitialized => _config != null && _sessionProvider != null;
+ bool get isInitialized =>
+ _config != null && _sessionProvider != null && _rustApi != null;
Future<void> init({
required BaseConfiguration config,
required LegacyKitSessionProvider sessionProvider,
+ required LegacyKitRustApi rustApi,
}) async {
_config = config;
_sessionProvider = sessionProvider;
+ _rustApi = rustApi;
unawaited(cleanStaleLegacyKitShareFiles());
}
Future<List<LegacyKit>> getKits() async {
final ctx = await _requireCtx();
- final kits = await ctx.legacyKits();
- return kits.map(LegacyKit.fromRust).toList(growable: false);
+ return ctx.legacyKits();
}
Future<LegacyKitCreateResult> createKit({
@@ -60,28 +62,25 @@ class LegacyKitService {
throw StateError("Missing account key attributes");
}
final ctx = await _requireCtx();
- final result = await ctx.legacyKitCreate(
- currentUserKeyAttrs: _toRustKeyAttributes(keyAttributes),
+ final createdKit = await ctx.legacyKitCreate(
+ currentUserKeyAttrs: keyAttributes,
partNames: partNames,
noticePeriodInHours: noticePeriodInHours,
);
- final createdKit = LegacyKitCreateResult.fromRust(result);
Bus.instance.fire(LegacyKitCreatedEvent());
return createdKit;
}
Future<List<LegacyKitShare>> downloadShares(String kitId) async {
final ctx = await _requireCtx();
- final shares = await ctx.legacyKitDownloadShares(kitId: kitId);
- return shares.map(LegacyKitShare.fromRust).toList(growable: false);
+ return ctx.legacyKitDownloadShares(kitId);
}
Future<LegacyKitOwnerRecoverySessionDetails> getRecoverySession(
String kitId,
) async {
final ctx = await _requireCtx();
- final details = await ctx.legacyKitRecoverySession(kitId: kitId);
- return LegacyKitOwnerRecoverySessionDetails.fromRust(details);
+ return ctx.legacyKitRecoverySession(kitId);
}
Future<void> updateRecoveryNotice({
@@ -97,12 +96,12 @@ class LegacyKitService {
Future<void> blockRecovery(String kitId) async {
final ctx = await _requireCtx();
- await ctx.legacyKitBlockRecovery(kitId: kitId);
+ await ctx.legacyKitBlockRecovery(kitId);
}
Future<void> deleteKit(String kitId) async {
final ctx = await _requireCtx();
- await ctx.legacyKitDelete(kitId: kitId);
+ await ctx.legacyKitDelete(kitId);
}
BaseConfiguration _requireConfig() {
@@ -113,9 +112,10 @@ class LegacyKitService {
return config;
}
- Future<rust.ContactsCtx> _requireCtx() async {
+ Future<LegacyKitRustContext> _requireCtx() async {
final provider = _sessionProvider;
- if (provider == null) {
+ final rustApi = _rustApi;
+ if (provider == null || rustApi == null) {
throw StateError("LegacyKitService has not been initialized");
}
final session = provider();
@@ -127,7 +127,7 @@ class LegacyKitService {
_ctxBaseUrl == session.baseUrl &&
_ctxUserId == session.userId) {
if (_ctxAuthToken != session.authToken) {
- await existing.updateAuthToken(authToken: session.authToken);
+ await existing.updateAuthToken(session.authToken);
_ctxAuthToken = session.authToken;
}
return existing;
@@ -135,42 +135,11 @@ class LegacyKitService {
final accountKey = await session.resolveAccountKey();
_logger.info("Opening legacy kit Rust context for user ${session.userId}");
- final opened = await rust.openContactsCtx(
- input: rust.OpenContactsCtxInput(
- baseUrl: session.baseUrl,
- authToken: session.authToken,
- userId: session.userId,
- masterKey: accountKey,
- userAgent: session.userAgent,
- clientPackage: session.clientPackage,
- clientVersion: session.clientVersion,
- ),
- );
- _ctx = opened.ctx;
+ final opened = await rustApi.open(session, accountKey);
+ _ctx = opened;
_ctxBaseUrl = session.baseUrl;
_ctxUserId = session.userId;
_ctxAuthToken = session.authToken;
- return opened.ctx;
- }
-
- rust.AccountKeyAttributes _toRustKeyAttributes(
- base.KeyAttributes attributes,
- ) {
- return rust.AccountKeyAttributes(
- kekSalt: attributes.kekSalt,
- encryptedKey: attributes.encryptedKey,
- keyDecryptionNonce: attributes.keyDecryptionNonce,
- publicKey: attributes.publicKey,
- encryptedSecretKey: attributes.encryptedSecretKey,
- secretKeyDecryptionNonce: attributes.secretKeyDecryptionNonce,
- memLimit: attributes.memLimit,
- opsLimit: attributes.opsLimit,
- masterKeyEncryptedWithRecoveryKey:
- attributes.masterKeyEncryptedWithRecoveryKey,
- masterKeyDecryptionNonce: attributes.masterKeyDecryptionNonce,
- recoveryKeyEncryptedWithMasterKey:
- attributes.recoveryKeyEncryptedWithMasterKey,
- recoveryKeyDecryptionNonce: attributes.recoveryKeyDecryptionNonce,
- );
+ return opened;
}
}
diff --git a/mobile/packages/legacy/pubspec.yaml b/mobile/packages/legacy/pubspec.yaml
index df22d0cc61..b837197f76 100644
--- a/mobile/packages/legacy/pubspec.yaml
+++ b/mobile/packages/legacy/pubspec.yaml
@@ -28,8 +28,6 @@ dependencies:
path: ../network
ente_pure_utils:
path: ../ente_pure_utils
- ente_rust:
- path: ../rust
ente_sharing:
path: ../sharing
ente_strings:
diff --git a/mobile/packages/rust/.gitignore b/mobile/packages/rust/.gitignore
deleted file mode 100644
index d776a6ebb3..0000000000
--- a/mobile/packages/rust/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# Generated FRB Dart bindings
-lib/src/rust/
diff --git a/mobile/packages/rust/.metadata b/mobile/packages/rust/.metadata
deleted file mode 100644
index 0be21c54e2..0000000000
--- a/mobile/packages/rust/.metadata
+++ /dev/null
@@ -1,42 +0,0 @@
-# This file tracks properties of this Flutter project.
-# Used by Flutter tool to assess capabilities and perform upgrades etc.
-#
-# This file should be version controlled and should not be manually edited.
-
-version:
- revision: "edada7c56edf4a183c1735310e123c7f923584f1"
- channel: "[user-branch]"
-
-project_type: plugin_ffi
-
-# Tracks metadata for the flutter migrate command
-migration:
- platforms:
- - platform: root
- create_revision: edada7c56edf4a183c1735310e123c7f923584f1
- base_revision: edada7c56edf4a183c1735310e123c7f923584f1
- - platform: android
- create_revision: edada7c56edf4a183c1735310e123c7f923584f1
- base_revision: edada7c56edf4a183c1735310e123c7f923584f1
- - platform: ios
- create_revision: edada7c56edf4a183c1735310e123c7f923584f1
- base_revision: edada7c56edf4a183c1735310e123c7f923584f1
- - platform: linux
- create_revision: edada7c56edf4a183c1735310e123c7f923584f1
- base_revision: edada7c56edf4a183c1735310e123c7f923584f1
- - platform: macos
- create_revision: edada7c56edf4a183c1735310e123c7f923584f1
- base_revision: edada7c56edf4a183c1735310e123c7f923584f1
- - platform: windows
- create_revision: edada7c56edf4a183c1735310e123c7f923584f1
- base_revision: edada7c56edf4a183c1735310e123c7f923584f1
-
- # User provided section
-
- # List of Local paths (relative to this file) that should be
- # ignored by the migrate tool.
- #
- # Files that are not part of the templates will be ignored by default.
- unmanaged_files:
- - 'lib/main.dart'
- - 'ios/Runner.xcodeproj/project.pbxproj'
diff --git a/mobile/packages/rust/analysis_options.yaml b/mobile/packages/rust/analysis_options.yaml
deleted file mode 100644
index 02d5905545..0000000000
--- a/mobile/packages/rust/analysis_options.yaml
+++ /dev/null
@@ -1,6 +0,0 @@
-include: package:flutter_lints/flutter.yaml
-
-analyzer:
- exclude:
- - lib/src/rust/**
- - cargokit/**
diff --git a/mobile/packages/rust/android/build.gradle b/mobile/packages/rust/android/build.gradle
deleted file mode 100644
index 1744815b9f..0000000000
--- a/mobile/packages/rust/android/build.gradle
+++ /dev/null
@@ -1,49 +0,0 @@
-group 'com.flutter_rust_bridge.ente_rust'
-version '1.0'
-
-buildscript {
- repositories {
- google()
- mavenCentral()
- }
-
- dependencies {
- classpath 'com.android.tools.build:gradle:7.3.0'
- }
-}
-
-rootProject.allprojects {
- repositories {
- google()
- mavenCentral()
- }
-}
-
-apply plugin: 'com.android.library'
-
-android {
- if (project.android.hasProperty("namespace")) {
- namespace 'com.flutter_rust_bridge.ente_rust'
- }
-
- // Bumping the plugin compileSdkVersion requires all clients of this plugin
- // to bump the version in their app.
- compileSdkVersion 33
-
- ndkVersion "28.2.13676358"
-
- compileOptions {
- sourceCompatibility JavaVersion.VERSION_1_8
- targetCompatibility JavaVersion.VERSION_1_8
- }
-
- defaultConfig {
- minSdkVersion 19
- }
-}
-
-apply from: "../cargokit/gradle/plugin.gradle"
-cargokit {
- manifestDir = "../../../../rust/bindings/frb/ente-rust"
- libname = "ente_rust"
-}
diff --git a/mobile/packages/rust/android/settings.gradle b/mobile/packages/rust/android/settings.gradle
deleted file mode 100644
index 7d37d5b30f..0000000000
--- a/mobile/packages/rust/android/settings.gradle
+++ /dev/null
@@ -1 +0,0 @@
-rootProject.name = 'ente_rust'
diff --git a/mobile/packages/rust/android/src/main/AndroidManifest.xml b/mobile/packages/rust/android/src/main/AndroidManifest.xml
deleted file mode 100644
index 25e608883c..0000000000
--- a/mobile/packages/rust/android/src/main/AndroidManifest.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.flutter_rust_bridge.ente_rust">
-</manifest>
diff --git a/mobile/packages/rust/cargokit/.gitignore b/mobile/packages/rust/cargokit/.gitignore
deleted file mode 100644
index 2f7896d1d1..0000000000
--- a/mobile/packages/rust/cargokit/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-target/
diff --git a/mobile/packages/rust/cargokit/LICENSE b/mobile/packages/rust/cargokit/LICENSE
deleted file mode 100644
index d33a5fea52..0000000000
--- a/mobile/packages/rust/cargokit/LICENSE
+++ /dev/null
@@ -1,42 +0,0 @@
-/// This is copied from Cargokit (which is the official way to use it currently)
-/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-Copyright 2022 Matej Knopp
-
-================================================================================
-
-MIT LICENSE
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-of the Software, and to permit persons to whom the Software is furnished to do
-so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
-OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
-IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-================================================================================
-
-APACHE LICENSE, VERSION 2.0
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-
diff --git a/mobile/packages/rust/cargokit/README b/mobile/packages/rust/cargokit/README
deleted file mode 100644
index 398474dbc8..0000000000
--- a/mobile/packages/rust/cargokit/README
+++ /dev/null
@@ -1,11 +0,0 @@
-/// This is copied from Cargokit (which is the official way to use it currently)
-/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-Experimental repository to provide glue for seamlessly integrating cargo build
-with flutter plugins and packages.
-
-See https://matejknopp.com/post/flutter_plugin_in_rust_with_no_prebuilt_binaries/
-for a tutorial on how to use Cargokit.
-
-Example plugin available at https://github.com/irondash/hello_rust_ffi_plugin.
-
diff --git a/mobile/packages/rust/cargokit/build_pod.sh b/mobile/packages/rust/cargokit/build_pod.sh
deleted file mode 100755
index acf0115892..0000000000
--- a/mobile/packages/rust/cargokit/build_pod.sh
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/bin/sh
-set -e
-
-BASEDIR=$(dirname "$0")
-
-# Workaround for https://github.com/dart-lang/pub/issues/4010
-BASEDIR=$(cd "$BASEDIR" ; pwd -P)
-
-# Remove XCode SDK from path. Otherwise this breaks tool compilation when building iOS project
-NEW_PATH=`echo $PATH | tr ":" "\n" | grep -v "Contents/Developer/" | tr "\n" ":"`
-
-export PATH=${NEW_PATH%?} # remove trailing :
-
-env
-
-export CARGOKIT_DARWIN_PLATFORM_NAME=$PLATFORM_NAME
-
-export CARGOKIT_DARWIN_ARCHS=$ARCHS
-
-export CARGOKIT_CONFIGURATION=$CONFIGURATION
-
-export CARGOKIT_MANIFEST_DIR=$PODS_TARGET_SRCROOT/$1
-
-export CARGOKIT_TARGET_TEMP_DIR=$TARGET_TEMP_DIR
-
-export CARGOKIT_OUTPUT_DIR=$PODS_CONFIGURATION_BUILD_DIR/$PRODUCT_NAME
-
-export CARGOKIT_TOOL_TEMP_DIR=$TARGET_TEMP_DIR/build_tool
-
-export CARGOKIT_ROOT_PROJECT_DIR=$SRCROOT
-
-FLUTTER_EXPORT_BUILD_ENVIRONMENT=(
- "$PODS_ROOT/../Flutter/ephemeral/flutter_export_environment.sh" # macOS
- "$PODS_ROOT/../Flutter/flutter_export_environment.sh" # iOS
-)
-
-for path in "${FLUTTER_EXPORT_BUILD_ENVIRONMENT[@]}"
-do
- if [[ -f "$path" ]]; then
- source "$path"
- fi
-done
-
-sh "$BASEDIR/run_build_tool.sh" build-pod "$@"
-
-# Make a symlink from built framework to phony file, which will be used as input to
-# build script. This should force rebuild (podspec currently doesn't support alwaysOutOfDate
-# attribute on custom build phase)
-ln -fs "$OBJROOT/XCBuildData/build.db" "${BUILT_PRODUCTS_DIR}/cargokit_phony"
-ln -fs "${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}" "${BUILT_PRODUCTS_DIR}/cargokit_phony_out"
diff --git a/mobile/packages/rust/cargokit/build_tool/README.md b/mobile/packages/rust/cargokit/build_tool/README.md
deleted file mode 100644
index a878c27964..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-/// This is copied from Cargokit (which is the official way to use it currently)
-/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-A sample command-line application with an entrypoint in `bin/`, library code
-in `lib/`, and example unit test in `test/`.
diff --git a/mobile/packages/rust/cargokit/build_tool/analysis_options.yaml b/mobile/packages/rust/cargokit/build_tool/analysis_options.yaml
deleted file mode 100644
index 2f58c85614..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/analysis_options.yaml
+++ /dev/null
@@ -1,9 +0,0 @@
-# This is copied from Cargokit (which is the official way to use it currently)
-# Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-include: package:lints/recommended.yaml
-
-linter:
- rules:
- - prefer_relative_imports
- - directives_ordering
diff --git a/mobile/packages/rust/cargokit/build_tool/bin/build_tool.dart b/mobile/packages/rust/cargokit/build_tool/bin/build_tool.dart
deleted file mode 100644
index 1bd58423b8..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/bin/build_tool.dart
+++ /dev/null
@@ -1,8 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'package:build_tool/build_tool.dart' as build_tool;
-
-void main(List<String> arguments) {
- build_tool.runMain(arguments);
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/build_tool.dart b/mobile/packages/rust/cargokit/build_tool/lib/build_tool.dart
deleted file mode 100644
index 09fabf2ceb..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/build_tool.dart
+++ /dev/null
@@ -1,8 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'src/build_tool.dart' as build_tool;
-
-Future<void> runMain(List<String> args) async {
- return build_tool.runMain(args);
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/android_environment.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/android_environment.dart
deleted file mode 100644
index 8811bdae6d..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/android_environment.dart
+++ /dev/null
@@ -1,188 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-import 'dart:isolate';
-import 'dart:math' as math;
-
-import 'package:collection/collection.dart';
-import 'package:path/path.dart' as path;
-import 'package:version/version.dart';
-
-import 'target.dart';
-import 'util.dart';
-
-class AndroidEnvironment {
- AndroidEnvironment({
- required this.sdkPath,
- required this.ndkVersion,
- required this.minSdkVersion,
- required this.targetTempDir,
- required this.target,
- });
-
- static void clangLinkerWrapper(List<String> args) {
- final clang = Platform.environment['_CARGOKIT_NDK_LINK_CLANG'];
- if (clang == null) {
- throw Exception(
- "cargo-ndk rustc linker: didn't find _CARGOKIT_NDK_LINK_CLANG env var",
- );
- }
- final target = Platform.environment['_CARGOKIT_NDK_LINK_TARGET'];
- if (target == null) {
- throw Exception(
- "cargo-ndk rustc linker: didn't find _CARGOKIT_NDK_LINK_TARGET env var",
- );
- }
-
- runCommand(clang, [target, ...args]);
- }
-
- final String sdkPath;
-
- final String ndkVersion;
-
- final int minSdkVersion;
-
- final String targetTempDir;
-
- final Target target;
-
- bool ndkIsInstalled() {
- final ndkPath = path.join(sdkPath, 'ndk', ndkVersion);
- final ndkPackageXml = File(path.join(ndkPath, 'package.xml'));
- return ndkPackageXml.existsSync();
- }
-
- void installNdk({required String javaHome}) {
- final sdkManagerExtension = Platform.isWindows ? '.bat' : '';
- final sdkManager = path.join(
- sdkPath,
- 'cmdline-tools',
- 'latest',
- 'bin',
- 'sdkmanager$sdkManagerExtension',
- );
-
- log.info('Installing NDK $ndkVersion');
- runCommand(
- sdkManager,
- ['--install', 'ndk;$ndkVersion'],
- environment: {'JAVA_HOME': javaHome},
- );
- }
-
- Future<Map<String, String>> buildEnvironment() async {
- final hostArch = Platform.isMacOS
- ? "darwin-x86_64"
- : (Platform.isLinux ? "linux-x86_64" : "windows-x86_64");
-
- final ndkPath = path.join(sdkPath, 'ndk', ndkVersion);
- final toolchainPath = path.join(
- ndkPath,
- 'toolchains',
- 'llvm',
- 'prebuilt',
- hostArch,
- 'bin',
- );
-
- final minSdkVersion = math.max(
- target.androidMinSdkVersion!,
- this.minSdkVersion,
- );
-
- final exe = Platform.isWindows ? '.exe' : '';
-
- final arKey = 'AR_${target.rust}';
- final arValue = ['${target.rust}-ar', 'llvm-ar', 'llvm-ar.exe']
- .map((e) => path.join(toolchainPath, e))
- .firstWhereOrNull((element) => File(element).existsSync());
- if (arValue == null) {
- throw Exception('Failed to find ar for $target in $toolchainPath');
- }
-
- final targetArg = '--target=${target.rust}$minSdkVersion';
-
- final ccKey = 'CC_${target.rust}';
- final ccValue = path.join(toolchainPath, 'clang$exe');
- final cfFlagsKey = 'CFLAGS_${target.rust}';
- final cFlagsValue = targetArg;
-
- final cxxKey = 'CXX_${target.rust}';
- final cxxValue = path.join(toolchainPath, 'clang++$exe');
- final cxxFlagsKey = 'CXXFLAGS_${target.rust}';
- final cxxFlagsValue = targetArg;
-
- final linkerKey = 'cargo_target_${target.rust.replaceAll('-', '_')}_linker'
- .toUpperCase();
-
- final ranlibKey = 'RANLIB_${target.rust}';
- final ranlibValue = path.join(toolchainPath, 'llvm-ranlib$exe');
-
- final ndkVersionParsed = Version.parse(ndkVersion);
- final rustFlagsKey = 'CARGO_ENCODED_RUSTFLAGS';
- final rustFlagsValue = _libGccWorkaround(targetTempDir, ndkVersionParsed);
-
- final runRustTool = Platform.isWindows
- ? 'run_build_tool.cmd'
- : 'run_build_tool.sh';
-
- final packagePath = (await Isolate.resolvePackageUri(
- Uri.parse('package:build_tool/buildtool.dart'),
- ))!.toFilePath();
- final selfPath = Uri.file(
- path.join(packagePath, '..', '..', '..', runRustTool),
- ).normalizePath().toFilePath(windows: Platform.isWindows);
-
- // Make sure that run_build_tool is working properly even initially launched directly
- // through dart run.
- final toolTempDir =
- Platform.environment['CARGOKIT_TOOL_TEMP_DIR'] ?? targetTempDir;
-
- return {
- arKey: arValue,
- ccKey: ccValue,
- cfFlagsKey: cFlagsValue,
- cxxKey: cxxValue,
- cxxFlagsKey: cxxFlagsValue,
- ranlibKey: ranlibValue,
- rustFlagsKey: rustFlagsValue,
- linkerKey: selfPath,
- // Recognized by main() so we know when we're acting as a wrapper
- '_CARGOKIT_NDK_LINK_TARGET': targetArg,
- '_CARGOKIT_NDK_LINK_CLANG': ccValue,
- 'CARGOKIT_TOOL_TEMP_DIR': toolTempDir,
- };
- }
-
- // Workaround for libgcc missing in NDK23, inspired by cargo-ndk
- String _libGccWorkaround(String buildDir, Version ndkVersion) {
- final workaroundDir = path.join(
- buildDir,
- 'cargokit',
- 'libgcc_workaround',
- '${ndkVersion.major}',
- );
- Directory(workaroundDir).createSync(recursive: true);
- if (ndkVersion.major >= 23) {
- File(
- path.join(workaroundDir, 'libgcc.a'),
- ).writeAsStringSync('INPUT(-lunwind)');
- } else {
- // Other way around, untested, forward libgcc.a from libunwind once Rust
- // gets updated for NDK23+.
- File(
- path.join(workaroundDir, 'libunwind.a'),
- ).writeAsStringSync('INPUT(-lgcc)');
- }
-
- var rustFlags = Platform.environment['CARGO_ENCODED_RUSTFLAGS'] ?? '';
- if (rustFlags.isNotEmpty) {
- rustFlags = '$rustFlags\x1f';
- }
- rustFlags = '$rustFlags-L\x1f$workaroundDir';
- rustFlags = '$rustFlags\x1f-C\x1flink-arg=-Wl,-z,max-page-size=16384';
- return rustFlags;
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/artifacts_provider.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/artifacts_provider.dart
deleted file mode 100644
index 2544c2eaf0..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/artifacts_provider.dart
+++ /dev/null
@@ -1,271 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:ed25519_edwards/ed25519_edwards.dart';
-import 'package:http/http.dart';
-import 'package:logging/logging.dart';
-import 'package:path/path.dart' as path;
-
-import 'builder.dart';
-import 'crate_hash.dart';
-import 'options.dart';
-import 'precompile_binaries.dart';
-import 'rustup.dart';
-import 'target.dart';
-
-class Artifact {
- final String path;
-
- final String finalFileName;
-
- AritifactType get type {
- if (finalFileName.endsWith('.dll') ||
- finalFileName.endsWith('.dll.lib') ||
- finalFileName.endsWith('.pdb') ||
- finalFileName.endsWith('.so') ||
- finalFileName.endsWith('.dylib')) {
- return AritifactType.dylib;
- } else if (finalFileName.endsWith('.lib') || finalFileName.endsWith('.a')) {
- return AritifactType.staticlib;
- } else {
- throw Exception('Unknown artifact type for $finalFileName');
- }
- }
-
- Artifact({required this.path, required this.finalFileName});
-}
-
-final _log = Logger('artifacts_provider');
-
-class ArtifactProvider {
- ArtifactProvider({required this.environment, required this.userOptions});
-
- final BuildEnvironment environment;
- final CargokitUserOptions userOptions;
-
- Future<Map<Target, List<Artifact>>> getArtifacts(List<Target> targets) async {
- final result = await _getPrecompiledArtifacts(targets);
-
- final pendingTargets = List.of(targets);
- pendingTargets.removeWhere((element) => result.containsKey(element));
-
- if (pendingTargets.isEmpty) {
- return result;
- }
-
- final rustup = Rustup();
- for (final target in targets) {
- final builder = RustBuilder(target: target, environment: environment);
- builder.prepare(rustup);
- _log.info('Building ${environment.crateInfo.packageName} for $target');
- final targetDir = await builder.build();
- // For local build accept both static and dynamic libraries.
- final artifactNames = <String>{
- ...getArtifactNames(
- target: target,
- libraryName: environment.crateInfo.packageName,
- aritifactType: AritifactType.dylib,
- remote: false,
- ),
- ...getArtifactNames(
- target: target,
- libraryName: environment.crateInfo.packageName,
- aritifactType: AritifactType.staticlib,
- remote: false,
- ),
- };
- final artifacts = artifactNames
- .map(
- (artifactName) => Artifact(
- path: path.join(targetDir, artifactName),
- finalFileName: artifactName,
- ),
- )
- .where((element) => File(element.path).existsSync())
- .toList();
- result[target] = artifacts;
- }
- return result;
- }
-
- Future<Map<Target, List<Artifact>>> _getPrecompiledArtifacts(
- List<Target> targets,
- ) async {
- if (userOptions.usePrecompiledBinaries == false) {
- _log.info('Precompiled binaries are disabled');
- return {};
- }
- if (environment.crateOptions.precompiledBinaries == null) {
- _log.fine('Precompiled binaries not enabled for this crate');
- return {};
- }
-
- final start = Stopwatch()..start();
- final crateHash = CrateHash.compute(
- environment.manifestDir,
- tempStorage: environment.targetTempDir,
- );
- _log.fine(
- 'Computed crate hash $crateHash in ${start.elapsedMilliseconds}ms',
- );
-
- final downloadedArtifactsDir = path.join(
- environment.targetTempDir,
- 'precompiled',
- crateHash,
- );
- Directory(downloadedArtifactsDir).createSync(recursive: true);
-
- final res = <Target, List<Artifact>>{};
-
- for (final target in targets) {
- final requiredArtifacts = getArtifactNames(
- target: target,
- libraryName: environment.crateInfo.packageName,
- remote: true,
- );
- final artifactsForTarget = <Artifact>[];
-
- for (final artifact in requiredArtifacts) {
- final fileName = PrecompileBinaries.fileName(target, artifact);
- final downloadedPath = path.join(downloadedArtifactsDir, fileName);
- if (!File(downloadedPath).existsSync()) {
- final signatureFileName = PrecompileBinaries.signatureFileName(
- target,
- artifact,
- );
- await _tryDownloadArtifacts(
- crateHash: crateHash,
- fileName: fileName,
- signatureFileName: signatureFileName,
- finalPath: downloadedPath,
- );
- }
- if (File(downloadedPath).existsSync()) {
- artifactsForTarget.add(
- Artifact(path: downloadedPath, finalFileName: artifact),
- );
- } else {
- break;
- }
- }
-
- // Only provide complete set of artifacts.
- if (artifactsForTarget.length == requiredArtifacts.length) {
- _log.fine('Found precompiled artifacts for $target');
- res[target] = artifactsForTarget;
- }
- }
-
- return res;
- }
-
- static Future<Response> _get(Uri url, {Map<String, String>? headers}) async {
- int attempt = 0;
- const maxAttempts = 10;
- while (true) {
- try {
- return await get(url, headers: headers);
- } on SocketException catch (e) {
- // Try to detect reset by peer error and retry.
- if (attempt++ < maxAttempts &&
- (e.osError?.errorCode == 54 || e.osError?.errorCode == 10054)) {
- _log.severe(
- 'Failed to download $url: $e, attempt $attempt of $maxAttempts, will retry...',
- );
- await Future.delayed(Duration(seconds: 1));
- continue;
- } else {
- rethrow;
- }
- }
- }
- }
-
- Future<void> _tryDownloadArtifacts({
- required String crateHash,
- required String fileName,
- required String signatureFileName,
- required String finalPath,
- }) async {
- final precompiledBinaries = environment.crateOptions.precompiledBinaries!;
- final prefix = precompiledBinaries.uriPrefix;
- final url = Uri.parse('$prefix$crateHash/$fileName');
- final signatureUrl = Uri.parse('$prefix$crateHash/$signatureFileName');
- _log.fine('Downloading signature from $signatureUrl');
- final signature = await _get(signatureUrl);
- if (signature.statusCode == 404) {
- _log.warning(
- 'Precompiled binaries not available for crate hash $crateHash ($fileName)',
- );
- return;
- }
- if (signature.statusCode != 200) {
- _log.severe(
- 'Failed to download signature $signatureUrl: status ${signature.statusCode}',
- );
- return;
- }
- _log.fine('Downloading binary from $url');
- final res = await _get(url);
- if (res.statusCode != 200) {
- _log.severe('Failed to download binary $url: status ${res.statusCode}');
- return;
- }
- if (verify(
- precompiledBinaries.publicKey,
- res.bodyBytes,
- signature.bodyBytes,
- )) {
- File(finalPath).writeAsBytesSync(res.bodyBytes);
- } else {
- _log.shout('Signature verification failed! Ignoring binary.');
- }
- }
-}
-
-enum AritifactType { staticlib, dylib }
-
-AritifactType artifactTypeForTarget(Target target) {
- if (target.darwinPlatform != null) {
- return AritifactType.staticlib;
- } else {
- return AritifactType.dylib;
- }
-}
-
-List<String> getArtifactNames({
- required Target target,
- required String libraryName,
- required bool remote,
- AritifactType? aritifactType,
-}) {
- aritifactType ??= artifactTypeForTarget(target);
- if (target.darwinArch != null) {
- if (aritifactType == AritifactType.staticlib) {
- return ['lib$libraryName.a'];
- } else {
- return ['lib$libraryName.dylib'];
- }
- } else if (target.rust.contains('-windows-')) {
- if (aritifactType == AritifactType.staticlib) {
- return ['$libraryName.lib'];
- } else {
- return [
- '$libraryName.dll',
- '$libraryName.dll.lib',
- if (!remote) '$libraryName.pdb',
- ];
- }
- } else if (target.rust.contains('-linux-')) {
- if (aritifactType == AritifactType.staticlib) {
- return ['lib$libraryName.a'];
- } else {
- return ['lib$libraryName.so'];
- }
- } else {
- throw Exception("Unsupported target: ${target.rust}");
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/build_cmake.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/build_cmake.dart
deleted file mode 100644
index 4bde10c5a9..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/build_cmake.dart
+++ /dev/null
@@ -1,43 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:path/path.dart' as path;
-
-import 'artifacts_provider.dart';
-import 'builder.dart';
-import 'environment.dart';
-import 'options.dart';
-import 'target.dart';
-
-class BuildCMake {
- final CargokitUserOptions userOptions;
-
- BuildCMake({required this.userOptions});
-
- Future<void> build() async {
- final targetPlatform = Environment.targetPlatform;
- final target = Target.forFlutterName(Environment.targetPlatform);
- if (target == null) {
- throw Exception("Unknown target platform: $targetPlatform");
- }
-
- final environment = BuildEnvironment.fromEnvironment(isAndroid: false);
- final provider = ArtifactProvider(
- environment: environment,
- userOptions: userOptions,
- );
- final artifacts = await provider.getArtifacts([target]);
-
- final libs = artifacts[target]!;
-
- for (final lib in libs) {
- if (lib.type == AritifactType.dylib) {
- File(
- lib.path,
- ).copySync(path.join(Environment.outputDir, lib.finalFileName));
- }
- }
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/build_gradle.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/build_gradle.dart
deleted file mode 100644
index 5c2e95b032..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/build_gradle.dart
+++ /dev/null
@@ -1,52 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:logging/logging.dart';
-import 'package:path/path.dart' as path;
-
-import 'artifacts_provider.dart';
-import 'builder.dart';
-import 'environment.dart';
-import 'options.dart';
-import 'target.dart';
-
-final log = Logger('build_gradle');
-
-class BuildGradle {
- BuildGradle({required this.userOptions});
-
- final CargokitUserOptions userOptions;
-
- Future<void> build() async {
- final targets = Environment.targetPlatforms.map((arch) {
- final target = Target.forFlutterName(arch);
- if (target == null) {
- throw Exception(
- "Unknown darwin target or platform: $arch, ${Environment.darwinPlatformName}",
- );
- }
- return target;
- }).toList();
-
- final environment = BuildEnvironment.fromEnvironment(isAndroid: true);
- final provider = ArtifactProvider(
- environment: environment,
- userOptions: userOptions,
- );
- final artifacts = await provider.getArtifacts(targets);
-
- for (final target in targets) {
- final libs = artifacts[target]!;
- final outputDir = path.join(Environment.outputDir, target.android!);
- Directory(outputDir).createSync(recursive: true);
-
- for (final lib in libs) {
- if (lib.type == AritifactType.dylib) {
- File(lib.path).copySync(path.join(outputDir, lib.finalFileName));
- }
- }
- }
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/build_pod.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/build_pod.dart
deleted file mode 100644
index aa99f478aa..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/build_pod.dart
+++ /dev/null
@@ -1,89 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:path/path.dart' as path;
-
-import 'artifacts_provider.dart';
-import 'builder.dart';
-import 'environment.dart';
-import 'options.dart';
-import 'target.dart';
-import 'util.dart';
-
-class BuildPod {
- BuildPod({required this.userOptions});
-
- final CargokitUserOptions userOptions;
-
- Future<void> build() async {
- final targets = Environment.darwinArchs.map((arch) {
- final target = Target.forDarwin(
- platformName: Environment.darwinPlatformName,
- darwinAarch: arch,
- );
- if (target == null) {
- throw Exception(
- "Unknown darwin target or platform: $arch, ${Environment.darwinPlatformName}",
- );
- }
- return target;
- }).toList();
-
- final environment = BuildEnvironment.fromEnvironment(isAndroid: false);
- final provider = ArtifactProvider(
- environment: environment,
- userOptions: userOptions,
- );
- final artifacts = await provider.getArtifacts(targets);
-
- void performLipo(String targetFile, Iterable<String> sourceFiles) {
- runCommand("lipo", ['-create', ...sourceFiles, '-output', targetFile]);
- }
-
- final outputDir = Environment.outputDir;
-
- Directory(outputDir).createSync(recursive: true);
-
- final staticLibs = artifacts.values
- .expand((element) => element)
- .where((element) => element.type == AritifactType.staticlib)
- .toList();
- final dynamicLibs = artifacts.values
- .expand((element) => element)
- .where((element) => element.type == AritifactType.dylib)
- .toList();
-
- final libName = environment.crateInfo.packageName;
-
- // If there is static lib, use it and link it with pod
- if (staticLibs.isNotEmpty) {
- final finalTargetFile = path.join(outputDir, "lib$libName.a");
- performLipo(finalTargetFile, staticLibs.map((e) => e.path));
- } else {
- // Otherwise try to replace bundle dylib with our dylib
- final bundlePaths = [
- '$libName.framework/Versions/A/$libName',
- '$libName.framework/$libName',
- ];
-
- for (final bundlePath in bundlePaths) {
- final targetFile = path.join(outputDir, bundlePath);
- if (File(targetFile).existsSync()) {
- performLipo(targetFile, dynamicLibs.map((e) => e.path));
-
- // Replace absolute id with @rpath one so that it works properly
- // when moved to Frameworks.
- runCommand("install_name_tool", [
- '-id',
- '@rpath/$bundlePath',
- targetFile,
- ]);
- return;
- }
- }
- throw Exception('Unable to find bundle for dynamic library');
- }
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/build_tool.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/build_tool.dart
deleted file mode 100644
index 634c359d95..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/build_tool.dart
+++ /dev/null
@@ -1,277 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:args/command_runner.dart';
-import 'package:ed25519_edwards/ed25519_edwards.dart';
-import 'package:github/github.dart';
-import 'package:hex/hex.dart';
-import 'package:logging/logging.dart';
-
-import 'android_environment.dart';
-import 'build_cmake.dart';
-import 'build_gradle.dart';
-import 'build_pod.dart';
-import 'logging.dart';
-import 'options.dart';
-import 'precompile_binaries.dart';
-import 'target.dart';
-import 'util.dart';
-import 'verify_binaries.dart';
-
-final log = Logger('build_tool');
-
-abstract class BuildCommand extends Command {
- Future<void> runBuildCommand(CargokitUserOptions options);
-
- @override
- Future<void> run() async {
- final options = CargokitUserOptions.load();
-
- if (options.verboseLogging ||
- Platform.environment['CARGOKIT_VERBOSE'] == '1') {
- enableVerboseLogging();
- }
-
- await runBuildCommand(options);
- }
-}
-
-class BuildPodCommand extends BuildCommand {
- @override
- final name = 'build-pod';
-
- @override
- final description = 'Build cocoa pod library';
-
- @override
- Future<void> runBuildCommand(CargokitUserOptions options) async {
- final build = BuildPod(userOptions: options);
- await build.build();
- }
-}
-
-class BuildGradleCommand extends BuildCommand {
- @override
- final name = 'build-gradle';
-
- @override
- final description = 'Build android library';
-
- @override
- Future<void> runBuildCommand(CargokitUserOptions options) async {
- final build = BuildGradle(userOptions: options);
- await build.build();
- }
-}
-
-class BuildCMakeCommand extends BuildCommand {
- @override
- final name = 'build-cmake';
-
- @override
- final description = 'Build CMake library';
-
- @override
- Future<void> runBuildCommand(CargokitUserOptions options) async {
- final build = BuildCMake(userOptions: options);
- await build.build();
- }
-}
-
-class GenKeyCommand extends Command {
- @override
- final name = 'gen-key';
-
- @override
- final description = 'Generate key pair for signing precompiled binaries';
-
- @override
- void run() {
- final kp = generateKey();
- final private = HEX.encode(kp.privateKey.bytes);
- final public = HEX.encode(kp.publicKey.bytes);
- print("Private Key: $private");
- print("Public Key: $public");
- }
-}
-
-class PrecompileBinariesCommand extends Command {
- PrecompileBinariesCommand() {
- argParser
- ..addOption(
- 'repository',
- mandatory: true,
- help: 'Github repository slug in format owner/name',
- )
- ..addOption(
- 'manifest-dir',
- mandatory: true,
- help: 'Directory containing Cargo.toml',
- )
- ..addMultiOption(
- 'target',
- help:
- 'Rust target triple of artifact to build.\n'
- 'Can be specified multiple times or omitted in which case\n'
- 'all targets for current platform will be built.',
- )
- ..addOption(
- 'android-sdk-location',
- help: 'Location of Android SDK (if available)',
- )
- ..addOption(
- 'android-ndk-version',
- help: 'Android NDK version (if available)',
- )
- ..addOption(
- 'android-min-sdk-version',
- help: 'Android minimum rquired version (if available)',
- )
- ..addOption(
- 'temp-dir',
- help: 'Directory to store temporary build artifacts',
- )
- ..addFlag(
- "verbose",
- abbr: "v",
- defaultsTo: false,
- help: "Enable verbose logging",
- );
- }
-
- @override
- final name = 'precompile-binaries';
-
- @override
- final description =
- 'Prebuild and upload binaries\n'
- 'Private key must be passed through PRIVATE_KEY environment variable. '
- 'Use gen_key through generate priave key.\n'
- 'Github token must be passed as GITHUB_TOKEN environment variable.\n';
-
- @override
- Future<void> run() async {
- final verbose = argResults!['verbose'] as bool;
- if (verbose) {
- enableVerboseLogging();
- }
-
- final privateKeyString = Platform.environment['PRIVATE_KEY'];
- if (privateKeyString == null) {
- throw ArgumentError('Missing PRIVATE_KEY environment variable');
- }
- final githubToken = Platform.environment['GITHUB_TOKEN'];
- if (githubToken == null) {
- throw ArgumentError('Missing GITHUB_TOKEN environment variable');
- }
- final privateKey = HEX.decode(privateKeyString);
- if (privateKey.length != 64) {
- throw ArgumentError('Private key must be 64 bytes long');
- }
- final manifestDir = argResults!['manifest-dir'] as String;
- if (!Directory(manifestDir).existsSync()) {
- throw ArgumentError('Manifest directory does not exist: $manifestDir');
- }
- String? androidMinSdkVersionString =
- argResults!['android-min-sdk-version'] as String?;
- int? androidMinSdkVersion;
- if (androidMinSdkVersionString != null) {
- androidMinSdkVersion = int.tryParse(androidMinSdkVersionString);
- if (androidMinSdkVersion == null) {
- throw ArgumentError(
- 'Invalid android-min-sdk-version: $androidMinSdkVersionString',
- );
- }
- }
- final targetStrigns = argResults!['target'] as List<String>;
- final targets = targetStrigns
- .map((target) {
- final res = Target.forRustTriple(target);
- if (res == null) {
- throw ArgumentError('Invalid target: $target');
- }
- return res;
- })
- .toList(growable: false);
- final precompileBinaries = PrecompileBinaries(
- privateKey: PrivateKey(privateKey),
- githubToken: githubToken,
- manifestDir: manifestDir,
- repositorySlug: RepositorySlug.full(argResults!['repository'] as String),
- targets: targets,
- androidSdkLocation: argResults!['android-sdk-location'] as String?,
- androidNdkVersion: argResults!['android-ndk-version'] as String?,
- androidMinSdkVersion: androidMinSdkVersion,
- tempDir: argResults!['temp-dir'] as String?,
- );
-
- await precompileBinaries.run();
- }
-}
-
-class VerifyBinariesCommand extends Command {
- VerifyBinariesCommand() {
- argParser.addOption(
- 'manifest-dir',
- mandatory: true,
- help: 'Directory containing Cargo.toml',
- );
- }
-
- @override
- final name = "verify-binaries";
-
- @override
- final description =
- 'Verifies published binaries\n'
- 'Checks whether there is a binary published for each targets\n'
- 'and checks the signature.';
-
- @override
- Future<void> run() async {
- final manifestDir = argResults!['manifest-dir'] as String;
- final verifyBinaries = VerifyBinaries(manifestDir: manifestDir);
- await verifyBinaries.run();
- }
-}
-
-Future<void> runMain(List<String> args) async {
- try {
- // Init logging before options are loaded
- initLogging();
-
- if (Platform.environment['_CARGOKIT_NDK_LINK_TARGET'] != null) {
- return AndroidEnvironment.clangLinkerWrapper(args);
- }
-
- final runner = CommandRunner('build_tool', 'Cargokit built_tool')
- ..addCommand(BuildPodCommand())
- ..addCommand(BuildGradleCommand())
- ..addCommand(BuildCMakeCommand())
- ..addCommand(GenKeyCommand())
- ..addCommand(PrecompileBinariesCommand())
- ..addCommand(VerifyBinariesCommand());
-
- await runner.run(args);
- } on ArgumentError catch (e) {
- stderr.writeln(e.toString());
- exit(1);
- } catch (e, s) {
- log.severe(kDoubleSeparator);
- log.severe('Cargokit BuildTool failed with error:');
- log.severe(kSeparator);
- log.severe(e);
- // This tells user to install Rust, there's no need to pollute the log with
- // stack trace.
- if (e is! RustupNotFoundException) {
- log.severe(kSeparator);
- log.severe(s);
- log.severe(kSeparator);
- log.severe('BuildTool arguments: $args');
- }
- log.severe(kDoubleSeparator);
- exit(1);
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/builder.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/builder.dart
deleted file mode 100644
index 6a5ce1fad8..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/builder.dart
+++ /dev/null
@@ -1,182 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'package:collection/collection.dart';
-import 'package:logging/logging.dart';
-import 'package:path/path.dart' as path;
-
-import 'android_environment.dart';
-import 'cargo.dart';
-import 'environment.dart';
-import 'options.dart';
-import 'rustup.dart';
-import 'target.dart';
-import 'util.dart';
-
-final _log = Logger('builder');
-
-enum BuildConfiguration { debug, release, profile }
-
-extension on BuildConfiguration {
- bool get isDebug => this == BuildConfiguration.debug;
- String get rustName => switch (this) {
- BuildConfiguration.debug => 'debug',
- BuildConfiguration.release => 'release',
- BuildConfiguration.profile => 'release',
- };
-}
-
-class BuildException implements Exception {
- final String message;
-
- BuildException(this.message);
-
- @override
- String toString() {
- return 'BuildException: $message';
- }
-}
-
-class BuildEnvironment {
- final BuildConfiguration configuration;
- final CargokitCrateOptions crateOptions;
- final String targetTempDir;
- final String manifestDir;
- final CrateInfo crateInfo;
-
- final bool isAndroid;
- final String? androidSdkPath;
- final String? androidNdkVersion;
- final int? androidMinSdkVersion;
- final String? javaHome;
-
- BuildEnvironment({
- required this.configuration,
- required this.crateOptions,
- required this.targetTempDir,
- required this.manifestDir,
- required this.crateInfo,
- required this.isAndroid,
- this.androidSdkPath,
- this.androidNdkVersion,
- this.androidMinSdkVersion,
- this.javaHome,
- });
-
- static BuildConfiguration parseBuildConfiguration(String value) {
- // XCode configuration adds the flavor to configuration name.
- final firstSegment = value.split('-').first;
- final buildConfiguration = BuildConfiguration.values.firstWhereOrNull(
- (e) => e.name == firstSegment,
- );
- if (buildConfiguration == null) {
- _log.warning('Unknown build configuraiton $value, will assume release');
- return BuildConfiguration.release;
- }
- return buildConfiguration;
- }
-
- static BuildEnvironment fromEnvironment({required bool isAndroid}) {
- final buildConfiguration = parseBuildConfiguration(
- Environment.configuration,
- );
- final manifestDir = Environment.manifestDir;
- final crateOptions = CargokitCrateOptions.load(manifestDir: manifestDir);
- final crateInfo = CrateInfo.load(manifestDir);
- return BuildEnvironment(
- configuration: buildConfiguration,
- crateOptions: crateOptions,
- targetTempDir: Environment.targetTempDir,
- manifestDir: manifestDir,
- crateInfo: crateInfo,
- isAndroid: isAndroid,
- androidSdkPath: isAndroid ? Environment.sdkPath : null,
- androidNdkVersion: isAndroid ? Environment.ndkVersion : null,
- androidMinSdkVersion: isAndroid
- ? int.parse(Environment.minSdkVersion)
- : null,
- javaHome: isAndroid ? Environment.javaHome : null,
- );
- }
-}
-
-class RustBuilder {
- final Target target;
- final BuildEnvironment environment;
-
- RustBuilder({required this.target, required this.environment});
-
- void prepare(Rustup rustup) {
- final toolchain = _toolchain;
- if (rustup.installedTargets(toolchain) == null) {
- rustup.installToolchain(toolchain);
- }
- if (toolchain == 'nightly') {
- rustup.installRustSrcForNightly();
- }
- if (!rustup.installedTargets(toolchain)!.contains(target.rust)) {
- rustup.installTarget(target.rust, toolchain: toolchain);
- }
- }
-
- CargoBuildOptions? get _buildOptions =>
- environment.crateOptions.cargo[environment.configuration];
-
- String get _toolchain => _buildOptions?.toolchain.name ?? 'stable';
-
- Future<String> build() async {
- final extraArgs = _buildOptions?.flags ?? [];
- final manifestPath = path.join(environment.manifestDir, 'Cargo.toml');
- runCommand('rustup', [
- 'run',
- _toolchain,
- 'cargo',
- 'build',
- ...extraArgs,
- '--manifest-path',
- manifestPath,
- '-p',
- environment.crateInfo.packageName,
- if (!environment.configuration.isDebug) '--release',
- '--target',
- target.rust,
- '--target-dir',
- environment.targetTempDir,
- ], environment: await _buildEnvironment());
- return path.join(
- environment.targetTempDir,
- target.rust,
- environment.configuration.rustName,
- );
- }
-
- Future<Map<String, String>> _buildEnvironment() async {
- if (target.android == null) {
- return {};
- } else {
- final sdkPath = environment.androidSdkPath;
- final ndkVersion = environment.androidNdkVersion;
- final minSdkVersion = environment.androidMinSdkVersion;
- if (sdkPath == null) {
- throw BuildException('androidSdkPath is not set');
- }
- if (ndkVersion == null) {
- throw BuildException('androidNdkVersion is not set');
- }
- if (minSdkVersion == null) {
- throw BuildException('androidMinSdkVersion is not set');
- }
- final env = AndroidEnvironment(
- sdkPath: sdkPath,
- ndkVersion: ndkVersion,
- minSdkVersion: minSdkVersion,
- targetTempDir: environment.targetTempDir,
- target: target,
- );
- if (!env.ndkIsInstalled() && environment.javaHome != null) {
- env.installNdk(javaHome: environment.javaHome!);
- }
- return env.buildEnvironment();
- }
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/cargo.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/cargo.dart
deleted file mode 100644
index 8ed618573d..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/cargo.dart
+++ /dev/null
@@ -1,48 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:path/path.dart' as path;
-import 'package:toml/toml.dart';
-
-class ManifestException {
- ManifestException(this.message, {required this.fileName});
-
- final String? fileName;
- final String message;
-
- @override
- String toString() {
- if (fileName != null) {
- return 'Failed to parse package manifest at $fileName: $message';
- } else {
- return 'Failed to parse package manifest: $message';
- }
- }
-}
-
-class CrateInfo {
- CrateInfo({required this.packageName});
-
- final String packageName;
-
- static CrateInfo parseManifest(String manifest, {final String? fileName}) {
- final toml = TomlDocument.parse(manifest);
- final package = toml.toMap()['package'];
- if (package == null) {
- throw ManifestException('Missing package section', fileName: fileName);
- }
- final name = package['name'];
- if (name == null) {
- throw ManifestException('Missing package name', fileName: fileName);
- }
- return CrateInfo(packageName: name);
- }
-
- static CrateInfo load(String manifestDir) {
- final manifestFile = File(path.join(manifestDir, 'Cargo.toml'));
- final manifest = manifestFile.readAsStringSync();
- return parseManifest(manifest, fileName: manifestFile.path);
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/crate_hash.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/crate_hash.dart
deleted file mode 100644
index b13b286597..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/crate_hash.dart
+++ /dev/null
@@ -1,112 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:convert';
-import 'dart:io';
-import 'dart:typed_data';
-
-import 'package:collection/collection.dart';
-import 'package:convert/convert.dart';
-import 'package:crypto/crypto.dart';
-import 'package:path/path.dart' as path;
-
-class CrateHash {
- static String compute(String manifestDir, {String? tempStorage}) {
- return CrateHash._(
- manifestDir: manifestDir,
- tempStorage: tempStorage,
- )._compute();
- }
-
- CrateHash._({required this.manifestDir, required this.tempStorage});
-
- String _compute() {
- final files = getFiles();
- final tempStorage = this.tempStorage;
- if (tempStorage != null) {
- final quickHash = _computeQuickHash(files);
- final quickHashFolder = Directory(path.join(tempStorage, 'crate_hash'));
- quickHashFolder.createSync(recursive: true);
- final quickHashFile = File(path.join(quickHashFolder.path, quickHash));
- if (quickHashFile.existsSync()) {
- return quickHashFile.readAsStringSync();
- }
- final hash = _computeHash(files);
- quickHashFile.writeAsStringSync(hash);
- return hash;
- } else {
- return _computeHash(files);
- }
- }
-
- String _computeQuickHash(List<File> files) {
- final output = AccumulatorSink<Digest>();
- final input = sha256.startChunkedConversion(output);
-
- final data = ByteData(8);
- for (final file in files) {
- input.add(utf8.encode(file.path));
- final stat = file.statSync();
- data.setUint64(0, stat.size);
- input.add(data.buffer.asUint8List());
- data.setUint64(0, stat.modified.millisecondsSinceEpoch);
- input.add(data.buffer.asUint8List());
- }
-
- input.close();
- return base64Url.encode(output.events.single.bytes);
- }
-
- String _computeHash(List<File> files) {
- final output = AccumulatorSink<Digest>();
- final input = sha256.startChunkedConversion(output);
-
- void addTextFile(File file) {
- // text Files are hashed by lines in case we're dealing with github checkout
- // that auto-converts line endings.
- final splitter = LineSplitter();
- if (file.existsSync()) {
- final data = file.readAsStringSync();
- final lines = splitter.convert(data);
- for (final line in lines) {
- input.add(utf8.encode(line));
- }
- }
- }
-
- for (final file in files) {
- addTextFile(file);
- }
-
- input.close();
- final res = output.events.single;
-
- // Truncate to 128bits.
- final hash = res.bytes.sublist(0, 16);
- return hex.encode(hash);
- }
-
- List<File> getFiles() {
- final src = Directory(path.join(manifestDir, 'src'));
- final files = src
- .listSync(recursive: true, followLinks: false)
- .whereType<File>()
- .toList();
- files.sortBy((element) => element.path);
- void addFile(String relative) {
- final file = File(path.join(manifestDir, relative));
- if (file.existsSync()) {
- files.add(file);
- }
- }
-
- addFile('Cargo.toml');
- addFile('Cargo.lock');
- addFile('build.rs');
- addFile('cargokit.yaml');
- return files;
- }
-
- final String manifestDir;
- final String? tempStorage;
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/environment.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/environment.dart
deleted file mode 100644
index 34680af042..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/environment.dart
+++ /dev/null
@@ -1,57 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-extension on String {
- String resolveSymlink() => File(this).resolveSymbolicLinksSync();
-}
-
-class Environment {
- static String get configuration =>
- _getEnv("CARGOKIT_CONFIGURATION").toLowerCase();
-
- static bool get isDebug => configuration == 'debug';
- static bool get isRelease => configuration == 'release';
-
- static String get targetTempDir => _getEnv("CARGOKIT_TARGET_TEMP_DIR");
-
- static String get outputDir => _getEnvPath('CARGOKIT_OUTPUT_DIR');
-
- static String get manifestDir => _getEnvPath('CARGOKIT_MANIFEST_DIR');
-
- // Symlinks are not resolved on purpose.
- static String get rootProjectDir => _getEnv('CARGOKIT_ROOT_PROJECT_DIR');
-
- static String get darwinPlatformName =>
- _getEnv("CARGOKIT_DARWIN_PLATFORM_NAME");
-
- static List<String> get darwinArchs =>
- _getEnv("CARGOKIT_DARWIN_ARCHS").split(' ');
-
- static String get minSdkVersion => _getEnv("CARGOKIT_MIN_SDK_VERSION");
- static String get ndkVersion => _getEnv("CARGOKIT_NDK_VERSION");
- static String get sdkPath => _getEnvPath("CARGOKIT_SDK_DIR");
- static String get javaHome => _getEnvPath("CARGOKIT_JAVA_HOME");
- static List<String> get targetPlatforms =>
- _getEnv("CARGOKIT_TARGET_PLATFORMS").split(',');
-
- static String get targetPlatform => _getEnv("CARGOKIT_TARGET_PLATFORM");
-
- static String _getEnv(String key) {
- final res = Platform.environment[key];
- if (res == null) {
- throw Exception("Missing environment variable $key");
- }
- return res;
- }
-
- static String _getEnvPath(String key) {
- final res = _getEnv(key);
- if (Directory(res).existsSync()) {
- return res.resolveSymlink();
- } else {
- return res;
- }
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/logging.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/logging.dart
deleted file mode 100644
index 72cd6848f0..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/logging.dart
+++ /dev/null
@@ -1,48 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:logging/logging.dart';
-
-const String kSeparator = "--";
-const String kDoubleSeparator = "==";
-
-bool _lastMessageWasSeparator = false;
-
-void _log(LogRecord rec) {
- final prefix = '${rec.level.name}: ';
- final out = rec.level == Level.SEVERE ? stderr : stdout;
- if (rec.message == kSeparator) {
- if (!_lastMessageWasSeparator) {
- out.write(prefix);
- out.writeln('-' * 80);
- _lastMessageWasSeparator = true;
- }
- return;
- } else if (rec.message == kDoubleSeparator) {
- out.write(prefix);
- out.writeln('=' * 80);
- _lastMessageWasSeparator = true;
- return;
- }
- out.write(prefix);
- out.writeln(rec.message);
- _lastMessageWasSeparator = false;
-}
-
-void initLogging() {
- Logger.root.level = Level.INFO;
- Logger.root.onRecord.listen((LogRecord rec) {
- final lines = rec.message.split('\n');
- for (final line in lines) {
- if (line.isNotEmpty || lines.length == 1 || line != lines.last) {
- _log(LogRecord(rec.level, line, rec.loggerName));
- }
- }
- });
-}
-
-void enableVerboseLogging() {
- Logger.root.level = Level.ALL;
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/options.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/options.dart
deleted file mode 100644
index a952b50771..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/options.dart
+++ /dev/null
@@ -1,295 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:collection/collection.dart';
-import 'package:ed25519_edwards/ed25519_edwards.dart';
-import 'package:hex/hex.dart';
-import 'package:logging/logging.dart';
-import 'package:path/path.dart' as path;
-import 'package:source_span/source_span.dart';
-import 'package:yaml/yaml.dart';
-
-import 'builder.dart';
-import 'environment.dart';
-import 'rustup.dart';
-
-final _log = Logger('options');
-
-class SourceSpanException implements Exception {
- // This is a getter so that subclasses can override it.
- String get message => _message;
- final String _message;
-
- // This is a getter so that subclasses can override it.
- SourceSpan? get span => _span;
- final SourceSpan? _span;
-
- SourceSpanException(this._message, this._span);
-
- @override
- String toString({Object? color}) {
- if (span == null) return message;
- return 'Error on ${span!.message(message, color: color)}';
- }
-}
-
-enum Toolchain { stable, beta, nightly }
-
-class CargoBuildOptions {
- final Toolchain toolchain;
- final List<String> flags;
-
- CargoBuildOptions({required this.toolchain, required this.flags});
-
- static Toolchain _toolchainFromNode(YamlNode node) {
- if (node case YamlScalar(value: String name)) {
- final toolchain = Toolchain.values.firstWhereOrNull(
- (element) => element.name == name,
- );
- if (toolchain != null) {
- return toolchain;
- }
- }
- throw SourceSpanException(
- 'Unknown toolchain. Must be one of ${Toolchain.values.map((e) => e.name)}.',
- node.span,
- );
- }
-
- static CargoBuildOptions parse(YamlNode node) {
- if (node is! YamlMap) {
- throw SourceSpanException('Cargo options must be a map', node.span);
- }
- Toolchain toolchain = Toolchain.stable;
- List<String> flags = [];
- for (final MapEntry(:key, :value) in node.nodes.entries) {
- if (key case YamlScalar(value: 'toolchain')) {
- toolchain = _toolchainFromNode(value);
- } else if (key case YamlScalar(value: 'extra_flags')) {
- if (value case YamlList(nodes: List<YamlNode> list)) {
- if (list.every((element) {
- if (element case YamlScalar(value: String _)) {
- return true;
- }
- return false;
- })) {
- flags = list.map((e) => e.value as String).toList();
- continue;
- }
- }
- throw SourceSpanException(
- 'Extra flags must be a list of strings',
- value.span,
- );
- } else {
- throw SourceSpanException(
- 'Unknown cargo option type. Must be "toolchain" or "extra_flags".',
- key.span,
- );
- }
- }
- return CargoBuildOptions(toolchain: toolchain, flags: flags);
- }
-}
-
-extension on YamlMap {
- Map<dynamic, YamlNode> get valueMap =>
- nodes.map((key, value) => MapEntry(key.value, value));
-}
-
-class PrecompiledBinaries {
- final String uriPrefix;
- final PublicKey publicKey;
-
- PrecompiledBinaries({required this.uriPrefix, required this.publicKey});
-
- static PublicKey _publicKeyFromHex(String key, SourceSpan? span) {
- final bytes = HEX.decode(key);
- if (bytes.length != 32) {
- throw SourceSpanException(
- 'Invalid public key. Must be 32 bytes long.',
- span,
- );
- }
- return PublicKey(bytes);
- }
-
- static PrecompiledBinaries parse(YamlNode node) {
- if (node case YamlMap(valueMap: Map<dynamic, YamlNode> map)) {
- if (map case {
- 'url_prefix': YamlNode urlPrefixNode,
- 'public_key': YamlNode publicKeyNode,
- }) {
- final urlPrefix = switch (urlPrefixNode) {
- YamlScalar(value: String urlPrefix) => urlPrefix,
- _ => throw SourceSpanException(
- 'Invalid URL prefix value.',
- urlPrefixNode.span,
- ),
- };
- final publicKey = switch (publicKeyNode) {
- YamlScalar(value: String publicKey) => _publicKeyFromHex(
- publicKey,
- publicKeyNode.span,
- ),
- _ => throw SourceSpanException(
- 'Invalid public key value.',
- publicKeyNode.span,
- ),
- };
- return PrecompiledBinaries(uriPrefix: urlPrefix, publicKey: publicKey);
- }
- }
- throw SourceSpanException(
- 'Invalid precompiled binaries value. '
- 'Expected Map with "url_prefix" and "public_key".',
- node.span,
- );
- }
-}
-
-class CargokitCrateOptions {
- CargokitCrateOptions({this.cargo = const {}, this.precompiledBinaries});
-
- final Map<BuildConfiguration, CargoBuildOptions> cargo;
- final PrecompiledBinaries? precompiledBinaries;
-
- static CargokitCrateOptions parse(YamlNode node) {
- if (node is! YamlMap) {
- throw SourceSpanException('Cargokit options must be a map', node.span);
- }
- final options = <BuildConfiguration, CargoBuildOptions>{};
- PrecompiledBinaries? precompiledBinaries;
-
- for (final entry in node.nodes.entries) {
- if (entry case MapEntry(
- key: YamlScalar(value: 'cargo'),
- value: YamlNode node,
- )) {
- if (node is! YamlMap) {
- throw SourceSpanException('Cargo options must be a map', node.span);
- }
- for (final MapEntry(:YamlNode key, :value) in node.nodes.entries) {
- if (key case YamlScalar(value: String name)) {
- final configuration = BuildConfiguration.values.firstWhereOrNull(
- (element) => element.name == name,
- );
- if (configuration != null) {
- options[configuration] = CargoBuildOptions.parse(value);
- continue;
- }
- }
- throw SourceSpanException(
- 'Unknown build configuration. Must be one of ${BuildConfiguration.values.map((e) => e.name)}.',
- key.span,
- );
- }
- } else if (entry.key case YamlScalar(value: 'precompiled_binaries')) {
- precompiledBinaries = PrecompiledBinaries.parse(entry.value);
- } else {
- throw SourceSpanException(
- 'Unknown cargokit option type. Must be "cargo" or "precompiled_binaries".',
- entry.key.span,
- );
- }
- }
- return CargokitCrateOptions(
- cargo: options,
- precompiledBinaries: precompiledBinaries,
- );
- }
-
- static CargokitCrateOptions load({required String manifestDir}) {
- final uri = Uri.file(path.join(manifestDir, "cargokit.yaml"));
- final file = File.fromUri(uri);
- if (file.existsSync()) {
- final contents = loadYamlNode(file.readAsStringSync(), sourceUrl: uri);
- return parse(contents);
- } else {
- return CargokitCrateOptions();
- }
- }
-}
-
-class CargokitUserOptions {
- // When Rustup is installed always build locally unless user opts into
- // using precompiled binaries.
- static bool defaultUsePrecompiledBinaries() {
- return Rustup.executablePath() == null;
- }
-
- CargokitUserOptions({
- required this.usePrecompiledBinaries,
- required this.verboseLogging,
- });
-
- CargokitUserOptions._()
- : usePrecompiledBinaries = defaultUsePrecompiledBinaries(),
- verboseLogging = false;
-
- static CargokitUserOptions parse(YamlNode node) {
- if (node is! YamlMap) {
- throw SourceSpanException('Cargokit options must be a map', node.span);
- }
- bool usePrecompiledBinaries = defaultUsePrecompiledBinaries();
- bool verboseLogging = false;
-
- for (final entry in node.nodes.entries) {
- if (entry.key case YamlScalar(value: 'use_precompiled_binaries')) {
- if (entry.value case YamlScalar(value: bool value)) {
- usePrecompiledBinaries = value;
- continue;
- }
- throw SourceSpanException(
- 'Invalid value for "use_precompiled_binaries". Must be a boolean.',
- entry.value.span,
- );
- } else if (entry.key case YamlScalar(value: 'verbose_logging')) {
- if (entry.value case YamlScalar(value: bool value)) {
- verboseLogging = value;
- continue;
- }
- throw SourceSpanException(
- 'Invalid value for "verbose_logging". Must be a boolean.',
- entry.value.span,
- );
- } else {
- throw SourceSpanException(
- 'Unknown cargokit option type. Must be "use_precompiled_binaries" or "verbose_logging".',
- entry.key.span,
- );
- }
- }
- return CargokitUserOptions(
- usePrecompiledBinaries: usePrecompiledBinaries,
- verboseLogging: verboseLogging,
- );
- }
-
- static CargokitUserOptions load() {
- String fileName = "cargokit_options.yaml";
- var userProjectDir = Directory(Environment.rootProjectDir);
-
- while (userProjectDir.parent.path != userProjectDir.path) {
- final configFile = File(path.join(userProjectDir.path, fileName));
- if (configFile.existsSync()) {
- final contents = loadYamlNode(
- configFile.readAsStringSync(),
- sourceUrl: configFile.uri,
- );
- final res = parse(contents);
- if (res.verboseLogging) {
- _log.info('Found user options file at ${configFile.path}');
- }
- return res;
- }
- userProjectDir = userProjectDir.parent;
- }
- return CargokitUserOptions._();
- }
-
- final bool usePrecompiledBinaries;
- final bool verboseLogging;
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/precompile_binaries.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/precompile_binaries.dart
deleted file mode 100644
index fc235ef5cd..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/precompile_binaries.dart
+++ /dev/null
@@ -1,205 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:ed25519_edwards/ed25519_edwards.dart';
-import 'package:github/github.dart';
-import 'package:logging/logging.dart';
-import 'package:path/path.dart' as path;
-
-import 'artifacts_provider.dart';
-import 'builder.dart';
-import 'cargo.dart';
-import 'crate_hash.dart';
-import 'options.dart';
-import 'rustup.dart';
-import 'target.dart';
-
-final _log = Logger('precompile_binaries');
-
-class PrecompileBinaries {
- PrecompileBinaries({
- required this.privateKey,
- required this.githubToken,
- required this.repositorySlug,
- required this.manifestDir,
- required this.targets,
- this.androidSdkLocation,
- this.androidNdkVersion,
- this.androidMinSdkVersion,
- this.tempDir,
- });
-
- final PrivateKey privateKey;
- final String githubToken;
- final RepositorySlug repositorySlug;
- final String manifestDir;
- final List<Target> targets;
- final String? androidSdkLocation;
- final String? androidNdkVersion;
- final int? androidMinSdkVersion;
- final String? tempDir;
-
- static String fileName(Target target, String name) {
- return '${target.rust}_$name';
- }
-
- static String signatureFileName(Target target, String name) {
- return '${target.rust}_$name.sig';
- }
-
- Future<void> run() async {
- final crateInfo = CrateInfo.load(manifestDir);
-
- final targets = List.of(this.targets);
- if (targets.isEmpty) {
- targets.addAll([
- ...Target.buildableTargets(),
- if (androidSdkLocation != null) ...Target.androidTargets(),
- ]);
- }
-
- _log.info('Precompiling binaries for $targets');
-
- final hash = CrateHash.compute(manifestDir);
- _log.info('Computed crate hash: $hash');
-
- final String tagName = 'precompiled_$hash';
-
- final github = GitHub(auth: Authentication.withToken(githubToken));
- final repo = github.repositories;
- final release = await _getOrCreateRelease(
- repo: repo,
- tagName: tagName,
- packageName: crateInfo.packageName,
- hash: hash,
- );
-
- final tempDir = this.tempDir != null
- ? Directory(this.tempDir!)
- : Directory.systemTemp.createTempSync('precompiled_');
-
- tempDir.createSync(recursive: true);
-
- final crateOptions = CargokitCrateOptions.load(manifestDir: manifestDir);
-
- final buildEnvironment = BuildEnvironment(
- configuration: BuildConfiguration.release,
- crateOptions: crateOptions,
- targetTempDir: tempDir.path,
- manifestDir: manifestDir,
- crateInfo: crateInfo,
- isAndroid: androidSdkLocation != null,
- androidSdkPath: androidSdkLocation,
- androidNdkVersion: androidNdkVersion,
- androidMinSdkVersion: androidMinSdkVersion,
- );
-
- final rustup = Rustup();
-
- for (final target in targets) {
- final artifactNames = getArtifactNames(
- target: target,
- libraryName: crateInfo.packageName,
- remote: true,
- );
-
- if (artifactNames.every((name) {
- final fileName = PrecompileBinaries.fileName(target, name);
- return (release.assets ?? []).any((e) => e.name == fileName);
- })) {
- _log.info("All artifacts for $target already exist - skipping");
- continue;
- }
-
- _log.info('Building for $target');
-
- final builder = RustBuilder(
- target: target,
- environment: buildEnvironment,
- );
- builder.prepare(rustup);
- final res = await builder.build();
-
- final assets = <CreateReleaseAsset>[];
- for (final name in artifactNames) {
- final file = File(path.join(res, name));
- if (!file.existsSync()) {
- throw Exception('Missing artifact: ${file.path}');
- }
-
- final data = file.readAsBytesSync();
- final create = CreateReleaseAsset(
- name: PrecompileBinaries.fileName(target, name),
- contentType: "application/octet-stream",
- assetData: data,
- );
- final signature = sign(privateKey, data);
- final signatureCreate = CreateReleaseAsset(
- name: signatureFileName(target, name),
- contentType: "application/octet-stream",
- assetData: signature,
- );
- bool verified = verify(public(privateKey), data, signature);
- if (!verified) {
- throw Exception('Signature verification failed');
- }
- assets.add(create);
- assets.add(signatureCreate);
- }
- _log.info('Uploading assets: ${assets.map((e) => e.name)}');
- for (final asset in assets) {
- // This seems to be failing on CI so do it one by one
- int retryCount = 0;
- while (true) {
- try {
- await repo.uploadReleaseAssets(release, [asset]);
- break;
- } on Exception catch (e) {
- if (retryCount == 10) {
- rethrow;
- }
- ++retryCount;
- _log.shout(
- 'Upload failed (attempt $retryCount, will retry): ${e.toString()}',
- );
- await Future.delayed(Duration(seconds: 2));
- }
- }
- }
- }
-
- _log.info('Cleaning up');
- tempDir.deleteSync(recursive: true);
- }
-
- Future<Release> _getOrCreateRelease({
- required RepositoriesService repo,
- required String tagName,
- required String packageName,
- required String hash,
- }) async {
- Release release;
- try {
- _log.info('Fetching release $tagName');
- release = await repo.getReleaseByTagName(repositorySlug, tagName);
- } on ReleaseNotFound {
- _log.info('Release not found - creating release $tagName');
- release = await repo.createRelease(
- repositorySlug,
- CreateRelease.from(
- tagName: tagName,
- name: 'Precompiled binaries ${hash.substring(0, 8)}',
- targetCommitish: null,
- isDraft: false,
- isPrerelease: false,
- body:
- 'Precompiled binaries for crate $packageName, '
- 'crate hash $hash.',
- ),
- );
- }
- return release;
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/rustup.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/rustup.dart
deleted file mode 100644
index fd012e00fe..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/rustup.dart
+++ /dev/null
@@ -1,146 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:collection/collection.dart';
-import 'package:path/path.dart' as path;
-
-import 'util.dart';
-
-class _Toolchain {
- _Toolchain(this.name, this.targets);
-
- final String name;
- final List<String> targets;
-}
-
-class Rustup {
- List<String>? installedTargets(String toolchain) {
- final targets = _installedTargets(toolchain);
- return targets != null ? List.unmodifiable(targets) : null;
- }
-
- void installToolchain(String toolchain) {
- log.info("Installing Rust toolchain: $toolchain");
- runCommand("rustup", ['toolchain', 'install', toolchain]);
- _installedToolchains.add(
- _Toolchain(toolchain, _getInstalledTargets(toolchain)),
- );
- }
-
- void installTarget(String target, {required String toolchain}) {
- log.info("Installing Rust target: $target");
- final lockFile = File(
- path.join(
- Directory.systemTemp.path,
- 'cargokit_rustup_target_${toolchain}_$target.lock',
- ),
- );
- lockFile.createSync(recursive: true);
- final lock = lockFile.openSync(mode: FileMode.write);
- var lockAcquired = false;
- try {
- lock.lockSync(FileLock.blockingExclusive);
- lockAcquired = true;
- if (_getInstalledTargets(toolchain).contains(target)) {
- _installedTargets(toolchain)?.add(target);
- return;
- }
- runCommand("rustup", ['target', 'add', '--toolchain', toolchain, target]);
- _installedTargets(toolchain)?.add(target);
- } finally {
- if (lockAcquired) {
- lock.unlockSync();
- }
- lock.closeSync();
- }
- }
-
- final List<_Toolchain> _installedToolchains;
-
- Rustup() : _installedToolchains = _getInstalledToolchains();
-
- List<String>? _installedTargets(String toolchain) => _installedToolchains
- .firstWhereOrNull(
- (e) => e.name == toolchain || e.name.startsWith('$toolchain-'),
- )
- ?.targets;
-
- static List<_Toolchain> _getInstalledToolchains() {
- String extractToolchainName(String line) {
- // ignore (default) after toolchain name
- final parts = line.split(' ');
- return parts[0];
- }
-
- final res = runCommand("rustup", ['toolchain', 'list']);
-
- // To list all non-custom toolchains, we need to filter out lines that
- // don't start with "stable", "beta", or "nightly".
- Pattern nonCustom = RegExp(r"^(stable|beta|nightly)");
- final lines = res.stdout
- .toString()
- .split('\n')
- .where((e) => e.isNotEmpty && e.startsWith(nonCustom))
- .map(extractToolchainName)
- .toList(growable: true);
-
- return lines
- .map((name) => _Toolchain(name, _getInstalledTargets(name)))
- .toList(growable: true);
- }
-
- static List<String> _getInstalledTargets(String toolchain) {
- final res = runCommand("rustup", [
- 'target',
- 'list',
- '--toolchain',
- toolchain,
- '--installed',
- ]);
- final lines = res.stdout
- .toString()
- .split('\n')
- .where((e) => e.isNotEmpty)
- .toList(growable: true);
- return lines;
- }
-
- bool _didInstallRustSrcForNightly = false;
-
- void installRustSrcForNightly() {
- if (_didInstallRustSrcForNightly) {
- return;
- }
- // Useful for -Z build-std
- runCommand("rustup", [
- 'component',
- 'add',
- 'rust-src',
- '--toolchain',
- 'nightly',
- ]);
- _didInstallRustSrcForNightly = true;
- }
-
- static String? executablePath() {
- final envPath = Platform.environment['PATH'];
- final envPathSeparator = Platform.isWindows ? ';' : ':';
- final home = Platform.isWindows
- ? Platform.environment['USERPROFILE']
- : Platform.environment['HOME'];
- final paths = [
- if (home != null) path.join(home, '.cargo', 'bin'),
- if (envPath != null) ...envPath.split(envPathSeparator),
- ];
- for (final p in paths) {
- final rustup = Platform.isWindows ? 'rustup.exe' : 'rustup';
- final rustupPath = path.join(p, rustup);
- if (File(rustupPath).existsSync()) {
- return rustupPath;
- }
- }
- return null;
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/target.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/target.dart
deleted file mode 100644
index dc7145dc45..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/target.dart
+++ /dev/null
@@ -1,134 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:collection/collection.dart';
-
-import 'util.dart';
-
-class Target {
- Target({
- required this.rust,
- this.flutter,
- this.android,
- this.androidMinSdkVersion,
- this.darwinPlatform,
- this.darwinArch,
- });
-
- static final all = [
- Target(
- rust: 'armv7-linux-androideabi',
- flutter: 'android-arm',
- android: 'armeabi-v7a',
- androidMinSdkVersion: 16,
- ),
- Target(
- rust: 'aarch64-linux-android',
- flutter: 'android-arm64',
- android: 'arm64-v8a',
- androidMinSdkVersion: 21,
- ),
- Target(
- rust: 'i686-linux-android',
- flutter: 'android-x86',
- android: 'x86',
- androidMinSdkVersion: 16,
- ),
- Target(
- rust: 'x86_64-linux-android',
- flutter: 'android-x64',
- android: 'x86_64',
- androidMinSdkVersion: 21,
- ),
- Target(rust: 'x86_64-pc-windows-msvc', flutter: 'windows-x64'),
- Target(rust: 'x86_64-unknown-linux-gnu', flutter: 'linux-x64'),
- Target(rust: 'aarch64-unknown-linux-gnu', flutter: 'linux-arm64'),
- Target(
- rust: 'x86_64-apple-darwin',
- darwinPlatform: 'macosx',
- darwinArch: 'x86_64',
- ),
- Target(
- rust: 'aarch64-apple-darwin',
- darwinPlatform: 'macosx',
- darwinArch: 'arm64',
- ),
- Target(
- rust: 'aarch64-apple-ios',
- darwinPlatform: 'iphoneos',
- darwinArch: 'arm64',
- ),
- Target(
- rust: 'aarch64-apple-ios-sim',
- darwinPlatform: 'iphonesimulator',
- darwinArch: 'arm64',
- ),
- Target(
- rust: 'x86_64-apple-ios',
- darwinPlatform: 'iphonesimulator',
- darwinArch: 'x86_64',
- ),
- ];
-
- static Target? forFlutterName(String flutterName) {
- return all.firstWhereOrNull((element) => element.flutter == flutterName);
- }
-
- static Target? forDarwin({
- required String platformName,
- required String darwinAarch,
- }) {
- return all.firstWhereOrNull(
- (element) => //
- element.darwinPlatform == platformName &&
- element.darwinArch == darwinAarch,
- );
- }
-
- static Target? forRustTriple(String triple) {
- return all.firstWhereOrNull((element) => element.rust == triple);
- }
-
- static List<Target> androidTargets() {
- return all
- .where((element) => element.android != null)
- .toList(growable: false);
- }
-
- static List<Target> buildableTargets() {
- if (Platform.isLinux) {
- // Right now we don't support cross-compiling on Linux. So we just return
- // the host target.
- final arch = runCommand('arch', []).stdout as String;
- if (arch.trim() == 'aarch64') {
- return [Target.forRustTriple('aarch64-unknown-linux-gnu')!];
- } else {
- return [Target.forRustTriple('x86_64-unknown-linux-gnu')!];
- }
- }
- return all
- .where((target) {
- if (Platform.isWindows) {
- return target.rust.contains('-windows-');
- } else if (Platform.isMacOS) {
- return target.darwinPlatform != null;
- }
- return false;
- })
- .toList(growable: false);
- }
-
- @override
- String toString() {
- return rust;
- }
-
- final String? flutter;
- final String rust;
- final String? android;
- final int? androidMinSdkVersion;
- final String? darwinPlatform;
- final String? darwinArch;
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/util.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/util.dart
deleted file mode 100644
index 863ff025f2..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/util.dart
+++ /dev/null
@@ -1,174 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:logging/logging.dart';
-import 'package:path/path.dart' as path;
-
-import 'logging.dart';
-import 'rustup.dart';
-
-final log = Logger("process");
-
-class CommandFailedException implements Exception {
- final String executable;
- final List<String> arguments;
- final ProcessResult result;
-
- CommandFailedException({
- required this.executable,
- required this.arguments,
- required this.result,
- });
-
- @override
- String toString() {
- final stdout = result.stdout.toString().trim();
- final stderr = result.stderr.toString().trim();
- return [
- "External Command: $executable ${arguments.map((e) => '"$e"').join(' ')}",
- "Returned Exit Code: ${result.exitCode}",
- kSeparator,
- "STDOUT:",
- if (stdout.isNotEmpty) stdout,
- kSeparator,
- "STDERR:",
- if (stderr.isNotEmpty) stderr,
- ].join('\n');
- }
-}
-
-class TestRunCommandArgs {
- final String executable;
- final List<String> arguments;
- final String? workingDirectory;
- final Map<String, String>? environment;
- final bool includeParentEnvironment;
- final bool runInShell;
- final Encoding? stdoutEncoding;
- final Encoding? stderrEncoding;
-
- TestRunCommandArgs({
- required this.executable,
- required this.arguments,
- this.workingDirectory,
- this.environment,
- this.includeParentEnvironment = true,
- this.runInShell = false,
- this.stdoutEncoding,
- this.stderrEncoding,
- });
-}
-
-class TestRunCommandResult {
- TestRunCommandResult({
- this.pid = 1,
- this.exitCode = 0,
- this.stdout = '',
- this.stderr = '',
- });
-
- final int pid;
- final int exitCode;
- final String stdout;
- final String stderr;
-}
-
-TestRunCommandResult Function(TestRunCommandArgs args)? testRunCommandOverride;
-
-ProcessResult runCommand(
- String executable,
- List<String> arguments, {
- String? workingDirectory,
- Map<String, String>? environment,
- bool includeParentEnvironment = true,
- bool runInShell = false,
- Encoding? stdoutEncoding = systemEncoding,
- Encoding? stderrEncoding = systemEncoding,
-}) {
- if (testRunCommandOverride != null) {
- final result = testRunCommandOverride!(
- TestRunCommandArgs(
- executable: executable,
- arguments: arguments,
- workingDirectory: workingDirectory,
- environment: environment,
- includeParentEnvironment: includeParentEnvironment,
- runInShell: runInShell,
- stdoutEncoding: stdoutEncoding,
- stderrEncoding: stderrEncoding,
- ),
- );
- return ProcessResult(
- result.pid,
- result.exitCode,
- result.stdout,
- result.stderr,
- );
- }
- log.finer('Running command $executable ${arguments.join(' ')}');
- final res = Process.runSync(
- _resolveExecutable(executable),
- arguments,
- workingDirectory: workingDirectory,
- environment: environment,
- includeParentEnvironment: includeParentEnvironment,
- runInShell: runInShell,
- stderrEncoding: stderrEncoding,
- stdoutEncoding: stdoutEncoding,
- );
- if (res.exitCode != 0) {
- throw CommandFailedException(
- executable: executable,
- arguments: arguments,
- result: res,
- );
- } else {
- return res;
- }
-}
-
-class RustupNotFoundException implements Exception {
- @override
- String toString() {
- return [
- ' ',
- 'rustup not found in PATH.',
- ' ',
- 'Maybe you need to install Rust? It only takes a minute:',
- ' ',
- if (Platform.isWindows) 'https://www.rust-lang.org/tools/install',
- if (hasHomebrewRustInPath()) ...[
- '\$ brew unlink rust # Unlink homebrew Rust from PATH',
- ],
- if (!Platform.isWindows)
- "\$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh",
- ' ',
- ].join('\n');
- }
-
- static bool hasHomebrewRustInPath() {
- if (!Platform.isMacOS) {
- return false;
- }
- final envPath = Platform.environment['PATH'] ?? '';
- final paths = envPath.split(':');
- return paths.any((p) {
- return p.contains('homebrew') && File(path.join(p, 'rustc')).existsSync();
- });
- }
-}
-
-String _resolveExecutable(String executable) {
- if (executable == 'rustup') {
- final resolved = Rustup.executablePath();
- if (resolved != null) {
- return resolved;
- }
- throw RustupNotFoundException();
- } else {
- return executable;
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/lib/src/verify_binaries.dart b/mobile/packages/rust/cargokit/build_tool/lib/src/verify_binaries.dart
deleted file mode 100644
index d7dc1e5aa6..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/lib/src/verify_binaries.dart
+++ /dev/null
@@ -1,88 +0,0 @@
-// This is copied from Cargokit (which is the official way to use it currently)
-// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import 'dart:io';
-
-import 'package:ed25519_edwards/ed25519_edwards.dart';
-import 'package:http/http.dart';
-
-import 'artifacts_provider.dart';
-import 'cargo.dart';
-import 'crate_hash.dart';
-import 'options.dart';
-import 'precompile_binaries.dart';
-import 'target.dart';
-
-class VerifyBinaries {
- VerifyBinaries({required this.manifestDir});
-
- final String manifestDir;
-
- Future<void> run() async {
- final crateInfo = CrateInfo.load(manifestDir);
-
- final config = CargokitCrateOptions.load(manifestDir: manifestDir);
- final precompiledBinaries = config.precompiledBinaries;
- if (precompiledBinaries == null) {
- stdout.writeln('Crate does not support precompiled binaries.');
- } else {
- final crateHash = CrateHash.compute(manifestDir);
- stdout.writeln('Crate hash: $crateHash');
-
- for (final target in Target.all) {
- final message = 'Checking ${target.rust}...';
- stdout.write(message.padRight(40));
- stdout.flush();
-
- final artifacts = getArtifactNames(
- target: target,
- libraryName: crateInfo.packageName,
- remote: true,
- );
-
- final prefix = precompiledBinaries.uriPrefix;
-
- bool ok = true;
-
- for (final artifact in artifacts) {
- final fileName = PrecompileBinaries.fileName(target, artifact);
- final signatureFileName = PrecompileBinaries.signatureFileName(
- target,
- artifact,
- );
-
- final url = Uri.parse('$prefix$crateHash/$fileName');
- final signatureUrl = Uri.parse(
- '$prefix$crateHash/$signatureFileName',
- );
-
- final signature = await get(signatureUrl);
- if (signature.statusCode != 200) {
- stdout.writeln('MISSING');
- ok = false;
- break;
- }
- final asset = await get(url);
- if (asset.statusCode != 200) {
- stdout.writeln('MISSING');
- ok = false;
- break;
- }
-
- if (!verify(
- precompiledBinaries.publicKey,
- asset.bodyBytes,
- signature.bodyBytes,
- )) {
- stdout.writeln('INVALID SIGNATURE');
- ok = false;
- }
- }
-
- if (ok) {
- stdout.writeln('OK');
- }
- }
- }
- }
-}
diff --git a/mobile/packages/rust/cargokit/build_tool/pubspec.yaml b/mobile/packages/rust/cargokit/build_tool/pubspec.yaml
deleted file mode 100644
index 83147e9e68..0000000000
--- a/mobile/packages/rust/cargokit/build_tool/pubspec.yaml
+++ /dev/null
@@ -1,32 +0,0 @@
-# This is copied from Cargokit (which is the official way to use it currently)
-# Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-name: build_tool
-description: Cargokit build_tool. Facilitates the build of Rust crate during Flutter application build.
-publish_to: none
-version: 1.0.0
-
-environment:
- sdk: ">=3.10.0 <4.0.0"
-
-dependencies:
- # these are pinned on purpose because the bundle_tool_runner doesn't have
- # pubspec.lock. See run_build_tool.sh
- logging: 1.2.0
- path: 1.8.0
- version: 3.0.0
- collection: 1.18.0
- ed25519_edwards: 0.3.1
- hex: 0.2.0
- yaml: 3.1.2
- source_span: 1.10.0
- github: 9.17.0
- args: 2.4.2
- crypto: 3.0.3
- convert: 3.1.1
- http: 1.1.0
- toml: 0.14.0
-
-dev_dependencies:
- lints: 2.1.1
- test: 1.24.6
diff --git a/mobile/packages/rust/cargokit/cmake/cargokit.cmake b/mobile/packages/rust/cargokit/cmake/cargokit.cmake
deleted file mode 100644
index ddd05df9b4..0000000000
--- a/mobile/packages/rust/cargokit/cmake/cargokit.cmake
+++ /dev/null
@@ -1,99 +0,0 @@
-SET(cargokit_cmake_root "${CMAKE_CURRENT_LIST_DIR}/..")
-
-# Workaround for https://github.com/dart-lang/pub/issues/4010
-get_filename_component(cargokit_cmake_root "${cargokit_cmake_root}" REALPATH)
-
-if(WIN32)
- # REALPATH does not properly resolve symlinks on windows :-/
- execute_process(COMMAND powershell -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_LIST_DIR}/resolve_symlinks.ps1" "${cargokit_cmake_root}" OUTPUT_VARIABLE cargokit_cmake_root OUTPUT_STRIP_TRAILING_WHITESPACE)
-endif()
-
-# Arguments
-# - target: CMAKE target to which rust library is linked
-# - manifest_dir: relative path from current folder to directory containing cargo manifest
-# - lib_name: cargo package name
-# - any_symbol_name: name of any exported symbol from the library.
-# used on windows to force linking with library.
-function(apply_cargokit target manifest_dir lib_name any_symbol_name)
-
- set(CARGOKIT_LIB_NAME "${lib_name}")
- set(CARGOKIT_LIB_FULL_NAME "${CMAKE_SHARED_MODULE_PREFIX}${CARGOKIT_LIB_NAME}${CMAKE_SHARED_MODULE_SUFFIX}")
- if (CMAKE_CONFIGURATION_TYPES)
- set(CARGOKIT_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>")
- set(OUTPUT_LIB "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/${CARGOKIT_LIB_FULL_NAME}")
- else()
- set(CARGOKIT_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}")
- set(OUTPUT_LIB "${CMAKE_CURRENT_BINARY_DIR}/${CARGOKIT_LIB_FULL_NAME}")
- endif()
- set(CARGOKIT_TEMP_DIR "${CMAKE_CURRENT_BINARY_DIR}/cargokit_build")
-
- if (FLUTTER_TARGET_PLATFORM)
- set(CARGOKIT_TARGET_PLATFORM "${FLUTTER_TARGET_PLATFORM}")
- else()
- set(CARGOKIT_TARGET_PLATFORM "windows-x64")
- endif()
-
- set(CARGOKIT_ENV
- "CARGOKIT_CMAKE=${CMAKE_COMMAND}"
- "CARGOKIT_CONFIGURATION=$<CONFIG>"
- "CARGOKIT_MANIFEST_DIR=${CMAKE_CURRENT_SOURCE_DIR}/${manifest_dir}"
- "CARGOKIT_TARGET_TEMP_DIR=${CARGOKIT_TEMP_DIR}"
- "CARGOKIT_OUTPUT_DIR=${CARGOKIT_OUTPUT_DIR}"
- "CARGOKIT_TARGET_PLATFORM=${CARGOKIT_TARGET_PLATFORM}"
- "CARGOKIT_TOOL_TEMP_DIR=${CARGOKIT_TEMP_DIR}/tool"
- "CARGOKIT_ROOT_PROJECT_DIR=${CMAKE_SOURCE_DIR}"
- )
-
- if (WIN32)
- set(SCRIPT_EXTENSION ".cmd")
- set(IMPORT_LIB_EXTENSION ".lib")
- else()
- set(SCRIPT_EXTENSION ".sh")
- set(IMPORT_LIB_EXTENSION "")
- execute_process(COMMAND chmod +x "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}")
- endif()
-
- # Using generators in custom command is only supported in CMake 3.20+
- if (CMAKE_CONFIGURATION_TYPES AND ${CMAKE_VERSION} VERSION_LESS "3.20.0")
- foreach(CONFIG IN LISTS CMAKE_CONFIGURATION_TYPES)
- add_custom_command(
- OUTPUT
- "${CMAKE_CURRENT_BINARY_DIR}/${CONFIG}/${CARGOKIT_LIB_FULL_NAME}"
- "${CMAKE_CURRENT_BINARY_DIR}/_phony_"
- COMMAND ${CMAKE_COMMAND} -E env ${CARGOKIT_ENV}
- "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}" build-cmake
- VERBATIM
- )
- endforeach()
- else()
- add_custom_command(
- OUTPUT
- ${OUTPUT_LIB}
- "${CMAKE_CURRENT_BINARY_DIR}/_phony_"
- COMMAND ${CMAKE_COMMAND} -E env ${CARGOKIT_ENV}
- "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}" build-cmake
- VERBATIM
- )
- endif()
-
-
- set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/_phony_" PROPERTIES SYMBOLIC TRUE)
-
- if (TARGET ${target})
- # If we have actual cmake target provided create target and make existing
- # target depend on it
- add_custom_target("${target}_cargokit" DEPENDS ${OUTPUT_LIB})
- add_dependencies("${target}" "${target}_cargokit")
- target_link_libraries("${target}" PRIVATE "${OUTPUT_LIB}${IMPORT_LIB_EXTENSION}")
- if(WIN32)
- target_link_options(${target} PRIVATE "/INCLUDE:${any_symbol_name}")
- endif()
- else()
- # Otherwise (FFI) just use ALL to force building always
- add_custom_target("${target}_cargokit" ALL DEPENDS ${OUTPUT_LIB})
- endif()
-
- # Allow adding the output library to plugin bundled libraries
- set("${target}_cargokit_lib" ${OUTPUT_LIB} PARENT_SCOPE)
-
-endfunction()
diff --git a/mobile/packages/rust/cargokit/cmake/resolve_symlinks.ps1 b/mobile/packages/rust/cargokit/cmake/resolve_symlinks.ps1
deleted file mode 100644
index 2ac593a1ff..0000000000
--- a/mobile/packages/rust/cargokit/cmake/resolve_symlinks.ps1
+++ /dev/null
@@ -1,34 +0,0 @@
-function Resolve-Symlinks {
- [CmdletBinding()]
- [OutputType([string])]
- param(
- [Parameter(Position = 0, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
- [string] $Path
- )
-
- [string] $separator = '/'
- [string[]] $parts = $Path.Split($separator)
-
- [string] $realPath = ''
- foreach ($part in $parts) {
- if ($realPath -and !$realPath.EndsWith($separator)) {
- $realPath += $separator
- }
-
- $realPath += $part.Replace('\', '/')
-
- # The slash is important when using Get-Item on Drive letters in pwsh.
- if (-not($realPath.Contains($separator)) -and $realPath.EndsWith(':')) {
- $realPath += '/'
- }
-
- $item = Get-Item $realPath
- if ($item.LinkTarget) {
- $realPath = $item.LinkTarget.Replace('\', '/')
- }
- }
- $realPath
-}
-
-$path = Resolve-Symlinks -Path $args[0]
-Write-Host $path
diff --git a/mobile/packages/rust/cargokit/gradle/plugin.gradle b/mobile/packages/rust/cargokit/gradle/plugin.gradle
deleted file mode 100644
index c0748c9272..0000000000
--- a/mobile/packages/rust/cargokit/gradle/plugin.gradle
+++ /dev/null
@@ -1,172 +0,0 @@
-/// This is copied from Cargokit (which is the official way to use it currently)
-/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin
-
-import java.nio.file.Paths
-import org.apache.tools.ant.taskdefs.condition.Os
-
-CargoKitPlugin.file = buildscript.sourceFile
-
-apply plugin: CargoKitPlugin
-
-class CargoKitExtension {
- String manifestDir; // Relative path to folder containing Cargo.toml
- String libname; // Library name within Cargo.toml. Must be a cdylib
-}
-
-abstract class CargoKitBuildTask extends DefaultTask {
-
- @Input
- String buildMode
-
- @Input
- String buildDir
-
- @Input
- String outputDir
-
- @Input
- String ndkVersion
-
- @Input
- String sdkDirectory
-
- @Input
- int compileSdkVersion;
-
- @Input
- int minSdkVersion;
-
- @Input
- String pluginFile
-
- @Input
- List<String> targetPlatforms
-
- @TaskAction
- def build() {
- if (project.cargokit.manifestDir == null) {
- throw new GradleException("Property 'manifestDir' must be set on cargokit extension");
- }
-
- if (project.cargokit.libname == null) {
- throw new GradleException("Property 'libname' must be set on cargokit extension");
- }
-
- def executableName = Os.isFamily(Os.FAMILY_WINDOWS) ? "run_build_tool.cmd" : "run_build_tool.sh"
- def path = Paths.get(new File(pluginFile).parent, "..", executableName);
-
- def manifestDir = Paths.get(project.buildscript.sourceFile.parent, project.cargokit.manifestDir)
-
- def rootProjectDir = project.rootProject.projectDir
-
- if (!Os.isFamily(Os.FAMILY_WINDOWS)) {
- project.exec {
- commandLine 'chmod', '+x', path
- }
- }
-
- project.exec {
- executable path
- args "build-gradle"
- environment "CARGOKIT_ROOT_PROJECT_DIR", rootProjectDir
- environment "CARGOKIT_TOOL_TEMP_DIR", "${buildDir}/build_tool"
- environment "CARGOKIT_MANIFEST_DIR", manifestDir
- environment "CARGOKIT_CONFIGURATION", buildMode
- environment "CARGOKIT_TARGET_TEMP_DIR", buildDir
- environment "CARGOKIT_OUTPUT_DIR", outputDir
- environment "CARGOKIT_NDK_VERSION", ndkVersion
- environment "CARGOKIT_SDK_DIR", sdkDirectory
- environment "CARGOKIT_COMPILE_SDK_VERSION", compileSdkVersion
- environment "CARGOKIT_MIN_SDK_VERSION", minSdkVersion
- environment "CARGOKIT_TARGET_PLATFORMS", targetPlatforms.join(",")
- environment "CARGOKIT_JAVA_HOME", System.properties['java.home']
- }
- }
-}
-
-class CargoKitPlugin implements Plugin<Project> {
-
- static String file;
-
- private Plugin findFlutterPlugin(Project rootProject) {
- _findFlutterPlugin(rootProject.childProjects)
- }
-
- private Plugin _findFlutterPlugin(Map projects) {
- for (project in projects) {
- for (plugin in project.value.getPlugins()) {
- if (plugin.class.name == "com.flutter.gradle.FlutterPlugin") {
- return plugin;
- }
- }
- def plugin = _findFlutterPlugin(project.value.childProjects);
- if (plugin != null) {
- return plugin;
- }
- }
- return null;
- }
-
- @Override
- void apply(Project project) {
- def plugin = findFlutterPlugin(project.rootProject);
-
- project.extensions.create("cargokit", CargoKitExtension)
-
- if (plugin == null) {
- print("Flutter plugin not found, CargoKit plugin will not be applied.")
- return;
- }
-
- def cargoBuildDir = "${project.buildDir}/build"
-
- def isApplication = plugin.project.plugins.hasPlugin('com.android.application')
- def variants = isApplication ? plugin.project.android.applicationVariants : plugin.project.android.libraryVariants
-
- variants.all { variant ->
-
- final buildType = variant.buildType.name
-
- def cargoOutputDir = "${project.buildDir}/jniLibs/${buildType}";
- def jniLibs = project.android.sourceSets.maybeCreate(buildType).jniLibs;
- jniLibs.srcDir(new File(cargoOutputDir))
-
- def platforms = com.flutter.gradle.FlutterPluginUtils.getTargetPlatforms(project).collect()
-
- // The task name depends on plugin properties, which are not available
- // at this point
- project.getGradle().afterProject {
- def taskName = "cargokitCargoBuild${project.cargokit.libname.capitalize()}${buildType.capitalize()}";
-
- if (project.tasks.findByName(taskName)) {
- return
- }
-
- if (plugin.project.android.ndkVersion == null) {
- throw new GradleException("Please set 'android.ndkVersion' in 'app/build.gradle'.")
- }
-
- def task = project.tasks.create(taskName, CargoKitBuildTask.class) {
- buildMode = variant.buildType.name
- buildDir = cargoBuildDir
- outputDir = cargoOutputDir
- ndkVersion = plugin.project.android.ndkVersion
- sdkDirectory = plugin.project.android.sdkDirectory
- minSdkVersion = plugin.project.android.defaultConfig.minSdkVersion.apiLevel as int
- compileSdkVersion = plugin.project.android.compileSdkVersion.substring(8) as int
- targetPlatforms = platforms
- pluginFile = CargoKitPlugin.file
- }
- def onTask = { newTask ->
- if (newTask.name == "merge${buildType.capitalize()}NativeLibs") {
- newTask.dependsOn task
- // Fix gradle 7.4.2 not picking up JNI library changes
- newTask.outputs.upToDateWhen { false }
- }
- }
- project.tasks.each onTask
- project.tasks.whenTaskAdded onTask
- }
- }
- }
-}
diff --git a/mobile/packages/rust/cargokit/run_build_tool.cmd b/mobile/packages/rust/cargokit/run_build_tool.cmd
deleted file mode 100755
index c45d0aa8b5..0000000000
--- a/mobile/packages/rust/cargokit/run_build_tool.cmd
+++ /dev/null
@@ -1,91 +0,0 @@
-@echo off
-setlocal
-
-setlocal ENABLEDELAYEDEXPANSION
-
-SET BASEDIR=%~dp0
-
-if not exist "%CARGOKIT_TOOL_TEMP_DIR%" (
- mkdir "%CARGOKIT_TOOL_TEMP_DIR%"
-)
-cd /D "%CARGOKIT_TOOL_TEMP_DIR%"
-
-SET BUILD_TOOL_PKG_DIR=%BASEDIR%build_tool
-SET DART=%FLUTTER_ROOT%\bin\cache\dart-sdk\bin\dart
-
-set BUILD_TOOL_PKG_DIR_POSIX=%BUILD_TOOL_PKG_DIR:\=/%
-
-(
- echo name: build_tool_runner
- echo version: 1.0.0
- echo publish_to: none
- echo.
- echo environment:
- echo sdk: '^>=3.0.0 ^<4.0.0'
- echo.
- echo dependencies:
- echo build_tool:
- echo path: %BUILD_TOOL_PKG_DIR_POSIX%
-) >pubspec.yaml
-
-if not exist bin (
- mkdir bin
-)
-
-(
- echo import 'package:build_tool/build_tool.dart' as build_tool;
- echo void main^(List^<String^> args^) ^{
- echo build_tool.runMain^(args^);
- echo ^}
-) >bin\build_tool_runner.dart
-
-SET PRECOMPILED=bin\build_tool_runner.dill
-
-REM To detect changes in package we compare output of DIR /s (recursive)
-set PREV_PACKAGE_INFO=.dart_tool\package_info.prev
-set CUR_PACKAGE_INFO=.dart_tool\package_info.cur
-
-DIR "%BUILD_TOOL_PKG_DIR%" /s > "%CUR_PACKAGE_INFO%_orig"
-
-REM Last line in dir output is free space on harddrive. That is bound to
-REM change between invocation so we need to remove it
-(
- Set "Line="
- For /F "UseBackQ Delims=" %%A In ("%CUR_PACKAGE_INFO%_orig") Do (
- SetLocal EnableDelayedExpansion
- If Defined Line Echo !Line!
- EndLocal
- Set "Line=%%A")
-) >"%CUR_PACKAGE_INFO%"
-DEL "%CUR_PACKAGE_INFO%_orig"
-
-REM Compare current directory listing with previous
-FC /B "%CUR_PACKAGE_INFO%" "%PREV_PACKAGE_INFO%" > nul 2>&1
-
-If %ERRORLEVEL% neq 0 (
- REM Changed - copy current to previous and remove precompiled kernel
- if exist "%PREV_PACKAGE_INFO%" (
- DEL "%PREV_PACKAGE_INFO%"
- )
- MOVE /Y "%CUR_PACKAGE_INFO%" "%PREV_PACKAGE_INFO%"
- if exist "%PRECOMPILED%" (
- DEL "%PRECOMPILED%"
- )
-)
-
-REM There is no CUR_PACKAGE_INFO it was renamed in previous step to %PREV_PACKAGE_INFO%
-REM which means we need to do pub get and precompile
-if not exist "%PRECOMPILED%" (
- echo Running pub get in "%cd%"
- "%DART%" pub get --no-precompile
- "%DART%" compile kernel bin/build_tool_runner.dart
-)
-
-"%DART%" "%PRECOMPILED%" %*
-
-REM 253 means invalid snapshot version.
-If %ERRORLEVEL% equ 253 (
- "%DART%" pub get --no-precompile
- "%DART%" compile kernel bin/build_tool_runner.dart
- "%DART%" "%PRECOMPILED%" %*
-)
diff --git a/mobile/packages/rust/cargokit/run_build_tool.sh b/mobile/packages/rust/cargokit/run_build_tool.sh
deleted file mode 100755
index 749e8033fa..0000000000
--- a/mobile/packages/rust/cargokit/run_build_tool.sh
+++ /dev/null
@@ -1,97 +0,0 @@
-#!/usr/bin/env bash
-
-set -e
-
-BASEDIR=$(dirname "$0")
-
-mkdir -p "$CARGOKIT_TOOL_TEMP_DIR"
-
-cd "$CARGOKIT_TOOL_TEMP_DIR"
-
-# Write a very simple bin package in temp folder that depends on build_tool package
-# from Cargokit. This is done to ensure that we don't pollute Cargokit folder
-# with .dart_tool contents.
-
-BUILD_TOOL_PKG_DIR="$BASEDIR/build_tool"
-
-if [[ -z $FLUTTER_ROOT ]]; then # not defined
- DART=dart
-else
- DART="$FLUTTER_ROOT/bin/cache/dart-sdk/bin/dart"
-fi
-
-cat << EOF > "pubspec.yaml"
-name: build_tool_runner
-version: 1.0.0
-publish_to: none
-
-environment:
- sdk: '>=3.0.0 <4.0.0'
-
-dependencies:
- build_tool:
- path: "$BUILD_TOOL_PKG_DIR"
-EOF
-
-mkdir -p "bin"
-
-cat << EOF > "bin/build_tool_runner.dart"
-import 'package:build_tool/build_tool.dart' as build_tool;
-void main(List<String> args) {
- build_tool.runMain(args);
-}
-EOF
-
-if ! [ -x "$(command -v shasum)" ] && [ -x "$(command -v sha1sum)" ]; then
- shopt -s expand_aliases
- alias shasum="sha1sum"
-fi
-
-# Dart run will not cache any package that has a path dependency, which
-# is the case for our build_tool_runner. So instead we precompile the package
-# ourselves.
-# To invalidate the cached kernel we use the hash of ls -LR of the build_tool
-# package directory. This should be good enough, as the build_tool package
-# itself is not meant to have any path dependencies.
-
-if [[ "$OSTYPE" == "darwin"* ]]; then
- PACKAGE_HASH=$(ls -lTR "$BUILD_TOOL_PKG_DIR" | shasum)
-else
- PACKAGE_HASH=$(ls -lR --full-time "$BUILD_TOOL_PKG_DIR" | shasum)
-fi
-
-PACKAGE_HASH_FILE=".package_hash"
-
-if [ -f "$PACKAGE_HASH_FILE" ]; then
- EXISTING_HASH=$(cat "$PACKAGE_HASH_FILE")
- if [ "$PACKAGE_HASH" != "$EXISTING_HASH" ]; then
- rm "$PACKAGE_HASH_FILE"
- fi
-fi
-
-if [ ! -f "$PACKAGE_HASH_FILE" ]; then
- "$DART" pub get --no-precompile
- "$DART" compile kernel bin/build_tool_runner.dart
- echo "$PACKAGE_HASH" > "$PACKAGE_HASH_FILE"
-fi
-
-# Rebuild the tool if it was deleted by Android Studio
-if [ ! -f "bin/build_tool_runner.dill" ]; then
- "$DART" compile kernel bin/build_tool_runner.dart
-fi
-
-set +e
-
-"$DART" bin/build_tool_runner.dill "$@"
-
-exit_code=$?
-
-# 253 means invalid snapshot version.
-if [ $exit_code == 253 ]; then
- "$DART" pub get --no-precompile
- "$DART" compile kernel bin/build_tool_runner.dart
- "$DART" bin/build_tool_runner.dill "$@"
- exit_code=$?
-fi
-
-exit $exit_code
diff --git a/mobile/packages/rust/flutter_rust_bridge.yaml b/mobile/packages/rust/flutter_rust_bridge.yaml
deleted file mode 100644
index b1455484ba..0000000000
--- a/mobile/packages/rust/flutter_rust_bridge.yaml
+++ /dev/null
@@ -1,9 +0,0 @@
-rust_input: crate::api
-rust_root: ../../../rust/bindings/frb/ente-rust/
-dart_output: lib/src/rust
-dart_entrypoint_class_name: EnteRust
-
-dart_preamble: |
- // ignore_for_file: require_trailing_commas
-
-web: false
diff --git a/mobile/packages/rust/ios/Classes/dummy_file.c b/mobile/packages/rust/ios/Classes/dummy_file.c
deleted file mode 100644
index e06dab9968..0000000000
--- a/mobile/packages/rust/ios/Classes/dummy_file.c
+++ /dev/null
@@ -1 +0,0 @@
-// This is an empty file to force CocoaPods to create a framework.
diff --git a/mobile/packages/rust/ios/ente_rust.podspec b/mobile/packages/rust/ios/ente_rust.podspec
deleted file mode 100644
index 817881c7c2..0000000000
--- a/mobile/packages/rust/ios/ente_rust.podspec
+++ /dev/null
@@ -1,41 +0,0 @@
-Pod::Spec.new do |s|
- s.name = 'ente_rust'
- s.version = '0.0.1'
- s.summary = 'A new Flutter FFI plugin project.'
- s.description = <<-DESC
-A new Flutter FFI plugin project.
- DESC
- s.homepage = 'http://example.com'
- s.license = { :file => '../LICENSE' }
- s.author = { 'Your Company' => '[email protected]' }
-
- # This will ensure the source files in Classes/ are included in the native
- # builds of apps using this FFI plugin. Podspec does not support relative
- # paths, so Classes contains a forwarder C file that relatively imports
- # `../src/*` so that the C sources can be shared among all target platforms.
- s.source = { :path => '.' }
- s.source_files = 'Classes/**/*'
- s.dependency 'Flutter'
- s.platform = :ios, '11.0'
-
- # Flutter.framework does not contain a i386 slice.
- s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
- s.swift_version = '5.0'
-
- s.script_phase = {
- :name => 'Build Rust library',
- # First argument is relative path to the `rust` folder, second is name of rust library
- :script => 'sh "$PODS_TARGET_SRCROOT/../cargokit/build_pod.sh" ../../../../rust/bindings/frb/ente-rust ente_rust',
- :execution_position => :before_compile,
- :input_files => ['${BUILT_PRODUCTS_DIR}/cargokit_phony'],
- # Let XCode know that the static library referenced in -force_load below is
- # created by this build step.
- :output_files => ["${BUILT_PRODUCTS_DIR}/libente_rust.a"],
- }
- s.pod_target_xcconfig = {
- 'DEFINES_MODULE' => 'YES',
- # Flutter.framework does not contain a i386 slice.
- 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386',
- 'OTHER_LDFLAGS' => '-force_load ${BUILT_PRODUCTS_DIR}/libente_rust.a',
- }
-end
diff --git a/mobile/packages/rust/lib/ente_rust.dart b/mobile/packages/rust/lib/ente_rust.dart
deleted file mode 100644
index 028f364f67..0000000000
--- a/mobile/packages/rust/lib/ente_rust.dart
+++ /dev/null
@@ -1,5 +0,0 @@
-library;
-
-export 'src/rust/api/contacts.dart';
-export 'src/rust/api/log.dart';
-export 'src/rust/frb_generated.dart' show EnteRust;
diff --git a/mobile/packages/rust/linux/CMakeLists.txt b/mobile/packages/rust/linux/CMakeLists.txt
deleted file mode 100644
index 6a58d55505..0000000000
--- a/mobile/packages/rust/linux/CMakeLists.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-# The Flutter tooling requires that developers have CMake 3.10 or later
-# installed. You should not increase this version, as doing so will cause
-# the plugin to fail to compile for some customers of the plugin.
-cmake_minimum_required(VERSION 3.10)
-
-# Project-level configuration.
-set(PROJECT_NAME "ente_rust")
-project(${PROJECT_NAME} LANGUAGES CXX)
-
-include("../cargokit/cmake/cargokit.cmake")
-apply_cargokit(${PROJECT_NAME} ../../../../rust/bindings/frb/ente-rust ente_rust "")
-
-# List of absolute paths to libraries that should be bundled with the plugin.
-# This list could contain prebuilt libraries, or libraries created by an
-# external build triggered from this build file.
-set(ente_rust_bundled_libraries
- "${${PROJECT_NAME}_cargokit_lib}"
- PARENT_SCOPE
-)
diff --git a/mobile/packages/rust/macos/Classes/dummy_file.c b/mobile/packages/rust/macos/Classes/dummy_file.c
deleted file mode 100644
index e06dab9968..0000000000
--- a/mobile/packages/rust/macos/Classes/dummy_file.c
+++ /dev/null
@@ -1 +0,0 @@
-// This is an empty file to force CocoaPods to create a framework.
diff --git a/mobile/packages/rust/macos/ente_rust.podspec b/mobile/packages/rust/macos/ente_rust.podspec
deleted file mode 100644
index 6f3cba21ce..0000000000
--- a/mobile/packages/rust/macos/ente_rust.podspec
+++ /dev/null
@@ -1,40 +0,0 @@
-Pod::Spec.new do |s|
- s.name = 'ente_rust'
- s.version = '0.0.1'
- s.summary = 'A new Flutter FFI plugin project.'
- s.description = <<-DESC
-A new Flutter FFI plugin project.
- DESC
- s.homepage = 'http://example.com'
- s.license = { :file => '../LICENSE' }
- s.author = { 'Your Company' => '[email protected]' }
-
- # This will ensure the source files in Classes/ are included in the native
- # builds of apps using this FFI plugin. Podspec does not support relative
- # paths, so Classes contains a forwarder C file that relatively imports
- # `../src/*` so that the C sources can be shared among all target platforms.
- s.source = { :path => '.' }
- s.source_files = 'Classes/**/*'
- s.dependency 'FlutterMacOS'
-
- s.platform = :osx, '10.11'
- s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
- s.swift_version = '5.0'
-
- s.script_phase = {
- :name => 'Build Rust library',
- # First argument is relative path to the `rust` folder, second is name of rust library
- :script => 'sh "$PODS_TARGET_SRCROOT/../cargokit/build_pod.sh" ../../../../rust/bindings/frb/ente-rust ente_rust',
- :execution_position => :before_compile,
- :input_files => ['${BUILT_PRODUCTS_DIR}/cargokit_phony'],
- # Let XCode know that the static library referenced in -force_load below is
- # created by this build step.
- :output_files => ["${BUILT_PRODUCTS_DIR}/libente_rust.a"],
- }
- s.pod_target_xcconfig = {
- 'DEFINES_MODULE' => 'YES',
- # Flutter.framework does not contain a i386 slice.
- 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386',
- 'OTHER_LDFLAGS' => '-force_load ${BUILT_PRODUCTS_DIR}/libente_rust.a',
- }
-end
diff --git a/mobile/packages/rust/pubspec.yaml b/mobile/packages/rust/pubspec.yaml
deleted file mode 100644
index bae6bfeb26..0000000000
--- a/mobile/packages/rust/pubspec.yaml
+++ /dev/null
@@ -1,38 +0,0 @@
-name: ente_rust
-description: A FFI plugin providing Dart bindings to the common Rust code shared by Ente apps
-
-resolution: workspace
-environment:
- sdk: ">=3.10.0 <4.0.0"
- flutter: '>=3.3.0'
-
-dependencies:
- flutter:
- sdk: flutter
- flutter_rust_bridge: 2.12.0
- freezed_annotation: 3.1.0
-
-dev_dependencies:
- ffi: 2.2.0
- ffigen: 13.0.0
- flutter_test:
- sdk: flutter
- flutter_lints: 6.0.0
- integration_test:
- sdk: flutter
- build_runner: 2.13.1
- freezed: 3.2.3
-
-flutter:
- plugin:
- platforms:
- android:
- ffiPlugin: true
- ios:
- ffiPlugin: true
- linux:
- ffiPlugin: true
- macos:
- ffiPlugin: true
- windows:
- ffiPlugin: true
diff --git a/mobile/packages/rust/windows/.gitignore b/mobile/packages/rust/windows/.gitignore
deleted file mode 100644
index f68e1be09f..0000000000
--- a/mobile/packages/rust/windows/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-flutter/
diff --git a/mobile/packages/rust/windows/CMakeLists.txt b/mobile/packages/rust/windows/CMakeLists.txt
deleted file mode 100644
index 8c57ebea2f..0000000000
--- a/mobile/packages/rust/windows/CMakeLists.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-# The Flutter tooling requires that developers have a version of Visual Studio
-# installed that includes CMake 3.14 or later. You should not increase this
-# version, as doing so will cause the plugin to fail to compile for some
-# customers of the plugin.
-cmake_minimum_required(VERSION 3.14)
-
-# Project-level configuration.
-set(PROJECT_NAME "ente_rust")
-project(${PROJECT_NAME} LANGUAGES CXX)
-
-include("../cargokit/cmake/cargokit.cmake")
-apply_cargokit(${PROJECT_NAME} ../../../../rust/bindings/frb/ente-rust ente_rust "")
-
-# List of absolute paths to libraries that should be bundled with the plugin.
-# This list could contain prebuilt libraries, or libraries created by an
-# external build triggered from this build file.
-set(ente_rust_bundled_libraries
- "${${PROJECT_NAME}_cargokit_lib}"
- PARENT_SCOPE
-)
diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock
index 4bcc2625d2..0bf68b8e47 100644
--- a/mobile/pubspec.lock
+++ b/mobile/pubspec.lock
@@ -705,14 +705,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.2.0"
- ffigen:
- dependency: transitive
- description:
- name: ffigen
- sha256: "10cb41647d73e0204f8d35138a3f20eb52418cce96599ad49167b1111e59a557"
- url: "https://pub.dev"
- source: hosted
- version: "13.0.0"
ffmpeg_kit_flutter:
dependency: transitive
description:
@@ -3228,14 +3220,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.3"
- yaml_edit:
- dependency: transitive
- description:
- name: yaml_edit
- sha256: "07c9e63ba42519745182b88ca12264a7ba2484d8239958778dfe4d44fe760488"
- url: "https://pub.dev"
- source: hosted
- version: "2.2.4"
zxing2:
dependency: transitive
description:
diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml
index 9b1e88c093..cffec16e95 100644
--- a/mobile/pubspec.yaml
+++ b/mobile/pubspec.yaml
@@ -39,7 +39,6 @@ workspace:
- packages/native_video_editor
- packages/network
- packages/qr
- - packages/rust
- packages/scoped_dir_access
- packages/screen_cover
- packages/sharing
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 216958e40c..3e6efd9a66 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2684,6 +2684,9 @@ dependencies = [
name = "ente_locker_rust"
version = "0.0.0"
dependencies = [
+ "ente-accounts",
+ "ente-contacts",
+ "ente-core",
"ente-frb-log",
"flutter_rust_bridge",
]
@@ -2705,7 +2708,10 @@ dependencies = [
name = "ente_photos_rust"
version = "0.0.0"
dependencies = [
+ "ente-accounts",
"ente-cast",
+ "ente-contacts",
+ "ente-core",
"ente-frb-log",
"ente-image",
"ente-ml",
@@ -2713,17 +2719,6 @@ dependencies = [
"flutter_rust_bridge",
]
-[[package]]
-name = "ente_rust"
-version = "0.0.0"
-dependencies = [
- "ente-accounts",
- "ente-contacts",
- "ente-core",
- "ente-frb-log",
- "flutter_rust_bridge",
-]
-
[[package]]
name = "enum-iterator"
version = "1.5.0"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index ff23229c42..fed3d976e4 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -4,7 +4,6 @@ members = [
"apps/cli",
"apps/codegen",
"apps/ensu/src-tauri",
- "bindings/frb/ente-rust",
"bindings/frb/locker",
"bindings/frb/log",
"bindings/frb/photos",
diff --git a/rust/apps/codegen/src/main.rs b/rust/apps/codegen/src/main.rs
index 8597999443..c267b142b4 100644
--- a/rust/apps/codegen/src/main.rs
+++ b/rust/apps/codegen/src/main.rs
@@ -29,7 +29,6 @@ enum NativeTarget {
#[derive(Clone, Copy)]
enum FrbTarget {
All,
- Shared,
Photos,
Locker,
}
@@ -59,7 +58,6 @@ fn run() -> Result<(), DynError> {
Some("frb") => {
let target = match args.next().as_deref() {
None => FrbTarget::All,
- Some("shared") => FrbTarget::Shared,
Some("photos") => FrbTarget::Photos,
Some("locker") => FrbTarget::Locker,
_ => return Err(usage_error()),
@@ -80,7 +78,7 @@ fn run() -> Result<(), DynError> {
}
fn usage_error() -> DynError {
- "usage: cargo codegen <native [ensu|cast]|frb [shared|photos|locker]|napi>".into()
+ "usage: cargo codegen <native [ensu|cast]|frb [photos|locker]|napi>".into()
}
fn generate_native(target: NativeTarget) -> Result<(), DynError> {
@@ -166,9 +164,6 @@ fn generate_frb(target: FrbTarget) -> Result<(), DynError> {
.parent()
.ok_or("failed to resolve repo root from rust/apps/codegen")?;
- if matches!(target, FrbTarget::All | FrbTarget::Shared) {
- generate_frb_package(&repo_root.join("mobile/packages/rust"))?;
- }
if matches!(target, FrbTarget::All | FrbTarget::Photos) {
generate_frb_package(&repo_root.join("mobile/apps/photos"))?;
}
@@ -301,16 +296,11 @@ fn format_frb_bindings(target: FrbTarget) -> Result<(), DynError> {
match target {
FrbTarget::All => {
command
- .arg("-p")
- .arg("ente_rust")
.arg("-p")
.arg("ente_photos_rust")
.arg("-p")
.arg("ente_locker_rust");
}
- FrbTarget::Shared => {
- command.arg("-p").arg("ente_rust");
- }
FrbTarget::Photos => {
command.arg("-p").arg("ente_photos_rust");
}
diff --git a/rust/bindings/frb/ente-rust/Cargo.toml b/rust/bindings/frb/ente-rust/Cargo.toml
deleted file mode 100644
index 1fef786422..0000000000
--- a/rust/bindings/frb/ente-rust/Cargo.toml
+++ /dev/null
@@ -1,20 +0,0 @@
-[package]
-name = "ente_rust"
-edition = "2024"
-
-[lib]
-crate-type = ["cdylib", "staticlib"]
-
-[dependencies]
-ente-accounts.workspace = true
-ente-contacts.workspace = true
-ente-core.workspace = true
-ente-frb-log.workspace = true
-flutter_rust_bridge.workspace = true
-
-[features]
-default = []
-flutter = []
-
-[lints.rust]
-unexpected_cfgs = { level = "warn", check-cfg = ['cfg(frb_expand)'] }
diff --git a/rust/bindings/frb/ente-rust/cargokit.yaml b/rust/bindings/frb/ente-rust/cargokit.yaml
deleted file mode 100644
index 56a90aa824..0000000000
--- a/rust/bindings/frb/ente-rust/cargokit.yaml
+++ /dev/null
@@ -1,7 +0,0 @@
-cargo:
- debug:
- extra_flags: ["--features", "flutter"]
- profile:
- extra_flags: ["--features", "flutter"]
- release:
- extra_flags: ["--features", "flutter"]
diff --git a/rust/bindings/frb/ente-rust/src/api/init.rs b/rust/bindings/frb/ente-rust/src/api/init.rs
deleted file mode 100644
index 44433ef339..0000000000
--- a/rust/bindings/frb/ente-rust/src/api/init.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-#[flutter_rust_bridge::frb(init)]
-pub fn init_app() {
- // Install before FRB claims the process logger.
- #[cfg(feature = "flutter")]
- crate::api::log::install();
- flutter_rust_bridge::setup_default_user_utils();
-}
diff --git a/rust/bindings/frb/ente-rust/src/api/log.rs b/rust/bindings/frb/ente-rust/src/api/log.rs
deleted file mode 100644
index d7dc13d971..0000000000
--- a/rust/bindings/frb/ente-rust/src/api/log.rs
+++ /dev/null
@@ -1 +0,0 @@
-ente_frb_log::setup!(crate::frb_generated::StreamSink);
diff --git a/rust/bindings/frb/ente-rust/src/api/mod.rs b/rust/bindings/frb/ente-rust/src/api/mod.rs
deleted file mode 100644
index ffd58f3423..0000000000
--- a/rust/bindings/frb/ente-rust/src/api/mod.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-pub mod contacts;
-pub mod init;
-#[cfg(any(feature = "flutter", frb_expand))]
-pub mod log;
-pub mod urls;
diff --git a/rust/bindings/frb/ente-rust/src/lib.rs b/rust/bindings/frb/ente-rust/src/lib.rs
deleted file mode 100644
index 0a29e8ff92..0000000000
--- a/rust/bindings/frb/ente-rust/src/lib.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-pub mod api;
-
-#[cfg(feature = "flutter")]
-#[rustfmt::skip]
-mod frb_generated;
diff --git a/rust/bindings/frb/locker/Cargo.toml b/rust/bindings/frb/locker/Cargo.toml
index bdac39c34d..4f04ad9af5 100644
--- a/rust/bindings/frb/locker/Cargo.toml
+++ b/rust/bindings/frb/locker/Cargo.toml
@@ -6,6 +6,9 @@ edition = "2024"
crate-type = ["cdylib", "staticlib"]
[dependencies]
+ente-accounts.workspace = true
+ente-contacts.workspace = true
+ente-core.workspace = true
ente-frb-log.workspace = true
flutter_rust_bridge.workspace = true
diff --git a/rust/bindings/frb/ente-rust/src/api/contacts.rs b/rust/bindings/frb/locker/src/api/contacts.rs
similarity index 100%
rename from rust/bindings/frb/ente-rust/src/api/contacts.rs
rename to rust/bindings/frb/locker/src/api/contacts.rs
diff --git a/rust/bindings/frb/locker/src/api/mod.rs b/rust/bindings/frb/locker/src/api/mod.rs
index f4ba0587c7..6bb4a97b24 100644
--- a/rust/bindings/frb/locker/src/api/mod.rs
+++ b/rust/bindings/frb/locker/src/api/mod.rs
@@ -1,3 +1,4 @@
+pub mod contacts;
pub mod init;
#[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 76b7fa9939..e8efeb5a35 100644
--- a/rust/bindings/frb/photos/Cargo.toml
+++ b/rust/bindings/frb/photos/Cargo.toml
@@ -6,7 +6,10 @@ edition = "2024"
crate-type = ["cdylib", "staticlib"]
[dependencies]
+ente-accounts.workspace = true
ente-cast.workspace = true
+ente-contacts.workspace = true
+ente-core.workspace = true
ente-frb-log.workspace = true
ente-image.workspace = true
ente-ml = { workspace = true, features = ["usearch"] }
diff --git a/rust/bindings/frb/photos/src/api/contacts.rs b/rust/bindings/frb/photos/src/api/contacts.rs
new file mode 100644
index 0000000000..cba55d7556
--- /dev/null
+++ b/rust/bindings/frb/photos/src/api/contacts.rs
@@ -0,0 +1,619 @@
+use std::sync::Arc;
+
+use ente_contacts::{LegacyKitOwnerRecoverySession, LegacyKitRecoveryInitiator};
+use flutter_rust_bridge::frb;
+
+#[frb]
+pub enum ContactsError {
+ Network { message: String },
+ Http { message: String },
+ Parse { message: String },
+ Crypto { message: String },
+ Auth { message: String },
+ InvalidInput { message: String },
+ MissingEncryptedData { message: String },
+ MissingEncryptedKey { message: String },
+ ProfilePictureNotFound { message: String },
+ ActiveRecoverySession { message: String },
+}
+
+impl From<ente_contacts::Error> for ContactsError {
+ fn from(e: ente_contacts::Error) -> Self {
+ use ente_contacts::ErrorKind as K;
+ let message = ente_core::error::chain(&e);
+ match e.kind() {
+ K::Network => Self::Network { message },
+ K::Http => Self::Http { message },
+ K::Parse => Self::Parse { message },
+ K::Crypto => Self::Crypto { message },
+ K::Auth => Self::Auth { message },
+ K::InvalidInput => Self::InvalidInput { message },
+ K::MissingEncryptedData => Self::MissingEncryptedData { message },
+ K::MissingEncryptedKey => Self::MissingEncryptedKey { message },
+ K::ProfilePictureNotFound => Self::ProfilePictureNotFound { message },
+ K::ActiveRecoverySession => Self::ActiveRecoverySession { message },
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct WrappedRootContactKey {
+ pub encrypted_key: String,
+ pub header: String,
+}
+
+impl From<ente_contacts::WrappedRootContactKey> for WrappedRootContactKey {
+ fn from(value: ente_contacts::WrappedRootContactKey) -> Self {
+ Self {
+ encrypted_key: value.encrypted_key,
+ header: value.header,
+ }
+ }
+}
+
+impl From<WrappedRootContactKey> for ente_contacts::WrappedRootContactKey {
+ fn from(value: WrappedRootContactKey) -> Self {
+ Self {
+ encrypted_key: value.encrypted_key,
+ header: value.header,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct AccountKeyAttributes {
+ pub kek_salt: String,
+ pub encrypted_key: String,
+ pub key_decryption_nonce: String,
+ pub public_key: String,
+ pub encrypted_secret_key: String,
+ pub secret_key_decryption_nonce: String,
+ pub mem_limit: u32,
+ pub ops_limit: u32,
+ pub master_key_encrypted_with_recovery_key: Option<String>,
+ pub master_key_decryption_nonce: Option<String>,
+ pub recovery_key_encrypted_with_master_key: Option<String>,
+ pub recovery_key_decryption_nonce: Option<String>,
+}
+
+impl From<AccountKeyAttributes> for ente_accounts::auth::KeyAttributes {
+ fn from(value: AccountKeyAttributes) -> Self {
+ Self {
+ kek_salt: value.kek_salt,
+ kek_hash: None,
+ encrypted_key: value.encrypted_key,
+ key_decryption_nonce: value.key_decryption_nonce,
+ public_key: value.public_key,
+ encrypted_secret_key: value.encrypted_secret_key,
+ secret_key_decryption_nonce: value.secret_key_decryption_nonce,
+ mem_limit: value.mem_limit,
+ ops_limit: value.ops_limit,
+ master_key_encrypted_with_recovery_key: value.master_key_encrypted_with_recovery_key,
+ master_key_decryption_nonce: value.master_key_decryption_nonce,
+ recovery_key_encrypted_with_master_key: value.recovery_key_encrypted_with_master_key,
+ recovery_key_decryption_nonce: value.recovery_key_decryption_nonce,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct ContactData {
+ pub contact_user_id: i64,
+ pub name: String,
+}
+
+impl From<ContactData> for ente_contacts::ContactData {
+ fn from(value: ContactData) -> Self {
+ Self {
+ contact_user_id: value.contact_user_id,
+ name: value.name,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct ContactRecord {
+ pub id: String,
+ pub contact_user_id: i64,
+ pub email: Option<String>,
+ pub name: Option<String>,
+ pub profile_picture_attachment_id: Option<String>,
+ pub is_deleted: bool,
+ pub created_at: i64,
+ pub updated_at: i64,
+}
+
+impl From<ente_contacts::ContactRecord> for ContactRecord {
+ fn from(value: ente_contacts::ContactRecord) -> Self {
+ Self {
+ id: value.id,
+ contact_user_id: value.contact_user_id,
+ email: value.email,
+ name: value.name,
+ profile_picture_attachment_id: value.profile_picture_attachment_id,
+ is_deleted: value.is_deleted,
+ created_at: value.created_at,
+ updated_at: value.updated_at,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone, Copy)]
+pub enum LegacyKitVariant {
+ TwoOfThree,
+}
+
+impl From<ente_contacts::LegacyKitVariant> for LegacyKitVariant {
+ fn from(value: ente_contacts::LegacyKitVariant) -> Self {
+ match value {
+ ente_contacts::LegacyKitVariant::TwoOfThree => Self::TwoOfThree,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone, Copy)]
+pub enum LegacyKitRecoveryStatus {
+ Waiting,
+ Ready,
+ Blocked,
+ Cancelled,
+ Recovered,
+}
+
+impl From<ente_contacts::LegacyKitRecoveryStatus> for LegacyKitRecoveryStatus {
+ fn from(value: ente_contacts::LegacyKitRecoveryStatus) -> Self {
+ match value {
+ ente_contacts::LegacyKitRecoveryStatus::Waiting => Self::Waiting,
+ ente_contacts::LegacyKitRecoveryStatus::Ready => Self::Ready,
+ ente_contacts::LegacyKitRecoveryStatus::Blocked => Self::Blocked,
+ ente_contacts::LegacyKitRecoveryStatus::Cancelled => Self::Cancelled,
+ ente_contacts::LegacyKitRecoveryStatus::Recovered => Self::Recovered,
+ }
+ }
+}
+
+#[frb]
+#[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_contacts::LegacyKitRecoverySession> for LegacyKitRecoverySession {
+ fn from(value: ente_contacts::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]
+#[derive(Clone)]
+pub struct LegacyKitRecoveryInitiatorHint {
+ pub used_part_indexes: Vec<u8>,
+ pub ip: String,
+ pub user_agent: String,
+}
+
+impl From<LegacyKitRecoveryInitiator> for LegacyKitRecoveryInitiatorHint {
+ fn from(value: LegacyKitRecoveryInitiator) -> Self {
+ Self {
+ used_part_indexes: value.used_part_indexes,
+ ip: value.ip,
+ user_agent: value.user_agent,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitOwnerRecoverySessionDetails {
+ pub session: Option<LegacyKitRecoverySession>,
+ pub initiators: Vec<LegacyKitRecoveryInitiatorHint>,
+}
+
+impl From<LegacyKitOwnerRecoverySession> for LegacyKitOwnerRecoverySessionDetails {
+ fn from(value: LegacyKitOwnerRecoverySession) -> Self {
+ Self {
+ session: value.session.map(Into::into),
+ initiators: value.initiators.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitPart {
+ pub index: u8,
+ pub name: String,
+}
+
+impl From<ente_contacts::LegacyKitPart> for LegacyKitPart {
+ fn from(value: ente_contacts::LegacyKitPart) -> Self {
+ Self {
+ index: value.index,
+ name: value.name,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitMetadata {
+ pub parts: Vec<LegacyKitPart>,
+}
+
+impl From<ente_contacts::LegacyKitMetadata> for LegacyKitMetadata {
+ fn from(value: ente_contacts::LegacyKitMetadata) -> Self {
+ Self {
+ parts: value.parts.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKit {
+ pub id: String,
+ pub variant: LegacyKitVariant,
+ pub notice_period_in_hours: i32,
+ pub legacy_url: String,
+ pub metadata: LegacyKitMetadata,
+ pub created_at: i64,
+ pub updated_at: i64,
+ pub active_recovery_session: Option<LegacyKitRecoverySession>,
+}
+
+impl From<ente_contacts::LegacyKit> for LegacyKit {
+ fn from(value: ente_contacts::LegacyKit) -> Self {
+ Self {
+ id: value.id,
+ variant: value.variant.into(),
+ notice_period_in_hours: value.notice_period_in_hours,
+ legacy_url: value.legacy_url,
+ metadata: value.metadata.into(),
+ created_at: value.created_at,
+ updated_at: value.updated_at,
+ active_recovery_session: value.active_recovery_session.map(Into::into),
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitShare {
+ pub payload_version: u8,
+ pub variant: LegacyKitVariant,
+ pub kit_id: String,
+ pub share_index: u8,
+ pub share: String,
+ pub checksum: String,
+ pub part_name: String,
+}
+
+impl From<ente_contacts::LegacyKitShare> for LegacyKitShare {
+ fn from(value: ente_contacts::LegacyKitShare) -> Self {
+ Self {
+ payload_version: value.payload_version,
+ variant: value.variant.into(),
+ kit_id: value.kit_id,
+ share_index: value.share_index,
+ share: value.share,
+ checksum: value.checksum,
+ part_name: value.part_name,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitCreateResult {
+ pub kit: LegacyKit,
+ pub shares: Vec<LegacyKitShare>,
+}
+
+impl From<ente_contacts::LegacyKitCreateResult> for LegacyKitCreateResult {
+ fn from(value: ente_contacts::LegacyKitCreateResult) -> Self {
+ Self {
+ kit: value.kit.into(),
+ shares: value.shares.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub enum RootKeySource {
+ Cache,
+ Unresolved,
+}
+
+impl From<ente_contacts::RootKeySource> for RootKeySource {
+ fn from(value: ente_contacts::RootKeySource) -> Self {
+ match value {
+ ente_contacts::RootKeySource::Cache => RootKeySource::Cache,
+ ente_contacts::RootKeySource::Unresolved => RootKeySource::Unresolved,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone, Copy)]
+pub enum AttachmentType {
+ ProfilePicture,
+}
+
+impl From<AttachmentType> for ente_contacts::AttachmentType {
+ fn from(value: AttachmentType) -> Self {
+ match value {
+ AttachmentType::ProfilePicture => ente_contacts::AttachmentType::ProfilePicture,
+ }
+ }
+}
+
+#[frb]
+pub struct OpenContactsCtxInput {
+ pub base_url: String,
+ pub auth_token: String,
+ pub user_id: i64,
+ pub master_key: Vec<u8>,
+ pub cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ pub user_agent: Option<String>,
+ pub client_package: Option<String>,
+ pub client_version: Option<String>,
+}
+
+#[frb]
+pub struct OpenContactsCtxResult {
+ pub ctx: ContactsCtx,
+ pub wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ pub root_key_source: RootKeySource,
+}
+
+#[frb(opaque)]
+#[derive(Clone)]
+pub struct ContactsCtx {
+ inner: Arc<ente_contacts::ContactsCtx>,
+}
+
+#[frb]
+pub async fn open_contacts_ctx(
+ input: OpenContactsCtxInput,
+) -> Result<OpenContactsCtxResult, ContactsError> {
+ let opened = ente_contacts::ContactsCtx::open(ente_contacts::OpenContactsCtxInput {
+ base_url: input.base_url,
+ auth_token: input.auth_token,
+ user_id: input.user_id,
+ master_key: input.master_key,
+ cached_wrapped_root_contact_key: input.cached_wrapped_root_contact_key.map(Into::into),
+ user_agent: input.user_agent,
+ client_package: input.client_package,
+ client_version: input.client_version,
+ })
+ .await
+ .map_err(ContactsError::from)?;
+
+ Ok(OpenContactsCtxResult {
+ ctx: ContactsCtx {
+ inner: Arc::new(opened.ctx),
+ },
+ wrapped_root_contact_key: opened.wrapped_root_contact_key.map(Into::into),
+ root_key_source: opened.root_key_source.into(),
+ })
+}
+
+impl ContactsCtx {
+ #[frb(sync)]
+ pub fn user_id(&self) -> i64 {
+ self.inner.user_id()
+ }
+
+ pub fn update_auth_token(&self, auth_token: String) {
+ self.inner.update_auth_token(auth_token);
+ }
+
+ #[frb(sync)]
+ pub fn current_wrapped_root_contact_key(&self) -> Option<WrappedRootContactKey> {
+ self.inner
+ .current_wrapped_root_contact_key()
+ .map(Into::into)
+ }
+
+ pub async fn create_contact(&self, data: ContactData) -> Result<ContactRecord, ContactsError> {
+ self.inner
+ .create_contact(&data.into())
+ .await
+ .map(Into::into)
+ .map_err(Into::into)
+ }
+
+ pub async fn get_contact(&self, contact_id: String) -> Result<ContactRecord, ContactsError> {
+ self.inner
+ .get_contact(&contact_id)
+ .await
+ .map(Into::into)
+ .map_err(Into::into)
+ }
+
+ pub async fn get_diff(
+ &self,
+ since_time: i64,
+ limit: u16,
+ ) -> Result<Vec<ContactRecord>, ContactsError> {
+ self.inner
+ .get_diff(since_time, limit)
+ .await
+ .map(|records| records.into_iter().map(Into::into).collect())
+ .map_err(Into::into)
+ }
+
+ pub async fn update_contact(
+ &self,
+ contact_id: String,
+ data: ContactData,
+ ) -> Result<ContactRecord, ContactsError> {
+ self.inner
+ .update_contact(&contact_id, &data.into())
+ .await
+ .map(Into::into)
+ .map_err(Into::into)
+ }
+
+ pub async fn delete_contact(&self, contact_id: String) -> Result<(), ContactsError> {
+ self.inner
+ .delete_contact(&contact_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn set_attachment(
+ &self,
+ contact_id: String,
+ attachment_type: AttachmentType,
+ attachment_bytes: Vec<u8>,
+ ) -> Result<ContactRecord, ContactsError> {
+ self.inner
+ .set_attachment(&contact_id, attachment_type.into(), &attachment_bytes)
+ .await
+ .map(Into::into)
+ .map_err(Into::into)
+ }
+
+ pub async fn get_attachment_encrypted(
+ &self,
+ attachment_type: AttachmentType,
+ attachment_id: String,
+ ) -> Result<Vec<u8>, ContactsError> {
+ self.inner
+ .get_attachment_encrypted(attachment_type.into(), &attachment_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn delete_attachment(
+ &self,
+ contact_id: String,
+ attachment_type: AttachmentType,
+ ) -> Result<ContactRecord, ContactsError> {
+ self.inner
+ .delete_attachment(&contact_id, attachment_type.into())
+ .await
+ .map(Into::into)
+ .map_err(Into::into)
+ }
+
+ pub async fn set_profile_picture(
+ &self,
+ contact_id: String,
+ profile_picture: Vec<u8>,
+ ) -> Result<ContactRecord, ContactsError> {
+ self.set_attachment(contact_id, AttachmentType::ProfilePicture, profile_picture)
+ .await
+ }
+
+ pub async fn get_profile_picture(&self, contact_id: String) -> Result<Vec<u8>, ContactsError> {
+ self.inner
+ .get_profile_picture(&contact_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn delete_profile_picture(
+ &self,
+ contact_id: String,
+ ) -> Result<ContactRecord, ContactsError> {
+ self.delete_attachment(contact_id, AttachmentType::ProfilePicture)
+ .await
+ }
+
+ pub async fn legacy_kits(&self) -> Result<Vec<LegacyKit>, ContactsError> {
+ self.inner
+ .legacy_kits()
+ .await
+ .map(|kits| kits.into_iter().map(Into::into).collect())
+ .map_err(Into::into)
+ }
+
+ pub async fn legacy_kit_create(
+ &self,
+ current_user_key_attrs: AccountKeyAttributes,
+ part_names: Vec<String>,
+ notice_period_in_hours: i32,
+ ) -> Result<LegacyKitCreateResult, ContactsError> {
+ let part_names: [String; 3] =
+ part_names
+ .try_into()
+ .map_err(|_| ContactsError::InvalidInput {
+ message: "legacy kit requires exactly three part names".into(),
+ })?;
+ self.inner
+ .legacy_kit_create(
+ &current_user_key_attrs.into(),
+ part_names,
+ notice_period_in_hours,
+ )
+ .await
+ .map(Into::into)
+ .map_err(Into::into)
+ }
+
+ pub async fn legacy_kit_download_shares(
+ &self,
+ kit_id: String,
+ ) -> Result<Vec<LegacyKitShare>, ContactsError> {
+ self.inner
+ .legacy_kit_download_shares(&kit_id)
+ .await
+ .map(|shares| shares.into_iter().map(Into::into).collect())
+ .map_err(Into::into)
+ }
+
+ pub async fn legacy_kit_recovery_session(
+ &self,
+ kit_id: String,
+ ) -> Result<LegacyKitOwnerRecoverySessionDetails, ContactsError> {
+ self.inner
+ .legacy_kit_recovery_session(&kit_id)
+ .await
+ .map(Into::into)
+ .map_err(Into::into)
+ }
+
+ pub async fn legacy_kit_update_recovery_notice(
+ &self,
+ kit_id: String,
+ notice_period_in_hours: i32,
+ ) -> Result<(), ContactsError> {
+ self.inner
+ .legacy_kit_update_recovery_notice(&kit_id, notice_period_in_hours)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn legacy_kit_block_recovery(&self, kit_id: String) -> Result<(), ContactsError> {
+ self.inner
+ .legacy_kit_block_recovery(&kit_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn legacy_kit_delete(&self, kit_id: String) -> Result<(), ContactsError> {
+ self.inner
+ .legacy_kit_delete(&kit_id)
+ .await
+ .map_err(Into::into)
+ }
+}
diff --git a/rust/bindings/frb/photos/src/api/mod.rs b/rust/bindings/frb/photos/src/api/mod.rs
index 7fed6c2f16..69c9ba0d9c 100644
--- a/rust/bindings/frb/photos/src/api/mod.rs
+++ b/rust/bindings/frb/photos/src/api/mod.rs
@@ -1,8 +1,10 @@
pub mod cast_api;
+pub mod contacts;
pub mod image_processing_api;
pub mod init;
#[cfg(any(feature = "flutter", frb_expand))]
pub mod log;
pub mod ml_indexing_api;
pub mod motion_photo_api;
+pub mod urls;
pub mod usearch_api;
diff --git a/rust/bindings/frb/ente-rust/src/api/urls.rs b/rust/bindings/frb/photos/src/api/urls.rs
similarity index 100%
rename from rust/bindings/frb/ente-rust/src/api/urls.rs
rename to rust/bindings/frb/photos/src/api/urls.rs