file_uploader_util.dart 12 KB

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