Yokan / rebuild
Course 1 8624561

Backup, restore and safety snapshots

142 min read + implementationSnapshot 8624561Markdown

Prerequisites: atomic database replacement, files and profile leases. File workbook.

How to write this chapter

Build backup decoding, inspectable restore plans and atomic target-profile application. Opening or decrypting a file never mutates the library; successful Apply is a durable guarded commit.

The 31 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.

Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.

Implementation sequence:

  • Step 1: Define backup/preview models and all format codecs.
  • Step 2: Implement the authenticated password envelope and error distinctions.
  • Step 3: Decode into a preview and merge with explicit identity remapping.
  • Step 4: Take a safety snapshot and atomically apply to the captured target.
  • Step 5: Wire create/open/unlock/preview/apply UI and scheduled exports.
  • Verification: recreate the full test/fixture listings and run the relevant target tasks. [chapter-content-end]: #

Step 1: define formats, options and preview

Implement BackupFormat (Yokan, Mangayomi, Tachiyomi), options, export/result models, restore preview/plan, Replace/Merge and open errors. Options independently select media types and sections. Sensitive tracker credentials require explicit opt-in. Sync credentials are not backup content. Device-local settings must survive restore according to the original policy. Private notes are eligible for native personal backups but excluded by cloud/sync exports.

Recreate native serialization and compression, Mangayomi codecs and external backup decoders, and Tachiyomi/Animetail protobuf import/export. Preserve IDs, enums/status, chapter numbers, credits, notes and section mappings. Tachiyomi protobuf carries manga/anime, omitting novels and unsupported Yokan-only fields; do not silently promise lossless export.

Follow the code

Options choose independent media/sections and whether sensitive account data is eligible. Native, Mangayomi and Tachiyomi formats carry different fields; preserve that lossiness explicitly in mappings rather than filling unsupported fields with misleading defaults. Compression/foreign protobuf parsing is a format boundary with size/error handling. Export policy excludes device-local/sync credentials even if those fields exist in DbSettings.

Write these files in this order:

  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupModels.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupCompression.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupExporter.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/MangayomiBackupCodec.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/TachiyomiBackupEncoder.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/ExternalBackupDecoders.kt
  • composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupCompression.ios.kt
  • composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupCompression.jvm.kt
  • composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/backup/JvmBackupCompression.kt
  • composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupCompression.wasm.kt

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines BackupFormat, BackupOpenResult, Ready, Failure, BackupOpenError, RestoreMode, SafetySnapshot, BackupPlan, withMode, BackupOptions and 9 further declarations.

The source describes its contract as:

Output container for a backup. - [Yokan]: native .json / .json.gz (gzipped JSON). - [Mangayomi]: a .backup ZIP holding one *.backup.db plain-JSON entry, in the schema the old Flutter Mangayomi app reads (version "2", singular keys, enum-as-index). Lets the old app restore Yokan backups. - [Tachiyomi]: an Animetail Backup protobuf Mihon/Aniyomi/Animetail restore; gzipped .tachibk, or raw .proto (SyncYomi wire form) at compression level 0. Novels and Yokan-only data are omitted.

Cross-chapter imports used by this file: DbCategory, DbChangedPart, DbChapter, DbCustomButton, DbHistory, DbItemType. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChangedPart
import eu.friedcutlet.yokan.database.DbChapter
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.DbTrack
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbUpdate
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

/**
 * Output container for a backup.
 *  - [Yokan]: native `.json` / `.json.gz` (gzipped JSON).
 *  - [Mangayomi]: a `.backup` ZIP holding one `*.backup.db` plain-JSON entry,
 *    in the schema the old Flutter Mangayomi app reads (version "2", singular
 *    keys, enum-as-index). Lets the old app restore Yokan backups.
 *  - [Tachiyomi]: an Animetail `Backup` protobuf Mihon/Aniyomi/Animetail restore;
 *    gzipped `.tachibk`, or raw `.proto` (SyncYomi wire form) at compression level 0.
 *    Novels and Yokan-only data are omitted.
 */
enum class BackupFormat { Yokan, Mangayomi, Tachiyomi }

sealed interface BackupOpenResult {
    data class Ready(val plan: BackupPlan) : BackupOpenResult
    data class Failure(val error: BackupOpenError) : BackupOpenResult
}

enum class BackupOpenError {
    PasswordRequired,
    AuthenticationFailed,
    Invalid,
    Unsupported,
}

enum class RestoreMode {
    Replace,
    Merge,
}

@Serializable
data class SafetySnapshot(
    val backupPath: String,
    val createdAt: Long,
    val description: String,
)

class BackupPlan internal constructor(
    val preview: RestorePreview,
    internal val snapshot: BackupSnapshot,
    internal val includedSections: Set<String>,
    internal val resolvedPassword: String? = null,
    val mode: RestoreMode = RestoreMode.Replace,
) {
    fun withMode(newMode: RestoreMode): BackupPlan = BackupPlan(
        preview = preview,
        snapshot = snapshot,
        includedSections = includedSections,
        resolvedPassword = resolvedPassword,
        mode = newMode,
    )
}

data class BackupOptions(
    val includeManga: Boolean = true,
    val includeAnime: Boolean = true,
    val includeNovel: Boolean = true,
    val includeCategories: Boolean = true,
    val includeChapters: Boolean = true,
    val includeHistory: Boolean = true,
    val includeUpdates: Boolean = true,
    val includeSettings: Boolean = true,
    /** Tracker OAuth/credential rows; explicitly opt-in like Mangayomi's option 8. */
    val includeSensitiveSettings: Boolean = false,
    val includeSources: Boolean = true,
    val includeTracks: Boolean = true,
    val includeCustomButtons: Boolean = true,
    val compressionLevel: Int? = null,
    val format: BackupFormat = BackupFormat.Yokan,
    val encrypt: Boolean = false,
    val password: String? = null,
    /** Cloud transports always disable this; native device backups include private text. */
    val includePrivateNotes: Boolean = true,
)

data class BackupResult(
    val fileName: String,
    val bytesWritten: Long,
    val itemCount: Int,
    val path: String? = null,
)

data class BackupExport(
    val fileName: String,
    val bytes: ByteArray,
    val itemCount: Int,
    val format: BackupFormat,
    val compressed: Boolean,
    val contentType: String,
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is BackupExport) return false
        return fileName == other.fileName &&
            bytes.contentEquals(other.bytes) &&
            itemCount == other.itemCount &&
            format == other.format &&
            compressed == other.compressed &&
            contentType == other.contentType
    }

    override fun hashCode(): Int {
        var result = fileName.hashCode()
        result = 31 * result + bytes.contentHashCode()
        result = 31 * result + itemCount
        result = 31 * result + format.hashCode()
        result = 31 * result + compressed.hashCode()
        result = 31 * result + contentType.hashCode()
        return result
    }
}

data class BackupFileEntry(
    val path: String,
    val fileName: String,
    val sizeBytes: Long,
    val lastModified: Long,
    val compressed: Boolean,
)

data class RestorePreview(
    val itemCount: Int,
    val warnings: List<String>,
    val mangaCount: Int = 0,
    val animeCount: Int = 0,
    val novelCount: Int = 0,
    val categoryCount: Int = 0,
    val chapterCount: Int = 0,
    val historyCount: Int = 0,
    val updateCount: Int = 0,
    val sourceCount: Int = 0,
    val trackCount: Int = 0,
    val newSeriesCount: Int = 0,
    val updatedSeriesCount: Int = 0,
    val newChapterCount: Int = 0,
    val conflictingCategories: List<String> = emptyList(),
    val unmatchedSourceNames: List<String> = emptyList(),
)

const val BackupSchemaVersion: Int = 1

/** Native Yokan backup payload; also the decoded form of every external format. */
@Serializable
data class BackupSnapshot(
    val schemaVersion: Int = BackupSchemaVersion,
    val createdAtMillis: Long,
    val sourceApp: String = "yokan-kmp",
    val includedSections: List<String>? = null,
    val settings: DbSettings? = null,
    val mangas: List<DbManga> = emptyList(),
    val chapters: List<DbChapter> = emptyList(),
    val categories: List<DbCategory> = emptyList(),
    val sources: List<DbSource> = emptyList(),
    val histories: List<DbHistory> = emptyList(),
    val updates: List<DbUpdate> = emptyList(),
    val tracks: List<DbTrack> = emptyList(),
    val trackPreferences: List<DbTrackPreference> = emptyList(),
    val customButtons: List<DbCustomButton> = emptyList(),
    val changedParts: List<DbChangedPart> = emptyList(),
    /** False for cloud exports; replacement preserves matching local notes. Legacy backups replace normally. */
    val privateNotesIncluded: Boolean = true,
)

/** Section names of [BackupSnapshot.includedSections]; restore only touches included sections. */
internal object BackupSection {
    const val Settings = "settings"
    const val Manga = "manga"
    const val Anime = "anime"
    const val Novel = "novel"
    const val Chapters = "chapters"
    const val Categories = "categories"
    const val Sources = "sources"
    const val History = "history"
    const val Updates = "updates"
    const val Tracks = "tracks"
    const val TrackPreferences = "trackPreferences"
    const val CustomButtons = "customButtons"
    const val ChangedParts = "changedParts"

    val all = setOf(
        Settings,
        Manga,
        Anime,
        Novel,
        Chapters,
        Categories,
        Sources,
        History,
        Updates,
        Tracks,
        TrackPreferences,
        CustomButtons,
        ChangedParts,
    )
}

/** Title types whose section is included. */
internal fun Set<String>.titleTypes(): Set<DbItemType> = buildSet {
    if (BackupSection.Manga in this@titleTypes) add(DbItemType.Manga)
    if (BackupSection.Anime in this@titleTypes) add(DbItemType.Anime)
    if (BackupSection.Novel in this@titleTypes) add(DbItemType.Novel)
}

