package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.database.sync.SyncPaths import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.services.download.DownloadService import eu.friedcutlet.yokan.services.download.DownloadProgress import kotlinx.coroutines.CancellationException data class ClearResult( val cleared: Boolean, val titlesRemoved: Int = 0, val chaptersRemoved: Int = 0, val dependentRowsRemoved: Int = 0, val sourcesRemoved: Int = 0, val deliveryPending: Boolean = false, val error: String? = null, ) /** Removes logical database data only. Downloaded media files are deliberately untouched. */ class SelectiveDataClearService( private val database: YokanDatabase, private val downloader: DownloadService, private val onSourcesCommitted: (Set) -> Unit = {}, ) { suspend fun clearLibrary(types: Set): ClearResult { require(types.isNotEmpty()) { "Select at least one library type to clear." } val before = database.snapshot() val selected = types.mapTo(mutableSetOf(), ::toDbType) val plan = planLibraryClear(before, selected) plan.error?.let { return ClearResult(cleared = false, error = it) } if (hasAffectedDownloads(before, plan.removedChapters, selected)) { return ClearResult(cleared = false, error = "Cancel or finish queued, paused, and active downloads for the selected library types before clearing them.") } val hubConfigured = before.syncPreferences.any { !it.server.isNullOrBlank() && !it.server.startsWith("cloud://") } val activeHub = SyncPaths.activeHubEpoch(before.syncPreferences) if (hubConfigured && (activeHub == null || before.syncPreferences.none { it.syncOn && !it.authToken.isNullOrBlank() && !it.server.isNullOrBlank() && it.hubEpoch > 0 && it.hubBootstrapComplete })) { return ClearResult(cleared = false, error = "Reconnect and complete hub sync setup before clearing library data, so deletions can be delivered.") } return commit(before, plan.after, plan, deliveryPending = activeHub != null) } suspend fun clearSources(types: Set): ClearResult { require(types.isNotEmpty()) { "Select at least one source type to clear." } val before = database.snapshot() val selected = types.mapTo(mutableSetOf(), ::toDbType) val sourceIds = before.sources.filter { it.itemType in selected }.mapTo(mutableSetOf()) { it.id } val chapterIds = before.mangas.filter { it.sourceId?.let(sourceIds::contains) == true }.flatMap { title -> before.chapters.filter { it.mangaId == title.id }.map { it.id } }.toSet() if (hasAffectedDownloads(before, chapterIds, selected, sourceIds)) { return ClearResult(cleared = false, error = "Cancel or finish queued, paused, and active downloads using the selected sources before clearing them.") } val after = planSourceClear(before, selected).after val result = commit(before, after, ClearPlan(after), removedSourceIds = sourceIds) if (result.cleared && sourceIds.isNotEmpty()) onSourcesCommitted(sourceIds) return result.copy(sourcesRemoved = if (result.cleared) sourceIds.size else 0) } private suspend fun commit( before: YokanDatabaseSnapshot, after: YokanDatabaseSnapshot, plan: ClearPlan, removedSourceIds: Set = emptySet(), deliveryPending: Boolean = false, ): ClearResult { if (!database.supportsAtomicSnapshotPersistence()) { return ClearResult(cleared = false, error = "This database backend cannot atomically clear data; nothing was changed.") } return try { val withOutbox = after.copy(outbox = SyncPaths.outboxForReplacement(before, after)) database.replaceAllAtomically(withOutbox, expectedSnapshot = before, removedSourceIds = removedSourceIds) ClearResult( cleared = true, titlesRemoved = plan.removedTitles.size, chaptersRemoved = plan.removedChapters.size, dependentRowsRemoved = plan.dependentRowsRemoved, deliveryPending = deliveryPending, ) } catch (error: CancellationException) { throw error } catch (error: Throwable) { ClearResult(cleared = false, error = error.message ?: "Database clear failed; no change was committed.") } } private fun hasAffectedDownloads( snapshot: YokanDatabaseSnapshot, chapterIds: Set, types: Set, sourceIds: Set = emptySet(), ): Boolean { val titles = snapshot.mangas.associateBy { it.id } fun affected(chapterId: Long?): Boolean { val title = snapshot.chapters.firstOrNull { it.id == chapterId }?.mangaId?.let(titles::get) ?: return false return chapterId in chapterIds || title.itemType in types || title.sourceId?.let(sourceIds::contains) == true } return snapshot.downloads.any { it.isStartDownload == true && it.isDownload != true && affected(it.chapterId) } || downloader.activeDownloads().any { !it.isCompleted && activeProgressAffected(it, snapshot, chapterIds, types, sourceIds) } } private fun activeProgressAffected( progress: DownloadProgress, snapshot: YokanDatabaseSnapshot, chapterIds: Set, types: Set, sourceIds: Set, ): Boolean { val chapterId = progress.taskId.removePrefix("chapter-").toLongOrNull() ?: return progress.itemType in types val title = snapshot.chapters.firstOrNull { it.id == chapterId }?.mangaId?.let { id -> snapshot.mangas.firstOrNull { it.id == id } } return chapterId in chapterIds || title?.itemType?.let(types::contains) == true || title?.sourceId?.let(sourceIds::contains) == true } } internal data class ClearPlan( val after: YokanDatabaseSnapshot, val removedTitles: Set = emptySet(), val removedChapters: Set = emptySet(), val dependentRowsRemoved: Int = 0, val error: String? = null, ) internal fun planLibraryClear(before: YokanDatabaseSnapshot, types: Set): ClearPlan { val titleIds = before.mangas.filter { it.itemType in types }.mapTo(mutableSetOf()) { it.id } val titleById = before.mangas.associateBy { it.id } val chapters = before.chapters.filter { it.mangaId in titleIds } val chapterIds = chapters.mapTo(mutableSetOf()) { it.id } // A row with conflicting explicit ownership is not safe to cascade. if (before.histories.any { it.mangaId in titleIds && it.itemType != titleById[it.mangaId]?.itemType }) { return ClearPlan(before, error = "A history row has conflicting media-type ownership; resolve it before clearing.") } if (before.tracks.any { it.mangaId in titleIds && it.itemType != titleById[it.mangaId]?.itemType }) { return ClearPlan(before, error = "A tracker row has conflicting media-type ownership; resolve it before clearing.") } val histories = before.histories.filter { it.mangaId in titleIds || it.chapterId in chapterIds } val updates = before.updates.filter { it.mangaId in titleIds || it.chapterId in chapterIds } val tracks = before.tracks.filter { it.mangaId in titleIds } val downloads = before.downloads.filter { it.chapterId in chapterIds } val searches = before.trackSearches.filter { it.libraryId in titleIds } val settings = before.settings.copy( sortChapterList = before.settings.sortChapterList?.filterNot { it.mangaId in titleIds }, chapterFilterDownloadedList = before.settings.chapterFilterDownloadedList?.filterNot { it.mangaId in titleIds }, chapterFilterUnreadList = before.settings.chapterFilterUnreadList?.filterNot { it.mangaId in titleIds }, chapterFilterBookmarkedList = before.settings.chapterFilterBookmarkedList?.filterNot { it.mangaId in titleIds }, chapterPageIndexList = before.settings.chapterPageIndexList?.filterNot { it.chapterId in chapterIds }, personalReaderModeList = before.settings.personalReaderModeList?.filterNot { it.mangaId in titleIds }, filterScanlatorList = before.settings.filterScanlatorList?.filterNot { it.mangaId in titleIds }, personalPageModeList = before.settings.personalPageModeList?.filterNot { it.mangaId in titleIds }, autoScrollPages = before.settings.autoScrollPages?.filterNot { it.mangaId in titleIds }, titleMetadata = before.settings.titleMetadata?.filterNot { it.mangaId in titleIds }, updateErrors = before.settings.updateErrors?.filterNot { it.mangaId in titleIds }, downloadQueueOrder = before.settings.downloadQueueOrder.filterNot { id -> downloads.any { it.id == id } }, ) val after = before.copy( settings = settings, mangas = before.mangas.filterNot { it.id in titleIds }, chapters = before.chapters.filterNot { it.id in chapterIds }, histories = before.histories.filterNot { it in histories }, updates = before.updates.filterNot { it in updates }, tracks = before.tracks.filterNot { it in tracks }, trackSearches = before.trackSearches.filterNot { it in searches }, downloads = before.downloads.filterNot { it in downloads }, pageCache = before.pageCache.filterNot { it.chapterId in chapterIds }, ) return ClearPlan(after, titleIds, chapterIds, histories.size + updates.size + tracks.size + searches.size + downloads.size + (before.pageCache.size - after.pageCache.size)) } internal fun planSourceClear(before: YokanDatabaseSnapshot, types: Set): ClearPlan { val sourceIds = before.sources.filter { it.itemType in types }.mapTo(mutableSetOf()) { it.id } val after = before.copy( sources = before.sources.filterNot { it.id in sourceIds }, settings = before.settings.copy(sourcePreferences = before.settings.sourcePreferences?.filterNot { it.sourceId in sourceIds }), pageCache = before.pageCache.filterNot { it.sourceId in sourceIds }, ) return ClearPlan(after) } /** Remote tombstones use this with [recordChange] false while inside applyRemote, so they do not echo. */ @Suppress("UNUSED_PARAMETER") internal fun removeTitleWithDependents(database: YokanDatabase, mangaId: Long, recordChange: Boolean = false) { if (database.manga(mangaId) == null) return val before = database.snapshot() val chapterIds = before.chapters.filter { it.mangaId == mangaId }.mapTo(mutableSetOf()) { it.id } val removedDownloadIds = before.downloads.filter { it.chapterId in chapterIds }.mapTo(mutableSetOf()) { it.id } val after = before.copy( mangas = before.mangas.filterNot { it.id == mangaId }, chapters = before.chapters.filterNot { it.id in chapterIds }, histories = before.histories.filterNot { it.mangaId == mangaId || it.chapterId in chapterIds }, updates = before.updates.filterNot { it.mangaId == mangaId || it.chapterId in chapterIds }, downloads = before.downloads.filterNot { it.id in removedDownloadIds }, tracks = before.tracks.filterNot { it.mangaId == mangaId }, trackSearches = before.trackSearches.filterNot { it.libraryId == mangaId }, pageCache = before.pageCache.filterNot { it.chapterId in chapterIds }, settings = before.settings.copy( sortChapterList = before.settings.sortChapterList?.filterNot { it.mangaId == mangaId }, chapterFilterDownloadedList = before.settings.chapterFilterDownloadedList?.filterNot { it.mangaId == mangaId }, chapterFilterUnreadList = before.settings.chapterFilterUnreadList?.filterNot { it.mangaId == mangaId }, chapterFilterBookmarkedList = before.settings.chapterFilterBookmarkedList?.filterNot { it.mangaId == mangaId }, chapterPageIndexList = before.settings.chapterPageIndexList?.filterNot { it.chapterId in chapterIds }, personalReaderModeList = before.settings.personalReaderModeList?.filterNot { it.mangaId == mangaId }, filterScanlatorList = before.settings.filterScanlatorList?.filterNot { it.mangaId == mangaId }, personalPageModeList = before.settings.personalPageModeList?.filterNot { it.mangaId == mangaId }, autoScrollPages = before.settings.autoScrollPages?.filterNot { it.mangaId == mangaId }, titleMetadata = before.settings.titleMetadata?.filterNot { it.mangaId == mangaId }, updateErrors = before.settings.updateErrors?.filterNot { it.mangaId == mangaId }, downloadQueueOrder = before.settings.downloadQueueOrder.filterNot { it in removedDownloadIds }, ), ) // replaceAll publishes the child and parent removals as one snapshot; sync callers run this in applyRemote. database.replaceAll(after, expectedSnapshot = before) } private fun toDbType(type: ItemType): DbItemType = when (type) { ItemType.Manga -> DbItemType.Manga ItemType.Anime -> DbItemType.Anime ItemType.Novel -> DbItemType.Novel }