file_util.dart 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 'package:photos/repositories/file_repository.dart';
  20. import 'package:photos/services/collections_service.dart';
  21. import 'package:photos/services/sync_service.dart';
  22. import 'crypto_util.dart';
  23. final logger = Logger("FileUtil");
  24. Future<void> deleteFiles(List<File> files) async {
  25. await PhotoManager.editor
  26. .deleteWithIds(files.map((file) => file.localID).toList());
  27. for (File file in files) {
  28. await FilesDB.instance.markForDeletion(file);
  29. }
  30. await FileRepository.instance.reloadFiles();
  31. SyncService.instance.sync();
  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>> fileDownloadsInProgress =
  90. Map<int, Future<io.File>>();
  91. final Map<int, Future<io.File>> thumbnailDownloadsInProgress =
  92. Map<int, Future<io.File>>();
  93. Future<io.File> getFileFromServer(File file,
  94. {ProgressCallback progressCallback}) async {
  95. final cacheManager = file.fileType == FileType.video
  96. ? VideoCacheManager()
  97. : DefaultCacheManager();
  98. if (!file.isEncrypted) {
  99. return cacheManager.getSingleFile(file.getDownloadUrl());
  100. } else {
  101. return cacheManager.getFileFromCache(file.getDownloadUrl()).then((info) {
  102. if (info == null) {
  103. if (!fileDownloadsInProgress.containsKey(file.uploadedFileID)) {
  104. fileDownloadsInProgress[file.uploadedFileID] = _downloadAndDecrypt(
  105. file,
  106. cacheManager,
  107. progressCallback: progressCallback,
  108. );
  109. }
  110. return fileDownloadsInProgress[file.uploadedFileID];
  111. } else {
  112. return info.file;
  113. }
  114. });
  115. }
  116. }
  117. Future<io.File> getThumbnailFromServer(File file) async {
  118. if (!file.isEncrypted) {
  119. return ThumbnailCacheManager()
  120. .getSingleFile(file.getThumbnailUrl())
  121. .then((data) {
  122. ThumbnailFileLruCache.put(file, data);
  123. return data;
  124. });
  125. } else {
  126. return ThumbnailCacheManager()
  127. .getFileFromCache(file.getThumbnailUrl())
  128. .then((info) {
  129. if (info == null) {
  130. if (!thumbnailDownloadsInProgress.containsKey(file.uploadedFileID)) {
  131. thumbnailDownloadsInProgress[file.uploadedFileID] =
  132. _downloadAndDecryptThumbnail(file).then((data) {
  133. ThumbnailFileLruCache.put(file, data);
  134. return data;
  135. });
  136. }
  137. return thumbnailDownloadsInProgress[file.uploadedFileID];
  138. } else {
  139. ThumbnailFileLruCache.put(file, info.file);
  140. return info.file;
  141. }
  142. });
  143. }
  144. }
  145. Future<io.File> _downloadAndDecrypt(File file, BaseCacheManager cacheManager,
  146. {ProgressCallback progressCallback}) async {
  147. logger.info("Downloading file " + file.uploadedFileID.toString());
  148. final encryptedFilePath = Configuration.instance.getTempDirectory() +
  149. file.generatedID.toString() +
  150. ".encrypted";
  151. final decryptedFilePath = Configuration.instance.getTempDirectory() +
  152. file.generatedID.toString() +
  153. ".decrypted";
  154. final encryptedFile = io.File(encryptedFilePath);
  155. final decryptedFile = io.File(decryptedFilePath);
  156. final startTime = DateTime.now().millisecondsSinceEpoch;
  157. return Dio()
  158. .download(
  159. file.getDownloadUrl(),
  160. encryptedFilePath,
  161. onReceiveProgress: progressCallback,
  162. )
  163. .then((response) async {
  164. if (response.statusCode != 200) {
  165. logger.warning("Could not download file: ", response.toString());
  166. return null;
  167. } else if (!encryptedFile.existsSync()) {
  168. logger.warning("File was not downloaded correctly.");
  169. return null;
  170. }
  171. logger.info("File downloaded: " + file.uploadedFileID.toString());
  172. logger.info("Download speed: " +
  173. (io.File(encryptedFilePath).lengthSync() /
  174. (DateTime.now().millisecondsSinceEpoch - startTime))
  175. .toString() +
  176. "kBps");
  177. await CryptoUtil.decryptFile(encryptedFilePath, decryptedFilePath,
  178. Sodium.base642bin(file.fileDecryptionHeader), decryptFileKey(file));
  179. logger.info("File decrypted: " + file.uploadedFileID.toString());
  180. io.File(encryptedFilePath).deleteSync();
  181. final fileExtension = extension(file.title).substring(1).toLowerCase();
  182. final cachedFile = await cacheManager.putFile(
  183. file.getDownloadUrl(),
  184. decryptedFile.readAsBytesSync(),
  185. eTag: file.getDownloadUrl(),
  186. maxAge: Duration(days: 365),
  187. fileExtension: fileExtension,
  188. );
  189. decryptedFile.deleteSync();
  190. fileDownloadsInProgress.remove(file.uploadedFileID);
  191. return cachedFile;
  192. }).catchError((e) {
  193. fileDownloadsInProgress.remove(file.uploadedFileID);
  194. });
  195. }
  196. Future<io.File> _downloadAndDecryptThumbnail(File file) async {
  197. final temporaryPath = Configuration.instance.getTempDirectory() +
  198. file.generatedID.toString() +
  199. "_thumbnail.decrypted";
  200. return Dio().download(file.getThumbnailUrl(), temporaryPath).then((_) async {
  201. final encryptedFile = io.File(temporaryPath);
  202. final thumbnailDecryptionKey = decryptFileKey(file);
  203. final data = CryptoUtil.decryptChaCha(
  204. encryptedFile.readAsBytesSync(),
  205. thumbnailDecryptionKey,
  206. Sodium.base642bin(file.thumbnailDecryptionHeader),
  207. );
  208. encryptedFile.deleteSync();
  209. return ThumbnailCacheManager().putFile(
  210. file.getThumbnailUrl(),
  211. data,
  212. eTag: file.getThumbnailUrl(),
  213. maxAge: Duration(days: 365),
  214. );
  215. });
  216. }
  217. Uint8List decryptFileKey(File file) {
  218. final encryptedKey = Sodium.base642bin(file.encryptedKey);
  219. final nonce = Sodium.base642bin(file.keyDecryptionNonce);
  220. final collectionKey =
  221. CollectionsService.instance.getCollectionKey(file.collectionID);
  222. return CryptoUtil.decryptSync(encryptedKey, collectionKey, nonce);
  223. }