/** JSON settings shared by every native backup reader and writer. */
internal val BackupJson = Json {
    ignoreUnknownKeys = true
    encodeDefaults = true
    prettyPrint = false
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines BackupCompression, compress, decompress, looksGzipped, looksZipped, unzipFirstEntry, unzipFirstEntryAsync, unzipEntries, unzipEntriesAsync, decompressAsync and 2 further declarations.

The source describes its contract as:

Mangayomi (Flutter) backups are a ZIP archive containing a single *.backup.db JSON entry. Return that entry's bytes for any ZIP whose local file header (PK\x03\x04) is at offset 0.

package eu.friedcutlet.yokan.services.backup

interface BackupCompression {
    fun compress(data: ByteArray, level: Int): ByteArray
    fun decompress(data: ByteArray): ByteArray
    fun looksGzipped(data: ByteArray): Boolean = data.size >= 2 && data[0] == 0x1F.toByte() && data[1] == 0x8B.toByte()

    /**
     * Mangayomi (Flutter) backups are a ZIP archive containing a single
     * `*.backup.db` JSON entry. Return that entry's bytes for any ZIP whose
     * local file header (PK\x03\x04) is at offset 0.
     */
    fun looksZipped(data: ByteArray): Boolean =
        data.size >= 4 &&
            data[0] == 0x50.toByte() && data[1] == 0x4B.toByte() &&
            (data[2] == 0x03.toByte() || data[2] == 0x05.toByte() || data[2] == 0x07.toByte())

    fun unzipFirstEntry(data: ByteArray): ByteArray? = null

    /** Async counterpart for browser-native ZIP decoders; synchronous platforms use the fast path. */
    suspend fun unzipFirstEntryAsync(data: ByteArray): ByteArray? = unzipFirstEntry(data)

    /** All non-directory entries by name; null on platforms without a ZIP decoder. */
    fun unzipEntries(data: ByteArray): Map<String, ByteArray>? = null

    /** Async counterpart for browser-native ZIP decoders; synchronous platforms use the fast path. */
    suspend fun unzipEntriesAsync(data: ByteArray): Map<String, ByteArray>? = unzipEntries(data)

    /** Async counterpart for browser-native decompression; synchronous platforms use the fast path. */
    suspend fun decompressAsync(data: ByteArray): ByteArray = decompress(data)

    /**
     * Produce a ZIP archive containing a single [entryName] entry holding
     * [data]. Used to write Mangayomi-compatible `.backup` files. Returns null
     * on platforms without a ZIP encoder.
     */
    fun zipSingleEntry(entryName: String, data: ByteArray, level: Int): ByteArray? = null
}

expect fun createPlatformBackupCompression(): BackupCompression

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines BackupExporter, export, payloadOf, BackupOptions.exportedTitleTypes, formatTimestamp.

The source describes its contract as:

Builds the unencrypted backup payload for [BackupOptions] and wraps it in the requested container.

Cross-chapter imports used by this file: DbCategory, DbChapter, DbItemType, DbManga, YokanDatabaseSnapshot, AppLogger. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.util.nowMillis

/** Builds the unencrypted backup payload for [BackupOptions] and wraps it in the requested container. */
internal class BackupExporter(private val gzip: BackupCompression) {
    private val json = BackupJson

    fun export(snapshot: YokanDatabaseSnapshot, options: BackupOptions): BackupExport {
        val payload = payloadOf(snapshot, options)
        val itemCount = listOf(
            payload.mangas.size,
            payload.chapters.size,
            payload.categories.size,
            payload.sources.size,
            payload.histories.size,
            payload.updates.size,
            payload.tracks.size,
            payload.trackPreferences.size,
            payload.customButtons.size,
        ).sum()
        return when (options.format) {
            BackupFormat.Mangayomi -> {
                // Old Flutter app container: a `.backup` ZIP holding one
                // `*.backup.db` plain-JSON entry (version "2", singular keys).
                val base = "mangayomi_${formatTimestamp(payload.createdAtMillis)}"
                val dbJson = MangayomiBackupCodec.encode(payload).encodeToByteArray()
                val level = (options.compressionLevel ?: 6).coerceIn(0, 9)
                val zipped = gzip.zipSingleEntry("$base.backup.db", dbJson, level)
                    ?: error("ZIP backups are not supported on this platform.")
                BackupExport(
                    fileName = "$base.backup",
                    bytes = zipped,
                    itemCount = itemCount,
                    format = options.format,
                    compressed = true,
                    contentType = "application/zip",
                )
            }
            BackupFormat.Yokan -> {
                val bodyBytes = json.encodeToString(BackupSnapshot.serializer(), payload).encodeToByteArray()
                val compress = (options.compressionLevel ?: 0) > 0
                val bytes = if (compress) gzip.compress(bodyBytes, options.compressionLevel ?: 6) else bodyBytes
                val baseName = "yokan-backup-${formatTimestamp(payload.createdAtMillis)}"
                BackupExport(
                    fileName = if (compress) "$baseName.json.gz" else "$baseName.json",
                    bytes = bytes,
                    itemCount = itemCount,
                    format = options.format,
                    compressed = compress,
                    contentType = if (compress) "application/gzip" else "application/json",
                )
            }
            BackupFormat.Tachiyomi -> {
                val novels = payload.mangas.count { it.itemType == DbItemType.Novel }
                if (novels > 0) AppLogger.info("[backup] Tachiyomi export omits $novels novel titles (no Mihon/Aniyomi model)")
                val proto = encodeTachiyomiBackup(payload)
                val level = (options.compressionLevel ?: 6).coerceIn(0, 9)
                // Level 0 is the raw SyncYomi wire form; the web's gzip is a passthrough, which Mihon also reads.
                val bytes = if (level > 0) gzip.compress(proto, level) else proto
                val base = "yokan_${formatTimestamp(payload.createdAtMillis)}"
                BackupExport(
                    fileName = if (level > 0) "$base.tachibk" else "$base.proto",
                    bytes = bytes,
                    itemCount = itemCount,
                    format = options.format,
                    compressed = gzip.looksGzipped(bytes),
                    contentType = "application/octet-stream",
                )
            }
        }
    }

    private fun payloadOf(snapshot: YokanDatabaseSnapshot, options: BackupOptions): BackupSnapshot {
        val exportedTitleTypes = options.exportedTitleTypes()
        val exportedMangas = snapshot.mangas.filter { it.itemType in exportedTitleTypes }
        val exportedCategories = if (options.includeCategories) {
            snapshot.categories.filter { it.forItemType in exportedTitleTypes }
        } else {
            emptyList()
        }
        val exportedCategoryIds = exportedCategories.mapTo(hashSetOf(), DbCategory::id)
        val exportedSources = if (options.includeSources) {
            snapshot.sources.filter { it.itemType in exportedTitleTypes }
        } else {
            emptyList()
        }
        val exportedSourceTypes = exportedSources.associate { it.id to it.itemType }
        val mangas = exportedMangas.map { manga ->
            manga.copy(
                privateNote = manga.privateNote.takeIf { options.includePrivateNotes && options.format == BackupFormat.Yokan }.orEmpty(),
                categories = manga.categories?.filter(exportedCategoryIds::contains),
                sourceId = manga.sourceId?.takeIf { exportedSourceTypes[it] == manga.itemType },
            )
        }
        val exportedTitleIds = mangas.mapTo(hashSetOf(), DbManga::id)
        val chapters = if (options.includeChapters) {
            snapshot.chapters.filter { it.mangaId == null || it.mangaId in exportedTitleIds }
        } else {
            emptyList()
        }
        val exportedChapterIds = chapters.mapTo(hashSetOf(), DbChapter::id)
        val includedSections = buildList {
            if (options.includeSettings) add(BackupSection.Settings)
            if (options.includeManga) add(BackupSection.Manga)
            if (options.includeAnime) add(BackupSection.Anime)
            if (options.includeNovel) add(BackupSection.Novel)
            if (options.includeChapters) add(BackupSection.Chapters)
            if (options.includeCategories) add(BackupSection.Categories)
            if (options.includeSources) add(BackupSection.Sources)
            if (options.includeHistory) add(BackupSection.History)
            if (options.includeUpdates) add(BackupSection.Updates)
            if (options.includeTracks) add(BackupSection.Tracks)
            if (options.includeSensitiveSettings) add(BackupSection.TrackPreferences)
            if (options.includeCustomButtons) add(BackupSection.CustomButtons)
            add(BackupSection.ChangedParts)
        }
        return BackupSnapshot(
            createdAtMillis = nowMillis(),
            privateNotesIncluded = options.includePrivateNotes && options.format == BackupFormat.Yokan,
            settings = snapshot.settings.takeIf { options.includeSettings }?.let { s ->
                val preservePassword = options.includeSensitiveSettings || options.encrypt || options.password != null
                s.copy(
                    backupEncryptionPassword = s.backupEncryptionPassword.takeIf { preservePassword },
                    // Home's API token is installation-local, including cloud and portable exports.
                    features = s.features.copy(
                        home = s.home.copy(tmdbReadAccessToken = "", sourceFeeds = emptyList()),
                        downloads = s.features.downloads.copy(pendingNewChapterIds = emptySet(), consumedChapterIds = emptySet(), manuallyMarkedChapterIds = emptySet()),
                        externalDownloads = eu.friedcutlet.yokan.database.DbExternalDownloads(),
                        discord = s.features.discord.forExport(),
                        torrent = s.features.torrent.forExport(),
                    ),
                )
            },
            includedSections = includedSections,
            mangas = mangas,
            chapters = chapters,
            categories = exportedCategories,
            sources = exportedSources,
            histories = if (options.includeHistory) snapshot.histories.filter {
                it.mangaId == null || it.mangaId in exportedTitleIds
            }.filter {
                it.chapterId == null || it.chapterId in exportedChapterIds
            } else emptyList(),
            updates = if (options.includeUpdates) snapshot.updates.filter {
                it.mangaId == null || it.mangaId in exportedTitleIds
            }.filter {
                it.chapterId == null || it.chapterId in exportedChapterIds
            } else emptyList(),
            tracks = if (options.includeTracks) snapshot.tracks.filter {
                it.mangaId == null || it.mangaId in exportedTitleIds
            } else emptyList(),
            // Tracker preferences carry OAuth tokens — only exported when the
            // user opts into "Sensitive settings" (Mangayomi option 8).
            trackPreferences = if (options.includeSensitiveSettings) snapshot.trackPreferences else emptyList(),
            customButtons = if (options.includeCustomButtons) snapshot.customButtons else emptyList(),
            changedParts = snapshot.changedParts,
        )
    }

    private fun BackupOptions.exportedTitleTypes(): Set<DbItemType> = buildSet {
        if (includeManga) add(DbItemType.Manga)
        if (includeAnime) add(DbItemType.Anime)
        if (includeNovel) add(DbItemType.Novel)
    }

    /** Compact timestamp suitable for filenames (seconds, no separators). */
    private fun formatTimestamp(millis: Long): String = (millis / 1000).toString()
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MangayomiBackupCodec, encode, encodeList, enc, decode, dec, indexToFrom, itemTypeToIndex, adaptArray, stripNulls and 8 further declarations.

The source describes its contract as:

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.

Cross-chapter imports used by this file: DbCategory, DbChapter, DbCustomButton, DbHistory, DbItemType, DbManga. Keep those contracts available as you connect this step.

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<JsonObject>,
            transform: (MutableMap<String, JsonElement>) -> Unit = {},
        ): JsonArray = JsonArray(
            items.map { obj ->
                val m = obj.toMutableMap()
                transform(m)
                JsonObject(m)
            },
        )

        fun <T> enc(serializer: KSerializer<T>, 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 <T> dec(
            key: String,
            serializer: KSerializer<T>,
            transform: (JsonObject) -> JsonObject = { it },
        ): List<T> = 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<String, JsonElement>,
        key: String,
        names: List<String>,
    ) {
        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<String, JsonElement>,
        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<String, JsonElement>,
        key: String,
        names: List<String>,
    ) {
        val idx = (m[key] as? JsonPrimitive)?.intOrNull ?: return
        if (idx in names.indices) m[key] = JsonPrimitive(names[idx])
    }

    private fun mapItemType(
        m: MutableMap<String, JsonElement>,
        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)
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines ProtoWriter, put, rawVarint, tag, varint, bytes, string, float, message, optVarint and 17 further declarations.

The source describes its contract as:

Inverse of [tachiyomiStatus]: SManga/SAnime status constants.

Cross-chapter imports used by this file: DbCategory, DbChapter, DbItemType, DbManga, DbStatus, DbTrack. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.effectiveFiller

// ─────────────────────────────────────────────────────────────────────────────
// Animetail `Backup` protobuf writer (field numbers in ExternalBackupDecoders.kt).
// Mihon reads the manga half (1, 2, 101) and skips the rest; Aniyomi/Animetail
// read anime at 501-503 because 500 (isLegacy) is written as false. Values equal
// to the upstream Kotlin defaults are omitted like kotlinx ProtoBuf does; fields
// without a default upstream (source, url, names, syncId, …) are always written.
// Timestamps follow upstream units: dateAdded/dateUpload/dateFetch/lastRead and
// episode positions in milliseconds, lastModifiedAt in seconds.
// Novels have no Tachiyomi model and are skipped.
// ─────────────────────────────────────────────────────────────────────────────

internal class ProtoWriter {
    private var buffer = ByteArray(256)
    private var size = 0

    private fun put(byte: Int) {
        if (size == buffer.size) buffer = buffer.copyOf(size * 2)
        buffer[size++] = byte.toByte()
    }

    private fun rawVarint(value: Long) {
        var v = value
        while (v and 0x7FL.inv() != 0L) {
            put(((v and 0x7F) or 0x80).toInt())
            v = v ushr 7
        }
        put(v.toInt())
    }

    private fun tag(field: Int, wire: Int) = rawVarint(((field shl 3) or wire).toLong())

    fun varint(field: Int, value: Long) {
        tag(field, 0)
        rawVarint(value)
    }

    fun bytes(field: Int, value: ByteArray) {
        tag(field, 2)
        rawVarint(value.size.toLong())
        value.forEach { put(it.toInt()) }
    }

    fun string(field: Int, value: String) = bytes(field, value.encodeToByteArray())

    fun float(field: Int, value: Float) {
        tag(field, 5)
        val bits = value.toRawBits()
        repeat(4) { put(bits ushr (8 * it)) }
    }

    fun message(field: Int, block: ProtoWriter.() -> Unit) = bytes(field, ProtoWriter().apply(block).toByteArray())

    fun optVarint(field: Int, value: Long) { if (value != 0L) varint(field, value) }
    fun optTrue(field: Int, value: Boolean) { if (value) varint(field, 1) }
    fun optString(field: Int, value: String?) { if (!value.isNullOrEmpty()) string(field, value) }
    fun optFloat(field: Int, value: Float) { if (value != 0f) float(field, value) }

    fun toByteArray(): ByteArray = buffer.copyOf(size)
}

internal fun encodeTachiyomiBackup(payload: BackupSnapshot): ByteArray {
    val chaptersByTitle = payload.chapters.groupBy { it.mangaId }
    val chapterById = payload.chapters.associateBy { it.id }
    val historiesByTitle = payload.histories.groupBy { it.mangaId }
    val tracksByTitle = payload.tracks.groupBy { it.mangaId }
    val sourceById = payload.sources.associateBy { it.id }

    // Upstream links titles to categories by `order`; re-number per type so orders are unique.
    fun categoriesOf(type: DbItemType): List<DbCategory> = payload.categories
        .filter { it.forItemType == type }
        .sortedWith(compareBy<DbCategory> { it.position ?: Int.MAX_VALUE }.thenBy { it.id })

    fun sourceIdOf(manga: DbManga): Long = manga.sourceId?.takeIf { it in sourceById }
        // ponytail: hash of the source name for titles without an exported source row; collides only on name hash collisions.
        ?: (manga.source.orEmpty().hashCode().toLong() and 0x7FFF_FFFFL)

    fun ProtoWriter.entry(manga: DbManga, anime: Boolean, categoryOrders: Map<Long, Long>) {
        varint(1, sourceIdOf(manga))
        string(2, manga.link.orEmpty())
        optString(3, manga.name)
        optString(4, manga.artist)
        optString(5, manga.author)
        optString(6, manga.description)
        manga.genre.orEmpty().forEach { string(7, it) }
        optVarint(8, tachiyomiStatusIndex(manga.status, anime).toLong())
        optString(9, manga.imageUrl)
        optVarint(13, manga.dateAdded ?: 0)
        chaptersByTitle[manga.id].orEmpty().forEachIndexed { index, item ->
            message(16) { writeChapter(item, index, anime) }
        }
        manga.categories.orEmpty().mapNotNull(categoryOrders::get).forEach { varint(17, it) }
        tracksByTitle[manga.id].orEmpty().forEach { writeTrack(it, anime) }
        if (!manga.favorite) varint(100, 0)
        historiesByTitle[manga.id].orEmpty().forEach { history ->
            val url = history.chapterId?.let(chapterById::get)?.url ?: return@forEach
            val readAt = history.date?.toLongOrNull() ?: return@forEach
            message(104) {
                string(1, url)
                varint(2, readAt)
                optVarint(3, (history.readingTimeSeconds ?: 0) * 1000L)
            }
        }
        optVarint(106, (manga.lastUpdate ?: 0) / 1000)
    }

    fun ProtoWriter.section(type: DbItemType, titleField: Int, categoryField: Int, sourceField: Int) {
        val anime = type == DbItemType.Anime
        val categories = categoriesOf(type)
        val orders = categories.withIndex().associate { (index, category) -> category.id to index.toLong() }
        val titles = payload.mangas.filter { it.itemType == type }
        titles.forEach { manga -> message(titleField) { entry(manga, anime, orders) } }
        categories.forEachIndexed { index, category ->
            message(categoryField) {
                string(1, category.name)
                optVarint(2, index.toLong())
            }
        }
        titles.associate { sourceIdOf(it) to (it.source ?: it.sourceId?.let(sourceById::get)?.name).orEmpty() }
            .forEach { (id, name) ->
                message(sourceField) {
                    optString(1, name)
                    varint(2, id)
                }
            }
    }

    return ProtoWriter().apply {
        section(DbItemType.Manga, titleField = 1, categoryField = 2, sourceField = 101)
        varint(500, 0) // isLegacy = false: anime lives at 501-503.
        section(DbItemType.Anime, titleField = 501, categoryField = 502, sourceField = 503)
    }.toByteArray()
}

private fun ProtoWriter.writeChapter(chapter: DbChapter, index: Int, anime: Boolean) {
    string(1, chapter.url)
    string(2, chapter.name.orEmpty())
    optString(3, chapter.scanlator)
    optTrue(4, chapter.isRead)
    optTrue(5, chapter.isBookmarked)
    val progress = chapter.lastPageRead.toLongOrNull() ?: 0
    // Yokan pages are 1-based; Mihon stores the 0-based page index. Episodes are milliseconds on both sides.
    optVarint(6, if (anime) progress else (progress - 1).coerceAtLeast(0))
    optVarint(7, chapter.fetchedAt)
    optVarint(8, chapter.dateUpload.toLongOrNull() ?: 0)
    optFloat(9, chapter.number?.toFloat() ?: 0f)
    optVarint(10, index.toLong())
    optVarint(11, chapter.updatedAt / 1000)
    if (anime) {
        optTrue(501, chapter.effectiveFiller)
        optString(502, chapter.description)
        optString(503, chapter.thumbnailUrl)
    }
}

private fun ProtoWriter.writeTrack(track: DbTrack, anime: Boolean) {
    val tracker = TachiyomiTrackers.firstOrNull { it.yokanId == track.syncId } ?: return
    message(18) {
        varint(1, tracker.id.toLong())
        varint(2, track.libraryId ?: 0)
        optString(4, track.trackingUrl)
        optString(5, track.title)
        optFloat(6, (track.lastChapterRead ?: 0).toFloat())
        optVarint(7, (track.totalChapter ?: 0).toLong())
        optFloat(8, (track.score ?: 0).toFloat())
        optVarint(9, tracker.code(track.status, anime).toLong())
        optVarint(10, track.startedReadingDate ?: 0)
        optVarint(11, track.finishedReadingDate ?: 0)
        optVarint(100, track.mediaId ?: 0)
    }
}

/** Inverse of [tachiyomiStatus]: SManga/SAnime status constants. */
internal fun tachiyomiStatusIndex(status: DbStatus, anime: Boolean): Int = when (status) {
    DbStatus.Ongoing -> 1
    DbStatus.Completed -> 2
    DbStatus.Licensed -> 3
    DbStatus.PublishingFinished -> 4
    DbStatus.Canceled -> 5
    DbStatus.OnHiatus -> 6
    DbStatus.Upcoming -> if (anime) 7 else 0
    DbStatus.Unknown -> 0
}

/**
 * Yokan tracker id ↔ Animetail `TrackerManager` id with that tracker's status
 * constants. Statuses are listed in their reading flavour; anime-only codes
 * (MAL/AniList/Kitsu `WATCHING = 11`, …) are listed explicitly.
 */
internal class TachiyomiTracker(val yokanId: Int, val id: Int, private val statuses: List<Pair<DbTrackStatus, Int>>) {
    fun code(status: DbTrackStatus, anime: Boolean): Int {
        val own = status.flavour(anime)
        val reading = status.flavour(anime = false)
        return listOf(own, own.withoutRepeat(), reading, reading.withoutRepeat())
            .firstNotNullOfOrNull { candidate -> statuses.firstOrNull { it.first == candidate }?.second } ?: 0
    }

    fun status(code: Int, anime: Boolean): DbTrackStatus =
        (statuses.firstOrNull { it.second == code }?.first ?: DbTrackStatus.Reading).flavour(anime)
}

private fun DbTrackStatus.flavour(anime: Boolean): DbTrackStatus = when (this) {
    DbTrackStatus.Reading, DbTrackStatus.Watching -> if (anime) DbTrackStatus.Watching else DbTrackStatus.Reading
    DbTrackStatus.PlanToRead, DbTrackStatus.PlanToWatch -> if (anime) DbTrackStatus.PlanToWatch else DbTrackStatus.PlanToRead
    DbTrackStatus.ReReading, DbTrackStatus.ReWatching -> if (anime) DbTrackStatus.ReWatching else DbTrackStatus.ReReading
    DbTrackStatus.Completed, DbTrackStatus.OnHold, DbTrackStatus.Dropped -> this
}

private fun DbTrackStatus.withoutRepeat(): DbTrackStatus = when (this) {
    DbTrackStatus.ReReading -> DbTrackStatus.Reading
    DbTrackStatus.ReWatching -> DbTrackStatus.Watching
    else -> this
}

private val R = DbTrackStatus.Reading
private val C = DbTrackStatus.Completed
private val H = DbTrackStatus.OnHold
private val D = DbTrackStatus.Dropped
private val P = DbTrackStatus.PlanToRead
private val RR = DbTrackStatus.ReReading

internal val TachiyomiTrackers: List<TachiyomiTracker> = listOf(
    TachiyomiTracker(1, 1, listOf(R to 1, C to 2, H to 3, D to 4, P to 6, RR to 7, DbTrackStatus.Watching to 11, DbTrackStatus.PlanToWatch to 16, DbTrackStatus.ReWatching to 17)), // MyAnimeList
    TachiyomiTracker(2, 2, listOf(R to 1, C to 2, H to 3, D to 4, P to 5, RR to 6, DbTrackStatus.Watching to 11, DbTrackStatus.PlanToWatch to 15, DbTrackStatus.ReWatching to 16)), // AniList
    TachiyomiTracker(3, 3, listOf(R to 1, C to 2, H to 3, D to 4, P to 5, DbTrackStatus.Watching to 11, DbTrackStatus.PlanToWatch to 15)), // Kitsu
    TachiyomiTracker(4, 101, listOf(R to 1, C to 2, H to 3, D to 4, P to 5)), // Simkl
    TachiyomiTracker(5, 201, listOf(R to 1, C to 2, H to 3, D to 4, P to 5)), // Trakt
    TachiyomiTracker(10, 7, listOf(R to 0, P to 1, C to 2, D to 3, H to 4)), // MangaUpdates
    TachiyomiTracker(11, 4, listOf(R to 1, C to 2, H to 3, D to 4, P to 5, RR to 6)), // Shikimori
    TachiyomiTracker(12, 5, listOf(P to 1, C to 2, R to 3, H to 4, D to 5)), // Bangumi
    TachiyomiTracker(13, 10, listOf(R to 0, C to 1, H to 2, D to 3, P to 4, RR to 5)), // Hikka
    TachiyomiTracker(14, 11, listOf(R to 1, C to 2, H to 3, D to 4, P to 5, RR to 6)), // MangaBaka
    TachiyomiTracker(15, 200, listOf(DbTrackStatus.Watching to 11, C to 2, H to 3, D to 4, DbTrackStatus.PlanToWatch to 15, DbTrackStatus.ReWatching to 16)), // TMDB
    TachiyomiTracker(20, 6, listOf(P to 1, R to 2, C to 3)), // Komga
    TachiyomiTracker(21, 8, listOf(P to 1, R to 2, C to 3)), // Kavita
    TachiyomiTracker(22, 9, listOf(P to 1, R to 2, C to 3)), // Suwayomi
    TachiyomiTracker(23, 102, listOf(P to 1, R to 2, C to 3)), // Jellyfin
)

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines ProtoReader, hasMore, readVarint, readTag, readBytes, readString, readFixed32, skip, ProtoEntry, ProtoChapter and 19 further declarations.

The source describes its contract as:

True when [bytes] parse as a Tachiyomi-family protobuf backup with content.

Cross-chapter imports used by this file: DbCategory, DbChapter, DbHistory, DbItemType, DbManga, DbStatus. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.database.DbTrack
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.longOrNull

// ─────────────────────────────────────────────────────────────────────────────
// Tachiyomi-family (.tachibk / .proto.gz) — Mihon, Tachiyomi, Neko, Aniyomi.
// The wire format is a plain protobuf `Backup` message; only the fields the
// restore mapping needs are decoded, everything else is skipped by wire type.
//
// Backup:        1=BackupManga*, 2=BackupCategory*, 101=BackupSource*,
//                3/501=BackupAnime*, 4/502=anime categories, 103/503=anime sources,
//                500=isLegacy (Animetail writes false and uses 501-503)
// BackupManga:   1=source(id) 2=url 3=title 4=artist 5=author 6=description
//                7=genre* 8=status 9=thumbnailUrl 13=dateAdded(ms) 16=BackupChapter*
//                17=categories(order)* 18=BackupTracking* 100=favorite(default true)
//                104=BackupHistory* 106=lastModifiedAt(s)
// BackupChapter: 1=url 2=name 3=scanlator 4=read 5=bookmark 6=lastPageRead(0-based)
//                7=dateFetch(ms) 8=dateUpload(ms) 9=chapterNumber(float) 10=sourceOrder
//                11=lastModifiedAt(s)
// BackupAnime:   same numbering with 16=BackupEpisode* (4=seen 6=lastSecondSeen(ms)
//                501=fillermark 502=summary 503=previewUrl)
// BackupHistory: 1=url 2=lastRead(ms) 3=readDuration(ms)
// BackupTracking:1=syncId 2=libraryId 3=mediaIdInt 4=trackingUrl 5=title
//                6=lastChapterRead(float) 7=totalChapters 8=score(float) 9=status
//                10=startedReadingDate 11=finishedReadingDate 100=mediaId
// BackupCategory:1=name 2=order   BackupSource: 1=name 2=sourceId
// ─────────────────────────────────────────────────────────────────────────────

internal class ProtoReader(private val data: ByteArray, private var pos: Int = 0, private val end: Int = data.size) {
    fun hasMore(): Boolean = pos < end

    fun readVarint(): Long {
        var shift = 0
        var result = 0L
        while (pos < end) {
            val byte = data[pos++].toInt()
            result = result or ((byte and 0x7F).toLong() shl shift)
            if (byte and 0x80 == 0) return result
            shift += 7
            if (shift >= 64) error("Malformed varint")
        }
        error("Truncated varint")
    }

    fun readTag(): Pair<Int, Int> {
        val tag = readVarint()
        return (tag ushr 3).toInt() to (tag and 0x7).toInt()
    }

    fun readBytes(): ByteArray {
        val length = readVarint().toInt()
        if (length < 0 || pos + length > end) error("Truncated length-delimited field")
        val out = data.copyOfRange(pos, pos + length)
        pos += length
        return out
    }

    fun readString(): String = readBytes().decodeToString()

    fun readFixed32(): Int {
        if (pos + 4 > end) error("Truncated fixed32")
        var value = 0
        repeat(4) { value = value or ((data[pos++].toInt() and 0xFF) shl (8 * it)) }
        return value
    }

    fun skip(wireType: Int) {
        when (wireType) {
            0 -> readVarint()
            1 -> pos += 8
            2 -> pos += readVarint().toInt()
            5 -> pos += 4
            else -> error("Unsupported wire type $wireType")
        }
        if (pos > end) error("Truncated field")
    }
}

private class ProtoEntry(
    var sourceId: Long = 0,
    var url: String = "",
    var title: String = "",
    var artist: String = "",
    var author: String = "",
    var description: String = "",
    val genre: MutableList<String> = mutableListOf(),
    var status: Int = 0,
    var thumbnailUrl: String = "",
    var dateAdded: Long = 0,
    var lastModifiedAt: Long = 0,
    var favorite: Boolean = true,
    val categoryOrders: MutableList<Long> = mutableListOf(),
    val chapters: MutableList<ProtoChapter> = mutableListOf(),
    val history: MutableList<ProtoHistory> = mutableListOf(),
    val tracks: MutableList<ProtoTrack> = mutableListOf(),
)

private class ProtoChapter(
    var url: String = "",
    var name: String = "",
    var scanlator: String = "",
    var read: Boolean = false,
    var bookmark: Boolean = false,
    var lastProgress: Long = 0,
    var dateFetch: Long = 0,
    var dateUpload: Long = 0,
    var number: Float = 0f,
    var lastModifiedAt: Long = 0,
    var filler: Boolean = false,
    var summary: String = "",
    var previewUrl: String = "",
)

private class ProtoHistory(var url: String = "", var lastRead: Long = 0, var readDuration: Long = 0)

private class ProtoTrack(
    var syncId: Int = 0,
    var libraryId: Long = 0,
    var mediaId: Long = 0,
    var trackingUrl: String = "",
    var title: String = "",
    var lastChapterRead: Float = 0f,
    var totalChapters: Int = 0,
    var score: Float = 0f,
    var status: Int = 0,
    var startedAt: Long = 0,
    var finishedAt: Long = 0,
)

private class ProtoBackup(
    val manga: MutableList<ProtoEntry> = mutableListOf(),
    val anime: MutableList<ProtoEntry> = mutableListOf(),
    val categories: MutableList<Pair<String, Long>> = mutableListOf(),
    val animeCategories: MutableList<Pair<String, Long>> = mutableListOf(),
    val sources: MutableMap<Long, String> = mutableMapOf(),
    val animeSources: MutableMap<Long, String> = mutableMapOf(),
)

/** True when [bytes] parse as a Tachiyomi-family protobuf backup with content. */
internal fun looksLikeTachiyomiBackup(bytes: ByteArray): Boolean =
    runCatching { parseTachiyomiProto(bytes) }.getOrNull()
        ?.let { it.manga.isNotEmpty() || it.anime.isNotEmpty() } == true

internal fun decodeTachiyomiBackup(bytes: ByteArray): BackupSnapshot {
    val backup = parseTachiyomiProto(bytes)
    if (backup.manga.isEmpty() && backup.anime.isEmpty()) error("Backup contains no entries.")
    var nextCategoryId = 1L
    var nextMangaId = 1L
    var nextChapterId = 1L
    var nextHistoryId = 1L
    var nextTrackId = 1L
    val categories = mutableListOf<DbCategory>()
    val mangas = mutableListOf<DbManga>()
    val chapters = mutableListOf<DbChapter>()
    val histories = mutableListOf<DbHistory>()
    val tracks = mutableListOf<DbTrack>()

    fun import(
        entries: List<ProtoEntry>,
        cats: List<Pair<String, Long>>,
        sources: Map<Long, String>,
        itemType: DbItemType,
    ) {
        if (entries.isEmpty()) return
        val categoryIdByOrder = cats.associate { (name, order) ->
            val category = DbCategory(
                id = nextCategoryId++,
                name = name,
                forItemType = itemType,
                position = order.toInt(),
            )
            categories += category
            order to category.id
        }
        entries.forEach { entry ->
            val mangaId = nextMangaId++
            mangas += DbManga(
                id = mangaId,
                name = entry.title,
                link = entry.url,
                imageUrl = entry.thumbnailUrl.takeIf(String::isNotBlank),
                description = entry.description.takeIf(String::isNotBlank),
                author = entry.author.takeIf(String::isNotBlank),
                artist = entry.artist.takeIf(String::isNotBlank),
                status = tachiyomiStatus(entry.status, itemType),
                itemType = itemType,
                genre = entry.genre.takeIf(List<String>::isNotEmpty),
                favorite = entry.favorite,
                source = sources[entry.sourceId] ?: "Unknown",
                lang = "en",
                dateAdded = entry.dateAdded,
                lastUpdate = entry.lastModifiedAt * 1000,
                categories = entry.categoryOrders.mapNotNull(categoryIdByOrder::get).takeIf(List<Long>::isNotEmpty),
            )
            val anime = itemType == DbItemType.Anime
            val chapterIdByUrl = mutableMapOf<String, Long>()
            var latest: Pair<Long, Long>? = null // chapterId to lastModifiedMillis
            entry.chapters.forEach { chapter ->
                val chapterId = nextChapterId++
                chapterIdByUrl.getOrPut(chapter.url) { chapterId }
                chapters += DbChapter(
                    id = chapterId,
                    mangaId = mangaId,
                    name = chapter.name,
                    url = chapter.url,
                    dateUpload = chapter.dateUpload.toString(),
                    scanlator = chapter.scanlator,
                    isBookmarked = chapter.bookmark,
                    isRead = chapter.read,
                    // Mihon pages are 0-based, Yokan's 1-based; episode positions are milliseconds on both sides.
                    lastPageRead = when {
                        !anime -> (chapter.lastProgress + 1).toString()
                        chapter.lastProgress != 0L -> chapter.lastProgress.toString()
                        else -> ""
                    },
                    fetchedAt = chapter.dateFetch,
                    number = chapter.number.takeIf { it != 0f }?.toDouble(),
                    isFiller = chapter.filler,
                    description = chapter.summary.takeIf(String::isNotBlank),
                    thumbnailUrl = chapter.previewUrl.takeIf(String::isNotBlank),
                )
                val modified = chapter.lastModifiedAt * 1000
                if (chapter.read && (latest == null || latest.second < modified)) {
                    latest = chapterId to modified
                }
            }
            // Yokan keeps one history row per title: the newest upstream entry, with the summed read time.
            val recorded = entry.history.maxByOrNull { it.lastRead }
                ?.let { newest -> chapterIdByUrl[newest.url]?.let { it to newest.lastRead } }
            (recorded ?: latest)?.let { (chapterId, date) ->
                histories += DbHistory(
                    id = nextHistoryId++,
                    mangaId = mangaId,
                    chapterId = chapterId,
                    itemType = itemType,
                    date = date.toString(),
                    readingTimeSeconds = recorded?.let { (entry.history.sumOf { it.readDuration } / 1000).toInt() }?.takeIf { it > 0 },
                )
            }
            entry.tracks.forEach { track ->
                val tracker = TachiyomiTrackers.firstOrNull { it.id == track.syncId } ?: return@forEach
                tracks += DbTrack(
                    id = nextTrackId++,
                    libraryId = track.libraryId.takeIf { it != 0L },
                    mediaId = track.mediaId,
                    mangaId = mangaId,
                    syncId = tracker.yokanId,
                    title = track.title.takeIf(String::isNotBlank),
                    lastChapterRead = track.lastChapterRead.toInt(),
                    totalChapter = track.totalChapters,
                    score = track.score.toInt(),
                    status = tracker.status(track.status, anime),
                    startedReadingDate = track.startedAt.takeIf { it != 0L },
                    finishedReadingDate = track.finishedAt.takeIf { it != 0L },
                    trackingUrl = track.trackingUrl.takeIf(String::isNotBlank),
                    itemType = itemType,
                )
            }
        }
    }

    import(backup.manga, backup.categories, backup.sources, DbItemType.Manga)
    import(
        backup.anime,
        backup.animeCategories.ifEmpty { backup.categories },
        backup.animeSources.ifEmpty { backup.sources },
        DbItemType.Anime,
    )
    return BackupSnapshot(
        createdAtMillis = eu.friedcutlet.yokan.util.nowMillis(),
        sourceApp = "tachiyomi-family",
        mangas = mangas,
        chapters = chapters,
        categories = categories,
        histories = histories,
        tracks = tracks,
    )
}

private fun parseTachiyomiProto(bytes: ByteArray): ProtoBackup {
    val backup = ProtoBackup()
    val reader = ProtoReader(bytes)
    while (reader.hasMore()) {
        val (field, wire) = reader.readTag()
        when {
            field == 1 && wire == 2 -> backup.manga += parseEntry(reader.readBytes())
            field == 2 && wire == 2 -> backup.categories += parseCategory(reader.readBytes())
            field == 101 && wire == 2 -> parseSource(reader.readBytes())?.let { backup.sources[it.second] = it.first }
            (field == 3 || field == 501) && wire == 2 -> backup.anime += parseEntry(reader.readBytes())
            (field == 4 || field == 502) && wire == 2 -> backup.animeCategories += parseCategory(reader.readBytes())
            (field == 103 || field == 503) && wire == 2 ->
                parseSource(reader.readBytes())?.let { backup.animeSources[it.second] = it.first }
            else -> reader.skip(wire)
        }
    }
    return backup
}

private fun parseEntry(bytes: ByteArray): ProtoEntry {
    val entry = ProtoEntry()
    val reader = ProtoReader(bytes)
    while (reader.hasMore()) {
        val (field, wire) = reader.readTag()
        when (field) {
            1 -> entry.sourceId = reader.readVarint()
            2 -> entry.url = reader.readString()
            3 -> entry.title = reader.readString()
            4 -> entry.artist = reader.readString()
            5 -> entry.author = reader.readString()
            6 -> entry.description = reader.readString()
            7 -> entry.genre += reader.readString()
            8 -> entry.status = reader.readVarint().toInt()
            9 -> entry.thumbnailUrl = reader.readString()
            13 -> entry.dateAdded = reader.readVarint()
            16 -> entry.chapters += parseChapter(reader.readBytes())
            17 -> if (wire == 2) {
                // Packed repeated int64.
                val packed = ProtoReader(reader.readBytes())
                while (packed.hasMore()) entry.categoryOrders += packed.readVarint()
            } else {
                entry.categoryOrders += reader.readVarint()
            }
            18 -> entry.tracks += parseTrack(reader.readBytes())
            100 -> entry.favorite = reader.readVarint() != 0L
            104 -> entry.history += parseHistory(reader.readBytes())
            106 -> entry.lastModifiedAt = reader.readVarint()
            else -> reader.skip(wire)
        }
    }
    return entry
}

private fun parseChapter(bytes: ByteArray): ProtoChapter {
    val chapter = ProtoChapter()
    val reader = ProtoReader(bytes)
    while (reader.hasMore()) {
        val (field, wire) = reader.readTag()
        when (field) {
            1 -> chapter.url = reader.readString()
            2 -> chapter.name = reader.readString()
            3 -> chapter.scanlator = reader.readString()
            4 -> chapter.read = reader.readVarint() != 0L
            5 -> chapter.bookmark = reader.readVarint() != 0L
            6 -> chapter.lastProgress = reader.readVarint()
            7 -> chapter.dateFetch = reader.readVarint()
            8 -> chapter.dateUpload = reader.readVarint()
            9 -> if (wire == 5) chapter.number = Float.fromBits(reader.readFixed32()) else reader.skip(wire)
            11 -> chapter.lastModifiedAt = reader.readVarint()
            501 -> chapter.filler = reader.readVarint() != 0L
            502 -> chapter.summary = reader.readString()
            503 -> chapter.previewUrl = reader.readString()
            else -> reader.skip(wire)
        }
    }
    return chapter
}

private fun parseHistory(bytes: ByteArray): ProtoHistory {
    val history = ProtoHistory()
    val reader = ProtoReader(bytes)
    while (reader.hasMore()) {
        val (field, wire) = reader.readTag()
        when (field) {
            1 -> history.url = reader.readString()
            2 -> history.lastRead = reader.readVarint()
            3 -> history.readDuration = reader.readVarint()
            else -> reader.skip(wire)
        }
    }
    return history
}

private fun parseTrack(bytes: ByteArray): ProtoTrack {
    val track = ProtoTrack()
    val reader = ProtoReader(bytes)
    fun float(wire: Int): Float = if (wire == 5) Float.fromBits(reader.readFixed32()) else 0f.also { reader.skip(wire) }
    while (reader.hasMore()) {
        val (field, wire) = reader.readTag()
        when (field) {
            1 -> track.syncId = reader.readVarint().toInt()
            2 -> track.libraryId = reader.readVarint()
            3 -> reader.readVarint().takeIf { it != 0L && track.mediaId == 0L }?.let { track.mediaId = it }
            4 -> track.trackingUrl = reader.readString()
            5 -> track.title = reader.readString()
            6 -> track.lastChapterRead = float(wire)
            7 -> track.totalChapters = reader.readVarint().toInt()
            8 -> track.score = float(wire)
            9 -> track.status = reader.readVarint().toInt()
            10 -> track.startedAt = reader.readVarint()
            11 -> track.finishedAt = reader.readVarint()
            100 -> reader.readVarint().takeIf { it != 0L }?.let { track.mediaId = it }
            else -> reader.skip(wire)
        }
    }
    return track
}

private fun parseCategory(bytes: ByteArray): Pair<String, Long> {
    var name = ""
    var order = 0L
    val reader = ProtoReader(bytes)
    while (reader.hasMore()) {
        val (field, wire) = reader.readTag()
        when (field) {
            1 -> name = reader.readString()
            2 -> order = reader.readVarint()
            else -> reader.skip(wire)
        }
    }
    return name to order
}

private fun parseSource(bytes: ByteArray): Pair<String, Long>? {
    var name = ""
    var sourceId = 0L
    val reader = ProtoReader(bytes)
    while (reader.hasMore()) {
        val (field, wire) = reader.readTag()
        when (field) {
            1 -> name = reader.readString()
            2 -> sourceId = reader.readVarint()
            else -> reader.skip(wire)
        }
    }
    return if (name.isBlank()) null else name to sourceId
}

private fun tachiyomiStatus(index: Int, itemType: DbItemType): DbStatus = when (index) {
    1 -> DbStatus.Ongoing
    2 -> DbStatus.Completed
    3 -> DbStatus.Licensed
    4 -> DbStatus.PublishingFinished
    5 -> DbStatus.Canceled
    6 -> DbStatus.OnHiatus
    7 -> if (itemType == DbItemType.Anime) DbStatus.Upcoming else DbStatus.Unknown
    else -> DbStatus.Unknown
}

// ─────────────────────────────────────────────────────────────────────────────
// Kotatsu — a ZIP with JSON-array entries named `favourites`, `categories`,
// and optionally `history`. Each favourite wraps a `manga` object.
// ─────────────────────────────────────────────────────────────────────────────

internal fun decodeKotatsuBackup(entries: Map<String, ByteArray>): BackupSnapshot {
    val json = Json { ignoreUnknownKeys = true; isLenient = true }
    fun array(name: String): JsonArray? = entries[name]
        ?.let { runCatching { json.parseToJsonElement(it.decodeToString()) as? JsonArray }.getOrNull() }

    fun JsonObject.string(key: String): String? = (get(key) as? JsonPrimitive)?.contentOrNull
    fun JsonObject.long(key: String): Long? = (get(key) as? JsonPrimitive)?.longOrNull

    var nextCategoryId = 1L
    val categories = array("categories").orEmpty().mapNotNull { element ->
        val obj = element as? JsonObject ?: return@mapNotNull null
        val name = obj.string("title") ?: return@mapNotNull null
        DbCategory(
            id = obj.long("category_id") ?: nextCategoryId++,
            name = name,
            forItemType = DbItemType.Manga,
            position = obj.long("sort_key")?.toInt(),
        )
    }
    var nextMangaId = 1L
    val mangas = array("favourites").orEmpty().mapNotNull { element ->
        val obj = element as? JsonObject ?: return@mapNotNull null
        val manga = obj["manga"] as? JsonObject ?: return@mapNotNull null
        val title = manga.string("title") ?: return@mapNotNull null
        DbManga(
            id = nextMangaId++,
            name = title,
            link = manga.string("public_url") ?: manga.string("url"),
            imageUrl = manga.string("cover_url"),
            author = manga.string("author"),
            itemType = DbItemType.Manga,
            favorite = true,
            source = manga.string("source") ?: "Unknown",
            genre = (manga["tags"] as? JsonArray)
                ?.mapNotNull { (it as? JsonObject)?.string("title") }
                ?.takeIf(List<String>::isNotEmpty),
            categories = obj.long("category_id")?.let(::listOf),
            dateAdded = obj.long("created_at"),
        )
    }
    if (mangas.isEmpty()) error("Kotatsu backup contains no favourites.")
    return BackupSnapshot(
        createdAtMillis = eu.friedcutlet.yokan.util.nowMillis(),
        sourceApp = "kotatsu",
        mangas = mangas,
        categories = categories,
    )
}

Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupCompression.ios.kt

Create this path in your reconstruction project. Source set: iosMain. Exact file download.

The implementation below defines createPlatformBackupCompression, IosBackupCompression, compress, decompress, unzipFirstEntry, unzipEntries, zipSingleEntry, gzipDeflate, gzipInflate.

The source describes its contract as:

zlib-backed compression for backups. ZIP reading reuses [IosZipArchive] (the same reader CBZ/EPUB support uses), so Mangayomi .backup archives restore on iOS like they do on the JVM platforms. ZIP writing emits a stored archive via [buildStoredZip]; the old Flutter app inflates entries regardless of method, so skipping deflate only costs file size.

Cross-chapter imports used by this file: IosZipArchive, buildStoredZip. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.services.files.IosZipArchive
import eu.friedcutlet.yokan.services.files.buildStoredZip
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.alloc
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.usePinned
import platform.zlib.Z_BUF_ERROR
import platform.zlib.Z_DEFAULT_STRATEGY
import platform.zlib.Z_DEFLATED
import platform.zlib.Z_FINISH
import platform.zlib.Z_NO_FLUSH
import platform.zlib.Z_OK
import platform.zlib.Z_STREAM_END
import platform.zlib.deflate
import platform.zlib.deflateBound
import platform.zlib.deflateEnd
import platform.zlib.deflateInit2
import platform.zlib.inflate
import platform.zlib.inflateEnd
import platform.zlib.inflateInit2
import platform.zlib.z_stream

actual fun createPlatformBackupCompression(): BackupCompression = IosBackupCompression

/**
 * zlib-backed compression for backups. ZIP reading reuses [IosZipArchive]
 * (the same reader CBZ/EPUB support uses), so Mangayomi `.backup` archives
 * restore on iOS like they do on the JVM platforms. ZIP writing emits a
 * stored archive via [buildStoredZip]; the old Flutter app inflates entries
 * regardless of method, so skipping deflate only costs file size.
 */
@OptIn(ExperimentalForeignApi::class)
private object IosBackupCompression : BackupCompression {
    // ponytail: single-shot gzip on whole byte arrays; stream if backups outgrow memory.
    override fun compress(data: ByteArray, level: Int): ByteArray =
        gzipDeflate(data, level) ?: error("gzip compression failed.")

    override fun decompress(data: ByteArray): ByteArray =
        gzipInflate(data) ?: error("Backup is not valid gzip data.")

    override fun unzipFirstEntry(data: ByteArray): ByteArray? {
        val archive = IosZipArchive.open(data) ?: return null
        return archive.entryNames.firstOrNull { !it.endsWith("/") }?.let(archive::read)
    }

    override fun unzipEntries(data: ByteArray): Map<String, ByteArray>? {
        val archive = IosZipArchive.open(data) ?: return null
        return buildMap {
            archive.entryNames.forEach { name ->
                if (!name.endsWith("/")) archive.read(name)?.let { put(name, it) }
            }
        }
    }

    override fun zipSingleEntry(entryName: String, data: ByteArray, level: Int): ByteArray =
        buildStoredZip(listOf(entryName to data))
}

/** windowBits 15 + 16 selects the gzip wrapper in zlib. */
private const val GZIP_WINDOW_BITS = 15 + 16

@OptIn(ExperimentalForeignApi::class)
private fun gzipDeflate(data: ByteArray, level: Int): ByteArray? = memScoped {
    val stream = alloc<z_stream>()
    val clamped = level.coerceIn(0, 9)
    if (deflateInit2(stream.ptr, clamped, Z_DEFLATED, GZIP_WINDOW_BITS, 8, Z_DEFAULT_STRATEGY) != Z_OK) return null
    try {
        val bound = deflateBound(stream.ptr, data.size.toULong()).toInt()
        val output = ByteArray(bound.coerceAtLeast(32))
        val input = if (data.isEmpty()) ByteArray(1) else data
        input.usePinned { pinnedIn ->
            output.usePinned { pinnedOut ->
                stream.next_in = pinnedIn.addressOf(0).reinterpret()
                stream.avail_in = data.size.toUInt()
                stream.next_out = pinnedOut.addressOf(0).reinterpret()
                stream.avail_out = output.size.toUInt()
                if (deflate(stream.ptr, Z_FINISH) != Z_STREAM_END) return null
            }
        }
        output.copyOf(stream.total_out.toInt())
    } finally {
        deflateEnd(stream.ptr)
    }
}

/** Deflate expands at most ~1032:1, so a trailer claiming more than that is a lie. */
private const val MAX_DEFLATE_RATIO = 1032L

/** The trailer size only sizes the first buffer, capped here; the buffer doubles if the data needs more. */
private const val MAX_INITIAL_INFLATE_BYTES = 64L * 1024 * 1024

@OptIn(ExperimentalForeignApi::class)
private fun gzipInflate(data: ByteArray): ByteArray? {
    if (data.size < 18) return null
    // gzip trailer stores the uncompressed size (mod 2^32) in the last 4 bytes; corrupt or hostile files
    // can claim anything, so it is a starting capacity, never an allocation we trust.
    val trailer = data.size - 4
    val isize = (data[trailer].toLong() and 0xFF) or
        ((data[trailer + 1].toLong() and 0xFF) shl 8) or
        ((data[trailer + 2].toLong() and 0xFF) shl 16) or
        ((data[trailer + 3].toLong() and 0xFF) shl 24)
    var output = ByteArray(isize.coerceIn(1L, minOf(data.size * MAX_DEFLATE_RATIO, MAX_INITIAL_INFLATE_BYTES)).toInt())
    return data.usePinned { pinnedIn ->
        memScoped {
            val stream = alloc<z_stream>()
            stream.next_in = pinnedIn.addressOf(0).reinterpret()
            stream.avail_in = data.size.toUInt()
            if (inflateInit2(stream.ptr, GZIP_WINDOW_BITS) != Z_OK) return@memScoped null
            try {
                while (true) {
                    val produced = stream.total_out.toInt()
                    if (produced == output.size) {
                        if (output.size == Int.MAX_VALUE) return@memScoped null
                        output = output.copyOf(minOf(output.size * 2L, Int.MAX_VALUE.toLong()).toInt())
                    }
                    val status = output.usePinned { pinnedOut ->
                        stream.next_out = pinnedOut.addressOf(produced).reinterpret()
                        stream.avail_out = (output.size - produced).toUInt()
                        inflate(stream.ptr, Z_NO_FLUSH)
                    }
                    if (status == Z_STREAM_END) break
                    // Output space left after Z_OK/Z_BUF_ERROR means the input ended before the stream did.
                    if ((status != Z_OK && status != Z_BUF_ERROR) || stream.avail_out != 0u) return@memScoped null
                }
                val produced = stream.total_out.toInt()
                if (produced == output.size) output else output.copyOf(produced)
            } finally {
                inflateEnd(stream.ptr)
            }
        }
    }
}

Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupCompression.jvm.kt

Create this path in your reconstruction project. Source set: jvmCommonMain. Exact file download.

The implementation below defines createPlatformBackupCompression.

package eu.friedcutlet.yokan.services.backup

actual fun createPlatformBackupCompression(): BackupCompression = JvmBackupCompression()

Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/backup/JvmBackupCompression.kt

Create this path in your reconstruction project. Source set: jvmCommonMain. Exact file download.

The implementation below defines JvmBackupCompression, compress, decompress, unzipFirstEntry, unzipEntries, zipSingleEntry, TunableGzipOutputStream.

package eu.friedcutlet.yokan.services.backup

import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.zip.Deflater
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream

internal class JvmBackupCompression : BackupCompression {
    override fun compress(data: ByteArray, level: Int): ByteArray {
        val clamped = level.coerceIn(Deflater.NO_COMPRESSION, Deflater.BEST_COMPRESSION)
        val output = ByteArrayOutputStream(data.size)
        TunableGzipOutputStream(output, clamped).use { it.write(data) }
        return output.toByteArray()
    }

    override fun decompress(data: ByteArray): ByteArray {
        GZIPInputStream(ByteArrayInputStream(data)).use { input ->
            return input.readBytes()
        }
    }

    override fun unzipFirstEntry(data: ByteArray): ByteArray? {
        if (!looksZipped(data)) return null
        return runCatching {
            ZipInputStream(ByteArrayInputStream(data)).use { zip ->
                // Mangayomi writes a single `*.backup.db` entry; take the
                // first non-directory entry whatever its name is so future
                // archive layouts don't silently break import.
                var entry = zip.nextEntry
                while (entry != null && entry.isDirectory) entry = zip.nextEntry
                if (entry == null) null else zip.readBytes()
            }
        }.getOrNull()
    }

    override fun unzipEntries(data: ByteArray): Map<String, ByteArray>? {
        if (!looksZipped(data)) return null
        return runCatching {
            buildMap {
                ZipInputStream(ByteArrayInputStream(data)).use { zip ->
                    var entry = zip.nextEntry
                    while (entry != null) {
                        if (!entry.isDirectory) put(entry.name, zip.readBytes())
                        entry = zip.nextEntry
                    }
                }
            }
        }.getOrNull()
    }

    override fun zipSingleEntry(entryName: String, data: ByteArray, level: Int): ByteArray {
        val clamped = level.coerceIn(Deflater.NO_COMPRESSION, Deflater.BEST_COMPRESSION)
        val output = ByteArrayOutputStream(data.size)
        ZipOutputStream(output).use { zip ->
            zip.setLevel(clamped)
            zip.putNextEntry(ZipEntry(entryName))
            zip.write(data)
            zip.closeEntry()
        }
        return output.toByteArray()
    }
}

private class TunableGzipOutputStream(out: java.io.OutputStream, level: Int) : GZIPOutputStream(out) {
    init {
        def.setLevel(level)
    }
}

Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupCompression.wasm.kt

Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.

The implementation below defines createPlatformBackupCompression, WasmBackupCompression, compress, decompress, unzipFirstEntryAsync, unzipEntriesAsync, readEntry, ZipEntry, parseZip, u16 and 8 further declarations.

The source describes its contract as:

The browser's CompressionStream API is async-only and this contract is synchronous, so web backups export uncompressed — other platforms sniff the gzip magic bytes and treat non-gzipped payloads as raw. Importing a gzipped backup on the web fails with a clear error instead of corrupting.

package eu.friedcutlet.yokan.services.backup

import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlin.js.ExperimentalWasmJsInterop
import kotlin.js.JsAny
import kotlin.js.Promise
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

actual fun createPlatformBackupCompression(): BackupCompression = WasmBackupCompression

/**
 * The browser's CompressionStream API is async-only and this contract is
 * synchronous, so web backups export uncompressed — other platforms sniff
 * the gzip magic bytes and treat non-gzipped payloads as raw. Importing a
 * gzipped backup on the web fails with a clear error instead of corrupting.
 */
private object WasmBackupCompression : BackupCompression {
    override fun compress(data: ByteArray, level: Int): ByteArray = data

    override fun decompress(data: ByteArray): ByteArray {
        if (looksGzipped(data)) {
            throw UnsupportedOperationException(
                "Gzipped backups cannot be imported in the browser; export an uncompressed backup instead.",
            )
        }
        return data
    }

    override suspend fun unzipFirstEntryAsync(data: ByteArray): ByteArray? =
        parseZip(data).firstOrNull { !it.name.endsWith('/') }?.let { readEntry(data, it, 0L) }

    override suspend fun unzipEntriesAsync(data: ByteArray): Map<String, ByteArray> = buildMap {
        var totalOutput = 0L
        parseZip(data).forEach { entry ->
            if (!entry.name.endsWith('/')) {
                val decoded = readEntry(data, entry, totalOutput)
                totalOutput += decoded.size.toLong()
                put(entry.name, decoded)
            }
        }
    }

    private suspend fun readEntry(data: ByteArray, entry: ZipEntry, totalOutput: Long): ByteArray {
        requireZip(entry.uncompressedSize <= MaxArchiveOutputBytes, "declared entry size exceeds the 64 MiB browser limit")
        requireZip(totalOutput <= MaxArchiveOutputBytes - entry.uncompressedSize, "archive output exceeds the 64 MiB browser limit")

        val localOffset = entry.localHeaderOffset
        requireZip(localOffset < entry.centralDirectoryOffset, "local file header overlaps the central directory")
        requireRange(data, localOffset, 30L, "local file header is truncated")
        requireZip(u32(data, localOffset.toInt()) == LocalFileHeader, "local file header signature is invalid")
        val local = localOffset.toInt()
        val localVersionNeeded = u16(data, local + 4)
        val localFlags = u16(data, local + 6)
        val localMethod = u16(data, local + 8)
        val localCrc = u32(data, local + 14)
        val localCompressedSize = u32(data, local + 18)
        val localUncompressedSize = u32(data, local + 22)
        val nameLength = u16(data, local + 26)
        val extraLength = u16(data, local + 28)
        requireUnsupported(localVersionNeeded <= 20L, "ZIP features newer than standard stored/deflate entries are not supported")
        requireZip(localFlags == entry.flags, "local and central flags differ for ${entry.name}")
        requireZip(localMethod == entry.method, "local and central methods differ for ${entry.name}")
        requireZip(localCrc != Zip32Sentinel && localCompressedSize != Zip32Sentinel && localUncompressedSize != Zip32Sentinel, "ZIP64 local entries are not supported in the browser")
        val contentStart = localOffset + 30L + nameLength + extraLength
        val contentEnd = contentStart + entry.compressedSize
        requireZip(contentEnd <= entry.centralDirectoryOffset, "entry data overlaps the central directory")
        requireRange(data, contentStart, entry.compressedSize, "entry data is truncated")
        val localNameEnd = localOffset + 30L + nameLength
        requireRange(data, localOffset + 30L, nameLength, "local entry name is truncated")
        val localName = data.copyOfRange((localOffset + 30L).toInt(), localNameEnd.toInt()).decodeToString()
        requireZip(localName == entry.name, "local and central names differ")
        requireZip(
            localCrc == entry.crc32 &&
                localCompressedSize == entry.compressedSize &&
                localUncompressedSize == entry.uncompressedSize,
            "local and central metadata differ for ${entry.name}",
        )
        val compressed = data.copyOfRange(contentStart.toInt(), contentEnd.toInt())
        return when (entry.method) {
            Stored -> {
                requireZip(entry.compressedSize == entry.uncompressedSize, "stored entry sizes differ for ${entry.name}")
                compressed
            }
            Deflated -> inflateRaw(compressed, entry.name, entry.uncompressedSize.toInt())
            else -> error("Unsupported ZIP backup: compression method ${entry.method} is not supported for ${entry.name}")
        }.also { decoded ->
            requireZip(decoded.size.toLong() == entry.uncompressedSize, "decoded size differs from central metadata for ${entry.name}")
            requireZip(crc32(decoded) == entry.crc32, "CRC-32 mismatch for ${entry.name}")
        }
    }
}

private data class ZipEntry(
    val name: String,
    val flags: Long,
    val method: Long,
    val crc32: Long,
    val compressedSize: Long,
    val uncompressedSize: Long,
    val localHeaderOffset: Long,
    val centralDirectoryOffset: Long,
)

private const val EndOfCentralDirectory = 0x06054B50L
private const val CentralDirectoryHeader = 0x02014B50L
private const val LocalFileHeader = 0x04034B50L
private const val Stored = 0L
private const val Deflated = 8L
private const val Zip32Sentinel = 0xFFFF_FFFFL
private const val Zip16Sentinel = 0xFFFFL
private const val Utf8Flag = 0x800L
private const val SupportedFlags = Utf8Flag
private const val MaxArchiveOutputBytes = 64L * 1024L * 1024L

private fun parseZip(data: ByteArray): List<ZipEntry> {
    requireZip(data.size >= 22, "end-of-central-directory record is missing")
    val eocd = (data.size - 22 downTo (data.size - 65_557).coerceAtLeast(0))
        .firstOrNull { candidate ->
            u32(data, candidate) == EndOfCentralDirectory &&
                candidate.toLong() + 22L + u16(data, candidate + 20) == data.size.toLong()
        }
        ?: error("Invalid ZIP backup: end-of-central-directory record is missing")
    val entryCount = u16(data, eocd + 10)
    val centralSize = u32(data, eocd + 12)
    val centralOffset = u32(data, eocd + 16)
    val diskNumber = u16(data, eocd + 4)
    val centralDisk = u16(data, eocd + 6)
    val entriesOnDisk = u16(data, eocd + 8)
    requireUnsupported(diskNumber == 0L && centralDisk == 0L && entriesOnDisk == entryCount, "multi-disk ZIP archives are not supported in the browser")
    requireUnsupported(
        entryCount != Zip16Sentinel && centralSize != Zip32Sentinel && centralOffset != Zip32Sentinel,
        "ZIP64 archives are not supported in the browser",
    )
    val centralEnd = centralOffset + centralSize
    requireZip(entryCount <= centralSize / 46L, "central directory entry count is invalid")
    requireZip(centralOffset <= data.size.toLong() && centralSize <= data.size.toLong() - centralOffset && centralEnd <= eocd.toLong(), "central directory is truncated")

    val entries = ArrayList<ZipEntry>(entryCount.toInt())
    var cursor = centralOffset
    repeat(entryCount.toInt()) {
        requireRange(data, cursor, 46L, "central directory entry is truncated")
        requireZip(u32(data, cursor.toInt()) == CentralDirectoryHeader, "central directory entry is invalid")
        val versionNeeded = u16(data, cursor.toInt() + 6)
        val flags = u16(data, cursor.toInt() + 8)
        val method = u16(data, cursor.toInt() + 10)
        val crc32 = u32(data, cursor.toInt() + 16)
        val compressedSize = u32(data, cursor.toInt() + 20)
        val uncompressedSize = u32(data, cursor.toInt() + 24)
        val nameLength = u16(data, cursor.toInt() + 28)
        val extraLength = u16(data, cursor.toInt() + 30)
        val commentLength = u16(data, cursor.toInt() + 32)
        val diskStart = u16(data, cursor.toInt() + 34)
        val localHeaderOffset = u32(data, cursor.toInt() + 42)
        requireUnsupported(versionNeeded <= 20L, "ZIP features newer than standard stored/deflate entries are not supported")
        requireUnsupported(flags and 1L == 0L, "encrypted ZIP entries are not supported in the browser")
        requireUnsupported(flags and SupportedFlags.inv() == 0L, "unsupported ZIP entry flags")
        requireUnsupported(
            diskStart == 0L && compressedSize != Zip32Sentinel && uncompressedSize != Zip32Sentinel && localHeaderOffset != Zip32Sentinel,
            "ZIP64 or multi-disk entries are not supported in the browser",
        )
        requireUnsupported(method == Stored || method == Deflated, "compression method $method is not supported in the browser")
        requireZip(uncompressedSize <= MaxArchiveOutputBytes, "declared entry size exceeds the 64 MiB browser limit")
        val nameStart = cursor + 46L
        val next = nameStart + nameLength + extraLength + commentLength
        requireZip(next >= nameStart && next <= centralEnd, "central directory entry is truncated")
        val name = data.copyOfRange(nameStart.toInt(), (nameStart + nameLength).toInt()).decodeToString()
        requireZip(name.isNotEmpty() && '\u0000' !in name, "ZIP entry name is invalid")
        entries += ZipEntry(name, flags, method, crc32, compressedSize, uncompressedSize, localHeaderOffset, centralOffset)
        cursor = next
    }
    requireZip(cursor == centralEnd, "central directory size does not match its entries")
    return entries
}

private fun u16(data: ByteArray, offset: Int): Long =
    (data[offset].toLong() and 0xFFL) or ((data[offset + 1].toLong() and 0xFFL) shl 8)

private fun u32(data: ByteArray, offset: Int): Long =
    (data[offset].toLong() and 0xFFL) or
        ((data[offset + 1].toLong() and 0xFFL) shl 8) or
        ((data[offset + 2].toLong() and 0xFFL) shl 16) or
        ((data[offset + 3].toLong() and 0xFFL) shl 24)

private fun requireZip(condition: Boolean, message: String) {
    if (!condition) error("Invalid ZIP backup: $message")
}

private fun requireUnsupported(condition: Boolean, message: String) {
    if (!condition) error("Unsupported ZIP backup: $message")
}

private fun requireRange(data: ByteArray, offset: Long, length: Long, message: String) {
    requireZip(offset >= 0L && length >= 0L && offset <= data.size.toLong() && length <= data.size.toLong() - offset, message)
}

private fun crc32(data: ByteArray): Long {
    var crc = 0xFFFF_FFFFL
    data.forEach { byte ->
        crc = (crc ushr 8) xor Crc32Table[((crc xor (byte.toLong() and 0xFFL)) and 0xFFL).toInt()]
    }
    return crc xor 0xFFFF_FFFFL
}

private val Crc32Table = LongArray(256) { index ->
    var value = index.toLong()
    repeat(8) { value = if (value and 1L != 0L) (value ushr 1) xor 0xEDB88320L else value ushr 1 }
    value
}

@OptIn(ExperimentalEncodingApi::class, ExperimentalWasmJsInterop::class)
private suspend fun inflateRaw(data: ByteArray, entryName: String, maxOutputBytes: Int): ByteArray {
    return try {
        suspendCancellableCoroutine { continuation ->
            inflateRawJs(Base64.encode(data), maxOutputBytes).then(
                onFulfilled = { value ->
                    if (value == null) {
                        continuation.resumeWithException(IllegalStateException("DecompressionStream returned no data"))
                    } else {
                        runCatching { Base64.decode(jsString(value)) }
                            .fold(continuation::resume, continuation::resumeWithException)
                    }
                    null
                },
                onRejected = { error ->
                    continuation.resumeWithException(IllegalStateException(jsString(error)))
                    null
                },
            )
        }
    } catch (error: Throwable) {
        throw IllegalArgumentException(
            "Browser could not deflate ZIP entry $entryName: ${error.message.orEmpty().ifBlank { "DecompressionStream('deflate-raw') is unavailable or the entry is corrupt" }}",
            error,
        )
    }
}

@OptIn(ExperimentalWasmJsInterop::class)
private fun inflateRawJs(base64: String, maxOutputBytes: Int): Promise<JsAny?> = js(
    """
    (async () => {
        const binary = atob(base64);
        const input = new Uint8Array(binary.length);
        for (let i = 0; i < binary.length; i++) input[i] = binary.charCodeAt(i);
        const stream = new Blob([input]).stream().pipeThrough(new DecompressionStream('deflate-raw'));
        const reader = stream.getReader();
        const chunks = [];
        let outputLength = 0;
        while (true) {
            const result = await reader.read();
            if (result.done) break;
            outputLength += result.value.byteLength;
            if (outputLength > maxOutputBytes) {
                await reader.cancel();
                throw new Error('decompressed ZIP entry exceeds its declared or browser output limit');
            }
            chunks.push(result.value);
        }
        const output = new Uint8Array(outputLength);
        let outputOffset = 0;
        for (const chunk of chunks) {
            output.set(chunk, outputOffset);
            outputOffset += chunk.byteLength;
        }
        let binaryOutput = '';
        for (let i = 0; i < output.length; i += 0x8000) {
            binaryOutput += String.fromCharCode(...output.subarray(i, i + 0x8000));
        }
        return btoa(binaryOutput);
    })()
    """,
)

@OptIn(ExperimentalWasmJsInterop::class)
private fun jsString(value: JsAny): String = js("String(value)")

Check your understanding

Round-trip a native backup and export the same state to Tachiyomi. List the fields/media that cannot return from the foreign format. [chapter-content-end]: #

Step 2: implement password envelope exactly

Write PasswordBackupEnvelope and deterministic-entropy test hooks. Version 1 uses magic YOKANENC, PBKDF2-SHA256, AES-256-GCM, 600,000 iterations for encoding, 16-byte salt, 12-byte nonce and 16-byte tag. Decoder bounds iterations to the accepted range through 2,000,000 and payload to 64 MiB. Passwords are exact UTF-8, 1–1024 bytes; do not normalize them unexpectedly.

Preserve the exact header layout, integer byte order, authenticated data and error distinctions from source/test vectors. Reject malformed/unsupported envelopes before expensive KDF work. Authentication failure must not expose partially decrypted data. Use platform crypto providers and cryptographic entropy; preserve cancellation outside unavoidable provider calls.

Follow the code

Read the header before invoking expensive cryptography. Version/algorithm/payload IDs occupy bytes 8–11, the big-endian iteration count begins at 12, salt at 16 and nonce after the salt. The complete header is authenticated as additional data for AES-GCM. Password validation uses exact UTF-8 bytes. Decoder bounds reject malformed or unsupported input before key derivation; authentication failure never yields partial plaintext. Deterministic entropy hooks belong to tests, while production obtains cryptographic randomness.

Write these files in this order:

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

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The header is 44 bytes: magic (8), four one-byte IDs, a four-byte big-endian iteration count, 16-byte salt and 12-byte nonce. AES-256-GCM authenticates that complete header. Encoding uses 600,000 PBKDF2-SHA256 iterations; decoding accepts only the source's bounded range and payload sizes.

The implementation below defines PasswordBackupEnvelopeResult, Success, Failure, PasswordBackupEnvelopeError, InvalidInput, Malformed, Unsupported, AuthenticationFailed, CryptoFailure, isValidBackupPassword and 10 further declarations.

The source describes its contract as:

Whether [password] is accepted by [PasswordBackupEnvelope]: 1 to [MAX_BACKUP_PASSWORD_BYTES] UTF-8 bytes.

package eu.friedcutlet.yokan.services.backup

import dev.whyoleg.cryptography.CryptographyProvider
import dev.whyoleg.cryptography.CryptographyProviderApi
import dev.whyoleg.cryptography.DelicateCryptographyApi
import dev.whyoleg.cryptography.algorithms.AES
import dev.whyoleg.cryptography.algorithms.PBKDF2
import dev.whyoleg.cryptography.algorithms.SHA256
import dev.whyoleg.cryptography.random.CryptographyRandom
import eu.friedcutlet.yokan.services.catchingNonCancellation
import kotlinx.coroutines.ensureActive
import kotlin.coroutines.coroutineContext

internal sealed interface PasswordBackupEnvelopeResult {
    data class Success(val bytes: ByteArray) : PasswordBackupEnvelopeResult
    data class Failure(val error: PasswordBackupEnvelopeError) : PasswordBackupEnvelopeResult
}

internal sealed interface PasswordBackupEnvelopeError {
    data object InvalidInput : PasswordBackupEnvelopeError
    data object Malformed : PasswordBackupEnvelopeError
    data object Unsupported : PasswordBackupEnvelopeError
    data object AuthenticationFailed : PasswordBackupEnvelopeError
    data object CryptoFailure : PasswordBackupEnvelopeError
}

// Passwords are encoded as exact UTF-8 bytes and capped before KDF work.
internal const val MAX_BACKUP_PASSWORD_BYTES = 1024

/** Whether [password] is accepted by [PasswordBackupEnvelope]: 1 to [MAX_BACKUP_PASSWORD_BYTES] UTF-8 bytes. */
internal fun isValidBackupPassword(password: String): Boolean =
    password.encodeToByteArray().size in 1..MAX_BACKUP_PASSWORD_BYTES

@OptIn(CryptographyProviderApi::class, DelicateCryptographyApi::class)
internal object PasswordBackupEnvelope {
    private const val VERSION = 1
    private const val KDF_PBKDF2_SHA256 = 1
    private const val AEAD_AES_256_GCM = 1
    private const val PAYLOAD_RAW_YOKAN_JSON = 1
    private const val ITERATIONS = 600_000
    private const val MAX_ITERATIONS = 2_000_000
    private const val KEY_SIZE_BYTES = 32
    private const val SALT_SIZE = 16
    private const val NONCE_SIZE = 12
    private const val TAG_SIZE = 16
    private const val HEADER_SIZE = 8 + 1 + 1 + 1 + 1 + 4 + SALT_SIZE + NONCE_SIZE
    private const val MAX_PAYLOAD_SIZE = 64 * 1024 * 1024
    private const val MAX_ENVELOPE_SIZE = HEADER_SIZE + MAX_PAYLOAD_SIZE + TAG_SIZE
    private val MAGIC = "YOKANENC".encodeToByteArray()
    private val provider = CryptographyProvider.Default

    suspend fun encode(payload: ByteArray, password: String): PasswordBackupEnvelopeResult =
        encodeWithEntropy(payload, password) { size -> CryptographyRandom.Default.nextBytes(size) }

    suspend fun decode(envelope: ByteArray, password: String): PasswordBackupEnvelopeResult {
        coroutineContext.ensureActive()
        val passwordBytes = passwordBytes(password)
            ?: return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput)
        if (envelope.size < HEADER_SIZE + TAG_SIZE || envelope.size > MAX_ENVELOPE_SIZE) {
            return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed)
        }

        val header = envelope.copyOfRange(0, HEADER_SIZE)
        if (!header.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)) {
            return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed)
        }
        if (header[8].unsigned() != VERSION ||
            header[9].unsigned() != KDF_PBKDF2_SHA256 ||
            header[10].unsigned() != AEAD_AES_256_GCM ||
            header[11].unsigned() != PAYLOAD_RAW_YOKAN_JSON
        ) {
            return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Unsupported)
        }

        val iterations = readInt(header, 12)
        if (iterations !in ITERATIONS..MAX_ITERATIONS) {
            return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed)
        }

        val ciphertext = envelope.copyOfRange(HEADER_SIZE, envelope.size)
        if (ciphertext.size < TAG_SIZE || ciphertext.size - TAG_SIZE > MAX_PAYLOAD_SIZE) {
            return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed)
        }

        val key = catchingNonCancellation {
            deriveKey(passwordBytes, header.copyOfRange(16, 16 + SALT_SIZE), iterations)
        }.getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) }
        val aesKey = catchingNonCancellation {
            provider.get(AES.GCM).keyDecoder().decodeFromByteArray(AES.Key.Format.RAW, key)
        }.getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) }
        val cipher = catchingNonCancellation { aesKey.cipher(AES.Key.Size.B128) }
            .getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) }
        val plaintext = catchingNonCancellation {
            cipher.decryptWithIv(
                header.copyOfRange(16 + SALT_SIZE, HEADER_SIZE),
                ciphertext,
                header,
            )
        }.getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.AuthenticationFailed) }
        return if (plaintext.size > MAX_PAYLOAD_SIZE) {
            PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed)
        } else {
            PasswordBackupEnvelopeResult.Success(plaintext)
        }
    }

    internal suspend fun encodeForTesting(
        payload: ByteArray,
        password: String,
        salt: ByteArray,
        nonce: ByteArray,
    ): PasswordBackupEnvelopeResult {
        coroutineContext.ensureActive()
        if (salt.size != SALT_SIZE || nonce.size != NONCE_SIZE) {
            return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput)
        }
        return encodeWithEntropy(payload, password) { size ->
            when (size) {
                SALT_SIZE -> salt.copyOf()
                NONCE_SIZE -> nonce.copyOf()
                else -> error("Unexpected envelope entropy request")
            }
        }
    }

    private suspend fun encodeWithEntropy(
        payload: ByteArray,
        password: String,
        entropy: (Int) -> ByteArray,
    ): PasswordBackupEnvelopeResult {
        coroutineContext.ensureActive()
        val passwordBytes = passwordBytes(password)
            ?: return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput)
        if (payload.size > MAX_PAYLOAD_SIZE) {
            return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput)
        }

        return catchingNonCancellation {
            val salt = entropy(SALT_SIZE)
            val nonce = entropy(NONCE_SIZE)
            if (salt.size != SALT_SIZE || nonce.size != NONCE_SIZE) {
                return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure)
            }
            val header = ByteArray(HEADER_SIZE).also {
                MAGIC.copyInto(it)
                it[8] = VERSION.toByte()
                it[9] = KDF_PBKDF2_SHA256.toByte()
                it[10] = AEAD_AES_256_GCM.toByte()
                it[11] = PAYLOAD_RAW_YOKAN_JSON.toByte()
                writeInt(it, 12, ITERATIONS)
                salt.copyInto(it, 16)
                nonce.copyInto(it, 16 + SALT_SIZE)
            }
            val key = deriveKey(passwordBytes, salt, ITERATIONS)
            val aes = provider.get(AES.GCM)
            val aesKey = aes.keyDecoder().decodeFromByteArray(AES.Key.Format.RAW, key)
            val ciphertext = aesKey.cipher(AES.Key.Size.B128).encryptWithIv(nonce, payload, header)
            PasswordBackupEnvelopeResult.Success(header + ciphertext)
        }.getOrElse { PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) }
    }

    private suspend fun deriveKey(password: ByteArray, salt: ByteArray, iterations: Int): ByteArray {
        val pbkdf2 = provider.get(PBKDF2)
        return pbkdf2.secretDerivation(SHA256, iterations, AES.Key.Size.B256, salt)
            .deriveSecretToByteArray(password)
    }

    private fun passwordBytes(password: String): ByteArray? = password.takeIf(::isValidBackupPassword)?.encodeToByteArray()

    private fun readInt(bytes: ByteArray, offset: Int): Int =
        (bytes[offset].unsigned() shl 24) or
            (bytes[offset + 1].unsigned() shl 16) or
            (bytes[offset + 2].unsigned() shl 8) or
            bytes[offset + 3].unsigned()

    private fun writeInt(bytes: ByteArray, offset: Int, value: Int) {
        bytes[offset] = (value ushr 24).toByte()
        bytes[offset + 1] = (value ushr 16).toByte()
        bytes[offset + 2] = (value ushr 8).toByte()
        bytes[offset + 3] = value.toByte()
    }

    private fun Byte.unsigned(): Int = toInt() and 0xff
}

