Portability and data safety: one workspace per server, portable Drive-In events
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 2m2s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m37s

Ported from release 0.108.41. On this line Advent's doors, the Naughty List and the approved debuts are Paul's by item and
apply only on his server too. Roadmap: the portability section, including LAN-only plain HTTP as a later, separate change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-06 02:46:15 +00:00
co-authored by Claude Opus 5.5
parent 458d6ebe13
commit 67ee3f8ffb
31 changed files with 837 additions and 104 deletions
@@ -2,7 +2,9 @@ package tv.orbit.classic
import org.json.JSONArray
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.io.File
import java.time.DayOfWeek
@@ -12,6 +14,9 @@ import java.time.ZonedDateTime
/** Premiere as a broadcast stage: two recommendations, a debut that only appends, a window, then the film's genre home. */
class DirectorPremiereTest {
// The curated Drive-In events as found in Paul's library, which these evenings compete with.
@Before fun paulsEvents() { CuratedDriveInEvents.refresh { PaulsEventCopies } }
@After fun noEvents() { CuratedDriveInEvents.list = emptyList(); CuratedDriveInEvents.copies = emptyMap() }
private val london = ZoneId.of("Europe/London")
private val minute = 60_000L
private val day = 24 * 60 * minute
@@ -52,7 +52,7 @@ class DriveInEventsReplayTest {
}
val committed = plan(File(dir, "schedule-300.json"))!!
val start = System.getenv("ORBIT_REPLAY_NOW")?.toLong() ?: committed.entries.first().startMs
for ((name, events) in listOf("drivein-events" to DriveInEvents, "drivein-baseline" to emptyList())) {
for ((name, events) in listOf("drivein-events" to PaulsDriveInEvents, "drivein-baseline" to emptyList())) {
val notes = mutableListOf<String>()
var current: ChannelPlan? = committed
val all = committed.entries.toMutableList()
@@ -186,7 +186,8 @@ class DriveInEventsTest {
assertEquals(DriveInEvents.size, DriveInEvents.map { it.evening }.distinct().size)
assertTrue(DriveInEvents.all { it.presentation.isEmpty() || it.presentation in DriveInTakeovers })
assertEquals("Arnold Schwarzenegger", DriveInEvents.single { it.key == "arnie" }.person)
assertTrue(DriveInEvents.flatMap { it.films }.all { it.imdb.matches(Regex("tt\\d{7,8}")) && EmbyClient.validId(it.itemId) })
// Templates name films by IMDb ID only: no server's item is built in.
assertTrue(DriveInEvents.flatMap { it.films }.all { it.imdb.matches(Regex("tt\\d{7,8}")) && it.itemId.isEmpty() })
// Three triples run past midnight; nothing else is booked on top of them by design (a triple has no late show).
assertTrue(DriveInEvents.filter { it.films.size == 3 }.all { it.hour == 19 })
}
@@ -32,7 +32,7 @@ class EventIdeasReplayTest {
val studios = EventStudios.associateWith { st -> films.values.filter { f -> f.studios.any { it.contains(st.first) } }.map { it.id } }
val read = films.values.filter { it.id in evidence }
val held = AdventDoors.map { it.film.itemId } + NaughtyList.map { it.film.itemId } + ApprovedDebuts.map { it.film.itemId }
val seeds = ideaSeeds(collections, studios, read, DriveInEvents.flatMap { e -> e.films.map { it.itemId } }.toSet() + held)
val seeds = ideaSeeds(collections, studios, read, PaulsDriveInEvents.flatMap { e -> e.films.map { it.itemId } }.toSet() + held)
val busy = strings(input, "busy").toSet()
val unavailable = { f: IdeaFilm -> if (f.id in busy) "booked" else if (f.id in held) "held" else null }
val bills = seeds.mapNotNull { billFor(it, films, unavailable).first }.sortedByDescending { it.score }
@@ -71,16 +71,22 @@ class EventIdeasTest {
@Test fun seedsSkipCuratedListsAndThemesAlreadyHad() {
val seeds = ideaSeeds(listOf("Godzilla Collection" to listOf("a", "b"), "IMDB Top 250 Movies" to listOf("a", "b"), "Rambo Collection" to listOf("5642223", "x")),
emptyMap(), emptyList(), DriveInEvents.flatMap { e -> e.films.map { it.itemId } }.toSet())
emptyMap(), emptyList(), PaulsDriveInEvents.flatMap { e -> e.films.map { it.itemId } }.toSet())
assertEquals(listOf("franchise:Godzilla Collection"), seeds.map { it.key })
}
@Test fun anEveningSuitsItsFormatAndCompetesWithNothing() {
val late = ideaEvening(IdeaFormat.LateShow, LocalDate.of(2026, 11, 16), 0L, emptySet(), 4 * 3_600_000L, london)!!
assertTrue(late.dayOfWeek in setOf(DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY)); assertEquals(23, late.hour)
assertNotEquals(LocalDate.of(2026, 11, 17), late.toLocalDate()) // Amicus has Tuesday 17 November
val sat = ideaEvening(IdeaFormat.SaturdayTriple, LocalDate.of(2026, 11, 14), 0L, emptySet(), 6 * 3_600_000L, london)!!
assertEquals(LocalDate.of(2026, 11, 21), sat.toLocalDate()) // Universal Monsters has the 14th
CuratedDriveInEvents.refresh { PaulsEventCopies }
try {
val late = ideaEvening(IdeaFormat.LateShow, LocalDate.of(2026, 11, 16), 0L, emptySet(), 4 * 3_600_000L, london)!!
assertTrue(late.dayOfWeek in setOf(DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY)); assertEquals(23, late.hour)
assertNotEquals(LocalDate.of(2026, 11, 17), late.toLocalDate()) // Amicus has Tuesday 17 November
val sat = ideaEvening(IdeaFormat.SaturdayTriple, LocalDate.of(2026, 11, 14), 0L, emptySet(), 6 * 3_600_000L, london)!!
assertEquals(LocalDate.of(2026, 11, 21), sat.toLocalDate()) // Universal Monsters has the 14th
// A library without Universal's films has no Universal night, so the 14th is free there.
CuratedDriveInEvents.refresh { PaulsEventCopies - "tt0034398" }
assertEquals(LocalDate.of(2026, 11, 14), ideaEvening(IdeaFormat.SaturdayTriple, LocalDate.of(2026, 11, 14), 0L, emptySet(), 6 * 3_600_000L, london)!!.toLocalDate())
} finally { CuratedDriveInEvents.list = emptyList(); CuratedDriveInEvents.copies = emptyMap() }
}
@Test fun anIdeaWithdrawnOnlyForARuleChangeComesBackWhenProposedAgain() {
@@ -0,0 +1,162 @@
package tv.orbit.classic
import org.json.JSONArray
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.net.URLDecoder
import java.time.LocalDateTime
import java.time.ZoneId
/**
* A new person's server, end to end (portability, Paul, 6 November 2026): a small library that isn't Paul's, with films and
* shows missing, duplicate copies and copies this box can't play. Sign-in, the catalogue, setting channels up and the
* Drive-In's curated events all run against it through the same code the box uses, with a fake server standing in for Emby.
*/
class FriendsLibraryTest {
@get:Rule val folder = TemporaryFolder()
private val zone = ZoneId.of("Europe/London")
@After fun reset() {
Workspaces.reset()
CuratedDriveInEvents.list = emptyList(); CuratedDriveInEvents.copies = emptyMap(); CuratedDriveInEvents.missing = emptyMap()
}
private class Film(val id: String, val name: String, val year: Int, val imdb: String?, val container: String = "mkv", val cast: List<String> = emptyList())
private class Show(val id: String, val name: String, val year: Int, val episodes: List<String>)
/** Sam's library: nothing like Paul's in size, and not the same items. "iso" is a container this box can't play directly. */
private val films = listOf(
Film("m-thing1", "The Thing", 1982, "tt0084787", container = "iso"), Film("m-thing2", "The Thing", 1982, "tt0084787"),
Film("m-theylive", "They Live", 1988, "tt0096256"), Film("m-video", "Videodrome", 1983, "tt0086541"), Film("m-repo", "Repo Man", 1984, "tt0087995"),
// Hammer: the Curse is here, Dracula (1958) isn't.
Film("m-curse", "The Curse of Frankenstein", 1957, "tt0050280"),
// Universal: every film, Dracula twice, one copy unplayable.
Film("m-drac-a", "Dracula", 1931, "tt0021814", container = "iso"), Film("m-drac-b", "Dracula", 1931, "tt0021814"),
Film("m-frank", "Frankenstein", 1931, "tt0021884"), Film("m-wolf", "The Wolf Man", 1941, "tt0034398"),
// Arnie: all three, but the library doesn't list him in The Running Man's cast.
Film("m-commando", "Commando", 1985, "tt0088944", cast = listOf("Arnold Schwarzenegger")), Film("m-recall", "Total Recall", 1990, "tt0100802", cast = listOf("Arnold Schwarzenegger")),
Film("m-running", "The Running Man", 1987, "tt0093894"),
Film("m-bluey", "Bluey: The Sign", 2024, null))
private val shows = listOf(
Show("s-xf1", "The X-Files", 1993, listOf("mkv")), Show("s-xf2", "The X-Files", 1993, List(6) { "mkv" }),
Show("s-buffy", "Buffy the Vampire Slayer", 1997, List(4) { "mkv" }), Show("s-fringe", "Fringe", 2008, listOf("mkv", "iso", "mkv")),
Show("s-tp", "Twin Peaks", 1990, listOf("iso", "iso")), Show("s-bluey", "Bluey", 2018, List(5) { "mp4" }))
private fun source(id: String, container: String, ms: Long) = JSONObject().put("Id", "src-$id").put("Container", container).put("RunTimeTicks", ms * 10_000)
private fun filmRow(f: Film) = JSONObject().put("Id", f.id).put("Type", "Movie").put("Name", f.name).put("ProductionYear", f.year).put("RunTimeTicks", 6_000_000L * 10_000)
.put("ProviderIds", JSONObject().apply { f.imdb?.let { put("Imdb", it) } }).put("MediaSources", JSONArray().put(source(f.id, f.container, 6_000_000)))
.put("People", JSONArray(f.cast.map { JSONObject().put("Name", it).put("Type", "Actor") })).put("Genres", JSONArray().put("Horror")).put("OfficialRating", "15")
.put("PremiereDate", "${f.year}-06-01T00:00:00.0000000Z")
private fun showRow(s: Show) = JSONObject().put("Id", s.id).put("Type", "Series").put("Name", s.name).put("ProductionYear", s.year).put("OfficialRating", "TV-14")
.put("ProviderIds", JSONObject()).put("Genres", JSONArray().put("Drama")).put("PremiereDate", "${s.year}-09-01T00:00:00.0000000Z")
private fun episodeRows(s: Show) = s.episodes.mapIndexed { i, container -> JSONObject().put("Id", "${s.id}-e${i + 1}").put("Type", "Episode").put("Name", "Episode ${i + 1}")
.put("ParentIndexNumber", 1).put("IndexNumber", i + 1).put("MediaSources", JSONArray().put(source("${s.id}-e${i + 1}", container, 2_700_000))) }
private fun page(rows: List<JSONObject>, start: Int = 0, limit: Int = rows.size) =
EmbyReply(200, JSONObject().put("Items", JSONArray(rows.drop(start).take(limit))).put("TotalRecordCount", rows.size).toString())
private fun matches(name: String, term: String) = name.lowercase().filter { it.isLetterOrDigit() || it == ' ' }.contains(term.lowercase().filter { it.isLetterOrDigit() || it == ' ' })
val requests = mutableListOf<String>()
/** Enough of Emby's API for everything the box asks of it here; anything else is a failure the test would see. */
private val server = EmbyTransport { request ->
requests += request.path
val query = request.path.substringAfter('?', "").split('&').filter { it.isNotEmpty() }.associate { URLDecoder.decode(it.substringBefore('='), "UTF-8") to URLDecoder.decode(it.substringAfter('=', ""), "UTF-8") }
val path = request.path.substringBefore('?')
val start = query["StartIndex"]?.toInt() ?: 0; val limit = query["Limit"]?.toInt() ?: 1_000
when {
path == "/System/Info/Public" -> EmbyReply(200, JSONObject().put("Id", "sams-server").put("Version", "4.8.10").put("ServerName", "Sam's Emby").toString())
path == "/Users/AuthenticateByName" -> EmbyReply(200, JSONObject().put("AccessToken", "sams-token").put("User", JSONObject().put("Id", "sam")).toString())
request.token != "sams-token" -> EmbyReply(401, "")
path == "/Users/sam/Items" -> page(films.map(::filmRow), 0, 20)
path.startsWith("/Shows/") -> page(episodeRows(shows.single { it.id == path.removePrefix("/Shows/").substringBefore('/') }), start, limit)
path == "/Items" && query["Ids"] != null -> query.getValue("Ids").split(',').let { ids -> page(films.filter { it.id in ids }.map(::filmRow) + shows.filter { it.id in ids }.map(::showRow)) }
path == "/Items" && query["SearchTerm"] != null -> {
val term = query.getValue("SearchTerm"); val years = query["Years"]?.split(',')?.map { it.toInt() }
val types = query["IncludeItemTypes"].orEmpty().split(',')
page((if ("Movie" in types) films.filter { matches(it.name, term) && (years == null || it.year in years) }.map(::filmRow) else emptyList()) +
(if ("Series" in types) shows.filter { matches(it.name, term) }.map(::showRow) else emptyList()), start, limit)
}
path == "/Items" && query["IncludeItemTypes"] == "Movie,Series" -> page(films.map(::filmRow) + shows.map(::showRow), start, limit)
else -> EmbyReply(404, "")
}
}
/** The catalogue, held in memory as the box holds it in its database, with the same IMDb lookup. */
private class MemoryCatalogue : CatalogueSink {
val records = mutableListOf<CatalogueRecord>(); var next = 0L; var finished = false
override fun position(userId: String) = next
override fun write(userId: String, records: List<CatalogueRecord>, nextStart: Long, total: Long?, finished: Boolean) { this.records += records; next = nextStart; this.finished = finished }
fun idsByImdb(imdbs: Collection<String>) = imdbs.map { it.lowercase() }.associateWith { imdb ->
records.filter { it.type == "Movie" && it.providerIds.entries.any { (k, v) -> k.equals("Imdb", true) && v.lowercase() == imdb } }.map { it.id } }.filterValues { it.isNotEmpty() }
}
@Test fun aNewServerSignsInBuildsItsOwnChannelsAndOnlyTheEventsItCanShow() {
val noBackup = folder.newFolder("no_backup"); val cache = folder.newFolder("cache")
// The box's own (Paul's) data, which must come through untouched.
java.io.File(noBackup, "schedule").mkdirs(); java.io.File(noBackup, "schedule/schedule-300.json").writeText("paul's drive-in")
val origin = "https://emby.sam.example"
assertEquals("Sam's Emby", EmbyClient(server).checkServer())
val workspace = Workspaces.openIn(noBackup, cache, origin)
val session = EmbyClient(server).connect("sam", "fixture-password")
assertEquals("sam", session.accountId)
// The catalogue, from Sam's library.
val catalogue = MemoryCatalogue()
session.importCatalogue(catalogue, CATALOGUE_PAGES_FULL_RUN)
assertTrue(catalogue.finished); assertEquals(films.size + shows.size, catalogue.records.size)
// Channels: Paradox (series) and After Dark (films), read and planned as switching them on does.
val scheduler = ChannelScheduler(workspace.schedules, copies = catalogue::idsByImdb, original = workspace.original,
clock = { LocalDateTime.of(2026, 11, 12, 12, 0).atZone(zone).toInstant().toEpochMilli() })
val paradox = SmartChannels.single { it.name == "Paradox" }
scheduler.setEnabled("sam", paradox.number, true)
val paradoxLoop = scheduler.seedLoop(session, "sam", paradox)
val paradoxReport = scheduler.topUp(session, "sam", paradox, paradoxLoop)
val paradoxPool = workspace.schedules.loadPool("sam", paradox.number)!!.series
// The X-Files from its fuller copy; Twin Peaks has nothing this box plays; Angel and the rest aren't in the library.
assertEquals(setOf("s-xf2", "s-buffy", "s-fringe"), paradoxPool.map { it.id }.toSet())
assertEquals(2, paradoxPool.single { it.id == "s-fringe" }.episodes.size)
assertTrue(paradoxReport.programmes > 0)
assertTrue(workspace.schedules.loadPlan("sam", paradox.number)!!.entries.all { it.seriesId in setOf("s-xf2", "s-buffy", "s-fringe") })
val afterDark = SmartChannels.single { it.number == AFTER_DARK_NUMBER }
assertTrue(afterDark.withdrawn.isEmpty()) // Paul's removals are his server's alone
scheduler.setEnabled("sam", afterDark.number, true)
scheduler.seedLoop(session, "sam", afterDark)
val darkPool = workspace.schedules.loadPool("sam", afterDark.number)?.series.orEmpty()
// The Thing from the copy that plays; nothing stands in for the films Sam doesn't have.
assertTrue(darkPool.map { it.id }.toSet().let { "m-thing2" in it && "m-thing1" !in it && it.all { id -> films.any { f -> f.id == id } } })
// The Drive-In's curated events: only those whose every film is in the library, read with every copy.
CuratedDriveInEvents.refresh(catalogue::idsByImdb)
assertEquals(setOf("universal", "arnie"), CuratedDriveInEvents.list.map { it.key }.toSet())
assertEquals(listOf("tt0051554"), CuratedDriveInEvents.missing["hammer"])
assertEquals(listOf("m-drac-a", "m-drac-b"), CuratedDriveInEvents.copies["tt0021814"])
val listed = CuratedDriveInEvents.list.flatMap { e -> e.films.flatMap { f -> eventFilmCopies(e, f, CuratedDriveInEvents.copies).map { EventFilm(f.title, f.year, f.imdb, it) to e.person } } }
val checks = session.readFilmChecks(listed)
assertEquals("unplayable", checks.getValue("m-drac-a").reason); assertEquals("verified", checks.getValue("m-drac-b").reason)
assertEquals("person not in cast", checks.getValue("m-running").reason)
val verified = checks.values.mapNotNull { it.film }.associateBy { it.id }
val booking = chooseEventCopies(CuratedDriveInEvents.list, CuratedDriveInEvents.copies, verified.keys)
assertEquals("m-drac-b", booking.single { it.key == "universal" }.films.first().itemId)
// Booked as the box books: Universal on its Saturday from the copies that play; Arnie and Hammer not at all, not even in part.
val pool = (1..40).map { n -> PoolSeries("p$n", "Film $n", listOf(PoolEpisode("p$n", "s$n", EpisodeMark(1, 1), "Film $n", 100 * 60_000L))) }
var plan: ChannelPlan? = null; var now = LocalDateTime.of(2026, 11, 12, 12, 0).atZone(zone).toInstant().toEpochMilli()
repeat(4) { plan = planDriveIn(plan, pool, pool, pool, now, zone, events = booking, eventFilms = verified); now += 24 * 60 * 60_000L }
val events = plan!!.entries.filter { it.why.startsWith(DRIVE_IN_EVENT_WHY) }
assertEquals(listOf("m-drac-b", "m-frank", "m-wolf"), events.map { it.seriesId })
assertTrue(plan!!.entries.none { it.seriesId in setOf("m-curse", "m-commando", "m-recall", "m-running", "m-drac-a") })
// Everything Sam's server produced is in Sam's folder; the box's own data is as it was.
assertEquals("paul's drive-in", java.io.File(noBackup, "schedule/schedule-300.json").readText())
assertTrue(java.io.File(workspace.scheduleDir, "schedule-${paradox.number}.json").exists())
assertFalse(java.io.File(noBackup, "schedule/schedule-${paradox.number}.json").exists())
// And Sam's token only ever went to Sam's server's requests, never in an address.
assertTrue(requests.none { it.contains("sams-token") })
}
}
@@ -0,0 +1,41 @@
package tv.orbit.classic
/**
* Paul's library's copies of the curated Drive-In films, IMDb ID to item, read from a read-only copy of the box's catalogue
* (5 November 2026): one copy each, every title and year matching. What the portable events must find on his server.
*/
internal val PaulsEventCopies: Map<String, List<String>> = mapOf(
"tt0050280" to listOf("5706532"), // The Curse of Frankenstein (1957)
"tt0051554" to listOf("5705114"), // Dracula (1958)
"tt0021814" to listOf("5661535"), // Dracula (1931)
"tt0021884" to listOf("5658574"), // Frankenstein (1931)
"tt0034398" to listOf("5848283"), // The Wolf Man (1941)
"tt0069341" to listOf("6047716"), // Tales from the Crypt (1972)
"tt0065854" to listOf("6036576"), // The House That Dripped Blood (1971)
"tt0178868" to listOf("7956704"), // Ring (1998)
"tt0364385" to listOf("5662234"), // Ju-on: The Grudge (2002)
"tt0078243" to listOf("6332423"), // The 36th Chamber of Shaolin (1978)
"tt0070800" to listOf("6336439"), // Five Fingers of Death (1972)
"tt0090190" to listOf("5672180"), // The Toxic Avenger (1984)
"tt0090849" to listOf("5706569"), // Class of Nuke 'Em High (1986)
"tt0088944" to listOf("6048687"), // Commando (1985)
"tt0100802" to listOf("5848135"), // Total Recall (1990)
"tt0093894" to listOf("5671824"), // The Running Man (1987)
"tt0096283" to listOf("5844712"), // My Neighbor Totoro (1988)
"tt0097814" to listOf("7883574"), // Kiki's Delivery Service (1989)
"tt0245429" to listOf("7950220"), // Spirited Away (2001)
"tt0083944" to listOf("5642223"), // First Blood (1982)
"tt0089880" to listOf("5848906"), // Rambo: First Blood Part II (1985)
"tt0095956" to listOf("5848907"), // Rambo III (1988)
"tt0038650" to listOf("6175183"), // It's a Wonderful Life (1946)
"tt0099785" to listOf("7416999"), // Home Alone (1990)
"tt0319343" to listOf("6952195") // Elf (2003)
)
/** The event films' signature the box saved before events became portable (its schedule folder, 6 November 2026 snapshot). */
internal const val PaulsSavedEventSignature = "events:hammer=5706532,5705114|universal=5661535,5658574,5848283|amicus=6047716,6036576|" +
"jhorror=7956704,5662234|shaw=6332423,6336439|troma=5672180,5706569|arnie=6048687,5848135,5671824|ghibli=5844712,7883574,7950220|" +
"rambo=5642223,5848906,5848907|christmas=6175183,7416999,6952195"
/** The curated events as found on Paul's server. */
internal val PaulsDriveInEvents: List<DriveInEvent> get() = resolveDriveInEvents(DriveInEvents, PaulsEventCopies).events
@@ -0,0 +1,173 @@
package tv.orbit.classic
import org.junit.After
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.net.URI
import java.security.MessageDigest
/**
* Portability and data safety (Paul, 6 November 2026): curated events found by IMDb ID in any library, each server's data in
* its own workspace, the box's existing data left exactly where it is, and Paul's own decisions kept to his own server.
*/
class PortabilityTest {
@get:Rule val folder = TemporaryFolder()
private val other = "https://emby.friend.example:8920"
@After fun reset() {
Workspaces.reset()
CuratedDriveInEvents.list = emptyList(); CuratedDriveInEvents.copies = emptyMap(); CuratedDriveInEvents.missing = emptyMap()
}
private fun digest(dir: File): Map<String, String> = dir.walkTopDown().filter { it.isFile }.associate { file ->
file.relativeTo(dir).path to MessageDigest.getInstance("SHA-256").digest(file.readBytes()).joinToString("") { "%02x".format(it) }
}
/** A box as it is today: the original server's sign-in, catalogue and schedules at the top of no_backup. */
private fun todaysBox(): Pair<File, File> {
val noBackup = folder.newFolder("no_backup"); val cache = folder.newFolder("cache")
File(noBackup, "orbit-connection.v1").writeBytes(byteArrayOf(1, 2, 3))
File(noBackup, "catalogue.db").writeText("catalogue")
File(noBackup, "schedule").mkdirs(); File(noBackup, "schedule/schedule-101.json").writeText("{\"user\":\"paul\"}"); File(noBackup, "schedule/numbering-2").writeText("")
File(cache, "artwork").mkdirs(); File(cache, "artwork/x.img").writeText("art")
return noBackup to cache
}
@Test fun curatedEventsFindExactlyPaulsItemsAndKeepTheSavedSignature() {
val found = resolveDriveInEvents(DriveInEvents, PaulsEventCopies)
assertEquals(10, found.events.size); assertTrue(found.missing.isEmpty())
// The same items as before the change, film for film, so nothing on his box reads, books or plans differently.
assertEquals(PaulsSavedEventSignature, eventSignature(found.events, PaulsEventCopies))
assertTrue(found.events.flatMap { it.films }.all { listOf(it.itemId) == PaulsEventCopies[it.imdb] })
}
@Test fun aMissingFilmLeavesItsWholeEventOutAndNothingStandsIn() {
val withoutDracula = PaulsEventCopies - "tt0051554"
val found = resolveDriveInEvents(DriveInEvents, withoutDracula)
assertNull(found.events.firstOrNull { it.key == "hammer" })
assertEquals(listOf("tt0051554"), found.missing["hammer"])
assertEquals(9, found.events.size)
// Its other film isn't offered alone, and no other film takes Dracula's place.
assertTrue(found.events.none { e -> e.films.any { it.imdb == "tt0050280" } })
assertTrue(resolveDriveInEvents(DriveInEvents, emptyMap()).events.isEmpty())
}
@Test fun aLibraryThatCantBeReadYetKeepsWhatWasFoundAndTheDriveInWaits() {
assertTrue(CuratedDriveInEvents.refresh { PaulsEventCopies })
assertFalse(CuratedDriveInEvents.refresh { null }) // catalogue still importing
assertFalse(CuratedDriveInEvents.refresh { throw IllegalStateException() }) // catalogue unreadable
assertEquals(10, CuratedDriveInEvents.list.size)
val store = ScheduleStore(folder.newFolder("schedule"))
val films = (1..40).map { n -> PoolSeries("$n", "Film $n", listOf(PoolEpisode("$n", "s$n", EpisodeMark(1, 1), "Film $n", 100 * 60_000L))) }
(DriveInMarqueeChannels + DriveInLateChannels + DriveInBillChannels).distinct().forEach { store.savePool("paul", it, ScheduleStore.SavedPool(films, 0L)) }
val now = { java.time.LocalDateTime.of(2026, 11, 12, 12, 0).atZone(java.time.ZoneId.of("Europe/London")).toInstant().toEpochMilli() }
assertNull(ChannelScheduler(store, copies = { null }, clock = now).topUpDriveIn("paul"))
assertNull(store.loadPlan("paul", DRIVE_IN_NUMBER))
// Once the library can be read, it books.
assertNotNull(ChannelScheduler(store, copies = { emptyMap() }, clock = now).topUpDriveIn("paul"))
}
@Test fun duplicateCopiesAreAllReadAndThePlayableOneBooks() {
val copies = PaulsEventCopies + ("tt0021814" to listOf("900", "5661535"))
val universal = resolveDriveInEvents(DriveInEvents, copies).events.single { it.key == "universal" }
assertTrue(eventSignature(listOf(universal), copies).contains("5661535/900"))
// Only the second copy plays on this box: that one books.
val chosen = chooseEventCopies(listOf(universal), copies, setOf("5661535", "5658574", "5848283")).single()
assertEquals("5661535", chosen.films.first().itemId)
// Both play: the first by item, every time.
assertEquals("900", chooseEventCopies(listOf(universal), copies, setOf("900", "5661535", "5658574", "5848283")).single().films.first().itemId)
// Neither plays: the film keeps a copy that isn't verified, so the booking leaves the whole event out.
val none = chooseEventCopies(listOf(universal), copies, setOf("5658574", "5848283")).single()
assertFalse(none.films.first().itemId in setOf("5658574", "5848283"))
}
@Test fun theOriginalServerIsTodaysDataWhereItIsAndOpeningItWritesNothing() {
val (noBackup, cache) = todaysBox()
val before = digest(noBackup); val cacheBefore = digest(cache)
assertEquals(EmbyServer.DEFAULT, Workspaces.activeOrigin(noBackup))
val original = Workspaces.openIn(noBackup, cache, Workspaces.activeOrigin(noBackup))
assertTrue(original.original)
assertEquals(File(noBackup, "orbit-connection.v1"), original.connectionFile)
assertEquals(File(noBackup, "catalogue.db"), original.catalogueFile)
assertEquals(File(noBackup, "schedule"), original.scheduleDir)
assertEquals(File(cache, "artwork"), original.artworkDir)
assertEquals(before, digest(noBackup)); assertEquals(cacheBefore, digest(cache))
assertEquals(setOf("orbit-connection.v1", "catalogue.db", "schedule"), noBackup.list()!!.toSet())
assertTrue(Workspaces.originalOpen)
}
@Test fun anotherServerGetsItsOwnFolderAndTodaysDataIsNeverTouched() {
val (noBackup, cache) = todaysBox()
val before = digest(noBackup)
Workspaces.openIn(noBackup, cache, EmbyServer.DEFAULT)
val friend = Workspaces.openIn(noBackup, cache, other)
assertFalse(friend.original); assertFalse(Workspaces.originalOpen)
assertEquals(File(noBackup, "servers/${Workspaces.keyOf(other)}"), friend.root)
assertNotEquals(File(cache, "artwork"), friend.artworkDir)
assertNotEquals("orbit-connection-key-v1", friend.keyAlias)
assertEquals(other, Workspaces.activeOrigin(noBackup)); assertEquals(other, EmbyServer.origin)
// Only the new folder's note and which server is in use were written; everything that was there is byte for byte the same.
val after = digest(noBackup)
assertEquals(before, after.filterKeys { it in before })
assertEquals(setOf("servers/${Workspaces.keyOf(other)}/server", "active-server"), after.keys - before.keys)
// Back to the original server: still the same data, and an older Orbit still finds all of it where it always was.
assertTrue(Workspaces.openIn(noBackup, cache, EmbyServer.DEFAULT).original)
assertEquals(before, digest(noBackup).filterKeys { it in before })
assertEquals(EmbyServer.DEFAULT, Workspaces.activeOrigin(noBackup))
assertEquals(listOf(EmbyServer.DEFAULT), Workspaces.known(noBackup, cache)) // the new server holds nothing yet
}
@Test fun aFolderNeverOpensForAnotherAddressAndAGarbledChoiceFallsBackToTheOriginal() {
val (noBackup, cache) = todaysBox()
val root = File(noBackup, "servers/${Workspaces.keyOf(other)}").apply { mkdirs() }
File(root, "server").writeText("https://someone.else.example")
assertThrows(IllegalStateException::class.java) { Workspaces.openIn(noBackup, cache, other) }
File(noBackup, "active-server").writeText("http://not-https.example")
assertEquals(EmbyServer.DEFAULT, Workspaces.activeOrigin(noBackup))
assertThrows(IllegalArgumentException::class.java) { Workspaces.openIn(noBackup, cache, "http://plain.example") }
}
@Test fun switchingServersForgetsWhatTheLastOneShowed() {
val (noBackup, cache) = todaysBox()
Workspaces.openIn(noBackup, cache, EmbyServer.DEFAULT)
CuratedDriveInEvents.refresh { PaulsEventCopies }
ApprovedDriveInEvents.list = PaulsDriveInEvents.take(1)
PromoBoard.shown[101] = 1L
Workspaces.openIn(noBackup, cache, other)
assertTrue(allDriveInEvents().isEmpty()); assertTrue(PromoBoard.items.isEmpty()); assertTrue(PromoBoard.shown.isEmpty())
}
@Test fun paulsOwnDecisionsByItemApplyOnlyOnHisServer() {
val (noBackup, cache) = todaysBox()
Workspaces.openIn(noBackup, cache, EmbyServer.DEFAULT)
val afterDark = SmartChannels.single { it.number == AFTER_DARK_NUMBER }
assertTrue(afterDark.withdrawn.isNotEmpty()); assertTrue(PremiereCalls.isNotEmpty())
val advent = java.time.LocalDateTime.of(2026, 12, 1, 18, 30).atZone(java.time.ZoneId.of("Europe/London")).toInstant().toEpochMilli()
assertEquals("Advent's Door 1", competingEvent(advent, advent + 60_000, java.time.ZoneId.of("Europe/London")))
assertEquals(25, AdventDoors.size); assertTrue(NaughtyList.isNotEmpty()); assertEquals(2, ApprovedDebuts.size)
Workspaces.openIn(noBackup, cache, other)
assertTrue(afterDark.withdrawn.isEmpty()); assertTrue(PremiereCalls.isEmpty())
// Advent, the Naughty List and the approved debuts name Paul's items: another server has none of them.
assertTrue(AdventDoors.isEmpty()); assertTrue(NaughtyList.isEmpty()); assertTrue(ApprovedDebuts.isEmpty()); assertTrue(seasonalFilms().isEmpty())
assertNull(competingEvent(advent, advent + 60_000, java.time.ZoneId.of("Europe/London"), season = false))
// Its pool signature changes with it, so a server never reuses a pool read under the other's rules.
assertFalse(afterDark.signature.contains("#withdrawn"))
}
@Test fun aSessionStaysWithItsOwnServerAfterTheServerInUseChanges() {
val requests = mutableListOf<String>()
val transport = HttpsEmbyTransport("fixture-device", "https://emby.home.example")
val session = EmbySampleSession(transport, "fixture-token", "fixture-user", EmbySample(emptyList(), 0))
EmbyServer.origin = other
assertEquals("https://emby.home.example", session.origin)
val url = session.mediaUrl("/emby/Videos/1/stream.mkv?api_key=fixture-token")
assertTrue(url.startsWith("https://emby.home.example/emby/Videos/1/stream.mkv")); assertFalse(url.contains("fixture-token"))
assertEquals(mapOf("X-Emby-Token" to "fixture-token"), session.mediaHeaders(url))
// The server now in use is someone else's: this session's token never goes there.
assertTrue(session.mediaHeaders("$other/emby/Videos/1/stream.mkv").isEmpty())
assertTrue(requests.isEmpty())
}
}
@@ -85,6 +85,7 @@ class PremiereReplayTest {
@Test fun releaseChecks() {
assumeTrue(dir != null && File(dir, "premiere-films.json").exists() && File(dir, "advent-films.json").exists())
CuratedDriveInEvents.refresh { PaulsEventCopies }
val with = run(true); val without = run(false)
val out = StringBuilder()
for (d in ApprovedDebuts) {
@@ -0,0 +1,37 @@
package tv.orbit.classic
import org.junit.After
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
import java.security.MessageDigest
/**
* The workspace change against a copy of the box's real data (never the box itself):
* ORBIT_SNAPSHOT_DIR=<a copy of the box's no_backup folder> ./gradlew :app:testDebugUnitTest --tests '*WorkspaceSnapshotTest*'
* Opening the original server, then another, then the original again must leave every existing file byte for byte as it was,
* and the saved Drive-In event signature must be what the portable events produce.
*/
class WorkspaceSnapshotTest {
@After fun reset() = Workspaces.reset()
private fun digest(dir: File) = dir.walkTopDown().filter { it.isFile }.associate { f ->
f.relativeTo(dir).path to MessageDigest.getInstance("SHA-256").digest(f.readBytes()).joinToString("") { "%02x".format(it) } }
@Test fun theBoxsDataIsUntouchedByOpeningServers() {
val dir = System.getenv("ORBIT_SNAPSHOT_DIR")?.let(::File)
assumeTrue(dir != null && dir.isDirectory)
val noBackup = dir!!; val cache = File(noBackup.parentFile, "cache-for-test").apply { mkdirs() }
val before = digest(noBackup)
val original = Workspaces.openIn(noBackup, cache, Workspaces.activeOrigin(noBackup))
assertTrue(original.original); assertEquals(File(noBackup, "schedule"), original.scheduleDir)
assertEquals(before, digest(noBackup))
Workspaces.openIn(noBackup, cache, "https://emby.friend.example")
Workspaces.openIn(noBackup, cache, EmbyServer.DEFAULT)
val after = digest(noBackup)
assertEquals(before, after.filterKeys { it in before })
println("snapshot files=${before.size} unchanged=${before.count { (k, v) -> after[k] == v }} added=${(after.keys - before.keys).sorted()}")
val saved = File(noBackup, "schedule/episodes-300.json").readText().let { Regex("\"signature\":\"(events:[^\"]*)\"").find(it)!!.groupValues[1] }
assertEquals(saved, eventSignature(PaulsDriveInEvents, PaulsEventCopies))
}
}