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 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 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 = 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 { 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, current: YokanDatabaseSnapshot? = null, ): RestorePreview { val warnings = mutableListOf() 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() val unmatchedSourceNames = mutableListOf() if (current != null) { val includedTypes = includedSections.titleTypes() val existingMangaKeys = current.mangas.map { BackupMerge.mangaKey(it.itemType, it.link, it.name) }.toSet() val existingChaptersByMangaKey = mutableMapOf>() 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, ) } }