Skip to content

armgit / ente

Public Imported from GitHub
0

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

Show new local photos immediately

Neeraj Guptad414e1573231
diff --git a/mobile/apps/photos/changes/show-new-local-photos-immediately.md b/mobile/apps/photos/changes/show-new-local-photos-immediately.md
new file mode 100644
index 0000000000..7aece706f1
--- /dev/null
+++ b/mobile/apps/photos/changes/show-new-local-photos-immediately.md
@@ -0,0 +1 @@
+- Show newly added device photos in the home gallery without waiting for a full reload.
diff --git a/mobile/apps/photos/lib/db/device_files_db.dart b/mobile/apps/photos/lib/db/device_files_db.dart
index 579eb4e7de..fe14c516b4 100644
--- a/mobile/apps/photos/lib/db/device_files_db.dart
+++ b/mobile/apps/photos/lib/db/device_files_db.dart
@@ -133,6 +133,27 @@ extension DeviceFiles on FilesDB {
return names.toList(growable: false);
}
+ Future<Set<String>> getLocalIDsInBackupFolders(
+ Set<String> localIDs,
+ Set<int> excludedCollectionIDs,
+ ) async {
+ if (localIDs.isEmpty) return {};
+
+ final db = await sqliteAsyncDB;
+ final localIDPlaceholders = List.filled(localIDs.length, '?').join(',');
+ final rows = await db.getAll('''
+ SELECT DISTINCT df.id, dc.collection_id
+ FROM device_files df
+ INNER JOIN device_collections dc ON dc.id = df.path_id
+ WHERE dc.should_backup = $_sqlBoolTrue
+ AND df.id IN ($localIDPlaceholders)
+ ''', localIDs.toList(growable: false));
+ return rows
+ .where((row) => !excludedCollectionIDs.contains(row['collection_id']))
+ .map((row) => row['id'] as String)
+ .toSet();
+ }
+
Future<Set<String>> getDevicePathIDs() async {
final db = await sqliteAsyncDB;
final rows = await db.getAll('''
diff --git a/mobile/apps/photos/lib/events/local_photos_updated_event.dart b/mobile/apps/photos/lib/events/local_photos_updated_event.dart
index 5b8e460f2a..5eb5a99a78 100644
--- a/mobile/apps/photos/lib/events/local_photos_updated_event.dart
+++ b/mobile/apps/photos/lib/events/local_photos_updated_event.dart
@@ -1,13 +1,25 @@
import 'package:photos/events/files_updated_event.dart';
+import 'package:photos/models/file/file.dart';
class LocalPhotosUpdatedEvent extends FilesUpdatedEvent {
- // "Recent" means created within the last seven days.
- final bool hasRecentNewLocalDiscovery;
+ final List<EnteFile> newlyDiscoveredFiles;
+ final bool canAddNewFilesWithoutReload;
+
+ bool get hasRecentNewLocalDiscovery {
+ final sevenDaysAgo = DateTime.now()
+ .subtract(const Duration(days: 7))
+ .microsecondsSinceEpoch;
+ return newlyDiscoveredFiles.any(
+ (file) => (file.creationTime ?? 0) > sevenDaysAgo,
+ );
+ }
LocalPhotosUpdatedEvent(
super.updatedFiles, {
type,
required source,
- this.hasRecentNewLocalDiscovery = false,
- }) : super(type: type ?? EventType.addedOrUpdated, source: source ?? "");
+ List<EnteFile> newlyDiscoveredFiles = const [],
+ this.canAddNewFilesWithoutReload = false,
+ }) : newlyDiscoveredFiles = List.unmodifiable(newlyDiscoveredFiles),
+ super(type: type ?? EventType.addedOrUpdated, source: source ?? "");
}
diff --git a/mobile/apps/photos/lib/services/sync/local_sync_service.dart b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
index 8c0980e40a..3c41145b86 100644
--- a/mobile/apps/photos/lib/services/sync/local_sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
@@ -243,10 +243,24 @@ class LocalSyncService {
"unSyncedFiles: $hasUnsyncedFiles",
);
if (hasAnyMappingChanged || hasUnsyncedFiles) {
+ final newlyDiscoveredFiles = localDiffResult.uniqueLocalFiles ?? [];
+ final newlyDiscoveredLocalIDs = newlyDiscoveredFiles
+ .map((file) => file.localID)
+ .nonNulls
+ .toSet();
+ final newlyMappedLocalIDs =
+ localDiffResult.newPathToLocalIDs?.values.expand((ids) => ids) ??
+ const Iterable<String>.empty();
+ final canAddNewFilesWithoutReload =
+ hasUnsyncedFiles &&
+ (localDiffResult.deletePathToLocalIDs?.isEmpty ?? true) &&
+ newlyMappedLocalIDs.every(newlyDiscoveredLocalIDs.contains);
Bus.instance.fire(
LocalPhotosUpdatedEvent(
- localDiffResult.uniqueLocalFiles ?? [],
+ newlyDiscoveredFiles,
source: "syncAllChange",
+ newlyDiscoveredFiles: newlyDiscoveredFiles,
+ canAddNewFilesWithoutReload: canAddNewFilesWithoutReload,
),
);
}
@@ -399,22 +413,13 @@ class LocalSyncService {
}
}
- // Check if any NEWLY INSERTED files were created in the last 7 days
- bool hasRecentNewLocalDiscovery = false;
- if (discoveredNewFiles) {
- final sevenDaysAgo = DateTime.now()
- .subtract(const Duration(days: 7))
- .microsecondsSinceEpoch;
- hasRecentNewLocalDiscovery = newlyInsertedFiles.any(
- (file) => (file.creationTime ?? 0) > sevenDaysAgo,
- );
- }
-
Bus.instance.fire(
LocalPhotosUpdatedEvent(
allFiles,
source: "loadedPhoto",
- hasRecentNewLocalDiscovery: hasRecentNewLocalDiscovery,
+ newlyDiscoveredFiles: newlyInsertedFiles,
+ canAddNewFilesWithoutReload:
+ discoveredNewFiles && allFiles.length == newlyInsertedFiles.length,
),
);
}
diff --git a/mobile/apps/photos/lib/ui/home/home_gallery_widget.dart b/mobile/apps/photos/lib/ui/home/home_gallery_widget.dart
index 705bcf4f0e..22d1dd6ab7 100644
--- a/mobile/apps/photos/lib/ui/home/home_gallery_widget.dart
+++ b/mobile/apps/photos/lib/ui/home/home_gallery_widget.dart
@@ -5,11 +5,13 @@ import 'package:flutter/material.dart';
import 'package:photos/core/configuration.dart';
import 'package:photos/core/event_bus.dart';
import "package:photos/core/user_config.dart";
+import 'package:photos/db/device_files_db.dart';
import 'package:photos/db/files_db.dart';
import 'package:photos/events/files_updated_event.dart';
import 'package:photos/events/force_reload_home_gallery_event.dart';
import "package:photos/events/hide_shared_items_from_home_gallery_event.dart";
import 'package:photos/events/local_photos_updated_event.dart';
+import 'package:photos/models/file/file.dart';
import 'package:photos/models/file_load_result.dart';
import 'package:photos/models/gallery_type.dart';
import 'package:photos/models/selected_files.dart';
@@ -43,6 +45,7 @@ class HomeGalleryWidget extends StatefulWidget {
}
class _HomeGalleryWidgetState extends State<HomeGalleryWidget> {
+ static const _maxFastAddFiles = 50;
late final StreamSubscription<HideSharedItemsFromHomeGalleryEvent>
_hideSharedFilesFromHomeSubscription;
bool _shouldHideSharedItems = localSettings.hideSharedItemsFromHomeGallery;
@@ -55,6 +58,50 @@ class _HomeGalleryWidgetState extends State<HomeGalleryWidget> {
const Duration(milliseconds: 500),
);
+ DBFilterOptions get _filterOptions => DBFilterOptions(
+ hideIgnoredForUpload: true,
+ dedupeUploadID: true,
+ ignoredCollectionIDs: CollectionsService.instance
+ .archivedOrHiddenCollectionIds(),
+ ignoreSavedFiles: true,
+ ignoreSharedItems: _shouldHideSharedItems,
+ );
+
+ Future<List<EnteFile>?> _resolveNewLocalFiles(
+ LocalPhotosUpdatedEvent event,
+ ) async {
+ final files = event.newlyDiscoveredFiles;
+ final filterOptions = _filterOptions;
+ if (files.any(
+ (file) =>
+ file.localID == null ||
+ file.creationTime == null ||
+ file.modificationTime == null,
+ )) {
+ return null;
+ }
+
+ var candidates = files;
+ if (!isLocalGalleryMode) {
+ if (files.length > _maxFastAddFiles ||
+ !event.hasRecentNewLocalDiscovery) {
+ return null;
+ }
+ if (!backupPreferenceService.hasSelectedAllFoldersForBackup) {
+ final localIDs = files.map((file) => file.localID!).toSet();
+ final selectedLocalIDs = await FilesDB.instance
+ .getLocalIDsInBackupFolders(
+ localIDs,
+ filterOptions.ignoredCollectionIDs ?? {},
+ );
+ candidates = files
+ .where((file) => selectedLocalIDs.contains(file.localID))
+ .toList(growable: false);
+ }
+ }
+ return applyDBFilters(candidates, filterOptions);
+ }
+
@override
void initState() {
super.initState();
@@ -87,16 +134,8 @@ class _HomeGalleryWidgetState extends State<HomeGalleryWidget> {
final hasSelectedAllForBackup =
backupPreferenceService.hasSelectedAllFoldersForBackup ||
isLocalGalleryMode;
- final collectionsToHide = CollectionsService.instance
- .archivedOrHiddenCollectionIds();
FileLoadResult result;
- final DBFilterOptions filterOptions = DBFilterOptions(
- hideIgnoredForUpload: true,
- dedupeUploadID: true,
- ignoredCollectionIDs: collectionsToHide,
- ignoreSavedFiles: true,
- ignoreSharedItems: _shouldHideSharedItems,
- );
+ final filterOptions = _filterOptions;
if (hasSelectedAllForBackup) {
result = await FilesDB.instance.getAllLocalAndUploadedFiles(
creationStartTime,
@@ -140,6 +179,7 @@ class _HomeGalleryWidgetState extends State<HomeGalleryWidget> {
reloadDebounceTime: const Duration(seconds: 2),
reloadDebounceExecutionInterval: const Duration(seconds: 5),
priorityReloadDebounceTime: const Duration(milliseconds: 200),
+ newLocalFilesResolver: _resolveNewLocalFiles,
galleryType: GalleryType.homepage,
groupType: widget.groupType,
showGallerySettingsCTA: true,
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart b/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart
index b0a44ef929..7b53a1c9e4 100644
--- a/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart
@@ -51,6 +51,9 @@ typedef GalleryLoader =
typedef SortAscFn = bool Function();
+typedef NewLocalFilesResolver =
+ Future<List<EnteFile>?> Function(LocalPhotosUpdatedEvent event);
+
class Gallery extends StatefulWidget {
final GalleryLoader asyncLoader;
final List<EnteFile>? initialFiles;
@@ -73,6 +76,9 @@ class Gallery extends StatefulWidget {
final GalleryType? galleryType;
final bool showGallerySettingsCTA;
+ /// Returns eligible additions, or null when the gallery must reload.
+ final NewLocalFilesResolver? newLocalFilesResolver;
+
/// When true, selection will be limited to one item. Tapping on any item
/// will select even when no other item is selected.
final bool limitSelectionToOne;
@@ -128,6 +134,7 @@ class Gallery extends StatefulWidget {
this.disableVerticalPaddingForScrollbar = false,
this.showGallerySettingsCTA = false,
this.fileToJumpTo,
+ this.newLocalFilesResolver,
super.key,
});
@@ -155,6 +162,7 @@ class GalleryState extends State<Gallery> {
final _forceReloadEventSubscriptions = <StreamSubscription<Event>>[];
late String _logTag;
bool _sortOrderAsc = false;
+ int _activeFileLoads = 0;
List<EnteFile> _allGalleryFiles = [];
final _scrollController = ScrollController();
final _headerKey = GlobalKey();
@@ -214,6 +222,11 @@ class GalleryState extends State<Gallery> {
return;
}
+ if (event is LocalPhotosUpdatedEvent &&
+ await _tryAddNewLocalFiles(event)) {
+ return;
+ }
+
final isPriorityEvent =
event is LocalPhotosUpdatedEvent &&
event.hasRecentNewLocalDiscovery;
@@ -533,6 +546,76 @@ class GalleryState extends State<Gallery> {
return false;
}
+ Future<bool> _tryAddNewLocalFiles(LocalPhotosUpdatedEvent event) async {
+ final resolver = widget.newLocalFilesResolver;
+ if (resolver == null ||
+ !event.canAddNewFilesWithoutReload ||
+ !_allFilesLoaded ||
+ _activeFileLoads > 0) {
+ return false;
+ }
+
+ List<EnteFile>? resolvedFiles;
+ try {
+ resolvedFiles = await resolver(event);
+ } catch (e, s) {
+ _logger.warning('Failed to resolve new local files', e, s);
+ return false;
+ }
+ if (resolvedFiles == null) return false;
+ if (!mounted) return true;
+ if (_activeFileLoads > 0) return false;
+
+ final visibleLocalIDs = _allGalleryFiles
+ .map((file) => file.localID)
+ .nonNulls
+ .toSet();
+ final filesToAdd =
+ resolvedFiles
+ .where(
+ (file) =>
+ file.localID != null && visibleLocalIDs.add(file.localID!),
+ )
+ .toList()
+ ..sort(_compareGalleryFiles);
+ if (filesToAdd.isNotEmpty) {
+ _setFilesAndReload(_mergeGalleryFiles(filesToAdd));
+ }
+ _logger.info('Added ${filesToAdd.length} new local files in memory');
+ return true;
+ }
+
+ List<EnteFile> _mergeGalleryFiles(List<EnteFile> filesToAdd) {
+ final merged = <EnteFile>[];
+ var currentIndex = 0;
+ var addedIndex = 0;
+ while (currentIndex < _allGalleryFiles.length &&
+ addedIndex < filesToAdd.length) {
+ if (_compareGalleryFiles(
+ filesToAdd[addedIndex],
+ _allGalleryFiles[currentIndex],
+ ) <
+ 0) {
+ merged.add(filesToAdd[addedIndex++]);
+ } else {
+ merged.add(_allGalleryFiles[currentIndex++]);
+ }
+ }
+ merged.addAll(_allGalleryFiles.skip(currentIndex));
+ merged.addAll(filesToAdd.skip(addedIndex));
+ return merged;
+ }
+
+ int _compareGalleryFiles(EnteFile first, EnteFile second) {
+ var result = (first.creationTime ?? 0).compareTo(second.creationTime ?? 0);
+ if (result == 0) {
+ result = (first.modificationTime ?? 0).compareTo(
+ second.modificationTime ?? 0,
+ );
+ }
+ return _sortOrderAsc ? result : -result;
+ }
+
void _updateSwipeHelper() {
if (widget.selectedFiles != null && _allFilesWithDummies.isNotEmpty) {
// Dispose existing helper if present
@@ -549,6 +632,7 @@ class GalleryState extends State<Gallery> {
Future<FileLoadResult> _loadFiles({int? limit}) async {
_logger.info("Loading ${limit ?? "all"} files");
+ _activeFileLoads++;
try {
final startTime = DateTime.now().microsecondsSinceEpoch;
final result = await widget.asyncLoader(
@@ -589,6 +673,8 @@ class GalleryState extends State<Gallery> {
} catch (e, s) {
_logger.severe("failed to load files", e, s);
rethrow;
+ } finally {
+ _activeFileLoads--;
}
}