Orbit Companion phase 3: Create in five steps, Director approvals, who's watching; logos fit

Create a channel in the Companion (Name, Shows, Style, Hours, Review), saved as
before; the phone can now make channels from any screen, not only while Settings
is open. The Director's Chair on the phone: Drive-In event ideas to approve,
defer or dismiss, and titles to place or drop, saved as Settings saves them.
Who's watching from the phone: Kids straight in, Adult with the PIN when one's
set; while Kids watches, making channels and the Director are refused. The
playback bug for Signature, Unscripted and Christmas fits the whole name.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-07 00:08:29 +00:00
co-authored by Claude Opus 5.5
parent 862b4b5448
commit 21884c1478
11 changed files with 319 additions and 73 deletions
@@ -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.80\"") +
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.81\"") +
(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.80\"" +
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.81\"" +
(token?.let { ", Token=\"$it\"" } ?: ""))
}
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
@@ -501,6 +501,67 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
if (lockedOut(selectedNumber) || profileHides(selectedNumber)) { watchingChannel = false; channelClockOffset = 0; selectedNumber = availableChannels.firstOrNull()?.number ?: 101 }
}
val liveChannel = availableChannels.firstOrNull { it.number == selectedNumber }
fun setSmartSchedule(programming: ChannelProgramming, turnOn: Boolean) {
val active = session ?: return
val existing = smartLoop(programming)
// A second press straight after the first is taken as a slip.
if (busy || now - lastSmartPress < 5_000) return
lastSmartPress = now
busy = true; busyLabel = "Reading ${programming.name}'s whole series and planning seven days…"; message = null
job = scope.launch {
try {
if (turnOn) {
val report = withContext(Dispatchers.IO) {
val context = coroutineContext
scheduler.setEnabled(active.accountId, programming.number, true)
val loop = existing ?: scheduler.seedLoop(active, active.accountId, programming) { context.ensureActive() }.also { extraChannels = extraChannels + it }
scheduler.topUp(active, active.accountId, programming, loop) { context.ensureActive() }.also {
scheduler.load(active.accountId, loop)?.let { on -> scheduledChannels = scheduledChannels + (programming.number to on) }
}
}
onChannelAvailable(true)
message = "${programming.name} is on, with ${report.programmes} programmes planned from ${report.shows.size} ${if (report.shows.size == 1) "title" else "titles"}."
} else {
withContext(Dispatchers.IO) { scheduler.setEnabled(active.accountId, programming.number, false) }
scheduledChannels = scheduledChannels - programming.number
message = "${programming.name} is off, and back to a short repeat. Its schedule and place are kept."
}
} catch (cancelled: CancellationException) { throw cancelled }
catch (failure: EmbyCheckException) { withContext(Dispatchers.IO) { scheduler.setEnabled(active.accountId, programming.number, false) }; message = failure.message }
catch (_: Exception) { withContext(Dispatchers.IO) { scheduler.setEnabled(active.accountId, programming.number, false) }; message = "${programming.name} could not be scheduled, so it stays off." }
finally { busy = false }
}
}
// Create your own from a phone and the Companion: kept here, before any screen returns early, so the phone can make
// and edit channels from every section, not only while Settings is open (Paul, 7 November 2026).
val channelMaker = remember(session, workspace) { session?.let { active -> ChannelMaker(
suggest = { description, chosen, skipped -> withContext(Dispatchers.IO) {
val wish = wishOf(description)
val rows = catalogue.chairRows(wish.genres, wish.years, wish.type, if (wish.genres.isEmpty() && wish.years == null) description else null)
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 ->
withContext(Dispatchers.IO) {
CustomChannels.upsert(workspace.scheduleDir, channel)
val before = scheduleStore.loadChoices(active.accountId, channel.number)
scheduleStore.saveChoices(active.accountId, channel.number, ChannelChoices(shows, before.rejected))
}
android.util.Log.i("OrbitSchedule", "yours channel=${channel.number} style=${channel.style} titles=${shows.size}")
SmartChannels.firstOrNull { it.number == channel.number }?.let { setSmartSchedule(it, true) }
"${channel.name} is ready on ${channel.number}. Its first programmes are being planned now."
}) } }
// The phone page (Create your own from a phone) asks the same of this screen as Settings does, and can tune the TV.
DisposableEffect(channelMaker) {
PhoneLink.handler = channelMaker?.let { m -> PhoneHandler(m, isOn = { n -> scheduledChannels.containsKey(n) }, watch = { n ->
if (!lockedOut(n) && !profileHides(n) && SmartChannels.any { it.number == n }) {
if (selectedNumber != n) { lastNumber = selectedNumber; selectedNumber = n }
channelClockOffset = 0; watchingChannel = true
if (!mainGuide && !mainHome && !mainWhatsOn && !mainCatchUp) onGuide()
}
}) }
onDispose { PhoneLink.handler = null }
}
fun tune(number: Int, offset: Long) {
if (number != selectedNumber) { lastNumber = selectedNumber; selectedNumber = number }
if (offset == 0L) liveHandoff.handOver(number)
@@ -513,6 +574,8 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
if (shownChannels.any { it.number == n }) { tune(n, offset); if (!mainGuide && !mainHome && !mainWhatsOn && !mainCatchUp) onGuide() }
}
val companionTickets by rememberUpdatedState(tickets)
val companionStore by rememberUpdatedState(scheduleStore)
val companionCatalogue by rememberUpdatedState(catalogue)
val companionSaveTickets by rememberUpdatedState<(Map<Long, Int>) -> Unit> { changed -> saveTickets(changed) }
val companionBills by rememberUpdatedState(driveInPlan.takeIf { Profiles.current?.let { it.kind != ProfileKind.Kids || it.driveIn } ?: true }
?.let { plan -> driveInLineup(driveInBills(plan), System.currentTimeMillis()).filter { !lockedOut(it) } }.orEmpty())
@@ -521,7 +584,23 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
CompanionScreen(channels = { shownChannels }, selected = { selectedNumber }, watching = { watchingChannel }, offset = { channelClockOffset },
tune = { n, offset -> companionTune(n, offset) }, driveIn = { companionBills }, tickets = { companionTickets.keys },
ticket = { start, held -> companionSaveTickets(if (held) companionTickets + (start to 0) else companionTickets - start) },
watchDriveIn = { if (companionDriveIn) watchingDriveIn = true else { pendingDriveInWatch = true; OrbitCompanion.open("Drive-In") } })
watchDriveIn = { if (companionDriveIn) watchingDriveIn = true else { pendingDriveInWatch = true; OrbitCompanion.open("Drive-In") } },
director = { session?.let { directorReports(companionStore, companionCatalogue, it.accountId)?.get(DirectorMode.Balanced) } },
place = { c, channel -> session?.let { active -> runCatching {
placeFromChair(companionStore, active.accountId, c.id, c.title, c.type, c.year, channel, c.options.firstOrNull()?.number, premiere = c.firstRun != null)
android.util.Log.i("OrbitSchedule", "director placed channel=$channel suggested=${channel == c.options.firstOrNull()?.number} from=phone")
} } },
drop = { c -> runCatching { dropFromChair(companionStore, c.id, c.title, c.type, c.options.firstOrNull()?.number, premiere = c.firstRun != null) }
android.util.Log.i("OrbitSchedule", "director dropped from=phone") },
decideIdea = { idea, decision ->
val films = runCatching { companionCatalogue.ideaFilms(idea.filmIds) }.getOrDefault(emptyList())
val ok = EventIdeaHistory.decide(companionStore.eventIdeaHistoryFile(), companionStore.eventIdeasFile(), idea.signature, decision, films, System.currentTimeMillis())
android.util.Log.i("OrbitSchedule", "event idea decision=$decision saved=$ok from=phone")
when { !ok -> "That decision couldn't be saved. Try again."
decision == "approved" -> "${idea.theme} approved for ${idea.evening}. It books once the Drive-In plans that evening, after its films are checked again."
decision == "deferred" -> "${idea.theme} deferred: it can come back in four weeks."
else -> "${idea.theme} dismissed: it won't be proposed again unless its films change." }
})
}
DisposableEffect(Unit) {
PhoneLink.screen = companionScreen
@@ -590,37 +669,6 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
}
return
}
fun setSmartSchedule(programming: ChannelProgramming, turnOn: Boolean) {
val active = session ?: return
val existing = smartLoop(programming)
// A second press straight after the first is taken as a slip.
if (busy || now - lastSmartPress < 5_000) return
lastSmartPress = now
busy = true; busyLabel = "Reading ${programming.name}'s whole series and planning seven days…"; message = null
job = scope.launch {
try {
if (turnOn) {
val report = withContext(Dispatchers.IO) {
val context = coroutineContext
scheduler.setEnabled(active.accountId, programming.number, true)
val loop = existing ?: scheduler.seedLoop(active, active.accountId, programming) { context.ensureActive() }.also { extraChannels = extraChannels + it }
scheduler.topUp(active, active.accountId, programming, loop) { context.ensureActive() }.also {
scheduler.load(active.accountId, loop)?.let { on -> scheduledChannels = scheduledChannels + (programming.number to on) }
}
}
onChannelAvailable(true)
message = "${programming.name} is on, with ${report.programmes} programmes planned from ${report.shows.size} ${if (report.shows.size == 1) "title" else "titles"}."
} else {
withContext(Dispatchers.IO) { scheduler.setEnabled(active.accountId, programming.number, false) }
scheduledChannels = scheduledChannels - programming.number
message = "${programming.name} is off, and back to a short repeat. Its schedule and place are kept."
}
} catch (cancelled: CancellationException) { throw cancelled }
catch (failure: EmbyCheckException) { withContext(Dispatchers.IO) { scheduler.setEnabled(active.accountId, programming.number, false) }; message = failure.message }
catch (_: Exception) { withContext(Dispatchers.IO) { scheduler.setEnabled(active.accountId, programming.number, false) }; message = "${programming.name} could not be scheduled, so it stays off." }
finally { busy = false }
}
}
fun openSuggestions(programming: ChannelProgramming) {
val active = session ?: return
if (busy) return
@@ -675,34 +723,6 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
}
}
// Remembered, so the phone link isn't handed a new one on every redraw.
val channelMaker = remember(session, workspace) { session?.let { active -> ChannelMaker(
suggest = { description, chosen, skipped -> withContext(Dispatchers.IO) {
val wish = wishOf(description)
val rows = catalogue.chairRows(wish.genres, wish.years, wish.type, if (wish.genres.isEmpty() && wish.years == null) description else null)
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 ->
withContext(Dispatchers.IO) {
CustomChannels.upsert(workspace.scheduleDir, channel)
val before = scheduleStore.loadChoices(active.accountId, channel.number)
scheduleStore.saveChoices(active.accountId, channel.number, ChannelChoices(shows, before.rejected))
}
android.util.Log.i("OrbitSchedule", "yours channel=${channel.number} style=${channel.style} titles=${shows.size}")
SmartChannels.firstOrNull { it.number == channel.number }?.let { setSmartSchedule(it, true) }
"${channel.name} is ready on ${channel.number}. Its first programmes are being planned now."
}) } }
// The phone page (Create your own from a phone) asks the same of this screen as Settings does, and can tune the TV.
DisposableEffect(channelMaker) {
PhoneLink.handler = channelMaker?.let { m -> PhoneHandler(m, isOn = { n -> scheduledChannels.containsKey(n) }, watch = { n ->
if (!lockedOut(n) && !profileHides(n) && SmartChannels.any { it.number == n }) {
if (selectedNumber != n) { lastNumber = selectedNumber; selectedNumber = n }
channelClockOffset = 0; watchingChannel = true
if (!mainGuide && !mainHome && !mainWhatsOn && !mainCatchUp) onGuide()
}
}) }
onDispose { PhoneLink.handler = null }
}
if (!visible) return
if (onboarding && session != null) return
suggesting?.let { programming ->
@@ -40,7 +40,12 @@ internal class CompanionScreen(
val tickets: () -> Set<Long> = { emptySet() },
val ticket: (startMs: Long, held: Boolean) -> Unit = { _, _ -> },
/** Out to the lot and onto the big screen, while a bill is showing. */
val watchDriveIn: () -> Unit = {})
val watchDriveIn: () -> Unit = {},
/** Phase 3: the Director's Chair, as Settings shows it (Balanced), and its decisions, saved as Settings saves them. */
val director: () -> DeskReport? = { null },
val place: (ChairChoice, Int) -> Unit = { _, _ -> },
val drop: (ChairChoice) -> Unit = {},
val decideIdea: (DeskEventIdea, String) -> String = { _, _ -> "" })
/**
* Phase 2's queue (Paul, 6 November 2026): what plays when the programme on now ends. A channel, live from then ("switch
@@ -198,6 +203,44 @@ internal object OrbitCompanion {
})
}
// --- Phase 3: Director approvals and profiles. ---
private fun choiceJson(c: ChairChoice) = JSONObject().put("id", c.id).put("title", c.title).put("type", c.type).put("year", c.year ?: JSONObject.NULL)
.put("line", c.line).put("ask", c.ask).put("options", JSONArray(c.options.map { JSONObject().put("number", it.number).put("name", it.name).put("reason", it.reason) }))
fun choices(report: DeskReport): List<ChairChoice> =
report.picks.filter { it.id.isNotEmpty() }.map { ChairChoice(it.title, it.id, it.type, it.year, it.tag, it.line, it.options, false, it.firstRun) } +
report.asks.filter { it.id.isNotEmpty() }.map { ChairChoice(it.title, it.id, it.type, it.year, null, it.line, it.options, true, it.firstRun) }
fun director(report: DeskReport?): JSONObject {
if (report == null) return JSONObject().put("ready", false)
return JSONObject().put("ready", true).put("choices", JSONArray(choices(report).map(::choiceJson)))
.put("ideas", JSONArray(report.eventIdeas.map { i -> JSONObject().put("signature", i.signature).put("theme", i.theme).put("format", i.format).put("evening", i.evening)
.put("films", JSONArray(i.films)).put("reasons", JSONArray(i.reasons)).put("decision", i.decision) }))
}
/** Wrong Adult PINs from phones: three in a row and the phone waits five minutes. */
private var pinMisses = 0
private var pinWaitUntil = 0L
fun profiles(): JSONObject = JSONObject().put("pinSet", AfterDarkLock.pinSet).put("kidsOn", Profiles.kidsOn)
.put("current", Profiles.current?.let { JSONObject().put("id", it.id).put("name", it.name).put("kind", it.kind.name) } ?: JSONObject.NULL)
.put("profiles", JSONArray(Profiles.all.map { JSONObject().put("id", it.id).put("name", it.name).put("kind", it.kind.name) }))
/** Switches who's watching on the TV. Kids goes straight in; Adult needs the PIN when one's set, as on the TV. Null when done, else why not. */
fun switchProfile(context: Context?, id: String, pin: String?, nowMs: Long): String? {
val p = Profiles.all.firstOrNull { it.id == id } ?: return "That profile isn't on this TV."
if (p.kind == ProfileKind.Grown && AfterDarkLock.pinSet) {
if (nowMs < pinWaitUntil) return "Too many wrong PINs. Try again in a few minutes."
if (pin.isNullOrEmpty()) return "PIN"
if (context == null || !AfterDarkLock.unlock(context, pin)) {
if (++pinMisses >= 3) { pinMisses = 0; pinWaitUntil = nowMs + 5 * 60_000L }
return "That's not the PIN."
}
pinMisses = 0
}
if (p.kind == ProfileKind.Kids) AfterDarkLock.lock()
Profiles.current = p
return null
}
/** While Kids is watching, the phone keeps to what Kids may do: no making channels and no Director. */
val grownUp get() = !Profiles.kids
/** The channel [step] away from the chosen one, round the guide. */
fun stepped(screen: CompanionScreen, step: Int): Int? {
val list = screen.channels().ifEmpty { return null }
@@ -306,6 +306,7 @@ internal object PhoneLink {
json(out, 200, JSONArray(runBlocking { h.maker.suggest(d, chosen, skipped).ifEmpty { h.maker.search(d) } }.map(::suggestionJson)))
}
"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"))
val number = o.optInt("number").takeIf { it in YOURS_FIRST..YOURS_LAST } ?: CustomChannels.nextNumber() ?: return json(out, 400, JSONObject().put("error", "Every number is taken."))
val shows = runCatching { o.getJSONArray("shows").let { a -> (0 until minOf(a.length(), 200)).map { suggestionOf(a.getJSONObject(it)) } } }.getOrNull()
@@ -328,7 +329,8 @@ internal object PhoneLink {
private val companionRoutes = setOf("GET /api/now", "GET /api/guide", "GET /api/catchup", "GET /api/rooms", "GET /api/looks", "POST /api/key", "POST /api/volume",
"POST /api/channel", "POST /api/tune", "POST /api/section", "POST /api/catchup/watch",
"GET /api/queue", "POST /api/queue", "POST /api/queue/remove", "GET /api/drivein", "POST /api/drivein/ticket", "POST /api/drivein/watch")
"GET /api/queue", "POST /api/queue", "POST /api/queue/remove", "GET /api/drivein", "POST /api/drivein/ticket", "POST /api/drivein/watch",
"GET /api/director", "POST /api/director/place", "POST /api/director/drop", "POST /api/director/idea", "GET /api/profiles", "POST /api/profile")
/** The Companion's remote, guide, Catch Up and rooms (see [OrbitCompanion]); false when [r] is for Create your own. */
private fun companion(r: Request, out: OutputStream): Boolean {
if ("${r.method} ${r.path}" !in companionRoutes) return false
@@ -371,6 +373,32 @@ internal object PhoneLink {
val entry = OrbitCompanion.catchUpEntry(s, o.optInt("number"), o.optLong("startMs"), now) ?: return json(out, 410, JSONObject().put("error", "That's no longer in Catch Up."))
onScreen { s.tune(entry.channel.number, entry.offsetFrom(clock())) }; json(out, 200, JSONObject().put("ok", true))
}
"GET /api/profiles" -> json(out, 200, OrbitCompanion.profiles())
"POST /api/profile" -> {
val o = body()
var why: String? = null
onScreen { why = OrbitCompanion.switchProfile(appContext, o.optString("id"), o.optString("pin").filter(Char::isDigit).take(8).ifEmpty { null }, now) }
if (why == "PIN") return json(out, 401, JSONObject().put("error", "PIN").put("pin", true))
if (why != null) return json(out, 403, JSONObject().put("error", why))
json(out, 200, OrbitCompanion.profiles())
}
"GET /api/director", "POST /api/director/place", "POST /api/director/drop", "POST /api/director/idea" -> {
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult for the Director."))
val report = runCatching { s.director() }.getOrNull()
if (r.method == "GET") return json(out, 200, OrbitCompanion.director(report))
report ?: return json(out, 409, JSONObject().put("error", "The Director is still reading your library."))
val o = body()
if (r.path == "/api/director/idea") {
val decision = o.optString("decision").takeIf { it in setOf("approved", "deferred", "dismissed") } ?: return json(out, 400, JSONObject())
val idea = report.eventIdeas.firstOrNull { it.signature == o.optString("signature") } ?: return json(out, 404, JSONObject().put("error", "That idea has gone."))
return json(out, 200, JSONObject().put("message", s.decideIdea(idea, decision)))
}
val choice = OrbitCompanion.choices(report).firstOrNull { it.id == o.optString("id") } ?: return json(out, 404, JSONObject().put("error", "That title has gone from the Chair."))
if (r.path == "/api/director/drop") { s.drop(choice); return json(out, 200, JSONObject().put("message", "${choice.title} won't be suggested again.")) }
val channel = choice.options.firstOrNull { it.number == o.optInt("channel") } ?: return json(out, 400, JSONObject().put("error", "Pick one of its channels."))
s.place(choice, channel.number)
json(out, 200, JSONObject().put("message", "${choice.title} joins ${channel.name}. It's added to the channel's list and appears as it plans ahead."))
}
"GET /api/queue" -> json(out, 200, JSONObject().put("queue", OrbitCompanion.queueJson()))
"POST /api/queue" -> {
val o = body()
@@ -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.80")
next.setRequestProperty("User-Agent", "OrbitTV/0.108.81")
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()) {