Skip to content

armgit / ente

Public Imported from GitHub
0

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

Temporay wip

AmanRajSinghMourya0e34a0328ec9
diff --git a/mobile/apps/locker/ios/Podfile.lock b/mobile/apps/locker/ios/Podfile.lock
index f48e53c41f..44cd9f143d 100644
--- a/mobile/apps/locker/ios/Podfile.lock
+++ b/mobile/apps/locker/ios/Podfile.lock
@@ -194,38 +194,38 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/url_launcher_ios/ios"
SPEC CHECKSUMS:
- app_links: f3e17e4ee5e357b39d8b95290a9b2c299fca71c6
- cupertino_http: 947a233f40cfea55167a49f2facc18434ea117ba
- device_info_plus: c6fb39579d0f423935b0c9ce7ee2f44b71b9fce6
+ app_links: 76b66b60cc809390ca1ad69bfd66b998d2387ac7
+ cupertino_http: 94ac07f5ff090b8effa6c5e2c47871d48ab7c86c
+ device_info_plus: 335f3ce08d2e174b9fdc3db3db0f4e3b1f66bd89
DKImagePickerController: 946cec48c7873164274ecc4624d19e3da4c1ef3c
DKPhotoGallery: b3834fecb755ee09a593d7c9e389d8b5d6deed60
- file_picker: b159e0c068aef54932bb15dc9fd1571818edaf49
- file_saver: 503e386464dbe118f630e17b4c2e1190fa0cf808
+ file_picker: a0560bc09d61de87f12d246fc47d2119e6ef37be
+ file_saver: 6cdbcddd690cb02b0c1a0c225b37cd805c2bf8b6
Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7
- flutter_email_sender: e03bdda7637bcd3539bfe718fddd980e9508efaa
- flutter_inappwebview_ios: 6f63631e2c62a7c350263b13fa5427aedefe81d4
- flutter_local_authentication: 1172a4dd88f6306dadce067454e2c4caf07977bb
- flutter_secure_storage: 23fc622d89d073675f2eaa109381aefbcf5a49be
- fluttertoast: 21eecd6935e7064cc1fcb733a4c5a428f3f24f0f
- listen_sharing_intent: 74a842adcbcf7bedf7bbc938c749da9155141b9a
- local_auth_darwin: 66e40372f1c29f383a314c738c7446e2f7fdadc3
- objective_c: 77e887b5ba1827970907e10e832eec1683f3431d
- open_file_ios: 461db5853723763573e140de3193656f91990d9e
+ flutter_email_sender: aa1e9772696691d02cd91fea829856c11efb8e58
+ flutter_inappwebview_ios: b89ba3482b96fb25e00c967aae065701b66e9b99
+ flutter_local_authentication: 989278c681612f1ee0e36019e149137f114b9d7f
+ flutter_secure_storage: 2c2ff13db9e0a5647389bff88b0ecac56e3f3418
+ fluttertoast: 2c67e14dce98bbdb200df9e1acf610d7a6264ea1
+ listen_sharing_intent: fe0b9a59913cc124dd6cbd55cd9f881de5f75759
+ local_auth_darwin: 553ce4f9b16d3fdfeafce9cf042e7c9f77c1c391
+ objective_c: 89e720c30d716b036faf9c9684022048eee1eee2
+ open_file_ios: 5ff7526df64e4394b4fe207636b67a95e83078bb
OrderedSet: e539b66b644ff081c73a262d24ad552a69be3a94
- package_info_plus: c0502532a26c7662a62a356cebe2692ec5fe4ec4
- path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46
- photo_manager: 81954a1bf804b6e882d0453b3b6bc7fad7b47d3d
- privacy_screen: 1a131c052ceb3c3659934b003b0d397c2381a24e
+ package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
+ path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564
+ photo_manager: 1d80ae07a89a67dfbcae95953a1e5a24af7c3e62
+ privacy_screen: 3159a541f5d3a31bea916cfd4e58f9dc722b3fd4
SDWebImage: 16309af6d214ba3f77a7c6f6fdda888cb313a50a
Sentry: da60d980b197a46db0b35ea12cb8f39af48d8854
- sentry_flutter: 2df8b0aab7e4aba81261c230cbea31c82a62dd1b
- share_plus: 8b6f8b3447e494cca5317c8c3073de39b3600d1f
- shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78
- sodium_libs: 1faae17af662384acbd13e41867a0008cd2e2318
- sqflite_darwin: 5a7236e3b501866c1c9befc6771dfd73ffb8702d
+ sentry_flutter: 27892878729f42701297c628eb90e7c6529f3684
+ share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a
+ shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7
+ sodium_libs: 6c6d0e83f4ee427c6464caa1f1bdc2abf3ca0b7f
+ sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
SwiftyGif: 706c60cf65fa2bc5ee0313beece843c8eb8194d4
- ua_client_hints: aeabd123262c087f0ce151ef96fa3ab77bfc8b38
- url_launcher_ios: 5334b05cef931de560670eeae103fd3e431ac3fe
+ ua_client_hints: 92fe0d139619b73ec9fcb46cc7e079a26178f586
+ url_launcher_ios: 694010445543906933d732453a59da0a173ae33d
PODFILE CHECKSUM: d2d3220ea22664a259778d9e314054751db31361
diff --git a/mobile/apps/locker/lib/services/collections/collections_api_client.dart b/mobile/apps/locker/lib/services/collections/collections_api_client.dart
index d601deb282..ec7afd879d 100644
--- a/mobile/apps/locker/lib/services/collections/collections_api_client.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_api_client.dart
@@ -228,30 +228,49 @@ class CollectionApiClient {
}
Future<void> move(
- EnteFile file,
+ List<EnteFile> files,
Collection fromCollection,
Collection toCollection,
) async {
+ if (files.isEmpty) {
+ _logger.info("No files to move");
+ return;
+ }
+
final params = <String, dynamic>{};
params["fromCollectionID"] = fromCollection.id;
params["toCollectionID"] = toCollection.id;
- final fileKey = await CollectionService.instance.getFileKey(file);
- final encryptedKeyData = CryptoUtil.encryptSync(
- fileKey,
- CryptoHelper.instance.getCollectionKey(toCollection),
- );
- params["files"] = [];
- params["files"].add(
- CollectionFileItem(
- file.uploadedFileID!,
- CryptoUtil.bin2base64(encryptedKeyData.encryptedData!),
- CryptoUtil.bin2base64(encryptedKeyData.nonce!),
- ).toMap(),
- );
- await _enteDio.post(
- "/collections/move-files",
- data: params,
- );
+
+ // Process files in batches
+ const batchSize = 100;
+ final batchedFiles = <List<EnteFile>>[];
+ for (int i = 0; i < files.length; i += batchSize) {
+ batchedFiles.add(
+ files.sublist(i, min(i + batchSize, files.length)),
+ );
+ }
+
+ for (final batch in batchedFiles) {
+ params["files"] = [];
+ for (final file in batch) {
+ final fileKey = await CollectionService.instance.getFileKey(file);
+ final encryptedKeyData = CryptoUtil.encryptSync(
+ fileKey,
+ CryptoHelper.instance.getCollectionKey(toCollection),
+ );
+ params["files"].add(
+ CollectionFileItem(
+ file.uploadedFileID!,
+ CryptoUtil.bin2base64(encryptedKeyData.encryptedData!),
+ CryptoUtil.bin2base64(encryptedKeyData.nonce!),
+ ).toMap(),
+ );
+ }
+ await _enteDio.post(
+ "/collections/move-files",
+ data: params,
+ );
+ }
}
Future<void> trashCollection(
diff --git a/mobile/apps/locker/lib/services/collections/collections_db.dart b/mobile/apps/locker/lib/services/collections/collections_db.dart
index a6c5582d12..3518030214 100644
--- a/mobile/apps/locker/lib/services/collections/collections_db.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_db.dart
@@ -386,6 +386,41 @@ class CollectionDB extends EnteBaseDatabase {
return result.map((row) => _mapToCollection(row)).toList();
}
+ Future<Map<int, List<EnteFile>>> getAllFilesGroupByCollectionID(
+ List<int> uploadedFileIDs,
+ ) async {
+ if (uploadedFileIDs.isEmpty) {
+ return {};
+ }
+
+ final Map<int, List<EnteFile>> collectionToFilesMap = {};
+
+ // Query to get all collection mappings for the given file IDs
+ final placeholders = List.filled(uploadedFileIDs.length, '?').join(',');
+ final result = await _db.rawQuery(
+ '''
+ SELECT cf.collection_id, f.*
+ FROM $_collectionFilesTable cf
+ JOIN $_filesTable f ON cf.uploaded_file_id = f.uploaded_file_id
+ WHERE cf.uploaded_file_id IN ($placeholders)
+ ''',
+ uploadedFileIDs,
+ );
+
+ // Group files by collection ID
+ for (final row in result) {
+ final collectionId = row['collection_id'] as int;
+ final file = _mapToFile(row);
+
+ if (!collectionToFilesMap.containsKey(collectionId)) {
+ collectionToFilesMap[collectionId] = [];
+ }
+ collectionToFilesMap[collectionId]!.add(file);
+ }
+
+ return collectionToFilesMap;
+ }
+
Future<List<EnteFile>> getAllFiles() async {
final result = await _db.query(_filesTable);
return result.map((row) => _mapToFile(row)).toList();
diff --git a/mobile/apps/locker/lib/services/collections/collections_service.dart b/mobile/apps/locker/lib/services/collections/collections_service.dart
index 20ec43804f..61fd5ef64a 100644
--- a/mobile/apps/locker/lib/services/collections/collections_service.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_service.dart
@@ -6,13 +6,16 @@ import "package:ente_accounts/services/user_service.dart";
import 'package:ente_events/event_bus.dart';
import 'package:ente_events/models/signed_in_event.dart';
import "package:ente_sharing/models/user.dart";
+import "package:ente_ui/utils/toast_util.dart";
import "package:fast_base58/fast_base58.dart";
import "package:flutter/foundation.dart";
+import "package:flutter/material.dart";
import 'package:locker/events/collections_updated_event.dart';
import "package:locker/services/collections/collections_api_client.dart";
import "package:locker/services/collections/collections_db.dart";
import 'package:locker/services/collections/models/collection.dart';
import "package:locker/services/collections/models/collection_items.dart";
+import "package:locker/services/collections/models/files_split.dart";
import "package:locker/services/collections/models/public_url.dart";
import 'package:locker/services/configuration.dart';
import 'package:locker/services/files/sync/models/file.dart';
@@ -345,46 +348,94 @@ class CollectionService {
return collection;
}
- Future<void> move(EnteFile file, Collection from, Collection to) async {
+ Future<void> removeFromCollection(
+ int collectionId,
+ List<EnteFile> files,
+ ) async {
+ if (files.isEmpty) {
+ _logger.info("No files to remove");
+ return;
+ }
+
+ try {
+ await _apiClient.removeFromCollection(collectionId, files);
+
+ final collection = await getCollectionByID(collectionId);
+ if (collection != null) {
+ await _db.deleteFilesFromCollection(collection, files);
+ }
+
+ Bus.instance.fire(CollectionsUpdatedEvent('files_removed'));
+
+ await sync();
+ } catch (e, stackTrace) {
+ _logger.severe(
+ "Failed to remove files from collection: $e",
+ e,
+ stackTrace,
+ );
+ rethrow;
+ }
+ }
+
+ Future<void> move(
+ List<EnteFile> files,
+ Collection from,
+ Collection to,
+ ) async {
+ if (files.isEmpty) {
+ _logger.info("No files to move");
+ return;
+ }
+
try {
- await _apiClient.move(file, from, to);
+ // Call API to move files on server
+ await _apiClient.move(files, from, to);
- // Update local database immediately for both collections
+ // Update local database for all files
// Remove from source collection
- await _db.deleteFilesFromCollection(from, [file]);
+ await _db.deleteFilesFromCollection(from, files);
+
+ // Update collectionID for all files
+ for (final file in files) {
+ file.collectionID = to.id;
+ }
- // Add to target collection with updated collectionID
- file.collectionID = to.id;
- await _db.addFilesToCollection(to, [file]);
+ // Add to target collection
+ await _db.addFilesToCollection(to, files);
// Fire event to update UI
- Bus.instance.fire(CollectionsUpdatedEvent('file_moved'));
+ Bus.instance.fire(CollectionsUpdatedEvent('files_moved'));
// Let sync update the local state to ensure consistency
await sync();
} catch (e, stackTrace) {
- _logger.severe("Failed to move file: $e", e, stackTrace);
+ _logger.severe("Failed to move files: $e", e, stackTrace);
rethrow;
}
}
Future<void> trashCollection(
+ BuildContext context,
Collection collection, {
bool keepFiles = true,
}) async {
if (keepFiles) {
- await trashCollectionKeepingFiles(collection);
+ await trashCollectionKeepingFiles(context, collection);
} else {
await trashCollectionWithFiles(collection);
}
}
- Future<void> trashCollectionKeepingFiles(Collection collection) async {
+ Future<void> trashCollectionKeepingFiles(
+ BuildContext context,
+ Collection collection,
+ ) async {
try {
final files = await _db.getFilesInCollection(collection);
if (files.isNotEmpty) {
- await moveFilesFromCurrentCollection(collection, files);
+ await moveFilesFromCurrentCollection(context, collection, files);
}
await _apiClient.trashCollection(collection, keepFiles: true);
@@ -447,161 +498,161 @@ class CollectionService {
}
Future<void> moveFilesFromCurrentCollection(
+ BuildContext context,
Collection collection,
- List<EnteFile> files,
- ) async {
- if (files.isEmpty) {
- return;
- }
-
+ Iterable<EnteFile> files, {
+ bool isHidden = false,
+ }) async {
final int currentUserID = Configuration.instance.getUserID()!;
-
- final List<EnteFile> ownedByCurrentUser = [];
- final List<EnteFile> ownedByOtherUsers = [];
- for (final file in files) {
- if (file.uploadedFileID == null) {
- _logger.warning(
- "Skipping file ${file.title} while moving from collection "
- "${collection.id} because uploadedFileID is null",
- );
- continue;
- }
- if (file.ownerID == null || file.ownerID == currentUserID) {
- ownedByCurrentUser.add(file);
- } else {
- ownedByOtherUsers.add(file);
- }
- }
-
- final bool isCollectionOwner = collection.owner.id == currentUserID;
- bool removalsPerformed = false;
- bool movesPerformed = false;
-
- if (isCollectionOwner && ownedByOtherUsers.isNotEmpty) {
- await _apiClient.removeFromCollection(collection.id, ownedByOtherUsers);
- removalsPerformed = true;
- } else if (!isCollectionOwner && ownedByCurrentUser.isNotEmpty) {
- await _apiClient.removeFromCollection(collection.id, ownedByCurrentUser);
- removalsPerformed = true;
- if (removalsPerformed) {
- await sync();
- }
+ final isCollectionOwner = collection.owner.id == currentUserID;
+ final FilesSplit split = FilesSplit.split(
+ files,
+ Configuration.instance.getUserID()!,
+ );
+ if (isCollectionOwner && split.ownedByOtherUsers.isNotEmpty) {
+ await _apiClient.removeFromCollection(
+ collection.id,
+ split.ownedByOtherUsers,
+ );
+ } else if (!isCollectionOwner && split.ownedByCurrentUser.isNotEmpty) {
+ // collection is not owned by the user, just remove files owned
+ // by current user and return
+ await _apiClient.removeFromCollection(
+ collection.id,
+ split.ownedByCurrentUser,
+ );
return;
}
- if (!isCollectionOwner && ownedByOtherUsers.isNotEmpty) {
- _logger.warning(
- "Cannot remove files owned by others from collection ${collection.id}",
+ if (!isCollectionOwner && split.ownedByOtherUsers.isNotEmpty) {
+ showShortToast(
+ context,
+ "Can only remove files owned by you",
);
- if (removalsPerformed) {
- await sync();
- }
return;
}
- if (ownedByCurrentUser.isEmpty) {
- if (removalsPerformed) {
- await sync();
+ // pendingAssignMap keeps a track of files which are yet to be assigned to
+ // to destination collection.
+ final Map<int, EnteFile> pendingAssignMap = {};
+ // destCollectionToFilesMap contains the destination collection and
+ // files entry which needs to be moved in destination.
+ // After the end of mapping logic, the number of files entries in
+ // pendingAssignMap should be equal to files in destCollectionToFilesMap
+ final Map<int, List<EnteFile>> destCollectionToFilesMap = {};
+ final List<int> uploadedIDs = [];
+ for (EnteFile f in split.ownedByCurrentUser) {
+ if (f.uploadedFileID != null) {
+ pendingAssignMap[f.uploadedFileID!] = f;
+ uploadedIDs.add(f.uploadedFileID!);
}
- return;
}
- final Map<int, List<EnteFile>> destinationMap = {};
- final Map<int, Collection> resolvedDestinationCollections = {};
- final List<EnteFile> fallbackFiles = [];
- for (final file in ownedByCurrentUser) {
- final Collection? targetCollection = await _findAutoMoveDestination(
- file,
- collection,
+ final Map<int, List<EnteFile>> collectionToFilesMap =
+ await _db.getAllFilesGroupByCollectionID(uploadedIDs);
+
+ // Find and map the files from current collection to to entries in other
+ // collections. This mapping is done to avoid moving all the files to
+ // uncategorized during remove from album.
+ for (MapEntry<int, List<EnteFile>> entry in collectionToFilesMap.entries) {
+ if (!await _isAutoMoveCandidate(
+ collection.id,
+ entry.key,
currentUserID,
- );
+ )) {
+ continue;
+ }
+ final Collection? targetCollection = await getCollectionByID(entry.key);
if (targetCollection != null) {
- resolvedDestinationCollections[targetCollection.id] = targetCollection;
- destinationMap
- .putIfAbsent(targetCollection.id, () => <EnteFile>[])
- .add(file);
- } else {
- fallbackFiles.add(file);
+ // for each file which already exist in the destination collection
+ // add entries in the moveDestCollectionToFiles map
+ for (EnteFile file in entry.value) {
+ // Check if the uploaded file is still waiting to be mapped
+ if (pendingAssignMap.containsKey(file.uploadedFileID)) {
+ if (!destCollectionToFilesMap.containsKey(targetCollection.id)) {
+ destCollectionToFilesMap[targetCollection.id] = <EnteFile>[];
+ }
+ destCollectionToFilesMap[targetCollection.id]!
+ .add(pendingAssignMap[file.uploadedFileID!]!);
+ pendingAssignMap.remove(file.uploadedFileID);
+ }
+ }
}
}
+ // Move the remaining files to uncategorized collection
+ if (pendingAssignMap.isNotEmpty) {
+ late final int toCollectionID;
- if (fallbackFiles.isNotEmpty) {
- final Collection fallbackCollection =
+ final Collection uncategorizedCollection =
await getOrCreateUncategorizedCollection();
- resolvedDestinationCollections[fallbackCollection.id] =
- fallbackCollection;
- destinationMap
- .putIfAbsent(fallbackCollection.id, () => <EnteFile>[])
- .addAll(fallbackFiles);
- }
-
- for (final entry in destinationMap.entries) {
- final Collection? targetCollection =
- resolvedDestinationCollections[entry.key] ??
- await getCollectionByID(entry.key);
- if (targetCollection == null) {
- _logger.warning(
- "Skipping move to unknown collection ${entry.key}",
- );
- continue;
+ toCollectionID = uncategorizedCollection.id;
+
+ for (MapEntry<int, EnteFile> entry in pendingAssignMap.entries) {
+ final file = entry.value;
+ if (pendingAssignMap.containsKey(file.uploadedFileID)) {
+ if (!destCollectionToFilesMap.containsKey(toCollectionID)) {
+ destCollectionToFilesMap[toCollectionID] = <EnteFile>[];
+ }
+ destCollectionToFilesMap[toCollectionID]!
+ .add(pendingAssignMap[file.uploadedFileID!]!);
+ }
}
+ }
+
+ // Verify that all files are mapped.
+ int mappedFilesCount = 0;
+ destCollectionToFilesMap.forEach((key, value) {
+ mappedFilesCount += value.length;
+ });
+ if (mappedFilesCount != uploadedIDs.length) {
+ throw AssertionError(
+ "Failed to map all files toMap: ${uploadedIDs.length} and mapped "
+ "$mappedFilesCount",
+ );
+ }
+
+ for (MapEntry<int, List<EnteFile>> entry
+ in destCollectionToFilesMap.entries) {
if (collection.type == CollectionType.uncategorized &&
- targetCollection.id == collection.id) {
+ entry.key == collection.id) {
+ // skip moving files to uncategorized collection from uncategorized
+ // this flow is triggered while cleaning up uncategerized collection
+
_logger.info(
- "Skipping move back into uncategorized collection ${collection.id}",
+ 'skipping moving ${entry.value.length} files to uncategorized collection',
);
- continue;
- }
- for (final file in entry.value) {
+ } else {
+ final toCollection = await getCollection(entry.key);
await move(
- file,
+ entry.value,
collection,
- targetCollection,
+ toCollection,
);
- movesPerformed = true;
}
}
-
- if (movesPerformed || removalsPerformed) {
- await sync();
- }
}
- Future<Collection?> _findAutoMoveDestination(
- EnteFile file,
- Collection fromCollection,
- int currentUserID,
+ // This method returns true if the given destination collection is a good
+ // target to moving files during file remove or delete collection but keep
+ // photos action. Uncategorized or favorite type of collections are not
+ // good auto-move candidates. Uncategorized will be fall back for all files
+ // which could not be mapped to a potential target collection
+ Future<bool> _isAutoMoveCandidate(
+ int fromCollectionID,
+ toCollectionID,
+ int userID,
) async {
- final collections = await getCollectionsForFile(file);
- for (final candidate in collections) {
- if (!_isAutoMoveCandidate(
- fromCollection: fromCollection,
- targetCollection: candidate,
- currentUserID: currentUserID,
- )) {
- continue;
- }
- return candidate;
- }
- return null;
- }
-
- bool _isAutoMoveCandidate({
- required Collection fromCollection,
- required Collection? targetCollection,
- required int currentUserID,
- }) {
- if (targetCollection == null) {
- return false;
- }
- if (fromCollection.id == targetCollection.id) {
- return false;
- }
- if (targetCollection.owner.id != currentUserID) {
+ if (fromCollectionID == toCollectionID) {
return false;
}
- if (targetCollection.type == CollectionType.uncategorized ||
- targetCollection.type == CollectionType.favorites) {
+ final Collection? targetCollection =
+ await getCollectionByID(toCollectionID);
+ // ignore non-cached collections, uncategorized and favorite
+ // collections and collections ignored by others
+ if (targetCollection == null ||
+ (CollectionType.uncategorized == targetCollection.type ||
+ targetCollection.type == CollectionType.favorites) ||
+ targetCollection.owner.id != userID) {
return false;
}
return true;
diff --git a/mobile/apps/locker/lib/services/favorites_service.dart b/mobile/apps/locker/lib/services/favorites_service.dart
index e5dcea3bca..1585c9c659 100644
--- a/mobile/apps/locker/lib/services/favorites_service.dart
+++ b/mobile/apps/locker/lib/services/favorites_service.dart
@@ -191,7 +191,7 @@ class FavoritesService {
await _collectionService.getOrCreateUncategorizedCollection();
await _collectionService.move(
- file,
+ [file],
favCollection!,
targetCollection,
);
@@ -253,7 +253,7 @@ class FavoritesService {
}
await _collectionService.move(
- file,
+ [file],
favCollection,
targetCollection,
);
diff --git a/mobile/apps/locker/lib/ui/components/file_edit_dialog.dart b/mobile/apps/locker/lib/ui/components/file_edit_dialog.dart
index 6683a61c46..b5950ad38b 100644
--- a/mobile/apps/locker/lib/ui/components/file_edit_dialog.dart
+++ b/mobile/apps/locker/lib/ui/components/file_edit_dialog.dart
@@ -9,7 +9,6 @@ import 'package:locker/ui/components/collection_selection_widget.dart';
import 'package:locker/ui/components/form_text_input_widget.dart';
import "package:locker/ui/components/gradient_button.dart";
import 'package:locker/utils/collection_list_util.dart';
-import 'package:locker/utils/snack_bar_utils.dart';
class FileEditDialogResult {
final String title;
@@ -125,14 +124,6 @@ class _FileEditDialogState extends State<FileEditDialog> {
.where((c) => _selectedCollectionIds.contains(c.id))
.toList();
- if (selectedCollections.isEmpty) {
- SnackBarUtils.showWarningSnackBar(
- widget.snackBarContext,
- widget.snackBarContext.l10n.pleaseSelectAtLeastOneCollection,
- );
- return;
- }
-
final result = FileEditDialogResult(
title: _titleController.text.trim(),
caption: _captionController.text.trim(),
@@ -158,7 +149,7 @@ class _FileEditDialogState extends State<FileEditDialog> {
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
- color: Colors.black.withOpacity(0.08),
+ color: Colors.black.withValues(alpha: 0.08),
blurRadius: 24,
offset: const Offset(0, 12),
),
diff --git a/mobile/apps/locker/lib/utils/collection_actions.dart b/mobile/apps/locker/lib/utils/collection_actions.dart
index 74c4c1cff5..c55f17163d 100644
--- a/mobile/apps/locker/lib/utils/collection_actions.dart
+++ b/mobile/apps/locker/lib/utils/collection_actions.dart
@@ -186,6 +186,7 @@ class CollectionActions {
for (final collection in nonEmptyCollections) {
try {
await CollectionService.instance.trashCollection(
+ context,
collection,
keepFiles: keepFiles,
);
@@ -293,6 +294,7 @@ class CollectionActions {
// If deleteFromAllCollections is true β†’ keepFiles should be false (move files to trash)
// If deleteFromAllCollections is false β†’ keepFiles should be true (keep files in other collections)
await CollectionService.instance.trashCollection(
+ context,
collection,
keepFiles: !(result?.deleteFromAllCollections ?? false),
);
diff --git a/mobile/apps/locker/lib/utils/file_actions.dart b/mobile/apps/locker/lib/utils/file_actions.dart
index 9ad385f7cf..620d5b47de 100644
--- a/mobile/apps/locker/lib/utils/file_actions.dart
+++ b/mobile/apps/locker/lib/utils/file_actions.dart
@@ -4,14 +4,13 @@ import "package:flutter/material.dart";
import "package:locker/l10n/l10n.dart";
import "package:locker/services/collections/collections_service.dart";
import "package:locker/services/collections/models/collection.dart";
+import "package:locker/services/favorites_service.dart";
import "package:locker/services/files/links/links_service.dart";
-import "package:locker/services/files/sync/metadata_updater_service.dart";
import "package:locker/services/files/sync/models/file.dart";
import "package:locker/services/trash/trash_service.dart";
import "package:locker/ui/components/delete_confirmation_dialog.dart";
import "package:locker/ui/components/file_edit_dialog.dart";
import "package:locker/ui/components/share_link_dialog.dart";
-import "package:locker/utils/collection_list_util.dart";
import "package:locker/utils/snack_bar_utils.dart";
import "package:logging/logging.dart";
@@ -19,107 +18,152 @@ import "package:logging/logging.dart";
class FileActions {
static final _logger = Logger("FileActions");
- /// Shows edit dialog for a file to update title, caption, and collections
+ /// Shows edit dialog for a file to update its collections
static Future<void> editFile(
BuildContext context,
EnteFile file, {
VoidCallback? onSuccess,
}) async {
+ _logger.info(
+ 'Opening edit dialog for file ${file.uploadedFileID}',
+ );
+
final allCollections = await CollectionService.instance.getCollections();
- final dedupedCollections = uniqueCollectionsById(allCollections);
+ final currentCollections =
+ await CollectionService.instance.getCollectionsForFile(file);
+
+ final favoriteCollection =
+ await CollectionService.instance.getOrCreateImportantCollection();
+
+ final editableCollections = allCollections
+ .where((c) => c.type != CollectionType.uncategorized)
+ .toList();
+
+ final currentCollectionIds = currentCollections.map((c) => c.id).toSet();
final result = await showFileEditDialog(
context,
file: file,
- collections: dedupedCollections,
- snackBarContext: context,
+ collections: editableCollections,
);
- if (result != null && context.mounted) {
- List<Collection> currentCollections;
- try {
- currentCollections =
- await CollectionService.instance.getCollectionsForFile(file);
- } catch (e) {
- currentCollections = <Collection>[];
+ if (result == null || !context.mounted) {
+ return;
+ }
+
+ final dialog = createProgressDialog(
+ context,
+ context.l10n.pleaseWait,
+ isDismissible: false,
+ );
+ await dialog.show();
+
+ try {
+ final selectedCollectionIds =
+ result.selectedCollections.map((c) => c.id).toSet();
+
+ final wasFavorite = currentCollectionIds.contains(favoriteCollection.id);
+ final isFavoriteNow =
+ selectedCollectionIds.contains(favoriteCollection.id);
+
+ if (wasFavorite && !isFavoriteNow) {
+ await FavoritesService.instance.removeFromFavorites(context, file);
+ } else if (!wasFavorite && isFavoriteNow) {
+ await FavoritesService.instance.addToFavorites(context, file);
}
- final currentCollectionsSet = currentCollections.toSet();
- final selectedCollectionsSet = result.selectedCollections.toSet();
- final collectionsToAdd =
- selectedCollectionsSet.difference(currentCollectionsSet).toList();
- final hasCollectionAdds = collectionsToAdd.isNotEmpty;
+ final regularCurrentIds = currentCollectionIds
+ .where((id) => id != favoriteCollection.id)
+ .toSet();
+ final regularSelectedIds = selectedCollectionIds
+ .where((id) => id != favoriteCollection.id)
+ .toSet();
- final currentTitle = file.displayName;
- final currentCaption = file.caption ?? '';
- final hasMetadataChanged =
- result.title != currentTitle || result.caption != currentCaption;
+ final collectionsToRemove =
+ regularCurrentIds.difference(regularSelectedIds);
- if (hasMetadataChanged || hasCollectionAdds) {
- final dialog = createProgressDialog(
- context,
- context.l10n.pleaseWait,
- isDismissible: false,
- );
- await dialog.show();
-
- try {
- final addFutures = <Future<void>>[];
- for (final collection in collectionsToAdd) {
- addFutures.add(
- CollectionService.instance.addToCollection(
- collection,
- file,
- runSync: false,
- ),
+ final collectionsToAdd = regularSelectedIds.difference(regularCurrentIds);
+
+ _logger
+ .info("=========== Collection To ADD ${collectionsToAdd.length}");
+ _logger.info(
+ "=========== Collection To Remove. ${collectionsToRemove.length}",
+ );
+
+ if (regularSelectedIds.isEmpty && collectionsToRemove.isNotEmpty) {
+ _logger.info('All collections deselected, moving to uncategorized');
+
+ for (final collectionId in collectionsToRemove) {
+ try {
+ final collection =
+ allCollections.firstWhere((c) => c.id == collectionId);
+ await CollectionService.instance.moveFilesFromCurrentCollection(
+ context,
+ collection,
+ [file],
+ );
+ } catch (e) {
+ final collection =
+ allCollections.firstWhere((c) => c.id == collectionId);
+ _logger.severe(
+ 'Failed to remove file from ${collection.name}: $e',
);
}
- if (addFutures.isNotEmpty) {
- await Future.wait(addFutures);
+ }
+ } else {
+ // Add to new collections
+ for (final collectionId in collectionsToAdd) {
+ final collection =
+ allCollections.firstWhere((c) => c.id == collectionId);
+
+ try {
+ await CollectionService.instance.addToCollection(
+ collection,
+ file,
+ runSync: false,
+ );
+ } catch (e) {
+ _logger.severe(
+ 'Failed to move file to collection ${collection.name}: $e',
+ );
}
+ }
- final List<Future<void>> apiCalls = [];
+ // Remove from collections that were deselected
+ for (final collectionId in collectionsToRemove) {
+ final collection =
+ allCollections.firstWhere((c) => c.id == collectionId);
+ await CollectionService.instance
+ .moveFilesFromCurrentCollection(context, collection, [file]);
+ }
+ }
- if (hasMetadataChanged) {
- apiCalls.add(
- MetadataUpdaterService.instance
- .editFileNameAndCaption(file, result.title, result.caption),
- );
- }
- await Future.wait(apiCalls);
+ await CollectionService.instance.sync();
- await dialog.hide();
+ await dialog.hide();
- if (!context.mounted) {
- return;
- }
+ if (!context.mounted) {
+ return;
+ }
- SnackBarUtils.showInfoSnackBar(
- context,
- context.l10n.fileUpdatedSuccessfully,
- );
+ SnackBarUtils.showInfoSnackBar(
+ context,
+ context.l10n.fileUpdatedSuccessfully,
+ );
- onSuccess?.call();
- } catch (e) {
- await dialog.hide();
- if (!context.mounted) {
- return;
- }
+ onSuccess?.call();
+ } catch (e) {
+ await dialog.hide();
+ _logger.severe('Failed to update file collections: $e');
- SnackBarUtils.showWarningSnackBar(
- context,
- context.l10n.failedToUpdateFile(e.toString()),
- );
- }
- } else {
- if (!context.mounted) {
- return;
- }
- SnackBarUtils.showWarningSnackBar(
- context,
- context.l10n.noChangesWereMade,
- );
+ if (!context.mounted) {
+ return;
}
+
+ SnackBarUtils.showWarningSnackBar(
+ context,
+ context.l10n.failedToUpdateFile(e.toString()),
+ );
}
}