Check your understanding

Change the header, ciphertext or password separately. Distinguish malformed/unsupported/authentication/crypto-provider failures and verify no decoded bytes reach restore planning after failure. [chapter-content-end]: #

Step 3: split decoding from application

Open bytes, detect/decompress/decrypt/decode, validate references, then produce a preview plan. Opening a file or receiving an OS backup link must not change the database. Apply only after the restore UI action. A plan's metadata does not choose its destination profile; the selected locked target does.

Implement selective restore and merge with explicit ID/reference remapping across titles, chapters, categories, tracks, history, settings references and source records. Reconcile duplicate identities and progress without confusing source-local IDs with current database IDs. Preserve private/local preferences and target credentials where required. Validate input sizes and malformed foreign formats.

Follow the code

Decoding establishes a candidate format/state without choosing its destination or applying it. Restore planning validates references and selected sections, then computes replace/merge behavior. Remap related IDs together: title, chapter, category, history and track references cannot be merged as independent lists. Preserve target-local preferences/credentials and user notes according to the native/personal versus sync export policies.

Write these files in this order:

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

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines InvalidBackupException, UnsupportedBackupException, DecodedBackup, ByteArray.startsWithEncryptedMagic, BackupDecoder, decode, decodeNative, normalizeNativeBackup, parseIncludedSections, inferNativeSections and 6 further declarations.

The source describes its contract as:

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.

Cross-chapter imports used by this file: DbItemType, DbSourceCodeLanguage. Keep those contracts available as you connect this step.

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<String>,
)

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<String>? {
        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<String> = 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<String> = 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<String, ByteArray>): Set<String> = 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<String> = 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<String>.addIfPresent(root: JsonObject, key: String, section: String) {
        if (key in root && root[key] is JsonArray) add(section)
    }

    private fun MutableSet<String>.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
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

ID/reference remapping and selected-section policy belong in the merge, not in UI row loops. Preserve relationships and target-local state while constructing a candidate that can be atomically checked/applied.

The implementation below defines BackupIdentityCollisionException, BackupMerge, mangaKey, replace, merge, Merged, nextId, mergeCategories, mergeSources, mergeMangas and 19 further declarations.

The source describes its contract as:

Combines the current database with a decoded backup. [replace] swaps every included section wholesale; [merge] adds what is missing and folds progress into matching titles. Both reject identity collisions and drop dangling references.

Cross-chapter imports used by this file: DbCategory, DbChangedPart, DbChapter, DbCustomButton, DbFetchType, DbHistory. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChangedPart
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.database.DbFetchType
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.DbTrack
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.sync.preserveDeviceLocalSettings
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.database.DbChapterReleasePreference
import eu.friedcutlet.yokan.database.mergeProgress
import eu.friedcutlet.yokan.database.presetIdentity
import eu.friedcutlet.yokan.domain.mergePrivateNotes

private class BackupIdentityCollisionException(message: String) : IllegalStateException(message)

/**
 * Combines the current database with a decoded backup. [replace] swaps every
 * included section wholesale; [merge] adds what is missing and folds progress
 * into matching titles. Both reject identity collisions and drop dangling references.
 */
internal object BackupMerge {
    /** Identity used to match titles across devices: link when known, else lowercase name. */
    fun mangaKey(itemType: DbItemType, link: String?, name: String?): String =
        if (!link.isNullOrBlank()) "${itemType.name}:link:${link.trim()}"
        else "${itemType.name}:name:${name?.trim()?.lowercase().orEmpty()}"

    fun replace(
        current: YokanDatabaseSnapshot,
        payload: BackupSnapshot,
        includedSections: Set<String>,
    ): YokanDatabaseSnapshot {
        val includedTypes = includedSections.titleTypes()
        val replacements = if (payload.privateNotesIncluded) payload.mangas else {
            val localNotes = current.mangas.associate { mangaKey(it.itemType, it.link, it.name) to it.privateNote }
            payload.mangas.map { it.copy(privateNote = localNotes[mangaKey(it.itemType, it.link, it.name)].orEmpty()) }
        }
        val mangas = applyMangaSections(current.mangas, replacements, includedTypes)
        checkIdentityCollisions(
            "mangas",
            current.mangas.filter { it.itemType !in includedTypes },
            payload.mangas.filter { it.itemType in includedTypes },
            DbManga::id,
        )
        val categories = mergeTypedCollection(
            current.categories,
            payload.categories,
            includedSections,
            BackupSection.Categories,
            DbCategory::forItemType,
            includedTypes,
            DbCategory::id,
        )
        val sources = mergeTypedCollection(
            current.sources,
            payload.sources,
            includedSections,
            BackupSection.Sources,
            DbSource::itemType,
            includedTypes,
            DbSource::id,
        )
        val chapters = mergeTitleDependent(
            current.chapters,
            payload.chapters,
            includedSections,
            BackupSection.Chapters,
            mangas,
            { it.mangaId },
            null,
            DbChapter::id,
            includedTypes,
        )
        val chaptersById = chapters.associateBy(DbChapter::id)
        val histories = mergeTitleDependent(
            current.histories,
            payload.histories,
            includedSections,
            BackupSection.History,
            mangas,
            { it.mangaId },
            { it.chapterId },
            DbHistory::id,
            includedTypes,
            chaptersById,
        )
        val updates = mergeTitleDependent(
            current.updates,
            payload.updates,
            includedSections,
            BackupSection.Updates,
            mangas,
            { it.mangaId },
            { it.chapterId },
            DbUpdate::id,
            includedTypes,
            chaptersById,
        )
        val tracks = mergeTitleDependent(
            current.tracks,
            payload.tracks,
            includedSections,
            BackupSection.Tracks,
            mangas,
            { it.mangaId },
            null,
            DbTrack::id,
            includedTypes,
        )
        val settings = if (payload.sourceApp == "mangayomi") {
            if (payload.settings?.backupEncryptionPassword != null) {
                current.settings.copy(
                    backupEncryptionEnabled = true,
                    backupEncryptionPassword = payload.settings.backupEncryptionPassword,
                )
            } else current.settings
        } else if (BackupSection.Settings in includedSections) {
            payload.settings
                ?.let { incoming ->
                    preserveDeviceLocalSettings(current.settings, incoming).copy(
                        savedSearches = incoming.savedSearches?.let { restorePresets(it, payload.sources, sources) },
                        chapterReleasePreferences = restoreReleasePreferences(incoming.chapterReleasePreferences, payload.mangas, mangas),
                        automaticReaderLayout = incoming.automaticReaderLayout,
                        readerHoldToScroll = incoming.readerHoldToScroll,
                        automaticReaderLayouts = restoreAutomaticLayouts(incoming.automaticReaderLayouts, payload.mangas, mangas),
                    )
                }
                ?: current.settings
        } else current.settings
        val changedParts = mergeChangedParts(current.changedParts, payload.changedParts, includedSections)
        if (BackupSection.TrackPreferences in includedSections) {
            checkIdentityCollisions("trackPreferences", emptyList(), payload.trackPreferences, DbTrackPreference::syncId)
        }
        if (BackupSection.CustomButtons in includedSections) {
            checkIdentityCollisions("customButtons", emptyList(), payload.customButtons, DbCustomButton::id)
        }
        return sanitizeRestoreSnapshot(
            current.copy(
                settings = settings,
                mangas = mangas,
                chapters = chapters,
                categories = categories,
                sources = sources,
                histories = histories,
                updates = updates,
                tracks = tracks,
                trackPreferences = if (BackupSection.TrackPreferences in includedSections) {
                    payload.trackPreferences
                } else {
                    current.trackPreferences
                },
                customButtons = if (BackupSection.CustomButtons in includedSections) {
                    payload.customButtons
                } else {
                    current.customButtons
                },
                changedParts = changedParts,
            ),
        )
    }

    fun merge(
        current: YokanDatabaseSnapshot,
        payload: BackupSnapshot,
        includedSections: Set<String>,
    ): YokanDatabaseSnapshot {
        val categories = mergeCategories(current.categories, payload.categories, BackupSection.Categories in includedSections)
        val sources = mergeSources(current.sources, payload.sources, BackupSection.Sources in includedSections)
        val mangas = mergeMangas(current.mangas, payload, includedSections.titleTypes(), categories.ids, sources.ids)
        val chapters = mergeChapters(current.chapters, payload.chapters, BackupSection.Chapters in includedSections, mangas)
        return sanitizeRestoreSnapshot(
            current.copy(
                settings = mergeSettings(current.settings, payload, includedSections, sources.rows, mangas.rows),
                mangas = mangas.rows,
                chapters = chapters.rows,
                categories = categories.rows,
                sources = sources.rows,
                histories = mergeHistories(current.histories, payload.histories, BackupSection.History in includedSections, mangas.ids, chapters.ids),
                updates = mergeUpdates(current.updates, payload.updates, BackupSection.Updates in includedSections, mangas.ids, chapters.ids),
                tracks = mergeTracks(current.tracks, payload.tracks, BackupSection.Tracks in includedSections, mangas.ids),
                customButtons = mergeButtons(current.customButtons, payload.customButtons, BackupSection.CustomButtons in includedSections),
            ),
        )
    }

    /** Merged rows, the backup→merged id of every accepted backup row, and the ids of rows the merge added. */
    private class Merged<T>(
        val rows: List<T>,
        val ids: Map<Long, Long> = emptyMap(),
        val added: Set<Long> = emptySet(),
    )

    private fun <T> nextId(a: List<T>, b: List<T>, id: (T) -> Long): Long =
        maxOf(a.maxOfOrNull(id) ?: 0L, b.maxOfOrNull(id) ?: 0L) + 1L

    private fun mergeCategories(current: List<DbCategory>, incoming: List<DbCategory>, included: Boolean): Merged<DbCategory> {
        if (!included) return Merged(current)
        var nextId = nextId(current, incoming, DbCategory::id)
        val ids = mutableMapOf<Long, Long>()
        val rows = current.toMutableList()
        for (incomingCat in incoming) {
            val existing = current.firstOrNull {
                it.name.trim().equals(incomingCat.name.trim(), ignoreCase = true) &&
                    it.forItemType == incomingCat.forItemType
            }
            if (existing != null) {
                ids[incomingCat.id] = existing.id
            } else {
                val newId = nextId++
                ids[incomingCat.id] = newId
                rows.add(incomingCat.copy(id = newId))
            }
        }
        return Merged(rows, ids)
    }

    private fun mergeSources(current: List<DbSource>, incoming: List<DbSource>, included: Boolean): Merged<DbSource> {
        if (!included) return Merged(current)
        var nextId = nextId(current, incoming, DbSource::id)
        val ids = mutableMapOf<Long, Long>()
        val rows = current.toMutableList()
        for (incomingSrc in incoming) {
            val existing = current.firstOrNull {
                it.itemType == incomingSrc.itemType &&
                    (it.id == incomingSrc.id || it.name.trim().equals(incomingSrc.name.trim(), ignoreCase = true))
            }
            if (existing != null) {
                ids[incomingSrc.id] = existing.id
            } else {
                val newId = if (current.none { it.id == incomingSrc.id }) incomingSrc.id else nextId++
                ids[incomingSrc.id] = newId
                rows.add(incomingSrc.copy(id = newId))
            }
        }
        return Merged(rows, ids)
    }

    private fun mergeMangas(
        current: List<DbManga>,
        payload: BackupSnapshot,
        includedTypes: Set<DbItemType>,
        categoryIds: Map<Long, Long>,
        sourceIds: Map<Long, Long>,
    ): Merged<DbManga> {
        var nextId = nextId(current, payload.mangas, DbManga::id)
        val ids = mutableMapOf<Long, Long>()
        val newIds = mutableSetOf<Long>()
        val rows = current.toMutableList()
        val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap()
        val byKey = mutableMapOf<String, DbManga>()
        for (m in current) {
            byKey[mangaKey(m.itemType, m.link, m.name)] = m
        }

        val incomingMangas = payload.mangas.filter { it.itemType in includedTypes }
        for (incomingManga in incomingMangas) {
            val key = mangaKey(incomingManga.itemType, incomingManga.link, incomingManga.name)
            val existing = byKey[key]
            val remappedCategories = incomingManga.categories?.mapNotNull { categoryIds[it] ?: it }?.distinct()
            val remappedSourceId = incomingManga.sourceId?.let { sourceIds[it] ?: it }

            if (existing != null) {
                ids[incomingManga.id] = existing.id
                val combinedCategories = (existing.categories.orEmpty() + remappedCategories.orEmpty()).distinct()
                val updated = existing.copy(
                    // Season records stay out of the library unless they were favorites themselves.
                    favorite = incomingManga.parentId == null || existing.favorite || incomingManga.favorite,
                    privateNote = mergePrivateNotes(existing.privateNote, incomingManga.privateNote.takeIf { payload.privateNotesIncluded }.orEmpty()),
                    categories = combinedCategories,
                    sourceId = existing.sourceId ?: remappedSourceId,
                    author = existing.author?.ifBlank { incomingManga.author } ?: incomingManga.author,
                    artist = existing.artist?.ifBlank { incomingManga.artist } ?: incomingManga.artist,
                    description = existing.description?.ifBlank { incomingManga.description } ?: incomingManga.description,
                    genre = (existing.genre.orEmpty() + incomingManga.genre.orEmpty()).distinct().takeIf { it.isNotEmpty() },
                    cast = existing.cast.ifEmpty { incomingManga.cast },
                    fetchType = if (incomingManga.fetchType == DbFetchType.Seasons) DbFetchType.Seasons else existing.fetchType,
                    seasonNumber = existing.seasonNumber ?: incomingManga.seasonNumber,
                )
                rows[indexById.getValue(existing.id)] = updated
            } else {
                val newId = nextId++
                ids[incomingManga.id] = newId
                newIds.add(newId)
                val newManga = incomingManga.copy(
                    id = newId,
                    privateNote = incomingManga.privateNote.takeIf { payload.privateNotesIncluded }.orEmpty(),
                    favorite = incomingManga.parentId == null || incomingManga.favorite,
                    parentId = null, // Remapped below once every parent has its merged id.
                    categories = remappedCategories,
                    sourceId = remappedSourceId,
                )
                rows.add(newManga)
                indexById[newId] = rows.lastIndex
                byKey[key] = newManga
            }
        }
        incomingMangas.forEach { incoming ->
            val parent = incoming.parentId?.let(ids::get) ?: return@forEach
            val index = indexById.getValue(ids.getValue(incoming.id))
            val merged = rows[index]
            if (merged.parentId == null && merged.id != parent) rows[index] = merged.copy(parentId = parent)
        }
        return Merged(rows, ids, newIds)
    }

