package eu.friedcutlet.yokan.database.sync import eu.friedcutlet.yokan.database.DbActionType import eu.friedcutlet.yokan.database.DbChangedPart import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive /** Canonical host/scheme while preserving path case; account identity is appended separately. */ internal fun normalizeMangayomiServer(value: String): String? { val raw = value.trim().trimEnd('/') val match = Regex("^([A-Za-z][A-Za-z0-9+.-]*://)([^/]+)(.*)$").matchEntire(raw) ?: return null return match.groupValues[1].lowercase() + match.groupValues[2].lowercase() + match.groupValues[3] } /** * Namespace -> "kind|localId" rows bound in persisted Mangayomi mappings. Mappings are persisted before every * upload, so an unbound row never reached that server and needs no deletion record. */ internal fun mangayomiBoundRows(prefs: Iterable): Map> { val result = linkedMapOf>() for (pref in prefs) { val raw = pref.mangayomiIdMappings ?: continue val namespaces = runCatching { Json.parseToJsonElement(raw).jsonObject["namespaces"] as? JsonObject }.getOrNull() ?: continue namespaces.forEach { (namespace, kinds) -> val rows = result.getOrPut(namespace) { linkedSetOf() } (kinds as? JsonObject)?.forEach { (kind, locals) -> (locals as? JsonObject)?.keys?.forEach { rows += "$kind|$it" } } } } return result } /** * Mangayomi delete records for rows present in [before] but not in [after] that a server already knows * (see [mangayomiBoundRows] over both snapshots' preferences). Rows already queued in [existing] are skipped, * and new record ids avoid the ids in [existing]. */ internal fun mangayomiDeleteParts( before: YokanDatabaseSnapshot, after: YokanDatabaseSnapshot, existing: List, now: Long, ): List { val bound = mangayomiBoundRows(before.syncPreferences + after.syncPreferences) if (bound.isEmpty()) return emptyList() val removed = buildList { addRemoved(before.categories.map { it.id }, after.categories.map { it.id }, SyncPaths.KIND_CATEGORY, DbActionType.RemoveCategory) addRemoved(before.mangas.map { it.id }, after.mangas.map { it.id }, SyncPaths.KIND_MANGA, DbActionType.RemoveItem) addRemoved(before.chapters.map { it.id }, after.chapters.map { it.id }, SyncPaths.KIND_CHAPTER, DbActionType.RemoveChapter) addRemoved(before.tracks.map { it.id }, after.tracks.map { it.id }, SyncPaths.KIND_TRACK, DbActionType.RemoveTrack) addRemoved(before.histories.map { it.id }, after.histories.map { it.id }, SyncPaths.KIND_HISTORY, DbActionType.RemoveHistory) addRemoved(before.updates.map { it.id }, after.updates.map { it.id }, SyncPaths.KIND_UPDATE, DbActionType.RemoveUpdate) } return deleteParts(removed, bound, existing, now) } /** [mangayomiDeleteParts] for one row removed under [preferences]. */ internal fun mangayomiDeleteParts( kind: Int, id: Long, action: DbActionType, preferences: List, existing: List, now: Long, ): List = deleteParts(listOf(RemovedRow(kind, id, action)), mangayomiBoundRows(preferences), existing, now) private class RemovedRow(val kind: Int, val id: Long, val action: DbActionType) private fun MutableList.addRemoved(before: List, after: List, kind: Int, action: DbActionType) { val kept = after.toHashSet() before.forEach { id -> if (id !in kept) add(RemovedRow(kind, id, action)) } } private fun deleteParts( removed: List, bound: Map>, existing: List, now: Long, ): List { if (removed.isEmpty() || bound.isEmpty()) return emptyList() val queued = existing.mapNotNullTo(HashSet()) { it.mangayomiDeleteKey() } val usedIds = existing.mapTo(HashSet(), DbChangedPart::id) return buildList { for (row in removed) for ((namespace, rows) in bound) { if (row.id <= 0 || "${row.kind}|${row.id}" !in rows || !queued.add("$namespace|${row.kind}|${row.id}")) continue val data = buildJsonObject { put("provider", JsonPrimitive(MANGAYOMI_PROVIDER)) put("namespace", JsonPrimitive(namespace)) put("kind", JsonPrimitive(row.kind)) put("localId", JsonPrimitive(row.id.toString())) }.toString() var recordId = SyncIds.random() while (!usedIds.add(recordId)) recordId = SyncIds.random() add(DbChangedPart(id = recordId, actionType = row.action, isarId = row.id, data = data, clientDate = now)) } } } /** "namespace|kind|localId" of a queued Mangayomi delete record, or `null` for any other part. */ private fun DbChangedPart.mangayomiDeleteKey(): String? { val record = runCatching { Json.parseToJsonElement(data).jsonObject }.getOrNull() ?: return null if (record["provider"]?.jsonPrimitive?.content != MANGAYOMI_PROVIDER) return null val namespace = record["namespace"]?.jsonPrimitive?.content ?: return null val kind = record["kind"]?.jsonPrimitive?.content?.toIntOrNull() ?: return null val id = record["localId"]?.jsonPrimitive?.content?.toLongOrNull() ?: return null return "$namespace|$kind|$id" } private const val MANGAYOMI_PROVIDER = "mangayomi"