file_util.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. import 'dart:async';
  2. import 'dart:io' as io;
  3. import 'dart:io';
  4. import 'package:archive/archive.dart';
  5. import 'package:dio/dio.dart';
  6. import 'package:flutter/foundation.dart';
  7. import 'package:flutter_cache_manager/flutter_cache_manager.dart';
  8. import 'package:flutter_image_compress/flutter_image_compress.dart';
  9. import 'package:logging/logging.dart';
  10. import 'package:motionphoto/motionphoto.dart';
  11. import 'package:path/path.dart';
  12. import 'package:photos/core/cache/image_cache.dart';
  13. import 'package:photos/core/cache/thumbnail_in_memory_cache.dart';
  14. import 'package:photos/core/cache/video_cache_manager.dart';
  15. import 'package:photos/core/configuration.dart';
  16. import 'package:photos/core/constants.dart';
  17. import 'package:photos/models/file.dart' as ente;
  18. import 'package:photos/models/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(ente.File 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<io.File?> getFile(
  31. ente.File 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(ente.File file) async {
  58. return await _getLocalDiskFile(file) != null;
  59. }
  60. Future<io.File?> _getLocalDiskFile(
  61. ente.File file, {
  62. bool liveVideo = false,
  63. bool isOrigin = false,
  64. }) async {
  65. if (file.isSharedMediaToAppSandbox) {
  66. final localFile = io.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(ente.File 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(ente.File file) {
  96. if (file.isRemoteFile) {
  97. getThumbnailFromServer(file);
  98. } else {
  99. getThumbnailFromLocal(file);
  100. }
  101. }
  102. final Map<String, Future<io.File?>> fileDownloadsInProgress =
  103. <String, Future<io.File?>>{};
  104. Future<io.File?> getFileFromServer(
  105. ente.File 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 (!fileDownloadsInProgress.containsKey(downloadID)) {
  118. if (file.fileType == FileType.livePhoto) {
  119. fileDownloadsInProgress[downloadID] = _getLivePhotoFromServer(
  120. file,
  121. progressCallback: progressCallback,
  122. needLiveVideo: liveVideo,
  123. );
  124. fileDownloadsInProgress[downloadID]!.whenComplete(() {
  125. fileDownloadsInProgress.remove(downloadID);
  126. });
  127. } else {
  128. fileDownloadsInProgress[downloadID] = _downloadAndCache(
  129. file,
  130. cacheManager,
  131. progressCallback: progressCallback,
  132. );
  133. fileDownloadsInProgress[downloadID]!.whenComplete(() {
  134. fileDownloadsInProgress.remove(downloadID);
  135. });
  136. }
  137. }
  138. return fileDownloadsInProgress[downloadID];
  139. }
  140. Future<bool> isFileCached(ente.File file, {bool liveVideo = false}) async {
  141. final cacheManager = (file.fileType == FileType.video || liveVideo)
  142. ? VideoCacheManager.instance
  143. : DefaultCacheManager();
  144. final fileInfo = await cacheManager.getFileFromCache(file.downloadUrl);
  145. return fileInfo != null;
  146. }
  147. final Map<int, Future<_LivePhoto?>> _livePhotoDownloadsTracker =
  148. <int, Future<_LivePhoto?>>{};
  149. Future<io.File?> _getLivePhotoFromServer(
  150. ente.File file, {
  151. ProgressCallback? progressCallback,
  152. required bool needLiveVideo,
  153. }) async {
  154. final downloadID = file.uploadedFileID!;
  155. try {
  156. if (!_livePhotoDownloadsTracker.containsKey(downloadID)) {
  157. _livePhotoDownloadsTracker[downloadID] =
  158. _downloadLivePhoto(file, progressCallback: progressCallback);
  159. }
  160. final livePhoto = await _livePhotoDownloadsTracker[file.uploadedFileID];
  161. _livePhotoDownloadsTracker.remove(downloadID);
  162. if (livePhoto == null) {
  163. return null;
  164. }
  165. return needLiveVideo ? livePhoto.video : livePhoto.image;
  166. } catch (e, s) {
  167. _logger.warning("live photo get failed", e, s);
  168. _livePhotoDownloadsTracker.remove(downloadID);
  169. return null;
  170. }
  171. }
  172. Future<_LivePhoto?> _downloadLivePhoto(
  173. ente.File file, {
  174. ProgressCallback? progressCallback,
  175. }) async {
  176. return downloadAndDecrypt(file, progressCallback: progressCallback)
  177. .then((decryptedFile) async {
  178. if (decryptedFile == null) {
  179. return null;
  180. }
  181. _logger.fine("Decoded zipped live photo from " + decryptedFile.path);
  182. io.File? imageFileCache, videoFileCache;
  183. final List<int> bytes = await decryptedFile.readAsBytes();
  184. final Archive archive = ZipDecoder().decodeBytes(bytes);
  185. final tempPath = Configuration.instance.getTempDirectory();
  186. // Extract the contents of Zip compressed archive to disk
  187. for (ArchiveFile archiveFile in archive) {
  188. if (archiveFile.isFile) {
  189. final String filename = archiveFile.name;
  190. final String fileExtension = getExtension(archiveFile.name);
  191. final String decodePath =
  192. tempPath + file.uploadedFileID.toString() + filename;
  193. final List<int> data = archiveFile.content;
  194. if (filename.startsWith("image")) {
  195. final imageFile = io.File(decodePath);
  196. await imageFile.create(recursive: true);
  197. await imageFile.writeAsBytes(data);
  198. io.File imageConvertedFile = imageFile;
  199. if ((fileExtension == "unknown") ||
  200. (io.Platform.isAndroid && fileExtension == "heic")) {
  201. final compressResult =
  202. await FlutterImageCompress.compressAndGetFile(
  203. decodePath,
  204. decodePath + ".jpg",
  205. keepExif: true,
  206. );
  207. await imageFile.delete();
  208. if (compressResult == null) {
  209. throw Exception("Failed to compress file");
  210. } else {
  211. imageConvertedFile = compressResult;
  212. }
  213. }
  214. imageFileCache = await DefaultCacheManager().putFile(
  215. file.downloadUrl,
  216. await imageConvertedFile.readAsBytes(),
  217. eTag: file.downloadUrl,
  218. maxAge: const Duration(days: 365),
  219. fileExtension: fileExtension,
  220. );
  221. await imageConvertedFile.delete();
  222. } else if (filename.startsWith("video")) {
  223. final videoFile = io.File(decodePath);
  224. await videoFile.create(recursive: true);
  225. await videoFile.writeAsBytes(data);
  226. videoFileCache = await VideoCacheManager.instance.putFile(
  227. file.downloadUrl,
  228. await videoFile.readAsBytes(),
  229. eTag: file.downloadUrl,
  230. maxAge: const Duration(days: 365),
  231. fileExtension: fileExtension,
  232. );
  233. await videoFile.delete();
  234. }
  235. }
  236. }
  237. if (imageFileCache != null && videoFileCache != null) {
  238. return _LivePhoto(imageFileCache, videoFileCache);
  239. } else {
  240. debugPrint("Warning: Either image or video is missing from remoteLive");
  241. return null;
  242. }
  243. }).catchError((e) {
  244. _logger.warning("failed to download live photos : ${file.tag}", e);
  245. throw e;
  246. });
  247. }
  248. Future<io.File?> _downloadAndCache(
  249. ente.File file,
  250. BaseCacheManager cacheManager, {
  251. ProgressCallback? progressCallback,
  252. }) async {
  253. return downloadAndDecrypt(file, progressCallback: progressCallback)
  254. .then((decryptedFile) async {
  255. if (decryptedFile == null) {
  256. return null;
  257. }
  258. final decryptedFilePath = decryptedFile.path;
  259. final String fileExtension = getExtension(file.title ?? '');
  260. io.File outputFile = decryptedFile;
  261. if ((fileExtension == "unknown" && file.fileType == FileType.image) ||
  262. (io.Platform.isAndroid && fileExtension == "heic")) {
  263. final compressResult = await FlutterImageCompress.compressAndGetFile(
  264. decryptedFilePath,
  265. decryptedFilePath + ".jpg",
  266. keepExif: true,
  267. );
  268. if (compressResult == null) {
  269. throw Exception("Failed to convert heic to jpg");
  270. } else {
  271. outputFile = compressResult;
  272. }
  273. await decryptedFile.delete();
  274. }
  275. final cachedFile = await cacheManager.putFile(
  276. file.downloadUrl,
  277. await outputFile.readAsBytes(),
  278. eTag: file.downloadUrl,
  279. maxAge: const Duration(days: 365),
  280. fileExtension: fileExtension,
  281. );
  282. await outputFile.delete();
  283. return cachedFile;
  284. }).catchError((e) {
  285. _logger.warning("failed to download file : ${file.tag}", e);
  286. throw e;
  287. });
  288. }
  289. String getExtension(String nameOrPath) {
  290. var fileExtension = "unknown";
  291. try {
  292. fileExtension = extension(nameOrPath).substring(1).toLowerCase();
  293. } catch (e) {
  294. _logger.severe("Could not capture file extension");
  295. }
  296. return fileExtension;
  297. }
  298. Future<Uint8List> compressThumbnail(Uint8List thumbnail) {
  299. return FlutterImageCompress.compressWithList(
  300. thumbnail,
  301. minHeight: compressedThumbnailResolution,
  302. minWidth: compressedThumbnailResolution,
  303. quality: 25,
  304. );
  305. }
  306. Future<void> clearCache(ente.File file) async {
  307. if (file.fileType == FileType.video) {
  308. VideoCacheManager.instance.removeFile(file.downloadUrl);
  309. } else {
  310. DefaultCacheManager().removeFile(file.downloadUrl);
  311. }
  312. final cachedThumbnail = io.File(
  313. Configuration.instance.getThumbnailCacheDirectory() +
  314. "/" +
  315. file.uploadedFileID.toString(),
  316. );
  317. if (cachedThumbnail.existsSync()) {
  318. await cachedThumbnail.delete();
  319. }
  320. ThumbnailInMemoryLruCache.clearCache(file);
  321. }
  322. class _LivePhoto {
  323. final io.File image;
  324. final io.File video;
  325. _LivePhoto(this.image, this.video);
  326. }