file_uploader_util.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. sourceFile = await asset.originFile
  83. .timeout(const Duration(seconds: 3))
  84. .catchError((e) async {
  85. if (e is TimeoutException) {
  86. _logger.info("Origin file fetch timed out for " + file.toString());
  87. return await asset.originFile;
  88. } else {
  89. throw e;
  90. }
  91. });
  92. if (sourceFile == null || !sourceFile.existsSync()) {
  93. throw InvalidFileError(
  94. "id: ${file.localID}",
  95. InvalidReason.sourceFileMissing,
  96. );
  97. }
  98. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  99. await _decorateEnteFileData(file, asset);
  100. fileHash = CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
  101. if (file.fileType == FileType.livePhoto && io.Platform.isIOS) {
  102. final io.File? videoUrl = await Motionphoto.getLivePhotoFile(file.localID!);
  103. if (videoUrl == null || !videoUrl.existsSync()) {
  104. final String errMsg =
  105. "missing livePhoto url for ${file.toString()} with subType ${file.fileSubType}";
  106. _logger.severe(errMsg);
  107. throw InvalidFileError(errMsg, InvalidReason.livePhotoVideoMissing);
  108. }
  109. final String livePhotoVideoHash =
  110. CryptoUtil.bin2base64(await CryptoUtil.getHash(videoUrl));
  111. // imgHash:vidHash
  112. fileHash = '$fileHash$kLivePhotoHashSeparator$livePhotoVideoHash';
  113. final tempPath = Configuration.instance.getTempDirectory();
  114. // .elp -> ente live photo
  115. final livePhotoPath = tempPath + file.generatedID.toString() + ".elp";
  116. _logger.fine("Uploading zipped live photo from " + livePhotoPath);
  117. final encoder = ZipFileEncoder();
  118. encoder.create(livePhotoPath);
  119. encoder.addFile(videoUrl, "video" + extension(videoUrl.path));
  120. encoder.addFile(sourceFile, "image" + extension(sourceFile.path));
  121. encoder.close();
  122. // delete the temporary video and image copy (only in IOS)
  123. if (io.Platform.isIOS) {
  124. await sourceFile.delete();
  125. }
  126. // new sourceFile which needs to be uploaded
  127. sourceFile = io.File(livePhotoPath);
  128. zipHash = CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
  129. }
  130. thumbnailData = await asset.thumbnailDataWithSize(
  131. const ThumbnailSize(thumbnailLargeSize, thumbnailLargeSize),
  132. quality: thumbnailQuality,
  133. );
  134. if (thumbnailData == null) {
  135. throw InvalidFileError(
  136. "no thumbnail ${file.tag}",
  137. InvalidReason.thumbnailMissing,
  138. );
  139. }
  140. int compressionAttempts = 0;
  141. while (thumbnailData!.length > thumbnailDataLimit &&
  142. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  143. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  144. thumbnailData = await compressThumbnail(thumbnailData);
  145. _logger
  146. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  147. compressionAttempts++;
  148. }
  149. isDeleted = !(await asset.exists);
  150. int? h, w;
  151. if (asset.width != 0 && asset.height != 0) {
  152. h = asset.height;
  153. w = asset.width;
  154. }
  155. int? motionPhotoStartingIndex;
  156. if (io.Platform.isAndroid && asset.type == AssetType.image) {
  157. try {
  158. motionPhotoStartingIndex =
  159. (await MotionPhotos(sourceFile.path).getMotionVideoIndex())?.start;
  160. } catch (e) {
  161. _logger.severe('error while detecthing motion photo start index', e);
  162. }
  163. }
  164. return MediaUploadData(
  165. sourceFile,
  166. thumbnailData,
  167. isDeleted,
  168. FileHashData(fileHash, zipHash: zipHash),
  169. height: h,
  170. width: w,
  171. motionPhotoStartIndex: motionPhotoStartingIndex,
  172. );
  173. }
  174. Future<void> _decorateEnteFileData(ente.File file, AssetEntity asset) async {
  175. // h4ck to fetch location data if missing (thank you Android Q+) lazily only during uploads
  176. if (file.location == null ||
  177. (file.location!.latitude == 0 && file.location!.longitude == 0)) {
  178. final latLong = await asset.latlngAsync();
  179. file.location =
  180. Location(latitude: latLong.latitude, longitude: latLong.longitude);
  181. }
  182. if (file.title == null || file.title!.isEmpty) {
  183. _logger.warning("Title was missing ${file.tag}");
  184. file.title = await asset.titleAsync;
  185. }
  186. }
  187. Future<MetadataRequest> getPubMetadataRequest(
  188. ente.File file,
  189. Map<String, dynamic> newData,
  190. Uint8List fileKey,
  191. ) async {
  192. final Map<String, dynamic> jsonToUpdate =
  193. jsonDecode(file.pubMmdEncodedJson ?? '{}');
  194. newData.forEach((key, value) {
  195. jsonToUpdate[key] = value;
  196. });
  197. // update the local information so that it's reflected on UI
  198. file.pubMmdEncodedJson = jsonEncode(jsonToUpdate);
  199. file.pubMagicMetadata = PubMagicMetadata.fromJson(jsonToUpdate);
  200. final encryptedMMd = await CryptoUtil.encryptChaCha(
  201. utf8.encode(jsonEncode(jsonToUpdate)) as Uint8List,
  202. fileKey,
  203. );
  204. return MetadataRequest(
  205. version: file.pubMmdVersion == 0 ? 1 : file.pubMmdVersion,
  206. count: jsonToUpdate.length,
  207. data: CryptoUtil.bin2base64(encryptedMMd.encryptedData!),
  208. header: CryptoUtil.bin2base64(encryptedMMd.header!),
  209. );
  210. }
  211. Future<MediaUploadData> _getMediaUploadDataFromAppCache(ente.File file) async {
  212. io.File sourceFile;
  213. Uint8List? thumbnailData;
  214. const bool isDeleted = false;
  215. final localPath = getSharedMediaFilePath(file);
  216. sourceFile = io.File(localPath);
  217. if (!sourceFile.existsSync()) {
  218. _logger.warning("File doesn't exist in app sandbox");
  219. throw InvalidFileError(
  220. "source missing in sandbox",
  221. InvalidReason.sourceFileMissing,
  222. );
  223. }
  224. try {
  225. thumbnailData = await getThumbnailFromInAppCacheFile(file);
  226. final fileHash =
  227. CryptoUtil.bin2base64(await CryptoUtil.getHash(sourceFile));
  228. Map<String, int>? dimensions;
  229. if (file.fileType == FileType.image) {
  230. dimensions = await getImageHeightAndWith(imagePath: localPath);
  231. } else {
  232. // for video, we need to use the thumbnail data with any max width/height
  233. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  234. video: localPath,
  235. imageFormat: ImageFormat.JPEG,
  236. thumbnailPath: (await getTemporaryDirectory()).path,
  237. quality: 10,
  238. );
  239. dimensions = await getImageHeightAndWith(imagePath: thumbnailFilePath);
  240. }
  241. return MediaUploadData(
  242. sourceFile,
  243. thumbnailData,
  244. isDeleted,
  245. FileHashData(fileHash),
  246. height: dimensions?['height'],
  247. width: dimensions?['width'],
  248. );
  249. } catch (e, s) {
  250. _logger.severe("failed to generate thumbnail", e, s);
  251. throw InvalidFileError(
  252. "thumbnail failed for appCache fileType: ${file.fileType.toString()}",
  253. InvalidReason.thumbnailMissing,
  254. );
  255. }
  256. }
  257. Future<Map<String, int>?> getImageHeightAndWith({
  258. String? imagePath,
  259. Uint8List? imageBytes,
  260. }) async {
  261. if (imagePath == null && imageBytes == null) {
  262. throw ArgumentError("imagePath and imageBytes cannot be null");
  263. }
  264. try {
  265. late Uint8List bytes;
  266. if (imagePath != null) {
  267. final io.File imageFile = io.File(imagePath);
  268. bytes = await imageFile.readAsBytes();
  269. } else {
  270. bytes = imageBytes!;
  271. }
  272. final ui.Codec codec = await ui.instantiateImageCodec(bytes);
  273. final ui.FrameInfo frameInfo = await codec.getNextFrame();
  274. if (frameInfo.image.width == 0 || frameInfo.image.height == 0) {
  275. return null;
  276. } else {
  277. return {
  278. "width": frameInfo.image.width,
  279. "height": frameInfo.image.height,
  280. };
  281. }
  282. } catch (e) {
  283. _logger.severe("Failed to get image size", e);
  284. return null;
  285. }
  286. }
  287. Future<Uint8List?> getThumbnailFromInAppCacheFile(ente.File file) async {
  288. var localFile = io.File(getSharedMediaFilePath(file));
  289. if (!localFile.existsSync()) {
  290. return null;
  291. }
  292. if (file.fileType == FileType.video) {
  293. final thumbnailFilePath = await VideoThumbnail.thumbnailFile(
  294. video: localFile.path,
  295. imageFormat: ImageFormat.JPEG,
  296. thumbnailPath: (await getTemporaryDirectory()).path,
  297. maxWidth: thumbnailLargeSize,
  298. quality: 80,
  299. );
  300. localFile = io.File(thumbnailFilePath!);
  301. }
  302. var thumbnailData = await localFile.readAsBytes();
  303. int compressionAttempts = 0;
  304. while (thumbnailData.length > thumbnailDataLimit &&
  305. compressionAttempts < kMaximumThumbnailCompressionAttempts) {
  306. _logger.info("Thumbnail size " + thumbnailData.length.toString());
  307. thumbnailData = await compressThumbnail(thumbnailData);
  308. _logger
  309. .info("Compressed thumbnail size " + thumbnailData.length.toString());
  310. compressionAttempts++;
  311. }
  312. return thumbnailData;
  313. }