file_util.dart 9.6 KB

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