diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 52567744..535105e0 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 = 69 +val ORBIT_BUILD = 70 android { namespace = "tv.orbit.classic" compileSdk = 36 diff --git a/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt b/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt index 37e77dac..97cdb0cd 100644 --- a/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt @@ -233,6 +233,19 @@ internal class CatalogueStore(context: Context, private val file: File) : Catalo buildList { while (c.moveToNext()) add(ShapeRow(c.getString(0), c.getString(1), c.getString(2), if (c.isNull(3)) null else c.getInt(3), c.getString(4), c.getString(5).split('|').filter { it.isNotBlank() }.toSet())) } } } + /** + * Rated films carrying any of [genres], at most [limit], for the Chair to judge from catalogue genres and ratings where no + * description has been read (audit, 18 November 2026). Read only; the box's own catalogue, never the server. + */ + @Synchronized fun ratedFilmsIn(genres: Collection, limit: Int): List { + val wanted = genres.filter { it.isNotBlank() }.distinct().take(12) + if (wanted.isEmpty() || limit <= 0) return emptyList() + val where = wanted.joinToString(" OR ") { "('|' || genres || '|') LIKE ?" } + return readableDatabase.rawQuery("SELECT id, type, title, year, rating, genres FROM items WHERE type = 'Movie' AND rating != '' AND ($where) LIMIT $limit", + wanted.map { "%|$it|%" }.toTypedArray()).use { c -> + buildList { while (c.moveToNext()) add(ShapeRow(c.getString(0), c.getString(1), c.getString(2), if (c.isNull(3)) null else c.getInt(3), c.getString(4), c.getString(5).split('|').filter { it.isNotBlank() }.toSet())) } + } + } @Volatile private var facetCache: Pair, List>? = null /** The library's most common genres and networks or studios, for browsing; worked out once. Read only. */ @Synchronized fun facets(): Pair, List> = facetCache ?: run { diff --git a/android/app/src/main/java/tv/orbit/classic/ChairRotation.kt b/android/app/src/main/java/tv/orbit/classic/ChairRotation.kt index 7ac9590f..bb67891a 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChairRotation.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChairRotation.kt @@ -30,6 +30,9 @@ internal const val ROTATION_KEPT_WATCHING = 2 internal const val ROTATION_MAX_CARDS = 3 internal const val ROTATION_MAX_PROPOSALS = 6 internal const val ROTATION_MAX_MOVES = 4 +/** At most this many films from the box's catalogue are judged on genres and rating alone, per report. */ +internal const val ROTATION_CATALOGUE_FILMS = 4_000 + /** 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. */ @@ -116,6 +119,9 @@ internal fun rotationCards(blocks: List, airings: Map, 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 }) + // Copies of one film are one film (23 November 2026: Fraggle Rock offered three times): by name and year, whichever copy. + fun work(e: TitleEvidence) = filmKey(e.name) + "|" + (e.year ?: "") + val carriedWorks = poolIds.flatMap { (n, ids) -> ids.mapNotNull { id -> evidence[id]?.let { work(it) to n } } }.groupBy({ it.first }, { it.second }) val offered = HashSet() return blocks.mapNotNull { b -> val ids = b.films.map { it.id }.toSet() @@ -129,7 +135,7 @@ internal fun rotationCards(blocks: List, airings: Map allowed(e) && (b.rules.isEmpty() || fitsRule(e, b.rules) != null) } .sortedByDescending { it.community ?: 0.0 } @@ -141,7 +147,8 @@ internal fun rotationCards(blocks: List, airings: Map 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) } + carriedWorks[work(e)].isNullOrEmpty() && allowed(e) && (b.rules.isEmpty() || fitsRule(e, b.rules) != null) } + .distinctBy(::work) .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, @@ -149,7 +156,7 @@ internal fun rotationCards(blocks: List, airings: Map evidence[p.id]?.let { work(it) } } 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) } @@ -179,13 +186,20 @@ internal fun rotationReport(store: ScheduleStore, catalogue: CatalogueStore, use 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 read = 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() } + // Where no description has been read, the catalogue's own genres and rating (audit, 18 November 2026: on the VPS most films + // had none read, so blocks had no known rating and nothing could be judged). A description, when there is one, still wins. + val briefs = BaseBriefs + customBriefs + val wantedGenres = briefs.filter { b -> blocks.any { it.channel == b.number } }.flatMap { it.genresAny } + val catalogued = runCatching { catalogue.shapeRows(pools.values.flatten().filter { it.isFilm && it.id !in read }.map { it.id }) + catalogue.ratedFilmsIn(wantedGenres, ROTATION_CATALOGUE_FILMS) } + .getOrDefault(emptyList()).associate { r -> r.id to TitleEvidence(r.id, r.type, r.title, r.year, null, r.genres.toList(), null, r.rating.ifBlank { null }, null, null) } + val evidence = catalogued + read 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, + val cards = rotationCards(blocks, airings, watchCounts(Taste.store), evidence, ChannelText(poolIds.mapValues { it.value.toList() }, evidence), briefs, 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}") @@ -224,3 +238,30 @@ internal fun decideRotation(store: ScheduleStore, userId: String, card: Rotation } return applied } + +/** + * A series a channel can only play part of: its playable episodes, and the numbers missing between them. Paul's continuity + * brief (18 November 2026): explain missing instalments rather than leave a story to jump. Orbit plays what's there in + * order and goes round again, so a show with two episodes of six looks out of order on the guide when it isn't. + */ +internal class SeriesGap(val channel: Int, val channelName: String, val title: String, val playable: Int, val missing: List) { + val line get() = "$playable playable; missing " + missing.take(6).joinToString(", ") { "S${it.season} E${it.episode}" } + + (if (missing.size > 6) " and ${missing.size - 6} more" else "") + ". The rest aren't on the server or won't play on this box." +} + +/** The numbers missing in each season of [series], from episode 1 to its last playable one. */ +internal fun missingEpisodes(series: PoolSeries): List = series.episodes.map { it.mark }.filter { it.season in 1..999 && it.episode > 0 } + .groupBy { it.season }.toSortedMap().flatMap { (season, marks) -> val have = marks.map { it.episode }.toSet(); (1..have.max()).filter { it !in have }.map { EpisodeMark(season, it) } } + +/** Series missing at least half as many episodes as they have, worst first: where a gap shows on screen. */ +internal fun seriesGaps(channels: List>>, limit: Int = 8): List = channels.flatMap { (p, pool) -> + pool.filter { !it.isFilm }.mapNotNull { s -> + val missing = missingEpisodes(s) + val playable = s.episodes.size + if (missing.size >= 2 && missing.size * 2 >= playable) SeriesGap(p.number, p.name, s.title, playable, missing) else null + } +}.sortedByDescending { it.missing.size.toDouble() / (it.missing.size + it.playable) }.take(limit) + +/** [seriesGaps] for every channel on the box, from the pools it has kept. Read only. */ +internal fun gapReport(store: ScheduleStore, userId: String): List = + seriesGaps(SmartChannels.mapNotNull { p -> store.loadPool(userId, p.number)?.series?.takeIf { it.isNotEmpty() }?.let { p to it } }) 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 686a39ae..43992f25 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt @@ -469,29 +469,67 @@ internal fun clashesWithAirings(airings: List): ProgrammeClash { return { show, startMs, endMs -> byKey[seriesKey(show.title)].orEmpty().any { it.startMs < endMs && startMs < it.endMs } } } +/** + * Network-wide film rest (Paul, 23 November 2026: Sleepaway Camp was Joe Bob's film on After Dark on Saturday, on the + * Drive-In on Sunday and booked on Horror for Friday). A film channel passes over a film that another channel has shown or + * booked within this long either side, as long as it has another rested film to play instead. It only steers new bookings: + * nothing already in the guide moves, and a channel never goes without because of it. + */ +internal const val NETWORK_FILM_REST_MS = 5 * 24 * 60 * 60_000L + +/** True if [film] airs on another channel within [NETWORK_FILM_REST_MS] of [startMs]. */ +internal typealias NetworkRest = (film: PoolSeries, startMs: Long) -> Boolean +internal val NoNetworkRest: NetworkRest = { _, _ -> false } + +/** A film's own name as a key, without any year a list gives it, so "Halloween (1978)" and "Halloween" are one film. */ +internal fun filmKey(title: String) = seriesKey(FilmIdentity.of(title).title) + +/** The films a plan shows: each film by name, and each hosted episode (Joe Bob's Last Drive-in) as the film it presents. */ +internal fun filmAiringsOf(plan: ChannelPlan) = plan.entries.mapNotNull { e -> + val title = e.media.item.title + when { + e.media.item.type == "Movie" -> Airing(filmKey(title), e.startMs, e.endMs) + title.startsWith("$LAST_DRIVE_IN / ") && title.count { it == '/' } >= 2 -> Airing(filmKey(title.substringAfterLast(" / ")), e.startMs, e.endMs) + else -> null + } +} + +/** [NetworkRest] from other channels' film airings. */ +internal fun restingElsewhere(airings: List, restMs: Long = NETWORK_FILM_REST_MS): NetworkRest { + if (airings.isEmpty()) return NoNetworkRest + val byKey = airings.groupBy { it.key } + return { film, startMs -> byKey[filmKey(film.title)].orEmpty().any { it.startMs < startMs + restMs && startMs - restMs < it.endMs } } +} + /** * A film past its rest, chosen by a generator seeded from the start time so a plan can be explained and reproduced. * If the pool is too small for the rest period, the film that has waited longest. */ -internal fun nextFilm(pool: List, shown: Map, startMs: Long, restMs: Long, avoid: ProgrammeClash = { _, _, _ -> false }): PoolSeries = - chooseFilm(pool, shown, startMs, restMs, avoid).first +internal fun nextFilm(pool: List, shown: Map, startMs: Long, restMs: Long, avoid: ProgrammeClash = { _, _, _ -> false }, network: NetworkRest = NoNetworkRest): PoolSeries = + chooseFilm(pool, shown, startMs, restMs, avoid, network).first /** [nextFilm], with the reason for its choice. The choice itself is made exactly as before. */ -internal fun chooseFilm(pool: List, shown: Map, startMs: Long, restMs: Long, avoid: ProgrammeClash = { _, _, _ -> false }): Pair { +internal fun chooseFilm(pool: List, shown: Map, startMs: Long, restMs: Long, avoid: ProgrammeClash = { _, _, _ -> false }, + network: NetworkRest = NoNetworkRest): Pair { val restedAll = pool.filter { film -> shown[film.id]?.let { startMs - it >= restMs } ?: true } val clear = restedAll.filter { !avoid(it, startMs, startMs + it.episodes.first().durationMs) } val rested = clear.ifEmpty { restedAll } if (rested.isNotEmpty()) { - val film = rested[java.util.Random(startMs).nextInt(rested.size)] + // Network rest: a film on another channel this week waits, unless every rested film is. + val fresh = rested.filter { !network(it, startMs) } + val from = fresh.ifEmpty { rested } + val film = from[java.util.Random(startMs).nextInt(from.size)] val waited = shown[film.id]?.let { "last shown ${(startMs - it) / 3_600_000}h ago" } ?: "not shown before" val deferred = restedAll.size - clear.size return film to buildString { - append("picked from ${rested.size} rested films, $waited") + append("picked from ${from.size} rested films, $waited") if (clear.isEmpty()) append("; fallback: every rested film airs elsewhere then") else if (deferred > 0) append("; deferred $deferred airing elsewhere") + if (fresh.isEmpty()) append("; every rested film is on another channel this week") + else if (fresh.size < rested.size) append("; rested ${rested.size - fresh.size} on another channel this week") } } - val unclashed = pool.filter { !avoid(it, startMs, startMs + it.episodes.first().durationMs) } + val unclashed = pool.filter { !avoid(it, startMs, startMs + it.episodes.first().durationMs) }.let { u -> u.filter { !network(it, startMs) }.ifEmpty { u } } val film = unclashed.ifEmpty { pool }.minBy { shown[it.id] ?: Long.MIN_VALUE } return film to "fallback: no film past its rest, so the longest waiting" + if (unclashed.isEmpty()) ", even though it airs elsewhere then" else "" } @@ -499,7 +537,7 @@ internal fun chooseFilm(pool: List, shown: Map, startM /** Films by their rest period, back to back from [fromMs] until [untilMs] is covered. */ internal fun extendFilmSchedule(pool: List, cursor: ScheduleCursor, fromMs: Long, untilMs: Long, restMs: Long, dayParts: List = emptyList(), zone: java.time.ZoneId = java.time.ZoneId.systemDefault(), avoid: ProgrammeClash = { _, _, _ -> false }, - adaptiveRest: Boolean = false): ChannelPlan { + adaptiveRest: Boolean = false, network: NetworkRest = NoNetworkRest): ChannelPlan { val shown = cursor.filmShown.toMutableMap() val entries = mutableListOf() var last = cursor.lastSeriesId @@ -533,11 +571,11 @@ internal fun extendFilmSchedule(pool: List, cursor: ScheduleCursor, val films = available.filter { it.isFilm }.ifEmpty { pool.filter { it.isFilm } }.ifEmpty { available } // Events keep the channel's rest; everyday blocks, when adaptive, rest by how long their own films last. val rest = if (adaptiveRest && part?.days.isNullOrEmpty()) blockRest.getOrPut(part) { sharedAdaptiveRestMs(pool, dayParts, part, restMs) } else restMs - var (film, why) = chooseFilm(films, shown, start, rest, avoid) + var (film, why) = chooseFilm(films, shown, start, rest, avoid, network) // Before an appointment, a rested film that leaves it on time, picked in the same seeded order as any other. val appointment = if (part?.onTime == true) null else nextAppointment(start, zone, (ON_TIME_FILM_RUN_IN_MS / (60 * 60_000L)).toInt()) { at -> dayPartFor(pool, dayParts, at, zone) } if (appointment != null) { - val clear = films.filter { f -> !avoid(f, start, start + f.episodes.first().durationMs) } + val clear = films.filter { f -> !avoid(f, start, start + f.episodes.first().durationMs) }.let { c -> c.filter { !network(it, start) }.ifEmpty { c } } // Rested films in the same seeded order as any other pick; when none is rested, the longest waiting first, as the fallback would. val rested = clear.filter { f -> shown[f.id]?.let { start - it >= rest } != false }.shuffled(java.util.Random(start)) .ifEmpty { clear.sortedBy { shown[it.id] ?: Long.MIN_VALUE } } @@ -917,9 +955,11 @@ internal fun extendSchedule(pool: List, cursor: ScheduleCursor, from /** Shorts grouping ([ShortsRule]), or null for none. */ shorts: ShortsRule? = null, /** Marathon: this many episodes of a show back to back before the next; 0 for none. */ - marathon: Int = 0): ChannelPlan { + marathon: Int = 0, + /** Film channels only: [NETWORK_FILM_REST_MS]. */ + network: NetworkRest = NoNetworkRest): ChannelPlan { require(pool.isNotEmpty() && pool.all { it.episodes.isNotEmpty() }) - if (filmRestMs != null) return extendFilmSchedule(pool, cursor, fromMs, untilMs, filmRestMs, dayParts, zone, avoid, adaptiveRest) + if (filmRestMs != null) return extendFilmSchedule(pool, cursor, fromMs, untilMs, filmRestMs, dayParts, zone, avoid, adaptiveRest, network) val marks = cursor.marks.toMutableMap() val entries = mutableListOf() var last = cursor.lastSeriesId @@ -1090,7 +1130,9 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List /** See [ChannelProgramming.marathon]. */ marathon: Int = 0, /** Nothing is booked to start from here on: a seasonal channel's end ([seasonEndMs]). */ - seasonEndMs: Long? = null): ChannelPlan? { + seasonEndMs: Long? = null, + /** Film channels only: [NETWORK_FILM_REST_MS]. */ + network: NetworkRest = NoNetworkRest): ChannelPlan? { val kept = existing?.let { plan -> plan.copy(entries = plan.entries.dropWhile { it.endMs < nowMs - SCHEDULE_KEEP_PAST_MS }) } if (kept != null && kept.endMs >= nowMs + SCHEDULE_TOP_UP_MS) return kept if (pool.isNullOrEmpty()) return kept @@ -1102,7 +1144,7 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List val added = if (weightOf != null && filmRestMs == null) { val recent = kept?.entries.orEmpty().filter { it.startMs >= from - fileRestMs }.associate { it.media.item.id to it.startMs } extendByBlock(pool, existing?.tail ?: aired, from, untilMs, weightOf, dayParts, zone, avoid, shuffle, mixed, finishTogether, recent, trailing, fileRestMs, stories, shorts) - } else extendSchedule(pool, existing?.tail ?: aired, from, untilMs, filmRestMs, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing, noThirdInARow && marathon == 0, blockRotation, adaptiveRest, stories = stories, shorts = shorts, marathon = marathon) + } else extendSchedule(pool, existing?.tail ?: aired, from, untilMs, filmRestMs, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing, noThirdInARow && marathon == 0, blockRotation, adaptiveRest, stories = stories, shorts = shorts, marathon = marathon, network = network) return ChannelPlan(kept?.entries.orEmpty() + added.entries, added.tail) } diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt index e11a5aa3..52c2a3b3 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -350,12 +350,15 @@ internal class ChannelScheduler(private val store: ScheduleStore, * What each other channel has on air, for clash avoidance, kept with its plan file's stamp, so a scheduling pass doesn't * parse every plan again for each channel. Only titles and times are kept, not whole plans. */ - private val otherAirings = HashMap, Pair, List>>() - private fun airingsOn(userId: String, number: Int): List = synchronized(otherAirings) { + private class OtherPlan(val airings: List, val films: List) + private val otherAirings = HashMap, Pair, OtherPlan>>() + private fun otherPlan(userId: String, number: Int): OtherPlan = synchronized(otherAirings) { val stamp = store.planStamp(number) otherAirings[userId to number]?.takeIf { it.first == stamp }?.second - ?: store.loadPlan(userId, number)?.let(::airingsOf).orEmpty().also { otherAirings[userId to number] = stamp to it } + ?: (store.loadPlan(userId, number)?.let { OtherPlan(airingsOf(it), filmAiringsOf(it)) } ?: OtherPlan(emptyList(), emptyList())) + .also { otherAirings[userId to number] = stamp to it } } + private fun airingsOn(userId: String, number: Int): List = otherPlan(userId, number).airings fun topUp(session: EmbySampleSession, userId: String, programming: ChannelProgramming, loop: SampleChannel, checkActive: () -> Unit = {}): SchedulerReport { SeriesInspection.take()?.let { title -> runCatching { session.inspectSeries(title, store.loadFailed(userId)) }.getOrElse { listOf("inspect failed: ${it.javaClass.simpleName} ${(it as? EmbyCheckException)?.httpStatus} ${it.message?.take(160)}") }.forEach { Log.i("OrbitSchedule", it) } } @@ -413,13 +416,16 @@ internal class ChannelScheduler(private val store: ScheduleStore, clashesWithAirings((SmartChannels.map { it.number }.filter { it != number } + DRIVE_IN_NUMBER).flatMap { airingsOn(userId, it) }) .also { othersMs = android.os.SystemClock.elapsedRealtime() - began } } + // Film channels also rest a film another channel (the Drive-In included) shows or has booked this week. + val restingElsewhere by lazy { restingElsewhere((SmartChannels.map { it.number }.filter { it != number } + DRIVE_IN_NUMBER).flatMap { otherPlan(userId, it).films }) } + val network: NetworkRest = if (programming.filmRestMs == null) NoNetworkRest else { film, at -> restingElsewhere(film, at) } // Under the plan lock, so a programme being re-timed for its real length (PlanEdits) is never written over. val (existing, plan) = synchronized(PlanEdits.lock) { val existing = store.loadPlan(userId, number) val plan = topUpPlan(existing, base, pool?.series?.let { withoutFailed(it, store.loadFailed(userId)) }?.let { if (programming.mixedTurns) mixedTurnOrder(it, number) else it }, 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, 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.") + seasonEndMs = seasonEndMs(number, now), network = network) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.") // Franchise films booked side by side go in release order, among the new bookings only (Continuity.kt). val ordered = if (plan === existing) plan else runCatching { val from = plan.entries.indexOfFirst { it.startMs >= (existing?.endMs ?: Long.MIN_VALUE) }.takeIf { it >= 0 } ?: plan.entries.size 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 e7a61902..f07422a1 100644 --- a/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt +++ b/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt @@ -403,7 +403,9 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ /** 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 = { _, _ -> "" }) { + decideRotation: suspend (RotationCard, List) -> String = { _, _ -> "" }, + /** Series a channel can only play part of ([gapReport]). */ + gaps: () -> List = { emptyList() }) { var mode by remember { mutableStateOf(DirectorMode.Balanced) } var version by remember { mutableIntStateOf(0) } var report by remember { mutableStateOf(null) } @@ -416,6 +418,8 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ var rotationCards by remember { mutableStateOf?>(null) } var rotationOpen by remember { mutableStateOf(null) } LaunchedEffect(version) { rotationCards = withContext(Dispatchers.Default) { runCatching { rotation() }.getOrDefault(emptyList()) } } + var gapList by remember { mutableStateOf(emptyList()) } + LaunchedEffect(version) { gapList = withContext(Dispatchers.Default) { runCatching { gaps() }.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)) { @@ -490,6 +494,7 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ 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 }) } } + gapList.forEach { g -> ChairCard("SHORT OF EPISODES", "${g.title} · ${g.channelName}", null, g.line) } 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 } 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 b32b69c5..25a1e015 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -1046,6 +1046,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea else -> "${idea.theme} dismissed: it won't be proposed again unless its films change." } } }, rotation = { session?.let { active -> rotationReport(scheduleStore, catalogue, active.accountId) }.orEmpty() }, + gaps = { session?.let { active -> gapReport(scheduleStore, 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 } diff --git a/android/app/src/test/java/tv/orbit/classic/ChairRotationTest.kt b/android/app/src/test/java/tv/orbit/classic/ChairRotationTest.kt index cb3cb6eb..0f45b279 100644 --- a/android/app/src/test/java/tv/orbit/classic/ChairRotationTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/ChairRotationTest.kt @@ -88,6 +88,36 @@ class ChairRotationTest { 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 copiesOfOneFilmAreOfferedOnceAndNotAtAllWhenAnotherChannelHasACopy() { + // 23 November 2026: Fraggle Rock offered three times, once for each copy in the library. + 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( + "c1" to ev("c1", "Copied Film", listOf("Horror", "Comedy"), "R"), + "c2" to ev("c2", "Copied Film", listOf("Horror", "Comedy"), "R"), + "c3" to ev("c3", "Copied Film", listOf("Horror", "Comedy"), "R"), + "r1" to ev("r1", "Copied Film", listOf("Horror", "Comedy"), "R", year = 2004), + "o1" to ev("o1", "Shown Elsewhere", listOf("Horror", "Comedy"), "R"), + "o2" to ev("o2", "Shown Elsewhere", listOf("Horror", "Comedy"), "R")) + 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("o1")), briefs = listOf(brief)).single() + // One copy of the 1988 film, the 2004 remake as its own film, and nothing another channel already has a copy of. + assertEquals(listOf("Copied Film|1988", "Copied Film|2004"), card.proposals.map { "${it.title}|${it.year}" }.sorted()) + } + + @Test fun catalogueGenresAndRatingsAreEnoughWhereNoDescriptionWasRead() { + // As rotationReport builds them from the box's catalogue: name, year, genres and rating, no description. + fun cat(id: String, name: String, genres: List, rating: String) = TitleEvidence(id, "Movie", name, 1988, null, genres, null, rating, null, null) + val dayFilms = (1..8).map { film("d$it", "Day $it") } + val evidence = dayFilms.associate { it.id to cat(it.id, it.title, listOf("Horror", "Comedy"), "R") } + mapOf( + "k1" to cat("k1", "Catalogue Film", listOf("Horror", "Comedy"), "R"), + "k2" to cat("k2", "Catalogue Drama", listOf("Drama"), "R")) + 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()), briefs = listOf(brief)).single() + assertEquals(listOf("Catalogue Film"), card.proposals.map { it.title }) + } + @Test fun yourOwnChannelWithTwentyFilmsIsCheckedToo() { val films = (1..20).map { film("c$it", "Comedy $it", minutes = 95) } val mine = ChannelProgramming(YOURS_FIRST, "My Comedy", emptyList()) diff --git a/android/app/src/test/java/tv/orbit/classic/NetworkFilmRestTest.kt b/android/app/src/test/java/tv/orbit/classic/NetworkFilmRestTest.kt new file mode 100644 index 00000000..82909510 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/NetworkFilmRestTest.kt @@ -0,0 +1,77 @@ +package tv.orbit.classic + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Network-wide film rest (Paul, 23 November 2026: Sleepaway Camp on After Dark, the Drive-In and Horror in one week). */ +class NetworkFilmRestTest { + private val hour = 60 * 60_000L + private val day = 24 * hour + private val start = java.time.LocalDate.of(2026, 11, 23).atStartOfDay(java.time.ZoneOffset.UTC).toInstant().toEpochMilli() + private fun film(n: Int, title: String = "Film $n", minutes: Int = 100) = + PoolSeries("f$n", title, listOf(PoolEpisode("f$n", "src", EpisodeMark(1, 1), title, minutes * 60_000L))) + private fun films(range: IntRange) = range.map { film(it) } + private fun entry(title: String, type: String, at: Long, minutes: Int = 100) = + ScheduleEntry("x", EpisodeMark(1, 1), ScheduledMedia(SampleItem(title, type, minutes.toLong(), "", "i-$title"), "src", minutes * 60_000L), at, "") + private fun otherChannel(vararg titles: String, at: Long = start) = ChannelPlan(titles.mapIndexed { i, t -> entry(t, "Movie", at + i * 2 * hour) }, ScheduleCursor()) + + @Test fun aFilmOnAnotherChannelThisWeekWaitsWhileOthersAreRested() { + val elsewhere = restingElsewhere(filmAiringsOf(otherChannel(*(1..10).map { "Film $it" }.toTypedArray()))) + val plan = extendFilmSchedule(films(1..40), ScheduleCursor(), start, start + 2 * day, 7 * day, network = elsewhere) + assertTrue(plan.entries.size > 20) + assertTrue(plan.entries.none { it.seriesId in (1..10).map { n -> "f$n" } }) + assertTrue(plan.entries.any { "on another channel this week" in it.why }) + plan.entries.zipWithNext().forEach { (a, b) -> assertEquals(a.endMs, b.startMs) } + } + + @Test fun aChannelNeverGoesWithoutBecauseOfIt() { + // Every film the channel has is on elsewhere: it plays them anyway, with no gap, and says why. + val elsewhere = restingElsewhere(filmAiringsOf(otherChannel(*(1..10).map { "Film $it" }.toTypedArray()))) + val plan = extendFilmSchedule(films(1..10), ScheduleCursor(), start, start + day, 7 * day, network = elsewhere) + assertTrue(plan.endMs >= start + day) + assertTrue(plan.entries.first().why.contains("every rested film is on another channel this week")) + plan.entries.zipWithNext().forEach { (a, b) -> assertEquals(a.endMs, b.startMs) } + } + + @Test fun withNothingElsewhereThePlanIsExactlyAsBefore() { + val pool = films(1..60) + val before = extendFilmSchedule(pool, ScheduleCursor(), start, start + 7 * day, 7 * day) + val after = extendFilmSchedule(pool, ScheduleCursor(), start, start + 7 * day, 7 * day, network = restingElsewhere(emptyList())) + val unrelated = extendFilmSchedule(pool, ScheduleCursor(), start, start + 7 * day, 7 * day, network = restingElsewhere(filmAiringsOf(otherChannel("Something Else")))) + assertEquals(before.entries.map { it.seriesId }, after.entries.map { it.seriesId }) + assertEquals(before.entries.map { it.seriesId }, unrelated.entries.map { it.seriesId }) + } + + @Test fun joeBobsEpisodeCountsAsTheFilmItPresents() { + val joeBob = ChannelPlan(listOf(entry("$LAST_DRIVE_IN / S1 E2 / Sleepaway Camp", "Episode", start, 120)), ScheduleCursor()) + val airings = filmAiringsOf(joeBob) + assertEquals(listOf("sleepaway camp"), airings.map { it.key }) + val elsewhere = restingElsewhere(airings) + assertTrue(elsewhere(film(1, "Sleepaway Camp (1983)"), start + 5 * day)) + assertFalse(elsewhere(film(2, "Sleepaway Camp 2"), start + day)) + // Any other series' episode is not a film showing. + assertTrue(filmAiringsOf(ChannelPlan(listOf(entry("Phoenix Nights / S1 E1 / Pilot", "Episode", start)), ScheduleCursor())).isEmpty()) + } + + @Test fun theRestRunsBothWaysForFiveDays() { + val elsewhere = restingElsewhere(filmAiringsOf(otherChannel("Army of Darkness", at = start))) + val army = film(1, "Army of Darkness") + assertTrue(elsewhere(army, start - 4 * day)) + assertTrue(elsewhere(army, start + 4 * day)) + assertFalse(elsewhere(army, start - 6 * day)) + assertFalse(elsewhere(army, start + 6 * day)) + } + + @Test fun channelsSharingAPoolStopShowingTheSameFilms() { + // Three film channels with the same 45 films, each planning a day after the one before it. + val pool = films(1..45) + fun showing(plans: List) = plans.flatMapIndexed { i, p -> p.entries.map { it.seriesId to i } }.groupBy({ it.first }, { it.second }).values.count { it.toSet().size >= 2 } + val rested = mutableListOf() + repeat(3) { rested += extendFilmSchedule(pool, ScheduleCursor(), start + it * hour, start + day, 7 * day, network = restingElsewhere(rested.flatMap(::filmAiringsOf))) } + val plain = (0 until 3).map { extendFilmSchedule(pool, ScheduleCursor(), start + it * hour, start + day, 7 * day) } + assertTrue(showing(plain) > 0) + assertEquals(0, showing(rested)) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/SeriesGapsTest.kt b/android/app/src/test/java/tv/orbit/classic/SeriesGapsTest.kt new file mode 100644 index 00000000..d9e145bc --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/SeriesGapsTest.kt @@ -0,0 +1,34 @@ +package tv.orbit.classic + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Missing instalments explained (23 November 2026: Phoenix Nights has 4 playable episodes of 12, so it seemed to jump back). */ +class SeriesGapsTest { + private fun show(title: String, vararg marks: Pair) = + PoolSeries(title, title, marks.map { (s, e) -> PoolEpisode("$title-$s-$e", "x", EpisodeMark(s, e), "Ep", 30 * 60_000L) }) + private val three = ChannelProgramming(103, "Orbit Three", emptyList()) + + @Test fun theNumbersMissingBetweenWhatsPlayableAreListed() { + val phoenix = show("Phoenix Nights", 1 to 3, 1 to 5, 2 to 2, 2 to 5) + assertEquals(listOf(EpisodeMark(1, 1), EpisodeMark(1, 2), EpisodeMark(1, 4), EpisodeMark(2, 1), EpisodeMark(2, 3), EpisodeMark(2, 4)), missingEpisodes(phoenix)) + val gap = seriesGaps(listOf(three to listOf(phoenix))).single() + assertEquals(4, gap.playable) + assertTrue(gap.line.startsWith("4 playable; missing S1 E1, S1 E2, S1 E4, S2 E1, S2 E3, S2 E4.")) + } + + @Test fun aWholeShowOrOneMissingEpisodeIsntFlaggedAndFilmsArentSeries() { + val whole = show("Whole", *(1..6).map { 1 to it }.toTypedArray()) + val oneShort = show("One Short", *(1..12).filter { it != 7 }.map { 1 to it }.toTypedArray()) + val film = PoolSeries("f1", "A Film", listOf(PoolEpisode("f1", "x", EpisodeMark(1, 9), "A Film", 90 * 60_000L))) + assertTrue(seriesGaps(listOf(three to listOf(whole, oneShort, film))).isEmpty()) + } + + @Test fun theWorstGapsComeFirstAndTheListIsShort() { + val shows = (1..20).map { n -> show("Show $n", 1 to n + 2) } + show("Nearly Empty", 1 to 40) + val gaps = seriesGaps(listOf(three to shows)) + assertEquals(8, gaps.size) + assertEquals("Nearly Empty", gaps.first().title) + } +}