π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Process android metadata
Neeraj Gupta033ebc007e26
diff --git a/mobile/apps/photos/lib/db/files_db.dart b/mobile/apps/photos/lib/db/files_db.dartindex 6fe0f6ec38..eed8fe4a88 100644--- a/mobile/apps/photos/lib/db/files_db.dart+++ b/mobile/apps/photos/lib/db/files_db.dart@@ -1038,6 +1038,25 @@ class FilesDB with SqlDbBase {return convertToFiles(results);}+ Future<List<EnteFile>> getUnUploadedLocalFilesPendingOfflineProcessing(+ int processingVersion, {+ int? limit,+ }) async {+ final db = await instance.sqliteAsyncDB;+ final args = <Object?>[processingVersion];+ var query = 'SELECT * FROM $filesTable WHERE ($columnUploadedFileID IS '+ 'NULL OR $columnUploadedFileID IS -1) AND $columnLocalID IS NOT NULL '+ 'AND $columnLocalID IS NOT -1 AND ($columnMetadataVersion IS NULL OR '+ '$columnMetadataVersion < ?) GROUP BY $columnLocalID ORDER BY '+ '$columnCreationTime DESC';+ if (limit != null) {+ query += ' LIMIT ?';+ args.add(limit);+ }+ final results = await db.getAll(query, args);+ return convertToFiles(results);+ }+Future<List<int>> getUploadedFileIDsToBeUpdated(int ownerID) async {final db = await instance.sqliteAsyncDB;final rows = await db.getAll(@@ -1241,6 +1260,35 @@ class FilesDB with SqlDbBase {);}+ Future<void> updateOfflineImportMetadataForLocalID(+ String localID, {+ required int processingVersion,+ int? creationTime,+ Location? location,+ int? fileSize,+ }) async {+ final db = await instance.sqliteAsyncDB;+ await db.execute(+ '''+ UPDATE $filesTable+ SET $columnCreationTime = COALESCE(?, $columnCreationTime),+ $columnLatitude = COALESCE(?, $columnLatitude),+ $columnLongitude = COALESCE(?, $columnLongitude),+ $columnFileSize = COALESCE(?, $columnFileSize),+ $columnMetadataVersion = ?+ WHERE $columnLocalID = ? AND ($columnUploadedFileID IS NULL OR $columnUploadedFileID = -1);+ ''',+ [+ creationTime,+ location?.latitude,+ location?.longitude,+ fileSize,+ processingVersion,+ localID,+ ],+ );+ }+/*This method should only return localIDs which are not uploaded yetand can be mapped to incoming remote entrydiff --git a/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dart b/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dartnew file mode 100644index 0000000000..d8f9a2ea46--- /dev/null+++ b/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dart@@ -0,0 +1,181 @@+import "dart:async";+import "dart:io";++import "package:exif_reader/exif_reader.dart";+import "package:logging/logging.dart";+import "package:photos/core/event_bus.dart";+import "package:photos/db/files_db.dart";+import "package:photos/events/files_updated_event.dart";+import "package:photos/events/local_photos_updated_event.dart";+import "package:photos/models/file/extensions/file_props.dart";+import "package:photos/models/file/file.dart";+import "package:photos/models/location/location.dart";+import "package:photos/service_locator.dart";+import "package:photos/utils/exif_util.dart";+import "package:photos/utils/file_uploader_util.dart";+import "package:photos/utils/file_util.dart";++class OfflineImportMetadataService {+ static const kProcessingVersion = 1;+ static const kDefaultBatchSize = 25;++ final _logger = Logger("OfflineImportMetadataService");+ final _db = FilesDB.instance;++ Completer<void>? _running;++ OfflineImportMetadataService._privateConstructor();++ static final instance = OfflineImportMetadataService._privateConstructor();++ Future<void> processPendingFiles({+ int batchSize = kDefaultBatchSize,+ int maxBatches = 4,+ }) async {+ if (!Platform.isAndroid || !isOfflineMode) {+ return;+ }+ if (_running != null) {+ _logger.info("Offline import metadata processing already in progress");+ return _running!.future;+ }++ _running = Completer<void>();+ try {+ for (var batch = 0; batch < maxBatches; batch++) {+ if (!isOfflineMode) {+ _logger.info(+ "Offline mode disabled, stopping metadata processing",+ );+ return;+ }++ final files = await _db.getUnUploadedLocalFilesPendingOfflineProcessing(+ kProcessingVersion,+ limit: batchSize,+ );+ if (files.isEmpty) {+ return;+ }++ final updatedFiles = <EnteFile>[];+ for (final file in files) {+ if (!isOfflineMode) {+ _logger.info(+ "Offline mode disabled during per-file processing, stopping",+ );+ return;+ }+ if ((file.localID ?? "").isEmpty) {+ continue;+ }+ final processed = await _processFile(file);+ if (processed) {+ updatedFiles.add(file);+ }+ }++ if (updatedFiles.isNotEmpty) {+ Bus.instance.fire(+ LocalPhotosUpdatedEvent(+ updatedFiles,+ type: EventType.coverChanged,+ source: "offlineImportMetadata",+ ),+ );+ }++ if (files.length < batchSize) {+ return;+ }+ }+ } finally {+ _running?.complete();+ _running = null;+ }+ }++ Future<bool> _processFile(EnteFile file) async {+ File? originFile;+ try {+ originFile = await getFile(file, isOrigin: true);+ if (originFile == null || !originFile.existsSync()) {+ return false;+ }++ final fileSize = await originFile.length();+ final exifData = await tryExifFromFile(originFile);+ final exifTime = await tryParseExifDateTime(null, exifData);++ await _updateLocationForOfflineFile(+ file,+ originFile,+ exifData,+ );++ final mediaUploadData = MediaUploadData(+ originFile,+ null,+ false,+ null,+ exifData: exifData,+ );+ await file.getMetadataForUpload(mediaUploadData, exifTime);++ await _db.updateOfflineImportMetadataForLocalID(+ file.localID!,+ processingVersion: kProcessingVersion,+ creationTime: file.creationTime,+ location: file.location,+ fileSize: fileSize,+ );++ file.fileSize = fileSize;+ file.metadataVersion = kProcessingVersion;+ return true;+ } catch (e, s) {+ _logger.warning("Failed to process ${file.tag}", e, s);+ return false;+ } finally {+ if (Platform.isIOS &&+ originFile != null &&+ !file.isSharedMediaToAppSandbox) {+ try {+ await originFile.delete();+ } catch (_) {}+ }+ }+ }++ Future<void> _updateLocationForOfflineFile(+ EnteFile file,+ File originFile,+ Map<String, IfdTag>? exifData,+ ) async {+ final shouldFetchAssetLocation = file.location == null ||+ ((file.location?.latitude ?? 0) == 0 &&+ (file.location?.longitude ?? 0) == 0);+ if (shouldFetchAssetLocation) {+ final asset = await file.getAsset;+ if (asset != null) {+ final latLong = await asset.latlngAsync();+ file.location =+ Location(latitude: latLong.latitude, longitude: latLong.longitude);+ }+ }++ if (!file.hasLocation && file.isVideo && Platform.isAndroid) {+ final props = await getVideoPropsAsync(originFile);+ if (props?.location != null) {+ file.location = props!.location;+ }+ }++ if (Platform.isAndroid && exifData != null) {+ final exifLocation = locationFromExif(exifData);+ if (Location.isValidLocation(exifLocation)) {+ file.location = exifLocation;+ }+ }+ }+}diff --git a/mobile/apps/photos/lib/services/sync/sync_service.dart b/mobile/apps/photos/lib/services/sync/sync_service.dartindex c9620b2f53..470517afda 100644--- a/mobile/apps/photos/lib/services/sync/sync_service.dart+++ b/mobile/apps/photos/lib/services/sync/sync_service.dart@@ -18,6 +18,7 @@ import 'package:photos/service_locator.dart';import 'package:photos/services/language_service.dart';import 'package:photos/services/notification_service.dart';import 'package:photos/services/sync/local_sync_service.dart';+import 'package:photos/services/sync/offline_import_metadata_service.dart';import 'package:photos/services/sync/remote_sync_service.dart';import 'package:photos/utils/file_uploader.dart';import 'package:shared_preferences/shared_preferences.dart';@@ -199,7 +200,19 @@ class SyncService {await _localSyncService.sync();if (isOfflineMode) {await _localSyncService.syncAll();- _logger.info("[SYNC] Offline mode, skipping remote sync");+ if (Platform.isAndroid) {+ unawaited(+ OfflineImportMetadataService.instance.processPendingFiles(+ batchSize: isProcessBg+ ? 10+ : OfflineImportMetadataService.kDefaultBatchSize,+ maxBatches: isProcessBg ? 1 : 4,+ ),+ );+ }+ _logger.info(+ "[SYNC] Offline mode${Platform.isAndroid ? '' : ' (non-Android, no metadata processing)'}, skipping remote sync",+ );return;}