Smart setup v2 (candidate, for review): channel-relative slots, balanced dayparts, ratings, whole collections, seasons

- Slots judged against the channel itself: a genre nearly every pick shares
  doesn't decide where a title goes; the age rating does, then genre.
- One-kind channels play all day; mixed ones are balanced by running time, so a
  slot that would run out within a week is topped up from one with plenty, and
  adult titles never leave Late.
- Age ratings normalised across countries (US, UK, FSK, Australia, Brazil and
  ages); unknown is never Kids.
- Collections read a page at a time up to 5,000 members, with complete/total
  kept; an old capped copy is read again once.
- From a collection in Browse, with Add all and an incomplete notice.
- Optional season per channel, with dates; the Director only suggests one.
- Film channels: stars are suggested, applied only on approval. Core prefers
  series. Shaped channels rest files six days.
- Regression fixtures from the Hallmark Christmas and Crunchyroll collections.

Not installed: kept on this branch until reviewed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-07 09:00:31 +00:00
co-authored by Claude Opus 5.5
parent ee856bd6cf
commit 1e0cd4cdb4
16 changed files with 398 additions and 54 deletions
@@ -560,15 +560,23 @@ internal const val CHRISTMAS_NUMBER = 310
* Orbit Christmas is seasonal (Paul, 6 November 2026: "from today ... off from 1st January"): on from 1 November to
* 31 December, and nowhere in the guide or Home the rest of the year.
*/
internal fun inSeason(number: Int, timeMs: Long, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): Boolean =
number != CHRISTMAS_NUMBER || java.time.Instant.ofEpochMilli(timeMs).atZone(zone).monthValue >= 11
internal fun inSeason(number: Int, timeMs: Long, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): Boolean {
val date = java.time.Instant.ofEpochMilli(timeMs).atZone(zone).toLocalDate()
if (number == CHRISTMAS_NUMBER) return date.monthValue >= 11
// A channel of your own with a season you chose.
return CustomChannels.of(number)?.season?.covers(date) ?: true
}
/**
* How far a seasonal channel may be booked: Orbit Christmas books nothing that starts from 1 January (it planned about a
* week into January before, out of sight). Null for every other channel.
*/
internal fun seasonEndMs(number: Int, timeMs: Long, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): Long? {
if (number != CHRISTMAS_NUMBER) return null
if (number != CHRISTMAS_NUMBER) {
val season = CustomChannels.of(number)?.season ?: return null
val date = java.time.Instant.ofEpochMilli(timeMs).atZone(zone).toLocalDate()
return if (season.covers(date)) season.endAfter(date, zone) else timeMs
}
val day = java.time.Instant.ofEpochMilli(timeMs).atZone(zone)
if (day.monthValue < 11) return timeMs
return java.time.LocalDate.of(day.year + 1, 1, 1).atStartOfDay(zone).toInstant().toEpochMilli()
@@ -60,6 +60,8 @@ internal data class ChannelProgramming(val number: Int, val name: String, val se
* the channel's brief. Null keeps equal turns. Only Orbit Three has it (approved 4 November 2026).
*/
val tierWeights: Map<String, Double>? = null,
/** Weighted channels only: how long a file rests before it airs again, where the pool allows ([SAME_FILE_MS] unless set). */
val fileRestMs: Long = SAME_FILE_MS,
/** A film channel's everyday blocks rest each film for a share of how long their own films take to play through ([adaptiveRestMs]). */
val adaptiveFilmRest: Boolean = false,
/**
@@ -102,6 +102,9 @@ internal class ChannelScheduler(private val store: ScheduleStore,
Log.i("OrbitSchedule", "evidence asked=${ids.distinct().size} missing=${missing.size} read=$read failedBatches=$failed")
// Emby's collections, for verified franchise links: resumable from where the last read stopped, a bounded number per run.
val collections = store.collectionsFile()
// Read before collections were paged (every one stopped at 300): set aside once and read again in full.
if (collections.exists() && collections.useLines { lines -> lines.firstOrNull()?.contains("\"complete\"") != true })
collections.renameTo(java.io.File(collections.path + ".before-paged"))
val done = if (collections.exists()) collections.useLines { it.count() } else 0
var start = done; var sets = 0; var total = -1
try {
@@ -313,7 +316,7 @@ internal class ChannelScheduler(private val store: ScheduleStore,
}
val plan = topUpPlan(existing, base, pool?.series?.let { withoutFailed(it, store.loadFailed(userId)) }, now, programming.filmRestMs, programming.finishTogether, programming.dayParts,
avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes,
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping, shorts = programming.shorts, marathon = programming.marathon,
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, fileRestMs = programming.fileRestMs, stories = programming.storyGrouping, shorts = programming.shorts, marathon = programming.marathon,
seasonEndMs = seasonEndMs(number, now)) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
if (plan !== existing) store.savePlan(userId, number, plan)
// Stage C, report only: every work any plan books, so "not yet shown on Orbit" has evidence.
@@ -52,7 +52,22 @@ internal class ChannelMaker(
/** For each title, the other channels already showing it (Paul, 7 November 2026: "check conflicts with the rest of the channels"). */
val carriedBy: (picks: Map<String, String>, number: Int?) -> Map<String, List<String>> = { _, _ -> emptyMap() },
/** How long the picks run all told, in milliseconds, or null when the library can't say. */
val runTime: suspend (List<ShapeRow>) -> Long? = { null })
val runTime: suspend (List<ShapeRow>) -> Long? = { null },
/** Your Emby collections, for Browse › From a collection: each one's name, members and whether all of them were read. */
val collections: suspend () -> List<LibraryCollection> = { emptyList() },
/** Titles by item from the catalogue alone, quickly, for listing a collection. */
val rowsOf: suspend (List<String>) -> List<ShapeRow> = { emptyList() })
/** One of the library's collections as Orbit read it. [complete] is false when it stopped short of [total]. */
internal class LibraryCollection(val name: String, val members: List<String>, val total: Int, val complete: Boolean)
/** The collections the Chair keeps a copy of, read from its file; nothing when it hasn't read them yet. */
internal fun readCollections(file: java.io.File): List<LibraryCollection> = if (!file.exists()) emptyList() else
file.readLines().mapNotNull { line -> runCatching { org.json.JSONObject(line) }.getOrNull() }.map { o ->
val members = o.optJSONArray("members")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty()
// Read before paging, every collection stopped at 300: treat one of exactly that size as possibly cut short.
LibraryCollection(o.optString("name"), members, o.optInt("total", members.size), if (o.has("complete")) o.optBoolean("complete") else members.size < 300)
}.filter { it.name.isNotBlank() && it.members.isNotEmpty() }.distinctBy { it.name }.sortedBy { it.name.lowercase() }
internal enum class CreateStep(val title: String) { Start("Create a channel"), Name("Name and number"), Shows("Shows and films"), Style("How it plays"), Hours("When it's on") }
@@ -157,7 +172,10 @@ internal fun CreateChannelFlow(maker: ChannelMaker, editing: CustomChannel?, onD
OrbitButton(if (working) "Making it…" else if (editing != null) "Save changes" else "Create and switch on", Modifier.width(260.dp), enabled = !working) {
working = true
scope.launch {
val channel = CustomChannel(number, name.trim(), style, hours, description.trim(), chosen.map { it.title })
// Editing on the TV keeps what the phone set: the season, and a shaped layout while the shows and style stay.
val kept = editing?.takeIf { it.style == style && it.shows.toSet() == chosen.map { c -> c.title }.toSet() }
val channel = CustomChannel(number, name.trim(), style, hours, description.trim(), chosen.map { it.title },
slots = kept?.slots.orEmpty(), core = kept?.core.orEmpty(), season = editing?.season)
onDone(runCatching { maker.create(channel, chosen) }.getOrElse { "That channel couldn't be made. Try again." })
}
}
@@ -40,24 +40,30 @@ internal data class CustomChannel(val number: Int, val name: String, val style:
/** The shows' titles in the order they were added: Blocks' timetable follows it. The shows themselves are the accepted choices. */
val shows: List<String> = emptyList(),
/** Shaped only: each title's slot, and the core titles. */
val slots: Map<String, Slot> = emptyMap(), val core: Set<String> = emptySet()) {
val slots: Map<String, Slot> = emptyMap(), val core: Set<String> = emptySet(),
/** On air only through this part of the year, if you chose one (Paul, 7 November 2026: an optional choice, with dates). */
val season: SeasonWindow? = null) {
init { require(number in YOURS_FIRST..YOURS_LAST && name.isNotBlank() && name.length <= 40) }
fun toJson(): JSONObject = JSONObject().put("number", number).put("name", name).put("style", style.name).put("description", description)
.put("hours", hours?.let { JSONObject().put("from", it.fromHour).put("to", it.toHour) } ?: JSONObject.NULL).put("shows", JSONArray(shows))
.put("slots", JSONObject(slots.mapValues { it.value.name })).put("core", JSONArray(core.toList()))
.put("slots", JSONObject(slots.mapValues { it.value.name })).put("core", JSONArray(core.toList())).put("season", season?.toJson() ?: JSONObject.NULL)
companion object {
fun fromJson(o: JSONObject) = CustomChannel(o.getInt("number"), o.getString("name").take(40),
runCatching { PlayStyle.valueOf(o.optString("style")) }.getOrDefault(PlayStyle.Standard),
o.optJSONObject("hours")?.let { OnHours(it.getInt("from").coerceIn(0, 23), it.getInt("to").coerceIn(0, 24)) }, o.optString("description").take(120),
o.optJSONArray("shows")?.let { a -> (0 until minOf(a.length(), 200)).map { a.getString(it).take(160) } }.orEmpty(),
o.optJSONObject("slots")?.let { m -> m.keys().asSequence().take(200).mapNotNull { k -> runCatching { k.take(160) to Slot.valueOf(m.getString(k)) }.getOrNull() }.toMap() }.orEmpty(),
o.optJSONArray("core")?.let { a -> (0 until minOf(a.length(), 20)).map { a.getString(it).take(160) }.toSet() }.orEmpty())
o.optJSONArray("core")?.let { a -> (0 until minOf(a.length(), 20)).map { a.getString(it).take(160) }.toSet() }.orEmpty(),
SeasonWindow.of(o.optJSONObject("season")))
}
}
/** Short episodes on a channel of your own: the same slots as ToonZ's, under a plain name. */
internal val YoursShorts = ShortsRule { _, _ -> "Shorts" }
/** How long a shaped channel's films and episodes rest before airing again. */
internal const val SHAPED_FILE_REST_MS = 6 * 24 * 60 * 60_000L
/** How many episodes a marathon runs before the next show takes over. */
internal const val MARATHON_RUN = 4
@@ -105,6 +111,9 @@ internal fun programmingOf(channel: CustomChannel): ChannelProgramming = Channel
storyGrouping = channel.style == PlayStyle.Standard || channel.style == PlayStyle.Shaped,
shorts = if (channel.style == PlayStyle.Standard || channel.style == PlayStyle.Shaped) YoursShorts else null,
tierWeights = if (channel.style == PlayStyle.Shaped && channel.core.isNotEmpty()) shapedWeights(channel.core) else null,
// A shaped channel's films and episodes rest most of a week before airing again, where it has enough to fill it (the
// Crunchyroll test: with a day's rest, its films came round every three days).
fileRestMs = if (channel.style == PlayStyle.Shaped) SHAPED_FILE_REST_MS else SAME_FILE_MS,
marathon = if (channel.style == PlayStyle.Marathon) MARATHON_RUN else 0)
/**
@@ -62,9 +62,9 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
}
/** The sign-in headers for this kind of server. */
internal fun authHeaders(token: String?): Map<String, String> = when (kind) {
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.84\"") +
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.85\"") +
(token?.let { mapOf("X-Emby-Token" to it) } ?: emptyMap())
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.84\"" +
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.85\"" +
(token?.let { ", Token=\"$it\"" } ?: ""))
}
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
@@ -543,12 +543,17 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
showsOf = { number -> withContext(Dispatchers.IO) { scheduleStore.loadChoices(active.accountId, number).accepted } },
browse = { genre, studio, ratings, type -> withContext(Dispatchers.IO) { catalogue.browseRows(genre, studio, ratings, type) } },
facets = { withContext(Dispatchers.IO) { catalogue.facets() } },
shapeOf = { ids -> withContext(Dispatchers.IO) { catalogue.shapeRows(ids) } },
runTime = { rows -> withContext(Dispatchers.IO) {
val films = rows.filter { it.type == "Movie" }.let { f -> catalogue.runTimes(f.map { it.id }).values.sum() }
val series = rows.filter { it.type == "Series" }.take(40).map { active.seriesRunTime(it.id) }
if (series.any { it == null }) null else films + series.sumOf { it ?: 0L }
// With each title's running time where the library can say (films from the catalogue, up to 60 series from Emby),
// so the Director balances the day by hours, not just by counts.
shapeOf = { ids -> withContext(Dispatchers.IO) {
val rows = catalogue.shapeRows(ids); val films = catalogue.runTimes(rows.filter { it.type == "Movie" }.map { it.id })
var asked = 0
rows.map { r -> val ms = if (r.type == "Movie") films[r.id] else if (asked++ < 60) active.seriesRunTime(r.id) else null
ShapeRow(r.id, r.type, r.title, r.year, r.rating, r.genres, ms) }
} },
collections = { withContext(Dispatchers.IO) { readCollections(scheduleStore.collectionsFile()) } },
rowsOf = { ids -> withContext(Dispatchers.IO) { catalogue.shapeRows(ids) } },
runTime = { rows -> rows.takeIf { r -> r.isNotEmpty() && r.all { it.runMs != null } }?.sumOf { it.runMs ?: 0L } },
carriedBy = { picks, number -> titlesCarriedBy(picks, scheduledChannels.values.filter { it.number != number }) },
create = { asked, shows ->
// Shaped on the TV, or from the phone without a layout: the Director lays it out from the catalogue.
@@ -46,6 +46,10 @@ internal object PlaybackUrls {
internal const val PLAYBACK_INFO_TIMEOUT_MS = 45_000
/** A temporary session is owned by the sample screen, never by persistent storage. */
/** Collections are read a page at a time, up to this many members each. */
internal const val COLLECTION_PAGE = 500
internal const val COLLECTION_MAX = 5000
internal class EmbySampleSession(private val transport: EmbyTransport, private var token: String?,
private val userId: String, sample: EmbySample) {
var sample: EmbySample = sample
@@ -286,10 +290,20 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
val rows = body.optJSONArray("Items")
val sets = (0 until (rows?.length() ?: 0)).mapNotNull { rows!!.optJSONObject(it) }.filter { EmbyClient.validId(it.optString("Id")) }
return sets.map { set ->
val members = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&ParentId=${set.optString("Id")}&Limit=300&Fields=ProviderIds&EnableImages=false&EnableUserData=false",
token = currentToken(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS)).let { r -> EmbyClient.expectSuccess(r.status, false); EmbyClient.parse(r.body).optJSONArray("Items") }
// Every member, a page at a time (Paul, 7 November 2026: it stopped at 300, so big collections were cut short), up to
// COLLECTION_MAX; "complete" says whether all of them were read.
val members = ArrayList<String>(); var total = 0
while (members.size < COLLECTION_MAX) {
val page = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&ParentId=${set.optString("Id")}&StartIndex=${members.size}&Limit=$COLLECTION_PAGE&SortBy=SortName&SortOrder=Ascending&Fields=ProviderIds&EnableImages=false&EnableUserData=false",
token = currentToken(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS)).let { r -> EmbyClient.expectSuccess(r.status, false); EmbyClient.parse(r.body) }
val items = page.optJSONArray("Items")
total = page.optInt("TotalRecordCount", members.size + (items?.length() ?: 0))
val ids = (0 until (items?.length() ?: 0)).mapNotNull { items!!.optJSONObject(it)?.optString("Id")?.takeIf(EmbyClient::validId) }
members += ids
if (ids.size < COLLECTION_PAGE || members.size >= total) break
}
JSONObject().put("id", set.optString("Id")).put("name", EmbyClient.clean(set.optString("Name"), 120))
.put("members", org.json.JSONArray((0 until (members?.length() ?: 0)).mapNotNull { members!!.optJSONObject(it)?.optString("Id")?.takeIf(EmbyClient::validId) }))
.put("members", org.json.JSONArray(members.take(COLLECTION_MAX))).put("total", total).put("complete", members.size >= total)
} to body.optInt("TotalRecordCount", sets.size)
}
@@ -310,7 +310,17 @@ internal object PhoneLink {
val (genres, studios) = runBlocking { h.maker.facets() }
json(out, 200, JSONObject().put("genres", JSONArray(genres)).put("studios", JSONArray(studios)).put("ratings", JSONArray(RatingGroups.keys.toList())))
}
"GET /api/browse" -> {
"GET /api/collections" -> {
val all = runBlocking { h.maker.collections() }
json(out, 200, JSONObject().put("collections", JSONArray(all.map { c -> JSONObject().put("name", c.name).put("count", c.members.size).put("total", c.total).put("complete", c.complete) })))
}
"GET /api/browse" -> if (r.query["collection"] != null) {
// From a collection: its actual members, as the library lists them, not a guess from its name.
val c = runBlocking { h.maker.collections() }.firstOrNull { it.name == r.query["collection"] } ?: return json(out, 404, JSONObject().put("error", "That collection isn't in the library copy yet."))
val rows = runBlocking { h.maker.rowsOf(c.members.take(1000)) }
json(out, 200, JSONObject().put("complete", c.complete).put("total", c.total).put("found", rows.size).put("items", JSONArray(rows.map { row -> suggestionJson(Suggestion(row.id, row.title, row.year, row.type, "",
listOfNotNull(row.genres.take(2).joinToString(", ").ifEmpty { null }, row.rating.ifEmpty { null }).joinToString(" · ").ifEmpty { "In ${c.name}" })) })))
} else {
val rows = runBlocking { h.maker.browse(r.query["genre"]?.take(60), r.query["studio"]?.take(80), RatingGroups[r.query["rating"]].orEmpty(), r.query["type"]?.takeIf { it == "Movie" || it == "Series" }) }
json(out, 200, JSONArray(rows.map { row -> suggestionJson(Suggestion(row.id, row.title, row.year, row.type, "",
listOfNotNull(row.genres.take(2).joinToString(", ").ifEmpty { null }, row.rating.ifEmpty { null }).joinToString(" · ").ifEmpty { "In your library" })) }))
@@ -326,6 +336,9 @@ internal object PhoneLink {
val total = runCatching { runBlocking { h.maker.runTime(rows) } }.getOrNull()
json(out, 200, JSONObject().put("slots", JSONObject(shape.slots.mapValues { it.value.name })).put("core", JSONArray(shape.core.toList()))
.put("mixed", shape.slots.isEmpty() && rows.size >= 3)
// What the Director would suggest but leaves to you: stars on a film channel, and a season.
.put("suggestedCore", JSONArray(shape.suggestedCore.toList())).put("notes", JSONArray(shape.notes))
.put("suggestedSeason", shape.suggestedSeason?.let { it.toJson().put("label", it.label) } ?: JSONObject.NULL)
.put("week", total?.takeIf { it > 0 }?.let { weekLine(it, hoursPerDay) } ?: weekCheck(series, films) ?: JSONObject.NULL)
.put("hours", total?.let { it / 3_600_000.0 } ?: JSONObject.NULL))
}
@@ -348,7 +361,8 @@ internal object PhoneLink {
if (shows.isEmpty()) return json(out, 400, JSONObject().put("error", "Add at least one show or film."))
// Shaped: the phone's layout, by item, kept by title as the planner reads it.
val titleOf = shows.associate { it.id to it.title }
val laidOut = if (channel.style != PlayStyle.Shaped) channel else channel.copy(
val seasoned = channel.copy(season = SeasonWindow.of(o.optJSONObject("season")))
val laidOut = if (seasoned.style != PlayStyle.Shaped) seasoned else seasoned.copy(
slots = o.optJSONObject("slots")?.let { m -> m.keys().asSequence().mapNotNull { id -> titleOf[id]?.let { t -> runCatching { t to Slot.valueOf(m.getString(id)) }.getOrNull() } }.toMap() }.orEmpty(),
core = o.optJSONArray("core")?.let { a -> (0 until minOf(a.length(), 20)).mapNotNull { titleOf[a.getString(it)] }.toSet() }.orEmpty())
val said = runBlocking { withContext(mainDispatcher) { h.maker.create(laidOut, shows) } }
@@ -39,7 +39,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B
next.instanceFollowRedirects = false
next.connectTimeout = 10_000
next.readTimeout = 20_000
next.setRequestProperty("User-Agent", "OrbitTV/0.108.84")
next.setRequestProperty("User-Agent", "OrbitTV/0.108.85")
next.setRequestProperty("Accept-Encoding", "identity")
session.mediaHeaders(address).forEach { (key, value) -> next.setRequestProperty(key, value) }
if (dataSpec.position != 0L || dataSpec.length != C.LENGTH_UNSET.toLong()) {
@@ -11,37 +11,157 @@ internal enum class Slot(val label: String, val fromHour: Int, val toHour: Int)
Daytime("Daytime", 6, 17), Evening("Evening", 17, 22), Late("Late", 22, 6)
}
/** What the Director reads of a title to place it: its kind, age rating, genres and year. */
internal class ShapeRow(val id: String, val type: String, val title: String, val year: Int?, val rating: String, val genres: Set<String>)
/** What the Director reads of a title to place it: its kind, age rating, genres and year, and its running time all told when known. */
internal class ShapeRow(val id: String, val type: String, val title: String, val year: Int?, val rating: String, val genres: Set<String>, val runMs: Long? = null)
/** A channel laid out: each title's slot, and the core titles. */
internal class Shape(val slots: Map<String, Slot>, val core: Set<String>)
/**
* A channel laid out: each title's slot (none: it plays all day), the core titles, and what the Director would suggest but
* leaves to you ([suggestedCore], [suggestedSeason]), with [notes] saying why it moved anything.
*/
internal class Shape(val slots: Map<String, Slot>, val core: Set<String>, val suggestedCore: Set<String> = emptySet(),
val suggestedSeason: SeasonWindow? = null, val notes: List<String> = emptyList())
/** Who a title is for, from its age rating in whichever country's system it uses. Unknown is never taken as Kids. */
internal enum class RatingBand { Kids, Family, Teen, Adult, Unknown }
private val BandOf = mapOf(
// United States
"TV-Y" to RatingBand.Kids, "TV-Y7" to RatingBand.Kids, "TV-Y7-FV" to RatingBand.Kids, "TV-G" to RatingBand.Kids, "G" to RatingBand.Kids,
"TV-PG" to RatingBand.Family, "PG" to RatingBand.Family, "PG-13" to RatingBand.Teen, "TV-14" to RatingBand.Teen,
"R" to RatingBand.Adult, "TV-MA" to RatingBand.Adult, "NC-17" to RatingBand.Adult, "X" to RatingBand.Adult,
// United Kingdom
"U" to RatingBand.Kids, "UC" to RatingBand.Kids, "12A" to RatingBand.Teen, "R18" to RatingBand.Adult,
// Australia and New Zealand
"M" to RatingBand.Teen, "MA15+" to RatingBand.Adult, "R18+" to RatingBand.Adult, "RP13" to RatingBand.Teen, "RP16" to RatingBand.Adult,
// Brazil, Netherlands and others without a number
"L" to RatingBand.Kids, "AL" to RatingBand.Kids, "ALL" to RatingBand.Kids, "E" to RatingBand.Kids)
/**
* Normalises an age rating from any country: US and UK names, Germany's FSK 0 to 18, Australia's, Brazil's BR-L to BR-18,
* and any rating that's an age (12, 16+, DE-16). NR, Not Rated, Approved or nothing at all is Unknown.
*/
internal fun ratingBand(raw: String): RatingBand {
val r = raw.trim().uppercase().removePrefix("FSK").removePrefix("FSK-").trim()
BandOf[r]?.let { return it }
val bare = r.substringAfter('-', r).trim().removeSuffix("+")
BandOf[bare]?.let { if (r.length > bare.length) return it }
val age = Regex("(\\d{1,2})").find(r)?.groupValues?.get(1)?.toIntOrNull() ?: return RatingBand.Unknown
return when { age <= 6 -> RatingBand.Kids; age <= 10 -> RatingBand.Family; age <= 14 -> RatingBand.Teen; else -> RatingBand.Adult }
}
private val LateRatings = setOf("TV-MA", "R", "NC-17", "X", "18", "R18", "MA15+")
private val DayRatings = setOf("TV-Y", "TV-Y7", "TV-Y7-FV", "TV-G", "G", "U", "PG")
private val DayGenres = setOf("Children", "Kids", "Family", "Game Show", "Reality", "Talk", "Home and Garden", "Food", "Travel")
/** Where the Director would put one title. */
internal fun slotFor(row: ShapeRow): Slot = when {
row.rating in LateRatings || "Horror" in row.genres -> Slot.Late
row.type == "Movie" && row.genres.any { it in setOf("Thriller", "Crime", "War") } -> Slot.Late
row.rating in DayRatings || row.genres.any { it in DayGenres } -> Slot.Daytime
"Animation" in row.genres && "Anime" !in row.genres -> Slot.Daytime
"Comedy" in row.genres && (row.year ?: 3000) < 2000 -> Slot.Daytime
else -> Slot.Evening
/** Genres nearly every pick shares: the channel's identity, so they say nothing about where one title belongs. */
internal fun sharedGenres(rows: List<ShapeRow>): Set<String> =
rows.flatMap { it.genres }.groupingBy { it }.eachCount().filter { rows.size >= 3 && it.value >= rows.size * .75 }.keys
/**
* Where the Director would put one title, judged against the channel it's on (Paul, 7 November 2026: on an anime channel,
* Animation says nothing; the rating and tone do). The age rating comes first; genres only where they set the title apart.
*/
internal fun slotFor(row: ShapeRow, shared: Set<String> = emptySet()): Slot {
val g = row.genres - shared
val band = ratingBand(row.rating)
return when {
band == RatingBand.Adult || "Horror" in g -> Slot.Late
row.type == "Movie" && g.any { it in setOf("Thriller", "Crime", "War") } && band != RatingBand.Kids && band != RatingBand.Family -> Slot.Late
band == RatingBand.Teen -> Slot.Evening
band == RatingBand.Kids || band == RatingBand.Family || g.any { it in DayGenres } -> Slot.Daytime
"Animation" in g && "Anime" !in row.genres -> Slot.Daytime
"Comedy" in g && (row.year ?: 3000) < 2000 -> Slot.Daytime
else -> Slot.Evening
}
}
/** Hours a week each slot fills, all day every day. */
private val WeekHours = mapOf(Slot.Daytime to 11 * 7.0, Slot.Evening to 5 * 7.0, Slot.Late to 8 * 7.0)
/** Which titles may move into [to] to fill it: adult titles never leave Late, and only Kids and Family ones join the daytime. */
private fun mayMove(row: ShapeRow, from: Slot, to: Slot): Boolean {
val band = ratingBand(row.rating)
return when (to) {
Slot.Evening -> from == Slot.Daytime
Slot.Late -> from == Slot.Evening || (from == Slot.Daytime && band != RatingBand.Kids)
Slot.Daytime -> from == Slot.Evening && (band == RatingBand.Kids || band == RatingBand.Family)
}
}
/**
* The whole layout: every title's slot, and up to three core titles, the newest of the evening's (or of all, with none there).
* The slots are a starting suggestion, not a rule (Paul, 7 November 2026): a channel that's nearly all one kind, an
* all-horror channel or a kids' one, isn't split up, and everything plays all day.
* The whole layout (Paul, 7 November 2026: a starting suggestion, balanced from the channel's own content):
* - A channel nearly all one kind, an all-horror channel or a kids' one, plays all day instead of being split.
* - Otherwise each title gets its slot ([slotFor]), then any slot that would run out within a week is topped up from
* one with plenty to spare, by running time when it's known, so a small evening isn't repeated night after night.
* - Core: up to three, the newest evening shows. On a film channel nothing is starred for you: the Director's choice is
* offered as [Shape.suggestedCore] to accept or not.
*/
internal fun shapeChannel(rows: List<ShapeRow>): Shape {
val suggested = rows.associate { it.id to slotFor(it) }
val shared = sharedGenres(rows)
val suggested = rows.associate { it.id to slotFor(it, shared) }
val largest = suggested.values.groupingBy { it }.eachCount().maxOfOrNull { it.value } ?: 0
val slots = if (rows.size >= 3 && largest >= rows.size * .75) emptyMap() else suggested
val evening = rows.filter { slots[it.id] == Slot.Evening }.ifEmpty { rows }
return Shape(slots, evening.sortedByDescending { it.year ?: 0 }.take(3).map { it.id }.toSet())
val films = rows.count { it.type == "Movie" }
val filmChannel = rows.isNotEmpty() && films >= rows.size * .75
val season = suggestSeason(rows)
if (rows.size >= 3 && largest >= rows.size * .75) {
val pick = rows.sortedByDescending { it.year ?: 0 }.take(3).map { it.id }.toSet()
return Shape(emptyMap(), if (filmChannel) emptySet() else pick, if (filmChannel) pick else emptySet(), season,
listOf("Nearly all of these belong in one part of the day, so they play all day rather than being split."))
}
val slots = suggested.toMutableMap()
val notes = mutableListOf<String>()
val byId = rows.associateBy { it.id }
// Running time per title: what's known, else a typical length for its kind.
val known = rows.mapNotNull { it.runMs }
fun hours(r: ShapeRow) = (r.runMs ?: if (r.type == "Movie") 6_300_000L else known.takeIf { it.isNotEmpty() }?.average()?.toLong() ?: 36_000_000L) / 3_600_000.0
val total = rows.sumOf(::hours)
val scale = minOf(1.0, total / 168.0)
fun content(s: Slot) = slots.filterValues { it == s }.keys.sumOf { hours(byId.getValue(it)) }
fun target(s: Slot) = WeekHours.getValue(s) * scale
for (to in listOf(Slot.Evening, Slot.Late, Slot.Daytime)) {
if (slots.values.none { it == to } && to != Slot.Evening) continue
val preferred = listOf(RatingBand.Teen, RatingBand.Unknown, RatingBand.Family, RatingBand.Kids)
for (from in Slot.entries.filter { it != to }) {
val candidates = rows.filter { slots[it.id] == from && mayMove(it, from, to) }
.sortedWith(compareBy<ShapeRow> { preferred.indexOf(ratingBand(it.rating)) }.thenByDescending { it.year ?: 0 })
for (c in candidates) {
if (content(to) >= target(to)) break
if (content(from) - hours(c) < target(from) || slots.values.count { it == from } <= 1) continue
slots[c.id] = to
notes += "${c.title} moves to ${to.label} to fill it."
}
}
}
// Core shows are series where there are any: a film plays once a week whatever its star.
val evening = rows.filter { slots[it.id] == Slot.Evening }.ifEmpty { rows }.let { e -> e.filter { it.type == "Series" }.ifEmpty { e } }
val pick = evening.sortedByDescending { it.year ?: 0 }.take(3).map { it.id }.toSet()
return Shape(slots, if (filmChannel) emptySet() else pick, if (filmChannel) pick else emptySet(), season, notes.take(12))
}
/** A Christmas channel's season, offered by the Director when most of the picks are Christmas titles; the choice is yours. */
internal fun suggestSeason(rows: List<ShapeRow>): SeasonWindow? {
val festive = rows.count { r -> Regex("(?i)christmas|xmas|holiday|noel|santa|mistletoe|snow").containsMatchIn(r.title) || "Christmas" in r.genres }
return if (rows.size >= 3 && festive >= rows.size * .5) SeasonWindow(11, 1, 12, 31) else null
}
/** When a channel of your own is on air through the year: from one day to another, wrapping past New Year. */
internal data class SeasonWindow(val fromMonth: Int, val fromDay: Int, val toMonth: Int, val toDay: Int) {
init { require(fromMonth in 1..12 && toMonth in 1..12 && fromDay in 1..31 && toDay in 1..31) }
private fun key(m: Int, d: Int) = m * 100 + d
fun covers(date: java.time.LocalDate): Boolean {
val k = key(date.monthValue, date.dayOfMonth); val from = key(fromMonth, fromDay); val to = key(toMonth, toDay)
return if (from <= to) k in from..to else k >= from || k <= to
}
/** The first moment after the window ends, from [date] inside it. */
fun endAfter(date: java.time.LocalDate, zone: java.time.ZoneId): Long {
var end = java.time.LocalDate.of(date.year, toMonth, 1).let { it.withDayOfMonth(minOf(toDay, it.lengthOfMonth())) }
if (end.isBefore(date)) end = end.plusYears(1)
return end.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
}
val label get() = "%d %s to %d %s".format(fromDay, month(fromMonth), toDay, month(toMonth))
private fun month(m: Int) = java.time.Month.of(m).getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.UK)
fun toJson(): org.json.JSONObject = org.json.JSONObject().put("fromMonth", fromMonth).put("fromDay", fromDay).put("toMonth", toMonth).put("toDay", toDay)
companion object {
fun of(o: org.json.JSONObject?): SeasonWindow? = o?.let { runCatching { SeasonWindow(it.getInt("fromMonth"), it.getInt("fromDay"), it.getInt("toMonth"), it.getInt("toDay")) }.getOrNull() }
}
}
/**
@@ -121,5 +241,7 @@ internal fun yourBrief(number: Int, name: String, rows: List<ShapeRow>): Brief?
val years = rows.mapNotNull { it.year }
val never = Regex("(?!)")
return Brief(number, name, rows.map { it.type }.toSet(), common.ifEmpty { counts.keys.take(4).toSet() }, must, never, never,
(years.minOrNull() ?: 1900) - 5 to (years.maxOrNull() ?: 2030) + 5, kids = rows.all { it.rating in KidsOk })
(years.minOrNull() ?: 1900) - 5 to (years.maxOrNull() ?: 2030) + 5,
// Unknown ratings never make a channel count as children's (Paul, 7 November 2026).
kids = rows.all { ratingBand(it.rating) == RatingBand.Kids || ratingBand(it.rating) == RatingBand.Family })
}