file_util.dart 11 KB

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