file_util.dart 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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(
  72. THUMBNAIL_SMALL_SIZE,
  73. THUMBNAIL_SMALL_SIZE,
  74. quality: THUMBNAIL_SMALL_SIZE_QUALITY,
  75. )
  76. .then((data) {
  77. ThumbnailLruCache.put(file, THUMBNAIL_SMALL_SIZE, data);
  78. });
  79. });
  80. }
  81. Future<io.File> getNativeFile(File file) async {
  82. if (file.localID == null) {
  83. return getFileFromServer(file);
  84. } else {
  85. return file.getAsset().then((asset) => asset.file);
  86. }
  87. }
  88. Future<Uint8List> getBytes(File file, {int quality = 100}) async {
  89. if (file.localID == null) {
  90. return getFileFromServer(file).then((file) => file.readAsBytesSync());
  91. } else {
  92. return await getBytesFromDisk(file, quality: quality);
  93. }
  94. }
  95. Future<Uint8List> getBytesFromDisk(File file, {int quality = 100}) async {
  96. final originalBytes = (await file.getAsset()).originBytes;
  97. if (extension(file.title) == ".HEIC" || quality != 100) {
  98. return originalBytes.then((bytes) {
  99. return FlutterImageCompress.compressWithList(bytes, quality: quality)
  100. .then((converted) {
  101. return Uint8List.fromList(converted);
  102. });
  103. });
  104. } else {
  105. return originalBytes;
  106. }
  107. }
  108. final Map<int, Future<io.File>> fileDownloadsInProgress =
  109. Map<int, Future<io.File>>();
  110. final Map<int, Future<io.File>> thumbnailDownloadsInProgress =
  111. Map<int, Future<io.File>>();
  112. Future<io.File> getFileFromServer(File file,
  113. {ProgressCallback progressCallback}) async {
  114. final cacheManager = file.fileType == FileType.video
  115. ? VideoCacheManager()
  116. : DefaultCacheManager();
  117. if (!file.isEncrypted) {
  118. return cacheManager.getSingleFile(file.getDownloadUrl());
  119. } else {
  120. return cacheManager.getFileFromCache(file.getDownloadUrl()).then((info) {
  121. if (info == null) {
  122. if (!fileDownloadsInProgress.containsKey(file.uploadedFileID)) {
  123. fileDownloadsInProgress[file.uploadedFileID] = _downloadAndDecrypt(
  124. file,
  125. cacheManager,
  126. progressCallback: progressCallback,
  127. );
  128. }
  129. return fileDownloadsInProgress[file.uploadedFileID];
  130. } else {
  131. return info.file;
  132. }
  133. });
  134. }
  135. }
  136. Future<io.File> getThumbnailFromServer(File file) async {
  137. if (!file.isEncrypted) {
  138. return ThumbnailCacheManager()
  139. .getSingleFile(file.getThumbnailUrl())
  140. .then((data) {
  141. ThumbnailFileLruCache.put(file, data);
  142. return data;
  143. });
  144. } else {
  145. return ThumbnailCacheManager()
  146. .getFileFromCache(file.getThumbnailUrl())
  147. .then((info) {
  148. if (info == null) {
  149. if (!thumbnailDownloadsInProgress.containsKey(file.uploadedFileID)) {
  150. thumbnailDownloadsInProgress[file.uploadedFileID] =
  151. _downloadAndDecryptThumbnail(file).then((data) {
  152. ThumbnailFileLruCache.put(file, data);
  153. return data;
  154. });
  155. }
  156. return thumbnailDownloadsInProgress[file.uploadedFileID];
  157. } else {
  158. ThumbnailFileLruCache.put(file, info.file);
  159. return info.file;
  160. }
  161. });
  162. }
  163. }
  164. Future<io.File> _downloadAndDecrypt(File file, BaseCacheManager cacheManager,
  165. {ProgressCallback progressCallback}) async {
  166. logger.info("Downloading file " + file.uploadedFileID.toString());
  167. final encryptedFilePath = Configuration.instance.getTempDirectory() +
  168. file.generatedID.toString() +
  169. ".encrypted";
  170. final decryptedFilePath = Configuration.instance.getTempDirectory() +
  171. file.generatedID.toString() +
  172. ".decrypted";
  173. final encryptedFile = io.File(encryptedFilePath);
  174. final decryptedFile = io.File(decryptedFilePath);
  175. final startTime = DateTime.now().millisecondsSinceEpoch;
  176. return Dio()
  177. .download(
  178. file.getDownloadUrl(),
  179. encryptedFilePath,
  180. onReceiveProgress: progressCallback,
  181. )
  182. .then((response) async {
  183. if (response.statusCode != 200) {
  184. logger.warning("Could not download file: ", response.toString());
  185. return null;
  186. } else if (!encryptedFile.existsSync()) {
  187. logger.warning("File was not downloaded correctly.");
  188. return null;
  189. }
  190. logger.info("File downloaded: " + file.uploadedFileID.toString());
  191. logger.info("Download speed: " +
  192. (io.File(encryptedFilePath).lengthSync() /
  193. (DateTime.now().millisecondsSinceEpoch - startTime))
  194. .toString() +
  195. "kBps");
  196. await CryptoUtil.decryptFile(encryptedFilePath, decryptedFilePath,
  197. Sodium.base642bin(file.fileDecryptionHeader), decryptFileKey(file));
  198. logger.info("File decrypted: " + file.uploadedFileID.toString());
  199. io.File(encryptedFilePath).deleteSync();
  200. final fileExtension = extension(file.title).substring(1).toLowerCase();
  201. final cachedFile = await cacheManager.putFile(
  202. file.getDownloadUrl(),
  203. decryptedFile.readAsBytesSync(),
  204. eTag: file.getDownloadUrl(),
  205. maxAge: Duration(days: 365),
  206. fileExtension: fileExtension,
  207. );
  208. decryptedFile.deleteSync();
  209. fileDownloadsInProgress.remove(file.uploadedFileID);
  210. return cachedFile;
  211. }).catchError((e) {
  212. fileDownloadsInProgress.remove(file.uploadedFileID);
  213. });
  214. }
  215. Future<io.File> _downloadAndDecryptThumbnail(File file) async {
  216. final temporaryPath = Configuration.instance.getTempDirectory() +
  217. file.generatedID.toString() +
  218. "_thumbnail.decrypted";
  219. return Dio().download(file.getThumbnailUrl(), temporaryPath).then((_) async {
  220. final encryptedFile = io.File(temporaryPath);
  221. final thumbnailDecryptionKey = decryptFileKey(file);
  222. final data = CryptoUtil.decryptChaCha(
  223. encryptedFile.readAsBytesSync(),
  224. thumbnailDecryptionKey,
  225. Sodium.base642bin(file.thumbnailDecryptionHeader),
  226. );
  227. encryptedFile.deleteSync();
  228. return ThumbnailCacheManager().putFile(
  229. file.getThumbnailUrl(),
  230. data,
  231. eTag: file.getThumbnailUrl(),
  232. maxAge: Duration(days: 365),
  233. );
  234. });
  235. }
  236. Uint8List decryptFileKey(File file) {
  237. final encryptedKey = Sodium.base642bin(file.encryptedKey);
  238. final nonce = Sodium.base642bin(file.keyDecryptionNonce);
  239. final collectionKey =
  240. CollectionsService.instance.getCollectionKey(file.collectionID);
  241. return CryptoUtil.decryptSync(encryptedKey, collectionKey, nonce);
  242. }