package eu.friedcutlet.yokan.services.backup import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbSourceCodeLanguage 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.contentOrNull import kotlinx.serialization.json.intOrNull internal class InvalidBackupException : Exception() internal class UnsupportedBackupException : Exception() internal data class DecodedBackup( val snapshot: BackupSnapshot, val includedSections: Set, ) internal fun ByteArray.startsWithEncryptedMagic(): Boolean = size >= 8 && copyOfRange(0, 8).contentEquals("YOKANENC".encodeToByteArray()) /** * Sniffs the container of unencrypted backup bytes and decodes native Yokan, * Mangayomi, Tachiyomi-family and Kotatsu backups into a [DecodedBackup] whose * sections reflect what the source actually contained. */ internal class BackupDecoder(private val gzip: BackupCompression) { private val json = BackupJson suspend fun decode(bytes: ByteArray): DecodedBackup { if (bytes.isEmpty()) throw InvalidBackupException() // Containers first: Mangayomi (Flutter) writes a ZIP with one // `*.backup.db` JSON entry; Kotatsu writes a ZIP with `favourites` / // `categories` JSON entries. Gzip wraps either native Yokan JSON or a // Tachiyomi-family (.tachibk/.proto.gz) protobuf. val raw = when { gzip.looksZipped(bytes) -> { val entries = gzip.unzipEntriesAsync(bytes) if (entries != null && "favourites" in entries) { return DecodedBackup(decodeKotatsuBackup(entries), inferKotatsuSections(entries)) } entries?.values?.firstOrNull() ?: gzip.unzipFirstEntryAsync(bytes) ?: throw InvalidBackupException() } gzip.looksGzipped(bytes) -> gzip.decompressAsync(bytes) else -> bytes } val text = raw.decodeToString() val root = runCatching { json.parseToJsonElement(text) as? JsonObject }.getOrNull() if (root == null) { // Not JSON — Mihon/Tachiyomi/Neko/Aniyomi backups are protobuf. if (looksLikeTachiyomiBackup(raw)) { val snapshot = decodeTachiyomiBackup(raw) return DecodedBackup(snapshot, inferSnapshotSections(snapshot)) } throw InvalidBackupException() } // Mangayomi backups carry a top-level `version` string and use // singular keys (`manga`, `history`, `extensions`). Native Yokan // backups carry `schemaVersion` and plural keys. Adapt the former // to the latter and reuse the same decode path. if ("version" in root && "schemaVersion" !in root) { return DecodedBackup(MangayomiBackupCodec.decode(root), inferMangayomiSections(root)) } return decodeNative(root) } private fun decodeNative(root: JsonObject): DecodedBackup { val schemaVersion = root["schemaVersion"]?.let { (it as? JsonPrimitive)?.intOrNull } ?: if ("schemaVersion" in root) throw InvalidBackupException() else BackupSchemaVersion if (schemaVersion != BackupSchemaVersion) throw UnsupportedBackupException() val sections = parseIncludedSections(root) ?: inferNativeSections(root) val snapshot = runCatching { json.decodeFromJsonElement(BackupSnapshot.serializer(), normalizeNativeBackup(root)) }.getOrElse { throw InvalidBackupException() } return DecodedBackup(snapshot, sections) } private fun normalizeNativeBackup(root: JsonObject): JsonObject { val sources = root["sources"] as? JsonArray ?: return root val normalizedSources = JsonArray( sources.map { element -> val source = element as? JsonObject ?: return@map element val language = (source["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull if (!language.equals("Lua", ignoreCase = true)) return@map source JsonObject(source + ("sourceCodeLanguage" to JsonPrimitive(DbSourceCodeLanguage.JavaScript.name))) }, ) return JsonObject(root + ("sources" to normalizedSources)) } private fun parseIncludedSections(root: JsonObject): Set? { val manifest = root["includedSections"] ?: return null // encodeDefaults writes nullable legacy fields as JSON null. Treat a // null manifest as an old backup with no manifest, not as malformed // manifest data. if (manifest is JsonNull) return null val values = manifest as? JsonArray ?: throw InvalidBackupException() val sections = values.map { val value = (it as? JsonPrimitive)?.takeIf { primitive -> primitive.isString }?.contentOrNull ?: throw InvalidBackupException() if (value !in BackupSection.all) throw UnsupportedBackupException() value }.toSet() return sections } private fun inferNativeSections(root: JsonObject): Set = buildSet { if (root["settings"] != null && root["settings"] !is JsonNull) add(BackupSection.Settings) addTypedSections(root["mangas"]) addIfPresent(root, "chapters", BackupSection.Chapters) addIfPresent(root, "categories", BackupSection.Categories) addIfPresent(root, "sources", BackupSection.Sources) addIfPresent(root, "histories", BackupSection.History) addIfPresent(root, "updates", BackupSection.Updates) addIfPresent(root, "tracks", BackupSection.Tracks) addIfPresent(root, "trackPreferences", BackupSection.TrackPreferences) addIfPresent(root, "customButtons", BackupSection.CustomButtons) addIfPresent(root, "changedParts", BackupSection.ChangedParts) } private fun inferMangayomiSections(root: JsonObject): Set = buildSet { addTypedSections(root["manga"], legacy = true) addIfPresent(root, "chapters", BackupSection.Chapters) addIfPresent(root, "categories", BackupSection.Categories) addIfPresent(root, "extensions", BackupSection.Sources) addIfPresent(root, "history", BackupSection.History) addIfPresent(root, "updates", BackupSection.Updates) addIfPresent(root, "tracks", BackupSection.Tracks) addIfPresent(root, "trackPreferences", BackupSection.TrackPreferences) addIfPresent(root, "customButtons", BackupSection.CustomButtons) addIfPresent(root, "backupEncryptionPassword", BackupSection.Settings) } private fun inferKotatsuSections(entries: Map): Set = buildSet { // Unlike the decoded snapshot, ZIP entry names retain presence for // empty arrays. Kotatsu only has manga favourites and categories; // unsupported sections are deliberately not guessed. if ("favourites" in entries) add(BackupSection.Manga) if ("categories" in entries) add(BackupSection.Categories) } private fun inferSnapshotSections(snapshot: BackupSnapshot): Set = buildSet { // Legacy decoder results without source-presence metadata (notably // Tachiyomi protobuf) must not turn an empty decoded list into a // destructive clear. Formats with raw keys use a dedicated inference // path instead. if (snapshot.settings != null) add(BackupSection.Settings) snapshot.mangas.map { it.itemType }.forEach { add(it.sectionName()) } if (snapshot.chapters.isNotEmpty()) add(BackupSection.Chapters) if (snapshot.categories.isNotEmpty()) add(BackupSection.Categories) if (snapshot.sources.isNotEmpty()) add(BackupSection.Sources) if (snapshot.histories.isNotEmpty()) add(BackupSection.History) if (snapshot.updates.isNotEmpty()) add(BackupSection.Updates) if (snapshot.tracks.isNotEmpty()) add(BackupSection.Tracks) if (snapshot.trackPreferences.isNotEmpty()) add(BackupSection.TrackPreferences) if (snapshot.customButtons.isNotEmpty()) add(BackupSection.CustomButtons) if (snapshot.changedParts.isNotEmpty()) add(BackupSection.ChangedParts) } private fun MutableSet.addIfPresent(root: JsonObject, key: String, section: String) { if (key in root && root[key] is JsonArray) add(section) } private fun MutableSet.addTypedSections(element: JsonElement?, legacy: Boolean = false) { val items = element as? JsonArray ?: return items.forEach { item -> val type = itemTypeFromJson(item, legacy) ?: return@forEach add(type.sectionName()) } } private fun itemTypeFromJson(element: JsonElement, legacy: Boolean): DbItemType? { val item = element as? JsonObject ?: return null val value = item["itemType"] as? JsonPrimitive val type = value?.contentOrNull?.let { name -> DbItemType.entries.firstOrNull { it.name == name } } if (type != null) return type val index = value?.intOrNull if (index != null) return DbItemType.entries.getOrNull(index) if (legacy) { val isManga = (item["isManga"] as? JsonPrimitive)?.booleanOrNull if (isManga != null) return if (isManga) DbItemType.Manga else DbItemType.Anime } return if (value == null) DbItemType.Manga else null } private fun DbItemType.sectionName(): String = when (this) { DbItemType.Manga -> BackupSection.Manga DbItemType.Anime -> BackupSection.Anime DbItemType.Novel -> BackupSection.Novel } }