oauth refactor

This commit is contained in:
Brahim Hadriche committed 2026-07-03 21:34:35 -04:00
1 parent 78ecdec28d
commit 6cb5bfe985
40 files changed
+782 -301

No files matched your search

+3 -1
View File
@@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
- Nothing worth mentioning yet. ### Fixed
- Signed-in accounts no longer get stuck sending failing requests after the login session expires
## [0.48.0] - 2026-07-01 ## [0.48.0] - 2026-07-01
+1
View File
@@ -34,6 +34,7 @@
], ],
"rooibos": { "rooibos": {
"logLevel": 2, "logLevel": 2,
"tags": ["!integration"],
"isRecordingCodeCoverage": false, "isRecordingCodeCoverage": false,
"printTestTimes": true, "printTestTimes": true,
"showOnlyFailures": true, "showOnlyFailures": true,
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/ContextMenu/ContextMenuUtils.bs" import "pkg:/components/ContextMenu/ContextMenuUtils.bs"
import "pkg:/components/Dialog/DialogUtils.bs" import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/JobSystem/Jobs.bs" import "pkg:/components/JobSystem/Jobs.bs"
@@ -44,7 +45,7 @@ function OnNodeready()
DisposableObserveFieldScoped(m.subscribeButton, "buttonSelected", FuncName(OnSubscribeButtonSelected)) DisposableObserveFieldScoped(m.subscribeButton, "buttonSelected", FuncName(OnSubscribeButtonSelected))
SetSubscribeButtonVisibility() SetSubscribeButtonVisibility()
DisposableObserveFieldScoped(m.invidious, "authToken", FuncName(SetSubscribeButtonVisibility)) DisposableObserveFieldScoped(m.profilesService, "currentProfileChanged", FuncName(SetSubscribeButtonVisibility))
OnSubscriptionChanged() OnSubscriptionChanged()
DisposableObserveFieldScoped(m.invidious, "subscriptions", FuncName(OnSubscriptionChanged)) DisposableObserveFieldScoped(m.invidious, "subscriptions", FuncName(OnSubscriptionChanged))
end function end function
@@ -172,7 +173,19 @@ function OnDispose()
end if end if
end function end function
function OnSubscribeButtonSelected() function OnSubscribeButtonSelected() as void
profile = m.profilesService.currentProfile
if profile = invalid
return
end if
if profile.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
DialogUtils.ShowDialogEx({
title: Tr(Locale.Dialogs.ProfileNeedsReauthTitle)
message: Tr(Locale.Dialogs.ProfileNeedsReauthMessage)
})
return
end if
if m.subscribeJob <> invalid if m.subscribeJob <> invalid
m.subscribeJob.cancel = true m.subscribeJob.cancel = true
end if end if
@@ -185,6 +198,7 @@ function OnSubscribeButtonSelected()
invidious: m.invidious invidious: m.invidious
ucid: m.authorId ucid: m.authorId
subscribe: not m.top.isSubscribed subscribe: not m.top.isSubscribed
profile: profile
} }
m.subscribeJob = JobSystem.CreateCallback() m.subscribeJob = JobSystem.CreateCallback()
@@ -367,7 +381,7 @@ function GetSortingContextMenuOptionsForItem(video as object) as object
end function end function
function IsLoggedIn() as boolean function IsLoggedIn() as boolean
return m.invidious.authToken <> invalid return m.profilesService.currentProfile <> invalid
end function end function
function OnAuthorIdChange() function OnAuthorIdChange()
@@ -386,7 +400,8 @@ function SetSubscribeButtonVisibility()
end function end function
function FetchSubscriptionStatus() as void function FetchSubscriptionStatus() as void
if not IsLoggedIn() profile = m.profilesService.currentProfile
if profile = invalid or profile.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
return return
end if end if
@@ -402,7 +417,7 @@ function FetchSubscriptionStatus() as void
input = { input = {
channelView: m.top channelView: m.top
ucid: authorId ucid: authorId
authToken: m.invidious.authToken profile: profile
invidious: m.invidious invidious: m.invidious
} }
@@ -5,6 +5,7 @@
<field id="isSubscribed" type="boolean" onChange="OnSubscriptionChanged" /> <field id="isSubscribed" type="boolean" onChange="OnSubscriptionChanged" />
<field id="appController" type="node" bind="/AppController" /> <field id="appController" type="node" bind="/AppController" />
<field id="invidious" type="node" bind="/Invidious" /> <field id="invidious" type="node" bind="/Invidious" />
<field id="profilesService" type="node" bind="/ProfilesService" />
<field id="preferences" type="node" bind="/Preferences" /> <field id="preferences" type="node" bind="/Preferences" />
<field id="jobQueue" type="node" bind="/JobQueue" /> <field id="jobQueue" type="node" bind="/JobQueue" />
<field id="bookmarksService" type="node" bind="/BookmarksService" /> <field id="bookmarksService" type="node" bind="/BookmarksService" />
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/CancellationUtils.bs"
@@ -9,7 +10,7 @@ function ExecuteJob() as void
channelView = input.channelView channelView = input.channelView
ucid = input.ucid ucid = input.ucid
invidiousNode = input.invidious invidiousNode = input.invidious
authToken = input.authToken profile = input.profile
if JobIsCancelled() if JobIsCancelled()
JobCancel() JobCancel()
@@ -17,12 +18,18 @@ function ExecuteJob() as void
end if end if
cancellation = JobGetCancellation() cancellation = JobGetCancellation()
isInnertubeProfile = authToken.profileNode.type = "youtube"
if isInnertubeProfile auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
JobError("No usable access token to fetch subscription status: " + auth.state)
return
end if
if profile.type = "youtube"
subscriptionStatus = InnertubeService.GetSubscriptionStatusForChannel(ucid, { subscriptionStatus = InnertubeService.GetSubscriptionStatusForChannel(ucid, {
cancellation: cancellation cancellation: cancellation
accessToken: authToken.token accessToken: auth.token
onBehalfOfUser: authToken.activeIdentifyToken onBehalfOfUser: auth.activeIdentifyToken
}) })
if subscriptionStatus.error <> invalid if subscriptionStatus.error <> invalid
@@ -32,7 +39,7 @@ function ExecuteJob() as void
channelView.isSubscribed = subscriptionStatus.isSubscribed channelView.isSubscribed = subscriptionStatus.isSubscribed
else else
service = new Invidious.InvidiousService(invidiousNode) service = new Invidious.InvidiousService(invidiousNode)
subscriptionsResponse = service.GetSubscriptions(cancellation) subscriptionsResponse = service.GetSubscriptions(auth, cancellation)
if not subscriptionsResponse.IsSuccess() if not subscriptionsResponse.IsSuccess()
JobError("Failed to fetch subscriptions: " + subscriptionsResponse.ErrorMessage()) JobError("Failed to fetch subscriptions: " + subscriptionsResponse.ErrorMessage())
return return
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs"
@job("SubscribeJob") @job("SubscribeJob")
@@ -8,6 +9,7 @@ function ExecuteJob() as void
invidiousNode = input.invidious invidiousNode = input.invidious
ucid = input.ucid ucid = input.ucid
subscribe = input.subscribe subscribe = input.subscribe
profile = input.profile
if JobIsCancelled() if JobIsCancelled()
JobCancel() JobCancel()
@@ -15,12 +17,19 @@ function ExecuteJob() as void
end if end if
cancellation = JobGetCancellation() cancellation = JobGetCancellation()
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
JobError("No usable access token to subscribe/unsubscribe: " + auth.state)
return
end if
service = new Invidious.InvidiousService(invidiousNode) service = new Invidious.InvidiousService(invidiousNode)
if subscribe if subscribe
response = service.Subscribe(ucid, cancellation) response = service.Subscribe(auth, ucid, cancellation)
else else
response = service.Unsubscribe(ucid, cancellation) response = service.Unsubscribe(auth, ucid, cancellation)
end if end if
if not response.IsSuccess() if not response.IsSuccess()
@@ -0,0 +1,46 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
namespace ProfileContentAuthTokenUtils
function DeriveAuthState(profileType as string, accessToken as dynamic, refreshToken as dynamic) as string
if profileType = "youtube"
if StringUtils.IsNullOrEmpty(refreshToken)
return ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
end if
return ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated
end if
if profileType = "invidious"
if StringUtils.IsNullOrEmpty(accessToken)
return ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
end if
' The Invidious token is signed JSON carrying its own expire timestamp.
token = StringUtils.ParseJsonSafe(accessToken)
if IsAssociativeArray(token) and IsNumber(token.expire) and token.expire <= TimeUtils.Now().AsSeconds()
return ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
end if
return ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated
end if
LogError("Unknown profile type when deriving auth state:", profileType)
return ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated
end function
' The unobserve at the end is field-level: it removes every scoped observer the
' calling component holds on refreshCompleted. Hold long-lived observers on authState.
function EnsureFreshAccessToken(profileNode as object) as ProfileContentAuthTokenUtils.AccessTokenResult
messagePort = CreateObject("roMessagePort")
MessagePortUtils.ObserveFieldScopedExSafe(profileNode, "refreshCompleted", messagePort)
result = profileNode@.ResolveAccessToken()
if result.state = ProfileContentAuthTokenUtils.AccessTokenState.Refreshing
wait(30000, messagePort)
result = profileNode@.ResolveAccessToken()
end if
result.profile = profileNode
profileNode.unobserveFieldScoped("refreshCompleted")
return result
end function
end namespace
@@ -0,0 +1,23 @@
namespace ProfileContentAuthTokenUtils
enum ProfileAuthState
Authenticated = "Authenticated"
NeedsReauth = "NeedsReauth"
end enum
enum AccessTokenState
Ok = "Ok"
Refreshing = "Refreshing"
NeedsReauth = "NeedsReauth"
end enum
interface AccessTokenResult
token as string
state as AccessTokenState
serverUrl as string
activeIdentifyToken as string
profile as object
freshUntilSeconds as integer
end interface
end namespace
@@ -1,50 +1,76 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/JobSystem/Jobs.bs" import "pkg:/components/JobSystem/Jobs.bs"
import "pkg:/components/JobSystem/JobSystem.bs" import "pkg:/components/JobSystem/JobSystem.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/Logging.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"
function HasValidAccessToken(_unused as dynamic) as boolean ' Refresh well before expiry; stop serving a few minutes before expiry so a request
serverType = m.top.type ' never carries a token that dies in flight.
accessToken = m.top.accessToken const REFRESH_THRESHOLD_SECONDS = 60 * 60
if StringUtils.IsNullOrEmpty(accessToken) const VALIDITY_THRESHOLD_SECONDS = 60 * 5
return false
' A Refreshing state means a refresh job is in flight; its completion pulses refreshCompleted.
function ResolveAccessToken(_unused as dynamic) as object
result = {
state: ProfileContentAuthTokenUtils.AccessTokenState.Refreshing
token: ""
serverUrl: m.top.serverUrl
activeIdentifyToken: m.top.activeIdentifyToken
freshUntilSeconds: 0
}
if m.top.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
result.state = ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth
return result
end if end if
if serverType = "invidious" if m.top.type = "invidious"
return true ' Invidious holds a single long-lived token — nothing to refresh.
result.state = ProfileContentAuthTokenUtils.AccessTokenState.Ok
result.token = m.top.accessToken
return result
end if end if
nowSeconds = TimeUtils.Now().AsSeconds() nowSeconds = TimeUtils.Now().AsSeconds()
expiresTimestamp = m.top.expiresTimestamp expiresTimestamp = m.top.expiresTimestamp
result.freshUntilSeconds = expiresTimestamp - REFRESH_THRESHOLD_SECONDS
' We should refresh the token if it's about to expire in 30 minutes accessToken = m.top.accessToken
' Although the current token might be valid, we can let current request ' An empty token refreshes regardless of the stored expiry — a Refreshing verdict
' wait for the new token ' must always have a live job behind it, or a waiter blocks on a pulse that never comes.
shouldRefreshToken = expiresTimestamp < nowSeconds + 60 * 30 if expiresTimestamp < nowSeconds + REFRESH_THRESHOLD_SECONDS or StringUtils.IsNullOrEmpty(accessToken)
StartRefreshJob()
if shouldRefreshToken if m.top.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
RefreshAccessToken() result.state = ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth
return result
end if
end if end if
return not shouldRefreshToken if not StringUtils.IsNullOrEmpty(accessToken) and expiresTimestamp > nowSeconds + VALIDITY_THRESHOLD_SECONDS
result.state = ProfileContentAuthTokenUtils.AccessTokenState.Ok
result.token = accessToken
end if
return result
end function end function
function RefreshAccessToken() as void function StartRefreshJob() as void
if m.profileRefreshTokenJob <> invalid if m.profileRefreshTokenJob <> invalid and not m.profileRefreshTokenJob.done
return return
end if end if
if m.scene = invalid ' A YouTube profile holds a refresh token by construction; none means the credential is gone.
m.scene = m.top.getScene() if StringUtils.IsNullOrEmpty(m.top.refreshToken)
end if LogError("Refresh requested for profile without a refresh token")
if m.profilesService = invalid MarkNeedsReauth(invalid)
m.profilesService = m.scene.findNode("ProfilesService") return
end if
if m.jobQueue = invalid
m.jobQueue = m.scene.findNode("JobQueue")
end if end if
EnsureSceneRefs()
LogInfo("Refreshing access token for profile:", m.top.username) LogInfo("Refreshing access token for profile:", m.top.username)
input = { input = {
@@ -65,3 +91,46 @@ function OnProfileRefreshTokenJobDone(event as object) as void
JobSystem.UnobserveCallback(event.getRoSGNode()) JobSystem.UnobserveCallback(event.getRoSGNode())
m.profileRefreshTokenJob = invalid m.profileRefreshTokenJob = invalid
end function end function
function MarkNeedsReauth(_unused as dynamic) as void
if m.top.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
return
end if
m.top.update({
accessToken: ""
refreshToken: ""
expiresTimestamp: 0
authState: ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
})
' Wake any waiter blocked on a refresh; it re-resolves and sees NeedsReauth.
m.top.refreshCompleted = true
LogError("Profile credential is dead; sign-in required")
EnsureSceneRefs()
if m.profilesService <> invalid
m.profilesService@.SaveUserProfilesToRegistry()
currentProfile = m.profilesService.currentProfile
if currentProfile <> invalid and currentProfile.isSameNode(m.top)
m.profilesService.currentProfileChanged = true
end if
end if
DialogUtils.ShowDialogEx({
title: Tr(Locale.Dialogs.ProfileNeedsReauthTitle)
message: Tr(Locale.Dialogs.ProfileNeedsReauthMessage)
})
end function
function EnsureSceneRefs() as void
if m.scene = invalid
m.scene = m.top.getScene()
end if
if m.profilesService = invalid
m.profilesService = m.scene.findNode("ProfilesService")
end if
if m.jobQueue = invalid
m.jobQueue = m.scene.findNode("JobQueue")
end if
end function
@@ -21,6 +21,13 @@
<field id="color" type="color" /> <field id="color" type="color" />
<function name="HasValidAccessToken" /> <!-- Runtime credential state (ProfileAuthState); derived from the stored
credential at load, mutated only by MarkNeedsReauth and re-login. -->
<field id="authState" type="string" value="Authenticated" />
<field id="refreshCompleted" type="boolean" alwaysNotify="true" />
<function name="ResolveAccessToken" />
<function name="MarkNeedsReauth" />
</interface> </interface>
</component> </component>
@@ -10,16 +10,23 @@ function ExecuteJob() as void
try try
cancellation = JobGetCancellation() cancellation = JobGetCancellation()
if InnertubeService.AuthRefreshAccessToken(accessTokenObject, cancellation) if InnertubeService.AuthRefreshAccessToken(accessTokenObject, cancellation)
profileNode.expiresIn = accessTokenObject.expiresIn profileNode.update({
profileNode.expiresTimestamp = accessTokenObject.expiresTimestamp expiresIn: accessTokenObject.expiresIn
profileNode.accessToken = accessTokenObject.accessToken expiresTimestamp: accessTokenObject.expiresTimestamp
accessToken: accessTokenObject.accessToken
})
profilesService@.SaveUserProfilesToRegistry() profilesService@.SaveUserProfilesToRegistry()
else else
JobError("Failed to refresh access token") JobError("Refresh response contained no access token")
profileNode.accessToken = invalid
end if end if
catch error catch error
' AuthRefreshAccessToken flags a permanently-dead refresh token on the shared object before throwing.
if ValidBool(accessTokenObject.terminalRefreshError)
profileNode@.MarkNeedsReauth()
end if
JobError("Failed to refresh access token: " + ErrorUtils.Format(error)) JobError("Failed to refresh access token: " + ErrorUtils.Format(error))
profileNode.accessToken = invalid
end try end try
' Signal completion on every outcome so a blocked waiter wakes.
profileNode.refreshCompleted = true
end function end function
@@ -22,7 +22,7 @@ function OnNodeReady()
m.urlLabel.text = Tr(Locale.Dialogs.IpAddressNotAvailable) m.urlLabel.text = Tr(Locale.Dialogs.IpAddressNotAvailable)
end if end if
m.invidious.observeFieldScoped("authToken", FuncName(OnAuthTokenChange)) m.profilesService.observeFieldScoped("currentProfileChanged", FuncName(OnCurrentProfileChanged))
end function end function
function Close() function Close()
@@ -36,7 +36,7 @@ function OnUrlSet()
m.qrCode.text = url m.qrCode.text = url
end function end function
function OnAuthTokenChange() function OnCurrentProfileChanged()
m.invidious.unobserveFieldScoped("authToken") m.profilesService.unobserveFieldScoped("currentProfileChanged")
Close() Close()
end function end function
@@ -1,7 +1,7 @@
<component name="InvidiousLoginDialog" extends="StandardDialog" initialFocus="buttonArea" includes="AutoBind"> <component name="InvidiousLoginDialog" extends="StandardDialog" initialFocus="buttonArea" includes="AutoBind">
<interface> <interface>
<field id="webServer" type="node" bind="/WebServer" /> <field id="webServer" type="node" bind="/WebServer" />
<field id="invidious" type="node" bind="/Invidious" /> <field id="profilesService" type="node" bind="/ProfilesService" />
<field id="url" type="string" onChange="OnUrlSet" /> <field id="url" type="string" onChange="OnUrlSet" />
<field id="alwaysOnTop" type="boolean" /> <field id="alwaysOnTop" type="boolean" />
</interface> </interface>
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Navigation/Navigation.bs" import "pkg:/components/Navigation/Navigation.bs"
import "pkg:/source/utils/DisposableObserve.bs" import "pkg:/source/utils/DisposableObserve.bs"
import "pkg:/source/utils/FocusManagement.bs" import "pkg:/source/utils/FocusManagement.bs"
@@ -10,6 +11,7 @@ function Init()
m.activateButton = m.top.findNode("activateButton") m.activateButton = m.top.findNode("activateButton")
m.logoutButton = m.top.findNode("logoutButton") m.logoutButton = m.top.findNode("logoutButton")
m.closeButton = m.top.findNode("closeButton") m.closeButton = m.top.findNode("closeButton")
m.reauthLabel = m.top.findNode("ReauthLabel")
DisposableObserveField(m.activateButton, "buttonSelected", FuncName(Activate)) DisposableObserveField(m.activateButton, "buttonSelected", FuncName(Activate))
DisposableObserveField(m.logoutButton, "buttonSelected", FuncName(Logout)) DisposableObserveField(m.logoutButton, "buttonSelected", FuncName(Logout))
@@ -29,6 +31,7 @@ end function
function OnContentSet() as void function OnContentSet() as void
content = m.top.content content = m.top.content
if content = invalid if content = invalid
m.reauthLabel.visible = false
return return
end if end if
@@ -70,6 +73,8 @@ function OnContentSet() as void
m.top.backendTypePosterUri = "" m.top.backendTypePosterUri = ""
end if end if
UpdateReauthState(content)
UpdateActivateButton() UpdateActivateButton()
end function end function
@@ -140,6 +145,17 @@ function OnDispose()
m.top.content = invalid m.top.content = invalid
end function end function
function UpdateReauthState(content as object) as void
needsReauth = content.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
if needsReauth
m.reauthLabel.text = [
Tr(Locale.Dialogs.ProfileNeedsReauthMessageLine1)
Tr(Locale.Dialogs.ProfileNeedsReauthMessageLine2)
].Join(Chr(10))
end if
m.reauthLabel.visible = needsReauth
end function
function OnCunrrentProfileChanged() as void function OnCunrrentProfileChanged() as void
content = m.top.content content = m.top.content
if content = invalid if content = invalid
@@ -21,11 +21,11 @@
</Rectangle> </Rectangle>
<Rectangle <Rectangle
width="720" width="720"
height="420" height="440"
translation="[280,150]" translation="[280,140]"
color="#242424"> color="#242424">
<Group translation="[100,90]"> <Group translation="[100,100]">
<Poster <Poster
id="circlePoster" id="circlePoster"
width="160" width="160"
@@ -85,21 +85,31 @@
anchor="[0.5,0.5]" anchor="[0.5,0.5]"
text="Activate" text="Activate"
minWidth="200" minWidth="200"
translation="[520,132]" /> translation="[520,142]" />
<ButtonEx <ButtonEx
id="logoutButton" id="logoutButton"
iconVisible="false" iconVisible="false"
anchor="[0.5,0.5]" anchor="[0.5,0.5]"
text="Logout" text="Logout"
minWidth="200" minWidth="200"
translation="[520,210]" /> translation="[520,220]" />
<ButtonEx <ButtonEx
id="closeButton" id="closeButton"
iconVisible="false" iconVisible="false"
anchor="[0.5,0.5]" anchor="[0.5,0.5]"
text="Close" text="Close"
minWidth="200" minWidth="200"
translation="[520,288]" /> translation="[520,298]" />
<Label id="ReauthLabel"
width="640"
horizAlign="center"
wrap="true"
maxLines="2"
translation="[40,382]"
visible="false">
<Font role="font" uri="font:SystemFontFile" size="16" />
</Label>
</Rectangle> </Rectangle>
</children> </children>
@@ -7,6 +7,20 @@ import "pkg:/source/utils/TimeUtils.bs"
namespace Innertube namespace Innertube
enum RefreshErrorCode
InvalidGrant = "invalid_grant"
InvalidClient = "invalid_client"
UnauthorizedClient = "unauthorized_client"
end enum
function IsTerminalRefreshError(json as object) as boolean
if not IsAssociativeArray(json)
return false
end if
oauthError = ValidString(json.error)
return oauthError = RefreshErrorCode.InvalidGrant or oauthError = RefreshErrorCode.InvalidClient or oauthError = RefreshErrorCode.UnauthorizedClient
end function
function GetClientIdentity(cancellation = invalid as dynamic) as object function GetClientIdentity(cancellation = invalid as dynamic) as object
request = HttpClient.Get("https://www.youtube.com/tv") request = HttpClient.Get("https://www.youtube.com/tv")
request.Headers({ request.Headers({
@@ -169,9 +183,26 @@ namespace Innertube
request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/token", payload) request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/token", payload)
request.Cancellation(cancellation) request.Cancellation(cancellation)
request.TryCount(3)
request.RetryCallback(function(context as object) as boolean
return not Innertube.IsTerminalRefreshError(context.response.Json())
end function)
response = request.Await() response = request.Await()
if not response.IsSuccess() if not response.IsSuccess()
json = response.Json()
oauthError = ""
if IsAssociativeArray(json)
oauthError = ValidString(json.error)
end if
if oauthError = RefreshErrorCode.InvalidGrant
' Dead user refresh token: flag the shared object so the job marks the profile.
accessToken.terminalRefreshError = true
else if oauthError = RefreshErrorCode.InvalidClient or oauthError = RefreshErrorCode.UnauthorizedClient
' Fleet-wide app-side rejection. The credentials are scraped public TV-client
' values, safe to log; don't clear the session — re-login uses the same client.
LogError("OAuth client rejected by token endpoint:", response.ErrorMessage(), "client_id:", accessToken.clientId, "client_secret:", accessToken.clientSecret)
end if
throw `Failed to refresh token: ${response.ErrorMessage()}` throw `Failed to refresh token: ${response.ErrorMessage()}`
end if end if
@@ -5,7 +5,6 @@
<field id="webServer" type="node" /> <field id="webServer" type="node" />
<field id="profilesService" type="node" /> <field id="profilesService" type="node" />
<field id="authToken" type="assocarray" />
<field id="apiDefinitions" type="assocarray" /> <field id="apiDefinitions" type="assocarray" />
<function name="GetInstance" /> <function name="GetInstance" />
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Dialog/DialogUtils.bs" import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs" import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
@@ -5,7 +6,6 @@ import "pkg:/components/VideoFeed/PaginationType.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/OptionUtils.bs" import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/RegistryUtils.bs" import "pkg:/source/utils/RegistryUtils.bs"
@@ -66,6 +66,16 @@ namespace Invidious
} }
end function end function
function GetCurrentProfile() as object
if m.profilesService = invalid
m.profilesService = m.invidiousNode.profilesService
end if
if m.profilesService = invalid
return invalid
end if
return m.profilesService.currentProfile
end function
function GetInstance() as string function GetInstance() as string
if m.preferences = invalid if m.preferences = invalid
m.preferences = m.invidiousNode.preferences m.preferences = m.invidiousNode.preferences
@@ -90,21 +100,17 @@ namespace Invidious
return m.preferences["invidious.instance"] return m.preferences["invidious.instance"]
end function end function
function MarkVideoWatched(videoId as dynamic, cancellation = invalid as object) as void function MarkVideoWatched(auth as ProfileContentAuthTokenUtils.AccessTokenResult, videoId as dynamic, cancellation = invalid as object) as void
if StringUtils.IsNullOrEmpty(videoId) if StringUtils.IsNullOrEmpty(videoId) or auth = invalid or auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return return
end if end if
authToken = m.invidiousNode.authToken url = `${auth.serverUrl}${Invidious.HISTORY_ENDPOINT}/${videoId}`
if authToken = invalid
return
end if
url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}`
request = HttpClient.Post(url, "") request = HttpClient.Post(url, "")
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(auth.token))
request.Cancellation(cancellation) request.Cancellation(cancellation)
request.Await() response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
end function end function
function SearchSuggestions(q as string, cancellation = invalid as object) as object function SearchSuggestions(q as string, cancellation = invalid as object) as object
@@ -180,13 +186,18 @@ namespace Invidious
end function end function
function GetPlaylist(playlistId as string, index = 0 as integer, continuation = "" as string, cancellation = invalid as object) as object function GetPlaylist(playlistId as string, index = 0 as integer, continuation = "" as string, cancellation = invalid as object) as object
authToken = m.invidiousNode.authToken profile = m.GetCurrentProfile()
if authToken <> invalid auth = invalid
url = `${authToken.instance}${Invidious.AUTH_PLAYLISTS}/${playlistId}` if profile <> invalid
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
end if
isAuthenticatedRequest = auth <> invalid and auth.state = ProfileContentAuthTokenUtils.AccessTokenState.Ok
if isAuthenticatedRequest
url = `${auth.serverUrl}${Invidious.AUTH_PLAYLISTS}/${playlistId}`
request = HttpClient.Get(url) request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(auth.token))
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken) if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken) request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken)
end if end if
else else
instance = m.GetInstance() instance = m.GetInstance()
@@ -201,7 +212,11 @@ namespace Invidious
end if end if
request.Cancellation(cancellation) request.Cancellation(cancellation)
return request.Await() response = request.Await()
if isAuthenticatedRequest
m.MarkNeedsReauthOn403(response, auth.profile)
end if
return response
end function end function
function GetChannel(authorId as string, cancellation = invalid as object) as object function GetChannel(authorId as string, cancellation = invalid as object) as object
@@ -284,34 +299,24 @@ namespace Invidious
request = HttpClient.Get(instance + endpoint.url) request = HttpClient.Get(instance + endpoint.url)
authToken = invalid profile = invalid
if endpoint.authenticated = true if endpoint.authenticated = true
authToken = m.invidiousNode.authToken profile = m.GetCurrentProfile()
if authToken = invalid auth = invalid
if profile <> invalid
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
end if
if auth = invalid or auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return { return {
success: false success: false
error: ERROR_NOT_AUTHENTICATED error: ERROR_NOT_AUTHENTICATED
} }
end if end if
profileNode = authToken.profileNode request.Url(auth.serverUrl + endpoint.url)
' This is not the right place for a token refresh, request.Headers(m.GetAuthenticationHeaders(auth.token))
' but it needs a refactor to be done properly. if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken)
if not profileNode@.HasValidAccessToken() request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken)
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.Headers(m.GetAuthenticationHeaders(authToken.token))
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
end if end if
end if end if
@@ -372,7 +377,7 @@ namespace Invidious
result = m[responseHandler]({ result = m[responseHandler]({
feedSource: feedSource feedSource: feedSource
response: response response: response
authToken: authToken profile: profile
}) })
if response.IsSuccess() and result <> invalid if response.IsSuccess() and result <> invalid
@@ -606,9 +611,8 @@ namespace Invidious
function AuthFeedHandler(context as object) as object function AuthFeedHandler(context as object) as object
response = context.response response = context.response
authToken = context.authToken
m.DeleteExpiredToken(response, authToken) m.MarkNeedsReauthOn403(response, context.profile)
if not response.IsSuccess() if not response.IsSuccess()
return invalid return invalid
@@ -642,9 +646,8 @@ namespace Invidious
function WatchHistoryHandler(context as object) as object function WatchHistoryHandler(context as object) as object
response = context.response response = context.response
authToken = context.authToken
m.DeleteExpiredToken(response, authToken) m.MarkNeedsReauthOn403(response, context.profile)
if not response.IsSuccess() if not response.IsSuccess()
return invalid return invalid
@@ -696,19 +699,16 @@ namespace Invidious
return json return json
end function end function
function DeleteExpiredToken(response as object, authToken as object) as void ' A 403 on an authenticated call is terminal — only a fresh sign-in recovers.
function MarkNeedsReauthOn403(response as object, profile as object) as void
if response.StatusCode() <> 403 if response.StatusCode() <> 403
return return
end if end if
LogWarn(`Invidious instance responded with 403: ${response.Text()}`) LogWarn(`Invidious instance responded with 403: ${response.Text()}`)
if not IsAssociativeArray(authToken) or not IsString(authToken.token) if profile <> invalid and profile.type = "invidious"
LogWarn("No valid token to delete") profile@.MarkNeedsReauth()
return
end if end if
LogInfo("Deleting Invidious token...")
m.invidiousNode.profilesService@.LogoutWithAccessToken(authToken.token)
end function end function
function VerifyTokenScope(token as string) as boolean function VerifyTokenScope(token as string) as boolean
@@ -732,11 +732,11 @@ namespace Invidious
return validScopes return validScopes
end function end function
function UnregisterToken(authToken as object) as object function UnregisterToken(instance as string, token as string) as object
url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}` url = `${instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
request = HttpClient.Post(url, authToken.token) request = HttpClient.Post(url, token)
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(token))
request.Header("Content-Type", "application/json") request.Header("Content-Type", "application/json")
return request.Await() return request.Await()
@@ -763,52 +763,43 @@ namespace Invidious
return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}` return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
end function end function
function GetSubscriptions(cancellation = invalid as object) as object function GetSubscriptions(auth as ProfileContentAuthTokenUtils.AccessTokenResult, cancellation = invalid as object) as object
authToken = m.invidiousNode.authToken url = `${auth.serverUrl}${Invidious.AUTH_SUBSCRIPTIONS}`
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}`
request = HttpClient.Get(url) request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(auth.token))
request.Cancellation(cancellation) request.Cancellation(cancellation)
return request.Await() response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
return response
end function end function
function Subscribe(channelId as string, cancellation = invalid as object) as object function Subscribe(auth as ProfileContentAuthTokenUtils.AccessTokenResult, channelId as string, cancellation = invalid as object) as object
authToken = m.invidiousNode.authToken url = `${auth.serverUrl}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Post(url, "") request = HttpClient.Post(url, "")
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken) if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken) request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken)
end if end if
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(auth.token))
request.Cancellation(cancellation) request.Cancellation(cancellation)
return request.Await() response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
return response
end function end function
function Unsubscribe(channelId as string, cancellation = invalid as object) as object function Unsubscribe(auth as ProfileContentAuthTokenUtils.AccessTokenResult, channelId as string, cancellation = invalid as object) as object
authToken = m.invidiousNode.authToken url = `${auth.serverUrl}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Delete(url) request = HttpClient.Delete(url)
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken) if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken) request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken)
end if end if
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(auth.token))
request.Cancellation(cancellation) request.Cancellation(cancellation)
return request.Await() response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
return response
end function end function
end class end class
@@ -16,11 +16,7 @@ function ExecuteJob() as void
token = profileNode.accessToken token = profileNode.accessToken
end if end if
authToken = { response = service.UnregisterToken(profileNode.serverUrl, token)
instance: profileNode.serverUrl
token: token
}
response = service.UnregisterToken(authToken)
if not response.IsSuccess() if not response.IsSuccess()
LogWarn(`Failed to unregister token: ${response.ErrorMessage()}`) LogWarn(`Failed to unregister token: ${response.ErrorMessage()}`)
end if end if
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/JobSystem/Jobs.bs" import "pkg:/components/JobSystem/Jobs.bs"
import "pkg:/components/JobSystem/JobSystem.bs" import "pkg:/components/JobSystem/JobSystem.bs"
import "pkg:/source/utils/ArrayUtils.bs" import "pkg:/source/utils/ArrayUtils.bs"
@@ -68,6 +69,8 @@ function LoadProfilesFromRegistry()
profileNode.color = profile.color profileNode.color = profile.color
profileNode.authState = ProfileContentAuthTokenUtils.DeriveAuthState(ValidString(profile.type), profile.accessToken, profile.refreshToken)
profileNodes.Push(profileNode) profileNodes.Push(profileNode)
end for end for
@@ -88,7 +91,6 @@ function LoadProfilesFromRegistry()
if profileNodes.Count() > 0 if profileNodes.Count() > 0
input = { input = {
profilesService: m.top
invidious: m.invidious invidious: m.invidious
profileNodes: profileNodes profileNodes: profileNodes
} }
@@ -231,6 +233,10 @@ function LoginWithProfile(newProfile as object)
newProfile.color = ColorUtils.RandomSoftColorHex() newProfile.color = ColorUtils.RandomSoftColorHex()
m.profilesContent.insertChild(newProfile, 0) m.profilesContent.insertChild(newProfile, 0)
end if end if
' The id-merge above reuses the existing node, which may carry NeedsReauth — re-derive.
newProfile.authState = ProfileContentAuthTokenUtils.DeriveAuthState(newProfile.type, newProfile.accessToken, newProfile.refreshToken)
SetCurrentProfile(newProfile) SetCurrentProfile(newProfile)
end function end function
@@ -301,38 +307,11 @@ function LogoutWithProfiles(profiles as object) as void
JobSystem.QueueJob(m.jobQueue, Jobs.ProfilesInvidiousUnregisterTokenJob, input) JobSystem.QueueJob(m.jobQueue, Jobs.ProfilesInvidiousUnregisterTokenJob, input)
end function end function
function LogoutWithAccessToken(accessToken as dynamic) as void
if StringUtils.IsNullOrEmpty(accessToken)
return
end if
' We are not going to invalidate the token on the server
' because we are likely dealing with an invalid token
' in the first place. All we need to do is remove the
' profile from the list of profiles.
allProfiles = m.profilesContent.getChildren(-1, 0)
for each profile in allProfiles
if profile.accessToken = accessToken
m.profilesContent.removeChild(profile)
currentProfile = m.top.currentProfile
if currentProfile <> invalid and currentProfile.id = profile.id
SetCurrentProfile(invalid)
else
RefreshActiveProfileState(currentProfile)
SaveUserProfilesToRegistry(invalid)
end if
m.top.onProfileLogout = true
exit for
end if
end for
end function
function SetCurrentProfile(newActiveProfile as object) as void function SetCurrentProfile(newActiveProfile as object) as void
if newActiveProfile = invalid if newActiveProfile = invalid
RefreshActiveProfileState(invalid) RefreshActiveProfileState(invalid)
m.top.currentProfile = invalid m.top.currentProfile = invalid
m.invidious.authToken = invalid m.top.currentProfileChanged = true
LogInfo("Current profile set to <invalid>") LogInfo("Current profile set to <invalid>")
SaveUserProfilesToRegistry(invalid) SaveUserProfilesToRegistry(invalid)
return return
@@ -341,13 +320,7 @@ function SetCurrentProfile(newActiveProfile as object) as void
RefreshActiveProfileState(newActiveProfile) RefreshActiveProfileState(newActiveProfile)
m.top.currentProfile = newActiveProfile m.top.currentProfile = newActiveProfile
m.invidious.authToken = { m.top.currentProfileChanged = true
token: newActiveProfile.accessToken
instance: newActiveProfile.serverUrl
username: newActiveProfile.username
activeIdentifyToken: newActiveProfile.activeIdentifyToken
profileNode: newActiveProfile
}
LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl) LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl)
SaveUserProfilesToRegistry(invalid) SaveUserProfilesToRegistry(invalid)
end function end function
@@ -7,6 +7,7 @@
--> -->
<field id="__version" type="integer" value="1" /> <field id="__version" type="integer" value="1" />
<field id="currentProfile" type="node" /> <field id="currentProfile" type="node" />
<field id="currentProfileChanged" type="boolean" alwaysNotify="true" />
<field id="onProfileLogout" type="boolean" alwaysNotify="true" /> <field id="onProfileLogout" type="boolean" alwaysNotify="true" />
<field id="content" type="node" /> <field id="content" type="node" />
@@ -17,7 +18,6 @@
<function name="LoginWithProfile" /> <function name="LoginWithProfile" />
<function name="LogoutWithProfile" /> <function name="LogoutWithProfile" />
<function name="LogoutWithProfiles" /> <function name="LogoutWithProfiles" />
<function name="LogoutWithAccessToken" />
<function name="SetCurrentProfile" /> <function name="SetCurrentProfile" />
<function name="SaveUserProfilesToRegistry" /> <function name="SaveUserProfilesToRegistry" />
</interface> </interface>
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
@@ -5,37 +6,21 @@ import "pkg:/source/utils/StringUtils.bs"
function ExecuteJob() as void function ExecuteJob() as void
input = JobGetInput() input = JobGetInput()
profilesNode = input.profilesService
invidiousNode = input.invidious invidiousNode = input.invidious
profileContentNodes = input.profileNodes profileContentNodes = input.profileNodes
service = new Invidious.InvidiousService(invidiousNode) service = new Invidious.InvidiousService(invidiousNode)
invalidProfiles = []
for each profileNode in profileContentNodes for each profileNode in profileContentNodes
if not StringUtils.IsNullOrEmpty(profileNode.refreshToken) if profileNode.type <> "invidious"
continue for
end if
if profileNode.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
continue for continue for
end if end if
if not service.VerifyTokenScope(profileNode.accessToken) if not service.VerifyTokenScope(profileNode.accessToken)
invalidProfiles.push(profileNode) ' The stored token can't make authenticated calls anymore (e.g. scopes changed in an update).
profileNode@.MarkNeedsReauth()
end if end if
end for end for
if invalidProfiles.Count() = 0
return
end if
profilesNode@.LogoutWithProfiles(invalidProfiles)
profileNames = []
for each profileNode in invalidProfiles
profileNames.push(profileNode.username)
end for
profileNames = profileNames.join(", ")
message = Tr(Locale.Dialogs.UserLoggedOutMessage).Replace("\n", `\n`).Replace("%1", profileNames)
DialogUtils.ShowDialogEx({
message: message
title: Tr(Locale.Dialogs.UserLoggedOut)
})
end function end function
@@ -26,7 +26,7 @@ function OnNodeReady()
DisposableObserveField(m.top, "visible", FuncName(OnVisibilityChange)) DisposableObserveField(m.top, "visible", FuncName(OnVisibilityChange))
' TODO:P1 Reload when subscriptions change ' TODO:P1 Reload when subscriptions change
DisposableObserveFieldScoped(m.invidious, "authToken", FuncName(OnAuthTokenChange)) DisposableObserveFieldScoped(m.profilesService, "currentProfileChanged", FuncName(OnCurrentProfileChanged))
InitializeLongPress(["OK"]) InitializeLongPress(["OK"])
end function end function
@@ -206,7 +206,7 @@ function Refresh(_unused as dynamic)
InitContent() InitContent()
end function end function
function OnAuthTokenChange() function OnCurrentProfileChanged()
' TODO:P2: Reload only content that is authenticated ' TODO:P2: Reload only content that is authenticated
' Should not reload if the page is not visible. Instead, capture state and reload when the page becomes visible ' Should not reload if the page is not visible. Instead, capture state and reload when the page becomes visible
InitContent() InitContent()
@@ -2,6 +2,7 @@
<interface> <interface>
<field id="appController" type="node" bind="/AppController" /> <field id="appController" type="node" bind="/AppController" />
<field id="invidious" type="node" bind="/Invidious" /> <field id="invidious" type="node" bind="/Invidious" />
<field id="profilesService" type="node" bind="/ProfilesService" />
<field id="videoQueue" type="node" bind="/VideoQueue" /> <field id="videoQueue" type="node" bind="/VideoQueue" />
<field id="bookmarksService" type="node" bind="/BookmarksService" /> <field id="bookmarksService" type="node" bind="/BookmarksService" />
<field id="jobQueue" type="node" bind="/JobQueue" /> <field id="jobQueue" type="node" bind="/JobQueue" />
@@ -1,6 +1,8 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/utils/MessagePortUtils.bs" import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
@job("MarkVideoWatchedJob") @job("MarkVideoWatchedJob")
function ExecuteJob() as void function ExecuteJob() as void
@@ -8,28 +10,37 @@ function ExecuteJob() as void
videoId = input.videoId videoId = input.videoId
invidiousNode = input.invidious invidiousNode = input.invidious
authToken = input.authToken profile = input.profile
profileType = input.profileType
playbackTrackingUrls = input.playbackTrackingUrls playbackTrackingUrls = input.playbackTrackingUrls
cpn = input.cpn cpn = input.cpn
cancellation = JobGetCancellation() cancellation = JobGetCancellation()
if profileType = "invidious" profileType = profile.type
service = new Invidious.InvidiousService(invidiousNode) if profileType <> "invidious" and profileType <> "youtube"
service.MarkVideoWatched(videoId, cancellation)
return
end if
if profileType <> "youtube"
JobError(`Unsupported profile type: ${profileType}`) JobError(`Unsupported profile type: ${profileType}`)
return return
end if end if
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return
end if
if profileType = "invidious"
service = new Invidious.InvidiousService(invidiousNode)
service.MarkVideoWatched(auth, videoId, cancellation)
return
end if
accessToken = auth.token
onBehalfOfUser = auth.activeIdentifyToken
freshUntilSeconds = auth.freshUntilSeconds
refreshRequested = WatchTimeAuthRefreshDue(freshUntilSeconds)
if playbackTrackingUrls = invalid or StringUtils.IsNullOrEmpty(playbackTrackingUrls.videostatsPlaybackUrl) or StringUtils.IsNullOrEmpty(playbackTrackingUrls.videostatsWatchtimeUrl) if playbackTrackingUrls = invalid or StringUtils.IsNullOrEmpty(playbackTrackingUrls.videostatsPlaybackUrl) or StringUtils.IsNullOrEmpty(playbackTrackingUrls.videostatsWatchtimeUrl)
playbackTrackingUrls = InnertubeService.AuthGetPlaybackTrackingUrls(videoId, { playbackTrackingUrls = InnertubeService.AuthGetPlaybackTrackingUrls(videoId, {
accessToken: authToken.token accessToken: accessToken
onBehalfOfUser: authToken.activeIdentifyToken onBehalfOfUser: onBehalfOfUser
cancellation: cancellation cancellation: cancellation
}) })
end if end if
@@ -49,8 +60,8 @@ function ExecuteJob() as void
end if end if
markedAsWatched = InnertubeService.AuthMarkVideoWatched(playbackTrackingUrls.videostatsPlaybackUrl, { markedAsWatched = InnertubeService.AuthMarkVideoWatched(playbackTrackingUrls.videostatsPlaybackUrl, {
accessToken: authToken.token accessToken: accessToken
onBehalfOfUser: authToken.activeIdentifyToken onBehalfOfUser: onBehalfOfUser
cpn: cpn cpn: cpn
cancellation: cancellation cancellation: cancellation
}) })
@@ -72,33 +83,73 @@ function ExecuteJob() as void
port = CreateObject("roMessagePort") port = CreateObject("roMessagePort")
callbackNode = JobGetCallbackNode() callbackNode = JobGetCallbackNode()
MessagePortUtils.ObserveFieldScopedExSafe(callbackNode, "watchTime", port) MessagePortUtils.ObserveFieldScopedExSafe(callbackNode, "watchTime", port)
' authState, not refreshCompleted: EnsureFreshAccessToken below unobserves
' refreshCompleted component-wide, which would remove this observer with it.
MessagePortUtils.ObserveFieldScopedExSafe(profile, "authState", port)
CancellationUtils.ObserveCancellationScoped(cancellation, port) CancellationUtils.ObserveCancellationScoped(cancellation, port)
successiveFailures = 0 successiveFailures = 0
while true while true
message = wait(60000, port) message = wait(WatchTimeAuthWaitMs(freshUntilSeconds, refreshRequested), port)
if CancellationUtils.IsCancellationEvent(cancellation, message) if CancellationUtils.IsCancellationEvent(cancellation, message)
JobCancel() JobCancel()
return return
end if end if
if message = invalid if message = invalid
if refreshRequested or WatchTimeAuthRefreshDue(freshUntilSeconds)
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return
end if
accessToken = auth.token
onBehalfOfUser = auth.activeIdentifyToken
freshUntilSeconds = auth.freshUntilSeconds
refreshRequested = WatchTimeAuthRefreshDue(freshUntilSeconds)
end if
continue while continue while
end if end if
' Drain the port to get the latest watch time watchTime = invalid
if IsWatchTimeEvent(callbackNode, message)
watchTime = message.getData()
else if IsAuthStateEvent(profile, message)
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return
end if
accessToken = auth.token
onBehalfOfUser = auth.activeIdentifyToken
freshUntilSeconds = auth.freshUntilSeconds
refreshRequested = WatchTimeAuthRefreshDue(freshUntilSeconds)
end if
' Drain the port to get the latest watch time and any credential transition.
newMessage = port.GetMessage() newMessage = port.GetMessage()
while newMessage <> invalid while newMessage <> invalid
if CancellationUtils.IsCancellationEvent(cancellation, newMessage) if CancellationUtils.IsCancellationEvent(cancellation, newMessage)
JobCancel() JobCancel()
return return
else if IsWatchTimeEvent(callbackNode, newMessage)
watchTime = newMessage.getData()
else if IsAuthStateEvent(profile, newMessage)
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return
end if
accessToken = auth.token
onBehalfOfUser = auth.activeIdentifyToken
freshUntilSeconds = auth.freshUntilSeconds
refreshRequested = WatchTimeAuthRefreshDue(freshUntilSeconds)
end if end if
message = newMessage
newMessage = port.GetMessage() newMessage = port.GetMessage()
end while end while
watchTime = message.getData() if watchTime = invalid
continue while
end if
success = InnertubeService.AuthMarkVideoWatchTime(watchTime, playbackTrackingUrls.videostatsWatchtimeUrl, { success = InnertubeService.AuthMarkVideoWatchTime(watchTime, playbackTrackingUrls.videostatsWatchtimeUrl, {
accessToken: authToken.token accessToken: accessToken
onBehalfOfUser: authToken.activeIdentifyToken onBehalfOfUser: onBehalfOfUser
cpn: cpn cpn: cpn
' TODO:P1 if we pass cancellation here, http client will remove scoped ' TODO:P1 if we pass cancellation here, http client will remove scoped
' observer, which is stored on the current node. ' observer, which is stored on the current node.
@@ -117,3 +168,41 @@ function ExecuteJob() as void
end if end if
end while end while
end function end function
function WatchTimeAuthRefreshDue(freshUntilSeconds as dynamic) as boolean
if not IsNumber(freshUntilSeconds) or freshUntilSeconds <= 0
return false
end if
return TimeUtils.Now().AsSeconds() >= freshUntilSeconds
end function
function WatchTimeAuthWaitMs(freshUntilSeconds as dynamic, refreshRequested as boolean) as integer
if refreshRequested or not IsNumber(freshUntilSeconds) or freshUntilSeconds <= 0
return 60000
end if
secondsUntilRefresh = freshUntilSeconds - TimeUtils.Now().AsSeconds()
if secondsUntilRefresh <= 0
return 1
end if
if secondsUntilRefresh > 60
return 60000
end if
return secondsUntilRefresh * 1000
end function
function IsWatchTimeEvent(callbackNode as object, message as dynamic) as boolean
if type(message) <> "roSGNodeEvent"
return false
end if
node = message.getRoSGNode()
return node <> invalid and node.isSameNode(callbackNode) and message.getField() = "watchTime"
end function
function IsAuthStateEvent(profile as object, message as dynamic) as boolean
if type(message) <> "roSGNodeEvent"
return false
end if
node = message.getRoSGNode()
return node <> invalid and node.isSameNode(profile) and message.getField() = "authState"
end function
@@ -1,6 +1,8 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/MessagePortUtils.bs" import "pkg:/source/utils/MessagePortUtils.bs"
@job("VideoContentJob") @job("VideoContentJob")
@@ -49,11 +51,18 @@ function ExecuteJob() as void
accessToken = invalid accessToken = invalid
onBehalfOfUser = invalid onBehalfOfUser = invalid
profileNode = invalid profileNode = invalid
authToken = invidiousNode.authToken profile = profilesService.currentProfile
if authToken <> invalid and authToken.profileNode <> invalid and authToken.profileNode.type = "youtube" and not StringUtils.IsNullOrEmpty(authToken.token) if profile <> invalid and profile.type = "youtube"
accessToken = authToken.token auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
onBehalfOfUser = authToken.activeIdentifyToken if auth.state = ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth
profileNode = authToken.profileNode JobError(Locale.Dialogs.ProfileNeedsReauthMessage)
return
end if
if auth.state = ProfileContentAuthTokenUtils.AccessTokenState.Ok
accessToken = auth.token
onBehalfOfUser = auth.activeIdentifyToken
profileNode = profile
end if
end if end if
metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, { metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, {
@@ -1,5 +1,6 @@
#const DEBUG_LOG_VIDEO_QUALITY = false #const DEBUG_LOG_VIDEO_QUALITY = false
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Dialog/DialogUtils.bs" import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/JobSystem/Jobs.bs" import "pkg:/components/JobSystem/Jobs.bs"
import "pkg:/components/JobSystem/JobSystem.bs" import "pkg:/components/JobSystem/JobSystem.bs"
@@ -359,9 +360,11 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, c
return return
end if end if
invidious = m.top.invidious profile = m.top.profilesService.currentProfile
authToken = invidious.authToken if profile = invalid
if authToken = invalid return
end if
if profile.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
return return
end if end if
@@ -369,13 +372,10 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, c
m.markVideoWatchedJob.cancel = true m.markVideoWatchedJob.cancel = true
end if end if
profileType = authToken.profileNode.type
input = { input = {
videoId: videoId videoId: videoId
invidious: invidious invidious: m.top.invidious
authToken: authToken profile: profile
profileType: profileType
playbackTrackingUrls: playbackTrackingUrls playbackTrackingUrls: playbackTrackingUrls
cpn: cpn cpn: cpn
} }
@@ -384,7 +384,7 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, c
m.markVideoWatchedJob.addField("watchTime", "float", false) m.markVideoWatchedJob.addField("watchTime", "float", false)
JobSystem.QueueJob(m.jobQueue, Jobs.MarkVideoWatchedJob, input, m.markVideoWatchedJob) JobSystem.QueueJob(m.jobQueue, Jobs.MarkVideoWatchedJob, input, m.markVideoWatchedJob)
if profileType <> "youtube" if profile.type <> "youtube"
return return
end if end if
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Dialog/DialogUtils.bs" import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/JobSystem/Jobs.bs" import "pkg:/components/JobSystem/Jobs.bs"
import "pkg:/components/JobSystem/JobSystem.bs" import "pkg:/components/JobSystem/JobSystem.bs"
@@ -1235,20 +1236,20 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, c
if StringUtils.IsNullOrEmpty(videoId) if StringUtils.IsNullOrEmpty(videoId)
return return
end if end if
invidious = m.top.invidious profile = m.top.profilesService.currentProfile
authToken = invidious.authToken if profile = invalid
if authToken = invalid return
end if
if profile.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
return return
end if end if
if m.markVideoWatchedJob <> invalid if m.markVideoWatchedJob <> invalid
m.markVideoWatchedJob.cancel = true m.markVideoWatchedJob.cancel = true
end if end if
profileType = authToken.profileNode.type
input = { input = {
videoId: videoId videoId: videoId
invidious: invidious invidious: m.top.invidious
authToken: authToken profile: profile
profileType: profileType
playbackTrackingUrls: playbackTrackingUrls playbackTrackingUrls: playbackTrackingUrls
cpn: cpn cpn: cpn
} }
@@ -1258,7 +1259,7 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, c
' only YouTube profiles take the periodic watch-time updates. ' only YouTube profiles take the periodic watch-time updates.
m.watchTimeMarker = -1 m.watchTimeMarker = -1
m.reportWatchTime = (profileType = "youtube") m.reportWatchTime = (profile.type = "youtube")
end function end function
function SeekToInitialPosition(content as object) as void function SeekToInitialPosition(content as object) as void
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Innertube/Constants.bs" import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Innertube/PoTokens.bs" import "pkg:/components/Services/Innertube/PoTokens.bs"
@@ -160,8 +161,12 @@ namespace Http
} }
currentProfile = m.profilesService.currentProfile currentProfile = m.profilesService.currentProfile
tokenResult = invalid
if currentProfile <> invalid and currentProfile.type = "youtube" if currentProfile <> invalid and currentProfile.type = "youtube"
options["accessToken"] = currentProfile.accessToken tokenResult = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(currentProfile)
end if
if tokenResult <> invalid and tokenResult.state = ProfileContentAuthTokenUtils.AccessTokenState.Ok
options["accessToken"] = tokenResult.token
else else
options["visitorData"] = m.innertube.sessionData.visitorData options["visitorData"] = m.innertube.sessionData.visitorData
end if end if
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs" import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
import "pkg:/source/utils/CryptoUtils.bs" import "pkg:/source/utils/CryptoUtils.bs"
@@ -54,9 +55,13 @@ namespace Http
request = context.request request = context.request
response = context.response response = context.response
token = m.invidiousNode.authToken profile = m.invidiousService.GetCurrentProfile()
if token = invalid if profile = invalid
response.Default(403, "No token, not logged in") response.Default(403, "Not logged in")
return true
end if
if profile.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
response.Default(403, "Session expired. Please sign in again.")
return true return true
end if end if
@@ -64,10 +64,6 @@
<source>Failed to load channel %1</source> <source>Failed to load channel %1</source>
<translation>Der Kanal %1 konnte nicht geladen werden</translation> <translation>Der Kanal %1 konnte nicht geladen werden</translation>
</message> </message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>Es sieht so aus, als hätten Sie sich bei Invidious angemeldet, ohne jedoch die erforderlichen Berechtigungen zu besitzen.\nAus diesem Grund wurden Sie aus Folgenden Profilen ausgeloggt: %1\nBitte loggen Sie sich wieder ein.\nDies kann Folge eines Updates von Playlet sein.\nWir entschuldigen uns für entstandene Unannehmlichkeiten.</translation>
</message>
<message> <message>
<source>Premieres in 1 minute</source> <source>Premieres in 1 minute</source>
<translation>Premiere in 1 Minute</translation> <translation>Premiere in 1 Minute</translation>
@@ -428,10 +424,6 @@
<source>Failed to load feed</source> <source>Failed to load feed</source>
<translation>Feed konnte nicht geladen werden</translation> <translation>Feed konnte nicht geladen werden</translation>
</message> </message>
<message>
<source>User logged out</source>
<translation>Benutzer ausgellogt</translation>
</message>
<message> <message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source> <source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>Bildschirm ID konnte nicht gefunden werden. Bitte starten sie Playlet neu, um die Cast-Funktion nutzen zu können.</translation> <translation>Bildschirm ID konnte nicht gefunden werden. Bitte starten sie Playlet neu, um die Cast-Funktion nutzen zu können.</translation>
+12 -4
View File
@@ -225,12 +225,20 @@
<translation>Failed to load feed</translation> <translation>Failed to load feed</translation>
</message> </message>
<message> <message>
<source>User logged out</source> <source>Session expired</source>
<translation>User logged out</translation> <translation>Session expired</translation>
</message> </message>
<message> <message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source> <source>The session has expired. Please sign in again with this profile, or switch to another profile.</source>
<translation>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</translation> <translation>The session has expired. Please sign in again with this profile, or switch to another profile.</translation>
</message>
<message>
<source>The session has expired.</source>
<translation>The session has expired.</translation>
</message>
<message>
<source>Please sign in again with this profile, or switch to another profile.</source>
<translation>Please sign in again with this profile, or switch to another profile.</translation>
</message> </message>
<message> <message>
<source>Lounge service setup error</source> <source>Lounge service setup error</source>
@@ -208,10 +208,6 @@
<source>Failed to load feed</source> <source>Failed to load feed</source>
<translation>Fallo al cargar el feed</translation> <translation>Fallo al cargar el feed</translation>
</message> </message>
<message>
<source>User logged out</source>
<translation>Usuario desconectado</translation>
</message>
<message> <message>
<source>Lounge service setup error</source> <source>Lounge service setup error</source>
<translation>Error de configuración del servicio Lounge</translation> <translation>Error de configuración del servicio Lounge</translation>
@@ -360,10 +356,6 @@
<source>Invalid JSON from %1 (couldn&apos;t read %2)</source> <source>Invalid JSON from %1 (couldn&apos;t read %2)</source>
<translation>JSON no válido para %1 (no se pudo leer %2)</translation> <translation>JSON no válido para %1 (no se pudo leer %2)</translation>
</message> </message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>Parece que has iniciado sesión en Invidious, pero no tienes los permisos necesarios.\nPor este motivo, hemos cerrado tu sesión en los siguientes perfiles: %1\nPor favor, inicia sesión de nuevo.\nEsto puede suceder cuando Playlet se actualiza con nuevas características.\nDisculpa las molestias.</translation>
</message>
<message> <message>
<source>Refresh</source> <source>Refresh</source>
<translation>Recargar</translation> <translation>Recargar</translation>
@@ -828,10 +828,6 @@
<source>Playlist load error</source> <source>Playlist load error</source>
<translation>Error al cargar la playlist</translation> <translation>Error al cargar la playlist</translation>
</message> </message>
<message>
<source>User logged out</source>
<translation>Usuario cerró sesión</translation>
</message>
<message> <message>
<source>Failed to load playlist %1</source> <source>Failed to load playlist %1</source>
<translation>Error al cargar la playlist %1</translation> <translation>Error al cargar la playlist %1</translation>
@@ -924,10 +920,6 @@
<source>Tap &apos;Link with TV code&apos; and enter the code below.</source> <source>Tap &apos;Link with TV code&apos; and enter the code below.</source>
<translation>Presiona &quot;Vincular con código de TV&quot;, y luego, ingresa el código que se muestra abajo.</translation> <translation>Presiona &quot;Vincular con código de TV&quot;, y luego, ingresa el código que se muestra abajo.</translation>
</message> </message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>Parece que has iniciado sesión en Invidious, pero no tienes los permisos necesarios.\nPor esta razón, hemos cerrado tu sesión en los siguientes perfiles: %1\nPor favor, accede de nuevo.\nEsto puede pasar cuando Playlet es actualizado con nuevas características.\nLo sentimos por la inconveniencia.</translation>
</message>
<message> <message>
<source>Tap the cast icon and select %1</source> <source>Tap the cast icon and select %1</source>
<translation>Presiona el ícono de transmisión y selecciona %1</translation> <translation>Presiona el ícono de transmisión y selecciona %1</translation>
@@ -208,14 +208,6 @@
<source>Failed to load feed</source> <source>Failed to load feed</source>
<translation>Échec du chargement du flux</translation> <translation>Échec du chargement du flux</translation>
</message> </message>
<message>
<source>User logged out</source>
<translation>Utilisateur déconnecté</translation>
</message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>Il semble que vous soyez connecté à Invidious, mais n&apos;avez pas les permissions requises.\nPour cette raison, nous vous avons déconnecté des profils suivants : %1\nVeuillez vous reconnecter.\nCela peut se produire lorsque Playlet est mis à jour avec de nouvelles fonctionnalités.\nNous nous excusons pour la gêne occasionnée.</translation>
</message>
<message> <message>
<source>Lounge service setup error</source> <source>Lounge service setup error</source>
<translation>Erreur de configuration du service Lounge</translation> <translation>Erreur de configuration du service Lounge</translation>
@@ -216,14 +216,6 @@
<source>Failed to load feed</source> <source>Failed to load feed</source>
<translation>Erro ao carregar o feed</translation> <translation>Erro ao carregar o feed</translation>
</message> </message>
<message>
<source>User logged out</source>
<translation>Usuário desconectado</translation>
</message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>Parece que você está logado no Invidious, mas não tem as permissões necessárias.\nPor esse motivo, nós o desconectamos dos seguintes perfis: %1\nPor favor, faça login novamente.\nIsso pode acontecer quando o Playlet é atualizado com novos recursos.\nPedimos desculpas pelo inconveniente.</translation>
</message>
<message> <message>
<source>Lounge service setup error</source> <source>Lounge service setup error</source>
<translation>Erro ao configurar o serviço de lounge</translation> <translation>Erro ao configurar o serviço de lounge</translation>
@@ -0,0 +1,51 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Innertube/OAuth.bs"
import "pkg:/source/utils/StringUtils.bs"
namespace Tests
@tags("integration")
@suite
class InnertubeRefreshTokenIntegrationTests extends Rooibos.BaseTestSuite
protected override function setup()
m.logger = CreateObject("roSGNode", "Logger")
m.logger.logLevel = -1
' A failed refresh goes through HttpClient's retry loop, which emits a
' telemetry warning; give the stub a no-op telemetry sink to write to.
telemetry = CreateObject("roSGNode", "Node")
telemetry.addField("LogWarn", "string", false)
telemetry.addField("LogEvent", "assocarray", false)
m.global.addFields({ telemetry: telemetry })
end function
@describe("Innertube refresh-token terminal classification (live)")
@slow(20000)
@it("A dead refresh token throws an error classified terminal (so it is cleared + re-auth, not retry-stormed)")
function _()
' A real client_id/secret with an invalid refresh token gets a real invalid_grant from Google.
identity = Innertube.GetClientIdentity(invalid)
m.assertFalse(IsAssociativeArray(identity) and identity.DoesExist("error"), "GetClientIdentity failed: " + FormatJson(identity))
m.assertFalse(StringUtils.IsNullOrEmpty(identity.clientId), "no client id scraped")
accessTokenObject = {
clientId: identity.clientId
clientSecret: identity.clientSecret
refreshToken: "invalid-refresh-token"
}
threw = false
try
InnertubeService.AuthRefreshAccessToken(accessTokenObject, invalid)
catch error
threw = true
end try
m.assertTrue(threw, "a dead refresh token must surface as a thrown error")
m.assertTrue(ValidBool(accessTokenObject.terminalRefreshError), "a dead refresh token must flag terminalRefreshError on the shared accessToken object")
end function
end class
end namespace
@@ -0,0 +1,27 @@
import "pkg:/components/Services/Innertube/OAuth.bs"
namespace Tests
@suite
class InnertubeOAuthTerminalErrorTests extends Rooibos.BaseTestSuite
@describe("Innertube.IsTerminalRefreshError")
@it("Returns true for terminal OAuth error codes (RFC 6749 §5.2)")
function _()
m.assertTrue(Innertube.IsTerminalRefreshError({ error: "invalid_grant" }))
m.assertTrue(Innertube.IsTerminalRefreshError({ error: "invalid_client" }))
m.assertTrue(Innertube.IsTerminalRefreshError({ error: "unauthorized_client" }))
end function
@it("Returns false for transient, successful, or non-object bodies")
function _()
m.assertFalse(Innertube.IsTerminalRefreshError({ error: "authorization_pending" }))
m.assertFalse(Innertube.IsTerminalRefreshError({ access_token: "ya29.abc" }))
m.assertFalse(Innertube.IsTerminalRefreshError({}))
m.assertFalse(Innertube.IsTerminalRefreshError(invalid))
end function
end class
end namespace
@@ -0,0 +1,135 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
namespace Tests
@SGNode("Group")
@suite
class ProfileContentAuthTokenUtilsTests extends Rooibos.BaseTestSuite
@describe("ProfileContentAuthTokenUtils.DeriveAuthState")
@it("A YouTube profile with a refresh token is Authenticated, even with a stale access token")
function _()
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("youtube", "", "rt"), ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated)
end function
@it("A YouTube profile without a refresh token is NeedsReauth, even with an access token")
function _()
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("youtube", "stale", ""), ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth)
end function
@it("An Invidious profile derives from its access token")
function _()
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("invidious", "token", ""), ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated)
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("invidious", "", ""), ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth)
end function
@it("An Invidious token past its embedded expire is NeedsReauth")
function _()
nowSeconds = CreateObject("roDateTime").AsSeconds()
expired = FormatJson({ session: "v1:abc", expire: nowSeconds - 60, scopes: ["GET:subscriptions"], signature: "sig" })
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("invidious", expired, ""), ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth)
end function
@it("An Invidious token with a future expire is Authenticated")
function _()
nowSeconds = CreateObject("roDateTime").AsSeconds()
live = FormatJson({ session: "v1:abc", expire: nowSeconds + 3600, scopes: ["GET:subscriptions"], signature: "sig" })
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("invidious", live, ""), ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated)
end function
@describe("ProfileContentAuthTokenUtils.EnsureFreshAccessToken")
@it("Reports NeedsReauth for a NeedsReauth YouTube profile without starting a refresh")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "youtube"
node.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.state, ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth)
m.assertEqual(result.token, "")
end function
@it("Reports NeedsReauth for a NeedsReauth Invidious profile")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "invidious"
node.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.state, ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth)
m.assertEqual(result.token, "")
end function
@it("Returns the token of an authenticated Invidious profile")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "invidious"
node.accessToken = "inv-token"
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.state, ProfileContentAuthTokenUtils.AccessTokenState.Ok)
m.assertEqual(result.token, "inv-token")
end function
@it("Carries the request context so consumers need no further profile reads")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "invidious"
node.accessToken = "inv-token"
node.serverUrl = "https://instance.example"
node.activeIdentifyToken = "delegation-token"
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.serverUrl, "https://instance.example")
m.assertEqual(result.activeIdentifyToken, "delegation-token")
m.assertTrue(result.profile.isSameNode(node))
end function
@it("Returns a still-valid YouTube token without refreshing")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "youtube"
node.accessToken = "fresh-token"
node.refreshToken = "rt"
expiresTimestamp = CreateObject("roDateTime").AsSeconds() + 7200
node.expiresTimestamp = expiresTimestamp
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.state, ProfileContentAuthTokenUtils.AccessTokenState.Ok)
m.assertEqual(result.token, "fresh-token")
m.assertTrue(result.freshUntilSeconds = expiresTimestamp - 3600)
end function
@it("An empty access token with a live-looking expiry resolves immediately instead of waiting on a refresh that was never started")
function _()
' No current code writes this state; the registry is a shared boundary (other
' builds, tooling), and no stored state may park a waiter on a dead 30s wait.
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "youtube"
node.accessToken = ""
node.refreshToken = ""
node.expiresTimestamp = CreateObject("roDateTime").AsSeconds() + 7200
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.state, ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth)
m.assertEqual(node.authState, ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth)
end function
@describe("ProfileContentNode.MarkNeedsReauth")
@it("Clears the credential and marks the profile in one transition")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "youtube"
node.username = "dying"
node.accessToken = "tok"
node.refreshToken = "rt"
node.expiresTimestamp = 12345
node@.MarkNeedsReauth()
m.assertEqual(node.accessToken, "")
m.assertEqual(node.refreshToken, "")
m.assertEqual(node.expiresTimestamp, 0&)
m.assertEqual(node.authState, ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth)
end function
end class
end namespace
+4 -2
View File
@@ -76,8 +76,10 @@ namespace Locale
InvidiousPublicInstancesLoadError = "Invidious public instances load error" InvidiousPublicInstancesLoadError = "Invidious public instances load error"
FailedToLoadInvidiousPublicInstances = "Failed to load Invidious public instances" FailedToLoadInvidiousPublicInstances = "Failed to load Invidious public instances"
FailedToLoadFeed = "Failed to load feed" FailedToLoadFeed = "Failed to load feed"
UserLoggedOut = "User logged out" ProfileNeedsReauthTitle = "Session expired"
UserLoggedOutMessage = "It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience." ProfileNeedsReauthMessage = "The session has expired. Please sign in again with this profile, or switch to another profile."
ProfileNeedsReauthMessageLine1 = "The session has expired."
ProfileNeedsReauthMessageLine2 = "Please sign in again with this profile, or switch to another profile."
LoungeServiceSetupError = "Lounge service setup error" LoungeServiceSetupError = "Lounge service setup error"
LoungeFailedToGetScreenId = "Failed to get screen ID. Please restart Playlet to use the cast function." LoungeFailedToGetScreenId = "Failed to get screen ID. Please restart Playlet to use the cast function."
LoungeNotAValidScreenId = "Not a valid screen id: %1" LoungeNotAValidScreenId = "Not a valid screen id: %1"