    private fun mergeChapters(
        current: List<DbChapter>,
        incoming: List<DbChapter>,
        included: Boolean,
        mangas: Merged<DbManga>,
    ): Merged<DbChapter> {
        if (!included) return Merged(current)
        var nextId = nextId(current, incoming, DbChapter::id)
        val ids = mutableMapOf<Long, Long>()
        val existingByMangaId = current.groupBy { it.mangaId }.mapValues { it.value.toMutableList() }.toMutableMap()
        val rows = current.toMutableList()
        val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap()

        for (incomingCh in incoming) {
            val targetMangaId = incomingCh.mangaId?.let { mangas.ids[it] } ?: continue
            if (targetMangaId in mangas.added) {
                val newId = nextId++
                ids[incomingCh.id] = newId
                rows.add(incomingCh.copy(id = newId, mangaId = targetMangaId))
                indexById[newId] = rows.lastIndex
                continue
            }
            val existingList = existingByMangaId.getOrPut(targetMangaId) { mutableListOf() }
            val matchingChapter = existingList.firstOrNull {
                (!it.url.isNullOrBlank() && it.url == incomingCh.url) ||
                    (it.url.isNullOrBlank() && incomingCh.url.isNullOrBlank() && it.name == incomingCh.name)
            }
            if (matchingChapter != null) {
                ids[incomingCh.id] = matchingChapter.id
                val updatedCh = matchingChapter.mergeProgress(incomingCh).copy(
                    dateUpload = if (incomingCh.dateUpload.isNotBlank() && matchingChapter.dateUpload.isBlank()) {
                        incomingCh.dateUpload
                    } else matchingChapter.dateUpload,
                    number = matchingChapter.number ?: incomingCh.number,
                    season = matchingChapter.season ?: incomingCh.season,
                    numberingName = matchingChapter.numberingName ?: incomingCh.numberingName,
                )
                if (updatedCh != matchingChapter) {
                    rows[indexById.getValue(matchingChapter.id)] = updatedCh
                    val exIdx = existingList.indexOfFirst { it.id == matchingChapter.id }
                    if (exIdx >= 0) existingList[exIdx] = updatedCh
                }
            } else {
                val newId = nextId++
                ids[incomingCh.id] = newId
                val newCh = incomingCh.copy(id = newId, mangaId = targetMangaId)
                rows.add(newCh)
                indexById[newId] = rows.lastIndex
                existingList.add(newCh)
            }
        }
        return Merged(rows, ids)
    }

    private fun mergeHistories(
        current: List<DbHistory>,
        incoming: List<DbHistory>,
        included: Boolean,
        mangaIds: Map<Long, Long>,
        chapterIds: Map<Long, Long>,
    ): List<DbHistory> {
        if (!included) return current
        var nextId = nextId(current, incoming, DbHistory::id)
        val rows = current.toMutableList()
        val byKey = current.associateBy { "${it.mangaId}:${it.chapterId}" }.toMutableMap()
        val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap()
        for (incomingH in incoming) {
            val targetMangaId = incomingH.mangaId?.let { mangaIds[it] } ?: continue
            val targetChapterId = incomingH.chapterId?.let { chapterIds[it] } ?: continue
            val key = "$targetMangaId:$targetChapterId"
            val existing = byKey[key]
            if (existing != null) {
                val mergedDate = listOfNotNull(existing.date, incomingH.date).maxOrNull() ?: existing.date
                if (mergedDate != existing.date) {
                    val updated = existing.copy(date = mergedDate)
                    rows[indexById.getValue(existing.id)] = updated
                    byKey[key] = updated
                }
            } else {
                val newId = nextId++
                val newH = incomingH.copy(id = newId, mangaId = targetMangaId, chapterId = targetChapterId)
                rows.add(newH)
                indexById[newId] = rows.lastIndex
                byKey[key] = newH
            }
        }
        return rows
    }

    private fun mergeUpdates(
        current: List<DbUpdate>,
        incoming: List<DbUpdate>,
        included: Boolean,
        mangaIds: Map<Long, Long>,
        chapterIds: Map<Long, Long>,
    ): List<DbUpdate> {
        if (!included) return current
        var nextId = nextId(current, incoming, DbUpdate::id)
        val rows = current.toMutableList()
        val byKey = current.associateBy { "${it.mangaId}:${it.chapterName}" }.toMutableMap()
        for (incomingU in incoming) {
            val targetMangaId = incomingU.mangaId?.let { mangaIds[it] } ?: continue
            val targetChapterId = incomingU.chapterId?.let { chapterIds[it] }
            val key = "$targetMangaId:${incomingU.chapterName}"
            if (key !in byKey) {
                val newU = incomingU.copy(id = nextId++, mangaId = targetMangaId, chapterId = targetChapterId)
                rows.add(newU)
                byKey[key] = newU
            }
        }
        return rows
    }

    private fun mergeTracks(
        current: List<DbTrack>,
        incoming: List<DbTrack>,
        included: Boolean,
        mangaIds: Map<Long, Long>,
    ): List<DbTrack> {
        if (!included) return current
        var nextId = nextId(current, incoming, DbTrack::id)
        val rows = current.toMutableList()
        val byKey = current.associateBy { "${it.mangaId}:${it.syncId}" }.toMutableMap()
        val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap()
        for (incomingT in incoming) {
            val targetMangaId = incomingT.mangaId?.let { mangaIds[it] } ?: continue
            val key = "$targetMangaId:${incomingT.syncId}"
            val existing = byKey[key]
            if (existing != null) {
                // This device's status and score win; the backup only fills progress and a missing score.
                val updated = existing.copy(
                    lastChapterRead = maxOf(existing.lastChapterRead ?: 0, incomingT.lastChapterRead ?: 0).takeIf { it > 0 },
                    score = if ((existing.score ?: 0) > 0) existing.score else incomingT.score,
                )
                rows[indexById.getValue(existing.id)] = updated
                byKey[key] = updated
            } else {
                val newId = nextId++
                val newT = incomingT.copy(id = newId, mangaId = targetMangaId)
                rows.add(newT)
                indexById[newId] = rows.lastIndex
                byKey[key] = newT
            }
        }
        return rows
    }

    private fun mergeButtons(current: List<DbCustomButton>, incoming: List<DbCustomButton>, included: Boolean): List<DbCustomButton> {
        if (!included) return current
        var nextId = nextId(current, incoming, DbCustomButton::id)
        val existingNames = current.map { it.title?.trim()?.lowercase().orEmpty() }.toSet()
        return current + incoming
            .filter { it.title?.trim()?.lowercase().orEmpty() !in existingNames }
            .map { it.copy(id = nextId++) }
    }

    private fun mergeSettings(
        current: DbSettings,
        payload: BackupSnapshot,
        includedSections: Set<String>,
        mergedSources: List<DbSource>,
        mergedMangas: List<DbManga>,
    ): DbSettings {
        val settings = if (payload.settings?.backupEncryptionPassword != null) {
            current.copy(
                backupEncryptionEnabled = true,
                backupEncryptionPassword = payload.settings.backupEncryptionPassword,
            )
        } else current
        if (BackupSection.Settings !in includedSections || payload.sourceApp == "mangayomi" || payload.settings == null) return settings
        val incoming = payload.settings.savedSearches?.let { restorePresets(it, payload.sources, mergedSources) }
        val releases = restoreReleasePreferences(payload.settings.chapterReleasePreferences, payload.mangas, mergedMangas)
        return settings.copy(
            savedSearches = if (incoming == null) settings.savedSearches else (settings.savedSearches.orEmpty() + incoming).distinctBy { it.id },
            chapterReleasePreferences = (settings.chapterReleasePreferences + releases).distinctBy { it.mangaId },
            automaticReaderLayouts = (settings.automaticReaderLayouts + restoreAutomaticLayouts(payload.settings.automaticReaderLayouts, payload.mangas, mergedMangas)).distinctBy { it.mangaId },
        )
    }

    private fun <T> mergeTypedCollection(
        current: List<T>,
        incoming: List<T>,
        includedSections: Set<String>,
        section: String,
        typeOf: (T) -> DbItemType,
        includedTypes: Set<DbItemType>,
        identityOf: (T) -> Long,
    ): List<T> = if (section !in includedSections) {
        current
    } else if (includedTypes.isEmpty()) {
        // The collection itself is explicitly selected, but no title type is
        // available to partition it (for example, an empty legacy backup).
        // Typed rows can still be replaced without guessing a title parent.
        incoming.also { checkIdentityCollisions(section, emptyList(), it, identityOf) }
    } else {
        val preserved = current.filter { typeOf(it) !in includedTypes }
        val accepted = incoming.filter { typeOf(it) in includedTypes }
        checkIdentityCollisions(section, preserved, accepted, identityOf)
        preserved + accepted
    }

    private fun <T> mergeTitleDependent(
        current: List<T>,
        incoming: List<T>,
        includedSections: Set<String>,
        section: String,
        mangas: List<DbManga>,
        mangaIdOf: (T) -> Long?,
        chapterIdOf: ((T) -> Long?)?,
        identityOf: (T) -> Long,
        includedTypes: Set<DbItemType>,
        chapters: Map<Long, DbChapter> = emptyMap(),
    ): List<T> {
        if (section !in includedSections) return current
        val titleTypes = mangas.associateBy(DbManga::id)
        fun typeOf(record: T): DbItemType? = mangaIdOf(record)?.let { titleTypes[it]?.itemType }
            ?: chapterIdOf?.invoke(record)?.let { chapters[it]?.mangaId?.let(titleTypes::get)?.itemType }
        val selectedIds = titleTypes.filterValues { it.itemType in includedTypes }.keys
        fun hasValidReferences(record: T): Boolean {
            val mangaId = mangaIdOf(record)
            val chapterId = chapterIdOf?.invoke(record)
            if (mangaId != null && mangaId !in titleTypes) return false
            if (chapterId != null && chapterId !in chapters) return false
            if (mangaId != null && chapterId != null && chapters[chapterId]?.mangaId?.let { it != mangaId } == true) {
                return false
            }
            return true
        }
        if (includedTypes.isEmpty()) {
            // No title type means there is no graph to partition. An explicit
            // dependent section is therefore a whole-section replacement;
            // validate its rows against the final (preserved) title graph.
            val accepted = incoming.filter(::hasValidReferences)
            checkIdentityCollisions(section, emptyList(), accepted, identityOf)
            return accepted
        }
        val preserved = current.filter { hasValidReferences(it) && typeOf(it) !in includedTypes }
        val accepted = incoming.filter { record ->
            val mangaId = mangaIdOf(record)
            val chapterId = chapterIdOf?.invoke(record)
            val directMangaIsSelected = mangaId != null && mangaId in selectedIds
            val chapterMangaId = chapterId?.let { chapters[it]?.mangaId }
            val chapterIsSelected = chapterMangaId != null && chapterMangaId in selectedIds
            val directMangaIsValid = mangaId == null || directMangaIsSelected
            val chapterIsValid = chapterId == null || chapterIsSelected
            val relationshipIsValid = mangaId == null || chapterMangaId == null || mangaId == chapterMangaId
            directMangaIsValid && chapterIsValid && relationshipIsValid &&
                (directMangaIsSelected || chapterIsSelected)
        }
        checkIdentityCollisions(section, preserved, accepted, identityOf)
        return preserved + accepted
    }

    private fun mergeChangedParts(
        current: List<DbChangedPart>,
        incoming: List<DbChangedPart>,
        includedSections: Set<String>,
    ): List<DbChangedPart> {
        if (BackupSection.ChangedParts !in includedSections) return current
        checkIdentityCollisions("changedParts", current, incoming, DbChangedPart::id)
        return current + incoming
    }

    private fun <T, K : Any> checkIdentityCollisions(
        collection: String,
        preserved: List<T>,
        incoming: List<T>,
        identityOf: (T) -> K?,
    ) {
        val preservedKeys = preserved.mapNotNull(identityOf).toSet()
        val incomingKeys = incoming.mapNotNull(identityOf)
        if (incomingKeys.size != incomingKeys.toSet().size || incomingKeys.any { it in preservedKeys }) {
            throw BackupIdentityCollisionException("Backup contains colliding $collection identities")
        }
    }

    private fun sanitizeRestoreSnapshot(snapshot: YokanDatabaseSnapshot): YokanDatabaseSnapshot {
        val categoryById = snapshot.categories.associateBy(DbCategory::id)
        val sourceTypes = snapshot.sources.associate { it.id to it.itemType }
        val mangas = snapshot.mangas.map { manga ->
            manga.copy(
                categories = manga.categories?.filter { categoryId ->
                    categoryById[categoryId]?.forItemType == manga.itemType
                },
                sourceId = manga.sourceId?.takeIf { sourceTypes[it] == manga.itemType },
            )
        }
        val mangaIds = mangas.mapTo(hashSetOf(), DbManga::id)
        val chapters = snapshot.chapters.filter { it.mangaId == null || it.mangaId in mangaIds }
        val chapterById = chapters.associateBy(DbChapter::id)
        fun validTitleAndChapter(mangaId: Long?, chapterId: Long?): Boolean {
            if (mangaId != null && mangaId !in mangaIds) return false
            if (chapterId != null && chapterId !in chapterById) return false
            if (mangaId != null && chapterId != null) {
                val chapterMangaId = chapterById[chapterId]?.mangaId
                if (chapterMangaId != null && chapterMangaId != mangaId) return false
            }
            return true
        }
        val histories = snapshot.histories.filter { validTitleAndChapter(it.mangaId, it.chapterId) }
        val updates = snapshot.updates.filter { validTitleAndChapter(it.mangaId, it.chapterId) }
        val tracks = snapshot.tracks.filter { it.mangaId == null || it.mangaId in mangaIds }
        val downloads = snapshot.downloads.filter { it.chapterId == null || it.chapterId in chapterById }
        val pageCache = snapshot.pageCache.filter { it.chapterId == null || it.chapterId in chapterById }
        val settings = snapshot.settings.sanitizeReferences(mangaIds, chapterById.keys)
        return snapshot.copy(
            settings = settings,
            mangas = mangas,
            chapters = chapters,
            histories = histories,
            updates = updates,
            tracks = tracks,
            downloads = downloads,
            pageCache = pageCache,
        )
    }

    private fun DbSettings.sanitizeReferences(
        mangaIds: Set<Long>,
        chapterIds: Set<Long>,
    ): DbSettings = copy(
        chapterReleasePreferences = chapterReleasePreferences.filter { it.mangaId == null || it.mangaId in mangaIds },
        automaticReaderLayouts = automaticReaderLayouts.filter { it.mangaId in mangaIds },
        sortChapterList = sortChapterList?.filter { it.mangaId == null || it.mangaId in mangaIds },
        chapterFilterDownloadedList = chapterFilterDownloadedList?.filter { it.mangaId == null || it.mangaId in mangaIds },
        chapterFilterUnreadList = chapterFilterUnreadList?.filter { it.mangaId == null || it.mangaId in mangaIds },
        chapterFilterBookmarkedList = chapterFilterBookmarkedList?.filter { it.mangaId == null || it.mangaId in mangaIds },
        chapterPageIndexList = chapterPageIndexList?.filter { it.chapterId == null || it.chapterId in chapterIds },
        personalReaderModeList = personalReaderModeList?.filter { it.mangaId == null || it.mangaId in mangaIds },
        personalPageModeList = personalPageModeList?.filter { it.mangaId == null || it.mangaId in mangaIds },
        autoScrollPages = autoScrollPages?.filter { it.mangaId == null || it.mangaId in mangaIds },
        filterScanlatorList = filterScanlatorList?.filter { it.mangaId == null || it.mangaId in mangaIds },
    )

    private fun restoreAutomaticLayouts(
        preferences: List<eu.friedcutlet.yokan.database.DbAutomaticReaderLayout>,
        originalMangas: List<DbManga>,
        targetMangas: List<DbManga>,
    ): List<eu.friedcutlet.yokan.database.DbAutomaticReaderLayout> = preferences.mapNotNull { preference ->
        val original = originalMangas.firstOrNull { it.id == preference.mangaId } ?: return@mapNotNull null
        val key = mangaKey(original.itemType, original.link, original.name)
        val target = targetMangas.filter { mangaKey(it.itemType, it.link, it.name) == key }.singleOrNull() ?: return@mapNotNull null
        preference.copy(mangaId = target.id)
    }

    private fun restoreReleasePreferences(
        preferences: List<DbChapterReleasePreference>,
        originalMangas: List<DbManga>,
        targetMangas: List<DbManga>,
    ): List<DbChapterReleasePreference> = preferences.mapNotNull { preference ->
        if (preference.mangaId == null) return@mapNotNull preference
        val original = originalMangas.firstOrNull { it.id == preference.mangaId } ?: return@mapNotNull null
        val key = mangaKey(original.itemType, original.link, original.name)
        val target = targetMangas.filter { mangaKey(it.itemType, it.link, it.name) == key }.singleOrNull() ?: return@mapNotNull null
        preference.copy(mangaId = target.id)
    }

    private fun restorePresets(
        presets: List<DbSavedSearch>,
        originalSources: List<DbSource>,
        targetSources: List<DbSource>,
    ): List<DbSavedSearch> = presets.map { preset ->
        val identity = preset.sourceIdentity ?: originalSources.firstOrNull { it.id == preset.sourceId }?.presetIdentity()
        val matches = targetSources.filter { it.presetIdentity() == identity }
        preset.copy(
            sourceId = matches.singleOrNull()?.id ?: preset.sourceId,
            sourceIdentity = identity,
            missingSourceIdentity = preset.missingSourceIdentity || identity == null,
        )
    }

    private fun applyMangaSections(
        current: List<DbManga>,
        incoming: List<DbManga>,
        includedTypes: Set<DbItemType>,
    ): List<DbManga> {
        if (includedTypes.isEmpty()) return current
        return current.filterNot { it.itemType in includedTypes } + incoming.filter { it.itemType in includedTypes }
    }
}

Check your understanding

Restore a backup whose IDs collide with different target records. Inspect the preview/remapping and verify no chapter points to an unrelated preexisting title. [chapter-content-end]: #

Step 4: implement safe atomic apply

Acquire target profile/storage ownership, take a safety snapshot for user restore, prepare replacement against the expected database snapshot, then commit atomically. A concurrent change produces a retry/conflict, not silent data loss. Rollback uses a selected safety snapshot. Retention belongs to the target profile and must not remove exported backups or external files.

Automatic state-sync merges use the guarded apply path without filling the user's restore-point retention queue. A callback predicate checks the exact account against the expected commit snapshot. Report success only after persistence completes; join restore finalizers before closing the target session.

Follow the code

The service binds the selected target profile/storage owner, prepares against the expected current snapshot and commits with the backend's atomic replacement capability. Concurrent edits cause conflict/retry rather than overwrite. Safety retention belongs to that target and protects user restore/rollback; automatic sync merges do not fill the same queue. Report success only after durable completion and joined finalizers.

Write these files in this order:

  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/SafetySnapshotStore.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupService.kt

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines SafetySnapshotStore, list, record, remove, clear, readMeta, decodeMeta, writeMeta.

The source describes its contract as:

Full native backups taken right before a restore, kept under \<backupRoot\>/safety_snapshots with a small JSON index. Only the newest [MAX_SNAPSHOTS] are kept.

Cross-chapter imports used by this file: YokanDatabaseSnapshot, LocalFileService, nowMillis. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.util.nowMillis

/**
 * Full native backups taken right before a restore, kept under
 * `<backupRoot>/safety_snapshots` with a small JSON index. Only the newest
 * [MAX_SNAPSHOTS] are kept.
 */
internal class SafetySnapshotStore(private val files: LocalFileService) {
    private val json = BackupJson
    private val dir get() = "${files.backupRoot}/safety_snapshots"
    private val metaPath get() = "$dir/snapshots.json"

    fun list(): List<SafetySnapshot> = readMeta().filter { files.exists(it.backupPath) }

    fun record(snapshot: YokanDatabaseSnapshot, description: String): SafetySnapshot {
        val createdAt = nowMillis()
        val backupPath = "$dir/safety-$createdAt.json"
        val payload = BackupSnapshot(
            createdAtMillis = createdAt,
            sourceApp = "yokan-kmp",
            settings = snapshot.settings,
            includedSections = BackupSection.all.toList(),
            mangas = snapshot.mangas,
            chapters = snapshot.chapters,
            categories = snapshot.categories,
            sources = snapshot.sources,
            histories = snapshot.histories,
            updates = snapshot.updates,
            tracks = snapshot.tracks,
            trackPreferences = snapshot.trackPreferences,
            customButtons = snapshot.customButtons,
            changedParts = snapshot.changedParts,
        )
        files.writeBytes(backupPath, json.encodeToString(BackupSnapshot.serializer(), payload).encodeToByteArray())

        val newSnapshot = SafetySnapshot(backupPath = backupPath, createdAt = createdAt, description = description)
        val updated = listOf(newSnapshot) + readMeta()
        for (old in updated.drop(MAX_SNAPSHOTS)) {
            files.deleteRecursively(old.backupPath)
        }
        writeMeta(updated.take(MAX_SNAPSHOTS))
        return newSnapshot
    }

    fun remove(snapshot: SafetySnapshot) {
        files.deleteRecursively(snapshot.backupPath)
        val metaBytes = files.readBytes(metaPath)
        if (metaBytes.isEmpty()) return
        val remaining = decodeMeta(metaBytes).filterNot { it.backupPath == snapshot.backupPath }
        if (remaining.isEmpty()) files.deleteRecursively(metaPath) else writeMeta(remaining)
    }

    fun clear() {
        for (s in list()) {
            files.deleteRecursively(s.backupPath)
        }
        files.deleteRecursively(metaPath)
    }

    private fun readMeta(): List<SafetySnapshot> = decodeMeta(files.readBytes(metaPath))

    private fun decodeMeta(metaBytes: ByteArray): List<SafetySnapshot> {
        if (metaBytes.isEmpty()) return emptyList()
        return runCatching { json.decodeFromString<List<SafetySnapshot>>(metaBytes.decodeToString()) }.getOrNull().orEmpty().filter {
            it.backupPath.startsWith("$dir/") && it.backupPath.removePrefix("$dir/").matches(Regex("safety-[0-9]+\\.json"))
        }
    }

    private fun writeMeta(snapshots: List<SafetySnapshot>) {
        files.writeBytes(metaPath, json.encodeToString(snapshots).encodeToByteArray())
    }

