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/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,
  127. {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(
  216. "failed to download live photos : ${file.tag()}", e);
  217. throw e;
  218. });
  219. }
  220. Future<io.File> _downloadAndCache(ente.File file, BaseCacheManager cacheManager,
  221. {ProgressCallback progressCallback}) async {
  222. return downloadAndDecrypt(file, progressCallback: progressCallback)
  223. .then((decryptedFile) async {
  224. if (decryptedFile == null) {
  225. return null;
  226. }
  227. var decryptedFilePath = decryptedFile.path;
  228. String fileExtension = getExtension(file.title);
  229. var outputFile = decryptedFile;
  230. if ((fileExtension == "unknown" && file.fileType == FileType.image) ||
  231. (io.Platform.isAndroid && fileExtension == "heic")) {
  232. outputFile = await FlutterImageCompress.compressAndGetFile(
  233. decryptedFilePath,
  234. decryptedFilePath + ".jpg",
  235. keepExif: true,
  236. );
  237. await decryptedFile.delete();
  238. }
  239. final cachedFile = await cacheManager.putFile(
  240. file.getDownloadUrl(),
  241. await outputFile.readAsBytes(),
  242. eTag: file.getDownloadUrl(),
  243. maxAge: Duration(days: 365),
  244. fileExtension: fileExtension,
  245. );
  246. await outputFile.delete();
  247. return cachedFile;
  248. }).catchError((e) {
  249. _logger.warning("failed to download file : ${file.tag()}", e);
  250. throw e;
  251. });
  252. }
  253. String getExtension(String nameOrPath) {
  254. var fileExtension = "unknown";
  255. try {
  256. fileExtension = extension(nameOrPath).substring(1).toLowerCase();
  257. } catch (e) {
  258. _logger.severe("Could not capture file extension");
  259. }
  260. return fileExtension;
  261. }
  262. Future<Uint8List> compressThumbnail(Uint8List thumbnail) {
  263. return FlutterImageCompress.compressWithList(
  264. thumbnail,
  265. minHeight: kCompressedThumbnailResolution,
  266. minWidth: kCompressedThumbnailResolution,
  267. quality: 25,
  268. );
  269. }
  270. Future<void> clearCache(ente.File file) async {
  271. if (file.fileType == FileType.video) {
  272. VideoCacheManager.instance.removeFile(file.getDownloadUrl());
  273. } else {
  274. DefaultCacheManager().removeFile(file.getDownloadUrl());
  275. }
  276. final cachedThumbnail = io.File(
  277. Configuration.instance.getThumbnailCacheDirectory() +
  278. "/" +
  279. file.uploadedFileID.toString());
  280. if (cachedThumbnail.existsSync()) {
  281. await cachedThumbnail.delete();
  282. }
  283. }
  284. class _LivePhoto {
  285. final io.File image;
  286. final io.File video;
  287. _LivePhoto(this.image, this.video);
  288. }