Four in one: late rotation, daily collections, Family on the phone, sound for four idents

Shaped channels' late nights take turns too, 24 shows a week. Collections refresh daily into a
fresh copy swapped in whole, so new titles reach the Chair on their own. The phone can add,
rename and remove profiles, adults only. Mistletoe, Sakura, Signature and Unscripted idents carry
a synthesised sting at -20 LUFS, played with Ident sound on at most once every 20 minutes a channel.
0.108.99.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-07 21:13:42 +00:00
co-authored by Claude Opus 5.5
parent f28c4977dd
commit 9989b156d1
17 changed files with 162 additions and 22 deletions
@@ -83,7 +83,9 @@ internal class ChannelScheduler(private val store: ScheduleStore,
* the last 60 days, read in batches and appended to the evidence file, skipping any already read. Read only.
*/
fun readEvidence(session: EmbySampleSession, userId: String, catalogue: CatalogueStore) {
if (!EvidenceRequest.take()) return
// Daily as well as on request (Paul, 7 November 2026): new titles in a collection reach the Chair on their own.
val refresh = CollectionRefresh(store.collectionsFile())
if (!EvidenceRequest.take() && !refresh.due(clock())) return
val today = java.time.LocalDate.now()
val ids = SmartChannels.flatMap { store.loadPool(userId, it.number)?.series.orEmpty().map { s -> s.id } } +
catalogue.releasedBetween(today.minusDays(NEWLY_RELEASED_DAYS).toString(), today.toString(), 2_000).map { it.id } +
@@ -105,19 +107,24 @@ internal class ChannelScheduler(private val store: ScheduleStore,
// Read before collections were paged (every one stopped at 300): set aside once and read again in full.
if (collections.exists() && collections.useLines { lines -> lines.firstOrNull()?.contains("\"complete\"") != true })
collections.renameTo(java.io.File(collections.path + ".before-paged"))
val done = if (collections.exists()) collections.useLines { it.count() } else 0
var start = done; var sets = 0; var total = -1
// The first full read appends to the file; after that each day's refresh reads into a fresh copy, swapped in once whole,
// so a collection's new members (and any removed) are picked up without ever leaving a half-read list in use.
val refreshing = refresh.complete()
val target = if (refreshing) refresh.next else collections
val done = if (target.exists()) target.useLines { it.count() } else 0
var start = done; var sets = 0; var total = -1; var finished = false
try {
while (sets < COLLECTIONS_MAX_PER_RUN) {
val (page, all) = session.readCollections(start, COLLECTIONS_PAGE)
total = all
if (page.isEmpty()) break
collections.appendText(page.joinToString("") { it.toString() + "\n" })
if (page.isEmpty()) { finished = true; break }
target.appendText(page.joinToString("") { it.toString() + "\n" })
start += page.size; sets += page.size
if (start >= all) break
if (start >= all) { finished = true; break }
}
} catch (failure: EmbyCheckException) { Log.w("OrbitSchedule", "collections failed status=${failure.httpStatus}") }
Log.i("OrbitSchedule", "collections read=$sets total=$total kept=${done + sets}")
if (finished) refresh.finish(refreshing, clock())
Log.i("OrbitSchedule", "collections read=$sets total=$total kept=${done + sets} refresh=$refreshing finished=$finished")
}
/**
@@ -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.98\"") +
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.99\"") +
(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.98\"" +
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.99\"" +
(token?.let { ", Token=\"$it\"" } ?: ""))
}
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
@@ -48,3 +48,25 @@ internal fun evidenceMissing(file: File, ids: List<String>): List<String> {
val have = if (file.exists()) file.useLines { lines -> lines.mapNotNull { runCatching { JSONObject(it).optString("id") }.getOrNull() }.toHashSet() } else emptySet()
return ids.distinct().filter { it !in have }
}
/**
* The daily collections refresh (Paul, 7 November 2026). Until the first full read finishes, reads go on appending to the
* collections file as before; from then on, once a day, the whole list is read again into [next] and swapped in when complete,
* a bounded number of sets per background round. [state] holds when the last full read finished.
*/
internal class CollectionRefresh(private val file: java.io.File) {
val next = java.io.File(file.path + ".next")
private val state = java.io.File(file.path + ".state")
private fun finishedAt(): Long? = runCatching { JSONObject(state.readText()).getLong("finishedAt") }.getOrNull()
/** A first full read has finished, so refreshes go to [next]. */
fun complete() = finishedAt() != null
/** Something to do: the first read isn't finished, a refresh is part-way, or the last full read is a day old. */
fun due(nowMs: Long): Boolean = finishedAt()?.let { next.exists() || nowMs - it >= COLLECTIONS_REFRESH_MS } ?: true
/** A full read reached the end: a refresh replaces the file; either way the time is noted. */
fun finish(refreshing: Boolean, nowMs: Long) {
if (refreshing && next.exists()) { if (!next.renameTo(file)) { file.writeText(next.readText()); next.delete() } }
state.writeText(JSONObject().put("finishedAt", nowMs).toString())
}
}
internal const val COLLECTIONS_REFRESH_MS = 24 * 60 * 60_000L
@@ -38,6 +38,18 @@ private val IdentVideos = mapOf(108 to R.raw.ident_108, 109 to R.raw.ident_109,
611 to R.raw.ident_611, 612 to R.raw.ident_612, 613 to R.raw.ident_613)
/** [atMs] is when the next programme starts, for a channel whose ident follows the time of day. */
/**
* Idents with a sound of their own (Paul, 7 November 2026; design/channels/sound): played with Ident sound on, at most once
* every 20 minutes a channel, so a run of short programmes doesn't repeat it every few minutes.
*/
internal val IdentsWithSound = setOf(R.raw.ident_mistletoe, R.raw.ident_sakura, R.raw.ident_109, R.raw.ident_110)
internal object IdentStings {
private val last = HashMap<Int, Long>()
const val GAP_MS = 20 * 60_000L
@Synchronized fun take(number: Int, nowMs: Long): Boolean =
(last[number]?.let { nowMs - it >= GAP_MS } ?: true).also { if (it) last[number] = nowMs }
}
internal fun identVideo(number: Int, atMs: Long = 0) = if (number == TOTS_NUMBER) totsVideo(atMs) else IdentVideos[number] ?: CustomChannels.of(number)?.brand?.let { BrandPackIdents[it] }
internal fun identLength(number: Int, atMs: Long = 0) = when (number) {
TOTS_NUMBER -> totsMood(atMs).lengthMs
@@ -120,7 +132,8 @@ internal fun IdentOverlay(session: EmbySampleSession, channel: SampleChannel, ne
}
seekTo(startedLateMs.coerceIn(0, identMs))
volume = if (block != null) (if (settings.blockIdentSound) 1f else 0f)
else if (mood != null && settings.identSound && TotsJingle.take(mood, System.currentTimeMillis())) 1f else 0f
else if (mood != null && settings.identSound && TotsJingle.take(mood, System.currentTimeMillis())) 1f
else if (mood == null && video in IdentsWithSound && settings.identSound && IdentStings.take(channel.number, System.currentTimeMillis())) 1f else 0f
prepare(); playWhenReady = true
}
}
@@ -463,7 +463,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/director", "POST /api/director/place", "POST /api/director/drop", "POST /api/director/idea", "GET /api/profiles", "POST /api/profile")
"GET /api/director", "POST /api/director/place", "POST /api/director/drop", "POST /api/director/idea", "GET /api/profiles", "POST /api/profile",
"POST /api/profile/add", "POST /api/profile/rename", "POST /api/profile/remove")
/** 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
@@ -515,6 +516,25 @@ internal object PhoneLink {
if (why != null) return json(out, 403, JSONObject().put("error", why))
json(out, 200, OrbitCompanion.profiles())
}
// Family on the phone (Paul, 7 November 2026), as Settings › Family on the TV: adults only.
"POST /api/profile/add", "POST /api/profile/rename", "POST /api/profile/remove" -> {
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult to change profiles."))
val ctx = appContext ?: return json(out, 409, JSONObject().put("error", "Orbit is starting up on the TV."))
val o = body(); var problem: String? = null
onScreen {
when (r.path) {
"/api/profile/add" -> if (Profiles.all.size >= MAX_PROFILES) problem = "Orbit holds $MAX_PROFILES profiles."
else Profiles.add(ctx, o.optString("name"), if (o.optString("kind") == "Kids") ProfileKind.Kids else ProfileKind.Grown,
o.optString("picture").takeIf { it in ProfilePictures } ?: if (o.optString("kind") == "Kids") "ollie" else "sil-pink")
"/api/profile/rename" -> Profiles.all.firstOrNull { it.id == o.optString("id") }?.let { Profiles.update(ctx, it.copy(name = cleanProfileName(o.optString("name")))) }
?: run { problem = "That profile has gone." }
else -> { val id = o.optString("id")
if (Profiles.remove(ctx, id)) runCatching { forgetProfileData(Workspaces.current(ctx).scheduleDir, id) } else problem = "Someone has to stay Adult." }
}
}
problem?.let { return json(out, 409, JSONObject().put("error", it)) }
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()
@@ -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.98")
next.setRequestProperty("User-Agent", "OrbitTV/0.108.99")
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()) {
@@ -279,7 +279,7 @@ private fun ViewingDetail(firstSwitch: FocusRequester, modifier: Modifier, top:
SettingLine("Idents", "Play each channel's ident between programmes. When off, Tots shows a still picture instead.") {
OnOff(idents, Modifier, onClick = { idents = !idents; settings.idents = idents })
}
SettingLine("Ident sound", "Let Tots play its jingle, at most once every 30 minutes.") {
SettingLine("Ident sound", "Let Tots play its jingle, and channels with a sound of their own (Mistletoe, Sakura, Signature, Unscripted) play theirs, never too often.") {
OnOff(identSound, Modifier, onClick = { identSound = !identSound; settings.identSound = identSound })
}
SettingLine("Special idents", "Give named blocks and events their own ident as they begin, such as Riot Laughs or PPV Sunday. Off uses each channel's usual ident.") {
@@ -236,6 +236,8 @@ internal fun shapedParts(slots: Map<String, Slot>, eveningPage: Long = 0): List<
// Evenings are appointments (Paul, 7 November 2026: Sakura's evening had 85 shows, each on once a week): at most
// EVENING_ROTATION shows a week, so each comes back most nights, and a different set the next week until all have had theirs.
bySlot[Slot.Evening] = eveningRotation(bySlot.getValue(Slot.Evening), eveningPage)
// Late nights the same way (Paul, 7 November 2026: Sakura's late had 52 shows), with a few more as the hours are longer.
bySlot[Slot.Late] = eveningRotation(bySlot.getValue(Slot.Late), eveningPage, LATE_ROTATION)
val gentle = bySlot.getValue(Slot.Daytime) + bySlot.getValue(Slot.Evening)
return Slot.entries.mapNotNull { s ->
val titles = bySlot.getValue(s).ifEmpty { if (s == Slot.Late) gentle + bySlot.getValue(Slot.Late) else gentle }
@@ -245,12 +247,14 @@ internal fun shapedParts(slots: Map<String, Slot>, eveningPage: Long = 0): List<
/** How many shows a shaped channel's evening carries in a week. */
internal const val EVENING_ROTATION = 12
/** How many shows a shaped channel's late nights carry in a week: eight hours a night, and enough that its films needn't repeat. */
internal const val LATE_ROTATION = 24
/** This week's evening shows from [titles]: all of them when there are few, else the week's turn of [EVENING_ROTATION]. */
internal fun eveningRotation(titles: List<String>, page: Long): List<String> {
if (titles.size <= EVENING_ROTATION) return titles
internal fun eveningRotation(titles: List<String>, page: Long, cap: Int = EVENING_ROTATION): List<String> {
if (titles.size <= cap) return titles
val sorted = titles.sortedBy { seriesKey(it) }
val pages = (sorted.size + EVENING_ROTATION - 1) / EVENING_ROTATION
val pages = (sorted.size + cap - 1) / cap
// Spread evenly, so the last week isn't a handful of leftovers.
val per = (sorted.size + pages - 1) / pages
val k = Math.floorMod(page, pages.toLong()).toInt()