file_uploader_util.dart 5.0 KB

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