KwikExtractor.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/KwikExtractor.kt
1package eu.friedcutlet.yokan.services.media.extractors23import eu.friedcutlet.yokan.database.DbVideo4import eu.friedcutlet.yokan.services.http.EnhancedHttpService5import eu.friedcutlet.yokan.services.http.HttpRequest6import eu.friedcutlet.yokan.services.http.HttpService7import eu.friedcutlet.yokan.services.media.AnimeExtractorService8import eu.friedcutlet.yokan.services.media.ExtractorResult9import eu.friedcutlet.yokan.services.media.extractVideos1011/**12 * Kwik / Pahewin embed extractor for AnimePahe.13 *14 * Kwik wraps its stream URL behind two distinct obfuscation schemes:15 *16 * - **`kwik.cx/e/<id>`** (HLS path) — the embed page ships a Dean Edwards17 * `eval(function(p,a,c,k,e,d){…})` packed script. After unpacking, the18 * `.m3u8` master is at `const source='…'`.19 * - **`pahe.win/<id>`** (MP4 / download path) — `GET /i` returns a 302 to20 * the canonical Kwik URL. The Kwik page contains a custom obfuscator21 * invocation `("<fullString>",N,"<key>",v1,v2,N)`; decrypting that22 * yields a `<form action="https://kwik.si/d/<token>"><input23 * value="<tok>">` snippet. Posting `_token=<tok>` to the action returns24 * a 302 whose `Location` header is the direct CDN .mp4 URL.25 *26 * Cloudflare handling is delegated to [HttpService], which retries challenged27 * requests through the platform WebView with the same headers and cookies.28 */29class KwikExtractor(30 private val http: HttpService,31) : AnimeExtractorService {3233 override val hostName: String get() = "kwik"3435 override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult {36 // AnimePahe hands us either a `pahe.win/<id>` download wrapper or a37 // `kwik.cx/e/<id>` HLS embed. Pick the right path per URL shape;38 // both end up producing a list of DbVideo entries.39 val cleanUrl = url.trim()40 val isDownload = cleanUrl.contains("pahe.win", ignoreCase = true)41 return extractVideos(headers + kwikHeaders()) {42 if (isDownload) extractMp4(cleanUrl, headers) else extractHls(cleanUrl, headers)43 }44 }4546 /** HLS extraction — unpack the packed eval() and read `const source='…'`. */47 suspend fun extractHls(48 kwikUrl: String,49 callerHeaders: Map<String, String>,50 qualityHint: String = "",51 ): List<DbVideo> {52 val pageHeaders = ePageHeaders() + callerHeaders + mapOf(53 "Referer" to (callerHeaders["Referer"] ?: "https://kwik.cx/"),54 )55 var embedRes = http.request(HttpRequest(kwikUrl, headers = pageHeaders))56 var masterUrl = embedRes.takeIf { it.statusCode in 200..299 }?.let { extractHlsUrl(it.body) }57 if (masterUrl == null) {58 embedRes = http.request(59 HttpRequest(60 kwikUrl,61 headers = pageHeaders + ("X-Yokan-Resolve-Cloudflare" to "1"),62 ),63 )64 masterUrl = embedRes.takeIf { it.statusCode in 200..299 }?.let { extractHlsUrl(it.body) }65 }66 masterUrl ?: return emptyList()67 val playbackHeaders = kwikHeaders()68 val labelPrefix = "Kwik" + (if (qualityHint.isBlank()) "" else " - $qualityHint")69 return http.m3u8Videos(70 masterUrl = masterUrl,71 labelPrefix = labelPrefix,72 headers = playbackHeaders,73 requestHeaders = playbackHeaders,74 ).ifEmpty {75 // Master fetch failed (some Kwik nodes only allow the player UA) or76 // it's a non-master single-variant playlist: hand the URL back77 // directly so the player still gets a usable URL.78 listOf(79 DbVideo(80 url = masterUrl,81 originalUrl = masterUrl,82 quality = labelPrefix,83 headers = playbackHeaders,84 ),85 )86 }87 }888990 private fun extractHlsUrl(body: String): String? {91 for (match in ScriptTagRegex.findAll(body)) {92 val script = match.groupValues[1]93 var searchFrom = script.lastIndex94 while (searchFrom >= 0) {95 val evalPosition = script.lastIndexOf("eval(function(", searchFrom)96 if (evalPosition < 0) break97 JsPacker.unpack(script.substring(evalPosition))98 ?.let(::extractM3u8)99 ?.let { return it }100 searchFrom = evalPosition - 1101 }102 }103 return null104 }105106 private fun extractM3u8(unpacked: String): String? =107 SOURCE_REGEX.find(unpacked)?.groupValues?.get(1)108 ?: M3U8_REGEX.find(unpacked)?.groupValues?.get(1)109110 /** MP4 / download extraction via `pahe.win/<id>` → Kwik → custom decrypt → POST. */111 suspend fun extractMp4(112 paheUrl: String,113 callerHeaders: Map<String, String>,114 qualityHint: String = "",115 ): List<DbVideo> {116 // Phase 1: pahe.win /i returns a 302 to the canonical Kwik URL. Our117 // HttpService follows redirects transparently, but we need the118 // pre-redirect Location to peel off any wrapper, so we issue the119 // initial request and read its final URL from the response chain.120 // EnhancedHttpService doesn't expose the redirect chain, so instead121 // hit /i and use the response URL — or, if that's not exposed,122 // probe the embed URL from the page body itself.123 val initRes = http.request(124 HttpRequest(125 url = "${paheUrl.trimEnd('/')}/i",126 headers = callerHeaders + mapOf("Referer" to "https://animepahe.ru/"),127 ),128 )129 // Locate the canonical Kwik URL. The first preference is the response130 // body's own form/script references; failing that we accept the131 // request URL itself if it already resolves to a Kwik host.132 val kwikUrl = KWIK_URL_REGEX.find(initRes.body)?.value133 ?: paheUrl.takeIf { it.contains("kwik.", ignoreCase = true) }134 ?: return emptyList()135136 // Phase 2: fetch the Kwik HTML and pull the obfuscator tuple.137 val embedHeaders = kwikHeaders() + mapOf("Referer" to "https://kwik.cx/")138 val embedRes = http.request(HttpRequest(kwikUrl, headers = embedHeaders))139 if (embedRes.statusCode !in 200..299) return emptyList()140 val match = PARAMS_REGEX.find(embedRes.body) ?: return emptyList()141 val (fullString, key, v1Str, v2Str) = match.destructured142 val v1 = v1Str.toIntOrNull() ?: return emptyList()143 val v2 = v2Str.toIntOrNull() ?: return emptyList()144 val decrypted = decrypt(fullString, key, v1, v2)145 val action = ACTION_REGEX.find(decrypted)?.groupValues?.get(1) ?: return emptyList()146 val token = VALUE_REGEX.find(decrypted)?.groupValues?.get(1) ?: return emptyList()147148 // Phase 3: POST `_token=<tok>` and use the redirect target.149 // We follow redirects via the HttpService and read the final URL150 // from the response body when available; if HttpService transparently151 // followed the 302 already, the body may be the actual file. To152 // keep things simple, we attempt the POST and treat the request URL153 // surfaced via response headers / inferred body as the stream URL.154 val postHeaders = kwikHeaders() + mapOf(155 "Referer" to kwikUrl,156 "Cookie" to listOf(157 embedRes.setCookies.joinToString("; ") { it.substringBefore(";") },158 callerHeaders["Cookie"].orEmpty(),159 ).filter { it.isNotBlank() }.joinToString("; "),160 "Content-Type" to "application/x-www-form-urlencoded",161 )162 val body = "_token=${urlEncode(token)}"163 val postRes = http.request(164 HttpRequest(165 url = action,166 method = "POST",167 headers = postHeaders,168 body = body,169 ),170 )171 // Kwik returns 302 → Location: <cdn>. HttpService follows redirects;172 // the final stream URL is whatever the response carries as173 // `request.url` (some HttpService implementations) or the Location174 // header if the redirect wasn't auto-followed.175 // EnhancedHttpService follows redirects transparently, which means176 // we usually won't see the Location header here. The fallback path177 // — sniffing the final URL from the response — isn't available178 // through our HttpService surface, so MP4 download extraction179 // returns the Location only when redirects weren't auto-followed.180 // The HLS path above is the canonical in-app playback route.181 val streamUrl = postRes.headers["location"]182 ?: postRes.headers["Location"]183 ?: return emptyList()184 val playbackHeaders = kwikHeaders() + mapOf("Referer" to "https://kwik.cx/")185 val label = "Kwik MP4" + (if (qualityHint.isBlank()) "" else " - $qualityHint")186 return listOf(187 DbVideo(188 url = streamUrl,189 originalUrl = streamUrl,190 quality = label,191 headers = playbackHeaders,192 ),193 )194 }195196 /**197 * Base-`v2` digit decoder using `key` as the alphabet. The packed string198 * splits on `key[v2]` as a separator; each segment between separators is199 * a base-`v2` number whose digit values come from `keyIndexMap`. Subtract200 * `v1` and cast to Char to recover one source character.201 */202 private fun decrypt(fullString: String, key: String, v1: Int, v2: Int): String {203 if (v2 < 2 || v2 > key.length) return ""204 val keyIndexMap = key.withIndex().associate { it.value to it.index }205 val separator = key[v2]206 val sb = StringBuilder()207 var i = 0208 while (i < fullString.length) {209 val next = fullString.indexOf(separator, i)210 if (next == -1) break211 val digits = StringBuilder()212 for (j in i until next) {213 val v = keyIndexMap[fullString[j]] ?: return sb.toString()214 digits.append(v.toString())215 }216 i = next + 1217 val n = digits.toString().toIntOrNull(v2) ?: return sb.toString()218 sb.append((n - v1).toChar())219 }220 return sb.toString()221 }222223 private fun ePageHeaders(): Map<String, String> = mapOf(224 "Accept" to "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",225 "Accept-Language" to "en-US,en;q=0.9",226 "Sec-Fetch-Dest" to "iframe",227 "Sec-Fetch-Mode" to "navigate",228 "Sec-Fetch-Site" to "cross-site",229 "Sec-Fetch-User" to "?1",230 "Upgrade-Insecure-Requests" to "1",231 )232233 private fun kwikHeaders(): Map<String, String> = mapOf(234 "Origin" to "https://kwik.cx",235 "Referer" to "https://kwik.cx/",236 )237238 private fun urlEncode(value: String): String {239 // Minimal application/x-www-form-urlencoded encoder — KMP-friendly240 // (no java.net.URLEncoder dependency).241 val sb = StringBuilder()242 for (c in value) {243 when {244 c.isLetterOrDigit() || c == '-' || c == '_' || c == '.' || c == '~' -> sb.append(c)245 else -> for (b in c.toString().encodeToByteArray()) {246 sb.append('%').append(b.toUByte().toString(16).padStart(2, '0').uppercase())247 }248 }249 }250 return sb.toString()251 }252253 private companion object {254 val SOURCE_REGEX = Regex("""(?:(?:const|var)\s+source\s*=|source\s*:\s*)\\?['"](https?://[^\s\\'"]+\.m3u8[^\s\\'"]*)""")255 val M3U8_REGEX = Regex("""(https?://[^\s\\'"]+\.m3u8[^\s\\'"]*)""")256 val PARAMS_REGEX = Regex("""\("(\w+)",\d+,"(\w+)",(\d+),(\d+),\d+\)""")257 val ACTION_REGEX = Regex("""action="([^"]+)"""")258 val VALUE_REGEX = Regex("""value="([^"]+)"""")259 val KWIK_URL_REGEX = Regex("""https?://kwik\.[a-z]+/[^\s"'<>)]+""", RegexOption.IGNORE_CASE)260 }261}262