OAuth refresh token (#601)

* OAuth refresh token

* Lint fix

* tweak refresh logic

* error handling cancelled request

* Ignore endScreenPlaylistRenderer

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
Brahim Hadricheandgithub-action linter authored and GitHub committed 2025-05-10 21:04:07 -04:00
1 parent b040b2997c
commit 1dcd88a9a4
9 files changed
+121 -19

No files matched your search

@@ -0,0 +1,56 @@
import "pkg:/source/AsyncTask/AsyncTask.bs"
import "pkg:/source/AsyncTask/Tasks.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
function HasValidAccessToken(_unused as dynamic) as boolean
serverType = m.top.type
accessToken = m.top.accessToken
if StringUtils.IsNullOrEmpty(accessToken)
return false
end if
if serverType = "invidious"
return true
end if
nowSeconds = TimeUtils.Now().AsSeconds()
expiresTimestamp = m.top.expiresTimestamp
' We should refresh the token if it's about to expire in 30 minutes
' Although the current token might be valid, we can let current request
' wait for the new token
shouldRefreshToken = expiresTimestamp < nowSeconds + 60 * 30
if shouldRefreshToken
RefreshAccessToken()
end if
return not shouldRefreshToken
end function
function RefreshAccessToken() as void
if m.refreshTokenTask <> invalid
return
end if
if m.profilesService = invalid
m.profilesService = m.top.getScene().findNode("ProfilesService")
end if
LogInfo("Refreshing access token for profile:", m.top.username)
m.refreshTokenTask = AsyncTask.Start(Tasks.ProfileRefreshTokenTask, {
profile: m.top
profilesService: m.profilesService
accessTokenObject: {
clientId: m.top.clientId
clientSecret: m.top.clientSecret
refreshToken: m.top.refreshToken
}
}, OnProfileRefreshTokenTaskResult)
end function
function OnProfileRefreshTokenTaskResult(output as object) as void
m.refreshTokenTask = invalid
end function
@@ -18,5 +18,7 @@
<field id="clientSecret" type="string" /> <field id="clientSecret" type="string" />
<field id="color" type="color" /> <field id="color" type="color" />
<function name="HasValidAccessToken" />
</interface> </interface>
</component> </component>
@@ -0,0 +1,25 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/source/utils/ErrorUtils.bs"
@asynctask
function ProfileRefreshTokenTask(input as object) as object
profileNode = input.profile
accessTokenObject = input.accessTokenObject
profilesService = input.profilesService
try
if InnertubeService.AuthRefreshAccessToken(accessTokenObject)
profileNode.expiresIn = accessTokenObject.expiresIn
profileNode.expiresTimestamp = accessTokenObject.expiresTimestamp
profileNode.accessToken = accessTokenObject.accessToken
profilesService@.SaveUserProfilesToRegistry()
else
LogError("Failed to refresh access token")
profileNode.accessToken = invalid
end if
catch error
LogError("Failed to refresh access token:", ErrorUtils.Format(error))
profileNode.accessToken = invalid
end try
return invalid
end function
@@ -524,24 +524,19 @@ namespace InnertubeService
return Innertube.PollForAccessToken(code, code, cancellation) return Innertube.PollForAccessToken(code, code, cancellation)
end function end function
function AuthRefreshAccessTokenIfNeeded(accessToken as object, cancellation = invalid as object) as boolean function AuthRefreshAccessToken(accessToken as object, cancellation = invalid as object) as boolean
if not IsAssociativeArray(accessToken) if not IsAssociativeArray(accessToken)
return false return false
end if end if
nowSeconds = TimeUtils.Now().AsSeconds() refreshed = Innertube.RefreshAccessToken(accessToken, cancellation)
expiresTimestamp = accessToken["expires_timestamp"]
if expiresTimestamp = invalid or expiresTimestamp < nowSeconds if IsAssociativeArray(refreshed) and refreshed.DoesExist("accessToken")
refreshed = Innertube.RefreshAccessToken(accessToken, cancellation) accessToken.Append(refreshed)
if accessToken.DoesExist("expiresIn")
if IsAssociativeArray(refreshed) and refreshed.DoesExist("accessToken") accessToken["expiresTimestamp"] = TimeUtils.Now().AsSeconds() + accessToken["expiresIn"]
accessToken.Append(refreshed)
if accessToken.DoesExist("expiresIn")
accessToken["expiresTimestamp"] = TimeUtils.Now().AsSeconds() + accessToken["expiresIn"]
end if
return true
end if end if
return true
end if end if
return false return false
@@ -82,6 +82,8 @@ namespace Innertube
"gridContinuation": ParseGridContinuation "gridContinuation": ParseGridContinuation
"tvSurfaceContentContinuation": ParseTvSurfaceContentContinuation "tvSurfaceContentContinuation": ParseTvSurfaceContentContinuation
' Ignored nodes: ' Ignored nodes:
' A playlist at the end of a video. We don't need that for now.
"endScreenPlaylistRenderer": ParseNotImplemented
' Posts not yet supported ' Posts not yet supported
"postRenderer": ParseNotImplemented "postRenderer": ParseNotImplemented
' a "View all posts" button ' a "View all posts" button
@@ -6,6 +6,7 @@ import "pkg:/source/AsyncTask/Tasks.bs"
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CryptoUtils.bs" 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/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"
@@ -294,6 +295,20 @@ namespace Invidious
error: ERROR_NOT_AUTHENTICATED error: ERROR_NOT_AUTHENTICATED
} }
end if end if
profileNode = authToken.profileNode
' This is not the right place for a token refresh,
' but it needs a refactor to be done properly.
if not profileNode@.HasValidAccessToken()
messagePort = CreateObject("roMessagePort")
MessagePortUtils.ObserveFieldScopedExSafe(profileNode, "accessToken", messagePort)
msg = wait(10000, messagePort)
profileNode.unobserveFieldScoped("accessToken")
if msg <> invalid
authToken.token = profileNode.accessToken
m.invidiousNode.authToken = authToken
end if
end if
request.Url(authToken.instance + endpoint.url) request.Url(authToken.instance + endpoint.url)
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
end if end if
@@ -367,6 +382,7 @@ namespace Invidious
return { return {
success: false success: false
error: response.ErrorMessage() error: response.ErrorMessage()
cancelled: response.IsCancelled()
} }
end if end if
end function end function
@@ -39,7 +39,7 @@ function LoadProfilesFromRegistry()
' Step 3: Save user preferences (if needed) ' Step 3: Save user preferences (if needed)
if isDirty if isDirty
SaveUserProfilesToRegistry() SaveUserProfilesToRegistry(invalid)
end if end if
' Step 4: Load user profiles into content nodes ' Step 4: Load user profiles into content nodes
@@ -127,7 +127,7 @@ function MigrateExistingProfiles(userProfiles as object) as boolean
return true return true
end function end function
function SaveUserProfilesToRegistry() as void function SaveUserProfilesToRegistry(_unused as dynamic) as void
if m.disableSavingToRegistry if m.disableSavingToRegistry
return return
end if end if
@@ -322,7 +322,7 @@ function SetCurrentProfile(newActiveProfile as object) as void
m.top.currentProfile = invalid m.top.currentProfile = invalid
m.invidious.authToken = invalid m.invidious.authToken = invalid
LogInfo("Current profile set to <invalid>") LogInfo("Current profile set to <invalid>")
SaveUserProfilesToRegistry() SaveUserProfilesToRegistry(invalid)
return return
end if end if
@@ -333,9 +333,10 @@ 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
profileNode: newActiveProfile
} }
LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl) LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl)
SaveUserProfilesToRegistry() SaveUserProfilesToRegistry(invalid)
end function end function
function RefreshActiveProfileState(activeProfile as object) as void function RefreshActiveProfileState(activeProfile as object) as void
@@ -18,6 +18,7 @@
<function name="LogoutWithProfiles" /> <function name="LogoutWithProfiles" />
<function name="LogoutWithAccessToken" /> <function name="LogoutWithAccessToken" />
<function name="SetCurrentProfile" /> <function name="SetCurrentProfile" />
<function name="SaveUserProfilesToRegistry" />
</interface> </interface>
<children> <children>
<!-- Note: two content nodes because we're rendering profiles in a RowList on the ProfilesScreen --> <!-- Note: two content nodes because we're rendering profiles in a RowList on the ProfilesScreen -->
@@ -96,7 +96,8 @@ function VideoRowListRowContentTask(input as object) as object
feedContentNode.title += " (Failed to load)" feedContentNode.title += " (Failed to load)"
end if end if
HandleFeedLoadErrorDialog(response.error, rowList) isCancelled = response.cancelled = true
HandleFeedLoadErrorDialog(response.error, isCancelled, rowList)
continue while continue while
end if end if
@@ -151,7 +152,7 @@ function VideoRowListRowContentTask(input as object) as object
end while end while
catch error catch error
HandleFeedLoadErrorDialog(error, rowList) HandleFeedLoadErrorDialog(error, false, rowList)
return { return {
success: false success: false
error: error error: error
@@ -186,13 +187,16 @@ function RemovePlaceHolderItems(contentNode as object)
end if end if
end function end function
function HandleFeedLoadErrorDialog(error as object, rowList as object) as void function HandleFeedLoadErrorDialog(error as object, isCancelled as boolean, rowList as object) as void
error = ErrorUtils.Format(error) error = ErrorUtils.Format(error)
LogError(error) LogError(error)
rowList.onError = error rowList.onError = error
if rowList.hasField("dispose") and rowList.dispose if rowList.hasField("dispose") and rowList.dispose
return return
end if end if
if isCancelled
return
end if
DialogUtils.ShowDialogEx({ DialogUtils.ShowDialogEx({
message: error message: error
title: "Failed to load feed" title: "Failed to load feed"