file_util.dart 6.4 KB

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