file_uploader_util.dart 11 KB

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