MigrationService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/migration/MigrationService.kt
1package eu.friedcutlet.yokan.services.migration23import eu.friedcutlet.yokan.data.SettingsStore4import eu.friedcutlet.yokan.data.YokanRepository5import eu.friedcutlet.yokan.database.YokanDatabase6import eu.friedcutlet.yokan.domain.Manga7import eu.friedcutlet.yokan.domain.Source8import eu.friedcutlet.yokan.domain.mergePrivateNotes9import eu.friedcutlet.yokan.services.catchingNonCancellation10import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory11import eu.friedcutlet.yokan.services.extensions.RemoteManga12import eu.friedcutlet.yokan.services.extensions.RemoteDetail13import eu.friedcutlet.yokan.services.extensions.withSourceRuntime14import eu.friedcutlet.yokan.services.library.withoutUpdateError15import eu.friedcutlet.yokan.services.logging.AppLogger16import kotlinx.coroutines.CoroutineScope17import kotlinx.coroutines.flow.MutableStateFlow18import kotlinx.coroutines.flow.StateFlow19import kotlinx.coroutines.flow.asStateFlow20import kotlinx.coroutines.launch21import kotlinx.coroutines.Job22import kotlinx.coroutines.CoroutineDispatcher23import kotlinx.coroutines.Dispatchers24import kotlinx.coroutines.currentCoroutineContext25import kotlinx.coroutines.isActive26import kotlinx.coroutines.ensureActive27import kotlinx.coroutines.flow.update2829/**30 * Moves library titles to another source. Single and mass migration share [migrate]; a mass run31 * lives in the app [scope], so it keeps going after its screen is left.32 */33class MigrationService(34 private val repository: YokanRepository,35 private val database: YokanDatabase,36 private val runtimeFactory: ExtensionRuntimeFactory,37 private val settings: SettingsStore,38 private val scope: CoroutineScope,39 private val searchLimits: MigrationSearchLimits = MigrationSearchLimits(),40 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,41) {42 private var job: Job? = null43 private val _progress = MutableStateFlow<MassMigrationProgress?>(null)4445 /** The latest mass run; stays at its final value until the next [start]. */46 val progress: StateFlow<MassMigrationProgress?> = _progress.asStateFlow()4748 /**49 * Fetches [candidate]'s detail from [destination] (which stores its chapters), copies read and50 * bookmark state where chapter names align, transfers categories, unfavorites [from] and51 * clears its update error. Returns the new title id, or null when the destination is no longer52 * installed or the fetch fails.53 */54 suspend fun migrate(from: Manga, destination: Source, candidate: RemoteManga): Long? = catchingNonCancellation {55 val detail = runtimeFactory.withSourceRuntime(database, destination.id) { it.detail(candidate.url) }56 migratePrepared(from, destination, detail)57 }.getOrNull()5859 /** The reviewed detail is reused; applying a proposal never performs a fresh network fetch. */60 private suspend fun migratePrepared(from: Manga, destination: Source, detail: RemoteDetail): Long? = catchingNonCancellation {61 val installed = repository.source(destination.id) ?: return@catchingNonCancellation null62 check(installed.isAdded && installed.isActive && installed.itemType == destination.itemType &&63 installed.name == destination.name && installed.lang == destination.lang && installed.baseUrl == destination.baseUrl &&64 installed.sourceCodeLanguage == destination.sourceCodeLanguage)65 val original = repository.manga(from.id) ?: return@catchingNonCancellation null66 check(original.favorite && original.link == from.link && original.sourceId == from.sourceId)67 currentCoroutineContext().ensureActive()68 val newManga = repository.upsertRemoteDetail(destination, detail, favorite = true)69 check(newManga.id != from.id)70 val oldChapters = repository.chapters(from.id)71 repository.chapters(newManga.id).forEach { newChapter ->72 val match = oldChapters.firstOrNull { old ->73 old.name.equals(newChapter.name, ignoreCase = true) ||74 old.url.endsWith(newChapter.url.substringAfterLast('/'))75 } ?: return@forEach76 if (match.isRead || match.isBookmarked) {77 repository.setChaptersRead(setOf(newChapter.id), match.isRead, match.lastPageRead.takeIf { it.isNotBlank() }, 0)78 repository.setChaptersBookmarked(setOf(newChapter.id), match.isBookmarked)79 }80 }81 val oldNote = repository.manga(from.id)?.privateNote.orEmpty()82 checkNotNull(repository.setMangaPrivateNote(newManga.id, mergePrivateNotes(newManga.privateNote, oldNote)))83 repository.setMangaCategories(newManga.id, from.categories)84 settings.updateDb { it.withoutUpdateError(from.id) }85 currentCoroutineContext().ensureActive()86 repository.setMangaFavorite(from.id, false)87 newManga.id88 }.onFailure { AppLogger.warn("[migration] title ${from.id} to ${destination.name} failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }89 .getOrNull()9091 /** Starts discovery only. Re-entering the same route attaches to its existing run. */92 fun start(sourceId: Long, destinationIds: List<Long>, mangaIds: List<Long>): Boolean {93 val ids = destinationIds.distinct()94 val titles = mangaIds.distinct()95 val current = _progress.value96 if (current?.sourceId == sourceId && current.destinationIds == ids && current.mangaIds == titles) return true97 if (current?.running == true || current?.phase == MigrationPhase.Reviewing || job?.isActive == true) return false98 val source = repository.source(sourceId) ?: return false99 val destinations = ids.mapNotNull(repository::source)100 if (destinations.size != ids.size || destinations.isEmpty() || destinations.any {101 it.id == source.id || !it.isAdded || !it.isActive || it.itemType != source.itemType102 }) return false103 val targets = titles.mapNotNull(repository::manga).filter {104 it.favorite && it.itemType == source.itemType && (it.sourceId == source.id ||105 (it.sourceId == null && it.source == source.name && (it.lang.isBlank() || it.lang == source.lang)))106 }107 val started = MassMigrationProgress(sourceId, ids, titles, targets.map {108 MigrationReviewItem(it, repository.chapters(it.id).size)109 }, MigrationPhase.Searching)110 if (!_progress.compareAndSet(current, started)) return false111 job = scope.launch(workDispatcher) {112 try {113 val planner = MigrationPlanner(database, runtimeFactory, searchLimits)114 for (target in targets) discover(target.id, destinations, planner)115 _progress.update { it?.copy(phase = MigrationPhase.Reviewing) }116 } finally {117 if (!currentCoroutineContext().isActive) _progress.update { it?.copy(phase = MigrationPhase.Cancelled) }118 }119 }120 return true121 }122123 private suspend fun discover(mangaId: Long, destinations: List<Source>, planner: MigrationPlanner = MigrationPlanner(database, runtimeFactory, searchLimits)) {124 val original = _progress.value?.items?.firstOrNull { it.original.id == mangaId }?.original ?: return125 val results = planner.discover(original, destinations)126 val candidates = rankedMigrationCandidates(results)127 updateItem(mangaId) { item -> item.copy(128 sources = results, candidates = candidates, selected = candidates.firstOrNull()?.key,129 status = when {130 candidates.isNotEmpty() -> MigrationItemStatus.Ready131 results.any { it.issues.isNotEmpty() } -> MigrationItemStatus.Failed132 else -> MigrationItemStatus.Unmatched133 },134 ) }135 }136137 fun select(mangaId: Long, key: MigrationCandidateKey?) {138 _progress.update { run ->139 if (run?.phase != MigrationPhase.Reviewing) run else run.copy(items = run.items.map { item ->140 if (item.original.id != mangaId || item.status == MigrationItemStatus.Migrated || item.status == MigrationItemStatus.Pending ||141 (key != null && item.candidates.none { it.key == key })) item142 else item.copy(selected = key, status = if (key == null) MigrationItemStatus.Skipped else MigrationItemStatus.Ready)143 })144 }145 }146147 /** Retry is explicit and refreshes search/details; other reviewed rows stay intact. */148 fun retry(mangaId: Long) {149 val current = _progress.value ?: return150 if (current.running || job?.isActive == true) return151 val item = current.items.firstOrNull { it.original.id == mangaId } ?: return152 if (item.status == MigrationItemStatus.Migrated) return153 val destinations = current.destinationIds.mapNotNull { id -> repository.source(id)154 ?: current.items.flatMap { it.sources }.firstOrNull { it.source.id == id }?.source }155 if (!_progress.compareAndSet(current, current.copy(phase = MigrationPhase.Searching,156 items = current.items.map { if (it.original.id == mangaId) it.copy(status = MigrationItemStatus.Pending, selected = null) else it }))) return157 job = scope.launch(workDispatcher) {158 try {159 discover(mangaId, destinations)160 _progress.update { it?.copy(phase = MigrationPhase.Reviewing) }161 } finally {162 if (!currentCoroutineContext().isActive) _progress.update { it?.copy(phase = MigrationPhase.Cancelled) }163 }164 }165 }166167 /** Called only from review. Incomplete source results stay visible beside the chosen winner. */168 fun commitSelected() {169 val current = _progress.value ?: return170 if (current.phase != MigrationPhase.Reviewing || current.selectedCount == 0 || current.items.any { it.status == MigrationItemStatus.Pending } || job?.isActive == true) return171 if (!_progress.compareAndSet(current, current.copy(phase = MigrationPhase.Migrating))) return172 job = scope.launch(workDispatcher) {173 try {174 for (item in current.items.filter { it.status == MigrationItemStatus.Ready && it.selected != null }) {175 currentCoroutineContext().ensureActive()176 val candidate = item.candidates.firstOrNull { it.key == item.selected } ?: continue177 val migrated = migratePrepared(item.original, candidate.source, candidate.detail) != null178 updateItem(item.original.id) { it.copy(status = if (migrated) MigrationItemStatus.Migrated else MigrationItemStatus.Failed) }179 }180 _progress.update { it?.copy(phase = MigrationPhase.Completed) }181 } finally {182 if (!currentCoroutineContext().isActive) _progress.update { it?.copy(phase = MigrationPhase.Cancelled) }183 }184 }185 }186187 fun cancel() {188 if (job?.isActive == true) job?.cancel()189 else _progress.update { it?.copy(phase = MigrationPhase.Cancelled) }190 }191192 private fun updateItem(mangaId: Long, transform: (MigrationReviewItem) -> MigrationReviewItem) {193 _progress.update { run -> run?.copy(items = run.items.map { if (it.original.id == mangaId) transform(it) else it }) }194 }195}196