diff --git a/CHANGELOG.md b/CHANGELOG.md index b66e7f8..726bbf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +- Add ability to abort a file download, via `IONFLTRController.abortTransfer` and the new `IONFLTRDownloadOptions.id`. + ## 1.0.3 ### 2026-01-08 diff --git a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/IONFLTRController.kt b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/IONFLTRController.kt index b568c9a..9c7d09a 100644 --- a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/IONFLTRController.kt +++ b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/IONFLTRController.kt @@ -5,15 +5,19 @@ import io.ionic.libs.ionfiletransferlib.helpers.FileToUploadInfo import io.ionic.libs.ionfiletransferlib.helpers.IONFLTRConnectionHelper import io.ionic.libs.ionfiletransferlib.helpers.IONFLTRFileHelper import io.ionic.libs.ionfiletransferlib.helpers.IONFLTRInputsValidator +import io.ionic.libs.ionfiletransferlib.helpers.IONFLTRTransferHandle import io.ionic.libs.ionfiletransferlib.helpers.assertSuccessHttpResponse import io.ionic.libs.ionfiletransferlib.helpers.runCatchingIONFLTRExceptions import io.ionic.libs.ionfiletransferlib.helpers.use import io.ionic.libs.ionfiletransferlib.model.IONFLTRDownloadOptions +import io.ionic.libs.ionfiletransferlib.model.IONFLTRException import io.ionic.libs.ionfiletransferlib.model.IONFLTRProgressStatus import io.ionic.libs.ionfiletransferlib.model.IONFLTRTransferComplete import io.ionic.libs.ionfiletransferlib.model.IONFLTRTransferResult import io.ionic.libs.ionfiletransferlib.model.IONFLTRUploadOptions import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn @@ -23,6 +27,7 @@ import java.io.File import java.io.FileOutputStream import java.net.HttpURLConnection import java.net.URI +import java.util.concurrent.ConcurrentHashMap /** * Entry point in IONFileTransferLib-Android @@ -40,6 +45,11 @@ class IONFLTRController internal constructor( connectionHelper = IONFLTRConnectionHelper() ) + /** + * The transfers that are currently in progress and were given an id, by id. + */ + private val activeTransfers = ConcurrentHashMap() + companion object { private const val BUFFER_SIZE = 8192 // 8KB buffer size private const val BOUNDARY = "++++IONFLTRBoundary" @@ -50,41 +60,87 @@ class IONFLTRController internal constructor( /** * Downloads a file from a remote URL to a local file path. * + * The download can be aborted by calling [abortTransfer] with the id in + * [IONFLTRDownloadOptions.id], which interrupts the download immediately. + * Cancelling the coroutine that is collecting the flow also stops the download, + * although only once the chunk being read at that moment is done. + * * @param options The download options including URL and file path - * @return A Flow of [IONFLTRTransferResult] to track progress and completion + * @return A Flow of [IONFLTRTransferResult] to track progress and completion; + * it fails with [IONFLTRException.TransferAborted] if the download is aborted via [abortTransfer] */ fun downloadFile(options: IONFLTRDownloadOptions): Flow = flow { - runCatchingIONFLTRExceptions { - // Prepare for download - val (targetFile, connection) = prepareForDownload(options) - - connection.use { conn -> - // Execute the download and handle response - val contentLength = beginDownload(conn) - - // Perform the actual file download with progress reporting - val totalBytesRead = downloadFileWithProgress( - connection = conn, - targetFile = targetFile, - contentLength = contentLength, - emit = { emit(it) } - ) + val handle = registerTransfer(options.id) + var targetFile: File? = null + try { + runCatchingIONFLTRExceptions { + handle.throwIfAborted() + + // Prepare for download + val (file, connection) = prepareForDownload(options) + targetFile = file + handle.setConnection(connection) + + connection.use { conn -> + // Execute the download and handle response + val contentLength = beginDownload(conn) + + // Perform the actual file download with progress reporting + val totalBytesRead = downloadFileWithProgress( + connection = conn, + targetFile = file, + contentLength = contentLength, + handle = handle, + emit = { emit(it) } + ) - // Emit completion - emit( - IONFLTRTransferResult.Complete( - IONFLTRTransferComplete( - totalBytes = totalBytesRead, - responseCode = conn.responseCode.toString(), - responseBody = null, - headers = conn.headerFields + // Emit completion + emit( + IONFLTRTransferResult.Complete( + IONFLTRTransferComplete( + totalBytes = totalBytesRead, + responseCode = conn.responseCode.toString(), + responseBody = null, + headers = conn.headerFields + ) ) ) - ) + } + }.getOrElse { error -> + // an abort closes the connection, so the resulting error is replaced by TransferAborted + val mappedError = handle.mapErrorIfAborted(error) + if (mappedError is IONFLTRException.TransferAborted) { + // the partially downloaded file is of no use to anyone + targetFile?.let { fileHelper.deleteFile(it) } + } + throw mappedError } - }.getOrThrow() + } finally { + options.id?.let { activeTransfers.remove(it, handle) } + } }.flowOn(Dispatchers.IO) + /** + * Aborts an ongoing transfer that was started with the provided id. + * + * The flow of the aborted transfer fails with [IONFLTRException.TransferAborted], + * and any partially downloaded file is deleted. + * + * @param id The id that was provided in [IONFLTRDownloadOptions.id] + * @return true if there was an ongoing transfer with the provided id, false otherwise + */ + fun abortTransfer(id: String): Boolean = + activeTransfers[id]?.also { it.abort() } != null + + /** + * @param id The id of the transfer, if any + * @return the handle to use for tracking (and aborting) the transfer + */ + private fun registerTransfer(id: String?): IONFLTRTransferHandle = + IONFLTRTransferHandle(id).also { handle -> + id?.let { activeTransfers[it] = handle } + } + /** * Uploads a file from a local path to a remote URL. * @@ -181,6 +237,7 @@ class IONFLTRController internal constructor( connection: HttpURLConnection, targetFile: File, contentLength: Long, + handle: IONFLTRTransferHandle, emit: suspend (IONFLTRTransferResult) -> Unit ): Long = BufferedInputStream(connection.inputStream).use { inputStream -> FileOutputStream(targetFile).use { fileOut -> @@ -191,6 +248,8 @@ class IONFLTRController internal constructor( var totalBytesRead: Long = 0 while (inputStream.read(buffer).also { bytesRead = it } != -1) { + handle.throwIfAborted() + currentCoroutineContext().ensureActive() outputStream.write(buffer, 0, bytesRead) totalBytesRead += bytesRead diff --git a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRExceptionsMapper.kt b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRExceptionsMapper.kt index 48279bf..172d45c 100644 --- a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRExceptionsMapper.kt +++ b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRExceptionsMapper.kt @@ -5,12 +5,15 @@ import java.io.FileNotFoundException import java.io.IOException import java.net.ConnectException import java.net.SocketTimeoutException +import kotlin.coroutines.cancellation.CancellationException internal inline fun T.runCatchingIONFLTRExceptions(block: T.() -> Unit): Result = runCatching(block).mapErrorToIONFLTRException() internal fun Result.mapErrorToIONFLTRException(): Result = exceptionOrNull()?.let { throwable -> + // coroutine cancellation must never be swallowed, so that structured concurrency is kept + if (throwable is CancellationException) throw throwable val mappedException: IONFLTRException = when (throwable) { is IONFLTRException -> throwable is FileNotFoundException -> IONFLTRException.FileDoesNotExist(throwable) diff --git a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRFileHelper.kt b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRFileHelper.kt index 5c4380e..1dcceab 100644 --- a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRFileHelper.kt +++ b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRFileHelper.kt @@ -98,6 +98,21 @@ internal class IONFLTRFileHelper(val contentResolver: ContentResolver) { } } + /** + * Deletes a file, ignoring any error while doing so. + * + * Used to clean up partially downloaded files when a download is aborted. + * + * @param file The file to delete + */ + fun deleteFile(file: File) { + try { + file.delete() + } catch (ex: SecurityException) { + // there is no partial file to clean up if it cannot be accessed + } + } + /** * Gets the size of the that the content uri is pointing to. * diff --git a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRTransferHandle.kt b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRTransferHandle.kt new file mode 100644 index 0000000..5c14cca --- /dev/null +++ b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/helpers/IONFLTRTransferHandle.kt @@ -0,0 +1,69 @@ +package io.ionic.libs.ionfiletransferlib.helpers + +import io.ionic.libs.ionfiletransferlib.model.IONFLTRException +import java.net.HttpURLConnection + +/** + * Holds the state of a single in-flight transfer, so that it can be aborted from another thread. + * + * Aborting marks the transfer as aborted and disconnects the underlying connection, which unblocks + * any read/write that is currently in progress. + */ +internal class IONFLTRTransferHandle(val id: String?) { + + @Volatile + private var aborted: Boolean = false + + @Volatile + private var connection: HttpURLConnection? = null + + val isAborted: Boolean get() = aborted + + /** + * Associates the connection being used by the transfer with this handle. + * + * If the transfer was already aborted before the connection was created, + * the connection is disconnected right away. + */ + fun setConnection(connection: HttpURLConnection) { + this.connection = connection + if (aborted) { + disconnectQuietly() + } + } + + /** + * Marks the transfer as aborted and disconnects the underlying connection, if there is one. + */ + fun abort() { + aborted = true + disconnectQuietly() + } + + /** + * Disconnects the underlying connection, which unblocks any read that is in progress. + */ + private fun disconnectQuietly() { + try { + connection?.disconnect() + } catch (ex: Exception) { + // the connection is being discarded anyway; nothing to do here + } + } + + /** + * @throws IONFLTRException.TransferAborted if the transfer was aborted + */ + fun throwIfAborted() { + if (aborted) { + throw IONFLTRException.TransferAborted(id) + } + } + + /** + * Replaces an error that was caused by aborting the transfer (e.g. the socket being closed + * mid-read) with [IONFLTRException.TransferAborted]. + */ + fun mapErrorIfAborted(error: Throwable): Throwable = + if (aborted) IONFLTRException.TransferAborted(id) else error +} diff --git a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/model/IONFLTRException.kt b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/model/IONFLTRException.kt index 57f2990..742a077 100644 --- a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/model/IONFLTRException.kt +++ b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/model/IONFLTRException.kt @@ -33,6 +33,9 @@ sealed class IONFLTRException( class TransferError(override val cause: Throwable?) : IONFLTRException("Error during file transfer", cause) + class TransferAborted(val id: String?) : + IONFLTRException("The file transfer was aborted.") + class UnknownError(override val cause: Throwable?) : IONFLTRException("An unknown error occurred while trying to run the operation", cause) } \ No newline at end of file diff --git a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/model/IONFLTRTransferOptions.kt b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/model/IONFLTRTransferOptions.kt index e5e1fd0..0af05b6 100644 --- a/src/main/kotlin/io/ionic/libs/ionfiletransferlib/model/IONFLTRTransferOptions.kt +++ b/src/main/kotlin/io/ionic/libs/ionfiletransferlib/model/IONFLTRTransferOptions.kt @@ -8,11 +8,14 @@ import javax.net.ssl.SSLSocketFactory * @property url The URL to download the file from * @property filePath The local path where the downloaded file will be saved * @property httpOptions Additional HTTP options for the download request + * @property id Optional identifier for the download; pass it to + * [io.ionic.libs.ionfiletransferlib.IONFLTRController.abortTransfer] to abort the download */ data class IONFLTRDownloadOptions( val url: String, val filePath: String, - val httpOptions: IONFLTRTransferHttpOptions = IONFLTRTransferHttpOptions("GET") + val httpOptions: IONFLTRTransferHttpOptions = IONFLTRTransferHttpOptions("GET"), + val id: String? = null ) /**