Smart setup for Create a channel: browse the library, and the Director shapes the day

Browse by type, genre, network or studio and age when picking shows. A new
style, Shaped by the Director: daytime, evening and late slots like Orbit's own
channels, with core shows weighted up; the phone shows the layout to change,
and the TV lays it out itself. A week check says when the picks would repeat
within days. Built on genres, networks and ratings, which Emby and Jellyfin
both carry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-07 08:06:54 +00:00
co-authored by Claude Opus 5.5
parent 6a24ae17ea
commit db88faaf77
12 changed files with 275 additions and 26 deletions
@@ -173,6 +173,38 @@ internal class CatalogueStore(context: Context, private val file: File) : Catalo
buildList { while (c.moveToNext()) add(ChairRow(c.getString(0), c.getString(1), c.getString(2), if (c.isNull(3)) null else c.getInt(3), c.getString(4).split('|').filter { it.isNotBlank() }.toSet())) }
}
}
/**
* Browse for Create a channel (Paul, 7 November 2026, after other apps' channel matching): titles by genre, network or
* studio, and age rating, newest first. Read only.
*/
@Synchronized fun browseRows(genre: String?, studio: String?, ratings: Set<String>, type: String?, limit: Int = 60): List<ShapeRow> {
val where = mutableListOf("type IN ('Movie','Series')"); val args = mutableListOf<String>()
if (type != null) { where += "type = ?"; args += type }
if (!genre.isNullOrBlank()) { where += "('|' || genres || '|') LIKE ?"; args += "%|${genre.take(60)}|%" }
if (!studio.isNullOrBlank()) { where += "('|' || studios || '|') LIKE ?"; args += "%|${studio.take(80)}|%" }
if (ratings.isNotEmpty()) { where += "rating IN (${ratings.joinToString(",") { "?" }})"; args += ratings }
return readableDatabase.rawQuery("SELECT id, type, title, year, rating, genres FROM items WHERE ${where.joinToString(" AND ")} ORDER BY year DESC, title LIMIT $limit", args.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())) }
}
}
/** What Smart setup reads of chosen titles: kind, rating, genres and year. Read only. */
@Synchronized fun shapeRows(ids: Collection<String>): List<ShapeRow> = ids.distinct().chunked(400).flatMap { chunk ->
readableDatabase.rawQuery("SELECT id, type, title, year, rating, genres FROM items WHERE id IN (${chunk.joinToString(",") { "?" }})", chunk.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<String>, List<String>>? = null
/** The library's most common genres and networks or studios, for browsing; worked out once. Read only. */
@Synchronized fun facets(): Pair<List<String>, List<String>> = facetCache ?: run {
val genres = HashMap<String, Int>(); val studios = HashMap<String, Int>()
readableDatabase.rawQuery("SELECT genres, studios FROM items WHERE type IN ('Movie','Series')", null).use { c ->
while (c.moveToNext()) {
c.getString(0).split('|').filter { it.isNotBlank() }.forEach { genres.merge(it, 1, Int::plus) }
c.getString(1).split('|').filter { it.isNotBlank() }.forEach { studios.merge(it, 1, Int::plus) }
}
}
(genres.entries.sortedByDescending { it.value }.take(24).map { it.key } to studios.entries.sortedByDescending { it.value }.take(40).map { it.key }).also { facetCache = it }
}
/** The same rows for chosen titles, by item. Read only. */
@Synchronized fun chairRowsById(ids: Collection<String>): List<ChairRow> = ids.distinct().chunked(400).flatMap { chunk ->
readableDatabase.rawQuery("SELECT id, type, title, year, genres FROM items WHERE id IN (${chunk.joinToString(",") { "?" }})", chunk.toTypedArray()).use { c ->
@@ -44,7 +44,11 @@ internal class ChannelMaker(
/** Saves the channel and its shows and switches it on; returns what to tell you. */
val create: suspend (CustomChannel, List<Suggestion>) -> String,
/** A channel's shows as they stand, for editing. */
val showsOf: suspend (Int) -> List<Suggestion> = { emptyList() })
val showsOf: suspend (Int) -> List<Suggestion> = { emptyList() },
/** Smart setup: browse the library, its genres and networks, and how the Director would lay chosen titles out. */
val browse: suspend (genre: String?, studio: String?, ratings: Set<String>, type: String?) -> List<ShapeRow> = { _, _, _, _ -> emptyList() },
val facets: suspend () -> Pair<List<String>, List<String>> = { emptyList<String>() to emptyList() },
val shapeOf: suspend (List<String>) -> List<ShapeRow> = { emptyList() })
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") }
@@ -25,7 +25,9 @@ internal enum class PlayStyle(val title: String, val line: String) {
Shuffled("Shuffled", "Episodes in a mixed order, every one before any repeats"),
/** A timetable: each show at its own hours, every day. */
Blocks("Blocks", "A timetable: each show at its own times, every day"),
Marathon("Marathon", "One show at a time, several episodes back to back")
Marathon("Marathon", "One show at a time, several episodes back to back"),
/** Smart setup ([shapeChannel]): daytime, evening and late slots as the Director laid them out, with core shows more often. */
Shaped("Shaped by the Director", "Daytime, evening and late, like Orbit's own, with your core shows more often")
}
/** When a channel is on: all day, or from one hour to another (wrapping past midnight). */
@@ -36,15 +38,20 @@ internal data class OnHours(val fromHour: Int, val toHour: Int) {
internal data class CustomChannel(val number: Int, val name: String, val style: PlayStyle = PlayStyle.Standard, val hours: OnHours? = null, val description: String = "",
/** 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()) {
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()) {
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()))
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.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())
}
}
@@ -92,11 +99,12 @@ internal object CustomChannels {
*/
internal fun programmingOf(channel: CustomChannel): ChannelProgramming = ChannelProgramming(
channel.number, channel.name, emptyList(), seriesCount = 60,
finishTogether = channel.style == PlayStyle.Standard || channel.style == PlayStyle.Blocks,
finishTogether = channel.style == PlayStyle.Standard || channel.style == PlayStyle.Blocks || channel.style == PlayStyle.Shaped,
exactTitles = true, shuffleEpisodes = channel.style == PlayStyle.Shuffled,
dayParts = if (channel.style == PlayStyle.Blocks) timetableParts(channel.shows) else emptyList(),
storyGrouping = channel.style == PlayStyle.Standard,
shorts = if (channel.style == PlayStyle.Standard) YoursShorts else null,
dayParts = when (channel.style) { PlayStyle.Blocks -> timetableParts(channel.shows); PlayStyle.Shaped -> shapedParts(channel.slots); else -> emptyList() },
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,
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.81\"") +
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.82\"") +
(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.81\"" +
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.82\"" +
(token?.let { ", Token=\"$it\"" } ?: ""))
}
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
@@ -541,7 +541,15 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
chairSuggestions(description, rows, catalogue.chairRowsById(chosen.map { it.id }), skipped) } },
search = { text -> withContext(Dispatchers.IO) { catalogue.chairRows(titleLike = text, limit = 30).map { Suggestion(it.id, it.title, it.year, it.type, "", "In your library") } } },
showsOf = { number -> withContext(Dispatchers.IO) { scheduleStore.loadChoices(active.accountId, number).accepted } },
create = { channel, shows ->
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) } },
create = { asked, shows ->
// Shaped on the TV, or from the phone without a layout: the Director lays it out from the catalogue.
val channel = if (asked.style == PlayStyle.Shaped && asked.slots.isEmpty()) withContext(Dispatchers.IO) {
val rows = catalogue.shapeRows(shows.map { it.id }); val shape = shapeChannel(rows); val titleOf = rows.associate { it.id to it.title }
asked.copy(slots = shape.slots.mapNotNull { (id, slot) -> titleOf[id]?.let { it to slot } }.toMap(), core = shape.core.mapNotNull { titleOf[it] }.toSet())
} else asked
withContext(Dispatchers.IO) {
CustomChannels.upsert(workspace.scheduleDir, channel)
val before = scheduleStore.loadChoices(active.accountId, channel.number)
@@ -305,6 +305,25 @@ internal object PhoneLink {
val d = r.query["d"].orEmpty().take(120)
json(out, 200, JSONArray(runBlocking { h.maker.suggest(d, chosen, skipped).ifEmpty { h.maker.search(d) } }.map(::suggestionJson)))
}
// Smart setup (Paul, 7 November 2026): browse the library and let the Director lay the channel out.
"GET /api/facets" -> {
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" -> {
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" })) }))
}
"POST /api/shape" -> {
val ids = runCatching { JSONObject(r.body).getJSONArray("ids").let { a -> (0 until minOf(a.length(), 200)).map { a.getString(it) }.filter(EmbyClient::validId) } }.getOrNull()
?: return json(out, 400, JSONObject())
val rows = runBlocking { h.maker.shapeOf(ids) }
val shape = shapeChannel(rows)
val series = rows.count { it.type == "Series" }; val films = rows.count { it.type == "Movie" }
json(out, 200, JSONObject().put("slots", JSONObject(shape.slots.mapValues { it.value.name })).put("core", JSONArray(shape.core.toList()))
.put("week", weekCheck(series, films) ?: JSONObject.NULL))
}
"POST /api/channels" -> {
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult to make channels."))
val o = runCatching { JSONObject(r.body) }.getOrNull() ?: return json(out, 400, JSONObject().put("error", "Unreadable"))
@@ -315,7 +334,12 @@ internal object PhoneLink {
o.optJSONObject("hours")?.let { OnHours(it.getInt("from").coerceIn(0, 23), it.getInt("to").coerceIn(0, 24)) }, o.optString("description").take(120), shows.map { it.title }) }.getOrNull()
?: return json(out, 400, JSONObject().put("error", "A channel needs a name."))
if (shows.isEmpty()) return json(out, 400, JSONObject().put("error", "Add at least one show or film."))
val said = runBlocking { withContext(mainDispatcher) { h.maker.create(channel, shows) } }
// 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(
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) } }
json(out, 200, JSONObject().put("message", said).put("number", number))
}
"POST /api/watch" -> {
@@ -429,3 +453,10 @@ internal object PhoneLink {
}
}
}
/** Age ratings by the groups the phone browses with. */
internal val RatingGroups = mapOf(
"Kids" to setOf("TV-Y", "TV-Y7", "TV-Y7-FV", "TV-G", "G", "U"),
"Family" to setOf("PG", "TV-PG"),
"Teen" to setOf("PG-13", "TV-14", "12", "12A", "15"),
"Grown-up" to setOf("R", "TV-MA", "NC-17", "18", "R18"))
@@ -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.81")
next.setRequestProperty("User-Agent", "OrbitTV/0.108.82")
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()) {
@@ -0,0 +1,53 @@
package tv.orbit.classic
/**
* Smart setup for Create a channel (Paul, 7 November 2026: "can the chair use our logic of day time, evening slots, core
* shows"). The Director lays a new channel out the way Orbit's own are: lighter shows in the daytime, the main ones in the
* evening, grown-up and darker ones late, with a few core shows that come round more often. It's a suggestion: the
* viewer can move any show, or keep it simple. Built from the catalogue's genres, networks and age ratings, which Emby
* and Jellyfin both carry, so it works the same on either.
*/
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>)
/** A channel laid out: each title's slot, and the core titles. */
internal class Shape(val slots: Map<String, Slot>, val core: Set<String>)
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
}
/** 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). */
internal fun shapeChannel(rows: List<ShapeRow>): Shape {
val slots = rows.associate { it.id to slotFor(it) }
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())
}
/** How the week looks: a gentle warning when the picks are few enough that episodes would repeat within days. */
internal fun weekCheck(series: Int, films: Int): String? = when {
series + films == 0 -> null
series == 0 && films < 21 -> "$films films is under three a day, so they'd repeat within the week. Add a few more, or keep it as it is."
series in 1..4 && films < 10 -> "With $series ${if (series == 1) "show" else "shows"}, the same few come round every day. A few more would make the week feel fuller."
else -> null
}
/** A layout as the planner reads it: each slot's titles for its hours, and the core titles weighted up. */
internal fun shapedParts(slots: Map<String, Slot>): List<DayPart> = Slot.entries.mapNotNull { s ->
slots.filterValues { it == s }.keys.toList().takeIf { it.isNotEmpty() }?.let { DayPart(s.fromHour, s.toHour, it) }
}
internal fun shapedWeights(core: Set<String>): Map<String, Double> = core.associate { seriesKey(it) to TIER_CORE }