Yokan / rebuild
Course 1 8624561

BackupDecoder.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupDecoder.kt

implementation197 lines
1package eu.friedcutlet.yokan.services.backup23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.DbSourceCodeLanguage5import kotlinx.serialization.json.JsonArray6import kotlinx.serialization.json.JsonElement7import kotlinx.serialization.json.JsonNull8import kotlinx.serialization.json.JsonObject9import kotlinx.serialization.json.JsonPrimitive10import kotlinx.serialization.json.booleanOrNull11import kotlinx.serialization.json.contentOrNull12import kotlinx.serialization.json.intOrNull1314internal class InvalidBackupException : Exception()1516internal class UnsupportedBackupException : Exception()1718internal data class DecodedBackup(19    val snapshot: BackupSnapshot,20    val includedSections: Set<String>,21)2223internal fun ByteArray.startsWithEncryptedMagic(): Boolean =24    size >= 8 && copyOfRange(0, 8).contentEquals("YOKANENC".encodeToByteArray())2526/**27 * Sniffs the container of unencrypted backup bytes and decodes native Yokan,28 * Mangayomi, Tachiyomi-family and Kotatsu backups into a [DecodedBackup] whose29 * sections reflect what the source actually contained.30 */31internal class BackupDecoder(private val gzip: BackupCompression) {32    private val json = BackupJson3334    suspend fun decode(bytes: ByteArray): DecodedBackup {35        if (bytes.isEmpty()) throw InvalidBackupException()36        // Containers first: Mangayomi (Flutter) writes a ZIP with one37        // `*.backup.db` JSON entry; Kotatsu writes a ZIP with `favourites` /38        // `categories` JSON entries. Gzip wraps either native Yokan JSON or a39        // Tachiyomi-family (.tachibk/.proto.gz) protobuf.40        val raw = when {41            gzip.looksZipped(bytes) -> {42                val entries = gzip.unzipEntriesAsync(bytes)43                if (entries != null && "favourites" in entries) {44                    return DecodedBackup(decodeKotatsuBackup(entries), inferKotatsuSections(entries))45                }46                entries?.values?.firstOrNull()47                    ?: gzip.unzipFirstEntryAsync(bytes)48                    ?: throw InvalidBackupException()49            }50            gzip.looksGzipped(bytes) -> gzip.decompressAsync(bytes)51            else -> bytes52        }53        val text = raw.decodeToString()54        val root = runCatching { json.parseToJsonElement(text) as? JsonObject }.getOrNull()55        if (root == null) {56            // Not JSON — Mihon/Tachiyomi/Neko/Aniyomi backups are protobuf.57            if (looksLikeTachiyomiBackup(raw)) {58                val snapshot = decodeTachiyomiBackup(raw)59                return DecodedBackup(snapshot, inferSnapshotSections(snapshot))60            }61            throw InvalidBackupException()62        }63        // Mangayomi backups carry a top-level `version` string and use64        // singular keys (`manga`, `history`, `extensions`). Native Yokan65        // backups carry `schemaVersion` and plural keys. Adapt the former66        // to the latter and reuse the same decode path.67        if ("version" in root && "schemaVersion" !in root) {68            return DecodedBackup(MangayomiBackupCodec.decode(root), inferMangayomiSections(root))69        }70        return decodeNative(root)71    }7273    private fun decodeNative(root: JsonObject): DecodedBackup {74        val schemaVersion = root["schemaVersion"]?.let { (it as? JsonPrimitive)?.intOrNull }75            ?: if ("schemaVersion" in root) throw InvalidBackupException() else BackupSchemaVersion76        if (schemaVersion != BackupSchemaVersion) throw UnsupportedBackupException()77        val sections = parseIncludedSections(root) ?: inferNativeSections(root)78        val snapshot = runCatching {79            json.decodeFromJsonElement(BackupSnapshot.serializer(), normalizeNativeBackup(root))80        }.getOrElse { throw InvalidBackupException() }81        return DecodedBackup(snapshot, sections)82    }8384    private fun normalizeNativeBackup(root: JsonObject): JsonObject {85        val sources = root["sources"] as? JsonArray ?: return root86        val normalizedSources = JsonArray(87            sources.map { element ->88                val source = element as? JsonObject ?: return@map element89                val language = (source["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull90                if (!language.equals("Lua", ignoreCase = true)) return@map source91                JsonObject(source + ("sourceCodeLanguage" to JsonPrimitive(DbSourceCodeLanguage.JavaScript.name)))92            },93        )94        return JsonObject(root + ("sources" to normalizedSources))95    }9697    private fun parseIncludedSections(root: JsonObject): Set<String>? {98        val manifest = root["includedSections"] ?: return null99        // encodeDefaults writes nullable legacy fields as JSON null. Treat a100        // null manifest as an old backup with no manifest, not as malformed101        // manifest data.102        if (manifest is JsonNull) return null103        val values = manifest as? JsonArray ?: throw InvalidBackupException()104        val sections = values.map {105            val value = (it as? JsonPrimitive)?.takeIf { primitive -> primitive.isString }?.contentOrNull106                ?: throw InvalidBackupException()107            if (value !in BackupSection.all) throw UnsupportedBackupException()108            value109        }.toSet()110        return sections111    }112113    private fun inferNativeSections(root: JsonObject): Set<String> = buildSet {114        if (root["settings"] != null && root["settings"] !is JsonNull) add(BackupSection.Settings)115        addTypedSections(root["mangas"])116        addIfPresent(root, "chapters", BackupSection.Chapters)117        addIfPresent(root, "categories", BackupSection.Categories)118        addIfPresent(root, "sources", BackupSection.Sources)119        addIfPresent(root, "histories", BackupSection.History)120        addIfPresent(root, "updates", BackupSection.Updates)121        addIfPresent(root, "tracks", BackupSection.Tracks)122        addIfPresent(root, "trackPreferences", BackupSection.TrackPreferences)123        addIfPresent(root, "customButtons", BackupSection.CustomButtons)124        addIfPresent(root, "changedParts", BackupSection.ChangedParts)125    }126127    private fun inferMangayomiSections(root: JsonObject): Set<String> = buildSet {128        addTypedSections(root["manga"], legacy = true)129        addIfPresent(root, "chapters", BackupSection.Chapters)130        addIfPresent(root, "categories", BackupSection.Categories)131        addIfPresent(root, "extensions", BackupSection.Sources)132        addIfPresent(root, "history", BackupSection.History)133        addIfPresent(root, "updates", BackupSection.Updates)134        addIfPresent(root, "tracks", BackupSection.Tracks)135        addIfPresent(root, "trackPreferences", BackupSection.TrackPreferences)136        addIfPresent(root, "customButtons", BackupSection.CustomButtons)137        addIfPresent(root, "backupEncryptionPassword", BackupSection.Settings)138    }139140    private fun inferKotatsuSections(entries: Map<String, ByteArray>): Set<String> = buildSet {141        // Unlike the decoded snapshot, ZIP entry names retain presence for142        // empty arrays. Kotatsu only has manga favourites and categories;143        // unsupported sections are deliberately not guessed.144        if ("favourites" in entries) add(BackupSection.Manga)145        if ("categories" in entries) add(BackupSection.Categories)146    }147148    private fun inferSnapshotSections(snapshot: BackupSnapshot): Set<String> = buildSet {149        // Legacy decoder results without source-presence metadata (notably150        // Tachiyomi protobuf) must not turn an empty decoded list into a151        // destructive clear. Formats with raw keys use a dedicated inference152        // path instead.153        if (snapshot.settings != null) add(BackupSection.Settings)154        snapshot.mangas.map { it.itemType }.forEach { add(it.sectionName()) }155        if (snapshot.chapters.isNotEmpty()) add(BackupSection.Chapters)156        if (snapshot.categories.isNotEmpty()) add(BackupSection.Categories)157        if (snapshot.sources.isNotEmpty()) add(BackupSection.Sources)158        if (snapshot.histories.isNotEmpty()) add(BackupSection.History)159        if (snapshot.updates.isNotEmpty()) add(BackupSection.Updates)160        if (snapshot.tracks.isNotEmpty()) add(BackupSection.Tracks)161        if (snapshot.trackPreferences.isNotEmpty()) add(BackupSection.TrackPreferences)162        if (snapshot.customButtons.isNotEmpty()) add(BackupSection.CustomButtons)163        if (snapshot.changedParts.isNotEmpty()) add(BackupSection.ChangedParts)164    }165166    private fun MutableSet<String>.addIfPresent(root: JsonObject, key: String, section: String) {167        if (key in root && root[key] is JsonArray) add(section)168    }169170    private fun MutableSet<String>.addTypedSections(element: JsonElement?, legacy: Boolean = false) {171        val items = element as? JsonArray ?: return172        items.forEach { item ->173            val type = itemTypeFromJson(item, legacy) ?: return@forEach174            add(type.sectionName())175        }176    }177178    private fun itemTypeFromJson(element: JsonElement, legacy: Boolean): DbItemType? {179        val item = element as? JsonObject ?: return null180        val value = item["itemType"] as? JsonPrimitive181        val type = value?.contentOrNull?.let { name -> DbItemType.entries.firstOrNull { it.name == name } }182        if (type != null) return type183        val index = value?.intOrNull184        if (index != null) return DbItemType.entries.getOrNull(index)185        if (legacy) {186            val isManga = (item["isManga"] as? JsonPrimitive)?.booleanOrNull187            if (isManga != null) return if (isManga) DbItemType.Manga else DbItemType.Anime188        }189        return if (value == null) DbItemType.Manga else null190    }191192    private fun DbItemType.sectionName(): String = when (this) {193        DbItemType.Manga -> BackupSection.Manga194        DbItemType.Anime -> BackupSection.Anime195        DbItemType.Novel -> BackupSection.Novel196    }197}198

Search chapters, reference and source filenames.