Build 76: scheduler fixes from the new-channel checks, and the Blender idents

- A block's film is the film it names (IMDb ID, else year within one): remakes no longer slip into another film's block
  (OUTLAW's 2007 3:10 to Yuma in the morning; also Horror and Christmas mix-ups)
- One-a-night film events play one film (Silver Screen's Sunday epic played two)
- Hitchcock Nights starts on time at 20:00
- On-time events on film channels: plan the lead-in from the block that actually precedes the appointment, three films
  and eight hours ahead, rested films first; a film may end up to 15 minutes early, the end card holding its slot
  (Frontline's 12:00 series runs were up to 58 minutes late)
- Story parts read up to twelve, so a nine-part miniseries isn't a six-part story (Masters of the Air)
- New idents for Stories, OUTLAW, Silver Screen and Frontline; block idents for After Sundown, The Cost of War,
  Hitchcock Nights and Stories' After Hours
- SnapshotRegressionTest: plans every film channel from a pulled TV snapshot and reports late, doubled and long events

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 11:30:28 +00:00
co-authored by Claude Opus 5.5
parent 39ef8fa059
commit f02b521a89
23 changed files with 217 additions and 30 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 = 75
val ORBIT_BUILD = 76
android {
namespace = "tv.orbit.classic"
compileSdk = 36
@@ -53,7 +53,12 @@ internal val BlockIdents: Map<String, BlockIdent> = mapOf(
"ringx.ppv" to BlockIdent(R.raw.block_ringx_ppv, R.raw.block_ringx_ppv_sting, BlockOverlay.TonightsEvent),
"terra.sunday" to BlockIdent(R.raw.block_terra_sunday, R.raw.block_terra_sunday_sting),
// OUTLAW's After Sundown (Paul, 23 November 2026): the brand kit's ident, with a distant shot and a low twang.
// The new channels' block idents (Paul, 24 November 2026), made in Blender: After Sundown on OUTLAW's own street at night,
// Frontline's Cost of War after sunset, Silver Screen's Hitchcock Nights and Orbit Stories' late block, After Hours.
"outlaw.sundown" to BlockIdent(R.raw.block_outlaw_sundown, R.raw.block_outlaw_sundown_sting),
"frontline.cost" to BlockIdent(R.raw.block_frontline_cost, R.raw.block_frontline_cost_sting),
"silver.hitchcock" to BlockIdent(R.raw.block_silver_hitchcock, R.raw.block_silver_hitchcock_sting),
"stories.afterhours" to BlockIdent(R.raw.block_stories_afterhours, R.raw.block_stories_afterhours_sting),
// Saturday Mornings (Paul, 6 November 2026): the weekend cartoons on Heroes, Orbit X and Rewind, each in its own
// colours with its logo; Sundays read SUNDAY.
"saturday.heroes" to BlockIdent(R.raw.block_saturday_heroes, R.raw.block_saturday_mornings_sting),
@@ -419,9 +419,9 @@ internal fun dayPartFor(pool: List<PoolSeries>, parts: List<DayPart>, startMs: L
val titles = part.titles.map(::seriesKey).toSet()
// A film is named with its year, as "Halloween (1978)"; the pool already holds that exact film under its plain title,
// or with the year in its name, as the VPS names its events ("AEW All Out 2019" for "AEW All Out (2019)").
val films = part.titles.flatMap { FilmIdentity.of(it).let { f -> listOfNotNull(seriesKey(f.title), f.year?.let { y -> seriesKey("${f.title} $y") }) } }.toSet()
val films = part.titles.map(FilmIdentity::of)
val open = openJoins(part, parts)
pool.filter { seriesKey(it.title) in titles || (it.isFilm && seriesKey(it.title) in films) || inGroup(it, part.group) || (open && it.group == OPEN_GROUP) }
pool.filter { seriesKey(it.title) in titles || (it.isFilm && films.any { f -> f.names(it) }) || inGroup(it, part.group) || (open && it.group == OPEN_GROUP) }
}
if (allowed.isNotEmpty()) return Triple(allowed, name, part)
}
@@ -566,8 +566,16 @@ internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor,
var start = fromMs
val marks = cursor.marks.toMutableMap()
val blockRest = HashMap<DayPart?, Long>()
// A one-a-night event gives the rest of its window to the usual block once it has started a film (Paul, 24 November 2026:
// Silver Screen's Sunday epic played Doctor Zhivago and then Ben-Hur, which ran into the evening's Great Films).
fun hadItsTurn(available: List<PoolSeries>, at: Long) = available.any { film -> film.isFilm && shown[film.id]?.let { at - it < ONCE_A_NIGHT_MS } == true }
fun partAt(at: Long): Triple<List<PoolSeries>, String, DayPart?> {
val first = dayPartFor(pool, dayParts, at, zone)
val part = first.third ?: return first
return if (part.once && hadItsTurn(first.first, at)) dayPartFor(pool, dayParts - part, at, zone) else first
}
while (start < untilMs) {
val (available, block, part) = dayPartFor(pool, dayParts, start, zone)
val (available, block, part) = partAt(start)
// An event naming only a series plays its next whole episode, once a night. Everywhere else is films only.
val series = available.singleOrNull()?.takeIf { !it.isFilm && block.startsWith("event ") }
if (series != null && shown[series.id]?.let { start - it < SERIES_NIGHT_MS } != true) {
@@ -595,13 +603,20 @@ internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor,
val rest = if (adaptiveRest && part?.days.isNullOrEmpty()) blockRest.getOrPut(part) { sharedAdaptiveRestMs(pool, dayParts, part, restMs) } else restMs
var (film, why) = chooseFilm(films, shown, start, rest, avoid, network)
// Before an appointment, a rested film that leaves it on time, picked in the same seeded order as any other.
val appointment = if (part?.onTime == true) null else nextAppointment(start, zone, (ON_TIME_FILM_RUN_IN_MS / (60 * 60_000L)).toInt()) { at -> dayPartFor(pool, dayParts, at, zone) }
val appointment = if (part?.onTime == true) null else nextAppointment(start, zone, (ON_TIME_FILM_RUN_IN_MS / (60 * 60_000L)).toInt()) { at -> partAt(at) }
if (appointment != null) {
val clear = films.filter { f -> !avoid(f, start, start + f.episodes.first().durationMs) }.let { c -> c.filter { !network(it, start) }.ifEmpty { c } }
// Rested films in the same seeded order as any other pick; when none is rested, the longest waiting first, as the fallback would.
val rested = clear.filter { f -> shown[f.id]?.let { start - it >= rest } != false }.shuffled(java.util.Random(start))
.ifEmpty { clear.sortedBy { shown[it.id] ?: Long.MIN_VALUE } }
fitBeforeAppointment(appointment, start, film, rested, ON_TIME_FILM_RUN_IN_MS, followers = 2) { start + it.episodes.first().durationMs }?.let {
// Rested films in the same seeded order as any other pick, then the rest, longest waiting first, so a small block
// can still land the appointment on time (Paul, 24 November 2026: Frontline's 12:00 series runs started up to 55
// minutes late, as the few rested Britain at War films couldn't add up to 12:00).
val restedOnly = clear.filter { f -> shown[f.id]?.let { start - it >= rest } != false }.shuffled(java.util.Random(start))
val rested = restedOnly + clear.filter { it !in restedOnly }.sortedBy { shown[it.id] ?: Long.MIN_VALUE }
val ends = { f: PoolSeries -> start + f.episodes.first().durationMs }
// The films that will lead into the appointment: the block just before it, when that isn't this one (Paul, 24 November
// 2026: Frontline planned 12:00 from After Hours' films at 04:41, though Britain at War's, all over 98 minutes, followed).
val leadIn = partAt(appointment - 60_000L).takeIf { it.third != part }?.first?.filter { it.isFilm }?.ifEmpty { null } ?: rested
(fitBeforeAppointment(appointment, start, film, restedOnly, ON_TIME_FILM_RUN_IN_MS, followers = 3, exact = true, earlyMs = FILM_EARLY_MS, followerCandidates = leadIn, ends = ends)
?: fitBeforeAppointment(appointment, start, film, rested, ON_TIME_FILM_RUN_IN_MS, followers = 3, earlyMs = FILM_EARLY_MS, followerCandidates = leadIn, ends = ends))?.let {
film = it
why = "$why; chosen to finish before the appointment at ${java.time.Instant.ofEpochMilli(appointment).atZone(zone).toLocalTime()}"
}
@@ -613,6 +628,14 @@ internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor,
shown[film.id] = start
last = film.id
start += copy.durationMs
// A film ending a little before an appointment holds its slot to it, the channel's ident filling the minutes left, as
// after any short file (Paul, 24 November 2026: Frontline's long films can rarely add up to exactly 12:00).
nextAppointment(start, zone, 1) { at -> partAt(at) }?.takeIf { it - start in 1..FILM_EARLY_MS && part?.onTime != true }?.let { at ->
val booked = entries.removeAt(entries.lastIndex)
val length = at - booked.startMs
entries += booked.copy(media = booked.media.copy(item = booked.media.item.copy(minutes = length / 60_000, durationMs = length), durationMs = length), fileMs = copy.durationMs)
start = at
}
}
return ChannelPlan(entries, ScheduleCursor(last, marks, shown))
}
@@ -643,8 +666,23 @@ private fun adaptiveRestMs(films: List<PoolSeries>, hours: Int, restMs: Long): L
internal fun filmsIn(pool: List<PoolSeries>, part: DayPart): List<PoolSeries> {
if (part.titles.isEmpty() && part.group.isEmpty()) return pool.filter { it.isFilm }
val titles = part.titles.map(::seriesKey).toSet()
val films = part.titles.map { seriesKey(FilmIdentity.of(it).title) }.toSet()
return pool.filter { it.isFilm && (seriesKey(it.title) in titles || seriesKey(it.title) in films || inGroup(it, part.group)) }
val films = part.titles.map(FilmIdentity::of)
return pool.filter { it.isFilm && (seriesKey(it.title) in titles || films.any { f -> f.names(it) } || inGroup(it, part.group)) }
}
/**
* Whether a block's film entry means this pool film. The title must agree (plain, or with the year in its name as the VPS
* names events), and then the film itself: by IMDb ID where both have one, else by year, a year out by one still agreeing
* as release dates differ between countries (Paul, 24 November 2026: the 2007 "3:10 to Yuma", an After Sundown film, was
* booked in OUTLAW's morning block because the 1957 original is in it, and so was the 2016 "The Magnificent Seven").
*/
internal fun FilmIdentity.names(film: PoolSeries): Boolean {
val key = seriesKey(film.title)
if (key != seriesKey(title) && (year == null || key != seriesKey("$title $year"))) return false
val own = imdb?.lowercase(); val theirs = film.ref.lowercase().removePrefix("imdb.").takeIf { film.ref.lowercase().startsWith("imdb.") }
if (own != null && theirs != null) return own == theirs
val y = year; val fy = film.year
return y == null || fy == null || kotlin.math.abs(y - fy) <= 1
}
/**
@@ -679,7 +717,11 @@ private const val ON_TIME_LAST_CALL_MS = 60 * 60_000L
/** How long before an appointment the programmes leading into it may be adjusted. */
private const val ON_TIME_RUN_IN_MS = 90 * 60_000L
/** The same for films, which are long: the last two or three before an appointment have to be chosen together for it to start in time. */
private const val ON_TIME_FILM_RUN_IN_MS = 6 * 60 * 60_000L
// Eight hours and three films ahead (Paul, 24 November 2026): Frontline's Britain at War films run 98 to 138 minutes, so no two
// of them make 12:00 from 07:00 and the run has to be planned from the film before.
private const val ON_TIME_FILM_RUN_IN_MS = 8 * 60 * 60_000L
/** How early a film channel's run may land before an appointment, its last film's slot held to it by the channel's ident. */
internal const val FILM_EARLY_MS = 15 * 60_000L
/**
* The next on-time appointment within [lookaheadHours] after [at]: the first hour boundary whose part is an
@@ -701,29 +743,39 @@ internal fun nextAppointment(at: Long, zone: java.time.ZoneId, lookaheadHours: I
* planner's own order of preference and already satisfy its rules. Null keeps [chosen].
*/
internal fun <T> fitBeforeAppointment(appointment: Long, start: Long, chosen: T, candidates: List<T>, runInMs: Long = ON_TIME_RUN_IN_MS,
/** How many more programmes may follow before the appointment: 1 for series, 2 for films, which are long. */
followers: Int = 1, graceMs: Long = ON_TIME_GRACE_MS, ends: (T) -> Long): T? {
/** How many more programmes may follow before the appointment: 1 for series, 3 for films, which are long. */
followers: Int = 1, graceMs: Long = ON_TIME_GRACE_MS,
/** True keeps to programmes that land the appointment in its grace, without the late fallbacks, so a caller can widen its candidates first. */
exact: Boolean = false,
/** How early a run may end, the channel's ident holding until the appointment: 0 for series; [FILM_EARLY_MS] for films. */
earlyMs: Long = 0,
/** What may follow [chosen] before the appointment, when that's a different block's (films): [candidates] otherwise. */
followerCandidates: List<T> = candidates, ends: (T) -> Long): T? {
val latest = appointment + graceMs
val earliest = appointment - earlyMs
if (ends(chosen) <= appointment - runInMs) return null
val remaining = appointment - start
fun length(x: T) = ends(x) - start
/** Whether [first] can open a run of up to [followers] more different candidates that ends at the appointment or in its grace. */
fun opensRun(first: T): Boolean {
val total = length(first)
if (total in remaining..remaining + graceMs) return true
val window = remaining - earlyMs..remaining + graceMs
if (total in window) return true
if (total > remaining) return false
val rest = candidates.filter { it != first }.map(::length)
if (followers >= 1 && rest.any { total + it in remaining..remaining + graceMs }) return true
if (followers >= 2) rest.forEachIndexed { i, a -> if (total + a < remaining) for (j in i + 1 until rest.size) if (total + a + rest[j] in remaining..remaining + graceMs) return true }
val rest = followerCandidates.filter { it != first }.map(::length)
if (followers >= 1 && rest.any { total + it in window }) return true
if (followers >= 2) rest.forEachIndexed { i, a -> if (total + a < window.first) for (j in i + 1 until rest.size) if (total + a + rest[j] in window) return true }
if (followers >= 3) rest.forEachIndexed { i, a -> if (total + a < window.first) for (j in i + 1 until rest.size) if (total + a + rest[j] < window.first)
for (k in j + 1 until rest.size) if (total + a + rest[j] + rest[k] in window) return true }
return false
}
if (opensRun(chosen)) return null
val fits = candidates.filter { ends(it) <= latest }
// Best is one ending at the appointment, then one a single programme can follow in time, then any that opens a run.
return fits.firstOrNull { ends(it) >= appointment }
?: fits.firstOrNull { x -> ends(x) < appointment && candidates.any { it != x && ends(x) + length(it) in appointment..latest } }
return fits.firstOrNull { ends(it) >= earliest }
?: fits.firstOrNull { x -> ends(x) < earliest && followerCandidates.any { it != x && ends(x) + length(it) in earliest..latest } }
?: fits.firstOrNull { opensRun(it) }
?: fits.firstOrNull().takeIf { ends(chosen) > latest }
?: if (exact) null else fits.firstOrNull().takeIf { ends(chosen) > latest }
// Failing that, at least something that ends while the appointment's window is still open, so it isn't missed.
?: candidates.firstOrNull { ends(it) < appointment + ON_TIME_LAST_CALL_MS }.takeIf { ends(chosen) >= appointment + ON_TIME_LAST_CALL_MS }
}
@@ -45,8 +45,8 @@ private val SilverEpics = listOf(
"The Ten Commandments (1956)", "Doctor Zhivago (1965)")
internal val SilverScreenFilms get() = (SilverMorning + SilverMatinee + SilverGreat + SilverHitchcock + SilverNoir + SilverEpics).distinct()
internal val SilverScreenDayParts get() = listOf(
// Hitchcock Nights (Paul, 23 November 2026): every Friday evening, a Hitchcock and a complementary noir or classic thriller.
DayPart(20, 0, SilverHitchcock + SilverNoir, group = "Hitchcock Nights", days = setOf(DayOfWeek.FRIDAY)),
// Hitchcock Nights (Paul, 23 November 2026): every Friday from 20:00, on time, a Hitchcock and a complementary noir or classic thriller.
DayPart(20, 0, SilverHitchcock + SilverNoir, group = "Hitchcock Nights", days = setOf(DayOfWeek.FRIDAY), onTime = true, key = "silver.hitchcock"),
// The Sunday epic: one a week, on time at 14:00.
DayPart(14, 18, SilverEpics, group = "Sunday Epic", days = setOf(DayOfWeek.SUNDAY), onTime = true, once = true),
DayPart(6, 12, SilverMorning, group = "Morning Pictures"), DayPart(12, 18, SilverMorning + SilverMatinee, group = "Matinee"),
@@ -97,7 +97,7 @@ internal val FrontlineDayParts get() = listOf(
duty("Generation Kill", DayOfWeek.THURSDAY, 1, 2), duty("SAS Rogue Heroes", DayOfWeek.FRIDAY, 1, 2), duty("Masters of the Air", DayOfWeek.SATURDAY, 1, 2),
duty("The Rat Patrol", DayOfWeek.SATURDAY, 15, 3),
DayPart(6, 12, FrontlineBritain, group = "Britain at War"), DayPart(12, 17, FrontlineBritain + FrontlineMissions, group = "On Duty"),
DayPart(17, 21, FrontlineMissions, group = "Missions and Escapes"), DayPart(21, 1, FrontlineCostOfWar, group = FRONTLINE_COST),
DayPart(17, 21, FrontlineMissions, group = "Missions and Escapes"), DayPart(21, 1, FrontlineCostOfWar, group = FRONTLINE_COST, key = "frontline.cost"),
DayPart(1, 6, FrontlineCostOfWar + FrontlineModernCombat, group = "After Hours"))
internal const val FRONTLINE_COST = "The Cost of War"
@@ -20,7 +20,7 @@ private val StoriesLate = listOf("Skins", "Shameless", "Euphoria (US)", "Ally Mc
internal val StoriesShows get() = (StoriesMornings + StoriesWards + StoriesAfterSchool + StoriesPrimetime + StoriesLate).distinct()
internal val StoriesDayParts get() = listOf(
DayPart(6, 12, StoriesMornings), DayPart(12, 17, StoriesWards), DayPart(17, 20, StoriesAfterSchool), DayPart(20, 23, StoriesPrimetime),
DayPart(23, 2, StoriesLate),
DayPart(23, 2, StoriesLate, key = "stories.afterhours"),
// Overnight repeats: the grown-up evening and late series, so nothing mature reaches the daytime.
DayPart(2, 6, StoriesPrimetime + StoriesLate))
/** Tiers: Casualty and Holby City have 550 episodes or more each, so they're supporting and the rest core. */
@@ -22,8 +22,13 @@ internal class ShowStories(stories: List<Story>) {
fun partOf(episode: PoolEpisode) = of(episode)?.parts?.indexOfFirst { it.id == episode.id } ?: -1
}
private val PartNumber = Regex("""(?:\((\d)\)|,?\s*\bPart\s+(\d|One|Two|Three|Four|Five|Six|I{1,3}|IV|V|VI))\s*$""", RegexOption.IGNORE_CASE)
private val PartWords = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "i" to 1, "ii" to 2, "iii" to 3, "iv" to 4, "v" to 5, "vi" to 6)
// Read up to twelve, so a miniseries titled "Part One" to "Part Nine" is seen as nine parts, too many for a story, and not
// taken for a six-part story with the rest cut off (Paul, 24 November 2026: Frontline played Masters of the Air's first six
// episodes in one night).
private val PartNumber = Regex("""(?:\((\d{1,2})\)|,?\s*\bPart\s+(\d{1,2}|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|XII|XI|X|IX|VIII|VII|VI|IV|V|I{1,3}))\s*$""", RegexOption.IGNORE_CASE)
private val PartWords = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9,
"ten" to 10, "eleven" to 11, "twelve" to 12, "i" to 1, "ii" to 2, "iii" to 3, "iv" to 4, "v" to 5, "vi" to 6, "vii" to 7, "viii" to 8, "ix" to 9,
"x" to 10, "xi" to 11, "xii" to 12)
/** The part number a title ends with, or null. */
internal fun partNumber(title: String): Int? = PartNumber.find(title)?.let { match ->
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -30,7 +30,9 @@ class EventAppointmentsTest {
.map { (date, es) -> (es.minOf { it.startMs } - date.atTime(21, 0).atZone(zone).toInstant().toEpochMilli()) / 60_000 }
assertEquals(3, starts.size)
assertTrue("late by $starts", starts.all { it in 0..20 })
assertTrue(plan.entries.all { it.media.durationMs == films.first { f -> f.id == it.seriesId }.episodes.first().durationMs })
// Nothing is cut: a film plays whole, its slot held at most FILM_EARLY_MS longer for an appointment (24 November 2026).
assertTrue(plan.entries.all { val file = films.first { f -> f.id == it.seriesId }.episodes.first().durationMs
it.media.durationMs == file || (it.fileMs == file && it.media.durationMs - file in 1..FILM_EARLY_MS) })
}
@Test fun aWeightedEventStartsNearItsHour() {
@@ -0,0 +1,29 @@
package tv.orbit.classic
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.DayOfWeek
import java.time.ZoneOffset
/** A one-a-night film event plays one film (Paul, 24 November 2026: Silver Screen's Sunday epic played two). */
class FilmEventOnceTest {
private val hour = 60 * 60_000L
private fun film(id: String, minutes: Int) = PoolSeries(id, "Film $id", listOf(PoolEpisode(id, "src", EpisodeMark(1, 1), "Film $id", minutes * 60_000L)))
private val epics = (1..6).map { film("e$it", 200) }
private val others = (1..40).map { film("f$it", 85 + (it * 7) % 41) }
private val sunday = java.time.LocalDate.of(2026, 11, 29).atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
@Test fun theSundayEpicPlaysOnceAndOnTime() {
val parts = listOf(
DayPart(14, 18, epics.map { it.title }, group = "Sunday Epic", days = setOf(DayOfWeek.SUNDAY), onTime = true, once = true),
DayPart(0, 24, others.map { it.title }, group = "Films"))
val plan = extendFilmSchedule(epics + others, ScheduleCursor(), sunday, sunday + 24 * hour, 7 * 24 * hour, parts, ZoneOffset.UTC)
val epicIds = epics.map { it.id }.toSet()
val played = plan.entries.filter { it.seriesId in epicIds }
assertEquals(1, played.size)
val at = played.single().startMs
assertTrue("starts ${(at - sunday) / 60_000} minutes into Sunday", at in sunday + 14 * hour..sunday + 14 * hour + 20 * 60_000L)
plan.entries.zipWithNext().forEach { (a, b) -> assertEquals(a.endMs, b.startMs) }
}
}
@@ -21,8 +21,8 @@ class PresentationTest {
val keys = SmartChannels.flatMap { it.dayParts }.map { it.key }.filter { it.isNotEmpty() }.toSet() - Takeovers.map { it.key }.toSet()
// Riot 3, After Dark 3, Horror, Gold, Three, Vortex 4 (Movie Night, Prime, Afterburn and its premiere), Orbit 2 2, Ring X 7 (six nights and PPV), Terra,
// and Saturday Mornings on Heroes, Orbit X and Rewind.
// OUTLAW's After Sundown joined on 23 November 2026.
assertEquals(27, keys.size)
// OUTLAW's After Sundown joined on 23 November 2026; Frontline's Cost of War, Hitchcock Nights and Stories' After Hours on the 24th.
assertEquals(30, keys.size)
assertEquals(emptySet<String>(), keys - BlockIdents.keys)
assertTrue(keys.all { PRESENTATION_KEY.matches(it) })
}
@@ -0,0 +1,45 @@
package tv.orbit.classic
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/** A block's film is the film it names, never a remake of the same name (Paul, 24 November 2026: OUTLAW's 3:10 to Yuma). */
class RemakeBlocksTest {
private fun film(id: String, title: String, year: Int?, ref: String = "") =
PoolSeries(id, title, listOf(PoolEpisode(id, "src", EpisodeMark(1, 1), title, 100 * 60_000L)), ref = ref, year = year)
private val original = film("a", "3:10 to Yuma", 1957, "imdb.tt0050086")
private val remake = film("b", "3:10 to Yuma", 2007, "imdb.tt0381849")
@Test fun theOriginalsBlockDoesNotTakeTheRemake() {
val part = DayPart(6, 12, listOf("3:10 to Yuma (1957)"))
assertEquals(listOf("a"), filmsIn(listOf(original, remake), part).map { it.id })
val late = DayPart(22, 2, listOf("3:10 to Yuma (2007)"))
assertEquals(listOf("b"), filmsIn(listOf(original, remake), late).map { it.id })
}
@Test fun byYearWithoutIds() {
val a = film("a", "The Magnificent Seven", 1960); val b = film("b", "The Magnificent Seven", 2016)
val part = DayPart(6, 12, listOf("The Magnificent Seven (1960)"))
assertEquals(listOf("a"), filmsIn(listOf(a, b), part).map { it.id })
}
@Test fun aYearOutByOneOrUnknownStillCounts() {
assertTrue(FilmIdentity("Legends of the Fall", 1994).names(film("x", "Legends of the Fall", 1995)))
assertTrue(FilmIdentity("Legends of the Fall", 1994).names(film("x", "Legends of the Fall", null)))
assertTrue(FilmIdentity("Legends of the Fall", null).names(film("x", "Legends of the Fall", 1995)))
assertFalse(FilmIdentity("Legends of the Fall", 1994).names(film("x", "Legends of the Fall", 1997)))
assertFalse(FilmIdentity("Something Else", 1994).names(film("x", "Legends of the Fall", 1994)))
}
@Test fun anEventNamedWithItsYearStillMatches() {
assertTrue(FilmIdentity("AEW All Out", 2019).names(film("x", "AEW All Out 2019", null)))
}
@Test fun theDayPartPoolFollowsTheSameRule() {
val parts = listOf(DayPart(0, 24, listOf("3:10 to Yuma (1957)")))
val (allowed, _, _) = dayPartFor(listOf(original, remake), parts, 0L, java.time.ZoneOffset.UTC)
assertEquals(listOf("a"), allowed.map { it.id })
}
}
@@ -0,0 +1,49 @@
package tv.orbit.classic
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
import java.time.ZoneOffset
/**
* Plans a week for every film channel from a pulled TV snapshot (ORBIT_SNAP=<schedule dir>), and reports what a person would
* notice: gaps, late on-time events, one-a-night events playing twice, series nights running long, and films outside their
* block. Skipped without a snapshot; a report, not a pass mark, written to ORBIT_SNAP_OUT.
*/
class SnapshotRegressionTest {
@Test fun filmChannelsFromTheTv() {
val dir = System.getenv("ORBIT_SNAP")?.let(::File)
assumeTrue(dir != null && dir.isDirectory)
val user = File(dir, "schedule-101.json").takeIf { it.exists() }?.let { org.json.JSONObject(it.readText()).getString("user") }
?: dir!!.listFiles()!!.first { it.name.startsWith("schedule-") }.let { org.json.JSONObject(it.readText()).getString("user") }
val store = ScheduleStore(dir!!)
val zone = ZoneOffset.UTC
val midnight = java.time.LocalDate.of(2026, 11, 30).atStartOfDay(zone).toInstant().toEpochMilli()
val hour = 60 * 60_000L
val out = StringBuilder()
for (p in SmartChannels.filter { it.filmRestMs != null }) for (offset in 0 until 8) {
val pool = store.loadPool(user, p.number)?.series ?: continue
val from = midnight + offset * (3 * hour + 17 * 60_000L)
val plan = extendSchedule(pool, ScheduleCursor(), from, from + 7 * 24 * hour, p.filmRestMs, dayParts = p.dayParts, zone = zone, adaptiveRest = p.adaptiveFilmRest)
val e = plan.entries
if (p.number == 313 && offset == 6) File((System.getenv("ORBIT_SNAP_OUT") ?: "/tmp/x") + ".313").writeText(e.joinToString("\n") { "${java.time.Instant.ofEpochMilli(it.startMs).atZone(zone).let { t -> "${t.dayOfWeek} ${t.toLocalTime()}" }} ${it.media.durationMs / 60_000} ${it.media.item.title} | ${it.why}" })
val gaps = e.zipWithNext().count { (a, b) -> a.endMs != b.startMs }
val late = mutableListOf<String>(); val twice = mutableListOf<String>()
for (day in 1 until 7) for (part in p.dayParts.filter { it.onTime || it.once }) {
val dayStart = midnight + day * 24 * hour
val dow = java.time.Instant.ofEpochMilli(dayStart).atZone(zone).dayOfWeek
if (part.days.isNotEmpty() && dow !in part.days) continue
val boundary = dayStart + part.fromHour * hour
val inPart = e.filter { it.why.startsWith("event " + part.group.ifEmpty { "${part.fromHour}-${part.toHour}" } + ";") && it.startMs >= boundary - hour && it.startMs < boundary + 12 * hour }
val first = inPart.minByOrNull { it.startMs } ?: continue
val mins = (first.startMs - boundary) / 60_000
if (part.onTime && mins > 20) late += "$dow ${part.fromHour}:00 +${mins}m"
if (part.once && inPart.count { it.media.item.type != "Episode" } > 1) twice += "$dow ${part.group}"
}
val nights = e.groupBy { it.why.substringBefore(";") to (it.startMs - from) / (24 * hour) }.filterKeys { it.first.startsWith("event ") }
.filter { (_, v) -> v.all { it.media.item.type == "Episode" } && v.size > 4 }.map { (k, v) -> "${k.first} day ${k.second}: ${v.size}" }
if (true || late.isNotEmpty() || twice.isNotEmpty() || nights.isNotEmpty()) out.append("${p.number} ${p.name} start+$offset: ${e.size} programmes, fallbacks ${e.count { "fallback" in it.why }}, held ${e.sumOf { it.fileMs?.let { f -> it.media.durationMs - f } ?: 0L } / 60_000}m in ${e.count { it.fileMs != null }}, gaps $gaps, late ${late.size} ${late.take(6)}, twice $twice, long series nights $nights\n")
}
File(System.getenv("ORBIT_SNAP_OUT") ?: "/tmp/orbit-snap-report.txt").writeText(out.toString())
}
}