Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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<Long, Int>()

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
}
Expand All @@ -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,
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ internal data class DownloadEntry(
val pauseRequested: Boolean = false,
val subtitles: List<DownloadSubtitle> = 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,17 @@ internal class DownloadsController(
init {
scope.launch { for (pending in starts) startInOrder(pending) }
scope.launch {
var refusals = emptySet<FilesItemId>()
store.entries.collect { entries ->
val running = entries.filter { it.status is DownloadStatus.Downloading }
.mapTo(mutableSetOf()) { it.fileId }
synchronized(lock) {
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 {
Expand Down Expand Up @@ -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 {
Expand All @@ -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)
}
Expand All @@ -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)
Expand Down Expand Up @@ -314,6 +331,7 @@ private class PendingStart(
val directPlay: Deferred<DirectPlayDownload?>?,
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. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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) }
}
}
Expand Down Expand Up @@ -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 &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -260,6 +261,7 @@ private fun JSONObject.toEntryOrNull(): DownloadEntry? {
pauseRequested = pauseRequested,
subtitles = optJSONArray("subtitles").toDownloadSubtitles(),
directPlayChosen = optBoolean("directPlayChosen", false),
directPlayUnanswered = optBoolean("directPlayUnanswered", false),
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -41,6 +42,7 @@ internal class MobileDownloadsViewModel(
ActiveDownloads(
DownloadsController(store, engine, viewModelScope, sources = sources),
engine,
DirectPlayRedeciders.shared.hold(userId),
)
}?.controller

Expand All @@ -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()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,60 @@ class DownloadMethodsTest {
}
}

@Test
fun aConvertedStandInRefusedBeforeItsFirstByteAsksAgainAndDownloadsTheOriginal() = runBlocking {
val answers = mutableListOf<DirectPlayDownload?>(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") }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down