After a rescan: one renumbered programme rechecks the channel's whole schedule in one go (1.0 RC3-8, build 50)
release-gate / verify (push) Successful in 8m26s
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 2m16s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m44s

15 November 2026: the scan the night before gave some booked programmes new numbers; Orbit found each again as it came
up, but only after asking for the old one first (35 failed asks overnight, Detour re-filed four times). Now the first
re-file on a channel checks the rest of its schedule against the server, fifty IDs a request, and re-files every one
that's gone, keeping its slot; at most once an hour a channel, in the background. Tuning ahead no longer asks again for
a programme the server has said it doesn't have.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 08:29:11 +00:00
co-authored by Claude Opus 5.5
parent 805f75f9c0
commit f2beb6ed76
5 changed files with 92 additions and 2 deletions
+1 -1
View File
@@ -3,7 +3,7 @@ plugins {
id("org.jetbrains.kotlin.plugin.compose")
}
/** The release's build number: versionCode is this x 10 plus the edition's channel. */
val ORBIT_BUILD = 49
val ORBIT_BUILD = 50
android {
namespace = "tv.orbit.classic"
compileSdk = 36
@@ -509,6 +509,21 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
private val lighterChecked = java.util.Collections.synchronizedSet(HashSet<String>())
fun lighterFilm(item: SampleItem): ScheduledMedia? = if (item.type != "Movie" || !lighterChecked.add(item.id)) null else refiledFilm(item)
/**
* Which of [ids] the server still has (15 November 2026: a rescan gave some booked programmes new numbers). Fifty at a
* time, one small request each, nothing but the IDs asked back; an ID the server doesn't return has gone.
*/
fun presentIds(ids: Collection<String>): Set<String> {
val found = HashSet<String>()
for (batch in ids.filter(EmbyClient::validId).distinct().chunked(50)) {
val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Ids=${batch.joinToString(",")}&Fields=&EnableImages=false&EnableUserData=false", token = currentToken()))
EmbyClient.expectSuccess(reply.status, false)
val rows = EmbyClient.parse(reply.body).optJSONArray("Items") ?: continue
for (i in 0 until rows.length()) rows.optJSONObject(i)?.optString("Id")?.let(found::add)
}
return found
}
fun refiledFilm(item: SampleItem): ScheduledMedia? {
if (item.type != "Movie") return null
val film = findFilm(transport, userId, ::currentToken, item.title, BoxDecoders::canDecode).film ?: return null
@@ -39,6 +39,8 @@ internal const val MAX_DRIFT_MS = 2 * 60_000L
internal const val FILM_SQUEEZE_MAX_MS = 2 * 60_000L
/** The same for an episode, whose credits are short. */
internal const val EPISODE_SQUEEZE_MAX_MS = 20_000L
/** A channel's whole schedule is re-checked after a renumbered programme at most this often. */
internal const val RECHECK_GAP_MS = 60 * 60_000L
private fun ScheduleEntry.file() = fileMs ?: media.durationMs
private fun ScheduleEntry.withSlot(slotMs: Long, file: Long) = copy(
@@ -118,7 +120,12 @@ internal fun openBooked(session: EmbySampleSession, channel: SampleChannel, stor
if (failure.httpStatus != 404 && failure.httpStatus != 500) throw failure
val found = session.refiledFilm(show.media.item) ?: session.refiledEpisode(show.media.item) ?: throw failure
android.util.Log.i("OrbitSchedule", "channel=${channel.number} refiled old=${show.media.item.id} new=${found.item.id}")
if (live) PlanEdits.replace(channel, store, session.accountId, show.startMs, show.media.item.id, found)
if (live) {
PlanEdits.replace(channel, store, session.accountId, show.startMs, show.media.item.id, found)
// One gone usually means a rescan renumbered more: the rest of the channel's schedule is checked in one go, in the
// background, rather than each programme failing once as it comes up (15 November 2026: 35 failed asks overnight).
PlanEdits.recheckSoon(session, channel, store, show.startMs)
}
// Booked in the old slot; the length check that follows then re-times it for the copy's own length.
val booked = show.copy(media = found.copy(durationMs = show.media.durationMs), fileMs = null)
return session.prepareForTuning(found.item, found.sourceId, ahead) { Thread.sleep(2_000) } to booked
@@ -150,6 +157,32 @@ internal object PlanEdits {
}
}
private val rechecked = HashMap<Int, Long>()
/** [recheck] on its own thread, at most once an hour a channel. */
fun recheckSoon(session: EmbySampleSession, channel: SampleChannel, store: ScheduleStore, afterMs: Long, nowMs: Long = System.currentTimeMillis()) {
synchronized(rechecked) { if ((rechecked[channel.number] ?: Long.MIN_VALUE) > nowMs - RECHECK_GAP_MS) return; rechecked[channel.number] = nowMs }
Thread({ runCatching { recheck(session, channel, store, afterMs) }.onFailure { android.util.Log.w("OrbitSchedule", "channel=${channel.number} recheck failed=${it.javaClass.simpleName}") } }, "orbit-recheck").apply { isDaemon = true }.start()
}
/**
* Every programme booked on [channel] after [afterMs], checked against the server in batches ([EmbySampleSession.presentIds]);
* each one that has gone is found again by title, as [openBooked] does, and its slot kept. Returns how many were re-filed.
*/
fun recheck(session: EmbySampleSession, channel: SampleChannel, store: ScheduleStore, afterMs: Long): Int {
if (channel !is ScheduledChannel || channel.number == DRIVE_IN_NUMBER) return 0
val ahead = (store.loadPlan(session.accountId, channel.number) ?: return 0).entries.filter { it.startMs > afterMs }
val present = session.presentIds(ahead.map { it.media.item.id })
val gone = ahead.filter { it.media.item.id !in present }
var refiled = 0
for (entry in gone) {
val found = runCatching { session.refiledFilm(entry.media.item) ?: session.refiledEpisode(entry.media.item) }.getOrNull() ?: continue
replace(channel, store, session.accountId, entry.startMs, entry.media.item.id, found); refiled++
}
android.util.Log.i("OrbitSchedule", "channel=${channel.number} recheck checked=${ahead.size} gone=${gone.size} refiled=$refiled")
return refiled
}
fun retime(channel: SampleChannel, store: ScheduleStore, userId: String, startMs: Long, actualMs: Long): Int {
if (channel !is ScheduledChannel || channel.number == DRIVE_IN_NUMBER) return 0
synchronized(lock) {
@@ -16,6 +16,8 @@ internal object TuneAhead {
private class Ready(val session: EmbySampleSession, val plan: EmbyPlaybackPlan, val at: Long)
private val ready = mutableMapOf<String, Ready>()
private val asking = mutableSetOf<String>()
/** Programmes the server said it no longer has (15 November 2026): not asked for again until they're re-filed. */
private val gone = mutableMapOf<String, Long>()
private fun key(item: SampleItem, sourceId: String) = "${item.id}/$sourceId"
@@ -28,6 +30,7 @@ internal object TuneAhead {
synchronized(this) {
val have = ready[k]
if (have != null && have.session === session && System.currentTimeMillis() - have.at < KEEP_MS) return
if ((gone[k] ?: 0L) > System.currentTimeMillis() - KEEP_MS * 6) return
if (!asking.add(k)) return
}
try {
@@ -36,6 +39,7 @@ internal object TuneAhead {
synchronized(this) { ready[k] = Ready(session, plan, System.currentTimeMillis()); ready.entries.removeAll { System.currentTimeMillis() - it.value.at >= KEEP_MS } }
android.util.Log.i("OrbitSchedule", "channel=${channel.number} readyAheadMs=${android.os.SystemClock.elapsedRealtime() - started}")
} catch (cancelled: CancellationException) { throw cancelled }
catch (failure: EmbyCheckException) { if (failure.httpStatus == 404 || failure.httpStatus == 500) synchronized(this) { gone[k] = System.currentTimeMillis() } }
catch (_: Exception) { /* Tuning asks again as usual. */ }
finally { synchronized(this) { asking.remove(k) } }
}
@@ -108,3 +108,41 @@ class LighterCopyTest {
assertEquals(1, searches)
}
}
/** 15 November 2026: one renumbered programme means a rescan; the rest of the channel's schedule is checked in one go. */
class RecheckAfterRescanTest {
@org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com" }
@org.junit.After fun noServer() { EmbyServer.origin = "" }
private val min = 60_000L
private fun ep(id: String, n: Int, start: Long) = ScheduleEntry("show", EpisodeMark(1, n),
ScheduledMedia(SampleItem("Fixture Show / S1 E$n / Part $n", "Episode", 22, "", id, 22 * min), "src$id", 22 * min), start)
private fun row(id: String, n: Int) = JSONObject().put("Id", id).put("Type", "Episode").put("Name", "Part $n").put("ParentIndexNumber", 1).put("IndexNumber", n)
.put("MediaSources", JSONArray().put(JSONObject().put("Id", "src$id").put("Container", "mkv").put("RunTimeTicks", 22 * min * 10_000)))
@Test fun theGoneOnesAreFoundAgainAndTheRestLeftAlone() {
val dir = kotlin.io.path.createTempDirectory("recheck").toFile()
try {
val asked = mutableListOf<String>()
val transport = EmbyTransport { r ->
asked += r.path
when {
"&Ids=" in r.path -> EmbyReply(200, JSONObject().put("Items", JSONArray().put(JSONObject().put("Id", "old1aaaa"))).toString())
"IncludeItemTypes=Series" in r.path -> EmbyReply(200, JSONObject().put("Items", JSONArray().put(JSONObject().put("Id", "show2").put("Name", "Fixture Show"))).toString())
r.path.startsWith("/Shows/show2/Episodes") -> EmbyReply(200, JSONObject().put("Items", JSONArray().put(row("new2bbbb", 2)).put(row("new3cccc", 3))).toString())
else -> EmbyReply(404, "")
}
}
val session = EmbySampleSession(transport, "fixture-token-private", "u1", EmbySample(listOf(SampleItem("Fixture", "Movie", 90, "mkv", "one")), 1))
val store = ScheduleStore(dir)
val p = ChannelPlan(listOf(ep("old0zzzz", 1, 0), ep("old1aaaa", 1, 22 * min), ep("old2bbbb", 2, 44 * min), ep("old3cccc", 3, 66 * min)), ScheduleCursor())
store.savePlan("u1", 601, p)
val channel = ScheduledChannel(SampleChannel(listOf(p.entries[0].media, p.entries[1].media), "Vortex", 601), p)
assertEquals(2, PlanEdits.recheck(session, channel, store, 0))
assertEquals(listOf("old0zzzz", "old1aaaa", "new2bbbb", "new3cccc"), store.loadPlan("u1", 601)!!.entries.map { it.media.item.id })
// Slots kept; the programme already on (at 0) isn't part of the check; one request checked all three ahead.
assertEquals(listOf(0L, 22 * min, 44 * min, 66 * min), channel.plan.entries.map { it.startMs })
assertEquals(1, asked.count { "&Ids=" in it })
assertFalse(asked.first { "&Ids=" in it }.contains("old0zzzz"))
} finally { dir.deleteRecursively() }
}
}