From 05afac70b4168aa9b561eb06636da7ed67211fe9 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Wed, 18 Nov 2026 13:46:45 +0000 Subject: [PATCH] Director's Chair keeps an eye on every channel's rotation; After Dark daytime gets five films (build 63) Paul, 18 November 2026: After Dark repeated by day (about 35 films in 16 hours, each back every five days). Added to its daytime, at his choice: Elvira: Mistress of the Dark, Creepshow 2, Dead Heat, Burke & Hare, Godzilla vs. Biollante. His rules for the Chair, for every channel including your own: a block whose films all come round within a week, or with three or more repeats nobody watched again, is running thin (a film you keep watching is a favourite, not a stale repeat: aired and watched are separate signals). The Chair then suggests a few films, each with its reasons: ones the channel already shows at other times that fit the block, never stronger in age rating than the block already shows and never with an unknown rating; and films from the library that fit the channel's brief and no other Orbit channel carries. Nothing changes until you approve; what you leave out isn't suggested again. A moved film keeps its old times too (groups like "late+day"). Worked out from what's on the box: no extra server scanning. At most three channels, six suggestions each. Co-Authored-By: Claude Opus 5.5 --- android/app/build.gradle.kts | 2 +- .../java/tv/orbit/classic/ChairRotation.kt | 226 ++++++++++++++++++ .../java/tv/orbit/classic/ChannelSchedule.kt | 21 +- .../tv/orbit/classic/ChannelSuggestions.kt | 4 +- .../java/tv/orbit/classic/DirectorChair.kt | 63 ++++- .../tv/orbit/classic/EmbyConnectionScreen.kt | 9 + .../tv/orbit/classic/ChairRotationTest.kt | 128 ++++++++++ 7 files changed, 445 insertions(+), 8 deletions(-) create mode 100644 android/app/src/main/java/tv/orbit/classic/ChairRotation.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/ChairRotationTest.kt diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 89a8e8f9..b5476eba 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -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 = 62 +val ORBIT_BUILD = 63 android { namespace = "tv.orbit.classic" compileSdk = 36 diff --git a/android/app/src/main/java/tv/orbit/classic/ChairRotation.kt b/android/app/src/main/java/tv/orbit/classic/ChairRotation.kt new file mode 100644 index 00000000..7ac9590f --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/ChairRotation.kt @@ -0,0 +1,226 @@ +package tv.orbit.classic + +import org.json.JSONArray +import org.json.JSONObject +import java.io.File + +/* + * The Director's Chair keeps an eye on each channel's rotation (Paul, 18 November 2026): + * - pool awareness: a block whose films all come round within a week is running thin; + * - repeat awareness: films back on air within a week, kept apart from films you keep watching (aired and watched are + * two signals: a favourite you watch every time isn't a stale repeat); + * - daypart flexibility: a film the channel already shows in another block may join this one, never stronger in its age + * rating than what the block already shows, and never one whose rating isn't known; + * - channel identity: additions from your own library must fit the channel's brief, as the Chair's picks do; + * - network awareness: nothing another Orbit channel already carries is offered; + * - approval: each suggestion comes with its reasons, and nothing changes until you approve it. + * Every channel, Orbit's own and the ones you make, from what's already on the box (the library evidence, the pools, the + * schedules and Taste): no extra server scanning. Film rotations only; series channels move through their episodes. + */ + +/** A block whose films would all play again within this many days is running thin. */ +internal const val ROTATION_THIN_DAYS = 7.0 +/** A film back on air within this long counts as a repeat. */ +internal const val ROTATION_REPEAT_WINDOW_MS = 7 * 24 * 60 * 60_000L +/** This many repeats nobody watched again is a stale rotation, however big the pool. */ +internal const val ROTATION_STALE_REPEATS = 3 +/** Watched this many times (finished, chosen or stayed with), a film is one you keep watching, not a stale repeat. */ +internal const val ROTATION_KEPT_WATCHING = 2 +/** Never hundreds of suggestions: a few channels at a time, a few films each. */ +internal const val ROTATION_MAX_CARDS = 3 +internal const val ROTATION_MAX_PROPOSALS = 6 +internal const val ROTATION_MAX_MOVES = 4 +/** An addition must fit the channel's brief at least as well as the Chair's "Possible" tier. */ +internal const val ROTATION_FIT = .35 +/** Fewer films than this isn't a film rotation. */ +internal const val ROTATION_MIN_FILMS = 4 +/** A channel is checked as a film rotation when at least this share of what it carries is films. */ +internal const val ROTATION_FILM_SHARE = .8 + +/** Age ratings in order of strength, US and UK. A rating not here is unknown and never moved or added on its strength. */ +private val RatingRank = mapOf("G" to 0, "U" to 0, "TV-G" to 0, "TV-Y" to 0, "TV-Y7" to 0, "PG" to 1, "TV-PG" to 1, + "PG-13" to 2, "12" to 2, "12A" to 2, "TV-14" to 2, "R" to 3, "15" to 3, "TV-MA" to 3, "NC-17" to 4, "18" to 4, "X" to 4) +internal fun ratingRank(rating: String?): Int? = rating?.trim()?.let { RatingRank[it] ?: RatingRank[it.uppercase()] } + +/** One suggestion: add a film from the library, or let a film the channel already shows play in this block too. */ +internal class RotationProposal(val channel: Int, val group: String, val id: String, val title: String, val year: Int?, val move: Boolean, val reason: String) { + val key get() = "${if (move) "move" else "add"}:$channel:$group:$id" + fun toJson(): JSONObject = JSONObject().put("c", channel).put("g", group).put("i", id).put("t", title).put("y", year ?: JSONObject.NULL).put("m", move).put("r", reason) + companion object { + fun of(o: JSONObject) = RotationProposal(o.optInt("c"), o.optString("g"), o.optString("i"), o.optString("t"), if (o.isNull("y")) null else o.optInt("y"), o.optBoolean("m"), o.optString("r")) + } +} + +/** One block that's running thin, what shows it, and what the Chair suggests. */ +internal class RotationCard(val channel: Int, val channelName: String, val block: String, val group: String, val films: Int, val cycleDays: Double, + /** Back on air within a week, nobody watching again. */ + val repeats: List, + /** Back within a week too, but you keep watching them: not counted against the rotation. */ + val keptWatching: List, val proposals: List) { + val headline get() = "$films films, each back about every ${days(cycleDays)}" + val line get() = listOfNotNull(headline, "${repeats.size} back within a week".takeIf { repeats.isNotEmpty() }, + "${keptWatching.size} you keep watching (not counted)".takeIf { keptWatching.isNotEmpty() }).joinToString("; ") + fun toJson(): JSONObject = JSONObject().put("n", channel).put("c", channelName).put("b", block).put("g", group).put("f", films).put("d", cycleDays) + .put("r", JSONArray(repeats)).put("w", JSONArray(keptWatching)).put("p", JSONArray(proposals.map { it.toJson() })) + companion object { + private fun strings(a: JSONArray?) = a?.let { (0 until it.length()).map { i -> it.optString(i) } }.orEmpty() + fun of(o: JSONObject) = RotationCard(o.optInt("n"), o.optString("c"), o.optString("b"), o.optString("g"), o.optInt("f"), o.optDouble("d"), + strings(o.optJSONArray("r")), strings(o.optJSONArray("w")), o.optJSONArray("p")?.let { a -> (0 until a.length()).map { RotationProposal.of(a.getJSONObject(it)) } }.orEmpty()) + } +} + +private fun days(d: Double) = if (d < 1.5) "day" else "%.0f days".format(java.util.Locale.UK, d) + +/** One everyday block of a channel as the rotation check sees it: its films, the channel's films outside it, and its hours. */ +internal class RotationBlock(val channel: Int, val channelName: String, val label: String, val group: String, val hoursPerDay: Int, + val films: List, val outside: List, val rules: List) { + val cycleDays get() = films.sumOf { it.episodes.firstOrNull()?.durationMs ?: 0L } / (hoursPerDay * 3_600_000.0) +} + +private fun hours(part: DayPart) = ((part.toHour - part.fromHour + 24) % 24).let { if (it == 0) 24 else it } + +/** A channel's everyday blocks with films to rotate: events, timetable slots and series channels are left out. */ +internal fun rotationBlocks(programming: ChannelProgramming, pool: List): List { + val films = pool.filter { it.isFilm } + if (films.size < ROTATION_MIN_FILMS || films.size < pool.size * ROTATION_FILM_SHARE) return emptyList() + val everyday = programming.dayParts.filter { it.days.isEmpty() && it.group != "timetable" } + val open = everyday.filter { it.titles.isEmpty() && it.group.isEmpty() } + val parts = if (everyday.isEmpty()) listOf(DayPart(0, 24)) else everyday + // Blocks drawing on the same films are one rotation, their hours added up. + return parts.groupBy { if (it.titles.isEmpty() && it.group.isEmpty()) "" else it.group + "|" + it.titles.joinToString("|") }.mapNotNull { (_, same) -> + val part = same.first() + val inBlock = filmsIn(pool, part) + if (inBlock.size < ROTATION_MIN_FILMS && part !in open) return@mapNotNull null + val ids = inBlock.map { it.id }.toSet() + val label = programming.suggestionRules.firstOrNull { it.group == part.group && part.group.isNotEmpty() }?.label + ?: if (part.titles.isEmpty() && part.group.isEmpty()) (if (same.sumOf(::hours) >= 24 || everyday.isEmpty()) "All day" else "%02d:00 to %02d:00".format(part.fromHour, part.toHour)) + else part.group.replaceFirstChar { it.uppercase() }.ifEmpty { "%02d:00 to %02d:00".format(part.fromHour, part.toHour) } + RotationBlock(programming.number, programming.name, label, part.group, same.sumOf(::hours).coerceAtMost(24), inBlock, films.filter { it.id !in ids }, + programming.suggestionRules.filter { it.type == "Movie" && it.group == part.group && part.group.isNotEmpty() }) + } +} + +/** Fits one of the block's own rules (genres, years, ratings), as Channel suggestions would have chosen it. */ +private fun fitsRule(e: TitleEvidence, rules: List): SuggestionRule? { + val genres = e.genres.orEmpty().map { it.lowercase() }.toSet() + return rules.firstOrNull { r -> r.genres.all { it.lowercase() in genres } && r.excludeGenres.none { it.lowercase() in genres } && (e.year == null || e.year in r.years) && + (e.rating ?: "") !in r.excludeRatings && (r.titleContains == null || e.name.contains(r.titleContains, ignoreCase = true)) } +} + +/** + * The Chair's rotation report: the blocks running thin, worst first, each with a few suggestions. Read only. + * [airings] is each channel's programmes as (film id, start), past and planned; [watches] is how often each film was watched + * (finished, chosen or stayed with); [carriedElsewhere] is every film id on another channel, by channel. + */ +internal fun rotationCards(blocks: List, airings: Map>>, watches: Map, evidence: Map, + text: ChannelText, briefs: List, poolIds: Map>, rejected: (Int) -> Set, movable: (Int) -> Set, + decided: Set, dismissed: Set, nowMs: Long): List { + val carriedByAnother = poolIds.flatMap { (n, ids) -> ids.map { it to n } }.groupBy({ it.first }, { it.second }) + val offered = HashSet() + return blocks.mapNotNull { b -> + val ids = b.films.map { it.id }.toSet() + val titles = b.films.associate { it.id to it.title } + val window = airings[b.channel].orEmpty().filter { (id, at) -> id in ids && at in (nowMs - ROTATION_REPEAT_WINDOW_MS)..(nowMs + ROTATION_REPEAT_WINDOW_MS) } + val back = window.groupBy({ it.first }, { it.second }).filter { (_, times) -> times.sorted().zipWithNext().any { (a, c) -> c - a < ROTATION_REPEAT_WINDOW_MS } }.keys + val kept = back.filter { (watches[it] ?: 0) >= ROTATION_KEPT_WATCHING } + val stale = back - kept.toSet() + val cycle = b.cycleDays + if (cycle >= ROTATION_THIN_DAYS && stale.size < ROTATION_STALE_REPEATS) return@mapNotNull null + // Never stronger than what the block already shows. + val ceiling = b.films.mapNotNull { ratingRank(evidence[it.id]?.rating) }.maxOrNull() ?: return@mapNotNull null + fun allowed(e: TitleEvidence) = ratingRank(e.rating)?.let { it <= ceiling } == true + fun open(p: RotationProposal) = p.key !in dismissed && p.id !in offered + val moves = if (b.group.isEmpty()) emptyList() else b.outside.asSequence().filter { it.id in movable(b.channel) }.mapNotNull { evidence[it.id] } + .filter { e -> allowed(e) && (b.rules.isEmpty() || fitsRule(e, b.rules) != null) } + .sortedByDescending { it.community ?: 0.0 } + .map { e -> RotationProposal(b.channel, b.group, e.id, e.name, e.year, true, + "Already on ${b.channelName} at other times; " + listOfNotNull(e.genres?.take(2)?.joinToString(" and "), e.year?.toString(), e.rating?.let { "rated $it" }).joinToString(", ") + + "; fits ${b.label.lowercase()}") } + .filter(::open).take(ROTATION_MAX_MOVES).toList() + val brief = briefs.firstOrNull { it.number == b.channel } + val inChannel = poolIds[b.channel].orEmpty() + val adds = if (brief == null) emptyList() else evidence.values.asSequence() + .filter { e -> e.type == "Movie" && e.id !in inChannel && carriedByAnother[e.id].orEmpty().none { it != b.channel } && e.id !in rejected(b.channel) && e.id !in decided && + allowed(e) && (b.rules.isEmpty() || fitsRule(e, b.rules) != null) } + .map { e -> e to channelScore(e, brief, text) }.filter { it.second.first >= ROTATION_FIT } + .sortedWith(compareByDescending>>> { it.second.first }.thenByDescending { it.first.community ?: 0.0 }) + .map { (e, s) -> RotationProposal(b.channel, b.group, e.id, e.name, e.year, false, + (s.second.filter { !it.startsWith("description like") && !it.startsWith("no ") }.take(2) + listOfNotNull(e.rating?.let { "rated $it" }, "on no other Orbit channel")).joinToString("; ")) } + .filter(::open).take(ROTATION_MAX_PROPOSALS).toList() + val proposals = (moves + adds).take(ROTATION_MAX_PROPOSALS) + if (proposals.isEmpty()) return@mapNotNull null + offered += proposals.map { it.id } + RotationCard(b.channel, b.channelName, b.label, b.group, b.films.size, cycle, stale.mapNotNull { titles[it] }.sorted(), kept.mapNotNull { titles[it] }.sorted(), proposals) + }.sortedBy { it.cycleDays }.take(ROTATION_MAX_CARDS) +} + +/** Films watched, by id: finished, chosen or stayed with, across every profile on this box. */ +internal fun watchCounts(taste: TasteStore?): Map { + val dir = taste?.directory ?: return emptyMap() + val counted = setOf(TasteKind.Finished, TasteKind.Chose, TasteKind.Stayed) + return dir.listFiles { f -> f.name.endsWith(".events.jsonl") }.orEmpty().flatMap { f -> taste.events(f.name.removeSuffix(".events.jsonl")) } + .filter { it.kind in counted }.groupingBy { it.itemId }.eachCount() +} + +private fun dismissedFile(store: ScheduleStore) = File(store.decisionsFile().parentFile, "rotation-dismissed-0.json") +internal fun loadDismissed(store: ScheduleStore): Set = + runCatching { JSONArray(dismissedFile(store).readText()).let { a -> (0 until a.length()).map { a.getString(it) }.toSet() } }.getOrDefault(emptySet()) + +private val RotationLock = Any() +@Volatile private var rotationCache: Pair>? = null + +/** The rotation report from what's on the box, worked out again when anything it reads changes, or each hour. */ +internal fun rotationReport(store: ScheduleStore, catalogue: CatalogueStore, userId: String, nowMs: Long = System.currentTimeMillis()): List = synchronized(RotationLock) { + val evidenceFile = store.evidenceFile() + if (!evidenceFile.exists()) return@synchronized emptyList() + val key = listOf(evidenceFile.lastModified(), store.poolsStamp(), dismissedFile(store).lastModified(), store.decisionsFile().lastModified(), nowMs / 3_600_000L, + CustomChannels.list.joinToString { "${it.number}" }).joinToString(":") + rotationCache?.takeIf { it.first == key }?.let { return@synchronized it.second } + val started = System.nanoTime() + val pools = SmartChannels.associate { p -> p.number to store.loadPool(userId, p.number)?.series.orEmpty() }.filterValues { it.isNotEmpty() } + val poolIds = pools.mapValues { (_, s) -> s.map { it.id }.toSet() } + val evidence = evidenceFile.readLines().mapNotNull { runCatching { JSONObject(it) }.getOrNull() }.associate { it.optString("id") to TitleEvidence.of(it) } + val customBriefs = CustomChannels.list.mapNotNull { c -> runCatching { yourBrief(c.number, c.name, catalogue.shapeRows(store.loadChoices(userId, c.number).accepted.map { it.id })) }.getOrNull() } + val blocks = SmartChannels.flatMap { p -> pools[p.number]?.let { rotationBlocks(p, it) }.orEmpty() } + val airings = blocks.map { it.channel }.distinct().associateWith { n -> store.loadPlan(userId, n)?.entries.orEmpty().map { it.seriesId to it.startMs } } + val choices = HashMap() + fun choicesOf(n: Int) = choices.getOrPut(n) { store.loadChoices(userId, n) } + val cards = rotationCards(blocks, airings, watchCounts(Taste.store), evidence, ChannelText(poolIds.mapValues { it.value.toList() }, evidence), BaseBriefs + customBriefs, poolIds, + { choicesOf(it).rejected }, { n -> choicesOf(n).accepted.filter { it.type == "Movie" }.map { it.id }.toSet() }, + loadDecisions(store.decisionsFile()).map { it.id }.toSet(), loadDismissed(store), nowMs) + android.util.Log.i("OrbitSchedule", "director rotation blocks=${blocks.size} thin=${cards.size} proposals=${cards.sumOf { it.proposals.size }} tookMs=${(System.nanoTime() - started) / 1_000_000}") + rotationCache = key to cards + cards +} + +/** + * Your decision on a rotation card (approval, Paul's rule): the ticked suggestions are applied and the rest dismissed, so they + * aren't offered again. An addition joins the channel's list for that block; a move lets a film the channel already shows play + * in that block too, keeping its old place. Both take effect at the channel's next top-up; nothing already booked changes. + */ +internal fun decideRotation(store: ScheduleStore, userId: String, card: RotationCard, approved: List, nowMs: Long = System.currentTimeMillis()): Int { + val choices = store.loadChoices(userId, card.channel) + var accepted = choices.accepted + var applied = 0 + for (p in approved) { + if (!EmbyClient.validId(p.id)) continue + if (p.move) { + accepted = accepted.map { s -> + if (s.id != p.id || p.group in s.group.split('+')) s + else { applied++; Suggestion(s.id, s.title, s.year, s.type, listOf(s.group, p.group).filter { it.isNotEmpty() }.joinToString("+"), s.reason, s.sourceId, s.durationMs) } + } + } else if (accepted.none { it.id == p.id }) { + accepted = accepted + Suggestion(p.id, p.title.take(160), p.year, "Movie", p.group, "Added from the Director's Chair: ${card.block.lowercase()} was running thin") + saveDecision(store.decisionsFile(), ChairDecision(p.id, p.title.take(160), "Movie", true, card.channel, card.channel, nowMs)) + applied++ + } + } + if (applied > 0) store.saveChoices(userId, card.channel, ChannelChoices(accepted, choices.rejected - approved.filter { !it.move }.map { it.id }.toSet())) + val skipped = card.proposals.filter { p -> approved.none { it.key == p.key } }.map { it.key } + synchronized(RotationLock) { + val all = loadDismissed(store) + skipped + approved.map { it.key } + runCatching { writeSafely(dismissedFile(store), JSONArray(all.toList().takeLast(2_000)).toString()) } + rotationCache = null + } + return applied +} diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt index c95517c8..686a39ae 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt @@ -198,7 +198,12 @@ private val AfterDarkFilms = listOf("The Thing (1982)", "The Evil Dead (1983)", "From Beyond", "Bad Taste", "Death Race 2000", "Critters", "The Blob (1958)", "Them! (1954)", "It Came from Outer Space", "The Day of the Triffids", "Mars Attacks!", "The Rocky Horror Picture Show", "Withnail & I", "Brazil (1985)", "Pink Flamingos", "Harold and Maude", "El Topo", "The Big Lebowski", "Heathers", "The Adventures of Buckaroo Banzai Across the 8th Dimension", "Big Trouble in Little China", "Barbarella", "The Warriors (1979)", "Evil Dead II", - "Army of Darkness", "House (1977)", "The Holy Mountain", "Repo! The Genetic Opera") + "Army of Darkness", "House (1977)", "The Holy Mountain", "Repo! The Genetic Opera", + // Paul, 18 November 2026: daytime was running thin (about 35 films, back every five days). + *AfterDarkDaytimeAdditions.toTypedArray()) + +/** Films Paul added for After Dark's daytime on 18 November 2026. They play late at night too, like the rest of the day list. */ +private val AfterDarkDaytimeAdditions get() = listOf("Elvira: Mistress of the Dark", "Creepshow 2", "Dead Heat (1988)", "Burke & Hare (2010)", "Godzilla vs. Biollante") /** Orbit's channels, and any you've made yourself (Create your own), as the planner and every screen see them. */ internal val SmartChannels: List get() = BuiltInChannels + CustomChannels.programmings @@ -208,7 +213,7 @@ private val BuiltInChannels = listOf( withdrawnOnOriginal = AfterDarkWithdrawn, dayParts = AfterDarkEvents + AfterDarkStrand + listOf(DayPart(21, 5), DayPart(5, 21, listOf("The 'Burbs", "'Til Death Do Us Part (2017)", "Tremors (1990)", "The Lost Boys (1987)", "Fright Night (1985)", "Poltergeist (1982)", "Scream (1996)", "Escape from New York", "They Live", "Repo Man", "Donnie Darko", "From Dusk Till Dawn", "Creepshow", "Near Dark", "Halloween (1978)", "The Fog (1980)", "Blue Velvet", - "The Wicker Man (1973)", "An American Werewolf in London", "Prince of Darkness") + AfterDarkDaytimeCrossover, group = "day")), + "The Wicker Man (1973)", "An American Werewolf in London", "Prince of Darkness") + AfterDarkDaytimeCrossover + AfterDarkDaytimeAdditions, group = "day")), suggestionRules = listOf( SuggestionRule("day", "Daytime", "Movie", listOf("Horror", "Comedy"), 1975..2010, 6f, setOf("NC-17", "X"), 40, NotCultCinema, 70), // Capped so the biggest blockbusters stay out: this channel is cult cinema. @@ -299,6 +304,12 @@ internal data class EpisodeMark(val season: Int, val episode: Int) : Comparable< } internal data class PoolEpisode(val id: String, val sourceId: String, val mark: EpisodeMark, val title: String, val durationMs: Long) /** [ref] and [year]: which film or series this is apart from the server's number, as [SampleItem] keeps them. */ +/** + * In a block's group. A film can belong to more than one, written "late+day": a film the Director's Chair moved into daytime + * with your approval keeps its place at night too (Paul, 18 November 2026). + */ +internal fun inGroup(series: PoolSeries, group: String) = group.isNotEmpty() && (series.group == group || group in series.group.split('+')) + internal data class PoolSeries(val id: String, val title: String, val episodes: List, val group: String = "", val ref: String = "", val year: Int? = null) { /** A film is its own only episode. */ val isFilm get() = episodes.size == 1 && episodes[0].id == id @@ -388,7 +399,7 @@ internal fun dayPartFor(pool: List, parts: List, 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. val films = part.titles.map { seriesKey(FilmIdentity.of(it).title) }.toSet() - pool.filter { seriesKey(it.title) in titles || (it.isFilm && seriesKey(it.title) in films) || (part.group.isNotEmpty() && it.group == part.group) } + pool.filter { seriesKey(it.title) in titles || (it.isFilm && seriesKey(it.title) in films) || inGroup(it, part.group) } } if (allowed.isNotEmpty()) return Triple(allowed, name, part) } @@ -569,11 +580,11 @@ private fun adaptiveRestMs(films: List, hours: Int, restMs: Long): L } /** The films an everyday block may play, as [dayPartFor] chooses them, without its fallbacks. */ -private fun filmsIn(pool: List, part: DayPart): List { +internal fun filmsIn(pool: List, part: DayPart): List { 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 || (part.group.isNotEmpty() && it.group == part.group)) } + return pool.filter { it.isFilm && (seriesKey(it.title) in titles || seriesKey(it.title) in films || inGroup(it, part.group)) } } /** diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelSuggestions.kt b/android/app/src/main/java/tv/orbit/classic/ChannelSuggestions.kt index 0f6849f8..e24a2067 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelSuggestions.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelSuggestions.kt @@ -24,7 +24,9 @@ internal data class Suggestion(val id: String, val title: String, val year: Int? internal class ChannelChoices(val accepted: List = emptyList(), val rejected: Set = emptySet()) { /** Part of the cache signature, so choosing different titles reads them in. */ - val tag get() = accepted.map { it.id }.sorted().joinToString(",").hashCode().toString() + // A film moved into another block (a group such as "late+day") counts too, so the pool is read again with it; plain groups + // are left out, so existing pools keep their signatures. + val tag get() = accepted.map { it.id + if ('+' in it.group) "@" + it.group else "" }.sorted().joinToString(",").hashCode().toString() } internal const val SUGGESTION_PAGE = 50 diff --git a/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt b/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt index 127256d1..e7a61902 100644 --- a/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt +++ b/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt @@ -399,7 +399,11 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ /** Confirms (true) or dismisses (false) a proposed lesson by its key. */ decideLesson: suspend (String, Boolean) -> Unit = { _, _ -> }, /** Your decision on a Drive-In event idea: approved, deferred or dismissed. Returns what to tell you. */ - decideIdea: suspend (DeskEventIdea, String) -> String = { _, _ -> "" }) { + decideIdea: suspend (DeskEventIdea, String) -> String = { _, _ -> "" }, + /** Blocks running thin, from what's on the box ([rotationReport]). */ + rotation: () -> List = { emptyList() }, + /** Your decision on a rotation card: the approved suggestions, the rest dismissed. Returns what to tell you. */ + decideRotation: suspend (RotationCard, List) -> String = { _, _ -> "" }) { var mode by remember { mutableStateOf(DirectorMode.Balanced) } var version by remember { mutableIntStateOf(0) } var report by remember { mutableStateOf(null) } @@ -409,6 +413,9 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ var said by remember { mutableStateOf(null) } var lesson by remember { mutableStateOf(null) } var eventOpen by remember { mutableStateOf(null) } + var rotationCards by remember { mutableStateOf?>(null) } + var rotationOpen by remember { mutableStateOf(null) } + LaunchedEffect(version) { rotationCards = withContext(Dispatchers.Default) { runCatching { rotation() }.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)) { @@ -476,6 +483,14 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ onClick = { open = ChairChoice(p.title, p.id, p.type, p.year, p.tag, p.line, p.options, false, p.firstRun) }.takeIf { p.options.isNotEmpty() && p.id.isNotEmpty() }) } } Column(Modifier.weight(1f).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(5.dp)) { + Text("SCHEDULE HEALTH", color = Ink, fontFamily = Anton, fontSize = 14.sp) + val thin = rotationCards + when { + thin == null -> Text("Checking each channel's rotation…", color = Muted, fontSize = 12.sp) + thin.isEmpty() -> Text("Every channel's rotation looks fresh.", color = Muted, fontSize = 12.sp) + else -> thin.forEach { c -> ChairCard("RUNNING THIN", "${c.channelName} · ${c.block}", "${c.proposals.size} IDEAS", c.line, onClick = { rotationOpen = c }) } + } + 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 } if (asks.isEmpty()) Text("No either-or calls this week.", color = Muted, fontSize = 12.sp) @@ -522,6 +537,12 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ } } } + rotationOpen?.let { card -> + RotationPopup(card, onDecide = { approved -> + rotationOpen = null; rotationCards = rotationCards?.filter { it !== card } + scope.launch { said = decideRotation(card, approved); version++ } + }, onClose = { rotationOpen = null }) + } lesson?.let { l -> androidx.compose.ui.window.Dialog(onDismissRequest = { lesson = null }, properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false)) { val first = remember { FocusRequester() } @@ -619,3 +640,43 @@ private fun ChairCard(tag: String?, title: String, channel: String?, line: Strin Text(line, color = if (tag == null) ChairGold else Muted, fontSize = 10.sp, maxLines = 2, overflow = TextOverflow.Ellipsis) } } + +/** One block running thin: why, and the Chair's suggestions, each ticked in or out before you approve (Paul, 18 November 2026). */ +@Composable +private fun RotationPopup(card: RotationCard, onDecide: (List) -> Unit, onClose: () -> Unit) { + var ticked by remember(card) { mutableStateOf(card.proposals.map { it.key }.toSet()) } + androidx.compose.ui.window.Dialog(onDismissRequest = onClose, properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false)) { + val first = remember { FocusRequester() } + LaunchedEffect(Unit) { runCatching { first.requestFocus() } } + Column(Modifier.width(680.dp).background(ChairNavy, RoundedCornerShape(10.dp)).border(2.dp, ChairGold, RoundedCornerShape(10.dp)).padding(20.dp), + verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text("SCHEDULE HEALTH · RUNNING THIN", color = ChairGold, fontSize = 11.sp, fontWeight = FontWeight.SemiBold) + Text("${card.channelName} · ${card.block}".uppercase(java.util.Locale.UK), color = Ink, fontFamily = Anton, fontSize = 24.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(card.headline + ".", color = ChairSky, fontSize = 13.sp) + if (card.repeats.isNotEmpty()) Text("Back on air within a week: " + card.repeats.take(5).joinToString(", ") + if (card.repeats.size > 5) " and ${card.repeats.size - 5} more" else "", + color = Muted, fontSize = 11.sp, maxLines = 2, overflow = TextOverflow.Ellipsis) + if (card.keptWatching.isNotEmpty()) Text("You keep watching ${card.keptWatching.take(3).joinToString(", ")}, so those repeats aren't counted against it.", + color = ChairMint, fontSize = 11.sp, maxLines = 2, overflow = TextOverflow.Ellipsis) + Column(Modifier.fillMaxWidth().heightIn(max = 300.dp).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(4.dp)) { + card.proposals.forEachIndexed { i, p -> + Row(Modifier.fillMaxWidth().background(ChairPanel, RoundedCornerShape(6.dp)).padding(horizontal = 10.dp, vertical = 5.dp), + verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + OrbitButton(if (p.key in ticked) "✓ In" else "Out", Modifier.width(76.dp).then(if (i == 0) Modifier.focusRequester(first) else Modifier), selected = p.key in ticked, + onClick = { ticked = if (p.key in ticked) ticked - p.key else ticked + p.key }) + Column(Modifier.weight(1f)) { + Text((if (p.move) "ALSO BY ${card.block.uppercase(java.util.Locale.UK)} · " else "ADD · ") + p.title + (p.year?.let { " ($it)" } ?: ""), + color = Ink, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(p.reason, color = Muted, fontSize = 10.sp, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } + } + } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + OrbitButton("Approve ticked (${ticked.size})", onClick = { onDecide(card.proposals.filter { it.key in ticked }) }) + OrbitButton("Not now", onClick = onClose) + } + Text("Approved, a film joins the channel at its next top-up; one moved keeps its old times too. Anything left out isn't suggested again. Nothing already booked changes.", + color = Muted, fontSize = 10.sp) + } + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt index 8b15fdc1..17620830 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -1044,6 +1044,15 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea decision == "approved" -> "${idea.theme} approved for ${idea.evening}. It books once the Drive-In plans that evening, after its films are checked again." decision == "deferred" -> "${idea.theme} deferred: it can come back in four weeks." else -> "${idea.theme} dismissed: it won't be proposed again unless its films change." } + } }, + rotation = { session?.let { active -> rotationReport(scheduleStore, catalogue, 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 } + android.util.Log.i("OrbitSchedule", "director rotation channel=${card.channel} approved=${approved.size} applied=$applied") + when { applied < 0 -> "That couldn't be saved. Try again." + applied == 0 -> "Nothing changed on ${card.channelName}; the rest won't be suggested again." + else -> "$applied approved for ${card.channelName} ${card.block.lowercase()}. They join at the next top-up, within the hour." } } }) }, isOn = { scheduledChannels.containsKey(it) }, onSwitch = { programming, on -> setSmartSchedule(programming, on) }, onSuggestions = { openSuggestions(it) }, onSignOut = { job?.cancel(); closeSession(signOut = true) }, onRemoveServer = { job?.cancel(); closeSession(remove = true) }, maker = channelMaker, onBackToTv = { onSection("Home") }, diff --git a/android/app/src/test/java/tv/orbit/classic/ChairRotationTest.kt b/android/app/src/test/java/tv/orbit/classic/ChairRotationTest.kt new file mode 100644 index 00000000..cb3cb6eb --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/ChairRotationTest.kt @@ -0,0 +1,128 @@ +package tv.orbit.classic + +import org.junit.Assert.* +import org.junit.Test + +/** The Chair's rotation check (Paul, 18 November 2026): thin pools, stale repeats, daypart moves, additions, approval. */ +class ChairRotationTest { + private val hour = 3_600_000L + private val day = 24 * hour + private val now = 1_795_000_000_000L + private fun film(id: String, title: String, group: String = "", minutes: Int = 100) = + PoolSeries(id, title, listOf(PoolEpisode(id, "s$id", EpisodeMark(1, 1), title, minutes * 60_000L)), group) + private fun ev(id: String, name: String, genres: List, rating: String?, year: Int = 1988, community: Double = 7.0, + overview: String = "A comedy about friends, jokes and laughs in a small town.") = + TitleEvidence(id, "Movie", name, year, overview, genres, null, rating, listOf("United States of America"), null, community = community) + + private val dayRule = SuggestionRule("day", "Daytime", "Movie", listOf("Horror", "Comedy"), 1975..2010, 6f, setOf("NC-17", "X"), 40) + /** A film channel with a daytime block of named films and an open late block, like After Dark. */ + private fun darkLike(dayTitles: List) = ChannelProgramming(305, "After Dark", emptyList(), + dayParts = listOf(DayPart(21, 5), DayPart(5, 21, dayTitles, group = "day")), suggestionRules = listOf(dayRule)) + + @Test fun aSmallDaytimePoolIsRunningThinAndABigLateOneIsNot() { + val dayFilms = (1..10).map { film("d$it", "Day $it") } + val lateFilms = (1..60).map { film("l$it", "Late $it", "late") } + val blocks = rotationBlocks(darkLike(dayFilms.map { it.title }), dayFilms + lateFilms) + val daytime = blocks.single { it.group == "day" } + assertEquals("Daytime", daytime.label) + assertEquals(16, daytime.hoursPerDay) + assertTrue(daytime.cycleDays < ROTATION_THIN_DAYS) // 10 films of 100 minutes in 16 hours a day + assertTrue(blocks.single { it.group == "" }.cycleDays >= ROTATION_THIN_DAYS) + } + + @Test fun aSeriesChannelIsntAFilmRotation() { + val series = (1..10).map { PoolSeries("s$it", "Show $it", (1..5).map { e -> PoolEpisode("s$it-$e", "x", EpisodeMark(1, e), "Ep", 30 * 60_000L) }) } + assertTrue(rotationBlocks(ChannelProgramming(107, "Evidence", emptyList()), series + (1..3).map { film("f$it", "F $it") }).isEmpty()) + } + + private fun cards(blocks: List, evidence: Map, airings: List> = emptyList(), watches: Map = emptyMap(), + poolIds: Map>, movable: Set = emptySet(), dismissed: Set = emptySet(), briefs: List = emptyList()) = + rotationCards(blocks, mapOf(305 to airings), watches, evidence, ChannelText(poolIds.mapValues { it.value.toList() }, evidence), briefs, poolIds, + { emptySet() }, { movable }, emptySet(), dismissed, now) + + @Test fun aLateFilmMovesToDaytimeOnlyWithinTheBlocksAgeRatings() { + val dayFilms = (1..8).map { film("d$it", "Day $it") } + val late = listOf(film("l1", "Gentle Fright", "late"), film("l2", "Gore Fest", "late"), film("l3", "Unknown Rating", "late"), film("l4", "Not Funny", "late")) + val evidence = dayFilms.associate { it.id to ev(it.id, it.title, listOf("Horror", "Comedy"), "R") } + mapOf( + "l1" to ev("l1", "Gentle Fright", listOf("Horror", "Comedy"), "PG-13"), + "l2" to ev("l2", "Gore Fest", listOf("Horror", "Comedy"), "NC-17"), + "l3" to ev("l3", "Unknown Rating", listOf("Horror", "Comedy"), null), + "l4" to ev("l4", "Not Funny", listOf("Horror"), "R")) + val blocks = rotationBlocks(darkLike(dayFilms.map { it.title }), dayFilms + late).filter { it.group == "day" } + val card = cards(blocks, evidence, poolIds = mapOf(305 to (dayFilms + late).map { it.id }.toSet()), movable = late.map { it.id }.toSet()).single() + assertEquals(listOf("Gentle Fright"), card.proposals.filter { it.move }.map { it.title }) // not stronger than R, rating known, fits the daytime rule + assertTrue(card.proposals.first().reason.contains("rated PG-13")) + } + + @Test fun repeatsYouKeepWatchingArentCountedAgainstTheRotation() { + val films = (1..80).map { film("d$it", "Day $it", minutes = 90) } // a big pool, not thin by size + val evidence = films.associate { it.id to ev(it.id, it.title, listOf("Horror", "Comedy"), "PG-13") } + ("x1" to ev("x1", "Spare Film", listOf("Horror", "Comedy"), "PG")) + val program = darkLike(films.map { it.title }) + val blocks = rotationBlocks(program, films).filter { it.group == "day" } + assertTrue(blocks.single().cycleDays >= ROTATION_THIN_DAYS) + val brief = Brief(305, "After Dark", setOf("Movie"), setOf("Horror", "Comedy"), themes = Regex("comedy"), against = Regex("^$"), era = 1970 to 2010) + fun airedTwice(ids: List) = ids.flatMap { listOf(it to now - 3 * day, it to now + day) } + val pools = mapOf(305 to films.map { it.id }.toSet()) + // Three films back within a week, but you watched each of them again: favourites, not a stale rotation. + val watched = (1..3).associate { "d$it" to 2 } + assertTrue(cards(blocks, evidence, airedTwice(listOf("d1", "d2", "d3")), watched, pools, briefs = listOf(brief)).isEmpty()) + // The same repeats with nobody watching are stale. + val stale = cards(blocks, evidence, airedTwice(listOf("d1", "d2", "d3")), emptyMap(), pools, briefs = listOf(brief)).single() + assertEquals(listOf("Day 1", "Day 2", "Day 3"), stale.repeats) + assertEquals("Spare Film", stale.proposals.single().title) + } + + @Test fun additionsFitTheChannelAndSkipFilmsOnAnotherChannel() { + val dayFilms = (1..8).map { film("d$it", "Day $it") } + val evidence = dayFilms.associate { it.id to ev(it.id, it.title, listOf("Horror", "Comedy"), "R") } + mapOf( + "a1" to ev("a1", "Free Film", listOf("Horror", "Comedy"), "R"), + "a2" to ev("a2", "Elsewhere Film", listOf("Horror", "Comedy"), "R"), + "a3" to ev("a3", "Romance Film", listOf("Romance"), "PG", overview = "Two people fall in love in Paris."), + "a4" to ev("a4", "Too Strong", listOf("Horror", "Comedy"), "NC-17")) + val brief = Brief(305, "After Dark", setOf("Movie"), setOf("Horror", "Comedy"), themes = Regex("comedy"), against = Regex("^$"), era = 1970 to 2010) + val blocks = rotationBlocks(darkLike(dayFilms.map { it.title }), dayFilms).filter { it.group == "day" } + val card = cards(blocks, evidence, poolIds = mapOf(305 to dayFilms.map { it.id }.toSet(), 306 to setOf("a2")), briefs = listOf(brief)).single() + assertEquals(listOf("Free Film"), card.proposals.map { it.title }) + assertTrue(card.proposals.single().reason.contains("on no other Orbit channel")) + // Dismissed once, it isn't offered again. + assertTrue(cards(blocks, evidence, poolIds = mapOf(305 to dayFilms.map { it.id }.toSet(), 306 to setOf("a2")), dismissed = setOf(card.proposals.single().key), briefs = listOf(brief)).isEmpty()) + } + + @Test fun yourOwnChannelWithTwentyFilmsIsCheckedToo() { + val films = (1..20).map { film("c$it", "Comedy $it", minutes = 95) } + val mine = ChannelProgramming(YOURS_FIRST, "My Comedy", emptyList()) + val block = rotationBlocks(mine, films).single() + assertEquals("All day", block.label) + assertTrue(block.cycleDays < 2) + val evidence = films.associate { it.id to ev(it.id, it.title, listOf("Comedy"), "PG-13") } + ("n1" to ev("n1", "New Comedy", listOf("Comedy"), "PG-13")) + val brief = Brief(YOURS_FIRST, "My Comedy", setOf("Movie"), setOf("Comedy"), themes = Regex("comedy|jokes"), against = Regex("^$"), era = 1970 to 2026) + val card = rotationCards(listOf(block), emptyMap(), emptyMap(), evidence, ChannelText(mapOf(YOURS_FIRST to films.map { it.id }), evidence), listOf(brief), + mapOf(YOURS_FIRST to films.map { it.id }.toSet()), { emptySet() }, { emptySet() }, emptySet(), emptySet(), now).single() + assertEquals("New Comedy", card.proposals.single().title) + assertFalse(card.proposals.single().move) + } + + @Test fun aMovedFilmKeepsItsOldPlaceAndJoinsTheNewBlock() { + val moved = film("l1", "Gentle Fright", "late+day") + assertTrue(inGroup(moved, "day")) + assertTrue(inGroup(moved, "late")) + assertFalse(inGroup(film("l2", "Other", "late"), "day")) + assertEquals(listOf(moved), filmsIn(listOf(moved, film("l2", "Other", "late")), DayPart(5, 21, emptyList(), group = "day"))) + } + + @Test fun aMoveChangesThePoolSignatureSoItsReadAgain() { + val before = ChannelChoices(listOf(Suggestion("l1", "Gentle Fright", 1988, "Movie", "late", ""))) + val after = ChannelChoices(listOf(Suggestion("l1", "Gentle Fright", 1988, "Movie", "late+day", ""))) + assertNotEquals(before.tag, after.tag) + // Plain groups don't count, so existing pools keep their signatures. + assertEquals(ChannelChoices(listOf(Suggestion("l1", "x", null, "Movie", "late", ""))).tag, ChannelChoices(listOf(Suggestion("l1", "x", null, "Movie", "day", ""))).tag) + } + + @Test fun cardsSurviveTheirSavedForm() { + val card = RotationCard(305, "After Dark", "Daytime", "day", 35, 3.7, listOf("Scream"), listOf("The Fog"), + listOf(RotationProposal(305, "day", "123", "Elvira", 1988, false, "fits"))) + val back = RotationCard.of(card.toJson()) + assertEquals(card.line, back.line) + assertEquals(card.proposals.single().key, back.proposals.single().key) + } +}