file_util.dart 13 KB

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