package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbChangedPart import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbChapterPageUrls import eu.friedcutlet.yokan.database.DbFetchType import eu.friedcutlet.yokan.database.DbHistory import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbStatus import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackStatus import eu.friedcutlet.yokan.database.DbUpdate import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot import eu.friedcutlet.yokan.database.effectiveFiller import eu.friedcutlet.yokan.database.sync.SyncIds import eu.friedcutlet.yokan.database.sync.SyncPaths import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.int import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put internal data class MangayomiNamespace(val server: String, val accountId: String) internal data class MangayomiBatch( val kind: Int?, val localIds: List, val deletions: List = emptyList(), ) internal data class MangayomiPage( val data: JsonObject, val cursors: Map, val sessionToken: String?, val hasMore: Boolean, val syncedAt: Long?, ) internal data class MangayomiMerge( val snapshot: YokanDatabaseSnapshot, val downloadedChanges: Int, val settingsChanged: Boolean, ) /** Pure conversion between Yokan snapshots and Mangayomi's independent clientId wire protocol. */ internal class MangayomiSyncMapper( mappingsJson: String?, private val namespace: MangayomiNamespace, ) { private val json = Json { ignoreUnknownKeys = true explicitNulls = false } private val namespaceKey = "${normalizeServer(namespace.server)}\n${namespace.accountId}" private val all = linkedMapOf>>() private val bindings = linkedMapOf>() // Every canonical/alias id of the active namespace -> owning local key, per kind. Binding id // sets only grow, so entries are never removed. private val owners = mutableMapOf>() private val pendingAliases = mutableMapOf>() private val pendingByCanonical = mutableMapOf>>() private class Binding( var canonical: Long, val aliases: MutableSet = linkedSetOf(), val retired: MutableSet = linkedSetOf(), val deletionTargets: MutableMap = linkedMapOf(), ) init { if (mappingsJson != null) { val root = json.parseToJsonElement(mappingsJson).jsonObject val version = root["version"] as? JsonPrimitive require(version != null && !version.isString && version.intOrNull == 1) { "Unsupported Mangayomi mapping version" } val namespaces = root["namespaces"]?.jsonObject ?: error("Missing mapping namespaces") namespaces.forEach { (key, value) -> require(key.isNotBlank()) { "Invalid mapping namespace" } val namespaceBindings = linkedMapOf>() value.jsonObject.forEach { (kind, rows) -> require( kind.toIntOrNull()?.let { it in SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE } == true ) { "Invalid mapping kind" } val entities = linkedMapOf() rows.jsonObject.forEach { (local, raw) -> val localId = local.toLongOrNull() require(localId != null && localId > 0 && local == localId.toString()) { "Invalid local mapping id" } val obj = raw.jsonObject val canonical = safeId(obj["canonical"]) val aliasesElement = obj["aliases"] require(aliasesElement == null || aliasesElement is JsonArray) { "Invalid mapping aliases" } val aliasList = aliasesElement.orEmpty().map(::safeId) require(aliasList.size == aliasList.toSet().size) { "Duplicate mapping alias" } val aliases = aliasList.toMutableSet() val retiredElement = obj["retired"] require(retiredElement == null || retiredElement is JsonArray) { "Invalid retired ids" } val retiredList = retiredElement.orEmpty().map(::safeId) require(retiredList.size == retiredList.toSet().size) { "Duplicate retired id" } val retired = retiredList.toMutableSet() require(canonical !in aliases) { "Canonical id repeated as alias" } require(canonical !in retired && retired.all { it in aliases }) { "Invalid retired mapping ids" } val targetsObj = obj["deletionTargets"]?.jsonObject ?: JsonObject(emptyMap()) val targets = targetsObj.mapValues { safeId(it.value) }.toMutableMap() require(targets.values.all { it == canonical || it in aliases }) { "Invalid recreation deletion target" } entities[local] = Binding(canonical, aliases, retired, targets) } validateOwnership(entities) namespaceBindings[kind] = entities } all[key] = namespaceBindings } all[namespaceKey]?.forEach { (kind, rows) -> bindings[kind] = rows rows.forEach { (local, b) -> own(kind, b.canonical, local) b.aliases.forEach { own(kind, it, local) } } } } } fun mappingsJson(): String = buildJsonObject { put("version", 1) put( "namespaces", buildJsonObject { val namespaces = all.toMutableMap() namespaces[namespaceKey] = bindings namespaces.entries .sortedBy { it.key } .forEach { (ns, kinds) -> put( ns, buildJsonObject { kinds.entries .sortedBy { it.key } .forEach { (kind, entries) -> put( kind, buildJsonObject { entries.entries .sortedBy { it.key } .forEach { (local, b) -> put( local, buildJsonObject { put( "canonical", b.canonical, ) put( "aliases", JsonArray( b.aliases .sorted() .map( :: JsonPrimitive ) ), ) if (b.retired.isNotEmpty()) put( "retired", JsonArray( b.retired .sorted() .map( :: JsonPrimitive ) ), ) if ( b.deletionTargets .isNotEmpty() ) put( "deletionTargets", buildJsonObject { b .deletionTargets .entries .sortedBy { it.key } .forEach { ( record, id) -> put( record, id, ) } }, ) }, ) } }, ) } }, ) } }, ) } .toString() fun prepare( snapshot: YokanDatabaseSnapshot, preference: DbSyncPreference, ): List { val rows = linkedMapOf( SyncPaths.KIND_CATEGORY to snapshot.categories.map { it.id }, SyncPaths.KIND_MANGA to snapshot.mangas.map { it.id }, SyncPaths.KIND_CHAPTER to snapshot.chapters.map { it.id }, SyncPaths.KIND_TRACK to snapshot.tracks.map { it.id }, SyncPaths.KIND_HISTORY to if (preference.syncHistories) snapshot.histories.map { it.id } else emptyList(), SyncPaths.KIND_UPDATE to if (preference.syncUpdates) snapshot.updates.map { it.id } else emptyList(), ) ensureRecreationTransitions(snapshot.changedParts, snapshot, preference) rows.forEach { (kind, ids) -> ids.forEach { id -> remoteId(kind, id) } } val rowSets = rows.mapValues { it.value.toHashSet() } validateUploadDependencies(snapshot, rowSets) val order = rows.keys.toList() val deleteGroups = linkedMapOf>() snapshot.changedParts.forEach { part -> deletionRecord(part)?.let { (kind, local) -> if ( kind in order && bindings[kind.toString()]?.containsKey(local.toString()) == true && (local !in rowSets.getValue(kind) || deletionTarget(kind, local, part) != null) && (kind != SyncPaths.KIND_HISTORY || preference.syncHistories) && (kind != SyncPaths.KIND_UPDATE || preference.syncUpdates) ) deleteGroups.getOrPut(kind) { mutableListOf() } += part } } val batches = mutableListOf() if (deleteGroups.isNotEmpty()) { deleteGroups.forEach { (kind, parts) -> val chunks = parts.distinct().chunked(5000) chunks.forEachIndexed { index, chunk -> val target = batches.size.also { batches += MangayomiBatch(null, emptyList()) } batches[target] = batches[target].copy(deletions = batches[target].deletions + chunk) } } } for (kind in order) for (chunk in rows.getValue(kind).chunked(5000)) batches += MangayomiBatch(kind, chunk) if (batches.isEmpty()) batches += MangayomiBatch(null, emptyList()) return batches } fun encode(captured: YokanDatabaseSnapshot, batch: MangayomiBatch): JsonObject = buildJsonObject { batch.kind?.let { kind -> val kindName = wireKey(kind) val byId = rowsById(captured, kind) val array = batch.localIds.map { id -> encodeRow( kind, byId[id] ?: error("Captured entity $kind/$id no longer exists"), ) } put(kindName, JsonArray(array)) } if (batch.deletions.isNotEmpty()) { val deleted = linkedMapOf>() batch.deletions.forEach { part -> val o = json.parseToJsonElement(part.data).jsonObject val kind = o.getValue("kind").jsonPrimitive.int val local = o.getValue("localId").jsonPrimitive.content.toLong() deleted.getOrPut(wireKey(kind)) { mutableListOf() } += deletionTarget(kind, local, part) ?: mappedId(kind, local) } put( "deleted", buildJsonObject { deleted.forEach { (k, ids) -> put(k, JsonArray(ids.distinct().map(::JsonPrimitive))) } }, ) } } fun decodePage(body: String): MangayomiPage { val root = json.parseToJsonElement(body).jsonObject val data = root["data"]?.let { raw -> val nested = raw as? JsonObject ?: error("Invalid response data") val wireKeys = (SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE).map(::wireKey) + listOf( "tombstones", "deleted", "mangaClientIdRemap", "chapterClientIdRemap", ) JsonObject(nested + root.filterKeys { it in wireKeys && it !in nested }) } ?: root val cursorsRaw = root["cursors"] ?: data["cursors"] val cursorObj = cursorsRaw?.let { it as? JsonObject ?: error("Invalid cursors") } ?: JsonObject(emptyMap()) val cursors = cursorObj.mapValues { (_, v) -> if (v is JsonNull) null else (v as? JsonPrimitive)?.takeIf { it.isString }?.content ?: error("Invalid cursor") } val moreElement = root["hasMore"] ?: data["hasMore"] ?: error("Missing hasMore") val hasMore = moreElement.jsonPrimitive.booleanOrNull ?: error("Invalid hasMore") val syncedElement = root["syncedAt"] ?: data["syncedAt"] ?: error("Missing syncedAt") val syncedAt = if (syncedElement is JsonNull && hasMore) null else longValue(syncedElement).also { require(it >= 0) { "Invalid syncedAt" } } val tokenElement = root["sessionToken"] ?: data["sessionToken"] val token = tokenElement?.let { if (it is JsonNull) null else (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content ?: error("Invalid sessionToken") } return MangayomiPage(data, cursors, token, hasMore, syncedAt) } fun acceptRemaps(page: MangayomiPage) { validatePage(page) acceptRemapKind(page.data, SyncPaths.KIND_MANGA, "mangaClientIdRemap") acceptRemapKind(page.data, SyncPaths.KIND_CHAPTER, "chapterClientIdRemap") } fun merge( current: YokanDatabaseSnapshot, pages: List, preference: DbSyncPreference, ): MangayomiMerge { pages.forEach(::validatePage) ensureRecreationTransitions(current.changedParts, current, preference) val rows = mutableMapOf>() val tombstones = mutableMapOf>() pages.forEach { page -> acceptRemaps(page) listOf( SyncPaths.KIND_CATEGORY, SyncPaths.KIND_MANGA, SyncPaths.KIND_CHAPTER, SyncPaths.KIND_TRACK, SyncPaths.KIND_HISTORY, SyncPaths.KIND_UPDATE, ) .forEach { k -> if ( k == SyncPaths.KIND_HISTORY && !preference.syncHistories || k == SyncPaths.KIND_UPDATE && !preference.syncUpdates ) return@forEach (page.data[wireKey(k)] as? JsonArray)?.forEach { rows.getOrPut(k) { mutableListOf() } += it.jsonObject } } val deleted = page.data["tombstones"] as? JsonObject ?: page.data["deleted"] as? JsonObject deleted?.forEach { (key, ids) -> kindForKey(key)?.let { k -> if ( (k != SyncPaths.KIND_HISTORY || preference.syncHistories) && (k != SyncPaths.KIND_UPDATE || preference.syncUpdates) ) (ids as JsonArray).forEach { tombstones.getOrPut(k) { mutableSetOf() } += safeId(it) } } } } val result = MutableSnapshot(current) val queuedDeleteLocals = current.changedParts .mapNotNull(::deletionRecord) .groupBy({ it.first }, { it.second }) .mapValues { it.value.toSet() } val localByRemote = mutableMapOf>() val claimedNaturalLocals = mutableMapOf>() // Identity is established for all rows before LWW, allowing stale rows/remaps to // canonicalize references. for (k in listOf( SyncPaths.KIND_CATEGORY, SyncPaths.KIND_MANGA, SyncPaths.KIND_CHAPTER, SyncPaths.KIND_TRACK, SyncPaths.KIND_HISTORY, SyncPaths.KIND_UPDATE, )) { rows[k].orEmpty().forEach { row -> val remote = safeId(row["clientId"]) val local = localByRemote[k]?.get(remote) ?: resolveLocal(result, k, remote, row, claimedNaturalLocals[k].orEmpty()) bind(k, local, remote) localByRemote.getOrPut(k) { mutableMapOf() }[remote] = local if (k == SyncPaths.KIND_HISTORY || k == SyncPaths.KIND_UPDATE) claimedNaturalLocals.getOrPut(k) { mutableSetOf() } += local } } val count = intArrayOf(0) for (k in listOf( SyncPaths.KIND_CATEGORY, SyncPaths.KIND_MANGA, SyncPaths.KIND_CHAPTER, SyncPaths.KIND_TRACK, SyncPaths.KIND_HISTORY, SyncPaths.KIND_UPDATE, )) { rows[k].orEmpty().forEach { row -> val local = localByRemote[k]?.get(safeId(row["clientId"])) if ( local != null && local in queuedDeleteLocals[k].orEmpty() && !hasLocalEntity(result, k, local) ) return@forEach if ( k != SyncPaths.KIND_MANGA && rowParentPendingDelete(result, k, row, localByRemote, queuedDeleteLocals) ) return@forEach if (applyRow(result, k, row, localByRemote, queuedDeleteLocals)) count[0]++ } } tombstones.forEach { (kind, ids) -> val recreationTargets = bindings[kind.toString()] ?.values ?.flatMapTo(hashSetOf()) { it.deletionTargets.values } .orEmpty() ids.forEach { remote -> if (remote in recreationTargets) return@forEach val owner = ownerForRemote(kind, remote) val local = owner?.takeIf { remote == it.second.canonical }?.first?.toLong() if (local == null) return@forEach require(!unsafeDownload(result, kind, local)) { "Cannot delete entity with active download" } rotate(kind, local) result.delete(kind, local) } } return MangayomiMerge(result.build(), count[0], false) } private fun encodeRow(k: Int, value: Any): JsonObject { val row = when (k) { SyncPaths.KIND_CATEGORY -> encodeCategory(value as DbCategory) SyncPaths.KIND_MANGA -> encodeManga(requireNotNull(value as? DbManga)) SyncPaths.KIND_CHAPTER -> encodeChapter(requireNotNull(value as? DbChapter)) SyncPaths.KIND_TRACK -> encodeTrack(value as DbTrack) SyncPaths.KIND_HISTORY -> encodeHistory(value as DbHistory) else -> encodeUpdate(value as DbUpdate) } return withinServerLimits(k, row) } private fun clientId(kind: Int, local: Long?): JsonElement = local?.let { JsonPrimitive(mappedId(kind, it)) } ?: JsonNull private fun millis(v: String?): JsonElement = v?.let { (it.toLongOrNull() ?: parseInstantMillis(it))?.let(::JsonPrimitive) } ?: JsonNull private fun encodeCategory(x: DbCategory) = buildJsonObject { put("clientId", clientId(SyncPaths.KIND_CATEGORY, x.id)) put("name", x.name) put("forItemType", x.forItemType.name.uppercase()) put("pos", x.position?.let(::JsonPrimitive) ?: JsonNull) put("hide", x.hidden ?: false) put("shouldUpdate", x.shouldUpdate ?: true) put("updatedAt", x.updatedAt) } private fun encodeManga(x: DbManga) = buildJsonObject { put("clientId", clientId(SyncPaths.KIND_MANGA, x.id)) nullable("source", x.source) nullable("sourceId", x.sourceId) nullable("link", x.link) put("itemType", type(x.itemType)) nullable("name", x.name) nullable("imageUrl", x.imageUrl) nullable("description", x.description) nullable("author", x.author) nullable("artist", x.artist) put("status", status(x.status)) put("genre", JsonArray((x.genre ?: emptyList()).map(::JsonPrimitive))) nullable("lang", x.lang) nullable("lastUpdate", x.lastUpdate) put("favorite", x.favorite) nullable("dateAdded", x.dateAdded) put("lastRead", x.lastRead) put("isLocalArchive", x.isLocalArchive) nullable("customCoverFromTracker", x.customCoverFromTracker) nullable("smartUpdateDays", x.smartUpdateDays) put( "categoryClientIds", JsonArray((x.categories ?: emptyList()).map { clientId(SyncPaths.KIND_CATEGORY, it) }), ) put("updatedAt", x.updatedAt) } private fun encodeChapter(x: DbChapter) = buildJsonObject { put("clientId", clientId(SyncPaths.KIND_CHAPTER, x.id)) put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId)) nullable("name", x.name) nullable("url", x.url) put("scanlator", x.scanlator) put("dateUpload", millis(x.dateUpload)) put("isFiller", x.effectiveFiller) nullable("thumbnailUrl", x.thumbnailUrl) nullable("description", x.description) put("downloadSize", JsonNull) nullable("duration", x.duration?.toLongOrNull()) put("isRead", x.isRead) put("isBookmarked", x.isBookmarked) put("lastPageRead", x.lastPageRead) put("updatedAt", x.updatedAt) } private fun encodeTrack(x: DbTrack) = buildJsonObject { put("clientId", clientId(SyncPaths.KIND_TRACK, x.id)) put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId)) nullable("syncId", x.syncId) nullable("mediaId", x.mediaId) nullable("libraryId", x.libraryId) nullable("title", x.title) nullable("lastChapterRead", x.lastChapterRead) nullable("totalChapter", x.totalChapter) nullable("score", x.score) put("status", x.status.name.replace(Regex("([a-z])([A-Z])"), "$1_$2").uppercase()) nullable("startedReadingDate", x.startedReadingDate) nullable("finishedReadingDate", x.finishedReadingDate) nullable("trackingUrl", x.trackingUrl) put("itemType", type(x.itemType)) put("updatedAt", x.updatedAt) } private fun encodeHistory(x: DbHistory) = buildJsonObject { put("clientId", clientId(SyncPaths.KIND_HISTORY, x.id)) put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId)) put("chapterClientId", clientId(SyncPaths.KIND_CHAPTER, x.chapterId)) put("itemType", type(x.itemType)) put("date", millis(x.date)) nullable("readingTimeSeconds", x.readingTimeSeconds ?: 0) put("updatedAt", x.updatedAt) } private fun encodeUpdate(x: DbUpdate) = buildJsonObject { put("clientId", clientId(SyncPaths.KIND_UPDATE, x.id)) put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId)) nullable("chapterName", x.chapterName) put("date", millis(x.date)) put("updatedAt", x.updatedAt) } /** * The server rejects a whole request (HTTP 400) when any field exceeds its schema, and real * libraries have longer descriptions/authors than it allows. Clip to its limits * (mangayomi-sync-server lib/validation/sync.ts): only the server's copy is shortened; local * rows keep full text because equal-timestamp pulls never replace them. */ private fun withinServerLimits(k: Int, row: JsonObject): JsonObject { val limits = SERVER_STRING_LIMITS.getValue(k) return JsonObject( row.mapValues { (key, value) -> val max = limits[key] when { key == "trackingUrl" && value is JsonPrimitive && value.isString && value.content.isNotEmpty() && !value.content.startsWith("http://") && !value.content.startsWith("https://") -> JsonNull max != null && value is JsonPrimitive && value.isString && value.content.length > max -> JsonPrimitive(clip(value.content, max)) key == "genre" && value is JsonArray -> JsonArray( value.map { g -> if (g is JsonPrimitive && g.content.length > 100) JsonPrimitive(clip(g.content, 100)) else g } ) key == "categoryClientIds" && value is JsonArray && value.size > 200 -> JsonArray(value.take(200)) else -> value } } ) } // Counts UTF-16 units like JavaScript's string length; never splits a surrogate pair. private fun clip(s: String, max: Int): String = s.take(if (s[max - 1].isHighSurrogate()) max - 1 else max) private fun JsonObjectBuilder.nullable(key: String, v: String?) { put(key, v?.let(::JsonPrimitive) ?: JsonNull) } private fun JsonObjectBuilder.nullable(key: String, v: Number?) { put(key, v?.let(::JsonPrimitive) ?: JsonNull) } // asReversed keeps the first row for a duplicated id, like firstOrNull did. private fun rowsById(s: YokanDatabaseSnapshot, k: Int): Map = when (k) { SyncPaths.KIND_CATEGORY -> s.categories.asReversed().associateBy { it.id } SyncPaths.KIND_MANGA -> s.mangas.asReversed().associateBy { it.id } SyncPaths.KIND_CHAPTER -> s.chapters.asReversed().associateBy { it.id } SyncPaths.KIND_TRACK -> s.tracks.asReversed().associateBy { it.id } SyncPaths.KIND_HISTORY -> s.histories.asReversed().associateBy { it.id } else -> s.updates.asReversed().associateBy { it.id } } private fun own(kind: String, id: Long, local: String) { val owner = owners.getOrPut(kind) { mutableMapOf() }.getOrPut(id) { local } require(owner == local) { "Remote mapping id collision" } } private fun remoteId(k: Int, local: Long): Long { require(local > 0) val ks = k.toString() val map = bindings.getOrPut(ks) { linkedMapOf() } val key = local.toString() map[key]?.let { return it.canonical } val used = owners[ks].orEmpty() var candidate = hash("$namespaceKey|$k|$local") while (candidate in used || candidate <= 0) candidate = if (candidate == MAX_SAFE) 1 else candidate + 1 map[key] = Binding(candidate) own(ks, candidate, key) return candidate } private fun mappedId(k: Int, local: Long): Long = bindings[k.toString()]?.get(local.toString())?.canonical ?: error("Missing prepared mapping for kind $k local id $local") private fun recordKey(part: DbChangedPart): String = buildJsonObject { put("id", part.id) put("actionType", part.actionType.name) put("isarId", part.isarId?.let(::JsonPrimitive) ?: JsonNull) put("clientDate", part.clientDate) put("data", part.data) } .toString() private fun deletionTarget(kind: Int, local: Long, part: DbChangedPart): Long? = bindings[kind.toString()]?.get(local.toString())?.deletionTargets?.get(recordKey(part)) private fun ensureRecreationTransitions( parts: List, snapshot: YokanDatabaseSnapshot, preference: DbSyncPreference, ) { val records = parts.mapNotNull { part -> deletionRecord(part)?.let { (kind, local) -> Triple(kind, local, part) } } if (records.isEmpty()) return val ids = entityIds(snapshot) val groups = records .filter { (kind, local, _) -> enabled(kind, preference) && local in ids.getValue(kind) } .groupBy({ it.first to it.second }, { it.third }) val children by lazy { Children(snapshot) } groups.forEach { (identity, records) -> val (kind, local) = identity val binding = bindings[kind.toString()]?.get(local.toString()) ?: return@forEach val known = records.mapNotNull { binding.deletionTargets[recordKey(it)] }.distinct() require(known.size <= 1) { "Conflicting recreation deletion targets" } val target = known.singleOrNull() ?: binding.canonical.also { rotate(kind, local) rotateDependents(children, kind, local) } records.forEach { val key = recordKey(it) if (key !in binding.deletionTargets) binding.deletionTargets[key] = target } } } // The server cascades a manga delete to its chapters/tracks/histories/updates and a chapter // delete to its histories. // Surviving children must leave those old IDs too, or the cascade tombstones delete them on the // next pull. private class Children(s: YokanDatabaseSnapshot) { val byManga = listOf( SyncPaths.KIND_CHAPTER to s.chapters.groupBy({ it.mangaId }, { it.id }), SyncPaths.KIND_TRACK to s.tracks.groupBy({ it.mangaId }, { it.id }), SyncPaths.KIND_HISTORY to s.histories.groupBy({ it.mangaId }, { it.id }), SyncPaths.KIND_UPDATE to s.updates.groupBy({ it.mangaId }, { it.id }), ) val historiesByChapter = s.histories.groupBy({ it.chapterId }, { it.id }) } private fun rotateDependents(c: Children, k: Int, id: Long) { when (k) { SyncPaths.KIND_MANGA -> c.byManga.forEach { (kind, byParent) -> byParent[id].orEmpty().forEach { rotate(kind, it) } } SyncPaths.KIND_CHAPTER -> c.historiesByChapter[id].orEmpty().forEach { rotate(SyncPaths.KIND_HISTORY, it) } } } private fun entityIds(s: YokanDatabaseSnapshot): Map> = mapOf( SyncPaths.KIND_CATEGORY to s.categories.mapTo(hashSetOf()) { it.id }, SyncPaths.KIND_MANGA to s.mangas.mapTo(hashSetOf()) { it.id }, SyncPaths.KIND_CHAPTER to s.chapters.mapTo(hashSetOf()) { it.id }, SyncPaths.KIND_TRACK to s.tracks.mapTo(hashSetOf()) { it.id }, SyncPaths.KIND_HISTORY to s.histories.mapTo(hashSetOf()) { it.id }, SyncPaths.KIND_UPDATE to s.updates.mapTo(hashSetOf()) { it.id }, ) private fun rotate(k: Int, local: Long) { val ks = k.toString() val key = local.toString() val b = bindings[ks]?.get(key) ?: return b.aliases += b.canonical b.retired += b.canonical var id = hash("$namespaceKey|$k|$local|${SyncIds.random()}") val used = owners[ks].orEmpty() while (id in used) id = if (id == MAX_SAFE) 1 else id + 1 b.canonical = id own(ks, id, key) } private fun bind(k: Int, local: Long, remote: Long) { val ks = k.toString() val map = bindings.getOrPut(ks) { linkedMapOf() } val key = local.toString() val owner = owners[ks]?.get(remote) require(owner == null || owner == key) { "Remote id $remote already belongs to another local row" } val b = map.getOrPut(key) { Binding(remote) } when { remote == b.canonical -> Unit remote in b.aliases -> Unit // A retired/legacy alias never becomes canonical again. else -> { require(owner == null) b.aliases += b.canonical b.retired += b.canonical b.canonical = remote b.aliases += remote b.aliases.remove(remote) b.retired.remove(remote) } } own(ks, remote, key) pendingByCanonical[ks]?.get(remote)?.forEach { old -> b.aliases += old b.retired += old own(ks, old, key) } } private fun resolveLocal( s: MutableSnapshot, k: Int, remote: Long, r: JsonObject, claimed: Set, ): Long { ownerForRemote(k, remote)?.let { return it.first.toLong() } val matches = when (k) { SyncPaths.KIND_CATEGORY -> emptyList() SyncPaths.KIND_MANGA -> { val link = nullableString(r, "link") val source = nullableString(r, "source") if (link.isNullOrBlank() || source.isNullOrBlank()) emptyList() else s.mangaNatural[Triple(link, source, itemType(r, "itemType"))].map { s.mangas[it].id } } SyncPaths.KIND_CHAPTER -> { val url = nullableString(r, "url") val parent = remoteLocal(SyncPaths.KIND_MANGA, long(r, "mangaClientId")) if (url.isNullOrBlank() || parent == null || !s.mangas.has(parent)) emptyList() else s.chapterByUrl[parent to url].map { s.chapters[it].id } } SyncPaths.KIND_TRACK -> { val parent = remoteLocal(SyncPaths.KIND_MANGA, long(r, "mangaClientId")) val tracker = intNullable(r, "syncId") if (parent == null || tracker == null || !s.mangas.has(parent)) emptyList() else s.trackBySync[parent to tracker].map { s.tracks[it].id } } SyncPaths.KIND_HISTORY -> s.historyByChapter[ remoteLocal(SyncPaths.KIND_CHAPTER, long(r, "chapterClientId"))] .map { s.histories[it].id } else -> { val parent = remoteLocal(SyncPaths.KIND_MANGA, long(r, "mangaClientId")) val name = nullableString(r, "chapterName") if (parent == null || name.isNullOrBlank() || !s.mangas.has(parent)) emptyList() else s.updateByName[parent to name].map { s.updates[it].id } } } val available = if (k == SyncPaths.KIND_HISTORY || k == SyncPaths.KIND_UPDATE) matches.filterNot { it in claimed } else matches require(available.size <= 1) { "Ambiguous Mangayomi natural identity" } return available.singleOrNull() ?: newLocalIdentity(s, k) } private fun applyRow( s: MutableSnapshot, k: Int, r: JsonObject, maps: Map>, pendingDeletes: Map>, ): Boolean { val remote = safeId(r["clientId"]) val id = maps[k]?.get(remote) ?: error("Missing mapped identity") val updated = long(r, "updatedAt") require(updated >= 0) return when (k) { SyncPaths.KIND_CATEGORY -> applyCategory(s, id, r, updated) SyncPaths.KIND_MANGA -> applyManga(s, id, r, updated, maps, pendingDeletes) SyncPaths.KIND_CHAPTER -> applyChapter(s, id, r, updated, maps) SyncPaths.KIND_TRACK -> applyTrack(s, id, r, updated, maps) SyncPaths.KIND_HISTORY -> applyHistory(s, id, r, updated, maps) else -> applyUpdate(s, id, r, updated, maps) } } private fun ref( s: MutableSnapshot, r: JsonObject, maps: Map>, kind: Int, key: String, ): Long { val rid = safeId(r[key]) return resolveReference(s, kind, rid, maps) ?: error("Unresolved $key reference") } private fun applyCategory(s: MutableSnapshot, id: Long, r: JsonObject, updated: Long): Boolean { val i = s.categories.indexOf(id) val old = s.categories.getOrNull(i) if (old != null && updated <= old.updatedAt) return false val x = DbCategory( id, str(r, "name"), itemType(r, "forItemType"), intNullable(r, "pos"), boolNullable(r, "hide"), boolNullable(r, "shouldUpdate"), updated, ) if (old == null) s.categories += x else s.categories[i] = x return true } private fun applyManga( s: MutableSnapshot, id: Long, r: JsonObject, updated: Long, maps: Map>, pendingDeletes: Map>, ): Boolean { val i = s.mangas.indexOf(id) val old = s.mangas.getOrNull(i) if (old != null && updated <= old.updatedAt) return false val catIds = r["categoryClientIds"] ?.jsonArray ?.mapNotNull { e -> val remoteCat = safeId(e) resolveReference(s, SyncPaths.KIND_CATEGORY, remoteCat, maps) ?: run { val owner = ownerForRemote(SyncPaths.KIND_CATEGORY, remoteCat)?.first?.toLong() if ( owner != null && owner in pendingDeletes[SyncPaths.KIND_CATEGORY].orEmpty() && !hasLocalEntity(s, SyncPaths.KIND_CATEGORY, owner) ) { null } else { error("Unresolved category membership") } } } ?.takeIf { r.containsKey("categoryClientIds") } val x = DbManga( id = id, name = nullableString(r, "name"), link = nullableString(r, "link"), imageUrl = nullableString(r, "imageUrl"), description = nullableString(r, "description"), author = nullableString(r, "author"), artist = nullableString(r, "artist"), status = status(r, old?.status), itemType = itemType(r, "itemType"), genre = r["genre"]?.jsonArray?.map { it.jsonPrimitive.content }, favorite = bool(r, "favorite", false), source = nullableString(r, "source"), lang = nullableString(r, "lang"), dateAdded = longNullable(r, "dateAdded"), lastUpdate = longNullable(r, "lastUpdate"), lastRead = longNullable(r, "lastRead") ?: old?.lastRead ?: 0, categories = catIds ?: old?.categories, isLocalArchive = bool(r, "isLocalArchive", false), customCoverImage = old?.customCoverImage, customCoverFromTracker = nullableString(r, "customCoverFromTracker"), smartUpdateDays = intNullable(r, "smartUpdateDays"), updatedAt = updated, sourceId = longNullable(r, "sourceId"), privateNote = old?.privateNote.orEmpty(), cast = old?.cast.orEmpty(), parentId = old?.parentId, fetchType = old?.fetchType ?: DbFetchType.Episodes, seasonNumber = old?.seasonNumber, ) if (old == null) s.mangas += x else s.mangas[i] = x return true } private fun applyChapter( s: MutableSnapshot, id: Long, r: JsonObject, updated: Long, maps: Map>, ): Boolean { val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId") val i = s.chapters.indexOf(id) val old = s.chapters.getOrNull(i) if (old != null && updated <= old.updatedAt) return false require(s.mangas.has(manga)) { "Unresolved manga reference" } val x = DbChapter( id = id, mangaId = manga, name = nullableString(r, "name"), url = nullableString(r, "url") ?: "", dateUpload = longNullable(r, "dateUpload")?.toString() ?: "", scanlator = nullableString(r, "scanlator") ?: "", isBookmarked = bool(r, "isBookmarked", false), isRead = bool(r, "isRead", false), lastPageRead = nullableString(r, "lastPageRead") ?: "", archivePath = old?.archivePath ?: "", isFiller = bool(r, "isFiller", false), thumbnailUrl = nullableString(r, "thumbnailUrl"), description = nullableString(r, "description"), downloadSize = old?.downloadSize, duration = longNullable(r, "duration")?.toString(), updatedAt = updated, fetchedAt = old?.fetchedAt ?: 0, number = old?.number, season = old?.season, numberingName = old?.numberingName, fillerOverride = old?.fillerOverride, ) if (old == null) s.chapters += x else s.chapters[i] = x return true } private fun applyTrack( s: MutableSnapshot, id: Long, r: JsonObject, updated: Long, maps: Map>, ): Boolean { val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId") val i = s.tracks.indexOf(id) val old = s.tracks.getOrNull(i) if (old != null && updated <= old.updatedAt) return false val x = DbTrack( id = id, libraryId = intNullable(r, "libraryId")?.toLong(), mediaId = intNullable(r, "mediaId")?.toLong(), mangaId = manga, syncId = intNullable(r, "syncId"), title = nullableString(r, "title"), lastChapterRead = intNumberNullable(r, "lastChapterRead"), totalChapter = intNullable(r, "totalChapter"), score = intNumberNullable(r, "score"), status = trackStatus(r), startedReadingDate = longNullable(r, "startedReadingDate"), finishedReadingDate = longNullable(r, "finishedReadingDate"), trackingUrl = nullableString(r, "trackingUrl"), itemType = itemType(r, "itemType"), updatedAt = updated, ) if (old == null) s.tracks += x else s.tracks[i] = x return true } private fun applyHistory( s: MutableSnapshot, id: Long, r: JsonObject, updated: Long, maps: Map>, ): Boolean { val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId") val chapter = ref(s, r, maps, SyncPaths.KIND_CHAPTER, "chapterClientId") require(s.mangas.has(manga) && s.chapters.row(chapter)?.mangaId == manga) { "Unresolved history reference" } val i = s.histories.indexOf(id) val old = s.histories.getOrNull(i) if (old != null && updated <= old.updatedAt) return false val x = DbHistory( id = id, mangaId = manga, chapterId = chapter, itemType = itemType(r, "itemType"), date = longNullable(r, "date")?.toString(), updatedAt = updated, readingTimeSeconds = intNullable(r, "readingTimeSeconds"), ) if (old == null) s.histories += x else s.histories[i] = x return true } private fun applyUpdate( s: MutableSnapshot, id: Long, r: JsonObject, updated: Long, maps: Map>, ): Boolean { val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId") val i = s.updates.indexOf(id) val old = s.updates.getOrNull(i) if (old != null && updated <= old.updatedAt) return false val chapterName = nullableString(r, "chapterName") val kept = old?.chapterId?.takeIf { old.mangaId == manga && s.chapters.row(it)?.mangaId == manga } val chapters = if (chapterName == null) emptyList() else s.chapterByName[manga to chapterName] val x = DbUpdate( id = id, mangaId = manga, chapterId = kept ?: chapters.singleOrNull()?.let { s.chapters[it].id }, chapterName = chapterName, date = longNullable(r, "date")?.toString(), updatedAt = updated, ) if (old == null) s.updates += x else s.updates[i] = x return true } private fun acceptRemapKind(data: JsonObject, k: Int, key: String) { (data[key] as? JsonObject)?.forEach { (from, v) -> val old = from.toLongOrNull()?.also { require(it in 1..MAX_SAFE) } ?: error("Invalid remap id") val canonical = safeId(v) val ks = k.toString() val fromOwner = owners[ks]?.get(old) val toOwner = owners[ks]?.get(canonical) // Two local rows for one server title (e.g. duplicate manga with the same source+link): // the server dedups // onto the other row's id. Stealing it would merge unrelated local identities, and // failing would block every // future sync, so keep both bindings; the duplicate's own id just stays unknown to the // server. if (fromOwner != null && toOwner != null && fromOwner != toOwner) return@forEach val owner = fromOwner ?: toOwner if (owner == null) { val previous = pendingAliases.getOrPut(ks) { mutableMapOf() }.put(old, canonical) if (previous != canonical) { previous?.let { pendingByCanonical[ks]?.get(it)?.remove(old) } pendingByCanonical .getOrPut(ks) { mutableMapOf() } .getOrPut(canonical) { linkedSetOf() } += old } } else { val b = bindings.getValue(ks).getValue(owner) if (canonical != b.canonical) { b.aliases += b.canonical b.retired += b.canonical b.aliases.remove(canonical) b.retired.remove(canonical) b.canonical = canonical own(ks, canonical, owner) } if (old != b.canonical) { b.aliases += old b.retired += old own(ks, old, owner) } } } } private fun wireKey(k: Int) = when (k) { SyncPaths.KIND_CATEGORY -> "categories" SyncPaths.KIND_MANGA -> "manga" SyncPaths.KIND_CHAPTER -> "chapters" SyncPaths.KIND_TRACK -> "tracks" SyncPaths.KIND_HISTORY -> "histories" SyncPaths.KIND_UPDATE -> "updates" else -> error("Unsupported kind") } private fun kindForKey(s: String) = when (s) { "categories" -> SyncPaths.KIND_CATEGORY "manga" -> SyncPaths.KIND_MANGA "chapters" -> SyncPaths.KIND_CHAPTER "tracks" -> SyncPaths.KIND_TRACK "histories" -> SyncPaths.KIND_HISTORY "updates" -> SyncPaths.KIND_UPDATE else -> null } private fun type(t: DbItemType) = t.name.uppercase() private fun status(s: DbStatus) = when (s) { DbStatus.Ongoing -> "ONGOING" DbStatus.Completed -> "COMPLETED" DbStatus.Canceled -> "CANCELED" DbStatus.Unknown, DbStatus.Licensed, DbStatus.Upcoming -> "UNKNOWN" DbStatus.OnHiatus -> "ON_HIATUS" DbStatus.PublishingFinished -> "PUBLISHING_FINISHED" } private fun itemType(o: JsonObject, k: String) = enumValue(str(o, k)) private fun status(o: JsonObject, previous: DbStatus? = null): DbStatus { val incoming = when (str(o, "status")) { "ONGOING" -> DbStatus.Ongoing "COMPLETED" -> DbStatus.Completed "CANCELED" -> DbStatus.Canceled "UNKNOWN" -> DbStatus.Unknown "ON_HIATUS" -> DbStatus.OnHiatus "PUBLISHING_FINISHED" -> DbStatus.PublishingFinished else -> error("Invalid manga status") } // UNKNOWN is also our downgrade for statuses this server cannot represent. return if ( incoming == DbStatus.Unknown && (previous == DbStatus.Licensed || previous == DbStatus.Upcoming) ) previous else incoming } private fun trackStatus(o: JsonObject) = when (str(o, "status")) { "READING" -> DbTrackStatus.Reading "COMPLETED" -> DbTrackStatus.Completed "ON_HOLD" -> DbTrackStatus.OnHold "DROPPED" -> DbTrackStatus.Dropped "PLAN_TO_READ" -> DbTrackStatus.PlanToRead "RE_READING" -> DbTrackStatus.ReReading "WATCHING" -> DbTrackStatus.Watching "PLAN_TO_WATCH" -> DbTrackStatus.PlanToWatch "RE_WATCHING" -> DbTrackStatus.ReWatching else -> error("Invalid track status") } private inline fun > enumValue(v: String) = enumValues().firstOrNull { it.name.uppercase() == v } ?: error("Invalid enum value") private fun safeId(v: JsonElement?): Long { val n = longValue(requireNotNull(v)) require(n in 1..MAX_SAFE) { "Invalid clientId" } return n } private fun longValue(v: JsonElement): Long { val p = v as? JsonPrimitive ?: error("Expected number") require(!p.isString && p.booleanOrNull == null) { "Expected number" } val d = p.content.toDoubleOrNull() ?: error("Invalid number") require( d.isFinite() && d % 1.0 == 0.0 && d >= Long.MIN_VALUE.toDouble() && d <= Long.MAX_VALUE.toDouble() ) { "Expected integral number" } return d.toLong() } private fun long(o: JsonObject, k: String, default: Long? = null) = o[k]?.let(::longValue) ?: default ?: error("Missing $k") private fun longNullable(o: JsonObject, k: String) = o[k]?.takeUnless { it is JsonNull }?.let(::longValue) private fun intNullable(o: JsonObject, k: String) = longNullable(o, k)?.also { require(it in Int.MIN_VALUE..Int.MAX_VALUE) }?.toInt() private fun bool(o: JsonObject, k: String, d: Boolean) = o[k]?.let { (it as? JsonPrimitive)?.booleanOrNull ?: error("Invalid $k") } ?: d private fun boolNullable(o: JsonObject, k: String) = o[k] ?.takeUnless { it is JsonNull } ?.let { (it as? JsonPrimitive)?.booleanOrNull ?: error("Invalid $k") } private fun str(o: JsonObject, k: String) = ((o[k] as? JsonPrimitive)?.takeIf { it.isString }?.content) ?: error("Missing or invalid $k") private fun nullableString(o: JsonObject, k: String) = o[k] ?.takeUnless { it is JsonNull } ?.let { (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content ?: error("Invalid $k") } private fun hash(s: String): Long { var h = -3750763034362895579L for (b in s.encodeToByteArray()) { h = (h xor (b.toLong() and 255)) * 1099511628211L } return (h and MAX_SAFE).coerceAtLeast(1) } private fun unsafeDownload(s: MutableSnapshot, k: Int, id: Long): Boolean { fun active(chapter: Long) = s.downloadByChapter[chapter].any { s.downloads[it].let { d -> d.isStartDownload == true && d.isDownload != true } } return when (k) { SyncPaths.KIND_MANGA -> s.chapterByManga[id].any { active(s.chapters[it].id) } SyncPaths.KIND_CHAPTER -> active(id) else -> false } } private fun remoteLocal(k: Int, id: Long) = ownerForRemote(k, id)?.first?.toLong() private fun MutableSnapshot.delete(k: Int, id: Long) { val chapterRows = if (k == SyncPaths.KIND_MANGA) chapterByManga[id] else emptyList() val affectedChapters = when (k) { SyncPaths.KIND_MANGA -> chapterRows.mapTo(linkedSetOf()) { chapters[it].id } SyncPaths.KIND_CHAPTER -> setOf(id) else -> emptySet() } affectedChapters.forEach { c -> downloadByChapter[c].forEach { removedDownloads += downloads[it].id } } when (k) { SyncPaths.KIND_CATEGORY -> { categories.killId(id) mangas.liveIndices().forEach { i -> val m = mangas[i] mangas[i] = m.copy(categories = m.categories?.filterNot { it == id }) } } SyncPaths.KIND_MANGA -> { val cs = affectedChapters cs.forEach { rotate(SyncPaths.KIND_CHAPTER, it) } trackByManga[id].forEach { rotate(SyncPaths.KIND_TRACK, tracks[it].id) } historyByManga[id].forEach { rotate(SyncPaths.KIND_HISTORY, histories[it].id) } updateByManga[id].forEach { rotate(SyncPaths.KIND_UPDATE, updates[it].id) } mangas.killId(id) chapterRows.forEach(chapters::kill) (cs.flatMap { historyByChapter[it] } + historyByManga[id]).forEach(histories::kill) trackByManga[id].forEach(tracks::kill) updateByManga[id].forEach(updates::kill) cs.forEach { c -> downloadByChapter[c].forEach(downloads::kill) pageCacheByChapter[c].forEach(pageCache::kill) } removedMangas += id removedChapters += cs settingsDirty = true } SyncPaths.KIND_CHAPTER -> { historyByChapter[id].forEach { rotate(SyncPaths.KIND_HISTORY, histories[it].id) } chapters.killId(id) historyByChapter[id].forEach(histories::kill) updateByChapter[id].forEach { i -> updates[i] = updates[i].copy(chapterId = null) } downloadByChapter[id].forEach(downloads::kill) pageCacheByChapter[id].forEach(pageCache::kill) removedChapters += id settingsDirty = true } SyncPaths.KIND_TRACK -> tracks.killId(id) SyncPaths.KIND_HISTORY -> histories.killId(id) SyncPaths.KIND_UPDATE -> updates.killId(id) } } private fun ownerForRemote(kind: Int, remote: Long): Pair? { val ks = kind.toString() val local = owners[ks]?.get(remote) ?: return null return local to bindings.getValue(ks).getValue(local) } private fun validateOwnership(entries: Map) { val owner = mutableMapOf() entries.forEach { (local, b) -> (listOf(b.canonical) + b.aliases).forEach { id -> val old = owner.put(id, local) require(old == null || old == local) { "Remote mapping id collision" } } } } private fun validatePage(page: MangayomiPage) { for (k in SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE) { val field = wireKey(k) val raw = page.data[field] ?: continue val array = raw as? JsonArray ?: error("Invalid $field array") array.forEach { element -> val row = element as? JsonObject ?: error("Invalid $field row") safeId(row["clientId"]) long(row, "updatedAt") fun requiredString(key: String) { str(row, key) } fun requiredId(key: String) { safeId(row[key]) } fun nullableStringField(key: String) { nullableString(row, key) } fun nullableBool(key: String) { boolNullable(row, key) } fun nullableNumber(key: String) { longNullable(row, key) } when (k) { SyncPaths.KIND_CATEGORY -> { requiredString("name") itemType(row, "forItemType") intNullable(row, "pos") nullableBool("hide") nullableBool("shouldUpdate") } SyncPaths.KIND_MANGA -> { itemType(row, "itemType") nullableStringField("source") nullableStringField("link") nullableStringField("name") nullableStringField("imageUrl") nullableStringField("description") nullableStringField("author") nullableStringField("artist") nullableStringField("lang") nullableStringField("customCoverFromTracker") nullableNumber("sourceId") nullableNumber("lastUpdate") nullableNumber("dateAdded") nullableNumber("lastRead") intNullable(row, "smartUpdateDays") status(row) row["favorite"]?.let { bool(row, "favorite", false) } row["isLocalArchive"]?.let { bool(row, "isLocalArchive", false) } row["genre"]?.let { v -> (v as? JsonArray ?: error("Invalid genre array")).forEach { require((it as? JsonPrimitive)?.isString == true) { "Invalid genre" } } } row["categoryClientIds"]?.let { v -> (v as? JsonArray ?: error("Invalid categoryClientIds")).forEach( ::safeId ) } } SyncPaths.KIND_CHAPTER -> { requiredId("mangaClientId") nullableStringField("name") nullableStringField("url") nullableStringField("scanlator") nullableStringField("thumbnailUrl") nullableStringField("description") nullableStringField("lastPageRead") nullableNumber("dateUpload") nullableNumber("downloadSize") nullableNumber("duration") nullableBool("isFiller") nullableBool("isRead") nullableBool("isBookmarked") } SyncPaths.KIND_TRACK -> { requiredId("mangaClientId") itemType(row, "itemType") trackStatus(row) nullableNumber("syncId") nullableNumber("mediaId") nullableNumber("libraryId") nullableStringField("title") intNumberNullable(row, "lastChapterRead") intNullable(row, "totalChapter") intNumberNullable(row, "score") nullableNumber("startedReadingDate") nullableNumber("finishedReadingDate") nullableStringField("trackingUrl") } SyncPaths.KIND_HISTORY -> { requiredId("mangaClientId") requiredId("chapterClientId") itemType(row, "itemType") nullableNumber("date") intNullable(row, "readingTimeSeconds") } SyncPaths.KIND_UPDATE -> { requiredId("mangaClientId") nullableStringField("chapterName") nullableNumber("date") } } } } validateRemapFields(page.data) (page.data["tombstones"] ?: page.data["deleted"])?.let { raw -> val obj = raw as? JsonObject ?: error("Invalid tombstones") obj.forEach { (key, ids) -> require(kindForKey(key) != null) (ids as? JsonArray ?: error("Invalid tombstones array")).forEach(::safeId) } } } private fun intNumberNullable(o: JsonObject, k: String): Int? = o[k] ?.takeUnless { it is JsonNull } ?.let { val p = it as? JsonPrimitive ?: error("Unsupported $k value") require(!p.isString) { "Unsupported $k value" } val d = p.content.toDoubleOrNull() ?: error("Unsupported $k value") require( d.isFinite() && d % 1.0 == 0.0 && d >= Int.MIN_VALUE && d <= Int.MAX_VALUE ) { "Unsupported fractional/out-of-range $k" } d.toInt() } private fun resolveReference( s: MutableSnapshot, k: Int, remote: Long, maps: Map>, ): Long? { val local = maps[k]?.get(remote) ?: ownerForRemote(k, remote)?.first?.toLong() ?: return null return if (hasLocalEntity(s, k, local)) local else null } private fun newLocalIdentity(s: MutableSnapshot, k: Int): Long { val table = s.table(k) val bound = bindings[k.toString()] var id = SyncIds.random() while (table.has(id) || bound?.containsKey(id.toString()) == true) id = SyncIds.random() return id } private fun hasLocalEntity(s: MutableSnapshot, k: Int, id: Long) = s.table(k).has(id) private fun rowParentPendingDelete( s: MutableSnapshot, k: Int, row: JsonObject, maps: Map>, pending: Map>, ): Boolean { fun local(kind: Int, key: String): Long? { val remote = row[key]?.let(::safeId) ?: return null return maps[kind]?.get(remote) ?: ownerForRemote(kind, remote)?.first?.toLong() } val parent = if (k in SyncPaths.KIND_CHAPTER..SyncPaths.KIND_UPDATE) local(SyncPaths.KIND_MANGA, "mangaClientId") else null if ( parent != null && parent in pending[SyncPaths.KIND_MANGA].orEmpty() && !hasLocalEntity(s, SyncPaths.KIND_MANGA, parent) ) { return true } val chapter = if (k == SyncPaths.KIND_HISTORY) local(SyncPaths.KIND_CHAPTER, "chapterClientId") else null return chapter != null && chapter in pending[SyncPaths.KIND_CHAPTER].orEmpty() && !hasLocalEntity(s, SyncPaths.KIND_CHAPTER, chapter) } private fun deletionRecord(part: DbChangedPart): Pair? = runCatching { val o = json.parseToJsonElement(part.data).jsonObject if ( o["provider"]?.jsonPrimitive?.content != "mangayomi" || o["namespace"]?.jsonPrimitive?.content != namespaceKey ) return null val kind = o["kind"]?.jsonPrimitive?.int ?: return null val localPrimitive = o["localId"] as? JsonPrimitive ?: return null require(localPrimitive.isString) val local = localPrimitive.content.toLongOrNull() ?: return null if (kind !in SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE || local <= 0) return null kind to local } .getOrNull() private fun enabled(kind: Int, p: DbSyncPreference) = when (kind) { SyncPaths.KIND_HISTORY -> p.syncHistories SyncPaths.KIND_UPDATE -> p.syncUpdates else -> true } private fun validateUploadDependencies(s: YokanDatabaseSnapshot, rows: Map>) { val mangas = s.mangas.associateBy { it.id } val chapters = s.chapters.associateBy { it.id } val cats = s.categories.associateBy { it.id } s.chapters .filter { it.id in rows[SyncPaths.KIND_CHAPTER].orEmpty() } .forEach { require(it.mangaId != null && mangas.containsKey(it.mangaId)) { "Unresolved local chapter manga" } } s.tracks .filter { it.id in rows[SyncPaths.KIND_TRACK].orEmpty() } .forEach { require(it.mangaId != null && mangas.containsKey(it.mangaId)) { "Unresolved local track manga" } } s.histories .filter { it.id in rows[SyncPaths.KIND_HISTORY].orEmpty() } .forEach { require( it.mangaId != null && mangas.containsKey(it.mangaId) && it.chapterId != null && chapters[it.chapterId]?.mangaId == it.mangaId ) { "Unresolved local history reference" } } s.updates .filter { it.id in rows[SyncPaths.KIND_UPDATE].orEmpty() } .forEach { require(it.mangaId != null && mangas.containsKey(it.mangaId)) { "Unresolved local update manga" } } s.mangas .filter { it.id in rows[SyncPaths.KIND_MANGA].orEmpty() } .flatMap { it.categories.orEmpty() } .forEach { require(cats.containsKey(it)) { "Unresolved local category membership" } } } private fun normalizeServer(value: String): String { val s = value.trim().trimEnd('/') val match = Regex("^([A-Za-z][A-Za-z0-9+.-]*://)([^/]+)(.*)$").matchEntire(s) ?: return s return match.groupValues[1].lowercase() + match.groupValues[2].lowercase() + match.groupValues[3] } private fun validateRemapFields(data: JsonObject) { listOf("mangaClientIdRemap", "chapterClientIdRemap").forEach { key -> data[key]?.let { raw -> (raw as? JsonObject ?: error("Invalid $key")).forEach { (from, to) -> val id = from.toLongOrNull() ?: error("Invalid remap id") require(id in 1..MAX_SAFE) safeId(to) } } } } /** * A list with an id index and lazily built secondary indexes. Deletes are tombstoned until * [live], so positions stay stable. */ private class Table(initial: List, private val idOf: (T) -> Long?) { private val rows = initial.toMutableList() private val dead = HashSet() private val byId = HashMap().also { m -> rows.forEachIndexed { i, x -> idOf(x)?.let { m.getOrPut(it) { i } } } } private val indexes = ArrayList() // Buckets are a superset (a replaced row keeps its old bucket entry), so lookups re-check // liveness and the key. inner class Index(val keyOf: (T) -> Any?) { var buckets: HashMap>? = null operator fun get(key: Any?): List { val b = buckets ?: HashMap>().also { b -> rows.indices.forEach { i -> if (i !in dead) b.getOrPut(keyOf(rows[i])) { ArrayList(1) } += i } buckets = b } return b[key].orEmpty().filter { it !in dead && keyOf(rows[it]) == key }.distinct() } fun note(i: Int) { buckets?.getOrPut(keyOf(rows[i])) { ArrayList(1) }?.add(i) } } fun index(keyOf: (T) -> Any?) = Index(keyOf).also { indexes += it } operator fun get(i: Int) = rows[i] fun getOrNull(i: Int) = rows.getOrNull(i) fun indexOf(id: Long) = byId[id] ?: -1 fun has(id: Long) = id in byId fun row(id: Long) = byId[id]?.let { rows[it] } operator fun plusAssign(x: T) { rows += x val i = rows.lastIndex idOf(x)?.let { byId.getOrPut(it) { i } } indexes.forEach { it.note(i) } } operator fun set(i: Int, x: T) { val old = rows[i] rows[i] = x indexes.forEach { if (it.keyOf(old) != it.keyOf(x)) it.note(i) } } fun kill(i: Int) { if (dead.add(i)) idOf(rows[i])?.let { if (byId[it] == i) byId.remove(it) } } fun killId(id: Long) { byId[id]?.let(::kill) } fun liveIndices() = rows.indices.filter { it !in dead } fun live(): List = if (dead.isEmpty()) rows else rows.filterIndexed { i, _ -> i !in dead } } private class MutableSnapshot(private val original: YokanDatabaseSnapshot) { val categories = Table(original.categories) { it.id } val mangas = Table(original.mangas) { it.id } val chapters = Table(original.chapters) { it.id } val tracks = Table(original.tracks) { it.id } val histories = Table(original.histories) { it.id } val updates = Table(original.updates) { it.id } val downloads = Table(original.downloads) { it.id } val pageCache = Table(original.pageCache) { null } val mangaNatural = mangas.index { Triple(it.link, it.source, it.itemType) } val chapterByManga = chapters.index { it.mangaId } val chapterByUrl = chapters.index { it.mangaId to it.url } val chapterByName = chapters.index { it.mangaId to it.name } val trackByManga = tracks.index { it.mangaId } val trackBySync = tracks.index { it.mangaId to it.syncId } val historyByManga = histories.index { it.mangaId } val historyByChapter = histories.index { it.chapterId } val updateByManga = updates.index { it.mangaId } val updateByChapter = updates.index { it.chapterId } val updateByName = updates.index { it.mangaId to it.chapterName } val downloadByChapter = downloads.index { it.chapterId } val pageCacheByChapter = pageCache.index { it.chapterId } // Settings cleanup only drops entries by id, so one pass over the accumulated ids in // build() equals a pass per delete. var settingsDirty = false val removedDownloads = HashSet() val removedMangas = HashSet() val removedChapters = HashSet() fun table(k: Int): Table<*> = when (k) { SyncPaths.KIND_CATEGORY -> categories SyncPaths.KIND_MANGA -> mangas SyncPaths.KIND_CHAPTER -> chapters SyncPaths.KIND_TRACK -> tracks SyncPaths.KIND_HISTORY -> histories else -> updates } fun build(): YokanDatabaseSnapshot { val st = original.settings val settings = if (!settingsDirty) st else st.copy( downloadQueueOrder = st.downloadQueueOrder.filterNot { it in removedDownloads }, sortChapterList = st.sortChapterList?.filterNot { it.mangaId in removedMangas }, chapterFilterDownloadedList = st.chapterFilterDownloadedList?.filterNot { it.mangaId in removedMangas }, chapterFilterUnreadList = st.chapterFilterUnreadList?.filterNot { it.mangaId in removedMangas }, chapterFilterBookmarkedList = st.chapterFilterBookmarkedList?.filterNot { it.mangaId in removedMangas }, personalReaderModeList = st.personalReaderModeList?.filterNot { it.mangaId in removedMangas }, personalPageModeList = st.personalPageModeList?.filterNot { it.mangaId in removedMangas }, filterScanlatorList = st.filterScanlatorList?.filterNot { it.mangaId in removedMangas }, autoScrollPages = st.autoScrollPages?.filterNot { it.mangaId in removedMangas }, titleMetadata = st.titleMetadata?.filterNot { it.mangaId in removedMangas }, chapterPageIndexList = st.chapterPageIndexList?.filterNot { it.chapterId in removedChapters }, ) return original.copy( settings = settings, mangas = mangas.live(), chapters = chapters.live(), categories = categories.live(), histories = histories.live(), updates = updates.live(), tracks = tracks.live(), downloads = downloads.live(), pageCache = pageCache.live(), ) } } companion object { private const val MAX_SAFE = 9_007_199_254_740_991L /** * String `.max()` limits per entity from the server's zod schemas; keep in step with * lib/validation/sync.ts. */ private val SERVER_STRING_LIMITS: Map> = mapOf( SyncPaths.KIND_CATEGORY to mapOf("name" to 200), SyncPaths.KIND_MANGA to mapOf( "source" to 200, "link" to 2000, "name" to 500, "imageUrl" to 2000, "description" to 10_000, "author" to 500, "artist" to 500, "lang" to 20, "customCoverFromTracker" to 2000, ), SyncPaths.KIND_CHAPTER to mapOf( "name" to 500, "url" to 2000, "scanlator" to 200, "thumbnailUrl" to 2000, "description" to 5000, "lastPageRead" to 50, ), SyncPaths.KIND_TRACK to mapOf("title" to 500, "trackingUrl" to 2000), SyncPaths.KIND_HISTORY to emptyMap(), SyncPaths.KIND_UPDATE to mapOf("chapterName" to 500), ) } }