visitorData() fails to parse sw.js_data about 1 time in 6 because of the "Cgt" prefix check
Describe the bug
YouTube.visitorData() extracts the visitor id from sw.js_data by looking for the first string that starts with "Cgt". That prefix is not constant. About one call in six the response contains the id but it starts with "Cgs". The lookup throws NoSuchElementException, the function catches it, and the app keeps the default visitor data instead of a fresh one. Nothing crashes, so it goes unnoticed.
To Reproduce
Fetch https://music.youtube.com/sw.js_data ten times (with or without cookies) and look at the visitor string in [0][2]:
run 1: CgtG… run 2: Cgsy… run 3: CgtB… run 4: Cgtm… run 5: Cgtw…
run 6: Cgtu… run 7: Cgs0… run 8: CgtW… run 9: Cgsy… run 10: Cgs3…
In the app: launch, log in, and check the logs. When a run lands on a Cgs value you get:
java.util.NoSuchElementException: Collection contains no element matching the predicate.
at com.maxrave.kotlinytmusicscraper.YouTube.visitorData(YouTube.kt)
Seen on Desktop (Linux); the code is common.
Cause
The visitor data is a base64 protobuf. The first two bytes are always 0x0a 0x0b (field 1, length 11), which encode to Cg plus a third character whose value depends on the top two bits of the first byte of the 11-character id:
- id starts with a letter or
_(0x41-0x7a): third char ist - id starts with a digit or
-(0x2d-0x39): third char iss
So startsWith("Cgt") (YouTube.kt, visitorData(), VISITOR_DATA_PREFIX = "Cgt") only matches ids that begin with a letter. With base64url ids that is roughly 53 out of 64 first characters; the remaining 11 make the parser fail.
Proposed fix
Match the protobuf header instead of the third character. One-line change in the predicate:
.first { (it as? JsonPrimitive)?.content?.matches(Regex("^Cg[stuv][A-Za-z0-9_-]{15,}.*")) == true }
[stuv] covers all four values the third character can take for a 0x0b length byte. The rest of the array (AIza… API key, QUZZ… token, empty string) does not start with Cg, so the match stays unambiguous.
Longer term the id could be read from responseContext.visitorData of any InnerTube response, or from ytcfg VISITOR_DATA on the home page, which avoids fixed array indices. That is a bigger change and not needed to fix this.
I can open a PR on core for this if you want it.