file_uploader_util.dart 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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/file_util.dart';
  17. import 'package:video_thumbnail/video_thumbnail.dart';
  18. final _logger = Logger("FileUtil");
  19. const kMaximumThumbnailCompressionAttempts = 2;
  20. class MediaUploadData {
  21. final io.File sourceFile;
  22. final Uint8List thumbnail;
  23. final bool isDeleted;
  24. MediaUploadData(this.sourceFile, this.thumbnail, this.isDeleted);
  25. }
  26. Future<MediaUploadData> getUploadDataFromEnteFile(ente.File file) async {
  27. if (file.isSharedMediaToAppSandbox()) {
  28. return await _getMediaUploadDataFromAppCache(file);
  29. } else {
  30. return await _getMediaUploadDataFromAssetFile(file);
  31. }
  32. }
  33. Future<MediaUploadData> _getMediaUploadDataFromAssetFile(ente.File file) async {
  34. io.File sourceFile;
  35. Uint8List thumbnailData;
  36. bool isDeleted;
  37. // The timeouts are to safeguard against https://github.com/CaiJingLong/flutter_photo_manager/issues/467
  38. final asset =
  39. await file.getAsset().timeout(Duration(seconds: 3)).catchError((e) async {
  40. if (e is TimeoutException) {
  41. _logger.info("Asset fetch timed out for " + file.toString());
  42. return await file.getAsset();
  43. } else {
  44. throw e;
  45. }
  46. });
  47. if (asset == null) {
  48. throw InvalidFileError("asset is null");
  49. }
  50. sourceFile = await asset.originFile
  51. .timeout(Duration(seconds: 3))
  52. .catchError((e) async {
  53. if (e is TimeoutException) {
  54. _logger.info("Origin file fetch timed out for " + file.toString());
  55. return await asset.originFile;
  56. } else {
  57. throw e;
  58. }
  59. });
  60. if (sourceFile == null || !sourceFile.existsSync()) {
  61. throw InvalidFileError("source fill is null or do not exist");
  62. }
  63. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  64. await _decorateEnteFileData(file, asset);
  65. if (file.fileType == FileType.livePhoto && io.Platform.isIOS) {
  66. final io.File videoUrl = await Motionphoto.getLivePhotoFile(file.localID);
  67. if (videoUrl == null || !videoUrl.existsSync()) {
  68. String errMsg = "missing livePhoto url for " + file.toString();
  69. _logger.severe(errMsg);
  70. throw InvalidFileUploadState(errMsg);
  71. }
  72. final tempPath = Configuration.instance.getTempDirectory();
  73. // .elp -> ente live photo
  74. final livePhotoPath = tempPath + file.generatedID.toString() + ".elp";
  75. _logger.fine("Uploading zipped live photo from " + livePhotoPath);
  76. var encoder = ZipFileEncoder();
  77. encoder.create(livePhotoPath);
  78. encoder.addFile(videoUrl, "video" + extension(videoUrl.path));
  79. encoder.addFile(sourceFile, "image" + extension(sourceFile.path));
  80. encoder.close();
  81. // delete the temporary video and image copy (only in IOS)
  82. if (io.Platform.isIOS) {
  83. await sourceFile.delete();
  84. }
  85. // new sourceFile which needs to be uploaded
  86. sourceFile = io.File(livePhotoPath);
  87. }
  88. thumbnailData = await asset.thumbnailDataWithSize(
  89. ThumbnailSize(kThumbnailLargeSize, kThumbnailLargeSize),
  90. quality: kThumbnailQuality,
  91. );
  92. if (thumbnailData == null) {
  93. throw InvalidFileError("unable to get asset thumbData");
  94. }
  95. int compressionAttempts = 0;
  96. while (thumbnailData.length > kThumbnailDataLimit &&
  97. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  98. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  99. thumbnailData = await compressThumbnail(thumbnailData);
  100. _logger
  101. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  102. compressionAttempts++;
  103. }
  104. isDeleted = asset == null || !(await asset.exists);
  105. return MediaUploadData(sourceFile, thumbnailData, isDeleted);
  106. }
  107. Future<void> _decorateEnteFileData(ente.File file, AssetEntity asset) async {
  108. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  109. if (file.location == null ||
  110. (file.location.latitude == 0 && file.location.longitude == 0)) {
  111. final latLong = await asset.latlngAsync();
  112. file.location = Location(latLong.latitude, latLong.longitude);
  113. }
  114. if (file.title == null || file.title.isEmpty) {
  115. _logger.severe("Title was missing");
  116. file.title = await asset.titleAsync;
  117. }
  118. }
  119. Future<MediaUploadData> _getMediaUploadDataFromAppCache(ente.File file) async {
  120. io.File sourceFile;
  121. Uint8List thumbnailData;
  122. bool isDeleted = false;
  123. var localPath = getSharedMediaFilePath(file);
  124. sourceFile = io.File(localPath);
  125. if (!sourceFile.existsSync()) {
  126. _logger.warning("File doesn't exist in app sandbox");
  127. throw InvalidFileError("File doesn't exist in app sandbox");
  128. }
  129. try {
  130. thumbnailData = await getThumbnailFromInAppCacheFile(file);
  131. return MediaUploadData(sourceFile, thumbnailData, isDeleted);
  132. } catch (e, s) {
  133. _logger.severe("failed to generate thumbnail", e, s);
  134. throw InvalidFileError(
  135. "thumbnail generation failed for fileType: ${file.fileType.toString()}");
  136. }
  137. }
  138. Future<Uint8List> getThumbnailFromInAppCacheFile(ente.File file) async {
  139. var localFile = io.File(getSharedMediaFilePath(file));
  140. if (!localFile.existsSync()) {
  141. return null;
  142. }
  143. if (file.fileType == FileType.video) {
  144. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  145. video: localFile.path,
  146. imageFormat: ImageFormat.JPEG,
  147. thumbnailPath: (await getTemporaryDirectory()).path,
  148. maxWidth: kThumbnailLargeSize,
  149. quality: 80,
  150. );
  151. localFile = io.File(thumbnailFilePath);
  152. }
  153. var thumbnailData = await localFile.readAsBytes();
  154. int compressionAttempts = 0;
  155. while (thumbnailData.length > kThumbnailDataLimit &&
  156. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  157. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  158. thumbnailData = await compressThumbnail(thumbnailData);
  159. _logger
  160. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  161. compressionAttempts++;
  162. }
  163. return thumbnailData;
  164. }