file_util.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import 'dart:async';
  2. import 'dart:collection';
  3. import 'dart:io' as io;
  4. import 'dart:io';
  5. import 'dart:typed_data';
  6. import 'package:flutter/widgets.dart';
  7. import 'package:flutter_sodium/flutter_sodium.dart';
  8. import 'package:logging/logging.dart';
  9. import 'package:path/path.dart';
  10. import 'package:dio/dio.dart';
  11. import 'package:flutter_cache_manager/flutter_cache_manager.dart';
  12. import 'package:flutter_image_compress/flutter_image_compress.dart';
  13. import 'package:photo_manager/photo_manager.dart';
  14. import 'package:photos/core/cache/image_cache.dart';
  15. import 'package:photos/core/cache/thumbnail_cache.dart';
  16. import 'package:photos/core/cache/thumbnail_cache_manager.dart';
  17. import 'package:photos/core/cache/video_cache_manager.dart';
  18. import 'package:photos/core/configuration.dart';
  19. import 'package:photos/core/constants.dart';
  20. import 'package:photos/core/event_bus.dart';
  21. import 'package:photos/core/network.dart';
  22. import 'package:photos/db/files_db.dart';
  23. import 'package:photos/events/collection_updated_event.dart';
  24. import 'package:photos/events/local_photos_updated_event.dart';
  25. import 'package:photos/models/file.dart';
  26. import 'package:photos/models/file_type.dart';
  27. import 'package:photos/services/collections_service.dart';
  28. import 'package:photos/services/sync_service.dart';
  29. import 'package:photos/utils/dialog_util.dart';
  30. import 'package:photos/utils/toast_util.dart';
  31. import 'crypto_util.dart';
  32. final _logger = Logger("FileUtil");
  33. Future<void> deleteFilesFromEverywhere(
  34. BuildContext context, List<File> files) async {
  35. final dialog = createProgressDialog(context, "deleting...");
  36. await dialog.show();
  37. final localIDs = List<String>();
  38. for (final file in files) {
  39. if (file.localID != null) {
  40. localIDs.add(file.localID);
  41. }
  42. }
  43. var deletedIDs;
  44. try {
  45. deletedIDs = (await PhotoManager.editor.deleteWithIds(localIDs)).toSet();
  46. } catch (e, s) {
  47. _logger.severe("Could not delete file", e, s);
  48. }
  49. final updatedCollectionIDs = Set<int>();
  50. final List<int> uploadedFileIDsToBeDeleted = [];
  51. final List<File> deletedFiles = [];
  52. for (final file in files) {
  53. if (file.localID != null) {
  54. // Remove only those files that have been removed from disk
  55. if (deletedIDs.contains(file.localID)) {
  56. deletedFiles.add(file);
  57. if (file.uploadedFileID != null) {
  58. uploadedFileIDsToBeDeleted.add(file.uploadedFileID);
  59. updatedCollectionIDs.add(file.collectionID);
  60. } else {
  61. await FilesDB.instance.deleteLocalFile(file.localID);
  62. }
  63. }
  64. } else {
  65. uploadedFileIDsToBeDeleted.add(file.uploadedFileID);
  66. }
  67. }
  68. if (uploadedFileIDsToBeDeleted.isNotEmpty) {
  69. try {
  70. await SyncService.instance
  71. .deleteFilesOnServer(uploadedFileIDsToBeDeleted);
  72. await FilesDB.instance
  73. .deleteMultipleUploadedFiles(uploadedFileIDsToBeDeleted);
  74. } catch (e) {
  75. _logger.severe(e);
  76. await dialog.hide();
  77. showGenericErrorDialog(context);
  78. throw e;
  79. }
  80. for (final collectionID in updatedCollectionIDs) {
  81. Bus.instance.fire(CollectionUpdatedEvent(
  82. collectionID,
  83. deletedFiles
  84. .where((file) => file.collectionID == collectionID)
  85. .toList()));
  86. }
  87. }
  88. if (deletedFiles.isNotEmpty) {
  89. Bus.instance.fire(LocalPhotosUpdatedEvent(deletedFiles));
  90. }
  91. await dialog.hide();
  92. showToast("deleted from everywhere");
  93. if (uploadedFileIDsToBeDeleted.isNotEmpty) {
  94. SyncService.instance.syncWithRemote(silently: true);
  95. }
  96. }
  97. Future<void> deleteFilesOnDeviceOnly(
  98. BuildContext context, List<File> files) async {
  99. final dialog = createProgressDialog(context, "deleting...");
  100. await dialog.show();
  101. final localIDs = List<String>();
  102. for (final file in files) {
  103. if (file.localID != null) {
  104. localIDs.add(file.localID);
  105. }
  106. }
  107. final deletedIDs =
  108. (await PhotoManager.editor.deleteWithIds(localIDs)).toSet();
  109. final List<File> deletedFiles = [];
  110. for (final file in files) {
  111. // Remove only those files that have been removed from disk
  112. if (deletedIDs.contains(file.localID)) {
  113. deletedFiles.add(file);
  114. file.localID = null;
  115. FilesDB.instance.update(file);
  116. }
  117. }
  118. if (deletedFiles.isNotEmpty) {
  119. Bus.instance.fire(LocalPhotosUpdatedEvent(deletedFiles));
  120. }
  121. await dialog.hide();
  122. }
  123. void preloadFile(File file) {
  124. if (file.fileType == FileType.video) {
  125. return;
  126. }
  127. if (file.localID == null) {
  128. getFileFromServer(file);
  129. } else {
  130. if (FileLruCache.get(file) == null) {
  131. file.getAsset().then((asset) {
  132. asset.file.then((assetFile) {
  133. FileLruCache.put(file, assetFile);
  134. });
  135. });
  136. }
  137. }
  138. }
  139. void preloadThumbnail(File file) {
  140. if (file.localID == null) {
  141. getThumbnailFromServer(file);
  142. } else {
  143. if (ThumbnailLruCache.get(file, THUMBNAIL_SMALL_SIZE) != null) {
  144. return;
  145. }
  146. file.getAsset().then((asset) {
  147. asset
  148. .thumbDataWithSize(
  149. THUMBNAIL_SMALL_SIZE,
  150. THUMBNAIL_SMALL_SIZE,
  151. quality: THUMBNAIL_QUALITY,
  152. )
  153. .then((data) {
  154. ThumbnailLruCache.put(file, THUMBNAIL_SMALL_SIZE, data);
  155. });
  156. });
  157. }
  158. }
  159. Future<io.File> getNativeFile(File file) async {
  160. if (file.localID == null) {
  161. return getFileFromServer(file);
  162. } else {
  163. return file.getAsset().then((asset) => asset.originFile);
  164. }
  165. }
  166. Future<Uint8List> getBytes(File file, {int quality = 100}) async {
  167. if (file.localID == null) {
  168. return getFileFromServer(file).then((file) => file.readAsBytesSync());
  169. } else {
  170. return await getBytesFromDisk(file, quality: quality);
  171. }
  172. }
  173. Future<Uint8List> getBytesFromDisk(File file, {int quality = 100}) async {
  174. final originalBytes = (await file.getAsset()).originBytes;
  175. if (extension(file.title) == ".HEIC" || quality != 100) {
  176. return originalBytes.then((bytes) {
  177. return FlutterImageCompress.compressWithList(bytes, quality: quality)
  178. .then((converted) {
  179. return Uint8List.fromList(converted);
  180. });
  181. });
  182. } else {
  183. return originalBytes;
  184. }
  185. }
  186. final Map<int, Future<io.File>> fileDownloadsInProgress =
  187. Map<int, Future<io.File>>();
  188. final _thumbnailQueue = LinkedHashMap<int, FileDownloadItem>();
  189. int _currentlyDownloading = 0;
  190. const int kMaximumConcurrentDownloads = 500;
  191. class FileDownloadItem {
  192. final File file;
  193. final Completer<io.File> completer;
  194. DownloadStatus status;
  195. FileDownloadItem(
  196. this.file,
  197. this.completer, {
  198. this.status = DownloadStatus.not_started,
  199. });
  200. }
  201. enum DownloadStatus {
  202. not_started,
  203. in_progress,
  204. }
  205. Future<io.File> getFileFromServer(File file,
  206. {ProgressCallback progressCallback}) async {
  207. final cacheManager = file.fileType == FileType.video
  208. ? VideoCacheManager()
  209. : DefaultCacheManager();
  210. return cacheManager.getFileFromCache(file.getDownloadUrl()).then((info) {
  211. if (info == null) {
  212. if (!fileDownloadsInProgress.containsKey(file.uploadedFileID)) {
  213. fileDownloadsInProgress[file.uploadedFileID] = _downloadAndDecrypt(
  214. file,
  215. cacheManager,
  216. progressCallback: progressCallback,
  217. );
  218. }
  219. return fileDownloadsInProgress[file.uploadedFileID];
  220. } else {
  221. return info.file;
  222. }
  223. });
  224. }
  225. Future<io.File> getThumbnailFromServer(File file) async {
  226. return ThumbnailCacheManager()
  227. .getFileFromCache(file.getThumbnailUrl())
  228. .then((info) {
  229. if (info == null) {
  230. if (!_thumbnailQueue.containsKey(file.uploadedFileID)) {
  231. final completer = Completer<io.File>();
  232. _thumbnailQueue[file.uploadedFileID] =
  233. FileDownloadItem(file, completer);
  234. _pollQueue();
  235. return completer.future;
  236. } else {
  237. return _thumbnailQueue[file.uploadedFileID].completer.future;
  238. }
  239. } else {
  240. ThumbnailFileLruCache.put(file, info.file);
  241. return info.file;
  242. }
  243. });
  244. }
  245. void removePendingGetThumbnailRequestIfAny(File file) {
  246. if (_thumbnailQueue[file.uploadedFileID] != null &&
  247. _thumbnailQueue[file.uploadedFileID].status ==
  248. DownloadStatus.not_started) {
  249. _thumbnailQueue.remove(file.uploadedFileID);
  250. }
  251. }
  252. void _pollQueue() async {
  253. if (_thumbnailQueue.length > 0 &&
  254. _currentlyDownloading < kMaximumConcurrentDownloads) {
  255. final firstPendingEntry = _thumbnailQueue.entries.firstWhere(
  256. (entry) => entry.value.status == DownloadStatus.not_started,
  257. orElse: () => null);
  258. if (firstPendingEntry != null) {
  259. final item = firstPendingEntry.value;
  260. _currentlyDownloading++;
  261. item.status = DownloadStatus.in_progress;
  262. try {
  263. final data = await _downloadAndDecryptThumbnail(item.file);
  264. ThumbnailFileLruCache.put(item.file, data);
  265. item.completer.complete(data);
  266. } catch (e, s) {
  267. _logger.severe(
  268. "Failed to download thumbnail " + item.file.toString(), e, s);
  269. item.completer.completeError(e);
  270. }
  271. _currentlyDownloading--;
  272. _thumbnailQueue.remove(firstPendingEntry.key);
  273. _pollQueue();
  274. }
  275. }
  276. }
  277. Future<io.File> _downloadAndDecrypt(File file, BaseCacheManager cacheManager,
  278. {ProgressCallback progressCallback}) async {
  279. _logger.info("Downloading file " + file.uploadedFileID.toString());
  280. final encryptedFilePath = Configuration.instance.getTempDirectory() +
  281. file.generatedID.toString() +
  282. ".encrypted";
  283. final decryptedFilePath = Configuration.instance.getTempDirectory() +
  284. file.generatedID.toString() +
  285. ".decrypted";
  286. final encryptedFile = io.File(encryptedFilePath);
  287. final decryptedFile = io.File(decryptedFilePath);
  288. final startTime = DateTime.now().millisecondsSinceEpoch;
  289. return Network.instance
  290. .getDio()
  291. .download(
  292. file.getDownloadUrl(),
  293. encryptedFilePath,
  294. options: Options(
  295. headers: {"X-Auth-Token": Configuration.instance.getToken()},
  296. ),
  297. onReceiveProgress: progressCallback,
  298. )
  299. .then((response) async {
  300. if (response.statusCode != 200) {
  301. _logger.warning("Could not download file: ", response.toString());
  302. return null;
  303. } else if (!encryptedFile.existsSync()) {
  304. _logger.warning("File was not downloaded correctly.");
  305. return null;
  306. }
  307. _logger.info("File downloaded: " + file.uploadedFileID.toString());
  308. _logger.info("Download speed: " +
  309. (io.File(encryptedFilePath).lengthSync() /
  310. (DateTime.now().millisecondsSinceEpoch - startTime))
  311. .toString() +
  312. "kBps");
  313. await CryptoUtil.decryptFile(encryptedFilePath, decryptedFilePath,
  314. Sodium.base642bin(file.fileDecryptionHeader), decryptFileKey(file));
  315. _logger.info("File decrypted: " + file.uploadedFileID.toString());
  316. encryptedFile.deleteSync();
  317. var fileExtension = extension(file.title).substring(1).toLowerCase();
  318. var outputFile = decryptedFile;
  319. if (Platform.isAndroid && fileExtension == "heic") {
  320. outputFile = await FlutterImageCompress.compressAndGetFile(
  321. decryptedFilePath,
  322. decryptedFilePath + ".jpg",
  323. keepExif: true,
  324. );
  325. decryptedFile.deleteSync();
  326. }
  327. final cachedFile = await cacheManager.putFile(
  328. file.getDownloadUrl(),
  329. outputFile.readAsBytesSync(),
  330. eTag: file.getDownloadUrl(),
  331. maxAge: Duration(days: 365),
  332. fileExtension: fileExtension,
  333. );
  334. outputFile.deleteSync();
  335. fileDownloadsInProgress.remove(file.uploadedFileID);
  336. return cachedFile;
  337. }).catchError((e) {
  338. fileDownloadsInProgress.remove(file.uploadedFileID);
  339. });
  340. }
  341. Future<io.File> _downloadAndDecryptThumbnail(File file) async {
  342. final temporaryPath = Configuration.instance.getTempDirectory() +
  343. file.generatedID.toString() +
  344. "_thumbnail.decrypted";
  345. await Network.instance.getDio().download(
  346. file.getThumbnailUrl(),
  347. temporaryPath,
  348. options: Options(
  349. headers: {"X-Auth-Token": Configuration.instance.getToken()},
  350. ),
  351. );
  352. final encryptedFile = io.File(temporaryPath);
  353. final thumbnailDecryptionKey = decryptFileKey(file);
  354. var data = CryptoUtil.decryptChaCha(
  355. encryptedFile.readAsBytesSync(),
  356. thumbnailDecryptionKey,
  357. Sodium.base642bin(file.thumbnailDecryptionHeader),
  358. );
  359. final thumbnailSize = data.length;
  360. if (thumbnailSize > THUMBNAIL_DATA_LIMIT) {
  361. data = await compressThumbnail(data);
  362. _logger.info("Compressed thumbnail from " +
  363. thumbnailSize.toString() +
  364. " to " +
  365. data.length.toString());
  366. }
  367. encryptedFile.deleteSync();
  368. final cachedThumbnail = ThumbnailCacheManager().putFile(
  369. file.getThumbnailUrl(),
  370. data,
  371. eTag: file.getThumbnailUrl(),
  372. maxAge: Duration(days: 365),
  373. );
  374. return cachedThumbnail;
  375. }
  376. Uint8List decryptFileKey(File file) {
  377. final encryptedKey = Sodium.base642bin(file.encryptedKey);
  378. final nonce = Sodium.base642bin(file.keyDecryptionNonce);
  379. final collectionKey =
  380. CollectionsService.instance.getCollectionKey(file.collectionID);
  381. return CryptoUtil.decryptSync(encryptedKey, collectionKey, nonce);
  382. }
  383. Future<Uint8List> compressThumbnail(Uint8List thumbnail) {
  384. return FlutterImageCompress.compressWithList(
  385. thumbnail,
  386. minHeight: COMPRESSED_THUMBNAIL_RESOLUTION,
  387. minWidth: COMPRESSED_THUMBNAIL_RESOLUTION,
  388. quality: 25,
  389. );
  390. }
  391. void clearCache(File file) {
  392. if (file.fileType == FileType.video) {
  393. VideoCacheManager().removeFile(file.getDownloadUrl());
  394. } else {
  395. DefaultCacheManager().removeFile(file.getDownloadUrl());
  396. }
  397. ThumbnailCacheManager().removeFile(file.getThumbnailUrl());
  398. }