    private companion object {
        const val MAX_SNAPSHOTS = 3
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

Opening/preview and applying are different public operations. The guarded target/expected snapshot and awaited persistence establish when a restore can truthfully be reported as successful.

The implementation below defines BackupRestoreTargetChangedException, BackupService, exportBackup, exportEncryptedBackup, createBackup, openBackup, previewBackup, applyBackup, listSafetySnapshots, createSafetySnapshot and 14 further declarations.

The source describes its contract as:

A guarded restore's predicate rejected the current library; nothing was written.

Cross-chapter imports used by this file: DbItemType, YokanDatabase, YokanDatabaseSnapshot, SyncPaths, LocalFileService, AppLogger. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.sync.SyncPaths
import eu.friedcutlet.yokan.services.blockingDispatcher
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.notifications.NotificationChannel
import eu.friedcutlet.yokan.services.notifications.NotificationPayload
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext

/** A guarded restore's predicate rejected the current library; nothing was written. */
class BackupRestoreTargetChangedException : IllegalStateException("Backup restore target changed.")

interface BackupService {
    suspend fun exportBackup(options: BackupOptions): BackupExport
    suspend fun exportEncryptedBackup(options: BackupOptions, password: String): BackupExport
    suspend fun createBackup(options: BackupOptions = BackupOptions()): BackupResult
    suspend fun openBackup(bytes: ByteArray, password: String? = null): BackupOpenResult
    suspend fun previewBackup(plan: BackupPlan): RestorePreview
    suspend fun applyBackup(plan: BackupPlan): RestorePreview
    suspend fun applyBackup(plan: BackupPlan, mode: RestoreMode): RestorePreview
    suspend fun listSafetySnapshots(): List<SafetySnapshot>
    suspend fun createSafetySnapshot(description: String): SafetySnapshot
    suspend fun rollbackSafetySnapshot(snapshot: SafetySnapshot): RestorePreview
    suspend fun clearSafetySnapshots()
    /** Compatibility wrapper for legacy, unencrypted restore callers. */
    suspend fun restore(bytes: ByteArray): RestorePreview
    /** Predicate is evaluated against the snapshot required by the atomic restore commit. */
    suspend fun restoreIf(bytes: ByteArray, accepts: (YokanDatabaseSnapshot) -> Boolean): RestorePreview {
        error("GUARDED_BACKUP_RESTORE_UNAVAILABLE")
    }
    /**
     * Guarded like [restoreIf], but applies an already opened [plan] in [mode] and records no safety snapshot:
     * state sync merges on every scheduled run and would otherwise evict the user's restore points.
     */
    suspend fun applyBackupIf(plan: BackupPlan, mode: RestoreMode, accepts: (YokanDatabaseSnapshot) -> Boolean): RestorePreview {
        error("GUARDED_BACKUP_RESTORE_UNAVAILABLE")
    }
    suspend fun listAvailableBackups(): List<BackupFileEntry>
    suspend fun readBackupFile(path: String): ByteArray
}

class DefaultBackupService(
    private val database: YokanDatabase,
    private val files: LocalFileService,
    gzip: BackupCompression,
    private val notifications: NotificationService,
    /** Blocking work: backup file and safety-snapshot I/O, encoding, encryption and restore. */
    private val workDispatcher: CoroutineDispatcher = blockingDispatcher,
) : BackupService {
    private val exporter = BackupExporter(gzip)
    private val decoder = BackupDecoder(gzip)
    private val safetySnapshots = SafetySnapshotStore(files)

    override suspend fun exportBackup(options: BackupOptions): BackupExport =
        withContext(workDispatcher) { exportPlain(options) }

    override suspend fun exportEncryptedBackup(options: BackupOptions, password: String): BackupExport =
        withContext(workDispatcher) { exportEncrypted(options, password) }

    private fun exportPlain(options: BackupOptions): BackupExport =
        exporter.export(database.snapshot(), options)
            .also { AppLogger.info("[backup] export ${options.format}: ${it.itemCount} items, ${it.bytes.size} bytes") }

    private suspend fun exportEncrypted(options: BackupOptions, password: String): BackupExport {
        // Deliberately use the uncompressed native JSON producer. Encrypted
        // backups are Yokan-only and must not inherit scheduled/cloud formats.
        val plain = exportPlain(
            options.copy(
                format = BackupFormat.Yokan,
                compressionLevel = null,
                encrypt = true,
                password = password,
            ),
        )
        val encrypted = when (val result = PasswordBackupEnvelope.encode(plain.bytes, password)) {
            is PasswordBackupEnvelopeResult.Success -> result.bytes
            is PasswordBackupEnvelopeResult.Failure -> error("Invalid backup password.")
        }
        return plain.copy(
            fileName = plain.fileName.substringBeforeLast('.') + ".yokanbak",
            bytes = encrypted,
            compressed = false,
            contentType = "application/octet-stream",
        )
    }

    override suspend fun createBackup(options: BackupOptions): BackupResult = withContext(workDispatcher) {
        val currentSettings = database.settings()
        val shouldEncrypt = options.encrypt || (options.password != null) || currentSettings.backupEncryptionEnabled
        val export = if (shouldEncrypt) {
            val password = options.password ?: currentSettings.backupEncryptionPassword
                ?: error("Backup encryption is enabled but no password is set. Re-enter it in Data and Storage settings.")
            exportEncrypted(options, password)
        } else {
            exportPlain(options)
        }
        val baseDir = currentSettings.autoBackupLocation?.takeIf { it.isNotBlank() } ?: files.backupRoot
        val path = "$baseDir/${export.fileName}"
        files.writeBytes(path, export.bytes)
        val result = BackupResult(
            fileName = export.fileName,
            bytesWritten = export.bytes.size.toLong(),
            itemCount = export.itemCount,
            path = path,
        )
        AppLogger.info("[backup] created ${result.fileName}: ${result.itemCount} items, ${result.bytesWritten} bytes")
        // A missing notification permission must not fail a backup that is already written.
        runCatching {
            notifications.notify(
                NotificationPayload(
                    channel = NotificationChannel.Backup,
                    title = "Backup created",
                    message = "${result.itemCount} items • ${result.bytesWritten / 1024} KB",
                    tag = "backup-${nowMillis()}",
                ),
            )
        }
        result
    }

    override suspend fun openBackup(bytes: ByteArray, password: String?): BackupOpenResult =
        withContext(workDispatcher) { open(bytes, password) }

    private suspend fun open(bytes: ByteArray, password: String?): BackupOpenResult {
        if (bytes.startsWithEncryptedMagic()) {
            val passwordToTry = password ?: database.settings().backupEncryptionPassword
            if (passwordToTry == null) return BackupOpenResult.Failure(BackupOpenError.PasswordRequired)
            val decrypted = when (val result = PasswordBackupEnvelope.decode(bytes, passwordToTry)) {
                is PasswordBackupEnvelopeResult.Success -> result.bytes
                is PasswordBackupEnvelopeResult.Failure -> {
                    AppLogger.warn("[backup] decrypting backup failed: ${result.error}")
                    return BackupOpenResult.Failure(
                        when (result.error) {
                            PasswordBackupEnvelopeError.AuthenticationFailed -> BackupOpenError.AuthenticationFailed
                            PasswordBackupEnvelopeError.Unsupported -> BackupOpenError.Unsupported
                            PasswordBackupEnvelopeError.InvalidInput,
                            PasswordBackupEnvelopeError.Malformed,
                            PasswordBackupEnvelopeError.CryptoFailure,
                            -> BackupOpenError.Invalid
                        },
                    )
                }
            }
            return openDecoded(decrypted, resolvedPassword = passwordToTry)
        }
        return openDecoded(bytes, resolvedPassword = null)
    }

    private suspend fun openDecoded(bytes: ByteArray, resolvedPassword: String?): BackupOpenResult =
        catchingNonCancellation {
            val decoded = decoder.decode(bytes)
            val currentSnapshot = runCatching { database.snapshot() }.getOrNull()
            BackupOpenResult.Ready(
                BackupPlan(
                    preview = previewOf(decoded.snapshot, decoded.includedSections, currentSnapshot),
                    snapshot = decoded.snapshot,
                    includedSections = decoded.includedSections,
                    resolvedPassword = resolvedPassword,
                ),
            )
        }.getOrElse { error ->
            AppLogger.warn("[backup] opening backup failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")
            BackupOpenResult.Failure(
                if (error is UnsupportedBackupException) BackupOpenError.Unsupported else BackupOpenError.Invalid,
            )
        }

    override suspend fun previewBackup(plan: BackupPlan): RestorePreview = plan.preview

    override suspend fun applyBackup(plan: BackupPlan): RestorePreview =
        applyBackup(plan, plan.mode)

    override suspend fun applyBackup(plan: BackupPlan, mode: RestoreMode): RestorePreview = withContext(workDispatcher) {
        applyBackupInternal(plan, mode, createSafetySnapshot = true)
    }

    private suspend fun applyBackupInternal(
        plan: BackupPlan,
        mode: RestoreMode,
        createSafetySnapshot: Boolean,
        accepts: (YokanDatabaseSnapshot) -> Boolean = { true },
    ): RestorePreview {
        currentCoroutineContext().ensureActive()
        val currentSnapshot = database.snapshot()
        if (!accepts(currentSnapshot)) throw BackupRestoreTargetChangedException()
        if (createSafetySnapshot) {
            val desc = when (mode) {
                RestoreMode.Merge -> {
                    val p = plan.preview
                    "Merge: +${p.newSeriesCount} series, ~${p.updatedSeriesCount} series, +${p.newChapterCount} ch"
                }
                RestoreMode.Replace -> "Replace: ${plan.preview.itemCount} items"
            }
            safetySnapshots.record(currentSnapshot, desc)
        }
        val merged = if (mode == RestoreMode.Merge) {
            BackupMerge.merge(currentSnapshot, plan.snapshot, plan.includedSections)
        } else {
            BackupMerge.replace(currentSnapshot, plan.snapshot, plan.includedSections)
        }
        val updatedSettings = if (plan.resolvedPassword != null) {
            merged.settings.copy(
                backupEncryptionEnabled = true,
                backupEncryptionPassword = plan.resolvedPassword,
            )
        } else merged.settings
        val restored = merged.copy(
            settings = updatedSettings,
            syncPreferences = merged.syncPreferences.map { it.copy(hubHead = 0) },
            // Download marks point at files on the device that downloaded them; drop the ones missing here.
            chapters = merged.chapters.map { chapter ->
                val missing = chapter.downloadSize != null &&
                    (chapter.archivePath.isBlank() || !runCatching { files.exists(chapter.archivePath) }.getOrDefault(false))
                if (missing) chapter.copy(archivePath = "", downloadSize = null) else chapter
            },
        )
        // Restored values go out like ordinary edits, so the next hub pull can't undo them.
        currentCoroutineContext().ensureActive()
        database.replaceAllAtomically(
            restored.copy(outbox = SyncPaths.outboxForReplacement(currentSnapshot, restored)),
            expectedSnapshot = currentSnapshot,
        )
        AppLogger.info("[backup] restored ($mode): ${plan.preview.itemCount} items, +${plan.preview.newSeriesCount} series, +${plan.preview.newChapterCount} chapters")
        return plan.preview
    }

    override suspend fun listSafetySnapshots(): List<SafetySnapshot> = withContext(workDispatcher) {
        safetySnapshots.list()
    }

    override suspend fun createSafetySnapshot(description: String): SafetySnapshot = withContext(workDispatcher) {
        safetySnapshots.record(database.snapshot(), description)
    }

    override suspend fun rollbackSafetySnapshot(snapshot: SafetySnapshot): RestorePreview = withContext(workDispatcher) {
        val bytes = files.readBytes(snapshot.backupPath)
        if (bytes.isEmpty()) error("Safety snapshot file not found: ${snapshot.backupPath}")
        val plan = when (val opened = open(bytes, password = null)) {
            is BackupOpenResult.Ready -> opened.plan
            is BackupOpenResult.Failure -> error("Failed to open safety snapshot: ${opened.error}")
        }
        val preview = applyBackupInternal(plan.withMode(RestoreMode.Replace), RestoreMode.Replace, createSafetySnapshot = false)
        safetySnapshots.remove(snapshot)
        preview
    }

    override suspend fun clearSafetySnapshots(): Unit = withContext(workDispatcher) {
        safetySnapshots.clear()
    }

    override suspend fun restore(bytes: ByteArray): RestorePreview = restoreIf(bytes) { true }

    override suspend fun restoreIf(bytes: ByteArray, accepts: (YokanDatabaseSnapshot) -> Boolean): RestorePreview =
        withContext(workDispatcher) {
            when (val result = open(bytes, password = null)) {
                is BackupOpenResult.Ready ->
                    applyBackupInternal(result.plan, result.plan.mode, createSafetySnapshot = true, accepts = accepts)
                is BackupOpenResult.Failure -> error("Backup restore failed: ${result.error}")
            }
        }

    override suspend fun applyBackupIf(plan: BackupPlan, mode: RestoreMode, accepts: (YokanDatabaseSnapshot) -> Boolean): RestorePreview =
        withContext(workDispatcher) { applyBackupInternal(plan, mode, createSafetySnapshot = false, accepts = accepts) }

    override suspend fun listAvailableBackups(): List<BackupFileEntry> {
        val root = database.settings().autoBackupLocation?.takeIf { it.isNotBlank() } ?: files.backupRoot
        return files.listFiles(root)
            .filter { it.name.endsWith(".json") || it.name.endsWith(".json.gz") || it.name.endsWith(".backup") }
            .map { entry ->
                BackupFileEntry(
                    path = entry.path,
                    fileName = entry.name,
                    sizeBytes = entry.sizeBytes,
                    lastModified = entry.lastModified,
                    compressed = entry.name.endsWith(".gz") || entry.name.endsWith(".backup"),
                )
            }
    }

    override suspend fun readBackupFile(path: String): ByteArray = withContext(workDispatcher) { files.readBytes(path) }

    private fun previewOf(
        payload: BackupSnapshot,
        includedSections: Set<String>,
        current: YokanDatabaseSnapshot? = null,
    ): RestorePreview {
        val warnings = mutableListOf<String>()
        if (BackupSection.Settings !in includedSections) warnings += "Backup does not contain app settings."
        if (includedSections.none { it == BackupSection.Manga || it == BackupSection.Anime || it == BackupSection.Novel }) {
            warnings += "Backup does not contain library titles."
        }
        val mangaCount = payload.mangas.count { it.itemType == DbItemType.Manga && BackupSection.Manga in includedSections }
        val animeCount = payload.mangas.count { it.itemType == DbItemType.Anime && BackupSection.Anime in includedSections }
        val novelCount = payload.mangas.count { it.itemType == DbItemType.Novel && BackupSection.Novel in includedSections }
        val itemCount = listOf(
            mangaCount + animeCount + novelCount,
            payload.chapters.size.takeIf { BackupSection.Chapters in includedSections } ?: 0,
            payload.categories.size.takeIf { BackupSection.Categories in includedSections } ?: 0,
            payload.sources.size.takeIf { BackupSection.Sources in includedSections } ?: 0,
            payload.histories.size.takeIf { BackupSection.History in includedSections } ?: 0,
            payload.updates.size.takeIf { BackupSection.Updates in includedSections } ?: 0,
            payload.tracks.size.takeIf { BackupSection.Tracks in includedSections } ?: 0,
        ).sum()

        var newSeriesCount = 0
        var updatedSeriesCount = 0
        var newChapterCount = 0
        val conflictingCategories = mutableListOf<String>()
        val unmatchedSourceNames = mutableListOf<String>()

        if (current != null) {
            val includedTypes = includedSections.titleTypes()
            val existingMangaKeys = current.mangas.map { BackupMerge.mangaKey(it.itemType, it.link, it.name) }.toSet()
            val existingChaptersByMangaKey = mutableMapOf<String, MutableSet<String>>()
            val existingMangaById = current.mangas.associateBy { it.id }
            for (ch in current.chapters) {
                val m = ch.mangaId?.let { existingMangaById[it] } ?: continue
                val set = existingChaptersByMangaKey.getOrPut(BackupMerge.mangaKey(m.itemType, m.link, m.name)) { mutableSetOf() }
                set.add(if (ch.url.isNotBlank()) ch.url else ch.name.orEmpty())
            }

            val payloadMangaById = payload.mangas.associateBy { it.id }
            for (m in payload.mangas.filter { it.itemType in includedTypes }) {
                if (BackupMerge.mangaKey(m.itemType, m.link, m.name) in existingMangaKeys) {
                    updatedSeriesCount++
                } else {
                    newSeriesCount++
                }
            }

            if (BackupSection.Chapters in includedSections) {
                for (ch in payload.chapters) {
                    val m = ch.mangaId?.let { payloadMangaById[it] } ?: continue
                    if (m.itemType !in includedTypes) continue
                    val existingChapterUrls = existingChaptersByMangaKey[BackupMerge.mangaKey(m.itemType, m.link, m.name)]
                    val chKey = if (ch.url.isNotBlank()) ch.url else ch.name.orEmpty()
                    if (existingChapterUrls == null || chKey !in existingChapterUrls) newChapterCount++
                }
            }

            if (BackupSection.Categories in includedSections) {
                val existingCatNames = current.categories.map { it.name.trim().lowercase() }.toSet()
                for (cat in payload.categories) {
                    if (cat.name.trim().lowercase() in existingCatNames && cat.name !in conflictingCategories) {
                        conflictingCategories.add(cat.name)
                    }
                }
            }

            val installedSourceNames = current.sources.map { it.name.trim().lowercase() }.toSet()
            for (src in payload.sources) {
                if (src.name.trim().lowercase() !in installedSourceNames && src.name !in unmatchedSourceNames) {
                    unmatchedSourceNames.add(src.name)
                }
            }
        } else {
            newSeriesCount = mangaCount + animeCount + novelCount
            newChapterCount = payload.chapters.size.takeIf { BackupSection.Chapters in includedSections } ?: 0
        }

        return RestorePreview(
            itemCount = itemCount,
            warnings = warnings,
            mangaCount = mangaCount,
            animeCount = animeCount,
            novelCount = novelCount,
            categoryCount = payload.categories.size.takeIf { BackupSection.Categories in includedSections } ?: 0,
            chapterCount = payload.chapters.size.takeIf { BackupSection.Chapters in includedSections } ?: 0,
            historyCount = payload.histories.size.takeIf { BackupSection.History in includedSections } ?: 0,
            updateCount = payload.updates.size.takeIf { BackupSection.Updates in includedSections } ?: 0,
            sourceCount = payload.sources.size.takeIf { BackupSection.Sources in includedSections } ?: 0,
            trackCount = payload.tracks.size.takeIf { BackupSection.Tracks in includedSections } ?: 0,
            newSeriesCount = newSeriesCount,
            updatedSeriesCount = updatedSeriesCount,
            newChapterCount = newChapterCount,
            conflictingCategories = conflictingCategories,
            unmatchedSourceNames = unmatchedSourceNames,
        )
    }
}

Check your understanding

Edit the target after preview but before Apply. Verify the old plan cannot overwrite it, then recover through a fresh plan or selected safety snapshot. [chapter-content-end]: #

Step 5: build UI and scheduled backup wiring

Implement create-backup format/section/password controls, destination selection, backup list, open/unlock preview, merge/replace, apply progress/errors, safety snapshot list/rollback and profile-targeted backup operations. Keep password state transient. Scheduled backup and cloud transport reuse the exporter but enforce their own selection/privacy policy.

Follow the code

The backup controls are assigned to chapter 09's data/storage screens and chapter 04's profile operations. Bind them to these real codec/plan/apply methods. Password stays transient in UI state. OS backup-open events select bytes and show preview; they do not select a target from untrusted file metadata or apply automatically. Scheduled/cloud callers reuse the exporter with their own privacy and destination policy.

This step connects or verifies implementations already listed in this chapter or its prerequisites. Follow the named call paths above while reading the complete tests at the end.

Check your understanding

Open an encrypted file through the OS entry point, cancel unlock/preview and confirm the database is unchanged. Apply only through the explicit target-bound action. [chapter-content-end]: #

Recreate the tests and verify the chapter

Recreate all native/foreign format, encryption, selective restore/merge, sensitive-settings, notes, safety-snapshot and target-profile fixtures. Use known envelopes and deterministic entropy to check exact bytes. Run compression/crypto on their actual platform providers, including wrong password, tampering, concurrent Apply and failed persistence.

These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupCastTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines BackupCastTest.

Read the setup, action and assertions in these cases before implementing their production paths:

  • nativeRestoreAndHubDocumentsKeepCreditsAndMergeOnlyFillsMissingCast
  • legacyExportOmitsUnsupportedCastFields

Cross-chapter imports used by this file: SyncPaths, TitleCredit. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.database.sync.SyncPaths
import eu.friedcutlet.yokan.domain.TitleCredit
import kotlinx.serialization.json.*
import kotlin.test.*

class BackupCastTest {
    private val credit = TitleCredit("Actor", "Voice actor", "Hero", "https://images.test/actor.png")
    private val title = DbManga(id = 10, link = "/show", itemType = DbItemType.Anime, cast = listOf(credit))
    private val payload = BackupSnapshot(createdAtMillis = 1, mangas = listOf(title))

    @Test fun nativeRestoreAndHubDocumentsKeepCreditsAndMergeOnlyFillsMissingCast() {
        val decoded = BackupJson.decodeFromString(BackupSnapshot.serializer(), BackupJson.encodeToString(BackupSnapshot.serializer(), payload))
        assertEquals(title.cast, BackupMerge.replace(emptySnapshot(), decoded, setOf(BackupSection.Anime)).mangas.single().cast)
        val current = emptySnapshot().copy(mangas = listOf(title.copy(id = 1, cast = emptyList(), privateNote = "Saved")))
        val merged = BackupMerge.merge(current, decoded, setOf(BackupSection.Anime))
        assertEquals(title.cast, merged.mangas.single().cast)
        assertEquals("Saved", merged.mangas.single().privateNote)
        val other = payload.copy(mangas = listOf(title.copy(cast = listOf(TitleCredit("Other actor")))))
        assertEquals(title.cast, BackupMerge.merge(merged, other, setOf(BackupSection.Anime)).mangas.single().cast)
        val doc = SyncPaths.doc(SyncPaths.KIND_MANGA, DbManga.serializer(), title)
        val restored = SyncPaths.json.decodeFromJsonElement(DbManga.serializer(), SyncPaths.fromDoc(SyncPaths.KIND_MANGA, doc))
        assertEquals(title.cast, restored.cast)
    }

    @Test fun legacyExportOmitsUnsupportedCastFields() {
        val root = BackupJson.parseToJsonElement(MangayomiBackupCodec.encode(payload)).jsonObject
        assertFalse(root.getValue("manga").jsonArray.single().jsonObject.containsKey("cast"))
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupChapterNumberTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines BackupChapterNumberTest, mergeFillsMissingNumberingWithoutLosingProgressOrOverwritingLocalValues, mergeKeepsPagePositionsBeyondIntRangeAndTakesTheNewerUpdatedAt, backupRoundTripAndReplaceRetainExplicitNumbersAndOriginalLabels.

Read the setup, action and assertions in these cases before implementing their production paths:

  • mergeFillsMissingNumberingWithoutLosingProgressOrOverwritingLocalValues
  • mergeKeepsPagePositionsBeyondIntRangeAndTakesTheNewerUpdatedAt
  • backupRoundTripAndReplaceRetainExplicitNumbersAndOriginalLabels

Cross-chapter imports used by this file: DbChapter, DbItemType, DbManga, emptySnapshot. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.emptySnapshot
import kotlin.test.Test
import kotlin.test.assertEquals

class BackupChapterNumberTest {
    private val sections = setOf(BackupSection.Anime, BackupSection.Chapters)
    private val title = DbManga(id = 10, link = "/show", itemType = DbItemType.Anime)
    private val episode = DbChapter(
        id = 20, mangaId = 10, url = "/episode", name = "Opening Night",
        number = 12.5, season = 0, numberingName = "Episode 12.5 [English]",
    )
    private val payload = BackupSnapshot(createdAtMillis = 1, mangas = listOf(title), chapters = listOf(episode))

    @Test
    fun mergeFillsMissingNumberingWithoutLosingProgressOrOverwritingLocalValues() {
        val local = episode.copy(
            id = 2, mangaId = 1, number = null, season = null, numberingName = null,
            isRead = true, isBookmarked = true, lastPageRead = "7",
        )
        val current = emptySnapshot().copy(mangas = listOf(title.copy(id = 1)), chapters = listOf(local))
        val merged = BackupMerge.merge(current, payload, sections)
        assertEquals(local.copy(number = 12.5, season = 0, numberingName = episode.numberingName), merged.chapters.single())

        val changed = payload.copy(chapters = listOf(episode.copy(number = 99.0, season = 2, numberingName = "Episode 99")))
        assertEquals(merged.chapters, BackupMerge.merge(merged, changed, sections).chapters)
    }

    @Test
    fun mergeKeepsPagePositionsBeyondIntRangeAndTakesTheNewerUpdatedAt() {
        val local = episode.copy(id = 2, mangaId = 1, lastPageRead = "5", updatedAt = 100)
        val current = emptySnapshot().copy(mangas = listOf(title.copy(id = 1)), chapters = listOf(local))
        val incoming = payload.copy(chapters = listOf(episode.copy(lastPageRead = "3000000000", updatedAt = 200)))

        val merged = BackupMerge.merge(current, incoming, sections).chapters.single()

        assertEquals("3000000000", merged.lastPageRead)
        assertEquals(200, merged.updatedAt)
    }

    @Test
    fun backupRoundTripAndReplaceRetainExplicitNumbersAndOriginalLabels() {
        val restored = BackupJson.decodeFromString(
            BackupSnapshot.serializer(), BackupJson.encodeToString(BackupSnapshot.serializer(), payload),
        )
        assertEquals(episode, restored.chapters.single())
        assertEquals(listOf(episode), BackupMerge.replace(emptySnapshot(), restored, sections).chapters)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupEncryptionTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines BackupEncryptionTest, encryptedNativeBackupRequiresPasswordAndWrongPasswordDoesNotMutate, encryptedExportIsRawYokanAndCanBeOpenedWithoutMutation, createBackupEncryptsWhenBackupEncryptionEnabled, writeBytes, createBackupThrowsWhenEncryptionEnabledWithoutPassword, openBackupAutomaticallyUsesStoredPasswordWhenNoneProvided, restoringEncryptedBackupPersistsResolvedPasswordAndEnablesEncryption, plainExportStripsBackupEncryptionPasswordUnlessSensitiveSettingsAllowed, mangayomiBackupWithEmbeddedPasswordRestoresPassword.

Read the setup, action and assertions in these cases before implementing their production paths:

  • encryptedNativeBackupRequiresPasswordAndWrongPasswordDoesNotMutate
  • encryptedExportIsRawYokanAndCanBeOpenedWithoutMutation
  • createBackupEncryptsWhenBackupEncryptionEnabled
  • createBackupThrowsWhenEncryptionEnabledWithoutPassword
  • openBackupAutomaticallyUsesStoredPasswordWhenNoneProvided
  • restoringEncryptedBackupPersistsResolvedPasswordAndEnablesEncryption
  • plainExportStripsBackupEncryptionPasswordUnlessSensitiveSettingsAllowed
  • mangayomiBackupWithEmbeddedPasswordRestoresPassword

Cross-chapter imports used by this file: NoNotifications, DbManga, InMemoryYokanDatabase, seedDatabaseSnapshot. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class BackupEncryptionTest {
    @Test
    fun encryptedNativeBackupRequiresPasswordAndWrongPasswordDoesNotMutate() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Local")),
        ))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val payload = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("manga"),
            mangas = listOf(DbManga(id = 7, name = "Encrypted")),
        ))
        val envelope = (PasswordBackupEnvelope.encode(payload, "correct") as PasswordBackupEnvelopeResult.Success).bytes
        val before = database.snapshot()

        assertEquals(BackupOpenError.PasswordRequired, (service.openBackup(envelope) as BackupOpenResult.Failure).error)
        assertEquals(before, database.snapshot())
        assertEquals(
            BackupOpenError.AuthenticationFailed,
            (service.openBackup(envelope, "wrong") as BackupOpenResult.Failure).error,
        )
        assertEquals(before, database.snapshot())

        val opened = service.openBackup(envelope, "correct") as BackupOpenResult.Ready
        service.applyBackup(opened.plan)
        assertEquals(listOf("Encrypted"), database.mangas().map { it.name })
    }

    @Test
    fun encryptedExportIsRawYokanAndCanBeOpenedWithoutMutation() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)

        val export = service.exportEncryptedBackup(BackupOptions(compressionLevel = 9), "sëcret")
        assertTrue(export.fileName.endsWith(".yokanbak"))
        assertTrue(export.bytes.copyOfRange(0, 8).contentEquals("YOKANENC".encodeToByteArray()))

        val opened = service.openBackup(export.bytes, "sëcret")
        assertTrue(opened is BackupOpenResult.Ready)
        assertTrue(database.snapshot() == seedDatabaseSnapshot())
    }

    @Test
    fun createBackupEncryptsWhenBackupEncryptionEnabled() = runTest {
        val seed = seedDatabaseSnapshot()
        val database = InMemoryYokanDatabase(
            seed.copy(
                settings = seed.settings.copy(
                    backupEncryptionEnabled = true,
                    backupEncryptionPassword = "testPassword123",
                ),
            ),
        )
        val files = object : MemoryFileService() {
            var writtenPath: String? = null
            var writtenBytes: ByteArray? = null
            override fun writeBytes(path: String, bytes: ByteArray) {
                writtenPath = path
                writtenBytes = bytes
            }
        }
        val service = DefaultBackupService(database, files, PassthroughCompression(), NoNotifications)

        val result = service.createBackup()
        assertTrue(result.fileName.endsWith(".yokanbak"))
        assertNotNull(files.writtenBytes)
        assertTrue(files.writtenBytes!!.copyOfRange(0, 8).contentEquals("YOKANENC".encodeToByteArray()))
    }

    @Test
    fun createBackupThrowsWhenEncryptionEnabledWithoutPassword() = runTest {
        val seed = seedDatabaseSnapshot()
        val database = InMemoryYokanDatabase(
            seed.copy(
                settings = seed.settings.copy(
                    backupEncryptionEnabled = true,
                    backupEncryptionPassword = null,
                ),
            ),
        )
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)

        val ex = assertFailsWith<IllegalStateException> {
            service.createBackup()
        }
        assertTrue(ex.message?.contains("Backup encryption is enabled but no password is set") == true)
    }

    @Test
    fun openBackupAutomaticallyUsesStoredPasswordWhenNoneProvided() = runTest {
        val seed = seedDatabaseSnapshot()
        val database = InMemoryYokanDatabase(
            seed.copy(
                settings = seed.settings.copy(
                    backupEncryptionEnabled = true,
                    backupEncryptionPassword = "storedPassword456",
                ),
            ),
        )
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)

        val export = service.exportEncryptedBackup(BackupOptions(), "storedPassword456")

        // 1. Calling openBackup without password automatically succeeds using database.settings().backupEncryptionPassword
        val opened = service.openBackup(export.bytes)
        assertTrue(opened is BackupOpenResult.Ready)

        // 2. If stored password is wrong, returns AuthenticationFailed
        database.updateSettings(database.settings().copy(backupEncryptionPassword = "wrongPassword"))
        val openedWrong = service.openBackup(export.bytes)
        assertTrue(openedWrong is BackupOpenResult.Failure)
        assertEquals(BackupOpenError.AuthenticationFailed, openedWrong.error)

        // 3. If no stored password, returns PasswordRequired
        database.updateSettings(database.settings().copy(backupEncryptionPassword = null))
        val openedNone = service.openBackup(export.bytes)
        assertTrue(openedNone is BackupOpenResult.Failure)
        assertEquals(BackupOpenError.PasswordRequired, openedNone.error)
    }

    @Test
    fun restoringEncryptedBackupPersistsResolvedPasswordAndEnablesEncryption() = runTest {
        val sourceDb = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val sourceService = DefaultBackupService(sourceDb, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val export = sourceService.exportEncryptedBackup(BackupOptions(), "persistedSecret789")

        // Target database initially has encryption disabled and no password
        val targetDb = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                settings = seedDatabaseSnapshot().settings.copy(
                    backupEncryptionEnabled = false,
                    backupEncryptionPassword = null,
                ),
            ),
        )
        val targetService = DefaultBackupService(targetDb, MemoryFileService(), PassthroughCompression(), NoNotifications)

        val opened = targetService.openBackup(export.bytes, "persistedSecret789") as BackupOpenResult.Ready
        assertEquals("persistedSecret789", opened.plan.resolvedPassword)

        targetService.applyBackup(opened.plan)

        assertTrue(targetDb.settings().backupEncryptionEnabled, "Target DB should have backupEncryptionEnabled = true")
        assertEquals("persistedSecret789", targetDb.settings().backupEncryptionPassword)
    }

    @Test
    fun plainExportStripsBackupEncryptionPasswordUnlessSensitiveSettingsAllowed() = runTest {
        val seed = seedDatabaseSnapshot()
        val database = InMemoryYokanDatabase(
            seed.copy(
                settings = seed.settings.copy(
                    backupEncryptionPassword = "superSecretPassword",
                ),
            ),
        )
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)

        // Default export (includeSensitiveSettings = false) strips backupEncryptionPassword
        val plainExport = service.exportBackup(BackupOptions(includeSettings = true, includeSensitiveSettings = false))
        val text = plainExport.bytes.decodeToString()
        assertFalse(text.contains("superSecretPassword"), "Plain backup without sensitive settings must not contain password")

        // Sensitive export retains backupEncryptionPassword
        val sensitiveExport = service.exportBackup(BackupOptions(includeSettings = true, includeSensitiveSettings = true))
        val sensitiveText = sensitiveExport.bytes.decodeToString()
        assertTrue(sensitiveText.contains("superSecretPassword"), "Sensitive backup must preserve backupEncryptionPassword")
    }

    @Test
    fun mangayomiBackupWithEmbeddedPasswordRestoresPassword() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = """
            {
              "version": "2",
              "backupEncryptionPassword": "mangayomiSecret",
              "manga": [],
              "chapters": [],
              "categories": [],
              "history": [],
              "downloads": [],
              "extensions": []
            }
        """.trimIndent().encodeToByteArray()

        val opened = service.openBackup(bytes) as BackupOpenResult.Ready
        service.applyBackup(opened.plan)

        assertTrue(database.settings().backupEncryptionEnabled)
        assertEquals("mangayomiSecret", database.settings().backupEncryptionPassword)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupFormatCompatibilityTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines BackupFormatCompatibilityTest, restoringABackupCanAddRepositoriesAndExtensionsToAnEmptyInstall, nativeGzipMangayomiAndExternalBackupsUseOpenApplyPath, unknownSchemaIsRejectedBeforeMutation, legacyNativePresenceUsesRawKeysAndConservativelyKeepsUnknownTitleTypes, restoresMangayomiFlutterBackupJson, mangayomiSourceLanguageUsesUpstreamOrdinals.

Read the setup, action and assertions in these cases before implementing their production paths:

  • restoringABackupCanAddRepositoriesAndExtensionsToAnEmptyInstall
  • nativeGzipMangayomiAndExternalBackupsUseOpenApplyPath
  • unknownSchemaIsRejectedBeforeMutation
  • legacyNativePresenceUsesRawKeysAndConservativelyKeepsUnknownTitleTypes
  • restoresMangayomiFlutterBackupJson
  • mangayomiSourceLanguageUsesUpstreamOrdinals

Cross-chapter imports used by this file: NoNotifications, DbCategory, DbItemType, DbManga, DbRepo, DbSettings. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.Manga
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json

class BackupFormatCompatibilityTest {
    @Test
    fun restoringABackupCanAddRepositoriesAndExtensionsToAnEmptyInstall() = runTest {
        val database = InMemoryYokanDatabase()
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val restoredSettings = DbSettings(
            mangaExtensionsRepo = listOf(DbRepo(name = "Manga", jsonUrl = "https://catalog.example/manga/index.json")),
            animeExtensionsRepo = listOf(DbRepo(name = "Anime", jsonUrl = "https://catalog.example/anime/index.json")),
            novelExtensionsRepo = listOf(DbRepo(name = "Novels", jsonUrl = "https://catalog.example/novels/index.json")),
        )
        val source = DbSource(id = 42, name = "Restored extension", sourceCode = "user extension payload", isAdded = true)

        service.restore(native(BackupSnapshot(createdAtMillis = 1, settings = restoredSettings, sources = listOf(source))))

        assertEquals(restoredSettings.mangaExtensionsRepo, database.settings().mangaExtensionsRepo)
        assertEquals(restoredSettings.animeExtensionsRepo, database.settings().animeExtensionsRepo)
        assertEquals(restoredSettings.novelExtensionsRepo, database.settings().novelExtensionsRepo)
        val restoredSource = database.sources().single()
        assertEquals(source.name, restoredSource.name)
        assertEquals(source.sourceCode, restoredSource.sourceCode)
        assertTrue(restoredSource.isAdded)
    }

