Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

locker: cache encrypted downloads and clear cache on logout

Neeraj Gupta379a7c7dde9a
diff --git a/mobile/apps/locker/lib/services/configuration.dart b/mobile/apps/locker/lib/services/configuration.dart
index 6f21f99385..2ecca1c5ea 100644
--- a/mobile/apps/locker/lib/services/configuration.dart
+++ b/mobile/apps/locker/lib/services/configuration.dart
@@ -1,10 +1,14 @@
+import 'dart:io';
+
import 'package:ente_configuration/base_configuration.dart';
import 'package:locker/services/collections/collections_service.dart';
import 'package:locker/services/favorites_service.dart';
+import 'package:logging/logging.dart';
class Configuration extends BaseConfiguration {
Configuration._privateConstructor();
static final Configuration instance = Configuration._privateConstructor();
+ static final _logger = Logger("Configuration");
@override
// Provide all secure storage keys that should be wiped on logout.
@@ -20,5 +24,18 @@ class Configuration extends BaseConfiguration {
FavoritesService.instance.clearCache();
await super.logout(autoLogout: autoLogout);
+ await _clearCachedFiles();
+ }
+
+ Future<void> _clearCachedFiles() async {
+ try {
+ final cacheDir = Directory(getCacheDirectory());
+ if (!await cacheDir.exists()) return;
+ await for (final entity in cacheDir.list(followLinks: false)) {
+ await entity.delete(recursive: true);
+ }
+ } catch (e, s) {
+ _logger.warning("Failed to clear cached files on logout", e, s);
+ }
}
}
diff --git a/mobile/apps/locker/lib/services/files/download/file_downloader.dart b/mobile/apps/locker/lib/services/files/download/file_downloader.dart
index 1b88f766ea..5382301151 100644
--- a/mobile/apps/locker/lib/services/files/download/file_downloader.dart
+++ b/mobile/apps/locker/lib/services/files/download/file_downloader.dart
@@ -10,6 +10,7 @@ import 'package:locker/services/files/download/models/task.dart';
import 'package:locker/services/files/download/service_locator.dart';
import 'package:locker/services/files/sync/models/file.dart';
import 'package:logging/logging.dart';
+import 'package:path/path.dart' as p;
final _logger = Logger("FileDownloader");
@@ -26,46 +27,76 @@ Future<File?> downloadAndDecrypt(
final String tempDir = Configuration.instance.getTempDirectory();
final String cacheDir = Configuration.instance.getCacheDirectory();
- String encryptedFilePath = "$tempDir${file.uploadedFileID}.encrypted";
+ final String cachedEncryptedFilePath =
+ "$cacheDir${file.uploadedFileID}.encrypted";
+ final String tempEncryptedFilePath =
+ "$tempDir${file.uploadedFileID}.encrypted";
+ String encryptedFilePath = tempEncryptedFilePath;
File encryptedFile = File(encryptedFilePath);
+ bool usingCachedEncryptedFile = false;
+ bool downloadedFreshEncryptedFile = false;
- final String decryptedFilePath = shouldUseCache
- ? "$cacheDir${file.displayName}"
- : "$tempDir${file.displayName}";
+ final String safeDisplayName = p.basename(file.displayName);
+ final String decryptedFilePath =
+ "$tempDir${file.uploadedFileID}_$safeDisplayName";
+ final File decryptedFile = File(decryptedFilePath);
final startTime = DateTime.now().millisecondsSinceEpoch;
try {
- if (downloadManager.enableResumableDownload(file.fileSize)) {
- final DownloadResult result = await downloadManager.download(
- file.uploadedFileID!,
- file.displayName,
- file.fileSize!,
- );
- if (result.success) {
- encryptedFilePath = result.task.filePath!;
- encryptedFile = File(encryptedFilePath);
+ bool shouldDownload = true;
+ if (shouldUseCache) {
+ final cachedEncryptedFile = File(cachedEncryptedFilePath);
+ if (await cachedEncryptedFile.exists()) {
+ final encryptedSize = await cachedEncryptedFile.length();
+ if (encryptedSize > 0) {
+ shouldDownload = false;
+ usingCachedEncryptedFile = true;
+ encryptedFilePath = cachedEncryptedFilePath;
+ encryptedFile = cachedEncryptedFile;
+ _logger.info('$logPrefix using cached encrypted file');
+ } else {
+ await cachedEncryptedFile.delete();
+ }
+ }
+ }
+
+ if (shouldDownload) {
+ if (downloadManager.enableResumableDownload(file.fileSize)) {
+ final DownloadResult result = await downloadManager.download(
+ file.uploadedFileID!,
+ file.displayName,
+ file.fileSize!,
+ );
+ if (result.success) {
+ encryptedFilePath = result.task.filePath!;
+ encryptedFile = File(encryptedFilePath);
+ downloadedFreshEncryptedFile = true;
+ } else {
+ _logger.warning(
+ '$logPrefix download failed ${result.task.error} ${result.task.status}',
+ );
+ return null;
+ }
} else {
- _logger.warning(
- '$logPrefix download failed ${result.task.error} ${result.task.status}',
+ // If the file is small, download it directly to the final location
+ final response = await Network.instance.getDio().download(
+ file.downloadUrl,
+ tempEncryptedFilePath,
+ options: Options(
+ headers: {"X-Auth-Token": Configuration.instance.getToken()},
+ ),
+ onReceiveProgress: (a, b) {
+ progressCallback?.call(a, b);
+ },
);
- return null;
- }
- } else {
- // If the file is small, download it directly to the final location
- final response = await Network.instance.getDio().download(
- file.downloadUrl,
- encryptedFilePath,
- options: Options(
- headers: {"X-Auth-Token": Configuration.instance.getToken()},
- ),
- onReceiveProgress: (a, b) {
- progressCallback?.call(a, b);
- },
- );
- if (response.statusCode != 200 || !encryptedFile.existsSync()) {
- _logger.warning('$logPrefix download failed ${response.toString()}');
- return null;
+ encryptedFilePath = tempEncryptedFilePath;
+ encryptedFile = File(encryptedFilePath);
+ downloadedFreshEncryptedFile = true;
+ if (response.statusCode != 200 || !encryptedFile.existsSync()) {
+ _logger.warning('$logPrefix download failed ${response.toString()}');
+ return null;
+ }
}
}
@@ -91,6 +122,9 @@ Future<File?> downloadAndDecrypt(
try {
// Start the periodic callback after initial 5 seconds
fakeProgress?.start();
+ if (await decryptedFile.exists()) {
+ await decryptedFile.delete();
+ }
await CryptoUtil.decryptFile(
encryptedFilePath,
decryptedFilePath,
@@ -103,10 +137,36 @@ Future<File?> downloadAndDecrypt(
} catch (e, s) {
fakeProgress?.stop();
_logger.severe("Critical: $logPrefix failed to decrypt", e, s);
+ if (downloadedFreshEncryptedFile) {
+ try {
+ await encryptedFile.delete();
+ } catch (_) {}
+ } else if (usingCachedEncryptedFile) {
+ // Cached encrypted file is likely corrupted; remove it so next attempt
+ // fetches a fresh copy.
+ try {
+ await encryptedFile.delete();
+ } catch (_) {}
+ }
return null;
}
- await encryptedFile.delete();
- return File(decryptedFilePath);
+ if (shouldUseCache && downloadedFreshEncryptedFile) {
+ try {
+ if (encryptedFilePath != cachedEncryptedFilePath) {
+ await encryptedFile.copy(cachedEncryptedFilePath);
+ await encryptedFile.delete();
+ }
+ } catch (e, s) {
+ _logger.warning(
+ '$logPrefix failed to persist encrypted file cache',
+ e,
+ s,
+ );
+ }
+ } else if (!shouldUseCache) {
+ await encryptedFile.delete();
+ }
+ return decryptedFile;
} catch (e, s) {
_logger.severe("$logPrefix failed to download or decrypt", e, s);
return null;
diff --git a/mobile/apps/locker/lib/services/files/download/manager.dart b/mobile/apps/locker/lib/services/files/download/manager.dart
index 2685f2e053..51dcea5ea4 100644
--- a/mobile/apps/locker/lib/services/files/download/manager.dart
+++ b/mobile/apps/locker/lib/services/files/download/manager.dart
@@ -52,7 +52,7 @@ class DownloadManager {
// Get or create task
final existingTask = _tasks[fileId];
- final task = existingTask ??
+ var task = existingTask ??
DownloadTask(
id: fileId,
filename: filename,
@@ -67,19 +67,17 @@ class DownloadManager {
// ensure that the file exists
final filePath = task.filePath;
if (filePath == null || !(await File(filePath).exists())) {
- // If the file doesn't exist, mark the task as error
_logger.warning(
- 'File not found for ${task.filename} (${task.bytesDownloaded}/${task.totalBytes} bytes)',
+ 'Completed file missing for ${task.filename}; restarting download '
+ '(${task.bytesDownloaded}/${task.totalBytes} bytes)',
);
- final updatedTask = task.copyWith(
- status: DownloadStatus.error,
- error: 'File not found',
+ task = task.copyWith(
+ status: DownloadStatus.pending,
+ bytesDownloaded: 0,
+ error: null,
filePath: null,
);
- _updateTask(updatedTask);
- final result = DownloadResult(updatedTask, false);
- completer.complete(result);
- return result;
+ _updateTask(task);
} else {
_logger.info(
'Download already completed for ${task.filename} (${task.bytesDownloaded}/${task.totalBytes} bytes)',
diff --git a/mobile/apps/locker/lib/utils/file_util.dart b/mobile/apps/locker/lib/utils/file_util.dart
index 5b985c99a0..58c0679e3a 100644
--- a/mobile/apps/locker/lib/utils/file_util.dart
+++ b/mobile/apps/locker/lib/utils/file_util.dart
@@ -9,7 +9,6 @@ import "package:flutter/material.dart";
import "package:locker/l10n/l10n.dart";
import "package:locker/models/info/info_item.dart";
import "package:locker/services/collections/collections_service.dart";
-import "package:locker/services/configuration.dart";
import "package:locker/services/files/download/file_downloader.dart";
import "package:locker/services/files/sync/models/file.dart";
import "package:locker/services/info_file_service.dart";
@@ -38,14 +37,6 @@ class FileUtil {
}
}
- final String cachedFilePath =
- "${Configuration.instance.getCacheDirectory()}${file.displayName}";
- final File cachedFile = File(cachedFilePath);
- if (await cachedFile.exists()) {
- await _launchFile(context, cachedFile, file.displayName);
- return;
- }
-
final dialog = createProgressDialog(
context,
context.l10n.downloading,