Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add option to delete hidden files from device

ashilkn03ca3fbbacf1
diff --git a/mobile/apps/photos/lib/db/files_db.dart b/mobile/apps/photos/lib/db/files_db.dart
index 2cc180473a..ad13352578 100644
--- a/mobile/apps/photos/lib/db/files_db.dart
+++ b/mobile/apps/photos/lib/db/files_db.dart
@@ -1901,7 +1901,7 @@ class FilesDB with SqlDbBase {
final db = await instance.sqliteAsyncDB;
final results = await db.getAll('''
SELECT DISTINCT $columnUploadedFileID FROM $filesTable
- WHERE $columnUploadedFileID IS NOT NULL AND $columnUploadedFileID IS NOT -1
+ WHERE $columnUploadedFileID IS NOT NULL AND $columnUploadedFileID IS NOT -1
''');
final ids = <int>{};
for (final result in results) {
@@ -1910,6 +1910,80 @@ class FilesDB with SqlDbBase {
return ids.length;
}
+ /// Returns hidden files that have local copies on the device.
+ /// Only returns files owned by [ownerID] from the specified
+ /// [hiddenCollectionIds].
+ /// Results are deduplicated by uploadedFileID to avoid showing the same
+ /// file multiple times if it exists in multiple hidden collections.
+ Future<List<EnteFile>> getHiddenFilesWithLocalCopy(
+ Set<int> hiddenCollectionIds,
+ int ownerID,
+ ) async {
+ if (hiddenCollectionIds.isEmpty) {
+ return [];
+ }
+ final db = await instance.sqliteAsyncDB;
+ final inParam = hiddenCollectionIds.join(',');
+ final results = await db.getAll(
+ '''
+ SELECT * FROM $filesTable
+ WHERE $columnCollectionID IN ($inParam)
+ AND $columnOwnerID = ?
+ AND $columnLocalID IS NOT NULL AND $columnLocalID != ''
+ AND $columnUploadedFileID IS NOT NULL AND $columnUploadedFileID != -1
+ GROUP BY $columnUploadedFileID
+ ORDER BY $columnCreationTime DESC
+ ''',
+ [ownerID],
+ );
+ return convertToFiles(results);
+ }
+
+ /// Returns true if there are any hidden files with local copies on the device.
+ /// More efficient than loading all files when only checking for existence.
+ Future<bool> hasHiddenFilesWithLocalCopy(
+ Set<int> hiddenCollectionIds,
+ int ownerID,
+ ) async {
+ if (hiddenCollectionIds.isEmpty) {
+ return false;
+ }
+ final db = await instance.sqliteAsyncDB;
+ final inParam = hiddenCollectionIds.join(',');
+ final results = await db.getAll(
+ '''
+ SELECT 1 FROM $filesTable
+ WHERE $columnCollectionID IN ($inParam)
+ AND $columnOwnerID = ?
+ AND $columnLocalID IS NOT NULL AND $columnLocalID != ''
+ AND $columnUploadedFileID IS NOT NULL AND $columnUploadedFileID != -1
+ LIMIT 1
+ ''',
+ [ownerID],
+ );
+ return results.isNotEmpty;
+ }
+
+ /// Clears localID for all rows matching any of the given uploadedFileIDs.
+ /// This is used when deleting files from device to ensure all collection
+ /// entries for the same file have their localID cleared.
+ Future<void> clearLocalIDsForUploadedFileIDs(
+ List<int> uploadedFileIDs,
+ ) async {
+ if (uploadedFileIDs.isEmpty) {
+ return;
+ }
+ final db = await instance.sqliteAsyncDB;
+ final inParam = uploadedFileIDs.join(',');
+ await db.execute(
+ '''
+ UPDATE $filesTable
+ SET $columnLocalID = NULL
+ WHERE $columnUploadedFileID IN ($inParam)
+ ''',
+ );
+ }
+
///Returns "columnName1 = ?, columnName2 = ?, ..."
String _generateUpdateAssignmentsWithPlaceholders({
required int? fileGenId,
diff --git a/mobile/apps/photos/lib/l10n/intl_en.arb b/mobile/apps/photos/lib/l10n/intl_en.arb
index 6ef385601a..68b153435a 100644
--- a/mobile/apps/photos/lib/l10n/intl_en.arb
+++ b/mobile/apps/photos/lib/l10n/intl_en.arb
@@ -2525,5 +2525,17 @@
"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"
+ "cleanupComplete": "Cleanup complete",
+ "deleteHiddenFilesFromDevice": "Delete hidden files from device",
+ "deleteHiddenFilesFromDeviceDescription": "Delete local copies of hidden files from your device while keeping them safe in the cloud.",
+ "noHiddenFilesOnDevice": "No hidden files on device",
+ "deleteSelectedFromDevice": "Delete selected from device",
+ "deleteFromDeviceConfirmation": "Are you sure you want to delete {count, plural, =1{1 file} other{{count} files}} from your device? The files will remain safe in the cloud.",
+ "@deleteFromDeviceConfirmation": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ }
}
diff --git a/mobile/apps/photos/lib/services/hidden_service.dart b/mobile/apps/photos/lib/services/hidden_service.dart
index 86726ca22e..7b18e2ab8d 100644
--- a/mobile/apps/photos/lib/services/hidden_service.dart
+++ b/mobile/apps/photos/lib/services/hidden_service.dart
@@ -395,6 +395,35 @@ extension HiddenService on CollectionsService {
return createRequest;
}
+ /// Returns true if there are hidden files with local copies on device.
+ /// Uses an efficient LIMIT 1 query instead of loading all files.
+ Future<bool> hasHiddenFilesOnDevice() async {
+ final userID = config.getUserID();
+ if (userID == null) {
+ return false;
+ }
+ final hiddenCollectionIds = getHiddenCollectionIds();
+ if (hiddenCollectionIds.isEmpty) {
+ return false;
+ }
+ return filesDB.hasHiddenFilesWithLocalCopy(hiddenCollectionIds, userID);
+ }
+
+ /// Gets hidden files that have local copies, deduplicated by uploadedFileID.
+ /// Only returns files owned by the current user from any hidden collection
+ /// (owned or shared).
+ Future<List<EnteFile>> getHiddenFilesOnDevice() async {
+ final userID = config.getUserID();
+ if (userID == null) {
+ return [];
+ }
+ final hiddenCollectionIds = getHiddenCollectionIds();
+ if (hiddenCollectionIds.isEmpty) {
+ return [];
+ }
+ return filesDB.getHiddenFilesWithLocalCopy(hiddenCollectionIds, userID);
+ }
+
/// Checks if there are hidden files that also exist in non-hidden collections.
/// Only considers files owned by the user.
Future<bool> hasFilesNeedingHiddenCleanup() async {
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/cleanup_hidden_from_device_page.dart b/mobile/apps/photos/lib/ui/viewer/gallery/cleanup_hidden_from_device_page.dart
new file mode 100644
index 0000000000..9c5e149e7a
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/cleanup_hidden_from_device_page.dart
@@ -0,0 +1,154 @@
+import "package:flutter/material.dart";
+import "package:photos/core/event_bus.dart";
+import "package:photos/events/files_updated_event.dart";
+import "package:photos/events/local_photos_updated_event.dart";
+import "package:photos/generated/l10n.dart";
+import "package:photos/models/file_load_result.dart";
+import "package:photos/models/selected_files.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/action_sheet_widget.dart";
+import "package:photos/ui/components/buttons/button_widget.dart";
+import "package:photos/ui/components/models/button_type.dart";
+import "package:photos/ui/viewer/gallery/empty_state.dart";
+import "package:photos/ui/viewer/gallery/gallery.dart";
+import "package:photos/ui/viewer/gallery/state/gallery_boundaries_provider.dart";
+import "package:photos/ui/viewer/gallery/state/gallery_files_inherited_widget.dart";
+import "package:photos/ui/viewer/gallery/state/selection_state.dart";
+import "package:photos/utils/delete_file_util.dart";
+import "package:photos/utils/dialog_util.dart";
+
+class CleanupHiddenFromDevicePage extends StatefulWidget {
+ final VoidCallback? onCleanupComplete;
+
+ const CleanupHiddenFromDevicePage({
+ this.onCleanupComplete,
+ super.key,
+ });
+
+ @override
+ State<CleanupHiddenFromDevicePage> createState() =>
+ _CleanupHiddenFromDevicePageState();
+}
+
+class _CleanupHiddenFromDevicePageState
+ extends State<CleanupHiddenFromDevicePage> {
+ final _selectedFiles = SelectedFiles();
+
+ @override
+ void initState() {
+ super.initState();
+ _selectedFiles.addListener(_onSelectionChange);
+ }
+
+ @override
+ void dispose() {
+ _selectedFiles.removeListener(_onSelectionChange);
+ super.dispose();
+ }
+
+ void _onSelectionChange() {
+ setState(() {});
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+
+ final gallery = Gallery(
+ asyncLoader: (creationStartTime, creationEndTime, {limit, asc}) async {
+ final files =
+ await CollectionsService.instance.getHiddenFilesOnDevice();
+ return FileLoadResult(files, false);
+ },
+ reloadEvent: Bus.instance.on<LocalPhotosUpdatedEvent>(),
+ removalEventTypes: const {EventType.deletedFromDevice},
+ tagPrefix: "cleanup_hidden_from_device",
+ selectedFiles: _selectedFiles,
+ inSelectionMode: true,
+ enableFileGrouping: false,
+ emptyState: EmptyState(
+ text: AppLocalizations.of(context).noHiddenFilesOnDevice,
+ ),
+ );
+
+ return GalleryBoundariesProvider(
+ child: GalleryFilesState(
+ child: Scaffold(
+ appBar: AppBar(
+ elevation: 0,
+ title: Text(
+ AppLocalizations.of(context).deleteHiddenFilesFromDevice,
+ style: textTheme.h3Bold,
+ ),
+ actions: [
+ if (_selectedFiles.files.isNotEmpty)
+ TextButton(
+ onPressed: _deleteSelected,
+ child: Text(
+ "${AppLocalizations.of(context).delete} (${_selectedFiles.files.length})",
+ style: textTheme.bodyBold.copyWith(
+ color: colorScheme.primary500,
+ ),
+ ),
+ ),
+ ],
+ ),
+ body: SelectionState(
+ selectedFiles: _selectedFiles,
+ child: gallery,
+ ),
+ ),
+ ),
+ );
+ }
+
+ Future<void> _deleteSelected() async {
+ final count = _selectedFiles.files.length;
+ final l10n = AppLocalizations.of(context);
+
+ final actionResult = await showActionSheet(
+ context: context,
+ buttons: [
+ ButtonWidget(
+ labelText: l10n.deleteSelectedFromDevice,
+ buttonType: ButtonType.critical,
+ buttonSize: ButtonSize.large,
+ shouldStickToDarkTheme: true,
+ buttonAction: ButtonAction.first,
+ shouldSurfaceExecutionStates: true,
+ isInAlert: true,
+ onTap: () async {
+ try {
+ final filesToDelete = _selectedFiles.files.toList();
+ await deleteFilesOnDeviceOnly(context, filesToDelete);
+ _selectedFiles.clearAll();
+ } catch (e) {
+ if (context.mounted) {
+ await showGenericErrorDialog(context: context, error: e);
+ }
+ rethrow;
+ }
+ },
+ ),
+ ButtonWidget(
+ labelText: l10n.cancel,
+ buttonType: ButtonType.secondary,
+ buttonSize: ButtonSize.large,
+ shouldStickToDarkTheme: true,
+ buttonAction: ButtonAction.cancel,
+ isInAlert: true,
+ ),
+ ],
+ title: l10n.deleteFromDevice,
+ body: l10n.deleteFromDeviceConfirmation(count: count),
+ actionSheetType: ActionSheetType.defaultActionSheet,
+ );
+
+ if (actionResult?.action == ButtonAction.first) {
+ widget.onCleanupComplete?.call();
+ }
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/cleanup_hidden_from_device_widget.dart b/mobile/apps/photos/lib/ui/viewer/gallery/cleanup_hidden_from_device_widget.dart
new file mode 100644
index 0000000000..b41e15202b
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/cleanup_hidden_from_device_widget.dart
@@ -0,0 +1,50 @@
+import "package:ente_pure_utils/ente_pure_utils.dart";
+import "package:flutter/material.dart";
+import "package:photos/generated/l10n.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";
+import "package:photos/ui/viewer/gallery/cleanup_hidden_from_device_page.dart";
+
+class CleanupHiddenFromDeviceWidget extends StatelessWidget {
+ final VoidCallback onCleanupComplete;
+
+ const CleanupHiddenFromDeviceWidget({
+ 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: 12),
+ child: Column(
+ children: [
+ MenuItemWidget(
+ captionedTextWidget: CaptionedTextWidget(
+ title: AppLocalizations.of(context).deleteHiddenFilesFromDevice,
+ ),
+ singleBorderRadius: 8.0,
+ menuItemColor: colorScheme.fillFaint,
+ leadingIcon: Icons.phone_android_outlined,
+ trailingIcon: Icons.chevron_right,
+ onTap: () async {
+ await routeToPage(
+ context,
+ CleanupHiddenFromDevicePage(
+ onCleanupComplete: onCleanupComplete,
+ ),
+ );
+ },
+ ),
+ MenuSectionDescriptionWidget(
+ content: AppLocalizations.of(context)
+ .deleteHiddenFilesFromDeviceDescription,
+ ),
+ ],
+ ),
+ );
+ }
+}
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 cd2922d007..6f4bdf32dc 100644
--- a/mobile/apps/photos/lib/ui/viewer/gallery/hidden_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/hidden_page.dart
@@ -19,6 +19,7 @@ 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/cleanup_hidden_from_device_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';
@@ -46,6 +47,7 @@ class _HiddenPageState extends State<HiddenPage> {
int? _defaultHiddenCollectionId;
final _hiddenCollectionsExcludingDefault = <Collection>[];
bool _hasFilesNeedingCleanup = false;
+ bool _hasHiddenFilesOnDevice = false;
late StreamSubscription<CollectionUpdatedEvent>
_collectionUpdatesSubscription;
@@ -58,9 +60,11 @@ class _HiddenPageState extends State<HiddenPage> {
getHiddenCollections();
});
_checkForCleanupNeeded();
+ _checkForDeviceCleanupNeeded();
});
getHiddenCollections();
_checkForCleanupNeeded();
+ _checkForDeviceCleanupNeeded();
}
Future<void> _checkForCleanupNeeded() async {
@@ -73,6 +77,16 @@ class _HiddenPageState extends State<HiddenPage> {
}
}
+ Future<void> _checkForDeviceCleanupNeeded() async {
+ final hasDeviceFiles =
+ await CollectionsService.instance.hasHiddenFilesOnDevice();
+ if (mounted && hasDeviceFiles != _hasHiddenFilesOnDevice) {
+ setState(() {
+ _hasHiddenFilesOnDevice = hasDeviceFiles;
+ });
+ }
+ }
+
getHiddenCollections() {
final hiddenCollections =
CollectionsService.instance.getHiddenCollections();
@@ -159,6 +173,21 @@ class _HiddenPageState extends State<HiddenPage> {
duration: const Duration(milliseconds: 750),
),
),
+ RepaintBoundary(
+ child: AnimatedCrossFade(
+ firstCurve: Curves.easeInOutQuart,
+ secondCurve: Curves.easeInOutQuart,
+ sizeCurve: Curves.easeInOutQuart,
+ firstChild: CleanupHiddenFromDeviceWidget(
+ onCleanupComplete: () => _checkForDeviceCleanupNeeded(),
+ ),
+ secondChild: const SizedBox(width: double.infinity),
+ crossFadeState: _hasHiddenFilesOnDevice
+ ? CrossFadeState.showFirst
+ : CrossFadeState.showSecond,
+ duration: const Duration(milliseconds: 750),
+ ),
+ ),
AlbumHorizontalList(
() async {
return _hiddenCollectionsExcludingDefault;
diff --git a/mobile/apps/photos/lib/utils/delete_file_util.dart b/mobile/apps/photos/lib/utils/delete_file_util.dart
index 0779529506..6d5d37a969 100644
--- a/mobile/apps/photos/lib/utils/delete_file_util.dart
+++ b/mobile/apps/photos/lib/utils/delete_file_util.dart
@@ -234,6 +234,7 @@ Future<void> deleteFilesOnDeviceOnly(
}
deletedIDs.addAll(await _tryDeleteSharedMediaFiles(localSharedMediaIDs));
final List<EnteFile> deletedFiles = [];
+ final List<int> uploadedFileIDsToClear = [];
for (final file in files) {
// Remove only those files that have been removed from disk
if (deletedIDs.contains(file.localID) ||
@@ -241,12 +242,19 @@ Future<void> deleteFilesOnDeviceOnly(
deletedFiles.add(file);
if (hasLocalOnlyFiles && localOnlyIDs.contains(file.localID)) {
await FilesDB.instance.deleteLocalFile(file);
- } else {
+ } else if (file.uploadedFileID != null) {
+ // Collect uploadedFileIDs to batch clear localID for all rows
+ // with the same uploadedFileID (handles multiple collection entries)
+ uploadedFileIDsToClear.add(file.uploadedFileID!);
file.localID = null;
- await FilesDB.instance.update(file);
}
}
}
+ // Batch clear localIDs for all rows with matching uploadedFileIDs
+ if (uploadedFileIDsToClear.isNotEmpty) {
+ await FilesDB.instance
+ .clearLocalIDsForUploadedFileIDs(uploadedFileIDsToClear);
+ }
if (deletedFiles.isNotEmpty || alreadyDeletedIDs.isNotEmpty) {
Bus.instance.fire(
LocalPhotosUpdatedEvent(