package eu.friedcutlet.yokan.services.extensions import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.database.DbVideo import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.services.files.LocalArchiveService import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.files.resolveConfiguredLocalArchivePath import eu.friedcutlet.yokan.services.files.resolveLocalEpisodeVideo import eu.friedcutlet.yokan.services.runJoined import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext /** Reader extraction retains one owner, including local files and runtime cleanup. */ class ProfileReaderContent internal constructor( val profileId: ProfileId, private val database: YokanDatabase, private val runtimeFactory: ExtensionRuntimeFactory, private val chapterPages: ChapterPageResolver, private val files: LocalFileService, private val archives: LocalArchiveService, ownerScope: CoroutineScope, private val fileDispatcher: CoroutineDispatcher = Dispatchers.Default, private val isOwnerOpen: () -> Boolean = { true }, private val torrents: eu.friedcutlet.yokan.services.torrent.TorrentStreams? = null, ) { private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) private val job = SupervisorJob(ownerJob) private val scope = CoroutineScope(ownerScope.coroutineContext + job) internal val isAvailable: Boolean get() = ownerJob.isActive && job.isActive && isOwnerOpen() private fun ensureCurrent(callJob: Job) { callJob.ensureActive() ownerJob.ensureActive() job.ensureActive() if (!isOwnerOpen()) throw CancellationException("Reader owner is retiring.") } private suspend fun runOwned(action: suspend (Job) -> T): T { val caller = requireNotNull(currentCoroutineContext()[Job]) try { return scope.runJoined(admit = { ensureCurrent(caller) }) { call -> ensureCurrent(call) action(call).also { ensureCurrent(call) } } } finally { // Expired calls must not publish failures to a screen's error/fallback handlers either. ensureCurrent(caller) } } suspend fun pages(source: Source?, chapter: Chapter, forceRefresh: Boolean): List = runOwned { call -> val local = withContext(fileDispatcher) { localPages(source, chapter, call) } ensureCurrent(call) if (local.isNotEmpty()) local else { val titleSource = source ?: error("Source is unavailable") chapterPages.pages( chapter, titleSource.id, forceRefresh, onFallback = { ensureCurrent(call) ExtensionLogger.error(titleSource.name, "pageList", it) }, ensureRequestCurrent = { ensureCurrent(call) }, ) } } suspend fun headers(source: Source): Map = runOwned { call -> runtimeFactory.withSourceRuntime(database, source.id, onFallback = { ensureCurrent(call) ExtensionLogger.error(source.name, "headers", it) }) { runtime -> ensureCurrent(call) runtime.headers().also { ensureCurrent(call) } } } /** An extension failure never turns its episode HTML URL into a playable stream. Torrents play through TorrServer. */ suspend fun videos(source: Source?, chapter: Chapter): List = runOwned { call -> if (source == null && eu.friedcutlet.yokan.services.library.TorrentUtils.isTorrentLink(chapter.url)) { return@runOwned checkNotNull(torrents) { "Torrent streaming is unavailable" }.videos(chapter.url, chapter.name) .also { ensureCurrent(call) } } val local = withContext(fileDispatcher) { ensureCurrent(call) chapter.archivePath.ifBlank { if (source == null && !chapter.url.startsWith("http", true) && !chapter.url.startsWith("//")) chapter.url else "" }.takeIf(String::isNotBlank)?.let { stored -> files.prepare() resolveLocalEpisodeVideo(stored, files, database.settings()) ?.let { DbVideo(url = files.readableUrl(it), quality = "Downloaded", originalUrl = chapter.url) } } } ensureCurrent(call) if (local != null) listOf(local) else if (source == null) directEpisodeVideo(chapter) else { runtimeFactory.withSourceRuntime(database, source.id) { runtime -> ensureCurrent(call) runtime.videoList(chapter.url).also { ensureCurrent(call) } }.let { videos -> torrents?.expand(videos, chapter.name) ?: videos }.also { ensureCurrent(call) } } } suspend fun novelText(source: Source?, name: String, url: String): String = runOwned { call -> extractNovelText(source, name, url, call) } /** Parse while owned; the embedded-resource capability expires when this call finishes. */ internal suspend fun novelContent( source: Source?, name: String, chapter: Chapter, parse: suspend (ProfileNovelContent) -> T, ): T = runOwned { call -> val local = withContext(fileDispatcher) { ensureCurrent(call) chapter.archivePath.takeIf { it.contains(".epub", ignoreCase = true) }?.let { storedPath -> val settings = database.settings() ensureCurrent(call) val resolved = resolveConfiguredLocalArchivePath(storedPath, files, settings) ensureCurrent(call) val path = resolved.substringBefore('#') val index = resolved.substringAfter('#', "0").toIntOrNull() ?: 0 files.prepare() val href = archives.listEpubChaptersAsync(path).getOrNull(index)?.href ensureCurrent(call) val html = archives.readEpubChapterAsync(path, index) ensureCurrent(call) LocalNovelChapter(path, href, html) } } ensureCurrent(call) val downloaded = if (local == null && chapter.archivePath.isNotBlank()) withContext(fileDispatcher) { files.prepare() val resolved = resolveConfiguredLocalArchivePath(chapter.archivePath, files, database.settings()) val path = if (resolved.substringAfterLast('.').lowercase() in setOf("html", "xhtml", "txt")) resolved.takeIf(files::exists) else files.listFiles(resolved).firstOrNull { it.name.substringAfterLast('.').lowercase() in setOf("html", "xhtml", "txt") }?.path path?.let { files.readBytesAsync(it, 16L * 1024 * 1024).decodeToString() } } else null ensureCurrent(call) val html = local?.html?.takeIf(String::isNotBlank) ?: downloaded?.takeIf(String::isNotBlank) ?: extractNovelText(source, name, chapter.url, call) ensureCurrent(call) withContext(fileDispatcher) { ensureCurrent(call) parse(ProfileNovelContent(html, local?.href) { resourcePath -> ensureCurrent(call) if (local?.href == null) null else { archives.readEpubResourceAsync(local.path, resourcePath).also { ensureCurrent(call) } } }).also { ensureCurrent(call) } } } private suspend fun extractNovelText(source: Source?, name: String, url: String, call: Job): String { ensureCurrent(call) return if (source == null) url else { runtimeFactory.withSourceRuntime(database, source.id) { runtime -> ensureCurrent(call) val html = runtime.htmlContent(name, url) ensureCurrent(call) runtime.cleanHtmlContent(html).also { ensureCurrent(call) } } } } private data class LocalNovelChapter(val path: String, val href: String?, val html: String) private suspend fun localPages(source: Source?, chapter: Chapter, call: Job): List { ensureCurrent(call) if (chapter.archivePath.isBlank() && source != null) return emptyList() val storedPath = chapter.archivePath.ifBlank { chapter.url } if (storedPath.isBlank() || storedPath.startsWith("http", ignoreCase = true)) return emptyList() files.prepare() val settings = database.settings() ensureCurrent(call) val resolved = resolveConfiguredLocalArchivePath(storedPath, files, settings).substringBefore('#') ensureCurrent(call) val pages = archives.listPagesAsync(resolved) ensureCurrent(call) if (pages.isNotEmpty()) return pages val exists = files.exists(resolved) ensureCurrent(call) if (!exists) return emptyList() val url = files.readableUrl(resolved) return listOf(DbPageUrl(url = url, fileName = resolved.substringAfterLast('/'))) } internal suspend fun closeAndJoin() { job.cancel() withContext(NonCancellable) { job.join() } } } internal class ProfileNovelContent( val html: String, val chapterHref: String?, val readEmbeddedResource: suspend (String) -> ByteArray?, ) internal fun directEpisodeVideo(chapter: Chapter): List { val raw = chapter.url val absolute = when { raw.startsWith("http://", ignoreCase = true) -> raw raw.startsWith("https://", ignoreCase = true) -> raw raw.startsWith("//") -> "https:$raw" else -> return emptyList() } return listOf(DbVideo(url = absolute, quality = "Auto", originalUrl = absolute)) }