file_uploader_util.dart 6.4 KB

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