Skip to content

armgit / ente

Public Imported from GitHub
0

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

Prune more Photos viewer comments

Manav Rathi71d660c5e3c1
diff --git a/mobile/apps/photos/lib/core/configuration.dart b/mobile/apps/photos/lib/core/configuration.dart
index ae137712da..84cc2db024 100644
--- a/mobile/apps/photos/lib/core/configuration.dart
+++ b/mobile/apps/photos/lib/core/configuration.dart
@@ -136,10 +136,8 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
_logger.info('User ID: ${getUserID()}');
} catch (e, s) {
_logger.severe("Configuration init failed", e, s);
- /*
- Check if it's a known is related to reading secret from secure storage
- on android https://github.com/mogol/flutter_secure_storage/issues/541
- */
+ // BadPaddingException can mean Android secure storage is inaccessible.
+ // https://github.com/mogol/flutter_secure_storage/issues/541
if (e is PlatformException) {
final PlatformException error = e;
final bool isBadPaddingError =
@@ -155,10 +153,7 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
}
}
- // _cleanUpStaleFiles deletes all files in the temp directory that are older
- // than kTempFolderDeletionTimeBuffer except the the temp encrypted files for upload.
- // Those file are deleted by file uploader after the upload is complete or those
- // files are not being used / tracked.
+ // Leave upload artifacts for FileUploader to resume or delete.
Future<void> _cleanUpStaleFiles(Directory tempDocumentsDir) async {
try {
final currentTime = DateTime.now().microsecondsSinceEpoch;
@@ -212,7 +207,6 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
await _clearTempFolderOnLogout();
- // Clear preferences and secure storage
await _preferences.clear();
await _secureStorage.deleteAll();
_key = null;
@@ -220,12 +214,10 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
_secretKey = null;
_volatilePassword = null;
- // Clear all scheduled notifications (ritual reminders, memories, etc.)
await NotificationService.instance.clearAllScheduledNotifications(
logLines: false,
);
- // Clear all database tables
await FilesDB.instance.clearTable();
await GalleryDownloadsDB.instance.clearTable();
await CollectionsDB.instance.clearTable();
@@ -237,31 +229,26 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
await ContactsDatabase().clearTable();
await SocialDB.instance.clearAllData();
- // Clear all in-memory caches
ThumbnailInMemoryLruCache.clearAll();
FileLruCache.clearAll();
- // Clear image cache
try {
await DefaultCacheManager().emptyCache();
} catch (e) {
_logger.warning("Failed to clear image cache", e);
}
- // Clear video cache
try {
await VideoCacheManager.instance.emptyCache();
} catch (e) {
_logger.warning("Failed to clear video cache", e);
}
- // Clear all service caches
await SimilarImagesService.instance.clearCache();
await IgnoredFilesService.instance.reset();
unawaited(HomeWidgetService.instance.clearWidget(autoLogout));
MemoryShareService.instance.clearCache();
- // Clear additional caches (safe to call even if not initialized)
try {
await magicCacheService.clearMagicCache();
} catch (e) {
@@ -277,7 +264,6 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
);
}
- // Reset Ente Rewind caches and services
try {
wrappedService.resetForLogout();
} catch (e) {
@@ -290,7 +276,7 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
}
if (!autoLogout) {
- // Following services won't be initialized if it's the case of autoLogout
+ // Auto logout can run before these services are initialized.
CollectionsService.instance.clearCache();
FavoritesService.instance.clearCache();
SearchService.instance.clearCache();
@@ -330,18 +316,10 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
}
Future<KeyGenResult> generateKey(String password) async {
- // Create a master key
final masterKey = CryptoUtil.generateKey();
-
- // Create a recovery key
final recoveryKey = CryptoUtil.generateKey();
-
- // Encrypt master key and recovery key with each other
final encryptedMasterKey = CryptoUtil.encryptSync(masterKey, recoveryKey);
final encryptedRecoveryKey = CryptoUtil.encryptSync(recoveryKey, masterKey);
-
- // Derive a key from the password that will be used to encrypt and
- // decrypt the master key
final kekSalt = CryptoUtil.getSaltToDeriveKey();
final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(
utf8.encode(password),
@@ -349,13 +327,11 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
);
final loginKey = await CryptoUtil.deriveLoginKey(derivedKeyResult.key);
- // Encrypt the key with this derived key
final encryptedKeyData = CryptoUtil.encryptSync(
masterKey,
derivedKeyResult.key,
);
- // Generate a public-private keypair and encrypt the latter
final keyPair = await CryptoUtil.generateKeyPair();
final encryptedSecretKeyData = CryptoUtil.encryptSync(
keyPair.sk,
@@ -387,11 +363,7 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
Future<Tuple2<KeyAttributes, Uint8List>> getAttributesForNewPassword(
String password,
) async {
- // Get master key
final masterKey = getKey();
-
- // Derive a key from the password that will be used to encrypt and
- // decrypt the master key
final kekSalt = CryptoUtil.getSaltToDeriveKey();
final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(
utf8.encode(password),
@@ -399,7 +371,6 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
);
final loginKey = await CryptoUtil.deriveLoginKey(derivedKeyResult.key);
- // Encrypt the key with this derived key
final encryptedKeyData = CryptoUtil.encryptSync(
masterKey!,
derivedKeyResult.key,
@@ -417,10 +388,6 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
return Tuple2(updatedAttributes, loginKey);
}
- // decryptSecretsAndGetLoginKey decrypts the master key and recovery key
- // with the given password and save them in local secure storage.
- // This method also returns the keyEncKey that can be used for performing
- // SRP setup for existing users.
Future<Uint8List> decryptSecretsAndGetKeyEncKey(
String password,
KeyAttributes attributes, {
@@ -431,8 +398,6 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
password,
getEncryptedToken(),
);
- // Derive key-encryption-key from the entered password and existing
- // mem and ops limits
keyEncryptionKey ??= await CryptoUtil.deriveKey(
utf8.encode(password),
CryptoUtil.base642bin(attributes.kekSalt),
@@ -442,7 +407,6 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
Uint8List key;
try {
- // Decrypt the master key with the derived key
key = CryptoUtil.decryptSync(
CryptoUtil.base642bin(attributes.encryptedKey),
keyEncryptionKey,
@@ -472,10 +436,7 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
final masterKey = getKey()!;
final existingAttributes = getKeyAttributes();
- // Create a recovery key
final recoveryKey = CryptoUtil.generateKey();
-
- // Encrypt master key and recovery key with each other
final encryptedMasterKey = CryptoUtil.encryptSync(masterKey, recoveryKey);
final encryptedRecoveryKey = CryptoUtil.encryptSync(recoveryKey, masterKey);
@@ -499,19 +460,16 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
// Legacy users will have recoveryKey in the form of a hex string, while
// newer users will have it as a mnemonic code
if (recoveryKey.contains(' ')) {
- // Check if user has entered a mnemonic code
if (recoveryKey.split(' ').length != mnemonicKeyWordCount) {
throw AssertionError(
'recovery code should have $mnemonicKeyWordCount words',
);
}
- // Convert mnemonic code to hex
recoveryKey = bip39.mnemonicToEntropy(recoveryKey);
}
final attributes = getKeyAttributes();
Uint8List masterKey;
try {
- // Decrypt the master key that was earlier encrypted with the recovery key
masterKey = await CryptoUtil.decrypt(
CryptoUtil.base642bin(attributes!.masterKeyEncryptedWithRecoveryKey!),
CryptoUtil.hex2bin(recoveryKey),
@@ -604,7 +562,6 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
Future<void> setKey(String? key) async {
_key = key;
if (key == null) {
- // Used to clear key from secure storage
await _secureStorage.delete(key: keyKey);
} else {
await _secureStorage.write(key: keyKey, value: key);
@@ -614,7 +571,6 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
Future<void> setSecretKey(String? secretKey) async {
_secretKey = secretKey;
if (secretKey == null) {
- // Used to clear secret key from secure storage
await _secureStorage.delete(key: secretKeyKey);
} else {
await _secureStorage.write(key: secretKeyKey, value: secretKey);
diff --git a/mobile/apps/photos/lib/core/error-reporting/super_logging.dart b/mobile/apps/photos/lib/core/error-reporting/super_logging.dart
index 5a6174d709..58e957aa27 100644
--- a/mobile/apps/photos/lib/core/error-reporting/super_logging.dart
+++ b/mobile/apps/photos/lib/core/error-reporting/super_logging.dart
@@ -55,7 +55,6 @@ extension SuperLogRecord on LogRecord {
}
final responseData = e.response?.data;
if (responseData != null) {
- // Skip logging response data if it exceeds 100KB
final contentLength = int.tryParse(
e.response?.headers.value('content-length') ?? '',
);
@@ -85,65 +84,20 @@ extension SuperLogRecord on LogRecord {
}
class LogConfig {
- /// The DSN for a Sentry app.
- /// This can be obtained from the Sentry apps's "settings > Client Keys (DSN)" page.
- ///
- /// Only logs containing errors are sent to sentry.
- /// Errors can be caught using a try-catch block, like so:
- ///
- /// ```
- /// final logger = Logger("main");
- ///
- /// try {
- /// // do something dangerous here
- /// } catch(e, trace) {
- /// logger.info("Huston, we have a problem", e, trace);
- /// }
- /// ```
- ///
- /// If this is [null], Sentry logger is completely disabled (default).
String? sentryDsn;
String? tunnel;
- /// A built-in retry mechanism for sending errors to sentry.
- ///
- /// This parameter defines the time to wait for, before retrying.
Duration sentryRetryDelay;
- /// Path of the directory where log files will be stored.
- ///
- /// If this is [null], file logging is completely disabled (default).
- ///
- /// If this is an empty string (['']),
- /// then a 'logs' directory will be created in [getTemporaryDirectory()].
- ///
- /// A non-empty string will be treated as an explicit path to a directory.
- ///
- /// The chosen directory can be accessed using [SuperLogging.logFile.parent].
String? logDirPath;
- /// The maximum number of log files inside [logDirPath].
- ///
- /// One log file is created per day.
- /// Older log files are deleted automatically.
int maxLogFiles;
- /// Whether to enable super logging features in debug mode.
- ///
- /// Sentry and file logging are typically not needed in debug mode,
- /// where a complete logcat is available.
bool enableInDebugMode;
- /// If provided, super logging will invoke this function, and
- /// any uncaught errors during its execution will be reported.
- ///
- /// Works by using [FlutterError.onError] and [runZoned].
FutureOrVoidCallback? body;
- /// The date format for storing log files.
- ///
- /// `DateFormat('y-M-d')` by default.
DateFormat? dateFmt;
String prefix;
@@ -164,14 +118,12 @@ class LogConfig {
}
class SuperLogging {
- /// The logger for SuperLogging
static final $ = Logger('ente_logging');
static final String _loggerPrefixDefine = const String.fromEnvironment(
'ENTE_LOGGER_PREFIX',
).trim().toLowerCase();
- /// The current super logging configuration
static late LogConfig config;
static late SharedPreferences _preferences;
@@ -265,12 +217,10 @@ class SuperLogging {
options,
);
}
- // Filter out errors that should not be sent to Sentry
options.beforeSend = (SentryEvent event, Hint hint) async {
- // Check if the error should be skipped
final dynamic error = event.throwable;
if (error != null && _shouldSkipSentry(error)) {
- return null; // Returning null drops the event
+ return null;
}
return event;
};
@@ -336,8 +286,6 @@ class SuperLogging {
return result;
}
- /// Send an error to sentry, if enabled.
- /// // note: stack is not reported currently
static Future<void> _sendErrorToSentry(
Object error,
StackTrace? stack, {
@@ -352,7 +300,6 @@ class SuperLogging {
return;
}
- // Determine execution context from prefix
final executionContext = _getExecutionContext();
if (rec != null) {
@@ -402,7 +349,6 @@ class SuperLogging {
}());
}
- /// Determine execution context from prefix
static String _getExecutionContext() {
final prefix = config.prefix.trim();
if (prefix.isEmpty) return 'foreground';
@@ -438,7 +384,6 @@ class SuperLogging {
}
static Future onLogRecord(LogRecord rec) async {
- // log misc info if it changed
String? extraLines = "app version: '$appVersion'\n";
if (extraLines != _lastExtraLines) {
_lastExtraLines = extraLines;
@@ -448,7 +393,6 @@ class SuperLogging {
final str = (config.prefix) + " " + rec.toPrettyString(extraLines);
- // write to stdout
if (shouldPrintLogRecord(rec)) {
printLog(str);
}
@@ -462,7 +406,6 @@ class SuperLogging {
LogRecord? rec,
StackTrace? stackTrace,
}) {
- // push to log queue
if (fileIsEnabled) {
fileQueueEntries.add(str + '\n');
if (fileQueueEntries.length == 1) {
@@ -470,7 +413,6 @@ class SuperLogging {
}
}
- // add error to sentry queue
if (sentryIsEnabled && error != null) {
_sendErrorToSentry(
error,
@@ -496,8 +438,8 @@ class SuperLogging {
}
}
- // Logs on must be chunked or they get truncated otherwise
- // See https://github.com/flutter/flutter/issues/22665
+ // Chunk long logs to avoid truncation.
+ // https://github.com/flutter/flutter/issues/22665
static var logChunkSize = 800;
static void printLog(String text) {
@@ -507,10 +449,8 @@ class SuperLogging {
}
}
- /// A queue to be consumed by [setupSentry].
static final sentryQueueControl = StreamController<Error>();
- /// Whether sentry logging is currently enabled or not.
static bool sentryIsEnabled = false;
static Future<void> setupSentry() async {
@@ -538,7 +478,7 @@ class SuperLogging {
if (_preferences.containsKey(keyShouldReportCrashes)) {
return _preferences.getBool(keyShouldReportCrashes)!;
} else {
- return true; // Report crashes by default
+ return true;
}
}
@@ -546,29 +486,24 @@ class SuperLogging {
return _preferences.setBool(keyShouldReportCrashes, value);
}
- /// The log file currently in use.
static File? logFile;
- /// Whether file logging is currently enabled or not.
static bool fileIsEnabled = false;
static Future<void> setupLogDir() async {
var dirPath = config.logDirPath;
- // choose [logDir]
if (dirPath == null || dirPath.isEmpty) {
final root = await getExternalStorageDirectory();
dirPath = '${root!.path}/logs';
}
- // create [logDir]
final dir = Directory(dirPath);
await dir.create(recursive: true);
final files = <File>[];
final dates = <File, DateTime>{};
- // collect all log files with valid names
await for (final file in dir.list()) {
try {
final date = config.dateFmt!.parse(basename(file.path));
@@ -578,9 +513,7 @@ class SuperLogging {
}
final nowTime = DateTime.now();
- // delete old log files, if [maxLogFiles] is exceeded.
if (files.length > config.maxLogFiles) {
- // sort files based on ascending order of date (older first)
files.sort(
(a, b) => (dates[a] ?? nowTime).compareTo((dates[b] ?? nowTime)),
);
@@ -599,9 +532,6 @@ class SuperLogging {
logFile = File("$dirPath/${config.dateFmt!.format(DateTime.now())}.log");
}
- /// Current app version, obtained from package_info plugin.
- ///
- /// See: [getAppVersion]
static String? appVersion;
static Future<String> getAppVersion() async {
@@ -618,8 +548,6 @@ class SuperLogging {
return pkgName.startsWith("io.ente.photos.fdroid");
}
- /// Show the log viewer page
- /// This is the main integration point for accessing the log viewer
static void showLogViewer(BuildContext context) {
Navigator.push(
context,
diff --git a/mobile/apps/photos/lib/db/collections_db.dart b/mobile/apps/photos/lib/db/collections_db.dart
index c38ec02e11..bddef84383 100644
--- a/mobile/apps/photos/lib/db/collections_db.dart
+++ b/mobile/apps/photos/lib/db/collections_db.dart
@@ -231,8 +231,6 @@ class CollectionsDB {
return collections;
}
- // getActiveCollectionIDsAndUpdationTime returns map of collectionID to
- // updationTime for non-deleted collections
Future<Map<int, int>> getActiveIDsAndRemoteUpdateTime() async {
final db = await instance.database;
final rows = await db.query(
@@ -319,7 +317,6 @@ class CollectionsDB {
),
int.parse(row[columnUpdationTime]),
sharedAt: _parseNullableInt(row[columnSharedAt]),
- // default to False is columnIsDeleted is not set
isDeleted: (row[columnIsDeleted] ?? _sqlBoolFalse) == _sqlBoolTrue,
);
result.mMdVersion = row[columnMMdVersion] ?? 0;
diff --git a/mobile/apps/photos/lib/db/device_files_db.dart b/mobile/apps/photos/lib/db/device_files_db.dart
index fe14c516b4..953e6c2929 100644
--- a/mobile/apps/photos/lib/db/device_files_db.dart
+++ b/mobile/apps/photos/lib/db/device_files_db.dart
@@ -202,7 +202,6 @@ extension DeviceFiles on FilesDB {
UPDATE device_collections SET name = ? WHERE id = ?;
''', parameterSetsForUpdate);
- // add the mappings for localIDs
if (pathIDToLocalIDsMap.isNotEmpty) {
await insertPathIDToLocalIDMapping(pathIDToLocalIDsMap);
}
@@ -257,7 +256,6 @@ extension DeviceFiles on FilesDB {
hasUpdated = true;
}
}
- // delete existing pathIDs which are missing on device
existingPathIds.removeAll(devicePathInfo.map((e) => e.item1.id).toSet());
if (existingPathIds.isNotEmpty) {
_logger.info(
@@ -293,8 +291,6 @@ extension DeviceFiles on FilesDB {
}
}
- // getDeviceSyncCollectionIDs returns the collectionIDs for the
- // deviceCollections which are marked for auto-backup
Future<Set<int>> getDeviceSyncCollectionIDs() async {
final db = await sqliteAsyncDB;
final rows = await db.getAll('''
diff --git a/mobile/apps/photos/lib/db/file_updation_db.dart b/mobile/apps/photos/lib/db/file_updation_db.dart
index 82942a3728..6f2b2b5de7 100644
--- a/mobile/apps/photos/lib/db/file_updation_db.dart
+++ b/mobile/apps/photos/lib/db/file_updation_db.dart
@@ -18,7 +18,6 @@ class FileUpdationDB {
static const modificationTimeUpdated = 'modificationTimeUpdated';
- // SQL code to create the database table
static List<String> _createTable() {
return [
'''
@@ -52,16 +51,13 @@ class FileUpdationDB {
static final FileUpdationDB instance = FileUpdationDB._privateConstructor();
- // only have a single app-wide reference to the database
static Future<Database>? _dbFuture;
Future<Database> get database async {
- // lazily instantiate the db the first time it is accessed
_dbFuture ??= _initDatabase();
return _dbFuture!;
}
- // this opens the database (and creates it if it doesn't exist)
Future<Database> _initDatabase() async {
final Directory documentsDirectory =
await getApplicationDocumentsDirectory();
@@ -117,7 +113,6 @@ class FileUpdationDB {
''');
}
- // check if entry existing for given localID and reason
Future<bool> isExisting(String localID, String reason) async {
final db = await instance.database;
final String whereClause =
@@ -140,7 +135,6 @@ class FileUpdationDB {
return result;
}
- // delete entries for given list of reasons
Future<void> deleteByReasons(List<String> reasons) async {
if (reasons.isEmpty) {
return;
diff --git a/mobile/apps/photos/lib/db/files_db.dart b/mobile/apps/photos/lib/db/files_db.dart
index 5451b1043f..3a3a80ab1f 100644
--- a/mobile/apps/photos/lib/db/files_db.dart
+++ b/mobile/apps/photos/lib/db/files_db.dart
@@ -1091,7 +1091,6 @@ class FilesDB with SqlDbBase {
return result;
}
- // Remove queued rows whose local IDs also have uploaded rows.
Future<int> removeQueuedLocalFiles(Set<String> localIDs, int ownerID) async {
if (localIDs.isEmpty) {
_logger.finest("No local IDs provided for removal");
@@ -1248,10 +1247,6 @@ class FilesDB with SqlDbBase {
);
}
- /*
- This method should only return localIDs which are not uploaded yet
- and can be mapped to incoming remote entry
- */
Future<List<EnteFile>> getUnlinkedLocalMatchesForRemoteFile(
int ownerID,
String localID,
@@ -1398,7 +1393,6 @@ class FilesDB with SqlDbBase {
Future<void> deleteLocalFile(EnteFile file) async {
final db = await instance.sqliteAsyncDB;
if (file.localID != null) {
- // Delete every queued row with the same local ID.
unawaited(
db.execute(
'DELETE FROM $filesTable WHERE $columnLocalID = ? AND ($columnUploadedFileID IS NULL OR $columnUploadedFileID = -1)',
@@ -2080,7 +2074,6 @@ class FilesDB with SqlDbBase {
return results.isNotEmpty;
}
- // Clear every collection row for each uploaded file.
Future<void> clearLocalIDsForUploadedFileIDs(
List<int> uploadedFileIDs,
) async {
diff --git a/mobile/apps/photos/lib/db/ignored_files_db.dart b/mobile/apps/photos/lib/db/ignored_files_db.dart
index bd0e24c330..774cca2cc9 100644
--- a/mobile/apps/photos/lib/db/ignored_files_db.dart
+++ b/mobile/apps/photos/lib/db/ignored_files_db.dart
@@ -6,10 +6,7 @@ import 'package:path_provider/path_provider.dart';
import 'package:photos/models/ignored_file.dart';
import 'package:sqflite/sqflite.dart';
-// Keeps track of localIDs which should be not uploaded to ente without
-// user's intervention.
-// Common use case:
-// when a user deletes a file just from ente on current or different device.
+// Prevent files deleted from Ente from being reuploaded without user action.
class IgnoredFilesDB {
static const _databaseName = "ente.ignored_files.db";
static const _databaseVersion = 1;
@@ -39,16 +36,13 @@ class IgnoredFilesDB {
static final IgnoredFilesDB instance = IgnoredFilesDB._privateConstructor();
- // only have a single app-wide reference to the database
static Future<Database>? _dbFuture;
Future<Database> get database async {
- // lazily instantiate the db the first time it is accessed
_dbFuture ??= _initDatabase();
return _dbFuture!;
}
- // this opens the database (and creates it if it doesn't exist)
Future<Database> _initDatabase() async {
final Directory documentsDirectory =
await getApplicationDocumentsDirectory();
diff --git a/mobile/apps/photos/lib/db/ml/clip_vector_db.dart b/mobile/apps/photos/lib/db/ml/clip_vector_db.dart
index f78ba43d84..22f7254807 100644
--- a/mobile/apps/photos/lib/db/ml/clip_vector_db.dart
+++ b/mobile/apps/photos/lib/db/ml/clip_vector_db.dart
@@ -23,7 +23,6 @@ class ClipVectorDB {
static Logger get logger => _logger;
- // Singleton pattern
ClipVectorDB._privateConstructor(this._databaseName, this._migrationKey);
static final instance = ClipVectorDB._privateConstructor(
"ente.ml.vectordb.clip.usearch",
@@ -35,7 +34,6 @@ class ClipVectorDB {
);
factory ClipVectorDB() => instance;
- // only have a single app-wide reference to the database
Future<VectorDb>? _vectorDbFuture;
Future<void>? _warmupFuture;
final Lock _writeLock = Lock();
@@ -448,7 +446,6 @@ class VectorDbStats {
final int capacity;
final int dimensions;
- // in bytes
final int fileSize;
final int memoryUsage;
diff --git a/mobile/apps/photos/lib/db/trash_db.dart b/mobile/apps/photos/lib/db/trash_db.dart
index b243a72088..556583dbaf 100644
--- a/mobile/apps/photos/lib/db/trash_db.dart
+++ b/mobile/apps/photos/lib/db/trash_db.dart
@@ -8,10 +8,7 @@ import 'package:photos/models/file/trash_file.dart';
import 'package:photos/models/file_load_result.dart';
import 'package:sqflite/sqflite.dart';
-// The TrashDB doesn't need to flatten and store all attributes of a file.
-// Before adding any other column, we should evaluate if we need to query on that
-// column or not while showing trashed items. Even if we miss storing any new attributes,
-// during restore, all file attributes will be fetched & stored as required.
+// Store only fields needed to query trash. Restore fetches the full file.
class TrashDB {
static const _databaseName = "ente.trash.db";
static const _databaseVersion = 2;
@@ -33,7 +30,6 @@ class TrashDB {
static const columnCreationTime = 'creation_time';
static const columnLocalID = 'local_id';
- // standard file metadata, which isn't editable
static const columnFileMetadata = 'file_metadata';
static const columnMMdEncodedJson = 'mmd_encoded_json';
@@ -82,16 +78,13 @@ class TrashDB {
static final TrashDB instance = TrashDB._privateConstructor();
- // only have a single app-wide reference to the database
static Future<Database>? _dbFuture;
Future<Database> get database async {
- // lazily instantiate the db the first time it is accessed
_dbFuture ??= _initDatabase();
return _dbFuture!;
}
- // this opens the database (and creates it if it doesn't exist)
Future<Database> _initDatabase() async {
final Directory documentsDirectory =
await getApplicationDocumentsDirectory();
@@ -195,7 +188,7 @@ class TrashDB {
trashFile.updateAt = row[columnTrashUpdatedAt];
trashFile.deleteBy = row[columnTrashDeleteBy];
trashFile.uploadedFileID = row[columnUploadedFileID];
- // dirty hack to ensure that the file_downloads & cache mechanism works
+ // Trash rows need a synthetic generatedID for download and cache keys.
trashFile.generatedID = -1 * trashFile.uploadedFileID!;
trashFile.ownerID = row[columnOwnerID];
trashFile.collectionID = row[columnCollectionID] == -1
diff --git a/mobile/apps/photos/lib/db/upload_locks_db.dart b/mobile/apps/photos/lib/db/upload_locks_db.dart
index 643916b28a..187c2158e9 100644
--- a/mobile/apps/photos/lib/db/upload_locks_db.dart
+++ b/mobile/apps/photos/lib/db/upload_locks_db.dart
@@ -352,7 +352,6 @@ class UploadLocksDB {
partsURLs: partsURLs,
);
- // Retrieve MD5 data
final String? fileMd5 = row[_trackUploadTable.columnFileMd5] as String?;
List<String>? partMd5s;
if (row[_trackUploadTable.columnPartMd5s] != null) {
@@ -374,7 +373,6 @@ class UploadLocksDB {
);
}
- // validateResume checks if the cached links are valid for resuming upload
void _validateResume(
List<Map<String, Object?>> rows,
String localId,
@@ -541,7 +539,6 @@ class UploadLocksDB {
);
}
- // getFileNameToLastAttemptedAtMap returns a map of encrypted file name to last attempted at time
Future<Map<String, int>> getFileNameToLastAttemptedAtMap() {
return database.then((db) async {
final rows = await db.query(
@@ -590,7 +587,6 @@ class UploadLocksDB {
});
}
- // Stream Queue Management Methods
Future<void> addToStreamQueue(
int uploadedFileID,
String queueType, // 'create' or 'recreate'
diff --git a/mobile/apps/photos/lib/models/collection/smart_album_config.dart b/mobile/apps/photos/lib/models/collection/smart_album_config.dart
index 50b4d6eb2e..5682a26045 100644
--- a/mobile/apps/photos/lib/models/collection/smart_album_config.dart
+++ b/mobile/apps/photos/lib/models/collection/smart_album_config.dart
@@ -1,13 +1,10 @@
typedef PersonInfo = ({int updatedAt, Set<int> addedFiles});
class SmartAlbumConfig {
- // A nullable remote ID for syncing purposes
final String? id;
final int collectionId;
- // person ids
final Set<String> personIDs;
- // person id mapped with updatedat, file ids
final Map<String, PersonInfo> infoMap;
final int updatedAt;
@@ -24,12 +21,10 @@ class SmartAlbumConfig {
final toRemove = personIDs.difference(newPersonsIds);
final newInfoMap = Map<String, PersonInfo>.from(infoMap);
- // Remove whats not needed
for (final personId in toRemove) {
newInfoMap.remove(personId);
}
- // Add files which are needed
for (final personId in toAdd) {
newInfoMap[personId] = (updatedAt: 0, addedFiles: <int>{});
}
@@ -73,7 +68,6 @@ class SmartAlbumConfig {
);
}
- // toJson and fromJson methods
Map<String, dynamic> toJson() {
return {
"collection_id": collectionId,
diff --git a/mobile/apps/photos/lib/module/download/gallery.dart b/mobile/apps/photos/lib/module/download/gallery.dart
index c3f8ba8e5f..d9a2533c11 100644
--- a/mobile/apps/photos/lib/module/download/gallery.dart
+++ b/mobile/apps/photos/lib/module/download/gallery.dart
@@ -22,10 +22,6 @@ import "package:photos/utils/gallery_save_title.dart";
final _logger = Logger("file_download_util");
-/// Use this instead of `file.displayName` directly for skip toasts.
-///
-/// Rationale:
-/// 1. We prefer the original title for stable, filename-like copy in the toast.
String getDownloadSkipToastFileName(EnteFile file) {
final title = (file.title ?? "").trim();
final displayName = file.displayName.trim();
diff --git a/mobile/apps/photos/lib/module/download/manager.dart b/mobile/apps/photos/lib/module/download/manager.dart
index 7b018e2bc7..8276898f8a 100644
--- a/mobile/apps/photos/lib/module/download/manager.dart
+++ b/mobile/apps/photos/lib/module/download/manager.dart
@@ -21,10 +21,8 @@ class DownloadManager {
final Dio _dio;
- // In-memory storage for download tasks
final Map<int, DownloadTask> _tasks = {};
- // Active downloads with their completers and streams
final Map<int, Completer<DownloadResult>> _completers = {};
final Map<int, StreamController<DownloadTask>> _streams = {};
final Map<int, CancelToken> _cancelTokens = {};
@@ -32,7 +30,6 @@ class DownloadManager {
DownloadManager(this._dio);
- /// Subscribe to download progress updates for a specific file ID
Stream<DownloadTask> watchDownload(int fileId) {
_streams[fileId] ??= StreamController<DownloadTask>.broadcast();
return _streams[fileId]!.stream;
@@ -44,15 +41,12 @@ class DownloadManager {
return size > downloadChunkSize;
}
- /// Start download and return a Future that completes when download finishes
- /// If download was paused, calling this again will resume it
Future<DownloadResult> download(
int fileId,
String filename,
int totalBytes,
) async {
_downloadStartTimes[fileId] = DateTime.now().microsecondsSinceEpoch;
- // If already downloading, return existing future
if (_completers.containsKey(fileId)) {
return _completers[fileId]!.future;
}
@@ -60,21 +54,16 @@ class DownloadManager {
final completer = Completer<DownloadResult>();
_completers[fileId] = completer;
- // Get or create task
final existingTask = _tasks[fileId];
final task =
existingTask ??
DownloadTask(id: fileId, filename: filename, totalBytes: totalBytes);
- // Store task in memory
_tasks[fileId] = task;
- // Don't restart if already completed
if (task.isCompleted) {
- // ensure that the file exists
final filePath = task.filePath;
if (filePath == null || !(await File(filePath).exists())) {
- // If the file doesn't exist, mark the task as error
_logger.warning(
'File not found for ${task.filename} (${task.bytesDownloaded}/${task.totalBytes} bytes)',
);
@@ -100,11 +89,9 @@ class DownloadManager {
return completer.future;
}
- /// Pause download
Future<void> pause(int fileId) async {
- // ignore cancel if download started less than 1 second ago,
- // this is to avoid cancellination due to different type of video players, where dispose is called
- // little later after other video player operations
+ // Video player disposal can issue a late pause, so ignore pauses during
+ // the first second.
final startTime = _downloadStartTimes[fileId];
if (startTime == null ||
DateTime.now().microsecondsSinceEpoch - startTime < 1e6) {
@@ -121,7 +108,6 @@ class DownloadManager {
_updateTask(task.copyWith(status: DownloadStatus.paused));
}
- // Clean up streams if no listeners
final stream = _streams[fileId];
if (stream != null && !stream.hasListener) {
await stream.close();
@@ -129,7 +115,6 @@ class DownloadManager {
}
}
- /// Cancel and delete download
Future<void> cancel(int fileId) async {
final token = _cancelTokens[fileId];
if (token != null && !token.isCancelled) {
@@ -145,10 +130,8 @@ class DownloadManager {
_cleanup(fileId);
}
- /// Get current download status
Future<DownloadTask?> getDownload(int fileId) async => _tasks[fileId];
- /// Get all downloads
Future<List<DownloadTask>> getAllDownloads() async => _tasks.values.toList();
Future<void> _startDownload(
@@ -165,7 +148,6 @@ class DownloadManager {
final directory = Configuration.instance.getTempDirectory();
final basePath = '$directory${task.id}.encrypted';
- // check if base file already exists and is of correct size
final baseFile = File(basePath);
if (await baseFile.exists()) {
final existingSize = await baseFile.length();
@@ -190,7 +172,6 @@ class DownloadManager {
}
}
- // Check existing chunks and calculate progress
final totalChunks = (task.totalBytes / downloadChunkSize).ceil();
final existingChunks = await _validateExistingChunks(
basePath,
@@ -244,7 +225,6 @@ class DownloadManager {
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) {
_logger.info('Download cancelled for ${task.filename}');
- // Complete future with current task state (paused or cancelled)
final currentTask = _tasks[task.id];
if (currentTask != null && !completer.isCompleted) {
completer.complete(DownloadResult(currentTask, false));
@@ -354,7 +334,6 @@ class DownloadManager {
_notifyProgress(updatedTask);
},
);
- // Update progress after chunk completion
final chunkFileSize = await File(chunkPath).length();
task = task.copyWith(
bytesDownloaded: (chunkIndex) * downloadChunkSize + chunkFileSize,
@@ -423,7 +402,6 @@ class DownloadManager {
final finalFile = File(basePath);
if (await finalFile.exists()) await finalFile.delete();
- // Delete chunk files
final totalChunks = (task.totalBytes / downloadChunkSize).ceil();
for (int i = 1; i <= totalChunks; i++) {
final chunkFile = File(_getChunkPath(basePath, i));
diff --git a/mobile/apps/photos/lib/module/metadata/asset_date_times.dart b/mobile/apps/photos/lib/module/metadata/asset_date_times.dart
index bdb857898e..e8752216b0 100644
--- a/mobile/apps/photos/lib/module/metadata/asset_date_times.dart
+++ b/mobile/apps/photos/lib/module/metadata/asset_date_times.dart
@@ -15,11 +15,8 @@ const _minDateTimeSecondsSinceEpoch = -_maxDateTimeSecondsSinceEpoch;
typedef AssetDateTimes = ({int creationTime, int modificationTime});
-/// Compares at the whole-second precision provided by photo_manager.
-///
-/// Uses the raw asset timestamps, counting invalid ones as epoch, so that
-/// assets with broken dates are picked up during first import (cutoff 0) but
-/// not re-flagged as updated on every incremental sync.
+// Treat invalid dates as epoch so the first import sees them without every
+// incremental sync flagging them again.
bool isAssetAtOrAfterSyncCutoff(AssetEntity asset, int cutoffTime) {
final latestAssetTimeSecond = max(
_validSecondsSinceEpoch(asset.createDateSecond) ?? 0,
diff --git a/mobile/apps/photos/lib/module/metadata/local_file.dart b/mobile/apps/photos/lib/module/metadata/local_file.dart
index 5810eafb56..e3724db996 100644
--- a/mobile/apps/photos/lib/module/metadata/local_file.dart
+++ b/mobile/apps/photos/lib/module/metadata/local_file.dart
@@ -22,8 +22,6 @@ EnteFile fileFromAsset(String deviceFolder, AssetEntity asset) {
..metadataVersion = -1;
}
-/// Applies creation-time precedence without fetching or decoding more media.
-/// Offline import runs this in batches and persists only this derived field.
void applyCreationTimeMetadata(EnteFile file, ParsedExifDateTime? exifTime) {
final hasExifTime = exifTime != null;
if (exifTime != null) {
diff --git a/mobile/apps/photos/lib/module/upload/service/existing_upload_resolver.dart b/mobile/apps/photos/lib/module/upload/service/existing_upload_resolver.dart
index a11308d7c4..174887d955 100644
--- a/mobile/apps/photos/lib/module/upload/service/existing_upload_resolver.dart
+++ b/mobile/apps/photos/lib/module/upload/service/existing_upload_resolver.dart
@@ -25,11 +25,6 @@ typedef LinkExistingUpload =
});
typedef EmitLocalPhotosUpdated = void Function(LocalPhotosUpdatedEvent event);
-/// Resolves a pending upload to an already-uploaded file with the same hash.
-///
-/// Resolution priority and side effects intentionally match the legacy upload
-/// flow: same local file in the target collection, missing local ID, same local
-/// file in another collection, then no mapping.
class ExistingUploadResolver {
ExistingUploadResolver({
required FindUploadedFiles findUploadedFiles,
@@ -71,7 +66,6 @@ class ExistingUploadResolver {
final LinkExistingUpload _linkExistingUpload;
final EmitLocalPhotosUpdated _emitLocalPhotosUpdated;
- /// Returns the mapped file, or `null` when the caller should upload it.
Future<EnteFile?> resolve({
required String fileHash,
required EnteFile fileToUpload,
@@ -98,7 +92,8 @@ class ExistingUploadResolver {
return null;
}
- // Case a: the same local file is already in the target collection.
+ // Resolution order matters because branches can delete or relink the
+ // pending row.
final sameLocalSameCollection = existingUploadedFiles.firstWhereOrNull(
(file) =>
file.collectionID == targetCollectionID &&
@@ -116,7 +111,6 @@ class ExistingUploadResolver {
return sameLocalSameCollection;
}
- // Case b: reuse an uploaded file whose local ID is not known yet.
final fileMissingLocal = existingUploadedFiles.firstWhereOrNull(
(file) => file.localID == null,
);
@@ -137,7 +131,6 @@ class ExistingUploadResolver {
return fileMissingLocal;
}
- // Case c: link the same local file from another collection.
final fileInDifferentCollection = existingUploadedFiles.firstWhereOrNull(
(file) =>
file.collectionID != targetCollectionID &&
@@ -155,7 +148,6 @@ class ExistingUploadResolver {
);
}
- // Case d: the hash belongs to a different local file, so upload this one.
final matchLocalIDs = existingUploadedFiles
.where((file) => file.localID != null)
.map((file) => file.localID!)
diff --git a/mobile/apps/photos/lib/module/upload/service/file_uploader.dart b/mobile/apps/photos/lib/module/upload/service/file_uploader.dart
index f6b1cf95e2..8c1599c2e2 100644
--- a/mobile/apps/photos/lib/module/upload/service/file_uploader.dart
+++ b/mobile/apps/photos/lib/module/upload/service/file_uploader.dart
@@ -46,7 +46,6 @@ import "package:photos/utils/network_util.dart";
import 'package:shared_preferences/shared_preferences.dart';
import "package:uuid/uuid.dart";
-/// Coordinates encryption, transfer, persistence, and retries for file uploads.
class FileUploader {
static const kMaximumConcurrentUploads = 4;
static const kMaximumConcurrentVideoUploads = 2;
@@ -73,10 +72,8 @@ class FileUploader {
final kBGTaskDeathTimeout = const Duration(seconds: 5).inMicroseconds;
Map<String, BackupItem> get allBackups => _queue.backupItems;
- /// Returns true if any file uploads are currently in progress
bool get isUploading => _queue.isUploading;
- /// Returns true if an upload is queued, running, or waiting in background.
bool get hasPendingUploads => _queue.hasPendingUploads;
late ProcessType _processType;
late SharedPreferences _prefs;
@@ -168,8 +165,6 @@ class FileUploader {
});
}
- // upload future will return null as File when the file entry is deleted
- // locally because it's already present in the destination collection.
Future<EnteFile> upload(EnteFile file, int collectionID) {
if (file.localID == null || file.localID!.isEmpty) {
return Future.error(Exception("file's localID can not be null or empty"));
@@ -179,8 +174,6 @@ class FileUploader {
_pollQueue();
return request.item.completer.future;
}
- // If the file exists in the queue for a matching collectionID,
- // return the existing future
if (request.disposition == UploadQueueDisposition.sameCollection) {
return request.item.completer.future;
}
@@ -188,8 +181,6 @@ class FileUploader {
"Wait on another upload on same local ID to finish before "
"adding it to new collection",
);
- // Else wait for the existing upload to complete,
- // and add it to the relevant collection
return request.item.completer.future.then((uploadedFile) async {
_logger.info(
"original upload completer resolved, try adding the file to another "
@@ -212,8 +203,6 @@ class FileUploader {
_queue.clear(reason);
}
- /// Validates that the user can upload before starting expensive encryption.
- /// Throws on 402 (no subscription) or 426 (storage exceeded).
Future<void> validateUploadEligibility() async {
try {
await _gateway.validateUploadEligibility();
@@ -300,8 +289,6 @@ class FileUploader {
_uploadArtifactLifecycle.removeStaleFiles();
Future<void> checkNetworkForUpload({bool isForceUpload = false}) async {
- // Note: We don't support force uploading currently. During force upload,
- // network check is skipped completely
if (isForceUpload) {
return;
}
@@ -316,15 +303,12 @@ class FileUploader {
if (Platform.isAndroid) {
final bool hasPermission = await Permission.accessMediaLocation.isGranted;
if (!hasPermission) {
- // In background isolate, we can't request permissions (no UI available)
- // Throw an error to properly handle this scenario
if (isProcessBg) {
_logger.severe(
"Media location access not granted in background isolate - cannot request permission",
);
throw NoMediaLocationAccessError();
}
- // Only request permission in foreground
final permissionStatus = await Permission.accessMediaLocation.request();
if (!permissionStatus.isGranted) {
_logger.severe(
@@ -437,9 +421,6 @@ class FileUploader {
try {
mediaUploadData = await getUploadDataFromEnteFile(file);
} catch (e) {
- // This additional try catch block is added because for resumable upload,
- // we need to compute the hash before the next step. Previously, this
- // was done in during the upload itself.
if (e is InvalidFileError) {
_logger.severe("File upload ignored for " + file.toString(), e);
await _onInvalidFileError(file, e);
@@ -465,8 +446,6 @@ class FileUploader {
late final int encThumbSize;
var uploadCompleted = false;
- // This flag is used to decide whether to clear the iOS origin file cache
- // or not.
var uploadHardFailure = false;
try {
@@ -500,7 +479,7 @@ class FileUploader {
debugPrint(
"File success mapped to existing uploaded ${file.toString()}",
);
- // treat as completed so _onUploadDone clears the source export
+ // Treat as completed so _onUploadDone clears the source export.
uploadCompleted = true;
return mappedFile;
}
@@ -508,8 +487,7 @@ class FileUploader {
final encryptedFileExists = File(encryptedFilePath).existsSync();
- // If the multipart entry exists but the encrypted file doesn't, it means
- // that we'll have to re-upload as the nonce is lost
+ // A missing encrypted file cannot be resumed because its nonce is lost.
if (hasExistingMultiPart) {
if (!encryptedFileExists) {
throw MultiPartFileMissingError(
@@ -524,15 +502,12 @@ class FileUploader {
throw MultiPartError('multiPart update resumed with differentKey');
}
} else if (encryptedFileExists) {
- // otherwise just delete the file for singlepart upload
_logger.severe('File exists without multipart entry, deleting file');
await File(encryptedFilePath).delete();
}
await _checkIfWithinStorageLimit(mediaUploadData.sourceFile);
final encryptedFile = File(encryptedFilePath);
- // Calculate the number of parts to determine if we need MD5
- // Use source length to estimate encrypted size for part count decision
final estimatedEncSize = CryptoUtil.estimateEncryptedSize(sourceLength);
final estimatedCount = _multiPartUploader.calculatePartCount(
estimatedEncSize,
@@ -583,7 +558,6 @@ class FileUploader {
encThumbSize = await encryptedThumbnailFile.length();
final thumbnailMd5 = await computeMd5(encryptedThumbnailPath);
- // Calculate the number of parts for the file.
final count = _multiPartUploader.calculatePartCount(encFileSize);
late String fileObjectKey;
@@ -654,10 +628,7 @@ class FileUploader {
onSendProgress: onSendProgress,
);
}
- // in case of multipart, upload the thumbnail towards the end to avoid
- // re-uploading the thumbnail in case of failure.
- // In regular upload, always upload the thumbnail first to keep existing behaviour
- //
+ // Send the thumbnail last so multipart retries do not re-upload it.
thumbnailObjectKey = await _uploadTransport!.uploadSinglePart(
encryptedThumbnailFile,
encThumbSize,
@@ -714,8 +685,6 @@ class FileUploader {
);
EnteFile remoteFile;
if (isUpdatedFile) {
- // Verify that the encrypted file can be decrypted before uploading
- // For updates, we need to verify with the existing file key
await CryptoUtil.decryptVerify(
encryptedFilePath,
fileDecryptionHeader,
@@ -728,7 +697,6 @@ class FileUploader {
file: file,
data: commitData,
);
- // Update across all collections
await FilesDB.instance.updateUploadedFileAcrossCollections(remoteFile);
// The update response does not carry public magic metadata, so derived values
// (width/height, mediaType, exif, camera) that change when the file is
@@ -824,7 +792,7 @@ class FileUploader {
e is FileTooLargeForPlanError ||
e is NoActiveSubscriptionError ||
e is InvalidFileError)) {
- // file upload can not be retried in such cases without user intervention
+ // These failures cannot be retried without user intervention.
uploadHardFailure = true;
}
if ((isMultipartUpload || hasExistingMultiPart) &&
@@ -900,15 +868,8 @@ class FileUploader {
await _uploadLocks.releaseLock(lockKey, _processType.toString());
}
- /*
- _checkIfWithinStorageLimit verifies if the file size for encryption and upload
- is within the storage limit. It throws StorageLimitExceededError if the limit
- is exceeded. This check is best effort and may not be completely accurate
- due to UserDetail cache. It prevents infinite loops when clients attempt to
- upload files that exceed the server's storage limit + buffer.
- Note: Local storageBuffer is 20MB, server storageBuffer is 50MB, and an
- additional 30MB is reserved for thumbnails and encryption overhead.
- */
+ // Keep the client buffer 30 MB below the server buffer for thumbnail and
+ // encryption overhead. Cached user details make this check best-effort.
Future<void> _checkIfWithinStorageLimit(File fileToBeUploaded) async {
try {
final UserDetails? userDetails = UserService.instance
@@ -916,7 +877,6 @@ class FileUploader {
if (userDetails == null) {
return;
}
- // add k20MBStorageBuffer to the free storage
final num freeStorage = userDetails.getFreeStorage() + k20MBStorageBuffer;
final int fileSize = await fileToBeUploaded.length();
if (fileSize > freeStorage) {
@@ -956,8 +916,6 @@ class FileUploader {
file.deviceFolder != null &&
file.title != null &&
!file.isSharedMediaToAppSandbox;
- // If the file is not uploaded yet and either it can not be ignored or the
- // err is related to live photo media, delete the local entry
final bool deleteEntry =
!file.isUploaded && (!canIgnoreFile || e.reason.isLivePhotoErr);
@@ -978,8 +936,6 @@ class FileUploader {
}
}
- // _pollBackgroundUploadStatus polls the background uploads to check if the
- // upload is completed or failed.
Future<void> _pollBackgroundUploadStatus() async {
final blockedUploads = _queue.backgroundItems;
for (final upload in blockedUploads) {
@@ -1009,9 +965,8 @@ class FileUploader {
"Background upload failure detected ${file.tag}: "
"$persistedState",
);
- // The upload status is marked as in background, but the file is not locked
- // by the background process. Release any lock taken by the foreground process
- // and complete the completer with error.
+ // The upload is marked as in background but has no background lock.
+ // Release any foreground lock and complete it with an error.
final releasedForegroundLocks = await _uploadLocks.releaseLock(
file.localID!,
ProcessType.foreground.toString(),
diff --git a/mobile/apps/photos/lib/module/upload/service/local_file_update_service.dart b/mobile/apps/photos/lib/module/upload/service/local_file_update_service.dart
index 2097fc382e..ec6f61bf2e 100644
--- a/mobile/apps/photos/lib/module/upload/service/local_file_update_service.dart
+++ b/mobile/apps/photos/lib/module/upload/service/local_file_update_service.dart
@@ -11,7 +11,6 @@ import 'package:photos/module/download/file.dart';
import "package:photos/module/upload/upload_data.dart";
import 'package:shared_preferences/shared_preferences.dart';
-/// Finds device files whose contents changed after upload and queues updates.
class LocalFileUpdateService {
static final instance = LocalFileUpdateService._privateConstructor();
@@ -59,7 +58,6 @@ class LocalFileUpdateService {
}
Future<void> _cleanUpOlderMigration() async {
- // check if any old_migration_keys are present in shared preferences
bool hasOldMigrationKey = false;
for (String key in _oldMigrationKeys) {
if (_prefs.containsKey(key)) {
@@ -83,15 +81,9 @@ class LocalFileUpdateService {
}
}
- // This method analyses all of local files for which the file
- // modification/update time was changed. It checks if the existing fileHash
- // is different from the hash of uploaded file. If fileHash are different,
- // then it marks the file for file update.
Future<void> _markFilesWhichAreActuallyUpdated() async {
final sTime = DateTime.now().microsecondsSinceEpoch;
- // singleRunLimit indicates number of files to check during single
- // invocation of this method. The limit act as a crude way to limit the
- // resource consumed by the method
+ // Limit each run to bound resource use.
const int singleRunLimit = 10;
final localIDsToProcess = await _fileUpdationDB
.getLocalIDsForPotentialReUpload(
diff --git a/mobile/apps/photos/lib/module/upload/service/multipart.dart b/mobile/apps/photos/lib/module/upload/service/multipart.dart
index 45ffe6c08b..defb73f1ef 100644
--- a/mobile/apps/photos/lib/module/upload/service/multipart.dart
+++ b/mobile/apps/photos/lib/module/upload/service/multipart.dart
@@ -46,7 +46,6 @@ class MultiPartUploader {
final encryptKeyNonce = CryptoUtil.base642bin(result.keyNonce);
- // Get the full multipart info to access MD5 data
final multipartInfo = await _db.getCachedLinks(
localId,
fileHash,
@@ -78,7 +77,6 @@ class MultiPartUploader {
endpointConfig.isProduction;
int calculatePartCount(int fileSize) {
- // If the feature flag is disabled, return 1
if (!_featureFlagService.enableMobMultiPart) return 1;
if (!localSettings.userEnabledMultiplePart) return 1;
@@ -93,7 +91,6 @@ class MultiPartUploader {
required List<String> partMd5s,
}) async {
try {
- // Expected number of parts for given content and part length
final recomputedCount = (contentLength / partLength).ceil();
final urls = await _gateway.getMultipartUploadUrl(
@@ -101,7 +98,6 @@ class MultiPartUploader {
partLength: partLength,
partMd5s: partMd5s,
);
- // Validate server respected the requested count/segmentation
if (urls.partsURLs.length != recomputedCount ||
count != recomputedCount) {
_logger.severe(
@@ -174,7 +170,6 @@ class MultiPartUploader {
Map<int, String> etags = multipartInfo.partETags ?? {};
if (multipartInfo.status == MultipartStatus.pending) {
- // upload individual parts and get their etags
try {
etags = await _uploadParts(
multipartInfo,
@@ -204,7 +199,6 @@ class MultiPartUploader {
}
if (multipartInfo.status != MultipartStatus.completed) {
- // complete the multipart upload
try {
await _completeMultipartUpload(
multipartInfo.urls.objectKey,
@@ -239,7 +233,6 @@ class MultiPartUploader {
List<String>? partMd5s,
ProgressCallback? onSendProgress,
}) async {
- // upload individual parts and get their etags
final etags = await _uploadParts(
MultipartInfo(
urls: urls,
@@ -251,7 +244,6 @@ class MultiPartUploader {
onSendProgress: onSendProgress,
);
- // complete the multipart upload
await _completeMultipartUpload(urls.objectKey, etags, urls.completeURL);
return urls.objectKey;
@@ -272,7 +264,6 @@ class MultiPartUploader {
int i = 0;
final partSize = partInfo.partSize ?? multipartPartSizeForUpload;
- // Go to the first part that is not uploaded
while (i < (partUploadStatus?.length ?? 0) &&
(partUploadStatus?[i] ?? false)) {
i++;
@@ -284,7 +275,6 @@ class MultiPartUploader {
"File size mismatch. Expected ${partInfo.encFileSize} but got $encFileLength",
);
}
- // Ensure the number of URLs matches what we expect from the part size
final expectedCount = (encFileLength / partSize).ceil();
if (partsLength != expectedCount) {
_logger.severe(
@@ -296,7 +286,6 @@ class MultiPartUploader {
}
var completedBytes = (i * partSize).clamp(0, encFileLength).toInt();
onSendProgress?.call(completedBytes, encFileLength);
- // Start parts upload
int count = 0;
while (i < partsLength) {
count++;
@@ -317,7 +306,6 @@ class MultiPartUploader {
Headers.contentTypeHeader: "application/octet-stream",
};
- // Add MD5 header if available for this part
if (partMd5s != null && i < partMd5s.length) {
headers[useUploadProxy ? 'CONTENT-MD5' : 'Content-MD5'] = partMd5s[i];
} else if (kDebugMode) {
diff --git a/mobile/apps/photos/lib/module/upload/upload_data.dart b/mobile/apps/photos/lib/module/upload/upload_data.dart
index 621376a536..432e3ba5aa 100644
--- a/mobile/apps/photos/lib/module/upload/upload_data.dart
+++ b/mobile/apps/photos/lib/module/upload/upload_data.dart
@@ -32,7 +32,6 @@ import "package:photos/utils/image_util.dart";
final _logger = Logger("UploadData");
-/// Builds the source, thumbnail, hashes, and embedded metadata for an upload.
Future<MediaUploadData> getUploadDataFromEnteFile(EnteFile file) async {
if (file.isSharedMediaToAppSandbox) {
return await _getMediaUploadDataFromAppCache(file);
@@ -41,7 +40,6 @@ Future<MediaUploadData> getUploadDataFromEnteFile(EnteFile file) async {
}
}
-/// Computes the content hash used to decide whether a local file changed.
Future<String> getFileContentIdentity(EnteFile file) async {
if (file.isSharedMediaToAppSandbox) {
final sourceFile = File(getSharedMediaFilePath(file));
@@ -94,7 +92,6 @@ Future<MediaUploadData> _getMediaUploadDataFromAssetFile(EnteFile file) async {
cameraModel = extractPrintableExifValue(exifData['Image Model']);
}
}
- // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
await _decorateEnteFileData(file, asset, sourceFile, exifData);
fileHash = CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
@@ -221,7 +218,6 @@ Future<Uint8List?> _getThumbnailForUpload(
quality: thumbnailQuality,
);
if (thumbnailData == null) {
- // allow videos to be uploaded without thumbnails
if (asset.type == AssetType.video) {
return null;
}
@@ -238,7 +234,6 @@ Future<Uint8List?> _getThumbnailForUpload(
final String errMessage =
"thumbErr for ${file.fileType}, ${extension(file.displayName)} ${file.tag}";
_logger.warning(errMessage, e);
- // allow videos to be uploaded without thumbnails
if (asset.type == AssetType.video) {
return null;
}
@@ -279,7 +274,7 @@ Future<void> _decorateEnteFileData(
File sourceFile,
Map<String, IfdTag>? exifData,
) async {
- // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
+ // Fetch missing Android Q+ location data lazily during upload.
if (!file.hasLocation) {
final latLong = await asset.latlngAsync();
if (latLong != null) {
diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dart
index 451b56573b..ea804e2c2f 100644
--- a/mobile/apps/photos/lib/services/collections_service.dart
+++ b/mobile/apps/photos/lib/services/collections_service.dart
@@ -85,15 +85,12 @@ class CollectionsService {
final Map<String, EnteFile> _coverCache = <String, EnteFile>{};
final Map<int, int> _countCache = <int, int>{};
- //Used for links-in-app
final _cachedPublicAlbumToken = <int, String>{};
final _cachedPublicAlbumJWT = <int, String>{};
final _cachedPublicCollectionID = <int>[];
final _cachedPublicAlbumKey = <int, String>{};
final _cachedPublicCollectionKeys = <int, Uint8List>{};
- // In-memory list of recently used collection IDs for add/move actions
- // Most recently used is at the front
static const int _maxRecentlyUsedCollections = 3;
final _recentlyUsedCollectionIDs = <int>[];
@@ -139,8 +136,6 @@ class CollectionsService {
FilesDB get filesDB => _filesDB;
- // sync method fetches just sync the collections, not the individual files
- // within the collection.
Future<void> sync() async {
_logger.info("Syncing collections");
final EnteWatch watch = EnteWatch("syncCollection")..start();
@@ -149,7 +144,6 @@ class CollectionsService {
_logger.info("[COLLECTIONS] Starting sync");
- // Might not have synced the collection fully
final fetchedCollections = await _fetchCollections(
lastCollectionUpdationTime,
);
@@ -174,7 +168,6 @@ class CollectionsService {
shouldFireDeleteEvent = true;
}
}
- // remove reference for incoming collections when unshared/deleted
if (collection.isDeleted && ownerID != collection.owner.id) {
await _db.deleteCollection(collection.id);
} else {
@@ -264,10 +257,6 @@ class CollectionsService {
return true;
}
- /// Returns true if the file exists in any shared collection.
- ///
- /// A collection is considered "shared" if it has sharees, has a public link,
- /// or is owned by someone else (incoming share).
Future<bool> isFileInSharedCollection(int uploadedFileID) async {
final Set<int> collectionIDs = await _filesDB.getAllCollectionIDsOfFile(
uploadedFileID,
@@ -299,10 +288,6 @@ class CollectionsService {
return false;
}
- /// Returns the shared collections containing [uploadedFileID].
- ///
- /// A collection is considered shared if it has sharees, has a public link,
- /// or is owned by someone else (incoming share).
Future<List<Collection>> getSharedCollectionsForFile(
int uploadedFileID, {
bool includeHidden = false,
@@ -329,10 +314,6 @@ class CollectionsService {
return sharedCollections;
}
- /// Returns IDs of shared collections containing [uploadedFileID].
- ///
- /// Use this to scope social content on the view path without constructing a
- /// list of collection objects.
Future<List<int>> getSharedCollectionIDsForFile(
int uploadedFileID, {
bool includeHidden = false,
@@ -542,7 +523,6 @@ class CollectionsService {
return _prefs.setInt(key, time);
}
- // getActiveCollections returns list of collections which are not deleted yet
List<Collection> getActiveCollections() {
return _collectionIDToCollections.values
.toList()
@@ -550,7 +530,6 @@ class CollectionsService {
.toList();
}
- // getActiveCollections returns list of collections which are not deleted yet
Set<int> nonHiddenOwnedCollections() {
final int ownerID = _config.getUserID()!;
return _collectionIDToCollections.values
@@ -565,8 +544,6 @@ class CollectionsService {
.toSet();
}
- // returns collections after removing deleted,uncategorized, and hidden
- // collections
List<Collection> getCollectionsForUI({
bool includedShared = false,
bool includeCollab = false,
@@ -602,8 +579,6 @@ class CollectionsService {
.toList();
}
- /// Records a collection as recently used for add/move actions.
- /// Most recently used collection is moved to front.
void recordCollectionUsage(int collectionID) {
_recentlyUsedCollectionIDs.remove(collectionID);
_recentlyUsedCollectionIDs.insert(0, collectionID);
@@ -612,8 +587,6 @@ class CollectionsService {
}
}
- /// Returns a list of recently used collections for add/move actions.
- /// Filters out collections that no longer exist or are hidden.
List<Collection> getRecentlyUsedCollections() {
final List<Collection> result = [];
for (final id in _recentlyUsedCollectionIDs) {
@@ -668,9 +641,7 @@ class CollectionsService {
final comparator = await _albumPreferenceComparator();
- // Sort incoming collections, then separate pinned from rest
incoming.sort((first, second) {
- // Sharee-pinned collections should come first
final firstPinned = first.hasShareePinned();
final secondPinned = second.hasShareePinned();
if (firstPinned && !secondPinned) return -1;
@@ -728,7 +699,6 @@ class CollectionsService {
continue;
}
if (collection.type == CollectionType.favorites) {
- // Hide fav collection if it's empty
if (hasFavorites) {
favorites.add(collection);
}
@@ -759,7 +729,6 @@ class CollectionsService {
continue;
}
if (collection.type == CollectionType.favorites) {
- // Hide fav collection if it's empty
if (hasFavorites) {
favorites.add(collection);
}
@@ -1157,7 +1126,6 @@ class CollectionsService {
final String customDomain = flagService.customDomain;
final bool applyCustomDomain = isOwner && customDomain.isNotEmpty;
- // Replace with custom domain if configured for the owner
if (applyCustomDomain) {
publicUrl = publicUrl.replace(
host: customDomain,
@@ -1166,12 +1134,10 @@ class CollectionsService {
);
}
- // Get the collection key for the URL fragment
final String collectionKey = Base58Encode(
CollectionsService.instance.getCollectionKey(c.id),
);
- // Build the final URL
String finalUrl = publicUrl.toString();
// Handle IDN domains - if the host was percent-encoded by Uri.replace,
@@ -1188,7 +1154,6 @@ class CollectionsService {
final PublicURL url = c.publicURLs.firstOrNull!;
Uri publicUrl = Uri.parse(url.url);
- // Replace with embed URL if configured
final String embedUrl = flagService.embedUrl;
if (embedUrl.isNotEmpty) {
final Uri embedUri = Uri.parse(embedUrl);
@@ -1201,12 +1166,10 @@ class CollectionsService {
);
}
- // Get the collection key for the URL fragment
final String collectionKey = Base58Encode(
CollectionsService.instance.getCollectionKey(c.id),
);
- // Build the final URL
String finalUrl = publicUrl.toString();
// Handle IDN domains - if the host was percent-encoded by Uri.replace,
@@ -1234,7 +1197,6 @@ class CollectionsService {
final encryptedKey = CryptoUtil.base642bin(collection.encryptedKey);
Uint8List? collectionKey;
if (collection.owner.id == _config.getUserID()) {
- // If the collection is owned by the user, decrypt with the master key
if (_config.getKey() == null) {
// Possible during AppStore account migration, where SecureStorage
// would become inaccessible to the new Developer Account
@@ -1246,7 +1208,6 @@ class CollectionsService {
CryptoUtil.base642bin(collection.keyDecryptionNonce!),
);
} else {
- // If owned by a different user, decrypt with the public key
collectionKey = CryptoUtil.openSealSync(
encryptedKey,
CryptoUtil.base642bin(_config.getKeyAttributes()!.publicKey),
@@ -1308,9 +1269,6 @@ class CollectionsService {
if (collection.owner.id != ownerID) {
throw AssertionError("cannot modify albums not owned by you");
}
- // read the existing magic metadata and apply new updates to existing data
- // current update is simple replace. This will be enhanced in the future,
- // as required.
final Map<String, dynamic> jsonToUpdate = jsonDecode(
collection.mMdEncodedJson ?? '{}',
);
@@ -1336,13 +1294,11 @@ class CollectionsService {
),
);
await collectionsGateway.updateMagicMetadata(params);
- // update the local information so that it's reflected on UI
collection.mMdEncodedJson = jsonEncode(jsonToUpdate);
collection.magicMetadata = CollectionMagicMetadata.fromJson(jsonToUpdate);
collection.mMdVersion = currentVersion + 1;
_collectionIDToCollections[collection.id] = collection;
- // trigger sync to fetch the latest collection state from server
sync().ignore();
} on DioException catch (e) {
if (e.response != null && e.response?.statusCode == 409) {
@@ -1365,9 +1321,6 @@ class CollectionsService {
if (collection.owner.id != ownerID) {
throw AssertionError("cannot modify albums not owned by you");
}
- // read the existing magic metadata and apply new updates to existing data
- // current update is simple replace. This will be enhanced in the future,
- // as required.
final Map<String, dynamic> jsonToUpdate = jsonDecode(
collection.mMdPubEncodedJson ?? '{}',
);
@@ -1393,14 +1346,12 @@ class CollectionsService {
),
);
await collectionsGateway.updatePublicMagicMetadata(params);
- // update the local information so that it's reflected on UI
collection.mMdPubEncodedJson = jsonEncode(jsonToUpdate);
collection.pubMagicMetadata = CollectionPubMagicMetadata.fromJson(
jsonToUpdate,
);
collection.mMbPubVersion = currentVersion + 1;
_cacheLocalPathAndCollection(collection);
- // trigger sync to fetch the latest collection state from server
sync().ignore();
} on DioException catch (e) {
if (e.response != null && e.response?.statusCode == 409) {
@@ -1426,9 +1377,6 @@ class CollectionsService {
"by you",
);
}
- // read the existing magic metadata and apply new updates to existing data
- // current update is simple replace. This will be enhanced in the future,
- // as required.
final Map<String, dynamic> jsonToUpdate = jsonDecode(
collection.sharedMmdJson ?? '{}',
);
@@ -1454,14 +1402,12 @@ class CollectionsService {
),
);
await collectionsGateway.updateShareeMagicMetadata(params);
- // update the local information so that it's reflected on UI
collection.sharedMmdJson = jsonEncode(jsonToUpdate);
collection.sharedMagicMetadata = ShareeMagicMetadata.fromJson(
jsonToUpdate,
);
collection.sharedMmdVersion = currentVersion + 1;
_cacheLocalPathAndCollection(collection);
- // trigger sync to fetch the latest collection state from server
sync().ignore();
} on DioException catch (e) {
if (e.response != null && e.response?.statusCode == 409) {
@@ -1512,7 +1458,6 @@ class CollectionsService {
collectionID: collection.id,
props: prop,
);
- // remove existing url information
collection.publicURLs.clear();
collection.publicURLs.add(publicUrl);
await _db.insert(List.from([collection]));
@@ -1844,7 +1789,6 @@ class CollectionsService {
};
}
- /// Is a public link opened in the app via deeplink
bool isSharedPublicLink(int collectionID) {
return _cachedPublicCollectionID.contains(collectionID);
}
@@ -2147,10 +2091,7 @@ class CollectionsService {
}
}
- // This method is used to add files to a collection without firing any events.
- // Unlike `addToCollection`, this method does not update the `FilesDB` or modify
- // the `EnteFile` objects passed to it. This is only used during dedupe process
- // for adding files to a collection without firing any events.
+ // Dedupe uses this without updating FilesDB or mutating the EnteFile objects.
Future<void> addSilentlyToCollection(
int collectionID,
List<EnteFile> files,
@@ -2158,7 +2099,6 @@ class CollectionsService {
if (files.isEmpty) {
return;
}
- // as any non uploaded file
final pendingUpload = files.any(
(element) => element.uploadedFileID == null,
);
@@ -2316,7 +2256,6 @@ class CollectionsService {
if (srcCollection == null) {
throw ArgumentError('Source collection not found');
}
- // verify that all fileIds belong to srcCollection and isn't owned by current user
for (final f in files) {
if (f.collectionID != srcCollectionID ||
f.ownerID == _config.getUserID()) {
@@ -2335,7 +2274,6 @@ class CollectionsService {
}) async {
final int uploadedFileID = existingUploadedFile.uploadedFileID!;
- // encrypt the fileKey with destination collection's key
final fileKey = getFileKey(existingUploadedFile);
final encryptedKeyData = CryptoUtil.encryptSync(
fileKey,
@@ -2426,7 +2364,6 @@ class CollectionsService {
if (localIDs.isNotEmpty) {
await _filesDB.deleteUnSyncedLocalFiles(localIDs);
}
- // Force reload home gallery to pull in the restored files
Bus.instance.fire(ForceReloadHomeGalleryEvent("restoredFromTrash"));
} catch (e, s) {
_logger.severe("failed to restore files", e, s);
@@ -2479,7 +2416,6 @@ class CollectionsService {
);
}
- // remove files from old collection
await _filesDB.removeFromCollection(
fromCollectionID,
files.map((e) => e.uploadedFileID!).toList(),
@@ -2492,7 +2428,6 @@ class CollectionsService {
type: EventType.deletedFromRemote,
),
);
- // insert new files in the toCollection which are not part of the toCollection
final existingUploadedIDs = await FilesDB.instance.getUploadedFileIDs(
toCollectionID,
);
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart
index 4c0346555a..59d33ef087 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart
@@ -85,11 +85,8 @@ class FaceClusteringService extends SuperIsolate {
@override
bool get shouldAutomaticDispose => true;
- // singleton pattern
FaceClusteringService._privateConstructor();
- /// Use this instance to access the FaceClustering service.
- /// e.g. `FaceLinearClustering.instance.predict(dataset)`
static final instance = FaceClusteringService._privateConstructor();
factory FaceClusteringService() => instance;
@@ -100,9 +97,6 @@ class FaceClusteringService extends SuperIsolate {
}
}
- /// Runs the clustering algorithm [runLinearClustering] on the given [input], in an isolate.
- ///
- /// Returns the clustering result, which is a list of clusters, where each cluster is a list of indices of the dataset.
Future<ClusteringResult?> predictLinearIsolate(
Set<FaceDbInfoForClustering> input, {
Map<int, int>? fileIDToCreationTime,
@@ -133,13 +127,10 @@ class FaceClusteringService extends SuperIsolate {
isRunning = true;
try {
- // Clustering inside the isolate
_logger.info(
"Start clustering on ${input.length} embeddings inside computer isolate",
);
final stopwatchClustering = Stopwatch()..start();
- // final Map<String, int> faceIdToCluster =
- // await _runLinearClusteringInComputer(input);
final ClusteringResult faceIdToCluster =
await runInIsolate(IsolateOperation.linearIncrementalClustering, {
'input': input,
@@ -151,7 +142,6 @@ class FaceClusteringService extends SuperIsolate {
'offset': offset,
'oldClusterSummaries': oldClusterSummaries,
});
- // return _runLinearClusteringInComputer(input);
_logger.info(
'predictLinear Clustering executed in ${stopwatchClustering.elapsed.inSeconds} seconds',
);
@@ -213,7 +203,6 @@ class FaceClusteringService extends SuperIsolate {
}
}
- /// Runs the clustering algorithm [runLinearClustering] on the given [input], in computer, without any dynamic thresholding
Future<ClusteringResult> _predictLinearComputer(
Map<String, Uint8List> input, {
Map<int, int>? fileIDToCreationTime,
@@ -229,7 +218,6 @@ class FaceClusteringService extends SuperIsolate {
return ClusteringResult.empty();
}
- // Clustering inside the isolate
_logger.info(
"Start Linear clustering on ${input.length} embeddings inside computer isolate",
);
@@ -277,9 +265,7 @@ class FaceClusteringService extends SuperIsolate {
}
}
- /// Runs the clustering algorithm [_runCompleteClustering] on the given [input], in computer.
- ///
- /// WARNING: Only use on small datasets, as it is not optimized for large datasets.
+ // Only use on small datasets; this is not optimized for large datasets.
Future<ClusteringResult> _predictCompleteComputer(
Map<String, Uint8List> input, {
Map<int, int>? fileIDToCreationTime,
@@ -296,7 +282,6 @@ class FaceClusteringService extends SuperIsolate {
return ClusteringResult.empty();
}
- // Clustering inside the isolate
_logger.info(
"Start Complete clustering on ${input.length} embeddings inside computer isolate",
);
@@ -331,7 +316,6 @@ class FaceClusteringService extends SuperIsolate {
final _logger = Logger("FaceLinearClustering");
ClusteringResult runLinearClustering(Map args) {
- // final input = args['input'] as Map<String, (int?, Uint8List)>;
final input = args['input'] as Set<FaceDbInfoForClustering>;
final fileIDToCreationTime = args['fileIDToCreationTime'] as Map<int, int>?;
final distanceThreshold = args['distanceThreshold'] as double;
@@ -344,7 +328,6 @@ ClusteringResult runLinearClustering(Map args) {
_logger.info("Copied to isolate ${input.length} faces");
- // Organize everything into a list of FaceInfo objects
final List<FaceInfo> faceInfos = [];
for (final face in input) {
faceInfos.add(
@@ -369,7 +352,6 @@ ClusteringResult runLinearClustering(Map args) {
);
}
- // Assert that the embeddings are normalized
for (final faceInfo in faceInfos) {
if (faceInfo.vEmbedding != null) {
final norm = faceInfo.vEmbedding!.norm();
@@ -381,7 +363,6 @@ ClusteringResult runLinearClustering(Map args) {
_sortFaceInfosOnCreationTime(faceInfos);
}
- // Sort the faceInfos such that the ones with null clusterId are at the end
final List<FaceInfo> facesWithClusterID = <FaceInfo>[];
final List<FaceInfo> facesWithoutClusterID = <FaceInfo>[];
for (final FaceInfo faceInfo in faceInfos) {
@@ -403,21 +384,17 @@ ClusteringResult runLinearClustering(Map args) {
final int totalFaces = sortedFaceInfos.length;
int dynamicThresholdCount = 0;
- // Start actual clustering
_logger.info(
"[ClusterIsolate] ${DateTime.now()} Processing $totalFaces faces ($newToClusterCount new, $alreadyClusteredCount already done) in total in this round ${offset != null ? "on top of ${offset + facesWithClusterID.length} earlier processed faces" : ""}",
);
String clusterID = newClusterID();
if (facesWithClusterID.isEmpty) {
- // assign a clusterID to the first face
sortedFaceInfos[0].clusterId = clusterID;
clusterID = newClusterID();
}
final stopwatchClustering = Stopwatch()..start();
for (int i = 1; i < totalFaces; i++) {
- // Incremental clustering, so we can skip faces that already have a clusterId
if (sortedFaceInfos[i].clusterId != null) {
- // clusterID = max(clusterID, sortedFaceInfos[i].clusterId!);
continue;
}
@@ -437,7 +414,7 @@ ClusteringResult runLinearClustering(Map args) {
if (i % 250 == 0) {
_logger.info("Processed ${offset != null ? i + offset : i} faces");
}
- // WARNING: The loop below is now O(n^2) so be very careful with anything you put in there!
+ // This loop makes clustering O(nΒ²); keep its body cheap.
for (int j = i - 1; j >= 0; j--) {
final double distance =
1 -
@@ -461,7 +438,6 @@ ClusteringResult runLinearClustering(Map args) {
if (closestDistance < thresholdValue) {
if (sortedFaceInfos[closestIdx].clusterId == null) {
- // Ideally this should never happen, but just in case log it
_logger.severe(
"Found new cluster $clusterID, but closest face has no clusterId",
);
@@ -475,14 +451,12 @@ ClusteringResult runLinearClustering(Map args) {
}
}
- // Finally, assign the new clusterId to the faces
final Map<String, String> newFaceIdToCluster = {};
final newClusteredFaceInfos = sortedFaceInfos.sublist(alreadyClusteredCount);
for (final faceInfo in newClusteredFaceInfos) {
newFaceIdToCluster[faceInfo.faceID] = faceInfo.clusterId!;
}
- // Create a map of clusterId to faceIds
final Map<String, List<String>> clusterIdToFaceIds = {};
for (final entry in newFaceIdToCluster.entries) {
final clusterID = entry.value;
@@ -503,15 +477,11 @@ ClusteringResult runLinearClustering(Map args) {
);
}
- // Now calculate the mean of the embeddings for each cluster and update the cluster summaries
final newClusterSummaries = _updateClusterSummaries(
newFaceInfos: newClusteredFaceInfos,
oldSummary: oldClusterSummaries,
);
- // analyze the results
- // FaceClusteringService._analyzeClusterResults(sortedFaceInfos);
-
return ClusteringResult(
newFaceIdToCluster: newFaceIdToCluster,
newClusterSummaries: newClusterSummaries,
@@ -531,7 +501,6 @@ ClusteringResult _runCompleteClustering(Map args) {
"[CompleteClustering] ${DateTime.now()} Copied to isolate ${input.length} faces for clustering",
);
- // Organize everything into a list of FaceInfo objects
final List<FaceInfo> faceInfos = [];
for (final entry in input.entries) {
faceInfos.add(
@@ -556,14 +525,12 @@ ClusteringResult _runCompleteClustering(Map args) {
}
final int totalFaces = faceInfos.length;
- // Start actual clustering
log(
"[CompleteClustering] ${DateTime.now()} Processing $totalFaces faces in one single round of complete clustering",
);
String clusterID = newClusterID();
- // Start actual clustering
final Map<String, String> newFaceIdToCluster = {};
final stopwatchClustering = Stopwatch()..start();
for (int i = 0; i < totalFaces; i++) {
@@ -595,7 +562,6 @@ ClusteringResult _runCompleteClustering(Map args) {
}
}
- // Now calculate the mean of the embeddings for each cluster
final Map<String, List<FaceInfo>> clusterIdToFaceInfos = {};
for (final faceInfo in faceInfos) {
if (clusterIdToFaceInfos.containsKey(faceInfo.clusterId)) {
@@ -618,7 +584,6 @@ ClusteringResult _runCompleteClustering(Map args) {
);
}
- // Now merge the clusters that are close to each other, based on mean embedding
final List<(String, String)> mergedClustersList = [];
final List<String> clusterIds = clusterIdToMeanEmbeddingAndWeight.keys
.toList();
@@ -669,7 +634,6 @@ ClusteringResult _runCompleteClustering(Map args) {
' [CompleteClustering] ${DateTime.now()} ${mergedClustersList.length} clusters merged',
);
- // Now assign the new clusterId to the faces
for (final faceInfo in faceInfos) {
for (final mergedClusters in mergedClustersList) {
if (faceInfo.clusterId == mergedClusters.$2) {
@@ -678,7 +642,6 @@ ClusteringResult _runCompleteClustering(Map args) {
}
}
- // Finally, assign the new clusterId to the faces
for (final faceInfo in faceInfos) {
newFaceIdToCluster[faceInfo.faceID] = faceInfo.clusterId!;
}
@@ -693,7 +656,6 @@ ClusteringResult _runCompleteClustering(Map args) {
}
}
- // Now calculate the mean of the embeddings for each cluster and update the cluster summaries
final newClusterSummaries = _updateClusterSummaries(
newFaceInfos: faceInfos,
oldSummary: oldClusterSummaries,
@@ -711,7 +673,6 @@ ClusteringResult _runCompleteClustering(Map args) {
);
}
-/// Sort the faceInfos based on fileCreationTime, in descending order, so newest faces are first
void _sortFaceInfosOnCreationTime(List<FaceInfo> faceInfos) {
faceInfos.sort((b, a) {
if (a.fileCreationTime == null && b.fileCreationTime == null) {
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_detection/detection.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_detection/detection.dart
index ff1b6ac679..9de9cbdb51 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_detection/detection.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_detection/detection.dart
@@ -31,16 +31,6 @@ abstract class Detection {
String toString();
}
-/// This class represents a face detection with relative coordinates in the range [0, 1].
-/// The coordinates are relative to the image size. The pattern for the coordinates is always [x, y], where x is the horizontal coordinate and y is the vertical coordinate.
-///
-/// The [score] attribute is a double representing the confidence of the face detection.
-///
-/// The [box] attribute is a list of 4 doubles, representing the coordinates of the bounding box of the face detection.
-/// The four values of the box in order are: [xMinBox, yMinBox, xMaxBox, yMaxBox].
-///
-/// The [allKeypoints] attribute is a list of 6 lists of 2 doubles, representing the coordinates of the keypoints of the face detection.
-/// The six lists of two values in order are: [leftEye, rightEye, nose, mouth, leftEar, rightEar]. Again, all in [x, y] order.
class FaceDetectionRelative extends Detection {
final List<double> box;
final List<List<double>> allKeypoints;
@@ -82,21 +72,17 @@ class FaceDetectionRelative extends Detection {
Dimensions originalSize,
Dimensions newSize,
) {
- // Return if both are the same size, meaning no scaling was done on both width and height
if (originalSize == newSize) {
return;
}
- // Calculate the scaling
final double scaleX = originalSize.width / newSize.width;
final double scaleY = originalSize.height / newSize.height;
const double translateX = 0;
const double translateY = 0;
- // Transform Box
_transformBox(box, scaleX, scaleY, translateX, translateY);
- // Transform All Keypoints
for (int i = 0; i < allKeypoints.length; i++) {
allKeypoints[i] = _transformPoint(
allKeypoints[i],
@@ -148,14 +134,10 @@ class FaceDetectionRelative extends Detection {
boxCopy[1] *= imageHeight;
boxCopy[2] *= imageWidth;
boxCopy[3] *= imageHeight;
- // final intbox = boxCopy.map((e) => e.toInt()).toList();
-
for (List<double> keypoint in allKeypointsCopy) {
keypoint[0] *= imageWidth;
keypoint[1] *= imageHeight;
}
- // final intKeypoints =
- // allKeypointsCopy.map((e) => e.map((e) => e.toInt()).toList()).toList();
return FaceDetectionAbsolute(
score: scoreCopy,
box: boxCopy,
@@ -164,7 +146,6 @@ class FaceDetectionRelative extends Detection {
}
String toFaceID({required int fileID}) {
- // Assert that the values are within the expected range
assert(
(xMinBox >= 0 && xMinBox <= 1) &&
(yMinBox >= 0 && yMinBox <= 1) &&
@@ -173,7 +154,6 @@ class FaceDetectionRelative extends Detection {
"Bounding box values must be in the range [0, 1]",
);
- // Extract bounding box values
final String xMin = xMinBox
.clamp(0.0, 0.999999)
.toStringAsFixed(5)
@@ -191,12 +171,10 @@ class FaceDetectionRelative extends Detection {
.toStringAsFixed(5)
.substring(2);
- // Convert the bounding box values to string and concatenate
final String rawID = "${xMin}_${yMin}_${xMax}_$yMax";
final faceID = fileID.toString() + '_' + rawID.toString();
- // Return the hexadecimal representation of the hash
return faceID;
}
@@ -220,24 +198,12 @@ class FaceDetectionRelative extends Detection {
}
@override
- /// The width of the bounding box of the face detection, in relative range [0, 1].
double get width => xMaxBox - xMinBox;
@override
- /// The height of the bounding box of the face detection, in relative range [0, 1].
double get height => yMaxBox - yMinBox;
}
-/// This class represents a face detection with absolute coordinates in pixels, in the range [0, imageWidth] for the horizontal coordinates and [0, imageHeight] for the vertical coordinates.
-/// The pattern for the coordinates is always [x, y], where x is the horizontal coordinate and y is the vertical coordinate.
-///
-/// The [score] attribute is a double representing the confidence of the face detection.
-///
-/// The [box] attribute is a list of 4 integers, representing the coordinates of the bounding box of the face detection.
-/// The four values of the box in order are: [xMinBox, yMinBox, xMaxBox, yMaxBox].
-///
-/// The [allKeypoints] attribute is a list of 6 lists of 2 integers, representing the coordinates of the keypoints of the face detection.
-/// The six lists of two values in order are: [leftEye, rightEye, nose, mouth, leftEar, rightEar]. Again, all in [x, y] order.
class FaceDetectionAbsolute extends Detection {
final List<double> box;
final List<List<double>> allKeypoints;
@@ -265,10 +231,8 @@ class FaceDetectionAbsolute extends Detection {
}
@override
- /// The width of the bounding box of the face detection, in number of pixels, range [0, imageWidth].
double get width => xMaxBox - xMinBox;
@override
- /// The height of the bounding box of the face detection, in number of pixels, range [0, imageHeight].
double get height => yMaxBox - yMinBox;
FaceDirection getFaceDirection() {
@@ -292,10 +256,8 @@ class FaceDetectionAbsolute extends 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/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart
index 5ab4237897..94912f7f5e 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart
@@ -1,18 +1,13 @@
-/// Blur detection threshold
const kLaplacianHardThreshold = 10;
const kLaplacianSoftThreshold = 50;
const kLaplacianVerySoftThreshold = 200;
-/// Default blur value
const kLapacianDefault = 10000.0;
-/// The minimum score for a face to be detected, regardless of quality. Use [kMinimumQualityFaceScore] for high quality faces.
const kMinFaceDetectionScore = 0.5;
-/// The minimum score for a face to be shown as detected in the UI
const kMinimumFaceShowScore = 0.75;
-/// The minimum score for a face to be considered a high quality face for clustering and person detection
const kMinimumQualityFaceScore = 0.80;
const kMediumQualityFaceScore = 0.85;
const kHighQualityFaceScore = 0.90;
@@ -28,8 +23,6 @@ bool isBadFaceForClustering({
faceScore < kMediumQualityFaceScore) ||
isSideways;
-/// The minimum cluster size for displaying a cluster in the UI by default
const kMinimumClusterSizeSearchResult = 10;
-/// The minimum cluster size for displaying a cluster when the user wants to see all faces
const kMinimumClusterSizeAllFaces = 1;
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
index 73d59d707f..4a399dfa1a 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
@@ -49,8 +49,7 @@ class ClusterFeedbackService<T> {
ClusterFeedbackService._privateConstructor();
late final mlDataDB = MLDataDB.instance;
- // Person entities and person suggestions require an Ente account; keep all
- // suggestion centroid mapping/vector access pinned to the Ente account DB.
+ // Person suggestions belong to the Ente account, not the local gallery.
MLDataDB get _mlDataDBForCentroidVectorDb => MLDataDB.instance;
ClusterCentroidVectorDB get _clusterCentroidVectorDB =>
ClusterCentroidVectorDB.instance;
@@ -76,7 +75,6 @@ class ClusterFeedbackService<T> {
return results[0].union(results[1]);
}
- /// Returns a list of cluster suggestions for a person.
Future<List<ClusterSuggestion>> getSuggestionForPerson(
PersonEntity person, {
bool extremeFilesFirst = true,
@@ -96,7 +94,6 @@ class ClusterFeedbackService<T> {
);
try {
- // Get the suggestions for the person using centroids and median
final startTime = DateTime.now();
final List<(String, double, bool)> foundSuggestions =
await _getSuggestions(person);
@@ -105,7 +102,6 @@ class ClusterFeedbackService<T> {
'getSuggestionForPerson `_getSuggestions`: Found ${foundSuggestions.length} suggestions in ${findSuggestionsTime.difference(startTime).inMilliseconds} ms',
);
- // Get the files for the suggestions
final suggestionClusterIDs = foundSuggestions.map((e) => e.$1).toSet();
final Map<int, Set<String>> fileIdToClusterID = await mlDataDB
.getFileIdToClusterIDSetForCluster(suggestionClusterIDs);
@@ -170,13 +166,11 @@ class ClusterFeedbackService<T> {
) async {
try {
Future<void>? manualAssignmentUpdate;
- // Get file IDs being removed
final fileIDsToRemove = files
.map((file) => file.uploadedFileID)
.whereType<int>()
.toSet();
- // Check for manually assigned files to remove
final manualFileIDs = p.data.manuallyAssigned.toSet();
final manualToRemove = manualFileIDs.intersection(fileIDsToRemove);
if (manualToRemove.isNotEmpty) {
@@ -192,7 +186,6 @@ class ClusterFeedbackService<T> {
);
}
- // Get the relevant faces to be removed
final faceIDs = await mlDataDB
.getFaceIDsForPerson(p.remoteID)
.then((iterable) => iterable.toList());
@@ -201,7 +194,6 @@ class ClusterFeedbackService<T> {
return files.any((file) => file.uploadedFileID == fileID);
});
- // If no faces to remove (might have been only manually assigned files)
if (faceIDs.isEmpty) {
if (manualAssignmentUpdate != null) {
await manualAssignmentUpdate;
@@ -226,7 +218,6 @@ class ClusterFeedbackService<T> {
final fileIDToCreationTime = await FilesDB.instance
.getFileIDToCreationTime();
- // Re-cluster within the deleted faces
final clusterResult = await FaceClusteringService.instance
.predictWithinClusterComputer(
embeddings,
@@ -239,18 +230,17 @@ class ClusterFeedbackService<T> {
}
final newFaceIdToClusterID = clusterResult.newFaceIdToCluster;
- // Update the deleted faces
await mlDataDB.forceUpdateClusterIds(newFaceIdToClusterID);
await mlDataDB.clusterSummaryUpdate(clusterResult.newClusterSummaries);
- // Make sure the deleted faces don't get suggested in the future
+ // Record rejection so removed faces are not suggested again.
final notClusterIdToPersonId = <String, String>{};
for (final clusterId in newFaceIdToClusterID.values.toSet()) {
notClusterIdToPersonId[clusterId] = p.remoteID;
}
await mlDataDB.bulkCaptureNotPersonFeedback(notClusterIdToPersonId);
- // Update remote so new sync does not undo this change
+ // Persist remotely so a later sync cannot undo the removal.
await PersonService.instance.removeFacesFromPerson(
person: p,
faceIDs: faceIDs.toSet(),
@@ -277,11 +267,11 @@ class ClusterFeedbackService<T> {
final newFaceIdToClusterID = {faceID: updatedClusterID};
await mlDataDB.forceUpdateClusterIds(newFaceIdToClusterID);
- // Make sure the deleted faces don't get suggested in the future
+ // Record rejection so the removed face is not suggested again.
final notClusterIdToPersonId = {updatedClusterID: person.remoteID};
await mlDataDB.bulkCaptureNotPersonFeedback(notClusterIdToPersonId);
- // Update remote so new sync does not undo this change
+ // Persist remotely so a later sync cannot undo the removal.
await PersonService.instance.removeFacesFromPerson(
person: person,
faceIDs: {faceID},
@@ -307,7 +297,6 @@ class ClusterFeedbackService<T> {
) async {
_logger.info('removeFilesFromCluster called');
try {
- // Get the relevant faces to be removed
final faceIDs = await mlDataDB
.getFaceIDsForCluster(clusterID)
.then((iterable) => iterable.toList());
@@ -327,7 +316,6 @@ class ClusterFeedbackService<T> {
final fileIDToCreationTime = await FilesDB.instance
.getFileIDToCreationTime();
- // Re-cluster within the deleted faces
final clusterResult = await FaceClusteringService.instance
.predictWithinClusterComputer(
embeddings,
@@ -340,7 +328,6 @@ class ClusterFeedbackService<T> {
}
final newFaceIdToClusterID = clusterResult.newFaceIdToCluster;
- // Update the deleted faces
await mlDataDB.forceUpdateClusterIds(newFaceIdToClusterID);
await mlDataDB.clusterSummaryUpdate(clusterResult.newClusterSummaries);
@@ -1273,7 +1260,6 @@ class ClusterFeedbackService<T> {
return false;
}
- // log suggestions
_logger.info(
'suggestions for ${kDebugMode ? p.data.name : "private"} for cluster ID ${p.remoteID} are suggestions $suggestions}',
);
@@ -1393,7 +1379,6 @@ class ClusterFeedbackService<T> {
'[CheckMixedClusters] Broke up cluster $clusterID into $amountOfNewClusters clusters \n ${newClusterIdToCount.toString()}',
);
- // Now find the sizes of the biggest and second biggest cluster
final String biggestClusterID = newClusterIdToCount.keys.reduce((a, b) {
return newClusterIdToCount[a]! > newClusterIdToCount[b]! ? a : b;
});
@@ -1532,10 +1517,7 @@ class ClusterFeedbackService<T> {
return false;
}
- /// Returns a list of suggestions. For each suggestion we return a record consisting of the following elements:
- /// 1. clusterID: the ID of the cluster
- /// 2. distance: the distance between the person's cluster and the suggestion
- /// 3. usedMean: whether the suggestion was found using the mean (true) or the median (false)
+ // Returns (cluster ID, distance, used mean rather than median).
Future<List<(String, double, bool)>> _getSuggestions(
PersonEntity p, {
int sampleSize = 50,
@@ -1545,7 +1527,6 @@ class ClusterFeedbackService<T> {
double goodMeanDistance = 0.45,
}) async {
final w = (kDebugMode ? EnteWatch('getSuggestions') : null)?..start();
- // Get all the cluster data
final allClusterIdsToCountMap = await mlDataDB.clusterIdToFaceCount();
final ignoredClusters = await mlDataDB.getPersonIgnoredClusters(p.remoteID);
ignoredClusters.addAll(await _getExcludedSuggestionClusterIDs());
@@ -1564,7 +1545,6 @@ class ClusterFeedbackService<T> {
final allClusterIdToFaceIDs = await mlDataDB.getAllClusterIdToFaceIDs();
w?.log('getAllClusterIdToFaceIDs done');
- // First only do a simple check on the big clusters, if the person does not have small clusters yet
final smallestPersonClusterSize = personClusters
.map((clusterID) => allClusterIdsToCountMap[clusterID] ?? 0)
.reduce((value, element) => min(value, element));
@@ -1597,7 +1577,6 @@ class ClusterFeedbackService<T> {
'Calculate suggestions using mean for ${clusterAvgBigClusters.length} clusters of min size $minimumSize',
);
for (final suggestion in suggestionsMeanBigClusters) {
- // Skip suggestions that have a high overlap with the person's files
final suggestionSet = allClusterIdToFaceIDs[suggestion.$1]!
.map((faceID) => getFileIdFromFaceId<int>(faceID))
.toSet();
@@ -1621,7 +1600,6 @@ class ClusterFeedbackService<T> {
}
w?.reset();
- // Find the other cluster candidates based on the median
final clusterAvg = clusterAvgBigClusters;
final moreSuggestionsMean = await _calcSuggestionsMeanWithFallback(
clusterAvg,
@@ -1648,7 +1626,6 @@ class ClusterFeedbackService<T> {
);
w?.logAndReset("Starting median test");
- // Take the embeddings from the person's clusters in one big list and sample from it
final List<Uint8List> personEmbeddingsProto = [];
for (final clusterID in personClusters) {
final Iterable<Uint8List> embeddings = await mlDataDB
@@ -1668,7 +1645,6 @@ class ClusterFeedbackService<T> {
)
.toList(growable: false);
- // Find the actual closest clusters for the person using median
final List<(String, double)> suggestionsMedian = [];
final List<(String, double)> greatSuggestionsMedian = [];
double minMedianDistance = maxMedianDistance;
@@ -1688,7 +1664,6 @@ class ClusterFeedbackService<T> {
)
.toList(growable: false);
- // Calculate distances and find the median
final List<double> distances = [];
for (final otherEmbedding in sampledOtherEmbeddings) {
for (final embedding in sampledEmbeddings) {
@@ -1725,24 +1700,12 @@ class ClusterFeedbackService<T> {
_logger.info(
"Found great suggestion using median: $greatSuggestionsMedian",
);
- // // Return the largest size cluster by using allClusterIdsToCountMap
- // final List<int> greatSuggestionsMedianClusterIds =
- // greatSuggestionsMedian.map((e) => e.$1).toList(growable: false);
- // greatSuggestionsMedianClusterIds.sort(
- // (a, b) =>
- // allClusterIdsToCountMap[b]!.compareTo(allClusterIdsToCountMap[a]!),
- // );
-
- // return [greatSuggestionsMedian.last.$1, ...finalSuggestionsMedian];
}
return finalSuggestionsMedian;
}
- /// Returns a list of suggestions. For each suggestion we return a record consisting of the following elements:
- /// 1. clusterID: the ID of the cluster
- /// 2. distance: the distance between the person's cluster and the suggestion
- /// 3. personClusterID: the ID of the person's cluster
+ // Returns (suggestion cluster ID, distance, person cluster ID).
Future<List<(String, double, String)>> _getFastSuggestions(
PersonEntity person,
String clusterID,
@@ -1774,7 +1737,6 @@ class ClusterFeedbackService<T> {
);
final avgCalcTime = DateTime.now();
- // Returns a list of tuples containing the suggestion ID, distance, and personClusterID, respectively
final List<(String, double, String)> foundSuggestions =
await calcSuggestionsMeanInComputer(
clusterAvg,
@@ -1832,7 +1794,6 @@ class ClusterFeedbackService<T> {
final alreadyUpdatedClustersCnt = serializationEmbeddings.$4;
final smallerClustersCnt = serializationEmbeddings.$5;
- // Assert that all existing clusterAvg are normalized
for (final avg in clusterAvg.values) {
assert((avg.norm() - 1.0).abs() < 1e-5);
}
@@ -1849,7 +1810,6 @@ class ClusterFeedbackService<T> {
return clusterAvg;
}
- // get clusterIDs sorted by count in descending order
final sortedClusterIDs = allClusterIds.toList();
sortedClusterIDs.sort(
(a, b) =>
@@ -1902,7 +1862,6 @@ class ClusterFeedbackService<T> {
embeddings.length,
);
}
- // store the intermediate updates
indexedInCurrentRun++;
if (shouldPersistClusterSummaryUpdates &&
updatesForClusterSummary.length > 100) {
@@ -2103,13 +2062,11 @@ class ClusterFeedbackService<T> {
return embeddings.toList();
}
- // If sampleSize is more than half the list size, shuffle and take first sampleSize elements
if (sampleSize > embeddings.length / 2) {
final List<S> shuffled = List<S>.from(embeddings)..shuffle(random);
return shuffled.take(sampleSize).toList(growable: false);
}
- // Otherwise, use the set-based method for efficiency
final selectedIndices = <int>{};
final sampledEmbeddings = <S>[];
while (sampledEmbeddings.length < sampleSize) {
@@ -2153,14 +2110,12 @@ class ClusterFeedbackService<T> {
if (avg != null) personAverages[person.remoteID] = avg;
}
- // Sort the suggestions based on the distance to the person
for (final suggestion in suggestions) {
if (onlySortBigSuggestions) {
if (suggestion.filesInCluster.length <= 8) {
continue;
}
}
- // get person average
Vector? personAvg = personAverages[suggestion.person.remoteID];
if (personAvg == null) {
personAvg = await _getPersonAvg(suggestion.person.remoteID);
@@ -2215,14 +2170,12 @@ class ClusterFeedbackService<T> {
Future<Vector?> _getPersonAvg(String personID) async {
final w = (kDebugMode ? EnteWatch('_getPersonAvg') : null)?..start();
- // Get the cluster averages for the person's clusters and the suggestions' clusters
final personClusters = await mlDataDB.getPersonClusterIDs(personID);
w?.log('got person clusters');
final Map<String, (Uint8List, int)> personClusterToSummary = await mlDataDB
.getClusterToClusterSummary(personClusters);
w?.log('got cluster summaries');
- // remove personClusters that don't have any summary
for (final clusterID in personClusters.toSet()) {
if (!personClusterToSummary.containsKey(clusterID)) {
_logger.warning('missing summary for $clusterID');
@@ -2234,7 +2187,6 @@ class ClusterFeedbackService<T> {
return null;
}
- // Calculate the avg embedding of the person
int personEmbeddingsCount = 0;
for (final clusterID in personClusters) {
personEmbeddingsCount += personClusterToSummary[clusterID]!.$2;
@@ -2263,14 +2215,12 @@ class ClusterFeedbackService<T> {
}) async {
if (!kDebugMode) return;
- // Logging the clusterID
_logger.info(
"Debug logging for cluster $clusterID${clusterSize != null ? ' with $clusterSize photos' : ''}",
);
// todo:(laurens) remove to review
const String biggestClusterID = 'some random id';
- // Logging the cluster summary for the cluster
if (logClusterSummary) {
final summaryMap = await mlDataDB.getClusterToClusterSummary([
clusterID,
@@ -2293,7 +2243,6 @@ class ClusterFeedbackService<T> {
"Cluster summary for current cluster $clusterID says the size is: ${clusterSummary.$2}",
);
- // Mean distance
final biggestMean = Vector.fromList(
EVector.fromBuffer(biggestClusterSummary.$1).values,
dtype: DType.float32,
@@ -2317,7 +2266,6 @@ class ClusterFeedbackService<T> {
);
_logger.info('True distance between the two means: $trueDistance');
- // Median distance
const sampleSize = 100;
final Iterable<Uint8List> biggestEmbeddings = await mlDataDB
.getFaceEmbeddingsForCluster(biggestClusterID);
@@ -2347,7 +2295,6 @@ class ClusterFeedbackService<T> {
)
.toList(growable: false);
- // Calculate distances and find the median
final List<double> distances = [];
final List<double> trueDistances = [];
for (final biggestEmbedding in biggestSampledEmbeddings) {
@@ -2375,7 +2322,6 @@ class ClusterFeedbackService<T> {
}
}
- // Logging the blur values for the cluster
if (logBlurValues) {
final List<double> blurValues = await mlDataDB
.getBlurValuesForCluster(clusterID)
@@ -2393,12 +2339,8 @@ class ClusterFeedbackService<T> {
}
}
-/// Returns a list of suggestions for a cluster in a tuple. The values of the tuple are:
-/// 1. The suggested cluster ID
-/// 2. The distance between the two clusters
-/// 3. The corresponding cluster ID of the person cluster
+// Returns (suggestion cluster ID, distance, person cluster ID).
List<(String, double, String)> _calcSuggestionsMean(Map<String, dynamic> args) {
- // Fill in args
final Map<String, Vector> clusterAvg = args['clusterAvg'];
final Set<String> personClusters = args['personClusters'];
final Set<String> ignoredClusters = args['ignoredClusters'];
@@ -2413,7 +2355,6 @@ List<(String, double, String)> _calcSuggestionsMean(Map<String, dynamic> args) {
int comparisons = 0;
final w = (kDebugMode ? EnteWatch('getSuggestions') : null)?..start();
- // ignore the clusters that belong to the person or is ignored
Set<String> otherClusters = clusterAvg.keys.toSet().difference(
personClusters,
);
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart
index c0790616c0..b65e063f7d 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart
@@ -65,7 +65,6 @@ class PersonService {
_currentUserIDProvider =
currentUserIDProvider ?? Configuration.instance.getUserID;
- // instance
static PersonService? _instance;
static const double kDefaultAutoMergeThreshold = 0.24;
static double autoMergeThreshold = kDefaultAutoMergeThreshold;
@@ -120,7 +119,6 @@ class PersonService {
.map((person) => person.data.email)
.whereType<String>();
- /// Prefers an account ID link, then supports legacy email-only person links.
PersonEntity? getCachedPersonForUser(int? userID, String email) {
final requestedUserID = userID != null && userID > 0 ? userID : null;
final userIdMatch = requestedUserID == null
@@ -165,7 +163,8 @@ class PersonService {
return null;
}
- // Pre-userID Person entities are email-only; only positive IDs block fallback.
+ // When an account ID was requested, email fallback is limited to legacy
+ // persons without one.
static bool _canUseEmailFallback(PersonEntity person, int? requestedUserID) {
return requestedUserID == null || (person.data.userID ?? 0) <= 0;
}
@@ -527,7 +526,6 @@ class PersonService {
}) async {
final personData = person.data;
- // Remove faces from clusters
final List<String> emptiedClusters = [];
for (final cluster in personData.assigned) {
cluster.faces.removeWhere((faceID) => faceIDs.contains(faceID));
@@ -536,7 +534,6 @@ class PersonService {
}
}
- // Safety check to make sure we haven't created an empty cluster now, if so delete it
for (final emptyClusterID in emptiedClusters) {
personData.assigned.removeWhere(
(element) => element.id == emptyClusterID,
@@ -547,7 +544,6 @@ class PersonService {
);
}
- // Add removed faces to rejected faces
personData.rejectedFaceIDs.addAll(faceIDs);
await _addOrUpdateEntity(
@@ -590,7 +586,6 @@ class PersonService {
}
}
- // fire PeopleChangeEvent
Bus.instance.fire(PeopleChangedEvent());
}
@@ -644,7 +639,6 @@ class PersonService {
}
int faceCount = 0;
- // Locally store the assignment of faces to clusters and people
for (var cluster in personData.assigned) {
faceCount += cluster.faces.length;
for (var faceId in cluster.faces) {
@@ -697,7 +691,6 @@ class PersonService {
);
if (assignedAndRejectedFaceIDs.isNotEmpty) {
- // Check that we don't have any empty clusters now
final dbPersonClusterInfo = dbPeopleClusterInfo[e.id]!;
final faceToClusterToRemove = <String, String>{};
for (final clusterIdToFaceIDs in dbPersonClusterInfo.entries) {
@@ -727,7 +720,6 @@ class PersonService {
faceToClusterToRemove.addAll(foundRejectedFacesToCluster);
}
}
- // Remove the clusterID for the remaining conflicting faces
await faceMLDataDB.removeFaceIdToClusterId(faceToClusterToRemove);
}
}
@@ -991,7 +983,6 @@ class PersonService {
}
}
- /// Wrapper method for entityService.addOrUpdate that handles cache refresh
Future<LocalEntityData> _addOrUpdateEntity(
EntityType type,
Map<String, dynamic> jsonMap, {
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
index 7808798ed9..ad81ff3f18 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
@@ -40,7 +40,6 @@ import "package:photos/utils/ram_check_util.dart";
class MLService {
final _logger = Logger("MLService");
- // Singleton pattern
MLService._privateConstructor();
static final instance = MLService._privateConstructor();
factory MLService() => instance;
@@ -92,7 +91,6 @@ class MLService {
mode;
}
- /// Only call this function once at app startup, after that you can directly call [runAllML]
Future<void> init() async {
if (_isInitialized) {
_schedulePredownloadLocalModels();
@@ -101,17 +99,14 @@ class MLService {
}
_logger.info("init called");
- // Check if the device has enough RAM to run local indexing
await checkDeviceTotalRAM();
FaceClusteringService.init(localSettings);
- // Get client name
final packageInfo = ServiceLocator.instance.packageInfo;
client = "${packageInfo.packageName}/${packageInfo.version}";
_logger.info("client: $client");
- // Listen on ComputeController
Bus.instance.on<ComputeControlEvent>().listen((event) {
if (!hasGrantedMLConsent) {
if (!isProcessBg && event.shouldRun) {
@@ -452,10 +447,6 @@ class MLService {
MLIndexingIsolate.instance.shouldPauseIndexingAndClustering = false;
}
- /// Analyzes all the images in the user library with the latest ml version and stores the results in the database.
- ///
- /// This function first fetches from remote and checks if the image has already been analyzed
- /// with the lastest faceMlVersion and stored on remote or local database. If so, it skips the image.
Future<void> fetchAndIndexAllImages({required MLMode mode}) async {
if (!_canRunMLFunction(function: "Indexing")) return;
if (mode == MLMode.enteGallery && !isLocalGalleryMode) {
@@ -584,13 +575,11 @@ class MLService {
}
try {
- // Get a sense of the total number of faces in the database
final int totalFaces = await _mlDataDB.getTotalFaceCount();
final fileIDToCreationTime = isLocalGalleryMode
? await _getLocalGalleryFileIdToCreationTime()
: await FilesDB.instance.getFileIDToCreationTime();
final startEmbeddingFetch = DateTime.now();
- // read all embeddings
final result = await _mlDataDB.getFaceInfoForClustering(
maxFaces: totalFaces,
);
@@ -606,7 +595,6 @@ class MLService {
allFaceInfoForClustering.add(faceInfo);
}
}
- // sort the embeddings based on file creation time, newest first
allFaceInfoForClustering.sort((b, a) {
return fileIDToCreationTime[a.fileID]!.compareTo(
fileIDToCreationTime[b.fileID]!,
@@ -617,7 +605,6 @@ class MLService {
'and ${missingFileIDs.length} missing fileIDs',
);
- // Get the current cluster statistics
final Map<String, (Uint8List, int)> oldClusterSummaries = await _mlDataDB
.getAllClusterSummary();
@@ -705,7 +692,6 @@ class MLService {
}
} else {
final clusterStartTime = DateTime.now();
- // Cluster the embeddings using the linear clustering algorithm, returning a map from faceID to clusterID
final clusteringResult = await FaceClusteringService.instance
.predictLinearIsolate(
allFaceInfoForClustering.toSet(),
@@ -721,7 +707,6 @@ class MLService {
'done with clustering ${allFaceInfoForClustering.length} in ${clusterDoneTime.difference(clusterStartTime).inSeconds} seconds ',
);
- // Store the updated clusterIDs in the database
_logger.info(
'Updating ${clusteringResult.newFaceIdToCluster.length} FaceIDs with clusterIDs in the DB',
);
@@ -768,7 +753,6 @@ class MLService {
instruction,
filePath,
);
- // Check if there's no result simply because MLController paused indexing
if (result == null) {
if (!_shouldPauseIndexingAndClustering &&
!MLIndexingIsolate.instance.shouldPauseIndexingAndClustering) {
@@ -778,11 +762,9 @@ class MLService {
}
return actuallyRanML;
}
- // Check anything actually ran
actuallyRanML = result.ranML;
if (!actuallyRanML) return actuallyRanML;
final bool isLocalGallery = instruction.isLocalGallery;
- // Prepare storing data on remote (online mode only)
final FileDataEntity? dataEntity = isLocalGallery
? null
: (instruction.existingRemoteFileML ??
@@ -790,7 +772,6 @@ class MLService {
instruction.file.uploadedFileID!,
DataType.mlData,
));
- // Faces results
final List<Face> faces = [];
if (result.facesRan) {
if (result.faces!.isEmpty) {
@@ -820,7 +801,6 @@ class MLService {
);
}
}
- // Clip results
if (result.clipRan) {
if (!isLocalGallery) {
dataEntity!.putClip(
@@ -834,10 +814,8 @@ class MLService {
}
}
if (!isLocalGallery && (result.facesRan || result.clipRan)) {
- // Storing results on remote
await fileDataService.putFileData(instruction.file, dataEntity!);
}
- // Storing results locally
if (result.facesRan) await mlDataDB.bulkInsertFaces(faces);
if (result.clipRan) {
if (isLocalGallery) {
@@ -855,8 +833,8 @@ class MLService {
}
}
- // Pet results locally β€” delete stale rows before writing so
- // re-indexing with fewer detections doesn't leave old data behind.
+ // Delete stale pet rows first so re-indexing with fewer detections does
+ // not leave old data behind.
final rustPets = result.petFaces != null || result.petBodies != null;
if (rustPets) {
await mlDataDB.deletePetDataForFiles([result.fileId]);
@@ -1041,7 +1019,6 @@ class MLService {
return false;
}
if (_shouldPauseIndexingAndClustering) {
- // This should ideally not be triggered, because one of the above should be triggered instead.
_logger.warning(
"Cannot run $function because indexing and clustering is being paused",
);
diff --git a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
index 12bae2d8e1..008f12566d 100644
--- a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
@@ -129,8 +129,8 @@ class SemanticSearchService {
}
}
- // searchScreenQuery should only be used for the user initiate query on the search screen.
- // If there are multiple call tho this method, then for all the calls, the result will be the same as the last query.
+ // Use only for interactive search. Concurrent calls all resolve with the
+ // latest query's results.
Future<(String, List<EnteFile>)> searchScreenQuery(String query) async {
if (!isMagicSearchEnabledAndReady()) {
if (flagService.internalUser) {
@@ -140,20 +140,15 @@ class SemanticSearchService {
}
return (query, <EnteFile>[]);
}
- // If there's an ongoing request, just update the last query and return its future.
if (_searchScreenRequest != null) {
_latestPendingQuery = query;
return _searchScreenRequest!;
} else {
- // No ongoing request, start a new search.
_searchScreenRequest = getMatchingFiles(query).then((result) {
- // Search completed, reset the ongoing request.
_searchScreenRequest = null;
- // If there was a new query during the last search, start a new search with the last query.
if (_latestPendingQuery != null) {
final String newQuery = _latestPendingQuery!;
- _latestPendingQuery = null; // Reset last query.
- // Recursively call search with the latest query.
+ _latestPendingQuery = null;
return searchScreenQuery(newQuery);
}
return (query, result);
@@ -204,7 +199,6 @@ class SemanticSearchService {
double? similarityThreshold,
}) async {
bool showThreshold = false;
- // if the query starts with 0.xxx, the split the query to get score threshold and actual query
if (query.startsWith(RegExp(r"0\.\d+"))) {
final parts = query.split(" ");
if (parts.length > 1) {
@@ -222,14 +216,6 @@ class SemanticSearchService {
minimumSimilarityMap: {query: minimumSimilarity},
);
final queryResults = similarityResults[query] ?? <QueryResult>[];
- // Uncomment if needed for debugging: print query for top ten scores
- // if (kDebugMode) {
- // for (int i = 0; i < min(10, queryResults.length); i++) {
- // final result = queryResults[i];
- // dev.log("Query: $query, Score: ${result.score}, index $i");
- // }
- // }
-
final Map<int, double> fileIDToScoreMap = {};
for (final result in queryResults) {
fileIDToScoreMap[result.id] = result.score;
@@ -319,10 +305,8 @@ class SemanticSearchService {
return results;
}
- /// Get matching file IDs for common repeated queries like smart memories and magic cache.
- /// WARNING: Use this method carefully - it uses persistent caching which is only
- /// beneficial for queries that are repeated across app sessions.
- /// For regular user searches, use getMatchingFiles instead.
+ // The persistent cache is only useful for queries repeated across app
+ // sessions. Use getMatchingFiles for user searches.
Future<Map<String, List<int>>> getMatchingFileIDsForCommonQueries(
Map<String, double> queryToScore,
) async {
@@ -332,7 +316,6 @@ class SemanticSearchService {
for (final entry in queryToScore.entries) {
final query = entry.key;
final score = entry.value;
- // Use cache service instead of _getTextEmbedding
final textEmbedding = await textEmbeddingsCacheService.getEmbedding(
query,
);
@@ -401,13 +384,6 @@ class SemanticSearchService {
required Map<String, double> minimumSimilarityMap,
int? maxResults,
}) async {
- // Uncomment if needed for debugging: print query embeddings
- // if (kDebugMode) {
- // for (final queryText in textQueryToEmbeddingMap.keys) {
- // final embedding = textQueryToEmbeddingMap[queryText]!;
- // dev.log("CLIPTEXT Query: $queryText, embedding: $embedding");
- // }
- // }
if (await _canUseVectorDbForSearch()) {
final startTime = DateTime.now();
try {
diff --git a/mobile/apps/photos/lib/services/machine_learning/similar_images_service.dart b/mobile/apps/photos/lib/services/machine_learning/similar_images_service.dart
index 27d9c933ad..9eb0884767 100644
--- a/mobile/apps/photos/lib/services/machine_learning/similar_images_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/similar_images_service.dart
@@ -26,8 +26,6 @@ class SimilarImagesService {
static final SimilarImagesService instance =
SimilarImagesService._privateConstructor();
- /// Returns a list of SimilarFiles, where each SimilarFiles object contains
- /// a list of files that are perceptually similar
Future<List<SimilarFiles>> getSimilarFiles(
double distanceThreshold, {
bool exact = false,
@@ -62,13 +60,11 @@ class SimilarImagesService {
await mlDataDB.checkMigrateFillClipVectorDB();
w?.log("checkMigrateFillClipVectorDB");
- // Get all files with CLIP embeddings first to avoid caching unindexed files
final Map<int, int> clipIndexedFiles = await mlDataDB
.clipIndexedFileWithVersion();
final Set<int> clipIndexedFileIDs = clipIndexedFiles.keys.toSet();
w?.log("getClipIndexedFiles");
- // Get all files, and all potential embedding IDs, and create a map of fileID to file
final allFiles = Set<EnteFile>.from(
await SearchService.instance.getAllFilesForSearch(),
);
@@ -86,7 +82,6 @@ class SimilarImagesService {
final Uint64List potentialKeys = Uint64List.fromList(fileIDs);
w?.log("getAllFilesForSearch");
- // Get mapping of fileIDs to corresponding personIDs
final fileIDToPersonIDs = <int, Set<String>>{};
final dbPersonClusterInfo = await mlDataDB.getPersonToClusterIdToFaceIds();
for (final personID in dbPersonClusterInfo.keys) {
@@ -122,7 +117,6 @@ class SimilarImagesService {
return result;
}
- // Load cached data
final SimilarFilesCache? cachedData = await _readCachedSimilarFiles();
if (cachedData == null) {
_logger.warning("No cached similar files found");
@@ -132,7 +126,6 @@ class SimilarImagesService {
);
}
- // Determine if we need full refresh
bool needsFullRefresh = false;
if (cachedData != null) {
final Set<int> cachedFileIDs = cachedData.allCheckedFileIDs;
@@ -143,19 +136,16 @@ class SimilarImagesService {
needsFullRefresh = true;
}
- // Check condition: less than 1000 files
if (currentFileIDs.length < 1000) {
needsFullRefresh = true;
}
- // Check condition: cache is older than a month
if (DateTime.fromMillisecondsSinceEpoch(
cachedData.cachedTime,
).isBefore(DateTime.now().subtract(const Duration(days: 30)))) {
needsFullRefresh = true;
}
- // Check condition: new files > 20% of total files
if (!needsFullRefresh) {
final newFileIDs = currentFileIDs.difference(cachedFileIDs);
if (newFileIDs.length > currentFileIDs.length * 0.2) {
@@ -163,7 +153,6 @@ class SimilarImagesService {
}
}
- // Check condition: 20+% of grouped files deleted
if (!needsFullRefresh) {
final Set<int> cacheGroupedFileIDs = await cachedData
.getGroupedFileIDs();
@@ -232,7 +221,6 @@ class SimilarImagesService {
final currentFileIDsSet = currentFileIDs.map((id) => id.toInt()).toSet();
final deletedFiles = cachedFileIDs.difference(currentFileIDsSet);
- // Clean up deleted files from existing groups
if (deletedFiles.isNotEmpty) {
for (final group in existingGroups) {
final filesInGroupToDelete = [];
@@ -246,10 +234,8 @@ class SimilarImagesService {
}
}
}
- // Remove empty groups
existingGroups.removeWhere((group) => group.length <= 1);
- // Identify new files
final newFileIDs = currentFileIDsSet.difference(cachedFileIDs);
if (newFileIDs.isEmpty) {
if (deletedFiles.isNotEmpty) {
@@ -264,13 +250,11 @@ class SimilarImagesService {
return existingGroups;
}
- // Search only new files
final newFileIDsList = Uint64List.fromList(newFileIDs.toList());
final (keys, vectorKeys, distances) = await MLComputer.instance
.bulkVectorSearchWithKeys(newFileIDsList, exact);
final keysList = keys.map((key) => key.toInt()).toList();
- // Try to assign new files to existing groups
final unassignedNewFilesIndices = <int>{};
final unassignedNewFileIDs = <int>{};
for (int i = 0; i < keysList.length; i++) {
@@ -317,7 +301,6 @@ class SimilarImagesService {
}
}
- // Check if unassigned new files form groups among themselves
if (unassignedNewFilesIndices.isNotEmpty) {
final alreadyUsedNewFiles = <int>{};
for (final searchIndex in unassignedNewFilesIndices) {
@@ -382,12 +365,10 @@ class SimilarImagesService {
) async {
_logger.info("Performing full search for similar files");
final w = (kDebugMode ? EnteWatch('getSimilarFiles') : null)?..start();
- // Run bulk vector search
final (keys, vectorKeys, distances) = await MLComputer.instance
.bulkVectorSearchWithKeys(potentialKeys, exact);
w?.log("bulkSearchVectors");
- // Run through the vector search results and create SimilarFiles objects
final alreadyUsedFileIDs = <int>{};
final allSimilarFiles = <SimilarFiles>[];
for (int i = 0; i < keys.length; i++) {
@@ -423,7 +404,6 @@ class SimilarImagesService {
for (final file in similarFilesList) {
alreadyUsedFileIDs.add(file.uploadedFileID!);
}
- // show highest quality files first
similarFilesList.sort((a, b) {
if (FavoritesService.instance.isFavoriteCache(a)) {
return -1;
diff --git a/mobile/apps/photos/lib/services/sync/diff_fetcher.dart b/mobile/apps/photos/lib/services/sync/diff_fetcher.dart
index 79a0173340..91e40b0b0b 100644
--- a/mobile/apps/photos/lib/services/sync/diff_fetcher.dart
+++ b/mobile/apps/photos/lib/services/sync/diff_fetcher.dart
@@ -87,7 +87,7 @@ class DiffFetcher {
);
}
- // To avoid local file to be used as thumbnail or full file.
+ // Do not use local media for public collection files.
file.localID = null;
sharedFiles.add(file);
diff --git a/mobile/apps/photos/lib/services/sync/import/diff.dart b/mobile/apps/photos/lib/services/sync/import/diff.dart
index 58a41ec990..b78f8daaeb 100644
--- a/mobile/apps/photos/lib/services/sync/import/diff.dart
+++ b/mobile/apps/photos/lib/services/sync/import/diff.dart
@@ -6,14 +6,10 @@ import "package:photos/module/metadata/local_file.dart";
import "package:photos/services/sync/import/model.dart";
class LocalDiffResult {
- // unique localPath Assets.
final List<LocalPathAsset>? localPathAssets;
- // set of File object created from localPathAssets
List<EnteFile>? uniqueLocalFiles;
- // newPathToLocalIDs represents new entries which needs to be synced to
- // the local db
final Map<String, Set<String>>? newPathToLocalIDs;
final Map<String, Set<String>>? deletePathToLocalIDs;
@@ -28,8 +24,7 @@ class LocalDiffResult {
Future<LocalDiffResult> getDiffFromExistingImport(
List<LocalPathAsset> assets,
- // current set of assets available on device
- Set<String> existingIDs, // localIDs of files already imported in app
+ Set<String> existingIDs,
Map<String, Set<String>> pathToLocalIDs,
) async {
final Map<String, dynamic> args = <String, dynamic>{};
@@ -73,8 +68,6 @@ Future<List<EnteFile>> _convertLocalAssetsToUniqueFiles(
return files;
}
-// _getLocalAssetsDiff compares local db with the file system and compute
-// the files which needs to be added or removed from device collection.
LocalDiffResult _getLocalAssetsDiff(Map<String, dynamic> args) {
final List<LocalPathAsset> onDeviceLocalPathAsset = args['assets'];
final Set<String> existingIDs = args['existingIDs'];
@@ -86,15 +79,13 @@ LocalDiffResult _getLocalAssetsDiff(Map<String, dynamic> args) {
for (final localPathAsset in onDeviceLocalPathAsset) {
final String pathID = localPathAsset.pathID;
- // Start identifying pathID to localID mapping changes which needs to be
- // synced
final Set<String> candidateLocalIDsForRemoval =
pathToLocalIDs[pathID] ?? <String>{};
final Set<String> missingLocalIDsInPath = <String>{};
for (final String localID in localPathAsset.localIDs) {
if (candidateLocalIDsForRemoval.contains(localID)) {
- // remove the localID after checking. Any pending existing ID indicates
- // the the local file was removed from the path.
+ // Remove IDs still present; any IDs left afterward were removed from
+ // the device folder.
candidateLocalIDsForRemoval.remove(localID);
} else {
missingLocalIDsInPath.add(localID);
@@ -106,8 +97,6 @@ LocalDiffResult _getLocalAssetsDiff(Map<String, dynamic> args) {
if (missingLocalIDsInPath.isNotEmpty) {
newPathToLocalIDs[pathID] = missingLocalIDsInPath;
}
- // End
-
localPathAsset.localIDs.removeAll(existingIDs);
if (localPathAsset.localIDs.isNotEmpty) {
unsyncedAssets.add(localPathAsset);
diff --git a/mobile/apps/photos/lib/services/sync/import/local_assets.dart b/mobile/apps/photos/lib/services/sync/import/local_assets.dart
index 5aa9811ec7..8225adcfda 100644
--- a/mobile/apps/photos/lib/services/sync/import/local_assets.dart
+++ b/mobile/apps/photos/lib/services/sync/import/local_assets.dart
@@ -25,9 +25,7 @@ Future<Tuple2<List<LocalPathAsset>, List<EnteFile>>> getLocalPathAssetsAndFiles(
);
final List<LocalPathAsset> localPathAssets = [];
- // alreadySeenLocalIDs is used to track and ignore file with particular
- // localID if it's already present in another album. This only impacts iOS
- // devices where a file can belong to multiple
+ // iOS assets can belong to multiple albums; emit each local ID once.
final Set<String> alreadySeenLocalIDs = {};
final List<EnteFile> uniqueFiles = [];
for (AssetPathEntity pathEntity in pathEntities) {
@@ -68,11 +66,6 @@ Future<Tuple2<List<LocalPathAsset>, List<EnteFile>>> getLocalPathAssetsAndFiles(
return Tuple2(localPathAssets, uniqueFiles);
}
-// getDeviceFolderWithCountAndLatestFile returns a tuple of AssetPathEntity and
-// latest file's localID in the assetPath, along with modifiedPath time and
-// total count of assets in a Asset Path.
-// We use this result to update the latest thumbnail for deviceFolder and
-// identify (in future) which AssetPath needs to be re-synced again.
Future<List<Tuple2<AssetPathEntity, String>>>
getDeviceFolderWithCountAndCoverID() async {
final List<Tuple2<AssetPathEntity, String>> result = [];
@@ -133,14 +126,11 @@ Future<List<LocalPathAsset>> getAllLocalAssets({bool? needsTitle}) async {
return localPathAssets;
}
-/// returns a list of AssetPathEntity with relevant filter operations.
-/// [needTitle] impacts the performance for fetching the actual [AssetEntity]
-/// in iOS. Same is true for [containsModifiedPath]
Future<List<AssetPathEntity>> _getGalleryList({
final int? updateFromTime,
final int? updateToTime,
+ // Fetching asset titles or modified-path data is expensive on iOS.
final bool containsModifiedPath = false,
- // in iOS fetching the AssetEntity title impacts performance
final bool needsTitle = true,
final OrderOption? orderOption,
}) async {
diff --git a/mobile/apps/photos/lib/services/sync/local_sync_service.dart b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
index 66ab17a3a5..8ccaf3e6be 100644
--- a/mobile/apps/photos/lib/services/sync/local_sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
@@ -99,9 +99,8 @@ class LocalSyncService {
_existingSync = Completer<void>();
final int ownerID = Configuration.instance.getUserIDV2();
- // We use a lock to prevent synchronisation to occur while it is downloading
- // as this introduces wrong entry in FilesDB due to race condition
- // This is a fix for https://github.com/ente/ente/issues/4296
+ // Local sync must not race downloads; that can create incorrect FilesDB
+ // rows.
await _lock.synchronized(() async {
final existingLocalFileIDs = await _db.getExistingLocalFileIDs(ownerID);
_logger.info("${existingLocalFileIDs.length} localIDs were discovered");
@@ -116,7 +115,6 @@ class LocalSyncService {
toTime: syncStartTime,
);
} else {
- // Load from 0 - 01.01.2010
Bus.instance.fire(
SyncStatusUpdate(SyncStatus.startedFirstGalleryImport),
);
@@ -176,8 +174,7 @@ class LocalSyncService {
result,
shouldBackup: backupPreferenceService.hasSelectedAllFoldersForBackup,
);
- // do not fire UI update event during first sync. Otherwise the next screen
- // to shop the backup folder is skipped
+ // Firing this during first sync skips the backup-folder screen.
if (hasUpdated && !isFirstSync) {
Bus.instance.fire(BackupFoldersUpdatedEvent());
}
@@ -306,8 +303,7 @@ class LocalSyncService {
return;
}
if (Platform.isIOS && error.reason == InvalidReason.sourceFileMissing) {
- // ignoreSourceFileMissing error on iOS as the file fetch from iCloud might have failed,
- // but the file might be available later
+ // Do not persist this failure; iCloud may make the asset available later.
return;
}
final reason = error.reason == InvalidReason.photosResourceUnavailable
@@ -330,9 +326,7 @@ class LocalSyncService {
return _prefs.getBool(kHasCompletedFirstImportKey) ?? false;
}
- /// Treat the first import as "done" when flag-driven flows intentionally
- /// bypass it (e.g., onboarding skipped or only-new backup). Falls back to the
- /// stored completion value otherwise.
+ // Onboarding skips and only-new backup intentionally bypass the first import.
bool hasCompletedFirstImportOrBypassed() {
if (!isLocalGalleryMode &&
Configuration.instance.hasConfiguredAccount() &&
@@ -356,8 +350,6 @@ class LocalSyncService {
final List<EnteFile> files = result.item2;
if (files.isNotEmpty) {
- // Update the mapping for device path_id to local file id. Also, keep track
- // of newly discovered device paths
await FilesDB.instance.insertLocalAssets(
result.item1,
shouldAutoBackup:
@@ -371,10 +363,8 @@ class LocalSyncService {
DateTime.fromMicrosecondsSinceEpoch(toTime).toString(),
);
await _trackUpdatedFiles(files, existingLocalDs);
- // keep reference of all Files for firing LocalPhotosUpdatedEvent
final List<EnteFile> allFiles = [];
allFiles.addAll(files);
- // remove existing files and insert newly imported files in the table
files.removeWhere((file) => existingLocalDs.contains(file.localID));
await _db.insertMultiple(
files,
@@ -496,8 +486,7 @@ class LocalSyncService {
}
_isChangeCallbackRegistered = true;
_changeCallbackDebouncer = Debouncer(const Duration(milliseconds: 500));
- // In case of iOS limit permission, this call back is fired immediately
- // after file selection dialog is dismissed.
+ // iOS fires this immediately after the limited-access picker closes.
PhotoManager.addChangeCallback((value) async {
_logger.info("Something changed on disk");
_changeCallbackDebouncer.run(() async {
diff --git a/mobile/apps/photos/lib/services/sync/remote_sync_service.dart b/mobile/apps/photos/lib/services/sync/remote_sync_service.dart
index 05c8c9ed1a..7c4075687b 100644
--- a/mobile/apps/photos/lib/services/sync/remote_sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/remote_sync_service.dart
@@ -59,19 +59,10 @@ class RemoteSyncService {
bool _isExistingSyncSilent = false;
StreamSubscription<LocalPhotosUpdatedEvent>? _localPhotosUpdatedSubscription;
- // _hasCleanupStaleEntry is used to track if we have already cleaned up
- // statle db entries in this sync session.
bool _hasCleanupStaleEntry = false;
static const kHasSyncedArchiveKey = "has_synced_archive";
- /* This setting is used to maintain a list of local IDs for videos that the user has manually
- marked for upload, even if the global video upload setting is currently disabled.
- When the global video upload setting is disabled, we typically ignore all video uploads. However, for videos that have been added to this list, we
- want to still allow them to be uploaded, despite the global setting being disabled.
-
- This allows users to queue up videos for upload, and have them successfully upload
- even if they later toggle the global video upload setting to disabled.
- */
+ // Disabling video backup must not prevent already queued videos from uploading.
static const _ignoreBackUpSettingsForIDs_ = "ignoreBackUpSettingsForIDs";
final String _isFirstRemoteSyncDone = "isFirstRemoteSyncDone";
@@ -114,8 +105,7 @@ class RemoteSyncService {
}
if (_existingSync != null) {
_logger.info("Remote sync already in progress, skipping");
- // if current sync is silent but request sync is non-silent (demands UI
- // updates), update the syncSilently flag
+ // A visible request upgrades an in-flight silent sync.
if (_isExistingSyncSilent && !silently) {
_isExistingSyncSilent = false;
}
@@ -132,10 +122,8 @@ class RemoteSyncService {
final canPrepareUploadsInBackground =
!isProcessBg || await canUseHighBandwidth();
- // use flag to decide if we should start marking files for upload before
- // remote-sync is done. This is done to avoid adding existing files to
- // the same or different collection when user had already uploaded them
- // before.
+ // First sync must pull the diff before marking uploads, or existing
+ // remote files can be queued again.
final bool hasSyncedBefore = _prefs.containsKey(_isFirstRemoteSyncDone);
if (hasSyncedBefore && canPrepareUploadsInBackground) {
await syncDeviceCollectionFilesForUpload();
@@ -144,7 +132,7 @@ class RemoteSyncService {
await trashSyncService.syncTrash();
await _collectionsService.movePendingRemovalActionsToUncategorized();
- // Sync social data immediately after diff sync, before uploads
+ // Sync social data immediately after the diff, before uploads.
if (AppLifecycleService.instance.isForeground) {
_socialSync().ignore();
} else {
@@ -158,9 +146,7 @@ class RemoteSyncService {
}
}
- if (
- // We don't need syncFDStatus here if in background
- !isProcessBg) {
+ if (!isProcessBg) {
fileDataService.syncFDStatus().ignore();
}
@@ -186,16 +172,12 @@ class RemoteSyncService {
final hasMoreFilesToBackup = (await _getFilesToBeUploaded()).isNotEmpty;
_logger.info("hasMoreFilesToBackup?" + hasMoreFilesToBackup.toString());
if (hasMoreFilesToBackup) {
- // Skipping a resync to ensure that files that were ignored in this
- // session are not processed now
await sync();
} else {
_logger.info("Fire backup completed event");
Bus.instance.fire(SyncStatusUpdate(SyncStatus.completedBackup));
}
} else {
- // if filesToBeUploaded is empty, clear any stale files in the temp
- // directory
if (filesToBeUploaded.isEmpty) {
await _uploader.removeStaleFiles();
}
@@ -215,7 +197,7 @@ class RemoteSyncService {
_logger.warning("Error executing remote sync", e, s);
if (flagService.internalUser ||
- // rethrow whitelisted error so that UI status can be updated correctly.
+ // The outer sync uses these errors to update UI state.
{
UnauthorizedError,
NoActiveSubscriptionError,
@@ -255,9 +237,8 @@ class RemoteSyncService {
Bus.instance.fire(SyncStatusUpdate(SyncStatus.applyingRemoteDiff));
}
await _collectionsService.sync();
- // check and reset user's collection syncTime in past for older clients
+ // Older clients may need collection diffs replayed from feature cutoffs.
if (isFirstSync) {
- // not need reset syncTime, mark all flags as done if firstSync
await _markResetSyncTimeAsDone();
} else if (_shouldResetSyncTime()) {
_logger.warning('Resetting syncTime for for the client');
@@ -280,10 +261,7 @@ class RemoteSyncService {
cid,
_collectionsService.getCollectionSyncTime(cid),
);
- // update syncTime for the collection in sharedPrefs. Note: the
- // syncTime can change on remote but we might not get a diff for the
- // collection if there are not changes in the file, but the collection
- // metadata (name, archive status, sharing etc) has changed.
+ // Collection metadata can advance remote time without a file diff.
final remoteUpdateTime = idsToRemoteUpdationTimeMap[cid];
await _collectionsService.setCollectionSyncTime(cid, remoteUpdateTime);
}
@@ -398,20 +376,18 @@ class RemoteSyncService {
final deviceCollections = await _db.getDeviceCollections();
deviceCollections.removeWhere((element) => !element.shouldBackup);
- // Sort by count to ensure that photos in iOS are first inserted in
- // smallest album marked for backup. This is to ensure that photo is
- // first attempted to upload in a non-recent album.
+ // On iOS, process smaller albums first so assets are first queued from a
+ // non-recent album.
deviceCollections.sort((a, b) => a.count.compareTo(b.count));
final Map<String, Set<String>> pathIdToLocalIDs = await _db
.getDevicePathIDToLocalIDMap();
- // Fetch all newer local IDs once if only-new backup is enabled
final backNewPhotosOnly = backupPreferenceService.isOnlyNewBackupEnabled;
late final Set<String> newerLocalIDs;
if (backNewPhotosOnly) {
final int onlyNewSince = backupPreferenceService.onlyNewSinceEpoch!;
- // Single DB query for all newer files
+ // Fetch newer IDs once for all backup folders.
newerLocalIDs = await _db.getAllLocalIDsNewerThan(onlyNewSince);
_logger.info("Found ${newerLocalIDs.length} newer files");
}
@@ -433,9 +409,7 @@ class RemoteSyncService {
}
}
- // Filter by only-new using pre-fetched set
if (backNewPhotosOnly) {
- // Keep only files that are in newerLocalIDs (removes old files)
localIDsToSync.retainAll(newerLocalIDs);
}
@@ -460,9 +434,7 @@ class RemoteSyncService {
localIDsToSync,
);
- // mark IDs as already synced if corresponding entry is present in
- // the collection. This can happen when a user has marked a folder
- // for sync, then un-synced it and again tries to mark if for sync.
+ // Re-enabling a backup folder must not duplicate its existing rows.
final Set<String> existingMapping = await _db
.getLocalFileIDsForCollection(collectionID);
final Set<String> commonElements = localIDsToSync.intersection(
@@ -476,9 +448,6 @@ class RemoteSyncService {
localIDsToSync.removeAll(commonElements);
}
- // At this point, the remaining localIDsToSync will need to create
- // new file entries, where we can store mapping for localID and
- // corresponding collection ID
if (localIDsToSync.isNotEmpty) {
debugPrint(
'Adding new entries for ${localIDsToSync.length} files'
@@ -531,7 +500,6 @@ class RemoteSyncService {
}
if (moreFilesMarkedForBackup &&
!backupPreferenceService.hasSelectedAllFoldersForBackup) {
- // "force reload due to display new files"
Bus.instance.fire(ForceReloadHomeGalleryEvent("newFilesDisplay"));
}
_hasCleanupStaleEntry = true;
@@ -546,7 +514,6 @@ class RemoteSyncService {
final Set<int> newCollectionIDsForAutoSync = await _db
.getDeviceSyncCollectionIDs();
SyncService.instance.onDeviceCollectionSet(newCollectionIDsForAutoSync);
- // remove all collectionIDs which are still marked for backup
oldCollectionIDsForAutoSync.removeAll(newCollectionIDsForAutoSync);
await removeFilesQueuedForUpload(oldCollectionIDsForAutoSync.toList());
if (syncStatusUpdate.values.any((syncStatus) => syncStatus == false)) {
@@ -559,12 +526,6 @@ class RemoteSyncService {
}
Future<void> removeFilesQueuedForUpload(List<int> collectionIDs) async {
- /*
- For each collection, perform following action
- 1) Get List of all files not uploaded yet
- 2) Delete files who localIDs is also present in other collections.
- 3) For Remaining files, set the collectionID as -1
- */
_logger.info("Removing files for collections $collectionIDs");
for (int collectionID in collectionIDs) {
final List<EnteFile> pendingUploads = await _db
@@ -611,19 +572,14 @@ class RemoteSyncService {
return collection.id;
}
if (collection == null) {
- // ideally, this should never happen because the app keeps a track of
- // all collections and their IDs. But, if somehow the collection is
- // deleted, we should fetch it again
_logger.severe(
"Collection ${deviceCollection.collectionID} missing "
"for pathID ${deviceCollection.id}",
);
+ // Retry next sync. Waiting on a bad mapping would block other paths.
_collectionsService
.fetchCollectionByID(deviceCollection.collectionID!)
.ignore();
- // return, by next run collection should be available.
- // we are not waiting on fetch by choice because device might have wrong
- // mapping which will result in breaking upload for other device path
return null;
} else if (collection.isDeleted) {
_logger.warning(
@@ -640,13 +596,8 @@ class RemoteSyncService {
}
Future<List<EnteFile>> _getFilesToBeUploaded() async {
- // Note: "only backup new photos" filtering is applied at the local sync
- // stage (see _syncDeviceCollectionFilesForUpload) where we filter by
- // localID before setting collectionID. Files that reach here with a
- // collectionID but no uploadedFileID either:
- // 1. Passed the only-new filter during auto-backup sync, OR
- // 2. Were manually added by the user to a collection
- // In case 2, we should NOT filter them out - user explicitly chose them.
+ // Only-new filtering happens while auto-backup mappings are created. Do
+ // not apply it here; this queue also includes manually selected files.
final List<EnteFile> originalFiles = await _db.getFilesPendingForUpload();
if (originalFiles.isEmpty) {
return originalFiles;
@@ -721,8 +672,7 @@ class RemoteSyncService {
futures.length >= kMaximumPermissibleUploadsInThrottledMode) {
break;
}
- // prefer existing collection ID for manually uploaded files.
- // See https://github.com/ente/photos-app/pull/187
+ // Keep manually selected files in their chosen collection.
try {
final collectionID =
file.collectionID ??
@@ -836,22 +786,8 @@ class RemoteSyncService {
}
}
- /* _storeDiff maps each remoteFile to existing
- entries in files table. When match is found, it compares both file to
- perform relevant actions like
- [1] Clear local cache when required (Both Shared and Owned files)
- [2] Retain localID of remote file based on matching logic [Owned files]
- [3] Refresh UI if visibility or creationTime has changed [Owned files]
- [4] Schedule file update if the local file has changed since last time
- [Owned files]
- [Important Note: If given uploadedFileID and collectionID is already present
- in files db, the generateID should already point to existing entry.
- Known Issues:
- [K1] Cached entry will not be cleared when if a file was edited and
- moved to different collection as Vid/Image cache key is uploadedID.
- [Existing]
- ]
- */
+ // Moving an edited file between collections does not invalidate cached media
+ // because the cache is keyed by upload ID.
Future<void> _storeDiff(List<EnteFile> diff, int collectionID) async {
int sharedFileNew = 0,
sharedFileUpdated = 0,
@@ -868,13 +804,11 @@ class RemoteSyncService {
final List<EnteFile> toBeInserted = [];
for (EnteFile remoteFile in diff) {
- // existingFile will be either set to existing collectionID+localID or
- // to the unclaimed aka not already linked to any uploaded file.
+ // DiffFetcher preserves generatedID for existing uploadedFileID and
+ // collectionID pairs.
EnteFile? existingFile;
if (remoteFile.generatedID != null) {
- // Case [1] Check and clear local cache when uploadedFile already exist
- // Note: Existing file can be null here if it's replaced by the time we
- // reach here
+ // The row may have been replaced since the diff was fetched.
existingFile = await _db.getUploadedFile(
remoteFile.uploadedFileID!,
remoteFile.collectionID!,
@@ -886,9 +820,7 @@ class RemoteSyncService {
}
}
- /* If file is not owned by the user, no further processing is required
- as Case [2,3,4] are only relevant to files owned by user
- */
+ // Local upload matching and update scheduling only apply to owned files.
if (userID != remoteFile.ownerID) {
if (existingFile == null) {
sharedFileNew++;
@@ -901,7 +833,6 @@ class RemoteSyncService {
remoteFile.localID = existingFile.localID;
}
toBeInserted.add(remoteFile);
- // end processing for file here, move to next file now
continue;
}
@@ -921,11 +852,9 @@ class RemoteSyncService {
deviceFolder: remoteFile.deviceFolder ?? '',
);
if (localFileEntries.isEmpty) {
- // set remote file's localID as null because corresponding local file
- // does not exist [Case 2, do not retain localID of the remote file]
+ // Do not retain a remote localID without a matching local file.
remoteFile.localID = null;
} else {
- // case 4: Check and schedule the file for update
final int maxModificationTime = localFileEntries
.map((e) => e.modificationTime ?? 0)
.reduce(max);
@@ -986,7 +915,6 @@ class RemoteSyncService {
" remoteFiles seen first time",
);
if (needsGalleryReload) {
- // 'force reload home gallery'
Bus.instance.fire(ForceReloadHomeGalleryEvent("remoteSync"));
}
}
@@ -1016,8 +944,6 @@ class RemoteSyncService {
return false;
}
- // return true if the client needs to re-sync the collections from previous
- // version
bool _shouldResetSyncTime() {
return !_prefs.containsKey(kHasSyncedEditTime) ||
!_prefs.containsKey(kHasSyncedArchiveKey);
@@ -1026,15 +952,13 @@ class RemoteSyncService {
Future<void> _markResetSyncTimeAsDone() async {
await _prefs.setBool(kHasSyncedArchiveKey, true);
await _prefs.setBool(kHasSyncedEditTime, true);
- // Check to avoid regression because of change or additions of keys
if (_shouldResetSyncTime()) {
throw Exception("_shouldResetSyncTime should return false now");
}
}
int _getSinceTimeForReSync() {
- // re-sync from archive feature time if the client still hasn't synced
- // since the feature release.
+ // Replay from the oldest feature whose migration has not completed.
if (!_prefs.containsKey(kHasSyncedArchiveKey)) {
return kArchiveFeatureReleaseTime;
}
@@ -1046,34 +970,26 @@ class RemoteSyncService {
}
bool get bgWithoutResumableUpload {
- // if multiple part is enabled, then we are not throttling uploads in bg
return !(flagService.enableMobMultiPart &&
localSettings.userEnabledMultiplePart) &&
!AppLifecycleService.instance.isForeground;
}
- // _sortByTime sort by creation time (desc).
- // This is done to upload most recent photo first.
+ // Upload newest files first, but defer videos in the background.
void _sortByTime(List<EnteFile> file) {
file.sort((first, second) {
- // 1. fileType: move videos to end when in bg
if (!AppLifecycleService.instance.isForeground &&
first.fileType != second.fileType) {
if (first.fileType == FileType.video) return 1;
if (second.fileType == FileType.video) return -1;
}
- // 2. creationTime descending
return second.creationTime!.compareTo(first.creationTime!);
});
}
- /// Builds an upload queue for iOS background sync. For each upload slot,
- /// checks up to [kMaximumPermissibleUploadsInThrottledMode] candidates to
- /// find one that's locally available (not iCloud-only). If a local file is
- /// found, it's picked; otherwise the next file in line is used.
- /// Files already checked and found to be iCloud-only are tracked to avoid
- /// re-checking.
+ // For each iOS background slot, check up to four candidates for a local
+ // file. If none is local, use the next iCloud-only file.
Future<List<EnteFile>> _buildBgUploadQueue(List<EnteFile> files) async {
const maxChecksPerSlot = kMaximumPermissibleUploadsInThrottledMode;
const slots = kMaximumPermissibleUploadsInThrottledMode;
@@ -1218,7 +1134,6 @@ class RemoteSyncService {
}
}
- /// Syncs social data and triggers notifications if needed.
Future<void> _socialSync() async {
try {
_logger.info("Starting social sync");
diff --git a/mobile/apps/photos/lib/services/sync/sync_service.dart b/mobile/apps/photos/lib/services/sync/sync_service.dart
index 892df02682..9b28082f1f 100644
--- a/mobile/apps/photos/lib/services/sync/sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/sync_service.dart
@@ -106,8 +106,7 @@ class SyncService {
});
}
- // Note: Do not use this future for anything except log out.
- // This is prone to bugs due to any potential race conditions
+ // Only logout may wait on this future; other uses are prone to sync races.
Future<bool> existingSync() async {
return _existingSync?.future ?? Future.value(true);
}
diff --git a/mobile/apps/photos/lib/services/sync/trash_sync_service.dart b/mobile/apps/photos/lib/services/sync/trash_sync_service.dart
index e9ca1e9d95..76f14c1c60 100644
--- a/mobile/apps/photos/lib/services/sync/trash_sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/trash_sync_service.dart
@@ -112,12 +112,10 @@ class TrashSyncService {
.getAllOwnedCollectionIDs();
for (final item in trashRequestItems) {
if (!includedFileIDs.contains(item.fileID)) {
- // Check if the collectionID in the request is owned by the user
if (ownedCollectionIDs.contains(item.collectionID)) {
uniqueItems.add(item);
includedFileIDs.add(item.fileID);
} else {
- // If not owned, use a different owned collectionID
final fileCollectionIDs = await FilesDB.instance
.getAllCollectionIDsOfFile(item.fileID);
bool foundAnotherOwnedCollection = false;
@@ -258,7 +256,6 @@ class TrashSyncService {
rethrow;
}
}
- // no need to await on syncing trash from remote
unawaited(syncTrash());
}
diff --git a/mobile/apps/photos/lib/ui/actions/collection/collection_file_actions.dart b/mobile/apps/photos/lib/ui/actions/collection/collection_file_actions.dart
index 35c19f4ea5..d40ca79da9 100644
--- a/mobile/apps/photos/lib/ui/actions/collection/collection_file_actions.dart
+++ b/mobile/apps/photos/lib/ui/actions/collection/collection_file_actions.dart
@@ -110,9 +110,7 @@ extension CollectionFileActions on CollectionActions {
if (file.uploadedFileID != null) {
currentFile = file.copyWith();
} else if (file.generatedID != null) {
- // when file is not uploaded, refresh the state from the db to
- // ensure we have latest upload status for given file before
- // queueing it up as pending upload
+ // Refresh before queuing in case the upload state has changed.
currentFile = await (FilesDB.instance.getFile(file.generatedID!));
} else if (file.generatedID == null) {
logger.severe("generated id should not be null");
@@ -134,7 +132,7 @@ extension CollectionFileActions on CollectionActions {
}
}
if (filesPendingUpload.isNotEmpty) {
- // Newly created collection might not be cached
+ // A newly created collection might not be cached yet.
final Collection? c = CollectionsService.instance.getCollectionByID(
collection.id,
);
@@ -181,8 +179,7 @@ extension CollectionFileActions on CollectionActions {
await showGenericErrorDialog(context: context, error: e);
return false;
} finally {
- // Syncing since successful addition to collection could have
- // happened before a failure
+ // Earlier collections may have succeeded before a later one failed.
unawaited(RemoteSyncService.instance.sync(silently: true));
}
}
@@ -225,9 +222,7 @@ extension CollectionFileActions on CollectionActions {
if (file.uploadedFileID != null) {
currentFile = file.copyWith();
} else if (file.generatedID != null) {
- // when file is not uploaded, refresh the state from the db to
- // ensure we have latest upload status for given file before
- // queueing it up as pending upload
+ // Refresh before queuing in case the upload state has changed.
currentFile = await (FilesDB.instance.getFile(file.generatedID!));
} else if (file.generatedID == null) {
logger.severe("generated id should not be null");
@@ -245,7 +240,7 @@ extension CollectionFileActions on CollectionActions {
}
}
if (filesPendingUpload.isNotEmpty) {
- // Newly created collection might not be cached
+ // A newly created collection might not be cached yet.
final Collection? c = CollectionsService.instance.getCollectionByID(
collectionID,
);
diff --git a/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart b/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart
index 400328b6fe..15e0b51aea 100644
--- a/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart
+++ b/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart
@@ -75,7 +75,6 @@ class CollectionActions {
shouldSurfaceExecutionStates: true,
labelText: context.strings.yesRemove,
onTap: () async {
- // for quickLink collection, we need to trash the collection
if (collection.isQuickLinkCollection() && !collection.hasSharees) {
await trashCollectionKeepingPhotos(collection);
} else {
@@ -92,9 +91,9 @@ class CollectionActions {
),
],
title: context.strings.removePublicLink,
- body:
- //'This will remove the public link for accessing "${collection.name}".',
- context.strings.disableLinkMessage(albumName: collection.displayName),
+ body: context.strings.disableLinkMessage(
+ albumName: collection.displayName,
+ ),
);
if (actionResult?.action != null) {
if (actionResult!.action == ButtonAction.error) {
@@ -116,8 +115,6 @@ class CollectionActions {
) async {
late final Collection newCollection;
try {
- // create album with emptyName, use collectionCreationTime on UI to
- // show name
logger.info("creating album for sharing files");
final EnteFile fileWithMinCreationTime = files.reduce(
(a, b) => (a.creationTime ?? 0) < (b.creationTime ?? 0) ? a : b,
@@ -165,7 +162,6 @@ class CollectionActions {
return null;
}
- // removeParticipant remove the user from a share album
Future<bool> removeParticipant(
BuildContext context,
Collection collection,
@@ -239,8 +235,6 @@ class CollectionActions {
await showGenericErrorDialog(context: context, error: e);
return false;
}
- // getPublicKey can return null when no user is associated with given
- // email id
if (publicKey == null || publicKey == '') {
// todo: neeraj replace this as per the design where a new screen
// is used for error. Do this change along with handling of network errors
@@ -252,7 +246,6 @@ class CollectionActions {
}
}
- // addEmailToCollection returns true if add operation was successful
Future<bool> addEmailToCollection(
BuildContext context,
Collection collection,
@@ -296,8 +289,6 @@ class CollectionActions {
await showGenericErrorDialog(context: context, error: e);
return false;
}
- // getPublicKey can return null when no user is associated with given
- // email id
if (publicKey == null || publicKey == '') {
// todo: neeraj replace this as per the design where a new screen
// is used for error. Do this change along with handling of network errors
@@ -382,7 +373,6 @@ class CollectionActions {
);
}
- // deleteCollectionSheet returns true if the album is successfully deleted
Future<bool> deleteCollectionSheet(
BuildContext bContext,
Collection collection,
@@ -525,7 +515,6 @@ class CollectionActions {
files,
isHidden: collection.isHidden() && !collection.isDefaultHidden(),
);
- // collection should be empty on server now
await collectionsService.trashEmptyCollection(collection);
}
@@ -549,8 +538,6 @@ class CollectionActions {
}
}
- // _confirmSharedAlbumDeletion should be shown when user tries to delete an
- // album shared with other ente users.
Future<bool> _confirmSharedAlbumDeletion(
BuildContext context,
Collection collection,
@@ -634,13 +621,7 @@ class CollectionActions {
return;
}
- // pendingAssignMap keeps a track of files which are yet to be assigned to
- // to destination collection.
final Map<int, EnteFile> pendingAssignMap = {};
- // destCollectionToFilesMap contains the destination collection and
- // files entry which needs to be moved in destination.
- // After the end of mapping logic, the number of files entries in
- // pendingAssignMap should be equal to files in destCollectionToFilesMap
final Map<int, List<EnteFile>> destCollectionToFilesMap = {};
final List<int> uploadedIDs = [];
for (EnteFile f in split.ownedByCurrentUser) {
@@ -676,10 +657,7 @@ class CollectionActions {
continue;
}
final targetCollection = collectionsService.getCollectionByID(entry.key)!;
- // for each file which already exist in the destination collection
- // add entries in the moveDestCollectionToFiles map
for (EnteFile file in entry.value) {
- // Check if the uploaded file is still waiting to be mapped
if (pendingAssignMap.containsKey(file.uploadedFileID)) {
if (!destCollectionToFilesMap.containsKey(targetCollection.id)) {
destCollectionToFilesMap[targetCollection.id] = <EnteFile>[];
@@ -691,7 +669,6 @@ class CollectionActions {
}
}
}
- // Move the remaining files to uncategorized collection
if (pendingAssignMap.isNotEmpty) {
late final int toCollectionID;
if (isHidden) {
@@ -715,7 +692,6 @@ class CollectionActions {
}
}
- // Verify that all files are mapped.
int mappedFilesCount = 0;
destCollectionToFilesMap.forEach((key, value) {
mappedFilesCount += value.length;
@@ -746,11 +722,6 @@ class CollectionActions {
}
}
- // This method returns true if the given destination collection is a good
- // target to moving files during file remove or delete collection but keey
- // photos action. Uncategorized or favorite type of collections are not
- // good auto-move candidates. Uncategorized will be fall back for all files
- // which could not be mapped to a potential target collection
bool _isAutoMoveCandidate(int fromCollectionID, toCollectionID, int userID) {
if (fromCollectionID == toCollectionID) {
return false;
@@ -758,8 +729,6 @@ class CollectionActions {
final Collection? targetCollection = collectionsService.getCollectionByID(
toCollectionID,
);
- // ignore non-cached, deleted, uncategorized and favorite collections,
- // and collections ignored by others
if (targetCollection == null ||
targetCollection.isDeleted ||
(CollectionType.uncategorized == targetCollection.type ||
@@ -783,7 +752,6 @@ class CollectionActions {
shouldSurfaceExecutionStates: true,
labelText: context.strings.subscribe,
onTap: () async {
- // for quickLink collection, we need to trash the collection
Navigator.of(context)
.push(
MaterialPageRoute(
diff --git a/mobile/apps/photos/lib/ui/collections/album/vertical_list.dart b/mobile/apps/photos/lib/ui/collections/album/vertical_list.dart
index fc5dd50749..d29ea99910 100644
--- a/mobile/apps/photos/lib/ui/collections/album/vertical_list.dart
+++ b/mobile/apps/photos/lib/ui/collections/album/vertical_list.dart
@@ -95,14 +95,6 @@ class _AlbumVerticalListWidgetState extends State<AlbumVerticalListWidget> {
return const EmptyState();
}
- // Calculate item count:
- // - Create new album (optional)
- // - Recent header (if recent collections exist)
- // - Recent collections
- // - Divider (if recent collections exist and regular collections exist)
- // - All collections
- // - Shared header (if shared collections exist)
- // - Shared collections
final createAlbumOffset = widget.shouldShowCreateAlbum ? 1 : 0;
final recentHeaderOffset = hasRecentCollections ? 1 : 0;
final recentItemsCount = widget.recentCollections.length;
@@ -123,19 +115,16 @@ class _AlbumVerticalListWidgetState extends State<AlbumVerticalListWidget> {
return ListView.separated(
controller: widget.scrollController,
itemBuilder: (context, index) {
- // Create new album button
if (index == 0 && widget.shouldShowCreateAlbum) {
return _getNewAlbumWidget(context, filesCount);
}
final adjustedIndex = index - createAlbumOffset;
- // Recent header
if (hasRecentCollections && adjustedIndex == 0) {
return _buildSectionHeader(context, context.strings.recent);
}
- // Recent collections
final recentStartIndex = recentHeaderOffset;
if (hasRecentCollections &&
adjustedIndex >= recentStartIndex &&
@@ -145,13 +134,11 @@ class _AlbumVerticalListWidgetState extends State<AlbumVerticalListWidget> {
return _buildCollectionItem(context, item);
}
- // Divider between recent and regular collections
final dividerIndex = recentStartIndex + recentItemsCount;
if (showDivider && adjustedIndex == dividerIndex) {
return _buildDivider(context);
}
- // Regular collections
final collectionsStartIndex =
recentStartIndex + recentItemsCount + dividerOffset;
final collectionsEndIndex =
@@ -163,13 +150,11 @@ class _AlbumVerticalListWidgetState extends State<AlbumVerticalListWidget> {
return _buildCollectionItem(context, item);
}
- // Shared header
final sharedHeaderIndex = collectionsEndIndex;
if (hasSharedCollections && adjustedIndex == sharedHeaderIndex) {
return _buildSectionHeader(context, "Shared with you");
}
- // Shared collections
final sharedStartIndex = sharedHeaderIndex + sharedHeaderOffset;
if (hasSharedCollections && adjustedIndex >= sharedStartIndex) {
final sharedIndex = adjustedIndex - sharedStartIndex;
diff --git a/mobile/apps/photos/lib/ui/collections/collection_action_sheet.dart b/mobile/apps/photos/lib/ui/collections/collection_action_sheet.dart
index 5c984e39aa..bb09699e68 100644
--- a/mobile/apps/photos/lib/ui/collections/collection_action_sheet.dart
+++ b/mobile/apps/photos/lib/ui/collections/collection_action_sheet.dart
@@ -298,7 +298,6 @@ class _CollectionActionSheetState extends State<CollectionActionSheet> {
future: _getCollections(),
builder: (context, snapshot) {
if (snapshot.hasError) {
- //Need to show an error on the UI here
return const SizedBox.shrink();
} else if (snapshot.hasData) {
final collections = snapshot.data as List<Collection>;
@@ -306,23 +305,19 @@ class _CollectionActionSheetState extends State<CollectionActionSheet> {
final shouldShowCreateAlbum =
widget.showOptionToCreateNewAlbum && _searchQuery.isEmpty;
- // Get recently used collections (only when not searching)
List<Collection> recentCollections = [];
if (_searchQuery.isEmpty && !_showOnlyHiddenCollections) {
recentCollections = CollectionsService.instance
.getRecentlyUsedCollections()
.where((c) => !c.isQuickLinkCollection())
.toList();
- // Remove recent collections from the main list to avoid duplicates
final recentIds = recentCollections.map((c) => c.id).toSet();
collections.removeWhere((c) => recentIds.contains(c.id));
}
- // Get shared collections for move action
List<Collection> sharedCollections = [];
if (widget.actionType == CollectionActionType.moveFiles) {
sharedCollections = _getSharedCollections();
- // Filter shared collections by search query
if (_searchQuery.isNotEmpty) {
sharedCollections = sharedCollections
.where(
@@ -389,12 +384,10 @@ class _CollectionActionSheetState extends State<CollectionActionSheet> {
List<Collection> _getSharedCollections() {
final userID = Configuration.instance.getUserID()!;
- // Get collections where user is collaborator/admin (can add files)
final allCollections = CollectionsService.instance.getCollectionsForUI(
includeCollab: true,
includeUncategorized: false,
);
- // Filter to only non-owner collections (incoming shared albums)
final sharedCollections = allCollections
.where(
(c) =>
@@ -451,7 +444,6 @@ class _CollectionActionSheetState extends State<CollectionActionSheet> {
final List<Collection> unpinned = [];
final List<Collection> recentlyCreated = [];
final userID = Configuration.instance.getUserID()!;
- // show uncategorized collection only for restore files action
Collection? uncategorized;
for (final collection in collections) {
if (collection.isQuickLinkCollection() ||
diff --git a/mobile/apps/photos/lib/ui/collections/flex_grid_view.dart b/mobile/apps/photos/lib/ui/collections/flex_grid_view.dart
index b7b57022d3..38bcdf45ec 100644
--- a/mobile/apps/photos/lib/ui/collections/flex_grid_view.dart
+++ b/mobile/apps/photos/lib/ui/collections/flex_grid_view.dart
@@ -57,16 +57,10 @@ typedef AlbumSelectionCallbacks = ({
});
class CollectionsFlexiGridViewWidget extends StatefulWidget {
- /*
- Aspect ratio 1:1
- Width changes dynamically with screen width
- */
-
static const maxThumbnailWidth = 224.0;
static const _thumbnailToTextSpacing = 8.0;
final List<Collection>? collections;
- // If true, the GridView will shrink-wrap its contents.
final bool shrinkWrap;
final String tag;
diff --git a/mobile/apps/photos/lib/ui/viewer/actions/album_selection_action_widget.dart b/mobile/apps/photos/lib/ui/viewer/actions/album_selection_action_widget.dart
index 2b8b54e714..24047d45f1 100644
--- a/mobile/apps/photos/lib/ui/viewer/actions/album_selection_action_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/actions/album_selection_action_widget.dart
@@ -115,7 +115,6 @@ class _AlbumSelectionActionWidgetState
}
if (widget.sectionType == UISectionType.archivedCollections) {
- // For archived albums: show unarchive and delete
items.add(
SelectionActionButton(
labelText: context.strings.unarchive,
@@ -132,7 +131,6 @@ class _AlbumSelectionActionWidgetState
),
);
} else if (widget.sectionType == UISectionType.hiddenCollections) {
- // For hidden albums: show unhide and delete
items.add(
SelectionActionButton(
labelText: context.strings.unhide,
@@ -159,8 +157,6 @@ class _AlbumSelectionActionWidgetState
}
if (widget.sectionType == UISectionType.incomingCollections) {
- // Pin/Unpin options for incoming collections (uses sharee metadata)
- // Behind feature flag
if (flagService.enableShareePin) {
final hasShareePinnedAlbum = widget.selectedAlbums.albums.any(
(album) => album.hasShareePinned(),
@@ -188,7 +184,6 @@ class _AlbumSelectionActionWidgetState
);
}
- // Hide option for incoming collections (uses sharee metadata)
items.add(
SelectionActionButton(
labelText: context.strings.hide,
@@ -363,7 +358,6 @@ class _AlbumSelectionActionWidgetState
return;
}
- // Determine if we're hiding or unhiding based on first collection
final isUnhiding = collections.first.isHidden();
if (!await prepareSharedAlbumsForHiding(
context,
@@ -436,7 +430,6 @@ class _AlbumSelectionActionWidgetState
return;
}
- // Determine if we're archiving or unarchiving based on first collection
final isUnarchiving =
widget.sectionType == UISectionType.incomingCollections
? collections.first.hasShareeArchived()
diff --git a/mobile/apps/photos/lib/ui/viewer/actions/delete_empty_albums.dart b/mobile/apps/photos/lib/ui/viewer/actions/delete_empty_albums.dart
index 4019409c5c..74c0c5c4b3 100644
--- a/mobile/apps/photos/lib/ui/viewer/actions/delete_empty_albums.dart
+++ b/mobile/apps/photos/lib/ui/viewer/actions/delete_empty_albums.dart
@@ -99,7 +99,6 @@ class _DeleteEmptyAlbumsState extends State<DeleteEmptyAlbums> {
final idToFileTimeStamp = await FilesDB.instance
.getCollectionIDToMaxCreationTime();
- // remove collections which are not empty or can't be deleted
collections.removeWhere(
(c) => !c.type.canDelete || idToFileTimeStamp.containsKey(c.id),
);
diff --git a/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart b/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart
index 02e51e47a3..4fd2f70c2b 100644
--- a/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart
@@ -80,9 +80,7 @@ class _FileSelectionActionsWidgetState
late FilesSplit split;
late CollectionActions collectionActions;
late bool isCollectionOwner;
- // _cachedCollectionForSharedLink is primarily used to avoid creating duplicate
- // links if user keeps on creating Create link button after selecting
- // few files. This link is reset on any selection changed;
+ // Reuse the link while the selection is unchanged.
Collection? _cachedCollectionForSharedLink;
final GlobalKey shareButtonKey = GlobalKey();
final GlobalKey sendLinkButtonKey = GlobalKey();
@@ -98,7 +96,6 @@ class _FileSelectionActionsWidgetState
@override
void initState() {
super.initState();
- //User ID will be null if the user is not logged in (links-in-app)
currentUserID = Configuration.instance.getUserID() ?? -1;
split = FilesSplit.split(<EnteFile>[], currentUserID);
@@ -164,9 +161,7 @@ class _FileSelectionActionsWidgetState
isCollectionOwnerOrAdmin &&
split.ownedByOtherUsers.isNotEmpty;
- //To animate adding and removing of [SelectedActionButton], add all items
- //and set [shouldShow] to false for items that should not be shown and true
- //for items that should be shown.
+ // Hidden items remain in the list so their removal can animate.
final List<SelectionActionButton> items = [];
if (widget.type == GalleryType.trash) {
items.add(
@@ -571,7 +566,6 @@ class _FileSelectionActionsWidgetState
topControl: Stack(
alignment: Alignment.bottomCenter,
children: [
- // This container is for increasing the tap area
Container(
width: double.infinity,
height: 36,
diff --git a/mobile/apps/photos/lib/ui/viewer/actions/file_selection_overlay_bar.dart b/mobile/apps/photos/lib/ui/viewer/actions/file_selection_overlay_bar.dart
index bba9d0f862..8e218949ca 100644
--- a/mobile/apps/photos/lib/ui/viewer/actions/file_selection_overlay_bar.dart
+++ b/mobile/apps/photos/lib/ui/viewer/actions/file_selection_overlay_bar.dart
@@ -113,20 +113,16 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar>
return _galleryType == GalleryType.homepage
? _body()
: PopScope(
- // iOS pop gesture get's blocked if we do canPop false, so always pop on iOS
+ // canPop=false disables iOS's back gesture.
canPop: Platform.isIOS,
onPopInvokedWithResult: (didPop, _) {
- // for iOS return and don't run anything
if (didPop) return;
- // Android specific block
- // if nothing is selected then pop the page
if (widget.selectedFiles.files.isEmpty) {
Navigator.of(context).pop();
return;
}
- // clear all selections if something is selected
widget.selectedFiles.clearAll();
},
child: _body(),
@@ -185,13 +181,10 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar>
}
void _boundaryUpdateListener() {
- // Update boundary after animation completes
Future.delayed(_FileSelectionOverlayBarState.animationDuration, () {
final isEmpty = widget.selectedFiles.files.isEmpty;
- // Only report boundary on empty ↔ non-empty transitions
if (_wasEmpty != isEmpty) {
- // Report boundary - will set to null if widget is not visible
reportBoundary(BoundaryPosition.bottom);
_wasEmpty = isEmpty;
}
@@ -203,12 +196,7 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar>
_updateGalleryTypeIfRequired();
}
- /// This method is used to update the GalleryType if the initial filter is
- /// removed from the applied filters. As long as the inital filter is present
- /// in the applied filters, the gallery type will remain the same as the type
- /// initally passed in the widget constructor. Once the inital filter is
- /// removed, the gallery type will be updated to GalleryType.searchResults
- /// and never be updated again.
+ // Once the initial filter is removed, this remains a search-results gallery.
void _updateGalleryTypeIfRequired() {
if (_galleryInitialFilterStillApplied != null &&
!_galleryInitialFilterStillApplied!) {
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.dart
index f861a182ab..888cf88ad1 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
@@ -132,8 +132,7 @@ class _NativeVideoProgressControlsState
}
void _startMovingSeekbar() {
- //Video starts playing after a slight delay. This delay is to ensure that
- //the seek bar animation starts after the video starts playing.
+ // Start the seek animation after delayed video playback begins.
Future.delayed(const Duration(milliseconds: 700), () {
if (!mounted) {
return;
@@ -177,9 +176,7 @@ class _NativeVideoProgressControlsState
}
final target = widget.controller.playbackPosition.inMilliseconds;
- //There is a slight delay (around 350 ms) for the event being listened to
- //by this listener on the next target (target that comes after 0). Adding
- //this buffer to keep the seek bar animation smooth.
+ // The position event after zero arrives about 350 ms late.
if (target == 0) {
await Future.delayed(const Duration(milliseconds: 450));
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/inline_text_detection.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/inline_text_detection.dart
index fc10a036f1..6d42bd9d79 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/inline_text_detection.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/inline_text_detection.dart
@@ -22,7 +22,6 @@ import "package:photos/ui/viewer/file/ocr/text_detector_widget.dart";
import "package:photos/ui/viewer/file/ocr/text_region_hit_test.dart";
import "package:photos/utils/image_util.dart";
-/// Routes still-photo gestures from the viewer to its OCR overlay.
class InlineTextDetectionController {
_InlineTextDetectionState? _state;
@@ -41,11 +40,8 @@ class InlineTextDetectionController {
}
}
-/// Inline on-demand text selection for the photo viewer.
-///
-/// Still images use long press as the signal to start recognition. Live and
-/// motion photos precompute detector-only regions so a long press on text
-/// starts selection, while a long press elsewhere continues to play video.
+// Live and motion photos detect text regions first. A long press on text starts
+// selection; a long press elsewhere plays the motion video.
class InlineTextDetection extends StatefulWidget {
final EnteFile file;
final InlineTextDetectionController controller;
@@ -789,11 +785,8 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
return ValueListenableBuilder<ZoomTransform>(
valueListenable: zoomTransformNotifier,
builder: (context, transform, _) {
- // Only reset the debounce when the transform has genuinely changed.
- // Guarding on value change prevents the setState rebuild from the
- // timer itself from re-entering this block and restarting the timer,
- // which would create an infinite loop where _zoomGestureSettled
- // can never stay true.
+ // setState rebuilds this builder. Restarting the timer unless the
+ // transform changed would prevent zoom from ever settling.
if (isZoomed && transform != _lastSeenTransform) {
_lastSeenTransform = transform;
_zoomGestureSettled = false;
@@ -814,13 +807,8 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
uiOffset: transform.offset,
);
- // Always apply the Transform, even when not zoomed.
- // When not zoomed, transform == ZoomTransform.identity (scale=1,
- // offset=zero), so this is a no-op visually. Applying it
- // unconditionally means teardrops and text boundaries immediately
- // track zoom from the very first stream event, with no flash at
- // the unscaled position that occurs when the Transform was only
- // added after isZoomedNotifier fired.
+ // Apply the identity transform too so the overlay follows the first
+ // zoom event instead of briefly remaining at its old position.
overlay = Transform(
alignment: Alignment.center,
transform: Matrix4.identity()
@@ -839,9 +827,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
child: overlay,
);
- // Ignore pointer events when:
- // - Actively pinching (2+ fingers down) β€” let PhotoView handle zoom
- // - Zoomed but gesture not yet settled β€” transform is still changing
+ // Let PhotoView own gestures while pinching or settling a zoom.
final shouldIgnore =
_isPinching || (isZoomed && !_zoomGestureSettled);
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/ocr_dot_wave_overlay.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/ocr_dot_wave_overlay.dart
index c76285cbe3..6f9abe560e 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/ocr_dot_wave_overlay.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/ocr_dot_wave_overlay.dart
@@ -1,6 +1,5 @@
import "package:flutter/material.dart";
-/// White dot grid that pulses in a radial wave from center outward.
class OcrDotWaveOverlay extends StatefulWidget {
final Color backgroundColor;
final Color dotColor;
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart
index e6b62c7700..1c2dd46b33 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart
@@ -11,7 +11,6 @@ import 'package:photos/ui/viewer/file/ocr/text_overlay_widget.dart';
const double _enteSelectionHighlightOpacity = 0.28;
-/// Controller that surfaces imperative actions for [TextDetectorWidget].
class TextDetectorController extends ChangeNotifier {
_TextDetectorWidgetState? _state;
@@ -36,13 +35,8 @@ class TextDetectorController extends ChangeNotifier {
notifyListeners();
}
- /// Whether text detection is currently running.
bool get isProcessing => _state?._isProcessing ?? false;
-
- /// Indicates if there is text that can be selected.
bool get hasSelectableText => _state?._hasSelectableText ?? false;
-
- /// Whether the user has explicitly interacted (e.g. long press).
bool get userAttemptedInteraction =>
_state?._userAttemptedInteraction ?? false;
@@ -69,7 +63,6 @@ class TextDetectorController extends ChangeNotifier {
}
}
-/// Detects text and renders the Photos OCR selection overlay.
class TextDetectorWidget extends StatefulWidget {
final String imagePath;
final VoidCallback? onTextCopied;
@@ -258,7 +251,6 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
try {
await _ensureModelsReady();
if (_errorMessage != null) {
- // Model-prep error; the finally block rebuilds to show the banner.
return;
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart
index 415db7ff7c..4e1844a40e 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart
@@ -18,7 +18,6 @@ const double _kHighlightVerticalPadding = 1.6;
const double _kHighlightCornerRadius = 4.0;
const double _kHighlightLineToleranceFactor = 0.7;
-/// Controller that surfaces imperative actions for [TextOverlayWidget].
class TextOverlayController {
_TextOverlayWidgetState? _state;
@@ -34,8 +33,6 @@ class TextOverlayController {
bool get hasActiveSelection => _state?._hasActiveSelection ?? false;
- /// Queue a position to auto-select when the overlay is ready.
- /// The selection happens after block visuals are computed.
Offset? _pendingAutoSelectPosition;
void selectTextAtPosition(Offset globalPosition) {
@@ -43,7 +40,6 @@ class TextOverlayController {
if (state != null && state._blockVisuals.isNotEmpty) {
state._selectTextAtGlobalPosition(globalPosition);
} else {
- // Block visuals aren't ready yet; store for later.
_pendingAutoSelectPosition = globalPosition;
}
}
@@ -72,7 +68,6 @@ class TextOverlayController {
}
}
-/// Renders selectable OCR text over the image displayed by the Photos viewer.
class TextOverlayWidget extends StatefulWidget {
final Size imageSize;
final List<TextBlock> textBlocks;
@@ -193,9 +188,8 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
_scheduleMetricsRebuild(constraints);
final Widget? copyButton = _buildCopyHandleButton(constraints);
- // All visual content shares the same KeyedSubtree so coordinates
- // are consistent. Text boundaries are in IgnorePointer; selection
- // handles and copy button are outside it so they can be touched.
+ // Keep all visuals in one coordinate space. Text ignores pointers;
+ // handles and the copy button remain interactive.
final Widget visualLayer = KeyedSubtree(
key: _overlayCoordinateKey,
child: Stack(
@@ -214,9 +208,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
),
);
- // Gesture layer: only intercepts touches on text regions
- // or selection handles. Uses a custom RenderBox that returns
- // false from hitTest unless the position passes the check.
final Widget gestureLayer = _TextRegionHitTestBox(
hitTest: _isPositionOnGestureLayer,
child: RawGestureDetector(
@@ -1955,8 +1946,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
return true;
}
- /// Select the word at [globalPosition] if there is text there.
- /// Falls back to the nearest text block if the exact position has no text.
bool _selectTextAtGlobalPosition(Offset globalPosition) {
final scenePoint = _sceneFromGlobal(globalPosition);
if (scenePoint == null) {
@@ -2486,10 +2475,7 @@ class _EditableBlockPainter extends CustomPainter {
}
}
-/// A [SingleChildRenderObjectWidget] whose render object only reports a hit
-/// when the touch position passes the provided [hitTest] callback. This lets
-/// the overlay be invisible to Flutter's hit-test tree for most of the screen
-/// area, so the underlying PageView / PhotoView receives swipes and taps.
+// Reject hits outside text so PageView and PhotoView receive the gesture.
class _TextRegionHitTestBox extends SingleChildRenderObjectWidget {
final bool Function(Offset globalPosition) hitTest;
@@ -2524,9 +2510,7 @@ class _RenderTextRegionHitTestBox extends RenderProxyBox {
}
}
-/// A [LongPressGestureRecognizer] that only accepts when the press
-/// position is on a text region. If not on text, it rejects so that
-/// competing recognizers (e.g. motion photo playback) can win.
+// Reject long presses outside text so motion-photo playback can win.
class _TextRegionLongPressRecognizer extends LongPressGestureRecognizer {
bool Function(Offset globalPosition) hitTestBlock;
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_reading_order.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_reading_order.dart
index 5f33be2d53..ef874c93f0 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_reading_order.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_reading_order.dart
@@ -14,12 +14,8 @@ class TextReadingOrderBlock {
final String text;
}
-/// Orders OCR blocks in visual reading order.
-///
-/// When blocks form overlapping vertical columns, each column is read from
-/// top to bottom before advancing horizontally. Blocks spanning most of the
-/// page width split the columns into vertical bands, which keeps headings and
-/// footers in their expected positions.
+// Read each column top to bottom. Wide headings and footers split columns into
+// vertical bands.
List<int> orderTextBlocksForReading(Iterable<TextReadingOrderBlock> source) {
final blocks = source
.where((block) => block.bounds.width > 0 && block.bounds.height > 0)
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_face_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_face_widget.dart
index 081dc39d57..8f438d148b 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_face_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_face_widget.dart
@@ -273,8 +273,7 @@ class _FileInfoFaceWidgetState extends State<FileInfoFaceWidget> {
return;
}
if (widget.face.score <= kMinimumQualityFaceScore) {
- // The face score is too low for automatic clustering,
- // assigning a manual new clusterID so that the user can cluster it manually
+ // Low-quality faces need their own cluster before manual assignment.
final String clusterID = newClusterID();
await mlDataDB.updateFaceIdToClusterId({widget.face.faceID: clusterID});
if (!mounted) return;
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_faces_item_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_faces_item_widget.dart
index 2bd244c134..b352b2dc2f 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_faces_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_faces_item_widget.dart
@@ -161,7 +161,6 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
Widget _buildPeopleGrid(double thumbnailWidth) {
final children = <Widget>[];
- // Add manual person widgets first
for (final person in _manualPersons) {
children.add(
_ManualPersonTag(
@@ -175,7 +174,6 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
);
}
- // Add face widgets
for (final faceInfo in _defaultFaces) {
children.add(
FileInfoFaceWidget(
@@ -195,7 +193,6 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
);
}
- // Add "Add person" button at the end
if (!isLocalGalleryMode &&
flagService.manualTagFileToPerson &&
widget.file.uploadedFileID != null) {
@@ -217,7 +214,6 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
) async {
final faceInfoList = <_FaceInfo>[];
- // Build person mapping for sorting
final faceIdToPersonID = <String, String>{};
for (final face in faces) {
final clusterID = faceIdsToClusterIds[face.faceID];
@@ -229,7 +225,6 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
}
}
- // Sort faces: named first, then by score, hidden last
faces.sort((a, b) {
final aPersonID = faceIdToPersonID[a.faceID];
final bPersonID = faceIdToPersonID[b.faceID];
@@ -243,7 +238,6 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
return b.score.compareTo(a.score);
});
- // Create face info objects
for (final face in faces) {
final faceCrop = faceCrops[face.faceID];
if (faceCrop == null) {
@@ -641,8 +635,7 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
fileKey = widget.file.uploadedFileID!;
}
- // Fetch persons map early so we can check for manual assignments
- // even when no faces are detected
+ // Manual assignments can exist even when no faces were detected.
final persons = isLocalGallery
? <String, PersonEntity>{}
: await PersonService.instance.getPersonsMap();
@@ -666,7 +659,6 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
);
}
- // Get additional data
final faceIdsToClusterIds = await mlDataDB.getFaceIdsToClusterIds(
faces.map((face) => face.faceID).toList(),
);
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
index 4b555db3c7..55ed644c66 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
@@ -67,9 +67,8 @@ class _PetsItemWidgetState extends State<PetsItemWidget> {
return;
}
- // Convert DBPetFace to Face objects for crop generation.
- // The detection JSON stores box as [xMin, yMin, xMax, yMax] (xyxy),
- // so we parse it into FaceBox(x, y, width, height) manually.
+ // Stored pet boxes are [xMin, yMin, xMax, yMax], while FaceBox takes
+ // [x, y, width, height].
final faces = <Face>[];
for (final dbPetFace in dbPetFaces) {
final json = jsonDecode(dbPetFace.detection) as Map<String, dynamic>;
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/file_properties_item_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_properties_item_widget.dart
index faf147f6a3..d21b60359b 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/file_properties_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_properties_item_widget.dart
@@ -69,10 +69,7 @@ class _FilePropertiesItemWidgetState extends State<FilePropertiesItemWidget> {
width = widget.file.width;
height = widget.file.height;
} else if (widget.isImage) {
- // No saved public dimensions (local-only / not-yet-backed-up / removed
- // from Ente). Derive from the actual current local file bytes so we show
- // the real rendered size instead of the (often stale) EXIF tag. Uses the
- // non-origin file (asset.file on iOS = the current rendered image).
+ // EXIF dimensions can be stale after edits. Read the current local file.
try {
final localFile = await getFile(widget.file);
final decoded = localFile != null
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/location_tags_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/location_tags_widget.dart
index 924e03d03f..c84d906f84 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/location_tags_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/location_tags_widget.dart
@@ -101,7 +101,6 @@ class _LocationTagsWidgetState extends State<LocationTagsWidget> {
}
Future<List<Widget>> _getLocationTags() async {
- // await Future.delayed(const Duration(seconds: 1));
final locationTags = await locationService.enclosingLocationTags(
widget.file.location!,
);
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/preview_properties_item_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/preview_properties_item_widget.dart
index 51d4d686ad..93d97b1a76 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/preview_properties_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/preview_properties_item_widget.dart
@@ -70,7 +70,6 @@ class _PreviewPropertiesItemWidgetState
if ((widget.file.fileType == FileType.video) &&
(widget.file.localID != null || widget.file.duration != 0) &&
data.size != null) {
- // show bitrate, i.e. size * 8 / duration formatted
final result = FFProbeProps.formatBitrate(
data.size! * 8 / widget.file.duration!,
"b/s",
diff --git a/mobile/apps/photos/lib/ui/viewer/location/add_location_sheet.dart b/mobile/apps/photos/lib/ui/viewer/location/add_location_sheet.dart
index 70f7514da1..dff8b44a3c 100644
--- a/mobile/apps/photos/lib/ui/viewer/location/add_location_sheet.dart
+++ b/mobile/apps/photos/lib/ui/viewer/location/add_location_sheet.dart
@@ -59,12 +59,8 @@ class AddLocationSheet extends StatefulWidget {
}
class _AddLocationSheetState extends State<AddLocationSheet> {
- //The value of this notifier has no significance.
- //When memoriesCountNotifier is null, we show the loading widget in the
- //memories count section which also means the gallery is loading.
+ // null means the gallery is still loading.
final ValueNotifier<int?> _memoriesCountNotifier = ValueNotifier(null);
-
- //The value of this notifier has no significance.
final ValueNotifier<bool> _submitNotifer = ValueNotifier(false);
final ValueNotifier<bool> _cancelNotifier = ValueNotifier(false);
diff --git a/mobile/apps/photos/lib/ui/viewer/location/dynamic_location_gallery_widget.dart b/mobile/apps/photos/lib/ui/viewer/location/dynamic_location_gallery_widget.dart
index 8705a3f2e1..c13c8de4c4 100644
--- a/mobile/apps/photos/lib/ui/viewer/location/dynamic_location_gallery_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/location/dynamic_location_gallery_widget.dart
@@ -14,8 +14,6 @@ import 'package:photos/states/location_state.dart';
import "package:photos/ui/viewer/gallery/gallery.dart";
import "package:photos/ui/viewer/gallery/state/gallery_files_inherited_widget.dart";
-///This gallery will get rebuilt with the updated radius when
-///InheritedLocationTagData notifies a change in radius.
class DynamicLocationGalleryWidget extends StatefulWidget {
final ValueNotifier<int?> memoriesCountNotifier;
final String tagPrefix;
@@ -80,7 +78,6 @@ class _DynamicLocationGalleryWidgetState
}
return FutureBuilder(
- //Only rebuild Gallery if the center point or radius changes
key: ValueKey(
"${InheritedLocationTagData.of(context).centerPoint}$selectedRadius",
),
diff --git a/mobile/apps/photos/lib/ui/viewer/location/edit_location_sheet.dart b/mobile/apps/photos/lib/ui/viewer/location/edit_location_sheet.dart
index e9aad331e9..e6f16ed577 100644
--- a/mobile/apps/photos/lib/ui/viewer/location/edit_location_sheet.dart
+++ b/mobile/apps/photos/lib/ui/viewer/location/edit_location_sheet.dart
@@ -52,9 +52,7 @@ class EditLocationSheet extends StatefulWidget {
}
class _EditLocationSheetState extends State<EditLocationSheet> {
- //The value of these notifiers has no significance.
- //When memoriesCountNotifier is null, we show the loading widget in the
- //memories count section which also means the gallery is loading.
+ // null means the gallery is still loading.
final ValueNotifier<int?> _memoriesCountNotifier = ValueNotifier(null);
final ValueNotifier<bool> _submitNotifer = ValueNotifier(false);
final ValueNotifier<bool> _cancelNotifier = ValueNotifier(false);
diff --git a/mobile/apps/photos/lib/ui/viewer/location/location_screen.dart b/mobile/apps/photos/lib/ui/viewer/location/location_screen.dart
index af5163470d..4a76dd50e5 100644
--- a/mobile/apps/photos/lib/ui/viewer/location/location_screen.dart
+++ b/mobile/apps/photos/lib/ui/viewer/location/location_screen.dart
@@ -149,7 +149,6 @@ class _LocationGalleryWidgetState extends State<LocationGalleryWidget> {
);
Future<FileLoadResult> filterFiles() async {
- //waiting for allFilesWithLocation to be initialized
await fileLoadResult;
final stopWatch = Stopwatch()..start();
final filesInLocation = allFilesWithLocation;
@@ -171,7 +170,6 @@ class _LocationGalleryWidgetState extends State<LocationGalleryWidget> {
}
return FutureBuilder(
- //rebuild gallery only when there is change in radius or center point
key: ValueKey("$centerPoint$selectedRadius"),
builder: (context, snapshot) {
if (snapshot.hasData) {
diff --git a/mobile/apps/photos/lib/ui/viewer/location/pick_center_point_widget.dart b/mobile/apps/photos/lib/ui/viewer/location/pick_center_point_widget.dart
index 31cd710347..da90f00d75 100644
--- a/mobile/apps/photos/lib/ui/viewer/location/pick_center_point_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/location/pick_center_point_widget.dart
@@ -129,7 +129,7 @@ class PickCenterPointWidget extends StatelessWidget {
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 428),
child: Padding(
- //inner stroke of 1pt + 15 pts of top padding = 16 pts
+ // The 1 pixel inner stroke completes the 16 pixel inset.
padding: const EdgeInsets.fromLTRB(16, 15, 16, 8),
child: ValueListenableBuilder(
valueListenable: isFileSelected,
diff --git a/mobile/apps/photos/lib/ui/viewer/location/radius_picker_widget.dart b/mobile/apps/photos/lib/ui/viewer/location/radius_picker_widget.dart
index 96d0058164..13f5d76799 100644
--- a/mobile/apps/photos/lib/ui/viewer/location/radius_picker_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/location/radius_picker_widget.dart
@@ -23,7 +23,6 @@ class CustomTrackShape extends RoundedRectSliderTrackShape {
}
class RadiusPickerWidget extends StatefulWidget {
- ///This notifier can be listened from a parent widget to get the selected radius
final ValueNotifier<double> selectedRadiusNotifier;
const RadiusPickerWidget(this.selectedRadiusNotifier, {super.key});
@@ -155,8 +154,6 @@ class _RadiusPickerWidgetState extends State<RadiusPickerWidget> {
);
}
- //9.99 -> 10, 9.0 -> 9, 5.02 -> 5, 5.09 -> 5.1
- //12.3 -> 12, 121.65 -> 122, 999.9 -> 1000
String roundRadius(double radius) {
String result;
final roundedRadius = (radius * 10).round() / 10;
@@ -216,14 +213,12 @@ class NumberWithDecimalInputFormatter extends TextInputFormatter {
TextEditingValue oldValue,
TextEditingValue newValue,
) {
- // Check if the new value matches the pattern
if (_pattern.hasMatch(newValue.text)) {
if (newValue.text.isEmpty) {
return newValue;
}
final newValueAsDouble = double.tryParse(newValue.text);
- // Check if the new value is within the allowed range
if (newValueAsDouble != null && newValueAsDouble <= maxValue) {
return newValue;
}
diff --git a/mobile/apps/photos/lib/ui/viewer/location/update_location_data_widget.dart b/mobile/apps/photos/lib/ui/viewer/location/update_location_data_widget.dart
index c7a070cd14..246c9c303c 100644
--- a/mobile/apps/photos/lib/ui/viewer/location/update_location_data_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/location/update_location_data_widget.dart
@@ -266,7 +266,6 @@ class _UpdateLocationInfoState extends State<UpdateLocationInfo> {
top: 0,
key: bottomChildKey,
child: bottomChild,
- // top: 0,
),
Positioned(key: topChildKey, child: topChild),
],
diff --git a/mobile/apps/photos/lib/ui/viewer/people/cluster_app_bar.dart b/mobile/apps/photos/lib/ui/viewer/people/cluster_app_bar.dart
index 6460203a1a..3e0cce10c6 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/cluster_app_bar.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/cluster_app_bar.dart
@@ -129,7 +129,6 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
List<Widget> _getDefaultActions(BuildContext context) {
final iconColor = getEnteColorScheme(context).contentLight;
final List<Widget> actions = <Widget>[];
- // If the user has selected files, don't show any actions
if (widget.selectedFiles.files.isNotEmpty ||
isLocalGalleryMode ||
!Configuration.instance.hasConfiguredAccount()) {
@@ -226,14 +225,12 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
final Map<String, String> newFaceIdToClusterID =
breakupResult.newFaceIdToCluster;
- // Update to delete the old clusters and save the new clusters
await mlDataDB.deleteClusterSummary(widget.clusterID);
await MLDataDB.instance.clusterSummaryUpdate(
breakupResult.newClusterSummaries,
);
await mlDataDB.updateFaceIdToClusterId(newFaceIdToClusterID);
- // Find the biggest cluster
biggestClusterID = '';
int biggestClusterSize = 0;
for (final MapEntry<String, List<String>> clusterToFaces
@@ -243,14 +240,13 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
biggestClusterID = clusterToFaces.key;
}
}
- // Get the files for the biggest new cluster
final biggestClusterFileIDs = newClusterIDToFaceIDs[biggestClusterID]!
.map((e) => getFileIdFromFaceId<int>(e))
.toList();
biggestClusterFiles = await FilesDB.instance
.getFileIDToFileFromIDs(biggestClusterFileIDs)
.then((mapping) => mapping.values.toList());
- // Sort the files to prevent issues with the order of the files in gallery
+ // Keep the replacement gallery in newest-first order.
biggestClusterFiles.sort(
(a, b) => b.creationTime!.compareTo(a.creationTime!),
);
@@ -258,18 +254,15 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
userConfirmed = true;
} catch (e, s) {
_logger.severe('Breakup cluster failed', e, s);
- // await showGenericErrorDialog(context: context, error: e);
}
},
);
if (userConfirmed) {
Bus.instance.fire(PeopleChangedEvent());
- // Close the old cluster page
if (!context.mounted) return;
Navigator.of(context).pop();
- // Push the new cluster page
if (!context.mounted) return;
await Navigator.of(context).push(
MaterialPageRoute(
diff --git a/mobile/apps/photos/lib/ui/viewer/people/cluster_breakup_page.dart b/mobile/apps/photos/lib/ui/viewer/people/cluster_breakup_page.dart
index 9dcc722867..970194a09c 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/cluster_breakup_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/cluster_breakup_page.dart
@@ -56,9 +56,7 @@ class _ClusterBreakupPageState extends State<ClusterBreakupPage> {
child: NoThumbnailWidget(addBorder: false),
),
),
- const SizedBox(
- width: 8.0,
- ), // Add some spacing between the thumbnail and the text
+ const SizedBox(width: 8.0),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
diff --git a/mobile/apps/photos/lib/ui/viewer/people/face_thumbnail_squircle.dart b/mobile/apps/photos/lib/ui/viewer/people/face_thumbnail_squircle.dart
index 7533ac329d..5457b65217 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/face_thumbnail_squircle.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/face_thumbnail_squircle.dart
@@ -2,12 +2,8 @@ import "dart:math" as math;
import "package:flutter/widgets.dart";
-// Flutter's `RSuperellipse` clamps radii so they don't overlap, which means
-// radii > (side / 2) become circles. Historically we used an oversized radius
-// with `ContinuousRectangleBorder` to approximate the iOS squircle.
-//
-// This factor produces a similarly "squircled" look without collapsing into a
-// circle for the common square thumbnail sizes used across the app.
+// RSuperellipse radii above half the side collapse into a circle. This factor
+// preserves the previous iOS-style squircle shape.
const double _kFaceThumbnailSquircleRadiusFactor = 0.30;
const double _kFaceThumbnailSquircleMinStraightEdge = 8.0;
diff --git a/mobile/apps/photos/lib/ui/viewer/people/file_face_widget.dart b/mobile/apps/photos/lib/ui/viewer/people/file_face_widget.dart
index 74f800606b..98d7ad5544 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/file_face_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/file_face_widget.dart
@@ -17,7 +17,6 @@ final _logger = Logger("FaceWidget");
class FileFaceWidget extends StatefulWidget {
final EnteFile file;
- // Data to find the right face, in order of preference
final Uint8List? faceCrop;
final Face? face;
final String? clusterID;
@@ -25,14 +24,6 @@ class FileFaceWidget extends StatefulWidget {
final bool useFullFile;
final bool thumbnailFallback;
- /// Physical pixel width for image decoding optimization.
- ///
- /// When provided and > 0, the image will be decoded at this width, with height
- /// computed to preserve aspect ratio. This reduces memory usage for small displays.
- ///
- /// Typically calculated as: `(logicalWidth * MediaQuery.devicePixelRatioOf(context)).toInt()`
- ///
- /// If null or <= 0, the image is decoded at full resolution.
final int? cachedPixelWidth;
const FileFaceWidget(
@@ -79,9 +70,8 @@ class _FileFaceWidgetState extends State<FileFaceWidget> {
future: faceCropFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
- // Only cacheWidth (not cacheHeight) to preserve aspect ratio.
- // Face crops are typically portrait, so constraining width ensures
- // sufficient height for BoxFit.cover without upscaling.
+ // Decode by width only so portrait crops retain enough height for
+ // BoxFit.cover without upscaling.
final shouldOptimize =
widget.cachedPixelWidth != null && widget.cachedPixelWidth! > 0;
final ImageProvider imageProvider = shouldOptimize
diff --git a/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart b/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart
index 55c4996fb7..235ea2988a 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart
@@ -59,7 +59,7 @@ class _MemoryLanePageState extends State<MemoryLanePage>
static const double _cardGapUpdateTolerance = 0.5;
static const double _controlsHeightUpdateTolerance = 0.5;
static const double _controlsHeightFallback = 140;
- // Wait for this many frames (or the available total) before auto-starting playback.
+ // Wait for this many frames, or all available frames, before autoplay.
static const int _initialFrameTarget = 120;
static const int _frameBuildConcurrency = 6;
@@ -1235,8 +1235,8 @@ class _TimelineFrame {
return null;
}
return _resizedImageCache.putIfAbsent(cacheWidth, () {
- // Decode face crops with width only so BoxFit.cover can crop them
- // naturally without forcing the crop to the card's aspect ratio.
+ // Decode face crops by width only so BoxFit.cover can crop naturally
+ // without forcing the image to the card's aspect ratio.
return ResizeImage.resizeIfNeeded(cacheWidth, null, baseImage);
});
}
@@ -1279,8 +1279,6 @@ class _MemoryLaneCard extends StatelessWidget {
final scale = _calculateScale(distance);
final yOffset = _calculateYOffset(distance);
final opacity = _calculateOpacity(distance);
- // Skip the expensive ImageFiltered blur for distant cards where the
- // combination of low opacity and dark overlay already obscures detail.
final blurSigma = blurEnabled && distance < 3.0
? _calculateBlur(distance)
: 0.0;
@@ -1293,13 +1291,11 @@ class _MemoryLaneCard extends StatelessWidget {
);
final cardShadow = _shadowForCard(distance);
- // Emphasize the active card by delaying the date reveal until the card is
- // nearly centered; keeps background cards calm while the primary one lifts.
final double emphasisDistance = distance.abs();
final double activation = (1 - (emphasisDistance * 1.8)).clamp(
0.0,
1.0,
- ); // hide until near front
+ );
final double emphasis = Curves.easeOutQuad.transform(activation);
final double dateOpacity = emphasis;
final double gradientAlpha = 0.6 * emphasis;
@@ -1430,7 +1426,6 @@ class _MemoryLaneCard extends StatelessWidget {
imageAspectRatio <= 0) {
return cardWidth;
}
- // BoxFit.cover needs enough decoded height for tall portrait cards.
return math.max(cardWidth, cardHeight * imageAspectRatio);
}
@@ -1495,8 +1490,6 @@ class _MemoryLaneCard extends StatelessWidget {
if (distance <= 0) {
return 0;
}
- // Drop blur aggressively once the card is mostly in view so the hero frame
- // looks sharp as soon as it settles.
const double clearDistance = 0.15;
const double blurMultiplier = 10;
final double effective = math.max(0, distance - clearDistance);
@@ -1508,7 +1501,7 @@ class _MemoryLaneCard extends StatelessWidget {
return 0;
}
final clamped = distance.clamp(0.0, 3.0);
- const double base = 0.035; // ~2 degrees
+ const double base = 0.035;
final falloff = math.max(0.2, 1 - clamped * 0.18);
return base * clamped * falloff;
}
@@ -1535,7 +1528,6 @@ class _MemoryLaneCard extends StatelessWidget {
const double reachDistance = 3.0;
final double normalized = (distance / reachDistance).clamp(0.0, 1.0);
final double eased = Curves.easeOutCubic.transform(normalized);
- // Fade the lift overlay much earlier so the card looks settled sooner.
return overlayMax * eased;
}
}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/people_app_bar.dart b/mobile/apps/photos/lib/ui/viewer/people/people_app_bar.dart
index de6b135ef5..ce2a783bb3 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/people_app_bar.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/people_app_bar.dart
@@ -275,7 +275,6 @@ class _AppBarWidgetState extends State<PeopleAppBar> {
final bool hideFromMemories = person.data.hideFromMemories;
final bool hasAssignedCluster = person.data.assigned.isNotEmpty;
final List<Widget> actions = <Widget>[];
- // If the user has selected files, don't show any actions
if (widget.selectedFiles.files.isNotEmpty ||
!Configuration.instance.hasConfiguredAccount()) {
return actions;
diff --git a/mobile/apps/photos/lib/ui/viewer/people/person_cluster_suggestion.dart b/mobile/apps/photos/lib/ui/viewer/people/person_cluster_suggestion.dart
index 62526fea7c..560b2919f0 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/person_cluster_suggestion.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/person_cluster_suggestion.dart
@@ -49,14 +49,12 @@ class _PersonClustersState extends State<PersonReviewClusterSuggestion> {
late final Logger _logger = Logger('_PersonClustersState');
late final mlDataDB = MLDataDB.instance;
- // Declare a variable for the future
late Future<List<ClusterSuggestion>> futureClusterSuggestions;
StreamSubscription<PeopleChangedEvent>? _peopleChangedEvent;
@override
void initState() {
super.initState();
- // Initialize the future in initState
_fetchClusterSuggestions();
}
@@ -277,11 +275,9 @@ class _PersonClustersState extends State<PersonReviewClusterSuggestion> {
bool yesOrNo,
int numberOfSuggestions,
) async {
- // Perform the action based on clusterID, e.g., assignClusterToPerson or captureNotPersonFeedback
if (!canGiveFeedback) {
return;
}
- // Store the feedback in case the user wants to revert
pastUserFeedback.add(
SuggestionUserFeedback(yesOrNo, allSuggestions[currentSuggestionIndex]),
);
@@ -292,17 +288,14 @@ class _PersonClustersState extends State<PersonReviewClusterSuggestion> {
clusterID: clusterID,
);
_notifySuggestionReviewed();
- // Increment the suggestion index
if (mounted) {
setState(() => currentSuggestionIndex++);
}
- // Check if we need to fetch new data
if (currentSuggestionIndex >= (numberOfSuggestions)) {
setState(() {
currentSuggestionIndex = 0;
- futureBuilderKeySuggestions =
- UniqueKey(); // Reset to trigger FutureBuilder
+ futureBuilderKeySuggestions = UniqueKey();
futureBuilderKeyFaceThumbnails = UniqueKey();
_fetchClusterSuggestions();
});
@@ -325,11 +318,9 @@ class _PersonClustersState extends State<PersonReviewClusterSuggestion> {
clusterID: clusterID,
);
_notifySuggestionReviewed();
- // Recalculate the suggestions when a suggestion is rejected
setState(() {
currentSuggestionIndex = 0;
- futureBuilderKeySuggestions =
- UniqueKey(); // Reset to trigger FutureBuilder
+ futureBuilderKeySuggestions = UniqueKey();
futureBuilderKeyFaceThumbnails = UniqueKey();
_fetchClusterSuggestions();
});
@@ -387,7 +378,6 @@ class _PersonClustersState extends State<PersonReviewClusterSuggestion> {
}
}
- // Method to fetch cluster suggestions
void _fetchClusterSuggestions() {
debugPrint("Fetching suggestions for ${widget.person.data.name}");
futureClusterSuggestions = ClusterFeedbackService.instance
@@ -419,7 +409,6 @@ class _PersonClustersState extends State<PersonReviewClusterSuggestion> {
const SizedBox(height: 24.0),
],
);
- // Precompute face thumbnails for next suggestions, in case there are
precomputeFaceCrops();
return widgetToReturn;
}
@@ -460,7 +449,6 @@ class _PersonClustersState extends State<PersonReviewClusterSuggestion> {
],
);
} else if (snapshot.hasError) {
- // log the error
return Center(child: Text(context.strings.error));
} else {
canGiveFeedback = false;
diff --git a/mobile/apps/photos/lib/ui/viewer/people/person_clusters_page.dart b/mobile/apps/photos/lib/ui/viewer/people/person_clusters_page.dart
index e968c7346b..82bb2849cd 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/person_clusters_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/person_clusters_page.dart
@@ -39,7 +39,6 @@ class _PersonClustersPageState extends State<PersonClustersPage> {
if (snapshot.hasData) {
final clusters = snapshot.data!;
final List<String> keys = clusters.keys.toList();
- // Sort the clusters by the number of files in each cluster, largest first
keys.sort(
(b, a) => clusters[a]!.length.compareTo(clusters[b]!.length),
);
@@ -74,9 +73,7 @@ class _PersonClustersPageState extends State<PersonClustersPage> {
: const NoThumbnailWidget(addBorder: false),
),
),
- const SizedBox(
- width: 8.0,
- ), // Add some spacing between the thumbnail and the text
+ const SizedBox(width: 8.0),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
@@ -165,15 +162,12 @@ class _PersonClustersWidgetState extends State<PersonClustersWidget> {
if (snapshot.hasData) {
final clusters = snapshot.data!;
final List<String> keys = clusters.keys.toList();
- // Sort the clusters by the number of files in each cluster, largest first
keys.sort(
(b, a) => clusters[a]!.length.compareTo(clusters[b]!.length),
);
return LayoutBuilder(
builder: (context, constraints) {
- // Determine number of columns based on available width
- // Minimum column width of 150, maximum of 250
final double columnWidth = MediaQuery.of(context).size.width > 600
? 250
: 150;
@@ -183,11 +177,10 @@ class _PersonClustersWidgetState extends State<PersonClustersWidget> {
return GridView.builder(
shrinkWrap: true,
- physics:
- const NeverScrollableScrollPhysics(), // Disable scrolling
+ physics: const NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount,
- childAspectRatio: 1, // Adjust this to control height vs width
+ childAspectRatio: 1,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
diff --git a/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart b/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart
index 2849142048..7e5cf40afd 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart
@@ -34,18 +34,8 @@ class PersonFaceWidget extends StatefulWidget {
final VoidCallback? onErrorCallback;
final bool keepAlive;
- /// Physical pixel width for image decoding optimization.
- ///
- /// When provided and > 0, the image will be decoded at this width, with height
- /// computed to preserve aspect ratio. This reduces memory usage for small displays.
- ///
- /// Typically calculated as: `(logicalWidth * MediaQuery.devicePixelRatioOf(context)).toInt()`
- ///
- /// If null or <= 0, the image is decoded at full resolution.
final int? cachedPixelWidth;
- // PersonFaceWidget constructor checks that both personId and clusterID are not null
- // and that the file is not null
const PersonFaceWidget({
this.personId,
this.clusterID,
@@ -147,17 +137,14 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
@override
Widget build(BuildContext context) {
- super.build(
- context,
- ); // Calling super.build for AutomaticKeepAliveClientMixin
+ super.build(context);
return FutureBuilder<Uint8List?>(
future: faceCropFuture,
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data != null) {
- // Only cacheWidth (not cacheHeight) to preserve aspect ratio.
- // Face crops are typically portrait, so constraining width ensures
- // sufficient height for BoxFit.cover without upscaling.
+ // Decode by width only so portrait crops retain enough height for
+ // BoxFit.cover without upscaling.
final shouldOptimize =
widget.cachedPixelWidth != null && widget.cachedPixelWidth! > 0;
final ImageProvider imageProvider = shouldOptimize
diff --git a/mobile/apps/photos/lib/ui/viewer/people/person_gallery_suggestion.dart b/mobile/apps/photos/lib/ui/viewer/people/person_gallery_suggestion.dart
index 8b985d37ce..08ac6f7ba4 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/person_gallery_suggestion.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/person_gallery_suggestion.dart
@@ -182,7 +182,6 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>
Future<void> _precomputeNextSuggestions([int? expectedLoadID]) async {
final loadID = expectedLoadID ?? _suggestionLoadID;
try {
- // Precompute face crops for next two suggestions
const maxPrecompute = 2;
final endIndex = (currentSuggestionIndex + maxPrecompute).clamp(
0,
@@ -357,7 +356,6 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>
),
);
if (result == null || result == false) {
- // Animate back in and reset processing state
unawaited(_animateIn());
if (mounted) {
setState(() {
@@ -366,7 +364,6 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>
}
return;
}
- // Wait for animation to complete before hiding widget
await Future.delayed(const Duration(milliseconds: 300));
if (mounted) {
setState(() {
@@ -388,14 +385,11 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>
Future<void> _prepareNextSuggestion() async {
if (!mounted) return;
- // Move to next suggestion
currentSuggestionIndex++;
- // Check if we have more suggestions
if (currentSuggestionIndex < allSuggestions.length) {
person = allSuggestions[currentSuggestionIndex].person;
try {
- // Get face crops for next suggestion (from precomputed or generate new)
Map<int, Uint8List?> nextCrops;
if (precomputedFaceCrops.containsKey(currentSuggestionIndex)) {
nextCrops = precomputedFaceCrops[currentSuggestionIndex]!;
@@ -427,7 +421,6 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>
}
}
} else {
- // No more suggestions available - stay hidden
if (mounted) {
setState(() {
isProcessing = false;
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/go_to_map_widget.dart b/mobile/apps/photos/lib/ui/viewer/search/result/go_to_map_widget.dart
index c0ae44013d..046799cd3f 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/result/go_to_map_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/go_to_map_widget.dart
@@ -3,7 +3,6 @@ import "package:flutter/material.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/viewer/search/search_map_navigation.dart";
-//Used for empty state of location section
class GoToMap extends StatelessWidget {
const GoToMap({super.key});
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/magic_result_screen.dart b/mobile/apps/photos/lib/ui/viewer/search/result/magic_result_screen.dart
index 1535176fe5..fc21cf361d 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/result/magic_result_screen.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/magic_result_screen.dart
@@ -24,8 +24,7 @@ import "package:photos/ui/viewer/gallery/state/search_filter_data_provider.dart"
import "package:photos/ui/viewer/gallery/state/selection_state.dart";
class MagicResultScreen extends StatefulWidget {
- ///This widget expects [files] to be sorted by most relelvant first to the
- ///magic search query.
+ // Files must be ordered from most to least relevant.
final List<EnteFile> files;
final String name;
final String heroTag;
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/no_result_widget.dart b/mobile/apps/photos/lib/ui/viewer/search/result/no_result_widget.dart
index 7f24943a39..4c18245f52 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/result/no_result_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/no_result_widget.dart
@@ -19,7 +19,6 @@ class _NoResultWidgetState extends State<NoResultWidget> {
void initState() {
super.initState();
searchTypes = SectionType.values.toList(growable: true);
- // remove face and content sectionType
searchTypes.removeWhere(
(type) => type == SectionType.magic || type == SectionType.wrapped,
);
@@ -123,7 +122,6 @@ class _NoResultWidgetState extends State<NoResultWidget> {
);
}
- /// Join the strings with ', ' and wrap each element with double quotes
String formatList(List<String> strings) {
return strings.map((str) => '"$str"').join(', ');
}
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/people_section_all_page.dart b/mobile/apps/photos/lib/ui/viewer/search/result/people_section_all_page.dart
index 0e6055c4e7..57cbae02cc 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/result/people_section_all_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/people_section_all_page.dart
@@ -531,7 +531,6 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
results.removeWhere((element) => element.params[kPersonParamID] == null);
if (init) {
- // sort widget.selectedPeople first
results.sort((a, b) {
final aIndex =
widget.selectedPeople?.personIds.contains(
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/searchable_item.dart b/mobile/apps/photos/lib/ui/viewer/search/result/searchable_item.dart
index de2d8deef0..b9184cbcfc 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/result/searchable_item.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/searchable_item.dart
@@ -28,10 +28,7 @@ class SearchableItemWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
- //The "searchable_item" tag is to remove hero animation between section
- //examples and searchableItems in 'view all'. Animation should exist between
- //searchableItems and SearchResultPages, so passing the extra prefix to
- //SearchResultPage
+ // Use separate hero tags for section examples and "view all" items.
const additionalPrefix = "searchable_item";
final heroTagPrefix = additionalPrefix + searchResult.heroTag();
final colors = context.componentColors;
diff --git a/mobile/apps/photos/lib/ui/viewer/search/search_suggestions.dart b/mobile/apps/photos/lib/ui/viewer/search/search_suggestions.dart
index 4408f6621d..a4e2cf3bbb 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/search_suggestions.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/search_suggestions.dart
@@ -25,10 +25,8 @@ import "package:photos/ui/viewer/search/result/search_result_widget.dart";
import "package:photos/ui/viewer/search/search_query_utils.dart";
import "package:photos/ui/viewer/search/search_widget.dart";
-///Not using StreamBuilder in this widget for rebuilding on every new event as
-///StreamBuilder is not lossless. It misses some events if the stream fires too
-///fast. Instead, we usi a queue to store the events and then generate the
-///widgets from the queue at regular intervals.
+// StreamBuilder can skip rapid events. Queue results and surface them on a
+// timer.
class SearchSuggestionsWidget extends StatefulWidget {
const SearchSuggestionsWidget({super.key});
@@ -48,8 +46,6 @@ class _SearchSuggestionsWidgetState extends State<SearchSuggestionsWidget> {
Locale? _cachedSectionOrderLocale;
List<_SearchResultsSection>? _cachedSectionOrder;
- ///This is the interval at which the queue is checked for new events and
- ///the search result widgets are generated from the queue.
static const _surfaceNewResultsInterval = 50;
@override
@@ -64,12 +60,7 @@ class _SearchSuggestionsWidgetState extends State<SearchSuggestionsWidget> {
subscription = resultsStream!.listen(
(searchResults) {
- //Currently, we add searchResults even if the list is empty. So we are adding
- //empty list to the queue, which will trigger rebuilds with no change in UI
- //(see [generateResultWidgetsInIntervalsFromQueue]'s setState()).
- //This is needed to clear the search results in this widget when the
- //search bar is cleared, and the event fired by the stream will be an
- //empty list. Can optimize rebuilds if there are performance issues in future.
+ // Empty results clear the suggestions when the query is cleared.
if (searchResults.isNotEmpty) {
IndexOfStackNotifier().searchState = SearchState.notEmpty;
}
@@ -101,10 +92,6 @@ class _SearchSuggestionsWidgetState extends State<SearchSuggestionsWidget> {
queueOfSearchResults.clear();
}
- ///This method generates searchResultsWidgets from the queueOfEvents by checking
- ///every [_surfaceNewResultsInterval] if the queue is empty or not. If the
- ///queue is not empty, it generates the widgets and clears the queue and
- ///updates the UI.
void generateResultWidgetsInIntervalsFromQueue() {
timer = Timer.periodic(
const Duration(milliseconds: _surfaceNewResultsInterval),
diff --git a/mobile/apps/photos/lib/ui/viewer/search/search_widget.dart b/mobile/apps/photos/lib/ui/viewer/search/search_widget.dart
index 00548a89bd..2b74783236 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/search_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/search_widget.dart
@@ -35,11 +35,8 @@ class SearchWidgetState extends State<SearchWidget> {
static final ValueNotifier<Stream<List<SearchResult>>?>
searchResultsStreamNotifier = ValueNotifier(null);
- ///This stores the query that is being searched for. When going to other tabs
- ///when searching, this state gets disposed and when coming back to the
- ///search tab, this query is used to populate the search bar.
+ // The search widget is disposed when switching tabs. Preserve its query.
static String query = "";
- //Debouncing + querying
static final isLoading = ValueNotifier(false);
final _searchService = SearchService.instance;
final _debouncer = Debouncer(const Duration(milliseconds: 314));
@@ -84,8 +81,6 @@ class SearchWidgetState extends State<SearchWidget> {
textController.addListener(textControllerListener);
- //Populate the serach tab with the latest query when coming back
- //to the serach tab.
textController.text = query;
_syncSearchBackNotifier();
diff --git a/mobile/apps/photos/lib/ui/viewer/search_tab/magic_section.dart b/mobile/apps/photos/lib/ui/viewer/search_tab/magic_section.dart
index 94881f768c..043fd8e0c8 100644
--- a/mobile/apps/photos/lib/ui/viewer/search_tab/magic_section.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search_tab/magic_section.dart
@@ -72,35 +72,6 @@ class _MagicSectionState extends State<MagicSection> {
@override
Widget build(BuildContext context) {
if (_magicSearchResults.isEmpty) {
- // final textTheme = getEnteTextTheme(context);
- // return Padding(
- // padding: const EdgeInsets.only(left: 12, right: 8),
- // child: Row(
- // children: [
- // Expanded(
- // child: Column(
- // crossAxisAlignment: CrossAxisAlignment.start,
- // children: [
- // Text(
- // SectionType.magic.sectionTitle(context),
- // style: textTheme.largeBold,
- // ),
- // const SizedBox(height: 24),
- // Padding(
- // padding: const EdgeInsets.only(left: 4),
- // child: Text(
- // SectionType.magic.getEmptyStateText(context),
- // style: textTheme.smallMuted,
- // ),
- // ),
- // ],
- // ),
- // ),
- // const SizedBox(width: 8),
- // const SearchSectionEmptyCTAIcon(SectionType.magic),
- // ],
- // ),
- // );
return const SizedBox.shrink();
} else {
final visibleResults = _magicSearchResults
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index de99d5dff5..eb341bd952 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -32,37 +32,16 @@ class RustCorruptModelException implements Exception {
}
enum IsolateOperation {
- /// [MLIndexingIsolate]
analyzeImage,
-
- /// [MLIndexingIsolate]
prepareRustMlRuntime,
-
- /// [MLIndexingIsolate]
releaseRustMlRuntime,
-
- /// [MLComputer]
generateFaceThumbnails,
-
- /// [MLComputer]
runClipText,
-
- /// [MLComputer]
computeBulkSimilarities,
-
- /// [MLComputer]
computeBulkSimilaritiesWithRust,
-
- /// [MLComputer]
bulkVectorSearch,
-
- /// [MLComputer]
bulkVectorSearchWithKeys,
-
- /// [FaceClusteringService]
linearIncrementalClustering,
-
- /// Cache operations
cacheImageEmbeddings,
setIsolateCache,
clearIsolateCache,
@@ -76,9 +55,9 @@ class _CachedImageEmbeddings {
rust_usearch.SemanticSearchExactCache? rustExactCache;
}
-/// WARNING: Only return primitives unless you know the method is only going
-/// to be used on regular isolates as opposed to DartUI and Flutter isolates
-/// https://api.flutter.dev/flutter/dart-isolate/SendPort/send.html
+// Return only primitives unless this operation only runs on regular Dart
+// isolates rather than Dart UI or Flutter isolates.
+// https://api.flutter.dev/flutter/dart-isolate/SendPort/send.html
Future<dynamic> isolateFunction(
IsolateOperation function,
Map<String, dynamic> args,
@@ -106,9 +85,6 @@ Future<dynamic> isolateFunction(
exact: exact,
);
- /// Cases for MLIndexingIsolate start here
-
- /// MLIndexingIsolate
case IsolateOperation.analyzeImage:
await _ensureRustLoaded();
final MLResult result;
@@ -119,22 +95,15 @@ Future<dynamic> isolateFunction(
}
return result.toJsonString();
- /// MLIndexingIsolate
case IsolateOperation.prepareRustMlRuntime:
await _ensureRustLoaded();
await _ensureRustRuntimePrepared(args);
return true;
- /// MLIndexingIsolate
case IsolateOperation.releaseRustMlRuntime:
await _releaseRustRuntime();
return true;
- /// Cases for MLIndexingIsolate stop here
-
- /// Cases for MLComputer start here
-
- /// MLComputer
case IsolateOperation.generateFaceThumbnails:
final imagePath = args['imagePath'] as String;
final faceBoxesJson = args['faceBoxesList'] as List<Map<String, dynamic>>;
@@ -159,7 +128,6 @@ Future<dynamic> isolateFunction(
);
return List.from(results);
- /// MLComputer
case IsolateOperation.runClipText:
await _ensureRustLoaded();
final text = args["text"] as String;
@@ -198,7 +166,6 @@ Future<dynamic> isolateFunction(
}
return List<double>.from(result.embedding, growable: false);
- /// MLComputer
case IsolateOperation.computeBulkSimilarities:
final cachedEmbeddings = _getCachedImageEmbeddings();
final textEmbedding =
@@ -225,7 +192,6 @@ Future<dynamic> isolateFunction(
}
return result;
- /// MLComputer
case IsolateOperation.computeBulkSimilaritiesWithRust:
await _ensureRustLoaded();
final cachedEmbeddings = _getCachedImageEmbeddings();
@@ -254,20 +220,10 @@ Future<dynamic> isolateFunction(
}
return result;
- /// Cases for MLComputer end here
-
- /// Cases for FaceClusteringService start here
-
- /// FaceClusteringService
case IsolateOperation.linearIncrementalClustering:
final ClusteringResult result = runLinearClustering(args);
return result;
- /// Cases for FaceClusteringService end here
-
- /// Cases for Caching start here
-
- /// Caching
case IsolateOperation.cacheImageEmbeddings:
final embeddings = args['embeddings'] as List<EmbeddingVector>;
final cacheRustExact = args['cacheRustExact'] as bool? ?? false;
@@ -283,7 +239,6 @@ Future<dynamic> isolateFunction(
_isolateCache[imageEmbeddingsKey] = cachedEmbeddings;
return true;
- /// Caching
case IsolateOperation.setIsolateCache:
final key = args['key'] as String;
final value = args['value'];
@@ -291,14 +246,12 @@ Future<dynamic> isolateFunction(
_isolateCache[key] = value;
return true;
- /// Caching
case IsolateOperation.clearIsolateCache:
final key = args['key'] as String;
final removedValue = _isolateCache.remove(key);
_disposeIsolateCacheValue(removedValue);
return true;
- /// Caching
case IsolateOperation.clearAllIsolateCache:
await _ensureRustDisposed();
for (final value in _isolateCache.values) {
@@ -307,7 +260,6 @@ Future<dynamic> isolateFunction(
_isolateCache.clear();
return true;
- /// Cases for Caching stop here
}
}
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 2541228f54..24f1d9a05a 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -98,9 +98,7 @@ class _OnlineMLIndexingCandidates {
});
}
-/// Counts indexing progress using the same eligibility predicates as the
-/// indexing candidate enumeration below, so the shown number always matches
-/// what the indexer would actually process.
+// Keep these eligibility rules in sync with candidate enumeration below.
Future<IndexStatus> getIndexStatus() async {
try {
final bool localGallery = isLocalGalleryMode;
@@ -171,16 +169,14 @@ Future<IndexStatus> getIndexStatus() async {
}
}
-// _lastFetchTimeForOthersIndexed indicates the last time we tried to
-// fetch embeddings for files that are owned by others. This is only used
-// when local indexing is disabled.
+// Throttles remote embedding checks for files owned by others when local
+// indexing is disabled.
int _lastFetchTimeForOthersIndexed = 0;
Future<_OnlineMLIndexingCandidates>
_getOnlineFilesForMlIndexingCandidates() async {
final mlDataDB = MLDataDB.instance;
final time = DateTime.now();
- // Get indexed fileIDs for each ML service
final Map<int, int> faceIndexedFileIDs = await mlDataDB.faceIndexedFileIds();
final Map<int, int> clipIndexedFileIDs = await mlDataDB
.clipIndexedFileWithVersion();
@@ -197,11 +193,9 @@ _getOnlineFilesForMlIndexingCandidates() async {
type: DataType.mlData,
);
- // Get all regular files and all hidden files
final enteFiles = await SearchService.instance.getAllFilesForSearch();
final hiddenFiles = await SearchService.instance.getHiddenFiles();
- // Sort out what should be indexed and in what order
final List<FileMLInstruction> filesWithLocalID = [];
final List<FileMLInstruction> filesWithoutLocalID = [];
final List<FileMLInstruction> hiddenFilesToIndex = [];
@@ -301,7 +295,6 @@ _getOnlineFilesForMlIndexingCandidates() async {
);
}
-/// Return a list of file instructions for files that should be indexed for ML
Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
_logger.info('getFilesForMlIndexing called');
final candidateSplit = await _getOnlineFilesForMlIndexingCandidates();
@@ -453,7 +446,6 @@ Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
}
}
}
- // Yield any remaining instructions
if (batchToYield.isNotEmpty) {
_logger.info("queueing indexing for ${batchToYield.length}");
yield batchToYield;
@@ -614,7 +606,7 @@ Future<List<FileMLInstruction>> hydrateRemoteMLDataForInstructions(
continue;
}
final facesFromRemoteEmbedding = _getFacesFromRemoteEmbedding(fileMl);
- // Note: always do null check; an empty value means no face was found.
+ // A non-null result is compatible remote data, even when no face was found.
if (facesFromRemoteEmbedding != null) {
faces.addAll(facesFromRemoteEmbedding);
existingInstruction.shouldRunFaces = false;
@@ -647,8 +639,6 @@ Future<List<FileMLInstruction>> hydrateRemoteMLDataForInstructions(
.toList();
}
-// Returns a list of faces from the given remote fileML. null if the version is less than the current version
-// or if the remote faceEmbedding is null.
List<Face>? _getFacesFromRemoteEmbedding(FileDataEntity fileMl) {
final RemoteFaceEmbedding? remoteFaceEmbedding = fileMl.faceEmbedding;
if (_shouldDiscardRemoteEmbedding(fileMl)) {
@@ -679,7 +669,6 @@ bool _shouldDiscardRemoteEmbedding(FileDataEntity fileML) {
);
return true;
}
- // are all landmarks equal?
bool allLandmarksEqual = true;
if (faceEmbedding.faces.isEmpty) {
allLandmarksEqual = false;
@@ -733,7 +722,6 @@ Future<String> getImagePathForML(EnteFile enteFile) async {
throw ThumbnailRetrievalException(e.toString(), s);
}
} else {
- // Don't process the file if it's too large (more than 100MB)
if (enteFile.fileSize != null && enteFile.fileSize! > maxFileDownloadSize) {
throw Exception(
"FileSizeTooLargeForMobileIndexing: size is ${enteFile.fileSize}",
@@ -922,9 +910,8 @@ Future<MLResult> analyzeImageRust(Map args) async {
height: rustResult.decodedImageSize.height,
);
- // Nullify faces/clip when their pipelines were not requested so that
- // facesRan/clipRan correctly report false and processImage does not
- // overwrite existing remote embeddings with empty payloads.
+ // Null means the pipeline did not run; an empty result would overwrite
+ // remote embeddings.
if (!runFaces) result.faces = null;
if (runFaces) {
@@ -981,7 +968,7 @@ Future<MLResult> analyzeImageRust(Map args) async {
.toList(growable: false),
);
final alignment = AlignmentResult(
- // Pet alignment is done in Rust; no Dart-side affine matrix needed.
+ // Rust already aligned pet faces; no Dart matrix is needed.
affineMatrix: const [],
center: face.alignment.center.toList(growable: false),
size: face.alignment.cropSize,