import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/components/Services/Innertube/NodesParser.bs" import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/ObjectUtils.bs" import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/UrlUtils.bs" namespace Innertube function CreatePlayerRequest(client as Innertube.ClientType, options = invalid as object) as object videoId = OptionUtils.Get(options, "videoId") cancellation = OptionUtils.Get(options, "cancellation") visitorData = OptionUtils.Get(options, "visitorData") accessToken = OptionUtils.Get(options, "accessToken") doSignatureTimestamp = ValidBool(OptionUtils.Get(options, "signatureTimestamp")) useAccessToken = client = Innertube.ClientType.TV and not StringUtils.IsNullOrEmpty(accessToken) deviceInfo = CreateObject("roDeviceInfo") context = Innertube.CreateContext(client, deviceInfo, options) payload = { "videoId": videoId "context": context "playbackContext": { "contentPlaybackContext": { "vis": 0 "splay": false "referer": "https://www.youtube.com/watch?v=" + videoId "currentUrl": "/watch?v=" + videoId "autonavState": "STATE_ON" "autoCaptionsDefaultOn": false "html5Preference": "HTML5_PREF_WANTS" "lactMilliseconds": "-1" "isInlinePlaybackNoAd": true } } "attestationRequest": { "omitBotguardData": true } "racyCheckOk": true "contentCheckOk": true } signatureTimestamp = invalid if doSignatureTimestamp signatureTimestamp = GetSignatureTimestamp(cancellation) if signatureTimestamp <> invalid payload["playbackContext"]["contentPlaybackContext"]["signatureTimestamp"] = signatureTimestamp end if end if request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload) request.Headers(Innertube.CreateHeaders(client)) if not StringUtils.IsNullOrEmpty(visitorData) and not useAccessToken request.Header("x-goog-visitor-id", visitorData) end if request.signatureTimestamp = signatureTimestamp return request end function function ParseInnertubePlayerResponse(payload as object, parsedResponse as object, signatureTimestamp as dynamic, cancellation as object) as object error = ParsePlayerResponseForError(payload) if error <> "" parsedResponse["error"] = error return parsedResponse end if videoDetails = payload["videoDetails"] if not IsAssociativeArray(videoDetails) parsedResponse["error"] = "Invalid videoDetails" return parsedResponse end if streamingData = payload["streamingData"] if not IsAssociativeArray(streamingData) parsedResponse["error"] = "Invalid streamingData" return parsedResponse end if lengthSeconds = videoDetails["lengthSeconds"].ToInt() isLive = ValidBool(videoDetails["isLive"]) adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"])) formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"])) if not isLive error = DecipherUrls(formats, adaptiveFormats, signatureTimestamp, cancellation) if error <> invalid parsedResponse["error"] = error.error if error.DoesExist("errorCode") parsedResponse["errorCode"] = error.errorCode end if return parsedResponse end if end if hasLiveStreamingData = FormatsHaveLiveStreamingData(adaptiveFormats) or FormatsHaveLiveStreamingData(formats) adaptiveFormats = TransformFormats(adaptiveFormats) formats = TransformFormats(formats) parsedResponse["type"] = "video" parsedResponse["videoId"] = videoDetails["videoId"] parsedResponse["videoThumbnails"] = videoDetails["thumbnail"]["thumbnails"] parsedResponse["storyboards"] = ParseStoryboards(payload, lengthSeconds) parsedResponse["author"] = videoDetails["author"] parsedResponse["authorId"] = videoDetails["channelId"] parsedResponse["lengthSeconds"] = lengthSeconds parsedResponse["liveNow"] = isLive parsedResponse["hasLiveStreamingData"] = hasLiveStreamingData parsedResponse["hlsUrl"] = streamingData["hlsManifestUrl"] parsedResponse["dashUrl"] = streamingData["dashManifestUrl"] parsedResponse["adaptiveFormats"] = adaptiveFormats parsedResponse["formatStreams"] = formats parsedResponse["captions"] = ParseCaptions(payload) if not StringUtils.IsNullOrEmpty(videoDetails["title"]) parsedResponse["title"] = videoDetails["title"] end if if not StringUtils.IsNullOrEmpty(videoDetails["author"]) parsedResponse["author"] = videoDetails["author"] end if if videoDetails.DoesExist("viewCount") parsedResponse["viewCount"] = videoDetails["viewCount"].ToInt() end if parsedResponse["isLoggedIn"] = ParseIsLoggedIn(payload) parsedResponse["playbackTrackingUrls"] = ParsePlaybackTrackingUrls(payload, parsedResponse.isLoggedIn) return parsedResponse end function function ParsePlayerResponseForError(payload as object) as string if not IsAssociativeArray(payload) return "Invalid payload" end if playabilityStatus = payload["playabilityStatus"] if not IsAssociativeArray(playabilityStatus) return "Invalid playability status" end if status = ValidString(playabilityStatus["status"]) if status = "OK" return "" end if errorLines = [] if not StringUtils.IsNullOrEmpty(playabilityStatus["reason"]) errorLines.Push(playabilityStatus["reason"]) end if if not StringUtils.IsNullOrEmpty(playabilityStatus["reasonTitle"]) errorLines.Push(playabilityStatus["reasonTitle"]) end if subreason = ParseText(ObjectUtils.Dig(playabilityStatus, ["errorScreen", "playerErrorMessageRenderer", "subreason"])) if subreason <> "" errorLines.Push(subreason) end if if errorLines.Count() = 0 errorLines.Push("Video not available (Unknown)") end if if status = "LOGIN_REQUIRED" ' TODO:P2 localize errorLines.Push("Hint: Log in to the YouTube app on your phone, then cast the video to Playlet.") end if return errorLines.Join(`\n`) end function function ParseStoryboards(payload as object, lengthSeconds as integer) as object storyboard = ObjectUtils.Dig(payload, ["storyboards", "playerLiveStoryboardSpecRenderer", "spec"]) if IsString(storyboard) storyboard = storyboard.Split("#") if storyboard.Count() <> 5 return [] end if return [{ "templateUrl": storyboard[0] "width": storyboard[1].ToInt() "height": storyboard[2].ToInt() "count": -1 "interval": 5000 "storyboardHeight": storyboard[3].ToInt() "storyboardWidth": storyboard[4].ToInt() }] end if storyboards = ObjectUtils.Dig(payload, ["storyboards", "playerStoryboardSpecRenderer", "spec"]) if not IsString(storyboards) return [] end if storyboardsData = storyboards.Split("|") if storyboardsData.Count() < 2 return [] end if baseUrl = storyboardsData.Shift() storyboards = [] index = 0 for each sb in storyboardsData sbData = sb.Split("#") if sbData.Count() <> 8 index += 1 continue for end if width = sbData[0].ToInt() height = sbData[1].ToInt() _count = sbData[2].ToInt() columns = sbData[3].ToInt() rows = sbData[4].ToInt() interval = sbData[5].ToInt() name = sbData[6] sigh = sbData[7] url = baseUrl url = url.Replace("$L", `${index}`) url = url.Replace("$N", name) queryComponents = UrlUtils.ParseQueryComponents(url) queryComponents["sigh"] = sigh.DecodeUriComponent() url = UrlUtils.SetQueryParams(url, queryComponents) thumbnailsPerImage = columns * rows imagesCount = _count \ thumbnailsPerImage if _count mod thumbnailsPerImage > 0 imagesCount += 1 end if if interval = 0 and _count > 0 interval = Cint(Cdbl(lengthSeconds) * 1000.0 / Cdbl(_count)) end if storyboards.Push({ "templateUrl": url "width": width "height": height "count": _count "interval": interval "storyboardWidth": columns "storyboardHeight": rows "storyboardCount": imagesCount }) index += 1 end for return storyboards end function function ParseCaptions(payload as object) as object tracks = ObjectUtils.Dig(payload, ["captions", "playerCaptionsTracklistRenderer", "captionTracks"]) if not IsArray(tracks) return [] end if captions = [] for each track in tracks if not IsAssociativeArray(track) continue for end if baseUrl = track["baseUrl"] if not IsString(baseUrl) continue for end if queryComponents = UrlUtils.ParseQueryComponents(baseUrl) queryComponents["fmt"] = "vtt" baseUrl = UrlUtils.SetQueryParams(baseUrl, queryComponents) languageCode = track["languageCode"] if not IsString(languageCode) continue for end if label = "" name = track["name"] if IsAssociativeArray(name) runs = name["runs"] if IsArray(runs) for each rn in runs text = rn["text"] if IsString(text) label += text end if end for end if end if captions.Push({ "label": label "language_code": languageCode "url": baseUrl }) end for return captions end function function TransformFormats(formats as object) as object for i = 0 to formats.Count() - 1 formats[i] = TransformFormat(formats[i]) end for return formats end function function TransformFormat(fmt as object) as object itag = `${fmt["itag"]}` result = { "bitrate": `${fmt["bitrate"]}` "url": fmt["url"] "itag": itag "type": fmt["mimeType"] "clen": `${fmt["approxDurationMs"]}` "lmt": `${fmt["lastModified"]}` } if IsAssociativeArray(fmt["initRange"]) result["init"] = `${fmt["initRange"]["start"]}-${fmt["initRange"]["end"]}` else result["init"] = "" end if if IsAssociativeArray(fmt["indexRange"]) result["index"] = `${fmt["indexRange"]["start"]}-${fmt["indexRange"]["end"]}` else result["index"] = "" end if if fmt["audioQuality"] <> invalid result["audioQuality"] = ToString(fmt["audioQuality"]) end if if fmt["audioSampleRate"] <> invalid result["audioSampleRate"] = ToString(fmt["audioSampleRate"]) end if if fmt["audioChannels"] <> invalid result["audioChannels"] = ToString(fmt["audioChannels"]) end if if IsString(fmt["qualityLabel"]) result["qualityLabel"] = fmt["qualityLabel"] end if if fmt["fps"] <> invalid result["fps"] = ToString(fmt["fps"]) end if result["width"] = fmt["width"] result["height"] = fmt["height"] if fmt["width"] <> invalid and fmt["height"] <> invalid result["size"] = `${fmt["width"]}x${fmt["height"]}` result["resolution"] = `${fmt["height"]}p` else #if DEBUG if result["type"].StartsWith("video/") throw "Missing width/height for itag " + itag end if #end if end if return result end function function GetSignatureTimestamp(cancellation as object) as dynamic cache = ReadAsciiFile("tmp:/sts_cache.json") if not StringUtils.IsNullOrEmpty(cache) json = ParseJson(cache) return json["sts"] end if request = HttpClient.Get(`${PLAYLET_SUPPORT_SERVER}/v1/sts`) request.Cancellation(cancellation) request.NoCache() response = request.Await() if not response.IsSuccess() if response.IsCancelled() LogErrorNoTelemetry(response.ErrorMessage()) else LogError(response.ErrorMessage()) end if return invalid end if text = response.Text() WriteAsciiFile("tmp:/sts_cache.json", text) json = response.Json() return json["sts"] end function function DecipherUrls(formats as object, adaptiveFormats as object, signatureTimestamp as dynamic, cancellation as object) as object if signatureTimestamp = invalid ' No need to decipher if signatureTimestamp is not available return invalid end if reqFormats = [] for each fmt in formats reqFormats.push({ "url": fmt["url"] "cipher": fmt["cipher"] "signatureCipher": fmt["signatureCipher"] }) end for reqAdaptiveFormats = [] for each fmt in adaptiveFormats reqAdaptiveFormats.push({ "url": fmt["url"] "cipher": fmt["cipher"] "signatureCipher": fmt["signatureCipher"] }) end for request = HttpClient.PostJson(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`, { "sts": signatureTimestamp "formats": reqFormats "adaptiveFormats": reqAdaptiveFormats }) request.Cancellation(cancellation) request.LogCurlCommand(false) response = request.Await() if not response.IsSuccess() errorCode = "" if response.StatusCode() = 400 json = response.Json() if IsAssociativeArray(json) errorCode = ValidString(json["code"]) if errorCode = "STS_MISMATCH" DeleteFile("tmp:/sts_cache.json") end if end if end if exception = { error: response.ErrorMessage() } if errorCode <> "" exception.errorCode = errorCode end if if response.IsCancelled() or errorCode = "STS_MISMATCH" LogErrorNoTelemetry(response.ErrorMessage()) else LogError(response.ErrorMessage()) end if return exception end if json = response.Json() if not IsAssociativeArray(json) or not json.DoesExist("formats") or not json.DoesExist("adaptiveFormats") error = "Invalid response from decipher service" LogError(error) return { error: error } end if decipheredFormats = json["formats"] if not IsArray(decipheredFormats) or decipheredFormats.Count() <> formats.Count() error = "Invalid formats in deciphered response" LogError(error) return { error: error } end if for i = 0 to decipheredFormats.Count() - 1 fmt = formats[i] decipheredFmt = decipheredFormats[i] fmt["url"] = decipheredFmt["url"] end for decipheredAdaptiveFormats = json["adaptiveFormats"] if not IsArray(decipheredAdaptiveFormats) or decipheredAdaptiveFormats.Count() <> adaptiveFormats.Count() error = "Invalid adaptiveFormats in deciphered response" LogError(error) return { error: error } end if for i = 0 to decipheredAdaptiveFormats.Count() - 1 fmt = adaptiveFormats[i] decipheredFmt = decipheredAdaptiveFormats[i] fmt["url"] = decipheredFmt["url"] end for return invalid end function function ParseIsLoggedIn(payload as object) as boolean trackingParams = ObjectUtils.Dig(payload, ["responseContext", "serviceTrackingParams"]) if not IsArray(trackingParams) return false end if for each trackingParam in trackingParams if not IsAssociativeArray(trackingParam) continue for end if params = trackingParam["params"] if not IsArray(params) continue for end if for each param in params if not IsAssociativeArray(param) continue for end if if param["key"] = "logged_in" and param["value"] = "1" return true end if end for end for return false end function function ParsePlaybackTrackingUrls(payload as object, isLoggedIn as boolean) as object if not isLoggedIn return invalid end if playbackTracking = payload["playbackTracking"] if not IsAssociativeArray(playbackTracking) return invalid end if return { "videostatsPlaybackUrl": ObjectUtils.Dig(playbackTracking, ["videostatsPlaybackUrl", "baseUrl"]) "videostatsWatchtimeUrl": ObjectUtils.Dig(playbackTracking, ["videostatsWatchtimeUrl", "baseUrl"]) } end function function IsLiveStream(payload as object) as boolean if ValidBool(ObjectUtils.Dig(payload, ["videoDetails", "isLive"])) return true end if adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"])) if FormatsHaveLiveStreamingData(adaptiveFormats) return true end if formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"])) if FormatsHaveLiveStreamingData(formats) return true end if return false end function function FormatsHaveLiveStreamingData(formats as object) as boolean if not IsArray(formats) return false end if for each fmt in formats url = fmt["url"] if IsString(url) and url.InStr("yt_live_broadcast") <> -1 return true end if end for return false end function end namespace