package eu.friedcutlet.yokan.services.extensions.js import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbVideo import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService import eu.friedcutlet.yokan.services.extensions.RemoteDetail import eu.friedcutlet.yokan.services.extensions.SourceFilter import eu.friedcutlet.yokan.services.extensions.SourceListing import eu.friedcutlet.yokan.services.extensions.SourcePreferenceValue import eu.friedcutlet.yokan.services.files.LocalArchiveService import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.media.AnimeExtractorService import eu.friedcutlet.yokan.services.webview.WebViewService import eu.friedcutlet.yokan.util.nowMillis import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.intOrNull private val IsoDatePattern = Regex("(\\d{4})-(\\d{1,2})-(\\d{1,2})") private val DigitsPattern = Regex("\\d+") private val RelativeDatePattern = Regex("(\\d+)\\s*(second|minute|hour|day|week|month|year)s?\\s*ago") private val NonLetterPattern = Regex("[^a-z]+") /** * Runtime for Mangayomi-style JavaScript extensions. The extension is evaluated once per runtime * on top of [javaScriptBootstrap]; [JavaScriptHost] owns the engine and its threading. */ class JavaScriptExtensionRuntimeService( override val source: DbSource, http: HttpService, database: YokanDatabase? = null, engineFactory: (JavaScriptMessageBridge) -> JavaScriptEngine = ::createJavaScriptEngine, private val archives: LocalArchiveService? = null, private val webView: WebViewService? = null, private val animeExtractors: List = emptyList(), ) : ExtensionRuntimeService { private val host = JavaScriptHost( source = source, http = http, database = database, engineFactory = engineFactory, boot = { engine -> engine.evaluate(javaScriptBootstrap(source)) // QuickJS accepts the extension's modern ECMAScript directly. engine.evaluate(synchronousJavaScriptSource(source.sourceCode)) engine.evaluate("var extention = new DefaultExtension();") }, channels = ::extensionChannel, ) override suspend fun supportsLatest(): Boolean = catchingNonCancellation { callJson("extention.supportsLatest").primitiveOrNull()?.booleanOrNull } .getOrNull() ?: (source.supportLatest == true) override fun dispose() = host.close() override suspend fun headers(): Map = catchingNonCancellation { headersFromJsonElement(callJson("extention.getHeaders(${source.baseUrl.quoted()})")) }.getOrElse { parseHeaders(source.headers) } override suspend fun popular(page: Int): SourceListing = listingFromJson(callJson("extention.getPopular($page)")) override suspend fun latest(page: Int): SourceListing = listingFromJson(callJson("extention.getLatestUpdates($page)")) override suspend fun search(query: String, page: Int, filters: List): SourceListing = listingFromJson( callJson("extention.search(${query.quoted()}, $page, ${sourceFiltersToJson(filters)})"), ) override suspend fun detail(url: String): RemoteDetail { val detail = callJson("extention.getDetail(${url.quoted()})") if (!detail.isSeasonsDetail()) return remoteDetailFromJson(detail) // Optional `getSeasonList(url)`; otherwise inline `seasons` from the detail response. val listed = callJson("typeof extention.getSeasonList === 'function'").primitiveOrNull()?.booleanOrNull == true return remoteDetailFromJson(detail, seasonsOverride = if (listed) seasonListFromJson(callJson("extention.getSeasonList(${url.quoted()})")) else null) } override suspend fun related(url: String): eu.friedcutlet.yokan.services.extensions.SourceRelations { val supported = callJson("typeof extention.getRelated === 'function'").primitiveOrNull()?.booleanOrNull == true if (!supported) return eu.friedcutlet.yokan.services.extensions.SourceRelations(false) return sourceRelationsFromJson(callJson("extention.getRelated(${url.quoted()})"), source.baseUrl) } override suspend fun pageList(url: String): List = callJson("extention.getPageList(${url.quoted()})").arrayOrEmpty().mapNotNull(::pageUrlFromJson) override suspend fun videoList(url: String): List = callJson("extention.getVideoList(${url.quoted()})").arrayOrEmpty().mapNotNull(::videoFromJson) override suspend fun htmlContent(name: String, url: String): String = callJson("extention.getHtmlContent(${name.quoted()}, ${url.quoted()})").primitiveOrNull()?.contentOrNull.orEmpty() override suspend fun cleanHtmlContent(html: String): String = callJson("extention.cleanHtmlContent(${html.quoted()})").primitiveOrNull()?.contentOrNull ?: html override suspend fun filterList(): List = catchingNonCancellation { filtersFromJson(callJson("extention.getFilterList()")) }.getOrElse { filtersFromJson(source.filterList) } override suspend fun sourcePreferences(): List = catchingNonCancellation { sourcePreferencesFromJson(callJson("extention.getSourcePreferences()")) }.getOrElse { sourcePreferencesFromJson(source.preferenceList) } private suspend fun callJson(expression: String): JsonElement { repeat(3) { attempt -> try { return callJsonOnce(expression) } catch (error: Throwable) { if (attempt >= 2 || !error.isRecoverableQuickJsFailure()) throw error } } error("Unreachable") } private suspend fun callJsonOnce(expression: String): JsonElement { // Parse on the engine's background lane too; listings can be large. val result = host.call { engine -> val raw = engine.evaluate( """ var __yokanValue = $expression; if (__yokanValue != null && typeof __yokanValue.then === "function") { throw new Error( "Extension methods must return synchronously; Yokan's Client APIs already return completed values." ); } JSON.stringify(__yokanValue === undefined ? null : __yokanValue); """.trimIndent(), ) if (raw.isBlank()) null else parseJsonElement(raw) ?: JsonNull } return result ?: throw IllegalStateException("JavaScript call returned no result: $expression") } private fun Throwable.isRecoverableQuickJsFailure(): Boolean { val detail = generateSequence(this) { it.cause } .joinToString(" ") { it.message.orEmpty() } .lowercase() return "stack overflow" in detail || "redeclaration of" in detail } /** Mangayomi-specific bridge channels; shared ones are answered by [JavaScriptHost]. */ private fun extensionChannel(channel: String, payload: String): String? = when (channel) { "parseDates" -> parseDatesBridge(payload) "xpathFirst", "xpathAll" -> xpathBridge(channel, payload) "evaluateJavascriptViaWebview" -> evaluateJavascriptViaWebview(payload) "parseEpub" -> parseEpubBridge(payload) "parseEpubChapter" -> parseEpubChapterBridge(payload) "cryptoAes" -> CryptoBridge.aes(payload) "cryptoAesGcm" -> CryptoBridge.aesGcm(payload) "cryptoDigest" -> CryptoBridge.digest(payload) "cryptoBase64" -> CryptoBridge.base64(payload) "cryptoHmac" -> CryptoBridge.hmac(payload) "cryptoDes" -> CryptoBridge.tripleDes(payload) "extractVideo" -> extractVideoBridge(payload) else -> null } private fun parseDatesBridge(payload: String): String { val args = payloadArray(payload) val rawDates = args.getOrNull(0) ?.arrayOrEmpty() ?.mapNotNull { it.primitiveOrNull()?.contentOrNull } .orEmpty() val format = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty() return buildJsonArray { rawDates.forEach { add(JsonPrimitive(coerceDateToMillis(it, format))) } }.toString() } private fun xpathBridge(channel: String, payload: String): String { val args = payloadArray(payload) val html = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty() val expression = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty() val matches = HtmlXPathMatcher.match(html, expression) return if (channel == "xpathFirst") { matches.firstOrNull()?.let { JsonPrimitive(it).toString() } ?: "null" } else { buildJsonArray { matches.forEach { add(JsonPrimitive(it)) } }.toString() } } private fun parseEpubBridge(payload: String): String { val args = payloadArray(payload) val path = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty() if (path.isBlank()) return "null" val archive = archives ?: return "null" val chapters = archive.listEpubChapters(path) return buildJsonObject { put("path", JsonPrimitive(path)) put("chapters", buildJsonArray { chapters.forEachIndexed { index, chapter -> add(buildJsonObject { put("index", JsonPrimitive(index)) put("title", JsonPrimitive(chapter.title)) put("href", JsonPrimitive(chapter.href)) }) } }) }.toString() } private fun parseEpubChapterBridge(payload: String): String { val args = payloadArray(payload) val path = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty() val index = args.getOrNull(1)?.primitiveOrNull()?.intOrNull ?: 0 if (path.isBlank()) return "" val archive = archives ?: return "" return archive.readEpubChapter(path, index) } private fun evaluateJavascriptViaWebview(payload: String): String { val args = payloadArray(payload) val url = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty() val script = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty() if (url.isBlank() || script.isBlank()) return "" val webView = webView ?: return "" val userAgent = args.getOrNull(2)?.primitiveOrNull()?.contentOrNull return catchingNonCancellation { host.blockingBridgeCall { webView.evaluateScript(url, script, userAgent) } }.getOrDefault("") } private fun extractVideoBridge(payload: String): String { val args = payloadArray(payload) val hostName = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty() val url = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty() val headers = args.getOrNull(2)?.objectOrNull().orEmpty() .mapValues { it.value.primitiveOrNull()?.contentOrNull.orEmpty() } if (hostName.isBlank() || url.isBlank()) return "null" val extractor = animeExtractors.firstOrNull { it.hostName.equals(hostName, ignoreCase = true) } ?: return "null" val result = catchingNonCancellation { host.blockingBridgeCall { extractor.extract(url, headers) } }.getOrNull() ?: return "null" return buildJsonObject { put("videos", buildJsonArray { result.videos.forEach { video -> add(buildJsonObject { put("url", JsonPrimitive(video.url)) put("quality", JsonPrimitive(video.quality)) put("originalUrl", JsonPrimitive(video.originalUrl)) }) } }) put("headers", buildJsonObject { result.headers.forEach { (key, value) -> put(key, JsonPrimitive(value)) } }) }.toString() } private fun coerceDateToMillis(raw: String, format: String): Long { if (raw.isBlank()) return 0L raw.toLongOrNull()?.let { return it } val now = nowMillis() val lower = raw.lowercase().trim() relativeDateOffsetMillis(lower)?.let { return now - it } // Recognize simple ISO yyyy-MM-dd val isoMatch = IsoDatePattern.find(raw) if (isoMatch != null) { val (y, m, d) = isoMatch.destructured return approximateMillisFor(y.toInt(), m.toInt(), d.toInt()) } // Try the dotted format from the extension if provided. if (format.isNotBlank()) { val numbers = DigitsPattern.findAll(raw).map { it.value }.toList() if (numbers.size >= 3) { val (y, m, d) = decodeFromFormat(numbers, format) if (y > 0) return approximateMillisFor(y, m, d) } } return now } private fun relativeDateOffsetMillis(value: String): Long? { val match = RelativeDatePattern.find(value) ?: return null val amount = match.groupValues[1].toLongOrNull() ?: return null val unitMs = when (match.groupValues[2]) { "second" -> 1_000L "minute" -> 60_000L "hour" -> 3_600_000L "day" -> 86_400_000L "week" -> 7L * 86_400_000L "month" -> 30L * 86_400_000L "year" -> 365L * 86_400_000L else -> return null } return amount * unitMs } private fun decodeFromFormat(numbers: List, format: String): Triple { val tokens = format.lowercase().split(NonLetterPattern).filter { it.isNotBlank() } var y = 0 var m = 0 var d = 0 tokens.forEachIndexed { index, token -> val numberValue = numbers.getOrNull(index)?.toIntOrNull() ?: return@forEachIndexed when { token.startsWith("y") -> y = numberValue token.startsWith("m") -> m = numberValue token.startsWith("d") -> d = numberValue } } return Triple(y, m, d) } private fun approximateMillisFor(year: Int, month: Int, day: Int): Long { if (year <= 0) return nowMillis() // Days since 1970-01-01, approximate (no leap-year correction beyond modulo 4). var days = (year - 1970).toLong() * 365 + ((year - 1969) / 4) val daysPerMonth = intArrayOf(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) for (i in 0 until (month - 1).coerceAtLeast(0)) { days += daysPerMonth.getOrNull(i) ?: 30 } days += (day - 1).coerceAtLeast(0) return days * 86_400_000L } }