Provider contract step 2: Emby and Jellyfin adapter, not wired in
EmbyProvider wraps today's readers and the session (catalogue page, whole series, collections, evidence, PlaybackInfo, progress) instead of rewriting them; only specials and picture sizes are read in the adapter. No existing file changed. Library id is the server's own id. Progress can be turned off. Failures map to the five contract kinds with fixed messages (no server text, address or token). Tests: Emby and Jellyfin both pass the 12 contract checks against a fixture library shaped like real replies; parity tests show the adapter returns exactly what today's catalogue import and whole-series read produce. The contract caught one real gap on the way (a 404 read as an unreadable reply), fixed in the adapter. 766 tests, lint clean. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
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), withTotal = true)
|
||||
Page(read.records.map { r ->
|
||||
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 })
|
||||
}, (read.total ?: 0L).toInt())
|
||||
}
|
||||
|
||||
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.")
|
||||
}
|
||||
@@ -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") })
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ 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 += pageSize; if (page.items.isEmpty() || start >= page.total) break }
|
||||
while (true) { val page = p.catalogue(PageRequest(start, pageSize)); out += page.items; start += page.items.size; if (page.items.isEmpty() || start >= page.total) break }
|
||||
out
|
||||
}
|
||||
|
||||
@@ -107,12 +107,11 @@ internal object ProviderContractChecks {
|
||||
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. */
|
||||
/** 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" }
|
||||
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. */
|
||||
|
||||
Reference in New Issue
Block a user