Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

Fix download interruption reset

dev.salmontechb75fd3ded54d
diff --git a/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt
index 560cef66..6f1245ae 100644
--- a/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt
@@ -65,6 +65,8 @@ class DownloadManagerImpl @Inject constructor(
) : DownloadManager {
private val activeJobs = ConcurrentHashMap<String, Job>()
+ private val activeCalls = ConcurrentHashMap<String, okhttp3.Call>()
+ private val playbackPausedIds = ConcurrentHashMap.newKeySet<String>()
private val schedulerMutex = Mutex()
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@Volatile private var playbackActive = false
@@ -149,6 +151,7 @@ class DownloadManagerImpl @Inject constructor(
override suspend fun cancelDownload(id: String): Result<Unit> {
return runCatching {
+ activeCalls.remove(id)?.cancel()
activeJobs.remove(id)?.cancelAndJoin()
downloadDao.getByIdOnce(id)?.let { entity ->
downloadDao.update(entity.copy(status = DownloadStatus.CANCELLED))
@@ -171,6 +174,7 @@ class DownloadManagerImpl @Inject constructor(
override suspend fun deleteDownload(id: String): Result<Unit> {
return runCatching {
+ activeCalls.remove(id)?.cancel()
activeJobs.remove(id)?.cancelAndJoin()
downloadDao.getByIdOnce(id)?.let { deleteOutput(it) }
downloadDao.deleteById(id)
@@ -236,7 +240,9 @@ class DownloadManagerImpl @Inject constructor(
}
private suspend fun pauseActiveDownloadsForPlayback() {
- activeJobs.values.toList().forEach { job ->
+ activeJobs.entries.toList().forEach { (id, job) ->
+ playbackPausedIds.add(id)
+ activeCalls.remove(id)?.cancel()
job.cancel(PlaybackStartedCancellation())
job.join()
}
@@ -265,7 +271,9 @@ class DownloadManagerImpl @Inject constructor(
requestBuilder.header("User-Agent", userAgent)
}
if (resumeFrom > 0L) requestBuilder.header("Range", "bytes=$resumeFrom-")
- okHttpClient.newCall(requestBuilder.build()).execute().use { response ->
+ val call = okHttpClient.newCall(requestBuilder.build())
+ activeCalls[initial.id] = call
+ call.execute().use { response ->
if (!response.isSuccessful) throw HttpDownloadException(response.code)
val body = response.body ?: error("Empty response body")
val rangeAccepted = resumeFrom > 0L && response.code == HttpURLConnection.HTTP_PARTIAL
@@ -342,21 +350,8 @@ class DownloadManagerImpl @Inject constructor(
}
} catch (cancelled: CancellationException) {
downloadDao.getByIdOnce(initial.id)?.let { entity ->
- if (cancelled is PlaybackStartedCancellation) {
- deleteOutput(current)
- downloadDao.update(
- current.copy(
- outputUri = null,
- outputDisplayPath = null,
- status = DownloadStatus.PAUSED,
- bytesWritten = 0L,
- totalBytes = null,
- supportsResume = false,
- retryCount = 0,
- completedAt = null,
- failureReason = "Waiting for playback to stop"
- )
- )
+ if (cancelled is PlaybackStartedCancellation || playbackPausedIds.contains(initial.id)) {
+ resetInterruptedDownload(current, DownloadStatus.PAUSED, "Waiting for playback to stop")
} else {
downloadDao.update(entity.copy(status = DownloadStatus.CANCELLED))
}
@@ -373,8 +368,16 @@ class DownloadManagerImpl @Inject constructor(
downloadDao.update(reset)
captureDownload(reset)
} catch (error: Throwable) {
- if (downloadDao.getByIdOnce(initial.id) != null) handleDownloadFailure(current, error)
+ if (downloadDao.getByIdOnce(initial.id) != null) {
+ if (playbackPausedIds.contains(initial.id)) {
+ resetInterruptedDownload(current, DownloadStatus.PAUSED, "Waiting for playback to stop")
+ } else {
+ handleDownloadFailure(current, error)
+ }
+ }
} finally {
+ activeCalls.remove(initial.id)
+ playbackPausedIds.remove(initial.id)
activeJobs.remove(initial.id)
startNextQueued()
}
@@ -383,12 +386,12 @@ class DownloadManagerImpl @Inject constructor(
private suspend fun handleDownloadFailure(entity: DownloadEntity, error: Throwable) {
val reason = error.message ?: error::class.java.simpleName
if (!isTransient(error) || entity.retryCount >= MAX_RETRIES) {
- downloadDao.update(entity.copy(status = DownloadStatus.FAILED, failureReason = reason))
+ resetInterruptedDownload(entity, DownloadStatus.FAILED, reason)
return
}
val retryCount = entity.retryCount + 1
- downloadDao.update(entity.copy(status = DownloadStatus.PAUSED, retryCount = retryCount, failureReason = reason))
+ resetInterruptedDownload(entity, DownloadStatus.PAUSED, reason, retryCount)
applicationScope.launch(Dispatchers.IO) {
delay(backoffMs(retryCount))
downloadDao.getByIdOnce(entity.id)
@@ -398,6 +401,28 @@ class DownloadManagerImpl @Inject constructor(
}
}
+ private suspend fun resetInterruptedDownload(
+ entity: DownloadEntity,
+ status: DownloadStatus,
+ reason: String,
+ retryCount: Int = 0
+ ) {
+ deleteOutput(entity)
+ downloadDao.update(
+ entity.copy(
+ outputUri = null,
+ outputDisplayPath = null,
+ status = status,
+ bytesWritten = 0L,
+ totalBytes = null,
+ supportsResume = false,
+ retryCount = retryCount,
+ completedAt = null,
+ failureReason = reason
+ )
+ )
+ }
+
private fun hasAppendTarget(entity: DownloadEntity): Boolean {
val path = entity.outputDisplayPath
return !entity.outputUri.isNullOrBlank() || (!path.isNullOrBlank() && File(path).exists())
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 09544505..b459c18f 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -13,6 +13,7 @@ All notable product changes are recorded in this document.
- Fixed completed local download playback so `content://`/`file://` files do not consume the provider download lease and do not pause active downloads.
- Fixed failed download Resume to clear partial output and restart through the scheduler.
+- Fixed provider playback interruptions leaving downloads stuck in `DOWNLOADING` by cancelling the active OkHttp call and resetting the partial row to zero-byte `PAUSED` state.
## [1.0.12] - 2026-05-15
diff --git a/docs/download-feature-handoff.md b/docs/download-feature-handoff.md
index 470d357b..e4a93603 100644
--- a/docs/download-feature-handoff.md
+++ b/docs/download-feature-handoff.md
@@ -36,7 +36,7 @@ LocalForge project `streamvalutfork` is back to completed with no follow-up back
- `DownloadManagerImpl` captures bytes with OkHttp and updates `DownloadEntity` status/progress.
- `DownloadEntity` stores stable source metadata (`sourceStreamUrl`, `sourceStreamId`, `containerExtension`) so restarted downloads can resolve a fresh provider URL instead of reusing a stale one-time link.
- Downloads are FIFO and single-provider-stream by design.
-- If provider-backed VOD playback starts during a download, the active partial file is deleted, progress resets to zero, and the download waits until playback stops before restarting from byte 0 with a fresh URL.
+- If provider-backed VOD playback starts during a download, the active capture coroutine and OkHttp call are cancelled, the active partial file is deleted, progress resets to zero, and the download waits until playback stops before restarting from byte 0 with a fresh URL.
- Playing a completed local download from `content://` or `file://` never pauses the queue, whether the file opens in StreamVault's internal player or an external player.
- `DownloadForegroundService` observes the active download row and updates notification text.
- Downloads tab lists rows, shows poster/status/progress/size, opens completed files via `ACTION_VIEW`, offers Resume for failed rows, and deletes both DB row and local output where possible.
@@ -70,5 +70,6 @@ app/build/outputs/apk/debug/app-debug.apk
- Manual device test still needed with a real provider stream: tap Download, verify notification/progress, verify completed item opens in an external/internal video handler, verify delete removes the file, verify provider playback pauses an active download and restarts it from 0 after playback stops.
- Process-death resume is not implemented. Active capture runs in application-scope coroutine plus foreground service observer; if Android kills the process, incomplete rows remain and should be retried or marked failed in a future feature.
- Pause UI is not implemented. Failed rows expose Resume, which deletes any partial output, resets progress, and restarts through the FIFO scheduler with fresh provider URL resolution.
+- A row stuck in `DOWNLOADING` after provider playback usually indicates interruption handling failed before the active OkHttp call was cancelled. `DownloadManagerImpl` now tracks active calls and resets provider-playback interruptions back to `PAUSED` with zero bytes.
- The fallback app-external storage path is private to the app; use the Downloads screen to open files or choose a SAF folder for user-visible storage.
- Project-wide `:app:lintDebug` still fails from existing lint debt, including API-level/manifest/test/l10n issues. Compile, smoke, and debug assemble pass.