    @Test
    fun nativeGzipMangayomiAndExternalBackupsUseOpenApplyPath() = runTest {
        val nativeBytes = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("manga"),
            mangas = listOf(DbManga(id = 7, name = "Gzipped")),
        ))
        val gzipDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val gzipService = DefaultBackupService(gzipDatabase, MemoryFileService(), FixtureCompression(gzipInput = true), NoNotifications)
        val gzipPlan = gzipService.openBackup(nativeBytes) as BackupOpenResult.Ready
        gzipService.applyBackup(gzipPlan.plan)
        assertEquals(listOf("Gzipped"), gzipDatabase.mangas().map { it.name })

        val mangayomi = """
            {"version":"2","manga":[{"id":7,"name":"Flutter","status":1,"isManga":true}],"categories":[]}
        """.trimIndent().encodeToByteArray()
        val mangayomiDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val mangayomiService = DefaultBackupService(
            mangayomiDatabase,
            MemoryFileService(),
            FixtureCompression(zipEntries = mapOf("restore.backup.db" to mangayomi)),
            NoNotifications,
        )
        val mangayomiPlan = mangayomiService.openBackup(ByteArray(4)) as BackupOpenResult.Ready
        mangayomiService.applyBackup(mangayomiPlan.plan)
        assertEquals(listOf("Flutter"), mangayomiDatabase.mangas().map { it.name })

        val tachiyomi = ProtoWriter().apply {
            message(1) { string(3, "Mihon") }
        }.toByteArray()
        val tachiyomiDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val tachiyomiService = DefaultBackupService(tachiyomiDatabase, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val tachiyomiPlan = tachiyomiService.openBackup(tachiyomi) as BackupOpenResult.Ready
        tachiyomiService.applyBackup(tachiyomiPlan.plan)
        assertEquals(listOf("Mihon"), tachiyomiDatabase.mangas().map { it.name })

        val kotatsuDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            categories = listOf(DbCategory(id = 2, name = "Old", forItemType = DbItemType.Manga)),
        ))
        val kotatsuService = DefaultBackupService(
            kotatsuDatabase,
            MemoryFileService(),
            FixtureCompression(
                zipEntries = mapOf(
                    "favourites" to """[{"manga":{"title":"Kotatsu","public_url":"https://k/1"}}]""".encodeToByteArray(),
                    "categories" to "[]".encodeToByteArray(),
                ),
            ),
            NoNotifications,
        )
        val kotatsuPlan = kotatsuService.openBackup(ByteArray(4)) as BackupOpenResult.Ready
        kotatsuService.applyBackup(kotatsuPlan.plan)
        assertEquals(listOf("Kotatsu"), kotatsuDatabase.mangas().map { it.name })
        assertTrue(kotatsuDatabase.categories().isEmpty(), "raw empty Kotatsu section was not applied")
    }

    @Test
    fun unknownSchemaIsRejectedBeforeMutation() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Local")),
        ))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val before = database.snapshot()
        val bytes = """{"schemaVersion":99,"includedSections":["manga"],"mangas":[]}""".encodeToByteArray()

        assertEquals(BackupOpenError.Unsupported, (service.openBackup(bytes) as BackupOpenResult.Failure).error)
        assertEquals(before, database.snapshot())
    }

    @Test
    fun legacyNativePresenceUsesRawKeysAndConservativelyKeepsUnknownTitleTypes() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Local", itemType = DbItemType.Manga)),
            categories = listOf(DbCategory(id = 2, name = "Local category", forItemType = DbItemType.Manga)),
        ))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        // No manifest is the legacy shape. The empty categories array is
        // authoritative; an empty shared mangas array cannot say whether
        // manga, anime, or novel was selected, so it is preserved.
        val bytes = """
            {"schemaVersion":1,"createdAtMillis":1,"mangas":[],"categories":[]}
        """.trimIndent().encodeToByteArray()

        val opened = service.openBackup(bytes) as BackupOpenResult.Ready
        service.applyBackup(opened.plan)

        assertEquals(listOf("Local"), database.mangas().map { it.name })
        assertTrue(database.categories().isEmpty())
    }

    @Test
    fun restoresMangayomiFlutterBackupJson() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        // Shape produced by the old Flutter app: version "2", singular keys,
        // enums as ordinal indices, explicit nulls, legacy pos/hide/isManga.
        val bytes = """
            {
              "version": "2",
              "manga": [
                {"id": 7, "name": "Imported", "status": 1, "isManga": true, "scanlator": null}
              ],
              "chapters": [
                {"id": 70, "mangaId": 7, "name": "Ch 1", "url": "u7", "scanlator": null}
              ],
              "categories": [
                {"id": 3, "name": "Favs", "pos": 2, "hide": false, "forManga": true}
              ],
              "history": [],
              "downloads": [],
              "extensions": []
            }
        """.trimIndent().encodeToByteArray()

        val opened = service.openBackup(bytes) as BackupOpenResult.Ready
        val preview = service.applyBackup(opened.plan)

        assertEquals(listOf("Imported"), database.mangas().map { it.name })
        assertEquals(listOf("Ch 1"), database.chapters().map { it.name })
        assertEquals(listOf(2), database.categories().filter { it.id == 3L }.map { it.position })
        assertEquals(3, preview.itemCount)
        assertEquals(1, preview.mangaCount)
    }

    @Test
    fun mangayomiSourceLanguageUsesUpstreamOrdinals() {
        // Mangayomi: SourceCodeLanguage { dart, javascript, mihon, lnreader, aidoku }.
        val root = Json.parseToJsonElement(
            """{"version":"2","extensions":[
              {"id":1,"sourceCodeLanguage":0},{"id":2,"sourceCodeLanguage":1},{"id":3,"sourceCodeLanguage":2},
              {"id":4,"sourceCodeLanguage":3},{"id":5,"sourceCodeLanguage":4}]}""",
        ) as kotlinx.serialization.json.JsonObject
        val sources = MangayomiBackupCodec.decode(root).sources
        val expected = listOf(
            DbSourceCodeLanguage.JavaScript, // Dart is unsupported; keeps the default.
            DbSourceCodeLanguage.JavaScript,
            DbSourceCodeLanguage.Mihon,
            DbSourceCodeLanguage.LnReader,
            DbSourceCodeLanguage.Aidoku,
        )
        assertEquals(expected, sources.map { it.sourceCodeLanguage })

        val reencoded = Json.parseToJsonElement(MangayomiBackupCodec.encode(BackupSnapshot(createdAtMillis = 1, sources = sources.drop(1))))
        assertEquals(sources.drop(1), MangayomiBackupCodec.decode(reencoded as kotlinx.serialization.json.JsonObject).sources)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupNotesAndSettingsRemapTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines BackupNotesAndSettingsRemapTest, unicodeNotesSurviveNativeRoundTripAndMergeButLegacyReplaceClearsThem, cloudStyleExportOmitsTextAndReplacePreservesMatchingLocalNotes, externalExportDoesNotIncludePrivateNoteText, compress, decompress, zipSingleEntry, presetsRoundTripInNativeSettingsAndMergeRemapsSourceIdentity, settingsOnlyRestoreMatchesTheSourceIdentityAndRejectsAnUnrelatedReusedId, releasePreferencesRoundTripAndRemapTitleOverridesWithoutTouchingExistingDefaults and 1 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • unicodeNotesSurviveNativeRoundTripAndMergeButLegacyReplaceClearsThem
  • cloudStyleExportOmitsTextAndReplacePreservesMatchingLocalNotes
  • externalExportDoesNotIncludePrivateNoteText
  • presetsRoundTripInNativeSettingsAndMergeRemapsSourceIdentity
  • settingsOnlyRestoreMatchesTheSourceIdentityAndRejectsAnUnrelatedReusedId
  • releasePreferencesRoundTripAndRemapTitleOverridesWithoutTouchingExistingDefaults
  • automaticLayoutNativeBackupsRemapOwnersAndSettingsOnlyDoesNotGuessTitleIds

Cross-chapter imports used by this file: NoNotifications, DbChapterReleasePreference, DbManga, DbSavedSearch, DbPresetFilter, DbPresetOption. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.database.DbChapterReleasePreference
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.database.DbPresetFilter
import eu.friedcutlet.yokan.database.DbPresetOption
import eu.friedcutlet.yokan.database.DbPresetSelection
import eu.friedcutlet.yokan.database.presetIdentity
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json

class BackupNotesAndSettingsRemapTest {
    @Test
    fun unicodeNotesSurviveNativeRoundTripAndMergeButLegacyReplaceClearsThem() = runTest {
        val note = "秘密 🌙\nLine two\n  spaces  "
        val original = seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Title", link = "/t", favorite = true, privateNote = note)),
        )
        val source = DefaultBackupService(InMemoryYokanDatabase(original), MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = source.exportBackup(BackupOptions()).bytes
        val target = InMemoryYokanDatabase(original.copy(mangas = emptyList()))
        val service = DefaultBackupService(target, MemoryFileService(), PassthroughCompression(), NoNotifications)
        service.restore(bytes)
        assertEquals(note, target.mangas().single().privateNote)

        val legacy = native(BackupSnapshot(createdAtMillis = 1, mangas = listOf(
            DbManga(id = 1, name = "Title", link = "/t", favorite = true),
        ))).decodeToString().replace(",\"privateNote\":\"\"", "").encodeToByteArray()
        val legacyPlan = (service.openBackup(legacy) as BackupOpenResult.Ready).plan
        service.applyBackup(legacyPlan, RestoreMode.Merge)
        assertEquals(note, target.mangas().single().privateNote)
        val different = (service.openBackup(native(BackupSnapshot(createdAtMillis = 1, mangas = listOf(
            DbManga(id = 1, name = "Title", link = "/t", favorite = true, privateNote = "Imported"),
        )))) as BackupOpenResult.Ready).plan
        service.applyBackup(different, RestoreMode.Merge)
        assertEquals("$note\n\n---\n\nImported", target.mangas().single().privateNote)
        service.applyBackup(different, RestoreMode.Merge)
        assertEquals("$note\n\n---\n\nImported", target.mangas().single().privateNote)
        service.applyBackup(legacyPlan, RestoreMode.Replace)
        assertEquals("", target.mangas().single().privateNote)
    }

    @Test
    fun cloudStyleExportOmitsTextAndReplacePreservesMatchingLocalNotes() = runTest {
        val original = seedDatabaseSnapshot().copy(mangas = listOf(
            DbManga(id = 1, name = "Title", link = "/t", favorite = true, privateNote = "PRIVATE_SENTINEL"),
        ))
        val database = InMemoryYokanDatabase(original)
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = service.exportBackup(BackupOptions(includePrivateNotes = false)).bytes
        assertFalse(bytes.decodeToString().contains("PRIVATE_SENTINEL"))
        val payload = Json.decodeFromString(BackupSnapshot.serializer(), bytes.decodeToString())
        assertFalse(payload.privateNotesIncluded)
        val ready = service.openBackup(bytes) as BackupOpenResult.Ready
        service.applyBackup(ready.plan, RestoreMode.Replace)
        assertEquals("PRIVATE_SENTINEL", database.mangas().single().privateNote)
    }

    @Test
    fun externalExportDoesNotIncludePrivateNoteText() {
        val compression = object : BackupCompression {
            override fun compress(data: ByteArray, level: Int) = data
            override fun decompress(data: ByteArray) = data
            // Inspect the formatted content passed to the archive writer.
            override fun zipSingleEntry(entryName: String, data: ByteArray, level: Int) = data
        }
        val snapshot = seedDatabaseSnapshot().copy(mangas = listOf(
            DbManga(id = 1, name = "Title", favorite = true, privateNote = "PRIVATE_SENTINEL"),
        ))
        val bytes = BackupExporter(compression).export(snapshot, BackupOptions(format = BackupFormat.Mangayomi)).bytes
        assertFalse(bytes.decodeToString().contains("PRIVATE_SENTINEL"))
        assertFalse(bytes.decodeToString().contains("privateNote"))
    }

    @Test
    fun presetsRoundTripInNativeSettingsAndMergeRemapsSourceIdentity() = runTest {
        val originalSource = DbSource(id = 50, name = "Preset source", baseUrl = "https://preset.test", lang = "en")
        val preset = DbSavedSearch(sourceId = 50, name = "Filters only", query = "", id = "stable-preset",
            sourceIdentity = originalSource.presetIdentity(), filterSchemaRecorded = true,
            filters = listOf(DbPresetFilter("genre", "Genre", "Group", "MultiSelect", true,
                listOf(DbPresetOption("Action", "action")), null, selection = DbPresetSelection.Multi(setOf("action")))))
        val original = seedDatabaseSnapshot().copy(sources = listOf(originalSource), mangas = emptyList(),
            settings = seedDatabaseSnapshot().settings.copy(savedSearches = listOf(preset)))
        val exporting = DefaultBackupService(InMemoryYokanDatabase(original), MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = exporting.exportBackup(BackupOptions()).bytes
        val target = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(sources = listOf(originalSource.copy(id = 7)), mangas = emptyList(),
            settings = seedDatabaseSnapshot().settings.copy(savedSearches = listOf(
                DbSavedSearch(7, "Existing", "existing", id = "existing"),
            ))))
        val service = DefaultBackupService(target, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val plan = (service.openBackup(bytes) as BackupOpenResult.Ready).plan
        service.applyBackup(plan, RestoreMode.Merge)
        val merged = target.settings().savedSearches.orEmpty()
        assertEquals(2, merged.size)
        assertEquals(7L, merged.single { it.id == preset.id }.sourceId)
        assertEquals(preset.sourceIdentity, merged.single { it.id == preset.id }.sourceIdentity)
        service.applyBackup(plan, RestoreMode.Merge)
        assertEquals(2, target.settings().savedSearches.orEmpty().size)
        service.applyBackup(plan, RestoreMode.Replace)
        assertEquals(listOf(preset), target.settings().savedSearches)
    }

    @Test
    fun settingsOnlyRestoreMatchesTheSourceIdentityAndRejectsAnUnrelatedReusedId() = runTest {
        val source = DbSource(id = 50, name = "Original", baseUrl = "https://original.test", lang = "en")
        val preset = DbSavedSearch(50, "Original filters", "query", id = "preset",
            sourceIdentity = source.presetIdentity())
        val snapshot = seedDatabaseSnapshot().copy(settings = seedDatabaseSnapshot().settings.copy(savedSearches = listOf(preset)),
            sources = listOf(source))
        val exporter = DefaultBackupService(InMemoryYokanDatabase(snapshot), MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = exporter.exportBackup(BackupOptions(includeSources = false)).bytes
        val target = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(sources = listOf(
            source.copy(id = 50, name = "Unrelated", baseUrl = "https://unrelated.test"), source.copy(id = 7),
        )))
        val service = DefaultBackupService(target, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val plan = (service.openBackup(bytes) as BackupOpenResult.Ready).plan
        service.applyBackup(plan, RestoreMode.Merge)
        assertEquals(7L, target.settings().savedSearches.orEmpty().single().sourceId)
        assertEquals(preset.sourceIdentity, target.settings().savedSearches.orEmpty().single().sourceIdentity)
    }

    @Test
    fun releasePreferencesRoundTripAndRemapTitleOverridesWithoutTouchingExistingDefaults() = runTest {
        val manga = DbManga(id = 50, name = "Release title", link = "/release", favorite = true)
        val defaults = DbChapterReleasePreference(scanlatorPriority = listOf("B", "A", ""), skipDuplicateReleases = true)
        val override = defaults.copy(mangaId = 50, scanlatorPriority = listOf("A", "B", ""))
        val snapshot = seedDatabaseSnapshot().copy(mangas = listOf(manga), chapters = emptyList(),
            settings = seedDatabaseSnapshot().settings.copy(chapterReleasePreferences = listOf(defaults, override)))
        val exporter = DefaultBackupService(InMemoryYokanDatabase(snapshot), MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = exporter.exportBackup(BackupOptions()).bytes
        val localDefault = DbChapterReleasePreference(scanlatorPriority = listOf("Local"))
        val target = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(manga.copy(id = 7)), chapters = emptyList(),
            settings = seedDatabaseSnapshot().settings.copy(chapterReleasePreferences = listOf(localDefault))))
        val service = DefaultBackupService(target, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val plan = (service.openBackup(bytes) as BackupOpenResult.Ready).plan
        service.applyBackup(plan, RestoreMode.Merge)
        assertEquals(listOf(localDefault, override.copy(mangaId = 7)), target.settings().chapterReleasePreferences)
        service.applyBackup(plan, RestoreMode.Merge)
        assertEquals(2, target.settings().chapterReleasePreferences.size)
        service.applyBackup(plan, RestoreMode.Replace)
        assertEquals(listOf(defaults, override), target.settings().chapterReleasePreferences)
        val settingsOnly = exporter.exportBackup(BackupOptions(includeManga = false, includeAnime = false, includeNovel = false)).bytes
        val settingsPlan = (service.openBackup(settingsOnly) as BackupOpenResult.Ready).plan
        service.applyBackup(settingsPlan, RestoreMode.Replace)
        assertEquals(listOf(defaults), target.settings().chapterReleasePreferences)
    }

    @Test
    fun automaticLayoutNativeBackupsRemapOwnersAndSettingsOnlyDoesNotGuessTitleIds() = runTest {
        val manga = DbManga(id = 50, name = "Automatic title", link = "/automatic", favorite = true)
        val preference = eu.friedcutlet.yokan.database.DbAutomaticReaderLayout(50, fallback = eu.friedcutlet.yokan.database.DbReaderMode.Rtl)
        val snapshot = seedDatabaseSnapshot().copy(mangas = listOf(manga), chapters = emptyList(),
            settings = seedDatabaseSnapshot().settings.copy(automaticReaderLayout = true, readerHoldToScroll = true, automaticReaderLayouts = listOf(preference)))
        val exporter = DefaultBackupService(InMemoryYokanDatabase(snapshot), MemoryFileService(), PassthroughCompression(), NoNotifications)
        val target = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(manga.copy(id = 7)), chapters = emptyList()))
        val service = DefaultBackupService(target, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val plan = (service.openBackup(exporter.exportBackup(BackupOptions()).bytes) as BackupOpenResult.Ready).plan
        service.applyBackup(plan, RestoreMode.Merge)
        assertEquals(listOf(preference.copy(mangaId = 7)), target.settings().automaticReaderLayouts)
        assertFalse(target.settings().readerHoldToScroll)
        service.applyBackup(plan, RestoreMode.Merge)
        assertEquals(1, target.settings().automaticReaderLayouts.size)
        service.applyBackup(plan, RestoreMode.Replace)
        assertTrue(target.settings().automaticReaderLayout)
        assertTrue(target.settings().readerHoldToScroll)
        assertEquals(listOf(preference), target.settings().automaticReaderLayouts)
        val settingsOnly = exporter.exportBackup(BackupOptions(includeManga = false, includeAnime = false, includeNovel = false)).bytes
        service.applyBackup((service.openBackup(settingsOnly) as BackupOpenResult.Ready).plan, RestoreMode.Replace)
        assertTrue(target.settings().automaticReaderLayout)
        assertTrue(target.settings().automaticReaderLayouts.isEmpty())
        assertTrue(target.settings().readerHoldToScroll)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupSafetySnapshotTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines BackupSafetySnapshotTest, guardedRestoreRejectsChangedAccountBeforeSafetySnapshotOrMutation, guardedRestoreCannotOverwriteAccountChangedAfterSnapshotAcceptance, guardedRestoreRetainsTargetCredentialsAndCreatesSafetySnapshot, restoreLeavesDatabaseUntouchedWhenSafetyBackupFails, writeBytes, restoreConflictDuringSafetyFileWritePreservesConcurrentEditWithoutRollback, safetyMetadataFailureDoesNotInvokeReplacement, safetySnapshotCreatedAndRollbackRestoresPreviousState.

Read the setup, action and assertions in these cases before implementing their production paths:

  • guardedRestoreRejectsChangedAccountBeforeSafetySnapshotOrMutation
  • guardedRestoreCannotOverwriteAccountChangedAfterSnapshotAcceptance
  • guardedRestoreRetainsTargetCredentialsAndCreatesSafetySnapshot
  • restoreLeavesDatabaseUntouchedWhenSafetyBackupFails
  • restoreConflictDuringSafetyFileWritePreservesConcurrentEditWithoutRollback
  • safetyMetadataFailureDoesNotInvokeReplacement
  • safetySnapshotCreatedAndRollbackRestoresPreviousState

Cross-chapter imports used by this file: NoNotifications, DbManga, DbSyncPreference, InMemoryYokanDatabase, SnapshotReplacementConflictException, seedDatabaseSnapshot. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class BackupSafetySnapshotTest {
    @Test
    fun guardedRestoreRejectsChangedAccountBeforeSafetySnapshotOrMutation() = runTest {
        val captured = DbSyncPreference(syncId = 1, server = "cloud://test", authToken = "old")
        val selected = captured.copy(authToken = "new")
        val initial = seedDatabaseSnapshot().copy(syncPreferences = listOf(selected))
        val database = InMemoryYokanDatabase(initial)
        val files = MemoryFileService()
        val service = DefaultBackupService(database, files, PassthroughCompression(), NoNotifications)
        val bytes = native(BackupSnapshot(createdAtMillis = 1, mangas = listOf(DbManga(id = 99, name = "Remote"))))
        assertFailsWith<BackupRestoreTargetChangedException> {
            service.restoreIf(bytes) { it.syncPreferences.single() == captured }
        }
        assertEquals(initial, database.snapshot())
        assertTrue(files.files.isEmpty())
    }

    @Test
    fun guardedRestoreCannotOverwriteAccountChangedAfterSnapshotAcceptance() = runTest {
        val captured = DbSyncPreference(syncId = 1, server = "cloud://test", authToken = "old")
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(syncPreferences = listOf(captured)))
        val replacement = captured.copy(authToken = "new")
        val files = MemoryFileService().apply { onWrite = { database.upsertSyncPreference(replacement) } }
        val service = DefaultBackupService(database, files, PassthroughCompression(), NoNotifications)
        val before = database.mangas()
        val bytes = native(BackupSnapshot(createdAtMillis = 1, mangas = listOf(DbManga(id = 99, name = "Remote"))))
        assertFailsWith<SnapshotReplacementConflictException> {
            service.restoreIf(bytes) { it.syncPreferences.single() == captured }
        }
        assertEquals(before, database.mangas())
        assertEquals(replacement, database.syncPreferences().single())
    }

    @Test
    fun guardedRestoreRetainsTargetCredentialsAndCreatesSafetySnapshot() = runTest {
        val account = DbSyncPreference(syncId = 1, server = "cloud://test", authToken = "target", email = "target-account")
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(syncPreferences = listOf(account)))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = native(BackupSnapshot(createdAtMillis = 1, mangas = listOf(DbManga(id = 99, name = "Remote"))))
        service.restoreIf(bytes) { it.syncPreferences.single() == account }
        assertEquals(account, database.syncPreferences().single())
        assertEquals(listOf("Remote"), database.mangas().map { it.name })
        assertEquals(1, service.listSafetySnapshots().size)
    }

    @Test
    fun restoreLeavesDatabaseUntouchedWhenSafetyBackupFails() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Original", favorite = true)),
        ))
        val before = database.snapshot()
        val files = object : MemoryFileService() {
            override fun writeBytes(path: String, bytes: ByteArray): Unit = error("Disk full")
        }
        val service = DefaultBackupService(database, files, PassthroughCompression(), NoNotifications)
        val opened = service.openBackup(native(BackupSnapshot(
            createdAtMillis = 200,
            mangas = listOf(DbManga(id = 2, name = "Incoming")),
        ))) as BackupOpenResult.Ready

        for (mode in RestoreMode.entries) {
            val failure = assertFailsWith<IllegalStateException> { service.applyBackup(opened.plan, mode) }
            assertEquals("Disk full", failure.message)
            assertEquals(before, database.snapshot())
        }
    }

    @Test
    fun restoreConflictDuringSafetyFileWritePreservesConcurrentEditWithoutRollback() = runTest {
        for (mode in RestoreMode.entries) {
            val database = CountingDatabase(InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
                mangas = listOf(DbManga(id = 1, name = "Original", favorite = true)),
            )))
            val files = MemoryFileService()
            var injected = false
            files.onWrite = {
                if (!injected) {
                    injected = true
                    database.upsertManga(database.mangas().single().copy(name = "Concurrent edit"))
                }
            }
            val service = DefaultBackupService(database, files, PassthroughCompression(), NoNotifications)
            val opened = service.openBackup(native(BackupSnapshot(
                createdAtMillis = 200,
                mangas = listOf(DbManga(id = 2, name = "Incoming")),
            ))) as BackupOpenResult.Ready

            assertFailsWith<SnapshotReplacementConflictException> {
                service.applyBackup(opened.plan, mode)
            }
            assertEquals(1, database.atomicReplacementCalls)
            assertEquals(listOf("Concurrent edit"), database.mangas().map { it.name })
        }
    }

    @Test
    fun safetyMetadataFailureDoesNotInvokeReplacement() = runTest {
        for (mode in RestoreMode.entries) {
            val database = CountingDatabase(InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
                mangas = listOf(DbManga(id = 1, name = "Original", favorite = true)),
            )))
            val before = database.snapshot()
            val files = object : MemoryFileService() {
                var writes = 0

                override fun writeBytes(path: String, bytes: ByteArray) {
                    if (++writes == 2) error("Metadata failed")
                    super.writeBytes(path, bytes)
                }
            }
            val service = DefaultBackupService(database, files, PassthroughCompression(), NoNotifications)
            val opened = service.openBackup(native(BackupSnapshot(
                createdAtMillis = 200,
                mangas = listOf(DbManga(id = 2, name = "Incoming")),
            ))) as BackupOpenResult.Ready

            assertFailsWith<IllegalStateException> {
                service.applyBackup(opened.plan, mode)
            }
            assertEquals(0, database.atomicReplacementCalls)
            assertEquals(before, database.snapshot())
        }
    }

    @Test
    fun safetySnapshotCreatedAndRollbackRestoresPreviousState() = runTest {
        val database = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                mangas = listOf(
                    DbManga(id = 1, name = "Original Title", favorite = true),
                ),
            ),
        )
        val fileService = MemoryFileService()
        val service = DefaultBackupService(database, fileService, PassthroughCompression(), NoNotifications)

        val incomingBackup = BackupSnapshot(
            createdAtMillis = 200,
            mangas = listOf(
                DbManga(id = 2, name = "Overwriting Title", favorite = true),
            ),
        )
        val bytes = native(incomingBackup)
        val opened = service.openBackup(bytes) as BackupOpenResult.Ready

        service.applyBackup(opened.plan, RestoreMode.Replace)

        // Title was replaced
        assertEquals(listOf("Overwriting Title"), database.mangas().map { it.name })

        // Safety snapshot was created
        val snapshots = service.listSafetySnapshots()
        assertEquals(1, snapshots.size)
        val snapshot = snapshots.first()
        assertTrue(snapshot.description.contains("Replace"))

        // Roll back the change
        service.rollbackSafetySnapshot(snapshot)

        // Database returned to original state
        assertEquals(listOf("Original Title"), database.mangas().map { it.name })

        // Safety snapshot list is now empty after rollback
        assertEquals(0, service.listSafetySnapshots().size)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupSelectiveRestoreTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines BackupSelectiveRestoreTest, restoreReplacesInsteadOfMerging, restoredDifferencesAreQueuedForTheHub, restoreKeepsOnlyDownloadMarksWhoseFilesExistOnThisDevice, openAndPreviewDoNotMutateDatabase, applyReplacesOnlySelectedCollectionsAndEmptySelectedClears, selectingOneTitleTypePreservesTheOtherTypes, incomingDependentRowsCannotCrossManifestTitleBoundary, identityCollisionRejectsBeforeMutation, dependentIdentityCollisionRejectsBeforeMutation and 6 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • restoreReplacesInsteadOfMerging
  • restoredDifferencesAreQueuedForTheHub
  • restoreKeepsOnlyDownloadMarksWhoseFilesExistOnThisDevice
  • openAndPreviewDoNotMutateDatabase
  • applyReplacesOnlySelectedCollectionsAndEmptySelectedClears
  • selectingOneTitleTypePreservesTheOtherTypes
  • incomingDependentRowsCannotCrossManifestTitleBoundary
  • identityCollisionRejectsBeforeMutation
  • dependentIdentityCollisionRejectsBeforeMutation
  • changedPartsAreMergedOnlyWhenSelected
  • applyFiltersInvalidDependentRecordsAgainstTheFinalGraph
  • selectedDependentSectionWithoutTitleTypesReplacesWholeSection
  • selectiveExportOpenApplyKeepsExcludedTypesAndTheirDependencies
  • restoreWithMergeModePreservesExistingTitlesAndMergesChaptersAndCategories
  • restoreWithReplaceModeWipesNonBackupTitles

Cross-chapter imports used by this file: DbActionType, NoNotifications, DbCategory, DbChangedPart, DbChapter, DbHistory. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbActionType
import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChangedPart
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.database.sync.SyncPaths
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json

private val LenientBackupJson = Json { ignoreUnknownKeys = true }

class BackupSelectiveRestoreTest {
    @Test
    fun restoreReplacesInsteadOfMerging() = runTest {
        val database = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                mangas = listOf(
                    DbManga(id = 1, name = "Stale title"),
                    DbManga(id = 2, name = "Another stale"),
                ),
                chapters = listOf(DbChapter(id = 10, mangaId = 1, name = "Stale ch", url = "u")),
            ),
        )
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val backup = BackupSnapshot(
            createdAtMillis = 1,
            mangas = listOf(DbManga(id = 7, name = "Restored title")),
            chapters = listOf(DbChapter(id = 70, mangaId = 7, name = "Restored ch", url = "u7")),
        )
        val bytes = native(backup)

        service.restore(bytes)

        assertEquals(listOf("Restored title"), database.mangas().map { it.name })
        assertEquals(listOf("Restored ch"), database.chapters().map { it.name })
    }

    @Test
    fun restoredDifferencesAreQueuedForTheHub() = runTest {
        val database = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                mangas = listOf(DbManga(id = 1, name = "Hub name"), DbManga(id = 2, name = "Gone"), DbManga(id = 3, name = "Same")),
                syncPreferences = listOf(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 4, hubHead = 50)),
            ),
        )
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)

        service.restore(native(BackupSnapshot(createdAtMillis = 1, mangas = listOf(DbManga(id = 1, name = "Backup name"), DbManga(id = 3, name = "Same")))))

        val ops = database.outbox().filter { it.kind == SyncPaths.KIND_MANGA }
        assertEquals("\"Backup name\"", ops.single { it.id == 1L && it.path == "name" }.value)
        assertEquals(SyncPaths.DELETED, ops.single { it.id == 2L }.path)
        assertTrue(ops.none { it.id == 3L }, "unchanged titles are not re-sent")
        assertTrue(ops.all { it.epoch == 4 }, "ops belong to the logged-in hub generation")
        assertEquals(0L, database.syncPreferences().single().hubHead)
    }

    @Test
    fun restoreKeepsOnlyDownloadMarksWhoseFilesExistOnThisDevice() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val files = MemoryFileService().apply { files["/here/ch1.cbz"] = byteArrayOf(1) }
        val service = DefaultBackupService(database, files, PassthroughCompression(), NoNotifications)

        service.restore(native(BackupSnapshot(
            createdAtMillis = 1,
            mangas = listOf(DbManga(id = 1, name = "Source title"), DbManga(id = 2, name = "Local title", isLocalArchive = true)),
            chapters = listOf(
                DbChapter(id = 10, mangaId = 1, name = "Here", url = "/c/1", archivePath = "/here/ch1.cbz", downloadSize = "1.0 MB"),
                DbChapter(id = 11, mangaId = 1, name = "Other device", url = "/c/2", archivePath = "/other/ch2", downloadSize = "2.0 MB"),
                DbChapter(id = 20, mangaId = 2, name = "Local", url = "local/Title/ch.cbz", archivePath = "local/Title/ch.cbz"),
            ),
        )))

        val chapters = database.chapters().associateBy { it.id }
        assertEquals("/here/ch1.cbz" to "1.0 MB", chapters.getValue(10).let { it.archivePath to it.downloadSize })
        assertEquals("" to null, chapters.getValue(11).let { it.archivePath to it.downloadSize }, "another device's download is not restored")
        assertEquals("local/Title/ch.cbz", chapters.getValue(20).archivePath, "local-library paths are not download marks")
    }

    @Test
    fun openAndPreviewDoNotMutateDatabase() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Local")),
            chapters = listOf(DbChapter(id = 2, mangaId = 1, name = "Local ch", url = "local")),
        ))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val before = database.snapshot()
        val bytes = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("manga", "chapters"),
            mangas = listOf(DbManga(id = 7, name = "Incoming")),
            chapters = listOf(DbChapter(id = 8, mangaId = 7, name = "Incoming ch", url = "incoming")),
        ))

        val opened = service.openBackup(bytes)
        assertTrue(opened is BackupOpenResult.Ready)
        service.previewBackup(opened.plan)

        assertEquals(before, database.snapshot())
    }

    @Test
    fun applyReplacesOnlySelectedCollectionsAndEmptySelectedClears() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(
                DbManga(id = 1, name = "Manga local", itemType = DbItemType.Manga),
                DbManga(id = 2, name = "Anime local", itemType = DbItemType.Anime),
            ),
            chapters = listOf(
                DbChapter(id = 3, mangaId = 1, name = "Clear", url = "clear"),
                DbChapter(id = 5, mangaId = 2, name = "Keep excluded", url = "keep-excluded"),
            ),
            categories = listOf(DbCategory(id = 4, name = "Keep category", forItemType = DbItemType.Manga)),
        ))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("manga", "categories"),
            mangas = emptyList(),
            categories = emptyList(),
            chapters = listOf(DbChapter(id = 99, mangaId = 99, name = "Ignored", url = "ignored")),
        ))

        val opened = service.openBackup(bytes) as BackupOpenResult.Ready
        service.applyBackup(opened.plan)

        assertEquals(listOf("Anime local"), database.mangas().map { it.name })
        assertTrue(database.categories().isEmpty(), "present-empty selected collection was not cleared")
        assertEquals(listOf("Keep excluded"), database.chapters().map { it.name })
    }

    @Test
    fun selectingOneTitleTypePreservesTheOtherTypes() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(
                DbManga(id = 1, name = "Manga local", itemType = DbItemType.Manga),
                DbManga(id = 2, name = "Anime local", itemType = DbItemType.Anime),
                DbManga(id = 3, name = "Novel local", itemType = DbItemType.Novel),
            ),
        ))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("anime"),
            mangas = listOf(
                DbManga(id = 20, name = "Anime incoming", itemType = DbItemType.Anime),
                DbManga(id = 21, name = "Should stay excluded", itemType = DbItemType.Manga),
            ),
        ))

        val opened = service.openBackup(bytes) as BackupOpenResult.Ready
        service.applyBackup(opened.plan)

        assertEquals(setOf("Manga local", "Anime incoming", "Novel local"), database.mangas().map { it.name }.toSet())
    }

    @Test
    fun incomingDependentRowsCannotCrossManifestTitleBoundary() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(
                DbManga(id = 1, name = "Manga local", itemType = DbItemType.Manga),
                DbManga(id = 2, name = "Anime local", itemType = DbItemType.Anime),
            ),
            chapters = listOf(DbChapter(id = 20, mangaId = 2, name = "Anime episode")),
            histories = listOf(DbHistory(id = 21, mangaId = 2, chapterId = 20, itemType = DbItemType.Anime)),
            updates = listOf(DbUpdate(id = 22, mangaId = 2, chapterId = 20)),
            tracks = listOf(DbTrack(id = 23, mangaId = 2, status = DbTrackStatus.Watching)),
        ))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("manga", "chapters", "history", "updates", "tracks"),
            mangas = listOf(DbManga(id = 10, name = "Imported manga", itemType = DbItemType.Manga)),
            chapters = listOf(
                DbChapter(id = 30, mangaId = 10, name = "Imported chapter"),
                DbChapter(id = 31, mangaId = 2, name = "Excluded incoming episode"),
            ),
            histories = listOf(
                DbHistory(id = 40, mangaId = 10, chapterId = 30, itemType = DbItemType.Manga),
                DbHistory(id = 41, mangaId = 2, chapterId = 20, itemType = DbItemType.Anime),
            ),
            updates = listOf(
                DbUpdate(id = 50, mangaId = 10, chapterId = 30),
                DbUpdate(id = 51, mangaId = 2, chapterId = 20),
            ),
            tracks = listOf(
                DbTrack(id = 60, mangaId = 10, status = DbTrackStatus.Reading),
                DbTrack(id = 61, mangaId = 2, status = DbTrackStatus.Watching),
            ),
        ))

        val opened = service.openBackup(bytes) as BackupOpenResult.Ready
        service.applyBackup(opened.plan)

        assertEquals(setOf(10L, 2L), database.mangas().map { it.id }.toSet())
        assertEquals(setOf(30L, 20L), database.chapters().map { it.id }.toSet())
        assertEquals(setOf(40L, 21L), database.histories().map { it.id }.toSet())
        assertEquals(setOf(50L, 22L), database.updates().map { it.id }.toSet())
        assertEquals(setOf(60L, 23L), database.tracks().map { it.id }.toSet())
    }

    @Test
    fun identityCollisionRejectsBeforeMutation() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(
                DbManga(id = 1, name = "Manga local", itemType = DbItemType.Manga),
                DbManga(id = 2, name = "Anime local", itemType = DbItemType.Anime),
            ),
        ))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val before = database.snapshot()
        val bytes = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("manga"),
            mangas = listOf(DbManga(id = 2, name = "Colliding manga", itemType = DbItemType.Manga)),
        ))

        assertFailsWith<IllegalStateException> {
            val opened = service.openBackup(bytes) as BackupOpenResult.Ready
            service.applyBackup(opened.plan)
        }
        assertEquals(before, database.snapshot())
    }

    @Test
    fun dependentIdentityCollisionRejectsBeforeMutation() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(
                DbManga(id = 1, name = "Manga local", itemType = DbItemType.Manga),
                DbManga(id = 2, name = "Anime local", itemType = DbItemType.Anime),
            ),
            chapters = listOf(DbChapter(id = 7, mangaId = 2, name = "Anime episode")),
        ))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val before = database.snapshot()
        val bytes = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("manga", "chapters"),
            mangas = listOf(DbManga(id = 3, name = "Incoming manga", itemType = DbItemType.Manga)),
            chapters = listOf(DbChapter(id = 7, mangaId = 3, name = "Colliding chapter")),
        ))

        assertFailsWith<IllegalStateException> {
            val opened = service.openBackup(bytes) as BackupOpenResult.Ready
            service.applyBackup(opened.plan)
        }
        assertEquals(before, database.snapshot())
    }

    @Test
    fun changedPartsAreMergedOnlyWhenSelected() = runTest {
        val localChange = DbChangedPart(
            id = 1,
            actionType = DbActionType.RemoveItem,
            isarId = 10,
            data = "local",
            clientDate = 1,
        )
        val incomingChange = localChange.copy(id = 99, data = "incoming")
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(changedParts = listOf(localChange)))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)

        val selected = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("changedParts"),
            changedParts = listOf(incomingChange),
        ))
        val selectedPlan = service.openBackup(selected) as BackupOpenResult.Ready
        service.applyBackup(selectedPlan.plan)
        assertEquals(listOf("local", "incoming"), database.changedParts().map { it.data })
        assertEquals(listOf(1L, 99L), database.changedParts().map { it.id })

        val absent = native(BackupSnapshot(createdAtMillis = 1, includedSections = emptyList(), changedParts = emptyList()))
        val absentPlan = service.openBackup(absent) as BackupOpenResult.Ready
        service.applyBackup(absentPlan.plan)
        assertEquals(listOf("local", "incoming"), database.changedParts().map { it.data })

        val selectedEmpty = native(BackupSnapshot(createdAtMillis = 1, includedSections = listOf("changedParts")))
        val selectedEmptyPlan = service.openBackup(selectedEmpty) as BackupOpenResult.Ready
        service.applyBackup(selectedEmptyPlan.plan)
        assertEquals(listOf("local", "incoming"), database.changedParts().map { it.data })
    }

    @Test
    fun applyFiltersInvalidDependentRecordsAgainstTheFinalGraph() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val bytes = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("manga", "categories", "chapters", "history", "updates", "tracks"),
            mangas = listOf(DbManga(id = 7, name = "Incoming", categories = listOf(1, 999))),
            categories = listOf(DbCategory(id = 1, name = "Valid", forItemType = DbItemType.Manga)),
            chapters = listOf(
                DbChapter(id = 70, mangaId = 7, name = "Valid chapter"),
                DbChapter(id = 71, mangaId = 999, name = "Orphan chapter"),
            ),
            histories = listOf(
                DbHistory(id = 80, mangaId = 7, chapterId = 70, itemType = DbItemType.Manga),
                DbHistory(id = 81, mangaId = 999, chapterId = 70, itemType = DbItemType.Manga),
            ),
            updates = listOf(
                DbUpdate(id = 90, mangaId = 7, chapterId = 70),
                DbUpdate(id = 91, mangaId = 7, chapterId = 999),
            ),
            tracks = listOf(
                DbTrack(id = 100, mangaId = 7, status = DbTrackStatus.Reading),
                DbTrack(id = 101, mangaId = 999, status = DbTrackStatus.Reading),
            ),
        ))

        val opened = service.openBackup(bytes) as BackupOpenResult.Ready
        service.applyBackup(opened.plan)

        assertEquals(listOf(7L), database.mangas().map { it.id })
        assertEquals(listOf(1L), database.mangas().single().categories)
        assertEquals(listOf(70L), database.chapters().map { it.id })
        assertEquals(listOf(80L), database.histories().map { it.id })
        assertEquals(listOf(90L), database.updates().map { it.id })
        assertEquals(listOf(100L), database.tracks().map { it.id })
    }

    @Test
    fun selectedDependentSectionWithoutTitleTypesReplacesWholeSection() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Existing")),
            chapters = listOf(DbChapter(id = 10, mangaId = 1, name = "Old chapter")),
        ))
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)

        val replacement = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("chapters"),
            chapters = listOf(
                DbChapter(id = 20, mangaId = 1, name = "Valid replacement"),
                DbChapter(id = 21, mangaId = 999, name = "Orphan replacement"),
            ),
        ))
        val replacementPlan = service.openBackup(replacement) as BackupOpenResult.Ready
        service.applyBackup(replacementPlan.plan)
        assertEquals(listOf("Valid replacement"), database.chapters().map { it.name })

        val selectedEmpty = native(BackupSnapshot(
            createdAtMillis = 1,
            includedSections = listOf("chapters"),
            chapters = emptyList(),
        ))
        val selectedEmptyPlan = service.openBackup(selectedEmpty) as BackupOpenResult.Ready
        service.applyBackup(selectedEmptyPlan.plan)
        assertTrue(database.chapters().isEmpty(), "selected-empty dependent section did not clear")
    }

    @Test
    fun selectiveExportOpenApplyKeepsExcludedTypesAndTheirDependencies() = runTest {
        val manga = DbManga(id = 1, name = "Manga", itemType = DbItemType.Manga, categories = listOf(10), sourceId = 20)
        val anime = DbManga(id = 2, name = "Anime", itemType = DbItemType.Anime, categories = listOf(11), sourceId = 21)
        val sourceManga = DbSource(id = 20, name = "Manga source", itemType = DbItemType.Manga)
        val sourceAnime = DbSource(id = 21, name = "Anime source", itemType = DbItemType.Anime)
        val mangaChapter = DbChapter(id = 30, mangaId = 1, name = "Manga chapter")
        val animeChapter = DbChapter(id = 31, mangaId = 2, name = "Anime episode")
        val sourceDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(manga, anime),
            categories = listOf(
                DbCategory(id = 10, name = "Manga category", forItemType = DbItemType.Manga),
                DbCategory(id = 11, name = "Anime category", forItemType = DbItemType.Anime),
            ),
            sources = listOf(sourceManga, sourceAnime),
            chapters = listOf(mangaChapter, animeChapter),
            histories = listOf(
                DbHistory(id = 40, mangaId = 1, chapterId = 30, itemType = DbItemType.Manga),
                DbHistory(id = 41, mangaId = 2, chapterId = 31, itemType = DbItemType.Anime),
            ),
            updates = listOf(
                DbUpdate(id = 50, mangaId = 1, chapterId = 30),
                DbUpdate(id = 51, mangaId = 2, chapterId = 31),
            ),
            tracks = listOf(
                DbTrack(id = 60, mangaId = 1, status = DbTrackStatus.Reading),
                DbTrack(id = 61, mangaId = 2, status = DbTrackStatus.Watching),
            ),
        ))
        val exporter = DefaultBackupService(sourceDatabase, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val export = exporter.exportBackup(BackupOptions(
            includeAnime = false,
            includeNovel = false,
            includeSettings = false,
            compressionLevel = 0,
        ))
        val exported = LenientBackupJson
            .decodeFromString(BackupSnapshot.serializer(), export.bytes.decodeToString())
        assertEquals(listOf(1L), exported.mangas.map { it.id })
        assertEquals(listOf(30L), exported.chapters.map { it.id })
        assertEquals(listOf(40L), exported.histories.map { it.id })
        assertEquals(listOf(50L), exported.updates.map { it.id })
        assertEquals(listOf(60L), exported.tracks.map { it.id })
        assertEquals(listOf(10L), exported.categories.map { it.id })
        assertEquals(listOf(20L), exported.sources.map { it.id })

        val targetDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(manga.copy(name = "Old manga"), anime),
            categories = listOf(
                DbCategory(id = 10, name = "Old manga category", forItemType = DbItemType.Manga),
                DbCategory(id = 11, name = "Anime category", forItemType = DbItemType.Anime),
            ),
            sources = listOf(sourceManga, sourceAnime),
            chapters = listOf(mangaChapter.copy(name = "Old chapter"), animeChapter),
            histories = listOf(
                DbHistory(id = 40, mangaId = 1, chapterId = 30, itemType = DbItemType.Manga),
                DbHistory(id = 41, mangaId = 2, chapterId = 31, itemType = DbItemType.Anime),
            ),
            updates = listOf(
                DbUpdate(id = 50, mangaId = 1, chapterId = 30),
                DbUpdate(id = 51, mangaId = 2, chapterId = 31),
            ),
            tracks = listOf(
                DbTrack(id = 60, mangaId = 1, status = DbTrackStatus.Reading),
                DbTrack(id = 61, mangaId = 2, status = DbTrackStatus.Watching),
            ),
        ))
        val applier = DefaultBackupService(targetDatabase, MemoryFileService(), PassthroughCompression(), NoNotifications)
        val opened = applier.openBackup(export.bytes) as BackupOpenResult.Ready
        applier.applyBackup(opened.plan)

        assertEquals(setOf("Manga", "Anime"), targetDatabase.mangas().map { it.name }.toSet())
        assertEquals(setOf(30L, 31L), targetDatabase.chapters().map { it.id }.toSet())
        assertEquals(setOf(40L, 41L), targetDatabase.histories().map { it.id }.toSet())
        assertEquals(setOf(50L, 51L), targetDatabase.updates().map { it.id }.toSet())
        assertEquals(setOf(60L, 61L), targetDatabase.tracks().map { it.id }.toSet())
        assertEquals(setOf(10L, 11L), targetDatabase.categories().map { it.id }.toSet())
        assertEquals(setOf(20L, 21L), targetDatabase.sources().map { it.id }.toSet())
    }

    @Test
    fun restoreWithMergeModePreservesExistingTitlesAndMergesChaptersAndCategories() = runTest {
        val database = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                categories = listOf(
                    DbCategory(id = 1, name = "Action", forItemType = DbItemType.Manga),
                ),
                mangas = listOf(
                    DbManga(id = 10, name = "One Piece", link = "https://example.com/op", favorite = true, categories = listOf(1L)),
                    DbManga(id = 20, name = "Naruto", link = "https://example.com/naruto", favorite = true),
                ),
                chapters = listOf(
                    DbChapter(id = 100, mangaId = 10, name = "Ch 1", url = "op/1", isRead = false, lastPageRead = "5"),
                ),
            ),
        )
        val fileService = MemoryFileService()
        val service = DefaultBackupService(database, fileService, PassthroughCompression(), NoNotifications)

        val incomingBackup = BackupSnapshot(
            createdAtMillis = 100,
            categories = listOf(
                DbCategory(id = 99, name = "Action", forItemType = DbItemType.Manga),
                DbCategory(id = 98, name = "Adventure", forItemType = DbItemType.Manga),
            ),
            mangas = listOf(
                DbManga(id = 50, name = "One Piece", link = "https://example.com/op", categories = listOf(99L, 98L)),
                DbManga(id = 60, name = "Bleach", link = "https://example.com/bleach", categories = listOf(98L)),
            ),
            chapters = listOf(
                DbChapter(id = 501, mangaId = 50, name = "Ch 1", url = "op/1", isRead = true, lastPageRead = "15"),
                DbChapter(id = 502, mangaId = 50, name = "Ch 2", url = "op/2", isRead = false, lastPageRead = "1"),
                DbChapter(id = 601, mangaId = 60, name = "Ch 1", url = "bleach/1", isRead = true),
            ),
        )
        val bytes = native(incomingBackup)
        val opened = service.openBackup(bytes) as BackupOpenResult.Ready

        // Verify preview stats
        assertEquals(1, opened.plan.preview.newSeriesCount) // Bleach
        assertEquals(1, opened.plan.preview.updatedSeriesCount) // One Piece
        assertEquals(2, opened.plan.preview.newChapterCount) // One Piece Ch 2 + Bleach Ch 1
        assertEquals(listOf("Action"), opened.plan.preview.conflictingCategories)

        // Apply in Merge mode
        service.applyBackup(opened.plan, RestoreMode.Merge)

        val finalMangas = database.mangas().associateBy { it.name }
        assertTrue("One Piece" in finalMangas)
        assertTrue("Naruto" in finalMangas, "Existing title not in backup must be preserved in merge mode")
        assertTrue("Bleach" in finalMangas, "New title from backup must be added in merge mode")

        val op = finalMangas.getValue("One Piece")
        assertTrue(op.favorite)
        val opCategoryNames = database.categories().filter { it.id in op.categories.orEmpty() }.map { it.name }.toSet()
        assertEquals(setOf("Action", "Adventure"), opCategoryNames)

        val opChapters = database.chapters(op.id).associateBy { it.url }
        val ch1 = opChapters.getValue("op/1")
        assertTrue(ch1.isRead, "Chapter progress should be merged (isRead = true)")
        assertEquals("15", ch1.lastPageRead, "Chapter lastPageRead should be maxOf(5, 15)")

        val ch2 = opChapters.getValue("op/2")
        assertFalse(ch2.isRead)

        val bleach = finalMangas.getValue("Bleach")
        val bleachChapters = database.chapters(bleach.id)
        assertEquals(1, bleachChapters.size)
        assertEquals("bleach/1", bleachChapters.first().url)
    }

    @Test
    fun restoreWithReplaceModeWipesNonBackupTitles() = runTest {
        val database = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                mangas = listOf(
                    DbManga(id = 10, name = "One Piece", link = "https://example.com/op", favorite = true),
                    DbManga(id = 20, name = "Naruto", link = "https://example.com/naruto", favorite = true),
                ),
            ),
        )
        val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)

        val incomingBackup = BackupSnapshot(
            createdAtMillis = 100,
            mangas = listOf(
                DbManga(id = 60, name = "Bleach", link = "https://example.com/bleach"),
            ),
        )
        val bytes = native(incomingBackup)
        val opened = service.openBackup(bytes) as BackupOpenResult.Ready

        // Apply in Replace mode
        service.applyBackup(opened.plan, RestoreMode.Replace)

        val mangaNames = database.mangas().map { it.name }
        assertEquals(listOf("Bleach"), mangaNames, "Replace mode must replace titles of included sections")
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupSensitiveSettingsTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines BackupSensitiveSettingsTest, PassthroughCompression, compress, decompress, service, database, trackingBackupsExcludeCredentialsUnlessSensitiveOptIn, sensitiveOptInExportsTrackerPreferences, discoveryTokenNeverLeavesDeviceThroughPortableBackup.

