π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mobile/photos] Add internal-only resumable gallery download queue
Neeraj Gupta71929d44996b
diff --git a/mobile/apps/photos/docs/resumable_downloads.md b/mobile/apps/photos/docs/resumable_downloads.mdnew file mode 100644index 0000000000..6fd6453a3a--- /dev/null+++ b/mobile/apps/photos/docs/resumable_downloads.md@@ -0,0 +1,40 @@+# Resumable Gallery Downloads++This document describes the `mobile/apps/photos` implementation for resumable+"Save to gallery" downloads.++## Overview++- Downloads are enqueued into a single app-wide queue.+- Queue state is persisted in `GalleryDownloadsDB` so tasks survive process+ restarts.+- Up to 5 downloads run concurrently.+- User-initiated save flows route through resumable download logic for all+ sizes.+- Progress is shown as a non-blocking banner on the home screen.++## Components++- `lib/module/download/gallery_download_queue_service.dart`+ Orchestrates enqueue, concurrency, resume, cancellation, and completion state.+- `lib/db/gallery_downloads_db.dart`+ Persists queue tasks.+- `lib/ui/home/gallery_download_banner.dart`+ Displays queue status and opens per-file details.+- `lib/utils/file_download_util.dart` and `lib/utils/file_util.dart`+ Added force-resumable mode for gallery save flows.++## Behavior++- Duplicate enqueue by uploaded file ID is ignored.+- Incomplete tasks older than 7 days are dropped on startup, and temp partials+ are cleaned up.+- Network interruptions pause tasks and auto-resume on connectivity recovery.+- Storage-related failures pause tasks until retried.+- Queue is cleared on logout.++## Entry points using queue++- Multi-selection download action.+- Single-file viewer download action.+- Public album download action.diff --git a/mobile/apps/photos/lib/core/configuration.dart b/mobile/apps/photos/lib/core/configuration.dartindex de1305077d..12737a0625 100644--- a/mobile/apps/photos/lib/core/configuration.dart+++ b/mobile/apps/photos/lib/core/configuration.dart@@ -17,6 +17,7 @@ import 'package:photos/core/error-reporting/super_logging.dart';import 'package:photos/core/event_bus.dart';import 'package:photos/db/collections_db.dart';import 'package:photos/db/files_db.dart';+import "package:photos/db/gallery_downloads_db.dart";import "package:photos/db/memories_db.dart";import "package:photos/db/ml/db.dart";import 'package:photos/db/trash_db.dart';@@ -224,6 +225,7 @@ class Configuration {// Clear all database tablesawait FilesDB.instance.clearTable();+ await GalleryDownloadsDB.instance.clearTable();await CollectionsDB.instance.clearTable();await MemoriesDB.instance.clearTable();await MLDataDB.instance.clearTable();diff --git a/mobile/apps/photos/lib/db/gallery_downloads_db.dart b/mobile/apps/photos/lib/db/gallery_downloads_db.dartnew file mode 100644index 0000000000..3a8249318b--- /dev/null+++ b/mobile/apps/photos/lib/db/gallery_downloads_db.dart@@ -0,0 +1,140 @@+import "package:logging/logging.dart";+import "package:path/path.dart";+import "package:path_provider/path_provider.dart";+import "package:photos/db/common/base.dart";+import "package:photos/module/download/task.dart";+import "package:sqlite_async/sqlite_async.dart";++class GalleryDownloadsDB with SqlDbBase {+ static const _databaseName = "ente.gallery_downloads.db";+ static const tableName = "gallery_download_tasks";++ static const columnID = "id";+ static const columnFilename = "filename";+ static const columnTotalBytes = "total_bytes";+ static const columnBytesDownloaded = "bytes_downloaded";+ static const columnStatus = "status";+ static const columnError = "error";+ static const columnFilePath = "file_path";+ static const columnCreatedAt = "created_at";+ static const columnUpdatedAt = "updated_at";++ static final Logger _logger = Logger("GalleryDownloadsDB");++ static final _migrationScripts = [+ '''+ CREATE TABLE IF NOT EXISTS $tableName (+ $columnID INTEGER PRIMARY KEY,+ $columnFilename TEXT NOT NULL,+ $columnTotalBytes INTEGER NOT NULL,+ $columnBytesDownloaded INTEGER NOT NULL DEFAULT 0,+ $columnStatus TEXT NOT NULL,+ $columnError TEXT,+ $columnFilePath TEXT,+ $columnCreatedAt INTEGER NOT NULL,+ $columnUpdatedAt INTEGER NOT NULL+ );+ ''',+ '''+ CREATE INDEX IF NOT EXISTS gallery_download_tasks_updated_at_index+ ON $tableName($columnUpdatedAt);+ ''',+ ];++ GalleryDownloadsDB._privateConstructor();++ static final GalleryDownloadsDB instance =+ GalleryDownloadsDB._privateConstructor();++ static Future<SqliteDatabase>? _sqliteAsyncDBFuture;++ Future<SqliteDatabase> get sqliteAsyncDB async {+ _sqliteAsyncDBFuture ??= _initSqliteAsyncDatabase();+ return _sqliteAsyncDBFuture!;+ }++ Future<SqliteDatabase> _initSqliteAsyncDatabase() async {+ final documentsDirectory = await getApplicationDocumentsDirectory();+ final path = join(documentsDirectory.path, _databaseName);+ _logger.info("DB path $path");+ final database = SqliteDatabase(path: path);+ await migrate(database, _migrationScripts);+ return database;+ }++ Future<void> upsertTask(DownloadTask task) async {+ final db = await sqliteAsyncDB;+ await db.execute(+ '''+ INSERT OR REPLACE INTO $tableName (+ $columnID,+ $columnFilename,+ $columnTotalBytes,+ $columnBytesDownloaded,+ $columnStatus,+ $columnError,+ $columnFilePath,+ $columnCreatedAt,+ $columnUpdatedAt+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ ''',+ [+ task.id,+ task.filename,+ task.totalBytes,+ task.bytesDownloaded,+ task.status.name,+ task.error,+ task.filePath,+ task.createdAt,+ task.updatedAt,+ ],+ );+ }++ Future<List<DownloadTask>> getAllTasks() async {+ final db = await sqliteAsyncDB;+ final rows = await db.getAll(+ '''+ SELECT+ $columnID as id,+ $columnFilename as filename,+ $columnTotalBytes as totalBytes,+ $columnBytesDownloaded as bytesDownloaded,+ $columnStatus as status,+ $columnError as error,+ $columnFilePath as filePath,+ $columnCreatedAt as createdAt,+ $columnUpdatedAt as updatedAt+ FROM $tableName+ ORDER BY $columnCreatedAt ASC+ ''',+ );+ return rows.map((row) => DownloadTask.fromMap(row)).toList();+ }++ Future<void> deleteTask(int id) async {+ final db = await sqliteAsyncDB;+ await db.execute(+ "DELETE FROM $tableName WHERE $columnID = ?",+ [id],+ );+ }++ Future<void> deleteTasks(List<int> ids) async {+ if (ids.isEmpty) {+ return;+ }+ final db = await sqliteAsyncDB;+ final params = List.filled(ids.length, "?").join(", ");+ await db.execute(+ "DELETE FROM $tableName WHERE $columnID IN ($params)",+ ids,+ );+ }++ Future<void> clearTable() async {+ final db = await sqliteAsyncDB;+ await db.execute("DELETE FROM $tableName");+ }+}diff --git a/mobile/apps/photos/lib/events/gallery_downloads_events.dart b/mobile/apps/photos/lib/events/gallery_downloads_events.dartnew file mode 100644index 0000000000..78771d6eda--- /dev/null+++ b/mobile/apps/photos/lib/events/gallery_downloads_events.dart@@ -0,0 +1,5 @@+import "package:photos/events/event.dart";++class GalleryDownloadsUpdatedEvent extends Event {}++class GalleryDownloadsResumedEvent extends Event {}diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dartindex c07d3bc1a7..30549ae1a4 100644--- a/mobile/apps/photos/lib/main.dart+++ b/mobile/apps/photos/lib/main.dart@@ -307,6 +307,12 @@ Future<void> _init(bool isBackground, {String via = ''}) async {await SyncService.instance.init(preferences);_logger.info("SyncService init done $tlog");+ if (!isBackground && flagService.internalUser) {+ _logger.info("GalleryDownloadQueueService init $tlog");+ await galleryDownloadQueueService.init();+ _logger.info("GalleryDownloadQueueService init done $tlog");+ }+_logger.info("RitualsService init $tlog");await ritualsService.init();_logger.info("RitualsService init done $tlog");diff --git a/mobile/apps/photos/lib/module/download/gallery_download_queue_service.dart b/mobile/apps/photos/lib/module/download/gallery_download_queue_service.dartnew file mode 100644index 0000000000..7df95ff04e--- /dev/null+++ b/mobile/apps/photos/lib/module/download/gallery_download_queue_service.dart@@ -0,0 +1,569 @@+import "dart:async";+import "dart:io";++import "package:collection/collection.dart";+import "package:connectivity_plus/connectivity_plus.dart";+import "package:logging/logging.dart";+import "package:photos/core/configuration.dart";+import "package:photos/core/event_bus.dart";+import "package:photos/db/files_db.dart";+import "package:photos/db/gallery_downloads_db.dart";+import "package:photos/events/gallery_downloads_events.dart";+import "package:photos/events/user_logged_out_event.dart";+import "package:photos/models/file/file.dart";+import "package:photos/module/download/manager.dart";+import "package:photos/module/download/task.dart";+import "package:photos/service_locator.dart";+import "package:photos/utils/file_download_util.dart";++class GalleryDownloadEnqueueResult {+ final int addedCount;+ final int duplicateCount;++ const GalleryDownloadEnqueueResult({+ required this.addedCount,+ required this.duplicateCount,+ });+}++class GalleryDownloadQueueService {+ static const int kMaximumConcurrentDownloads = 5;+ static const Duration kCompletionBannerDuration = Duration(seconds: 5);+ static const Duration kStaleTaskDuration = Duration(days: 7);++ final _logger = Logger("GalleryDownloadQueueService");+ final _db = GalleryDownloadsDB.instance;++ final Map<int, DownloadTask> _tasks = {};+ final Set<int> _activeDownloads = {};+ final Map<int, StreamSubscription<DownloadTask>> _watchSubscriptions = {};+ final Map<int, EnteFile> _queuedFilesByID = {};++ StreamSubscription<List<ConnectivityResult>>? _connectivitySubscription;+ StreamSubscription<UserLoggedOutEvent>? _logoutSubscription;+ Timer? _completionCleanupTimer;+ Completer<void>? _initCompleter;++ bool _isInitialized = false;+ bool _isBannerDismissedByUser = false;+ bool _showCompletionBanner = false;++ GalleryDownloadQueueService._privateConstructor();++ static final GalleryDownloadQueueService instance =+ GalleryDownloadQueueService._privateConstructor();++ List<DownloadTask> get orderedTasks {+ final tasks = _tasks.values.toList();+ tasks.sort((a, b) => a.createdAt.compareTo(b.createdAt));+ return tasks;+ }++ int get totalCount => _tasks.length;+ int get completedCount => _tasks.values+ .where((task) => task.status == DownloadStatus.completed)+ .length;+ int get unavailableCount => _tasks.values+ .where((task) => task.error == DownloadManager.unavailableError)+ .length;+ int get downloadingCount => _tasks.values+ .where((task) => task.status == DownloadStatus.downloading)+ .length;+ int get pendingCount => _tasks.values+ .where((task) => task.status == DownloadStatus.pending)+ .length;+ int get pausedCount => _tasks.values+ .where((task) => task.status == DownloadStatus.paused)+ .length;++ bool get hasPausedDueToNoConnection => _tasks.values.any(+ (task) =>+ task.status == DownloadStatus.paused &&+ task.error == DownloadManager.noConnectionError,+ );++ bool get hasPausedDueToStorage => _tasks.values.any(+ (task) =>+ task.status == DownloadStatus.paused &&+ task.error == DownloadManager.notEnoughStorageError,+ );++ bool get hasNonUnavailableErrors => _tasks.values.any(+ (task) =>+ task.status == DownloadStatus.error &&+ task.error != DownloadManager.unavailableError,+ );++ bool get isCompletionBannerVisible =>+ _showCompletionBanner && completedCount > 0 && _allTasksAreTerminal;++ bool get isBannerVisible {+ if (_tasks.isEmpty) {+ return false;+ }+ if (isCompletionBannerVisible) {+ return true;+ }+ final hasBlockingError = _tasks.values.any(+ (task) =>+ task.status == DownloadStatus.paused ||+ (task.status == DownloadStatus.error &&+ task.error != DownloadManager.unavailableError),+ );+ if (_isBannerDismissedByUser && !hasBlockingError) {+ return false;+ }+ return _tasks.values.any((task) => !_isTerminal(task.status)) ||+ hasBlockingError;+ }++ double get overallProgress {+ if (_tasks.isEmpty) {+ return 0;+ }+ int totalBytes = 0;+ int downloadedBytes = 0;+ for (final task in _tasks.values) {+ totalBytes += task.totalBytes;+ downloadedBytes += task.bytesDownloaded.clamp(0, task.totalBytes);+ }+ if (totalBytes <= 0) {+ return 0;+ }+ return (downloadedBytes / totalBytes).clamp(0.0, 1.0);+ }++ Future<void> init() async {+ if (_isInitialized) {+ return;+ }+ if (_initCompleter != null) {+ return _initCompleter!.future;+ }+ _initCompleter = Completer<void>();+ try {+ await _loadTasksFromDB();+ _listenToConnectivity();+ _listenToLogout();+ _isInitialized = true;+ _emitUpdatedEvent();+ _pollQueue();+ _initCompleter!.complete();+ } catch (e, s) {+ _logger.severe("Failed to initialize gallery download queue", e, s);+ _initCompleter!.completeError(e, s);+ rethrow;+ } finally {+ _initCompleter = null;+ }+ }++ Future<GalleryDownloadEnqueueResult> enqueueFiles(+ List<EnteFile> files,+ ) async {+ await init();+ if (files.isEmpty) {+ return const GalleryDownloadEnqueueResult(+ addedCount: 0,+ duplicateCount: 0,+ );+ }++ int addedCount = 0;+ int duplicateCount = 0;+ int createTimestamp = DateTime.now().microsecondsSinceEpoch;++ for (final file in files) {+ final uploadID = file.uploadedFileID;+ final fileSize = file.fileSize;+ if (uploadID == null || fileSize == null || fileSize <= 0) {+ continue;+ }+ _queuedFilesByID[uploadID] =+ file.isRemoteFile ? file.copyWith() : file.copyWith(localID: null);+ if (_tasks.containsKey(uploadID)) {+ duplicateCount++;+ continue;+ }+ final task = DownloadTask(+ id: uploadID,+ filename: file.displayName,+ totalBytes: fileSize,+ status: DownloadStatus.pending,+ createdAt: createTimestamp++,+ updatedAt: createTimestamp,+ );+ _tasks[uploadID] = task;+ await _db.upsertTask(task);+ addedCount++;+ }++ if (addedCount > 0) {+ _completionCleanupTimer?.cancel();+ _showCompletionBanner = false;+ _isBannerDismissedByUser = false;+ _emitUpdatedEvent();+ _pollQueue();+ }++ return GalleryDownloadEnqueueResult(+ addedCount: addedCount,+ duplicateCount: duplicateCount,+ );+ }++ Future<void> cancelTask(int fileID) async {+ await init();+ final task = _tasks[fileID];+ if (task == null) {+ return;+ }+ final removedSubscription = _watchSubscriptions.remove(fileID);+ if (removedSubscription != null) {+ await removedSubscription.cancel();+ }+ if (_activeDownloads.contains(fileID)) {+ await downloadManager.cancel(fileID);+ _activeDownloads.remove(fileID);+ }+ _tasks.remove(fileID);+ _queuedFilesByID.remove(fileID);+ await _db.deleteTask(fileID);+ _emitUpdatedEvent();+ _pollQueue();+ }++ Future<void> cancelAll() async {+ await init();+ final activeIDs = _activeDownloads.toList(growable: false);+ for (final id in activeIDs) {+ await downloadManager.cancel(id);+ final subscription = _watchSubscriptions.remove(id);+ if (subscription != null) {+ await subscription.cancel();+ }+ }+ _activeDownloads.clear();+ _tasks.clear();+ _queuedFilesByID.clear();+ _showCompletionBanner = false;+ _isBannerDismissedByUser = false;+ _completionCleanupTimer?.cancel();+ await _db.clearTable();+ _emitUpdatedEvent();+ }++ void dismissBanner() {+ if (_tasks.isEmpty) {+ return;+ }+ _isBannerDismissedByUser = true;+ _showCompletionBanner = false;+ _emitUpdatedEvent();+ }++ void showBannerAfterAppReopen() {+ if (_tasks.isEmpty) {+ return;+ }+ if (_isBannerDismissedByUser) {+ _isBannerDismissedByUser = false;+ _emitUpdatedEvent();+ }+ }++ Future<void> dismissCompletionBanner() async {+ _completionCleanupTimer?.cancel();+ _showCompletionBanner = false;+ await _clearTerminalTasks();+ _emitUpdatedEvent();+ }++ Future<void> _loadTasksFromDB() async {+ final tasks = await _db.getAllTasks();+ final now = DateTime.now().microsecondsSinceEpoch;+ final staleCutoff = now - kStaleTaskDuration.inMicroseconds;+ final staleIDs = <int>[];++ for (var task in tasks) {+ if (!_isTerminal(task.status) && task.updatedAt < staleCutoff) {+ staleIDs.add(task.id);+ await _deletePartialFiles(task);+ continue;+ }+ if (task.status == DownloadStatus.downloading ||+ task.status == DownloadStatus.paused) {+ task = task.copyWith(+ status: DownloadStatus.pending,+ error: null,+ );+ }+ _tasks[task.id] = task;+ }++ if (staleIDs.isNotEmpty) {+ await _db.deleteTasks(staleIDs);+ }++ if (_tasks.isNotEmpty) {+ _isBannerDismissedByUser = false;+ }++ if (_tasks.isNotEmpty &&+ _tasks.values.every((task) => _isTerminal(task.status))) {+ await _clearTerminalTasks();+ }+ }++ void _listenToConnectivity() {+ _connectivitySubscription?.cancel();+ _connectivitySubscription =+ Connectivity().onConnectivityChanged.listen((results) {+ final hasConnection =+ results.any((result) => result != ConnectivityResult.none);+ if (!hasConnection) {+ return;+ }+ _resumePausedNetworkTasks().ignore();+ });+ }++ void _listenToLogout() {+ _logoutSubscription?.cancel();+ _logoutSubscription = Bus.instance.on<UserLoggedOutEvent>().listen((_) {+ cancelAll().ignore();+ });+ }++ Future<void> _resumePausedNetworkTasks() async {+ final pausedTasks = orderedTasks+ .where(+ (task) =>+ task.status == DownloadStatus.paused &&+ task.error == DownloadManager.noConnectionError,+ )+ .toList();+ if (pausedTasks.isEmpty) {+ return;+ }+ for (final task in pausedTasks) {+ await _updateTask(+ task.copyWith(status: DownloadStatus.pending, error: null),+ );+ }+ _isBannerDismissedByUser = false;+ _showCompletionBanner = false;+ Bus.instance.fire(GalleryDownloadsResumedEvent());+ _pollQueue();+ }++ void _pollQueue() {+ if (!_isInitialized) {+ return;+ }+ while (_activeDownloads.length < kMaximumConcurrentDownloads) {+ final nextTask = orderedTasks.firstWhereOrNull(+ (task) =>+ task.status == DownloadStatus.pending &&+ !_activeDownloads.contains(task.id),+ );+ if (nextTask == null) {+ break;+ }+ _startTask(nextTask);+ }+ _maybeShowCompletionState();+ _emitUpdatedEvent();+ }++ void _startTask(DownloadTask task) {+ _activeDownloads.add(task.id);+ _updateTask(+ task.copyWith(+ status: DownloadStatus.downloading,+ error: null,+ ),+ ).ignore();+ _watchSubscriptions[task.id]?.cancel();+ _watchSubscriptions[task.id] =+ downloadManager.watchDownload(task.id).listen(+ (downloadTask) {+ final existing = _tasks[task.id];+ if (existing == null) {+ return;+ }+ final updatedTask = existing.copyWith(+ bytesDownloaded: downloadTask.bytesDownloaded,+ filePath: downloadTask.filePath,+ );+ _updateTask(updatedTask).ignore();+ },+ );+ _runTask(task.id).ignore();+ }++ Future<void> _runTask(int fileID) async {+ try {+ await _downloadAndSaveToGallery(fileID);+ final task = _tasks[fileID];+ if (task != null) {+ await _updateTask(+ task.copyWith(+ status: DownloadStatus.completed,+ bytesDownloaded: task.totalBytes,+ error: null,+ ),+ );+ }+ } on DownloadNoConnectionError {+ await _setPausedState(fileID, DownloadManager.noConnectionError);+ } on DownloadNotEnoughStorageError {+ await _setPausedState(fileID, DownloadManager.notEnoughStorageError);+ } on DownloadUnavailableError {+ await _setErrorState(fileID, DownloadManager.unavailableError);+ } on DownloadFailedError catch (e) {+ await _setErrorState(fileID, e.message);+ } catch (e, s) {+ _logger.warning("Gallery download failed for fileID=$fileID", e, s);+ await _setErrorState(fileID, e.toString());+ } finally {+ _activeDownloads.remove(fileID);+ final subscription = _watchSubscriptions.remove(fileID);+ if (subscription != null) {+ await subscription.cancel();+ }+ _pollQueue();+ }+ }++ Future<void> _downloadAndSaveToGallery(int fileID) async {+ EnteFile? file = _queuedFilesByID[fileID];+ if (file == null) {+ final filesMap = await FilesDB.instance.getFileIDToFileFromIDs([fileID]);+ file = filesMap[fileID];+ }+ if (file == null) {+ throw DownloadUnavailableError();+ }+ file.fileSize ??= _tasks[fileID]?.totalBytes;+ final fileToDownload =+ file.isRemoteFile ? file.copyWith() : file.copyWith(localID: null);+ await downloadToGallery(+ fileToDownload,+ forceResumableDownload: true,+ );+ }++ Future<void> _setPausedState(int fileID, String reason) async {+ final task = _tasks[fileID];+ if (task == null) {+ return;+ }+ await _updateTask(+ task.copyWith(+ status: DownloadStatus.paused,+ error: reason,+ ),+ );+ _isBannerDismissedByUser = false;+ _showCompletionBanner = false;+ }++ Future<void> _setErrorState(int fileID, String reason) async {+ final task = _tasks[fileID];+ if (task == null) {+ return;+ }+ await _updateTask(+ task.copyWith(+ status: DownloadStatus.error,+ error: reason,+ ),+ );+ _isBannerDismissedByUser = false;+ _showCompletionBanner = false;+ }++ Future<void> _updateTask(DownloadTask task) async {+ _tasks[task.id] = task;+ await _db.upsertTask(task);+ _emitUpdatedEvent();+ }++ void _maybeShowCompletionState() {+ if (!_allTasksAreTerminal) {+ _completionCleanupTimer?.cancel();+ _showCompletionBanner = false;+ return;+ }+ if (_isBannerDismissedByUser) {+ _showCompletionBanner = false;+ _clearTerminalTasks().ignore();+ return;+ }+ if (completedCount == 0 && unavailableCount == 0) {+ _showCompletionBanner = false;+ _clearTerminalTasks().ignore();+ return;+ }+ if (_showCompletionBanner) {+ return;+ }+ _showCompletionBanner = true;+ _completionCleanupTimer?.cancel();+ _completionCleanupTimer = Timer(+ kCompletionBannerDuration,+ () => dismissCompletionBanner().ignore(),+ );+ }++ bool get _allTasksAreTerminal =>+ _tasks.isNotEmpty &&+ _tasks.values.every((task) => _isTerminal(task.status));++ bool _isTerminal(DownloadStatus status) =>+ status == DownloadStatus.completed ||+ status == DownloadStatus.error ||+ status == DownloadStatus.cancelled;++ Future<void> _clearTerminalTasks() async {+ final terminalIDs = _tasks.values+ .where((task) => _isTerminal(task.status))+ .map((task) => task.id)+ .toList(growable: false);+ if (terminalIDs.isEmpty) {+ return;+ }+ for (final id in terminalIDs) {+ _tasks.remove(id);+ _queuedFilesByID.remove(id);+ }+ await _db.deleteTasks(terminalIDs);+ _emitUpdatedEvent();+ }++ Future<void> _deletePartialFiles(DownloadTask task) async {+ try {+ final directory = Configuration.instance.getTempDirectory();+ final basePath = "$directory${task.id}.encrypted";+ final file = File(basePath);+ if (await file.exists()) {+ await file.delete();+ }+ final totalChunks =+ (task.totalBytes / DownloadManager.downloadChunkSize).ceil();+ for (int i = 1; i <= totalChunks; i++) {+ final chunk = File("$basePath.${i}_part");+ if (await chunk.exists()) {+ await chunk.delete();+ }+ }+ } catch (e) {+ _logger.warning("Failed to clean stale partial files for ${task.id}", e);+ }+ }++ void _emitUpdatedEvent() {+ Bus.instance.fire(GalleryDownloadsUpdatedEvent());+ }+}diff --git a/mobile/apps/photos/lib/module/download/manager.dart b/mobile/apps/photos/lib/module/download/manager.dartindex d46c278ba9..d6e310a801 100644--- a/mobile/apps/photos/lib/module/download/manager.dart+++ b/mobile/apps/photos/lib/module/download/manager.dart@@ -11,6 +11,9 @@ import "package:photos/module/download/task.dart";class DownloadManager {final _logger = Logger('DownloadManager');static const int downloadChunkSize = 40 * 1024 * 1024;+ static const String noConnectionError = 'NO_CONNECTION';+ static const String notEnoughStorageError = 'NOT_ENOUGH_STORAGE';+ static const String unavailableError = 'UNAVAILABLE';final Dio _dio;@@ -236,7 +239,15 @@ class DownloadManager {return;}_logger.warning('Error downloading ${task.filename}', e);- task = task.copyWith(status: DownloadStatus.error, error: e.toString());+ final isNetworkError = _isNetworkError(e);+ final isStorageError = _isStorageError(e);+ final String errorCode = _getErrorCode(e);+ task = task.copyWith(+ status: isNetworkError || isStorageError+ ? DownloadStatus.paused+ : DownloadStatus.error,+ error: errorCode,+ );_updateTask(task);if (!completer.isCompleted) {completer.complete(DownloadResult(task, false));@@ -414,4 +425,48 @@ class DownloadManager {_tasks.clear();}++ bool _isNetworkError(Object error) {+ if (error is DioException) {+ return error.type == DioExceptionType.connectionTimeout ||+ error.type == DioExceptionType.sendTimeout ||+ error.type == DioExceptionType.receiveTimeout ||+ error.type == DioExceptionType.connectionError ||+ error.type == DioExceptionType.unknown;+ }+ if (error is SocketException) {+ return true;+ }+ if (error is FileSystemException && error.message.contains('Connection')) {+ return true;+ }+ return false;+ }++ bool _isStorageError(Object error) {+ if (error is FileSystemException) {+ final code = error.osError?.errorCode;+ return code == 28 || code == 112;+ }+ if (error is DioException && error.error != null) {+ return _isStorageError(error.error!);+ }+ return false;+ }++ String _getErrorCode(Object error) {+ if (_isStorageError(error)) {+ return notEnoughStorageError;+ }+ if (_isNetworkError(error)) {+ return noConnectionError;+ }+ if (error is DioException) {+ final status = error.response?.statusCode;+ if (status == 404 || status == 410) {+ return unavailableError;+ }+ }+ return error.toString();+ }}diff --git a/mobile/apps/photos/lib/module/download/task.dart b/mobile/apps/photos/lib/module/download/task.dartindex 1bd96ca295..3c490370bc 100644--- a/mobile/apps/photos/lib/module/download/task.dart+++ b/mobile/apps/photos/lib/module/download/task.dart@@ -11,6 +11,8 @@ class DownloadTask {final int id;final String filename;final int totalBytes;+ final int createdAt;+ final int updatedAt;int bytesDownloaded;DownloadStatus status;String? error;@@ -20,11 +22,14 @@ class DownloadTask {required this.id,required this.filename,required this.totalBytes,+ int? createdAt,+ int? updatedAt,this.bytesDownloaded = 0,this.status = DownloadStatus.pending,this.error,this.filePath,- });+ }) : createdAt = createdAt ?? DateTime.now().microsecondsSinceEpoch,+ updatedAt = updatedAt ?? DateTime.now().microsecondsSinceEpoch;double get progress => totalBytes > 0 ? bytesDownloaded / totalBytes : 0.0;bool get isCompleted => status == DownloadStatus.completed;@@ -39,6 +44,8 @@ class DownloadTask {'id': id,'filename': filename,'totalBytes': totalBytes,+ 'createdAt': createdAt,+ 'updatedAt': updatedAt,'bytesDownloaded': bytesDownloaded,'status': status.name,'error': error,@@ -49,6 +56,8 @@ class DownloadTask {id: map['id'],filename: map['filename'],totalBytes: map['totalBytes'],+ createdAt: map['createdAt'],+ updatedAt: map['updatedAt'],bytesDownloaded: map['bytesDownloaded'] ?? 0,status: DownloadStatus.values.byName(map['status']),error: map['error'],@@ -56,6 +65,8 @@ class DownloadTask {);DownloadTask copyWith({+ int? createdAt,+ int? updatedAt,int? bytesDownloaded,DownloadStatus? status,String? error,@@ -65,6 +76,8 @@ class DownloadTask {id: id,filename: filename,totalBytes: totalBytes,+ createdAt: createdAt ?? this.createdAt,+ updatedAt: updatedAt ?? DateTime.now().microsecondsSinceEpoch,bytesDownloaded: bytesDownloaded ?? this.bytesDownloaded,status: status ?? this.status,error: error ?? this.error,diff --git a/mobile/apps/photos/lib/service_locator.dart b/mobile/apps/photos/lib/service_locator.dartindex c9df82dbc0..e2f46bc91f 100644--- a/mobile/apps/photos/lib/service_locator.dart+++ b/mobile/apps/photos/lib/service_locator.dart@@ -20,6 +20,7 @@ import "package:photos/gateways/social/social_gateway.dart";import "package:photos/gateways/trash/trash_gateway.dart";import "package:photos/gateways/users/passkey_gateway.dart";import "package:photos/gateways/users/users_gateway.dart";+import "package:photos/module/download/gallery_download_queue_service.dart";import "package:photos/module/download/manager.dart";import "package:photos/services/account/billing_service.dart";import "package:photos/services/backup_preference_service.dart";@@ -245,6 +246,12 @@ DownloadManager get downloadManager {return _downloadManager!;}+GalleryDownloadQueueService? _galleryDownloadQueueService;+GalleryDownloadQueueService get galleryDownloadQueueService {+ _galleryDownloadQueueService ??= GalleryDownloadQueueService.instance;+ return _galleryDownloadQueueService!;+}+SmartAlbumsService? _smartAlbumsService;SmartAlbumsService get smartAlbumsService {_smartAlbumsService ??= SmartAlbumsService();diff --git a/mobile/apps/photos/lib/ui/home/gallery_download_banner.dart b/mobile/apps/photos/lib/ui/home/gallery_download_banner.dartnew file mode 100644index 0000000000..bf1e798000--- /dev/null+++ b/mobile/apps/photos/lib/ui/home/gallery_download_banner.dart@@ -0,0 +1,453 @@+import "dart:async";++import "package:ente_pure_utils/ente_pure_utils.dart";+import "package:flutter/material.dart";+import "package:photos/core/event_bus.dart";+import "package:photos/events/gallery_downloads_events.dart";+import "package:photos/generated/l10n.dart";+import "package:photos/module/download/manager.dart";+import "package:photos/module/download/task.dart";+import "package:photos/service_locator.dart";+import "package:photos/services/app_lifecycle_service.dart";+import "package:photos/theme/ente_theme.dart";+import "package:photos/ui/components/buttons/button_widget.dart";+import "package:photos/ui/notification/toast.dart";+import "package:photos/utils/dialog_util.dart";++class GalleryDownloadBanner extends StatefulWidget {+ const GalleryDownloadBanner({super.key});++ @override+ State<GalleryDownloadBanner> createState() => _GalleryDownloadBannerState();+}++class _GalleryDownloadBannerState extends State<GalleryDownloadBanner>+ with WidgetsBindingObserver {+ static const Duration _appReopenThreshold = Duration(seconds: 20);+ StreamSubscription<GalleryDownloadsUpdatedEvent>? _updatedSubscription;+ StreamSubscription<GalleryDownloadsResumedEvent>? _resumedSubscription;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ galleryDownloadQueueService.init().ignore();+ _updatedSubscription =+ Bus.instance.on<GalleryDownloadsUpdatedEvent>().listen((_) {+ if (mounted) {+ setState(() {});+ }+ });+ _resumedSubscription =+ Bus.instance.on<GalleryDownloadsResumedEvent>().listen((_) {+ if (mounted) {+ showToast(context, "Connection restored - resuming downloads");+ }+ });+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ _updatedSubscription?.cancel();+ _resumedSubscription?.cancel();+ super.dispose();+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ if (state != AppLifecycleState.resumed) {+ return;+ }+ final lastBackgroundTime =+ AppLifecycleService.instance.getLastAppOpenTime();+ if (lastBackgroundTime <= 0) {+ return;+ }+ final elapsed = DateTime.now().microsecondsSinceEpoch - lastBackgroundTime;+ if (elapsed >= _appReopenThreshold.inMicroseconds) {+ galleryDownloadQueueService.showBannerAfterAppReopen();+ }+ }++ @override+ Widget build(BuildContext context) {+ final service = galleryDownloadQueueService;+ if (!service.isBannerVisible || service.orderedTasks.isEmpty) {+ return const SizedBox.shrink();+ }++ final colorScheme = getEnteColorScheme(context);+ final textTheme = getEnteTextTheme(context);+ final isErrorState = service.hasPausedDueToNoConnection ||+ service.hasPausedDueToStorage ||+ service.hasNonUnavailableErrors;++ return Padding(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),+ child: Material(+ color: colorScheme.backgroundElevated2,+ borderRadius: const BorderRadius.all(Radius.circular(12)),+ child: InkWell(+ borderRadius: const BorderRadius.all(Radius.circular(12)),+ onTap: _openDetailsSheet,+ child: Padding(+ padding: const EdgeInsets.all(12),+ child: Row(+ children: [+ Icon(+ Icons.cloud_download_outlined,+ color: isErrorState+ ? colorScheme.warning500+ : colorScheme.primary500,+ ),+ const SizedBox(width: 10),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ _bannerMessage(context),+ style: textTheme.smallBold,+ ),+ if (!service.isCompletionBannerVisible) ...[+ const SizedBox(height: 8),+ ClipRRect(+ borderRadius:+ const BorderRadius.all(Radius.circular(2)),+ child: LinearProgressIndicator(+ value: service.overallProgress,+ minHeight: 4,+ color: isErrorState+ ? colorScheme.warning500+ : colorScheme.primary500,+ backgroundColor: colorScheme.fillMuted,+ ),+ ),+ ],+ ],+ ),+ ),+ const SizedBox(width: 8),+ if (service.isCompletionBannerVisible)+ TextButton(+ onPressed: () {+ service.dismissCompletionBanner().ignore();+ },+ child: Text(AppLocalizations.of(context).dismiss),+ )+ else+ IconButton(+ onPressed: service.dismissBanner,+ icon: const Icon(Icons.close),+ iconSize: 18,+ visualDensity: VisualDensity.compact,+ color: colorScheme.strokeBase,+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }++ String _bannerMessage(BuildContext context) {+ final l10n = AppLocalizations.of(context);+ final service = galleryDownloadQueueService;++ if (service.isCompletionBannerVisible) {+ if (service.unavailableCount > 0) {+ return "${service.completedCount} of ${service.totalCount} saved - "+ "${service.unavailableCount} unavailable";+ }+ if (service.completedCount == 1) {+ return l10n.fileSavedToGallery;+ }+ return "${service.completedCount} files saved to gallery";+ }++ if (service.hasPausedDueToStorage) {+ return "Download paused - Not enough storage";+ }+ if (service.hasPausedDueToNoConnection) {+ return "Download paused - No connection";+ }+ if (service.hasNonUnavailableErrors) {+ return l10n.downloadFailed;+ }++ final current =+ (service.completedCount + (service.downloadingCount > 0 ? 1 : 0))+ .clamp(0, service.totalCount);+ return "Downloading $current of ${service.totalCount}";+ }++ Future<void> _openDetailsSheet() async {+ await showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ useRootNavigator: false,+ backgroundColor: getEnteColorScheme(context).backgroundElevated,+ shape: const RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(16)),+ ),+ builder: (_) => const _DownloadsDetailSheet(),+ );+ }+}++class _DownloadsDetailSheet extends StatefulWidget {+ const _DownloadsDetailSheet();++ @override+ State<_DownloadsDetailSheet> createState() => _DownloadsDetailSheetState();+}++class _DownloadsDetailSheetState extends State<_DownloadsDetailSheet> {+ StreamSubscription<GalleryDownloadsUpdatedEvent>? _updatedSubscription;++ @override+ void initState() {+ super.initState();+ _updatedSubscription =+ Bus.instance.on<GalleryDownloadsUpdatedEvent>().listen((_) {+ if (mounted) {+ setState(() {});+ }+ });+ }++ @override+ void dispose() {+ _updatedSubscription?.cancel();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final service = galleryDownloadQueueService;+ final tasks = service.orderedTasks;+ final colorScheme = getEnteColorScheme(context);+ final textTheme = getEnteTextTheme(context);+ final hasCancelableTasks = tasks.any(+ (task) =>+ task.status == DownloadStatus.pending ||+ task.status == DownloadStatus.downloading ||+ task.status == DownloadStatus.paused,+ );++ return SafeArea(+ child: Padding(+ padding: EdgeInsets.fromLTRB(+ 16,+ 12,+ 16,+ 16 + MediaQuery.of(context).viewInsets.bottom,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Container(+ width: 40,+ height: 4,+ decoration: BoxDecoration(+ color: colorScheme.strokeMuted,+ borderRadius: const BorderRadius.all(Radius.circular(2)),+ ),+ ),+ const SizedBox(height: 12),+ Row(+ children: [+ Text(+ "Downloads",+ style: textTheme.h3Bold,+ ),+ const Spacer(),+ if (hasCancelableTasks)+ TextButton(+ onPressed: _confirmCancelAll,+ child: const Text("Cancel all"),+ ),+ ],+ ),+ const SizedBox(height: 8),+ if (tasks.isEmpty)+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 24),+ child: Text(+ "No downloads",+ style: textTheme.smallMuted,+ ),+ )+ else+ Flexible(+ child: ConstrainedBox(+ constraints: BoxConstraints(+ maxHeight: MediaQuery.of(context).size.height * 0.6,+ ),+ child: ListView.separated(+ shrinkWrap: true,+ itemCount: tasks.length,+ separatorBuilder: (_, __) => Divider(+ height: 1,+ color: colorScheme.strokeFaint,+ ),+ itemBuilder: (context, index) {+ final task = tasks[index];+ return _DownloadTaskRow(task: task);+ },+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }++ Future<void> _confirmCancelAll() async {+ final result = await showChoiceActionSheet(+ context,+ title: "Cancel all downloads?",+ body: "Queued and in-progress downloads will be cancelled.",+ firstButtonLabel: "Cancel all",+ isCritical: true,+ );+ if (!mounted) {+ return;+ }+ if (result?.action == ButtonAction.first) {+ await galleryDownloadQueueService.cancelAll();+ if (mounted) {+ Navigator.of(context).pop();+ }+ }+ }+}++class _DownloadTaskRow extends StatelessWidget {+ const _DownloadTaskRow({required this.task});++ final DownloadTask task;++ @override+ Widget build(BuildContext context) {+ final colorScheme = getEnteColorScheme(context);+ final textTheme = getEnteTextTheme(context);+ final canCancel = task.status == DownloadStatus.pending ||+ task.status == DownloadStatus.downloading ||+ task.status == DownloadStatus.paused;++ return Padding(+ padding: const EdgeInsets.symmetric(vertical: 10),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ task.filename,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: textTheme.body,+ ),+ const SizedBox(height: 4),+ _TaskStatus(task: task),+ ],+ ),+ ),+ if (canCancel)+ IconButton(+ onPressed: () =>+ galleryDownloadQueueService.cancelTask(task.id).ignore(),+ icon: const Icon(Icons.close),+ iconSize: 18,+ visualDensity: VisualDensity.compact,+ color: colorScheme.strokeMuted,+ ),+ ],+ ),+ );+ }+}++class _TaskStatus extends StatelessWidget {+ const _TaskStatus({required this.task});++ final DownloadTask task;++ @override+ Widget build(BuildContext context) {+ final colorScheme = getEnteColorScheme(context);+ final textTheme = getEnteTextTheme(context);+ switch (task.status) {+ case DownloadStatus.completed:+ return Row(+ children: [+ Icon(+ Icons.check_circle,+ size: 14,+ color: colorScheme.primary500,+ ),+ const SizedBox(width: 6),+ Text(+ "Saved",+ style: textTheme.mini.copyWith(color: colorScheme.primary500),+ ),+ ],+ );+ case DownloadStatus.downloading:+ final progress = task.progress.clamp(0.0, 1.0);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ ClipRRect(+ borderRadius: const BorderRadius.all(Radius.circular(2)),+ child: LinearProgressIndicator(+ value: progress,+ minHeight: 4,+ backgroundColor: colorScheme.fillMuted,+ color: colorScheme.primary500,+ ),+ ),+ const SizedBox(height: 4),+ Text(+ "${(progress * 100).toStringAsFixed(0)}%",+ style: textTheme.miniMuted,+ ),+ ],+ );+ case DownloadStatus.pending:+ return Text(+ "${AppLocalizations.of(context).queued} β’ ${formatBytes(task.totalBytes)}",+ style: textTheme.miniMuted,+ );+ case DownloadStatus.paused:+ case DownloadStatus.error:+ case DownloadStatus.cancelled:+ return Text(+ _errorMessage(task.error),+ style: textTheme.mini.copyWith(color: colorScheme.warning500),+ );+ }+ }++ String _errorMessage(String? error) {+ if (error == DownloadManager.noConnectionError) {+ return "No connection";+ }+ if (error == DownloadManager.notEnoughStorageError) {+ return "Not enough storage";+ }+ if (error == DownloadManager.unavailableError) {+ return "Unavailable";+ }+ if (error == null || error.isEmpty) {+ return "Download failed";+ }+ return error;+ }+}diff --git a/mobile/apps/photos/lib/ui/tabs/home_widget.dart b/mobile/apps/photos/lib/ui/tabs/home_widget.dartindex deb16374a7..19054c0e07 100644--- a/mobile/apps/photos/lib/ui/tabs/home_widget.dart+++ b/mobile/apps/photos/lib/ui/tabs/home_widget.dart@@ -61,6 +61,7 @@ import "package:photos/ui/extents_page_view.dart";import "package:photos/ui/home/christmas/christmas_pull_animation.dart";import "package:photos/ui/home/christmas/christmas_utils.dart";import "package:photos/ui/home/christmas/snow_fall_overlay.dart";+import "package:photos/ui/home/gallery_download_banner.dart";import "package:photos/ui/home/grant_permissions_widget.dart";import "package:photos/ui/home/header_widget.dart";import "package:photos/ui/home/home_bottom_nav_bar.dart";@@ -977,10 +978,16 @@ class _HomeWidgetState extends State<HomeWidget> {child: ValueListenableBuilder(valueListenable: isOnSearchTabNotifier,builder: (context, value, child) {- return HomeBottomNavigationBar(- _selectedFiles,- _selectedAlbums,- selectedTabIndex: _selectedTabIndex,+ return Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (flagService.internalUser) const GalleryDownloadBanner(),+ HomeBottomNavigationBar(+ _selectedFiles,+ _selectedAlbums,+ selectedTabIndex: _selectedTabIndex,+ ),+ ],);},),diff --git a/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart b/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dartindex 53aee77792..212219c276 100644--- a/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart+++ b/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart@@ -1125,45 +1125,59 @@ class _FileSelectionActionsWidgetState);}final skippedFilesCount = skippedFiles.length;+ int addedToQueueCount = 0;if (filesToDownload.isNotEmpty) {- final totalFiles = filesToDownload.length;- int downloadedFiles = 0;-- final dialog = createProgressDialog(- context,- AppLocalizations.of(context).downloading +- " ($downloadedFiles/$totalFiles)",- isDismissible: true,- );- await dialog.show();- try {- final taskQueue = SimpleTaskQueue(maxConcurrent: 5);- final futures = <Future>[];- for (final file in filesToDownload) {- futures.add(- taskQueue.add(() async {- await downloadToGallery(file);- downloadedFiles++;- dialog.update(- message: AppLocalizations.of(context).downloading +- " ($downloadedFiles/$totalFiles)",- );- }),- );+ if (flagService.internalUser) {+ try {+ final enqueueResult =+ await galleryDownloadQueueService.enqueueFiles(filesToDownload);+ addedToQueueCount = enqueueResult.addedCount;+ } catch (e) {+ _logger.warning("Failed to enqueue files for download", e);+ await showGenericErrorDialog(context: context, error: e);+ return;+ }+ } else {+ final totalFiles = filesToDownload.length;+ int downloadedFiles = 0;++ final dialog = createProgressDialog(+ context,+ AppLocalizations.of(context).downloading ++ " ($downloadedFiles/$totalFiles)",+ isDismissible: true,+ );+ await dialog.show();+ try {+ final taskQueue = SimpleTaskQueue(maxConcurrent: 5);+ final futures = <Future>[];+ for (final file in filesToDownload) {+ futures.add(+ taskQueue.add(() async {+ await downloadToGallery(file);+ downloadedFiles++;+ dialog.update(+ message: AppLocalizations.of(context).downloading ++ " ($downloadedFiles/$totalFiles)",+ );+ }),+ );+ }+ await Future.wait(futures);+ addedToQueueCount = downloadedFiles;+ await dialog.hide();+ } catch (e) {+ _logger.warning("Failed to save files", e);+ await dialog.hide();+ await showGenericErrorDialog(context: context, error: e);+ return;}- await Future.wait(futures);- await dialog.hide();- } catch (e) {- _logger.warning("Failed to save files", e);- await dialog.hide();- await showGenericErrorDialog(context: context, error: e);- return;}}- String finalMessage;if (skippedFilesCount > 0) {+ String finalMessage;if (skippedFilesCount == 1) {final skippedFile = skippedFiles.first;finalMessage = l10n.downloadSkippedInSelectionSingleFile(@@ -1175,15 +1189,26 @@ class _FileSelectionActionsWidgetStatefileCount: skippedFilesCount,);}- } else {- finalMessage = AppLocalizations.of(context).filesSavedToGallery;+ showToast(+ context,+ finalMessage,+ iosLongToastLengthInSec: 4,+ );}- showToast(- context,- finalMessage,- iosLongToastLengthInSec: 4,- );+ if (!flagService.internalUser &&+ skippedFilesCount == 0 &&+ addedToQueueCount > 0) {+ showToast(+ context,+ AppLocalizations.of(context).filesSavedToGallery,+ iosLongToastLengthInSec: 4,+ );+ }++ if (addedToQueueCount == 0 && skippedFilesCount == 0) {+ return;+ }if (skippedFilesCount == 0) {widget.selectedFiles.clearAll();diff --git a/mobile/apps/photos/lib/ui/viewer/file/file_app_bar.dart b/mobile/apps/photos/lib/ui/viewer/file/file_app_bar.dartindex 6d6c6b68bb..e37d39228a 100644--- a/mobile/apps/photos/lib/ui/viewer/file/file_app_bar.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/file_app_bar.dart@@ -12,7 +12,6 @@ import "package:photos/core/configuration.dart";import "package:photos/core/event_bus.dart";import "package:photos/events/guest_view_event.dart";import "package:photos/generated/l10n.dart";-import "package:photos/l10n/l10n.dart";import "package:photos/models/collection/collection.dart";import "package:photos/models/file/extensions/file_props.dart";import 'package:photos/models/file/file.dart';@@ -637,9 +636,19 @@ class FileAppBarState extends State<FileAppBar> {final fileToDownload =!file.isRemoteFile ? file.copyWith(localID: null) : file;+ if (flagService.internalUser) {+ try {+ await galleryDownloadQueueService.enqueueFiles([fileToDownload]);+ } catch (e) {+ _logger.warning("Failed to save file", e);+ await showGenericErrorDialog(context: context, error: e);+ }+ return;+ }+final dialog = createProgressDialog(context,- context.l10n.downloading,+ AppLocalizations.of(context).downloading,isDismissible: true,);await dialog.show();diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/gallery_app_bar_widget.dart b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_app_bar_widget.dartindex c6839a013c..9418401bcf 100644--- a/mobile/apps/photos/lib/ui/viewer/gallery/gallery_app_bar_widget.dart+++ b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_app_bar_widget.dart@@ -785,6 +785,16 @@ class _GalleryAppBarWidgetState extends State<GalleryAppBarWidget> {if (files == null || files.isEmpty) {return;}+ if (flagService.internalUser) {+ try {+ await galleryDownloadQueueService.enqueueFiles(files);+ } catch (e, s) {+ _logger.severe("Failed to download album", e, s);+ await showGenericErrorDialog(context: context, error: e);+ }+ return;+ }+final totalFiles = files.length;final dialog = createProgressDialog(context,diff --git a/mobile/apps/photos/lib/utils/file_download_util.dart b/mobile/apps/photos/lib/utils/file_download_util.dartindex 34e91179b4..b33fa8b44b 100644--- a/mobile/apps/photos/lib/utils/file_download_util.dart+++ b/mobile/apps/photos/lib/utils/file_download_util.dart@@ -18,6 +18,7 @@ import 'package:photos/models/file/file.dart';import "package:photos/models/file/file_type.dart";import "package:photos/models/ignored_file.dart";import "package:photos/module/download/file_url.dart";+import "package:photos/module/download/manager.dart";import "package:photos/module/download/task.dart";import "package:photos/service_locator.dart";import "package:photos/services/collections_service.dart";@@ -28,6 +29,27 @@ import "package:photos/utils/file_util.dart";final _logger = Logger("file_download_util");+class DownloadFailedError implements Exception {+ final String message;++ DownloadFailedError(this.message);++ @override+ String toString() => message;+}++class DownloadNoConnectionError extends DownloadFailedError {+ DownloadNoConnectionError() : super("No connection");+}++class DownloadNotEnoughStorageError extends DownloadFailedError {+ DownloadNotEnoughStorageError() : super("Not enough storage");+}++class DownloadUnavailableError extends DownloadFailedError {+ DownloadUnavailableError() : super("Unavailable");+}+/// Use this instead of `file.displayName` directly for skip toasts.////// Rationale:@@ -127,6 +149,8 @@ Future<File?> downloadAndDecryptPublicFile(Future<File?> downloadAndDecrypt(EnteFile file, {ProgressCallback? progressCallback,+ bool forceResumableDownload = false,+ bool throwOnFailure = false,}) async {if (CollectionsService.instance.isSharedPublicLink(file.collectionID!)) {return await downloadAndDecryptPublicFile(@@ -145,7 +169,8 @@ Future<File?> downloadAndDecrypt(final startTime = DateTime.now().millisecondsSinceEpoch;try {- if (downloadManager.enableResumableDownload(file.fileSize)) {+ if (forceResumableDownload ||+ downloadManager.enableResumableDownload(file.fileSize)) {final DownloadResult result = await downloadManager.download(file.uploadedFileID!,file.displayName,@@ -158,6 +183,9 @@ Future<File?> downloadAndDecrypt(_logger.warning('$logPrefix download failed ${result.task.error} ${result.task.status}',);+ if (throwOnFailure) {+ throw _toDownloadFailure(result.task.error);+ }return null;}} else {@@ -179,6 +207,9 @@ Future<File?> downloadAndDecrypt();if (response.statusCode != 200 || !encryptedFile.existsSync()) {_logger.warning('$logPrefix download failed ${response.toString()}');+ if (throwOnFailure) {+ throw DownloadFailedError(response.toString());+ }return null;}}@@ -220,16 +251,52 @@ Future<File?> downloadAndDecrypt(final metadata =await _getFileMetadataForLogging(file, encryptedFilePath);_logger.severe("Critical: $logPrefix failed to decrypt, $metadata", e, s);+ if (throwOnFailure) {+ throw DownloadFailedError("Failed to decrypt downloaded file");+ }return null;}await encryptedFile.delete();return File(decryptedFilePath);} catch (e, s) {_logger.severe("$logPrefix failed to download or decrypt", e, s);+ if (throwOnFailure) {+ if (e is DownloadFailedError) {+ rethrow;+ }+ if (_isStorageError(e)) {+ throw DownloadNotEnoughStorageError();+ }+ throw DownloadFailedError(e.toString());+ }return null;}}+DownloadFailedError _toDownloadFailure(String? error) {+ if (error == DownloadManager.noConnectionError) {+ return DownloadNoConnectionError();+ }+ if (error == DownloadManager.notEnoughStorageError) {+ return DownloadNotEnoughStorageError();+ }+ if (error == DownloadManager.unavailableError) {+ return DownloadUnavailableError();+ }+ return DownloadFailedError(error ?? "Download failed");+}++bool _isStorageError(Object error) {+ if (error is FileSystemException) {+ final code = error.osError?.errorCode;+ return code == 28 || code == 112;+ }+ if (error is DioException && error.error != null) {+ return _isStorageError(error.error!);+ }+ return false;+}+Future<String> _getFileMetadataForLogging(EnteFile file,String encFilePath,@@ -248,13 +315,22 @@ Future<String> _getFileMetadataForLogging(return buffer.toString();}-Future<void> downloadToGallery(EnteFile file) async {+Future<void> downloadToGallery(+ EnteFile file, {+ bool forceResumableDownload = false,+}) async {try {final FileType type = file.fileType;final bool downloadLivePhotoOnDroid =type == FileType.livePhoto && Platform.isAndroid;AssetEntity? savedAsset;- final File? fileToSave = await getFile(file);+ final File? fileToSave = await getFile(+ file,+ forGalleryDownload: forceResumableDownload,+ );+ if (fileToSave == null) {+ throw DownloadFailedError("Unable to fetch file for gallery download");+ }// We use a lock to prevent synchronisation to occur while it is downloading// as this introduces wrong entry in FilesDB due to race condition// This is a fix for https://github.com/ente-io/ente/issues/4296@@ -264,21 +340,24 @@ Future<void> downloadToGallery(EnteFile file) async {await PhotoManager.stopChangeNotify();if (type == FileType.image) {savedAsset = await PhotoManager.editor- .saveImageWithPath(fileToSave!.path, title: file.title!);+ .saveImageWithPath(fileToSave.path, title: file.title!);} else if (type == FileType.video) {- savedAsset = await PhotoManager.editor- .saveVideo(fileToSave!, title: file.title!);+ savedAsset =+ await PhotoManager.editor.saveVideo(fileToSave, title: file.title!);} else if (type == FileType.livePhoto) {- final File? liveVideoFile =- await getFileFromServer(file, liveVideo: true);+ final File? liveVideoFile = await getFileFromServer(+ file,+ liveVideo: true,+ forGalleryDownload: forceResumableDownload,+ );if (liveVideoFile == null) {throw AssertionError("Live video can not be null");}if (downloadLivePhotoOnDroid) {- await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);+ await _saveLivePhotoOnDroid(fileToSave, liveVideoFile, file);} else {savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(- imageFile: fileToSave!,+ imageFile: fileToSave,videoFile: liveVideoFile,title: file.title!,);@@ -299,6 +378,10 @@ Future<void> downloadToGallery(EnteFile file) async {}});} catch (e) {+ if (forceResumableDownload && _isStorageError(e)) {+ _logger.severe("Failed to save file due to storage limit", e);+ throw DownloadNotEnoughStorageError();+ }_logger.severe("Failed to save file", e);rethrow;} finally {diff --git a/mobile/apps/photos/lib/utils/file_util.dart b/mobile/apps/photos/lib/utils/file_util.dartindex 4831a923f9..0b77733713 100644--- a/mobile/apps/photos/lib/utils/file_util.dart+++ b/mobile/apps/photos/lib/utils/file_util.dart@@ -36,11 +36,16 @@ Future<File?> getFile(EnteFile file, {bool liveVideo = false,bool isOrigin = false,+ bool forGalleryDownload = false,} // only relevant for live photos) async {try {if (file.isRemoteFile) {- return getFileFromServer(file, liveVideo: liveVideo);+ return getFileFromServer(+ file,+ liveVideo: liveVideo,+ forGalleryDownload: forGalleryDownload,+ );} else {final String key = file.tag + liveVideo.toString() + isOrigin.toString();final cachedFile = FileLruCache.get(key);@@ -61,6 +66,9 @@ Future<File?> getFile(}} catch (e, s) {_logger.warning("Failed to get file", e, s);+ if (forGalleryDownload) {+ rethrow;+ }return null;}}@@ -134,6 +142,7 @@ Future<File?> getFileFromServer(EnteFile file, {ProgressCallback? progressCallback,bool liveVideo = false, // only needed in case of live photos+ bool forGalleryDownload = false,}) async {final cacheManager = (file.fileType == FileType.video || liveVideo)? VideoCacheManager.instance@@ -160,6 +169,7 @@ Future<File?> getFileFromServer(_progressCallbacks[downloadID]?.call(count, total);},needLiveVideo: liveVideo,+ forGalleryDownload: forGalleryDownload,);} else {downloadFuture = _downloadAndCache(@@ -168,12 +178,20 @@ Future<File?> getFileFromServer(progressCallback: (count, total) {_progressCallbacks[downloadID]?.call(count, total);},+ forGalleryDownload: forGalleryDownload,);}// ignore: unawaited_futures- downloadFuture.then((downloadedFile) async {- completer.complete(downloadedFile);- await _fileDownloadsInProgress.remove(downloadID);+ downloadFuture.then((downloadedFile) {+ if (!completer.isCompleted) {+ completer.complete(downloadedFile);+ }+ }).catchError((error, stackTrace) {+ if (!completer.isCompleted) {+ completer.completeError(error, stackTrace);+ }+ }).whenComplete(() {+ _fileDownloadsInProgress.remove(downloadID);_progressCallbacks.remove(downloadID);});}@@ -195,12 +213,16 @@ Future<File?> _getLivePhotoFromServer(EnteFile file, {ProgressCallback? progressCallback,required bool needLiveVideo,+ bool forGalleryDownload = false,}) async {final downloadID = file.uploadedFileID!;try {if (!_livePhotoDownloadsTracker.containsKey(downloadID)) {- _livePhotoDownloadsTracker[downloadID] =- _downloadLivePhoto(file, progressCallback: progressCallback);+ _livePhotoDownloadsTracker[downloadID] = _downloadLivePhoto(+ file,+ progressCallback: progressCallback,+ forGalleryDownload: forGalleryDownload,+ );}final livePhoto = await _livePhotoDownloadsTracker[file.uploadedFileID];await _livePhotoDownloadsTracker.remove(downloadID);@@ -211,6 +233,9 @@ Future<File?> _getLivePhotoFromServer(} catch (e, s) {_logger.warning("live photo get failed", e, s);await _livePhotoDownloadsTracker.remove(downloadID);+ if (forGalleryDownload) {+ rethrow;+ }return null;}}@@ -218,9 +243,14 @@ Future<File?> _getLivePhotoFromServer(Future<_LivePhoto?> _downloadLivePhoto(EnteFile file, {ProgressCallback? progressCallback,+ bool forGalleryDownload = false,}) async {- return downloadAndDecrypt(file, progressCallback: progressCallback)- .then((decryptedFile) async {+ return downloadAndDecrypt(+ file,+ progressCallback: progressCallback,+ forceResumableDownload: forGalleryDownload,+ throwOnFailure: forGalleryDownload,+ ).then((decryptedFile) async {if (decryptedFile == null) {return null;}@@ -298,9 +328,14 @@ Future<File?> _downloadAndCache(EnteFile file,BaseCacheManager cacheManager, {required ProgressCallback progressCallback,+ bool forGalleryDownload = false,}) async {- return downloadAndDecrypt(file, progressCallback: progressCallback)- .then((decryptedFile) async {+ return downloadAndDecrypt(+ file,+ progressCallback: progressCallback,+ forceResumableDownload: forGalleryDownload,+ throwOnFailure: forGalleryDownload,+ ).then((decryptedFile) async {if (decryptedFile == null) {return null;}