From a719f68b197cc3f45981968c1352d5a114d7375b Mon Sep 17 00:00:00 2001 From: Pauljd Date: Sun, 8 Nov 2026 17:19:14 +0000 Subject: [PATCH] Provider contract step 1: MediaProvider interface, shared contract tests, release gate Paul approved the seven-operation contract (8 November 2026). This step adds it alongside today's Emby session, which the app still uses unchanged: nothing calls MediaProvider yet, so no behaviour, stored id, schedule, database or signing changes. - MediaProvider.kt: the contract, LibraryId (server's own id, never its address), MediaRef for anything leaving its library, five ProviderError kinds, PlaybackPlan whose loggable form leaves out credentials, local file ids from a 128-bit SHA-256 prefix. - MediaProviderContract: twelve shared checks every adapter must pass; a reference provider passes them all, and ContractCatchesFlawsTest shows each check fails on the flaw it guards against. - tools/verify.sh: the release gate (build, all tests, lint, contract suite present); .gitea/workflows/ci.yml runs it on every push where a runner exists. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 14 ++ .../java/tv/orbit/classic/MediaProvider.kt | 140 ++++++++++++++ .../tv/orbit/classic/MediaProviderContract.kt | 171 ++++++++++++++++++ .../classic/ReferenceProviderContractTest.kt | 119 ++++++++++++ tools/verify.sh | 26 +++ 5 files changed, 470 insertions(+) create mode 100644 .gitea/workflows/ci.yml create mode 100644 android/app/src/main/java/tv/orbit/classic/MediaProvider.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/MediaProviderContract.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/ReferenceProviderContractTest.kt create mode 100755 tools/verify.sh diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 00000000..2f4e28dd --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -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 diff --git a/android/app/src/main/java/tv/orbit/classic/MediaProvider.kt b/android/app/src/main/java/tv/orbit/classic/MediaProvider.kt new file mode 100644 index 00000000..187e2734 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/MediaProvider.kt @@ -0,0 +1,140 @@ +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 + + /** Films and series, a page at a time, for the local catalogue. */ + suspend fun catalogue(page: PageRequest): Page + + /** A series' episodes in season and episode order; specials (season 0) only when asked. */ + suspend fun episodes(seriesId: ItemId, includeSpecials: Boolean = false): List + + /** The library's own collections and their members; empty without [Capability.Collections]. */ + suspend fun collections(page: PageRequest): Page + + /** 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): List + + /** 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) + +internal data class PageRequest(val start: Int, val limit: Int) { + init { require(start >= 0 && limit in 1..PAGE_MAX) } + companion object { const val PAGE_MAX = 500 } +} + +internal data class Page(val items: List, val total: Int) + +internal data class CatalogueItem(val id: ItemId, val type: MediaType, val title: String, val year: Int? = null, val runtimeMs: Long? = null, + val genres: List = emptyList(), val rating: String? = null, val premiere: String? = null) + +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 = emptyList()) + +internal data class MediaCollection(val id: ItemId, val name: String, val members: List, val complete: Boolean = true) + +internal data class ItemDetails(val id: ItemId, val overview: String? = null, val tagline: String? = null, val leads: List = emptyList(), + val directors: List = emptyList(), val genres: List = emptyList(), val studios: List = 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, val subtitles: List = emptyList(), + val audio: List = 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)) diff --git a/android/app/src/test/java/tv/orbit/classic/MediaProviderContract.kt b/android/app/src/test/java/tv/orbit/classic/MediaProviderContract.kt new file mode 100644 index 00000000..651556a0 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/MediaProviderContract.kt @@ -0,0 +1,171 @@ +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, 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, + /** 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 = runBlocking { + val out = ArrayList(); var start = 0 + while (true) { val page = p.catalogue(PageRequest(start, pageSize)); out += page.items; start += pageSize; 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, with its tracks listed. */ + 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" } + check(plan.audio.isNotEmpty()) { "no audio track listed" } + } + + /** 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 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) +} diff --git a/android/app/src/test/java/tv/orbit/classic/ReferenceProviderContractTest.kt b/android/app/src/test/java/tv/orbit/classic/ReferenceProviderContractTest.kt new file mode 100644 index 00000000..bf877369 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/ReferenceProviderContractTest.kt @@ -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 { + 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) + } + override suspend fun episodes(seriesId: ItemId, includeSpecials: Boolean): List { + 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 { + 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): List { + 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 + } +} diff --git a/tools/verify.sh b/tools/verify.sh new file mode 100755 index 00000000..3ecc7a50 --- /dev/null +++ b/tools/verify.sh @@ -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."