file_util.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. downloadFuture.then((downloadedFile) {
  154. completer.complete(downloadedFile);
  155. _fileDownloadsInProgress.remove(downloadID);
  156. _progressCallbacks.remove(downloadID);
  157. });
  158. }
  159. return _fileDownloadsInProgress[downloadID];
  160. }
  161. Future<bool> isFileCached(EnteFile file, {bool liveVideo = false}) async {
  162. final cacheManager = (file.fileType == FileType.video || liveVideo)
  163. ? VideoCacheManager.instance
  164. : DefaultCacheManager();
  165. final fileInfo = await cacheManager.getFileFromCache(file.downloadUrl);
  166. return fileInfo != null;
  167. }
  168. final Map<int, Future<_LivePhoto?>> _livePhotoDownloadsTracker =
  169. <int, Future<_LivePhoto?>>{};
  170. Future<File?> _getLivePhotoFromServer(
  171. EnteFile file, {
  172. ProgressCallback? progressCallback,
  173. required bool needLiveVideo,
  174. }) async {
  175. final downloadID = file.uploadedFileID!;
  176. try {
  177. if (!_livePhotoDownloadsTracker.containsKey(downloadID)) {
  178. _livePhotoDownloadsTracker[downloadID] =
  179. _downloadLivePhoto(file, progressCallback: progressCallback);
  180. }
  181. final livePhoto = await _livePhotoDownloadsTracker[file.uploadedFileID];
  182. _livePhotoDownloadsTracker.remove(downloadID);
  183. if (livePhoto == null) {
  184. return null;
  185. }
  186. return needLiveVideo ? livePhoto.video : livePhoto.image;
  187. } catch (e, s) {
  188. _logger.warning("live photo get failed", e, s);
  189. await _livePhotoDownloadsTracker.remove(downloadID);
  190. return null;
  191. }
  192. }
  193. Future<_LivePhoto?> _downloadLivePhoto(
  194. EnteFile file, {
  195. ProgressCallback? progressCallback,
  196. }) async {
  197. return downloadAndDecrypt(file, progressCallback: progressCallback)
  198. .then((decryptedFile) async {
  199. if (decryptedFile == null) {
  200. return null;
  201. }
  202. _logger.fine("Decoded zipped live photo from " + decryptedFile.path);
  203. File? imageFileCache, videoFileCache;
  204. final List<int> bytes = await decryptedFile.readAsBytes();
  205. final Archive archive = ZipDecoder().decodeBytes(bytes);
  206. final tempPath = Configuration.instance.getTempDirectory();
  207. // Extract the contents of Zip compressed archive to disk
  208. for (ArchiveFile archiveFile in archive) {
  209. if (archiveFile.isFile) {
  210. final String filename = archiveFile.name;
  211. final String fileExtension = getExtension(archiveFile.name);
  212. final String decodePath =
  213. tempPath + file.uploadedFileID.toString() + filename;
  214. final List<int> data = archiveFile.content;
  215. if (filename.startsWith("image")) {
  216. final imageFile = File(decodePath);
  217. await imageFile.create(recursive: true);
  218. await imageFile.writeAsBytes(data);
  219. File imageConvertedFile = imageFile;
  220. if ((fileExtension == "unknown") ||
  221. (Platform.isAndroid && fileExtension == "heic")) {
  222. final compressResult =
  223. await FlutterImageCompress.compressAndGetFile(
  224. decodePath,
  225. decodePath + ".jpg",
  226. keepExif: true,
  227. );
  228. await imageFile.delete();
  229. if (compressResult == null) {
  230. throw Exception("Failed to compress file");
  231. } else {
  232. imageConvertedFile = compressResult;
  233. }
  234. }
  235. imageFileCache = await DefaultCacheManager().putFile(
  236. file.downloadUrl,
  237. await imageConvertedFile.readAsBytes(),
  238. eTag: file.downloadUrl,
  239. maxAge: const Duration(days: 365),
  240. fileExtension: fileExtension,
  241. );
  242. await imageConvertedFile.delete();
  243. } else if (filename.startsWith("video")) {
  244. final videoFile = File(decodePath);
  245. await videoFile.create(recursive: true);
  246. await videoFile.writeAsBytes(data);
  247. videoFileCache = await VideoCacheManager.instance.putFileStream(
  248. file.downloadUrl,
  249. videoFile.openRead(),
  250. eTag: file.downloadUrl,
  251. maxAge: const Duration(days: 365),
  252. fileExtension: fileExtension,
  253. );
  254. await videoFile.delete();
  255. }
  256. }
  257. }
  258. if (imageFileCache != null && videoFileCache != null) {
  259. return _LivePhoto(imageFileCache, videoFileCache);
  260. } else {
  261. debugPrint("Warning: Either image or video is missing from remoteLive");
  262. return null;
  263. }
  264. }).catchError((e) {
  265. _logger.warning("failed to download live photos : ${file.tag}", e);
  266. throw e;
  267. });
  268. }
  269. Future<File?> _downloadAndCache(
  270. EnteFile file,
  271. BaseCacheManager cacheManager, {
  272. required ProgressCallback progressCallback,
  273. }) async {
  274. return downloadAndDecrypt(file, progressCallback: progressCallback)
  275. .then((decryptedFile) async {
  276. if (decryptedFile == null) {
  277. return null;
  278. }
  279. final decryptedFilePath = decryptedFile.path;
  280. final String fileExtension = getExtension(file.title ?? '');
  281. File outputFile = decryptedFile;
  282. if ((fileExtension == "unknown" && file.fileType == FileType.image)) {
  283. final compressResult = await FlutterImageCompress.compressAndGetFile(
  284. decryptedFilePath,
  285. decryptedFilePath + ".jpg",
  286. keepExif: true,
  287. );
  288. if (compressResult == null) {
  289. throw Exception("Failed to convert heic to jpg");
  290. } else {
  291. outputFile = compressResult;
  292. }
  293. await decryptedFile.delete();
  294. }
  295. final cachedFile = await cacheManager.putFileStream(
  296. file.downloadUrl,
  297. outputFile.openRead(),
  298. eTag: file.downloadUrl,
  299. maxAge: const Duration(days: 365),
  300. fileExtension: fileExtension,
  301. );
  302. await outputFile.delete();
  303. return cachedFile;
  304. }).catchError((e) {
  305. _logger.warning("failed to download file : ${file.tag}", e);
  306. throw e;
  307. });
  308. }
  309. String getExtension(String nameOrPath) {
  310. var fileExtension = "unknown";
  311. try {
  312. fileExtension = extension(nameOrPath).substring(1).toLowerCase();
  313. } catch (e) {
  314. _logger.severe("Could not capture file extension");
  315. }
  316. return fileExtension;
  317. }
  318. Future<Uint8List> compressThumbnail(Uint8List thumbnail) {
  319. return FlutterImageCompress.compressWithList(
  320. thumbnail,
  321. minHeight: compressedThumbnailResolution,
  322. minWidth: compressedThumbnailResolution,
  323. quality: 25,
  324. );
  325. }
  326. Future<void> clearCache(EnteFile file) async {
  327. if (file.fileType == FileType.video) {
  328. await VideoCacheManager.instance.removeFile(file.downloadUrl);
  329. } else {
  330. await DefaultCacheManager().removeFile(file.downloadUrl);
  331. }
  332. final cachedThumbnail = File(
  333. Configuration.instance.getThumbnailCacheDirectory() +
  334. "/" +
  335. file.uploadedFileID.toString(),
  336. );
  337. if (cachedThumbnail.existsSync()) {
  338. await cachedThumbnail.delete();
  339. }
  340. ThumbnailInMemoryLruCache.clearCache(file);
  341. }
  342. class _LivePhoto {
  343. final File image;
  344. final File video;
  345. _LivePhoto(this.image, this.video);
  346. }