Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][photos] Fix edited iOS photo reuploads

AmanRajSinghMouryaf147be07b1ec
diff --git a/mobile/apps/photos/changes/ios-edited-photo-sync.md b/mobile/apps/photos/changes/ios-edited-photo-sync.md
new file mode 100644
index 0000000000..1331dcde59
--- /dev/null
+++ b/mobile/apps/photos/changes/ios-edited-photo-sync.md
@@ -0,0 +1 @@
+- Fix syncing edited iOS photos after local gallery changes.
diff --git a/mobile/apps/photos/lib/db/files_db.dart b/mobile/apps/photos/lib/db/files_db.dart
index 467c07c640..93d9924d8b 100644
--- a/mobile/apps/photos/lib/db/files_db.dart
+++ b/mobile/apps/photos/lib/db/files_db.dart
@@ -73,8 +73,9 @@ class FilesDB with SqlDbBase {
// we need to write query based on that field
static const columnMMdVisibility = 'mmd_visibility';
- //If adding or removing a new column, make sure to update the `_columnNames` list
- //and update `_generateColumnsAndPlaceholdersForInsert` and
+ //If adding or removing a new column, make sure to update the `_columnNames`
+ //list, the parallel value list in `_getParameterSetForFile`, and the column
+ //builders `_generateColumnsAndPlaceholdersForInsert` and
//`_generateUpdateAssignmentsWithPlaceholders`
static final _migrationScripts = [
...createTable(filesTable),
@@ -507,10 +508,14 @@ class FilesDB with SqlDbBase {
Future<void> insert(EnteFile file) async {
_logger.info("Inserting $file");
final db = await instance.sqliteAsyncDB;
+ final bool omitGeneratedId = file.generatedID == null;
final columnsAndPlaceholders = _generateColumnsAndPlaceholdersForInsert(
- fileGenId: file.generatedID,
+ omitGeneratedId: omitGeneratedId,
+ );
+ final values = _getParameterSetForFile(
+ file,
+ omitGeneratedId: omitGeneratedId,
);
- final values = _getParameterSetForFile(file);
await db.execute(
'INSERT OR REPLACE INTO $filesTable (${columnsAndPlaceholders["columns"]}) VALUES (${columnsAndPlaceholders["placeholders"]})',
@@ -521,10 +526,14 @@ class FilesDB with SqlDbBase {
Future<int> insertAndGetId(EnteFile file) async {
_logger.info("Inserting $file");
final db = await instance.sqliteAsyncDB;
+ final bool omitGeneratedId = file.generatedID == null;
final columnsAndPlaceholders = _generateColumnsAndPlaceholdersForInsert(
- fileGenId: file.generatedID,
+ omitGeneratedId: omitGeneratedId,
+ );
+ final values = _getParameterSetForFile(
+ file,
+ omitGeneratedId: omitGeneratedId,
);
- final values = _getParameterSetForFile(file);
return await db.writeTransaction((tx) async {
await tx.execute(
'INSERT OR REPLACE INTO $filesTable (${columnsAndPlaceholders["columns"]}) VALUES (${columnsAndPlaceholders["placeholders"]})',
@@ -1360,9 +1369,13 @@ class FilesDB with SqlDbBase {
Future<void> update(EnteFile file) async {
final db = await instance.sqliteAsyncDB;
- final parameterSet = _getParameterSetForFile(file)..add(file.generatedID);
+ final bool omitGeneratedId = file.generatedID == null;
+ final parameterSet = _getParameterSetForFile(
+ file,
+ omitGeneratedId: omitGeneratedId,
+ )..add(file.generatedID);
final updateAssignments = _generateUpdateAssignmentsWithPlaceholders(
- fileGenId: file.generatedID,
+ omitGeneratedId: omitGeneratedId,
);
await db.execute(
'UPDATE $filesTable '
@@ -1373,11 +1386,21 @@ class FilesDB with SqlDbBase {
Future<void> updateUploadedFileAcrossCollections(EnteFile file) async {
final db = await instance.sqliteAsyncDB;
- final parameterSet = _getParameterSetForFile(file, omitCollectionId: true)
- ..add(file.uploadedFileID);
+ // _id, collection_id and the encrypted key material must not be written
+ // here: the same uploadedFileID can exist as multiple rows (one per
+ // collection), each with its own _id, collection_id and encrypted_key/
+ // key_decryption_nonce (the file key wrapped with that collection's key).
+ // Writing one collection's values across all rows would corrupt the others.
+ final parameterSet = _getParameterSetForFile(
+ file,
+ omitCollectionId: true,
+ omitGeneratedId: true,
+ omitKeyMaterial: true,
+ )..add(file.uploadedFileID);
final updateAssignments = _generateUpdateAssignmentsWithPlaceholders(
- fileGenId: file.generatedID,
+ omitGeneratedId: true,
omitCollectionId: true,
+ omitKeyMaterial: true,
);
await db.execute(
'UPDATE $filesTable '
@@ -2136,18 +2159,24 @@ class FilesDB with SqlDbBase {
///Returns "columnName1 = ?, columnName2 = ?, ..."
String _generateUpdateAssignmentsWithPlaceholders({
- required int? fileGenId,
+ required bool omitGeneratedId,
bool omitCollectionId = false,
+ bool omitKeyMaterial = false,
}) {
final assignments = <String>[];
for (String columnName in _columnNames) {
- if (columnName == columnGeneratedID && fileGenId == null) {
+ if (columnName == columnGeneratedID && omitGeneratedId) {
continue;
}
if (columnName == columnCollectionID && omitCollectionId) {
continue;
}
+ if (omitKeyMaterial &&
+ (columnName == columnEncryptedKey ||
+ columnName == columnKeyDecryptionNonce)) {
+ continue;
+ }
assignments.add("$columnName = ?");
}
@@ -2155,12 +2184,12 @@ class FilesDB with SqlDbBase {
}
Map<String, String> _generateColumnsAndPlaceholdersForInsert({
- required int? fileGenId,
+ required bool omitGeneratedId,
}) {
final columnNames = <String>[];
for (String columnName in _columnNames) {
- if (columnName == columnGeneratedID && fileGenId == null) {
+ if (columnName == columnGeneratedID && omitGeneratedId) {
continue;
}
@@ -2176,6 +2205,8 @@ class FilesDB with SqlDbBase {
List<Object?> _getParameterSetForFile(
EnteFile file, {
bool omitCollectionId = false,
+ bool omitGeneratedId = false,
+ bool omitKeyMaterial = false,
}) {
final values = <Object?>[];
@@ -2194,22 +2225,25 @@ class FilesDB with SqlDbBase {
}
}
- if (file.generatedID != null) {
+ if (file.generatedID != null && !omitGeneratedId) {
values.add(file.generatedID);
}
values.addAll([
file.localID,
file.uploadedFileID ?? -1,
file.ownerID,
- file.collectionID ?? -1,
+ if (!omitCollectionId) file.collectionID ?? -1,
file.title,
file.deviceFolder,
latitude,
longitude,
getInt(file.fileType),
file.modificationTime,
- file.encryptedKey,
- file.keyDecryptionNonce,
+ // encrypted_key/key_decryption_nonce are per-collection (the file key
+ // wrapped with that collection's key), so they must be omitted from a
+ // cross-collection update to avoid overwriting sibling rows.
+ if (!omitKeyMaterial) file.encryptedKey,
+ if (!omitKeyMaterial) file.keyDecryptionNonce,
file.fileDecryptionHeader,
file.thumbnailDecryptionHeader,
file.metadataDecryptionHeader,
@@ -2229,10 +2263,6 @@ class FilesDB with SqlDbBase {
file.addedTime ?? -1,
]);
- if (omitCollectionId) {
- values.removeAt(3);
- }
-
return values;
}
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 6461972a1e..4902c73ab2 100644
--- a/mobile/apps/photos/lib/services/sync/local_sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
@@ -30,10 +30,13 @@ import "package:shared_preferences/shared_preferences.dart";
import "package:synchronized/synchronized.dart";
import "package:tuple/tuple.dart";
-// This map is used to track if a iOS origin file is being fetched for uploading
-// or ML processing. In such cases, we want to ignore these files if they come in response
-// from the local sync service. When a file is download
-final LRUMap<String, bool> trackOriginFetchForUploadOrML = LRUMap(200);
+// Tracks iOS assets whose origin bytes were recently fetched for upload or
+// ML, mapped to the asset's modificationTime (in microseconds) at fetch time.
+// Fetching origin bytes can itself fire a photo library change notification;
+// such self-inflicted notifications carry an unchanged modificationTime and
+// are skipped during update tracking. A real edit moves modificationTime
+// forward, so it is always tracked even when the localID is present here.
+final LRUMap<String, int> trackOriginFetchForUploadOrML = LRUMap(200);
class LocalSyncService {
final _logger = Logger("LocalSyncService");
@@ -395,10 +398,7 @@ class LocalSyncService {
if (allFiles.isEmpty) return;
final bool discoveredNewFiles = newlyInsertedFiles.isNotEmpty;
if (!discoveredNewFiles) {
- allFiles.removeWhere(
- (file) =>
- trackOriginFetchForUploadOrML.get(file.localID ?? '') ?? false,
- );
+ allFiles.removeWhere(_isSelfInflictedUpdate);
if (allFiles.isEmpty) {
_logger.info("skipping firing LocalPhotosUpdatedEvent as no new files");
return;
@@ -429,32 +429,60 @@ class LocalSyncService {
List<EnteFile> files,
Set<String> existingLocalFileIDs,
) async {
- final List<String> updatedLocalIDs = files
+ final List<EnteFile> updatedFiles = files
.where(
(file) =>
file.localID != null &&
existingLocalFileIDs.contains(file.localID),
)
- .map((e) => e.localID!)
.toList();
- if (updatedLocalIDs.isNotEmpty) {
- final int updateCount = updatedLocalIDs.length;
- updatedLocalIDs.removeWhere(
- (x) => trackOriginFetchForUploadOrML.get(x) ?? false,
+ if (updatedFiles.isNotEmpty) {
+ final int updateCount = updatedFiles.length;
+ updatedFiles.removeWhere(
+ (file) => _isSelfInflictedUpdate(file, logDecision: true),
);
_logger.info(
- "track ${updatedLocalIDs.length}/ $updateCount files due to modification change",
+ "track ${updatedFiles.length}/ $updateCount files due to modification change",
);
- if (updatedLocalIDs.isNotEmpty) {
+ if (updatedFiles.isNotEmpty) {
await FileUpdationDB.instance.insertMultiple(
- updatedLocalIDs,
+ updatedFiles.map((e) => e.localID!).toList(),
FileUpdationDB.modificationTimeUpdated,
);
}
}
}
+ // A change notification for a file whose modificationTime still matches the
+ // value recorded when we last fetched its origin bytes was caused by that
+ // fetch itself, not by a user edit.
+ bool _isSelfInflictedUpdate(EnteFile file, {bool logDecision = false}) {
+ final int? trackedModificationTime = trackOriginFetchForUploadOrML.get(
+ file.localID ?? '',
+ );
+ if (trackedModificationTime == null) {
+ return false;
+ }
+ final bool isSelfInflicted =
+ trackedModificationTime == file.modificationTime;
+ if (logDecision) {
+ if (isSelfInflicted) {
+ _logger.info(
+ "Skipping self-inflicted update for ${file.localID}, "
+ "modificationTime unchanged at $trackedModificationTime",
+ );
+ } else {
+ _logger.info(
+ "Tracking edit of recently fetched ${file.localID}, "
+ "modificationTime moved $trackedModificationTime -> "
+ "${file.modificationTime}",
+ );
+ }
+ }
+ return isSelfInflicted;
+ }
+
void _registerChangeCallback() {
if (_isChangeCallbackRegistered) {
return;
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 98d3fef121..2de64d8be5 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
@@ -39,6 +39,7 @@ class AlbumSelectionActionWidget extends StatefulWidget {
class _AlbumSelectionActionWidgetState
extends State<AlbumSelectionActionWidget> {
final _logger = Logger("AlbumSelectionActionWidgetState");
+ final _scrollController = ScrollController();
late CollectionActions collectionActions;
bool hasFavorites = false;
@@ -52,6 +53,7 @@ class _AlbumSelectionActionWidgetState
@override
void dispose() {
widget.selectedAlbums.removeListener(_selectionChangedListener);
+ _scrollController.dispose();
super.dispose();
}
@@ -204,17 +206,16 @@ class _AlbumSelectionActionWidgetState
);
}
- final scrollController = ScrollController();
-
return MediaQuery(
data: MediaQuery.of(context).removePadding(removeBottom: true),
child: SafeArea(
child: Scrollbar(
radius: const Radius.circular(1),
thickness: 2,
- controller: scrollController,
+ controller: _scrollController,
thumbVisibility: true,
child: SingleChildScrollView(
+ controller: _scrollController,
physics: const BouncingScrollPhysics(
decelerationRate: ScrollDecelerationRate.fast,
),
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 2820629db8..de7c86c15f 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
@@ -56,16 +56,16 @@ class _FilePropertiesItemWidgetState extends State<FilePropertiesItemWidget> {
Future<List<Widget>> _subTitleSection() async {
final textStyle = getEnteTextTheme(context).miniMuted;
final StringBuffer dimString = StringBuffer();
- if (widget.exifData["resolution"] != null &&
- widget.exifData["megaPixels"] != null) {
- dimString.write('${widget.exifData["megaPixels"]}MP ');
- dimString.write('${widget.exifData["resolution"]}');
- } else if (widget.file.hasDimensions) {
+ if (widget.file.hasDimensions) {
final double megaPixels =
(widget.file.width * widget.file.height) / 1000000;
final double roundedMegaPixels = (megaPixels * 10).round() / 10.0;
dimString.write('${roundedMegaPixels.toStringAsFixed(1)}MP ');
dimString.write('${widget.file.width} x ${widget.file.height}');
+ } else if (widget.exifData["resolution"] != null &&
+ widget.exifData["megaPixels"] != null) {
+ dimString.write('${widget.exifData["megaPixels"]}MP ');
+ dimString.write('${widget.exifData["resolution"]}');
}
final subSectionWidgets = <Widget>[];
diff --git a/mobile/apps/photos/lib/utils/file_uploader.dart b/mobile/apps/photos/lib/utils/file_uploader.dart
index bb945ed80e..fe1ccca43e 100644
--- a/mobile/apps/photos/lib/utils/file_uploader.dart
+++ b/mobile/apps/photos/lib/utils/file_uploader.dart
@@ -35,6 +35,7 @@ import "package:photos/module/upload/service/multipart.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/account/user_service.dart";
import 'package:photos/services/collections_service.dart';
+import 'package:photos/services/file_magic_service.dart';
import 'package:photos/services/sync/local_sync_service.dart';
import 'package:photos/services/sync/sync_service.dart';
import "package:photos/utils/exif_util.dart";
@@ -855,6 +856,10 @@ class FileUploader {
throw LockFreedError();
}
+ final Map<String, dynamic> pubMetadata = _buildPublicMagicData(
+ mediaUploadData,
+ exifTime,
+ );
EnteFile remoteFile;
if (isUpdatedFile) {
// Verify that the encrypted file can be decrypted before uploading
@@ -880,6 +885,24 @@ class FileUploader {
);
// Update across all collections
await FilesDB.instance.updateUploadedFileAcrossCollections(remoteFile);
+ // _updateFile does not carry public magic metadata, so derived values
+ // (width/height, mediaType, exif, camera) that change when the file is
+ // edited would stay stale. Refresh them here. updatePublicMagicMetadata
+ // merges into the existing pub mmd, preserving user-editable keys
+ // (editedTime/editedName/caption).
+ if (pubMetadata.isNotEmpty) {
+ try {
+ await FileMagicService.instance.updatePublicMagicMetadata([
+ remoteFile,
+ ], pubMetadata);
+ } catch (e, s) {
+ _logger.warning(
+ "Failed to refresh public metadata on re-upload of ${file.tag}",
+ e,
+ s,
+ );
+ }
+ }
} else {
final encryptedFileKeyData = CryptoUtil.encryptSync(
fileAttributes.key,
@@ -891,10 +914,6 @@ class FileUploader {
final keyDecryptionNonce = CryptoUtil.bin2base64(
encryptedFileKeyData.nonce!,
);
- final Map<String, dynamic> pubMetadata = _buildPublicMagicData(
- mediaUploadData,
- exifTime,
- );
MetadataRequest? pubMetadataRequest;
if (pubMetadata.isNotEmpty) {
pubMetadataRequest = await getPubMetadataRequest(
diff --git a/mobile/apps/photos/lib/utils/file_uploader_util.dart b/mobile/apps/photos/lib/utils/file_uploader_util.dart
index 4e12dc46ef..db0edbfb23 100644
--- a/mobile/apps/photos/lib/utils/file_uploader_util.dart
+++ b/mobile/apps/photos/lib/utils/file_uploader_util.dart
@@ -130,7 +130,10 @@ Future<MediaUploadData> _getMediaUploadDataFromAssetFile(
}
_assertFileType(asset, file);
if (Platform.isIOS) {
- trackOriginFetchForUploadOrML.put(file.localID!, true);
+ trackOriginFetchForUploadOrML.put(
+ file.localID!,
+ asset.modifiedDateTime.microsecondsSinceEpoch,
+ );
}
try {
sourceFile = await asset.originFile
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 829f7a2c87..d109436ce4 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -722,7 +722,13 @@ Future<String> getImagePathForML(EnteFile enteFile) async {
}
try {
if (Platform.isIOS && enteFile.localID != null) {
- trackOriginFetchForUploadOrML.put(enteFile.localID!, true);
+ final asset = await enteFile.getAsset;
+ if (asset != null) {
+ trackOriginFetchForUploadOrML.put(
+ enteFile.localID!,
+ asset.modifiedDateTime.microsecondsSinceEpoch,
+ );
+ }
}
file = await getFile(enteFile, isOrigin: true);
} catch (e, s) {