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 <githubaction@githubaction.com>
This commit is contained in:
Brahim Hadricheandgithub-action linter authored and GitHub committed 2025-05-31 14:40:33 -04:00
1 parent 4c94db2c03
commit 9e3da6b67d
31 files changed
+593 -400

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added ### Added
- German translations - German translations
- Support for multi-accounts, such as brand accounts
### Fixed ### Fixed
@@ -17,6 +17,7 @@ function FetchSubscriptionStatusTask(input as object) as object
subscriptionStatus = InnertubeService.GetSubscriptionStatusForChannel(ucid, { subscriptionStatus = InnertubeService.GetSubscriptionStatusForChannel(ucid, {
cancellation: m.top.cancellation cancellation: m.top.cancellation
accessToken: authToken.token accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
}) })
if subscriptionStatus.error <> invalid if subscriptionStatus.error <> invalid
@@ -8,6 +8,7 @@
<field id="accessToken" type="string" /> <field id="accessToken" type="string" />
<!-- Innertube fields --> <!-- Innertube fields -->
<field id="activeIdentifyToken" type="string" />
<field id="thumbnail" type="uri" /> <field id="thumbnail" type="uri" />
<field id="refreshToken" type="string" /> <field id="refreshToken" type="string" />
<field id="scope" type="string" /> <field id="scope" type="string" />
@@ -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
@@ -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/AsyncTask.bs"
import "pkg:/source/AsyncTask/Tasks.bs" import "pkg:/source/AsyncTask/Tasks.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Locale.bs" import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/Types.bs"
function Init() function Init()
@@ -28,7 +32,47 @@ function OnNodeReady()
m.task = AsyncTask.Start(Tasks.YouTubeLoginTask, { m.task = AsyncTask.Start(Tasks.YouTubeLoginTask, {
dialog: m.top dialog: m.top
profilesService: m.top.profilesService 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 end function
function OnCodeSet(event as object) function OnCodeSet(event as object)
@@ -1,6 +1,7 @@
<component name="YouTubeLoginDialog" extends="StandardDialog" initialFocus="buttonArea" includes="AutoBind"> <component name="YouTubeLoginDialog" extends="StandardDialog" initialFocus="buttonArea" includes="AutoBind">
<interface> <interface>
<field id="profilesService" type="node" bind="/ProfilesService" /> <field id="profilesService" type="node" bind="/ProfilesService" />
<field id="appController" type="node" bind="/AppController" />
<field id="code" type="string" alias="codeLabel.text" /> <field id="code" type="string" alias="codeLabel.text" />
<field id="url" type="string" onChange="OnUrlSet" /> <field id="url" type="string" onChange="OnUrlSet" />
<field id="alwaysOnTop" type="boolean" /> <field id="alwaysOnTop" type="boolean" />
@@ -1,4 +1,5 @@
import "pkg:/components/Dialog/DialogUtils.bs" import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Dialog/YouTubeLoginAccountItemUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/Logging.bs"
@@ -17,13 +18,10 @@ function YouTubeLoginTask(input as object) as object
end if end if
if authCode.error <> invalid if authCode.error <> invalid
LogError(authCode.error) return {
DialogUtils.ShowDialogEx({ success: false
title: "Error" error: authCode.error
message: authCode.error }
large: true
})
return invalid
end if end if
url = InnertubeService.AuthGetActivationUrl(authCode) url = InnertubeService.AuthGetActivationUrl(authCode)
@@ -40,13 +38,10 @@ function YouTubeLoginTask(input as object) as object
end if end if
if accessToken.error <> invalid if accessToken.error <> invalid
LogError(accessToken.error) return {
DialogUtils.ShowDialogEx({ success: false
title: "Error" error: accessToken.error
message: accessToken.error }
large: true
})
return invalid
end if end if
accounts = InnertubeService.AuthListAccounts(accessToken.accessToken, cancellation) accounts = InnertubeService.AuthListAccounts(accessToken.accessToken, cancellation)
@@ -56,63 +51,33 @@ function YouTubeLoginTask(input as object) as object
end if end if
if IsAssociativeArray(accounts) and accounts.error <> invalid if IsAssociativeArray(accounts) and accounts.error <> invalid
LogError(accounts.error) return {
DialogUtils.ShowDialogEx({ success: false
title: "Error" error: accounts.error
message: accounts.error }
large: true
})
return invalid
end if end if
if not IsArray(accounts) or accounts.Count() = 0 if not IsArray(accounts) or accounts.Count() = 0
LogError("No accounts found") return {
DialogUtils.ShowDialogEx({ success: false
title: "Error" error: Tr(Locale.Dialogs.NoValidAccountsFound)
message: "No accounts found" }
large: true
})
return invalid
end if end if
selectedAccount = invalid ' If there is only one account, we can skip the selection screen
for each account in accounts ' and just create a profile
if ValidBool(account.isSelected) if accounts.Count() = 1
selectedAccount = account profile = YouTubeLoginAccountItemUtils.CreateProfileContentNode(accounts[0], accessToken)
exit for
end if
end for
if selectedAccount = invalid
selectedAccount = accounts[0]
end if
profile = CreateProfileContentNode(selectedAccount, accessToken)
profilesNode@.LoginWithProfile(profile) profilesNode@.LoginWithProfile(profile)
dialogNode.close = true return {
success: 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 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 end function
@@ -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
@@ -0,0 +1,31 @@
<component name="YouTubeAccountListItem" extends="Group">
<interface>
<field id="itemContent" type="node" onChange="OnContentSet" />
<field id="accountPhoto" type="uri" alias="accountPhoto.uri" />
<field id="text1" type="string" alias="text1Label.text" />
<field id="text2" type="string" alias="text2Label.text" />
</interface>
<children>
<LayoutGroup layoutDirection="horiz" translation="[0, 2]" itemSpacings="[10]">
<Poster
width="64"
height="64"
blendColor="#DDDDDDFF"
uri="pkg:/images/white-circle.png">
<CirclePoster
id="accountPhoto"
width="60"
height="60"
translation="[2,2]"
failedBitmapUri="pkg:/images/thumbnail-missing.jpg" />
</Poster>
<LayoutGroup layoutDirection="vert" translation="[8, 0]" itemSpacings="[10]">
<Label id="text1Label" font="font:SmallestBoldSystemFont" />
<Label id="text2Label" font="font:SmallestSystemFont" />
</LayoutGroup>
</LayoutGroup>
</children>
</component>
@@ -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
@@ -0,0 +1,41 @@
<component name="YouTubeAccountSelectionView" extends="Group" includes="AutoBind,Focus">
<interface>
<field id="accessToken" type="assocarray" />
<field id="accounts" type="array" onChange="OnAccountsChanged" />
<field id="appController" type="node" bind="/AppController" />
<field id="profilesService" type="node" bind="/ProfilesService" />
</interface>
<children>
<Rectangle
width="1280"
height="720"
color="#000000"
opacity="0.5">
</Rectangle>
<Rectangle
width="720"
height="420"
translation="[280,150]"
color="#242424">
<Label
width="720"
horizAlign="center"
translation="[0,38]"
text="Who's watching?">
<Font role="font" uri="font:SystemFontFile" size="24" />
</Label>
<MarkupGrid
id="accountList"
itemComponentName="YouTubeAccountListItem"
itemSize="[640,70]"
itemSpacing="[0,20]"
numColumns="1"
numRows="3"
vertFocusAnimationStyle="floatingFocus"
translation="[40,100]"
focusBitmapUri="pkg:/images/focus-glow-padding-27.9.png" />
</Rectangle>
</children>
</component>
@@ -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
@@ -1,14 +1,18 @@
import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
namespace Innertube 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") deviceInfo = CreateObject("roDeviceInfo")
payload = { payload = {
"context": Innertube.CreateContext(clienType, deviceInfo, "", "") "context": Innertube.CreateContext(clienType, deviceInfo, options)
} }
if not StringUtils.IsNullOrEmpty(continuation) if not StringUtils.IsNullOrEmpty(continuation)
@@ -21,12 +25,7 @@ namespace Innertube
end if end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json", payload) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json", payload)
headers = { request.Headers(Innertube.CreateHeaders(clienType))
"accept": "*/*"
"accept-language": "*"
}
headers.Append(Innertube.CreateHeaders(clienType))
request.Headers(headers)
return request return request
end function end function
@@ -1,4 +1,5 @@
import "pkg:/components/Services/Innertube/Constants.bs" import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
namespace Innertube namespace Innertube
@@ -12,18 +13,24 @@ namespace Innertube
function CreateHeaders(clienType as Innertube.ClientType) as object function CreateHeaders(clienType as Innertube.ClientType) as object
if clienType = ClientType.Web if clienType = ClientType.Web
return { return {
"accept": "*/*"
"accept-language": "*"
"user-agent": INNERTUBE_WEB_USER_AGENT "user-agent": INNERTUBE_WEB_USER_AGENT
"x-youtube-client-name": INNERTUBE_WEB_CLIENT_NAME "x-youtube-client-name": INNERTUBE_WEB_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_WEB_CLIENT_VERSION "x-youtube-client-version": INNERTUBE_WEB_CLIENT_VERSION
} }
else if clienType = ClientType.IOS else if clienType = ClientType.IOS
return { return {
"accept": "*/*"
"accept-language": "*"
"user-agent": INNERTUBE_IOS_USER_AGENT "user-agent": INNERTUBE_IOS_USER_AGENT
"x-youtube-client-name": INNERTUBE_IOS_CLIENT_NAME "x-youtube-client-name": INNERTUBE_IOS_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_IOS_CLIENT_VERSION "x-youtube-client-version": INNERTUBE_IOS_CLIENT_VERSION
} }
else if clienType = ClientType.Tv else if clienType = ClientType.Tv
return { return {
"accept": "*/*"
"accept-language": "*"
"user-agent": INNERTUBE_TV_USER_AGENT "user-agent": INNERTUBE_TV_USER_AGENT
"x-youtube-client-name": INNERTUBE_TV_CLIENT_NAME "x-youtube-client-name": INNERTUBE_TV_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_TV_CLIENT_VERSION "x-youtube-client-version": INNERTUBE_TV_CLIENT_VERSION
@@ -33,7 +40,7 @@ namespace Innertube
end if end if
end function 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 client = invalid
if clienType = ClientType.Web if clienType = ClientType.Web
client = CreateContextClientWeb(deviceInfo) client = CreateContextClientWeb(deviceInfo)
@@ -45,6 +52,10 @@ namespace Innertube
throw "Invalid client type" throw "Invalid client type"
end if end if
credentialTransferToken = OptionUtils.Get(options, "credentialTransferToken")
visitorData = OptionUtils.Get(options, "visitorData")
onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser")
context = { context = {
"client": client "client": client
"user": { "user": {
@@ -57,9 +68,9 @@ namespace Innertube
} }
} }
if not StringUtils.IsNullOrEmpty(ctt) if not StringUtils.IsNullOrEmpty(credentialTransferToken)
context["user"]["credentialTransferTokens"] = [{ context["user"]["credentialTransferTokens"] = [{
"token": ctt "token": credentialTransferToken
"scope": "VIDEO" "scope": "VIDEO"
}] }]
end if end if
@@ -68,6 +79,10 @@ namespace Innertube
context["client"]["visitorData"] = visitorData context["client"]["visitorData"] = visitorData
end if end if
if not StringUtils.IsNullOrEmpty(onBehalfOfUser)
context["user"]["onBehalfOfUser"] = onBehalfOfUser
end if
return context return context
end function end function
@@ -11,36 +11,17 @@ import "pkg:/components/Services/Innertube/SubscriptionEndpoint.bs"
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/ObjectUtils.bs" import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/TimeUtils.bs" import "pkg:/source/utils/TimeUtils.bs"
namespace InnertubeService namespace InnertubeService
function GetVideoMetadata(videoId as string, options = invalid as object) as object function GetVideoMetadata(videoId as string, options = invalid as object) as object
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
fetchNext = true fetchNext = OptionUtils.GetOrDefault(options, "fetchNext", true)
ctt = "" raw = OptionUtils.GetOrDefault(options, "raw", false)
visitorData = ""
raw = false
if options <> invalid playerRequest = Innertube.CreatePlayerRequest(videoId, Innertube.ClientType.IOS, options)
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.Cancellation(cancellation) playerRequest.Cancellation(cancellation)
if raw if raw
playerRequest.LogCurlCommand() playerRequest.LogCurlCommand()
@@ -51,7 +32,7 @@ namespace InnertubeService
nextRequest = invalid nextRequest = invalid
nextResponse = invalid nextResponse = invalid
if fetchNext if fetchNext
nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, ctt) nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, options)
nextRequest.Cancellation(cancellation) nextRequest.Cancellation(cancellation)
if raw if raw
nextRequest.LogCurlCommand() nextRequest.LogCurlCommand()
@@ -111,20 +92,11 @@ namespace InnertubeService
} }
end if end if
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
retry = true retry = OptionUtils.GetOrDefault(options, "retry", true)
if options <> invalid
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("retry")
retry = options.retry
end if
end if
params = Innertube.GetEncodedNextParams(videoIds) params = Innertube.GetEncodedNextParams(videoIds)
request = Innertube.CreateNextRequest({ "params": params }, "") request = Innertube.CreateNextRequest({ "params": params })
request.Cancellation(cancellation) request.Cancellation(cancellation)
response = request.Await() response = request.Await()
@@ -186,18 +158,12 @@ namespace InnertubeService
end function end function
function GetTrending(options = invalid as object) as object 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 = "" 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" if trendingType = "music"
' {"44:proto": {"3:string": "ytma_charts"}} ' {"44:proto": {"3:string": "ytma_charts"}}
params = "4gINGgt5dG1hX2NoYXJ0cw%3D%3D" params = "4gINGgt5dG1hX2NoYXJ0cw%3D%3D"
@@ -208,16 +174,8 @@ namespace InnertubeService
' {"44:proto": {"3:string": "trailers"}} ' {"44:proto": {"3:string": "trailers"}}
params = "4gIKGgh0cmFpbGVycw%3D%3D" params = "4gIKGgh0cmFpbGVycw%3D%3D"
end if end if
end if
if options.DoesExist("disableShorts")
disableShorts = options.disableShorts
end if
if options.DoesExist("raw")
raw = options.raw
end if
end if
request = Innertube.CreateBrowseRequest("FEtrending", Innertube.ClientType.WEB, params) request = Innertube.CreateBrowseRequest("FEtrending", Innertube.ClientType.WEB, { params: params })
request.Cancellation(cancellation) request.Cancellation(cancellation)
if raw if raw
@@ -270,27 +228,12 @@ namespace InnertubeService
end function end function
function GetBrowseAuthenticatedPage(browserId as string, options = invalid as object) as object function GetBrowseAuthenticatedPage(browserId as string, options = invalid as object) as object
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
accessToken = invalid accessToken = OptionUtils.Get(options, "accessToken")
continuation = "" disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false)
disableShorts = false
if options <> invalid request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv, options)
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, "", continuation)
if accessToken <> invalid if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken) request.Header("Authorization", "Bearer " + accessToken)
end if end if
@@ -325,7 +268,7 @@ namespace InnertubeService
cancellation = options.cancellation cancellation = options.cancellation
end if end if
playerRequest = Innertube.CreatePlayerRequest(videoId, "", "", Innertube.ClientType.Tv) playerRequest = Innertube.CreatePlayerRequest(videoId, Innertube.ClientType.Tv, options)
playerRequest.Cancellation(cancellation) playerRequest.Cancellation(cancellation)
playerRequest.Header("Authorization", "Bearer " + accessToken) playerRequest.Header("Authorization", "Bearer " + accessToken)
@@ -338,6 +281,13 @@ namespace InnertubeService
json = playerResponse.Json() json = playerResponse.Json()
error = Innertube.ParsePlayerResponseForError(json)
if error <> ""
return {
error: error
}
end if
videostatsPlaybackUrl = ObjectUtils.Dig(json, ["playbackTracking", "videostatsPlaybackUrl", "baseUrl"]) videostatsPlaybackUrl = ObjectUtils.Dig(json, ["playbackTracking", "videostatsPlaybackUrl", "baseUrl"])
videostatsWatchtimeUrl = ObjectUtils.Dig(json, ["playbackTracking", "videostatsWatchtimeUrl", "baseUrl"]) videostatsWatchtimeUrl = ObjectUtils.Dig(json, ["playbackTracking", "videostatsWatchtimeUrl", "baseUrl"])
@@ -348,12 +298,9 @@ namespace InnertubeService
end function end function
function AuthMarkVideoWatched(videostatsPlaybackUrl as string, options as object) as boolean function AuthMarkVideoWatched(videostatsPlaybackUrl as string, options as object) as boolean
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
accessToken = options.accessToken accessToken = OptionUtils.Get(options, "accessToken")
onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser")
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
videostatsPlaybackUrl = videostatsPlaybackUrl.replace("https://s.", "https://www.") videostatsPlaybackUrl = videostatsPlaybackUrl.replace("https://s.", "https://www.")
queryParams = UrlUtils.ParseQueryComponents(videostatsPlaybackUrl) queryParams = UrlUtils.ParseQueryComponents(videostatsPlaybackUrl)
@@ -371,6 +318,9 @@ namespace InnertubeService
request.NoCache() request.NoCache()
request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv)) request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv))
request.Header("Authorization", "Bearer " + accessToken) request.Header("Authorization", "Bearer " + accessToken)
if not StringUtils.IsNullOrEmpty(onBehalfOfUser)
request.Header("X-Goog-Pageid", onBehalfOfUser)
end if
response = request.Await() response = request.Await()
if not response.IsSuccess() if not response.IsSuccess()
@@ -383,14 +333,9 @@ namespace InnertubeService
end function end function
function AuthMarkVideoWatchTime(time as float, videostatsWatchtimeUrl as string, options = invalid as object) as boolean function AuthMarkVideoWatchTime(time as float, videostatsWatchtimeUrl as string, options = invalid as object) as boolean
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
accessToken = options.accessToken accessToken = OptionUtils.Get(options, "accessToken")
onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser")
if options <> invalid
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
end if
timeStr = time.ToStr("%.3f") timeStr = time.ToStr("%.3f")
@@ -412,6 +357,9 @@ namespace InnertubeService
request.NoCache() request.NoCache()
request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv)) request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv))
request.Header("Authorization", "Bearer " + accessToken) request.Header("Authorization", "Bearer " + accessToken)
if not StringUtils.IsNullOrEmpty(onBehalfOfUser)
request.Header("X-Goog-Pageid", onBehalfOfUser)
end if
response = request.Await() response = request.Await()
if not response.IsSuccess() if not response.IsSuccess()
@@ -437,27 +385,10 @@ namespace InnertubeService
end function end function
function GetChannel(channelId as string, options = invalid as object) as object function GetChannel(channelId as string, options = invalid as object) as object
continuation = "" cancellation = OptionUtils.Get(options, "cancellation")
params = "" raw = OptionUtils.GetOrDefault(options, "raw", false)
cancellation = invalid
raw = false
if options <> invalid request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, options)
if options.DoesExist("continuation")
continuation = options.continuation
end if
if options.DoesExist("params")
params = options.params
end if
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("raw")
raw = options.raw
end if
end if
request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, params, continuation)
request.Cancellation(cancellation) request.Cancellation(cancellation)
if raw if raw
request.LogCurlCommand() request.LogCurlCommand()
@@ -489,16 +420,10 @@ namespace InnertubeService
end function end function
function GetSubscriptionStatusForChannel(channelId as string, options = invalid as object) as object function GetSubscriptionStatusForChannel(channelId as string, options = invalid as object) as object
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
accessToken = options.accessToken accessToken = OptionUtils.Get(options, "accessToken")
if options <> invalid request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Tv, options)
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
end if
request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Tv, "", "")
request.Cancellation(cancellation) request.Cancellation(cancellation)
if accessToken <> invalid if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken) request.Header("Authorization", "Bearer " + accessToken)
@@ -555,16 +480,10 @@ namespace InnertubeService
end function end function
function SubscribeToChannel(channelId as string, options = invalid as object) as object function SubscribeToChannel(channelId as string, options = invalid as object) as object
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
accessToken = options.accessToken accessToken = OptionUtils.Get(options, "accessToken")
if options <> invalid request = Innertube.CreateSubscribeRequest(channelId, options)
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
end if
request = Innertube.CreateSubscribeRequest(channelId, "")
request.Cancellation(cancellation) request.Cancellation(cancellation)
if accessToken <> invalid if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken) request.Header("Authorization", "Bearer " + accessToken)
@@ -578,16 +497,10 @@ namespace InnertubeService
end function end function
function UnsubscribeFromChannel(channelId as string, options = invalid as object) as object function UnsubscribeFromChannel(channelId as string, options = invalid as object) as object
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
accessToken = options.accessToken accessToken = OptionUtils.Get(options, "accessToken")
if options <> invalid request = Innertube.CreateUnsubscribeRequest(channelId, options)
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
end if
request = Innertube.CreateUnsubscribeRequest(channelId, "")
request.Cancellation(cancellation) request.Cancellation(cancellation)
if accessToken <> invalid if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken) request.Header("Authorization", "Bearer " + accessToken)
@@ -601,25 +514,9 @@ namespace InnertubeService
end function end function
function GetPlaylist(playlistId as string, options = invalid as object) as object function GetPlaylist(playlistId as string, options = invalid as object) as object
continuation = "" cancellation = OptionUtils.Get(options, "cancellation")
cancellation = invalid raw = OptionUtils.GetOrDefault(options, "raw", false)
raw = false accessToken = OptionUtils.Get(options, "accessToken")
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
if not playlistId.StartsWith("VL") if not playlistId.StartsWith("VL")
playlistId = "VL" + playlistId playlistId = "VL" + playlistId
@@ -630,7 +527,7 @@ namespace InnertubeService
client = Innertube.ClientType.Tv client = Innertube.ClientType.Tv
end if end if
request = Innertube.CreateBrowseRequest(playlistId, client, "", continuation) request = Innertube.CreateBrowseRequest(playlistId, client, options)
request.Cancellation(cancellation) request.Cancellation(cancellation)
if accessToken <> invalid if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken) request.Header("Authorization", "Bearer " + accessToken)
@@ -666,27 +563,15 @@ namespace InnertubeService
end function end function
function GetMix(mixId as string, options = invalid as object) as object function GetMix(mixId as string, options = invalid as object) as object
videoId = "" videoId = OptionUtils.Get(options, "videoId")
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
raw = false raw = OptionUtils.GetOrDefault(options, "raw", false)
if options <> invalid
if options.DoesExist("videoId")
videoId = options.videoId
end if
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("raw")
raw = options.raw
end if
end if
args = { "playlistId": mixId } args = { "playlistId": mixId }
if videoId <> "" if not StringUtils.IsNullOrEmpty(videoId)
args["videoId"] = videoId args["videoId"] = videoId
end if end if
request = Innertube.CreateNextRequest(args, "") request = Innertube.CreateNextRequest(args)
request.Cancellation(cancellation) request.Cancellation(cancellation)
if raw if raw
request.LogCurlCommand() request.LogCurlCommand()
@@ -715,13 +600,7 @@ namespace InnertubeService
end function end function
function ResolveUrl(url as string, options = invalid as object) as object function ResolveUrl(url as string, options = invalid as object) as object
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
if options <> invalid
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
end if
request = Innertube.CreateResolveUrlRequest(url) request = Innertube.CreateResolveUrlRequest(url)
request.Cancellation(cancellation) request.Cancellation(cancellation)
@@ -8,21 +8,18 @@ import "pkg:/source/utils/Types.bs"
namespace Innertube 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") deviceInfo = CreateObject("roDeviceInfo")
context = Innertube.CreateContext(Innertube.ClientType.Web, deviceInfo, options)
payload = { payload = {
"context": Innertube.CreateContext(Innertube.ClientType.Web, deviceInfo, ctt, "") "context": context
} }
payload.Append(payloadArgs) payload.Append(payloadArgs)
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json", payload) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json", payload)
headers = { request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Web))
"accept": "*/*"
"accept-language": "*"
}
headers.Append(Innertube.CreateHeaders(Innertube.ClientType.Web))
request.Headers(headers)
return request return request
end function end function
@@ -196,7 +196,7 @@ namespace Innertube
deviceInfo = CreateObject("roDeviceInfo") deviceInfo = CreateObject("roDeviceInfo")
payload = { payload = {
"context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, "", "") "context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo)
"accountReadMask": { "accountReadMask": {
"returnOwner": true "returnOwner": true
"returnBrandAccounts": true "returnBrandAccounts": true
@@ -243,6 +243,7 @@ namespace Innertube
"hasChannel": ValidBool(accountItem["hasChannel"]) "hasChannel": ValidBool(accountItem["hasChannel"])
"accountByline": ParseText(accountItem["accountByline"]) "accountByline": ParseText(accountItem["accountByline"])
"channelHandle": ParseText(accountItem["channelHandle"]) "channelHandle": ParseText(accountItem["channelHandle"])
"activeIdentifyToken": ParseAccountItemIdentityToken(accountItem)
} }
parsedAccounts.Push(parsedAccount) parsedAccounts.Push(parsedAccount)
end for end for
@@ -250,6 +251,48 @@ namespace Innertube
return parsedAccounts return parsedAccounts
end function 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 function ToCamelCase(obj as object) as object
if not IsAssociativeArray(obj) if not IsAssociativeArray(obj)
return obj return obj
@@ -6,12 +6,16 @@ import "pkg:/source/utils/Types.bs"
namespace Innertube 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") deviceInfo = CreateObject("roDeviceInfo")
context = Innertube.CreateContext(client, deviceInfo, options)
payload = { payload = {
"videoId": videoId "videoId": videoId
"context": Innertube.CreateContext(client, deviceInfo, ctt, visitorData) "context": context
"playbackContext": { "playbackContext": {
"contentPlaybackContext": { "contentPlaybackContext": {
"vis": 0 "vis": 0
@@ -32,48 +36,19 @@ namespace Innertube
} }
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload)
headers = { request.Headers(Innertube.CreateHeaders(client))
"accept": "*/*" if not StringUtils.IsNullOrEmpty(visitorData)
"accept-language": "*" request.Header("x-goog-visitor-id", visitorData)
} end if
headers.Append(Innertube.CreateHeaders(client))
request.Headers(headers)
return request return request
end function end function
function ParseInnertubePlayerResponse(payload as object) as object function ParseInnertubePlayerResponse(payload as object) as object
if not IsAssociativeArray(payload) error = ParsePlayerResponseForError(payload)
if error <> ""
return { return {
error: "Invalid payload" error: error
}
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
} }
end if end if
@@ -114,6 +89,38 @@ namespace Innertube
return videoInfo return videoInfo
end function 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 function ParseStoryboards(payload as object, lengthSeconds as integer) as object
storyboard = ObjectUtils.Dig(payload, ["storyboards", "playerLiveStoryboardSpecRenderer", "spec"]) storyboard = ObjectUtils.Dig(payload, ["storyboards", "playerLiveStoryboardSpecRenderer", "spec"])
if IsString(storyboard) if IsString(storyboard)
@@ -6,17 +6,12 @@ namespace Innertube
deviceInfo = CreateObject("roDeviceInfo") deviceInfo = CreateObject("roDeviceInfo")
payload = { payload = {
"context": CreateContext(ClientType.Web, deviceInfo, "", "") "context": CreateContext(ClientType.Web, deviceInfo)
"url": url "url": url
} }
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/navigation/resolve_url?prettyPrint=false&alt=json", payload) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/navigation/resolve_url?prettyPrint=false&alt=json", payload)
headers = { request.Headers(Innertube.CreateHeaders(ClientType.Web))
"accept": "*/*"
"accept-language": "*"
}
headers.Append(CreateHeaders(ClientType.Web))
request.Headers(headers)
return request return request
end function end function
@@ -2,42 +2,25 @@ import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/components/Services/Innertube/Parser.bs" import "pkg:/components/Services/Innertube/Parser.bs"
import "pkg:/components/Services/Innertube/SearchFilters.bs" import "pkg:/components/Services/Innertube/SearchFilters.bs"
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/Types.bs"
namespace Innertube namespace Innertube
function Search(query as string, options = invalid as object) as object function Search(query as string, options = invalid as object) as object
searchFilters = invalid searchFilters = OptionUtils.Get(options, "searchFilters")
continuation = "" continuation = OptionUtils.Get(options, "continuation")
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
disableShorts = false disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false)
raw = false raw = OptionUtils.GetOrDefault(options, "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
deviceInfo = CreateObject("roDeviceInfo") deviceInfo = CreateObject("roDeviceInfo")
payload = { 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 payload["continuation"] = continuation
else else
payload["query"] = query payload["query"] = query
@@ -50,13 +33,7 @@ namespace Innertube
end if end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json", payload) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json", payload)
request.Headers({ request.Headers(Innertube.CreateHeaders(ClientType.Web))
"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.Cancellation(cancellation) request.Cancellation(cancellation)
if raw if raw
@@ -3,11 +3,11 @@ import "pkg:/source/utils/Types.bs"
namespace Innertube 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") deviceInfo = CreateObject("roDeviceInfo")
payload = { payload = {
"context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, "", "") "context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, options)
} }
if IsString(channelIds) if IsString(channelIds)
@@ -15,26 +15,17 @@ namespace Innertube
end if end if
payload["channelIds"] = channelIds 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) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/subscription/subscribe?prettyPrint=false&alt=json", payload)
headers = { request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv))
"accept": "*/*"
"accept-language": "*"
}
headers.Append(Innertube.CreateHeaders(Innertube.ClientType.Tv))
request.Headers(headers)
return request return request
end function 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") deviceInfo = CreateObject("roDeviceInfo")
payload = { payload = {
"context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, "", "") "context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, options)
} }
if IsString(channelIds) if IsString(channelIds)
@@ -42,17 +33,8 @@ namespace Innertube
end if end if
payload["channelIds"] = channelIds 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) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/subscription/unsubscribe?prettyPrint=false&alt=json", payload)
headers = { request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv))
"accept": "*/*"
"accept-language": "*"
}
headers.Append(Innertube.CreateHeaders(Innertube.ClientType.Tv))
request.Headers(headers)
return request return request
end function end function
@@ -8,6 +8,7 @@ import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/MessagePortUtils.bs" import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/OptionUtils.bs" import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/RegistryUtils.bs" import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.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 ' have the exact expiration time, we'll use 5 hours. Invidious currently
' Does a fresh fetch if the cache is older than 10 minutes. ' 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 ' https://github.com/iv-org/invidious/blob/069e91d2a609b1df94bdfbb693335969b2a281d8/src/invidious/videos.cr#L349
cacheSeconds = 18000 ' 5 hours cacheSeconds = OptionUtils.GetOrDefault(options, "cacheSeconds", 18000) ' 5 hours
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
tryCount = 2 tryCount = OptionUtils.GetOrDefault(options, "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
instance = m.GetInstance() instance = m.GetInstance()
url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}` url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}`
@@ -197,6 +186,9 @@ namespace Invidious
url = `${authToken.instance}${Invidious.AUTH_PLAYLISTS}/${playlistId}` url = `${authToken.instance}${Invidious.AUTH_PLAYLISTS}/${playlistId}`
request = HttpClient.Get(url) request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
end if
else else
instance = m.GetInstance() instance = m.GetInstance()
url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}` url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}`
@@ -319,6 +311,9 @@ namespace Invidious
request.Url(authToken.instance + endpoint.url) request.Url(authToken.instance + endpoint.url)
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
end if
end if end if
if endpoint.queryParams <> invalid if endpoint.queryParams <> invalid
@@ -786,6 +781,9 @@ namespace Invidious
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}` url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Post(url, "") request = HttpClient.Post(url, "")
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
end if
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation) request.Cancellation(cancellation)
@@ -800,6 +798,9 @@ namespace Invidious
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}` url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Delete(url) request = HttpClient.Delete(url)
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
end if
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation) request.Cancellation(cancellation)
@@ -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. ' 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. ' 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. ' These tokens need to be managed better, based on the video they belong to.
if not StringUtils.IsNullOrEmpty(commandArgs.ctt) if not StringUtils.IsNullOrEmpty(commandArgs[FIELD_CTT])
m.loungeServiceNode.ctt = commandArgs.ctt m.loungeServiceNode.credentialTransferToken = commandArgs[FIELD_CTT]
end if end if
LoungeVideoQueue.SetPlaylist(m.videoQueueNode, m.invService, commandArgs) LoungeVideoQueue.SetPlaylist(m.videoQueueNode, m.invService, commandArgs)
end function end function
@@ -5,7 +5,7 @@
<field id="deviceName" type="string" /> <field id="deviceName" type="string" />
<field id="screenId" type="string" /> <field id="screenId" type="string" />
<field id="loungeToken" type="string" /> <field id="loungeToken" type="string" />
<field id="ctt" type="string" /> <field id="credentialTransferToken" type="string" />
<field id="join" type="boolean" alwaysNotify="true" /> <field id="join" type="boolean" alwaysNotify="true" />
<field id="outgoingMessages" type="array" alwaysNotify="true" /> <field id="outgoingMessages" type="array" alwaysNotify="true" />
@@ -53,6 +53,7 @@ function LoadProfilesFromRegistry()
profileNode.thumbnail = profile.thumbnail profileNode.thumbnail = profile.thumbnail
profileNode.accessToken = profile.accessToken profileNode.accessToken = profile.accessToken
profileNode.activeIdentifyToken = profile.activeIdentifyToken
profileNode.refreshToken = profile.refreshToken profileNode.refreshToken = profile.refreshToken
profileNode.scope = profile.scope profileNode.scope = profile.scope
profileNode.tokenType = profile.tokenType profileNode.tokenType = profile.tokenType
@@ -103,7 +104,7 @@ function MigrateExistingProfiles(userProfiles as object) as boolean
return false return false
end if end if
id = CreateProfileId(authToken.username, authToken.instance) id = CreateProfileId(authToken.username, "", authToken.instance)
for each profile in userProfiles.profiles for each profile in userProfiles.profiles
if profile.id = id if profile.id = id
return false return false
@@ -161,6 +162,7 @@ function GetProfilesDto(includeAccessToken as boolean) as object
"id": profileNode.id "id": profileNode.id
"type": profileNode.type "type": profileNode.type
"username": profileNode.username "username": profileNode.username
"activeIdentifyToken": profileNode.activeIdentifyToken
"serverUrl": profileNode.serverUrl "serverUrl": profileNode.serverUrl
"thumbnail": profileNode.thumbnail "thumbnail": profileNode.thumbnail
"color": color "color": color
@@ -191,7 +193,7 @@ end function
function LoginWithProfile(newProfile as object) function LoginWithProfile(newProfile as object)
isNewProfile = true isNewProfile = true
if StringUtils.IsNullOrEmpty(newProfile.id) if StringUtils.IsNullOrEmpty(newProfile.id)
newProfile.id = CreateProfileId(newProfile.username, newProfile.serverUrl) newProfile.id = CreateProfileId(newProfile.username, newProfile.activeIdentifyToken, newProfile.serverUrl)
end if end if
existingProfile = invalid existingProfile = invalid
@@ -206,6 +208,7 @@ function LoginWithProfile(newProfile as object)
if not isNewProfile if not isNewProfile
existingProfile.username = newProfile.username existingProfile.username = newProfile.username
existingProfile.activeIdentifyToken = newProfile.activeIdentifyToken
existingProfile.thumbnail = newProfile.thumbnail existingProfile.thumbnail = newProfile.thumbnail
existingProfile.accessToken = newProfile.accessToken existingProfile.accessToken = newProfile.accessToken
existingProfile.refreshToken = newProfile.refreshToken existingProfile.refreshToken = newProfile.refreshToken
@@ -333,6 +336,7 @@ function SetCurrentProfile(newActiveProfile as object) as void
token: newActiveProfile.accessToken token: newActiveProfile.accessToken
instance: newActiveProfile.serverUrl instance: newActiveProfile.serverUrl
username: newActiveProfile.username username: newActiveProfile.username
activeIdentifyToken: newActiveProfile.activeIdentifyToken
profileNode: newActiveProfile profileNode: newActiveProfile
} }
LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl) LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl)
@@ -353,6 +357,6 @@ function RefreshActiveProfileState(activeProfile as object) as void
end for end for
end function end function
function CreateProfileId(username as string, serverUrl as string) as string function CreateProfileId(username as string, activeIdentifyToken as string, serverUrl as string) as string
return "v1:" + CryptoUtils.GetMd5(username + serverUrl) return "v1:" + CryptoUtils.GetMd5(username + activeIdentifyToken + serverUrl)
end function end function
@@ -23,6 +23,7 @@ function MarkVideoWatchedTask(input as object) as object
playbackTrackingUrls = InnertubeService.AuthGetPlaybackTrackingUrls(videoId, { playbackTrackingUrls = InnertubeService.AuthGetPlaybackTrackingUrls(videoId, {
accessToken: authToken.token accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
cancellation: cancellation cancellation: cancellation
}) })
@@ -38,6 +39,7 @@ function MarkVideoWatchedTask(input as object) as object
markedAsWatched = InnertubeService.AuthMarkVideoWatched(playbackTrackingUrls.videostatsPlaybackUrl, { markedAsWatched = InnertubeService.AuthMarkVideoWatched(playbackTrackingUrls.videostatsPlaybackUrl, {
accessToken: authToken.token accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
cancellation: cancellation cancellation: cancellation
}) })
if not markedAsWatched if not markedAsWatched
@@ -67,6 +69,7 @@ function MarkVideoWatchedTask(input as object) as object
watchTime = message.getData() watchTime = message.getData()
InnertubeService.AuthMarkVideoWatchTime(watchTime, playbackTrackingUrls.videostatsWatchtimeUrl, { InnertubeService.AuthMarkVideoWatchTime(watchTime, playbackTrackingUrls.videostatsWatchtimeUrl, {
accessToken: authToken.token accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
cancellation: cancellation cancellation: cancellation
}) })
end while end while
@@ -24,7 +24,7 @@ function VideoContentTask(input as object) as object
if backend = "playlet" if backend = "playlet"
metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, { metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, {
"cancellation": m.top.cancellation "cancellation": m.top.cancellation
"ctt": loungeServiceNode.ctt "credentialTransferToken": loungeServiceNode.credentialTransferToken
"visitorData": innertubeNode.visitorData "visitorData": innertubeNode.visitorData
}) })
else else
@@ -69,6 +69,12 @@ namespace Http
"accessToken": accessToken.Mid("Bearer ".Len()) "accessToken": accessToken.Mid("Bearer ".Len())
"disableShorts": m.preferences["content_feed.disable_shorts"] "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 continuation = request.query.continuation
if not StringUtils.IsNullOrEmpty(continuation) if not StringUtils.IsNullOrEmpty(continuation)
options.continuation = continuation options.continuation = continuation
@@ -141,6 +147,12 @@ namespace Http
options = { options = {
"accessToken": accessToken.Mid("Bearer ".Len()) "accessToken": accessToken.Mid("Bearer ".Len())
} }
activeIdentifyToken = request.query.activeIdentifyToken
if not StringUtils.IsNullOrEmpty(activeIdentifyToken)
options.onBehalfOfUser = activeIdentifyToken
end if
continuation = request.query.continuation continuation = request.query.continuation
if not StringUtils.IsNullOrEmpty(continuation) if not StringUtils.IsNullOrEmpty(continuation)
options.continuation = continuation options.continuation = continuation
@@ -188,6 +200,11 @@ namespace Http
"accessToken": accessToken.Mid("Bearer ".Len()) "accessToken": accessToken.Mid("Bearer ".Len())
} }
activeIdentifyToken = request.query.activeIdentifyToken
if not StringUtils.IsNullOrEmpty(activeIdentifyToken)
options.onBehalfOfUser = activeIdentifyToken
end if
continuation = request.query.continuation continuation = request.query.continuation
hasContinuation = not StringUtils.IsNullOrEmpty(continuation) hasContinuation = not StringUtils.IsNullOrEmpty(continuation)
if hasContinuation if hasContinuation
@@ -302,6 +319,11 @@ namespace Http
"disableShorts": m.preferences["content_feed.disable_shorts"] "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 continuation = request.query.continuation
if not StringUtils.IsNullOrEmpty(continuation) if not StringUtils.IsNullOrEmpty(continuation)
options.continuation = continuation options.continuation = continuation
@@ -589,6 +611,11 @@ namespace Http
accessToken = request.headers["authorization"] accessToken = request.headers["authorization"]
if not StringUtils.IsNullOrEmpty(accessToken) and accessToken.StartsWith("Bearer ") if not StringUtils.IsNullOrEmpty(accessToken) and accessToken.StartsWith("Bearer ")
options["accessToken"] = accessToken.Mid("Bearer ".Len()) options["accessToken"] = accessToken.Mid("Bearer ".Len())
activeIdentifyToken = request.query.activeIdentifyToken
if not StringUtils.IsNullOrEmpty(activeIdentifyToken)
options.onBehalfOfUser = activeIdentifyToken
end if
end if end if
if playlistId.StartsWith("RD") if playlistId.StartsWith("RD")
@@ -781,6 +808,11 @@ namespace Http
"accessToken": accessToken.Mid("Bearer ".Len()) "accessToken": accessToken.Mid("Bearer ".Len())
} }
activeIdentifyToken = request.query.activeIdentifyToken
if not StringUtils.IsNullOrEmpty(activeIdentifyToken)
options.onBehalfOfUser = activeIdentifyToken
end if
result = InnertubeService.SubscribeToChannel(channelId, options) result = InnertubeService.SubscribeToChannel(channelId, options)
if result.success <> true if result.success <> true
@@ -836,6 +868,11 @@ namespace Http
"accessToken": accessToken.Mid("Bearer ".Len()) "accessToken": accessToken.Mid("Bearer ".Len())
} }
activeIdentifyToken = request.query.activeIdentifyToken
if not StringUtils.IsNullOrEmpty(activeIdentifyToken)
options.onBehalfOfUser = activeIdentifyToken
end if
result = InnertubeService.UnsubscribeFromChannel(channelId, options) result = InnertubeService.UnsubscribeFromChannel(channelId, options)
if result.success <> true if result.success <> true
@@ -292,6 +292,14 @@
<source>Use responsibly, especially if your YouTube account is tied to business or monetization.</source> <source>Use responsibly, especially if your YouTube account is tied to business or monetization.</source>
<translation>Use responsibly, especially if your YouTube account is tied to business or monetization.</translation> <translation>Use responsibly, especially if your YouTube account is tied to business or monetization.</translation>
</message> </message>
<message>
<source>Who&#39;s watching?</source>
<translation>Who&#39;s watching?</translation>
</message>
<message>
<source>No valid accounts found for YouTube login.</source>
<translation>No valid accounts found for YouTube login.</translation>
</message>
<message> <message>
<source>Invidious custom instance</source> <source>Invidious custom instance</source>
<translation>Invidious custom instance</translation> <translation>Invidious custom instance</translation>
@@ -348,6 +356,10 @@
<source>Success</source> <source>Success</source>
<translation>Success</translation> <translation>Success</translation>
</message> </message>
<message>
<source>Error</source>
<translation>Error</translation>
</message>
<message> <message>
<source>Refresh</source> <source>Refresh</source>
<translation>Refresh</translation> <translation>Refresh</translation>
+3
View File
@@ -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." 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." 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." 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 end enum
@locale @locale
@@ -114,6 +116,7 @@ namespace Locale
Yes = "Yes" Yes = "Yes"
No = "No" No = "No"
Success = "Success" Success = "Success"
Error = "Error"
end enum end enum
@locale @locale
+9 -10
View File
@@ -1,24 +1,23 @@
namespace OptionUtils 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 opts = invalid
if passthroughFunction = invalid
return invalid return invalid
end if end if
return passthroughFunction(invalid)
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 end if
value = opts[key] value = opts[key]
if value = invalid if value = invalid
if passthroughFunction = invalid return defaultValue
return invalid
end if
return passthroughFunction(invalid)
end if end if
if passthroughFunction <> invalid
return passthroughFunction(value)
end if
return value return value
end function end function