Orbit Companion phase 2: queue next, switch when this ends, Drive-In; Christmas stops at New Year
The phone can queue a channel (switches when the programme being watched ends) or a Catch Up programme (plays from its start), five at most, shown as Up next and removable. The Guide gains a Drive-In view with tonight's bills, tickets and Watch while one is showing. Orbit Christmas no longer books anything that starts from 1 January, and books nothing out of season. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -562,3 +562,14 @@ internal const val CHRISTMAS_NUMBER = 310
|
||||
*/
|
||||
internal fun inSeason(number: Int, timeMs: Long, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): Boolean =
|
||||
number != CHRISTMAS_NUMBER || java.time.Instant.ofEpochMilli(timeMs).atZone(zone).monthValue >= 11
|
||||
|
||||
/**
|
||||
* How far a seasonal channel may be booked: Orbit Christmas books nothing that starts from 1 January (it planned about a
|
||||
* week into January before, out of sight). Null for every other channel.
|
||||
*/
|
||||
internal fun seasonEndMs(number: Int, timeMs: Long, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): Long? {
|
||||
if (number != CHRISTMAS_NUMBER) return null
|
||||
val day = java.time.Instant.ofEpochMilli(timeMs).atZone(zone)
|
||||
if (day.monthValue < 11) return timeMs
|
||||
return java.time.LocalDate.of(day.year + 1, 1, 1).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
}
|
||||
|
||||
@@ -1031,16 +1031,20 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List
|
||||
/** See [ChannelProgramming.shorts]. */
|
||||
shorts: ShortsRule? = null,
|
||||
/** See [ChannelProgramming.marathon]. */
|
||||
marathon: Int = 0): ChannelPlan? {
|
||||
marathon: Int = 0,
|
||||
/** Nothing is booked to start from here on: a seasonal channel's end ([seasonEndMs]). */
|
||||
seasonEndMs: Long? = null): 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
|
||||
val from = if (kept != null && kept.endMs > nowMs) kept.endMs else nowMs
|
||||
val untilMs = minOf(nowMs + SCHEDULE_AHEAD_MS, seasonEndMs ?: Long.MAX_VALUE)
|
||||
if (from >= untilMs) return kept ?: ChannelPlan(emptyList(), existing?.tail ?: aired)
|
||||
val trailing = kept?.entries?.lastOrNull()?.let { tail -> kept.entries.asReversed().takeWhile { it.seriesId == tail.seriesId }.size } ?: 0
|
||||
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, nowMs + SCHEDULE_AHEAD_MS, weightOf, dayParts, zone, avoid, shuffle, mixed, finishTogether, recent, trailing, fileRestMs, stories, shorts)
|
||||
} else extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, filmRestMs, finishTogether, dayParts, zone, avoid, shuffle, mixed, trailing, noThirdInARow && marathon == 0, blockRotation, adaptiveRest, stories = stories, shorts = shorts, marathon = marathon)
|
||||
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)
|
||||
return ChannelPlan(kept?.entries.orEmpty() + added.entries, added.tail)
|
||||
}
|
||||
|
||||
|
||||
@@ -313,7 +313,8 @@ internal class ChannelScheduler(private val store: ScheduleStore,
|
||||
}
|
||||
val plan = topUpPlan(existing, base, pool?.series?.let { withoutFailed(it, store.loadFailed(userId)) }, now, programming.filmRestMs, programming.finishTogether, programming.dayParts,
|
||||
avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes,
|
||||
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping, shorts = programming.shorts, marathon = programming.marathon) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
|
||||
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping, shorts = programming.shorts, marathon = programming.marathon,
|
||||
seasonEndMs = seasonEndMs(number, now)) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
|
||||
if (plan !== existing) store.savePlan(userId, number, plan)
|
||||
// Stage C, report only: every work any plan books, so "not yet shown on Orbit" has evidence.
|
||||
if (plan !== existing) runCatching {
|
||||
|
||||
@@ -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.77\"") +
|
||||
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.78\"") +
|
||||
(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.77\"" +
|
||||
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.78\"" +
|
||||
(token?.let { ", Token=\"$it\"" } ?: ""))
|
||||
}
|
||||
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
|
||||
|
||||
@@ -512,11 +512,26 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
|
||||
val companionTune by rememberUpdatedState<(Int, Long) -> Unit> { n, offset ->
|
||||
if (shownChannels.any { it.number == n }) { tune(n, offset); if (!mainGuide && !mainHome && !mainWhatsOn && !mainCatchUp) onGuide() }
|
||||
}
|
||||
val companionTickets by rememberUpdatedState(tickets)
|
||||
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())
|
||||
val companionDriveIn by rememberUpdatedState(mainDriveIn)
|
||||
val companionScreen = remember {
|
||||
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") } })
|
||||
}
|
||||
DisposableEffect(Unit) {
|
||||
PhoneLink.screen = CompanionScreen(channels = { shownChannels }, selected = { selectedNumber }, watching = { watchingChannel }, offset = { channelClockOffset },
|
||||
tune = { n, offset -> companionTune(n, offset) })
|
||||
PhoneLink.screen = companionScreen
|
||||
onDispose { PhoneLink.screen = null }
|
||||
}
|
||||
// Phase 2's queue: the next item plays when the programme being watched ends.
|
||||
LaunchedEffect(Unit) {
|
||||
var anchor: Pair<Int, Long>? = null
|
||||
while (true) { delay(1_000); anchor = OrbitCompanion.follow(companionScreen, anchor, System.currentTimeMillis()) }
|
||||
}
|
||||
// The Companion's jump buttons: a section on the TV closes the programme being watched, as Back would.
|
||||
LaunchedEffect(OrbitCompanion.asked) { if (OrbitCompanion.asked != null) { watchingChannel = false; watchingDriveIn = false } }
|
||||
if (mainDriveIn && liveSession != null) {
|
||||
|
||||
@@ -34,7 +34,21 @@ internal class CompanionScreen(
|
||||
/** Catch Up's replay clock: below zero while catching up. */
|
||||
val offset: () -> Long,
|
||||
/** Tune [number] from [offset] (zero is live), as the guide does. */
|
||||
val tune: (number: Int, offset: Long) -> Unit)
|
||||
val tune: (number: Int, offset: Long) -> Unit,
|
||||
/** The Drive-In's bills this profile may see (none for a Kids profile without it, and no Late Show while locked). */
|
||||
val driveIn: () -> List<DriveInBill> = { emptyList() },
|
||||
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 = {})
|
||||
|
||||
/**
|
||||
* Phase 2's queue (Paul, 6 November 2026): what plays when the programme on now ends. A channel, live from then ("switch
|
||||
* when this one ends"), or a Catch Up programme from its start. Kept while Orbit is open; five at most.
|
||||
*/
|
||||
internal class Queued(val number: Int, val channel: String, val title: String, val sub: String?,
|
||||
/** A Catch Up programme's start; null to switch to the channel live. */
|
||||
val catchUpStartMs: Long?)
|
||||
|
||||
internal object OrbitCompanion {
|
||||
/** The buttons the phone may press, by the name the page uses. */
|
||||
@@ -124,6 +138,55 @@ internal object OrbitCompanion {
|
||||
fun catchUpEntry(screen: CompanionScreen, number: Int, startMs: Long, nowMs: Long): CatchUpEntry? =
|
||||
catchUpShelves(screen.channels(), nowMs).flatMap { it.entries }.firstOrNull { it.channel.number == number && it.show.startMs == startMs }
|
||||
|
||||
const val QUEUE_MAX = 5
|
||||
var queue by mutableStateOf<List<Queued>>(emptyList())
|
||||
|
||||
/** Queue [number] live after the programme on now, or a Catch Up programme ([catchUpStartMs]); null when it can't be. */
|
||||
fun enqueue(screen: CompanionScreen, number: Int, catchUpStartMs: Long?, nowMs: Long): Queued? {
|
||||
if (queue.size >= QUEUE_MAX) return null
|
||||
val item = if (catchUpStartMs != null) {
|
||||
val e = catchUpEntry(screen, number, catchUpStartMs, nowMs) ?: return null
|
||||
guideTitleParts(e.show.media.item.title).let { (t, sub) -> Queued(number, e.channel.name, t, sub, catchUpStartMs) }
|
||||
} else {
|
||||
val channel = screen.channels().firstOrNull { it.number == number } ?: return null
|
||||
// What that channel will be showing when the programme on the TV now ends.
|
||||
val tv = screen.channels().firstOrNull { it.number == screen.selected() }
|
||||
val at = tv?.at(nowMs + screen.offset())?.endMs?.minus(screen.offset()) ?: nowMs
|
||||
guideTitleParts(channel.at(at).media.item.title).let { (t, sub) -> Queued(number, channel.name, t, sub, null) }
|
||||
}
|
||||
queue = queue + item
|
||||
return item
|
||||
}
|
||||
fun queueJson(): JSONArray = JSONArray(queue.map { q ->
|
||||
JSONObject().put("number", q.number).put("channel", q.channel).put("title", q.title).put("sub", q.sub ?: JSONObject.NULL)
|
||||
.put("catchUp", q.catchUpStartMs != null).put("startMs", q.catchUpStartMs ?: JSONObject.NULL) })
|
||||
|
||||
/**
|
||||
* The TV's side: called every second while Orbit is open. [anchor] is the programme being waited on (channel and start);
|
||||
* when the programme on the same channel changes, the queue's first item plays. Changing channel, or not watching,
|
||||
* moves the anchor, so the queue waits for the end of whatever is watched next. Returns the new anchor.
|
||||
*/
|
||||
fun follow(screen: CompanionScreen, anchor: Pair<Int, Long>?, nowMs: Long): Pair<Int, Long>? {
|
||||
val head = queue.firstOrNull() ?: return null
|
||||
val channel = screen.channels().firstOrNull { it.number == screen.selected() } ?: return anchor
|
||||
val on = screen.selected() to channel.at(nowMs + screen.offset()).startMs
|
||||
if (anchor == null || !screen.watching() || anchor.first != on.first || anchor == on) return on
|
||||
queue = queue.drop(1)
|
||||
val offset = head.catchUpStartMs?.let { start -> catchUpEntry(screen, head.number, start, nowMs)?.offsetFrom(nowMs) }
|
||||
if (head.catchUpStartMs == null || offset != null) screen.tune(head.number, offset ?: 0)
|
||||
android.util.Log.i("OrbitCompanion", "queue played catchUp=${head.catchUpStartMs != null} left=${queue.size}")
|
||||
return null
|
||||
}
|
||||
|
||||
/** Tonight's and the coming bills, as the Drive-In lists them, with this TV's tickets. */
|
||||
fun driveIn(screen: CompanionScreen, nowMs: Long): JSONArray = screen.tickets().let { held ->
|
||||
JSONArray(screen.driveIn().map { b ->
|
||||
JSONObject().put("kind", b.kind.label).put("event", b.event ?: JSONObject.NULL).put("startMs", b.startMs).put("endMs", b.endMs)
|
||||
.put("day", driveInDay(b, nowMs)).put("showing", b.startMs <= nowMs && nowMs < b.endMs).put("ticket", b.startMs in held)
|
||||
.put("films", JSONArray(b.entries.map { guideTitleParts(it.media.item.title).first }))
|
||||
})
|
||||
}
|
||||
|
||||
/** 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 }
|
||||
|
||||
@@ -327,7 +327,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")
|
||||
"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")
|
||||
/** 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
|
||||
@@ -339,7 +340,7 @@ internal object PhoneLink {
|
||||
fun body() = runCatching { JSONObject(r.body) }.getOrNull() ?: JSONObject()
|
||||
fun onScreen(block: () -> Unit) = runBlocking { withContext(mainDispatcher) { block() } }
|
||||
when ("${r.method} ${r.path}") {
|
||||
"GET /api/now" -> json(out, 200, OrbitCompanion.now(s, now))
|
||||
"GET /api/now" -> json(out, 200, OrbitCompanion.now(s, now).put("queue", OrbitCompanion.queueJson()))
|
||||
"GET /api/guide" -> json(out, 200, OrbitCompanion.guide(s, now))
|
||||
"GET /api/catchup" -> json(out, 200, JSONObject().put("shelves", OrbitCompanion.catchUp(s, now)))
|
||||
"GET /api/rooms" -> json(out, 200, OrbitCompanion.rooms(appContext))
|
||||
@@ -370,6 +371,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/queue" -> json(out, 200, JSONObject().put("queue", OrbitCompanion.queueJson()))
|
||||
"POST /api/queue" -> {
|
||||
val o = body()
|
||||
val start = if (o.isNull("startMs") || !o.has("startMs")) null else o.optLong("startMs")
|
||||
var added: Queued? = null
|
||||
onScreen { added = OrbitCompanion.enqueue(s, o.optInt("number"), start, now) }
|
||||
if (added == null) return json(out, if (OrbitCompanion.queue.size >= OrbitCompanion.QUEUE_MAX) 409 else 404,
|
||||
JSONObject().put("error", if (OrbitCompanion.queue.size >= OrbitCompanion.QUEUE_MAX) "The queue holds five. Remove one first." else "That isn't on this TV right now."))
|
||||
json(out, 200, JSONObject().put("queue", OrbitCompanion.queueJson()))
|
||||
}
|
||||
"POST /api/queue/remove" -> {
|
||||
val at = body().optInt("index", -1)
|
||||
onScreen { OrbitCompanion.queue = if (at < 0) emptyList() else OrbitCompanion.queue.filterIndexed { i, _ -> i != at } }
|
||||
json(out, 200, JSONObject().put("queue", OrbitCompanion.queueJson()))
|
||||
}
|
||||
"GET /api/drivein" -> json(out, 200, JSONObject().put("bills", OrbitCompanion.driveIn(s, now)))
|
||||
"POST /api/drivein/ticket" -> {
|
||||
val o = body(); val start = o.optLong("startMs")
|
||||
if (s.driveIn().none { it.startMs == start }) return json(out, 404, JSONObject().put("error", "That showing isn't on the board."))
|
||||
onScreen { s.ticket(start, o.optBoolean("held", true)) }
|
||||
json(out, 200, JSONObject().put("bills", OrbitCompanion.driveIn(s, now)))
|
||||
}
|
||||
"POST /api/drivein/watch" -> {
|
||||
if (s.driveIn().none { it.startMs <= now && now < it.endMs }) return json(out, 409, JSONObject().put("error", "Nothing's showing at the Drive-In right now."))
|
||||
onScreen { s.watchDriveIn() }; json(out, 200, JSONObject().put("ok", true))
|
||||
}
|
||||
else -> json(out, 404, JSONObject().put("error", "Not found"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.77")
|
||||
next.setRequestProperty("User-Agent", "OrbitTV/0.108.78")
|
||||
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()) {
|
||||
|
||||
Reference in New Issue
Block a user