Merge branch 'provider-contract' into integration-0.110.9

# Conflicts:
#	android/app/build.gradle.kts
This commit is contained in:
2026-11-08 22:32:03 +00:00
16 changed files with 984 additions and 9 deletions
@@ -76,7 +76,9 @@ internal fun fetchCataloguePage(transport: EmbyTransport, userId: String, token:
*/
internal fun importCatalogue(transport: EmbyTransport, userId: String, token: () -> String, sink: CatalogueSink,
maxPages: Int = CATALOGUE_PAGES_PER_RUN, pause: () -> Unit = {}, checkActive: () -> Unit = {}, onPage: () -> Unit = {},
backoff: (Int) -> Unit = {}, onRetry: (Int) -> Unit = {}): CatalogueRun {
backoff: (Int) -> Unit = {}, onRetry: (Int) -> Unit = {},
/** Where a page comes from: today's reader, unless the provider switch routes it through the contract (step 3). */
fetch: (start: Long, size: Int, withTotal: Boolean) -> CataloguePage = { start, size, withTotal -> fetchCataloguePage(transport, userId, token, start, size, withTotal) }): CatalogueRun {
require(maxPages in 1..CATALOGUE_PAGES_FULL_RUN)
var start = sink.position(userId)
var pages = 0
@@ -91,7 +93,7 @@ internal fun importCatalogue(transport: EmbyTransport, userId: String, token: ()
val began = System.currentTimeMillis()
val page = try {
// A retry skips the count, in case the count is what's slow.
fetchCataloguePage(transport, userId, token, start, size, pages == 0 && failures == 0).also { if (it.total != null) total = it.total }
fetch(start, size, pages == 0 && failures == 0).also { if (it.total != null) total = it.total }
} catch (failure: EmbyCheckException) {
if (!failure.retryable) throw failure
if (++failures >= CATALOGUE_MAX_ATTEMPTS)
@@ -116,3 +118,19 @@ internal fun importCatalogue(transport: EmbyTransport, userId: String, token: ()
}
return result(false)
}
/**
* A catalogue page read through the provider contract (step 3, 8 November 2026), shaped exactly as today's reader
* returns it, so the same import loop (resume, smaller pages on a slow answer, back-off) runs unchanged. The contract's
* failures go back to the kinds that loop knows: unreachable is retryable, a sign-in failure stops it as a 401 does.
*/
internal fun cataloguePageVia(provider: MediaProvider, start: Long, size: Int, withTotal: Boolean): CataloguePage = try {
val page = kotlinx.coroutines.runBlocking { provider.catalogue(PageRequest(start.toInt(), size, withTotal)) }
CataloguePage(page.items.map(::catalogueRecordOf), (page.next - start.toInt()).coerceAtLeast(0), page.total.takeIf { withTotal && it >= 0 }?.toLong())
} catch (f: ProviderException) {
throw when (f.error) {
ProviderError.Unreachable -> EmbyCheckException(f.message.orEmpty(), retryable = true)
ProviderError.Authentication -> EmbyCheckException(f.message.orEmpty(), 401)
else -> EmbyCheckException(f.message.orEmpty())
}
}
@@ -0,0 +1,108 @@
package tv.orbit.classic
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* The provider switches (step 3, 8 November 2026). Each routes one existing path through the provider contract; all are
* off by default, and today's path stays the immediate fallback. Set from adb only, kept in Orbit's settings:
* am start -n tv.orbit.classic/.MainActivity --es orbit_provider_catalogue on|off
*/
internal object ProviderSwitches {
@Volatile var catalogue = false
private const val KEY = "provider_catalogue"
fun load(context: Context) { catalogue = context.getSharedPreferences("orbit_settings", Context.MODE_PRIVATE).getBoolean(KEY, false) }
fun setCatalogue(context: Context, on: Boolean) {
catalogue = on; context.getSharedPreferences("orbit_settings", Context.MODE_PRIVATE).edit().putBoolean(KEY, on).apply()
android.util.Log.i("OrbitProvider", "catalogue switch=${if (on) "on" else "off"}")
}
}
/**
* The read-only shadow comparison (step 3): today's catalogue reader and the provider path read the same pages side by
* side, and every page is compared (ids, every stored field, paging, totals). It never writes the live catalogue: nothing
* here touches CatalogueStore. It records time, memory and errors, writes a report, and keeps a sanitised copy of the
* first raw pages (titles, people and ids outside Orbit replaced, structure kept) as a test fixture. Asked for from adb:
* am start -n tv.orbit.classic/.MainActivity --ei orbit_shadow_catalogue <pages, 0 = the whole library>
* The report lands in Orbit's shared folder, shadow-catalogue/, for adb to pull. Counts and ids only; no titles.
*/
internal object CatalogueShadow {
/** Pages asked for; null when no comparison is waiting. */
@Volatile var pending: Int? = null
private const val FIXTURE_PAGES = 3
fun runIfPending(session: EmbySampleSession, context: Context) {
val pages = pending ?: return
pending = null
val out = File(context.getExternalFilesDir(null), "shadow-catalogue").apply { deleteRecursively(); mkdirs() }
val raw = mutableListOf<String>()
val report = compare(
today = { start, size, withTotal -> session.cataloguePageRecorded(start, size, withTotal) { if (raw.size < FIXTURE_PAGES) raw += it } },
viaProvider = { start, size, withTotal -> cataloguePageVia(session.provider(), start, size, withTotal) },
maxPages = if (pages <= 0) CATALOGUE_PAGES_FULL_RUN else pages)
File(out, "report.json").writeText(report.toString(2))
raw.forEachIndexed { i, body -> File(out, "page-$i.json").writeText(sanitiseCataloguePage(body).toString()) }
android.util.Log.i("OrbitProvider", "shadow catalogue pages=${report.optInt("pages")} same=${report.optBoolean("identical")} mismatches=${report.optInt("mismatches")}")
}
/**
* Reads [maxPages] pages from both paths, the same way today's import does (counted first page, CATALOGUE_PAGE_SIZE rows),
* and compares them. Pure: pass any two readers. The report holds counts, timings, memory and the first mismatching ids.
*/
fun compare(today: (Long, Int, Boolean) -> CataloguePage, viaProvider: (Long, Int, Boolean) -> CataloguePage, maxPages: Int,
heapUsed: () -> Long = { Runtime.getRuntime().let { it.totalMemory() - it.freeMemory() } }): JSONObject {
var start = 0L; var pages = 0; var mismatches = 0; var records = 0
var todayMs = 0L; var providerMs = 0L; var peakHeap = heapUsed(); val heapBefore = peakHeap
val firstMismatches = JSONArray(); var error: String? = null; var total: Long? = null
while (pages < maxPages) {
val withTotal = pages == 0
val a: CataloguePage; val b: CataloguePage
try {
var t = System.nanoTime(); a = today(start, CATALOGUE_PAGE_SIZE, withTotal); todayMs += (System.nanoTime() - t) / 1_000_000
t = System.nanoTime(); b = viaProvider(start, CATALOGUE_PAGE_SIZE, withTotal); providerMs += (System.nanoTime() - t) / 1_000_000
} catch (f: Exception) { error = "${f.javaClass.simpleName} at position $start"; break }
peakHeap = maxOf(peakHeap, heapUsed())
if (withTotal) total = a.total
val same = a.rawCount == b.rawCount && a.total == b.total && a.records == b.records
if (!same) {
mismatches++
if (firstMismatches.length() < 20) firstMismatches.put(JSONObject().put("position", start).put("rawToday", a.rawCount).put("rawProvider", b.rawCount)
.put("totalToday", a.total ?: JSONObject.NULL).put("totalProvider", b.total ?: JSONObject.NULL)
.put("ids", JSONArray((a.records.map { it.id } + b.records.map { it.id }).distinct().filter { id ->
a.records.firstOrNull { it.id == id } != b.records.firstOrNull { it.id == id } }.take(10))))
}
records += a.records.size; pages++
start += a.rawCount
if (a.rawCount == 0 || total?.let { start >= it } == true) break
}
return JSONObject().put("pages", pages).put("records", records).put("positionReached", start).put("total", total ?: JSONObject.NULL)
.put("identical", mismatches == 0 && error == null).put("mismatches", mismatches).put("firstMismatches", firstMismatches)
.put("todayMs", todayMs).put("providerMs", providerMs).put("heapBeforeKb", heapBefore / 1024).put("heapPeakKb", peakHeap / 1024)
.put("error", error ?: JSONObject.NULL).put("wroteCatalogue", false)
}
}
/**
* A raw catalogue page with the personal parts replaced and its structure kept (step 3 fixtures): every row, key and type
* stays; titles become "Title n", original titles and tags keep their shape with neutral words, external ids keep their
* keys with digits of the same length, and fields the import doesn't read are dropped.
*/
internal fun sanitiseCataloguePage(body: String): JSONObject {
val page = JSONObject(body)
val rows = page.optJSONArray("Items") ?: JSONArray()
val clean = JSONArray()
val keep = setOf("Id", "Type", "Name", "ProductionYear", "OfficialRating", "Genres", "Studios", "ProviderIds", "PremiereDate", "RunTimeTicks", "OriginalTitle", "Tags", "TagItems")
for (i in 0 until rows.length()) {
val row = rows.optJSONObject(i) ?: run { clean.put(rows.opt(i)); null } ?: continue
val out = JSONObject()
for (key in row.keys()) if (key in keep) out.put(key, row.get(key))
if (out.has("Name")) out.put("Name", "Title ${i + 1}")
if (out.optString("OriginalTitle").isNotBlank()) out.put("OriginalTitle", "Original title ${i + 1}")
out.optJSONObject("ProviderIds")?.let { ids -> val fake = JSONObject(); ids.keys().forEach { k -> fake.put(k, (ids.opt(k) as? String)?.map { c -> if (c.isDigit()) '7' else c }?.joinToString("") ?: ids.opt(k)) }; out.put("ProviderIds", fake) }
for (tagKey in listOf("Tags", "TagItems")) out.optJSONArray(tagKey)?.let { a -> out.put(tagKey, JSONArray((0 until a.length()).map { j -> if (a.opt(j) is JSONObject) JSONObject().put("Name", "tag${j + 1}") else "tag${j + 1}" })) }
clean.put(out)
}
return JSONObject().put("Items", clean).apply { if (page.has("TotalRecordCount")) put("TotalRecordCount", page.get("TotalRecordCount")) }
}
@@ -72,7 +72,8 @@ internal class ChannelScheduler(private val store: ScheduleStore,
catalogue.write(userId, records, nextStart, total, finished); found += records
}
}
val run = session.importCatalogue(sink, ARRIVALS_REFRESH_PAGES)
// Through the provider contract only when its switch is on (step 3, off by default); today's path stays the fallback.
val run = if (ProviderSwitches.catalogue) session.importCatalogueViaProvider(sink, ARRIVALS_REFRESH_PAGES) else session.importCatalogue(sink, ARRIVALS_REFRESH_PAGES)
val arrivals = if (baseline) found.map { arrivalOf(it, now) } else emptyList()
store.saveArrivals(userId, mergeArrivals(kept, arrivals, now), now)
Log.i("OrbitSchedule", "arrivals pages=${run.pages} read=${found.size} new=${arrivals.size} baseline=$baseline")
@@ -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.110.5\"") +
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.110.6\"") +
(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.5\"" +
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.110.6\"" +
(token?.let { ", Token=\"$it\"" } ?: ""))
}
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
@@ -391,6 +391,11 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
runCatching { withContext(Dispatchers.IO) { Taste.watching(channel.number, show, channel.seriesIdAt(show.startMs), at - show.startMs, now) } }
}
}
// The read-only catalogue shadow comparison (provider contract step 3), when asked for from adb. Never writes the catalogue.
LaunchedEffect(session) {
val active = session ?: return@LaunchedEffect
while (true) { delay(10_000); if (CatalogueShadow.pending != null) withContext(Dispatchers.IO) { runCatching { CatalogueShadow.runIfPending(active, appContext) } } }
}
// Rooms sync (7 November 2026): every two minutes while Orbit is open, with each paired room it can reach on the Wi-Fi.
LaunchedEffect(workspace) {
val finder = RoomFinder(appContext); finder.start()
@@ -454,6 +454,24 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
fun importCatalogue(sink: CatalogueSink, maxPages: Int = CATALOGUE_PAGES_PER_RUN, pause: () -> Unit = {}, checkActive: () -> Unit = {}, onPage: () -> Unit = {},
backoff: (Int) -> Unit = {}, onRetry: (Int) -> Unit = {}): CatalogueRun =
importCatalogue(transport, userId, ::currentToken, sink, maxPages, pause, checkActive, onPage, backoff, onRetry)
/**
* This library behind the provider contract (step 3, 8 November 2026). Its id is the server's own, read once from
* /System/Info/Public; if that can't be read, a hash of the address stands in until it can.
*/
fun provider(images: (String) -> ByteArray? = ::fetchArtwork): EmbyProvider = EmbyProvider(this, transport, userId, ::currentToken,
if (kind == ServerKind.Jellyfin) ProviderKind.Jellyfin else ProviderKind.Emby, serverId, images)
private val serverId: String by lazy {
runCatching { EmbyClient.parse(transport.execute(EmbyRequest("GET", "/System/Info/Public")).body).optString("Id") }.getOrNull()?.takeIf(EmbyClient::validId)
?: ("addr-" + java.security.MessageDigest.getInstance("SHA-256").digest(origin.toByteArray()).take(8).joinToString("") { "%02x".format(it) })
}
/** Today's catalogue reader for the shadow comparison, handing each raw reply to [onRaw] (sanitised before it's kept). */
fun cataloguePageRecorded(start: Long, size: Int, withTotal: Boolean, onRaw: (String) -> Unit): CataloguePage =
fetchCataloguePage(EmbyTransport { r -> transport.execute(r).also { if (it.status in 200..299) onRaw(it.body) } }, userId, ::currentToken, start, size, withTotal)
/** Today's import, with pages read through the contract instead (step 3; off unless ProviderSwitches.catalogue is on). */
fun importCatalogueViaProvider(sink: CatalogueSink, maxPages: Int = CATALOGUE_PAGES_PER_RUN): CatalogueRun {
val p = provider()
return importCatalogue(transport, userId, ::currentToken, sink, maxPages, fetch = { start, size, withTotal -> cataloguePageVia(p, start, size, withTotal) })
}
fun checkAfterDarkMovies(genre: String): List<AfterDarkMovie> {
val found = discoverAfterDarkMovies(transport, userId, ::currentToken, genre)
currentToken()
@@ -0,0 +1,129 @@
package tv.orbit.classic
import org.json.JSONArray
import org.json.JSONObject
/**
* Emby and Jellyfin behind the provider contract (step 2, 8 November 2026). It wraps today's code rather than rewriting
* it: the catalogue page, whole-series and collection readers, the evidence reader and the session's own playback and
* progress calls are the very functions Orbit uses now, so the data is the same. Only specials (which today's readers
* leave out) and picture sizes are read here.
*
* Not wired into the app yet: Orbit still calls the session directly until this is reviewed.
*/
internal class EmbyProvider(
private val session: EmbySampleSession,
private val transport: EmbyTransport,
private val userId: String,
private val token: () -> String,
override val kind: ProviderKind,
/** The server's own Id from /System/Info/Public, never its address. */
serverId: String,
/** Picture bytes for a server path; the session's own fetch unless a test supplies one. */
private val images: (String) -> ByteArray? = session::fetchArtwork,
/** Progress back to the server: on, as today, unless the viewer turns it off. */
private val progressOn: () -> Boolean = { true },
) : MediaProvider {
init { require(kind == ProviderKind.Emby || kind == ProviderKind.Jellyfin || kind == ProviderKind.Silo) }
override val library = LibraryId.of(kind, serverId)
override val capabilities = setOf(Capability.Collections, Capability.Progress, Capability.ExternalIds, Capability.ServerArtworkResize)
private val plans = java.util.concurrent.ConcurrentHashMap<String, EmbyPlaybackPlan>()
override suspend fun catalogue(page: PageRequest): Page<CatalogueItem> = guarded {
// Today's reader, unchanged: oldest first, Movie and Series only, at most CATALOGUE_PAGE_SIZE a page.
val read = fetchCataloguePage(transport, userId, token, page.start.toLong(), minOf(page.limit, CATALOGUE_PAGE_SIZE), page.withTotal)
Page(read.records.map(::catalogueItemOf), (read.total ?: -1L).toInt(), page.start + read.rawCount)
}
override suspend fun episodes(seriesId: ItemId, includeSpecials: Boolean): List<Episode> = guarded {
val regular = readWholeSeries(transport, userId, token, SeriesCandidate(seriesId.value, "", null, "")).episodes.map { e ->
Episode(ItemId(e.id), seriesId, e.mark.season, e.mark.episode, e.title, e.durationMs, listOf(SourceId(e.sourceId)))
}
if (!includeSpecials) regular else (specials(seriesId) + regular).sortedWith(compareBy({ it.season }, { it.episode }))
}
/** Season 0, which today's whole-series reader leaves out; read only when asked. */
private fun specials(seriesId: ItemId): List<Episode> {
val reply = transport.execute(EmbyRequest("GET", "/Shows/${seriesId.value}/Episodes?UserId=$userId&Season=0&StartIndex=0&Limit=$WHOLE_SERIES_PAGE" +
"&Fields=MediaSources&EnableImages=false&EnableUserData=false", token = token(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS))
EmbyClient.expectSuccess(reply.status, false)
val rows = EmbyClient.parse(reply.body).optJSONArray("Items") ?: return emptyList()
return (0 until minOf(rows.length(), WHOLE_SERIES_PAGE)).mapNotNull { rows.optJSONObject(it) }.mapNotNull { row ->
val id = row.optString("Id").takeIf(EmbyClient::validId) ?: return@mapNotNull null
if (row.optString("Type") != "Episode" || row.optInt("ParentIndexNumber", -1) != 0) return@mapNotNull null
val source = row.optJSONArray("MediaSources")?.optJSONObject(0)?.optString("Id")?.takeIf(EmbyClient::validId)
Episode(ItemId(id), seriesId, 0, row.optInt("IndexNumber", 0), EmbyClient.clean(row.optString("Name"), 160).ifBlank { "Special" },
(row.optLong("RunTimeTicks", 0) / 10_000).takeIf { it > 0 }, listOfNotNull(source?.let(::SourceId)))
}
}
override suspend fun collections(page: PageRequest): Page<MediaCollection> = guarded {
val (sets, total) = session.readCollections(page.start, minOf(page.limit, COLLECTION_PAGE))
Page(sets.mapNotNull { s ->
val id = s.optString("id").takeIf(EmbyClient::validId) ?: return@mapNotNull null
val members = s.optJSONArray("members")?.let { a -> (0 until a.length()).map { a.optString(it) }.filter(EmbyClient::validId).map(::ItemId) }.orEmpty()
MediaCollection(ItemId(id), s.optString("name"), members, s.optBoolean("complete", true))
}, total)
}
override suspend fun details(ids: List<ItemId>): List<ItemDetails> = guarded {
require(ids.size <= DETAILS_BATCH_MAX)
session.readEvidence(ids.map { it.value }).map { e ->
fun list(key: String) = e.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
ItemDetails(ItemId(e.getString("id")), e.optString("overview").takeIf { !e.isNull("overview") && it.isNotBlank() }, null,
list("leads"), list("directors"), list("genres"), list("studios"),
e.optString("rating").takeIf { !e.isNull("rating") && it.isNotBlank() },
e.optDouble("community").takeIf { !it.isNaN() }, e.optInt("year", 0).takeIf { it > 0 })
}.filter { d -> ids.contains(d.id) }
}
override suspend fun artwork(id: ItemId, kind: ArtworkKind, maxWidthPx: Int): ByteArray? {
require(maxWidthPx in 16..3840)
val type = when (kind) { ArtworkKind.Backdrop -> "Backdrop"; ArtworkKind.Poster -> "Primary"; ArtworkKind.Logo -> "Logo" }
// The server resizes the picture (Capability.ServerArtworkResize); a missing one, or any failure, is just no picture.
return runCatching { images("/Items/${id.value}/Images/$type?maxWidth=$maxWidthPx&quality=80") }.getOrNull()
}
override suspend fun prepare(item: ItemId, source: SourceId?): PlaybackPlan = guarded(playback = true) {
// The session only plays items it has been told about, as the scheduler does today.
val sample = SampleItem(item.value, "Episode", null, "", item.value)
session.rememberScheduledItems(listOf(sample))
val plan = session.prepare(sample, preferredSourceId = source?.value)
plans[item.value] = plan
PlaybackPlan(plan.url, session.mediaHeaders(plan.url),
subtitles = plan.subtitles.mapIndexed { i, s -> TrackInfo("$i", s.language, s.label, external = true) },
container = plan.url.substringBefore('?').substringAfterLast('.'), directPlay = true)
}
override suspend fun reportProgress(item: ItemId, positionMs: Long, state: PlaybackState) {
if (!progressOn()) return
val plan = plans[item.value] ?: return
val event = when (state) { PlaybackState.Started -> "Playing"; PlaybackState.Progress -> "Playing/Progress"; PlaybackState.Stopped -> "Playing/Stopped" }
runCatching { session.report(plan, event, positionMs, paused = false) } // never fails the viewer's programme
if (state == PlaybackState.Stopped) plans.remove(item.value)
}
/** Today's exceptions, as the contract's five kinds, with messages that never carry server text, addresses or tokens. */
private inline fun <T> guarded(playback: Boolean = false, block: () -> T): T = try { block() } catch (f: Throwable) { throw providerErrorOf(f, playback) }
}
/** Maps today's Emby failures to the contract's five kinds (8 November 2026). */
internal fun providerErrorOf(f: Throwable, playback: Boolean = false): ProviderException = when {
f is ProviderException -> f
f is EmbyCheckException && (f.httpStatus == 401 || f.httpStatus == 403) -> ProviderException(ProviderError.Authentication, "Sign in to the library again.")
// Today's expectSuccess names other statuses only in its message, "(HTTP 404)"; read it here rather than change it.
f is EmbyCheckException && (f.httpStatus == 404 || f.message.orEmpty().endsWith("(HTTP 404).")) ->
ProviderException(ProviderError.NotFound, "That programme is no longer in the library.")
f is EmbyCheckException && (f.retryable || f.httpStatus == 429) || f is java.io.IOException -> ProviderException(ProviderError.Unreachable, "The library isn't answering right now.")
playback && f is EmbyCheckException && (f.message.orEmpty().startsWith("This title needs a playback method") || f.message.orEmpty().startsWith("Unsupported direct container")
|| f.message.orEmpty().startsWith("The provider did not offer a playable source")) ->
ProviderException(ProviderError.UnsupportedPlayback, "This programme can't be played directly on this TV.")
else -> ProviderException(ProviderError.InvalidResponse, "The library sent something Orbit couldn't read.")
}
/** Today's catalogue row as the contract's item, and back: every field kept, so the round trip is exact. */
internal fun catalogueItemOf(r: CatalogueRecord) = CatalogueItem(ItemId(r.id), if (r.type == "Series") MediaType.Series else MediaType.Movie, r.title, r.year,
r.runtimeMs, r.genres, r.rating.ifBlank { null }, r.premiere.ifBlank { null }, r.studios, r.providerIds, r.originalTitle.ifBlank { null }, r.tags)
internal fun catalogueRecordOf(i: CatalogueItem) = CatalogueRecord(i.id.value, if (i.type == MediaType.Series) "Series" else "Movie", i.title, i.year,
i.rating.orEmpty(), i.genres, i.studios, i.externalIds, i.premiere.orEmpty(), i.runtimeMs, i.originalTitle.orEmpty(), i.tags)
@@ -60,6 +60,19 @@ class MainActivity : ComponentActivity() {
// 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() { InstallSnapshot.screenOpen = false; super.onDestroy() }
override fun onStop() { 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.
*/
private fun readAdbRequests(intent: android.content.Intent?) {
if (intent?.getBooleanExtra("orbit_intro_test", false) == true) IntroTrial.nextTune = true
intent?.getStringExtra("orbit_inspect_series")?.take(120)?.let { SeriesInspection.title = it }
if (intent?.getBooleanExtra("orbit_read_evidence", false) == true) EvidenceRequest.pending = true
// Provider contract, step 3: the catalogue switch and the read-only shadow comparison.
when (intent?.getStringExtra("orbit_provider_catalogue")) { "on" -> ProviderSwitches.setCatalogue(this, true); "off" -> ProviderSwitches.setCatalogue(this, false) }
if (intent?.hasExtra("orbit_shadow_catalogue") == true) CatalogueShadow.pending = intent.getIntExtra("orbit_shadow_catalogue", 5)
}
override fun onNewIntent(intent: android.content.Intent) { super.onNewIntent(intent); setIntent(intent); readAdbRequests(intent) }
override fun onCreate(savedInstanceState: Bundle?) {
InstallSnapshot.screenOpen = true
OrbitCompanion.activity = java.lang.ref.WeakReference(this)
@@ -68,9 +81,8 @@ class MainActivity : ComponentActivity() {
Motion.load(OrbitSettings(this))
// The guide's logos, decoded ahead on a background thread so the guide opens with them ready.
Thread({ Pictures.warmLogos(resources) }, "orbit-logos").apply { priority = Thread.MIN_PRIORITY }.start()
if (intent?.getBooleanExtra("orbit_intro_test", false) == true) IntroTrial.nextTune = true
intent?.getStringExtra("orbit_inspect_series")?.take(120)?.let { SeriesInspection.title = it }
if (intent?.getBooleanExtra("orbit_read_evidence", false) == true) EvidenceRequest.pending = true
ProviderSwitches.load(this)
readAdbRequests(intent)
// The hand-run playback test opens over Orbit, which stops in the background as it would for any other app, and comes back when it ends.
intent?.getStringExtra("orbit_play_test")?.takeIf(EmbyClient::validId)?.let { item ->
startActivity(android.content.Intent(this, PlaybackTestActivity::class.java).putExtra(PlaybackTestActivity.ITEM, item))
@@ -0,0 +1,151 @@
package tv.orbit.classic
/**
* The provider-neutral media contract (Paul, 8 November 2026; docs: "Orbit provider contract proposal"). Everything Orbit
* needs from a media source, and nothing else: the guide, Taste, the Director's Chair, profiles and channels read Orbit's
* own local copies and never care whether an episode came from Emby, Jellyfin, Silo, Plex or a local drive.
*
* Rules every adapter keeps, proved by the shared contract tests (MediaProviderContract):
* - read-only, except progress reporting, which is optional;
* - ids are opaque and stable, and fit [validMediaId], so every id Orbit has already stored stays valid;
* - no transcoding: a stream is played as it is, or reported unplayable;
* - credentials travel in headers only, never in anything logged;
* - failures are one of the five [ProviderError] kinds.
* Sign-in is not part of the contract: each provider has its own (a password, a plex.tv code, a folder picker), and a
* signed-in [MediaProvider] is what the rest of Orbit receives. Search stays on Orbit's local catalogue.
*
* Step 1: introduced alongside today's Emby session, which the app still uses directly. Nothing calls this yet.
*/
internal interface MediaProvider {
val kind: ProviderKind
/** The library itself, stable across address changes (the server's own id, or a local library's marker). */
val library: LibraryId
val capabilities: Set<Capability>
/** Films and series, a page at a time, for the local catalogue. */
suspend fun catalogue(page: PageRequest): Page<CatalogueItem>
/** A series' episodes in season and episode order; specials (season 0) only when asked. */
suspend fun episodes(seriesId: ItemId, includeSpecials: Boolean = false): List<Episode>
/** The library's own collections and their members; empty without [Capability.Collections]. */
suspend fun collections(page: PageRequest): Page<MediaCollection>
/** Synopsis, tagline, cast and the rest for up to [DETAILS_BATCH_MAX] items; unknown ids are left out, not errors. */
suspend fun details(ids: List<ItemId>): List<ItemDetails>
/** Picture bytes no wider than [maxWidthPx], or null when there isn't one. Never throws for a missing picture. */
suspend fun artwork(id: ItemId, kind: ArtworkKind, maxWidthPx: Int): ByteArray?
/** A stream Media3 plays as it is, with its subtitle and audio tracks. No transcoding. */
suspend fun prepare(item: ItemId, source: SourceId? = null): PlaybackPlan
/** Tells the server what was watched; does nothing without [Capability.Progress] or when the viewer turned it off. */
suspend fun reportProgress(item: ItemId, positionMs: Long, state: PlaybackState)
}
internal enum class ProviderKind(val key: String) { Emby("emby"), Jellyfin("jellyfin"), Silo("silo"), Plex("plex"), Local("local") }
internal enum class Capability { Collections, Progress, Taglines, ExternalIds, ServerArtworkResize }
internal enum class ArtworkKind { Backdrop, Poster, Logo }
internal enum class MediaType { Movie, Series, Episode }
internal enum class PlaybackState { Started, Progress, Stopped }
/** The most ids [MediaProvider.details] takes at once. */
internal const val DETAILS_BATCH_MAX = 60
/** Today's id rule (EmbyClient.validId), kept for every provider so stored ids stay valid: 1 to 128 of A-Z a-z 0-9 _ -. */
internal fun validMediaId(value: String): Boolean =
value.length in 1..128 && value.all { it in 'A'..'Z' || it in 'a'..'z' || it in '0'..'9' || it == '_' || it == '-' }
@JvmInline internal value class ItemId(val value: String) {
init { require(validMediaId(value)) { "Not a media id" } }
override fun toString() = value
}
@JvmInline internal value class SourceId(val value: String) {
init { require(validMediaId(value)) { "Not a source id" } }
override fun toString() = value
}
/** A library, as "kind:id": the server's own id, never its address, so it survives an address change. */
@JvmInline internal value class LibraryId(val value: String) {
init { require(Regex("(emby|jellyfin|silo|plex|local):[A-Za-z0-9_-]{1,128}").matches(value)) { "Not a library id" } }
val kind get() = ProviderKind.entries.first { value.startsWith(it.key + ":") }
override fun toString() = value
companion object { fun of(kind: ProviderKind, id: String) = LibraryId("${kind.key}:$id") }
}
/** Media named everywhere it could leave its own library (room sync, TV Times): never confused with another library's. */
internal data class MediaRef(val library: LibraryId, val item: ItemId, val source: SourceId? = null)
/** [withTotal]: whether to count the whole library too; costly on a big server, so a long read asks only on its first page. */
internal data class PageRequest(val start: Int, val limit: Int, val withTotal: Boolean = true) {
init { require(start >= 0 && limit in 1..PAGE_MAX) }
companion object { const val PAGE_MAX = 500 }
}
/**
* One page. [next] is where the following page starts: the rows the server returned, including any Orbit skipped (an item
* with no title, say), so a resumed read never re-reads or misses rows. [total] is -1 when it wasn't asked for.
*/
internal data class Page<T>(val items: List<T>, val total: Int, val next: Int = -1)
/**
* A film or series as the local catalogue keeps it (step 3, 8 November 2026: the fields today's import stores, so the
* contract path writes exactly the same catalogue rows). [externalIds] are the library's IMDb, TMDb and similar ids.
*/
internal data class CatalogueItem(val id: ItemId, val type: MediaType, val title: String, val year: Int? = null, val runtimeMs: Long? = null,
val genres: List<String> = emptyList(), val rating: String? = null, val premiere: String? = null,
val studios: List<String> = emptyList(), val externalIds: Map<String, String> = emptyMap(), val originalTitle: String? = null,
val tags: List<String> = emptyList())
internal data class Episode(val id: ItemId, val seriesId: ItemId, val season: Int, val episode: Int, val title: String,
val runtimeMs: Long? = null, val sources: List<SourceId> = emptyList())
internal data class MediaCollection(val id: ItemId, val name: String, val members: List<ItemId>, val complete: Boolean = true)
internal data class ItemDetails(val id: ItemId, val overview: String? = null, val tagline: String? = null, val leads: List<String> = emptyList(),
val directors: List<String> = emptyList(), val genres: List<String> = emptyList(), val studios: List<String> = emptyList(),
val rating: String? = null, val communityRating: Double? = null, val year: Int? = null)
internal data class TrackInfo(val id: String, val language: String? = null, val title: String? = null, val external: Boolean = false)
/**
* A stream to play as it is. [headers] carry the credentials; [toString] and [loggable] leave them out, and the query
* string with them, so a plan can be logged or shown without giving anything away.
*/
internal class PlaybackPlan(val uri: String, val headers: Map<String, String>, val subtitles: List<TrackInfo> = emptyList(),
val audio: List<TrackInfo> = emptyList(), val container: String? = null, val directPlay: Boolean = true) {
fun loggable(): String = "plan ${uri.substringBefore('?').substringAfterLast('/')} container=${container ?: "?"} " +
"subtitles=${subtitles.size} audio=${audio.size} headers=${headers.size}"
override fun toString() = loggable()
}
/** The five ways a provider call can fail, each with its own message and retry rule in Orbit. */
internal enum class ProviderError {
/** Sign-in expired or revoked: ask to sign in again, never retry silently. */
Authentication,
/** No network, DNS or timeout: retry with a growing wait. */
Unreachable,
/** A reply Orbit can't read: skip that item, never crash. */
InvalidResponse,
/** The box can't play it directly: mark it unplayable, as today. No transcoding. */
UnsupportedPlayback,
/** The item is gone: drop it from future plans; booked schedules are left alone. */
NotFound
}
/** A failure from a provider. Its message is for people and logs, so it never carries a token, password or address. */
internal class ProviderException(val error: ProviderError, message: String, cause: Throwable? = null) : Exception(message, cause)
/**
* A local file's id: the first 32 hex characters (128 bits) of a SHA-256 of its path within the library, so the same
* file keeps the same id and two files practically never share one (import still refuses a clash).
*/
internal fun localMediaId(relativePath: String): ItemId =
ItemId(java.security.MessageDigest.getInstance("SHA-256").digest(relativePath.replace('\\', '/').trimStart('/').toByteArray(Charsets.UTF_8))
.joinToString("") { "%02x".format(it) }.take(32))
@@ -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.5")
next.setRequestProperty("User-Agent", "OrbitTV/0.110.6")
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()) {