file_util.dart 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import 'dart:io' as io;
  2. import 'dart:typed_data';
  3. import 'package:flutter_sodium/flutter_sodium.dart';
  4. import 'package:logging/logging.dart';
  5. import 'package:path/path.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:photo_manager/photo_manager.dart';
  10. import 'package:photos/core/cache/image_cache.dart';
  11. import 'package:photos/core/cache/thumbnail_cache.dart';
  12. import 'package:photos/core/cache/thumbnail_cache_manager.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/db/files_db.dart';
  17. import 'package:photos/models/encrypted_file_attributes.dart';
  18. import 'package:photos/models/encryption_attribute.dart';
  19. import 'package:photos/models/file.dart';
  20. import 'package:photos/models/file_type.dart';
  21. import 'crypto_util.dart';
  22. final logger = Logger("FileUtil");
  23. Future<void> deleteFiles(List<File> files,
  24. {bool deleteEveryWhere = false}) async {
  25. await PhotoManager.editor
  26. .deleteWithIds(files.map((file) => file.localID).toList());
  27. for (File file in files) {
  28. deleteEveryWhere
  29. ? await FilesDB.instance.markForDeletion(file)
  30. : await FilesDB.instance.delete(file);
  31. }
  32. }
  33. void preloadFile(File file) {
  34. if (file.fileType == FileType.video) {
  35. return;
  36. }
  37. if (file.localID == null) {
  38. // getFileFromServer(file);
  39. } else {
  40. if (FileLruCache.get(file) == null) {
  41. file.getAsset().then((asset) {
  42. asset.file.then((assetFile) {
  43. FileLruCache.put(file, assetFile);
  44. });
  45. });
  46. }
  47. }
  48. }
  49. void preloadLocalFileThumbnail(File file) {
  50. if (file.localID == null ||
  51. ThumbnailLruCache.get(file, THUMBNAIL_SMALL_SIZE) != null) {
  52. return;
  53. }
  54. file.getAsset().then((asset) {
  55. asset
  56. .thumbDataWithSize(THUMBNAIL_SMALL_SIZE, THUMBNAIL_SMALL_SIZE)
  57. .then((data) {
  58. ThumbnailLruCache.put(file, THUMBNAIL_SMALL_SIZE, data);
  59. });
  60. });
  61. }
  62. Future<io.File> getNativeFile(File file) async {
  63. if (file.localID == null) {
  64. return getFileFromServer(file);
  65. } else {
  66. return file.getAsset().then((asset) => asset.file);
  67. }
  68. }
  69. Future<Uint8List> getBytes(File file, {int quality = 100}) async {
  70. if (file.localID == null) {
  71. return getFileFromServer(file).then((file) => file.readAsBytesSync());
  72. } else {
  73. return await getBytesFromDisk(file, quality: quality);
  74. }
  75. }
  76. Future<Uint8List> getBytesFromDisk(File file, {int quality = 100}) async {
  77. final originalBytes = (await file.getAsset()).originBytes;
  78. if (extension(file.title) == ".HEIC" || quality != 100) {
  79. return originalBytes.then((bytes) {
  80. return FlutterImageCompress.compressWithList(bytes, quality: quality)
  81. .then((converted) {
  82. return Uint8List.fromList(converted);
  83. });
  84. });
  85. } else {
  86. return originalBytes;
  87. }
  88. }
  89. final Map<int, Future<io.File>> downloadsInProgress =
  90. Map<int, Future<io.File>>();
  91. Future<io.File> getFileFromServer(File file,
  92. {ProgressCallback progressCallback}) async {
  93. final cacheManager = file.fileType == FileType.video
  94. ? VideoCacheManager()
  95. : DefaultCacheManager();
  96. if (!file.isEncrypted) {
  97. return cacheManager.getSingleFile(file.getDownloadUrl());
  98. } else {
  99. return cacheManager.getFileFromCache(file.getDownloadUrl()).then((info) {
  100. if (info == null) {
  101. if (!downloadsInProgress.containsKey(file.uploadedFileID)) {
  102. downloadsInProgress[file.uploadedFileID] = _downloadAndDecrypt(
  103. file,
  104. cacheManager,
  105. progressCallback: progressCallback,
  106. );
  107. }
  108. return downloadsInProgress[file.uploadedFileID];
  109. } else {
  110. return info.file;
  111. }
  112. });
  113. }
  114. }
  115. Future<io.File> getThumbnailFromServer(File file) async {
  116. if (!file.isEncrypted) {
  117. return ThumbnailCacheManager()
  118. .getSingleFile(file.getThumbnailUrl())
  119. .then((data) {
  120. ThumbnailFileLruCache.put(file, data);
  121. return data;
  122. });
  123. } else {
  124. return ThumbnailCacheManager()
  125. .getFileFromCache(file.getThumbnailUrl())
  126. .then((info) {
  127. if (info == null) {
  128. return _downloadAndDecryptThumbnail(file).then((data) {
  129. ThumbnailFileLruCache.put(file, data);
  130. return data;
  131. });
  132. } else {
  133. ThumbnailFileLruCache.put(file, info.file);
  134. return info.file;
  135. }
  136. });
  137. }
  138. }
  139. Future<io.File> _downloadAndDecrypt(File file, BaseCacheManager cacheManager,
  140. {ProgressCallback progressCallback}) async {
  141. logger.info("Downloading file " + file.uploadedFileID.toString());
  142. final encryptedFilePath = Configuration.instance.getTempDirectory() +
  143. file.generatedID.toString() +
  144. ".encrypted";
  145. final decryptedFilePath = Configuration.instance.getTempDirectory() +
  146. file.generatedID.toString() +
  147. ".decrypted";
  148. final encryptedFile = io.File(encryptedFilePath);
  149. final decryptedFile = io.File(decryptedFilePath);
  150. return Dio()
  151. .download(
  152. file.getDownloadUrl(),
  153. encryptedFilePath,
  154. onReceiveProgress: progressCallback,
  155. )
  156. .then((response) async {
  157. if (response.statusCode != 200) {
  158. logger.warning("Could not download file: ", response.toString());
  159. return null;
  160. } else if (!encryptedFile.existsSync()) {
  161. logger.warning("File was not downloaded correctly.");
  162. return null;
  163. }
  164. logger.info("File downloaded: " + file.uploadedFileID.toString());
  165. var attributes = ChaChaAttributes(
  166. EncryptionAttribute(
  167. bytes: await CryptoUtil.decrypt(
  168. Sodium.base642bin(file.fileDecryptionParams.encryptedKey),
  169. Configuration.instance.getKey(),
  170. Sodium.base642bin(file.fileDecryptionParams.keyDecryptionNonce),
  171. )),
  172. EncryptionAttribute(base64: file.fileDecryptionParams.header),
  173. );
  174. await CryptoUtil.decryptFile(
  175. encryptedFilePath, decryptedFilePath, attributes);
  176. logger.info("File decrypted: " + file.uploadedFileID.toString());
  177. io.File(encryptedFilePath).deleteSync();
  178. final fileExtension = extension(file.title).substring(1).toLowerCase();
  179. final cachedFile = await cacheManager.putFile(
  180. file.getDownloadUrl(),
  181. decryptedFile.readAsBytesSync(),
  182. eTag: file.getDownloadUrl(),
  183. maxAge: Duration(days: 365),
  184. fileExtension: fileExtension,
  185. );
  186. decryptedFile.deleteSync();
  187. downloadsInProgress.remove(file.uploadedFileID);
  188. return cachedFile;
  189. });
  190. }
  191. Future<io.File> _downloadAndDecryptThumbnail(File file) async {
  192. final temporaryPath = Configuration.instance.getTempDirectory() +
  193. file.generatedID.toString() +
  194. "_thumbnail.decrypted";
  195. return Dio().download(file.getThumbnailUrl(), temporaryPath).then((_) async {
  196. final encryptedFile = io.File(temporaryPath);
  197. final thumbnailDecryptionKey = await CryptoUtil.decrypt(
  198. Sodium.base642bin(file.thumbnailDecryptionParams.encryptedKey),
  199. Configuration.instance.getKey(),
  200. Sodium.base642bin(file.thumbnailDecryptionParams.keyDecryptionNonce));
  201. final data = await CryptoUtil.decrypt(
  202. encryptedFile.readAsBytesSync(),
  203. thumbnailDecryptionKey,
  204. Sodium.base642bin(file.thumbnailDecryptionParams.nonce),
  205. );
  206. encryptedFile.deleteSync();
  207. return ThumbnailCacheManager().putFile(
  208. file.getThumbnailUrl(),
  209. data,
  210. eTag: file.getThumbnailUrl(),
  211. maxAge: Duration(days: 365),
  212. );
  213. });
  214. }