file_uploader_util.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import 'dart:async';
  2. import "dart:convert";
  3. import 'dart:io' as io;
  4. import 'dart:typed_data';
  5. import 'dart:ui' as ui;
  6. import 'package:archive/archive_io.dart';
  7. import 'package:logging/logging.dart';
  8. import 'package:motionphoto/motionphoto.dart';
  9. import 'package:path/path.dart';
  10. import 'package:path_provider/path_provider.dart';
  11. import 'package:photo_manager/photo_manager.dart';
  12. import 'package:photos/core/configuration.dart';
  13. import 'package:photos/core/constants.dart';
  14. import 'package:photos/core/errors.dart';
  15. import 'package:photos/models/file.dart' as ente;
  16. import 'package:photos/models/file_type.dart';
  17. import 'package:photos/models/location.dart';
  18. import "package:photos/models/magic_metadata.dart";
  19. import "package:photos/services/file_magic_service.dart";
  20. import 'package:photos/utils/crypto_util.dart';
  21. import 'package:photos/utils/file_util.dart';
  22. import 'package:video_thumbnail/video_thumbnail.dart';
  23. final _logger = Logger("FileUtil");
  24. const kMaximumThumbnailCompressionAttempts = 2;
  25. const kLivePhotoHashSeparator = ':';
  26. class MediaUploadData {
  27. final io.File? sourceFile;
  28. final Uint8List? thumbnail;
  29. final bool isDeleted;
  30. final FileHashData? hashData;
  31. final int? height;
  32. final int? width;
  33. MediaUploadData(
  34. this.sourceFile,
  35. this.thumbnail,
  36. this.isDeleted,
  37. this.hashData, {
  38. this.height,
  39. this.width,
  40. });
  41. }
  42. class FileHashData {
  43. // For livePhotos, the fileHash value will be imageHash:videoHash
  44. final String? fileHash;
  45. // zipHash is used to take care of existing live photo uploads from older
  46. // mobile clients
  47. String? zipHash;
  48. FileHashData(this.fileHash, {this.zipHash});
  49. }
  50. Future<MediaUploadData> getUploadDataFromEnteFile(ente.File file) async {
  51. if (file.isSharedMediaToAppSandbox) {
  52. return await _getMediaUploadDataFromAppCache(file);
  53. } else {
  54. return await _getMediaUploadDataFromAssetFile(file);
  55. }
  56. }
  57. Future<MediaUploadData> _getMediaUploadDataFromAssetFile(ente.File file) async {
  58. io.File? sourceFile;
  59. Uint8List? thumbnailData;
  60. bool isDeleted;
  61. String? zipHash;
  62. String fileHash;
  63. // The timeouts are to safeguard against https://github.com/CaiJingLong/flutter_photo_manager/issues/467
  64. final asset = await file.getAsset
  65. .timeout(const Duration(seconds: 3))
  66. .catchError((e) async {
  67. if (e is TimeoutException) {
  68. _logger.info("Asset fetch timed out for " + file.toString());
  69. return await file.getAsset;
  70. } else {
  71. throw e;
  72. }
  73. });
  74. if (asset == null) {
  75. throw InvalidFileError("asset is null");
  76. }
  77. sourceFile = await asset.originFile
  78. .timeout(const Duration(seconds: 3))
  79. .catchError((e) async {
  80. if (e is TimeoutException) {
  81. _logger.info("Origin file fetch timed out for " + file.toString());
  82. return await asset.originFile;
  83. } else {
  84. throw e;
  85. }
  86. });
  87. if (sourceFile == null || !sourceFile.existsSync()) {
  88. throw InvalidFileError("source fill is null or do not exist");
  89. }
  90. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  91. await _decorateEnteFileData(file, asset);
  92. fileHash = CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
  93. if (file.fileType == FileType.livePhoto && io.Platform.isIOS) {
  94. final io.File? videoUrl = await Motionphoto.getLivePhotoFile(file.localID!);
  95. if (videoUrl == null || !videoUrl.existsSync()) {
  96. final String errMsg =
  97. "missing livePhoto url for ${file.toString()} with subType ${file.fileSubType}";
  98. _logger.severe(errMsg);
  99. throw InvalidFileUploadState(errMsg);
  100. }
  101. final String livePhotoVideoHash =
  102. CryptoUtil.bin2base64(await CryptoUtil.getHash(videoUrl));
  103. // imgHash:vidHash
  104. fileHash = '$fileHash$kLivePhotoHashSeparator$livePhotoVideoHash';
  105. final tempPath = Configuration.instance.getTempDirectory();
  106. // .elp -> ente live photo
  107. final livePhotoPath = tempPath + file.generatedID.toString() + ".elp";
  108. _logger.fine("Uploading zipped live photo from " + livePhotoPath);
  109. final encoder = ZipFileEncoder();
  110. encoder.create(livePhotoPath);
  111. encoder.addFile(videoUrl, "video" + extension(videoUrl.path));
  112. encoder.addFile(sourceFile, "image" + extension(sourceFile.path));
  113. encoder.close();
  114. // delete the temporary video and image copy (only in IOS)
  115. if (io.Platform.isIOS) {
  116. await sourceFile.delete();
  117. }
  118. // new sourceFile which needs to be uploaded
  119. sourceFile = io.File(livePhotoPath);
  120. zipHash = CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
  121. }
  122. thumbnailData = await asset.thumbnailDataWithSize(
  123. const ThumbnailSize(thumbnailLargeSize, thumbnailLargeSize),
  124. quality: thumbnailQuality,
  125. );
  126. if (thumbnailData == null) {
  127. throw InvalidFileError("unable to get asset thumbData");
  128. }
  129. int compressionAttempts = 0;
  130. while (thumbnailData!.length > thumbnailDataLimit &&
  131. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  132. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  133. thumbnailData = await compressThumbnail(thumbnailData);
  134. _logger
  135. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  136. compressionAttempts++;
  137. }
  138. isDeleted = !(await asset.exists);
  139. int? h, w;
  140. if (asset.width != 0 && asset.height != 0) {
  141. h = asset.height;
  142. w = asset.width;
  143. }
  144. return MediaUploadData(
  145. sourceFile,
  146. thumbnailData,
  147. isDeleted,
  148. FileHashData(fileHash, zipHash: zipHash),
  149. height: h,
  150. width: w,
  151. );
  152. }
  153. Future<void> _decorateEnteFileData(ente.File file, AssetEntity asset) async {
  154. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  155. if (file.location == null ||
  156. (file.location!.latitude == 0 && file.location!.longitude == 0)) {
  157. final latLong = await asset.latlngAsync();
  158. file.location = Location(latLong.latitude, latLong.longitude);
  159. }
  160. if (file.title == null || file.title!.isEmpty) {
  161. _logger.warning("Title was missing ${file.tag}");
  162. file.title = await asset.titleAsync;
  163. }
  164. }
  165. Future<MetadataRequest> getPubMetadataRequest(
  166. ente.File file,
  167. Map<String, dynamic> newData,
  168. Uint8List fileKey,
  169. ) async {
  170. final Map<String, dynamic> jsonToUpdate =
  171. jsonDecode(file.pubMmdEncodedJson ?? '{}');
  172. newData.forEach((key, value) {
  173. jsonToUpdate[key] = value;
  174. });
  175. // update the local information so that it's reflected on UI
  176. file.pubMmdEncodedJson = jsonEncode(jsonToUpdate);
  177. file.pubMagicMetadata = PubMagicMetadata.fromJson(jsonToUpdate);
  178. final encryptedMMd = await CryptoUtil.encryptChaCha(
  179. utf8.encode(jsonEncode(jsonToUpdate)) as Uint8List,
  180. fileKey,
  181. );
  182. return MetadataRequest(
  183. version: file.pubMmdVersion,
  184. count: jsonToUpdate.length,
  185. data: CryptoUtil.bin2base64(encryptedMMd.encryptedData!),
  186. header: CryptoUtil.bin2base64(encryptedMMd.header!),
  187. );
  188. }
  189. Future<MediaUploadData> _getMediaUploadDataFromAppCache(ente.File file) async {
  190. io.File sourceFile;
  191. Uint8List? thumbnailData;
  192. const bool isDeleted = false;
  193. final localPath = getSharedMediaFilePath(file);
  194. sourceFile = io.File(localPath);
  195. if (!sourceFile.existsSync()) {
  196. _logger.warning("File doesn't exist in app sandbox");
  197. throw InvalidFileError("File doesn't exist in app sandbox");
  198. }
  199. try {
  200. thumbnailData = await getThumbnailFromInAppCacheFile(file);
  201. final fileHash =
  202. CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
  203. Map<String, int>? dimensions;
  204. if (file.fileType == FileType.image) {
  205. dimensions = await getImageHeightAndWith(imagePath: localPath);
  206. } else {
  207. // for video, we need to use the thumbnail data with any max width/height
  208. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  209. video: localPath,
  210. imageFormat: ImageFormat.JPEG,
  211. thumbnailPath: (await getTemporaryDirectory()).path,
  212. quality: 10,
  213. );
  214. dimensions = await getImageHeightAndWith(imagePath: thumbnailFilePath);
  215. }
  216. return MediaUploadData(
  217. sourceFile,
  218. thumbnailData,
  219. isDeleted,
  220. FileHashData(fileHash),
  221. height: dimensions?['height'],
  222. width: dimensions?['width'],
  223. );
  224. } catch (e, s) {
  225. _logger.severe("failed to generate thumbnail", e, s);
  226. throw InvalidFileError(
  227. "thumbnail generation failed for fileType: ${file.fileType.toString()}",
  228. );
  229. }
  230. }
  231. Future<Map<String, int>?> getImageHeightAndWith({
  232. String? imagePath,
  233. Uint8List? imageBytes,
  234. }) async {
  235. if (imagePath == null && imageBytes == null) {
  236. throw ArgumentError("imagePath and imageBytes cannot be null");
  237. }
  238. try {
  239. late Uint8List bytes;
  240. if (imagePath != null) {
  241. final io.File imageFile = io.File(imagePath);
  242. bytes = await imageFile.readAsBytes();
  243. } else {
  244. bytes = imageBytes!;
  245. }
  246. final ui.Codec codec = await ui.instantiateImageCodec(bytes);
  247. final ui.FrameInfo frameInfo = await codec.getNextFrame();
  248. if (frameInfo.image.width == 0 || frameInfo.image.height == 0) {
  249. return null;
  250. } else {
  251. return {
  252. "width": frameInfo.image.width,
  253. "height": frameInfo.image.height,
  254. };
  255. }
  256. } catch (e) {
  257. _logger.severe("Failed to get image size", e);
  258. return null;
  259. }
  260. }
  261. Future<Uint8List?> getThumbnailFromInAppCacheFile(ente.File file) async {
  262. var localFile = io.File(getSharedMediaFilePath(file));
  263. if (!localFile.existsSync()) {
  264. return null;
  265. }
  266. if (file.fileType == FileType.video) {
  267. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  268. video: localFile.path,
  269. imageFormat: ImageFormat.JPEG,
  270. thumbnailPath: (await getTemporaryDirectory()).path,
  271. maxWidth: thumbnailLargeSize,
  272. quality: 80,
  273. );
  274. localFile = io.File(thumbnailFilePath!);
  275. }
  276. var thumbnailData = await localFile.readAsBytes();
  277. int compressionAttempts = 0;
  278. while (thumbnailData.length > thumbnailDataLimit &&
  279. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  280. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  281. thumbnailData = await compressThumbnail(thumbnailData);
  282. _logger
  283. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  284. compressionAttempts++;
  285. }
  286. return thumbnailData;
  287. }