file_util.dart 7.0 KB

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