file_uploader_util.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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}',
  186. InvalidReason.livePhotoToImageTypeChanged,
  187. );
  188. } else if (assetType == FileType.livePhoto &&
  189. file.fileType == FileType.image) {
  190. throw InvalidFileError(
  191. 'id ${asset.id}',
  192. InvalidReason.imageToLivePhotoTypeChanged,
  193. );
  194. }
  195. }
  196. throw InvalidFileError(
  197. 'fileType mismatch for id ${asset.id} assetType $assetType fileType ${file.fileType}',
  198. InvalidReason.unknown,
  199. );
  200. }
  201. Future<void> _decorateEnteFileData(ente.File file, AssetEntity asset) async {
  202. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  203. if (file.location == null ||
  204. (file.location!.latitude == 0 && file.location!.longitude == 0)) {
  205. final latLong = await asset.latlngAsync();
  206. file.location =
  207. Location(latitude: latLong.latitude, longitude: latLong.longitude);
  208. }
  209. if (file.title == null || file.title!.isEmpty) {
  210. _logger.warning("Title was missing ${file.tag}");
  211. file.title = await asset.titleAsync;
  212. }
  213. }
  214. Future<MetadataRequest> getPubMetadataRequest(
  215. ente.File file,
  216. Map<String, dynamic> newData,
  217. Uint8List fileKey,
  218. ) async {
  219. final Map<String, dynamic> jsonToUpdate =
  220. jsonDecode(file.pubMmdEncodedJson ?? '{}');
  221. newData.forEach((key, value) {
  222. jsonToUpdate[key] = value;
  223. });
  224. // update the local information so that it's reflected on UI
  225. file.pubMmdEncodedJson = jsonEncode(jsonToUpdate);
  226. file.pubMagicMetadata = PubMagicMetadata.fromJson(jsonToUpdate);
  227. final encryptedMMd = await CryptoUtil.encryptChaCha(
  228. utf8.encode(jsonEncode(jsonToUpdate)) as Uint8List,
  229. fileKey,
  230. );
  231. return MetadataRequest(
  232. version: file.pubMmdVersion == 0 ? 1 : file.pubMmdVersion,
  233. count: jsonToUpdate.length,
  234. data: CryptoUtil.bin2base64(encryptedMMd.encryptedData!),
  235. header: CryptoUtil.bin2base64(encryptedMMd.header!),
  236. );
  237. }
  238. Future<MediaUploadData> _getMediaUploadDataFromAppCache(ente.File file) async {
  239. io.File sourceFile;
  240. Uint8List? thumbnailData;
  241. const bool isDeleted = false;
  242. final localPath = getSharedMediaFilePath(file);
  243. sourceFile = io.File(localPath);
  244. if (!sourceFile.existsSync()) {
  245. _logger.warning("File doesn't exist in app sandbox");
  246. throw InvalidFileError(
  247. "source missing in sandbox",
  248. InvalidReason.sourceFileMissing,
  249. );
  250. }
  251. try {
  252. thumbnailData = await getThumbnailFromInAppCacheFile(file);
  253. final fileHash =
  254. CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
  255. Map<String, int>? dimensions;
  256. if (file.fileType == FileType.image) {
  257. dimensions = await getImageHeightAndWith(imagePath: localPath);
  258. } else {
  259. // for video, we need to use the thumbnail data with any max width/height
  260. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  261. video: localPath,
  262. imageFormat: ImageFormat.JPEG,
  263. thumbnailPath: (await getTemporaryDirectory()).path,
  264. quality: 10,
  265. );
  266. dimensions = await getImageHeightAndWith(imagePath: thumbnailFilePath);
  267. }
  268. return MediaUploadData(
  269. sourceFile,
  270. thumbnailData,
  271. isDeleted,
  272. FileHashData(fileHash),
  273. height: dimensions?['height'],
  274. width: dimensions?['width'],
  275. );
  276. } catch (e, s) {
  277. _logger.severe("failed to generate thumbnail", e, s);
  278. throw InvalidFileError(
  279. "thumbnail failed for appCache fileType: ${file.fileType.toString()}",
  280. InvalidReason.thumbnailMissing,
  281. );
  282. }
  283. }
  284. Future<Map<String, int>?> getImageHeightAndWith({
  285. String? imagePath,
  286. Uint8List? imageBytes,
  287. }) async {
  288. if (imagePath == null && imageBytes == null) {
  289. throw ArgumentError("imagePath and imageBytes cannot be null");
  290. }
  291. try {
  292. late Uint8List bytes;
  293. if (imagePath != null) {
  294. final io.File imageFile = io.File(imagePath);
  295. bytes = await imageFile.readAsBytes();
  296. } else {
  297. bytes = imageBytes!;
  298. }
  299. final ui.Codec codec = await ui.instantiateImageCodec(bytes);
  300. final ui.FrameInfo frameInfo = await codec.getNextFrame();
  301. if (frameInfo.image.width == 0 || frameInfo.image.height == 0) {
  302. return null;
  303. } else {
  304. return {
  305. "width": frameInfo.image.width,
  306. "height": frameInfo.image.height,
  307. };
  308. }
  309. } catch (e) {
  310. _logger.severe("Failed to get image size", e);
  311. return null;
  312. }
  313. }
  314. Future<Uint8List?> getThumbnailFromInAppCacheFile(ente.File file) async {
  315. var localFile = io.File(getSharedMediaFilePath(file));
  316. if (!localFile.existsSync()) {
  317. return null;
  318. }
  319. if (file.fileType == FileType.video) {
  320. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  321. video: localFile.path,
  322. imageFormat: ImageFormat.JPEG,
  323. thumbnailPath: (await getTemporaryDirectory()).path,
  324. maxWidth: thumbnailLargeSize,
  325. quality: 80,
  326. );
  327. localFile = io.File(thumbnailFilePath!);
  328. }
  329. var thumbnailData = await localFile.readAsBytes();
  330. int compressionAttempts = 0;
  331. while (thumbnailData.length > thumbnailDataLimit &&
  332. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  333. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  334. thumbnailData = await compressThumbnail(thumbnailData);
  335. _logger
  336. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  337. compressionAttempts++;
  338. }
  339. return thumbnailData;
  340. }