Yokan / rebuild
Course 1 8624561

QuarkUcExtractor.kt

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

implementation346 lines
1package eu.friedcutlet.yokan.services.media.extractors23import eu.friedcutlet.yokan.database.DbVideo4import eu.friedcutlet.yokan.database.DbVideoTrack5import 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.extractVideos10import kotlinx.coroutines.delay11import kotlinx.serialization.json.Json12import kotlinx.serialization.json.JsonArray13import kotlinx.serialization.json.add14import kotlinx.serialization.json.JsonElement15import kotlinx.serialization.json.JsonObject16import kotlinx.serialization.json.buildJsonArray17import kotlinx.serialization.json.buildJsonObject18import kotlinx.serialization.json.jsonPrimitive19import kotlinx.serialization.json.put2021/**22 * Quark Pan / UC Pan cloud-drive video extractor — covers two backends from23 * one class because they share the same API shape, only differing in base URL,24 * user-agent, and referer.25 *26 * Yokan's HTTP layer has no equivalent of the Flutter app's per-host cookie27 * store, so this extractor expects the calling source (JavaScript extension or28 * native caller) to pass a valid drive cookie via the `Cookie` header on the29 * incoming `headers` map — same way Mihon's JS extensions handle session30 * tokens. Without a cookie the API returns auth errors and we fall through31 * to an empty list.32 *33 * Input URL format (matches Flutter): `type++fileId++fileToken++shareId++stoken[++subtitles]`34 * — where `type` is either `quark` or `uc`, and `subtitles` (optional) is a35 * `+`-separated list of `name@@@ext@@@fileId` triples.36 */37class QuarkUcExtractor(38    private val http: HttpService,39    private val cookieJar: eu.friedcutlet.yokan.services.http.cookies.CookieJar? = null,40) : AnimeExtractorService {4142    override val hostName: String get() = "quarkuc"4344    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =45        extractVideos(headers) { videosFromUrl(url, headers) }4647    private suspend fun videosFromUrl(url: String, callerHeaders: Map<String, String> = emptyMap()): List<DbVideo> {48        val parts = url.split("++")49        if (parts.size < 5) return emptyList()50        val driveLabel = parts[0]51        val fileId = parts[1]52        val fileToken = parts[2]53        val shareId = parts[3]54        val stoken = parts[4]55        val subtitleParts = if (parts.size > 5) parts[5].split("+").filter { it.isNotBlank() } else emptyList()5657        val drive = Drive.forLabel(driveLabel)58        // Honour an explicit Cookie header first (sources that mint their own59        // token still control the call). Fall through to the shared cookie jar60        // so users who logged in via the in-app WebView are reused61        // automatically; without either we bail out — the drive API returns62        // auth errors and there's nothing to extract.63        val cookie = pickCookie(callerHeaders) ?: drive.cookieDomains64            .firstNotNullOfOrNull { cookieJar?.rawCookieFor(it) }65        if (cookie.isNullOrBlank()) return emptyList()66        val apiHeaders = drive.headers(cookie)6768        val state = ExtractState(drive, apiHeaders, mutableMapOf(), null)6970        // Ensure we have a save directory and the share token; then ask the71        // cloud drive to mint per-resolution transcoding URLs.72        val quality = liveTranscoding(state, shareId, stoken, fileId, fileToken) ?: return emptyList()73        if (quality.isEmpty()) return emptyList()7475        val videoHeaders = apiHeaders.toMutableMap().apply { remove("Content-Type") }76        val originalUrl = quality.firstOrNull()?.url.orEmpty()77        val videos = quality.map { entry ->78            DbVideo(79                url = entry.url,80                quality = entry.quality,81                originalUrl = originalUrl,82                headers = videoHeaders,83                subtitles = emptyList(),84            )85        }8687        // Subtitle bundles ride along under the same headers — fetch each88        // download URL and attach the full subtitle list to every video so89        // the player can switch tracks without re-fetching.90        val subtitles = subtitleParts.mapNotNull { entry ->91            val triple = entry.split("@@@")92            if (triple.size != 3) return@mapNotNull null93            val subName = triple[0]94            val subFileId = triple[2]95            val download = downloadInfo(state, shareId, stoken, subFileId, "", clean = false)96            val subUrl = download?.get("download_url")?.jsonPrimitive?.content97            subUrl?.let { DbVideoTrack(file = it, label = subName) }98        }99        return if (subtitles.isEmpty()) videos100        else videos.map { it.copy(subtitles = subtitles) }101    }102103    // ─────────────────────────────────────────────────────────────────────────104    // Drive setup105106    private fun pickCookie(headers: Map<String, String>): String? {107        val candidate = headers.entries.firstOrNull { it.key.equals("Cookie", ignoreCase = true) }?.value108        return candidate?.takeIf { it.isNotBlank() }109    }110111    private enum class Drive(112        val apiBase: String,113        val pr: String,114        val userAgent: String,115        val referer: String,116        val label: String,117        /**118         * Hosts the cookie jar may already hold sessions for after the user119         * logged in via the in-app WebView. We probe these in order — the120         * UA-bearing API hosts first, then the user-facing pages users see in121         * the browser.122         */123        val cookieDomains: List<String>,124    ) {125        Quark(126            apiBase = "https://drive-pc.quark.cn/1/clouddrive/",127            pr = "pr=ucpro&fr=pc",128            userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) quark-cloud-drive/2.5.20 Chrome/100.0.4896.160 Electron/18.3.5.4-b478491100 Safari/537.36 Channel/pckk_other_ch",129            referer = "https://pan.quark.cn/",130            label = "quark",131            cookieDomains = listOf("drive-pc.quark.cn", "pan.quark.cn", "quark.cn"),132        ),133        UC(134            apiBase = "https://pc-api.uc.cn/1/clouddrive/",135            pr = "pr=UCBrowser&fr=pc",136            userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) uc-cloud-drive/2.5.20 Chrome/100.0.4896.160 Electron/18.3.5.4-b478491100 Safari/537.36 Channel/pckk_other_ch",137            referer = "https://drive.uc.cn/",138            label = "uc",139            cookieDomains = listOf("pc-api.uc.cn", "drive.uc.cn", "uc.cn"),140        );141142        fun headers(cookie: String): Map<String, String> = mapOf(143            "User-Agent" to userAgent,144            "Referer" to referer,145            "Content-Type" to "application/json",146            "Cookie" to cookie,147        )148149        companion object {150            fun forLabel(label: String): Drive = entries.firstOrNull { it.label.equals(label, ignoreCase = true) } ?: Quark151        }152    }153154    private data class QualityEntry(val url: String, val quality: String)155156    private class ExtractState(157        val drive: Drive,158        val headers: Map<String, String>,159        val saveFileIdCache: MutableMap<String, String>,160        var saveDirId: String?,161    )162163    // ─────────────────────────────────────────────────────────────────────────164    // Network helpers165166    /** POSTs [body] when non-null, otherwise GETs. */167    private suspend fun api(state: ExtractState, path: String, body: JsonElement? = null): JsonObject? {168        val url = state.drive.apiBase + path169        val request = if (body == null) {170            HttpRequest(url = url, method = "GET", headers = state.headers)171        } else {172            HttpRequest(url = url, method = "POST", headers = state.headers, body = body.toString())173        }174        val response = http.request(request)175        if (response.statusCode !in 200..299) return null176        return runCatching { Json.parseToJsonElement(response.body) as? JsonObject }.getOrNull()177    }178179    private suspend fun shareToken(state: ExtractState, shareId: String): String? {180        val result = api(181            state,182            "share/sharepage/token?${state.drive.pr}",183            buildJsonObject {184                put("pwd_id", shareId)185                put("passcode", "")186            },187        ) ?: return null188        return (result["data"] as? JsonObject)?.get("stoken")?.jsonPrimitive?.content?.takeIf { it.isNotBlank() }189    }190191    /** Saves [fileId] into the drive (once per extraction) and returns the saved file id. */192    private suspend fun savedFileId(193        state: ExtractState,194        shareId: String,195        stoken: String,196        fileId: String,197        fileToken: String,198        clean: Boolean,199    ): String? {200        state.saveFileIdCache[fileId]?.let { return it }201        val saved = save(state, shareId, stoken, fileId, fileToken, clean) ?: return null202        state.saveFileIdCache[fileId] = saved203        return saved204    }205206    private suspend fun liveTranscoding(207        state: ExtractState,208        shareId: String,209        stoken: String,210        fileId: String,211        fileToken: String,212    ): List<QualityEntry>? {213        val fid = savedFileId(state, shareId, stoken, fileId, fileToken, clean = true) ?: return null214        val transcoding = api(215            state,216            "file/v2/play?${state.drive.pr}",217            buildJsonObject {218                put("fid", fid)219                put("resolutions", "normal,low,high,super,2k,4k")220                put("supports", "fmp4")221            },222        ) ?: return null223        val list = (transcoding["data"] as? JsonObject)?.get("video_list") as? JsonArray ?: return null224        return list.mapNotNull { entry ->225            val obj = entry as? JsonObject ?: return@mapNotNull null226            val info = obj["video_info"] as? JsonObject ?: return@mapNotNull null227            val u = info["url"]?.jsonPrimitive?.content ?: return@mapNotNull null228            val q = obj["resolution"]?.jsonPrimitive?.content.orEmpty()229            QualityEntry(url = u, quality = q.ifBlank { "Original" })230        }231    }232233    private suspend fun save(234        state: ExtractState,235        shareId: String,236        stoken: String,237        fileId: String,238        fileToken: String,239        clean: Boolean,240    ): String? {241        ensureSaveDir(state, clean)242        val dirId = state.saveDirId ?: return null243        // The share token rides with every save call; mint it if the caller244        // didn't already.245        val effectiveStoken = stoken.ifBlank { shareToken(state, shareId) ?: return null }246        val saveResult = api(247            state,248            "share/sharepage/save?${state.drive.pr}",249            buildJsonObject {250                put("fid_list", buildJsonArray { add(fileId) })251                put("fid_token_list", buildJsonArray { add(fileToken) })252                put("to_pdir_fid", dirId)253                put("pwd_id", shareId)254                put("stoken", effectiveStoken)255                put("pdir_fid", "0")256                put("scene", "link")257            },258        ) ?: return null259        val taskId = (saveResult["data"] as? JsonObject)?.get("task_id")?.jsonPrimitive?.content ?: return null260        // Poll the task endpoint up to three times — Quark/UC sometimes takes261        // a beat to materialise the saved file. The Flutter version uses the262        // same retry budget.263        repeat(3) { retry ->264            val taskResult = api(state, "task?${state.drive.pr}&task_id=$taskId&retry_index=$retry")265            val savedAs = ((taskResult?.get("data") as? JsonObject)?.get("save_as") as? JsonObject)266                ?.get("save_as_top_fids") as? JsonArray267            val firstFid = savedAs?.firstOrNull()?.jsonPrimitive?.content268            if (!firstFid.isNullOrBlank()) return firstFid269            delay(1_000)270        }271        return null272    }273274    private suspend fun ensureSaveDir(state: ExtractState, clean: Boolean) {275        if (state.saveDirId != null) {276            if (clean) clearSaveDir(state)277            return278        }279        val list = api(280            state,281            "file/sort?${state.drive.pr}&pdir_fid=0&_page=1&_size=200&_sort=file_type:asc,updated_at:desc",282        )283        val items = (list?.get("data") as? JsonObject)?.get("list") as? JsonArray284        items?.forEach { item ->285            val obj = item as? JsonObject ?: return@forEach286            if (obj["file_name"]?.jsonPrimitive?.content == SAVE_DIR_NAME) {287                state.saveDirId = obj["fid"]?.jsonPrimitive?.content288                clearSaveDir(state)289                return290            }291        }292        val create = api(293            state,294            "file?${state.drive.pr}",295            buildJsonObject {296                put("pdir_fid", "0")297                put("file_name", SAVE_DIR_NAME)298                put("dir_path", "")299                put("dir_init_lock", false)300            },301        )302        state.saveDirId = (create?.get("data") as? JsonObject)?.get("fid")?.jsonPrimitive?.content303    }304305    private suspend fun clearSaveDir(state: ExtractState) {306        val saveDirId = state.saveDirId ?: return307        val list = api(308            state,309            "file/sort?${state.drive.pr}&pdir_fid=$saveDirId&_page=1&_size=200&_sort=file_type:asc,updated_at:desc",310        )311        val rows = (list?.get("data") as? JsonObject)?.get("list") as? JsonArray ?: return312        if (rows.isEmpty()) return313        val deleteBody = buildJsonObject {314            put("action_type", 2)315            put("filelist", buildJsonArray {316                rows.forEach { row ->317                    val fid = (row as? JsonObject)?.get("fid")?.jsonPrimitive?.content ?: return@forEach318                    add(fid)319                }320            })321            put("exclude_fids", buildJsonArray { })322        }323        api(state, "file/delete?${state.drive.pr}", deleteBody)324    }325326    private suspend fun downloadInfo(327        state: ExtractState,328        shareId: String,329        stoken: String,330        fileId: String,331        fileToken: String,332        clean: Boolean,333    ): JsonObject? {334        val fid = savedFileId(state, shareId, stoken, fileId, fileToken, clean) ?: return null335        val down = api(336            state,337            "file/download?${state.drive.pr}&uc_param_str=",338            buildJsonObject { put("fids", buildJsonArray { add(fid) }) },339        ) ?: return null340        return (down["data"] as? JsonArray)?.firstOrNull() as? JsonObject341    }342343    private companion object {344        const val SAVE_DIR_NAME = "TV"345    }346}347

Search chapters, reference and source filenames.