More OAuth work (#551)

* More OAuth work

* Lint fix

* tweaks

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
Brahim Hadricheandgithub-action linter authored and GitHub committed 2025-01-28 22:20:07 -05:00
1 parent 12231fe2ec
commit 29a3206f17
11 files changed
+379 -22

No files matched your search

@@ -8,6 +8,7 @@
<field id="accessToken" type="string" /> <field id="accessToken" type="string" />
<!-- Innertube fields --> <!-- Innertube fields -->
<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" />
<field id="tokenType" type="string" /> <field id="tokenType" type="string" />
@@ -0,0 +1,51 @@
import "pkg:/source/AsyncTask/AsyncTask.bs"
import "pkg:/source/AsyncTask/Tasks.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.qrCode = m.top.findNode("QrCodePoster")
codeLabel = m.top.findNode("codeLabel")
if codeLabel <> invalid
codeLabel = codeLabel.getChild(0)
if codeLabel <> invalid
codeFont = m.top.findNode("codeFont")
codeLabel.font = codeFont
end if
end if
m.top.width = "920"
m.top.observeFieldScoped("buttonSelected", FuncName(Close))
m.top.observeFieldScoped("wasClosed", FuncName(OnWasClosed))
scanLabel = m.top.findNode("scanLabel")
' TODO:P2 localize all dialog items
scanLabel.text = Tr(Locale.Dialogs.ScanTheQrCode)
end function
function OnNodeReady()
m.task = AsyncTask.Start(Tasks.YouTubeLoginTask, {
dialog: m.top
profilesService: m.top.profilesService
})
end function
function OnCodeSet(event as object)
code = event.getData()
m.qrCode.text = code
end function
function Close()
m.top.close = true
end function
function OnWasClosed()
if m.task <> invalid
m.task.cancel = true
m.task = invalid
end if
end function
function OnUrlSet()
m.qrCode.text = m.top.url
end function
@@ -0,0 +1,49 @@
<component name="YouTubeLoginDialog" extends="StandardDialog" initialFocus="buttonArea" includes="AutoBind">
<interface>
<field id="profilesService" type="node" bind="/ProfilesService" />
<field id="code" type="string" alias="codeLabel.text" />
<field id="url" type="string" onChange="OnUrlSet" />
<field id="alwaysOnTop" type="boolean" />
</interface>
<children>
<Font id="codeFont" uri="font:MediumSystemFontFile" size="36" />
<StdDlgTitleArea primaryTitle="Login to YouTube" />
<StdDlgContentArea>
<StdDlgTextItem text="Open the link 'https://yt.be/activate' and enter the following code:" />
<StdDlgTextItem id="codeLabel" text="Loading..." />
</StdDlgContentArea>
<StdDlgButtonArea id="buttonArea">
<StdDlgButton text="OK" />
</StdDlgButtonArea>
<StdDlgSideCardArea
id="sideCarArea"
horizAlign="right"
width="400"
extendToDialogEdge="false"
showDivider="false">
<Label
id="scanLabel"
text="Scan the QR Code"
horizAlign="center"
wrap="true" width="400">
<Font role="font" uri="font:SystemFontFile" size="24" />
</Label>
<QrCodePoster
id="QrCodePoster"
width="300"
height="300"
loadWidth="300"
loadHeight="300"
padding="10"
translation="[50, 50]" />
<Label
horizAlign="center"
width="400"
translation="[0, 380]"
text="https://yt.be/activate">
<Font role="font" uri="font:MediumSystemFontFile" size="18" />
</Label>
</StdDlgSideCardArea>
</children>
</component>
@@ -0,0 +1,118 @@
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/Logging.bs"
@asynctask
function YouTubeLoginTask(input as object) as object
profilesNode = input.profilesService
dialogNode = input.dialog
cancellation = m.top.cancellation
' TODO:P2 cache client identity
authCode = InnertubeService.AuthGetCode(cancellation)
if CancellationUtils.IsCancelled(cancellation)
return invalid
end if
if authCode.error <> invalid
LogError(authCode.error)
DialogUtils.ShowDialogEx({
title: "Error"
message: authCode.error
large: true
})
return invalid
end if
url = InnertubeService.AuthGetActivationUrl(authCode)
LogInfo("Login url:", url)
dialogNode.url = url
dialogNode.code = authCode.userCode
accessToken = InnertubeService.AuthPollForAccessToken(authCode, cancellation)
if CancellationUtils.IsCancelled(cancellation)
return invalid
end if
if accessToken.error <> invalid
LogError(accessToken.error)
DialogUtils.ShowDialogEx({
title: "Error"
message: accessToken.error
large: true
})
return invalid
end if
accounts = InnertubeService.AuthListAccounts(accessToken.accessToken, cancellation)
if CancellationUtils.IsCancelled(cancellation)
return invalid
end if
if IsAssociativeArray(accounts) and accounts.error <> invalid
LogError(accounts.error)
DialogUtils.ShowDialogEx({
title: "Error"
message: accounts.error
large: true
})
return invalid
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
end if
selectedAccount = invalid
for each account in accounts
if ValidBool(account.isSelected)
selectedAccount = account
exit for
end if
end for
if selectedAccount = invalid
selectedAccount = accounts[0]
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
end function
@@ -24,24 +24,37 @@ function OnContentSet() as void
return return
end if end if
m.top.circlePosterInnerUri = "pkg:/images/white-circle.png"
m.top.circlePosterInnerBlendColor = content.color
username = content.username username = content.username
m.top.username = username m.top.username = username
thumbnail = content.thumbnail
if not StringUtils.IsNullOrEmpty(thumbnail)
m.top.circlePosterInnerUri = thumbnail
' bs:disable-next-line LINT3023
m.top.circlePosterInnerBlendColor = "#FFFFFFFF"
m.top.letter = ""
else
m.top.circlePosterInnerUri = "pkg:/images/white-circle.png"
m.top.circlePosterInnerBlendColor = content.color
if not StringUtils.IsNullOrEmpty(username) if not StringUtils.IsNullOrEmpty(username)
m.top.letter = UCase(username.Left(1)) m.top.letter = UCase(username.Left(1))
else else
m.top.letter = "" m.top.letter = ""
end if end if
m.top.serverUrl = content.serverUrl end if
m.top.crownVisible = content.isSelected m.top.crownVisible = content.isSelected
backendType = content.type backendType = content.type
if backendType = "invidious" if backendType = "invidious"
m.top.serverUrl = content.serverUrl
m.top.backendTypePosterUri = "pkg:/images/invidious-logo.png" m.top.backendTypePosterUri = "pkg:/images/invidious-logo.png"
else if backendType = "youtube" else if backendType = "youtube"
m.top.serverUrl = "YouTube"
m.top.backendTypePosterUri = "pkg:/images/youtube-logo.png" m.top.backendTypePosterUri = "pkg:/images/youtube-logo.png"
else else
m.top.serverUrl = ""
m.top.backendTypePosterUri = "" m.top.backendTypePosterUri = ""
end if end if
end function end function
@@ -61,7 +61,7 @@ function OnBackEndSelected(event as object) as void
if selectedBackendType = "BackendTypeInvidious" if selectedBackendType = "BackendTypeInvidious"
LoginWithInvidious() LoginWithInvidious()
else if selectedBackendType = "BackendTypeYouTube" else if selectedBackendType = "BackendTypeYouTube"
LoginWithYouTube() ShowLoginWithYouTubeDialog()
else else
LogError("Unknown backend type:", selectedBackendType) LogError("Unknown backend type:", selectedBackendType)
end if end if
@@ -85,11 +85,32 @@ function LoginWithInvidious() as void
m.top.getScene().dialog = dialog m.top.getScene().dialog = dialog
end function end function
function LoginWithYouTube() as void function ShowLoginWithYouTubeDialog() as void
DialogUtils.ShowDialogEx({ ' TODO:P2 localize
title: "YouTube" dialog = DialogUtils.ShowDialogEx({
message: ["Not implemented yet."] title: "Disclaimer"
message: "Playlet authors acknowledge that all trademarks and registered trademarks mentioned in this application and related pages are the property of their respective owners. The use of these trademarks or trade names is for identification purposes only and does not imply any endorsement, affiliation, or sponsorship by the trademark owner."
buttons: [
Tr(Locale.Buttons.OK)
Tr(Locale.Buttons.Cancel)
]
}) })
dialog.ObserveField("buttonSelected", FuncName(OnLoginWithYouTubeDialogButtonSelected))
end function
function OnLoginWithYouTubeDialogButtonSelected(event as object) as void
buttonSelected = event.getData()
if buttonSelected <> 0
return
end if
LoginWithYouTube()
end function
function LoginWithYouTube() as void
dialog = CreateObject("roSGNode", "YouTubeLoginDialog")
dialog@.BindNode()
m.top.getScene().dialog = dialog
end function end function
function OnCurrentProfileChanged() as void function OnCurrentProfileChanged() as void
@@ -43,6 +43,16 @@ function OnContentSet() as void
end if end if
m.top.serverUrl = content.serverUrl m.top.serverUrl = content.serverUrl
m.top.crownVisible = content.isSelected m.top.crownVisible = content.isSelected
backendType = content.type
if backendType = "invidious"
m.top.backendTypePosterUri = "pkg:/images/invidious-logo.png"
else if backendType = "youtube"
m.top.backendTypePosterUri = "pkg:/images/youtube-logo.png"
else
m.top.backendTypePosterUri = ""
end if
UpdateActivateButton() UpdateActivateButton()
end function end function
@@ -5,6 +5,7 @@
<field id="username" type="string" alias="UsernameLabel.text" /> <field id="username" type="string" alias="UsernameLabel.text" />
<field id="serverUrl" type="string" alias="ServerLabel.text" /> <field id="serverUrl" type="string" alias="ServerLabel.text" />
<field id="circlePosterInnerUri" type="uri" alias="circlePosterInner.uri" /> <field id="circlePosterInnerUri" type="uri" alias="circlePosterInner.uri" />
<field id="backendTypePosterUri" type="uri" alias="backendTypePoster.uri" />
<field id="circlePosterInnerBlendColor" type="uri" alias="circlePosterInner.blendColor" /> <field id="circlePosterInnerBlendColor" type="uri" alias="circlePosterInner.blendColor" />
<field id="crownVisible" type="boolean" alias="CrownPoster.visible" /> <field id="crownVisible" type="boolean" alias="CrownPoster.visible" />
@@ -47,6 +48,12 @@
horizAlign="center"> horizAlign="center">
<Font role="font" uri="font:SystemFontFile" size="120" /> <Font role="font" uri="font:SystemFontFile" size="120" />
</Label> </Label>
<Poster
id="backendTypePoster"
width="60"
height="60"
translation="[110,110]"
/>
</Poster> </Poster>
<Poster <Poster
id="CrownPoster" id="CrownPoster"
@@ -455,14 +455,14 @@ namespace InnertubeService
function AuthGetCode(cancellation = invalid as object) as object function AuthGetCode(cancellation = invalid as object) as object
result = Innertube.GetClientIdentity(cancellation) result = Innertube.GetClientIdentity(cancellation)
if CancellationUtils.IsCancelled(cancellation) if CancellationUtils.IsCancelled(cancellation) or result.error <> invalid
return invalid return result
end if end if
result2 = Innertube.GetDeviceAndUserCode(result.clientId, cancellation) result2 = Innertube.GetDeviceAndUserCode(result.clientId, cancellation)
if CancellationUtils.IsCancelled(cancellation) if CancellationUtils.IsCancelled(cancellation) or result2.error <> invalid
return invalid return result2
end if end if
result.Append(result2) result.Append(result2)
@@ -508,4 +508,7 @@ namespace InnertubeService
return Innertube.RevokeAccessToken(accessToken["accessToken"], cancellation) return Innertube.RevokeAccessToken(accessToken["accessToken"], cancellation)
end function end function
function AuthListAccounts(accessToken as string, cancellation = invalid as object) as object
return Innertube.ListAccounts(accessToken, cancellation)
end function
end namespace end namespace
@@ -1,4 +1,5 @@
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/TimeUtils.bs" import "pkg:/source/utils/TimeUtils.bs"
namespace Innertube namespace Innertube
@@ -14,7 +15,9 @@ namespace Innertube
response = request.Await() response = request.Await()
if not response.IsSuccess() if not response.IsSuccess()
throw `Failed to get client id: ${response.ErrorMessage()}` return {
"error": `Failed to get client id: ${response.ErrorMessage()}`
}
end if end if
text = response.Text() text = response.Text()
@@ -23,7 +26,9 @@ namespace Innertube
match = scriptRegex.Match(text) match = scriptRegex.Match(text)
if match.Count() < 2 if match.Count() < 2
throw "Could not find base-js script" return {
"error": "Could not find base-js script"
}
end if end if
baseJsUrl = "https://www.youtube.com" + match[1] baseJsUrl = "https://www.youtube.com" + match[1]
@@ -33,7 +38,9 @@ namespace Innertube
response = request.Await() response = request.Await()
if not response.IsSuccess() if not response.IsSuccess()
throw `Failed to get base js: ${response.ErrorMessage()}` return {
"error": `Failed to get base js: ${response.ErrorMessage()}`
}
end if end if
text = response.Text() text = response.Text()
@@ -42,7 +49,9 @@ namespace Innertube
match = clientIdRegex.Match(text) match = clientIdRegex.Match(text)
if match.Count() < 3 if match.Count() < 3
throw "Could not find client id" return {
"error": "Could not find client id and secret"
}
end if end if
return { return {
@@ -66,13 +75,17 @@ namespace Innertube
response = request.Await() response = request.Await()
if not response.IsSuccess() if not response.IsSuccess()
throw `Failed to get device code: ${response.ErrorMessage()}` return {
"error": `Failed to get device code: ${response.ErrorMessage()}`
}
end if end if
responseData = ToCamelCase(response.Json()) responseData = ToCamelCase(response.Json())
if responseData.DoesExist("errorCode") if responseData.DoesExist("errorCode")
throw "Failed to get device code: " + ToString(responseData) return {
"error": "Failed to get device code: " + ToString(responseData)
}
end if end if
if responseData.DoesExist("expiresIn") if responseData.DoesExist("expiresIn")
@@ -130,11 +143,13 @@ namespace Innertube
end if end if
continue while continue while
else if responseData.error = "expired_token" else if responseData.error = "expired_token"
throw "Failed to get access token: " + ToString(responseData) return responseData
else if responseData.error = "access_denied" else if responseData.error = "access_denied"
throw "Failed to get access token: " + ToString(responseData) return responseData
else else
throw "Failed to get access token: " + ToString(responseData) return {
"error": "Failed to get access token: " + ToString(responseData)
}
end if end if
end while end while
@@ -177,6 +192,64 @@ namespace Innertube
return success return success
end function end function
function ListAccounts(accessToken as string, cancellation = invalid as dynamic) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, "", "")
"accountReadMask": {
"returnOwner": true
"returnBrandAccounts": true
"returnPersonaAccounts": true
"returnFamilyChildAccounts": true
}
}
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/account/accounts_list", payload)
headers = {
"Authorization": `Bearer ${accessToken}`
}
headers.Append(Innertube.CreateHeaders(Innertube.ClientType.Tv))
request.Headers(headers)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
return {
"error": `Failed to list accounts: ${response.ErrorMessage()}`
}
end if
accounts = ObjectUtils.Dig(response.Json(), ["contents", 0, "accountSectionListRenderer", "contents", 0, "accountItemSectionRenderer", "contents"])
if not IsArray(accounts)
return {
"error": "Could not parse accounts"
}
end if
parsedAccounts = []
for each account in accounts
accountItem = account["accountItem"]
if not IsAssociativeArray(accountItem)
continue for
end if
parsedAccount = {
"accountName": ParseText(accountItem["accountName"])
"accountPhoto": ObjectUtils.Dig(accountItem, ["accountPhoto", "thumbnails", 0, "url"])
"isSelected": ValidBool(accountItem["isSelected"])
"isDisabled": ValidBool(accountItem["isDisabled"])
"hasChannel": ValidBool(accountItem["hasChannel"])
"accountByline": ParseText(accountItem["accountByline"])
"channelHandle": ParseText(accountItem["channelHandle"])
}
parsedAccounts.Push(parsedAccount)
end for
return parsedAccounts
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
@@ -50,6 +50,7 @@ function LoadProfilesFromRegistry()
profileNode.type = profile.type profileNode.type = profile.type
profileNode.username = profile.username profileNode.username = profile.username
profileNode.serverUrl = profile.serverUrl profileNode.serverUrl = profile.serverUrl
profileNode.thumbnail = profile.thumbnail
profileNode.accessToken = profile.accessToken profileNode.accessToken = profile.accessToken
profileNode.refreshToken = profile.refreshToken profileNode.refreshToken = profile.refreshToken
@@ -161,6 +162,7 @@ function GetProfilesDto(includeAccessToken as boolean) as object
"type": profileNode.type "type": profileNode.type
"username": profileNode.username "username": profileNode.username
"serverUrl": profileNode.serverUrl "serverUrl": profileNode.serverUrl
"thumbnail": profileNode.thumbnail
"color": color "color": color
} }
@@ -203,8 +205,17 @@ function LoginWithProfile(newProfile as object)
end for end for
if not isNewProfile if not isNewProfile
' Refresh token of existing profile existingProfile.username = newProfile.username
existingProfile.thumbnail = newProfile.thumbnail
existingProfile.accessToken = newProfile.accessToken existingProfile.accessToken = newProfile.accessToken
existingProfile.refreshToken = newProfile.refreshToken
existingProfile.scope = newProfile.scope
existingProfile.tokenType = newProfile.tokenType
existingProfile.expiresIn = newProfile.expiresIn
existingProfile.expiresTimestamp = newProfile.expiresTimestamp
existingProfile.clientId = newProfile.clientId
existingProfile.clientSecret = newProfile.clientSecret
newProfile = existingProfile newProfile = existingProfile
end if end if