An open-source cross-platform alternative to AirDrop
feat: retry on checksum mismatch
Tien Do Nam9ba0726d24fa
diff --git a/app/android/app/src/main/kotlin/org/localsend/localsend_app/MainActivity.kt b/app/android/app/src/main/kotlin/org/localsend/localsend_app/MainActivity.ktindex b10d976f..7bc27337 100644--- a/app/android/app/src/main/kotlin/org/localsend/localsend_app/MainActivity.kt+++ b/app/android/app/src/main/kotlin/org/localsend/localsend_app/MainActivity.kt@@ -63,6 +63,8 @@ class MainActivity : FlutterActivity() {"createFile" -> handleCreateFile(call, result)+ "deleteFile" -> handleDeleteFile(call, result)+"openContentUri" -> {openUri(context, call.argument<String>("uri")!!)result.success(null)@@ -176,6 +178,34 @@ class MainActivity : FlutterActivity() {}}+ /// Deletes a document created by [handleCreateFile].+ ///+ /// Returns whether the document was deleted. A document that no longer+ /// exists is reported as not deleted instead of as an error.+ private fun handleDeleteFile(call: MethodCall, result: MethodChannel.Result) {+ val uriString = call.argument<String>("uri")+ if (uriString == null) {+ result.error("INVALID_ARGUMENT", "Missing content URI", null)+ return+ }++ val uri = Uri.parse(uriString)+ if (uri.scheme != ContentResolver.SCHEME_CONTENT) {+ result.error("INVALID_ARGUMENT", "Expected a content:// URI", null)+ return+ }++ try {+ result.success(DocumentsContract.deleteDocument(contentResolver, uri))+ } catch (e: SecurityException) {+ result.error("PERMISSION_DENIED", e.message ?: "Permission denied for content URI", null)+ } catch (e: java.io.FileNotFoundException) {+ result.success(false)+ } catch (e: Exception) {+ result.error("DELETE_FAILED", e.message ?: "Failed to delete file", null)+ }+ }+private fun openDirectoryPicker(onlyPath: Boolean) {val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)diff --git a/app/lib/provider/network/server/controller/receive_controller.dart b/app/lib/provider/network/server/controller/receive_controller.dartindex 2bb37f76..3a9b2ff7 100644--- a/app/lib/provider/network/server/controller/receive_controller.dart+++ b/app/lib/provider/network/server/controller/receive_controller.dart@@ -394,8 +394,11 @@ class ReceiveController {),);final settings = server.ref.read(settingsProvider);- bool quickSave = settings.quickSave && server.getState().session?.message == null;- final quickSaveFromFavorites = settings.quickSaveFromFavorites && server.getState().session?.message == null;+ // Only auto-close fully successful sessions: a failed file may still be+ // retried by the sender (e.g. after a checksum mismatch), which requires+ // the session to stay open.+ bool quickSave = settings.quickSave && !hasError && server.getState().session?.message == null;+ final quickSaveFromFavorites = settings.quickSaveFromFavorites && !hasError && server.getState().session?.message == null;if (quickSaveFromFavorites) {final bool isFavorite = server.ref.read(favoritesProvider).any((e) => e.fingerprint == session.sender.fingerprint);if (isFavorite) {diff --git a/packages/core/src/http/server/common/save.rs b/packages/core/src/http/server/common/save.rsindex b6948db4..f93dd1d5 100644--- a/packages/core/src/http/server/common/save.rs+++ b/packages/core/src/http/server/common/save.rs@@ -19,6 +19,10 @@ pub enum FileUploadTarget {/// The application should compare the number of received bytes with `file.size`/// and report the result on the sender side of `result_rx` which determines/// the HTTP response (200 on `Ok`, 500 on `Err` or when the sender is dropped).+ ///+ /// Note: the checksum is only verified after the application reported its+ /// result, so a checksum mismatch is not observable by the application here+ /// (unlike [FileUploadTarget::Path] and [FileUploadTarget::Fd]).Stream {/// Channel the server sends the binary chunks of the file into.binary_tx: mpsc::Sender<Bytes>,@@ -34,7 +38,8 @@ pub enum FileUploadTarget {/// The path to write the file to.path: PathBuf,- /// Channel on which the server reports whether the file was saved successfully.+ /// Channel on which the server reports whether the file was saved+ /// successfully, including the checksum verification if one was given.result_tx: oneshot::Sender<Result<(), String>>,/// Optional channel on which the server reports the number of bytes@@ -50,7 +55,8 @@ pub enum FileUploadTarget {/// Ownership is transferred; the descriptor is closed after writing.fd: std::os::fd::RawFd,- /// Channel on which the server reports whether the file was saved successfully.+ /// Channel on which the server reports whether the file was saved+ /// successfully, including the checksum verification if one was given.result_tx: oneshot::Sender<Result<(), String>>,/// Optional channel on which the server reports the number of bytes@@ -82,43 +88,50 @@ pub(crate) async fn save_req_to_target(use sha2::{Digest, Sha256};// Resolve the target into a chunk sender and a result receiver.- let (binary_tx, result_rx) = match target {+ // For [FileUploadTarget::Path] and [FileUploadTarget::Fd], the application's+ // result channel is answered by this function once the complete outcome+ // (including the checksum verification) is known.+ let (binary_tx, result_rx, app_result_tx) = match target {FileUploadTarget::Stream {binary_tx,result_rx,- } => (binary_tx, result_rx),+ } => (binary_tx, result_rx, None),FileUploadTarget::Path {path,result_tx,progress_tx,- } => spawn_file_writer(- async move {- tokio::fs::File::create(&path)- .await- .map_err(|e| format!("Failed to create {}: {e}", path.display()))- },- file_size,- result_tx,- progress_tx,- ),+ } => {+ let (binary_tx, result_rx) = spawn_file_writer(+ async move {+ tokio::fs::File::create(&path)+ .await+ .map_err(|e| format!("Failed to create {}: {e}", path.display()))+ },+ file_size,+ progress_tx,+ );+ (binary_tx, result_rx, Some(result_tx))+ }#[cfg(target_os = "android")]FileUploadTarget::Fd {fd,result_tx,progress_tx,- } => spawn_file_writer(- async move {- use std::os::fd::FromRawFd;-- // SAFETY: the descriptor is owned by this transfer; wrapping it in- // a File transfers that ownership so it is closed once writing finishes.- let std_file = unsafe { std::fs::File::from_raw_fd(fd) };- Ok(tokio::fs::File::from_std(std_file))- },- file_size,- result_tx,- progress_tx,- ),+ } => {+ let (binary_tx, result_rx) = spawn_file_writer(+ async move {+ use std::os::fd::FromRawFd;++ // SAFETY: the descriptor is owned by this transfer; wrapping it in+ // a File transfers that ownership so it is closed once writing finishes.+ let std_file = unsafe { std::fs::File::from_raw_fd(fd) };+ Ok(tokio::fs::File::from_std(std_file))+ },+ file_size,+ progress_tx,+ );+ (binary_tx, result_rx, Some(result_tx))+ }};// Forward the request body to the target, hashing it on the way if requested.@@ -155,38 +168,60 @@ pub(crate) async fn save_req_to_target(// Signal end of file to the receiving side.drop(binary_tx);- if stream_error {- return SaveResult::Failed;- }+ // Determine the outcome; `error` carries the reason for the application.+ let (result, error): (SaveResult, Option<String>) = 'outcome: {+ if stream_error {+ // The file writer (if any) fails with a size mismatch or its own+ // write error once the channel is closed; collect that reason.+ let error = match app_result_tx.is_some() {+ true => match result_rx.await {+ Ok(Err(err)) => Some(err),+ _ => None,+ },+ false => None,+ };+ break 'outcome (SaveResult::Failed, error.or(Some("Upload aborted".to_string())));+ }- match result_rx.await {- Ok(Ok(())) => (),- Ok(Err(err)) => {- tracing::warn!("Failed to process file: {err}");- return SaveResult::Failed;+ match result_rx.await {+ Ok(Ok(())) => (),+ Ok(Err(err)) => {+ tracing::warn!("Failed to process file: {err}");+ break 'outcome (SaveResult::Failed, Some(err));+ }+ Err(_) => break 'outcome (SaveResult::Failed, Some("Upload aborted".to_string())),}- Err(_) => return SaveResult::Failed,- }- if let (Some(hasher), Some(expected)) = (hasher, expected_sha256) {- let actual = crypto::hash::to_hex(&hasher.finalize());- if !actual.eq_ignore_ascii_case(expected) {- tracing::warn!("Checksum mismatch: expected {expected}, got {actual}");- return SaveResult::HashMismatch;+ if let (Some(hasher), Some(expected)) = (hasher, expected_sha256) {+ let actual = crypto::hash::to_hex(&hasher.finalize());+ if !actual.eq_ignore_ascii_case(expected) {+ tracing::warn!("Checksum mismatch: expected {expected}, got {actual}");+ break 'outcome (+ SaveResult::HashMismatch,+ Some("Checksum mismatch".to_string()),+ );+ }}++ (SaveResult::Success, None)+ };++ if let Some(app_result_tx) = app_result_tx {+ let _ = app_result_tx.send(match error {+ None => Ok(()),+ Some(err) => Err(err),+ });}- SaveResult::Success+ result}/// Spawns a task that writes incoming chunks to a file provided by `open`.////// Returns the sender for the binary chunks and a receiver for the final result.-/// The result is additionally reported to the application on `result_tx`.fn spawn_file_writer(open: impl Future<Output = Result<tokio::fs::File, String>> + Send + 'static,expected_size: u64,- result_tx: oneshot::Sender<Result<(), String>>,progress_tx: Option<mpsc::Sender<u64>>,) -> (mpsc::Sender<Bytes>, oneshot::Receiver<Result<(), String>>) {let (binary_tx, mut binary_rx) = mpsc::channel::<Bytes>(UPLOAD_CHANNEL_CAPACITY);@@ -197,7 +232,6 @@ fn spawn_file_writer(write_file_from_receiver(open, expected_size, &mut binary_rx, progress_tx).await;// Unblock the request handler if it is still sending chunks.binary_rx.close();- let _ = result_tx.send(result.clone());let _ = internal_tx.send(result);});diff --git a/packages/core/src/http/server/common/session.rs b/packages/core/src/http/server/common/session.rsindex d0530905..a17f3167 100644--- a/packages/core/src/http/server/common/session.rs+++ b/packages/core/src/http/server/common/session.rs@@ -37,6 +37,11 @@ pub(crate) struct SessionFileV2 {pub(crate) token: String,pub(crate) status: FileStatusV2,++ /// Number of upload requests started for this file.+ /// Limits how often a checksum mismatch resets the file to+ /// [FileStatusV2::Pending] for a retry.+ pub(crate) attempts: u8,}#[derive(Clone, Copy, Debug, Eq, PartialEq)]diff --git a/packages/core/src/http/server/v2.rs b/packages/core/src/http/server/v2.rsindex 8ccbe9af..1c621be7 100644--- a/packages/core/src/http/server/v2.rs+++ b/packages/core/src/http/server/v2.rs@@ -277,6 +277,7 @@ pub(crate) async fn prepare_upload(dto,token: Uuid::new_v4().to_string(),status: FileStatusV2::Pending,+ attempts: 0,};(id, file)})@@ -352,6 +353,7 @@ pub(crate) async fn upload(return Err(invalid_token_error());}file.status = FileStatusV2::InProgress;+ file.attempts = file.attempts.saturating_add(1);file.dto.clone()};@@ -369,19 +371,19 @@ pub(crate) async fn upload(target_tx,};if v2.event_tx.send(event).await.is_err() {- upload_guard.finish(false).await;+ upload_guard.finish(SaveResult::Failed).await;return Err(AppError::Status(StatusCode::INTERNAL_SERVER_ERROR));}let Ok(target) = target_rx.await else {- upload_guard.finish(false).await;+ upload_guard.finish(SaveResult::Failed).await;return Err(AppError::Status(StatusCode::INTERNAL_SERVER_ERROR));};let result =common::save::save_req_to_target(req, target, file_size, expected_sha256.as_deref()).await;- upload_guard.finish(result == SaveResult::Success).await;+ upload_guard.finish(result).await;match result {SaveResult::Success => Ok(Response::new(empty_body())),@@ -533,9 +535,9 @@ impl UploadGuard {}}- async fn finish(&mut self, success: bool) {+ async fn finish(&mut self, result: SaveResult) {self.armed = false;- finalize_file(&self.v2, &self.session_id, &self.file_id, success).await;+ finalize_file(&self.v2, &self.session_id, &self.file_id, result).await;}}@@ -548,13 +550,22 @@ impl Drop for UploadGuard {let session_id = std::mem::take(&mut self.session_id);let file_id = std::mem::take(&mut self.file_id);tokio::spawn(async move {- finalize_file(&v2, &session_id, &file_id, false).await;+ finalize_file(&v2, &session_id, &file_id, SaveResult::Failed).await;});}}+/// How often an upload of the same file may be started, i.e. how often a+/// sender may retry a file after a checksum mismatch.+/// Senders must not retry more often than this (see the upload isolate).+const MAX_UPLOAD_ATTEMPTS: u8 = 3;+/// Sets the final status of a file and ends the session once all files are done.-async fn finalize_file(v2: &V2State, session_id: &str, file_id: &str, success: bool) {+///+/// A checksum mismatch resets the file to [FileStatusV2::Pending] (as long as+/// [MAX_UPLOAD_ATTEMPTS] is not exhausted) so the sender can retry the upload+/// with the same token; the session stays active in that case.+async fn finalize_file(v2: &V2State, session_id: &str, file_id: &str, result: SaveResult) {let session_ended = {let mut slot = v2.session.lock().await;let Some(SessionStateV2::Active(session)) = slot.as_mut() else {@@ -565,9 +576,12 @@ async fn finalize_file(v2: &V2State, session_id: &str, file_id: &str, success: b}if let Some(file) = session.files.get_mut(file_id) {if file.status == FileStatusV2::InProgress {- file.status = match success {- true => FileStatusV2::Finished,- false => FileStatusV2::Failed,+ file.status = match result {+ SaveResult::Success => FileStatusV2::Finished,+ SaveResult::HashMismatch if file.attempts < MAX_UPLOAD_ATTEMPTS => {+ FileStatusV2::Pending+ }+ SaveResult::Failed | SaveResult::HashMismatch => FileStatusV2::Failed,};}}diff --git a/packages/core/tests/v2_server.rs b/packages/core/tests/v2_server.rsindex b16b1df7..d81f76fa 100644--- a/packages/core/tests/v2_server.rs+++ b/packages/core/tests/v2_server.rs@@ -441,6 +441,118 @@ async fn test_upload_with_mismatched_sha256() {assert_status(result, 422);}+#[tokio::test]+async fn test_upload_retry_after_mismatched_sha256() {+ let server = start_test_server(None, true, None).await;+ let client = LsHttpClientV2::try_new_without_cert().unwrap();++ let bytes = b"hello".to_vec();+ let corrupted = b"hellO".to_vec();+ let mut file = file_dto("file-a", "a.bin", bytes.len() as u64);+ file.sha256 = Some(sha256_hex(&bytes));++ let response = client+ .prepare_upload(+ ProtocolType::Http,+ "127.0.0.1",+ server.port,+ None,+ prepare_upload_request(&[file]),+ None,+ )+ .await+ .unwrap()+ .response+ .unwrap();++ // The first upload is rejected because of the checksum mismatch ...+ let result = upload_bytes(+ &client,+ server.port,+ &response.session_id,+ "file-a",+ &response.files["file-a"],+ &corrupted,+ )+ .await;+ assert_status(result, 422);++ // ... but a retry with the same token is accepted.+ upload_bytes(+ &client,+ server.port,+ &response.session_id,+ "file-a",+ &response.files["file-a"],+ &bytes,+ )+ .await+ .unwrap();++ assert_eq!(server.received.lock().await["file-a"], bytes);++ tokio::time::sleep(Duration::from_millis(100)).await;+ let session_ends = server.session_ends.lock().await;+ assert_eq!(session_ends.len(), 1);+ assert_eq!(session_ends[0].0, response.session_id);+ assert!(matches!(session_ends[0].1, SessionEndReasonV2::Finished));+}++#[tokio::test]+async fn test_upload_mismatched_sha256_attempts_exhausted() {+ let server = start_test_server(None, true, None).await;+ let client = LsHttpClientV2::try_new_without_cert().unwrap();++ let bytes = b"hello".to_vec();+ let corrupted = b"hellO".to_vec();+ let mut file = file_dto("file-a", "a.bin", bytes.len() as u64);+ file.sha256 = Some(sha256_hex(&bytes));++ let response = client+ .prepare_upload(+ ProtocolType::Http,+ "127.0.0.1",+ server.port,+ None,+ prepare_upload_request(&[file]),+ None,+ )+ .await+ .unwrap()+ .response+ .unwrap();++ // Three attempts are allowed, each failing with a checksum mismatch.+ for _ in 0..3 {+ let result = upload_bytes(+ &client,+ server.port,+ &response.session_id,+ "file-a",+ &response.files["file-a"],+ &corrupted,+ )+ .await;+ assert_status(result, 422);+ }++ // The file is now failed and the session is over; further attempts are rejected.+ let result = upload_bytes(+ &client,+ server.port,+ &response.session_id,+ "file-a",+ &response.files["file-a"],+ &bytes,+ )+ .await;+ assert_status(result, 403);++ tokio::time::sleep(Duration::from_millis(100)).await;+ let session_ends = server.session_ends.lock().await;+ assert_eq!(session_ends.len(), 1);+}+#[tokio::test]async fn test_upload_saved_to_path_by_server() {let save_dir = std::env::temp_dir().join(format!("localsend-test-{}", uuid::Uuid::new_v4()));diff --git a/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dart b/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dartindex a34ec412..fc589838 100644--- a/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dart+++ b/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dart@@ -11,6 +11,7 @@ import 'package:localsend_isolates/src/isolate/child/sync_provider.dart';import 'package:localsend_isolates/src/isolate/dto/send_to_isolate_data.dart';import 'package:localsend_isolates/src/task/server/file_saver.dart';import 'package:localsend_isolates/src/task/server/http_server.dart';+import 'package:localsend_isolates/util/future_queue.dart';import 'package:localsend_isolates/util/rust.dart';import 'package:logging/logging.dart';import 'package:refena_flutter/refena_flutter.dart';@@ -336,6 +337,12 @@ class _ReceiveSession {/// files of the session.final Set<String> createdDirectories = {};+ /// One queue per file ID, so that uploads of the same file do not overlap.+ ///+ /// A sender may upload the same file again after it was rejected because of+ /// a checksum mismatch.+ final Map<String, FutureQueue> uploads = {};+_ReceiveSession(this.config);}@@ -444,25 +451,31 @@ Future<void> setupHttpServerIsolate(break;}- emit(- HttpServerFileUploadEvent(- sessionId: sessionId,- fileId: fileId,- file: file,- ),+ // Files may be uploaded concurrently, so the event loop must+ // not block. Attempts of the same file are queued instead,+ // see [_ReceiveSession.uploads].+ final queue = session.uploads.putIfAbsent(+ fileId,+ () => FutureQueue(onError: (e, st) => _logger.severe('Unexpected error while receiving file $fileId', e, st)),);-- // Files may be uploaded concurrently, so the event loop must not block.- unawaited(- _handleFileUpload(+ queue.add(() async {+ emit(+ HttpServerFileUploadEvent(+ sessionId: sessionId,+ fileId: fileId,+ file: file,+ ),+ );++ await _handleFileUpload(ref: ref,session: session,sessionId: sessionId,fileId: fileId,file: file,emit: emit,- ),- );+ );+ });case RsServerEvent_SessionEnd(:final sessionId, :final reason):if (holder.session?.config.sessionId == sessionId) {holder.session = null;@@ -589,10 +602,23 @@ Future<void> _handleFileUpload({final isImage = dartFile.fileType == FileType.image;final shouldSaveToGallery = config.saveToGallery && (isImage || dartFile.fileType == FileType.video);- try {- _logger.info('Saving ${dartFile.fileName}');+ void emitFailed(Object e) {+ emit(+ HttpServerFileUploadResultEvent(+ sessionId: sessionId,+ fileId: fileId,+ path: null,+ savedToGallery: false,+ error: e.humanErrorMessage,+ ),+ );+ }++ _logger.info('Saving ${dartFile.fileName}');- final target = await prepareFileSaveTarget(+ final FileSaveTarget target;+ try {+ target = await prepareFileSaveTarget(destinationDirectory: config.destinationDirectory,cacheDirectory: config.cacheDirectory,fileName: desiredName,@@ -601,7 +627,22 @@ Future<void> _handleFileUpload({createdDirectories: session.createdDirectories,androidSdkInt: config.androidSdkInt,);+ } catch (e, st) {+ _logger.severe('Failed to prepare save target', e, st);+ // The Rust server is still waiting for the target; rejecting fails the+ // sender's request which would otherwise hang forever.+ try {+ await ref.read(httpServerProvider).rejectFileUpload(sessionId: sessionId, fileId: fileId);+ } catch (e) {+ _logger.warning('Failed to reject file upload', e);+ }++ emitFailed(e);+ return;+ }++ try {// The Rust server writes the file and reports the progress.final progressStream = ref.read(httpServerProvider)@@ -621,7 +662,20 @@ Future<void> _handleFileUpload({),);}+ } catch (e, st) {+ _logger.severe('Failed to save file', e, st);++ // Delete the partial (or checksum-mismatched) file so a retried upload+ // gets the same file name again instead of a renamed one.+ await deleteFileSaveTarget(target);+ emitFailed(e);+ return;+ }++ // The file is fully received and the sender was already told success,+ // so failures from here on must not delete the file.+ try {await applyFileTimestamps(target: target,lastModified: dartFile.metadata?.lastModified,@@ -653,26 +707,7 @@ Future<void> _handleFileUpload({),);} catch (e, st) {- _logger.severe('Failed to save file', e, st);-- // If the failure happened before the upload target was dispatched- // (e.g. preparing the save target failed), the Rust server is still- // waiting for it and the sender's request would hang forever.- // Rejecting fails the request; a no-op if the target was already sent.- try {- await ref.read(httpServerProvider).rejectFileUpload(sessionId: sessionId, fileId: fileId);- } catch (e) {- _logger.warning('Failed to reject file upload', e);- }-- emit(- HttpServerFileUploadResultEvent(- sessionId: sessionId,- fileId: fileId,- path: null,- savedToGallery: false,- error: e.humanErrorMessage,- ),- );+ _logger.severe('Failed to post-process file', e, st);+ emitFailed(e);}}diff --git a/packages/localsend_isolates/lib/src/isolate/child/upload_isolate.dart b/packages/localsend_isolates/lib/src/isolate/child/upload_isolate.dartindex 01b0a1d0..1a8dbc65 100644--- a/packages/localsend_isolates/lib/src/isolate/child/upload_isolate.dart+++ b/packages/localsend_isolates/lib/src/isolate/child/upload_isolate.dart@@ -2,6 +2,7 @@ import 'package:flutter/services.dart';import 'package:localsend_isolates/isolate.dart';import 'package:localsend_isolates/model/device.dart';import 'package:localsend_isolates/rust/api/cancel.dart';+import 'package:localsend_isolates/rust/api/http.dart';import 'package:localsend_isolates/src/isolate/child/main.dart';import 'package:localsend_isolates/src/isolate/dto/send_to_isolate_data.dart';import 'package:localsend_isolates/src/task/upload/http_upload.dart';@@ -14,6 +15,12 @@ import 'package:typed_isolates/typed_isolates.dart';/// How many files of a [HttpUploadFilesTask] are uploaded in parallel.const _concurrency = 2;+/// How often a single file is uploaded at most when the receiver keeps+/// rejecting it with a checksum mismatch (HTTP 422).+/// Must not exceed MAX_UPLOAD_ATTEMPTS of the Rust server which stops+/// accepting retries at some point.+const _maxUploadAttempts = 3;+sealed class BaseHttpUploadTask {}class HttpUploadFile {@@ -146,32 +153,46 @@ Future<void> setupHttpUploadIsolate(try {final filePath = file.filePath;final isContentUri = filePath?.startsWith('content://') ?? false;- final fileDescriptor = isContentUri ? await getFileDescriptorAndroid(uri: filePath!) : null;-- await ref- .read(httpUploadProvider)- .upload(- stream: filePath == null && file.fileBytes != null ? Stream.value(file.fileBytes!) : null,- path: !isContentUri ? filePath : null,- fileDescriptor: fileDescriptor,- contentLength: file.fileSize,- target: uploadTask.device,- remoteSessionId: uploadTask.remoteSessionId,- fileId: file.fileId,- token: file.remoteFileToken,- onSendProgress: (progress) {- sendToMain(- IsolateTaskStreamResult.event(- id: task.id,- data: HttpUploadFileProgressEvent(- fileId: file.fileId,- progress: progress,- ),- ),++ for (var attempt = 1; ; attempt++) {+ // The file descriptor is consumed by the upload, so a fresh one+ // is needed for every attempt.+ final fileDescriptor = isContentUri ? await getFileDescriptorAndroid(uri: filePath!) : null;++ try {+ await ref+ .read(httpUploadProvider)+ .upload(+ stream: filePath == null && file.fileBytes != null ? Stream.value(file.fileBytes!) : null,+ path: !isContentUri ? filePath : null,+ fileDescriptor: fileDescriptor,+ contentLength: file.fileSize,+ target: uploadTask.device,+ remoteSessionId: uploadTask.remoteSessionId,+ fileId: file.fileId,+ token: file.remoteFileToken,+ onSendProgress: (progress) {+ sendToMain(+ IsolateTaskStreamResult.event(+ id: task.id,+ data: HttpUploadFileProgressEvent(+ fileId: file.fileId,+ progress: progress,+ ),+ ),+ );+ },+ cancelToken: cancelToken,);- },- cancelToken: cancelToken,- );+ break;+ } on RsHttpClientError_StatusCode catch (e) {+ if (e.status != 422 || attempt >= _maxUploadAttempts) {+ rethrow;+ }+ // The receiver discarded the file because its checksum did not+ // match (e.g. the file changed while being read). Send it again.+ }+ }sendToMain(IsolateTaskStreamResult.event(diff --git a/packages/localsend_isolates/lib/src/task/server/file_saver.dart b/packages/localsend_isolates/lib/src/task/server/file_saver.dartindex 94bb44b4..f306054e 100644--- a/packages/localsend_isolates/lib/src/task/server/file_saver.dart+++ b/packages/localsend_isolates/lib/src/task/server/file_saver.dart@@ -93,6 +93,32 @@ Future<FileSaveTarget> prepareFileSaveTarget({);}+/// Deletes the file behind [target].+///+/// Used when a file could not be received completely, so that a retry of the+/// same file gets the original file name again instead of a numbered one.+///+/// Failures are logged and swallowed: a leftover file is not worth failing+/// the transfer for.+Future<void> deleteFileSaveTarget(FileSaveTarget target) async {+ // SAF targets are written through a file descriptor and must be deleted+ // through the Storage Access Framework, addressed by their document URI.+ final uri = target.path ?? target.displayPath;+ try {+ if (uri.startsWith('content://')) {+ await android_channel.deleteFileAndroid(uri: uri);+ return;+ }++ final file = File(uri);+ if (await file.exists()) {+ await file.delete();+ }+ } catch (e) {+ _logger.warning('Could not delete file at $uri', e);+ }+}+/// Applies the file timestamps after the file has been written to a plain path.Future<void> applyFileTimestamps({required FileSaveTarget target,diff --git a/packages/localsend_isolates/lib/util/android_channel.dart b/packages/localsend_isolates/lib/util/android_channel.dartindex 95f25eb9..33d856f5 100644--- a/packages/localsend_isolates/lib/util/android_channel.dart+++ b/packages/localsend_isolates/lib/util/android_channel.dart@@ -84,3 +84,14 @@ Future<CreatedFileAndroid> createFileAndroid({fileDescriptor: result['fd'] as int,);}++/// Deletes the document at [uri], e.g. a file created by [createFileAndroid].+///+/// Returns whether the document has been deleted. A document that does not+/// exist (anymore) returns `false` instead of throwing.+Future<bool> deleteFileAndroid({required String uri}) async {+ final deleted = await _methodChannel.invokeMethod<bool>('deleteFile', {+ 'uri': uri,+ });+ return deleted ?? false;+}