file_util.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:archive/archive.dart';
  4. import "package:dio/dio.dart";
  5. import 'package:flutter/foundation.dart';
  6. import 'package:flutter_cache_manager/flutter_cache_manager.dart';
  7. import 'package:flutter_image_compress/flutter_image_compress.dart';
  8. import 'package:logging/logging.dart';
  9. import 'package:motionphoto/motionphoto.dart';
  10. import 'package:path/path.dart';
  11. import 'package:photos/core/cache/image_cache.dart';
  12. import 'package:photos/core/cache/thumbnail_in_memory_cache.dart';
  13. import 'package:photos/core/cache/video_cache_manager.dart';
  14. import 'package:photos/core/configuration.dart';
  15. import 'package:photos/core/constants.dart';
  16. import "package:photos/models/file/extensions/file_props.dart";
  17. import 'package:photos/models/file/file.dart';
  18. import 'package:photos/models/file/file_type.dart';
  19. import 'package:photos/utils/file_download_util.dart';
  20. import 'package:photos/utils/thumbnail_util.dart';
  21. final _logger = Logger("FileUtil");
  22. void preloadFile(EnteFile file) {
  23. if (file.fileType == FileType.video) {
  24. return;
  25. }
  26. getFile(file);
  27. }
  28. // IMPORTANT: Delete the returned file if `isOrigin` is set to true
  29. // https://github.com/CaiJingLong/flutter_photo_manager#cache-problem-of-ios
  30. Future<File?> getFile(
  31. EnteFile file, {
  32. bool liveVideo = false,
  33. bool isOrigin = false,
  34. } // only relevant for live photos
  35. ) async {
  36. if (file.isRemoteFile) {
  37. return getFileFromServer(file, liveVideo: liveVideo);
  38. } else {
  39. final String key = file.tag + liveVideo.toString() + isOrigin.toString();
  40. final cachedFile = FileLruCache.get(key);
  41. if (cachedFile == null) {
  42. final diskFile = await _getLocalDiskFile(
  43. file,
  44. liveVideo: liveVideo,
  45. isOrigin: isOrigin,
  46. );
  47. // do not cache origin file for IOS as they are immediately deleted
  48. // after usage
  49. if (!(isOrigin && Platform.isIOS) && diskFile != null) {
  50. FileLruCache.put(key, diskFile);
  51. }
  52. return diskFile;
  53. }
  54. return cachedFile;
  55. }
  56. }
  57. Future<bool> doesLocalFileExist(EnteFile file) async {
  58. return await _getLocalDiskFile(file) != null;
  59. }
  60. Future<File?> _getLocalDiskFile(
  61. EnteFile file, {
  62. bool liveVideo = false,
  63. bool isOrigin = false,
  64. }) async {
  65. if (file.isSharedMediaToAppSandbox) {
  66. final localFile = File(getSharedMediaFilePath(file));
  67. return localFile.exists().then((exist) {
  68. return exist ? localFile : null;
  69. });
  70. } else if (file.fileType == FileType.livePhoto && liveVideo) {
  71. return Motionphoto.getLivePhotoFile(file.localID!);
  72. } else {
  73. return file.getAsset.then((asset) async {
  74. if (asset == null || !(await asset.exists)) {
  75. return null;
  76. }
  77. return isOrigin ? asset.originFile : asset.file;
  78. });
  79. }
  80. }
  81. String getSharedMediaFilePath(EnteFile file) {
  82. return getSharedMediaPathFromLocalID(file.localID!);
  83. }
  84. String getSharedMediaPathFromLocalID(String localID) {
  85. if (localID.startsWith(oldSharedMediaIdentifier)) {
  86. return Configuration.instance.getOldSharedMediaCacheDirectory() +
  87. "/" +
  88. localID.replaceAll(oldSharedMediaIdentifier, '');
  89. } else {
  90. return Configuration.instance.getSharedMediaDirectory() +
  91. "/" +
  92. localID.replaceAll(sharedMediaIdentifier, '');
  93. }
  94. }
  95. void preloadThumbnail(EnteFile file) {
  96. if (file.isRemoteFile) {
  97. getThumbnailFromServer(file);
  98. } else {
  99. getThumbnailFromLocal(file);
  100. }
  101. }
  102. final Map<String, Future<File?>> _fileDownloadsInProgress =
  103. <String, Future<File?>>{};
  104. Map<String, ProgressCallback?> _progressCallbacks = {};
  105. void removeCallBack(EnteFile file) {
  106. if (!file.isUploaded) {
  107. return;
  108. }
  109. String id = file.uploadedFileID.toString() + false.toString();
  110. _progressCallbacks.remove(id);
  111. if (file.isLivePhoto) {
  112. id = file.uploadedFileID.toString() + true.toString();
  113. _progressCallbacks.remove(id);
  114. }
  115. }
  116. Future<File?> getFileFromServer(
  117. EnteFile file, {
  118. ProgressCallback? progressCallback,
  119. bool liveVideo = false, // only needed in case of live photos
  120. }) async {
  121. final cacheManager = (file.fileType == FileType.video || liveVideo)
  122. ? VideoCacheManager.instance
  123. : DefaultCacheManager();
  124. final fileFromCache = await cacheManager.getFileFromCache(file.downloadUrl);
  125. if (fileFromCache != null) {
  126. return fileFromCache.file;
  127. }
  128. final downloadID = file.uploadedFileID.toString() + liveVideo.toString();
  129. if (progressCallback != null) {
  130. _progressCallbacks[downloadID] = progressCallback;
  131. }
  132. if (!_fileDownloadsInProgress.containsKey(downloadID)) {
  133. final completer = Completer<File?>();
  134. _fileDownloadsInProgress[downloadID] = completer.future;
  135. Future<File?> downloadFuture;
  136. if (file.fileType == FileType.livePhoto) {
  137. downloadFuture = _getLivePhotoFromServer(
  138. file,
  139. progressCallback: (count, total) {
  140. _progressCallbacks[downloadID]?.call(count, total);
  141. },
  142. needLiveVideo: liveVideo,
  143. );
  144. } else {
  145. downloadFuture = _downloadAndCache(
  146. file,
  147. cacheManager,
  148. progressCallback: (count, total) {
  149. _progressCallbacks[downloadID]?.call(count, total);
  150. },
  151. );
  152. }
  153. // ignore: unawaited_futures
  154. downloadFuture.then((downloadedFile) async {
  155. completer.complete(downloadedFile);
  156. await _fileDownloadsInProgress.remove(downloadID);
  157. _progressCallbacks.remove(downloadID);
  158. });
  159. }
  160. return _fileDownloadsInProgress[downloadID];
  161. }
  162. Future<bool> isFileCached(EnteFile file, {bool liveVideo = false}) async {
  163. final cacheManager = (file.fileType == FileType.video || liveVideo)
  164. ? VideoCacheManager.instance
  165. : DefaultCacheManager();
  166. final fileInfo = await cacheManager.getFileFromCache(file.downloadUrl);
  167. return fileInfo != null;
  168. }
  169. final Map<int, Future<_LivePhoto?>> _livePhotoDownloadsTracker =
  170. <int, Future<_LivePhoto?>>{};
  171. Future<File?> _getLivePhotoFromServer(
  172. EnteFile file, {
  173. ProgressCallback? progressCallback,
  174. required bool needLiveVideo,
  175. }) async {
  176. final downloadID = file.uploadedFileID!;
  177. try {
  178. if (!_livePhotoDownloadsTracker.containsKey(downloadID)) {
  179. _livePhotoDownloadsTracker[downloadID] =
  180. _downloadLivePhoto(file, progressCallback: progressCallback);
  181. }
  182. final livePhoto = await _livePhotoDownloadsTracker[file.uploadedFileID];
  183. await _livePhotoDownloadsTracker.remove(downloadID);
  184. if (livePhoto == null) {
  185. return null;
  186. }
  187. return needLiveVideo ? livePhoto.video : livePhoto.image;
  188. } catch (e, s) {
  189. _logger.warning("live photo get failed", e, s);
  190. await _livePhotoDownloadsTracker.remove(downloadID);
  191. return null;
  192. }
  193. }
  194. Future<_LivePhoto?> _downloadLivePhoto(
  195. EnteFile file, {
  196. ProgressCallback? progressCallback,
  197. }) async {
  198. return downloadAndDecrypt(file, progressCallback: progressCallback)
  199. .then((decryptedFile) async {
  200. if (decryptedFile == null) {
  201. return null;
  202. }
  203. _logger.fine("Decoded zipped live photo from " + decryptedFile.path);
  204. File? imageFileCache, videoFileCache;
  205. final List<int> bytes = await decryptedFile.readAsBytes();
  206. final Archive archive = ZipDecoder().decodeBytes(bytes);
  207. final tempPath = Configuration.instance.getTempDirectory();
  208. // Extract the contents of Zip compressed archive to disk
  209. for (ArchiveFile archiveFile in archive) {
  210. if (archiveFile.isFile) {
  211. final String filename = archiveFile.name;
  212. final String fileExtension = getExtension(archiveFile.name);
  213. final String decodePath =
  214. tempPath + file.uploadedFileID.toString() + filename;
  215. final List<int> data = archiveFile.content;
  216. if (filename.startsWith("image")) {
  217. final imageFile = File(decodePath);
  218. await imageFile.create(recursive: true);
  219. await imageFile.writeAsBytes(data);
  220. File imageConvertedFile = imageFile;
  221. if ((fileExtension == "unknown") ||
  222. (Platform.isAndroid && fileExtension == "heic")) {
  223. final compressResult =
  224. await FlutterImageCompress.compressAndGetFile(
  225. decodePath,
  226. decodePath + ".jpg",
  227. keepExif: true,
  228. );
  229. await imageFile.delete();
  230. if (compressResult == null) {
  231. throw Exception("Failed to compress file");
  232. } else {
  233. imageConvertedFile = compressResult;
  234. }
  235. }
  236. imageFileCache = await DefaultCacheManager().putFile(
  237. file.downloadUrl,
  238. await imageConvertedFile.readAsBytes(),
  239. eTag: file.downloadUrl,
  240. maxAge: const Duration(days: 365),
  241. fileExtension: fileExtension,
  242. );
  243. await imageConvertedFile.delete();
  244. } else if (filename.startsWith("video")) {
  245. final videoFile = File(decodePath);
  246. await videoFile.create(recursive: true);
  247. await videoFile.writeAsBytes(data);
  248. videoFileCache = await VideoCacheManager.instance.putFileStream(
  249. file.downloadUrl,
  250. videoFile.openRead(),
  251. eTag: file.downloadUrl,
  252. maxAge: const Duration(days: 365),
  253. fileExtension: fileExtension,
  254. );
  255. await videoFile.delete();
  256. }
  257. }
  258. }
  259. if (imageFileCache != null && videoFileCache != null) {
  260. return _LivePhoto(imageFileCache, videoFileCache);
  261. } else {
  262. debugPrint("Warning: Either image or video is missing from remoteLive");
  263. return null;
  264. }
  265. }).catchError((e) {
  266. _logger.warning("failed to download live photos : ${file.tag}", e);
  267. throw e;
  268. });
  269. }
  270. Future<File?> _downloadAndCache(
  271. EnteFile file,
  272. BaseCacheManager cacheManager, {
  273. required ProgressCallback progressCallback,
  274. }) async {
  275. return downloadAndDecrypt(file, progressCallback: progressCallback)
  276. .then((decryptedFile) async {
  277. if (decryptedFile == null) {
  278. return null;
  279. }
  280. final decryptedFilePath = decryptedFile.path;
  281. final String fileExtension = getExtension(file.title ?? '');
  282. File outputFile = decryptedFile;
  283. if ((fileExtension == "unknown" && file.fileType == FileType.image)) {
  284. final compressResult = await FlutterImageCompress.compressAndGetFile(
  285. decryptedFilePath,
  286. decryptedFilePath + ".jpg",
  287. keepExif: true,
  288. );
  289. if (compressResult == null) {
  290. throw Exception("Failed to convert heic to jpg");
  291. } else {
  292. outputFile = compressResult;
  293. }
  294. await decryptedFile.delete();
  295. }
  296. final cachedFile = await cacheManager.putFileStream(
  297. file.downloadUrl,
  298. outputFile.openRead(),
  299. eTag: file.downloadUrl,
  300. maxAge: const Duration(days: 365),
  301. fileExtension: fileExtension,
  302. );
  303. await outputFile.delete();
  304. return cachedFile;
  305. }).catchError((e) {
  306. _logger.warning("failed to download file : ${file.tag}", e);
  307. throw e;
  308. });
  309. }
  310. String getExtension(String nameOrPath) {
  311. var fileExtension = "unknown";
  312. try {
  313. fileExtension = extension(nameOrPath).substring(1).toLowerCase();
  314. } catch (e) {
  315. _logger.severe("Could not capture file extension");
  316. }
  317. return fileExtension;
  318. }
  319. Future<Uint8List> compressThumbnail(Uint8List thumbnail) {
  320. return FlutterImageCompress.compressWithList(
  321. thumbnail,
  322. minHeight: compressedThumbnailResolution,
  323. minWidth: compressedThumbnailResolution,
  324. quality: 25,
  325. );
  326. }
  327. Future<void> clearCache(EnteFile file) async {
  328. if (file.fileType == FileType.video) {
  329. await VideoCacheManager.instance.removeFile(file.downloadUrl);
  330. } else {
  331. await DefaultCacheManager().removeFile(file.downloadUrl);
  332. }
  333. final cachedThumbnail = File(
  334. Configuration.instance.getThumbnailCacheDirectory() +
  335. "/" +
  336. file.uploadedFileID.toString(),
  337. );
  338. if (cachedThumbnail.existsSync()) {
  339. await cachedThumbnail.delete();
  340. }
  341. ThumbnailInMemoryLruCache.clearCache(file);
  342. }
  343. class _LivePhoto {
  344. final File image;
  345. final File video;
  346. _LivePhoto(this.image, this.video);
  347. }