import "pkg:/components/Services/Innertube/BrowseEndpoint.bs" import "pkg:/components/Services/Innertube/Constants.bs" import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/components/Services/Innertube/GetDrmLicenseEndpoint.bs" import "pkg:/components/Services/Innertube/NextEndpoint.bs" import "pkg:/components/Services/Innertube/OAuth.bs" import "pkg:/components/Services/Innertube/PlayerEndpoint.bs" import "pkg:/components/Services/Innertube/ResolveUrlEndpoint.bs" import "pkg:/components/Services/Innertube/SearchEndpoint.bs" import "pkg:/components/Services/Innertube/SearchFilters.bs" import "pkg:/components/Services/Innertube/SubscriptionEndpoint.bs" import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/ObjectUtils.bs" import "pkg:/source/utils/OptionUtils.bs" import "pkg:/source/utils/TimeUtils.bs" ' DEBUG-only: force the SABR downgrade retry on every playable response. #const DEBUG_FORCE_SABR_DOWNGRADE = false namespace InnertubeService function GetVideoMetadata(videoId as string, options = invalid as object) as object options["videoId"] = videoId if not OptionUtils.GetOrDefault(options, "fetchNext", true) return GetPlayerMetadata(videoId, options) end if raw = OptionUtils.GetOrDefault(options, "raw", false) nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, options) nextRequest.Cancellation(OptionUtils.Get(options, "cancellation")) if raw nextRequest.LogCurlCommand() end if pendingNext = nextRequest.Send() return AwaitAndParseNextResponse(raw, GetPlayerMetadata(videoId, options), nextRequest, pendingNext) end function ' The parsed player response (raw: { playerResponse }), or { error }. function GetPlayerMetadata(videoId as string, options as object) as object cancellation = OptionUtils.Get(options, "cancellation") accessToken = OptionUtils.Get(options, "accessToken") raw = OptionUtils.GetOrDefault(options, "raw", false) client = Innertube.ClientType.Tv triedReloadRefresh = false ' We shouldn't be making more than 3 requests: ' 1. Make request with TV client. ' 2. Make request, but STS_MISMATCH error -> retry with new STS. ' 3. useServerDrivenAbr -> retry with downgraded TV client version to recover format URLs. for playerRequestCount = 1 to 3 stsResult = Innertube.GetSignatureTimestamp(cancellation) if CancellationUtils.IsCancelled(cancellation) return { error: "Cancelled" } end if if stsResult.error <> invalid return stsResult end if options["signatureTimestamp"] = stsResult.sts playerRequest = Innertube.CreatePlayerRequest(client, options) if not StringUtils.IsNullOrEmpty(accessToken) and (client = Innertube.ClientType.Tv or client = Innertube.ClientType.TvDowngraded) playerRequest.Header("Authorization", "Bearer " + accessToken) end if playerRequest.Cancellation(cancellation) if raw playerRequest.LogCurlCommand() end if playerResponse = playerRequest.Await() if CancellationUtils.IsCancelled(cancellation) return { error: "Cancelled" } end if if not playerResponse.IsSuccess() return { error: playerResponse.ErrorMessage() } end if playerResponseJson = playerResponse.Json() ' Under server-driven ABR the TV client can withhold every adaptive format URL (stuck ' at 360p); the downgraded TV client is not served SABR. Retry once with it. if client = Innertube.ClientType.Tv and IsSabrLocked(playerResponseJson) LogInfo("SABR-locked response, retrying with downgraded TV client...") client = Innertube.ClientType.TvDowngraded continue for else if client = Innertube.ClientType.TvDowngraded and not HasUsableAdaptiveUrl(playerResponseJson) LogError("Downgraded TV client did not recover SABR-withheld format URLs") end if parsedResponse = Innertube.ParseInnertubePlayerResponse(playerRequest, playerResponse, client, cancellation) if parsedResponse.error = invalid if raw return { "playerResponse": playerResponseJson } end if if StringUtils.IsNullOrEmpty(parsedResponse.videoId) parsedResponse["videoId"] = videoId end if return parsedResponse end if if parsedResponse.errorCode <> invalid if parsedResponse.errorCode = "STS_MISMATCH" LogInfo("STS_MISMATCH error, retrying...") continue for else if parsedResponse.errorCode = "RELOAD_PAGE" and not triedReloadRefresh triedReloadRefresh = true LogInfo("RELOAD_PAGE: clearing stale STS cache and retrying...") DeleteFile("tmp:/sts_cache.json") continue for else if parsedResponse.errorCode = "MISSING_FORMAT_FIELD" useServerDrivenAbr = `${ObjectUtils.Dig(playerResponseJson, ["playerConfig", "mediaCommonConfig", "useServerDrivenAbr"])}` LogTelemetryEvent({ level: "error" message: parsedResponse.errorCode + `\nplayerConfig.mediaCommonConfig.useServerDrivenAbr:` + useServerDrivenAbr fingerprint: parsedResponse.errorCode + useServerDrivenAbr attachments: [{ filename: "request.txt" content_type: "text/plain" data: playerRequest.ToCurlCommand() }, { filename: "response.json" content_type: "application/json" data: playerResponse.Text() }] }) end if end if return parsedResponse end for LogError("Too many player requests, aborting.") return { error: "Too many player requests" } end function ' True when the TV client's response is SABR-locked: server-driven ABR signaled with no usable ' adaptive URL. function IsSabrLocked(playerResponseJson as object) as boolean if not IsAssociativeArray(ObjectUtils.Dig(playerResponseJson, ["streamingData"])) return false end if serverDrivenAbr = ValidBool(ObjectUtils.Dig(playerResponseJson, ["playerConfig", "mediaCommonConfig", "useServerDrivenAbr"])) locked = serverDrivenAbr and not HasUsableAdaptiveUrl(playerResponseJson) #if DEBUG #if DEBUG_FORCE_SABR_DOWNGRADE locked = true #end if #end if return locked end function ' True if any adaptive format carries a playable field (url / signatureCipher / cipher). function HasUsableAdaptiveUrl(playerResponseJson as object) as boolean adaptiveFormats = ObjectUtils.Dig(playerResponseJson, ["streamingData", "adaptiveFormats"]) if not IsArray(adaptiveFormats) return false end if for each format in adaptiveFormats if IsAssociativeArray(format) and (not StringUtils.IsNullOrEmpty(format["url"]) or not StringUtils.IsNullOrEmpty(format["signatureCipher"]) or not StringUtils.IsNullOrEmpty(format["cipher"])) return true end if end for return false end function function AwaitAndParseNextResponse(raw as boolean, parsedResponse as object, nextRequest as HttpClient.Request, pendingNext as HttpClient.PendingResponse) as object nextResponse = pendingNext.Await() if not nextResponse.IsSuccess() if nextResponse.IsCancelled() return parsedResponse end if error = nextResponse.ErrorMessage() LogWarn(error) if raw parsedResponse["nextError"] = error end if return parsedResponse end if if raw parsedResponse["nextResponse"] = nextResponse.Json() return parsedResponse end if return Innertube.ParseInnertubeNextResponse(nextResponse.Json(), parsedResponse, nextRequest) end function function GetVideoInfoBatched(videoIds as object, options = invalid as object) as object if not IsArray(videoIds) or videoIds.Count() = 0 return { videos: [] } end if cancellation = OptionUtils.Get(options, "cancellation") retry = OptionUtils.GetOrDefault(options, "retry", true) params = Innertube.GetEncodedNextParams(videoIds) request = Innertube.CreateNextRequest({ "params": params }) request.Cancellation(cancellation) response = request.Await() if not response.IsSuccess() return { error: response.ErrorMessage() } end if responseData = response.Json() error = Innertube.ParseResponseDataForError(responseData) if error <> "" return { error: error } end if ' If we're fetching more than one video, we want to search for the playlist if videoIds.Count() > 1 responseData = ObjectUtils.Dig(responseData, ["contents", "twoColumnWatchNextResults", "playlist", "playlist"]) if responseData = invalid ' Sometimes the response doesn't contain a playlist. ' The theory here is that when a private video is in the list, the created playlist ' is no longer publicly available. That's why it is not returned. Also happens with ' a deleted video. ' A retry after a short sleep SOMETIMES fixes this (but not always). ' TODO:P1: Figure out why this happens and if there's a better way to handle it. if retry LogWarn("Response data missing playlist. Retrying in a bit...") newOptions = {} if options <> invalid newOptions.Append(options) end if newOptions["retry"] = false sleep(200 + Rnd(500)) return GetVideoInfoBatched(videoIds, newOptions) else LogWarn("Response data missing playlist. Not retrying.") end if end if end if feeds = Innertube.ParseResponseDataForFeeds(responseData, { request: request }) if videoIds.Count() > 1 if feeds.Count() > 0 return { videos: ValidArray(feeds[0].items) } end if else if feeds.Count() > 0 foundVideos = feeds[0].items for each video in foundVideos if video.videoId = videoIds[0] return { videos: [video] } end if end for end if end if return { videos: [] } end function function SearchSuggestions(q as string, cancellation = invalid as object) as object return Innertube.SearchSuggestions(q, cancellation) end function function Search(query as string, options = invalid as object) as object return Innertube.Search(query, options) end function function GetTrending(options = invalid as object) as object cancellation = OptionUtils.Get(options, "cancellation") trendingType = LCase(OptionUtils.GetOrDefault(options, "type", "")) disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false) raw = OptionUtils.GetOrDefault(options, "raw", false) if trendingType = "gaming" browseId = "UCOpNcN46UbXVtpKMrmU4Abg" ' Gaming params = "Egh0cmVuZGluZw%3D%3D" else browseId = "UC4R8DWoMoI7CAwX8_LjQHig" ' Livestreams (default) params = "EgdsaXZldGFikgEDCKEK" end if request = Innertube.CreateBrowseRequest(browseId, Innertube.ClientType.Web, { params: params }) request.Cancellation(cancellation) if raw request.LogCurlCommand() end if response = request.Await() if not response.IsSuccess() return { error: response.ErrorMessage() } end if if raw return response.Json() end if feeds = Innertube.ParseResponseDataForFeeds(response.Json(), { request: request disableCreatorOnTheRise: true disableShorts: disableShorts browseId: browseId }) result = { feeds: feeds } cacheControl = Innertube.ParseResponseForCacheControl(response) if cacheControl <> invalid result["cache-control"] = cacheControl end if return result end function function GetHome(options = invalid as object) as object return GetBrowseAuthenticatedPage("FEwhat_to_watch", options) end function function GetSubscriptions(options = invalid as object) as object return GetBrowseAuthenticatedPage("FEsubscriptions", options) end function function GetWatchHistory(options = invalid as object) as object return GetBrowseAuthenticatedPage("FEhistory", options) end function function GetPlaylists(options = invalid as object) as object return GetBrowseAuthenticatedPage("FEplaylist_aggregation", options) end function function GetBrowseAuthenticatedPage(browseId as string, options = invalid as object) as object cancellation = OptionUtils.Get(options, "cancellation") accessToken = OptionUtils.Get(options, "accessToken") disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false) request = Innertube.CreateBrowseRequest(browseId, Innertube.ClientType.Tv, options) if accessToken <> invalid request.Header("Authorization", "Bearer " + accessToken) end if request.Cancellation(cancellation) response = request.Await() if not response.IsSuccess() return { error: response.ErrorMessage() } end if feeds = Innertube.ParseResponseDataForFeeds(response.Json(), { request: request disableShorts: disableShorts browseId: browseId }) result = { feeds: feeds } cacheControl = Innertube.ParseResponseForCacheControl(response) if cacheControl <> invalid result["cache-control"] = cacheControl end if return result end function function AuthGetPlaybackTrackingUrls(videoId as string, options as object) as object cancellation = invalid accessToken = options.accessToken if options.DoesExist("cancellation") cancellation = options.cancellation end if options["videoId"] = videoId stsResult = Innertube.GetSignatureTimestamp(cancellation) if stsResult.error <> invalid return stsResult end if options["signatureTimestamp"] = stsResult.sts playerRequest = Innertube.CreatePlayerRequest(Innertube.ClientType.Tv, options) playerRequest.Cancellation(cancellation) playerRequest.Header("Authorization", "Bearer " + accessToken) playerResponse = playerRequest.Await() if not playerResponse.IsSuccess() return { error: playerResponse.ErrorMessage() } end if json = playerResponse.Json() error = Innertube.ParsePlayerResponseForError(json, playerRequest) if error <> "" return { error: error } end if videostatsPlaybackUrl = ObjectUtils.Dig(json, ["playbackTracking", "videostatsPlaybackUrl", "baseUrl"]) videostatsWatchtimeUrl = ObjectUtils.Dig(json, ["playbackTracking", "videostatsWatchtimeUrl", "baseUrl"]) return { videostatsPlaybackUrl: videostatsPlaybackUrl videostatsWatchtimeUrl: videostatsWatchtimeUrl } end function function AuthMarkVideoWatched(videostatsPlaybackUrl as string, options as object) as boolean cancellation = OptionUtils.Get(options, "cancellation") accessToken = OptionUtils.Get(options, "accessToken") onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser") cpn = OptionUtils.Get(options, "cpn") videostatsPlaybackUrl = videostatsPlaybackUrl.replace("https://s.", "https://www.") queryParams = UrlUtils.ParseQueryComponents(videostatsPlaybackUrl) queryParams["c"] = "TVHTML5" queryParams["cbrver"] = INNERTUBE_TV_CLIENT_VERSION queryParams["cver"] = INNERTUBE_TV_CLIENT_VERSION queryParams["ver"] = "2" queryParams["cmt"] = "0" queryParams["cpn"] = cpn queryParams["final"] = "1" videostatsPlaybackUrl = UrlUtils.SetQueryParams(videostatsPlaybackUrl, queryParams) request = HttpClient.Get(videostatsPlaybackUrl) request.Cancellation(cancellation) request.NoCache() request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv)) request.Header("Authorization", "Bearer " + accessToken) if not StringUtils.IsNullOrEmpty(onBehalfOfUser) request.Header("X-Goog-Pageid", onBehalfOfUser) end if response = request.Await() if not response.IsSuccess() LogError("Error marking video as watched:", response.ErrorMessage()) return false end if LogDebug("Marked video as watched") return true end function function AuthMarkVideoWatchTime(time as float, videostatsWatchtimeUrl as string, options = invalid as object) as boolean cancellation = OptionUtils.Get(options, "cancellation") accessToken = OptionUtils.Get(options, "accessToken") onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser") timeStr = time.ToStr("%.3f") cpn = OptionUtils.Get(options, "cpn") videostatsWatchtimeUrl = videostatsWatchtimeUrl.replace("https://s.", "https://www.") queryParams = UrlUtils.ParseQueryComponents(videostatsWatchtimeUrl) queryParams["c"] = "TVHTML5" queryParams["cbrver"] = INNERTUBE_TV_CLIENT_VERSION queryParams["cver"] = INNERTUBE_TV_CLIENT_VERSION queryParams["ver"] = "2" queryParams["cpn"] = cpn queryParams["cmt"] = "0" queryParams["st"] = timeStr queryParams["et"] = timeStr queryParams["final"] = "1" videostatsWatchtimeUrl = UrlUtils.SetQueryParams(videostatsWatchtimeUrl, queryParams) request = HttpClient.Get(videostatsWatchtimeUrl) request.Cancellation(cancellation) request.NoCache() request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv)) request.Header("Authorization", "Bearer " + accessToken) if not StringUtils.IsNullOrEmpty(onBehalfOfUser) request.Header("X-Goog-Pageid", onBehalfOfUser) end if response = request.Await() if not response.IsSuccess() LogError("Error marking video watch time:", response.ErrorMessage()) return false end if LogDebug("Marked video watch time:", timeStr) return true end function function CreateClientPlaybackNonce() as string length = 16 result = [] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" alphabetLen = alphabet.len() for i = 1 to length result.push(alphabet.mid(Rnd(alphabetLen - 1), 1)) end for return result.join("") end function function GetChannel(channelId as string, options = invalid as object) as object cancellation = OptionUtils.Get(options, "cancellation") raw = OptionUtils.GetOrDefault(options, "raw", false) request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, options) request.Cancellation(cancellation) if raw request.LogCurlCommand() end if response = request.Await() if not response.IsSuccess() return { error: response.ErrorMessage() } end if if raw return response.Json() end if result = Innertube.ParseChannelPageResponseData(channelId, response.Json(), request) if result.authorId = invalid and result.error = invalid result["authorId"] = channelId end if cacheControl = Innertube.ParseResponseForCacheControl(response) if cacheControl <> invalid result["cache-control"] = cacheControl end if return result end function function GetSubscriptionStatusForChannel(channelId as string, options = invalid as object) as object cancellation = OptionUtils.Get(options, "cancellation") accessToken = OptionUtils.Get(options, "accessToken") request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Tv, options) request.Cancellation(cancellation) if accessToken <> invalid request.Header("Authorization", "Bearer " + accessToken) end if response = request.Await() if not response.IsSuccess() return { error: response.ErrorMessage() } end if responseData = response.Json() error = Innertube.ParseResponseDataForError(responseData) if error <> "" return { error: error } end if channelHeaderButtons = ObjectUtils.Dig(responseData, ["contents", "tvBrowseRenderer", "content", "tvSurfaceContentRenderer", "header", "channelHeaderRenderer", "buttons"]) if not IsArray(channelHeaderButtons) return { error: "Node 'contents.tvBrowseRenderer.content.tvSurfaceContentRenderer.header.channelHeaderRenderer.buttons' not found" } end if subscribeButtonRenderer = invalid for each button in channelHeaderButtons if not IsAssociativeArray(button) or not button.DoesExist("subscribeButtonRenderer") continue for end if subscribeButtonRenderer = button.subscribeButtonRenderer exit for end for if subscribeButtonRenderer = invalid return { error: "no 'subscribeButtonRenderer' found under 'buttons'" } end if if not IsBool(subscribeButtonRenderer["subscribed"]) return { error: "no 'subscribed' status found under 'subscribeButtonRenderer'" } end if return { success: true isSubscribed: subscribeButtonRenderer["subscribed"] } end function function SubscribeToChannel(channelId as string, options = invalid as object) as object cancellation = OptionUtils.Get(options, "cancellation") accessToken = OptionUtils.Get(options, "accessToken") request = Innertube.CreateSubscribeRequest(channelId, options) request.Cancellation(cancellation) if accessToken <> invalid request.Header("Authorization", "Bearer " + accessToken) end if response = request.Await() return { success: response.IsSuccess() error: response.ErrorMessage() } end function function UnsubscribeFromChannel(channelId as string, options = invalid as object) as object cancellation = OptionUtils.Get(options, "cancellation") accessToken = OptionUtils.Get(options, "accessToken") request = Innertube.CreateUnsubscribeRequest(channelId, options) request.Cancellation(cancellation) if accessToken <> invalid request.Header("Authorization", "Bearer " + accessToken) end if response = request.Await() return { success: response.IsSuccess() error: response.ErrorMessage() } end function function GetPlaylist(playlistId as string, options = invalid as object) as object cancellation = OptionUtils.Get(options, "cancellation") raw = OptionUtils.GetOrDefault(options, "raw", false) accessToken = OptionUtils.Get(options, "accessToken") if not playlistId.StartsWith("VL") playlistId = "VL" + playlistId end if client = Innertube.ClientType.Web if accessToken <> invalid client = Innertube.ClientType.Tv end if request = Innertube.CreateBrowseRequest(playlistId, client, options) request.Cancellation(cancellation) if accessToken <> invalid request.Header("Authorization", "Bearer " + accessToken) end if if raw request.LogCurlCommand() end if response = request.Await() if not response.IsSuccess() return { error: response.ErrorMessage() } end if if raw return response.Json() end if result = Innertube.ParsePlaylistPageResponseData(playlistId, response.Json(), request) if result.playlistId = invalid and result.error = invalid result["playlistId"] = playlistId end if cacheControl = Innertube.ParseResponseForCacheControl(response) if cacheControl <> invalid result["cache-control"] = cacheControl end if return result end function function GetMix(mixId as string, options = invalid as object) as object videoId = OptionUtils.Get(options, "videoId") cancellation = OptionUtils.Get(options, "cancellation") raw = OptionUtils.GetOrDefault(options, "raw", false) args = { "playlistId": mixId } if not StringUtils.IsNullOrEmpty(videoId) args["videoId"] = videoId end if request = Innertube.CreateNextRequest(args) request.Cancellation(cancellation) if raw request.LogCurlCommand() end if response = request.Await() if not response.IsSuccess() return { error: response.ErrorMessage() } end if if raw return response.Json() end if result = Innertube.ParseMixPageResponseData(response.Json(), request) cacheControl = Innertube.ParseResponseForCacheControl(response) if cacheControl <> invalid result["cache-control"] = cacheControl end if return result end function function ResolveUrl(url as string, options = invalid as object) as object cancellation = OptionUtils.Get(options, "cancellation") request = Innertube.CreateResolveUrlRequest(url) request.Cancellation(cancellation) response = request.Await() if not response.IsSuccess() return { error: response.ErrorMessage() } end if json = response.Json() return json end function function AuthGetCode(cancellation = invalid as object) as object result = Innertube.GetClientIdentity(cancellation) if CancellationUtils.IsCancelled(cancellation) or result.error <> invalid return result end if result2 = Innertube.GetDeviceAndUserCode(result.clientId, cancellation) if CancellationUtils.IsCancelled(cancellation) or result2.error <> invalid return result2 end if result.Append(result2) return result end function function AuthGetActivationUrl(code as object) as string return `https://www.youtube.com/tv/activate?user_code=${code.userCode}` end function function AuthPollForAccessToken(code as object, cancellation = invalid as object) as object return Innertube.PollForAccessToken(code, code, cancellation) end function function AuthRefreshAccessToken(accessToken as object, cancellation = invalid as object) as boolean if not IsAssociativeArray(accessToken) return false end if refreshed = Innertube.RefreshAccessToken(accessToken, cancellation) if IsAssociativeArray(refreshed) and refreshed.DoesExist("accessToken") accessToken.Append(refreshed) if accessToken.DoesExist("expiresIn") accessToken["expiresTimestamp"] = TimeUtils.Now().AsSeconds() + accessToken["expiresIn"] end if return true end if return false end function function AuthRevokeToken(token as string, cancellation = invalid as object) as boolean return Innertube.RevokeToken(token, cancellation) end function function AuthListAccounts(accessToken as string, cancellation = invalid as object) as object return Innertube.ListAccounts(accessToken, cancellation) end function function GetDrmLicense(options as object) as Innertube.DrmLicenseResponse request = Innertube.CreateGetDrmLicenceRequest(options) response = request.Await() if not response.IsSuccess() return { error: response.ErrorMessage() } end if return Innertube.ParseGetDrmLicenseResponse(response.Json()) end function end namespace