Skip to content

armgit / ente

Public Imported from GitHub
0

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

Implement file removal and collection trashing features with confirmation options

AmanRajSinghMouryabbf892c75dcc
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 fc03bf2284..2b4f30d794 100644
--- a/mobile/apps/locker/lib/services/collections/collections_api_client.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_api_client.dart
@@ -150,6 +150,48 @@ class CollectionApiClient {
}
}
+ Future<void> removeFromCollection(
+ int collectionID,
+ List<EnteFile> files,
+ ) async {
+ if (files.isEmpty) return;
+
+ final params = <String, dynamic>{};
+ params["collectionID"] = collectionID;
+
+ 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["fileIDs"] = <int>[];
+ for (final file in batch) {
+ if (file.uploadedFileID != null) {
+ params["fileIDs"].add(file.uploadedFileID);
+ }
+ }
+
+ if (params["fileIDs"].isNotEmpty) {
+ final response = await _enteDio.post(
+ "/collections/v3/remove-files",
+ data: params,
+ );
+ if (response.statusCode != 200) {
+ throw Exception("Failed to remove files from collection");
+ }
+
+ await _db.deleteFilesFromCollection(
+ await _db.getCollection(collectionID),
+ batch,
+ );
+ }
+ }
+ }
+
Future<void> rename(Collection collection, String newName) async {
final collectionKey = CryptoHelper.instance.getCollectionKey(collection);
final encryptedName = CryptoUtil.encryptSync(
@@ -221,6 +263,7 @@ class CollectionApiClient {
"?keepFiles=${keepFiles ? "True" : "False"}"
"&collectionID=${collection.id}",
);
+ await _handleCollectionDeletion(collection);
} catch (e) {
_logger.severe('failed to trash collection', e);
rethrow;
diff --git a/mobile/apps/locker/lib/services/collections/collections_service.dart b/mobile/apps/locker/lib/services/collections/collections_service.dart
index 8deea684a4..d500c14801 100644
--- a/mobile/apps/locker/lib/services/collections/collections_service.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_service.dart
@@ -267,13 +267,10 @@ class CollectionService {
requests.add(TrashRequest(file.uploadedFileID!, collection.id));
await _apiClient.trash(requests);
- // Update local database immediately
await _db.deleteFilesFromCollection(collection, [file]);
- // Fire event to update UI
Bus.instance.fire(CollectionsUpdatedEvent('trash_file'));
- // Also sync to ensure we have the latest state
await sync();
await TrashService.instance.syncTrash();
} catch (e) {
@@ -282,6 +279,43 @@ class CollectionService {
}
}
+ Future<void> trashFileFromAllCollections(
+ EnteFile file, {
+ bool runSync = true,
+ }) async {
+ try {
+ final collections = await getCollectionsForFile(file);
+
+ if (collections.isEmpty) {
+ return;
+ }
+
+ final List<TrashRequest> requests = [];
+ for (final collection in collections) {
+ requests.add(TrashRequest(file.uploadedFileID!, collection.id));
+ }
+
+ if (requests.isNotEmpty) {
+ await _apiClient.trash(requests);
+ }
+
+ for (final collection in collections) {
+ await _db.deleteFilesFromCollection(collection, [file]);
+ }
+
+ Bus.instance
+ .fire(CollectionsUpdatedEvent('file_trashed_from_all_collections'));
+
+ if (runSync) {
+ await sync();
+ await TrashService.instance.syncTrash();
+ }
+ } catch (e) {
+ _logger.severe("Failed to trash file from all collections: $e");
+ rethrow;
+ }
+ }
+
Future<void> rename(Collection collection, String newName) async {
try {
await _apiClient.rename(
@@ -367,47 +401,243 @@ class CollectionService {
}
}
- Future<void> trashCollection(Collection collection) async {
+ Future<void> trashCollection(
+ Collection collection, {
+ bool keepFiles = true,
+ }) async {
+ if (keepFiles) {
+ await trashCollectionKeepingFiles(collection);
+ } else {
+ await trashCollectionWithFiles(collection);
+ }
+ }
+
+ Future<void> trashCollectionKeepingFiles(Collection collection) async {
+ try {
+ final files = await _db.getFilesInCollection(collection);
+
+ if (files.isNotEmpty) {
+ await moveFilesFromCurrentCollection(collection, files);
+ }
+
+ await _apiClient.trashCollection(
+ collection,
+ keepFiles: true,
+ );
+
+ Bus.instance
+ .fire(CollectionsUpdatedEvent('collection_trashed_keeping_files'));
+ } catch (e) {
+ _logger.severe("Failed to trash collection keeping files: $e");
+ rethrow;
+ }
+ }
+
+ Future<void> trashCollectionWithFiles(Collection collection) async {
try {
final files = await _db.getFilesInCollection(collection);
- var keepFiles = false;
if (files.isNotEmpty) {
- keepFiles = true;
- final requests = files
- .where((file) => file.uploadedFileID != null)
- .map(
- (file) => TrashRequest(
- file.uploadedFileID!,
- collection.id,
- ),
- )
- .toList();
-
- if (requests.isNotEmpty) {
- await _apiClient.trash(requests);
+ for (final file in files) {
+ await trashFileFromAllCollections(
+ file,
+ runSync: false,
+ );
}
-
- await _db.deleteFilesFromCollection(collection, files);
- Bus.instance.fire(CollectionsUpdatedEvent('collection_files_trashed'));
- await TrashService.instance.syncTrash();
}
await _apiClient.trashCollection(
collection,
- keepFiles: keepFiles,
+ keepFiles: false,
);
- _logger.info("Trashed collection: ${collection.name}");
- // Let sync update the local state
+ Bus.instance
+ .fire(CollectionsUpdatedEvent('collection_trashed_with_files'));
+
await sync();
await TrashService.instance.syncTrash();
} catch (e) {
- _logger.severe("Failed to trash collection: $e");
+ _logger.severe("Failed to trash collection with files: $e");
rethrow;
}
}
+ Future<void> moveFilesFromCurrentCollection(
+ Collection collection,
+ List<EnteFile> files,
+ ) async {
+ if (files.isEmpty) {
+ return;
+ }
+
+ 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) {
+ Bus.instance.fire(
+ CollectionsUpdatedEvent('files_moved_from_collection'),
+ );
+ await sync();
+ }
+ return;
+ }
+
+ if (!isCollectionOwner && ownedByOtherUsers.isNotEmpty) {
+ _logger.warning(
+ "Cannot remove files owned by others from collection ${collection.id}",
+ );
+ if (removalsPerformed) {
+ Bus.instance.fire(
+ CollectionsUpdatedEvent('files_moved_from_collection'),
+ );
+ await sync();
+ }
+ return;
+ }
+
+ if (ownedByCurrentUser.isEmpty) {
+ if (removalsPerformed) {
+ Bus.instance.fire(
+ CollectionsUpdatedEvent('files_moved_from_collection'),
+ );
+ await sync();
+ }
+ 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,
+ currentUserID,
+ );
+ if (targetCollection != null) {
+ resolvedDestinationCollections[targetCollection.id] = targetCollection;
+ destinationMap
+ .putIfAbsent(targetCollection.id, () => <EnteFile>[])
+ .add(file);
+ } else {
+ fallbackFiles.add(file);
+ }
+ }
+
+ if (fallbackFiles.isNotEmpty) {
+ final Collection fallbackCollection =
+ 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;
+ }
+ if (collection.type == CollectionType.uncategorized &&
+ targetCollection.id == collection.id) {
+ _logger.info(
+ "Skipping move back into uncategorized collection ${collection.id}",
+ );
+ continue;
+ }
+ for (final file in entry.value) {
+ await move(
+ file,
+ collection,
+ targetCollection,
+ );
+ movesPerformed = true;
+ }
+ }
+
+ if (removalsPerformed) {
+ Bus.instance.fire(
+ CollectionsUpdatedEvent('files_moved_from_collection'),
+ );
+ }
+
+ if (movesPerformed || removalsPerformed) {
+ await sync();
+ }
+ }
+
+ Future<Collection?> _findAutoMoveDestination(
+ EnteFile file,
+ Collection fromCollection,
+ int currentUserID,
+ ) 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) {
+ return false;
+ }
+ if (targetCollection.type == CollectionType.uncategorized ||
+ targetCollection.type == CollectionType.favorites) {
+ return false;
+ }
+ return true;
+ }
+
// Track if default collections have been set up
bool _defaultCollectionsSetupCompleted = false;
diff --git a/mobile/apps/locker/lib/services/collections/models/files_split.dart b/mobile/apps/locker/lib/services/collections/models/files_split.dart
new file mode 100644
index 0000000000..d4eb4b1afe
--- /dev/null
+++ b/mobile/apps/locker/lib/services/collections/models/files_split.dart
@@ -0,0 +1,38 @@
+import "package:locker/services/files/sync/models/file.dart";
+
+class FilesSplit {
+ final List<EnteFile> pendingUploads;
+ final List<EnteFile> ownedByCurrentUser;
+ final List<EnteFile> ownedByOtherUsers;
+
+ FilesSplit({
+ required this.pendingUploads,
+ required this.ownedByCurrentUser,
+ required this.ownedByOtherUsers,
+ });
+
+ int get totalFileOwnedCount =>
+ pendingUploads.length + ownedByCurrentUser.length;
+
+ int get count => totalFileOwnedCount + ownedByOtherUsers.length;
+
+ static FilesSplit split(Iterable<EnteFile> files, int currentUserID) {
+ final List<EnteFile> ownedByCurrentUser = [],
+ ownedByOtherUsers = [],
+ pendingUploads = [];
+ for (var f in files) {
+ if (f.ownerID == null || f.uploadedFileID == null) {
+ pendingUploads.add(f);
+ } else if (f.ownerID == currentUserID) {
+ ownedByCurrentUser.add(f);
+ } else {
+ ownedByOtherUsers.add(f);
+ }
+ }
+ return FilesSplit(
+ pendingUploads: pendingUploads,
+ ownedByCurrentUser: ownedByCurrentUser,
+ ownedByOtherUsers: ownedByOtherUsers,
+ );
+ }
+}
diff --git a/mobile/apps/locker/lib/ui/components/delete_confirmation_dialog.dart b/mobile/apps/locker/lib/ui/components/delete_confirmation_dialog.dart
index ea18243eaf..5243dd842b 100644
--- a/mobile/apps/locker/lib/ui/components/delete_confirmation_dialog.dart
+++ b/mobile/apps/locker/lib/ui/components/delete_confirmation_dialog.dart
@@ -4,15 +4,26 @@ import "package:ente_ui/theme/ente_theme.dart";
import "package:flutter/material.dart";
import "package:hugeicons/hugeicons.dart";
-Future<ButtonResult?> showDeleteConfirmationDialog(
+class DeleteConfirmationResult {
+ final ButtonResult buttonResult;
+ final bool deleteFromAllCollections;
+
+ DeleteConfirmationResult({
+ required this.buttonResult,
+ required this.deleteFromAllCollections,
+ });
+}
+
+Future<DeleteConfirmationResult?> showDeleteConfirmationDialog(
BuildContext context, {
required String title,
required String body,
required String deleteButtonLabel,
required String assetPath,
Widget? icon,
+ bool showDeleteFromAllCollectionsOption = false,
}) {
- return showModalBottomSheet<ButtonResult>(
+ return showModalBottomSheet<DeleteConfirmationResult>(
context: context,
isScrollControlled: true,
isDismissible: true,
@@ -23,17 +34,19 @@ Future<ButtonResult?> showDeleteConfirmationDialog(
deleteButtonLabel: deleteButtonLabel,
assetPath: assetPath,
icon: icon,
+ showDeleteFromAllCollectionsOption: showDeleteFromAllCollectionsOption,
);
},
);
}
-class _DeleteConfirmationBottomSheet extends StatelessWidget {
+class _DeleteConfirmationBottomSheet extends StatefulWidget {
final String title;
final String body;
final String deleteButtonLabel;
final String assetPath;
final Widget? icon;
+ final bool showDeleteFromAllCollectionsOption;
const _DeleteConfirmationBottomSheet({
required this.title,
@@ -41,8 +54,18 @@ class _DeleteConfirmationBottomSheet extends StatelessWidget {
required this.deleteButtonLabel,
required this.assetPath,
this.icon,
+ required this.showDeleteFromAllCollectionsOption,
});
+ @override
+ State<_DeleteConfirmationBottomSheet> createState() =>
+ _DeleteConfirmationBottomSheetState();
+}
+
+class _DeleteConfirmationBottomSheetState
+ extends State<_DeleteConfirmationBottomSheet> {
+ bool _deleteFromAllCollections = false;
+
@override
Widget build(BuildContext context) {
final textTheme = getEnteTextTheme(context);
@@ -62,52 +85,107 @@ class _DeleteConfirmationBottomSheet extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 8),
- Row(
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- GestureDetector(
- onTap: () => Navigator.of(context).pop(),
- child: Container(
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(50),
- color: colorScheme.backgroundElevated,
- ),
- padding: const EdgeInsets.all(8),
- child: Icon(
- Icons.close,
- size: 24,
- color: colorScheme.textBase,
+ SizedBox(
+ width: double.infinity,
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ GestureDetector(
+ onTap: () => Navigator.of(context).pop(),
+ child: Container(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(50),
+ color: colorScheme.backgroundElevated,
+ ),
+ padding: const EdgeInsets.all(8),
+ child: Icon(
+ Icons.close,
+ size: 24,
+ color: colorScheme.textBase,
+ ),
),
),
- ),
- ],
+ ],
+ ),
),
const SizedBox(height: 8),
- Image.asset(assetPath),
+ Center(child: Image.asset(widget.assetPath)),
const SizedBox(height: 24),
Text(
- title,
+ widget.title,
style: textTheme.h3Bold,
textAlign: TextAlign.center,
),
const SizedBox(height: 12),
Text(
- body,
+ widget.body,
style: textTheme.body.copyWith(
color: colorScheme.textMuted,
),
textAlign: TextAlign.center,
),
- const SizedBox(height: 32),
+ const SizedBox(height: 12),
+ if (widget.showDeleteFromAllCollectionsOption) ...[
+ GestureDetector(
+ onTap: () {
+ setState(() {
+ _deleteFromAllCollections = !_deleteFromAllCollections;
+ });
+ },
+ child: SizedBox(
+ width: double.infinity,
+ child: Row(
+ children: [
+ Container(
+ width: 18,
+ height: 18,
+ decoration: BoxDecoration(
+ border: Border.all(
+ color: _deleteFromAllCollections
+ ? colorScheme.primary700
+ : colorScheme.strokeMuted,
+ width: 2,
+ ),
+ borderRadius: BorderRadius.circular(6),
+ color: _deleteFromAllCollections
+ ? colorScheme.primary700
+ : Colors.transparent,
+ ),
+ alignment: Alignment.center,
+ child: _deleteFromAllCollections
+ ? const Icon(
+ Icons.check,
+ size: 12,
+ color: Colors.white,
+ )
+ : null,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ "Also delete items from all other collections",
+ style: textTheme.small,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 20),
+ ],
SizedBox(
width: double.infinity,
height: 56,
child: ElevatedButton.icon(
onPressed: () {
Navigator.of(context).pop(
- ButtonResult(ButtonAction.first),
+ DeleteConfirmationResult(
+ buttonResult: ButtonResult(ButtonAction.first),
+ deleteFromAllCollections: _deleteFromAllCollections,
+ ),
);
},
style: ElevatedButton.styleFrom(
@@ -117,7 +195,7 @@ class _DeleteConfirmationBottomSheet extends StatelessWidget {
),
elevation: 0,
),
- icon: icon ??
+ icon: widget.icon ??
const HugeIcon(
icon: HugeIcons.strokeRoundedFileUpload,
color: Colors.white,
@@ -125,7 +203,7 @@ class _DeleteConfirmationBottomSheet extends StatelessWidget {
strokeWidth: 1.9,
),
label: Text(
- deleteButtonLabel,
+ widget.deleteButtonLabel,
style: textTheme.bodyBold.copyWith(
color: Colors.white,
),
diff --git a/mobile/apps/locker/lib/ui/pages/trash_page.dart b/mobile/apps/locker/lib/ui/pages/trash_page.dart
index d95a4d9610..d527f449b9 100644
--- a/mobile/apps/locker/lib/ui/pages/trash_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/trash_page.dart
@@ -170,7 +170,7 @@ class _TrashPageState extends State<TrashPage> {
assetPath: "assets/collection_delete_icon.png",
);
- if (result?.action == ButtonAction.first && context.mounted) {
+ if (result?.buttonResult.action == ButtonAction.first && context.mounted) {
await _performEmptyTrash();
}
}
diff --git a/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart b/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart
index 672606ec20..c3b8352503 100644
--- a/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart
+++ b/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart
@@ -672,7 +672,7 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar> {
assetPath: "assets/file_delete_icon.png",
);
- if (confirmation?.action != ButtonAction.first) {
+ if (confirmation?.buttonResult.action != ButtonAction.first) {
return;
}
@@ -730,7 +730,7 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar> {
assetPath: "assets/file_delete_icon.png",
);
- if (confirmation?.action != ButtonAction.first) {
+ if (confirmation?.buttonResult.action != ButtonAction.first) {
return;
}
diff --git a/mobile/apps/locker/lib/utils/collection_actions.dart b/mobile/apps/locker/lib/utils/collection_actions.dart
index d0783cac6b..6b34ad183f 100644
--- a/mobile/apps/locker/lib/utils/collection_actions.dart
+++ b/mobile/apps/locker/lib/utils/collection_actions.dart
@@ -130,9 +130,10 @@ class CollectionActions {
context.l10n.deleteMultipleCollectionsDialogBody(collections.length),
deleteButtonLabel: context.l10n.yesDeleteCollections(collections.length),
assetPath: "assets/collection_delete_icon.png",
+ showDeleteFromAllCollectionsOption: true,
);
- if (dialogChoice?.action != ButtonAction.first) return;
+ if (dialogChoice?.buttonResult.action != ButtonAction.first) return;
final progressDialog =
createProgressDialog(context, context.l10n.pleaseWait);
@@ -147,7 +148,10 @@ class CollectionActions {
continue;
}
if (collection.type.canDelete) {
- await CollectionService.instance.trashCollection(collection);
+ await CollectionService.instance.trashCollection(
+ collection,
+ keepFiles: !(dialogChoice?.deleteFromAllCollections ?? false),
+ );
}
}
await progressDialog.hide();
@@ -198,9 +202,10 @@ class CollectionActions {
body: l10n.deleteCollectionDialogBody(collectionName),
deleteButtonLabel: l10n.yesDeleteCollections(1),
assetPath: "assets/collection_delete_icon.png",
+ showDeleteFromAllCollectionsOption: true,
);
- if (result?.action != ButtonAction.first && context.mounted) {
+ if (result?.buttonResult.action != ButtonAction.first && context.mounted) {
return;
}
@@ -208,7 +213,13 @@ class CollectionActions {
await progressDialog.show();
try {
- await CollectionService.instance.trashCollection(collection);
+ // 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(
+ collection,
+ keepFiles: !(result?.deleteFromAllCollections ?? false),
+ );
+
await progressDialog.hide();
SnackBarUtils.showInfoSnackBar(