file_util.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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_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_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. 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)) {
  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. var 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 Configuration.instance.getSharedMediaCacheDirectory() +
  83. "/" +
  84. file.localID.replaceAll(kSharedMediaIdentifier, '');
  85. }
  86. void preloadThumbnail(ente.File file) {
  87. if (file.isRemoteFile()) {
  88. getThumbnailFromServer(file);
  89. } else {
  90. getThumbnailFromLocal(file);
  91. }
  92. }
  93. final Map<String, Future<io.File>> fileDownloadsInProgress =
  94. <String, Future<io.File>>{};
  95. Future<io.File> getFileFromServer(
  96. ente.File file, {
  97. ProgressCallback progressCallback,
  98. bool liveVideo = false, // only needed in case of live photos
  99. }) async {
  100. final cacheManager = (file.fileType == FileType.video || liveVideo)
  101. ? VideoCacheManager.instance
  102. : DefaultCacheManager();
  103. final fileFromCache =
  104. await cacheManager.getFileFromCache(file.getDownloadUrl());
  105. if (fileFromCache != null) {
  106. return fileFromCache.file;
  107. }
  108. final downloadID = file.uploadedFileID.toString() + liveVideo.toString();
  109. if (!fileDownloadsInProgress.containsKey(downloadID)) {
  110. if (file.fileType == FileType.livePhoto) {
  111. fileDownloadsInProgress[downloadID] = _getLivePhotoFromServer(file,
  112. progressCallback: progressCallback, needLiveVideo: liveVideo)
  113. .whenComplete(() {
  114. fileDownloadsInProgress.remove(downloadID);
  115. });
  116. } else {
  117. fileDownloadsInProgress[downloadID] = _downloadAndCache(
  118. file, cacheManager,
  119. progressCallback: progressCallback)
  120. .whenComplete(() {
  121. fileDownloadsInProgress.remove(downloadID);
  122. });
  123. }
  124. }
  125. return fileDownloadsInProgress[downloadID];
  126. }
  127. Future<bool> isFileCached(ente.File file, {bool liveVideo = false}) async {
  128. final cacheManager = (file.fileType == FileType.video || liveVideo)
  129. ? VideoCacheManager.instance
  130. : DefaultCacheManager();
  131. final fileInfo = await cacheManager.getFileFromCache(file.getDownloadUrl());
  132. return fileInfo != null;
  133. }
  134. final Map<int, Future<_LivePhoto>> livePhotoDownloadsTracker =
  135. <int, Future<_LivePhoto>>{};
  136. Future<io.File> _getLivePhotoFromServer(ente.File file,
  137. {ProgressCallback progressCallback, bool needLiveVideo}) async {
  138. final downloadID = file.uploadedFileID;
  139. try {
  140. if (!livePhotoDownloadsTracker.containsKey(downloadID)) {
  141. livePhotoDownloadsTracker[downloadID] =
  142. _downloadLivePhoto(file, progressCallback: progressCallback);
  143. }
  144. final livePhoto = await livePhotoDownloadsTracker[file.uploadedFileID];
  145. livePhotoDownloadsTracker.remove(downloadID);
  146. if (livePhoto == null) {
  147. return null;
  148. }
  149. return needLiveVideo ? livePhoto.video : livePhoto.image;
  150. } catch (e, s) {
  151. _logger.warning("live photo get failed", e, s);
  152. livePhotoDownloadsTracker.remove(downloadID);
  153. return null;
  154. }
  155. }
  156. Future<_LivePhoto> _downloadLivePhoto(ente.File file,
  157. {ProgressCallback progressCallback}) async {
  158. return downloadAndDecrypt(file, progressCallback: progressCallback)
  159. .then((decryptedFile) async {
  160. if (decryptedFile == null) {
  161. return null;
  162. }
  163. _logger.fine("Decoded zipped live photo from " + decryptedFile.path);
  164. io.File imageFileCache, videoFileCache;
  165. List<int> bytes = await decryptedFile.readAsBytes();
  166. Archive archive = ZipDecoder().decodeBytes(bytes);
  167. final tempPath = Configuration.instance.getTempDirectory();
  168. // Extract the contents of Zip compressed archive to disk
  169. for (ArchiveFile archiveFile in archive) {
  170. if (archiveFile.isFile) {
  171. String filename = archiveFile.name;
  172. String fileExtension = getExtension(archiveFile.name);
  173. String decodePath =
  174. tempPath + file.uploadedFileID.toString() + filename;
  175. List<int> data = archiveFile.content;
  176. if (filename.startsWith("image")) {
  177. final imageFile = io.File(decodePath);
  178. await imageFile.create(recursive: true);
  179. await imageFile.writeAsBytes(data);
  180. io.File imageConvertedFile = imageFile;
  181. if ((fileExtension == "unknown") ||
  182. (io.Platform.isAndroid && fileExtension == "heic")) {
  183. imageConvertedFile = await FlutterImageCompress.compressAndGetFile(
  184. decodePath,
  185. decodePath + ".jpg",
  186. keepExif: true,
  187. );
  188. await imageFile.delete();
  189. }
  190. imageFileCache = await DefaultCacheManager().putFile(
  191. file.getDownloadUrl(),
  192. await imageConvertedFile.readAsBytes(),
  193. eTag: file.getDownloadUrl(),
  194. maxAge: Duration(days: 365),
  195. fileExtension: fileExtension,
  196. );
  197. await imageConvertedFile.delete();
  198. } else if (filename.startsWith("video")) {
  199. final videoFile = io.File(decodePath);
  200. await videoFile.create(recursive: true);
  201. await videoFile.writeAsBytes(data);
  202. videoFileCache = await VideoCacheManager.instance.putFile(
  203. file.getDownloadUrl(),
  204. await videoFile.readAsBytes(),
  205. eTag: file.getDownloadUrl(),
  206. maxAge: Duration(days: 365),
  207. fileExtension: fileExtension,
  208. );
  209. await videoFile.delete();
  210. }
  211. }
  212. }
  213. return _LivePhoto(imageFileCache, videoFileCache);
  214. }).catchError((e) {
  215. _logger.warning("failed to download live photos : ${file.tag()}", e);
  216. throw e;
  217. });
  218. }
  219. Future<io.File> _downloadAndCache(ente.File file, BaseCacheManager cacheManager,
  220. {ProgressCallback progressCallback}) async {
  221. return downloadAndDecrypt(file, progressCallback: progressCallback)
  222. .then((decryptedFile) async {
  223. if (decryptedFile == null) {
  224. return null;
  225. }
  226. var decryptedFilePath = decryptedFile.path;
  227. String fileExtension = getExtension(file.title);
  228. var outputFile = decryptedFile;
  229. if ((fileExtension == "unknown" && file.fileType == FileType.image) ||
  230. (io.Platform.isAndroid && fileExtension == "heic")) {
  231. outputFile = await FlutterImageCompress.compressAndGetFile(
  232. decryptedFilePath,
  233. decryptedFilePath + ".jpg",
  234. keepExif: true,
  235. );
  236. await decryptedFile.delete();
  237. }
  238. final cachedFile = await cacheManager.putFile(
  239. file.getDownloadUrl(),
  240. await outputFile.readAsBytes(),
  241. eTag: file.getDownloadUrl(),
  242. maxAge: Duration(days: 365),
  243. fileExtension: fileExtension,
  244. );
  245. await outputFile.delete();
  246. return cachedFile;
  247. }).catchError((e) {
  248. _logger.warning("failed to download file : ${file.tag()}", e);
  249. throw e;
  250. });
  251. }
  252. String getExtension(String nameOrPath) {
  253. var fileExtension = "unknown";
  254. try {
  255. fileExtension = extension(nameOrPath).substring(1).toLowerCase();
  256. } catch (e) {
  257. _logger.severe("Could not capture file extension");
  258. }
  259. return fileExtension;
  260. }
  261. Future<Uint8List> compressThumbnail(Uint8List thumbnail) {
  262. return FlutterImageCompress.compressWithList(
  263. thumbnail,
  264. minHeight: kCompressedThumbnailResolution,
  265. minWidth: kCompressedThumbnailResolution,
  266. quality: 25,
  267. );
  268. }
  269. Future<void> clearCache(ente.File file) async {
  270. if (file.fileType == FileType.video) {
  271. VideoCacheManager.instance.removeFile(file.getDownloadUrl());
  272. } else {
  273. DefaultCacheManager().removeFile(file.getDownloadUrl());
  274. }
  275. final cachedThumbnail = io.File(
  276. Configuration.instance.getThumbnailCacheDirectory() +
  277. "/" +
  278. file.uploadedFileID.toString());
  279. if (cachedThumbnail.existsSync()) {
  280. await cachedThumbnail.delete();
  281. }
  282. ThumbnailLruCache.clearCache(file);
  283. }
  284. class _LivePhoto {
  285. final io.File image;
  286. final io.File video;
  287. _LivePhoto(this.image, this.video);
  288. }