Compare commits

..
9 Commits
62 changed files with 1253 additions and 376 deletions

No files matched your search

+8
View File
@@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.48.1] - 2026-07-04
### Fixed
- Signed-in accounts no longer get stuck sending failing requests after the login session expires
- Parser for channel video live indicator
- Home screen reduced to only the Trending sections after updating to 0.48.0
## [0.48.0] - 2026-07-01 ## [0.48.0] - 2026-07-01
### Added ### Added
+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,
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet", "name": "playlet",
"version": "0.48.0", "version": "0.48.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet", "name": "playlet",
"version": "0.48.0", "version": "0.48.1",
"hasInstallScript": true, "hasInstallScript": true,
"devDependencies": { "devDependencies": {
"@rokucommunity/bslint": "^0.8.44", "@rokucommunity/bslint": "^0.8.44",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet", "name": "playlet",
"version": "0.48.0", "version": "0.48.1",
"description": "Unofficial YouTube client for Roku", "description": "Unofficial YouTube client for Roku",
"devDependencies": { "devDependencies": {
"@rokucommunity/bslint": "^0.8.44", "@rokucommunity/bslint": "^0.8.44",
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet-app", "name": "playlet-app",
"version": "0.48.0", "version": "0.48.1",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-app", "name": "playlet-app",
"version": "0.48.0" "version": "0.48.1"
} }
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-app", "name": "playlet-app",
"version": "0.48.0", "version": "0.48.1",
"description": "Unofficial YouTube client for Roku", "description": "Unofficial YouTube client for Roku",
"scripts": { "scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-app", "prebuild": "node ../tools/rm.js ../build/playlet-app",
+1 -1
View File
@@ -3,7 +3,7 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json # Do not update version manually, it is auto updated from package.json
major_version=0 major_version=0
minor_version=48 minor_version=48
build_version=00000 build_version=00001
ui_resolutions=hd ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p uri_resolution_autosub=$$RES$$,480p,720p,1080p
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.48.0", "version": "0.48.1",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.48.0" "version": "0.48.1"
} }
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.48.0", "version": "0.48.1",
"description": "Unofficial YouTube client for Roku", "description": "Unofficial YouTube client for Roku",
"scripts": { "scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-lib", "prebuild": "node ../tools/rm.js ../build/playlet-lib",
@@ -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>
@@ -23,10 +23,22 @@ namespace HomeScreenUtils
feedItems[item["id"]] = item feedItems[item["id"]] = item
end for end for
' Sections missing from the saved layout (new sections, or layouts
' damaged by old bugs) render as enabled at the end of the feed.
filteredFeed = [] filteredFeed = []
seenIds = {}
for each item in homeLayout for each item in homeLayout
if item.enabled = true if IsAssociativeArray(item) and IsString(item.id)
filteredFeed.push(feedItems[item.id]) seenIds[item.id] = true
if item.enabled = true and feedItems[item.id] <> invalid
filteredFeed.push(feedItems[item.id])
end if
end if
end for
for each item in feed
if not seenIds.DoesExist(item["id"])
filteredFeed.push(item)
end if end if
end for end for
@@ -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>
@@ -1106,10 +1106,10 @@ namespace Innertube
' The badge overlay has two shapes: thumbnailOverlayBadgeViewModel.thumbnailBadges (older, still ' The badge overlay has two shapes: thumbnailOverlayBadgeViewModel.thumbnailBadges (older, still
' used on playlist/podcast/album lockups) and thumbnailBottomOverlayViewModel.badges (video lockups) ' used on playlist/podcast/album lockups) and thumbnailBottomOverlayViewModel.badges (video lockups)
function GetThumbnailBadgeText(thumbnailViewModel as object) as string function ParseThumbnailBadge(thumbnailViewModel as object) as object
overlays = ObjectUtils.Dig(thumbnailViewModel, ["overlays"]) overlays = ObjectUtils.Dig(thumbnailViewModel, ["overlays"])
if not IsArray(overlays) if not IsArray(overlays)
return "" return invalid
end if end if
for each overlay in overlays for each overlay in overlays
@@ -1117,17 +1117,34 @@ namespace Innertube
if not IsArray(badges) if not IsArray(badges)
badges = ObjectUtils.Dig(overlay, ["thumbnailOverlayBadgeViewModel", "thumbnailBadges"]) badges = ObjectUtils.Dig(overlay, ["thumbnailOverlayBadgeViewModel", "thumbnailBadges"])
end if end if
if IsArray(badges) if not IsArray(badges)
for each badge in badges continue for
text = ValidString(ObjectUtils.Dig(badge, ["thumbnailBadgeViewModel", "text"]))
if text <> ""
return text
end if
end for
end if end if
for each badge in badges
badgeViewModel = badge["thumbnailBadgeViewModel"]
if not IsAssociativeArray(badgeViewModel)
continue for
end if
text = ValidString(badgeViewModel["text"])
if text = ""
continue for
end if
return {
"text": text
"isLive": ValidString(badgeViewModel["badgeStyle"]) = "THUMBNAIL_OVERLAY_BADGE_STYLE_LIVE"
}
end for
end for end for
return "" return invalid
end function
function GetThumbnailBadgeText(thumbnailViewModel as object) as string
parsedBadge = ParseThumbnailBadge(thumbnailViewModel)
if parsedBadge = invalid
return ""
end if
return parsedBadge.text
end function end function
function LockupViewModelTypeVideo(nodeData as object, context as object) as object function LockupViewModelTypeVideo(nodeData as object, context as object) as object
@@ -1151,7 +1168,17 @@ namespace Innertube
end if end if
end if end if
lengthText = GetThumbnailBadgeText(thumbnailViewModel) lengthText = ""
liveNow = false
parsedBadge = ParseThumbnailBadge(thumbnailViewModel)
if parsedBadge <> invalid
if parsedBadge.isLive
liveNow = true
else
lengthText = parsedBadge.text
end if
end if
authorId = ObjectUtils.Dig(metadata, ["image", "decoratedAvatarViewModel", "rendererContext", "commandContext", "onTap", "innertubeCommand", "browseEndpoint", "browseId"]) authorId = ObjectUtils.Dig(metadata, ["image", "decoratedAvatarViewModel", "rendererContext", "commandContext", "onTap", "innertubeCommand", "browseEndpoint", "browseId"])
@@ -1183,6 +1210,7 @@ namespace Innertube
"lines": lines "lines": lines
"videoThumbnails": videoThumbnails "videoThumbnails": videoThumbnails
"lengthText": lengthText "lengthText": lengthText
"liveNow": liveNow
} }
PushFeedItem(video, context) PushFeedItem(video, context)
@@ -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
@@ -505,7 +505,9 @@ namespace Innertube
cache = ReadAsciiFile("tmp:/sts_cache.json") cache = ReadAsciiFile("tmp:/sts_cache.json")
if not StringUtils.IsNullOrEmpty(cache) if not StringUtils.IsNullOrEmpty(cache)
json = StringUtils.ParseJsonSafe(cache) json = StringUtils.ParseJsonSafe(cache)
return { sts: json["sts"] } if IsAssociativeArray(json) and json["sts"] <> invalid
return { sts: json["sts"] }
end if
end if end if
request = HttpClient.Get(`${PLAYLET_SUPPORT_SERVER}/v1/sts`) request = HttpClient.Get(`${PLAYLET_SUPPORT_SERVER}/v1/sts`)
@@ -523,8 +525,16 @@ namespace Innertube
end if end if
text = response.Text() text = response.Text()
json = StringUtils.ParseJsonSafe(text)
if not IsAssociativeArray(json) or json["sts"] = invalid
error = "Invalid response from sts service"
LogError(error, text)
return {
error: error
}
end if
WriteAsciiFile("tmp:/sts_cache.json", text) WriteAsciiFile("tmp:/sts_cache.json", text)
json = response.Json()
return { sts: json["sts"] } return { sts: json["sts"] }
end function end function
@@ -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
@@ -198,6 +198,34 @@ function MigrateExistingPreferences(userPrefs as object) as boolean
isDirty = true isDirty = true
end if end if
if userPrefs.__version = 8
' A pre-0.45.0 bug persisted an empty home screen layout on fresh installs,
' which the v7 -> v8 migration then turned into a trending-only layout.
' Heal layouts that lost sections: reset tiny ones to defaults, otherwise
' re-add missing sections as enabled so users notice they are back.
homeScreenLayout = userPrefs["misc.home_screen_layout"]
if IsArray(homeScreenLayout)
if homeScreenLayout.Count() < 3
userPrefs.Delete("misc.home_screen_layout")
else
defaultIds = ["subscriptions", "recommended", "popular", "playlists", "watch_history", "trending_livestreams", "trending_gaming"]
existingIds = {}
for each item in homeScreenLayout
if IsAssociativeArray(item) and IsString(item.id)
existingIds[item.id] = true
end if
end for
for each id in defaultIds
if not existingIds.DoesExist(id)
homeScreenLayout.Push({ id: id, enabled: true })
end if
end for
end if
end if
userPrefs.__version = 9
isDirty = true
end if
' TODO:P2 handle case where saved preferences version is higher than current version (e.g. user downgraded) ' TODO:P2 handle case where saved preferences version is higher than current version (e.g. user downgraded)
#if DEBUG #if DEBUG
@@ -5,7 +5,7 @@
user prefs saved need to be migrated. If the version is less than the user prefs saved need to be migrated. If the version is less than the
current version, a migration is needed. current version, a migration is needed.
--> -->
<field id="__version" type="integer" value="8" /> <field id="__version" type="integer" value="9" />
<field id="prefsModel" type="array" /> <field id="prefsModel" type="array" />
<field id="preferenceFields" type="assocarray" /> <field id="preferenceFields" type="assocarray" />
<function name="GetUserPreferences" /> <function name="GetUserPreferences" />
@@ -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
@@ -22,6 +22,7 @@ namespace PlayerCoordinatorLogic
None = 0 None = 0
Freeze = 1 ' the video is advancing under a transport -> the coordinator must re-pause it Freeze = 1 ' the video is advancing under a transport -> the coordinator must re-pause it
FinishEof = 2 ' VOD played to the end under a transport also sitting at the end -> finish, don't re-pause forever FinishEof = 2 ' VOD played to the end under a transport also sitting at the end -> finish, don't re-pause forever
ResumeLiveTail = 3 ' live: the sliding DVR tail overtook the frozen playhead -> resolve forward, a re-pause cannot stick
end enum end enum
' The buttons in the row above the trackbar, in focus order (the index). The COUNT is owned by ButtonRow ' The buttons in the row above the trackbar, in focus order (the index). The COUNT is owned by ButtonRow
@@ -79,16 +80,26 @@ namespace PlayerCoordinatorLogic
' Only a video actively PLAYING under a transport must be re-paused. Every other state is already ' Only a video actively PLAYING under a transport must be re-paused. Every other state is already
' not-advancing or owned elsewhere: buffering = a seek/rebuffer the bif covers; paused = the desired frozen ' not-advancing or owned elsewhere: buffering = a seek/rebuffer the bif covers; paused = the desired frozen
' state; none/stopping/stopped = teardown; finished/error = handled in their own OnVideoState branches. ' state; none/stopping/stopped = teardown; finished/error = handled in their own OnVideoState branches.
' EXCEPTION: VOD playing at the very end while the transport cursor is ALSO at the end — the device refuses ' EXCEPTION (VOD): playing at the very end while the transport cursor is ALSO at the end — the device refuses
' to stay paused at EOF (the freeze would loop forever), and the user is at the end anyway: finish instead. ' to stay paused at EOF (the freeze would loop forever), and the user is at the end anyway: finish instead.
' A cursor rewound away from the end keeps the freeze (the user is heading backwards). ' A cursor rewound away from the end keeps the freeze (the user is heading backwards).
function TransportSafetyAction(deviceState as string, inTransport as boolean, isLive as boolean, positionMs as integer, cursorMs as integer, durationMs as integer) as integer ' EXCEPTION (live): the sliding DVR tail overtaking the frozen playhead — the device force-resumes such a
' pause on every manifest refresh (from ~10s above the advertised floor), so a re-pause cannot stick and the
' freeze would loop forever; resolve forward instead. liveFloorMs is the availability floor (edge − window),
' or -1 when the window is unknown (no floor knowledge -> plain freeze).
function TransportSafetyAction(deviceState as string, inTransport as boolean, isLive as boolean, positionMs as integer, cursorMs as integer, durationMs as integer, liveFloorMs as integer) as integer
if not inTransport or deviceState <> VideoState.Playing if not inTransport or deviceState <> VideoState.Playing
return SafetyAction.None return SafetyAction.None
end if end if
if isLive
if liveFloorMs >= 0 and positionMs < liveFloorMs + TransportController.LIVE_TAIL_RESUME_MARGIN_MS
return SafetyAction.ResumeLiveTail
end if
return SafetyAction.Freeze
end if
atEof = durationMs > 0 and positionMs >= durationMs - TransportController.FINISH_EPSILON_MS atEof = durationMs > 0 and positionMs >= durationMs - TransportController.FINISH_EPSILON_MS
cursorAtEof = cursorMs >= durationMs - TransportController.FINISH_EPSILON_MS cursorAtEof = cursorMs >= durationMs - TransportController.FINISH_EPSILON_MS
if not isLive and atEof and cursorAtEof if atEof and cursorAtEof
return SafetyAction.FinishEof return SafetyAction.FinishEof
end if end if
return SafetyAction.Freeze return SafetyAction.Freeze
@@ -68,6 +68,15 @@ namespace TransportController
const SCAN_LEVEL_MAX = 3 const SCAN_LEVEL_MAX = 3
const LIVE_DVR_STEP_MS = 5000 const LIVE_DVR_STEP_MS = 5000
const LIVE_EDGE_SEEK_MS = 999999000 ' seek target that means "jump to the live edge" const LIVE_EDGE_SEEK_MS = 999999000 ' seek target that means "jump to the live edge"
' Video.position is single-precision, so the 999999s sentinel echoes back as 999998.976s and
' Int(position * 1000) lands 24ms UNDER the constant. Sentinel checks take this slack — nothing
' legitimate on the window timeline gets near 11.5 days.
const LIVE_EDGE_SENTINEL_SLACK_MS = 100000
' The device will not hold a pause this close to the sliding DVR tail: it force-resumes ~1/s
' (each manifest refresh), starting ~10s ABOVE the advertised floor (measured on device). The
' tail resolution resumes at least this far above the floor so the resumed playhead isn't
' immediately overtaken again.
const LIVE_TAIL_RESUME_MARGIN_MS = 30000
' Live scan base scales with DVR window length: base = effectiveEdge / DIVISOR, floored at the storyboard ' Live scan base scales with DVR window length: base = effectiveEdge / DIVISOR, floored at the storyboard
' interval so short DVRs are unchanged. 4000 -> ~10.8s base on a 12h DVR -> L3 ~65s/tick. ' interval so short DVRs are unchanged. 4000 -> ~10.8s base on a 12h DVR -> L3 ~65s/tick.
const LIVE_SCAN_BASE_DIVISOR = 4000 const LIVE_SCAN_BASE_DIVISOR = 4000
@@ -89,6 +98,13 @@ namespace TransportController
' back on every burst reads as flicker. User actions (rewind/seek/commit) keep the tight band. ' back on every burst reads as flicker. User actions (rewind/seek/commit) keep the tight band.
const LIVE_EDGE_ATEDGE_LEAVE_MS = 6000 const LIVE_EDGE_ATEDGE_LEAVE_MS = 6000
' Whether a device-reported ms value is the live-edge seek sentinel echoing back through the
' single-precision position/duration fields (see LIVE_EDGE_SENTINEL_SLACK_MS): such values are
' seek plumbing, not positions.
function IsLiveEdgeSentinelMs(ms as integer) as boolean
return ms >= TransportController.LIVE_EDGE_SEEK_MS - TransportController.LIVE_EDGE_SENTINEL_SLACK_MS
end function
' The transport state machine. ' The transport state machine.
class Controller class Controller
' ---- content facts (set once at contentReady) ---- ' ---- content facts (set once at contentReady) ----
@@ -200,6 +216,16 @@ namespace TransportController
return floor return floor
end function end function
' The floor for the coordinator's tail-overtake safety decision: the availability floor when
' the window is known, -1 when it is not (without floor knowledge the safety verdict stays a
' plain freeze).
function SafetyFloorMs() as integer
if not m.isLive or m.dvrWindowMs <= 0
return -1
end if
return m.LiveFloorMs()
end function
' Storyboards arrive late (the native Video.thumbnailTiles field populates after the manifest loads), ' Storyboards arrive late (the native Video.thumbnailTiles field populates after the manifest loads),
' so the coordinator updates the scrub step + bif gate here without the live-edge / replay resets that ' so the coordinator updates the scrub step + bif gate here without the live-edge / replay resets that
' SetContent does for new content. ' SetContent does for new content.
@@ -224,7 +250,7 @@ namespace TransportController
' Last real Video position. While idle the cursor tracks it; while a transport is active the machine owns ' Last real Video position. While idle the cursor tracks it; while a transport is active the machine owns
' the cursor. Drops the live-edge seek sentinel echo (see OnDuration). ' the cursor. Drops the live-edge seek sentinel echo (see OnDuration).
function OnPosition(ms as integer) as void function OnPosition(ms as integer) as void
if m.isLive and ms >= TransportController.LIVE_EDGE_SEEK_MS if m.isLive and TransportController.IsLiveEdgeSentinelMs(ms)
return return
end if end if
m.positionMs = ms m.positionMs = ms
@@ -275,7 +301,7 @@ namespace TransportController
' at the manifest's availabilityStartTime and pushed ~1/s. Advances through pauses, rebuffers and ' at the manifest's availabilityStartTime and pushed ~1/s. Advances through pauses, rebuffers and
' startup — the offset/badge math needs no event-pattern heuristics on top. ' startup — the offset/badge math needs no event-pattern heuristics on top.
function OnLiveEdge(ms as integer) as void function OnLiveEdge(ms as integer) as void
if not m.isLive or ms <= 0 or ms >= TransportController.LIVE_EDGE_SEEK_MS if not m.isLive or ms <= 0 or TransportController.IsLiveEdgeSentinelMs(ms)
return return
end if end if
m.edgeMs = ms m.edgeMs = ms
@@ -522,6 +548,24 @@ namespace TransportController
m.commitSeq = m.commitSeq + 1 m.commitSeq = m.commitSeq + 1
end function end function
' The sliding DVR tail overtook the frozen playhead (SafetyAction.ResumeLiveTail): the device
' force-resumes such a pause on every manifest refresh, so freezing again just loops. Resolve
' the transport forward instead — a normal commit, with the cursor floored above the tail
' (what the stock player does when paused live content expires). The resume parks a FULL margin
' above the trigger threshold: parked exactly on it, the floor advancing through the resume's
' rebuffer leaves the playhead hovering at the boundary and the very next rewind press would
' trip the trigger again and eat itself.
function ResolveLiveTail() as void
if m.transportMode <> TransportController.Mode.LiveDvr
return ' only a frozen live transport has a tail to resolve
end if
floorSafe = m.LiveFloorMs() + 2 * TransportController.LIVE_TAIL_RESUME_MARGIN_MS
if m.cursorMs < floorSafe
m.cursorMs = m.Clamp(floorSafe, 0, m.LiveEdgeMs())
end if
m.Commit()
end function
' The EFFECTIVE live edge: raw edge minus the latency baseline (where the offset reads 0 / "● LIVE"). ' The EFFECTIVE live edge: raw edge minus the latency baseline (where the offset reads 0 / "● LIVE").
' Forward commit + cursor clamp use THIS so the offset-hits-0 point and the auto-commit point COINCIDE — ' Forward commit + cursor clamp use THIS so the offset-hits-0 point and the auto-commit point COINCIDE —
' no dead-zone seeking forward past the visible edge. ' no dead-zone seeking forward past the visible edge.
@@ -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"
@@ -17,6 +18,11 @@ import "pkg:/source/utils/RemoteKeys.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/Types.bs"
' Per-content ceiling on INV-D1 heal / tail-resolve telemetry: a pathological loop otherwise emits one
' error per second for as long as it runs. Occurrences keep counting past the cap (each message carries
' its ordinal) and a capped heal loop's true total rides out in one summary event when the content ends.
const INV_D1_TELEMETRY_CAP = 3
' Coordinator for the custom video player. extends Video, enableUI=false. ' Coordinator for the custom video player. extends Video, enableUI=false.
' '
' Owns the focused Video node + key router, the Chrome-group fade, PiP resize, and lifecycle plumbing. All ' Owns the focused Video node + key router, the Chrome-group fade, PiP resize, and lifecycle plumbing. All
@@ -59,6 +65,8 @@ function Initialize()
m.errorDialogNode = invalid m.errorDialogNode = invalid
m.ignoreNextFinished = false ' a retry replay -> swallow the next "finished" edge m.ignoreNextFinished = false ' a retry replay -> swallow the next "finished" edge
m.videoPlayedSuccessfully = false ' true once the stream has actually played (gates error-retry) m.videoPlayedSuccessfully = false ' true once the stream has actually played (gates error-retry)
m.healCount = 0 ' INV-D1 heals this content (telemetry stops at INV_D1_TELEMETRY_CAP; total goes out in the close summary)
m.tailResolveCount = 0 ' live tail resolutions this content (telemetry capped the same way)
m.chromeMode = ChromeMode.Hidden m.chromeMode = ChromeMode.Hidden
m.liveBadgeHoldActive = false ' the "● LIVE" reveal hold is running m.liveBadgeHoldActive = false ' the "● LIVE" reveal hold is running
@@ -312,7 +320,7 @@ end function
' Apply a seek (ms). The live "jump to edge" sentinel maps to the live-end seek the OS understands. ' Apply a seek (ms). The live "jump to edge" sentinel maps to the live-end seek the OS understands.
function ApplySeek(seekMs as integer) as void function ApplySeek(seekMs as integer) as void
if seekMs >= TransportController.LIVE_EDGE_SEEK_MS if TransportController.IsLiveEdgeSentinelMs(seekMs)
m.top.seek = 999999 m.top.seek = 999999
return return
end if end if
@@ -776,21 +784,41 @@ end function
' event). Re-pausing yields state=paused -> OnPosition stops -> no loop. ' event). Re-pausing yields state=paused -> OnPosition stops -> no loop.
function EnforceTransportFreeze(source as string) as void function EnforceTransportFreeze(source as string) as void
inTransport = (m.transport.transportMode <> TransportController.Mode.Idle) inTransport = (m.transport.transportMode <> TransportController.Mode.Idle)
action = PlayerCoordinatorLogic.TransportSafetyAction(m.top.state, inTransport, m.transport.isLive, Int(m.top.position * 1000), m.transport.cursorMs, m.transport.durationMs) action = PlayerCoordinatorLogic.TransportSafetyAction(m.top.state, inTransport, m.transport.isLive, Int(m.top.position * 1000), m.transport.cursorMs, m.transport.durationMs, m.transport.SafetyFloorMs())
if action = PlayerCoordinatorLogic.SafetyAction.Freeze if action = PlayerCoordinatorLogic.SafetyAction.Freeze
m.top.control = VideoControl.Pause m.top.control = VideoControl.Pause
' the play-through seek that opened this transport has landed, so clear autoplayAfterSeek; a later ' the play-through seek that opened this transport has landed, so clear autoplayAfterSeek; a later
' seek-complete must not silently un-freeze the video behind the transport. ' seek-complete must not silently un-freeze the video behind the transport.
m.top.autoplayAfterSeek = false m.top.autoplayAfterSeek = false
m.healCount += 1
' Position detail rides in the message; the fingerprint pins grouping (heal + mode + trigger) so it ' Position detail rides in the message; the fingerprint pins grouping (heal + mode + trigger) so it
' stays a handful of issues instead of fragmenting on the per-event posMs/cursorMs values. ' stays a handful of issues instead of fragmenting on the per-event posMs/cursorMs values.
healInfo = `INV-D1 heal: re-pause under active transport. src=${source} mode=${m.transport.transportMode} isLive=${m.transport.isLive} state=${m.top.state} posMs=${Int(m.top.position * 1000)} cursorMs=${m.transport.cursorMs} edgeMs=${m.transport.edgeMs}` ' floorMs=-1 marks an unknown-window live stream — the one shape the tail resolution cannot cover.
healInfo = `INV-D1 heal: re-pause under active transport. src=${source} mode=${m.transport.transportMode} isLive=${m.transport.isLive} state=${m.top.state} posMs=${Int(m.top.position * 1000)} cursorMs=${m.transport.cursorMs} edgeMs=${m.transport.edgeMs} floorMs=${m.transport.SafetyFloorMs()} heal=${m.healCount}`
LogErrorNoTelemetry(healInfo) LogErrorNoTelemetry(healInfo)
LogTelemetryEvent({ if m.healCount <= INV_D1_TELEMETRY_CAP
level: "error" LogTelemetryEvent({
message: healInfo level: "error"
fingerprint: ["INV-D1 heal", m.transport.transportMode, source] message: healInfo
}) fingerprint: ["INV-D1 heal", m.transport.transportMode, source]
})
end if
else if action = PlayerCoordinatorLogic.SafetyAction.ResumeLiveTail
' the tail overtook the frozen playhead: resolve forward (ResolveLiveTail), don't heal. Telemetered
' at info level so the field shows the resolution working — resolve>1 on one content means the
' resumed playhead was overtaken AGAIN, i.e. LIVE_TAIL_RESUME_MARGIN_MS is too small.
m.tailResolveCount += 1
resolveInfo = `INV-D1 tail-resolve: resume forward. src=${source} posMs=${Int(m.top.position * 1000)} cursorMs=${m.transport.cursorMs} floorMs=${m.transport.SafetyFloorMs()} edgeMs=${m.transport.edgeMs} resolve=${m.tailResolveCount}`
LogInfo(resolveInfo)
if m.tailResolveCount <= INV_D1_TELEMETRY_CAP
LogTelemetryEvent({
level: "info"
message: resolveInfo
fingerprint: ["INV-D1 tail-resolve", source]
})
end if
m.transport.ResolveLiveTail()
ApplyTransport()
else if action = PlayerCoordinatorLogic.SafetyAction.FinishEof else if action = PlayerCoordinatorLogic.SafetyAction.FinishEof
' content played to the end under a transport sitting at the end: finishing is what "at the end" ' content played to the end under a transport sitting at the end: finishing is what "at the end"
' means, and the alternative (re-pausing at EOF) loops against the device forever. ' means, and the alternative (re-pausing at EOF) loops against the device forever.
@@ -801,6 +829,19 @@ function EnforceTransportFreeze(source as string) as void
end if end if
end function end function
' A heal loop that ran past the telemetry cap still reports its true size: one tally event when the
' content ends (close or content switch). Loop size is the discriminator between a singleton heal and a
' fight the player lost for minutes — the capped per-event stream can no longer show it.
function SendHealSummary() as void
if m.healCount > INV_D1_TELEMETRY_CAP
LogTelemetryEvent({
level: "error"
message: `INV-D1 heal: ${m.healCount} heals over one content (${m.healCount - INV_D1_TELEMETRY_CAP} past the telemetry cap)`
fingerprint: ["INV-D1 heal suppressed"]
})
end if
end function
' The Video node reached state=error. ErrorDialogController decides retry-vs-dialog; the coordinator applies ' The Video node reached state=error. ErrorDialogController decides retry-vs-dialog; the coordinator applies
' (replay the next URL, or show the scene-level TimedDialog). ' (replay the next URL, or show the scene-level TimedDialog).
function OnVideoError() as void function OnVideoError() as void
@@ -880,7 +921,7 @@ function OnDuration(event as object) as void
m.transport.OnDuration(durMs) ' the brain ignores this on live (the edge comes from the clock) m.transport.OnDuration(durMs) ' the brain ignores this on live (the edge comes from the clock)
' a live stream WITHOUT the manifest anchor in its metadata: anchor the clock off each duration report ' a live stream WITHOUT the manifest anchor in its metadata: anchor the clock off each duration report
' instead (duration freezes during pause, so each report re-anchors; between reports the clock projects). ' instead (duration freezes during pause, so each report re-anchors; between reports the clock projects).
if m.transport.isLive and m.liveAstSeconds <= 0 and durMs > 0 and durMs < TransportController.LIVE_EDGE_SEEK_MS if m.transport.isLive and m.liveAstSeconds <= 0 and durMs > 0 and not TransportController.IsLiveEdgeSentinelMs(durMs)
m.liveFallbackEdgeMs = durMs m.liveFallbackEdgeMs = durMs
m.liveFallbackAtSeconds = NowSeconds() m.liveFallbackAtSeconds = NowSeconds()
PushLiveEdge() PushLiveEdge()
@@ -1120,6 +1161,9 @@ function OnVideoContentJobDone(event as object) as void
' fill them in for VOD. ' fill them in for VOD.
isLive = content <> invalid and content.Live = true isLive = content <> invalid and content.Live = true
m.transport.SetContent(isLive, 2000, false) m.transport.SetContent(isLive, 2000, false)
SendHealSummary() ' the previous content's capped heal tally, if any
m.healCount = 0
m.tailResolveCount = 0
' live floor: how far back the DVR window reaches (0 = unknown -> the brain keeps the [0, edge] clamp). ' live floor: how far back the DVR window reaches (0 = unknown -> the brain keeps the [0, edge] clamp).
' The generated DASH anchors t=0 to the window start, so floor = edge - window as the session outlives it. ' The generated DASH anchors t=0 to the window start, so floor = edge - window as the session outlives it.
' The same window decides rewindability: a buffer-sized window means no live trickplay at all. ' The same window decides rewindability: a buffer-sized window means no live trickplay at all.
@@ -1192,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
} }
@@ -1215,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
@@ -1511,6 +1555,7 @@ function OnClose() as void
end if end if
m.onCloseCalled = true m.onCloseCalled = true
m.top.previousPlayer = invalid m.top.previousPlayer = invalid
SendHealSummary()
' A closed player must not react to anything anymore. The onCloseCalled guards already make the handlers ' A closed player must not react to anything anymore. The onCloseCalled guards already make the handlers
' no-ops; unobserving stops the traffic at the source — late device edges from the async stop, a stray ' no-ops; unobserving stops the traffic at the source — late device edges from the async stop, a stray
@@ -76,6 +76,14 @@ function TestSetup() as void
m.webServer = m.top.webServer m.webServer = m.top.webServer
m.innertube = m.top.innertube m.innertube = m.top.innertube
' OnNodeReady re-registers the device-field observers; unobserve-first for the same reason as the
' nudge counter above — stacked observers fire a handler once per prior TestSetup on every write,
' and OnPosition's latency learning reads two identical fires as a CONFIRMED min-gap, poisoning
' LiveEdgeMs for any live test that runs after another test in the suite.
for each deviceField in ["state", "position", "duration", "close", "thumbnailTiles", "control"]
m.top.unobserveField(deviceField)
end for
OnNodeReady() OnNodeReady()
end function end function
@@ -175,6 +183,7 @@ function TestSnapshot() as object
return { return {
transportMode: m.transport.transportMode transportMode: m.transport.transportMode
seekSettling: m.transport.seekSettling seekSettling: m.transport.seekSettling
brainEdgeMs: m.transport.edgeMs
onCloseCalled: m.onCloseCalled = true onCloseCalled: m.onCloseCalled = true
control: m.top.control control: m.top.control
autoplay: m.top.autoplayAfterSeek autoplay: m.top.autoplayAfterSeek
@@ -86,6 +86,58 @@ namespace Tests
end for end for
end function end function
' The one live case where the re-freeze must NOT happen: the sliding DVR tail overtook the frozen
' playhead, and the device force-resumes such a pause on every manifest refresh (verified on device) —
' re-pausing loops 1/s forever. The coordinator resolves forward instead: a commit from a cursor
' floored a margin above the tail.
@it("a live playhead the sliding tail overtook resolves forward (commit), not a re-pause loop")
function _()
' 12h stream at the edge, 4h window -> floor = 8h. Park the playhead 5s above the floor (a deep
' rewind), then freeze: the frozen position sits inside the tail margin the device cannot hold.
m.top.callFunc("TestSetLive", 43200000)
m.top.position = 28805.0 ' fires the REAL OnPosition -> brain playhead 28805000ms
m.top.callFunc("TestKey", RemoteKeys.Left, true) ' freeze; the cursor clamps at the floor
m.top.callFunc("TestKey", RemoteKeys.Left, false)
mid = m.Snap()
m.assertEqual(mid.transportMode, TransportController.Mode.LiveDvr)
m.assertEqual(mid.control, VideoControl.Pause)
' the device force-resumes the doomed pause (what the real player does each manifest refresh).
m.top.callFunc("TestSetState", VideoState.Playing)
snap = m.Snap()
m.assertEqual(snap.transportMode, TransportController.Mode.Idle, "the transport resolved instead of fighting")
m.assertEqual(snap.control, VideoControl.Resume, "resumed forward, not re-paused")
m.assertEqual(Int(m.top.seek * 1000), 28860000, "the resume parks a full margin above the trigger (28800s + 60s)")
' the resolution telemeters at info level (never as a heal) with its per-content ordinal.
sent = m.global.telemetry.LogEvent
m.assertEqual(sent.level, "info")
m.assertTrue(sent.message.InStr("INV-D1 tail-resolve") = 0, "got: " + sent.message)
m.assertTrue(sent.message.InStr("resolve=1") > 0)
end function
@it("heal telemetry stops at the cap while the occurrences keep counting")
function _()
' a frozen VOD scrub the device keeps flipping to playing: 5 heals, but only 3 events may leave.
m.top.callFunc("TestKey", RemoteKeys.Left, true)
m.top.callFunc("TestKey", RemoteKeys.Left, false)
for i = 1 to 5
m.top.callFunc("TestSetState", VideoState.Playing)
end for
sent = m.global.telemetry.LogEvent
m.assertTrue(sent.message.InStr("heal=3") > 0, "telemetry must stop at the 3rd heal; last sent: " + sent.message)
end function
@it("a sentinel-valued duration report cannot anchor the live-edge fallback clock")
function _()
m.top.callFunc("TestSetLive", 300000)
' the 999999s live seek echoing back through the single-precision duration field.
m.top.duration = 999998.976
m.assertEqual(m.Snap().brainEdgeMs, 300000, "the sentinel echo must not move the edge")
' a real duration report anchors the fallback and re-feeds the edge.
m.top.duration = 400.0
m.assertEqual(m.Snap().brainEdgeMs, 400000)
end function
' An external resume (the linked phone via Lounge) under an active transport must TAKE OVER: VPD never ' An external resume (the linked phone via Lounge) under an active transport must TAKE OVER: VPD never
' resumes under a transport itself, so a resume here is the phone's. It cancels the scrub and plays. ' resumes under a transport itself, so a resume here is the phone's. It cancels the scrub and plays.
@it("an external Lounge resume under a transport takes over: cancels the scrub and lets it play") @it("an external Lounge resume under a transport takes over: cancels the scrub and lets it play")
@@ -341,7 +393,7 @@ namespace Tests
classified[name] = "axis" classified[name] = "axis"
end for end for
' flags / scratch — one-shot latches and counters with a single consuming path. ' flags / scratch — one-shot latches and counters with a single consuming path.
for each name in ["onCloseCalled", "ignoreNextFinished", "videoPlayedSuccessfully", "firstFrameSeen", "showFullScreenHint", "repauseAfterSeek", "seekToPercent", "watchTimeMarker", "reportWatchTime", "errorDialogNode", "lastCommitSeq", "lastExitSeq", "lastFinishSeq", "liveAstSeconds", "liveFallbackEdgeMs", "liveFallbackAtSeconds", "liveBadgeHoldActive"] for each name in ["onCloseCalled", "ignoreNextFinished", "videoPlayedSuccessfully", "firstFrameSeen", "showFullScreenHint", "repauseAfterSeek", "seekToPercent", "watchTimeMarker", "reportWatchTime", "errorDialogNode", "lastCommitSeq", "lastExitSeq", "lastFinishSeq", "liveAstSeconds", "liveFallbackEdgeMs", "liveFallbackAtSeconds", "liveBadgeHoldActive", "healCount", "tailResolveCount"]
classified[name] = "flag" classified[name] = "flag"
end for end for
' NOT coordinator state — node-scope + test-environment entries, pinned EXPLICITLY (no hidden ' NOT coordinator state — node-scope + test-environment entries, pinned EXPLICITLY (no hidden
@@ -422,7 +474,8 @@ namespace Tests
' FinishEof -> OnPlaybackFinished -> ClosePlayer -> the queue sets player.close -> OnClose drops ' FinishEof -> OnPlaybackFinished -> ClosePlayer -> the queue sets player.close -> OnClose drops
' m.sponsorblock — then OnPosition continues to `m.sponsorblock.OnPosition()` and derefs the dropped ' m.sponsorblock — then OnPosition continues to `m.sponsorblock.OnPosition()` and derefs the dropped
' controller. (`m.sponsorblock` is a field, so the invalid deref is &hf3, not &hec.) The OLD code crashes ' controller. (`m.sponsorblock` is a field, so the invalid deref is &hf3, not &hec.) The OLD code crashes
' here; the onCloseCalled re-check after EnforceTransportFreeze bails. Kept LAST: OnClose detaches the node. ' here; the onCloseCalled re-check after EnforceTransportFreeze bails. Kept at the END with the other
' closing test: OnClose detaches the node.
@it("a finish during a position tick must not deref the dropped sponsorblock (the OnPosition ERR_RO3 crash)") @it("a finish during a position tick must not deref the dropped sponsorblock (the OnPosition ERR_RO3 crash)")
function _() function _()
m.top.callFunc("TestWireQueueClose") ' the stub queue now closes the player on closePlayer, as the real one does m.top.callFunc("TestWireQueueClose") ' the stub queue now closes the player on closePlayer, as the real one does
@@ -446,6 +499,21 @@ namespace Tests
m.assertTrue(m.Snap().onCloseCalled, "the finish closed the player from within the position tick") m.assertTrue(m.Snap().onCloseCalled, "the finish closed the player from within the position tick")
end function end function
' Also at the end (closes the player): a heal loop that ran past the telemetry cap reports its
' true size in one tally event when the content ends.
@it("the close summary carries a capped heal loop's true size")
function _()
m.top.callFunc("TestKey", RemoteKeys.Left, true)
m.top.callFunc("TestKey", RemoteKeys.Left, false)
for i = 1 to 5
m.top.callFunc("TestSetState", VideoState.Playing)
end for
m.top.close = true
summary = m.global.telemetry.LogEvent
m.assertTrue(summary.message.InStr("5 heals") > 0, "got: " + summary.message)
m.assertTrue(summary.message.InStr("2 past the telemetry cap") > 0, "got: " + summary.message)
end function
end class end class
end namespace end namespace
@@ -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
@@ -174,8 +179,18 @@ namespace Http
response.ContentType("text/html; charset=utf-8") response.ContentType("text/html; charset=utf-8")
response.headers["Cache-Control"] = "no-cache" response.headers["Cache-Control"] = "no-cache"
else if IsAssociativeArray(drmResponse) else if IsAssociativeArray(drmResponse)
LogTelemetryEvent({
level: "error"
message: `DRM license request failed: ${ValidString(drmResponse.error)}\nvideoId: ${request.query.videoId}`
fingerprint: ["DRM license request failed"]
})
response.Default(500, FormatJson(drmResponse)) response.Default(500, FormatJson(drmResponse))
else else
LogTelemetryEvent({
level: "error"
message: `DRM license request returned an unexpected response type\nvideoId: ${request.query.videoId}`
fingerprint: ["DRM license request failed"]
})
response.Default(500, "Invalid DRM license response") response.Default(500, "Invalid DRM license response")
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>
+1 -1
View File
@@ -3,7 +3,7 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json # Do not update version manually, it is auto updated from package.json
major_version=0 major_version=0
minor_version=48 minor_version=48
build_version=00000 build_version=00001
ui_resolutions=hd ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p uri_resolution_autosub=$$RES$$,480p,720p,1080p
@@ -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
@@ -101,11 +101,13 @@ namespace Tests
' ========================================================================================= ' =========================================================================================
@describe("TransportSafetyAction (total device-seam guard)") @describe("TransportSafetyAction (total device-seam guard)")
@it("the guard decision is DEFINED and correct over the FULL axis cross-product (state x transport x live x eof)") @it("the guard decision is DEFINED and correct over the FULL axis cross-product (state x transport x live x eof x floor)")
function _() function _()
' the full Roku Video.state enum — including the ones the old guard ignored (none/paused/stopping/ ' the full Roku Video.state enum — including the ones the old guard ignored (none/paused/stopping/
' stopped) — crossed with the live and at-end axes. Only playing-under-a-transport ever acts, and it ' stopped) — crossed with the live, at-end and tail-floor axes. Only playing-under-a-transport ever
' finishes (instead of freezing) exactly when VOD has both the device AND the cursor at the end. ' acts: it finishes (instead of freezing) exactly when VOD has both the device AND the cursor at the
' end, and resolves forward (instead of freezing) exactly when a live playhead sits under the known
' floor + margin. Floors: -1 = unknown, 0 = known but safely below, 100000 = mid pos overtaken.
states = ["none", "buffering", "playing", "paused", "finished", "error", "stopping", "stopped"] states = ["none", "buffering", "playing", "paused", "finished", "error", "stopping", "stopped"]
durationMs = 210000 durationMs = 210000
endMs = 209000 ' within FINISH_EPSILON_MS of the duration endMs = 209000 ' within FINISH_EPSILON_MS of the duration
@@ -115,26 +117,30 @@ namespace Tests
for each isLive in [false, true] for each isLive in [false, true]
for each posAtEnd in [false, true] for each posAtEnd in [false, true]
for each curAtEnd in [false, true] for each curAtEnd in [false, true]
if posAtEnd for each floorMs in [-1, 0, 100000]
posMs = endMs if posAtEnd
else posMs = endMs
posMs = midMs
end if
if curAtEnd
curMs = endMs
else
curMs = midMs
end if
expected = PlayerCoordinatorLogic.SafetyAction.None
if inT and s = "playing"
if not isLive and posAtEnd and curAtEnd
expected = PlayerCoordinatorLogic.SafetyAction.FinishEof
else else
expected = PlayerCoordinatorLogic.SafetyAction.Freeze posMs = midMs
end if end if
end if if curAtEnd
got = PlayerCoordinatorLogic.TransportSafetyAction(s, inT, isLive, posMs, curMs, durationMs) curMs = endMs
m.assertEqual(got, expected, "state=" + s + " inT=" + inT.ToStr() + " live=" + isLive.ToStr() + " posEnd=" + posAtEnd.ToStr() + " curEnd=" + curAtEnd.ToStr()) else
curMs = midMs
end if
expected = PlayerCoordinatorLogic.SafetyAction.None
if inT and s = "playing"
if isLive and floorMs >= 0 and posMs < floorMs + TransportController.LIVE_TAIL_RESUME_MARGIN_MS
expected = PlayerCoordinatorLogic.SafetyAction.ResumeLiveTail
else if not isLive and posAtEnd and curAtEnd
expected = PlayerCoordinatorLogic.SafetyAction.FinishEof
else
expected = PlayerCoordinatorLogic.SafetyAction.Freeze
end if
end if
got = PlayerCoordinatorLogic.TransportSafetyAction(s, inT, isLive, posMs, curMs, durationMs, floorMs)
m.assertEqual(got, expected, "state=" + s + " inT=" + inT.ToStr() + " live=" + isLive.ToStr() + " posEnd=" + posAtEnd.ToStr() + " curEnd=" + curAtEnd.ToStr() + " floor=" + floorMs.ToStr())
end for
end for end for
end for end for
end for end for
@@ -145,22 +151,37 @@ namespace Tests
@it("an unmodeled / unexpected device state under a transport is a safe no-op, never an undefined freeze") @it("an unmodeled / unexpected device state under a transport is a safe no-op, never an undefined freeze")
function _() function _()
' the wedge's failure mode: a state the guard did not enumerate must NOT trigger a spurious freeze. ' the wedge's failure mode: a state the guard did not enumerate must NOT trigger a spurious freeze.
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("buffering", true, false, 60000, 60000, 210000), PlayerCoordinatorLogic.SafetyAction.None) m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("buffering", true, false, 60000, 60000, 210000, -1), PlayerCoordinatorLogic.SafetyAction.None)
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("some_future_state", true, false, 60000, 60000, 210000), PlayerCoordinatorLogic.SafetyAction.None) m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("some_future_state", true, false, 60000, 60000, 210000, -1), PlayerCoordinatorLogic.SafetyAction.None)
end function end function
@it("VOD playing at the end under a transport whose cursor is ALSO at the end -> FinishEof, not Freeze") @it("VOD playing at the end under a transport whose cursor is ALSO at the end -> FinishEof, not Freeze")
function _() function _()
' both the device and the cursor within the 2s epsilon of duration -> finish. ' both the device and the cursor within the 2s epsilon of duration -> finish.
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, false, 209000, 209500, 210000), PlayerCoordinatorLogic.SafetyAction.FinishEof) m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, false, 209000, 209500, 210000, -1), PlayerCoordinatorLogic.SafetyAction.FinishEof)
' cursor rewound away from the end -> the user is heading backwards: keep the freeze. ' cursor rewound away from the end -> the user is heading backwards: keep the freeze.
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, false, 209000, 100000, 210000), PlayerCoordinatorLogic.SafetyAction.Freeze) m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, false, 209000, 100000, 210000, -1), PlayerCoordinatorLogic.SafetyAction.Freeze)
' device not at the end -> freeze as usual. ' device not at the end -> freeze as usual.
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, false, 60000, 209500, 210000), PlayerCoordinatorLogic.SafetyAction.Freeze) m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, false, 60000, 209500, 210000, -1), PlayerCoordinatorLogic.SafetyAction.Freeze)
' LIVE has no EOF: always freeze. ' LIVE has no EOF: always freeze (above the tail).
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, true, 209000, 209500, 210000), PlayerCoordinatorLogic.SafetyAction.Freeze) m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, true, 209000, 209500, 210000, -1), PlayerCoordinatorLogic.SafetyAction.Freeze)
' unknown duration -> no EOF concept -> freeze. ' unknown duration -> no EOF concept -> freeze.
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, false, 209000, 209500, 0), PlayerCoordinatorLogic.SafetyAction.Freeze) m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, false, 209000, 209500, 0, -1), PlayerCoordinatorLogic.SafetyAction.Freeze)
end function
@it("live: the sliding tail overtaking the frozen playhead -> ResumeLiveTail, not a doomed freeze")
function _()
' frozen 10s above a known floor -> inside the resume margin: resolve forward.
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, true, 446000, 441000, 0, 436000), PlayerCoordinatorLogic.SafetyAction.ResumeLiveTail)
' exactly AT floor + margin -> still holdable: keep the freeze.
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, true, 436000 + TransportController.LIVE_TAIL_RESUME_MARGIN_MS, 441000, 0, 436000), PlayerCoordinatorLogic.SafetyAction.Freeze)
' floor unknown (-1) -> no floor knowledge, plain freeze even at a tiny position.
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, true, 5000, 5000, 0, -1), PlayerCoordinatorLogic.SafetyAction.Freeze)
' VOD ignores the floor argument entirely.
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", true, false, 60000, 60000, 210000, 436000), PlayerCoordinatorLogic.SafetyAction.Freeze)
' not playing / not in a transport -> None regardless of the overtaken floor.
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("paused", true, true, 446000, 441000, 0, 436000), PlayerCoordinatorLogic.SafetyAction.None)
m.assertEqual(PlayerCoordinatorLogic.TransportSafetyAction("playing", false, true, 446000, 441000, 0, 436000), PlayerCoordinatorLogic.SafetyAction.None)
end function end function
' ========================================================================================= ' =========================================================================================
@@ -1144,6 +1144,109 @@ namespace Tests
m.assertEqual(t.LiveFloorMs(), 0) m.assertEqual(t.LiveFloorMs(), 0)
end function end function
' =========================================================================================
' LIVE TAIL RESOLUTION — the sliding floor overtaking the frozen playhead cannot be fought
' (the device force-resumes such a pause every manifest refresh): the transport resolves
' forward with a normal commit from a cursor floored above the tail.
' =========================================================================================
@describe("live tail resolution")
' the doom setup: playing deep in the window, frozen by a rewind step, then the edge (and with
' it the floor) slides toward the frozen playhead until it sits inside the trigger margin.
' edge 400->405s, window 300s -> floor 100->105s; frozen playhead at 120s.
function LiveTailOvertaken() as object
t = new TransportController.Controller()
t.SetContent(true, 0, false)
t.SetLiveDvrWindow(300000)
t.OnLiveEdge(400000)
t.OnPosition(400000)
t.OnPosition(400000) ' confirmed latency floor
t.OnReady()
t.OnPosition(120000) ' playing deep in the window (after a deep-rewind commit)
t.HandleCommand(TransportController.Command.Left) ' freeze; cursor steps to 115000
t.TakeVideoIntent() ' drain the freeze pause
t.OnLiveEdge(405000) ' floor 105000: the frozen 120000 playhead is inside the trigger margin
return t
end function
@it("SafetyFloorMs is -1 on VOD and on an unknown live window; the known floor otherwise")
function _()
m.assertEqual(m.t.SafetyFloorMs(), -1) ' VOD
m.assertEqual(m.Live().SafetyFloorMs(), -1) ' live, window unknown
t = m.LiveTailOvertaken()
m.assertEqual(t.SafetyFloorMs(), 105000) ' rides the edge (405000 - 300000)
end function
@it("ResolveLiveTail commits forward from the safe floor when the cursor sits at the tail")
function _()
t = m.LiveTailOvertaken()
m.assertEqual(t.cursorMs, 115000)
t.ResolveLiveTail()
m.assertEqual(t.transportMode, TransportController.Mode.Idle)
intent = t.TakeVideoIntent()
m.assertEqual(intent.control, TransportController.Control.Resume)
m.assertTrue(intent.hasSeek)
m.assertEqual(intent.seekMs, 165000) ' floor 105000 + 2x margin (a full margin above the trigger)
m.assertEqual(t.cursorMs, 165000)
m.assertEqual(t.commitSeq, 1)
m.assertEqual(t.liveOffsetMs, 240000) ' the bar keeps showing how far behind the resume is
m.assertFalse(t.atLiveEdge)
end function
@it("ResolveLiveTail keeps a cursor the user had already moved above the safe floor")
function _()
t = m.LiveTailOvertaken()
for i = 1 to 11 ' step the cursor up from 115000: +5s per press to 170000
t.HandleCommand(TransportController.Command.Right)
end for
m.assertEqual(t.cursorMs, 170000)
t.ResolveLiveTail()
m.assertEqual(t.TakeVideoIntent().seekMs, 170000) ' the user's target wins; only the floor is raised
end function
@it("ResolveLiveTail outside LiveDvr is a no-op (idle, and VOD transports)")
function _()
t = m.LiveWindowed()
t.ResolveLiveTail() ' idle
m.assertEqual(t.transportMode, TransportController.Mode.Idle)
m.assertInvalid(t.TakeVideoIntent())
m.assertEqual(t.cursorMs, 300000)
' a VOD scrub is not a live tail
m.t.HandleCommand(TransportController.Command.Left)
m.t.TakeVideoIntent() ' drain the freeze
m.t.ResolveLiveTail()
m.assertEqual(m.t.transportMode, TransportController.Mode.Scrub)
m.assertInvalid(m.t.TakeVideoIntent())
end function
' =========================================================================================
' LIVE-EDGE SENTINEL ECHO — the 999999s jump-to-edge seek echoes back through the
' single-precision position field as 999998976ms (24ms UNDER the constant): both ingest
' guards must drop it, or it poisons positionMs and (via the max rule) edgeMs.
' =========================================================================================
@describe("live edge sentinel echo")
@it("OnPosition drops the float32 sentinel echo — position, edge and cursor stay clean")
function _()
t = m.LiveWindowed()
t.OnPosition(999998976) ' Int(float32(999999.0s) * 1000): the echo as the device reports it
t.OnPosition(999999000) ' the exact constant
m.assertEqual(t.positionMs, 300000)
m.assertEqual(t.edgeMs, 300000)
m.assertEqual(t.cursorMs, 300000)
t.OnPosition(295000) ' a real sample still lands
m.assertEqual(t.positionMs, 295000)
end function
@it("OnLiveEdge drops the float32 sentinel echo")
function _()
t = m.LiveWindowed()
t.OnLiveEdge(999998976)
m.assertEqual(t.edgeMs, 300000)
t.OnLiveEdge(305000) ' the real heartbeat still lands
m.assertEqual(t.edgeMs, 305000)
end function
' ========================================================================================= ' =========================================================================================
' LIVE REWINDABILITY — a buffer-sized DVR window (the manifest's timeShiftBufferDepth) is not ' LIVE REWINDABILITY — a buffer-sized DVR window (the manifest's timeShiftBufferDepth) is not
' a rewind feature: the brain takes no live transport input and the bar drops its label. ' a rewind feature: the brain takes no live transport input and the bar drops its label.
@@ -145,7 +145,7 @@ namespace Tests
' ---------- seeded fuzz with shrink ---------- ' ---------- seeded fuzz with shrink ----------
' a 16-bit LCG (ZX-Spectrum constants): s*25173 < 2^31 so it never overflows Integer; deterministic + ' a 16-bit LCG (ZX-Spectrum constants): s*25173 < 2^31 so it never overflows Integer; deterministic +
' reproducible (NOT Rnd, which is clock-seeded). Token = s mod 13 -> one input. ' reproducible (NOT Rnd, which is clock-seeded). Token = s mod 14 -> one input.
function Lcg(s as integer) as integer function Lcg(s as integer) as integer
return (s * 25173 + 13849) and 65535 return (s * 25173 + 13849) and 65535
end function end function
@@ -155,7 +155,7 @@ namespace Tests
s = seed s = seed
for i = 0 to n - 1 for i = 0 to n - 1
s = m.Lcg(s) s = m.Lcg(s)
seq.Push(s mod 13) seq.Push(s mod 14)
end for end for
return seq return seq
end function end function
@@ -187,6 +187,8 @@ namespace Tests
t.Tick(TransportController.Timer.ReplayToast) t.Tick(TransportController.Timer.ReplayToast)
else if tok = 12 else if tok = 12
t.OnLiveEdge(t.edgeMs + 50000) ' a big edge jump (long pause's catch-up) t.OnLiveEdge(t.edgeMs + 50000) ' a big edge jump (long pause's catch-up)
else if tok = 13
t.ResolveLiveTail() ' the coordinator's tail-overtake resolution (no-op outside LiveDvr)
end if end if
end function end function
+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"
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet-web", "name": "playlet-web",
"version": "0.48.0", "version": "0.48.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-web", "name": "playlet-web",
"version": "0.48.0", "version": "0.48.1",
"devDependencies": { "devDependencies": {
"@sveltejs/vite-plugin-svelte": "^7.1.2", "@sveltejs/vite-plugin-svelte": "^7.1.2",
"@tailwindcss/postcss": "^4.3.1", "@tailwindcss/postcss": "^4.3.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-web", "name": "playlet-web",
"version": "0.48.0", "version": "0.48.1",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",