Merge branch 'provider-contract' into integration-0.110.9
# Conflicts: # android/app/build.gradle.kts
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
# Orbit's release gate on every push (8 November 2026). Runs where the git server has an Actions runner; the same
|
||||
# checks run locally with tools/verify.sh. GitHub Actions reads the same syntax, for the public repository later.
|
||||
name: release-gate
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
with: { distribution: temurin, java-version: '17' }
|
||||
- uses: android-actions/setup-android@v3
|
||||
- name: Build, unit tests (provider contract suite included) and lint
|
||||
run: ORBIT_TOOLING=/nonexistent tools/verify.sh
|
||||
@@ -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()) {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/** Step 3 (8 November 2026): the catalogue import through the contract writes exactly what today's import writes. */
|
||||
class CatalogueViaProviderTest {
|
||||
/** A library with the awkward rows real servers have: an episode in the list, a row with no title, a bad id. */
|
||||
private class Awkward : EmbyTransport {
|
||||
val rows = (1..37).map { i -> JSONObject().put("Id", "item$i").put("Type", if (i % 5 == 0) "Series" else "Movie").put("Name", "Fictional $i")
|
||||
.put("ProductionYear", 1980 + i).put("RunTimeTicks", (40L + i) * 60_000 * 10_000).put("OfficialRating", if (i % 3 == 0) "" else "15")
|
||||
.put("Genres", JSONArray().put("Drama")).put("Studios", JSONArray().put(JSONObject().put("Name", "Studio $i")))
|
||||
.put("ProviderIds", JSONObject().put("Imdb", "tt00$i").put("Tmdb", "$i")).put("PremiereDate", "${1980 + i}-01-01T00:00:00Z")
|
||||
.put("OriginalTitle", if (i % 7 == 0) "Original $i" else "").put("Tags", JSONArray().put("tag$i")) } +
|
||||
listOf(JSONObject().put("Id", "ep1").put("Type", "Episode").put("Name", "An episode"), JSONObject().put("Id", "untitled").put("Type", "Movie"),
|
||||
JSONObject().put("Id", "../bad").put("Type", "Movie").put("Name", "Bad id"))
|
||||
override fun execute(request: EmbyRequest): EmbyReply {
|
||||
val q = { k: String -> Regex("[?&]$k=([^&]*)").find(request.path)!!.groupValues[1] }
|
||||
val start = q("StartIndex").toInt(); val limit = q("Limit").toInt()
|
||||
return EmbyReply(200, JSONObject().put("Items", JSONArray(rows.drop(start).take(limit))).put("TotalRecordCount", if (request.path.contains("EnableTotalRecordCount=false")) 0 else rows.size).toString())
|
||||
}
|
||||
}
|
||||
private class Capture : CatalogueSink {
|
||||
var pos = 0L; val writes = mutableListOf<List<Any?>>()
|
||||
override fun position(userId: String) = pos
|
||||
override fun write(userId: String, records: List<CatalogueRecord>, nextStart: Long, total: Long?, finished: Boolean) { writes += listOf(records, nextStart, total, finished); pos = nextStart }
|
||||
}
|
||||
private fun provider(t: EmbyTransport) = EmbyProvider(EmbySampleSession(t, "fixture-token-private", "fixtureuser", EmbySample(emptyList(), 0)), t, "fixtureuser",
|
||||
{ "fixture-token-private" }, ProviderKind.Emby, "fixtureserver1", images = { null })
|
||||
|
||||
@Test fun importThroughTheContractWritesTheSameRecordsPositionsAndTotals() {
|
||||
for (pageSize in listOf(5, 200)) {
|
||||
val t = Awkward(); val today = Capture(); val via = Capture(); val p = provider(t)
|
||||
importCatalogue(t, "fixtureuser", { "fixture-token-private" }, today, maxPages = 50, fetch = { s, _, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, pageSize, w) })
|
||||
importCatalogue(t, "fixtureuser", { "fixture-token-private" }, via, maxPages = 50, fetch = { s, _, w -> cataloguePageVia(p, s, pageSize, w) })
|
||||
assertEquals(today.writes, via.writes)
|
||||
assertEquals(37, today.writes.sumOf { (it[0] as List<*>).size })
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theShadowComparisonFindsThemIdenticalAndNeverWrites() {
|
||||
val t = Awkward(); val p = provider(t)
|
||||
val r = CatalogueShadow.compare({ s, n, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, n, w) }, { s, n, w -> cataloguePageVia(p, s, n, w) }, 50)
|
||||
assertTrue(r.getBoolean("identical")); assertEquals(37, r.getInt("records")); assertEquals(40L, r.getLong("positionReached"))
|
||||
assertFalse(r.getBoolean("wroteCatalogue"))
|
||||
assertTrue(r.has("todayMs") && r.has("providerMs") && r.has("heapPeakKb"))
|
||||
}
|
||||
|
||||
@Test fun theShadowComparisonReportsADifferenceByIdOnly() {
|
||||
val t = Awkward(); val p = provider(t)
|
||||
val r = CatalogueShadow.compare({ s, n, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, n, w) },
|
||||
{ s, n, w -> cataloguePageVia(p, s, n, w).let { pg -> CataloguePage(pg.records.map { if (it.id == "item3") it.copy(year = 1900) else it }, pg.rawCount, pg.total) } }, 50)
|
||||
assertFalse(r.getBoolean("identical")); assertEquals(1, r.getInt("mismatches"))
|
||||
assertEquals("item3", r.getJSONArray("firstMismatches").getJSONObject(0).getJSONArray("ids").getString(0))
|
||||
assertFalse(r.toString().contains("Fictional")) // no titles in the report
|
||||
}
|
||||
|
||||
@Test fun theShadowComparisonRecordsAnErrorInsteadOfFailing() {
|
||||
val t = Awkward()
|
||||
val r = CatalogueShadow.compare({ s, n, w -> fetchCataloguePage(t, "fixtureuser", { "x" }, s, n, w) }, { _, _, _ -> throw EmbyCheckException("down", retryable = true) }, 5)
|
||||
assertFalse(r.getBoolean("identical")); assertTrue(r.getString("error").startsWith("EmbyCheckException"))
|
||||
}
|
||||
|
||||
@Test fun sanitisingKeepsStructureAndRemovesTitles() {
|
||||
val raw = JSONObject().put("Items", JSONArray(Awkward().rows)).put("TotalRecordCount", 40).toString()
|
||||
val clean = sanitiseCataloguePage(raw)
|
||||
assertEquals(40, clean.getJSONArray("Items").length()); assertEquals(40, clean.getInt("TotalRecordCount"))
|
||||
assertFalse(clean.toString().contains("Fictional"))
|
||||
val before = fetchCataloguePage(EmbyTransport { EmbyReply(200, raw) }, "fixtureuser", { "x" }, 0, 200)
|
||||
val after = fetchCataloguePage(EmbyTransport { EmbyReply(200, clean.toString()) }, "fixtureuser", { "x" }, 0, 200)
|
||||
assertEquals(before.records.map { Triple(it.id, it.type, it.runtimeMs) }, after.records.map { Triple(it.id, it.type, it.runtimeMs) })
|
||||
assertEquals(before.rawCount, after.rawCount)
|
||||
assertEquals("tt777", after.records.first { it.id == "item7" }.providerIds["Imdb"]) // "tt007": same length, digits replaced
|
||||
}
|
||||
|
||||
@Test fun theSwitchStartsOff() { assertFalse(ProviderSwitches.catalogue) }
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import java.awt.image.BufferedImage
|
||||
import java.io.ByteArrayOutputStream
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
/**
|
||||
* A recorded-style Emby/Jellyfin library for the contract (8 November 2026): the replies are shaped exactly as the
|
||||
* server sends them to today's readers (catalogue pages, whole series, collections, evidence, PlaybackInfo). The media
|
||||
* is fictional. [fail] makes every call fail one way: 401s, a dropped connection, or a reply that isn't JSON.
|
||||
*/
|
||||
internal class FixtureEmbyServer(private val fail: ProviderError? = null) : EmbyTransport {
|
||||
val requests = mutableListOf<String>()
|
||||
private val films = (1..9).map { i -> JSONObject().put("Id", "film$i").put("Type", "Movie").put("Name", "Fictional Film $i").put("ProductionYear", 1990 + i)
|
||||
.put("RunTimeTicks", 95L * 60_000 * 10_000).put("OfficialRating", "PG").put("Genres", JSONArray().put("Comedy")).put("PremiereDate", "${1990 + i}-05-01T00:00:00Z") }
|
||||
private val shows = (1..3).map { i -> JSONObject().put("Id", "show$i").put("Type", "Series").put("Name", "Fictional Show $i").put("ProductionYear", 2000 + i) }
|
||||
private val items = films + shows
|
||||
private fun episode(s: Int, e: Int) = JSONObject().put("Id", "ep${s}x$e").put("Type", "Episode").put("Name", "Episode $s.$e").put("SeriesId", "show1")
|
||||
.put("ParentIndexNumber", s).put("IndexNumber", e).put("RunTimeTicks", 30L * 60_000 * 10_000)
|
||||
.put("MediaSources", JSONArray().put(JSONObject().put("Id", "src${s}x$e").put("Container", "mkv").put("RunTimeTicks", 30L * 60_000 * 10_000)))
|
||||
private fun page(rows: List<JSONObject>, total: Int) = EmbyReply(200, JSONObject().put("Items", JSONArray(rows)).put("TotalRecordCount", total).toString())
|
||||
private fun q(path: String, key: String) = Regex("[?&]$key=([^&]*)").find(path)?.groupValues?.get(1)
|
||||
|
||||
override fun execute(request: EmbyRequest): EmbyReply {
|
||||
requests += "${request.method} ${request.path.substringBefore('?')}"
|
||||
when (fail) {
|
||||
ProviderError.Authentication -> return EmbyReply(401, "")
|
||||
ProviderError.Unreachable -> throw EmbyCheckException("The provider did not answer in time (connect to https://bk2.appboxmanager.xyz).", retryable = true)
|
||||
ProviderError.InvalidResponse -> return EmbyReply(200, "<html>fixture-token-private</html>")
|
||||
else -> {}
|
||||
}
|
||||
val p = request.path
|
||||
return when {
|
||||
p.startsWith("/Items/") && p.endsWith("/PlaybackInfo") -> {
|
||||
val id = p.removePrefix("/Items/").removeSuffix("/PlaybackInfo")
|
||||
if (items.none { it.getString("Id") == id } && !id.startsWith("ep")) return EmbyReply(404, "")
|
||||
val direct = id != "film9"
|
||||
EmbyReply(200, JSONObject().put("PlaySessionId", "play1").put("ErrorCode", JSONObject.NULL).put("MediaSources", JSONArray().put(
|
||||
JSONObject().put("Id", "src-$id").put("Container", "mkv").put("SupportsDirectPlay", direct).put("SupportsDirectStream", direct))).toString())
|
||||
}
|
||||
p.startsWith("/Shows/show1/Episodes") -> if (q(p, "Season") == "0") page(listOf(episode(0, 1), episode(0, 2)), 2)
|
||||
else page(((1..2).flatMap { s -> (1..4).map { e -> episode(s, e) } }).drop(q(p, "StartIndex")!!.toInt()), 8)
|
||||
p.startsWith("/Items?") && q(p, "IncludeItemTypes") == "BoxSet" -> page(listOf(JSONObject().put("Id", "set1").put("Name", "Fictional Saga")).drop(q(p, "StartIndex")!!.toInt()), 1)
|
||||
p.startsWith("/Items?") && q(p, "ParentId") == "set1" -> page(listOf("film1", "film2", "film3").map { JSONObject().put("Id", it) }, 3)
|
||||
p.startsWith("/Items?") && q(p, "Ids") != null -> { val ids = q(p, "Ids")!!.split(','); page(items.filter { it.getString("Id") in ids }.map { JSONObject(it.toString()).put("Overview", "A fictional synopsis.") }, ids.size) }
|
||||
p.startsWith("/Items?") && q(p, "IncludeItemTypes") == "Movie,Series" -> {
|
||||
val start = q(p, "StartIndex")!!.toInt(); val limit = q(p, "Limit")!!.toInt()
|
||||
page(items.drop(start).take(limit), items.size)
|
||||
}
|
||||
else -> EmbyReply(404, "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Pictures as the server sends them, resized to the asked width; only film1 has one. */
|
||||
internal fun fixtureImages(path: String): ByteArray? {
|
||||
if (!path.startsWith("/Items/film1/")) return null
|
||||
val width = minOf(1280, Regex("maxWidth=(\\d+)").find(path)!!.groupValues[1].toInt())
|
||||
return ByteArrayOutputStream().also { ImageIO.write(BufferedImage(width, width * 9 / 16, BufferedImage.TYPE_INT_RGB), "png", it) }.toByteArray()
|
||||
}
|
||||
|
||||
internal fun fixtureEmby(kind: ProviderKind = ProviderKind.Emby, fail: ProviderError? = null, server: FixtureEmbyServer = FixtureEmbyServer(fail)): EmbyProvider {
|
||||
val session = EmbySampleSession(server, "fixture-token-private", "fixtureuser", EmbySample(emptyList(), 0))
|
||||
return EmbyProvider(session, server, "fixtureuser", { "fixture-token-private" }, kind, "fixtureserver1", images = ::fixtureImages)
|
||||
}
|
||||
|
||||
internal fun embyFixture(kind: ProviderKind) = ContractFixture(
|
||||
catalogueSize = 12, series = ItemId("show1"), seriesEpisodes = 8, seriesSpecials = 2, collections = 1,
|
||||
known = listOf(ItemId("film1"), ItemId("show2")), missing = ItemId("gone1"),
|
||||
withArtwork = ItemId("film1"), withoutArtwork = ItemId("film2"), playable = ItemId("film1"), unplayable = ItemId("film9"),
|
||||
secrets = listOf("fixture-token-private", "appboxmanager", "fixtureuser"), failing = { e -> fixtureEmby(kind, e) })
|
||||
|
||||
/** Emby, through today's code, keeps the whole contract. */
|
||||
class EmbyProviderContractTest : MediaProviderContract() {
|
||||
override fun provider(): MediaProvider = fixtureEmby(ProviderKind.Emby)
|
||||
override fun fixture() = embyFixture(ProviderKind.Emby)
|
||||
}
|
||||
|
||||
/** Jellyfin is the same adapter and the same readers; its own path and header differences are covered by EmbyClientTest. */
|
||||
class JellyfinProviderContractTest : MediaProviderContract() {
|
||||
override fun provider(): MediaProvider = fixtureEmby(ProviderKind.Jellyfin)
|
||||
override fun fixture() = embyFixture(ProviderKind.Jellyfin)
|
||||
}
|
||||
|
||||
/** The adapter hands back exactly what today's catalogue import writes: wrapping changed nothing. */
|
||||
class EmbyProviderParityTest {
|
||||
@Test fun catalogueMatchesTodaysImport() {
|
||||
val server = FixtureEmbyServer()
|
||||
val written = mutableListOf<CatalogueRecord>()
|
||||
importCatalogue(server, "fixtureuser", { "fixture-token-private" }, object : CatalogueSink {
|
||||
var pos = 0L
|
||||
override fun position(userId: String) = pos
|
||||
override fun write(userId: String, records: List<CatalogueRecord>, nextStart: Long, total: Long?, finished: Boolean) { written += records; pos = nextStart }
|
||||
}, maxPages = 10)
|
||||
val viaContract = runBlocking { fixtureEmby(server = server).catalogue(PageRequest(0, 200)) }.items
|
||||
assertEquals(written.map { it.id to it.title }, viaContract.map { it.id.value to it.title })
|
||||
assertEquals(written.map { it.runtimeMs }, viaContract.map { it.runtimeMs })
|
||||
assertEquals(written.map { it.year }, viaContract.map { it.year })
|
||||
}
|
||||
|
||||
@Test fun episodesMatchTodaysWholeSeriesRead() {
|
||||
val server = FixtureEmbyServer()
|
||||
val today = readWholeSeries(server, "fixtureuser", { "fixture-token-private" }, SeriesCandidate("show1", "", null, "")).episodes
|
||||
val viaContract = runBlocking { fixtureEmby(server = server).episodes(ItemId("show1")) }
|
||||
assertEquals(today.map { Triple(it.id, it.sourceId, it.mark) }, viaContract.map { Triple(it.id.value, it.sources.single().value, EpisodeMark(it.season, it.episode)) })
|
||||
}
|
||||
|
||||
@Test fun libraryIsTheServersOwnIdNotItsAddress() {
|
||||
assertEquals("emby:fixtureserver1", fixtureEmby().library.value)
|
||||
assertEquals("jellyfin:fixtureserver1", fixtureEmby(ProviderKind.Jellyfin).library.value)
|
||||
}
|
||||
|
||||
@Test fun progressCanBeTurnedOff() {
|
||||
val server = FixtureEmbyServer()
|
||||
val session = EmbySampleSession(server, "fixture-token-private", "fixtureuser", EmbySample(emptyList(), 0))
|
||||
val off = EmbyProvider(session, server, "fixtureuser", { "fixture-token-private" }, ProviderKind.Emby, "fixtureserver1", ::fixtureImages, progressOn = { false })
|
||||
runBlocking { off.prepare(ItemId("film1")); off.reportProgress(ItemId("film1"), 60_000, PlaybackState.Started) }
|
||||
assertEquals(0, server.requests.count { it.contains("/Sessions/Playing") })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
/**
|
||||
* The shared provider contract tests (8 November 2026; "Orbit provider contract proposal", section 5). Written once,
|
||||
* run against every adapter with that adapter's own fixture library; an adapter ships only when all of them pass.
|
||||
* Each check is a plain function in [ProviderContractChecks], so ContractCatchesFlawsTest can prove every check really
|
||||
* fails on the flaw it is there to catch.
|
||||
*/
|
||||
internal class ContractFixture(
|
||||
/** Films and series in the fixture library. */
|
||||
val catalogueSize: Int,
|
||||
/** A series with [seriesEpisodes] regular episodes and [seriesSpecials] specials. */
|
||||
val series: ItemId, val seriesEpisodes: Int, val seriesSpecials: Int,
|
||||
/** A collection-capable provider's collections, or zero. */
|
||||
val collections: Int,
|
||||
/** Items that have details, and one that doesn't exist. */
|
||||
val known: List<ItemId>, val missing: ItemId,
|
||||
/** An item with a picture wider than 400 px, and one with none. */
|
||||
val withArtwork: ItemId, val withoutArtwork: ItemId,
|
||||
/** An item that plays directly, and one the box can't play directly. */
|
||||
val playable: ItemId, val unplayable: ItemId,
|
||||
/** Tokens, passwords and addresses that must never appear in anything loggable. */
|
||||
val secrets: List<String>,
|
||||
/** The same provider set up to fail in a given way (expired sign-in, unreachable, unreadable replies). */
|
||||
val failing: (ProviderError) -> MediaProvider,
|
||||
)
|
||||
|
||||
internal object ProviderContractChecks {
|
||||
private fun check(ok: Boolean, what: () -> String) { if (!ok) throw AssertionError(what()) }
|
||||
private fun everything(p: MediaProvider, pageSize: Int = 7): List<CatalogueItem> = runBlocking {
|
||||
val out = ArrayList<CatalogueItem>(); var start = 0
|
||||
while (true) { val page = p.catalogue(PageRequest(start, pageSize)); out += page.items; start = if (page.next >= 0) page.next else start + page.items.size; if (page.items.isEmpty() || start >= page.total) break }
|
||||
out
|
||||
}
|
||||
|
||||
/** 1. The same item has the same id on every read and across paging: stored bookings depend on it. */
|
||||
fun idsAreStable(p: MediaProvider, f: ContractFixture) {
|
||||
val a = everything(p, 7).map { it.title to it.id }.toSet(); val b = everything(p, 3).map { it.title to it.id }.toSet()
|
||||
check(a == b) { "ids changed between reads" }
|
||||
val e1 = runBlocking { p.episodes(f.series) }.map { it.id }; val e2 = runBlocking { p.episodes(f.series) }.map { it.id }
|
||||
check(e1 == e2) { "episode ids changed between reads" }
|
||||
}
|
||||
|
||||
/** 2. Every id fits today's rule, so it can be stored where Emby ids are stored now. */
|
||||
fun idsFitTheRule(p: MediaProvider, f: ContractFixture) {
|
||||
val ids = everything(p).map { it.id.value } + runBlocking { p.episodes(f.series, includeSpecials = true) }.flatMap { listOf(it.id.value) + it.sources.map { s -> s.value } }
|
||||
check(ids.all(::validMediaId)) { "an id breaks the rule" }
|
||||
check(Regex("(emby|jellyfin|silo|plex|local):.+").matches(p.library.value)) { "library id has no kind" }
|
||||
}
|
||||
|
||||
/** 3. Paging returns every item exactly once, and the total matches. */
|
||||
fun catalogueIsComplete(p: MediaProvider, f: ContractFixture) {
|
||||
val all = everything(p, 4)
|
||||
check(all.size == f.catalogueSize) { "expected ${f.catalogueSize} items, got ${all.size}" }
|
||||
check(all.map { it.id }.toSet().size == all.size) { "an item came back twice" }
|
||||
check(runBlocking { p.catalogue(PageRequest(0, 1)) }.total == f.catalogueSize) { "total doesn't match" }
|
||||
}
|
||||
|
||||
/** 4. Each film and series can be scheduled: a title, a film or series type, and a runtime when there is one. */
|
||||
fun catalogueItemsAreUsable(p: MediaProvider, f: ContractFixture) {
|
||||
everything(p).forEach { item ->
|
||||
check(item.title.isNotBlank()) { "${item.id} has no title" }
|
||||
check(item.type == MediaType.Movie || item.type == MediaType.Series) { "${item.id} is ${item.type} in the catalogue" }
|
||||
check(item.runtimeMs == null || item.runtimeMs > 0) { "${item.id} has a runtime of ${item.runtimeMs}" }
|
||||
}
|
||||
}
|
||||
|
||||
/** 5. Episodes come in season then episode order; specials only when asked. */
|
||||
fun episodesAreInOrder(p: MediaProvider, f: ContractFixture) {
|
||||
val regular = runBlocking { p.episodes(f.series) }
|
||||
check(regular.size == f.seriesEpisodes) { "expected ${f.seriesEpisodes} episodes, got ${regular.size}" }
|
||||
check(regular.none { it.season == 0 }) { "a special came back unasked" }
|
||||
check(regular == regular.sortedWith(compareBy({ it.season }, { it.episode }))) { "episodes out of order" }
|
||||
check(regular.all { it.seriesId == f.series }) { "an episode names another series" }
|
||||
check(runBlocking { p.episodes(f.series, includeSpecials = true) }.size == f.seriesEpisodes + f.seriesSpecials) { "specials missing when asked" }
|
||||
}
|
||||
|
||||
/** 6. Every collection member is in the catalogue; without the capability the list is empty, not an error. */
|
||||
fun collectionsHoldRealMembers(p: MediaProvider, f: ContractFixture) {
|
||||
val page = runBlocking { p.collections(PageRequest(0, 100)) }
|
||||
if (Capability.Collections !in p.capabilities) { check(page.items.isEmpty()) { "collections without the capability" }; return }
|
||||
check(page.items.size == f.collections) { "expected ${f.collections} collections, got ${page.items.size}" }
|
||||
val known = everything(p).map { it.id }.toSet()
|
||||
page.items.forEach { c -> check(c.members.all { it in known }) { "${c.name} has a member that isn't in the catalogue" } }
|
||||
}
|
||||
|
||||
/** 7. Details leave unknown ids out instead of failing, and a full batch works. */
|
||||
fun detailsSkipTheUnknown(p: MediaProvider, f: ContractFixture) {
|
||||
val got = runBlocking { p.details(f.known + f.missing) }.map { it.id }
|
||||
check(got.toSet() == f.known.toSet()) { "details returned $got" }
|
||||
val batch = everything(p).map { it.id }.take(DETAILS_BATCH_MAX)
|
||||
check(runBlocking { p.details(batch) }.size <= batch.size) { "more details than asked" }
|
||||
}
|
||||
|
||||
/** 8. Artwork never throws for a missing picture, and is never wider than asked. */
|
||||
fun artworkIsBounded(p: MediaProvider, f: ContractFixture) {
|
||||
check(runBlocking { p.artwork(f.withoutArtwork, ArtworkKind.Backdrop, 400) } == null) { "a missing picture wasn't null" }
|
||||
check(runBlocking { p.artwork(f.missing, ArtworkKind.Poster, 400) } == null) { "a missing item's picture wasn't null" }
|
||||
val bytes = runBlocking { p.artwork(f.withArtwork, ArtworkKind.Backdrop, 400) }
|
||||
check(bytes != null) { "the picture didn't come back" }
|
||||
val image = ImageIO.read(ByteArrayInputStream(bytes!!))
|
||||
check(image != null && image.width <= 400) { "picture is ${image?.width} px wide, asked for 400" }
|
||||
}
|
||||
|
||||
/** 9. Playback is the original file, played directly: no transcoding asked of the server. */
|
||||
fun playbackIsDirect(p: MediaProvider, f: ContractFixture) {
|
||||
val plan = runBlocking { p.prepare(f.playable) }
|
||||
check(plan.directPlay) { "plan isn't direct play" }
|
||||
check(!Regex("(?i)transcod|/master\\.m3u8|videobitrate|maxstreamingbitrate").containsMatchIn(plan.uri)) { "plan asks the server to transcode" }
|
||||
}
|
||||
|
||||
/** 10. No token, password or address appears in a plan's loggable form or in an error message. */
|
||||
fun credentialsStayOutOfLogs(p: MediaProvider, f: ContractFixture) {
|
||||
val plan = runBlocking { p.prepare(f.playable) }
|
||||
val texts = listOf(plan.loggable(), plan.toString()) + ProviderError.entries.mapNotNull { e ->
|
||||
runCatching { runBlocking { f.failing(e).catalogue(PageRequest(0, 5)) } }.exceptionOrNull()?.let { "${it.message} ${it.cause?.message}" } }
|
||||
f.secrets.forEach { s -> check(texts.none { it.contains(s) }) { "a secret appears in something loggable" } }
|
||||
}
|
||||
|
||||
/** 11. Failures are the same kinds for every provider. */
|
||||
fun errorsAreUniform(p: MediaProvider, f: ContractFixture) {
|
||||
for (e in listOf(ProviderError.Authentication, ProviderError.Unreachable, ProviderError.InvalidResponse)) {
|
||||
val thrown = runCatching { runBlocking { f.failing(e).catalogue(PageRequest(0, 5)) } }.exceptionOrNull()
|
||||
check(thrown is ProviderException && thrown.error == e) { "$e came back as $thrown" }
|
||||
}
|
||||
val gone = runCatching { runBlocking { p.prepare(f.missing) } }.exceptionOrNull()
|
||||
check(gone is ProviderException && gone.error == ProviderError.NotFound) { "a missing item came back as $gone" }
|
||||
val cant = runCatching { runBlocking { p.prepare(f.unplayable) } }.exceptionOrNull()
|
||||
check(cant is ProviderException && cant.error == ProviderError.UnsupportedPlayback) { "an unplayable item came back as $cant" }
|
||||
}
|
||||
|
||||
/** 12. Progress is optional: without the capability, reporting does nothing and never fails. */
|
||||
fun progressIsOptional(p: MediaProvider, f: ContractFixture) {
|
||||
val failure = runCatching { runBlocking { p.reportProgress(f.playable, 60_000, PlaybackState.Progress) } }.exceptionOrNull()
|
||||
check(failure == null) { "reporting progress failed: $failure" }
|
||||
}
|
||||
|
||||
val all: List<Pair<String, (MediaProvider, ContractFixture) -> Unit>> = listOf(
|
||||
"ids are stable" to ::idsAreStable, "ids fit the rule" to ::idsFitTheRule, "catalogue is complete" to ::catalogueIsComplete,
|
||||
"catalogue items are usable" to ::catalogueItemsAreUsable, "episodes are in order" to ::episodesAreInOrder,
|
||||
"collections hold real members" to ::collectionsHoldRealMembers, "details skip the unknown" to ::detailsSkipTheUnknown,
|
||||
"artwork is bounded" to ::artworkIsBounded, "playback is direct" to ::playbackIsDirect,
|
||||
"credentials stay out of logs" to ::credentialsStayOutOfLogs, "errors are uniform" to ::errorsAreUniform,
|
||||
"progress is optional" to ::progressIsOptional)
|
||||
}
|
||||
|
||||
/** Every adapter's contract test extends this, supplying its provider and fixture. */
|
||||
abstract class MediaProviderContract {
|
||||
internal abstract fun provider(): MediaProvider
|
||||
internal abstract fun fixture(): ContractFixture
|
||||
private fun run(check: (MediaProvider, ContractFixture) -> Unit) = check(provider(), fixture())
|
||||
|
||||
@Test fun t01_idsAreStable() = run(ProviderContractChecks::idsAreStable)
|
||||
@Test fun t02_idsFitTheRule() = run(ProviderContractChecks::idsFitTheRule)
|
||||
@Test fun t03_catalogueIsComplete() = run(ProviderContractChecks::catalogueIsComplete)
|
||||
@Test fun t04_catalogueItemsAreUsable() = run(ProviderContractChecks::catalogueItemsAreUsable)
|
||||
@Test fun t05_episodesAreInOrder() = run(ProviderContractChecks::episodesAreInOrder)
|
||||
@Test fun t06_collectionsHoldRealMembers() = run(ProviderContractChecks::collectionsHoldRealMembers)
|
||||
@Test fun t07_detailsSkipTheUnknown() = run(ProviderContractChecks::detailsSkipTheUnknown)
|
||||
@Test fun t08_artworkIsBounded() = run(ProviderContractChecks::artworkIsBounded)
|
||||
@Test fun t09_playbackIsDirect() = run(ProviderContractChecks::playbackIsDirect)
|
||||
@Test fun t10_credentialsStayOutOfLogs() = run(ProviderContractChecks::credentialsStayOutOfLogs)
|
||||
@Test fun t11_errorsAreUniform() = run(ProviderContractChecks::errorsAreUniform)
|
||||
@Test fun t12_progressIsOptional() = run(ProviderContractChecks::progressIsOptional)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Test
|
||||
import java.awt.image.BufferedImage
|
||||
import java.io.ByteArrayOutputStream
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
/**
|
||||
* A reference provider: an in-memory library that keeps the contract, used to prove the contract tests themselves
|
||||
* (8 November 2026). It can be given one flaw at a time, and ContractCatchesFlawsTest shows each check fails on its flaw.
|
||||
* Its media is fictional.
|
||||
*/
|
||||
internal enum class Flaw { None, UnstableIds, PagingRepeats, EpisodesUnordered, SpecialsUnasked, StrayMember, DetailsThrow,
|
||||
WideArtwork, MissingArtworkThrows, Transcodes, LeaksToken, RawErrors, ProgressThrows }
|
||||
|
||||
internal class ReferenceProvider(private val flaw: Flaw = Flaw.None, private val failWith: ProviderError? = null) : MediaProvider {
|
||||
override val kind = ProviderKind.Jellyfin
|
||||
override val library = LibraryId.of(ProviderKind.Jellyfin, "ref0library")
|
||||
override val capabilities = setOf(Capability.Collections)
|
||||
private var reads = 0
|
||||
|
||||
private val films = (1..9).map { CatalogueItem(ItemId("film$it"), MediaType.Movie, "Fictional Film $it", 1990 + it, 95 * 60_000L) }
|
||||
private val shows = (1..3).map { CatalogueItem(ItemId("show$it"), MediaType.Series, "Fictional Show $it", 2000 + it) }
|
||||
private val items get() = films + shows
|
||||
private val episodes = (0..2).flatMap { s -> (1..(if (s == 0) 2 else 4)).map { e ->
|
||||
Episode(ItemId("ep${s}x$e"), ItemId("show1"), s, e, "Episode $s.$e", 30 * 60_000L, listOf(SourceId("src${s}x$e"))) } }
|
||||
|
||||
private fun fail() { failWith?.let { e ->
|
||||
if (flaw == Flaw.RawErrors) throw RuntimeException("GET http://192.168.1.50:8096/Items?api_key=SECRETTOKEN failed")
|
||||
throw ProviderException(e, when (e) { ProviderError.Authentication -> "Sign in again"; ProviderError.Unreachable -> "The library isn't answering"
|
||||
ProviderError.InvalidResponse -> "The library sent something Orbit can't read"; else -> e.name })
|
||||
} }
|
||||
|
||||
override suspend fun catalogue(page: PageRequest): Page<CatalogueItem> {
|
||||
fail(); reads++
|
||||
val list = if (flaw == Flaw.UnstableIds && reads % 2 == 0) items.map { it.copy(id = ItemId(it.id.value + "x")) } else items
|
||||
val from = if (flaw == Flaw.PagingRepeats) maxOf(0, page.start - 1) else page.start
|
||||
return Page(list.drop(from).take(page.limit), list.size, from + minOf(page.limit, maxOf(0, list.size - from)))
|
||||
}
|
||||
override suspend fun episodes(seriesId: ItemId, includeSpecials: Boolean): List<Episode> {
|
||||
fail()
|
||||
val chosen = episodes.filter { it.seriesId == seriesId && (includeSpecials || it.season != 0 || flaw == Flaw.SpecialsUnasked) }
|
||||
return if (flaw == Flaw.EpisodesUnordered) chosen.reversed() else chosen
|
||||
}
|
||||
override suspend fun collections(page: PageRequest): Page<MediaCollection> {
|
||||
fail()
|
||||
val all = listOf(MediaCollection(ItemId("set1"), "Fictional Saga", listOf(ItemId("film1"), ItemId("film2"), ItemId(if (flaw == Flaw.StrayMember) "film99" else "film3"))))
|
||||
return Page(all.drop(page.start).take(page.limit), all.size)
|
||||
}
|
||||
override suspend fun details(ids: List<ItemId>): List<ItemDetails> {
|
||||
fail(); require(ids.size <= DETAILS_BATCH_MAX)
|
||||
if (flaw == Flaw.DetailsThrow && ids.any { it !in items.map { i -> i.id } }) throw ProviderException(ProviderError.NotFound, "unknown item")
|
||||
return ids.filter { id -> items.any { it.id == id } }.map { ItemDetails(it, overview = "A fictional synopsis.") }
|
||||
}
|
||||
override suspend fun artwork(id: ItemId, kind: ArtworkKind, maxWidthPx: Int): ByteArray? {
|
||||
fail()
|
||||
if (id.value != "film1") { if (flaw == Flaw.MissingArtworkThrows) throw ProviderException(ProviderError.NotFound, "no picture"); return null }
|
||||
val width = if (flaw == Flaw.WideArtwork) 1280 else minOf(1280, maxWidthPx)
|
||||
return ByteArrayOutputStream().also { ImageIO.write(BufferedImage(width, width * 9 / 16, BufferedImage.TYPE_INT_RGB), "png", it) }.toByteArray()
|
||||
}
|
||||
override suspend fun prepare(item: ItemId, source: SourceId?): PlaybackPlan {
|
||||
fail()
|
||||
if (item.value == "film9") throw ProviderException(ProviderError.UnsupportedPlayback, "This file's video can't be played directly on this TV")
|
||||
if (items.none { it.id == item } && episodes.none { it.id == item }) throw ProviderException(ProviderError.NotFound, "That programme is no longer in the library")
|
||||
val uri = "http://192.168.1.50:8096/Videos/${item.value}/stream.mkv?static=true" + if (flaw == Flaw.Transcodes) "&VideoBitrate=4000000" else ""
|
||||
// A careless adapter that puts its token somewhere loggable (here the container label) is caught by check 10.
|
||||
return PlaybackPlan(uri, mapOf("X-Emby-Token" to "SECRETTOKEN"), audio = listOf(TrackInfo("1", "eng")),
|
||||
container = if (flaw == Flaw.LeaksToken) "mkv;token=SECRETTOKEN" else "mkv")
|
||||
}
|
||||
override suspend fun reportProgress(item: ItemId, positionMs: Long, state: PlaybackState) {
|
||||
if (flaw == Flaw.ProgressThrows) throw ProviderException(ProviderError.Unreachable, "no progress")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun referenceFixture(flaw: Flaw = Flaw.None) = ContractFixture(
|
||||
catalogueSize = 12, series = ItemId("show1"), seriesEpisodes = 8, seriesSpecials = 2, collections = 1,
|
||||
known = listOf(ItemId("film1"), ItemId("show2")), missing = ItemId("gone1"),
|
||||
withArtwork = ItemId("film1"), withoutArtwork = ItemId("film2"), playable = ItemId("film1"), unplayable = ItemId("film9"),
|
||||
secrets = listOf("SECRETTOKEN", "192.168.1.50"), failing = { e -> ReferenceProvider(flaw, e) })
|
||||
|
||||
/** The reference provider keeps the whole contract. */
|
||||
class ReferenceProviderContractTest : MediaProviderContract() {
|
||||
override fun provider(): MediaProvider = ReferenceProvider()
|
||||
override fun fixture() = referenceFixture()
|
||||
}
|
||||
|
||||
/** Every check fails on the flaw it is there to catch, so a passing adapter really keeps the contract. */
|
||||
class ContractCatchesFlawsTest {
|
||||
private val catches = mapOf(
|
||||
Flaw.UnstableIds to "ids are stable", Flaw.PagingRepeats to "catalogue is complete", Flaw.EpisodesUnordered to "episodes are in order",
|
||||
Flaw.SpecialsUnasked to "episodes are in order", Flaw.StrayMember to "collections hold real members", Flaw.DetailsThrow to "details skip the unknown",
|
||||
Flaw.WideArtwork to "artwork is bounded", Flaw.MissingArtworkThrows to "artwork is bounded", Flaw.Transcodes to "playback is direct",
|
||||
Flaw.LeaksToken to "credentials stay out of logs", Flaw.RawErrors to "credentials stay out of logs", Flaw.ProgressThrows to "progress is optional")
|
||||
|
||||
@Test fun eachCheckCatchesItsFlaw() {
|
||||
for ((flaw, name) in catches) {
|
||||
val check = ProviderContractChecks.all.first { it.first == name }.second
|
||||
val caught = runCatching { check(ReferenceProvider(flaw), referenceFixture(flaw)) }.exceptionOrNull()
|
||||
assertNotNull("'$name' missed $flaw", caught) // an assertion, or the adapter's own exception: either way the test fails
|
||||
}
|
||||
// Raw errors are also caught as non-uniform.
|
||||
val uniform = ProviderContractChecks.all.first { it.first == "errors are uniform" }.second
|
||||
assertNotNull(runCatching { uniform(ReferenceProvider(Flaw.RawErrors), referenceFixture(Flaw.RawErrors)) }.exceptionOrNull())
|
||||
}
|
||||
|
||||
@Test fun localIdsAreStableAndDistinct() {
|
||||
assertEquals(localMediaId("Films/Fictional Film (1991)/film.mkv"), localMediaId("/Films/Fictional Film (1991)/film.mkv"))
|
||||
assertEquals(localMediaId("Films\\A\\a.mkv"), localMediaId("Films/A/a.mkv"))
|
||||
val ids = (1..5000).map { localMediaId("Shows/Show/S01/E$it.mkv").value }
|
||||
assertEquals(ids.size, ids.toSet().size); assertEquals(32, ids.first().length); assert(ids.all(::validMediaId))
|
||||
}
|
||||
|
||||
@Test fun libraryIdsNameTheirKind() {
|
||||
assertEquals(ProviderKind.Plex, LibraryId.of(ProviderKind.Plex, "abc123").kind)
|
||||
assert(runCatching { LibraryId("192.168.0.20:8096") }.isFailure) // an address is never a library id
|
||||
}
|
||||
}
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
# Orbit's release gate (8 November 2026): the same checks for every change and every provider, before anything reaches a TV.
|
||||
# Builds the release APK, runs every unit test (the shared provider contract suite included) and lint, and fails on any
|
||||
# failure, any lint error, or a missing contract suite. Prints the APK's SHA-256 for the install record.
|
||||
# tools/verify.sh (uses Orbit's offline .tooling cache when it's there)
|
||||
set -euo pipefail
|
||||
ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
TOOLING="${ORBIT_TOOLING:-$ROOT/../orbit-tv/.tooling}"
|
||||
OFFLINE=()
|
||||
if [ -d "$TOOLING/gradle-cache" ]; then export GRADLE_USER_HOME="$TOOLING/gradle-cache" ANDROID_USER_HOME="$TOOLING/android"; OFFLINE=(--offline); fi
|
||||
export ANDROID_HOME="${ANDROID_HOME:-/opt/android-sdk}"
|
||||
cd "$ROOT/android"
|
||||
./gradlew --no-daemon "${OFFLINE[@]}" -q :app:assembleRelease :app:testDebugUnitTest --rerun :app:lintRelease
|
||||
python3 - <<'PY'
|
||||
import glob, re, sys
|
||||
tests = fails = 0; contract = False
|
||||
for p in glob.glob('app/build/test-results/testDebugUnitTest/*.xml'):
|
||||
s = open(p).read(); m = re.search(r'tests="(\d+)".*?failures="(\d+)".*?errors="(\d+)"', s)
|
||||
tests += int(m[1]); fails += int(m[2]) + int(m[3])
|
||||
if 'ContractTest' in p and 'MediaProviderContract' not in p: contract = True
|
||||
lint = len(re.findall(r'severity="(Error|Fatal)"', open('app/build/reports/lint-results-release.xml').read()))
|
||||
print(f"tests {tests}, failures {fails}, lint errors {lint}, contract suite {'present' if contract else 'MISSING'}")
|
||||
sys.exit(0 if fails == 0 and lint == 0 and contract and tests > 0 else 1)
|
||||
PY
|
||||
sha256sum app/build/outputs/apk/release/app-release.apk | cut -c1-64
|
||||
echo "Release gate passed."
|
||||
Reference in New Issue
Block a user