file_uploader_util.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 _getThumbnailForUpload(asset, file);
  132. isDeleted = !(await asset.exists);
  133. int? h, w;
  134. if (asset.width != 0 && asset.height != 0) {
  135. h = asset.height;
  136. w = asset.width;
  137. }
  138. int? motionPhotoStartingIndex;
  139. if (io.Platform.isAndroid && asset.type == AssetType.image) {
  140. try {
  141. motionPhotoStartingIndex =
  142. (await MotionPhotos(sourceFile.path).getMotionVideoIndex())?.start;
  143. } catch (e) {
  144. _logger.severe('error while detecthing motion photo start index', e);
  145. }
  146. }
  147. return MediaUploadData(
  148. sourceFile,
  149. thumbnailData,
  150. isDeleted,
  151. FileHashData(fileHash, zipHash: zipHash),
  152. height: h,
  153. width: w,
  154. motionPhotoStartIndex: motionPhotoStartingIndex,
  155. );
  156. }
  157. Future<Uint8List?> _getThumbnailForUpload(
  158. AssetEntity asset,
  159. ente.File file,
  160. ) async {
  161. try {
  162. Uint8List? thumbnailData = await asset.thumbnailDataWithSize(
  163. const ThumbnailSize(thumbnailLargeSize, thumbnailLargeSize),
  164. quality: thumbnailQuality,
  165. );
  166. if (thumbnailData == null) {
  167. throw InvalidFileError(
  168. "no thumbnail : ${file.fileType} ${file.tag}",
  169. InvalidReason.thumbnailMissing,
  170. );
  171. }
  172. int compressionAttempts = 0;
  173. while (thumbnailData!.length > thumbnailDataLimit &&
  174. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  175. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  176. thumbnailData = await compressThumbnail(thumbnailData);
  177. _logger
  178. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  179. compressionAttempts++;
  180. }
  181. return thumbnailData;
  182. } catch (e) {
  183. final String errMessage =
  184. "thumbErr for ${file.fileType}, ${extension(file.displayName)} ${file.tag}";
  185. _logger.warning(errMessage, e);
  186. throw InvalidFileError(errMessage, InvalidReason.thumbnailMissing);
  187. }
  188. }
  189. // check if the assetType is still the same. This can happen for livePhotos
  190. // if the user turns off the video using native photos app
  191. void _assertFileType(AssetEntity asset, ente.File file) {
  192. final assetType = fileTypeFromAsset(asset);
  193. if (assetType == file.fileType) {
  194. return;
  195. }
  196. if (io.Platform.isIOS || io.Platform.isMacOS) {
  197. if (assetType == FileType.image && file.fileType == FileType.livePhoto) {
  198. throw InvalidFileError(
  199. 'id ${asset.id}',
  200. InvalidReason.livePhotoToImageTypeChanged,
  201. );
  202. } else if (assetType == FileType.livePhoto &&
  203. file.fileType == FileType.image) {
  204. throw InvalidFileError(
  205. 'id ${asset.id}',
  206. InvalidReason.imageToLivePhotoTypeChanged,
  207. );
  208. }
  209. }
  210. throw InvalidFileError(
  211. 'fileType mismatch for id ${asset.id} assetType $assetType fileType ${file.fileType}',
  212. InvalidReason.unknown,
  213. );
  214. }
  215. Future<void> _decorateEnteFileData(ente.File file, AssetEntity asset) async {
  216. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  217. if (file.location == null ||
  218. (file.location!.latitude == 0 && file.location!.longitude == 0)) {
  219. final latLong = await asset.latlngAsync();
  220. file.location =
  221. Location(latitude: latLong.latitude, longitude: latLong.longitude);
  222. }
  223. if (file.title == null || file.title!.isEmpty) {
  224. _logger.warning("Title was missing ${file.tag}");
  225. file.title = await asset.titleAsync;
  226. }
  227. }
  228. Future<MetadataRequest> getPubMetadataRequest(
  229. ente.File file,
  230. Map<String, dynamic> newData,
  231. Uint8List fileKey,
  232. ) async {
  233. final Map<String, dynamic> jsonToUpdate =
  234. jsonDecode(file.pubMmdEncodedJson ?? '{}');
  235. newData.forEach((key, value) {
  236. jsonToUpdate[key] = value;
  237. });
  238. // update the local information so that it's reflected on UI
  239. file.pubMmdEncodedJson = jsonEncode(jsonToUpdate);
  240. file.pubMagicMetadata = PubMagicMetadata.fromJson(jsonToUpdate);
  241. final encryptedMMd = await CryptoUtil.encryptChaCha(
  242. utf8.encode(jsonEncode(jsonToUpdate)) as Uint8List,
  243. fileKey,
  244. );
  245. return MetadataRequest(
  246. version: file.pubMmdVersion == 0 ? 1 : file.pubMmdVersion,
  247. count: jsonToUpdate.length,
  248. data: CryptoUtil.bin2base64(encryptedMMd.encryptedData!),
  249. header: CryptoUtil.bin2base64(encryptedMMd.header!),
  250. );
  251. }
  252. Future<MediaUploadData> _getMediaUploadDataFromAppCache(ente.File file) async {
  253. io.File sourceFile;
  254. Uint8List? thumbnailData;
  255. const bool isDeleted = false;
  256. final localPath = getSharedMediaFilePath(file);
  257. sourceFile = io.File(localPath);
  258. if (!sourceFile.existsSync()) {
  259. _logger.warning("File doesn't exist in app sandbox");
  260. throw InvalidFileError(
  261. "source missing in sandbox",
  262. InvalidReason.sourceFileMissing,
  263. );
  264. }
  265. try {
  266. thumbnailData = await getThumbnailFromInAppCacheFile(file);
  267. final fileHash =
  268. CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
  269. Map<String, int>? dimensions;
  270. if (file.fileType == FileType.image) {
  271. dimensions = await getImageHeightAndWith(imagePath: localPath);
  272. } else {
  273. // for video, we need to use the thumbnail data with any max width/height
  274. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  275. video: localPath,
  276. imageFormat: ImageFormat.JPEG,
  277. thumbnailPath: (await getTemporaryDirectory()).path,
  278. quality: 10,
  279. );
  280. dimensions = await getImageHeightAndWith(imagePath: thumbnailFilePath);
  281. }
  282. return MediaUploadData(
  283. sourceFile,
  284. thumbnailData,
  285. isDeleted,
  286. FileHashData(fileHash),
  287. height: dimensions?['height'],
  288. width: dimensions?['width'],
  289. );
  290. } catch (e, s) {
  291. _logger.severe("failed to generate thumbnail", e, s);
  292. throw InvalidFileError(
  293. "thumbnail failed for appCache fileType: ${file.fileType.toString()}",
  294. InvalidReason.thumbnailMissing,
  295. );
  296. }
  297. }
  298. Future<Map<String, int>?> getImageHeightAndWith({
  299. String? imagePath,
  300. Uint8List? imageBytes,
  301. }) async {
  302. if (imagePath == null && imageBytes == null) {
  303. throw ArgumentError("imagePath and imageBytes cannot be null");
  304. }
  305. try {
  306. late Uint8List bytes;
  307. if (imagePath != null) {
  308. final io.File imageFile = io.File(imagePath);
  309. bytes = await imageFile.readAsBytes();
  310. } else {
  311. bytes = imageBytes!;
  312. }
  313. final ui.Codec codec = await ui.instantiateImageCodec(bytes);
  314. final ui.FrameInfo frameInfo = await codec.getNextFrame();
  315. if (frameInfo.image.width == 0 || frameInfo.image.height == 0) {
  316. return null;
  317. } else {
  318. return {
  319. "width": frameInfo.image.width,
  320. "height": frameInfo.image.height,
  321. };
  322. }
  323. } catch (e) {
  324. _logger.severe("Failed to get image size", e);
  325. return null;
  326. }
  327. }
  328. Future<Uint8List?> getThumbnailFromInAppCacheFile(ente.File file) async {
  329. var localFile = io.File(getSharedMediaFilePath(file));
  330. if (!localFile.existsSync()) {
  331. return null;
  332. }
  333. if (file.fileType == FileType.video) {
  334. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  335. video: localFile.path,
  336. imageFormat: ImageFormat.JPEG,
  337. thumbnailPath: (await getTemporaryDirectory()).path,
  338. maxWidth: thumbnailLargeSize,
  339. quality: 80,
  340. );
  341. localFile = io.File(thumbnailFilePath!);
  342. }
  343. var thumbnailData = await localFile.readAsBytes();
  344. int compressionAttempts = 0;
  345. while (thumbnailData.length > thumbnailDataLimit &&
  346. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  347. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  348. thumbnailData = await compressThumbnail(thumbnailData);
  349. _logger
  350. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  351. compressionAttempts++;
  352. }
  353. return thumbnailData;
  354. }