BackupService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupService.kt
1package eu.friedcutlet.yokan.services.backup23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.YokanDatabase5import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot6import eu.friedcutlet.yokan.database.sync.SyncPaths7import eu.friedcutlet.yokan.services.blockingDispatcher8import eu.friedcutlet.yokan.services.catchingNonCancellation9import eu.friedcutlet.yokan.services.files.LocalFileService10import eu.friedcutlet.yokan.services.logging.AppLogger11import eu.friedcutlet.yokan.services.notifications.NotificationChannel12import eu.friedcutlet.yokan.services.notifications.NotificationPayload13import eu.friedcutlet.yokan.services.notifications.NotificationService14import eu.friedcutlet.yokan.util.nowMillis15import kotlinx.coroutines.CoroutineDispatcher16import kotlinx.coroutines.currentCoroutineContext17import kotlinx.coroutines.ensureActive18import kotlinx.coroutines.withContext1920/** A guarded restore's predicate rejected the current library; nothing was written. */21class BackupRestoreTargetChangedException : IllegalStateException("Backup restore target changed.")2223interface BackupService {24 suspend fun exportBackup(options: BackupOptions): BackupExport25 suspend fun exportEncryptedBackup(options: BackupOptions, password: String): BackupExport26 suspend fun createBackup(options: BackupOptions = BackupOptions()): BackupResult27 suspend fun openBackup(bytes: ByteArray, password: String? = null): BackupOpenResult28 suspend fun previewBackup(plan: BackupPlan): RestorePreview29 suspend fun applyBackup(plan: BackupPlan): RestorePreview30 suspend fun applyBackup(plan: BackupPlan, mode: RestoreMode): RestorePreview31 suspend fun listSafetySnapshots(): List<SafetySnapshot>32 suspend fun createSafetySnapshot(description: String): SafetySnapshot33 suspend fun rollbackSafetySnapshot(snapshot: SafetySnapshot): RestorePreview34 suspend fun clearSafetySnapshots()35 /** Compatibility wrapper for legacy, unencrypted restore callers. */36 suspend fun restore(bytes: ByteArray): RestorePreview37 /** Predicate is evaluated against the snapshot required by the atomic restore commit. */38 suspend fun restoreIf(bytes: ByteArray, accepts: (YokanDatabaseSnapshot) -> Boolean): RestorePreview {39 error("GUARDED_BACKUP_RESTORE_UNAVAILABLE")40 }41 /**42 * Guarded like [restoreIf], but applies an already opened [plan] in [mode] and records no safety snapshot:43 * state sync merges on every scheduled run and would otherwise evict the user's restore points.44 */45 suspend fun applyBackupIf(plan: BackupPlan, mode: RestoreMode, accepts: (YokanDatabaseSnapshot) -> Boolean): RestorePreview {46 error("GUARDED_BACKUP_RESTORE_UNAVAILABLE")47 }48 suspend fun listAvailableBackups(): List<BackupFileEntry>49 suspend fun readBackupFile(path: String): ByteArray50}5152class DefaultBackupService(53 private val database: YokanDatabase,54 private val files: LocalFileService,55 gzip: BackupCompression,56 private val notifications: NotificationService,57 /** Blocking work: backup file and safety-snapshot I/O, encoding, encryption and restore. */58 private val workDispatcher: CoroutineDispatcher = blockingDispatcher,59) : BackupService {60 private val exporter = BackupExporter(gzip)61 private val decoder = BackupDecoder(gzip)62 private val safetySnapshots = SafetySnapshotStore(files)6364 override suspend fun exportBackup(options: BackupOptions): BackupExport =65 withContext(workDispatcher) { exportPlain(options) }6667 override suspend fun exportEncryptedBackup(options: BackupOptions, password: String): BackupExport =68 withContext(workDispatcher) { exportEncrypted(options, password) }6970 private fun exportPlain(options: BackupOptions): BackupExport =71 exporter.export(database.snapshot(), options)72 .also { AppLogger.info("[backup] export ${options.format}: ${it.itemCount} items, ${it.bytes.size} bytes") }7374 private suspend fun exportEncrypted(options: BackupOptions, password: String): BackupExport {75 // Deliberately use the uncompressed native JSON producer. Encrypted76 // backups are Yokan-only and must not inherit scheduled/cloud formats.77 val plain = exportPlain(78 options.copy(79 format = BackupFormat.Yokan,80 compressionLevel = null,81 encrypt = true,82 password = password,83 ),84 )85 val encrypted = when (val result = PasswordBackupEnvelope.encode(plain.bytes, password)) {86 is PasswordBackupEnvelopeResult.Success -> result.bytes87 is PasswordBackupEnvelopeResult.Failure -> error("Invalid backup password.")88 }89 return plain.copy(90 fileName = plain.fileName.substringBeforeLast('.') + ".yokanbak",91 bytes = encrypted,92 compressed = false,93 contentType = "application/octet-stream",94 )95 }9697 override suspend fun createBackup(options: BackupOptions): BackupResult = withContext(workDispatcher) {98 val currentSettings = database.settings()99 val shouldEncrypt = options.encrypt || (options.password != null) || currentSettings.backupEncryptionEnabled100 val export = if (shouldEncrypt) {101 val password = options.password ?: currentSettings.backupEncryptionPassword102 ?: error("Backup encryption is enabled but no password is set. Re-enter it in Data and Storage settings.")103 exportEncrypted(options, password)104 } else {105 exportPlain(options)106 }107 val baseDir = currentSettings.autoBackupLocation?.takeIf { it.isNotBlank() } ?: files.backupRoot108 val path = "$baseDir/${export.fileName}"109 files.writeBytes(path, export.bytes)110 val result = BackupResult(111 fileName = export.fileName,112 bytesWritten = export.bytes.size.toLong(),113 itemCount = export.itemCount,114 path = path,115 )116 AppLogger.info("[backup] created ${result.fileName}: ${result.itemCount} items, ${result.bytesWritten} bytes")117 // A missing notification permission must not fail a backup that is already written.118 runCatching {119 notifications.notify(120 NotificationPayload(121 channel = NotificationChannel.Backup,122 title = "Backup created",123 message = "${result.itemCount} items • ${result.bytesWritten / 1024} KB",124 tag = "backup-${nowMillis()}",125 ),126 )127 }128 result129 }130131 override suspend fun openBackup(bytes: ByteArray, password: String?): BackupOpenResult =132 withContext(workDispatcher) { open(bytes, password) }133134 private suspend fun open(bytes: ByteArray, password: String?): BackupOpenResult {135 if (bytes.startsWithEncryptedMagic()) {136 val passwordToTry = password ?: database.settings().backupEncryptionPassword137 if (passwordToTry == null) return BackupOpenResult.Failure(BackupOpenError.PasswordRequired)138 val decrypted = when (val result = PasswordBackupEnvelope.decode(bytes, passwordToTry)) {139 is PasswordBackupEnvelopeResult.Success -> result.bytes140 is PasswordBackupEnvelopeResult.Failure -> {141 AppLogger.warn("[backup] decrypting backup failed: ${result.error}")142 return BackupOpenResult.Failure(143 when (result.error) {144 PasswordBackupEnvelopeError.AuthenticationFailed -> BackupOpenError.AuthenticationFailed145 PasswordBackupEnvelopeError.Unsupported -> BackupOpenError.Unsupported146 PasswordBackupEnvelopeError.InvalidInput,147 PasswordBackupEnvelopeError.Malformed,148 PasswordBackupEnvelopeError.CryptoFailure,149 -> BackupOpenError.Invalid150 },151 )152 }153 }154 return openDecoded(decrypted, resolvedPassword = passwordToTry)155 }156 return openDecoded(bytes, resolvedPassword = null)157 }158159 private suspend fun openDecoded(bytes: ByteArray, resolvedPassword: String?): BackupOpenResult =160 catchingNonCancellation {161 val decoded = decoder.decode(bytes)162 val currentSnapshot = runCatching { database.snapshot() }.getOrNull()163 BackupOpenResult.Ready(164 BackupPlan(165 preview = previewOf(decoded.snapshot, decoded.includedSections, currentSnapshot),166 snapshot = decoded.snapshot,167 includedSections = decoded.includedSections,168 resolvedPassword = resolvedPassword,169 ),170 )171 }.getOrElse { error ->172 AppLogger.warn("[backup] opening backup failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")173 BackupOpenResult.Failure(174 if (error is UnsupportedBackupException) BackupOpenError.Unsupported else BackupOpenError.Invalid,175 )176 }177178 override suspend fun previewBackup(plan: BackupPlan): RestorePreview = plan.preview179180 override suspend fun applyBackup(plan: BackupPlan): RestorePreview =181 applyBackup(plan, plan.mode)182183 override suspend fun applyBackup(plan: BackupPlan, mode: RestoreMode): RestorePreview = withContext(workDispatcher) {184 applyBackupInternal(plan, mode, createSafetySnapshot = true)185 }186187 private suspend fun applyBackupInternal(188 plan: BackupPlan,189 mode: RestoreMode,190 createSafetySnapshot: Boolean,191 accepts: (YokanDatabaseSnapshot) -> Boolean = { true },192 ): RestorePreview {193 currentCoroutineContext().ensureActive()194 val currentSnapshot = database.snapshot()195 if (!accepts(currentSnapshot)) throw BackupRestoreTargetChangedException()196 if (createSafetySnapshot) {197 val desc = when (mode) {198 RestoreMode.Merge -> {199 val p = plan.preview200 "Merge: +${p.newSeriesCount} series, ~${p.updatedSeriesCount} series, +${p.newChapterCount} ch"201 }202 RestoreMode.Replace -> "Replace: ${plan.preview.itemCount} items"203 }204 safetySnapshots.record(currentSnapshot, desc)205 }206 val merged = if (mode == RestoreMode.Merge) {207 BackupMerge.merge(currentSnapshot, plan.snapshot, plan.includedSections)208 } else {209 BackupMerge.replace(currentSnapshot, plan.snapshot, plan.includedSections)210 }211 val updatedSettings = if (plan.resolvedPassword != null) {212 merged.settings.copy(213 backupEncryptionEnabled = true,214 backupEncryptionPassword = plan.resolvedPassword,215 )216 } else merged.settings217 val restored = merged.copy(218 settings = updatedSettings,219 syncPreferences = merged.syncPreferences.map { it.copy(hubHead = 0) },220 // Download marks point at files on the device that downloaded them; drop the ones missing here.221 chapters = merged.chapters.map { chapter ->222 val missing = chapter.downloadSize != null &&223 (chapter.archivePath.isBlank() || !runCatching { files.exists(chapter.archivePath) }.getOrDefault(false))224 if (missing) chapter.copy(archivePath = "", downloadSize = null) else chapter225 },226 )227 // Restored values go out like ordinary edits, so the next hub pull can't undo them.228 currentCoroutineContext().ensureActive()229 database.replaceAllAtomically(230 restored.copy(outbox = SyncPaths.outboxForReplacement(currentSnapshot, restored)),231 expectedSnapshot = currentSnapshot,232 )233 AppLogger.info("[backup] restored ($mode): ${plan.preview.itemCount} items, +${plan.preview.newSeriesCount} series, +${plan.preview.newChapterCount} chapters")234 return plan.preview235 }236237 override suspend fun listSafetySnapshots(): List<SafetySnapshot> = withContext(workDispatcher) {238 safetySnapshots.list()239 }240241 override suspend fun createSafetySnapshot(description: String): SafetySnapshot = withContext(workDispatcher) {242 safetySnapshots.record(database.snapshot(), description)243 }244245 override suspend fun rollbackSafetySnapshot(snapshot: SafetySnapshot): RestorePreview = withContext(workDispatcher) {246 val bytes = files.readBytes(snapshot.backupPath)247 if (bytes.isEmpty()) error("Safety snapshot file not found: ${snapshot.backupPath}")248 val plan = when (val opened = open(bytes, password = null)) {249 is BackupOpenResult.Ready -> opened.plan250 is BackupOpenResult.Failure -> error("Failed to open safety snapshot: ${opened.error}")251 }252 val preview = applyBackupInternal(plan.withMode(RestoreMode.Replace), RestoreMode.Replace, createSafetySnapshot = false)253 safetySnapshots.remove(snapshot)254 preview255 }256257 override suspend fun clearSafetySnapshots(): Unit = withContext(workDispatcher) {258 safetySnapshots.clear()259 }260261 override suspend fun restore(bytes: ByteArray): RestorePreview = restoreIf(bytes) { true }262263 override suspend fun restoreIf(bytes: ByteArray, accepts: (YokanDatabaseSnapshot) -> Boolean): RestorePreview =264 withContext(workDispatcher) {265 when (val result = open(bytes, password = null)) {266 is BackupOpenResult.Ready ->267 applyBackupInternal(result.plan, result.plan.mode, createSafetySnapshot = true, accepts = accepts)268 is BackupOpenResult.Failure -> error("Backup restore failed: ${result.error}")269 }270 }271272 override suspend fun applyBackupIf(plan: BackupPlan, mode: RestoreMode, accepts: (YokanDatabaseSnapshot) -> Boolean): RestorePreview =273 withContext(workDispatcher) { applyBackupInternal(plan, mode, createSafetySnapshot = false, accepts = accepts) }274275 override suspend fun listAvailableBackups(): List<BackupFileEntry> {276 val root = database.settings().autoBackupLocation?.takeIf { it.isNotBlank() } ?: files.backupRoot277 return files.listFiles(root)278 .filter { it.name.endsWith(".json") || it.name.endsWith(".json.gz") || it.name.endsWith(".backup") }279 .map { entry ->280 BackupFileEntry(281 path = entry.path,282 fileName = entry.name,283 sizeBytes = entry.sizeBytes,284 lastModified = entry.lastModified,285 compressed = entry.name.endsWith(".gz") || entry.name.endsWith(".backup"),286 )287 }288 }289290 override suspend fun readBackupFile(path: String): ByteArray = withContext(workDispatcher) { files.readBytes(path) }291292 private fun previewOf(293 payload: BackupSnapshot,294 includedSections: Set<String>,295 current: YokanDatabaseSnapshot? = null,296 ): RestorePreview {297 val warnings = mutableListOf<String>()298 if (BackupSection.Settings !in includedSections) warnings += "Backup does not contain app settings."299 if (includedSections.none { it == BackupSection.Manga || it == BackupSection.Anime || it == BackupSection.Novel }) {300 warnings += "Backup does not contain library titles."301 }302 val mangaCount = payload.mangas.count { it.itemType == DbItemType.Manga && BackupSection.Manga in includedSections }303 val animeCount = payload.mangas.count { it.itemType == DbItemType.Anime && BackupSection.Anime in includedSections }304 val novelCount = payload.mangas.count { it.itemType == DbItemType.Novel && BackupSection.Novel in includedSections }305 val itemCount = listOf(306 mangaCount + animeCount + novelCount,307 payload.chapters.size.takeIf { BackupSection.Chapters in includedSections } ?: 0,308 payload.categories.size.takeIf { BackupSection.Categories in includedSections } ?: 0,309 payload.sources.size.takeIf { BackupSection.Sources in includedSections } ?: 0,310 payload.histories.size.takeIf { BackupSection.History in includedSections } ?: 0,311 payload.updates.size.takeIf { BackupSection.Updates in includedSections } ?: 0,312 payload.tracks.size.takeIf { BackupSection.Tracks in includedSections } ?: 0,313 ).sum()314315 var newSeriesCount = 0316 var updatedSeriesCount = 0317 var newChapterCount = 0318 val conflictingCategories = mutableListOf<String>()319 val unmatchedSourceNames = mutableListOf<String>()320321 if (current != null) {322 val includedTypes = includedSections.titleTypes()323 val existingMangaKeys = current.mangas.map { BackupMerge.mangaKey(it.itemType, it.link, it.name) }.toSet()324 val existingChaptersByMangaKey = mutableMapOf<String, MutableSet<String>>()325 val existingMangaById = current.mangas.associateBy { it.id }326 for (ch in current.chapters) {327 val m = ch.mangaId?.let { existingMangaById[it] } ?: continue328 val set = existingChaptersByMangaKey.getOrPut(BackupMerge.mangaKey(m.itemType, m.link, m.name)) { mutableSetOf() }329 set.add(if (ch.url.isNotBlank()) ch.url else ch.name.orEmpty())330 }331332 val payloadMangaById = payload.mangas.associateBy { it.id }333 for (m in payload.mangas.filter { it.itemType in includedTypes }) {334 if (BackupMerge.mangaKey(m.itemType, m.link, m.name) in existingMangaKeys) {335 updatedSeriesCount++336 } else {337 newSeriesCount++338 }339 }340341 if (BackupSection.Chapters in includedSections) {342 for (ch in payload.chapters) {343 val m = ch.mangaId?.let { payloadMangaById[it] } ?: continue344 if (m.itemType !in includedTypes) continue345 val existingChapterUrls = existingChaptersByMangaKey[BackupMerge.mangaKey(m.itemType, m.link, m.name)]346 val chKey = if (ch.url.isNotBlank()) ch.url else ch.name.orEmpty()347 if (existingChapterUrls == null || chKey !in existingChapterUrls) newChapterCount++348 }349 }350351 if (BackupSection.Categories in includedSections) {352 val existingCatNames = current.categories.map { it.name.trim().lowercase() }.toSet()353 for (cat in payload.categories) {354 if (cat.name.trim().lowercase() in existingCatNames && cat.name !in conflictingCategories) {355 conflictingCategories.add(cat.name)356 }357 }358 }359360 val installedSourceNames = current.sources.map { it.name.trim().lowercase() }.toSet()361 for (src in payload.sources) {362 if (src.name.trim().lowercase() !in installedSourceNames && src.name !in unmatchedSourceNames) {363 unmatchedSourceNames.add(src.name)364 }365 }366 } else {367 newSeriesCount = mangaCount + animeCount + novelCount368 newChapterCount = payload.chapters.size.takeIf { BackupSection.Chapters in includedSections } ?: 0369 }370371 return RestorePreview(372 itemCount = itemCount,373 warnings = warnings,374 mangaCount = mangaCount,375 animeCount = animeCount,376 novelCount = novelCount,377 categoryCount = payload.categories.size.takeIf { BackupSection.Categories in includedSections } ?: 0,378 chapterCount = payload.chapters.size.takeIf { BackupSection.Chapters in includedSections } ?: 0,379 historyCount = payload.histories.size.takeIf { BackupSection.History in includedSections } ?: 0,380 updateCount = payload.updates.size.takeIf { BackupSection.Updates in includedSections } ?: 0,381 sourceCount = payload.sources.size.takeIf { BackupSection.Sources in includedSections } ?: 0,382 trackCount = payload.tracks.size.takeIf { BackupSection.Tracks in includedSections } ?: 0,383 newSeriesCount = newSeriesCount,384 updatedSeriesCount = updatedSeriesCount,385 newChapterCount = newChapterCount,386 conflictingCategories = conflictingCategories,387 unmatchedSourceNames = unmatchedSourceNames,388 )389 }390}391