file_uploader_util.dart 7.5 KB

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