π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
feat: Implement offline file access
AmanRajSinghMourya422bd9ad89f1
diff --git a/mobile/apps/locker/lib/l10n/app_en.arb b/mobile/apps/locker/lib/l10n/app_en.arbindex 9f16b5c914..688ad7d371 100644--- a/mobile/apps/locker/lib/l10n/app_en.arb+++ b/mobile/apps/locker/lib/l10n/app_en.arb@@ -29,6 +29,83 @@}}},+ "saveOffline": "Save offline",+ "removeFromOffline": "Remove offline",+ "savingOffline": "Saving offline...",+ "savingOfflineProgress": "Saving offline... {percentage}%",+ "@savingOfflineProgress": {+ "description": "Offline save progress message",+ "placeholders": {+ "percentage": {+ "type": "int",+ "example": "75"+ }+ }+ },+ "filesAvailableOffline": "{count, plural, =1{1 file saved offline} other{{count} files saved offline}}",+ "@filesAvailableOffline": {+ "description": "Success message when files are saved offline",+ "placeholders": {+ "count": {+ "type": "int",+ "example": "3"+ }+ }+ },+ "filesAvailableOfflinePartial": "{successCount} files saved offline, {failureCount} failed",+ "@filesAvailableOfflinePartial": {+ "description": "Partial success message for offline save",+ "placeholders": {+ "successCount": {+ "type": "int",+ "example": "2"+ },+ "failureCount": {+ "type": "int",+ "example": "1"+ }+ }+ },+ "failedToSaveFilesOffline": "{count, plural, =1{Failed to save 1 file offline} other{Failed to save {count} files offline}}",+ "@failedToSaveFilesOffline": {+ "description": "Failure message when files could not be saved offline",+ "placeholders": {+ "count": {+ "type": "int",+ "example": "2"+ }+ }+ },+ "failedToSaveFilesOfflineNetwork": "{count, plural, =1{No internet connection. Failed to save 1 file offline} other{No internet connection. Failed to save {count} files offline}}",+ "@failedToSaveFilesOfflineNetwork": {+ "description": "Failure message when files could not be saved offline because the device was offline",+ "placeholders": {+ "count": {+ "type": "int",+ "example": "2"+ }+ }+ },+ "failedToSaveFilesOfflineStorage": "{count, plural, =1{Failed to save 1 file offline. Check device storage} other{Failed to save {count} files offline. Check device storage}}",+ "@failedToSaveFilesOfflineStorage": {+ "description": "Failure message when files could not be saved offline because local storage failed",+ "placeholders": {+ "count": {+ "type": "int",+ "example": "2"+ }+ }+ },+ "filesRemovedFromOffline": "{count, plural, =1{Offline removed for 1 file} other{Offline removed for {count} files}}",+ "@filesRemovedFromOffline": {+ "description": "Success message when offline copies are removed",+ "placeholders": {+ "count": {+ "type": "int",+ "example": "2"+ }+ }+ },"downloadFailed": "Download failed","failedToDownloadOrDecrypt": "Failed to download item","errorOpeningFile": "Error opening item",diff --git a/mobile/apps/locker/lib/l10n/app_localizations.dart b/mobile/apps/locker/lib/l10n/app_localizations.dartindex 5b3764548c..5a196aa907 100644--- a/mobile/apps/locker/lib/l10n/app_localizations.dart+++ b/mobile/apps/locker/lib/l10n/app_localizations.dart@@ -270,6 +270,66 @@ abstract class AppLocalizations {/// **'Downloading... {percentage}%'**String downloadingProgress(int percentage);+ /// No description provided for @saveOffline.+ ///+ /// In en, this message translates to:+ /// **'Save offline'**+ String get saveOffline;++ /// No description provided for @removeFromOffline.+ ///+ /// In en, this message translates to:+ /// **'Remove offline'**+ String get removeFromOffline;++ /// No description provided for @savingOffline.+ ///+ /// In en, this message translates to:+ /// **'Saving offline...'**+ String get savingOffline;++ /// Offline save progress message+ ///+ /// In en, this message translates to:+ /// **'Saving offline... {percentage}%'**+ String savingOfflineProgress(int percentage);++ /// Success message when files are saved offline+ ///+ /// In en, this message translates to:+ /// **'{count, plural, =1{1 file saved offline} other{{count} files saved offline}}'**+ String filesAvailableOffline(int count);++ /// Partial success message for offline save+ ///+ /// In en, this message translates to:+ /// **'{successCount} files saved offline, {failureCount} failed'**+ String filesAvailableOfflinePartial(int successCount, int failureCount);++ /// Failure message when files could not be saved offline+ ///+ /// In en, this message translates to:+ /// **'{count, plural, =1{Failed to save 1 file offline} other{Failed to save {count} files offline}}'**+ String failedToSaveFilesOffline(int count);++ /// Failure message when files could not be saved offline because the device was offline+ ///+ /// In en, this message translates to:+ /// **'{count, plural, =1{No internet connection. Failed to save 1 file offline} other{No internet connection. Failed to save {count} files offline}}'**+ String failedToSaveFilesOfflineNetwork(int count);++ /// Failure message when files could not be saved offline because local storage failed+ ///+ /// In en, this message translates to:+ /// **'{count, plural, =1{Failed to save 1 file offline. Check device storage} other{Failed to save {count} files offline. Check device storage}}'**+ String failedToSaveFilesOfflineStorage(int count);++ /// Success message when offline copies are removed+ ///+ /// In en, this message translates to:+ /// **'{count, plural, =1{Offline removed for 1 file} other{Offline removed for {count} files}}'**+ String filesRemovedFromOffline(int count);+/// No description provided for @downloadFailed.////// In en, this message translates to:diff --git a/mobile/apps/locker/lib/l10n/app_localizations_en.dart b/mobile/apps/locker/lib/l10n/app_localizations_en.dartindex 839b1da596..7a9e18a5c1 100644--- a/mobile/apps/locker/lib/l10n/app_localizations_en.dart+++ b/mobile/apps/locker/lib/l10n/app_localizations_en.dart@@ -75,6 +75,80 @@ class AppLocalizationsEn extends AppLocalizations {return 'Downloading... $percentage%';}+ @override+ String get saveOffline => 'Save offline';++ @override+ String get removeFromOffline => 'Remove offline';++ @override+ String get savingOffline => 'Saving offline...';++ @override+ String savingOfflineProgress(int percentage) {+ return 'Saving offline... $percentage%';+ }++ @override+ String filesAvailableOffline(int count) {+ String _temp0 = intl.Intl.pluralLogic(+ count,+ locale: localeName,+ other: '$count files saved offline',+ one: '1 file saved offline',+ );+ return '$_temp0';+ }++ @override+ String filesAvailableOfflinePartial(int successCount, int failureCount) {+ return '$successCount files saved offline, $failureCount failed';+ }++ @override+ String failedToSaveFilesOffline(int count) {+ String _temp0 = intl.Intl.pluralLogic(+ count,+ locale: localeName,+ other: 'Failed to save $count files offline',+ one: 'Failed to save 1 file offline',+ );+ return '$_temp0';+ }++ @override+ String failedToSaveFilesOfflineNetwork(int count) {+ String _temp0 = intl.Intl.pluralLogic(+ count,+ locale: localeName,+ other: 'No internet connection. Failed to save $count files offline',+ one: 'No internet connection. Failed to save 1 file offline',+ );+ return '$_temp0';+ }++ @override+ String failedToSaveFilesOfflineStorage(int count) {+ String _temp0 = intl.Intl.pluralLogic(+ count,+ locale: localeName,+ other: 'Failed to save $count files offline. Check device storage',+ one: 'Failed to save 1 file offline. Check device storage',+ );+ return '$_temp0';+ }++ @override+ String filesRemovedFromOffline(int count) {+ String _temp0 = intl.Intl.pluralLogic(+ count,+ locale: localeName,+ other: 'Offline removed for $count files',+ one: 'Offline removed for 1 file',+ );+ return '$_temp0';+ }+@overrideString get downloadFailed => 'Download failed';diff --git a/mobile/apps/locker/lib/main.dart b/mobile/apps/locker/lib/main.dartindex dadfc03abc..b89596572e 100644--- a/mobile/apps/locker/lib/main.dart+++ b/mobile/apps/locker/lib/main.dart@@ -25,13 +25,14 @@ import 'package:locker/l10n/app_localizations.dart';import 'package:locker/services/collections/collections_api_client.dart';import 'package:locker/services/collections/collections_service.dart';import 'package:locker/services/configuration.dart';-import "package:locker/services/db/locker_db.dart";+import 'package:locker/services/db/locker_db.dart';import 'package:locker/services/favorites_service.dart';import 'package:locker/services/files/download/service_locator.dart';-import "package:locker/services/files/links/links_client.dart";-import "package:locker/services/files/links/links_service.dart";+import 'package:locker/services/files/links/links_client.dart';+import 'package:locker/services/files/links/links_service.dart';+import 'package:locker/services/files/offline/offline_files_service.dart';import 'package:locker/services/trash/trash_service.dart';-import "package:locker/services/update_service.dart";+import 'package:locker/services/update_service.dart';import 'package:locker/ui/pages/home_page.dart';import 'package:package_info_plus/package_info_plus.dart';import 'package:path_provider/path_provider.dart';@@ -179,6 +180,7 @@ Future<void> _init(bool bool, {String? via}) async {await CollectionApiClient.instance.init();await CollectionService.instance.init(preferences);await FavoritesService.instance.init();+ await OfflineFilesService.instance.init();await LinksClient.instance.init();await LinksService.instance.init();await ServiceLocator.instance.init(diff --git a/mobile/apps/locker/lib/services/collections/collections_service.dart b/mobile/apps/locker/lib/services/collections/collections_service.dartindex 23894237a7..f6a7428aea 100644--- a/mobile/apps/locker/lib/services/collections/collections_service.dart+++ b/mobile/apps/locker/lib/services/collections/collections_service.dart@@ -21,6 +21,7 @@ import "package:locker/services/collections/models/files_split.dart";import "package:locker/services/collections/models/public_url.dart";import 'package:locker/services/configuration.dart';import "package:locker/services/db/locker_db.dart";+import 'package:locker/services/files/offline/offline_files_service.dart';import 'package:locker/services/files/sync/models/file.dart';import 'package:locker/services/trash/models/trash_item_request.dart';import "package:locker/services/trash/trash_service.dart";@@ -347,6 +348,10 @@ class CollectionService {requests.add(TrashRequest(file.uploadedFileID!, collection.id));await _apiClient.trash(requests);+ await OfflineFilesService.instance.unmarkFilesOfflineLocally(+ [file],+ removeWorkingCopies: false,+ );await _db.deleteFilesFromCollection(collection, [file]);if (runSync) {@@ -436,11 +441,6 @@ class CollectionService {try {await _apiClient.removeFromCollection(collectionId, files);- final collection = await getCollectionByID(collectionId);- if (collection != null) {- await _db.deleteFilesFromCollection(collection, files);- }-Bus.instance.fire(CollectionsUpdatedEvent('files_removed'));await sync();@@ -469,17 +469,15 @@ class CollectionService {// Call API to move files on serverawait _apiClient.move(files, from, to);- // Update local database for all files- // Remove from source collection- await _db.deleteFilesFromCollection(from, files);-// Update collectionID for all filesfor (final file in files) {file.collectionID = to.id;}- // Add to target collection+ // Write the destination row first so local key material and offline state+ // stay attached to the moved file before the source mapping is removed.await _db.addFilesToCollection(to, files);+ await _db.deleteFilesFromCollection(from, files);// Let sync update the local state to ensure consistencyif (runSync) {diff --git a/mobile/apps/locker/lib/services/configuration.dart b/mobile/apps/locker/lib/services/configuration.dartindex 2ecca1c5ea..1747a8fcc2 100644--- a/mobile/apps/locker/lib/services/configuration.dart+++ b/mobile/apps/locker/lib/services/configuration.dart@@ -3,6 +3,7 @@ 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:locker/services/files/offline/offline_file_storage.dart';import 'package:logging/logging.dart';class Configuration extends BaseConfiguration {@@ -25,6 +26,7 @@ class Configuration extends BaseConfiguration {await super.logout(autoLogout: autoLogout);await _clearCachedFiles();+ await clearAllOfflineFileCopies();}Future<void> _clearCachedFiles() async {diff --git a/mobile/apps/locker/lib/services/db/locker_db.dart b/mobile/apps/locker/lib/services/db/locker_db.dartindex 89c230a249..f4c7dd0487 100644--- a/mobile/apps/locker/lib/services/db/locker_db.dart+++ b/mobile/apps/locker/lib/services/db/locker_db.dart@@ -22,20 +22,27 @@ class LockerDB extends EnteBaseDatabase {Database? _database;int _collectionSyncTime = 0;final Map<int, int> _collectionSyncTimesCache = {};+ final Set<int> _offlineMarkedFileIDsCache = {};static const String databaseName = 'locker.db';static const String _collectionsTable = 'collections';static const String _filesTable = 'files';static const String trashTable = 'trash_files';static const String _collectionFilesTable = 'collection_files';+ static const String _offlineFilesTable = 'offline_marks';static const String _syncTimesTable = 'sync_times';static const int _collectionPayloadVersion = 1;static const int _filePayloadVersion = 1;static const int _trashPayloadVersion = 1;+ static const int _databaseVersion = 2;++ static final List<Future<void> Function(DatabaseExecutor)> _migrationScripts =+ [+ _createOfflineFilesTable,+ ];Future<void> init() async {_database = await _initDatabase();- await _createTables(_db, 1);await _loadCaches();}@@ -57,6 +64,19 @@ class LockerDB extends EnteBaseDatabase {final globalSyncTime = await getSyncTimeAsync();_collectionSyncTime = globalSyncTime;+ await _populateOfflineMarkedFileIDsCache();+ }++ Future<void> _populateOfflineMarkedFileIDsCache() async {+ final offlineMarkedRows = await _db.query(+ _offlineFilesTable,+ columns: ['uploaded_file_id'],+ );+ _offlineMarkedFileIDsCache+ ..clear()+ ..addAll(+ offlineMarkedRows.map((row) => row['uploaded_file_id'] as int),+ );}Future<Database> _initDatabase() async {@@ -69,12 +89,25 @@ class LockerDB extends EnteBaseDatabase {return await openDatabase(path,- version: 1,- onCreate: _createTables,+ version: _databaseVersion,+ onCreate: (db, _) => _createTables(db),+ onUpgrade: _onUpgrade,);}- Future<void> _createTables(Database db, int version) async {+ Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {+ if (oldVersion >= newVersion) {+ return;+ }++ await db.transaction((txn) async {+ for (var index = oldVersion - 1; index < newVersion - 1; index++) {+ await _migrationScripts[index](txn);+ }+ });+ }++ Future<void> _createTables(Database db) async {await db.execute('''CREATE TABLE IF NOT EXISTS $_collectionsTable (id INTEGER PRIMARY KEY,@@ -92,6 +125,7 @@ class LockerDB extends EnteBaseDatabase {await _createFilesTable(db);await _createTrashTable(db);+ await _createOfflineFilesTable(db);await db.execute('''CREATE TABLE IF NOT EXISTS $_collectionFilesTable (@@ -145,6 +179,14 @@ class LockerDB extends EnteBaseDatabase {''');}+ static Future<void> _createOfflineFilesTable(DatabaseExecutor db) async {+ await db.execute('''+ CREATE TABLE IF NOT EXISTS $_offlineFilesTable (+ uploaded_file_id INTEGER PRIMARY KEY+ )+ ''');+ }+Future<void> _createTrashTable(Database db) async {await db.execute('''CREATE TABLE IF NOT EXISTS ${LockerDB.trashTable} (@@ -538,6 +580,94 @@ class LockerDB extends EnteBaseDatabase {await batch.commit();}+ Future<List<EnteFile>> getOfflineMarkedFiles() async {+ final markedIds = _offlineMarkedFileIDsCache.toList(growable: false);+ if (markedIds.isEmpty) {+ return [];+ }++ final placeholders = List.filled(markedIds.length, '?').join(',');+ final rows = await _db.rawQuery(+ '''+ SELECT f.*+ FROM $_filesTable f+ WHERE f.uploaded_file_id IN ($placeholders)+ AND EXISTS (+ SELECT 1+ FROM $_collectionFilesTable cf+ INNER JOIN $_collectionsTable c+ ON c.id = cf.collection_id+ WHERE cf.uploaded_file_id = f.uploaded_file_id+ AND c.is_deleted = 0+ )+ ''',+ markedIds,+ );+ final files = <EnteFile>[];+ for (final row in rows) {+ files.add(await _mapFromRow(row));+ }+ return files;+ }++ bool isFileMarkedOfflineById(int? uploadedFileID) {+ return uploadedFileID != null &&+ _offlineMarkedFileIDsCache.contains(uploadedFileID);+ }++ bool isFileMarkedOffline(EnteFile file) {+ return isFileMarkedOfflineById(file.uploadedFileID);+ }++ Future<void> setFilesMarkedOffline(+ Iterable<int> uploadedFileIDs,+ bool isMarkedOffline,+ ) async {+ final ids = uploadedFileIDs.toSet();+ if (ids.isEmpty) {+ return;+ }++ final batch = _db.batch();+ for (final uploadedFileID in ids) {+ if (isMarkedOffline) {+ batch.insert(+ _offlineFilesTable,+ {'uploaded_file_id': uploadedFileID},+ conflictAlgorithm: ConflictAlgorithm.ignore,+ );+ } else {+ batch.delete(+ _offlineFilesTable,+ where: 'uploaded_file_id = ?',+ whereArgs: [uploadedFileID],+ );+ }+ }+ await batch.commit();+ if (isMarkedOffline) {+ _offlineMarkedFileIDsCache.addAll(ids);+ } else {+ _offlineMarkedFileIDsCache.removeAll(ids);+ }+ }++ Future<bool> hasActiveFile(int uploadedFileID) async {+ final rows = await _db.rawQuery(+ '''+ SELECT 1+ FROM $_collectionFilesTable cf+ INNER JOIN $_collectionsTable c+ ON c.id = cf.collection_id+ WHERE c.is_deleted = 0+ AND cf.uploaded_file_id = ?+ LIMIT 1+ ''',+ [uploadedFileID],+ );+ return rows.isNotEmpty;+ }+Map<String, dynamic> _collectionToMap(Collection collection) {final collectionKey = CryptoHelper.instance.getCollectionKey(collection);final encryptedPayload = CryptoUtil.encryptSync(@@ -852,8 +982,10 @@ class LockerDB extends EnteBaseDatabase {await _database?.delete(_filesTable);await _database?.delete(LockerDB.trashTable);await _database?.delete(_collectionFilesTable);+ await _database?.delete(_offlineFilesTable);await _database?.delete(_syncTimesTable);_collectionSyncTimesCache.clear();+ _offlineMarkedFileIDsCache.clear();_collectionSyncTime = 0;}}diff --git a/mobile/apps/locker/lib/services/files/download/file_downloader.dart b/mobile/apps/locker/lib/services/files/download/file_downloader.dartindex 849992730b..88390b6b6c 100644--- a/mobile/apps/locker/lib/services/files/download/file_downloader.dart+++ b/mobile/apps/locker/lib/services/files/download/file_downloader.dart@@ -6,30 +6,194 @@ import 'package:ente_crypto_api/ente_crypto_api.dart';import 'package:ente_network/network.dart';import 'package:ente_pure_utils/ente_pure_utils.dart';import 'package:locker/services/configuration.dart';+import 'package:locker/services/db/locker_db.dart';import 'package:locker/services/files/download/models/task.dart';import 'package:locker/services/files/download/service_locator.dart';+import 'package:locker/services/files/offline/offline_file_storage.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");-String getCachedEncryptedFilePath(EnteFile file) {- final String cacheDir = Configuration.instance.getCacheDirectory();- return "$cacheDir${file.uploadedFileID}.encrypted";-}+/// Returns the encrypted offline blob for this device, downloading it only when+/// a usable local copy does not already exist.+Future<File> ensureEncryptedOfflineCopy(+ EnteFile file, {+ ProgressCallback? progressCallback,+}) async {+ final existingFile = await getCurrentOfflineEncryptedCopy(file);+ if (existingFile != null) {+ final existingSize = await existingFile.length();+ progressCallback?.call(existingSize, existingSize);+ return existingFile;+ }++ final String logPrefix = 'File-${file.uploadedFileID}:';+ final String tempDir = Configuration.instance.getTempDirectory();+ final String tempEncryptedFilePath =+ "$tempDir${file.uploadedFileID}.encrypted";+ final String finalEncryptedFilePath = await getOfflineEncryptedFilePath(file);+ final File finalEncryptedFile = File(finalEncryptedFilePath);++ String encryptedFilePath = tempEncryptedFilePath;+ File encryptedFile = File(encryptedFilePath);++ try {+ if (downloadManager.enableResumableDownload(file.fileSize)) {+ final DownloadResult result = await downloadManager.download(+ file.uploadedFileID!,+ file.displayName,+ file.fileSize!,+ );+ if (!result.success || result.task.filePath == null) {+ throw Exception(+ '$logPrefix download failed ${result.task.error} ${result.task.status}',+ );+ }+ encryptedFilePath = result.task.filePath!;+ encryptedFile = File(encryptedFilePath);+ final encryptedSize = await encryptedFile.length();+ progressCallback?.call(encryptedSize, encryptedSize);+ } else {+ late final Response response;+ try {+ response = await Network.instance.getDio().download(+ file.downloadUrl,+ tempEncryptedFilePath,+ options: Options(+ headers: {"X-Auth-Token": Configuration.instance.getToken()},+ ),+ onReceiveProgress: progressCallback,+ );+ } catch (e) {+ try {+ if (await encryptedFile.exists()) {+ await encryptedFile.delete();+ }+ } catch (_) {}+ rethrow;+ }++ if (response.statusCode != 200 || !await encryptedFile.exists()) {+ throw Exception('$logPrefix download failed ${response.toString()}');+ }+ }++ if (await finalEncryptedFile.exists()) {+ await finalEncryptedFile.delete();+ }++ if (encryptedFilePath == finalEncryptedFilePath) {+ return finalEncryptedFile;+ }-String getCachedDecryptedFilePath(EnteFile file) {- final String cacheDir = Configuration.instance.getCacheDirectory();- final String extension = _safeExtension(file.displayName);- return "$cacheDir${file.uploadedFileID}.decrypted$extension";+ await encryptedFile.copy(finalEncryptedFilePath);+ await encryptedFile.delete();+ _logger.info('$logPrefix persisted encrypted offline copy');+ return finalEncryptedFile;+ } catch (e, s) {+ _logger.severe(+ '$logPrefix failed to ensure encrypted offline copy',+ e,+ s,+ );+ try {+ if (await encryptedFile.exists() &&+ encryptedFile.path != finalEncryptedFilePath) {+ await encryptedFile.delete();+ }+ } catch (_) {}+ try {+ if (await finalEncryptedFile.exists()) {+ await finalEncryptedFile.delete();+ }+ } catch (_) {}+ rethrow;+ }}-String _safeExtension(String fileName) {- final ext = p.extension(p.basename(fileName));- if (ext.isEmpty) return '';- final sanitized = ext.replaceAll(RegExp(r'[\\/:*?"<>|]'), '');- return sanitized == '.' ? '' : sanitized;+Future<File?> openFile(+ EnteFile file,+ Uint8List fileKey, {+ ProgressCallback? progressCallback,+}) async {+ if (!LockerDB.instance.isFileMarkedOffline(file)) {+ return downloadAndDecrypt(+ file,+ fileKey,+ progressCallback: progressCallback,+ shouldUseCache: true,+ );+ }++ try {+ final offlineEncryptedFile = await ensureEncryptedOfflineCopy(+ file,+ progressCallback: progressCallback,+ );+ final String logPrefix = 'File-${file.uploadedFileID}:';+ final int startTime = DateTime.now().millisecondsSinceEpoch;+ final String decryptedFilePath = getCachedDecryptedFilePath(file);+ final File decryptedFile = File(decryptedFilePath);+ final int sizeInBytes = file.fileSize ?? await offlineEncryptedFile.length();++ try {+ if (await decryptedFile.exists()) {+ final decryptedSize = await decryptedFile.length();+ if (decryptedSize > 0) {+ progressCallback?.call(decryptedSize, decryptedSize);+ return decryptedFile;+ }+ await decryptedFile.delete();+ }++ await CryptoUtil.decryptFile(+ offlineEncryptedFile.path,+ decryptedFilePath,+ CryptoUtil.base642bin(file.fileDecryptionHeader!),+ fileKey,+ );++ final double elapsedSeconds =+ (DateTime.now().millisecondsSinceEpoch - startTime) / 1000;+ final double speedInKBps =+ elapsedSeconds <= 0 ? 0 : sizeInBytes / 1024.0 / elapsedSeconds;+ _logger.info(+ '$logPrefix local decrypt completed: ${formatBytes(sizeInBytes)}, avg speed: ${speedInKBps.toStringAsFixed(2)} KB/s',+ );+ return decryptedFile;+ } catch (e, s) {+ _logger.severe("Critical: $logPrefix failed to decrypt", e, s);+ try {+ if (await decryptedFile.exists()) {+ await decryptedFile.delete();+ }+ } catch (_) {}+ }+ } catch (e, s) {+ _logger.warning(+ 'Failed to use offline encrypted copy for ${file.uploadedFileID}, falling back to direct download',+ e,+ s,+ );+ }++ if (file.uploadedFileID != null) {+ try {+ await removeOfflineFileCopiesFromDisk(+ [file.uploadedFileID!],+ removeWorkingCopies: false,+ );+ } catch (_) {}+ }++ return downloadAndDecrypt(+ file,+ fileKey,+ progressCallback: progressCallback,+ shouldUseCache: true,+ );}Future<File?> downloadAndDecrypt(@@ -108,7 +272,6 @@ Future<File?> downloadAndDecrypt(return null;}} else {- // If the file is small, download it directly to the final locationfinal response = await Network.instance.getDio().download(file.downloadUrl,tempEncryptedFilePath,@@ -138,18 +301,15 @@ Future<File?> downloadAndDecrypt('$logPrefix download completed: ${formatBytes(sizeInBytes)}, avg speed: ${speedInKBps.toStringAsFixed(2)} KB/s',);- // As decryption can take time, emit fake progress for large files during- // decryptionfinal FakePeriodicProgress? fakeProgress = shouldFakeProgress? FakePeriodicProgress(- callback: (count) {+ callback: (_) {progressCallback?.call(sizeInBytes, sizeInBytes);},duration: const Duration(milliseconds: 5000),): null;try {- // Start the periodic callback after initial 5 secondsfakeProgress?.start();if (await decryptedFile.exists()) {await decryptedFile.delete();@@ -171,14 +331,13 @@ Future<File?> downloadAndDecrypt(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;}+if (shouldUseCache && downloadedFreshEncryptedFile) {try {if (encryptedFilePath != cachedEncryptedFilePath) {diff --git a/mobile/apps/locker/lib/services/files/offline/offline_file_storage.dart b/mobile/apps/locker/lib/services/files/offline/offline_file_storage.dartnew file mode 100644index 0000000000..5fd7c204b3--- /dev/null+++ b/mobile/apps/locker/lib/services/files/offline/offline_file_storage.dart@@ -0,0 +1,233 @@+import 'dart:io';++import 'package:locker/services/configuration.dart';+import 'package:locker/services/files/sync/models/file.dart';+import 'package:logging/logging.dart';+import 'package:path/path.dart' as p;+import 'package:path_provider/path_provider.dart';++const _offlineEncryptedDirName = 'offline_documents';+final _logger = Logger('OfflineFileStorage');++String _safeExtension(String fileName) {+ final ext = p.extension(p.basename(fileName));+ if (ext.isEmpty) return '';+ final sanitized = ext.replaceAll(RegExp(r'[\\/:*?"<>|]'), '');+ return sanitized == '.' ? '' : sanitized;+}++String getCachedEncryptedFilePath(EnteFile file) {+ final String cacheDir = Configuration.instance.getCacheDirectory();+ return "$cacheDir${file.uploadedFileID}.encrypted";+}++String getCachedDecryptedFilePath(EnteFile file) {+ final String cacheDir = Configuration.instance.getCacheDirectory();+ final String extension = _safeExtension(file.displayName);+ return "$cacheDir${file.uploadedFileID}.decrypted$extension";+}++/// Persistent encrypted offline blobs live in app support so they survive app+/// restarts and are not mixed with temporary cache files.+Future<Directory> _getOfflineEncryptedDirectory() async {+ final supportDirectory = await getApplicationSupportDirectory();+ final directory = Directory(+ p.join(supportDirectory.path, _offlineEncryptedDirName),+ );+ if (!await directory.exists()) {+ await directory.create(recursive: true);+ }+ return directory;+}++Future<String> getOfflineEncryptedFilePath(EnteFile file) async {+ final directory = await _getOfflineEncryptedDirectory();+ return p.join(directory.path, '${file.uploadedFileID}.encrypted');+}++/// Returns the current encrypted offline blob for a file from the current+/// `<fileId>.encrypted` layout.+Future<File?> getCurrentOfflineEncryptedCopy(EnteFile file) async {+ final finalPath = await getOfflineEncryptedFilePath(file);+ final encryptedFile = File(finalPath);+ if (await encryptedFile.exists()) {+ final encryptedSize = await encryptedFile.length();+ if (encryptedSize > 0) {+ return encryptedFile;+ }+ _logger.warning(+ 'Deleting empty offline encrypted copy for ${file.uploadedFileID}',+ );+ await encryptedFile.delete();+ }++ return null;+}++/// Remove persistent encrypted copies and, optionally, temporary decrypted+/// working copies for the given Locker file IDs from local disk only.+Future<void> removeOfflineFileCopiesFromDisk(+ Iterable<int> fileIds, {+ bool removeWorkingCopies = true,+}) async {+ final ids = fileIds.toSet();+ if (ids.isEmpty) {+ return;+ }++ _logger.fine(+ 'Removing offline file copies for ${ids.length} files'+ ' (removeWorkingCopies=$removeWorkingCopies)',+ );++ await _deleteFilesFromDirectory(await _getOfflineEncryptedDirectory(), (+ baseName,+ ) {+ final fileId = _parseEncryptedFileId(baseName);+ return fileId != null && ids.contains(fileId);+ });++ if (!removeWorkingCopies) {+ return;+ }++ await _deleteCachedFileCopies(ids);+}++/// Prune encrypted blobs for files that are no longer part of the local offline+/// set. Working copies are optional because open files may still be in use by+/// another app.+Future<void> removeOfflineFileCopiesExcept(+ Set<int> keepIds, {+ bool removeWorkingCopies = true,+}) async {+ await _deleteFilesFromDirectory(await _getOfflineEncryptedDirectory(), (+ baseName,+ ) {+ final fileId = _parseEncryptedFileId(baseName);+ return fileId != null && !keepIds.contains(fileId);+ });++ if (!removeWorkingCopies) {+ return;+ }++ await _deleteCachedFileCopiesExcept(keepIds);+}++Future<void> clearAllOfflineFileCopies() async {+ _logger.info('Clearing all offline file copies');+ final encryptedDirectory = await _getOfflineEncryptedDirectory();+ if (await encryptedDirectory.exists()) {+ await encryptedDirectory.delete(recursive: true);+ }++ await _deleteCachedFileCopiesExcept(<int>{});+}++Future<void> cleanupOfflineWorkingFiles({+ Duration olderThan = Duration.zero,+}) async {+ _logger.fine('Cleaning offline working files older than $olderThan');+ final directory = Directory(Configuration.instance.getCacheDirectory());+ if (!await directory.exists()) {+ return;+ }++ final now = DateTime.now();+ await for (final entity in directory.list(followLinks: false)) {+ if (entity is! File) {+ continue;+ }++ final baseName = p.basename(entity.path);+ if (_parseEncryptedFileId(baseName) == null &&+ _parseCachedDecryptedFileId(baseName) == null) {+ continue;+ }++ try {+ if (olderThan > Duration.zero) {+ final stat = await entity.stat();+ if (now.difference(stat.modified) < olderThan) {+ continue;+ }+ }+ await entity.delete();+ } catch (e, s) {+ _logger.warning('Failed to delete cached offline working file', e, s);+ }+ }+}++int? _parseEncryptedFileId(String baseName) {+ final match = RegExp(r'^(\d+)\.encrypted$').firstMatch(baseName);+ if (match == null) {+ return null;+ }+ return int.tryParse(match.group(1)!);+}++int? _parseCachedDecryptedFileId(String baseName) {+ final match = RegExp(r'^(\d+)\.decrypted').firstMatch(baseName);+ if (match == null) {+ return null;+ }+ return int.tryParse(match.group(1)!);+}++Future<void> _deleteCachedFileCopies(Set<int> ids) async {+ final cacheDirectory = Directory(Configuration.instance.getCacheDirectory());+ await _deleteFilesFromDirectory(cacheDirectory, (baseName) {+ final encryptedId = _parseEncryptedFileId(baseName);+ if (encryptedId != null && ids.contains(encryptedId)) {+ return true;+ }++ final decryptedId = _parseCachedDecryptedFileId(baseName);+ return decryptedId != null && ids.contains(decryptedId);+ });+}++Future<void> _deleteCachedFileCopiesExcept(Set<int> keepIds) async {+ final cacheDirectory = Directory(Configuration.instance.getCacheDirectory());+ await _deleteFilesFromDirectory(cacheDirectory, (baseName) {+ final encryptedId = _parseEncryptedFileId(baseName);+ if (encryptedId != null) {+ return !keepIds.contains(encryptedId);+ }++ final decryptedId = _parseCachedDecryptedFileId(baseName);+ if (decryptedId != null) {+ return !keepIds.contains(decryptedId);+ }++ return false;+ });+}++Future<void> _deleteFilesFromDirectory(+ Directory directory,+ bool Function(String baseName) shouldDelete,+) async {+ if (!await directory.exists()) {+ return;+ }++ await for (final entity in directory.list(followLinks: false)) {+ if (entity is! File) {+ continue;+ }++ final baseName = p.basename(entity.path);+ if (!shouldDelete(baseName)) {+ continue;+ }++ try {+ await entity.delete();+ } catch (e, s) {+ _logger.warning('Failed to delete offline file copy ${entity.path}', e, s);+ }+ }+}diff --git a/mobile/apps/locker/lib/services/files/offline/offline_files_service.dart b/mobile/apps/locker/lib/services/files/offline/offline_files_service.dartnew file mode 100644index 0000000000..db8a92170e--- /dev/null+++ b/mobile/apps/locker/lib/services/files/offline/offline_files_service.dart@@ -0,0 +1,457 @@+import 'dart:async';+import 'dart:io';++import 'package:dio/dio.dart';+import 'package:ente_events/event_bus.dart';+import 'package:ente_ui/utils/dialog_util.dart';+import 'package:ente_ui/utils/toast_util.dart';+import 'package:flutter/material.dart';+import 'package:locker/events/collections_updated_event.dart';+import 'package:locker/l10n/l10n.dart';+import 'package:locker/services/configuration.dart';+import 'package:locker/services/db/locker_db.dart';+import 'package:locker/services/files/download/file_downloader.dart';+import 'package:locker/services/files/offline/offline_file_storage.dart';+import 'package:locker/services/files/sync/models/file.dart';+import 'package:locker/services/info_file_service.dart';+import 'package:logging/logging.dart';++enum _OfflineSaveFailureKind {+ generic,+ network,+ storage,+}++/// Handles Locker's explicit per-file offline save flow.+///+/// A file is marked offline only after the encrypted blob has been saved on+/// this device.+class OfflineFilesService {+ OfflineFilesService._privateConstructor();++ static const _cachedFileCleanupAge = Duration(hours: 12);++ static final OfflineFilesService instance =+ OfflineFilesService._privateConstructor();++ final Logger _logger = Logger('OfflineFilesService');++ Future<void> init() async {+ _logger.fine('Cleaning up stale offline working files');+ await cleanupOfflineWorkingFiles(+ olderThan: _cachedFileCleanupAge,+ );+ }++ /// Shared files and info records are intentionally excluded from offline save.+ bool canMarkOffline(EnteFile file) {+ final currentUserID = Configuration.instance.getUserID();+ return file.uploadedFileID != null &&+ file.fileDecryptionHeader != null &&+ file.ownerID == currentUserID &&+ !InfoFileService.instance.isInfoFile(file);+ }++ /// Deduplicate selections by uploaded file ID so bulk actions only process+ /// each file once.+ List<EnteFile> getEligibleFiles(Iterable<EnteFile> files) {+ final filesById = <int, EnteFile>{};++ for (final file in files) {+ final fileId = file.uploadedFileID;+ if (fileId == null || !canMarkOffline(file)) {+ continue;+ }+ filesById[fileId] = file;+ }++ return filesById.values.toList();+ }++ /// Count shared files for UI messaging while still allowing owned files in+ /// the same selection to continue.+ int countSharedFiles(Iterable<EnteFile> files) {+ final currentUserID = Configuration.instance.getUserID();+ var sharedCount = 0;+ final seenFileIDs = <int>{};++ for (final file in files) {+ final fileId = file.uploadedFileID;+ if (fileId == null || !seenFileIDs.add(fileId)) {+ continue;+ }+ if (InfoFileService.instance.isInfoFile(file)) {+ continue;+ }+ if (file.ownerID != null && file.ownerID != currentUserID) {+ sharedCount += 1;+ }+ }++ return sharedCount;+ }++ bool hasEligibleFiles(Iterable<EnteFile> files) {+ return getEligibleFiles(files).isNotEmpty;+ }++ /// The bottom sheet only shows "Remove offline" when every actionable+ /// file in the selection is already marked offline on this device.+ bool shouldRemoveOfflineForSelection(Iterable<EnteFile> files) {+ final eligibleFiles = getEligibleFiles(files);+ if (eligibleFiles.isEmpty) {+ return false;+ }+ return eligibleFiles.every(LockerDB.instance.isFileMarkedOffline);+ }++ /// Downloads the encrypted blob and marks the file offline on success.+ Future<bool> markFilesOffline(+ BuildContext context,+ Iterable<EnteFile> files,+ ) async {+ final eligibleFiles = getEligibleFiles(files);+ final sharedCount = countSharedFiles(files);+ _logger.info(+ 'Mark offline requested for ${eligibleFiles.length} eligible files'+ '${sharedCount > 0 ? ' ($sharedCount shared skipped)' : ''}',+ );++ if (sharedCount > 0 && context.mounted) {+ showToast(+ context,+ context.l10n.actionNotSupportedForSharedFiles(sharedCount),+ );+ }++ if (eligibleFiles.isEmpty || !context.mounted) {+ _logger.fine('No eligible files to mark offline');+ return false;+ }++ final total = eligibleFiles.length;+ final dialog = createProgressDialog(+ context,+ total == 1+ ? context.l10n.savingOffline+ : '${context.l10n.savingOffline} 0/$total',+ isDismissible: false,+ );++ var successCount = 0;+ var failureCount = 0;+ final failureKinds = <_OfflineSaveFailureKind>{};++ await dialog.show();++ try {+ for (var index = 0; index < eligibleFiles.length; index++) {+ final file = eligibleFiles[index];+ final fileID = file.uploadedFileID!;+ final currentStep = index + 1;++ dialog.update(+ message: _buildMarkProgressMessage(+ context,+ currentStep,+ total,+ ),+ );++ final alreadyHasOfflineCopy =+ LockerDB.instance.isFileMarkedOffline(file) &&+ await getCurrentOfflineEncryptedCopy(file) != null;+ if (alreadyHasOfflineCopy) {+ _logger.fine('File $fileID already available offline');+ successCount += 1;+ continue;+ }++ try {+ final didMarkFile = await _ensureOfflineCopyAndMark(+ file,+ progressCallback: (downloaded, totalBytes) {+ if (!context.mounted || totalBytes <= 0) {+ return;+ }+ final percentage =+ ((downloaded / totalBytes) * 100).clamp(0, 100).round();+ dialog.update(+ message: _buildMarkProgressMessage(+ context,+ currentStep,+ total,+ percentage: percentage,+ ),+ );+ },+ );+ if (didMarkFile) {+ _logger.info('Marked file $fileID available offline');+ successCount += 1;+ continue;+ }++ failureCount += 1;+ failureKinds.add(_OfflineSaveFailureKind.generic);+ } catch (e, s) {+ final failureKind = _classifyOfflineSaveFailure(e);+ failureCount += 1;+ failureKinds.add(failureKind);+ _logger.warning(+ 'Failed to mark file $fileID available offline',+ e,+ s,+ );+ await _cleanupFailedMark(file);+ if (_shouldStopBatchOnFailure(failureKind)) {+ failureCount += total - currentStep;+ break;+ }+ }+ }+ } finally {+ try {+ await dialog.hide();+ } catch (_) {}+ }++ _logger.info(+ 'Mark offline completed: success=$successCount failure=$failureCount',+ );++ if (successCount > 0) {+ Bus.instance+ .fire(CollectionsUpdatedEvent('offline_availability_changed'));+ }++ if (!context.mounted) {+ return successCount > 0;+ }++ if (failureCount == 0) {+ showToast(+ context,+ context.l10n.filesAvailableOffline(successCount),+ );+ } else if (successCount > 0) {+ showToast(+ context,+ context.l10n.filesAvailableOfflinePartial(successCount, failureCount),+ );+ } else {+ showToast(+ context,+ _buildMarkFailureMessage(context, failureCount, failureKinds),+ );+ }++ return successCount > 0;+ }++ /// Clears offline state for the selected files on this device.+ Future<bool> unmarkFilesOffline(+ BuildContext context,+ Iterable<EnteFile> files,+ ) async {+ final eligibleFiles = getEligibleFiles(files);+ final sharedCount = countSharedFiles(files);+ _logger.info(+ 'Remove offline requested for ${eligibleFiles.length} eligible files'+ '${sharedCount > 0 ? ' ($sharedCount shared skipped)' : ''}',+ );++ if (sharedCount > 0 && context.mounted) {+ showToast(+ context,+ context.l10n.actionNotSupportedForSharedFiles(sharedCount),+ );+ }++ if (eligibleFiles.isEmpty) {+ _logger.fine('No eligible files to remove from offline');+ return false;+ }++ final filesToUnmark = <EnteFile>[];+ for (final file in eligibleFiles) {+ final hasOfflineCopy = await getCurrentOfflineEncryptedCopy(file) != null;+ if (!LockerDB.instance.isFileMarkedOffline(file) && !hasOfflineCopy) {+ continue;+ }+ filesToUnmark.add(file);+ }++ final changedCount = filesToUnmark.length;+ _logger.fine('Removing offline state for $changedCount files');+ await unmarkFilesOfflineLocally(filesToUnmark);++ if (changedCount > 0) {+ Bus.instance+ .fire(CollectionsUpdatedEvent('offline_availability_changed'));+ }++ if (changedCount == 0 || !context.mounted) {+ return changedCount > 0;+ }++ showToast(+ context,+ context.l10n.filesRemovedFromOffline(changedCount),+ );+ return true;+ }++ Future<void> _setOfflineMarkForFile(+ EnteFile file,+ bool isMarkedOffline,+ ) async {+ final fileID = file.uploadedFileID!;+ await LockerDB.instance.setFilesMarkedOffline(+ [fileID],+ isMarkedOffline,+ );+ }++ /// Service-level unmark path used by non-UI flows like trash/delete.+ Future<void> unmarkFilesOfflineById(+ Iterable<int> fileIDs, {+ bool removeWorkingCopies = true,+ }) async {+ final ids = fileIDs.toSet();+ if (ids.isEmpty) {+ return;+ }++ _logger.fine(+ 'Clearing offline state for ${ids.length} files'+ ' (removeWorkingCopies=$removeWorkingCopies)',+ );++ await LockerDB.instance.setFilesMarkedOffline(ids, false);+ await removeOfflineFileCopiesFromDisk(+ ids,+ removeWorkingCopies: removeWorkingCopies,+ );+ }++ Future<void> unmarkFilesOfflineLocally(+ Iterable<EnteFile> files, {+ bool removeWorkingCopies = true,+ }) async {+ final ids = <int>{};+ for (final file in files) {+ final fileID = file.uploadedFileID;+ if (fileID == null) {+ continue;+ }+ ids.add(fileID);+ }++ await unmarkFilesOfflineById(+ ids,+ removeWorkingCopies: removeWorkingCopies,+ );+ }++ /// Downloads first, then writes the local offline mark if the file is still+ /// active in the current library view.+ Future<bool> _ensureOfflineCopyAndMark(+ EnteFile file, {+ ProgressCallback? progressCallback,+ }) async {+ final fileID = file.uploadedFileID!;+ if (await getCurrentOfflineEncryptedCopy(file) == null) {+ await ensureEncryptedOfflineCopy(+ file,+ progressCallback: progressCallback,+ );+ }++ if (!await LockerDB.instance.hasActiveFile(fileID)) {+ _logger.warning(+ 'Skipping offline mark for file $fileID because it is no longer active',+ );+ await unmarkFilesOfflineLocally(+ [file],+ removeWorkingCopies: false,+ );+ return false;+ }++ await _setOfflineMarkForFile(file, true);+ return true;+ }++ /// Keep decrypted working files intact; only clear offline state.+ Future<void> _cleanupFailedMark(EnteFile file) async {+ _logger.fine(+ 'Cleaning up failed offline mark for file ${file.uploadedFileID}',+ );+ await unmarkFilesOfflineLocally(+ [file],+ removeWorkingCopies: false,+ );+ }++ String _buildMarkProgressMessage(+ BuildContext context,+ int current,+ int total, {+ int? percentage,+ }) {+ final progressLabel = percentage == null+ ? context.l10n.savingOffline+ : context.l10n.savingOfflineProgress(percentage);+ if (total == 1) {+ return progressLabel;+ }+ return '$progressLabel ($current/$total)';+ }++ _OfflineSaveFailureKind _classifyOfflineSaveFailure(Object error) {+ if (error is FileSystemException) {+ return _OfflineSaveFailureKind.storage;+ }+ if (_isNetworkError(error)) {+ return _OfflineSaveFailureKind.network;+ }+ return _OfflineSaveFailureKind.generic;+ }++ bool _shouldStopBatchOnFailure(_OfflineSaveFailureKind failureKind) {+ return failureKind == _OfflineSaveFailureKind.network ||+ failureKind == _OfflineSaveFailureKind.storage;+ }++ bool _isNetworkError(Object error) {+ if (error is SocketException) {+ return true;+ }+ if (error is DioException) {+ return error.type == DioExceptionType.connectionTimeout ||+ error.type == DioExceptionType.connectionError ||+ (error.type == DioExceptionType.unknown && error.response == null);+ }+ return false;+ }++ String _buildMarkFailureMessage(+ BuildContext context,+ int failureCount,+ Set<_OfflineSaveFailureKind> failureKinds,+ ) {+ final failureKind = failureKinds.length == 1+ ? failureKinds.first+ : _OfflineSaveFailureKind.generic;++ switch (failureKind) {+ case _OfflineSaveFailureKind.network:+ return context.l10n.failedToSaveFilesOfflineNetwork(failureCount);+ case _OfflineSaveFailureKind.storage:+ return context.l10n.failedToSaveFilesOfflineStorage(failureCount);+ case _OfflineSaveFailureKind.generic:+ return context.l10n.failedToSaveFilesOffline(failureCount);+ }+ }+}diff --git a/mobile/apps/locker/lib/services/trash/trash_service.dart b/mobile/apps/locker/lib/services/trash/trash_service.dartindex 29329d8314..00dde6c7a9 100644--- a/mobile/apps/locker/lib/services/trash/trash_service.dart+++ b/mobile/apps/locker/lib/services/trash/trash_service.dart@@ -15,6 +15,7 @@ import 'package:locker/services/collections/models/collection_file_item.dart';import "package:locker/services/configuration.dart";import 'package:locker/services/db/locker_db.dart';import 'package:locker/services/db/trash_table.dart';+import 'package:locker/services/files/offline/offline_files_service.dart';import 'package:locker/services/files/sync/models/file.dart';import 'package:locker/services/files/sync/models/file_magic.dart';import 'package:locker/services/trash/models/trash_file.dart';@@ -54,10 +55,20 @@ class TrashService {if (diff.trashedFiles.isNotEmpty) {_logger.fine("inserting ${diff.trashedFiles.length} items in trash");await _db.insertTrashFiles(diff.trashedFiles);+ final trashedFileIds =+ diff.trashedFiles.map((file) => file.uploadedFileID!).toList();+ await OfflineFilesService.instance.unmarkFilesOfflineById(+ trashedFileIds,+ removeWorkingCopies: false,+ );}if (diff.deletedUploadIDs.isNotEmpty) {_logger.fine("discard ${diff.deletedUploadIDs.length} deleted items");await _db.deleteTrashFiles(diff.deletedUploadIDs);+ await OfflineFilesService.instance.unmarkFilesOfflineById(+ diff.deletedUploadIDs,+ removeWorkingCopies: false,+ );}if (diff.restoredFiles.isNotEmpty) {_logger.fine("discard ${diff.restoredFiles.length} restored items");@@ -72,6 +83,7 @@ class TrashService {if (diff.hasMore) {return syncTrash();}+}Future<List<TrashFile>> getTrashFiles() async {diff --git a/mobile/apps/locker/lib/ui/components/file_list_widget.dart b/mobile/apps/locker/lib/ui/components/file_list_widget.dartindex e351b6ff59..5ec83b2545 100644--- a/mobile/apps/locker/lib/ui/components/file_list_widget.dart+++ b/mobile/apps/locker/lib/ui/components/file_list_widget.dart@@ -6,6 +6,7 @@ import "package:hugeicons/hugeicons.dart";import "package:locker/models/selected_files.dart";import "package:locker/services/collections/collections_service.dart";import "package:locker/services/configuration.dart";+import "package:locker/services/db/locker_db.dart";import "package:locker/services/files/sync/models/file.dart";import "package:locker/services/info_file_service.dart";import "package:locker/utils/file_icon_utils.dart";@@ -46,6 +47,7 @@ class FileListWidget extends StatelessWidget {final bool isOutgoing = isOwner && hasSharees;final bool isIncoming = collection != null && !isOwner;final bool showSharingIndicator = isOutgoing || isIncoming;+ final isMarkedOffline = LockerDB.instance.isFileMarkedOffline(file);final fileRowWidget = Flexible(flex: 6,@@ -60,6 +62,23 @@ class FileListWidget extends StatelessWidget {padding: const EdgeInsets.all(10.0),child: _buildFileIcon(),),+ if (isMarkedOffline)+ Positioned(+ top: 4,+ right: 2,+ child: Container(+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: colorScheme.backdropBase,+ ),+ padding: const EdgeInsets.all(1.0),+ child: Icon(+ Icons.offline_pin_rounded,+ color: colorScheme.primary700,+ size: 16.0,+ ),+ ),+ ),if (showSharingIndicator)Positioned(right: 1,diff --git a/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart b/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dartindex d7385b1150..7b6f5d950b 100644--- a/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart+++ b/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart@@ -15,6 +15,7 @@ import "package:locker/services/collections/models/collection.dart";import "package:locker/services/collections/models/collection_view_type.dart";import "package:locker/services/configuration.dart";import "package:locker/services/favorites_service.dart";+import "package:locker/services/files/offline/offline_files_service.dart";import "package:locker/services/files/sync/models/file.dart";import "package:locker/services/trash/trash_service.dart";import "package:locker/ui/components/add_to_collection_sheet.dart";@@ -465,6 +466,12 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar> {final files = selectedFiles.toList();final viewType = widget.collectionViewType;final actions = <Widget>[];+ final canToggleOffline =+ OfflineFilesService.instance.hasEligibleFiles(files);+ final shouldRemoveOffline = canToggleOffline &&+ OfflineFilesService.instance.shouldRemoveOfflineForSelection(+ files,+ );final showEdit = viewType?.showEditOption ?? true;final showShare = viewType?.showShareOption ?? true;@@ -506,9 +513,47 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar> {);}+ if (canToggleOffline) {+ actions.add(+ SelectionActionButton(+ icon: shouldRemoveOffline+ ? Icons.cloud_off_outlined+ : Icons.offline_pin_outlined,+ label: shouldRemoveOffline+ ? context.l10n.removeFromOffline+ : context.l10n.saveOffline,+ onTap: () => _toggleOfflineAvailability(+ context,+ files,+ shouldRemoveOffline: shouldRemoveOffline,+ ),+ ),+ );+ }+return actions;}+ Future<void> _toggleOfflineAvailability(+ BuildContext context,+ List<EnteFile> files, {+ required bool shouldRemoveOffline,+ }) async {+ final success = shouldRemoveOffline+ ? await OfflineFilesService.instance.unmarkFilesOffline(+ context,+ files,+ )+ : await OfflineFilesService.instance.markFilesOffline(+ context,+ files,+ );++ if (success) {+ widget.selectedFiles.clearAll();+ }+ }+Future<void> _downloadFile(BuildContext context, EnteFile file) async {try {final success = await FileUtil.downloadFile(context, file);diff --git a/mobile/apps/locker/lib/utils/file_actions.dart b/mobile/apps/locker/lib/utils/file_actions.dartindex 5c7ca2b7ad..d30b45d5df 100644--- a/mobile/apps/locker/lib/utils/file_actions.dart+++ b/mobile/apps/locker/lib/utils/file_actions.dart@@ -166,12 +166,15 @@ class FileActions {}}- showToast(context, context.l10n.fileUpdatedSuccessfully);-await CollectionService.instance.sync();-await dialog.hide();+ if (!context.mounted) {+ return;+ }++ showToast(context, context.l10n.fileUpdatedSuccessfully);+onSuccess?.call();} catch (e) {await dialog.hide();diff --git a/mobile/apps/locker/lib/utils/file_util.dart b/mobile/apps/locker/lib/utils/file_util.dartindex 1e96e72e6b..81f3cca7f9 100644--- a/mobile/apps/locker/lib/utils/file_util.dart+++ b/mobile/apps/locker/lib/utils/file_util.dart@@ -11,7 +11,9 @@ 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/files/download/file_downloader.dart";+import "package:locker/services/files/download/file_downloader.dart"+ as file_downloader;+import "package:locker/services/files/offline/offline_file_storage.dart";import "package:locker/services/files/sync/models/file.dart";import "package:locker/services/info_file_service.dart";import "package:locker/ui/components/gradient_button.dart";@@ -55,21 +57,22 @@ class FileUtil {try {await dialog.show();final fileKey = await CollectionService.instance.getFileKey(file);- final decryptedFile = await downloadAndDecrypt(+ File? decryptedFile;+ void progressCallback(int downloaded, int total) {+ if (total > 0 && downloaded >= 0) {+ final percentage = ((downloaded / total) * 100).clamp(0, 100).round();+ dialog.update(+ message: context.l10n.downloadingProgress(percentage),+ );+ } else {+ dialog.update(message: context.l10n.downloading);+ }+ }++ decryptedFile = await file_downloader.openFile(file,fileKey,- progressCallback: (downloaded, total) {- if (total > 0 && downloaded >= 0) {- final percentage =- ((downloaded / total) * 100).clamp(0, 100).round();- dialog.update(- message: context.l10n.downloadingProgress(percentage),- );- } else {- dialog.update(message: context.l10n.downloading);- }- },- shouldUseCache: true,+ progressCallback: progressCallback,);await dialog.hide();@@ -227,7 +230,7 @@ class FileUtil {}) async {final fileKey = await CollectionService.instance.getFileKey(file);- final decryptedFile = await downloadAndDecrypt(+ final decryptedFile = await file_downloader.openFile(file,fileKey,progressCallback: (downloaded, total) {@@ -239,7 +242,6 @@ class FileUtil {);}},- shouldUseCache: false,);if (decryptedFile == null) {@@ -401,7 +403,10 @@ class FileUtil {String fileName,) async {try {- await OpenFile.open(file.path);+ final result = await OpenFile.open(file.path);+ if (result.type != ResultType.done) {+ throw Exception(result.message);+ }} catch (e) {await showGenericErrorBottomSheet(context: context,