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 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