Yokan / rebuild
Course 1 8624561

ProfileReaderContent.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/ProfileReaderContent.kt

implementation222 lines
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.database.DbPageUrl5import eu.friedcutlet.yokan.database.DbVideo6import eu.friedcutlet.yokan.database.YokanDatabase7import eu.friedcutlet.yokan.domain.Chapter8import eu.friedcutlet.yokan.domain.Source9import eu.friedcutlet.yokan.services.files.LocalArchiveService10import eu.friedcutlet.yokan.services.files.LocalFileService11import eu.friedcutlet.yokan.services.files.resolveConfiguredLocalArchivePath12import eu.friedcutlet.yokan.services.files.resolveLocalEpisodeVideo13import eu.friedcutlet.yokan.services.runJoined14import kotlinx.coroutines.CancellationException15import kotlinx.coroutines.CoroutineDispatcher16import kotlinx.coroutines.CoroutineScope17import kotlinx.coroutines.Dispatchers18import kotlinx.coroutines.Job19import kotlinx.coroutines.NonCancellable20import kotlinx.coroutines.SupervisorJob21import kotlinx.coroutines.currentCoroutineContext22import kotlinx.coroutines.ensureActive23import kotlinx.coroutines.withContext2425/** Reader extraction retains one owner, including local files and runtime cleanup. */26class ProfileReaderContent internal constructor(27    val profileId: ProfileId,28    private val database: YokanDatabase,29    private val runtimeFactory: ExtensionRuntimeFactory,30    private val chapterPages: ChapterPageResolver,31    private val files: LocalFileService,32    private val archives: LocalArchiveService,33    ownerScope: CoroutineScope,34    private val fileDispatcher: CoroutineDispatcher = Dispatchers.Default,35    private val isOwnerOpen: () -> Boolean = { true },36    private val torrents: eu.friedcutlet.yokan.services.torrent.TorrentStreams? = null,37) {38    private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job])39    private val job = SupervisorJob(ownerJob)40    private val scope = CoroutineScope(ownerScope.coroutineContext + job)4142    internal val isAvailable: Boolean43        get() = ownerJob.isActive && job.isActive && isOwnerOpen()4445    private fun ensureCurrent(callJob: Job) {46        callJob.ensureActive()47        ownerJob.ensureActive()48        job.ensureActive()49        if (!isOwnerOpen()) throw CancellationException("Reader owner is retiring.")50    }5152    private suspend fun <T> runOwned(action: suspend (Job) -> T): T {53        val caller = requireNotNull(currentCoroutineContext()[Job])54        try {55            return scope.runJoined(admit = { ensureCurrent(caller) }) { call ->56                ensureCurrent(call)57                action(call).also { ensureCurrent(call) }58            }59        } finally {60            // Expired calls must not publish failures to a screen's error/fallback handlers either.61            ensureCurrent(caller)62        }63    }6465    suspend fun pages(source: Source?, chapter: Chapter, forceRefresh: Boolean): List<DbPageUrl> = runOwned { call ->66        val local = withContext(fileDispatcher) { localPages(source, chapter, call) }67        ensureCurrent(call)68        if (local.isNotEmpty()) local else {69            val titleSource = source ?: error("Source is unavailable")70            chapterPages.pages(71                chapter, titleSource.id, forceRefresh,72                onFallback = {73                    ensureCurrent(call)74                    ExtensionLogger.error(titleSource.name, "pageList", it)75                },76                ensureRequestCurrent = { ensureCurrent(call) },77            )78        }79    }8081    suspend fun headers(source: Source): Map<String, String> = runOwned { call ->82        runtimeFactory.withSourceRuntime(database, source.id, onFallback = {83            ensureCurrent(call)84            ExtensionLogger.error(source.name, "headers", it)85        }) { runtime ->86            ensureCurrent(call)87            runtime.headers().also { ensureCurrent(call) }88        }89    }9091    /** An extension failure never turns its episode HTML URL into a playable stream. Torrents play through TorrServer. */92    suspend fun videos(source: Source?, chapter: Chapter): List<DbVideo> = runOwned { call ->93        if (source == null && eu.friedcutlet.yokan.services.library.TorrentUtils.isTorrentLink(chapter.url)) {94            return@runOwned checkNotNull(torrents) { "Torrent streaming is unavailable" }.videos(chapter.url, chapter.name)95                .also { ensureCurrent(call) }96        }97        val local = withContext(fileDispatcher) {98            ensureCurrent(call)99            chapter.archivePath.ifBlank {100                if (source == null && !chapter.url.startsWith("http", true) && !chapter.url.startsWith("//")) chapter.url else ""101            }.takeIf(String::isNotBlank)?.let { stored ->102                files.prepare()103                resolveLocalEpisodeVideo(stored, files, database.settings())104                    ?.let { DbVideo(url = files.readableUrl(it), quality = "Downloaded", originalUrl = chapter.url) }105            }106        }107        ensureCurrent(call)108        if (local != null) listOf(local) else if (source == null) directEpisodeVideo(chapter) else {109            runtimeFactory.withSourceRuntime(database, source.id) { runtime ->110                ensureCurrent(call)111                runtime.videoList(chapter.url).also { ensureCurrent(call) }112            }.let { videos -> torrents?.expand(videos, chapter.name) ?: videos }.also { ensureCurrent(call) }113        }114    }115116    suspend fun novelText(source: Source?, name: String, url: String): String = runOwned { call ->117        extractNovelText(source, name, url, call)118    }119120    /** Parse while owned; the embedded-resource capability expires when this call finishes. */121    internal suspend fun <T> novelContent(122        source: Source?,123        name: String,124        chapter: Chapter,125        parse: suspend (ProfileNovelContent) -> T,126    ): T = runOwned { call ->127        val local = withContext(fileDispatcher) {128            ensureCurrent(call)129            chapter.archivePath.takeIf { it.contains(".epub", ignoreCase = true) }?.let { storedPath ->130                val settings = database.settings()131                ensureCurrent(call)132                val resolved = resolveConfiguredLocalArchivePath(storedPath, files, settings)133                ensureCurrent(call)134                val path = resolved.substringBefore('#')135                val index = resolved.substringAfter('#', "0").toIntOrNull() ?: 0136                files.prepare()137                val href = archives.listEpubChaptersAsync(path).getOrNull(index)?.href138                ensureCurrent(call)139                val html = archives.readEpubChapterAsync(path, index)140                ensureCurrent(call)141                LocalNovelChapter(path, href, html)142            }143        }144        ensureCurrent(call)145        val downloaded = if (local == null && chapter.archivePath.isNotBlank()) withContext(fileDispatcher) {146            files.prepare()147            val resolved = resolveConfiguredLocalArchivePath(chapter.archivePath, files, database.settings())148            val path = if (resolved.substringAfterLast('.').lowercase() in setOf("html", "xhtml", "txt")) resolved.takeIf(files::exists)149                else files.listFiles(resolved).firstOrNull { it.name.substringAfterLast('.').lowercase() in setOf("html", "xhtml", "txt") }?.path150            path?.let { files.readBytesAsync(it, 16L * 1024 * 1024).decodeToString() }151        } else null152        ensureCurrent(call)153        val html = local?.html?.takeIf(String::isNotBlank) ?: downloaded?.takeIf(String::isNotBlank)154            ?: extractNovelText(source, name, chapter.url, call)155        ensureCurrent(call)156        withContext(fileDispatcher) {157            ensureCurrent(call)158            parse(ProfileNovelContent(html, local?.href) { resourcePath ->159                ensureCurrent(call)160                if (local?.href == null) null else {161                    archives.readEpubResourceAsync(local.path, resourcePath).also { ensureCurrent(call) }162                }163            }).also { ensureCurrent(call) }164        }165    }166167    private suspend fun extractNovelText(source: Source?, name: String, url: String, call: Job): String {168        ensureCurrent(call)169        return if (source == null) url else {170            runtimeFactory.withSourceRuntime(database, source.id) { runtime ->171                ensureCurrent(call)172                val html = runtime.htmlContent(name, url)173                ensureCurrent(call)174                runtime.cleanHtmlContent(html).also { ensureCurrent(call) }175            }176        }177    }178179    private data class LocalNovelChapter(val path: String, val href: String?, val html: String)180181    private suspend fun localPages(source: Source?, chapter: Chapter, call: Job): List<DbPageUrl> {182        ensureCurrent(call)183        if (chapter.archivePath.isBlank() && source != null) return emptyList()184        val storedPath = chapter.archivePath.ifBlank { chapter.url }185        if (storedPath.isBlank() || storedPath.startsWith("http", ignoreCase = true)) return emptyList()186        files.prepare()187        val settings = database.settings()188        ensureCurrent(call)189        val resolved = resolveConfiguredLocalArchivePath(storedPath, files, settings).substringBefore('#')190        ensureCurrent(call)191        val pages = archives.listPagesAsync(resolved)192        ensureCurrent(call)193        if (pages.isNotEmpty()) return pages194        val exists = files.exists(resolved)195        ensureCurrent(call)196        if (!exists) return emptyList()197        val url = files.readableUrl(resolved)198        return listOf(DbPageUrl(url = url, fileName = resolved.substringAfterLast('/')))199    }200201    internal suspend fun closeAndJoin() {202        job.cancel()203        withContext(NonCancellable) { job.join() }204    }205}206207internal class ProfileNovelContent(208    val html: String,209    val chapterHref: String?,210    val readEmbeddedResource: suspend (String) -> ByteArray?,211)212213internal fun directEpisodeVideo(chapter: Chapter): List<DbVideo> {214    val raw = chapter.url215    val absolute = when {216        raw.startsWith("http://", ignoreCase = true) -> raw217        raw.startsWith("https://", ignoreCase = true) -> raw218        raw.startsWith("//") -> "https:$raw"219        else -> return emptyList()220    }221    return listOf(DbVideo(url = absolute, quality = "Auto", originalUrl = absolute))222}223

Search chapters, reference and source filenames.