file_util.dart 11 KB

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