file_util.dart 11 KB

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