Mistletoe's 10-hour booking: a one-off adb fix, and a hold on odd running times

fix-booking replaces one booking that hasn't started with named films from the channel's own
pool, back to back, the last slot running to where it ended; nothing else moves, and the plan
file is kept aside. Films whose file runs over 5 hours are held for review (never on Ring X),
shown under Schedule health, and released from adb with release-runtime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 16:06:33 +00:00
co-authored by Claude Opus 5.5
parent da1f203071
commit 0e29d8748d
8 changed files with 216 additions and 3 deletions
@@ -23,7 +23,12 @@ import java.security.MessageDigest
* - `approve-add` (23 November 2026): titles you approved outside the app, from install-restore/approve.json, added to their
* channels' lists with `confirm ADD` while Orbit's screen isn't open. See [ApprovedTitles]: it only adds.
*
* Apart from `restore` and `approve-add`, it only ever copies; it never changes the schedules, the library or the sign-in.
* - `fix-booking` (23 November 2026): one booking replaced by hand, from install-restore/fix.json, with `confirm FIX` while
* Orbit's screen isn't open. See [BookingFix]: nothing else in the plan moves.
*
* - `release-runtime` (23 November 2026): a film held for an odd running time, let through (`--es id`, `confirm RELEASE`).
*
* Apart from `restore`, `approve-add`, `fix-booking` and `release-runtime`, it only ever copies; it never changes the schedules, the library or the sign-in.
*/
class InstallSnapshotReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
@@ -60,6 +65,28 @@ class InstallSnapshotReceiver : BroadcastReceiver() {
} catch (e: Exception) { resultData = "failed: ${e.javaClass.simpleName}" } finally { incoming.delete() }
android.util.Log.i("OrbitInstall", "approve-add: $resultData")
return
} else if (intent.getStringExtra("do") == "release-runtime") {
// A film held for an odd running time ([RuntimeReview]) that you've looked at: booked as normal from now on.
val target = Workspaces.current(context)
resultData = if (intent.getStringExtra("confirm") != "RELEASE") "refused: needs confirm RELEASE"
else ScheduleStore(target.scheduleDir).runtimeReleases().add(intent.getStringExtra("id").orEmpty())
android.util.Log.i("OrbitInstall", "release-runtime: $resultData")
return
} else if (intent.getStringExtra("do") == "fix-booking") {
// One booking replaced by hand ([BookingFix]): adb pushes install-restore/fix.json; it's read once and removed.
val incoming = File(context.getExternalFilesDir(null), "install-restore/fix.json")
try {
val target = Workspaces.current(context)
resultData = when {
intent.getStringExtra("confirm") != "FIX" -> "refused: needs confirm FIX"
OrbitScreen.open -> "refused: Orbit is open; force-stop it first"
!incoming.exists() -> "refused: no fix.json"
else -> ServerMove.userOf(target.scheduleDir)?.let { user ->
BookingFix.apply(target.scheduleDir, user, org.json.JSONObject(incoming.readText()), System.currentTimeMillis()) } ?: "refused: no saved schedules"
}
} catch (e: Exception) { resultData = "failed: ${e.javaClass.simpleName}" } finally { incoming.delete() }
android.util.Log.i("OrbitInstall", "fix-booking: $resultData")
return
} else if (intent.getStringExtra("do").orEmpty().startsWith("move-")) {
// Reading two catalogues takes a few seconds: off the main thread, answered when done.
val pending = goAsync()
@@ -0,0 +1,65 @@
package tv.orbit.classic
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* One booking replaced by hand (Paul, 23 November 2026: Mistletoe's "Coming Home for Christmas" was a 10-hour file, booked at
* 23:21). The films named take its place, back to back, and the last one's slot runs to where the bad booking ended, the
* channel's ident filling the few minutes left as it does after any short file. Nothing else in the plan moves.
*
* - only a booking that hasn't started, found by its start and its item, is replaced;
* - each replacement is a film in the channel's own pool, named once, and not the file being replaced;
* - together they fill the slot to within [MAX_LEFTOVER_MS], without running past it;
* - the plan file is kept as it was in fix-<time>/ beside the schedules, to put back if wanted.
*/
internal object BookingFix {
const val MAX_LEFTOVER_MS = 30 * 60_000L
/** The plan with the booking at [startMs] replaced, or why not. */
fun replaced(plan: ChannelPlan, pool: List<PoolSeries>, startMs: Long, oldId: String, withIds: List<String>, nowMs: Long): Pair<ChannelPlan?, String> {
val at = plan.entries.indexOfFirst { it.startMs == startMs && it.media.item.id == oldId }
if (at < 0) return null to "refused: no booking of $oldId at $startMs"
val old = plan.entries[at]
if (startMs <= nowMs) return null to "refused: it has already started"
if (withIds.isEmpty() || withIds.toSet().size != withIds.size || oldId in withIds) return null to "refused: name each replacement once, and not the file itself"
val films = withIds.map { id -> pool.firstOrNull { it.id == id && it.isFilm } ?: return null to "refused: $id isn't a film in this channel's pool" }
val total = films.sumOf { it.episodes.first().durationMs }
val slot = old.media.durationMs
if (total > slot) return null to "refused: the films run ${(total - slot) / 60_000} minutes past the slot"
if (slot - total > MAX_LEFTOVER_MS) return null to "refused: ${(slot - total) / 60_000} minutes would be left over"
var start = startMs
val fresh = films.mapIndexed { index, film ->
val copy = film.episodes.first()
val last = index == films.lastIndex
val length = if (last) old.endMs - start else copy.durationMs
val item = filmItem(film, copy).let { if (last) it.copy(minutes = length / 60_000, durationMs = length) else it }
ScheduleEntry(film.id, copy.mark, ScheduledMedia(item, copy.sourceId, length), start,
"replaced a booking whose file ran ${slot / 60_000} minutes (Paul, 23 November 2026)", old.presentation,
fileMs = copy.durationMs.takeIf { it != length })
.also { start += length }
}
val entries = plan.entries.toMutableList().apply { removeAt(at); addAll(at, fresh) }
val shown = plan.tail.filmShown + fresh.associate { it.seriesId to maxOf(it.startMs, plan.tail.filmShown[it.seriesId] ?: Long.MIN_VALUE) }
return ChannelPlan(entries, plan.tail.copy(filmShown = shown)) to "replaced with ${fresh.size} films, ${(slot - total) / 60_000} minutes of ident"
}
/** From adb (household): {"c": channel, "start": ms, "old": item id, "with": [film ids]}. */
fun apply(dir: File, userId: String, request: JSONObject, nowMs: Long): String {
val channel = request.optInt("c", -1).takeIf { it in 100..999 } ?: return "refused: a bad channel"
val oldId = request.optString("old").takeIf(EmbyClient::validId) ?: return "refused: a bad item id"
val ids = request.optJSONArray("with") ?: JSONArray()
val withIds = (0 until ids.length()).map { ids.optString(it).takeIf(EmbyClient::validId) ?: return "refused: a bad replacement id" }
val store = ScheduleStore(dir)
synchronized(PlanEdits.lock) {
val plan = store.loadPlan(userId, channel) ?: return "refused: no plan for $channel"
val pool = store.loadPool(userId, channel)?.series ?: return "refused: no pool for $channel"
val (fixed, why) = replaced(plan, pool, request.optLong("start"), oldId, withIds, nowMs)
if (fixed == null) return why
File(dir, "schedule-$channel.json").takeIf { it.exists() }?.let { val keep = File(dir, "fix-$nowMs").apply { mkdirs() }; it.copyTo(File(keep, it.name), overwrite = true) }
store.savePlan(userId, channel, fixed)
return "$why (kept fix-$nowMs)"
}
}
}
@@ -422,7 +422,7 @@ internal class ChannelScheduler(private val store: ScheduleStore,
// Under the plan lock, so a programme being re-timed for its real length (PlanEdits) is never written over.
val (existing, plan) = synchronized(PlanEdits.lock) {
val existing = store.loadPlan(userId, number)
val plan = topUpPlan(existing, base, pool?.series?.let { withOpenApprovals(withoutFailed(it, store.loadFailed(userId)), choices) }?.let { if (programming.mixedTurns) mixedTurnOrder(it, number) else it }, now, programming.filmRestMs, programming.finishTogether, programming.dayParts,
val plan = topUpPlan(existing, base, pool?.series?.let { withOpenApprovals(withoutOddRuntimes(withoutFailed(it, store.loadFailed(userId)), number, store.runtimeReleases().load()), choices) }?.let { if (programming.mixedTurns) mixedTurnOrder(it, number) else it }, now, programming.filmRestMs, programming.finishTogether, programming.dayParts,
avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes,
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, fileRestMs = programming.fileRestMs, stories = programming.storyGrouping, shorts = programming.shorts, marathon = programming.marathon,
seasonEndMs = seasonEndMs(number, now), network = network) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
@@ -405,7 +405,9 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ
/** Your decision on a rotation card: the approved suggestions, the rest dismissed. Returns what to tell you. */
decideRotation: suspend (RotationCard, List<RotationProposal>) -> String = { _, _ -> "" },
/** Series a channel can only play part of ([gapReport]). */
gaps: () -> List<SeriesGap> = { emptyList() }) {
gaps: () -> List<SeriesGap> = { emptyList() },
/** Films held for an odd running time ([oddRuntimeReport]). */
oddRuntimes: () -> List<OddRuntime> = { emptyList() }) {
var mode by remember { mutableStateOf(DirectorMode.Balanced) }
var version by remember { mutableIntStateOf(0) }
var report by remember { mutableStateOf<DeskReport?>(null) }
@@ -420,6 +422,8 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ
LaunchedEffect(version) { rotationCards = withContext(Dispatchers.Default) { runCatching { rotation() }.getOrDefault(emptyList()) } }
var gapList by remember { mutableStateOf(emptyList<SeriesGap>()) }
LaunchedEffect(version) { gapList = withContext(Dispatchers.Default) { runCatching { gaps() }.getOrDefault(emptyList()) } }
var oddList by remember { mutableStateOf(emptyList<OddRuntime>()) }
LaunchedEffect(version) { oddList = withContext(Dispatchers.Default) { runCatching { oddRuntimes() }.getOrDefault(emptyList()) } }
val scope = rememberCoroutineScope()
LaunchedEffect(mode, version) { withContext(Dispatchers.Default) { runCatching { load(mode) }.getOrNull() }?.let { report = it; OrbitTiming.ready("Settings/Director") } }
Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -495,6 +499,7 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ
else -> thin.forEach { c -> ChairCard("RUNNING THIN", "${c.channelName} · ${c.block}", "${c.proposals.size} IDEAS", c.line, onClick = { rotationOpen = c }) }
}
gapList.forEach { g -> ChairCard("SHORT OF EPISODES", "${g.title} · ${g.channelName}", null, g.line) }
oddList.forEach { o -> ChairCard("ODD RUNNING TIME", "${o.title} · ${o.channelName}", null, o.line) }
Spacer(Modifier.height(4.dp))
Text("NEEDS YOUR EYE", color = Ink, fontFamily = Anton, fontSize = 14.sp)
val asks = r.asks.filter { it.id !in decided }
@@ -1047,6 +1047,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
} },
rotation = { session?.let { active -> rotationReport(scheduleStore, catalogue, active.accountId) }.orEmpty() },
gaps = { session?.let { active -> gapReport(scheduleStore, active.accountId) }.orEmpty() },
oddRuntimes = { session?.let { active -> oddRuntimeReport(scheduleStore, active.accountId) }.orEmpty() },
decideRotation = { card, approved -> withContext(Dispatchers.IO) {
val active = session ?: return@withContext "Not connected to the server, so nothing was changed."
val applied = runCatching { decideRotation(scheduleStore, active.accountId, card, approved) }.getOrElse { -1 }
@@ -0,0 +1,45 @@
package tv.orbit.classic
import org.json.JSONArray
import java.io.File
/**
* Odd running times (Paul, 23 November 2026: a 10-hour file of "Coming Home for Christmas" was booked on Mistletoe). A film
* whose file runs longer than [ODD_FILM_RUNTIME_MS] isn't booked until you've looked: it's held, not dropped, and shows in the
* Director's Chair under Schedule health. Long legitimate films (an extended Return of the King runs about 4 hours 20) stay
* under the line, and Ring X's events, which really do run for hours, are never held. Once you've let one through it's booked
* as normal. Programmes already booked aren't touched.
*/
internal const val ODD_FILM_RUNTIME_MS = 5 * 60 * 60_000L
/** Channels whose events legitimately run long. */
internal val LongEventChannels = setOf(401)
internal fun isOddRuntime(film: PoolSeries, channel: Int, released: Set<String>) =
film.isFilm && channel !in LongEventChannels && film.id !in released && film.episodes.first().durationMs > ODD_FILM_RUNTIME_MS
internal fun withoutOddRuntimes(pool: List<PoolSeries>, channel: Int, released: Set<String>): List<PoolSeries> =
pool.filter { !isOddRuntime(it, channel, released) }
internal class OddRuntime(val channel: Int, val channelName: String, val id: String, val title: String, val minutes: Long) {
val line get() = "Its file runs ${minutes / 60} hours ${minutes % 60} minutes, so it isn't booked until you've looked at it."
}
/** Films held for an odd running time on every channel on the box, from the pools it has kept. Read only. */
internal fun oddRuntimeReport(store: ScheduleStore, userId: String): List<OddRuntime> {
val released = store.runtimeReleases().load()
return SmartChannels.flatMap { p ->
store.loadPool(userId, p.number)?.series.orEmpty().filter { isOddRuntime(it, p.number, released) }
.map { OddRuntime(p.number, p.name, it.id, it.title, it.episodes.first().durationMs / 60_000) }
}
}
/** The films let through. Ids only. */
internal class RuntimeReleases(private val file: File) {
fun load(): Set<String> = runCatching { JSONArray(file.readText()).let { a -> (0 until a.length()).map { a.getString(it) }.filter(EmbyClient::validId).toSet() } }.getOrDefault(emptySet())
fun add(id: String): String {
if (!EmbyClient.validId(id)) return "refused: a bad item id"
val ids = load() + id
writeSafely(file) { out -> out.write(JSONArray(ids.sorted()).toString().toByteArray()) }
return "released $id"
}
}
@@ -185,6 +185,8 @@ internal class ScheduleStore(private val directory: File) {
/** Files that wouldn't play on this box, across every channel. Never planned again. */
fun unplayable() = UnplayableLog(File(directory, "failed-reasons-0.json"))
/** Films you've looked at and let through despite an odd running time ([RuntimeReview]). */
fun runtimeReleases() = RuntimeReleases(File(directory, "runtime-released-0.json"))
fun saveFailed(userId: String, ids: Set<String>) =
write(file("failed", 0), root(userId, 0).put("items", JSONArray(ids.toList())))
/**
@@ -0,0 +1,68 @@
package tv.orbit.classic
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/** Mistletoe's 10-hour booking (Paul, 23 November 2026), and the odd-running-time hold that follows from it. */
class BookingFixTest {
private val min = 60_000L
private val start = 1_795_000_000_000L
private fun film(id: String, minutes: Long) = PoolSeries(id, "Film $id", listOf(PoolEpisode(id, "src$id", EpisodeMark(1, 1), "Film $id", minutes * min)))
private fun entry(f: PoolSeries, at: Long) = ScheduleEntry(f.id, EpisodeMark(1, 1), ScheduledMedia(filmItem(f), "src${f.id}", f.episodes.first().durationMs), at, "w")
private val bad = film("bad", 600)
private val before = film("b", 90)
private val after = film("a", 95)
private val plan = ChannelPlan(listOf(entry(before, start - 90 * min), entry(bad, start), entry(after, start + 600 * min)), ScheduleCursor())
private val pool = listOf(bad, before, after) + (1..8).map { film("r$it", listOf(95L, 98L, 100L, 92L, 97L, 98L, 91L, 91L)[it - 1]) }
@Test fun theBookingIsReplacedAndNothingElseMoves() {
val (fixed, why) = BookingFix.replaced(plan, pool, start, "bad", listOf("r1", "r2", "r3", "r4", "r5", "r6"), start - 60 * min)
fixed!!
assertTrue(why, why.startsWith("replaced with 6 films"))
assertEquals(plan.entries.first(), fixed.entries.first())
assertEquals(plan.entries.last(), fixed.entries.last())
assertTrue(fixed.entries.none { it.seriesId == "bad" })
fixed.entries.zipWithNext().forEach { (a, b) -> assertEquals(a.endMs, b.startMs) }
// The last film's slot runs to where the bad booking ended; its real length is kept so the ident fills the rest.
val last = fixed.entries[fixed.entries.size - 2]
assertEquals(start + 600 * min, last.endMs)
assertEquals(98 * min, last.fileMs)
assertEquals(118 * min, last.media.durationMs)
assertTrue(fixed.tail.filmShown.keys.containsAll(listOf("r1", "r6")))
}
@Test fun itRefusesAnythingUnsafe() {
fun why(ids: List<String>, at: Long = start, old: String = "bad", now: Long = start - min) = BookingFix.replaced(plan, pool, at, old, ids, now)
assertNull(why(listOf("r1"), now = start + min).first) // already on air
assertNull(why(listOf("r1", "r2", "r3", "r4", "r5", "r6"), at = start + 1).first) // no such booking
assertNull(why(listOf("r1", "r1", "r2", "r3", "r4", "r5")).first) // named twice
assertNull(why(listOf("r1", "r2", "r3", "r4", "r5", "r6", "r7")).first) // runs past the slot
assertNull(why(listOf("r1", "r2", "r3", "r4", "r5")).first) // leaves too long a gap
assertNull(why(listOf("r1", "r2", "r3", "r4", "r5", "nope")).first) // not in the pool
assertNull(why(listOf("r1", "r2", "r3", "r4", "r5", "bad")).first) // the file itself
}
@Test fun anOddRunningTimeIsHeldUntilReleasedExceptOnRingX() {
val long = film("long", 10 * 60); val rotk = film("rotk", 263)
assertTrue(isOddRuntime(long, 701, emptySet()))
assertFalse(isOddRuntime(rotk, 301, emptySet()))
assertFalse(isOddRuntime(long, 401, emptySet()))
assertFalse(isOddRuntime(long, 701, setOf("long")))
assertEquals(listOf("rotk"), withoutOddRuntimes(listOf(long, rotk), 701, emptySet()).map { it.id })
// A series episode is never held by this rule.
val show = PoolSeries("s", "Show", listOf(PoolEpisode("e1", "x", EpisodeMark(1, 1), "One", 6 * 60 * min), PoolEpisode("e2", "x", EpisodeMark(1, 2), "Two", 30 * min)))
assertFalse(isOddRuntime(show, 701, emptySet()))
}
@Test fun releasesAreKept() {
val f = java.io.File.createTempFile("released", ".json").apply { delete(); deleteOnExit() }
val r = RuntimeReleases(f)
assertEquals(emptySet<String>(), r.load())
assertEquals("released 5551701", r.add("5551701"))
assertEquals(setOf("5551701"), r.load())
assertTrue(r.add("../x").startsWith("refused"))
}
}