|
|
|
@@ -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()
|
|
|
|
|
}
|
|
|
|
|
}
|