SelectiveDataClearService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/SelectiveDataClearService.kt
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.database.*4import eu.friedcutlet.yokan.database.sync.SyncPaths5import eu.friedcutlet.yokan.domain.ItemType6import eu.friedcutlet.yokan.services.download.DownloadService7import eu.friedcutlet.yokan.services.download.DownloadProgress8import kotlinx.coroutines.CancellationException910data class ClearResult(11 val cleared: Boolean,12 val titlesRemoved: Int = 0,13 val chaptersRemoved: Int = 0,14 val dependentRowsRemoved: Int = 0,15 val sourcesRemoved: Int = 0,16 val deliveryPending: Boolean = false,17 val error: String? = null,18)1920/** Removes logical database data only. Downloaded media files are deliberately untouched. */21class SelectiveDataClearService(22 private val database: YokanDatabase,23 private val downloader: DownloadService,24 private val onSourcesCommitted: (Set<Long>) -> Unit = {},25) {26 suspend fun clearLibrary(types: Set<ItemType>): ClearResult {27 require(types.isNotEmpty()) { "Select at least one library type to clear." }28 val before = database.snapshot()29 val selected = types.mapTo(mutableSetOf(), ::toDbType)30 val plan = planLibraryClear(before, selected)31 plan.error?.let { return ClearResult(cleared = false, error = it) }32 if (hasAffectedDownloads(before, plan.removedChapters, selected)) {33 return ClearResult(cleared = false, error = "Cancel or finish queued, paused, and active downloads for the selected library types before clearing them.")34 }35 val hubConfigured = before.syncPreferences.any { !it.server.isNullOrBlank() && !it.server.startsWith("cloud://") }36 val activeHub = SyncPaths.activeHubEpoch(before.syncPreferences)37 if (hubConfigured && (activeHub == null || before.syncPreferences.none { it.syncOn && !it.authToken.isNullOrBlank() && !it.server.isNullOrBlank() && it.hubEpoch > 0 && it.hubBootstrapComplete })) {38 return ClearResult(cleared = false, error = "Reconnect and complete hub sync setup before clearing library data, so deletions can be delivered.")39 }40 return commit(before, plan.after, plan, deliveryPending = activeHub != null)41 }4243 suspend fun clearSources(types: Set<ItemType>): ClearResult {44 require(types.isNotEmpty()) { "Select at least one source type to clear." }45 val before = database.snapshot()46 val selected = types.mapTo(mutableSetOf(), ::toDbType)47 val sourceIds = before.sources.filter { it.itemType in selected }.mapTo(mutableSetOf()) { it.id }48 val chapterIds = before.mangas.filter { it.sourceId?.let(sourceIds::contains) == true }.flatMap { title ->49 before.chapters.filter { it.mangaId == title.id }.map { it.id }50 }.toSet()51 if (hasAffectedDownloads(before, chapterIds, selected, sourceIds)) {52 return ClearResult(cleared = false, error = "Cancel or finish queued, paused, and active downloads using the selected sources before clearing them.")53 }54 val after = planSourceClear(before, selected).after55 val result = commit(before, after, ClearPlan(after), removedSourceIds = sourceIds)56 if (result.cleared && sourceIds.isNotEmpty()) onSourcesCommitted(sourceIds)57 return result.copy(sourcesRemoved = if (result.cleared) sourceIds.size else 0)58 }5960 private suspend fun commit(61 before: YokanDatabaseSnapshot,62 after: YokanDatabaseSnapshot,63 plan: ClearPlan,64 removedSourceIds: Set<Long> = emptySet(),65 deliveryPending: Boolean = false,66 ): ClearResult {67 if (!database.supportsAtomicSnapshotPersistence()) {68 return ClearResult(cleared = false, error = "This database backend cannot atomically clear data; nothing was changed.")69 }70 return try {71 val withOutbox = after.copy(outbox = SyncPaths.outboxForReplacement(before, after))72 database.replaceAllAtomically(withOutbox, expectedSnapshot = before, removedSourceIds = removedSourceIds)73 ClearResult(74 cleared = true,75 titlesRemoved = plan.removedTitles.size,76 chaptersRemoved = plan.removedChapters.size,77 dependentRowsRemoved = plan.dependentRowsRemoved,78 deliveryPending = deliveryPending,79 )80 } catch (error: CancellationException) {81 throw error82 } catch (error: Throwable) {83 ClearResult(cleared = false, error = error.message ?: "Database clear failed; no change was committed.")84 }85 }8687 private fun hasAffectedDownloads(88 snapshot: YokanDatabaseSnapshot,89 chapterIds: Set<Long>,90 types: Set<DbItemType>,91 sourceIds: Set<Long> = emptySet(),92 ): Boolean {93 val titles = snapshot.mangas.associateBy { it.id }94 fun affected(chapterId: Long?): Boolean {95 val title = snapshot.chapters.firstOrNull { it.id == chapterId }?.mangaId?.let(titles::get) ?: return false96 return chapterId in chapterIds || title.itemType in types || title.sourceId?.let(sourceIds::contains) == true97 }98 return snapshot.downloads.any { it.isStartDownload == true && it.isDownload != true && affected(it.chapterId) } ||99 downloader.activeDownloads().any { !it.isCompleted && activeProgressAffected(it, snapshot, chapterIds, types, sourceIds) }100 }101102 private fun activeProgressAffected(103 progress: DownloadProgress,104 snapshot: YokanDatabaseSnapshot,105 chapterIds: Set<Long>,106 types: Set<DbItemType>,107 sourceIds: Set<Long>,108 ): Boolean {109 val chapterId = progress.taskId.removePrefix("chapter-").toLongOrNull() ?: return progress.itemType in types110 val title = snapshot.chapters.firstOrNull { it.id == chapterId }?.mangaId?.let { id -> snapshot.mangas.firstOrNull { it.id == id } }111 return chapterId in chapterIds || title?.itemType?.let(types::contains) == true || title?.sourceId?.let(sourceIds::contains) == true112 }113}114115internal data class ClearPlan(116 val after: YokanDatabaseSnapshot,117 val removedTitles: Set<Long> = emptySet(),118 val removedChapters: Set<Long> = emptySet(),119 val dependentRowsRemoved: Int = 0,120 val error: String? = null,121)122123internal fun planLibraryClear(before: YokanDatabaseSnapshot, types: Set<DbItemType>): ClearPlan {124 val titleIds = before.mangas.filter { it.itemType in types }.mapTo(mutableSetOf()) { it.id }125 val titleById = before.mangas.associateBy { it.id }126 val chapters = before.chapters.filter { it.mangaId in titleIds }127 val chapterIds = chapters.mapTo(mutableSetOf()) { it.id }128 // A row with conflicting explicit ownership is not safe to cascade.129 if (before.histories.any { it.mangaId in titleIds && it.itemType != titleById[it.mangaId]?.itemType }) {130 return ClearPlan(before, error = "A history row has conflicting media-type ownership; resolve it before clearing.")131 }132 if (before.tracks.any { it.mangaId in titleIds && it.itemType != titleById[it.mangaId]?.itemType }) {133 return ClearPlan(before, error = "A tracker row has conflicting media-type ownership; resolve it before clearing.")134 }135 val histories = before.histories.filter { it.mangaId in titleIds || it.chapterId in chapterIds }136 val updates = before.updates.filter { it.mangaId in titleIds || it.chapterId in chapterIds }137 val tracks = before.tracks.filter { it.mangaId in titleIds }138 val downloads = before.downloads.filter { it.chapterId in chapterIds }139 val searches = before.trackSearches.filter { it.libraryId in titleIds }140 val settings = before.settings.copy(141 sortChapterList = before.settings.sortChapterList?.filterNot { it.mangaId in titleIds },142 chapterFilterDownloadedList = before.settings.chapterFilterDownloadedList?.filterNot { it.mangaId in titleIds },143 chapterFilterUnreadList = before.settings.chapterFilterUnreadList?.filterNot { it.mangaId in titleIds },144 chapterFilterBookmarkedList = before.settings.chapterFilterBookmarkedList?.filterNot { it.mangaId in titleIds },145 chapterPageIndexList = before.settings.chapterPageIndexList?.filterNot { it.chapterId in chapterIds },146 personalReaderModeList = before.settings.personalReaderModeList?.filterNot { it.mangaId in titleIds },147 filterScanlatorList = before.settings.filterScanlatorList?.filterNot { it.mangaId in titleIds },148 personalPageModeList = before.settings.personalPageModeList?.filterNot { it.mangaId in titleIds },149 autoScrollPages = before.settings.autoScrollPages?.filterNot { it.mangaId in titleIds },150 titleMetadata = before.settings.titleMetadata?.filterNot { it.mangaId in titleIds },151 updateErrors = before.settings.updateErrors?.filterNot { it.mangaId in titleIds },152 downloadQueueOrder = before.settings.downloadQueueOrder.filterNot { id -> downloads.any { it.id == id } },153 )154 val after = before.copy(155 settings = settings,156 mangas = before.mangas.filterNot { it.id in titleIds },157 chapters = before.chapters.filterNot { it.id in chapterIds },158 histories = before.histories.filterNot { it in histories },159 updates = before.updates.filterNot { it in updates },160 tracks = before.tracks.filterNot { it in tracks },161 trackSearches = before.trackSearches.filterNot { it in searches },162 downloads = before.downloads.filterNot { it in downloads },163 pageCache = before.pageCache.filterNot { it.chapterId in chapterIds },164 )165 return ClearPlan(after, titleIds, chapterIds, histories.size + updates.size + tracks.size + searches.size + downloads.size + (before.pageCache.size - after.pageCache.size))166}167168internal fun planSourceClear(before: YokanDatabaseSnapshot, types: Set<DbItemType>): ClearPlan {169 val sourceIds = before.sources.filter { it.itemType in types }.mapTo(mutableSetOf()) { it.id }170 val after = before.copy(171 sources = before.sources.filterNot { it.id in sourceIds },172 settings = before.settings.copy(sourcePreferences = before.settings.sourcePreferences?.filterNot { it.sourceId in sourceIds }),173 pageCache = before.pageCache.filterNot { it.sourceId in sourceIds },174 )175 return ClearPlan(after)176}177178/** Remote tombstones use this with [recordChange] false while inside applyRemote, so they do not echo. */179@Suppress("UNUSED_PARAMETER")180internal fun removeTitleWithDependents(database: YokanDatabase, mangaId: Long, recordChange: Boolean = false) {181 if (database.manga(mangaId) == null) return182 val before = database.snapshot()183 val chapterIds = before.chapters.filter { it.mangaId == mangaId }.mapTo(mutableSetOf()) { it.id }184 val removedDownloadIds = before.downloads.filter { it.chapterId in chapterIds }.mapTo(mutableSetOf()) { it.id }185 val after = before.copy(186 mangas = before.mangas.filterNot { it.id == mangaId },187 chapters = before.chapters.filterNot { it.id in chapterIds },188 histories = before.histories.filterNot { it.mangaId == mangaId || it.chapterId in chapterIds },189 updates = before.updates.filterNot { it.mangaId == mangaId || it.chapterId in chapterIds },190 downloads = before.downloads.filterNot { it.id in removedDownloadIds },191 tracks = before.tracks.filterNot { it.mangaId == mangaId },192 trackSearches = before.trackSearches.filterNot { it.libraryId == mangaId },193 pageCache = before.pageCache.filterNot { it.chapterId in chapterIds },194 settings = before.settings.copy(195 sortChapterList = before.settings.sortChapterList?.filterNot { it.mangaId == mangaId },196 chapterFilterDownloadedList = before.settings.chapterFilterDownloadedList?.filterNot { it.mangaId == mangaId },197 chapterFilterUnreadList = before.settings.chapterFilterUnreadList?.filterNot { it.mangaId == mangaId },198 chapterFilterBookmarkedList = before.settings.chapterFilterBookmarkedList?.filterNot { it.mangaId == mangaId },199 chapterPageIndexList = before.settings.chapterPageIndexList?.filterNot { it.chapterId in chapterIds },200 personalReaderModeList = before.settings.personalReaderModeList?.filterNot { it.mangaId == mangaId },201 filterScanlatorList = before.settings.filterScanlatorList?.filterNot { it.mangaId == mangaId },202 personalPageModeList = before.settings.personalPageModeList?.filterNot { it.mangaId == mangaId },203 autoScrollPages = before.settings.autoScrollPages?.filterNot { it.mangaId == mangaId },204 titleMetadata = before.settings.titleMetadata?.filterNot { it.mangaId == mangaId },205 updateErrors = before.settings.updateErrors?.filterNot { it.mangaId == mangaId },206 downloadQueueOrder = before.settings.downloadQueueOrder.filterNot { it in removedDownloadIds },207 ),208 )209 // replaceAll publishes the child and parent removals as one snapshot; sync callers run this in applyRemote.210 database.replaceAll(after, expectedSnapshot = before)211}212213private fun toDbType(type: ItemType): DbItemType = when (type) {214 ItemType.Manga -> DbItemType.Manga215 ItemType.Anime -> DbItemType.Anime216 ItemType.Novel -> DbItemType.Novel217}218