file_uploader_util.dart 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. kThumbnailSmallSize,
  82. kThumbnailSmallSize,
  83. quality: kThumbnailQuality,
  84. );
  85. int compressionAttempts = 0;
  86. while (thumbnailData.length > kThumbnailDataLimit &&
  87. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  88. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  89. thumbnailData = await compressThumbnail(thumbnailData);
  90. _logger
  91. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  92. compressionAttempts++;
  93. }
  94. isDeleted = asset == null || !(await asset.exists);
  95. return MediaUploadData(sourceFile, thumbnailData, isDeleted);
  96. }
  97. Future<void> _decorateEnteFileData(ente.File file, AssetEntity asset) async {
  98. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  99. if (file.location == null ||
  100. (file.location.latitude == 0 && file.location.longitude == 0)) {
  101. final latLong = await asset.latlngAsync();
  102. file.location = Location(latLong.latitude, latLong.longitude);
  103. }
  104. if (file.title == null || file.title.isEmpty) {
  105. _logger.severe("Title was missing");
  106. file.title = await asset.titleAsync;
  107. }
  108. }
  109. Future<MediaUploadData> _getMediaUploadDataFromAppCache(ente.File file) async {
  110. io.File sourceFile;
  111. Uint8List thumbnailData;
  112. bool isDeleted = false;
  113. var localPath = getSharedMediaFilePath(file);
  114. sourceFile = io.File(localPath);
  115. if (!sourceFile.existsSync()) {
  116. _logger.warning("File doesn't exist in app sandbox");
  117. throw InvalidFileError();
  118. }
  119. thumbnailData = await getThumbnailFromInAppCacheFile(file);
  120. return MediaUploadData(sourceFile, thumbnailData, isDeleted);
  121. }
  122. Future<Uint8List> getThumbnailFromInAppCacheFile(ente.File file) async {
  123. var localFile = io.File(getSharedMediaFilePath(file));
  124. if (!localFile.existsSync()) {
  125. return null;
  126. }
  127. var thumbnailData = localFile.readAsBytesSync();
  128. int compressionAttempts = 0;
  129. while (thumbnailData.length > kThumbnailDataLimit &&
  130. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  131. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  132. thumbnailData = await compressThumbnail(thumbnailData);
  133. _logger
  134. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  135. compressionAttempts++;
  136. }
  137. return thumbnailData;
  138. }