Modern Apps git

← Modern-Apps.git

youpipe: make android_vr signed-out /player request byte-identical to PipePipe + add offline dump test

Commit
8388e695346763d87c389ff3c76b4852701c794c
Author
vayun-mathur <[email protected]>
When
2026-08-16 18:46 UTC (3 months ago)
Parents
4803ccd
Strip context.request/user from the android_vr player body and match PipePipe's exact
field set/order via YoutubeStreamHelper.buildAndroidVrPlayerRequestBody. Add an offline
unit test that dumps the request (method/URL/headers/body) and asserts byte-identity.

Diff

youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/YoutubeStreamHelper.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/YoutubeStreamHelper.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/YoutubeStreamHelper.ktindex 05c7580226..57ed9dc105 100644--- a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/YoutubeStreamHelper.kt+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/YoutubeStreamHelper.kt@@ -197,6 +197,72 @@ object YoutubeStreamHelper {         ).getObject("playerResponse")     } +    /**+     * ANDROID_VR request headers, matching PipePipe's android_vr player call exactly.+     *+     * The standard www.youtube.com InnerTube player endpoint is used (NOT the gapis host, and+     * without the &t=/&id= params which the gapis PO-token flow uses). X-YouTube-Client-Name (28)+     * and X-YouTube-Client-Version identify the client.+     */+    @JvmStatic+    fun getAndroidVrHeaders(): Map<String, List<String>> = mapOf(+        "Content-Type" to listOf("application/json"),+        "User-Agent" to listOf(ClientsConstants.ANDROID_VR_USER_AGENT),+        "X-YouTube-Client-Name" to listOf(ClientsConstants.ANDROID_VR_CLIENT_ID),+        "X-YouTube-Client-Version" to listOf(ClientsConstants.ANDROID_VR_CLIENT_VERSION)+    )++    @JvmStatic+    fun getAndroidVrPlayerUrl(): String =+        YOUTUBEI_V1_URL + PLAYER + "?" + DISABLE_PRETTY_PRINT_PARAMETER++    /**+     * Builds the ANDROID_VR /player request body byte-for-byte identical to PipePipe's+     * `fetchConfiguredJsonPlayer` for the signed-out path: a minimal context.client (no+     * request/user/thirdParty objects), a playbackContext carrying html5Preference ++     * signatureTimestamp, then cpn/videoId/contentCheckOk/racyCheckOk. On the signed-out+     * path there is no visitorData and no serviceIntegrityDimensions/poToken.+     *+     * The field order matches PipePipe exactly so the serialized JSON is identical.+     */+    @JvmStatic+    fun buildAndroidVrPlayerRequestBody(+        localization: Localization,+        contentCountry: ContentCountry,+        videoId: String,+        cpn: String,+        signatureTimestamp: Int+    ): JsonObject {+        val builder = YoutubeJsonBuilder()+        builder.`object`("context")+            .`object`("client")+            .value("utcOffsetMinutes", 0)+            .value("timeZone", "UTC")+            .value("hl", localization.getLocalizationCode())+            .value("gl", contentCountry.countryCode)+            .value("userAgent", ClientsConstants.ANDROID_VR_USER_AGENT)+            .value("clientName", ClientsConstants.ANDROID_VR_CLIENT_NAME)+            .value("clientVersion", ClientsConstants.ANDROID_VR_CLIENT_VERSION)+            .value("deviceMake", ClientsConstants.ANDROID_VR_DEVICE_MAKE)+            .value("deviceModel", ClientsConstants.ANDROID_VR_DEVICE_MODEL)+            .value("androidSdkVersion", ClientsConstants.ANDROID_VR_SDK_VERSION)+            .value("osName", ClientsConstants.ANDROID_VR_OS_NAME)+            .value("osVersion", ClientsConstants.ANDROID_VR_OS_VERSION)+            .end()+            .end()+            .`object`("playbackContext")+            .`object`("contentPlaybackContext")+            .value("html5Preference", "HTML5_PREF_WANTS")+            .value("signatureTimestamp", signatureTimestamp)+            .end()+            .end()+            .value(CPN, cpn)+            .value(VIDEO_ID, videoId)+            .value(CONTENT_CHECK_OK, true)+            .value(RACY_CHECK_OK, true)+        return builder.done()+    }+     @JvmStatic     @Throws(IOException::class, ExtractionException::class)     fun getAndroidVrPlayerResponse(@@ -207,38 +273,18 @@ object YoutubeStreamHelper {     ): JsonObject {         // ANDROID_VR returns direct stream URLs and does not require a PO Token or visitorData,         // which is why it is far more reliable than the SABR (WEB) path right now.-        //-        // The request shape mirrors PipePipe's working android_vr player call:-        //  - the standard www.youtube.com InnerTube player endpoint (NOT the gapis host, and-        //    without the &t=/&id= params, which the gapis PO-token flow uses);-        //  - X-YouTube-Client-Name (28) / X-YouTube-Client-Version headers identifying the client;-        //  - a playbackContext carrying the signatureTimestamp + HTML5 preference so YouTube-        //    returns HTML5-decipherable formats instead of an invalid/SABR-only response.-        val innertubeClientRequestInfo = InnertubeClientRequestInfo.ofAndroidVrClient()--        val headers = mapOf(-            "User-Agent" to listOf(ClientsConstants.ANDROID_VR_USER_AGENT),-            "X-YouTube-Client-Name" to listOf(ClientsConstants.ANDROID_VR_CLIENT_ID),-            "X-YouTube-Client-Version" to listOf(ClientsConstants.ANDROID_VR_CLIENT_VERSION)-        )+        val headers = getAndroidVrHeaders() -        val builder = prepareJsonBuilder(-            localization, contentCountry, innertubeClientRequestInfo, null-        )--        addVideoIdCpnAndOkChecks(builder, videoId, cpn)--        addVrPlaybackContext(-            builder, YoutubeJavaScriptPlayerManager.getSignatureTimestamp(videoId)-        )--        val body = builder.done().toString().toByteArray(Charsets.UTF_8)--        val url = YOUTUBEI_V1_URL + PLAYER + "?" + DISABLE_PRETTY_PRINT_PARAMETER+        val body = buildAndroidVrPlayerRequestBody(+            localization, contentCountry, videoId, cpn,+            YoutubeJavaScriptPlayerManager.getSignatureTimestamp(videoId)+        ).toString().toByteArray(Charsets.UTF_8)          return JsonUtils.toJsonObject(             getValidJsonResponseBody(-                getDownloader().postWithContentTypeJson(url, headers, body, localization)+                getDownloader().postWithContentTypeJson(+                    getAndroidVrPlayerUrl(), headers, body, localization+                )             )         )     }@@ -353,18 +399,6 @@ object YoutubeStreamHelper {             .end()     } -    private fun addVrPlaybackContext(-        builder: YoutubeJsonBuilder,-        signatureTimestamp: Int-    ) {-        builder.`object`("playbackContext")-            .`object`("contentPlaybackContext")-            .value("html5Preference", "HTML5_PREF_WANTS")-            .value("signatureTimestamp", signatureTimestamp)-            .end()-            .end()-    }-     private fun addPoToken(builder: YoutubeJsonBuilder, poToken: String) {         builder.`object`(SERVICE_INTEGRITY_DIMENSIONS)             .value(PO_TOKEN, poToken)
youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/AndroidVrPlayerRequestDumpTest.kt
diff --git a/youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/AndroidVrPlayerRequestDumpTest.kt b/youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/AndroidVrPlayerRequestDumpTest.ktnew file mode 100644index 0000000000..69956cc448--- /dev/null+++ b/youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/AndroidVrPlayerRequestDumpTest.kt@@ -0,0 +1,148 @@+package org.schabi.newpipe.extractor.services.youtube++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonObject+import org.schabi.newpipe.extractor.localization.ContentCountry+import org.schabi.newpipe.extractor.localization.Localization++/**+ * Offline dump + regression test for the signed-out ANDROID_VR /player request.+ *+ * This constructs youpipe's real android_vr request body via+ * [YoutubeStreamHelper.buildAndroidVrPlayerRequestBody] (the exact same function used by+ * [YoutubeStreamHelper.getAndroidVrPlayerResponse]) for a fixed videoId, then prints the HTTP+ * method, full URL, all headers and the complete request body JSON so it can be compared+ * byte-for-byte with PipePipe's android_vr request.+ *+ * signatureTimestamp is the only value that would otherwise require a network/JS fetch; it is+ * pinned to a fixed placeholder here purely so the dump is deterministic and offline.+ */+class AndroidVrPlayerRequestDumpTest {++    private val videoId = "dQw4w9WgXcQ"+    private val cpn = "abcdef_1234567890AB"+    private val signatureTimestamp = 20073+    private val localization = Localization.DEFAULT+    private val contentCountry = ContentCountry.DEFAULT++    private fun body(): JsonObject = YoutubeStreamHelper.buildAndroidVrPlayerRequestBody(+        localization, contentCountry, videoId, cpn, signatureTimestamp+    )++    @Test+    fun dumpAndroidVrRequest() {+        val bodyJson = body()+        val bodyBytes = bodyJson.toString().toByteArray(Charsets.UTF_8)+        val headers = YoutubeStreamHelper.getAndroidVrHeaders()+        val url = YoutubeStreamHelper.getAndroidVrPlayerUrl()++        val sb = StringBuilder()+        sb.appendLine("==================== ANDROID_VR /player REQUEST DUMP ====================")+        sb.appendLine("METHOD: POST")+        sb.appendLine("URL: $url")+        sb.appendLine("videoId (fixed): $videoId")+        sb.appendLine("signatureTimestamp (fixed placeholder): $signatureTimestamp")+        sb.appendLine("--- HEADERS ---")+        headers.toSortedMap().forEach { (name, values) ->+            values.forEach { sb.appendLine("$name: $it") }+        }+        sb.appendLine("--- BODY (compact, exactly what is sent, ${bodyBytes.size} bytes) ---")+        sb.appendLine(bodyJson.toString())+        sb.appendLine("--- BODY (pretty) ---")+        sb.appendLine(prettyPrint(bodyJson.toString()))+        sb.appendLine("========================================================================")+        println(sb.toString())+    }++    @Test+    fun bodyMatchesPipePipeShape() {+        val root = body()+        val client = root["context"]!!.jsonObject["client"]!!.jsonObject++        // Signed-out android_vr body must NOT carry request/user/thirdParty objects+        // (PipePipe's fetchConfiguredJsonPlayer omits them).+        val context = root["context"]!!.jsonObject+        assertFalse(context.containsKey("request"), "context.request must be absent (matches PipePipe)")+        assertFalse(context.containsKey("user"), "context.user must be absent (matches PipePipe)")+        assertFalse(context.containsKey("thirdParty"), "context.thirdParty must be absent")++        // Signed-out: no visitorData and no poToken/serviceIntegrityDimensions.+        assertFalse(client.containsKey("visitorData"), "visitorData must be absent when signed out")+        assertFalse(+            root.containsKey("serviceIntegrityDimensions"),+            "serviceIntegrityDimensions must be absent when signed out"+        )++        // Client identity must match PipePipe's android_vr PlayerClient exactly.+        assertEquals("ANDROID_VR", client["clientName"]!!.toString().trim('"'))+        assertEquals("1.65.10", client["clientVersion"]!!.toString().trim('"'))+        assertEquals("Oculus", client["deviceMake"]!!.toString().trim('"'))+        assertEquals("Quest 3", client["deviceModel"]!!.toString().trim('"'))+        assertEquals("Android", client["osName"]!!.toString().trim('"'))+        assertEquals("12L", client["osVersion"]!!.toString().trim('"'))+        assertEquals("32", client["androidSdkVersion"]!!.toString())+        assertEquals("UTC", client["timeZone"]!!.toString().trim('"'))+        assertEquals("0", client["utcOffsetMinutes"]!!.toString())++        // playbackContext + top-level checks.+        val cpc = root["playbackContext"]!!.jsonObject["contentPlaybackContext"]!!.jsonObject+        assertEquals("HTML5_PREF_WANTS", cpc["html5Preference"]!!.toString().trim('"'))+        assertTrue(cpc.containsKey("signatureTimestamp"))+        assertEquals(videoId, root["videoId"]!!.toString().trim('"'))+        assertEquals(cpn, root["cpn"]!!.toString().trim('"'))+        assertEquals("true", root["contentCheckOk"]!!.toString())+        assertEquals("true", root["racyCheckOk"]!!.toString())+    }++    @Test+    fun bodyIsByteIdenticalToExpectedPipePipeJson() {+        // The exact compact JSON PipePipe's fetchConfiguredJsonPlayer produces for the signed-out+        // android_vr path with the same inputs (field order included).+        val expected =+            """{"context":{"client":{"utcOffsetMinutes":0,"timeZone":"UTC","hl":"${+                localization.getLocalizationCode()+            }","gl":"${+                contentCountry.countryCode+            }","userAgent":"${+                ClientsConstants.ANDROID_VR_USER_AGENT+            }","clientName":"ANDROID_VR","clientVersion":"1.65.10","deviceMake":"Oculus",""" ++                """"deviceModel":"Quest 3","androidSdkVersion":32,"osName":"Android","osVersion":"12L"}},""" ++                """"playbackContext":{"contentPlaybackContext":{"html5Preference":"HTML5_PREF_WANTS",""" ++                """"signatureTimestamp":$signatureTimestamp}},""" ++                """"cpn":"$cpn","videoId":"$videoId","contentCheckOk":true,"racyCheckOk":true}"""++        assertEquals(expected, body().toString())+    }++    private fun prettyPrint(compact: String): String {+        val out = StringBuilder()+        var indent = 0+        var inString = false+        var escaped = false+        for (c in compact) {+            if (escaped) {+                out.append(c); escaped = false; continue+            }+            when (c) {+                '\\' -> { out.append(c); escaped = true }+                '"' -> { out.append(c); inString = !inString }+                '{', '[' -> if (inString) out.append(c) else {+                    out.append(c).append('\n'); indent++; out.append("  ".repeat(indent))+                }+                '}', ']' -> if (inString) out.append(c) else {+                    out.append('\n'); indent--; out.append("  ".repeat(indent)).append(c)+                }+                ',' -> if (inString) out.append(c) else {+                    out.append(c).append('\n').append("  ".repeat(indent))+                }+                ':' -> if (inString) out.append(c) else out.append(": ")+                else -> out.append(c)+            }+        }+        return out.toString()+    }+}