Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add support for resumable download

Neeraj Gupta6c9107301c66
diff --git a/mobile/ios/Podfile.lock b/mobile/ios/Podfile.lock
index 35f0ecafad..b893a58a69 100644
--- a/mobile/ios/Podfile.lock
+++ b/mobile/ios/Podfile.lock
@@ -75,6 +75,8 @@ PODS:
- Flutter
- flutter_sodium (0.0.1):
- Flutter
+ - flutter_timezone (0.0.1):
+ - Flutter
- fluttertoast (0.0.2):
- Flutter
- GoogleDataTransport (10.1.0):
@@ -259,6 +261,7 @@ DEPENDENCIES:
- flutter_native_splash (from `.symlinks/plugins/flutter_native_splash/ios`)
- flutter_secure_storage (from `.symlinks/plugins/flutter_secure_storage/ios`)
- flutter_sodium (from `.symlinks/plugins/flutter_sodium/ios`)
+ - flutter_timezone (from `.symlinks/plugins/flutter_timezone/ios`)
- fluttertoast (from `.symlinks/plugins/fluttertoast/ios`)
- home_widget (from `.symlinks/plugins/home_widget/ios`)
- image_editor_common (from `.symlinks/plugins/image_editor_common/ios`)
@@ -298,7 +301,7 @@ DEPENDENCIES:
- wakelock_plus (from `.symlinks/plugins/wakelock_plus/ios`)
SPEC REPOS:
- https://github.com/ente-io/ffmpeg-kit-custom-repo-ios:
+ https://github.com/ente-io/ffmpeg-kit-custom-repo-ios.git:
- ffmpeg_kit_custom
trunk:
- Firebase
@@ -359,6 +362,8 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/flutter_secure_storage/ios"
flutter_sodium:
:path: ".symlinks/plugins/flutter_sodium/ios"
+ flutter_timezone:
+ :path: ".symlinks/plugins/flutter_timezone/ios"
fluttertoast:
:path: ".symlinks/plugins/fluttertoast/ios"
home_widget:
@@ -460,6 +465,7 @@ SPEC CHECKSUMS:
flutter_native_splash: f71420956eb811e6d310720fee915f1d42852e7a
flutter_secure_storage: 23fc622d89d073675f2eaa109381aefbcf5a49be
flutter_sodium: a00383520fc689c688b66fd3092984174712493e
+ flutter_timezone: ac3da59ac941ff1c98a2e1f0293420e020120282
fluttertoast: 21eecd6935e7064cc1fcb733a4c5a428f3f24f0f
GoogleDataTransport: aae35b7ea0c09004c3797d53c8c41f66f219d6a7
GoogleUtilities: 26a3abef001b6533cf678d3eb38fd3f614b7872d
diff --git a/mobile/ios/Runner.xcodeproj/project.pbxproj b/mobile/ios/Runner.xcodeproj/project.pbxproj
index 678d1e3446..d2a68628c0 100644
--- a/mobile/ios/Runner.xcodeproj/project.pbxproj
+++ b/mobile/ios/Runner.xcodeproj/project.pbxproj
@@ -389,6 +389,7 @@
"${BUILT_PRODUCTS_DIR}/flutter_native_splash/flutter_native_splash.framework",
"${BUILT_PRODUCTS_DIR}/flutter_secure_storage/flutter_secure_storage.framework",
"${BUILT_PRODUCTS_DIR}/flutter_sodium/flutter_sodium.framework",
+ "${BUILT_PRODUCTS_DIR}/flutter_timezone/flutter_timezone.framework",
"${BUILT_PRODUCTS_DIR}/fluttertoast/fluttertoast.framework",
"${BUILT_PRODUCTS_DIR}/home_widget/home_widget.framework",
"${BUILT_PRODUCTS_DIR}/image_editor_common/image_editor_common.framework",
@@ -483,6 +484,7 @@
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_native_splash.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_secure_storage.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_sodium.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_timezone.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/fluttertoast.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/home_widget.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/image_editor_common.framework",
diff --git a/mobile/lib/core/constants.dart b/mobile/lib/core/constants.dart
index 9067d14b14..1f8f3fb218 100644
--- a/mobile/lib/core/constants.dart
+++ b/mobile/lib/core/constants.dart
@@ -103,7 +103,7 @@ const blackThumbnailBase64 = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEB'
const uploadTempFilePrefix = "upload_file_";
final tempDirCleanUpInterval = kDebugMode
- ? const Duration(seconds: 30).inMicroseconds
+ ? const Duration(hours: 1).inMicroseconds
: const Duration(hours: 6).inMicroseconds;
const kFilterChipHeight = 32.0;
diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart
index c4ae34fa28..eb605bf58b 100644
--- a/mobile/lib/main.dart
+++ b/mobile/lib/main.dart
@@ -224,7 +224,7 @@ Future<void> _init(bool isBackground, {String via = ''}) async {
_logger.info("NetworkClient init done $tlog");
ServiceLocator.instance
- .init(preferences, NetworkClient.instance.enteDio, packageInfo);
+ .init(preferences, NetworkClient.instance.enteDio,NetworkClient.instance.getDio(), packageInfo);
_logger.info("UserService init $tlog");
await UserService.instance.init();
diff --git a/mobile/lib/module/download/db.dart b/mobile/lib/module/download/db.dart
index 097322ba0a..a6fcbfe163 100644
--- a/mobile/lib/module/download/db.dart
+++ b/mobile/lib/module/download/db.dart
@@ -38,8 +38,11 @@ class DatabaseHelper {
Future<void> save(DownloadTask task) async {
final db = await database;
- await db.insert('downloads', task.toMap(),
- conflictAlgorithm: ConflictAlgorithm.replace);
+ await db.insert(
+ 'downloads',
+ task.toMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
}
Future<DownloadTask?> get(int id) async {
diff --git a/mobile/lib/module/download/resumable.dart b/mobile/lib/module/download/manager.dart
similarity index 79%
rename from mobile/lib/module/download/resumable.dart
rename to mobile/lib/module/download/manager.dart
index c95d46b2f4..fc298259ec 100644
--- a/mobile/lib/module/download/resumable.dart
+++ b/mobile/lib/module/download/manager.dart
@@ -10,11 +10,12 @@ import "package:photos/module/download/file_url.dart";
import "package:photos/module/download/task.dart";
class DownloadManager {
- static const int _chunkSize = 50 * 1024 * 1024;
+ static const int downloadChunkSize = 10 * 1024 * 1024;
final _db = DatabaseHelper();
- final _dio = Dio();
+ final Dio _dio;
final _logger = Logger('DownloadManager');
+ DownloadManager(this._dio);
// Active downloads with their completers and streams
final Map<int, Completer<DownloadResult>> _completers = {};
@@ -51,11 +52,28 @@ class DownloadManager {
// Don't restart if already completed
if (task.isCompleted) {
- final result = DownloadResult(task, true);
- completer.complete(result);
- return result;
+ // ensure that the file exists
+ final filePath = task.filePath;
+ if (filePath == null || !(await File(filePath).exists())) {
+ // If the file doesn't exist, mark the task as error
+ _logger.warning(
+ 'File not found for ${task.filename} (${task.bytesDownloaded}/${task.totalBytes} bytes)',
+ );
+ final updatedTask = task.copyWith(
+ status: DownloadStatus.error,
+ error: 'File not found',
+ filePath: null,
+ );
+ await _updateTask(updatedTask);
+ } else {
+ _logger.info(
+ 'Download already completed for ${task.filename} (${task.bytesDownloaded}/${task.totalBytes} bytes)',
+ );
+ final result = DownloadResult(task, true);
+ completer.complete(result);
+ return result;
+ }
}
-
unawaited(_startDownload(task, completer));
return completer.future;
}
@@ -108,7 +126,7 @@ class DownloadManager {
final basePath = '$directory${task.id}_${task.filename}';
// Check existing chunks and calculate progress
- final totalChunks = (task.totalBytes / _chunkSize).ceil();
+ final totalChunks = (task.totalBytes / downloadChunkSize).ceil();
final existingChunks =
await _validateExistingChunks(basePath, task.totalBytes, totalChunks);
@@ -122,10 +140,15 @@ class DownloadManager {
await _updateTask(task);
// Download missing chunks
+ // log existing progress and download bytes
+ _logger.info(
+ 'Resuming download for ${task.filename} (${task.bytesDownloaded}/${task.totalBytes} bytes)',
+ );
for (int i = 0; i < totalChunks; i++) {
if (existingChunks[i] || cancelToken.isCancelled) continue;
-
+ _logger.info('Downloading chunk ${i + 1} of $totalChunks');
await _downloadChunk(task, basePath, i, totalChunks, cancelToken);
+ _logger.info('Chunk ${i + 1} downloaded');
existingChunks[i] = true;
}
@@ -164,13 +187,20 @@ class DownloadManager {
final chunkFile = File('$basePath.part${i + 1}');
if (!await chunkFile.exists()) continue;
- final expectedSize =
- i == totalChunks - 1 ? totalBytes - (i * _chunkSize) : _chunkSize;
+ final expectedSize = i == totalChunks - 1
+ ? totalBytes - (i * downloadChunkSize)
+ : downloadChunkSize;
final actualSize = await chunkFile.length();
if (actualSize == expectedSize) {
+ _logger.info('exiging chunk ${i + 1} is valid');
existingChunks[i] = true;
} else {
+ _logger.warning(
+ 'Chunk ${i + 1} is corrupted: expected $expectedSize bytes, '
+ 'but got $actualSize bytes',
+ );
+ existingChunks[i] = false;
await chunkFile.delete(); // Remove corrupted chunk
}
}
@@ -186,8 +216,9 @@ class DownloadManager {
int bytes = 0;
for (int i = 0; i < existingChunks.length; i++) {
if (existingChunks[i]) {
- bytes +=
- i == totalChunks - 1 ? totalBytes - (i * _chunkSize) : _chunkSize;
+ bytes += i == totalChunks - 1
+ ? totalBytes - (i * downloadChunkSize)
+ : downloadChunkSize;
}
}
return bytes;
@@ -201,13 +232,13 @@ class DownloadManager {
CancelToken cancelToken,
) async {
final chunkPath = '$basePath.part${chunkIndex + 1}';
- final startByte = chunkIndex * _chunkSize;
+ final startByte = chunkIndex * downloadChunkSize;
final endByte = chunkIndex == totalChunks - 1
? task.totalBytes - 1
- : (startByte + _chunkSize) - 1;
+ : (startByte + downloadChunkSize) - 1;
await _dio.download(
- FileUrl.getUrl(task.id, FileUrlType.download),
+ FileUrl.getUrl(task.id, FileUrlType.directDownload),
chunkPath,
options: Options(
headers: {
@@ -225,8 +256,8 @@ class DownloadManager {
);
// Update progress after chunk completion
- final chunkSize = await File(chunkPath).length();
- task = task.copyWith(bytesDownloaded: task.bytesDownloaded + chunkSize);
+ final chunkFileSize = await File(chunkPath).length();
+ task = task.copyWith(bytesDownloaded: task.bytesDownloaded + chunkFileSize);
await _updateTask(task);
}
@@ -257,7 +288,7 @@ class DownloadManager {
if (await finalFile.exists()) await finalFile.delete();
// Delete chunk files
- final totalChunks = (task.totalBytes / _chunkSize).ceil();
+ final totalChunks = (task.totalBytes / downloadChunkSize).ceil();
for (int i = 1; i <= totalChunks; i++) {
final chunkFile = File('$basePath.part$i');
if (await chunkFile.exists()) await chunkFile.delete();
diff --git a/mobile/lib/module/download/task.dart b/mobile/lib/module/download/task.dart
index b691c08646..1bd96ca295 100644
--- a/mobile/lib/module/download/task.dart
+++ b/mobile/lib/module/download/task.dart
@@ -32,7 +32,7 @@ class DownloadTask {
bool get isFinished => [
DownloadStatus.completed,
DownloadStatus.error,
- DownloadStatus.cancelled
+ DownloadStatus.cancelled,
].contains(status);
Map<String, dynamic> toMap() => {
diff --git a/mobile/lib/service_locator.dart b/mobile/lib/service_locator.dart
index 57728a7a26..00e789b5ae 100644
--- a/mobile/lib/service_locator.dart
+++ b/mobile/lib/service_locator.dart
@@ -4,6 +4,7 @@ import "package:ente_cast_normal/ente_cast_normal.dart";
import "package:ente_feature_flag/ente_feature_flag.dart";
import "package:package_info_plus/package_info_plus.dart";
import "package:photos/gateways/entity_gw.dart";
+import "package:photos/module/download/manager.dart";
import "package:photos/services/account/billing_service.dart";
import "package:photos/services/entity_service.dart";
import "package:photos/services/location_service.dart";
@@ -22,6 +23,7 @@ import "package:shared_preferences/shared_preferences.dart";
class ServiceLocator {
late final SharedPreferences prefs;
late final Dio enteDio;
+ late final Dio nonEnteDio;
late final PackageInfo packageInfo;
// instance
@@ -29,9 +31,10 @@ class ServiceLocator {
static final ServiceLocator instance = ServiceLocator._privateConstructor();
- init(SharedPreferences prefs, Dio enteDio, PackageInfo packageInfo) {
+ init(SharedPreferences prefs, Dio enteDio, Dio nonEnteDio, PackageInfo packageInfo) {
this.prefs = prefs;
this.enteDio = enteDio;
+ this.nonEnteDio = nonEnteDio;
this.packageInfo = packageInfo;
}
}
@@ -150,3 +153,11 @@ PermissionService get permissionService {
_permissionService ??= PermissionService(ServiceLocator.instance.prefs);
return _permissionService!;
}
+
+DownloadManager? _downloadManager;
+DownloadManager get downloadManager {
+ _downloadManager ??= DownloadManager(
+ ServiceLocator.instance.nonEnteDio,
+ );
+ return _downloadManager!;
+}
\ No newline at end of file
diff --git a/mobile/lib/ui/viewer/file/thumbnail_widget.dart b/mobile/lib/ui/viewer/file/thumbnail_widget.dart
index f4d3e1cc3c..8f9119348e 100644
--- a/mobile/lib/ui/viewer/file/thumbnail_widget.dart
+++ b/mobile/lib/ui/viewer/file/thumbnail_widget.dart
@@ -23,6 +23,7 @@ import 'package:photos/ui/viewer/file/file_icons_widget.dart';
import "package:photos/ui/viewer/gallery/component/group/type.dart";
import "package:photos/ui/viewer/gallery/state/gallery_context_state.dart";
import 'package:photos/utils/file_util.dart';
+import "package:photos/utils/standalone/data.dart";
import "package:photos/utils/standalone/task_queue.dart";
import 'package:photos/utils/thumbnail_util.dart';
@@ -225,8 +226,8 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
viewChildren.add(TrashedFileOverlayText(widget.file as TrashFile));
} else if (GalleryContextState.of(context)?.type == GroupType.size) {
viewChildren.add(FileSizeOverlayText(widget.file));
- } else if (widget.file.debugCaption != null) {
- viewChildren.add(FileOverlayText(widget.file.debugCaption!));
+ } else if (widget.file.fileSize != null) {
+ viewChildren.add(FileOverlayText(formatBytes(widget.file.fileSize!)));
}
// todo: Move this icon overlay to the collection widget.
if (widget.shouldShowArchiveStatus) {
diff --git a/mobile/lib/utils/file_download_util.dart b/mobile/lib/utils/file_download_util.dart
index ed7909247a..e528327097 100644
--- a/mobile/lib/utils/file_download_util.dart
+++ b/mobile/lib/utils/file_download_util.dart
@@ -16,6 +16,9 @@ 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";
import "package:photos/services/ignored_files_service.dart";
import "package:photos/services/sync/local_sync_service.dart";
@@ -95,6 +98,8 @@ Future<File?> downloadAndDecryptPublicFile(
}
}
+String lastProgress = "";
+
Future<File?> downloadAndDecrypt(
EnteFile file, {
ProgressCallback? progressCallback,
@@ -114,30 +119,62 @@ Future<File?> downloadAndDecrypt(
_logger
.info('$logPrefix starting download ${formatBytes(file.fileSize ?? 0)}');
final String tempDir = Configuration.instance.getTempDirectory();
- final String encryptedFilePath = "$tempDir${file.generatedID}.encrypted";
- final encryptedFile = File(encryptedFilePath);
+ String encryptedFilePath = "$tempDir${file.generatedID}.encrypted";
+ File encryptedFile = File(encryptedFilePath);
final startTime = DateTime.now().millisecondsSinceEpoch;
try {
- final response = await NetworkClient.instance.getDio().download(
- file.downloadUrl,
- encryptedFilePath,
- options: Options(
- headers: {"X-Auth-Token": Configuration.instance.getToken()},
- ),
- onReceiveProgress: (a, b) {
- if (kDebugMode && a >= 0 && b >= 0) {
- // _logger.fine(
- // "$logPrefix download progress: ${formatBytes(a)} / ${formatBytes(b)}",
- // );
+ // check if great than 10MB
+ if (file.fileSize != null &&
+ file.fileSize! > DownloadManager.downloadChunkSize) {
+ // Subscribe to progress updates
+ downloadManager.watchDownload(file.uploadedFileID!).listen((task) {
+ final newProgress = (task.progress * 100).toStringAsFixed(1);
+ if (newProgress != lastProgress) {
+ lastProgress = newProgress;
+ _logger.info(
+ 'Resumable Progress: $newProgress%',
+ );
}
- progressCallback?.call(a, b);
- },
- );
- if (response.statusCode != 200 || !encryptedFile.existsSync()) {
- _logger.warning('$logPrefix download failed ${response.toString()}');
- return null;
+
+ if (progressCallback != null) {
+ progressCallback(task.bytesDownloaded, task.totalBytes);
+ }
+ });
+ final DownloadResult result = await downloadManager.download(
+ file.uploadedFileID!,
+ file.displayName,
+ file.fileSize!,
+ );
+ if (result.success) {
+ encryptedFilePath = result.task.filePath!;
+ encryptedFile = File(encryptedFilePath);
+ } else {
+ _logger.warning('$logPrefix download failed ${result.task}');
+ return null;
+ }
+ } else {
+ // If the file is small, download it directly to the final location
+ final response = await NetworkClient.instance.getDio().download(
+ file.downloadUrl,
+ encryptedFilePath,
+ options: Options(
+ headers: {"X-Auth-Token": Configuration.instance.getToken()},
+ ),
+ onReceiveProgress: (a, b) {
+ if (kDebugMode && a >= 0 && b >= 0) {
+ // _logger.fine(
+ // "$logPrefix download progress: ${formatBytes(a)} / ${formatBytes(b)}",
+ // );
+ }
+ progressCallback?.call(a, b);
+ },
+ );
+ if (response.statusCode != 200 || !encryptedFile.existsSync()) {
+ _logger.warning('$logPrefix download failed ${response.toString()}');
+ return null;
+ }
}
final int sizeInBytes = file.fileSize ?? await encryptedFile.length();