Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add support for removing files from non-hidden collections if the file exists in a hidden collection

ashilkn669e89e51fff
diff --git a/mobile/apps/photos/lib/db/files_db.dart b/mobile/apps/photos/lib/db/files_db.dart
index 1bfbcb3dc6..2cc180473a 100644
--- a/mobile/apps/photos/lib/db/files_db.dart
+++ b/mobile/apps/photos/lib/db/files_db.dart
@@ -1693,6 +1693,57 @@ class FilesDB with SqlDbBase {
return collectionIDsOfFiles;
}
+ /// Returns only uploaded file IDs from given collections.
+ /// Used for checking if hidden files exist in non-hidden collections.
+ /// If [ownerID] is provided, only returns files owned by that user.
+ Future<List<int>> getUploadedFileIDsInCollections(
+ Set<int> collectionIds, {
+ int? ownerID,
+ }) async {
+ if (collectionIds.isEmpty) {
+ return [];
+ }
+ final db = await instance.sqliteAsyncDB;
+ final inParam = collectionIds.join(',');
+
+ String query = '''
+ SELECT DISTINCT $columnUploadedFileID FROM $filesTable
+ WHERE $columnCollectionID IN ($inParam)
+ AND $columnUploadedFileID IS NOT NULL
+ AND $columnUploadedFileID != -1
+ ''';
+
+ final List<Object> args = [];
+ if (ownerID != null) {
+ query += ' AND $columnOwnerID = ?';
+ args.add(ownerID);
+ }
+
+ final results = await db.getAll(query, args);
+ return results.map((row) => row[columnUploadedFileID] as int).toList();
+ }
+
+ /// Returns only collection IDs that contain any of the given uploaded file
+ /// IDs.
+ Future<Set<int>> getCollectionIDsForUploadedFileIDs(
+ List<int> uploadedFileIds,
+ ) async {
+ if (uploadedFileIds.isEmpty) {
+ return {};
+ }
+ final db = await instance.sqliteAsyncDB;
+ final inParam = uploadedFileIds.join(',');
+ final results = await db.getAll(
+ '''
+ SELECT DISTINCT $columnCollectionID FROM $filesTable
+ WHERE $columnUploadedFileID IN ($inParam)
+ AND $columnCollectionID IS NOT NULL
+ AND $columnCollectionID != -1
+ ''',
+ );
+ return results.map((row) => row[columnCollectionID] as int).toSet();
+ }
+
List<EnteFile> convertToFilesForIsolate(Map args) {
final List<EnteFile> files = [];
for (final result in args["result"]) {
diff --git a/mobile/apps/photos/lib/l10n/intl_en.arb b/mobile/apps/photos/lib/l10n/intl_en.arb
index 9f287a7bf0..36204aaa8f 100644
--- a/mobile/apps/photos/lib/l10n/intl_en.arb
+++ b/mobile/apps/photos/lib/l10n/intl_en.arb
@@ -2503,5 +2503,8 @@
}
},
"searchSettings": "Search settings",
- "suggestions": "Suggestions"
+ "suggestions": "Suggestions",
+ "cleanupHiddenFiles": "Clean up hidden files",
+ "cleanupHiddenFilesDescription": "Some files in hidden albums still exist in non-hidden albums making them visible outside of the hidden section. Cleaning up will remove them from non-hidden albums.",
+ "cleanupComplete": "Cleanup complete"
}
diff --git a/mobile/apps/photos/lib/services/hidden_service.dart b/mobile/apps/photos/lib/services/hidden_service.dart
index c2a02ca61e..520c97ccfc 100644
--- a/mobile/apps/photos/lib/services/hidden_service.dart
+++ b/mobile/apps/photos/lib/services/hidden_service.dart
@@ -5,6 +5,7 @@ import 'package:collection/collection.dart';
import 'package:ente_crypto/ente_crypto.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
+import "package:photos/core/configuration.dart";
import "package:photos/core/constants.dart";
import 'package:photos/core/event_bus.dart';
import "package:photos/db/files_db.dart";
@@ -19,8 +20,53 @@ import 'package:photos/models/file/file.dart';
import "package:photos/models/metadata/collection_magic.dart";
import "package:photos/models/metadata/common_keys.dart";
import 'package:photos/services/collections_service.dart';
+import 'package:photos/ui/notification/toast.dart';
import 'package:photos/utils/dialog_util.dart';
+/// Represents a file that needs to be cleaned up from a non-hidden collection.
+class HiddenCleanupItem {
+ final EnteFile file;
+ final int nonHiddenCollectionID;
+ final int hiddenCollectionID;
+
+ HiddenCleanupItem({
+ required this.file,
+ required this.nonHiddenCollectionID,
+ required this.hiddenCollectionID,
+ });
+
+ bool get isNonHiddenCollectionOwnedByUser {
+ final userID = Configuration.instance.getUserID()!;
+ final collection =
+ CollectionsService.instance.getCollectionByID(nonHiddenCollectionID);
+ return collection?.isOwner(userID) ?? false;
+ }
+
+ bool get isHiddenCollectionOwnedByUser {
+ final userID = Configuration.instance.getUserID()!;
+ final collection =
+ CollectionsService.instance.getCollectionByID(hiddenCollectionID);
+ return collection?.isOwner(userID) ?? false;
+ }
+
+ /// Returns true if this item should be acted upon (cleaned up).
+ /// An item is actionable if the user owns the non-hidden collection.
+ bool get isActionable => isNonHiddenCollectionOwnedByUser;
+
+ /// Returns the collection ID to move from.
+ int get fromCollectionID => nonHiddenCollectionID;
+
+ /// Returns the collection ID to move to.
+ /// Uses the original hidden collection if owned by user,
+ /// otherwise uses the user's default hidden collection.
+ int get toCollectionID {
+ if (isHiddenCollectionOwnedByUser) {
+ return hiddenCollectionID;
+ }
+ return CollectionsService.instance.cachedDefaultHiddenCollection!.id;
+ }
+}
+
extension HiddenService on CollectionsService {
static final _logger = Logger("HiddenCollectionService");
@@ -348,4 +394,185 @@ extension HiddenService on CollectionsService {
);
return createRequest;
}
+
+ /// Checks if there are hidden files that also exist in non-hidden collections.
+ /// Only considers files owned by the user.
+ Future<bool> hasFilesNeedingHiddenCleanup() async {
+ final int userID = config.getUserID()!;
+ final hiddenCollectionIds = getHiddenCollectionIds();
+ if (hiddenCollectionIds.isEmpty) {
+ return false;
+ }
+
+ final uploadedHiddenFileIds = await filesDB.getUploadedFileIDsInCollections(
+ hiddenCollectionIds,
+ ownerID: userID,
+ );
+ if (uploadedHiddenFileIds.isEmpty) {
+ return false;
+ }
+
+ final allCollectionIdsHiddenFilesExistsIn =
+ await filesDB.getCollectionIDsForUploadedFileIDs(
+ uploadedHiddenFileIds,
+ );
+
+ // Check if any collection is non-hidden
+ for (final collectionId in allCollectionIdsHiddenFilesExistsIn) {
+ if (hiddenCollectionIds.contains(collectionId)) {
+ continue;
+ }
+
+ final collection = getCollectionByID(collectionId);
+ if (collection != null && collection.isOwner(userID)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /// Gets the list of files that need to be cleaned up from non-hidden
+ /// collections. Only processes files owned by the user.
+ Future<List<HiddenCleanupItem>> getFilesNeedingHiddenCleanup() async {
+ final int userID = config.getUserID()!;
+ final hiddenCollectionIds = getHiddenCollectionIds();
+ if (hiddenCollectionIds.isEmpty) {
+ return [];
+ }
+
+ final uploadedHiddenFileIds = await filesDB.getUploadedFileIDsInCollections(
+ hiddenCollectionIds,
+ ownerID: userID,
+ );
+ if (uploadedHiddenFileIds.isEmpty) {
+ return [];
+ }
+
+ final filesByCollectionID = await filesDB.getAllFilesGroupByCollectionID(
+ uploadedHiddenFileIds,
+ );
+
+ // Build map of uploadedFileID -> hiddenCollectionID
+ final Map<int, int> fileToHiddenCollection = {};
+ for (final entry in filesByCollectionID.entries) {
+ final collectionID = entry.key;
+ if (hiddenCollectionIds.contains(collectionID)) {
+ for (final file in entry.value) {
+ if (file.uploadedFileID != null) {
+ // Store first hidden collection found for each file
+ fileToHiddenCollection.putIfAbsent(
+ file.uploadedFileID!,
+ () => collectionID,
+ );
+ }
+ }
+ }
+ }
+
+ // Create cleanup items for non-hidden collections
+ final cleanupItems = <HiddenCleanupItem>[];
+ for (final entry in filesByCollectionID.entries) {
+ final collectionID = entry.key;
+
+ if (hiddenCollectionIds.contains(collectionID)) {
+ continue;
+ }
+
+ final collection = getCollectionByID(collectionID);
+ if (collection == null) {
+ continue;
+ }
+
+ for (final file in entry.value) {
+ // Files are already filtered by ownerID at DB level, but double-check
+ if (file.ownerID != userID) {
+ continue;
+ }
+
+ final hiddenCollectionID = fileToHiddenCollection[file.uploadedFileID];
+ if (hiddenCollectionID == null) {
+ continue; // Shouldn't happen
+ }
+
+ cleanupItems.add(
+ HiddenCleanupItem(
+ file: file,
+ nonHiddenCollectionID: collectionID,
+ hiddenCollectionID: hiddenCollectionID,
+ ),
+ );
+ }
+ }
+
+ return cleanupItems;
+ }
+
+ /// Cleans up hidden files by moving them from non-hidden collections to their
+ /// hidden collection.
+ Future<void> cleanupHiddenFiles(BuildContext context) async {
+ final dialog = createProgressDialog(
+ context,
+ AppLocalizations.of(context).pleaseWait,
+ );
+ await dialog.show();
+
+ try {
+ final cleanupItems = await getFilesNeedingHiddenCleanup();
+
+ if (cleanupItems.isEmpty) {
+ await dialog.hide();
+ return;
+ }
+
+ final actionableItems =
+ cleanupItems.where((item) => item.isActionable).toList();
+ final nonActionableItems =
+ cleanupItems.where((item) => !item.isActionable).toList();
+
+ for (final item in nonActionableItems) {
+ _logger.info(
+ "Should not clean up file ${item.file.uploadedFileID} from collection "
+ "${item.nonHiddenCollectionID} - user doesn't own the collection",
+ );
+ }
+
+ // Group actionable items by (fromCollectionID, toCollectionID) for batch moves
+ final Map<(int, int), List<EnteFile>> moveGroups = {};
+ for (final item in actionableItems) {
+ final key = (item.fromCollectionID, item.toCollectionID);
+ moveGroups.putIfAbsent(key, () => []).add(item.file);
+ }
+
+ // Execute moves
+ for (final entry in moveGroups.entries) {
+ final (fromCollectionID, toCollectionID) = entry.key;
+ final files = entry.value;
+
+ await move(
+ files,
+ toCollectionID: toCollectionID,
+ fromCollectionID: fromCollectionID,
+ );
+ }
+
+ // Fire events for UI refresh
+ final allMovedFiles = actionableItems.map((e) => e.file).toList();
+ if (allMovedFiles.isNotEmpty) {
+ Bus.instance.fire(
+ FilesUpdatedEvent(
+ allMovedFiles,
+ source: "hiddenCleanup",
+ ),
+ );
+ }
+
+ await dialog.hide();
+ showShortToast(context, AppLocalizations.of(context).cleanupComplete);
+ } catch (e, s) {
+ _logger.severe("Failed to cleanup hidden files", e, s);
+ await dialog.hide();
+ await showGenericErrorDialog(context: context, error: e);
+ }
+ }
}
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/cleanup_hidden_files_widget.dart b/mobile/apps/photos/lib/ui/viewer/gallery/cleanup_hidden_files_widget.dart
new file mode 100644
index 0000000000..1ed56e2ed8
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/cleanup_hidden_files_widget.dart
@@ -0,0 +1,45 @@
+import 'package:flutter/material.dart';
+import "package:photos/generated/l10n.dart";
+import 'package:photos/services/collections_service.dart';
+import "package:photos/services/hidden_service.dart";
+import 'package:photos/theme/ente_theme.dart';
+import 'package:photos/ui/components/captioned_text_widget.dart';
+import 'package:photos/ui/components/menu_item_widget/menu_item_widget.dart';
+import 'package:photos/ui/components/menu_section_description_widget.dart';
+
+class CleanupHiddenFilesWidget extends StatelessWidget {
+ final VoidCallback onCleanupComplete;
+
+ const CleanupHiddenFilesWidget({
+ required this.onCleanupComplete,
+ super.key,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ return Padding(
+ padding: const EdgeInsets.only(left: 12, right: 12, top: 24),
+ child: Column(
+ children: [
+ MenuItemWidget(
+ captionedTextWidget: CaptionedTextWidget(
+ title: AppLocalizations.of(context).cleanupHiddenFiles,
+ ),
+ singleBorderRadius: 8.0,
+ menuItemColor: colorScheme.fillFaint,
+ leadingIcon: Icons.cleaning_services_outlined,
+ alwaysShowSuccessState: true,
+ onTap: () async {
+ await CollectionsService.instance.cleanupHiddenFiles(context);
+ onCleanupComplete();
+ },
+ ),
+ MenuSectionDescriptionWidget(
+ content: AppLocalizations.of(context).cleanupHiddenFilesDescription,
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/hidden_page.dart b/mobile/apps/photos/lib/ui/viewer/gallery/hidden_page.dart
index c6d60b815b..cd2922d007 100644
--- a/mobile/apps/photos/lib/ui/viewer/gallery/hidden_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/hidden_page.dart
@@ -18,6 +18,7 @@ import "package:photos/ui/collections/album/horizontal_list.dart";
import "package:photos/ui/collections/collection_list_page.dart";
import "package:photos/ui/common/loading_widget.dart";
import 'package:photos/ui/viewer/actions/file_selection_overlay_bar.dart';
+import "package:photos/ui/viewer/gallery/cleanup_hidden_files_widget.dart";
import 'package:photos/ui/viewer/gallery/empty_hidden_widget.dart';
import 'package:photos/ui/viewer/gallery/gallery.dart';
import 'package:photos/ui/viewer/gallery/gallery_app_bar_widget.dart';
@@ -44,6 +45,7 @@ class HiddenPage extends StatefulWidget {
class _HiddenPageState extends State<HiddenPage> {
int? _defaultHiddenCollectionId;
final _hiddenCollectionsExcludingDefault = <Collection>[];
+ bool _hasFilesNeedingCleanup = false;
late StreamSubscription<CollectionUpdatedEvent>
_collectionUpdatesSubscription;
@@ -55,8 +57,20 @@ class _HiddenPageState extends State<HiddenPage> {
setState(() {
getHiddenCollections();
});
+ _checkForCleanupNeeded();
});
getHiddenCollections();
+ _checkForCleanupNeeded();
+ }
+
+ Future<void> _checkForCleanupNeeded() async {
+ final hasCleanup =
+ await CollectionsService.instance.hasFilesNeedingHiddenCleanup();
+ if (mounted && hasCleanup != _hasFilesNeedingCleanup) {
+ setState(() {
+ _hasFilesNeedingCleanup = hasCleanup;
+ });
+ }
}
getHiddenCollections() {
@@ -128,22 +142,41 @@ class _HiddenPageState extends State<HiddenPage> {
emptyState: _hiddenCollectionsExcludingDefault.isEmpty
? const EmptyHiddenWidget()
: const SizedBox.shrink(),
- header: AlbumHorizontalList(
- () async {
- return _hiddenCollectionsExcludingDefault;
- },
- hasVerifiedLock: true,
- onViewAllTapped: () async {
- await routeToPage(
- context,
- CollectionListPage(
- _hiddenCollectionsExcludingDefault,
- sectionType: UISectionType.hiddenCollections,
- appTitle: Text(AppLocalizations.of(context).hidden),
- tag: "hidden",
+ header: Column(
+ children: [
+ RepaintBoundary(
+ child: AnimatedCrossFade(
+ firstCurve: Curves.easeInOutQuart,
+ secondCurve: Curves.easeInOutQuart,
+ sizeCurve: Curves.easeInOutQuart,
+ firstChild: CleanupHiddenFilesWidget(
+ onCleanupComplete: () => _checkForCleanupNeeded(),
+ ),
+ secondChild: const SizedBox(width: double.infinity),
+ crossFadeState: _hasFilesNeedingCleanup
+ ? CrossFadeState.showFirst
+ : CrossFadeState.showSecond,
+ duration: const Duration(milliseconds: 750),
),
- );
- },
+ ),
+ AlbumHorizontalList(
+ () async {
+ return _hiddenCollectionsExcludingDefault;
+ },
+ hasVerifiedLock: true,
+ onViewAllTapped: () async {
+ await routeToPage(
+ context,
+ CollectionListPage(
+ _hiddenCollectionsExcludingDefault,
+ sectionType: UISectionType.hiddenCollections,
+ appTitle: Text(AppLocalizations.of(context).hidden),
+ tag: "hidden",
+ ),
+ );
+ },
+ ),
+ ],
),
);
return GalleryBoundariesProvider(