π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Download by individual chunks
Neeraj Gupta8bc701d10456
diff --git a/mobile/lib/module/download/db.dart b/mobile/lib/module/download/db.dartnew file mode 100644index 0000000000..097322ba0a--- /dev/null+++ b/mobile/lib/module/download/db.dart@@ -0,0 +1,61 @@+import "package:path/path.dart";+import "package:photos/module/download/task.dart";+import "package:sqflite/sqflite.dart";++class DatabaseHelper {+ static final _instance = DatabaseHelper._internal();+ static Database? _database;++ factory DatabaseHelper() => _instance;+ DatabaseHelper._internal();++ Future<Database> get database async {+ _database ??= await _initDatabase();+ return _database!;+ }++ Future<Database> _initDatabase() async {+ final path = join(await getDatabasesPath(), 'download_manager.db');++ return await openDatabase(+ path,+ version: 1,+ onCreate: (db, version) async {+ await db.execute('''+ CREATE TABLE downloads (+ id INTEGER PRIMARY KEY,+ filename TEXT NOT NULL,+ totalBytes INTEGER NOT NULL,+ bytesDownloaded INTEGER DEFAULT 0,+ status TEXT NOT NULL,+ error TEXT,+ filePath TEXT+ )+ ''');+ },+ );+ }++ Future<void> save(DownloadTask task) async {+ final db = await database;+ await db.insert('downloads', task.toMap(),+ conflictAlgorithm: ConflictAlgorithm.replace);+ }++ Future<DownloadTask?> get(int id) async {+ final db = await database;+ final maps = await db.query('downloads', where: 'id = ?', whereArgs: [id]);+ return maps.isNotEmpty ? DownloadTask.fromMap(maps.first) : null;+ }++ Future<List<DownloadTask>> getAll() async {+ final db = await database;+ final maps = await db.query('downloads');+ return maps.map(DownloadTask.fromMap).toList();+ }++ Future<void> delete(int id) async {+ final db = await database;+ await db.delete('downloads', where: 'id = ?', whereArgs: [id]);+ }+}diff --git a/mobile/lib/module/download/file_url.dart b/mobile/lib/module/download/file_url.dartindex eed4398cec..e5faced127 100644--- a/mobile/lib/module/download/file_url.dart+++ b/mobile/lib/module/download/file_url.dart@@ -7,6 +7,7 @@ enum FileUrlType {publicDownload,thumbnail,publicThumbnail,+ directDownload,}class FileUrl {@@ -16,6 +17,8 @@ class FileUrl {endpoint != kDefaultProductionEndpoint || flagService.disableCFWorker;switch (type) {+ case FileUrlType.directDownload:+ return "$endpoint/files/download/$fileID";case FileUrlType.download:return disableWorker? "$endpoint/files/download/$fileID"diff --git a/mobile/lib/module/download/resumable.dart b/mobile/lib/module/download/resumable.dartindex 8de0e53479..c95d46b2f4 100644--- a/mobile/lib/module/download/resumable.dart+++ b/mobile/lib/module/download/resumable.dart@@ -1,325 +1,311 @@import "dart:async";-import 'dart:io';-import 'package:dio/dio.dart';-import 'package:path/path.dart';-import 'package:path_provider/path_provider.dart';+import "dart:io";++import "package:dio/dio.dart";+import "package:logging/logging.dart";+import "package:photos/core/configuration.dart";++import 'package:photos/module/download/db.dart';import "package:photos/module/download/file_url.dart";import "package:photos/module/download/task.dart";-import 'package:sqflite/sqflite.dart';-class DatabaseHelper {- static final DatabaseHelper _instance = DatabaseHelper._internal();- static Database? _database;-- factory DatabaseHelper() => _instance;+class DownloadManager {+ static const int _chunkSize = 50 * 1024 * 1024;- DatabaseHelper._internal();+ final _db = DatabaseHelper();+ final _dio = Dio();+ final _logger = Logger('DownloadManager');- Future<Database> get database async {- if (_database != null) return _database!;- _database = await _initDatabase();- return _database!;- }+ // Active downloads with their completers and streams+ final Map<int, Completer<DownloadResult>> _completers = {};+ final Map<int, StreamController<DownloadTask>> _streams = {};+ final Map<int, CancelToken> _cancelTokens = {};- Future<Database> _initDatabase() async {- final String path = join(await getDatabasesPath(), 'download_manager.db');- return await openDatabase(- path,- version: 1,- onCreate: (Database db, int version) async {- await db.execute('''- CREATE TABLE downloads (- id INTEGER PRIMARY KEY,- url TEXT,- filename TEXT,- bytesDownloaded INTEGER,- totalBytes INTEGER,- status TEXT,- error TEXT- )- ''');- },- );+ /// Subscribe to download progress updates for a specific file ID+ Stream<DownloadTask> watchDownload(int fileId) {+ _streams[fileId] ??= StreamController<DownloadTask>.broadcast();+ return _streams[fileId]!.stream;}- Future<int> insertDownload(DownloadTask task) async {- final db = await database;- return await db.insert('downloads', task.toMap());- }+ /// Start download and return a Future that completes when download finishes+ Future<DownloadResult> download(+ int fileId,+ String filename,+ int totalBytes,+ ) async {+ // If already downloading, return existing future+ if (_completers.containsKey(fileId)) {+ return _completers[fileId]!.future;+ }- Future<int> updateDownload(DownloadTask task) async {- final db = await database;- return await db.update(- 'downloads',- task.toMap(),- where: 'id = ?',- whereArgs: [task.id],- );- }+ final completer = Completer<DownloadResult>();+ _completers[fileId] = completer;++ // Get or create task+ final task = await _db.get(fileId) ??+ DownloadTask(+ id: fileId,+ filename: filename,+ totalBytes: totalBytes,+ );++ // Don't restart if already completed+ if (task.isCompleted) {+ final result = DownloadResult(task, true);+ completer.complete(result);+ return result;+ }- Future<List<DownloadTask>> getDownloads() async {- final db = await database;- final List<Map<String, dynamic>> maps = await db.query('downloads');- return List.generate(maps.length, (i) {- return DownloadTask.fromMap(maps[i]);- });+ unawaited(_startDownload(task, completer));+ return completer.future;}- Future<DownloadTask?> getDownload(int id) async {- final db = await database;- final List<Map<String, dynamic>> maps = await db.query(- 'downloads',- where: 'id = ?',- whereArgs: [id],- );- if (maps.isNotEmpty) {- return DownloadTask.fromMap(maps.first);+ /// Pause download+ Future<void> pause(int fileId) async {+ final token = _cancelTokens[fileId];+ if (token != null && !token.isCancelled) {+ token.cancel('paused');}- return null;- }- Future<int> deleteDownload(int id) async {- final db = await database;- return await db.delete(- 'downloads',- where: 'id = ?',- whereArgs: [id],- );+ final task = await _db.get(fileId);+ if (task != null && task.isActive) {+ await _updateTask(task.copyWith(status: DownloadStatus.paused));+ }}-}--class DownloadManager {- final DatabaseHelper _dbHelper = DatabaseHelper();- final Map<int, StreamController<DownloadTask>> _progressControllers = {};- final Map<int, CancelToken> _cancelTokens = {};- final Dio _dio = Dio();- DownloadManager();+ /// Cancel and delete download+ Future<void> cancel(int fileId) async {+ await pause(fileId);- // Stream for subscribers to listen for download updates- Stream<DownloadTask> getDownloadProgress(int taskId) {- if (!_progressControllers.containsKey(taskId)) {- _progressControllers[taskId] = StreamController<DownloadTask>.broadcast();+ final task = await _db.get(fileId);+ if (task != null) {+ await _deleteFiles(task);+ await _updateTask(task.copyWith(status: DownloadStatus.cancelled));+ await _db.delete(fileId);}- return _progressControllers[taskId]!.stream;- }- // Create a new download task- Future<DownloadTask> createDownload(int id, String filename, int size) async {- final task = DownloadTask(- id: DateTime.now().millisecondsSinceEpoch,- url: FileUrl.getUrl(id, FileUrlType.download),- totalBytes: size,- filename: filename,- status: 'pending',- );- await _dbHelper.insertDownload(task);- return task;+ _cleanup(fileId);}- // Start or resume a download- Future<void> startDownload(int taskId) async {- final task = await _dbHelper.getDownload(taskId);- if (task == null) return;-- if (task.status == 'downloading') return; // Already running+ /// Get current download status+ Future<DownloadTask?> getDownload(int fileId) => _db.get(fileId);- task.status = 'downloading';- await _dbHelper.updateDownload(task);- _updateProgress(task);-- // Create a cancel token for this download- final cancelToken = CancelToken();- _cancelTokens[taskId] = cancelToken;+ /// Get all downloads+ Future<List<DownloadTask>> getAllDownloads() => _db.getAll();+ Future<void> _startDownload(+ DownloadTask task,+ Completer<DownloadResult> completer,+ ) async {try {- // Get download directory and create file- final directory = await getApplicationDocumentsDirectory();- final filePath = '${directory.path}/${task.filename}';- final file = File(filePath);-- // Prepare request options- final options = Options(- headers: {},- responseType: ResponseType.stream,+ task = task.copyWith(status: DownloadStatus.downloading);+ await _updateTask(task);++ final cancelToken = CancelToken();+ _cancelTokens[task.id] = cancelToken;++ final directory = Configuration.instance.getTempDirectory();+ final basePath = '$directory${task.id}_${task.filename}';++ // Check existing chunks and calculate progress+ final totalChunks = (task.totalBytes / _chunkSize).ceil();+ final existingChunks =+ await _validateExistingChunks(basePath, task.totalBytes, totalChunks);++ task = task.copyWith(+ bytesDownloaded: _calculateDownloadedBytes(+ existingChunks,+ task.totalBytes,+ totalChunks,+ ),);+ await _updateTask(task);- // If we've already downloaded some bytes, add Range header- if (task.bytesDownloaded > 0) {- options.headers!['Range'] = 'bytes=${task.bytesDownloaded}-';- }+ // Download missing chunks+ for (int i = 0; i < totalChunks; i++) {+ if (existingChunks[i] || cancelToken.isCancelled) continue;- // Make actual download request- final response = await _dio.get(- task.url,- options: options,- cancelToken: cancelToken,- );-- // For handling the response stream- final responseStream = response.data.stream as Stream<List<int>>;-- // Check response status- final statusCode = response.statusCode ?? 0;-- if (statusCode == 200 || statusCode == 206) {- // Open the file in append mode if resuming, otherwise create new- IOSink fileSink;- if (task.bytesDownloaded > 0 && statusCode == 206) {- fileSink = file.openWrite(mode: FileMode.append);- } else {- // If it's not a partial response, start from the beginning- task.bytesDownloaded = 0;- fileSink = file.openWrite(mode: FileMode.write);- }-- // Process the response stream- await responseStream.listen(- (List<int> chunk) async {- // Write to file- fileSink.add(chunk);-- // Update progress- task.bytesDownloaded += chunk.length;- await _dbHelper.updateDownload(task);- _updateProgress(task);- },- onDone: () async {- await fileSink.close();-- // Download completed- task.status = 'completed';- await _dbHelper.updateDownload(task);- _updateProgress(task);-- _cancelTokens.remove(taskId);- },- onError: (error) async {- await fileSink.close();-- // Handle error- task.status = 'error';- task.error = error.toString();- await _dbHelper.updateDownload(task);- _updateProgress(task);-- _cancelTokens.remove(taskId);- },- cancelOnError: true,- ).asFuture();- } else if (statusCode == 416) {- // Requested range not satisfiable- task.bytesDownloaded = 0;- task.error = 'Server does not support resume. Starting from beginning.';- await _dbHelper.updateDownload(task);- _updateProgress(task);-- // Retry from beginning- await startDownload(taskId);- } else {- // Other HTTP error- task.status = 'error';- task.error = 'HTTP Error: $statusCode';- await _dbHelper.updateDownload(task);- _updateProgress(task);+ await _downloadChunk(task, basePath, i, totalChunks, cancelToken);+ existingChunks[i] = true;+ }- _cancelTokens.remove(taskId);+ if (!cancelToken.isCancelled) {+ final finalPath = await _combineChunks(basePath, totalChunks);+ task = task.copyWith(+ status: DownloadStatus.completed,+ filePath: finalPath,+ bytesDownloaded: task.totalBytes,+ );+ await _updateTask(task);+ completer.complete(DownloadResult(task, true));}- } on DioException catch (e) {- // Handle Dio exceptions- if (e.type == DioExceptionType.cancel) {- // Download was canceled - don't update status as it was likely paused- _cancelTokens.remove(taskId);+ } catch (e) {+ if (e is DioException && e.type == DioExceptionType.cancel) {+ // Handle pause - don't complete the futurereturn;}- task.status = 'error';- task.error = 'Download error: ${e.message}';- await _dbHelper.updateDownload(task);- _updateProgress(task);-- _cancelTokens.remove(taskId);- } catch (e) {- // Handle generic exceptions- task.status = 'error';- task.error = e.toString();- await _dbHelper.updateDownload(task);- _updateProgress(task);-- _cancelTokens.remove(taskId);+ task = task.copyWith(status: DownloadStatus.error, error: e.toString());+ await _updateTask(task);+ completer.complete(DownloadResult(task, false));+ } finally {+ _cleanup(task.id);}}- // Pause a download- Future<void> pauseDownload(int taskId) async {- final task = await _dbHelper.getDownload(taskId);- if (task == null) return;+ Future<List<bool>> _validateExistingChunks(+ String basePath,+ int totalBytes,+ int totalChunks,+ ) async {+ final existingChunks = List.filled(totalChunks, false);++ for (int i = 0; i < totalChunks; i++) {+ final chunkFile = File('$basePath.part${i + 1}');+ if (!await chunkFile.exists()) continue;- if (task.status == 'downloading') {- task.status = 'paused';- await _dbHelper.updateDownload(task);- _updateProgress(task);+ final expectedSize =+ i == totalChunks - 1 ? totalBytes - (i * _chunkSize) : _chunkSize;- // Cancel the download- if (_cancelTokens.containsKey(taskId)) {- _cancelTokens[taskId]!.cancel('Download paused');- _cancelTokens.remove(taskId);+ final actualSize = await chunkFile.length();+ if (actualSize == expectedSize) {+ existingChunks[i] = true;+ } else {+ await chunkFile.delete(); // Remove corrupted chunk}}++ return existingChunks;}- // Cancel and delete a download- Future<void> cancelDownload(int taskId) async {- // Pause download first- await pauseDownload(taskId);+ int _calculateDownloadedBytes(+ List<bool> existingChunks,+ int totalBytes,+ int totalChunks,+ ) {+ int bytes = 0;+ for (int i = 0; i < existingChunks.length; i++) {+ if (existingChunks[i]) {+ bytes +=+ i == totalChunks - 1 ? totalBytes - (i * _chunkSize) : _chunkSize;+ }+ }+ return bytes;+ }- // Delete the file- final task = await _dbHelper.getDownload(taskId);- if (task != null) {- try {- final directory = await getApplicationDocumentsDirectory();- final file = File('${directory.path}/${task.filename}');- if (await file.exists()) {- await file.delete();- }- } catch (e) {- print('Error deleting file: $e');+ Future<void> _downloadChunk(+ DownloadTask task,+ String basePath,+ int chunkIndex,+ int totalChunks,+ CancelToken cancelToken,+ ) async {+ final chunkPath = '$basePath.part${chunkIndex + 1}';+ final startByte = chunkIndex * _chunkSize;+ final endByte = chunkIndex == totalChunks - 1+ ? task.totalBytes - 1+ : (startByte + _chunkSize) - 1;++ await _dio.download(+ FileUrl.getUrl(task.id, FileUrlType.download),+ chunkPath,+ options: Options(+ headers: {+ "X-Auth-Token": Configuration.instance.getToken(),+ "Range": "bytes=$startByte-$endByte",+ },+ ),+ cancelToken: cancelToken,+ onReceiveProgress: (received, total) async {+ final updatedTask = task.copyWith(+ bytesDownloaded: task.bytesDownloaded + received,+ );+ _notifyProgress(updatedTask);+ },+ );++ // Update progress after chunk completion+ final chunkSize = await File(chunkPath).length();+ task = task.copyWith(bytesDownloaded: task.bytesDownloaded + chunkSize);+ await _updateTask(task);+ }++ Future<String> _combineChunks(String basePath, int totalChunks) async {+ final finalFile = File(basePath);+ final sink = finalFile.openWrite();++ try {+ for (int i = 1; i <= totalChunks; i++) {+ final chunkFile = File('$basePath.part$i');+ final bytes = await chunkFile.readAsBytes();+ sink.add(bytes);+ await chunkFile.delete();}+ } finally {+ await sink.close();}- // Remove from database- await _dbHelper.deleteDownload(taskId);+ return finalFile.path;+ }- // Close the stream controller- if (_progressControllers.containsKey(taskId)) {- await _progressControllers[taskId]!.close();- _progressControllers.remove(taskId);+ Future<void> _deleteFiles(DownloadTask task) async {+ try {+ final directory = Configuration.instance.getTempDirectory();+ final basePath = '$directory${task.id}_${task.filename}';+ // Delete final file+ final finalFile = File(basePath);+ if (await finalFile.exists()) await finalFile.delete();++ // Delete chunk files+ final totalChunks = (task.totalBytes / _chunkSize).ceil();+ for (int i = 1; i <= totalChunks; i++) {+ final chunkFile = File('$basePath.part$i');+ if (await chunkFile.exists()) await chunkFile.delete();+ }+ } catch (e) {+ _logger.warning('Error deleting files: $e');}}- // Get a list of all downloads- Future<List<DownloadTask>> getAllDownloads() async {- return await _dbHelper.getDownloads();+ Future<void> _updateTask(DownloadTask task) async {+ await _db.save(task);+ _notifyProgress(task);}- // Update the progress and notify listeners- void _updateProgress(DownloadTask task) {- if (_progressControllers.containsKey(task.id) &&- !_progressControllers[task.id]!.isClosed) {- _progressControllers[task.id]!.add(task);+ void _notifyProgress(DownloadTask task) {+ final stream = _streams[task.id];+ if (stream != null && !stream.isClosed) {+ stream.add(task);+ }+ }++ void _cleanup(int fileId) {+ _completers.remove(fileId);+ _cancelTokens.remove(fileId);++ final stream = _streams[fileId];+ if (stream != null && !stream.hasListener) {+ stream.close();+ _streams.remove(fileId);}}- // Cleanup resourcesFuture<void> dispose() async {- for (final controller in _progressControllers.values) {- await controller.close();+ for (final completer in _completers.values) {+ if (!completer.isCompleted) {+ completer.completeError('Disposed');+ }}- _progressControllers.clear();+ _completers.clear();- for (final cancelToken in _cancelTokens.values) {- cancelToken.cancel('Disposed');+ for (final token in _cancelTokens.values) {+ token.cancel('Disposed');}_cancelTokens.clear();++ for (final stream in _streams.values) {+ await stream.close();+ }+ _streams.clear();}}diff --git a/mobile/lib/module/download/task.dart b/mobile/lib/module/download/task.dartindex ef2c157eba..b691c08646 100644--- a/mobile/lib/module/download/task.dart+++ b/mobile/lib/module/download/task.dart@@ -1,43 +1,80 @@+enum DownloadStatus {+ pending,+ downloading,+ paused,+ completed,+ error,+ cancelled+}+class DownloadTask {final int id;- final String url;final String filename;+ final int totalBytes;int bytesDownloaded;- int totalBytes;- String status; // 'pending', 'downloading', 'paused', 'completed', 'error'- String error;+ DownloadStatus status;+ String? error;+ String? filePath;DownloadTask({required this.id,- required this.url,required this.filename,required this.totalBytes,this.bytesDownloaded = 0,- this.status = 'pending',- this.error = '',+ this.status = DownloadStatus.pending,+ this.error,+ this.filePath,});- Map<String, dynamic> toMap() {- return {- 'id': id,- 'url': url,- 'filename': filename,- 'bytesDownloaded': bytesDownloaded,- 'totalBytes': totalBytes,- 'status': status,- 'error': error,- };- }-- factory DownloadTask.fromMap(Map<String, dynamic> map) {- return DownloadTask(- id: map['id'],- url: map['url'],- filename: map['filename'],- bytesDownloaded: map['bytesDownloaded'],- totalBytes: map['totalBytes'],- status: map['status'],- error: map['error'],- );- }+ double get progress => totalBytes > 0 ? bytesDownloaded / totalBytes : 0.0;+ bool get isCompleted => status == DownloadStatus.completed;+ bool get isActive => status == DownloadStatus.downloading;+ bool get isFinished => [+ DownloadStatus.completed,+ DownloadStatus.error,+ DownloadStatus.cancelled+ ].contains(status);++ Map<String, dynamic> toMap() => {+ 'id': id,+ 'filename': filename,+ 'totalBytes': totalBytes,+ 'bytesDownloaded': bytesDownloaded,+ 'status': status.name,+ 'error': error,+ 'filePath': filePath,+ };++ static DownloadTask fromMap(Map<String, dynamic> map) => DownloadTask(+ id: map['id'],+ filename: map['filename'],+ totalBytes: map['totalBytes'],+ bytesDownloaded: map['bytesDownloaded'] ?? 0,+ status: DownloadStatus.values.byName(map['status']),+ error: map['error'],+ filePath: map['filePath'],+ );++ DownloadTask copyWith({+ int? bytesDownloaded,+ DownloadStatus? status,+ String? error,+ String? filePath,+ }) =>+ DownloadTask(+ id: id,+ filename: filename,+ totalBytes: totalBytes,+ bytesDownloaded: bytesDownloaded ?? this.bytesDownloaded,+ status: status ?? this.status,+ error: error ?? this.error,+ filePath: filePath ?? this.filePath,+ );+}++class DownloadResult {+ final DownloadTask task;+ final bool success;++ DownloadResult(this.task, this.success);}