From 592882219fe2898193c7246fec2b7676f4c41fa9 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Tue, 17 Nov 2026 13:50:06 +0000 Subject: [PATCH] Built-in recovery when a server renumbers: bookings keep each film's and series' provider ID and year (1.0 RC3-14, build 56) Paul, 17 November 2026: Halloween on After Dark failed after a rescan gave it a new number, because its name is shared by three films. A booked programme now keeps its IMDb or TVDB ID and year, saved with the schedule. When its number has gone, the film or series is found again by that ID first (one small request, and it survives a rename), then by name and year, then by the channel's own list entry for programmes booked before IDs were kept. Co-Authored-By: Claude Opus 5.5 --- android/app/build.gradle.kts | 2 +- .../java/tv/orbit/classic/ChannelPresets.kt | 2 +- .../java/tv/orbit/classic/ChannelSchedule.kt | 36 ++++++++-- .../src/main/java/tv/orbit/classic/DriveIn.kt | 2 +- .../main/java/tv/orbit/classic/EmbyClient.kt | 8 ++- .../tv/orbit/classic/EmbyPlaybackProtocol.kt | 56 ++++++++++----- .../java/tv/orbit/classic/EpisodeDiscovery.kt | 2 +- .../java/tv/orbit/classic/FilmIdentity.kt | 2 +- .../java/tv/orbit/classic/ScheduleStore.kt | 11 +-- .../java/tv/orbit/classic/SeriesDiscovery.kt | 6 +- .../test/java/tv/orbit/classic/RefiledTest.kt | 68 +++++++++++++++++++ 11 files changed, 160 insertions(+), 35 deletions(-) diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index b78566bb..78f5e564 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -3,7 +3,7 @@ plugins { id("org.jetbrains.kotlin.plugin.compose") } /** The release's build number: versionCode is this x 10 plus the edition's channel. */ -val ORBIT_BUILD = 55 +val ORBIT_BUILD = 56 android { namespace = "tv.orbit.classic" compileSdk = 36 diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelPresets.kt b/android/app/src/main/java/tv/orbit/classic/ChannelPresets.kt index d0d3373d..ab5f86e2 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelPresets.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelPresets.kt @@ -78,7 +78,7 @@ internal val ChannelPresets = listOf( internal fun loopFromPool(pool: List, programming: ChannelProgramming): SampleChannel? { val turns = (0 until (pool.maxOfOrNull { it.episodes.size } ?: 0)).asSequence().flatMap { round -> pool.asSequence().mapNotNull { show -> show.episodes.getOrNull(round)?.let { show to it } } } val media = turns.take(15).map { (show, episode) -> - val item = if (show.isFilm) SampleItem(show.title, "Movie", episode.durationMs / 60_000, "", episode.id, episode.durationMs) else scheduledItem(show.title, episode) + val item = bookedItem(show, episode) ScheduledMedia(item, episode.sourceId, episode.durationMs) }.toList() return if (media.size < 2) null else SampleChannel(media, programming.name, programming.number) diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt index 6a3b7e0e..c95517c8 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt @@ -1,5 +1,7 @@ package tv.orbit.classic +import org.json.JSONObject + /** Local hours, wrapping past midnight, and the titles a channel may use then. No titles means everything in its pool. */ internal data class DayPart(val fromHour: Int, val toHour: Int, val titles: List = emptyList(), val group: String = "", /** Set for an event: only these days, starting from its [fromHour] on each. List it before the everyday blocks. */ @@ -296,7 +298,8 @@ internal data class EpisodeMark(val season: Int, val episode: Int) : Comparable< override fun compareTo(other: EpisodeMark) = compareValuesBy(this, other, { it.season }, { it.episode }) } internal data class PoolEpisode(val id: String, val sourceId: String, val mark: EpisodeMark, val title: String, val durationMs: Long) -internal data class PoolSeries(val id: String, val title: String, val episodes: List, val group: String = "") { +/** [ref] and [year]: which film or series this is apart from the server's number, as [SampleItem] keeps them. */ +internal data class PoolSeries(val id: String, val title: String, val episodes: List, val group: String = "", val ref: String = "", val year: Int? = null) { /** A film is its own only episode. */ val isFilm get() = episodes.size == 1 && episodes[0].id == id } @@ -533,7 +536,7 @@ internal fun extendFilmSchedule(pool: List, cursor: ScheduleCursor, } } val copy = film.episodes.first() - val item = SampleItem(film.title, "Movie", copy.durationMs / 60_000, "", copy.id, copy.durationMs) + val item = filmItem(film, copy) // Only a programme actually drawn from the event's own titles carries its presentation. entries += ScheduleEntry(film.id, copy.mark, ScheduledMedia(item, copy.sourceId, copy.durationMs), start, "$block; $why", if (film in available) part?.key.orEmpty() else "") shown[film.id] = start @@ -831,7 +834,7 @@ internal fun extendWeighted(pool: List, cursor: ScheduleCursor, from } + (if (fitted != null) "; chosen to finish before the appointment at ${java.time.Instant.ofEpochMilli(appointment!!).atZone(zone).toLocalTime()}" else "") + (if (story != null) "; story: part 1 of ${story.first}, booked whole" else "") + (if (part?.premiere == true && series in available) "; premiere: first airing on Orbit" else "") - val item = if (series.isFilm) SampleItem(series.title, "Movie", episode.durationMs / 60_000, "", episode.id, episode.durationMs) else scheduledItem(series.title, episode) + val item = bookedItem(series, episode) val tag = shortsTagFor(shorts, slot, series, episode, series in available, start, zone).also { slot = it.second }.first entries += ScheduleEntry(series.id, episode.mark, ScheduledMedia(item, episode.sourceId, episode.durationMs), start, why + if (tag.isEmpty()) "" else "; shorts slot", if (series in available) part?.key.orEmpty() else "", tag) val weight = part?.takeIf { series in available }?.weights?.get(seriesKey(series.title)) ?: weightOf(series) @@ -1005,7 +1008,7 @@ internal fun extendSchedule(pool: List, cursor: ScheduleCursor, from if (waiting.isNotEmpty()) append("; deferred until the rest finish: ${someOf(waiting)}") if (elsewhere.isNotEmpty()) append("; deferred, airing elsewhere: ${someOf(elsewhere)}") } - val item = if (series.isFilm) SampleItem(series.title, "Movie", episode.durationMs / 60_000, "", episode.id, episode.durationMs) else scheduledItem(series.title, episode) + val item = bookedItem(series, episode) val media = ScheduledMedia(item, episode.sourceId, episode.durationMs) val tag = shortsTagFor(shorts, slot, series, episode, series in available, start, zone).also { slot = it.second }.first entries += ScheduleEntry(series.id, episode.mark, media, start, why + if (tag.isEmpty()) "" else "; shorts slot", if (series in available) part?.key.orEmpty() else "", tag) @@ -1019,9 +1022,30 @@ internal fun extendSchedule(pool: List, cursor: ScheduleCursor, from return ChannelPlan(withoutLoneShorts(entries), ScheduleCursor(last, marks, shown, blockLast)) } -internal fun scheduledItem(seriesTitle: String, episode: PoolEpisode) = SampleItem( +internal fun scheduledItem(seriesTitle: String, episode: PoolEpisode, ref: String = "", year: Int? = null) = SampleItem( "$seriesTitle / S${episode.mark.season} E${episode.mark.episode} / ${episode.title}", - "Episode", episode.durationMs / 60_000, "", episode.id, episode.durationMs) + "Episode", episode.durationMs / 60_000, "", episode.id, episode.durationMs, ref, year) + +/** A film booked from [film], keeping which film it is (see [SampleItem.ref]). */ +internal fun filmItem(film: PoolSeries, copy: PoolEpisode = film.episodes.first()) = + SampleItem(film.title, "Movie", copy.durationMs / 60_000, "", copy.id, copy.durationMs, film.ref, film.year) + +/** What a programme from [series] is booked as: a film keeps its name, an episode its series, season and number. */ +internal fun bookedItem(series: PoolSeries, episode: PoolEpisode) = + if (series.isFilm) filmItem(series, episode) else scheduledItem(series.title, episode, series.ref, series.year) + +/** A provider ID as the server matches it ("imdb.tt0077651"): the first of [order] the item has, or empty. */ +internal fun providerRef(item: JSONObject, order: List): String { + val ids = item.optJSONObject("ProviderIds") ?: return "" + for (name in order) { + val key = ids.keys().asSequence().firstOrNull { it.equals(name, true) } ?: continue + val value = ids.optString(key).trim() + if (value.matches(Regex("[A-Za-z0-9_-]{1,40}"))) return "${name.lowercase()}.$value" + } + return "" +} +internal val FILM_REF_ORDER = listOf("Imdb", "Tmdb") +internal val SERIES_REF_ORDER = listOf("Tvdb", "Imdb", "Tmdb") /** What has actually gone out by [nowMs]. Saved apart from the schedule, so losing the schedule doesn't lose the place. */ internal fun airedCursor(base: ScheduleCursor, entries: List, nowMs: Long): ScheduleCursor { diff --git a/android/app/src/main/java/tv/orbit/classic/DriveIn.kt b/android/app/src/main/java/tv/orbit/classic/DriveIn.kt index ff87dec2..748dac20 100644 --- a/android/app/src/main/java/tv/orbit/classic/DriveIn.kt +++ b/android/app/src/main/java/tv/orbit/classic/DriveIn.kt @@ -93,7 +93,7 @@ internal fun driveInBookedAhead(plan: ChannelPlan?, nowMs: Long, zone: ZoneId = private fun filmEntry(film: PoolSeries, startMs: Long): ScheduleEntry { val copy = film.episodes.first() - return ScheduleEntry(film.id, copy.mark, ScheduledMedia(SampleItem(film.title, "Movie", copy.durationMs / 60_000, "", copy.id, copy.durationMs), copy.sourceId, copy.durationMs), startMs) + return ScheduleEntry(film.id, copy.mark, ScheduledMedia(filmItem(film, copy), copy.sourceId, copy.durationMs), startMs) } /** The Late Show's limit: longer than this is a compilation reel or a marathon, not a late film. */ diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt index c3801caa..13fadbef 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt @@ -10,7 +10,13 @@ import java.net.HttpURLConnection internal open class EmbyCheckException(message: String, val httpStatus: Int? = null, val retryable: Boolean = false) : Exception(message) /** The server took too long or couldn't be reached at all, as opposed to answering with a problem (1.0 RC3). */ internal class ServerNotAnswering(message: String) : EmbyCheckException(message, retryable = true) -internal data class SampleItem(val title: String, val type: String, val minutes: Long?, val format: String, val id: String = "", val durationMs: Long? = minutes?.takeIf { it in 1..(Long.MAX_VALUE / 60_000) }?.times(60_000)) +/** + * [ref] and [year] say which film or series this is apart from the server's own number (17 November 2026: a rescan renumbers + * items, and a name alone can belong to several films). [ref] is a provider ID as the server matches it, as "imdb.tt0077651" + * or "tvdb.81189"; empty when the server gave none. + */ +internal data class SampleItem(val title: String, val type: String, val minutes: Long?, val format: String, val id: String = "", val durationMs: Long? = minutes?.takeIf { it in 1..(Long.MAX_VALUE / 60_000) }?.times(60_000), + val ref: String = "", val year: Int? = null) internal data class EmbySample(val items: List, val total: Long?) internal class EmbyRequest(val method: String, val path: String, val body: String? = null, val token: String? = null, val readTimeoutMs: Int? = null) internal class EmbyReply(val status: Int, val body: String) diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt index c196ea33..972607e1 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt @@ -383,7 +383,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v if (programming.filmRestMs != null) { // Films already in this channel's old line-up stay in it, unless the list now names another film of that title. val listed = programming.searches.map { seriesKey(FilmIdentity.of(it).title) }.toSet() - val earlier = loop?.lineup.orEmpty().filter { it.item.type == "Movie" }.map { PoolSeries(it.item.id, it.item.title, listOf(PoolEpisode(it.item.id, it.sourceId, EpisodeMark(1, 1), it.item.title, it.durationMs))) } + val earlier = loop?.lineup.orEmpty().filter { it.item.type == "Movie" }.map { PoolSeries(it.item.id, it.item.title, listOf(PoolEpisode(it.item.id, it.sourceId, EpisodeMark(1, 1), it.item.title, it.durationMs)), ref = it.item.ref, year = it.item.year) } pool += earlier.filter { seriesKey(it.title) !in listed } // The limit counts films found from the list, so films carried over from the old line-up can't crowd the list out. var found = 0 @@ -469,7 +469,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v // A film placed from the Director's Chair carries no copy yet: its first copy this box can play is found here, or it waits. val (source, duration) = if (accepted.sourceId != null && accepted.durationMs != null) accepted.sourceId to accepted.durationMs else { requests++; playableFilm(accepted.id, programming.englishAudio) ?: continue } - pool += PoolSeries(accepted.id, accepted.title, listOf(PoolEpisode(accepted.id, source, EpisodeMark(1, 1), accepted.title, duration)), accepted.group) + pool += PoolSeries(accepted.id, accepted.title, listOf(PoolEpisode(accepted.id, source, EpisodeMark(1, 1), accepted.title, duration)), accepted.group, year = accepted.year) } else { val whole = try { readWholeSeries(transport, userId, ::currentToken, SeriesCandidate(accepted.id, accepted.title, accepted.year, ""), checkActive, onRequest = { requests++ }, canDecode = BoxDecoders::canDecode, englishAudio = programming.englishAudio) } catch (failure: Exception) { @@ -526,15 +526,36 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v fun refiledFilm(item: SampleItem, channelNumber: Int? = null): ScheduledMedia? { if (item.type != "Movie") return null - // The booked title has no year (17 November 2026: "Halloween" on After Dark matched the 1978, 2007 and 2018 films, so - // it was never found again). The channel's own list entry carries the year and IMDb ID, so it's searched by that. - val entry = channelNumber?.let { listedFilmEntry(it, item.title) } ?: item.title - val film = findFilm(transport, userId, ::currentToken, entry, BoxDecoders::canDecode).film ?: return null + val film = refiledFilmLookup(item, channelNumber) ?: return null if (film.id == item.id) return null - val copy = film.episodes.first() - val found = SampleItem(film.title, "Movie", copy.durationMs / 60_000, "", copy.id, copy.durationMs) + val found = filmItem(film) rememberScheduledItems(listOf(found)) - return ScheduledMedia(found, copy.sourceId, copy.durationMs) + return ScheduledMedia(found, film.episodes.first().sourceId, found.durationMs!!) + } + + /** + * Built in for any server that renumbers (17 November 2026: "Halloween" on After Dark matched the 1978, 2007 and 2018 + * films, so it was never found again). The film's own provider ID first, which survives a rename too; then its name and + * year; then, for a programme booked before IDs were kept, the channel's own list entry, which carries the year. + */ + private fun refiledFilmLookup(item: SampleItem, channelNumber: Int?): PoolSeries? { + if (item.ref.isNotEmpty()) { + val rows = byProvider("Movie", item.ref, "&Fields=MediaSources,ProviderIds,ProductionYear") + val candidates = rows.mapNotNull(::filmCandidate) + val imdb = item.ref.takeIf { it.startsWith("imdb.") }?.removePrefix("imdb.") + candidates.firstOrNull()?.let { first -> resolveFilm(FilmIdentity(first.name, item.year, imdb), candidates, BoxDecoders::canDecode).film?.let { return it } } + } + val entry = item.year?.let { "${item.title} ($it)" } ?: channelNumber?.let { listedFilmEntry(it, item.title) } ?: item.title + return findFilm(transport, userId, ::currentToken, entry, BoxDecoders::canDecode).film + } + + /** Items of [type] carrying provider ID [ref], at most ten; one small request. */ + private fun byProvider(type: String, ref: String, fields: String = ""): List { + val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Recursive=true&IncludeItemTypes=$type&AnyProviderIdEquals=${java.net.URLEncoder.encode(ref, "UTF-8")}" + + "&StartIndex=0&Limit=10$fields&EnableImages=false&EnableUserData=false", token = currentToken())) + EmbyClient.expectSuccess(reply.status, false) + val rows = EmbyClient.parse(reply.body).optJSONArray("Items") ?: return emptyList() + return (0 until minOf(rows.length(), 10)).mapNotNull { rows.optJSONObject(it) }.filter { it.optString("Type") == type && EmbyClient.validId(it.optString("Id")) } } /** @@ -544,12 +565,15 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v fun refiledEpisode(item: SampleItem): ScheduledMedia? { if (item.type != "Episode") return null val (series, season, number) = Regex("""^(.*) / S(\d+) E(\d+) / """).find(item.title)?.destructured ?: return null - val term = java.net.URLEncoder.encode(series, "UTF-8") - val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Recursive=true&IncludeItemTypes=Series&SearchTerm=$term&StartIndex=0&Limit=10&EnableImages=false&EnableUserData=false", token = currentToken())) - EmbyClient.expectSuccess(reply.status, false) - val rows = EmbyClient.parse(reply.body).optJSONArray("Items") ?: return null - val named = (0 until minOf(rows.length(), 10)).mapNotNull { rows.optJSONObject(it) } - .filter { seriesKey(it.optString("Name")) == seriesKey(series) && EmbyClient.validId(it.optString("Id")) }.take(2) + // The series by its provider ID first (it survives a rename), then by its exact name. + val named = item.ref.takeIf { it.isNotEmpty() }?.let { byProvider("Series", it) }.orEmpty().take(2).ifEmpty { + val term = java.net.URLEncoder.encode(series, "UTF-8") + val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Recursive=true&IncludeItemTypes=Series&SearchTerm=$term&StartIndex=0&Limit=10&EnableImages=false&EnableUserData=false", token = currentToken())) + EmbyClient.expectSuccess(reply.status, false) + val rows = EmbyClient.parse(reply.body).optJSONArray("Items") ?: return null + (0 until minOf(rows.length(), 10)).mapNotNull { rows.optJSONObject(it) } + .filter { seriesKey(it.optString("Name")) == seriesKey(series) && EmbyClient.validId(it.optString("Id")) }.take(2) + } for (show in named) { val episodes = transport.execute(EmbyRequest("GET", "/Shows/${show.optString("Id")}/Episodes?UserId=$userId&Season=$season&Fields=MediaSources&EnableImages=false&EnableUserData=false", token = currentToken())) EmbyClient.expectSuccess(episodes.status, false) @@ -558,7 +582,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v .firstOrNull { it.optInt("ParentIndexNumber", -1) == season.toInt() && it.optInt("IndexNumber", -1) == number.toInt() } ?.let { poolEpisode(it, BoxDecoders::canDecode, englishAudio = false) } ?: continue if (episode.id == item.id) return null - val found = scheduledItem(series, episode) + val found = scheduledItem(series, episode, item.ref, item.year) rememberScheduledItems(listOf(found)) return ScheduledMedia(found, episode.sourceId, episode.durationMs) } diff --git a/android/app/src/main/java/tv/orbit/classic/EpisodeDiscovery.kt b/android/app/src/main/java/tv/orbit/classic/EpisodeDiscovery.kt index 8995caac..ef70402d 100644 --- a/android/app/src/main/java/tv/orbit/classic/EpisodeDiscovery.kt +++ b/android/app/src/main/java/tv/orbit/classic/EpisodeDiscovery.kt @@ -72,7 +72,7 @@ internal fun readWholeSeries(transport: EmbyTransport, userId: String, token: () start += rows.length() if (rows.length() == 0 || start >= body.optInt("TotalRecordCount", 0)) break } - return PoolSeries(series.id, series.title, episodes.sortedBy { it.mark }.distinctBy { it.mark }) + return PoolSeries(series.id, series.title, episodes.sortedBy { it.mark }.distinctBy { it.mark }, ref = series.ref, year = series.year) } internal fun poolEpisode(item: org.json.JSONObject, canDecode: (String) -> Boolean, englishAudio: Boolean): PoolEpisode? { diff --git a/android/app/src/main/java/tv/orbit/classic/FilmIdentity.kt b/android/app/src/main/java/tv/orbit/classic/FilmIdentity.kt index a204fc15..3255fece 100644 --- a/android/app/src/main/java/tv/orbit/classic/FilmIdentity.kt +++ b/android/app/src/main/java/tv/orbit/classic/FilmIdentity.kt @@ -70,7 +70,7 @@ internal fun resolveFilm(identity: FilmIdentity, candidates: List val duration = (ticks / 10_000).takeIf { it in 1_000..SampleChannel.MAX_DURATION_MS } if (duration == null) { passed += "${copy.id} no runtime"; continue } val note = if (passed.isEmpty()) "" else "film=\"${identity.label}\" used ${copy.id}, passed over: ${passed.joinToString()}" - return FilmLookup(PoolSeries(copy.id, copy.name, listOf(PoolEpisode(copy.id, source.getString("Id"), EpisodeMark(1, 1), copy.name, duration))), note) + return FilmLookup(PoolSeries(copy.id, copy.name, listOf(PoolEpisode(copy.id, source.getString("Id"), EpisodeMark(1, 1), copy.name, duration)), ref = copy.imdb?.let { "imdb.$it" }.orEmpty(), year = copy.year ?: identity.year), note) } return FilmLookup(null, "film=\"${identity.label}\" unplayable: ${passed.joinToString()}") } diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt index 73bc34dd..408c798e 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -123,12 +123,13 @@ internal class ScheduleStore(private val directory: File) { private fun validId(id: String) = id.also { require(EmbyClient.validId(it)) } /** Reasons are diagnostics. A long one is cut rather than refused, so it can never cost a plan. */ private val MAX_REASON_CHARS = 400 + private val REF = Regex("""(imdb|tmdb|tvdb)\.[A-Za-z0-9_-]{1,40}""") private fun validDuration(ms: Long) = ms.also { require(it in 1_000..SampleChannel.MAX_DURATION_MS) } fun savePlan(userId: String, number: Int, plan: ChannelPlan) { val entries = JSONArray() plan.entries.forEach { e -> entries.put(JSONObject().put("s", e.seriesId).put("n", JSONArray().put(e.mark.season).put(e.mark.episode)) - .put("i", e.media.item.id).put("c", e.media.sourceId).put("t", e.media.item.title).put("d", e.media.durationMs).put("a", e.startMs).also { row -> if (e.media.item.type == "Movie") row.put("k", "Movie"); if (e.why.isNotEmpty()) row.put("w", e.why); if (e.presentation.isNotEmpty()) row.put("p", e.presentation); if (e.group.isNotEmpty()) row.put("g", e.group); if (e.bookedStartMs != e.startMs) row.put("b", e.bookedStartMs); e.fileMs?.let { row.put("f", it) } }) } + .put("i", e.media.item.id).put("c", e.media.sourceId).put("t", e.media.item.title).put("d", e.media.durationMs).put("a", e.startMs).also { row -> if (e.media.item.type == "Movie") row.put("k", "Movie"); if (e.why.isNotEmpty()) row.put("w", e.why); if (e.presentation.isNotEmpty()) row.put("p", e.presentation); if (e.group.isNotEmpty()) row.put("g", e.group); if (e.bookedStartMs != e.startMs) row.put("b", e.bookedStartMs); e.fileMs?.let { row.put("f", it) }; if (e.media.item.ref.isNotEmpty()) row.put("r", e.media.item.ref); e.media.item.year?.let { row.put("y", it) } }) } write(file("schedule", number), root(userId, number).put("tail", encodeCursor(plan.tail)).put("entries", entries)) } /** Changes whenever the plan file is written, so a plan already read can be reused until then. */ @@ -139,7 +140,9 @@ internal class ScheduleStore(private val directory: File) { val o = rows.getJSONObject(index) val duration = validDuration(o.getLong("d")) val mark = o.getJSONArray("n").let { EpisodeMark(it.getInt(0), it.getInt(1)) } - val item = SampleItem(o.getString("t"), o.optString("k", "Episode").also { require(it in listOf("Episode", "Movie")) }, duration / 60_000, "", validId(o.getString("i")), duration) + // Which film or series it is, for finding it again after a rescan: absent before RC3-14, and anything unexpected is ignored. + val item = SampleItem(o.getString("t"), o.optString("k", "Episode").also { require(it in listOf("Episode", "Movie")) }, duration / 60_000, "", validId(o.getString("i")), duration, + o.optString("r").takeIf { REF.matches(it) }.orEmpty(), o.optInt("y", 0).takeIf { it in 1800..2200 }) ScheduleEntry(validId(o.getString("s")), mark, ScheduledMedia(item, validId(o.getString("c")), duration), o.getLong("a"), o.optString("w").take(MAX_REASON_CHARS), // Absent in plans booked before presentations were kept; anything unexpected is ignored rather than refused. o.optString("p").takeIf { PRESENTATION_KEY.matches(it) }.orEmpty(), @@ -164,7 +167,7 @@ internal class ScheduleStore(private val directory: File) { pool.series.forEach { show -> val episodes = JSONArray() show.episodes.forEach { e -> episodes.put(JSONArray().put(e.id).put(e.sourceId).put(e.mark.season).put(e.mark.episode).put(e.title).put(e.durationMs)) } - series.put(JSONObject().put("id", show.id).put("title", show.title).put("episodes", episodes).put("group", show.group)) + series.put(JSONObject().put("id", show.id).put("title", show.title).put("episodes", episodes).put("group", show.group).put("ref", show.ref).apply { show.year?.let { put("year", it) } }) } write(file("episodes", number), root(userId, number).put("fetched", pool.fetchedAtMs).put("signature", pool.signature).put("series", series)) } @@ -176,7 +179,7 @@ internal class ScheduleStore(private val directory: File) { PoolSeries(validId(show.getString("id")), show.getString("title"), (0 until episodes.length()).map { row -> val e = episodes.getJSONArray(row) PoolEpisode(validId(e.getString(0)), validId(e.getString(1)), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), validDuration(e.getLong(5))) - }.also { require(it.isNotEmpty()) }, show.optString("group")) + }.also { require(it.isNotEmpty()) }, show.optString("group"), show.optString("ref").takeIf { REF.matches(it) }.orEmpty(), show.optInt("year", 0).takeIf { it in 1800..2200 }) }, root.getLong("fetched"), root.optString("signature")) } diff --git a/android/app/src/main/java/tv/orbit/classic/SeriesDiscovery.kt b/android/app/src/main/java/tv/orbit/classic/SeriesDiscovery.kt index d445f2b7..2817a50b 100644 --- a/android/app/src/main/java/tv/orbit/classic/SeriesDiscovery.kt +++ b/android/app/src/main/java/tv/orbit/classic/SeriesDiscovery.kt @@ -3,7 +3,7 @@ package tv.orbit.classic import org.json.JSONObject import java.net.URLEncoder -internal data class SeriesCandidate(val id: String, val title: String, val year: Int?, val rating: String, val variantLabel: String = "") +internal data class SeriesCandidate(val id: String, val title: String, val year: Int?, val rating: String, val variantLabel: String = "", val ref: String = "") internal data class SeriesMatches(val requested: String, val candidates: List, val moreAvailable: Boolean) internal val ToonamiSearches = listOf("Dragon Ball Z", "Batman Beyond", "Superman", "Powerpuff Girls", "ThunderCats", "Dragon Ball", "Sailor Moon", "Voltron", "ReBoot", "Beast Wars", @@ -23,7 +23,7 @@ internal fun discoverToonamiSeries(transport: EmbyTransport, userId: String, tok internal fun searchSeries(transport: EmbyTransport, userId: String, token: () -> String, requested: String): SeriesMatches { val term = URLEncoder.encode(requested, "UTF-8") - val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Recursive=true&IncludeItemTypes=Series&SearchTerm=$term&StartIndex=0&Limit=10&SortBy=SortName&SortOrder=Ascending&EnableImages=false&EnableUserData=false", token = token())) + val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Recursive=true&IncludeItemTypes=Series&SearchTerm=$term&StartIndex=0&Limit=10&SortBy=SortName&SortOrder=Ascending&Fields=ProviderIds,ProductionYear&EnableImages=false&EnableUserData=false", token = token())) EmbyClient.expectSuccess(reply.status, false) val body = EmbyClient.parse(reply.body) val items = body.optJSONArray("Items") ?: throw EmbyCheckException("The provider did not return series search results.") @@ -33,7 +33,7 @@ internal fun searchSeries(transport: EmbyTransport, userId: String, token: () -> val title = EmbyClient.clean(item.optString("Name"), 160) if (item.optString("Type") != "Series" || !EmbyClient.validId(id) || title.isBlank()) return@mapNotNull null SeriesCandidate(id, title, item.optInt("ProductionYear").takeIf { it in 1800..2200 }, - EmbyClient.clean(item.optString("OfficialRating"), 40)) + EmbyClient.clean(item.optString("OfficialRating"), 40), ref = providerRef(item, SERIES_REF_ORDER)) }.distinctBy { it.id } return SeriesMatches(requested, labelSeriesVariants(candidates), body.optLong("TotalRecordCount", items.length().toLong()) > 10) } diff --git a/android/app/src/test/java/tv/orbit/classic/RefiledTest.kt b/android/app/src/test/java/tv/orbit/classic/RefiledTest.kt index 46b14889..891a5da8 100644 --- a/android/app/src/test/java/tv/orbit/classic/RefiledTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/RefiledTest.kt @@ -179,3 +179,71 @@ class RefiledPlaysTest { assertNull(shownPlan(plan("new1"), "old1", 1_000L, booked, "This programme isn't available right now.")) } } + +/** + * 17 November 2026, built in for any server that renumbers: a booked programme keeps which film or series it is (its + * provider ID and year), so it's found again after a rescan even when its name is shared or has changed. + */ +class RenumberingTest { + @org.junit.Before fun server() { EmbyServer.origin = "https://emby.example.com" } + @org.junit.After fun noServer() { EmbyServer.origin = "" } + private fun source(id: String, minutes: Long = 91) = JSONArray().put(JSONObject().put("Id", id).put("Container", "mkv").put("RunTimeTicks", minutes * 60_000L * 10_000)) + private fun film(id: String, name: String, year: Int, imdb: String) = JSONObject().put("Id", id).put("Name", name).put("Type", "Movie").put("ProductionYear", year) + .put("ProviderIds", JSONObject().put("Imdb", imdb)).put("MediaSources", source("src$id")) + private fun session(transport: EmbyTransport, item: SampleItem) = EmbySampleSession(transport, "fixture-token-private", "fixture-user", EmbySample(listOf(item), 1)) + + @Test fun aFilmIsFoundByItsProviderIdEvenRenamed() { + val asked = mutableListOf() + val transport = EmbyTransport { r -> + asked += r.path + if ("AnyProviderIdEquals=imdb.tt0077651" in r.path) EmbyReply(200, JSONObject().put("Items", JSONArray().put(film("new1978", "John Carpenter's Halloween", 1978, "tt0077651"))).toString()) + else EmbyReply(404, "") + } + val booked = SampleItem("Halloween", "Movie", 91, "", "old1978", 91 * 60_000L, "imdb.tt0077651", 1978) + val found = session(transport, booked).refiledFilm(booked)!! + assertEquals("new1978", found.item.id) + assertEquals("imdb.tt0077651", found.item.ref) + assertEquals(1978, found.item.year) + assertEquals(1, asked.size) + } + + @Test fun withoutAnIdTheYearSettlesASharedName() { + val transport = EmbyTransport { r -> + if ("SearchTerm=Halloween" in r.path) EmbyReply(200, JSONObject().put("TotalRecordCount", 3).put("Items", JSONArray() + .put(film("h2018", "Halloween", 2018, "tt1502407")).put(film("h1978", "Halloween", 1978, "tt0077651")).put(film("h2007", "Halloween", 2007, "tt0373883"))).toString()) + else EmbyReply(404, "") + } + val booked = SampleItem("Halloween", "Movie", 91, "", "old", 91 * 60_000L, year = 2007) + assertEquals("h2007", session(transport, booked).refiledFilm(booked)!!.item.id) + } + + @Test fun aSeriesIsFoundByItsProviderIdEvenRenamed() { + val transport = EmbyTransport { r -> + when { + "AnyProviderIdEquals=tvdb.81189" in r.path -> EmbyReply(200, JSONObject().put("Items", JSONArray().put(JSONObject().put("Id", "show9").put("Type", "Series").put("Name", "Breaking Bad (2008)"))).toString()) + r.path.startsWith("/Shows/show9/Episodes") -> EmbyReply(200, JSONObject().put("Items", JSONArray().put(JSONObject().put("Id", "newep").put("Type", "Episode").put("Name", "Pilot") + .put("ParentIndexNumber", 1).put("IndexNumber", 1).put("MediaSources", source("srcnewep", 58)))).toString()) + else -> EmbyReply(404, "") + } + } + val booked = SampleItem("Breaking Bad / S1 E1 / Pilot", "Episode", 58, "", "oldep", 58 * 60_000L, "tvdb.81189", 2008) + val found = session(transport, booked).refiledEpisode(booked)!! + assertEquals("newep", found.item.id) + assertEquals("tvdb.81189", found.item.ref) + } + + @Test fun theIdAndYearAreKeptWithTheSchedule() { + val folder = kotlin.io.path.createTempDirectory("renumbering").toFile() + val pool = listOf(PoolSeries("f1", "Halloween", listOf(PoolEpisode("f1", "s1", EpisodeMark(1, 1), "Halloween", 91 * 60_000L)), ref = "imdb.tt0077651", year = 1978), + PoolSeries("f2", "The Fog", listOf(PoolEpisode("f2", "s2", EpisodeMark(1, 1), "The Fog", 89 * 60_000L)), year = 1980)) + assertEquals("imdb.tt0077651", bookedItem(pool[0], pool[0].episodes[0]).ref) + val entry = ScheduleEntry("f1", EpisodeMark(1, 1), ScheduledMedia(bookedItem(pool[0], pool[0].episodes[0]), "s1", 91 * 60_000L), 0L) + val other = ScheduleEntry("f2", EpisodeMark(1, 1), ScheduledMedia(bookedItem(pool[1], pool[1].episodes[0]), "s2", 89 * 60_000L), 91 * 60_000L) + ScheduleStore(folder).savePlan("user", 305, ChannelPlan(listOf(entry, other), ScheduleCursor())) + val back = ScheduleStore(folder).loadPlan("user", 305)!!.entries + assertEquals("imdb.tt0077651", back[0].media.item.ref); assertEquals(1978, back[0].media.item.year) + assertEquals("", back[1].media.item.ref); assertEquals(1980, back[1].media.item.year) + assertEquals("tvdb.81189", providerRef(JSONObject().put("ProviderIds", JSONObject().put("Imdb", "tt0903747").put("Tvdb", "81189")), SERIES_REF_ORDER)) + assertEquals("", providerRef(JSONObject().put("ProviderIds", JSONObject().put("Imdb", "bad id&x=1")), FILM_REF_ORDER)) + } +}