file_uploader_util.dart 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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:photo_manager/photo_manager.dart';
  9. import 'package:photos/core/configuration.dart';
  10. import 'package:photos/core/constants.dart';
  11. import 'package:photos/core/errors.dart';
  12. import 'package:photos/models/file.dart' as ente;
  13. import 'package:photos/models/file_type.dart';
  14. import 'package:photos/models/location.dart';
  15. import 'file_util.dart';
  16. final _logger = Logger("FileUtil");
  17. const kMaximumThumbnailCompressionAttempts = 2;
  18. class MediaUploadData {
  19. final io.File sourceFile;
  20. final Uint8List thumbnail;
  21. final bool isDeleted;
  22. MediaUploadData(this.sourceFile, this.thumbnail, this.isDeleted);
  23. }
  24. Future<MediaUploadData> getUploadDataFromEnteFile(ente.File file) async {
  25. if (file.isSharedMediaToAppSandbox()) {
  26. return await _getMediaUploadDataFromAppCache(file);
  27. } else {
  28. return await _getMediaUploadDataFromAssetFile(file);
  29. }
  30. }
  31. Future<MediaUploadData> _getMediaUploadDataFromAssetFile(ente.File file) async {
  32. io.File sourceFile;
  33. Uint8List thumbnailData;
  34. bool isDeleted;
  35. // The timeouts are to safeguard against https://github.com/CaiJingLong/flutter_photo_manager/issues/467
  36. final asset =
  37. await file.getAsset().timeout(Duration(seconds: 3)).catchError((e) async {
  38. if (e is TimeoutException) {
  39. _logger.info("Asset fetch timed out for " + file.toString());
  40. return await file.getAsset();
  41. } else {
  42. throw e;
  43. }
  44. });
  45. if (asset == null) {
  46. throw InvalidFileError();
  47. }
  48. sourceFile = await asset.originFile
  49. .timeout(Duration(seconds: 3))
  50. .catchError((e) async {
  51. if (e is TimeoutException) {
  52. _logger.info("Origin file fetch timed out for " + file.toString());
  53. return await asset.originFile;
  54. } else {
  55. throw e;
  56. }
  57. });
  58. if (!sourceFile.existsSync()) {
  59. throw InvalidFileError();
  60. }
  61. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  62. await _decorateEnteFileData(file, asset);
  63. if (file.fileType == FileType.livePhoto && io.Platform.isIOS) {
  64. final io.File videoUrl = await Motionphoto.getLivePhotoFile(file.localID);
  65. final tempPath = Configuration.instance.getTempDirectory();
  66. final zipFilePath = tempPath + file.generatedID.toString() + ".zip";
  67. _logger.fine("Uploading zipped live photo from " + zipFilePath);
  68. var encoder = ZipFileEncoder();
  69. encoder.create(zipFilePath);
  70. encoder.addFile(videoUrl, "video" + extension(videoUrl.path));
  71. encoder.addFile(sourceFile, "image" + extension(sourceFile.path));
  72. encoder.close();
  73. // delete the temporary video and image copy (only in IOS)
  74. if(io.Platform.isIOS) {
  75. sourceFile.deleteSync();
  76. }
  77. // new sourceFile which needs to be uploaded
  78. sourceFile = io.File(zipFilePath);
  79. }
  80. thumbnailData = await asset.thumbDataWithSize(
  81. kThumbnailLargeSize,
  82. kThumbnailLargeSize,
  83. quality: kThumbnailQuality,
  84. );
  85. if (thumbnailData == null) {
  86. throw InvalidFileError();
  87. }
  88. int compressionAttempts = 0;
  89. while (thumbnailData.length > kThumbnailDataLimit &&
  90. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  91. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  92. thumbnailData = await compressThumbnail(thumbnailData);
  93. _logger
  94. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  95. compressionAttempts++;
  96. }
  97. isDeleted = asset == null || !(await asset.exists);
  98. return MediaUploadData(sourceFile, thumbnailData, isDeleted);
  99. }
  100. Future<void> _decorateEnteFileData(ente.File file, AssetEntity asset) async {
  101. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  102. if (file.location == null ||
  103. (file.location.latitude == 0 && file.location.longitude == 0)) {
  104. final latLong = await asset.latlngAsync();
  105. file.location = Location(latLong.latitude, latLong.longitude);
  106. }
  107. if (file.title == null || file.title.isEmpty) {
  108. _logger.severe("Title was missing");
  109. file.title = await asset.titleAsync;
  110. }
  111. }
  112. Future<MediaUploadData> _getMediaUploadDataFromAppCache(ente.File file) async {
  113. io.File sourceFile;
  114. Uint8List thumbnailData;
  115. bool isDeleted = false;
  116. var localPath = getSharedMediaFilePath(file);
  117. sourceFile = io.File(localPath);
  118. if (!sourceFile.existsSync()) {
  119. _logger.warning("File doesn't exist in app sandbox");
  120. throw InvalidFileError();
  121. }
  122. thumbnailData = await getThumbnailFromInAppCacheFile(file);
  123. return MediaUploadData(sourceFile, thumbnailData, isDeleted);
  124. }
  125. Future<Uint8List> getThumbnailFromInAppCacheFile(ente.File file) async {
  126. var localFile = io.File(getSharedMediaFilePath(file));
  127. if (!localFile.existsSync()) {
  128. return null;
  129. }
  130. var thumbnailData = localFile.readAsBytesSync();
  131. int compressionAttempts = 0;
  132. while (thumbnailData.length > kThumbnailDataLimit &&
  133. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  134. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  135. thumbnailData = await compressThumbnail(thumbnailData);
  136. _logger
  137. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  138. compressionAttempts++;
  139. }
  140. return thumbnailData;
  141. }