Read the setup, action and assertions in these cases before implementing their production paths:

  • externalDownloadSecretsAndWorkNeverLeaveDeviceEvenWithSensitiveOptIn
  • trackingBackupsExcludeCredentialsUnlessSensitiveOptIn
  • sensitiveOptInExportsTrackerPreferences
  • discoveryTokenNeverLeavesDeviceThroughPortableBackup

Cross-chapter imports used by this file: DbManga, NoNotifications, DbTrack, DbTrackPreference, InMemoryYokanDatabase, seedDatabaseSnapshot. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.files.MemoryFiles
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json

class BackupSensitiveSettingsTest {
    @Test fun externalDownloadSecretsAndWorkNeverLeaveDeviceEvenWithSensitiveOptIn() = runTest {
        val database = database()
        database.updateSettings(database.settings().let { current -> current.copy(features = current.features.copy(externalDownloads = eu.friedcutlet.yokan.database.DbExternalDownloads(
            preferred = eu.friedcutlet.yokan.database.PreferredDownloader.Aria2,
            endpoint = "https://aria.example.org/jsonrpc", secret = "RPC-PRIVATE-TOKEN", directory = "/downloads",
            jobs = listOf(eu.friedcutlet.yokan.database.DbRemoteDownloadJob("id", 1, eu.friedcutlet.yokan.database.DbItemType.Manga, "Title", "Chapter", "https://aria.example.org/jsonrpc", "binding", "/downloads/id",
                listOf(eu.friedcutlet.yokan.database.DbRemoteDownloadFile("1111111111111111", "page.jpg", "https://source.example.org/page?secret=SOURCE-PRIVATE", mapOf("Cookie" to "COOKIE-PRIVATE"))))),
        ))) })
        for (sensitive in listOf(false, true)) {
            val export = service(database).exportBackup(BackupOptions(includeSensitiveSettings = sensitive, compressionLevel = 0))
            val text = export.bytes.decodeToString()
            assertFalse(listOf("RPC-PRIVATE-TOKEN", "SOURCE-PRIVATE", "COOKIE-PRIVATE").any(text::contains))
            val payload = json.decodeFromString(BackupSnapshot.serializer(), text)
            assertEquals(eu.friedcutlet.yokan.database.DbExternalDownloads(), payload.settings?.features?.externalDownloads)
        }
    }

    private class PassthroughCompression : BackupCompression {
        override fun compress(data: ByteArray, level: Int): ByteArray = data
        override fun decompress(data: ByteArray): ByteArray = data
    }

    private fun service(database: InMemoryYokanDatabase) =
        DefaultBackupService(database, MemoryFiles(), PassthroughCompression(), NoNotifications)

