file_uploader_util.dart 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import 'dart:async';
  2. import 'dart:io' as io;
  3. import 'dart:typed_data';
  4. import 'package:archive/archive_io.dart';
  5. import 'package:flutter_sodium/flutter_sodium.dart';
  6. import 'package:logging/logging.dart';
  7. import 'package:motionphoto/motionphoto.dart';
  8. import 'package:path/path.dart';
  9. import 'package:path_provider/path_provider.dart';
  10. import 'package:photo_manager/photo_manager.dart';
  11. import 'package:photos/core/configuration.dart';
  12. import 'package:photos/core/constants.dart';
  13. import 'package:photos/core/errors.dart';
  14. import 'package:photos/models/file.dart' as ente;
  15. import 'package:photos/models/file_type.dart';
  16. import 'package:photos/models/location.dart';
  17. import 'package:photos/utils/crypto_util.dart';
  18. import 'package:photos/utils/file_util.dart';
  19. import 'package:video_thumbnail/video_thumbnail.dart';
  20. final _logger = Logger("FileUtil");
  21. const kMaximumThumbnailCompressionAttempts = 2;
  22. class MediaUploadData {
  23. final io.File sourceFile;
  24. final Uint8List thumbnail;
  25. final bool isDeleted;
  26. final FileHashData hashData;
  27. MediaUploadData(
  28. this.sourceFile,
  29. this.thumbnail,
  30. this.isDeleted, {
  31. this.hashData,
  32. });
  33. }
  34. class FileHashData {
  35. // For livePhotos, the fileHash value will be imageHash:videoHash
  36. final String fileHash;
  37. // zipHash is used to take care of existing live photo uploads from older
  38. // mobile clients
  39. String zipHash;
  40. FileHashData(this.fileHash, {this.zipHash});
  41. }
  42. Future<MediaUploadData> getUploadDataFromEnteFile(ente.File file) async {
  43. if (file.isSharedMediaToAppSandbox()) {
  44. return await _getMediaUploadDataFromAppCache(file);
  45. } else {
  46. return await _getMediaUploadDataFromAssetFile(file);
  47. }
  48. }
  49. Future<MediaUploadData> _getMediaUploadDataFromAssetFile(ente.File file) async {
  50. io.File sourceFile;
  51. Uint8List thumbnailData;
  52. bool isDeleted;
  53. String fileHash, zipHash;
  54. // The timeouts are to safeguard against https://github.com/CaiJingLong/flutter_photo_manager/issues/467
  55. final asset = await file
  56. .getAsset()
  57. .timeout(const Duration(seconds: 3))
  58. .catchError((e) async {
  59. if (e is TimeoutException) {
  60. _logger.info("Asset fetch timed out for " + file.toString());
  61. return await file.getAsset();
  62. } else {
  63. throw e;
  64. }
  65. });
  66. if (asset == null) {
  67. throw InvalidFileError("asset is null");
  68. }
  69. sourceFile = await asset.originFile
  70. .timeout(const Duration(seconds: 3))
  71. .catchError((e) async {
  72. if (e is TimeoutException) {
  73. _logger.info("Origin file fetch timed out for " + file.toString());
  74. return await asset.originFile;
  75. } else {
  76. throw e;
  77. }
  78. });
  79. if (sourceFile == null || !sourceFile.existsSync()) {
  80. throw InvalidFileError("source fill is null or do not exist");
  81. }
  82. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  83. await _decorateEnteFileData(file, asset);
  84. fileHash = Sodium.bin2base64(await CryptoUtil.getHash(sourceFile));
  85. if (file.fileType == FileType.livePhoto && io.Platform.isIOS) {
  86. final io.File videoUrl = await Motionphoto.getLivePhotoFile(file.localID);
  87. if (videoUrl == null || !videoUrl.existsSync()) {
  88. String errMsg =
  89. "missing livePhoto url for ${file.toString()} with subType ${file.fileSubType}";
  90. _logger.severe(errMsg);
  91. throw InvalidFileUploadState(errMsg);
  92. }
  93. String livePhotoVideoHash =
  94. Sodium.bin2base64(await CryptoUtil.getHash(videoUrl));
  95. fileHash = '$fileHash:$livePhotoVideoHash';
  96. final tempPath = Configuration.instance.getTempDirectory();
  97. // .elp -> ente live photo
  98. final livePhotoPath = tempPath + file.generatedID.toString() + ".elp";
  99. _logger.fine("Uploading zipped live photo from " + livePhotoPath);
  100. var encoder = ZipFileEncoder();
  101. encoder.create(livePhotoPath);
  102. encoder.addFile(videoUrl, "video" + extension(videoUrl.path));
  103. encoder.addFile(sourceFile, "image" + extension(sourceFile.path));
  104. encoder.close();
  105. // delete the temporary video and image copy (only in IOS)
  106. if (io.Platform.isIOS) {
  107. await sourceFile.delete();
  108. }
  109. // new sourceFile which needs to be uploaded
  110. sourceFile = io.File(livePhotoPath);
  111. zipHash = Sodium.bin2base64(await CryptoUtil.getHash(sourceFile));
  112. }
  113. thumbnailData = await asset.thumbnailDataWithSize(
  114. const ThumbnailSize(kThumbnailLargeSize, kThumbnailLargeSize),
  115. quality: kThumbnailQuality,
  116. );
  117. if (thumbnailData == null) {
  118. throw InvalidFileError("unable to get asset thumbData");
  119. }
  120. int compressionAttempts = 0;
  121. while (thumbnailData.length > kThumbnailDataLimit &&
  122. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  123. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  124. thumbnailData = await compressThumbnail(thumbnailData);
  125. _logger
  126. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  127. compressionAttempts++;
  128. }
  129. isDeleted = asset == null || !(await asset.exists);
  130. return MediaUploadData(
  131. sourceFile,
  132. thumbnailData,
  133. isDeleted,
  134. hashData: FileHashData(fileHash, zipHash: zipHash),
  135. );
  136. }
  137. Future<void> _decorateEnteFileData(ente.File file, AssetEntity asset) async {
  138. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  139. if (file.location == null ||
  140. (file.location.latitude == 0 && file.location.longitude == 0)) {
  141. final latLong = await asset.latlngAsync();
  142. file.location = Location(latLong.latitude, latLong.longitude);
  143. }
  144. if (file.title == null || file.title.isEmpty) {
  145. _logger.warning("Title was missing ${file.tag()}");
  146. file.title = await asset.titleAsync;
  147. }
  148. }
  149. Future<MediaUploadData> _getMediaUploadDataFromAppCache(ente.File file) async {
  150. io.File sourceFile;
  151. Uint8List thumbnailData;
  152. bool isDeleted = false;
  153. var localPath = getSharedMediaFilePath(file);
  154. sourceFile = io.File(localPath);
  155. if (!sourceFile.existsSync()) {
  156. _logger.warning("File doesn't exist in app sandbox");
  157. throw InvalidFileError("File doesn't exist in app sandbox");
  158. }
  159. try {
  160. thumbnailData = await getThumbnailFromInAppCacheFile(file);
  161. return MediaUploadData(sourceFile, thumbnailData, isDeleted);
  162. } catch (e, s) {
  163. _logger.severe("failed to generate thumbnail", e, s);
  164. throw InvalidFileError(
  165. "thumbnail generation failed for fileType: ${file.fileType.toString()}",
  166. );
  167. }
  168. }
  169. Future<Uint8List> getThumbnailFromInAppCacheFile(ente.File file) async {
  170. var localFile = io.File(getSharedMediaFilePath(file));
  171. if (!localFile.existsSync()) {
  172. return null;
  173. }
  174. if (file.fileType == FileType.video) {
  175. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  176. video: localFile.path,
  177. imageFormat: ImageFormat.JPEG,
  178. thumbnailPath: (await getTemporaryDirectory()).path,
  179. maxWidth: kThumbnailLargeSize,
  180. quality: 80,
  181. );
  182. localFile = io.File(thumbnailFilePath);
  183. }
  184. var thumbnailData = await localFile.readAsBytes();
  185. int compressionAttempts = 0;
  186. while (thumbnailData.length > kThumbnailDataLimit &&
  187. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  188. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  189. thumbnailData = await compressThumbnail(thumbnailData);
  190. _logger
  191. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  192. compressionAttempts++;
  193. }
  194. return thumbnailData;
  195. }