file_util.dart 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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>> 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. final startTime = DateTime.now().millisecondsSinceEpoch;
  151. return Dio()
  152. .download(
  153. file.getDownloadUrl(),
  154. encryptedFilePath,
  155. onReceiveProgress: progressCallback,
  156. )
  157. .then((response) async {
  158. if (response.statusCode != 200) {
  159. logger.warning("Could not download file: ", response.toString());
  160. return null;
  161. } else if (!encryptedFile.existsSync()) {
  162. logger.warning("File was not downloaded correctly.");
  163. return null;
  164. }
  165. logger.info("File downloaded: " + file.uploadedFileID.toString());
  166. logger.info("Download speed: " +
  167. (io.File(encryptedFilePath).lengthSync() /
  168. (DateTime.now().millisecondsSinceEpoch - startTime))
  169. .toString() +
  170. "kBps");
  171. await CryptoUtil.decryptFile(encryptedFilePath, decryptedFilePath,
  172. Sodium.base642bin(file.fileDecryptionHeader), decryptFileKey(file));
  173. logger.info("File decrypted: " + file.uploadedFileID.toString());
  174. io.File(encryptedFilePath).deleteSync();
  175. final fileExtension = extension(file.title).substring(1).toLowerCase();
  176. final cachedFile = await cacheManager.putFile(
  177. file.getDownloadUrl(),
  178. decryptedFile.readAsBytesSync(),
  179. eTag: file.getDownloadUrl(),
  180. maxAge: Duration(days: 365),
  181. fileExtension: fileExtension,
  182. );
  183. decryptedFile.deleteSync();
  184. downloadsInProgress.remove(file.uploadedFileID);
  185. return cachedFile;
  186. }).catchError((e) {
  187. downloadsInProgress.remove(file.uploadedFileID);
  188. });
  189. }
  190. Future<io.File> _downloadAndDecryptThumbnail(File file) async {
  191. final temporaryPath = Configuration.instance.getTempDirectory() +
  192. file.generatedID.toString() +
  193. "_thumbnail.decrypted";
  194. return Dio().download(file.getThumbnailUrl(), temporaryPath).then((_) async {
  195. final encryptedFile = io.File(temporaryPath);
  196. final thumbnailDecryptionKey = decryptFileKey(file);
  197. final data = CryptoUtil.decryptChaCha(
  198. encryptedFile.readAsBytesSync(),
  199. thumbnailDecryptionKey,
  200. Sodium.base642bin(file.thumbnailDecryptionHeader),
  201. );
  202. encryptedFile.deleteSync();
  203. return ThumbnailCacheManager().putFile(
  204. file.getThumbnailUrl(),
  205. data,
  206. eTag: file.getThumbnailUrl(),
  207. maxAge: Duration(days: 365),
  208. );
  209. });
  210. }
  211. Uint8List decryptFileKey(File file) {
  212. final encryptedKey = Sodium.base642bin(file.encryptedKey);
  213. final nonce = Sodium.base642bin(file.keyDecryptionNonce);
  214. final collectionKey =
  215. CollectionsService.instance.getCollectionKey(file.collectionID);
  216. return CryptoUtil.decryptSync(encryptedKey, collectionKey, nonce);
  217. }