Server move: your programming survives a change of server; approvals heal themselves (build 65)
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 3m39s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 3m28s
release-gate / verify (push) Successful in 14m53s

Paul, 18 November 2026 (Stage 1 of the network audit): the move to the VPS left every approval, both of his own
channels, Chair decisions and viewing behind, since each server's data is kept apart. ServerMove carries them to the
server in use: approved titles with their blocks, rejections, your channels (renumbered on a clash, never duplicated),
Chair decisions and dismissals, the learning switch, each profile's Taste. Matched through the two catalogues on the TV
by IMDb, TMDB or TVDB, then title and year; remakes, conflicting IDs and two possible works are listed, never guessed.
Preview changes nothing; apply needs the preview's signature, only adds, never touches plans, bookings, tickets or
anything already on the new server, and keeps every touched file in a receipt for rollback. No server is contacted.
For now from adb (household receiver: move-preview, move-apply, move-rollback).

The VPS renumbers its items, so about 40% of the TV's catalogue IDs are stale: moved approvals are saved under a
placeholder with their provider ID, and a pool read finds each by that ID (one request, paced) and keeps the server's
own ID. Any approval with a provider ID heals the same way when its item has gone, and a saved film ID whose name doesn't
match the approval is no longer trusted. Short pools are marked for an early, paced re-read.

Tests: matching, preview, apply, rollback, refusal, renumbering, self-healing approvals; small, medium and 120,000-item
fictional libraries with missing metadata, changed IDs, copies and renames.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 14:37:18 +00:00
co-authored by Claude Opus 5.5
parent 59f7392d73
commit 97b0947257
9 changed files with 762 additions and 17 deletions
@@ -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 {
@@ -20,7 +20,12 @@ internal data class SuggestionRule(val group: String, val label: String, val typ
val excludeGenres: Set<String> = 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<Suggestion> = emptyList(), val rejected: Set<String> = emptySet()) {
/** Part of the cache signature, so choosing different titles reads them in. */
@@ -372,7 +372,9 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
internal class PoolRead(val series: List<PoolSeries>, 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<String, String> = 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<String, String>()
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<String, Long>? {
private fun playableFilm(id: String, englishAudio: Boolean, title: String? = null): Pair<String, Long>? {
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<SuggestionRule>, alreadyInPool: Set<String>, rejected: Set<String>, takenTitles: Set<String> = 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<org.json.JSONObject> {
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()))
@@ -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()
@@ -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<String, String>)
/** 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<MoveItem>
fun byTitle(type: String, key: String): List<MoveItem>
}
internal class MemoryMoveCatalogue(items: Sequence<MoveItem>) : MoveCatalogue {
private val ids = HashMap<String, MoveItem>()
private val refs = HashMap<String, MutableList<MoveItem>>()
private val titles = HashMap<String, MutableList<MoveItem>>()
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<MoveItem>()
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<String>, titles: Set<String>): Pair<MemoryMoveCatalogue, MemoryMoveCatalogue> {
val old = of(oldFile) { it.id in ids }
val refs = HashSet<String>(); val keys = HashSet<String>(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<String, String> = 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<String> = 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<String> = emptySet()) {
private val cache = HashMap<String, MoveMatch>()
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<MoveItem>) = copies.firstOrNull { it.id in preferred }
?: copies.minWithOrNull(compareBy<MoveItem>({ 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<Pair<MoveMatch, String>>, val alreadyThere: Int, val add: List<Suggestion>,
val rejectedMatched: Set<String>, 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<ChannelMove>, val yours: List<YourChannelMove>, val decisions: List<ChairDecision>, val decisionsTotal: Int,
val taste: Map<String, List<TasteEvent>>, val tasteTotal: Int, val copyLearning: Boolean, val dismissed: Set<String>, val refresh: List<Int>) {
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<Int> = 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<CustomChannel> = 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<Int, Int>()
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<String, String, Int?>? = 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<Int, Int>): Pair<Map<String, List<TasteEvent>>, 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<String> =
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<String>, Set<String>> {
val ids = HashSet<String>(); val titles = HashSet<String>()
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()
}
}