Modern Apps git

← Modern-Apps.git

youpipe: default signed-out client to VISIONOS to fix ANDROID_VR bot-flag (match PipePipe)

Commit
554eb59cf46dbfe2e968f9a4c849c6957fcbd334
Author
vayun-mathur <[email protected]>
When
2026-08-16 18:55 UTC (3 months ago)
Parents
abc45a9

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 57ed9dc105..a49f506bca 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@@ -345,12 +345,11 @@ object YoutubeStreamHelper {          val headers = getMobileClientHeaders(getVisionOsUserAgent(localization)) -        // We must always pass a valid visitorData to get valid player responses, which needs to be-        // got from YouTube+        // visitorData is fetched from the gapis host, matching PipePipe's visionos path.         innertubeClientRequestInfo.clientInfo.visitorData =             YoutubeParsingHelper.getVisitorDataFromInnertube(                 innertubeClientRequestInfo, localization, contentCountry, headers,-                YOUTUBEI_V1_URL, null, false+                YOUTUBEI_V1_GAPIS_URL, null, false             )          val builder = prepareJsonBuilder(
youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.ktindex 128398da58..b7968151d4 100644--- a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.kt+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.kt@@ -826,7 +826,14 @@ class YoutubeStreamExtractor(         val poTokenProviderInstance = poTokenProvider         val noPoTokenProviderSet = poTokenProviderInstance == null -        fetchAndroidVrClient(localization, contentCountry, videoId)+        // Default anonymous client = VISIONOS, matching PipePipe's current default+        // (NewPipe.youtubePlayerClient = "visionos"; PipePipe commit 3b2aa5e "default+        // anonymous YouTube client to VisionOS", which supersedes the earlier android_vr+        // default). VISIONOS sends a valid visitorData, so YouTube does not bot-flag it.+        // The anonymous ANDROID_VR request has no visitorData and is now rejected with+        // SignInConfirmNotBotException (LOGIN_REQUIRED), which is why android_vr must NOT+        // be the primary/gating client.+        fetchVisionOsClient(localization, contentCountry, videoId)          setStreamType() @@ -836,8 +843,6 @@ class YoutubeStreamExtractor(             fetchIosClient(localization, contentCountry, videoId, iosPoTokenResult)         } -        fetchVisionOsClient(localization, contentCountry, videoId)-         fetchWebClientMetadataAndSetThumbnails(localization, contentCountry, videoId)          val nextBody = prepareDesktopJsonBuilder(localization, contentCountry)@@ -850,23 +855,23 @@ class YoutubeStreamExtractor(     }      @Throws(IOException::class, ExtractionException::class)-    private fun fetchAndroidVrClient(+    private fun fetchVisionOsClient(         localization: Localization,         contentCountry: ContentCountry,         videoId: String     ) {-        androidCpn = generateContentPlaybackNonce()+        visionOsCpn = generateContentPlaybackNonce() -        playerResponse = YoutubeStreamHelper.getAndroidVrPlayerResponse(-            contentCountry, localization, videoId, androidCpn!!+        playerResponse = YoutubeStreamHelper.getVisionOsPlayerResponse(+            contentCountry, localization, videoId, visionOsCpn!!         )          checkPlayabilityStatus(playerResponse!!.getObject(PLAYABILITY_STATUS).orEmptyObject())         if (isPlayerResponseNotValid(playerResponse, videoId)) {-            throw ExtractionException("ANDROID_VR player response is not valid")+            throw ExtractionException("VISIONOS player response is not valid")         } -        androidStreamingData = playerResponse?.getObject(STREAMING_DATA)+        visionOsStreamingData = playerResponse?.getObject(STREAMING_DATA)          playerCaptionsTracklistRenderer = playerResponse?.getObject(CAPTIONS)             ?.getObject(PLAYER_CAPTIONS_TRACKLIST_RENDERER)@@ -901,30 +906,6 @@ class YoutubeStreamExtractor(         }     } -    private fun fetchVisionOsClient(-        localization: Localization,-        contentCountry: ContentCountry,-        videoId: String-    ) {-        try {-            visionOsCpn = generateContentPlaybackNonce()--            val visionOsPlayerResponse = YoutubeStreamHelper.getVisionOsPlayerResponse(-                contentCountry, localization, videoId, visionOsCpn!!-            )--            if (!isPlayerResponseNotValid(visionOsPlayerResponse, videoId)) {-                visionOsStreamingData = visionOsPlayerResponse.getObject(STREAMING_DATA)--                if (Utils.isNullOrEmpty(playerCaptionsTracklistRenderer)) {-                    playerCaptionsTracklistRenderer = visionOsPlayerResponse.getObject(CAPTIONS)-                        ?.getObject(PLAYER_CAPTIONS_TRACKLIST_RENDERER)-                }-            }-        } catch (ignored: Exception) {-        }-    }-     private fun fetchWebClientMetadataAndSetThumbnails(         localization: Localization,         contentCountry: ContentCountry,
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.ktdeleted file mode 100644index 69956cc448..0000000000--- a/youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/AndroidVrPlayerRequestDumpTest.kt+++ /dev/null@@ -1,148 +0,0 @@-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()-    }-}
youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/SignedOutPlayerRequestDumpTest.kt
diff --git a/youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/SignedOutPlayerRequestDumpTest.kt b/youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/SignedOutPlayerRequestDumpTest.ktnew file mode 100644index 0000000000..5d399ae935--- /dev/null+++ b/youpipe/extractor/src/test/kotlin/org/schabi/newpipe/extractor/services/youtube/SignedOutPlayerRequestDumpTest.kt@@ -0,0 +1,159 @@+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 /player requests.+ *+ * The DEFAULT signed-out client is VISIONOS, matching PipePipe's current default+ * (NewPipe.youtubePlayerClient = "visionos"). VISIONOS carries a valid visitorData, so YouTube+ * does not bot-flag it; the anonymous ANDROID_VR request has no visitorData and is now rejected+ * with SignInConfirmNotBotException (LOGIN_REQUIRED).+ *+ * This test reconstructs both requests offline for a fixed videoId and prints method, full URL,+ * all headers and the complete body JSON so they can be compared byte-for-byte with PipePipe.+ * Values that would otherwise require a network/JS fetch (visitorData, signatureTimestamp) are+ * pinned to fixed placeholders purely so the dump is deterministic and offline.+ */+class SignedOutPlayerRequestDumpTest {++    private val videoId = "dQw4w9WgXcQ"+    private val cpn = "abcdef_1234567890AB"+    private val signatureTimestamp = 20073+    private val visitorDataPlaceholder = "CgtプレースホルダーVISITOR"+    private val localization = Localization.DEFAULT+    private val contentCountry = ContentCountry.DEFAULT++    // ---- VISIONOS (primary / default signed-out path) ----++    private fun visionOsBody(): JsonObject {+        val info = InnertubeClientRequestInfo.ofVisionOsClient()+        info.clientInfo.visitorData = visitorDataPlaceholder+        val builder = YoutubeParsingHelper.prepareJsonBuilder(+            localization, contentCountry, info, null+        )+        builder.value(YoutubeParsingHelper.VIDEO_ID, videoId)+            .value(YoutubeParsingHelper.CPN, cpn)+            .value(YoutubeParsingHelper.CONTENT_CHECK_OK, true)+            .value(YoutubeParsingHelper.RACY_CHECK_OK, true)+        return builder.done()+    }++    @Test+    fun dumpVisionOsRequest() {+        val body = visionOsBody()+        val url = YoutubeParsingHelper.YOUTUBEI_V1_GAPIS_URL + "player?" ++            YoutubeParsingHelper.DISABLE_PRETTY_PRINT_PARAMETER + "&t=<tParam>&id=$videoId"+        val sb = StringBuilder()+        sb.appendLine("============ VISIONOS /player REQUEST DUMP (DEFAULT signed-out) ============")+        sb.appendLine("METHOD: POST")+        sb.appendLine("URL: $url")+        sb.appendLine("videoId (fixed): $videoId")+        sb.appendLine("visitorData (fixed placeholder; real value fetched from gapis /visitor_id): $visitorDataPlaceholder")+        sb.appendLine("--- HEADERS ---")+        sb.appendLine("Content-Type: application/json")+        sb.appendLine("User-Agent: <visionOS UA from getVisionOsUserAgent(localization)>")+        sb.appendLine("X-Goog-Api-Format-Version: 2")+        sb.appendLine("--- BODY (compact) ---")+        sb.appendLine(body.toString())+        sb.appendLine("--- BODY (pretty) ---")+        sb.appendLine(prettyPrint(body.toString()))+        sb.appendLine("===========================================================================")+        println(sb.toString())+    }++    @Test+    fun visionOsBodyCarriesVisitorDataAndCorrectClient() {+        val root = visionOsBody()+        val client = root["context"]!!.jsonObject["client"]!!.jsonObject+        // The whole point: VISIONOS sends visitorData (this is why it is not bot-flagged).+        assertTrue(client.containsKey("visitorData"), "VISIONOS body MUST carry visitorData")+        assertEquals("VISIONOS", client["clientName"]!!.toString().trim('"'))+        assertEquals("1.02", client["clientVersion"]!!.toString().trim('"'))+        assertEquals("RealityDevice14,1", client["deviceModel"]!!.toString().trim('"'))+        assertEquals("visionOS", client["osName"]!!.toString().trim('"'))+        assertEquals(videoId, root["videoId"]!!.toString().trim('"'))+        assertEquals(cpn, root["cpn"]!!.toString().trim('"'))+    }++    // ---- ANDROID_VR (reference only; NOT used by default — bot-flagged when anonymous) ----++    private fun androidVrBody(): JsonObject = YoutubeStreamHelper.buildAndroidVrPlayerRequestBody(+        localization, contentCountry, videoId, cpn, signatureTimestamp+    )++    @Test+    fun dumpAndroidVrRequest() {+        val body = androidVrBody()+        val headers = YoutubeStreamHelper.getAndroidVrHeaders()+        val url = YoutubeStreamHelper.getAndroidVrPlayerUrl()+        val sb = StringBuilder()+        sb.appendLine("======= ANDROID_VR /player REQUEST DUMP (reference; not default) =======")+        sb.appendLine("METHOD: POST")+        sb.appendLine("URL: $url")+        sb.appendLine("NOTE: anonymous ANDROID_VR has NO visitorData => bot-flagged (LOGIN_REQUIRED).")+        sb.appendLine("--- HEADERS ---")+        headers.toSortedMap().forEach { (name, values) -> values.forEach { sb.appendLine("$name: $it") } }+        sb.appendLine("--- BODY (compact) ---")+        sb.appendLine(body.toString())+        sb.appendLine("--- BODY (pretty) ---")+        sb.appendLine(prettyPrint(body.toString()))+        sb.appendLine("=======================================================================")+        println(sb.toString())+    }++    @Test+    fun androidVrBodyIsByteIdenticalToPipePipe() {+        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, androidVrBody().toString())+        // Reference invariant: android_vr anonymous body has NO visitorData (the bot-flag cause).+        val client = androidVrBody()["context"]!!.jsonObject["client"]!!.jsonObject+        assertFalse(client.containsKey("visitorData"))+    }++    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()+    }+}