diff --git a/CHANGELOG.md b/CHANGELOG.md index d641e714..66844984 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Attempt to fix `No valid bitrates` error by adding PoToken generation in server and web app +- Attempt to fix `No valid bitrates` error ### Removed diff --git a/playlet-lib/src/components/Dialog/YouTubeLoginAccountItemUtils.bs b/playlet-lib/src/components/Dialog/YouTubeLoginAccountItemUtils.bs index 66853669..e7ff84f2 100644 --- a/playlet-lib/src/components/Dialog/YouTubeLoginAccountItemUtils.bs +++ b/playlet-lib/src/components/Dialog/YouTubeLoginAccountItemUtils.bs @@ -12,7 +12,6 @@ namespace YouTubeLoginAccountItemUtils end if profile.username = username profile.activeIdentifyToken = accountItem.activeIdentifyToken - profile.selectActiveIdentityEndpoint = accountItem.selectActiveIdentityEndpoint profile.thumbnail = accountItem.accountPhoto profile.accessToken = accessToken.accessToken profile.refreshToken = accessToken.refreshToken diff --git a/playlet-lib/src/components/Services/Innertube/Context.bs b/playlet-lib/src/components/Services/Innertube/Context.bs index 410abd8d..20584712 100644 --- a/playlet-lib/src/components/Services/Innertube/Context.bs +++ b/playlet-lib/src/components/Services/Innertube/Context.bs @@ -51,12 +51,13 @@ namespace Innertube function CreateContext(client as Innertube.ClientType, deviceInfo as object, options = invalid as object) as object contextClient = invalid + livingRoomPoTokenId = OptionUtils.Get(options, "livingRoomPoTokenId") if client = ClientType.Web contextClient = CreateContextClientWeb(deviceInfo) else if client = ClientType.IOS contextClient = CreateContextClientIOS(deviceInfo) else if client = ClientType.Tv or client = ClientType.TvDowngraded - contextClient = CreateContextClientTv(deviceInfo, client) + contextClient = CreateContextClientTv(deviceInfo, client, livingRoomPoTokenId) else throw "Invalid client type" end if @@ -163,12 +164,12 @@ namespace Innertube } end function - function CreateContextClientTv(deviceInfo as object, client as Innertube.ClientType) as object + function CreateContextClientTv(deviceInfo as object, client as Innertube.ClientType, livingRoomPoTokenId = "" as dynamic) as object tvClientVersion = INNERTUBE_TV_CLIENT_VERSION if client = ClientType.TvDowngraded tvClientVersion = INNERTUBE_TV_CLIENT_VERSION_DOWNGRADED end if - return { + contextClient = { "hl": GetCurrentLocale(deviceInfo) "gl": GetContentRegion(deviceInfo) "remoteHost": "" @@ -205,6 +206,10 @@ namespace Innertube "playerType": "UNIPLAYER" "connectionType": "CONN_CELLULAR_4G" } + if not StringUtils.IsNullOrEmpty(livingRoomPoTokenId) + contextClient.tvAppInfo["livingRoomPoTokenId"] = livingRoomPoTokenId + end if + return contextClient end function function GetCurrentLocale(deviceInfo as object) as string diff --git a/playlet-lib/src/components/Services/Innertube/Innertube.bs b/playlet-lib/src/components/Services/Innertube/Innertube.bs index 9d57603f..38c3e472 100644 --- a/playlet-lib/src/components/Services/Innertube/Innertube.bs +++ b/playlet-lib/src/components/Services/Innertube/Innertube.bs @@ -4,29 +4,23 @@ import "pkg:/components/Services/Innertube/Constants.bs" import "pkg:/source/utils/StringUtils.bs" function Init() - m.top.observeField("requestVisitorData", FuncName(OnRequestVisitorData)) + m.top.observeField("requestSessionData", FuncName(OnRequestSessionData)) end function function OnNodeReady() - OnRequestVisitorData() + QueueSessionDataJob() end function -function OnRequestVisitorData() as void - if m.innertubeSessionDataJob <> invalid and not m.innertubeSessionDataJob.done +function OnRequestSessionData() as void + sessionData = m.top.sessionData + if IsAssociativeArray(sessionData) and not StringUtils.IsNullOrEmpty(sessionData.visitorData) and not StringUtils.IsNullOrEmpty(sessionData.livingRoomPoTokenId) return end if - - RequestVisitorData() + QueueSessionDataJob() end function -function RequestVisitorData() as void - if m.innertubeSessionDataJob <> invalid - m.innertubeSessionDataJob.cancel = true - m.innertubeSessionDataJob = invalid - end if - - visitorData = m.top.visitorData - if not StringUtils.IsNullOrEmpty(visitorData) +function QueueSessionDataJob() as void + if m.innertubeSessionDataJob <> invalid and not m.innertubeSessionDataJob.done return end if @@ -41,8 +35,4 @@ end function function OnInnertubeSessionDataJobDone(event as object) as void JobSystem.UnobserveCallback(event.getRoSGNode()) m.innertubeSessionDataJob = invalid - if StringUtils.IsNullOrEmpty(m.top.visitorData) - ' Trigger observers in case the job threw an error and didn't set the visitorData - m.top.visitorData = "" - end if end function diff --git a/playlet-lib/src/components/Services/Innertube/Innertube.xml b/playlet-lib/src/components/Services/Innertube/Innertube.xml index 31916000..a54d68e7 100644 --- a/playlet-lib/src/components/Services/Innertube/Innertube.xml +++ b/playlet-lib/src/components/Services/Innertube/Innertube.xml @@ -1,8 +1,7 @@ - - - + + \ No newline at end of file diff --git a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs index dfdf4aff..97a0f4f7 100644 --- a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs +++ b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs @@ -28,13 +28,6 @@ namespace InnertubeService accessToken = OptionUtils.Get(options, "accessToken") raw = OptionUtils.GetOrDefault(options, "raw", false) - if not StringUtils.IsNullOrEmpty(accessToken) - profileNode = OptionUtils.Get(options, "profileNode") - if profileNode <> invalid - options["datasyncIdToken"] = GetProfileDatasyncIdToken(profileNode, accessToken, OptionUtils.Get(options, "profilesService"), cancellation) - end if - end if - nextRequest = invalid if fetchNext nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, options) @@ -767,53 +760,6 @@ namespace InnertubeService return Innertube.ListAccounts(accessToken, cancellation) end function - function GetProfileDatasyncIdToken(profileNode as object, accessToken as string, profilesService as object, cancellation as object) as string - endpoint = profileNode.selectActiveIdentityEndpoint - if not IsAssociativeArray(endpoint) or endpoint.Count() = 0 - endpoint = BackfillSelectActiveIdentityEndpoint(profileNode, accessToken, profilesService, cancellation) - end if - return Innertube.GetDatasyncIdToken(endpoint) - end function - - ' The identity used to bind GVS poTokens: the signed-in profile's datasyncIdToken, - ' falling back to visitorData when logged out (or when no datasyncIdToken is available). - function GetCurrentPoTokenIdentity(profilesService as object, innertubeNode as object) as string - currentProfile = profilesService.currentProfile - if currentProfile <> invalid and currentProfile.type = "youtube" - accessToken = currentProfile.accessToken - if not StringUtils.IsNullOrEmpty(accessToken) - ' Signed in: bind to the datasyncIdToken, matching the decipher request's identity. - return GetProfileDatasyncIdToken(currentProfile, accessToken, profilesService, invalid) - end if - end if - return innertubeNode.visitorData - end function - - function BackfillSelectActiveIdentityEndpoint(profileNode as object, accessToken as string, profilesService as object, cancellation as object) as object - LogInfo("Backfilling selectActiveIdentityEndpoint for signed-in profile") - accounts = Innertube.ListAccounts(accessToken, cancellation) - if not IsArray(accounts) - return invalid - end if - - for each account in accounts - if account.activeIdentifyToken <> profileNode.activeIdentifyToken - continue for - end if - endpoint = account.selectActiveIdentityEndpoint - if IsAssociativeArray(endpoint) and endpoint.Count() > 0 - profileNode.selectActiveIdentityEndpoint = endpoint - if profilesService <> invalid - profilesService@.SaveUserProfilesToRegistry() - end if - return endpoint - end if - exit for - end for - - return invalid - end function - function GetDrmLicense(options as object) as dynamic request = Innertube.CreateGetDrmLicenceRequest(options) diff --git a/playlet-lib/src/components/Services/Innertube/InnertubeSessionDataJob.bs b/playlet-lib/src/components/Services/Innertube/InnertubeSessionDataJob.bs index a4076ad7..ad45bb19 100644 --- a/playlet-lib/src/components/Services/Innertube/InnertubeSessionDataJob.bs +++ b/playlet-lib/src/components/Services/Innertube/InnertubeSessionDataJob.bs @@ -6,23 +6,50 @@ function ExecuteJob() as void innertubeNode = JobGetInput().innertube cached = Innertube.ReadSessionDataFromRegistry() - if cached <> invalid and not StringUtils.IsNullOrEmpty(cached.visitorData) - if IsInt(cached.timestamp) - innertubeNode.timestamp = cached.timestamp - end if - innertubeNode.visitorData = cached.visitorData - if Innertube.IsSessionDataFresh(cached) - return - end if + cachedVisitorData = "" + cachedLivingRoomPoTokenId = "" + if IsAssociativeArray(cached) + cachedVisitorData = ValidString(cached.visitorData) + cachedLivingRoomPoTokenId = ValidString(cached.livingRoomPoTokenId) end if - fetched = Innertube.RequestSessionData(JobGetCancellation()) - if fetched <> invalid - Innertube.SaveSessionDataToRegistry(fetched) - innertubeNode.timestamp = fetched.timestamp - innertubeNode.visitorData = fetched.visitorData - else if StringUtils.IsNullOrEmpty(innertubeNode.visitorData) - ' Refresh failed and we never had an id — wake a cold waiter to fail. Never blank a valid id. - innertubeNode.visitorData = "" + ' Publish the cached values immediately so playback isn't blocked while /tv is fetched. + innertubeNode.sessionData = { + "visitorData": cachedVisitorData + "livingRoomPoTokenId": cachedLivingRoomPoTokenId + } + + fresh = Innertube.RequestTvClientData(JobGetCancellation()) + if fresh = invalid + return end if + + visitorData = cachedVisitorData + timestamp = 0 + if Innertube.IsVisitorDataFresh(cached) + visitorData = cached.visitorData + timestamp = cached.timestamp + else if not StringUtils.IsNullOrEmpty(fresh.visitorData) + visitorData = fresh.visitorData + timestamp = fresh.timestamp + else if not StringUtils.IsNullOrEmpty(cachedVisitorData) + visitorData = cachedVisitorData + timestamp = cached.timestamp + end if + + livingRoomPoTokenId = cachedLivingRoomPoTokenId + if not StringUtils.IsNullOrEmpty(fresh.livingRoomPoTokenId) + livingRoomPoTokenId = fresh.livingRoomPoTokenId + end if + + Innertube.SaveSessionDataToRegistry({ + "timestamp": timestamp + "visitorData": visitorData + "livingRoomPoTokenId": livingRoomPoTokenId + }) + + innertubeNode.sessionData = { + "visitorData": visitorData + "livingRoomPoTokenId": livingRoomPoTokenId + } end function diff --git a/playlet-lib/src/components/Services/Innertube/OAuth.bs b/playlet-lib/src/components/Services/Innertube/OAuth.bs index 85bb02f5..cb4cafa4 100644 --- a/playlet-lib/src/components/Services/Innertube/OAuth.bs +++ b/playlet-lib/src/components/Services/Innertube/OAuth.bs @@ -248,7 +248,6 @@ namespace Innertube "accountByline": ParseText(accountItem["accountByline"]) "channelHandle": ParseText(accountItem["channelHandle"]) "activeIdentifyToken": ParseAccountItemIdentityToken(accountItem) - "selectActiveIdentityEndpoint": ValidAssociativeArray(ObjectUtils.Dig(accountItem, ["serviceEndpoint", "selectActiveIdentityEndpoint"])) } parsedAccounts.Push(parsedAccount) end for @@ -298,26 +297,6 @@ namespace Innertube return "" end function - function GetDatasyncIdToken(selectActiveIdentityEndpoint as object) as string - supportedTokens = ObjectUtils.Dig(selectActiveIdentityEndpoint, ["supportedTokens"]) - if not IsArray(supportedTokens) - return "" - end if - - for each supportedToken in supportedTokens - if not IsAssociativeArray(supportedToken) - continue for - end if - - datasyncIdToken = ObjectUtils.Dig(supportedToken, ["datasyncIdToken", "datasyncIdToken"]) - if not StringUtils.IsNullOrEmpty(datasyncIdToken) - return datasyncIdToken - end if - end for - - return "" - end function - function ToCamelCase(obj as object) as object if not IsAssociativeArray(obj) return obj diff --git a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs index 8d826dd7..179ea4a5 100644 --- a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs @@ -15,7 +15,7 @@ namespace Innertube cancellation = OptionUtils.Get(options, "cancellation") visitorData = OptionUtils.Get(options, "visitorData") accessToken = OptionUtils.Get(options, "accessToken") - datasyncIdToken = OptionUtils.Get(options, "datasyncIdToken") + livingRoomPoTokenId = OptionUtils.Get(options, "livingRoomPoTokenId") cpn = InnertubeService.CreateClientPlaybackNonce() isTv = (client = Innertube.ClientType.Tv or client = Innertube.ClientType.TvDowngraded) @@ -68,12 +68,15 @@ namespace Innertube if not StringUtils.IsNullOrEmpty(visitorData) and not useAccessToken request.Header("x-goog-visitor-id", visitorData) - request.poTokenIdentity = visitorData - else if useAccessToken and not StringUtils.IsNullOrEmpty(datasyncIdToken) - request.poTokenIdentity = datasyncIdToken + end if + + if not StringUtils.IsNullOrEmpty(livingRoomPoTokenId) + request.poTokenIdentity = livingRoomPoTokenId end if if not StringUtils.IsNullOrEmpty(request.poTokenIdentity) + ' NOTE: local potoken (browser-minted) is currently not in use. + ' GetValidPoTokenForIdentity should return "", and the backend would mint the potoken. request.poToken = Innertube.PoTokens.GetValidPoTokenForIdentity(request.poTokenIdentity) end if diff --git a/playlet-lib/src/components/Services/Innertube/SessionData.bs b/playlet-lib/src/components/Services/Innertube/SessionData.bs index adfb3341..45bc10f2 100644 --- a/playlet-lib/src/components/Services/Innertube/SessionData.bs +++ b/playlet-lib/src/components/Services/Innertube/SessionData.bs @@ -1,7 +1,8 @@ import "pkg:/components/Services/Innertube/Constants.bs" +import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/source/services/HttpClient.bs" +import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/Logging.bs" -import "pkg:/source/utils/ObjectUtils.bs" import "pkg:/source/utils/RegistryUtils.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/TimeUtils.bs" @@ -10,8 +11,9 @@ namespace Innertube const SESSION_DATA_VERSION = 1 const INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS = 60 * 60 * 24 * 14 ' 14 days + const TV_CLIENT_DATA_MAX_ATTEMPTS = 3 - function IsSessionDataFresh(sessionData as object) as boolean + function IsVisitorDataFresh(sessionData as object) as boolean if sessionData = invalid or not IsInt(sessionData.timestamp) return false end if @@ -19,48 +21,79 @@ namespace Innertube return nowSeconds - sessionData.timestamp <= INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS end function - function RequestSessionData(cancellation = invalid as object) as object - request = HttpClient.Get("https://www.youtube.com/sw.js_data") - request.Headers({ - "Accept-Language": "en-US,en;q=0.9" - "User-Agent": INNERTUBE_WEB_USER_AGENT - "Accept": "*/*" - "Referer": "https://www.youtube.com/sw.js" - }) - request.Cancellation(cancellation) - request.TryCount(2) - request.NoCache() + function RequestTvClientData(cancellation = invalid as object) as object + visitorData = "" + livingRoomPoTokenId = "" - response = request.Await() - if not response.IsSuccess() - LogError("Failed to fetch session data: " + response.ErrorMessage()) - return invalid - end if + for attempt = 1 to TV_CLIENT_DATA_MAX_ATTEMPTS + text = FetchTvClientPage(cancellation) + if text <> invalid + if StringUtils.IsNullOrEmpty(visitorData) + visitorData = ExtractEscapedJsonString(text, "visitorData") + end if + if StringUtils.IsNullOrEmpty(livingRoomPoTokenId) + livingRoomPoTokenId = ExtractEscapedJsonString(text, "LIVING_ROOM_PO_TOKEN_ID") + end if + if not StringUtils.IsNullOrEmpty(visitorData) and not StringUtils.IsNullOrEmpty(livingRoomPoTokenId) + exit for + end if + end if + if CancellationUtils.IsCancelled(cancellation) + exit for + end if + if attempt < TV_CLIENT_DATA_MAX_ATTEMPTS + sleep(attempt * 1000) + end if + end for - text = response.Text() - text = text.Replace(`)]}'`, "") - - json = StringUtils.ParseJsonSafe(text) - if json = invalid - LogError("Failed to parse session data: " + text) - return invalid - end if - - visitorData = ObjectUtils.Dig(json, [0, 2, 0, 0, 13]) if StringUtils.IsNullOrEmpty(visitorData) - LogError("Failed to find visitorData in session data: " + text) + LogError("Could not extract visitorData from tv client data") + end if + if StringUtils.IsNullOrEmpty(livingRoomPoTokenId) + LogError("Could not extract livingRoomPoTokenId from tv client data") + end if + if StringUtils.IsNullOrEmpty(visitorData) and StringUtils.IsNullOrEmpty(livingRoomPoTokenId) return invalid end if return { "timestamp": TimeUtils.Now().AsSeconds() "visitorData": visitorData + "livingRoomPoTokenId": livingRoomPoTokenId } end function + function FetchTvClientPage(cancellation as object) as dynamic + request = HttpClient.Get("https://www.youtube.com/tv") + headers = Innertube.CreateHeaders(Innertube.ClientType.Tv) + headers["Referer"] = "https://www.youtube.com/tv" + request.Headers(headers) + request.Cancellation(cancellation) + request.NoCache() + + response = request.Await() + if not response.IsSuccess() + LogError("Failed to fetch tv client data:", response.ErrorMessage()) + return invalid + end if + return response.Text() + end function + + function ExtractEscapedJsonString(text as string, key as string) as string + regex = CreateObject("roRegex", `"${key}":"([^"]*)"`, "") + match = regex.Match(text) + if match.Count() < 2 + return "" + end if + decoded = StringUtils.ParseJsonSafe(`["${match[1]}"]`) + if not IsArray(decoded) or decoded.Count() <> 1 + return "" + end if + return decoded[0] + end function + function SaveSessionDataToRegistry(sessionData as object) as void sessionData.__version = SESSION_DATA_VERSION - RegistryUtils.Write(RegistryUtils.INNERTUBE_SESSION_DATA, FormatJson(sessionData)) end function @@ -70,13 +103,7 @@ namespace Innertube return invalid end if - sessionData = StringUtils.ParseJsonSafe(sessionData) - if sessionData = invalid - RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA) - return invalid - end if - - return sessionData + return StringUtils.ParseJsonSafe(sessionData) end function end namespace diff --git a/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs b/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs index d2b751a7..2b7c7310 100644 --- a/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs +++ b/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs @@ -58,7 +58,6 @@ function LoadProfilesFromRegistry() profileNode.accessToken = profile.accessToken profileNode.activeIdentifyToken = profile.activeIdentifyToken - profileNode.selectActiveIdentityEndpoint = profile.selectActiveIdentityEndpoint profileNode.refreshToken = profile.refreshToken profileNode.scope = profile.scope profileNode.tokenType = profile.tokenType @@ -183,7 +182,6 @@ function GetProfilesDto(includeAccessToken as boolean) as object profile["expiresTimestamp"] = profileNode.expiresTimestamp profile["clientId"] = profileNode.clientId profile["clientSecret"] = profileNode.clientSecret - profile["selectActiveIdentityEndpoint"] = ValidAssociativeArray(profileNode.selectActiveIdentityEndpoint) end if userProfiles.profiles.Push(profile) diff --git a/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs b/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs index 41cc7ae1..451a27da 100644 --- a/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs +++ b/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs @@ -36,13 +36,13 @@ function ExecuteJob() as void cancellation = JobGetCancellation() if backend = "playlet" - visitorData = GetVisitorData(innertubeNode, cancellation) - if visitorData.cancel = true + sessionData = GetSessionData(innertubeNode, cancellation) + if sessionData.cancel = true JobCancel() return end if - if visitorData.error <> invalid - JobError(visitorData.error) + if sessionData.error <> invalid + JobError(sessionData.error) return end if @@ -59,7 +59,8 @@ function ExecuteJob() as void metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, { "cancellation": cancellation "credentialTransferToken": loungeServiceNode.credentialTransferToken - "visitorData": visitorData.visitorData + "visitorData": sessionData.visitorData + "livingRoomPoTokenId": sessionData.livingRoomPoTokenId "accessToken": accessToken "onBehalfOfUser": onBehalfOfUser "profileNode": profileNode @@ -164,48 +165,42 @@ function ExecuteJob() as void end if end function -function GetVisitorData(innertubeNode as object, cancellation as object) as object - port = CreateObject("roMessagePort") +function GetSessionData(innertubeNode as object, cancellation as object) as object + sessionData = innertubeNode.sessionData + if SessionDataComplete(sessionData) + return sessionData + end if - MessagePortUtils.ObserveFieldScopedExSafe(innertubeNode, "visitorData", port) + port = CreateObject("roMessagePort") + MessagePortUtils.ObserveFieldScopedExSafe(innertubeNode, "sessionData", port) CancellationUtils.ObserveCancellationScoped(cancellation, port) - visitorData = innertubeNode.visitorData - if not StringUtils.IsNullOrEmpty(visitorData) - innertubeNode.unobserveFieldScoped("visitorData") - CancellationUtils.UnobserveCancellationScoped(cancellation) - - return { - visitorData: visitorData - } - end if - - innertubeNode.requestVisitorData = true + innertubeNode.requestSessionData = true message = wait(30000, port) - innertubeNode.unobserveFieldScoped("visitorData") + innertubeNode.unobserveFieldScoped("sessionData") CancellationUtils.UnobserveCancellationScoped(cancellation) - if message <> invalid - if CancellationUtils.IsCancellationEvent(cancellation, message) - return { - cancel: true - } - end if - visitorData = message.getData() + if message <> invalid and CancellationUtils.IsCancellationEvent(cancellation, message) + return { + cancel: true + } end if - if StringUtils.IsNullOrEmpty(visitorData) - return { - error: "Failed to get visitor data. Please try again later." - } + sessionData = innertubeNode.sessionData + if SessionDataComplete(sessionData) + return sessionData end if return { - visitorData: visitorData + error: "Failed to get session data. Please try again later." } end function +function SessionDataComplete(sessionData as object) as boolean + return IsAssociativeArray(sessionData) and not StringUtils.IsNullOrEmpty(sessionData.visitorData) and not StringUtils.IsNullOrEmpty(sessionData.livingRoomPoTokenId) +end function + function CreateStreamUrls(metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object instance = service.GetInstance() proxyVideos = preferences["invidious.proxy_videos"] diff --git a/playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs b/playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs index b1f6cfdc..fde657e1 100644 --- a/playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs +++ b/playlet-lib/src/components/VideoQueue/VideoQueueViewContentJob.bs @@ -21,12 +21,18 @@ function ExecuteJob() as void backend = preferencesNode["backend.selected"] + visitorData = "" + sessionData = innertubeNode.sessionData + if IsAssociativeArray(sessionData) + visitorData = ValidString(sessionData.visitorData) + end if + requestOptions = { cacheSeconds: 8640000 ' 100 days cancellation: cancellation tryCount: 1 fetchNext: false - visitorData: innertubeNode.visitorData + visitorData: visitorData } ' TODO:P1: Use InnertubeService.GetVideoInfoBatched with an array instead of loading each video individually diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs index dd174dbc..bce18329 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs @@ -20,7 +20,12 @@ namespace Http function GetPoToken(context as object) as object response = context.response - identity = InnertubeService.GetCurrentPoTokenIdentity(m.profilesService, m.innertube) + identity = "" + sessionData = m.innertube.sessionData + if IsAssociativeArray(sessionData) + identity = ValidString(sessionData.livingRoomPoTokenId) + end if + if StringUtils.IsNullOrEmpty(identity) response.Default(503, "No current identity") return true @@ -64,8 +69,20 @@ namespace Http return true end if + + identity = "" + sessionData = m.innertube.sessionData + if IsAssociativeArray(sessionData) + identity = ValidString(sessionData.livingRoomPoTokenId) + end if + + if StringUtils.IsNullOrEmpty(identity) + response.Default(503, "No current identity") + return true + end if + ' Reject identities other than the device's current one (guards the shared registry). - if payload.identity <> InnertubeService.GetCurrentPoTokenIdentity(m.profilesService, m.innertube) + if payload.identity <> identity response.Default(409, "identity is not the device's current identity") return true end if @@ -146,7 +163,7 @@ namespace Http if currentProfile <> invalid and currentProfile.type = "youtube" options["accessToken"] = currentProfile.accessToken else - options["visitorData"] = m.innertube.visitorData + options["visitorData"] = m.innertube.sessionData.visitorData end if drmResponse = InnertubeService.GetDrmLicense(options) diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs index 252310ce..a405cd87 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs @@ -548,9 +548,15 @@ namespace Http raw = request.query.raw <> invalid videoInfoBatched = request.query.video_info_batched <> invalid + visitorData = "" + sessionData = m.innertube.sessionData + if IsAssociativeArray(sessionData) + visitorData = ValidString(sessionData.visitorData) + end if + options = { "raw": raw - "visitorData": m.innertube.visitorData + "visitorData": visitorData } if videoInfoBatched diff --git a/playlet-lib/src/config/preferences.json5 b/playlet-lib/src/config/preferences.json5 index 6eb76632..b3f0c7f9 100644 --- a/playlet-lib/src/config/preferences.json5 +++ b/playlet-lib/src/config/preferences.json5 @@ -315,14 +315,14 @@ displayText: "Mint PoToken", key: "dev.mint_potoken", description: "Mint a PoToken for the current identity.", - visibility: "web", + visibility: "off", svelteComponent: "MintPoTokenControl", }, { displayText: "Clear PoTokens", key: "dev.clear_potokens", description: "Clear all stored PoTokens.", - visibility: "web", + visibility: "off", svelteComponent: "ClearPoTokensControl", }, { diff --git a/playlet-lib/src/source/tests/Innertube/ExtractEscapedJsonString.spec.bs b/playlet-lib/src/source/tests/Innertube/ExtractEscapedJsonString.spec.bs new file mode 100644 index 00000000..09f21185 --- /dev/null +++ b/playlet-lib/src/source/tests/Innertube/ExtractEscapedJsonString.spec.bs @@ -0,0 +1,37 @@ +import "pkg:/components/Services/Innertube/SessionData.bs" + +namespace Tests + + @suite + class InnertubeExtractEscapedJsonStringTests extends Rooibos.BaseTestSuite + + @describe("Innertube.ExtractEscapedJsonString") + + @it("extracts a plain value") + function plain() + text = `noise "visitorData":"AbCd123" noise` + m.assertEqual(Innertube.ExtractEscapedJsonString(text, "visitorData"), "AbCd123") + end function + + @it("decodes the escaped = padding") + function decodesPadding() + bs = Chr(92) + text = `"LIVING_ROOM_PO_TOKEN_ID":"THWY0ox3FA4${bs}u003d"` + m.assertEqual(Innertube.ExtractEscapedJsonString(text, "LIVING_ROOM_PO_TOKEN_ID"), "THWY0ox3FA4=") + end function + + @it("decodes any escape, not just the padding") + function decodesAnyEscape() + bs = Chr(92) + text = `"key":"a${bs}u002fb"` + m.assertEqual(Innertube.ExtractEscapedJsonString(text, "key"), "a/b") + end function + + @it("returns empty string when the key is absent") + function keyAbsent() + m.assertEqual(Innertube.ExtractEscapedJsonString(`"other":"x"`, "visitorData"), "") + end function + + end class + +end namespace diff --git a/playlet-lib/src/source/tests/Innertube/GetDatasyncIdToken.spec.bs b/playlet-lib/src/source/tests/Innertube/GetDatasyncIdToken.spec.bs deleted file mode 100644 index e34a8ad5..00000000 --- a/playlet-lib/src/source/tests/Innertube/GetDatasyncIdToken.spec.bs +++ /dev/null @@ -1,54 +0,0 @@ -import "pkg:/components/Services/Innertube/OAuth.bs" - -namespace Tests - - @suite - class InnertubeGetDatasyncIdTokenTests extends Rooibos.BaseTestSuite - - @describe("Innertube.GetDatasyncIdToken") - - @it("returns the datasyncIdToken verbatim (brand account, both halves)") - function brandVerbatim() - endpoint = { - supportedTokens: [ - { pageIdToken: { pageId: "100000000000000000001" } } - { datasyncIdToken: { datasyncIdToken: "100000000000000000001||200000000000000000002" } } - ] - } - m.assertEqual(Innertube.GetDatasyncIdToken(endpoint), "100000000000000000001||200000000000000000002") - end function - - @it("returns the default-account token verbatim, keeping the empty second half") - function defaultEmptySecondHalf() - endpoint = { - supportedTokens: [ - { datasyncIdToken: { datasyncIdToken: "300000000000000000003||" } } - ] - } - m.assertEqual(Innertube.GetDatasyncIdToken(endpoint), "300000000000000000003||") - end function - - @it("returns empty string when no datasyncIdToken is present") - function noDatasyncToken() - endpoint = { - supportedTokens: [ - { pageIdToken: { pageId: "400000000000000000004" } } - { accountStateToken: { obfuscatedGaiaId: "500000000000000000005" } } - ] - } - m.assertEqual(Innertube.GetDatasyncIdToken(endpoint), "") - end function - - @it("returns empty string for an invalid endpoint") - function invalidEndpoint() - m.assertEqual(Innertube.GetDatasyncIdToken(invalid), "") - end function - - @it("returns empty string for an endpoint without supportedTokens") - function emptyEndpoint() - m.assertEqual(Innertube.GetDatasyncIdToken({}), "") - end function - - end class - -end namespace