file_util.dart 8.4 KB

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