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 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 17:19:14 +00:00
co-authored by Claude Opus 5.5
parent 84b28b6f34
commit a719f68b19
5 changed files with 470 additions and 0 deletions
@@ -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<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)
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<T>(val items: List<T>, 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<String> = 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<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))