Skip to content

armgit / ente

Public Imported from GitHub
0

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

Optimize feed loading and remove profiling logs

Neeraj Guptafccb2d0a64a7
diff --git a/mobile/apps/photos/lib/db/files_db.dart b/mobile/apps/photos/lib/db/files_db.dart
index 99d07fcf5a..f4f15adf2d 100644
--- a/mobile/apps/photos/lib/db/files_db.dart
+++ b/mobile/apps/photos/lib/db/files_db.dart
@@ -589,52 +589,46 @@ class FilesDB with SqlDbBase {
/// Checks which (fileID, collectionID) pairs exist in the database.
///
- /// Returns a set of keys in the format "collectionID_fileID" for files that exist.
- /// This is more efficient than calling getUploadedFile() for each pair.
- Future<Set<String>> getExistingFileKeys(
+ /// Returns a map keyed by collection ID, with each value containing
+ /// the existing file IDs for that collection.
+ Future<Map<int, Set<int>>> getExistingFileIDsByCollection(
Set<(int fileID, int collectionID)> pairs,
) async {
if (pairs.isEmpty) return {};
final db = await instance.sqliteAsyncDB;
- final existingKeys = <String>{};
-
- // Build a query with OR conditions for each pair
- // SQLite has a limit on compound SELECT statements, so we batch
- const batchSize = 100;
- final pairsList = pairs.toList();
-
- for (var i = 0; i < pairsList.length; i += batchSize) {
- final batch = pairsList.sublist(
- i,
- i + batchSize > pairsList.length ? pairsList.length : i + batchSize,
- );
-
- final conditions = batch
- .map(
- (_) => '($columnUploadedFileID = ? AND $columnCollectionID = ?)',
- )
- .join(' OR ');
-
- final args = <Object>[];
- for (final (fileID, collectionID) in batch) {
- args.add(fileID);
- args.add(collectionID);
- }
-
- final results = await db.getAll(
- 'SELECT $columnUploadedFileID, $columnCollectionID FROM $filesTable WHERE $conditions',
- args,
- );
-
- for (final row in results) {
- final fileID = row[columnUploadedFileID] as int;
- final collectionID = row[columnCollectionID] as int;
- existingKeys.add('${collectionID}_$fileID');
+ final existing = <int, Set<int>>{};
+ final fileIDsByCollection = <int, Set<int>>{};
+ for (final (fileID, collectionID) in pairs) {
+ fileIDsByCollection.putIfAbsent(collectionID, () => {}).add(fileID);
+ }
+
+ // Keep placeholders under common SQLite variable limits.
+ const maxInParams = 900;
+
+ for (final entry in fileIDsByCollection.entries) {
+ final collectionID = entry.key;
+ final fileIDs = entry.value.toList(growable: false);
+ for (var i = 0; i < fileIDs.length; i += maxInParams) {
+ final end = (i + maxInParams > fileIDs.length)
+ ? fileIDs.length
+ : i + maxInParams;
+ final chunk = fileIDs.sublist(i, end);
+ final placeholders = List.filled(chunk.length, '?').join(',');
+ final results = await db.getAll(
+ 'SELECT $columnUploadedFileID FROM $filesTable '
+ 'WHERE $columnCollectionID = ? '
+ 'AND $columnUploadedFileID IN ($placeholders)',
+ [collectionID, ...chunk],
+ );
+ for (final row in results) {
+ final fileID = row[columnUploadedFileID] as int;
+ existing.putIfAbsent(collectionID, () => {}).add(fileID);
+ }
}
}
- return existingKeys;
+ return existing;
}
Future<(Set<int>, Map<String, int>)> getUploadAndHash(
diff --git a/mobile/apps/photos/lib/models/social/feed_data_provider.dart b/mobile/apps/photos/lib/models/social/feed_data_provider.dart
index e0bb296e2e..1860e31b8d 100644
--- a/mobile/apps/photos/lib/models/social/feed_data_provider.dart
+++ b/mobile/apps/photos/lib/models/social/feed_data_provider.dart
@@ -26,6 +26,12 @@ class FeedDataProvider {
static const _kSharedPhotoFetchMaxPages = 5;
static const _kSharedPhotoFetchMaxRows =
_kSharedPhotoFetchPageSize * _kSharedPhotoFetchMaxPages;
+ static const _kFeedItemsCacheTtlMs = 3000;
+ Future<List<FeedItem>>? _inFlightFeedItemsFuture;
+ String? _inFlightFeedItemsKey;
+ List<FeedItem>? _lastFeedItems;
+ String? _lastFeedItemsKey;
+ int? _lastFeedItemsAtMs;
/// Gets feed items aggregated from local database.
///
@@ -34,6 +40,51 @@ class FeedDataProvider {
/// Items from hidden collections or associated with deleted files are filtered out.
Future<List<FeedItem>> getFeedItems({
int limit = 50,
+ bool includeSharedPhotos = true,
+ bool verifyFileExistence = true,
+ }) async {
+ final requestKey = '$limit|$includeSharedPhotos|$verifyFileExistence';
+ final nowMs = DateTime.now().millisecondsSinceEpoch;
+
+ if (_inFlightFeedItemsFuture != null &&
+ _inFlightFeedItemsKey == requestKey) {
+ return _inFlightFeedItemsFuture!;
+ }
+
+ final lastAtMs = _lastFeedItemsAtMs;
+ if (_lastFeedItems != null &&
+ _lastFeedItemsKey == requestKey &&
+ lastAtMs != null &&
+ (nowMs - lastAtMs) <= _kFeedItemsCacheTtlMs) {
+ return List<FeedItem>.from(_lastFeedItems!);
+ }
+
+ final future = _computeFeedItems(
+ limit: limit,
+ includeSharedPhotos: includeSharedPhotos,
+ verifyFileExistence: verifyFileExistence,
+ );
+ _inFlightFeedItemsFuture = future;
+ _inFlightFeedItemsKey = requestKey;
+
+ try {
+ final items = await future;
+ _lastFeedItems = List<FeedItem>.from(items);
+ _lastFeedItemsKey = requestKey;
+ _lastFeedItemsAtMs = DateTime.now().millisecondsSinceEpoch;
+ return items;
+ } finally {
+ if (identical(_inFlightFeedItemsFuture, future)) {
+ _inFlightFeedItemsFuture = null;
+ _inFlightFeedItemsKey = null;
+ }
+ }
+ }
+
+ Future<List<FeedItem>> _computeFeedItems({
+ required int limit,
+ required bool includeSharedPhotos,
+ required bool verifyFileExistence,
}) async {
final userID = Configuration.instance.getUserID();
if (userID == null) {
@@ -111,10 +162,19 @@ class FeedDataProvider {
);
// Aggregate shared photos (files added by others to user's collections)
- feedItems.addAll(await _getSharedPhotoFeedItems(userID: userID));
+ if (includeSharedPhotos) {
+ feedItems.addAll(
+ await _getSharedPhotoFeedItems(
+ userID: userID,
+ limit: limit,
+ ),
+ );
+ }
// Filter out items where the associated file doesn't exist or collection is hidden
- final validItems = await _filterFeedItems(feedItems);
+ final validItems = verifyFileExistence
+ ? await _filterFeedItems(feedItems)
+ : _filterHiddenCollectionsOnly(feedItems);
// Sort by most recent activity
validItems.sort((a, b) => b.createdAt.compareTo(a.createdAt));
@@ -129,22 +189,42 @@ class FeedDataProvider {
/// Gets a single feed item for preview display.
Future<FeedItem?> getLatestFeedItem() async {
- final items = await getFeedItems(limit: 1);
+ final items = await getFeedItems(
+ limit: 1,
+ includeSharedPhotos: false,
+ verifyFileExistence: false,
+ );
return items.isNotEmpty ? items.first : null;
}
/// Triggers background sync for all shared collections.
- Future<void> syncAllSharedCollections() async {
+ Future<bool> syncAllSharedCollections() async {
try {
- await SocialSyncService.instance.syncAllSharedCollections();
+ final hasNewData =
+ await SocialSyncService.instance.syncAllSharedCollections();
await SocialNotificationCoordinator.instance.notifyAfterSocialSync(
trigger: SocialNotificationTrigger.feedRefresh,
);
+ return hasNewData;
} catch (e) {
_logger.warning('Failed to sync shared collections', e);
+ return false;
}
}
+ List<FeedItem> _filterHiddenCollectionsOnly(
+ List<FeedItem> items,
+ ) {
+ if (items.isEmpty) {
+ return items;
+ }
+ final hiddenCollectionIds =
+ CollectionsService.instance.getHiddenCollectionIds();
+ return items
+ .where((item) => !hiddenCollectionIds.contains(item.collectionID))
+ .toList();
+ }
+
/// Aggregates reactions on files by (collectionID, fileID).
List<FeedItem> _aggregateReactionsByFile(
List<Reaction> reactions,
@@ -353,7 +433,6 @@ class FeedDataProvider {
if (!flagService.internalUser) {
return [];
}
-
final sharedPhotoFeedCutoffTime =
await localSettings.getOrCreateSharedPhotoFeedCutoffTime();
@@ -476,8 +555,8 @@ class FeedDataProvider {
/// - The associated file no longer exists in FilesDB
/// - The collection is hidden
///
- /// For sharedPhoto items, filters out deleted files from sharedFileIDs
- /// and only removes the item if ALL shared files are deleted.
+ /// For sharedPhoto items, validates only the representative fileID.
+ /// The underlying shared list comes from live files-table rows.
Future<List<FeedItem>> _filterFeedItems(
List<FeedItem> items,
) async {
@@ -487,15 +566,10 @@ class FeedDataProvider {
final hiddenCollectionIds =
CollectionsService.instance.getHiddenCollectionIds();
- // Collect unique (fileID, collectionID) pairs - include all sharedFileIDs
+ // Collect unique (fileID, collectionID) pairs
final filesToCheck = <(int, int)>{};
for (final item in items) {
- if (item.type == FeedItemType.sharedPhoto && item.sharedFileIDs != null) {
- // For shared items, check all files in the list
- for (final fileID in item.sharedFileIDs!) {
- filesToCheck.add((fileID, item.collectionID));
- }
- } else if (item.fileID != null) {
+ if (item.fileID != null) {
filesToCheck.add((item.fileID!, item.collectionID));
}
}
@@ -508,8 +582,8 @@ class FeedDataProvider {
}
// Check which files exist using batch query (single DB call)
- final existingFiles =
- await FilesDB.instance.getExistingFileKeys(filesToCheck);
+ final existingFilesByCollection =
+ await FilesDB.instance.getExistingFileIDsByCollection(filesToCheck);
// Filter and transform items
final result = <FeedItem>[];
@@ -519,27 +593,6 @@ class FeedDataProvider {
continue;
}
- // Handle sharedPhoto items specially
- if (item.type == FeedItemType.sharedPhoto && item.sharedFileIDs != null) {
- // Filter to only existing files
- final existingSharedFiles = item.sharedFileIDs!.where((fileID) {
- final key = '${item.collectionID}_$fileID';
- return existingFiles.contains(key);
- }).toList();
-
- // Only keep item if at least one file still exists
- if (existingSharedFiles.isNotEmpty) {
- // Update item with filtered sharedFileIDs and new fileID
- result.add(
- item.copyWith(
- sharedFileIDs: existingSharedFiles,
- fileID: existingSharedFiles.first,
- ),
- );
- }
- continue;
- }
-
// Items without fileID (collection-level activity) are kept
if (item.fileID == null) {
result.add(item);
@@ -547,8 +600,8 @@ class FeedDataProvider {
}
// Exclude items where file no longer exists
- final key = '${item.collectionID}_${item.fileID}';
- if (existingFiles.contains(key)) {
+ final existingInCollection = existingFilesByCollection[item.collectionID];
+ if (existingInCollection?.contains(item.fileID) ?? false) {
result.add(item);
}
}
diff --git a/mobile/apps/photos/lib/services/social_sync_service.dart b/mobile/apps/photos/lib/services/social_sync_service.dart
index 012650c8ad..2dc560423b 100644
--- a/mobile/apps/photos/lib/services/social_sync_service.dart
+++ b/mobile/apps/photos/lib/services/social_sync_service.dart
@@ -158,14 +158,14 @@ class SocialSyncService {
/// Called during background sync to keep social data up to date.
/// Uses the /comments-reactions/updated-at endpoint to determine which
/// collections actually need syncing, avoiding unnecessary API calls.
- Future<void> syncAllSharedCollections() async {
+ Future<bool> syncAllSharedCollections() async {
if (!flagService.isSocialEnabled) {
_logger.info('Social features disabled, skipping sync');
- return;
+ return false;
}
if (_isSyncing) {
_logger.info('Sync already in progress, skipping');
- return;
+ return false;
}
_isSyncing = true;
@@ -173,7 +173,7 @@ class SocialSyncService {
final userID = Configuration.instance.getUserID();
if (userID == null) {
_logger.info('User not logged in, skipping social sync');
- return;
+ return false;
}
// Get latest update timestamps from server
@@ -181,7 +181,7 @@ class SocialSyncService {
if (latestUpdates.updates.isEmpty) {
_logger.info('No collections have social activity');
- return;
+ return false;
}
_logger.info(
@@ -255,8 +255,10 @@ class SocialSyncService {
),
);
}
+ return syncedCount > 0;
} catch (e) {
_logger.severe('Failed to fetch latest updates', e);
+ return false;
} finally {
_isSyncing = false;
}
diff --git a/mobile/apps/photos/lib/ui/social/feed_screen.dart b/mobile/apps/photos/lib/ui/social/feed_screen.dart
index ad0ea0c1bb..4c6de73bd0 100644
--- a/mobile/apps/photos/lib/ui/social/feed_screen.dart
+++ b/mobile/apps/photos/lib/ui/social/feed_screen.dart
@@ -145,9 +145,11 @@ class _FeedScreenState extends State<FeedScreen> {
Future<void> _syncAndRefresh() async {
try {
- await FeedDataProvider.instance.syncAllSharedCollections();
+ final hasNewSocialData =
+ await FeedDataProvider.instance.syncAllSharedCollections();
if (!mounted) return;
+ if (!hasNewSocialData) return;
// Reload feed items after sync
final freshItems =