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/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:/source/services/HttpClient.bs" import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/ObjectUtils.bs" import "pkg:/source/utils/TimeUtils.bs" namespace InnertubeService function GetVideoMetadata(videoId as string, options = invalid as object) as object cancellation = invalid fetchNext = true ctt = "" visitorData = "" raw = false if options <> invalid if options.DoesExist("cancellation") cancellation = options.cancellation end if if options.DoesExist("fetchNext") fetchNext = options.fetchNext end if if options.DoesExist("ctt") ctt = options.ctt end if if options.DoesExist("raw") raw = options.raw end if if options.DoesExist("visitorData") visitorData = options.visitorData end if end if playerRequest = Innertube.CreatePlayerRequest(videoId, ctt, visitorData) playerRequest.Cancellation(cancellation) if raw playerRequest.LogCurlCommand() playerRequest.NoCache() end if playerRequest.Send() nextRequest = invalid nextResponse = invalid if fetchNext nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, ctt) nextRequest.Cancellation(cancellation) if raw nextRequest.LogCurlCommand() nextRequest.NoCache() end if nextRequest.Send() end if playerResponse = playerRequest.Await() if not playerResponse.IsSuccess() return { error: playerResponse.ErrorMessage() } end if if CancellationUtils.IsCancelled(cancellation) return { error: "Cancelled" } end if if fetchNext nextResponse = nextRequest.Await() end if if raw rawResponse = { "playerResponse": playerResponse.Json() } if fetchNext rawResponse["nextResponse"] = nextResponse.Json() end if return rawResponse end if parsedResponse = Innertube.ParseInnertubePlayerResponse(playerResponse.Json()) if parsedResponse.error <> invalid return parsedResponse end if if fetchNext parsedResponse = Innertube.ParseInnertubeNextResponse(nextResponse.Json(), parsedResponse) end if ' If for some reason we missed the videoId, add it back if parsedResponse.error = invalid and StringUtils.IsNullOrEmpty(parsedResponse.videoId) parsedResponse["videoId"] = videoId end if return parsedResponse 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 = invalid retry = true if options <> invalid if options.DoesExist("cancellation") cancellation = options.cancellation end if if options.DoesExist("retry") retry = options.retry end if end if 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 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 feeds = Innertube.ParseResponseDataForFeeds(responseData) if feeds.Count() > 0 return { videos: ValidArray(feeds[0].items) } 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 searchFilters = invalid continuation = "" cancellation = invalid raw = false if options <> invalid if options.DoesExist("searchFilters") searchFilters = options.searchFilters end if if options.DoesExist("continuation") continuation = options.continuation end if if options.DoesExist("cancellation") cancellation = options.cancellation end if if options.DoesExist("raw") raw = options.raw end if end if return Innertube.Search(query, searchFilters, continuation, cancellation, raw) end function function GetTrending(options = invalid as object) as object cancellation = invalid params = "" raw = false if options <> invalid if options.DoesExist("cancellation") cancellation = options.cancellation end if if options.DoesExist("type") trendingType = LCase(ValidString(options.type)) if trendingType = "music" ' {"44:proto": {"3:string": "ytma_charts"}} params = "4gINGgt5dG1hX2NoYXJ0cw%3D%3D" else if trendingType = "gaming" ' {"44:proto": {"3:string": "gaming_corpus_most_popular"}} params = "4gIcGhpnYW1pbmdfY29ycHVzX21vc3RfcG9wdWxhcg%3D%3D" else if trendingType = "movies" ' {"44:proto": {"3:string": "trailers"}} params = "4gIKGgh0cmFpbGVycw%3D%3D" end if end if if options.DoesExist("raw") raw = options.raw end if end if request = Innertube.CreateBrowseRequest("FEtrending", Innertube.ClientType.WEB, params) request.Cancellation(cancellation) if raw request.LogCurlCommand() request.NoCache() 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(), { skipCreatorOnTheRise: true }) 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(browserId as string, options = invalid as object) as object cancellation = invalid accessToken = invalid continuation = "" if options <> invalid if options.DoesExist("cancellation") cancellation = options.cancellation end if if options.DoesExist("accessToken") accessToken = options.accessToken end if if options.DoesExist("continuation") continuation = options.continuation end if end if request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv, "", continuation) 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 json = response.Json() return Innertube.ParseResponseDataForFeeds(json) end function function GetChannel(channelId as string, options = invalid as object) as object continuation = "" params = "" cancellation = invalid raw = false if options <> invalid if options.DoesExist("continuation") continuation = options.continuation end if if options.DoesExist("params") params = options.params end if if options.DoesExist("cancellation") cancellation = options.cancellation end if if options.DoesExist("raw") raw = options.raw end if end if request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, params, continuation) request.Cancellation(cancellation) if raw request.LogCurlCommand() request.NoCache() 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(response.Json()) 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 GetPlaylist(playlistId as string, options = invalid as object) as object continuation = "" cancellation = invalid raw = false if options <> invalid if options.DoesExist("continuation") continuation = options.continuation end if if options.DoesExist("cancellation") cancellation = options.cancellation end if if options.DoesExist("raw") raw = options.raw end if end if if not playlistId.StartsWith("VL") playlistId = "VL" + playlistId end if request = Innertube.CreateBrowseRequest(playlistId, Innertube.ClientType.Web, "", continuation) request.Cancellation(cancellation) if raw request.LogCurlCommand() request.NoCache() 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(response.Json()) 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 = "" cancellation = invalid raw = false if options <> invalid if options.DoesExist("videoId") videoId = options.videoId end if if options.DoesExist("cancellation") cancellation = options.cancellation end if if options.DoesExist("raw") raw = options.raw end if end if args = { "playlistId": mixId } if videoId <> "" args["videoId"] = videoId end if request = Innertube.CreateNextRequest(args, "") request.Cancellation(cancellation) if raw request.LogCurlCommand() request.NoCache() end if response = request.Await() if not response.IsSuccess() return { error: response.ErrorMessage() } end if if raw return response.Json() end if return Innertube.ParseMixPageResponseData(response.Json()) end function function ResolveUrl(url as string, options = invalid as object) as object cancellation = invalid if options <> invalid if options.DoesExist("cancellation") cancellation = options.cancellation end if end if 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 AuthRefreshAccessTokenIfNeeded(accessToken as object, cancellation = invalid as object) as boolean if not IsAssociativeArray(accessToken) return false end if nowSeconds = TimeUtils.Now().AsSeconds() expiresTimestamp = accessToken["expires_timestamp"] if expiresTimestamp = invalid or expiresTimestamp < nowSeconds 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 end if return false end function function AuthRevokeAccessToken(accessToken as object, cancellation = invalid as object) as boolean if not IsAssociativeArray(accessToken) return false end if return Innertube.RevokeAccessToken(accessToken["accessToken"], cancellation) end function function AuthListAccounts(accessToken as string, cancellation = invalid as object) as object return Innertube.ListAccounts(accessToken, cancellation) end function end namespace