From 569c7549d5179948f1992af0baa76ea0333f6cd5 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Thu, 5 Nov 2026 17:56:01 +0000 Subject: [PATCH] Drive-In event ideas, phase 1: read-only proposals in the Director's Chair Approved by Paul on 5 November 2026: Drive-In only, at most two a week across it, none when nothing is worthwhile, nothing booked. Seeds come from franchise collections, event studios (Amicus, Toho, Cannon, Full Moon, AIP, Ealing, Aardman...), and directors and leading performers with three or more read films; a seed touching an existing event's films is left out. A bill needs a coherent theme: one shared genre, one audience (adult horror late, family on a Saturday, the rest a Friday double), the best films (in story order for a franchise) clearing a 6.4 average rating. Low-budget cult films stay eligible for The Late Show. On the box, once a day: missing evidence read for candidates (bounded), the strongest bills verified film by film (item, IMDb ID, playable copy), films booked within four weeks or shown on the Drive-In in the last four left out, evenings free of events, committed bookings and competing headlines. Every idea shown is kept as history; dismissed themes stay dismissed unless their films change. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../java/tv/orbit/classic/CatalogueStore.kt | 15 ++ .../java/tv/orbit/classic/ChannelScheduler.kt | 61 ++++++ .../java/tv/orbit/classic/DirectorChair.kt | 60 +++++- .../java/tv/orbit/classic/DirectorScoring.kt | 4 +- .../tv/orbit/classic/EmbyConnectionScreen.kt | 4 +- .../main/java/tv/orbit/classic/EventIdeas.kt | 173 ++++++++++++++++++ .../java/tv/orbit/classic/ScheduleStore.kt | 3 + .../java/tv/orbit/classic/EventIdeasTest.kt | 72 ++++++++ 8 files changed, 384 insertions(+), 8 deletions(-) create mode 100644 android/app/src/main/java/tv/orbit/classic/EventIdeas.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/EventIdeasTest.kt 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 1974f5fb..d894a14b 100644 --- a/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt @@ -76,6 +76,21 @@ internal class CatalogueStore private constructor(context: Context) : CatalogueS row.getString(5).take(10), if (row.isNull(6)) null else row.getLong(6), workKey(ids, row.getString(1), year)) }.toList() } + /** Drive-In event ideas: films by these library ids, with what the catalogue knows of them. */ + @Synchronized fun ideaFilms(ids: Collection): List = ids.distinct().chunked(400).flatMap { chunk -> + readableDatabase.rawQuery("SELECT id, title, year, rating, genres, studios, provider_ids, runtime_ms FROM items WHERE type = 'Movie' AND id IN (${chunk.joinToString(",") { "?" }})", chunk.toTypedArray()).use { c -> + generateSequence { if (c.moveToNext()) c else null }.map { row -> + val imdb = runCatching { JSONObject(row.getString(6)).optString("Imdb").ifBlank { JSONObject(row.getString(6)).optString("IMDB") } }.getOrDefault("").ifBlank { null } + IdeaFilm(row.getString(0), row.getString(1), if (row.isNull(2)) null else row.getInt(2), imdb?.lowercase(), if (row.isNull(7)) null else row.getLong(7), row.getString(3), + row.getString(4).split('|').filter { it.isNotEmpty() }.toSet(), row.getString(5).split('|').filter { it.isNotEmpty() }) + }.toList() + } + } + /** Drive-In event ideas: the films whose studios include [studio] (a plain name, matched as a substring). */ + @Synchronized fun filmsByStudio(studio: String, limit: Int = 400): List = + readableDatabase.rawQuery("SELECT id FROM items WHERE type = 'Movie' AND studios LIKE ? LIMIT $limit", arrayOf("%$studio%")).use { c -> + generateSequence { if (c.moveToNext()) c.getString(0) else null }.toList() + } /** Stage C: the work each of these library ids is, for telling which works a channel already holds. */ @Synchronized fun worksOf(ids: Collection): Map = ids.chunked(400).flatMap { chunk -> readableDatabase.rawQuery("SELECT id, title, year, provider_ids FROM items WHERE id IN (${chunk.joinToString(",") { "?" }})", chunk.toTypedArray()).use { c -> 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 af664b03..82fa603f 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -1,6 +1,8 @@ package tv.orbit.classic import android.util.Log +import org.json.JSONArray +import org.json.JSONObject internal const val POOL_REFRESH_MS = 7 * 24 * 60 * 60_000L @@ -109,6 +111,65 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl Log.i("OrbitSchedule", "collections read=$sets total=$total kept=${done + sets}") } + /** + * Drive-In event ideas, phase 1 (read only; approved by Paul on 5 November 2026), worked out at most once a day: seeds from + * the library, the candidates' evidence read where it's missing (a bounded, read-only read), bills judged, the strongest + * verified on the box film by film (item, IMDb ID, a playable copy), given free evenings, and kept with their history. + * Books nothing and changes no schedule. + */ + fun eventIdeas(session: EmbySampleSession, userId: String, catalogue: CatalogueStore, now: Long = clock()) { + val zone = java.time.ZoneId.systemDefault() + val today = java.time.Instant.ofEpochMilli(now).atZone(zone).toLocalDate() + val file = store.eventIdeasFile(); val historyFile = store.eventIdeaHistoryFile() + if (runCatching { JSONObject(file.readText()).optString("day") }.getOrNull() == today.toString()) return + val weekStart = today.with(java.time.DayOfWeek.MONDAY).atStartOfDay(zone).toInstant().toEpochMilli() + val shownThisWeek = EventIdeaHistory.load(historyFile).count { it.optLong("shownMs") >= weekStart } + val evidenceFile = store.evidenceFile() + val lines = if (evidenceFile.exists()) evidenceFile.readLines().mapNotNull { runCatching { JSONObject(it) }.getOrNull() }.filter { it.optString("type") == "Movie" }.associateBy { it.optString("id") }.toMutableMap() else mutableMapOf() + fun enrich(f: IdeaFilm): IdeaFilm = lines[f.id]?.let { e -> + fun names(key: String) = e.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty() + IdeaFilm(f.id, f.title, f.year, f.imdb, f.runtimeMs, f.rating, f.genres, f.studios, names("directors"), names("leads"), if (e.isNull("community")) null else e.optDouble("community").takeIf { !it.isNaN() }) + } ?: f + val collections = if (store.collectionsFile().exists()) store.collectionsFile().readLines().mapNotNull { runCatching { JSONObject(it) }.getOrNull() }.map { o -> + o.optString("name") to o.optJSONArray("members")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty() } else emptyList() + val studios = EventStudios.associateWith { catalogue.filmsByStudio(it.first) } + val read = catalogue.ideaFilms(lines.keys).map(::enrich) + val held = seasonalFilms().map { it.first.itemId } + ApprovedDebuts.map { it.film.itemId } + val eventFilms = DriveInEvents.flatMap { e -> e.films.map { it.itemId } }.toSet() + held + val seeds = ideaSeeds(collections, studios, read, eventFilms) + var films = catalogue.ideaFilms(seeds.flatMap { it.members }).associateBy { it.id }.mapValues { enrich(it.value) } + // Evidence for the candidates that have none yet, read only and bounded: a theme can't be judged without its ratings. + val missing = films.values.filter { it.id !in lines && ideaSuitable(it) == null }.map { it.id }.take(EVENT_IDEA_READS_PER_DAY) + var readNow = 0 + for (batch in missing.chunked(EVIDENCE_BATCH)) { + val got = try { session.readEvidence(batch) } catch (failure: EmbyCheckException) { break } + evidenceFile.appendText(got.joinToString("") { it.toString() + "\n" }); got.forEach { lines[it.optString("id")] = it }; readNow += got.size + } + films = films.mapValues { enrich(it.value) } + // Unavailable: booked anywhere in the next four weeks, or shown on the Drive-In in the last four. + val window = 28 * 24 * 60 * 60_000L + val busy = (SmartChannels.map { it.number } + DRIVE_IN_NUMBER).flatMap { n -> store.loadPlan(userId, n)?.entries.orEmpty() + .filter { it.startMs in now - (if (n == DRIVE_IN_NUMBER) window else 0L)..now + window }.map { it.seriesId } }.toSet() + val unavailable = { f: IdeaFilm -> if (f.id in busy) "booked or recently shown on Orbit" else if (f.id in held) "held for a seasonal event or premiere" else null } + val drivePlanEnd = store.loadPlan(userId, DRIVE_IN_NUMBER)?.endMs ?: now + // The strongest bills, verified on the box before any is shown. + val bills = seeds.mapNotNull { billFor(it, films, unavailable).first }.sortedByDescending { it.score }.take(12) + val checks = try { session.readFilmChecks(bills.flatMap { b -> b.films.map { EventFilm(it.title, it.year ?: 0, it.imdb.orEmpty(), it.id) to null } }) } catch (failure: EmbyCheckException) { emptyMap() } + val verified = bills.filter { b -> b.films.all { checks[it.id]?.film != null } } + val verifiedSeeds = seeds.filter { s -> verified.any { it.key.startsWith(s.key + "|") } } + val ideas = weeklyEventIdeas(verifiedSeeds, films, unavailable, { format, taken -> ideaEvening(format, today.plusDays(1), drivePlanEnd, taken, format.films * 2 * 60 * 60_000L, zone) }, + EventIdeaHistory.dismissed(historyFile), limit = (EVENT_IDEAS_PER_WEEK - shownThisWeek).coerceAtLeast(0)) + EventIdeaHistory.record(historyFile, ideas, now) + val thisWeek = EventIdeaHistory.load(historyFile).filter { it.optLong("shownMs") >= weekStart } + runCatching { file.writeText(JSONObject().put("day", today.toString()).put("ideas", JSONArray(thisWeek.map { h -> + val ids = h.getJSONArray("films").let { a -> (0 until a.length()).map { a.getString(it) } } + JSONObject(h.toString()).put("details", JSONArray(ids.mapNotNull { films[it] ?: read.firstOrNull { r -> r.id == it } }.map { f -> + JSONObject().put("title", f.title).put("year", f.year ?: JSONObject.NULL).put("community", f.community ?: JSONObject.NULL).put("rating", f.rating) })) + })).toString()) } + Log.i("OrbitSchedule", "event ideas seeds=${seeds.size} bills=${bills.size} verified=${verified.size} proposed=${ideas.size} thisWeek=${thisWeek.size} evidenceRead=$readNow " + + checks.values.groupingBy { it.reason }.eachCount().entries.joinToString(" ") { "${it.key.replace(' ', '_')}=${it.value}" }) + } + fun topUpDriveIn(userId: String, session: EmbySampleSession? = null): ChannelPlan? { val now = clock() val existing = store.loadPlan(userId, DRIVE_IN_NUMBER) 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 6b1290da..6b97b1b8 100644 --- a/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt +++ b/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt @@ -52,6 +52,30 @@ internal class DeskPick(val title: String, val channel: String, val tag: String, internal class DeskAsk(val title: String, val first: String, val second: String, val id: String = "", val type: String = "", val year: Int? = null, val options: List = emptyList(), val line: String = "", val firstRun: DeskOption? = null) +/** A Drive-In event idea as the Chair shows it (phase 1, read only): the occasion, its evening, its films and why. */ +internal class DeskEventIdea(val theme: String, val format: String, val evening: String, val films: List, val reasons: List) { + fun toJson(): JSONObject = JSONObject().put("t", theme).put("f", format).put("e", evening).put("m", JSONArray(films)).put("r", JSONArray(reasons)) + companion object { + fun of(o: JSONObject): DeskEventIdea { + fun strings(key: String) = o.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty() + return DeskEventIdea(o.optString("t"), o.optString("f"), o.optString("e"), strings("m"), strings("r")) + } + /** From the ideas file the box keeps: this week's ideas, with each film's year and viewer rating. */ + fun fromFile(file: File): List = runCatching { + val ideas = JSONObject(file.readText()).getJSONArray("ideas") + (0 until ideas.length()).map { ideas.getJSONObject(it) }.map { o -> + val details = o.optJSONArray("details")?.let { a -> (0 until a.length()).map { a.getJSONObject(it) } }.orEmpty() + val evening = o.optString("evening").takeIf { it.isNotEmpty() && it != "null" }?.let { java.time.LocalDateTime.parse(it) } + DeskEventIdea(o.optString("theme"), IdeaFormat.valueOf(o.optString("format")).label, + evening?.let { "%s %d %s, %02d:%02d".format(it.dayOfWeek.getDisplayName(java.time.format.TextStyle.FULL, java.util.Locale.UK), it.dayOfMonth, + it.month.getDisplayName(java.time.format.TextStyle.FULL, java.util.Locale.UK), it.hour, it.minute) } ?: "no free evening yet", + details.map { d -> d.optString("title") + (if (d.isNull("year")) "" else " (${d.optInt("year")})") + (if (d.isNull("community")) "" else ", rated %.1f".format(d.optDouble("community"))) }, + o.optJSONArray("reasons")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty()) + } + }.getOrDefault(emptyList()) + } +} + /** A lesson as the Chair shows it: proposed until you confirm or dismiss it. */ internal class DeskLesson(val key: String, val text: String, val state: String) @@ -86,14 +110,16 @@ internal class DeskReport(val newlyReleased: Int, val newToLibrary: Int, val sca /** Premiere debuts you've approved, waiting for the booking workflow. */ val premiereApproved: List = emptyList(), /** What the Chair has learned from your decisions, in plain words, and whether it's allowed to use it. */ - val learnedSummary: String = "", val lessons: List = emptyList(), val learningOn: Boolean = false) { + val learnedSummary: String = "", val lessons: List = emptyList(), val learningOn: Boolean = false, + /** This week's Drive-In event ideas (phase 1, read only), at most two. */ + val eventIdeas: List = emptyList()) { fun toJson(): JSONObject = JSONObject().put("newlyReleased", newlyReleased).put("newToLibrary", newToLibrary).put("scanned", scanned).put("unread", unread) .put("strong", strong).put("strongByChannel", JSONArray(strongByChannel.map { JSONObject().put("c", it.first).put("n", it.second) })) .put("picks", JSONArray(picks.map { JSONObject().put("t", it.title).put("c", it.channel).put("g", it.tag).put("l", it.line).item(it.id, it.type, it.year, it.options, it.firstRun) })) .put("asks", JSONArray(asks.map { JSONObject().put("t", it.title).put("a", it.first).put("b", it.second).put("l", it.line).item(it.id, it.type, it.year, it.options, it.firstRun) })) .put("collections", collections).put("franchises", franchises).put("catalogueComplete", catalogueComplete).put("computedMs", computedMs).put("tookMs", tookMs) .put("decided", decided).put("premieres", JSONArray(premieres.map { it.toJson() })).put("premiereQueued", premiereQueued).put("premiereApproved", JSONArray(premiereApproved)) - .put("learnedSummary", learnedSummary).put("lessons", JSONArray(lessons.map { JSONObject().put("k", it.key).put("t", it.text).put("s", it.state) })).put("learningOn", learningOn) + .put("eventIdeas", JSONArray(eventIdeas.map { it.toJson() })).put("learnedSummary", learnedSummary).put("lessons", JSONArray(lessons.map { JSONObject().put("k", it.key).put("t", it.text).put("s", it.state) })).put("learningOn", learningOn) companion object { fun of(o: JSONObject): DeskReport { fun list(key: String) = o.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.getJSONObject(it) } }.orEmpty() @@ -104,7 +130,8 @@ internal class DeskReport(val newlyReleased: Int, val newToLibrary: Int, val sca o.optInt("collections"), o.optBoolean("catalogueComplete"), o.optInt("franchises"), o.optLong("computedMs"), o.optLong("tookMs"), o.optInt("decided"), list("premieres").map(DeskPremiere::of), o.optInt("premiereQueued"), o.optJSONArray("premiereApproved")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty(), - o.optString("learnedSummary"), list("lessons").map { DeskLesson(it.optString("k"), it.optString("t"), it.optString("s")) }, o.optBoolean("learningOn")) + o.optString("learnedSummary"), list("lessons").map { DeskLesson(it.optString("k"), it.optString("t"), it.optString("s")) }, o.optBoolean("learningOn"), + list("eventIdeas").map(DeskEventIdea::of)) } } } @@ -286,7 +313,7 @@ private val DirectorLock = Any() internal fun directorReports(store: ScheduleStore, catalogue: CatalogueStore, userId: String, nowMs: Long = System.currentTimeMillis()): Map? = synchronized(DirectorLock) { val evidence = store.evidenceFile(); val collections = store.collectionsFile(); val cache = store.directorFile(); val decisions = store.decisionsFile() val key = listOf(evidence.lastModified(), collections.lastModified(), store.poolsStamp(), catalogue.summary().total ?: 0L, decisions.lastModified(), - store.learningFile().lastModified()).joinToString(":") + store.learningFile().lastModified(), store.eventIdeasFile().lastModified()).joinToString(":") runCatching { JSONObject(cache.readText()) }.getOrNull()?.takeIf { it.optString("key") == key && nowMs - it.optLong("savedMs") < 24 * 60 * 60_000L }?.let { saved -> val reports = saved.optJSONObject("reports") if (reports != null) return@synchronized DirectorMode.values().associateWith { DeskReport.of(reports.getJSONObject(it.name)) } @@ -297,9 +324,11 @@ internal fun directorReports(store: ScheduleStore, catalogue: CatalogueStore, us val carriedWorks = catalogue.worksOf(ids.values.flatten()).values.toSet() val (arrivals, _) = store.loadArrivals(userId) val newToLibrary = arrivals.count { nowMs - it.firstSeenMs < NEW_TO_LIBRARY_DAYS * 24 * 60 * 60_000L } - val reports = buildDeskReports(evidence, collections, ids, released, carriedWorks, catalogue.originalTitles(released.map { it.id }), newToLibrary, catalogue.complete(), nowMs, + val reports0 = buildDeskReports(evidence, collections, ids, released, carriedWorks, catalogue.originalTitles(released.map { it.id }), newToLibrary, catalogue.complete(), nowMs, decided = loadDecisions(decisions).map { it.id }.toSet(), premiere = premiereInputs(store, catalogue, userId, nowMs), history = loadDecisions(decisions), learning = ChairLearning.load(store.learningFile())) + val ideas = DeskEventIdea.fromFile(store.eventIdeasFile()) + val reports = reports0.mapValues { (_, r) -> DeskReport.of(r.toJson().put("eventIdeas", JSONArray(ideas.map { it.toJson() }))) } runCatching { cache.writeText(JSONObject().put("key", key).put("savedMs", nowMs).put("reports", JSONObject().apply { reports.forEach { (m, r) -> put(m.name, r.toJson()) } }).toString()) } val b = reports.getValue(DirectorMode.Balanced) android.util.Log.i("OrbitSchedule", "director newlyReleased=${b.newlyReleased} read=${b.scanned} strong=${b.strong} asks=${b.asks.size} collections=${b.collections} tookMs=${b.tookMs}") @@ -369,6 +398,7 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ var open by remember { mutableStateOf(null) } var said by remember { mutableStateOf(null) } var lesson by remember { mutableStateOf(null) } + var eventOpen by remember { mutableStateOf(null) } val scope = rememberCoroutineScope() LaunchedEffect(mode, version) { withContext(Dispatchers.Default) { runCatching { load(mode) }.getOrNull() }?.let { report = it } } Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) { @@ -420,6 +450,10 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ onClick = { open = ChairChoice(p.title, p.id, "Movie", p.year, "ORBIT PREMIERE", (p.reasons + p.cautions.map { "but $it" }).joinToString("; "), listOfNotNull(p.home), false, DeskOption(PREMIERE_NUMBER, "Orbit Premiere", p.after + if (p.remainsOnPremiere) ", and stays eligible for Premiere" else "")) }) } + // Drive-In event ideas (phase 1, read only): at most two a week, none when nothing is worthwhile. + r.eventIdeas.forEach { idea -> + ChairCard("DRIVE-IN EVENT IDEA", idea.theme, idea.format.uppercase(java.util.Locale.UK), idea.evening, onClick = { eventOpen = idea }) + } if (r.premiereApproved.isNotEmpty()) Text("Approved for Premiere, waiting for booking: ${r.premiereApproved.joinToString(", ")}", color = ChairMint, fontSize = 10.sp) if (r.premiereQueued > 0) Text("${r.premiereQueued} recent major films still being read for Premiere", color = Muted, fontSize = 10.sp) val picks = r.picks.filter { it.id !in decided } @@ -449,6 +483,22 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ Text(said ?: "Press a title to place it or drop it. A placed title joins that channel's list at its next top-up; nothing already booked changes. Worked out in ${r.tookMs} ms.", color = if (said != null) ChairMint else Muted, fontSize = 10.sp) } + eventOpen?.let { idea -> + androidx.compose.ui.window.Dialog(onDismissRequest = { eventOpen = null }, properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false)) { + val first = remember { FocusRequester() } + LaunchedEffect(Unit) { runCatching { first.requestFocus() } } + Column(Modifier.width(600.dp).background(ChairNavy, RoundedCornerShape(10.dp)).border(2.dp, ChairGold, RoundedCornerShape(10.dp)).padding(20.dp), verticalArrangement = Arrangement.spacedBy(7.dp)) { + Text("DRIVE-IN EVENT IDEA", color = ChairGold, fontSize = 11.sp, fontWeight = FontWeight.SemiBold) + Text(idea.theme.uppercase(java.util.Locale.UK), color = Color.White, fontFamily = Anton, fontSize = 26.sp, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text("${idea.format} · ${idea.evening}", color = ChairSky, fontSize = 13.sp) + idea.films.forEachIndexed { i, f -> Text("${i + 1}. $f", color = Color.White, fontSize = 13.sp) } + idea.reasons.forEach { Text("· $it", color = Muted, fontSize = 11.sp) } + Text("Checked on the box: every film is the right library item with a copy this box can play, rested, not booked elsewhere around the evening, and nothing competes for the night. Read only for now: nothing is booked.", + color = Muted, fontSize = 10.sp) + OrbitButton("Close", Modifier.focusRequester(first), onClick = { eventOpen = null }) + } + } + } lesson?.let { l -> androidx.compose.ui.window.Dialog(onDismissRequest = { lesson = null }, properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false)) { val first = remember { FocusRequester() } diff --git a/android/app/src/main/java/tv/orbit/classic/DirectorScoring.kt b/android/app/src/main/java/tv/orbit/classic/DirectorScoring.kt index 5a69d318..9141813d 100644 --- a/android/app/src/main/java/tv/orbit/classic/DirectorScoring.kt +++ b/android/app/src/main/java/tv/orbit/classic/DirectorScoring.kt @@ -82,8 +82,8 @@ internal val Briefs: List = listOf( Brief(614, "Tots", setOf("Series"), setOf("Children", "Animation", "Family"), setOf("Children", "Kids"), w("preschool", "little", "learn", "friends", "gentle", "toddler", "young children"), w("adult", "violence", "fight", "battle"), 1980 to 2026, kids = true)) -private val KidsOk = setOf("G", "PG", "TV-Y", "TV-Y7", "TV-G", "TV-PG", "U", "TV-Y7-FV", "E", "0+", "3+", "6+", "7+") -private val Adult = setOf("R", "TV-MA", "NC-17", "18", "18+", "X", "NR18", "SG-R21", "SG-M18", "GB-18") +internal val KidsOk = setOf("G", "PG", "TV-Y", "TV-Y7", "TV-G", "TV-PG", "U", "TV-Y7-FV", "E", "0+", "3+", "6+", "7+") +internal val Adult = setOf("R", "TV-MA", "NC-17", "18", "18+", "X", "NR18", "SG-R21", "SG-M18", "GB-18") internal val GenreSynonyms = mapOf("Anime" to "Animation", "Martial Arts" to "Action", "Sci-Fi & Fantasy" to "Science Fiction", "Action & Adventure" to "Action", "Kids" to "Children", "Suspense" to "Thriller", "Sports" to "Sport") private val Uk = Regex("United Kingdom|England|Scotland|Wales|\\bUK\\b") 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 2309297f..b5f7a8d6 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -271,7 +271,9 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { /* Tried again next hour. */ } // Stage C's light daily library refresh, in the background. A failure changes nothing and is tried next hour. - try { withContext(Dispatchers.IO) { scheduler.readEvidence(active, active.accountId, catalogue); directorReports(scheduleStore, catalogue, active.accountId) } } + try { withContext(Dispatchers.IO) { scheduler.readEvidence(active, active.accountId, catalogue) + runCatching { scheduler.eventIdeas(active, active.accountId, catalogue) }.onFailure { android.util.Log.w("OrbitSchedule", "event ideas failed=${it.javaClass.simpleName}") } + directorReports(scheduleStore, catalogue, active.accountId) } } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Exception) { android.util.Log.w("OrbitSchedule", "evidence failed=${failure.javaClass.simpleName}") } try { withContext(Dispatchers.IO) { scheduler.refreshArrivals(active, active.accountId, catalogue) } } diff --git a/android/app/src/main/java/tv/orbit/classic/EventIdeas.kt b/android/app/src/main/java/tv/orbit/classic/EventIdeas.kt new file mode 100644 index 00000000..b7895d35 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/EventIdeas.kt @@ -0,0 +1,173 @@ +package tv.orbit.classic + +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneId + +/** + * Orbit-generated Drive-In events, phase 1 (approved by Paul on 5 November 2026): read only. The Director's Chair proposes at + * most [EVENT_IDEAS_PER_WEEK] events a week across the whole Drive-In, and none when nothing is genuinely worthwhile. The aim is + * a television occasion, not films grouped by a shared tag: a franchise, a director, a performer or a studio only suggests an + * idea; every bill needs a coherent theme (one shared genre across its films, an audience, an evening that suits it). + * Cult, independent and low-budget films are welcome at The Late Show; family franchises get a family evening; adult horror + * stays late. Each film must be the verified library item with a playable copy ([checkEventFilm], on the box), suit its slot, + * be rested and not booked elsewhere around the evening, and the evening must be free of committed bookings and of any + * competing headline event ([competingEvent]). Nothing here books or changes a schedule. Proposals, and later your + * approvals, deferrals and dismissals, are kept as history for explainable learning; a dismissed theme isn't proposed again + * unless its films change. + */ +internal const val EVENT_IDEAS_PER_WEEK = 2 +/** An idea needs this average viewer rating across the films that have one, to be worth an evening. */ +internal const val EVENT_IDEA_BAR = 6.4 +/** How many candidate films' evidence the idea step may read in a day, read only. */ +internal const val EVENT_IDEA_READS_PER_DAY = 400 + +internal enum class IdeaFormat(val label: String, val hour: Int, val films: Int, val days: Set) { + SaturdayTriple("Saturday triple bill", 19, 3, setOf(DayOfWeek.SATURDAY)), + FridayDouble("Friday double bill", 20, 2, setOf(DayOfWeek.FRIDAY)), + LateShow("The Late Show double", 23, 2, setOf(DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY)) +} + +/** A film an idea can use, from the catalogue and (where read) its evidence. */ +internal class IdeaFilm(val id: String, val title: String, val year: Int?, val imdb: String?, val runtimeMs: Long?, val rating: String, val genres: Set, + val studios: List, val directors: List = emptyList(), val leads: List = emptyList(), val community: Double? = null) + +internal class EventIdea(val key: String, val theme: String, val source: String, val format: IdeaFormat, val evening: LocalDateTime?, val films: List, + val reasons: List, val score: Double) { + /** The same idea with the same films: what a dismissal is remembered by. */ + val signature get() = key + ":" + films.map { it.id }.sorted().joinToString(",") +} + +/** Studios and movements that make a Drive-In occasion: (studio name as the library writes it, theme, the genre its bill shares). */ +internal val EventStudios: List> = listOf( + Triple("Amicus Productions", "Amicus Portmanteau Night", "Horror"), + Triple("Toho", "Toho Monster Night", "Science Fiction"), + Triple("Cannon Group", "Cannon Action Night", "Action"), + Triple("Full Moon Features", "Full Moon After Midnight", "Horror"), + Triple("Empire Pictures", "Empire Pictures Creature Feature", "Horror"), + Triple("American International Pictures", "AIP Drive-In Classics", "Horror"), + Triple("New World Pictures", "New World Midnight Movies", "Horror"), + Triple("Ealing Studios", "Ealing Comedy Night", "Comedy"), + Triple("Tigon British Film Productions", "Tigon British Terror", "Horror"), + Triple("Aardman", "Aardman Family Saturday", "Animation"), + Triple("Laika", "Laika Family Saturday", "Animation"), + Triple("Carolco Pictures", "Carolco Blockbuster Night", "Action"), + Triple("Orion Pictures", "Orion Eighties Night", "Action")) + +/** A theme's candidate films, from where it came: (key, theme name, source, members). */ +internal class IdeaSeed(val key: String, val theme: String, val source: String, val members: List, val sharedGenre: String? = null, val chronological: Boolean = false) + +/** + * The seeds a theme can come from: franchise collections, the studios above, and directors and leading performers with three or + * more films whose evidence has been read. A seed that touches an existing Drive-In event's films is left out: that occasion + * has been had. Curated lists are never seeds. + */ +internal fun ideaSeeds(collections: List>>, studios: Map, List>, read: List, eventFilms: Set): List { + val seeds = mutableListOf() + collections.filter { (name, members) -> FranchiseCollection.containsMatchIn(name) && members.size >= 2 }.forEach { (name, members) -> + seeds += IdeaSeed("franchise:$name", name.removeSuffix(" Collection").trim() + " Night", "franchise", members, chronological = true) + } + studios.forEach { (studio, members) -> seeds += IdeaSeed("studio:${studio.first}", studio.second, "studio", members, sharedGenre = studio.third) } + read.flatMap { f -> f.directors.take(2).map { it to f.id } }.groupBy({ it.first }, { it.second }).filterValues { it.size >= 3 }.forEach { (who, ids) -> + seeds += IdeaSeed("director:$who", "A $who Night", "director", ids) + } + read.mapNotNull { f -> f.leads.firstOrNull()?.let { it to f.id } }.groupBy({ it.first }, { it.second }).filterValues { it.size >= 3 }.forEach { (who, ids) -> + seeds += IdeaSeed("performer:$who", "$who Night", "performer", ids) + } + return seeds.filter { seed -> seed.members.none { it in eventFilms } } +} + +private fun adult(f: IdeaFilm) = f.rating in Adult || "Horror" in f.genres +private fun family(f: IdeaFilm) = f.rating in KidsOk && ("Family" in f.genres || "Animation" in f.genres) + +/** Whether a film suits the Drive-In at all: a feature film, verified identity, not a documentary, special or TV movie. */ +internal fun ideaSuitable(f: IdeaFilm): String? = when { + f.imdb.isNullOrBlank() -> "no IMDb ID to verify it by" + f.runtimeMs == null || f.runtimeMs < 70 * 60_000L || f.runtimeMs > 200 * 60_000L -> "not a feature length" + "Documentary" in f.genres || "TV Movie" in f.genres -> "a documentary or TV movie" + else -> null +} + +/** + * The bill a seed makes, or why it makes none: its best films (in story order for a franchise) that share one genre and one + * audience, in the format that suits them. Adult horror only ever goes to The Late Show. + */ +internal fun billFor(seed: IdeaSeed, films: Map, unavailable: (IdeaFilm) -> String?): Pair { + val usable = seed.members.mapNotNull { films[it] }.filter { ideaSuitable(it) == null && unavailable(it) == null }.distinctBy { it.imdb } + if (usable.size < 2) return null to "fewer than two usable films" + // One audience per bill: late (adult or horror), family, or the evening in between. + val groups = listOf(IdeaFormat.LateShow to usable.filter(::adult), IdeaFormat.SaturdayTriple to usable.filter(::family), + IdeaFormat.FridayDouble to usable.filter { !adult(it) && !family(it) }) + var best: EventIdea? = null; var why = "no shared genre" + for ((format0, group) in groups) { + val genre = seed.sharedGenre?.takeIf { g -> group.count { g in it.genres } >= 2 } + ?: group.flatMap { it.genres }.filter { it != "Drama" }.groupingBy { it }.eachCount().filterValues { it >= 2 }.maxByOrNull { it.value }?.key ?: continue + val pool = group.filter { genre in it.genres } + val format = if (format0 == IdeaFormat.FridayDouble && pool.size >= 3) IdeaFormat.SaturdayTriple else format0 + val ranked = pool.sortedWith(compareByDescending { it.community ?: 0.0 }.thenBy { it.year ?: 9999 }).take(format.films) + if (ranked.size < 2) continue + val chosen = if (seed.chronological) ranked.sortedBy { it.year ?: 9999 } else ranked + val rated = chosen.mapNotNull { it.community } + if (rated.size * 2 < chosen.size) { why = "too few viewer ratings to judge it"; continue } + val average = rated.average() + if (average < EVENT_IDEA_BAR) { why = "rated %.1f on average, under the bar".format(average); continue } + val score = average + when (seed.source) { "franchise" -> .6; "director" -> .5; "performer" -> .4; else -> .3 } + if (chosen.size == 3) .2 else 0.0 + val idea = EventIdea("${seed.key}|${format.name}", seed.theme, seed.source, format, null, chosen, + listOf("${seed.source}: ${seed.theme}", "every film is $genre", "%.1f average viewer rating".format(average)), score) + if (best == null || idea.score > best.score) best = idea + } + return best to (if (best == null) why else "") +} + +/** + * This week's ideas: the strongest bills over the bar, each given the first free evening of its format, at most [limit] + * (two, less what's already proposed this week), never a theme you've dismissed with the same films. A week with nothing + * worthwhile proposes nothing. + */ +internal fun weeklyEventIdeas(seeds: List, films: Map, unavailable: (IdeaFilm) -> String?, freeEvening: (IdeaFormat, Set) -> LocalDateTime?, + dismissed: Set, limit: Int = EVENT_IDEAS_PER_WEEK): List { + val bills = seeds.mapNotNull { billFor(it, films, unavailable).first }.filter { it.signature !in dismissed }.sortedByDescending { it.score } + val out = mutableListOf(); val taken = mutableSetOf(); val used = mutableSetOf() + for (b in bills) { + if (out.size >= limit) break + if (b.films.any { it.id in used }) continue + val evening = freeEvening(b.format, taken) ?: continue + taken += evening; used += b.films.map { it.id } + out += EventIdea(b.key, b.theme, b.source, b.format, evening, b.films, b.reasons, b.score) + } + return out +} + +/** + * The first evening from [from] for [format]: its weekday, after the Drive-In's committed plan, with no Drive-In event that + * night, nothing competing for its audience, and not already [taken] by another idea. Looks four weeks ahead. + */ +internal fun ideaEvening(format: IdeaFormat, from: LocalDate, planEndMs: Long, taken: Set, filmsMs: Long, zone: ZoneId = ZoneId.systemDefault()): LocalDateTime? { + var day = from + repeat(28) { + if (day.dayOfWeek in format.days && DriveInEvents.none { it.evening == day }) { + val at = day.atTime(format.hour, 0); val ms = at.atZone(zone).toInstant().toEpochMilli() + if (ms > planEndMs && at !in taken && competingEvent(ms, ms + filmsMs, zone) == null) return at + } + day = day.plusDays(1) + } + return null +} + +/** The proposal history: every idea shown, when, and (from phase 2) what you decided. Kept for explainable learning. */ +internal object EventIdeaHistory { + fun load(file: File): List = runCatching { JSONArray(file.readText()).let { a -> (0 until a.length()).map { a.getJSONObject(it) } } }.getOrDefault(emptyList()) + fun dismissed(file: File): Set = load(file).filter { it.optString("decision") == "dismissed" }.map { it.optString("signature") }.toSet() + fun record(file: File, ideas: List, nowMs: Long) = runCatching { + val all = load(file); val known = all.map { it.optString("signature") }.toSet() + val added = ideas.filter { it.signature !in known }.map { i -> + JSONObject().put("signature", i.signature).put("theme", i.theme).put("source", i.source).put("format", i.format.name).put("evening", i.evening?.toString()) + .put("films", JSONArray(i.films.map { it.id })).put("titles", JSONArray(i.films.map { it.title })).put("reasons", JSONArray(i.reasons)).put("shownMs", nowMs).put("decision", "proposed") + } + if (added.isNotEmpty()) file.writeText(JSONArray(all + added).toString()) + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt index b4d61ade..16b16e01 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -60,6 +60,9 @@ internal class ScheduleStore(private val directory: File) { fun premiereRunsFile() = File(directory, "premiere-runs-0.json") /** Your Director's Chair learning switch ([ChairLearning]). */ fun learningFile() = File(directory, "director-learning-0.json") + /** This week's Drive-In event ideas ([EventIdea]), and every idea ever shown with what you decided. */ + fun eventIdeasFile() = File(directory, "event-ideas-0.json") + fun eventIdeaHistoryFile() = File(directory, "event-ideas-history-0.json") /** When the channels' pools last changed, without reading them: their files' times together. */ fun poolsStamp(): Long = directory.listFiles { f -> f.name.startsWith("episodes-") && f.name.endsWith(".json") }?.sumOf { it.lastModified() } ?: 0L diff --git a/android/app/src/test/java/tv/orbit/classic/EventIdeasTest.kt b/android/app/src/test/java/tv/orbit/classic/EventIdeasTest.kt new file mode 100644 index 00000000..888063f1 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/EventIdeasTest.kt @@ -0,0 +1,72 @@ +package tv.orbit.classic + +import org.junit.Assert.* +import org.junit.Test +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.ZoneId + +/** Drive-In event ideas (phase 1): coherent themes, the right evening for the audience, a bar to clear, and no repeats. */ +class EventIdeasTest { + private val london = ZoneId.of("Europe/London") + private fun film(id: String, title: String, genres: Set, rating: String = "R", community: Double? = 7.0, year: Int = 1985, minutes: Long = 95, imdb: String? = "tt$id") = + IdeaFilm(id, title, year, imdb, minutes * 60_000, rating, genres, emptyList(), community = community) + private val none = { _: IdeaFilm -> null as String? } + + @Test fun aFranchiseOfAdultHorrorIsALateShowInStoryOrder() { + val films = listOf(film("1", "Haunt III", setOf("Horror"), year = 1990, community = 6.6), film("2", "Haunt", setOf("Horror"), year = 1979, community = 7.4), + film("3", "Haunt II", setOf("Horror"), year = 1982, community = 6.9)).associateBy { it.id } + val (idea, _) = billFor(IdeaSeed("franchise:Haunt Collection", "Haunt Night", "franchise", films.keys.toList(), chronological = true), films, none) + assertEquals(IdeaFormat.LateShow, idea!!.format) // adult horror stays late + assertEquals(listOf("Haunt", "Haunt II"), idea.films.map { it.title }) // the best two, in story order + assertTrue(idea.reasons.any { "every film is Horror" in it }) + } + + @Test fun aFamilyFranchiseGetsAFamilyEveningAndLowBudgetCultIsWelcomeLate() { + val family = listOf(film("4", "Clay Pals", setOf("Animation", "Family"), "U", 7.6), film("5", "Clay Pals 2", setOf("Animation", "Family"), "U", 7.3), + film("6", "Clay Pals 3", setOf("Animation", "Family"), "PG", 7.1)).associateBy { it.id } + assertEquals(IdeaFormat.SaturdayTriple, billFor(IdeaSeed("studio:Clay", "Clay Saturday", "studio", family.keys.toList(), "Animation"), family, none).first!!.format) + val cult = listOf(film("7", "Puppet Terror", setOf("Horror"), "R", 6.5), film("8", "Puppet Terror 2", setOf("Horror"), "R", 6.6)).associateBy { it.id } + assertNotNull(billFor(IdeaSeed("studio:Full Moon Features", "Full Moon After Midnight", "studio", cult.keys.toList(), "Horror"), cult, none).first) + } + + @Test fun noCoherentThemeOrTooWeakMeansNoBill() { + val mixed = listOf(film("9", "A", setOf("Comedy"), "PG-13"), film("10", "B", setOf("Western"), "PG-13")).associateBy { it.id } + assertNull(billFor(IdeaSeed("director:X", "A X Night", "director", mixed.keys.toList()), mixed, none).first) + val weak = listOf(film("11", "C", setOf("Action"), "PG-13", 5.2), film("12", "D", setOf("Action"), "PG-13", 5.5)).associateBy { it.id } + assertTrue(billFor(IdeaSeed("performer:Y", "Y Night", "performer", weak.keys.toList()), weak, none).second.contains("under the bar")) + val unrated = listOf(film("13", "E", setOf("Action"), "PG-13", null), film("14", "F", setOf("Action"), "PG-13", null)).associateBy { it.id } + assertTrue(billFor(IdeaSeed("performer:Z", "Z Night", "performer", unrated.keys.toList()), unrated, none).second.contains("ratings")) + // Unverifiable or unsuitable films don't count: no IMDb ID, a short, a TV movie. + assertEquals("no IMDb ID to verify it by", ideaSuitable(film("15", "G", setOf("Action"), imdb = null))) + assertEquals("not a feature length", ideaSuitable(film("16", "H", setOf("Action"), minutes = 40))) + } + + @Test fun atMostTwoAWeekNoneWhenNothingIsWorthItAndDismissedThemesStayDismissed() { + val films = (1..12).map { film("$it", "Film $it", setOf("Action"), "PG-13", 7.0 + it / 20.0) }.associateBy { it.id } + val seeds = (0 until 4).map { k -> IdeaSeed("director:D$k", "A D$k Night", "director", (1..12).filter { it % 4 == k }.map { "$it" }) } + var day = LocalDate.of(2026, 12, 1) + val evening = { _: IdeaFormat, taken: Set -> generateSequence(day.atTime(20, 0)) { it.plusDays(1) }.first { it !in taken } } + val week = weeklyEventIdeas(seeds, films, none, evening, emptySet()) + assertEquals(2, week.size); assertNotEquals(week[0].evening, week[1].evening) + assertTrue(weeklyEventIdeas(seeds, films, none, evening, emptySet(), limit = 0).isEmpty()) + val weak = films.mapValues { (_, f) -> IdeaFilm(f.id, f.title, f.year, f.imdb, f.runtimeMs, f.rating, f.genres, f.studios, community = 5.0) } + assertTrue(weeklyEventIdeas(seeds, weak, none, evening, emptySet()).isEmpty()) // no filler + val dismissed = setOf(week[0].signature) + assertTrue(weeklyEventIdeas(seeds, films, none, evening, dismissed).none { it.signature == week[0].signature }) + } + + @Test fun seedsSkipCuratedListsAndThemesAlreadyHad() { + val seeds = ideaSeeds(listOf("Godzilla Collection" to listOf("a", "b"), "IMDB Top 250 Movies" to listOf("a", "b"), "Rambo Collection" to listOf("5642223", "x")), + emptyMap(), emptyList(), DriveInEvents.flatMap { e -> e.films.map { it.itemId } }.toSet()) + assertEquals(listOf("franchise:Godzilla Collection"), seeds.map { it.key }) + } + + @Test fun anEveningSuitsItsFormatAndCompetesWithNothing() { + val late = ideaEvening(IdeaFormat.LateShow, LocalDate.of(2026, 11, 16), 0L, emptySet(), 4 * 3_600_000L, london)!! + assertTrue(late.dayOfWeek in setOf(DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY)); assertEquals(23, late.hour) + assertNotEquals(LocalDate.of(2026, 11, 17), late.toLocalDate()) // Amicus has Tuesday 17 November + val sat = ideaEvening(IdeaFormat.SaturdayTriple, LocalDate.of(2026, 11, 14), 0L, emptySet(), 6 * 3_600_000L, london)!! + assertEquals(LocalDate.of(2026, 11, 21), sat.toLocalDate()) // Universal Monsters has the 14th + } +}