diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 28b3c6f0..6e7dd2d7 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 = 64 +val ORBIT_BUILD = 65 android { namespace = "tv.orbit.classic" compileSdk = 36 diff --git a/android/app/src/household/java/tv/orbit/classic/InstallSnapshot.kt b/android/app/src/household/java/tv/orbit/classic/InstallSnapshot.kt index 8e6697f8..169e60df 100644 --- a/android/app/src/household/java/tv/orbit/classic/InstallSnapshot.kt +++ b/android/app/src/household/java/tv/orbit/classic/InstallSnapshot.kt @@ -42,6 +42,16 @@ class InstallSnapshotReceiver : BroadcastReceiver() { tv.orbit.classic.arcade.hive.HiveLegacy.adoptCopy(File(context.filesDir, "arcade"), incoming, intent.getStringExtra("sha256"), intent.getStringExtra("confirm"), intent.getStringExtra("from"), System.currentTimeMillis()) } finally { incoming.delete() } + } else if (intent.getStringExtra("do").orEmpty().startsWith("move-")) { + // Reading two catalogues takes a few seconds: off the main thread, answered when done. + val pending = goAsync() + Thread { + val answer = runCatching { InstallSnapshot.move(context, intent.getStringExtra("do")!!, intent.getStringExtra("signature"), intent.getStringExtra("receipt"), intent.getStringExtra("refresh")) } + .getOrElse { "failed: ${it.javaClass.simpleName}: ${it.message?.take(120)}" } + android.util.Log.i("OrbitInstall", "${intent.getStringExtra("do")}: $answer") + pending.resultData = answer; pending.finish() + }.start() + return } else InstallSnapshot.handle(context, intent.getStringExtra("do").orEmpty(), intent.getStringExtra("version")) } resultData = result.fold({ it }, { "failed" }) @@ -105,6 +115,40 @@ internal object InstallSnapshot { } } + /** + * The server move ([ServerMove], 18 November 2026), from adb until it has its own screen: the original server's + * programming onto the server in use. `move-preview` writes the plan to install-snapshot/move-preview.json and changes + * nothing; `move-apply` needs the preview's signature and Orbit's screen closed; `move-rollback` puts back the files of + * the named receipt. Neither server is contacted. + */ + fun move(context: Context, action: String, signature: String?, receipt: String?, refresh: String?): String { + val data = context.filesDir.parentFile ?: return "no data" + val target = Workspaces.current(context) + if (target.original) return "refused: the server in use is the original one" + val from = File(data, "no_backup/schedule"); val to = target.scheduleDir + if (action != "move-preview" && OrbitScreen.open) return "refused: Orbit is open; force-stop it first" + if (action == "move-rollback") { + val folder = File(target.root, receipt ?: return "refused: no receipt").takeIf { Regex("server-move-\\d+").matches(it.name) && it.isDirectory } ?: return "refused: no such receipt" + return "rolled back ${ServerMove.rollback(to, folder)} files" + } + val fromUser = ServerMove.userOf(from) ?: return "refused: no saved schedules from the original server" + val toUser = ServerMove.userOf(to) ?: return "refused: no saved schedules on the server in use" + val channels = refresh.orEmpty().split(',').mapNotNull { it.trim().toIntOrNull() }.toSet() + val (ids, titles) = ServerMove.namedIn(from) + val (oldCat, newCat) = MemoryMoveCatalogue.forMove(File(data, "no_backup/catalogue.db"), target.catalogueFile, ids, titles) + val move = ServerMove(from, fromUser, to, toUser, oldCat, newCat, channels) + return when (action) { + "move-preview" -> { + val plan = move.preview() + val out = File(context.getExternalFilesDir(null), "install-snapshot").apply { mkdirs() } + File(out, "move-preview.json").writeText(plan.toJson().toString(1)) + "preview ${plan.signature} adds=${plan.adds} missing=${plan.missing.size} ambiguous=${plan.ambiguous.size} yours=${plan.yours.size}" + } + "move-apply" -> "applied ${move.apply(signature ?: return "refused: no signature").name}" + else -> "unknown" + } + } + /** The other servers' workspaces (see Workspaces): no_backup/servers/. */ private fun serverFolders(data: File): List = File(data, "no_backup/servers").listFiles { f -> f.isDirectory && Regex("[A-Za-z0-9_-]{1,64}").matches(f.name) }.orEmpty().sortedBy { it.name } diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt index 58471bf9..b9a0c13b 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -368,7 +368,15 @@ internal class ChannelScheduler(private val store: ScheduleStore, // A refresh that had to keep a few previous copies is tried again in a few hours rather than a week. val fetched = if (read.carried > 0) now - POOL_REFRESH_MS + PARTIAL_POOL_RETRY_MS else now if (read.carried > 0) Log.w("OrbitSchedule", "channel=$number poolRefreshPartial carried=${read.carried}") - pool = ScheduleStore.SavedPool(read.series, fetched, signature) + // Approvals found again under a new ID keep it, so the next read asks for them directly (18 November 2026). + val signed = if (read.refound.isEmpty()) signature else { + val now2 = store.loadChoices(userId, number) + val moved = ChannelChoices(now2.accepted.map { s -> read.refound[s.id]?.let { id -> s.copy(id = id, sourceId = null, durationMs = null) } ?: s }.distinctBy { it.id }, now2.rejected) + store.saveChoices(userId, number, moved) + Log.i("OrbitSchedule", "channel=$number approvalsRefound=${read.refound.size}") + "${programming.signature}#${moved.tag}" + } + pool = ScheduleStore.SavedPool(read.series, fetched, signed) store.savePool(userId, number, pool) // Stage C, report only: episodes a show here didn't have at the previous read. Never touches the plan. if (cached != null) runCatching { diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelSuggestions.kt b/android/app/src/main/java/tv/orbit/classic/ChannelSuggestions.kt index e24a2067..6a1398e2 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelSuggestions.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelSuggestions.kt @@ -20,7 +20,12 @@ internal data class SuggestionRule(val group: String, val label: String, val typ val excludeGenres: Set = emptySet(), val minMinutes: Int = 0, val maxRating: Float = 10f, val titleContains: String? = null) internal data class Suggestion(val id: String, val title: String, val year: Int?, val type: String, val group: String, val reason: String, - val sourceId: String? = null, val durationMs: Long? = null) + val sourceId: String? = null, val durationMs: Long? = null, + /** + * Its IMDb, TMDB or TVDB ID as "imdb.tt0100814" (18 November 2026), so an approval survives the server renumbering its + * items or a move to another server: a pool read that finds the ID gone looks the title up again by this. + */ + val ref: String = "") internal class ChannelChoices(val accepted: List = emptyList(), val rejected: Set = emptySet()) { /** Part of the cache signature, so choosing different titles reads them in. */ 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 972607e1..78c3a669 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt @@ -372,7 +372,9 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v internal class PoolRead(val series: List, val requests: Int, /** Shows whose read failed this time and kept their copy from the previous pool instead. */ - val carried: Int = 0) + val carried: Int = 0, + /** Approvals whose item had gone and was found again by its provider ID: old ID to new, for the choices to follow. */ + val refound: Map = emptyMap()) /** The first shows in the channel's list that have episodes to schedule. */ fun readChannelPool(programming: ChannelProgramming, loop: SampleChannel?, choices: ChannelChoices = ChannelChoices(), checkActive: () -> Unit = {}, /** The pool being refreshed, so one show whose read fails can keep its copy rather than losing the whole refresh. */ @@ -462,37 +464,64 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v // One slow or failing series among many chosen (Sakura's 200, 7 November 2026) is skipped this time rather than failing // the whole read; it's tried again at the next refresh. A provider that keeps failing still stops the read. var skipped = 0 - for (accepted in choices.accepted) { + val refound = HashMap() + for (accepted0 in choices.accepted) { checkActive() - if (pool.any { it.id == accepted.id || seriesKey(it.title) == seriesKey(accepted.title) }) continue + if (pool.any { it.id == accepted0.id || seriesKey(it.title) == seriesKey(accepted0.title) }) continue + var accepted = accepted0 if (accepted.type == "Movie") { // 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 } + // A placeholder from a server move has no item to ask for: it goes straight to its provider ID. + var found = if (accepted.sourceId != null && accepted.durationMs != null) accepted.sourceId!! to accepted.durationMs!! + else if (accepted.id.startsWith(MOVED_PREFIX)) null + else { requests++; playableFilm(accepted.id, programming.englishAudio, accepted.title) } + // Gone (renumbered, or moved from another server): found again by its provider ID, one request (18 November 2026). + if (found == null && accepted.ref.isNotEmpty()) { + requests++ + val row = runCatching { byProvider("Movie", accepted.ref, "&Fields=MediaSources") }.getOrDefault(emptyList()).firstOrNull() + found = row?.let { playableSource(it, BoxDecoders::canDecode, programming.englishAudio) } + if (found != null) { refound[accepted.id] = row!!.optString("Id"); accepted = accepted.copy(id = row.optString("Id"), sourceId = null, durationMs = null) } + } + val (source, duration) = found ?: continue 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) } + fun read(id: String) = readWholeSeries(transport, userId, ::currentToken, SeriesCandidate(id, accepted.title, accepted.year, ""), checkActive, onRequest = { requests++ }, canDecode = BoxDecoders::canDecode, englishAudio = programming.englishAudio) + // A series whose item has gone (renumbered, or moved from another server) is found again by its provider ID, + // one request, only when reading it by its saved ID fails or finds nothing (18 November 2026). + fun refind(): PoolSeries? { + if (accepted.ref.isEmpty()) return null + requests++ + val id = runCatching { byProvider("Series", accepted.ref) }.getOrDefault(emptyList()).firstOrNull()?.optString("Id")?.takeIf { it != accepted.id } ?: return null + return runCatching { read(id) }.getOrNull()?.takeIf { it.episodes.isNotEmpty() }?.also { refound[accepted.id] = id; accepted = accepted.copy(id = id) } + } + val whole = try { (if (accepted.id.startsWith(MOVED_PREFIX)) null else read(accepted.id).takeIf { it.episodes.isNotEmpty() && sameFilmName(it.title, accepted.title) }) ?: refind() ?: continue } catch (failure: Exception) { // Signed out, cancelled, or too many: stop. Anything else about one series: skip it this time. val status = (failure as? EmbyCheckException)?.httpStatus - if (failure is kotlinx.coroutines.CancellationException || failure is InterruptedException || status == 401 || status == 403 || - ++skipped > maxOf(MAX_FAILED_READS, choices.accepted.size / 10)) throw failure - android.util.Log.w("OrbitSchedule", "channel=${programming.number} chosen read skipped=$skipped failed=${failure.javaClass.simpleName} status=$status") - continue + if (failure is kotlinx.coroutines.CancellationException || failure is InterruptedException || status == 401 || status == 403) throw failure + refind() ?: run { + if (++skipped > maxOf(MAX_FAILED_READS, choices.accepted.size / 10)) throw failure + android.util.Log.w("OrbitSchedule", "channel=${programming.number} chosen read skipped=$skipped failed=${failure.javaClass.simpleName} status=$status") + null + } ?: continue } if (whole.episodes.isNotEmpty()) pool += whole.copy(group = accepted.group) } } // An editorial withdrawal takes that exact item out, however it arrived: list, old line-up or accepted suggestion. - return PoolRead(withoutWithdrawn(pool, programming.withdrawn), requests, partial.carried) + return PoolRead(withoutWithdrawn(pool, programming.withdrawn), requests, partial.carried, refound) } + /** One film's first copy this box can play, as (source id, runtime), by its exact library item; null if it has none. */ - private fun playableFilm(id: String, englishAudio: Boolean): Pair? { + private fun playableFilm(id: String, englishAudio: Boolean, title: String? = null): Pair? { if (!EmbyClient.validId(id)) return null val reply = runCatching { transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Ids=$id&Fields=MediaSources&EnableImages=false&EnableUserData=false", token = currentToken(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS)) }.getOrNull() ?: return null if (reply.status !in 200..299) return null val row = EmbyClient.parse(reply.body).optJSONArray("Items")?.optJSONObject(0)?.takeIf { it.optString("Id") == id && it.optString("Type") == "Movie" } ?: return null + // A renumbered server can give an old number to another film (18 November 2026): one whose name shares nothing with + // the approval's isn't it, and the approval is then looked up by its provider ID instead. + if (title != null && !sameFilmName(row.optString("Name"), title)) return null return playableSource(row, BoxDecoders::canDecode, englishAudio) } fun suggestFor(rules: List, alreadyInPool: Set, rejected: Set, takenTitles: Set = emptySet(), checkActive: () -> Unit = {}) = @@ -550,6 +579,12 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v } /** Items of [type] carrying provider ID [ref], at most ten; one small request. */ + /** Two names for one title: equal once case, punctuation and a year are set aside, or one contains the other. */ + private fun sameFilmName(a: String, b: String): Boolean { + val x = moveTitleKey(a); val y = moveTitleKey(b) + return x.isNotEmpty() && y.isNotEmpty() && (x == y || x.contains(y) || y.contains(x)) + } + 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())) 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 408c798e..fe3da074 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -246,7 +246,7 @@ internal class ScheduleStore(private val directory: File) { fun saveChoices(userId: String, number: Int, choices: ChannelChoices) { val accepted = JSONArray() choices.accepted.forEach { s -> accepted.put(JSONObject().put("i", s.id).put("t", s.title).put("y", s.year ?: JSONObject.NULL).put("k", s.type).put("g", s.group) - .put("r", s.reason).put("c", s.sourceId ?: JSONObject.NULL).put("d", s.durationMs ?: JSONObject.NULL)) } + .put("r", s.reason).put("c", s.sourceId ?: JSONObject.NULL).put("d", s.durationMs ?: JSONObject.NULL).apply { if (s.ref.isNotEmpty()) put("p", s.ref) }) } write(file("choices", number), root(userId, number).put("accepted", accepted).put("rejected", JSONArray(choices.rejected.toList()))) } fun loadChoices(userId: String, number: Int): ChannelChoices = read(file("choices", number), userId, number) { root -> @@ -255,7 +255,8 @@ internal class ScheduleStore(private val directory: File) { ChannelChoices((0 until rows.length()).map { index -> val o = rows.getJSONObject(index) Suggestion(validId(o.getString("i")), o.getString("t"), if (o.isNull("y")) null else o.getInt("y"), o.getString("k").also { require(it in listOf("Movie", "Series")) }, o.getString("g"), - o.getString("r"), if (o.isNull("c")) null else validId(o.getString("c")), if (o.isNull("d")) null else validDuration(o.getLong("d"))) + o.getString("r"), if (o.isNull("c")) null else validId(o.getString("c")), if (o.isNull("d")) null else validDuration(o.getLong("d")), + o.optString("p").takeIf { REF.matches(it) }.orEmpty()) }, (0 until rejected.length()).map { validId(rejected.getString(it)) }.toSet()) } ?: ChannelChoices() diff --git a/android/app/src/main/java/tv/orbit/classic/ServerMove.kt b/android/app/src/main/java/tv/orbit/classic/ServerMove.kt new file mode 100644 index 00000000..0c24007e --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/ServerMove.kt @@ -0,0 +1,373 @@ +package tv.orbit.classic + +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.security.MessageDigest + +/* + * Moving your programming to another server (Paul, 18 November 2026, after the move to the VPS left every approval behind). + * + * What you decided on one server comes with you to the next: approved titles and the block each was approved for, rejected + * suggestions, your own channels, Director's Chair decisions and dismissals, its learning switch, and what each profile has + * watched. Each title is matched by its IMDb, TMDB or TVDB ID through the two servers' catalogues already on the TV, then by + * title and year; nothing is guessed. A title with no match, or with more than one possible match, is listed for you. + * + * It never contacts either server, and never changes a plan, a booking, a ticket, a reminder or anything already on the new + * server: it only adds. Preview first; apply does exactly what the preview showed (its signature must match); every file it + * touches is copied aside first, so rollback puts each one back as it was. Pools that came up short are marked for an early + * re-read, which the usual paced background reads do within the household's request budget. + */ + +internal class MoveItem(val id: String, val type: String, val title: String, val year: Int?, val refs: Map) + +/** A library as the move sees it: titles by ID, by provider ID and by title. */ +internal interface MoveCatalogue { + fun item(id: String): MoveItem? + fun byRef(type: String, source: String, value: String): List + fun byTitle(type: String, key: String): List +} + +internal class MemoryMoveCatalogue(items: Sequence) : MoveCatalogue { + private val ids = HashMap() + private val refs = HashMap>() + private val titles = HashMap>() + init { + items.forEach { i -> + ids[i.id] = i + i.refs.forEach { (s, v) -> refs.getOrPut("${i.type}|$s|${v.lowercase()}") { ArrayList(1) }.add(i) } + titles.getOrPut("${i.type}|${moveTitleKey(i.title)}") { ArrayList(1) }.add(i) + } + } + val size get() = ids.size + override fun item(id: String) = ids[id] + override fun byRef(type: String, source: String, value: String) = refs["$type|$source|${value.lowercase()}"].orEmpty() + override fun byTitle(type: String, key: String) = titles["$type|$key"].orEmpty() + + companion object { + /** + * Read straight from a catalogue file, read-only, without opening it as Orbit's own store. Only the rows [keep] + * wants are held, so a library of any size is one pass and a small map. + */ + fun of(file: File, keep: (MoveItem) -> Boolean = { true }): MemoryMoveCatalogue { + val db = android.database.sqlite.SQLiteDatabase.openDatabase(file.path, null, android.database.sqlite.SQLiteDatabase.OPEN_READONLY) + try { + val rows = ArrayList() + db.rawQuery("SELECT id, type, title, year, provider_ids FROM items", null).use { c -> + while (c.moveToNext()) { + val item = MoveItem(c.getString(0), c.getString(1), c.getString(2).trim(), if (c.isNull(3)) null else c.getInt(3), providerRefs(c.getString(4))) + if (keep(item)) rows += item + } + } + return MemoryMoveCatalogue(rows.asSequence()) + } finally { db.close() } + } + + /** The two catalogues a move needs: the old one's rows for [ids], the new one's rows that could match them. */ + fun forMove(oldFile: File, newFile: File, ids: Set, titles: Set): Pair { + val old = of(oldFile) { it.id in ids } + val refs = HashSet(); val keys = HashSet(titles.map(::moveTitleKey)) + ids.forEach { id -> old.item(id)?.let { i -> i.refs.forEach { (s, v) -> refs += "$s|${v.lowercase()}" }; keys += moveTitleKey(i.title) } } + val new = of(newFile) { i -> moveTitleKey(i.title) in keys || i.refs.any { (s, v) -> "$s|${v.lowercase()}" in refs } } + return old to new + } + } +} + +/** The IMDb, TMDB and TVDB IDs from a catalogue row's provider IDs. */ +internal fun providerRefs(json: String?): Map = runCatching { + val o = JSONObject(json ?: "{}") + o.keys().asSequence().map { it to o.optString(it) }.filter { (k, v) -> k.lowercase() in MOVE_SOURCES && v.isNotBlank() && v.length <= 40 } + .associate { (k, v) -> k.lowercase() to v.trim() } +}.getOrDefault(emptyMap()) + +internal val MOVE_SOURCES = listOf("imdb", "tmdb", "tvdb") + +/** An approval carried from another server waits under this placeholder until a pool read finds it by its provider ID. */ +internal const val MOVED_PREFIX = "moved-" + +/** A title as a key: case, punctuation, "and"/"&", a leading article and a trailing year don't count. */ +internal fun moveTitleKey(title: String): String = title.lowercase().trim().replace("&", " and ") + .replace(Regex("\\s*\\((19|20)\\d\\d\\)\\s*$"), "").replace(Regex("^(the|a|an)\\s+"), "").replace(Regex("[^a-z0-9]"), "") + +internal enum class MoveHow(val label: String) { + Provider("matched by IMDb, TMDB or TVDB"), TitleYear("matched by title and year"), Title("matched by title"), + Ambiguous("more than one possible match"), Missing("not in the new library") +} + +internal class MoveMatch(val oldId: String, val title: String, val type: String, val year: Int?, val newId: String?, val how: MoveHow, + /** For an ambiguous match, the titles it could be. */ + val candidates: List = emptyList()) { + val matched get() = newId != null + fun toJson(): JSONObject = JSONObject().put("old", oldId).put("t", title).put("k", type).put("y", year ?: JSONObject.NULL).put("new", newId ?: JSONObject.NULL) + .put("how", how.name).put("cands", JSONArray(candidates)) +} + +/** + * Matches titles from one library to another. A title's copies (the same work twice) are one match; two different works + * that could both be it are ambiguous and left for you. [preferred] are IDs already in use on the new server, chosen first + * among a work's copies so the move agrees with what's already playing. + */ +internal class MoveMatcher(private val old: MoveCatalogue, private val new: MoveCatalogue, private val preferred: Set = emptySet()) { + private val cache = HashMap() + + private fun work(i: MoveItem) = MOVE_SOURCES.firstNotNullOfOrNull { s -> i.refs[s]?.let { "$s:${it.lowercase()}" } } ?: "t:${moveTitleKey(i.title)}:${i.year}" + private fun pick(copies: List) = copies.firstOrNull { it.id in preferred } + ?: copies.minWithOrNull(compareBy({ it.id.length }, { it.id }))!! + + fun match(oldId: String, title: String, type: String, year: Int?): MoveMatch = cache.getOrPut("$type|$oldId") { + val was = old.item(oldId)?.takeIf { it.type == type } ?: MoveItem(oldId, type, title, year, emptyMap()) + val name = was.title.ifBlank { title } + val y = was.year ?: year + // By provider ID: every source the old title has, all of them agreeing on one work. + val byRef = MOVE_SOURCES.flatMap { s -> was.refs[s]?.let { new.byRef(type, s, it) }.orEmpty() }.distinctBy { it.id } + if (byRef.isNotEmpty()) { + // Each candidate shares an ID with the old title; one that contradicts another of its IDs is a different work. + val agreed = byRef.filter { c -> MOVE_SOURCES.none { s -> was.refs[s] != null && c.refs[s] != null && !c.refs[s].equals(was.refs[s], true) } } + return@getOrPut if (agreed.isNotEmpty()) MoveMatch(oldId, name, type, y, pick(agreed).id, MoveHow.Provider) + else MoveMatch(oldId, name, type, y, null, MoveHow.Ambiguous, byRef.map { "${it.title} (${it.year ?: "?"})" }.distinct().take(5)) + } + // By title: never a title whose own IDs say it's a different work (a remake), and the year must agree when both have one. + val sameName = new.byTitle(type, moveTitleKey(name)).filter { c -> MOVE_SOURCES.none { s -> was.refs[s] != null && c.refs[s] != null && !c.refs[s].equals(was.refs[s], true) } } + val fits = if (y != null) sameName.filter { it.year == null || it.year == y } else sameName + val works = fits.groupBy(::work) + when { + works.size == 1 -> MoveMatch(oldId, name, type, y, pick(fits).id, if (y != null && fits.any { it.year == y }) MoveHow.TitleYear else MoveHow.Title) + works.size > 1 -> MoveMatch(oldId, name, type, y, null, MoveHow.Ambiguous, fits.map { "${it.title} (${it.year ?: "?"})" }.distinct().take(5)) + sameName.isNotEmpty() -> MoveMatch(oldId, name, type, y, null, MoveHow.Ambiguous, sameName.map { "${it.title} (${it.year ?: "?"})" }.distinct().take(5)) + else -> MoveMatch(oldId, name, type, y, null, MoveHow.Missing) + } + } +} + +/** One channel's approvals and rejections, matched. */ +internal class ChannelMove(val number: Int, val name: String, val matches: List>, val alreadyThere: Int, val add: List, + val rejectedMatched: Set, val rejectedTotal: Int) + +/** One of your channels, possibly under a new number if the new server already uses its own. */ +internal class YourChannelMove(val from: Int, val channel: CustomChannel, val enabled: Boolean) + +internal class MovePlan(val channels: List, val yours: List, val decisions: List, val decisionsTotal: Int, + val taste: Map>, val tasteTotal: Int, val copyLearning: Boolean, val dismissed: Set, val refresh: List) { + val all get() = channels.flatMap { c -> c.matches.map { it.first } } + val missing get() = all.filter { it.how == MoveHow.Missing }.distinctBy { it.oldId } + val ambiguous get() = all.filter { it.how == MoveHow.Ambiguous }.distinctBy { it.oldId } + val adds get() = channels.sumOf { it.add.size } + /** Titles the TV's copy of the new library didn't have, carried with their provider ID to be looked up. */ + val lookups get() = channels.flatMap { c -> c.matches.filter { (m, _) -> m.how == MoveHow.Missing && c.add.any { it.id == MOVED_PREFIX + m.oldId } }.map { it.first } } + /** Titles with no provider ID that nothing in the new library matched: only listed. */ + val unrecoverable get() = missing.filter { m -> lookups.none { it.oldId == m.oldId } } + + /** What apply will do, as a fingerprint: apply refuses unless the preview it's given still matches. */ + val signature: String get() { + val text = channels.joinToString("\n") { c -> "${c.number}:" + c.add.joinToString(",") { "${it.id}/${it.group}" } + "|" + c.rejectedMatched.sorted().joinToString(",") } + + yours.joinToString("\n") { "y${it.from}>${it.channel.number}" } + "d${decisions.size}t${taste.values.sumOf { it.size }}l$copyLearning" + dismissed.sorted().joinToString(",") + refresh.joinToString(",") + return MessageDigest.getInstance("SHA-256").digest(text.toByteArray()).take(8).joinToString("") { "%02x".format(it) } + } + + fun toJson(): JSONObject = JSONObject().put("signature", signature).put("adds", adds).put("missing", missing.size).put("ambiguous", ambiguous.size) + .put("lookups", JSONArray(lookups.map { it.title })).put("unrecoverable", JSONArray(unrecoverable.map { it.title })) + .put("channels", JSONArray(channels.map { c -> JSONObject().put("n", c.number).put("name", c.name).put("approved", c.matches.size).put("alreadyThere", c.alreadyThere) + .put("add", c.add.size).put("missing", JSONArray(c.matches.filter { it.first.how == MoveHow.Missing }.map { it.first.title })) + .put("ambiguous", JSONArray(c.matches.filter { it.first.how == MoveHow.Ambiguous }.map { it.first.toJson() })) + .put("byHow", JSONObject(c.matches.groupingBy { it.first.how.name }.eachCount())).put("rejected", "${c.rejectedMatched.size}/${c.rejectedTotal}") })) + .put("yours", JSONArray(yours.map { JSONObject().put("from", it.from).put("to", it.channel.number).put("name", it.channel.name).put("enabled", it.enabled) })) + .put("decisions", "${decisions.size}/$decisionsTotal").put("taste", "${taste.values.sumOf { it.size }}/$tasteTotal").put("learning", copyLearning) + .put("dismissed", dismissed.size).put("refresh", JSONArray(refresh)) +} + +/** + * The move from one server's workspace ([from], its account [fromUser]) to another's. Read-only until [apply]. + * [refreshChannels] are channels whose pools came up short on the new server, re-read early by the usual paced reads. + */ +internal class ServerMove(private val from: File, private val fromUser: String, private val to: File, private val toUser: String, + private val old: MoveCatalogue, private val new: MoveCatalogue, private val refreshChannels: Set = emptySet(), private val nowMs: Long = System.currentTimeMillis()) { + private val oldStore = ScheduleStore(from) + private val newStore = ScheduleStore(to) + private val inUse = to.listFiles { f -> f.name.startsWith("choices-") || f.name.startsWith("episodes-") }.orEmpty() + .flatMap { f -> Regex("\"(?:i|id)\":\"([A-Za-z0-9_-]{1,64})\"").findAll(runCatching { f.readText() }.getOrDefault("")).map { it.groupValues[1] } }.toSet() + private val matcher = MoveMatcher(old, new, inUse) + + private fun numbers(dir: File, kind: String) = dir.listFiles { f -> f.name.matches(Regex("$kind-\\d+\\.json")) }.orEmpty() + .map { it.name.removePrefix("$kind-").removeSuffix(".json").toInt() }.sorted() + + private fun yoursIn(dir: File): List = runCatching { JSONArray(File(dir, "yours.json").readText()).let { a -> (0 until a.length()).mapNotNull { runCatching { CustomChannel.fromJson(a.getJSONObject(it)) }.getOrNull() } } }.getOrDefault(emptyList()) + + fun preview(): MovePlan { + // Your channels first: one the new server already has (same name) keeps its number; otherwise its own, or the next free one. + val there = yoursIn(to) + val taken = there.map { it.number }.toMutableSet() + val renumber = HashMap() + val yours = yoursIn(from).mapNotNull { c -> + there.firstOrNull { it.name.equals(c.name, true) }?.let { renumber[c.number] = it.number; return@mapNotNull null } + val number = if (c.number !in taken) c.number else (YOURS_FIRST..YOURS_LAST).firstOrNull { it !in taken } ?: return@mapNotNull null + taken += number; renumber[c.number] = number + YourChannelMove(c.number, c.copy(number = number, seen = emptySet()), oldStore.loadProgress(fromUser, c.number)?.enabled ?: true) + } + val names = SmartChannels.associate { it.number to it.name } + there.associate { it.number to it.name } + yours.associate { it.channel.number to it.channel.name } + val channels = numbers(from, "choices").mapNotNull { n -> + val was = oldStore.loadChoices(fromUser, n) + if (was.accepted.isEmpty() && was.rejected.isEmpty()) return@mapNotNull null + val target = renumber[n] ?: n + val now = newStore.loadChoices(toUser, target) + val have = now.accepted.map { it.id }.toSet() + val matches = was.accepted.map { s -> matcher.match(s.id, s.title, s.type, s.year) to s.group } + val haveTitles = now.accepted.map { moveTitleKey(it.title) + "|" + it.type }.toSet() + // Saved under a placeholder with its provider ID, never the catalogue's ID: the server may have renumbered since the + // catalogue was read, and an old number can belong to another title now. The first pool read looks each one up by its + // ID and keeps the server's own (one request each, paced). A title the TV's copy of the catalogue doesn't have, but + // whose ID is known, is looked up the same way rather than written off; one with neither is only listed. + val add = matches.filter { (m, _) -> (m.matched || (m.how == MoveHow.Missing && refOf(m.oldId, m.type, old).isNotEmpty())) && + m.newId !in have && m.newId !in now.rejected && moveTitleKey(m.title) + "|" + m.type !in haveTitles } + .map { (m, group) -> + val s = was.accepted.first { it.id == m.oldId } + val ref = m.newId?.let { refOf(it, s.type, new) }.orEmpty().ifEmpty { refOf(m.oldId, s.type, old) } + val reason = s.reason.ifBlank { "Approved on your previous server" }.take(200) + if (ref.isNotEmpty()) Suggestion(MOVED_PREFIX + m.oldId, s.title, s.year, s.type, group, reason, ref = ref) + else Suggestion(m.newId!!, s.title, s.year, s.type, group, reason) + }.distinctBy { it.ref.ifEmpty { it.id } } + val rejected = was.rejected.mapNotNull { id -> old.itemType(id)?.let { (title, type, year) -> matcher.match(id, title, type, year).newId } }.toSet() - have - now.rejected + ChannelMove(target, names[target] ?: "Channel $target", matches, matches.count { it.first.newId in have }, add, rejected, was.rejected.size) + }.filter { it.add.isNotEmpty() || it.rejectedMatched.isNotEmpty() || it.matches.any { m -> !m.first.matched } } + val oldDecisions = loadDecisions(oldStore.decisionsFile()) + val haveDecisions = loadDecisions(newStore.decisionsFile()).map { it.id }.toSet() + val decisions = oldDecisions.mapNotNull { d -> + val m = matcher.match(d.id, d.title, d.type, null).newId ?: return@mapNotNull null + if (m in haveDecisions) null else ChairDecision(m, d.title, d.type, d.placed, d.channel?.let { renumber[it] ?: it }, d.suggested?.let { renumber[it] ?: it }, d.atMs, d.premiere) + }.distinctBy { it.id } + val taste = moveTaste(renumber) + val dismissed = runCatching { JSONArray(File(from, "rotation-dismissed-0.json").readText()).let { a -> (0 until a.length()).map { a.getString(it) } } }.getOrDefault(emptyList()) + .mapNotNull { key -> key.split(':').takeIf { it.size == 4 }?.let { (kind, ch, group, id) -> + val n = ch.toIntOrNull() ?: return@let null + old.itemType(id)?.let { (t, k, y) -> matcher.match(id, t, k, y).newId }?.let { "$kind:${renumber[n] ?: n}:$group:$it" } } }.toSet() - loadDismissedKeys(to) + val copyLearning = oldStore.learningFile().exists() && !newStore.learningFile().exists() + val refresh = refreshChannels.filter { newStore.loadPool(toUser, it) != null }.sorted() + return MovePlan(channels, yours, decisions, oldDecisions.size, taste.first, taste.second, copyLearning, dismissed, refresh) + } + + /** The approval's provider ID, from the new library's row (or the old one's), so it can be found again if the ID moves. */ + private fun refOf(id: String, type: String, catalogue: MoveCatalogue): String { + val order = if (type == "Series") listOf("tvdb", "imdb", "tmdb") else listOf("imdb", "tmdb") + val refs = catalogue.item(id)?.refs.orEmpty() + return order.firstNotNullOfOrNull { s -> refs[s]?.takeIf { it.matches(Regex("[A-Za-z0-9_-]{1,40}")) }?.let { "$s.$it" } }.orEmpty() + } + + private fun MoveCatalogue.itemType(id: String): Triple? = item(id)?.let { Triple(it.title, it.type, it.year) } + + /** Each profile's viewing: films by their own match, episodes by their series (the episode itself can't be matched). */ + private fun moveTaste(renumber: Map): Pair>, Int> { + val oldTaste = File(from, "taste"); val newTaste = TasteStore(File(to, "taste")) + var total = 0 + val out = oldTaste.listFiles { f -> f.name.endsWith(".events.jsonl") }.orEmpty().associate { f -> + val profile = f.name.removeSuffix(".events.jsonl") + val events = TasteStore(oldTaste).events(profile); total += events.size + val have = newTaste.events(profile).map { it.id }.toSet() + profile to events.filter { it.id !in have }.mapNotNull { e -> + val series = e.seriesId?.let { s -> matcher.match(s, e.title.substringBefore(" / "), "Series", null).newId } + val item = if (e.seriesId != null && e.seriesId != e.itemId) series else matcher.match(e.itemId, e.title, "Movie", null).newId + if (item == null) null else TasteEvent(e.id, e.profile, e.kind, item, series, e.title, e.channel?.let { renumber[it] ?: it }, e.atMs, e.watchedMs, + e.source, e.runtimeMs, e.percent, null, (e.extras ?: JSONObject()).put("moved", true)) + } + }.filterValues { it.isNotEmpty() } + return out to total + } + + /** + * Does what [plan] showed, only if a fresh preview still has the same [signature]. Every file it touches is copied + * aside first, in a receipt folder beside the workspace's schedules; [rollback] puts them back. + */ + fun apply(signature: String): File { + val plan = preview() + require(plan.signature == signature) { "The move has changed since its preview; preview it again." } + val receipt = File(to.parentFile, "server-move-$nowMs").apply { mkdirs() } + val manifest = JSONArray() + fun keep(file: File) { + val rel = file.relativeTo(to).path + if ((0 until manifest.length()).any { manifest.getJSONObject(it).getString("p") == rel }) return + val existed = file.exists() + if (existed) file.copyTo(File(receipt, "files/$rel"), overwrite = true) + manifest.put(JSONObject().put("p", rel).put("existed", existed)) + writeSafely(File(receipt, "manifest.json"), JSONObject().put("at", nowMs).put("signature", signature).put("files", manifest).toString()) + } + plan.channels.forEach { c -> + if (c.add.isEmpty() && c.rejectedMatched.isEmpty()) return@forEach + keep(File(to, "choices-${c.number}.json")); keep(File(to, "choices-${c.number}.json.prev")) + val now = newStore.loadChoices(toUser, c.number) + newStore.saveChoices(toUser, c.number, ChannelChoices(now.accepted + c.add.filter { a -> now.accepted.none { it.id == a.id } }, now.rejected + c.rejectedMatched)) + } + if (plan.yours.isNotEmpty()) { + keep(File(to, "yours.json")) + val there = yoursIn(to) + val merged = (there + plan.yours.map { it.channel }.filter { y -> there.none { it.number == y.number } }).sortedBy { it.number } + writeSafely(File(to, "yours.json"), JSONArray(merged.map { it.toJson() }).toString()) + plan.yours.forEach { y -> + val progress = File(to, "progress-${y.channel.number}.json") + if (!progress.exists()) { keep(progress); newStore.saveProgress(toUser, y.channel.number, ScheduleStore.SavedProgress(y.enabled, ScheduleCursor())) } + } + } + if (plan.decisions.isNotEmpty()) { + keep(newStore.decisionsFile()) + val all = loadDecisions(newStore.decisionsFile()) + plan.decisions + writeSafely(newStore.decisionsFile(), JSONArray(all.map { it.toJson() }).toString()) + } + if (plan.copyLearning) { keep(newStore.learningFile()); oldStore.learningFile().copyTo(newStore.learningFile(), overwrite = true) } + if (plan.dismissed.isNotEmpty()) { + val file = File(to, "rotation-dismissed-0.json"); keep(file) + writeSafely(file, JSONArray((loadDismissedKeys(to) + plan.dismissed).toList()).toString()) + } + plan.taste.forEach { (profile, events) -> + val store = TasteStore(File(to, "taste")); val file = store.eventsFile(profile); keep(file) + file.parentFile?.mkdirs() + val merged = (store.events(profile) + events).distinctBy { it.id }.sortedBy { it.atMs } + writeSafely(file, merged.joinToString("") { it.toLine() + "\n" }) + } + plan.refresh.forEach { n -> + val pool = newStore.loadPool(toUser, n) ?: return@forEach + keep(File(to, "episodes-$n.json")); keep(File(to, "episodes-$n.json.prev")) + newStore.savePool(toUser, n, ScheduleStore.SavedPool(pool.series, 0L, pool.signature)) + } + writeSafely(File(receipt, "plan.json"), plan.toJson().toString(1)) + return receipt + } + + companion object { + /** Puts back every file a move touched, as it was before; files it created are removed. Nothing else changes. */ + fun rollback(to: File, receipt: File): Int { + val manifest = JSONObject(File(receipt, "manifest.json").readText()).getJSONArray("files") + var restored = 0 + for (i in 0 until manifest.length()) { + val entry = manifest.getJSONObject(i) + val rel = entry.getString("p") + require(!rel.startsWith("/") && ".." !in rel.split('/', '\\')) { "bad path in the receipt" } + val target = File(to, rel) + if (entry.getBoolean("existed")) File(receipt, "files/$rel").copyTo(target, overwrite = true) else target.delete() + restored++ + } + File(receipt, "rolled-back").writeText(System.currentTimeMillis().toString()) + return restored + } + + private fun loadDismissedKeys(dir: File): Set = + runCatching { JSONArray(File(dir, "rotation-dismissed-0.json").readText()).let { a -> (0 until a.length()).map { a.getString(it) }.toSet() } }.getOrDefault(emptySet()) + + /** Every item ID and title a workspace's programming names: what a move has to match. */ + fun namedIn(dir: File): Pair, Set> { + val ids = HashSet(); val titles = HashSet() + val files = dir.listFiles { f -> f.name.matches(Regex("choices-\\d+\\.json")) || f.name == "director-decisions-0.json" || f.name == "rotation-dismissed-0.json" }.orEmpty().toList() + + File(dir, "taste").listFiles { f -> f.name.endsWith(".events.jsonl") }.orEmpty() + val idPattern = Regex("\"(?:i|s)\":\"([A-Za-z0-9_-]{1,64})\"|\"[a-z]+:\\d+:[a-z+]*:([A-Za-z0-9_-]{1,64})\"") + val titlePattern = Regex("\"t\":\"((?:[^\"\\\\]|\\\\.){1,160})\"") + files.forEach { f -> val text = runCatching { f.readText() }.getOrDefault("") + idPattern.findAll(text).forEach { m -> ids += m.groupValues[1].ifEmpty { m.groupValues[2] } } + if (f.name.startsWith("choices-")) titlePattern.findAll(text).forEach { m -> titles += m.groupValues[1] } + // Rejected IDs are a plain list. + if (f.name.startsWith("choices-")) runCatching { JSONObject(text).optJSONArray("rejected") }.getOrNull()?.let { a -> (0 until a.length()).forEach { ids += a.getString(it) } } + } + return ids to titles + } + + /** The account a workspace's files belong to, from any of its saved files. */ + fun userOf(dir: File): String? = dir.listFiles { f -> f.name.matches(Regex("(choices|schedule|progress|episodes)-\\d+\\.json")) }.orEmpty().asSequence() + .mapNotNull { f -> runCatching { JSONObject(f.readText()).optString("user").takeIf { EmbyClient.validId(it) } }.getOrNull() }.firstOrNull() + } +} 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 891a5da8..be4df83e 100644 --- a/android/app/src/test/java/tv/orbit/classic/RefiledTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/RefiledTest.kt @@ -247,3 +247,57 @@ class RenumberingTest { assertEquals("", providerRef(JSONObject().put("ProviderIds", JSONObject().put("Imdb", "bad id&x=1")), FILM_REF_ORDER)) } } + +/** 18 November 2026: an approval whose item has gone (the server renumbered, or it came from another server) is found again. */ +class SelfHealingApprovalTest { + @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 = 90) = JSONArray().put(JSONObject().put("Id", id).put("Container", "mkv").put("RunTimeTicks", minutes * 60_000L * 10_000)) + private fun film(id: String, name: String) = JSONObject().put("Id", id).put("Name", name).put("Type", "Movie").put("MediaSources", source("src$id")) + private val channel = ChannelProgramming(305, "After Dark", emptyList(), filmRestMs = 1L) + + @Test fun aGoneFilmIsFoundByItsProviderIdOnce() { + val asked = mutableListOf() + val transport = EmbyTransport { r -> + asked += r.path + if ("AnyProviderIdEquals=imdb.tt0100814" in r.path) EmbyReply(200, JSONObject().put("Items", JSONArray().put(film("new1", "Tremors"))).toString()) + else EmbyReply(200, JSONObject().put("Items", JSONArray()).toString()) // the old ID: nothing there + } + val s = EmbySampleSession(transport, "fixture-token-private", "fixture-user", EmbySample(emptyList(), 0)) + val read = s.readChannelPool(channel, null, ChannelChoices(listOf(Suggestion("old1", "Tremors", 1990, "Movie", "day", "", ref = "imdb.tt0100814")))) + assertEquals(listOf("new1"), read.series.map { it.id }) + assertEquals("day", read.series.single().group) + assertEquals(mapOf("old1" to "new1"), read.refound) + assertEquals(1, asked.count { "AnyProviderIdEquals" in it }) + } + + @Test fun anApprovalWithoutAnIdIsLeftAsItWas() { + val transport = EmbyTransport { EmbyReply(200, JSONObject().put("Items", JSONArray()).toString()) } + val s = EmbySampleSession(transport, "fixture-token-private", "fixture-user", EmbySample(emptyList(), 0)) + val read = s.readChannelPool(channel, null, ChannelChoices(listOf(Suggestion("old1", "Tremors", 1990, "Movie", "", "")))) + assertTrue(read.series.isEmpty()); assertTrue(read.refound.isEmpty()) + } + + @Test fun aGoneSeriesIsFoundByItsProviderId() { + 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"))).toString()) + r.path.startsWith("/Shows/show9/Episodes") -> EmbyReply(200, JSONObject().put("Items", JSONArray().put(JSONObject().put("Id", "ep1").put("Type", "Episode").put("Name", "Pilot") + .put("ParentIndexNumber", 1).put("IndexNumber", 1).put("MediaSources", source("srcep1", 58)))).toString()) + else -> EmbyReply(404, "") + } + } + val s = EmbySampleSession(transport, "fixture-token-private", "fixture-user", EmbySample(emptyList(), 0)) + val read = s.readChannelPool(ChannelProgramming(702, "Sakura", emptyList()), null, ChannelChoices(listOf(Suggestion("oldshow", "Breaking Bad", 2008, "Series", "", "", ref = "tvdb.81189")))) + assertEquals(listOf("show9"), read.series.map { it.id }) + assertEquals(mapOf("oldshow" to "show9"), read.refound) + } + + @Test fun anApprovalsIdSurvivesSaving() { + val folder = kotlin.io.path.createTempDirectory("approvals").toFile() + val store = ScheduleStore(folder) + store.saveChoices("0123456789abcdef0123456789abcdef", 305, ChannelChoices(listOf(Suggestion("a1", "Tremors", 1990, "Movie", "day", "", ref = "imdb.tt0100814")))) + assertEquals("imdb.tt0100814", store.loadChoices("0123456789abcdef0123456789abcdef", 305).accepted.single().ref) + folder.deleteRecursively() + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/ServerMoveTest.kt b/android/app/src/test/java/tv/orbit/classic/ServerMoveTest.kt new file mode 100644 index 00000000..3a642325 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/ServerMoveTest.kt @@ -0,0 +1,225 @@ +package tv.orbit.classic + +import org.junit.Assert.* +import org.junit.Test +import java.io.File +import java.nio.file.Files + +/** Moving your programming to another server (Paul, 18 November 2026): fictional libraries only. */ +class ServerMoveTest { + private val oldUser = "0123456789abcdef0123456789abcdef" + private val newUser = "fedcba9876543210fedcba9876543210" + private fun film(id: String, title: String, year: Int?, vararg refs: Pair) = MoveItem(id, "Movie", title, year, refs.toMap()) + private fun show(id: String, title: String, year: Int?, vararg refs: Pair) = MoveItem(id, "Series", title, year, refs.toMap()) + + // --- Matching --- + + @Test fun aFilmWithANewIdIsFoundByItsImdbId() { + val old = MemoryMoveCatalogue(sequenceOf(film("100", "Tremors", 1990, "imdb" to "tt0100814"))) + val new = MemoryMoveCatalogue(sequenceOf(film("9001", "Tremors", 1990, "imdb" to "tt0100814"))) + val m = MoveMatcher(old, new).match("100", "Tremors", "Movie", 1990) + assertEquals("9001", m.newId); assertEquals(MoveHow.Provider, m.how) + } + + @Test fun aRenamedTitleIsStillFoundByItsId() { + val old = MemoryMoveCatalogue(sequenceOf(film("1", "Arrietty", 2010, "tmdb" to "51739"))) + val new = MemoryMoveCatalogue(sequenceOf(film("2", "The Secret World of Arrietty", 2010, "tmdb" to "51739"))) + assertEquals("2", MoveMatcher(old, new).match("1", "Arrietty", "Movie", 2010).newId) + } + + @Test fun copiesOfOneFilmAreOneMatchAndTheCopyAlreadyInUseIsChosen() { + val old = MemoryMoveCatalogue(sequenceOf(film("1", "Krull", 1983, "imdb" to "tt0085811"))) + val new = MemoryMoveCatalogue(sequenceOf(film("50", "Krull", 1983, "imdb" to "tt0085811"), film("51", "Krull", 1983, "imdb" to "tt0085811", "tmdb" to "9967"))) + assertEquals("50", MoveMatcher(old, new).match("1", "Krull", "Movie", 1983).newId) + assertEquals("51", MoveMatcher(old, new, preferred = setOf("51")).match("1", "Krull", "Movie", 1983).newId) + } + + @Test fun aRemakeWithTheSameTitleIsNeverTaken() { + val old = MemoryMoveCatalogue(sequenceOf(film("1", "The Blob", 1958, "imdb" to "tt0051418"))) + val new = MemoryMoveCatalogue(sequenceOf(film("2", "The Blob", 1988, "imdb" to "tt0094761"))) + val m = MoveMatcher(old, new).match("1", "The Blob", "Movie", 1958) + assertNull(m.newId); assertEquals(MoveHow.Missing, m.how) + } + + @Test fun noIdsAtAllFallsBackToTitleAndYear() { + val old = MemoryMoveCatalogue(sequenceOf(film("1", "Robin Redbreast", 1970))) + val new = MemoryMoveCatalogue(sequenceOf(film("2", "Robin Redbreast (1970)", 1970), film("3", "Robin Redbreast", 2020))) + val m = MoveMatcher(old, new).match("1", "Robin Redbreast", "Movie", 1970) + assertEquals("2", m.newId); assertEquals(MoveHow.TitleYear, m.how) + } + + @Test fun twoPossibleWorksAreListedNotGuessed() { + val old = MemoryMoveCatalogue(sequenceOf(show("1", "Cosmos", null))) + val new = MemoryMoveCatalogue(sequenceOf(show("2", "Cosmos", 1980, "tvdb" to "1"), show("3", "Cosmos", 2014, "tvdb" to "2"))) + val m = MoveMatcher(old, new).match("1", "Cosmos", "Series", null) + assertNull(m.newId); assertEquals(MoveHow.Ambiguous, m.how); assertEquals(2, m.candidates.size) + } + + @Test fun idsThatDisagreeAreAmbiguous() { + val old = MemoryMoveCatalogue(sequenceOf(show("1", "Life", 2009, "imdb" to "tt1", "tvdb" to "77"))) + val new = MemoryMoveCatalogue(sequenceOf(show("2", "Life", 2009, "imdb" to "tt1", "tvdb" to "99"), show("3", "Life Story", 2014, "tvdb" to "77", "imdb" to "tt5"))) + assertEquals(MoveHow.Ambiguous, MoveMatcher(old, new).match("1", "Life", "Series", 2009).how) + } + + @Test fun aTitleMissingFromTheOldCatalogueIsMatchedFromItsSavedName() { + val new = MemoryMoveCatalogue(sequenceOf(film("7", "Dead Heat", 1988))) + assertEquals("7", MoveMatcher(MemoryMoveCatalogue(emptySequence()), new).match("1", "Dead Heat", "Movie", 1988).newId) + } + + @Test fun titleKeysIgnoreArticlesPunctuationAndYears() { + assertEquals(moveTitleKey("The Burbs"), moveTitleKey("'Burbs")) + assertEquals(moveTitleKey("Burke & Hare (2010)"), moveTitleKey("Burke and Hare")) + } + + // --- Workspaces --- + + private fun dir() = Files.createTempDirectory("move").toFile().apply { deleteOnExit() } + private class Rig(val from: File, val to: File) + + private fun rig(): Rig { + val from = File(dir(), "schedule").apply { mkdirs() }; val to = File(dir(), "schedule").apply { mkdirs() } + val old = ScheduleStore(from); val new = ScheduleStore(to) + old.saveChoices(oldUser, 305, ChannelChoices(listOf( + Suggestion("100", "Tremors", 1990, "Movie", "day", "Daytime pick"), + Suggestion("101", "Evil Dead II", 1987, "Movie", "late", "Late pick", "mediasource_101", 5_000_000), + Suggestion("102", "Robin Redbreast", 1970, "Movie", "late", ""), + Suggestion("103", "Cosmos", null, "Series", "", "")), setOf("104"))) + new.saveChoices(newUser, 305, ChannelChoices(listOf(Suggestion("9500", "Night of the Creeps", 1986, "Movie", "late", "Approved on the VPS")))) + new.saveChoices(newUser, 303, ChannelChoices(listOf(Suggestion("9600", "Aliens", 1986, "Movie", "", "")))) + // A plan and a booking on the new server: never touched. + new.savePlan(newUser, 305, ChannelPlan(emptyList(), ScheduleCursor())) + new.saveBooked(newUser, setOf("9500")) + new.savePool(newUser, 306, ScheduleStore.SavedPool(listOf(PoolSeries("9700", "Cocoon", listOf(PoolEpisode("9700", "s", EpisodeMark(1, 1), "Cocoon", 6_000_000)))), 1_000L, "sig")) + // Your channel, a clash on 701 with a different channel already on the new server. + File(from, "yours.json").writeText("""[{"number":701,"name":"Orbit Mistletoe","style":"Shaped","shows":["A Christmas Film"]}]""") + File(to, "yours.json").writeText("""[{"number":701,"name":"Comedy Club","style":"Standard","shows":[]}]""") + old.saveChoices(oldUser, 701, ChannelChoices(listOf(Suggestion("200", "A Christmas Film", 2019, "Movie", "", "")))) + old.saveProgress(oldUser, 701, ScheduleStore.SavedProgress(true, ScheduleCursor())) + saveDecision(old.decisionsFile(), ChairDecision("100", "Tremors", "Movie", true, 305, 305, 1L)) + File(from, "taste").mkdirs() + File(from, "taste/grown.events.jsonl").writeText(TasteEvent("e1", "grown", TasteKind.Finished, "100", null, "Tremors", 305, 5L, 6_000_000, "channel").toLine() + "\n") + return Rig(from, to) + } + private val oldCat = MemoryMoveCatalogue(sequenceOf(film("100", "Tremors", 1990, "imdb" to "tt0100814"), film("101", "Evil Dead II", 1987, "imdb" to "tt0092991"), + film("102", "Robin Redbreast", 1970), show("103", "Cosmos", null), film("104", "Bad Film", 2001, "imdb" to "tt9"), film("200", "A Christmas Film", 2019, "tmdb" to "55"))) + private val newCat = MemoryMoveCatalogue(sequenceOf(film("9001", "Tremors", 1990, "imdb" to "tt0100814"), film("9002", "Evil Dead II", 1987, "imdb" to "tt0092991"), + show("9003", "Cosmos", 1980, "tvdb" to "1"), show("9004", "Cosmos", 2014, "tvdb" to "2"), film("9005", "Bad Film", 2001, "imdb" to "tt9"), + film("9006", "A Christmas Film", 2019, "tmdb" to "55"), film("9500", "Night of the Creeps", 1986))) + private fun move(r: Rig, refresh: Set = setOf(306)) = ServerMove(r.from, oldUser, r.to, newUser, oldCat, newCat, refresh, nowMs = 1_800_000_000_000) + + @Test fun thePreviewMatchesListsAndChangesNothing() { + val r = rig(); val before = snapshot(r.to) + val plan = move(r).preview() + val ad = plan.channels.single { it.number == 305 } + assertEquals(listOf("moved-100", "moved-101"), ad.add.map { it.id }) // Tremors, Evil Dead II: placeholders until the server confirms + assertEquals(listOf("imdb.tt0100814", "imdb.tt0092991"), ad.add.map { it.ref }) + assertEquals(listOf("day", "late"), ad.add.map { it.group }) // each keeps its block + assertTrue(ad.add.all { it.sourceId == null && it.durationMs == null }) // the copy is checked afresh by the pool read + assertEquals(setOf("9005"), ad.rejectedMatched) + assertEquals(listOf("Robin Redbreast"), plan.missing.map { it.title }) + assertEquals(listOf("Robin Redbreast"), plan.unrecoverable.map { it.title }) // no ID to look it up by: listed only + assertEquals(listOf("Cosmos"), plan.ambiguous.map { it.title }) + assertEquals(702, plan.yours.single().channel.number) // 701 is taken by your other channel + assertEquals(listOf(306), plan.refresh) + assertEquals(before, snapshot(r.to)) + } + + @Test fun applyAddsOnlyKeepsWhatsThereAndRollbackPutsItBack() { + val r = rig(); val before = snapshot(r.to) + val m = move(r); val plan = m.preview() + val receipt = m.apply(plan.signature) + val store = ScheduleStore(r.to) + val ad = store.loadChoices(newUser, 305) + assertEquals(listOf("9500", "moved-100", "moved-101"), ad.accepted.map { it.id }) // the VPS approval first, kept + assertEquals(setOf("9005"), ad.rejected) + assertEquals(listOf("9600"), store.loadChoices(newUser, 303).accepted.map { it.id }) + assertEquals(listOf("moved-200"), store.loadChoices(newUser, 702).accepted.map { it.id }) + assertTrue(File(r.to, "yours.json").readText().contains("Comedy Club")) + assertTrue(File(r.to, "yours.json").readText().contains("Orbit Mistletoe")) + assertEquals(true, store.loadProgress(newUser, 702)?.enabled) + assertEquals("9001", loadDecisions(store.decisionsFile()).single().id) + assertEquals("9001", TasteStore(File(r.to, "taste")).events("grown").single().itemId) + assertEquals(0L, store.loadPool(newUser, 306)?.fetchedAtMs) + // Plans and bookings are untouched. + listOf("schedule-305.json", "booked-0.json").forEach { assertEquals(before[it], snapshot(r.to)[it]) } + // A second move finds nothing more to do. + assertEquals(0, move(r, emptySet()).preview().adds) + ServerMove.rollback(r.to, receipt) + assertEquals(before, snapshot(r.to).filterKeys { it in before }) + assertFalse(File(r.to, "choices-702.json").exists()) + } + + @Test fun applyRefusesWhenThePreviewNoLongerMatches() { + val r = rig(); val m = move(r); val sig = m.preview().signature + ScheduleStore(r.from).saveChoices(oldUser, 307, ChannelChoices(listOf(Suggestion("100", "Tremors", 1990, "Movie", "", "")))) + assertThrows(IllegalArgumentException::class.java) { move(r).apply(sig) } + } + + @Test fun aChannelOfYoursAlreadyOnTheNewServerByNameIsntMadeTwice() { + val r = rig() + File(r.to, "yours.json").writeText("""[{"number":705,"name":"Orbit Mistletoe","style":"Shaped","shows":[]}]""") + val plan = move(r).preview() + assertTrue(plan.yours.isEmpty()) + assertEquals(listOf("moved-200"), plan.channels.single { it.number == 705 }.add.map { it.id }) + } + + @Test fun aTitleTheCatalogueCopyLacksIsLookedUpByItsIdNotWrittenOff() { + val r = rig() + ScheduleStore(r.from).saveChoices(oldUser, 304, ChannelChoices(listOf(Suggestion("105", "Deep Red", 1975, "Movie", "", "")))) + val withDeepRed = MemoryMoveCatalogue(sequenceOf(film("105", "Deep Red", 1975, "imdb" to "tt0073582"))) + val plan = ServerMove(r.from, oldUser, r.to, newUser, withDeepRed, newCat, nowMs = 1L).preview() + assertEquals(listOf("Deep Red"), plan.lookups.map { it.title }) + assertEquals("imdb.tt0073582", plan.channels.single { it.number == 304 }.add.single().ref) + assertTrue(plan.unrecoverable.none { it.title == "Deep Red" }) + } + + @Test fun aTitleAlreadyApprovedOnTheNewServerIsntAddedTwice() { + val r = rig() + ScheduleStore(r.to).saveChoices(newUser, 305, ChannelChoices(listOf(Suggestion("9999", "Tremors", 1990, "Movie", "late", "")))) + assertTrue(move(r).preview().channels.single { it.number == 305 }.add.none { it.title == "Tremors" }) + } + + private fun snapshot(dir: File): Map = + dir.walk().filter { it.isFile && !it.name.endsWith(".prev") && !it.name.endsWith(".tmp") }.associate { it.relativeTo(dir).path to it.readText() } + + // --- Scale: small, medium and very large fictional libraries, with gaps in the metadata --- + + private fun library(size: Int, seed: Int, idBase: Int): Pair, List> { + val r = java.util.Random(seed.toLong()) + val old = ArrayList(size); val new = ArrayList(size) + for (i in 0 until size) { + val type = if (i % 5 == 0) "Series" else "Movie" + val title = "Title $i " + listOf("Night", "Day", "Return", "Saga")[i % 4] + val year = if (r.nextInt(10) == 0) null else 1950 + r.nextInt(75) + val refs = buildMap { if (r.nextInt(10) < 8) put("imdb", "tt$i"); if (r.nextInt(10) < 5) put(if (type == "Series") "tvdb" else "tmdb", "$i") } + old += MoveItem("$i", type, title, year, refs) + when { + i % 50 == 0 -> {} // gone from the new library + i % 31 == 0 -> new += MoveItem("${idBase + i}", type, "$title Remastered", year, refs.ifEmpty { mapOf("imdb" to "tt$i") }) // renamed + else -> { new += MoveItem("${idBase + i}", type, title, year, refs); if (i % 7 == 0) new += MoveItem("${idBase * 2 + i}", type, title, year, refs) } // some copies + } + } + return old to new + } + + private fun matchAll(size: Int) { + val (o, n) = library(size, size, 10_000_000) + val started = System.nanoTime() + val matcher = MoveMatcher(MemoryMoveCatalogue(o.asSequence()), MemoryMoveCatalogue(n.asSequence())) + val results = o.map { matcher.match(it.id, it.title, it.type, it.year) } + val tookMs = (System.nanoTime() - started) / 1_000_000 + // Nothing gone is ever matched, and nothing matched is the wrong work. + results.zip(o).forEach { (m, item) -> + val i = item.id.toInt() + if (i % 50 == 0) assertFalse("gone $i matched", m.matched) + if (m.matched) assertTrue("wrong work for $i", m.newId!!.toInt() % 10_000_000 == i) + } + val present = o.count { it.id.toInt() % 50 != 0 } + assertTrue("size $size matched ${results.count { it.matched }} of $present", results.count { it.matched } >= present * 0.97) + assertTrue("size $size took $tookMs ms", tookMs < 20_000) + } + + @Test fun aSmallLibrary() = matchAll(200) + @Test fun aMediumLibrary() = matchAll(5_000) + @Test fun aVeryLargeLibrary() = matchAll(120_000) +}