package eu.friedcutlet.yokan.database.sync import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbHistory import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbOutboxOp import eu.friedcutlet.yokan.database.DbPersonalReaderMode import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.SyncServerProvider import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbUpdate import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot import eu.friedcutlet.yokan.util.nowMillis import kotlinx.serialization.KSerializer 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.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.encodeToJsonElement import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive /** * Wire shape of a synced entity and the path-level diff that feeds the outbox. * * The hub stores each entity as a JSON object and merges per *path*: a top-level field, or * `field.key` for keyed collections. So a `List` travels as * `{ "": {...element...} }` and a manga's `categories: List` as `{ "": true }`. * `yokan-hub/src/snapshots.rs::to_backup_snapshot` performs the inverse on export. */ object SyncPaths { const val KIND_CATEGORY = 1 const val KIND_MANGA = 2 const val KIND_CHAPTER = 3 const val KIND_TRACK = 4 const val KIND_HISTORY = 5 const val KIND_UPDATE = 6 const val KIND_SETTINGS = 7 const val SETTINGS_ID = 1L const val DELETED = "_deleted" val json: Json = Json { encodeDefaults = true explicitNulls = false ignoreUnknownKeys = true } /** `value == null` removes the path. */ data class PathChange(val path: String, val value: JsonElement?) /** * The one list of device-local [DbSettings] fields: never pushed through sync and never * overwritten by a restored backup (see [preserveDeviceLocalSettings]). Paths, loopback * endpoints and credentials only make sense on the machine that set them. */ private val settingsDeviceLocal = setOf( "id", "syncIdentityVersion", // device paths and processes "localFolders", "namedLocalFolders", "downloadLocalFolderName", "askDownloadDestination", "downloadLocation", "autoBackupLocation", "themeSeedImagePath", "androidProxyServer", "cloudflareBypassProxyUrl", "jrePath", "extensionServerPath", "btServerAddress", "btServerPort", "desktopCloseToTray", "desktopLaunchAtLogin", "customHubServers", // secrets and caches "cookiesList", "metadataServerToken", "updateErrors", // Discovery layout, installed-source references and API credentials belong to this device. "features", // debugging "enableLogs", "enableFileLogging", "developerMode", // Title-owned preferences need explicit owner remapping before hub protocol support. "chapterReleasePreferences", "automaticReaderLayout", "automaticReaderLayouts", "readerHoldToScroll", // E-ink display mode describes this device's screen. "einkMode", "einkPreset", "einkRefreshEveryPages", "einkOptimizeDownloads", ) private val excludedByKind: Map> = mapOf( KIND_MANGA to setOf("id", "customCoverImage", "privateNote"), // Only downloads set downloadSize; with it, archivePath is this device's download folder (see hasDownloadMark). KIND_CHAPTER to setOf("id", "downloadSize"), KIND_SETTINGS to settingsDeviceLocal, ) fun excluded(kind: Int): Set = excludedByKind[kind] ?: setOf("id") private const val SOURCE_PREF_KEY = "sourceId+key" private val settingsKeyed: Map = mapOf( "sortChapterList" to "mangaId", "chapterFilterDownloadedList" to "mangaId", "chapterFilterUnreadList" to "mangaId", "chapterFilterBookmarkedList" to "mangaId", "chapterPageIndexList" to "chapterId", "personalReaderModeList" to "mangaId", "filterScanlatorList" to "mangaId", "personalPageModeList" to "mangaId", "autoScrollPages" to "mangaId", "titleMetadata" to "mangaId", "sourcePreferences" to SOURCE_PREF_KEY, ) /** Fields stored as objects keyed by an element field, so two devices can edit different entries. */ fun keyedFields(kind: Int): Map = if (kind == KIND_SETTINGS) settingsKeyed else emptyMap() /** `List` fields stored as `{ "": true }` (a set with per-element clocks). */ fun idSetFields(kind: Int): Set = if (kind == KIND_MANGA) setOf("categories") else emptySet() private fun elementKey(spec: String, element: JsonObject): String? = if (spec == SOURCE_PREF_KEY) { val s = element["sourceId"]?.jsonPrimitive?.content ?: return null val k = element["key"]?.jsonPrimitive?.content ?: return null "$s:$k" } else { element[spec]?.jsonPrimitive?.content } fun doc(kind: Int, serializer: KSerializer, value: T): JsonObject = toDoc(kind, json.encodeToJsonElement(serializer, value).jsonObject) /** Content equality used for local timestamps: excludes device-local fields and updatedAt itself. */ fun syncContentChanged(kind: Int, serializer: KSerializer, before: T, after: T): Boolean { val old = doc(kind, serializer, before).filterKeys { it != "updatedAt" } val next = doc(kind, serializer, after).filterKeys { it != "updatedAt" } return old != next } fun localUpdatedAt(kind: Int, serializer: KSerializer, previous: T?, incoming: T, timestamp: (T) -> Long): Long { val incomingAt = timestamp(incoming) if (previous == null) return maxOf(nowMillis(), incomingAt) if (!syncContentChanged(kind, serializer, previous, incoming)) return timestamp(previous) val priorAt = timestamp(previous) val nextAt = if (priorAt == Long.MAX_VALUE) priorAt else priorAt + 1 return maxOf(nowMillis(), incomingAt, nextAt) } fun toDoc(kind: Int, obj: JsonObject): JsonObject { val excluded = excluded(kind) val keyed = keyedFields(kind) val idSets = idSetFields(kind) return buildJsonObject { for ((k, v) in obj) { if (k in excluded || (kind == KIND_SETTINGS && k == "home")) continue if (kind == KIND_CHAPTER && k == "archivePath" && obj.hasDownloadMark()) { // Local-library chapters keep syncing their (virtual) archivePath; a download's path stays here. put(k, JsonPrimitive("")) continue } when { k in idSets && v is JsonArray -> put(k, buildJsonObject { v.forEach { put(it.jsonPrimitive.content, JsonPrimitive(true)) } }) k in keyed && v is JsonArray -> put( k, buildJsonObject { val spec = keyed.getValue(k) v.forEach { el -> val o = el as? JsonObject ?: return@forEach elementKey(spec, o)?.let { put(it, o) } } }, ) else -> put(k, v) } } } } fun fromDoc(kind: Int, doc: JsonObject): JsonObject { val keyed = keyedFields(kind) val idSets = idSetFields(kind) return buildJsonObject { for ((k, v) in doc) { if (k == DELETED) continue when { k in idSets && v is JsonObject -> put(k, JsonArray(v.keys.mapNotNull { it.toLongOrNull() }.sorted().map(::JsonPrimitive))) k in keyed && v is JsonObject -> put(k, JsonArray(v.values.toList())) else -> put(k, v) } } } } /** Path-level difference between two docs; keyed and id-set fields diff one level down. */ fun diff(kind: Int, before: JsonObject?, after: JsonObject): List { val nested = keyedFields(kind).keys + idSetFields(kind) val out = ArrayList() for (k in LinkedHashSet(before?.keys.orEmpty() + after.keys)) { val a = before?.get(k) val b = after[k] if (a == b) continue if (k in nested && (a == null || a is JsonObject) && (b == null || b is JsonObject)) { val ao = a val bo = b for (sub in LinkedHashSet(ao?.keys.orEmpty() + bo?.keys.orEmpty())) { val x = ao?.get(sub) val y = bo?.get(sub) if (x != y) out += PathChange("$k.$sub", y) } } else { out += PathChange(k, b) } } return out } /** * Merge an incoming hub doc onto the local object: every synced field comes from the hub * (absent means removed), excluded fields keep their local value even when an older client * pushed them to the hub, `id` is the entity key. A chapter keeps this device's download * folder, and a download folder pushed from another device is dropped. */ fun applyIncoming(kind: Int, local: JsonObject?, incomingDoc: JsonObject, id: Long): JsonObject { val excluded = excluded(kind) val incoming = fromDoc(kind, incomingDoc) return buildJsonObject { local?.forEach { (k, v) -> if (k in excluded && k != "id") put(k, v) } incoming.forEach { (k, v) -> if (k !in excluded && !(kind == KIND_SETTINGS && k == "home")) put(k, v) } if (kind == KIND_CHAPTER) { when { local?.hasDownloadMark() == true -> put("archivePath", local["archivePath"] ?: JsonPrimitive("")) incoming.hasDownloadMark() -> put("archivePath", JsonPrimitive("")) } } put("id", JsonPrimitive(id)) } } private fun JsonObject.hasDownloadMark(): Boolean = this["downloadSize"].let { it != null && it !is JsonNull } /** Put this device's still-pending values for their paths back on top of an incoming doc. */ fun overlay(doc: JsonObject, pending: List): JsonObject { if (pending.isEmpty()) return doc val top = LinkedHashMap(doc) for (op in pending) { if (op.path == DELETED) continue val value = op.value?.let(json::parseToJsonElement) val dot = op.path.indexOf('.') if (dot < 0) { if (value == null || value is JsonNull) top.remove(op.path) else top[op.path] = value } else { val field = op.path.substring(0, dot) val sub = op.path.substring(dot + 1) val inner = LinkedHashMap((top[field] as? JsonObject).orEmpty()) if (value == null || value is JsonNull) inner.remove(sub) else inner[sub] = value top[field] = JsonObject(inner) } } return JsonObject(top) } /** Every synced entity of [s] (restricted to [kinds]) as `(kind, id, doc)`. */ fun docs(s: YokanDatabaseSnapshot, kinds: Set = ALL_KINDS): Sequence> { fun List.docs(kind: Int, serializer: KSerializer, id: (T) -> Long) = if (kind in kinds) asSequence().map { Triple(kind, id(it), doc(kind, serializer, it)) } else emptySequence() return s.categories.docs(KIND_CATEGORY, DbCategory.serializer(), DbCategory::id) + s.mangas.docs(KIND_MANGA, DbManga.serializer(), DbManga::id) + s.chapters.docs(KIND_CHAPTER, DbChapter.serializer(), DbChapter::id) + s.tracks.docs(KIND_TRACK, DbTrack.serializer(), DbTrack::id) + s.histories.docs(KIND_HISTORY, DbHistory.serializer(), DbHistory::id) + s.updates.docs(KIND_UPDATE, DbUpdate.serializer(), DbUpdate::id) + listOf(s.settings).docs(KIND_SETTINGS, DbSettings.serializer()) { SETTINGS_ID } } val ALL_KINDS: Set = (KIND_CATEGORY..KIND_SETTINGS).toSet() /** * Epoch new outbox ops belong to: the logged-in hub's (0 until negotiated), or null while no hub * is active. Nothing is recorded then; the first sync seeds the hub with full local state. */ fun activeHubEpoch(prefs: List): Int? = prefs.firstOrNull { it.serverProvider == SyncServerProvider.YokanHub && it.syncOn && !it.authToken.isNullOrBlank() && !it.server.isNullOrBlank() && !it.server.startsWith("cloud://") }?.hubEpoch /** * [after]'s outbox extended with every path that differs from [before], each with a fresh clock, * so a wholesale replacement (backup restore) reaches the hub like ordinary edits and wins over * what the hub had. Entities missing from [after] are sent as deletes. Without an active hub * nothing is added, as for ordinary edits. */ fun outboxForReplacement(before: YokanDatabaseSnapshot, after: YokanDatabaseSnapshot): List { val epoch = activeHubEpoch(after.syncPreferences) ?: return after.outbox val old = docs(before).associate { (kind, id, doc) -> (kind to id) to doc }.toMutableMap() var seq = after.outbox.maxOfOrNull { it.seq } ?: 0L val added = ArrayList() fun add(kind: Int, id: Long, change: PathChange) { added += DbOutboxOp(kind = kind, id = id, path = change.path, value = change.value?.toString(), hlc = SyncClock.tick(), seq = ++seq, epoch = epoch) } for ((kind, id, doc) in docs(after)) { for (change in diff(kind, old.remove(kind to id), doc)) add(kind, id, change) } for ((key, _) in old) add(key.first, key.second, PathChange(DELETED, JsonPrimitive(true))) if (added.isEmpty()) return after.outbox val replaced = added.mapTo(HashSet()) { Triple(it.kind, it.id, it.path) } return after.outbox.filterNot { Triple(it.kind, it.id, it.path) in replaced } + added } } /** * [incoming] settings (e.g. from a restored backup) with every device-local field * ([SyncPaths.excluded] for [SyncPaths.KIND_SETTINGS]) kept from [current]. */ fun preserveDeviceLocalSettings(current: DbSettings, incoming: DbSettings): DbSettings { val json = SyncPaths.json val local = json.encodeToJsonElement(DbSettings.serializer(), current).jsonObject val merged = json.encodeToJsonElement(DbSettings.serializer(), incoming).jsonObject.toMutableMap() for (key in SyncPaths.excluded(SyncPaths.KIND_SETTINGS)) { // explicitNulls = false omits null fields; removing the key restores the null default. val value = local[key] if (value == null) merged.remove(key) else merged[key] = value } return json.decodeFromJsonElement(DbSettings.serializer(), JsonObject(merged)) }