Yokan / rebuild
Course 1 8624561

GogoCdnExtractor.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/GogoCdnExtractor.kt

implementation168 lines
1package eu.friedcutlet.yokan.services.media.extractors23import eu.friedcutlet.yokan.database.DbVideo4import eu.friedcutlet.yokan.services.extensions.js.aesDecrypt5import eu.friedcutlet.yokan.services.extensions.js.aesEncrypt6import eu.friedcutlet.yokan.services.http.HttpRequest7import eu.friedcutlet.yokan.services.http.HttpService8import eu.friedcutlet.yokan.services.media.AnimeExtractorService9import eu.friedcutlet.yokan.services.media.ExtractorResult10import eu.friedcutlet.yokan.services.media.extractVideos11import kotlin.io.encoding.Base6412import kotlin.io.encoding.ExperimentalEncodingApi13import kotlinx.serialization.json.Json14import kotlinx.serialization.json.JsonArray15import kotlinx.serialization.json.JsonObject16import kotlinx.serialization.json.jsonPrimitive1718/**19 * GoGoCDN / Vidstreaming embed extractor.20 *21 * The player negotiates the actual stream URL via a pair of AES-CBC roundtrips.22 *23 *   1. Scrape `iv`, `secretKey`, `decryptionKey` and the `data-value` blob out24 *      of the embed page.25 *   2. AES-CBC-decrypt `data-value` with (secretKey, iv) → the query params26 *      that have to be appended to `encrypt-ajax.php`.27 *   3. AES-CBC-encrypt the `id` query param with the same (secretKey, iv) →28 *      the `encryptedId` we send to `encrypt-ajax.php`.29 *   4. Decrypt the response's `data` field with (decryptionKey, iv) → JSON30 *      containing the source list (either an HLS master URL or one or more31 *      labelled stream URLs).32 *33 * AES key + IV come through as raw ASCII strings, which we right-pad with null34 * bytes (or truncate) to AES-128's 16-byte requirement — matching how the35 * Flutter `encrypt` package handles undersized inputs.36 */37class GogoCdnExtractor(38    private val http: HttpService,39) : AnimeExtractorService {4041    override val hostName: String get() = "gogocdn"4243    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =44        extractVideos(headers) { videosFromUrl(url) }4546    @OptIn(ExperimentalEncodingApi::class)47    private suspend fun videosFromUrl(serverUrl: String): List<DbVideo> {48        val response = http.request(HttpRequest(serverUrl))49        if (response.statusCode !in 200..299) return emptyList()50        val document = response.body5152        val iv = WRAPPER_REGEX.find(document)?.groupValues?.get(1)?.removePrefix("container-")53            ?: return emptyList()54        val secretKey = BODY_REGEX.find(document)?.groupValues?.get(1)?.removePrefix("container-")55            ?: return emptyList()56        val decryptionKey = DECRYPTION_KEY_REGEX.find(document)?.groupValues?.get(1)57            ?: return emptyList()58        val dataValue = DATA_VALUE_REGEX.find(document)?.groupValues?.get(1).orEmpty()5960        val ivBytes = paddedKey(iv, 16)61        val secretKeyBytes = paddedKey(secretKey, 16)62        val decryptionKeyBytes = paddedKey(decryptionKey, 16)6364        // Decrypt data-value to learn the extra query params for encrypt-ajax.php.65        val decryptedDataValue = decryptToString(secretKeyBytes, ivBytes, dataValue) ?: return emptyList()66        val encryptAjaxParams = decryptedDataValue.substringAfter("&", missingDelimiterValue = "")67        if (encryptAjaxParams.isBlank()) return emptyList()6869        val (host, idParam) = splitHostAndId(serverUrl) ?: return emptyList()70        val encryptedId = encryptToBase64(secretKeyBytes, ivBytes, idParam) ?: return emptyList()71        val isGogostream = serverUrl.contains("token=", ignoreCase = true)72        val qualityPrefix = if (isGogostream) "Gogostream - " else "Vidstreaming - "7374        val encryptAjaxUrl = "${host}encrypt-ajax.php?id=$encryptedId&$encryptAjaxParams&alias=$idParam"75        val ajaxResponse = http.request(76            HttpRequest(77                url = encryptAjaxUrl,78                headers = mapOf("X-Requested-With" to "XMLHttpRequest"),79            ),80        )81        if (ajaxResponse.statusCode !in 200..299) return emptyList()82        val ajaxRoot = runCatching { Json.parseToJsonElement(ajaxResponse.body) as? JsonObject }.getOrNull()83            ?: return emptyList()84        val encryptedData = ajaxRoot["data"]?.jsonPrimitive?.content ?: return emptyList()85        val decryptedJson = decryptToString(decryptionKeyBytes, ivBytes, encryptedData) ?: return emptyList()86        val payload = runCatching { Json.parseToJsonElement(decryptedJson) as? JsonObject }.getOrNull()87            ?: return emptyList()88        val sources = payload["source"] as? JsonArray ?: return emptyList()8990        return buildSources(sources, qualityPrefix, serverUrl)91    }9293    private suspend fun buildSources(94        sources: JsonArray,95        qualityPrefix: String,96        serverUrl: String,97    ): List<DbVideo> {98        val (hls, others) = sources.partition { it is JsonObject && (it["type"]?.jsonPrimitive?.content == "hls") }99        val videos = mutableListOf<DbVideo>()100        // Single HLS master URL — fan out to per-resolution variants.101        if (hls.size == 1) {102            val fileUrl = (hls[0] as JsonObject)["file"]?.jsonPrimitive?.content?.trim().orEmpty()103            if (fileUrl.isNotBlank()) {104                // Single-rendition playlist — fall back to the master URL itself.105                videos += http.m3u8Videos(106                    masterUrl = fileUrl,107                    labelPrefix = qualityPrefix,108                    fallbackQuality = "${qualityPrefix}Original",109                )110            }111        }112        // Labelled streams — emit one DbVideo per entry, with "auto" pushed last113        // so per-quality selectors default to a real resolution.114        val autoVideos = mutableListOf<DbVideo>()115        for (entry in others) {116            val obj = entry as? JsonObject ?: continue117            val label = obj["label"]?.jsonPrimitive?.content.orEmpty()118                .lowercase().trim().replace(" ", "")119            val fileUrl = obj["file"]?.jsonPrimitive?.content.orEmpty().trim()120            if (fileUrl.isBlank()) continue121            val video = DbVideo(122                url = fileUrl,123                quality = "$qualityPrefix$label",124                originalUrl = fileUrl,125                headers = mapOf("Referer" to serverUrl),126            )127            if (label == "auto") autoVideos += video else videos += video128        }129        return videos + autoVideos130    }131132    private fun splitHostAndId(serverUrl: String): Pair<String, String>? {133        val host = "https://${hostOf(serverUrl) ?: return null}/"134        val idParam = QUERY_ID_REGEX.find(serverUrl)?.groupValues?.get(1) ?: return null135        return host to idParam136    }137138    private fun paddedKey(value: String, target: Int): ByteArray {139        val raw = value.encodeToByteArray()140        return when {141            raw.size == target -> raw142            raw.size > target -> raw.copyOf(target)143            else -> ByteArray(target).also { out -> raw.copyInto(out) }144        }145    }146147    @OptIn(ExperimentalEncodingApi::class)148    private fun decryptToString(key: ByteArray, iv: ByteArray, base64Cipher: String): String? {149        if (base64Cipher.isBlank()) return null150        val cipherBytes = runCatching { Base64.decode(base64Cipher) }.getOrNull() ?: return null151        val plain = aesDecrypt(key, iv, cipherBytes) ?: return null152        return runCatching { plain.decodeToString() }.getOrNull()153    }154155    @OptIn(ExperimentalEncodingApi::class)156    private fun encryptToBase64(key: ByteArray, iv: ByteArray, plain: String): String? {157        val enc = aesEncrypt(key, iv, plain.encodeToByteArray()) ?: return null158        return Base64.encode(enc)159    }160161    private companion object {162        val WRAPPER_REGEX = Regex("""<div[^>]*class="([^"]*container-[^"\s]+)[^"]*"""", RegexOption.IGNORE_CASE)163        val BODY_REGEX = Regex("""<body[^>]*class="([^"]*container-[^"\s]+)[^"]*"""", RegexOption.IGNORE_CASE)164        val DECRYPTION_KEY_REGEX = Regex("""videocontent-(\d+)""")165        val DATA_VALUE_REGEX = Regex("""data-value="([^"]+)"""")166        val QUERY_ID_REGEX = Regex("""[?&]id=([^&#]+)""")167    }168}169

Search chapters, reference and source filenames.