Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c75903d11 | ||
|
|
e2e3e3099f | ||
|
|
3381d19b53 | ||
|
|
0f2a1a2b16 | ||
|
|
38bfa1a102 | ||
|
|
fbb4a45ce5 | ||
|
|
8dd24ddb43 | ||
|
|
fbf8e0a499 | ||
|
|
c81f5cd9e1 | ||
|
|
17ff6b940b | ||
|
|
2e1a4c9ea3 | ||
|
|
bd01da01e6 | ||
|
|
333553790f | ||
|
|
422d58508e |
No files matched your search
@@ -5,6 +5,18 @@ 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
|
||||
|
||||
@@ -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)
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "playlet",
|
||||
"version": "0.47.5",
|
||||
"version": "0.48.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "playlet",
|
||||
"version": "0.47.5",
|
||||
"version": "0.48.0",
|
||||
"hasInstallScript": true,
|
||||
"devDependencies": {
|
||||
"@rokucommunity/bslint": "^0.8.44",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "playlet",
|
||||
"version": "0.47.5",
|
||||
"version": "0.48.0",
|
||||
"description": "Unofficial YouTube client for Roku",
|
||||
"devDependencies": {
|
||||
"@rokucommunity/bslint": "^0.8.44",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "playlet-app",
|
||||
"version": "0.47.5",
|
||||
"version": "0.48.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "playlet-app",
|
||||
"version": "0.47.5"
|
||||
"version": "0.48.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "playlet-app",
|
||||
"version": "0.47.5",
|
||||
"version": "0.48.0",
|
||||
"description": "Unofficial YouTube client for Roku",
|
||||
"scripts": {
|
||||
"prebuild": "node ../tools/rm.js ../build/playlet-app",
|
||||
|
||||
@@ -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=00005
|
||||
minor_version=48
|
||||
build_version=00000
|
||||
|
||||
ui_resolutions=hd
|
||||
uri_resolution_autosub=$$RES$$,480p,720p,1080p
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "playlet-lib",
|
||||
"version": "0.47.5",
|
||||
"version": "0.48.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "playlet-lib",
|
||||
"version": "0.47.5"
|
||||
"version": "0.48.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "playlet-lib",
|
||||
"version": "0.47.5",
|
||||
"version": "0.48.0",
|
||||
"description": "Unofficial YouTube client for Roku",
|
||||
"scripts": {
|
||||
"prebuild": "node ../tools/rm.js ../build/playlet-lib",
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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,9 @@
|
||||
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"
|
||||
@@ -12,7 +14,6 @@ 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")
|
||||
@@ -54,7 +55,7 @@ namespace Innertube
|
||||
"contentCheckOk": true
|
||||
}
|
||||
|
||||
signatureTimestamp = GetSignatureTimestamp(cancellation)
|
||||
signatureTimestamp = OptionUtils.Get(options, "signatureTimestamp")
|
||||
if signatureTimestamp <> invalid
|
||||
payload["playbackContext"]["contentPlaybackContext"]["signatureTimestamp"] = signatureTimestamp
|
||||
end if
|
||||
@@ -190,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
|
||||
@@ -496,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()
|
||||
@@ -514,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
|
||||
@@ -743,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,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
|
||||
@@ -24,15 +24,23 @@ namespace Innertube
|
||||
function RequestTvClientData(cancellation = invalid as object) as object
|
||||
visitorData = ""
|
||||
livingRoomPoTokenId = ""
|
||||
visitorDataResponse = ""
|
||||
livingRoomPoTokenIdResponse = ""
|
||||
|
||||
for attempt = 1 to TV_CLIENT_DATA_MAX_ATTEMPTS
|
||||
text = FetchTvClientPage(cancellation)
|
||||
if text <> invalid
|
||||
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
|
||||
@@ -47,10 +55,10 @@ namespace Innertube
|
||||
end for
|
||||
|
||||
if StringUtils.IsNullOrEmpty(visitorData)
|
||||
LogError("Could not extract visitorData from tv client data")
|
||||
ReportTvClientDataFailure("Could not extract visitorData from tv client data", visitorDataResponse)
|
||||
end if
|
||||
if StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
|
||||
LogError("Could not extract livingRoomPoTokenId from tv client data")
|
||||
ReportTvClientDataFailure("Could not extract livingRoomPoTokenId from tv client data", livingRoomPoTokenIdResponse)
|
||||
end if
|
||||
if StringUtils.IsNullOrEmpty(visitorData) and StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
|
||||
return invalid
|
||||
@@ -63,6 +71,22 @@ namespace Innertube
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -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
|
||||
+4
@@ -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" />
|
||||
|
||||
@@ -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.
|
||||
|
||||
+42
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -265,6 +265,14 @@
|
||||
id: "watch_history",
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: "trending_livestreams",
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: "trending_gaming",
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
visibility: "tv",
|
||||
rokuComponent: "EditHomeScreenControl",
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,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=00005
|
||||
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
|
||||
|
||||
@@ -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"
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "playlet-web",
|
||||
"version": "0.47.5",
|
||||
"version": "0.48.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "playlet-web",
|
||||
"version": "0.47.5",
|
||||
"version": "0.48.0",
|
||||
"devDependencies": {
|
||||
"@sveltejs/vite-plugin-svelte": "^7.1.2",
|
||||
"@tailwindcss/postcss": "^4.3.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "playlet-web",
|
||||
"version": "0.47.5",
|
||||
"version": "0.48.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
Reference in new issue
Block a user