file_util.dart 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import 'dart:async';
  2. import 'dart:io' as io;
  3. import 'dart:typed_data';
  4. import 'package:dio/dio.dart';
  5. import 'package:flutter_cache_manager/flutter_cache_manager.dart';
  6. import 'package:flutter_image_compress/flutter_image_compress.dart';
  7. import 'package:flutter_sodium/flutter_sodium.dart';
  8. import 'package:logging/logging.dart';
  9. import 'package:path/path.dart';
  10. import 'package:photos/core/cache/image_cache.dart';
  11. import 'package:photos/core/cache/video_cache_manager.dart';
  12. import 'package:photos/core/configuration.dart';
  13. import 'package:photos/core/constants.dart';
  14. import 'package:photos/core/network.dart';
  15. import 'package:photos/models/file.dart' as ente;
  16. import 'package:photos/models/file_type.dart';
  17. import 'package:photos/services/collections_service.dart';
  18. import 'package:photos/utils/thumbnail_util.dart';
  19. import 'crypto_util.dart';
  20. import 'file_uploader_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. Future<io.File> getFile(ente.File file) async {
  29. if (file.isRemoteFile()) {
  30. return getFileFromServer(file);
  31. } else {
  32. final cachedFile = FileLruCache.get(file);
  33. if (cachedFile == null) {
  34. final diskFile = await _getLocalDiskFile(file);
  35. FileLruCache.put(file, diskFile);
  36. return diskFile;
  37. }
  38. return cachedFile;
  39. }
  40. }
  41. Future<io.File> _getLocalDiskFile(ente.File file) async {
  42. if (file.isSharedMediaToAppSandbox()) {
  43. var localFile = io.File(getSharedMediaFilePath(file));
  44. return localFile.exists().then((exist) {
  45. return exist ? localFile : null;
  46. });
  47. } else {
  48. return file.getAsset().then((asset) async {
  49. if (asset == null || !(await asset.exists)) {
  50. return null;
  51. }
  52. return asset.file;
  53. });
  54. }
  55. }
  56. String getSharedMediaFilePath(ente.File file) {
  57. return Configuration.instance.getSharedMediaCacheDirectory()
  58. + "/" + file.localID.replaceAll(kSharedMediaIdentifier, '');
  59. }
  60. void preloadThumbnail(ente.File file) {
  61. if (file.isRemoteFile()) {
  62. getThumbnailFromServer(file);
  63. } else {
  64. getThumbnailFromLocal(file);
  65. }
  66. }
  67. final Map<int, Future<io.File>> fileDownloadsInProgress =
  68. Map<int, Future<io.File>>();
  69. Future<io.File> getFileFromServer(ente.File file,
  70. {ProgressCallback progressCallback}) async {
  71. final cacheManager = file.fileType == FileType.video
  72. ? VideoCacheManager.instance
  73. : DefaultCacheManager();
  74. return cacheManager.getFileFromCache(file.getDownloadUrl()).then((info) {
  75. if (info == null) {
  76. if (!fileDownloadsInProgress.containsKey(file.uploadedFileID)) {
  77. fileDownloadsInProgress[file.uploadedFileID] = _downloadAndDecrypt(
  78. file,
  79. cacheManager,
  80. progressCallback: progressCallback,
  81. );
  82. }
  83. return fileDownloadsInProgress[file.uploadedFileID];
  84. } else {
  85. return info.file;
  86. }
  87. });
  88. }
  89. Future<io.File> _downloadAndDecrypt(
  90. ente.File file, BaseCacheManager cacheManager,
  91. {ProgressCallback progressCallback}) async {
  92. _logger.info("Downloading file " + file.uploadedFileID.toString());
  93. final encryptedFilePath = Configuration.instance.getTempDirectory() +
  94. file.generatedID.toString() +
  95. ".encrypted";
  96. final decryptedFilePath = Configuration.instance.getTempDirectory() +
  97. file.generatedID.toString() +
  98. ".decrypted";
  99. final encryptedFile = io.File(encryptedFilePath);
  100. final decryptedFile = io.File(decryptedFilePath);
  101. final startTime = DateTime.now().millisecondsSinceEpoch;
  102. return Network.instance
  103. .getDio()
  104. .download(
  105. file.getDownloadUrl(),
  106. encryptedFilePath,
  107. options: Options(
  108. headers: {"X-Auth-Token": Configuration.instance.getToken()},
  109. ),
  110. onReceiveProgress: progressCallback,
  111. )
  112. .then((response) async {
  113. if (response.statusCode != 200) {
  114. _logger.warning("Could not download file: ", response.toString());
  115. return null;
  116. } else if (!encryptedFile.existsSync()) {
  117. _logger.warning("File was not downloaded correctly.");
  118. return null;
  119. }
  120. _logger.info("File downloaded: " + file.uploadedFileID.toString());
  121. _logger.info("Download speed: " +
  122. (io.File(encryptedFilePath).lengthSync() /
  123. (DateTime.now().millisecondsSinceEpoch - startTime))
  124. .toString() +
  125. "kBps");
  126. await CryptoUtil.decryptFile(encryptedFilePath, decryptedFilePath,
  127. Sodium.base642bin(file.fileDecryptionHeader), decryptFileKey(file));
  128. _logger.info("File decrypted: " + file.uploadedFileID.toString());
  129. encryptedFile.deleteSync();
  130. var fileExtension = "unknown";
  131. try {
  132. fileExtension = extension(file.title).substring(1).toLowerCase();
  133. } catch (e) {
  134. _logger.severe("Could not capture file extension");
  135. }
  136. var outputFile = decryptedFile;
  137. if ((fileExtension == "unknown" && file.fileType == FileType.image) ||
  138. (io.Platform.isAndroid && fileExtension == "heic")) {
  139. outputFile = await FlutterImageCompress.compressAndGetFile(
  140. decryptedFilePath,
  141. decryptedFilePath + ".jpg",
  142. keepExif: true,
  143. );
  144. decryptedFile.deleteSync();
  145. }
  146. final cachedFile = await cacheManager.putFile(
  147. file.getDownloadUrl(),
  148. outputFile.readAsBytesSync(),
  149. eTag: file.getDownloadUrl(),
  150. maxAge: Duration(days: 365),
  151. fileExtension: fileExtension,
  152. );
  153. outputFile.deleteSync();
  154. fileDownloadsInProgress.remove(file.uploadedFileID);
  155. return cachedFile;
  156. }).catchError((e) {
  157. fileDownloadsInProgress.remove(file.uploadedFileID);
  158. });
  159. }
  160. Uint8List decryptFileKey(ente.File file) {
  161. final encryptedKey = Sodium.base642bin(file.encryptedKey);
  162. final nonce = Sodium.base642bin(file.keyDecryptionNonce);
  163. final collectionKey =
  164. CollectionsService.instance.getCollectionKey(file.collectionID);
  165. return CryptoUtil.decryptSync(encryptedKey, collectionKey, nonce);
  166. }
  167. Future<Uint8List> compressThumbnail(Uint8List thumbnail) {
  168. return FlutterImageCompress.compressWithList(
  169. thumbnail,
  170. minHeight: kCompressedThumbnailResolution,
  171. minWidth: kCompressedThumbnailResolution,
  172. quality: 25,
  173. );
  174. }
  175. void clearCache(ente.File file) {
  176. if (file.fileType == FileType.video) {
  177. VideoCacheManager.instance.removeFile(file.getDownloadUrl());
  178. } else {
  179. DefaultCacheManager().removeFile(file.getDownloadUrl());
  180. }
  181. final cachedThumbnail = io.File(
  182. Configuration.instance.getThumbnailCacheDirectory() +
  183. "/" +
  184. file.uploadedFileID.toString());
  185. if (cachedThumbnail.existsSync()) {
  186. cachedThumbnail.deleteSync();
  187. }
  188. }