file_util.dart 11 KB

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