file_uploader_util.dart 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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:logging/logging.dart';
  6. import 'package:motionphoto/motionphoto.dart';
  7. import 'package:path/path.dart';
  8. import 'package:path_provider/path_provider.dart';
  9. import 'package:photo_manager/photo_manager.dart';
  10. import 'package:photos/core/configuration.dart';
  11. import 'package:photos/core/constants.dart';
  12. import 'package:photos/core/errors.dart';
  13. import 'package:photos/models/file.dart' as ente;
  14. import 'package:photos/models/file_type.dart';
  15. import 'package:photos/models/location.dart';
  16. import 'package:photos/utils/crypto_util.dart';
  17. import 'package:photos/utils/file_util.dart';
  18. import 'package:video_thumbnail/video_thumbnail.dart';
  19. final _logger = Logger("FileUtil");
  20. const kMaximumThumbnailCompressionAttempts = 2;
  21. const kLivePhotoHashSeparator = ':';
  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? zipHash;
  54. String fileHash;
  55. // The timeouts are to safeguard against https://github.com/CaiJingLong/flutter_photo_manager/issues/467
  56. final asset = await file.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 = CryptoUtil.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. final String errMsg =
  89. "missing livePhoto url for ${file.toString()} with subType ${file.fileSubType}";
  90. _logger.severe(errMsg);
  91. throw InvalidFileUploadState(errMsg);
  92. }
  93. final String livePhotoVideoHash =
  94. CryptoUtil.bin2base64(await CryptoUtil.getHash(videoUrl));
  95. // imgHash:vidHash
  96. fileHash = '$fileHash$kLivePhotoHashSeparator$livePhotoVideoHash';
  97. final tempPath = Configuration.instance.getTempDirectory();
  98. // .elp -> ente live photo
  99. final livePhotoPath = tempPath + file.generatedID.toString() + ".elp";
  100. _logger.fine("Uploading zipped live photo from " + livePhotoPath);
  101. final encoder = ZipFileEncoder();
  102. encoder.create(livePhotoPath);
  103. encoder.addFile(videoUrl, "video" + extension(videoUrl.path));
  104. encoder.addFile(sourceFile, "image" + extension(sourceFile.path));
  105. encoder.close();
  106. // delete the temporary video and image copy (only in IOS)
  107. if (io.Platform.isIOS) {
  108. await sourceFile.delete();
  109. }
  110. // new sourceFile which needs to be uploaded
  111. sourceFile = io.File(livePhotoPath);
  112. zipHash = CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
  113. }
  114. thumbnailData = await asset.thumbnailDataWithSize(
  115. const ThumbnailSize(thumbnailLargeSize, thumbnailLargeSize),
  116. quality: thumbnailQuality,
  117. );
  118. if (thumbnailData == null) {
  119. throw InvalidFileError("unable to get asset thumbData");
  120. }
  121. int compressionAttempts = 0;
  122. while (thumbnailData!.length > thumbnailDataLimit &&
  123. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  124. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  125. thumbnailData = await compressThumbnail(thumbnailData);
  126. _logger
  127. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  128. compressionAttempts++;
  129. }
  130. isDeleted = !(await asset.exists);
  131. return MediaUploadData(
  132. sourceFile,
  133. thumbnailData,
  134. isDeleted,
  135. FileHashData(fileHash, zipHash: zipHash),
  136. );
  137. }
  138. Future<void> _decorateEnteFileData(ente.File file, AssetEntity asset) async {
  139. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  140. if (file.location == null ||
  141. (file.location!.latitude == 0 && file.location!.longitude == 0)) {
  142. final latLong = await asset.latlngAsync();
  143. file.location = Location(latLong.latitude, latLong.longitude);
  144. }
  145. if (file.title == null || file.title!.isEmpty) {
  146. _logger.warning("Title was missing ${file.tag}");
  147. file.title = await asset.titleAsync;
  148. }
  149. }
  150. Future<MediaUploadData> _getMediaUploadDataFromAppCache(ente.File file) async {
  151. io.File sourceFile;
  152. Uint8List? thumbnailData;
  153. const bool isDeleted = false;
  154. final localPath = getSharedMediaFilePath(file);
  155. sourceFile = io.File(localPath);
  156. if (!sourceFile.existsSync()) {
  157. _logger.warning("File doesn't exist in app sandbox");
  158. throw InvalidFileError("File doesn't exist in app sandbox");
  159. }
  160. try {
  161. thumbnailData = await getThumbnailFromInAppCacheFile(file);
  162. final fileHash = CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
  163. return MediaUploadData(
  164. sourceFile,
  165. thumbnailData,
  166. isDeleted,
  167. FileHashData(fileHash),
  168. );
  169. } catch (e, s) {
  170. _logger.severe("failed to generate thumbnail", e, s);
  171. throw InvalidFileError(
  172. "thumbnail generation failed for fileType: ${file.fileType.toString()}",
  173. );
  174. }
  175. }
  176. Future<Uint8List?> getThumbnailFromInAppCacheFile(ente.File file) async {
  177. var localFile = io.File(getSharedMediaFilePath(file));
  178. if (!localFile.existsSync()) {
  179. return null;
  180. }
  181. if (file.fileType == FileType.video) {
  182. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  183. video: localFile.path,
  184. imageFormat: ImageFormat.JPEG,
  185. thumbnailPath: (await getTemporaryDirectory()).path,
  186. maxWidth: thumbnailLargeSize,
  187. quality: 80,
  188. );
  189. localFile = io.File(thumbnailFilePath!);
  190. }
  191. var thumbnailData = await localFile.readAsBytes();
  192. int compressionAttempts = 0;
  193. while (thumbnailData.length > thumbnailDataLimit &&
  194. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  195. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  196. thumbnailData = await compressThumbnail(thumbnailData);
  197. _logger
  198. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  199. compressionAttempts++;
  200. }
  201. return thumbnailData;
  202. }