MangayomiBackupCodec.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/MangayomiBackupCodec.kt
1package eu.friedcutlet.yokan.services.backup23import eu.friedcutlet.yokan.database.DbCategory4import eu.friedcutlet.yokan.database.DbChapter5import eu.friedcutlet.yokan.database.effectiveFiller6import eu.friedcutlet.yokan.database.DbCustomButton7import eu.friedcutlet.yokan.database.DbHistory8import eu.friedcutlet.yokan.database.DbItemType9import eu.friedcutlet.yokan.database.DbManga10import eu.friedcutlet.yokan.database.DbSettings11import eu.friedcutlet.yokan.database.DbSource12import eu.friedcutlet.yokan.database.DbSourceCodeLanguage13import eu.friedcutlet.yokan.database.DbStatus14import eu.friedcutlet.yokan.database.DbTrack15import eu.friedcutlet.yokan.database.DbTrackPreference16import eu.friedcutlet.yokan.database.DbTrackStatus17import eu.friedcutlet.yokan.database.DbUpdate18import eu.friedcutlet.yokan.util.nowMillis19import kotlinx.serialization.KSerializer20import kotlinx.serialization.builtins.ListSerializer21import kotlinx.serialization.json.JsonArray22import kotlinx.serialization.json.JsonElement23import kotlinx.serialization.json.JsonNull24import kotlinx.serialization.json.JsonObject25import kotlinx.serialization.json.JsonPrimitive26import kotlinx.serialization.json.booleanOrNull27import kotlinx.serialization.json.buildJsonObject28import kotlinx.serialization.json.contentOrNull29import kotlinx.serialization.json.intOrNull30import kotlinx.serialization.json.put3132/**33 * The old Flutter Mangayomi backup schema: version "2", singular collection keys34 * (`manga`, `history`, `extensions`) and enums written as their ordinal index.35 * The Db* models share field names with the Mangayomi Isar models, so both36 * directions are the native JSON with enum/alias fields adapted.37 */38internal object MangayomiBackupCodec {39 private val json = BackupJson4041 /**42 * Serialize a native snapshot into the Mangayomi schema (the inverse of43 * [decode]): enum names mapped back to indices and the legacy44 * `isManga`/`pos`/`hide` aliases re-added.45 */46 fun encode(payload: BackupSnapshot): String {47 fun encodeList(48 items: List<JsonObject>,49 transform: (MutableMap<String, JsonElement>) -> Unit = {},50 ): JsonArray = JsonArray(51 items.map { obj ->52 val m = obj.toMutableMap()53 transform(m)54 JsonObject(m)55 },56 )5758 fun <T> enc(serializer: KSerializer<T>, value: T): JsonObject =59 json.encodeToJsonElement(serializer, value) as JsonObject6061 val mangas = encodeList(payload.mangas.map { enc(DbManga.serializer(), it) }) { m ->62 m.remove("privateNote")63 m.remove("cast") // The legacy format has no cast model.64 m.remove("parentId"); m.remove("fetchType"); m.remove("seasonNumber") // No season-record model either.65 if ((m["status"] as? JsonPrimitive)?.contentOrNull !in MANGAYOMI_STATUSES) {66 m["status"] = JsonPrimitive(DbStatus.Unknown.name)67 }68 indexToFrom(m, "status", MANGAYOMI_STATUSES)69 itemTypeToIndex(m, "itemType")70 }71 // Mangayomi has no filler override: export the effective mark.72 val chapters = encodeList(payload.chapters.map { enc(DbChapter.serializer(), it.copy(isFiller = it.effectiveFiller)) }) { m ->73 m.remove("fillerOverride")74 }75 val categories = encodeList(payload.categories.map { enc(DbCategory.serializer(), it) }) { m ->76 m["position"]?.let { m["pos"] = it }77 m["hidden"]?.let { m["hide"] = it }78 itemTypeToIndex(m, "forItemType", legacyKey = "forManga")79 }80 val sources = encodeList(payload.sources.map { enc(DbSource.serializer(), it) }) { m ->81 itemTypeToIndex(m, "itemType")82 indexToFrom(m, "sourceCodeLanguage", MANGAYOMI_SOURCE_LANGUAGES)83 }84 val histories = encodeList(payload.histories.map { enc(DbHistory.serializer(), it) }) { m ->85 itemTypeToIndex(m, "itemType")86 }87 val updates = encodeList(payload.updates.map { enc(DbUpdate.serializer(), it) })88 val tracks = encodeList(payload.tracks.map { enc(DbTrack.serializer(), it) }) { m ->89 indexToFrom(m, "status", DbTrackStatus.entries.map { it.name })90 itemTypeToIndex(m, "itemType")91 }92 val trackPreferences = encodeList(payload.trackPreferences.map { enc(DbTrackPreference.serializer(), it) })93 val customButtons = encodeList(payload.customButtons.map { enc(DbCustomButton.serializer(), it) }) { m ->94 m["position"]?.let { m["pos"] = it }95 }9697 val datas = buildJsonObject {98 put("version", "2")99 put("manga", mangas)100 put("categories", categories)101 put("chapters", chapters)102 put("downloads", JsonArray(emptyList()))103 put("tracks", tracks)104 put("history", histories)105 put("updates", updates)106 put("extensions", sources)107 put("trackPreferences", trackPreferences)108 put("customButtons", customButtons)109 payload.settings?.backupEncryptionPassword?.let {110 put("backupEncryptionPassword", it)111 }112 // Settings intentionally omitted — the Mangayomi Settings model113 // diverges from DbSettings, so we don't risk corrupting the old114 // app's preferences. Library data is the load-bearing part.115 }116 return json.encodeToString(JsonObject.serializer(), datas)117 }118119 fun decode(root: JsonObject): BackupSnapshot {120 // Mangayomi serializes optional non-null Yokan fields (e.g.121 // `scanlator`, `url`, `name`) as JSON null. kotlinx.serialization122 // refuses to decode null into a non-nullable field even when a123 // default is declared, so route every record through stripNulls124 // first to let the declared defaults take over.125 //126 // Decode collection-by-collection (instead of assembling one adapted127 // mega-JsonObject) so each adapted array becomes garbage as soon as128 // its list is decoded — real backups are tens of MB of JSON and the129 // duplicated tree was enough to OOM Android during restore.130 fun <T> dec(131 key: String,132 serializer: KSerializer<T>,133 transform: (JsonObject) -> JsonObject = { it },134 ): List<T> = json.decodeFromJsonElement(135 ListSerializer(serializer),136 adaptArray(root[key], transform),137 )138 // Mangayomi's Settings model diverges from DbSettings (different139 // fields, different defaults). Skip the settings block — letting140 // it silently fall back to defaults would overwrite the user's141 // current Yokan preferences with mostly-empty values. Library data142 // is the load-bearing part of the import.143 val embeddedPassword = (root["backupEncryptionPassword"] as? JsonPrimitive)?.contentOrNull144 val settings = embeddedPassword?.let {145 DbSettings(backupEncryptionEnabled = true, backupEncryptionPassword = it)146 }147 return BackupSnapshot(148 createdAtMillis = nowMillis(),149 sourceApp = "mangayomi",150 settings = settings,151 mangas = dec("manga", DbManga.serializer(), ::adaptManga),152 chapters = dec("chapters", DbChapter.serializer()),153 categories = dec("categories", DbCategory.serializer(), ::adaptCategory),154 sources = dec("extensions", DbSource.serializer(), ::adaptSource),155 histories = dec("history", DbHistory.serializer(), ::adaptHistory),156 updates = dec("updates", DbUpdate.serializer()),157 tracks = dec("tracks", DbTrack.serializer(), ::adaptTrack),158 trackPreferences = dec("trackPreferences", DbTrackPreference.serializer()),159 customButtons = dec("customButtons", DbCustomButton.serializer(), ::adaptCustomButton),160 )161 }162163 /** Map an enum *name* string back to its ordinal index (inverse of [mapEnumIndex]). */164 private fun indexToFrom(165 m: MutableMap<String, JsonElement>,166 key: String,167 names: List<String>,168 ) {169 val name = (m[key] as? JsonPrimitive)?.takeIf { it.isString }?.content ?: return170 val idx = names.indexOf(name)171 if (idx >= 0) m[key] = JsonPrimitive(idx)172 }173174 /** Write itemType as an ordinal index and re-add the legacy boolean alias. */175 private fun itemTypeToIndex(176 m: MutableMap<String, JsonElement>,177 key: String,178 legacyKey: String = "isManga",179 ) {180 val names = DbItemType.entries.map { it.name }181 val name = (m[key] as? JsonPrimitive)?.takeIf { it.isString }?.content182 val idx = name?.let { names.indexOf(it) } ?: -1183 if (idx >= 0) m[key] = JsonPrimitive(idx)184 m[legacyKey] = JsonPrimitive(name == "Manga")185 }186187 private fun adaptArray(188 element: JsonElement?,189 transform: (JsonObject) -> JsonObject = { it },190 ): JsonArray {191 val array = element as? JsonArray ?: return JsonArray(emptyList())192 return JsonArray(193 array.mapNotNull { item ->194 (item as? JsonObject)?.let { obj -> transform(stripNulls(obj)) }195 },196 )197 }198199 /**200 * Drop JsonNull-valued keys so the kotlinx.serialization decoder falls201 * back to the field's declared default instead of failing on a strictly202 * non-null field. Required for Mangayomi backups, which serialize most203 * optional string fields as explicit nulls.204 */205 private fun stripNulls(o: JsonObject): JsonObject =206 if (o.values.none { it is JsonNull }) o else JsonObject(o.filterValues { it !is JsonNull })207208 private fun adaptManga(o: JsonObject): JsonObject {209 val m = o.toMutableMap()210 mapEnumIndex(m, "status", MANGAYOMI_STATUSES)211 mapItemType(m, "itemType", legacyKey = "isManga")212 return JsonObject(m)213 }214215 private fun adaptCategory(o: JsonObject): JsonObject {216 val m = o.toMutableMap()217 // Mangayomi stores Category.pos / hide; Yokan stores position / hidden.218 m["pos"]?.let { m["position"] = it }219 m["hide"]?.let { m["hidden"] = it }220 m.remove("pos")221 m.remove("hide")222 mapItemType(m, "forItemType", legacyKey = "forManga")223 return JsonObject(m)224 }225226 private fun adaptSource(o: JsonObject): JsonObject {227 val m = o.toMutableMap()228 mapItemType(m, "itemType", legacyKey = "isManga")229 // Upstream index 0 is Dart, which Yokan cannot run; it keeps the JavaScript default.230 mapEnumIndex(m, "sourceCodeLanguage", MANGAYOMI_SOURCE_LANGUAGES)231 val language = (m["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull232 if (DbSourceCodeLanguage.entries.none { it.name == language }) {233 m["sourceCodeLanguage"] = JsonPrimitive(DbSourceCodeLanguage.JavaScript.name)234 }235 return JsonObject(m)236 }237238 private fun adaptHistory(o: JsonObject): JsonObject {239 val m = o.toMutableMap()240 mapItemType(m, "itemType", legacyKey = "isManga")241 return JsonObject(m)242 }243244 private fun adaptTrack(o: JsonObject): JsonObject {245 val m = o.toMutableMap()246 // Mangayomi's TrackStatus has 9 values; Yokan's DbTrackStatus has 8247 // (no `reWatching`). Out-of-range indices fall back to Reading.248 mapEnumIndex(m, "status", DbTrackStatus.entries.map { it.name })249 mapItemType(m, "itemType", legacyKey = "isManga")250 return JsonObject(m)251 }252253 private fun adaptCustomButton(o: JsonObject): JsonObject {254 val m = o.toMutableMap()255 m["pos"]?.let { m["position"] = it }256 m.remove("pos")257 return JsonObject(m)258 }259260 /** Fixed wire ordinals; extending Yokan's model must not extend this legacy format. */261 private val MANGAYOMI_STATUSES = listOf("Ongoing", "Completed", "Canceled", "Unknown", "OnHiatus", "PublishingFinished")262263 /** Mangayomi's `SourceCodeLanguage { dart, javascript, mihon, lnreader, aidoku }`, by ordinal. */264 private val MANGAYOMI_SOURCE_LANGUAGES = listOf("Dart") + listOf(265 DbSourceCodeLanguage.JavaScript,266 DbSourceCodeLanguage.Mihon,267 DbSourceCodeLanguage.LnReader,268 DbSourceCodeLanguage.Aidoku,269 ).map { it.name }270271 private fun mapEnumIndex(272 m: MutableMap<String, JsonElement>,273 key: String,274 names: List<String>,275 ) {276 val idx = (m[key] as? JsonPrimitive)?.intOrNull ?: return277 if (idx in names.indices) m[key] = JsonPrimitive(names[idx])278 }279280 private fun mapItemType(281 m: MutableMap<String, JsonElement>,282 key: String,283 legacyKey: String,284 ) {285 val idx = (m[key] as? JsonPrimitive)?.intOrNull286 val names = DbItemType.entries.map { it.name }287 if (idx != null) {288 if (idx in names.indices) m[key] = JsonPrimitive(names[idx])289 return290 }291 // Legacy Mangayomi backups predate itemType — fall back to the292 // boolean `isManga` / `forManga` field for the same record.293 val legacy = (m[legacyKey] as? JsonPrimitive)?.booleanOrNull294 if (legacy != null) {295 m[key] = JsonPrimitive(if (legacy) "Manga" else "Anime")296 }297 m.remove(legacyKey)298 }299}300