π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Isolate Live Photo processing
Neeraj Gupta6647616891e7
diff --git a/mobile/apps/photos/lib/module/download/file.dart b/mobile/apps/photos/lib/module/download/file.dartindex 3d2eb7669c..e7d026efb2 100644--- a/mobile/apps/photos/lib/module/download/file.dart+++ b/mobile/apps/photos/lib/module/download/file.dart@@ -2,7 +2,6 @@ import 'dart:async';import 'dart:io';import "package:dio/dio.dart";-import 'package:flutter/foundation.dart';import 'package:flutter_cache_manager/flutter_cache_manager.dart';import 'package:flutter_image_compress/flutter_image_compress.dart';import 'package:logging/logging.dart';@@ -17,7 +16,7 @@ import "package:photos/models/file/extensions/file_props.dart";import 'package:photos/models/file/file.dart';import 'package:photos/models/file/file_type.dart';import 'package:photos/module/download/decrypt.dart';-import 'package:photos/module/live_photo/archive.dart';+import 'package:photos/module/live_photo/download.dart';final _logger = Logger("FileUtil");@@ -213,8 +212,8 @@ Future<bool> isFileCached(EnteFile file, {bool liveVideo = false}) async {return fileInfo != null;}-final Map<int, Future<_LivePhoto?>> _livePhotoDownloadsTracker =- <int, Future<_LivePhoto?>>{};+final Map<int, Future<LivePhotoFiles?>> _livePhotoDownloadsTracker =+ <int, Future<LivePhotoFiles?>>{};Future<File?> _getLivePhotoFromServer(EnteFile file, {@@ -227,7 +226,7 @@ Future<File?> _getLivePhotoFromServer(final livePhoto = await _runOncePerKey(_livePhotoDownloadsTracker,downloadID,- () => _downloadLivePhoto(+ () => downloadLivePhotoFiles(file,progressCallback: progressCallback,forGalleryDownload: forGalleryDownload,@@ -246,87 +245,6 @@ Future<File?> _getLivePhotoFromServer(}}-Future<_LivePhoto?> _downloadLivePhoto(- EnteFile file, {- ProgressCallback? progressCallback,- bool forGalleryDownload = false,-}) async {- return downloadAndDecrypt(- file,- progressCallback: progressCallback,- forceResumableDownload: forGalleryDownload,- throwOnFailure: forGalleryDownload,- )- .then((decryptedFile) async {- if (decryptedFile == null) {- return null;- }- _logger.info("Decoded zipped live photo from " + decryptedFile.path);- File? imageFileCache, videoFileCache;- final List<int> bytes = await decryptedFile.readAsBytes();- final parts = decodeLivePhotoArchive(bytes);- final tempPath = Configuration.instance.getTempDirectory();- for (final part in parts) {- final String fileExtension = getExtension(part.fileName);- final String decodePath =- tempPath + file.uploadedFileID.toString() + part.fileName;- if (part.type == LivePhotoArchivePartType.image) {- final imageFile = File(decodePath);- await imageFile.create(recursive: true);- await imageFile.writeAsBytes(part.bytes);- File imageConvertedFile = imageFile;- if ((fileExtension == "unknown") ||- (Platform.isAndroid && fileExtension == "heic")) {- final compressResult =- await FlutterImageCompress.compressAndGetFile(- decodePath,- decodePath + ".jpg",- keepExif: true,- );- await imageFile.delete();- if (compressResult == null) {- throw Exception("Failed to compress file");- } else {- imageConvertedFile = File(compressResult.path);- }- }- imageFileCache = await DefaultCacheManager().putFile(- file.downloadUrl,- await imageConvertedFile.readAsBytes(),- eTag: file.downloadUrl,- maxAge: const Duration(days: 365),- fileExtension: fileExtension,- );- await imageConvertedFile.delete();- } else {- final videoFile = File(decodePath);- await videoFile.create(recursive: true);- await videoFile.writeAsBytes(part.bytes);- videoFileCache = await VideoCacheManager.instance.putFileStream(- file.downloadUrl,- videoFile.openRead(),- eTag: file.downloadUrl,- maxAge: const Duration(days: 365),- fileExtension: fileExtension,- );- await videoFile.delete();- }- }- if (imageFileCache != null && videoFileCache != null) {- return _LivePhoto(imageFileCache, videoFileCache);- } else {- debugPrint(- "Warning: ${file.tag} either image ${imageFileCache == null} or video ${videoFileCache == null} is missing from remoteLive",- );- return null;- }- })- .catchError((e) {- _logger.warning("failed to download live photos : ${file.tag}", e);- throw e;- });-}-Future<File?> _downloadAndCache(EnteFile file,BaseCacheManager cacheManager, {@@ -401,9 +319,3 @@ Future<void> clearCache(EnteFile file) async {}ThumbnailInMemoryLruCache.clearCache(file);}-class _LivePhoto {- final File image;- final File video;-- _LivePhoto(this.image, this.video);-}diff --git a/mobile/apps/photos/lib/module/live_photo/download.dart b/mobile/apps/photos/lib/module/live_photo/download.dartnew file mode 100644index 0000000000..376020720f--- /dev/null+++ b/mobile/apps/photos/lib/module/live_photo/download.dart@@ -0,0 +1,123 @@+import 'dart:io';++import 'package:dio/dio.dart';+import 'package:flutter/foundation.dart';+import 'package:flutter_cache_manager/flutter_cache_manager.dart';+import 'package:flutter_image_compress/flutter_image_compress.dart';+import 'package:logging/logging.dart';+import 'package:path/path.dart';+import 'package:photos/core/cache/video_cache_manager.dart';+import 'package:photos/core/configuration.dart';+import 'package:photos/models/file/file.dart';+import 'package:photos/module/download/decrypt.dart';+import 'package:photos/module/live_photo/archive.dart';++typedef LivePhotoFiles = ({File image, File video});++final _logger = Logger('FileUtil');++Future<LivePhotoFiles?> downloadLivePhotoFiles(+ EnteFile file, {+ ProgressCallback? progressCallback,+ bool forGalleryDownload = false,+}) async {+ File? decryptedFile;+ try {+ decryptedFile = await downloadAndDecrypt(+ file,+ progressCallback: progressCallback,+ forceResumableDownload: forGalleryDownload,+ throwOnFailure: forGalleryDownload,+ );+ if (decryptedFile == null) {+ return null;+ }+ _logger.info('Decoded zipped live photo from ${decryptedFile.path}');+ File? imageFileCache;+ File? videoFileCache;+ final parts = decodeLivePhotoArchive(await decryptedFile.readAsBytes());+ final tempPath = Configuration.instance.getTempDirectory();+ for (final part in parts) {+ final fileExtension = _fileExtension(part.fileName);+ final decodePath = '$tempPath${file.uploadedFileID}${part.fileName}';+ if (part.type == LivePhotoArchivePartType.image) {+ final imageFile = File(decodePath);+ await imageFile.create(recursive: true);+ await imageFile.writeAsBytes(part.bytes);+ File imageConvertedFile = imageFile;+ if (fileExtension == 'unknown' ||+ (Platform.isAndroid && fileExtension == 'heic')) {+ final compressResult = await FlutterImageCompress.compressAndGetFile(+ decodePath,+ '$decodePath.jpg',+ keepExif: true,+ );+ await imageFile.delete();+ if (compressResult == null) {+ throw Exception('Failed to compress file');+ }+ imageConvertedFile = File(compressResult.path);+ }+ imageFileCache = await DefaultCacheManager().putFile(+ file.downloadUrl,+ await imageConvertedFile.readAsBytes(),+ eTag: file.downloadUrl,+ maxAge: const Duration(days: 365),+ fileExtension: fileExtension,+ );+ await imageConvertedFile.delete();+ } else {+ final videoFile = File(decodePath);+ await videoFile.create(recursive: true);+ await videoFile.writeAsBytes(part.bytes);+ videoFileCache = await VideoCacheManager.instance.putFileStream(+ file.downloadUrl,+ videoFile.openRead(),+ eTag: file.downloadUrl,+ maxAge: const Duration(days: 365),+ fileExtension: fileExtension,+ );+ await videoFile.delete();+ }+ }+ if (imageFileCache != null && videoFileCache != null) {+ return (image: imageFileCache, video: videoFileCache);+ }+ debugPrint(+ 'Warning: ${file.tag} either image ${imageFileCache == null} or video ${videoFileCache == null} is missing from remoteLive',+ );+ return null;+ } catch (error, stackTrace) {+ _logger.warning(+ 'failed to download live photos : ${file.tag}',+ error,+ stackTrace,+ );+ rethrow;+ } finally {+ if (decryptedFile != null) {+ await _deleteDecryptedArchive(decryptedFile);+ }+ }+}++Future<void> _deleteDecryptedArchive(File file) async {+ try {+ await file.delete();+ } catch (error, stackTrace) {+ _logger.warning(+ 'Failed to delete decrypted live photo archive',+ error,+ stackTrace,+ );+ }+}++String _fileExtension(String nameOrPath) {+ try {+ return extension(nameOrPath).substring(1).toLowerCase();+ } catch (_) {+ _logger.severe('Could not capture file extension');+ return 'unknown';+ }+}diff --git a/mobile/apps/photos/lib/module/live_photo/upload.dart b/mobile/apps/photos/lib/module/live_photo/upload.dartnew file mode 100644index 0000000000..452b129fba--- /dev/null+++ b/mobile/apps/photos/lib/module/live_photo/upload.dart@@ -0,0 +1,64 @@+import 'dart:io';++import 'package:ente_crypto/ente_crypto.dart';+import 'package:ente_pure_utils/ente_pure_utils.dart'+ show deleteFileSystemEntityIfPresent;+import 'package:logging/logging.dart';+import 'package:motionphoto/motionphoto.dart';+import 'package:path/path.dart';+import 'package:photos/core/configuration.dart';+import 'package:photos/core/constants.dart';+import 'package:photos/core/errors.dart';+import 'package:photos/models/file/file.dart';+import 'package:photos/module/live_photo/archive.dart';+import 'package:uuid/uuid.dart';++typedef LivePhotoUploadData = ({+ File sourceFile,+ String fileHash,+ String zipHash,+});++final _logger = Logger('LivePhotoUpload');++/// Uploads may prepare several files concurrently. Keep this per-file pipeline+/// sequential to limit duplicate reads and I/O pressure. If Live Photo imports+/// become a bottleneck, profile the shared worker queue before parallelizing it.+Future<LivePhotoUploadData> prepareLivePhotoForUpload(+ EnteFile file,+ File imageFile,+ String imageHash,+) async {+ final videoFile = await Motionphoto.getLivePhotoFile(file.localID!);+ if (videoFile == null || !videoFile.existsSync()) {+ final message =+ 'missing livePhoto url for ${file.toString()} with subType ${file.fileSubType}';+ _logger.severe(message);+ throw InvalidFileError(message, InvalidReason.livePhotoVideoMissing);+ }++ final videoHash = CryptoUtil.bin2base64(await CryptoUtil.getHash(videoFile));+ final fileHash = '$imageHash$kLivePhotoHashSeparator$videoHash';+ final archivePath =+ '${Configuration.instance.getTempDirectory()}${const Uuid().v4()}_${file.generatedID}.elp';+ final archiveFile = File(archivePath);+ _logger.info('Creating zip for live photo from ${basename(archivePath)}');++ try {+ await createLivePhotoArchive(+ archivePath: archivePath,+ imagePath: imageFile.path,+ videoPath: videoFile.path,+ );+ // photo_manager can return the same iOS temp copy to concurrent upload or+ // hash-check paths, where cleanup may have already run.+ await deleteFileSystemEntityIfPresent(imageFile);+ final zipHash = CryptoUtil.bin2base64(+ await CryptoUtil.getHash(archiveFile),+ );+ return (sourceFile: archiveFile, fileHash: fileHash, zipHash: zipHash);+ } catch (_) {+ await deleteFileSystemEntityIfPresent(archiveFile);+ rethrow;+ }+}diff --git a/mobile/apps/photos/lib/module/upload/upload_data.dart b/mobile/apps/photos/lib/module/upload/upload_data.dartindex ca8465db66..d11f9e101a 100644--- a/mobile/apps/photos/lib/module/upload/upload_data.dart+++ b/mobile/apps/photos/lib/module/upload/upload_data.dart@@ -7,11 +7,9 @@ import "package:ente_pure_utils/ente_pure_utils.dart"show deleteFileSystemEntityIfPresent;import "package:exif_reader/exif_reader.dart";import 'package:logging/logging.dart';-import 'package:motionphoto/motionphoto.dart';import 'package:path/path.dart';import 'package:path_provider/path_provider.dart';import 'package:photo_manager/photo_manager.dart';-import 'package:photos/core/configuration.dart';import 'package:photos/core/constants.dart';import 'package:photos/core/errors.dart';import "package:photos/models/ffmpeg/ffprobe_props.dart";@@ -21,7 +19,7 @@ import 'package:photos/models/file/file_type.dart';import "package:photos/models/location/location.dart";import 'package:photos/module/download/file.dart';import 'package:photos/module/download/thumbnail.dart';-import "package:photos/module/live_photo/archive.dart";+import 'package:photos/module/live_photo/upload.dart';import "package:photos/module/metadata/exif.dart";import "package:photos/module/metadata/video.dart";import 'package:photos/module/upload/model/media_upload_data.dart';@@ -30,7 +28,6 @@ import "package:photos/src/rust/api/motion_photo_api.dart";import "package:photos/utils/apple_photos_errors.dart";import "package:photos/utils/embedded_media_location.dart";import "package:photos/utils/image_util.dart";-import "package:uuid/uuid.dart";import 'package:video_thumbnail/video_thumbnail.dart';final _logger = Logger("UploadData");@@ -117,37 +114,14 @@ Future<MediaUploadData> _getMediaUploadDataFromAssetFile(fileHash = CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));if (file.fileType == FileType.livePhoto && Platform.isIOS) {- final File? videoUrl = await Motionphoto.getLivePhotoFile(file.localID!);- if (videoUrl == null || !videoUrl.existsSync()) {- final String errMsg =- "missing livePhoto url for ${file.toString()} with subType ${file.fileSubType}";- _logger.severe(errMsg);- throw InvalidFileError(errMsg, InvalidReason.livePhotoVideoMissing);- }- final String livePhotoVideoHash = CryptoUtil.bin2base64(- await CryptoUtil.getHash(videoUrl),- );- // imgHash:vidHash- fileHash = '$fileHash$kLivePhotoHashSeparator$livePhotoVideoHash';- final tempPath = Configuration.instance.getTempDirectory();- // .elp -> ente live photo- final uniqueId = const Uuid().v4().toString();- final livePhotoPath = tempPath + uniqueId + "_${file.generatedID}.elp";- _logger.info(- "Creating zip for live photo from " + basename(livePhotoPath),+ final livePhoto = await prepareLivePhotoForUpload(+ file,+ sourceFile,+ fileHash,);- await createLivePhotoArchive(- archivePath: livePhotoPath,- imagePath: sourceFile.path,- videoPath: videoUrl.path,- );- // delete the temporary video and image copy (only in IOS)- if (Platform.isIOS) {- await sourceFile.delete();- }- // new sourceFile which needs to be uploaded- sourceFile = File(livePhotoPath);- zipHash = CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));+ sourceFile = livePhoto.sourceFile;+ fileHash = livePhoto.fileHash;+ zipHash = livePhoto.zipHash;}thumbnailData = await _getThumbnailForUpload(asset, file);