Compare commits

...
20 Commits
Author SHA1 Message Date
Brahim Hadriche 7c75903d11 Release v0.48.0 (#904) 2026-07-01 19:13:33 -04:00
Brahim Hadriche e2e3e3099f move trending items to the bottom of the list by default 2026-07-01 18:54:54 -04:00
Brahim Hadriche 3381d19b53 fmt fix 2026-07-01 18:31:20 -04:00
Brahim Hadriche 0f2a1a2b16 handle redirect in lounge code 2026-07-01 18:17:31 -04:00
Brahim Hadriche 38bfa1a102 Add trending back (Gaming and Live) 2026-07-01 17:53:02 -04:00
Brahim Hadriche fbb4a45ce5 Adjust live stream cushion 2026-07-01 11:12:18 -04:00
Brahim Hadriche 8dd24ddb43 Better tracking for INV-D1 in player 2026-06-30 18:36:39 -04:00
Brahim Hadriche fbf8e0a499 Attempt to reduce errors in post-live DVR videos 2026-06-30 16:21:46 -04:00
Brahim Hadriche c81f5cd9e1 Rewrite lounge service long poller 2026-06-30 16:09:04 -04:00
Brahim Hadriche 17ff6b940b retry sts, http client fix 2026-06-30 09:28:56 -04:00
Brahim Hadriche 2e1a4c9ea3 Merge branch 'main' of https://github.com/iBicha/playlet 2026-06-30 09:17:06 -04:00
Brahim Hadriche bd01da01e6 [skip ci] update README.md 2026-06-29 17:00:13 -04:00
Brahim Hadriche 333553790f OTF x DRM investigation 2026-06-29 12:54:44 -04:00
Brahim Hadriche 422d58508e [skip ci] capture response data when id extraction fails 2026-06-29 09:19:43 -04:00
Brahim Hadriche 430fef1585 Release v0.47.5 (#902) 2026-06-28 15:01:29 -04:00
Brahim Hadriche 4754e1620b Use living room potoken identity 2026-06-28 14:56:17 -04:00
Brahim Hadriche 5c5fe19440 Add "isLivingRoomDeeplink" param to /player payload, and remove auto-refresh of browser based tokens
browser based tokens are fallbacks now.
2026-06-27 14:28:46 -04:00
Brahim Hadriche ce32d2f762 small tweak 2026-06-26 13:13:51 -04:00
Brahim Hadriche 63f9ac693a Browser based potokens 2026-06-26 13:06:51 -04:00
Brahim Hadriche 5e798f19de Use datasyncIdToken as poTokenIdentity 2026-06-25 15:47:26 -04:00
71 changed files with 2521 additions and 1104 deletions

No files matched your search

+22
View File
@@ -5,6 +5,28 @@ 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/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.48.0] - 2026-07-01
### Added
- Trending back (Gaming and Live) for Playlet backend and Invidious - to avoid a blank home screen when not logged in.
### Fixed
- Retry condition issue in http client
- Attempt to fix "page needs to be reloaded" edge case
- Attempt to reduce errors in post-live DVR videos
## [0.47.5] - 2026-06-28
### Fixed
- Attempt to fix `No valid bitrates` error
### Removed
- Play with ytjs option from web app, as it wasn't working anyway
## [0.47.4] - 2026-06-25
### Fixed
-16
View File
@@ -66,22 +66,6 @@ Can't install from the store? See [How to install Playlet as a sideloaded/dev ap
- Use the YouTube app to connect using the same Wi-Fi; OR
- Use the `Link with TV code` to connect
### Picture-in-picture
- When viewing a video in full screen, press ⬇️ (down) button on your remote to shrink the video
- You can browse or search for videos while you watch
- To restore currently playing video to full screen, press the ✳️ (options) button
### Customize Invidious instance
1. Open settings in Playlet
1. Select Invidious -> Instance
1. Set a custom instance, or choose a public one hosted by volunteers (from [api.invidious.io](https://api.invidious.io/))
1. Optionally, Select `Test instance` to make sure it works
1. Hit save
> ℹ️ **Note**: If you are logged in when you change the instance, you will remain logged in to the old instance. In this case, Playlet will use the old instance to retrieve your subscriptions and your playlists, but will use the new instance for everything else. After switching to a new instance, you can log out and log in again to use your profile on the new instance.
## Development
For everything related to Playlet app development, please see the [documentation](./docs/README.md)
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet",
"version": "0.47.4",
"version": "0.48.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet",
"version": "0.47.4",
"version": "0.48.0",
"hasInstallScript": true,
"devDependencies": {
"@rokucommunity/bslint": "^0.8.44",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet",
"version": "0.47.4",
"version": "0.48.0",
"description": "Unofficial YouTube client for Roku",
"devDependencies": {
"@rokucommunity/bslint": "^0.8.44",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-app",
"version": "0.47.4",
"version": "0.48.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-app",
"version": "0.47.4"
"version": "0.48.0"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-app",
"version": "0.47.4",
"version": "0.48.0",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-app",
+2 -2
View File
@@ -2,8 +2,8 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=47
build_version=00004
minor_version=48
build_version=00000
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-lib",
"version": "0.47.4",
"version": "0.48.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-lib",
"version": "0.47.4"
"version": "0.48.0"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-lib",
"version": "0.47.4",
"version": "0.48.0",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-lib",
@@ -9,6 +9,7 @@
<!-- Innertube fields -->
<field id="activeIdentifyToken" type="string" />
<field id="selectActiveIdentityEndpoint" type="assocarray" />
<field id="thumbnail" type="uri" />
<field id="refreshToken" type="string" />
<field id="scope" type="string" />
@@ -0,0 +1,149 @@
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/source/services/HttpClient.bs"
namespace Innertube
' Some adaptive formats are tagged FORMAT_STREAM_TYPE_OTF yet are byte-range (the URL
' carries clen/gir=yes). Fetch a bounded head of one such video and audio format and
' report the response status, headers, and head bytes. No playback change.
' Large enough that the head spans ftyp+moov+sidx.
const BYTE_RANGE_PROBE_BYTES = 16383
function ProbeByteRangeFormats(adaptiveFormats as object, cancellation as object) as void
if not IsArray(adaptiveFormats)
return
end if
' One video + one audio sample is enough; stop once we have both.
videoFormat = invalid
audioFormat = invalid
for each format in adaptiveFormats
if IsByteRangeMislabeledOtf(format)
mimeType = ValidString(format.type)
if videoFormat = invalid and mimeType.StartsWith("video")
videoFormat = format
else if audioFormat = invalid and mimeType.StartsWith("audio")
audioFormat = format
end if
end if
if videoFormat <> invalid and audioFormat <> invalid
exit for
end if
end for
targets = []
if videoFormat <> invalid
targets.Push({ format: videoFormat, kind: "video", filePath: "tmp:/byte_range_probe_video.bin" })
end if
if audioFormat <> invalid
targets.Push({ format: audioFormat, kind: "audio", filePath: "tmp:/byte_range_probe_audio.bin" })
end if
if targets.Count() = 0
return
end if
requestHeaders = Innertube.CreateHeaders(Innertube.ClientType.Tv)
requestHeaders["origin"] = "https://www.youtube.com"
requestHeaders["referer"] = "https://www.youtube.com"
' Launch all fetches before awaiting any, so they download in parallel.
for each target in targets
' Plain concat keeps the signed query intact; range is a native byte-range
' param and bounds the download.
url = `${target.format.url}&range=0-${BYTE_RANGE_PROBE_BYTES}&rn=0`
request = HttpClient.Get(url)
request.Headers(requestHeaders)
request.ToFile(target.filePath)
request.Cancellation(cancellation)
request.Send()
target.request = request
end for
attachments = []
for each target in targets
AppendProbeReport(target, attachments)
DeleteFile(target.filePath)
end for
if CancellationUtils.IsCancelled(cancellation)
return
end if
LogTelemetryEvent({
level: "error"
message: "Byte-range probe for OTF-mislabeled formats"
fingerprint: ["Byte-range probe for OTF-mislabeled formats"]
attachments: attachments
})
end function
' OTF-tagged format that is actually byte-range: the URL carries clen (live OTF has
' none). Restrict to fragmented mp4 audio/video.
function IsByteRangeMislabeledOtf(format as object) as boolean
if not IsAssociativeArray(format)
return false
end if
if format.isTypeOTF <> true
return false
end if
mimeType = ValidString(format.type)
if not (mimeType.StartsWith("video/mp4") or mimeType.StartsWith("audio/mp4"))
return false
end if
url = ValidString(format.url)
return url.InStr("&clen=") <> -1 or url.InStr("?clen=") <> -1
end function
function AppendProbeReport(target as object, attachments as object) as void
format = target.format
itag = ValidString(format.itag)
response = target.request.Await()
lines = []
lines.Push(`itag: ${itag}`)
lines.Push(`kind: ${target.kind}`)
lines.Push(`mimeType: ${ValidString(format.type)}`)
lines.Push(`drm: ${IsArray(format.drmFamilies)}`)
if response.IsCancelled()
lines.Push("result: cancelled")
attachments.Push(ReportAttachment(target.kind, itag, lines))
return
end if
lines.Push(`http_status: ${response.StatusCode()}`)
lines.Push(`headers: ${ToString(response.Headers())}`)
if not response.IsSuccess()
lines.Push(`error: ${ValidString(response.ErrorMessage())}`)
attachments.Push(ReportAttachment(target.kind, itag, lines))
return
end if
' range bounds the response, so reading the whole temp file is safe.
head = CreateObject("roByteArray")
head.ReadFile(target.filePath)
fileLen = head.Count()
lines.Push(`bytes_received: ${fileLen}`)
if fileLen <= 0
attachments.Push(ReportAttachment(target.kind, itag, lines))
return
end if
attachments.Push(ReportAttachment(target.kind, itag, lines))
attachments.Push({
filename: `byte-range-${target.kind}-${itag}.bin.hex`
content_type: "text/plain"
data: head.ToHexString()
})
end function
function ReportAttachment(kind as string, itag as string, lines as object) as object
return {
filename: `byte-range-${kind}-${itag}.txt`
content_type: "text/plain"
data: lines.Join(`\n`)
}
end function
end namespace
@@ -51,12 +51,13 @@ namespace Innertube
function CreateContext(client as Innertube.ClientType, deviceInfo as object, options = invalid as object) as object
contextClient = invalid
livingRoomPoTokenId = OptionUtils.Get(options, "livingRoomPoTokenId")
if client = ClientType.Web
contextClient = CreateContextClientWeb(deviceInfo)
else if client = ClientType.IOS
contextClient = CreateContextClientIOS(deviceInfo)
else if client = ClientType.Tv or client = ClientType.TvDowngraded
contextClient = CreateContextClientTv(deviceInfo, client)
contextClient = CreateContextClientTv(deviceInfo, client, livingRoomPoTokenId)
else
throw "Invalid client type"
end if
@@ -163,12 +164,12 @@ namespace Innertube
}
end function
function CreateContextClientTv(deviceInfo as object, client as Innertube.ClientType) as object
function CreateContextClientTv(deviceInfo as object, client as Innertube.ClientType, livingRoomPoTokenId = "" as dynamic) as object
tvClientVersion = INNERTUBE_TV_CLIENT_VERSION
if client = ClientType.TvDowngraded
tvClientVersion = INNERTUBE_TV_CLIENT_VERSION_DOWNGRADED
end if
return {
contextClient = {
"hl": GetCurrentLocale(deviceInfo)
"gl": GetContentRegion(deviceInfo)
"remoteHost": ""
@@ -205,6 +206,10 @@ namespace Innertube
"playerType": "UNIPLAYER"
"connectionType": "CONN_CELLULAR_4G"
}
if not StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
contextClient.tvAppInfo["livingRoomPoTokenId"] = livingRoomPoTokenId
end if
return contextClient
end function
function GetCurrentLocale(deviceInfo as object) as string
@@ -4,29 +4,23 @@ import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/source/utils/StringUtils.bs"
function Init()
m.top.observeField("requestVisitorData", FuncName(OnRequestVisitorData))
m.top.observeField("requestSessionData", FuncName(OnRequestSessionData))
end function
function OnNodeReady()
OnRequestVisitorData()
QueueSessionDataJob()
end function
function OnRequestVisitorData() as void
if m.innertubeSessionDataJob <> invalid and not m.innertubeSessionDataJob.done
function OnRequestSessionData() as void
sessionData = m.top.sessionData
if IsAssociativeArray(sessionData) and not StringUtils.IsNullOrEmpty(sessionData.visitorData) and not StringUtils.IsNullOrEmpty(sessionData.livingRoomPoTokenId)
return
end if
RequestVisitorData()
QueueSessionDataJob()
end function
function RequestVisitorData() as void
if m.innertubeSessionDataJob <> invalid
m.innertubeSessionDataJob.cancel = true
m.innertubeSessionDataJob = invalid
end if
visitorData = m.top.visitorData
if not StringUtils.IsNullOrEmpty(visitorData)
function QueueSessionDataJob() as void
if m.innertubeSessionDataJob <> invalid and not m.innertubeSessionDataJob.done
return
end if
@@ -41,8 +35,4 @@ end function
function OnInnertubeSessionDataJobDone(event as object) as void
JobSystem.UnobserveCallback(event.getRoSGNode())
m.innertubeSessionDataJob = invalid
if StringUtils.IsNullOrEmpty(m.top.visitorData)
' Trigger observers in case the job threw an error and didn't set the visitorData
m.top.visitorData = ""
end if
end function
@@ -1,8 +1,7 @@
<component name="Innertube" extends="Node" includes="AutoBind">
<interface>
<field id="timestamp" type="int" />
<field id="visitorData" type="string" alwaysNotify="true" />
<field id="requestVisitorData" type="boolean" alwaysNotify="true" />
<field id="sessionData" type="assocarray" alwaysNotify="true" />
<field id="requestSessionData" type="boolean" alwaysNotify="true" />
<field id="jobQueue" type="node" />
</interface>
</component>
@@ -54,6 +54,16 @@ namespace InnertubeService
}
end if
totalPlayerRequests += 1
stsResult = Innertube.GetSignatureTimestamp(cancellation)
if CancellationUtils.IsCancelled(cancellation)
return {
error: "Cancelled"
}
end if
if stsResult.error <> invalid
return stsResult
end if
options["signatureTimestamp"] = stsResult.sts
playerRequest = Innertube.CreatePlayerRequest(client, options)
if not StringUtils.IsNullOrEmpty(accessToken) and (client = Innertube.ClientType.Tv or client = Innertube.ClientType.TvDowngraded)
playerRequest.Header("Authorization", "Bearer " + accessToken)
@@ -297,6 +307,58 @@ namespace InnertubeService
return Innertube.Search(query, options)
end function
function GetTrending(options = invalid as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
trendingType = LCase(OptionUtils.GetOrDefault(options, "type", ""))
disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false)
raw = OptionUtils.GetOrDefault(options, "raw", false)
if trendingType = "gaming"
browseId = "UCOpNcN46UbXVtpKMrmU4Abg" ' Gaming
params = "Egh0cmVuZGluZw%3D%3D"
else
browseId = "UC4R8DWoMoI7CAwX8_LjQHig" ' Livestreams (default)
params = "EgdsaXZldGFikgEDCKEK"
end if
request = Innertube.CreateBrowseRequest(browseId, Innertube.ClientType.Web, { params: params })
request.Cancellation(cancellation)
if raw
request.LogCurlCommand(true)
request.NoCache()
end if
response = request.Await()
if not response.IsSuccess()
return {
error: response.ErrorMessage()
}
end if
if raw
return response.Json()
end if
feeds = Innertube.ParseResponseDataForFeeds(response.Json(), {
response: response
disableCreatorOnTheRise: true
disableShorts: disableShorts
browseId: browseId
})
result = {
feeds: feeds
}
cacheControl = Innertube.ParseResponseForCacheControl(response)
if cacheControl <> invalid
result["cache-control"] = cacheControl
end if
return result
end function
function GetHome(options = invalid as object) as object
return GetBrowseAuthenticatedPage("FEwhat_to_watch", options)
end function
@@ -359,6 +421,11 @@ namespace InnertubeService
end if
options["videoId"] = videoId
stsResult = Innertube.GetSignatureTimestamp(cancellation)
if stsResult.error <> invalid
return stsResult
end if
options["signatureTimestamp"] = stsResult.sts
playerRequest = Innertube.CreatePlayerRequest(Innertube.ClientType.Tv, options)
playerRequest.Cancellation(cancellation)
playerRequest.Header("Authorization", "Bearer " + accessToken)
@@ -6,23 +6,50 @@ function ExecuteJob() as void
innertubeNode = JobGetInput().innertube
cached = Innertube.ReadSessionDataFromRegistry()
if cached <> invalid and not StringUtils.IsNullOrEmpty(cached.visitorData)
if IsInt(cached.timestamp)
innertubeNode.timestamp = cached.timestamp
end if
innertubeNode.visitorData = cached.visitorData
if Innertube.IsSessionDataFresh(cached)
return
end if
cachedVisitorData = ""
cachedLivingRoomPoTokenId = ""
if IsAssociativeArray(cached)
cachedVisitorData = ValidString(cached.visitorData)
cachedLivingRoomPoTokenId = ValidString(cached.livingRoomPoTokenId)
end if
fetched = Innertube.RequestSessionData(JobGetCancellation())
if fetched <> invalid
Innertube.SaveSessionDataToRegistry(fetched)
innertubeNode.timestamp = fetched.timestamp
innertubeNode.visitorData = fetched.visitorData
else if StringUtils.IsNullOrEmpty(innertubeNode.visitorData)
' Refresh failed and we never had an id — wake a cold waiter to fail. Never blank a valid id.
innertubeNode.visitorData = ""
' Publish the cached values immediately so playback isn't blocked while /tv is fetched.
innertubeNode.sessionData = {
"visitorData": cachedVisitorData
"livingRoomPoTokenId": cachedLivingRoomPoTokenId
}
fresh = Innertube.RequestTvClientData(JobGetCancellation())
if fresh = invalid
return
end if
visitorData = cachedVisitorData
timestamp = 0
if Innertube.IsVisitorDataFresh(cached)
visitorData = cached.visitorData
timestamp = cached.timestamp
else if not StringUtils.IsNullOrEmpty(fresh.visitorData)
visitorData = fresh.visitorData
timestamp = fresh.timestamp
else if not StringUtils.IsNullOrEmpty(cachedVisitorData)
visitorData = cachedVisitorData
timestamp = cached.timestamp
end if
livingRoomPoTokenId = cachedLivingRoomPoTokenId
if not StringUtils.IsNullOrEmpty(fresh.livingRoomPoTokenId)
livingRoomPoTokenId = fresh.livingRoomPoTokenId
end if
Innertube.SaveSessionDataToRegistry({
"timestamp": timestamp
"visitorData": visitorData
"livingRoomPoTokenId": livingRoomPoTokenId
})
innertubeNode.sessionData = {
"visitorData": visitorData
"livingRoomPoTokenId": livingRoomPoTokenId
}
end function
@@ -10,7 +10,7 @@ const LIVE_MAX_DVR_WINDOW_SEC = 43200
' Hold the live edge this many fragments behind the head so a momentary edge-miss refetches
' instead of erroring. Baked into liveCushionedAvailabilityStartUtc. 0 = ride the head.
const LIVE_EDGE_CUSHION_SEGMENTS = 2
const LIVE_EDGE_CUSHION_SEGMENTS = 3
namespace Innertube
@@ -1,7 +1,10 @@
import "pkg:/components/Services/Innertube/ByteRangeProbe.bs"
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/components/Services/Innertube/NodesParser.bs"
import "pkg:/components/Services/Innertube/OTFSegmentInfo.bs"
import "pkg:/components/Services/Innertube/PostLiveDvrInfo.bs"
import "pkg:/components/Services/Innertube/PoTokens.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/Types.bs"
@@ -11,12 +14,13 @@ namespace Innertube
function CreatePlayerRequest(client as Innertube.ClientType, options = invalid as object) as object
videoId = OptionUtils.Get(options, "videoId")
cancellation = OptionUtils.Get(options, "cancellation")
visitorData = OptionUtils.Get(options, "visitorData")
accessToken = OptionUtils.Get(options, "accessToken")
livingRoomPoTokenId = OptionUtils.Get(options, "livingRoomPoTokenId")
cpn = InnertubeService.CreateClientPlaybackNonce()
useAccessToken = (client = Innertube.ClientType.Tv or client = Innertube.ClientType.TvDowngraded) and not StringUtils.IsNullOrEmpty(accessToken)
isTv = (client = Innertube.ClientType.Tv or client = Innertube.ClientType.TvDowngraded)
useAccessToken = isTv and not StringUtils.IsNullOrEmpty(accessToken)
deviceInfo = CreateObject("roDeviceInfo")
@@ -51,17 +55,30 @@ namespace Innertube
"contentCheckOk": true
}
signatureTimestamp = GetSignatureTimestamp(cancellation)
signatureTimestamp = OptionUtils.Get(options, "signatureTimestamp")
if signatureTimestamp <> invalid
payload["playbackContext"]["contentPlaybackContext"]["signatureTimestamp"] = signatureTimestamp
end if
if isTv
payload["playbackContext"]["contentPlaybackContext"]["isLivingRoomDeeplink"] = true
end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload)
request.Headers(Innertube.CreateHeaders(client))
if not StringUtils.IsNullOrEmpty(visitorData) and not useAccessToken
request.Header("x-goog-visitor-id", visitorData)
request.poTokenIdentity = visitorData
end if
if not StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
request.poTokenIdentity = livingRoomPoTokenId
end if
if not StringUtils.IsNullOrEmpty(request.poTokenIdentity)
' NOTE: local potoken (browser-minted) is currently not in use.
' GetValidPoTokenForIdentity should return "", and the backend would mint the potoken.
request.poToken = Innertube.PoTokens.GetValidPoTokenForIdentity(request.poTokenIdentity)
end if
request.signatureTimestamp = signatureTimestamp
@@ -103,7 +120,7 @@ namespace Innertube
adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"]))
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
parsedResponse["error"] = error.error
if error.DoesExist("errorCode")
@@ -113,11 +130,15 @@ namespace Innertube
end if
parsedResponse["potAttached"] = HasPotParam(adaptiveFormats) or HasPotParam(formats)
LogDebug("poToken attached to deciphered urls:", parsedResponse["potAttached"])
' if isLive and adaptiveFormats.Count() > 0
' LogInfo("[LIVE-INFO] post-decipher, sts:", playerRequest.signatureTimestamp, "format[0].itag:", adaptiveFormats[0]["itag"], "url:", adaptiveFormats[0]["url"])
' end if
' 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
LogInfo("poToken attached to deciphered urls:", parsedResponse["potAttached"], "source:", parsedResponse["potSource"])
hasLiveStreamingData = FormatsHaveLiveStreamingData(adaptiveFormats) or FormatsHaveLiveStreamingData(formats)
isOTF = FormatsHasTypeOTF(adaptiveFormats)
@@ -170,12 +191,15 @@ namespace Innertube
if isPostLiveDvr
LogDebug("Fetching Post-Live DVR info")
GetPostLiveDvrInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, client, cancellation)
GetPostLiveDvrInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, client, cancellation, payload)
end if
if isOTF
LogDebug("Fetching OTF segment info")
OTFGetSegmentInfo(adaptiveFormats, client, cancellation)
' Some of these formats are byte-range despite the OTF tag; report what a
' byte-range fetch returns for them.
Innertube.ProbeByteRangeFormats(adaptiveFormats, cancellation)
end if
if isLive
@@ -476,16 +500,17 @@ namespace Innertube
return result
end function
function GetSignatureTimestamp(cancellation as object) as dynamic
function GetSignatureTimestamp(cancellation as object) as object
LogDebug(`ReadAsciiFile("tmp:/sts_cache.json")`)
cache = ReadAsciiFile("tmp:/sts_cache.json")
if not StringUtils.IsNullOrEmpty(cache)
json = StringUtils.ParseJsonSafe(cache)
return json["sts"]
return { sts: json["sts"] }
end if
request = HttpClient.Get(`${PLAYLET_SUPPORT_SERVER}/v1/sts`)
request.Cancellation(cancellation)
request.TryCount(3)
request.NoCache()
response = request.Await()
if not response.IsSuccess()
@@ -494,13 +519,13 @@ namespace Innertube
else
LogError(response.ErrorMessage())
end if
return invalid
return { error: response.ErrorMessage() }
end if
text = response.Text()
WriteAsciiFile("tmp:/sts_cache.json", text)
json = response.Json()
return json["sts"]
return { sts: json["sts"] }
end function
function HasPotParam(formats as object) as boolean
@@ -515,7 +540,7 @@ namespace Innertube
return false
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
' No need to decipher if signatureTimestamp is not available
return invalid
@@ -547,6 +572,10 @@ namespace Innertube
if not StringUtils.IsNullOrEmpty(poTokenIdentity)
body["identity"] = poTokenIdentity
end if
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.Cancellation(cancellation)
@@ -719,64 +748,4 @@ namespace Innertube
return false
end function
function GetPostLiveDvrInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as void
if adaptiveFormats.Count() = 0
LogWarn("GetPostLiveDvrInfo: No adaptive formats available")
return
end if
url = adaptiveFormats[0]["url"]
if StringUtils.IsNullOrEmpty(url)
LogWarn("GetPostLiveDvrInfo: URL is empty")
return
end if
queryComponents = UrlUtils.ParseQueryComponents(url)
queryComponents["rn"] = "0"
queryComponents["sq"] = "0"
if not StringUtils.IsNullOrEmpty(cpn)
queryComponents["cpn"] = cpn
end if
url = UrlUtils.SetQueryParams(url, queryComponents)
request = HttpClient.Head(url)
requestHeaders = Innertube.CreateHeaders(client)
requestHeaders["origin"] = "https://www.youtube.com"
requestHeaders["referer"] = "https://www.youtube.com"
requestHeaders["DNT"] = "?1"
request.Headers(requestHeaders)
request.TryCount(2)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
LogError("Failed to fetch Post-Live DVR info", response.ErrorMessage())
return
end if
headers = response.Headers()
if not headers.DoesExist("X-Head-Time-Millis") or not headers.DoesExist("X-Head-Seqnum")
msg = "GetPostLiveDvrInfo: Missing Post-Live DVR info in headers"
LogErrorNoTelemetry(msg, url, headers)
LogTelemetryEvent({
level: "error"
message: msg + `\nVideoID: ${parsedResponse["videoId"]}\nUrl: ${url}\nHeaders: ${FormatJson(headers)}`
fingerprint: [msg]
})
end if
durationMs = ValidString(headers["X-Head-Time-Millis"]).ToInt()
segmentCount = ValidString(headers["X-Head-Seqnum"]).ToInt()
if durationMs > 0
parsedResponse["postLiveDvrDurationMs"] = durationMs
end if
if segmentCount > 0
parsedResponse["postLiveDvrSegmentCount"] = segmentCount
end if
end function
end namespace
@@ -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
@@ -0,0 +1,106 @@
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/UrlUtils.bs"
namespace Innertube
function GetPostLiveDvrInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, client as Innertube.ClientType, cancellation as object, playerResponse as object) as void
if adaptiveFormats.Count() = 0
LogWarn("GetPostLiveDvrInfo: No adaptive formats available")
return
end if
formatUrl = adaptiveFormats[0]["url"]
if StringUtils.IsNullOrEmpty(formatUrl)
LogWarn("GetPostLiveDvrInfo: URL is empty")
return
end if
' Query the live edge (no sq): that response is Cache-Control: no-cache, always
' served fresh, so it carries X-Head-*. A finished stream's head is its final
' segment, so X-Head-Seqnum is the total count and X-Head-Time-Millis the duration.
primary = FetchPostLiveDvrHead(formatUrl, invalid, cpn, client, cancellation)
headers = invalid
if HasPostLiveDvrHead(primary)
headers = primary.headers
else
' sq=0 is cacheable, so an edge can return it missing X-Head-* (#359); fall
' back to it only when the live-edge query misses.
fallback = FetchPostLiveDvrHead(formatUrl, "0", cpn, client, cancellation)
diagnostics = PostLiveDvrDiagnostics(parsedResponse["videoId"], primary, fallback)
if HasPostLiveDvrHead(fallback)
headers = fallback.headers
LogTelemetryEvent({
level: "warning"
message: `GetPostLiveDvrInfo: no-sq missing head, sq=0 fallback recovered\n${diagnostics}`
fingerprint: ["GetPostLiveDvrInfo: sq=0 fallback recovered"]
})
else
' Stuck: neither header path has the head. Attach the full /player response
' so a fix is findable from telemetry alone - lengthSeconds + targetDurationSec
' approximate count/duration today, and any other usable field is there too.
' The blob folds into Sentry extra, keeping the message lean.
LogTelemetryEvent({
level: "error"
message: `GetPostLiveDvrInfo: both no-sq and sq=0 missing head\n${diagnostics}`
fingerprint: ["GetPostLiveDvrInfo: both no-sq and sq=0 missing head"]
attachments: [{
filename: "player_response.json"
content_type: "application/json"
data: FormatJson(playerResponse)
}]
})
return
end if
end if
durationMs = ValidString(headers["X-Head-Time-Millis"]).ToInt()
segmentCount = ValidString(headers["X-Head-Seqnum"]).ToInt()
if durationMs > 0
parsedResponse["postLiveDvrDurationMs"] = durationMs
end if
if segmentCount > 0
parsedResponse["postLiveDvrSegmentCount"] = segmentCount
end if
end function
function FetchPostLiveDvrHead(formatUrl as string, sq as dynamic, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as object
queryComponents = UrlUtils.ParseQueryComponents(formatUrl)
queryComponents["rn"] = "0"
if sq <> invalid
queryComponents["sq"] = sq
end if
if not StringUtils.IsNullOrEmpty(cpn)
queryComponents["cpn"] = cpn
end if
url = UrlUtils.SetQueryParams(formatUrl, queryComponents)
request = HttpClient.Head(url)
requestHeaders = Innertube.CreateHeaders(client)
requestHeaders["origin"] = "https://www.youtube.com"
requestHeaders["referer"] = "https://www.youtube.com"
requestHeaders["DNT"] = "?1"
request.Headers(requestHeaders)
request.TryCount(2)
request.Cancellation(cancellation)
response = request.Await()
return {
url: url
statusCode: response.StatusCode()
headers: response.Headers()
}
end function
function HasPostLiveDvrHead(result as object) as boolean
return IsAssociativeArray(result) and IsAssociativeArray(result.headers) and result.headers.DoesExist("X-Head-Time-Millis") and result.headers.DoesExist("X-Head-Seqnum")
end function
function PostLiveDvrDiagnostics(videoId as dynamic, primary as object, fallback as object) as string
return `VideoID: ${ValidString(videoId)}` + Chr(10) + `URL (no-sq; sq=0 appends &sq=0): ${primary.url}` + Chr(10) + `no-sq HEAD status: ${primary.statusCode.ToStr()} headers: ${FormatJson(primary.headers)}` + Chr(10) + `sq=0 HEAD status: ${fallback.statusCode.ToStr()} headers: ${FormatJson(fallback.headers)}`
end function
end namespace
@@ -1,7 +1,8 @@
import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
@@ -10,8 +11,9 @@ namespace Innertube
const SESSION_DATA_VERSION = 1
const INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS = 60 * 60 * 24 * 14 ' 14 days
const TV_CLIENT_DATA_MAX_ATTEMPTS = 3
function IsSessionDataFresh(sessionData as object) as boolean
function IsVisitorDataFresh(sessionData as object) as boolean
if sessionData = invalid or not IsInt(sessionData.timestamp)
return false
end if
@@ -19,48 +21,103 @@ namespace Innertube
return nowSeconds - sessionData.timestamp <= INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS
end function
function RequestSessionData(cancellation = invalid as object) as object
request = HttpClient.Get("https://www.youtube.com/sw.js_data")
request.Headers({
"Accept-Language": "en-US,en;q=0.9"
"User-Agent": INNERTUBE_WEB_USER_AGENT
"Accept": "*/*"
"Referer": "https://www.youtube.com/sw.js"
})
request.Cancellation(cancellation)
request.TryCount(2)
request.NoCache()
function RequestTvClientData(cancellation = invalid as object) as object
visitorData = ""
livingRoomPoTokenId = ""
visitorDataResponse = ""
livingRoomPoTokenIdResponse = ""
response = request.Await()
if not response.IsSuccess()
LogError("Failed to fetch session data: " + response.ErrorMessage())
return invalid
end if
for attempt = 1 to TV_CLIENT_DATA_MAX_ATTEMPTS
text = FetchTvClientPage(cancellation)
if not StringUtils.IsNullOrEmpty(text)
if StringUtils.IsNullOrEmpty(visitorData)
visitorData = ExtractEscapedJsonString(text, "visitorData")
if StringUtils.IsNullOrEmpty(visitorData)
visitorDataResponse = text
end if
end if
if StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
livingRoomPoTokenId = ExtractEscapedJsonString(text, "LIVING_ROOM_PO_TOKEN_ID")
if StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
livingRoomPoTokenIdResponse = text
end if
end if
if not StringUtils.IsNullOrEmpty(visitorData) and not StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
exit for
end if
end if
if CancellationUtils.IsCancelled(cancellation)
exit for
end if
if attempt < TV_CLIENT_DATA_MAX_ATTEMPTS
sleep(attempt * 1000)
end if
end for
text = response.Text()
text = text.Replace(`)]}'`, "")
json = StringUtils.ParseJsonSafe(text)
if json = invalid
LogError("Failed to parse session data: " + text)
return invalid
end if
visitorData = ObjectUtils.Dig(json, [0, 2, 0, 0, 13])
if StringUtils.IsNullOrEmpty(visitorData)
LogError("Failed to find visitorData in session data: " + text)
ReportTvClientDataFailure("Could not extract visitorData from tv client data", visitorDataResponse)
end if
if StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
ReportTvClientDataFailure("Could not extract livingRoomPoTokenId from tv client data", livingRoomPoTokenIdResponse)
end if
if StringUtils.IsNullOrEmpty(visitorData) and StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
return invalid
end if
return {
"timestamp": TimeUtils.Now().AsSeconds()
"visitorData": visitorData
"livingRoomPoTokenId": livingRoomPoTokenId
}
end function
function ReportTvClientDataFailure(message as string, responseText as dynamic) as void
LogErrorNoTelemetry(message)
event = {
level: "error"
message: message
}
if not StringUtils.IsNullOrEmpty(responseText)
event.attachments = [{
filename: "response.html"
content_type: "text/html"
data: responseText
}]
end if
LogTelemetryEvent(event)
end function
function FetchTvClientPage(cancellation as object) as dynamic
request = HttpClient.Get("https://www.youtube.com/tv")
headers = Innertube.CreateHeaders(Innertube.ClientType.Tv)
headers["Referer"] = "https://www.youtube.com/tv"
request.Headers(headers)
request.Cancellation(cancellation)
request.NoCache()
response = request.Await()
if not response.IsSuccess()
LogError("Failed to fetch tv client data:", response.ErrorMessage())
return invalid
end if
return response.Text()
end function
function ExtractEscapedJsonString(text as string, key as string) as string
regex = CreateObject("roRegex", `"${key}":"([^"]*)"`, "")
match = regex.Match(text)
if match.Count() < 2
return ""
end if
decoded = StringUtils.ParseJsonSafe(`["${match[1]}"]`)
if not IsArray(decoded) or decoded.Count() <> 1
return ""
end if
return decoded[0]
end function
function SaveSessionDataToRegistry(sessionData as object) as void
sessionData.__version = SESSION_DATA_VERSION
RegistryUtils.Write(RegistryUtils.INNERTUBE_SESSION_DATA, FormatJson(sessionData))
end function
@@ -70,13 +127,7 @@ namespace Innertube
return invalid
end if
sessionData = StringUtils.ParseJsonSafe(sessionData)
if sessionData = invalid
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
return invalid
end if
return sessionData
return StringUtils.ParseJsonSafe(sessionData)
end function
end namespace
@@ -0,0 +1,271 @@
import "pkg:/components/Services/LoungeService/LoungeBytes.bs"
import "pkg:/source/utils/ByteArrayUtils.bs"
enum HttpDecoderState
Head
ChunkSize
ChunkData
Done
Redirect
Error
end enum
enum HttpDecoderError
None = ""
MalformedStatus = "malformed_status"
UnsupportedEncoding = "unsupported_encoding"
ChunkOverflow = "chunk_overflow"
ShortRead = "short_read"
end enum
const HTTP_DECODER_COMPACT_THRESHOLD = 32768
const HTTP_DECODER_READ_LENGTH = 65536
class HttpChunkedDecoder
public statusCode = 0
public statusText = ""
public errorReason = HttpDecoderError.None
public headers
private buffer
private cursor = 0
private state = HttpDecoderState.Head
private chunkRemaining = 0
private headCheckedSize = 0
function new()
m.buffer = CreateObject("roByteArray")
m.headers = {}
end function
function Pump(socket as object, output as object) as integer
received = m.ReceiveFrom(socket)
if received > 0
m.Process(output)
end if
return received
end function
function IsDone() as boolean
return m.state = HttpDecoderState.Done
end function
function IsError() as boolean
return m.state = HttpDecoderState.Error
end function
function IsRedirect() as boolean
return m.state = HttpDecoderState.Redirect
end function
function Location() as dynamic
return m.headers["location"]
end function
private function ReceiveFrom(socket as object) as integer
available = socket.GetCountRcvBuf()
if available <= 0
return 0
end if
lengthToRead = available
if lengthToRead > HTTP_DECODER_READ_LENGTH
lengthToRead = HTTP_DECODER_READ_LENGTH
end if
writeIndex = m.buffer.Count()
m.buffer[writeIndex + lengthToRead - 1] = 0
received = socket.Receive(m.buffer, writeIndex, lengthToRead)
if received > 0 and received < lengthToRead
' GetCountRcvBuf reported more than Receive delivered, leaving uninitialised slack.
m.errorReason = HttpDecoderError.ShortRead
m.state = HttpDecoderState.Error
end if
return received
end function
private function Process(output as object) as void
running = true
while running
if m.state = HttpDecoderState.Head
running = m.ParseHead()
else if m.state = HttpDecoderState.ChunkSize
running = m.ParseChunkSize()
else if m.state = HttpDecoderState.ChunkData
running = m.ParseChunkData(output)
else
running = false
end if
end while
m.Compact()
end function
' Status line and headers are ASCII, so they parse as a string; the chunk body that follows is
' not, so it stays in bytes.
private function ParseHead() as boolean
bufferSize = m.buffer.Count()
if bufferSize = m.headCheckedSize
return false
end if
head = m.buffer.ToAsciiString()
delimiter = head.InStr(`\r\n\r\n`)
if delimiter = -1
m.headCheckedSize = bufferSize
return false
end if
contentStart = delimiter + 4
if m.buffer[contentStart - 4] <> 13 or m.buffer[contentStart - 3] <> 10 or m.buffer[contentStart - 2] <> 13 or m.buffer[contentStart - 1] <> 10
m.statusText = "Invalid header delimiter - is there unicode text in headers?"
m.errorReason = HttpDecoderError.MalformedStatus
m.state = HttpDecoderState.Error
return false
end if
lines = head.Left(delimiter).Split(`\r\n`)
if not m.ParseStatusLine(lines[0])
return false
end if
for i = 1 to lines.Count() - 1
m.ParseHeaderLine(lines[i])
end for
m.cursor = contentStart
return m.FinishHead()
end function
private function ParseStatusLine(line as string) as boolean
if not line.StartsWith("HTTP/1.1 ") and not line.StartsWith("HTTP/1.0 ")
m.statusText = "Malformed status line"
m.errorReason = HttpDecoderError.MalformedStatus
m.state = HttpDecoderState.Error
return false
end if
rest = line.Mid(9).Trim()
spaceIndex = rest.InStr(" ")
if spaceIndex = -1
m.statusCode = Int(Val(rest, 10))
m.statusText = ""
else
m.statusCode = Int(Val(rest.Left(spaceIndex), 10))
m.statusText = rest.Mid(spaceIndex + 1)
end if
return true
end function
private function ParseHeaderLine(line as string) as void
colon = line.InStr(":")
if colon > 0
key = LCase(line.Left(colon).Trim())
m.headers[key] = line.Mid(colon + 1).Trim()
end if
end function
private function FinishHead() as boolean
if m.IsRedirectStatus(m.statusCode)
m.state = HttpDecoderState.Redirect
return false
end if
if m.statusCode <> 200
m.state = HttpDecoderState.Error
return false
end if
transferEncoding = m.headers["transfer-encoding"]
if transferEncoding = invalid or LCase(transferEncoding).InStr("chunked") = -1
m.statusText = "Unsupported transfer-encoding"
m.errorReason = HttpDecoderError.UnsupportedEncoding
m.state = HttpDecoderState.Error
return false
end if
m.state = HttpDecoderState.ChunkSize
return true
end function
private function IsRedirectStatus(code as integer) as boolean
return code = 301 or code = 302 or code = 303 or code = 307 or code = 308
end function
private function ParseChunkSize() as boolean
' Skip the CRLF trailing the previous chunk's data (and any stray newlines).
while m.cursor < m.buffer.Count() and (m.buffer[m.cursor] = 13 or m.buffer[m.cursor] = 10)
m.cursor += 1
end while
crlf = LoungeBytes.IndexOfCrlf(m.buffer, m.cursor)
if crlf = -1
return false
end if
sizeLine = LoungeBytes.RangeToString(m.buffer, m.cursor, crlf)
m.cursor = crlf + 2
' A chunk-size line may carry ';ext' extensions; the size is the leading hex token.
semicolon = sizeLine.InStr(";")
if semicolon > 0
sizeLine = sizeLine.Left(semicolon)
end if
m.chunkRemaining = Int(Val(sizeLine.Trim(), 16))
if m.chunkRemaining < 0
' A size that doesn't fit a 32-bit int is a corrupt size line or a parse desync.
m.errorReason = HttpDecoderError.ChunkOverflow
m.state = HttpDecoderState.Error
return false
end if
if m.chunkRemaining = 0
m.state = HttpDecoderState.Done
return false
end if
m.state = HttpDecoderState.ChunkData
return true
end function
private function ParseChunkData(output as object) as boolean
available = m.buffer.Count() - m.cursor
if available <= 0
return false
end if
take = available
if take > m.chunkRemaining
take = m.chunkRemaining
end if
chunk = ByteArrayUtils.Slice(m.buffer, m.cursor, m.cursor + take)
output.Append(chunk)
m.cursor += take
m.chunkRemaining -= take
if m.chunkRemaining = 0
m.state = HttpDecoderState.ChunkSize
return true
end if
return false
end function
' A fully consumed buffer Clears for free; a partial one waits until the dead prefix is worth a slice.
private function Compact() as void
if m.cursor = 0
return
end if
if m.cursor >= m.buffer.Count()
m.buffer.Clear()
else if m.cursor >= HTTP_DECODER_COMPACT_THRESHOLD
m.buffer = LoungeBytes.Tail(m.buffer, m.cursor)
else
return
end if
m.cursor = 0
m.headCheckedSize = 0
end function
end class
@@ -1,310 +0,0 @@
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/UrlUtils.bs"
const LONG_POLL_BUFSIZE = 65536
const LONG_POLL_TIMEOUT_MS = 60000
enum HttpResponseState
INIT = 0
READING_STATUS = 1
READING_HEADERS = 2
READING_BODY_CHUNK_SIZE = 3
READING_BODY_CHUNK = 4
end enum
class LongPoller
' Socket stuff for long polling
private socket
private socket_buffer
private socket_state = HttpResponseState.INIT
private socket_chunk_size = 0
private socket_timer
private status_code = 0
private status_text
private headers
function new()
m.socket_timer = CreateObject("roTimespan")
end function
function SendRequest(url as string, messagePort as object) as boolean
m.url = url
urlObject = UrlUtils.ParseUrl(url)
if urlObject.protocol <> "http"
throw `Invalid protocol: ${urlObject.protocol}`
end if
sendAddress = CreateObject("roSocketAddress")
sendAddress.SetAddress(`${urlObject.host}:${urlObject.port}`)
socket = CreateObject("roStreamSocket")
socket.setSendToAddress(sendAddress)
if not socket.Connect()
LogError("Failed to connect")
return false
end if
LogInfo(`Sending long polling GET ${url}`, "ID:", socket.GetID())
LogDebug(`======== curl command ========\n${m.ToCurlCommand()}\n==============================`)
message = `GET ${urlObject.path} HTTP/1.1\r\n`
message += `Host: ${urlObject.host}\r\n`
message += `\r\n`
socket.SendStr(message)
socket.notifyReadable(true)
socket.setMessagePort(messagePort)
m.socket = socket
m.socket_timer.Mark()
return true
end function
' Returns:
' - false if we're no longer returning data - socket is closed
' - true if we're still waiting for data
' - array we've received chunk(s) of data
function Poll(socketMessages as object) as dynamic
if m.socket = invalid
return false
end if
socket = m.socket
if not socket.IsConnected()
LogError("Socket is not connected")
m.CloseSocket()
return false
end if
' Not receiving data for LONG_POLL_TIMEOUT_MS seconds might be a sign of a dead connection
if m.socket_timer.TotalMilliseconds() > LONG_POLL_TIMEOUT_MS
LogWarnNoTelemetry("Timeout after", LONG_POLL_TIMEOUT_MS, "ms")
m.CloseSocket()
return false
end if
if socketMessages.Count() = 0
return true
end if
hasDataToReceive = false
for each socketMessage in socketMessages
if socketMessage.GetSocketID() = socket.GetID()
hasDataToReceive = true
exit for
end if
end for
if not hasDataToReceive
return true
end if
data = socket.ReceiveStr(LONG_POLL_BUFSIZE)
if not socket.eSuccess()
LogError("Error receiving data")
m.CloseSocket()
return false
end if
m.socket_timer.Mark()
if m.socket_buffer = invalid
m.socket_buffer = ""
end if
m.socket_buffer += data
return m.ParseData()
end function
function IsOpen() as boolean
return m.socket <> invalid and m.socket.IsConnected()
end function
function CloseSocket() as void
if m.socket = invalid
return
end if
m.socket.notifyReadable(false)
m.socket.close()
m.socket = invalid
m.socket_buffer = invalid
m.socket_state = HttpResponseState.INIT
end function
function ParseData() as dynamic
if m.socket_state = HttpResponseState.INIT
m.socket_state = HttpResponseState.READING_STATUS
end if
if m.socket_state = HttpResponseState.READING_STATUS
if not m.ParseOpration()
return false
end if
end if
if m.socket_state = HttpResponseState.READING_HEADERS
if not m.ParseHeaders()
return false
end if
end if
chunks = []
READING_BODY_CHUNK_SIZE:
if m.socket_state = HttpResponseState.READING_BODY_CHUNK_SIZE
if not m.ParseChunkSize()
return chunks
end if
end if
if m.socket_state = HttpResponseState.READING_BODY_CHUNK
chunk = m.ParseChunk()
if IsBool(chunk)
if not chunk
return chunks
end if
else
chunks.Push(chunk)
goto READING_BODY_CHUNK_SIZE
end if
end if
return chunks
end function
function ParseOpration() as boolean
newLineIndex = m.socket_buffer.InStr(`\r\n`)
if newLineIndex > 0
operationLine = m.socket_buffer.Left(newLineIndex)
if not operationLine.StartsWith("HTTP/1.1 ")
LogError("Invalid operation line:", operationLine)
m.CloseSocket()
return false
end if
status = operationLine.Mid(9)
spaceIndex = status.InStr(" ")
if spaceIndex = -1
LogError("Invalid operation line:", operationLine)
m.CloseSocket()
return false
end if
statusCode = status.Left(spaceIndex)
m.status_code = Val(statusCode)
m.status_text = status.Mid(spaceIndex + 1)
if m.status_code <> 200
' TODO:P2 refactor http parsing! headers probably contains a keep-alive, but we
' ignore and close anyway
if m.status_code = 410 or (m.status_code = 400 and m.socket_buffer.InStr("Unknown SID") <> -1)
LogErrorNoTelemetry("Invalid status code:", m.status_code, `\nResponse data:`, m.socket_buffer)
else
LogError("Invalid status code:", m.status_code, `\nResponse data:`, m.socket_buffer)
end if
m.CloseSocket()
return false
end if
m.socket_buffer = m.socket_buffer.Mid(newLineIndex + 2)
m.socket_state = HttpResponseState.READING_HEADERS
end if
return true
end function
function ParseHeaders() as boolean
newLineIndex = m.socket_buffer.InStr(`\r\n\r\n`)
if newLineIndex > 0
headersStr = m.socket_buffer.Left(newLineIndex)
headers = {}
headerLines = headersStr.Split(`\r\n`)
for each headerLine in headerLines
colonIndex = headerLine.InStr(":")
key = headerLine.Left(colonIndex).Trim()
value = headerLine.Mid(colonIndex + 1).Trim()
headers[key] = value
end for
m.headers = headers
LogDebug("Headers:", headers)
if headers["Transfer-Encoding"] <> "chunked"
LogError("Invalid transfer encoding:", headers["Transfer-Encoding"])
m.CloseSocket()
return false
end if
m.socket_buffer = m.socket_buffer.Mid(newLineIndex + 4)
m.socket_state = HttpResponseState.READING_BODY_CHUNK_SIZE
end if
return true
end function
function ParseChunkSize() as boolean
m.ConsumeNewLines()
newLineIndex = m.socket_buffer.InStr(`\r\n`)
if newLineIndex > 0
chunkSize = m.socket_buffer.Left(newLineIndex)
chunkSize = chunkSize.Trim()
chunkSize = Val(chunkSize, 16)
LogDebug("Chunk size:", chunkSize)
m.socket_chunk_size = chunkSize
if chunkSize = 0
LogDebug("End of chunked data")
m.CloseSocket()
return false
end if
m.socket_buffer = m.socket_buffer.Mid(newLineIndex + 2)
m.socket_state = HttpResponseState.READING_BODY_CHUNK
end if
return true
end function
function ParseChunk() as dynamic
if m.socket_chunk_size > 0
if m.socket_buffer.Len() >= m.socket_chunk_size
chunk = m.socket_buffer.Left(m.socket_chunk_size)
m.socket_buffer = m.socket_buffer.Mid(m.socket_chunk_size)
m.socket_chunk_size = 0
m.socket_state = HttpResponseState.READING_BODY_CHUNK_SIZE
return chunk
end if
else
LogError("Invalid chunk size")
m.CloseSocket()
return false
end if
return true
end function
function ConsumeNewLines()
CR = `\r`
LF = `\n`
startIndex = 0
while true
char = m.socket_buffer.Mid(startIndex, 1)
if char = CR or char = LF
startIndex += 1
else
exit while
end if
end while
if startIndex > 0
m.socket_buffer = m.socket_buffer.Mid(startIndex)
end if
end function
function ToCurlCommand() as string
' It won't work the same since it will disconnect quickly
return `curl "${m.url}"`
end function
end class
@@ -1,7 +1,8 @@
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
import "pkg:/components/Services/LoungeService/LongPoller.bs"
import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs"
import "pkg:/components/Services/LoungeService/LoungeConstants.bs"
import "pkg:/components/Services/LoungeService/LoungeFraming.bs"
import "pkg:/components/Services/LoungeService/LoungeMessages.bs"
import "pkg:/components/Services/LoungeService/LoungeVideoQueue.bs"
import "pkg:/components/Services/LoungeService/Notifications/DeviceConnectedNotificationUtils.bs"
@@ -36,7 +37,7 @@ class LoungeApi
private ofs
private lastProcessedCommandIndex = -1
private poller
private backchannel
private outgoingMessagesRequests
function new(loungeServiceNode as object, videoQueueNode as object, notificationsNode as object, invidiousNode as object)
@@ -50,7 +51,7 @@ class LoungeApi
m.deviceName = deviceName
m.screenName = deviceName
m.ofs = 0
m.poller = invalid
m.backchannel = invalid
m.outgoingMessagesRequests = {}
m.devices = {}
@@ -211,19 +212,30 @@ class LoungeApi
return false
end if
text = response.Text()
' First line should be a number, which is the length of the JSON payload
text = text.Mid(text.instr(`\n`) + 1)
body = CreateObject("roByteArray")
body.FromAsciiString(response.Text())
' A new session restarts command indices from 0; clear the high-water mark so its commands
' aren't skipped as duplicates.
m.lastProcessedCommandIndex = -1
messagesToSend = []
commands = StringUtils.ParseJsonSafe(text)
m.ProcessCommands(commands, messagesToSend)
result = LoungeFraming.Extract(body, 0)
for each frame in result.frames
m.ProcessFrame(frame, messagesToSend)
end for
if StringUtils.IsNullOrEmpty(m.sessionId) or StringUtils.IsNullOrEmpty(m.gSessionId)
LogTelemetryEvent({
level: "error"
message: "Lounge bind succeeded but yielded no session id"
fingerprint: "lounge-bind-no-sid"
})
end if
m.SendMessages(messagesToSend)
return true
end function
function FetchCommandsRpc(messagePort as object) as void
' Note we're not using https, not supported by LongPoller
' Plain HTTP: LoungeBackchannel streams this response over a raw socket, which has no TLS
baseUrl = "http://www.youtube.com/api/lounge/bc/bind"
queryParams = {
"device": "LOUNGE_SCREEN"
@@ -247,63 +259,48 @@ class LoungeApi
url = UrlUtils.BuildUrl(baseUrl, invalid, queryParams)
if m.poller = invalid
m.poller = new LongPoller()
if m.backchannel = invalid
m.backchannel = new LoungeBackchannel()
end if
m.poller.SendRequest(url, messagePort)
m.backchannel.Open(url, messagePort)
end function
function Poll(socketMessages as object, messagesToSend as object) as boolean
chunks = m.poller.Poll(socketMessages)
if IsArray(chunks)
for each chunk in chunks
m.ProcessChunk(chunk, messagesToSend)
end for
end if
frames = m.backchannel.Poll(socketMessages)
for each frame in frames
m.ProcessFrame(frame, messagesToSend)
end for
return m.poller.IsOpen()
return m.backchannel.IsOpen()
end function
function ProcessChunk(chunk as string, messagesToSend as object) as void
chunk = m.ConsumeNewLines(chunk)
newLineIndex = chunk.InStr(`\n`)
while newLineIndex > 0
payloadSize = chunk.Left(newLineIndex).trim()
payloadSize = payloadSize.ToInt()
payload = chunk.Mid(newLineIndex + 1, payloadSize)
commands = StringUtils.ParseJsonSafe(payload)
m.ProcessCommands(commands, messagesToSend)
chunk = chunk.Mid(newLineIndex + payloadSize + 1)
newLineIndex = chunk.InStr(`\n`)
end while
function GetCloseInfo() as object
if m.backchannel = invalid
return { statusCode: 0, reason: "", target: "" }
end if
return { statusCode: m.backchannel.statusCode, reason: m.backchannel.closeReason, target: m.backchannel.redirectTarget }
end function
function ConsumeNewLines(chunk as string) as string
CR = `\r`
LF = `\n`
startIndex = 0
while true
char = chunk.Mid(startIndex, 1)
if char = CR or char = LF
startIndex += 1
else
exit while
end if
end while
function RefreshToken() as dynamic
m.loungeToken = invalid
return m.GetToken()
end function
if startIndex > 0
return chunk.Mid(startIndex)
function ProcessFrame(frame as string, messagesToSend as object) as void
commands = StringUtils.ParseJsonSafe(frame)
if not IsArray(commands)
LogTelemetryEvent({
level: "error"
message: "Lounge frame did not parse to a command array: " + frame.Left(256)
fingerprint: "lounge-unparseable-frame"
})
return
end if
return chunk
m.ProcessCommands(commands, messagesToSend)
end function
function ProcessCommands(commands as object, messagesToSend as object) as void
if not IsArray(commands)
return
end if
for each command in commands
if not IsArray(command) or command.Count() <> 2
continue for
@@ -646,12 +643,19 @@ class LoungeApi
if not response.IsSuccess()
isGone = response.StatusCode() = 410
unknownSid = response.StatusCode() = 400 and response.ErrorMessage().InStr("Unknown SID") <> -1
' TODO:P2 handle expired lounge id token
' expiredLoungeIdToken = response.StatusCode() = 401 and response.ErrorMessage().InStr("Expired lounge id token") <> -1
isKnownError = isGone or unknownSid
expiredToken = response.StatusCode() = 401 and response.ErrorMessage().InStr("Expired lounge id token") <> -1
isKnownError = isGone or unknownSid or expiredToken
if isKnownError
' NoTelemetry: the body carries a volatile token; logging it would fragment these.
LogErrorNoTelemetry(response.ErrorMessage())
if expiredToken
LogTelemetryEvent({
level: "warning"
message: "Lounge id token expired"
fingerprint: "lounge-expired-token"
})
end if
else
LogError(response.ErrorMessage())
end if
@@ -0,0 +1,242 @@
import "pkg:/components/Services/LoungeService/HttpChunkedDecoder.bs"
import "pkg:/components/Services/LoungeService/LoungeBytes.bs"
import "pkg:/components/Services/LoungeService/LoungeFraming.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/UrlUtils.bs"
' Server sends periodic noop keepalives, so no data for this long means a dead connection.
const LOUNGE_BACKCHANNEL_TIMEOUT_MS = 60000
const LOUNGE_BACKCHANNEL_BODY_COMPACT = 32768
const LOUNGE_BACKCHANNEL_MAX_REDIRECTS = 10
' Raw socket on plain HTTP: roUrlTransfer can't read a streaming body incrementally, and
' roStreamSocket has no TLS.
class LoungeBackchannel
public statusCode = 0
public closeReason = ""
public redirectTarget = ""
private socket
private decoder
private body
private bodyCursor = 0
private timer
private url = ""
private messagePort
private redirectCount = 0
function new()
m.timer = CreateObject("roTimespan")
end function
function Open(url as string, messagePort as object) as boolean
m.messagePort = messagePort
m.redirectCount = 0
m.redirectTarget = ""
return m.Connect(url)
end function
private function Connect(url as string) as boolean
' A redirect or reconnect reuses Connect; close the previous socket so it doesn't leak.
if m.socket <> invalid
m.socket.NotifyReadable(false)
m.socket.Close()
m.socket = invalid
end if
m.url = url
m.statusCode = 0
m.closeReason = ""
urlObject = UrlUtils.ParseUrl(url)
if urlObject.protocol <> "http"
m.closeReason = "invalid_protocol"
LogError("Lounge backchannel needs http, got:", urlObject.protocol)
return false
end if
portValue = urlObject.port
if portValue = invalid or portValue = ""
portValue = "80"
end if
address = CreateObject("roSocketAddress")
address.SetAddress(urlObject.host + ":" + portValue)
socket = CreateObject("roStreamSocket")
socket.SetSendToAddress(address)
if not socket.Connect()
m.closeReason = "connect_failed"
LogWarnNoTelemetry("Lounge backchannel connect failed:", urlObject.host)
return false
end if
CRLF = Chr(13) + Chr(10)
request = "GET " + urlObject.path + " HTTP/1.1" + CRLF
request += "Host: " + urlObject.host + CRLF
request += "Connection: keep-alive" + CRLF
request += CRLF
socket.SendStr(request)
socket.NotifyReadable(true)
socket.SetMessagePort(m.messagePort)
m.socket = socket
m.decoder = new HttpChunkedDecoder()
m.body = CreateObject("roByteArray")
m.bodyCursor = 0
m.timer.Mark()
LogInfo("Lounge backchannel open, socket", socket.GetID())
return true
end function
function IsOpen() as boolean
return m.socket <> invalid and m.closeReason = ""
end function
function Poll(socketEvents as object) as object
frames = []
if m.socket = invalid
return frames
end if
if not m.socket.IsConnected()
m.CloseWith("disconnected")
return frames
end if
if m.timer.TotalMilliseconds() > LOUNGE_BACKCHANNEL_TIMEOUT_MS
m.CloseWith("timeout")
return frames
end if
if not m.HasReadableEvent(socketEvents)
return frames
end if
received = m.decoder.Pump(m.socket, m.body)
if received = 0
m.CloseWith("eof")
return frames
else if received < 0
if not m.socket.eOK()
m.CloseWith("receive_error")
end if
return frames
end if
m.timer.Mark()
if m.decoder.IsRedirect()
return m.FollowRedirect()
end if
result = LoungeFraming.Extract(m.body, m.bodyCursor)
m.bodyCursor = result.nextPos
for each frame in result.frames
frames.Push(frame)
end for
m.CompactBody()
if m.decoder.IsError()
m.statusCode = m.decoder.statusCode
if m.decoder.errorReason <> HttpDecoderError.None
m.CloseWith(m.decoder.errorReason)
else
m.CloseWith("http_" + StrI(m.statusCode).Trim())
end if
else if m.decoder.IsDone()
m.CloseWith("complete")
end if
return frames
end function
function Close() as void
m.CloseWith("closed")
end function
private function HasReadableEvent(socketEvents as object) as boolean
id = m.socket.GetID()
for each event in socketEvents
if event.GetSocketID() = id
return true
end if
end for
return false
end function
private function CloseWith(reason as string) as void
if m.socket <> invalid
m.socket.NotifyReadable(false)
m.socket.Close()
m.socket = invalid
end if
if m.closeReason = ""
m.closeReason = reason
end if
end function
private function CompactBody() as void
if m.bodyCursor = 0
return
end if
if m.bodyCursor >= m.body.Count()
m.body.Clear()
else if m.bodyCursor >= LOUNGE_BACKCHANNEL_BODY_COMPACT
m.body = LoungeBytes.Tail(m.body, m.bodyCursor)
else
return
end if
m.bodyCursor = 0
end function
private function FollowRedirect() as object
frames = []
location = m.decoder.Location()
if not IsString(location) or location = ""
m.CloseWith("redirect_no_location")
return frames
end if
nextUrl = LoungeRedirect.Resolve(m.url, location)
m.redirectTarget = nextUrl
m.redirectCount += 1
if m.redirectCount > LOUNGE_BACKCHANNEL_MAX_REDIRECTS
m.CloseWith("redirect_limit")
return frames
end if
LogInfo("Lounge backchannel following redirect to", m.redirectTarget)
m.Connect(nextUrl)
return frames
end function
end class
namespace LoungeRedirect
' Force the target to plain HTTP - a raw socket has no TLS, so an https redirect is followed over http.
function Resolve(currentUrl as string, location as string) as string
if location.StartsWith("http://") or location.StartsWith("https://")
parts = UrlUtils.ParseUrl(location)
else
parts = UrlUtils.ParseUrl(currentUrl)
if not location.StartsWith("/")
location = "/" + location
end if
parts.path = location
end if
parts.protocol = "http"
if parts.port = "80" or parts.port = "443"
parts.port = invalid
end if
return UrlUtils.BuildUrlFromParts(parts)
end function
end namespace
@@ -0,0 +1,33 @@
import "pkg:/source/utils/ByteArrayUtils.bs"
namespace LoungeBytes
function RangeToString(bytes as object, fromIndex as integer, toIndex as integer) as string
return ByteArrayUtils.Slice(bytes, fromIndex, toIndex).ToAsciiString()
end function
function IndexOfCrlf(bytes as object, fromIndex as integer) as integer
last = bytes.Count() - 2
for i = fromIndex to last
if bytes[i] = 13 and bytes[i + 1] = 10
return i
end if
end for
return -1
end function
function IndexOfByte(bytes as object, fromIndex as integer, value as integer) as integer
last = bytes.Count() - 1
for i = fromIndex to last
if bytes[i] = value
return i
end if
end for
return -1
end function
function Tail(bytes as object, fromIndex as integer) as object
return ByteArrayUtils.Slice(bytes, fromIndex)
end function
end namespace
@@ -0,0 +1,43 @@
import "pkg:/components/Services/LoungeService/LoungeBytes.bs"
namespace LoungeFraming
' Frame = `<byteLength>\n<json>`, the length counted in BYTES. An incomplete trailing frame
' is left unconsumed (nextPos marks its start).
function Extract(body as object, startPos as integer) as object
frames = []
cursor = startPos
count = body.Count()
while true
while cursor < count and (body[cursor] = 13 or body[cursor] = 10)
cursor += 1
end while
if cursor >= count
exit while
end if
lf = LoungeBytes.IndexOfByte(body, cursor, 10)
if lf = -1
exit while
end if
frameLength = Int(Val(LoungeBytes.RangeToString(body, cursor, lf).Trim(), 10))
if frameLength <= 0
cursor = lf + 1
continue while
end if
dataStart = lf + 1
if count - dataStart < frameLength
exit while
end if
frames.Push(LoungeBytes.RangeToString(body, dataStart, dataStart + frameLength))
cursor = dataStart + frameLength
end while
return { frames: frames, nextPos: cursor }
end function
end namespace
@@ -48,6 +48,10 @@ function ExecuteJob() as void
response = request.Await()
if not response.IsSuccess()
if response.IsCancelled()
JobCancel()
return
end if
JobError(response.ErrorMessage())
return
end if
@@ -73,6 +73,7 @@ function LoungeServiceLoop() as void
m.top.shouldQuit = false
isOpen = false
reconnectAttempts = 0
outgoingLoungeMessages = []
portMessages = []
socketMessages = []
@@ -119,36 +120,52 @@ function LoungeServiceLoop() as void
outgoingLoungeMessagesResults = api.ProcessPendingOutgoingMessages()
if not isOpen
sleep(3000)
closeInfo = api.GetCloseInfo()
needsRebind = closeInfo.statusCode = 410 or closeInfo.statusCode = 400
needsTokenRefresh = closeInfo.statusCode = 401
unknownSid = false
' TODO:P2 move this check somewhere else
if (api.poller.status_code = 410) or (api.poller.status_code = 400 and ValidString(api.poller.status_text) = "Unknown SID")
api.poller.status_code = 0
unknownSid = true
for each result in outgoingLoungeMessagesResults
if result.status = 410 or (result.status = 400 and result.error.InStr("Unknown SID") <> -1)
needsRebind = true
else if result.status = 401 and result.error.InStr("Expired lounge id token") <> -1
needsTokenRefresh = true
end if
end for
LogDebug("Backchannel closed:", closeInfo.reason)
if IsActionableCloseFailure(closeInfo.reason, needsRebind, needsTokenRefresh)
message = "Lounge backchannel failure: " + closeInfo.reason
if not StringUtils.IsNullOrEmpty(closeInfo.target)
message += " -> " + closeInfo.target
end if
LogTelemetryEvent({
level: "warning"
message: message
fingerprint: "lounge-backchannel-" + closeInfo.reason
})
end if
if not unknownSid
for each result in outgoingLoungeMessagesResults
if result.status = 410 or (result.status = 400 and result.error.InStr("Unknown SID") <> -1)
unknownSid = true
exit for
end if
end for
sleep(ComputeReconnectBackoffMs(reconnectAttempts))
reconnectAttempts += 1
if needsTokenRefresh
LogWarnNoTelemetry("Lounge token expired, refreshing")
api.RefreshToken()
needsRebind = true
end if
if unknownSid
' We lost the session for some reason, so we need to rejoin the lounge
LogWarnNoTelemetry("Lost session, rejoining")
if needsRebind
LogWarnNoTelemetry("Rejoining lounge session")
if not api.GetSessionData()
Shutdown("Failed to rejoin session data")
return
end if
api.SaveCurrentLoungeData()
end if
api.FetchCommandsRpc(messagePort)
else
reconnectAttempts = 0
end if
end while
@@ -160,3 +177,26 @@ function Shutdown(reason as string)
m.top.unobserveField("outgoingMessages")
m.top.isRunning = false
end function
' Full jitter (random in [0, window)) avoids a fleet-wide thundering-herd reconnect.
function ComputeReconnectBackoffMs(attempts as integer) as integer
capped = attempts
if capped > 6
capped = 6
end if
windowMs = 1000 * (2 ^ capped)
if windowMs > 30000
windowMs = 30000
end if
return 500 + Int(Rnd(0) * windowMs)
end function
function IsActionableCloseFailure(reason as string, needsRebind as boolean, needsTokenRefresh as boolean) as boolean
if needsRebind or needsTokenRefresh
return false
end if
if reason = "complete" or reason = "eof" or reason = "closed" or reason = "timeout" or reason = "disconnected" or reason = ""
return false
end if
return true
end function
@@ -188,6 +188,16 @@ function MigrateExistingPreferences(userPrefs as object) as boolean
isDirty = true
end if
if userPrefs.__version = 7
homeScreenLayout = userPrefs["misc.home_screen_layout"]
if IsArray(homeScreenLayout)
homeScreenLayout.Push({ id: "trending_livestreams", enabled: true })
homeScreenLayout.Push({ id: "trending_gaming", enabled: true })
end if
userPrefs.__version = 8
isDirty = true
end if
' TODO:P2 handle case where saved preferences version is higher than current version (e.g. user downgraded)
#if DEBUG
@@ -5,7 +5,7 @@
user prefs saved need to be migrated. If the version is less than the
current version, a migration is needed.
-->
<field id="__version" type="integer" value="7" />
<field id="__version" type="integer" value="8" />
<field id="prefsModel" type="array" />
<field id="preferenceFields" type="assocarray" />
<function name="GetUserPreferences" />
@@ -13,6 +13,7 @@ function ExecuteJob() as void
preferencesNode = input.preferences
loungeServiceNode = input.loungeService
playletServerPort = input.playletServerPort
profilesService = input.profilesService
if JobIsCancelled()
JobCancel()
@@ -35,34 +36,40 @@ function ExecuteJob() as void
cancellation = JobGetCancellation()
if backend = "playlet"
visitorData = GetVisitorData(innertubeNode, cancellation)
if visitorData.cancel = true
sessionData = GetSessionData(innertubeNode, cancellation)
if sessionData.cancel = true
JobCancel()
return
end if
if visitorData.error <> invalid
JobError(visitorData.error)
if sessionData.error <> invalid
JobError(sessionData.error)
return
end if
accessToken = invalid
onBehalfOfUser = invalid
profileNode = invalid
authToken = invidiousNode.authToken
if authToken <> invalid and authToken.profileNode <> invalid and authToken.profileNode.type = "youtube" and not StringUtils.IsNullOrEmpty(authToken.token)
accessToken = authToken.token
onBehalfOfUser = authToken.activeIdentifyToken
profileNode = authToken.profileNode
end if
metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, {
"cancellation": cancellation
"credentialTransferToken": loungeServiceNode.credentialTransferToken
"visitorData": visitorData.visitorData
"visitorData": sessionData.visitorData
"livingRoomPoTokenId": sessionData.livingRoomPoTokenId
"accessToken": accessToken
"onBehalfOfUser": onBehalfOfUser
"profileNode": profileNode
"profilesService": profilesService
})
if IsAssociativeArray(metadata)
contentNode.addFields({
potAttached: ValidBool(metadata.potAttached)
potSource: ValidString(metadata.potSource)
loggedIn: not StringUtils.IsNullOrEmpty(accessToken)
})
end if
@@ -158,48 +165,42 @@ function ExecuteJob() as void
end if
end function
function GetVisitorData(innertubeNode as object, cancellation as object) as object
port = CreateObject("roMessagePort")
function GetSessionData(innertubeNode as object, cancellation as object) as object
sessionData = innertubeNode.sessionData
if SessionDataComplete(sessionData)
return sessionData
end if
MessagePortUtils.ObserveFieldScopedExSafe(innertubeNode, "visitorData", port)
port = CreateObject("roMessagePort")
MessagePortUtils.ObserveFieldScopedExSafe(innertubeNode, "sessionData", port)
CancellationUtils.ObserveCancellationScoped(cancellation, port)
visitorData = innertubeNode.visitorData
if not StringUtils.IsNullOrEmpty(visitorData)
innertubeNode.unobserveFieldScoped("visitorData")
CancellationUtils.UnobserveCancellationScoped(cancellation)
return {
visitorData: visitorData
}
end if
innertubeNode.requestVisitorData = true
innertubeNode.requestSessionData = true
message = wait(30000, port)
innertubeNode.unobserveFieldScoped("visitorData")
innertubeNode.unobserveFieldScoped("sessionData")
CancellationUtils.UnobserveCancellationScoped(cancellation)
if message <> invalid
if CancellationUtils.IsCancellationEvent(cancellation, message)
return {
cancel: true
}
end if
visitorData = message.getData()
if message <> invalid and CancellationUtils.IsCancellationEvent(cancellation, message)
return {
cancel: true
}
end if
if StringUtils.IsNullOrEmpty(visitorData)
return {
error: "Failed to get visitor data. Please try again later."
}
sessionData = innertubeNode.sessionData
if SessionDataComplete(sessionData)
return sessionData
end if
return {
visitorData: visitorData
error: "Failed to get session data. Please try again later."
}
end function
function SessionDataComplete(sessionData as object) as boolean
return IsAssociativeArray(sessionData) and not StringUtils.IsNullOrEmpty(sessionData.visitorData) and not StringUtils.IsNullOrEmpty(sessionData.livingRoomPoTokenId)
end function
function CreateStreamUrls(metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object
instance = service.GetInstance()
proxyVideos = preferences["invidious.proxy_videos"]
@@ -187,6 +187,7 @@ function StartVideoContentJob(videoContentNode as object)
preferences: m.top.preferences
loungeService: m.top.loungeService
playletServerPort: m.top.webServer.port
profilesService: m.top.profilesService
}
m.videoContentJob = JobSystem.CreateCallback(OnVideoContentJobDone)
@@ -10,6 +10,7 @@
<field id="invidious" type="node" bind="../../Invidious" />
<field id="webServer" type="node" bind="../../WebServer" />
<field id="loungeService" type="node" bind="../../LoungeService" />
<field id="profilesService" type="node" bind="../../ProfilesService" />
<field id="previousPlayer" type="node" />
<field id="minRect" type="rect2D" value="[834,460,426,240]" />
<field id="maxRect" type="rect2D" value="[0,0,1280,720]" />
@@ -737,7 +737,7 @@ function OnVideoState(event as object) as void
' reaching "playing" means any in-flight play-through seek has landed. Clear the settling flag before
' the freeze so a transport that deferred its pause now freezes this settled-playing video.
m.transport.MarkSeekSettled()
EnforceTransportFreeze()
EnforceTransportFreeze("OnVideoState")
' a keep-playing seek issued while paused has landed (the device auto-resumed): restore the pause.
if m.repauseAfterSeek
m.repauseAfterSeek = false
@@ -774,15 +774,23 @@ end function
' visible over the now-paused video. Called from OnVideoState (the change edge) and OnPosition (the net —
' OnPosition fires only while playing, so a transport-under-playing always trips it even with no state-change
' event). Re-pausing yields state=paused -> OnPosition stops -> no loop.
function EnforceTransportFreeze() as void
function EnforceTransportFreeze(source as string) as void
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)
if action = PlayerCoordinatorLogic.SafetyAction.Freeze
LogError("INV-D1 heal: re-pause; playing under transportMode=", m.transport.transportMode)
m.top.control = VideoControl.Pause
' 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.
m.top.autoplayAfterSeek = false
' 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.
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}`
LogErrorNoTelemetry(healInfo)
LogTelemetryEvent({
level: "error"
message: healInfo
fingerprint: ["INV-D1 heal", m.transport.transportMode, source]
})
else if action = PlayerCoordinatorLogic.SafetyAction.FinishEof
' 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.
@@ -835,7 +843,7 @@ function OnPosition(event as object) as void
posMs = Int(event.getData() * 1000)
m.transport.OnPosition(posMs)
ApplyTransport()
EnforceTransportFreeze() ' OnPosition only fires while playing, so it catches a transport auto-resumed with no state-change edge.
EnforceTransportFreeze("OnPosition") ' OnPosition only fires while playing, so it catches a transport auto-resumed with no state-change edge.
' EnforceTransportFreeze can finish playback (FinishEof at the end of content under a transport), which
' synchronously closes the player and drops m.sponsorblock. A closed player must run no more of the tick.
@@ -1075,6 +1083,7 @@ function StartVideoContentJob(videoContentNode as object)
preferences: m.top.preferences
loungeService: m.top.loungeService
playletServerPort: m.top.webServer.port
profilesService: m.top.profilesService
}
m.videoContentJob = JobSystem.CreateCallback(OnVideoContentJobDone)
@@ -1405,12 +1414,16 @@ function ReportVideoError(errorData as object, url as dynamic, urls as object, u
}]
end if
potAttached = "false"
potSource = "none"
loggedIn = "false"
content = m.top.content
if content <> invalid
if ValidBool(content.potAttached)
potAttached = "true"
end if
if not StringUtils.IsNullOrEmpty(content.potSource)
potSource = content.potSource
end if
if ValidBool(content.loggedIn)
loggedIn = "true"
end if
@@ -1425,10 +1438,12 @@ function ReportVideoError(errorData as object, url as dynamic, urls as object, u
"Urls: " + FormatJson(urls)
`Url index: ${urlIndex}`
`pot_attached: ${potAttached}`
`pot_source: ${potSource}`
`logged_in: ${loggedIn}`
].Join(Chr(10))
errorData.fingerprint.Push(shownInDialog)
errorData.fingerprint.Push(potAttached)
errorData.fingerprint.Push(potSource)
errorData.fingerprint.Push(loggedIn)
if shownInDialog
level = "error"
@@ -24,6 +24,7 @@
<field id="invidious" type="node" bind="../../Invidious" />
<field id="webServer" type="node" bind="../../WebServer" />
<field id="loungeService" type="node" bind="../../LoungeService" />
<field id="profilesService" type="node" bind="../../ProfilesService" />
<field id="previousPlayer" type="node" />
<!-- PiP rects: minRect/maxRect drive width/height/translation. -->
<field id="minRect" type="rect2D" value="[834,460,426,240]" />
@@ -21,12 +21,18 @@ function ExecuteJob() as void
backend = preferencesNode["backend.selected"]
visitorData = ""
sessionData = innertubeNode.sessionData
if IsAssociativeArray(sessionData)
visitorData = ValidString(sessionData.visitorData)
end if
requestOptions = {
cacheSeconds: 8640000 ' 100 days
cancellation: cancellation
tryCount: 1
fetchNext: false
visitorData: innertubeNode.visitorData
visitorData: visitorData
}
' TODO:P1: Use InnertubeService.GetVideoInfoBatched with an array instead of loading each video individually
@@ -1,7 +1,9 @@
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:/source/services/HttpClient.bs"
import "pkg:/source/utils/Types.bs"
namespace Http
@@ -14,21 +16,37 @@ namespace Http
m.profilesService = server.sceneNodes.profilesService
end function
@get("/api/innertube/session")
function GetSessionData(context as object) as object
@get("/api/innertube/potoken")
function GetPoToken(context as object) as object
response = context.response
sessionData = {
"timestamp": m.innertube.timestamp
"visitorData": m.innertube.visitorData
}
identity = ""
sessionData = m.innertube.sessionData
if IsAssociativeArray(sessionData)
identity = ValidString(sessionData.livingRoomPoTokenId)
end if
response.Json(sessionData)
if StringUtils.IsNullOrEmpty(identity)
response.Default(503, "No current identity")
return true
end if
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
end function
@post("/api/innertube/session")
function SetSessionData(context as object) as object
@post("/api/innertube/potoken")
function SetPoToken(context as object) as object
request = context.request
response = context.response
@@ -37,24 +55,49 @@ namespace Http
response.Default(400, "Invalid payload")
return true
end if
if not IsInt(payload.timestamp)
response.Default(400, "Invalid timestamp")
if StringUtils.IsNullOrEmpty(payload.poToken)
response.Default(400, "Invalid poToken")
return true
end if
if StringUtils.IsNullOrEmpty(payload.visitorData)
response.Default(400, "Invalid visitorData")
if StringUtils.IsNullOrEmpty(payload.identity)
response.Default(400, "Invalid identity")
return true
end if
Innertube.SaveSessionDataToRegistry({
"timestamp": payload.timestamp
"visitorData": payload.visitorData
})
if not IsInt(payload.mintedAt) or not IsInt(payload.expiresAt)
response.Default(400, "Invalid mintedAt/expiresAt")
return true
end if
m.innertube.timestamp = payload.timestamp
m.innertube.visitorData = payload.visitorData
response.Default(204, "Session data updated successfully")
identity = ""
sessionData = m.innertube.sessionData
if IsAssociativeArray(sessionData)
identity = ValidString(sessionData.livingRoomPoTokenId)
end if
if StringUtils.IsNullOrEmpty(identity)
response.Default(503, "No current identity")
return true
end if
' Reject identities other than the device's current one (guards the shared registry).
if payload.identity <> identity
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
end function
@@ -70,8 +113,8 @@ namespace Http
end if
requestHeaders = requestArgs.Headers
' Ytjs can send requests without specifying a User-Agent.
' In this case, Roku would use its default User-Agent.
' Proxied web-app requests (e.g. BotGuard attestation) may omit a
' User-Agent; fall back to ours instead of Roku's default.
if StringUtils.IsNullOrEmpty(requestHeaders["User-Agent"])
requestHeaders["User-Agent"] = VIDEO_PLAYER_USER_AGENT
end if
@@ -120,7 +163,7 @@ namespace Http
if currentProfile <> invalid and currentProfile.type = "youtube"
options["accessToken"] = currentProfile.accessToken
else
options["visitorData"] = m.innertube.visitorData
options["visitorData"] = m.innertube.sessionData.visitorData
end if
drmResponse = InnertubeService.GetDrmLicense(options)
@@ -237,6 +237,48 @@ namespace Http
return true
end function
@get("/playlet-invidious-backend/api/v1/trending")
function GetTrending(context as object) as boolean
request = context.request
response = context.response
raw = request.query.raw <> invalid
options = {
"disableShorts": m.preferences["content_feed.disable_shorts"]
raw: raw
type: request.query.type
}
result = InnertubeService.GetTrending(options)
if raw
response.Json(result)
return true
end if
if result.error <> invalid
response.Json(result)
response.http_code = 500
return true
end if
if not IsArray(result.feeds) or result.feeds.Count() = 0
response.Json({
"error": "Failed to get trending feed"
})
response.http_code = 500
return true
end if
response.Json(ValidArray(result.feeds[0].items))
if result.DoesExist("cache-control")
response.headers["cache-control"] = result["cache-control"]
end if
return true
end function
@get("/playlet-invidious-backend/api/v1/popular")
function GetPopular(context as object) as boolean
request = context.request
@@ -548,9 +590,15 @@ namespace Http
raw = request.query.raw <> invalid
videoInfoBatched = request.query.video_info_batched <> invalid
visitorData = ""
sessionData = m.innertube.sessionData
if IsAssociativeArray(sessionData)
visitorData = ValidString(sessionData.visitorData)
end if
options = {
"raw": raw
"visitorData": m.innertube.visitorData
"visitorData": visitorData
}
if videoInfoBatched
@@ -56,10 +56,16 @@ namespace Http
return true
end function
function Default(errcode as integer, reason as string)
errname = m.server.utils.HttpTitle(errcode)
function Default(errcode as integer, reason as string) as void
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>
<h1>${errname}</h1>
${reason}
@@ -14,6 +14,26 @@
apiType: Invidious
endpoint: auth_recommended
- title: Trending - Live
id: trending_livestreams
feedSources:
- id: inv_trending_livestreams
title: Trending - Live
apiType: Invidious
endpoint: trending
queryParams:
type: Livestreams
- title: Trending - Gaming
id: trending_gaming
feedSources:
- id: inv_trending_gaming
title: Trending - Gaming
apiType: Invidious
endpoint: trending
queryParams:
type: Gaming
- title: Popular
id: popular
feedSources:
@@ -1,3 +1,16 @@
trending:
title: Trending
url: /api/v1/trending
cacheSeconds: 21600 # 6 hours
queryParams:
type:
type:
- Livestreams
- Gaming
region:
type: "#ISO3166"
default: GetUserCountryCode
popular:
title: Popular
url: /api/v1/popular
+22
View File
@@ -265,6 +265,14 @@
id: "watch_history",
enabled: true,
},
{
id: "trending_livestreams",
enabled: true,
},
{
id: "trending_gaming",
enabled: true,
},
],
visibility: "tv",
rokuComponent: "EditHomeScreenControl",
@@ -311,6 +319,20 @@
visibility: "tv",
rokuComponent: "ClearCacheControl",
},
{
displayText: "Mint PoToken",
key: "dev.mint_potoken",
description: "Mint a PoToken for the current identity.",
visibility: "off",
svelteComponent: "MintPoTokenControl",
},
{
displayText: "Clear PoTokens",
key: "dev.clear_potokens",
description: "Clear all stored PoTokens.",
visibility: "off",
svelteComponent: "ClearPoTokensControl",
},
{
displayText: "Enable Diagnostics",
key: "dev.diagnostics.enabled",
@@ -312,6 +312,14 @@
<source>Watch history</source>
<translation>Wiedergabeverlauf</translation>
</message>
<message>
<source>Trending - Live</source>
<translation>Trends - Live</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Trends - Gaming</translation>
</message>
<message>
<source>Popular</source>
<translation>Populär</translation>
@@ -88,6 +88,14 @@
<source>Watch history</source>
<translation>Watch history</translation>
</message>
<message>
<source>Trending - Live</source>
<translation>Trending - Live</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Trending - Gaming</translation>
</message>
<message>
<source>Popular</source>
<translation>Popular</translation>
@@ -1380,6 +1388,18 @@
<source>Cache cleared.</source>
<translation>Cache cleared.</translation>
</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>
<source>Enable Diagnostics</source>
<translation>Enable Diagnostics</translation>
@@ -80,6 +80,14 @@
<source>Watch history</source>
<translation>Ver el historial</translation>
</message>
<message>
<source>Trending - Live</source>
<translation>Tendencias - En directo</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Tendencias - Juegos</translation>
</message>
<message>
<source>Popular</source>
<translation>Popular</translation>
@@ -308,6 +308,14 @@
<source>Test instance</source>
<translation>Probar Instancia</translation>
</message>
<message>
<source>Trending - Live</source>
<translation>Tendencias - En vivo</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Tendencias - Videojuegos</translation>
</message>
<message>
<source>Popular</source>
<translation>Popular</translation>
@@ -76,6 +76,14 @@
<source>Watch history</source>
<translation>Historique</translation>
</message>
<message>
<source>Trending - Live</source>
<translation>Tendances - En direct</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Tendances - Jeux vidéo</translation>
</message>
<message>
<source>Popular</source>
<translation>Populaire</translation>
@@ -140,6 +140,14 @@
<source>Watch history</source>
<translation>Histórico de assistidos</translation>
</message>
<message>
<source>Trending - Live</source>
<translation>Em alta - Ao vivo</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Em alta - Jogos</translation>
</message>
<message>
<source>Popular</source>
<translation>Popular</translation>
+2 -2
View File
@@ -2,8 +2,8 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=47
build_version=00004
minor_version=48
build_version=00000
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
@@ -0,0 +1,176 @@
import "pkg:/components/Services/LoungeService/HttpChunkedDecoder.bs"
namespace Tests
@suite
class HttpChunkedDecoderTests extends Rooibos.BaseTestSuite
@describe("HttpChunkedDecoder.Pump")
@it("decodes a single-chunk 200 response and reaches Done")
function singleChunk()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello")
m.assertEqual(r.decoder.statusCode, 200)
m.assertTrue(r.decoder.IsDone())
m.assertFalse(r.decoder.IsError())
end function
@it("concatenates multiple chunks into one body")
function multipleChunks()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello world")
m.assertTrue(r.decoder.IsDone())
end function
' A chunk boundary need not align with a socket read: the same response delivered one byte
' per read must reassemble identically.
@it("reassembles a response delivered one byte per socket read")
function bytewise()
r = m.Drive(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n`, 1)
m.assertEqual(r.body, "hello world")
m.assertTrue(r.decoder.IsDone())
end function
@it("parses a hex chunk size greater than 9")
function hexChunkSize()
payload = "0123456789abcdef" ' 16 bytes -> chunk size "10" in hex
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n10\r\n` + payload + `\r\n0\r\n\r\n`)
m.assertEqual(r.body, payload)
end function
@it("ignores chunk-size extensions after a semicolon")
function chunkExtensions()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5;foo=bar\r\nhello\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello")
end function
@it("extracts a chunk byte-exactly when the body holds multi-byte UTF-8")
function utf8Chunk()
' "café" is 4 characters but 5 UTF-8 bytes; the chunk size counts bytes.
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\ncafé\r\n0\r\n\r\n`)
m.assertEqual(r.body, "café")
m.assertTrue(r.decoder.IsDone())
end function
@it("flags a non-200 status as an error carrying the code")
@params("410 Gone", 410)
@params("400 Bad Request", 400)
@params("401 Unauthorized", 401)
function non200(statusLine as string, expectedCode as integer)
r = m.DecodeWhole(`HTTP/1.1 ` + statusLine + `\r\n\r\n`)
m.assertTrue(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.decoder.statusCode, expectedCode)
m.assertEqual(r.decoder.errorReason, "", "an HTTP status error is fingerprinted by code, not a slug")
end function
@it("surfaces a 3xx as a redirect carrying the Location, not an error")
@params("301 Moved Permanently", 301)
@params("302 Found", 302)
@params("303 See Other", 303)
@params("307 Temporary Redirect", 307)
@params("308 Permanent Redirect", 308)
function redirect(statusLine as string, expectedCode as integer)
r = m.DecodeWhole(`HTTP/1.1 ` + statusLine + `\r\nLocation: https://rr4.youtube.com/api/lounge/bc/bind?SID=x\r\n\r\n`)
m.assertTrue(r.decoder.IsRedirect())
m.assertFalse(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.decoder.statusCode, expectedCode)
m.assertEqual(r.decoder.Location(), "https://rr4.youtube.com/api/lounge/bc/bind?SID=x")
end function
@it("treats an HTTP/1.0 307 as a redirect")
function redirectHttp10()
r = m.DecodeWhole(`HTTP/1.0 307 Temporary Redirect\r\nLocation: http://portal.example/login\r\n\r\n`)
m.assertTrue(r.decoder.IsRedirect())
m.assertFalse(r.decoder.IsError())
m.assertEqual(r.decoder.Location(), "http://portal.example/login")
end function
@it("flags a 200 response that is not chunked as an error rather than crashing")
function nonChunked()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "unsupported_encoding")
end function
@it("flags a malformed status line with a stable error reason")
function malformedStatus()
r = m.DecodeWhole(`HELLO not http\r\n\r\n`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "malformed_status")
end function
@it("waits for more bytes when the status line is incomplete")
function partialStatus()
r = m.Drive("HTTP/1.1 20", 0)
m.assertFalse(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.body, "")
end function
@it("errors on a chunk size that overflows a 32-bit int")
function chunkOverflow()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nFFFFFFFF\r\nx`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "chunk_overflow")
end function
function DecodeWhole(response as string) as object
return m.Drive(response, 0)
end function
function Drive(response as string, readSize as integer) as object
decoder = new HttpChunkedDecoder()
socket = new LoungeMockSocket(m.Bytes(response), readSize)
out = CreateObject("roByteArray")
while socket.GetCountRcvBuf() > 0 and not decoder.IsDone() and not decoder.IsError() and not decoder.IsRedirect()
decoder.Pump(socket, out)
end while
return { decoder: decoder, body: out.ToAsciiString() }
end function
function Bytes(text as string) as object
bytes = CreateObject("roByteArray")
bytes.FromAsciiString(text)
return bytes
end function
end class
' Feeds `bytes` to the decoder, at most `readSize` per Receive (0 = all at once), so a test
' can drive fragmented reads.
class LoungeMockSocket
private data
private readPos = 0
private readSize = 0
function new(bytes as object, readSize as integer)
m.data = bytes
m.readSize = readSize
end function
function GetCountRcvBuf() as integer
remaining = m.data.Count() - m.readPos
if remaining <= 0
return 0
end if
if m.readSize > 0 and m.readSize < remaining
return m.readSize
end if
return remaining
end function
function Receive(ba as object, index as integer, length as integer) as integer
count = 0
while count < length and m.readPos < m.data.Count()
ba[index + count] = m.data[m.readPos]
count += 1
m.readPos += 1
end while
return count
end function
end class
end namespace
@@ -0,0 +1,59 @@
import "pkg:/components/Services/LoungeService/LoungeBytes.bs"
namespace Tests
@suite
class LoungeBytesTests extends Rooibos.BaseTestSuite
@describe("LoungeBytes byte helpers")
@it("converts a byte range to a string, byte-exact across a UTF-8 boundary")
function rangeToString()
' "Xcafé" where é is 2 bytes; extract "café" = bytes [1, end).
cafe = "caf" + m.Utf8(&hC3, &hA9)
bytes = m.Bytes("X" + cafe)
m.assertEqual(LoungeBytes.RangeToString(bytes, 1, bytes.Count()), cafe)
end function
@it("finds the first CRLF at or after a position")
function indexOfCrlf()
bytes = m.Bytes(`ab\r\ncd\r\n`)
m.assertEqual(LoungeBytes.IndexOfCrlf(bytes, 0), 2)
m.assertEqual(LoungeBytes.IndexOfCrlf(bytes, 3), 6)
end function
@it("returns -1 when no CRLF is present")
function indexOfCrlfMissing()
m.assertEqual(LoungeBytes.IndexOfCrlf(m.Bytes("abc"), 0), -1)
end function
@it("finds the first byte value at or after a position, or -1")
function indexOfByte()
bytes = m.Bytes("a,b,c")
m.assertEqual(LoungeBytes.IndexOfByte(bytes, 0, Asc(",")), 1)
m.assertEqual(LoungeBytes.IndexOfByte(bytes, 2, Asc(",")), 3)
m.assertEqual(LoungeBytes.IndexOfByte(bytes, 0, Asc("z")), -1)
end function
@it("returns a tail copy from a position to the end")
function tail()
tail = LoungeBytes.Tail(m.Bytes("hello"), 2)
m.assertEqual(tail.ToAsciiString(), "llo")
end function
function Bytes(text as string) as object
bytes = CreateObject("roByteArray")
bytes.FromAsciiString(text)
return bytes
end function
function Utf8(b1 as integer, b2 as integer) as string
bytes = CreateObject("roByteArray")
bytes.Push(b1)
bytes.Push(b2)
return bytes.ToAsciiString()
end function
end class
end namespace
@@ -0,0 +1,105 @@
import "pkg:/components/Services/LoungeService/LoungeFraming.bs"
namespace Tests
@suite
class LoungeFramingTests extends Rooibos.BaseTestSuite
@describe("LoungeFraming.Extract")
@it("extracts a single complete frame and reports the consumed position")
function singleFrame()
result = LoungeFraming.Extract(m.Bytes(`5\nhello`), 0)
m.assertEqual(result.frames.Count(), 1)
m.assertEqual(result.frames[0], "hello")
m.assertEqual(result.nextPos, 7)
end function
@it("extracts multiple consecutive frames in one pass")
function multipleFrames()
result = LoungeFraming.Extract(m.Bytes(`5\nhello3\nfoo`), 0)
m.assertEqual(result.frames, ["hello", "foo"])
end function
@it("skips leading CR/LF between frames")
function leadingNewlines()
result = LoungeFraming.Extract(m.Bytes(`\r\n5\nhello`), 0)
m.assertEqual(result.frames, ["hello"])
end function
' The bug that motivated the rewrite: the length prefix is a BYTE count, but the old
' parser sliced with character-based string ops, so any multi-byte payload shifted every
' subsequent frame. A char-based slice of 5 from "café2..." keeps 5 characters ("café2")
' and desyncs; a byte-accurate slice keeps "café" (5 bytes) and frame 2 still lines up.
@it("slices payloads by byte length so multi-byte UTF-8 does not desync the stream")
function utf8ByteAccurate()
cafe = "caf" + m.Utf8(&hC3, &hA9) ' é is 2 bytes -> "café" is 5 bytes, 4 characters
body = m.Bytes(Str(m.ByteLen(cafe)).Trim() + Chr(10) + cafe + Str(m.ByteLen("ok")).Trim() + Chr(10) + "ok")
result = LoungeFraming.Extract(body, 0)
m.assertEqual(result.frames.Count(), 2, "a character-based slice would mis-split frame 2")
m.assertEqual(result.frames[0], cafe)
m.assertEqual(result.frames[1], "ok")
end function
@it("leaves a whole frame unconsumed when its payload has not fully arrived")
function partialPayload()
result = LoungeFraming.Extract(m.Bytes(`5\nhel`), 0)
m.assertEqual(result.frames.Count(), 0)
m.assertEqual(result.nextPos, 0)
end function
@it("consumes complete frames but retains an incomplete trailing frame")
function partialAfterComplete()
result = LoungeFraming.Extract(m.Bytes(`5\nhello2\nh`), 0)
m.assertEqual(result.frames, ["hello"])
m.assertEqual(result.nextPos, 7)
end function
@it("waits when the length line is not yet terminated")
function partialLengthLine()
result = LoungeFraming.Extract(m.Bytes("12"), 0)
m.assertEqual(result.frames.Count(), 0)
m.assertEqual(result.nextPos, 0)
end function
@it("resumes extraction from a caller-supplied position")
function resumeFromPosition()
' Index 7 is the start of the second frame ("3\nfoo").
result = LoungeFraming.Extract(m.Bytes(`5\nhello3\nfoo`), 7)
m.assertEqual(result.frames, ["foo"])
end function
@it("skips a non-positive length line instead of stalling")
function malformedLength()
result = LoungeFraming.Extract(m.Bytes(`0\n5\nhello`), 0)
m.assertEqual(result.frames, ["hello"])
end function
@it("returns no frames for an empty body")
function emptyBody()
result = LoungeFraming.Extract(m.Bytes(""), 0)
m.assertEqual(result.frames.Count(), 0)
m.assertEqual(result.nextPos, 0)
end function
function Bytes(text as string) as object
bytes = CreateObject("roByteArray")
bytes.FromAsciiString(text)
return bytes
end function
function ByteLen(text as string) as integer
return m.Bytes(text).Count()
end function
function Utf8(b1 as integer, b2 as integer) as string
bytes = CreateObject("roByteArray")
bytes.Push(b1)
bytes.Push(b2)
return bytes.ToAsciiString()
end function
end class
end namespace
@@ -0,0 +1,44 @@
import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs"
namespace Tests
@suite
class LoungeRedirectTests extends Rooibos.BaseTestSuite
@describe("LoungeRedirect.Resolve")
@it("downgrades an https target to http, keeping host, path and query")
function downgradesHttps()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind?SID=a", "https://rr4.youtube.com/api/lounge/bc/bind?SID=a&gsessionid=b")
m.assertEqual(resolved, "http://rr4.youtube.com/api/lounge/bc/bind?SID=a&gsessionid=b")
end function
@it("keeps an http target as-is")
function keepsHttp()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/x", "http://other.host/y?z=1")
m.assertEqual(resolved, "http://other.host/y?z=1")
end function
@it("drops a default 80 or 443 port")
@params("https://host:443/p", "http://host/p")
@params("http://host:80/p", "http://host/p")
@params("http://host:8080/p", "http://host:8080/p")
function dropsDefaultPort(location as string, expected as string)
m.assertEqual(LoungeRedirect.Resolve("http://www.youtube.com/x", location), expected)
end function
@it("resolves a root-relative Location against the current host")
function relativeLocation()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind?SID=a", "/api/lounge/bc/bind?SID=a&AID=5")
m.assertEqual(resolved, "http://www.youtube.com/api/lounge/bc/bind?SID=a&AID=5")
end function
@it("prefixes a slash onto a bare relative Location")
function bareRelativeLocation()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind", "elsewhere?x=1")
m.assertEqual(resolved, "http://www.youtube.com/elsewhere?x=1")
end function
end class
end namespace
@@ -485,7 +485,7 @@ namespace HttpClient
sleep(backoffMs)
response = m.AwaitInternal()
if response.IsSuccess() or response.IsTimedOut() or response.IsCancelled() or response.StatusCode() < 500
if response.IsTimedOut() or response.IsCancelled() or (response.StatusCode() >= 200 and response.StatusCode() < 500)
return response
end if
triesLeft -= 1
@@ -0,0 +1,37 @@
import "pkg:/components/Services/Innertube/SessionData.bs"
namespace Tests
@suite
class InnertubeExtractEscapedJsonStringTests extends Rooibos.BaseTestSuite
@describe("Innertube.ExtractEscapedJsonString")
@it("extracts a plain value")
function plain()
text = `noise "visitorData":"AbCd123" noise`
m.assertEqual(Innertube.ExtractEscapedJsonString(text, "visitorData"), "AbCd123")
end function
@it("decodes the escaped = padding")
function decodesPadding()
bs = Chr(92)
text = `"LIVING_ROOM_PO_TOKEN_ID":"THWY0ox3FA4${bs}u003d"`
m.assertEqual(Innertube.ExtractEscapedJsonString(text, "LIVING_ROOM_PO_TOKEN_ID"), "THWY0ox3FA4=")
end function
@it("decodes any escape, not just the padding")
function decodesAnyEscape()
bs = Chr(92)
text = `"key":"a${bs}u002fb"`
m.assertEqual(Innertube.ExtractEscapedJsonString(text, "key"), "a/b")
end function
@it("returns empty string when the key is absent")
function keyAbsent()
m.assertEqual(Innertube.ExtractEscapedJsonString(`"other":"x"`, "visitorData"), "")
end function
end class
end namespace
+5
View File
@@ -41,6 +41,8 @@ namespace Locale
Recommended = "Recommended"
Playlists = "Playlists"
WatchHistory = "Watch history"
TrendingLive = "Trending - Live"
TrendingGaming = "Trending - Gaming"
Popular = "Popular"
Videos = "Videos"
Shorts = "Shorts"
@@ -310,6 +312,9 @@ namespace Locale
ClearCache = "Clear cache"
ClearCacheDescription = "Clear cache from cachefs: and tmp:"
CacheCleared = "Cache cleared."
ClearPoTokens = "Clear PoTokens"
ClearPoTokensDescription = "Clear all stored PoTokens."
PoTokensCleared = "PoTokens cleared."
EnableDiagnostics = "Enable Diagnostics"
EnableDiagnosticsDescription = "Help improve Playlet by enabling diagnostics. This will send anonymous diagnotics data to the developer."
end enum
@@ -11,6 +11,7 @@ namespace RegistryUtils
const MESSAGES = "messages"
const INNERTUBE_SESSION_DATA = "innertube_session_data"
const INNERTUBE_POTOKENS = "innertube_potokens"
const LAST_LOUNGE_DATA = "last_lounge_data"
' "invidious_instances" is deprecated, but we keep for migration purposes
+69 -35
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-web",
"version": "0.47.4",
"version": "0.48.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet-web",
"version": "0.47.4",
"version": "0.48.0",
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^7.1.2",
"@tailwindcss/postcss": "^4.3.1",
@@ -29,8 +29,7 @@
"tslib": "^2.8.1",
"typescript": "^5.9.3",
"vite": "^8.0.16",
"vite-plugin-compression": "^0.5.1",
"youtubei.js": "^17.0.1"
"vite-plugin-compression": "^0.5.1"
}
},
"node_modules/@alloc/quick-lru": {
@@ -1578,13 +1577,6 @@
"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": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
@@ -2236,6 +2228,72 @@
"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": {
"version": "4.3.1",
"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"
}
},
"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": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
@@ -4617,20 +4665,6 @@
"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": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.47.4",
"version": "0.48.0",
"type": "module",
"scripts": {
"dev": "vite",
@@ -30,7 +30,6 @@
"tslib": "^2.8.1",
"typescript": "^5.9.3",
"vite": "^8.0.16",
"vite-plugin-compression": "^0.5.1",
"youtubei.js": "^17.0.1"
"vite-plugin-compression": "^0.5.1"
}
}
+3
View File
@@ -24,6 +24,7 @@
import BookmarksScreen from "lib/Screens/BookmarksScreen.svelte";
import RemoteControlScreen from "lib/Screens/RemoteControlScreen.svelte";
import { fetchLocale } from "lib/Api/Locale";
import Toast from "lib/Toast.svelte";
onMount(() => {
PlayletApi.getState().then((value) => {
@@ -93,3 +94,5 @@
</div>
<BottomNavigation />
</main>
<Toast />
+21
View File
@@ -164,6 +164,27 @@ export class PlayletApi {
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() {
const response = await fetch(`${PlayletApi.host()}/api/bookmarks/feeds`);
return await response.json();
+214
View File
@@ -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.
static async ensureDevicePoToken(): 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 (!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) };
}
}
}
-411
View File
@@ -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()}
>{$translate("Mint PoToken")}</button
>
</div>
@@ -7,6 +7,8 @@
import StringControl from "lib/Screens/Settings/SettingControls/StringControl.svelte";
import NumberControl from "./SettingControls/NumberControl.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 SponsorBlockCategoriesControl from "./SettingControls/SponsorBlockCategoriesControl.svelte";
import { translate } from "lib/Stores";
@@ -34,6 +36,8 @@
const customComponents = {
ClearSearchHistoryControl,
ClearCacheControl,
ClearPoTokensControl,
MintPoTokenControl,
EditHomeScreenControl,
PlayletLibVersionControl,
EditQualityControl,
+22
View File
@@ -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>
+25
View File
@@ -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 VideoStartAt from "./VideoStartAt.svelte";
import VideoThumbnail from "./VideoThumbnail.svelte";
import { YoutubeJs } from "lib/Api/YoutubeJs";
export let videoId: 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() {
try {
const videoInfo = getVideoInfo();
@@ -168,9 +147,6 @@
<button class="btn join-item hover:btn-accent" on:click={playOnTv}>
{$translate("Play on %1").replace("%1", tvName)}
</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}>
{$translate("Queue on %1").replace("%1", tvName)}
</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() {
const result = await PoTokenMinter.ensureDevicePoToken();
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;
}