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 = 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() }