    private fun database() = InMemoryYokanDatabase(
        seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Seed")),
            tracks = listOf(DbTrack(id = 5, mangaId = 1, mediaId = 42, syncId = 1, status = eu.friedcutlet.yokan.database.DbTrackStatus.Reading)),
            trackPreferences = listOf(DbTrackPreference(syncId = 1, username = "user", oauth = "SECRET-TOKEN")),
        ),
    )

    private val json = Json { ignoreUnknownKeys = true }

    @Test
    fun trackingBackupsExcludeCredentialsUnlessSensitiveOptIn() = runTest {
        val export = service(database()).exportBackup(
            BackupOptions(includeTracks = true, includeSensitiveSettings = false, compressionLevel = 0),
        )

        val payload = json.decodeFromString(BackupSnapshot.serializer(), export.bytes.decodeToString())
        assertEquals(1, payload.tracks.size)
        assertTrue(payload.trackPreferences.isEmpty(), "credentials leaked without sensitive opt-in")
        assertTrue("SECRET-TOKEN" !in export.bytes.decodeToString())
    }

    @Test
    fun sensitiveOptInExportsTrackerPreferences() = runTest {
        val export = service(database()).exportBackup(
            BackupOptions(includeTracks = true, includeSensitiveSettings = true, compressionLevel = 0),
        )

        val payload = json.decodeFromString(BackupSnapshot.serializer(), export.bytes.decodeToString())
        assertEquals(listOf("user"), payload.trackPreferences.map(DbTrackPreference::username))
    }

    @Test
    fun discoveryTokenNeverLeavesDeviceThroughPortableBackup() = runTest {
        val database = database()
        database.updateSettings(database.settings().copy(features = eu.friedcutlet.yokan.database.DbFeaturePreferences(
            home = eu.friedcutlet.yokan.database.DbHomePreferences(tmdbReadAccessToken = "HOME-DEVICE-SECRET"),
            downloads = eu.friedcutlet.yokan.database.DbDownloadPolicy(pendingNewChapterIds = setOf(1), consumedChapterIds = setOf(2), manuallyMarkedChapterIds = setOf(3)),
            discord = eu.friedcutlet.yokan.database.DbDiscordPreferences().withAccount(
                eu.friedcutlet.yokan.database.DbDiscordAccount(id = "1", username = "u", token = "DISCORD-DEVICE-SECRET"),
            ),
        )))
        for (sensitive in listOf(false, true)) {
            val export = service(database).exportBackup(BackupOptions(includeSensitiveSettings = sensitive, compressionLevel = 0))
            assertFalse(export.bytes.decodeToString().contains("HOME-DEVICE-SECRET"))
            assertFalse(export.bytes.decodeToString().contains("DISCORD-DEVICE-SECRET"))
            val payload = json.decodeFromString(BackupSnapshot.serializer(), export.bytes.decodeToString())
            assertEquals("", payload.settings?.home?.tmdbReadAccessToken)
            assertTrue(payload.settings?.features?.downloads?.pendingNewChapterIds.orEmpty().isEmpty())
            assertTrue(payload.settings?.features?.downloads?.consumedChapterIds.orEmpty().isEmpty())
            assertTrue(payload.settings?.features?.downloads?.manuallyMarkedChapterIds.orEmpty().isEmpty())
        }
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupTestFixtures.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines MemoryFileService, writeBytes, readBytes, canonicalPath, exists, deleteRecursively, directorySize, openLocation, listLocalEntries, listFiles and 10 further declarations.

Cross-chapter imports used by this file: InMemoryYokanDatabase, YokanDatabase, YokanDatabaseSnapshot, LocalEntry, LocalFileEntry, LocalFileService. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.services.files.LocalEntry
import eu.friedcutlet.yokan.services.files.LocalFileEntry
import eu.friedcutlet.yokan.services.files.LocalFileService
import kotlinx.serialization.json.Json

internal open class MemoryFileService : LocalFileService {
    val files = mutableMapOf<String, ByteArray>()
    var onWrite: (() -> Unit)? = null
    override val downloadRoot: String = "/tmp/downloads"
    override val backupRoot: String = "/tmp/backups"
    override val cacheRoot: String = "/tmp/cache"
    override fun writeBytes(path: String, bytes: ByteArray) {
        onWrite?.invoke()
        files[path] = bytes
    }
    override fun readBytes(path: String): ByteArray = files[path] ?: ByteArray(0)
    override fun canonicalPath(path: String): String? = path
    override fun exists(path: String): Boolean = path in files
    override fun deleteRecursively(path: String): Boolean {
        files.keys.removeAll { it == path || it.startsWith("$path/") }
        return true
    }
    override fun directorySize(path: String): Long = files.filter { it.key.startsWith(path) }.values.sumOf { it.size.toLong() }
    override fun openLocation(path: String): Boolean = false
    override fun listLocalEntries(root: String): List<LocalEntry>? = emptyList()
    override fun listFiles(root: String): List<LocalFileEntry> = files.filter { it.key.startsWith(root) }.map {
        LocalFileEntry(it.key, it.key.substringAfterLast('/'), it.value.size.toLong(), 1000L)
    }
}

internal class PassthroughCompression : BackupCompression {
    override fun compress(data: ByteArray, level: Int): ByteArray = data
    override fun decompress(data: ByteArray): ByteArray = data
}

internal class FixtureCompression(
    private val gzipInput: Boolean = false,
    private val zipEntries: Map<String, ByteArray>? = null,
) : BackupCompression {
    override fun compress(data: ByteArray, level: Int): ByteArray = data
    override fun decompress(data: ByteArray): ByteArray = data
    override fun looksGzipped(data: ByteArray): Boolean = gzipInput
    override fun looksZipped(data: ByteArray): Boolean = zipEntries != null
    override suspend fun unzipEntriesAsync(data: ByteArray): Map<String, ByteArray>? = zipEntries
}

internal class CountingDatabase(
    private val delegate: InMemoryYokanDatabase,
) : YokanDatabase by delegate {
    var atomicReplacementCalls = 0

    override suspend fun replaceAllAtomically(
        snapshot: YokanDatabaseSnapshot,
        expectedSnapshot: YokanDatabaseSnapshot?,
        removedSourceIds: Set<Long>,
    ) {
        atomicReplacementCalls++
        delegate.replaceAllAtomically(snapshot, expectedSnapshot, removedSourceIds)
    }
}

internal val NativeBackupJson = Json { encodeDefaults = true }

internal fun native(snapshot: BackupSnapshot): ByteArray = NativeBackupJson
    .encodeToString(BackupSnapshot.serializer(), snapshot)
    .encodeToByteArray()

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupTitleStatusTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines BackupTitleStatusTest.

Read the setup, action and assertions in these cases before implementing their production paths:

  • nativeBackupsKeepEveryStatusAndReplacementRestoresThem
  • mangayomiOrdinalsStayFixedAndUnsupportedStatusesDowngradeToUnknown

Cross-chapter imports used by this file: DbItemType, DbManga, DbStatus, emptySnapshot. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.database.emptySnapshot
import kotlinx.serialization.json.*
import kotlin.test.Test
import kotlin.test.assertEquals

class BackupTitleStatusTest {
    private val payload = BackupSnapshot(
        createdAtMillis = 1,
        mangas = DbStatus.entries.mapIndexed { index, status ->
            DbManga(id = index + 1L, name = status.name, link = "/$index", itemType = DbItemType.Anime, status = status)
        },
    )

    @Test fun nativeBackupsKeepEveryStatusAndReplacementRestoresThem() {
        val decoded = BackupJson.decodeFromString(
            BackupSnapshot.serializer(), BackupJson.encodeToString(BackupSnapshot.serializer(), payload),
        )
        assertEquals(payload.mangas, decoded.mangas)
        val replaced = BackupMerge.replace(emptySnapshot(), decoded, setOf(BackupSection.Anime))
        assertEquals(DbStatus.entries, replaced.mangas.map { it.status })
    }

    @Test fun mangayomiOrdinalsStayFixedAndUnsupportedStatusesDowngradeToUnknown() {
        val root = BackupJson.parseToJsonElement(MangayomiBackupCodec.encode(payload)).jsonObject
        val ordinals = root.getValue("manga").jsonArray.map { it.jsonObject.getValue("status").jsonPrimitive.int }
        assertEquals(listOf(0, 1, 2, 3, 4, 5, 3, 3), ordinals)
        assertEquals(
            listOf(DbStatus.Ongoing, DbStatus.Completed, DbStatus.Canceled, DbStatus.Unknown, DbStatus.OnHiatus,
                DbStatus.PublishingFinished, DbStatus.Unknown, DbStatus.Unknown),
            MangayomiBackupCodec.decode(root).mangas.map { it.status },
        )
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/ExternalBackupDecodersTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines ExternalBackupDecodersTest, ProtoWriter, varint, string, bytes, message, tag, writeVarint, toByteArray, mihonFixture and 5 further declarations.

The source describes its contract as:

Minimal protobuf writer for building fixtures.

Read the setup, action and assertions in these cases before implementing their production paths:

  • decodesMihonBackup
  • licensedAndUpcomingStatusesRespectMangaAndAnimeSourceConstants
  • aniyomiAnimeFieldsMapToAnimeEntries
  • randomJsonIsNotMistakenForTachiyomi
  • decodesKotatsuFavourites

Cross-chapter imports used by this file: DbItemType, DbStatus, Chapter. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.domain.Chapter
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class ExternalBackupDecodersTest {
    /** Minimal protobuf writer for building fixtures. */
    private class ProtoWriter {
        private val bytes = mutableListOf<Byte>()

        fun varint(field: Int, value: Long) {
            tag(field, 0)
            writeVarint(value)
        }

        fun string(field: Int, value: String) = bytes(field, value.encodeToByteArray())

        fun bytes(field: Int, value: ByteArray) {
            tag(field, 2)
            writeVarint(value.size.toLong())
            value.forEach(bytes::add)
        }

        fun message(field: Int, block: ProtoWriter.() -> Unit) {
            bytes(field, ProtoWriter().apply(block).toByteArray())
        }

        private fun tag(field: Int, wire: Int) = writeVarint(((field shl 3) or wire).toLong())

        private fun writeVarint(value: Long) {
            var v = value
            while (true) {
                if (v and 0x7F.toLong().inv() == 0L) {
                    bytes.add(v.toByte())
                    return
                }
                bytes.add(((v and 0x7F) or 0x80).toByte())
                v = v ushr 7
            }
        }

        fun toByteArray(): ByteArray = bytes.toByteArray()
    }

    private fun mihonFixture(): ByteArray = ProtoWriter().apply {
        message(1) { // backupManga
            varint(1, 2499283573021220255L) // source id
            string(2, "/manga/solo")
            string(3, "Solo Leveling")
            string(5, "Chugong")
            string(6, "Hunters and gates.")
            string(7, "Action")
            string(7, "Fantasy")
            varint(8, 2) // completed
            string(9, "https://img/solo.jpg")
            varint(13, 1_700_000_000L)
            message(16) { // chapter
                string(1, "/manga/solo/1")
                string(2, "Chapter 1")
                varint(4, 1) // read
                varint(6, 17) // lastPageRead
                varint(8, 1_600_000_000L)
                varint(11, 1_650_000_000L)
            }
            varint(17, 3) // category order (unpacked)
            varint(106, 1_710_000_000L)
        }
        message(2) { // category
            string(1, "Favourites")
            varint(2, 3)
        }
        message(101) { // source
            string(1, "MangaDex")
            varint(2, 2499283573021220255L)
        }
    }.toByteArray()

    @Test
    fun decodesMihonBackup() {
        val fixture = mihonFixture()
        assertTrue(looksLikeTachiyomiBackup(fixture))

        val snapshot = decodeTachiyomiBackup(fixture)

        val manga = snapshot.mangas.single()
        assertEquals("Solo Leveling", manga.name)
        assertEquals("MangaDex", manga.source)
        assertEquals(DbStatus.Completed, manga.status)
        assertEquals(listOf("Action", "Fantasy"), manga.genre)
        assertEquals(DbItemType.Manga, manga.itemType)
        assertTrue(manga.favorite)

        val category = snapshot.categories.single()
        assertEquals("Favourites", category.name)
        assertEquals(listOf(category.id), manga.categories)

        val chapter = snapshot.chapters.single()
        assertEquals("Chapter 1", chapter.name)
        assertTrue(chapter.isRead)
        assertEquals("18", chapter.lastPageRead) // Mihon's 0-based page 17 is Yokan's page 18.
        assertEquals("1600000000", chapter.dateUpload) // Mihon dateUpload is already epoch millis.

        val history = snapshot.histories.single()
        assertEquals(chapter.id, history.chapterId)
        assertEquals((1_650_000_000L * 1000).toString(), history.date)
    }

    @Test
    fun licensedAndUpcomingStatusesRespectMangaAndAnimeSourceConstants() {
        val fixture = ProtoWriter().apply {
            message(1) { string(3, "Licensed manga"); varint(8, 3) }
            message(1) { string(3, "Unknown manga status"); varint(8, 7) }
            message(501) { string(3, "Licensed anime"); varint(8, 3) }
            message(501) { string(3, "Upcoming anime"); varint(8, 7) }
        }.toByteArray()
        val entries = decodeTachiyomiBackup(fixture).mangas.associate { it.name to it.status }
        assertEquals(DbStatus.Licensed, entries["Licensed manga"])
        assertEquals(DbStatus.Unknown, entries["Unknown manga status"])
        assertEquals(DbStatus.Licensed, entries["Licensed anime"])
        assertEquals(DbStatus.Upcoming, entries["Upcoming anime"])
    }

    @Test
    fun aniyomiAnimeFieldsMapToAnimeEntries() {
        val fixture = ProtoWriter().apply {
            message(501) {
                string(3, "Frieren")
                varint(8, 1)
                message(16) {
                    string(2, "Episode 1")
                    varint(4, 1) // seen
                }
            }
            message(503) {
                string(1, "AniSource")
                varint(2, 0)
            }
        }.toByteArray()

        val snapshot = decodeTachiyomiBackup(fixture)

        val anime = snapshot.mangas.single()
        assertEquals(DbItemType.Anime, anime.itemType)
        assertEquals("Frieren", anime.name)
        assertEquals("AniSource", anime.source)
        assertEquals(DbStatus.Ongoing, anime.status)
        assertTrue(snapshot.chapters.single().isRead)
    }

    @Test
    fun randomJsonIsNotMistakenForTachiyomi() {
        assertFalse(looksLikeTachiyomiBackup("""{"schemaVersion":1}""".encodeToByteArray()))
    }

    @Test
    fun decodesKotatsuFavourites() {
        val favourites = """
            [{"manga":{"title":"Kaguya-sama","public_url":"https://k/1","cover_url":"https://img/k.jpg",
              "source":"MANGADEX","tags":[{"title":"Romance"},{"title":"Comedy"}]},
              "category_id":2,"created_at":1700000000000}]
        """.trimIndent()
        val categories = """[{"category_id":2,"title":"Reading","sort_key":1}]"""

        val snapshot = decodeKotatsuBackup(
            mapOf(
                "favourites" to favourites.encodeToByteArray(),
                "categories" to categories.encodeToByteArray(),
            ),
        )

        val manga = snapshot.mangas.single()
        assertEquals("Kaguya-sama", manga.name)
        assertEquals("MANGADEX", manga.source)
        assertEquals(listOf("Romance", "Comedy"), manga.genre)
        assertEquals(listOf(2L), manga.categories)
        assertEquals("Reading", snapshot.categories.single().name)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/PasswordBackupEnvelopeTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines PasswordBackupEnvelopeTest, nonAsciiPasswordRoundTripsAndWritesV1Header, nodeGoldenVectorMatchesFullEnvelopeAndDecodes, wrongPasswordAndAuthenticationFailuresAreNeutral, malformedAndTruncatedInputsAreRejected, unsupportedVersionAndAlgorithmsAreRejected, iterationsOutsideAllowedRangeAreRejected, emptyAndOverlongPasswordsAreRejectedBeforeKdf, backupPasswordValidityCountsUtf8BytesUpToTheMaximum, cancellationIsNotConvertedToCryptoFailure and 7 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • nonAsciiPasswordRoundTripsAndWritesV1Header
  • nodeGoldenVectorMatchesFullEnvelopeAndDecodes
  • wrongPasswordAndAuthenticationFailuresAreNeutral
  • malformedAndTruncatedInputsAreRejected
  • unsupportedVersionAndAlgorithmsAreRejected
  • iterationsOutsideAllowedRangeAreRejected
  • emptyAndOverlongPasswordsAreRejectedBeforeKdf
  • backupPasswordValidityCountsUtf8BytesUpToTheMaximum
  • cancellationIsNotConvertedToCryptoFailure
package eu.friedcutlet.yokan.services.backup

import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.cancel
import kotlinx.coroutines.coroutineScope
import kotlin.coroutines.cancellation.CancellationException
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class PasswordBackupEnvelopeTest {
    private val password = "pässwörd🔒"
    private val payload = "{\"manga\":[]}".encodeToByteArray()
    private val salt = ByteArray(16) { it.toByte() }
    private val nonce = ByteArray(12) { (it + 16).toByte() }
    private val goldenEnvelope = """
        594f4b414e454e4301010101000927c0000102030405060708090a0b0c0d0e0f
        101112131415161718191a1b4ae72c324f4f1921be7a18c51dd77173a0fec4411
        e77dcf28b9db351
    """.filterNot(Char::isWhitespace).hexToBytes()

    @Test
    fun nonAsciiPasswordRoundTripsAndWritesV1Header() = runTest {
        val envelope = encoded(5)

        assertContentEquals("YOKANENC".encodeToByteArray(), envelope.copyOfRange(0, 8))
        assertEquals(1, envelope[8].toInt())
        assertEquals(1, envelope[9].toInt())
        assertEquals(1, envelope[10].toInt())
        assertEquals(1, envelope[11].toInt())
        assertEquals(600_000, readInt(envelope, 12))
        assertContentEquals(saltFor(5), envelope.copyOfRange(16, 32))
        assertContentEquals(nonceFor(5), envelope.copyOfRange(32, 44))
        assertContentEquals(payload, decoded(envelope, password))
    }

    @Test
    fun nodeGoldenVectorMatchesFullEnvelopeAndDecodes() = runTest {
        val encoded = PasswordBackupEnvelope.encodeForTesting(payload, password, salt, nonce)

        assertContentEquals(goldenEnvelope, (encoded as PasswordBackupEnvelopeResult.Success).bytes)
        assertContentEquals(payload, decoded(goldenEnvelope, password))
    }

    @Test
    fun wrongPasswordAndAuthenticationFailuresAreNeutral() = runTest {
        val envelope = encoded(1)
        val changedHeader = envelope.copyOf().also { it[16] = (it[16].toInt() xor 1).toByte() }
        val changedCiphertext = envelope.copyOf().also { it[44] = (it[44].toInt() xor 1).toByte() }
        val changedTag = envelope.copyOf().also { it[it.lastIndex] = (it.last().toInt() xor 1).toByte() }

        listOf(
            PasswordBackupEnvelope.decode(envelope, "wrong password"),
            PasswordBackupEnvelope.decode(changedHeader, password),
            PasswordBackupEnvelope.decode(changedCiphertext, password),
            PasswordBackupEnvelope.decode(changedTag, password),
        ).forEach { result ->
            assertEquals(
                PasswordBackupEnvelopeError.AuthenticationFailed,
                (result as PasswordBackupEnvelopeResult.Failure).error,
            )
        }
    }

    @Test
    fun malformedAndTruncatedInputsAreRejected() = runTest {
        val envelope = encoded(2)

        listOf(
            ByteArray(0),
            envelope.copyOf(43),
            envelope.copyOf(44),
            envelope.copyOf(44 + 15),
        ).forEach { malformed ->
            assertEquals(
                PasswordBackupEnvelopeError.Malformed,
                (PasswordBackupEnvelope.decode(malformed, password) as PasswordBackupEnvelopeResult.Failure).error,
            )
        }
        assertEquals(
            PasswordBackupEnvelopeError.InvalidInput,
            (PasswordBackupEnvelope.encodeForTesting(ByteArray(64 * 1024 * 1024 + 1), password, salt, nonce)
                as PasswordBackupEnvelopeResult.Failure).error,
        )
    }

    @Test
    fun unsupportedVersionAndAlgorithmsAreRejected() = runTest {
        val envelope = encoded(3)
        listOf(8, 9, 10, 11).forEach { offset ->
            val unsupported = envelope.copyOf().also { it[offset] = 2 }
            assertEquals(
                PasswordBackupEnvelopeError.Unsupported,
                (PasswordBackupEnvelope.decode(unsupported, password) as PasswordBackupEnvelopeResult.Failure).error,
            )
        }
    }

    @Test
    fun iterationsOutsideAllowedRangeAreRejected() = runTest {
        val envelope = encoded(4)
        val tooMany = envelope.copyOf().also { writeInt(it, 12, 2_000_001) }
        val tooFew = envelope.copyOf().also { writeInt(it, 12, 599_999) }

        listOf(tooMany, tooFew).forEach { invalid ->
            assertEquals(
                PasswordBackupEnvelopeError.Malformed,
                (PasswordBackupEnvelope.decode(invalid, password) as PasswordBackupEnvelopeResult.Failure).error,
            )
        }
    }

    @Test
    fun emptyAndOverlongPasswordsAreRejectedBeforeKdf() = runTest {
        val tooLong = "é".repeat(513)

        listOf("", tooLong).forEach { invalidPassword ->
            assertEquals(
                PasswordBackupEnvelopeError.InvalidInput,
                (
                    PasswordBackupEnvelope.encodeForTesting(
                        payload,
                        invalidPassword,
                        saltFor(6),
                        nonceFor(6),
                    ) as PasswordBackupEnvelopeResult.Failure
                ).error,
            )
        }
    }

    @Test
    fun backupPasswordValidityCountsUtf8BytesUpToTheMaximum() {
        assertFalse(isValidBackupPassword(""))
        assertTrue(isValidBackupPassword("a"))
        assertTrue(isValidBackupPassword("a".repeat(MAX_BACKUP_PASSWORD_BYTES)))
        assertFalse(isValidBackupPassword("a".repeat(MAX_BACKUP_PASSWORD_BYTES + 1)))
        // Two-byte "é": 512 characters fill the limit, 513 exceed it despite being far fewer characters.
        assertTrue(isValidBackupPassword("é".repeat(MAX_BACKUP_PASSWORD_BYTES / 2)))
        assertFalse(isValidBackupPassword("é".repeat(MAX_BACKUP_PASSWORD_BYTES / 2 + 1)))
        // Four-byte emoji: 256 fit, 257 do not.
        assertTrue(isValidBackupPassword("🔒".repeat(MAX_BACKUP_PASSWORD_BYTES / 4)))
        assertFalse(isValidBackupPassword("🔒".repeat(MAX_BACKUP_PASSWORD_BYTES / 4 + 1)))
    }

    @Test
    fun cancellationIsNotConvertedToCryptoFailure() = runTest {
        assertFailsWith<CancellationException> {
            coroutineScope {
                cancel()
                PasswordBackupEnvelope.encodeForTesting(payload, password, saltFor(7), nonceFor(7))
            }
        }
    }

    private suspend fun encoded(testCase: Int): ByteArray =
        (PasswordBackupEnvelope.encodeForTesting(
            payload,
            password,
            saltFor(testCase),
            nonceFor(testCase),
        ) as PasswordBackupEnvelopeResult.Success)
            .bytes

    private suspend fun decoded(envelope: ByteArray, password: String): ByteArray =
        (PasswordBackupEnvelope.decode(envelope, password) as PasswordBackupEnvelopeResult.Success).bytes

    private fun readInt(bytes: ByteArray, offset: Int): Int =
        ((bytes[offset].toInt() and 0xff) shl 24) or
            ((bytes[offset + 1].toInt() and 0xff) shl 16) or
            ((bytes[offset + 2].toInt() and 0xff) shl 8) or
            (bytes[offset + 3].toInt() and 0xff)

    private fun writeInt(bytes: ByteArray, offset: Int, value: Int) {
        bytes[offset] = (value ushr 24).toByte()
        bytes[offset + 1] = (value ushr 16).toByte()
        bytes[offset + 2] = (value ushr 8).toByte()
        bytes[offset + 3] = value.toByte()
    }

    private fun saltFor(testCase: Int): ByteArray = salt.copyOf().also { it[0] = testCase.toByte() }

    private fun nonceFor(testCase: Int): ByteArray = nonce.copyOf().also { it[0] = (16 + testCase).toByte() }

    private fun String.hexToBytes(): ByteArray = ByteArray(length / 2) { index ->
        substring(index * 2, index * 2 + 2).toInt(16).toByte()
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/ProfileRestorePlanTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines ProfileRestorePlanTest.

Read the setup, action and assertions in these cases before implementing their production paths:

  • destinationKeepsDeviceFieldsAndCredentialsWhileProfileDataMoves

Cross-chapter imports used by this file: DbChapter, DbCookie, DbManga, DbSettings, DbTrackPreference, profileRestorePlan. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbCookie
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbTrackPreference
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import eu.friedcutlet.yokan.app.profiles.profileRestorePlan

class ProfileRestorePlanTest {
    @Test fun destinationKeepsDeviceFieldsAndCredentialsWhileProfileDataMoves() {
        val incoming = DbSettings(
            cookiesList = listOf(DbCookie("source.example", "session=backup")),
            downloadLocation = "/backup/device/downloads",
            backupEncryptionPassword = "backup-secret",
            metadataServerToken = "backup-token",
            readerHoldToScroll = true,
        )
        val destination = DbSettings(
            cookiesList = listOf(DbCookie("source.example", "session=target")),
            downloadLocation = "/target/downloads",
            backupEncryptionPassword = null,
            metadataServerToken = "",
        )
        val plan = BackupPlan(
            preview = RestorePreview(itemCount = 2, warnings = emptyList()),
            snapshot = BackupSnapshot(
                createdAtMillis = 1,
                settings = incoming,
                mangas = listOf(DbManga(id = 1, link = "/backup/device/book.cbz", isLocalArchive = true), DbManga(id = 2, link = "https://source.example/2")),
                chapters = listOf(DbChapter(id = 3, mangaId = 1, archivePath = "/backup/device/ch.cbz", downloadSize = "10")),
                trackPreferences = listOf(DbTrackPreference(syncId = 1, username = "user", oauth = "SECRET")),
            ),
            includedSections = BackupSection.all,
            resolvedPassword = "file-password",
        )

        val restored = profileRestorePlan(plan, destination)

        val settings = restored.snapshot.settings!!
        assertEquals(destination.cookiesList, settings.cookiesList)
        assertEquals("/target/downloads", settings.downloadLocation)
        assertNull(settings.backupEncryptionPassword)
        assertEquals("", settings.metadataServerToken)
        assertEquals(true, settings.readerHoldToScroll)
        assertFalse(BackupSection.TrackPreferences in restored.includedSections)
        assertEquals(emptyList(), restored.snapshot.trackPreferences)
        assertNull(restored.snapshot.mangas[0].link)
        assertEquals("https://source.example/2", restored.snapshot.mangas[1].link)
        assertEquals("", restored.snapshot.chapters.single().archivePath)
        assertNull(restored.snapshot.chapters.single().downloadSize)
        assertNull(restored.resolvedPassword)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/TachiyomiBackupEncoderTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines TachiyomiBackupEncoderTest, FakeGzip, compress, decompress, library, gzippedExportRoundTripsThroughTheDecoder, compressionLevelZeroWritesRawProtobufThatStillDecodes, fieldNumbersFollowAnimetailBackupModels, emptyAndNovelOnlyBackupsEncodeOnlyTheLegacyFlag, Field and 2 further declarations.

The source describes its contract as:

Marks "gzip" with the magic bytes so the decoder's sniffing path is exercised on every target.

Read the setup, action and assertions in these cases before implementing their production paths:

  • gzippedExportRoundTripsThroughTheDecoder
  • compressionLevelZeroWritesRawProtobufThatStillDecodes
  • fieldNumbersFollowAnimetailBackupModels
  • emptyAndNovelOnlyBackupsEncodeOnlyTheLegacyFlag

Cross-chapter imports used by this file: DbCategory, DbChapter, DbHistory, DbItemType, DbManga, DbSource. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.backup

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class TachiyomiBackupEncoderTest {
    /** Marks "gzip" with the magic bytes so the decoder's sniffing path is exercised on every target. */
    private object FakeGzip : BackupCompression {
        override fun compress(data: ByteArray, level: Int): ByteArray = byteArrayOf(0x1F, 0x8B.toByte()) + data
        override fun decompress(data: ByteArray): ByteArray = data.copyOfRange(2, data.size)
    }

    private val mangaDexId = 2499283573021220255L

    private fun library(): YokanDatabaseSnapshot = seedDatabaseSnapshot().copy(
        sources = listOf(
            DbSource(id = mangaDexId, name = "MangaDex", itemType = DbItemType.Manga),
            DbSource(id = 77, name = "AniSrc", itemType = DbItemType.Anime),
        ),
        categories = listOf(
            DbCategory(id = 10, name = "Reading", forItemType = DbItemType.Manga, position = 0),
            DbCategory(id = 11, name = "Later", forItemType = DbItemType.Manga, position = 1),
            DbCategory(id = 20, name = "Watching", forItemType = DbItemType.Anime, position = 0),
        ),
        mangas = listOf(
            DbManga(
                id = 1, name = "Solo Leveling", link = "/manga/solo", imageUrl = "https://img/solo.jpg",
                description = "Hunters.", author = "Chugong", artist = "Dubu", status = DbStatus.Completed,
                itemType = DbItemType.Manga, genre = listOf("Action", "Fantasy"), favorite = true,
                source = "MangaDex", sourceId = mangaDexId, dateAdded = 1_700_000_000_000,
                lastUpdate = 1_710_000_000_000, categories = listOf(11L),
            ),
            DbManga(id = 4, name = "History only", link = "/manga/h", favorite = false, source = "MangaDex", sourceId = mangaDexId),
            DbManga(
                id = 2, name = "Frieren", link = "/anime/frieren", status = DbStatus.Ongoing, itemType = DbItemType.Anime,
                favorite = true, source = "AniSrc", sourceId = 77, categories = listOf(20L),
            ),
            DbManga(id = 3, name = "Novel X", itemType = DbItemType.Novel, favorite = true, source = "NovSrc"),
        ),
        chapters = listOf(
            DbChapter(
                id = 100, mangaId = 1, name = "Chapter 1", url = "/c1", dateUpload = "1600000000000",
                isRead = true, lastPageRead = "1", number = 1.0, updatedAt = 1_650_000_000_000,
            ),
            DbChapter(id = 101, mangaId = 1, name = "Chapter 2", url = "/c2", isBookmarked = true, lastPageRead = "18", number = 2.5),
            DbChapter(
                id = 200, mangaId = 2, name = "Episode 1", url = "/e1", isRead = true, lastPageRead = "1440000",
                fillerOverride = true, description = "Intro",
            ),
            DbChapter(id = 300, mangaId = 3, name = "Novel chapter", url = "/n1"),
        ),
        histories = listOf(
            DbHistory(id = 1, mangaId = 1, chapterId = 101, itemType = DbItemType.Manga, date = "1700000123000", readingTimeSeconds = 90),
            DbHistory(id = 2, mangaId = 2, chapterId = 200, itemType = DbItemType.Anime, date = "1700000456000"),
        ),
        tracks = listOf(
            DbTrack(
                id = 1, mediaId = 151807, mangaId = 1, syncId = 2, title = "Solo", lastChapterRead = 2,
                totalChapter = 200, score = 85, status = DbTrackStatus.ReReading, trackingUrl = "https://anilist.co/manga/151807",
            ),
            DbTrack(id = 2, mediaId = 52991, mangaId = 2, syncId = 1, lastChapterRead = 1, status = DbTrackStatus.Watching, itemType = DbItemType.Anime),
            DbTrack(id = 3, mangaId = 1, syncId = 6, status = DbTrackStatus.Reading), // metadata pseudo-tracker: no upstream id
        ),
    )

    @Test
    fun gzippedExportRoundTripsThroughTheDecoder() = runTest {
        val export = BackupExporter(FakeGzip).export(library(), BackupOptions(format = BackupFormat.Tachiyomi))
        assertTrue(export.fileName.endsWith(".tachibk"), export.fileName)
        assertTrue(export.compressed)
        assertEquals("application/octet-stream", export.contentType)

        val snapshot = BackupDecoder(FakeGzip).decode(export.bytes).snapshot
        assertEquals(listOf("Solo Leveling", "History only", "Frieren"), snapshot.mangas.map { it.name })

        val solo = snapshot.mangas.first { it.name == "Solo Leveling" }
        assertEquals("MangaDex", solo.source)
        assertEquals("/manga/solo", solo.link)
        assertEquals(DbStatus.Completed, solo.status)
        assertEquals(listOf("Action", "Fantasy"), solo.genre)
        assertEquals("Chugong", solo.author)
        assertEquals("Dubu", solo.artist)
        assertEquals(1_700_000_000_000, solo.dateAdded)
        assertEquals(1_710_000_000_000, solo.lastUpdate)
        assertTrue(solo.favorite)
        assertFalse(snapshot.mangas.first { it.name == "History only" }.favorite)
        val frieren = snapshot.mangas.first { it.name == "Frieren" }
        assertEquals(DbItemType.Anime, frieren.itemType)
        assertEquals("AniSrc", frieren.source)

        val categoryById = snapshot.categories.associateBy { it.id }
        assertEquals(listOf("Reading", "Later"), snapshot.categories.filter { it.forItemType == DbItemType.Manga }.map { it.name })
        assertEquals(listOf("Later"), solo.categories.orEmpty().map { categoryById.getValue(it).name })
        assertEquals(listOf("Watching"), frieren.categories.orEmpty().map { categoryById.getValue(it).name })
        assertEquals(DbItemType.Anime, categoryById.getValue(frieren.categories!!.single()).forItemType)

        val chapters = snapshot.chapters.associateBy { it.url }
        assertEquals(setOf("/c1", "/c2", "/e1"), chapters.keys)
        chapters.getValue("/c1").let {
            assertTrue(it.isRead)
            assertEquals("1", it.lastPageRead)
            assertEquals("1600000000000", it.dateUpload)
            assertEquals(1.0, it.number)
        }
        chapters.getValue("/c2").let {
            assertTrue(it.isBookmarked)
            assertFalse(it.isRead)
            assertEquals("18", it.lastPageRead)
            assertEquals(2.5, it.number)
        }
        chapters.getValue("/e1").let {
            assertTrue(it.isRead)
            assertEquals("1440000", it.lastPageRead)
            assertTrue(it.isFiller)
            assertEquals("Intro", it.description)
            assertEquals(frieren.id, it.mangaId)
        }

        val histories = snapshot.histories.associateBy { it.mangaId }
        histories.getValue(solo.id).let {
            assertEquals(chapters.getValue("/c2").id, it.chapterId)
            assertEquals("1700000123000", it.date)
            assertEquals(90, it.readingTimeSeconds)
        }
        histories.getValue(frieren.id).let {
            assertEquals(chapters.getValue("/e1").id, it.chapterId)
            assertEquals("1700000456000", it.date)
            assertEquals(DbItemType.Anime, it.itemType)
        }

        assertEquals(2, snapshot.tracks.size)
        snapshot.tracks.single { it.mangaId == solo.id }.let {
            assertEquals(2, it.syncId)
            assertEquals(151807L, it.mediaId)
            assertEquals(DbTrackStatus.ReReading, it.status)
            assertEquals(85, it.score)
            assertEquals(2, it.lastChapterRead)
            assertEquals(200, it.totalChapter)
            assertEquals("https://anilist.co/manga/151807", it.trackingUrl)
            assertNull(it.libraryId)
        }
        snapshot.tracks.single { it.mangaId == frieren.id }.let {
            assertEquals(1, it.syncId)
            assertEquals(52991L, it.mediaId)
            assertEquals(DbTrackStatus.Watching, it.status)
            assertEquals(DbItemType.Anime, it.itemType)
        }
    }

    @Test
    fun compressionLevelZeroWritesRawProtobufThatStillDecodes() = runTest {
        val export = BackupExporter(FakeGzip).export(library(), BackupOptions(format = BackupFormat.Tachiyomi, compressionLevel = 0))
        assertTrue(export.fileName.endsWith(".proto"), export.fileName)
        assertFalse(export.compressed)
        assertFalse(FakeGzip.looksGzipped(export.bytes))

        val snapshot = BackupDecoder(FakeGzip).decode(export.bytes).snapshot
        assertEquals(listOf("Solo Leveling", "History only", "Frieren"), snapshot.mangas.map { it.name })
        assertEquals(3, snapshot.chapters.size)
    }

    @Test
    fun fieldNumbersFollowAnimetailBackupModels() {
        val raw = BackupExporter(FakeGzip).export(library(), BackupOptions(format = BackupFormat.Tachiyomi, compressionLevel = 0)).bytes
        val top = fields(raw)

        // Backup: 1 manga, 2 categories, 101 sources, 500 isLegacy=false, 501-503 anime; never the legacy 3/4/103.
        assertEquals(2, top.all(1).size)
        assertTrue(top.all(1).all { it.wire == 2 })
        assertEquals(2, top.all(2).size)
        assertEquals(1, top.all(101).size)
        top.one(500).let { assertEquals(0, it.wire); assertEquals(0L, it.varint) }
        assertEquals(1, top.all(501).size)
        assertEquals(1, top.all(502).size)
        assertEquals(1, top.all(503).size)
        assertTrue(top.all(3).isEmpty() && top.all(4).isEmpty() && top.all(103).isEmpty())
        assertFalse(raw.decodeToString().contains("Novel"), "novels have no Tachiyomi model")

        // BackupManga
        val solo = fields(top.all(1)[0].bytes)
        assertEquals(mangaDexId, solo.one(1).varint)
        assertEquals("/manga/solo", solo.one(2).text)
        assertEquals("Solo Leveling", solo.one(3).text)
        assertEquals("Dubu", solo.one(4).text)
        assertEquals("Chugong", solo.one(5).text)
        assertEquals("Hunters.", solo.one(6).text)
        assertEquals(listOf("Action", "Fantasy"), solo.all(7).map { it.text })
        assertEquals(2L, solo.one(8).varint) // SManga.COMPLETED
        assertEquals("https://img/solo.jpg", solo.one(9).text)
        assertEquals(1_700_000_000_000, solo.one(13).varint) // millis
        assertEquals(2, solo.all(16).size)
        solo.all(17).let { orders -> assertEquals(listOf(1L), orders.map { it.varint }); assertTrue(orders.all { it.wire == 0 }) }
        assertEquals(1, solo.all(18).size) // metadata pseudo-tracker skipped
        assertTrue(solo.all(100).isEmpty(), "favorite=true is the upstream default")
        assertEquals(1_710_000_000L, solo.one(106).varint) // seconds
        fields(top.all(1)[1].bytes).one(100).let { assertEquals(0, it.wire); assertEquals(0L, it.varint) }

        // BackupChapter
        val chapter1 = fields(solo.all(16)[0].bytes)
        assertEquals("/c1", chapter1.one(1).text)
        assertEquals("Chapter 1", chapter1.one(2).text)
        assertEquals(1L, chapter1.one(4).varint)
        assertTrue(chapter1.all(6).isEmpty(), "Yokan page 1 is Mihon index 0 (default)")
        assertEquals(1_600_000_000_000, chapter1.one(8).varint)
        chapter1.one(9).let { assertEquals(5, it.wire); assertEquals(1f, Float.fromBits(it.fixed32)) }
        assertTrue(chapter1.all(10).isEmpty())
        assertEquals(1_650_000_000L, chapter1.one(11).varint)
        val chapter2 = fields(solo.all(16)[1].bytes)
        assertEquals(1L, chapter2.one(5).varint)
        assertEquals(17L, chapter2.one(6).varint)
        assertEquals(2.5f, Float.fromBits(chapter2.one(9).fixed32))
        assertEquals(1L, chapter2.one(10).varint)

        // BackupTracking
        val track = fields(solo.one(18).bytes)
        assertEquals(2L, track.one(1).varint) // TrackerManager.ANILIST
        assertEquals(0L, track.one(2).varint) // required libraryId
        assertEquals("https://anilist.co/manga/151807", track.one(4).text)
        assertEquals("Solo", track.one(5).text)
        assertEquals(2f, Float.fromBits(track.one(6).fixed32))
        assertEquals(200L, track.one(7).varint)
        assertEquals(85f, Float.fromBits(track.one(8).fixed32))
        assertEquals(6L, track.one(9).varint) // Anilist.REREADING
        assertEquals(151807L, track.one(100).varint)

        // BackupHistory
        val history = fields(solo.one(104).bytes)
        assertEquals("/c2", history.one(1).text)
        assertEquals(1_700_000_123_000, history.one(2).varint)
        assertEquals(90_000L, history.one(3).varint)

        // BackupCategory / BackupSource
        fields(top.all(2)[0].bytes).let { assertEquals("Reading", it.one(1).text); assertTrue(it.all(2).isEmpty()) }
        fields(top.all(2)[1].bytes).let { assertEquals("Later", it.one(1).text); assertEquals(1L, it.one(2).varint) }
        fields(top.one(101).bytes).let { assertEquals("MangaDex", it.one(1).text); assertEquals(mangaDexId, it.one(2).varint) }

        // BackupAnime / BackupEpisode / BackupAnimeTracking / BackupAnimeHistory
        val anime = fields(top.one(501).bytes)
        assertEquals(77L, anime.one(1).varint)
        assertEquals("Frieren", anime.one(3).text)
        assertEquals(1L, anime.one(8).varint)
        assertEquals(listOf(0L), anime.all(17).map { it.varint })
        val episode = fields(anime.one(16).bytes)
        assertEquals(1L, episode.one(4).varint) // seen
        assertEquals(1_440_000L, episode.one(6).varint) // lastSecondSeen, millis
        assertEquals(1L, episode.one(501).varint) // fillermark
        assertEquals("Intro", episode.one(502).text) // summary
        fields(anime.one(18).bytes).let { assertEquals(1L, it.one(1).varint); assertEquals(11L, it.one(9).varint) } // MAL WATCHING
        fields(anime.one(104).bytes).let { assertEquals("/e1", it.one(1).text); assertEquals(1_700_000_456_000, it.one(2).varint) }
        fields(top.one(502).bytes).let { assertEquals("Watching", it.one(1).text) }
        fields(top.one(503).bytes).let { assertEquals("AniSrc", it.one(1).text); assertEquals(77L, it.one(2).varint) }
    }

    @Test
    fun emptyAndNovelOnlyBackupsEncodeOnlyTheLegacyFlag() = runTest {
        assertContentEquals(byteArrayOf(0xA0.toByte(), 0x1F, 0x00), encodeTachiyomiBackup(BackupSnapshot(createdAtMillis = 1)))
        // Categories are exported even when empty (as Mihon does); drop them so only novels remain.
        val novelsOnly = library().let { it.copy(mangas = it.mangas.filter { m -> m.itemType == DbItemType.Novel }, categories = emptyList()) }
        val export = BackupExporter(FakeGzip).export(novelsOnly, BackupOptions(format = BackupFormat.Tachiyomi, compressionLevel = 0))
        assertContentEquals(byteArrayOf(0xA0.toByte(), 0x1F, 0x00), export.bytes)
        // Nothing restorable: the decoder reports an invalid backup instead of an empty restore.
        assertFailsWith<InvalidBackupException> { BackupDecoder(FakeGzip).decode(export.bytes) }
    }

    private class Field(val number: Int, val wire: Int, val varint: Long = 0, val bytes: ByteArray = ByteArray(0), val fixed32: Int = 0) {
        val text: String get() = bytes.decodeToString()
    }

    private fun fields(bytes: ByteArray): List<Field> {
        val reader = ProtoReader(bytes)
        return buildList {
            while (reader.hasMore()) {
                val (number, wire) = reader.readTag()
                add(
                    when (wire) {
                        0 -> Field(number, wire, varint = reader.readVarint())
                        2 -> Field(number, wire, bytes = reader.readBytes())
                        5 -> Field(number, wire, fixed32 = reader.readFixed32())
                        else -> error("Unexpected wire type $wire for field $number")
                    },
                )
            }
        }
    }

    private fun List<Field>.all(number: Int): List<Field> = filter { it.number == number }
    private fun List<Field>.one(number: Int): Field = single { it.number == number }
}

Write composeApp/src/iosTest/kotlin/eu/friedcutlet/yokan/services/backup/IosBackupCompressionTest.kt

Create this path in your reconstruction project. Source set: iosTest. Exact file download.

The implementation below defines IosBackupCompressionTest, unzipsMangayomiFlutterBackup, gzipRoundTrips, gzipTreatsTheTrailerSizeAsAHintOnly, zipSingleEntryRoundTrips.

The source describes its contract as:

A real Mangayomi .backup: ZIP with one deflated *.backup.db JSON entry, generated by the Flutter app's exact code path (dart archive 4.0.9 ZipFileEncoder.create + addFile).

Read the setup, action and assertions in these cases before implementing their production paths:

  • unzipsMangayomiFlutterBackup
  • gzipRoundTrips
  • gzipTreatsTheTrailerSizeAsAHintOnly
  • zipSingleEntryRoundTrips
package eu.friedcutlet.yokan.services.backup

import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue

@OptIn(ExperimentalEncodingApi::class)
class IosBackupCompressionTest {
    private val gzip = createPlatformBackupCompression()

    /**
     * A real Mangayomi `.backup`: ZIP with one deflated `*.backup.db` JSON
     * entry, generated by the Flutter app's exact code path
     * (dart `archive` 4.0.9 `ZipFileEncoder.create` + `addFile`).
     */
    private val mangayomiBackup = Base64.decode(
        "UEsDBBQAAAgIAByl/1yyOASaVwAAAH0AAAAuAAAAbWFuZ2F5b21pXzIwMjYtMDctMzFfMTJfMDBf" +
            "MDAuMDAwMDAwLmJhY2t1cC5kYjXNuw6AIAyF4XfpzOTIqxiHBhogKiWl3mJ8d6Pidr7l/CesJDVx" +
            "BgsdGJgxBwTbDwYcKgWWRLU5YlGSJs9bnhh9owq6se2YqrIcH5biUf8L2pXyU3t93VBLAQIUABQA" +
            "AAgIAByl/1yyOASaVwAAAH0AAAAuAAAAAAAAAAAAAACkgQAAAABtYW5nYXlvbWlfMjAyNi0wNy0z" +
            "MV8xMl8wMF8wMC4wMDAwMDAuYmFja3VwLmRiUEsFBgAAAAABAAEAXAAAAKMAAAAAAA==",
    )

    @Test
    fun unzipsMangayomiFlutterBackup() {
        assertTrue(gzip.looksZipped(mangayomiBackup))
        val entries = assertNotNull(gzip.unzipEntries(mangayomiBackup))
        assertEquals(listOf("mangayomi_2026-07-31_12_00_00.000000.backup.db"), entries.keys.toList())
        val json = assertNotNull(gzip.unzipFirstEntry(mangayomiBackup)).decodeToString()
        assertTrue(json.startsWith("""{"version":"2""""), json)
    }

    @Test
    fun gzipRoundTrips() {
        val payload = """{"schemaVersion":1,"mangas":[]}""".repeat(50).encodeToByteArray()
        val compressed = gzip.compress(payload, level = 6)
        assertTrue(gzip.looksGzipped(compressed))
        assertTrue(compressed.size < payload.size)
        assertContentEquals(payload, gzip.decompress(compressed))
    }

    @Test
    fun gzipTreatsTheTrailerSizeAsAHintOnly() {
        val payload = """{"schemaVersion":1,"mangas":[]}""".repeat(50).encodeToByteArray()
        val compressed = gzip.compress(payload, level = 6)
        // Trailing bytes after the member (padding, a truncated second member) replace the size read from
        // the end: one claims 1 byte, the other ~2 GiB. Inflate must neither fail nor trust them.
        assertContentEquals(payload, gzip.decompress(compressed + byteArrayOf(1, 0, 0, 0)))
        assertContentEquals(payload, gzip.decompress(compressed + byteArrayOf(-1, -1, -1, 0x7F)))
    }

    @Test
    fun zipSingleEntryRoundTrips() {
        val payload = """{"version":"2"}""".encodeToByteArray()
        val zipped = assertNotNull(gzip.zipSingleEntry("yokan.backup.db", payload, level = 6))
        assertTrue(gzip.looksZipped(zipped))
        assertContentEquals(payload, gzip.unzipFirstEntry(zipped))
    }
}

Write composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/backup/WasmBackupCompressionTest.kt

Create this path in your reconstruction project. Source set: wasmJsTest. Exact file download.

The implementation below defines WasmBackupCompressionTest, decodesMangayomiRawDeflateEntry, decodesStoredEntry, rejectsCorruptPayloadCrc, rejectsMalformedEocdCommentLength, rejectsEntryOverOutputLimitBeforeReadingIt, storedDataOffset, centralDirectoryOffset, readLe16, readLe32 and 1 further declarations.

The source describes its contract as:

Mangayomi-shaped ZIP: one raw-deflate *.backup.db entry, no data descriptor.

Read the setup, action and assertions in these cases before implementing their production paths:

  • decodesMangayomiRawDeflateEntry
  • decodesStoredEntry
  • rejectsCorruptPayloadCrc
  • rejectsMalformedEocdCommentLength
  • rejectsEntryOverOutputLimitBeforeReadingIt
package eu.friedcutlet.yokan.services.backup

import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

@OptIn(ExperimentalEncodingApi::class)
class WasmBackupCompressionTest {
    /** Mangayomi-shaped ZIP: one raw-deflate *.backup.db entry, no data descriptor. */
    private val deflatedBackup = Base64.decode(
        "UEsDBBQAAAgIAByl/1yyOASaVwAAAH0AAAAuAAAAbWFuZ2F5b21pXzIwMjYtMDctMzFfMTJfMDBf" +
            "MDAuMDAwMDAwLmJhY2t1cC5kYjXNuw6AIAyF4XfpzOTIqxiHBhogKiWl3mJ8d6Pidr7l/CesJDVx" +
            "BgsdGJgxBwTbDwYcKgWWRLU5YlGSJs9bnhh9owq6se2YqrIcH5biUf8L2pXyU3t93VBLAQIUABQA" +
            "AAgIAByl/1yyOASaVwAAAH0AAAAuAAAAAAAAAAAAAACkgQAAAABtYW5nYXlvbWlfMjAyNi0wNy0z" +
            "MV8xMl8wMF8wMC4wMDAwMDAuYmFja3VwLmRiUEsFBgAAAAABAAEAXAAAAKMAAAAAAA==",
    )

    private val storedBackup = Base64.decode(
        "UEsDBBQAAAAAAAFhH10WbRMSGgAAABoAAAAYAAAAbWFuZ2F5b21pX3Rlc3QuYmFja3VwLmRieyJ2ZXJzaW9uIjoiMiIsIm1hbmdhIjpbXX1QSwECFAMUAAAAAAABYR9dFm0TEhoAAAAaAAAAGAAAAAAAAAAAAAAAgAEAAAAAbWFuZ2F5b21pX3Rlc3QuYmFja3VwLmRiUEsFBgAAAAABAAEARgAAAFAAAAAAAA==",
    )

    @Test
    fun decodesMangayomiRawDeflateEntry() = runTest {
        val entries = assertNotNull(createPlatformBackupCompression().unzipEntriesAsync(deflatedBackup))
        assertTrue(entries.keys.single().endsWith(".backup.db"))
        assertTrue(entries.values.single().decodeToString().contains("\"version\":\"2\""))
    }

    @Test
    fun decodesStoredEntry() = runTest {
        val entry = assertNotNull(createPlatformBackupCompression().unzipFirstEntryAsync(storedBackup))
        assertContentEquals("{\"version\":\"2\",\"manga\":[]}".encodeToByteArray(), entry)
    }

    @Test
    fun rejectsCorruptPayloadCrc() = runTest {
        val corrupted = storedBackup.copyOf().also { it[storedDataOffset(it)] = (it[storedDataOffset(it)].toInt() xor 1).toByte() }
        val error = assertFailsWith<IllegalStateException> {
            createPlatformBackupCompression().unzipFirstEntryAsync(corrupted)
        }
        assertTrue(error.message.orEmpty().contains("CRC-32 mismatch"))
    }

    @Test
    fun rejectsMalformedEocdCommentLength() = runTest {
        val corrupted = storedBackup.copyOf().also { it[it.size - 2] = 1 }
        val error = assertFailsWith<IllegalStateException> {
            createPlatformBackupCompression().unzipEntriesAsync(corrupted)
        }
        assertTrue(error.message.orEmpty().contains("end-of-central-directory"))
    }

    @Test
    fun rejectsEntryOverOutputLimitBeforeReadingIt() = runTest {
        val oversized = storedBackup.copyOf()
        val central = centralDirectoryOffset(oversized)
        writeLe32(oversized, central + 24, 64L * 1024L * 1024L + 1L)
        val error = assertFailsWith<IllegalStateException> {
            createPlatformBackupCompression().unzipFirstEntryAsync(oversized)
        }
        assertTrue(error.message.orEmpty().contains("64 MiB"))
    }

    private fun storedDataOffset(zip: ByteArray): Int =
        30 + readLe16(zip, 26) + readLe16(zip, 28)

    private fun centralDirectoryOffset(zip: ByteArray): Int = readLe32(zip, zip.size - 22 + 16).toInt()

    private fun readLe16(data: ByteArray, offset: Int): Int =
        (data[offset].toInt() and 0xFF) or ((data[offset + 1].toInt() and 0xFF) shl 8)

    private fun readLe32(data: ByteArray, offset: Int): Long =
        (data[offset].toLong() and 0xFFL) or
            ((data[offset + 1].toLong() and 0xFFL) shl 8) or
            ((data[offset + 2].toLong() and 0xFFL) shl 16) or
            ((data[offset + 3].toLong() and 0xFFL) shl 24)

    private fun writeLe32(data: ByteArray, offset: Int, value: Long) {
        repeat(4) { index -> data[offset + index] = (value ushr (index * 8)).toByte() }
    }
}

Completion record

  • [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
  • [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
  • [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
  • [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry. [chapter-content-end]: #

Gate: round-trip each format, verify known lossy fields, decrypt fixtures, reject wrong password/truncation/tampering, restore selected sections, remap colliding IDs, simulate concurrent writes and recover from failed persistence. Run backup format/encryption/sensitive-settings/notes/selection/safety/profile-restore tests on all relevant compression/crypto platforms.

Ready to move on?

Check the chapter’s verification gate before marking it complete.

Search chapters, reference and source filenames.