A booked film the scan re-filed under a new number plays again
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 2m44s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m43s
release-gate / verify (push) Successful in 9m5s

Scream 2 still wouldn't open on the VPS: the TV asked for item 3866244, which
the first scan had removed (Emby answers 500 for a gone item), while the film
lives on under a new number. On a 404 or 500, openBooked looks the film up once
by its exact title (findFilm), plays that copy in the same slot, updates the
saved plan (PlanEdits.replace) and re-times it for its own length. Films only;
no extra reads otherwise. Server errors now carry their HTTP status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 23:00:38 +00:00
co-authored by Claude Opus 5.5
parent b8ced6768d
commit 02eadfd48b
6 changed files with 78 additions and 5 deletions
@@ -226,7 +226,7 @@ internal class EmbyClient(private val transport: EmbyTransport = HttpsEmbyTransp
403 -> throw EmbyCheckException("The provider did not permit this connection or library request.", status)
429 -> throw EmbyCheckException("The provider asked us to slow down. Wait before trying again.", status)
in 300..399 -> throw EmbyCheckException("The provider redirected the request. The login was not forwarded to another address.")
else -> throw EmbyCheckException("The provider could not complete this check (HTTP $status).", retryable = status >= 500)
else -> throw EmbyCheckException("The provider could not complete this check (HTTP $status).", status, retryable = status >= 500)
}
}
}
@@ -496,6 +496,21 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
fun fetchArtwork(path: String): ByteArray? = (transport as? HttpsEmbyTransport)?.fetchImage(path, currentToken())
fun rememberScheduledItems(items: List<SampleItem>) { channelEpisodes = channelEpisodes + items.associateBy { it.id } }
/**
* A booked film the library no longer has under its number (Paul, 12 November 2026: Scream 2 on the new server, whose
* first scan re-files titles). One search for the same title, matched exactly as a channel's list is; null when there's
* no copy, or only the one that's gone.
*/
fun refiledFilm(item: SampleItem): ScheduledMedia? {
if (item.type != "Movie") return null
val film = findFilm(transport, userId, ::currentToken, item.title, BoxDecoders::canDecode).film ?: return null
if (film.id == item.id) return null
val copy = film.episodes.first()
val found = SampleItem(film.title, "Movie", copy.durationMs / 60_000, "", copy.id, copy.durationMs)
rememberScheduledItems(listOf(found))
return ScheduledMedia(found, copy.sourceId, copy.durationMs)
}
fun checkMetadataCoverage(checkActive: () -> Unit = {}): List<MetadataCoverage> =
auditMetadataCoverage(transport, userId, ::currentToken, checkActive)
fun importCatalogue(sink: CatalogueSink, maxPages: Int = CATALOGUE_PAGES_PER_RUN, pause: () -> Unit = {}, checkActive: () -> Unit = {}, onPage: () -> Unit = {},
@@ -143,8 +143,8 @@ private fun GuideLiveProgramme(session: EmbySampleSession, channel: SampleChanne
LaunchedEffect(Unit) {
if (returned != null) return@LaunchedEffect
try {
val opened = withContext(Dispatchers.IO) { session.prepareForTuning(programme.media.item, programme.media.sourceId) { Thread.sleep(2_000) } }
val fit = runtimeFit(opened, programme)
val (opened, booked) = withContext(Dispatchers.IO) { openBooked(session, channel, Workspaces.current(context).schedules, programme, live = true) }
val fit = runtimeFit(opened, booked)
// A longer file makes room for itself here too, so the picture and full screen agree (ProgrammeLengths.kt).
if (fit == RuntimeFit.Adjust) opened.durationMs?.let { actual ->
withContext(Dispatchers.IO) { PlanEdits.retime(channel, Workspaces.current(context).schedules, session.accountId, programme.startMs, actual) }
@@ -96,6 +96,24 @@ internal fun retimedPlan(plan: ChannelPlan, startMs: Long, actualMs: Long): Chan
return plan.copy(entries = entries)
}
/**
* Opens a booked programme. A film the server answers for with an error because its number has gone (404, or Emby's 500
* for an item it no longer has) is looked for once by title; the copy found plays in the same slot, and on a live channel
* the schedule is updated to it, so the guide and every screen agree. Returns the plan and the programme as now booked.
*/
internal fun openBooked(session: EmbySampleSession, channel: SampleChannel, store: ScheduleStore, show: SampleBroadcast, live: Boolean, ahead: Boolean = false): Pair<EmbyPlaybackPlan, SampleBroadcast> {
try { return session.prepareForTuning(show.media.item, show.media.sourceId, ahead) { Thread.sleep(2_000) } to show }
catch (failure: EmbyCheckException) {
if (failure.httpStatus != 404 && failure.httpStatus != 500) throw failure
val found = session.refiledFilm(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)
// 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
}
}
/** Every change to a saved plan goes through this, so a top-up and a re-timing never write over each other. */
internal object PlanEdits {
val lock = Any()
@@ -106,6 +124,21 @@ internal object PlanEdits {
* screen (guide, What's On, the Companion, the player) reads the same plan, so they all move together. Returns how many
* programmes moved.
*/
/** Puts [found] in place of the booked file [oldId] at [startMs], keeping its slot (see [openBooked]). */
fun replace(channel: SampleChannel, store: ScheduleStore, userId: String, startMs: Long, oldId: String, found: ScheduledMedia) {
if (channel !is ScheduledChannel || channel.number == DRIVE_IN_NUMBER) return
synchronized(lock) {
val saved = store.loadPlan(userId, channel.number) ?: return
val at = saved.entries.indexOfFirst { it.startMs == startMs && it.media.item.id == oldId }.takeIf { it >= 0 } ?: return
val entry = saved.entries[at]
val slot = entry.media.durationMs
val media = found.copy(durationMs = slot, item = found.item.copy(minutes = slot / 60_000, durationMs = slot))
val updated = saved.copy(entries = saved.entries.toMutableList().also { it[at] = entry.copy(media = media, fileMs = null) })
store.savePlan(userId, channel.number, updated)
channel.plan = updated
}
}
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) {
@@ -138,14 +138,16 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC
val tuneStarted = android.os.SystemClock.elapsedRealtime()
// Got ready ahead (TuneAhead) when it's a channel either side, or a guide row rested on.
val ahead = if (clockOffsetMs == 0L) TuneAhead.take(session, current.media.item, current.media.sourceId) else null
// A film the scan has re-filed under a new number is found again once (openBooked).
var booked = current
val plan = ahead ?: prepareMutex.withLock {
withContext(Dispatchers.IO) {
session.prepareForTuning(current.media.item, current.media.sourceId) { Thread.sleep(2_000) }
openBooked(session, channel, schedules, current, live = clockOffsetMs == 0L).also { booked = it.second }.first
}
}
android.util.Log.i("OrbitSchedule", "channel=${channel.number} tunePrepareMs=${android.os.SystemClock.elapsedRealtime() - tuneStarted} ahead=${ahead != null}")
// A different length plays like a real network's would (ProgrammeLengths.kt); only a file that isn't the one booked is skipped.
val fit = runtimeFit(plan, current)
val fit = runtimeFit(plan, booked)
if (fit == RuntimeFit.Refuse) throw EmbyCheckException("This programme's runtime changed. Return and rebuild the sample channel.")
// Live only: Catch Up replays the past, which mustn't move what's on now.
if (fit == RuntimeFit.Adjust && clockOffsetMs == 0L) plan.durationMs?.let { actual ->
@@ -137,6 +137,29 @@ class ProgrammeLengthsTest {
assertNull(retimedPlan(once, 0, 101 * min))
}
@Test
fun aRefiledFilmTakesTheSameSlotAndIsThenTimedForItsOwnLength() {
// 12 November 2026: the scan re-filed Scream 2 under a new number. The copy found keeps the slot, then re-times.
val dir = kotlin.io.path.createTempDirectory("refiled").toFile()
try {
val store = ScheduleStore(dir)
val p = plan(entry("old1", 0, 120 * min), entry("next1", 120 * min, 30 * min))
store.savePlan("u1", 304, p)
val channel = ScheduledChannel(SampleChannel(listOf(entry("loop1", 0, 30 * min).media, entry("loop2", 0, 30 * min).media), "Horror", 304), p)
val copy = entry("new1", 0, 120 * min + 14_000).media
PlanEdits.replace(channel, store, "u1", 0, "old1", copy)
assertEquals("new1", channel.plan.entries[0].media.item.id)
assertEquals(120 * min, channel.plan.entries[0].media.durationMs)
assertEquals("new1", store.loadPlan("u1", 304)!!.entries[0].media.item.id)
// Then its own length: 14 seconds longer, so what follows moves.
assertEquals(1, PlanEdits.retime(channel, store, "u1", 0, 120 * min + 14_000))
assertEquals(120 * min + 14_000, channel.plan.entries[1].startMs)
// A different booked file at that time is left alone.
PlanEdits.replace(channel, store, "u1", 0, "someoneelse", entry("x1", 0, min).media)
assertEquals("new1", channel.plan.entries[0].media.item.id)
} finally { dir.deleteRecursively() }
}
@Test
fun aReTimedPlanSavesAndLoads() {
val dir = kotlin.io.path.createTempDirectory("lengths").toFile()