file_util.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 getSharedMediaPathFromLocalID(file.localID);
  83. }
  84. String getSharedMediaPathFromLocalID(String localID) {
  85. if (localID.startsWith(kOldSharedMediaIdentifier)) {
  86. return Configuration.instance.getOldSharedMediaCacheDirectory() +
  87. "/" +
  88. localID.replaceAll(kOldSharedMediaIdentifier, '');
  89. } else {
  90. return Configuration.instance.getSharedMediaDirectory() +
  91. "/" +
  92. localID.replaceAll(kSharedMediaIdentifier, '');
  93. }
  94. }
  95. void preloadThumbnail(ente.File file) {
  96. if (file.isRemoteFile()) {
  97. getThumbnailFromServer(file);
  98. } else {
  99. getThumbnailFromLocal(file);
  100. }
  101. }
  102. final Map<String, Future<io.File>> fileDownloadsInProgress =
  103. <String, Future<io.File>>{};
  104. Future<io.File> getFileFromServer(
  105. ente.File file, {
  106. ProgressCallback progressCallback,
  107. bool liveVideo = false, // only needed in case of live photos
  108. }) async {
  109. final cacheManager = (file.fileType == FileType.video || liveVideo)
  110. ? VideoCacheManager.instance
  111. : DefaultCacheManager();
  112. final fileFromCache =
  113. await cacheManager.getFileFromCache(file.getDownloadUrl());
  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.getDownloadUrl());
  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. 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. List<int> bytes = await decryptedFile.readAsBytes();
  183. 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. String filename = archiveFile.name;
  189. String fileExtension = getExtension(archiveFile.name);
  190. String decodePath =
  191. tempPath + file.uploadedFileID.toString() + filename;
  192. 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. imageConvertedFile = await FlutterImageCompress.compressAndGetFile(
  201. decodePath,
  202. decodePath + ".jpg",
  203. keepExif: true,
  204. );
  205. await imageFile.delete();
  206. }
  207. imageFileCache = await DefaultCacheManager().putFile(
  208. file.getDownloadUrl(),
  209. await imageConvertedFile.readAsBytes(),
  210. eTag: file.getDownloadUrl(),
  211. maxAge: const Duration(days: 365),
  212. fileExtension: fileExtension,
  213. );
  214. await imageConvertedFile.delete();
  215. } else if (filename.startsWith("video")) {
  216. final videoFile = io.File(decodePath);
  217. await videoFile.create(recursive: true);
  218. await videoFile.writeAsBytes(data);
  219. videoFileCache = await VideoCacheManager.instance.putFile(
  220. file.getDownloadUrl(),
  221. await videoFile.readAsBytes(),
  222. eTag: file.getDownloadUrl(),
  223. maxAge: const Duration(days: 365),
  224. fileExtension: fileExtension,
  225. );
  226. await videoFile.delete();
  227. }
  228. }
  229. }
  230. return _LivePhoto(imageFileCache, videoFileCache);
  231. }).catchError((e) {
  232. _logger.warning("failed to download live photos : ${file.tag()}", e);
  233. throw e;
  234. });
  235. }
  236. Future<io.File> _downloadAndCache(
  237. ente.File file,
  238. BaseCacheManager cacheManager, {
  239. ProgressCallback progressCallback,
  240. }) async {
  241. return downloadAndDecrypt(file, progressCallback: progressCallback)
  242. .then((decryptedFile) async {
  243. if (decryptedFile == null) {
  244. return null;
  245. }
  246. var decryptedFilePath = decryptedFile.path;
  247. String fileExtension = getExtension(file.title);
  248. var outputFile = decryptedFile;
  249. if ((fileExtension == "unknown" && file.fileType == FileType.image) ||
  250. (io.Platform.isAndroid && fileExtension == "heic")) {
  251. outputFile = await FlutterImageCompress.compressAndGetFile(
  252. decryptedFilePath,
  253. decryptedFilePath + ".jpg",
  254. keepExif: true,
  255. );
  256. await decryptedFile.delete();
  257. }
  258. final cachedFile = await cacheManager.putFile(
  259. file.getDownloadUrl(),
  260. await outputFile.readAsBytes(),
  261. eTag: file.getDownloadUrl(),
  262. maxAge: const Duration(days: 365),
  263. fileExtension: fileExtension,
  264. );
  265. await outputFile.delete();
  266. return cachedFile;
  267. }).catchError((e) {
  268. _logger.warning("failed to download file : ${file.tag()}", e);
  269. throw e;
  270. });
  271. }
  272. String getExtension(String nameOrPath) {
  273. var fileExtension = "unknown";
  274. try {
  275. fileExtension = extension(nameOrPath).substring(1).toLowerCase();
  276. } catch (e) {
  277. _logger.severe("Could not capture file extension");
  278. }
  279. return fileExtension;
  280. }
  281. Future<Uint8List> compressThumbnail(Uint8List thumbnail) {
  282. return FlutterImageCompress.compressWithList(
  283. thumbnail,
  284. minHeight: kCompressedThumbnailResolution,
  285. minWidth: kCompressedThumbnailResolution,
  286. quality: 25,
  287. );
  288. }
  289. Future<void> clearCache(ente.File file) async {
  290. if (file.fileType == FileType.video) {
  291. VideoCacheManager.instance.removeFile(file.getDownloadUrl());
  292. } else {
  293. DefaultCacheManager().removeFile(file.getDownloadUrl());
  294. }
  295. final cachedThumbnail = io.File(
  296. Configuration.instance.getThumbnailCacheDirectory() +
  297. "/" +
  298. file.uploadedFileID.toString(),
  299. );
  300. if (cachedThumbnail.existsSync()) {
  301. await cachedThumbnail.delete();
  302. }
  303. ThumbnailLruCache.clearCache(file);
  304. }
  305. class _LivePhoto {
  306. final io.File image;
  307. final io.File video;
  308. _LivePhoto(this.image, this.video);
  309. }