package eu.friedcutlet.yokan.services.extensions import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.services.files.JvmLocalFileService import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService import eu.friedcutlet.yokan.services.http.EnhancedHttpService import eu.friedcutlet.yokan.services.http.cookies.CookieJar import eu.friedcutlet.yokan.services.http.createPlatformHttpService import eu.friedcutlet.yokan.services.webview.WebViewRequest import eu.friedcutlet.yokan.services.webview.createPlatformWebViewService import java.nio.file.Path import kotlin.test.Test import org.junit.Assume.assumeTrue import kotlin.test.fail import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeoutOrNull import eu.friedcutlet.yokan.services.extensions.js.JavaScriptExtensionRuntimeService /** * Live end-to-end flow for repository extensions, exercised through the real * QuickJS runtime and real OkHttp network stack. For each selected source it * runs: popular -> latest (if supported) -> search -> detail -> page/video links * (validating the returned links), and reports Cloudflare handling. * * Opt-in and network-bound, so it never runs in the default suite. Enable with: * * ./gradlew :composeApp:desktopTest --tests '*ExtensionLiveFlowTest*' \ * -Dyokan.generated.repository=/abs/path/build/repository/anime_index.json \ * -Dyokan.live.extensions=all # or sample:12, or a comma list of names/ids * -Dyokan.live.parallelism=8 # source flows; QuickJS itself is globally bounded * -Dyokan.live.itemType=anime # anime (default), manga, or novel * -Dyokan.live.resolveCloudflare=true # defaults off for all-source audits * -Dyokan.live.fullFlow=true # all-mode defaults to popular-page smoke coverage * * The test fails only on genuine host/runtime defects (missing globals, QuickJS * exceptions, unported bridge calls). External outcomes — network errors, * geo-blocks, and Cloudflare challenges — are classified and reported, not * failed, because they are properties of the live site, not of Yokan. */ class ExtensionLiveFlowTest { @Test fun runsLiveFlowForSelectedExtensions() { val selection = System.getProperty(SelectionProperty)?.trim().orEmpty() val repoProperty = System.getProperty(RepositoryProperty)?.trim().orEmpty() assumeTrue( "set -D$SelectionProperty and -D$RepositoryProperty to run.", selection.isNotBlank() && repoProperty.isNotBlank(), ) val repositoryPath = Path.of(repoProperty).toAbsolutePath().normalize() val repositoryUrl = repositoryPath.toUri().toString() val itemType = when (System.getProperty(ItemTypeProperty)?.trim()?.lowercase()) { null, "", "anime" -> DbItemType.Anime "manga" -> DbItemType.Manga "novel" -> DbItemType.Novel else -> error("$ItemTypeProperty must be anime, manga, or novel.") } val catalogDatabase = InMemoryYokanDatabase() val catalogCookieJar = CookieJar(catalogDatabase) val catalogHttp = EnhancedHttpService(createPlatformHttpService(), catalogDatabase, catalogCookieJar) val files = JvmLocalFileService( downloadRoot = repositoryPath.parent.toString(), backupRoot = repositoryPath.parent.toString(), cacheRoot = repositoryPath.parent.toString(), ) val catalog = HttpSourceCatalogService(catalogHttp, files) val allSources = runBlocking { catalog.fetchSources(repositoryUrl, itemType) } val selected = selectSources(allSources, selection) check(selected.isNotEmpty()) { "No sources matched selection '$selection' (of ${allSources.size})." } val parallelism = System.getProperty(ParallelismProperty)?.toIntOrNull()?.coerceIn(1, 8) ?: 8 val resolveCloudflare = System.getProperty(ResolveCloudflareProperty)?.toBooleanStrictOrNull() ?: !selection.equals("all", ignoreCase = true) val completeFlow = System.getProperty(FullFlowProperty)?.toBooleanStrictOrNull() ?: !selection.equals("all", ignoreCase = true) println( "[live-flow] running ${selected.size} source(s) with parallelism $parallelism " + "mode=${if (completeFlow) "complete" else "popular-smoke"} from $repositoryUrl", ) val prepared = selected.map { source -> val payload = runBlocking { catalog.fetchSourcePayload(source) } source to payload } val dispatcher = Dispatchers.IO.limitedParallelism(parallelism) val reports = runBlocking { prepared.map { (source, payload) -> async(dispatcher) { if (payload == null) { FlowReport(source.name).apply { hostError = "missing payload" } } else { runFlow(source.copy(sourceCode = payload.decodeToString()), resolveCloudflare, completeFlow) } } }.awaitAll() } reports.forEachIndexed { index, report -> println("[live-flow] (${index + 1}/${selected.size}) ${report.render()}") } val hostFailures = reports.filter { it.hostError != null } println(summary(reports)) if (hostFailures.isNotEmpty()) { fail( "Host/runtime defects in ${hostFailures.size} source(s):\n" + hostFailures.joinToString("\n") { " ${it.name}: ${it.hostError}" }, ) } } private fun runFlow(source: DbSource, resolveCloudflare: Boolean, completeFlow: Boolean): FlowReport { val database = InMemoryYokanDatabase() val cookieJar = CookieJar(database) val http = EnhancedHttpService(createPlatformHttpService(), database, cookieJar) val webView = createPlatformWebViewService(http, cookieJar, createPlatformLocalFileService()) val report = FlowReport(source.name) val runtime = JavaScriptExtensionRuntimeService(source = source, http = http, database = database) try { // 1. Popular (with a Cloudflare cookie-refresh retry through the WebView resolver). val popular = step(report, "popular") { runtime.popular(1) } if (resolveCloudflare && report.cloudflare && popular == null) { report.cloudflareResolveAttempted = true val resolved = runCatching { runBlocking { webView.resolveCloudflare(WebViewRequest(url = source.baseUrl, title = source.name)) withTimeoutOrNull(StepTimeoutMs) { runtime.popular(1) } } }.getOrNull() report.cloudflareResolved = resolved != null && resolved.items.isNotEmpty() } val listing = popular ?: (if (report.cloudflareResolved) runCatching { runBlocking { runtime.popular(1) } }.getOrNull() else null) report.popularCount = listing?.items?.size ?: report.popularCount if (!completeFlow) return report // 2. Latest (only when advertised). if (source.supportLatest == true || runCatching { runBlocking { runtime.supportsLatest() } }.getOrDefault(false)) { val latest = step(report, "latest") { runtime.latest(1) } report.latestCount = latest?.items?.size ?: -1 } else { report.latestCount = -2 // not supported } // 3. Search — reuse a popular title so the query is meaningful. val query = listing?.items?.firstOrNull()?.title?.split(Regex("\\s+"))?.firstOrNull()?.takeIf { it.length > 1 } ?: "a" val search = step(report, "search") { runtime.search(query, 1, runtime.filterList()) } report.searchCount = search?.items?.size ?: report.searchCount // 4. Detail of the first popular (or search) item. val entry = listing?.items?.firstOrNull() ?: search?.items?.firstOrNull() if (entry != null) { val detail = step(report, "detail") { runtime.detail(entry.url) } if (detail != null) { report.detailTitle = detail.title report.chapterCount = detail.chapters.size // 5. Page list / video list for the first chapter/episode; validate links. val chapter = detail.chapters.firstOrNull() if (chapter != null) { if (source.itemType == DbItemType.Anime) { val videos = step(report, "videoList") { runtime.videoList(chapter.url) } report.linkCount = videos?.size ?: -1 report.validLinks = videos?.count { isValidLink(it.url) } ?: 0 report.firstLink = videos?.firstOrNull()?.url } else { val pages = step(report, "pageList") { runtime.pageList(chapter.url) } report.linkCount = pages?.size ?: -1 report.validLinks = pages?.count { isValidLink(it.url) } ?: 0 report.firstLink = pages?.firstOrNull()?.url } } } } } finally { runtime.dispose() } return report } /** Run one flow step; classify host defects vs external failures; note Cloudflare. */ private fun step(report: FlowReport, name: String, block: suspend () -> T): T? { return try { runBlocking { withTimeout(StepTimeoutMs) { block() } } } catch (error: Throwable) { val message = (generateSequence(error) { it.cause }.lastOrNull()?.message ?: error.message).orEmpty() if (message.contains("stack overflow", ignoreCase = true)) { println("[live-flow] ${report.name} $name stack trace:\n${error.stackTraceToString()}") } if (isCloudflare(message)) { report.cloudflare = true report.notes += "$name: cloudflare" } else if (isHostDefect(message)) { report.hostError = "$name: ${message.take(160)}" } else { report.notes += "$name: ${message.take(80)}" } null } } private fun selectSources(sources: List, selection: String): List = when { selection.equals("all", ignoreCase = true) -> sources selection.startsWith("sample:", ignoreCase = true) -> { val n = selection.substringAfter(":").toIntOrNull() ?: 12 // Spread the sample across the catalog rather than taking a contiguous block. val stride = (sources.size / n).coerceAtLeast(1) sources.filterIndexed { i, _ -> i % stride == 0 }.take(n) } else -> { val tokens = selection.split(",").map { it.trim().lowercase() }.filter { it.isNotEmpty() }.toSet() sources.filter { it.name.lowercase() in tokens || it.id.toString() in tokens } } } private fun summary(reports: List): String { val popular = reports.count { it.popularCount > 0 } val search = reports.count { it.searchCount > 0 } val detail = reports.count { it.detailTitle != null } val links = reports.count { it.validLinks > 0 } val cloudflare = reports.count { it.cloudflare } val cfResolved = reports.count { it.cloudflareResolved } val hostErrors = reports.count { it.hostError != null } return buildString { appendLine("[live-flow] summary of ${reports.size} source(s):") appendLine(" popular>0: $popular") appendLine(" search>0: $search") appendLine(" detail ok: $detail") appendLine(" video/page links>0: $links") appendLine(" cloudflare detected: $cloudflare (resolved via WebView: $cfResolved)") appendLine(" host/runtime defects: $hostErrors") } } private companion object { const val SelectionProperty = "yokan.live.extensions" const val RepositoryProperty = "yokan.generated.repository" const val ItemTypeProperty = "yokan.live.itemType" const val ParallelismProperty = "yokan.live.parallelism" const val ResolveCloudflareProperty = "yokan.live.resolveCloudflare" const val FullFlowProperty = "yokan.live.fullFlow" const val StepTimeoutMs = 30_000L fun isValidLink(url: String): Boolean { val trimmed = url.trim() if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return false val host = trimmed.removePrefix("https://").removePrefix("http://").substringBefore("/").substringBefore("?") return host.contains(".") && host.length > 3 } fun isCloudflare(message: String): Boolean { val lower = message.lowercase() return "cloudflare" in lower || "anti-bot" in lower || "just a moment" in lower || "challenge" in lower || "http 403" in lower || "http 503" in lower || "ddos-guard" in lower } fun isHostDefect(message: String): Boolean { val lower = message.lowercase() if (isCloudflare(message)) return false // Network/transport failures are external, not host defects. if ("unknownhost" in lower || "sslhandshake" in lower || "connect" in lower || "timeout" in lower || "timed out" in lower || "closedbytechannel" in lower || "econnreset" in lower || "no route" in lower || "interrupted" in lower ) return false return "not a function" in lower || "is not defined" in lower || "no setter" in lower || "quickjsexception" in lower || "not a constructor" in lower || "cannot read prop" in lower || "not implemented" in lower || "bridge channel" in lower || "undefined is not" in lower || "not iterable" in lower || "is not an object" in lower || "is undefined" in lower || "stack overflow" in lower || "syntaxerror" in lower || "unexpected token" in lower || "redeclaration of" in lower || "invalid property name" in lower } } private class FlowReport(val name: String) { var popularCount = -1 var latestCount = -3 // -3 unrun, -2 unsupported, -1 error, >=0 count var searchCount = -1 var detailTitle: String? = null var chapterCount = -1 var linkCount = -1 var validLinks = 0 var firstLink: String? = null var cloudflare = false var cloudflareResolveAttempted = false var cloudflareResolved = false var hostError: String? = null val notes = mutableListOf() fun render(): String { val latest = when (latestCount) { -3 -> "-"; -2 -> "n/a"; -1 -> "err"; else -> "$latestCount" } val cf = when { cloudflareResolved -> "cf:resolved" cloudflareResolveAttempted -> "cf:unresolved" cloudflare -> "cf:detected" else -> "cf:none" } val link = firstLink?.let { " first=${it.take(60)}" } ?: "" val err = hostError?.let { " HOST-ERROR[$it]" } ?: "" val note = if (notes.isEmpty()) "" else " notes[${notes.joinToString("; ")}]" return "$name: popular=$popularCount latest=$latest search=$searchCount " + "detail=${detailTitle?.take(24) ?: "-"} chapters=$chapterCount links=$validLinks/$linkCount $cf$link$err$note" } } }