package eu.friedcutlet.yokan.services.backup import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbChangedPart import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.database.DbFetchType import eu.friedcutlet.yokan.database.DbHistory import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackPreference import eu.friedcutlet.yokan.database.DbUpdate import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot import eu.friedcutlet.yokan.database.sync.preserveDeviceLocalSettings import eu.friedcutlet.yokan.database.DbSavedSearch import eu.friedcutlet.yokan.database.DbChapterReleasePreference import eu.friedcutlet.yokan.database.mergeProgress import eu.friedcutlet.yokan.database.presetIdentity import eu.friedcutlet.yokan.domain.mergePrivateNotes private class BackupIdentityCollisionException(message: String) : IllegalStateException(message) /** * Combines the current database with a decoded backup. [replace] swaps every * included section wholesale; [merge] adds what is missing and folds progress * into matching titles. Both reject identity collisions and drop dangling references. */ internal object BackupMerge { /** Identity used to match titles across devices: link when known, else lowercase name. */ fun mangaKey(itemType: DbItemType, link: String?, name: String?): String = if (!link.isNullOrBlank()) "${itemType.name}:link:${link.trim()}" else "${itemType.name}:name:${name?.trim()?.lowercase().orEmpty()}" fun replace( current: YokanDatabaseSnapshot, payload: BackupSnapshot, includedSections: Set, ): YokanDatabaseSnapshot { val includedTypes = includedSections.titleTypes() val replacements = if (payload.privateNotesIncluded) payload.mangas else { val localNotes = current.mangas.associate { mangaKey(it.itemType, it.link, it.name) to it.privateNote } payload.mangas.map { it.copy(privateNote = localNotes[mangaKey(it.itemType, it.link, it.name)].orEmpty()) } } val mangas = applyMangaSections(current.mangas, replacements, includedTypes) checkIdentityCollisions( "mangas", current.mangas.filter { it.itemType !in includedTypes }, payload.mangas.filter { it.itemType in includedTypes }, DbManga::id, ) val categories = mergeTypedCollection( current.categories, payload.categories, includedSections, BackupSection.Categories, DbCategory::forItemType, includedTypes, DbCategory::id, ) val sources = mergeTypedCollection( current.sources, payload.sources, includedSections, BackupSection.Sources, DbSource::itemType, includedTypes, DbSource::id, ) val chapters = mergeTitleDependent( current.chapters, payload.chapters, includedSections, BackupSection.Chapters, mangas, { it.mangaId }, null, DbChapter::id, includedTypes, ) val chaptersById = chapters.associateBy(DbChapter::id) val histories = mergeTitleDependent( current.histories, payload.histories, includedSections, BackupSection.History, mangas, { it.mangaId }, { it.chapterId }, DbHistory::id, includedTypes, chaptersById, ) val updates = mergeTitleDependent( current.updates, payload.updates, includedSections, BackupSection.Updates, mangas, { it.mangaId }, { it.chapterId }, DbUpdate::id, includedTypes, chaptersById, ) val tracks = mergeTitleDependent( current.tracks, payload.tracks, includedSections, BackupSection.Tracks, mangas, { it.mangaId }, null, DbTrack::id, includedTypes, ) val settings = if (payload.sourceApp == "mangayomi") { if (payload.settings?.backupEncryptionPassword != null) { current.settings.copy( backupEncryptionEnabled = true, backupEncryptionPassword = payload.settings.backupEncryptionPassword, ) } else current.settings } else if (BackupSection.Settings in includedSections) { payload.settings ?.let { incoming -> preserveDeviceLocalSettings(current.settings, incoming).copy( savedSearches = incoming.savedSearches?.let { restorePresets(it, payload.sources, sources) }, chapterReleasePreferences = restoreReleasePreferences(incoming.chapterReleasePreferences, payload.mangas, mangas), automaticReaderLayout = incoming.automaticReaderLayout, readerHoldToScroll = incoming.readerHoldToScroll, automaticReaderLayouts = restoreAutomaticLayouts(incoming.automaticReaderLayouts, payload.mangas, mangas), ) } ?: current.settings } else current.settings val changedParts = mergeChangedParts(current.changedParts, payload.changedParts, includedSections) if (BackupSection.TrackPreferences in includedSections) { checkIdentityCollisions("trackPreferences", emptyList(), payload.trackPreferences, DbTrackPreference::syncId) } if (BackupSection.CustomButtons in includedSections) { checkIdentityCollisions("customButtons", emptyList(), payload.customButtons, DbCustomButton::id) } return sanitizeRestoreSnapshot( current.copy( settings = settings, mangas = mangas, chapters = chapters, categories = categories, sources = sources, histories = histories, updates = updates, tracks = tracks, trackPreferences = if (BackupSection.TrackPreferences in includedSections) { payload.trackPreferences } else { current.trackPreferences }, customButtons = if (BackupSection.CustomButtons in includedSections) { payload.customButtons } else { current.customButtons }, changedParts = changedParts, ), ) } fun merge( current: YokanDatabaseSnapshot, payload: BackupSnapshot, includedSections: Set, ): YokanDatabaseSnapshot { val categories = mergeCategories(current.categories, payload.categories, BackupSection.Categories in includedSections) val sources = mergeSources(current.sources, payload.sources, BackupSection.Sources in includedSections) val mangas = mergeMangas(current.mangas, payload, includedSections.titleTypes(), categories.ids, sources.ids) val chapters = mergeChapters(current.chapters, payload.chapters, BackupSection.Chapters in includedSections, mangas) return sanitizeRestoreSnapshot( current.copy( settings = mergeSettings(current.settings, payload, includedSections, sources.rows, mangas.rows), mangas = mangas.rows, chapters = chapters.rows, categories = categories.rows, sources = sources.rows, histories = mergeHistories(current.histories, payload.histories, BackupSection.History in includedSections, mangas.ids, chapters.ids), updates = mergeUpdates(current.updates, payload.updates, BackupSection.Updates in includedSections, mangas.ids, chapters.ids), tracks = mergeTracks(current.tracks, payload.tracks, BackupSection.Tracks in includedSections, mangas.ids), customButtons = mergeButtons(current.customButtons, payload.customButtons, BackupSection.CustomButtons in includedSections), ), ) } /** Merged rows, the backup→merged id of every accepted backup row, and the ids of rows the merge added. */ private class Merged( val rows: List, val ids: Map = emptyMap(), val added: Set = emptySet(), ) private fun nextId(a: List, b: List, id: (T) -> Long): Long = maxOf(a.maxOfOrNull(id) ?: 0L, b.maxOfOrNull(id) ?: 0L) + 1L private fun mergeCategories(current: List, incoming: List, included: Boolean): Merged { if (!included) return Merged(current) var nextId = nextId(current, incoming, DbCategory::id) val ids = mutableMapOf() val rows = current.toMutableList() for (incomingCat in incoming) { val existing = current.firstOrNull { it.name.trim().equals(incomingCat.name.trim(), ignoreCase = true) && it.forItemType == incomingCat.forItemType } if (existing != null) { ids[incomingCat.id] = existing.id } else { val newId = nextId++ ids[incomingCat.id] = newId rows.add(incomingCat.copy(id = newId)) } } return Merged(rows, ids) } private fun mergeSources(current: List, incoming: List, included: Boolean): Merged { if (!included) return Merged(current) var nextId = nextId(current, incoming, DbSource::id) val ids = mutableMapOf() val rows = current.toMutableList() for (incomingSrc in incoming) { val existing = current.firstOrNull { it.itemType == incomingSrc.itemType && (it.id == incomingSrc.id || it.name.trim().equals(incomingSrc.name.trim(), ignoreCase = true)) } if (existing != null) { ids[incomingSrc.id] = existing.id } else { val newId = if (current.none { it.id == incomingSrc.id }) incomingSrc.id else nextId++ ids[incomingSrc.id] = newId rows.add(incomingSrc.copy(id = newId)) } } return Merged(rows, ids) } private fun mergeMangas( current: List, payload: BackupSnapshot, includedTypes: Set, categoryIds: Map, sourceIds: Map, ): Merged { var nextId = nextId(current, payload.mangas, DbManga::id) val ids = mutableMapOf() val newIds = mutableSetOf() val rows = current.toMutableList() val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap() val byKey = mutableMapOf() for (m in current) { byKey[mangaKey(m.itemType, m.link, m.name)] = m } val incomingMangas = payload.mangas.filter { it.itemType in includedTypes } for (incomingManga in incomingMangas) { val key = mangaKey(incomingManga.itemType, incomingManga.link, incomingManga.name) val existing = byKey[key] val remappedCategories = incomingManga.categories?.mapNotNull { categoryIds[it] ?: it }?.distinct() val remappedSourceId = incomingManga.sourceId?.let { sourceIds[it] ?: it } if (existing != null) { ids[incomingManga.id] = existing.id val combinedCategories = (existing.categories.orEmpty() + remappedCategories.orEmpty()).distinct() val updated = existing.copy( // Season records stay out of the library unless they were favorites themselves. favorite = incomingManga.parentId == null || existing.favorite || incomingManga.favorite, privateNote = mergePrivateNotes(existing.privateNote, incomingManga.privateNote.takeIf { payload.privateNotesIncluded }.orEmpty()), categories = combinedCategories, sourceId = existing.sourceId ?: remappedSourceId, author = existing.author?.ifBlank { incomingManga.author } ?: incomingManga.author, artist = existing.artist?.ifBlank { incomingManga.artist } ?: incomingManga.artist, description = existing.description?.ifBlank { incomingManga.description } ?: incomingManga.description, genre = (existing.genre.orEmpty() + incomingManga.genre.orEmpty()).distinct().takeIf { it.isNotEmpty() }, cast = existing.cast.ifEmpty { incomingManga.cast }, fetchType = if (incomingManga.fetchType == DbFetchType.Seasons) DbFetchType.Seasons else existing.fetchType, seasonNumber = existing.seasonNumber ?: incomingManga.seasonNumber, ) rows[indexById.getValue(existing.id)] = updated } else { val newId = nextId++ ids[incomingManga.id] = newId newIds.add(newId) val newManga = incomingManga.copy( id = newId, privateNote = incomingManga.privateNote.takeIf { payload.privateNotesIncluded }.orEmpty(), favorite = incomingManga.parentId == null || incomingManga.favorite, parentId = null, // Remapped below once every parent has its merged id. categories = remappedCategories, sourceId = remappedSourceId, ) rows.add(newManga) indexById[newId] = rows.lastIndex byKey[key] = newManga } } incomingMangas.forEach { incoming -> val parent = incoming.parentId?.let(ids::get) ?: return@forEach val index = indexById.getValue(ids.getValue(incoming.id)) val merged = rows[index] if (merged.parentId == null && merged.id != parent) rows[index] = merged.copy(parentId = parent) } return Merged(rows, ids, newIds) } private fun mergeChapters( current: List, incoming: List, included: Boolean, mangas: Merged, ): Merged { if (!included) return Merged(current) var nextId = nextId(current, incoming, DbChapter::id) val ids = mutableMapOf() val existingByMangaId = current.groupBy { it.mangaId }.mapValues { it.value.toMutableList() }.toMutableMap() val rows = current.toMutableList() val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap() for (incomingCh in incoming) { val targetMangaId = incomingCh.mangaId?.let { mangas.ids[it] } ?: continue if (targetMangaId in mangas.added) { val newId = nextId++ ids[incomingCh.id] = newId rows.add(incomingCh.copy(id = newId, mangaId = targetMangaId)) indexById[newId] = rows.lastIndex continue } val existingList = existingByMangaId.getOrPut(targetMangaId) { mutableListOf() } val matchingChapter = existingList.firstOrNull { (!it.url.isNullOrBlank() && it.url == incomingCh.url) || (it.url.isNullOrBlank() && incomingCh.url.isNullOrBlank() && it.name == incomingCh.name) } if (matchingChapter != null) { ids[incomingCh.id] = matchingChapter.id val updatedCh = matchingChapter.mergeProgress(incomingCh).copy( dateUpload = if (incomingCh.dateUpload.isNotBlank() && matchingChapter.dateUpload.isBlank()) { incomingCh.dateUpload } else matchingChapter.dateUpload, number = matchingChapter.number ?: incomingCh.number, season = matchingChapter.season ?: incomingCh.season, numberingName = matchingChapter.numberingName ?: incomingCh.numberingName, ) if (updatedCh != matchingChapter) { rows[indexById.getValue(matchingChapter.id)] = updatedCh val exIdx = existingList.indexOfFirst { it.id == matchingChapter.id } if (exIdx >= 0) existingList[exIdx] = updatedCh } } else { val newId = nextId++ ids[incomingCh.id] = newId val newCh = incomingCh.copy(id = newId, mangaId = targetMangaId) rows.add(newCh) indexById[newId] = rows.lastIndex existingList.add(newCh) } } return Merged(rows, ids) } private fun mergeHistories( current: List, incoming: List, included: Boolean, mangaIds: Map, chapterIds: Map, ): List { if (!included) return current var nextId = nextId(current, incoming, DbHistory::id) val rows = current.toMutableList() val byKey = current.associateBy { "${it.mangaId}:${it.chapterId}" }.toMutableMap() val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap() for (incomingH in incoming) { val targetMangaId = incomingH.mangaId?.let { mangaIds[it] } ?: continue val targetChapterId = incomingH.chapterId?.let { chapterIds[it] } ?: continue val key = "$targetMangaId:$targetChapterId" val existing = byKey[key] if (existing != null) { val mergedDate = listOfNotNull(existing.date, incomingH.date).maxOrNull() ?: existing.date if (mergedDate != existing.date) { val updated = existing.copy(date = mergedDate) rows[indexById.getValue(existing.id)] = updated byKey[key] = updated } } else { val newId = nextId++ val newH = incomingH.copy(id = newId, mangaId = targetMangaId, chapterId = targetChapterId) rows.add(newH) indexById[newId] = rows.lastIndex byKey[key] = newH } } return rows } private fun mergeUpdates( current: List, incoming: List, included: Boolean, mangaIds: Map, chapterIds: Map, ): List { if (!included) return current var nextId = nextId(current, incoming, DbUpdate::id) val rows = current.toMutableList() val byKey = current.associateBy { "${it.mangaId}:${it.chapterName}" }.toMutableMap() for (incomingU in incoming) { val targetMangaId = incomingU.mangaId?.let { mangaIds[it] } ?: continue val targetChapterId = incomingU.chapterId?.let { chapterIds[it] } val key = "$targetMangaId:${incomingU.chapterName}" if (key !in byKey) { val newU = incomingU.copy(id = nextId++, mangaId = targetMangaId, chapterId = targetChapterId) rows.add(newU) byKey[key] = newU } } return rows } private fun mergeTracks( current: List, incoming: List, included: Boolean, mangaIds: Map, ): List { if (!included) return current var nextId = nextId(current, incoming, DbTrack::id) val rows = current.toMutableList() val byKey = current.associateBy { "${it.mangaId}:${it.syncId}" }.toMutableMap() val indexById = rows.withIndex().associate { it.value.id to it.index }.toMutableMap() for (incomingT in incoming) { val targetMangaId = incomingT.mangaId?.let { mangaIds[it] } ?: continue val key = "$targetMangaId:${incomingT.syncId}" val existing = byKey[key] if (existing != null) { // This device's status and score win; the backup only fills progress and a missing score. val updated = existing.copy( lastChapterRead = maxOf(existing.lastChapterRead ?: 0, incomingT.lastChapterRead ?: 0).takeIf { it > 0 }, score = if ((existing.score ?: 0) > 0) existing.score else incomingT.score, ) rows[indexById.getValue(existing.id)] = updated byKey[key] = updated } else { val newId = nextId++ val newT = incomingT.copy(id = newId, mangaId = targetMangaId) rows.add(newT) indexById[newId] = rows.lastIndex byKey[key] = newT } } return rows } private fun mergeButtons(current: List, incoming: List, included: Boolean): List { if (!included) return current var nextId = nextId(current, incoming, DbCustomButton::id) val existingNames = current.map { it.title?.trim()?.lowercase().orEmpty() }.toSet() return current + incoming .filter { it.title?.trim()?.lowercase().orEmpty() !in existingNames } .map { it.copy(id = nextId++) } } private fun mergeSettings( current: DbSettings, payload: BackupSnapshot, includedSections: Set, mergedSources: List, mergedMangas: List, ): DbSettings { val settings = if (payload.settings?.backupEncryptionPassword != null) { current.copy( backupEncryptionEnabled = true, backupEncryptionPassword = payload.settings.backupEncryptionPassword, ) } else current if (BackupSection.Settings !in includedSections || payload.sourceApp == "mangayomi" || payload.settings == null) return settings val incoming = payload.settings.savedSearches?.let { restorePresets(it, payload.sources, mergedSources) } val releases = restoreReleasePreferences(payload.settings.chapterReleasePreferences, payload.mangas, mergedMangas) return settings.copy( savedSearches = if (incoming == null) settings.savedSearches else (settings.savedSearches.orEmpty() + incoming).distinctBy { it.id }, chapterReleasePreferences = (settings.chapterReleasePreferences + releases).distinctBy { it.mangaId }, automaticReaderLayouts = (settings.automaticReaderLayouts + restoreAutomaticLayouts(payload.settings.automaticReaderLayouts, payload.mangas, mergedMangas)).distinctBy { it.mangaId }, ) } private fun mergeTypedCollection( current: List, incoming: List, includedSections: Set, section: String, typeOf: (T) -> DbItemType, includedTypes: Set, identityOf: (T) -> Long, ): List = if (section !in includedSections) { current } else if (includedTypes.isEmpty()) { // The collection itself is explicitly selected, but no title type is // available to partition it (for example, an empty legacy backup). // Typed rows can still be replaced without guessing a title parent. incoming.also { checkIdentityCollisions(section, emptyList(), it, identityOf) } } else { val preserved = current.filter { typeOf(it) !in includedTypes } val accepted = incoming.filter { typeOf(it) in includedTypes } checkIdentityCollisions(section, preserved, accepted, identityOf) preserved + accepted } private fun mergeTitleDependent( current: List, incoming: List, includedSections: Set, section: String, mangas: List, mangaIdOf: (T) -> Long?, chapterIdOf: ((T) -> Long?)?, identityOf: (T) -> Long, includedTypes: Set, chapters: Map = emptyMap(), ): List { if (section !in includedSections) return current val titleTypes = mangas.associateBy(DbManga::id) fun typeOf(record: T): DbItemType? = mangaIdOf(record)?.let { titleTypes[it]?.itemType } ?: chapterIdOf?.invoke(record)?.let { chapters[it]?.mangaId?.let(titleTypes::get)?.itemType } val selectedIds = titleTypes.filterValues { it.itemType in includedTypes }.keys fun hasValidReferences(record: T): Boolean { val mangaId = mangaIdOf(record) val chapterId = chapterIdOf?.invoke(record) if (mangaId != null && mangaId !in titleTypes) return false if (chapterId != null && chapterId !in chapters) return false if (mangaId != null && chapterId != null && chapters[chapterId]?.mangaId?.let { it != mangaId } == true) { return false } return true } if (includedTypes.isEmpty()) { // No title type means there is no graph to partition. An explicit // dependent section is therefore a whole-section replacement; // validate its rows against the final (preserved) title graph. val accepted = incoming.filter(::hasValidReferences) checkIdentityCollisions(section, emptyList(), accepted, identityOf) return accepted } val preserved = current.filter { hasValidReferences(it) && typeOf(it) !in includedTypes } val accepted = incoming.filter { record -> val mangaId = mangaIdOf(record) val chapterId = chapterIdOf?.invoke(record) val directMangaIsSelected = mangaId != null && mangaId in selectedIds val chapterMangaId = chapterId?.let { chapters[it]?.mangaId } val chapterIsSelected = chapterMangaId != null && chapterMangaId in selectedIds val directMangaIsValid = mangaId == null || directMangaIsSelected val chapterIsValid = chapterId == null || chapterIsSelected val relationshipIsValid = mangaId == null || chapterMangaId == null || mangaId == chapterMangaId directMangaIsValid && chapterIsValid && relationshipIsValid && (directMangaIsSelected || chapterIsSelected) } checkIdentityCollisions(section, preserved, accepted, identityOf) return preserved + accepted } private fun mergeChangedParts( current: List, incoming: List, includedSections: Set, ): List { if (BackupSection.ChangedParts !in includedSections) return current checkIdentityCollisions("changedParts", current, incoming, DbChangedPart::id) return current + incoming } private fun checkIdentityCollisions( collection: String, preserved: List, incoming: List, identityOf: (T) -> K?, ) { val preservedKeys = preserved.mapNotNull(identityOf).toSet() val incomingKeys = incoming.mapNotNull(identityOf) if (incomingKeys.size != incomingKeys.toSet().size || incomingKeys.any { it in preservedKeys }) { throw BackupIdentityCollisionException("Backup contains colliding $collection identities") } } private fun sanitizeRestoreSnapshot(snapshot: YokanDatabaseSnapshot): YokanDatabaseSnapshot { val categoryById = snapshot.categories.associateBy(DbCategory::id) val sourceTypes = snapshot.sources.associate { it.id to it.itemType } val mangas = snapshot.mangas.map { manga -> manga.copy( categories = manga.categories?.filter { categoryId -> categoryById[categoryId]?.forItemType == manga.itemType }, sourceId = manga.sourceId?.takeIf { sourceTypes[it] == manga.itemType }, ) } val mangaIds = mangas.mapTo(hashSetOf(), DbManga::id) val chapters = snapshot.chapters.filter { it.mangaId == null || it.mangaId in mangaIds } val chapterById = chapters.associateBy(DbChapter::id) fun validTitleAndChapter(mangaId: Long?, chapterId: Long?): Boolean { if (mangaId != null && mangaId !in mangaIds) return false if (chapterId != null && chapterId !in chapterById) return false if (mangaId != null && chapterId != null) { val chapterMangaId = chapterById[chapterId]?.mangaId if (chapterMangaId != null && chapterMangaId != mangaId) return false } return true } val histories = snapshot.histories.filter { validTitleAndChapter(it.mangaId, it.chapterId) } val updates = snapshot.updates.filter { validTitleAndChapter(it.mangaId, it.chapterId) } val tracks = snapshot.tracks.filter { it.mangaId == null || it.mangaId in mangaIds } val downloads = snapshot.downloads.filter { it.chapterId == null || it.chapterId in chapterById } val pageCache = snapshot.pageCache.filter { it.chapterId == null || it.chapterId in chapterById } val settings = snapshot.settings.sanitizeReferences(mangaIds, chapterById.keys) return snapshot.copy( settings = settings, mangas = mangas, chapters = chapters, histories = histories, updates = updates, tracks = tracks, downloads = downloads, pageCache = pageCache, ) } private fun DbSettings.sanitizeReferences( mangaIds: Set, chapterIds: Set, ): DbSettings = copy( chapterReleasePreferences = chapterReleasePreferences.filter { it.mangaId == null || it.mangaId in mangaIds }, automaticReaderLayouts = automaticReaderLayouts.filter { it.mangaId in mangaIds }, sortChapterList = sortChapterList?.filter { it.mangaId == null || it.mangaId in mangaIds }, chapterFilterDownloadedList = chapterFilterDownloadedList?.filter { it.mangaId == null || it.mangaId in mangaIds }, chapterFilterUnreadList = chapterFilterUnreadList?.filter { it.mangaId == null || it.mangaId in mangaIds }, chapterFilterBookmarkedList = chapterFilterBookmarkedList?.filter { it.mangaId == null || it.mangaId in mangaIds }, chapterPageIndexList = chapterPageIndexList?.filter { it.chapterId == null || it.chapterId in chapterIds }, personalReaderModeList = personalReaderModeList?.filter { it.mangaId == null || it.mangaId in mangaIds }, personalPageModeList = personalPageModeList?.filter { it.mangaId == null || it.mangaId in mangaIds }, autoScrollPages = autoScrollPages?.filter { it.mangaId == null || it.mangaId in mangaIds }, filterScanlatorList = filterScanlatorList?.filter { it.mangaId == null || it.mangaId in mangaIds }, ) private fun restoreAutomaticLayouts( preferences: List, originalMangas: List, targetMangas: List, ): List = preferences.mapNotNull { preference -> val original = originalMangas.firstOrNull { it.id == preference.mangaId } ?: return@mapNotNull null val key = mangaKey(original.itemType, original.link, original.name) val target = targetMangas.filter { mangaKey(it.itemType, it.link, it.name) == key }.singleOrNull() ?: return@mapNotNull null preference.copy(mangaId = target.id) } private fun restoreReleasePreferences( preferences: List, originalMangas: List, targetMangas: List, ): List = preferences.mapNotNull { preference -> if (preference.mangaId == null) return@mapNotNull preference val original = originalMangas.firstOrNull { it.id == preference.mangaId } ?: return@mapNotNull null val key = mangaKey(original.itemType, original.link, original.name) val target = targetMangas.filter { mangaKey(it.itemType, it.link, it.name) == key }.singleOrNull() ?: return@mapNotNull null preference.copy(mangaId = target.id) } private fun restorePresets( presets: List, originalSources: List, targetSources: List, ): List = presets.map { preset -> val identity = preset.sourceIdentity ?: originalSources.firstOrNull { it.id == preset.sourceId }?.presetIdentity() val matches = targetSources.filter { it.presetIdentity() == identity } preset.copy( sourceId = matches.singleOrNull()?.id ?: preset.sourceId, sourceIdentity = identity, missingSourceIdentity = preset.missingSourceIdentity || identity == null, ) } private fun applyMangaSections( current: List, incoming: List, includedTypes: Set, ): List { if (includedTypes.isEmpty()) return current return current.filterNot { it.itemType in includedTypes } + incoming.filter { it.itemType in includedTypes } } }