file_uploader_util.dart 7.4 KB

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