BackupMerge.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupMerge.kt
1package eu.friedcutlet.yokan.services.backup23import eu.friedcutlet.yokan.database.DbCategory4import eu.friedcutlet.yokan.database.DbChangedPart5import eu.friedcutlet.yokan.database.DbChapter6import eu.friedcutlet.yokan.database.DbCustomButton7import eu.friedcutlet.yokan.database.DbFetchType8import eu.friedcutlet.yokan.database.DbHistory9import eu.friedcutlet.yokan.database.DbItemType10import eu.friedcutlet.yokan.database.DbManga11import eu.friedcutlet.yokan.database.DbSettings12import eu.friedcutlet.yokan.database.DbSource13import eu.friedcutlet.yokan.database.DbTrack14import eu.friedcutlet.yokan.database.DbTrackPreference15import eu.friedcutlet.yokan.database.DbUpdate16import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot17import eu.friedcutlet.yokan.database.sync.preserveDeviceLocalSettings18import eu.friedcutlet.yokan.database.DbSavedSearch19import eu.friedcutlet.yokan.database.DbChapterReleasePreference20import eu.friedcutlet.yokan.database.mergeProgress21import eu.friedcutlet.yokan.database.presetIdentity22import eu.friedcutlet.yokan.domain.mergePrivateNotes2324private class BackupIdentityCollisionException(message: String) : IllegalStateException(message)2526/**27 * Combines the current database with a decoded backup. [replace] swaps every28 * included section wholesale; [merge] adds what is missing and folds progress29 * into matching titles. Both reject identity collisions and drop dangling references.30 */31internal object BackupMerge {32 /** Identity used to match titles across devices: link when known, else lowercase name. */33 fun mangaKey(itemType: DbItemType, link: String?, name: String?): String =34 if (!link.isNullOrBlank()) "${itemType.name}:link:${link.trim()}"35 else "${itemType.name}:name:${name?.trim()?.lowercase().orEmpty()}"3637 fun replace(38 current: YokanDatabaseSnapshot,39 payload: BackupSnapshot,40 includedSections: Set<String>,41 ): YokanDatabaseSnapshot {42 val includedTypes = includedSections.titleTypes()43 val replacements = if (payload.privateNotesIncluded) payload.mangas else {44 val localNotes = current.mangas.associate { mangaKey(it.itemType, it.link, it.name) to it.privateNote }45 payload.mangas.map { it.copy(privateNote = localNotes[mangaKey(it.itemType, it.link, it.name)].orEmpty()) }46 }47 val mangas = applyMangaSections(current.mangas, replacements, includedTypes)48 checkIdentityCollisions(49 "mangas",50 current.mangas.filter { it.itemType !in includedTypes },51 payload.mangas.filter { it.itemType in includedTypes },52 DbManga::id,53 )54 val categories = mergeTypedCollection(55 current.categories,56 payload.categories,57 includedSections,58 BackupSection.Categories,59 DbCategory::forItemType,60 includedTypes,61 DbCategory::id,62 )63 val sources = mergeTypedCollection(64 current.sources,65 payload.sources,66 includedSections,67 BackupSection.Sources,68 DbSource::itemType,69 includedTypes,70 DbSource::id,71 )72 val chapters = mergeTitleDependent(73 current.chapters,74 payload.chapters,75 includedSections,76 BackupSection.Chapters,77 mangas,78 { it.mangaId },79 null,80 DbChapter::id,81 includedTypes,82 )83 val chaptersById = chapters.associateBy(DbChapter::id)84 val histories = mergeTitleDependent(85 current.histories,86 payload.histories,87 includedSections,88 BackupSection.History,89 mangas,90 { it.mangaId },91 { it.chapterId },92 DbHistory::id,93 includedTypes,94 chaptersById,95 )96 val updates = mergeTitleDependent(97 current.updates,98 payload.updates,99 includedSections,100 BackupSection.Updates,101 mangas,102 { it.mangaId },103 { it.chapterId },104 DbUpdate::id,105 includedTypes,106 chaptersById,107 )108 val tracks = mergeTitleDependent(109 current.tracks,110 payload.tracks,111 includedSections,112 BackupSection.Tracks,113 mangas,114 { it.mangaId },115 null,116 DbTrack::id,117 includedTypes,118 )119 val settings = if (payload.sourceApp == "mangayomi") {120 if (payload.settings?.backupEncryptionPassword != null) {121 current.settings.copy(122 backupEncryptionEnabled = true,123 backupEncryptionPassword = payload.settings.backupEncryptionPassword,124 )125 } else current.settings126 } else if (BackupSection.Settings in includedSections) {127 payload.settings128 ?.let { incoming ->129 preserveDeviceLocalSettings(current.settings, incoming).copy(130 savedSearches = incoming.savedSearches?.let { restorePresets(it, payload.sources, sources) },131 chapterReleasePreferences = restoreReleasePreferences(incoming.chapterReleasePreferences, payload.mangas, mangas),132 automaticReaderLayout = incoming.automaticReaderLayout,133 readerHoldToScroll = incoming.readerHoldToScroll,134 automaticReaderLayouts = restoreAutomaticLayouts(incoming.automaticReaderLayouts, payload.mangas, mangas),135 )136 }137 ?: current.settings138 } else current.settings139 val changedParts = mergeChangedParts(current.changedParts, payload.changedParts, includedSections)140 if (BackupSection.TrackPreferences in includedSections) {141 checkIdentityCollisions("trackPreferences", emptyList(), payload.trackPreferences, DbTrackPreference::syncId)142 }143 if (BackupSection.CustomButtons in includedSections) {144 checkIdentityCollisions("customButtons", emptyList(), payload.customButtons, DbCustomButton::id)145 }146 return sanitizeRestoreSnapshot(147 current.copy(148 settings = settings,149 mangas = mangas,150 chapters = chapters,151 categories = categories,152 sources = sources,153 histories = histories,154 updates = updates,155 tracks = tracks,156 trackPreferences = if (BackupSection.TrackPreferences in includedSections) {157 payload.trackPreferences158 } else {159 current.trackPreferences160 },161 customButtons = if (BackupSection.CustomButtons in includedSections) {162 payload.customButtons163 } else {164 current.customButtons165 },166 changedParts = changedParts,167 ),168 )169 }170171 fun merge(172 current: YokanDatabaseSnapshot,173 payload: BackupSnapshot,174 includedSections: Set<String>,175 ): YokanDatabaseSnapshot {176 val categories = mergeCategories(current.categories, payload.categories, BackupSection.Categories in includedSections)177 val sources = mergeSources(current.sources, payload.sources, BackupSection.Sources in includedSections)178 val mangas = mergeMangas(current.mangas, payload, includedSections.titleTypes(), categories.ids, sources.ids)179 val chapters = mergeChapters(current.chapters, payload.chapters, BackupSection.Chapters in includedSections, mangas)180 return sanitizeRestoreSnapshot(181 current.copy(182 settings = mergeSettings(current.settings, payload, includedSections, sources.rows, mangas.rows),183 mangas = mangas.rows,184 chapters = chapters.rows,185 categories = categories.rows,186 sources = sources.rows,187 histories = mergeHistories(current.histories, payload.histories, BackupSection.History in includedSections, mangas.ids, chapters.ids),188 updates = mergeUpdates(current.updates, payload.updates, BackupSection.Updates in includedSections, mangas.ids, chapters.ids),189 tracks = mergeTracks(current.tracks, payload.tracks, BackupSection.Tracks in includedSections, mangas.ids),190 customButtons = mergeButtons(current.customButtons, payload.customButtons, BackupSection.CustomButtons in includedSections),191 ),192 )193 }194195 /** Merged rows, the backup→merged id of every accepted backup row, and the ids of rows the merge added. */196 private class Merged<T>(197 val rows: List<T>,198 val ids: Map<Long, Long> = emptyMap(),199 val added: Set<Long> = emptySet(),200 )201202 private fun <T> nextId(a: List<T>, b: List<T>, id: (T) -> Long): Long =203 maxOf(a.maxOfOrNull(id) ?: 0L, b.maxOfOrNull(id) ?: 0L) + 1L204205 private fun mergeCategories(current: List<DbCategory>, incoming: List<DbCategory>, included: Boolean): Merged<DbCategory> {206 if (!included) return Merged(current)207 var nextId = nextId(current, incoming, DbCategory::id)208 val ids = mutableMapOf<Long, Long>()209 val rows = current.toMutableList()210 for (incomingCat in incoming) {211 val existing = current.firstOrNull {212 it.name.trim().equals(incomingCat.name.trim(), ignoreCase = true) &&213 it.forItemType == incomingCat.forItemType214 }215 if (existing != null) {216 ids[incomingCat.id] = existing.id217 } else {218 val newId = nextId++219 ids[incomingCat.id] = newId220 rows.add(incomingCat.copy(id = newId))221 }222 }223 return Merged(rows, ids)224 }225226 private fun mergeSources(current: List<DbSource>, incoming: List<DbSource>, included: Boolean): Merged<DbSource> {227 if (!included) return Merged(current)228 var nextId = nextId(current, incoming, DbSource::id)229 val ids = mutableMapOf<Long, Long>()230 val rows = current.toMutableList()231 for (incomingSrc in incoming) {232 val existing = current.firstOrNull {233 it.itemType == incomingSrc.itemType &&234 (it.id == incomingSrc.id || it.name.trim().equals(incomingSrc.name.trim(), ignoreCase = true))235 }236 if (existing != null) {237 ids[incomingSrc.id] = existing.id238 } else {239 val newId = if (current.none { it.id == incomingSrc.id }) incomingSrc.id else nextId++240 ids[incomingSrc.id] = newId241 rows.add(incomingSrc.copy(id = newId))242 }243 }244 return Merged(rows, ids)245 }246247 private fun mergeMangas(248 current: List<DbManga>,249 payload: BackupSnapshot,250 includedTypes: Set<DbItemType>,251 categoryIds: Map<Long, Long>,252 sourceIds: Map<Long, Long>,253 ): Merged<DbManga> {254 var nextId = nextId(current, payload.mangas, DbManga::id)255 val ids = mutableMapOf<Long, Long>()256 val newIds = mutableSetOf<Long>()257 val rows = current.toMutableList()258 val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap()259 val byKey = mutableMapOf<String, DbManga>()260 for (m in current) {261 byKey[mangaKey(m.itemType, m.link, m.name)] = m262 }263264 val incomingMangas = payload.mangas.filter { it.itemType in includedTypes }265 for (incomingManga in incomingMangas) {266 val key = mangaKey(incomingManga.itemType, incomingManga.link, incomingManga.name)267 val existing = byKey[key]268 val remappedCategories = incomingManga.categories?.mapNotNull { categoryIds[it] ?: it }?.distinct()269 val remappedSourceId = incomingManga.sourceId?.let { sourceIds[it] ?: it }270271 if (existing != null) {272 ids[incomingManga.id] = existing.id273 val combinedCategories = (existing.categories.orEmpty() + remappedCategories.orEmpty()).distinct()274 val updated = existing.copy(275 // Season records stay out of the library unless they were favorites themselves.276 favorite = incomingManga.parentId == null || existing.favorite || incomingManga.favorite,277 privateNote = mergePrivateNotes(existing.privateNote, incomingManga.privateNote.takeIf { payload.privateNotesIncluded }.orEmpty()),278 categories = combinedCategories,279 sourceId = existing.sourceId ?: remappedSourceId,280 author = existing.author?.ifBlank { incomingManga.author } ?: incomingManga.author,281 artist = existing.artist?.ifBlank { incomingManga.artist } ?: incomingManga.artist,282 description = existing.description?.ifBlank { incomingManga.description } ?: incomingManga.description,283 genre = (existing.genre.orEmpty() + incomingManga.genre.orEmpty()).distinct().takeIf { it.isNotEmpty() },284 cast = existing.cast.ifEmpty { incomingManga.cast },285 fetchType = if (incomingManga.fetchType == DbFetchType.Seasons) DbFetchType.Seasons else existing.fetchType,286 seasonNumber = existing.seasonNumber ?: incomingManga.seasonNumber,287 )288 rows[indexById.getValue(existing.id)] = updated289 } else {290 val newId = nextId++291 ids[incomingManga.id] = newId292 newIds.add(newId)293 val newManga = incomingManga.copy(294 id = newId,295 privateNote = incomingManga.privateNote.takeIf { payload.privateNotesIncluded }.orEmpty(),296 favorite = incomingManga.parentId == null || incomingManga.favorite,297 parentId = null, // Remapped below once every parent has its merged id.298 categories = remappedCategories,299 sourceId = remappedSourceId,300 )301 rows.add(newManga)302 indexById[newId] = rows.lastIndex303 byKey[key] = newManga304 }305 }306 incomingMangas.forEach { incoming ->307 val parent = incoming.parentId?.let(ids::get) ?: return@forEach308 val index = indexById.getValue(ids.getValue(incoming.id))309 val merged = rows[index]310 if (merged.parentId == null && merged.id != parent) rows[index] = merged.copy(parentId = parent)311 }312 return Merged(rows, ids, newIds)313 }314315 private fun mergeChapters(316 current: List<DbChapter>,317 incoming: List<DbChapter>,318 included: Boolean,319 mangas: Merged<DbManga>,320 ): Merged<DbChapter> {321 if (!included) return Merged(current)322 var nextId = nextId(current, incoming, DbChapter::id)323 val ids = mutableMapOf<Long, Long>()324 val existingByMangaId = current.groupBy { it.mangaId }.mapValues { it.value.toMutableList() }.toMutableMap()325 val rows = current.toMutableList()326 val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap()327328 for (incomingCh in incoming) {329 val targetMangaId = incomingCh.mangaId?.let { mangas.ids[it] } ?: continue330 if (targetMangaId in mangas.added) {331 val newId = nextId++332 ids[incomingCh.id] = newId333 rows.add(incomingCh.copy(id = newId, mangaId = targetMangaId))334 indexById[newId] = rows.lastIndex335 continue336 }337 val existingList = existingByMangaId.getOrPut(targetMangaId) { mutableListOf() }338 val matchingChapter = existingList.firstOrNull {339 (!it.url.isNullOrBlank() && it.url == incomingCh.url) ||340 (it.url.isNullOrBlank() && incomingCh.url.isNullOrBlank() && it.name == incomingCh.name)341 }342 if (matchingChapter != null) {343 ids[incomingCh.id] = matchingChapter.id344 val updatedCh = matchingChapter.mergeProgress(incomingCh).copy(345 dateUpload = if (incomingCh.dateUpload.isNotBlank() && matchingChapter.dateUpload.isBlank()) {346 incomingCh.dateUpload347 } else matchingChapter.dateUpload,348 number = matchingChapter.number ?: incomingCh.number,349 season = matchingChapter.season ?: incomingCh.season,350 numberingName = matchingChapter.numberingName ?: incomingCh.numberingName,351 )352 if (updatedCh != matchingChapter) {353 rows[indexById.getValue(matchingChapter.id)] = updatedCh354 val exIdx = existingList.indexOfFirst { it.id == matchingChapter.id }355 if (exIdx >= 0) existingList[exIdx] = updatedCh356 }357 } else {358 val newId = nextId++359 ids[incomingCh.id] = newId360 val newCh = incomingCh.copy(id = newId, mangaId = targetMangaId)361 rows.add(newCh)362 indexById[newId] = rows.lastIndex363 existingList.add(newCh)364 }365 }366 return Merged(rows, ids)367 }368369 private fun mergeHistories(370 current: List<DbHistory>,371 incoming: List<DbHistory>,372 included: Boolean,373 mangaIds: Map<Long, Long>,374 chapterIds: Map<Long, Long>,375 ): List<DbHistory> {376 if (!included) return current377 var nextId = nextId(current, incoming, DbHistory::id)378 val rows = current.toMutableList()379 val byKey = current.associateBy { "${it.mangaId}:${it.chapterId}" }.toMutableMap()380 val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap()381 for (incomingH in incoming) {382 val targetMangaId = incomingH.mangaId?.let { mangaIds[it] } ?: continue383 val targetChapterId = incomingH.chapterId?.let { chapterIds[it] } ?: continue384 val key = "$targetMangaId:$targetChapterId"385 val existing = byKey[key]386 if (existing != null) {387 val mergedDate = listOfNotNull(existing.date, incomingH.date).maxOrNull() ?: existing.date388 if (mergedDate != existing.date) {389 val updated = existing.copy(date = mergedDate)390 rows[indexById.getValue(existing.id)] = updated391 byKey[key] = updated392 }393 } else {394 val newId = nextId++395 val newH = incomingH.copy(id = newId, mangaId = targetMangaId, chapterId = targetChapterId)396 rows.add(newH)397 indexById[newId] = rows.lastIndex398 byKey[key] = newH399 }400 }401 return rows402 }403404 private fun mergeUpdates(405 current: List<DbUpdate>,406 incoming: List<DbUpdate>,407 included: Boolean,408 mangaIds: Map<Long, Long>,409 chapterIds: Map<Long, Long>,410 ): List<DbUpdate> {411 if (!included) return current412 var nextId = nextId(current, incoming, DbUpdate::id)413 val rows = current.toMutableList()414 val byKey = current.associateBy { "${it.mangaId}:${it.chapterName}" }.toMutableMap()415 for (incomingU in incoming) {416 val targetMangaId = incomingU.mangaId?.let { mangaIds[it] } ?: continue417 val targetChapterId = incomingU.chapterId?.let { chapterIds[it] }418 val key = "$targetMangaId:${incomingU.chapterName}"419 if (key !in byKey) {420 val newU = incomingU.copy(id = nextId++, mangaId = targetMangaId, chapterId = targetChapterId)421 rows.add(newU)422 byKey[key] = newU423 }424 }425 return rows426 }427428 private fun mergeTracks(429 current: List<DbTrack>,430 incoming: List<DbTrack>,431 included: Boolean,432 mangaIds: Map<Long, Long>,433 ): List<DbTrack> {434 if (!included) return current435 var nextId = nextId(current, incoming, DbTrack::id)436 val rows = current.toMutableList()437 val byKey = current.associateBy { "${it.mangaId}:${it.syncId}" }.toMutableMap()438 val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap()439 for (incomingT in incoming) {440 val targetMangaId = incomingT.mangaId?.let { mangaIds[it] } ?: continue441 val key = "$targetMangaId:${incomingT.syncId}"442 val existing = byKey[key]443 if (existing != null) {444 // This device's status and score win; the backup only fills progress and a missing score.445 val updated = existing.copy(446 lastChapterRead = maxOf(existing.lastChapterRead ?: 0, incomingT.lastChapterRead ?: 0).takeIf { it > 0 },447 score = if ((existing.score ?: 0) > 0) existing.score else incomingT.score,448 )449 rows[indexById.getValue(existing.id)] = updated450 byKey[key] = updated451 } else {452 val newId = nextId++453 val newT = incomingT.copy(id = newId, mangaId = targetMangaId)454 rows.add(newT)455 indexById[newId] = rows.lastIndex456 byKey[key] = newT457 }458 }459 return rows460 }461462 private fun mergeButtons(current: List<DbCustomButton>, incoming: List<DbCustomButton>, included: Boolean): List<DbCustomButton> {463 if (!included) return current464 var nextId = nextId(current, incoming, DbCustomButton::id)465 val existingNames = current.map { it.title?.trim()?.lowercase().orEmpty() }.toSet()466 return current + incoming467 .filter { it.title?.trim()?.lowercase().orEmpty() !in existingNames }468 .map { it.copy(id = nextId++) }469 }470471 private fun mergeSettings(472 current: DbSettings,473 payload: BackupSnapshot,474 includedSections: Set<String>,475 mergedSources: List<DbSource>,476 mergedMangas: List<DbManga>,477 ): DbSettings {478 val settings = if (payload.settings?.backupEncryptionPassword != null) {479 current.copy(480 backupEncryptionEnabled = true,481 backupEncryptionPassword = payload.settings.backupEncryptionPassword,482 )483 } else current484 if (BackupSection.Settings !in includedSections || payload.sourceApp == "mangayomi" || payload.settings == null) return settings485 val incoming = payload.settings.savedSearches?.let { restorePresets(it, payload.sources, mergedSources) }486 val releases = restoreReleasePreferences(payload.settings.chapterReleasePreferences, payload.mangas, mergedMangas)487 return settings.copy(488 savedSearches = if (incoming == null) settings.savedSearches else (settings.savedSearches.orEmpty() + incoming).distinctBy { it.id },489 chapterReleasePreferences = (settings.chapterReleasePreferences + releases).distinctBy { it.mangaId },490 automaticReaderLayouts = (settings.automaticReaderLayouts + restoreAutomaticLayouts(payload.settings.automaticReaderLayouts, payload.mangas, mergedMangas)).distinctBy { it.mangaId },491 )492 }493494 private fun <T> mergeTypedCollection(495 current: List<T>,496 incoming: List<T>,497 includedSections: Set<String>,498 section: String,499 typeOf: (T) -> DbItemType,500 includedTypes: Set<DbItemType>,501 identityOf: (T) -> Long,502 ): List<T> = if (section !in includedSections) {503 current504 } else if (includedTypes.isEmpty()) {505 // The collection itself is explicitly selected, but no title type is506 // available to partition it (for example, an empty legacy backup).507 // Typed rows can still be replaced without guessing a title parent.508 incoming.also { checkIdentityCollisions(section, emptyList(), it, identityOf) }509 } else {510 val preserved = current.filter { typeOf(it) !in includedTypes }511 val accepted = incoming.filter { typeOf(it) in includedTypes }512 checkIdentityCollisions(section, preserved, accepted, identityOf)513 preserved + accepted514 }515516 private fun <T> mergeTitleDependent(517 current: List<T>,518 incoming: List<T>,519 includedSections: Set<String>,520 section: String,521 mangas: List<DbManga>,522 mangaIdOf: (T) -> Long?,523 chapterIdOf: ((T) -> Long?)?,524 identityOf: (T) -> Long,525 includedTypes: Set<DbItemType>,526 chapters: Map<Long, DbChapter> = emptyMap(),527 ): List<T> {528 if (section !in includedSections) return current529 val titleTypes = mangas.associateBy(DbManga::id)530 fun typeOf(record: T): DbItemType? = mangaIdOf(record)?.let { titleTypes[it]?.itemType }531 ?: chapterIdOf?.invoke(record)?.let { chapters[it]?.mangaId?.let(titleTypes::get)?.itemType }532 val selectedIds = titleTypes.filterValues { it.itemType in includedTypes }.keys533 fun hasValidReferences(record: T): Boolean {534 val mangaId = mangaIdOf(record)535 val chapterId = chapterIdOf?.invoke(record)536 if (mangaId != null && mangaId !in titleTypes) return false537 if (chapterId != null && chapterId !in chapters) return false538 if (mangaId != null && chapterId != null && chapters[chapterId]?.mangaId?.let { it != mangaId } == true) {539 return false540 }541 return true542 }543 if (includedTypes.isEmpty()) {544 // No title type means there is no graph to partition. An explicit545 // dependent section is therefore a whole-section replacement;546 // validate its rows against the final (preserved) title graph.547 val accepted = incoming.filter(::hasValidReferences)548 checkIdentityCollisions(section, emptyList(), accepted, identityOf)549 return accepted550 }551 val preserved = current.filter { hasValidReferences(it) && typeOf(it) !in includedTypes }552 val accepted = incoming.filter { record ->553 val mangaId = mangaIdOf(record)554 val chapterId = chapterIdOf?.invoke(record)555 val directMangaIsSelected = mangaId != null && mangaId in selectedIds556 val chapterMangaId = chapterId?.let { chapters[it]?.mangaId }557 val chapterIsSelected = chapterMangaId != null && chapterMangaId in selectedIds558 val directMangaIsValid = mangaId == null || directMangaIsSelected559 val chapterIsValid = chapterId == null || chapterIsSelected560 val relationshipIsValid = mangaId == null || chapterMangaId == null || mangaId == chapterMangaId561 directMangaIsValid && chapterIsValid && relationshipIsValid &&562 (directMangaIsSelected || chapterIsSelected)563 }564 checkIdentityCollisions(section, preserved, accepted, identityOf)565 return preserved + accepted566 }567568 private fun mergeChangedParts(569 current: List<DbChangedPart>,570 incoming: List<DbChangedPart>,571 includedSections: Set<String>,572 ): List<DbChangedPart> {573 if (BackupSection.ChangedParts !in includedSections) return current574 checkIdentityCollisions("changedParts", current, incoming, DbChangedPart::id)575 return current + incoming576 }577578 private fun <T, K : Any> checkIdentityCollisions(579 collection: String,580 preserved: List<T>,581 incoming: List<T>,582 identityOf: (T) -> K?,583 ) {584 val preservedKeys = preserved.mapNotNull(identityOf).toSet()585 val incomingKeys = incoming.mapNotNull(identityOf)586 if (incomingKeys.size != incomingKeys.toSet().size || incomingKeys.any { it in preservedKeys }) {587 throw BackupIdentityCollisionException("Backup contains colliding $collection identities")588 }589 }590591 private fun sanitizeRestoreSnapshot(snapshot: YokanDatabaseSnapshot): YokanDatabaseSnapshot {592 val categoryById = snapshot.categories.associateBy(DbCategory::id)593 val sourceTypes = snapshot.sources.associate { it.id to it.itemType }594 val mangas = snapshot.mangas.map { manga ->595 manga.copy(596 categories = manga.categories?.filter { categoryId ->597 categoryById[categoryId]?.forItemType == manga.itemType598 },599 sourceId = manga.sourceId?.takeIf { sourceTypes[it] == manga.itemType },600 )601 }602 val mangaIds = mangas.mapTo(hashSetOf(), DbManga::id)603 val chapters = snapshot.chapters.filter { it.mangaId == null || it.mangaId in mangaIds }604 val chapterById = chapters.associateBy(DbChapter::id)605 fun validTitleAndChapter(mangaId: Long?, chapterId: Long?): Boolean {606 if (mangaId != null && mangaId !in mangaIds) return false607 if (chapterId != null && chapterId !in chapterById) return false608 if (mangaId != null && chapterId != null) {609 val chapterMangaId = chapterById[chapterId]?.mangaId610 if (chapterMangaId != null && chapterMangaId != mangaId) return false611 }612 return true613 }614 val histories = snapshot.histories.filter { validTitleAndChapter(it.mangaId, it.chapterId) }615 val updates = snapshot.updates.filter { validTitleAndChapter(it.mangaId, it.chapterId) }616 val tracks = snapshot.tracks.filter { it.mangaId == null || it.mangaId in mangaIds }617 val downloads = snapshot.downloads.filter { it.chapterId == null || it.chapterId in chapterById }618 val pageCache = snapshot.pageCache.filter { it.chapterId == null || it.chapterId in chapterById }619 val settings = snapshot.settings.sanitizeReferences(mangaIds, chapterById.keys)620 return snapshot.copy(621 settings = settings,622 mangas = mangas,623 chapters = chapters,624 histories = histories,625 updates = updates,626 tracks = tracks,627 downloads = downloads,628 pageCache = pageCache,629 )630 }631632 private fun DbSettings.sanitizeReferences(633 mangaIds: Set<Long>,634 chapterIds: Set<Long>,635 ): DbSettings = copy(636 chapterReleasePreferences = chapterReleasePreferences.filter { it.mangaId == null || it.mangaId in mangaIds },637 automaticReaderLayouts = automaticReaderLayouts.filter { it.mangaId in mangaIds },638 sortChapterList = sortChapterList?.filter { it.mangaId == null || it.mangaId in mangaIds },639 chapterFilterDownloadedList = chapterFilterDownloadedList?.filter { it.mangaId == null || it.mangaId in mangaIds },640 chapterFilterUnreadList = chapterFilterUnreadList?.filter { it.mangaId == null || it.mangaId in mangaIds },641 chapterFilterBookmarkedList = chapterFilterBookmarkedList?.filter { it.mangaId == null || it.mangaId in mangaIds },642 chapterPageIndexList = chapterPageIndexList?.filter { it.chapterId == null || it.chapterId in chapterIds },643 personalReaderModeList = personalReaderModeList?.filter { it.mangaId == null || it.mangaId in mangaIds },644 personalPageModeList = personalPageModeList?.filter { it.mangaId == null || it.mangaId in mangaIds },645 autoScrollPages = autoScrollPages?.filter { it.mangaId == null || it.mangaId in mangaIds },646 filterScanlatorList = filterScanlatorList?.filter { it.mangaId == null || it.mangaId in mangaIds },647 )648649 private fun restoreAutomaticLayouts(650 preferences: List<eu.friedcutlet.yokan.database.DbAutomaticReaderLayout>,651 originalMangas: List<DbManga>,652 targetMangas: List<DbManga>,653 ): List<eu.friedcutlet.yokan.database.DbAutomaticReaderLayout> = preferences.mapNotNull { preference ->654 val original = originalMangas.firstOrNull { it.id == preference.mangaId } ?: return@mapNotNull null655 val key = mangaKey(original.itemType, original.link, original.name)656 val target = targetMangas.filter { mangaKey(it.itemType, it.link, it.name) == key }.singleOrNull() ?: return@mapNotNull null657 preference.copy(mangaId = target.id)658 }659660 private fun restoreReleasePreferences(661 preferences: List<DbChapterReleasePreference>,662 originalMangas: List<DbManga>,663 targetMangas: List<DbManga>,664 ): List<DbChapterReleasePreference> = preferences.mapNotNull { preference ->665 if (preference.mangaId == null) return@mapNotNull preference666 val original = originalMangas.firstOrNull { it.id == preference.mangaId } ?: return@mapNotNull null667 val key = mangaKey(original.itemType, original.link, original.name)668 val target = targetMangas.filter { mangaKey(it.itemType, it.link, it.name) == key }.singleOrNull() ?: return@mapNotNull null669 preference.copy(mangaId = target.id)670 }671672 private fun restorePresets(673 presets: List<DbSavedSearch>,674 originalSources: List<DbSource>,675 targetSources: List<DbSource>,676 ): List<DbSavedSearch> = presets.map { preset ->677 val identity = preset.sourceIdentity ?: originalSources.firstOrNull { it.id == preset.sourceId }?.presetIdentity()678 val matches = targetSources.filter { it.presetIdentity() == identity }679 preset.copy(680 sourceId = matches.singleOrNull()?.id ?: preset.sourceId,681 sourceIdentity = identity,682 missingSourceIdentity = preset.missingSourceIdentity || identity == null,683 )684 }685686 private fun applyMangaSections(687 current: List<DbManga>,688 incoming: List<DbManga>,689 includedTypes: Set<DbItemType>,690 ): List<DbManga> {691 if (includedTypes.isEmpty()) return current692 return current.filterNot { it.itemType in includedTypes } + incoming.filter { it.itemType in includedTypes }693 }694}695