file_util.dart 10 KB

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