file_util.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import 'dart:io' as io;
  2. import 'dart:io';
  3. import 'dart:typed_data';
  4. import 'package:flutter/widgets.dart';
  5. import 'package:flutter_sodium/flutter_sodium.dart';
  6. import 'package:logging/logging.dart';
  7. import 'package:path/path.dart';
  8. import 'package:dio/dio.dart';
  9. import 'package:flutter_cache_manager/flutter_cache_manager.dart';
  10. import 'package:flutter_image_compress/flutter_image_compress.dart';
  11. import 'package:photo_manager/photo_manager.dart';
  12. import 'package:photos/core/cache/image_cache.dart';
  13. import 'package:photos/core/cache/thumbnail_cache.dart';
  14. import 'package:photos/core/cache/thumbnail_cache_manager.dart';
  15. import 'package:photos/core/cache/video_cache_manager.dart';
  16. import 'package:photos/core/configuration.dart';
  17. import 'package:photos/core/constants.dart';
  18. import 'package:photos/core/event_bus.dart';
  19. import 'package:photos/core/network.dart';
  20. import 'package:photos/db/files_db.dart';
  21. import 'package:photos/events/collection_updated_event.dart';
  22. import 'package:photos/models/file.dart';
  23. import 'package:photos/models/file_type.dart';
  24. import 'package:photos/repositories/file_repository.dart';
  25. import 'package:photos/services/collections_service.dart';
  26. import 'package:photos/services/sync_service.dart';
  27. import 'package:photos/utils/dialog_util.dart';
  28. import 'crypto_util.dart';
  29. final _logger = Logger("FileUtil");
  30. Future<void> deleteFilesFromEverywhere(
  31. BuildContext context, List<File> files) async {
  32. final dialog = createProgressDialog(context, "deleting...");
  33. await dialog.show();
  34. final localIDs = List<String>();
  35. for (final file in files) {
  36. if (file.localID != null) {
  37. localIDs.add(file.localID);
  38. }
  39. }
  40. final deletedIDs =
  41. (await PhotoManager.editor.deleteWithIds(localIDs)).toSet();
  42. bool hasUploadedFiles = false;
  43. for (final file in files) {
  44. if (file.localID != null) {
  45. // Remove only those files that have been removed from disk
  46. if (deletedIDs.contains(file.localID)) {
  47. if (file.uploadedFileID != null) {
  48. hasUploadedFiles = true;
  49. await FilesDB.instance.markForDeletion(file.uploadedFileID);
  50. } else {
  51. await FilesDB.instance.deleteLocalFile(file.localID);
  52. }
  53. }
  54. } else {
  55. hasUploadedFiles = true;
  56. await FilesDB.instance.markForDeletion(file.uploadedFileID);
  57. }
  58. await dialog.hide();
  59. }
  60. await FileRepository.instance.reloadFiles();
  61. if (hasUploadedFiles) {
  62. Bus.instance.fire(CollectionUpdatedEvent());
  63. // TODO: Blocking call?
  64. SyncService.instance.deleteFilesOnServer();
  65. }
  66. }
  67. Future<void> deleteFilesOnDeviceOnly(
  68. BuildContext context, List<File> files) async {
  69. final dialog = createProgressDialog(context, "deleting...");
  70. await dialog.show();
  71. final localIDs = List<String>();
  72. for (final file in files) {
  73. if (file.localID != null) {
  74. localIDs.add(file.localID);
  75. }
  76. }
  77. final deletedIDs =
  78. (await PhotoManager.editor.deleteWithIds(localIDs)).toSet();
  79. for (final file in files) {
  80. // Remove only those files that have been removed from disk
  81. if (deletedIDs.contains(file.localID)) {
  82. file.localID = null;
  83. FilesDB.instance.update(file);
  84. }
  85. }
  86. await FileRepository.instance.reloadFiles();
  87. await dialog.hide();
  88. }
  89. void preloadFile(File file) {
  90. if (file.fileType == FileType.video) {
  91. return;
  92. }
  93. if (file.localID == null) {
  94. // getFileFromServer(file);
  95. } else {
  96. if (FileLruCache.get(file) == null) {
  97. file.getAsset().then((asset) {
  98. asset.file.then((assetFile) {
  99. FileLruCache.put(file, assetFile);
  100. });
  101. });
  102. }
  103. }
  104. }
  105. void preloadLocalFileThumbnail(File file) {
  106. if (file.localID == null ||
  107. ThumbnailLruCache.get(file, THUMBNAIL_SMALL_SIZE) != null) {
  108. return;
  109. }
  110. file.getAsset().then((asset) {
  111. asset
  112. .thumbDataWithSize(
  113. THUMBNAIL_SMALL_SIZE,
  114. THUMBNAIL_SMALL_SIZE,
  115. quality: THUMBNAIL_SMALL_SIZE_QUALITY,
  116. )
  117. .then((data) {
  118. ThumbnailLruCache.put(file, THUMBNAIL_SMALL_SIZE, data);
  119. });
  120. });
  121. }
  122. Future<io.File> getNativeFile(File file) async {
  123. if (file.localID == null) {
  124. return getFileFromServer(file);
  125. } else {
  126. return file.getAsset().then((asset) => asset.originFile);
  127. }
  128. }
  129. Future<Uint8List> getBytes(File file, {int quality = 100}) async {
  130. if (file.localID == null) {
  131. return getFileFromServer(file).then((file) => file.readAsBytesSync());
  132. } else {
  133. return await getBytesFromDisk(file, quality: quality);
  134. }
  135. }
  136. Future<Uint8List> getBytesFromDisk(File file, {int quality = 100}) async {
  137. final originalBytes = (await file.getAsset()).originBytes;
  138. if (extension(file.title) == ".HEIC" || quality != 100) {
  139. return originalBytes.then((bytes) {
  140. return FlutterImageCompress.compressWithList(bytes, quality: quality)
  141. .then((converted) {
  142. return Uint8List.fromList(converted);
  143. });
  144. });
  145. } else {
  146. return originalBytes;
  147. }
  148. }
  149. final Map<int, Future<io.File>> fileDownloadsInProgress =
  150. Map<int, Future<io.File>>();
  151. final Map<int, Future<io.File>> thumbnailDownloadsInProgress =
  152. Map<int, Future<io.File>>();
  153. Future<io.File> getFileFromServer(File file,
  154. {ProgressCallback progressCallback}) async {
  155. final cacheManager = file.fileType == FileType.video
  156. ? VideoCacheManager()
  157. : DefaultCacheManager();
  158. if (!file.isEncrypted) {
  159. return cacheManager.getSingleFile(file.getDownloadUrl());
  160. } else {
  161. return cacheManager.getFileFromCache(file.getDownloadUrl()).then((info) {
  162. if (info == null) {
  163. if (!fileDownloadsInProgress.containsKey(file.uploadedFileID)) {
  164. fileDownloadsInProgress[file.uploadedFileID] = _downloadAndDecrypt(
  165. file,
  166. cacheManager,
  167. progressCallback: progressCallback,
  168. );
  169. }
  170. return fileDownloadsInProgress[file.uploadedFileID];
  171. } else {
  172. return info.file;
  173. }
  174. });
  175. }
  176. }
  177. Future<io.File> getThumbnailFromServer(File file) async {
  178. if (!file.isEncrypted) {
  179. return ThumbnailCacheManager()
  180. .getSingleFile(file.getThumbnailUrl())
  181. .then((data) {
  182. ThumbnailFileLruCache.put(file, data);
  183. return data;
  184. });
  185. } else {
  186. return ThumbnailCacheManager()
  187. .getFileFromCache(file.getThumbnailUrl())
  188. .then((info) {
  189. if (info == null) {
  190. if (!thumbnailDownloadsInProgress.containsKey(file.uploadedFileID)) {
  191. thumbnailDownloadsInProgress[file.uploadedFileID] =
  192. _downloadAndDecryptThumbnail(file).then((data) {
  193. ThumbnailFileLruCache.put(file, data);
  194. return data;
  195. });
  196. }
  197. return thumbnailDownloadsInProgress[file.uploadedFileID];
  198. } else {
  199. ThumbnailFileLruCache.put(file, info.file);
  200. return info.file;
  201. }
  202. });
  203. }
  204. }
  205. Future<io.File> _downloadAndDecrypt(File file, BaseCacheManager cacheManager,
  206. {ProgressCallback progressCallback}) async {
  207. _logger.info("Downloading file " + file.uploadedFileID.toString());
  208. final encryptedFilePath = Configuration.instance.getTempDirectory() +
  209. file.generatedID.toString() +
  210. ".encrypted";
  211. final decryptedFilePath = Configuration.instance.getTempDirectory() +
  212. file.generatedID.toString() +
  213. ".decrypted";
  214. final encryptedFile = io.File(encryptedFilePath);
  215. final decryptedFile = io.File(decryptedFilePath);
  216. final startTime = DateTime.now().millisecondsSinceEpoch;
  217. return Network.instance
  218. .getDio()
  219. .download(
  220. file.getDownloadUrl(),
  221. encryptedFilePath,
  222. options: Options(
  223. headers: {"X-Auth-Token": Configuration.instance.getToken()},
  224. ),
  225. onReceiveProgress: progressCallback,
  226. )
  227. .then((response) async {
  228. if (response.statusCode != 200) {
  229. _logger.warning("Could not download file: ", response.toString());
  230. return null;
  231. } else if (!encryptedFile.existsSync()) {
  232. _logger.warning("File was not downloaded correctly.");
  233. return null;
  234. }
  235. _logger.info("File downloaded: " + file.uploadedFileID.toString());
  236. _logger.info("Download speed: " +
  237. (io.File(encryptedFilePath).lengthSync() /
  238. (DateTime.now().millisecondsSinceEpoch - startTime))
  239. .toString() +
  240. "kBps");
  241. await CryptoUtil.decryptFile(encryptedFilePath, decryptedFilePath,
  242. Sodium.base642bin(file.fileDecryptionHeader), decryptFileKey(file));
  243. _logger.info("File decrypted: " + file.uploadedFileID.toString());
  244. encryptedFile.deleteSync();
  245. var fileExtension = extension(file.title).substring(1).toLowerCase();
  246. var outputFile = decryptedFile;
  247. if (Platform.isAndroid && fileExtension == "heic") {
  248. outputFile = await FlutterImageCompress.compressAndGetFile(
  249. decryptedFilePath,
  250. decryptedFilePath + ".jpg",
  251. keepExif: true,
  252. );
  253. decryptedFile.deleteSync();
  254. }
  255. final cachedFile = await cacheManager.putFile(
  256. file.getDownloadUrl(),
  257. outputFile.readAsBytesSync(),
  258. eTag: file.getDownloadUrl(),
  259. maxAge: Duration(days: 365),
  260. fileExtension: fileExtension,
  261. );
  262. outputFile.deleteSync();
  263. fileDownloadsInProgress.remove(file.uploadedFileID);
  264. return cachedFile;
  265. }).catchError((e) {
  266. fileDownloadsInProgress.remove(file.uploadedFileID);
  267. });
  268. }
  269. Future<io.File> _downloadAndDecryptThumbnail(File file) async {
  270. final temporaryPath = Configuration.instance.getTempDirectory() +
  271. file.generatedID.toString() +
  272. "_thumbnail.decrypted";
  273. return Network.instance
  274. .getDio()
  275. .download(
  276. file.getThumbnailUrl(),
  277. temporaryPath,
  278. options: Options(
  279. headers: {"X-Auth-Token": Configuration.instance.getToken()},
  280. ),
  281. )
  282. .then((_) async {
  283. final encryptedFile = io.File(temporaryPath);
  284. final thumbnailDecryptionKey = decryptFileKey(file);
  285. var data = CryptoUtil.decryptChaCha(
  286. encryptedFile.readAsBytesSync(),
  287. thumbnailDecryptionKey,
  288. Sodium.base642bin(file.thumbnailDecryptionHeader),
  289. );
  290. final thumbnailSize = data.length;
  291. if (thumbnailSize > THUMBNAIL_DATA_LIMIT) {
  292. data = await compressThumbnail(data);
  293. _logger.info("Compressed thumbnail from " +
  294. thumbnailSize.toString() +
  295. " to " +
  296. data.length.toString());
  297. }
  298. encryptedFile.deleteSync();
  299. final cachedThumbnail = ThumbnailCacheManager().putFile(
  300. file.getThumbnailUrl(),
  301. data,
  302. eTag: file.getThumbnailUrl(),
  303. maxAge: Duration(days: 365),
  304. );
  305. thumbnailDownloadsInProgress.remove(file.uploadedFileID);
  306. return cachedThumbnail;
  307. }).catchError((e, s) {
  308. _logger.severe("Error downloading thumbnail ", e, s);
  309. thumbnailDownloadsInProgress.remove(file.uploadedFileID);
  310. });
  311. }
  312. Uint8List decryptFileKey(File file) {
  313. final encryptedKey = Sodium.base642bin(file.encryptedKey);
  314. final nonce = Sodium.base642bin(file.keyDecryptionNonce);
  315. final collectionKey =
  316. CollectionsService.instance.getCollectionKey(file.collectionID);
  317. return CryptoUtil.decryptSync(encryptedKey, collectionKey, nonce);
  318. }
  319. Future<Uint8List> compressThumbnail(Uint8List thumbnail) {
  320. return FlutterImageCompress.compressWithList(
  321. thumbnail,
  322. minHeight: COMPRESSED_THUMBNAIL_RESOLUTION,
  323. minWidth: COMPRESSED_THUMBNAIL_RESOLUTION,
  324. quality: 25,
  325. );
  326. }