Browser based potokens
This commit is contained in:
1 parent
5e798f19de
commit
63f9ac693a
27 files changed
+722
-499
No files matched your search
@@ -5,6 +5,16 @@ 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).
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Attempt to fix `No valid bitrates` error by adding PoToken generation in web app
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- Play with ytjs option from web app, as it wasn't working anyway
|
||||||
|
|
||||||
## [0.47.4] - 2026-06-25
|
## [0.47.4] - 2026-06-25
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import "pkg:/components/Dialog/DialogUtils.bs"
|
||||||
|
import "pkg:/components/Services/Innertube/PoTokens.bs"
|
||||||
|
import "pkg:/source/utils/FocusManagement.bs"
|
||||||
|
import "pkg:/source/utils/Locale.bs"
|
||||||
|
|
||||||
|
function Init()
|
||||||
|
m.top.focusable = true
|
||||||
|
m.top.itemSpacings = [8]
|
||||||
|
m.button = m.top.findNode("Button")
|
||||||
|
m.button.observeField("buttonSelected", FuncName(OnButtonSelected))
|
||||||
|
end function
|
||||||
|
|
||||||
|
function OnFocusChange() as void
|
||||||
|
if not m.top.focus
|
||||||
|
return
|
||||||
|
end if
|
||||||
|
NodeSetFocus(m.button, true)
|
||||||
|
end function
|
||||||
|
|
||||||
|
function BindPreference(_preferences as object, _key as string)
|
||||||
|
' Do nothing
|
||||||
|
end function
|
||||||
|
|
||||||
|
function OnButtonSelected()
|
||||||
|
Innertube.PoTokens.ClearAllPoTokens()
|
||||||
|
DialogUtils.ShowDialogEx({
|
||||||
|
message: Tr(Locale.Settings.PoTokensCleared)
|
||||||
|
title: Tr(Locale.Generic.Success)
|
||||||
|
})
|
||||||
|
end function
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<component name="ClearPoTokensControl" extends="LayoutGroup" includes="Focus">
|
||||||
|
<interface>
|
||||||
|
<field id="displayText" type="string" alias="Button.text" />
|
||||||
|
<field id="description" type="string" alias="DescriptionLabel.text" />
|
||||||
|
<function name="BindPreference" />
|
||||||
|
</interface>
|
||||||
|
<children>
|
||||||
|
<Button
|
||||||
|
id="Button"
|
||||||
|
minWidth="340"
|
||||||
|
showFocusFootprint="true" />
|
||||||
|
<Label id="DescriptionLabel"
|
||||||
|
width="450"
|
||||||
|
color="0xb4b4b4ff"
|
||||||
|
wrap="true">
|
||||||
|
<Font role="font" uri="font:SystemFontFile" size="18" />
|
||||||
|
</Label>
|
||||||
|
</children>
|
||||||
|
</component>
|
||||||
@@ -775,6 +775,20 @@ namespace InnertubeService
|
|||||||
return Innertube.GetDatasyncIdToken(endpoint)
|
return Innertube.GetDatasyncIdToken(endpoint)
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
' The identity used to bind GVS poTokens: the signed-in profile's datasyncIdToken,
|
||||||
|
' falling back to visitorData when logged out (or when no datasyncIdToken is available).
|
||||||
|
function GetCurrentPoTokenIdentity(profilesService as object, innertubeNode as object) as string
|
||||||
|
currentProfile = profilesService.currentProfile
|
||||||
|
if currentProfile <> invalid and currentProfile.type = "youtube"
|
||||||
|
accessToken = currentProfile.accessToken
|
||||||
|
if not StringUtils.IsNullOrEmpty(accessToken)
|
||||||
|
' Signed in: bind to the datasyncIdToken, matching the decipher request's identity.
|
||||||
|
return GetProfileDatasyncIdToken(currentProfile, accessToken, profilesService, invalid)
|
||||||
|
end if
|
||||||
|
end if
|
||||||
|
return innertubeNode.visitorData
|
||||||
|
end function
|
||||||
|
|
||||||
function BackfillSelectActiveIdentityEndpoint(profileNode as object, accessToken as string, profilesService as object, cancellation as object) as object
|
function BackfillSelectActiveIdentityEndpoint(profileNode as object, accessToken as string, profilesService as object, cancellation as object) as object
|
||||||
LogInfo("Backfilling selectActiveIdentityEndpoint for signed-in profile")
|
LogInfo("Backfilling selectActiveIdentityEndpoint for signed-in profile")
|
||||||
accounts = Innertube.ListAccounts(accessToken, cancellation)
|
accounts = Innertube.ListAccounts(accessToken, cancellation)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import "pkg:/components/Services/Innertube/Context.bs"
|
|||||||
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
|
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
|
||||||
import "pkg:/components/Services/Innertube/NodesParser.bs"
|
import "pkg:/components/Services/Innertube/NodesParser.bs"
|
||||||
import "pkg:/components/Services/Innertube/OTFSegmentInfo.bs"
|
import "pkg:/components/Services/Innertube/OTFSegmentInfo.bs"
|
||||||
|
import "pkg:/components/Services/Innertube/PoTokens.bs"
|
||||||
import "pkg:/source/services/HttpClient.bs"
|
import "pkg:/source/services/HttpClient.bs"
|
||||||
import "pkg:/source/utils/ObjectUtils.bs"
|
import "pkg:/source/utils/ObjectUtils.bs"
|
||||||
import "pkg:/source/utils/Types.bs"
|
import "pkg:/source/utils/Types.bs"
|
||||||
@@ -67,6 +68,10 @@ namespace Innertube
|
|||||||
request.poTokenIdentity = datasyncIdToken
|
request.poTokenIdentity = datasyncIdToken
|
||||||
end if
|
end if
|
||||||
|
|
||||||
|
if not StringUtils.IsNullOrEmpty(request.poTokenIdentity)
|
||||||
|
request.poToken = Innertube.PoTokens.GetValidPoTokenForIdentity(request.poTokenIdentity)
|
||||||
|
end if
|
||||||
|
|
||||||
request.signatureTimestamp = signatureTimestamp
|
request.signatureTimestamp = signatureTimestamp
|
||||||
request.cpn = cpn
|
request.cpn = cpn
|
||||||
|
|
||||||
@@ -106,7 +111,7 @@ namespace Innertube
|
|||||||
adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"]))
|
adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"]))
|
||||||
formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"]))
|
formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"]))
|
||||||
|
|
||||||
error = DecipherUrls(formats, adaptiveFormats, playerRequest.signatureTimestamp, cancellation, client, playerRequest.poTokenIdentity)
|
error = DecipherUrls(formats, adaptiveFormats, playerRequest.signatureTimestamp, cancellation, client, playerRequest.poTokenIdentity, playerRequest.poToken)
|
||||||
if error <> invalid
|
if error <> invalid
|
||||||
parsedResponse["error"] = error.error
|
parsedResponse["error"] = error.error
|
||||||
if error.DoesExist("errorCode")
|
if error.DoesExist("errorCode")
|
||||||
@@ -116,7 +121,15 @@ namespace Innertube
|
|||||||
end if
|
end if
|
||||||
|
|
||||||
parsedResponse["potAttached"] = HasPotParam(adaptiveFormats) or HasPotParam(formats)
|
parsedResponse["potAttached"] = HasPotParam(adaptiveFormats) or HasPotParam(formats)
|
||||||
LogDebug("poToken attached to deciphered urls:", parsedResponse["potAttached"])
|
' browser = we forwarded a token; server = server minted; none = no pot attached.
|
||||||
|
if not parsedResponse["potAttached"]
|
||||||
|
parsedResponse["potSource"] = "none"
|
||||||
|
else if StringUtils.IsNullOrEmpty(playerRequest.poToken)
|
||||||
|
parsedResponse["potSource"] = "server"
|
||||||
|
else
|
||||||
|
parsedResponse["potSource"] = "browser"
|
||||||
|
end if
|
||||||
|
LogDebug("poToken attached to deciphered urls:", parsedResponse["potAttached"], "source:", parsedResponse["potSource"])
|
||||||
|
|
||||||
' if isLive and adaptiveFormats.Count() > 0
|
' if isLive and adaptiveFormats.Count() > 0
|
||||||
' LogInfo("[LIVE-INFO] post-decipher, sts:", playerRequest.signatureTimestamp, "format[0].itag:", adaptiveFormats[0]["itag"], "url:", adaptiveFormats[0]["url"])
|
' LogInfo("[LIVE-INFO] post-decipher, sts:", playerRequest.signatureTimestamp, "format[0].itag:", adaptiveFormats[0]["itag"], "url:", adaptiveFormats[0]["url"])
|
||||||
@@ -518,7 +531,7 @@ namespace Innertube
|
|||||||
return false
|
return false
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function DecipherUrls(formats as object, adaptiveFormats as object, signatureTimestamp as dynamic, cancellation as object, client = invalid as dynamic, poTokenIdentity = invalid as dynamic) as object
|
function DecipherUrls(formats as object, adaptiveFormats as object, signatureTimestamp as dynamic, cancellation as object, client = invalid as dynamic, poTokenIdentity = invalid as dynamic, poToken = invalid as dynamic) as object
|
||||||
if signatureTimestamp = invalid
|
if signatureTimestamp = invalid
|
||||||
' No need to decipher if signatureTimestamp is not available
|
' No need to decipher if signatureTimestamp is not available
|
||||||
return invalid
|
return invalid
|
||||||
@@ -551,6 +564,9 @@ namespace Innertube
|
|||||||
body["identity"] = poTokenIdentity
|
body["identity"] = poTokenIdentity
|
||||||
end if
|
end if
|
||||||
LogDebug("decipher poToken identity:", poTokenIdentity)
|
LogDebug("decipher poToken identity:", poTokenIdentity)
|
||||||
|
if not StringUtils.IsNullOrEmpty(poToken)
|
||||||
|
body["poToken"] = poToken
|
||||||
|
end if
|
||||||
|
|
||||||
request = HttpClient.PostJson(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`, body)
|
request = HttpClient.PostJson(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`, body)
|
||||||
request.Cancellation(cancellation)
|
request.Cancellation(cancellation)
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import "pkg:/source/utils/RegistryUtils.bs"
|
||||||
|
import "pkg:/source/utils/StringUtils.bs"
|
||||||
|
import "pkg:/source/utils/TimeUtils.bs"
|
||||||
|
|
||||||
|
namespace Innertube.PoTokens
|
||||||
|
|
||||||
|
const POTOKENS_VERSION = 1
|
||||||
|
|
||||||
|
function IsPoTokenEntryValid(entry as object) as boolean
|
||||||
|
if not IsAssociativeArray(entry) or StringUtils.IsNullOrEmpty(entry.token) or not IsInt(entry.expiresAt)
|
||||||
|
return false
|
||||||
|
end if
|
||||||
|
return TimeUtils.Now().AsSeconds() < entry.expiresAt
|
||||||
|
end function
|
||||||
|
|
||||||
|
function PrunePoTokens(poTokens as object) as object
|
||||||
|
pruned = {}
|
||||||
|
for each identity in poTokens
|
||||||
|
if IsPoTokenEntryValid(poTokens[identity])
|
||||||
|
pruned[identity] = poTokens[identity]
|
||||||
|
end if
|
||||||
|
end for
|
||||||
|
return pruned
|
||||||
|
end function
|
||||||
|
|
||||||
|
' Stored as { identity: { token, expiresAt, mintedAt } }; identity = visitorData or datasyncIdToken.
|
||||||
|
' Returns the valid token string for an identity (for playback), or "" if there is none.
|
||||||
|
function GetValidPoTokenForIdentity(identity as string) as string
|
||||||
|
if StringUtils.IsNullOrEmpty(identity)
|
||||||
|
return ""
|
||||||
|
end if
|
||||||
|
entry = ReadPoTokensFromRegistry()[identity]
|
||||||
|
if IsPoTokenEntryValid(entry)
|
||||||
|
return entry.token
|
||||||
|
end if
|
||||||
|
return ""
|
||||||
|
end function
|
||||||
|
|
||||||
|
' Returns the stored entry { token, expiresAt, mintedAt } for an identity, or invalid. The web
|
||||||
|
' app reads this to decide whether to re-mint.
|
||||||
|
function GetPoTokenEntryForIdentity(identity as string) as object
|
||||||
|
if StringUtils.IsNullOrEmpty(identity)
|
||||||
|
return invalid
|
||||||
|
end if
|
||||||
|
entry = ReadPoTokensFromRegistry()[identity]
|
||||||
|
if not IsAssociativeArray(entry)
|
||||||
|
return invalid
|
||||||
|
end if
|
||||||
|
return entry
|
||||||
|
end function
|
||||||
|
|
||||||
|
function StorePoToken(identity as string, token as string, expiresAt as integer, mintedAt as integer) as void
|
||||||
|
poTokens = PrunePoTokens(ReadPoTokensFromRegistry())
|
||||||
|
poTokens[identity] = {
|
||||||
|
"token": token
|
||||||
|
"expiresAt": expiresAt
|
||||||
|
"mintedAt": mintedAt
|
||||||
|
}
|
||||||
|
SavePoTokensToRegistry(poTokens)
|
||||||
|
end function
|
||||||
|
|
||||||
|
function ClearAllPoTokens() as void
|
||||||
|
SavePoTokensToRegistry({})
|
||||||
|
end function
|
||||||
|
|
||||||
|
function ReadPoTokensFromRegistry() as object
|
||||||
|
stored = RegistryUtils.Read(RegistryUtils.INNERTUBE_POTOKENS)
|
||||||
|
if StringUtils.IsNullOrEmpty(stored)
|
||||||
|
return {}
|
||||||
|
end if
|
||||||
|
parsed = StringUtils.ParseJsonSafe(stored)
|
||||||
|
if not IsAssociativeArray(parsed)
|
||||||
|
return {}
|
||||||
|
end if
|
||||||
|
if parsed.__version <> POTOKENS_VERSION
|
||||||
|
return {}
|
||||||
|
end if
|
||||||
|
if not IsAssociativeArray(parsed.tokens)
|
||||||
|
return {}
|
||||||
|
end if
|
||||||
|
return parsed.tokens
|
||||||
|
end function
|
||||||
|
|
||||||
|
function SavePoTokensToRegistry(poTokens as object) as void
|
||||||
|
RegistryUtils.Write(RegistryUtils.INNERTUBE_POTOKENS, FormatJson({
|
||||||
|
"__version": POTOKENS_VERSION
|
||||||
|
"tokens": poTokens
|
||||||
|
}))
|
||||||
|
end function
|
||||||
|
|
||||||
|
end namespace
|
||||||
@@ -68,6 +68,7 @@ function ExecuteJob() as void
|
|||||||
if IsAssociativeArray(metadata)
|
if IsAssociativeArray(metadata)
|
||||||
contentNode.addFields({
|
contentNode.addFields({
|
||||||
potAttached: ValidBool(metadata.potAttached)
|
potAttached: ValidBool(metadata.potAttached)
|
||||||
|
potSource: ValidString(metadata.potSource)
|
||||||
loggedIn: not StringUtils.IsNullOrEmpty(accessToken)
|
loggedIn: not StringUtils.IsNullOrEmpty(accessToken)
|
||||||
})
|
})
|
||||||
end if
|
end if
|
||||||
|
|||||||
@@ -1406,12 +1406,16 @@ function ReportVideoError(errorData as object, url as dynamic, urls as object, u
|
|||||||
}]
|
}]
|
||||||
end if
|
end if
|
||||||
potAttached = "false"
|
potAttached = "false"
|
||||||
|
potSource = "none"
|
||||||
loggedIn = "false"
|
loggedIn = "false"
|
||||||
content = m.top.content
|
content = m.top.content
|
||||||
if content <> invalid
|
if content <> invalid
|
||||||
if ValidBool(content.potAttached)
|
if ValidBool(content.potAttached)
|
||||||
potAttached = "true"
|
potAttached = "true"
|
||||||
end if
|
end if
|
||||||
|
if not StringUtils.IsNullOrEmpty(content.potSource)
|
||||||
|
potSource = content.potSource
|
||||||
|
end if
|
||||||
if ValidBool(content.loggedIn)
|
if ValidBool(content.loggedIn)
|
||||||
loggedIn = "true"
|
loggedIn = "true"
|
||||||
end if
|
end if
|
||||||
@@ -1426,10 +1430,12 @@ function ReportVideoError(errorData as object, url as dynamic, urls as object, u
|
|||||||
"Urls: " + FormatJson(urls)
|
"Urls: " + FormatJson(urls)
|
||||||
`Url index: ${urlIndex}`
|
`Url index: ${urlIndex}`
|
||||||
`pot_attached: ${potAttached}`
|
`pot_attached: ${potAttached}`
|
||||||
|
`pot_source: ${potSource}`
|
||||||
`logged_in: ${loggedIn}`
|
`logged_in: ${loggedIn}`
|
||||||
].Join(Chr(10))
|
].Join(Chr(10))
|
||||||
errorData.fingerprint.Push(shownInDialog)
|
errorData.fingerprint.Push(shownInDialog)
|
||||||
errorData.fingerprint.Push(potAttached)
|
errorData.fingerprint.Push(potAttached)
|
||||||
|
errorData.fingerprint.Push(potSource)
|
||||||
errorData.fingerprint.Push(loggedIn)
|
errorData.fingerprint.Push(loggedIn)
|
||||||
if shownInDialog
|
if shownInDialog
|
||||||
level = "error"
|
level = "error"
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import "pkg:/components/Services/Innertube/Constants.bs"
|
import "pkg:/components/Services/Innertube/Constants.bs"
|
||||||
import "pkg:/components/Services/Innertube/SessionData.bs"
|
import "pkg:/components/Services/Innertube/InnertubeService.bs"
|
||||||
|
import "pkg:/components/Services/Innertube/PoTokens.bs"
|
||||||
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
|
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
|
||||||
import "pkg:/source/services/HttpClient.bs"
|
import "pkg:/source/services/HttpClient.bs"
|
||||||
|
import "pkg:/source/utils/Types.bs"
|
||||||
|
|
||||||
namespace Http
|
namespace Http
|
||||||
|
|
||||||
@@ -14,21 +16,32 @@ namespace Http
|
|||||||
m.profilesService = server.sceneNodes.profilesService
|
m.profilesService = server.sceneNodes.profilesService
|
||||||
end function
|
end function
|
||||||
|
|
||||||
@get("/api/innertube/session")
|
@get("/api/innertube/potoken")
|
||||||
function GetSessionData(context as object) as object
|
function GetPoToken(context as object) as object
|
||||||
response = context.response
|
response = context.response
|
||||||
|
|
||||||
sessionData = {
|
identity = InnertubeService.GetCurrentPoTokenIdentity(m.profilesService, m.innertube)
|
||||||
"timestamp": m.innertube.timestamp
|
if StringUtils.IsNullOrEmpty(identity)
|
||||||
"visitorData": m.innertube.visitorData
|
response.Default(503, "No current identity")
|
||||||
}
|
return true
|
||||||
|
end if
|
||||||
|
|
||||||
response.Json(sessionData)
|
result = {
|
||||||
|
"identity": identity
|
||||||
|
}
|
||||||
|
entry = Innertube.PoTokens.GetPoTokenEntryForIdentity(identity)
|
||||||
|
if IsAssociativeArray(entry)
|
||||||
|
result["poToken"] = entry.token
|
||||||
|
result["mintedAt"] = entry.mintedAt
|
||||||
|
result["expiresAt"] = entry.expiresAt
|
||||||
|
end if
|
||||||
|
|
||||||
|
response.Json(result)
|
||||||
return true
|
return true
|
||||||
end function
|
end function
|
||||||
|
|
||||||
@post("/api/innertube/session")
|
@post("/api/innertube/potoken")
|
||||||
function SetSessionData(context as object) as object
|
function SetPoToken(context as object) as object
|
||||||
request = context.request
|
request = context.request
|
||||||
response = context.response
|
response = context.response
|
||||||
|
|
||||||
@@ -37,24 +50,37 @@ namespace Http
|
|||||||
response.Default(400, "Invalid payload")
|
response.Default(400, "Invalid payload")
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
|
if StringUtils.IsNullOrEmpty(payload.poToken)
|
||||||
if not IsInt(payload.timestamp)
|
response.Default(400, "Invalid poToken")
|
||||||
response.Default(400, "Invalid timestamp")
|
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
if StringUtils.IsNullOrEmpty(payload.visitorData)
|
if StringUtils.IsNullOrEmpty(payload.identity)
|
||||||
response.Default(400, "Invalid visitorData")
|
response.Default(400, "Invalid identity")
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
|
|
||||||
Innertube.SaveSessionDataToRegistry({
|
if not IsInt(payload.mintedAt) or not IsInt(payload.expiresAt)
|
||||||
"timestamp": payload.timestamp
|
response.Default(400, "Invalid mintedAt/expiresAt")
|
||||||
"visitorData": payload.visitorData
|
return true
|
||||||
})
|
end if
|
||||||
|
|
||||||
m.innertube.timestamp = payload.timestamp
|
' Reject identities other than the device's current one (guards the shared registry).
|
||||||
m.innertube.visitorData = payload.visitorData
|
if payload.identity <> InnertubeService.GetCurrentPoTokenIdentity(m.profilesService, m.innertube)
|
||||||
response.Default(204, "Session data updated successfully")
|
response.Default(409, "identity is not the device's current identity")
|
||||||
|
return true
|
||||||
|
end if
|
||||||
|
|
||||||
|
Innertube.PoTokens.StorePoToken(payload.identity, payload.poToken, payload.expiresAt, payload.mintedAt)
|
||||||
|
response.Default(204, "PoToken updated successfully")
|
||||||
|
return true
|
||||||
|
end function
|
||||||
|
|
||||||
|
@delete("/api/innertube/potoken/all")
|
||||||
|
function ClearPoTokens(context as object) as object
|
||||||
|
response = context.response
|
||||||
|
|
||||||
|
Innertube.PoTokens.ClearAllPoTokens()
|
||||||
|
response.Default(204, "PoTokens cleared")
|
||||||
return true
|
return true
|
||||||
end function
|
end function
|
||||||
|
|
||||||
@@ -70,8 +96,8 @@ namespace Http
|
|||||||
end if
|
end if
|
||||||
|
|
||||||
requestHeaders = requestArgs.Headers
|
requestHeaders = requestArgs.Headers
|
||||||
' Ytjs can send requests without specifying a User-Agent.
|
' Proxied web-app requests (e.g. BotGuard attestation) may omit a
|
||||||
' In this case, Roku would use its default User-Agent.
|
' User-Agent; fall back to ours instead of Roku's default.
|
||||||
if StringUtils.IsNullOrEmpty(requestHeaders["User-Agent"])
|
if StringUtils.IsNullOrEmpty(requestHeaders["User-Agent"])
|
||||||
requestHeaders["User-Agent"] = VIDEO_PLAYER_USER_AGENT
|
requestHeaders["User-Agent"] = VIDEO_PLAYER_USER_AGENT
|
||||||
end if
|
end if
|
||||||
|
|||||||
@@ -56,10 +56,16 @@ namespace Http
|
|||||||
return true
|
return true
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function Default(errcode as integer, reason as string)
|
function Default(errcode as integer, reason as string) as void
|
||||||
errname = m.server.utils.HttpTitle(errcode)
|
|
||||||
m.http_code = errcode
|
m.http_code = errcode
|
||||||
|
|
||||||
|
if errcode = 204
|
||||||
|
' 204 No Content carries no body.
|
||||||
|
m.SetBodyDataString("")
|
||||||
|
return
|
||||||
|
end if
|
||||||
|
|
||||||
|
errname = m.server.utils.HttpTitle(errcode)
|
||||||
buffer = `<html><head><title>${errcode} ${errname}</title></head><body>
|
buffer = `<html><head><title>${errcode} ${errname}</title></head><body>
|
||||||
<h1>${errname}</h1>
|
<h1>${errname}</h1>
|
||||||
${reason}
|
${reason}
|
||||||
|
|||||||
@@ -311,6 +311,27 @@
|
|||||||
visibility: "tv",
|
visibility: "tv",
|
||||||
rokuComponent: "ClearCacheControl",
|
rokuComponent: "ClearCacheControl",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
displayText: "Mint PoToken",
|
||||||
|
key: "dev.mint_potoken",
|
||||||
|
description: "Force-mint a PoToken for the current identity.",
|
||||||
|
visibility: "web",
|
||||||
|
svelteComponent: "MintPoTokenControl",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
displayText: "Clear PoTokens",
|
||||||
|
key: "dev.clear_potokens",
|
||||||
|
description: "Clear all stored PoTokens.",
|
||||||
|
visibility: "web",
|
||||||
|
svelteComponent: "ClearPoTokensControl",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
displayText: "Clear PoTokens",
|
||||||
|
key: "dev.clear_potokens",
|
||||||
|
description: "Clear all stored PoTokens.",
|
||||||
|
visibility: "tv",
|
||||||
|
rokuComponent: "ClearPoTokensControl",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
displayText: "Enable Diagnostics",
|
displayText: "Enable Diagnostics",
|
||||||
key: "dev.diagnostics.enabled",
|
key: "dev.diagnostics.enabled",
|
||||||
|
|||||||
@@ -1380,6 +1380,18 @@
|
|||||||
<source>Cache cleared.</source>
|
<source>Cache cleared.</source>
|
||||||
<translation>Cache cleared.</translation>
|
<translation>Cache cleared.</translation>
|
||||||
</message>
|
</message>
|
||||||
|
<message>
|
||||||
|
<source>Clear PoTokens</source>
|
||||||
|
<translation>Clear PoTokens</translation>
|
||||||
|
</message>
|
||||||
|
<message>
|
||||||
|
<source>Clear all stored PoTokens.</source>
|
||||||
|
<translation>Clear all stored PoTokens.</translation>
|
||||||
|
</message>
|
||||||
|
<message>
|
||||||
|
<source>PoTokens cleared.</source>
|
||||||
|
<translation>PoTokens cleared.</translation>
|
||||||
|
</message>
|
||||||
<message>
|
<message>
|
||||||
<source>Enable Diagnostics</source>
|
<source>Enable Diagnostics</source>
|
||||||
<translation>Enable Diagnostics</translation>
|
<translation>Enable Diagnostics</translation>
|
||||||
|
|||||||
@@ -310,6 +310,9 @@ namespace Locale
|
|||||||
ClearCache = "Clear cache"
|
ClearCache = "Clear cache"
|
||||||
ClearCacheDescription = "Clear cache from cachefs: and tmp:"
|
ClearCacheDescription = "Clear cache from cachefs: and tmp:"
|
||||||
CacheCleared = "Cache cleared."
|
CacheCleared = "Cache cleared."
|
||||||
|
ClearPoTokens = "Clear PoTokens"
|
||||||
|
ClearPoTokensDescription = "Clear all stored PoTokens."
|
||||||
|
PoTokensCleared = "PoTokens cleared."
|
||||||
EnableDiagnostics = "Enable Diagnostics"
|
EnableDiagnostics = "Enable Diagnostics"
|
||||||
EnableDiagnosticsDescription = "Help improve Playlet by enabling diagnostics. This will send anonymous diagnotics data to the developer."
|
EnableDiagnosticsDescription = "Help improve Playlet by enabling diagnostics. This will send anonymous diagnotics data to the developer."
|
||||||
end enum
|
end enum
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ namespace RegistryUtils
|
|||||||
const MESSAGES = "messages"
|
const MESSAGES = "messages"
|
||||||
|
|
||||||
const INNERTUBE_SESSION_DATA = "innertube_session_data"
|
const INNERTUBE_SESSION_DATA = "innertube_session_data"
|
||||||
|
const INNERTUBE_POTOKENS = "innertube_potokens"
|
||||||
const LAST_LOUNGE_DATA = "last_lounge_data"
|
const LAST_LOUNGE_DATA = "last_lounge_data"
|
||||||
|
|
||||||
' "invidious_instances" is deprecated, but we keep for migration purposes
|
' "invidious_instances" is deprecated, but we keep for migration purposes
|
||||||
|
|||||||
Generated
+67
-33
@@ -29,8 +29,7 @@
|
|||||||
"tslib": "^2.8.1",
|
"tslib": "^2.8.1",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
"vite": "^8.0.16",
|
"vite": "^8.0.16",
|
||||||
"vite-plugin-compression": "^0.5.1",
|
"vite-plugin-compression": "^0.5.1"
|
||||||
"youtubei.js": "^17.0.1"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@alloc/quick-lru": {
|
"node_modules/@alloc/quick-lru": {
|
||||||
@@ -1578,13 +1577,6 @@
|
|||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@bufbuild/protobuf": {
|
|
||||||
"version": "2.11.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.11.0.tgz",
|
|
||||||
"integrity": "sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "(Apache-2.0 AND BSD-3-Clause)"
|
|
||||||
},
|
|
||||||
"node_modules/@emnapi/core": {
|
"node_modules/@emnapi/core": {
|
||||||
"version": "1.10.0",
|
"version": "1.10.0",
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
|
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
|
||||||
@@ -2236,6 +2228,72 @@
|
|||||||
"node": ">=14.0.0"
|
"node": ">=14.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
|
||||||
|
"version": "1.10.0",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@emnapi/wasi-threads": "1.2.1",
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
|
||||||
|
"version": "1.10.0",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
|
||||||
|
"version": "1.2.1",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
|
||||||
|
"version": "1.1.4",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@tybys/wasm-util": "^0.10.1"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@emnapi/core": "^1.7.1",
|
||||||
|
"@emnapi/runtime": "^1.7.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
|
||||||
|
"version": "0.10.2",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
|
||||||
|
"version": "2.8.1",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "0BSD",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
|
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
|
||||||
"version": "4.3.1",
|
"version": "4.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.1.tgz",
|
||||||
@@ -3593,16 +3651,6 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/meriyah": {
|
|
||||||
"version": "6.1.4",
|
|
||||||
"resolved": "https://registry.npmjs.org/meriyah/-/meriyah-6.1.4.tgz",
|
|
||||||
"integrity": "sha512-Sz8FzjzI0kN13GK/6MVEsVzMZEPvOhnmmI1lU5+/1cGOiK3QUahntrNNtdVeihrO7t9JpoH75iMNXg6R6uWflQ==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "ISC",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=18.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/mri": {
|
"node_modules/mri": {
|
||||||
"version": "1.2.0",
|
"version": "1.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
|
||||||
@@ -4617,20 +4665,6 @@
|
|||||||
"node": "^20.19.0 || ^22.12.0 || >=23"
|
"node": "^20.19.0 || ^22.12.0 || >=23"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/youtubei.js": {
|
|
||||||
"version": "17.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/youtubei.js/-/youtubei.js-17.0.1.tgz",
|
|
||||||
"integrity": "sha512-1lO4b8UqMDzE0oh2qEGzbBOd4UYRdxn/4PdpRM7BGTHxM6ddsEsKZTu90jp8V9FHVgC2h1UirQyqoqLiKwl+Zg==",
|
|
||||||
"dev": true,
|
|
||||||
"funding": [
|
|
||||||
"https://github.com/sponsors/LuanRT"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@bufbuild/protobuf": "^2.0.0",
|
|
||||||
"meriyah": "^6.1.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/zimmerframe": {
|
"node_modules/zimmerframe": {
|
||||||
"version": "1.1.4",
|
"version": "1.1.4",
|
||||||
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
|
||||||
|
|||||||
@@ -30,7 +30,6 @@
|
|||||||
"tslib": "^2.8.1",
|
"tslib": "^2.8.1",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
"vite": "^8.0.16",
|
"vite": "^8.0.16",
|
||||||
"vite-plugin-compression": "^0.5.1",
|
"vite-plugin-compression": "^0.5.1"
|
||||||
"youtubei.js": "^17.0.1"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -24,8 +24,19 @@
|
|||||||
import BookmarksScreen from "lib/Screens/BookmarksScreen.svelte";
|
import BookmarksScreen from "lib/Screens/BookmarksScreen.svelte";
|
||||||
import RemoteControlScreen from "lib/Screens/RemoteControlScreen.svelte";
|
import RemoteControlScreen from "lib/Screens/RemoteControlScreen.svelte";
|
||||||
import { fetchLocale } from "lib/Api/Locale";
|
import { fetchLocale } from "lib/Api/Locale";
|
||||||
|
import { ensureDevicePoTokenWithToast } from "lib/ensureDevicePoToken";
|
||||||
|
import Toast from "lib/Toast.svelte";
|
||||||
|
|
||||||
|
// Mint on load, then refresh hourly while the page is open.
|
||||||
|
const POTOKEN_REFRESH_INTERVAL_MS = 60 * 60 * 1000;
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
|
ensureDevicePoTokenWithToast();
|
||||||
|
const poTokenRefreshInterval = setInterval(
|
||||||
|
ensureDevicePoTokenWithToast,
|
||||||
|
POTOKEN_REFRESH_INTERVAL_MS,
|
||||||
|
);
|
||||||
|
|
||||||
PlayletApi.getState().then((value) => {
|
PlayletApi.getState().then((value) => {
|
||||||
playletStateStore.set(value);
|
playletStateStore.set(value);
|
||||||
fetchLocale(value.device?.current_locale);
|
fetchLocale(value.device?.current_locale);
|
||||||
@@ -62,6 +73,8 @@
|
|||||||
PlayletApi.getBookmarkFeeds().then((value) => {
|
PlayletApi.getBookmarkFeeds().then((value) => {
|
||||||
bookmarksStore.set(value);
|
bookmarksStore.set(value);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return () => clearInterval(poTokenRefreshInterval);
|
||||||
});
|
});
|
||||||
|
|
||||||
let currentScreen: AppState["screen"];
|
let currentScreen: AppState["screen"];
|
||||||
@@ -93,3 +106,5 @@
|
|||||||
</div>
|
</div>
|
||||||
<BottomNavigation />
|
<BottomNavigation />
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
<Toast />
|
||||||
@@ -164,6 +164,27 @@ export class PlayletApi {
|
|||||||
return await fetch(`${PlayletApi.host()}/api/cache`, { method: "DELETE" });
|
return await fetch(`${PlayletApi.host()}/api/cache`, { method: "DELETE" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static async getDevicePoToken() {
|
||||||
|
const response = await fetch(`${PlayletApi.host()}/api/innertube/potoken`);
|
||||||
|
if (!response.ok) {
|
||||||
|
const body = await response.text().catch(() => "");
|
||||||
|
throw new Error(`Failed to read device poToken (HTTP ${response.status}): ${body}`);
|
||||||
|
}
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
static async sendPoToken(identity: string, poToken: string, mintedAt: number, expiresAt: number) {
|
||||||
|
const response = await PlayletApi.postJson(`${PlayletApi.host()}/api/innertube/potoken`, { identity, poToken, mintedAt, expiresAt });
|
||||||
|
if (!response.ok) {
|
||||||
|
const body = await response.text().catch(() => "");
|
||||||
|
throw new Error(`Device rejected poToken (HTTP ${response.status}): ${body}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async clearPoTokens() {
|
||||||
|
return await fetch(`${PlayletApi.host()}/api/innertube/potoken/all`, { method: "DELETE" });
|
||||||
|
}
|
||||||
|
|
||||||
static async getBookmarkFeeds() {
|
static async getBookmarkFeeds() {
|
||||||
const response = await fetch(`${PlayletApi.host()}/api/bookmarks/feeds`);
|
const response = await fetch(`${PlayletApi.host()}/api/bookmarks/feeds`);
|
||||||
return await response.json();
|
return await response.json();
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
import { getHost } from "lib/Api/Host";
|
||||||
|
import { PlayletApi } from "lib/Api/PlayletApi";
|
||||||
|
import { BG, buildURL, GOOG_API_KEY, type WebPoSignalOutput, type BgConfig } from "bgutils-js";
|
||||||
|
|
||||||
|
// Fallback lifetime when GenerateIT reports no TTL.
|
||||||
|
const DEFAULT_POTOKEN_TTL_SECONDS = 60 * 60 * 6;
|
||||||
|
|
||||||
|
// Re-mint when the device's token is older than this; the web app owns the refresh cadence.
|
||||||
|
const REFRESH_AGE_SECONDS = 60 * 60;
|
||||||
|
|
||||||
|
export type EnsurePoTokenResult =
|
||||||
|
| { status: "minted" }
|
||||||
|
| { status: "current" }
|
||||||
|
| { status: "no-session" }
|
||||||
|
| { status: "failed"; error: string };
|
||||||
|
|
||||||
|
interface DevicePoToken {
|
||||||
|
identity?: string;
|
||||||
|
poToken?: string;
|
||||||
|
mintedAt?: number;
|
||||||
|
expiresAt?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mints a GVS poToken in the browser (BotGuard) and hands it to the Roku.
|
||||||
|
export class PoTokenMinter {
|
||||||
|
static webPoMinter: BG.WebPoMinter;
|
||||||
|
static webPoMinterPromise: Promise<void>;
|
||||||
|
static integrityTokenExpiresAtMs = 0;
|
||||||
|
|
||||||
|
// Proxied through the Roku to dodge browser CORS.
|
||||||
|
static async fetch(input: RequestInfo | URL, init?: RequestInit) {
|
||||||
|
const method = init?.method
|
||||||
|
? init.method
|
||||||
|
: input instanceof Request
|
||||||
|
? input.method
|
||||||
|
: 'GET';
|
||||||
|
|
||||||
|
const url = typeof input === 'string'
|
||||||
|
? new URL(input)
|
||||||
|
: input instanceof URL
|
||||||
|
? input
|
||||||
|
: new URL(input.url);
|
||||||
|
|
||||||
|
const headers = init?.headers
|
||||||
|
? new Headers(init.headers)
|
||||||
|
: input instanceof Request
|
||||||
|
? input.headers
|
||||||
|
: new Headers();
|
||||||
|
|
||||||
|
const headersObject = {};
|
||||||
|
headers.forEach((value, key) => {
|
||||||
|
headersObject[key] = value;
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = init?.body;
|
||||||
|
|
||||||
|
const args = {
|
||||||
|
Method: method,
|
||||||
|
Url: url,
|
||||||
|
Headers: headersObject,
|
||||||
|
Body: body,
|
||||||
|
CacheSeconds: -1,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch(`http://${getHost()}/api/innertube/proxy`, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(args)
|
||||||
|
});
|
||||||
|
|
||||||
|
const responseData = await response.json();
|
||||||
|
|
||||||
|
return new Response(responseData.body, {
|
||||||
|
status: responseData.status,
|
||||||
|
statusText: `${responseData.status}`,
|
||||||
|
headers: responseData.headers,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static async initWebPoMinter() {
|
||||||
|
// Re-attest once the integrity token nears expiry.
|
||||||
|
if (PoTokenMinter.webPoMinter && Date.now() < PoTokenMinter.integrityTokenExpiresAtMs - 60_000) {
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (PoTokenMinter.webPoMinterPromise) {
|
||||||
|
return PoTokenMinter.webPoMinterPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
PoTokenMinter.webPoMinterPromise = new Promise(async (resolve, reject) => {
|
||||||
|
try {
|
||||||
|
const requestKey = 'O43z0dpjhgX20SCx4KAo';
|
||||||
|
|
||||||
|
const bgConfig: BgConfig = {
|
||||||
|
fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => PoTokenMinter.fetch(input, init),
|
||||||
|
globalObj: globalThis,
|
||||||
|
requestKey,
|
||||||
|
identifier: ''
|
||||||
|
};
|
||||||
|
|
||||||
|
const bgChallenge = await BG.Challenge.create(bgConfig);
|
||||||
|
if (!bgChallenge) {
|
||||||
|
throw new Error('Could not get challenge');
|
||||||
|
}
|
||||||
|
|
||||||
|
const interpreterJavascript = bgChallenge.interpreterJavascript.privateDoNotAccessOrElseSafeScriptWrappedValue;
|
||||||
|
if (interpreterJavascript) {
|
||||||
|
new Function(interpreterJavascript)();
|
||||||
|
} else {
|
||||||
|
throw new Error('Could not load VM');
|
||||||
|
}
|
||||||
|
|
||||||
|
const botguard = await BG.BotGuardClient.create({
|
||||||
|
globalName: bgChallenge.globalName,
|
||||||
|
globalObj: globalThis,
|
||||||
|
program: bgChallenge.program
|
||||||
|
});
|
||||||
|
|
||||||
|
const webPoSignalOutput: WebPoSignalOutput = [];
|
||||||
|
const botguardResponse = await botguard.snapshot({ webPoSignalOutput });
|
||||||
|
|
||||||
|
const integrityTokenResponse = await bgConfig.fetch(buildURL('GenerateIT', true), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'content-type': 'application/json+protobuf',
|
||||||
|
'x-goog-api-key': GOOG_API_KEY,
|
||||||
|
'x-user-agent': 'grpc-web-javascript/0.1'
|
||||||
|
},
|
||||||
|
body: JSON.stringify([requestKey, botguardResponse])
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await integrityTokenResponse.json() as unknown[];
|
||||||
|
|
||||||
|
if (typeof response[0] !== 'string')
|
||||||
|
throw new Error('Could not get integrity token');
|
||||||
|
|
||||||
|
// GenerateIT returns the integrity token's estimated TTL (seconds) as body[1].
|
||||||
|
const ttlSeconds = typeof response[1] === 'number' && response[1] > 0
|
||||||
|
? Math.floor(response[1])
|
||||||
|
: DEFAULT_POTOKEN_TTL_SECONDS;
|
||||||
|
PoTokenMinter.integrityTokenExpiresAtMs = Date.now() + ttlSeconds * 1000;
|
||||||
|
|
||||||
|
PoTokenMinter.webPoMinter = await BG.WebPoMinter.create({ integrityToken: response[0] }, webPoSignalOutput);
|
||||||
|
PoTokenMinter.webPoMinterPromise = null;
|
||||||
|
resolve();
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
PoTokenMinter.webPoMinter = null;
|
||||||
|
PoTokenMinter.integrityTokenExpiresAtMs = 0;
|
||||||
|
PoTokenMinter.webPoMinterPromise = null;
|
||||||
|
reject(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return PoTokenMinter.webPoMinterPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async mintPoToken(identity: string) {
|
||||||
|
await PoTokenMinter.initWebPoMinter();
|
||||||
|
|
||||||
|
if (!PoTokenMinter.webPoMinter) {
|
||||||
|
throw new Error('WebPoMinter is not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
return await PoTokenMinter.webPoMinter.mintAsWebsafeString(identity);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-mint when the device has no token, it expired, or it is older than the refresh window.
|
||||||
|
static shouldRefresh(device: DevicePoToken): boolean {
|
||||||
|
if (!device.poToken || typeof device.mintedAt !== "number" || typeof device.expiresAt !== "number") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
if (now >= device.expiresAt) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return now - device.mintedAt >= REFRESH_AGE_SECONDS;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mints + uploads a poToken when the device's token needs refreshing, or always when forced.
|
||||||
|
static async ensureDevicePoToken(force = false): Promise<EnsurePoTokenResult> {
|
||||||
|
let device: DevicePoToken;
|
||||||
|
try {
|
||||||
|
device = await PlayletApi.getDevicePoToken();
|
||||||
|
} catch (error) {
|
||||||
|
return { status: "failed", error: String(error) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Identity = what the device sends to the decipher server (empty = nothing to mint for).
|
||||||
|
const identity = device?.identity;
|
||||||
|
if (!identity) {
|
||||||
|
return { status: "no-session" };
|
||||||
|
}
|
||||||
|
if (!force && !PoTokenMinter.shouldRefresh(device)) {
|
||||||
|
return { status: "current" };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const poToken = await PoTokenMinter.mintPoToken(identity);
|
||||||
|
// The token is valid until the integrity token expires; fall back to a default TTL.
|
||||||
|
const mintedAt = Math.floor(Date.now() / 1000);
|
||||||
|
const expiresAt = PoTokenMinter.integrityTokenExpiresAtMs > 0
|
||||||
|
? Math.floor(PoTokenMinter.integrityTokenExpiresAtMs / 1000)
|
||||||
|
: mintedAt + DEFAULT_POTOKEN_TTL_SECONDS;
|
||||||
|
await PlayletApi.sendPoToken(identity, poToken, mintedAt, expiresAt);
|
||||||
|
return { status: "minted" };
|
||||||
|
} catch (error) {
|
||||||
|
return { status: "failed", error: String(error) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,411 +0,0 @@
|
|||||||
import { Innertube, Platform, UniversalCache, type Types } from 'youtubei.js/web';
|
|
||||||
import { getHost } from "lib/Api/Host";
|
|
||||||
import { BG, buildURL, GOOG_API_KEY, type WebPoSignalOutput } from "bgutils-js";
|
|
||||||
import { type BgConfig } from "bgutils-js";
|
|
||||||
import type { VideoInfo } from 'node_modules/youtubei.js/dist/src/parser/youtube';
|
|
||||||
import type { StoryboardData } from 'node_modules/youtubei.js/dist/src/parser/classes/PlayerStoryboardSpec';
|
|
||||||
import type { PlayerLiveStoryboardSpec, PlayerStoryboardSpec } from 'node_modules/youtubei.js/dist/src/parser/nodes';
|
|
||||||
import type { Format } from 'node_modules/youtubei.js/dist/src/parser/misc';
|
|
||||||
|
|
||||||
export class YoutubeJs {
|
|
||||||
static host = () => `http://${getHost()}`
|
|
||||||
|
|
||||||
static innerTube: Innertube;
|
|
||||||
static innerTubePromise: Promise<void>;
|
|
||||||
|
|
||||||
static webPoMinter: BG.WebPoMinter;
|
|
||||||
static webPoMinterPromise: Promise<void>;
|
|
||||||
|
|
||||||
static visitorData?: string = undefined;
|
|
||||||
|
|
||||||
static async fetch(input: RequestInfo | URL, init?: RequestInit) {
|
|
||||||
const method = init?.method
|
|
||||||
? init.method
|
|
||||||
: input instanceof Request
|
|
||||||
? input.method
|
|
||||||
: 'GET';
|
|
||||||
|
|
||||||
const url = typeof input === 'string'
|
|
||||||
? new URL(input)
|
|
||||||
: input instanceof URL
|
|
||||||
? input
|
|
||||||
: new URL(input.url);
|
|
||||||
|
|
||||||
const headers = init?.headers
|
|
||||||
? new Headers(init.headers)
|
|
||||||
: input instanceof Request
|
|
||||||
? input.headers
|
|
||||||
: new Headers();
|
|
||||||
|
|
||||||
const headersObject = {};
|
|
||||||
headers.forEach((value, key) => {
|
|
||||||
headersObject[key] = value;
|
|
||||||
});
|
|
||||||
|
|
||||||
let body = init?.body
|
|
||||||
|
|
||||||
const args = {
|
|
||||||
Method: method,
|
|
||||||
Url: url,
|
|
||||||
Headers: headersObject,
|
|
||||||
Body: body,
|
|
||||||
CacheSeconds: -1,
|
|
||||||
};
|
|
||||||
|
|
||||||
const response = await fetch(`http://${getHost()}/api/innertube/proxy`, {
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify(args)
|
|
||||||
})
|
|
||||||
|
|
||||||
const responseData = await response.json();
|
|
||||||
|
|
||||||
return new Response(responseData.body, {
|
|
||||||
status: responseData.status,
|
|
||||||
statusText: `${responseData.status}`,
|
|
||||||
headers: responseData.headers,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
static async initVisitorData() {
|
|
||||||
if (YoutubeJs.visitorData) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
const sessionData = await YoutubeJs.getSessionData();
|
|
||||||
if (sessionData.visitorData) {
|
|
||||||
YoutubeJs.visitorData = sessionData.visitorData;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
YoutubeJs.visitorData = await YoutubeJs.generateVisitorData();
|
|
||||||
|
|
||||||
await YoutubeJs.setSessionData({
|
|
||||||
visitorData: YoutubeJs.visitorData,
|
|
||||||
timestamp: Math.floor(Date.now() / 1000)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getSessionData() {
|
|
||||||
const response = await fetch(`http://${getHost()}/api/innertube/session`)
|
|
||||||
return await response.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
static async setSessionData(sessionData: any) {
|
|
||||||
await fetch(`http://${getHost()}/api/innertube/session`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify(sessionData)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getInnertube() {
|
|
||||||
await YoutubeJs.initInnertube();
|
|
||||||
return YoutubeJs.innerTube;
|
|
||||||
}
|
|
||||||
|
|
||||||
static async initInnertube() {
|
|
||||||
if (YoutubeJs.innerTube) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (YoutubeJs.innerTubePromise) {
|
|
||||||
return YoutubeJs.innerTubePromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
YoutubeJs.innerTubePromise = new Promise(async (resolve, reject) => {
|
|
||||||
try {
|
|
||||||
this.initJsEvaluator();
|
|
||||||
await YoutubeJs.initVisitorData()
|
|
||||||
YoutubeJs.innerTube = await Innertube.create({
|
|
||||||
fetch: YoutubeJs.fetch,
|
|
||||||
cache: new UniversalCache(true),
|
|
||||||
visitor_data: YoutubeJs.visitorData,
|
|
||||||
});
|
|
||||||
YoutubeJs.innerTubePromise = null;
|
|
||||||
resolve();
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
YoutubeJs.innerTube = null;
|
|
||||||
YoutubeJs.innerTubePromise = null;
|
|
||||||
reject(error);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return YoutubeJs.innerTubePromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
static initJsEvaluator() {
|
|
||||||
Platform.shim.eval = async (data: Types.BuildScriptResult, env: Record<string, Types.VMPrimative>) => {
|
|
||||||
return new Function(data.output)();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
static async generateVisitorData() {
|
|
||||||
const innertube = await Innertube.create({ retrieve_player: false });
|
|
||||||
const visitorData = innertube.session.context.client.visitorData;
|
|
||||||
if (!visitorData) {
|
|
||||||
throw new Error('Could not get visitor data');
|
|
||||||
}
|
|
||||||
return visitorData;
|
|
||||||
}
|
|
||||||
|
|
||||||
static async initWebPoMinter() {
|
|
||||||
if (YoutubeJs.webPoMinter) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (YoutubeJs.webPoMinterPromise) {
|
|
||||||
return YoutubeJs.webPoMinterPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
YoutubeJs.webPoMinterPromise = new Promise(async (resolve, reject) => {
|
|
||||||
try {
|
|
||||||
const requestKey = 'O43z0dpjhgX20SCx4KAo';
|
|
||||||
|
|
||||||
const bgConfig: BgConfig = {
|
|
||||||
fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => YoutubeJs.fetch(input, init),
|
|
||||||
globalObj: globalThis,
|
|
||||||
requestKey,
|
|
||||||
identifier: ''
|
|
||||||
};
|
|
||||||
|
|
||||||
const bgChallenge = await BG.Challenge.create(bgConfig);
|
|
||||||
if (!bgChallenge) {
|
|
||||||
throw new Error('Could not get challenge');
|
|
||||||
}
|
|
||||||
|
|
||||||
const interpreterJavascript = bgChallenge.interpreterJavascript.privateDoNotAccessOrElseSafeScriptWrappedValue;
|
|
||||||
if (interpreterJavascript) {
|
|
||||||
new Function(interpreterJavascript)();
|
|
||||||
} else {
|
|
||||||
throw new Error('Could not load VM');
|
|
||||||
}
|
|
||||||
|
|
||||||
const botguard = await BG.BotGuardClient.create({
|
|
||||||
globalName: bgChallenge.globalName,
|
|
||||||
globalObj: globalThis,
|
|
||||||
program: bgChallenge.program
|
|
||||||
});
|
|
||||||
|
|
||||||
const webPoSignalOutput: WebPoSignalOutput = [];
|
|
||||||
const botguardResponse = await botguard.snapshot({ webPoSignalOutput });
|
|
||||||
|
|
||||||
const integrityTokenResponse = await bgConfig.fetch(buildURL('GenerateIT', true), {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'content-type': 'application/json+protobuf',
|
|
||||||
'x-goog-api-key': GOOG_API_KEY,
|
|
||||||
'x-user-agent': 'grpc-web-javascript/0.1'
|
|
||||||
},
|
|
||||||
body: JSON.stringify([requestKey, botguardResponse])
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await integrityTokenResponse.json() as unknown[];
|
|
||||||
|
|
||||||
if (typeof response[0] !== 'string')
|
|
||||||
throw new Error('Could not get integrity token');
|
|
||||||
|
|
||||||
YoutubeJs.webPoMinter = await BG.WebPoMinter.create({ integrityToken: response[0] }, webPoSignalOutput);
|
|
||||||
YoutubeJs.webPoMinterPromise = null;
|
|
||||||
resolve();
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
YoutubeJs.webPoMinter = null;
|
|
||||||
YoutubeJs.webPoMinterPromise = null;
|
|
||||||
reject(error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return YoutubeJs.webPoMinterPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
static async generatePoToken(videoId: string) {
|
|
||||||
await YoutubeJs.initWebPoMinter();
|
|
||||||
|
|
||||||
if (!YoutubeJs.webPoMinter) {
|
|
||||||
throw new Error('WebPoMinter is not initialized');
|
|
||||||
}
|
|
||||||
|
|
||||||
return await YoutubeJs.webPoMinter.mintAsWebsafeString(videoId);
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getVideoInfo(videoId: string) {
|
|
||||||
await YoutubeJs.initInnertube();
|
|
||||||
|
|
||||||
const info = await YoutubeJs.innerTube.getBasicInfo(videoId, {
|
|
||||||
client: 'TV',
|
|
||||||
po_token: await YoutubeJs.generatePoToken(videoId),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (info.playability_status.status !== 'OK') {
|
|
||||||
throw new Error(`Video is not playable: ${info.playability_status.status}\nReason: ${info.playability_status.reason}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// We can't generate a proper dash from live videos.
|
|
||||||
// By returning null, we're telling Playlet to fetch video info itself.
|
|
||||||
if (info.basic_info.is_live) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
YoutubeJs.innerTube.session.player.po_token = YoutubeJs.innerTube.session.po_token;
|
|
||||||
|
|
||||||
// Populate a video object that is similar to Invidious format.
|
|
||||||
// Mostly populate only fields we care about, enough to make it work.
|
|
||||||
return {
|
|
||||||
type: "video",
|
|
||||||
title: info.basic_info.title,
|
|
||||||
videoId: info.basic_info.id,
|
|
||||||
videoThumbnails: [],
|
|
||||||
storyboards: YoutubeJs.getStoryboards(info),
|
|
||||||
description: "",
|
|
||||||
published: 0,
|
|
||||||
publishedText: "",
|
|
||||||
keywords: [],
|
|
||||||
viewCount: 0,
|
|
||||||
likeCount: 0,
|
|
||||||
dislikeCount: 0,
|
|
||||||
paid: false,
|
|
||||||
premium: false,
|
|
||||||
isFamilyFriendly: true,
|
|
||||||
allowedRegions: [],
|
|
||||||
genre: "",
|
|
||||||
genreUrl: null,
|
|
||||||
author: info.basic_info.author,
|
|
||||||
authorId: info.basic_info.channel_id,
|
|
||||||
authorUrl: "",
|
|
||||||
authorVerified: false,
|
|
||||||
authorThumbnails: [],
|
|
||||||
subCountText: "",
|
|
||||||
lengthSeconds: info.basic_info.duration,
|
|
||||||
allowRatings: true,
|
|
||||||
rating: 0,
|
|
||||||
isListed: true,
|
|
||||||
liveNow: info.basic_info.is_live,
|
|
||||||
isPostLiveDvr: info.basic_info.is_post_live_dvr,
|
|
||||||
isUpcoming: info.basic_info.is_upcoming,
|
|
||||||
dashUrl: info.streaming_data.dash_manifest_url || "",
|
|
||||||
hlsUrl: info.streaming_data.hls_manifest_url,
|
|
||||||
adaptiveFormats: await YoutubeJs.transformFormats(info.streaming_data?.adaptive_formats),
|
|
||||||
formatStreams: await YoutubeJs.transformFormats(info.streaming_data?.formats),
|
|
||||||
captions: YoutubeJs.getCaptions(info),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static async transformFormats(formats: Format[]) {
|
|
||||||
if (!formats) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.all(formats.map(format =>
|
|
||||||
YoutubeJs.transformStreamFormat(format)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
static async transformStreamFormat(format: Format): Promise<any> {
|
|
||||||
const result: any = {
|
|
||||||
init: format.init_range ? `${format.init_range.start}-${format.init_range.end}` : "",
|
|
||||||
index: format.index_range ? `${format.index_range.start}-${format.index_range.end}` : "",
|
|
||||||
bitrate: `${format.bitrate}`,
|
|
||||||
itag: `${format.itag}`,
|
|
||||||
type: format.mime_type,
|
|
||||||
clen: `${format.approx_duration_ms}`,
|
|
||||||
lmt: `${format.last_modified}`,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (format.url || format.signature_cipher || format.cipher) {
|
|
||||||
result.url = await format.decipher(YoutubeJs.innerTube.session.player);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (format.audio_quality) {
|
|
||||||
result.audioQuality = format.audio_quality;
|
|
||||||
}
|
|
||||||
if (format.audio_sample_rate) {
|
|
||||||
result.audioSampleRate = format.audio_sample_rate;
|
|
||||||
}
|
|
||||||
if (format.audio_channels) {
|
|
||||||
result.audioChannels = format.audio_channels;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (format.quality_label) {
|
|
||||||
result.qualityLabel = format.quality_label;
|
|
||||||
}
|
|
||||||
if (format.fps) {
|
|
||||||
result.fps = format.fps;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (format.width) {
|
|
||||||
result.width = format.width;
|
|
||||||
}
|
|
||||||
if (format.height) {
|
|
||||||
result.height = format.height;
|
|
||||||
}
|
|
||||||
if (format.height && format.width) {
|
|
||||||
result.size = `${format.width}x${format.height}`;
|
|
||||||
result.resolution = `${format.height}p`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
static getStoryboards(videoInfo: VideoInfo) {
|
|
||||||
if (!videoInfo.storyboards) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (videoInfo.storyboards.type === 'PlayerLiveStoryboardSpec') {
|
|
||||||
const board = (videoInfo.storyboards as PlayerLiveStoryboardSpec).board
|
|
||||||
return [{
|
|
||||||
templateUrl: board.template_url,
|
|
||||||
width: board.thumbnail_width,
|
|
||||||
height: board.thumbnail_height,
|
|
||||||
count: -1,
|
|
||||||
interval: 5000,
|
|
||||||
storyboardWidth: board.columns,
|
|
||||||
storyboardHeight: board.rows,
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
|
|
||||||
const storyboards = (videoInfo.storyboards as PlayerStoryboardSpec).boards;
|
|
||||||
return storyboards.map((board: StoryboardData) => {
|
|
||||||
return {
|
|
||||||
templateUrl: board.template_url,
|
|
||||||
width: board.thumbnail_width,
|
|
||||||
height: board.thumbnail_height,
|
|
||||||
count: board.thumbnail_count,
|
|
||||||
interval: board.interval,
|
|
||||||
storyboardWidth: board.columns,
|
|
||||||
storyboardHeight: board.rows,
|
|
||||||
storyboardCount: board.storyboard_count
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
static getCaptions(videoInfo: VideoInfo) {
|
|
||||||
if (!videoInfo.captions?.caption_tracks) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return videoInfo.captions.caption_tracks.map(track => {
|
|
||||||
const baseUrl = track.base_url;
|
|
||||||
if (!baseUrl) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryComponents = new URLSearchParams(baseUrl.split('?')[1]);
|
|
||||||
queryComponents.set('fmt', 'vtt');
|
|
||||||
const modifiedBaseUrl = `${baseUrl.split('?')[0]}?${queryComponents.toString()}`;
|
|
||||||
|
|
||||||
return {
|
|
||||||
label: track.name.toString(),
|
|
||||||
language_code: track.language_code || '',
|
|
||||||
url: modifiedBaseUrl
|
|
||||||
};
|
|
||||||
}).filter(caption => !!caption);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { PlayletApi } from "lib/Api/PlayletApi";
|
||||||
|
import { translate } from "lib/Stores";
|
||||||
|
import { get } from "svelte/store";
|
||||||
|
|
||||||
|
const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"];
|
||||||
|
|
||||||
|
export let displayText: string = "";
|
||||||
|
// svelte-ignore unused-export-let
|
||||||
|
export let key: string = "";
|
||||||
|
export let description: string = "";
|
||||||
|
export let level: number = 0;
|
||||||
|
|
||||||
|
async function clearPoTokens() {
|
||||||
|
await PlayletApi.clearPoTokens();
|
||||||
|
alert(get(translate)("PoTokens cleared."));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="m-5">
|
||||||
|
<div class={textSizes[level]}>{$translate(displayText)}</div>
|
||||||
|
<div class="text-xs text-gray-500">{@html $translate(description)}</div>
|
||||||
|
<button class="btn m-1" on:click={clearPoTokens}
|
||||||
|
>{$translate("Clear PoTokens")}</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { translate } from "lib/Stores";
|
||||||
|
import { ensureDevicePoTokenWithToast } from "lib/ensureDevicePoToken";
|
||||||
|
|
||||||
|
const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"];
|
||||||
|
|
||||||
|
export let displayText: string = "";
|
||||||
|
// svelte-ignore unused-export-let
|
||||||
|
export let key: string = "";
|
||||||
|
export let description: string = "";
|
||||||
|
export let level: number = 0;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="m-5">
|
||||||
|
<div class={textSizes[level]}>{$translate(displayText)}</div>
|
||||||
|
<div class="text-xs text-gray-500">{@html $translate(description)}</div>
|
||||||
|
<button class="btn m-1" on:click={() => ensureDevicePoTokenWithToast(true)}
|
||||||
|
>{$translate("Mint PoToken")}</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
@@ -7,6 +7,8 @@
|
|||||||
import StringControl from "lib/Screens/Settings/SettingControls/StringControl.svelte";
|
import StringControl from "lib/Screens/Settings/SettingControls/StringControl.svelte";
|
||||||
import NumberControl from "./SettingControls/NumberControl.svelte";
|
import NumberControl from "./SettingControls/NumberControl.svelte";
|
||||||
import ClearCacheControl from "./SettingControls/ClearCacheControl.svelte";
|
import ClearCacheControl from "./SettingControls/ClearCacheControl.svelte";
|
||||||
|
import ClearPoTokensControl from "./SettingControls/ClearPoTokensControl.svelte";
|
||||||
|
import MintPoTokenControl from "./SettingControls/MintPoTokenControl.svelte";
|
||||||
import EditQualityControl from "./SettingControls/EditQualityControl.svelte";
|
import EditQualityControl from "./SettingControls/EditQualityControl.svelte";
|
||||||
import SponsorBlockCategoriesControl from "./SettingControls/SponsorBlockCategoriesControl.svelte";
|
import SponsorBlockCategoriesControl from "./SettingControls/SponsorBlockCategoriesControl.svelte";
|
||||||
import { translate } from "lib/Stores";
|
import { translate } from "lib/Stores";
|
||||||
@@ -34,6 +36,8 @@
|
|||||||
const customComponents = {
|
const customComponents = {
|
||||||
ClearSearchHistoryControl,
|
ClearSearchHistoryControl,
|
||||||
ClearCacheControl,
|
ClearCacheControl,
|
||||||
|
ClearPoTokensControl,
|
||||||
|
MintPoTokenControl,
|
||||||
EditHomeScreenControl,
|
EditHomeScreenControl,
|
||||||
PlayletLibVersionControl,
|
PlayletLibVersionControl,
|
||||||
EditQualityControl,
|
EditQualityControl,
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { toastStore, removeToast } from "lib/Toast";
|
||||||
|
|
||||||
|
const alertClass: Record<string, string> = {
|
||||||
|
success: "alert-success",
|
||||||
|
error: "alert-error",
|
||||||
|
info: "alert-info",
|
||||||
|
warning: "alert-warning",
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="toast toast-end toast-bottom z-50">
|
||||||
|
{#each $toastStore as toast (toast.id)}
|
||||||
|
<div class="alert {alertClass[toast.type] ?? 'alert-info'}">
|
||||||
|
<span>{toast.message}</span>
|
||||||
|
<button
|
||||||
|
class="btn btn-ghost btn-xs"
|
||||||
|
on:click={() => removeToast(toast.id)}>✕</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { writable } from "svelte/store";
|
||||||
|
|
||||||
|
export type ToastType = "success" | "error" | "info" | "warning";
|
||||||
|
|
||||||
|
export interface Toast {
|
||||||
|
id: number;
|
||||||
|
type: ToastType;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const toastStore = writable<Toast[]>([]);
|
||||||
|
|
||||||
|
let nextId = 0;
|
||||||
|
|
||||||
|
export function addToast(message: string, type: ToastType = "info", durationMs = 5000) {
|
||||||
|
const id = nextId++;
|
||||||
|
toastStore.update((toasts) => [...toasts, { id, type, message }]);
|
||||||
|
if (durationMs > 0) {
|
||||||
|
setTimeout(() => removeToast(id), durationMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeToast(id: number) {
|
||||||
|
toastStore.update((toasts) => toasts.filter((toast) => toast.id !== id));
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@
|
|||||||
import { playletStateStore, translate } from "lib/Stores";
|
import { playletStateStore, translate } from "lib/Stores";
|
||||||
import VideoStartAt from "./VideoStartAt.svelte";
|
import VideoStartAt from "./VideoStartAt.svelte";
|
||||||
import VideoThumbnail from "./VideoThumbnail.svelte";
|
import VideoThumbnail from "./VideoThumbnail.svelte";
|
||||||
import { YoutubeJs } from "lib/Api/YoutubeJs";
|
|
||||||
|
|
||||||
export let videoId: string | undefined = undefined;
|
export let videoId: string | undefined = undefined;
|
||||||
export let title: string | undefined = undefined;
|
export let title: string | undefined = undefined;
|
||||||
@@ -58,26 +57,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function playOnTvYtjs() {
|
|
||||||
try {
|
|
||||||
const videoInfo = getVideoInfo() as any;
|
|
||||||
|
|
||||||
// measure length of time it takes to get video info
|
|
||||||
const start = performance.now();
|
|
||||||
const metadata = await YoutubeJs.getVideoInfo(videoId);
|
|
||||||
const end = performance.now();
|
|
||||||
console.log(`Time to get video info: ${end - start}ms`);
|
|
||||||
|
|
||||||
if (metadata) {
|
|
||||||
videoInfo.metadata = metadata;
|
|
||||||
}
|
|
||||||
await PlayletApi.playVideo(videoInfo);
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
alert(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function queueOnTv() {
|
async function queueOnTv() {
|
||||||
try {
|
try {
|
||||||
const videoInfo = getVideoInfo();
|
const videoInfo = getVideoInfo();
|
||||||
@@ -168,9 +147,6 @@
|
|||||||
<button class="btn join-item hover:btn-accent" on:click={playOnTv}>
|
<button class="btn join-item hover:btn-accent" on:click={playOnTv}>
|
||||||
{$translate("Play on %1").replace("%1", tvName)}
|
{$translate("Play on %1").replace("%1", tvName)}
|
||||||
</button>
|
</button>
|
||||||
<button class="btn join-item hover:btn-accent" on:click={playOnTvYtjs}>
|
|
||||||
{$translate("Play on %1").replace("%1", tvName)} (ytjs)
|
|
||||||
</button>
|
|
||||||
<button class="btn join-item hover:btn-accent" on:click={queueOnTv}>
|
<button class="btn join-item hover:btn-accent" on:click={queueOnTv}>
|
||||||
{$translate("Queue on %1").replace("%1", tvName)}
|
{$translate("Queue on %1").replace("%1", tvName)}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { PoTokenMinter } from "lib/Api/PoTokenMinter";
|
||||||
|
import { addToast } from "lib/Toast";
|
||||||
|
|
||||||
|
// Mints for the current identity if needed, surfacing the outcome as a toast.
|
||||||
|
export async function ensureDevicePoTokenWithToast(force = false) {
|
||||||
|
const result = await PoTokenMinter.ensureDevicePoToken(force);
|
||||||
|
switch (result.status) {
|
||||||
|
case "minted":
|
||||||
|
addToast("PoToken minted on device", "success");
|
||||||
|
break;
|
||||||
|
case "current":
|
||||||
|
addToast("PoToken already up to date on device", "info");
|
||||||
|
break;
|
||||||
|
case "no-session":
|
||||||
|
addToast("No identity available to mint a PoToken yet", "warning");
|
||||||
|
break;
|
||||||
|
case "failed":
|
||||||
|
addToast(`PoToken minting failed: ${result.error}`, "error");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user