π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Prune Photos model and service comments
Manav Rathib541cc3584af
diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dartindex 4ddb3730f2..91628775a3 100644--- a/mobile/apps/photos/lib/db/ml/db.dart+++ b/mobile/apps/photos/lib/db/ml/db.dart@@ -32,27 +32,12 @@ import "package:photos/utils/ml_util.dart";import 'package:sqlite_async/sqlite_async.dart';import "package:synchronized/synchronized.dart";-/// Stores all data for the ML related features. The database can be accessed by `MLDataDB.instance.database`.-///-/// This includes:-/// [facesTable] - Stores all the detected faces and its embeddings in the images.-/// [faceClustersTable] - Stores all the mappings from the faces (faceID) to the clusters (clusterID).-/// [clusterPersonTable] - Stores all the clusters that are mapped to a certain person.-/// [clusterSummaryTable] - Stores a summary of each cluster, containg the mean embedding and the number of faces in the cluster.-/// [notPersonFeedback] - Stores the clusters that are confirmed not to belong to a certain person by the user-///-/// [clipTable] - Stores the embeddings of the CLIP model-/// [fileDataTable] - Stores data about the files that are already processed by the ML models-///-/// [faceCacheTable] - Stores a all the mappings from personID or clusterID to the faceID that has been used as cover face.class MLDataDB with SqlDbBase implements IMLDataDB<int> {static final Logger _logger = Logger("MLDataDB");static const int _maxSqlBindParamsPerQuery = 10000;static Logger get logger => _logger;- // static const _databaseVersion = 1;-final String _databaseName;final ClipVectorDB _clipVectorDB;final ClusterCentroidVectorDB _clusterCentroidVectorDB;@@ -111,7 +96,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {..._defaultMigrationScripts,];- // only have a single app-wide reference to the databaseFuture<SqliteDatabase>? _sqliteAsyncDBFuture;Future<SqliteDatabase> get asyncDB async {@@ -146,9 +130,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- // bulkInsertFaces inserts the faces in the database in batches of 1000.- // This is done to avoid the error "too many SQL variables" when inserting- // a large number of faces.+ // Batch to stay below SQLite's bind-variable limit.@overrideFuture<void> bulkInsertFaces(List<Face> faces) async {final db = await asyncDB;@@ -308,7 +290,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- /// Store pet face embeddings into PetVectorDB after SQLite insert.Future<void> storePetFaceEmbeddings(List<DBPetFace> dbPetFaces,List<PetFaceResult> petFaces,@@ -320,7 +301,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}try {final db = await asyncDB;- // Group by speciesfinal bySpecies = <int, List<(DBPetFace, PetFaceResult)>>{};for (int i = 0; i < dbPetFaces.length; i++) {final species = petFaces[i].species;@@ -371,7 +351,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- /// Store pet body embeddings into PetVectorDB after SQLite insert.Future<void> storePetBodyEmbeddings(List<DBPetBody> dbPetBodies,List<PetBodyResult> petBodies,@@ -383,7 +362,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}try {final db = await asyncDB;- // Group by species (0 = dog, 1 = cat)final bySpecies = <int, List<(DBPetBody, PetBodyResult)>>{};for (int i = 0; i < dbPetBodies.length; i++) {final species = dbPetBodies[i].species;@@ -458,7 +436,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- /// Returns a map of fileID to the indexed ML version@overrideFuture<Map<int, int>> faceIndexedFileIds({int minimumMlVersion = faceMlVersion,@@ -542,7 +519,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {@overrideFuture<Set<String>> getPersonIgnoredClusters(String personID) async {final db = await asyncDB;- // find out clusterIds that are assigned to other persons using the clusters tablefinal List<Map<String, dynamic>> otherPersonMaps = await db.getAll('SELECT $clusterIDColumn FROM $clusterPersonTable WHERE $personIdColumn != ? AND $personIdColumn IS NOT NULL',[personID],@@ -609,7 +585,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {await db.execute(deleteFileDataTable);await _clipVectorDB.deleteIndexFile();await _clusterCentroidVectorDB.deleteIndexFile();- // Pet tablesawait db.execute(deletePetFacesTable);await db.execute(deletePetBodiesTable);await db.execute(deletePetFaceVectorIdMappingTable);@@ -698,7 +673,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {String? avatarFaceId,String? clusterID,}) async {- // read person from dbfinal db = await asyncDB;if (personID != null) {final List<int> fileId = [recentFileID];@@ -931,7 +905,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {return faceIdsResult.map((e) => e[faceIDColumn] as String).toList();}- // Get Map of personID to Map of clusterID to faceIDs@overrideFuture<Map<String, Map<String, Set<String>>>>getPersonToClusterIdToFaceIds() async {@@ -1043,11 +1016,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {JOIN $faceClustersTable ON $facesTable.$faceIDColumn = $faceClustersTable.$faceIDColumnWHERE $faceClustersTable.$clusterIDColumn = ?''';- // const String query2 = '''- // SELECT $faceBlur- // FROM $facesTable- // WHERE $faceIDColumn IN (SELECT $faceIDColumn FROM $faceClustersTable WHERE $clusterIDColumn = ?)- // ''';final List<Map<String, dynamic>> maps = await db.getAll(query, [clusterID]);return maps.map((e) => e[faceBlur] as double).toSet();}@@ -1159,14 +1127,12 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final List<FaceDbInfoForClustering> result = <FaceDbInfoForClustering>[];while (true) {- // Query a batch of rowsfinal List<Map<String, dynamic>> maps = await db.getAll('SELECT $faceIDColumn, $embeddingColumn, $faceScore, $faceBlur, $isSideways FROM $facesTable'' WHERE $faceScore > $kMinimumQualityFaceScore AND $faceBlur > $kLaplacianHardThreshold'' ORDER BY $faceIDColumn'' DESC LIMIT $batchSize OFFSET $offset',);- // Break the loop if no more rowsif (maps.isEmpty) {break;}@@ -1207,13 +1173,11 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {_logger.info('reading face embeddings for ${faceIDs.length} faces');final db = await asyncDB;- // Define the batch sizeconst batchSize = 10000;int offset = 0;final Map<String, Uint8List> result = {};while (true) {- // Query a batch of rowsfinal String query ='''SELECT $faceIDColumn, $embeddingColumn@@ -1223,7 +1187,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {LIMIT $batchSize OFFSET $offset''';final List<Map<String, dynamic>> maps = await db.getAll(query);- // Break the loop if no more rowsif (maps.isEmpty) {break;}@@ -1332,8 +1295,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {return maps.first['count'] as int;}- /// WARNING: Only use this method if the person has just been created.- /// Otherwise, use [ClusterFeedbackService.instance.addClusterToExistingPerson] instead.+ // Existing people must go through ClusterFeedbackService instead.@overrideFuture<void> assignClusterToPerson({required String personID,@@ -1423,7 +1385,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {await db.execute(sql, [personID, clusterID]);}- // for a given personID, return a map of clusterID to fileIDs using join query@overrideFuture<Map<int, Set<String>>> getFileIdToClusterIDSet(String personID) {final db = asyncDB;@@ -1657,7 +1618,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- /// Returns a map of clusterID to (avg embedding, count)@overrideFuture<Map<String, (Uint8List, int)>> getAllClusterSummary([int? minClusterSize,@@ -1710,7 +1670,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {return result;}- /// WARNING: This will delete ALL data in the database! Only use this for debug/testing purposes!@overrideFuture<void> dropClustersAndPersonTable({bool faces = false}) async {try {@@ -1750,17 +1709,14 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- /// WARNING: This will delete ALL data in the tables! Only use this for debug/testing purposes!@overrideFuture<void> dropFacesFeedbackTables() async {try {final db = await asyncDB;- // Drop the tablesawait db.execute(deleteClusterPersonTable);await db.execute(deleteNotPersonFeedbackTable);- // Recreate the tablesawait db.execute(createClusterPersonTable);await db.execute(createNotPersonFeedbackTable);} catch (e) {@@ -1837,10 +1793,8 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {'SELECT $fileIDColumn, $embeddingColumn FROM $clipTable',);- // Convert rows to vectorsfinal List<EmbeddingVector> embeddings = [];for (final result in results) {- // Convert to EmbeddingVectorfinal embedding = EmbeddingVector(fileID: result[fileIDColumn],embedding: Float32List.view(result[embeddingColumn].buffer),@@ -2159,7 +2113,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}_logger.info("Starting ClipVectorDB migration");- // Get total count first to track progress_logger.info("Getting total count of clip embeddings");final db = await asyncDB;final countResult = await db.getAll(@@ -2194,7 +2147,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {const String migrationKey = "clip_vector_db_migration_in_progress";final stopwatch = Stopwatch()..start();try {- // Make sure no other heavy compute is runningcomputeController.blockCompute(blocker: migrationKey);while (true) {whileCount++;@@ -2289,7 +2241,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {rethrow;} finally {stopwatch.stop();- // Make sure compute can run againcomputeController.unblockCompute(blocker: migrationKey);}});@@ -2413,7 +2364,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- // Get indexed FileIDs@overrideFuture<Map<int, int>> clipIndexedFileWithVersion() async {final db = await asyncDB;@@ -2521,7 +2471,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {fileIDs,);- // Group face vector IDs by species for targeted vector DB deletion.final faceVidsBySpecies = <int, List<int>>{};final faceIdsToRemove = <String>[];for (final row in faceRows) {@@ -2535,7 +2484,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- // Group body vector IDs by species.final bodyVidsBySpecies = <int, List<int>>{};final bodyIdsToRemove = <String>[];for (final row in bodyRows) {@@ -2549,7 +2497,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- // Delete from usearch vector indexes.for (final entry in faceVidsBySpecies.entries) {try {final vdb = PetVectorDB.forModel(@@ -2575,7 +2522,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- // Delete mapping table entries and detection rows atomically.await db.writeTransaction((tx) async {if (faceIdsToRemove.isNotEmpty) {final placeholders = List.filled(faceIdsToRemove.length, '?').join(',');@@ -2652,7 +2598,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {Bus.instance.fire(EmbeddingUpdatedEvent());}- /// WARNING: don't confuse this with [putClip]. If you're not sure, use [putClip]+ // This is the repeated-query cache, not the per-file CLIP store.Future<void> putRepeatedTextEmbeddingCache(String query,List<double> embedding,@@ -2671,7 +2617,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {);}- /// WARNING: don't confuse this with [getAllClipVectors]. If you're not sure, use [getAllClipVectors]+ // This is the repeated-query cache, not the per-file CLIP store.Future<List<double>?> getRepeatedTextEmbeddingCache(String query) async {final db = await asyncDB;final results = await db.getAll(@@ -2686,7 +2632,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final threeMonthsAgo =DateTime.now().millisecondsSinceEpoch - (90 * 24 * 60 * 60 * 1000);- // Find first valid entryfor (final result in results) {if (result[mlVersionColumn] == clipMlVersion &&result[createdAtColumn] as int > threeMonthsAgo) {@@ -2694,7 +2639,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}}- // No valid entry found, clean upawait db.execute('DELETE FROM $textEmbeddingsCacheTable WHERE $textQueryColumn = ?',[query],@@ -2744,8 +2688,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {];}- /// WARNING: Better to use the similarly named [putFaceIdCachedForPersonOrCluster]- /// method from face_thumbnail_cache instead!+ // Prefer the face_thumbnail_cache helper with the same name.Future<void> putFaceIdCachedForPersonOrCluster(String personOrClusterId,String faceID,diff --git a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart b/mobile/apps/photos/lib/db/ml/pet_vector_db.dartindex c2a86a6f9f..4782360a6e 100644--- a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart+++ b/mobile/apps/photos/lib/db/ml/pet_vector_db.dart@@ -12,15 +12,7 @@ import "package:photos/src/rust/api/usearch_api.dart";import "package:sqlite_async/sqlite_async.dart";import "package:synchronized/synchronized.dart";-/// Vector database for pet embeddings.-///-/// **Each embedding model gets its own vector space** because embeddings from-/// different models (dog face BYOL vs cat body, etc.) are not comparable.-/// Face embeddings are 128-d, body embeddings are 192-d.-///-/// Uses usearch (via Rust FFI) for approximate nearest-neighbor search.-/// Pet face IDs are strings, so they are mapped to auto-incrementing integers-/// via [petFaceVectorIdMappingTable] before being stored as usearch keys.+// Each model needs its own vector space; their embeddings are not comparable.class PetVectorDB {static final Logger _logger = Logger("PetVectorDB");@@ -32,11 +24,8 @@ class PetVectorDB {static Logger get logger => _logger;- // Private constructor for named instancesPetVectorDB._named(this._databaseName, this._embeddingDimension);- // ββ Online vector spaces ββ-static final dogFace = PetVectorDB._named("ente.ml.vectordb.pet.dog_face.usearch",BigInt.from(faceDimension),@@ -57,8 +46,6 @@ class PetVectorDB {BigInt.from(bodyDimension),);- // ββ Local-gallery vector spaces ββ-static final localGalleryDogFace = PetVectorDB._named("ente.ml.offline.vectordb.pet.dog_face.usearch",BigInt.from(faceDimension),@@ -79,7 +66,6 @@ class PetVectorDB {BigInt.from(bodyDimension),);- /// All online vector DB instances for iteration.static final List<PetVectorDB> allInstances = [dogFace,catFace,@@ -87,7 +73,6 @@ class PetVectorDB {catBody,];- /// All local-gallery vector DB instances for iteration.static final List<PetVectorDB> allLocalGalleryInstances = [localGalleryDogFace,localGalleryCatFace,@@ -95,9 +80,7 @@ class PetVectorDB {localGalleryCatBody,];- /// Get the correct vector DB for a species + embedding type.- /// [species]: 0 = dog, 1 = cat- /// [isFace]: true = face embedding, false = body embedding+ // Species is 0 for dogs and 1 for cats.static PetVectorDB forModel({required int species,required bool isFace,@@ -152,10 +135,8 @@ class PetVectorDB {return vectorDB;}- // ββ ID Mapping (pet_face_id string β integer for usearch) ββ+ // usearch needs integer keys; faces and bodies use separate ID spaces.- /// Get or create integer vector IDs for the given pet face IDs.- /// Returns a map of petFaceId β integer vectorId.Future<Map<String, int>> getPetFaceVectorIdMap(Iterable<String> petFaceIds, {required SqliteDatabase db,@@ -194,8 +175,6 @@ class PetVectorDB {return result;}- /// Get or create integer vector IDs for body/object embeddings.- /// Uses [petBodyVectorIdMappingTable] β separate ID space from face embeddings.Future<Map<String, int>> getObjectVectorIdMap(Iterable<String> objectIds, {required SqliteDatabase db,@@ -234,8 +213,6 @@ class PetVectorDB {return result;}- // ββ Vector Operations ββ-Future<void> _runWriteOperation(Future<void> Function(VectorDb db) operation,) async {@@ -245,7 +222,6 @@ class PetVectorDB {});}- /// Insert a single pet face embedding into the vector DB.Future<void> insertEmbedding({required int vectorId,required List<double> embedding,@@ -260,7 +236,6 @@ class PetVectorDB {}}- /// Bulk insert pet face embeddings.Future<void> bulkInsertEmbeddings({required List<int> vectorIds,required List<Float32List> embeddings,@@ -279,7 +254,6 @@ class PetVectorDB {}}- /// Get embeddings by their vector IDs.Future<List<Float32List>> getEmbeddings(List<int> vectorIds) async {final db = await _vectorDB;try {@@ -291,7 +265,6 @@ class PetVectorDB {}}- /// Delete embeddings by their vector IDs.Future<void> deleteEmbeddings(List<int> vectorIds) async {if (vectorIds.isEmpty) {return;@@ -312,7 +285,6 @@ class PetVectorDB {}}- /// Search for the closest pet face embeddings to a query.Future<(Uint64List, Float32List)> searchClosestVectors(List<double> query,int count, {@@ -331,7 +303,6 @@ class PetVectorDB {}}- /// Delete all embeddings and reset the index.Future<void> deleteAllEmbeddings() async {try {await _runWriteOperation((db) async {diff --git a/mobile/apps/photos/lib/db/ml/schema.dart b/mobile/apps/photos/lib/db/ml/schema.dartindex 39ed4f0085..e7220042e2 100644--- a/mobile/apps/photos/lib/db/ml/schema.dart+++ b/mobile/apps/photos/lib/db/ml/schema.dart@@ -1,4 +1,3 @@-// Faces Table Fields & Schema Queriesimport 'package:photos/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart';const facesTable = 'faces';@@ -36,12 +35,8 @@ const createFacesTable =''';const deleteFacesTable = 'DELETE FROM $facesTable';-// End of Faces Table Fields & Schema Queries--//##region Face Clusters Table Fields & Schema Queriesconst faceClustersTable = 'face_clusters';-// fcClusterId & fcFaceId are the primary keys and fcClusterId is a foreign key to faces tableconst createFaceClustersTable ='''CREATE TABLE IF NOT EXISTS $faceClustersTable (@@ -50,13 +45,9 @@ CREATE TABLE IF NOT EXISTS $faceClustersTable (PRIMARY KEY($faceIDColumn));''';-// -- Creating a non-unique index on clusterID for query optimizationconst fcClusterIDIndex ='''CREATE INDEX IF NOT EXISTS idx_fcClusterID ON $faceClustersTable($clusterIDColumn);''';const deleteFaceClustersTable = 'DELETE FROM $faceClustersTable';-//##endregion--// Clusters Table Fields & Schema Queriesconst clusterPersonTable = 'cluster_person';const createClusterPersonTable =@@ -68,9 +59,7 @@ CREATE TABLE IF NOT EXISTS $clusterPersonTable ();''';const deleteClusterPersonTable = 'DELETE FROM $clusterPersonTable';-// End Clusters Table Fields & Schema Queries-/// Cluster Summary Table Fields & Schema Queriesconst clusterSummaryTable = 'cluster_summary';const avgColumn = 'avg';const countColumn = 'count';@@ -86,9 +75,6 @@ CREATE TABLE IF NOT EXISTS $clusterSummaryTable (const deleteClusterSummaryTable = 'DELETE FROM $clusterSummaryTable';-/// End Cluster Summary Table Fields & Schema Queries--/// Cluster Centroid Vector ID Mapping Table Fields & Schema Queriesconst clusterCentroidVectorIdMappingTable = 'cluster_centroid_vector_id_map';const clusterCentroidVectorIdColumn = 'cluster_vector_id';@@ -103,9 +89,6 @@ CREATE TABLE IF NOT EXISTS $clusterCentroidVectorIdMappingTable (const deleteClusterCentroidVectorIdMappingTable ='DELETE FROM $clusterCentroidVectorIdMappingTable';-/// End Cluster Centroid Vector ID Mapping Table Fields & Schema Queries--/// notPersonFeedback Table Fields & Schema Queriesconst notPersonFeedback = 'not_person_feedback';const createNotPersonFeedbackTable =@@ -117,9 +100,6 @@ CREATE TABLE IF NOT EXISTS $notPersonFeedback ();''';const deleteNotPersonFeedbackTable = 'DELETE FROM $notPersonFeedback';-// End Clusters Table Fields & Schema Queries--// ## CLIP EMBEDDINGS TABLEconst clipTable = 'clip';const createClipEmbeddingsTable =@@ -151,7 +131,6 @@ CREATE TABLE IF NOT EXISTS $fileDataTable (const deleteFileDataTable = 'DELETE FROM $fileDataTable';-// ## FACE CACHE TABLEconst faceCacheTable = 'face_cache';const createFaceCacheTable =@@ -165,7 +144,6 @@ CREATE TABLE IF NOT EXISTS $faceCacheTable (const deleteFaceCacheTable = 'DELETE FROM $faceCacheTable';-// ## TEXT EMBEDDINGS CACHE TABLEconst textEmbeddingsCacheTable = 'text_embeddings_cache';const createTextEmbeddingsCacheTable =@@ -181,7 +159,6 @@ CREATE TABLE IF NOT EXISTS $textEmbeddingsCacheTable (const deleteTextEmbeddingsCacheTable = 'DELETE FROM $textEmbeddingsCacheTable';-// ## OFFLINE FILE KEY MAP TABLEconst offlineFileKeyMapTable = 'offline_file_key_map';const offlineFileKeyLocalIdColumn = 'local_id';const offlineFileKeyIntIdColumn = 'local_int_id';@@ -194,9 +171,6 @@ CREATE TABLE IF NOT EXISTS $offlineFileKeyMapTable ();''';-// ββ PET RECOGNITION TABLES βββββββββββββββββββββββββββββββββββββββββββββ--// Shared column namesconst petFaceIDColumn = 'pet_face_id';const petBodyIDColumn = 'pet_body_id';const speciesColumn = 'species';@@ -204,8 +178,6 @@ const detectionColumn = 'detection';const faceVectorIdColumn = 'face_vector_id';const bodyVectorIdColumn = 'body_vector_id';-// ββ Pet Faces Table ββ-const petFacesTable = 'pet_faces';const createPetFacesTable =@@ -225,11 +197,8 @@ const createPetFacesTable =const deletePetFacesTable = 'DELETE FROM $petFacesTable';-// ββ Pet Bodies Table ββ-const petBodiesTable = 'pet_bodies';-// Alias so pet-body code doesn't reference the face-specific constant name.-// The underlying SQL column is the same ('score').+// Both tables use the SQL column "score".const bodyScore = faceScore;const createPetBodiesTable =@@ -249,9 +218,6 @@ const createPetBodiesTable =const deletePetBodiesTable = 'DELETE FROM $petBodiesTable';-// ββ Vector ID Mapping Tables ββ--/// Maps pet_face_id (string) β integer for face usearch indexconst petFaceVectorIdMappingTable = 'pet_face_vector_id_map';const petFaceVectorIdColumn = 'pet_face_vector_id';@@ -266,7 +232,6 @@ CREATE TABLE IF NOT EXISTS $petFaceVectorIdMappingTable (const deletePetFaceVectorIdMappingTable ='DELETE FROM $petFaceVectorIdMappingTable';-/// Maps pet_body_id (string) β integer for body usearch indexconst petBodyVectorIdMappingTable = 'pet_body_vector_id_map';const petBodyVectorIdColumn = 'pet_body_vector_id';diff --git a/mobile/apps/photos/lib/events/local_photos_updated_event.dart b/mobile/apps/photos/lib/events/local_photos_updated_event.dartindex c275168ea8..5b8e460f2a 100644--- a/mobile/apps/photos/lib/events/local_photos_updated_event.dart+++ b/mobile/apps/photos/lib/events/local_photos_updated_event.dart@@ -1,8 +1,7 @@import 'package:photos/events/files_updated_event.dart';class LocalPhotosUpdatedEvent extends FilesUpdatedEvent {- /// True when newly discovered local files include at least one- /// created within the last 7 days. Used to trigger priority refresh.+ // "Recent" means created within the last seven days.final bool hasRecentNewLocalDiscovery;LocalPhotosUpdatedEvent(diff --git a/mobile/apps/photos/lib/events/social_data_updated_event.dart b/mobile/apps/photos/lib/events/social_data_updated_event.dartindex e21f2d2783..f62f169c7f 100644--- a/mobile/apps/photos/lib/events/social_data_updated_event.dart+++ b/mobile/apps/photos/lib/events/social_data_updated_event.dart@@ -1,16 +1,8 @@import "package:photos/events/event.dart";-/// Event fired when social data (comments, reactions) has been synced.-///-/// Used to notify UI components that they should refresh their display.class SocialDataUpdatedEvent extends Event {- /// The collection ID that was synced, or null if multiple collections were synced.final int? collectionID;-- /// Whether new comments were synced.final bool hasNewComments;-- /// Whether new reactions were synced.final bool hasNewReactions;SocialDataUpdatedEvent({diff --git a/mobile/apps/photos/lib/extensions/logger_extension.dart b/mobile/apps/photos/lib/extensions/logger_extension.dartindex 119cfe3710..b0afdead08 100644--- a/mobile/apps/photos/lib/extensions/logger_extension.dart+++ b/mobile/apps/photos/lib/extensions/logger_extension.dart@@ -2,17 +2,12 @@ import "package:logging/logging.dart";import "package:photos/service_locator.dart";extension LoggerExtension on Logger {- /// Logs an info message only if the user is an internal user.- ///- /// This is useful for debug logging that should only be visible to internal- /// users during development and testing.void internalInfo(String message) {if (flagService.internalUser) {info(message);}}- /// Logs a warning message only if the user is an internal user.void internalWarning(String message, [Object? error,@@ -23,7 +18,6 @@ extension LoggerExtension on Logger {}}- /// Logs a severe message only if the user is an internal user.void internalSevere(String message, [Object? error, StackTrace? stackTrace]) {if (flagService.internalUser) {severe(message, error, stackTrace);diff --git a/mobile/apps/photos/lib/extensions/ml_linalg_extensions.dart b/mobile/apps/photos/lib/extensions/ml_linalg_extensions.dartindex e4d9d5fc8d..71387a3afd 100644--- a/mobile/apps/photos/lib/extensions/ml_linalg_extensions.dart+++ b/mobile/apps/photos/lib/extensions/ml_linalg_extensions.dart@@ -126,7 +126,8 @@ extension MatrixCalculations on Matrix {}}- /// Computes the singular value decomposition of a matrix, using https://lucidar.me/en/mathematics/singular-value-decomposition-of-a-2x2-matrix/ as reference, but with slightly different signs for the second columns of U and V+ // Reference: https://lucidar.me/en/mathematics/singular-value-decomposition-of-a-2x2-matrix/+ // The signs of the second columns of U and V differ.Map<String, dynamic> svd() {if (rowCount != 2 || columnCount != 2) {throw Exception('Matrix must be 2x2');@@ -136,7 +137,6 @@ extension MatrixCalculations on Matrix {final c = this[1][0];final d = this[1][1];- // Computation of U matrixfinal tempCalc = a * a + b * b - c * c - d * d;final theta = 0.5 * math.atan2(2 * a * c + 2 * b * d, tempCalc);final U = Matrix.fromList([@@ -144,7 +144,6 @@ extension MatrixCalculations on Matrix {[math.sin(theta), -math.cos(theta)],]);- // Computation of S matrix// ignore: non_constant_identifier_namesfinal S1 = a * a + b * b + c * c + d * d;// ignore: non_constant_identifier_names@@ -155,7 +154,6 @@ extension MatrixCalculations on Matrix {final sigma2 = math.sqrt((S1 - S2) / 2);final S = Vector.fromList([sigma1, sigma2]);- // Computation of V matrixfinal tempCalc2 = a * a - b * b + c * c - d * d;final phi = 0.5 * math.atan2(2 * a * b + 2 * c * d, tempCalc2);final s11 =diff --git a/mobile/apps/photos/lib/models/api/collection/user.dart b/mobile/apps/photos/lib/models/api/collection/user.dartindex 9b6ac232e1..fd44f83d92 100644--- a/mobile/apps/photos/lib/models/api/collection/user.dart+++ b/mobile/apps/photos/lib/models/api/collection/user.dart@@ -4,8 +4,6 @@ import "dart:convert";class User {final int id;String email;-- /// Local-only display name for anonymous social actors; never serialized.final String? label;String? role;@@ -43,7 +41,5 @@ class UserSuggestion {final int? userID;final String email;-- /// Local-only display label; see [User.label].final String? label;}diff --git a/mobile/apps/photos/lib/models/button_result.dart b/mobile/apps/photos/lib/models/button_result.dartindex a9705f18d6..23ea461ffc 100644--- a/mobile/apps/photos/lib/models/button_result.dart+++ b/mobile/apps/photos/lib/models/button_result.dart@@ -1,10 +1,6 @@import 'package:photos/ui/components/buttons/button_widget.dart';class ButtonResult {- ///action can be null when action for the button that is returned when popping- ///the widget (dialog, actionSheet) which uses a ButtonWidget isn't- ///relevant/useful and so is not assigned a value when an instance of- ///ButtonWidget is created.final ButtonAction? action;final Exception? exception;ButtonResult([this.action, this.exception]);diff --git a/mobile/apps/photos/lib/models/collection/collection.dart b/mobile/apps/photos/lib/models/collection/collection.dartindex bd2487baf9..0da75bd934 100644--- a/mobile/apps/photos/lib/models/collection/collection.dart+++ b/mobile/apps/photos/lib/models/collection/collection.dart@@ -14,7 +14,7 @@ class Collection {final String encryptedKey;final String? keyDecryptionNonce;- /// WARNING: use collectionName instead of name! Name is deprecated but can't be removed because of old accounts.+ // Deprecated but required for old accounts. Use collectionName.String? name;// encryptedName & nameDecryptionNonce will be null for collections@@ -121,8 +121,7 @@ class Collection {return (sharedMagicMetadata.order ?? 0) != 0;}- // hasLink returns true if there's any link attached to the collection- // including expired links+ // Includes expired links.bool get hasLink => publicURLs.isNotEmpty;bool get hasCover => (pubMagicMetadata.coverID ?? 0) > 0;@@ -132,7 +131,6 @@ class Collection {return description == null || description.isEmpty ? null : description;}- // hasSharees returns true if the collection is shared with other ente usersbool get hasSharees => sharees.isNotEmpty;bool get isPinned => (magicMetadata.order ?? 0) != 0;@@ -143,10 +141,8 @@ class Collection {}final userID = Configuration.instance.getUserID();if (userID != null && isOwner(userID)) {- // Owner: check owner's magic metadatareturn mMdVersion > 0 && magicMetadata.visibility == hiddenVisibility;} else {- // Sharee: check sharee's magic metadatareturn hasShareeHidden();}}@@ -231,9 +227,7 @@ class Collection {return CollectionParticipantRole.unknown;}- // canLinkToDevicePath returns true if the collection can be linked to local- // device album based on path. The path is nothing but the name of the device- // album.+ // The encrypted path names the linked device album.bool canLinkToDevicePath(int userID) {return isOwner(userID) && !isDeleted && attributes.encryptedPath != null;}diff --git a/mobile/apps/photos/lib/models/ffmpeg/ffprobe_props.dart b/mobile/apps/photos/lib/models/ffmpeg/ffprobe_props.dartindex a15ea2474d..968b975963 100644--- a/mobile/apps/photos/lib/models/ffmpeg/ffprobe_props.dart+++ b/mobile/apps/photos/lib/models/ffmpeg/ffprobe_props.dart@@ -21,7 +21,6 @@ class FFProbeProps {int? _rotation;Duration? duration;- // dot separated bitrate, fps, codecWidth, codecHeight. Ignore null valueString get videoInfo {final List<String> info = [];if (bitrate != null) info.add('$bitrate');@@ -47,8 +46,6 @@ class FFProbeProps {return finalWidth;}- /// To know more, read about Sample Aspect Ratio (SAR), Display Aspect Ratio (DAR)- /// and Pixel Aspect Ratio (PAR)int _calculateWidthConsideringSAR(int width) {final List<String> sar = propData![FFProbeKeys.sampleAspectRatio].toString()@@ -85,7 +82,6 @@ class FFProbeProps {int? get rotation => _rotation;- // toString() method@overrideString toString() {final buffer = StringBuffer();@@ -166,7 +162,6 @@ class FFProbeProps {parsedData[stringKey] = json[key];}}- // iterate through the streamsfinal List<dynamic> streams = json["streams"];final List<dynamic> newStreams = [];final Map<String, dynamic> metadata = {};@@ -264,7 +259,6 @@ class FFProbeProps {? null: _codecNames[value] ?? value.toUpperCase().replaceAll('_', ' ');- // input example: '2021-04-12T09:14:37.000000Z'static String? _formatDate(String value) {final dateInUtc = DateTime.tryParse(value);if (dateInUtc == null) return value;@@ -286,7 +280,6 @@ class FFProbeProps {);}- // input example: '00:00:05.408000000' or '5.408000'static Duration? _parseDuration(String? value) {if (value == null) return null;@@ -318,7 +311,6 @@ class FFProbeProps {return null;}- // input example: '00:00:05.408000000' or '5.408000'static String? _formatDuration(String? value) {if (value == null) return null;final duration = _parseDuration(value);@@ -337,8 +329,6 @@ class FFProbeProps {final int? t = int.tryParse(value.split('/')[0]);final int? b = int.tryParse(value.split('/')[1]);if (t != null && b != null) {- // return the value upto 2 decimal places. ignore even two decimal places- // if t is perfectly divisible by breturn (t % b == 0)? (t / b).toStringAsFixed(0): (t / b).toStringAsFixed(2);diff --git a/mobile/apps/photos/lib/models/file/dummy_file.dart b/mobile/apps/photos/lib/models/file/dummy_file.dartindex 9705d73336..bd6f1b2221 100644--- a/mobile/apps/photos/lib/models/file/dummy_file.dart+++ b/mobile/apps/photos/lib/models/file/dummy_file.dart@@ -1,15 +1,11 @@import "package:photos/models/file/file.dart";-/// A dummy file used to fill empty spaces in gallery grid rows to help with-/// swipe-to-select.-/// Can be uniquely identified by groupID and index within the group.class DummyFile extends EnteFile {final String groupID;final int index;DummyFile({required this.groupID, required this.index}) {- // Set a unique generatedID based on groupID and index- // Using a negative number to distinguish from real files+ // Negative IDs distinguish dummies from real files.generatedID = -(groupID.hashCode + index);}diff --git a/mobile/apps/photos/lib/models/file/file.dart b/mobile/apps/photos/lib/models/file/file.dartindex 3b41471eb8..9e4e390c8b 100644--- a/mobile/apps/photos/lib/models/file/file.dart+++ b/mobile/apps/photos/lib/models/file/file.dart@@ -51,7 +51,6 @@ class EnteFile {set magicMetadata(MagicMetadata? val) => _mmd = val;- // public magic metadata is shared if during file/album sharingString? _pubMmdEncodedJson;String? get pubMmdEncodedJson => _pubMmdEncodedJson;@@ -143,7 +142,6 @@ class EnteFile {fileType == FileType.livePhoto &&metadata.containsKey('imageHash') &&metadata.containsKey('videoHash')) {- // convert to imgHash:vidHashhash ='${metadata['imageHash']}$kLivePhotoHashSeparator${metadata['videoHash']}';}@@ -196,7 +194,6 @@ class EnteFile {return title ?? '';}- // return 0 if the height is not availableint get height {return pubMagicMetadata?.h ?? 0;}@@ -231,10 +228,7 @@ class EnteFile {ownerID: $ownerID, collectionID: $collectionID, updationTime: $updationTime)''';}- /// Mutates this file in place with upload-result fields from [uploadedFile].- /// Used by the gallery's soft refresh path so that all existing references- /// (GalleryGroups sub-lists, GalleryFileWidget.widget.file, etc.) see the- /// updated state without needing to rebuild GalleryGroups.+ // Soft refreshes mutate in place because gallery groups retain this object.void applyUploadedData(EnteFile uploadedFile) {uploadedFileID = uploadedFile.uploadedFileID;collectionID = uploadedFile.collectionID;diff --git a/mobile/apps/photos/lib/models/gallery/gallery_groups.dart b/mobile/apps/photos/lib/models/gallery/gallery_groups.dartindex 4d4fffc28b..2009cd959a 100644--- a/mobile/apps/photos/lib/models/gallery/gallery_groups.dart+++ b/mobile/apps/photos/lib/models/gallery/gallery_groups.dart@@ -15,9 +15,6 @@ import "package:photos/ui/viewer/gallery/component/group/group_header_widget.darimport "package:photos/ui/viewer/gallery/component/group/type.dart";import "package:uuid/uuid.dart";-/// In order to make the gallery performant when GroupTypes do not show group-/// headers, groups are still created here but with the group header replaced by-/// the grid's main axis spacing.class GalleryGroups {final List<EnteFile> allFiles;final GroupType groupType;@@ -38,8 +35,6 @@ class GalleryGroups {required this.selectedFiles,required this.tagPrefix,this.sortOrderAsc = true,-- /// Should be GroupGallery.spacing if GroupType.showGroupHeader() is false.required this.groupHeaderExtent,required this.showSelectAll,this.limitSelectionToOne = false,@@ -86,8 +81,6 @@ class GalleryGroups {List<({String groupID, String title})> get scrollbarDivisions =>_scrollbarDivisions;- /// Returns allFiles with dummy entries added at appropriate positions to fill- /// incomplete rows in each group.List<EnteFile> get allFilesWithDummies => _allFilesWithDummies;double? getOffsetOfGroupContainingFile(EnteFile file) {@@ -112,7 +105,6 @@ class GalleryGroups {return scrollOffset;}- /// Uses binary search to find the group ID that contains the given creation time.String? _findGroupForCreationTime(int creationTime) {if (_groupIds.isEmpty) {_logger.warning(@@ -137,7 +129,6 @@ class GalleryGroups {final minTime = groupData.minCreationTime;if (creationTime <= maxTime && creationTime >= minTime) {- // Found the group containing this creation timereturn groupId;} else if (sortOrderAsc) {if (creationTime < minTime) {@@ -238,7 +229,6 @@ class GalleryGroups {filesInGroup[firstIndexOfRowWrtFilesInGroup + i];if (currentFile is DummyFile) {- // Add dummy widget for DummyFilegridRowChildren.add(RepaintBoundary(key: ValueKey(tagPrefix + currentFile.tag),@@ -250,7 +240,6 @@ class GalleryGroups {),);} else {- // Add normal GalleryFileWidget for real filesgridRowChildren.add(RepaintBoundary(key: ValueKey(tagPrefix + currentFile.tag),@@ -357,12 +346,10 @@ class GalleryGroups {void _createNewGroup(List<EnteFile> groupFiles, Set<int> yearsInGroups) {final uuid = _uuid.v1();- // Save original last file before adding dummies to the endfinal lastFile = groupFiles.last;// Dummy files are used for gesture tracking in swipe-to-selectif (!limitSelectionToOne) {- // Add dummy files to fill the last row if neededfinal incompleteRowCount = groupFiles.length % crossAxisCount;if (incompleteRowCount != 0) {final dummiesNeeded = crossAxisCount - incompleteRowCount;@@ -395,7 +382,6 @@ class GalleryGroups {_allFilesWithDummies.addAll(groupFiles);}- // For scrollbar divisionsif (groupType.timeGrouping()) {final yearOfGroup = DateTime.fromMicrosecondsSinceEpoch(groupFiles.first.creationTime!,diff --git a/mobile/apps/photos/lib/models/metadata/common_keys.dart b/mobile/apps/photos/lib/models/metadata/common_keys.dartindex 1156623e8a..1d2007feea 100644--- a/mobile/apps/photos/lib/models/metadata/common_keys.dart+++ b/mobile/apps/photos/lib/models/metadata/common_keys.dart@@ -4,5 +4,4 @@ const magicKeyVisibility = 'visibility';const visibleVisibility = 0;const archiveVisibility = 1;-///Do not use [hiddenVisibility] for hidden filesconst hiddenVisibility = 2;diff --git a/mobile/apps/photos/lib/models/ml/face/box.dart b/mobile/apps/photos/lib/models/ml/face/box.dartindex a470f92ff7..f02b677449 100644--- a/mobile/apps/photos/lib/models/ml/face/box.dart+++ b/mobile/apps/photos/lib/models/ml/face/box.dart@@ -1,11 +1,6 @@import "package:ente_pure_utils/ente_pure_utils.dart";-/// Bounding box of a face.-///-/// [ x] and [y] are the minimum coordinates, so the top left corner of the box.-/// [width] and [height] are the width and height of the box.-///-/// WARNING: All values are relative to the original image size, so in the range [0, 1].+// x and y are the top-left corner; all values are fractions of the image.class FaceBox {final double x;final double y;diff --git a/mobile/apps/photos/lib/models/ml/face/detection.dart b/mobile/apps/photos/lib/models/ml/face/detection.dartindex ddd770b317..1d753ee9cf 100644--- a/mobile/apps/photos/lib/models/ml/face/detection.dart+++ b/mobile/apps/photos/lib/models/ml/face/detection.dart@@ -4,21 +4,15 @@ import "package:photos/models/ml/face/box.dart";import "package:photos/models/ml/face/landmark.dart";import "package:photos/services/machine_learning/face_ml/face_detection/detection.dart";-/// Stores the face detection data, notably the bounding box and landmarks.-///-/// - Bounding box: [FaceBox] with x, y (minimum, so top left corner), width, height-/// - Landmarks: list of [Landmark]s, namely leftEye, rightEye, nose, leftMouth, rightMouth-///-/// WARNING: All coordinates are relative to the image size, so in the range [0, 1]!class Detection {FaceBox box;+ // Order: left eye, right eye, nose, left mouth, right mouth.List<Landmark> landmarks;Detection({required this.box, required this.landmarks});bool get isEmpty => box.width == 0 && box.height == 0 && landmarks.isEmpty;- // empty boxDetection.empty(): box = const FaceBox(x: 0, y: 0, width: 0, height: 0),landmarks = [];@@ -69,10 +63,8 @@ class Detection {final bool noseCloseToRightEye =(nose[0] - rightEye[0]).abs() < 0.2 * eyeDistanceX;- // if (faceIsUpright && (noseStickingOutLeft || noseCloseToLeftEye)) {if (noseStickingOutLeft || (faceIsUpright && noseCloseToLeftEye)) {return FaceDirection.left;- // } else if (faceIsUpright && (noseStickingOutRight || noseCloseToRightEye)) {} else if (noseStickingOutRight || (faceIsUpright && noseCloseToRightEye)) {return FaceDirection.right;}diff --git a/mobile/apps/photos/lib/models/ml/face/face.dart b/mobile/apps/photos/lib/models/ml/face/face.dartindex fe4054f68e..c9036d99ab 100644--- a/mobile/apps/photos/lib/models/ml/face/face.dart+++ b/mobile/apps/photos/lib/models/ml/face/face.dart@@ -6,7 +6,6 @@ import "package:photos/models/ml/face/landmark.dart";import 'package:photos/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart';import "package:photos/services/machine_learning/ml_result.dart";-// FileInfo contains the image width and height of the image the face was detected in.class FileInfo {int? imageWidth;int? imageHeight;@@ -20,13 +19,9 @@ class Face {final double score;final double blur;- ///#region Local DB fields- // This is not stored on the server, using it for local DB rowFileInfo? fileInfo;final int fileID;- ///#endregion-bool get isBlurry => blur < kLaplacianHardThreshold;bool get hasHighScore => score > kMinimumQualityFaceScore;@@ -93,7 +88,6 @@ class Face {parseAsDoubleList(json['embedding'] as List),parseIntOrDoubleAsDouble(json['score'])!,Detection.fromJson(json['detection'] as Map<String, dynamic>),- // high value means tparseIntOrDoubleAsDouble(json['blur']) ?? kLapacianDefault,);}diff --git a/mobile/apps/photos/lib/models/ml/face/landmark.dart b/mobile/apps/photos/lib/models/ml/face/landmark.dartindex bb01d5fcaf..877e45f294 100644--- a/mobile/apps/photos/lib/models/ml/face/landmark.dart+++ b/mobile/apps/photos/lib/models/ml/face/landmark.dart@@ -1,6 +1,4 @@-/// Landmark coordinate data.-///-/// WARNING: All coordinates are relative to the image size, so in the range [0, 1]!+// Coordinates are fractions of the original image dimensions.class Landmark {double x;double y;diff --git a/mobile/apps/photos/lib/models/ml/face/person.dart b/mobile/apps/photos/lib/models/ml/face/person.dartindex 5efe22bde9..b945f9d5dc 100644--- a/mobile/apps/photos/lib/models/ml/face/person.dart+++ b/mobile/apps/photos/lib/models/ml/face/person.dart@@ -1,6 +1,3 @@-// PersonEntity represents information about a Person in the context of FaceClustering that is stored.-// On the remote server, the PersonEntity is stored as {Entity} with type person.-// On the device, this information is stored as [LocalEntityData] with type person.import "package:flutter/foundation.dart";const Object _personDataUnchanged = Object();@@ -10,7 +7,6 @@ class PersonEntity {final PersonData data;PersonEntity(this.remoteID, this.data);- // copyWithPersonEntity copyWith({String? remoteID, PersonData? data}) {return PersonEntity(remoteID ?? this.remoteID, data ?? this.data);}@@ -21,10 +17,8 @@ class ClusterInfo {final Set<String> faces;ClusterInfo({required this.id, required this.faces});- // toJsonMap<String, dynamic> toJson() => {'id': id, 'faces': faces.toList()};- // from Jsonfactory ClusterInfo.fromJson(Map<String, dynamic> json) {return ClusterInfo(id: json['id'] as String,@@ -36,8 +30,7 @@ class ClusterInfo {class PersonData {final String name;- /// Used to mark a person to not show in the people section.- /// WARNING: When checking whether to show a person, use [isIgnored] instead, as it also checks legacy hidden names.+ // Use isIgnored; it also handles legacy hidden names.final bool isHidden;final bool isPinned;final bool hideFromMemories;@@ -47,18 +40,15 @@ class PersonData {List<String> rejectedFaceIDs = List<String>.empty();List<int> manuallyAssigned = List<int>.empty();- /// string formatted in `yyyy-MM-dd`+ // Formatted as yyyy-MM-dd.final String? birthDate;- /// email should be always looked via userID as user might have changed- /// their email ids.+ // Look up the current email by userID; this value can be stale.final String? email;final int? userID;bool hasAvatar() => avatarFaceID != null;- /// Returns true if the person should be ignored in the UI.- /// This included the regular [isHidden] check, but also a check for legacy namesbool get isIgnored =>(isHidden || name.isEmpty || name == '(hidden)' || name == '(ignored)');@@ -75,7 +65,6 @@ class PersonData {this.email,this.userID,});- // copyWithPersonData copyWith({String? name,List<ClusterInfo>? assigned,@@ -114,7 +103,6 @@ class PersonData {void logStats() {if (kDebugMode == false) return;- // log number of assigned and rejected clusters and total number of faces in each clusterfinal StringBuffer sb = StringBuffer();sb.writeln('Person: $name');int assignedCount = 0;@@ -130,7 +118,6 @@ class PersonData {debugPrint(sb.toString());}- // toJsonMap<String, dynamic> toJson() => {'name': name,'assigned': assigned.map((e) => e.toJson()).toList(),@@ -145,7 +132,6 @@ class PersonData {'manuallyAssigned': manuallyAssigned,};- // fromJsonfactory PersonData.fromJson(Map<String, dynamic> json) {final assigned =(json['assigned'] == null ||diff --git a/mobile/apps/photos/lib/models/ml/ml_versions.dart b/mobile/apps/photos/lib/models/ml/ml_versions.dartindex 3c84095d24..146841138a 100644--- a/mobile/apps/photos/lib/models/ml/ml_versions.dart+++ b/mobile/apps/photos/lib/models/ml/ml_versions.dart@@ -6,8 +6,7 @@ const clusterMlVersion = 1;const petMlVersion = 1;const minimumClusterSize = 2;-/// Bits for the `flags` bitmask on RemoteFaceEmbedding / RemoteClipEmbedding.-/// Once shipped, a bit's meaning is immutable β only add new bits.+// Remote embedding flag bits are immutable. Add new bits; never reuse old ones.const int mlIndexFlagRuntimeRust = 1 << 0;const int mlIndexFlagCoreML = 1 << 1;const int mlIndexFlagWebGPU = 1 << 2;diff --git a/mobile/apps/photos/lib/models/search/hierarchical/album_filter.dart b/mobile/apps/photos/lib/models/search/hierarchical/album_filter.dartindex 2344fb4d5c..b1915d7a90 100644--- a/mobile/apps/photos/lib/models/search/hierarchical/album_filter.dart+++ b/mobile/apps/photos/lib/models/search/hierarchical/album_filter.dart@@ -5,8 +5,6 @@ import "package:photos/models/search/hierarchical/hierarchical_search_filter.darclass AlbumFilter extends HierarchicalSearchFilter {final int collectionID;final String albumName;-- ///Number of files in the gallery that are from [collectionID]final int occurrence;AlbumFilter({diff --git a/mobile/apps/photos/lib/models/search/hierarchical/hierarchical_search_filter.dart b/mobile/apps/photos/lib/models/search/hierarchical/hierarchical_search_filter.dartindex b4ba4d631f..321d86144a 100644--- a/mobile/apps/photos/lib/models/search/hierarchical/hierarchical_search_filter.dart+++ b/mobile/apps/photos/lib/models/search/hierarchical/hierarchical_search_filter.dart@@ -28,8 +28,6 @@ abstract class HierarchicalSearchFilter {HierarchicalSearchFilter({required this.filterTypeName, matchedUploadedIDs}): matchedUploadedIDs = matchedUploadedIDs ?? {},- //Check to ensure that when a new filter extends HierarchicalSearchFilter,- //it's filterTypeName is added to FilterTypeNames enum.assert(FilterTypeNames.values.map((e) => e.toString().split(".").last)@@ -40,9 +38,6 @@ abstract class HierarchicalSearchFilter {String name();SearchFilterIcon? icon();- /// Will be [kmostRelevantFilter] if the filter is a Top-level filter. For- /// example, when searching for an album 'A' and opening it, when- /// hierarchical search starts, the album 'A' will be the top level filter.int relevance();bool isMatch(EnteFile file);bool isSameFilter(HierarchicalSearchFilter other);diff --git a/mobile/apps/photos/lib/models/search/hierarchical/only_them_filter.dart b/mobile/apps/photos/lib/models/search/hierarchical/only_them_filter.dartindex 4329848e0d..682d70b6b0 100644--- a/mobile/apps/photos/lib/models/search/hierarchical/only_them_filter.dart+++ b/mobile/apps/photos/lib/models/search/hierarchical/only_them_filter.dart@@ -6,9 +6,6 @@ import "package:photos/models/search/hierarchical/hierarchical_search_filter.darclass OnlyThemFilter extends HierarchicalSearchFilter {final List<FaceFilter> faceFilters;final int occurrence;-- /// Workaround to avoid passing context to the filter to avoid making context- /// a long lived object.final String onlyThemString;OnlyThemFilter({diff --git a/mobile/apps/photos/lib/models/search/hierarchical/top_level_generic_filter.dart b/mobile/apps/photos/lib/models/search/hierarchical/top_level_generic_filter.dartindex b651afe879..e9c8ccba88 100644--- a/mobile/apps/photos/lib/models/search/hierarchical/top_level_generic_filter.dart+++ b/mobile/apps/photos/lib/models/search/hierarchical/top_level_generic_filter.dart@@ -2,10 +2,6 @@ import "package:photos/models/file/file.dart";import "package:photos/models/search/hierarchical/hierarchical_search_filter.dart";import "package:photos/models/search/search_types.dart";-///Not necessary that all top level filters in hierarchical search have to be-///a [TopLevelGenericFilter]. This is just a generic filter that can be used-///for dates, descriptions etc which do not have a specific-///[HierarchicalSearchFilter].class TopLevelGenericFilter extends HierarchicalSearchFilter {final String filterName;final int occurrence;diff --git a/mobile/apps/photos/lib/models/search/search_types.dart b/mobile/apps/photos/lib/models/search/search_types.dartindex a639769f10..fb4ab9f499 100644--- a/mobile/apps/photos/lib/models/search/search_types.dart+++ b/mobile/apps/photos/lib/models/search/search_types.dart@@ -60,7 +60,6 @@ enum SectionType {}extension SectionTypeExtensions on SectionType {- // passing context for internalization in the futureString sectionTitle(BuildContext context) {switch (this) {case SectionType.face:@@ -103,8 +102,6 @@ extension SectionTypeExtensions on SectionType {}}- // isCTAVisible is used to show/hide the CTA button in the empty state- // Disable the CTA for face, content, moment, fileTypesAndExtension, fileCaptionbool get isCTAVisible {switch (this) {case SectionType.face:@@ -213,7 +210,6 @@ extension SectionTypeExtensions on SectionType {initialValue: "",textCapitalization: TextCapitalization.words,onSubmit: (String text) async {- // indicates user cancelled the rename requestif (text.trim() == "") {return;}@@ -314,8 +310,6 @@ extension SectionTypeExtensions on SectionType {}}- ///Events to listen to for different search sections, different from common- ///events listened to in AllSectionsExampleState.List<Stream<Event>> sectionUpdateEvents() {switch (this) {case SectionType.location:diff --git a/mobile/apps/photos/lib/models/selected_files.dart b/mobile/apps/photos/lib/models/selected_files.dartindex 6a7d73d975..f27dd143ed 100644--- a/mobile/apps/photos/lib/models/selected_files.dart+++ b/mobile/apps/photos/lib/models/selected_files.dart@@ -5,34 +5,14 @@ import 'package:photos/events/clear_selections_event.dart';import 'package:photos/models/file/dummy_file.dart';import 'package:photos/models/file/file.dart';-/// Manages the set of currently selected files in the gallery.-///-/// This class serves as the single source of truth for file selection state-/// and automatically filters out [DummyFile] instances from all selection-/// operations. Dummy files are used for gallery layout purposes and should-/// never be selected.-///-/// All selection methods ([toggleSelection], [selectAll],-/// [unSelectAll], [toggleGroupSelection]) automatically exclude dummy files.-/// Calling code does not need to check for or filter out dummy files before-/// calling these methods.class SelectedFiles extends ChangeNotifier {final files = <EnteFile>{};-- ///This variable is used to track the files that were involved in last selection- ///operation (select/unselect). Each [LazyGridView] checks this variable on- ///change in [SelectedFiles] to see if any of it's files were involved in last- ///select/unselect operation. If yes, then it will rebuild itself.final lastSelectionOperationFiles = <EnteFile>{};void toggleSelection(EnteFile fileToToggle) {- // Skip dummy files - they should never be selectedif (fileToToggle is DummyFile) {return;}- // To handle the cases, where the file might have changed due to upload- // or any other update, using file.generatedID to track if this file was already- // selected or notfinal EnteFile? alreadySelected = files.firstWhereOrNull((element) => _isMatch(fileToToggle, element),);@@ -47,7 +27,6 @@ class SelectedFiles extends ChangeNotifier {}void toggleGroupSelection(Set<EnteFile> filesToToggle) {- // Filter out dummy files before processingfinal nonDummyFiles = filesToToggle.where((file) => file is! DummyFile).toSet();@@ -62,7 +41,6 @@ class SelectedFiles extends ChangeNotifier {}void selectAll(Set<EnteFile> filesToSelect) {- // Filter out dummy files before adding to selectionfinal nonDummyFiles = filesToSelect.where((file) => file is! DummyFile).toSet();@@ -75,7 +53,6 @@ class SelectedFiles extends ChangeNotifier {void unSelectAll(Set<EnteFile> filesToUnselect, {bool skipNotify = false}) {files.removeWhere((file) => filesToUnselect.contains(file));lastSelectionOperationFiles.clear();- // Filter out dummy files before adding to lastSelectionOperationFileslastSelectionOperationFiles.addAll(filesToUnselect.where((file) => file is! DummyFile),);@@ -118,11 +95,7 @@ class SelectedFiles extends ChangeNotifier {notifyListeners();}- /// Removes [file] from internal sets before a mutation that changes fields- /// participating in `==`/`hashCode`, then re-adds it after the mutation.- ///- /// Call this around in-place mutations (e.g. [EnteFile.applyUploadedData])- /// so that the hash-based sets stay consistent.+ // Remove before mutating fields used by == or hashCode, then reinsert.void mutateFile(EnteFile file, void Function() mutate) {final wasInFiles = files.remove(file);final wasInLastOp = lastSelectionOperationFiles.remove(file);@@ -132,14 +105,11 @@ class SelectedFiles extends ChangeNotifier {if (wasInFiles || wasInLastOp) notifyListeners();}- ///Retains only the files that are present in the [filesToRetain] set in- ///[files]. Takes the intersection of the two sets.void retainFiles(Set<EnteFile> filesToRetain) {files.retainAll(filesToRetain);notifyListeners();}- ///Replaces the current selection with [filesToSelect] in a single update.void replaceSelection(Set<EnteFile> filesToSelect) {final nonDummyFiles = filesToSelect.where((file) => file is! DummyFile)diff --git a/mobile/apps/photos/lib/models/similar_files.dart b/mobile/apps/photos/lib/models/similar_files.dartindex 6881a6c734..7efee07af1 100644--- a/mobile/apps/photos/lib/models/similar_files.dart+++ b/mobile/apps/photos/lib/models/similar_files.dart@@ -75,8 +75,6 @@ class SimilarFilesCache {final bool exact;List<SimilarFiles>? _similarFilesList;-- /// Milliseconds since epochfinal int cachedTime;SimilarFilesCache({diff --git a/mobile/apps/photos/lib/models/social/anon_profile.dart b/mobile/apps/photos/lib/models/social/anon_profile.dartindex bcc5fa0ef8..578c662a06 100644--- a/mobile/apps/photos/lib/models/social/anon_profile.dart+++ b/mobile/apps/photos/lib/models/social/anon_profile.dart@@ -1,21 +1,8 @@-/// Decrypted anonymous user profile stored locally.-///-/// Stores the decrypted display name payload for anonymous users who interact-/// via shared album links.class AnonProfile {- /// The anonymous user ID (e.g., "anon_abc123")final String anonUserID;-- /// The collection this profile belongs tofinal int collectionID;-- /// The decrypted display name payload as raw string.final String data;-- /// When the profile was created (microseconds since epoch)final int createdAt;-- /// When the profile was last updated (microseconds since epoch)final int updatedAt;AnonProfile({@@ -26,7 +13,6 @@ class AnonProfile {required this.updatedAt,});- /// Extracts the trimmed display name from the payload.String? get displayName {final trimmed = data.trim();return trimmed.isEmpty ? null : trimmed;diff --git a/mobile/apps/photos/lib/models/social/api_responses.dart b/mobile/apps/photos/lib/models/social/api_responses.dartindex cc6b6c9931..0c4014a677 100644--- a/mobile/apps/photos/lib/models/social/api_responses.dart+++ b/mobile/apps/photos/lib/models/social/api_responses.dart@@ -1,7 +1,3 @@-/// Raw comment data from the API (encrypted).-///-/// This represents the wire format from the server with cipher/nonce pairs.-/// Decryption happens in the sync service before storing locally.class CommentApiResponse {final String id;final int collectionID;@@ -49,10 +45,6 @@ class CommentApiResponse {}}-/// Raw reaction data from the API (encrypted).-///-/// This represents the wire format from the server with cipher/nonce pairs.-/// Decryption happens in the sync service before storing locally.class ReactionApiResponse {final String id;final int collectionID;@@ -100,7 +92,6 @@ class ReactionApiResponse {}}-/// Response from GET /comments/diffclass CommentsDiffResponse {final List<CommentApiResponse> comments;final bool hasMore;@@ -118,7 +109,6 @@ class CommentsDiffResponse {}}-/// Response from GET /reactions/diffclass ReactionsDiffResponse {final List<ReactionApiResponse> reactions;final bool hasMore;@@ -136,7 +126,6 @@ class ReactionsDiffResponse {}}-/// Response from GET /social/diff (unified endpoint)class SocialDiffResponse {final List<CommentApiResponse> comments;final List<ReactionApiResponse> reactions;@@ -166,7 +155,6 @@ class SocialDiffResponse {}}-/// Per-collection latest update timestamps from GET /comments-reactions/updated-atclass CollectionLatestUpdate {final int collectionID;final int? commentsUpdatedAt;@@ -190,7 +178,6 @@ class CollectionLatestUpdate {}}-/// Response from GET /comments-reactions/updated-atclass LatestUpdatesResponse {final List<CollectionLatestUpdate> updates;@@ -208,7 +195,6 @@ class LatestUpdatesResponse {}}-/// Anonymous user profile from GET /social/anon-profiles (encrypted)class AnonProfileApiResponse {final String anonUserID;final int collectionID;@@ -238,7 +224,6 @@ class AnonProfileApiResponse {}}-/// Response from GET /social/anon-profilesclass AnonProfilesResponse {final List<AnonProfileApiResponse> profiles;diff --git a/mobile/apps/photos/lib/models/social/feed_data_provider.dart b/mobile/apps/photos/lib/models/social/feed_data_provider.dartindex de3ae2e6df..dd4998dd25 100644--- a/mobile/apps/photos/lib/models/social/feed_data_provider.dart+++ b/mobile/apps/photos/lib/models/social/feed_data_provider.dart@@ -18,10 +18,6 @@ import "package:photos/services/collections_service.dart";import 'package:photos/services/social_notification_coordinator.dart';import "package:photos/services/social_sync_service.dart";-/// Provider for feed data.-///-/// Aggregates social activity (comments, reactions) into feed items-/// for display in the activity feed.class FeedDataProvider {FeedDataProvider._() {Bus.instance.on<UserLoggedOutEvent>().listen((_) => _cache.clear());@@ -39,11 +35,6 @@ class FeedDataProvider {static const _kSharedCollectionPreviewFileLimit = 30;final _cache = FeedItemsCache(ttl: const Duration(seconds: 3));- /// Gets feed items aggregated from local database.- ///- /// Feed items are sorted by most recent activity.- /// Each item represents a unique (type, fileID, commentID) combination.- /// Items from hidden collections or associated with deleted files are filtered out.Future<List<FeedItem>> getFeedItems({int limit = 50,bool includeSharedPhotos = true,@@ -83,7 +74,6 @@ class FeedDataProvider {}) async {final feedItems = <FeedItem>[];- // Fetch all activity types in parallelfinal results = await Future.wait([_db.getReactionsOnFiles(excludeUserID: userID, limit: limit),_db.getCommentsOnFiles(excludeUserID: userID, limit: limit),@@ -98,7 +88,6 @@ class FeedDataProvider {final commentLikeReactions = results[3] as List<Reaction>;final replyLikeReactions = results[4] as List<Reaction>;- // Collect all fileIDs for batch loading to resolve ownershipfinal fileIDs = <int>{};for (final r in photoLikeReactions) {if (r.fileID != null) fileIDs.add(r.fileID!);@@ -110,7 +99,6 @@ class FeedDataProvider {? await FilesDB.instance.getFileIDToFileFromIDs(fileIDs.toList()): <int, EnteFile>{};- // Aggregate photo likes by filefeedItems.addAll(_aggregateReactionsByFile(photoLikeReactions,@@ -120,7 +108,6 @@ class FeedDataProvider {),);- // Aggregate comments by filefeedItems.addAll(_aggregateCommentsByFile(fileComments,@@ -129,10 +116,8 @@ class FeedDataProvider {),);- // Aggregate replies by parent commentfeedItems.addAll(_aggregateRepliesByParent(replies, userID: userID));- // Aggregate comment likes by commentfeedItems.addAll(await _aggregateReactionsByComment(commentLikeReactions,@@ -141,7 +126,6 @@ class FeedDataProvider {),);- // Aggregate reply likes by replyfeedItems.addAll(await _aggregateReactionsByComment(replyLikeReactions,@@ -150,7 +134,6 @@ class FeedDataProvider {),);- // Aggregate shared photos (files added by others to user's collections)if (includeSharedPhotos) {final sharedFeedCutoffTime = kDebugMode? 0@@ -185,15 +168,12 @@ class FeedDataProvider {feedItems.addAll(sharedPhotoFeedResult.sharedPhotoFeedItems);}- // Filter out items where the associated file doesn't exist or collection is hiddenfinal validItems = verifyFileExistence? await _filterFeedItems(feedItems): _filterHiddenCollectionsOnly(feedItems);- // Sort by most recent activityvalidItems.sort((a, b) => b.createdAt.compareTo(a.createdAt));- // Limit total resultsif (validItems.length > limit) {return validItems.sublist(0, limit);}@@ -201,13 +181,11 @@ class FeedDataProvider {return validItems;}- /// Gets a single feed item for preview display.Future<FeedItem?> getLatestFeedItem() async {final items = await getFeedItems(limit: 1, verifyFileExistence: false);return items.isNotEmpty ? items.first : null;}- /// Triggers background sync for all shared collections.Future<bool> syncAllSharedCollections() async {try {final hasNewData = await SocialSyncService.instance@@ -233,7 +211,6 @@ class FeedDataProvider {.toList();}- /// Aggregates reactions on files by (collectionID, fileID).List<FeedItem> _aggregateReactionsByFile(List<Reaction> reactions,FeedItemType type, {@@ -250,10 +227,8 @@ class FeedDataProvider {return groupedByFile.entries.map((entry) {final reactions = entry.value;- // Sort by created_at DESC to get most recent firstreactions.sort((a, b) => b.createdAt.compareTo(a.createdAt));- // Dedupe actors by userID, keeping order (most recent first)final seenUserIDs = <int>{};final uniqueUserIDs = <int>[];final uniqueAnonIDs = <String?>[];@@ -281,7 +256,6 @@ class FeedDataProvider {}).toList();}- /// Aggregates comments on files by (collectionID, fileID).List<FeedItem> _aggregateCommentsByFile(List<Comment> comments, {required Map<int, EnteFile> filesByID,@@ -297,10 +271,8 @@ class FeedDataProvider {return groupedByFile.entries.map((entry) {final comments = entry.value;- // Sort by created_at DESC to get most recent firstcomments.sort((a, b) => b.createdAt.compareTo(a.createdAt));- // Dedupe actors by userID, keeping order (most recent first)final seenUserIDs = <int>{};final uniqueUserIDs = <int>[];final uniqueAnonIDs = <String?>[];@@ -329,7 +301,6 @@ class FeedDataProvider {}).toList();}- /// Aggregates replies by parent comment ID.List<FeedItem> _aggregateRepliesByParent(List<Comment> replies, {required int userID,@@ -344,10 +315,8 @@ class FeedDataProvider {return groupedByParent.entries.map((entry) {final replies = entry.value;- // Sort by created_at DESC to get most recent firstreplies.sort((a, b) => b.createdAt.compareTo(a.createdAt));- // Dedupe actors by userID, keeping order (most recent first)final seenUserIDs = <int>{};final uniqueUserIDs = <int>[];final uniqueAnonIDs = <String?>[];@@ -372,7 +341,6 @@ class FeedDataProvider {}).toList();}- /// Aggregates reactions by comment ID.Future<List<FeedItem>> _aggregateReactionsByComment(List<Reaction> reactions,FeedItemType type, {@@ -397,10 +365,8 @@ class FeedDataProvider {return groupedByComment.entries.map((entry) {final reactions = entry.value;- // Sort by created_at DESC to get most recent firstreactions.sort((a, b) => b.createdAt.compareTo(a.createdAt));- // Dedupe actors by userID, keeping order (most recent first)final seenUserIDs = <int>{};final uniqueUserIDs = <int>[];final uniqueAnonIDs = <String?>[];@@ -433,11 +399,6 @@ class FeedDataProvider {.toList();}- /// Gets shared photo feed items.- ///- /// Groups files added by others into session-like buckets using- /// (collectionID, ownerID) + a short addedTime gap.- /// Hidden collections are filtered downstream in _filterFeedItems.Future<_SharedPhotoFeedResult> _getSharedPhotoFeedResult({required int userID,int limit = 50,@@ -628,22 +589,12 @@ class FeedDataProvider {.toList();}- /// Filters out feed items that should not be displayed.- ///- /// Removes items where:- /// - The associated file no longer exists in FilesDB- /// - The collection is hidden- ///- /// 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 {if (items.isEmpty) return items;- // Get hidden collection IDs to filter outfinal hiddenCollectionIds = CollectionsService.instance.getHiddenCollectionIds();- // Collect unique (fileID, collectionID) pairsfinal filesToCheck = <(int, int)>{};for (final item in items) {if (item.fileID != null) {@@ -652,31 +603,25 @@ class FeedDataProvider {}if (filesToCheck.isEmpty) {- // Still filter hidden collections even if no files to checkreturn items.where((item) => !hiddenCollectionIds.contains(item.collectionID)).toList();}- // Check which files exist using batch query (single DB call)final existingFilesByCollection = await FilesDB.instance.getExistingFileIDsByCollection(filesToCheck);- // Filter and transform itemsfinal result = <FeedItem>[];for (final item in items) {- // Exclude hidden collectionsif (hiddenCollectionIds.contains(item.collectionID)) {continue;}- // Items without fileID (collection-level activity) are keptif (item.fileID == null) {result.add(item);continue;}- // Exclude items where file no longer existsfinal existingInCollection = existingFilesByCollection[item.collectionID];if (existingInCollection?.contains(item.fileID) ?? false) {result.add(item);diff --git a/mobile/apps/photos/lib/models/social/feed_item.dart b/mobile/apps/photos/lib/models/social/feed_item.dartindex 69a576cf01..e047d69a2f 100644--- a/mobile/apps/photos/lib/models/social/feed_item.dart+++ b/mobile/apps/photos/lib/models/social/feed_item.dart@@ -1,66 +1,24 @@-/// Types of feed activity items.enum FeedItemType {- /// Reaction (like) on a photo/filephotoLike,-- /// Comment on a photo/filecomment,-- /// Reply to user's commentreply,-- /// Reaction (like) on user's commentcommentLike,-- /// Reaction (like) on user's replyreplyLike,-- /// Photos shared by others to user's albumssharedPhoto,-- /// Album shared with the current usersharedCollection,}-/// Represents an activity item in the user's feed.-///-/// Feed items are aggregated by type and target (file or comment),-/// showing multiple actors who performed the same action.class FeedItem {final FeedItemType type;final int collectionID;final int? fileID;final String? commentID;-- /// User IDs of users who performed this action.- /// First user is the most recent actor.final List<int> actorUserIDs;-- /// Anonymous user IDs corresponding to actorUserIDs.- /// Null entries indicate non-anonymous users.final List<String?> actorAnonIDs;-- /// Timestamp of the most recent activity (microseconds since epoch).final int createdAt;-- /// Whether the target of this action is owned by the current user.- ///- /// For photoLike/comment: whether the user owns the file.- /// For reply: whether the user wrote the parent comment.- /// For commentLike/replyLike: whether the user wrote the liked comment/reply.final bool isOwnedByCurrentUser;-- /// File IDs for shared photo items (multiple photos can be grouped).- /// Only populated for [FeedItemType.sharedPhoto].final List<int>? sharedFileIDs;-- /// Collection name for display in shared items.- /// Populated for [FeedItemType.sharedPhoto] and [FeedItemType.sharedCollection].final String? collectionName;-- /// Whether the target file is a video.- /// Only meaningful for types whose copy varies by photo vs video- /// ([FeedItemType.photoLike] and [FeedItemType.comment]).final bool isVideo;const FeedItem({@@ -77,23 +35,16 @@ class FeedItem {this.isVideo = false,});- /// Number of users who performed this action.int get actorCount => actorUserIDs.length;- /// Whether this feed item has multiple actors.bool get hasMultipleActors => actorCount > 1;- /// The primary actor's user ID (most recent).int get primaryActorUserID => actorUserIDs.first;- /// The primary actor's anonymous ID (if anonymous).String? get primaryActorAnonID => actorAnonIDs.first;- /// Number of additional actors beyond the primary.int get additionalActorCount => actorCount - 1;- /// Number of shared files in this feed item.- /// Only meaningful for [FeedItemType.sharedPhoto].int get sharedFileCount => sharedFileIDs?.length ?? 0;@override@@ -120,7 +71,6 @@ class FeedItem {return Object.hash(type, collectionID, fileID, commentID, createdAt);}- /// Creates a copy of this FeedItem with the given fields replaced.FeedItem copyWith({FeedItemType? type,int? collectionID,diff --git a/mobile/apps/photos/lib/models/social/social_data_provider.dart b/mobile/apps/photos/lib/models/social/social_data_provider.dartindex dd2c41871d..9e323283f2 100644--- a/mobile/apps/photos/lib/models/social/social_data_provider.dart+++ b/mobile/apps/photos/lib/models/social/social_data_provider.dart@@ -6,10 +6,6 @@ import "package:photos/models/social/reaction.dart";import "package:photos/services/social_service.dart";import "package:photos/services/social_sync_service.dart";-/// Provider for social data (comments and reactions).-///-/// Orchestrates between local database and remote API.-/// Query methods read from local DB, mutation methods call API then update DB.class SocialDataProvider {SocialDataProvider._();static final instance = SocialDataProvider._();@@ -18,14 +14,10 @@ class SocialDataProvider {final _db = SocialDB.instance;final _api = SocialService.instance;- // ============ Query methods (read from local DB) ============-Future<List<Comment>> getCommentsForFile(int fileID) {return _db.getCommentsForFile(fileID);}- /// [candidateCollectionIDs] narrows the indexed lookup to collections the- /// caller already knows are eligible.Future<Comment?> getLatestCommentForFile(int fileID, {required List<int> candidateCollectionIDs,@@ -112,30 +104,18 @@ class SocialDataProvider {return _db.getReactionsForCollection(collectionID);}- // ============ Sync methods ============-- /// Syncs reactions for a specific file.- /// Call this before displaying reactions for a file to ensure data is fresh.Future<void> syncFileReactions(int collectionID, int fileID) {return SocialSyncService.instance.syncFileReactions(collectionID, fileID);}- /// Syncs both comments and reactions for a specific file.- /// Call this before displaying comments screen to ensure data is fresh.Future<void> syncFileSocialData(int collectionID, int fileID) {return SocialSyncService.instance.syncFileSocialData(collectionID, fileID);}- /// Syncs anonymous profiles for a collection.Future<void> syncAnonProfiles(int collectionID) {return SocialSyncService.instance.syncAnonProfiles(collectionID);}- // ============ Comment mutation methods ============-- /// Adds a comment via API, then stores locally.- ///- /// Returns the created Comment on success, throws on failure.Future<Comment?> addComment({required int collectionID,required String text,@@ -143,10 +123,8 @@ class SocialDataProvider {String? parentCommentID,}) async {try {- // Encrypt the comment textfinal encrypted = _api.encryptComment(text, collectionID);- // Call APIfinal commentID = await _api.createComment(collectionID: collectionID,cipher: encrypted.cipher,@@ -155,7 +133,6 @@ class SocialDataProvider {parentCommentID: parentCommentID,);- // Create local comment object (timestamps in microseconds to match server)final now = DateTime.now().microsecondsSinceEpoch;final userID = Configuration.instance.getUserID() ?? 0;final comment = Comment(@@ -169,7 +146,6 @@ class SocialDataProvider {updatedAt: now,);- // Store locallyawait _db.addComment(comment);return comment;} catch (e) {@@ -178,15 +154,10 @@ class SocialDataProvider {}}- /// Deletes a comment via API, then marks as deleted locally.- ///- /// Returns the deleted Comment on success, throws on failure.Future<Comment?> deleteComment(String id) async {try {- // Call APIawait _api.deleteComment(id);- // Mark as deleted locallyreturn _db.deleteComment(id);} catch (e) {_logger.severe('Failed to delete comment $id', e);@@ -194,14 +165,6 @@ class SocialDataProvider {}}- // ============ Reaction mutation methods ============-- /// Toggles a reaction (like) on a file or comment.- ///- /// If the user hasn't reacted, creates a new reaction.- /// If the user has already reacted, deletes the existing reaction.- ///- /// Returns the new reaction state (Reaction with isDeleted flag).Future<Reaction?> toggleReaction({required int userID,required int collectionID,@@ -210,7 +173,6 @@ class SocialDataProvider {String reactionType = 'green_heart',}) async {try {- // Check if user already has a reactionfinal existingReaction = await _findExistingReaction(userID: userID,collectionID: collectionID,@@ -219,10 +181,8 @@ class SocialDataProvider {);if (existingReaction != null && !existingReaction.isDeleted) {- // User has an active reaction - delete itawait _api.deleteReaction(existingReaction.id);- // Mark as deleted locally (timestamps in microseconds to match server)final now = DateTime.now().microsecondsSinceEpoch;final deletedReaction = existingReaction.copyWith(isDeleted: true,@@ -231,7 +191,6 @@ class SocialDataProvider {await _db.upsertReactions([deletedReaction]);return deletedReaction;} else {- // User doesn't have a reaction or it's deleted - create/upsert onefinal encrypted = _api.encryptReaction(reactionType, collectionID);final reactionID = await _api.upsertReaction(@@ -242,7 +201,6 @@ class SocialDataProvider {commentID: commentID,);- // Create local reaction object (timestamps in microseconds to match server)final now = DateTime.now().microsecondsSinceEpoch;final reaction = Reaction(id: reactionID,@@ -256,7 +214,6 @@ class SocialDataProvider {updatedAt: now,);- // Store locallyawait _db.upsertReactions([reaction]);return reaction;}@@ -266,7 +223,6 @@ class SocialDataProvider {}}- /// Finds an existing reaction for the user on the given target.Future<Reaction?> _findExistingReaction({required int userID,required int collectionID,@@ -295,7 +251,6 @@ class SocialDataProvider {return null;}- /// Checks if the current user has liked a file in a collection.Future<bool> hasUserLikedFile(int fileID, int collectionID) async {final userID = Configuration.instance.getUserID();if (userID == null) return false;@@ -307,7 +262,6 @@ class SocialDataProvider {return reactions.any((r) => r.userID == userID && !r.isDeleted);}- /// Gets the current user's reaction on a file in a collection (if any).Future<Reaction?> getUserReactionForFile(int fileID, int collectionID) async {final userID = Configuration.instance.getUserID();if (userID == null) return null;@@ -322,12 +276,6 @@ class SocialDataProvider {return null;}- // ============ Anon Profile methods ============-- /// Gets the decrypted display name for an anonymous user.- ///- /// Returns the display name from the synced AnonProfile if available,- /// otherwise returns [fallback] (typically the raw anonUserID).Future<String> getAnonDisplayName(String anonUserID,int collectionID, {@@ -337,9 +285,6 @@ class SocialDataProvider {return profile?.displayName ?? fallback ?? anonUserID;}- /// Gets all anon profiles for a collection as a map of anonUserID -> displayName.- ///- /// Only includes profiles where displayName could be extracted from the data.Future<Map<String, String>> getAnonDisplayNamesForCollection(int collectionID,) async {diff --git a/mobile/apps/photos/lib/services/account/billing_service.dart b/mobile/apps/photos/lib/services/account/billing_service.dartindex 0d11c72464..9a930585e2 100644--- a/mobile/apps/photos/lib/services/account/billing_service.dart+++ b/mobile/apps/photos/lib/services/account/billing_service.dart@@ -2,8 +2,6 @@ import 'dart:io';import 'package:ente_pure_utils/ente_pure_utils.dart';import 'package:flutter/material.dart';-// import 'package:flutter/foundation.dart';-// import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';import 'package:logging/logging.dart';import "package:photos/gateways/billing/billing_gateway.dart";import 'package:photos/gateways/billing/models/billing_plan.dart';diff --git a/mobile/apps/photos/lib/services/account/user_service.dart b/mobile/apps/photos/lib/services/account/user_service.dartindex 725b798b59..a1bdeb29cc 100644--- a/mobile/apps/photos/lib/services/account/user_service.dart+++ b/mobile/apps/photos/lib/services/account/user_service.dart@@ -98,7 +98,6 @@ class UserService {});_preferences = await SharedPreferences.getInstance();if (Configuration.instance.isLoggedIn() && !isLocalGalleryMode) {- // add artificial delay in refreshing 2FA statusFuture.delayed(const Duration(seconds: 5),() => {setTwoFactor(fetchTwoFactorStatus: true).ignore()},@@ -206,8 +205,6 @@ class UserService {await _gateway.sendFeedback(feedback: feedback, type: type);}- // getPublicKey returns null value if email id is not- // associated with another ente accountFuture<String?> getPublicKey(String email) async {final String? cachedPubKey = _publicKeyCache.get(email);if (cachedPubKey != null) {@@ -255,7 +252,6 @@ class UserService {if (hasSecurityStatusChanged) {Bus.instance.fire(UserDetailsChangedEvent());}- // handle email change from different clientif (userDetails.email != _config.getEmail()) {await setEmail(userDetails.email);}@@ -287,11 +283,8 @@ class UserService {if (!context.mounted) return;Navigator.of(context).popUntil((route) => route.isFirst);} catch (e) {- // Determine if we should silently ignore the error and proceed with logoutfinal bool silentlyIgnoreError =- // Token is already invalid (401 response)(e is DioException && e.response?.statusCode == 401) ||- // Custom endpoints where server might be non-existent or unavailable!endpointConfig.isProduction;if (silentlyIgnoreError) {@@ -305,7 +298,6 @@ class UserService {await Configuration.instance.logout();- // Navigate to first route if context is still mountedif (context.mounted) {Navigator.of(context).popUntil((route) => route.isFirst);}@@ -313,8 +305,7 @@ class UserService {}_logger.severe("Failed to logout", e);- //This future is for waiting for the dialog from which logout() is called- //to close and only then to show the error dialog.+ // Let the logout dialog close before showing the error.if (!context.mounted) return;unawaited(Future.delayed(const Duration(milliseconds: 150), () {@@ -1237,15 +1228,6 @@ class UserService {}}- /// Returns Contacts(Users) that are relevant to the account owner.- /// Note: "User" refers to the account owner in the points below.- /// This includes:- /// - Collaborators and viewers of collections owned by user- /// - Owners of collections shared to user.- /// - All collaborators of collections in which user is a collaborator or- /// a viewer.- /// - All family members of user.- /// - All contacts linked to a person.List<UserSuggestion> getRelevantContacts() {final int ownerID = Configuration.instance.getUserID()!;final String ownerEmail = Configuration.instance.getEmail()!;@@ -1260,14 +1242,11 @@ class UserService {for (final c in CollectionsService.instance.getActiveCollections()) {if (c.owner.id == ownerID) {- // Collaborators and viewers of collections owned by userfor (final User u in c.sharees) {add(u.email, userID: u.id);}} else if (c.owner.email.isNotEmpty) {- // Owners of collections shared with useradd(c.owner.email, userID: c.owner.id);- // Collaborators of collections in which user participatesfinal participates = c.sharees.any((u) =>u.email == ownerEmail &&diff --git a/mobile/apps/photos/lib/services/album_home_widget_service.dart b/mobile/apps/photos/lib/services/album_home_widget_service.dartindex 679f552d4b..dbf8cfcac0 100644--- a/mobile/apps/photos/lib/services/album_home_widget_service.dart+++ b/mobile/apps/photos/lib/services/album_home_widget_service.dart@@ -29,7 +29,6 @@ import 'package:shared_preferences/shared_preferences.dart';enum _AlbumWidgetCacheUpdateReason { none, changed, stale }class AlbumHomeWidgetService {- // Constantsstatic const String SELECTED_ALBUMS_KEY = "selectedAlbumsHW";static const String ALBUMS_LAST_HASH_KEY = "albumsLastHash";static const String ANDROID_CLASS_NAME = "EnteAlbumsWidgetProvider";@@ -42,14 +41,12 @@ class AlbumHomeWidgetService {static const int MAX_ALBUMS_LIMIT = 50;static const Duration ALBUMS_CACHE_REFRESH_INTERVAL = Duration(hours: 24);- // Singleton patternstatic final AlbumHomeWidgetService instance =AlbumHomeWidgetService._privateConstructor();AlbumHomeWidgetService._privateConstructor() {_listenToLocalPhotoUpdates();}- // Propertiesfinal Logger _logger = Logger((AlbumHomeWidgetService).toString());SharedPreferences get _prefs => ServiceLocator.instance.prefs;@@ -81,7 +78,6 @@ class AlbumHomeWidgetService {});}- // Public methodsList<int>? getSelectedAlbumIds() {final selectedAlbums = _prefs.getStringList(SELECTED_ALBUMS_KEY);return selectedAlbums?.map((id) => int.tryParse(id) ?? 0).toList();@@ -215,7 +211,6 @@ class AlbumHomeWidgetService {return;}- // First navigate to the collection pagefinal thumbnail = await CollectionsService.instance.getCover(collection);AppNavigationService.instance.pushPage(@@ -226,7 +221,6 @@ class AlbumHomeWidgetService {collection.id,);- // Then open the specific filefinal file = await FilesDB.instance.getFile(fileId);if (file == null) {_logger.warning("Cannot launch widget: file with ID $fileId not found");@@ -248,7 +242,6 @@ class AlbumHomeWidgetService {await _refreshAlbumsWidget();}- // Private methodsString _calculateHash(List<int> albumIds) {String updationTimestamps = "";@@ -270,14 +263,12 @@ class AlbumHomeWidgetService {}Future<bool> _hasAnyBlockers([bool isBg = false]) async {- // Check if first import is completedfinal hasCompletedFirstImport = LocalSyncService.instance.hasCompletedFirstImportOrBypassed();if (!hasCompletedFirstImport) {return true;}- // Check if selected albums existfinal selectedAlbumIds = await _getEffectiveSelectedAlbumIds(isBg);final albums = getAlbumsByIds(selectedAlbumIds);@@ -359,7 +350,6 @@ class AlbumHomeWidgetService {}Future<void> _refreshAlbumsWidget() async {- // only refresh if widget was synced without issuesif (await countHomeWidgets() == 0) return;await _refreshWidget(message: "Refreshing from existing album set");}@@ -370,18 +360,15 @@ class AlbumHomeWidgetService {}Future<_AlbumWidgetCacheUpdateReason> _getWidgetCacheUpdateReason() async {- // Check if albums changed flag is setif (hasSelectionChanged() == true) {return _AlbumWidgetCacheUpdateReason.changed;}- // Check if we have any albums selectedfinal selectedAlbumIds = await _getEffectiveSelectedAlbumIds();if (selectedAlbumIds.isEmpty) {return _AlbumWidgetCacheUpdateReason.none;}- // Check if hash has changedfinal currentHash = _calculateHash(selectedAlbumIds);final lastHash = getAlbumsLastHash();@@ -438,7 +425,6 @@ class AlbumHomeWidgetService {Future<List<int>> _getEffectiveSelectedAlbumIds([bool isBg = false]) async {final selectedAlbumIds = getSelectedAlbumIds();- // If no albums selected, use favorites as defaultif (selectedAlbumIds == null || selectedAlbumIds.isEmpty) {if (isBg) {await FavoritesService.instance.initFav();@@ -581,7 +567,6 @@ class AlbumHomeWidgetService {final albumName = randomEntry.value.$1;final String renderKey = '${albumId}_${randomAlbumFile.generatedID}';- // Skip if already rendered or previously failedif (!renderedKeys.add(renderKey) || failedKeys.contains(renderKey)) {attemptsCount++;continue;@@ -601,7 +586,6 @@ class AlbumHomeWidgetService {});if (renderResult != null) {- // Check for blockers again before continuingif (await _hasAnyBlockers()) {await clearWidget();return;@@ -610,7 +594,6 @@ class AlbumHomeWidgetService {renderedCount++;await _setTotalAlbums(renderedCount);- // Show update toast after first item is renderedif (renderedCount == 1) {await _refreshWidget(message: "First album fetched, updating widget");await updateAlbumsStatus(WidgetStatus.syncedPartially);@@ -618,7 +601,6 @@ class AlbumHomeWidgetService {attemptsCount++;} else {- // Track failed renders to avoid retrying known-bad filesrenderedKeys.remove(renderKey);failedKeys.add(renderKey);attemptsCount++;@@ -631,7 +613,6 @@ class AlbumHomeWidgetService {);}- // Update the hash to track changesfinal hash = _calculateHash(selectedAlbumIds);await setAlbumsLastHash(hash);diff --git a/mobile/apps/photos/lib/services/app_navigation_service.dart b/mobile/apps/photos/lib/services/app_navigation_service.dartindex c81eecda8f..2e9c9ce2d7 100644--- a/mobile/apps/photos/lib/services/app_navigation_service.dart+++ b/mobile/apps/photos/lib/services/app_navigation_service.dart@@ -5,22 +5,9 @@ import 'package:ente_pure_utils/ente_pure_utils.dart';import 'package:flutter/material.dart';import 'package:logging/logging.dart';-/// Routes pages onto the inner Photos app navigator.-///-/// The Photos app is currently wrapped by an outer `AppLock` `MaterialApp`-/// that owns the lock-screen navigator, while `EnteApp` creates the real app-/// `MaterialApp` inside it. External entry points such as widgets and-/// notifications can arrive while the app is backgrounded and locked. In those-/// cases, a random `BuildContext` may resolve to the outer lock navigator,-/// causing the destination page to be pushed on the wrong stack.-///-/// Use this service for navigation that must land on the actual app stack even-/// when the app is resuming from background, opening from a widget, or handling-/// a notification/deep link without a reliable inner-app `BuildContext`.-///-/// Do not use this service for ordinary in-app navigation where a local page-/// context is already available and intentionally scoped to the current nested-/// navigator tree.+// External entry points must use the inner Photos navigator. A BuildContext may+// resolve to AppLock's outer navigator while the app is locked or resuming.+// Ordinary in-app navigation should use its local context.class AppNavigationService {AppNavigationService._privateConstructor();@@ -35,12 +22,6 @@ class AppNavigationService {NavigatorState? get navigator => navigatorKey.currentState;- /// Pushes a page onto the inner app navigator.- ///- /// This waits briefly for the inner `MaterialApp` to finish rebuilding during- /// resume/unlock so callers from widget and notification handlers do not have- /// to coordinate navigator readiness themselves. Push requests are scheduled- /// in call order so stacked routes do not race each other during resume.Future<T?> pushPage<T extends Object>(Widget page, {bool forceCustomPageRoute = false,@@ -109,9 +90,7 @@ class AppNavigationService {);}- /// The inner navigator can be temporarily unavailable while Flutter is- /// restoring the app tree after resume or unlock. Wait on frame boundaries- /// so external launch handlers can navigate after the app tree is rebuilt.+ // The inner navigator may be unavailable while AppLock rebuilds after resume.Future<NavigatorState?> _waitForNavigator() async {final binding = WidgetsBinding.instance;for (var attempt = 0; attempt < 120; attempt++) {diff --git a/mobile/apps/photos/lib/services/date_parse_service.dart b/mobile/apps/photos/lib/services/date_parse_service.dartindex 223b6e4682..195b2edfe2 100644--- a/mobile/apps/photos/lib/services/date_parse_service.dart+++ b/mobile/apps/photos/lib/services/date_parse_service.dart@@ -215,11 +215,9 @@ class DateParseService {if (year < _MIN_YEAR || year > _MAX_YEAR) return PartialDate.empty;- // Try dd/mm/yyyy or dd-mm-yyyyif (p1 >= 1 && p1 <= 31 && p2 >= 1 && p2 <= 12) {return PartialDate(day: p1, month: p2, year: year);}- // Try mm/dd/yyyy or mm-dd-yyyyelse if (p1 >= 1 && p1 <= 12 && p2 >= 1 && p2 <= 31) {return PartialDate(day: p2, month: p1, year: year);}@@ -303,10 +301,8 @@ class DateParseService {month = _monthMap[monthNames.first];}- // Handle cases like "23 03" or "24 04 2024"if (numbers.isNotEmpty) {if (numbers.length == 3) {- // Assume dd mm yyyy if month name isn't presentfinal potentialDay = numbers[0];final potentialMonth = numbers[1];final potentialYear = numbers[2];@@ -322,7 +318,6 @@ class DateParseService {}}} else if (numbers.length == 2) {- // Assume dd mmfinal potentialDay = numbers[0];final potentialMonth = numbers[1];@@ -351,7 +346,6 @@ class DateParseService {}}- // If month was found by name, and we have numbers remainingif (month != null && numbers.isNotEmpty) {if (numbers.length == 2) {final n1 = numbers[0];diff --git a/mobile/apps/photos/lib/services/deduplication_service.dart b/mobile/apps/photos/lib/services/deduplication_service.dartindex 569c43f103..e77a391a47 100644--- a/mobile/apps/photos/lib/services/deduplication_service.dart+++ b/mobile/apps/photos/lib/services/deduplication_service.dart@@ -29,8 +29,6 @@ class DeduplicationService {}}- // Returns a list of DuplicateFiles, where each DuplicateFiles object contains- // a list of files that have the same hashFuture<List<DuplicateFiles>> _getDuplicateFiles() async {Map<int, int> uploadIDToSize = {};final bool hasFileSizes = await FilesService.instance.hasMigratedSizes();@@ -66,9 +64,7 @@ class DeduplicationService {final Map<String, Set<int>> livePhotoHashToCollectionsSet = {};final Set<int> processedFileIds = <int>{};for (final file in filteredFiles) {- // Note: For live photos, the zipped file size could be different if- // the files were uploaded from different devices. So, we dedupe live- // photos based on hash only.+ // Equivalent live photos can have different archive sizes across devices.if (file.fileType == FileType.livePhoto) {final key = '${file.hash}';if (!livePhotoHashToFilesMap.containsKey(key)) {diff --git a/mobile/apps/photos/lib/services/favorites_service.dart b/mobile/apps/photos/lib/services/favorites_service.dartindex e8ea941509..5b613bd47e 100644--- a/mobile/apps/photos/lib/services/favorites_service.dart+++ b/mobile/apps/photos/lib/services/favorites_service.dart@@ -43,8 +43,7 @@ class FavoritesService {_cachedFavoritesCollectionID != null &&_cachedFavoritesCollectionID == event.collectionID) {if (event.type == EventType.addedOrUpdated) {- // Note: This source check is a ugly hack because currently we- // don't have any event type related to remove from collection+ // There is no collection-removal event; the source identifies it.final bool isAdded = !event.source.contains("remove");_updateFavoriteFilesCache(event.updatedFiles, favFlag: isAdded);} else if (event.type == EventType.deletedFromEverywhere ||@@ -136,10 +135,6 @@ class FavoritesService {hashes[file.hash!] = file.uploadedFileID!;}} else if (file.localID != null || file.localID != "") {- /* Note: Favorite un-uploaded files- For such files, as we don't have uploaded IDs yet, we will cache- cache the local ID for showing the fav icon in the gallery- */localIDs.add(file.localID!);}}diff --git a/mobile/apps/photos/lib/services/file_magic_service.dart b/mobile/apps/photos/lib/services/file_magic_service.dartindex fc517f740e..30e907e055 100644--- a/mobile/apps/photos/lib/services/file_magic_service.dart+++ b/mobile/apps/photos/lib/services/file_magic_service.dart@@ -56,7 +56,6 @@ class FileMagicService {final Map<String, dynamic> update = {magicKeyVisibility: visibility};await _updateMagicData(files, update);if (visibility == visibleVisibility) {- // Force reload home gallery to pull in the now unarchived filesBus.instance.fire(ForceReloadHomeGalleryEvent("unarchivedFiles"));Bus.instance.fire(LocalPhotosUpdatedEvent(@@ -124,15 +123,12 @@ class FileMagicService {await _gateway.updatePublicMagicMetadata(updates.map((update) => update.request).toList(),);- // Remote has accepted these versions; commit the same state locally.for (final update in updates) {update.file..pubMmdEncodedJson = update.encodedJson..pubMagicMetadata = update.decodedMetadata..pubMmdVersion = update.nextVersion;}- // update the state of the selected file. Same file in other collection- // should be eventually synced after remote sync has completedawait _filesDB.insertMultiple(files);RemoteSyncService.instance.sync(silently: true).ignore();} on DioException catch (e) {@@ -180,7 +176,6 @@ class FileMagicService {await _gateway.updateMagicMetadata(updates.map((update) => update.request).toList(),);- // Each batch is committed locally only after its remote transaction.for (final update in updates) {update.file..mMdEncodedJson = update.encodedJson@@ -190,8 +185,6 @@ class FileMagicService {await _filesDB.insertMultiple(batch);}- // update the state of the selected file. Same file in other collection- // should be eventually synced after remote sync has completedRemoteSyncService.instance.sync(silently: true).ignore();} on DioException catch (e) {if (e.response != null && e.response!.statusCode == 409) {diff --git a/mobile/apps/photos/lib/services/filedata/model/file_data.dart b/mobile/apps/photos/lib/services/filedata/model/file_data.dartindex 050e090077..c144c302e8 100644--- a/mobile/apps/photos/lib/services/filedata/model/file_data.dart+++ b/mobile/apps/photos/lib/services/filedata/model/file_data.dart@@ -92,9 +92,6 @@ class RemoteFaceEmbedding {final int height;final int width;- /// Bitmask describing properties of this index (e.g. which runtime produced- /// it). Bits are defined in `ml_versions.dart`. Absent on the wire => 0- /// (legacy).final int flags;RemoteFaceEmbedding(@@ -106,7 +103,6 @@ class RemoteFaceEmbedding {this.flags = 0,});- // toJsonMap<String, dynamic> toJson() => {'faces': faces.map((x) => x.toJson()).toList(),'version': version,@@ -116,7 +112,6 @@ class RemoteFaceEmbedding {if (flags != 0) 'flags': flags,};- // fromJsonfactory RemoteFaceEmbedding.fromJson(Map<String, dynamic> json) {return RemoteFaceEmbedding(List<Face>.from(@@ -136,9 +131,6 @@ class RemoteClipEmbedding {final String client;final List<double> embedding;- /// Bitmask describing properties of this index (e.g. which runtime produced- /// it). Bits are defined in `ml_versions.dart`. Absent on the wire => 0- /// (legacy).final int flags;RemoteClipEmbedding(@@ -148,7 +140,6 @@ class RemoteClipEmbedding {this.flags = 0,});- // toJsonMap<String, dynamic> toJson() => {'embedding': embedding,'version': version,@@ -156,7 +147,6 @@ class RemoteClipEmbedding {if (flags != 0) 'flags': flags,};- // fromJsonfactory RemoteClipEmbedding.fromJson(Map<String, dynamic> json) {return RemoteClipEmbedding(parseAsDoubleList(json['embedding'] as List),@@ -167,7 +157,6 @@ class RemoteClipEmbedding {}}-// FDStatus represents the status of a file data entry.class FDStatus {final int fileID;final int userID;diff --git a/mobile/apps/photos/lib/services/filedata/model/response.dart b/mobile/apps/photos/lib/services/filedata/model/response.dartindex 557c2c1d5d..b356603229 100644--- a/mobile/apps/photos/lib/services/filedata/model/response.dart+++ b/mobile/apps/photos/lib/services/filedata/model/response.dart@@ -2,10 +2,7 @@ import "package:photos/services/filedata/model/file_data.dart";class FileDataResponse {final Map<int, FileDataEntity> data;- // fetchErrorFileIDs are the fileIDs for whom we failed failed to fetch embeddings- // from the storagefinal Set<int> fetchErrorFileIDs;- // pendingIndexFileIDs are the fileIDs that were never indexedfinal Set<int> pendingIndexFileIDs;FileDataResponse(this.data, {@@ -13,7 +10,6 @@ class FileDataResponse {required this.pendingIndexFileIDs,});- // empty responseFileDataResponse.empty(): data = {},fetchErrorFileIDs = {},diff --git a/mobile/apps/photos/lib/services/files_service.dart b/mobile/apps/photos/lib/services/files_service.dartindex 3fd6817250..8c0e0c903b 100644--- a/mobile/apps/photos/lib/services/files_service.dart+++ b/mobile/apps/photos/lib/services/files_service.dart@@ -70,6 +70,7 @@ class FilesService {}Future<FreeableSpaceInfo> getFreeableSpaceInfo({String? pathID}) async {+ // PhotoManager cannot delete iCloud shared-album assets.final excludeLocalIDs = await _getICloudSharedAlbumAssetIDs();FreeableFileIDs ids;final bool hasMigratedSize = await FilesService.instance.hasMigratedSizes();@@ -94,8 +95,6 @@ class FilesService {return FreeableSpaceInfo(ids.localIDs, size);}- /// Returns iCloud shared album paths on iOS.- /// Returns empty list on non-iOS platforms.Future<List<AssetPathEntity>> _getICloudSharedAlbumPaths() async {if (!Platform.isIOS) return [];return PhotoManager.getAssetPathList(@@ -110,9 +109,6 @@ class FilesService {);}- /// Returns local asset IDs that belong to iCloud shared albums on iOS.- /// These assets cannot be deleted via PhotoManager and must be excluded- /// from the free-up-space operation.Future<Set<String>> _getICloudSharedAlbumAssetIDs() async {final paths = await _getICloudSharedAlbumPaths();final Set<String> sharedIDs = {};@@ -127,8 +123,6 @@ class FilesService {return sharedIDs;}- /// Returns path IDs of iCloud shared albums on iOS.- /// Returns empty set on non-iOS platforms.Future<Set<String>> getICloudSharedAlbumPathIDs() async {final paths = await _getICloudSharedAlbumPaths();return paths.map((p) => p.id).toSet();@@ -203,8 +197,6 @@ class FilesService {LatLng location,) async {for (EnteFile remoteFile in uploadedFiles) {- // discard files not owned by user and also dedupe already processed- // filesif (remoteFile.ownerID != _config.getUserID()! ||fileIDToUpdateMetadata.containsKey(remoteFile.uploadedFileID!)) {continue;@@ -226,14 +218,11 @@ class FilesService {}}- // Note: this method is not used anywhere, but it is kept for future- // reference when we add bulk EditTime featureFuture<void> bulkEditTime(List<EnteFile> files, EditTimeSource source) async {final ListMatch<EnteFile> result = files.splitMatch((element) => element.isUploaded,);final List<EnteFile> uploadedFiles = result.matched;- // editTime For LocalFilesfinal List<EnteFile> localOnlyFiles = result.unmatched;for (EnteFile localFile in localOnlyFiles) {final timeResult = _parseTime(localFile, source);@@ -246,8 +235,6 @@ class FilesService {final List<EnteFile> remoteFilesToUpdate = [];final Map<int, Map<String, int>> fileIDToUpdateMetadata = {};for (EnteFile remoteFile in uploadedFiles) {- // discard files not owned by user and also dedupe already processed- // filesif (remoteFile.ownerID != _config.getUserID()! ||fileIDToUpdateMetadata.containsKey(remoteFile.uploadedFileID!)) {continue;@@ -291,14 +278,8 @@ class FilesService {}enum EditTimeSource {- // parse the time from fileNamefileName,- // parse the time from exif data of file.exif,- // use the which user provided as inputmanualFix,- // adjust the time of selected photos by +/- time.- // required for cases when the original device in which photos were taken- // had incorrect time (quite common with physical cameras)manualAdjusted,}diff --git a/mobile/apps/photos/lib/services/filter/collection_ignore.dart b/mobile/apps/photos/lib/services/filter/collection_ignore.dartindex f7f50a7df2..8d3edeef18 100644--- a/mobile/apps/photos/lib/services/filter/collection_ignore.dart+++ b/mobile/apps/photos/lib/services/filter/collection_ignore.dart@@ -1,10 +1,6 @@import 'package:photos/models/file/file.dart';import "package:photos/services/filter/filter.dart";-// CollectionsOrHashIgnoreFilter will filter out all files that are in present in the-// given collections collectionIDs. This is useful for filtering out files that are in archive-// or hidden collections from home page and other places. Based on flag, it will also filter out-// shared files if the user already as another file with the same hash.class CollectionsAndSavedFileFilter extends Filter {final Set<int> collectionIDs;final bool ignoreSavedFiles;@@ -40,9 +36,6 @@ class CollectionsAndSavedFileFilter extends Filter {@overridebool filter(EnteFile file) {if (!file.isUploaded) {- // if file is in one of the ignored collections, filter it out. This check- // avoids showing un-uploaded files that are going to be uploaded to one of- // the ignored collectionsif (file.collectionID != null &&collectionIDs.contains(file.collectionID!)) {return false;@@ -55,8 +48,6 @@ class CollectionsAndSavedFileFilter extends Filter {if (ignoreSavedFiles &&file.ownerID != ownerID &&(file.hash ?? '').isNotEmpty) {- // if the file is shared and the user already has a file with the same hash- // then filter it out by returning falsereturn !ownedFileHashes.contains(file.hash!);}return true;diff --git a/mobile/apps/photos/lib/services/filter/db_filters.dart b/mobile/apps/photos/lib/services/filter/db_filters.dartindex 2f6ac3768a..7e1476052d 100644--- a/mobile/apps/photos/lib/services/filter/db_filters.dart+++ b/mobile/apps/photos/lib/services/filter/db_filters.dart@@ -9,17 +9,12 @@ import "package:photos/services/filter/upload_ignore.dart";import "package:photos/services/ignored_files_service.dart";class DBFilterOptions {- // typically used for filtering out all files which are present in hidden- // (searchable files result) or archived collections or both (ex: home- // timeline)Set<int>? ignoredCollectionIDs;bool dedupeUploadID;bool hideIgnoredForUpload;- // If true, shared files that are already saved in the users account will be ignored.bool ignoreSavedFiles;bool onlyUploadedFiles;- // If true, files owned by other users or uploaded by other users will be ignored.bool ignoreSharedItems = false;DBFilterOptions({diff --git a/mobile/apps/photos/lib/services/hidden_service.dart b/mobile/apps/photos/lib/services/hidden_service.dartindex 2ee19374dd..bc8d627ba0 100644--- a/mobile/apps/photos/lib/services/hidden_service.dart+++ b/mobile/apps/photos/lib/services/hidden_service.dart@@ -23,7 +23,6 @@ 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;@@ -51,16 +50,10 @@ class HiddenCleanupItem {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;@@ -104,7 +97,6 @@ extension HiddenService on CollectionsService {Future<Collection> clubAllDefaultHiddenToOne(List<Collection> allDefaultHidden,) async {- // select first collection as default hidden where all files will be clubbedfinal Collection defaultHidden = allDefaultHidden.first;for (Collection hidden in allDefaultHidden) {try {@@ -135,8 +127,6 @@ extension HiddenService on CollectionsService {return defaultHidden;}- // getUncategorizedCollection will return the uncategorized collection- // for the given userFuture<Collection> getUncategorizedCollection() async {if (cachedUncategorizedCollection != null) {return cachedUncategorizedCollection!;@@ -202,8 +192,8 @@ extension HiddenService on CollectionsService {continue;}- // Determine destination: files from hidden collections go to default- // hidden collection, others go to uncategorized+ // Files removed from hidden collections stay hidden; others move to+ // Uncategorized.final Collection? sourceCollection = getCollectionByID(collectionID);final bool isSourceHidden = sourceCollection?.isHidden() ?? false;final int destinationCollectionID;@@ -260,8 +250,6 @@ extension HiddenService on CollectionsService {continue;}final Collection? c = getCollectionByID(entry.key);- // if the collection is not owned by the user, remove the file from the- // collectionif (c != null && !c.isOwner(userID)) {await removeFromCollection(entry.key, entry.value);} else {@@ -397,8 +385,6 @@ 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) {@@ -411,9 +397,6 @@ extension HiddenService on CollectionsService {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) {@@ -426,8 +409,6 @@ extension HiddenService on CollectionsService {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 {final int userID = config.getUserID()!;final hiddenCollectionIds = getHiddenCollectionIds();@@ -446,7 +427,6 @@ extension HiddenService on CollectionsService {final allCollectionIdsHiddenFilesExistsIn = await filesDB.getCollectionIDsForUploadedFileIDs(uploadedHiddenFileIds);- // Check if any collection is non-hiddenfor (final collectionId in allCollectionIdsHiddenFilesExistsIn) {if (hiddenCollectionIds.contains(collectionId)) {continue;@@ -461,8 +441,6 @@ extension HiddenService on CollectionsService {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();@@ -482,14 +460,12 @@ extension HiddenService on CollectionsService {uploadedHiddenFileIds,);- // Build map of uploadedFileID -> hiddenCollectionIDfinal 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 filefileToHiddenCollection.putIfAbsent(file.uploadedFileID!,() => collectionID,@@ -499,7 +475,6 @@ extension HiddenService on CollectionsService {}}- // Create cleanup items for non-hidden collectionsfinal cleanupItems = <HiddenCleanupItem>[];for (final entry in filesByCollectionID.entries) {final collectionID = entry.key;@@ -514,14 +489,13 @@ extension HiddenService on CollectionsService {}for (final file in entry.value) {- // Files are already filtered by ownerID at DB level, but double-checkif (file.ownerID != userID) {continue;}final hiddenCollectionID = fileToHiddenCollection[file.uploadedFileID];if (hiddenCollectionID == null) {- continue; // Shouldn't happen+ continue;}cleanupItems.add(@@ -537,13 +511,6 @@ extension HiddenService on CollectionsService {return cleanupItems;}- /// Cleans up hidden files by moving them from non-hidden collections to their- /// hidden collection.- /// Only own files are processed.- /// For files whose hidden collection is owned by the user,- /// they are moved back to their original hidden collection.- /// For files whose hidden collection is not owned by the user,- /// they are moved to the user's default hidden collection.Future<void> cleanupHiddenFiles(BuildContext context) async {final dialog = createProgressDialog(context, context.strings.pleaseWait);await dialog.show();@@ -570,14 +537,12 @@ extension HiddenService on CollectionsService {);}- // Group actionable items by (fromCollectionID, toCollectionID) for batch movesfinal Map<(int, int), List<EnteFile>> moveGroups = {};for (final item in actionableItems) {final key = (item.fromCollectionID, item.toCollectionID);moveGroups.putIfAbsent(key, () => []).add(item.file);}- // Execute movesfor (final entry in moveGroups.entries) {final (fromCollectionID, toCollectionID) = entry.key;final files = entry.value;@@ -589,7 +554,6 @@ extension HiddenService on CollectionsService {);}- // Fire events for UI refreshfinal allMovedFiles = actionableItems.map((e) => e.file).toList();if (allMovedFiles.isNotEmpty) {Bus.instance.fire(diff --git a/mobile/apps/photos/lib/services/home_widget_service.dart b/mobile/apps/photos/lib/services/home_widget_service.dartindex 5acb7ba2db..304586e52b 100644--- a/mobile/apps/photos/lib/services/home_widget_service.dart+++ b/mobile/apps/photos/lib/services/home_widget_service.dart@@ -22,37 +22,25 @@ import 'package:photos/ui/settings/widgets/people_widget_settings.dart';import 'package:synchronized/synchronized.dart';enum WidgetStatus {- // notSynced means the widget is not initialized or has no datanotSynced,- // partially synced means some images were synced but not all- // this can happen if some widgets were not installed but we did a sync regardless- // or if the sync fails midwaysyncedPartially,- // we purposefully set widget to empty, widget had datasyncedEmpty,- // all widgets were synced successfullysyncedAll,}-/// Service to manage home screen widgets across the application-/// Handles widget initialization, updates, and interaction with platform-specific widget APIsclass HomeWidgetService {- // Constantsstatic const double THUMBNAIL_SIZE = 512.0;static const String WIDGET_DIRECTORY = 'home_widget';static const int WIDGET_IMAGE_LIMIT_V1 = 50;static const int WIDGET_IMAGE_LIMIT_MINIMAL = 5;- // URI schemes for different widget typesstatic const String MEMORY_WIDGET_SCHEME = 'memorywidget';static const String PEOPLE_WIDGET_SCHEME = 'peoplewidget';static const String ALBUM_WIDGET_SCHEME = 'albumwidget';- // Query parameter keysstatic const String GENERATED_ID_PARAM = 'generatedId';static const String MAIN_KEY_PARAM = 'mainKey';- // Widget data keysstatic const String DATA_SUFFIX = '_data';static const String UPLOADED_FILE_ID_KEY = 'uploadedFileID';static const String WIDGET_HIDE_TITLE_FLAGS_KEY = 'widgetHideTitleFlags';@@ -153,17 +141,14 @@ class HomeWidgetService {int? uploadedFileID,) async {try {- // Get thumbnail datafinal thumbnail = await getThumbnail(file);if (thumbnail == null) {_logger.warning("Failed to get thumbnail for file ${file.displayName}");return false;}- // Get appropriate directory for widget assetsfinal String widgetDirectory = await _getWidgetStorageDirectory();- // Save thumbnail to filefinal String thumbnailPath ='$widgetDirectory/$WIDGET_DIRECTORY/$key.png';final File thumbnailFile = File(thumbnailPath);@@ -175,12 +160,10 @@ class HomeWidgetService {await thumbnailFile.writeAsBytes(thumbnail);await setData(key, thumbnailPath);- // Format date for displayfinal subText = await SmartMemoriesService.getDateFormattedLocale(creationTime: file.creationTime!,);- // Create metadatafinal Map<String, dynamic> metadata = {"title": title,"subText": subText,@@ -189,7 +172,6 @@ class HomeWidgetService {UPLOADED_FILE_ID_KEY: ?uploadedFileID,};- // Save metadata in platform-specific formatawait _saveWidgetMetadata(key, metadata);return true;@@ -205,14 +187,13 @@ class HomeWidgetService {) async {final String dataKey = key + DATA_SUFFIX;+ // iOS stores maps directly; Android expects a JSON string.if (Platform.isIOS) {- // iOS can store the map directlyawait hw.HomeWidget.saveWidgetData<Map<String, dynamic>>(dataKey,metadata,);} else {- // Android needs the data as a JSON stringawait hw.HomeWidget.saveWidgetData<String>(dataKey, jsonEncode(metadata));}}@@ -252,7 +233,6 @@ class HomeWidgetService {}}- /// Handle app launch from a widgetFuture<void> onLaunchFromWidget(Uri? uri) async {if (uri == null) {_logger.warning("Widget launch failed: URI is null");@@ -268,7 +248,6 @@ class HomeWidgetService {final bool isConfigureRoute =uri.host == 'configure' || generatedId == null;- // Route to appropriate handler based on widget schemeswitch (uri.scheme) {case MEMORY_WIDGET_SCHEME:if (isConfigureRoute) {diff --git a/mobile/apps/photos/lib/services/ignored_files_service.dart b/mobile/apps/photos/lib/services/ignored_files_service.dartindex 5d8ca0cab5..85eff03e1e 100644--- a/mobile/apps/photos/lib/services/ignored_files_service.dart+++ b/mobile/apps/photos/lib/services/ignored_files_service.dart@@ -19,7 +19,6 @@ class IgnoredFilesService {Future<Map<String, String>>? _idsToReasonMap;Future<Map<String, String>> get idToIgnoreReasonMap async {- // lazily instantiate the db the first time it is accessed_idsToReasonMap ??= _loadIDsToReasonMap();return _idsToReasonMap!;}@@ -35,11 +34,7 @@ class IgnoredFilesService {return _db.insertMultiple(ignoredFiles);}- // shouldSkipUpload takes IDs to ignore and file for which it will return- // whether either true or false. This helper method takes ignoredIDs as input- // to avoid making it async in nature.- // This syntax is intentional as we want to ensure that ignoredIDs are loaded- // from the DB before calling this method.+ // The caller supplies a fully loaded map so this remains synchronous.bool shouldSkipUpload(Map<String, String> idToReasonMap, EnteFile file) {final id = _getIgnoreID(file.localID, file.deviceFolder, file.title);if (id != null && id.isNotEmpty) {@@ -64,19 +59,14 @@ class IgnoredFilesService {return shouldSkipUpload(ignoredID, file);}- // removeIgnoredMappings is used to remove the ignore mapping for the given- // set of files so that they can be uploaded.Future<void> removeIgnoredMappings(List<EnteFile> files) async {final List<IgnoredFile> ignoredFiles = [];final Set<String> idsToRemoveFromCache = {};final Map<String, String> currentlyIgnoredIDs = await idToIgnoreReasonMap;for (final file in files) {- // check if upload is not skipped for file. If not, no need to remove- // any mappingif (!shouldSkipUpload(currentlyIgnoredIDs, file)) {continue;}- // _shouldSkipUpload checks for null ignoreIDfinal id = _getIgnoreID(file.localID, file.deviceFolder, file.title)!;idsToRemoveFromCache.add(id);ignoredFiles.add(@@ -106,8 +96,7 @@ class IgnoredFilesService {if (id != null) {if (Platform.isIOS &&iFile.reason == InvalidReason.sourceFileMissing.name) {- // ignoreSourceFileMissing error on iOS as the file fetch from iCloud might have failed,- // but the file might be available later+ // An unavailable iCloud file may become available later.continue;}result[id] = iFile.reason;@@ -128,14 +117,7 @@ class IgnoredFilesService {return _getIgnoreID(file.localID, file.deviceFolder, file.title);}- // _getIgnoreID will return null if don't have sufficient information- // to ignore the file based on the platform. Uploads from web or files shared to- // end usually don't have local id.- // For Android: It returns deviceFolder-title as ID for Android.- // For iOS, it returns localID as localID is uuid and the title or deviceFolder (aka- // album name) can be missing due to various reasons.String? _getIgnoreID(String? localID, String? deviceFolder, String? title) {- // file was not uploaded from mobile deviceif (localID == null || localID.isEmpty) {return null;}diff --git a/mobile/apps/photos/lib/services/location_service.dart b/mobile/apps/photos/lib/services/location_service.dartindex 24bf05a540..8a2028dc11 100644--- a/mobile/apps/photos/lib/services/location_service.dart+++ b/mobile/apps/photos/lib/services/location_service.dart@@ -26,8 +26,7 @@ class LocationService {final Logger _logger = Logger((LocationService).toString());final Computer _computer = Computer.shared();- // If the discovery section is loaded before the cities are loaded, then we- // need to refresh the discovery section after the cities are loaded.+ // Refresh discovery if it ran before the city index loaded.bool reloadLocationDiscoverySection = false;static const _kCitiesKdTreeRemotePath =@@ -73,7 +72,6 @@ class LocationService {List<EnteFile> allFiles,String query,) async {- // check if the cities where not loaded when discovery section was loadedif (allFiles.isNotEmpty && _cities.isEmpty && query.isEmpty) {reloadLocationDiscoverySection = true;}@@ -114,11 +112,8 @@ class LocationService {Location centerPoint,double radius,) async {- //The area enclosed by the location tag will be a circle on a 3D spherical- //globe and an ellipse on a 2D Mercator projection (2D map)- //a & b are the semi-major and semi-minor axes of the ellipse- //Converting the unit from kilometers to degrees for a and b as that is- //the unit on the caritesian plane+ // A circular radius on the globe maps to an ellipse in Mercator+ // coordinates. Store its axes in degrees for latitude/longitude checks.try {final a =@@ -164,7 +159,6 @@ class LocationService {}}- /// returns [lat, lng]List<String>? convertLocationToDMS(Location centerPoint) {if (centerPoint.latitude == null || centerPoint.longitude == null) {return null;@@ -189,7 +183,6 @@ class LocationService {return [degrees, minutes, seconds];}- ///Will only update if there is a change in the locationTag's propertiesFuture<void> updateLocationTag({required LocalEntity<LocationTag> locationTagEntity,double? newRadius,@@ -202,7 +195,6 @@ class LocationService {final name = newName ?? locationTagEntity.item.name;final locationTag = locationTagEntity.item;- //Exit if there is no change in locationTag's propertiesif (radius == locationTag.radius &¢erPoint == locationTag.centerPoint &&name == locationTag.name) {@@ -533,13 +525,11 @@ Map<City, List<EnteFile>> getCityResults(Map args) {final x = city.lat - fileLocation.latitude!;final y = city.lng - fileLocation.longitude!;- // Bounding box pre-filter: quick rejection for points clearly outsideif (x.abs() > city.a || y.abs() > city.b) continue;- // Ellipse containment check using pre-computed squared parametersif ((x * x) / city.aSquare + (y * y) / city.bSquare <= 1) {results.putIfAbsent(city, () => []).add(file);- break; // Stop searching once a file is matched with a city+ break;}}}@@ -603,31 +593,27 @@ bool isFileInsideLocationTag(return false;}+// Returns kilometers.double calculateDistance(Location point1, Location point2) {final lat1 = point1.latitude! * (pi / 180);final lat2 = point2.latitude! * (pi / 180);final long1 = point1.longitude! * (pi / 180);final long2 = point2.longitude! * (pi / 180);- // Difference in latitude and longitudefinal dLat = lat2 - lat1;final dLong = long2 - long1;- // Haversine formulafinal a =sin(dLat / 2) * sin(dLat / 2) +cos(lat1) * cos(lat2) * sin(dLong / 2) * sin(dLong / 2);- // Angular distance in radiansfinal c = 2 * atan2(sqrt(a), sqrt(1 - a));- return earthRadius * c; // Distance in kilometers+ return earthRadius * c;}-///The area bounded by the location tag becomes more elliptical with increase-///in the magnitude of the latitude on the caritesian plane. When latitude is-///0 degrees, the ellipse is a circle with a = b = r. When latitude incrases,-///the major axis (a) has to be scaled by the secant of the latitude.+// Mercator stretches longitude by sec(latitude), so a circle's horizontal+// radius must scale with latitude.double scaleFactor(double lat) {return 1 / cos(lat * (pi / 180));}@@ -638,17 +624,10 @@ class City {final double lat;final double lng;- /// Pre-computed ellipse parameter for location containment check.- /// a = (defaultCityRadius * scaleFactor(lat)) / kilometersPerDegree+ // Ellipse semi-axes in degrees and their precomputed squares.final double a;-- /// Pre-computed squared ellipse parameter: a * afinal double aSquare;-- /// Pre-computed ellipse parameter: defaultCityRadius / kilometersPerDegreefinal double b;-- /// Pre-computed squared ellipse parameter: b * bfinal double bSquare;City({@@ -726,8 +705,6 @@ class GPSData {}}- //At this point, latSign and longSign will only be null if latRef and longRef- //is of invalid format.if (latSign == null || longSign == null) {return null;}diff --git a/mobile/apps/photos/lib/services/magic_cache_service.dart b/mobile/apps/photos/lib/services/magic_cache_service.dartindex 8f2ffdeee5..eecd325d8d 100644--- a/mobile/apps/photos/lib/services/magic_cache_service.dart+++ b/mobile/apps/photos/lib/services/magic_cache_service.dart@@ -37,7 +37,6 @@ class MagicCache {MagicCache(this.title, this.fileUploadedIDs, {this.fileLocalIntIDs});- // Get map of uploadID to index in fileUploadedIDsMap<int, int> get fileIdToPositionMap {if (_fileIdToPositionMap == null) {_fileIdToPositionMap = {};@@ -234,8 +233,7 @@ class MagicCacheService {static const _kSearchTabIndex = 3;static const _kBackgroundUpdateDebounce = Duration(minutes: 5);- /// Delay is for cache update to be done not during app init, during which a- /// lot of other things are happening.+ // Avoid competing with other startup work.static const _kCacheUpdateDelay = Duration(seconds: 10);final SharedPreferences _prefs;@@ -622,9 +620,6 @@ class MagicCacheService {}}- ///Returns non-empty magic results from magicPromptsData- ///Length is number of prompts, can be less if there are not enough non-empty- ///resultsFuture<List<MagicCache>> _nonEmptyMagicResults(List<Prompt> magicPromptsData,) async {diff --git a/mobile/apps/photos/lib/services/memories/photo_selector.dart b/mobile/apps/photos/lib/services/memories/photo_selector.dartindex 03f85ef7c4..3ddb093786 100644--- a/mobile/apps/photos/lib/services/memories/photo_selector.dart+++ b/mobile/apps/photos/lib/services/memories/photo_selector.dart@@ -10,68 +10,35 @@ import "package:photos/models/ml/face/face_with_embedding.dart";import "package:photos/models/ml/vector.dart";import "package:photos/services/location_service.dart";-// ----------------------------------------------------------------------------// Strategy enums-// -----------------------------------------------------------------------------/// How to distribute photo selection across groups to ensure variety.enum SelectionDistribution {- /// No grouping. Iterate the scored list greedily.none,-- /// Divide into N equal time-buckets and pick one per bucket.- /// Narrow each bucket to top [preNarrowTopPercent] before picking.timeBuckets,-- /// Group by year, round-robin through years (recent first).yearRoundRobin,}-/// How to pick the winner from a set of candidates.enum SelectionPick {- /// Take the highest-scored candidate that passes filters.ranked,-- /// Pick the candidate geographically farthest from already-selected photos.geographicFarthest,}-/// How to sort the final selection.enum SelectionSort {- /// Oldest first.chronological,-- /// Newest first.reverseChronological,}-// ----------------------------------------------------------------------------// Configuration-// -----------------------------------------------------------------------------/// All the parameters that control how [PhotoSelector.select] works.class SelectionConfig {final int targetSize;final bool isLocalGalleryMode;final Map<int, EmbeddingVector> fileIDToImageEmbedding;- /// Pre-computed score per file-ID. Higher = better.- /// For time/trip memories this is typically a combined CLIP + face score.- /// For people memories this is CLIP nostalgia only.final Map<int, double> scores;final SelectionDistribution distribution;final SelectionPick pick;final SelectionSort sort;- /// For [SelectionDistribution.timeBuckets]: fraction of each bucket to keep- /// after scoring (e.g. 0.3 = top 30%). `null` means keep all.- /// When less than 50% of a bucket has embeddings this is auto-disabled.final double? preNarrowTopPercent;- /// For [SelectionDistribution.yearRoundRobin]: if true, skip the- /// near-duplicate check on the first round (to guarantee at least one- /// photo per year even when all photos look similar).final bool skipDuplicateCheckOnFirstRound;const SelectionConfig({@@ -87,22 +54,10 @@ class SelectionConfig {});}-// ----------------------------------------------------------------------------// PhotoSelector-// ----------------------------------------------------------------------------class PhotoSelector {static const clipSimilarImageThreshold = 0.80;static const minimumMemoryTimeGap = Duration(minutes: 10);- // ------------------------------------------------------------------------ // Unified selection entry point- // ------------------------------------------------------------------------- /// Selects up to [config.targetSize] memories from [memories], applying the- /// distribution, filtering, picking and sorting strategies in [config].- ///- /// Returns [memories] unchanged if the list is already small enough.static Future<List<Memory>> select(List<Memory> memories,SelectionConfig config,@@ -126,17 +81,11 @@ class PhotoSelector {return _sortResult(result, config.sort);}- // ------------------------------------------------------------------------ // Distribution strategies- // ------------------------------------------------------------------------- /// Flat selection: sort by score descending, greedily iterate.static List<Memory> _selectFlat(List<Memory> memories,SelectionConfig config,) {final fileCount = memories.length;- // Sort by score descending.memories.sort((a, b) {final aID = memoryFileIdFromMemory(a,@@ -178,13 +127,10 @@ class PhotoSelector {return selected;}- /// Time-bucket selection: divide into N equal chronological buckets, pick- /// one per bucket using nostalgia narrowing + geographic or ranked pick.static List<Memory> _selectTimeBuckets(List<Memory> memories,SelectionConfig config,) {- // Filter to memories with creation time and sort chronologically.final sorted = memories.where((m) => m.file.creationTime != null).toList()..sort((a, b) => a.file.creationTime!.compareTo(b.file.creationTime!));@@ -217,7 +163,6 @@ class PhotoSelector {final finalSelection = <Memory>[];for (final bucket in buckets) {- // Score within bucket.final bucketFileIDs = bucket.map((m) => memoryFileIdFromMemory(@@ -231,9 +176,9 @@ class PhotoSelector {config.fileIDToImageEmbedding,bucketFileIDs,);+ // Score narrowing is unreliable when fewer than half have embeddings.final bool littleEmbeddings = bucketVectors.length < bucket.length * 0.5;- // Sort bucket by score descending.bucket.sort((a, b) {final aID = memoryFileIdFromMemory(a,@@ -246,7 +191,6 @@ class PhotoSelector {return (config.scores[bID] ?? 0.0).compareTo(config.scores[aID] ?? 0.0);});- // Optionally narrow to top N%.List<Memory> candidates;if (!littleEmbeddings && config.preNarrowTopPercent != null) {final keep = max(@@ -263,7 +207,6 @@ class PhotoSelector {continue;}- // Filter against already-selected photos.if (finalSelection.isNotEmpty) {final filteredCandidates = excludeNearDuplicates(candidates,@@ -278,7 +221,6 @@ class PhotoSelector {}if (candidates.isEmpty) continue;- // Pick the winner.final winner = _pickCandidate(candidates, finalSelection, config.pick);finalSelection.add(winner);}@@ -337,15 +279,12 @@ class PhotoSelector {return finalSelection;}- /// Year-round-robin selection: group by year, sort each year by score,- /// round-robin through years taking one at a time.static List<Memory> _selectYearRoundRobin(List<Memory> memories,SelectionConfig config,) {final fileCount = memories.length;- // Group by year.final yearToFiles = <int, List<Memory>>{};for (final mem in memories) {final year = DateTime.fromMicrosecondsSinceEpoch(@@ -354,7 +293,6 @@ class PhotoSelector {yearToFiles.putIfAbsent(year, () => []).add(mem);}- // Sort each year's list by score descending.for (final yearFiles in yearToFiles.values) {yearFiles.sort((a, b) {final aID = memoryFileIdFromMemory(@@ -370,7 +308,7 @@ class PhotoSelector {}final years = yearToFiles.keys.toList()- ..sort((a, b) => b.compareTo(a)); // Recent years first+ ..sort((a, b) => b.compareTo(a));final selected = <Memory>[];final selectedCreationTimes = <int>[];@@ -432,17 +370,12 @@ class PhotoSelector {}}round++;- if (round > fileCount) break; // safety+ if (round > fileCount) break;}return selected;}- // ------------------------------------------------------------------------ // Picking strategies- // ------------------------------------------------------------------------- /// Picks one candidate from the list based on the pick strategy.static Memory _pickCandidate(List<Memory> candidates,List<Memory> alreadySelected,@@ -483,11 +416,6 @@ class PhotoSelector {}}- // ------------------------------------------------------------------------ // Shared filtering- // ------------------------------------------------------------------------- /// Returns true if [mem] passes time-spacing and near-duplicate filters.static bool _passesFilters(Memory mem,List<Memory> selected,@@ -539,11 +467,6 @@ class PhotoSelector {return memories;}- // ------------------------------------------------------------------------ // Legacy entry points (delegate to select())- // ------------------------------------------------------------------------- /// Creates a curated selection of memories for the People memories.static Future<List<Memory>> bestSelectionPeople(List<Memory> memories, {int? prefferedSize,@@ -556,7 +479,6 @@ class PhotoSelector {final int targetSize = prefferedSize ?? 10;if (memories.length <= targetSize) return memories;- // Pre-compute nostalgia scores.final Map<int, double> scores = {};for (final mem in memories) {final fileID = memoryFileIdFromMemory(@@ -596,12 +518,6 @@ class PhotoSelector {}}- /// Returns the best selection for time and trip memories.- ///- /// When [mlEnabled] is false, scoring and CLIP near-duplicate filtering are- /// skipped; candidates are shuffled randomly and distributed across years or- /// chronologically based solely on creation time, keeping only the- /// time-spacing filter.static Future<List<Memory>> bestSelection(List<Memory> memories, {int? prefferedSize,@@ -637,13 +553,11 @@ class PhotoSelector {);if (fileID == null) continue;- // CLIP scorefinal embedding = fileIDToImageEmbedding[fileID];final clipScore = embedding != null? embedding.vector.dot(clipPositiveTextVector): 0.0;- // Face score: named faces = 10, unnamed = 1int faceCount = 0;final faces = fileIdToFaces[fileID];if (faces != null) {@@ -692,7 +606,6 @@ class PhotoSelector {),);} else {- // Multiple years: adjust target size for many years.if (prefferedSize == null && (allYears.length * 2) > 10) {targetSize = allYears.length * 3;if (fileCount < targetSize) return memories;@@ -714,15 +627,6 @@ class PhotoSelector {}}- // ------------------------------------------------------------------------ // ML-free selection path- // ------------------------------------------------------------------------- /// Produces a time-distributed selection without using any ML signals:- /// - No scoring (face counts / CLIP nostalgia).- /// - No CLIP near-duplicate filtering.- /// - Within each year / bucket, candidates are shuffled with fresh- /// randomness and then filtered by the time-spacing rule.static List<Memory> _bestSelectionNoMl(List<Memory> memories, {required int targetSize,@@ -748,8 +652,6 @@ class PhotoSelector {(distributionOverride == null && allYears.length <= 1)) {sortedChronologically = List<Memory>.from(withCreationTime)..sort((a, b) => a.file.creationTime!.compareTo(b.file.creationTime!));- // Single year / time-buckets override: distribute evenly across the- // chronological range and shuffle within each bucket.return _pickAcrossTimeBuckets(sortedChronologically,targetSize: effectiveTargetSize,@@ -764,8 +666,6 @@ class PhotoSelector {}}- // Multiple years: round-robin through recent-years-first, shuffling each- // year's list with fresh randomness.final yearToFiles = <int, List<Memory>>{};for (final mem in withCreationTime) {final year = DateTime.fromMicrosecondsSinceEpoch(@@ -879,10 +779,6 @@ class PhotoSelector {return selected;}- // ------------------------------------------------------------------------ // Utility functions (shared building blocks)- // ------------------------------------------------------------------------static List<EmbeddingVector> getEmbeddingsForFileIDs(Map<int, EmbeddingVector> fileIDToImageEmbedding,Set<int> fileIDs,diff --git a/mobile/apps/photos/lib/services/memories_cache_service.dart b/mobile/apps/photos/lib/services/memories_cache_service.dartindex 8937f1aed7..e50d19acde 100644--- a/mobile/apps/photos/lib/services/memories_cache_service.dart+++ b/mobile/apps/photos/lib/services/memories_cache_service.dart@@ -49,8 +49,7 @@ class MemoriesCacheService {static const _shouldUpdateCacheKey = "memories.shouldUpdateCache";static const _tripMemoryCarryForwardLimit = kTripSurfaceSlots;- /// Delay is for cache update to be done not during app init, during which a- /// lot of other things are happening.+ // Avoid competing with other startup work.static const _kCacheUpdateDelay = Duration(seconds: 20);final SharedPreferences _prefs;@@ -77,11 +76,7 @@ class MemoriesCacheService {Future.delayed(_kCacheUpdateDelay, () {_checkIfTimeToUpdateCache();- // Self-schedule cache updates independently of runAllML, so that users- // with ML disabled still get their memories cache refreshed on the- // configured cadence. Safe to call unconditionally: updateCache() is a- // no-op when neither _shouldUpdate nor forced is true, and the lock- // serialises against concurrent invocations from runAllML.+ // Schedule independently of ML so non-ML memories also refresh.unawaited(updateCache());_memoriesDB.clearMemoriesSeenBeforeTime(DateTime.now()@@ -858,7 +853,6 @@ class MemoriesCacheService {w?.log("gotten old cache");final MemoriesCache newCache = _processOldCache(oldCache);w?.log("processed old cache");- // calculate memories for this period and for the next periodfinal now = DateTime.now();final next = now.add(kMemoriesUpdateFrequency);final mlReady = await _isMlReady();@@ -896,9 +890,8 @@ class MemoriesCacheService {final nowEntries = nowResult.memories.map((memory) => _toCacheMemory(memory, now, localIdToIntId)).toList();- // Splice carried-forward trip entries into the natural trip slot so- // the UI keeps showing trips in their usual position (after- // onThisDay/people) instead of jumping to the front of the row.+ // Keep carried trips with other trips instead of moving them to the+ // front.int tripInsertIdx = nowEntries.indexWhere((e) => e.type == MemoryType.trips,);@@ -1103,8 +1096,7 @@ class MemoriesCacheService {if (memory.type != MemoryType.trips) {return false;}- // Drop legacy keyless trips during migration so they cannot coexist with- // newly recomputed keyed trips for the same trip.+ // Drop old trips without keys to avoid duplicates after migration.final tripKey = memory.tripKey;return tripKey != null && tripKey.isNotEmpty;}@@ -1129,17 +1121,13 @@ class MemoriesCacheService {Bus.instance.fire(MemoriesChangedEvent());}- /// WARNING: Use for testing only, TODO: lau: remove later+ // WARNING: Use for testing only, TODO: lau: remove laterFuture<MemoriesCache> debugCacheForTesting() async {final oldCache = await _readCacheFromDisk();final MemoriesCache newCache = _processOldCache(oldCache);return newCache;}- /// WARNING: Use for testing only.- ///- /// Computes the full smart memories set with debug surfacing enabled without- /// mutating the persisted memories cache.Future<List<SmartMemory>> debugGetAllMemories({DateTime? calcTime}) async {return _memoriesUpdateLock.synchronized(() async {final mlReady = await _isMlReady();diff --git a/mobile/apps/photos/lib/services/memory_home_widget_service.dart b/mobile/apps/photos/lib/services/memory_home_widget_service.dartindex ca39a124d8..c6ab8c84c3 100644--- a/mobile/apps/photos/lib/services/memory_home_widget_service.dart+++ b/mobile/apps/photos/lib/services/memory_home_widget_service.dart@@ -11,7 +11,6 @@ import 'package:photos/services/sync/local_sync_service.dart';import 'package:shared_preferences/shared_preferences.dart';class MemoryHomeWidgetService {- // Constantsstatic const String SELECTED_LAST_YEAR_MEMORIES_KEY ="selectedLastYearMemoriesHW";static const String SELECTED_ML_MEMORIES_KEY = "selectedMLMemoriesHW";@@ -24,16 +23,13 @@ class MemoryHomeWidgetService {static const String TOTAL_MEMORIES_KEY = "totalMemories";static const int MAX_MEMORIES_LIMIT = 50;- // Singleton patternstatic final MemoryHomeWidgetService instance =MemoryHomeWidgetService._privateConstructor();MemoryHomeWidgetService._privateConstructor();- // Propertiesfinal Logger _logger = Logger((MemoryHomeWidgetService).toString());SharedPreferences get _prefs => ServiceLocator.instance.prefs;- // Preference getters and settersbool? hasLastYearMemoriesSelected() {return _prefs.getBool(SELECTED_LAST_YEAR_MEMORIES_KEY);}@@ -58,7 +54,6 @@ class MemoryHomeWidgetService {await _prefs.setBool(SELECTED_ON_THIS_DAY_MEMORIES_KEY, selectedMemories);}- // Public methodsFuture<void> initMemoryHomeWidget() async {await HomeWidgetService.instance.computeLock.synchronized(() async {if (await _hasAnyBlockers()) {@@ -152,16 +147,13 @@ class MemoryHomeWidgetService {await _refreshMemoriesWidget();}- // Private methodsFuture<bool> _hasAnyBlockers() async {- // Check if first import is completedfinal hasCompletedFirstImport = LocalSyncService.instance.hasCompletedFirstImportOrBypassed();if (!hasCompletedFirstImport) {return true;}- // Check if memories are enabledfinal areMemoriesShown = memoriesCacheService.showAnyMemories;if (!areMemoriesShown) {return true;@@ -171,20 +163,15 @@ class MemoryHomeWidgetService {}Future<void> _refreshMemoriesWidget() async {- // only refresh if widget was synced without issuesif (await countHomeWidgets() == 0) return;await _refreshWidget(message: "Refreshing from existing memory set");}Future<bool> _shouldUpdateWidgetCache() async {- // Update widget cache when memories were changedif (isMemoryChanged() == true) return true;final memoriesStatus = getMemoriesStatus();- // update widget cache if- // - memories not synced- // - memories synced partially but now home widget is presentreturn memoriesStatus == WidgetStatus.notSynced ||memoriesStatus == WidgetStatus.syncedPartially &&await countHomeWidgets() > 0;@@ -196,7 +183,6 @@ class MemoryHomeWidgetService {bool? lastYearValue = hasLastYearMemoriesSelected();bool? onThisDayValue = getOnThisDayMemoriesSelected();- // If ML is enabled then we use Smart memories by default, otherwise date based memoriesif (isMLEnabled) {lastYearValue ??= false;onThisDayValue ??= false;@@ -258,7 +244,6 @@ class MemoryHomeWidgetService {await HomeWidgetService.instance.setData(TOTAL_MEMORIES_KEY, total);}- // _updateMemoriesWidgetCache will return false if no memories were cachedFuture<bool> _updateMemoriesWidgetCache() async {// TODO: Can update the method to fetch directly max limit random memoriesfinal memoriesWithFiles = await _getMemoriesWithFiles();@@ -306,7 +291,6 @@ class MemoryHomeWidgetService {});if (renderResult != null) {- // Check for blockers again before continuingif (await _hasAnyBlockers()) {await clearWidget();return true;@@ -314,7 +298,6 @@ class MemoryHomeWidgetService {await _setTotalMemories(renderedCount);- // Show update toast after first item is renderedif (renderedCount == 1) {await _refreshWidget(message: "First memory fetched, updating widget",diff --git a/mobile/apps/photos/lib/services/people_home_widget_service.dart b/mobile/apps/photos/lib/services/people_home_widget_service.dartindex 0a90ecb32c..ebddcc04da 100644--- a/mobile/apps/photos/lib/services/people_home_widget_service.dart+++ b/mobile/apps/photos/lib/services/people_home_widget_service.dart@@ -18,7 +18,6 @@ import 'package:shared_preferences/shared_preferences.dart';import 'package:synchronized/synchronized.dart';class PeopleHomeWidgetService {- // Constantsstatic const String SELECTED_PEOPLE_KEY = "selectedPeopleHW";static const String PEOPLE_LAST_HASH_KEY = "peopleLastHash";static const String ANDROID_CLASS_NAME = "EntePeopleWidgetProvider";@@ -28,17 +27,14 @@ class PeopleHomeWidgetService {static const String TOTAL_PEOPLE_KEY = "totalPeople";static const int MAX_PEOPLE_LIMIT = 50;- // Singleton patternstatic final PeopleHomeWidgetService instance =PeopleHomeWidgetService._privateConstructor();PeopleHomeWidgetService._privateConstructor();- // Propertiesfinal Logger _logger = Logger((PeopleHomeWidgetService).toString());SharedPreferences get _prefs => ServiceLocator.instance.prefs;final peopleChangedLock = Lock();- // Public methodsList<String>? getSelectedPeople() {return _prefs.getStringList(SELECTED_PEOPLE_KEY);}@@ -215,19 +211,16 @@ class PeopleHomeWidgetService {return true;}- // Check if first import is completedfinal hasCompletedFirstImport = LocalSyncService.instance.hasCompletedFirstImportOrBypassed();if (!hasCompletedFirstImport) {return true;}- // Check ML consentif (isLocalGalleryMode || !hasGrantedMLConsent) {return true;}- // Check if selected people or hash existfinal peopleIds = await _getEffectiveSelections();final hash = await _calculateHash(peopleIds);@@ -241,20 +234,15 @@ class PeopleHomeWidgetService {}Future<void> _refreshPeopleWidget() async {- // only refresh if widget was synced without issuesif (await countHomeWidgets() == 0) return;await _refreshWidget(message: "Refreshing from existing people set");}Future<bool> _shouldUpdateWidgetCache() async {- // Update widget cache when people were changedif (getPeopleChanged() == true) {return true;}- // update widget cache if- // - people not synced- // - people synced partially but now home widget is presentfinal peopleStatus = getPeopleStatus();return peopleStatus == WidgetStatus.notSynced ||peopleStatus == WidgetStatus.syncedPartially &&@@ -360,14 +348,12 @@ class PeopleHomeWidgetService {});if (renderResult != null) {- // Check for blockers again before continuingif (await _hasAnyBlockers()) {return;}await _setTotalPeople(renderedCount);- // Show update toast after first item is renderedif (renderedCount == 1) {await _refreshWidget(message: "First person fetched, updating widget",diff --git a/mobile/apps/photos/lib/services/remote_assets_service.dart b/mobile/apps/photos/lib/services/remote_assets_service.dartindex d66e8894bb..0e17b4b5b5 100644--- a/mobile/apps/photos/lib/services/remote_assets_service.dart+++ b/mobile/apps/photos/lib/services/remote_assets_service.dart@@ -63,7 +63,6 @@ class RemoteAssetsService {return file.path;}- ///Returns asset if the remote asset is new compared to the local copy of itFuture<File?> getAssetIfUpdated(String remotePath, {String? expectedSha256,@@ -125,14 +124,9 @@ class RemoteAssetsService {}String _urlToFileName(String url) {- // Remove the protocol part (http:// or https://)String fileName = url.replaceAll(RegExp(r'https?://'), '')- // Replace all non-alphanumeric characters except for underscores and periods with an underscore.replaceAll(RegExp(r'[^\w\.]'), '_');- // Optionally, you might want to trim the resulting string to a certain length-- // Replace periods with underscores for better readability, if desiredfileName = fileName.replaceAll('.', '_');return fileName;diff --git a/mobile/apps/photos/lib/services/search_service.dart b/mobile/apps/photos/lib/services/search_service.dartindex cd6716759e..cf5e0c5d82 100644--- a/mobile/apps/photos/lib/services/search_service.dart+++ b/mobile/apps/photos/lib/services/search_service.dart@@ -90,7 +90,7 @@ class SearchService {_localPhotosUpdatedSubscription = Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {- // only invalidate, let the load happen on demand+ // Invalidate only; reload on demand._cachedFilesFuture = null;_cachedFilesForSearch = null;_cachedFilesForHierarchicalSearch = null;@@ -441,8 +441,6 @@ class SearchService {unawaited(memoriesCacheService.clearMemoriesCache());}- // getFilteredCollectionsWithThumbnail removes deleted or archived or- // collections which don't have a file from search resultFuture<List<AlbumSearchResult>> getCollectionSearchResults(String query,) async {@@ -1032,8 +1030,6 @@ class SearchService {}if (showNoLocationTag) {_logger.info("finding photos with no location tag");- // find files that have location but the file's location is not inside- // any location tagfinal noLocationTagFiles = allFiles.where((file) {if (!file.hasLocation) {return false;@@ -1092,8 +1088,8 @@ class SearchService {);}}- //todo: remove this later, this hack is for interval+external evaluation- // for suggestions+ // TODO: Remove the __city override used by interval and external+ // suggestion evaluation.final allCitiesSearch = query == '__city';if (allCitiesSearch) {query = '';@@ -1102,7 +1098,6 @@ class SearchService {final List<City> sortedByResultCount = results.keys.toList()..sort((a, b) => results[b]!.length.compareTo(results[a]!.length));for (final city in sortedByResultCount) {- // If the location tag already exists for a city, don't add it againif (!locationTagNames.contains(city.city)) {final a =(defaultCityRadius * scaleFactor(city.lat)) / kilometersPerDegree;@@ -1385,7 +1380,6 @@ class SearchService {}}- // get sorted personId by files countfinal sortedPersonIds = personIdToFiles.keys.toList()..sort((a, b) =>@@ -1472,7 +1466,6 @@ class SearchService {final String personID = clusterIDToPersonID[clusterId]!;final PersonEntity? p = personIdToPerson[personID];if (p != null) {- // This should not be possible since it should be handled in the above loop, logging just in case_logger.severe("`getAllFace`: Something unexpected happened, Cluster $clusterId should not have person id $personID",Exception(@@ -1480,8 +1473,6 @@ class SearchService {),);} else {- // This should not happen, means a clusterID is still assigned to a personID of a person that no longer exists- // Logging the error and deleting the clusterID to personID mapping_logger.severe("`getAllFace`: Cluster $clusterId should not have person id ${clusterIDToPersonID[clusterId]}, deleting the mapping",Exception(@@ -1585,8 +1576,6 @@ class SearchService {tagToItemsMap[tag]!.add(file);}}- // If the location tag already exists for a city, do not consider- // it for the city suggestionsif (!hasLocationTag) {filesWithNoLocTag.add(file);}@@ -1607,7 +1596,6 @@ class SearchService {LocationScreenStateProvider(entry.key,LocationScreen(- //this is SearchResult.heroTag()tagPrefix:"${ResultType.location.toString()}_${entry.key.item.name}",),@@ -1623,41 +1611,7 @@ class SearchService {);}}- // Add the found base locations from the location/memories service- // TODO: lau: Add base location names- // if (limit == null || tagSearchResults.length < limit) {- // for (final BaseLocation base in locationService.baseLocations) {- // final a = (baseRadius * scaleFactor(base.location.latitude!)) /- // kilometersPerDegree;- // const b = baseRadius / kilometersPerDegree;- // tagSearchResults.add(- // GenericSearchResult(- // ResultType.location,- // "Base",- // base.files,- // onResultTap: (ctx) {- // showAddLocationSheet(- // ctx,- // base.location,- // name: "Base",- // radius: baseRadius,- // );- // },- // hierarchicalSearchFilter: LocationFilter(- // locationTag: LocationTag(- // name: "Base",- // radius: baseRadius,- // centerPoint: base.location,- // aSquare: a * a,- // bSquare: b * b,- // ),- // occurrence: kMostRelevantFilter,- // matchedUploadedIDs: filesToUploadedFileIDs(base.files),- // ),- // ),- // );- // }- // }+ // TODO: Add named base locations to search results.if (limit == null || tagSearchResults.length < limit) {final results = await locationService.getFilesInCity(@@ -1720,7 +1674,6 @@ class SearchService {if (parsedDate.isEmpty) {return searchResults;}- // Handle month-year queriesif (parsedDate.day == null &&parsedDate.month != null &&parsedDate.year != null) {@@ -1751,7 +1704,6 @@ class SearchService {);}}- // Handle day-month queries (with or without year)else if (parsedDate.day != null && parsedDate.month != null) {final int day = parsedDate.day!;final int month = parsedDate.month!;@@ -1842,7 +1794,7 @@ class SearchService {return searchResults;}- /// For debug purposes only, don't use this in production!+ // Debug only; do not use in production.Future<List<GenericSearchResult>> smartMemories(BuildContext context,int? limit,@@ -1852,7 +1804,6 @@ class SearchService {if (limit != null) {memories = await memoriesCacheService.getMemories();} else {- // await two seconds to let new page load firstawait Future.delayed(const Duration(seconds: 1));if (!context.mounted) return const [];final DateTime? pickedTime = await showDatePicker(@@ -1878,7 +1829,6 @@ class SearchService {);}cache.baseLocations.addAll(memoriesResult.baseLocations);- // memories = memoriesResult.memories;final tempCachePath =(await getTemporaryDirectory()).path +"/cache/test/memories_cache_test";diff --git a/mobile/apps/photos/lib/services/smart_albums_service.dart b/mobile/apps/photos/lib/services/smart_albums_service.dartindex 0d6b74a7a2..175f3c6f1a 100644--- a/mobile/apps/photos/lib/services/smart_albums_service.dart+++ b/mobile/apps/photos/lib/services/smart_albums_service.dart@@ -128,7 +128,6 @@ class SmartAlbumsService {final infoMap = config.infoMap;- // Person Id key mapped to updatedAt valuefinal updatedAtMap = await entityService.getUpdatedAts(EntityType.cgroup,config.personIDs.toList(),@@ -139,7 +138,6 @@ class SmartAlbumsService {var newConfig = config;for (final personId in config.personIDs) {- // compares current updateAt with last added file's updatedAtif (updatedAtMap[personId] == null ||infoMap[personId] != null &&(updatedAtMap[personId]! <= infoMap[personId]!.updatedAt)) {@@ -203,8 +201,6 @@ class SmartAlbumsService {final infoMap = Map<String, PersonInfo>.from(config?.infoMap ?? {});for (final personId in personIDs) {- // skip if personId already exists in infoMap- // only relevant when config exists beforeif (infoMap.containsKey(personId)) continue;infoMap[personId] = (updatedAt: 0, addedFiles: {});}@@ -241,7 +237,6 @@ class SmartAlbumsService {String getId({required int collectionId, required int userId}) =>"sa_${userId}_$collectionId";- /// Wrapper method for entityService.addOrUpdate that handles cache refreshFuture<LocalEntityData> _addOrUpdateEntity(EntityType type,Map<String, dynamic> jsonMap, {diff --git a/mobile/apps/photos/lib/services/smart_memories_service.dart b/mobile/apps/photos/lib/services/smart_memories_service.dartindex 0ed88f9dc5..e62620de45 100644--- a/mobile/apps/photos/lib/services/smart_memories_service.dart+++ b/mobile/apps/photos/lib/services/smart_memories_service.dart@@ -140,7 +140,6 @@ class SmartMemoriesService {);}- // One general method to get all memories, which calls on internal methods for each separate memory typeFuture<MemoriesResult> calcSmartMemories(DateTime now,MemoriesCache oldCache, {@@ -918,14 +917,13 @@ class SmartMemoriesService {dev.log('arguments from indirect data calculated $t');dev.log('starting actual memory calculations ${DateTime.now()}');dev.log("All files length at start: ${allFileIdsToFile.length} $t");- // Keep one canonical file store and track cross-category deduction by- // file ID so full-source memories do not require a second file set.+ // Some memory types need every file, so track used files by ID instead of+ // removing them from the source map.final fullSourceFiles = allFileIdsToFile.values;final usedMemoryFileIds = <int>{};final List<SmartMemory> memories = [];- // On this day memoriesfinal onThisDayFiles = _collectAvailableFiles(allFileIdsToFile,usedMemoryFileIds,@@ -947,7 +945,6 @@ class SmartMemoriesService {"${_remainingFilesCount(allFileIdsToFile, usedMemoryFileIds)} $t",);- // People memories (ML only)if (mlEnabled) {final peopleMemories = await _getPeopleResults(allFileIdsToFile,@@ -981,7 +978,6 @@ class SmartMemoriesService {dev.log('ML disabled, skipping people memories $t');}- // Trip memoriesfinal (tripMemories, bases) = await _getTripsResults(tripSourceFiles: fullSourceFiles,allFileIdsToFile: allFileIdsToFile,@@ -1009,7 +1005,6 @@ class SmartMemoriesService {"${_remainingFilesCount(allFileIdsToFile, usedMemoryFileIds)} $t",);- // Clip memories (ML only)if (mlEnabled) {final clipMemories = await _getClipResults(fullSourceFiles,@@ -1035,7 +1030,6 @@ class SmartMemoriesService {dev.log('ML disabled, skipping clip memories $t');}- // Time memoriesfinal timeFiles = _collectAvailableFiles(allFileIdsToFile,usedMemoryFileIds,@@ -1063,7 +1057,6 @@ class SmartMemoriesService {"${_remainingFilesCount(allFileIdsToFile, usedMemoryFileIds)} $t",);- // Filler memoriesfinal fillerFiles = _collectAvailableFiles(allFileIdsToFile,usedMemoryFileIds,@@ -1111,7 +1104,6 @@ class SmartMemoriesService {final List<SmartMemory> memories = [];- // On this day memoriesfinal onThisDayFiles = _collectAvailableFiles(allFileIdsToFile,usedMemoryFileIds,@@ -1131,7 +1123,6 @@ class SmartMemoriesService {], isLocalGalleryMode: isLocalGalleryMode);}- // Filler memoriesfinal fillerFiles = _collectAvailableFiles(allFileIdsToFile,usedMemoryFileIds,@@ -1334,7 +1325,6 @@ class SmartMemoriesService {}final collections = CollectionsService.instance.getCollectionsForUI();- // Names of collections to excludeconst excludedNames = {'screenshot','whatsapp',diff --git a/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart b/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dartindex 5653fe4194..2af653e2b1 100644--- a/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart+++ b/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart@@ -85,22 +85,16 @@ class _TripSurfaceCandidate {}class TripMemoriesCalculatorV2 {- // Temporal gap to split photos into separate time windows.static const _maxTemporalGapDays = 15;- // Spatial radius for clustering photos within a temporal block.static const _tripClusterRadius = 25.0;- // Max hop distance for chaining clusters into road trips.static const _chainHopDistance = 800.0;- // Base location overlap check radius.static const _baseOverlapRadius = 10.0;- // Secondary merge radius for nearby home clusters.static const _baseMergeRadius = 1.5;- // Base evidence thresholds.static const _minBasePhotos = 10;static const _minBaseActiveDays = 10;static const _minBaseActiveWeeks = 6;@@ -109,23 +103,16 @@ class TripMemoriesCalculatorV2 {static const _baseDensityWindowDays = 120;static const _minBaseActiveDaysInWindow = 12;- // Trip duration bounds (in days).static const _minTripDays = 2;static const _maxTripDays = 30;- // Minimum photos for a valid trip.static const _minTripPhotos = 20;- // Minimum photos for a cluster to participate in chain merging.- // Smaller clusters are kept as standalone candidates (and typically- // filtered out by _isValidTrip), preventing stray photos from being- // absorbed into legitimate trips.+ // Keep small clusters separate so stray photos cannot join valid trips.static const _minChainClusterPhotos = 5;- // Max temporal gap (in days) for merging clusters or trips.static const _mergeWindowDays = 2;- // Max spatial distance (in km) for merging trips across temporal blocks.static const _mergeMaxDistance = 25.0;static const _tripDisplayDuration = Duration(days: 10);@@ -155,8 +142,6 @@ class TripMemoriesCalculatorV2 {.microsecondsSinceEpoch;final cutOffTime = currentTime.subtract(const Duration(days: 365));- // ββ Phase 1: Base location detection ββ-final baseLocations = _detectBaseLocations(allFiles,isLocalGalleryMode: isLocalGalleryMode,@@ -168,8 +153,6 @@ class TripMemoriesCalculatorV2 {seenTimes,);- // ββ Phase 2: Trip detection ββ-final filesWithLocation = allFiles.where((f) => f.hasLocation).toList()..sort((a, b) => a.creationTime!.compareTo(b.creationTime!));@@ -177,15 +160,12 @@ class TripMemoriesCalculatorV2 {return (<TripMemory>[], baseLocations);}- // Step 2a: Filter base photos out of the trip stream before- // temporal segmentation, so repeated visits to the same place remain- // separated by time spent back at base.+ // Returning to a base separates otherwise nearby trips.final temporalBlocks = _segmentAwayFilesByTime(filesWithLocation,baseLocations,);- // Step 2b: Spatial clustering + chain merging within each blockfinal tripCandidates = <TripMemory>[];for (final block in temporalBlocks) {var spatialClusters = _clusterByLocation(@@ -219,10 +199,8 @@ class TripMemoriesCalculatorV2 {}}- // Step 2c: Merge trips across temporal blocks (same location, close time)final mergedTrips = _mergeNearbyTrips(tripCandidates);- // Step 2d: Final validationfinal validTrips = mergedTrips.where((t) =>@@ -232,8 +210,6 @@ class TripMemoriesCalculatorV2 {.map(_ensureTripKey).toList();- // ββ Phase 3: Surface selection ββ-final List<TripMemory> memoryResults = [];if (surfaceAll) {@@ -276,8 +252,6 @@ class TripMemoriesCalculatorV2 {);}- // ββ Base location detection ββ-static List<BaseLocation> _detectBaseLocations(Iterable<EnteFile> allFiles, {required bool isLocalGalleryMode,@@ -323,8 +297,6 @@ class TripMemoriesCalculatorV2 {return baseLocations;}- // ββ Temporal segmentation ββ-static List<List<EnteFile>> _segmentAwayFilesByTime(List<EnteFile> sortedFiles,List<BaseLocation> baseLocations,@@ -367,8 +339,6 @@ class TripMemoriesCalculatorV2 {return blocks;}- // ββ Spatial clustering within a temporal block ββ-static List<_LocationCluster> _clusterByLocation(Iterable<EnteFile> files, {required double radius,@@ -417,10 +387,6 @@ class TripMemoriesCalculatorV2 {return mergedClusters;}- // ββ Chain merge for road trips ββ-- /// Merges spatial clusters within the same temporal block if they form- /// a chronological chain with hops <= [_chainHopDistance].static List<_LocationCluster> _mergeChainedClusters(List<_LocationCluster> clusters,) {@@ -474,8 +440,6 @@ class TripMemoriesCalculatorV2 {return [...merged, ...tooSmall];}- // ββ Trip validation ββ-static bool _isValidTrip(List<EnteFile> files,Location location,@@ -549,8 +513,6 @@ class TripMemoriesCalculatorV2 {return false;}- // ββ Merge trips across temporal blocks ββ-static List<TripMemory> _mergeNearbyTrips(List<TripMemory> trips) {final sortedTrips = List<TripMemory>.from(trips)..sort((a, b) => a.firstCreationTime!.compareTo(b.firstCreationTime!));@@ -870,8 +832,6 @@ class TripMemoriesCalculatorV2 {return b.trip.averageCreationTime().compareTo(a.trip.averageCreationTime());}- // ββ Surface all (debug mode) ββ-static Future<(List<TripMemory>, List<BaseLocation>)> _surfaceAll(List<TripMemory> memoryResults,List<BaseLocation> baseLocations,@@ -944,8 +904,6 @@ class TripMemoriesCalculatorV2 {return (memoryResults, baseLocations);}- // ββ Surface scheduled (production mode) ββ-static Future<(List<TripMemory>, List<BaseLocation>)> _surfaceScheduled(List<TripMemory> memoryResults,List<BaseLocation> baseLocations,diff --git a/mobile/apps/photos/lib/services/social_service.dart b/mobile/apps/photos/lib/services/social_service.dartindex 6562f1379b..d70880194f 100644--- a/mobile/apps/photos/lib/services/social_service.dart+++ b/mobile/apps/photos/lib/services/social_service.dart@@ -8,9 +8,6 @@ import 'package:photos/models/social/api_responses.dart';import 'package:photos/service_locator.dart';import 'package:photos/services/collections_service.dart';-/// Service for social features (comments and reactions).-///-/// Handles API calls and encryption/decryption using collection keys.class SocialService {SocialService._();static final instance = SocialService._();@@ -24,32 +21,17 @@ class SocialService {static const _alphabet ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';- /// Reaction type padding length before encryption.- /// Ensures all encrypted reactions have the same ciphertext length.+ // Fixed-length padding keeps reaction ciphertexts the same size.static const _reactionPadLength = 100;- /// Generates a new comment ID in the format: cmt_ + 21 char nanoidString generateCommentID() {return '$_commentPrefix${customAlphabet(_alphabet, _commentIDLength)}';}- /// Generates a new reaction ID in the format: rct_ + 21 char nanoidString generateReactionID() {return '$_reactionPrefix${customAlphabet(_alphabet, _reactionIDLength)}';}- // ============ Comments API ============-- /// Creates a new comment on the server.- ///- /// [collectionID] - The collection this comment belongs to- /// [cipher] - The encrypted comment text (base64)- /// [nonce] - The encryption nonce (base64)- /// [fileID] - Optional file ID if commenting on a file- /// [parentCommentID] - Optional parent comment ID for replies- /// [id] - Optional comment ID; generated if not provided- ///- /// Returns the comment ID (server-assigned or the provided one)Future<String> createComment({required int collectionID,required String cipher,@@ -69,11 +51,6 @@ class SocialService {);}- /// Updates an existing comment.- ///- /// [commentID] - The comment ID to update- /// [cipher] - The new encrypted comment text (base64)- /// [nonce] - The new encryption nonce (base64)Future<void> updateComment({required String commentID,required String cipher,@@ -86,19 +63,10 @@ class SocialService {);}- /// Deletes a comment (soft delete on server).Future<void> deleteComment(String commentID) async {return socialGateway.deleteComment(commentID);}- /// Fetches comments diff for a collection.- ///- /// [collectionID] - The collection to fetch comments from- /// [sinceTime] - Only fetch comments updated after this timestamp- /// [limit] - Maximum number of comments to fetch (default 1000, max 2000)- /// [fileID] - Optional filter for comments on a specific file- ///- /// Returns [CommentsDiffResponse] with comments and hasMore flagFuture<CommentsDiffResponse> fetchCommentsDiff({required int collectionID,int? sinceTime,@@ -113,18 +81,6 @@ class SocialService {);}- // ============ Reactions API ============-- /// Creates or updates a reaction (upsert).- ///- /// [collectionID] - The collection this reaction belongs to- /// [cipher] - The encrypted reaction type (base64, exactly 156 bytes)- /// [nonce] - The encryption nonce (base64)- /// [fileID] - Optional file ID if reacting to a file- /// [commentID] - Optional comment ID if reacting to a comment- /// [id] - Optional reaction ID; generated if not provided- ///- /// Returns the reaction IDFuture<String> upsertReaction({required int collectionID,required String cipher,@@ -144,20 +100,10 @@ class SocialService {);}- /// Deletes a reaction (soft delete on server).Future<void> deleteReaction(String reactionID) async {return socialGateway.deleteReaction(reactionID);}- /// Fetches reactions diff for a collection.- ///- /// [collectionID] - The collection to fetch reactions from- /// [sinceTime] - Only fetch reactions updated after this timestamp- /// [limit] - Maximum number of reactions to fetch (default 1000, max 2000)- /// [fileID] - Optional filter for reactions on a specific file- /// [commentID] - Optional filter for reactions on a specific comment- ///- /// Returns [ReactionsDiffResponse] with reactions and hasMore flagFuture<ReactionsDiffResponse> fetchReactionsDiff({required int collectionID,int? sinceTime,@@ -174,36 +120,14 @@ class SocialService {);}- // ============ Latest Updates API ============-- /// Fetches latest update timestamps for all collections accessible to the- /// user.- ///- /// Returns per-collection timestamps for comments, reactions, and anonymous- /// profiles. Use this to determine which collections need syncing.Future<LatestUpdatesResponse> fetchLatestUpdates() async {return socialGateway.fetchLatestUpdates();}- /// Fetches anonymous profiles for a collection.- ///- /// Returns encrypted profile data that needs to be decrypted with the- /// collection key.Future<AnonProfilesResponse> fetchAnonProfiles(int collectionID) async {return socialGateway.fetchAnonProfiles(collectionID);}- // ============ Unified/Social API ============-- /// Fetches both comments and reactions in a single call.- ///- /// [collectionID] - The collection to fetch social data from- /// [commentsSinceTime] - Only fetch comments updated after this timestamp- /// [reactionsSinceTime] - Only fetch reactions updated after this timestamp- /// [limit] - Maximum number of items per type (default 1000, max 2000)- /// [fileID] - Optional filter for items on a specific file- ///- /// Returns [SocialDiffResponse] with comments, reactions, and hasMore flagsFuture<SocialDiffResponse> fetchSocialDiff({required int collectionID,int? commentsSinceTime,@@ -220,18 +144,10 @@ class SocialService {);}- /// Fetches comment and reaction counts for all collections.- ///- /// Returns a map of collectionID -> countFuture<Map<int, int>> fetchCounts() async {return socialGateway.fetchCounts();}- // ============ Encryption/Decryption ============-- /// Encrypts comment text with the collection key.- ///- /// Returns a record of (cipher, nonce) as base64 strings.({String cipher, String nonce}) encryptComment(String text,int collectionID,@@ -252,9 +168,7 @@ class SocialService {);}- /// Decrypts comment cipher to plaintext.- ///- /// Returns the decrypted text, or empty string if decryption fails.+ // Returns an empty string when decryption fails.String decryptComment(String? cipher, String? nonce, int collectionID) {if (cipher == null || nonce == null || cipher.isEmpty || nonce.isEmpty) {return '';@@ -280,10 +194,6 @@ class SocialService {}}- /// Encrypts reaction type with the collection key.- ///- /// The reaction type is padded to fixed length before encryption,- /// ensuring consistent ciphertext length.({String cipher, String nonce}) encryptReaction(String reactionType,int collectionID,@@ -292,7 +202,6 @@ class SocialService {collectionID,);- // Pad reaction type to fixed lengthfinal padded = _padReactionType(reactionType);final paddedBytes = utf8.encode(padded);@@ -307,10 +216,7 @@ class SocialService {);}- /// Decrypts reaction cipher to reaction type.- ///- /// Returns the decrypted reaction type (with padding removed),- /// or empty string if decryption fails.+ // Returns an empty string when decryption fails.String decryptReaction(String? cipher, String? nonce, int collectionID) {if (cipher == null || nonce == null || cipher.isEmpty || nonce.isEmpty) {return '';@@ -329,7 +235,6 @@ class SocialService {nonceBytes,);- // Remove null byte paddingfinal decoded = utf8.decode(decrypted);return _unpadReactionType(decoded);} catch (e) {@@ -338,7 +243,6 @@ class SocialService {}}- /// Pads a reaction type to fixed length with null bytes.String _padReactionType(String reactionType) {if (reactionType.length >= _reactionPadLength) {return reactionType.substring(0, _reactionPadLength);@@ -346,7 +250,6 @@ class SocialService {return reactionType.padRight(_reactionPadLength, '\x00');}- /// Removes null byte padding from reaction type.String _unpadReactionType(String padded) {final nullIndex = padded.indexOf('\x00');if (nullIndex == -1) {@@ -355,10 +258,7 @@ class SocialService {return padded.substring(0, nullIndex);}- /// Decrypts anonymous profile data.- ///- /// Returns the decrypted display-name string, or empty string if decryption- /// fails.+ // Returns an empty string when decryption fails.String decryptAnonProfile(String? cipher, String? nonce, int collectionID) {if (cipher == null || nonce == null || cipher.isEmpty || nonce.isEmpty) {return '';diff --git a/mobile/apps/photos/lib/services/social_sync_service.dart b/mobile/apps/photos/lib/services/social_sync_service.dartindex d9c07ac617..1aca10be47 100644--- a/mobile/apps/photos/lib/services/social_sync_service.dart+++ b/mobile/apps/photos/lib/services/social_sync_service.dart@@ -9,9 +9,6 @@ import 'package:photos/models/social/comment.dart';import 'package:photos/models/social/reaction.dart';import 'package:photos/services/social_service.dart';-/// Service for syncing social data (comments and reactions) with the server.-///-/// Handles diff-based sync, encryption/decryption, and local storage.class SocialSyncService {SocialSyncService._();static final instance = SocialSyncService._();@@ -26,9 +23,6 @@ class SocialSyncService {bool _isSyncing = false;- /// Syncs social data for a single collection.- ///- /// Uses diff-based sync with separate sinceTime for comments and reactions.Future<void> syncCollection(int collectionID) async {int normalizeSinceTime(int syncTime) => syncTime > 0 ? syncTime - 1 : 0;int commentsSinceTime = normalizeSinceTime(@@ -45,7 +39,6 @@ class SocialSyncService {bool hasMoreComments = true;bool hasMoreReactions = true;- // Sync using unified endpoint with separate since timeswhile (hasMoreComments || hasMoreReactions) {final response = await _api.fetchSocialDiff(collectionID: collectionID,@@ -53,7 +46,6 @@ class SocialSyncService {reactionsSinceTime: reactionsSinceTime,);- // Process commentsif (response.comments.isNotEmpty) {final comments = _decryptComments(response.comments, collectionID);await _db.upsertComments(comments);@@ -65,7 +57,6 @@ class SocialSyncService {}}- // Process reactionsif (response.reactions.isNotEmpty) {final reactions = _decryptReactions(response.reactions, collectionID);await _db.upsertReactions(reactions);@@ -84,12 +75,10 @@ class SocialSyncService {break;}- // Update since times for paginationcommentsSinceTime = maxCommentsUpdatedAt;reactionsSinceTime = maxReactionsUpdatedAt;}- // Update sync timesif (maxCommentsUpdatedAt > await _db.getCommentsSyncTime(collectionID)) {await _db.setCommentsSyncTime(collectionID, maxCommentsUpdatedAt);}@@ -105,9 +94,6 @@ class SocialSyncService {}}- /// Syncs reactions for a specific file in a collection.- ///- /// Useful for on-demand sync when viewing a file.Future<void> syncFileReactions(int collectionID, int fileID) async {try {final response = await _api.fetchReactionsDiff(@@ -126,9 +112,6 @@ class SocialSyncService {}}- /// Syncs both comments and reactions for a specific file in a collection.- ///- /// Useful for on-demand sync when opening comments screen.Future<void> syncFileSocialData(int collectionID, int fileID) async {try {final response = await _api.fetchSocialDiff(@@ -154,11 +137,6 @@ class SocialSyncService {}}- /// Syncs social data for all collections that have new updates.- ///- /// 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<bool> syncAllSharedCollections() async {if (_isSyncing) {_logger.info('Sync already in progress, skipping');@@ -173,7 +151,6 @@ class SocialSyncService {return false;}- // Get latest update timestamps from serverfinal latestUpdates = await _api.fetchLatestUpdates();if (latestUpdates.updates.isEmpty) {@@ -229,7 +206,6 @@ class SocialSyncService {hasNewReactions = hasNewReactions || needsReactionsSync;}- // Sync anon profiles if neededif (update.anonProfilesUpdatedAt != null) {final localAnonSyncTime = await _db.getAnonProfilesSyncTime(update.collectionID,@@ -248,7 +224,6 @@ class SocialSyncService {_logger.info('Synced $syncedCount collections with new updates');- // Fire event if any data was syncedif (syncedCount > 0) {Bus.instance.fire(SocialDataUpdatedEvent(@@ -292,7 +267,6 @@ class SocialSyncService {return false;}- /// Syncs anonymous profiles for a collection.Future<void> syncAnonProfiles(int collectionID) async {try {final response = await _api.fetchAnonProfiles(collectionID);@@ -343,7 +317,6 @@ class SocialSyncService {}}- /// Decrypts API comment responses to local Comment models.List<Comment> _decryptComments(List<CommentApiResponse> apiComments,int collectionID,@@ -377,7 +350,6 @@ class SocialSyncService {return comments;}- /// Decrypts API reaction responses to local Reaction models.List<Reaction> _decryptReactions(List<ReactionApiResponse> apiReactions,int collectionID,diff --git a/mobile/apps/photos/lib/services/update_service.dart b/mobile/apps/photos/lib/services/update_service.dartindex 3a464d1a8c..7ac8a896ec 100644--- a/mobile/apps/photos/lib/services/update_service.dart+++ b/mobile/apps/photos/lib/services/update_service.dart@@ -31,11 +31,9 @@ class UpdateService {}Future<bool> shouldShowChangeLog() async {- // fetch the change log version which was last shown to user.final lastShownAtVersion = _prefs.getInt(changeLogVersionKey);if (lastShownAtVersion == null) {- // Fresh install: the key was never set, so the user has no previous- // version to show a "What's New" for. Silently mark as seen.+ // Fresh installs have no earlier version whose changelog should be shown.await hideChangeLog();return false;}diff --git a/mobile/apps/photos/lib/services/video_preview_service.dart b/mobile/apps/photos/lib/services/video_preview_service.dartindex cbb4b75e89..8e17c50a17 100644--- a/mobile/apps/photos/lib/services/video_preview_service.dart+++ b/mobile/apps/photos/lib/services/video_preview_service.dart@@ -138,10 +138,7 @@ class VideoPreviewService {}}- // Clear queue - will be rebuilt from DB when processing resumesvoid clearQueue() {- // Fire events for all items being cleared so UI can reset- // Use paused status when flag is enabled (items will resume), otherwise uploadedfinal status = flagService.stopStreamProcess? PreviewItemStatus.paused: PreviewItemStatus.uploaded;@@ -152,7 +149,6 @@ class VideoPreviewService {_items.clear();}- /// Stop streaming immediately, cancels FFmpeg and network requests.void stop(String reason) {if (_items.isEmpty) return;@@ -170,7 +166,6 @@ class VideoPreviewService {}}- // Stop streaming process if ffmpeg not started or if ffmpeg progress < 75%Future<void> stopSafely(String reason) async {if (!flagService.stopStreamProcess) return;@@ -194,7 +189,6 @@ class VideoPreviewService {? "${(progress * 100).toStringAsFixed(1)}%": "N/A";- // Don't interrupt upload or compression >= 75%, but clear queueif (status == PreviewItemStatus.uploading ||(status == PreviewItemStatus.compressing &&progress != null &&@@ -213,26 +207,21 @@ class VideoPreviewService {Bus.instance.fire(VideoPreviewStateChangedEvent(fileId, status));}- // Return value indicates file was successfully added to queue or notFuture<bool> addToManualQueue(EnteFile file, String queueType) async {if (file.uploadedFileID == null) return false;- // Check if already in queuefinal bool alreadyInQueue = await uploadLocksDB.isInStreamQueue(file.uploadedFileID!,);if (alreadyInQueue) {- // File is already queued, but trigger processing in case it was stalledif (uploadingFileId < 0) {queueFiles(duration: Duration.zero, isManual: true, forceProcess: true);}- return false; // Indicates file was already in queue+ return false;}- // Add to persistent database queueawait uploadLocksDB.addToStreamQueue(file.uploadedFileID!, queueType);- // Start processing if not already processingif (uploadingFileId < 0) {queueFiles(duration: Duration.zero, isManual: true);} else {@@ -255,7 +244,6 @@ class VideoPreviewService {bool isCurrentlyProcessing(int? uploadedFileID) {if (uploadedFileID == null) return false;- // Also check if file is in queue or other processing statesfinal item = _items[uploadedFileID];if (item != null) {switch (item.status) {@@ -279,8 +267,7 @@ class VideoPreviewService {if (file.uploadedFileID == null) return false;try {- // Check database directly instead of relying on in-memory _manualQueueFiles- // which might not be populated yet+ // The in-memory manual queue may not be initialized yet.final manualQueueFiles = await uploadLocksDB.getStreamQueue();final queueType = manualQueueFiles[file.uploadedFileID!];return queueType == 'recreate';@@ -290,7 +277,6 @@ class VideoPreviewService {}Future<void> _ensurePreviewIdsInitialized() async {- // Ensure fileDataService previewIds is initialized before using itif (fileDataService.previewIds.isEmpty) {await fileDataService.syncFDStatus();}@@ -332,29 +318,20 @@ class VideoPreviewService {List<EnteFile> files,Map<int, PreviewInfo> previewIds,) async {- // This is the total video files that have streamsfinal Set<int> processed = previewIds.keys.toSet();- // Total: Total Remote video files owned - skipped video files- // + processed videos (any platform)final Set<int> total = {...processed};for (final file in files) {- // skipped -> don't addif (file.pubMagicMetadata?.sv == 1) {continue;}- // Include the file to total settotal.add(file.uploadedFileID!);}- // If total is empty then mark all as processed else compute the ratio- // of processed files and total remote video files- // netProcessedItems = processed / totalfinal double netProcessedItems = total.isEmpty? 1: (processed.length / total.length).clamp(0, 1);- // Store the data and return itfinal status = netProcessedItems;return status;}@@ -363,9 +340,6 @@ class VideoPreviewService {try {await _ensurePreviewIdsInitialized();- // This will get us all the video files that are present on remote- // and also that could be / have been skipped due to device- // limitationsfinal files = await _getFiles(beginDate: null,onlyFilesWithLocalId: false,@@ -381,16 +355,12 @@ class VideoPreviewService {Future<void> chunkAndUploadVideo(BuildContext? ctx,EnteFile enteFile, {-- /// Indicates this function is an continuation of a chunking threadbool continuation = false,- // not used currentlybool forceUpload = false,}) async {if (_items.isEmpty) return;_streamingCancelToken ??= CancelToken();- // Check if file upload is happening before processing video for streamingif (flagService.stopStreamProcess && FileUploader.instance.isUploading) {stop("upload in progress");return;@@ -409,7 +379,6 @@ class VideoPreviewService {return;}try {- // check if playlist already exist, but skip this check for 'recreate' operationsfinal isRecreateOperation = await _isRecreateOperation(enteFile);if (!isRecreateOperation && await getPlaylist(enteFile) != null) {if (ctx != null && ctx.mounted) {@@ -420,7 +389,6 @@ class VideoPreviewService {}} catch (e, s) {if (e is DioException && e.response?.statusCode == 404) {- // 404 is expected when checking if preview exists_logger.fine("No preview found for ${enteFile.displayName}, will create one",);@@ -433,7 +401,6 @@ class VideoPreviewService {_logger.info("Starting video preview generation for ${enteFile.displayName}",);- // elimination case for <=10 MB with H.264final isManual = await uploadLocksDB.isInStreamQueue(enteFile.uploadedFileID!,);@@ -446,7 +413,6 @@ class VideoPreviewService {return;}- // check if there is already a preview in processingif (!continuation && uploadingFileId >= 0) {if (uploadingFileId == enteFile.uploadedFileID) return;@@ -466,7 +432,6 @@ class VideoPreviewService {return;}- // everything is fine, let's processuploadingFileId = enteFile.uploadedFileID!;_items[enteFile.uploadedFileID!] = PreviewItem(status: PreviewItemStatus.compressing,@@ -481,7 +446,6 @@ class VideoPreviewService {PreviewItemStatus.compressing,);- // get filefile ??= await getFile(enteFile, isOrigin: true);if (_items.isEmpty) return;if (file == null) {@@ -489,7 +453,6 @@ class VideoPreviewService {return;}- // check metadata for bitrate, codec, color spaceprops ??= await getVideoProps(file);final fileSize = enteFile.fileSize ?? file.lengthSync();@@ -526,7 +489,6 @@ class VideoPreviewService {colorTransfer != null &&(colorTransfer == "smpte2084" || colorTransfer == "arib-std-b67");- // create temp file & directory for preview generationfinal String tempDir = config.getTempDirectory();final String prefix ="${tempDir}_${enteFile.uploadedFileID}_${newID("pv")}";@@ -559,18 +521,14 @@ class VideoPreviewService {final videoFilters = <String>[];if (rescaleVideo || needsTonemap) {- // scale smaller dimension to 720p (or keep original if less than 720p)- // portrait: scale width to min(720,iw), landscape: scale height to min(720,ih)videoFilters.add("scale='if(lt(iw,ih),min(720,iw),-2)':'if(lt(iw,ih),-2,min(720,ih))'",);- // reduce fps to 30 if it is more than 30if (applyFPS) videoFilters.add("fps=30");}if (needsTonemap) {- // apply tonemapping for HDR videosvideoFilters.addAll(['zscale=transfer=linear','tonemap=tonemap=hable:desat=0',@@ -584,13 +542,9 @@ class VideoPreviewService {}final command =- // scaling, fps, tonemapping'$filters'- // video encoding with maxrate cap at 2000kbps to preserve smaller bitrates'${reencodeVideo ? '-c:v libx264 -maxrate 2000k -bufsize 4000k ' : '-c:v copy '}'- // audio encoding'-c:a aac -b:a 128k '- // hls options'-f hls -hls_flags single_file ''-hls_list_size 0 -hls_key_info_file ${keyinfo.path} ';@@ -640,7 +594,6 @@ class VideoPreviewService {objectId = result.$1;objectSize = result.$2;- // Fetch resolution of generated stream by decrypting a single framefinal playlistFrameResult = await ffmpegService.runFfmpeg('-allowed_extensions ALL -i "$prefix/output.m3u8" -frames:v 1 -c copy "$prefix/frame.ts"',@@ -694,7 +647,6 @@ class VideoPreviewService {}if (error == null) {- // update previewIdsfileDataService.appendPreview(enteFile.uploadedFileID!,objectId!,@@ -721,20 +673,16 @@ class VideoPreviewService {_removeFile(enteFile);_removeFromLocks(enteFile).ignore();}- // Check if we should stop processing due to network errorsfinal bool shouldStopProcessing = _isNetworkError(error);if (fileQueue.isNotEmpty && !shouldStopProcessing) {- // If there was an error, add a delay before processing next fileif (error != null) {_logger.info("[chunk] Error occurred, waiting before processing next item. Queue size: ${fileQueue.length}",);- // Add a small delay before processing next file after an errorawait Future.delayed(const Duration(seconds: 2));}- // process next file_logger.info("[chunk] Processing ${_items.length} items for streaming");final entry = fileQueue.entries.first;final file = entry.value;@@ -745,7 +693,6 @@ class VideoPreviewService {await chunkAndUploadVideo(null, file, continuation: true);}} else {- // Release compute when queue is empty or network is unavailablestop(shouldStopProcessing ? "network error" : "nothing to process");}}@@ -773,14 +720,12 @@ class VideoPreviewService {void _removeFile(EnteFile enteFile) {final fileId = enteFile.uploadedFileID!;_items.remove(fileId);- // Note: Using 'uploaded' status as there's no 'removed' status in PreviewItemStatus- // This indicates the item has been successfully processed and removed from queue+ // There is no removed status; uploaded also clears the item from the UI._fireVideoPreviewStateChange(fileId, PreviewItemStatus.uploaded);}bool _isNetworkError(Object? error) {if (error is DioException) {- // Check for any network-related errorreturn error.type == DioExceptionType.connectionError ||error.type == DioExceptionType.connectionTimeout ||error.type == DioExceptionType.unknown ||@@ -791,7 +736,6 @@ class VideoPreviewService {}void _retryFile(EnteFile enteFile, Object error) {- // Check if it's a network error that should not be retried immediatelybool shouldRetry = true;if (_isNetworkError(error)) {_logger.fine(@@ -1158,7 +1102,6 @@ class VideoPreviewService {double totalDuration = 0.0;for (final line in lines) {if (line.startsWith("#EXTINF:")) {- // Extract duration value (e.g., "#EXTINF:2.400000," β "2.400000")final durationStr = line.substring(8, line.length - 1);final duration = double.tryParse(durationStr);if (duration != null) {@@ -1262,8 +1205,6 @@ class VideoPreviewService {return (props, skipFile, file);}- // generate stream for all files after cutoff date- // returns false if it fails to launch chuncking functionFuture<bool> _putFilesForPreviewCreation() async {if (!isVideoStreamingEnabled || !await canUseHighBandwidth()) return false;@@ -1275,24 +1216,20 @@ class VideoPreviewService {manualQueueFiles = await uploadLocksDB.getStreamQueue();- // handle case when failures are already previewedfor (final failure in _failureFiles!) {if (_items.containsKey(failure)) {uploadLocksDB.deleteStreamUploadErrorEntry(failure).ignore();}}- // handle case when manual queue items are already previewed (for 'create' type only)for (final queueItem in manualQueueFiles.keys) {final queueType = manualQueueFiles[queueItem];final hasPreview = fileDataService.previewIds[queueItem] != null;if (hasPreview && queueType == 'create') {- // Remove from queue only if it's a 'create' type and preview existsawait uploadLocksDB.removeFromStreamQueue(queueItem);}}- // Refresh manual queue after cleanupmanualQueueFiles = await uploadLocksDB.getStreamQueue();} catch (_) {}@@ -1306,12 +1243,10 @@ class VideoPreviewService {"[init] Found ${files.length} files in last 60 days, ${manualQueueFiles.length} manual queue files: ${manualQueueFiles.keys.toList()}",);- // Add manual queue files first (they have priority)for (final queueFileId in manualQueueFiles.keys) {final queueType = manualQueueFiles[queueFileId] ?? 'create';final hasPreview = previewIds[queueFileId] != null;- // For create, only add if no preview existsif (queueType == 'create' && hasPreview) {_logger.info("[manual-queue] Skipping file $queueFileId (type=$queueType, hasPreview=$hasPreview)",@@ -1319,12 +1254,10 @@ class VideoPreviewService {continue;}- // First try to find the file in the 60-day listvar queueFile = files.firstWhereOrNull((f) => f.uploadedFileID == queueFileId,);- // If not found in 60-day list, fetch it individuallyqueueFile ??= await filesDB.getAnyUploadedFile(queueFileId).catchError((e) => null);@@ -1348,7 +1281,6 @@ class VideoPreviewService {fileQueue[queueFile.uploadedFileID!] = queueFile;}- // Then add regular files that need processingfinal allFiles = files.where((file) =>@@ -1357,7 +1289,6 @@ class VideoPreviewService {).toList();- // set all video status to in queuevar n = allFiles.length, i = 0;while (i < n) {final enteFile = allFiles[i];@@ -1409,7 +1340,6 @@ class VideoPreviewService {"[init] Processing $totalFiles items for streaming (${manualQueueFiles.length} manual requested, ${fileQueue.length} queued, ${allFiles.length} regular)",);- // take first file and put it for stream generationfinal entry = fileQueue.entries.first;final file = entry.value;fileQueue.remove(entry.key);@@ -1431,7 +1361,6 @@ class VideoPreviewService {);}- /// To check if it's enabled, device is healthy and running streamingbool _isPermissionGranted() {return isVideoStreamingEnabled &&computeController.computeState == ComputeRunState.generatingStream &&@@ -1444,10 +1373,9 @@ class VideoPreviewService {bool forceProcess = false,}) {Future.delayed(duration, () async {- _streamingCancelToken = null; // Reset for new session+ _streamingCancelToken = null;if (_hasQueuedFile && !forceProcess) return;- // Don't start streaming if file uploads are in progressif (flagService.stopStreamProcess && FileUploader.instance.isUploading) {_logger.info("Skipping stream queue - file upload in progress");return;@@ -1458,7 +1386,6 @@ class VideoPreviewService {await _ensurePreviewIdsInitialized();final result = await _putFilesForPreviewCreation();- // Cannot proceed to stream generation, would have to release compute ASAPif (!result) {computeController.releaseCompute(stream: true);}diff --git a/mobile/apps/photos/lib/services/wake_lock_service.dart b/mobile/apps/photos/lib/services/wake_lock_service.dartindex d409645675..8c29609f1d 100644--- a/mobile/apps/photos/lib/services/wake_lock_service.dart+++ b/mobile/apps/photos/lib/services/wake_lock_service.dart@@ -10,11 +10,8 @@ enum WakeLockFor {largeBackupStandbyScreen,}-/// Use this wrapper to use wakelock. This class makes sure that the wakelock-/// setting across sessions if set is respected when wakelock is updated for-/// other non across session purposes.-/// Only place where this wrapper is not used for accessing wakelock APIs is-/// in media_kit package.+// Temporary callers must not override the across-session setting.+// media_kit is the only code that intentionally bypasses this wrapper.class EnteWakeLockService {static const String kKeepAppAwakeAcrossSessions ="keepAppAwakeAcrossSessions";diff --git a/mobile/apps/photos/lib/services/wrapped/builders/media_selector.dart b/mobile/apps/photos/lib/services/wrapped/builders/media_selector.dartindex 5fad37d3b1..32c92b0bf6 100644--- a/mobile/apps/photos/lib/services/wrapped/builders/media_selector.dart+++ b/mobile/apps/photos/lib/services/wrapped/builders/media_selector.dart@@ -1,7 +1,5 @@part of "package:photos/services/wrapped/candidate_builders.dart";-/// Shared helper that picks a diverse, people-forward set of media for-/// Wrapped cards while filtering obvious screenshots/documents.class WrappedMediaSelector {const WrappedMediaSelector._();diff --git a/mobile/apps/photos/lib/services/wrapped/candidate_builders.dart b/mobile/apps/photos/lib/services/wrapped/candidate_builders.dartindex b47559ffc2..8943a4c0ed 100644--- a/mobile/apps/photos/lib/services/wrapped/candidate_builders.dart+++ b/mobile/apps/photos/lib/services/wrapped/candidate_builders.dart@@ -59,7 +59,6 @@ List<int> buildMetaUploadedIDs(List<int> candidates, int desiredCount) {return candidates.take(limit).toList(growable: false);}-/// Provides basic context details for candidate builders.@immutableclass WrappedEngineContext {WrappedEngineContext({@@ -113,7 +112,6 @@ class WrappedEngineContext {}}-/// Contract for producing Wrapped candidate cards for a specific domain.abstract class WrappedCandidateBuilder {const WrappedCandidateBuilder();@@ -122,7 +120,6 @@ abstract class WrappedCandidateBuilder {Future<List<WrappedCard>> build(WrappedEngineContext context);}-/// Registry of all candidate builders invoked by the engine.const List<WrappedCandidateBuilder> wrappedCandidateBuilders =<WrappedCandidateBuilder>[StatsCandidateBuilder(),diff --git a/mobile/apps/photos/lib/services/wrapped/models.dart b/mobile/apps/photos/lib/services/wrapped/models.dartindex b72b45ff17..b78f3d3f2a 100644--- a/mobile/apps/photos/lib/services/wrapped/models.dart+++ b/mobile/apps/photos/lib/services/wrapped/models.dart@@ -320,12 +320,9 @@ class WrappedPersonEntry {}}-/// Sentinel value used in heatmap grids when a day should be hidden but space-/// must still be reserved (e.g. future dates).+// Future cells are hidden; padded cells remain faintly visible.const int kWrappedHeatmapFutureValue = -2;-/// Sentinel value used when a day is outside the display window but we still-/// want to render a faint placeholder (e.g. padded weeks).const int kWrappedHeatmapPaddedValue = -1;@immutablediff --git a/mobile/apps/photos/lib/services/wrapped/wrapped_cache_service.dart b/mobile/apps/photos/lib/services/wrapped/wrapped_cache_service.dartindex 15b0efea90..cbcd3fdd81 100644--- a/mobile/apps/photos/lib/services/wrapped/wrapped_cache_service.dart+++ b/mobile/apps/photos/lib/services/wrapped/wrapped_cache_service.dart@@ -7,7 +7,6 @@ import "package:path_provider/path_provider.dart";import "package:photos/services/wrapped/models.dart";import "package:synchronized/synchronized.dart";-/// Persists Wrapped results to disk so we can avoid recomputing on every boot.class WrappedCacheService {WrappedCacheService._();diff --git a/mobile/apps/photos/lib/services/wrapped/wrapped_engine.dart b/mobile/apps/photos/lib/services/wrapped/wrapped_engine.dartindex 454c67155a..0542006162 100644--- a/mobile/apps/photos/lib/services/wrapped/wrapped_engine.dart+++ b/mobile/apps/photos/lib/services/wrapped/wrapped_engine.dart@@ -21,11 +21,9 @@ import "package:photos/services/wrapped/models.dart";final Logger _engineLogger = Logger("WrappedEngine");final Logger _computeLogger = Logger("WrappedEngineIsolate");-/// Orchestrates the single-isolate computation pipeline for Ente Rewind.class WrappedEngine {const WrappedEngine._();- /// Schedules the compute pipeline on a worker isolate.static Future<WrappedResult> compute({required int year}) async {final DateTime now = DateTime.now();_engineLogger.fine("Scheduling Wrapped compute for $year at $now");diff --git a/mobile/apps/photos/lib/services/wrapped/wrapped_media_preloader.dart b/mobile/apps/photos/lib/services/wrapped/wrapped_media_preloader.dartindex 762672be07..9f68e9e930 100644--- a/mobile/apps/photos/lib/services/wrapped/wrapped_media_preloader.dart+++ b/mobile/apps/photos/lib/services/wrapped/wrapped_media_preloader.dart@@ -6,8 +6,6 @@ import "package:photos/models/file/file.dart";import "package:photos/module/download/thumbnail.dart";import "package:photos/services/wrapped/models.dart";-/// Preloads the media referenced by Wrapped cards so the viewer can render-/// without waiting on database and thumbnail fetches.class WrappedMediaPreloader {WrappedMediaPreloader._(): _logger = Logger("WrappedMediaPreloader"),@@ -20,7 +18,6 @@ class WrappedMediaPreloader {final Map<int, EnteFile> _cache;final Map<int, Future<EnteFile?>> _inFlight;- /// Loads and caches the media for the supplied Wrapped result.Future<void> prime(WrappedResult result) async {final Set<int> targetIDs = _extractMediaIDs(result.cards);_pruneTo(targetIDs);@@ -35,13 +32,11 @@ class WrappedMediaPreloader {await Future.wait(pending, eagerError: false);}- /// Clears all cached entries and cancels outstanding loads.void reset() {_cache.clear();_inFlight.clear();}- /// Returns the cached file for [uploadedID] if available.EnteFile? getCachedFile(int uploadedID) {if (uploadedID <= 0) {return null;@@ -49,7 +44,6 @@ class WrappedMediaPreloader {return _cache[uploadedID];}- /// Ensures the [EnteFile] for [uploadedID] is cached and returns it.Future<EnteFile?> ensureFile(int uploadedID) {if (uploadedID <= 0) {return Future<EnteFile?>.value(null);@@ -91,7 +85,6 @@ class WrappedMediaPreloader {}void _warmThumbnail(EnteFile file) {- // Thumbnail preloading returns a future internally; fire-and-forget.try {// ignore: unawaited_futurespreloadThumbnail(file);diff --git a/mobile/apps/photos/lib/settings/local_settings.dart b/mobile/apps/photos/lib/settings/local_settings.dartindex 76f407839d..97ee4793e6 100644--- a/mobile/apps/photos/lib/settings/local_settings.dart+++ b/mobile/apps/photos/lib/settings/local_settings.dart@@ -16,14 +16,10 @@ enum AlbumViewType { grid, list }enum PeopleSortKey { mostPhotos, name, lastUpdated }-/// Bit positions for per-widget-type "hide text" flags stored as a single-/// integer. The same integer is mirrored to the home_widget plugin's data-/// store so the native (Android/iOS) widget providers can read it directly.-/// IMPORTANT: Never reorder or remove values. Only append new values at the end.+// Stored as bit positions. Append only; never reorder or remove values.enum WidgetHideTextFlag { memory, album, people }-/// Bit positions for local-gallery boolean flags stored as a single integer.-/// IMPORTANT: Never reorder or remove values. Only append new values at the end.+// Stored as bit positions. Append only; never reorder or remove values.enum LocalGalleryFlag {mlConsent,mapEnabled,@@ -117,9 +113,7 @@ class LocalSettings {static const _kWidgetHideTextFlags = "ls.widget_hide_text_flags";- /// Key used by the native (Android/iOS) widget providers to read the- /// mirrored copy of the widget hide-text bitmask from the home_widget- /// data store. Must stay in sync with the native code.+ // Must match the key read by the native widget providers.static const _kWidgetHideTextFlagsNativeKey = "widgetHideTitleFlags";static const _kLocalGalleryFlags = "ls.offline_flags";@@ -136,16 +130,9 @@ class LocalSettings {AppMode? _cachedAppMode;- /// True only for the session in which the user just enabled local-gallery- /// mode during onboarding. Intentionally not persisted, so it resets to- /// false on the next app launch. Used to defer the get-started banner to- /// the second app open (after onboarding).bool localGalleryModeEnabledThisSession = false;- /// Set after the first local-gallery import completes before an account is- /// configured. When the user later signs in or signs up, the online flow- /// replays first-import completion once so backup-folder selection can run- /// against the imported local rows, then clears this marker.+ // Carries first-import completion from local-gallery mode into account setup.bool get isFromLocalGalleryToEnte =>_prefs.getBool(_kIsFromLocalGalleryToEnte) ?? false;@@ -293,8 +280,6 @@ class LocalSettings {}}- // getEstimatedInstallTimeInMs returns the time when the app was installed- // The time is stored in shared preferences and will be reset on logoutDateTime getInstallDateTime() {if (_prefs.containsKey('ls.install_time')) {return DateTime.fromMillisecondsSinceEpoch(@@ -418,7 +403,6 @@ class LocalSettings {return value;}- /// toggleFaceIndexing toggles the face indexing setting and returns the new valueFuture<bool> toggleLocalMLIndexing() async {final nextValue =!(_prefs.getBool(_mlLocalIndexingKey) ??@@ -487,8 +471,6 @@ class LocalSettings {await _prefs.setBool(_hasConfiguredLinksInAppPermissionKey, value);}- /// This is only relevant for fdorid and independent builds since in them,- /// user has to manually allow the app to open public links in-appbool hasConfiguredInAppLinkPermissions() {final result = _prefs.getBool(_hasConfiguredLinksInAppPermissionKey);return result ?? false;@@ -530,9 +512,6 @@ class LocalSettings {await _prefs.setBool(_kBGDebugNotificationsEnabled, value);}- /// User's explicit override for the Cloudflare upload proxy toggle.- /// `null` means the user has not chosen β callers should fall back to- /// `flagService.cloudflareUploadWorker` (the rollout default).bool? get cfUploadProxyEnabled => _prefs.getBool(_kCFUploadProxyEnabled);Future<void> setCFUploadProxyEnabled(bool value) async {diff --git a/mobile/apps/photos/lib/states/detail_page_state.dart b/mobile/apps/photos/lib/states/detail_page_state.dartindex b5b1dc9d46..a3eb5c9e66 100644--- a/mobile/apps/photos/lib/states/detail_page_state.dart+++ b/mobile/apps/photos/lib/states/detail_page_state.dart@@ -2,10 +2,6 @@ import "package:flutter/material.dart";import "package:flutter/services.dart";import "package:photos/models/file/file.dart";-/// Continuous zoom transform from the photo viewer.-///-/// [scale] is relative to the initial "contained" scale (1.0 = no zoom).-/// [offset] is the pan translation in logical pixels.@immutableclass ZoomTransform {static const ZoomTransform identity = ZoomTransform(@@ -48,19 +44,10 @@ String? detailPageFileIdentifier(EnteFile file) {class InheritedDetailPageState extends InheritedWidget {final ValueNotifier<bool> enableFullScreenNotifier;final ValueNotifier<bool> isInSharedCollectionNotifier;-- /// Holds the stable identifier of the file currently showing thumbnail- /// fallback. Only the file with matching ID should display the indicator.final ValueNotifier<String?> showingThumbnailFallbackNotifier;-- /// Whether the photo viewer is currently zoomed in.final ValueNotifier<bool> isZoomedNotifier;-- /// Continuous zoom transform (scale + offset) from the photo viewer.- /// Updated on every gesture frame so overlays can track the zoom.final ValueNotifier<ZoomTransform> zoomTransformNotifier;- // Cannot be const because we accept a ValueNotifier instance at runtime// ignore: prefer_const_constructors_in_immutablesInheritedDetailPageState({super.key,diff --git a/mobile/apps/photos/lib/states/location_state.dart b/mobile/apps/photos/lib/states/location_state.dartindex 91a1ba1057..c188e50275 100644--- a/mobile/apps/photos/lib/states/location_state.dart+++ b/mobile/apps/photos/lib/states/location_state.dart@@ -20,7 +20,6 @@ class LocationTagStateProvider extends StatefulWidget {this.child, {this.centerPoint,this.locationTagEntity,- // if the locationTagEntity is null, we use the centerPoint and radiusthis.radius,super.key,});@@ -48,9 +47,6 @@ class _LocationTagStateProviderState extends State<LocationTagStateProvider> {assert(_centerPoint != null || _locationTagEntity != null);_centerPoint = _locationTagEntity?.item.centerPoint ?? _centerPoint!;- ///If the location tag has a custom radius value, we add the custom radius- ///value to the list of default radius values only for this location tag and- ///keep it in the state of this widget._radiusValues = _getRadiusValuesOfLocTag(_locationTagEntity?.item.radius ?? widget.radius,);@@ -119,9 +115,6 @@ class _LocationTagStateProviderState extends State<LocationTagStateProvider> {}}- ///Returns the list of radius values for the location tag entity. If radius of- ///the location tag is not present in the default list, it returns the list- ///with the custom radius value.List<double> _getRadiusValuesOfLocTag(double? radiusOfLocTag) {final radiusValues = <double>[...defaultRadiusValues];if (radiusOfLocTag != null &&@@ -147,11 +140,9 @@ class _LocationTagStateProviderState extends State<LocationTagStateProvider> {}}-///This InheritedWidget's state is used in add & edit location sheetsclass InheritedLocationTagData extends InheritedWidget {final double selectedRadius;final Location centerPoint;- //locationTag is null when we are creating a new location tag in add location sheetfinal LocalEntity<LocationTag>? locationTagEntity;final VoidCallbackParamDouble updateSelectedRadius;final VoidCallbackParamLocation updateCenterPoint;diff --git a/mobile/apps/photos/lib/ui/settings/streaming/video_streaming_settings_page.dart b/mobile/apps/photos/lib/ui/settings/streaming/video_streaming_settings_page.dartindex 7125fc96bb..e99ef473b2 100644--- a/mobile/apps/photos/lib/ui/settings/streaming/video_streaming_settings_page.dart+++ b/mobile/apps/photos/lib/ui/settings/streaming/video_streaming_settings_page.dart@@ -199,7 +199,6 @@ class VideoStreamingStatusWidgetState) {final status = event.status;- // Handle different statesswitch (status) {case PreviewItemStatus.uploaded:init();diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_crop_page.dart b/mobile/apps/photos/lib/ui/tools/editor/video_crop_page.dartindex 5ecd0f14bb..0826fda8c9 100644--- a/mobile/apps/photos/lib/ui/tools/editor/video_crop_page.dart+++ b/mobile/apps/photos/lib/ui/tools/editor/video_crop_page.dart@@ -30,7 +30,6 @@ class _VideoCropPageState extends State<VideoCropPage> {return;}- // Find which crop value matches the current ratiofor (final value in CropValue.values) {if (value == CropValue.original || value == CropValue.free) continue;diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_crop_util.dart b/mobile/apps/photos/lib/ui/tools/editor/video_crop_util.dartindex ca1e125291..275847a814 100644--- a/mobile/apps/photos/lib/ui/tools/editor/video_crop_util.dart+++ b/mobile/apps/photos/lib/ui/tools/editor/video_crop_util.dart@@ -15,7 +15,6 @@ class CropCalculation {final int width;final int height;- /// FFmpeg crop filter string: crop=w:h:x:yString toFFmpegFilter() => 'crop=$width:$height:$x:$y';}@@ -27,15 +26,11 @@ class VideoCropException implements Exception {String toString() => 'VideoCropException: $message';}-/// Helpers to derive display- and file-space crop rectangles for native exportclass VideoCropUtil {static double _clampNormalized(double value) {return value.clamp(0.0, 1.0);}- /// Calculate the crop rectangle in display-space pixels.- ///- /// Returns a Rect in display-space so the native plugins can transform to file-space.static Rect calculateDisplaySpaceCropRect({required VideoEditorController controller,}) {@@ -46,8 +41,6 @@ class VideoCropUtil {);}- /// Testability helper: bypasses controller and platform checks by accepting- /// raw crop data. Only used in unit tests.@visibleForTestingstatic Rect calculateDisplaySpaceCropRectFromData({required Offset minCrop,@@ -104,7 +97,6 @@ class VideoCropUtil {);}- /// Convert the normalised crop selection into file-space coordinates.static CropCalculation calculateFileSpaceCrop({required VideoEditorController controller,}) {diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_editor_page.dart b/mobile/apps/photos/lib/ui/tools/editor/video_editor_page.dartindex 4e9c197b44..70a68db836 100644--- a/mobile/apps/photos/lib/ui/tools/editor/video_editor_page.dart+++ b/mobile/apps/photos/lib/ui/tools/editor/video_editor_page.dart@@ -57,15 +57,12 @@ class _VideoEditorPageState extends State<VideoEditorPage> {VideoEditorController? _controller;- /// Toggle state for internal users to switch between native and FFmpeg export- /// Initially set to the flag service valuelate bool _useNativeExport;@overridevoid initState() {super.initState();- // Initialize toggle with flagService value_useNativeExport = flagService.useNativeVideoEditor;_controller = VideoEditorController.file(widget.ioFile);@@ -419,8 +416,7 @@ class _VideoEditorPageState extends State<VideoEditorPage> {".mp4";final galleryTitle = await getMediaStoreCompatibleTitle(fileName);- //Disabling notifications for assets changing to insert the file into- //files db before triggering a sync.+ // Insert the edited file before asset notifications trigger a sync.await PhotoManager.stopChangeNotify();notificationsStopped = true;@@ -460,8 +456,6 @@ class _VideoEditorPageState extends State<VideoEditorPage> {showShortToast(context, context.strings.editsSaved);final files = List<EnteFile>.of(widget.detailPageConfig.files);- // the index could be -1 if the files fetched doesn't contain the newly- // edited filesint selectionIndex = files.indexWhere((file) => file.generatedID == newFile.generatedID,);diff --git a/mobile/apps/photos/lib/ui/viewer/file/native_video_player_controls/seek_bar.dart b/mobile/apps/photos/lib/ui/viewer/file/native_video_player_controls/seek_bar.dartindex 611337062f..f861a182ab 100644--- a/mobile/apps/photos/lib/ui/viewer/file/native_video_player_controls/seek_bar.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/native_video_player_controls/seek_bar.dart@@ -151,11 +151,9 @@ class _NativeVideoProgressControlsStatevoid _listen(PlaybackEvent playerData) {switch (playerData) {case PlaybackStatusChangedEvent():- // Emitted when playback status changes (playing, paused, or stopped)_onPlaybackStatusChanged();break;case PlaybackPositionChangedEvent():- // Emitted when playback position changes_onPlaybackPositionChanged();break;case PlaybackEndedEvent():diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_exif_dialog.dart b/mobile/apps/photos/lib/ui/viewer/file/video_exif_dialog.dartindex c734a40865..8fc525ac8d 100644--- a/mobile/apps/photos/lib/ui/viewer/file/video_exif_dialog.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/video_exif_dialog.dart@@ -32,9 +32,9 @@ class VideoExifDialog extends StatelessWidget {child: ExpansionTile(initiallyExpanded: false,title: Text(title, style: getEnteTextTheme(context).body),- childrenPadding: EdgeInsets.zero, // Remove padding around children+ childrenPadding: EdgeInsets.zero,tilePadding: EdgeInsets.zero,- collapsedShape: const Border(), // Remove border when collapsed+ collapsedShape: const Border(),shape: const Border(),children: [content],),@@ -72,7 +72,6 @@ class VideoExifDialog extends StatelessWidget {if (value is List) {continue;}- // print type of valueif (value is int ||value is double ||value is String ||@@ -102,7 +101,7 @@ class VideoExifDialog extends StatelessWidget {title: Text(titleString, style: getEnteTextTheme(context).small),childrenPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 4),tilePadding: EdgeInsets.zero,- collapsedShape: const Border(), // Remove border when collapsed+ collapsedShape: const Border(),shape: const Border(),children: [Column(@@ -141,7 +140,7 @@ class VideoExifDialog extends StatelessWidget {}if (value == null) {- return const SizedBox.shrink(); // Return an empty container if there's no data for the key.+ return const SizedBox.shrink();}return Padding(padding: const EdgeInsets.symmetric(vertical: 4.0),diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_stream_change.dart b/mobile/apps/photos/lib/ui/viewer/file/video_stream_change.dartindex 6e3c5ea332..93ed479c32 100644--- a/mobile/apps/photos/lib/ui/viewer/file/video_stream_change.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/video_stream_change.dart@@ -38,7 +38,6 @@ class _VideoStreamChangeWidgetState extends State<VideoStreamChangeWidget> {@overridevoid initState() {super.initState();- // Initialize processing state safely in initStateisCurrentlyProcessing = VideoPreviewService.instance.isCurrentlyProcessing(widget.file.uploadedFileID,);@@ -49,7 +48,6 @@ class _VideoStreamChangeWidgetState extends State<VideoStreamChangeWidget> {final fileId = event.fileId;final status = event.status;- // Handle different states - will be false for different files or non-processing statesfinal newProcessingState =widget.file.uploadedFileID == fileId &&switch (status) {@@ -60,7 +58,6 @@ class _VideoStreamChangeWidgetState extends State<VideoStreamChangeWidget> {_ => false,};- // Only update state if value changedif (isCurrentlyProcessing != newProcessingState) {isCurrentlyProcessing = newProcessingState;setState(() {});@@ -92,7 +89,6 @@ class _VideoStreamChangeWidgetState extends State<VideoStreamChangeWidget> {widget.file.uploadedFileID != null &&(fileDataService.previewIds.containsKey(widget.file.uploadedFileID));- // Get the current processing status for more specific messagingfinal processingStatus = widget.file.uploadedFileID != null? VideoPreviewService.instance.getProcessingStatus(widget.file.uploadedFileID!,diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/video_widget.dartindex 20dae85349..36e43d2f82 100644--- a/mobile/apps/photos/lib/ui/viewer/file/video_widget.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/video_widget.dart@@ -58,7 +58,6 @@ class _VideoWidgetState extends State<VideoWidget> {@overridevoid initState() {super.initState();- // Automatic error fallback: switch to MediaKit when native player failsuseMediaKitForVideoSubscription = Bus.instance.on<UseMediaKitForVideo>().listen((event) {@@ -78,8 +77,7 @@ class _VideoWidgetState extends State<VideoWidget> {widget.file.uploadedFileID,);if (!widget.file.isOwner) {- // For shared video, we need to on-demand check if the file is streamable- // and if not, we need to set isPreviewLoadable to false+ // Shared previews are discovered on demand; assume loadable until checked.isPreviewLoadable = true;}_checkForPreview();diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit.dart b/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit.dartindex 5a68376991..d23acc38a7 100644--- a/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit.dart@@ -158,7 +158,7 @@ class _VideoWidgetMediaKitState extends State<VideoWidgetMediaKit>}} else {widget.file.getAsset.then((asset) async {- // asset.exists may return false for files in the android device trash+ // Android trash assets may report that they do not exist.if (asset == null ||!(await asset.exists || widget.file.isDeviceTrash)) {if (widget.file.uploadedFileID != null) {@@ -228,8 +228,6 @@ class _VideoWidgetMediaKitState extends State<VideoWidgetMediaKit>@overrideWidget build(BuildContext context) {return GestureDetector(- // Keep recognizer out of the arena during multi-touch/zoom to avoid- // it stealing pinch gestures with predominantly vertical movement.onVerticalDragUpdate: _isGuestView || _isZooming? null: (d) {diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit_common.dart b/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit_common.dartindex 2c9b76e7aa..031ba67cb1 100644--- a/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit_common.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/video_widget_media_kit_common.dart@@ -100,7 +100,6 @@ class _VideoWidgetState extends State<VideoWidget> {return Stack(alignment: Alignment.center,children: [- // Video layer with zoom supportwidget.transformationController != null? ZoomableVideoViewer(transformationController: widget.transformationController!,@@ -108,7 +107,6 @@ class _VideoWidgetState extends State<VideoWidget> {child: videoWidget,): videoWidget,- // Controls overlay (fixed position, not affected by zoom)ValueListenableBuilder(valueListenable: showControlsNotifier,builder: (context, value, _) {diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_widget_native.dart b/mobile/apps/photos/lib/ui/viewer/file/video_widget_native.dartindex 860f3fd4e7..b74decbb54 100644--- a/mobile/apps/photos/lib/ui/viewer/file/video_widget_native.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/video_widget_native.dart@@ -201,7 +201,7 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>}} else {await widget.file.getAsset.then((asset) async {- // asset.exists may return false for files in the android device trash+ // Android trash assets may report that they do not exist.if (asset == null ||!(await asset.exists || widget.file.isDeviceTrash)) {if (widget.file.uploadedFileID != null) {@@ -251,8 +251,6 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>_logger.info("Clearing cache");final file = File(_filePath!);- /// Checking if exists to avoid observed PathNotFoundException. Didn't find- /// root cause.if (file.existsSync()) {file.delete().then((value) {_logger.info("Cache cleared");@@ -304,8 +302,6 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>}},child: GestureDetector(- // Keep recognizer out of the arena during multi-touch/zoom to avoid- // it stealing pinch gestures with predominantly vertical movement.onVerticalDragUpdate: _isGuestView || _isZooming? null: (d) {@@ -323,8 +319,8 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>duration: const Duration(milliseconds: 750),switchOutCurve: Curves.easeOutExpo,switchInCurve: Curves.easeInExpo,- //Loading two high-res potrait videos together causes one to- //go blank. So only loading video when it is completely visible.+ // Two high-resolution portrait videos can blank one another.+ // Load only the completely visible one.child: !_isCompletelyVisible || _filePath == null? _getLoadingWidget(): Stack(@@ -583,7 +579,6 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>}void _onError(String errorMessage) {- //This doesn't work all the time_logger.severe("Error in native video player controller for file gen id: ${widget.file.generatedID}",);@@ -770,8 +765,7 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>return;}if (Platform.isIOS) {- // FFprobe in ffmpeg_kit can crash on certain iOS media files.- // On iOS, use lightweight metadata probing via AVPlayer.+ // FFprobe can crash on some iOS media; use AVPlayer metadata instead.if (widget.file.hasDimensions) {aspectRatio = widget.file.width / widget.file.height;} else {@@ -814,10 +808,7 @@ class _VideoWidgetNativeState extends State<VideoWidgetNative>await metadataController.initialize().timeout(const Duration(seconds: 4));final value = metadataController.value;final probeAspectRatio = value.aspectRatio;- // Always prefer the probed aspect ratio over file metadata dimensions,- // because AVPlayer correctly accounts for video rotation metadata.- // Raw file width/height may not reflect rotation (e.g. a portrait video- // stored as 1920x1080 with 90Β° rotation).+ // AVPlayer's aspect ratio includes rotation; stored dimensions may not.if (probeAspectRatio > 0) {aspectRatio = probeAspectRatio;}diff --git a/mobile/apps/photos/lib/ui/viewer/file/zoomable_video_viewer.dart b/mobile/apps/photos/lib/ui/viewer/file/zoomable_video_viewer.dartindex 7e6603b077..49acac3eaa 100644--- a/mobile/apps/photos/lib/ui/viewer/file/zoomable_video_viewer.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/zoomable_video_viewer.dart@@ -1,19 +1,10 @@import "package:flutter/widgets.dart";-/// Threshold for considering the view as "zoomed in".-/// Using 1.01 instead of 1.0 to account for floating-point precision.+// Keep above 1 to ignore floating-point noise.const double kZoomThreshold = 1.01;-/// A widget that wraps [InteractiveViewer] with multi-touch detection.-///-/// This widget solves a gesture arena race condition: when pinch-to-zoom-/// is attempted on a video inside a PageView, the PageView's drag gesture-/// recognizer can claim single-finger touches before InteractiveViewer's-/// scale gesture recognizer detects the second finger.-///-/// By using a low-level [Listener], we detect multi-touch at the pointer-/// level (before gesture arena processing) and immediately disable the-/// parent PageView's scrolling.+// Lock the parent PageView as soon as a second pointer arrives. Waiting for the+// gesture arena lets PageView steal the pinch before InteractiveViewer sees it.class ZoomableVideoViewer extends StatefulWidget {final TransformationController transformationController;final ValueChanged<bool>? onInteractionLockChanged;diff --git a/mobile/apps/photos/lib/ui/wrapped/cards/stats_card_content.dart b/mobile/apps/photos/lib/ui/wrapped/cards/stats_card_content.dartindex 08dcd3313f..6312426752 100644--- a/mobile/apps/photos/lib/ui/wrapped/cards/stats_card_content.dart+++ b/mobile/apps/photos/lib/ui/wrapped/cards/stats_card_content.dart@@ -194,7 +194,7 @@ List<_ChartTick> _buildAxisTicks(double axisMax) {return const <_ChartTick>[_ChartTick(value: 0, label: "0")];}- const int divisions = 2; // top, mid, baseline+ const int divisions = 2;final double step = axisMax / divisions;final NumberFormat compactFormat = NumberFormat.compact();final NumberFormat integerFormat = NumberFormat.decimalPattern();diff --git a/mobile/apps/photos/lib/ui/wrapped/wrapped_viewer_page.dart b/mobile/apps/photos/lib/ui/wrapped/wrapped_viewer_page.dartindex 7ff15a78b1..e380842e0c 100644--- a/mobile/apps/photos/lib/ui/wrapped/wrapped_viewer_page.dart+++ b/mobile/apps/photos/lib/ui/wrapped/wrapped_viewer_page.dart@@ -67,7 +67,6 @@ const double _kStoryControlHorizontalMarginFromEdge =_kStoryCardOuterHorizontalInset + _kStoryCardInnerHorizontalPadding;const double _kStoryControlBottomMarginFromEdge = _kStoryCardOuterVerticalInset;-/// Basic viewer for the stats-only Ente Rewind experience.class WrappedViewerPage extends StatefulWidget {const WrappedViewerPage({required this.initialState, super.key});