package eu.friedcutlet.yokan.services.backup import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.effectiveFiller import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.database.DbHistory import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbSourceCodeLanguage import eu.friedcutlet.yokan.database.DbStatus import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackPreference import eu.friedcutlet.yokan.database.DbTrackStatus import eu.friedcutlet.yokan.database.DbUpdate import eu.friedcutlet.yokan.util.nowMillis import kotlinx.serialization.KSerializer import kotlinx.serialization.builtins.ListSerializer 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.booleanOrNull import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.put /** * The old Flutter Mangayomi backup schema: version "2", singular collection keys * (`manga`, `history`, `extensions`) and enums written as their ordinal index. * The Db* models share field names with the Mangayomi Isar models, so both * directions are the native JSON with enum/alias fields adapted. */ internal object MangayomiBackupCodec { private val json = BackupJson /** * Serialize a native snapshot into the Mangayomi schema (the inverse of * [decode]): enum names mapped back to indices and the legacy * `isManga`/`pos`/`hide` aliases re-added. */ fun encode(payload: BackupSnapshot): String { fun encodeList( items: List, transform: (MutableMap) -> Unit = {}, ): JsonArray = JsonArray( items.map { obj -> val m = obj.toMutableMap() transform(m) JsonObject(m) }, ) fun enc(serializer: KSerializer, value: T): JsonObject = json.encodeToJsonElement(serializer, value) as JsonObject val mangas = encodeList(payload.mangas.map { enc(DbManga.serializer(), it) }) { m -> m.remove("privateNote") m.remove("cast") // The legacy format has no cast model. m.remove("parentId"); m.remove("fetchType"); m.remove("seasonNumber") // No season-record model either. if ((m["status"] as? JsonPrimitive)?.contentOrNull !in MANGAYOMI_STATUSES) { m["status"] = JsonPrimitive(DbStatus.Unknown.name) } indexToFrom(m, "status", MANGAYOMI_STATUSES) itemTypeToIndex(m, "itemType") } // Mangayomi has no filler override: export the effective mark. val chapters = encodeList(payload.chapters.map { enc(DbChapter.serializer(), it.copy(isFiller = it.effectiveFiller)) }) { m -> m.remove("fillerOverride") } val categories = encodeList(payload.categories.map { enc(DbCategory.serializer(), it) }) { m -> m["position"]?.let { m["pos"] = it } m["hidden"]?.let { m["hide"] = it } itemTypeToIndex(m, "forItemType", legacyKey = "forManga") } val sources = encodeList(payload.sources.map { enc(DbSource.serializer(), it) }) { m -> itemTypeToIndex(m, "itemType") indexToFrom(m, "sourceCodeLanguage", MANGAYOMI_SOURCE_LANGUAGES) } val histories = encodeList(payload.histories.map { enc(DbHistory.serializer(), it) }) { m -> itemTypeToIndex(m, "itemType") } val updates = encodeList(payload.updates.map { enc(DbUpdate.serializer(), it) }) val tracks = encodeList(payload.tracks.map { enc(DbTrack.serializer(), it) }) { m -> indexToFrom(m, "status", DbTrackStatus.entries.map { it.name }) itemTypeToIndex(m, "itemType") } val trackPreferences = encodeList(payload.trackPreferences.map { enc(DbTrackPreference.serializer(), it) }) val customButtons = encodeList(payload.customButtons.map { enc(DbCustomButton.serializer(), it) }) { m -> m["position"]?.let { m["pos"] = it } } val datas = buildJsonObject { put("version", "2") put("manga", mangas) put("categories", categories) put("chapters", chapters) put("downloads", JsonArray(emptyList())) put("tracks", tracks) put("history", histories) put("updates", updates) put("extensions", sources) put("trackPreferences", trackPreferences) put("customButtons", customButtons) payload.settings?.backupEncryptionPassword?.let { put("backupEncryptionPassword", it) } // Settings intentionally omitted — the Mangayomi Settings model // diverges from DbSettings, so we don't risk corrupting the old // app's preferences. Library data is the load-bearing part. } return json.encodeToString(JsonObject.serializer(), datas) } fun decode(root: JsonObject): BackupSnapshot { // Mangayomi serializes optional non-null Yokan fields (e.g. // `scanlator`, `url`, `name`) as JSON null. kotlinx.serialization // refuses to decode null into a non-nullable field even when a // default is declared, so route every record through stripNulls // first to let the declared defaults take over. // // Decode collection-by-collection (instead of assembling one adapted // mega-JsonObject) so each adapted array becomes garbage as soon as // its list is decoded — real backups are tens of MB of JSON and the // duplicated tree was enough to OOM Android during restore. fun dec( key: String, serializer: KSerializer, transform: (JsonObject) -> JsonObject = { it }, ): List = json.decodeFromJsonElement( ListSerializer(serializer), adaptArray(root[key], transform), ) // Mangayomi's Settings model diverges from DbSettings (different // fields, different defaults). Skip the settings block — letting // it silently fall back to defaults would overwrite the user's // current Yokan preferences with mostly-empty values. Library data // is the load-bearing part of the import. val embeddedPassword = (root["backupEncryptionPassword"] as? JsonPrimitive)?.contentOrNull val settings = embeddedPassword?.let { DbSettings(backupEncryptionEnabled = true, backupEncryptionPassword = it) } return BackupSnapshot( createdAtMillis = nowMillis(), sourceApp = "mangayomi", settings = settings, mangas = dec("manga", DbManga.serializer(), ::adaptManga), chapters = dec("chapters", DbChapter.serializer()), categories = dec("categories", DbCategory.serializer(), ::adaptCategory), sources = dec("extensions", DbSource.serializer(), ::adaptSource), histories = dec("history", DbHistory.serializer(), ::adaptHistory), updates = dec("updates", DbUpdate.serializer()), tracks = dec("tracks", DbTrack.serializer(), ::adaptTrack), trackPreferences = dec("trackPreferences", DbTrackPreference.serializer()), customButtons = dec("customButtons", DbCustomButton.serializer(), ::adaptCustomButton), ) } /** Map an enum *name* string back to its ordinal index (inverse of [mapEnumIndex]). */ private fun indexToFrom( m: MutableMap, key: String, names: List, ) { val name = (m[key] as? JsonPrimitive)?.takeIf { it.isString }?.content ?: return val idx = names.indexOf(name) if (idx >= 0) m[key] = JsonPrimitive(idx) } /** Write itemType as an ordinal index and re-add the legacy boolean alias. */ private fun itemTypeToIndex( m: MutableMap, key: String, legacyKey: String = "isManga", ) { val names = DbItemType.entries.map { it.name } val name = (m[key] as? JsonPrimitive)?.takeIf { it.isString }?.content val idx = name?.let { names.indexOf(it) } ?: -1 if (idx >= 0) m[key] = JsonPrimitive(idx) m[legacyKey] = JsonPrimitive(name == "Manga") } private fun adaptArray( element: JsonElement?, transform: (JsonObject) -> JsonObject = { it }, ): JsonArray { val array = element as? JsonArray ?: return JsonArray(emptyList()) return JsonArray( array.mapNotNull { item -> (item as? JsonObject)?.let { obj -> transform(stripNulls(obj)) } }, ) } /** * Drop JsonNull-valued keys so the kotlinx.serialization decoder falls * back to the field's declared default instead of failing on a strictly * non-null field. Required for Mangayomi backups, which serialize most * optional string fields as explicit nulls. */ private fun stripNulls(o: JsonObject): JsonObject = if (o.values.none { it is JsonNull }) o else JsonObject(o.filterValues { it !is JsonNull }) private fun adaptManga(o: JsonObject): JsonObject { val m = o.toMutableMap() mapEnumIndex(m, "status", MANGAYOMI_STATUSES) mapItemType(m, "itemType", legacyKey = "isManga") return JsonObject(m) } private fun adaptCategory(o: JsonObject): JsonObject { val m = o.toMutableMap() // Mangayomi stores Category.pos / hide; Yokan stores position / hidden. m["pos"]?.let { m["position"] = it } m["hide"]?.let { m["hidden"] = it } m.remove("pos") m.remove("hide") mapItemType(m, "forItemType", legacyKey = "forManga") return JsonObject(m) } private fun adaptSource(o: JsonObject): JsonObject { val m = o.toMutableMap() mapItemType(m, "itemType", legacyKey = "isManga") // Upstream index 0 is Dart, which Yokan cannot run; it keeps the JavaScript default. mapEnumIndex(m, "sourceCodeLanguage", MANGAYOMI_SOURCE_LANGUAGES) val language = (m["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull if (DbSourceCodeLanguage.entries.none { it.name == language }) { m["sourceCodeLanguage"] = JsonPrimitive(DbSourceCodeLanguage.JavaScript.name) } return JsonObject(m) } private fun adaptHistory(o: JsonObject): JsonObject { val m = o.toMutableMap() mapItemType(m, "itemType", legacyKey = "isManga") return JsonObject(m) } private fun adaptTrack(o: JsonObject): JsonObject { val m = o.toMutableMap() // Mangayomi's TrackStatus has 9 values; Yokan's DbTrackStatus has 8 // (no `reWatching`). Out-of-range indices fall back to Reading. mapEnumIndex(m, "status", DbTrackStatus.entries.map { it.name }) mapItemType(m, "itemType", legacyKey = "isManga") return JsonObject(m) } private fun adaptCustomButton(o: JsonObject): JsonObject { val m = o.toMutableMap() m["pos"]?.let { m["position"] = it } m.remove("pos") return JsonObject(m) } /** Fixed wire ordinals; extending Yokan's model must not extend this legacy format. */ private val MANGAYOMI_STATUSES = listOf("Ongoing", "Completed", "Canceled", "Unknown", "OnHiatus", "PublishingFinished") /** Mangayomi's `SourceCodeLanguage { dart, javascript, mihon, lnreader, aidoku }`, by ordinal. */ private val MANGAYOMI_SOURCE_LANGUAGES = listOf("Dart") + listOf( DbSourceCodeLanguage.JavaScript, DbSourceCodeLanguage.Mihon, DbSourceCodeLanguage.LnReader, DbSourceCodeLanguage.Aidoku, ).map { it.name } private fun mapEnumIndex( m: MutableMap, key: String, names: List, ) { val idx = (m[key] as? JsonPrimitive)?.intOrNull ?: return if (idx in names.indices) m[key] = JsonPrimitive(names[idx]) } private fun mapItemType( m: MutableMap, key: String, legacyKey: String, ) { val idx = (m[key] as? JsonPrimitive)?.intOrNull val names = DbItemType.entries.map { it.name } if (idx != null) { if (idx in names.indices) m[key] = JsonPrimitive(names[idx]) return } // Legacy Mangayomi backups predate itemType — fall back to the // boolean `isManga` / `forManga` field for the same record. val legacy = (m[legacyKey] as? JsonPrimitive)?.booleanOrNull if (legacy != null) { m[key] = JsonPrimitive(if (legacy) "Manga" else "Anime") } m.remove(legacyKey) } }