file_util.dart 6.8 KB

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