diff --git a/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadDecisions.kt b/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadDecisions.kt index 43d71fb64..2d60bdada 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadDecisions.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadDecisions.kt @@ -11,6 +11,7 @@ import io.putdotio.android.playback.OriginalVideoPolicy import io.putdotio.android.settings.StreamingMethod import io.putdotio.sdk.PutioClient import io.putdotio.sdk.files.PutioFileType +import java.io.Closeable internal fun mobileDirectPlayDownloads(context: Context, client: PutioClient): DirectPlayDownloads = DirectPlayDownloads( @@ -51,6 +52,35 @@ internal val DownloadEntry.awaitsDirectPlay: Boolean get() = status == DownloadStatus.Queued && !accepted && !removing && type == PutioFileType.VIDEO && artifact == DownloadArtifact.MP4 +internal fun DownloadEntry.redecidesDirectPlay(failure: DownloadStatus? = status): Boolean = + directPlayUnanswered && !removing && artifact == DownloadArtifact.MP4 && + failure == DIRECT_PLAY_REFUSAL + +internal val DIRECT_PLAY_REFUSAL = DownloadStatus.Failed(DownloadFailureReason.UNAVAILABLE, 0L) + +internal class DirectPlayRedeciders { + private val holders = mutableMapOf() + + fun hold(userId: Long): Closeable { + synchronized(holders) { holders[userId] = (holders[userId] ?: 0) + 1 } + var released = false + return Closeable { + synchronized(holders) { + if (released) return@Closeable + released = true + val left = holders.getValue(userId) - 1 + if (left == 0) holders.remove(userId) else holders[userId] = left + } + } + } + + fun holds(userId: Long): Boolean = synchronized(holders) { userId in holders } + + companion object { + val shared = DirectPlayRedeciders() + } +} + internal class DownloadStart(val entry: DownloadEntry, val decides: Boolean) { val asksDirectPlay: Boolean get() = decides && entry.resolvesDirectPlay } @@ -65,8 +95,15 @@ internal fun DownloadEntry.retryStart(): DownloadStart = internal fun DownloadEntry.decidedBy(directPlay: DirectPlayDownload?): DownloadEntry { val artifact = directPlay?.artifact return when { - directPlay == null -> this - artifact == null -> copy(status = DownloadStatus.Failed(DownloadFailureReason.UNAVAILABLE, 0L)) - else -> copy(artifact = artifact, subtitles = directPlay.subtitles.mapNotNull { it.toDownloadSubtitle() }) + directPlay == null -> copy(directPlayUnanswered = true) + artifact == null -> copy( + status = DownloadStatus.Failed(DownloadFailureReason.UNAVAILABLE, 0L), + directPlayUnanswered = false, + ) + else -> copy( + artifact = artifact, + subtitles = directPlay.subtitles.mapNotNull { it.toDownloadSubtitle() }, + directPlayUnanswered = false, + ) } } diff --git a/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadModels.kt b/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadModels.kt index 9655902b2..7756d7902 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadModels.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadModels.kt @@ -111,6 +111,7 @@ internal data class DownloadEntry( val pauseRequested: Boolean = false, val subtitles: List = emptyList(), val directPlayChosen: Boolean = false, + val directPlayUnanswered: Boolean = false, ) { val isCompleted: Boolean get() = status is DownloadStatus.Completed val canRetry: Boolean get() = status is DownloadStatus.Failed || status is DownloadStatus.Missing diff --git a/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadsController.kt b/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadsController.kt index 2c2ca6a57..196f0a563 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadsController.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/downloads/DownloadsController.kt @@ -61,6 +61,7 @@ internal class DownloadsController( init { scope.launch { for (pending in starts) startInOrder(pending) } scope.launch { + var refusals = emptySet() store.entries.collect { entries -> val running = entries.filter { it.status is DownloadStatus.Downloading } .mapTo(mutableSetOf()) { it.fileId } @@ -68,6 +69,9 @@ internal class DownloadsController( val next = mutableState.value.withEntries(entries) mutableState.value = next.copy(speeds = next.speeds.filterKeys { it in running }) } + val refused = entries.filter { it.status == DIRECT_PLAY_REFUSAL }.mapTo(mutableSetOf()) { it.fileId } + entries.filter { it.fileId !in refusals && it.redecidesDirectPlay() }.forEach { redecide(it.fileId) } + refusals = refused } } enqueue { @@ -144,11 +148,22 @@ internal class DownloadsController( return true } + private fun redecide(fileId: FilesItemId) { + enqueue { + val refused = store.find(fileId)?.takeIf { it.redecidesDirectPlay() && accepts(fileId, retry = true) } + ?: return@enqueue + val queued = refused.copy(status = DownloadStatus.Queued, queuedAt = clock(), pauseRequested = false) + store.upsert(queued) + queueStart(queued, decide = true, replaced = refused.copy(directPlayUnanswered = false), redecides = true) + } + } + private fun queueStart( entry: DownloadEntry, decide: Boolean, replaced: DownloadEntry? = null, startup: Boolean = false, + redecides: Boolean = false, ) { val directPlay = if (decide && entry.resolvesDirectPlay) { scope.async { @@ -159,7 +174,7 @@ internal class DownloadsController( } else { null } - val pending = PendingStart(entry, directPlay, replaced, startup) + val pending = PendingStart(entry, directPlay, replaced, startup, redecides) latestStarts[entry.fileId] = pending starts.trySend(pending) } @@ -174,9 +189,11 @@ internal class DownloadsController( synchronized(lock) { it.fileId !in mutableState.value.removing } && (!pending.startup || it.awaitsDirectPlay && !engine.hasRecord(it.fileId)) } ?: return - val chosen = pending.replaced?.takeIf { directPlay.unavailable } ?: current.decidedBy(directPlay) + val refused = directPlay.unavailable || pending.redecides && directPlay == null + val decided = if (pending.directPlay == null) current else current.decidedBy(directPlay) + val chosen = pending.replaced?.takeIf { refused } ?: decided if (chosen != current) store.upsert(chosen) - if (directPlay.unavailable) { + if (refused) { engine.notifyFailed(chosen, DownloadFailureReason.UNAVAILABLE) } else { engine.start(chosen) @@ -314,6 +331,7 @@ private class PendingStart( val directPlay: Deferred?, val replaced: DownloadEntry?, val startup: Boolean, + val redecides: Boolean, ) /** Progress is display-only, so it polls outside the mutation queue and dies with the controller scope. */ diff --git a/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadActionReceiver.kt b/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadActionReceiver.kt index c6b79b87d..31c0c7886 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadActionReceiver.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadActionReceiver.kt @@ -271,14 +271,18 @@ internal class DownloadNotificationRetries( decision.failed(userId, entry) DownloadRetryOutcome.UNAVAILABLE } - else -> startDecided(userId, entry, retry.entry.decidedBy(answer)) + retry.asksDirectPlay -> startDecided(userId, entry, retry.entry.decidedBy(answer)) + else -> startDecided(userId, entry, retry.entry) } } private suspend fun startDecided(userId: Long, entry: DownloadEntry, chosen: DownloadEntry): DownloadRetryOutcome { - if (chosen.artifact != entry.artifact || chosen.subtitles != entry.subtitles) { - decision.save(userId, entry.copy(artifact = chosen.artifact, subtitles = chosen.subtitles)) - } + val saved = entry.copy( + artifact = chosen.artifact, + subtitles = chosen.subtitles, + directPlayUnanswered = chosen.directPlayUnanswered, + ) + if (saved != entry) decision.save(userId, saved) return try { start(userId, chosen) DownloadRetryOutcome.STARTED diff --git a/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadNotifications.kt b/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadNotifications.kt index f465fbca0..10073f5a1 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadNotifications.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadNotifications.kt @@ -37,6 +37,7 @@ internal sealed interface DownloadOutcome { internal class MobileDownloadNotifications( private val context: Context, private val stores: (Long) -> MobileDownloadStore = { MobileDownloadStore.shared(context, it) }, + private val redeciding: (Long) -> Boolean = DirectPlayRedeciders.shared::holds, private val signedInUser: () -> Long?, ) : DownloadManager.Listener { override fun onDownloadChanged( @@ -57,7 +58,10 @@ internal class MobileDownloadNotifications( if (download.fallingBackToConverted(finalException)) { stores(owner).find(fileId)?.takeUnless { it.removing }?.let { fallBack(downloadManager, owner, it) } } else if (owner == signedInUser()) { - MobileDownloadStore.peek(context, owner, fileId)?.takeUnless { it.removing } + MobileDownloadStore.peek(context, owner, fileId) + ?.takeUnless { + it.removing || redeciding(owner) && it.redecidesDirectPlay(download.failedStatus(outcome)) + } ?.let { post(context, owner, it, outcome) } } } @@ -211,6 +215,10 @@ internal fun DownloadFailureReason.message(): Int = DownloadFailureReason.UNEXPECTED -> R.string.mobile_downloads_status_failed_unexpected } +@androidx.annotation.OptIn(markerClass = [UnstableApi::class]) +private fun Download.failedStatus(outcome: DownloadOutcome): DownloadStatus? = + (outcome as? DownloadOutcome.Failed)?.let { DownloadStatus.Failed(it.reason, bytesDownloaded) } + @androidx.annotation.OptIn(markerClass = [UnstableApi::class]) internal fun Download.fallingBackToConverted(error: Exception?): Boolean = state == Download.STATE_FAILED && error != null && diff --git a/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadStore.kt b/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadStore.kt index e5f05c7e2..efa5cdc1e 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadStore.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadStore.kt @@ -211,6 +211,7 @@ private fun DownloadEntry.toJson(): JSONObject = if (pauseRequested) json.put("pauseRequested", true) if (subtitles.isNotEmpty()) json.put("subtitles", subtitles.toJson()) if (directPlayChosen) json.put("directPlayChosen", true) + if (directPlayUnanswered) json.put("directPlayUnanswered", true) } private fun DownloadStatus.toJson(): JSONObject = @@ -260,6 +261,7 @@ private fun JSONObject.toEntryOrNull(): DownloadEntry? { pauseRequested = pauseRequested, subtitles = optJSONArray("subtitles").toDownloadSubtitles(), directPlayChosen = optBoolean("directPlayChosen", false), + directPlayUnanswered = optBoolean("directPlayUnanswered", false), ) } } diff --git a/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadsViewModel.kt b/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadsViewModel.kt index a0f90265f..dec334a35 100644 --- a/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadsViewModel.kt +++ b/mobile/src/main/kotlin/io/putdotio/android/downloads/MobileDownloadsViewModel.kt @@ -11,6 +11,7 @@ import io.putdotio.android.auth.MobileAuthState import io.putdotio.android.auth.MobileSessionKey import io.putdotio.android.auth.sessionKey import io.putdotio.android.session.SessionScopedHolder +import java.io.Closeable import kotlinx.coroutines.flow.StateFlow /** Owns one downloads controller per signed-in user; the index and cache outlive sign-out. */ @@ -41,6 +42,7 @@ internal class MobileDownloadsViewModel( ActiveDownloads( DownloadsController(store, engine, viewModelScope, sources = sources), engine, + DirectPlayRedeciders.shared.hold(userId), ) }?.controller @@ -51,10 +53,12 @@ internal class MobileDownloadsViewModel( private class ActiveDownloads( val controller: DownloadsController, private val engine: MobileDownloadEngine, + private val redecider: Closeable, ) { fun park() = engine.park() fun close() { + redecider.close() controller.close() engine.close() } diff --git a/mobile/src/test/kotlin/io/putdotio/android/downloads/DownloadMethodsTest.kt b/mobile/src/test/kotlin/io/putdotio/android/downloads/DownloadMethodsTest.kt index f77c167c0..3d8b13b6a 100644 --- a/mobile/src/test/kotlin/io/putdotio/android/downloads/DownloadMethodsTest.kt +++ b/mobile/src/test/kotlin/io/putdotio/android/downloads/DownloadMethodsTest.kt @@ -128,6 +128,60 @@ class DownloadMethodsTest { } } + @Test + fun aConvertedStandInRefusedBeforeItsFirstByteAsksAgainAndDownloadsTheOriginal() = runBlocking { + val answers = mutableListOf(null, original(ENGLISH), null) + val sources = DownloadSources({ StreamingMethod.File }) { fileId, includeSubtitles, _ -> + asked += fileId to includeSubtitles + answers.removeAt(0) + } + DownloadsController(store, engine, this, sources = sources).use { controller -> + assertTrue(controller.dispatch(DownloadsEvent.Start(video))) + engine.await { it.started.size == 1 } + assertEquals(DownloadArtifact.MP4, engine.started.single().artifact) + + store.report(video.fileId, DownloadStatus.Failed(DownloadFailureReason.UNAVAILABLE, 0L)) + engine.await { it.started.size == 2 } + val resumed = engine.started.last() + assertEquals(DownloadArtifact.ORIGINAL, resumed.artifact) + assertEquals(listOf("en-key"), resumed.subtitles.map { it.key }) + assertTrue(engine.failed.isEmpty()) + + store.report(video.fileId, DownloadStatus.Failed(DownloadFailureReason.UNAVAILABLE, 0L)) + settle() + assertEquals(2, engine.started.size) + } + } + + @Test + fun aConvertedStandInRefusedAgainWithoutAnAnswerStaysFailed() = runBlocking { + controller(StreamingMethod.File, emptyMap()).use { controller -> + assertTrue(controller.dispatch(DownloadsEvent.Start(video))) + engine.await { it.started.size == 1 } + val refused = DownloadStatus.Failed(DownloadFailureReason.UNAVAILABLE, 0L) + store.report(video.fileId, refused) + + engine.await { it.failed.size == 1 } + settle() + assertEquals(1, engine.started.size) + assertEquals(refused, store.find(video.fileId)?.status) + assertEquals(listOf(video.fileId, video.fileId), asked.map { it.first }) + } + } + + @Test + fun aRefusedRowThatANotificationRetryMarksUnansweredIsNotAskedAgain() = runBlocking { + val refused = failed(DownloadArtifact.MP4, 0L).copy(status = DIRECT_PLAY_REFUSAL) + store.upsert(refused) + controller(StreamingMethod.File, mapOf(video.fileId to original())).use { + settle() + store.upsert(refused.copy(directPlayUnanswered = true)) + settle() + assertTrue(asked.isEmpty()) + assertTrue(engine.started.isEmpty()) + } + } + @Test fun directPlayLookupsRunTogetherAndStartsKeepTapOrder() = runBlocking { val episodes = (20L..22L).map { video.copy(fileId = FilesItemId(it), name = "Episode $it.mkv") } diff --git a/mobile/src/test/kotlin/io/putdotio/android/downloads/MobileDownloadNotificationsTest.kt b/mobile/src/test/kotlin/io/putdotio/android/downloads/MobileDownloadNotificationsTest.kt index f1697945a..412d13806 100644 --- a/mobile/src/test/kotlin/io/putdotio/android/downloads/MobileDownloadNotificationsTest.kt +++ b/mobile/src/test/kotlin/io/putdotio/android/downloads/MobileDownloadNotificationsTest.kt @@ -303,6 +303,27 @@ class MobileDownloadNotificationsTest { assertTrue(removing.actions.isNullOrEmpty()) } + @Test + fun aStandInRefusedBeforeItsFirstByteIsHeldBackOnlyWhileAControllerAsksAgain() = runBlocking { + shadowOf(context).grantPermissions(Manifest.permission.POST_NOTIFICATIONS) + MobileDownloadStore(context, USER).upsert( + row(13L, "Stand-in.mkv").copy(artifact = DownloadArtifact.MP4, directPlayUnanswered = true), + ) + val redeciders = DirectPlayRedeciders() + val listener = MobileDownloadNotifications(context, redeciding = redeciders::holds) { signedIn } + val refused = download(13L, Download.STATE_FAILED) + val notFound = rejected(HTTP_NOT_FOUND) + + val controller = redeciders.hold(USER) + listener.changed(refused, notFound) + assertTrue(shadowOf(manager).allNotifications.isEmpty()) + + controller.close() + listener.changed(refused, notFound) + val posted = shadowOf(manager).allNotifications.single() + assertEquals("Download failed", posted.extras.getString(Notification.EXTRA_TITLE)) + } + private fun assertOpensMainActivityFromThisAppOnly(intent: Intent) { val entry = context.packageManager.getActivityInfo(checkNotNull(intent.component), 0) assertEquals(MainActivity::class.java.name, entry.targetActivity) @@ -368,6 +389,7 @@ class MobileDownloadNotificationsTest { private companion object { const val HTTP_BAD_REQUEST = 400 + const val HTTP_NOT_FOUND = 404 const val USER = 7L const val OTHER = 8L }