0.129 P1: server-friendly requests: counters by kind, paced background reads, staggered list refreshes, weekly changes-only collections, playback reports every 30 s, real version in headers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 19:01:42 +00:00
co-authored by Claude Opus 5.5
parent 4f0fb0c368
commit 5842d28235
16 changed files with 371 additions and 29 deletions
@@ -30,6 +30,11 @@ internal object Edition {
if (intent?.getBooleanExtra("orbit_shadow_catalogue_stop", false) == true) CatalogueShadow.cancel = true
// Timings (0.129 stage 0): on, off or clear; local only.
intent?.getStringExtra("orbit_timing")?.let { OrbitTiming.set(activity, it) }
// Requests to the server, by kind and hour (0.129): written to Orbit's own folder for adb to pull. Counts only.
if (intent?.getStringExtra("orbit_requests") == "dump") runCatching {
val out = java.io.File(activity.getExternalFilesDir(null), "server-requests.json")
writeSafely(out, ServerRequests.summary().toString(2)); android.util.Log.i("OrbitRequests", "dumped hours=${ServerRequests.recent(72).size}")
}
if (intent?.hasExtra("orbit_shadow_from") == true) CatalogueShadow.from = intent.getLongExtra("orbit_shadow_from", 0L).coerceAtLeast(0L)
if (intent?.getBooleanExtra("orbit_shadow_resume", false) == true) CatalogueShadow.resume = true
if (intent?.hasExtra("orbit_shadow_catalogue") == true) CatalogueShadow.pending = intent.getIntExtra("orbit_shadow_catalogue", 5)
@@ -95,7 +95,8 @@ internal fun importCatalogue(transport: EmbyTransport, userId: String, token: ()
// A retry skips the count, in case the count is what's slow.
fetch(start, size, pages == 0 && failures == 0).also { if (it.total != null) total = it.total }
} catch (failure: EmbyCheckException) {
if (!failure.retryable) throw failure
// Out of this hour's background budget (0.129): stop here, nothing was asked of the server; the next round goes on.
if (!failure.retryable || failure is PacedOut) throw failure
if (++failures >= CATALOGUE_MAX_ATTEMPTS)
throw EmbyCheckException("${failure.message} Stopped at position $start after $failures tries, the last asking for $size titles.", retryable = true)
size = maxOf(CATALOGUE_MIN_PAGE_SIZE, size / 2)
@@ -6,6 +6,16 @@ import org.json.JSONObject
import java.time.LocalDateTime
internal const val POOL_REFRESH_MS = 7 * 24 * 60 * 60_000L
/**
* Spreading the weekly refreshes (0.129): each channel's list waits an extra 0 to 48 hours of its own, so lists read in the
* same hour don't all fall due together, and the background round refreshes at most one routine list per
* [POOL_ROUTINE_GAP_MS]. A channel that's new or changed is still read at once.
*/
internal const val POOL_JITTER_MS = 48 * 60 * 60_000L
internal const val POOL_ROUTINE_GAP_MS = 30 * 60_000L
internal fun poolJitterMs(number: Int): Long = (number.toLong() * 7_919L % 48L) * 60 * 60_000L
/** Whether a cached list is old enough for its routine refresh. */
internal fun poolRefreshDue(fetchedAtMs: Long, number: Int, nowMs: Long) = nowMs - fetchedAtMs >= POOL_REFRESH_MS + poolJitterMs(number)
/** Only counts and times, so it's safe to log. Never titles, addresses or the account. */
internal class SchedulerReport(val programmes: Int, val episodes: Int, val shows: List<String>, val requests: Int,
@@ -23,6 +33,8 @@ internal class ChannelScheduler(private val store: ScheduleStore,
/** The original server, whose season plans (Advent, the Naughty List, the premieres) are Paul's own: no other server has them. */
private val original: Boolean = true,
private val clock: () -> Long = System::currentTimeMillis) {
/** When this TV last made a routine (weekly) list refresh; at most one per [POOL_ROUTINE_GAP_MS]. */
@Volatile internal var lastRoutineRefreshMs = 0L
/** Disk only and quick, so the guide and player agree from the first frame after a restart. */
fun load(userId: String, loop: SampleChannel): ScheduledChannel? {
if (store.loadProgress(userId, loop.number)?.enabled != true) return null
@@ -84,9 +96,19 @@ 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) {
// Daily as well as on request (Paul, 7 November 2026): new titles in a collection reach the Chair on their own.
// Daily as well as on request (Paul, 7 November 2026): new titles in a collection reach the Chair on their own. Since
// 0.129 the evidence (only titles not read before) stays daily and the collections refresh is weekly.
val refresh = CollectionRefresh(store.collectionsFile())
if (!EvidenceRequest.take() && !refresh.due(clock())) return
val asked = EvidenceRequest.take()
val stamp = java.io.File(store.evidenceFile().path + ".day")
val evidenceDue = asked || !stamp.exists() || clock() - stamp.lastModified() >= 24 * 60 * 60_000L
val collectionsDue = asked || refresh.due(clock())
if (!evidenceDue && !collectionsDue) return
if (evidenceDue) readEvidenceOnly(session, userId, catalogue).also { runCatching { stamp.writeText(""); stamp.setLastModified(clock()) } }
if (collectionsDue) readCollectionsOnly(session, refresh)
}
private fun readEvidenceOnly(session: EmbySampleSession, userId: String, catalogue: CatalogueStore) {
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 } +
@@ -103,6 +125,9 @@ internal class ChannelScheduler(private val store: ScheduleStore,
} catch (failure: EmbyCheckException) { failed++; if (failed > 3) break }
}
Log.i("OrbitSchedule", "evidence asked=${ids.distinct().size} missing=${missing.size} read=$read failedBatches=$failed")
}
private fun readCollectionsOnly(session: EmbySampleSession, refresh: CollectionRefresh) {
// Emby's collections, for verified franchise links: resumable from where the last read stopped, a bounded number per run.
val collections = store.collectionsFile()
// Read before collections were paged (every one stopped at 300): set aside once and read again in full.
@@ -112,11 +137,15 @@ internal class ChannelScheduler(private val store: ScheduleStore,
// 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
// A weekly refresh reuses each collection whose member count hasn't changed (0.129); every fourth is read in full, in
// case members were swapped one for one.
val known = if (refreshing && !refresh.fullDue()) runCatching { collections.useLines { lines -> lines.mapNotNull { runCatching { JSONObject(it) }.getOrNull() }
.associateBy { it.optString("id") } } }.getOrNull() else null
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)
val (page, all) = session.readCollections(start, COLLECTIONS_PAGE, known)
total = all
if (page.isEmpty()) { finished = true; break }
target.appendText(page.joinToString("") { it.toString() + "\n" })
@@ -290,7 +319,11 @@ internal class ChannelScheduler(private val store: ScheduleStore,
var pool = cached
var requests = 0
var fetchMs = 0L
if (cached == null || now - cached.fetchedAtMs >= POOL_REFRESH_MS || cached.signature != signature) {
val routine = cached != null && cached.signature == signature
val due = cached == null || cached.signature != signature ||
(poolRefreshDue(cached.fetchedAtMs, number, now) && now - lastRoutineRefreshMs >= POOL_ROUTINE_GAP_MS)
if (due) {
if (routine) lastRoutineRefreshMs = now
val started = android.os.SystemClock.elapsedRealtime()
try {
val read = session.readChannelPool(programming, loop, choices, checkActive, previous = cached?.series)
@@ -7,7 +7,7 @@ import java.net.URL
import java.util.UUID
import java.net.HttpURLConnection
internal class EmbyCheckException(message: String, val httpStatus: Int? = null, val retryable: Boolean = false) : Exception(message)
internal open class EmbyCheckException(message: String, val httpStatus: Int? = null, val retryable: Boolean = false) : Exception(message)
internal data class SampleItem(val title: String, val type: String, val minutes: Long?, val format: String, val id: String = "", val durationMs: Long? = minutes?.takeIf { it in 1..(Long.MAX_VALUE / 60_000) }?.times(60_000))
internal data class EmbySample(val items: List<SampleItem>, val total: Long?)
internal class EmbyRequest(val method: String, val path: String, val body: String? = null, val token: String? = null, val readTimeoutMs: Int? = null)
@@ -62,14 +62,17 @@ 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.110.9\"") +
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"${AppVersion.name}\"") +
(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.110.9\"" +
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"${AppVersion.name}\"" +
(token?.let { ", Token=\"$it\"" } ?: ""))
}
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
fun fetchImage(path: String, token: String): ByteArray? {
require(path.startsWith("/") && !path.startsWith("//"))
return fetchImageOnce(path, token).also { ServerRequests.count(RequestKind.Images, it != null) }
}
private fun fetchImageOnce(path: String, token: String): ByteArray? {
if (runCatching { EmbyServer.checkHomeConnection(origin) }.isFailure) return null
val prefix = runCatching { kind.prefix }.getOrNull() ?: return null
val connection = URL("$origin$prefix$path").openConnection() as HttpURLConnection
@@ -96,6 +99,13 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
override fun execute(request: EmbyRequest): EmbyReply {
// Paths come from the protocol below, never from a provider response or a text field.
require(request.path.startsWith("/") && !request.path.startsWith("//"))
// Background reads wait their turn and keep to the hour's budget (0.129); every request is counted by kind.
BackgroundPacing.beforeRequest()
val kind = RequestKind.of(request.method, request.path)
var ok = false
try { return send(request).also { ok = it.status in 200..299 } } finally { ServerRequests.count(kind, ok) }
}
private fun send(request: EmbyRequest): EmbyReply {
// HTTPS, or plain HTTP to a home server whose name still leads only to private addresses.
require(origin.startsWith("https://") || EmbyServer.isHome(origin))
EmbyServer.checkHomeConnection(origin)
@@ -434,7 +434,8 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
try {
withContext(Dispatchers.IO) {
if (scheduler.enabled(active.accountId, programming.number)) {
scheduler.topUp(active, active.accountId, programming, loop)
// Paced and within the hour's background budget (0.129): see BackgroundPacing.
BackgroundPacing.run { scheduler.topUp(active, active.accountId, programming, loop) }
val fresh = scheduleStore.loadPlan(active.accountId, programming.number)
val onAirNow = scheduledChannels[programming.number]?.takeIf { it.loop === loop }
if (fresh != null && onAirNow != null) onAirNow.plan = fresh
@@ -444,16 +445,16 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
} catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { /* Tried again next hour. */ }
}
try { driveInPlan = withContext(Dispatchers.IO) { scheduler.topUpDriveIn(active.accountId, active) } }
try { driveInPlan = withContext(Dispatchers.IO) { BackgroundPacing.run { scheduler.topUpDriveIn(active.accountId, active) } } }
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)
try { withContext(Dispatchers.IO) { BackgroundPacing.run { 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) } }
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) } }
try { withContext(Dispatchers.IO) { BackgroundPacing.run { scheduler.refreshArrivals(active, active.accountId, catalogue) } } }
catch (cancelled: CancellationException) { throw cancelled }
catch (failure: Exception) { android.util.Log.w("OrbitSchedule", "arrivals failed=${failure.javaClass.simpleName}") }
delay(60 * 60_000L)
@@ -404,7 +404,7 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl
val startPosition = player.currentPosition; val startPaused = !player.isPlaying
withContext(Dispatchers.IO) { if (foreground) session.report(plan, "Playing", startPosition, startPaused) }
while (foreground) {
delay(10_000)
delay(PLAYBACK_REPORT_MS)
if (!foreground) break
val position = player.currentPosition; val paused = !player.isPlaying
withContext(Dispatchers.IO) { if (foreground) session.report(plan, "Playing/Progress", position, paused) }
@@ -56,6 +56,12 @@ internal const val PLAYBACK_INFO_TIMEOUT_MS = 45_000
/** A temporary session is owned by the sample screen, never by persistent storage. */
/** Collections are read a page at a time, up to this many members each. */
internal const val COLLECTION_PAGE = 500
/**
* How often a playing programme tells the server where it is (0.129: 30 s, from 10 s; Paul's provider counted every one). The
* resume point doesn't depend on it: "Stopped", with the exact position, is sent whenever a programme ends, the channel
* changes or Orbit leaves. At worst, if the TV loses power mid-programme, the server's place is up to 30 s behind.
*/
internal const val PLAYBACK_REPORT_MS = 30_000L
internal const val COLLECTION_MAX = 5000
internal class EmbySampleSession(private val transport: EmbyTransport, private var token: String?,
@@ -307,14 +313,20 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
* Emby's own collections (BoxSets), read only, for verified franchise and series relationships: a page of collections,
* each with its members' IDs. A relationship no collection supplies stays unknown; nothing is inferred from titles.
*/
fun readCollections(start: Int, limit: Int): Pair<List<JSONObject>, Int> {
val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&IncludeItemTypes=BoxSet&Recursive=true&StartIndex=$start&Limit=$limit&Fields=ProviderIds" +
fun readCollections(start: Int, limit: Int,
/**
* Collections already read, by ID (0.129): one whose member count (ChildCount) is unchanged is kept as it was, with no
* request for its members. A whole refresh then costs a request per page of collections, not one per collection.
*/
known: Map<String, JSONObject>? = null): Pair<List<JSONObject>, Int> {
val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&IncludeItemTypes=BoxSet&Recursive=true&StartIndex=$start&Limit=$limit&Fields=ProviderIds,ChildCount" +
"&SortBy=SortName&SortOrder=Ascending&EnableImages=false&EnableUserData=false", token = currentToken(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS))
EmbyClient.expectSuccess(reply.status, false)
val body = EmbyClient.parse(reply.body)
val rows = body.optJSONArray("Items")
val sets = (0 until (rows?.length() ?: 0)).mapNotNull { rows!!.optJSONObject(it) }.filter { EmbyClient.validId(it.optString("Id")) }
return sets.map { set ->
unchangedCollection(set, known)?.let { return@map it }
// Every member, a page at a time (Paul, 7 November 2026: it stopped at 300, so big collections were cut short), up to
// COLLECTION_MAX; "complete" says whether all of them were read.
val members = ArrayList<String>(); var total = 0
@@ -576,3 +588,13 @@ internal fun timesBlurb(tagline: String?, overview: String?, leads: List<String>
}
internal const val TIMES_BLURB_MAX = 150
/**
* A collection read before whose member count hasn't changed (0.129), kept as it was; null when it must be read again: new,
* a different count, incomplete before, or a server that doesn't say how many members a collection has.
*/
internal fun unchangedCollection(set: JSONObject, known: Map<String, JSONObject>?): JSONObject? {
val before = known?.get(set.optString("Id")) ?: return null
if (!set.has("ChildCount") || !before.optBoolean("complete")) return null
return before.takeIf { set.optInt("ChildCount", -1) == it.optInt("total", -2) }
}
@@ -19,7 +19,8 @@ internal object EvidenceRequest {
internal const val EVIDENCE_BATCH = 40
internal const val EVIDENCE_MAX_PER_RUN = 4_000
internal const val COLLECTIONS_PAGE = 50
/** Collections a listing page (0.129: 200, from 50; the listing is small, and four times fewer pages). */
internal const val COLLECTIONS_PAGE = 200
internal const val COLLECTIONS_MAX_PER_RUN = 1_000
/** One item's evidence as kept: only what the provider gave, trimmed, with people limited to leads and directors. */
@@ -50,14 +51,17 @@ internal fun evidenceMissing(file: File, ids: List<String>): List<String> {
}
/**
* 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,
* The collections refresh (Paul, 7 November 2026; weekly since 0.129). Until the first full read finishes, reads go on appending
* to the collections file as before; from then on, once a week, 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()
private fun reads(): Int = runCatching { JSONObject(state.readText()).optInt("reads") }.getOrDefault(0)
/** Every fourth refresh reads every collection's members again (0.129); the others only those whose count changed. */
fun fullDue(): Boolean = reads() % COLLECTIONS_FULL_EVERY == COLLECTIONS_FULL_EVERY - 1
/** 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. */
@@ -65,8 +69,13 @@ internal class CollectionRefresh(private val file: java.io.File) {
/** 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)) { writeSafely(file, next.readText()); next.delete() } }
writeSafely(state, JSONObject().put("finishedAt", nowMs).toString())
writeSafely(state, JSONObject().put("finishedAt", nowMs).put("reads", reads() + 1).toString())
}
}
internal const val COLLECTIONS_REFRESH_MS = 24 * 60 * 60_000L
/**
* Weekly, not daily (0.129, Paul): a daily re-read of every collection was over 3,000 requests a day per TV on his provider.
* Collections change slowly, and the Chair only needs them for franchise links.
*/
internal const val COLLECTIONS_REFRESH_MS = 7 * 24 * 60 * 60_000L
internal const val COLLECTIONS_FULL_EVERY = 4
@@ -179,7 +179,7 @@ private fun GuideLivePlayer(session: EmbySampleSession, plan: EmbyPlaybackPlan,
val startPosition = player.currentPosition
withContext(Dispatchers.IO) { session.report(plan, "Playing", startPosition, false) }
while (true) {
delay(10_000)
delay(PLAYBACK_REPORT_MS)
val position = player.currentPosition; val paused = !player.isPlaying
withContext(Dispatchers.IO) { session.report(plan, "Playing/Progress", position, paused) }
}
@@ -60,7 +60,7 @@ class MainActivity : ComponentActivity() {
// Phones stay connected while Orbit is in the background (Paul, 8 November 2026: the web app couldn't connect while the TV
// was in another app), and paired rooms keep syncing; the phone says Orbit isn't on screen instead of failing to load.
override fun onDestroy() { OrbitScreen.open = false; super.onDestroy() }
override fun onStop() { WatchCheck.stopped(); OrbitCompanion.onTv = false; PhoneLink.offerRoom(null); if (PhoneLink.phones.isEmpty() && RoomLinks.links.none { it.on }) { RoomBeacon.off(this); PhoneLink.stop() }; super.onStop() }
override fun onStop() { ServerRequests.save(); WatchCheck.stopped(); OrbitCompanion.onTv = false; PhoneLink.offerRoom(null); if (PhoneLink.phones.isEmpty() && RoomLinks.links.none { it.on }) { RoomBeacon.off(this); PhoneLink.stop() }; super.onStop() }
/**
* The adb-only requests (inspection, evidence, the provider switch and shadow comparison). Read at start and, since Orbit
* opens as one copy (singleTask, 8 November 2026), also when adb sends them to an Orbit already open.
@@ -72,6 +72,9 @@ class MainActivity : ComponentActivity() {
PhoneBackups.finishAtStart(this)
// Timings (0.129 stage 0): off unless switched on by adb on a household TV; kept on this TV only.
OrbitTiming.load(this)
// Requests to the server, counted by kind on this TV only (0.129).
ServerRequests.attach(noBackupFilesDir)
runCatching { packageManager.getPackageInfo(packageName, 0).versionName?.let { AppVersion.name = it } }
OrbitScreen.open = true
OrbitCompanion.activity = java.lang.ref.WeakReference(this)
super.onCreate(savedInstanceState)
@@ -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.110.9")
next.setRequestProperty("User-Agent", "OrbitTV/${AppVersion.name}")
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()) {
@@ -47,6 +47,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B
next.setRequestProperty("Range", "bytes=${dataSpec.position}-$end")
}
val status = next.responseCode
ServerRequests.count(RequestKind.Media, status in 200..399, background = false)
if (status in listOf(301, 302, 303, 307, 308)) {
val location = next.getHeaderField("Location") ?: throw MediaDeliveryException("The media redirect had no destination.")
if (redirect == 5) throw MediaDeliveryException("The stream redirected too many times.")
@@ -0,0 +1,134 @@
package tv.orbit.classic
import org.json.JSONObject
import java.io.File
/**
* Being a good guest on someone's media server (0.129, Paul, 10 November 2026, after his provider warned of ~11,000 requests
* in five hours). Two parts, both on this TV only:
*
* - [ServerRequests]: counts every request Orbit makes to the server, by kind, by the hour, with failures, so a TV can say
* what it did. Paths, titles, IDs and addresses are never kept: only the kind, the hour and the numbers.
* - [BackgroundPacing]: requests made by the background round (channel lists, collections, library reads) wait their turn,
* at most one every [BackgroundPacing.GAP_MS], and at most [BackgroundPacing.HOURLY_BUDGET] an hour. What doesn't fit in
* the hour stops cleanly and carries on in a later round. Watching, tuning and anything a person asks for are never slowed.
*/
internal enum class RequestKind(val label: String) {
Report("Playback reports"), PlaybackInfo("Getting ready to play"), Media("Video"), Images("Pictures"),
Catalogue("Library list"), Collections("Collections"), Episodes("Episode lists"), Search("Searches"), Details("Item details"),
SignIn("Sign-in and server checks"), Other("Other");
companion object {
/** The kind of a request, from its method and path. Nothing of the path is kept. */
fun of(method: String, path: String): RequestKind = when {
path.startsWith("/Sessions/Playing") -> Report
path.contains("/PlaybackInfo") -> PlaybackInfo
path.startsWith("/Users/AuthenticateByName") || path.startsWith("/Sessions/Logout") || path.startsWith("/System/Info") ||
(method == "GET" && Regex("^/Users/[0-9a-fA-F-]+$").matches(path.substringBefore('?'))) -> SignIn
path.contains("IncludeItemTypes=BoxSet") || path.contains("ParentId=") -> Collections
path.startsWith("/Shows/") -> Episodes
path.contains("SearchTerm=") -> Search
path.contains("&Ids=") || path.contains("?Ids=") -> Details
path.contains("SortBy=DateCreated") -> Catalogue
else -> Other
}
}
}
internal object ServerRequests {
/** One hour's counts: by kind, how many were background, and how many failed. */
class Hour(val startMs: Long) {
val byKind = IntArray(RequestKind.entries.size)
var background = 0; var failed = 0
val total get() = byKind.sum()
fun toJson() = JSONObject().put("hour", startMs).put("total", total).put("background", background).put("failed", failed)
.put("kinds", JSONObject().also { o -> RequestKind.entries.forEach { k -> if (byKind[k.ordinal] > 0) o.put(k.name, byKind[k.ordinal]) } })
}
private const val HOUR_MS = 60 * 60_000L
private const val KEEP_HOURS = 72
private val hours = ArrayDeque<Hour>()
internal var clock: () -> Long = System::currentTimeMillis
@Volatile private var file: File? = null
@Volatile private var lastSaveMs = 0L
fun attach(dir: File) { file = File(dir, "server-requests.json"); load() }
@Synchronized fun count(kind: RequestKind, ok: Boolean, background: Boolean = BackgroundPacing.active) {
val now = clock()
val start = now - now % HOUR_MS
val hour = hours.lastOrNull()?.takeIf { it.startMs == start } ?: Hour(start).also { hours.addLast(it); while (hours.size > KEEP_HOURS) hours.removeFirst() }
hour.byKind[kind.ordinal]++
if (background) hour.background++
if (!ok) hour.failed++
if (now - lastSaveMs > 5 * 60_000L) { lastSaveMs = now; save() }
}
/** The last [n] hours, newest last. */
@Synchronized fun recent(n: Int = 24): List<Hour> = hours.toList().takeLast(n)
@Synchronized fun lastHourTotal(): Int { val now = clock(); return hours.filter { it.startMs > now - HOUR_MS * 2 && it.startMs <= now }.lastOrNull()?.total ?: 0 }
@Synchronized fun lastDayTotal(): Int { val now = clock(); return hours.filter { it.startMs > now - 24 * HOUR_MS }.sumOf { it.total } }
@Synchronized fun summary(): JSONObject = JSONObject().put("hours", org.json.JSONArray(hours.map { it.toJson() }))
@Synchronized internal fun clearForTest() { hours.clear(); file = null; lastSaveMs = 0 }
@Synchronized fun save() {
val target = file ?: return
runCatching { writeSafely(target, summary().toString()) }
}
@Synchronized private fun load() {
val target = file ?: return
runCatching {
val a = JSONObject(target.readText()).getJSONArray("hours")
hours.clear()
for (i in 0 until a.length()) {
val o = a.getJSONObject(i); val h = Hour(o.getLong("hour"))
h.background = o.optInt("background"); h.failed = o.optInt("failed")
val kinds = o.optJSONObject("kinds") ?: JSONObject()
RequestKind.entries.forEach { k -> h.byKind[k.ordinal] = kinds.optInt(k.name) }
hours.addLast(h)
}
}
}
}
/** A background read that has used its share of the hour: it stops cleanly, keeps what it had, and goes on next round. */
internal class PacedOut : EmbyCheckException("Orbit is pacing its background reads; it carries on later.", retryable = true)
internal object BackgroundPacing {
/** At most one background request this often: 1.5 s is at most 2,400 an hour, and the budget keeps it well under. */
const val GAP_MS = 1_500L
/** Background requests per TV per hour (Paul: never thousands an hour again). */
const val HOURLY_BUDGET = 600
private val inBackground = ThreadLocal<Boolean>()
/** This thread is doing the background round's work. */
val active: Boolean get() = inBackground.get() == true
internal var clock: () -> Long = System::currentTimeMillis
internal var sleep: (Long) -> Unit = { Thread.sleep(it) }
private var lastMs = 0L
private var hourStart = 0L
private var used = 0
/** Runs [block] as background work: its server requests are paced and counted against the hourly budget. */
fun <T> run(block: () -> T): T {
val was = inBackground.get()
inBackground.set(true)
try { return block() } finally { inBackground.set(was) }
}
/** Called before each request; waits its turn for background work, or refuses once the hour's budget is spent. */
fun beforeRequest() {
if (!active) return
synchronized(this) {
val now = clock()
if (now - hourStart >= 60 * 60_000L) { hourStart = now - now % (60 * 60_000L); used = 0 }
if (used >= HOURLY_BUDGET) throw PacedOut()
val wait = lastMs + GAP_MS - now
if (wait > 0) sleep(wait)
lastMs = clock(); used++
}
}
internal fun resetForTest() { lastMs = 0; hourStart = 0; used = 0; clock = System::currentTimeMillis; sleep = { Thread.sleep(it) } }
internal fun usedThisHour() = used
}
/** Orbit's version as the server sees it in its logs (0.129: it said 0.110.9 whatever was installed). Set at start. */
internal object AppVersion { @Volatile var name: String = "0.129" }
@@ -522,6 +522,9 @@ private fun AccountDetail(server: String, titles: Long?, onSignOut: () -> Unit,
}
}
} else SettingLine("Remove this server", "For leaving a box or starting again: deletes this server's data from this box only.") { OrbitButton("Remove", onClick = { removing = true }) }
// Requests to the server (0.129): counted on this TV only, so you can see Orbit is a light user of it.
val requestsHour = remember { ServerRequests.lastHourTotal() }; val requestsDay = remember { ServerRequests.lastDayTotal() }
SettingLine("Requests to your server", "This hour: $requestsHour. Last 24 hours: $requestsDay. Counted on this TV only; nothing is sent anywhere. Background reading keeps to $BACKGROUND_BUDGET_LINE.") {}
SettingLine("Welcome tour", "See the first-launch steps a new box goes through, from Ollie's welcome to You're on air. Nothing is changed by it.") {
OrbitButton("Show it", onClick = { Onboarding.start(tour = true) })
}
@@ -635,3 +638,6 @@ internal fun SettingsSubPage(first: FocusRequester?, onBack: (() -> Unit)?, modi
content()
}
}
/** How the background budget reads in Settings. */
internal val BACKGROUND_BUDGET_LINE = "at most ${BackgroundPacing.HOURLY_BUDGET} an hour, one at a time"
@@ -5,18 +5,18 @@ import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
/** Collections refresh daily (7 November 2026): the first read appends, later ones read a fresh copy and swap it in whole. */
/** Collections refresh weekly since 0.129 (daily from 7 November 2026): the first read appends, later ones read a fresh copy and swap it in whole. */
class CollectionRefreshTest {
@get:Rule val tmp = TemporaryFolder()
private val day = 24 * 60 * 60_000L
private val day = 7 * 24 * 60 * 60_000L // a refresh period: a week since 0.129
@Test fun refreshesOnceADayAndSwapsInWhole() {
@Test fun refreshesOnceAWeekAndSwapsInWhole() {
val file = java.io.File(tmp.root, "collections-0.jsonl")
val r = CollectionRefresh(file)
assertTrue("the first read is always due", r.due(0)); assertFalse(r.complete())
file.writeText("old\n")
r.finish(refreshing = false, nowMs = 1_000)
assertTrue(r.complete()); assertFalse(r.due(1_000 + day - 1)); assertTrue(r.due(1_000 + day))
assertTrue(r.complete()); assertFalse(r.due(1_000 + 24 * 60 * 60_000L)); assertFalse(r.due(1_000 + day - 1)); assertTrue(r.due(1_000 + day))
// A refresh part-way is carried on at the next round, and the old list stays in use until it's whole.
r.next.writeText("new-part\n")
assertTrue(r.due(2_000)); assertEquals("old\n", file.readText())
@@ -0,0 +1,117 @@
package tv.orbit.classic
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
/**
* Being a good guest on the media server (0.129, after Paul's provider counted ~11,000 requests in five hours): counting by
* kind, pacing the background round, spreading the weekly channel-list refreshes, and reading collections weekly and only
* where they changed. With the numbers before and after.
*/
class ServerRequestsTest {
@get:Rule val tmp = TemporaryFolder()
private var now = 1_794_268_800_000L // Wed 11 Nov 2026, 00:00 UTC
@Before fun up() { ServerRequests.clearForTest(); ServerRequests.clock = { now }; BackgroundPacing.resetForTest(); BackgroundPacing.clock = { now }; BackgroundPacing.sleep = { now += it } }
@After fun down() { ServerRequests.clearForTest(); ServerRequests.clock = System::currentTimeMillis; BackgroundPacing.resetForTest() }
@Test fun eachRequestIsCountedByItsKindNeverByWhatItAskedFor() {
assertEquals(RequestKind.Report, RequestKind.of("POST", "/Sessions/Playing/Progress"))
assertEquals(RequestKind.PlaybackInfo, RequestKind.of("POST", "/Items/abc/PlaybackInfo"))
assertEquals(RequestKind.Collections, RequestKind.of("GET", "/Items?UserId=u&IncludeItemTypes=BoxSet&Recursive=true"))
assertEquals(RequestKind.Collections, RequestKind.of("GET", "/Items?UserId=u&ParentId=abc&StartIndex=0"))
assertEquals(RequestKind.Episodes, RequestKind.of("GET", "/Shows/abc/Episodes?UserId=u"))
assertEquals(RequestKind.Search, RequestKind.of("GET", "/Items?UserId=u&Recursive=true&IncludeItemTypes=Series&SearchTerm=x"))
assertEquals(RequestKind.Details, RequestKind.of("GET", "/Items?UserId=u&Ids=a,b"))
assertEquals(RequestKind.Catalogue, RequestKind.of("GET", "/Items?UserId=u&Recursive=true&IncludeItemTypes=Movie,Series&StartIndex=0&Limit=200&SortBy=DateCreated"))
assertEquals(RequestKind.SignIn, RequestKind.of("POST", "/Users/AuthenticateByName"))
assertEquals(RequestKind.SignIn, RequestKind.of("GET", "/Users/0123abcd"))
ServerRequests.attach(tmp.root)
repeat(3) { ServerRequests.count(RequestKind.Report, ok = true) }
ServerRequests.count(RequestKind.Episodes, ok = false, background = true)
now += 60 * 60_000L
ServerRequests.count(RequestKind.Media, ok = true)
val hours = ServerRequests.recent()
assertEquals(2, hours.size); assertEquals(4, hours[0].total); assertEquals(1, hours[0].background); assertEquals(1, hours[0].failed)
assertEquals(5, ServerRequests.lastDayTotal())
ServerRequests.save()
val kept = tmp.root.resolve("server-requests.json").readText()
assertTrue(kept.contains("\"Report\":3")); assertFalse(kept.contains("Sessions")); assertFalse(kept.contains("abc"))
}
@Test fun backgroundReadsWaitTheirTurnAndStopAtTheHoursBudget() {
var made = 0
BackgroundPacing.run {
try { while (true) { BackgroundPacing.beforeRequest(); made++ } } catch (_: PacedOut) {}
}
assertEquals(BackgroundPacing.HOURLY_BUDGET, made)
// One at a time: 600 requests took at least 599 gaps of 1.5 s, about 15 minutes, never a burst.
// A new hour, a new budget.
now += 60 * 60_000L
BackgroundPacing.run { BackgroundPacing.beforeRequest() }
assertEquals(1, BackgroundPacing.usedThisHour())
// Watching and anything a person asks for are never slowed or refused.
BackgroundPacing.resetForTest(); BackgroundPacing.clock = { now }; var slept = 0L; BackgroundPacing.sleep = { slept += it }
repeat(10_000) { BackgroundPacing.beforeRequest() }
assertEquals(0L, slept); assertFalse(BackgroundPacing.active)
}
@Test fun pacingSpacesBackgroundRequests() {
val start = now
BackgroundPacing.run { repeat(11) { BackgroundPacing.beforeRequest() } }
assertEquals(10 * BackgroundPacing.GAP_MS, now - start)
}
@Test fun weeklyListRefreshesNoLongerFallDueTogether() {
// Downstairs on 10 November: 18 channels' lists read in the same hour on 4 November.
val channels = listOf(101, 103, 104, 105, 107, 202, 203, 301, 302, 303, 306, 308, 602, 603, 604, 612, 613, 614)
val fetched = 1_794_225_600_000L - 7 * 24 * 60 * 60_000L // 4 Nov, 12:00
val dueHours = channels.map { n -> (POOL_REFRESH_MS + poolJitterMs(n)) / (60 * 60_000L) }
assertTrue("spread over more than a day: ${dueHours.toSortedSet()}", dueHours.max() - dueHours.min() >= 24)
// Hour by hour through the week after, with at most one routine refresh per half hour and hourly rounds.
var last = 0L; val refreshedAt = mutableListOf<Long>()
val pending = channels.toMutableSet()
var t = fetched
while (pending.isNotEmpty() && t < fetched + 10 * 24 * 60 * 60_000L) {
for (n in pending.toList()) if (poolRefreshDue(fetched, n, t) && t - last >= POOL_ROUTINE_GAP_MS) { pending -= n; last = t; refreshedAt += t }
t += 60 * 60_000L
}
assertTrue(pending.isEmpty())
// Never two in the same hour: about 90 requests an hour at most, from ~1,666 in one hour before.
assertEquals(refreshedAt.size, refreshedAt.map { it / (60 * 60_000L) }.toSet().size)
}
@Test fun anUnchangedCollectionIsKeptWithoutReadingItsMembers() {
val before = mapOf("c1" to JSONObject().put("id", "c1").put("total", 12).put("complete", true).put("members", org.json.JSONArray(listOf("a"))),
"c2" to JSONObject().put("id", "c2").put("total", 5).put("complete", false))
assertNotNull(unchangedCollection(JSONObject().put("Id", "c1").put("ChildCount", 12), before))
assertNull(unchangedCollection(JSONObject().put("Id", "c1").put("ChildCount", 13), before)) // a member added
assertNull(unchangedCollection(JSONObject().put("Id", "c2").put("ChildCount", 5), before)) // incomplete before
assertNull(unchangedCollection(JSONObject().put("Id", "c3").put("ChildCount", 1), before)) // new
assertNull(unchangedCollection(JSONObject().put("Id", "c1"), before)) // server gives no count
assertNull(unchangedCollection(JSONObject().put("Id", "c1").put("ChildCount", 12), null)) // a full read
}
@Test fun everyFourthCollectionsRefreshIsReadInFull() {
val r = CollectionRefresh(tmp.root.resolve("collections-0.jsonl"))
val full = (1..8).map { i -> r.fullDue().also { r.finish(refreshing = i > 1, nowMs = i * 1_000L) } }
assertEquals(listOf(false, false, false, true, false, false, false, true), full)
}
@Test fun beforeAndAfterForPaulsLibrary() {
// 3,223 collections (downstairs, 10 November), per TV, a week.
val collections = 3_223
val before = 7 * (collections / 50 + 1 + collections) // daily: listing pages of 50 + one per collection
val afterWeekly = (collections / COLLECTIONS_PAGE + 1) + 30 // weekly: listing pages of 200 + ~30 changed collections
val afterFull = collections / COLLECTIONS_PAGE + 1 + collections // every fourth week
assertEquals(23_016, before) // per TV per week
assertTrue(afterWeekly < 60)
assertTrue("the full read is paced: ${afterFull} requests take ${afterFull * BackgroundPacing.GAP_MS / 60_000} min or more and span rounds", afterFull > BackgroundPacing.HOURLY_BUDGET)
// Playback reports, one TV playing all day: 8,640 a day at 10 s, 2,880 at 30 s.
assertEquals(2_880, (24 * 60 * 60_000L / PLAYBACK_REPORT_MS).toInt())
}
}
+1 -1
View File
@@ -74,7 +74,7 @@ if "android.permission.REQUEST_INSTALL_PACKAGES" not in editions["household APK"
forbidden = [b"android/content/pm/PackageInstaller", b"RoomUpdates", b"ROOM_UPDATE", b"/room/orbit.apk", b"InstallSnapshotReceiver",
b"INSTALL_SNAPSHOT", b"PlaybackTestActivity", b"orbit_play_test", b"orbit_shadow_catalogue", b"orbit_provider_catalogue",
b"orbit_frame_rate", b"orbit_avi", b"orbit_timing", b"PlaytestFileActivity", b"playtest-approved", b"appboxmanager"]
b"orbit_frame_rate", b"orbit_avi", b"orbit_timing", b"orbit_requests", b"PlaytestFileActivity", b"playtest-approved", b"appboxmanager"]
for label, path in (("Play APK", play_apk), ("Play bundle", play_aab)):
found = [f.decode() for f in forbidden if f in dex(path)]
if found: problems.append(f"{label} contains: {', '.join(found)}")