From 9e3da6b67da83423d8dc486533078f052cf8bb6f Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Sat, 31 May 2025 14:40:33 -0400 Subject: [PATCH] Refactor for activeIdentityToken (#631) * Refactor for activeIdentityToken * Account selector stuff * Small refactor * Tweak * That's a wrap * comment * Lint fix * Localize * Lint fix * Close view on error * parse error when gathering tracking urls --------- Co-authored-by: github-action linter --- CHANGELOG.md | 1 + .../FetchSubscriptionStatusTask.bs | 1 + .../ContentNode/ProfileContentNode.xml | 1 + .../Dialog/YouTubeLoginAccountItemUtils.bs | 27 ++ .../components/Dialog/YouTubeLoginDialog.bs | 46 ++- .../components/Dialog/YouTubeLoginDialog.xml | 1 + .../src/components/Dialog/YouTubeLoginTask.bs | 95 ++----- .../YouTubeAccountListItem.bs | 17 ++ .../YouTubeAccountListItem.xml | 31 +++ .../YouTubeAccountSelectionView.bs | 100 +++++++ .../YouTubeAccountSelectionView.xml | 41 +++ .../YouTubeAccountSelectionViewUtils.bs | 11 + .../Services/Innertube/BrowseEndpoint.bs | 15 +- .../components/Services/Innertube/Context.bs | 21 +- .../Services/Innertube/InnertubeService.bs | 261 +++++------------- .../Services/Innertube/NextEndpoint.bs | 13 +- .../components/Services/Innertube/OAuth.bs | 45 ++- .../Services/Innertube/PlayerEndpoint.bs | 83 +++--- .../Services/Innertube/ResolveUrlEndpoint.bs | 9 +- .../Services/Innertube/SearchEndpoint.bs | 41 +-- .../Innertube/SubscriptionEndpoint.bs | 30 +- .../Services/Invidious/InvidiousService.bs | 31 ++- .../Services/LoungeService/LoungeApi.bs | 4 +- .../Services/LoungeService/LoungeService.xml | 2 +- .../ProfilesService/ProfilesService.bs | 12 +- .../VideoPlayer/MarkVideoWatchedTask.bs | 3 + .../VideoPlayer/VideoContentTask.bs | 2 +- .../PlayletInvidiousBackendRouter.bs | 37 +++ playlet-lib/src/locale/en_US/translations.ts | 12 + playlet-lib/src/source/utils/Locale.bs | 3 + playlet-lib/src/source/utils/OptionUtils.bs | 23 +- 31 files changed, 606 insertions(+), 413 deletions(-) create mode 100644 playlet-lib/src/components/Dialog/YouTubeLoginAccountItemUtils.bs create mode 100644 playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountListItem.bs create mode 100644 playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountListItem.xml create mode 100644 playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionView.bs create mode 100644 playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionView.xml create mode 100644 playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionViewUtils.bs diff --git a/CHANGELOG.md b/CHANGELOG.md index 513a3b2c..ae4a5458 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - German translations +- Support for multi-accounts, such as brand accounts ### Fixed diff --git a/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusTask.bs b/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusTask.bs index 59b95347..8c60e72e 100644 --- a/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusTask.bs +++ b/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusTask.bs @@ -17,6 +17,7 @@ function FetchSubscriptionStatusTask(input as object) as object subscriptionStatus = InnertubeService.GetSubscriptionStatusForChannel(ucid, { cancellation: m.top.cancellation accessToken: authToken.token + onBehalfOfUser: authToken.activeIdentifyToken }) if subscriptionStatus.error <> invalid diff --git a/playlet-lib/src/components/ContentNode/ProfileContentNode.xml b/playlet-lib/src/components/ContentNode/ProfileContentNode.xml index 65d8cca0..e8d2e238 100644 --- a/playlet-lib/src/components/ContentNode/ProfileContentNode.xml +++ b/playlet-lib/src/components/ContentNode/ProfileContentNode.xml @@ -8,6 +8,7 @@ + diff --git a/playlet-lib/src/components/Dialog/YouTubeLoginAccountItemUtils.bs b/playlet-lib/src/components/Dialog/YouTubeLoginAccountItemUtils.bs new file mode 100644 index 00000000..e7ff84f2 --- /dev/null +++ b/playlet-lib/src/components/Dialog/YouTubeLoginAccountItemUtils.bs @@ -0,0 +1,27 @@ +import "pkg:/source/utils/StringUtils.bs" + +namespace YouTubeLoginAccountItemUtils + + function CreateProfileContentNode(accountItem as object, accessToken as object) as object + profile = CreateObject("roSGNode", "ProfileContentNode") + profile.type = "youtube" + profile.serverUrl = "http://127.0.0.1:8888/playlet-invidious-backend" + username = accountItem.channelHandle + if StringUtils.IsNullOrEmpty(username) + username = accountItem.accountByline + end if + profile.username = username + profile.activeIdentifyToken = accountItem.activeIdentifyToken + profile.thumbnail = accountItem.accountPhoto + profile.accessToken = accessToken.accessToken + profile.refreshToken = accessToken.refreshToken + profile.scope = accessToken.scope + profile.tokenType = accessToken.tokenType + profile.expiresIn = accessToken.expiresIn + profile.expiresTimestamp = accessToken.expiresTimestamp + profile.clientId = accessToken.clientId + profile.clientSecret = accessToken.clientSecret + + return profile + end function +end namespace diff --git a/playlet-lib/src/components/Dialog/YouTubeLoginDialog.bs b/playlet-lib/src/components/Dialog/YouTubeLoginDialog.bs index 48dd8657..e174c30e 100644 --- a/playlet-lib/src/components/Dialog/YouTubeLoginDialog.bs +++ b/playlet-lib/src/components/Dialog/YouTubeLoginDialog.bs @@ -1,6 +1,10 @@ +import "pkg:/components/Dialog/DialogUtils.bs" +import "pkg:/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionViewUtils.bs" import "pkg:/source/AsyncTask/AsyncTask.bs" import "pkg:/source/AsyncTask/Tasks.bs" +import "pkg:/source/utils/ErrorUtils.bs" import "pkg:/source/utils/Locale.bs" +import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/Types.bs" function Init() @@ -28,7 +32,47 @@ function OnNodeReady() m.task = AsyncTask.Start(Tasks.YouTubeLoginTask, { dialog: m.top profilesService: m.top.profilesService - }) + }, OnYouTubeLoginTaskResult) +end function + +function OnYouTubeLoginTaskResult(output as object) as void + m.task = invalid + + if output.cancelled + Close() + return + end if + + if not output.success or not output.result.success + ' output.error for unhandled exception + error = output.error + if error = invalid + ' output.result.error for network errors + error = output.result.error + end if + error = ErrorUtils.Format(error) + LogError(error) + DialogUtils.ShowDialogEx({ + message: error + title: Tr(Locale.Generic.Error) + large: true + }) + return + end if + + accounts = output.result.accounts + accessToken = output.result.accessToken + ' if accounts is invalid, we're going to assume a profile is already created. + if accounts = invalid or accessToken = invalid + Close() + return + end if + + ' The accountSelectionView will take over the creation of the profile. + accountSelectionView = YouTubeAccountSelectionViewUtils.Open(m.top.appController) + accountSelectionView.accessToken = accessToken + accountSelectionView.accounts = accounts + Close() end function function OnCodeSet(event as object) diff --git a/playlet-lib/src/components/Dialog/YouTubeLoginDialog.xml b/playlet-lib/src/components/Dialog/YouTubeLoginDialog.xml index 8e827f69..38775351 100644 --- a/playlet-lib/src/components/Dialog/YouTubeLoginDialog.xml +++ b/playlet-lib/src/components/Dialog/YouTubeLoginDialog.xml @@ -1,6 +1,7 @@ + diff --git a/playlet-lib/src/components/Dialog/YouTubeLoginTask.bs b/playlet-lib/src/components/Dialog/YouTubeLoginTask.bs index 8d426069..31f6b1a4 100644 --- a/playlet-lib/src/components/Dialog/YouTubeLoginTask.bs +++ b/playlet-lib/src/components/Dialog/YouTubeLoginTask.bs @@ -1,4 +1,5 @@ import "pkg:/components/Dialog/DialogUtils.bs" +import "pkg:/components/Dialog/YouTubeLoginAccountItemUtils.bs" import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/Logging.bs" @@ -17,13 +18,10 @@ function YouTubeLoginTask(input as object) as object end if if authCode.error <> invalid - LogError(authCode.error) - DialogUtils.ShowDialogEx({ - title: "Error" - message: authCode.error - large: true - }) - return invalid + return { + success: false + error: authCode.error + } end if url = InnertubeService.AuthGetActivationUrl(authCode) @@ -40,13 +38,10 @@ function YouTubeLoginTask(input as object) as object end if if accessToken.error <> invalid - LogError(accessToken.error) - DialogUtils.ShowDialogEx({ - title: "Error" - message: accessToken.error - large: true - }) - return invalid + return { + success: false + error: accessToken.error + } end if accounts = InnertubeService.AuthListAccounts(accessToken.accessToken, cancellation) @@ -56,63 +51,33 @@ function YouTubeLoginTask(input as object) as object end if if IsAssociativeArray(accounts) and accounts.error <> invalid - LogError(accounts.error) - DialogUtils.ShowDialogEx({ - title: "Error" - message: accounts.error - large: true - }) - return invalid + return { + success: false + error: accounts.error + } end if if not IsArray(accounts) or accounts.Count() = 0 - LogError("No accounts found") - DialogUtils.ShowDialogEx({ - title: "Error" - message: "No accounts found" - large: true - }) - return invalid + return { + success: false + error: Tr(Locale.Dialogs.NoValidAccountsFound) + } end if - selectedAccount = invalid - for each account in accounts - if ValidBool(account.isSelected) - selectedAccount = account - exit for - end if - end for + ' If there is only one account, we can skip the selection screen + ' and just create a profile + if accounts.Count() = 1 + profile = YouTubeLoginAccountItemUtils.CreateProfileContentNode(accounts[0], accessToken) + profilesNode@.LoginWithProfile(profile) - if selectedAccount = invalid - selectedAccount = accounts[0] + return { + success: true + } end if - profile = CreateProfileContentNode(selectedAccount, accessToken) - profilesNode@.LoginWithProfile(profile) - - dialogNode.close = true - - return invalid -end function - -function CreateProfileContentNode(account as object, accessToken as object) as object - profile = CreateObject("roSGNode", "ProfileContentNode") - profile.type = "youtube" - profile.serverUrl = "http://127.0.0.1:8888/playlet-invidious-backend" - username = account.channelHandle - if StringUtils.IsNullOrEmpty(username) - username = account.accountByline - end if - profile.username = username - profile.thumbnail = account.accountPhoto - profile.accessToken = accessToken.accessToken - profile.refreshToken = accessToken.refreshToken - profile.scope = accessToken.scope - profile.tokenType = accessToken.tokenType - profile.expiresIn = accessToken.expiresIn - profile.expiresTimestamp = accessToken.expiresTimestamp - profile.clientId = accessToken.clientId - profile.clientSecret = accessToken.clientSecret - - return profile + return { + success: true + accounts: accounts + accessToken: accessToken + } end function diff --git a/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountListItem.bs b/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountListItem.bs new file mode 100644 index 00000000..ee6cbc7c --- /dev/null +++ b/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountListItem.bs @@ -0,0 +1,17 @@ +import "pkg:/source/utils/Types.bs" + +function OnContentSet() as void + content = m.top.itemContent + if content = invalid + return + end if + + accountItem = content.accountItem + if not IsAssociativeArray(accountItem) + return + end if + + m.top.accountPhoto = accountItem.accountPhoto + m.top.text1 = accountItem.accountName + m.top.text2 = accountItem.channelHandle +end function diff --git a/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountListItem.xml b/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountListItem.xml new file mode 100644 index 00000000..cf58b11f --- /dev/null +++ b/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountListItem.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionView.bs b/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionView.bs new file mode 100644 index 00000000..5a0446d7 --- /dev/null +++ b/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionView.bs @@ -0,0 +1,100 @@ +import "pkg:/components/Dialog/YouTubeLoginAccountItemUtils.bs" +import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs" +import "pkg:/source/utils/FocusManagement.bs" +import "pkg:/source/utils/Locale.bs" +import "pkg:/source/utils/Logging.bs" +import "pkg:/source/utils/RemoteKeys.bs" +import "pkg:/source/utils/Types.bs" + +function Init() + m.accountList = m.top.FindNode("accountList") + m.accountList.ObserveField("itemSelected", FuncName(OnAccountSelected)) +end function + +function OnFocusChange() as void + if not m.top.focus + return + end if + + NodeSetFocus(m.accountList, true) +end function + +function OnKeyEvent(key as string, press as boolean) as boolean + if key = RemoteKeys.Options or key = RemoteKeys.Play or key = RemoteKeys.Pause or key = RemoteKeys.PlayOnly + ' A pass-through to the app controller, so it can toggle picture-in-picture and pause/play + return false + end if + + if key = RemoteKeys.Back and press + Close() + return true + end if + + return true +end function + +function Close() + m.top.appController@.PopScreen() +end function + +function OnAccountsChanged() as void + accounts = m.top.accounts + if not IsArray(accounts) or accounts.Count() = 0 + m.accountList.content = invalid + LogError(Tr(Locale.Dialogs.NoValidAccountsFound)) + Close() + return + end if + + content = CreateObject("roSGNode", "ContentNode") + accountNodes = [] + for each accountItem in accounts + if not IsAssociativeArray(accountItem) + continue for + end if + + accountNode = CreateObject("roSGNode", "ContentNode") + accountNode.addField("accountItem", "assocarray", false) + accountNode.accountItem = accountItem + accountNodes.Push(accountNode) + end for + + if accountNodes.Count() = 0 + m.accountList.content = invalid + LogError(Tr(Locale.Dialogs.NoValidAccountsFound)) + Close() + return + end if + + content.appendChildren(accountNodes) + m.accountList.content = content +end function + +function OnAccountSelected(event as object) as void + itemSelected = m.accountList.itemSelected + itemNode = m.accountList.content.GetChild(itemSelected) + if itemNode = invalid + LogError("Invalid item selected:", itemSelected) + Close() + return + end if + + accountItem = itemNode.accountItem + if not IsAssociativeArray(accountItem) + LogError("Invalid account item selected:", accountItem) + Close() + return + end if + + accessToken = m.top.accessToken + if accessToken = invalid or not IsAssociativeArray(accessToken) + LogError("No valid access token available for YouTube login.") + Close() + return + end if + + profileNode = YouTubeLoginAccountItemUtils.CreateProfileContentNode(accountItem, accessToken) + m.top.profilesService@.LoginWithProfile(profileNode) + + Close() +end function diff --git a/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionView.xml b/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionView.xml new file mode 100644 index 00000000..5e4dbbfe --- /dev/null +++ b/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionView.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionViewUtils.bs b/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionViewUtils.bs new file mode 100644 index 00000000..f1eb4be5 --- /dev/null +++ b/playlet-lib/src/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionViewUtils.bs @@ -0,0 +1,11 @@ +namespace YouTubeAccountSelectionViewUtils + + function Open(appController as object) as object + youTubeAccountSelectionView = CreateObject("roSGNode", "YouTubeAccountSelectionView") + + appController@.PushScreen(youTubeAccountSelectionView) + youTubeAccountSelectionView@.BindNode() + return youTubeAccountSelectionView + end function + +end namespace diff --git a/playlet-lib/src/components/Services/Innertube/BrowseEndpoint.bs b/playlet-lib/src/components/Services/Innertube/BrowseEndpoint.bs index 9a171a6f..4b245175 100644 --- a/playlet-lib/src/components/Services/Innertube/BrowseEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/BrowseEndpoint.bs @@ -1,14 +1,18 @@ import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/source/services/HttpClient.bs" +import "pkg:/source/utils/OptionUtils.bs" import "pkg:/source/utils/StringUtils.bs" namespace Innertube - function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, params = "" as string, continuation = "" as string) as object + function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, options = invalid as object) as object + params = OptionUtils.GetOrDefault(options, "params", "") + continuation = OptionUtils.GetOrDefault(options, "continuation", "") + deviceInfo = CreateObject("roDeviceInfo") payload = { - "context": Innertube.CreateContext(clienType, deviceInfo, "", "") + "context": Innertube.CreateContext(clienType, deviceInfo, options) } if not StringUtils.IsNullOrEmpty(continuation) @@ -21,12 +25,7 @@ namespace Innertube end if request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json", payload) - headers = { - "accept": "*/*" - "accept-language": "*" - } - headers.Append(Innertube.CreateHeaders(clienType)) - request.Headers(headers) + request.Headers(Innertube.CreateHeaders(clienType)) return request end function diff --git a/playlet-lib/src/components/Services/Innertube/Context.bs b/playlet-lib/src/components/Services/Innertube/Context.bs index 44396627..796b59a3 100644 --- a/playlet-lib/src/components/Services/Innertube/Context.bs +++ b/playlet-lib/src/components/Services/Innertube/Context.bs @@ -1,4 +1,5 @@ import "pkg:/components/Services/Innertube/Constants.bs" +import "pkg:/source/utils/OptionUtils.bs" import "pkg:/source/utils/StringUtils.bs" namespace Innertube @@ -12,18 +13,24 @@ namespace Innertube function CreateHeaders(clienType as Innertube.ClientType) as object if clienType = ClientType.Web return { + "accept": "*/*" + "accept-language": "*" "user-agent": INNERTUBE_WEB_USER_AGENT "x-youtube-client-name": INNERTUBE_WEB_CLIENT_NAME "x-youtube-client-version": INNERTUBE_WEB_CLIENT_VERSION } else if clienType = ClientType.IOS return { + "accept": "*/*" + "accept-language": "*" "user-agent": INNERTUBE_IOS_USER_AGENT "x-youtube-client-name": INNERTUBE_IOS_CLIENT_NAME "x-youtube-client-version": INNERTUBE_IOS_CLIENT_VERSION } else if clienType = ClientType.Tv return { + "accept": "*/*" + "accept-language": "*" "user-agent": INNERTUBE_TV_USER_AGENT "x-youtube-client-name": INNERTUBE_TV_CLIENT_NAME "x-youtube-client-version": INNERTUBE_TV_CLIENT_VERSION @@ -33,7 +40,7 @@ namespace Innertube end if end function - function CreateContext(clienType as Innertube.ClientType, deviceInfo as object, ctt as string, visitorData as string) as object + function CreateContext(clienType as Innertube.ClientType, deviceInfo as object, options = invalid as object) as object client = invalid if clienType = ClientType.Web client = CreateContextClientWeb(deviceInfo) @@ -45,6 +52,10 @@ namespace Innertube throw "Invalid client type" end if + credentialTransferToken = OptionUtils.Get(options, "credentialTransferToken") + visitorData = OptionUtils.Get(options, "visitorData") + onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser") + context = { "client": client "user": { @@ -57,9 +68,9 @@ namespace Innertube } } - if not StringUtils.IsNullOrEmpty(ctt) + if not StringUtils.IsNullOrEmpty(credentialTransferToken) context["user"]["credentialTransferTokens"] = [{ - "token": ctt + "token": credentialTransferToken "scope": "VIDEO" }] end if @@ -68,6 +79,10 @@ namespace Innertube context["client"]["visitorData"] = visitorData end if + if not StringUtils.IsNullOrEmpty(onBehalfOfUser) + context["user"]["onBehalfOfUser"] = onBehalfOfUser + end if + return context end function diff --git a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs index 9fd4e099..b9b8ca85 100644 --- a/playlet-lib/src/components/Services/Innertube/InnertubeService.bs +++ b/playlet-lib/src/components/Services/Innertube/InnertubeService.bs @@ -11,36 +11,17 @@ 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" namespace InnertubeService function GetVideoMetadata(videoId as string, options = invalid as object) as object - cancellation = invalid - fetchNext = true - ctt = "" - visitorData = "" - raw = false + cancellation = OptionUtils.Get(options, "cancellation") + fetchNext = OptionUtils.GetOrDefault(options, "fetchNext", true) + raw = OptionUtils.GetOrDefault(options, "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, Innertube.ClientType.IOS) + playerRequest = Innertube.CreatePlayerRequest(videoId, Innertube.ClientType.IOS, options) playerRequest.Cancellation(cancellation) if raw playerRequest.LogCurlCommand() @@ -51,7 +32,7 @@ namespace InnertubeService nextRequest = invalid nextResponse = invalid if fetchNext - nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, ctt) + nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, options) nextRequest.Cancellation(cancellation) if raw nextRequest.LogCurlCommand() @@ -111,20 +92,11 @@ namespace InnertubeService } 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 + cancellation = OptionUtils.Get(options, "cancellation") + retry = OptionUtils.GetOrDefault(options, "retry", true) params = Innertube.GetEncodedNextParams(videoIds) - request = Innertube.CreateNextRequest({ "params": params }, "") + request = Innertube.CreateNextRequest({ "params": params }) request.Cancellation(cancellation) response = request.Await() @@ -186,38 +158,24 @@ namespace InnertubeService end function function GetTrending(options = invalid as object) as object - cancellation = invalid + cancellation = OptionUtils.Get(options, "cancellation") + trendingType = LCase(OptionUtils.GetOrDefault(options, "type", "")) + disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false) + raw = OptionUtils.GetOrDefault(options, "raw", false) + params = "" - disableShorts = false - 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("disableShorts") - disableShorts = options.disableShorts - end if - if options.DoesExist("raw") - raw = options.raw - end if + 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 - request = Innertube.CreateBrowseRequest("FEtrending", Innertube.ClientType.WEB, params) + request = Innertube.CreateBrowseRequest("FEtrending", Innertube.ClientType.WEB, { params: params }) request.Cancellation(cancellation) if raw @@ -270,27 +228,12 @@ namespace InnertubeService end function function GetBrowseAuthenticatedPage(browserId as string, options = invalid as object) as object - cancellation = invalid - accessToken = invalid - continuation = "" - disableShorts = false + cancellation = OptionUtils.Get(options, "cancellation") + accessToken = OptionUtils.Get(options, "accessToken") + disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false) - 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 - if options.DoesExist("disableShorts") - disableShorts = options.disableShorts - end if - end if + request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv, options) - request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv, "", continuation) if accessToken <> invalid request.Header("Authorization", "Bearer " + accessToken) end if @@ -325,7 +268,7 @@ namespace InnertubeService cancellation = options.cancellation end if - playerRequest = Innertube.CreatePlayerRequest(videoId, "", "", Innertube.ClientType.Tv) + playerRequest = Innertube.CreatePlayerRequest(videoId, Innertube.ClientType.Tv, options) playerRequest.Cancellation(cancellation) playerRequest.Header("Authorization", "Bearer " + accessToken) @@ -338,6 +281,13 @@ namespace InnertubeService json = playerResponse.Json() + error = Innertube.ParsePlayerResponseForError(json) + if error <> "" + return { + error: error + } + end if + videostatsPlaybackUrl = ObjectUtils.Dig(json, ["playbackTracking", "videostatsPlaybackUrl", "baseUrl"]) videostatsWatchtimeUrl = ObjectUtils.Dig(json, ["playbackTracking", "videostatsWatchtimeUrl", "baseUrl"]) @@ -348,12 +298,9 @@ namespace InnertubeService end function function AuthMarkVideoWatched(videostatsPlaybackUrl as string, options as object) as boolean - cancellation = invalid - accessToken = options.accessToken - - if options.DoesExist("cancellation") - cancellation = options.cancellation - end if + cancellation = OptionUtils.Get(options, "cancellation") + accessToken = OptionUtils.Get(options, "accessToken") + onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser") videostatsPlaybackUrl = videostatsPlaybackUrl.replace("https://s.", "https://www.") queryParams = UrlUtils.ParseQueryComponents(videostatsPlaybackUrl) @@ -371,6 +318,9 @@ namespace InnertubeService 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() @@ -383,14 +333,9 @@ namespace InnertubeService end function function AuthMarkVideoWatchTime(time as float, videostatsWatchtimeUrl as string, options = invalid as object) as boolean - cancellation = invalid - accessToken = options.accessToken - - if options <> invalid - if options.DoesExist("cancellation") - cancellation = options.cancellation - end if - end if + cancellation = OptionUtils.Get(options, "cancellation") + accessToken = OptionUtils.Get(options, "accessToken") + onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser") timeStr = time.ToStr("%.3f") @@ -412,6 +357,9 @@ namespace InnertubeService 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() @@ -437,27 +385,10 @@ namespace InnertubeService end function function GetChannel(channelId as string, options = invalid as object) as object - continuation = "" - params = "" - cancellation = invalid - raw = false + cancellation = OptionUtils.Get(options, "cancellation") + raw = OptionUtils.GetOrDefault(options, "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 = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, options) request.Cancellation(cancellation) if raw request.LogCurlCommand() @@ -489,16 +420,10 @@ namespace InnertubeService end function function GetSubscriptionStatusForChannel(channelId as string, options = invalid as object) as object - cancellation = invalid - accessToken = options.accessToken + cancellation = OptionUtils.Get(options, "cancellation") + accessToken = OptionUtils.Get(options, "accessToken") - if options <> invalid - if options.DoesExist("cancellation") - cancellation = options.cancellation - end if - end if - - request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Tv, "", "") + request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Tv, options) request.Cancellation(cancellation) if accessToken <> invalid request.Header("Authorization", "Bearer " + accessToken) @@ -555,16 +480,10 @@ namespace InnertubeService end function function SubscribeToChannel(channelId as string, options = invalid as object) as object - cancellation = invalid - accessToken = options.accessToken + cancellation = OptionUtils.Get(options, "cancellation") + accessToken = OptionUtils.Get(options, "accessToken") - if options <> invalid - if options.DoesExist("cancellation") - cancellation = options.cancellation - end if - end if - - request = Innertube.CreateSubscribeRequest(channelId, "") + request = Innertube.CreateSubscribeRequest(channelId, options) request.Cancellation(cancellation) if accessToken <> invalid request.Header("Authorization", "Bearer " + accessToken) @@ -578,16 +497,10 @@ namespace InnertubeService end function function UnsubscribeFromChannel(channelId as string, options = invalid as object) as object - cancellation = invalid - accessToken = options.accessToken + cancellation = OptionUtils.Get(options, "cancellation") + accessToken = OptionUtils.Get(options, "accessToken") - if options <> invalid - if options.DoesExist("cancellation") - cancellation = options.cancellation - end if - end if - - request = Innertube.CreateUnsubscribeRequest(channelId, "") + request = Innertube.CreateUnsubscribeRequest(channelId, options) request.Cancellation(cancellation) if accessToken <> invalid request.Header("Authorization", "Bearer " + accessToken) @@ -601,25 +514,9 @@ namespace InnertubeService end function function GetPlaylist(playlistId as string, options = invalid as object) as object - continuation = "" - cancellation = invalid - raw = false - accessToken = invalid - - 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 - if options.DoesExist("accessToken") - accessToken = options.accessToken - end if - end if + cancellation = OptionUtils.Get(options, "cancellation") + raw = OptionUtils.GetOrDefault(options, "raw", false) + accessToken = OptionUtils.Get(options, "accessToken") if not playlistId.StartsWith("VL") playlistId = "VL" + playlistId @@ -630,7 +527,7 @@ namespace InnertubeService client = Innertube.ClientType.Tv end if - request = Innertube.CreateBrowseRequest(playlistId, client, "", continuation) + request = Innertube.CreateBrowseRequest(playlistId, client, options) request.Cancellation(cancellation) if accessToken <> invalid request.Header("Authorization", "Bearer " + accessToken) @@ -666,27 +563,15 @@ namespace InnertubeService 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 + videoId = OptionUtils.Get(options, "videoId") + cancellation = OptionUtils.Get(options, "cancellation") + raw = OptionUtils.GetOrDefault(options, "raw", false) args = { "playlistId": mixId } - if videoId <> "" + if not StringUtils.IsNullOrEmpty(videoId) args["videoId"] = videoId end if - request = Innertube.CreateNextRequest(args, "") + request = Innertube.CreateNextRequest(args) request.Cancellation(cancellation) if raw request.LogCurlCommand() @@ -715,13 +600,7 @@ namespace InnertubeService 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 + cancellation = OptionUtils.Get(options, "cancellation") request = Innertube.CreateResolveUrlRequest(url) request.Cancellation(cancellation) diff --git a/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs b/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs index 8b385fd2..27282ca9 100644 --- a/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/NextEndpoint.bs @@ -8,21 +8,18 @@ import "pkg:/source/utils/Types.bs" namespace Innertube - function CreateNextRequest(payloadArgs as object, ctt as string) as object + function CreateNextRequest(payloadArgs as object, options = invalid as object) as object deviceInfo = CreateObject("roDeviceInfo") + context = Innertube.CreateContext(Innertube.ClientType.Web, deviceInfo, options) + payload = { - "context": Innertube.CreateContext(Innertube.ClientType.Web, deviceInfo, ctt, "") + "context": context } payload.Append(payloadArgs) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json", payload) - headers = { - "accept": "*/*" - "accept-language": "*" - } - headers.Append(Innertube.CreateHeaders(Innertube.ClientType.Web)) - request.Headers(headers) + request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Web)) return request end function diff --git a/playlet-lib/src/components/Services/Innertube/OAuth.bs b/playlet-lib/src/components/Services/Innertube/OAuth.bs index e9e1c484..abd91784 100644 --- a/playlet-lib/src/components/Services/Innertube/OAuth.bs +++ b/playlet-lib/src/components/Services/Innertube/OAuth.bs @@ -196,7 +196,7 @@ namespace Innertube deviceInfo = CreateObject("roDeviceInfo") payload = { - "context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, "", "") + "context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo) "accountReadMask": { "returnOwner": true "returnBrandAccounts": true @@ -243,6 +243,7 @@ namespace Innertube "hasChannel": ValidBool(accountItem["hasChannel"]) "accountByline": ParseText(accountItem["accountByline"]) "channelHandle": ParseText(accountItem["channelHandle"]) + "activeIdentifyToken": ParseAccountItemIdentityToken(accountItem) } parsedAccounts.Push(parsedAccount) end for @@ -250,6 +251,48 @@ namespace Innertube return parsedAccounts end function + function ParseAccountItemIdentityToken(accountItem as object) as string + ' Although selected (default) account would have a token, we usually don't + ' need it, since we don't need to pass the "onBehalfOfUser" argument + ' when using selected account. + if ValidBool(accountItem.isSelected) + return "" + end if + + supportedTokens = ObjectUtils.Dig(accountItem, ["serviceEndpoint", "selectActiveIdentityEndpoint", "supportedTokens"]) + if not IsArray(supportedTokens) or supportedTokens.Count() = 0 + return "" + end if + + for each supportedToken in supportedTokens + if not IsAssociativeArray(supportedToken) + continue for + end if + + ' TODO:P2 should we stick with pageId, and ignore the rest? + pageId = ObjectUtils.Dig(supportedToken, ["pageIdToken", "pageId"]) + if not StringUtils.IsNullOrEmpty(pageId) + return pageId + end if + + obfuscatedGaiaId = ObjectUtils.Dig(supportedToken, ["accountStateToken", "obfuscatedGaiaId"]) + if not StringUtils.IsNullOrEmpty(obfuscatedGaiaId) + return obfuscatedGaiaId + end if + + datasyncIdToken = ObjectUtils.Dig(supportedToken, ["datasyncIdToken", "datasyncIdToken"]) + if not StringUtils.IsNullOrEmpty(datasyncIdToken) + ' "datasyncIdToken": "123456789012345678901||123456789012345678901" + match = /(\d+)\|\|(\d+)/.match(datasyncIdToken) + if match.Count() = 3 + return match[1] + end if + 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 ab5cde6f..e0307ebb 100644 --- a/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/PlayerEndpoint.bs @@ -6,12 +6,16 @@ import "pkg:/source/utils/Types.bs" namespace Innertube - function CreatePlayerRequest(videoId as string, ctt as string, visitorData as string, client as Innertube.ClientType) as object + function CreatePlayerRequest(videoId as string, client as Innertube.ClientType, options = invalid as object) as object + visitorData = OptionUtils.Get(options, "visitorData") + deviceInfo = CreateObject("roDeviceInfo") + context = Innertube.CreateContext(client, deviceInfo, options) + payload = { "videoId": videoId - "context": Innertube.CreateContext(client, deviceInfo, ctt, visitorData) + "context": context "playbackContext": { "contentPlaybackContext": { "vis": 0 @@ -32,48 +36,19 @@ namespace Innertube } request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload) - headers = { - "accept": "*/*" - "accept-language": "*" - } - headers.Append(Innertube.CreateHeaders(client)) - request.Headers(headers) + request.Headers(Innertube.CreateHeaders(client)) + if not StringUtils.IsNullOrEmpty(visitorData) + request.Header("x-goog-visitor-id", visitorData) + end if return request end function function ParseInnertubePlayerResponse(payload as object) as object - if not IsAssociativeArray(payload) + error = ParsePlayerResponseForError(payload) + if error <> "" return { - error: "Invalid payload" - } - end if - - playabilityStatus = payload["playabilityStatus"] - if not IsAssociativeArray(playabilityStatus) - return { - error: "Invalid playability status" - } - end if - - if playabilityStatus["status"] <> "OK" - errorMessage = "" - if IsString(playabilityStatus["reason"]) - errorMessage = playabilityStatus["reason"] - end if - - subreason = ParseText(ObjectUtils.Dig(playabilityStatus, ["errorScreen", "playerErrorMessageRenderer", "subreason"])) - - if subreason <> "" - errorMessage += `\n` + subreason - end if - - if errorMessage = "" - errorMessage = "Video not available" - end if - - return { - error: errorMessage + error: error } end if @@ -114,6 +89,38 @@ namespace Innertube return videoInfo 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 + + if playabilityStatus["status"] = "OK" + return "" + end if + + errorMessage = "" + if IsString(playabilityStatus["reason"]) + errorMessage = playabilityStatus["reason"] + end if + + subreason = ParseText(ObjectUtils.Dig(playabilityStatus, ["errorScreen", "playerErrorMessageRenderer", "subreason"])) + + if subreason <> "" + errorMessage += `\n` + subreason + end if + + if errorMessage = "" + errorMessage = "Video not available" + end if + + return errorMessage + end function + function ParseStoryboards(payload as object, lengthSeconds as integer) as object storyboard = ObjectUtils.Dig(payload, ["storyboards", "playerLiveStoryboardSpecRenderer", "spec"]) if IsString(storyboard) diff --git a/playlet-lib/src/components/Services/Innertube/ResolveUrlEndpoint.bs b/playlet-lib/src/components/Services/Innertube/ResolveUrlEndpoint.bs index 137de711..ac4e6ad3 100644 --- a/playlet-lib/src/components/Services/Innertube/ResolveUrlEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/ResolveUrlEndpoint.bs @@ -6,17 +6,12 @@ namespace Innertube deviceInfo = CreateObject("roDeviceInfo") payload = { - "context": CreateContext(ClientType.Web, deviceInfo, "", "") + "context": CreateContext(ClientType.Web, deviceInfo) "url": url } request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/navigation/resolve_url?prettyPrint=false&alt=json", payload) - headers = { - "accept": "*/*" - "accept-language": "*" - } - headers.Append(CreateHeaders(ClientType.Web)) - request.Headers(headers) + request.Headers(Innertube.CreateHeaders(ClientType.Web)) return request end function diff --git a/playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs b/playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs index da2cfd60..25253641 100644 --- a/playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/SearchEndpoint.bs @@ -2,42 +2,25 @@ import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/components/Services/Innertube/Parser.bs" import "pkg:/components/Services/Innertube/SearchFilters.bs" import "pkg:/source/services/HttpClient.bs" +import "pkg:/source/utils/OptionUtils.bs" import "pkg:/source/utils/Types.bs" namespace Innertube function Search(query as string, options = invalid as object) as object - searchFilters = invalid - continuation = "" - cancellation = invalid - disableShorts = false - 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("disableShorts") - disableShorts = options.disableShorts - end if - if options.DoesExist("raw") - raw = options.raw - end if - end if + searchFilters = OptionUtils.Get(options, "searchFilters") + continuation = OptionUtils.Get(options, "continuation") + cancellation = OptionUtils.Get(options, "cancellation") + disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false) + raw = OptionUtils.GetOrDefault(options, "raw", false) deviceInfo = CreateObject("roDeviceInfo") payload = { - context: Innertube.CreateContext(Innertube.ClientType.WEB, deviceInfo, "", "") + context: Innertube.CreateContext(Innertube.ClientType.WEB, deviceInfo) } - if continuation <> "" + if not StringUtils.IsNullOrEmpty(continuation) payload["continuation"] = continuation else payload["query"] = query @@ -50,13 +33,7 @@ namespace Innertube end if request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json", payload) - request.Headers({ - "accept": "*/*" - "accept-language": "*" - "user-agent": INNERTUBE_WEB_USER_AGENT - "x-youtube-client-name": INNERTUBE_WEB_CLIENT_NAME - "x-youtube-client-version": INNERTUBE_WEB_CLIENT_VERSION - }) + request.Headers(Innertube.CreateHeaders(ClientType.Web)) request.Cancellation(cancellation) if raw diff --git a/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs b/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs index 49b24a9d..5b5a9e05 100644 --- a/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs +++ b/playlet-lib/src/components/Services/Innertube/SubscriptionEndpoint.bs @@ -3,11 +3,11 @@ import "pkg:/source/utils/Types.bs" namespace Innertube - function CreateSubscribeRequest(channelIds as dynamic, params as string) as object + function CreateSubscribeRequest(channelIds as dynamic, options = invalid as object) as object deviceInfo = CreateObject("roDeviceInfo") payload = { - "context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, "", "") + "context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, options) } if IsString(channelIds) @@ -15,26 +15,17 @@ namespace Innertube end if payload["channelIds"] = channelIds - if not StringUtils.IsNullOrEmpty(params) - payload["params"] = params - end if - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/subscription/subscribe?prettyPrint=false&alt=json", payload) - headers = { - "accept": "*/*" - "accept-language": "*" - } - headers.Append(Innertube.CreateHeaders(Innertube.ClientType.Tv)) - request.Headers(headers) + request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv)) return request end function - function CreateUnsubscribeRequest(channelIds as dynamic, params as string) as object + function CreateUnsubscribeRequest(channelIds as dynamic, options = invalid as object) as object deviceInfo = CreateObject("roDeviceInfo") payload = { - "context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, "", "") + "context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, options) } if IsString(channelIds) @@ -42,17 +33,8 @@ namespace Innertube end if payload["channelIds"] = channelIds - if not StringUtils.IsNullOrEmpty(params) - payload["params"] = params - end if - request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/subscription/unsubscribe?prettyPrint=false&alt=json", payload) - headers = { - "accept": "*/*" - "accept-language": "*" - } - headers.Append(Innertube.CreateHeaders(Innertube.ClientType.Tv)) - request.Headers(headers) + request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv)) return request end function diff --git a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs index aba15245..34d08557 100644 --- a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs +++ b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs @@ -8,6 +8,7 @@ import "pkg:/source/utils/CryptoUtils.bs" import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/MessagePortUtils.bs" import "pkg:/source/utils/OptionUtils.bs" +import "pkg:/source/utils/OptionUtils.bs" import "pkg:/source/utils/RegistryUtils.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/TimeUtils.bs" @@ -140,21 +141,9 @@ namespace Invidious ' have the exact expiration time, we'll use 5 hours. Invidious currently ' Does a fresh fetch if the cache is older than 10 minutes. ' https://github.com/iv-org/invidious/blob/069e91d2a609b1df94bdfbb693335969b2a281d8/src/invidious/videos.cr#L349 - cacheSeconds = 18000 ' 5 hours - cancellation = invalid - tryCount = 2 - - if options <> invalid - if options.DoesExist("cacheSeconds") - cacheSeconds = options.cacheSeconds - end if - if options.DoesExist("cancellation") - cancellation = options.cancellation - end if - if options.DoesExist("tryCount") - tryCount = options.tryCount - end if - end if + cacheSeconds = OptionUtils.GetOrDefault(options, "cacheSeconds", 18000) ' 5 hours + cancellation = OptionUtils.Get(options, "cancellation") + tryCount = OptionUtils.GetOrDefault(options, "tryCount", 2) instance = m.GetInstance() url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}` @@ -197,6 +186,9 @@ namespace Invidious url = `${authToken.instance}${Invidious.AUTH_PLAYLISTS}/${playlistId}` request = HttpClient.Get(url) request.Headers(m.GetAuthenticationHeaders(authToken.token)) + if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken) + request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken) + end if else instance = m.GetInstance() url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}` @@ -319,6 +311,9 @@ namespace Invidious request.Url(authToken.instance + endpoint.url) request.Headers(m.GetAuthenticationHeaders(authToken.token)) + if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken) + request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken) + end if end if if endpoint.queryParams <> invalid @@ -786,6 +781,9 @@ namespace Invidious url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}` request = HttpClient.Post(url, "") + if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken) + request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken) + end if request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Cancellation(cancellation) @@ -800,6 +798,9 @@ namespace Invidious url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}` request = HttpClient.Delete(url) + if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken) + request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken) + end if request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Cancellation(cancellation) diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs b/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs index 40496561..95237342 100644 --- a/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs +++ b/playlet-lib/src/components/Services/LoungeService/LoungeApi.bs @@ -427,8 +427,8 @@ class LoungeApi ' Right now we just store only the last ctt, which works ok if we're casting one video at a time. ' But if the age restrcited video is added to the queue, we don't capture a token and playing the video would fail. ' These tokens need to be managed better, based on the video they belong to. - if not StringUtils.IsNullOrEmpty(commandArgs.ctt) - m.loungeServiceNode.ctt = commandArgs.ctt + if not StringUtils.IsNullOrEmpty(commandArgs[FIELD_CTT]) + m.loungeServiceNode.credentialTransferToken = commandArgs[FIELD_CTT] end if LoungeVideoQueue.SetPlaylist(m.videoQueueNode, m.invService, commandArgs) end function diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeService.xml b/playlet-lib/src/components/Services/LoungeService/LoungeService.xml index dfee9dce..b4cf4cd2 100644 --- a/playlet-lib/src/components/Services/LoungeService/LoungeService.xml +++ b/playlet-lib/src/components/Services/LoungeService/LoungeService.xml @@ -5,7 +5,7 @@ - + diff --git a/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs b/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs index 8443b029..da666e55 100644 --- a/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs +++ b/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs @@ -53,6 +53,7 @@ function LoadProfilesFromRegistry() profileNode.thumbnail = profile.thumbnail profileNode.accessToken = profile.accessToken + profileNode.activeIdentifyToken = profile.activeIdentifyToken profileNode.refreshToken = profile.refreshToken profileNode.scope = profile.scope profileNode.tokenType = profile.tokenType @@ -103,7 +104,7 @@ function MigrateExistingProfiles(userProfiles as object) as boolean return false end if - id = CreateProfileId(authToken.username, authToken.instance) + id = CreateProfileId(authToken.username, "", authToken.instance) for each profile in userProfiles.profiles if profile.id = id return false @@ -161,6 +162,7 @@ function GetProfilesDto(includeAccessToken as boolean) as object "id": profileNode.id "type": profileNode.type "username": profileNode.username + "activeIdentifyToken": profileNode.activeIdentifyToken "serverUrl": profileNode.serverUrl "thumbnail": profileNode.thumbnail "color": color @@ -191,7 +193,7 @@ end function function LoginWithProfile(newProfile as object) isNewProfile = true if StringUtils.IsNullOrEmpty(newProfile.id) - newProfile.id = CreateProfileId(newProfile.username, newProfile.serverUrl) + newProfile.id = CreateProfileId(newProfile.username, newProfile.activeIdentifyToken, newProfile.serverUrl) end if existingProfile = invalid @@ -206,6 +208,7 @@ function LoginWithProfile(newProfile as object) if not isNewProfile existingProfile.username = newProfile.username + existingProfile.activeIdentifyToken = newProfile.activeIdentifyToken existingProfile.thumbnail = newProfile.thumbnail existingProfile.accessToken = newProfile.accessToken existingProfile.refreshToken = newProfile.refreshToken @@ -333,6 +336,7 @@ function SetCurrentProfile(newActiveProfile as object) as void token: newActiveProfile.accessToken instance: newActiveProfile.serverUrl username: newActiveProfile.username + activeIdentifyToken: newActiveProfile.activeIdentifyToken profileNode: newActiveProfile } LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl) @@ -353,6 +357,6 @@ function RefreshActiveProfileState(activeProfile as object) as void end for end function -function CreateProfileId(username as string, serverUrl as string) as string - return "v1:" + CryptoUtils.GetMd5(username + serverUrl) +function CreateProfileId(username as string, activeIdentifyToken as string, serverUrl as string) as string + return "v1:" + CryptoUtils.GetMd5(username + activeIdentifyToken + serverUrl) end function diff --git a/playlet-lib/src/components/VideoPlayer/MarkVideoWatchedTask.bs b/playlet-lib/src/components/VideoPlayer/MarkVideoWatchedTask.bs index 8aabe919..33514058 100644 --- a/playlet-lib/src/components/VideoPlayer/MarkVideoWatchedTask.bs +++ b/playlet-lib/src/components/VideoPlayer/MarkVideoWatchedTask.bs @@ -23,6 +23,7 @@ function MarkVideoWatchedTask(input as object) as object playbackTrackingUrls = InnertubeService.AuthGetPlaybackTrackingUrls(videoId, { accessToken: authToken.token + onBehalfOfUser: authToken.activeIdentifyToken cancellation: cancellation }) @@ -38,6 +39,7 @@ function MarkVideoWatchedTask(input as object) as object markedAsWatched = InnertubeService.AuthMarkVideoWatched(playbackTrackingUrls.videostatsPlaybackUrl, { accessToken: authToken.token + onBehalfOfUser: authToken.activeIdentifyToken cancellation: cancellation }) if not markedAsWatched @@ -67,6 +69,7 @@ function MarkVideoWatchedTask(input as object) as object watchTime = message.getData() InnertubeService.AuthMarkVideoWatchTime(watchTime, playbackTrackingUrls.videostatsWatchtimeUrl, { accessToken: authToken.token + onBehalfOfUser: authToken.activeIdentifyToken cancellation: cancellation }) end while diff --git a/playlet-lib/src/components/VideoPlayer/VideoContentTask.bs b/playlet-lib/src/components/VideoPlayer/VideoContentTask.bs index ea08a41b..15bb0bf7 100644 --- a/playlet-lib/src/components/VideoPlayer/VideoContentTask.bs +++ b/playlet-lib/src/components/VideoPlayer/VideoContentTask.bs @@ -24,7 +24,7 @@ function VideoContentTask(input as object) as object if backend = "playlet" metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, { "cancellation": m.top.cancellation - "ctt": loungeServiceNode.ctt + "credentialTransferToken": loungeServiceNode.credentialTransferToken "visitorData": innertubeNode.visitorData }) else diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs index bb1d3cdc..52dc206c 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs @@ -69,6 +69,12 @@ namespace Http "accessToken": accessToken.Mid("Bearer ".Len()) "disableShorts": m.preferences["content_feed.disable_shorts"] } + + activeIdentifyToken = request.query.activeIdentifyToken + if not StringUtils.IsNullOrEmpty(activeIdentifyToken) + options.onBehalfOfUser = activeIdentifyToken + end if + continuation = request.query.continuation if not StringUtils.IsNullOrEmpty(continuation) options.continuation = continuation @@ -141,6 +147,12 @@ namespace Http options = { "accessToken": accessToken.Mid("Bearer ".Len()) } + + activeIdentifyToken = request.query.activeIdentifyToken + if not StringUtils.IsNullOrEmpty(activeIdentifyToken) + options.onBehalfOfUser = activeIdentifyToken + end if + continuation = request.query.continuation if not StringUtils.IsNullOrEmpty(continuation) options.continuation = continuation @@ -188,6 +200,11 @@ namespace Http "accessToken": accessToken.Mid("Bearer ".Len()) } + activeIdentifyToken = request.query.activeIdentifyToken + if not StringUtils.IsNullOrEmpty(activeIdentifyToken) + options.onBehalfOfUser = activeIdentifyToken + end if + continuation = request.query.continuation hasContinuation = not StringUtils.IsNullOrEmpty(continuation) if hasContinuation @@ -302,6 +319,11 @@ namespace Http "disableShorts": m.preferences["content_feed.disable_shorts"] } + activeIdentifyToken = request.query.activeIdentifyToken + if not StringUtils.IsNullOrEmpty(activeIdentifyToken) + options.onBehalfOfUser = activeIdentifyToken + end if + continuation = request.query.continuation if not StringUtils.IsNullOrEmpty(continuation) options.continuation = continuation @@ -589,6 +611,11 @@ namespace Http accessToken = request.headers["authorization"] if not StringUtils.IsNullOrEmpty(accessToken) and accessToken.StartsWith("Bearer ") options["accessToken"] = accessToken.Mid("Bearer ".Len()) + + activeIdentifyToken = request.query.activeIdentifyToken + if not StringUtils.IsNullOrEmpty(activeIdentifyToken) + options.onBehalfOfUser = activeIdentifyToken + end if end if if playlistId.StartsWith("RD") @@ -781,6 +808,11 @@ namespace Http "accessToken": accessToken.Mid("Bearer ".Len()) } + activeIdentifyToken = request.query.activeIdentifyToken + if not StringUtils.IsNullOrEmpty(activeIdentifyToken) + options.onBehalfOfUser = activeIdentifyToken + end if + result = InnertubeService.SubscribeToChannel(channelId, options) if result.success <> true @@ -836,6 +868,11 @@ namespace Http "accessToken": accessToken.Mid("Bearer ".Len()) } + activeIdentifyToken = request.query.activeIdentifyToken + if not StringUtils.IsNullOrEmpty(activeIdentifyToken) + options.onBehalfOfUser = activeIdentifyToken + end if + result = InnertubeService.UnsubscribeFromChannel(channelId, options) if result.success <> true diff --git a/playlet-lib/src/locale/en_US/translations.ts b/playlet-lib/src/locale/en_US/translations.ts index 32ca5c90..b587c1de 100644 --- a/playlet-lib/src/locale/en_US/translations.ts +++ b/playlet-lib/src/locale/en_US/translations.ts @@ -292,6 +292,14 @@ Use responsibly, especially if your YouTube account is tied to business or monetization. Use responsibly, especially if your YouTube account is tied to business or monetization. + + Who's watching? + Who's watching? + + + No valid accounts found for YouTube login. + No valid accounts found for YouTube login. + Invidious custom instance Invidious custom instance @@ -348,6 +356,10 @@ Success Success + + Error + Error + Refresh Refresh diff --git a/playlet-lib/src/source/utils/Locale.bs b/playlet-lib/src/source/utils/Locale.bs index a629bf5c..bebfa401 100644 --- a/playlet-lib/src/source/utils/Locale.bs +++ b/playlet-lib/src/source/utils/Locale.bs @@ -94,6 +94,8 @@ namespace Locale YouTubeLoginDisclaimer1 = "Playlet is a third-party app and is not affiliated with, endorsed by, or sponsored by YouTube or Google. All trademarks and registered trademarks mentioned are the property of their respective owners and are used only for identification purposes." YouTubeLoginDisclaimer2 = "By using Playlet and signing in with your YouTube account, you acknowledge that you do so at your own risk. The developers of Playlet are not liable for any harm, including but not limited to data loss, account suspension or ban, hacking, or loss of content." YouTubeLoginDisclaimer3 = "Use responsibly, especially if your YouTube account is tied to business or monetization." + WhosWatching = "Who's watching?" + NoValidAccountsFound = "No valid accounts found for YouTube login." end enum @locale @@ -114,6 +116,7 @@ namespace Locale Yes = "Yes" No = "No" Success = "Success" + Error = "Error" end enum @locale diff --git a/playlet-lib/src/source/utils/OptionUtils.bs b/playlet-lib/src/source/utils/OptionUtils.bs index 1b2e2422..19ee1edb 100644 --- a/playlet-lib/src/source/utils/OptionUtils.bs +++ b/playlet-lib/src/source/utils/OptionUtils.bs @@ -1,24 +1,23 @@ namespace OptionUtils - function Get(opts as object, key as string, passthroughFunction = invalid as dynamic) as dynamic + function Get(opts as object, key as string) as dynamic if opts = invalid - if passthroughFunction = invalid - return invalid - end if - return passthroughFunction(invalid) + return invalid + end if + + return opts[key] + end function + + function GetOrDefault(opts as object, key as string, defaultValue as dynamic) as dynamic + if opts = invalid or not opts.DoesExist(key) + return defaultValue end if value = opts[key] if value = invalid - if passthroughFunction = invalid - return invalid - end if - return passthroughFunction(invalid) + return defaultValue end if - if passthroughFunction <> invalid - return passthroughFunction(value) - end if return value end function