BackupExporter.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupExporter.kt
1package eu.friedcutlet.yokan.services.backup23import eu.friedcutlet.yokan.database.DbCategory4import eu.friedcutlet.yokan.database.DbChapter5import eu.friedcutlet.yokan.database.DbItemType6import eu.friedcutlet.yokan.database.DbManga7import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot8import eu.friedcutlet.yokan.services.logging.AppLogger9import eu.friedcutlet.yokan.util.nowMillis1011/** Builds the unencrypted backup payload for [BackupOptions] and wraps it in the requested container. */12internal class BackupExporter(private val gzip: BackupCompression) {13 private val json = BackupJson1415 fun export(snapshot: YokanDatabaseSnapshot, options: BackupOptions): BackupExport {16 val payload = payloadOf(snapshot, options)17 val itemCount = listOf(18 payload.mangas.size,19 payload.chapters.size,20 payload.categories.size,21 payload.sources.size,22 payload.histories.size,23 payload.updates.size,24 payload.tracks.size,25 payload.trackPreferences.size,26 payload.customButtons.size,27 ).sum()28 return when (options.format) {29 BackupFormat.Mangayomi -> {30 // Old Flutter app container: a `.backup` ZIP holding one31 // `*.backup.db` plain-JSON entry (version "2", singular keys).32 val base = "mangayomi_${formatTimestamp(payload.createdAtMillis)}"33 val dbJson = MangayomiBackupCodec.encode(payload).encodeToByteArray()34 val level = (options.compressionLevel ?: 6).coerceIn(0, 9)35 val zipped = gzip.zipSingleEntry("$base.backup.db", dbJson, level)36 ?: error("ZIP backups are not supported on this platform.")37 BackupExport(38 fileName = "$base.backup",39 bytes = zipped,40 itemCount = itemCount,41 format = options.format,42 compressed = true,43 contentType = "application/zip",44 )45 }46 BackupFormat.Yokan -> {47 val bodyBytes = json.encodeToString(BackupSnapshot.serializer(), payload).encodeToByteArray()48 val compress = (options.compressionLevel ?: 0) > 049 val bytes = if (compress) gzip.compress(bodyBytes, options.compressionLevel ?: 6) else bodyBytes50 val baseName = "yokan-backup-${formatTimestamp(payload.createdAtMillis)}"51 BackupExport(52 fileName = if (compress) "$baseName.json.gz" else "$baseName.json",53 bytes = bytes,54 itemCount = itemCount,55 format = options.format,56 compressed = compress,57 contentType = if (compress) "application/gzip" else "application/json",58 )59 }60 BackupFormat.Tachiyomi -> {61 val novels = payload.mangas.count { it.itemType == DbItemType.Novel }62 if (novels > 0) AppLogger.info("[backup] Tachiyomi export omits $novels novel titles (no Mihon/Aniyomi model)")63 val proto = encodeTachiyomiBackup(payload)64 val level = (options.compressionLevel ?: 6).coerceIn(0, 9)65 // Level 0 is the raw SyncYomi wire form; the web's gzip is a passthrough, which Mihon also reads.66 val bytes = if (level > 0) gzip.compress(proto, level) else proto67 val base = "yokan_${formatTimestamp(payload.createdAtMillis)}"68 BackupExport(69 fileName = if (level > 0) "$base.tachibk" else "$base.proto",70 bytes = bytes,71 itemCount = itemCount,72 format = options.format,73 compressed = gzip.looksGzipped(bytes),74 contentType = "application/octet-stream",75 )76 }77 }78 }7980 private fun payloadOf(snapshot: YokanDatabaseSnapshot, options: BackupOptions): BackupSnapshot {81 val exportedTitleTypes = options.exportedTitleTypes()82 val exportedMangas = snapshot.mangas.filter { it.itemType in exportedTitleTypes }83 val exportedCategories = if (options.includeCategories) {84 snapshot.categories.filter { it.forItemType in exportedTitleTypes }85 } else {86 emptyList()87 }88 val exportedCategoryIds = exportedCategories.mapTo(hashSetOf(), DbCategory::id)89 val exportedSources = if (options.includeSources) {90 snapshot.sources.filter { it.itemType in exportedTitleTypes }91 } else {92 emptyList()93 }94 val exportedSourceTypes = exportedSources.associate { it.id to it.itemType }95 val mangas = exportedMangas.map { manga ->96 manga.copy(97 privateNote = manga.privateNote.takeIf { options.includePrivateNotes && options.format == BackupFormat.Yokan }.orEmpty(),98 categories = manga.categories?.filter(exportedCategoryIds::contains),99 sourceId = manga.sourceId?.takeIf { exportedSourceTypes[it] == manga.itemType },100 )101 }102 val exportedTitleIds = mangas.mapTo(hashSetOf(), DbManga::id)103 val chapters = if (options.includeChapters) {104 snapshot.chapters.filter { it.mangaId == null || it.mangaId in exportedTitleIds }105 } else {106 emptyList()107 }108 val exportedChapterIds = chapters.mapTo(hashSetOf(), DbChapter::id)109 val includedSections = buildList {110 if (options.includeSettings) add(BackupSection.Settings)111 if (options.includeManga) add(BackupSection.Manga)112 if (options.includeAnime) add(BackupSection.Anime)113 if (options.includeNovel) add(BackupSection.Novel)114 if (options.includeChapters) add(BackupSection.Chapters)115 if (options.includeCategories) add(BackupSection.Categories)116 if (options.includeSources) add(BackupSection.Sources)117 if (options.includeHistory) add(BackupSection.History)118 if (options.includeUpdates) add(BackupSection.Updates)119 if (options.includeTracks) add(BackupSection.Tracks)120 if (options.includeSensitiveSettings) add(BackupSection.TrackPreferences)121 if (options.includeCustomButtons) add(BackupSection.CustomButtons)122 add(BackupSection.ChangedParts)123 }124 return BackupSnapshot(125 createdAtMillis = nowMillis(),126 privateNotesIncluded = options.includePrivateNotes && options.format == BackupFormat.Yokan,127 settings = snapshot.settings.takeIf { options.includeSettings }?.let { s ->128 val preservePassword = options.includeSensitiveSettings || options.encrypt || options.password != null129 s.copy(130 backupEncryptionPassword = s.backupEncryptionPassword.takeIf { preservePassword },131 // Home's API token is installation-local, including cloud and portable exports.132 features = s.features.copy(133 home = s.home.copy(tmdbReadAccessToken = "", sourceFeeds = emptyList()),134 downloads = s.features.downloads.copy(pendingNewChapterIds = emptySet(), consumedChapterIds = emptySet(), manuallyMarkedChapterIds = emptySet()),135 externalDownloads = eu.friedcutlet.yokan.database.DbExternalDownloads(),136 discord = s.features.discord.forExport(),137 torrent = s.features.torrent.forExport(),138 ),139 )140 },141 includedSections = includedSections,142 mangas = mangas,143 chapters = chapters,144 categories = exportedCategories,145 sources = exportedSources,146 histories = if (options.includeHistory) snapshot.histories.filter {147 it.mangaId == null || it.mangaId in exportedTitleIds148 }.filter {149 it.chapterId == null || it.chapterId in exportedChapterIds150 } else emptyList(),151 updates = if (options.includeUpdates) snapshot.updates.filter {152 it.mangaId == null || it.mangaId in exportedTitleIds153 }.filter {154 it.chapterId == null || it.chapterId in exportedChapterIds155 } else emptyList(),156 tracks = if (options.includeTracks) snapshot.tracks.filter {157 it.mangaId == null || it.mangaId in exportedTitleIds158 } else emptyList(),159 // Tracker preferences carry OAuth tokens — only exported when the160 // user opts into "Sensitive settings" (Mangayomi option 8).161 trackPreferences = if (options.includeSensitiveSettings) snapshot.trackPreferences else emptyList(),162 customButtons = if (options.includeCustomButtons) snapshot.customButtons else emptyList(),163 changedParts = snapshot.changedParts,164 )165 }166167 private fun BackupOptions.exportedTitleTypes(): Set<DbItemType> = buildSet {168 if (includeManga) add(DbItemType.Manga)169 if (includeAnime) add(DbItemType.Anime)170 if (includeNovel) add(DbItemType.Novel)171 }172173 /** Compact timestamp suitable for filenames (seconds, no separators). */174 private fun formatTimestamp(millis: Long): String = (millis / 1000).toString()175}176