MangayomiSyncMapper.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/MangayomiSyncMapper.kt
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.database.DbCategory4import eu.friedcutlet.yokan.database.DbChangedPart5import eu.friedcutlet.yokan.database.DbChapter6import eu.friedcutlet.yokan.database.DbChapterPageUrls7import eu.friedcutlet.yokan.database.DbFetchType8import eu.friedcutlet.yokan.database.DbHistory9import eu.friedcutlet.yokan.database.DbItemType10import eu.friedcutlet.yokan.database.DbManga11import eu.friedcutlet.yokan.database.DbStatus12import eu.friedcutlet.yokan.database.DbSyncPreference13import eu.friedcutlet.yokan.database.DbTrack14import eu.friedcutlet.yokan.database.DbTrackStatus15import eu.friedcutlet.yokan.database.DbUpdate16import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot17import eu.friedcutlet.yokan.database.effectiveFiller18import eu.friedcutlet.yokan.database.sync.SyncIds19import eu.friedcutlet.yokan.database.sync.SyncPaths20import kotlinx.serialization.json.Json21import kotlinx.serialization.json.JsonArray22import kotlinx.serialization.json.JsonElement23import kotlinx.serialization.json.JsonNull24import kotlinx.serialization.json.JsonObject25import kotlinx.serialization.json.JsonObjectBuilder26import kotlinx.serialization.json.JsonPrimitive27import kotlinx.serialization.json.booleanOrNull28import kotlinx.serialization.json.buildJsonObject29import kotlinx.serialization.json.int30import kotlinx.serialization.json.intOrNull31import kotlinx.serialization.json.jsonArray32import kotlinx.serialization.json.jsonObject33import kotlinx.serialization.json.jsonPrimitive34import kotlinx.serialization.json.put3536internal data class MangayomiNamespace(val server: String, val accountId: String)3738internal data class MangayomiBatch(39 val kind: Int?,40 val localIds: List<Long>,41 val deletions: List<DbChangedPart> = emptyList(),42)4344internal data class MangayomiPage(45 val data: JsonObject,46 val cursors: Map<String, String?>,47 val sessionToken: String?,48 val hasMore: Boolean,49 val syncedAt: Long?,50)5152internal data class MangayomiMerge(53 val snapshot: YokanDatabaseSnapshot,54 val downloadedChanges: Int,55 val settingsChanged: Boolean,56)5758/** Pure conversion between Yokan snapshots and Mangayomi's independent clientId wire protocol. */59internal class MangayomiSyncMapper(60 mappingsJson: String?,61 private val namespace: MangayomiNamespace,62) {63 private val json = Json {64 ignoreUnknownKeys = true65 explicitNulls = false66 }67 private val namespaceKey = "${normalizeServer(namespace.server)}\n${namespace.accountId}"68 private val all = linkedMapOf<String, MutableMap<String, MutableMap<String, Binding>>>()69 private val bindings = linkedMapOf<String, MutableMap<String, Binding>>()70 // Every canonical/alias id of the active namespace -> owning local key, per kind. Binding id71 // sets only grow, so entries are never removed.72 private val owners = mutableMapOf<String, MutableMap<Long, String>>()73 private val pendingAliases = mutableMapOf<String, MutableMap<Long, Long>>()74 private val pendingByCanonical = mutableMapOf<String, MutableMap<Long, MutableSet<Long>>>()7576 private class Binding(77 var canonical: Long,78 val aliases: MutableSet<Long> = linkedSetOf(),79 val retired: MutableSet<Long> = linkedSetOf(),80 val deletionTargets: MutableMap<String, Long> = linkedMapOf(),81 )8283 init {84 if (mappingsJson != null) {85 val root = json.parseToJsonElement(mappingsJson).jsonObject86 val version = root["version"] as? JsonPrimitive87 require(version != null && !version.isString && version.intOrNull == 1) {88 "Unsupported Mangayomi mapping version"89 }90 val namespaces = root["namespaces"]?.jsonObject ?: error("Missing mapping namespaces")91 namespaces.forEach { (key, value) ->92 require(key.isNotBlank()) { "Invalid mapping namespace" }93 val namespaceBindings = linkedMapOf<String, MutableMap<String, Binding>>()94 value.jsonObject.forEach { (kind, rows) ->95 require(96 kind.toIntOrNull()?.let {97 it in SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE98 } == true99 ) {100 "Invalid mapping kind"101 }102 val entities = linkedMapOf<String, Binding>()103 rows.jsonObject.forEach { (local, raw) ->104 val localId = local.toLongOrNull()105 require(localId != null && localId > 0 && local == localId.toString()) {106 "Invalid local mapping id"107 }108 val obj = raw.jsonObject109 val canonical = safeId(obj["canonical"])110 val aliasesElement = obj["aliases"]111 require(aliasesElement == null || aliasesElement is JsonArray) {112 "Invalid mapping aliases"113 }114 val aliasList = aliasesElement.orEmpty().map(::safeId)115 require(aliasList.size == aliasList.toSet().size) {116 "Duplicate mapping alias"117 }118 val aliases = aliasList.toMutableSet()119 val retiredElement = obj["retired"]120 require(retiredElement == null || retiredElement is JsonArray) {121 "Invalid retired ids"122 }123 val retiredList = retiredElement.orEmpty().map(::safeId)124 require(retiredList.size == retiredList.toSet().size) {125 "Duplicate retired id"126 }127 val retired = retiredList.toMutableSet()128 require(canonical !in aliases) { "Canonical id repeated as alias" }129 require(canonical !in retired && retired.all { it in aliases }) {130 "Invalid retired mapping ids"131 }132 val targetsObj =133 obj["deletionTargets"]?.jsonObject ?: JsonObject(emptyMap())134 val targets = targetsObj.mapValues { safeId(it.value) }.toMutableMap()135 require(targets.values.all { it == canonical || it in aliases }) {136 "Invalid recreation deletion target"137 }138 entities[local] = Binding(canonical, aliases, retired, targets)139 }140 validateOwnership(entities)141 namespaceBindings[kind] = entities142 }143 all[key] = namespaceBindings144 }145 all[namespaceKey]?.forEach { (kind, rows) ->146 bindings[kind] = rows147 rows.forEach { (local, b) ->148 own(kind, b.canonical, local)149 b.aliases.forEach { own(kind, it, local) }150 }151 }152 }153 }154155 fun mappingsJson(): String =156 buildJsonObject {157 put("version", 1)158 put(159 "namespaces",160 buildJsonObject {161 val namespaces = all.toMutableMap()162 namespaces[namespaceKey] = bindings163 namespaces.entries164 .sortedBy { it.key }165 .forEach { (ns, kinds) ->166 put(167 ns,168 buildJsonObject {169 kinds.entries170 .sortedBy { it.key }171 .forEach { (kind, entries) ->172 put(173 kind,174 buildJsonObject {175 entries.entries176 .sortedBy { it.key }177 .forEach { (local, b) ->178 put(179 local,180 buildJsonObject {181 put(182 "canonical",183 b.canonical,184 )185 put(186 "aliases",187 JsonArray(188 b.aliases189 .sorted()190 .map(191 ::192 JsonPrimitive193 )194 ),195 )196 if (b.retired.isNotEmpty())197 put(198 "retired",199 JsonArray(200 b.retired201 .sorted()202 .map(203 ::204 JsonPrimitive205 )206 ),207 )208 if (209 b.deletionTargets210 .isNotEmpty()211 )212 put(213 "deletionTargets",214 buildJsonObject {215 b216 .deletionTargets217 .entries218 .sortedBy {219 it.key220 }221 .forEach {222 (223 record,224 id)225 ->226 put(227 record,228 id,229 )230 }231 },232 )233 },234 )235 }236 },237 )238 }239 },240 )241 }242 },243 )244 }245 .toString()246247 fun prepare(248 snapshot: YokanDatabaseSnapshot,249 preference: DbSyncPreference,250 ): List<MangayomiBatch> {251 val rows =252 linkedMapOf(253 SyncPaths.KIND_CATEGORY to snapshot.categories.map { it.id },254 SyncPaths.KIND_MANGA to snapshot.mangas.map { it.id },255 SyncPaths.KIND_CHAPTER to snapshot.chapters.map { it.id },256 SyncPaths.KIND_TRACK to snapshot.tracks.map { it.id },257 SyncPaths.KIND_HISTORY to258 if (preference.syncHistories) snapshot.histories.map { it.id } else emptyList(),259 SyncPaths.KIND_UPDATE to260 if (preference.syncUpdates) snapshot.updates.map { it.id } else emptyList(),261 )262 ensureRecreationTransitions(snapshot.changedParts, snapshot, preference)263 rows.forEach { (kind, ids) -> ids.forEach { id -> remoteId(kind, id) } }264 val rowSets = rows.mapValues { it.value.toHashSet() }265 validateUploadDependencies(snapshot, rowSets)266 val order = rows.keys.toList()267 val deleteGroups = linkedMapOf<Int, MutableList<DbChangedPart>>()268 snapshot.changedParts.forEach { part ->269 deletionRecord(part)?.let { (kind, local) ->270 if (271 kind in order &&272 bindings[kind.toString()]?.containsKey(local.toString()) == true &&273 (local !in rowSets.getValue(kind) ||274 deletionTarget(kind, local, part) != null) &&275 (kind != SyncPaths.KIND_HISTORY || preference.syncHistories) &&276 (kind != SyncPaths.KIND_UPDATE || preference.syncUpdates)277 )278 deleteGroups.getOrPut(kind) { mutableListOf() } += part279 }280 }281 val batches = mutableListOf<MangayomiBatch>()282 if (deleteGroups.isNotEmpty()) {283 deleteGroups.forEach { (kind, parts) ->284 val chunks = parts.distinct().chunked(5000)285 chunks.forEachIndexed { index, chunk ->286 val target = batches.size.also { batches += MangayomiBatch(null, emptyList()) }287 batches[target] =288 batches[target].copy(deletions = batches[target].deletions + chunk)289 }290 }291 }292 for (kind in order) for (chunk in rows.getValue(kind).chunked(5000)) batches +=293 MangayomiBatch(kind, chunk)294 if (batches.isEmpty()) batches += MangayomiBatch(null, emptyList())295 return batches296 }297298 fun encode(captured: YokanDatabaseSnapshot, batch: MangayomiBatch): JsonObject =299 buildJsonObject {300 batch.kind?.let { kind ->301 val kindName = wireKey(kind)302 val byId = rowsById(captured, kind)303 val array =304 batch.localIds.map { id ->305 encodeRow(306 kind,307 byId[id] ?: error("Captured entity $kind/$id no longer exists"),308 )309 }310 put(kindName, JsonArray(array))311 }312 if (batch.deletions.isNotEmpty()) {313 val deleted = linkedMapOf<String, MutableList<Long>>()314 batch.deletions.forEach { part ->315 val o = json.parseToJsonElement(part.data).jsonObject316 val kind = o.getValue("kind").jsonPrimitive.int317 val local = o.getValue("localId").jsonPrimitive.content.toLong()318 deleted.getOrPut(wireKey(kind)) { mutableListOf() } +=319 deletionTarget(kind, local, part) ?: mappedId(kind, local)320 }321 put(322 "deleted",323 buildJsonObject {324 deleted.forEach { (k, ids) ->325 put(k, JsonArray(ids.distinct().map(::JsonPrimitive)))326 }327 },328 )329 }330 }331332 fun decodePage(body: String): MangayomiPage {333 val root = json.parseToJsonElement(body).jsonObject334 val data =335 root["data"]?.let { raw ->336 val nested = raw as? JsonObject ?: error("Invalid response data")337 val wireKeys =338 (SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE).map(::wireKey) +339 listOf(340 "tombstones",341 "deleted",342 "mangaClientIdRemap",343 "chapterClientIdRemap",344 )345 JsonObject(nested + root.filterKeys { it in wireKeys && it !in nested })346 } ?: root347 val cursorsRaw = root["cursors"] ?: data["cursors"]348 val cursorObj =349 cursorsRaw?.let { it as? JsonObject ?: error("Invalid cursors") }350 ?: JsonObject(emptyMap())351 val cursors =352 cursorObj.mapValues { (_, v) ->353 if (v is JsonNull) null354 else355 (v as? JsonPrimitive)?.takeIf { it.isString }?.content356 ?: error("Invalid cursor")357 }358 val moreElement = root["hasMore"] ?: data["hasMore"] ?: error("Missing hasMore")359 val hasMore = moreElement.jsonPrimitive.booleanOrNull ?: error("Invalid hasMore")360 val syncedElement = root["syncedAt"] ?: data["syncedAt"] ?: error("Missing syncedAt")361 val syncedAt =362 if (syncedElement is JsonNull && hasMore) null363 else longValue(syncedElement).also { require(it >= 0) { "Invalid syncedAt" } }364 val tokenElement = root["sessionToken"] ?: data["sessionToken"]365 val token =366 tokenElement?.let {367 if (it is JsonNull) null368 else369 (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content370 ?: error("Invalid sessionToken")371 }372 return MangayomiPage(data, cursors, token, hasMore, syncedAt)373 }374375 fun acceptRemaps(page: MangayomiPage) {376 validatePage(page)377 acceptRemapKind(page.data, SyncPaths.KIND_MANGA, "mangaClientIdRemap")378 acceptRemapKind(page.data, SyncPaths.KIND_CHAPTER, "chapterClientIdRemap")379 }380381 fun merge(382 current: YokanDatabaseSnapshot,383 pages: List<MangayomiPage>,384 preference: DbSyncPreference,385 ): MangayomiMerge {386 pages.forEach(::validatePage)387 ensureRecreationTransitions(current.changedParts, current, preference)388 val rows = mutableMapOf<Int, MutableList<JsonObject>>()389 val tombstones = mutableMapOf<Int, MutableSet<Long>>()390 pages.forEach { page ->391 acceptRemaps(page)392 listOf(393 SyncPaths.KIND_CATEGORY,394 SyncPaths.KIND_MANGA,395 SyncPaths.KIND_CHAPTER,396 SyncPaths.KIND_TRACK,397 SyncPaths.KIND_HISTORY,398 SyncPaths.KIND_UPDATE,399 )400 .forEach { k ->401 if (402 k == SyncPaths.KIND_HISTORY && !preference.syncHistories ||403 k == SyncPaths.KIND_UPDATE && !preference.syncUpdates404 )405 return@forEach406 (page.data[wireKey(k)] as? JsonArray)?.forEach {407 rows.getOrPut(k) { mutableListOf() } += it.jsonObject408 }409 }410 val deleted =411 page.data["tombstones"] as? JsonObject ?: page.data["deleted"] as? JsonObject412 deleted?.forEach { (key, ids) ->413 kindForKey(key)?.let { k ->414 if (415 (k != SyncPaths.KIND_HISTORY || preference.syncHistories) &&416 (k != SyncPaths.KIND_UPDATE || preference.syncUpdates)417 )418 (ids as JsonArray).forEach {419 tombstones.getOrPut(k) { mutableSetOf() } += safeId(it)420 }421 }422 }423 }424 val result = MutableSnapshot(current)425 val queuedDeleteLocals =426 current.changedParts427 .mapNotNull(::deletionRecord)428 .groupBy({ it.first }, { it.second })429 .mapValues { it.value.toSet() }430 val localByRemote = mutableMapOf<Int, MutableMap<Long, Long>>()431 val claimedNaturalLocals = mutableMapOf<Int, MutableSet<Long>>()432 // Identity is established for all rows before LWW, allowing stale rows/remaps to433 // canonicalize references.434 for (k in435 listOf(436 SyncPaths.KIND_CATEGORY,437 SyncPaths.KIND_MANGA,438 SyncPaths.KIND_CHAPTER,439 SyncPaths.KIND_TRACK,440 SyncPaths.KIND_HISTORY,441 SyncPaths.KIND_UPDATE,442 )) {443 rows[k].orEmpty().forEach { row ->444 val remote = safeId(row["clientId"])445 val local =446 localByRemote[k]?.get(remote)447 ?: resolveLocal(result, k, remote, row, claimedNaturalLocals[k].orEmpty())448 bind(k, local, remote)449 localByRemote.getOrPut(k) { mutableMapOf() }[remote] = local450 if (k == SyncPaths.KIND_HISTORY || k == SyncPaths.KIND_UPDATE)451 claimedNaturalLocals.getOrPut(k) { mutableSetOf() } += local452 }453 }454 val count = intArrayOf(0)455 for (k in456 listOf(457 SyncPaths.KIND_CATEGORY,458 SyncPaths.KIND_MANGA,459 SyncPaths.KIND_CHAPTER,460 SyncPaths.KIND_TRACK,461 SyncPaths.KIND_HISTORY,462 SyncPaths.KIND_UPDATE,463 )) {464 rows[k].orEmpty().forEach { row ->465 val local = localByRemote[k]?.get(safeId(row["clientId"]))466 if (467 local != null &&468 local in queuedDeleteLocals[k].orEmpty() &&469 !hasLocalEntity(result, k, local)470 )471 return@forEach472 if (473 k != SyncPaths.KIND_MANGA &&474 rowParentPendingDelete(result, k, row, localByRemote, queuedDeleteLocals)475 )476 return@forEach477 if (applyRow(result, k, row, localByRemote, queuedDeleteLocals)) count[0]++478 }479 }480 tombstones.forEach { (kind, ids) ->481 val recreationTargets =482 bindings[kind.toString()]483 ?.values484 ?.flatMapTo(hashSetOf()) { it.deletionTargets.values }485 .orEmpty()486 ids.forEach { remote ->487 if (remote in recreationTargets) return@forEach488 val owner = ownerForRemote(kind, remote)489 val local = owner?.takeIf { remote == it.second.canonical }?.first?.toLong()490 if (local == null) return@forEach491 require(!unsafeDownload(result, kind, local)) {492 "Cannot delete entity with active download"493 }494 rotate(kind, local)495 result.delete(kind, local)496 }497 }498 return MangayomiMerge(result.build(), count[0], false)499 }500501 private fun encodeRow(k: Int, value: Any): JsonObject {502 val row =503 when (k) {504 SyncPaths.KIND_CATEGORY -> encodeCategory(value as DbCategory)505 SyncPaths.KIND_MANGA -> encodeManga(requireNotNull(value as? DbManga))506 SyncPaths.KIND_CHAPTER -> encodeChapter(requireNotNull(value as? DbChapter))507 SyncPaths.KIND_TRACK -> encodeTrack(value as DbTrack)508 SyncPaths.KIND_HISTORY -> encodeHistory(value as DbHistory)509 else -> encodeUpdate(value as DbUpdate)510 }511 return withinServerLimits(k, row)512 }513514 private fun clientId(kind: Int, local: Long?): JsonElement =515 local?.let { JsonPrimitive(mappedId(kind, it)) } ?: JsonNull516517 private fun millis(v: String?): JsonElement =518 v?.let { (it.toLongOrNull() ?: parseInstantMillis(it))?.let(::JsonPrimitive) } ?: JsonNull519520 private fun encodeCategory(x: DbCategory) = buildJsonObject {521 put("clientId", clientId(SyncPaths.KIND_CATEGORY, x.id))522 put("name", x.name)523 put("forItemType", x.forItemType.name.uppercase())524 put("pos", x.position?.let(::JsonPrimitive) ?: JsonNull)525 put("hide", x.hidden ?: false)526 put("shouldUpdate", x.shouldUpdate ?: true)527 put("updatedAt", x.updatedAt)528 }529530 private fun encodeManga(x: DbManga) = buildJsonObject {531 put("clientId", clientId(SyncPaths.KIND_MANGA, x.id))532 nullable("source", x.source)533 nullable("sourceId", x.sourceId)534 nullable("link", x.link)535 put("itemType", type(x.itemType))536 nullable("name", x.name)537 nullable("imageUrl", x.imageUrl)538 nullable("description", x.description)539 nullable("author", x.author)540 nullable("artist", x.artist)541 put("status", status(x.status))542 put("genre", JsonArray((x.genre ?: emptyList()).map(::JsonPrimitive)))543 nullable("lang", x.lang)544 nullable("lastUpdate", x.lastUpdate)545 put("favorite", x.favorite)546 nullable("dateAdded", x.dateAdded)547 put("lastRead", x.lastRead)548 put("isLocalArchive", x.isLocalArchive)549 nullable("customCoverFromTracker", x.customCoverFromTracker)550 nullable("smartUpdateDays", x.smartUpdateDays)551 put(552 "categoryClientIds",553 JsonArray((x.categories ?: emptyList()).map { clientId(SyncPaths.KIND_CATEGORY, it) }),554 )555 put("updatedAt", x.updatedAt)556 }557558 private fun encodeChapter(x: DbChapter) = buildJsonObject {559 put("clientId", clientId(SyncPaths.KIND_CHAPTER, x.id))560 put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId))561 nullable("name", x.name)562 nullable("url", x.url)563 put("scanlator", x.scanlator)564 put("dateUpload", millis(x.dateUpload))565 put("isFiller", x.effectiveFiller)566 nullable("thumbnailUrl", x.thumbnailUrl)567 nullable("description", x.description)568 put("downloadSize", JsonNull)569 nullable("duration", x.duration?.toLongOrNull())570 put("isRead", x.isRead)571 put("isBookmarked", x.isBookmarked)572 put("lastPageRead", x.lastPageRead)573 put("updatedAt", x.updatedAt)574 }575576 private fun encodeTrack(x: DbTrack) = buildJsonObject {577 put("clientId", clientId(SyncPaths.KIND_TRACK, x.id))578 put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId))579 nullable("syncId", x.syncId)580 nullable("mediaId", x.mediaId)581 nullable("libraryId", x.libraryId)582 nullable("title", x.title)583 nullable("lastChapterRead", x.lastChapterRead)584 nullable("totalChapter", x.totalChapter)585 nullable("score", x.score)586 put("status", x.status.name.replace(Regex("([a-z])([A-Z])"), "$1_$2").uppercase())587 nullable("startedReadingDate", x.startedReadingDate)588 nullable("finishedReadingDate", x.finishedReadingDate)589 nullable("trackingUrl", x.trackingUrl)590 put("itemType", type(x.itemType))591 put("updatedAt", x.updatedAt)592 }593594 private fun encodeHistory(x: DbHistory) = buildJsonObject {595 put("clientId", clientId(SyncPaths.KIND_HISTORY, x.id))596 put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId))597 put("chapterClientId", clientId(SyncPaths.KIND_CHAPTER, x.chapterId))598 put("itemType", type(x.itemType))599 put("date", millis(x.date))600 nullable("readingTimeSeconds", x.readingTimeSeconds ?: 0)601 put("updatedAt", x.updatedAt)602 }603604 private fun encodeUpdate(x: DbUpdate) = buildJsonObject {605 put("clientId", clientId(SyncPaths.KIND_UPDATE, x.id))606 put("mangaClientId", clientId(SyncPaths.KIND_MANGA, x.mangaId))607 nullable("chapterName", x.chapterName)608 put("date", millis(x.date))609 put("updatedAt", x.updatedAt)610 }611612 /**613 * The server rejects a whole request (HTTP 400) when any field exceeds its schema, and real614 * libraries have longer descriptions/authors than it allows. Clip to its limits615 * (mangayomi-sync-server lib/validation/sync.ts): only the server's copy is shortened; local616 * rows keep full text because equal-timestamp pulls never replace them.617 */618 private fun withinServerLimits(k: Int, row: JsonObject): JsonObject {619 val limits = SERVER_STRING_LIMITS.getValue(k)620 return JsonObject(621 row.mapValues { (key, value) ->622 val max = limits[key]623 when {624 key == "trackingUrl" &&625 value is JsonPrimitive &&626 value.isString &&627 value.content.isNotEmpty() &&628 !value.content.startsWith("http://") &&629 !value.content.startsWith("https://") -> JsonNull630 max != null &&631 value is JsonPrimitive &&632 value.isString &&633 value.content.length > max -> JsonPrimitive(clip(value.content, max))634 key == "genre" && value is JsonArray ->635 JsonArray(636 value.map { g ->637 if (g is JsonPrimitive && g.content.length > 100)638 JsonPrimitive(clip(g.content, 100))639 else g640 }641 )642 key == "categoryClientIds" && value is JsonArray && value.size > 200 ->643 JsonArray(value.take(200))644 else -> value645 }646 }647 )648 }649650 // Counts UTF-16 units like JavaScript's string length; never splits a surrogate pair.651 private fun clip(s: String, max: Int): String =652 s.take(if (s[max - 1].isHighSurrogate()) max - 1 else max)653654 private fun JsonObjectBuilder.nullable(key: String, v: String?) {655 put(key, v?.let(::JsonPrimitive) ?: JsonNull)656 }657658 private fun JsonObjectBuilder.nullable(key: String, v: Number?) {659 put(key, v?.let(::JsonPrimitive) ?: JsonNull)660 }661662 // asReversed keeps the first row for a duplicated id, like firstOrNull did.663 private fun rowsById(s: YokanDatabaseSnapshot, k: Int): Map<Long, Any> =664 when (k) {665 SyncPaths.KIND_CATEGORY -> s.categories.asReversed().associateBy { it.id }666 SyncPaths.KIND_MANGA -> s.mangas.asReversed().associateBy { it.id }667 SyncPaths.KIND_CHAPTER -> s.chapters.asReversed().associateBy { it.id }668 SyncPaths.KIND_TRACK -> s.tracks.asReversed().associateBy { it.id }669 SyncPaths.KIND_HISTORY -> s.histories.asReversed().associateBy { it.id }670 else -> s.updates.asReversed().associateBy { it.id }671 }672673 private fun own(kind: String, id: Long, local: String) {674 val owner = owners.getOrPut(kind) { mutableMapOf() }.getOrPut(id) { local }675 require(owner == local) { "Remote mapping id collision" }676 }677678 private fun remoteId(k: Int, local: Long): Long {679 require(local > 0)680 val ks = k.toString()681 val map = bindings.getOrPut(ks) { linkedMapOf() }682 val key = local.toString()683 map[key]?.let {684 return it.canonical685 }686 val used = owners[ks].orEmpty()687 var candidate = hash("$namespaceKey|$k|$local")688 while (candidate in used || candidate <= 0) candidate =689 if (candidate == MAX_SAFE) 1 else candidate + 1690 map[key] = Binding(candidate)691 own(ks, candidate, key)692 return candidate693 }694695 private fun mappedId(k: Int, local: Long): Long =696 bindings[k.toString()]?.get(local.toString())?.canonical697 ?: error("Missing prepared mapping for kind $k local id $local")698699 private fun recordKey(part: DbChangedPart): String =700 buildJsonObject {701 put("id", part.id)702 put("actionType", part.actionType.name)703 put("isarId", part.isarId?.let(::JsonPrimitive) ?: JsonNull)704 put("clientDate", part.clientDate)705 put("data", part.data)706 }707 .toString()708709 private fun deletionTarget(kind: Int, local: Long, part: DbChangedPart): Long? =710 bindings[kind.toString()]?.get(local.toString())?.deletionTargets?.get(recordKey(part))711712 private fun ensureRecreationTransitions(713 parts: List<DbChangedPart>,714 snapshot: YokanDatabaseSnapshot,715 preference: DbSyncPreference,716 ) {717 val records =718 parts.mapNotNull { part ->719 deletionRecord(part)?.let { (kind, local) -> Triple(kind, local, part) }720 }721 if (records.isEmpty()) return722 val ids = entityIds(snapshot)723 val groups =724 records725 .filter { (kind, local, _) ->726 enabled(kind, preference) && local in ids.getValue(kind)727 }728 .groupBy({ it.first to it.second }, { it.third })729 val children by lazy { Children(snapshot) }730 groups.forEach { (identity, records) ->731 val (kind, local) = identity732 val binding = bindings[kind.toString()]?.get(local.toString()) ?: return@forEach733 val known = records.mapNotNull { binding.deletionTargets[recordKey(it)] }.distinct()734 require(known.size <= 1) { "Conflicting recreation deletion targets" }735 val target =736 known.singleOrNull()737 ?: binding.canonical.also {738 rotate(kind, local)739 rotateDependents(children, kind, local)740 }741 records.forEach {742 val key = recordKey(it)743 if (key !in binding.deletionTargets) binding.deletionTargets[key] = target744 }745 }746 }747748 // The server cascades a manga delete to its chapters/tracks/histories/updates and a chapter749 // delete to its histories.750 // Surviving children must leave those old IDs too, or the cascade tombstones delete them on the751 // next pull.752 private class Children(s: YokanDatabaseSnapshot) {753 val byManga =754 listOf(755 SyncPaths.KIND_CHAPTER to s.chapters.groupBy({ it.mangaId }, { it.id }),756 SyncPaths.KIND_TRACK to s.tracks.groupBy({ it.mangaId }, { it.id }),757 SyncPaths.KIND_HISTORY to s.histories.groupBy({ it.mangaId }, { it.id }),758 SyncPaths.KIND_UPDATE to s.updates.groupBy({ it.mangaId }, { it.id }),759 )760 val historiesByChapter = s.histories.groupBy({ it.chapterId }, { it.id })761 }762763 private fun rotateDependents(c: Children, k: Int, id: Long) {764 when (k) {765 SyncPaths.KIND_MANGA ->766 c.byManga.forEach { (kind, byParent) ->767 byParent[id].orEmpty().forEach { rotate(kind, it) }768 }769 SyncPaths.KIND_CHAPTER ->770 c.historiesByChapter[id].orEmpty().forEach { rotate(SyncPaths.KIND_HISTORY, it) }771 }772 }773774 private fun entityIds(s: YokanDatabaseSnapshot): Map<Int, Set<Long>> =775 mapOf(776 SyncPaths.KIND_CATEGORY to s.categories.mapTo(hashSetOf()) { it.id },777 SyncPaths.KIND_MANGA to s.mangas.mapTo(hashSetOf()) { it.id },778 SyncPaths.KIND_CHAPTER to s.chapters.mapTo(hashSetOf()) { it.id },779 SyncPaths.KIND_TRACK to s.tracks.mapTo(hashSetOf()) { it.id },780 SyncPaths.KIND_HISTORY to s.histories.mapTo(hashSetOf()) { it.id },781 SyncPaths.KIND_UPDATE to s.updates.mapTo(hashSetOf()) { it.id },782 )783784 private fun rotate(k: Int, local: Long) {785 val ks = k.toString()786 val key = local.toString()787 val b = bindings[ks]?.get(key) ?: return788 b.aliases += b.canonical789 b.retired += b.canonical790 var id = hash("$namespaceKey|$k|$local|${SyncIds.random()}")791 val used = owners[ks].orEmpty()792 while (id in used) id = if (id == MAX_SAFE) 1 else id + 1793 b.canonical = id794 own(ks, id, key)795 }796797 private fun bind(k: Int, local: Long, remote: Long) {798 val ks = k.toString()799 val map = bindings.getOrPut(ks) { linkedMapOf() }800 val key = local.toString()801 val owner = owners[ks]?.get(remote)802 require(owner == null || owner == key) {803 "Remote id $remote already belongs to another local row"804 }805 val b = map.getOrPut(key) { Binding(remote) }806 when {807 remote == b.canonical -> Unit808 remote in b.aliases -> Unit // A retired/legacy alias never becomes canonical again.809 else -> {810 require(owner == null)811 b.aliases += b.canonical812 b.retired += b.canonical813 b.canonical = remote814 b.aliases += remote815 b.aliases.remove(remote)816 b.retired.remove(remote)817 }818 }819 own(ks, remote, key)820 pendingByCanonical[ks]?.get(remote)?.forEach { old ->821 b.aliases += old822 b.retired += old823 own(ks, old, key)824 }825 }826827 private fun resolveLocal(828 s: MutableSnapshot,829 k: Int,830 remote: Long,831 r: JsonObject,832 claimed: Set<Long>,833 ): Long {834 ownerForRemote(k, remote)?.let {835 return it.first.toLong()836 }837 val matches =838 when (k) {839 SyncPaths.KIND_CATEGORY -> emptyList()840 SyncPaths.KIND_MANGA -> {841 val link = nullableString(r, "link")842 val source = nullableString(r, "source")843 if (link.isNullOrBlank() || source.isNullOrBlank()) emptyList()844 else845 s.mangaNatural[Triple(link, source, itemType(r, "itemType"))].map {846 s.mangas[it].id847 }848 }849 SyncPaths.KIND_CHAPTER -> {850 val url = nullableString(r, "url")851 val parent = remoteLocal(SyncPaths.KIND_MANGA, long(r, "mangaClientId"))852 if (url.isNullOrBlank() || parent == null || !s.mangas.has(parent)) emptyList()853 else s.chapterByUrl[parent to url].map { s.chapters[it].id }854 }855 SyncPaths.KIND_TRACK -> {856 val parent = remoteLocal(SyncPaths.KIND_MANGA, long(r, "mangaClientId"))857 val tracker = intNullable(r, "syncId")858 if (parent == null || tracker == null || !s.mangas.has(parent)) emptyList()859 else s.trackBySync[parent to tracker].map { s.tracks[it].id }860 }861 SyncPaths.KIND_HISTORY ->862 s.historyByChapter[863 remoteLocal(SyncPaths.KIND_CHAPTER, long(r, "chapterClientId"))]864 .map { s.histories[it].id }865 else -> {866 val parent = remoteLocal(SyncPaths.KIND_MANGA, long(r, "mangaClientId"))867 val name = nullableString(r, "chapterName")868 if (parent == null || name.isNullOrBlank() || !s.mangas.has(parent)) emptyList()869 else s.updateByName[parent to name].map { s.updates[it].id }870 }871 }872 val available =873 if (k == SyncPaths.KIND_HISTORY || k == SyncPaths.KIND_UPDATE)874 matches.filterNot { it in claimed }875 else matches876 require(available.size <= 1) { "Ambiguous Mangayomi natural identity" }877 return available.singleOrNull() ?: newLocalIdentity(s, k)878 }879880 private fun applyRow(881 s: MutableSnapshot,882 k: Int,883 r: JsonObject,884 maps: Map<Int, Map<Long, Long>>,885 pendingDeletes: Map<Int, Set<Long>>,886 ): Boolean {887 val remote = safeId(r["clientId"])888 val id = maps[k]?.get(remote) ?: error("Missing mapped identity")889 val updated = long(r, "updatedAt")890 require(updated >= 0)891 return when (k) {892 SyncPaths.KIND_CATEGORY -> applyCategory(s, id, r, updated)893 SyncPaths.KIND_MANGA -> applyManga(s, id, r, updated, maps, pendingDeletes)894 SyncPaths.KIND_CHAPTER -> applyChapter(s, id, r, updated, maps)895 SyncPaths.KIND_TRACK -> applyTrack(s, id, r, updated, maps)896 SyncPaths.KIND_HISTORY -> applyHistory(s, id, r, updated, maps)897 else -> applyUpdate(s, id, r, updated, maps)898 }899 }900901 private fun ref(902 s: MutableSnapshot,903 r: JsonObject,904 maps: Map<Int, Map<Long, Long>>,905 kind: Int,906 key: String,907 ): Long {908 val rid = safeId(r[key])909 return resolveReference(s, kind, rid, maps) ?: error("Unresolved $key reference")910 }911912 private fun applyCategory(s: MutableSnapshot, id: Long, r: JsonObject, updated: Long): Boolean {913 val i = s.categories.indexOf(id)914 val old = s.categories.getOrNull(i)915 if (old != null && updated <= old.updatedAt) return false916 val x =917 DbCategory(918 id,919 str(r, "name"),920 itemType(r, "forItemType"),921 intNullable(r, "pos"),922 boolNullable(r, "hide"),923 boolNullable(r, "shouldUpdate"),924 updated,925 )926 if (old == null) s.categories += x else s.categories[i] = x927 return true928 }929930 private fun applyManga(931 s: MutableSnapshot,932 id: Long,933 r: JsonObject,934 updated: Long,935 maps: Map<Int, Map<Long, Long>>,936 pendingDeletes: Map<Int, Set<Long>>,937 ): Boolean {938 val i = s.mangas.indexOf(id)939 val old = s.mangas.getOrNull(i)940 if (old != null && updated <= old.updatedAt) return false941 val catIds =942 r["categoryClientIds"]943 ?.jsonArray944 ?.mapNotNull { e ->945 val remoteCat = safeId(e)946 resolveReference(s, SyncPaths.KIND_CATEGORY, remoteCat, maps)947 ?: run {948 val owner =949 ownerForRemote(SyncPaths.KIND_CATEGORY, remoteCat)?.first?.toLong()950 if (951 owner != null &&952 owner in pendingDeletes[SyncPaths.KIND_CATEGORY].orEmpty() &&953 !hasLocalEntity(s, SyncPaths.KIND_CATEGORY, owner)954 ) {955 null956 } else {957 error("Unresolved category membership")958 }959 }960 }961 ?.takeIf { r.containsKey("categoryClientIds") }962 val x =963 DbManga(964 id = id,965 name = nullableString(r, "name"),966 link = nullableString(r, "link"),967 imageUrl = nullableString(r, "imageUrl"),968 description = nullableString(r, "description"),969 author = nullableString(r, "author"),970 artist = nullableString(r, "artist"),971 status = status(r, old?.status),972 itemType = itemType(r, "itemType"),973 genre = r["genre"]?.jsonArray?.map { it.jsonPrimitive.content },974 favorite = bool(r, "favorite", false),975 source = nullableString(r, "source"),976 lang = nullableString(r, "lang"),977 dateAdded = longNullable(r, "dateAdded"),978 lastUpdate = longNullable(r, "lastUpdate"),979 lastRead = longNullable(r, "lastRead") ?: old?.lastRead ?: 0,980 categories = catIds ?: old?.categories,981 isLocalArchive = bool(r, "isLocalArchive", false),982 customCoverImage = old?.customCoverImage,983 customCoverFromTracker = nullableString(r, "customCoverFromTracker"),984 smartUpdateDays = intNullable(r, "smartUpdateDays"),985 updatedAt = updated,986 sourceId = longNullable(r, "sourceId"),987 privateNote = old?.privateNote.orEmpty(),988 cast = old?.cast.orEmpty(),989 parentId = old?.parentId,990 fetchType = old?.fetchType ?: DbFetchType.Episodes,991 seasonNumber = old?.seasonNumber,992 )993 if (old == null) s.mangas += x else s.mangas[i] = x994 return true995 }996997 private fun applyChapter(998 s: MutableSnapshot,999 id: Long,1000 r: JsonObject,1001 updated: Long,1002 maps: Map<Int, Map<Long, Long>>,1003 ): Boolean {1004 val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId")1005 val i = s.chapters.indexOf(id)1006 val old = s.chapters.getOrNull(i)1007 if (old != null && updated <= old.updatedAt) return false1008 require(s.mangas.has(manga)) { "Unresolved manga reference" }1009 val x =1010 DbChapter(1011 id = id,1012 mangaId = manga,1013 name = nullableString(r, "name"),1014 url = nullableString(r, "url") ?: "",1015 dateUpload = longNullable(r, "dateUpload")?.toString() ?: "",1016 scanlator = nullableString(r, "scanlator") ?: "",1017 isBookmarked = bool(r, "isBookmarked", false),1018 isRead = bool(r, "isRead", false),1019 lastPageRead = nullableString(r, "lastPageRead") ?: "",1020 archivePath = old?.archivePath ?: "",1021 isFiller = bool(r, "isFiller", false),1022 thumbnailUrl = nullableString(r, "thumbnailUrl"),1023 description = nullableString(r, "description"),1024 downloadSize = old?.downloadSize,1025 duration = longNullable(r, "duration")?.toString(),1026 updatedAt = updated,1027 fetchedAt = old?.fetchedAt ?: 0,1028 number = old?.number,1029 season = old?.season,1030 numberingName = old?.numberingName,1031 fillerOverride = old?.fillerOverride,1032 )1033 if (old == null) s.chapters += x else s.chapters[i] = x1034 return true1035 }10361037 private fun applyTrack(1038 s: MutableSnapshot,1039 id: Long,1040 r: JsonObject,1041 updated: Long,1042 maps: Map<Int, Map<Long, Long>>,1043 ): Boolean {1044 val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId")1045 val i = s.tracks.indexOf(id)1046 val old = s.tracks.getOrNull(i)1047 if (old != null && updated <= old.updatedAt) return false1048 val x =1049 DbTrack(1050 id = id,1051 libraryId = intNullable(r, "libraryId")?.toLong(),1052 mediaId = intNullable(r, "mediaId")?.toLong(),1053 mangaId = manga,1054 syncId = intNullable(r, "syncId"),1055 title = nullableString(r, "title"),1056 lastChapterRead = intNumberNullable(r, "lastChapterRead"),1057 totalChapter = intNullable(r, "totalChapter"),1058 score = intNumberNullable(r, "score"),1059 status = trackStatus(r),1060 startedReadingDate = longNullable(r, "startedReadingDate"),1061 finishedReadingDate = longNullable(r, "finishedReadingDate"),1062 trackingUrl = nullableString(r, "trackingUrl"),1063 itemType = itemType(r, "itemType"),1064 updatedAt = updated,1065 )1066 if (old == null) s.tracks += x else s.tracks[i] = x1067 return true1068 }10691070 private fun applyHistory(1071 s: MutableSnapshot,1072 id: Long,1073 r: JsonObject,1074 updated: Long,1075 maps: Map<Int, Map<Long, Long>>,1076 ): Boolean {1077 val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId")1078 val chapter = ref(s, r, maps, SyncPaths.KIND_CHAPTER, "chapterClientId")1079 require(s.mangas.has(manga) && s.chapters.row(chapter)?.mangaId == manga) {1080 "Unresolved history reference"1081 }1082 val i = s.histories.indexOf(id)1083 val old = s.histories.getOrNull(i)1084 if (old != null && updated <= old.updatedAt) return false1085 val x =1086 DbHistory(1087 id = id,1088 mangaId = manga,1089 chapterId = chapter,1090 itemType = itemType(r, "itemType"),1091 date = longNullable(r, "date")?.toString(),1092 updatedAt = updated,1093 readingTimeSeconds = intNullable(r, "readingTimeSeconds"),1094 )1095 if (old == null) s.histories += x else s.histories[i] = x1096 return true1097 }10981099 private fun applyUpdate(1100 s: MutableSnapshot,1101 id: Long,1102 r: JsonObject,1103 updated: Long,1104 maps: Map<Int, Map<Long, Long>>,1105 ): Boolean {1106 val manga = ref(s, r, maps, SyncPaths.KIND_MANGA, "mangaClientId")1107 val i = s.updates.indexOf(id)1108 val old = s.updates.getOrNull(i)1109 if (old != null && updated <= old.updatedAt) return false1110 val chapterName = nullableString(r, "chapterName")1111 val kept =1112 old?.chapterId?.takeIf { old.mangaId == manga && s.chapters.row(it)?.mangaId == manga }1113 val chapters =1114 if (chapterName == null) emptyList() else s.chapterByName[manga to chapterName]1115 val x =1116 DbUpdate(1117 id = id,1118 mangaId = manga,1119 chapterId = kept ?: chapters.singleOrNull()?.let { s.chapters[it].id },1120 chapterName = chapterName,1121 date = longNullable(r, "date")?.toString(),1122 updatedAt = updated,1123 )1124 if (old == null) s.updates += x else s.updates[i] = x1125 return true1126 }11271128 private fun acceptRemapKind(data: JsonObject, k: Int, key: String) {1129 (data[key] as? JsonObject)?.forEach { (from, v) ->1130 val old =1131 from.toLongOrNull()?.also { require(it in 1..MAX_SAFE) }1132 ?: error("Invalid remap id")1133 val canonical = safeId(v)1134 val ks = k.toString()1135 val fromOwner = owners[ks]?.get(old)1136 val toOwner = owners[ks]?.get(canonical)1137 // Two local rows for one server title (e.g. duplicate manga with the same source+link):1138 // the server dedups1139 // onto the other row's id. Stealing it would merge unrelated local identities, and1140 // failing would block every1141 // future sync, so keep both bindings; the duplicate's own id just stays unknown to the1142 // server.1143 if (fromOwner != null && toOwner != null && fromOwner != toOwner) return@forEach1144 val owner = fromOwner ?: toOwner1145 if (owner == null) {1146 val previous = pendingAliases.getOrPut(ks) { mutableMapOf() }.put(old, canonical)1147 if (previous != canonical) {1148 previous?.let { pendingByCanonical[ks]?.get(it)?.remove(old) }1149 pendingByCanonical1150 .getOrPut(ks) { mutableMapOf() }1151 .getOrPut(canonical) { linkedSetOf() } += old1152 }1153 } else {1154 val b = bindings.getValue(ks).getValue(owner)1155 if (canonical != b.canonical) {1156 b.aliases += b.canonical1157 b.retired += b.canonical1158 b.aliases.remove(canonical)1159 b.retired.remove(canonical)1160 b.canonical = canonical1161 own(ks, canonical, owner)1162 }1163 if (old != b.canonical) {1164 b.aliases += old1165 b.retired += old1166 own(ks, old, owner)1167 }1168 }1169 }1170 }11711172 private fun wireKey(k: Int) =1173 when (k) {1174 SyncPaths.KIND_CATEGORY -> "categories"1175 SyncPaths.KIND_MANGA -> "manga"1176 SyncPaths.KIND_CHAPTER -> "chapters"1177 SyncPaths.KIND_TRACK -> "tracks"1178 SyncPaths.KIND_HISTORY -> "histories"1179 SyncPaths.KIND_UPDATE -> "updates"1180 else -> error("Unsupported kind")1181 }11821183 private fun kindForKey(s: String) =1184 when (s) {1185 "categories" -> SyncPaths.KIND_CATEGORY1186 "manga" -> SyncPaths.KIND_MANGA1187 "chapters" -> SyncPaths.KIND_CHAPTER1188 "tracks" -> SyncPaths.KIND_TRACK1189 "histories" -> SyncPaths.KIND_HISTORY1190 "updates" -> SyncPaths.KIND_UPDATE1191 else -> null1192 }11931194 private fun type(t: DbItemType) = t.name.uppercase()11951196 private fun status(s: DbStatus) =1197 when (s) {1198 DbStatus.Ongoing -> "ONGOING"1199 DbStatus.Completed -> "COMPLETED"1200 DbStatus.Canceled -> "CANCELED"1201 DbStatus.Unknown,1202 DbStatus.Licensed,1203 DbStatus.Upcoming -> "UNKNOWN"1204 DbStatus.OnHiatus -> "ON_HIATUS"1205 DbStatus.PublishingFinished -> "PUBLISHING_FINISHED"1206 }12071208 private fun itemType(o: JsonObject, k: String) = enumValue<DbItemType>(str(o, k))12091210 private fun status(o: JsonObject, previous: DbStatus? = null): DbStatus {1211 val incoming =1212 when (str(o, "status")) {1213 "ONGOING" -> DbStatus.Ongoing1214 "COMPLETED" -> DbStatus.Completed1215 "CANCELED" -> DbStatus.Canceled1216 "UNKNOWN" -> DbStatus.Unknown1217 "ON_HIATUS" -> DbStatus.OnHiatus1218 "PUBLISHING_FINISHED" -> DbStatus.PublishingFinished1219 else -> error("Invalid manga status")1220 }1221 // UNKNOWN is also our downgrade for statuses this server cannot represent.1222 return if (1223 incoming == DbStatus.Unknown &&1224 (previous == DbStatus.Licensed || previous == DbStatus.Upcoming)1225 )1226 previous1227 else incoming1228 }12291230 private fun trackStatus(o: JsonObject) =1231 when (str(o, "status")) {1232 "READING" -> DbTrackStatus.Reading1233 "COMPLETED" -> DbTrackStatus.Completed1234 "ON_HOLD" -> DbTrackStatus.OnHold1235 "DROPPED" -> DbTrackStatus.Dropped1236 "PLAN_TO_READ" -> DbTrackStatus.PlanToRead1237 "RE_READING" -> DbTrackStatus.ReReading1238 "WATCHING" -> DbTrackStatus.Watching1239 "PLAN_TO_WATCH" -> DbTrackStatus.PlanToWatch1240 "RE_WATCHING" -> DbTrackStatus.ReWatching1241 else -> error("Invalid track status")1242 }12431244 private inline fun <reified T : Enum<T>> enumValue(v: String) =1245 enumValues<T>().firstOrNull { it.name.uppercase() == v } ?: error("Invalid enum value")12461247 private fun safeId(v: JsonElement?): Long {1248 val n = longValue(requireNotNull(v))1249 require(n in 1..MAX_SAFE) { "Invalid clientId" }1250 return n1251 }12521253 private fun longValue(v: JsonElement): Long {1254 val p = v as? JsonPrimitive ?: error("Expected number")1255 require(!p.isString && p.booleanOrNull == null) { "Expected number" }1256 val d = p.content.toDoubleOrNull() ?: error("Invalid number")1257 require(1258 d.isFinite() &&1259 d % 1.0 == 0.0 &&1260 d >= Long.MIN_VALUE.toDouble() &&1261 d <= Long.MAX_VALUE.toDouble()1262 ) {1263 "Expected integral number"1264 }1265 return d.toLong()1266 }12671268 private fun long(o: JsonObject, k: String, default: Long? = null) =1269 o[k]?.let(::longValue) ?: default ?: error("Missing $k")12701271 private fun longNullable(o: JsonObject, k: String) =1272 o[k]?.takeUnless { it is JsonNull }?.let(::longValue)12731274 private fun intNullable(o: JsonObject, k: String) =1275 longNullable(o, k)?.also { require(it in Int.MIN_VALUE..Int.MAX_VALUE) }?.toInt()12761277 private fun bool(o: JsonObject, k: String, d: Boolean) =1278 o[k]?.let { (it as? JsonPrimitive)?.booleanOrNull ?: error("Invalid $k") } ?: d12791280 private fun boolNullable(o: JsonObject, k: String) =1281 o[k]1282 ?.takeUnless { it is JsonNull }1283 ?.let { (it as? JsonPrimitive)?.booleanOrNull ?: error("Invalid $k") }12841285 private fun str(o: JsonObject, k: String) =1286 ((o[k] as? JsonPrimitive)?.takeIf { it.isString }?.content)1287 ?: error("Missing or invalid $k")12881289 private fun nullableString(o: JsonObject, k: String) =1290 o[k]1291 ?.takeUnless { it is JsonNull }1292 ?.let {1293 (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content ?: error("Invalid $k")1294 }12951296 private fun hash(s: String): Long {1297 var h = -3750763034362895579L1298 for (b in s.encodeToByteArray()) {1299 h = (h xor (b.toLong() and 255)) * 1099511628211L1300 }1301 return (h and MAX_SAFE).coerceAtLeast(1)1302 }13031304 private fun unsafeDownload(s: MutableSnapshot, k: Int, id: Long): Boolean {1305 fun active(chapter: Long) =1306 s.downloadByChapter[chapter].any {1307 s.downloads[it].let { d -> d.isStartDownload == true && d.isDownload != true }1308 }1309 return when (k) {1310 SyncPaths.KIND_MANGA -> s.chapterByManga[id].any { active(s.chapters[it].id) }1311 SyncPaths.KIND_CHAPTER -> active(id)1312 else -> false1313 }1314 }13151316 private fun remoteLocal(k: Int, id: Long) = ownerForRemote(k, id)?.first?.toLong()13171318 private fun MutableSnapshot.delete(k: Int, id: Long) {1319 val chapterRows = if (k == SyncPaths.KIND_MANGA) chapterByManga[id] else emptyList()1320 val affectedChapters =1321 when (k) {1322 SyncPaths.KIND_MANGA -> chapterRows.mapTo(linkedSetOf()) { chapters[it].id }1323 SyncPaths.KIND_CHAPTER -> setOf(id)1324 else -> emptySet()1325 }1326 affectedChapters.forEach { c ->1327 downloadByChapter[c].forEach { removedDownloads += downloads[it].id }1328 }1329 when (k) {1330 SyncPaths.KIND_CATEGORY -> {1331 categories.killId(id)1332 mangas.liveIndices().forEach { i ->1333 val m = mangas[i]1334 mangas[i] = m.copy(categories = m.categories?.filterNot { it == id })1335 }1336 }1337 SyncPaths.KIND_MANGA -> {1338 val cs = affectedChapters1339 cs.forEach { rotate(SyncPaths.KIND_CHAPTER, it) }1340 trackByManga[id].forEach { rotate(SyncPaths.KIND_TRACK, tracks[it].id) }1341 historyByManga[id].forEach { rotate(SyncPaths.KIND_HISTORY, histories[it].id) }1342 updateByManga[id].forEach { rotate(SyncPaths.KIND_UPDATE, updates[it].id) }1343 mangas.killId(id)1344 chapterRows.forEach(chapters::kill)1345 (cs.flatMap { historyByChapter[it] } + historyByManga[id]).forEach(histories::kill)1346 trackByManga[id].forEach(tracks::kill)1347 updateByManga[id].forEach(updates::kill)1348 cs.forEach { c ->1349 downloadByChapter[c].forEach(downloads::kill)1350 pageCacheByChapter[c].forEach(pageCache::kill)1351 }1352 removedMangas += id1353 removedChapters += cs1354 settingsDirty = true1355 }1356 SyncPaths.KIND_CHAPTER -> {1357 historyByChapter[id].forEach { rotate(SyncPaths.KIND_HISTORY, histories[it].id) }1358 chapters.killId(id)1359 historyByChapter[id].forEach(histories::kill)1360 updateByChapter[id].forEach { i -> updates[i] = updates[i].copy(chapterId = null) }1361 downloadByChapter[id].forEach(downloads::kill)1362 pageCacheByChapter[id].forEach(pageCache::kill)1363 removedChapters += id1364 settingsDirty = true1365 }1366 SyncPaths.KIND_TRACK -> tracks.killId(id)1367 SyncPaths.KIND_HISTORY -> histories.killId(id)1368 SyncPaths.KIND_UPDATE -> updates.killId(id)1369 }1370 }13711372 private fun ownerForRemote(kind: Int, remote: Long): Pair<String, Binding>? {1373 val ks = kind.toString()1374 val local = owners[ks]?.get(remote) ?: return null1375 return local to bindings.getValue(ks).getValue(local)1376 }13771378 private fun validateOwnership(entries: Map<String, Binding>) {1379 val owner = mutableMapOf<Long, String>()1380 entries.forEach { (local, b) ->1381 (listOf(b.canonical) + b.aliases).forEach { id ->1382 val old = owner.put(id, local)1383 require(old == null || old == local) { "Remote mapping id collision" }1384 }1385 }1386 }13871388 private fun validatePage(page: MangayomiPage) {1389 for (k in SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE) {1390 val field = wireKey(k)1391 val raw = page.data[field] ?: continue1392 val array = raw as? JsonArray ?: error("Invalid $field array")1393 array.forEach { element ->1394 val row = element as? JsonObject ?: error("Invalid $field row")1395 safeId(row["clientId"])1396 long(row, "updatedAt")1397 fun requiredString(key: String) {1398 str(row, key)1399 }1400 fun requiredId(key: String) {1401 safeId(row[key])1402 }1403 fun nullableStringField(key: String) {1404 nullableString(row, key)1405 }1406 fun nullableBool(key: String) {1407 boolNullable(row, key)1408 }1409 fun nullableNumber(key: String) {1410 longNullable(row, key)1411 }1412 when (k) {1413 SyncPaths.KIND_CATEGORY -> {1414 requiredString("name")1415 itemType(row, "forItemType")1416 intNullable(row, "pos")1417 nullableBool("hide")1418 nullableBool("shouldUpdate")1419 }1420 SyncPaths.KIND_MANGA -> {1421 itemType(row, "itemType")1422 nullableStringField("source")1423 nullableStringField("link")1424 nullableStringField("name")1425 nullableStringField("imageUrl")1426 nullableStringField("description")1427 nullableStringField("author")1428 nullableStringField("artist")1429 nullableStringField("lang")1430 nullableStringField("customCoverFromTracker")1431 nullableNumber("sourceId")1432 nullableNumber("lastUpdate")1433 nullableNumber("dateAdded")1434 nullableNumber("lastRead")1435 intNullable(row, "smartUpdateDays")1436 status(row)1437 row["favorite"]?.let { bool(row, "favorite", false) }1438 row["isLocalArchive"]?.let { bool(row, "isLocalArchive", false) }1439 row["genre"]?.let { v ->1440 (v as? JsonArray ?: error("Invalid genre array")).forEach {1441 require((it as? JsonPrimitive)?.isString == true) {1442 "Invalid genre"1443 }1444 }1445 }1446 row["categoryClientIds"]?.let { v ->1447 (v as? JsonArray ?: error("Invalid categoryClientIds")).forEach(1448 ::safeId1449 )1450 }1451 }1452 SyncPaths.KIND_CHAPTER -> {1453 requiredId("mangaClientId")1454 nullableStringField("name")1455 nullableStringField("url")1456 nullableStringField("scanlator")1457 nullableStringField("thumbnailUrl")1458 nullableStringField("description")1459 nullableStringField("lastPageRead")1460 nullableNumber("dateUpload")1461 nullableNumber("downloadSize")1462 nullableNumber("duration")1463 nullableBool("isFiller")1464 nullableBool("isRead")1465 nullableBool("isBookmarked")1466 }1467 SyncPaths.KIND_TRACK -> {1468 requiredId("mangaClientId")1469 itemType(row, "itemType")1470 trackStatus(row)1471 nullableNumber("syncId")1472 nullableNumber("mediaId")1473 nullableNumber("libraryId")1474 nullableStringField("title")1475 intNumberNullable(row, "lastChapterRead")1476 intNullable(row, "totalChapter")1477 intNumberNullable(row, "score")1478 nullableNumber("startedReadingDate")1479 nullableNumber("finishedReadingDate")1480 nullableStringField("trackingUrl")1481 }1482 SyncPaths.KIND_HISTORY -> {1483 requiredId("mangaClientId")1484 requiredId("chapterClientId")1485 itemType(row, "itemType")1486 nullableNumber("date")1487 intNullable(row, "readingTimeSeconds")1488 }1489 SyncPaths.KIND_UPDATE -> {1490 requiredId("mangaClientId")1491 nullableStringField("chapterName")1492 nullableNumber("date")1493 }1494 }1495 }1496 }1497 validateRemapFields(page.data)1498 (page.data["tombstones"] ?: page.data["deleted"])?.let { raw ->1499 val obj = raw as? JsonObject ?: error("Invalid tombstones")1500 obj.forEach { (key, ids) ->1501 require(kindForKey(key) != null)1502 (ids as? JsonArray ?: error("Invalid tombstones array")).forEach(::safeId)1503 }1504 }1505 }15061507 private fun intNumberNullable(o: JsonObject, k: String): Int? =1508 o[k]1509 ?.takeUnless { it is JsonNull }1510 ?.let {1511 val p = it as? JsonPrimitive ?: error("Unsupported $k value")1512 require(!p.isString) { "Unsupported $k value" }1513 val d = p.content.toDoubleOrNull() ?: error("Unsupported $k value")1514 require(1515 d.isFinite() && d % 1.0 == 0.0 && d >= Int.MIN_VALUE && d <= Int.MAX_VALUE1516 ) {1517 "Unsupported fractional/out-of-range $k"1518 }1519 d.toInt()1520 }15211522 private fun resolveReference(1523 s: MutableSnapshot,1524 k: Int,1525 remote: Long,1526 maps: Map<Int, Map<Long, Long>>,1527 ): Long? {1528 val local =1529 maps[k]?.get(remote) ?: ownerForRemote(k, remote)?.first?.toLong() ?: return null1530 return if (hasLocalEntity(s, k, local)) local else null1531 }15321533 private fun newLocalIdentity(s: MutableSnapshot, k: Int): Long {1534 val table = s.table(k)1535 val bound = bindings[k.toString()]1536 var id = SyncIds.random()1537 while (table.has(id) || bound?.containsKey(id.toString()) == true) id = SyncIds.random()1538 return id1539 }15401541 private fun hasLocalEntity(s: MutableSnapshot, k: Int, id: Long) = s.table(k).has(id)15421543 private fun rowParentPendingDelete(1544 s: MutableSnapshot,1545 k: Int,1546 row: JsonObject,1547 maps: Map<Int, Map<Long, Long>>,1548 pending: Map<Int, Set<Long>>,1549 ): Boolean {1550 fun local(kind: Int, key: String): Long? {1551 val remote = row[key]?.let(::safeId) ?: return null1552 return maps[kind]?.get(remote) ?: ownerForRemote(kind, remote)?.first?.toLong()1553 }1554 val parent =1555 if (k in SyncPaths.KIND_CHAPTER..SyncPaths.KIND_UPDATE)1556 local(SyncPaths.KIND_MANGA, "mangaClientId")1557 else null1558 if (1559 parent != null &&1560 parent in pending[SyncPaths.KIND_MANGA].orEmpty() &&1561 !hasLocalEntity(s, SyncPaths.KIND_MANGA, parent)1562 ) {1563 return true1564 }1565 val chapter =1566 if (k == SyncPaths.KIND_HISTORY) local(SyncPaths.KIND_CHAPTER, "chapterClientId")1567 else null1568 return chapter != null &&1569 chapter in pending[SyncPaths.KIND_CHAPTER].orEmpty() &&1570 !hasLocalEntity(s, SyncPaths.KIND_CHAPTER, chapter)1571 }15721573 private fun deletionRecord(part: DbChangedPart): Pair<Int, Long>? =1574 runCatching {1575 val o = json.parseToJsonElement(part.data).jsonObject1576 if (1577 o["provider"]?.jsonPrimitive?.content != "mangayomi" ||1578 o["namespace"]?.jsonPrimitive?.content != namespaceKey1579 )1580 return null1581 val kind = o["kind"]?.jsonPrimitive?.int ?: return null1582 val localPrimitive = o["localId"] as? JsonPrimitive ?: return null1583 require(localPrimitive.isString)1584 val local = localPrimitive.content.toLongOrNull() ?: return null1585 if (kind !in SyncPaths.KIND_CATEGORY..SyncPaths.KIND_UPDATE || local <= 0)1586 return null1587 kind to local1588 }1589 .getOrNull()15901591 private fun enabled(kind: Int, p: DbSyncPreference) =1592 when (kind) {1593 SyncPaths.KIND_HISTORY -> p.syncHistories1594 SyncPaths.KIND_UPDATE -> p.syncUpdates1595 else -> true1596 }15971598 private fun validateUploadDependencies(s: YokanDatabaseSnapshot, rows: Map<Int, Set<Long>>) {1599 val mangas = s.mangas.associateBy { it.id }1600 val chapters = s.chapters.associateBy { it.id }1601 val cats = s.categories.associateBy { it.id }1602 s.chapters1603 .filter { it.id in rows[SyncPaths.KIND_CHAPTER].orEmpty() }1604 .forEach {1605 require(it.mangaId != null && mangas.containsKey(it.mangaId)) {1606 "Unresolved local chapter manga"1607 }1608 }1609 s.tracks1610 .filter { it.id in rows[SyncPaths.KIND_TRACK].orEmpty() }1611 .forEach {1612 require(it.mangaId != null && mangas.containsKey(it.mangaId)) {1613 "Unresolved local track manga"1614 }1615 }1616 s.histories1617 .filter { it.id in rows[SyncPaths.KIND_HISTORY].orEmpty() }1618 .forEach {1619 require(1620 it.mangaId != null &&1621 mangas.containsKey(it.mangaId) &&1622 it.chapterId != null &&1623 chapters[it.chapterId]?.mangaId == it.mangaId1624 ) {1625 "Unresolved local history reference"1626 }1627 }1628 s.updates1629 .filter { it.id in rows[SyncPaths.KIND_UPDATE].orEmpty() }1630 .forEach {1631 require(it.mangaId != null && mangas.containsKey(it.mangaId)) {1632 "Unresolved local update manga"1633 }1634 }1635 s.mangas1636 .filter { it.id in rows[SyncPaths.KIND_MANGA].orEmpty() }1637 .flatMap { it.categories.orEmpty() }1638 .forEach { require(cats.containsKey(it)) { "Unresolved local category membership" } }1639 }16401641 private fun normalizeServer(value: String): String {1642 val s = value.trim().trimEnd('/')1643 val match = Regex("^([A-Za-z][A-Za-z0-9+.-]*://)([^/]+)(.*)$").matchEntire(s) ?: return s1644 return match.groupValues[1].lowercase() +1645 match.groupValues[2].lowercase() +1646 match.groupValues[3]1647 }16481649 private fun validateRemapFields(data: JsonObject) {1650 listOf("mangaClientIdRemap", "chapterClientIdRemap").forEach { key ->1651 data[key]?.let { raw ->1652 (raw as? JsonObject ?: error("Invalid $key")).forEach { (from, to) ->1653 val id = from.toLongOrNull() ?: error("Invalid remap id")1654 require(id in 1..MAX_SAFE)1655 safeId(to)1656 }1657 }1658 }1659 }16601661 /**1662 * A list with an id index and lazily built secondary indexes. Deletes are tombstoned until1663 * [live], so positions stay stable.1664 */1665 private class Table<T>(initial: List<T>, private val idOf: (T) -> Long?) {1666 private val rows = initial.toMutableList()1667 private val dead = HashSet<Int>()1668 private val byId =1669 HashMap<Long, Int>().also { m ->1670 rows.forEachIndexed { i, x -> idOf(x)?.let { m.getOrPut(it) { i } } }1671 }1672 private val indexes = ArrayList<Index>()16731674 // Buckets are a superset (a replaced row keeps its old bucket entry), so lookups re-check1675 // liveness and the key.1676 inner class Index(val keyOf: (T) -> Any?) {1677 var buckets: HashMap<Any?, MutableList<Int>>? = null16781679 operator fun get(key: Any?): List<Int> {1680 val b =1681 buckets1682 ?: HashMap<Any?, MutableList<Int>>().also { b ->1683 rows.indices.forEach { i ->1684 if (i !in dead) b.getOrPut(keyOf(rows[i])) { ArrayList(1) } += i1685 }1686 buckets = b1687 }1688 return b[key].orEmpty().filter { it !in dead && keyOf(rows[it]) == key }.distinct()1689 }16901691 fun note(i: Int) {1692 buckets?.getOrPut(keyOf(rows[i])) { ArrayList(1) }?.add(i)1693 }1694 }16951696 fun index(keyOf: (T) -> Any?) = Index(keyOf).also { indexes += it }16971698 operator fun get(i: Int) = rows[i]16991700 fun getOrNull(i: Int) = rows.getOrNull(i)17011702 fun indexOf(id: Long) = byId[id] ?: -117031704 fun has(id: Long) = id in byId17051706 fun row(id: Long) = byId[id]?.let { rows[it] }17071708 operator fun plusAssign(x: T) {1709 rows += x1710 val i = rows.lastIndex1711 idOf(x)?.let { byId.getOrPut(it) { i } }1712 indexes.forEach { it.note(i) }1713 }17141715 operator fun set(i: Int, x: T) {1716 val old = rows[i]1717 rows[i] = x1718 indexes.forEach { if (it.keyOf(old) != it.keyOf(x)) it.note(i) }1719 }17201721 fun kill(i: Int) {1722 if (dead.add(i)) idOf(rows[i])?.let { if (byId[it] == i) byId.remove(it) }1723 }17241725 fun killId(id: Long) {1726 byId[id]?.let(::kill)1727 }17281729 fun liveIndices() = rows.indices.filter { it !in dead }17301731 fun live(): List<T> =1732 if (dead.isEmpty()) rows else rows.filterIndexed { i, _ -> i !in dead }1733 }17341735 private class MutableSnapshot(private val original: YokanDatabaseSnapshot) {1736 val categories = Table(original.categories) { it.id }1737 val mangas = Table(original.mangas) { it.id }1738 val chapters = Table(original.chapters) { it.id }1739 val tracks = Table(original.tracks) { it.id }1740 val histories = Table(original.histories) { it.id }1741 val updates = Table(original.updates) { it.id }1742 val downloads = Table(original.downloads) { it.id }1743 val pageCache = Table<DbChapterPageUrls>(original.pageCache) { null }1744 val mangaNatural = mangas.index { Triple(it.link, it.source, it.itemType) }1745 val chapterByManga = chapters.index { it.mangaId }1746 val chapterByUrl = chapters.index { it.mangaId to it.url }1747 val chapterByName = chapters.index { it.mangaId to it.name }1748 val trackByManga = tracks.index { it.mangaId }1749 val trackBySync = tracks.index { it.mangaId to it.syncId }1750 val historyByManga = histories.index { it.mangaId }1751 val historyByChapter = histories.index { it.chapterId }1752 val updateByManga = updates.index { it.mangaId }1753 val updateByChapter = updates.index { it.chapterId }1754 val updateByName = updates.index { it.mangaId to it.chapterName }1755 val downloadByChapter = downloads.index { it.chapterId }1756 val pageCacheByChapter = pageCache.index { it.chapterId }1757 // Settings cleanup only drops entries by id, so one pass over the accumulated ids in1758 // build() equals a pass per delete.1759 var settingsDirty = false1760 val removedDownloads = HashSet<Long>()1761 val removedMangas = HashSet<Long?>()1762 val removedChapters = HashSet<Long?>()17631764 fun table(k: Int): Table<*> =1765 when (k) {1766 SyncPaths.KIND_CATEGORY -> categories1767 SyncPaths.KIND_MANGA -> mangas1768 SyncPaths.KIND_CHAPTER -> chapters1769 SyncPaths.KIND_TRACK -> tracks1770 SyncPaths.KIND_HISTORY -> histories1771 else -> updates1772 }17731774 fun build(): YokanDatabaseSnapshot {1775 val st = original.settings1776 val settings =1777 if (!settingsDirty) st1778 else1779 st.copy(1780 downloadQueueOrder =1781 st.downloadQueueOrder.filterNot { it in removedDownloads },1782 sortChapterList =1783 st.sortChapterList?.filterNot { it.mangaId in removedMangas },1784 chapterFilterDownloadedList =1785 st.chapterFilterDownloadedList?.filterNot {1786 it.mangaId in removedMangas1787 },1788 chapterFilterUnreadList =1789 st.chapterFilterUnreadList?.filterNot { it.mangaId in removedMangas },1790 chapterFilterBookmarkedList =1791 st.chapterFilterBookmarkedList?.filterNot {1792 it.mangaId in removedMangas1793 },1794 personalReaderModeList =1795 st.personalReaderModeList?.filterNot { it.mangaId in removedMangas },1796 personalPageModeList =1797 st.personalPageModeList?.filterNot { it.mangaId in removedMangas },1798 filterScanlatorList =1799 st.filterScanlatorList?.filterNot { it.mangaId in removedMangas },1800 autoScrollPages =1801 st.autoScrollPages?.filterNot { it.mangaId in removedMangas },1802 titleMetadata = st.titleMetadata?.filterNot { it.mangaId in removedMangas },1803 chapterPageIndexList =1804 st.chapterPageIndexList?.filterNot { it.chapterId in removedChapters },1805 )1806 return original.copy(1807 settings = settings,1808 mangas = mangas.live(),1809 chapters = chapters.live(),1810 categories = categories.live(),1811 histories = histories.live(),1812 updates = updates.live(),1813 tracks = tracks.live(),1814 downloads = downloads.live(),1815 pageCache = pageCache.live(),1816 )1817 }1818 }18191820 companion object {1821 private const val MAX_SAFE = 9_007_199_254_740_991L18221823 /**1824 * String `.max()` limits per entity from the server's zod schemas; keep in step with1825 * lib/validation/sync.ts.1826 */1827 private val SERVER_STRING_LIMITS: Map<Int, Map<String, Int>> =1828 mapOf(1829 SyncPaths.KIND_CATEGORY to mapOf("name" to 200),1830 SyncPaths.KIND_MANGA to1831 mapOf(1832 "source" to 200,1833 "link" to 2000,1834 "name" to 500,1835 "imageUrl" to 2000,1836 "description" to 10_000,1837 "author" to 500,1838 "artist" to 500,1839 "lang" to 20,1840 "customCoverFromTracker" to 2000,1841 ),1842 SyncPaths.KIND_CHAPTER to1843 mapOf(1844 "name" to 500,1845 "url" to 2000,1846 "scanlator" to 200,1847 "thumbnailUrl" to 2000,1848 "description" to 5000,1849 "lastPageRead" to 50,1850 ),1851 SyncPaths.KIND_TRACK to mapOf("title" to 500, "trackingUrl" to 2000),1852 SyncPaths.KIND_HISTORY to emptyMap(),1853 SyncPaths.KIND_UPDATE to mapOf("chapterName" to 500),1854 )1855 }1856}1857