diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt index 1a7d4226..c32f4e2c 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -112,7 +112,7 @@ internal class ChannelScheduler(private val store: ScheduleStore, /** Going back to the loop keeps the schedule and the place, so turning it on again carries on. */ fun setEnabled(userId: String, number: Int, enabled: Boolean) { val progress = store.loadProgress(userId, number) - store.saveProgress(userId, number, ScheduleStore.SavedProgress(enabled, progress?.aired ?: ScheduleCursor())) + store.saveProgress(userId, number, ScheduleStore.SavedProgress(enabled, progress?.aired ?: ScheduleCursor(), progress?.ahead.orEmpty())) } /** Books the Drive-In's evenings from the film pools already on the box, so it asks the provider for nothing. */ @@ -610,7 +610,7 @@ internal class ChannelScheduler(private val store: ScheduleStore, if (!(due && cached != null && !onlyWaiting && BackgroundPacing.active)) pool?.let { RefreshStatus.note(number, it.fetchedAtMs, 0, null) } val started = android.os.SystemClock.elapsedRealtime() val progress = store.loadProgress(userId, number) - val base = progress?.aired ?: ScheduleCursor() + var base = progress?.aired ?: ScheduleCursor() // Other channels' plans are only read if this one is actually about to grow, and a plan read before is reused until its file changes. var othersMs = 0L val others by lazy { @@ -624,6 +624,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) + base = placeToPlanFrom(existing, progress, now) val plan = topUpPlan(existing, base, pool?.series?.let { withOpenApprovals(withoutOddRuntimes(withoutFailed(withinRuns(it, programming.episodeRuns), store.loadFailed(userId)), number, store.runtimeReleases().load()), choices) }?.let { if (programming.mixedTurns) mixedTurnOrder(it, number) else it }, now, programming.filmRestMs, programming.finishTogether, programming.dayParts, // SYNDICATE, a series channel that books films every day, also rests a film another channel shows within five days // (25 November 2026), as the film channels do: a preference, given up only when nothing else fits, like a clash. @@ -650,7 +651,7 @@ internal class ChannelScheduler(private val store: ScheduleStore, val all = known + plan.entries.map { it.seriesId } if (all.size != known.size) store.saveBooked(userId, all.toList().takeLast(BOOKED_MAX).toSet()) } - store.saveProgress(userId, number, ScheduleStore.SavedProgress(progress?.enabled ?: true, airedCursor(base, plan.entries, now))) + store.saveProgress(userId, number, progressAfter(progress?.enabled ?: true, base, plan, now)) session.rememberScheduledItems(plan.entries.map { it.media.item }) val planMs = android.os.SystemClock.elapsedRealtime() - started val added = if (plan === existing) emptyList() else plan.entries.filter { it.startMs >= (existing?.endMs ?: Long.MIN_VALUE) } diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt index 24024786..35c96e43 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -51,7 +51,23 @@ internal class ScheduleStore(private val directory: File) { */ const val OLDEST_READABLE = 1 } - internal class SavedProgress(val enabled: Boolean, val aired: ScheduleCursor) + /** + * A channel's place: on or off, what had aired by the last plan, and the programmes booked after then ([ahead], series and + * episode only). If the schedule is ever lost completely (both copies), [airedBy] still knows what went out since the last + * plan, so a series neither starts its season again nor repeats what has already aired (Paul, 1 December 2026). + */ + internal class SavedProgress(val enabled: Boolean, val aired: ScheduleCursor, val ahead: List = emptyList()) { + fun airedBy(nowMs: Long): ScheduleCursor { + // Started before now: aired. One starting this very moment hasn't, and the new plan books in its place. + val gone = ahead.takeWhile { it.startMs < nowMs } + if (gone.isEmpty()) return aired + val marks = aired.marks.toMutableMap(); val shown = aired.filmShown.toMutableMap() + gone.forEach { marks[it.seriesId] = it.mark; if (it.film) shown[it.seriesId] = it.startMs } + return aired.copy(lastSeriesId = gone.last().seriesId, marks = marks, filmShown = shown) + } + } + /** A booked programme as [SavedProgress.ahead] keeps it. */ + internal data class AheadMark(val seriesId: String, val mark: EpisodeMark, val startMs: Long, val film: Boolean) internal class SavedPool(val series: List, val fetchedAtMs: Long, val signature: String = "") private fun file(kind: String, number: Int) = File(directory, "$kind-$number.json") @@ -157,9 +173,13 @@ internal class ScheduleStore(private val directory: File) { } fun saveProgress(userId: String, number: Int, progress: SavedProgress) = - write(file("progress", number), root(userId, number).put("enabled", progress.enabled).put("aired", encodeCursor(progress.aired))) + write(file("progress", number), root(userId, number).put("enabled", progress.enabled).put("aired", encodeCursor(progress.aired)) + .also { o -> if (progress.ahead.isNotEmpty()) o.put("ahead", JSONArray().also { a -> progress.ahead.forEach { m -> a.put(JSONArray().put(m.seriesId).put(m.mark.season).put(m.mark.episode).put(m.startMs).put(if (m.film) 1 else 0)) } }) }) fun loadProgress(userId: String, number: Int): SavedProgress? = read(file("progress", number), userId, number) { root -> - SavedProgress(root.getBoolean("enabled"), decodeCursor(root.getJSONObject("aired"))) + SavedProgress(root.getBoolean("enabled"), decodeCursor(root.getJSONObject("aired")), + // Absent in files saved before 1 December 2026; in start order, as saved. + root.optJSONArray("ahead")?.let { a -> (0 until a.length()).map { i -> a.getJSONArray(i).let { m -> AheadMark(validId(m.getString(0)), EpisodeMark(m.getInt(1), m.getInt(2)), m.getLong(3), m.getInt(4) == 1) } } } + ?.also { list -> require(list.zipWithNext().all { (x, y) -> x.startMs <= y.startMs }) }.orEmpty()) } private fun encodeSeries(list: List): JSONArray { @@ -307,3 +327,15 @@ internal class ScheduleStore(private val directory: File) { /** On forgetting the account. Rollback never needs this: the channel simply goes back to its loop. */ fun clear() { directory.listFiles()?.filter { it.name != "numbering-2" }?.forEach { it.delete() } } } + +/** + * Where a channel plans on from: the saved place, and when the schedule has been lost completely (both copies), also what was + * booked after the last plan and has aired since ([ScheduleStore.SavedProgress.airedBy]), so nothing that went out repeats and + * no series starts its season again. + */ +internal fun placeToPlanFrom(existing: ChannelPlan?, progress: ScheduleStore.SavedProgress?, nowMs: Long): ScheduleCursor = + (if (existing == null) progress?.airedBy(nowMs) else progress?.aired) ?: ScheduleCursor() + +/** The place saved after planning: what has aired by [nowMs], and everything booked after it. */ +internal fun progressAfter(enabled: Boolean, base: ScheduleCursor, plan: ChannelPlan, nowMs: Long) = ScheduleStore.SavedProgress(enabled, airedCursor(base, plan.entries, nowMs), + plan.entries.filter { it.startMs > nowMs }.map { ScheduleStore.AheadMark(it.seriesId, it.mark, it.startMs, it.media.item.type == "Movie") }) diff --git a/android/app/src/main/res/drawable-nodpi/orbit_horror_tv_offair.webp b/android/app/src/main/res/drawable-nodpi/orbit_horror_tv_offair.webp index b2126626..d1ff1403 100644 Binary files a/android/app/src/main/res/drawable-nodpi/orbit_horror_tv_offair.webp and b/android/app/src/main/res/drawable-nodpi/orbit_horror_tv_offair.webp differ diff --git a/android/app/src/test/java/tv/orbit/classic/ScheduleLossTest.kt b/android/app/src/test/java/tv/orbit/classic/ScheduleLossTest.kt new file mode 100644 index 00000000..56fcf403 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/ScheduleLossTest.kt @@ -0,0 +1,101 @@ +package tv.orbit.classic + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.time.LocalDate +import java.time.ZoneId + +/** + * A schedule lost completely, both copies (Paul, 1 December 2026, before Horror TV is signed): the channel must neither start a + * series' season again nor repeat what has already aired. Rounds run as the box runs them (plan, save the plan, save the place), + * through the same [placeToPlanFrom] and [progressAfter] the scheduler uses, with the schedule files deleted now and then. + */ +class ScheduleLossTest { + @get:Rule val folder = TemporaryFolder() + private val user = "fixture-user" + private val zone = ZoneId.systemDefault() + private val minute = 60_000L + private fun serial(name: String, vararg seasons: Int, minutes: Int = 47) = PoolSeries("s-$name", name, + seasons.withIndex().flatMap { (s, n) -> (1..n).map { e -> PoolEpisode("$name-${s + 1}-$e", "m", EpisodeMark(s + 1, e), "$name / S${s + 1} E$e", minutes * minute) } }) + private val pool = listOf(serial("A", 4, 5), serial("B", 6, 3), serial("C", 3, 3, 3), serial("D", 8), serial("E", 5, 5), serial("Anth", 40, minutes = 26)) + // Horror TV's shape: off air by day, an anthology in the evening, a season rotation overnight. + private val parts = listOf(DayPart(6, 18, offAir = true), DayPart(18, 23, listOf("Anth")), DayPart(23, 6, listOf("A", "B", "C", "D", "E"), seasonCap = 2)) + private fun start() = LocalDate.of(2026, 12, 1).atTime(18, 0).atZone(zone).toInstant().toEpochMilli() + + /** Runs rounds every 53 minutes for [days]; [lose] says which rounds find the schedule gone. Returns what aired, in order. */ + private fun run(days: Int, keepAhead: Boolean = true, lose: (Int) -> Boolean): List { + val dir = folder.newFolder(); val store = ScheduleStore(dir) + val aired = sortedMapOf() + var round = 0; var now = start(); var previous = now - 1 + while (now < start() + days * 86_400_000L) { + if (lose(round)) dir.listFiles()!!.filter { it.name.startsWith("schedule") }.forEach { it.delete() } + val existing = store.loadPlan(user, HORROR_TV_NUMBER) + val progress = store.loadProgress(user, HORROR_TV_NUMBER) + // What the TV showed since the last round: the schedule it had then. + existing?.entries?.filter { it.startMs >= previous && it.startMs < now }?.forEach { aired[it.startMs] = it } + if (existing == null) lastPlan?.entries?.filter { it.startMs >= previous && it.startMs < now }?.forEach { aired[it.startMs] = it } + val base = placeToPlanFrom(existing, progress, now) + val plan = topUpPlan(existing, base, pool, now, finishTogether = true, dayParts = parts, zone = zone)!! + store.savePlan(user, HORROR_TV_NUMBER, plan) + val saved = progressAfter(true, base, plan, now) + store.saveProgress(user, HORROR_TV_NUMBER, if (keepAhead) saved else ScheduleStore.SavedProgress(saved.enabled, saved.aired)) + lastPlan = plan + previous = now; now += 53 * minute; round++ + } + return aired.values.toList() + } + private var lastPlan: ChannelPlan? = null + + private fun inOrder(entries: List) = entries.groupBy { it.seriesId }.all { (id, l) -> + val eps = pool.first { it.id == id }.episodes.map { it.mark } + l.zipWithNext().all { (a, b) -> eps[(eps.indexOf(a.mark) + 1) % eps.size] == b.mark } + } + private fun mostOpen(entries: List): Int { + val open = HashSet(); var most = 0 + entries.filter { it.seriesId != "s-Anth" }.forEach { e -> open += e.seriesId; most = maxOf(most, open.size); if (!midSeason(pool.first { it.id == e.seriesId }, e.mark)) open -= e.seriesId } + return most + } + + @Test fun losingTheWholeScheduleNeitherRepeatsNorRestartsASeason() { + // Lost every ninth round: at every time of day, off air included, and part way through seasons. + val aired = run(21) { it > 0 && it % 9 == 0 } + assertTrue(aired.size > 150) + assertTrue("nothing repeated or skipped", inOrder(aired)) + assertTrue("the rotation never opens more than its places", mostOpen(aired) <= 2) + // Nothing starts off air, even right after a loss in the day. + assertTrue(aired.none { java.time.Instant.ofEpochMilli(it.startMs).atZone(zone).hour in 6..17 }) + // Every series that started a season before a loss carries on with the next episode after it, never episode 1. + val restarts = aired.groupBy { it.seriesId }.entries.sumOf { (id, l) -> l.zipWithNext().count { (a, b) -> b.mark.episode == 1 && midSeason(pool.first { it.id == id }, a.mark) } } + assertEquals(0, restarts) + } + + @Test fun losingItEveryRoundStillHolds() { + val aired = run(10) { it > 0 } + assertTrue(aired.size > 60) + assertTrue("in order: " + aired.joinToString(" ") { "${it.seriesId.removePrefix("s-")}${it.mark.season}.${it.mark.episode}" }, inOrder(aired)) + assertTrue("open ${mostOpen(aired)}", mostOpen(aired) <= 2) + } + + @Test fun withoutTheBookedAheadPartTheLossWouldRepeatEpisodes() { + // The check is real: the place saved before this change (what had aired by the last round) repeats what went out since. + assertFalse(inOrder(run(21, keepAhead = false) { it > 0 && it % 9 == 0 })) + } + + @Test fun theBookedAheadPartRoundTripsAndOlderFilesStillRead() { + val dir = folder.newFolder(); val store = ScheduleStore(dir) + val plan = topUpPlan(null, ScheduleCursor(), pool, start(), dayParts = parts, zone = zone)!! + val saved = progressAfter(true, ScheduleCursor(), plan, start() + 90 * minute) + store.saveProgress(user, HORROR_TV_NUMBER, saved) + val read = store.loadProgress(user, HORROR_TV_NUMBER)!! + assertEquals(saved.ahead, read.ahead) + assertEquals(airedCursor(ScheduleCursor(), plan.entries, start() + 900 * minute).marks, read.airedBy(start() + 900 * minute).marks) + // A file from before has no booked-ahead part: it reads as before. + val file = java.io.File(dir, "progress-$HORROR_TV_NUMBER.json") + file.writeText(org.json.JSONObject(file.readText()).apply { remove("ahead") }.toString()) + assertTrue(store.loadProgress(user, HORROR_TV_NUMBER)!!.ahead.isEmpty()) + } +} diff --git a/docs/CHANGELOG-build86.md b/docs/CHANGELOG-build86.md index 65ca4cae..5c6bcedb 100644 --- a/docs/CHANGELOG-build86.md +++ b/docs/CHANGELOG-build86.md @@ -17,6 +17,13 @@ Nothing here moves an existing booking or changes another channel's home, rating series, so it carries across restarts, refreshes, top-ups and a lost schedule. - **Homes kept:** Tales from the Crypt stays After Dark's (a guest here, never at the same moment). The Ray Bradbury Theater waits for Paradox's review, Jamaica Inn for Orbit Showcase's, Sapphire & Steel until complete; mysteries stay Evidence's. -- **Look:** logo, guide badge, corner logo, colours, six block idents, a channel ident and the off-air card. +- **Look:** logo, guide badge, corner logo, colours, six block idents, a channel ident and the off-air card (full 1080p). + +## Losing the whole schedule (every channel, Paul, 1 December 2026) + +- **A lost schedule no longer repeats what aired since the last round.** The saved place now keeps the programmes booked + ahead (series and episode only), so if both copies of a channel's schedule are ever lost, everything that started since the + last plan still counts as aired: no episode repeats, and no series starts its season again. Older progress files still read. + Tests: ScheduleLossTest (losses at every time of day, and every round; without the fix the same test repeats episodes). - Tests: SeasonRotationTest, HorrorTvChannelTest, HorrorTvBuildSimulationTest (three five-week runs, one losing its schedule every week: nothing off air, nothing stricter than TV-14 before 23:00, no clashes, every series in order).