Live stream fixes, http client rewrite, telemetry improvements

This commit is contained in:
Brahim Hadriche committed 2026-10-13 17:13:12 -04:00
1 parent df4e16b846
commit 9200bd1c74
63 files changed
+4382 -1157

No files matched your search

+36 -35
View File
@@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Small security fixes
- SponsorBlock skip looping back to the start of a segment on some devices, and overlapping segments
- Live streams buffering on slow networks
### Changed
@@ -20,11 +21,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Backend changes from Invidious to Playlet if no instance url is set. This is to avoid playback errors.
- Backend changes from Invidious to Playlet if no instance url is set. This is to avoid playback errors
### Fixed
- Various Live stream improvements, streamed directly without local proxy, attempt to reduce errors and stutters.
- Various Live stream improvements, streamed directly without local proxy, attempt to reduce errors and stutters
## [0.48.7] - 2026-10-05
@@ -47,7 +48,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Issue with start up tasks that might have caused "Failed to fetch session data" errors.
- Issue with start up tasks that might have caused "Failed to fetch session data" errors
## [0.48.4] - 2026-09-24
@@ -61,7 +62,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Display issues for 720p devices
- Attempt to fix session data fetch errors
- Remove volume handing from cast, to avoid a possible "mute softlock" - feature will be added back later.
- Remove volume handing from cast, to avoid a possible "mute softlock" - feature will be added back later
## [0.48.2] - 2026-07-11
@@ -89,7 +90,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Trending back (Gaming and Live) for Playlet backend and Invidious - to avoid a blank home screen when not logged in.
- Trending back (Gaming and Live) for Playlet backend and Invidious - to avoid a blank home screen when not logged in
### Fixed
@@ -198,7 +199,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Always use `signatureTimestamp` in `/player` calls to prevent "reload page" errors. This affects watch history.
- Always use `signatureTimestamp` in `/player` calls to prevent "reload page" errors. This affects watch history
- Attempt 2 to fix watch history and watch progress
## [0.44.7] - 2026-04-23
@@ -249,7 +250,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Small change in post-live dvr detection
- Issue where recommended videos are all "UPCOMING" paid content
- Errors related to loading the trending feeds. Trending will be removed from Playlet in a future release.
- Errors related to loading the trending feeds. Trending will be removed from Playlet in a future release
## [0.44.0] - 2025-11-09
@@ -534,13 +535,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Telemetry to collect anonymous diagnostics data. Can be turned off from the settings.
- Telemetry to collect anonymous diagnostics data. Can be turned off from the settings
## [0.40.15] - 2025-08-28
### Fixed
- Shorts being merged with subscription videos, regardless of "Disable Shorts" preference.
- Shorts being merged with subscription videos, regardless of "Disable Shorts" preference
- Gracefully handle STS_MISMATCH errors
## [0.40.14] - 2025-08-22
@@ -559,17 +560,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Attempt to fix `no valid bitrates` and `Sign in to confirm you're not a bot` errors.
- Attempt to fix `no valid bitrates` and `Sign in to confirm you're not a bot` errors
- Introduced a "Playlet support server" to allow handling sig/nsig decoding. These are not possible to do without a Javascript execution environment, so this was necessary.
- Live videos are not affected by this fix yet, but hopefully it reduce the amount of errors.
- Videos longer than 5 hours now work [https://github.com/iBicha/playlet/issues/500](https://github.com/iBicha/playlet/issues/500)
- Age restricted videos should play normally if logged in using a YouTube account.
- Age restricted videos should play normally if logged in using a YouTube account
## [0.40.10] - 2025-07-19
### Added
- An option to export Playlet's state from the web app for easier debugging.
- An option to export Playlet's state from the web app for easier debugging
- This is a zip file that contains logs, the app state, and the registry (local storage)
### Fixed
@@ -618,7 +619,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- [perf] Added a job system to control background tasks.
- [perf] Added a job system to control background tasks
### Fixed
@@ -640,7 +641,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Added a "hint" in the error message when playing a video and login is required.
- Added a "hint" in the error message when playing a video and login is required
- Various performance improvements
## [0.40.2] - 2025-06-12
@@ -765,7 +766,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- [advanced users]: the Playlet web server's CORS headers are no longer set to `*`, for security reasons.
- [advanced users]: the Playlet web server's CORS headers are no longer set to `*`, for security reasons
## [0.36.7] - 2025-05-04
@@ -893,7 +894,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Removed
- [YouTube.js](https://github.com/LuanRT/YouTube.js) from web app. It is no longer needed, so this reduces app size.
- [YouTube.js](https://github.com/LuanRT/YouTube.js) from web app. It is no longer needed, so this reduces app size
## [0.35.0] - 2024-12-24
@@ -952,7 +953,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Improved on issue with long videos (10+ hours) showing as 2:30 only. They now show about 5 hours.
- Improved on issue with long videos (10+ hours) showing as 2:30 only. They now show about 5 hours
## [0.32.1] - 2024-12-03
@@ -975,7 +976,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Support for Trickplay thumbnails in Playlet backend. Done by parsing storyboards and injecting them into HLS manifest.
- Support for Trickplay thumbnails in Playlet backend. Done by parsing storyboards and injecting them into HLS manifest
## [0.30.0] - 2024-11-22
@@ -1044,7 +1045,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Support for casting clips from web app
- A workaround for video loading errors: uses Playlet Web app and [YouTube.js](https://github.com/LuanRT/YouTube.js) to load streaming data. This workaround is limited, and might not work. It doesn't have closed captions, nor trickplay thumbnails (storyboards).
- A workaround for video loading errors: uses Playlet Web app and [YouTube.js](https://github.com/LuanRT/YouTube.js) to load streaming data. This workaround is limited, and might not work. It doesn't have closed captions, nor trickplay thumbnails (storyboards)
- **How To use**: Open the web app, click on a video, and choose "Play on <TV_NAME> (HOT FIX)".
## [0.25.6] - 2024-09-12
@@ -1231,7 +1232,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Loading Playlet lib as squashfs, with fallback to the zip file. This significantly decreases load times.
- Loading Playlet lib as squashfs, with fallback to the zip file. This significantly decreases load times
### Changed
@@ -1299,12 +1300,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Support for multiple profiles. You can now use multiple Invidious accounts.
- Support for multiple profiles. You can now use multiple Invidious accounts
- When a video error dialog shows, a timer with 10 seconds starts to play the next video
### Fixed
- A bug where the loading screen does not disappear if search results are empty.
- A bug where the loading screen does not disappear if search results are empty
- Empty invidious instance in preferences when default instance is being used
## [0.20.2] - 2024-02-26
@@ -1350,12 +1351,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- The queue no longer contains playlists. When a playlist is added to the queue, the entire playlist is loaded.
- The queue no longer contains playlists. When a playlist is added to the queue, the entire playlist is loaded
- It can take a few seconds to load large playlist before it can be added to the queue
- This is done to be more compatible more the lounge, which does not contain "Playlists in the queue" concept.
- The `Web App` tab is now called `Remote`. It can be used to open the web app, or connect using Lounge (cast from YouTube)
- Removed `fields` from Invidious requests, as per [https://github.com/iv-org/invidious/pull/4276](https://github.com/iv-org/invidious/pull/4276)
- The `POST /api/queue/` no longer returns the current queue. Instead it returns a 204.
- The `POST /api/queue/` no longer returns the current queue. Instead it returns a 204
### Fixed
@@ -1389,7 +1390,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- A home screen editor allowing to enable/disable feeds, and change their order.
- A home screen editor allowing to enable/disable feeds, and change their order
- The editor can be accessed from the Settings screen.
### Fixed
@@ -1409,7 +1410,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Removed
- `Funny` and `News` from the Home screen.
- `Funny` and `News` from the Home screen
- These are not standard feeds (like `Trending`), and are just search results for `Funny` and `News`. They were added in earlier Playlet versions to have more content in the Home screen.
- If you like to add these two feeds to your bookmarks:
- Search for `Funny` (or `News`)
@@ -1511,7 +1512,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Bookmarks: different items can now be bookmarked, and be found in the `Bookmarks` screen.
- Bookmarks: different items can now be bookmarked, and be found in the `Bookmarks` screen
Things that can be bookmarked:
- A video
- A channel
@@ -1538,7 +1539,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Layout in channel view so that the upload time and view count of videos is visible
- A few things in the logger
- A bug where channels show "0 videos". Channel handle is shown instead.
- A bug where channels show "0 videos". Channel handle is shown instead
### Changed
@@ -1610,7 +1611,7 @@ This version went through a major refactor, which resulted in a different arcite
### Added
- The concept of a `Queue`. Videos can now be queued to play one after another.
- The concept of a `Queue`. Videos can now be queued to play one after another
- Currently the queue is funcitonal, but no proper UI to support it, such as seeing the queue, clearing it, and so on.
- UI for the `Queue` will be introduced in a future version.
- Videos and playlists can be queued from the web app
@@ -1648,7 +1649,7 @@ This version went through a major refactor, which resulted in a different arcite
- The web server is now decoupled from Playlet specific logic
- When not logged in, authenticated feed (like user Subscriptions and Playlists) show a "Login to view X" message, with a QR Code that redirects to the login screen
- [Breaking change] web apis changed a bit (for example the `/api/command` endpoint is removed) refer to the [Open API spec](docs/playlet-web-api.yml)
- If the Invidious auth token is missing permissions (A token aquired using a previous version of Playlet) you will be auto logged out.
- If the Invidious auth token is missing permissions (A token aquired using a previous version of Playlet) you will be auto logged out
### Removed
@@ -1660,7 +1661,7 @@ This version went through a major refactor, which resulted in a different arcite
- Excessive logging without a way to toggle it, or redirect it to a file
- Some unused parts of the code (Like basic auth in the server, WebSockets, RegistryRouter, Kanji QR Code)
- These were unused and/or feature flagged features. Things can be restored as needed.
- The video player loading spinner when the video is minimized: this added too much hacky code with minimum value.
- The video player loading spinner when the video is minimized: this added too much hacky code with minimum value
### Fixed
@@ -1672,7 +1673,7 @@ This version went through a major refactor, which resulted in a different arcite
### Added
- Support for saved playlists. By adding a playlist from a youtube channel to your Invidious profile, you can see the playlist on Playlet.
- Support for saved playlists. By adding a playlist from a youtube channel to your Invidious profile, you can see the playlist on Playlet
## [0.10.2] - 2023-07-10
@@ -1681,7 +1682,7 @@ This version went through a major refactor, which resulted in a different arcite
- Links to the app info in web app
- Loading indicator for search page in web app
- Feedback link through email
- Scopes and expire fields to the Invidious auth token. This is to detect when a token is close to expiry, or if we have missing permissions.
- Scopes and expire fields to the Invidious auth token. This is to detect when a token is close to expiry, or if we have missing permissions
### Fixed
@@ -1823,7 +1824,7 @@ This version went through a major refactor, which resulted in a different arcite
### Fixed
- Bug where playing and exiting a video too quickly would cause the video to play in the background.
- Bug where playing and exiting a video too quickly would cause the video to play in the background
- Bug where logging in causes issues if a video is already playing
- Bug where casting from web app while playing a video from the search
- Spinner for the video
@@ -1844,7 +1845,7 @@ This version went through a major refactor, which resulted in a different arcite
### Fixed
- Bug where Settings page and home page are both visible, if settings page is selected, and user logs in.
- Bug where Settings page and home page are both visible, if settings page is selected, and user logs in
## [0.3.0] - 2022-11-19
+1
View File
@@ -35,6 +35,7 @@
"rooibos": {
"logLevel": 2,
"tags": ["!integration"],
"isGlobalMethodMockingEnabled": true,
"isRecordingCodeCoverage": false,
"printTestTimes": true,
"showOnlyFailures": true,
@@ -303,7 +303,7 @@ function CanFetchVideoThumbails(instance as string, testNode as object, cancella
response = HttpClient.Get(thumbnail).NoCache().Cancellation(cancellation).Await()
if not response.IsSuccess()
testNode.state = "failed"
testNode.details = Tr(Locale.InvidiousTesting.ThumbnailNotReachable).Replace("%1", thumbnail) + `\n` + response.ErrorMessage(false)
testNode.details = Tr(Locale.InvidiousTesting.ThumbnailNotReachable).Replace("%1", thumbnail) + `\n` + response.ErrorMessage()
return
end if
@@ -0,0 +1,119 @@
import "pkg:/components/Services/Dash/LiveTimeline.types.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/MathUtils.bs"
' Roku waits over 10s on a manifest refresh, but the response holds every route of the web server
' meanwhile, and from 5s Roku sends a second request (measured).
const LIVE_HEAD_WAIT_MS = 2000
' One check per LIVE_MANIFEST_REFRESH_MS over HttpClient's 30s default attempt timeout.
const LIVE_HEAD_MAX_CHECKS_IN_FLIGHT = 3
class LiveHeadChecks
public counts as object
private headUrl as string
private inFlight as LiveHeadCheck[]
private refreshes as integer = 0
private refreshesWithoutNewerHead as integer = 0
private newestSeqnum as integer = -1
function new(headUrl as string)
m.headUrl = headUrl
m.inFlight = []
m.counts = {
"checks_sent": 0
"answered_after_wait": 0
"timed_out": 0
"answered_without_head": 0
"refreshes_without_newer_head_max_streak": 0
}
end function
' A check unanswered within LIVE_HEAD_WAIT_MS stays in flight; a later refresh returns its answer. A check that
' answers with a head cancels the checks sent before it: they can only answer with an older one.
function Refresh() as LiveHeadReading[]
m.refreshes += 1
answers = m.CollectAnswers()
if m.inFlight.Count() < LIVE_HEAD_MAX_CHECKS_IN_FLIGHT
check = { pending: m.Send(), sentAtRefresh: m.refreshes }
m.counts["checks_sent"] += 1
response = check.pending.Wait(LIVE_HEAD_WAIT_MS)
' Earlier checks answered during the wait.
answers.Append(m.CollectAnswers())
if response = invalid
m.inFlight.Push(check)
else
head = m.Read(check, response)
answers.Push(head)
if head.seqnum >= 0
m.Cancel()
end if
end if
end if
m.refreshesWithoutNewerHead += 1
for each head in answers
if head.seqnum > m.newestSeqnum
m.newestSeqnum = head.seqnum
m.refreshesWithoutNewerHead = 0
end if
end for
m.counts["refreshes_without_newer_head_max_streak"] = MathUtils.Max(m.counts["refreshes_without_newer_head_max_streak"], m.refreshesWithoutNewerHead)
return answers
end function
' Cancels the checks in flight: the video load they were sent for is over, or a newer check answered.
function Cancel() as void
for each check in m.inFlight
check.pending.Cancel()
end for
m.inFlight = []
end function
private function Send() as HttpClient.PendingResponse
return Innertube.CreateLiveHeadRequest(m.headUrl).Send()
end function
' The answers of the checks in flight, in the order they were sent.
private function CollectAnswers() as LiveHeadReading[]
answers = []
stillInFlight = []
for each check in m.inFlight
response = check.pending.Poll()
if response = invalid
stillInFlight.Push(check)
else
head = m.Read(check, response)
answers.Push(head)
if head.seqnum >= 0
for each sentBefore in stillInFlight
sentBefore.pending.Cancel()
end for
stillInFlight = []
end if
end if
end for
m.inFlight = stillInFlight
return answers
end function
private function Read(check as LiveHeadCheck, response as HttpClient.Response) as LiveHeadReading
head = {
seqnum: Innertube.ReadLiveHeadSeqnum(response)
timeMs: Innertube.ReadLiveHeadTimeMs(response)
response: response
}
if response.IsTimedOut()
m.counts["timed_out"] += 1
return head
end if
if check.sentAtRefresh < m.refreshes
m.counts["answered_after_wait"] += 1
end if
if head.seqnum < 0
m.counts["answered_without_head"] += 1
end if
return head
end function
end class
@@ -0,0 +1,3 @@
' The head check counts of the latest live video load, as { video_load_id, counts }. One file,
' overwritten by each live load: tmp:/ lasts as long as the app.
const LIVE_HEAD_COUNTS_PATH = "tmp:/live_head_counts.json"
@@ -1,3 +1,5 @@
import "pkg:/source/services/HttpClient.bs"
' Segments fromSeqnum up to the next run's fromSeqnum, each durationMs long, the first
' starting at startMs on the live timeline. A run starts at or after the previous one's end.
interface LiveDurationRun
@@ -12,3 +14,8 @@ interface LiveHeadReading
timeMs as dynamic
response as object
end interface
interface LiveHeadCheck
pending as HttpClient.PendingResponse
sentAtRefresh as integer
end interface
@@ -5,7 +5,7 @@ import "pkg:/source/utils/StringUtils.bs"
namespace Innertube
function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, options = invalid as object) as object
function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, options = invalid as object) as HttpClient.Request
params = OptionUtils.GetOrDefault(options, "params", "")
continuation = OptionUtils.GetOrDefault(options, "continuation", "")
@@ -24,7 +24,7 @@ namespace Innertube
end if
end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json", payload)
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json").JsonBody(payload)
request.Headers(Innertube.CreateHeaders(clienType))
return request
@@ -1,6 +1,6 @@
namespace Innertube
function CreateGetDrmLicenceRequest(options as object) as object
function CreateGetDrmLicenceRequest(options as object) as HttpClient.Request
videoId = OptionUtils.Get(options, "videoId")
licenseRequest = OptionUtils.Get(options, "licenseRequest")
drmParams = OptionUtils.Get(options, "drmParams")
@@ -26,7 +26,7 @@ namespace Innertube
"drmVideoFeature": "DRM_VIDEO_FEATURE_SDR"
}
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player/get_drm_license?alt=json", payload)
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/player/get_drm_license?alt=json").JsonBody(payload)
request.Headers(Innertube.CreateHeaders(ClientType.Tv))
if not StringUtils.IsNullOrEmpty(accessToken)
@@ -23,37 +23,34 @@ namespace InnertubeService
function GetVideoMetadata(videoId as string, options = invalid as object) as object
options["videoId"] = videoId
if not OptionUtils.GetOrDefault(options, "fetchNext", true)
return GetPlayerMetadata(videoId, options)
end if
raw = OptionUtils.GetOrDefault(options, "raw", false)
nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, options)
nextRequest.Cancellation(OptionUtils.Get(options, "cancellation"))
if raw
nextRequest.LogCurlCommand()
end if
pendingNext = nextRequest.Send()
return AwaitAndParseNextResponse(raw, GetPlayerMetadata(videoId, options), nextRequest, pendingNext)
end function
' The parsed player response (raw: { playerResponse }), or { error }.
function GetPlayerMetadata(videoId as string, options as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
fetchNext = OptionUtils.GetOrDefault(options, "fetchNext", true)
accessToken = OptionUtils.Get(options, "accessToken")
raw = OptionUtils.GetOrDefault(options, "raw", false)
nextRequest = invalid
if fetchNext
nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, options)
nextRequest.Cancellation(cancellation)
if raw
nextRequest.LogCurlCommand(true)
end if
nextRequest.Send()
end if
playerResponseJson = invalid
client = Innertube.ClientType.Tv
totalPlayerRequests = 0
triedReloadRefresh = false
while true
' We shouldn't be making more than 3 requests:
' 1. Make request with TV client.
' 2. Make request, but STS_MISMATCH error -> retry with new STS.
' 3. useServerDrivenAbr -> retry with downgraded TV client version to recover format URLs.
if totalPlayerRequests >= 3
LogError("Too many player requests, aborting.")
return {
error: "Too many player requests"
}
end if
totalPlayerRequests += 1
' We shouldn't be making more than 3 requests:
' 1. Make request with TV client.
' 2. Make request, but STS_MISMATCH error -> retry with new STS.
' 3. useServerDrivenAbr -> retry with downgraded TV client version to recover format URLs.
for playerRequestCount = 1 to 3
stsResult = Innertube.GetSignatureTimestamp(cancellation)
if CancellationUtils.IsCancelled(cancellation)
return {
@@ -70,7 +67,7 @@ namespace InnertubeService
end if
playerRequest.Cancellation(cancellation)
if raw
playerRequest.LogCurlCommand(true)
playerRequest.LogCurlCommand()
end if
playerResponse = playerRequest.Await()
@@ -82,11 +79,9 @@ namespace InnertubeService
end if
if not playerResponse.IsSuccess()
parsedResponse = {
return {
error: playerResponse.ErrorMessage()
}
parsedResponse = AwaitAndParseNextResponse(fetchNext, raw, parsedResponse, nextRequest)
return parsedResponse
end if
playerResponseJson = playerResponse.Json()
@@ -96,7 +91,7 @@ namespace InnertubeService
if client = Innertube.ClientType.Tv and IsSabrLocked(playerResponseJson)
LogInfo("SABR-locked response, retrying with downgraded TV client...")
client = Innertube.ClientType.TvDowngraded
continue while
continue for
else if client = Innertube.ClientType.TvDowngraded and not HasUsableAdaptiveUrl(playerResponseJson)
LogError("Downgraded TV client did not recover SABR-withheld format URLs")
end if
@@ -104,18 +99,26 @@ namespace InnertubeService
parsedResponse = Innertube.ParseInnertubePlayerResponse(playerRequest, playerResponse, client, cancellation)
if parsedResponse.error = invalid
exit while
if raw
return {
"playerResponse": playerResponseJson
}
end if
if StringUtils.IsNullOrEmpty(parsedResponse.videoId)
parsedResponse["videoId"] = videoId
end if
return parsedResponse
end if
if parsedResponse.errorCode <> invalid
if parsedResponse.errorCode = "STS_MISMATCH"
LogInfo("STS_MISMATCH error, retrying...")
continue while
continue for
else if parsedResponse.errorCode = "RELOAD_PAGE" and not triedReloadRefresh
triedReloadRefresh = true
LogInfo("RELOAD_PAGE: clearing stale STS cache and retrying...")
DeleteFile("tmp:/sts_cache.json")
continue while
continue for
else if parsedResponse.errorCode = "MISSING_FORMAT_FIELD"
useServerDrivenAbr = `${ObjectUtils.Dig(playerResponseJson, ["playerConfig", "mediaCommonConfig", "useServerDrivenAbr"])}`
LogTelemetryEvent({
@@ -135,25 +138,13 @@ namespace InnertubeService
end if
end if
parsedResponse = AwaitAndParseNextResponse(fetchNext, raw, parsedResponse, nextRequest)
return parsedResponse
end while
end for
if raw
rawResponse = {
"playerResponse": playerResponseJson
}
rawResponse = AwaitAndParseNextResponse(fetchNext, raw, rawResponse, nextRequest)
return rawResponse
end if
parsedResponse = AwaitAndParseNextResponse(fetchNext, raw, parsedResponse, nextRequest)
if StringUtils.IsNullOrEmpty(parsedResponse.videoId)
parsedResponse["videoId"] = videoId
end if
return parsedResponse
LogError("Too many player requests, aborting.")
return {
error: "Too many player requests"
}
end function
' True when the TV client's response is SABR-locked: server-driven ABR signaled with no usable
@@ -186,12 +177,8 @@ namespace InnertubeService
return false
end function
function AwaitAndParseNextResponse(fetchNext as boolean, raw as boolean, parsedResponse as object, nextRequest as object) as object
if not fetchNext
return parsedResponse
end if
nextResponse = nextRequest.Await()
function AwaitAndParseNextResponse(raw as boolean, parsedResponse as object, nextRequest as HttpClient.Request, pendingNext as HttpClient.PendingResponse) as object
nextResponse = pendingNext.Await()
if not nextResponse.IsSuccess()
if nextResponse.IsCancelled()
@@ -213,7 +200,7 @@ namespace InnertubeService
return parsedResponse
end if
return Innertube.ParseInnertubeNextResponse(nextResponse.Json(), parsedResponse, nextResponse)
return Innertube.ParseInnertubeNextResponse(nextResponse.Json(), parsedResponse, nextRequest)
end function
function GetVideoInfoBatched(videoIds as object, options = invalid as object) as object
@@ -272,7 +259,7 @@ namespace InnertubeService
end if
feeds = Innertube.ParseResponseDataForFeeds(responseData, {
response: response
request: request
})
if videoIds.Count() > 1
@@ -325,8 +312,7 @@ namespace InnertubeService
request.Cancellation(cancellation)
if raw
request.LogCurlCommand(true)
request.NoCache()
request.LogCurlCommand()
end if
response = request.Await()
@@ -341,7 +327,7 @@ namespace InnertubeService
end if
feeds = Innertube.ParseResponseDataForFeeds(response.Json(), {
response: response
request: request
disableCreatorOnTheRise: true
disableShorts: disableShorts
browseId: browseId
@@ -395,7 +381,7 @@ namespace InnertubeService
end if
feeds = Innertube.ParseResponseDataForFeeds(response.Json(), {
response: response
request: request
disableShorts: disableShorts
browseId: browseId
})
@@ -551,8 +537,7 @@ namespace InnertubeService
request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, options)
request.Cancellation(cancellation)
if raw
request.LogCurlCommand(true)
request.NoCache()
request.LogCurlCommand()
end if
response = request.Await()
@@ -566,7 +551,7 @@ namespace InnertubeService
return response.Json()
end if
result = Innertube.ParseChannelPageResponseData(channelId, response.Json(), response)
result = Innertube.ParseChannelPageResponseData(channelId, response.Json(), request)
if result.authorId = invalid and result.error = invalid
result["authorId"] = channelId
end if
@@ -693,8 +678,7 @@ namespace InnertubeService
request.Header("Authorization", "Bearer " + accessToken)
end if
if raw
request.LogCurlCommand(true)
request.NoCache()
request.LogCurlCommand()
end if
response = request.Await()
@@ -708,7 +692,7 @@ namespace InnertubeService
return response.Json()
end if
result = Innertube.ParsePlaylistPageResponseData(playlistId, response.Json(), response)
result = Innertube.ParsePlaylistPageResponseData(playlistId, response.Json(), request)
if result.playlistId = invalid and result.error = invalid
result["playlistId"] = playlistId
@@ -734,8 +718,7 @@ namespace InnertubeService
request = Innertube.CreateNextRequest(args)
request.Cancellation(cancellation)
if raw
request.LogCurlCommand(true)
request.NoCache()
request.LogCurlCommand()
end if
response = request.Await()
@@ -749,7 +732,7 @@ namespace InnertubeService
return response.Json()
end if
result = Innertube.ParseMixPageResponseData(response.Json(), response)
result = Innertube.ParseMixPageResponseData(response.Json(), request)
cacheControl = Innertube.ParseResponseForCacheControl(response)
if cacheControl <> invalid
@@ -34,10 +34,12 @@ namespace Innertube
headUrl = GetLiveHeadUrl(adaptiveFormats[0]["url"], cpn)
request = CreateLiveHeadRequest(headUrl)
request.TryCount(2)
request.RetryCallback(function(context as object) as boolean
response = context.response
return Innertube.ReadLiveHeadSeqnum(response) < 0 or (Innertube.ReadLiveHeadTimeMs(response) = invalid and Innertube.ReadLiveHeadTimeSecAsMs(response) = invalid)
request.RetryCount(1)
request.RetryIf(function(response as HttpClient.Response) as string
if Innertube.ReadLiveHeadSeqnum(response) < 0 or (Innertube.ReadLiveHeadTimeMs(response) = invalid and Innertube.ReadLiveHeadTimeSecAsMs(response) = invalid)
return `no X-Head-* in the response (HTTP ${response.StatusCode()})`
end if
return ""
end function)
request.Cancellation(cancellation)
response = request.Await()
@@ -49,7 +51,7 @@ namespace Innertube
averagedTimeMs = ReadLiveHeadTimeSecAsMs(response)
end if
if headSeqnum < 0 or averagedTimeMs = invalid
parsedResponse["error"] = `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP ${response.StatusCode()})\n${response.ErrorMessage(false)}`
parsedResponse["error"] = `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP ${response.StatusCode()})\n${response.ErrorMessage()}`
return
end if
@@ -136,7 +138,7 @@ namespace Innertube
return UrlUtils.SetQueryParams(formatUrl, queryComponents)
end function
function CreateLiveHeadRequest(headUrl as string) as object
function CreateLiveHeadRequest(headUrl as string) as HttpClient.Request
request = HttpClient.Head(headUrl)
request.Headers({
"origin": "https://www.youtube.com"
@@ -149,9 +151,9 @@ namespace Innertube
' X-Head-Seqnum of a live head response, -1 if absent. Not gated on HTTP status: a
' head check can come back non-2xx yet still carry the X-Head-* headers
' (observed: one stream returns 500, another 200; both include them).
function ReadLiveHeadSeqnum(response as object) as integer
function ReadLiveHeadSeqnum(response as HttpClient.Response) as integer
headers = response.Headers()
if not IsAssociativeArray(headers) or not headers.DoesExist("X-Head-Seqnum")
if not headers.DoesExist("X-Head-Seqnum")
return -1
end if
return ValidString(headers["X-Head-Seqnum"]).ToInt()
@@ -161,19 +163,15 @@ namespace Innertube
' long-running stream's (e.g. 207 days = 1.79e10 ms) overflows BrightScript's 32-bit
' int: ParseJson keeps it as a LongInteger, which .ToInt() and Cdbl() would truncate
' (measured).
function ReadLiveHeadTimeMs(response as object) as dynamic
headers = response.Headers()
if not IsAssociativeArray(headers)
return invalid
end if
return StringUtils.ParseJsonSafe(ValidString(headers["X-Head-Time-Millis"]))
function ReadLiveHeadTimeMs(response as HttpClient.Response) as dynamic
return StringUtils.ParseJsonSafe(ValidString(response.Headers()["X-Head-Time-Millis"]))
end function
' X-Head-Time-Sec in ms, invalid if absent: whole seconds, too coarse to average a
' young stream's few segments or to time the head between checks.
function ReadLiveHeadTimeSecAsMs(response as object) as dynamic
function ReadLiveHeadTimeSecAsMs(response as HttpClient.Response) as dynamic
headers = response.Headers()
if not IsAssociativeArray(headers) or not headers.DoesExist("X-Head-Time-Sec")
if not headers.DoesExist("X-Head-Time-Sec")
return invalid
end if
return ValidString(headers["X-Head-Time-Sec"]).ToInt() * 1000&
@@ -8,7 +8,7 @@ import "pkg:/source/utils/Types.bs"
namespace Innertube
function CreateNextRequest(payloadArgs as object, options = invalid as object) as object
function CreateNextRequest(payloadArgs as object, options = invalid as object) as HttpClient.Request
deviceInfo = CreateObject("roDeviceInfo")
context = Innertube.CreateContext(Innertube.ClientType.Web, deviceInfo, options)
@@ -18,7 +18,7 @@ namespace Innertube
}
payload.Append(payloadArgs)
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json", payload)
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json").JsonBody(payload)
request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Web))
return request
@@ -34,7 +34,7 @@ namespace Innertube
})
end function
function ParseInnertubeNextResponse(payload as object, parsedResponse as object, httpResponse as object) as object
function ParseInnertubeNextResponse(payload as object, parsedResponse as object, request as HttpClient.Request) as object
if not IsAssociativeArray(payload)
LogWarn("Invalid payload", payload)
return parsedResponse
@@ -49,7 +49,7 @@ namespace Innertube
endscreen = playerOverlayRenderer["endScreen"]
feeds = Innertube.ParseResponseDataForFeeds(endscreen, {
response: httpResponse
request: request
noContainers: true
})
if feeds.Count() > 0
@@ -2250,7 +2250,7 @@ namespace Innertube
}, {
filename: "request.txt"
content_type: "text/plain"
data: context.response.request.ToCurlCommand()
data: context.request.ToCurlCommand()
}]
})
end function
@@ -21,6 +21,14 @@ namespace Innertube
return oauthError = RefreshErrorCode.InvalidGrant or oauthError = RefreshErrorCode.InvalidClient or oauthError = RefreshErrorCode.UnauthorizedClient
end function
' A failed refresh is retried, unless the token endpoint rejected the credential or the client.
function RefreshRetryReason(response as HttpClient.Response) as string
if response.IsSuccess() or IsTerminalRefreshError(response.Json())
return ""
end if
return response.ErrorMessage()
end function
function GetClientIdentity(cancellation = invalid as dynamic) as object
request = HttpClient.Get("https://www.youtube.com/tv")
request.Headers({
@@ -87,7 +95,7 @@ namespace Innertube
"device_model": "ytlr::"
}
request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/device/code", payload)
request = HttpClient.Post("https://www.youtube.com/o/oauth2/device/code").JsonBody(payload)
request.Cancellation(cancellation)
response = request.Await()
@@ -123,7 +131,7 @@ namespace Innertube
intervalMs = deviceAndUserCode.interval * 1000
while true
request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/token", payload)
request = HttpClient.Post("https://www.youtube.com/o/oauth2/token").JsonBody(payload)
request.Cancellation(cancellation)
response = request.Await()
@@ -181,12 +189,10 @@ namespace Innertube
"grant_type": "refresh_token"
}
request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/token", payload)
request = HttpClient.Post("https://www.youtube.com/o/oauth2/token").JsonBody(payload)
request.Cancellation(cancellation)
request.TryCount(3)
request.RetryCallback(function(context as object) as boolean
return not Innertube.IsTerminalRefreshError(context.response.Json())
end function)
request.RetryCount(2)
request.RetryIf(Innertube.RefreshRetryReason)
response = request.Await()
if not response.IsSuccess()
@@ -215,7 +221,7 @@ namespace Innertube
end function
function RevokeToken(token as string, cancellation = invalid as dynamic) as boolean
request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/revoke", {
request = HttpClient.Post("https://www.youtube.com/o/oauth2/revoke").JsonBody({
"token": token
})
request.Cancellation(cancellation)
@@ -240,7 +246,7 @@ namespace Innertube
}
}
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/account/accounts_list", payload)
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/account/accounts_list").JsonBody(payload)
headers = {
"Authorization": `Bearer ${accessToken}`
}
@@ -29,19 +29,20 @@ namespace Innertube
' Bare and sq responses are full media on a healthy URL — stream those to files
' instead of buffering them into strings.
variants = [
{ name: "GET bare", request: HttpClient.Get(url).ToFile(`${Innertube.DRM_PROBE_DIR}/bare.bin`) }
{ name: "GET bare", request: HttpClient.Get(url).SaveBodyToFile(`${Innertube.DRM_PROBE_DIR}/bare.bin`) }
{ name: "GET Range header", request: HttpClient.Get(url).Header("Range", "bytes=0-16383") }
{ name: "GET range param", request: HttpClient.Get(rangeUrl) }
{ name: "GET sq=0", request: HttpClient.Get(sqUrl).ToFile(`${Innertube.DRM_PROBE_DIR}/sq.bin`) }
{ name: "POST empty range param", request: HttpClient.Post(rangeUrl, "") }
{ name: "POST {15:0} range param", request: HttpClient.Post(rangeUrl, "").FromFile(`${Innertube.DRM_PROBE_DIR}/post_body.bin`) }
{ name: "GET sq=0", request: HttpClient.Get(sqUrl).SaveBodyToFile(`${Innertube.DRM_PROBE_DIR}/sq.bin`) }
{ name: "POST empty range param", request: HttpClient.Post(rangeUrl) }
{ name: "POST {15:0} range param", request: HttpClient.Post(rangeUrl).FileBody(`${Innertube.DRM_PROBE_DIR}/post_body.bin`) }
]
for each variant in variants
variant.request.Headers(requestHeaders)
variant.request.TimeoutSeconds(Innertube.DRM_PROBE_TIMEOUT_SECONDS)
variant.request.AttemptTimeoutMs(Innertube.DRM_PROBE_TIMEOUT_SECONDS * 1000)
variant.request.Cancellation(cancellation)
variant.request.Send()
variant.request.NoCache()
variant.pending = variant.request.Send()
end for
lines = [`drm probe itag=${format.itag} drmFamilies=${ValidArray(format.drmFamilies).Join(",")}`]
@@ -62,7 +63,7 @@ namespace Innertube
function DrmProbeCollect(variant as object) as string
name = variant.name
response = variant.request.Await()
response = variant.pending.Await()
if response.IsCancelled()
return `${name} -> cancelled`
@@ -72,12 +73,7 @@ namespace Innertube
return `${name} -> timed out after ${Innertube.DRM_PROBE_TIMEOUT_SECONDS}s`
end if
line = `${name} -> ${response.StatusCode()}`
responseHeaders = response.Headers()
if IsAssociativeArray(responseHeaders)
line += ` headers=${ToString(responseHeaders)}`
end if
return line
return `${name} -> ${response.StatusCode()} headers=${ToString(response.Headers())}`
end function
end namespace
@@ -49,9 +49,9 @@ namespace Innertube
while true
while formatsToProcess.Count() > 0 and pendingFormats.Count() < OTF_MAX_REQUEST_COUNT
formatToProcess = formatsToProcess.Pop()
request = OTFMakeSegmentInfoRequest(formatToProcess.format, formatToProcess.filePath, requestHeaders, errors, cancellation)
if request <> invalid
formatToProcess.request = request
pending = OTFSendSegmentInfoRequest(formatToProcess.format, formatToProcess.filePath, requestHeaders, errors, cancellation)
if pending <> invalid
formatToProcess.pending = pending
pendingFormats.Push(formatToProcess)
end if
end while
@@ -62,10 +62,13 @@ namespace Innertube
pendingFormat = pendingFormats.Shift()
' returns false if processing should stop (e.g., cancelled)
if not OTFProcessPendingFormat(pendingFormat.format, pendingFormat.request, pendingFormat.filePath, segmentDurationsRegex, errors, requestHeaders, cancellation)
if not OTFProcessPendingFormat(pendingFormat.format, pendingFormat.pending, pendingFormat.filePath, segmentDurationsRegex, errors, requestHeaders, cancellation)
exit while
end if
end while
for each pendingFormat in pendingFormats
pendingFormat.pending.Cancel()
end for
fs.Delete("tmp:/otf_segments")
@@ -87,7 +90,7 @@ namespace Innertube
end if
end function
function OTFMakeSegmentInfoRequest(format as object, filePath as string, requestHeaders as object, errors as object, cancellation as object) as object
function OTFSendSegmentInfoRequest(format as object, filePath as string, requestHeaders as object, errors as object, cancellation as object) as dynamic
url = format.url
if StringUtils.IsNullOrEmpty(url)
errors.message += `URL is empty for itag ${format.itag}.\n`
@@ -101,15 +104,14 @@ namespace Innertube
request = HttpClient.Get(otfUrl)
request.Headers(requestHeaders)
request.ToFile(filePath)
request.SaveBodyToFile(filePath)
request.NoCache()
request.Cancellation(cancellation)
request.Send()
return request
return request.Send()
end function
function OTFProcessPendingFormat(format as object, request as object, filePath as string, segmentDurationsRegex as object, errors as object, requestHeaders as object, cancellation as object) as boolean
response = request.Await()
function OTFProcessPendingFormat(format as object, pending as HttpClient.PendingResponse, filePath as string, segmentDurationsRegex as object, errors as object, requestHeaders as object, cancellation as object) as boolean
response = pending.Await()
if response.IsCancelled()
return false
@@ -1,4 +1,5 @@
import "pkg:/components/Services/Innertube/NodesParser.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
@@ -44,7 +45,7 @@ namespace Innertube
return context.feeds
end function
function ParseChannelPageResponseData(browseId as string, responseData as object, response as object) as object
function ParseChannelPageResponseData(browseId as string, responseData as object, request as HttpClient.Request) as object
if responseData = invalid
return {
error: "Invalid response data"
@@ -149,7 +150,7 @@ namespace Innertube
continuation = invalid
sortOptions = invalid
feeds = ParseResponseDataForFeeds(responseData, {
response: response
request: request
"currentAuthor": author
"currentAuthorId": authorId
browseId: browseId
@@ -187,7 +188,7 @@ namespace Innertube
return channel
end function
function ParsePlaylistPageResponseData(browseId as string, responseData as object, response as object) as object
function ParsePlaylistPageResponseData(browseId as string, responseData as object, request as HttpClient.Request) as object
if responseData = invalid
return {
error: "Invalid response data"
@@ -285,7 +286,7 @@ namespace Innertube
end if
feeds = ParseResponseDataForFeeds(responseData, {
response: response
request: request
browseId: browseId
})
if feeds.Count() > 0
@@ -302,7 +303,7 @@ namespace Innertube
return playlist
end function
function ParseMixPageResponseData(responseData as object, response as object) as object
function ParseMixPageResponseData(responseData as object, request as HttpClient.Request) as object
if responseData = invalid
return {
error: "Invalid response data"
@@ -348,7 +349,7 @@ namespace Innertube
}
feeds = ParseResponseDataForFeeds(playlist, {
response: response
request: request
})
if feeds.Count() > 0
result["videos"] = ValidArray(feeds[0].items)
@@ -395,12 +396,12 @@ namespace Innertube
return error
end function
function ParseResponseForCacheControl(response as object) as dynamic
function ParseResponseForCacheControl(response as HttpClient.Response) as dynamic
if not response.IsSuccess()
return invalid
end if
headers = ValidAssociativeArray(response.Headers())
headers = response.Headers()
if headers.DoesExist("cache-control")
return headers["cache-control"]
end if
@@ -11,7 +11,7 @@ import "pkg:/source/utils/UrlUtils.bs"
namespace Innertube
function CreatePlayerRequest(client as Innertube.ClientType, options = invalid as object) as object
function CreatePlayerRequest(client as Innertube.ClientType, options = invalid as object) as HttpClient.Request
videoId = OptionUtils.Get(options, "videoId")
visitorData = OptionUtils.Get(options, "visitorData")
accessToken = OptionUtils.Get(options, "accessToken")
@@ -63,7 +63,7 @@ namespace Innertube
payload["playbackContext"]["contentPlaybackContext"]["isLivingRoomDeeplink"] = true
end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload)
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json").JsonBody(payload)
request.Headers(Innertube.CreateHeaders(client))
if not StringUtils.IsNullOrEmpty(visitorData) and not useAccessToken
@@ -86,7 +86,7 @@ namespace Innertube
return request
end function
function ParseInnertubePlayerResponse(playerRequest as dynamic, playerResponse as dynamic, client as Innertube.ClientType, cancellation as object) as object
function ParseInnertubePlayerResponse(playerRequest as HttpClient.Request, playerResponse as HttpClient.Response, client as Innertube.ClientType, cancellation as object) as object
WriteAsciiFile("cachefs:/last_player_response.json", playerResponse.Text())
parsedResponse = {}
payload = playerResponse.Json()
@@ -206,7 +206,7 @@ namespace Innertube
return parsedResponse
end function
function ParsePlayerResponseForError(payload as object, playerRequest as object) as string
function ParsePlayerResponseForError(payload as object, playerRequest as HttpClient.Request) as string
if not IsAssociativeArray(payload)
return "Invalid payload"
end if
@@ -244,7 +244,7 @@ namespace Innertube
errorLines.Push("Hint: Log in to the YouTube app on your phone, then cast the video to Playlet.")
hasAccessToken = ValidString(playerRequest.GetHeaders()["Authorization"]).Len() > "Bearer ".Len()
hasCtt = ValidString(playerRequest.GetBody()).InStr("credentialTransferTokens") <> -1
hasCtt = ValidString(playerRequest.GetTextBody()).InStr("credentialTransferTokens") <> -1
if hasAccessToken or hasCtt
LogTelemetryEvent({
@@ -508,7 +508,7 @@ namespace Innertube
request = HttpClient.Get(`${PLAYLET_SUPPORT_SERVER}/v1/sts`)
request.Cancellation(cancellation)
request.TryCount(3)
request.RetryCount(2)
request.NoCache()
response = request.Await()
if not response.IsSuccess()
@@ -583,9 +583,8 @@ namespace Innertube
body["poToken"] = poToken
end if
request = HttpClient.PostJson(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`, body)
request = HttpClient.Post(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`).JsonBody(body)
request.Cancellation(cancellation)
request.LogCurlCommand(false)
response = request.Await()
@@ -76,7 +76,7 @@ namespace Innertube
requestHeaders["referer"] = "https://www.youtube.com"
requestHeaders["DNT"] = "?1"
request.Headers(requestHeaders)
request.TryCount(2)
request.RetryCount(1)
request.Cancellation(cancellation)
response = request.Await()
@@ -2,7 +2,7 @@ import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/source/services/HttpClient.bs"
namespace Innertube
function CreateResolveUrlRequest(url as string) as object
function CreateResolveUrlRequest(url as string) as HttpClient.Request
deviceInfo = CreateObject("roDeviceInfo")
payload = {
@@ -10,7 +10,7 @@ namespace Innertube
"url": url
}
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/navigation/resolve_url?prettyPrint=false&alt=json", payload)
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/navigation/resolve_url?prettyPrint=false&alt=json").JsonBody(payload)
request.Headers(Innertube.CreateHeaders(ClientType.Web))
return request
@@ -32,13 +32,12 @@ namespace Innertube
end if
end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json", payload)
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json").JsonBody(payload)
request.Headers(Innertube.CreateHeaders(ClientType.Web))
request.Cancellation(cancellation)
if raw
request.NoCache()
request.LogCurlCommand(true)
request.LogCurlCommand()
end if
response = request.Await()
@@ -53,7 +52,7 @@ namespace Innertube
end if
feeds = ParseResponseDataForFeeds(response.Json(), {
response: response
request: request
disableShorts: disableShorts
})
@@ -4,7 +4,7 @@ import "pkg:/source/utils/Types.bs"
namespace Innertube
function CreateSubscribeRequest(channelIds as dynamic, options = invalid as object) as object
function CreateSubscribeRequest(channelIds as dynamic, options = invalid as object) as HttpClient.Request
deviceInfo = CreateObject("roDeviceInfo")
payload = {
@@ -16,13 +16,13 @@ namespace Innertube
end if
payload["channelIds"] = channelIds
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/subscription/subscribe?prettyPrint=false&alt=json", payload)
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/subscription/subscribe?prettyPrint=false&alt=json").JsonBody(payload)
request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv))
return request
end function
function CreateUnsubscribeRequest(channelIds as dynamic, options = invalid as object) as object
function CreateUnsubscribeRequest(channelIds as dynamic, options = invalid as object) as HttpClient.Request
deviceInfo = CreateObject("roDeviceInfo")
payload = {
@@ -34,7 +34,7 @@ namespace Innertube
end if
payload["channelIds"] = channelIds
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/subscription/unsubscribe?prettyPrint=false&alt=json", payload)
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/subscription/unsubscribe?prettyPrint=false&alt=json").JsonBody(payload)
request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv))
return request
@@ -106,7 +106,7 @@ namespace Invidious
end if
url = `${auth.serverUrl}${Invidious.HISTORY_ENDPOINT}/${videoId}`
request = HttpClient.Post(url, "")
request = HttpClient.Post(url)
request.Headers(m.GetAuthenticationHeaders(auth.token))
request.Cancellation(cancellation)
response = request.Await()
@@ -120,7 +120,7 @@ namespace Invidious
request = HttpClient.Get(url)
request.QueryParam("region", m.GetUserCountryCode())
request.QueryParam("q", q)
request.CacheSeconds(60 * 60 * 24)
request.CacheForSeconds(60 * 60 * 24)
request.Cancellation(cancellation)
@@ -136,31 +136,23 @@ namespace Invidious
function GetVideoMetadata(videoId as string, options = invalid as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
tryCount = OptionUtils.GetOrDefault(options, "tryCount", 2)
retryCount = OptionUtils.GetOrDefault(options, "retryCount", 1)
instance = m.GetInstance()
url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}`
request = HttpClient.Get(url)
request.Cancellation(cancellation)
if tryCount > 1
request.TryCount(tryCount)
request.RetryCallback(function(context as object) as boolean
response = context.response
' In some cases, video info requests return "HTTP/0.9 when not allowed" errors.
' Retrying should usually fix the issue.
if response.StatusCode() = HttpClient.CurlErrors.CURLE_UNSUPPORTED_PROTOCOL
errorMessage = response.ErrorMessage()
if errorMessage.InStr("HTTP/0.9") <> -1
return true
end if
end if
return false
end function)
end if
request.RetryCount(retryCount)
' In some cases, video info requests return "HTTP/0.9 when not allowed" errors.
' Retrying should usually fix the issue.
request.RetryIf(function(response as HttpClient.Response) as string
errorMessage = response.ErrorMessage()
if response.StatusCode() = HttpClient.CurlErrors.CURLE_UNSUPPORTED_PROTOCOL and errorMessage.InStr("HTTP/0.9") <> -1
return errorMessage
end if
return ""
end function)
response = request.Await()
if not response.IsSuccess()
@@ -227,8 +219,8 @@ namespace Invidious
request = HttpClient.Get(url)
request.Cancellation(cancellation)
request.CacheSeconds(60 * 60 * 24)' 24 hours
request.TryCount(3)
request.CacheForSeconds(60 * 60 * 24)' 24 hours
request.RetryCount(2)
return request.Await()
end function
@@ -297,10 +289,6 @@ namespace Invidious
}
end if
instance = m.GetInstance()
request = HttpClient.Get(instance + endpoint.url)
profile = invalid
if endpoint.authenticated = true
@@ -315,11 +303,13 @@ namespace Invidious
error: ERROR_NOT_AUTHENTICATED
}
end if
request.Url(auth.serverUrl + endpoint.url)
request = HttpClient.Get(auth.serverUrl + endpoint.url)
request.Headers(m.GetAuthenticationHeaders(auth.token))
if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken)
end if
else
request = HttpClient.Get(m.GetInstance() + endpoint.url)
end if
if endpoint.queryParams <> invalid
@@ -342,15 +332,15 @@ namespace Invidious
end if
if feedSource.cacheSeconds <> invalid
request.CacheSeconds(feedSource.cacheSeconds)
request.CacheForSeconds(feedSource.cacheSeconds)
else if endpoint.cacheSeconds <> invalid
request.CacheSeconds(endpoint.cacheSeconds)
request.CacheForSeconds(endpoint.cacheSeconds)
end if
if feedSource.tryCount <> invalid
request.TryCount(feedSource.tryCount)
request.RetryCount(feedSource.tryCount - 1)
else if endpoint.tryCount <> invalid
request.TryCount(endpoint.tryCount)
request.RetryCount(endpoint.tryCount - 1)
end if
if feedSource.queryParams <> invalid
@@ -382,7 +372,7 @@ namespace Invidious
profile: profile
})
if response.IsSuccess() and result <> invalid
if result <> invalid
return {
success: true
result: result
@@ -396,32 +386,28 @@ namespace Invidious
end if
end function
function SendRequest(request as HttpClient.HttpRequest, httpServer as dynamic) as dynamic
function SendRequest(request as HttpClient.Request, httpServer as dynamic) as HttpClient.Response
if httpServer = invalid
return request.Await()
end if
url = request.BuildUrl()
url = request.GetFullUrl()
isUrlToLocalServer = url.StartsWith("http://127.0.0.1:8888") or url.StartsWith(m.invidiousNode.webServer@.GetServerAddress())
if not isUrlToLocalServer
return request.Await()
end if
parsedUrl = UrlUtils.ParseUrl(url)
method = request.GetMethod()
uri = parsedUrl.path
headers = request.GetHeaders()
body = ValidString(request.GetBody())
responseObj = httpServer.ProcessRequestLocal(method, uri, headers, body)
response = new HttpClient.HttpResponse(request, invalid)
response.OverrideStatusCode(responseObj.http_code)
response.OverrideHeaders(responseObj.headers)
responseObj = httpServer.ProcessRequestLocal(request.GetMethod(), parsedUrl.path, request.GetHeaders(), ValidString(request.GetTextBody()))
body = ""
if responseObj.body <> invalid
body = responseObj.body.ToAsciiString()
end if
response.OverrideText(body)
return response
return new HttpClient.Response({
statusCode: responseObj.http_code
headers: responseObj.headers
text: body
})
end function
function DefaultHandler(context as object) as object
@@ -450,7 +436,6 @@ namespace Invidious
if not response.IsSuccess()
' Similar to VideoInfoHandler, we can return a valid response
' in case of a deleted playlist.
response.OverrideStatusCode(200)
return {
isLastPage: true
items: [{
@@ -481,7 +466,6 @@ namespace Invidious
if not response.IsSuccess()
' Similar to VideoInfoHandler, we can return a valid response
' in case of a deleted channel.
response.OverrideStatusCode(200)
return {
isLastPage: true
items: [{
@@ -534,7 +518,6 @@ namespace Invidious
' with just a video id, which will allow us to show a valid thumbnail if possible.
' This is to makes it possible to load a bookmarked video and delete it even if
' it is no longer valid.
response.OverrideStatusCode(200)
return {
items: [{
"type": "video"
@@ -561,7 +544,6 @@ namespace Invidious
if not response.IsSuccess()
' Similar to VideoInfoHandler, we can return a valid response
' in case of a deleted playlist.
response.OverrideStatusCode(200)
return {
items: [{
"type": "playlist"
@@ -590,7 +572,6 @@ namespace Invidious
if not response.IsSuccess()
' Similar to VideoInfoHandler, we can return a valid response
' in case of a deleted channel.
response.OverrideStatusCode(200)
return {
items: [{
"type": "channel"
@@ -701,12 +682,12 @@ namespace Invidious
return json
end function
function MarkNeedsReauthIfCredentialsRejected(response as object, profile as object) as void
function MarkNeedsReauthIfCredentialsRejected(response as HttpClient.Response, profile as object) as void
if response.StatusCode() <> 403
return
end if
body = ValidString(response.Text())
body = response.Text()
LogWarn(`Invidious instance responded with 403: ${body}`)
if profile = invalid or profile.type <> "invidious"
return
@@ -743,7 +724,7 @@ namespace Invidious
function UnregisterToken(instance as string, token as string) as object
url = `${instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
request = HttpClient.Post(url, token)
request = HttpClient.Post(url).TextBody(token)
request.Headers(m.GetAuthenticationHeaders(token))
request.Header("Content-Type", "application/json")
@@ -787,7 +768,7 @@ namespace Invidious
function Subscribe(auth as ProfileContentAuthTokenUtils.AccessTokenResult, channelId as string, cancellation = invalid as object) as object
url = `${auth.serverUrl}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Post(url, "")
request = HttpClient.Post(url)
if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken)
end if
@@ -38,7 +38,7 @@ class LoungeApi
private ofs
private lastProcessedCommandIndex = -1
private backchannel
private outgoingMessagesRequests
private pendingOutgoingMessages
function new(loungeServiceNode as object, videoQueueNode as object, notificationsNode as object, invidiousNode as object)
m.loungeServiceNode = loungeServiceNode
@@ -52,7 +52,7 @@ class LoungeApi
m.screenName = deviceName
m.ofs = 0
m.backchannel = invalid
m.outgoingMessagesRequests = {}
m.pendingOutgoingMessages = []
m.devices = {}
commandHandlers = {}
@@ -144,8 +144,8 @@ class LoungeApi
return m.loungeToken
end if
request = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/get_lounge_token_batch", "")
request.UrlEncodedForm({
request = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/get_lounge_token_batch")
request.FormBody({
"screen_ids": m.screenId
})
@@ -195,9 +195,9 @@ class LoungeApi
queryParams["loungeIdToken"] = m.loungeToken
queryParams["zx"] = m.Zx()
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind", "")
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams)
request.UrlEncodedForm({
request.FormBody({
"count": 0
})
@@ -599,25 +599,20 @@ class LoungeApi
LogDebug("Sending messages:", postData)
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind", "")
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams)
request.UrlEncodedForm(postData)
request.Send()
' we do not need to wait for requests to finish, we check on them later
' to avoid blocking the thread.
' This is specific to sent lounge messages, since we're not waiting for a response.
requestId = request.urlTransfer.GetIdentity().ToStr()
m.outgoingMessagesRequests[requestId] = request
request.FormBody(postData)
m.pendingOutgoingMessages.Push(request.Send())
end function
function ProcessPendingOutgoingMessages() as object
results = []
for each key in m.outgoingMessagesRequests
request = m.outgoingMessagesRequests[key]
if request.IsCompleted()
response = request.Await()
stillPending = []
for each pending in m.pendingOutgoingMessages
response = pending.Poll()
if response = invalid
stillPending.Push(pending)
else
status = response.StatusCode()
error = response.ErrorMessage()
@@ -651,10 +646,9 @@ class LoungeApi
})
end if
end if
m.outgoingMessagesRequests.Delete(key)
end if
end for
m.pendingOutgoingMessages = stillPending
return results
end function
@@ -42,8 +42,8 @@ function ExecuteJob() as void
form["app"] = "Playlet"
cancellation = JobGetCancellation()
request = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/get_pairing_code?ctx=pair", "")
request.UrlEncodedForm(form)
request = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/get_pairing_code?ctx=pair")
request.FormBody(form)
request.Cancellation(cancellation)
response = request.Await()
@@ -62,7 +62,7 @@ namespace SponsorBlock
end if
url = `${serverAddress}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}`
HttpClient.Post(url, "").Cancellation(cancellation).Await()
HttpClient.Post(url).Cancellation(cancellation).Await()
end function
function GenerateProgressBarBackground(segments as object, timeline as SponsorBlockTimeline, lengthSeconds as integer, path as string)
@@ -9,32 +9,32 @@ namespace Sentry
function SendEvents(events as object) as integer
payload = BuildEnvelope(events, false)
request = HttpClient.Post(SUPPORT_SERVER_ENVELOPE_URL, payload)
request = HttpClient.Post(SUPPORT_SERVER_ENVELOPE_URL).TextBody(payload)
request.Header("Content-Type", "application/x-sentry-envelope")
response = request.Await()
' Only when the server never answered: its own failures hit every device at once and would exhaust the fallback's quota
if response.StatusCode() <= 0
LogWarnNoTelemetry("Support server unreachable, sending events to the Sentry fallback:", response.ErrorMessage())
request = HttpClient.Post(SENTRY_FALLBACK_ENVELOPE_URL, BuildEnvelope([CreateSupportServerUnreachableEvent(events[0], payload, response.ErrorMessage())], true))
request = HttpClient.Post(SENTRY_FALLBACK_ENVELOPE_URL).TextBody(BuildEnvelope([CreateSupportServerUnreachableEvent(events[0], payload, response.ErrorMessage())], true))
request.Header("Content-Type", "application/x-sentry-envelope")
request.QueryParam("sentry_key", SENTRY_FALLBACK_KEY)
response = request.Await()
end if
if response.IsSuccess()
LogDebug("Sent events to", request.BuildUrl(), "Response:", response.Text())
LogDebug("Sent events to", request.GetFullUrl(), "Response:", response.Text())
return 0
end if
retryAfter = ValidString(response.Headers()["Retry-After"]).ToInt()
if retryAfter = 0
retryAfter = response.RetryAfterSeconds()
if retryAfter = invalid or retryAfter = 0
retryAfter = 60
end if
if response.StatusCode() = 429
LogErrorNoTelemetry("Rate limited by", request.BuildUrl(), "Retry after", retryAfter, "seconds")
LogErrorNoTelemetry("Rate limited by", request.GetFullUrl(), "Retry after", retryAfter, "seconds")
else
LogErrorNoTelemetry("Failed to send events to", request.BuildUrl(), response.ErrorMessage(), `\nRetry after`, retryAfter, "seconds")
LogErrorNoTelemetry("Failed to send events to", request.GetFullUrl(), response.ErrorMessage(), `\nRetry after`, retryAfter, "seconds")
end if
return retryAfter
end function
@@ -1,3 +1,4 @@
import "pkg:/components/Services/Dash/LiveHeadCounts.bs"
import "pkg:/components/VideoPlayerDev/VideoNode.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Locale.bs"
@@ -105,6 +106,8 @@ namespace PlaybackTelemetry
private healSamples as object = invalid
private tailResolveCount as integer = 0
private tailResolveSamples as object = invalid
private startSegmentBitrateBps as integer = 0
private startMeasuredBitrateBps as integer = 0
function new(deps as object)
m.playerTimer = deps.playerTimer
@@ -128,6 +131,7 @@ namespace PlaybackTelemetry
m.span = PlaybackTelemetry.Span.Playing
if m.firstPlayingAtMs < 0
m.firstPlayingAtMs = nowMs
m.startMeasuredBitrateBps = ValidInt(ValidAssociativeArray(m.top.streamInfo).measuredBitrate)
end if
' playing under an error dialog: the playback recovered, so the error did not end it.
if m.outcome = PlaybackTelemetry.Outcome.Error
@@ -170,6 +174,18 @@ namespace PlaybackTelemetry
end if
end function
' True once the first segment carrying video started streaming: its bitrate is the one kept.
function OnStreamingSegment(segment as object) as boolean
if segment = invalid or not IsInt(segment.segType)
return false
end if
if segment.segType <> SegmentType.Mux and segment.segType <> SegmentType.Video
return false
end if
m.startSegmentBitrateBps = ValidInt(segment.segBitrateBps)
return true
end function
function OnErrorDialog() as void
m.outcome = PlaybackTelemetry.Outcome.Error
end function
@@ -328,13 +344,20 @@ namespace PlaybackTelemetry
"tail_resolve_count": m.tailResolveCount
"tail_resolve_samples": m.tailResolveSamples
}
if m.transport.isLive
liveHead = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH))
if liveHead <> invalid and liveHead["video_load_id"] = summary["video_load_id"]
summary["live_head"] = liveHead["counts"]
DeleteFile(LIVE_HEAD_COUNTS_PATH)
end if
summary["start_segment_bitrate_bps"] = m.startSegmentBitrateBps
summary["start_measured_bitrate_bps"] = m.startMeasuredBitrateBps
end if
if content <> invalid
summary["video_id"] = content.videoId
summary["stream_source"] = content.playletStreamSource
summary["drm"] = not StringUtils.IsNullOrEmpty(ValidAssociativeArray(content.drmParams).keySystem)
summary["stream_url_index"] = content.playletStreamUrlIndex
if m.firstPlayingAtMs < 0 or m.underrunCount > 0 or m.bufferingsWithoutStatusCount > 0 or m.isUnderrunChangeCount > 0 or m.errorCount > 0 or m.healCount > 0 or m.outcome = PlaybackTelemetry.Outcome.Error
summary["video_id"] = content.videoId
end if
end if
LogTelemetryEvent({
level: "info"
@@ -1,5 +1,5 @@
' The Roku Video node's `state` and `control` field values (see Video node reference). String-valued so members
' compare and assign directly against m.top.state / m.top.control.
' compare and assign directly against m.top.state / m.top.control. SegmentType is `streamingSegment.segType`.
enum VideoState
None = "none"
@@ -22,3 +22,10 @@ enum VideoControl
Prebuffer = "prebuffer"
SkipContent = "skipcontent"
end enum
enum SegmentType
Mux = 0
Audio = 1
Video = 2
Captions = 3
end enum
@@ -171,6 +171,7 @@ function OnNodeReady()
m.top.ObserveField("setSeek", FuncName(OnSetSeek))
m.top.ObserveField("bufferingStatus", FuncName(OnBufferingStatus))
m.top.ObserveField("playStartInfo", FuncName(OnPlayStartInfo))
m.top.ObserveField("streamingSegment", FuncName(OnStreamingSegment))
' a player that starts minimized shows the PiP hint (1s after the shrink settles, auto-hides after 5s).
m.showFullScreenHint = not m.container.fullscreen
@@ -805,6 +806,16 @@ function OnPlayStartInfo(event as object) as void
m.playbackTelemetry.OnPlayStartInfo(event.getData())
end function
' Only the first video segment is wanted: no callback per segment for the rest of the play.
function OnStreamingSegment(event as object) as void
if m.onCloseCalled = true
return
end if
if m.playbackTelemetry.OnStreamingSegment(event.getData())
m.top.unobserveField("streamingSegment")
end if
end function
' A transport freezes the video; if the device is playing under an active transport (Roku resumes a paused
' Video on a seek, or a freeze command was dropped), re-pause. The transport stays active so the bif stays
' visible over the now-paused video. Called from OnVideoState (the change edge) and OnPosition (the net —
@@ -1506,6 +1517,7 @@ function OnClose() as void
m.top.unobserveField("setSeek")
m.top.unobserveField("bufferingStatus")
m.top.unobserveField("playStartInfo")
m.top.unobserveField("streamingSegment")
m.top.unobserveField("close")
content = m.top.content
if content <> invalid
@@ -73,7 +73,7 @@ function TestSetup() as void
' nudge counter above — stacked observers fire a handler once per prior TestSetup on every write,
' and OnPosition's latency learning reads two identical fires as a CONFIRMED min-gap, poisoning
' LiveEdgeMs for any live test that runs after another test in the suite.
for each deviceField in ["state", "position", "duration", "close", "thumbnailTiles", "control", "setSeek", "bufferingStatus", "playStartInfo"]
for each deviceField in ["state", "position", "duration", "close", "thumbnailTiles", "control", "setSeek", "bufferingStatus", "playStartInfo", "streamingSegment"]
m.top.unobserveField(deviceField)
end for
@@ -28,6 +28,8 @@
<field id="errorInfo" type="assocarray" />
<field id="bufferingStatus" type="assocarray" alwaysNotify="true" />
<field id="playStartInfo" type="assocarray" alwaysNotify="true" />
<field id="streamingSegment" type="assocarray" alwaysNotify="true" />
<field id="streamInfo" type="assocarray" />
<!-- AutoBind deps + layout (set by TestSetup; NOT bound). -->
<field id="appController" type="node" />
<field id="jobQueue" type="node" />
@@ -1,7 +1,6 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/MathUtils.bs"
@@ -28,9 +27,8 @@ function ExecuteJob() as void
end if
requestOptions = {
cacheSeconds: 8640000 ' 100 days
cancellation: cancellation
tryCount: 1
retryCount: 0
fetchNext: false
visitorData: visitorData
}
@@ -1,4 +1,6 @@
import "pkg:/components/Services/Dash/DashManifest.bs"
import "pkg:/components/Services/Dash/LiveHeadChecks.bs"
import "pkg:/components/Services/Dash/LiveHeadCounts.bs"
import "pkg:/components/Services/Dash/LiveTimeline.types.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
@@ -10,8 +12,6 @@ import "pkg:/source/utils/Types.bs"
' Manifest requests closer together than this (Roku re-fetching after an error) share one live head check.
const LIVE_HEAD_MIN_INTERVAL_MS = 500
' The manifest response waits on the head check; past this it lists the last known head.
const LIVE_HEAD_TIMEOUT_SECONDS = 2
' Head time leaping this far past the listed timeline within one head check is a stall.
const LIVE_STALL_JUMP_MS = 10000
@@ -40,6 +40,7 @@ namespace Http
m.cachedMetadata = invalid
m.liveHeadUrl = ""
m.liveHeadTimer = invalid ' since the last head check; invalid = never checked
m.liveHeadChecks = invalid
m.liveHeadSeqnum = 0
m.liveLoadHeadSeqnum = 0
m.liveLoadHeadTimeMs = invalid
@@ -175,8 +176,7 @@ namespace Http
return true
end if
dashRequest = HttpClient.Get(url)
dashResponse = dashRequest.Await()
dashResponse = HttpClient.Get(url).Await()
if not dashResponse.IsSuccess()
LogError("Failed to fetch DASH manifest from URL", dashResponse.ErrorMessage())
@@ -184,7 +184,7 @@ namespace Http
return true
end if
dashContent = ValidString(dashResponse.Text())
dashContent = dashResponse.Text()
storyboardIndex = dashContent.InStr("</Period>")
if storyboardIndex = -1
response.Redirect(url)
@@ -229,8 +229,8 @@ namespace Http
return xmlContent
end function
' Raise the live head to the stream's newest segment. On failure the timeline
' keeps its end, and the player holds at it until a later check succeeds.
' Raise the live head to the newest one answered. Until a check answers with a newer head, the
' timeline keeps its end and the player holds at it.
function RefreshLiveHead() as void
if StringUtils.IsNullOrEmpty(m.liveHeadUrl)
return
@@ -242,28 +242,21 @@ namespace Http
end if
m.liveHeadTimer.Mark()
head = m.CheckLiveHead()
if head.seqnum < 0
m.ReportLiveHeadFailure(head.response)
return
end if
' Listed segments can't be withdrawn: the head only moves forward.
if head.seqnum > m.liveHeadSeqnum
m.AlignLiveTimeline(head)
m.liveHeadSeqnum = head.seqnum
end if
end function
newest = invalid
for each head in m.liveHeadChecks.Refresh()
if head.seqnum < 0
m.ReportLiveHeadFailure(head.response)
else if newest = invalid or head.seqnum > newest.seqnum
newest = head
end if
end for
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": m.cachedVideoLoadId, "counts": m.liveHeadChecks.counts }))
' A no-sq HEAD: googlevideo answers at once with the X-Head-* headers.
function CheckLiveHead() as LiveHeadReading
request = Innertube.CreateLiveHeadRequest(m.liveHeadUrl)
request.TimeoutSeconds(LIVE_HEAD_TIMEOUT_SECONDS)
response = request.Await()
return {
seqnum: Innertube.ReadLiveHeadSeqnum(response)
timeMs: Innertube.ReadLiveHeadTimeMs(response)
response: response
}
' Listed segments can't be withdrawn: the head only moves forward.
if newest <> invalid and newest.seqnum > m.liveHeadSeqnum
m.AlignLiveTimeline(newest)
m.liveHeadSeqnum = newest.seqnum
end if
end function
' Segments are listed at the duration at load, the stream's lifetime average: off
@@ -353,11 +346,10 @@ namespace Http
})
end function
' Until a head check succeeds, the listed timeline stops growing and the player
' holds at its end. Telemetry once per video load.
function ReportLiveHeadFailure(response as object) as void
' Telemetry once per video load.
function ReportLiveHeadFailure(response as HttpClient.Response) as void
statusText = Str(response.StatusCode()).Trim()
LogWarnNoTelemetry("Live head check returned no X-Head-Seqnum (HTTP", statusText, "); head stays at", m.liveHeadSeqnum)
LogWarnNoTelemetry("Live head check returned no X-Head-Seqnum (HTTP", statusText, ")")
if m.reportedLiveHeadFailure
return
end if
@@ -375,7 +367,7 @@ namespace Http
`video_load_id: ${ValidString(m.cachedVideoLoadId)}`
`head: ${m.liveHeadSeqnum}`
`status: ${statusText}`
`error: ${response.ErrorMessage(false)}`
`error: ${response.ErrorMessage()}`
`url: ${m.liveHeadUrl}`
].Join(`\n`)
}]
@@ -384,6 +376,10 @@ namespace Http
function ResetLiveState(metadata as object) as void
m.liveHeadUrl = ValidString(metadata.liveHeadUrl)
if m.liveHeadChecks <> invalid
m.liveHeadChecks.Cancel()
end if
m.liveHeadChecks = new LiveHeadChecks(m.liveHeadUrl)
m.liveHeadTimer = invalid
m.liveHeadSeqnum = ValidInt(metadata.liveHeadSeqnum)
m.liveLoadHeadSeqnum = m.liveHeadSeqnum
@@ -81,8 +81,8 @@ namespace Http
end if
end if
req = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/register_pairing_code", "")
req.UrlEncodedForm({
req = HttpClient.Post("https://www.youtube.com/api/lounge/pairing/register_pairing_code")
req.FormBody({
"pairing_code": pairingCode
"screen_id": m.loungeService.screenId
"screen_name": m.deviceName
@@ -128,8 +128,23 @@ namespace Http
requestHeaders["User-Agent"] = VIDEO_PLAYER_USER_AGENT
end if
httpReq = HttpClient.FromObject(requestArgs)
httpRes = httpReq.Await()
method = "GET"
if requestArgs.Method <> invalid
method = requestArgs.Method
end if
proxyRequest = new HttpClient.Request(method, requestArgs.Url)
proxyRequest.Headers(requestHeaders)
if requestArgs.Body <> invalid
proxyRequest.TextBody(requestArgs.Body)
end if
if requestArgs.CacheSeconds <> invalid
if requestArgs.CacheSeconds > 0
proxyRequest.CacheForSeconds(requestArgs.CacheSeconds)
else
proxyRequest.NoCache()
end if
end if
httpRes = proxyRequest.Await()
result = {
"status": httpRes.StatusCode()
@@ -0,0 +1,13 @@
import "pkg:/source/services/HttpClient.bs"
' Awaits url on this task's thread, as a job does, cancellable through cancellationNode.cancel.
function Init()
m.top.functionName = "AwaitUrl"
end function
function AwaitUrl() as void
cancellation = CancellationUtils.CreateCancellation(m.top.cancellationNode, "cancel", true)
pending = HttpClient.Get(m.top.url).Cancellation(cancellation).Send()
m.top.sending = true
m.top.cancelled = pending.Await().IsCancelled()
end function
@@ -0,0 +1,9 @@
<component name="AwaitInTask" extends="Task">
<interface>
<field id="url" type="string" />
<!-- owned by the thread that made it, so cancelling it reaches this task from another thread -->
<field id="cancellationNode" type="node" />
<field id="sending" type="boolean" />
<field id="cancelled" type="boolean" />
</interface>
</component>
@@ -0,0 +1,17 @@
' Sets cancellationNode.cancel cancelAfterMs after that field is set, while the caller's thread blocks.
function Init()
m.top.functionName = "CancelLater"
end function
function CancelLater() as void
node = CreateObject("roSGNode", "Node")
node.addField("cancel", "boolean", false)
port = CreateObject("roMessagePort")
m.top.ObserveField("cancelAfterMs", port)
m.top.cancellationNode = node
' Waiting on the port lets other threads rendezvous with this one.
while type(wait(0, port)) <> "roSGNodeEvent"
end while
wait(m.top.cancelAfterMs, port)
node.cancel = true
end function
@@ -0,0 +1,7 @@
<component name="CancelLaterTask" extends="Task">
<interface>
<!-- owned by this task's thread, so setting its cancel field needs no other thread -->
<field id="cancellationNode" type="node" />
<field id="cancelAfterMs" type="integer" alwaysNotify="true" />
</interface>
</component>
@@ -0,0 +1,220 @@
import "pkg:/source/utils/Types.bs"
' Responds to one request per connection, by path:
' /status/<code> the status
' /seq/<id>/<code>,<code>,... the next status in the list for that path, then its last one;
' <code>@<ms> responds after <ms>
' /delay/<ms> 200 after <ms>
' /echo 200 with the request's { method, path, headers, body } as JSON
' /maxage/<seconds>/<id> 200 with Cache-Control: max-age=<seconds>
' A path in routes (its query aside) responds as its route says instead: { status, headers, body, delayMs }.
' A route { drop: true } closes the connection without a response.
' Every response carries X-Hit, the request's count for its path. Connections are read and responded to
' without blocking each other, so a slow or abandoned one holds up nothing.
' The last request read is in lastRequest: { method, path, headers, body }.
' Roku's roUrlTransfer sometimes never completes when the whole response and the close reach it over
' loopback within a millisecond of its request (9 of 8000 such requests; 0 of 16000 at 5ms or 20ms).
const MIN_RESPONSE_DELAY_MS = 5
' A connection whose request isn't complete by then is dropped.
const READ_TIMEOUT_MS = 2000
function Init()
m.top.functionName = "Serve"
end function
function Serve() as void
messagePort = CreateObject("roMessagePort")
listener = CreateObject("roStreamSocket")
listener.SetReuseAddr(true)
address = CreateObject("roSocketAddress")
address.SetAddress(`127.0.0.1:${m.top.port}`)
listener.SetAddress(address)
listener.SetMessagePort(messagePort)
listener.NotifyReadable(true)
if not listener.Listen(8)
return
end if
m.top.ObserveField("shouldQuit", messagePort)
m.hits = {}
m.clock = CreateObject("roTimespan")
reading = []
responses = []
m.top.isRunning = true
while true
' 0: no deadline, wait for the next socket event.
waitMs = 0
for each item in reading
waitMs = ShorterWaitMs(waitMs, item.sinceMs + READ_TIMEOUT_MS)
end for
for each response in responses
waitMs = ShorterWaitMs(waitMs, response.sendAtMs)
end for
message = wait(waitMs, messagePort)
if type(message) = "roSGNodeEvent"
exit while
end if
if listener.IsReadable()
connection = listener.Accept()
while connection <> invalid
connection.SetMessagePort(messagePort)
connection.NotifyReadable(true)
reading.Push({ connection: connection, data: "", byteCount: 0, sinceMs: m.clock.TotalMilliseconds() })
connection = listener.Accept()
end while
end if
stillReading = []
for each item in reading
connection = item.connection
closed = false
if connection.IsReadable()
count = connection.GetCountRcvBuf()
if count > 0
' ReceiveStr ends at a NUL byte; a binary body is counted in bytes, read as text up to its first NUL.
bytes = CreateObject("roByteArray")
bytes[count - 1] = 0
item.byteCount += connection.Receive(bytes, 0, count)
item.data += bytes.ToAsciiString()
else
' Readable with nothing to read: the peer closed.
closed = true
end if
end if
response = BuildResponse(item)
if response <> invalid
connection.NotifyReadable(false)
responses.Push(response)
else if closed or m.clock.TotalMilliseconds() - item.sinceMs >= READ_TIMEOUT_MS
connection.Close()
else
stillReading.Push(item)
end if
end for
reading = stillReading
unsent = []
for each response in responses
if response.sendAtMs <= m.clock.TotalMilliseconds()
response.connection.SendStr(response.text)
response.connection.Close()
else
unsent.Push(response)
end if
end for
responses = unsent
end while
for each item in reading
item.connection.Close()
end for
for each response in responses
response.connection.Close()
end for
listener.Close()
m.top.isRunning = false
end function
' The wait until deadlineMs, or waitMs if that is shorter; 0 means no wait limit yet.
function ShorterWaitMs(waitMs as integer, deadlineMs as integer) as integer
untilDeadlineMs = deadlineMs - m.clock.TotalMilliseconds()
if untilDeadlineMs < 1
untilDeadlineMs = 1
end if
if waitMs = 0 or untilDeadlineMs < waitMs
return untilDeadlineMs
end if
return waitMs
end function
' The response to the connection's request and when to send it, or invalid until the request is complete.
function BuildResponse(item as object) as object
headEnd = item.data.InStr(`\r\n\r\n`)
if headEnd = -1
return invalid
end if
head = item.data.Left(headEnd)
headers = {}
for each line in head.Split(`\r\n`)
colon = line.InStr(":")
if colon > 0
headers[LCase(line.Left(colon))] = line.Mid(colon + 1).Trim()
end if
end for
requestBody = item.data.Mid(headEnd + 4)
if item.byteCount - headEnd - 4 < ValidString(headers["content-length"]).ToInt()
return invalid
end if
requestLine = head.Split(`\r\n`)[0].Split(" ")
if requestLine.Count() < 2
return invalid
end if
method = requestLine[0]
path = requestLine[1]
m.hits[path] = ValidInt(m.hits[path]) + 1
hit = m.hits[path]
m.top.hits = m.hits
request = { method: method, path: path, headers: headers, body: requestBody }
m.top.lastRequest = request
delayMs = MIN_RESPONSE_DELAY_MS
route = ValidAssociativeArray(m.top.routes)[path.Split("?")[0]]
if route <> invalid
if ValidInt(route.delayMs) > delayMs
delayMs = route.delayMs
end if
if route.drop = true
return { connection: item.connection, text: "", sendAtMs: m.clock.TotalMilliseconds() + delayMs }
end if
text = `HTTP/1.1 ${route.status} Test\r\nContent-Length: ${ValidString(route.body).Len()}\r\nX-Hit: ${hit}\r\nConnection: close\r\n`
for each name in ValidAssociativeArray(route.headers)
text += `${name}: ${route.headers[name]}\r\n`
end for
text += `\r\n`
if method <> "HEAD"
text += ValidString(route.body)
end if
return { connection: item.connection, text: text, sendAtMs: m.clock.TotalMilliseconds() + delayMs }
end if
status = 404
segments = path.Split("?")[0].Split("/")
if segments.Count() = 3 and segments[1] = "status"
status = segments[2].ToInt()
else if segments.Count() = 4 and segments[1] = "seq"
codes = segments[3].Split(",")
index = hit - 1
if index >= codes.Count()
index = codes.Count() - 1
end if
entry = codes[index].Split("@")
status = entry[0].ToInt()
if entry.Count() > 1
delayMs = entry[1].ToInt()
end if
else if segments.Count() = 3 and segments[1] = "delay"
delayMs = segments[2].ToInt()
status = 200
else if segments.Count() = 2 and segments[1] = "echo"
status = 200
else if segments.Count() = 4 and segments[1] = "maxage"
status = 200
end if
body = `hit ${hit}`
extraHeaders = ""
if segments[1] = "echo"
body = FormatJson(request)
else if segments[1] = "maxage"
extraHeaders = `Cache-Control: max-age=${segments[2]}\r\n`
end if
text = `HTTP/1.1 ${status} Test\r\nContent-Type: text/plain\r\nContent-Length: ${body.Len()}\r\nX-Hit: ${hit}\r\n${extraHeaders}Connection: close\r\n\r\n`
if method <> "HEAD"
text += body
end if
return { connection: item.connection, text: text, sendAtMs: m.clock.TotalMilliseconds() + delayMs }
end function
@@ -0,0 +1,11 @@
<component name="HttpTestServer" extends="Task">
<interface>
<field id="port" type="integer" value="54124" />
<field id="isRunning" type="boolean" />
<!-- request count per /seq id -->
<field id="hits" type="assocarray" />
<field id="routes" type="assocarray" />
<field id="lastRequest" type="assocarray" />
<field id="shouldQuit" type="boolean" alwaysNotify="true" />
</interface>
</component>
@@ -0,0 +1,19 @@
import "pkg:/source/services/HttpClient.bs"
' Polls url's response on this task's thread without ever waiting on a port, cancellable through cancellationNode.cancel.
function Init()
m.top.functionName = "PollUrl"
end function
function PollUrl() as void
cancellation = CancellationUtils.CreateCancellation(m.top.cancellationNode, "cancel", true)
pending = HttpClient.Get(m.top.url).Cancellation(cancellation).Send()
m.top.sending = true
response = invalid
timer = CreateObject("roTimespan")
while response = invalid and timer.TotalMilliseconds() < 5000
response = pending.Poll()
sleep(10)
end while
m.top.cancelled = response <> invalid and response.IsCancelled()
end function
@@ -0,0 +1,9 @@
<component name="PollInTask" extends="Task">
<interface>
<field id="url" type="string" />
<!-- owned by the thread that made it, so cancelling it reaches this task from another thread -->
<field id="cancellationNode" type="node" />
<field id="sending" type="boolean" />
<field id="cancelled" type="boolean" />
</interface>
</component>
@@ -42,6 +42,26 @@ namespace Tests
m.assertFalse(StringUtils.IsNullOrEmpty(api.gSessionId), "no gSessionId after rebind")
end function
@slow(30000)
@it("sends the messages a bind calls for, and reports each one's status once it completes")
function _()
api = m.CreateLiveApi()
api.GetScreenId()
api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed")
results = []
timer = CreateObject("roTimespan")
while results.Count() = 0 and timer.TotalMilliseconds() < 10000
results.Append(api.ProcessPendingOutgoingMessages())
sleep(50)
end while
m.assertNotEmpty(results, "no outgoing message completed")
for each result in results
m.assertEqual(result.status, 200, result.error)
end for
end function
private function CreateLiveApi() as object
loungeServiceNode = CreateObject("roSGNode", "Node")
loungeServiceNode.addFields({
@@ -22,6 +22,18 @@ namespace Tests
m.assertFalse(Innertube.IsTerminalRefreshError(invalid))
end function
@describe("Innertube.RefreshRetryReason")
@it("Retries a failed refresh with its error, unless the token endpoint rejected the credential or the client")
function _()
transient = new HttpClient.Response({ statusCode: 503, text: `{"error":"backend_error"}` })
m.assertEqual(Innertube.RefreshRetryReason(transient), transient.ErrorMessage())
m.assertNotEqual(transient.ErrorMessage(), "")
m.assertEqual(Innertube.RefreshRetryReason(new HttpClient.Response({ statusCode: 400, text: `{"error":"invalid_grant"}` })), "")
m.assertEqual(Innertube.RefreshRetryReason(new HttpClient.Response({ statusCode: 401, text: `{"error":"invalid_client"}` })), "")
m.assertEqual(Innertube.RefreshRetryReason(new HttpClient.Response({ statusCode: 200, text: `{"access_token":"ya29.abc"}` })), "")
end function
end class
end namespace
@@ -0,0 +1,104 @@
import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
' Responses to GET requests, kept on disk until they expire. An entry is one file: a JSON line
' { expiresAt, statusCode, headers }, then the body as is.
namespace HttpCache
' An entry per url, headers and file the body is saved to.
function GetFilePath(url as string, headers as object, bodyFilePath as dynamic) as string
key = url + FormatJson(headers)
if bodyFilePath <> invalid
key += bodyFilePath
end if
return `cachefs:/request_v3_${CryptoUtils.GetMd5(key)}.json`
end function
' The entry as { statusCode, headers, text }; invalid when there is none, it expired, or the file its body was
' saved to is gone. Such an entry, or a corrupt one, is deleted; a corrupt one warns, whether its body file exists
' or not.
function Read(filePath as string, bodyFilePath as dynamic) as dynamic
' ReadAsciiFile prints an error to the console for a file that doesn't exist.
fileSystem = CreateObject("roFileSystem")
if fileSystem = invalid or not fileSystem.Exists(filePath)
return invalid
end if
text = ReadAsciiFile(filePath)
metadataEnd = text.InStr(`\n`)
if metadataEnd = -1
LogWarn("Failed to parse cache.")
DeleteFile(filePath)
return invalid
end if
metadata = StringUtils.ParseJsonSafe(text.Left(metadataEnd))
if not IsAssociativeArray(metadata) or not IsInt(metadata.expiresAt) or not IsInt(metadata.statusCode)
LogWarn("Failed to parse metadata from cache.")
DeleteFile(filePath)
return invalid
end if
if not IsAssociativeArray(metadata.headers)
LogWarn("Failed to parse headers from cache.")
DeleteFile(filePath)
return invalid
end if
if metadata.expiresAt < CreateObject("roDateTime").AsSeconds()
DeleteFile(filePath)
return invalid
end if
if bodyFilePath <> invalid and not fileSystem.Exists(bodyFilePath)
DeleteFile(filePath)
return invalid
end if
' ParseJson's keys are case-sensitive; a response's headers aren't.
headers = {}
headers.Append(metadata.headers)
return {
statusCode: metadata.statusCode
headers: headers
text: text.Mid(metadataEnd + 1)
}
end function
' cacheSeconds: invalid for the headers' Cache-Control max-age; without one, nothing is written.
function Write(filePath as string, cacheSeconds as dynamic, statusCode as integer, headers as object, body as string) as void
if cacheSeconds = invalid
cacheSeconds = ParseMaxAgeSeconds(headers)
if cacheSeconds = invalid
return
end if
end if
metadata = FormatJson({
expiresAt: CreateObject("roDateTime").AsSeconds() + cacheSeconds
statusCode: statusCode
headers: headers
})
WriteAsciiFile(filePath, metadata + `\n` + body)
end function
' Cache-Control's max-age, invalid when absent or when no-store/no-cache forbid caching.
function ParseMaxAgeSeconds(headers as object) as dynamic
cacheControl = headers["cache-control"]
if not IsString(cacheControl)
return invalid
end if
maxAgeSeconds = invalid
for each directive in cacheControl.Split(",")
parts = directive.Trim().Split("=")
name = LCase(parts[0].Trim())
if name = "no-store" or name = "no-cache"
return invalid
else if name = "max-age" and parts.Count() > 1
maxAgeSeconds = parts[1].Trim().ToInt()
end if
end for
if maxAgeSeconds = invalid or maxAgeSeconds <= 0
return invalid
end if
return maxAgeSeconds
end function
end namespace
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,36 @@
import "pkg:/source/utils/Types.bs"
namespace Tests
const HTTP_TEST_SERVER_PORT = 54125
function StartHttpTestServer() as object
server = CreateObject("roSGNode", "HttpTestServer")
server.port = HTTP_TEST_SERVER_PORT
server.control = "run"
timer = CreateObject("roTimespan")
while server.isRunning <> true and timer.TotalMilliseconds() < 3000
sleep(10)
end while
return server
end function
function StopHttpTestServer(server as object) as void
server.shouldQuit = true
timer = CreateObject("roTimespan")
while server.isRunning = true and timer.TotalMilliseconds() < 3000
sleep(10)
end while
end function
function HttpTestServerUrl(path as string) as string
return `http://127.0.0.1:${HTTP_TEST_SERVER_PORT}${path}`
end function
' How many requests the server answered for a path or url, its query included.
function HttpTestServerHits(server as object, pathOrUrl as string) as integer
path = pathOrUrl.Replace(HttpTestServerUrl(""), "")
return ValidInt(ValidAssociativeArray(server.hits)[path])
end function
end namespace
@@ -20,4 +20,23 @@ namespace Tests
return logLevel
end function
' The lines logged while action(subject) runs.
function LogLines(action as function, subject as dynamic) as string[]
logPort = CreateObject("roMessagePort")
m.global.logger.ObserveFieldScoped("logLine", logPort)
action(subject)
m.global.logger.UnobserveFieldScoped("logLine")
lines = [] as string[]
message = logPort.GetMessage()
while message <> invalid
lines.Push(message.GetData())
message = logPort.GetMessage()
end while
return lines
end function
function LogLineMessage(line as string) as string
return line.Mid(line.InStr(" ") + 1).Replace(Chr(27) + "[0m", "")
end function
end namespace
@@ -0,0 +1,228 @@
import "pkg:/components/Services/Dash/LiveHeadChecks.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
import "pkg:/source/tests/Services/Dash/LiveHeadFakes.bs"
namespace Tests
@suite
class LiveHeadChecksTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
end function
function NewChecks(answers as object) as object
checks = new LiveHeadChecks("https://example.googlevideo.com/videoplayback?rn=0")
Tests.FakeLiveHeadChecks(checks, answers)
return checks
end function
function Seqnums(heads as object) as object
seqnums = []
for each head in heads
seqnums.Push(head.seqnum)
end for
return seqnums
end function
@describe("LiveHeadChecks.Refresh")
@it("returns a check answered within the wait at once")
function _()
checks = m.NewChecks([{ seqnum: 10, timeMs: 18630 }])
m.assertEqual(m.Seqnums(checks.Refresh()), [10])
m.assertEqual(checks.counts["answered_after_wait"], 0)
end function
@it("keeps a check unanswered within the wait in flight, and returns it at the refresh after its answer")
function _()
checks = m.NewChecks([{ seqnum: 10, timeMs: 18630, pending: true }, { seqnum: 11, timeMs: 20630, pending: true }])
m.assertEmpty(checks.Refresh())
Tests.AnswerLiveHeadChecks(checks)
m.assertEqual(m.Seqnums(checks.Refresh()), [10])
m.assertEqual(checks.counts["answered_after_wait"], 1)
m.assertEqual(checks.inFlight.Count(), 1)
end function
@it("sends no check while LIVE_HEAD_MAX_CHECKS_IN_FLIGHT are in flight")
function _()
answers = []
for i = 0 to LIVE_HEAD_MAX_CHECKS_IN_FLIGHT
answers.Push({ seqnum: 10 + i, timeMs: 18630, pending: true })
end for
checks = m.NewChecks(answers)
for i = 0 to LIVE_HEAD_MAX_CHECKS_IN_FLIGHT
checks.Refresh()
end for
m.assertEqual(checks.counts["checks_sent"], LIVE_HEAD_MAX_CHECKS_IN_FLIGHT)
end function
@it("sends a check at the refresh that collects a check given up")
function _()
answers = []
for i = 1 to LIVE_HEAD_MAX_CHECKS_IN_FLIGHT + 1
answers.Push({ seqnum: -1, timeMs: invalid, pending: true })
end for
checks = m.NewChecks(answers)
for i = 1 to LIVE_HEAD_MAX_CHECKS_IN_FLIGHT
checks.Refresh()
end for
oldest = checks.inFlight[0].pending.answer
oldest.pending = false
oldest.timedOut = true
m.assertEqual(m.Seqnums(checks.Refresh()), [-1])
m.assertEqual(checks.counts["checks_sent"], LIVE_HEAD_MAX_CHECKS_IN_FLIGHT + 1)
end function
@it("cancels the checks sent before one that answers with a head, and none sent after it")
function _()
checks = m.NewChecks([
{ seqnum: 10, timeMs: 18630, pending: true }
{ seqnum: 11, timeMs: 20630, pending: true }
{ seqnum: 12, timeMs: 22630, pending: true }
{ seqnum: 13, timeMs: 24630, pending: true }
])
for i = 1 to 3
checks.Refresh()
end for
first = checks.inFlight[0].pending.answer
second = checks.inFlight[1].pending.answer
third = checks.inFlight[2].pending.answer
second.pending = false
m.assertEqual(m.Seqnums(checks.Refresh()), [11])
m.assertTrue(ValidBool(first.cancelled))
m.assertFalse(ValidBool(third.cancelled))
m.assertEqual(checks.inFlight.Count(), 2)
m.assertEqual(checks.counts["checks_sent"], 4)
end function
@it("cancels the checks in flight when the refresh's own check answers with a head within the wait")
function _()
checks = m.NewChecks([{ seqnum: 10, timeMs: 18630, pending: true }, { seqnum: 11, timeMs: 20630 }])
checks.Refresh()
first = checks.inFlight[0].pending.answer
m.assertEqual(m.Seqnums(checks.Refresh()), [11])
m.assertTrue(ValidBool(first.cancelled))
m.assertEmpty(checks.inFlight)
end function
@it("cancels no check for an answer without a head")
function _()
checks = m.NewChecks([{ seqnum: 10, timeMs: 18630, pending: true }, { seqnum: -1, timeMs: invalid }])
checks.Refresh()
first = checks.inFlight[0].pending.answer
m.assertEqual(m.Seqnums(checks.Refresh()), [-1])
m.assertFalse(ValidBool(first.cancelled))
m.assertEqual(checks.inFlight.Count(), 1)
end function
@it("counts a check given up as timed out, not as answered")
function _()
checks = m.NewChecks([{ seqnum: -1, timeMs: invalid, timedOut: true }])
m.assertEqual(m.Seqnums(checks.Refresh()), [-1])
m.assertEqual(checks.counts["timed_out"], 1)
m.assertEqual(checks.counts["answered_without_head"], 0)
end function
@it("counts an answer without a head")
function _()
checks = m.NewChecks([{ seqnum: -1, timeMs: invalid }])
checks.Refresh()
m.assertEqual(checks.counts["answered_without_head"], 1)
end function
@it("counts the longest run of refreshes that returned no head newer than the newest seen")
function _()
checks = m.NewChecks([{ seqnum: 11, timeMs: 20630 }, { seqnum: 10, timeMs: 18630 }, { seqnum: -1, timeMs: invalid }, { seqnum: 12, timeMs: 22630 }, { seqnum: -1, timeMs: invalid }])
for i = 1 to 5
checks.Refresh()
end for
m.assertEqual(checks.counts["refreshes_without_newer_head_max_streak"], 2)
end function
@describe("LiveHeadChecks against HttpTestServer")
' Head checks against the test server's `path`, which answers X-Head-Seqnum `seqnum` after `delayMs`.
function NewServedChecks(path as string, seqnum as integer, delayMs as integer) as object
m.ServeHead(path, seqnum, delayMs)
return new LiveHeadChecks(Tests.HttpTestServerUrl(`${path}?rn=0`))
end function
function ServeHead(path as string, seqnum as integer, delayMs as integer)
routes = {}
routes[path] = { status: 200, headers: { "X-Head-Seqnum": seqnum.ToStr(), "X-Head-Time-Millis": (seqnum * 2000).ToStr() }, delayMs: delayMs }
m.server.routes = routes
end function
@it("returns a check answered within the wait without waiting it out")
function _()
checks = m.NewServedChecks("/live/fast-head", 10, 0)
timer = CreateObject("roTimespan")
m.assertEqual(m.Seqnums(checks.Refresh()), [10])
m.assertTrue(timer.TotalMilliseconds() < LIVE_HEAD_WAIT_MS \ 2, `${timer.TotalMilliseconds()} ms`)
end function
@it("waits LIVE_HEAD_WAIT_MS on a slow check, then returns it at the next refresh with that refresh's own check")
function _()
checks = m.NewServedChecks("/live/slow-head", 10, LIVE_HEAD_WAIT_MS + 1000)
timer = CreateObject("roTimespan")
m.assertEmpty(checks.Refresh())
elapsedMs = timer.TotalMilliseconds()
m.assertTrue(elapsedMs >= LIVE_HEAD_WAIT_MS and elapsedMs < LIVE_HEAD_WAIT_MS + 1000, `${elapsedMs} ms`)
m.assertEqual(checks.inFlight.Count(), 1)
m.ServeHead("/live/slow-head", 11, 0)
sleep(1500)
m.assertEqual(m.Seqnums(checks.Refresh()), [10, 11])
m.assertEqual(checks.inFlight.Count(), 0)
m.assertEqual(checks.counts["checks_sent"], 2)
m.assertEqual(checks.counts["answered_after_wait"], 1)
m.assertEqual(Tests.HttpTestServerHits(m.server, "/live/slow-head?rn=0"), 2)
end function
@it("sends a check answering without X-Head-* once: the next refresh checks again")
function _()
m.server.routes = { "/live/headless": { status: 200 } }
checks = new LiveHeadChecks(Tests.HttpTestServerUrl("/live/headless?rn=0"))
m.assertEqual(m.Seqnums(checks.Refresh()), [-1])
m.assertEqual(checks.counts["answered_without_head"], 1)
m.assertEqual(Tests.HttpTestServerHits(m.server, "/live/headless?rn=0"), 1)
end function
@it("cancels a slow check, and drops its transfer, once a later one answers with a head")
function _()
checks = m.NewServedChecks("/live/overtaken-head", 10, 10000)
m.assertEmpty(checks.Refresh())
slow = checks.inFlight[0].pending
m.ServeHead("/live/overtaken-head", 11, 0)
m.assertEqual(m.Seqnums(checks.Refresh()), [11])
m.assertEmpty(checks.inFlight)
m.assertInvalid(slow["_fetch"]["_urlTransfer"])
m.assertTrue(slow.Poll().IsCancelled())
end function
@it("Cancel cancels the checks in flight and drops their transfers")
function _()
checks = m.NewServedChecks("/live/hung-head", 10, 10000)
checks.Refresh()
pending = checks.inFlight[0].pending
m.assertNotInvalid(pending["_fetch"]["_urlTransfer"])
checks.Cancel()
m.assertEmpty(checks.inFlight)
m.assertInvalid(pending["_fetch"]["_urlTransfer"])
m.assertTrue(pending.Poll().IsCancelled())
end function
end class
end namespace
@@ -0,0 +1,60 @@
import "pkg:/components/Services/Dash/LiveHeadChecks.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/Types.bs"
namespace Tests
' Makes `checks` send fake head checks answering `answers` in order: { seqnum, timeMs } (seqnum -1:
' no X-Head-* headers, a 403), `pending: true` to stay unanswered until AnswerLiveHeadChecks,
' `timedOut: true` to be given up.
function FakeLiveHeadChecks(checks as object, answers as object)
checks.answers = answers
checks.Send = function() as object
return Tests.FakeLiveHeadPending(m.answers.Shift())
end function
end function
function AnswerLiveHeadChecks(checks as object)
for each check in checks.inFlight
check.pending.answer.pending = false
end for
end function
' A PendingResponse answering `answer` once it isn't pending.
function FakeLiveHeadPending(answer as object) as object
return {
answer: answer
Wait: function(_timeoutMs as integer) as dynamic
return m.Poll()
end function
Poll: function() as dynamic
if ValidBool(m.answer.pending)
return invalid
end if
return Tests.FakeLiveHeadResponse(m.answer)
end function
Cancel: function() as void
m.answer.cancelled = true
end function
}
end function
function FakeLiveHeadResponse(answer as object) as HttpClient.Response
if ValidBool(answer.timedOut)
return new HttpClient.Response({ timedOut: true })
end if
headers = {}
if answer.seqnum >= 0
headers["X-Head-Seqnum"] = answer.seqnum.ToStr()
end if
if answer.timeMs <> invalid
headers["X-Head-Time-Millis"] = FormatJson(answer.timeMs)
end if
status = 200
if answer.seqnum < 0
status = 403
end if
return new HttpClient.Response({ statusCode: status, headers: headers })
end function
end namespace
@@ -0,0 +1,61 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class InnertubeRequestsTests extends Rooibos.BaseTestSuite
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.global.telemetry.LogEvent = {}
end function
function AssertContains(text as string, part as string)
m.assertTrue(text.InStr(part) <> -1, `"${text}" doesn't contain "${part}"`)
end function
@describe("Innertube requests")
@it("are JSON POSTs carrying the client's context and headers")
function _()
requests = [
Innertube.CreateBrowseRequest("FEwhat_to_watch", Innertube.ClientType.Tv)
Innertube.CreateNextRequest({ "videoId": "v" })
Innertube.CreateResolveUrlRequest("https://www.youtube.com/@handle")
Innertube.CreateSubscribeRequest("UC")
Innertube.CreateUnsubscribeRequest("UC")
Innertube.CreatePlayerRequest(Innertube.ClientType.Tv, { "videoId": "v" })
Innertube.CreateGetDrmLicenceRequest({ "videoId": "v" })
]
for each request in requests
m.assertEqual(request.GetMethod(), "POST")
m.AssertContains(request.GetFullUrl(), "https://www.youtube.com/youtubei/v1/")
headers = request.GetHeaders()
m.assertEqual(headers["Content-Type"], "application/json")
m.assertNotInvalid(headers["x-youtube-client-name"])
m.assertTrue(IsAssociativeArray(StringUtils.ParseJsonSafe(request.GetTextBody()).context))
end for
end function
@it("report a parser warning with the request's curl command")
function _()
request = Innertube.CreateBrowseRequest("FEwhat_to_watch", Innertube.ClientType.Tv)
Innertube.Warning("Unknown node", { "someRenderer": {} }, { request: request })
event = m.global.telemetry.LogEvent
m.assertEqual(event.attachments[1].filename, "request.txt")
m.assertEqual(event.attachments[1].data, request.ToCurlCommand())
m.AssertContains(event.attachments[1].data, "FEwhat_to_watch")
end function
@it("tell telemetry a LOGIN_REQUIRED response came to a request sent with an access token")
function _()
request = Innertube.CreatePlayerRequest(Innertube.ClientType.Tv, { "videoId": "v" })
request.Header("Authorization", "Bearer token")
Innertube.ParsePlayerResponseForError({ "playabilityStatus": { "status": "LOGIN_REQUIRED" } }, request)
m.AssertContains(m.global.telemetry.LogEvent.message, "LOGIN_REQUIRED: hasAccessToken=true hasCtt=false")
end function
end class
end namespace
@@ -1,10 +1,26 @@
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class LiveStreamInfoTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.global.telemetry.LogEvent = {}
end function
' availabilityStartTime + the timeline offset place the first segment's start so that the head
' segment ends a cushion behind now.
function AssertAnchored(timeline as object, nowSec as integer, nowMs as integer, cushionMs as integer)
@@ -117,40 +133,62 @@ namespace Tests
m.AssertAnchored(timeline, 2000000000, 900, 5400)
end function
@describe("Innertube.GetLiveStreamInfo")
@it("reads the timeline from the head check's X-Head-* headers")
function _()
m.server.routes = { "/live/head": { status: 200, headers: { "X-Head-Seqnum": "100", "X-Head-Time-Millis": "200000" } } }
formatUrl = Tests.HttpTestServerUrl("/live/head?itag=1")
parsedResponse = {}
Innertube.GetLiveStreamInfo(parsedResponse, [{ url: formatUrl, targetDurationSec: 2 }], 0, "cpn1", invalid)
m.assertInvalid(parsedResponse.error)
m.assertEqual(parsedResponse.liveHeadSeqnum, 100)
m.assertEqual(parsedResponse.liveSegmentDurationMs, 2000)
m.assertEqual(parsedResponse.liveHeadUrl, Innertube.GetLiveHeadUrl(formatUrl, "cpn1"))
m.assertEqual(Tests.HttpTestServerHits(m.server, parsedResponse.liveHeadUrl), 1)
end function
@it("checks the head again when a response lacks X-Head-*, a success included, then fails the load with the cause")
function _()
m.server.routes = { "/live/headless": { status: 200 } }
formatUrl = Tests.HttpTestServerUrl("/live/headless?itag=1")
parsedResponse = {}
Innertube.GetLiveStreamInfo(parsedResponse, [{ url: formatUrl, targetDurationSec: 2 }], 0, invalid, invalid)
m.assertEqual(Tests.HttpTestServerHits(m.server, Innertube.GetLiveHeadUrl(formatUrl, invalid)), 2)
m.assertEqual(m.global.telemetry.LogEvent.level, "warning")
m.assertEqual(m.global.telemetry.LogEvent.message, "no X-Head-* in the response (HTTP 200)")
m.assertEqual(parsedResponse.error, `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP 200)\n`)
end function
@describe("Innertube.ReadLiveHeadSeqnum")
@it("reads X-Head-Seqnum")
function _()
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.FakeResponse({ "X-Head-Seqnum": "9059091" })), 9059091)
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.ResponseWithHeaders({ "X-Head-Seqnum": "9059091" })), 9059091)
end function
@it("returns -1 without the header")
function _()
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.FakeResponse({ "X-Walltime-Ms": "1791305190669" })), -1)
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.FakeResponse(invalid)), -1)
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.ResponseWithHeaders({ "X-Walltime-Ms": "1791305190669" })), -1)
m.assertEqual(Innertube.ReadLiveHeadSeqnum(m.ResponseWithHeaders({})), -1)
end function
@describe("Innertube.ReadLiveHeadTimeMs")
@it("reads X-Head-Time-Millis past 32 bits")
function _()
m.assertEqual(Innertube.ReadLiveHeadTimeMs(m.FakeResponse({ "X-Head-Time-Millis": "17900000123", "X-Head-Time-Sec": "17900000" })), 17900000123&)
m.assertEqual(Innertube.ReadLiveHeadTimeMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123", "X-Head-Time-Sec": "17900000" })), 17900000123&)
end function
@it("returns invalid without X-Head-Time-Millis, X-Head-Time-Sec or not")
function _()
m.assertInvalid(Innertube.ReadLiveHeadTimeMs(m.FakeResponse({ "X-Head-Time-Sec": "17900000" })))
m.assertEqual(Innertube.ReadLiveHeadTimeSecAsMs(m.FakeResponse({ "X-Head-Time-Sec": "17900000" })), 17900000000&)
m.assertInvalid(Innertube.ReadLiveHeadTimeSecAsMs(m.FakeResponse({ "X-Head-Time-Millis": "17900000123" })))
m.assertInvalid(Innertube.ReadLiveHeadTimeMs(m.ResponseWithHeaders({ "X-Head-Time-Sec": "17900000" })))
m.assertEqual(Innertube.ReadLiveHeadTimeSecAsMs(m.ResponseWithHeaders({ "X-Head-Time-Sec": "17900000" })), 17900000000&)
m.assertInvalid(Innertube.ReadLiveHeadTimeSecAsMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123" })))
end function
function FakeResponse(headers as dynamic) as object
return {
headerData: headers
Headers: function() as dynamic
return m.headerData
end function
}
function ResponseWithHeaders(headers as object) as HttpClient.Response
return new HttpClient.Response({ headers: headers })
end function
end class
@@ -0,0 +1,101 @@
import "pkg:/components/Services/Innertube/OTFSegmentInfo.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class OTFSegmentInfoTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.global.telemetry.LogEvent = {}
end function
function Formats(path as string, count as integer) as object
formats = []
for i = 1 to count
formats.Push({ itag: i, url: Tests.HttpTestServerUrl(`${path}?itag=${i}`) })
end for
return formats
end function
function HitsUnder(prefix as string) as integer
hits = 0
serverHits = ValidAssociativeArray(m.server.hits)
for each path in serverHits
if path.StartsWith(prefix)
hits += serverHits[path]
end if
end for
return hits
end function
function AssertContains(text as string, part as string)
m.assertTrue(text.InStr(part) <> -1, `"${text}" doesn't contain "${part}"`)
end function
@describe("Innertube.OTFGetSegmentInfo")
@it("reads every format's segment durations from its init segment, saved to a file")
function _()
m.server.routes = { "/otf/init": { status: 200, body: `init bytes\r\nSegment-Count: 3\r\nSegment-Durations-Ms: 5333,5334(r=1),\r\n` } }
formats = m.Formats("/otf/init", 10)
Innertube.OTFGetSegmentInfo(formats, Innertube.ClientType.Tv, invalid, "{}")
for each format in formats
m.assertEqual(format.otfSegmentDurations, [{ d: 5333 }, { d: 5334, r: 1 }])
end for
m.assertEqual(m.HitsUnder("/otf/init?"), 10)
m.assertEmpty(m.global.telemetry.LogEvent)
end function
@it("probes a DRM format whose init segment failed, and reports both")
function _()
m.server.routes = { "/otf/drm": { status: 404 } }
formats = m.Formats("/otf/drm", 1)
formats[0].drmFamilies = ["WIDEVINE"]
Innertube.OTFGetSegmentInfo(formats, Innertube.ClientType.Tv, invalid, `{"player":1}`)
event = m.global.telemetry.LogEvent
m.assertEqual(event.level, "error")
m.AssertContains(event.message, "Failed to get segment info for itag 1")
m.AssertContains(event.message, "drm probe itag=1 drmFamilies=WIDEVINE")
for each variant in ["GET bare", "GET Range header", "GET range param", "GET sq=0", "POST empty range param", "POST {15:0} range param"]
m.AssertContains(event.message, `${variant} -> 404`)
end for
m.assertEqual(event.attachments[0].data, `{"player":1}`)
m.assertInvalid(formats[0].otfSegmentDurations)
end function
@it("stops at a cancellation set mid-flight")
function _()
canceller = CreateObject("roSGNode", "CancelLaterTask")
canceller.control = "run"
timer = CreateObject("roTimespan")
while canceller.cancellationNode = invalid and timer.TotalMilliseconds() < 3000
sleep(10)
end while
cancellation = CancellationUtils.CreateCancellation(canceller.cancellationNode, "cancel", true)
formats = m.Formats("/delay/3000", 10)
canceller.cancelAfterMs = 300
timer.Mark()
Innertube.OTFGetSegmentInfo(formats, Innertube.ClientType.Tv, cancellation, "{}")
elapsedMs = timer.TotalMilliseconds()
m.assertTrue(elapsedMs >= 250 and elapsedMs < 800, `took ${elapsedMs} ms`)
for each format in formats
m.assertInvalid(format.otfSegmentDurations)
end for
m.assertEmpty(m.global.telemetry.LogEvent)
end function
end class
end namespace
@@ -0,0 +1,57 @@
import "pkg:/components/Services/Innertube/PostLiveDvrInfo.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class PostLiveDvrInfoTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.global.telemetry.LogEvent = {}
end function
@describe("Innertube.FetchPostLiveDvrHead")
@it("reads a HEAD's status and headers")
function _()
m.server.routes = { "/dvr/head": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } }
result = Innertube.FetchPostLiveDvrHead(Tests.HttpTestServerUrl("/dvr/head?itag=1"), invalid, "cpn1", Innertube.ClientType.Tv, invalid)
m.assertEqual(result.statusCode, 200)
m.assertTrue(Innertube.HasPostLiveDvrHead(result))
m.assertEqual(Tests.HttpTestServerHits(m.server, result.url), 1)
end function
@it("sends a failed HEAD once more")
function _()
m.server.routes = { "/dvr/failing": { status: 503 } }
result = Innertube.FetchPostLiveDvrHead(Tests.HttpTestServerUrl("/dvr/failing?itag=1"), "0", invalid, Innertube.ClientType.Tv, invalid)
m.assertEqual(result.statusCode, 503)
m.assertFalse(Innertube.HasPostLiveDvrHead(result))
m.assertEqual(Tests.HttpTestServerHits(m.server, result.url), 2)
end function
@describe("Innertube.GetPostLiveDvrInfo")
@it("reads the duration and segment count from the live edge's head")
function _()
m.server.routes = { "/dvr/ended": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } }
parsedResponse = {}
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/ended?itag=1") }], invalid, Innertube.ClientType.Tv, invalid)
m.assertEqual(parsedResponse.postLiveDvrDurationMs, 80000)
m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 40)
end function
end class
end namespace
@@ -1,10 +1,116 @@
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class InvidiousServiceTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.global.telemetry.LogEvent = {}
end function
function CreateService(backend = "invidious" as string) as object
return new Invidious.InvidiousService({
preferences: { "backend.selected": backend, "invidious.instance": Tests.HttpTestServerUrl("/inv") }
apiDefinitions: {
cached: { url: "/api/v1/cached/{id}", cacheSeconds: 60 }
flaky: { url: "/api/v1/flaky", tryCount: 2 }
video_info: { url: "/api/v1/videos/{id}", responseHandler: "VideoInfoHandler" }
}
})
end function
function AssertContains(text as string, part as string)
m.assertTrue(text.InStr(part) <> -1, `"${text}" doesn't contain "${part}"`)
end function
@describe("Invidious.InvidiousService.MakeRequest")
@it("serves an endpoint from the cache for its cacheSeconds")
function _()
DeleteFile(HttpCache.GetFilePath(Tests.HttpTestServerUrl("/inv/api/v1/cached/x"), {}, invalid))
m.server.routes = { "/inv/api/v1/cached/x": { status: 200, body: "[1,2]" } }
service = m.CreateService()
m.assertEqual(service.MakeRequest({ endpoint: "cached", pathParams: { id: "x" } }).result.items, [1, 2])
m.assertEqual(service.MakeRequest({ endpoint: "cached", pathParams: { id: "x" } }).result.items, [1, 2])
m.assertEqual(Tests.HttpTestServerHits(m.server, "/inv/api/v1/cached/x"), 1)
end function
@it("makes an endpoint's tryCount attempts, then fails with the last one's error")
function _()
m.server.routes = { "/inv/api/v1/flaky": { status: 503, body: "busy" } }
result = m.CreateService().MakeRequest({ endpoint: "flaky" })
m.assertFalse(result.success)
m.assertFalse(result.cancelled)
m.AssertContains(result.error, "StatusCode: 503")
m.assertEqual(Tests.HttpTestServerHits(m.server, "/inv/api/v1/flaky"), 2)
end function
@it("succeeds with the placeholder a handler makes of a failed response")
function _()
m.server.routes = { "/inv/api/v1/videos/gone": { status: 500 } }
result = m.CreateService().MakeRequest({ endpoint: "video_info", pathParams: { id: "gone" } })
m.assertTrue(result.success)
m.assertEqual(result.result.items[0].videoId, "gone")
m.assertEqual(result.result.items[0].title, "[Video not available]")
end function
@it("asks the web server for the built-in backend's response, without the network")
function _()
httpServer = {
calls: []
ProcessRequestLocal: function(method as string, uri as string, _headers as object, body as string) as object
m.calls.Push({ method: method, uri: uri, body: body })
responseBody = CreateObject("roByteArray")
responseBody.FromAsciiString("[3]")
return { http_code: 200, headers: {}, body: responseBody }
end function
}
result = m.CreateService("playlet").MakeRequest({ endpoint: "cached", pathParams: { id: "local" } }, { httpServer: httpServer })
m.assertEqual(result.result.items, [3])
m.assertEqual(httpServer.calls, [{ method: "GET", uri: "/playlet-invidious-backend/api/v1/cached/local", body: "" }])
end function
@it("fails with the built-in backend's status and body")
function _()
httpServer = {
ProcessRequestLocal: function(_method as string, _uri as string, _headers as object, _body as string) as object
responseBody = CreateObject("roByteArray")
responseBody.FromAsciiString("backend down")
return { http_code: 500, headers: {}, body: responseBody }
end function
}
result = m.CreateService("playlet").MakeRequest({ endpoint: "cached", pathParams: { id: "failing" } }, { httpServer: httpServer })
m.assertFalse(result.success)
m.assertEqual(result.error, `StatusCode: 500\nBody: backend down`)
end function
@describe("Invidious.InvidiousService.GetVideoMetadata")
@it("doesn't retry a failure other than curl's HTTP/0.9 error, and reports it")
function _()
m.server.routes = { "/inv/api/v1/videos/missing": { status: 500 } }
metadata = m.CreateService().GetVideoMetadata("missing")
m.AssertContains(metadata.error, "StatusCode: 500")
m.assertEqual(Tests.HttpTestServerHits(m.server, "/inv/api/v1/videos/missing"), 1)
event = m.global.telemetry.LogEvent
m.assertEqual(event.level, "warning")
m.assertEqual(event.message, metadata.error)
m.AssertContains(event.attachments[0].data, "/inv/api/v1/videos/missing")
end function
@describe("Invidious.NeedsLiveStreamInfo")
@it("needs the live timeline for a live response from an Invidious server")
@@ -0,0 +1,57 @@
import "pkg:/components/Services/SponsorBlock/SponsorBlockConfig.bs"
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class SponsorBlockServiceTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
config = new SponsorBlock.SponsorBlockConfig()
config.config = { serverAddress: Tests.HttpTestServerUrl("/sb") }
m.service = new SponsorBlock.SponsorBlockService(config)
end function
function RouteSkipSegments(videoId as string, route as object)
routes = {}
routes[`/sb/api/skipSegments/${CryptoUtils.GetSha256(videoId).Left(4)}`] = route
m.server.routes = routes
end function
@describe("SponsorBlock.SponsorBlockService")
@it("finds the video's segments in its hash prefix's list")
function _()
m.RouteSkipSegments("video1", { status: 200, body: `[{"videoId":"other","segments":[]},{"videoId":"video1","segments":[{"segment":[1,2]}]}]` })
segments = m.service.GetSkipSegmentsForVideo("video1")
m.assertEqual(segments[0].segment, [1, 2])
end function
@it("has no segments when the server fails")
function _()
m.RouteSkipSegments("video2", { status: 500 })
m.assertInvalid(m.service.GetSkipSegmentsForVideo("video2"))
end function
@it("posts a viewed segment's UUID")
function _()
m.server.routes = { "/sb/api/viewedVideoSponsorTime": { status: 200 } }
m.service.PostSegmentViewed("segment1")
m.assertEqual(Tests.HttpTestServerHits(m.server, "/sb/api/viewedVideoSponsorTime?UUID=segment1"), 1)
end function
end class
end namespace
@@ -0,0 +1,255 @@
import "pkg:/components/Telemetry/Sentry.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
' Nothing listens on port 1: a request there fails without an answer.
const UNREACHABLE_ENVELOPE_URL = "http://127.0.0.1:1/envelope"
' Stands in for HttpClient.CreateUrlTransfer, sending to the urls Serve set in place of the support server's and the fallback's.
function SentryUrlTransfer(url as string, headers as object, messagePort as object) as object
urls = GetGlobalAA().sentryEnvelopeUrls
url = url.Replace(SUPPORT_SERVER_ENVELOPE_URL, urls.supportServer).Replace(SENTRY_FALLBACK_ENVELOPE_URL, urls.fallback)
urlTransfer = CreateObject("roUrlTransfer")
urlTransfer.RetainBodyOnError(true)
urlTransfer.SetUrl(url)
urlTransfer.SetHeaders(headers)
urlTransfer.SetMessagePort(messagePort)
return urlTransfer
end function
@suite
class SentrySendEventsTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
' BuildEnvelope gives an event without an event_id one from the Telemetry task's m.deviceInfo.
GetGlobalAA().deviceInfo = CreateObject("roDeviceInfo")
end function
protected override function tearDown()
GetGlobalAA().Delete("deviceInfo")
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.stubCall(HttpClient.CreateUrlTransfer, Tests.SentryUrlTransfer)
end function
protected override function afterEach()
GetGlobalAA().Delete("sentryEnvelopeUrls")
end function
' Points the support server and the fallback at routes of the test server under id; invalid for one nothing answers.
function Serve(id as string, supportServerRoute as dynamic, fallbackRoute as dynamic) as void
m.supportServerPath = `/support/${id}`
m.fallbackPath = `/sentry/${id}/`
routes = {}
urls = { supportServer: UNREACHABLE_ENVELOPE_URL, fallback: UNREACHABLE_ENVELOPE_URL }
if supportServerRoute <> invalid
routes[m.supportServerPath] = supportServerRoute
urls.supportServer = Tests.HttpTestServerUrl(m.supportServerPath)
end if
if fallbackRoute <> invalid
routes[m.fallbackPath] = fallbackRoute
urls.fallback = Tests.HttpTestServerUrl(m.fallbackPath)
end if
m.server.routes = routes
GetGlobalAA().sentryEnvelopeUrls = urls
end function
' SendEvents' result for one event, and the lines it logged.
function Send(message as string) as object
result = {
events: [{
level: "error"
message: message
release: "1.0.0-test"
tags: { session_id: "session1" }
userId: "user1"
}]
retryAfter: invalid
}
result.lines = Tests.LogLines(function(result as object) as void
result.retryAfter = Sentry.SendEvents(result.events)
end function, result)
return result
end function
function SupportServerHits() as integer
return Tests.HttpTestServerHits(m.server, m.supportServerPath)
end function
function FallbackHits() as integer
return Tests.HttpTestServerHits(m.server, `${m.fallbackPath}?sentry_key=${SENTRY_FALLBACK_KEY}`)
end function
function Messages(lines as string[], level as string) as string[]
messages = [] as string[]
for each line in lines
if line.InStr(`[${level}]`) <> -1
messages.Push(Tests.LogLineMessage(line))
end if
end for
return messages
end function
' The one error logged.
function ErrorLogged(lines as string[]) as string
errors = m.Messages(lines, "ERROR")
m.assertEqual(errors.Count(), 1, FormatJson(lines))
return errors[0]
end function
' The events' envelope the test server read last: one JSON item per line, ending with a line break.
function LastEnvelopeLines() as object
request = m.server.lastRequest
m.assertEqual(request.method, "POST")
m.assertEqual(request.headers["content-type"], "application/x-sentry-envelope")
return request.body.Split(`\n`)
end function
@describe("Sentry.SendEvents")
@it("sends the events to the support server, holding nothing back")
function _()
m.Serve("sent", { status: 200 }, { status: 200 })
result = m.Send("sent event")
m.assertEqual(result.retryAfter, 0)
m.assertEmpty(m.Messages(result.lines, "ERROR"))
m.assertEmpty(m.Messages(result.lines, "WARN"))
m.assertEqual(m.SupportServerHits(), 1)
m.assertEqual(m.FallbackHits(), 0)
lines = m.LastEnvelopeLines()
m.assertEqual(lines.Count(), 4)
m.assertEqual(ParseJson(lines[0]).sdk.name, "sentry.roku.playlet")
m.assertEqual(lines[1], `{"type":"event"}`)
event = ParseJson(lines[2])
m.assertEqual(event.logentry.formatted, "sent event")
m.assertEqual(event.level, "error")
m.assertEqual(event.release, "1.0.0-test")
m.assertEqual(event.tags, { session_id: "session1" })
m.assertEqual(event.user, { id: "user1" })
m.assertEqual(event.event_id, result.events[0].event_id)
m.assertEqual(lines[3], "")
end function
@it("sends the Sentry fallback, with its key, a warning that the support server is unreachable, the unsent envelope attached")
function _()
m.Serve("unreachable", invalid, { status: 200 })
result = m.Send("unsent event")
m.assertEqual(result.retryAfter, 0)
m.assertEmpty(m.Messages(result.lines, "ERROR"))
m.assertEqual(m.FallbackHits(), 1)
warningPrefix = "Support server unreachable, sending events to the Sentry fallback: "
errorMessage = invalid
for each warning in m.Messages(result.lines, "WARN")
if warning.StartsWith(warningPrefix)
errorMessage = warning.Mid(warningPrefix.Len())
end if
end for
m.assertNotInvalid(errorMessage, FormatJson(result.lines))
m.assertNotEqual(errorMessage.InStr("StatusCode: -"), -1, errorMessage)
lines = m.LastEnvelopeLines()
m.assertEqual(lines[1], `{"type":"event"}`)
event = ParseJson(lines[2])
m.assertEqual(event.logentry.formatted, `Support server unreachable: ${errorMessage}`)
m.assertEqual(event.level, "warning")
m.assertEqual(event.fingerprint, ["support server unreachable"])
m.assertEqual(event.release, "1.0.0-test")
m.assertEqual(event.tags, { session_id: "session1" })
m.assertEqual(event.user, { id: "user1" })
m.assertInvalid(event.extra)
attachment = ParseJson(lines[3])
m.assertEqual(attachment.type, "attachment")
m.assertEqual(attachment.filename, "envelope.txt")
m.assertEqual(attachment.content_type, "text/plain")
attachedOffset = lines[0].Len() + lines[1].Len() + lines[2].Len() + lines[3].Len() + 4
attached = m.server.lastRequest.body.Mid(attachedOffset)
m.assertEqual(attachment.length, attached.Len() - 1)
attachedLines = attached.Split(`\n`)
m.assertEqual(attachedLines[1], `{"type":"event"}`)
unsentEvent = ParseJson(attachedLines[2])
m.assertEqual(unsentEvent.logentry.formatted, "unsent event")
m.assertEqual(unsentEvent.event_id, result.events[0].event_id)
end function
@it("holds the events back for the fallback's Retry-After when it rate-limits them")
function _()
m.Serve("fallbackratelimited", invalid, { status: 429, headers: { "Retry-After": "45" } })
result = m.Send("rate-limited event")
m.assertEqual(result.retryAfter, 45)
m.assertEqual(m.FallbackHits(), 1)
m.assertEqual(m.ErrorLogged(result.lines), `Rate limited by ${SENTRY_FALLBACK_ENVELOPE_URL}?sentry_key=${SENTRY_FALLBACK_KEY} Retry after 45 seconds`)
end function
@it("holds the events back for 60 seconds when the fallback fails too")
function _()
testCases = [
{ id: "answered", route: { status: 500 } }
{ id: "unreachable", route: invalid }
]
for each testCase in testCases
m.Serve(`fallbackfailed${testCase.id}`, invalid, testCase.route)
result = m.Send("failed event")
m.assertEqual(result.retryAfter, 60, testCase.id)
errorLogged = m.ErrorLogged(result.lines)
m.assertTrue(errorLogged.StartsWith(`Failed to send events to ${SENTRY_FALLBACK_ENVELOPE_URL}?sentry_key=${SENTRY_FALLBACK_KEY} `), errorLogged)
m.assertTrue(errorLogged.EndsWith(` \nRetry after 60 seconds`), errorLogged)
end for
end function
@it("holds the events back for the support server's Retry-After when it rate-limits them, sending the fallback nothing")
function _()
m.Serve("ratelimited", { status: 429, headers: { "Retry-After": "120" } }, { status: 200 })
result = m.Send("rate-limited event")
m.assertEqual(result.retryAfter, 120)
m.assertEqual(m.SupportServerHits(), 1)
m.assertEqual(m.FallbackHits(), 0)
m.assertEqual(m.ErrorLogged(result.lines), `Rate limited by ${SUPPORT_SERVER_ENVELOPE_URL} Retry after 120 seconds`)
end function
@it("holds the events back for 60 seconds on a 429 whose Retry-After is absent, zero or a date")
function _()
testCases = [
{ id: "absent", headers: {} }
{ id: "zero", headers: { "Retry-After": "0" } }
{ id: "date", headers: { "Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT" } }
]
for each testCase in testCases
m.Serve(`ratelimited${testCase.id}`, { status: 429, headers: testCase.headers }, { status: 200 })
result = m.Send("rate-limited event")
m.assertEqual(result.retryAfter, 60, testCase.id)
m.assertEqual(m.FallbackHits(), 0, testCase.id)
m.assertEqual(m.ErrorLogged(result.lines), `Rate limited by ${SUPPORT_SERVER_ENVELOPE_URL} Retry after 60 seconds`, testCase.id)
end for
end function
@it("holds the events back for the Retry-After of a failure the support server answers, or 60 seconds, sending the fallback nothing")
function _()
testCases = [
{ id: "500", route: { status: 500 }, retryAfter: 60 }
{ id: "503", route: { status: 503, headers: { "Retry-After": "30" } }, retryAfter: 30 }
]
for each testCase in testCases
m.Serve(`failed${testCase.id}`, testCase.route, { status: 200 })
result = m.Send("failed event")
m.assertEqual(result.retryAfter, testCase.retryAfter, testCase.id)
m.assertEqual(m.SupportServerHits(), 1, testCase.id)
m.assertEqual(m.FallbackHits(), 0, testCase.id)
errorLogged = m.ErrorLogged(result.lines)
m.assertTrue(errorLogged.StartsWith(`Failed to send events to ${SUPPORT_SERVER_ENVELOPE_URL} `), errorLogged)
m.assertNotEqual(errorLogged.InStr(`StatusCode: ${testCase.id}`), -1, errorLogged)
m.assertTrue(errorLogged.EndsWith(` \nRetry after ${testCase.retryAfter} seconds`), errorLogged)
end for
end function
end class
end namespace
@@ -85,9 +85,10 @@ namespace Tests
m.State(VideoState.Playing)
m.StartInfo("init")
summary = m.SendAt(62000)
m.assertEqual(m.SortedKeys(summary), ["backend", "first_playing_at_ms", "lifetime_ms", "metadata_done_at_ms", "outcome", "play_start_count", "play_start_infos", "playing_ms", "stream_source"])
m.assertEqual(m.SortedKeys(summary), ["backend", "first_playing_at_ms", "lifetime_ms", "metadata_done_at_ms", "outcome", "play_start_count", "play_start_infos", "playing_ms", "stream_source", "video_id"])
m.assertEqual(summary.backend, "playlet")
m.assertEqual(summary.stream_source, "adaptiveFormats")
m.assertEqual(summary.video_id, "vid1")
m.assertEqual(summary.outcome, "closed")
m.assertEqual(summary.metadata_done_at_ms, 1000)
m.assertEqual(summary.first_playing_at_ms, 2000)
@@ -121,7 +122,6 @@ namespace Tests
m.assertEqual(summary.underrun_samples[9].ms, 1000)
m.assertTrue(summary.live)
m.assertFalse(summary.DoesExist("ended_in_underrun"))
m.assertEqual(summary.video_id, "vid1")
end function
@it("a buffering whose first bufferingStatus is no underrun is not counted")
@@ -152,7 +152,7 @@ namespace Tests
m.assertEqual(summary.underrun_samples[0], { at_ms: 100, ms: 2000 })
end function
@it("a buffering with no valid bufferingStatus is counted as one, with the video id")
@it("a buffering with no valid bufferingStatus is counted as one")
function _()
m.At(1000)
m.State(VideoState.Playing)
@@ -165,7 +165,6 @@ namespace Tests
m.assertEqual(summary.bufferings_without_status_count, 1)
m.assertFalse(summary.DoesExist("underrun_count"))
m.assertEqual(summary.playing_ms, 4850)
m.assertEqual(summary.video_id, "vid1")
end function
@it("a buffering cut short before any status is not counted: a pause, an error, the close")
@@ -210,7 +209,6 @@ namespace Tests
summary = m.SendAt(7000)
m.assertEqual(summary.is_underrun_change_count, 2)
m.assertFalse(summary.DoesExist("underrun_count"))
m.assertEqual(summary.video_id, "vid1")
end function
@it("a bufferingStatus outside a buffering is ignored")
@@ -273,7 +271,7 @@ namespace Tests
m.assertEqual(summary.play_start_infos[1].start_type, "cseek")
end function
@it("a video that never played: -1 for what never happened, with its video id")
@it("a video that never played: -1 for what never happened")
function _()
m.At(100)
m.State(VideoState.Buffering)
@@ -283,7 +281,6 @@ namespace Tests
m.assertFalse(summary.DoesExist("bufferings_without_status_count"), "a buffering open at the close never reached playing")
m.assertFalse(summary.DoesExist("play_start_infos"))
m.assertFalse(summary.DoesExist("playing_ms"))
m.assertEqual(summary.video_id, "vid1")
end function
@it("DRM content from the DASH manifest url, after a retry")
@@ -316,7 +313,6 @@ namespace Tests
m.assertEqual(summary.outcome, "error")
m.assertEqual(summary.error_count, 1)
m.assertEqual(summary.playing_ms, 1000)
m.assertEqual(summary.video_id, "vid1")
end function
@it("playing under the error dialog: recovered, so the error did not end it")
@@ -329,7 +325,6 @@ namespace Tests
summary = m.SendAt(4000)
m.assertEqual(summary.outcome, "closed")
m.assertEqual(summary.error_count, 1)
m.assertEqual(summary.video_id, "vid1")
end function
@it("a finished video ends in finished")
@@ -342,7 +337,6 @@ namespace Tests
summary = m.SendAt(9000)
m.assertEqual(summary.outcome, "finished")
m.assertEqual(summary.playing_ms, 8000)
m.assertFalse(summary.DoesExist("video_id"), "a clean finish carries no video id")
end function
@it("heals: all counted, the first 3 sampled, no event of their own")
@@ -361,10 +355,9 @@ namespace Tests
m.assertEqual(summary.heal_count, 5)
m.assertEqual(summary.heal_samples.Count(), 3)
m.assertEqual(summary.heal_samples[0], { at_ms: 1000, source: "OnPosition", mode: TransportController.Mode.Scrub, position_ms: 51200, cursor_ms: 48000, floor_ms: -1 })
m.assertEqual(summary.video_id, "vid1")
end function
@it("tail resolves: all counted, the first 3 sampled, no event of their own, no video id")
@it("tail resolves: all counted, the first 3 sampled, no event of their own")
function _()
m.fakeTransport.isLive = true
m.fakeTransport.cursorMs = 6134000
@@ -384,7 +377,6 @@ namespace Tests
m.assertEqual(summary.tail_resolve_count, 4)
m.assertEqual(summary.tail_resolve_samples.Count(), 3)
m.assertEqual(summary.tail_resolve_samples[0], { at_ms: 1000, source: "OnVideoState", position_ms: 6137000, cursor_ms: 6134000, floor_ms: 6134000, edge_ms: 6640000 })
m.assertFalse(summary.DoesExist("video_id"))
end function
@it("no content: an unknown backend, no content fields")
@@ -396,6 +388,68 @@ namespace Tests
m.assertFalse(summary.DoesExist("stream_source"))
end function
@it("the live head check counts of the video load, without defaults, read once")
function _()
m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1"
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": "live1", "counts": { "checks_sent": 6, "answered_after_wait": 1, "timed_out": 0 } }))
summary = m.SendAt(1000)
m.assertEqual(summary.live_head, { "checks_sent": 6, "answered_after_wait": 1 })
m.assertFalse(CreateObject("roFileSystem").Exists(LIVE_HEAD_COUNTS_PATH), "read once")
m.assertFalse(m.SendAt(2000).DoesExist("live_head"))
end function
@it("a live play without live head check counts has none")
function _()
m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1"
DeleteFile(LIVE_HEAD_COUNTS_PATH)
m.assertFalse(m.SendAt(1000).DoesExist("live_head"))
end function
@it("leaves the live head check counts of another video load")
function _()
m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1"
handoff = FormatJson({ "video_load_id": "live2", "counts": { "checks_sent": 6 } })
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, handoff)
m.assertFalse(m.SendAt(1000).DoesExist("live_head"))
m.assertEqual(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH), handoff)
DeleteFile(LIVE_HEAD_COUNTS_PATH)
end function
@it("a live play: the first video segment's bitrate and the network's at the first playing")
function _()
m.fakeTransport.isLive = true
m.fakeTop.streamInfo = { measuredBitrate: 5000000, streamBitrate: 1200000 }
m.State(VideoState.Buffering)
m.assertFalse(m.recorder.OnStreamingSegment({ segType: SegmentType.Audio, segBitrateBps: 128000 }), "audio")
m.assertTrue(m.recorder.OnStreamingSegment({ segType: SegmentType.Video, segBitrateBps: 1200000 }), "video")
m.At(1000)
m.State(VideoState.Playing)
m.fakeTop.streamInfo = { measuredBitrate: 9000000 }
m.State(VideoState.Buffering)
m.State(VideoState.Playing)
summary = m.SendAt(2000)
m.assertEqual(summary.start_segment_bitrate_bps, 1200000)
m.assertEqual(summary.start_measured_bitrate_bps, 5000000)
end function
@it("a muxed segment carries video; a segment without a type does not")
function _()
m.assertFalse(m.recorder.OnStreamingSegment({ segBitrateBps: 1 }))
m.assertFalse(m.recorder.OnStreamingSegment(invalid))
m.assertTrue(m.recorder.OnStreamingSegment({ segType: SegmentType.Mux, segBitrateBps: 800000 }))
end function
@it("a live play that never streamed video omits the starting bitrates")
function _()
m.fakeTransport.isLive = true
summary = m.SendAt(1000)
m.assertFalse(summary.DoesExist("start_segment_bitrate_bps"))
m.assertFalse(summary.DoesExist("start_measured_bitrate_bps"))
end function
@it("a video error report: its level, fingerprint and the summary's error count")
function _()
m.fakeTop.content = { videoId: "vid1", backend: "playlet", playletStreamUrls: ["http://a", "http://b"] }
@@ -246,10 +246,8 @@ namespace Tests
"heal_samples": heals
"tail_resolve_count": tailCount
"tail_resolve_samples": tails
"video_id": "vid1"
}
if firstPlayingAtMs < 0 or underrunCount > 0 or withoutStatus > 0 or changes > 0 or errorCount > 0 or healCount > 0 or outcome = "error"
expected["video_id"] = "vid1"
end if
return m.WithoutDefaults(expected)
end function
@@ -1,11 +1,22 @@
import "pkg:/components/Web/PlayletWebServer/Middleware/DashRouter.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
import "pkg:/source/tests/Services/Dash/LiveHeadFakes.bs"
namespace Tests
@suite
class DashRouterTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.content = CreateObject("roSGNode", "Node")
@@ -20,6 +31,10 @@ namespace Tests
})
end function
protected override function afterEach()
DeleteFile(LIVE_HEAD_COUNTS_PATH)
end function
' What VideoContentJob sets on the player's content for a video load.
function PushLoad(videoLoadId as string, metadata as object)
m.content.metadata = metadata
@@ -61,7 +76,7 @@ namespace Tests
' A live load whose head was 2 at 2630 ms (a 0.63s first segment, then 2s: the
' load-time average is 1315 ms), with `overrides` on its metadata and head checks
' answering `heads` in order ({ seqnum, timeMs }) and always due.
' answering `heads` in order (Tests.FakeLiveHeadChecks) and always due.
function LoadLive(heads as object, overrides = {} as object)
metadata = {
videoId: "v"
@@ -77,21 +92,7 @@ namespace Tests
metadata.Append(overrides)
m.PushLoad("live1", metadata)
m.router.GetMetadata("live1")
m.router.heads = heads
m.router.headChecks = 0
m.router.CheckLiveHead = function() as object
m.headChecks += 1
head = m.heads.Shift()
head.response = {
StatusCode: function() as integer
return 403
end function
ErrorMessage: function(_includeBody = true as boolean) as string
return "Reason:Forbidden"
end function
}
return head
end function
Tests.FakeLiveHeadChecks(m.router.liveHeadChecks, heads)
end function
function RefreshDue()
@@ -117,13 +118,13 @@ namespace Tests
m.LoadLive([{ seqnum: 10, timeMs: 18630 }, { seqnum: 11, timeMs: 20630 }])
m.router.RefreshLiveHead()
m.router.RefreshLiveHead()
m.assertEqual(m.router.headChecks, 1)
m.assertEqual(m.router.liveHeadChecks.counts["checks_sent"], 1)
m.assertEqual(m.router.liveHeadSeqnum, 10)
end function
@it("keeps the head on a failed check, reporting the first failure of a video load only")
function _()
m.LoadLive([{ seqnum: -1, timeMs: invalid }, { seqnum: -1, timeMs: invalid }, { seqnum: -1, timeMs: invalid }])
m.LoadLive([{ seqnum: -1, timeMs: invalid }, { seqnum: -1, timeMs: invalid }])
m.global.telemetry.LogEvent = {}
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 2)
@@ -134,10 +135,54 @@ namespace Tests
' a new video load reports again
m.PushLoad("live2", { videoId: "v", adaptiveFormats: [], liveHeadUrl: "https://example.googlevideo.com/videoplayback?rn=0" })
m.router.GetMetadata("live2")
Tests.FakeLiveHeadChecks(m.router.liveHeadChecks, [{ seqnum: -1, timeMs: invalid }])
m.RefreshDue()
m.assertNotEmpty(m.global.telemetry.LogEvent)
end function
@it("takes a check answered after the wait at a later refresh")
function _()
m.LoadLive([{ seqnum: 10, timeMs: 18630, pending: true }, { seqnum: 11, timeMs: 20630, pending: true }])
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 2)
Tests.AnswerLiveHeadChecks(m.router.liveHeadChecks)
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 10)
end function
@it("takes the newest head among the checks answered since the last refresh")
function _()
m.LoadLive([{ seqnum: 12, timeMs: 22630, pending: true }, { seqnum: 10, timeMs: 18630 }])
m.RefreshDue()
Tests.AnswerLiveHeadChecks(m.router.liveHeadChecks)
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 12)
end function
@it("a new video load cancels the checks the previous one left in flight")
function _()
m.server.routes = { "/live/hung-head": { status: 200, headers: { "X-Head-Seqnum": "10" }, delayMs: 10000 } }
m.PushLoad("live1", { videoId: "v", adaptiveFormats: [], liveHeadUrl: Tests.HttpTestServerUrl("/live/hung-head?rn=0") })
m.router.GetMetadata("live1")
m.RefreshDue()
pending = m.router.liveHeadChecks.inFlight[0].pending
m.PushMetadata("vod1", "v2")
m.router.GetMetadata("vod1")
m.assertTrue(pending.Poll().IsCancelled())
m.assertInvalid(pending["_fetch"]["_urlTransfer"])
end function
@it("writes the load's head check counts at every refresh")
function _()
m.LoadLive([{ seqnum: 10, timeMs: 18630 }, { seqnum: -1, timeMs: invalid }])
m.RefreshDue()
m.RefreshDue()
handoff = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH))
m.assertEqual(handoff["video_load_id"], "live1")
m.assertEqual(handoff["counts"]["checks_sent"], 2)
m.assertEqual(handoff["counts"]["answered_without_head"], 1)
end function
@it("gives a list behind the head the cadence since load; the load head ended where the list stays ahead")
function _()
' the load head (2) ended at 3 x 1315; head 7 ends 10000 ms later, at 13945, but is
@@ -287,6 +332,42 @@ namespace Tests
m.assertEqual(m.router.liveLeadMs, 300)
end function
@describe("DashRouter.GenerateDashManifestAppendStoryboards")
function AppendStoryboards(path as string) as object
m.content.metadata = { storyboards: [{ interval: 2000, storyboardWidth: 5, storyboardHeight: 5, storyboardCount: 2, width: 160, height: 90, count: 40, templateUrl: "https://i.ytimg.com/sb/v/$M.jpg" }] }
response = {
SetBodyDataString: function(data as string) as void
m.body = data
end function
ContentType: function(mimeType as string) as void
m.contentType = mimeType
end function
Redirect: function(where as string) as void
m.redirect = where
end function
}
m.router.GenerateDashManifestAppendStoryboards({ request: { query: { url: Tests.HttpTestServerUrl(path) } }, response: response })
return response
end function
@it("adds the storyboards to the fetched manifest's period")
function _()
m.server.routes = { "/dash/manifest.mpd": { status: 200, body: "<MPD><Period><AdaptationSet id=""0""/></Period></MPD>" } }
response = m.AppendStoryboards("/dash/manifest.mpd")
m.assertEqual(response.http_code, 200)
m.assertEqual(response.contentType, "application/dash+xml")
m.assertTrue(response.body.StartsWith("<MPD><Period><AdaptationSet id=""0""/><AdaptationSet"), response.body)
m.assertTrue(response.body.EndsWith("</Period></MPD>"), response.body)
end function
@it("redirects to the manifest it couldn't fetch")
function _()
response = m.AppendStoryboards("/status/503")
m.assertEqual(response.redirect, Tests.HttpTestServerUrl("/status/503"))
m.assertInvalid(response.body)
end function
end class
end namespace
@@ -0,0 +1,82 @@
import "pkg:/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class InnertubeRouterTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.router = new Http.InnertubeRouter({ sceneNodes: { innertube: invalid, profilesService: invalid } })
end function
function Proxy(args as object) as object
response = {
Json: function(value as object) as void
m.json = value
end function
Default: function(code as integer, _message as string) as void
m.code = code
end function
}
m.router.ProxyRequest({
request: {
args: args
BodyJson: function() as object
return m.args
end function
}
response: response
})
return response
end function
function UniquePath(prefix as string) as string
return prefix + CreateObject("roDeviceInfo").GetRandomUUID()
end function
@describe("Http.InnertubeRouter.ProxyRequest")
@it("sends the method, headers and body, with our User-Agent when it has none")
function _()
proxied = m.Proxy({ Method: "POST", Url: Tests.HttpTestServerUrl("/echo"), Headers: { "X-A": "1" }, Body: "body", CacheSeconds: -1 }).json
m.assertEqual(proxied.status, 200)
echo = StringUtils.ParseJsonSafe(proxied.body)
m.assertEqual(echo.method, "POST")
m.assertEqual(echo.headers["x-a"], "1")
m.assertEqual(echo.headers["user-agent"], VIDEO_PLAYER_USER_AGENT)
m.assertEqual(echo.body, "body")
end function
@it("caches a GET for its max-age, unless CacheSeconds is negative")
function _()
cached = m.UniquePath("/maxage/60/")
m.Proxy({ Url: Tests.HttpTestServerUrl(cached), Headers: {} })
m.Proxy({ Url: Tests.HttpTestServerUrl(cached), Headers: {} })
m.assertEqual(Tests.HttpTestServerHits(m.server, cached), 1)
uncached = m.UniquePath("/maxage/60/")
m.Proxy({ Url: Tests.HttpTestServerUrl(uncached), Headers: {}, CacheSeconds: -1 })
m.Proxy({ Url: Tests.HttpTestServerUrl(uncached), Headers: {}, CacheSeconds: -1 })
m.assertEqual(Tests.HttpTestServerHits(m.server, uncached), 2)
end function
@it("rejects a key it doesn't take")
function _()
m.assertEqual(m.Proxy({ Url: Tests.HttpTestServerUrl("/echo"), Headers: {}, Timeout: 1 }).code, 400)
end function
end class
end namespace