MangayomiNamespace.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/MangayomiNamespace.kt
1package eu.friedcutlet.yokan.database.sync23import eu.friedcutlet.yokan.database.DbActionType4import eu.friedcutlet.yokan.database.DbChangedPart5import eu.friedcutlet.yokan.database.DbSyncPreference6import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot7import kotlinx.serialization.json.Json8import kotlinx.serialization.json.JsonObject9import kotlinx.serialization.json.JsonPrimitive10import kotlinx.serialization.json.buildJsonObject11import kotlinx.serialization.json.jsonObject12import kotlinx.serialization.json.jsonPrimitive1314/** Canonical host/scheme while preserving path case; account identity is appended separately. */15internal fun normalizeMangayomiServer(value: String): String? {16 val raw = value.trim().trimEnd('/')17 val match = Regex("^([A-Za-z][A-Za-z0-9+.-]*://)([^/]+)(.*)$").matchEntire(raw) ?: return null18 return match.groupValues[1].lowercase() + match.groupValues[2].lowercase() + match.groupValues[3]19}2021/**22 * Namespace -> "kind|localId" rows bound in persisted Mangayomi mappings. Mappings are persisted before every23 * upload, so an unbound row never reached that server and needs no deletion record.24 */25internal fun mangayomiBoundRows(prefs: Iterable<DbSyncPreference>): Map<String, Set<String>> {26 val result = linkedMapOf<String, MutableSet<String>>()27 for (pref in prefs) {28 val raw = pref.mangayomiIdMappings ?: continue29 val namespaces = runCatching { Json.parseToJsonElement(raw).jsonObject["namespaces"] as? JsonObject }.getOrNull() ?: continue30 namespaces.forEach { (namespace, kinds) ->31 val rows = result.getOrPut(namespace) { linkedSetOf() }32 (kinds as? JsonObject)?.forEach { (kind, locals) -> (locals as? JsonObject)?.keys?.forEach { rows += "$kind|$it" } }33 }34 }35 return result36}3738/**39 * Mangayomi delete records for rows present in [before] but not in [after] that a server already knows40 * (see [mangayomiBoundRows] over both snapshots' preferences). Rows already queued in [existing] are skipped,41 * and new record ids avoid the ids in [existing].42 */43internal fun mangayomiDeleteParts(44 before: YokanDatabaseSnapshot,45 after: YokanDatabaseSnapshot,46 existing: List<DbChangedPart>,47 now: Long,48): List<DbChangedPart> {49 val bound = mangayomiBoundRows(before.syncPreferences + after.syncPreferences)50 if (bound.isEmpty()) return emptyList()51 val removed = buildList {52 addRemoved(before.categories.map { it.id }, after.categories.map { it.id }, SyncPaths.KIND_CATEGORY, DbActionType.RemoveCategory)53 addRemoved(before.mangas.map { it.id }, after.mangas.map { it.id }, SyncPaths.KIND_MANGA, DbActionType.RemoveItem)54 addRemoved(before.chapters.map { it.id }, after.chapters.map { it.id }, SyncPaths.KIND_CHAPTER, DbActionType.RemoveChapter)55 addRemoved(before.tracks.map { it.id }, after.tracks.map { it.id }, SyncPaths.KIND_TRACK, DbActionType.RemoveTrack)56 addRemoved(before.histories.map { it.id }, after.histories.map { it.id }, SyncPaths.KIND_HISTORY, DbActionType.RemoveHistory)57 addRemoved(before.updates.map { it.id }, after.updates.map { it.id }, SyncPaths.KIND_UPDATE, DbActionType.RemoveUpdate)58 }59 return deleteParts(removed, bound, existing, now)60}6162/** [mangayomiDeleteParts] for one row removed under [preferences]. */63internal fun mangayomiDeleteParts(64 kind: Int,65 id: Long,66 action: DbActionType,67 preferences: List<DbSyncPreference>,68 existing: List<DbChangedPart>,69 now: Long,70): List<DbChangedPart> = deleteParts(listOf(RemovedRow(kind, id, action)), mangayomiBoundRows(preferences), existing, now)7172private class RemovedRow(val kind: Int, val id: Long, val action: DbActionType)7374private fun MutableList<RemovedRow>.addRemoved(before: List<Long>, after: List<Long>, kind: Int, action: DbActionType) {75 val kept = after.toHashSet()76 before.forEach { id -> if (id !in kept) add(RemovedRow(kind, id, action)) }77}7879private fun deleteParts(80 removed: List<RemovedRow>,81 bound: Map<String, Set<String>>,82 existing: List<DbChangedPart>,83 now: Long,84): List<DbChangedPart> {85 if (removed.isEmpty() || bound.isEmpty()) return emptyList()86 val queued = existing.mapNotNullTo(HashSet()) { it.mangayomiDeleteKey() }87 val usedIds = existing.mapTo(HashSet(), DbChangedPart::id)88 return buildList {89 for (row in removed) for ((namespace, rows) in bound) {90 if (row.id <= 0 || "${row.kind}|${row.id}" !in rows || !queued.add("$namespace|${row.kind}|${row.id}")) continue91 val data = buildJsonObject {92 put("provider", JsonPrimitive(MANGAYOMI_PROVIDER))93 put("namespace", JsonPrimitive(namespace))94 put("kind", JsonPrimitive(row.kind))95 put("localId", JsonPrimitive(row.id.toString()))96 }.toString()97 var recordId = SyncIds.random()98 while (!usedIds.add(recordId)) recordId = SyncIds.random()99 add(DbChangedPart(id = recordId, actionType = row.action, isarId = row.id, data = data, clientDate = now))100 }101 }102}103104/** "namespace|kind|localId" of a queued Mangayomi delete record, or `null` for any other part. */105private fun DbChangedPart.mangayomiDeleteKey(): String? {106 val record = runCatching { Json.parseToJsonElement(data).jsonObject }.getOrNull() ?: return null107 if (record["provider"]?.jsonPrimitive?.content != MANGAYOMI_PROVIDER) return null108 val namespace = record["namespace"]?.jsonPrimitive?.content ?: return null109 val kind = record["kind"]?.jsonPrimitive?.content?.toIntOrNull() ?: return null110 val id = record["localId"]?.jsonPrimitive?.content?.toLongOrNull() ?: return null111 return "$namespace|$kind|$id"112}113114private const val MANGAYOMI_PROVIDER = "mangayomi"115