0.99.12: one failed show in a pool refresh keeps its previous copy instead of losing the whole refresh; retry in 6 hours
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 2m7s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m43s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-04 12:50:58 +00:00
co-authored by Claude Opus 5.5
parent 3903d73304
commit e552871589
8 changed files with 123 additions and 12 deletions
@@ -332,6 +332,30 @@ internal fun turnOrder(pool: List<PoolSeries>, last: String?): List<PoolSeries>
return (0 until pool.size).map { pool[(after + it) % pool.size] }
}
/** How many shows' reads may fail in one refresh, each keeping its previous copy, before the refresh is abandoned as an outage. */
internal const val MAX_FAILED_READS = 3
/** A refresh that kept some previous copies is tried again after this long, rather than waiting a week. */
internal const val PARTIAL_POOL_RETRY_MS = 6 * 60 * 60_000L
/**
* A pool refresh where one show's read fails (a timeout, say): that show keeps its copy from the previous pool and the
* rest of the refresh stands. A show with no previous copy, a failure that isn't worth retrying, or more than
* [MAX_FAILED_READS] failures (the provider is down) abandons the refresh, so the whole previous pool is kept as before.
* Nothing is ever dropped from a pool because a read failed.
*/
internal class PartialRead(private val previous: List<PoolSeries>?, private val limit: Int = MAX_FAILED_READS) {
var carried = 0
private set
private var failures = 0
fun carry(key: String, failure: EmbyCheckException): PoolSeries {
failures++
if (!failure.retryable || failures > limit) throw failure
val kept = previous?.firstOrNull { seriesKey(it.title) == key || seriesKey(FilmIdentity.of(it.title).title) == key } ?: throw failure
carried++
return kept
}
}
/** A pool without the items taken off a channel by editorial decision ([ChannelProgramming.withdrawn]). */
internal fun withoutWithdrawn(pool: List<PoolSeries>, withdrawn: Set<String>): List<PoolSeries> =
if (withdrawn.isEmpty()) pool else pool.filter { show -> show.id !in withdrawn && show.episodes.none { it.id in withdrawn } }
@@ -102,11 +102,14 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
if (cached == null || now - cached.fetchedAtMs >= POOL_REFRESH_MS || cached.signature != signature) {
val started = android.os.SystemClock.elapsedRealtime()
try {
val read = session.readChannelPool(programming, loop, choices, checkActive)
val read = session.readChannelPool(programming, loop, choices, checkActive, previous = cached?.series)
requests = read.requests
fetchMs = android.os.SystemClock.elapsedRealtime() - started
if (read.series.isNotEmpty()) {
pool = ScheduleStore.SavedPool(read.series, now, signature)
// A refresh that had to keep a few previous copies is tried again in a few hours rather than a week.
val fetched = if (read.carried > 0) now - POOL_REFRESH_MS + PARTIAL_POOL_RETRY_MS else now
if (read.carried > 0) Log.w("OrbitSchedule", "channel=$number poolRefreshPartial carried=${read.carried}")
pool = ScheduleStore.SavedPool(read.series, fetched, signature)
store.savePool(userId, number, pool)
}
} catch (failure: EmbyCheckException) {
@@ -66,7 +66,7 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
connection.connectTimeout = 10_000
connection.readTimeout = request.readTimeoutMs ?: if (request.path == "/Sessions/Logout") 5_000 else 15_000
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.99.11\"")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.99.12\"")
request.token?.let { connection.setRequestProperty("X-Emby-Token", it) }
if (request.method == "POST") {
val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8)
@@ -210,11 +210,16 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
}
}
internal class PoolRead(val series: List<PoolSeries>, val requests: Int)
internal class PoolRead(val series: List<PoolSeries>, val requests: Int,
/** Shows whose read failed this time and kept their copy from the previous pool instead. */
val carried: Int = 0)
/** The first shows in the channel's list that have episodes to schedule. */
fun readChannelPool(programming: ChannelProgramming, loop: SampleChannel?, choices: ChannelChoices = ChannelChoices(), checkActive: () -> Unit = {}): PoolRead {
fun readChannelPool(programming: ChannelProgramming, loop: SampleChannel?, choices: ChannelChoices = ChannelChoices(), checkActive: () -> Unit = {},
/** The pool being refreshed, so one show whose read fails can keep its copy rather than losing the whole refresh. */
previous: List<PoolSeries>? = null): PoolRead {
var requests = 0
val pool = mutableListOf<PoolSeries>()
val partial = PartialRead(previous)
if (programming.filmRestMs != null) {
// Films already in this channel's old line-up stay in it, unless the list now names another film of that title.
val listed = programming.searches.map { seriesKey(FilmIdentity.of(it).title) }.toSet()
@@ -226,7 +231,12 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
if (found >= programming.seriesCount) break
checkActive()
requests++
val lookup = findFilm(transport, userId, ::currentToken, entry, BoxDecoders::canDecode)
val lookup = try { findFilm(transport, userId, ::currentToken, entry, BoxDecoders::canDecode) } catch (failure: EmbyCheckException) {
android.util.Log.w("OrbitSchedule", "channel=${programming.number} film failed=${failure.javaClass.simpleName} status=${failure.httpStatus}")
val kept = partial.carry(seriesKey(FilmIdentity.of(entry).title), failure)
if (pool.none { it.id == kept.id }) { pool += kept; found++ }
continue
}
if (lookup.note.isNotEmpty()) android.util.Log.i("OrbitSchedule", "channel=${programming.number} ${lookup.note}")
val film = lookup.film ?: continue
if (pool.none { it.id == film.id }) { pool += film; found++ }
@@ -249,7 +259,11 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
fun <T> traced(step: String, block: () -> T): T = try { block() } catch (failure: Exception) {
android.util.Log.w("OrbitSchedule", "channel=${programming.number} listed=${index + 1} $step failed=${failure.javaClass.simpleName}"); throw failure
}
val candidates = traced("search") { searchSeries(transport, userId, ::currentToken, search).candidates }
val candidates = try { traced("search") { searchSeries(transport, userId, ::currentToken, search).candidates } } catch (failure: EmbyCheckException) {
val kept = partial.carry(seriesKey(search), failure)
if (pool.none { it.id == kept.id }) pool += kept
continue
}
val exact = candidates.count { seriesKey(it.title) == seriesKey(search) }
val match = bestSeriesMatch(search, if (programming.exactTitles) candidates.filter { seriesKey(it.title) == seriesKey(search) } else candidates)
// Counts only, never titles: which list entry found nothing, and at which step, so a missing show can be traced.
@@ -259,7 +273,12 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
// A library can hold several copies of one show, one with a single episode and another with the whole run.
// The copy with the most episodes this box can play is the one the channel uses.
val copies = (listOf(match) + candidates.filter { it.id != match.id && seriesKey(it.title) == seriesKey(match.title) }.sortedBy { it.year ?: Int.MAX_VALUE }).take(MAX_SERIES_COPIES)
val read = traced("read") { copies.map { copy -> readWholeSeries(transport, userId, ::currentToken, copy, checkActive, onRequest = { requests++ }, canDecode = BoxDecoders::canDecode, englishAudio = programming.englishAudio) } }
val read = try { traced("read") { copies.map { copy -> readWholeSeries(transport, userId, ::currentToken, copy, checkActive, onRequest = { requests++ }, canDecode = BoxDecoders::canDecode, englishAudio = programming.englishAudio) } } }
catch (failure: EmbyCheckException) {
val kept = partial.carry(seriesKey(match.title), failure)
if (pool.none { it.id == kept.id }) pool += kept
continue
}
val best = read.maxByOrNull { it.episodes.size }?.takeIf { it.episodes.isNotEmpty() }
if (best == null) { android.util.Log.i("OrbitSchedule", "channel=${programming.number} listed=${index + 1} matched copies=${copies.size} playableEpisodes=0"); continue }
if (copies.size > 1) android.util.Log.i("OrbitSchedule", "channel=${programming.number} copies=${copies.size} usedCopy=${read.indexOf(best) + 1} episodes=${read.map { it.episodes.size }}")
@@ -287,7 +306,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
}
}
// An editorial withdrawal takes that exact item out, however it arrived: list, old line-up or accepted suggestion.
return PoolRead(withoutWithdrawn(pool, programming.withdrawn), requests)
return PoolRead(withoutWithdrawn(pool, programming.withdrawn), requests, partial.carried)
}
fun suggestFor(rules: List<SuggestionRule>, alreadyInPool: Set<String>, rejected: Set<String>, takenTitles: Set<String> = emptySet(), checkActive: () -> Unit = {}) =
findSuggestions(transport, userId, ::currentToken, rules, alreadyInPool, rejected, checkActive, BoxDecoders::canDecode, takenTitles, englishAudio = true)
@@ -33,7 +33,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B
next.instanceFollowRedirects = false
next.connectTimeout = 10_000
next.readTimeout = 20_000
next.setRequestProperty("User-Agent", "OrbitTV/0.99.11")
next.setRequestProperty("User-Agent", "OrbitTV/0.99.12")
next.setRequestProperty("Accept-Encoding", "identity")
session.mediaHeaders(address).forEach { (key, value) -> next.setRequestProperty(key, value) }
if (dataSpec.position != 0L || dataSpec.length != C.LENGTH_UNSET.toLong()) {