file_uploader_util.dart 12 KB

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