Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
430fef1585 | ||
|
|
4754e1620b | ||
|
|
5c5fe19440 | ||
|
|
ce32d2f762 | ||
|
|
63f9ac693a | ||
|
|
5e798f19de | ||
|
|
6a4a61b61f | ||
|
|
7e21e46ec0 | ||
|
|
5e34ce8067 | ||
|
|
9d23efe7e6 | ||
|
|
7f7cf55486 | ||
|
|
ef39f1c34b | ||
|
|
98d81a4773 | ||
|
|
7310befaaf | ||
|
|
4d047909fc | ||
|
|
105b9ab12c | ||
|
|
4588e9dbbb | ||
|
|
95dff3bc07 | ||
|
|
9980b591b3 | ||
|
|
e8f1a98cfe | ||
|
|
513c13420a | ||
|
|
c32431fefc | ||
|
|
d03909f8d6 | ||
|
|
bbabb3184d |
No files matched your search
@@ -5,6 +5,40 @@ All notable changes to this project will be documented in this file.
|
|||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [0.47.5] - 2026-06-28
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Attempt to fix `No valid bitrates` error
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- Play with ytjs option from web app, as it wasn't working anyway
|
||||||
|
|
||||||
|
## [0.47.4] - 2026-06-25
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Attempt to fix `MISSING_FORMAT_FIELD` error in live videos
|
||||||
|
- Attempt to fix `No valid bitrates` error
|
||||||
|
|
||||||
|
## [0.47.3] - 2026-06-23
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Attempt to fix low quality videos, by downgrading tv client version
|
||||||
|
- Live streaming improvements
|
||||||
|
|
||||||
|
## [0.47.2] - 2026-06-21
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Attempt to fix the "The page needs to be reloaded" error by refreshing the signature timestamp automatically
|
||||||
|
- Playlists with more than one page of videos no longer stop loading after the first ~100 videos
|
||||||
|
- Report previous-run crashes to diagnostics
|
||||||
|
- Live streams no longer fail with a 502 error on transient segment failures
|
||||||
|
- Attempt to fix low quality videos, by downgrading tv client version
|
||||||
|
|
||||||
## [0.47.1] - 2026-06-18
|
## [0.47.1] - 2026-06-18
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "playlet",
|
"name": "playlet",
|
||||||
"version": "0.47.1",
|
"version": "0.47.5",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "playlet",
|
"name": "playlet",
|
||||||
"version": "0.47.1",
|
"version": "0.47.5",
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@rokucommunity/bslint": "^0.8.44",
|
"@rokucommunity/bslint": "^0.8.44",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "playlet",
|
"name": "playlet",
|
||||||
"version": "0.47.1",
|
"version": "0.47.5",
|
||||||
"description": "Unofficial YouTube client for Roku",
|
"description": "Unofficial YouTube client for Roku",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@rokucommunity/bslint": "^0.8.44",
|
"@rokucommunity/bslint": "^0.8.44",
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "playlet-app",
|
"name": "playlet-app",
|
||||||
"version": "0.47.1",
|
"version": "0.47.5",
|
||||||
"lockfileVersion": 2,
|
"lockfileVersion": 2,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "playlet-app",
|
"name": "playlet-app",
|
||||||
"version": "0.47.1"
|
"version": "0.47.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "playlet-app",
|
"name": "playlet-app",
|
||||||
"version": "0.47.1",
|
"version": "0.47.5",
|
||||||
"description": "Unofficial YouTube client for Roku",
|
"description": "Unofficial YouTube client for Roku",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prebuild": "node ../tools/rm.js ../build/playlet-app",
|
"prebuild": "node ../tools/rm.js ../build/playlet-app",
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
<field id="playletLibLoadedUrl" type="assocarray" />
|
<field id="playletLibLoadedUrl" type="assocarray" />
|
||||||
<field id="systemLogEvent" type="assocarray" alwaysNotify="true" />
|
<field id="systemLogEvent" type="assocarray" alwaysNotify="true" />
|
||||||
<field id="enableSystemLogType" type="string" />
|
<field id="enableSystemLogType" type="string" />
|
||||||
|
<field id="lastExitInfo" type="assocarray" />
|
||||||
</interface>
|
</interface>
|
||||||
<script type="text/brightscript" uri="pkg:/source/Dialog.bs" />
|
<script type="text/brightscript" uri="pkg:/source/Dialog.bs" />
|
||||||
<script type="text/brightscript" uri="pkg:/source/Manifest.bs" />
|
<script type="text/brightscript" uri="pkg:/source/Manifest.bs" />
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ title=Playlet
|
|||||||
# Do not update version manually, it is auto updated from package.json
|
# Do not update version manually, it is auto updated from package.json
|
||||||
major_version=0
|
major_version=0
|
||||||
minor_version=47
|
minor_version=47
|
||||||
build_version=00001
|
build_version=00005
|
||||||
|
|
||||||
ui_resolutions=hd
|
ui_resolutions=hd
|
||||||
uri_resolution_autosub=$$RES$$,480p,720p,1080p
|
uri_resolution_autosub=$$RES$$,480p,720p,1080p
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace AppManager
|
||||||
|
|
||||||
|
function CaptureLastExitInfo(scene as object) as void
|
||||||
|
manager = CreateObject("roAppManager")
|
||||||
|
' roAppManager.GetLastExitInfo() is only available on Roku OS 13 and above
|
||||||
|
if FindMemberFunction(manager, "GetLastExitInfo") = invalid
|
||||||
|
return
|
||||||
|
end if
|
||||||
|
lastExitInfo = manager.GetLastExitInfo()
|
||||||
|
Logger.LogLastExitInfo(lastExitInfo)
|
||||||
|
scene.lastExitInfo = lastExitInfo
|
||||||
|
end function
|
||||||
|
|
||||||
|
end namespace
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
namespace Tests
|
||||||
|
|
||||||
|
@suite
|
||||||
|
class AppManagerTests extends Rooibos.BaseTestSuite
|
||||||
|
|
||||||
|
@describe("AppManager")
|
||||||
|
|
||||||
|
@it("captures the device's last exit info onto the scene")
|
||||||
|
function _()
|
||||||
|
manager = CreateObject("roAppManager")
|
||||||
|
scene = {}
|
||||||
|
AppManager.CaptureLastExitInfo(scene)
|
||||||
|
|
||||||
|
if FindMemberFunction(manager, "GetLastExitInfo") = invalid
|
||||||
|
' Roku OS < 13: nothing to capture
|
||||||
|
m.assertInvalid(scene.lastExitInfo)
|
||||||
|
else
|
||||||
|
info = scene.lastExitInfo
|
||||||
|
m.assertAAHasKeys(info, ["exit_code", "timestamp", "app_state", "console_log"])
|
||||||
|
m.assertTrue(info.exit_code.StartsWith("EXIT_"), "exit_code should be an EXIT_* string")
|
||||||
|
m.assertTrue(Len(info.timestamp) > 0, "timestamp should be a non-empty string")
|
||||||
|
m.assertTrue(Len(info.app_state) > 0, "app_state should be a non-empty string")
|
||||||
|
m.assertTrue(GetInterface(info.console_log, "ifString") <> invalid, "console_log should be a string")
|
||||||
|
end if
|
||||||
|
end function
|
||||||
|
|
||||||
|
end class
|
||||||
|
|
||||||
|
end namespace
|
||||||
@@ -16,15 +16,7 @@ namespace Logger
|
|||||||
buffer.AppendFile(LOGS_FILE_PATH)
|
buffer.AppendFile(LOGS_FILE_PATH)
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function LogLastExitInfo() as void
|
function LogLastExitInfo(lastExitInfo as object) as void
|
||||||
' roAppManager.GetLastExitInfo() is only available on Roku OS 13 and above
|
|
||||||
appManager = CreateObject("roAppManager")
|
|
||||||
hasMethod = FindMemberFunction(appManager, "GetLastExitInfo") <> invalid
|
|
||||||
if not hasMethod
|
|
||||||
return
|
|
||||||
end if
|
|
||||||
|
|
||||||
lastExitInfo = appManager.GetLastExitInfo()
|
|
||||||
if lastExitInfo = invalid
|
if lastExitInfo = invalid
|
||||||
return
|
return
|
||||||
end if
|
end if
|
||||||
|
|||||||
@@ -24,11 +24,11 @@ function Main(args as object) as void
|
|||||||
Registry.ClearPlayletLibUrlsIfNeeded(args)
|
Registry.ClearPlayletLibUrlsIfNeeded(args)
|
||||||
Registry.ClearRegistryIfNeeded(args)
|
Registry.ClearRegistryIfNeeded(args)
|
||||||
|
|
||||||
Logger.LogLastExitInfo()
|
|
||||||
|
|
||||||
scene = screen.CreateScene("BootstrapScene")
|
scene = screen.CreateScene("BootstrapScene")
|
||||||
screen.show()
|
screen.show()
|
||||||
|
|
||||||
|
AppManager.CaptureLastExitInfo(scene)
|
||||||
|
|
||||||
SetScenePalette(scene)
|
SetScenePalette(scene)
|
||||||
scene.ObserveField("exitChannel", port)
|
scene.ObserveField("exitChannel", port)
|
||||||
scene.launchArgs = args
|
scene.launchArgs = args
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "playlet-lib",
|
"name": "playlet-lib",
|
||||||
"version": "0.47.1",
|
"version": "0.47.5",
|
||||||
"lockfileVersion": 2,
|
"lockfileVersion": 2,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "playlet-lib",
|
"name": "playlet-lib",
|
||||||
"version": "0.47.1"
|
"version": "0.47.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "playlet-lib",
|
"name": "playlet-lib",
|
||||||
"version": "0.47.1",
|
"version": "0.47.5",
|
||||||
"description": "Unofficial YouTube client for Roku",
|
"description": "Unofficial YouTube client for Roku",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prebuild": "node ../tools/rm.js ../build/playlet-lib",
|
"prebuild": "node ../tools/rm.js ../build/playlet-lib",
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
|
|
||||||
<!-- Innertube fields -->
|
<!-- Innertube fields -->
|
||||||
<field id="activeIdentifyToken" type="string" />
|
<field id="activeIdentifyToken" type="string" />
|
||||||
|
<field id="selectActiveIdentityEndpoint" type="assocarray" />
|
||||||
<field id="thumbnail" type="uri" />
|
<field id="thumbnail" type="uri" />
|
||||||
<field id="refreshToken" type="string" />
|
<field id="refreshToken" type="string" />
|
||||||
<field id="scope" type="string" />
|
<field id="scope" type="string" />
|
||||||
|
|||||||
@@ -106,31 +106,23 @@ class DashManifest
|
|||||||
}
|
}
|
||||||
nowUtc = ""
|
nowUtc = ""
|
||||||
if isLive
|
if isLive
|
||||||
' Dynamic (live) manifest: the player derives the current segment from
|
|
||||||
' wall-clock against availabilityStartTime, and the duration-based
|
|
||||||
' SegmentTemplate (see GenerateSegmentInformation) auto-extends as the
|
|
||||||
' stream advances. timeShiftBufferDepth exposes the DVR window.
|
|
||||||
segmentSec = Cint(m.GetLiveFragmentDurationMs(metadata) / 1000.0)
|
|
||||||
if segmentSec < 1
|
|
||||||
segmentSec = 1
|
|
||||||
end if
|
|
||||||
dvrWindowSec = ValidInt(metadata.liveDvrWindowSec)
|
dvrWindowSec = ValidInt(metadata.liveDvrWindowSec)
|
||||||
mpdAttributes["profiles"] = "urn:mpeg:dash:profile:isoff-live:2011"
|
mpdAttributes["profiles"] = "urn:mpeg:dash:profile:isoff-live:2011"
|
||||||
mpdAttributes["type"] = "dynamic"
|
mpdAttributes["type"] = "dynamic"
|
||||||
' Roku won't track the live edge from wall-clock unless it's handed an
|
' Roku needs an authoritative "now" to track the live edge from wall-clock; UTCTiming +
|
||||||
' authoritative "now": without it, it anchors to the Period start
|
' publishTime carry the current UTC, restamped each refresh.
|
||||||
' (availabilityStartTime) and the playhead sits ~stream-age behind. A
|
|
||||||
' direct UTCTiming + a fresh publishTime (both = current UTC, restamped on
|
|
||||||
' every refresh) give it that anchor so it computes the real live edge.
|
|
||||||
nowUtc = CreateObject("roDateTime").ToISOString()
|
nowUtc = CreateObject("roDateTime").ToISOString()
|
||||||
mpdAttributes["publishTime"] = nowUtc
|
mpdAttributes["publishTime"] = nowUtc
|
||||||
mpdAttributes["minimumUpdatePeriod"] = `PT${segmentSec}S`
|
' 20s: the duration SegmentTemplate extrapolates the edge between refreshes.
|
||||||
mpdAttributes["suggestedPresentationDelay"] = `PT${segmentSec * 3}S`
|
mpdAttributes["minimumUpdatePeriod"] = "PT20S"
|
||||||
if not StringUtils.IsNullOrEmpty(metadata.liveAvailabilityStartUtc)
|
' Cushion already lives in availabilityStartTime; present at minBufferTime.
|
||||||
mpdAttributes["availabilityStartTime"] = metadata.liveAvailabilityStartUtc
|
mpdAttributes["suggestedPresentationDelay"] = mpdAttributes["minBufferTime"]
|
||||||
|
if not StringUtils.IsNullOrEmpty(metadata.liveCushionedAvailabilityStartUtc)
|
||||||
|
mpdAttributes["availabilityStartTime"] = metadata.liveCushionedAvailabilityStartUtc
|
||||||
end if
|
end if
|
||||||
if dvrWindowSec > 0
|
if dvrWindowSec > 0
|
||||||
mpdAttributes["timeShiftBufferDepth"] = `PT${dvrWindowSec}S`
|
' Seekable range = window - cushion; the player's DVR floor uses the same value.
|
||||||
|
mpdAttributes["timeShiftBufferDepth"] = `PT${ValidInt(metadata.liveSeekableWindowSec)}S`
|
||||||
else
|
else
|
||||||
LogWarn("Live stream has no DVR window; omitting timeShiftBufferDepth (live seek may fail). videoId:", metadata.videoId)
|
LogWarn("Live stream has no DVR window; omitting timeShiftBufferDepth (live seek may fail). videoId:", metadata.videoId)
|
||||||
end if
|
end if
|
||||||
@@ -140,9 +132,7 @@ class DashManifest
|
|||||||
mpdAttributes["mediaPresentationDuration"] = `PT${duration}S`
|
mpdAttributes["mediaPresentationDuration"] = `PT${duration}S`
|
||||||
end if
|
end if
|
||||||
|
|
||||||
' Dynamic (live) manifests need an explicit Period start so the player can
|
' Live needs an explicit Period start to anchor the timeline against availabilityStartTime.
|
||||||
' anchor the timeline against availabilityStartTime; static keeps the
|
|
||||||
' attribute-less Period it has always used.
|
|
||||||
periodAttributes = {}
|
periodAttributes = {}
|
||||||
if isLive
|
if isLive
|
||||||
periodAttributes["start"] = "PT0S"
|
periodAttributes["start"] = "PT0S"
|
||||||
@@ -665,7 +655,7 @@ class DashManifest
|
|||||||
' The `v` (video id) lets the proxy cache the per-video format lookup.
|
' The `v` (video id) lets the proxy cache the per-video format lookup.
|
||||||
segBase = `${m.liveSegmentBaseUrl}/api/dash/live-seg?v=${metadata.videoId}&itag=${stream.itag}&backend=${m.liveBackend}`
|
segBase = `${m.liveSegmentBaseUrl}/api/dash/live-seg?v=${metadata.videoId}&itag=${stream.itag}&backend=${m.liveBackend}`
|
||||||
xml.EmptyNode("SegmentTemplate", {
|
xml.EmptyNode("SegmentTemplate", {
|
||||||
"initialization": `${segBase}&sq=init`
|
"initialization": `${segBase}&init=true`
|
||||||
"media": `${segBase}&sq=$Number$`
|
"media": `${segBase}&sq=$Number$`
|
||||||
"timescale": "1000"
|
"timescale": "1000"
|
||||||
"duration": durationMs
|
"duration": durationMs
|
||||||
|
|||||||
@@ -23,3 +23,5 @@ const INNERTUBE_TV_DEVICE_MODEL = "SmartTV"
|
|||||||
const INNERTUBE_TV_OS_NAME = "Tizen"
|
const INNERTUBE_TV_OS_NAME = "Tizen"
|
||||||
const INNERTUBE_TV_OS_VERSION = "4.0.0.2"
|
const INNERTUBE_TV_OS_VERSION = "4.0.0.2"
|
||||||
const INNERTUBE_TV_USER_AGENT = "Mozilla/5.0(SMART-TV; Linux; Tizen 4.0.0.2) AppleWebkit/605.1.15 (KHTML, like Gecko) SamsungBrowser/9.2 TV Safari/605.1.15"
|
const INNERTUBE_TV_USER_AGENT = "Mozilla/5.0(SMART-TV; Linux; Tizen 4.0.0.2) AppleWebkit/605.1.15 (KHTML, like Gecko) SamsungBrowser/9.2 TV Safari/605.1.15"
|
||||||
|
|
||||||
|
const INNERTUBE_TV_CLIENT_VERSION_DOWNGRADED = "5.20260114"
|
||||||
@@ -8,6 +8,7 @@ namespace Innertube
|
|||||||
Web = "WEB"
|
Web = "WEB"
|
||||||
IOS = "IOS"
|
IOS = "IOS"
|
||||||
Tv = "TV"
|
Tv = "TV"
|
||||||
|
TvDowngraded = "TV_DOWNGRADED"
|
||||||
end enum
|
end enum
|
||||||
|
|
||||||
function CreateHeaders(client as Innertube.ClientType) as object
|
function CreateHeaders(client as Innertube.ClientType) as object
|
||||||
@@ -35,6 +36,14 @@ namespace Innertube
|
|||||||
"x-youtube-client-name": INNERTUBE_TV_CLIENT_NAME
|
"x-youtube-client-name": INNERTUBE_TV_CLIENT_NAME
|
||||||
"x-youtube-client-version": INNERTUBE_TV_CLIENT_VERSION
|
"x-youtube-client-version": INNERTUBE_TV_CLIENT_VERSION
|
||||||
}
|
}
|
||||||
|
else if client = ClientType.TvDowngraded
|
||||||
|
return {
|
||||||
|
"accept": "*/*"
|
||||||
|
"accept-language": "*"
|
||||||
|
"user-agent": INNERTUBE_TV_USER_AGENT
|
||||||
|
"x-youtube-client-name": INNERTUBE_TV_CLIENT_NAME
|
||||||
|
"x-youtube-client-version": INNERTUBE_TV_CLIENT_VERSION_DOWNGRADED
|
||||||
|
}
|
||||||
else
|
else
|
||||||
throw "Invalid client type"
|
throw "Invalid client type"
|
||||||
end if
|
end if
|
||||||
@@ -42,12 +51,13 @@ namespace Innertube
|
|||||||
|
|
||||||
function CreateContext(client as Innertube.ClientType, deviceInfo as object, options = invalid as object) as object
|
function CreateContext(client as Innertube.ClientType, deviceInfo as object, options = invalid as object) as object
|
||||||
contextClient = invalid
|
contextClient = invalid
|
||||||
|
livingRoomPoTokenId = OptionUtils.Get(options, "livingRoomPoTokenId")
|
||||||
if client = ClientType.Web
|
if client = ClientType.Web
|
||||||
contextClient = CreateContextClientWeb(deviceInfo)
|
contextClient = CreateContextClientWeb(deviceInfo)
|
||||||
else if client = ClientType.IOS
|
else if client = ClientType.IOS
|
||||||
contextClient = CreateContextClientIOS(deviceInfo)
|
contextClient = CreateContextClientIOS(deviceInfo)
|
||||||
else if client = ClientType.Tv
|
else if client = ClientType.Tv or client = ClientType.TvDowngraded
|
||||||
contextClient = CreateContextClientTv(deviceInfo)
|
contextClient = CreateContextClientTv(deviceInfo, client, livingRoomPoTokenId)
|
||||||
else
|
else
|
||||||
throw "Invalid client type"
|
throw "Invalid client type"
|
||||||
end if
|
end if
|
||||||
@@ -58,8 +68,8 @@ namespace Innertube
|
|||||||
accessToken = OptionUtils.Get(options, "accessToken")
|
accessToken = OptionUtils.Get(options, "accessToken")
|
||||||
videoId = OptionUtils.Get(options, "videoId")
|
videoId = OptionUtils.Get(options, "videoId")
|
||||||
|
|
||||||
useAccessToken = client = Innertube.ClientType.TV and not StringUtils.IsNullOrEmpty(accessToken)
|
useAccessToken = (client = ClientType.Tv or client = ClientType.TvDowngraded) and not StringUtils.IsNullOrEmpty(accessToken)
|
||||||
useCtt = client = Innertube.ClientType.TV and IsAssociativeArray(credentialTransferToken) and not StringUtils.IsNullOrEmpty(videoId)
|
useCtt = (client = ClientType.Tv or client = ClientType.TvDowngraded) and IsAssociativeArray(credentialTransferToken) and not StringUtils.IsNullOrEmpty(videoId)
|
||||||
|
|
||||||
context = {
|
context = {
|
||||||
"client": contextClient
|
"client": contextClient
|
||||||
@@ -154,8 +164,12 @@ namespace Innertube
|
|||||||
}
|
}
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function CreateContextClientTv(deviceInfo as object) as object
|
function CreateContextClientTv(deviceInfo as object, client as Innertube.ClientType, livingRoomPoTokenId = "" as dynamic) as object
|
||||||
return {
|
tvClientVersion = INNERTUBE_TV_CLIENT_VERSION
|
||||||
|
if client = ClientType.TvDowngraded
|
||||||
|
tvClientVersion = INNERTUBE_TV_CLIENT_VERSION_DOWNGRADED
|
||||||
|
end if
|
||||||
|
contextClient = {
|
||||||
"hl": GetCurrentLocale(deviceInfo)
|
"hl": GetCurrentLocale(deviceInfo)
|
||||||
"gl": GetContentRegion(deviceInfo)
|
"gl": GetContentRegion(deviceInfo)
|
||||||
"remoteHost": ""
|
"remoteHost": ""
|
||||||
@@ -163,7 +177,7 @@ namespace Innertube
|
|||||||
"deviceModel": INNERTUBE_TV_DEVICE_MODEL
|
"deviceModel": INNERTUBE_TV_DEVICE_MODEL
|
||||||
"userAgent": INNERTUBE_TV_USER_AGENT
|
"userAgent": INNERTUBE_TV_USER_AGENT
|
||||||
"clientName": "TVHTML5"
|
"clientName": "TVHTML5"
|
||||||
"clientVersion": INNERTUBE_TV_CLIENT_VERSION
|
"clientVersion": tvClientVersion
|
||||||
"osName": INNERTUBE_TV_OS_NAME
|
"osName": INNERTUBE_TV_OS_NAME
|
||||||
"osVersion": INNERTUBE_TV_OS_VERSION
|
"osVersion": INNERTUBE_TV_OS_VERSION
|
||||||
"originalUrl": "https://www.youtube.com/tv"
|
"originalUrl": "https://www.youtube.com/tv"
|
||||||
@@ -192,6 +206,10 @@ namespace Innertube
|
|||||||
"playerType": "UNIPLAYER"
|
"playerType": "UNIPLAYER"
|
||||||
"connectionType": "CONN_CELLULAR_4G"
|
"connectionType": "CONN_CELLULAR_4G"
|
||||||
}
|
}
|
||||||
|
if not StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
|
||||||
|
contextClient.tvAppInfo["livingRoomPoTokenId"] = livingRoomPoTokenId
|
||||||
|
end if
|
||||||
|
return contextClient
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function GetCurrentLocale(deviceInfo as object) as string
|
function GetCurrentLocale(deviceInfo as object) as string
|
||||||
|
|||||||
@@ -4,28 +4,23 @@ import "pkg:/components/Services/Innertube/Constants.bs"
|
|||||||
import "pkg:/source/utils/StringUtils.bs"
|
import "pkg:/source/utils/StringUtils.bs"
|
||||||
|
|
||||||
function Init()
|
function Init()
|
||||||
|
m.top.observeField("requestSessionData", FuncName(OnRequestSessionData))
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function OnNodeReady()
|
function OnNodeReady()
|
||||||
OnRequestVisitorData()
|
QueueSessionDataJob()
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function OnRequestVisitorData() as void
|
function OnRequestSessionData() as void
|
||||||
if m.innertubeSessionDataJob <> invalid
|
sessionData = m.top.sessionData
|
||||||
|
if IsAssociativeArray(sessionData) and not StringUtils.IsNullOrEmpty(sessionData.visitorData) and not StringUtils.IsNullOrEmpty(sessionData.livingRoomPoTokenId)
|
||||||
return
|
return
|
||||||
end if
|
end if
|
||||||
|
QueueSessionDataJob()
|
||||||
OnForceRequestVisitorData()
|
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function OnForceRequestVisitorData() as void
|
function QueueSessionDataJob() as void
|
||||||
if m.innertubeSessionDataJob <> invalid
|
if m.innertubeSessionDataJob <> invalid and not m.innertubeSessionDataJob.done
|
||||||
m.innertubeSessionDataJob.cancel = true
|
|
||||||
m.innertubeSessionDataJob = invalid
|
|
||||||
end if
|
|
||||||
|
|
||||||
visitorData = m.top.visitorData
|
|
||||||
if not StringUtils.IsNullOrEmpty(visitorData)
|
|
||||||
return
|
return
|
||||||
end if
|
end if
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
<component name="Innertube" extends="Node" includes="AutoBind">
|
<component name="Innertube" extends="Node" includes="AutoBind">
|
||||||
<interface>
|
<interface>
|
||||||
<field id="timestamp" type="int" />
|
<field id="sessionData" type="assocarray" alwaysNotify="true" />
|
||||||
<field id="visitorData" type="string" />
|
<field id="requestSessionData" type="boolean" alwaysNotify="true" />
|
||||||
<field id="requestVisitorData" type="boolean" alwaysNotify="true" onChange="OnRequestVisitorData" />
|
|
||||||
<field id="forceRequestVisitorData" type="boolean" alwaysNotify="true" onChange="OnForceRequestVisitorData" />
|
|
||||||
<field id="jobQueue" type="node" />
|
<field id="jobQueue" type="node" />
|
||||||
</interface>
|
</interface>
|
||||||
</component>
|
</component>
|
||||||
@@ -15,6 +15,9 @@ import "pkg:/source/utils/ObjectUtils.bs"
|
|||||||
import "pkg:/source/utils/OptionUtils.bs"
|
import "pkg:/source/utils/OptionUtils.bs"
|
||||||
import "pkg:/source/utils/TimeUtils.bs"
|
import "pkg:/source/utils/TimeUtils.bs"
|
||||||
|
|
||||||
|
' DEBUG-only: force the SABR downgrade retry on every playable response.
|
||||||
|
#const DEBUG_FORCE_SABR_DOWNGRADE = false
|
||||||
|
|
||||||
namespace InnertubeService
|
namespace InnertubeService
|
||||||
|
|
||||||
function GetVideoMetadata(videoId as string, options = invalid as object) as object
|
function GetVideoMetadata(videoId as string, options = invalid as object) as object
|
||||||
@@ -38,11 +41,13 @@ namespace InnertubeService
|
|||||||
playerResponseJson = invalid
|
playerResponseJson = invalid
|
||||||
client = Innertube.ClientType.Tv
|
client = Innertube.ClientType.Tv
|
||||||
totalPlayerRequests = 0
|
totalPlayerRequests = 0
|
||||||
|
triedReloadRefresh = false
|
||||||
while true
|
while true
|
||||||
' We shouldn't be making more than 2 requests:
|
' We shouldn't be making more than 3 requests:
|
||||||
' 1. Make request with TV client.
|
' 1. Make request with TV client.
|
||||||
' 2. Make request, but STS_MISMATCH error -> retry with new STS.
|
' 2. Make request, but STS_MISMATCH error -> retry with new STS.
|
||||||
if totalPlayerRequests >= 2
|
' 3. useServerDrivenAbr -> retry with downgraded TV client version to recover format URLs.
|
||||||
|
if totalPlayerRequests >= 3
|
||||||
LogError("Too many player requests, aborting.")
|
LogError("Too many player requests, aborting.")
|
||||||
return {
|
return {
|
||||||
error: "Too many player requests"
|
error: "Too many player requests"
|
||||||
@@ -50,7 +55,7 @@ namespace InnertubeService
|
|||||||
end if
|
end if
|
||||||
totalPlayerRequests += 1
|
totalPlayerRequests += 1
|
||||||
playerRequest = Innertube.CreatePlayerRequest(client, options)
|
playerRequest = Innertube.CreatePlayerRequest(client, options)
|
||||||
if not StringUtils.IsNullOrEmpty(accessToken) and client = Innertube.ClientType.Tv
|
if not StringUtils.IsNullOrEmpty(accessToken) and (client = Innertube.ClientType.Tv or client = Innertube.ClientType.TvDowngraded)
|
||||||
playerRequest.Header("Authorization", "Bearer " + accessToken)
|
playerRequest.Header("Authorization", "Bearer " + accessToken)
|
||||||
end if
|
end if
|
||||||
playerRequest.Cancellation(cancellation)
|
playerRequest.Cancellation(cancellation)
|
||||||
@@ -76,6 +81,16 @@ namespace InnertubeService
|
|||||||
|
|
||||||
playerResponseJson = playerResponse.Json()
|
playerResponseJson = playerResponse.Json()
|
||||||
|
|
||||||
|
' Under server-driven ABR the TV client can withhold every adaptive format URL (stuck
|
||||||
|
' at 360p); the downgraded TV client is not served SABR. Retry once with it.
|
||||||
|
if client = Innertube.ClientType.Tv and IsSabrLocked(playerResponseJson)
|
||||||
|
LogInfo("SABR-locked response, retrying with downgraded TV client...")
|
||||||
|
client = Innertube.ClientType.TvDowngraded
|
||||||
|
continue while
|
||||||
|
else if client = Innertube.ClientType.TvDowngraded and not HasUsableAdaptiveUrl(playerResponseJson)
|
||||||
|
LogError("Downgraded TV client did not recover SABR-withheld format URLs")
|
||||||
|
end if
|
||||||
|
|
||||||
parsedResponse = Innertube.ParseInnertubePlayerResponse(playerRequest, playerResponse, client, cancellation)
|
parsedResponse = Innertube.ParseInnertubePlayerResponse(playerRequest, playerResponse, client, cancellation)
|
||||||
|
|
||||||
if parsedResponse.error = invalid
|
if parsedResponse.error = invalid
|
||||||
@@ -86,6 +101,11 @@ namespace InnertubeService
|
|||||||
if parsedResponse.errorCode = "STS_MISMATCH"
|
if parsedResponse.errorCode = "STS_MISMATCH"
|
||||||
LogInfo("STS_MISMATCH error, retrying...")
|
LogInfo("STS_MISMATCH error, retrying...")
|
||||||
continue while
|
continue while
|
||||||
|
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
|
||||||
else if parsedResponse.errorCode = "MISSING_FORMAT_FIELD"
|
else if parsedResponse.errorCode = "MISSING_FORMAT_FIELD"
|
||||||
useServerDrivenAbr = `${ObjectUtils.Dig(playerResponseJson, ["playerConfig", "mediaCommonConfig", "useServerDrivenAbr"])}`
|
useServerDrivenAbr = `${ObjectUtils.Dig(playerResponseJson, ["playerConfig", "mediaCommonConfig", "useServerDrivenAbr"])}`
|
||||||
LogTelemetryEvent({
|
LogTelemetryEvent({
|
||||||
@@ -126,6 +146,36 @@ namespace InnertubeService
|
|||||||
return parsedResponse
|
return parsedResponse
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
' True when the TV client's response is SABR-locked: server-driven ABR signaled with no usable
|
||||||
|
' adaptive URL.
|
||||||
|
function IsSabrLocked(playerResponseJson as object) as boolean
|
||||||
|
if not IsAssociativeArray(ObjectUtils.Dig(playerResponseJson, ["streamingData"]))
|
||||||
|
return false
|
||||||
|
end if
|
||||||
|
serverDrivenAbr = ValidBool(ObjectUtils.Dig(playerResponseJson, ["playerConfig", "mediaCommonConfig", "useServerDrivenAbr"]))
|
||||||
|
locked = serverDrivenAbr and not HasUsableAdaptiveUrl(playerResponseJson)
|
||||||
|
#if DEBUG
|
||||||
|
#if DEBUG_FORCE_SABR_DOWNGRADE
|
||||||
|
locked = true
|
||||||
|
#end if
|
||||||
|
#end if
|
||||||
|
return locked
|
||||||
|
end function
|
||||||
|
|
||||||
|
' True if any adaptive format carries a playable field (url / signatureCipher / cipher).
|
||||||
|
function HasUsableAdaptiveUrl(playerResponseJson as object) as boolean
|
||||||
|
adaptiveFormats = ObjectUtils.Dig(playerResponseJson, ["streamingData", "adaptiveFormats"])
|
||||||
|
if not IsArray(adaptiveFormats)
|
||||||
|
return false
|
||||||
|
end if
|
||||||
|
for each format in adaptiveFormats
|
||||||
|
if IsAssociativeArray(format) and (not StringUtils.IsNullOrEmpty(format["url"]) or not StringUtils.IsNullOrEmpty(format["signatureCipher"]) or not StringUtils.IsNullOrEmpty(format["cipher"]))
|
||||||
|
return true
|
||||||
|
end if
|
||||||
|
end for
|
||||||
|
return false
|
||||||
|
end function
|
||||||
|
|
||||||
function AwaitAndParseNextResponse(fetchNext as boolean, raw as boolean, parsedResponse as object, nextRequest as object) as object
|
function AwaitAndParseNextResponse(fetchNext as boolean, raw as boolean, parsedResponse as object, nextRequest as object) as object
|
||||||
if not fetchNext
|
if not fetchNext
|
||||||
return parsedResponse
|
return parsedResponse
|
||||||
|
|||||||
@@ -1,26 +1,55 @@
|
|||||||
import "pkg:/components/Services/Innertube/SessionData.bs"
|
import "pkg:/components/Services/Innertube/SessionData.bs"
|
||||||
|
import "pkg:/source/utils/StringUtils.bs"
|
||||||
|
|
||||||
@job("InnertubeSessionDataJob")
|
@job("InnertubeSessionDataJob")
|
||||||
function ExecuteJob() as void
|
function ExecuteJob() as void
|
||||||
input = JobGetInput()
|
innertubeNode = JobGetInput().innertube
|
||||||
|
|
||||||
innertubeNode = input.innertube
|
cached = Innertube.ReadSessionDataFromRegistry()
|
||||||
|
cachedVisitorData = ""
|
||||||
|
cachedLivingRoomPoTokenId = ""
|
||||||
|
if IsAssociativeArray(cached)
|
||||||
|
cachedVisitorData = ValidString(cached.visitorData)
|
||||||
|
cachedLivingRoomPoTokenId = ValidString(cached.livingRoomPoTokenId)
|
||||||
|
end if
|
||||||
|
|
||||||
cancellation = JobGetCancellation()
|
' Publish the cached values immediately so playback isn't blocked while /tv is fetched.
|
||||||
sessionData = Innertube.GetSessionData(cancellation)
|
innertubeNode.sessionData = {
|
||||||
if sessionData.error <> invalid
|
"visitorData": cachedVisitorData
|
||||||
JobError(sessionData.error)
|
"livingRoomPoTokenId": cachedLivingRoomPoTokenId
|
||||||
|
}
|
||||||
|
|
||||||
|
fresh = Innertube.RequestTvClientData(JobGetCancellation())
|
||||||
|
if fresh = invalid
|
||||||
return
|
return
|
||||||
end if
|
end if
|
||||||
|
|
||||||
innertubeNode.queueFields(true)
|
visitorData = cachedVisitorData
|
||||||
if IsInt(sessionData.timestamp)
|
timestamp = 0
|
||||||
innertubeNode.timestamp = sessionData.timestamp
|
if Innertube.IsVisitorDataFresh(cached)
|
||||||
|
visitorData = cached.visitorData
|
||||||
|
timestamp = cached.timestamp
|
||||||
|
else if not StringUtils.IsNullOrEmpty(fresh.visitorData)
|
||||||
|
visitorData = fresh.visitorData
|
||||||
|
timestamp = fresh.timestamp
|
||||||
|
else if not StringUtils.IsNullOrEmpty(cachedVisitorData)
|
||||||
|
visitorData = cachedVisitorData
|
||||||
|
timestamp = cached.timestamp
|
||||||
end if
|
end if
|
||||||
|
|
||||||
if not StringUtils.IsNullOrEmpty(sessionData.visitorData)
|
livingRoomPoTokenId = cachedLivingRoomPoTokenId
|
||||||
innertubeNode.visitorData = sessionData.visitorData
|
if not StringUtils.IsNullOrEmpty(fresh.livingRoomPoTokenId)
|
||||||
|
livingRoomPoTokenId = fresh.livingRoomPoTokenId
|
||||||
end if
|
end if
|
||||||
|
|
||||||
innertubeNode.queueFields(false)
|
Innertube.SaveSessionDataToRegistry({
|
||||||
|
"timestamp": timestamp
|
||||||
|
"visitorData": visitorData
|
||||||
|
"livingRoomPoTokenId": livingRoomPoTokenId
|
||||||
|
})
|
||||||
|
|
||||||
|
innertubeNode.sessionData = {
|
||||||
|
"visitorData": visitorData
|
||||||
|
"livingRoomPoTokenId": livingRoomPoTokenId
|
||||||
|
}
|
||||||
end function
|
end function
|
||||||
@@ -8,6 +8,10 @@ import "pkg:/source/utils/UrlUtils.bs"
|
|||||||
' under INT32_MAX (~24.8 days at timescale=1000). YouTube caps live DVR at 12h.
|
' under INT32_MAX (~24.8 days at timescale=1000). YouTube caps live DVR at 12h.
|
||||||
const LIVE_MAX_DVR_WINDOW_SEC = 43200
|
const LIVE_MAX_DVR_WINDOW_SEC = 43200
|
||||||
|
|
||||||
|
' Hold the live edge this many fragments behind the head so a momentary edge-miss refetches
|
||||||
|
' instead of erroring. Baked into liveCushionedAvailabilityStartUtc. 0 = ride the head.
|
||||||
|
const LIVE_EDGE_CUSHION_SEGMENTS = 2
|
||||||
|
|
||||||
namespace Innertube
|
namespace Innertube
|
||||||
|
|
||||||
' Live streams come back with no hlsManifestUrl/dashManifestUrl, just
|
' Live streams come back with no hlsManifestUrl/dashManifestUrl, just
|
||||||
@@ -109,12 +113,6 @@ namespace Innertube
|
|||||||
windowSec = headTimeSec
|
windowSec = headTimeSec
|
||||||
end if
|
end if
|
||||||
|
|
||||||
astDate = CreateObject("roDateTime")
|
|
||||||
astDate.FromSeconds(nowSec - windowSec)
|
|
||||||
|
|
||||||
parsedResponse["liveHeadSeqnum"] = headSeqnum
|
|
||||||
parsedResponse["liveAvailabilityStartUtc"] = astDate.ToISOString()
|
|
||||||
parsedResponse["liveDvrWindowSec"] = windowSec
|
|
||||||
' Effective per-fragment duration, derived from the stream's own counters.
|
' Effective per-fragment duration, derived from the stream's own counters.
|
||||||
' YouTube's reported targetDurationSec is unreliable for long-running streams
|
' YouTube's reported targetDurationSec is unreliable for long-running streams
|
||||||
' (observed 5s vs a real ~1.8s cadence); using it desyncs the duration-based
|
' (observed 5s vs a real ~1.8s cadence); using it desyncs the duration-based
|
||||||
@@ -122,8 +120,33 @@ namespace Innertube
|
|||||||
' (404). headTime/headSeqnum is the true average and keeps the manifest's
|
' (404). headTime/headSeqnum is the true average and keeps the manifest's
|
||||||
' wall-clock -> sq mapping anchored to the same (headTime, headSeqnum) pair
|
' wall-clock -> sq mapping anchored to the same (headTime, headSeqnum) pair
|
||||||
' that availabilityStartTime is built from.
|
' that availabilityStartTime is built from.
|
||||||
|
fragmentDurationMs = 0
|
||||||
if headSeqnum > 0
|
if headSeqnum > 0
|
||||||
parsedResponse["liveFragmentDurationMs"] = Cint((headTimeSec / headSeqnum) * 1000.0)
|
fragmentDurationMs = Cint((headTimeSec / headSeqnum) * 1000.0)
|
||||||
|
end if
|
||||||
|
|
||||||
|
astSec = nowSec - windowSec
|
||||||
|
astDate = CreateObject("roDateTime")
|
||||||
|
astDate.FromSeconds(astSec)
|
||||||
|
cushionSec = Cint(LIVE_EDGE_CUSHION_SEGMENTS * fragmentDurationMs / 1000.0)
|
||||||
|
' Younger than the cushion: shifting the anchor past now would break the edge math.
|
||||||
|
if cushionSec >= windowSec
|
||||||
|
cushionSec = 0
|
||||||
|
end if
|
||||||
|
' Shift the anchor later by the cushion so the computed edge lands a cushion behind the head.
|
||||||
|
cushionedAstDate = CreateObject("roDateTime")
|
||||||
|
cushionedAstDate.FromSeconds(astSec + cushionSec)
|
||||||
|
' Window minus the cushion; the full window would seek below startNumber.
|
||||||
|
seekableWindowSec = windowSec - cushionSec
|
||||||
|
|
||||||
|
parsedResponse["liveHeadSeqnum"] = headSeqnum
|
||||||
|
' The real (uncushioned) availabilityStartTime, kept for diagnostics.
|
||||||
|
parsedResponse["liveAvailabilityStartUtc"] = astDate.ToISOString()
|
||||||
|
parsedResponse["liveCushionedAvailabilityStartUtc"] = cushionedAstDate.ToISOString()
|
||||||
|
parsedResponse["liveDvrWindowSec"] = windowSec
|
||||||
|
parsedResponse["liveSeekableWindowSec"] = seekableWindowSec
|
||||||
|
if fragmentDurationMs > 0
|
||||||
|
parsedResponse["liveFragmentDurationMs"] = fragmentDurationMs
|
||||||
end if
|
end if
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
|||||||
@@ -88,6 +88,7 @@ namespace Innertube
|
|||||||
"feedFilterChipBarRenderer": ParseFeedFilterChipBarRenderer
|
"feedFilterChipBarRenderer": ParseFeedFilterChipBarRenderer
|
||||||
"chipBarViewModel": ParseChipBarViewModel
|
"chipBarViewModel": ParseChipBarViewModel
|
||||||
"continuationItemRenderer": ParseContinuationItemRenderer
|
"continuationItemRenderer": ParseContinuationItemRenderer
|
||||||
|
"continuationItemViewModel": ParseContinuationItemViewModel
|
||||||
"appendContinuationItemsAction": ParseAppendContinuationItemsAction
|
"appendContinuationItemsAction": ParseAppendContinuationItemsAction
|
||||||
"reloadContinuationItemsCommand": ParseReloadContinuationItemsCommand
|
"reloadContinuationItemsCommand": ParseReloadContinuationItemsCommand
|
||||||
"gridContinuation": ParseGridContinuation
|
"gridContinuation": ParseGridContinuation
|
||||||
@@ -1850,6 +1851,19 @@ namespace Innertube
|
|||||||
return invalid
|
return invalid
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
function ParseContinuationItemViewModel(nodeData as object, context as object) as object
|
||||||
|
if not StringUtils.IsNullOrEmpty(context.currentFeed.continuation)
|
||||||
|
return invalid
|
||||||
|
end if
|
||||||
|
|
||||||
|
continuation = ObjectUtils.Dig(nodeData, ["continuationCommand", "innertubeCommand", "continuationCommand", "token"])
|
||||||
|
if IsString(continuation)
|
||||||
|
context.currentFeed.continuation = continuation
|
||||||
|
end if
|
||||||
|
|
||||||
|
return invalid
|
||||||
|
end function
|
||||||
|
|
||||||
function ParseContinuationItemRenderer(nodeData as object, context as object) as object
|
function ParseContinuationItemRenderer(nodeData as object, context as object) as object
|
||||||
' In Playlists there are 2 continuation items:
|
' In Playlists there are 2 continuation items:
|
||||||
' - The first one (innermost) we encounter is the continuation for the next page of videos
|
' - The first one (innermost) we encounter is the continuation for the next page of videos
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import "pkg:/components/Services/Innertube/Context.bs"
|
|||||||
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
|
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
|
||||||
import "pkg:/components/Services/Innertube/NodesParser.bs"
|
import "pkg:/components/Services/Innertube/NodesParser.bs"
|
||||||
import "pkg:/components/Services/Innertube/OTFSegmentInfo.bs"
|
import "pkg:/components/Services/Innertube/OTFSegmentInfo.bs"
|
||||||
|
import "pkg:/components/Services/Innertube/PoTokens.bs"
|
||||||
import "pkg:/source/services/HttpClient.bs"
|
import "pkg:/source/services/HttpClient.bs"
|
||||||
import "pkg:/source/utils/ObjectUtils.bs"
|
import "pkg:/source/utils/ObjectUtils.bs"
|
||||||
import "pkg:/source/utils/Types.bs"
|
import "pkg:/source/utils/Types.bs"
|
||||||
@@ -14,15 +15,17 @@ namespace Innertube
|
|||||||
cancellation = OptionUtils.Get(options, "cancellation")
|
cancellation = OptionUtils.Get(options, "cancellation")
|
||||||
visitorData = OptionUtils.Get(options, "visitorData")
|
visitorData = OptionUtils.Get(options, "visitorData")
|
||||||
accessToken = OptionUtils.Get(options, "accessToken")
|
accessToken = OptionUtils.Get(options, "accessToken")
|
||||||
|
livingRoomPoTokenId = OptionUtils.Get(options, "livingRoomPoTokenId")
|
||||||
cpn = InnertubeService.CreateClientPlaybackNonce()
|
cpn = InnertubeService.CreateClientPlaybackNonce()
|
||||||
|
|
||||||
useAccessToken = client = Innertube.ClientType.TV and not StringUtils.IsNullOrEmpty(accessToken)
|
isTv = (client = Innertube.ClientType.Tv or client = Innertube.ClientType.TvDowngraded)
|
||||||
|
useAccessToken = isTv and not StringUtils.IsNullOrEmpty(accessToken)
|
||||||
|
|
||||||
deviceInfo = CreateObject("roDeviceInfo")
|
deviceInfo = CreateObject("roDeviceInfo")
|
||||||
|
|
||||||
context = Innertube.CreateContext(client, deviceInfo, options)
|
context = Innertube.CreateContext(client, deviceInfo, options)
|
||||||
|
|
||||||
if client = Innertube.ClientType.TV
|
if client = Innertube.ClientType.Tv or client = Innertube.ClientType.TvDowngraded
|
||||||
referer = "https://www.youtube.com/tv#/watch?v=" + videoId
|
referer = "https://www.youtube.com/tv#/watch?v=" + videoId
|
||||||
else
|
else
|
||||||
referer = "https://www.youtube.com/watch?v=" + videoId
|
referer = "https://www.youtube.com/watch?v=" + videoId
|
||||||
@@ -56,6 +59,10 @@ namespace Innertube
|
|||||||
payload["playbackContext"]["contentPlaybackContext"]["signatureTimestamp"] = signatureTimestamp
|
payload["playbackContext"]["contentPlaybackContext"]["signatureTimestamp"] = signatureTimestamp
|
||||||
end if
|
end if
|
||||||
|
|
||||||
|
if isTv
|
||||||
|
payload["playbackContext"]["contentPlaybackContext"]["isLivingRoomDeeplink"] = true
|
||||||
|
end if
|
||||||
|
|
||||||
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload)
|
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload)
|
||||||
request.Headers(Innertube.CreateHeaders(client))
|
request.Headers(Innertube.CreateHeaders(client))
|
||||||
|
|
||||||
@@ -63,6 +70,16 @@ namespace Innertube
|
|||||||
request.Header("x-goog-visitor-id", visitorData)
|
request.Header("x-goog-visitor-id", visitorData)
|
||||||
end if
|
end if
|
||||||
|
|
||||||
|
if not StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
|
||||||
|
request.poTokenIdentity = livingRoomPoTokenId
|
||||||
|
end if
|
||||||
|
|
||||||
|
if not StringUtils.IsNullOrEmpty(request.poTokenIdentity)
|
||||||
|
' NOTE: local potoken (browser-minted) is currently not in use.
|
||||||
|
' GetValidPoTokenForIdentity should return "", and the backend would mint the potoken.
|
||||||
|
request.poToken = Innertube.PoTokens.GetValidPoTokenForIdentity(request.poTokenIdentity)
|
||||||
|
end if
|
||||||
|
|
||||||
request.signatureTimestamp = signatureTimestamp
|
request.signatureTimestamp = signatureTimestamp
|
||||||
request.cpn = cpn
|
request.cpn = cpn
|
||||||
|
|
||||||
@@ -77,6 +94,9 @@ namespace Innertube
|
|||||||
error = ParsePlayerResponseForError(payload, playerRequest)
|
error = ParsePlayerResponseForError(payload, playerRequest)
|
||||||
if error <> ""
|
if error <> ""
|
||||||
parsedResponse["error"] = error
|
parsedResponse["error"] = error
|
||||||
|
if PlayerResponseRequiresPageReload(payload)
|
||||||
|
parsedResponse["errorCode"] = "RELOAD_PAGE"
|
||||||
|
end if
|
||||||
return parsedResponse
|
return parsedResponse
|
||||||
end if
|
end if
|
||||||
|
|
||||||
@@ -99,7 +119,7 @@ namespace Innertube
|
|||||||
adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"]))
|
adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"]))
|
||||||
formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"]))
|
formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"]))
|
||||||
|
|
||||||
error = DecipherUrls(formats, adaptiveFormats, playerRequest.signatureTimestamp, cancellation)
|
error = DecipherUrls(formats, adaptiveFormats, playerRequest.signatureTimestamp, cancellation, client, playerRequest.poTokenIdentity, playerRequest.poToken)
|
||||||
if error <> invalid
|
if error <> invalid
|
||||||
parsedResponse["error"] = error.error
|
parsedResponse["error"] = error.error
|
||||||
if error.DoesExist("errorCode")
|
if error.DoesExist("errorCode")
|
||||||
@@ -108,9 +128,16 @@ namespace Innertube
|
|||||||
return parsedResponse
|
return parsedResponse
|
||||||
end if
|
end if
|
||||||
|
|
||||||
' if isLive and adaptiveFormats.Count() > 0
|
parsedResponse["potAttached"] = HasPotParam(adaptiveFormats) or HasPotParam(formats)
|
||||||
' LogInfo("[LIVE-INFO] post-decipher, sts:", playerRequest.signatureTimestamp, "format[0].itag:", adaptiveFormats[0]["itag"], "url:", adaptiveFormats[0]["url"])
|
' browser = we forwarded a token; server = server minted; none = no pot attached.
|
||||||
' end if
|
if not parsedResponse["potAttached"]
|
||||||
|
parsedResponse["potSource"] = "none"
|
||||||
|
else if StringUtils.IsNullOrEmpty(playerRequest.poToken)
|
||||||
|
parsedResponse["potSource"] = "server"
|
||||||
|
else
|
||||||
|
parsedResponse["potSource"] = "browser"
|
||||||
|
end if
|
||||||
|
LogInfo("poToken attached to deciphered urls:", parsedResponse["potAttached"], "source:", parsedResponse["potSource"])
|
||||||
|
|
||||||
hasLiveStreamingData = FormatsHaveLiveStreamingData(adaptiveFormats) or FormatsHaveLiveStreamingData(formats)
|
hasLiveStreamingData = FormatsHaveLiveStreamingData(adaptiveFormats) or FormatsHaveLiveStreamingData(formats)
|
||||||
isOTF = FormatsHasTypeOTF(adaptiveFormats)
|
isOTF = FormatsHasTypeOTF(adaptiveFormats)
|
||||||
@@ -231,6 +258,11 @@ namespace Innertube
|
|||||||
return errorLines.Join(`\n`)
|
return errorLines.Join(`\n`)
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
function PlayerResponseRequiresPageReload(payload as object) as boolean
|
||||||
|
signal = ObjectUtils.Dig(payload, ["playabilityStatus", "errorScreen", "playerErrorMessageRenderer", "proceedButton", "buttonRenderer", "command", "signalAction", "signal"])
|
||||||
|
return IsString(signal) and signal = "RELOAD_PAGE"
|
||||||
|
end function
|
||||||
|
|
||||||
function ParseStoryboards(payload as object, lengthSeconds as integer) as object
|
function ParseStoryboards(payload as object, lengthSeconds as integer) as object
|
||||||
storyboard = ObjectUtils.Dig(payload, ["storyboards", "playerLiveStoryboardSpecRenderer", "spec"])
|
storyboard = ObjectUtils.Dig(payload, ["storyboards", "playerLiveStoryboardSpecRenderer", "spec"])
|
||||||
if IsString(storyboard)
|
if IsString(storyboard)
|
||||||
@@ -491,7 +523,19 @@ namespace Innertube
|
|||||||
return json["sts"]
|
return json["sts"]
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function DecipherUrls(formats as object, adaptiveFormats as object, signatureTimestamp as dynamic, cancellation as object) as object
|
function HasPotParam(formats as object) as boolean
|
||||||
|
for each fmt in formats
|
||||||
|
url = fmt["url"]
|
||||||
|
if not StringUtils.IsNullOrEmpty(url)
|
||||||
|
if url.Instr("&pot=") <> -1
|
||||||
|
return true
|
||||||
|
end if
|
||||||
|
end if
|
||||||
|
end for
|
||||||
|
return false
|
||||||
|
end function
|
||||||
|
|
||||||
|
function DecipherUrls(formats as object, adaptiveFormats as object, signatureTimestamp as dynamic, cancellation as object, client = invalid as dynamic, poTokenIdentity = invalid as dynamic, poToken = invalid as dynamic) as object
|
||||||
if signatureTimestamp = invalid
|
if signatureTimestamp = invalid
|
||||||
' No need to decipher if signatureTimestamp is not available
|
' No need to decipher if signatureTimestamp is not available
|
||||||
return invalid
|
return invalid
|
||||||
@@ -515,11 +559,20 @@ namespace Innertube
|
|||||||
})
|
})
|
||||||
end for
|
end for
|
||||||
|
|
||||||
request = HttpClient.PostJson(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`, {
|
body = {
|
||||||
"sts": signatureTimestamp
|
"sts": signatureTimestamp
|
||||||
"formats": reqFormats
|
"formats": reqFormats
|
||||||
"adaptiveFormats": reqAdaptiveFormats
|
"adaptiveFormats": reqAdaptiveFormats
|
||||||
})
|
}
|
||||||
|
if not StringUtils.IsNullOrEmpty(poTokenIdentity)
|
||||||
|
body["identity"] = poTokenIdentity
|
||||||
|
end if
|
||||||
|
LogDebug("decipher poToken identity:", poTokenIdentity)
|
||||||
|
if not StringUtils.IsNullOrEmpty(poToken)
|
||||||
|
body["poToken"] = poToken
|
||||||
|
end if
|
||||||
|
|
||||||
|
request = HttpClient.PostJson(`${PLAYLET_SUPPORT_SERVER}/v2/decipher`, body)
|
||||||
request.Cancellation(cancellation)
|
request.Cancellation(cancellation)
|
||||||
|
|
||||||
request.LogCurlCommand(false)
|
request.LogCurlCommand(false)
|
||||||
@@ -573,7 +626,7 @@ namespace Innertube
|
|||||||
for i = 0 to decipheredFormats.Count() - 1
|
for i = 0 to decipheredFormats.Count() - 1
|
||||||
fmt = formats[i]
|
fmt = formats[i]
|
||||||
decipheredFmt = decipheredFormats[i]
|
decipheredFmt = decipheredFormats[i]
|
||||||
fmt["url"] = ResetUrlClientVersion(decipheredFmt["url"])
|
fmt["url"] = ResetUrlClientVersion(decipheredFmt["url"], client)
|
||||||
end for
|
end for
|
||||||
|
|
||||||
decipheredAdaptiveFormats = json["adaptiveFormats"]
|
decipheredAdaptiveFormats = json["adaptiveFormats"]
|
||||||
@@ -587,7 +640,7 @@ namespace Innertube
|
|||||||
for i = 0 to decipheredAdaptiveFormats.Count() - 1
|
for i = 0 to decipheredAdaptiveFormats.Count() - 1
|
||||||
fmt = adaptiveFormats[i]
|
fmt = adaptiveFormats[i]
|
||||||
decipheredFmt = decipheredAdaptiveFormats[i]
|
decipheredFmt = decipheredAdaptiveFormats[i]
|
||||||
fmt["url"] = ResetUrlClientVersion(decipheredFmt["url"])
|
fmt["url"] = ResetUrlClientVersion(decipheredFmt["url"], client)
|
||||||
end for
|
end for
|
||||||
return invalid
|
return invalid
|
||||||
end function
|
end function
|
||||||
@@ -595,7 +648,7 @@ namespace Innertube
|
|||||||
' YouTube.js sets cver to hardcoded values that might be different from
|
' YouTube.js sets cver to hardcoded values that might be different from
|
||||||
' What's used in Playlet. There's no indication that this makes a difference,
|
' What's used in Playlet. There's no indication that this makes a difference,
|
||||||
' but it makes sense to keep it consistent.
|
' but it makes sense to keep it consistent.
|
||||||
function ResetUrlClientVersion(url as dynamic) as dynamic
|
function ResetUrlClientVersion(url as dynamic, requestClient = invalid as dynamic) as dynamic
|
||||||
if StringUtils.IsNullOrEmpty(url)
|
if StringUtils.IsNullOrEmpty(url)
|
||||||
return url
|
return url
|
||||||
end if
|
end if
|
||||||
@@ -603,7 +656,11 @@ namespace Innertube
|
|||||||
queryComponents = UrlUtils.ParseQueryComponents(url)
|
queryComponents = UrlUtils.ParseQueryComponents(url)
|
||||||
client = ValidString(queryComponents["c"])
|
client = ValidString(queryComponents["c"])
|
||||||
if client = "TVHTML5"
|
if client = "TVHTML5"
|
||||||
|
if requestClient = Innertube.ClientType.TvDowngraded
|
||||||
|
queryComponents["cver"] = INNERTUBE_TV_CLIENT_VERSION_DOWNGRADED
|
||||||
|
else
|
||||||
queryComponents["cver"] = INNERTUBE_TV_CLIENT_VERSION
|
queryComponents["cver"] = INNERTUBE_TV_CLIENT_VERSION
|
||||||
|
end if
|
||||||
else if client = "IOS"
|
else if client = "IOS"
|
||||||
queryComponents["cver"] = INNERTUBE_IOS_CLIENT_VERSION
|
queryComponents["cver"] = INNERTUBE_IOS_CLIENT_VERSION
|
||||||
else if client = "WEB"
|
else if client = "WEB"
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import "pkg:/source/utils/RegistryUtils.bs"
|
||||||
|
import "pkg:/source/utils/StringUtils.bs"
|
||||||
|
import "pkg:/source/utils/TimeUtils.bs"
|
||||||
|
|
||||||
|
namespace Innertube.PoTokens
|
||||||
|
|
||||||
|
const POTOKENS_VERSION = 1
|
||||||
|
|
||||||
|
function IsPoTokenEntryValid(entry as object) as boolean
|
||||||
|
if not IsAssociativeArray(entry) or StringUtils.IsNullOrEmpty(entry.token) or not IsInt(entry.expiresAt)
|
||||||
|
return false
|
||||||
|
end if
|
||||||
|
return TimeUtils.Now().AsSeconds() < entry.expiresAt
|
||||||
|
end function
|
||||||
|
|
||||||
|
function PrunePoTokens(poTokens as object) as object
|
||||||
|
pruned = {}
|
||||||
|
for each identity in poTokens
|
||||||
|
if IsPoTokenEntryValid(poTokens[identity])
|
||||||
|
pruned[identity] = poTokens[identity]
|
||||||
|
end if
|
||||||
|
end for
|
||||||
|
return pruned
|
||||||
|
end function
|
||||||
|
|
||||||
|
' Stored as { identity: { token, expiresAt, mintedAt } }; identity = visitorData or datasyncIdToken.
|
||||||
|
' Returns the valid token string for an identity (for playback), or "" if there is none.
|
||||||
|
function GetValidPoTokenForIdentity(identity as string) as string
|
||||||
|
if StringUtils.IsNullOrEmpty(identity)
|
||||||
|
return ""
|
||||||
|
end if
|
||||||
|
entry = ReadPoTokensFromRegistry()[identity]
|
||||||
|
if IsPoTokenEntryValid(entry)
|
||||||
|
return entry.token
|
||||||
|
end if
|
||||||
|
return ""
|
||||||
|
end function
|
||||||
|
|
||||||
|
' Returns the stored entry { token, expiresAt, mintedAt } for an identity, or invalid. The web
|
||||||
|
' app reads this to decide whether to re-mint.
|
||||||
|
function GetPoTokenEntryForIdentity(identity as string) as object
|
||||||
|
if StringUtils.IsNullOrEmpty(identity)
|
||||||
|
return invalid
|
||||||
|
end if
|
||||||
|
entry = ReadPoTokensFromRegistry()[identity]
|
||||||
|
if not IsAssociativeArray(entry)
|
||||||
|
return invalid
|
||||||
|
end if
|
||||||
|
return entry
|
||||||
|
end function
|
||||||
|
|
||||||
|
function StorePoToken(identity as string, token as string, expiresAt as integer, mintedAt as integer) as void
|
||||||
|
poTokens = PrunePoTokens(ReadPoTokensFromRegistry())
|
||||||
|
poTokens[identity] = {
|
||||||
|
"token": token
|
||||||
|
"expiresAt": expiresAt
|
||||||
|
"mintedAt": mintedAt
|
||||||
|
}
|
||||||
|
SavePoTokensToRegistry(poTokens)
|
||||||
|
end function
|
||||||
|
|
||||||
|
function ClearAllPoTokens() as void
|
||||||
|
SavePoTokensToRegistry({})
|
||||||
|
end function
|
||||||
|
|
||||||
|
function ReadPoTokensFromRegistry() as object
|
||||||
|
stored = RegistryUtils.Read(RegistryUtils.INNERTUBE_POTOKENS)
|
||||||
|
if StringUtils.IsNullOrEmpty(stored)
|
||||||
|
return {}
|
||||||
|
end if
|
||||||
|
parsed = StringUtils.ParseJsonSafe(stored)
|
||||||
|
if not IsAssociativeArray(parsed)
|
||||||
|
return {}
|
||||||
|
end if
|
||||||
|
if parsed.__version <> POTOKENS_VERSION
|
||||||
|
return {}
|
||||||
|
end if
|
||||||
|
if not IsAssociativeArray(parsed.tokens)
|
||||||
|
return {}
|
||||||
|
end if
|
||||||
|
return parsed.tokens
|
||||||
|
end function
|
||||||
|
|
||||||
|
function SavePoTokensToRegistry(poTokens as object) as void
|
||||||
|
RegistryUtils.Write(RegistryUtils.INNERTUBE_POTOKENS, FormatJson({
|
||||||
|
"__version": POTOKENS_VERSION
|
||||||
|
"tokens": poTokens
|
||||||
|
}))
|
||||||
|
end function
|
||||||
|
|
||||||
|
end namespace
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import "pkg:/components/Services/Innertube/Constants.bs"
|
import "pkg:/components/Services/Innertube/Constants.bs"
|
||||||
|
import "pkg:/components/Services/Innertube/Context.bs"
|
||||||
import "pkg:/source/services/HttpClient.bs"
|
import "pkg:/source/services/HttpClient.bs"
|
||||||
|
import "pkg:/source/utils/CancellationUtils.bs"
|
||||||
import "pkg:/source/utils/Logging.bs"
|
import "pkg:/source/utils/Logging.bs"
|
||||||
import "pkg:/source/utils/ObjectUtils.bs"
|
|
||||||
import "pkg:/source/utils/RegistryUtils.bs"
|
import "pkg:/source/utils/RegistryUtils.bs"
|
||||||
import "pkg:/source/utils/StringUtils.bs"
|
import "pkg:/source/utils/StringUtils.bs"
|
||||||
import "pkg:/source/utils/TimeUtils.bs"
|
import "pkg:/source/utils/TimeUtils.bs"
|
||||||
@@ -10,65 +11,89 @@ namespace Innertube
|
|||||||
|
|
||||||
const SESSION_DATA_VERSION = 1
|
const SESSION_DATA_VERSION = 1
|
||||||
const INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS = 60 * 60 * 24 * 14 ' 14 days
|
const INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS = 60 * 60 * 24 * 14 ' 14 days
|
||||||
|
const TV_CLIENT_DATA_MAX_ATTEMPTS = 3
|
||||||
|
|
||||||
function GetSessionData(cancellation = invalid as object) as object
|
function IsVisitorDataFresh(sessionData as object) as boolean
|
||||||
sessionData = ReadSessionDataFromRegistry()
|
if sessionData = invalid or not IsInt(sessionData.timestamp)
|
||||||
if sessionData <> invalid
|
return false
|
||||||
return sessionData
|
|
||||||
end if
|
end if
|
||||||
|
nowSeconds = TimeUtils.Now().AsSeconds()
|
||||||
sessionData = RequestSessionData(cancellation)
|
return nowSeconds - sessionData.timestamp <= INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS
|
||||||
if sessionData.error <> invalid
|
|
||||||
return sessionData
|
|
||||||
end if
|
|
||||||
SaveSessionDataToRegistry(sessionData)
|
|
||||||
return sessionData
|
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function RequestSessionData(cancellation = invalid as object) as object
|
function RequestTvClientData(cancellation = invalid as object) as object
|
||||||
request = HttpClient.Get("https://www.youtube.com/sw.js_data")
|
visitorData = ""
|
||||||
request.Headers({
|
livingRoomPoTokenId = ""
|
||||||
"Accept-Language": "en-US,en;q=0.9"
|
|
||||||
"User-Agent": INNERTUBE_WEB_USER_AGENT
|
|
||||||
"Accept": "*/*"
|
|
||||||
"Referer": "https://www.youtube.com/sw.js"
|
|
||||||
})
|
|
||||||
request.Cancellation(cancellation)
|
|
||||||
request.TryCount(2)
|
|
||||||
|
|
||||||
response = request.Await()
|
for attempt = 1 to TV_CLIENT_DATA_MAX_ATTEMPTS
|
||||||
if not response.IsSuccess()
|
text = FetchTvClientPage(cancellation)
|
||||||
return {
|
if text <> invalid
|
||||||
"error": "Failed to fetch session data: " + response.ErrorMessage()
|
|
||||||
}
|
|
||||||
end if
|
|
||||||
|
|
||||||
text = response.Text()
|
|
||||||
text = text.Replace(`)]}'`, "")
|
|
||||||
|
|
||||||
json = StringUtils.ParseJsonSafe(text)
|
|
||||||
if json = invalid
|
|
||||||
return {
|
|
||||||
"error": "Failed to parse session data: " + text
|
|
||||||
}
|
|
||||||
end if
|
|
||||||
|
|
||||||
visitorData = ObjectUtils.Dig(json, [0, 2, 0, 0, 13])
|
|
||||||
if StringUtils.IsNullOrEmpty(visitorData)
|
if StringUtils.IsNullOrEmpty(visitorData)
|
||||||
return {
|
visitorData = ExtractEscapedJsonString(text, "visitorData")
|
||||||
"error": "Failed to find visitorData in session data: " + text
|
end if
|
||||||
}
|
if StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
|
||||||
|
livingRoomPoTokenId = ExtractEscapedJsonString(text, "LIVING_ROOM_PO_TOKEN_ID")
|
||||||
|
end if
|
||||||
|
if not StringUtils.IsNullOrEmpty(visitorData) and not StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
|
||||||
|
exit for
|
||||||
|
end if
|
||||||
|
end if
|
||||||
|
if CancellationUtils.IsCancelled(cancellation)
|
||||||
|
exit for
|
||||||
|
end if
|
||||||
|
if attempt < TV_CLIENT_DATA_MAX_ATTEMPTS
|
||||||
|
sleep(attempt * 1000)
|
||||||
|
end if
|
||||||
|
end for
|
||||||
|
|
||||||
|
if StringUtils.IsNullOrEmpty(visitorData)
|
||||||
|
LogError("Could not extract visitorData from tv client data")
|
||||||
|
end if
|
||||||
|
if StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
|
||||||
|
LogError("Could not extract livingRoomPoTokenId from tv client data")
|
||||||
|
end if
|
||||||
|
if StringUtils.IsNullOrEmpty(visitorData) and StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
|
||||||
|
return invalid
|
||||||
end if
|
end if
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"timestamp": TimeUtils.Now().AsSeconds()
|
"timestamp": TimeUtils.Now().AsSeconds()
|
||||||
"visitorData": visitorData
|
"visitorData": visitorData
|
||||||
|
"livingRoomPoTokenId": livingRoomPoTokenId
|
||||||
}
|
}
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
function FetchTvClientPage(cancellation as object) as dynamic
|
||||||
|
request = HttpClient.Get("https://www.youtube.com/tv")
|
||||||
|
headers = Innertube.CreateHeaders(Innertube.ClientType.Tv)
|
||||||
|
headers["Referer"] = "https://www.youtube.com/tv"
|
||||||
|
request.Headers(headers)
|
||||||
|
request.Cancellation(cancellation)
|
||||||
|
request.NoCache()
|
||||||
|
|
||||||
|
response = request.Await()
|
||||||
|
if not response.IsSuccess()
|
||||||
|
LogError("Failed to fetch tv client data:", response.ErrorMessage())
|
||||||
|
return invalid
|
||||||
|
end if
|
||||||
|
return response.Text()
|
||||||
|
end function
|
||||||
|
|
||||||
|
function ExtractEscapedJsonString(text as string, key as string) as string
|
||||||
|
regex = CreateObject("roRegex", `"${key}":"([^"]*)"`, "")
|
||||||
|
match = regex.Match(text)
|
||||||
|
if match.Count() < 2
|
||||||
|
return ""
|
||||||
|
end if
|
||||||
|
decoded = StringUtils.ParseJsonSafe(`["${match[1]}"]`)
|
||||||
|
if not IsArray(decoded) or decoded.Count() <> 1
|
||||||
|
return ""
|
||||||
|
end if
|
||||||
|
return decoded[0]
|
||||||
|
end function
|
||||||
|
|
||||||
function SaveSessionDataToRegistry(sessionData as object) as void
|
function SaveSessionDataToRegistry(sessionData as object) as void
|
||||||
sessionData.__version = SESSION_DATA_VERSION
|
sessionData.__version = SESSION_DATA_VERSION
|
||||||
|
|
||||||
RegistryUtils.Write(RegistryUtils.INNERTUBE_SESSION_DATA, FormatJson(sessionData))
|
RegistryUtils.Write(RegistryUtils.INNERTUBE_SESSION_DATA, FormatJson(sessionData))
|
||||||
end function
|
end function
|
||||||
|
|
||||||
@@ -78,19 +103,7 @@ namespace Innertube
|
|||||||
return invalid
|
return invalid
|
||||||
end if
|
end if
|
||||||
|
|
||||||
sessionData = StringUtils.ParseJsonSafe(sessionData)
|
return StringUtils.ParseJsonSafe(sessionData)
|
||||||
if sessionData = invalid
|
|
||||||
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
|
|
||||||
return invalid
|
|
||||||
end if
|
|
||||||
|
|
||||||
timestamp = sessionData.timestamp
|
|
||||||
nowSeconds = TimeUtils.Now().AsSeconds()
|
|
||||||
if nowSeconds - timestamp > INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS
|
|
||||||
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
|
|
||||||
return invalid
|
|
||||||
end if
|
|
||||||
|
|
||||||
return sessionData
|
|
||||||
end function
|
end function
|
||||||
|
|
||||||
end namespace
|
end namespace
|
||||||
@@ -70,6 +70,7 @@ class LoungeApi
|
|||||||
commandHandlers[COMMAND_TYPE_SEND_DEBUG_COMMAND] = m.HandleIgnoreCommand
|
commandHandlers[COMMAND_TYPE_SEND_DEBUG_COMMAND] = m.HandleIgnoreCommand
|
||||||
commandHandlers[COMMAND_TYPE_SET_AUTOPLAY_MODE] = m.HandleIgnoreCommand
|
commandHandlers[COMMAND_TYPE_SET_AUTOPLAY_MODE] = m.HandleIgnoreCommand
|
||||||
commandHandlers[COMMAND_TYPE_GET_PARTY_GAMES_MODE] = m.HandleIgnoreCommand
|
commandHandlers[COMMAND_TYPE_GET_PARTY_GAMES_MODE] = m.HandleIgnoreCommand
|
||||||
|
commandHandlers[COMMAND_TYPE_SET_IMPACTED_SESSIONS_SERVER_EVENT] = m.HandleIgnoreCommand
|
||||||
|
|
||||||
commandHandlers[COMMAND_TYPE_GET_NOW_PLAYING] = m.HandleGetPlayingNow
|
commandHandlers[COMMAND_TYPE_GET_NOW_PLAYING] = m.HandleGetPlayingNow
|
||||||
commandHandlers[COMMAND_TYPE_SESSION_ID] = m.HandleSessionId
|
commandHandlers[COMMAND_TYPE_SESSION_ID] = m.HandleSessionId
|
||||||
@@ -86,6 +87,7 @@ class LoungeApi
|
|||||||
commandHandlers[COMMAND_TYPE_STOP_VIDEO] = m.HandleStopVideo
|
commandHandlers[COMMAND_TYPE_STOP_VIDEO] = m.HandleStopVideo
|
||||||
commandHandlers[COMMAND_TYPE_SEEK_TO] = m.HandleSeekTo
|
commandHandlers[COMMAND_TYPE_SEEK_TO] = m.HandleSeekTo
|
||||||
commandHandlers[COMMAND_TYPE_SET_PLAYBACK_SPEED] = m.HandleSetPlaybackSpeed
|
commandHandlers[COMMAND_TYPE_SET_PLAYBACK_SPEED] = m.HandleSetPlaybackSpeed
|
||||||
|
commandHandlers[COMMAND_TYPE_GET_PLAYBACK_SPEED] = m.HandleGetPlaybackSpeed
|
||||||
|
|
||||||
for each key in commandHandlers
|
for each key in commandHandlers
|
||||||
m[COMMAND_HANDLER_PREFIX + key] = commandHandlers[key]
|
m[COMMAND_HANDLER_PREFIX + key] = commandHandlers[key]
|
||||||
@@ -508,6 +510,11 @@ class LoungeApi
|
|||||||
speed = 1.0
|
speed = 1.0
|
||||||
end if
|
end if
|
||||||
|
|
||||||
|
content = player.content
|
||||||
|
if content <> invalid and content.live = true
|
||||||
|
return
|
||||||
|
end if
|
||||||
|
|
||||||
currentSpeed = ValidFloat(player.playbackSpeed)
|
currentSpeed = ValidFloat(player.playbackSpeed)
|
||||||
|
|
||||||
if Abs(currentSpeed - speed) < 0.001
|
if Abs(currentSpeed - speed) < 0.001
|
||||||
@@ -534,6 +541,27 @@ class LoungeApi
|
|||||||
messagesToSend.Push(LoungeMessages.OnPlaybackSpeedChanged(speed, true))
|
messagesToSend.Push(LoungeMessages.OnPlaybackSpeedChanged(speed, true))
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
function HandleGetPlaybackSpeed(commandId as integer, _commandType as string, _commandArgs as object, messagesToSend as object) as void
|
||||||
|
player = m.videoQueueNode.player
|
||||||
|
if player = invalid
|
||||||
|
return
|
||||||
|
end if
|
||||||
|
|
||||||
|
if not player.hasField("playbackSpeed")
|
||||||
|
LogWarn("Video node does not support 'playbackSpeed' field on this device, ignoring getPlaybackSpeed command")
|
||||||
|
return
|
||||||
|
end if
|
||||||
|
|
||||||
|
speed = ValidFloat(player.playbackSpeed)
|
||||||
|
if speed <= 0
|
||||||
|
speed = 1.0
|
||||||
|
end if
|
||||||
|
|
||||||
|
message = LoungeMessages.OnPlaybackSpeedChanged(speed)
|
||||||
|
message["commandId"] = commandId
|
||||||
|
messagesToSend.Push(message)
|
||||||
|
end function
|
||||||
|
|
||||||
function SendMessages(messages as object, loungeData = invalid as object) as void
|
function SendMessages(messages as object, loungeData = invalid as object) as void
|
||||||
if messages.Count() = 0
|
if messages.Count() = 0
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ const COMMAND_TYPE_GET_RECEIVER_STATUS = "getReceiverStatus"
|
|||||||
const COMMAND_TYPE_SEND_DEBUG_COMMAND = "sendDebugCommand"
|
const COMMAND_TYPE_SEND_DEBUG_COMMAND = "sendDebugCommand"
|
||||||
const COMMAND_TYPE_SET_AUTOPLAY_MODE = "setAutoplayMode"
|
const COMMAND_TYPE_SET_AUTOPLAY_MODE = "setAutoplayMode"
|
||||||
const COMMAND_TYPE_SET_PLAYBACK_SPEED = "setPlaybackSpeed"
|
const COMMAND_TYPE_SET_PLAYBACK_SPEED = "setPlaybackSpeed"
|
||||||
|
const COMMAND_TYPE_GET_PLAYBACK_SPEED = "getPlaybackSpeed"
|
||||||
|
const COMMAND_TYPE_SET_IMPACTED_SESSIONS_SERVER_EVENT = "setImpactedSessionsServerEvent"
|
||||||
' Special commands
|
' Special commands
|
||||||
const COMMAND_TYPE_SESSION_ID = "c"
|
const COMMAND_TYPE_SESSION_ID = "c"
|
||||||
const COMMAND_TYPE_G_SESSION_ID = "S"
|
const COMMAND_TYPE_G_SESSION_ID = "S"
|
||||||
|
|||||||
@@ -15,16 +15,18 @@ namespace LoungeMessages
|
|||||||
return message
|
return message
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function OnPlaybackSpeedChanged(speed as float, isContentSupportVSP as boolean) as object
|
function OnPlaybackSpeedChanged(speed as float, isContentSupportVSP = invalid as dynamic) as object
|
||||||
message = {
|
message = {
|
||||||
commandType: COMMAND_ON_PLAYBACK_SPEED_CHANGED
|
commandType: COMMAND_ON_PLAYBACK_SPEED_CHANGED
|
||||||
}
|
}
|
||||||
commandArgs = {}
|
commandArgs = {}
|
||||||
commandArgs[FIELD_PLAYBACK_SPEED] = speed
|
commandArgs[FIELD_PLAYBACK_SPEED] = speed
|
||||||
|
if isContentSupportVSP <> invalid
|
||||||
commandArgs[FIELD_PLAYBACK_SPEED_INFO] = FormatJson({
|
commandArgs[FIELD_PLAYBACK_SPEED_INFO] = FormatJson({
|
||||||
"playbackSpeed": speed
|
"playbackSpeed": speed
|
||||||
"isContentSupportVSP": isContentSupportVSP
|
"isContentSupportVSP": isContentSupportVSP
|
||||||
})
|
})
|
||||||
|
end if
|
||||||
message.commandArgs = commandArgs
|
message.commandArgs = commandArgs
|
||||||
return message
|
return message
|
||||||
end function
|
end function
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
#const DEBUG_THROW_ON_UNKNOWN_EXIT_CODE = true
|
||||||
|
|
||||||
|
import "pkg:/components/Telemetry/Sentry.bs"
|
||||||
|
import "pkg:/source/utils/Logging.bs"
|
||||||
|
import "pkg:/source/utils/Types.bs"
|
||||||
|
|
||||||
|
function ReportLastExitCrash() as void
|
||||||
|
scene = m.top.getScene()
|
||||||
|
if scene = invalid or not scene.hasField("lastExitInfo")
|
||||||
|
return
|
||||||
|
end if
|
||||||
|
|
||||||
|
lastExitInfo = scene.lastExitInfo
|
||||||
|
scene.lastExitInfo = invalid
|
||||||
|
if not IsAssociativeArray(lastExitInfo)
|
||||||
|
return
|
||||||
|
end if
|
||||||
|
|
||||||
|
crashExitCodes = {
|
||||||
|
"EXIT_BRIGHTSCRIPT_CRASH": true
|
||||||
|
"EXIT_BRIGHTSCRIPT_STOP": true
|
||||||
|
"EXIT_BRIGHTSCRIPT_UNK_FUNC": true
|
||||||
|
"EXIT_BRIGHTSCRIPT_TIMEOUT": true
|
||||||
|
"EXIT_OUT_OF_MEMORY": true
|
||||||
|
"EXIT_CHANNEL_MEM_LIMIT_FG": true
|
||||||
|
"EXIT_CHANNEL_MEM_LIMIT_BG": true
|
||||||
|
"EXIT_SYSTEM_KILL": true
|
||||||
|
"EXIT_GRAPHICS_NOT_RELEASED": true
|
||||||
|
"EXIT_DECODER_NOT_RELEASED": true
|
||||||
|
"EXIT_RUNNING_AFTER_SUSPEND": true
|
||||||
|
"EXIT_NOT_RESUMED": true
|
||||||
|
"EXIT_SIGNAL_TIMEOUT": true
|
||||||
|
"EXIT_APP_ERROR": true
|
||||||
|
"EXIT_UNKNOWN": false
|
||||||
|
"EXIT_POWER_MODE": false
|
||||||
|
"EXIT_DIAL_DELETE": false
|
||||||
|
"EXIT_IDLE_AUTO_EXIT": false
|
||||||
|
"EXIT_USER_KILL": false
|
||||||
|
"EXIT_USER_NAV": false
|
||||||
|
"EXIT_AM_LOWRESOURCE": false
|
||||||
|
"EXIT_UNLOADED": false
|
||||||
|
"EXIT_GUEST_MODE_ENABLED": false
|
||||||
|
"EXIT_GUEST_MODE_DISABLED": false
|
||||||
|
"EXIT_GUEST_CHECKOUT": false
|
||||||
|
"EXIT_OS_UPDATE": false
|
||||||
|
"EXIT_CHANNEL_UPDATE": false
|
||||||
|
"EXIT_CHANNEL_SIDELOAD": false
|
||||||
|
"EXIT_CHANNEL_RESTART": false
|
||||||
|
"EXIT_TILE_HIDDEN": false
|
||||||
|
"EXIT_SETTINGS_UPDATE": false
|
||||||
|
"EXIT_ADDON_DEPENDENCY": false
|
||||||
|
"EXIT_SOFTFAIL": false
|
||||||
|
}
|
||||||
|
exitCode = ValidString(lastExitInfo.exit_code)
|
||||||
|
|
||||||
|
#if DEBUG_THROW_ON_UNKNOWN_EXIT_CODE
|
||||||
|
#if DEBUG
|
||||||
|
if not crashExitCodes.DoesExist(exitCode)
|
||||||
|
throw "Unhandled exit code: " + exitCode
|
||||||
|
end if
|
||||||
|
#end if
|
||||||
|
#end if
|
||||||
|
|
||||||
|
if crashExitCodes[exitCode] = false
|
||||||
|
return
|
||||||
|
end if
|
||||||
|
|
||||||
|
message = `[FATAL][LastExit] App crashed: ${exitCode}`
|
||||||
|
for each key in lastExitInfo
|
||||||
|
message += `\n${key}: ${ToString(lastExitInfo[key])}`
|
||||||
|
end for
|
||||||
|
message = RedactAuthHeaders(message)
|
||||||
|
|
||||||
|
Sentry.SendEvents([{
|
||||||
|
level: "fatal"
|
||||||
|
message: message
|
||||||
|
timestamp: ValidString(lastExitInfo.timestamp)
|
||||||
|
fingerprint: [exitCode]
|
||||||
|
release: m.release
|
||||||
|
dist: m.dist
|
||||||
|
tags: m.tags
|
||||||
|
userId: m.userId
|
||||||
|
}])
|
||||||
|
end function
|
||||||
|
|
||||||
|
function RedactAuthHeaders(text as string) as string
|
||||||
|
authRegex = /Authorization: [^\r\n]*/i
|
||||||
|
matches = authRegex.MatchAll(text)
|
||||||
|
for each match in matches
|
||||||
|
text = text.Replace(match[0], "Authorization: <REDACTED>")
|
||||||
|
end for
|
||||||
|
return text
|
||||||
|
end function
|
||||||
@@ -67,14 +67,13 @@ namespace Sentry
|
|||||||
hasAttachments = IsArray(event.attachments) and event.attachments.Count() > 0
|
hasAttachments = IsArray(event.attachments) and event.attachments.Count() > 0
|
||||||
|
|
||||||
if (not SUPPORTS_ATTACHMENTS) and hasAttachments
|
if (not SUPPORTS_ATTACHMENTS) and hasAttachments
|
||||||
message += `\nAttachments: (${event.attachments.Count()} files)`
|
extra = {}
|
||||||
for each attachment in event.attachments
|
for each attachment in event.attachments
|
||||||
message += `\nAttachment: ${attachment.filename} (${attachment.content_type})\n${attachment.data}`
|
extra[attachment.filename] = `content_type:${attachment.content_type}\n${attachment.data}`
|
||||||
end for
|
end for
|
||||||
message += `\nEnd of attachments.`
|
eventPayload.extra = extra
|
||||||
end if
|
end if
|
||||||
|
|
||||||
' TODO:P1 compress if message is larger than 8192
|
|
||||||
eventPayload.logentry = {
|
eventPayload.logentry = {
|
||||||
formatted: message
|
formatted: message
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#const SUPPORTS_BATCHING = false
|
#const SUPPORTS_BATCHING = false
|
||||||
|
|
||||||
|
import "pkg:/components/Telemetry/LastExitCrash.bs"
|
||||||
import "pkg:/components/Telemetry/Sentry.bs"
|
import "pkg:/components/Telemetry/Sentry.bs"
|
||||||
import "pkg:/source/utils/Logging.bs"
|
import "pkg:/source/utils/Logging.bs"
|
||||||
import "pkg:/source/utils/Types.bs"
|
import "pkg:/source/utils/Types.bs"
|
||||||
@@ -47,6 +48,8 @@ function TelemetryLoop() as void
|
|||||||
m.dist = GetDist(m.tags)
|
m.dist = GetDist(m.tags)
|
||||||
m.userId = GetUserId()
|
m.userId = GetUserId()
|
||||||
|
|
||||||
|
ReportLastExitCrash()
|
||||||
|
|
||||||
m.top.observeField("LogInfo", msgPort)
|
m.top.observeField("LogInfo", msgPort)
|
||||||
m.top.observeField("LogWarn", msgPort)
|
m.top.observeField("LogWarn", msgPort)
|
||||||
m.top.observeField("LogError", msgPort)
|
m.top.observeField("LogError", msgPort)
|
||||||
|
|||||||
@@ -16,8 +16,9 @@ namespace Lounge
|
|||||||
overrides[FIELD_VIDEO_ID] = videoId
|
overrides[FIELD_VIDEO_ID] = videoId
|
||||||
end if
|
end if
|
||||||
nowPlayingMsg = LoungeMessages.NowPlaying(m.top, overrides)
|
nowPlayingMsg = LoungeMessages.NowPlaying(m.top, overrides)
|
||||||
' Sending playback speed to indicate that we will reset it to 1.0 when the content starts playing
|
' Reset the displayed speed to 1.0 on load. The content's live status (which decides VSP support)
|
||||||
playbackSpeedMsg = LoungeMessages.OnPlaybackSpeedChanged(playbackSpeed, true)
|
' isn't known yet here, so report only the speed, as the real receiver does for non-change updates.
|
||||||
|
playbackSpeedMsg = LoungeMessages.OnPlaybackSpeedChanged(playbackSpeed)
|
||||||
m.loungeService.outgoingMessages = [nowPlayingMsg, loungeStateMsg, playbackSpeedMsg]
|
m.loungeService.outgoingMessages = [nowPlayingMsg, loungeStateMsg, playbackSpeedMsg]
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import "pkg:/components/Services/Innertube/InnertubeService.bs"
|
import "pkg:/components/Services/Innertube/InnertubeService.bs"
|
||||||
import "pkg:/components/Services/Invidious/InvidiousService.bs"
|
import "pkg:/components/Services/Invidious/InvidiousService.bs"
|
||||||
|
import "pkg:/source/utils/CancellationUtils.bs"
|
||||||
|
import "pkg:/source/utils/MessagePortUtils.bs"
|
||||||
|
|
||||||
@job("VideoContentJob")
|
@job("VideoContentJob")
|
||||||
function ExecuteJob() as void
|
function ExecuteJob() as void
|
||||||
@@ -11,6 +13,7 @@ function ExecuteJob() as void
|
|||||||
preferencesNode = input.preferences
|
preferencesNode = input.preferences
|
||||||
loungeServiceNode = input.loungeService
|
loungeServiceNode = input.loungeService
|
||||||
playletServerPort = input.playletServerPort
|
playletServerPort = input.playletServerPort
|
||||||
|
profilesService = input.profilesService
|
||||||
|
|
||||||
if JobIsCancelled()
|
if JobIsCancelled()
|
||||||
JobCancel()
|
JobCancel()
|
||||||
@@ -32,36 +35,44 @@ function ExecuteJob() as void
|
|||||||
if not IsAssociativeArray(metadata)
|
if not IsAssociativeArray(metadata)
|
||||||
cancellation = JobGetCancellation()
|
cancellation = JobGetCancellation()
|
||||||
if backend = "playlet"
|
if backend = "playlet"
|
||||||
visitorData = innertubeNode.visitorData
|
|
||||||
if StringUtils.IsNullOrEmpty(visitorData)
|
sessionData = GetSessionData(innertubeNode, cancellation)
|
||||||
messagePort = CreateObject("roMessagePort")
|
if sessionData.cancel = true
|
||||||
MessagePortUtils.ObserveFieldScopedExSafe(innertubeNode, "visitorData", messagePort)
|
JobCancel()
|
||||||
innertubeNode.requestVisitorData = true
|
|
||||||
message = wait(20000, messagePort)
|
|
||||||
innertubeNode.unobserveFieldScoped("visitorData")
|
|
||||||
if message = invalid
|
|
||||||
innertubeNode.forceRequestVisitorData = true
|
|
||||||
JobError("Failed to get visitor data. Please try again later.")
|
|
||||||
return
|
return
|
||||||
end if
|
end if
|
||||||
visitorData = message.getData()
|
if sessionData.error <> invalid
|
||||||
|
JobError(sessionData.error)
|
||||||
|
return
|
||||||
end if
|
end if
|
||||||
|
|
||||||
accessToken = invalid
|
accessToken = invalid
|
||||||
onBehalfOfUser = invalid
|
onBehalfOfUser = invalid
|
||||||
|
profileNode = invalid
|
||||||
authToken = invidiousNode.authToken
|
authToken = invidiousNode.authToken
|
||||||
if authToken <> invalid and authToken.profileNode <> invalid and authToken.profileNode.type = "youtube" and not StringUtils.IsNullOrEmpty(authToken.token)
|
if authToken <> invalid and authToken.profileNode <> invalid and authToken.profileNode.type = "youtube" and not StringUtils.IsNullOrEmpty(authToken.token)
|
||||||
accessToken = authToken.token
|
accessToken = authToken.token
|
||||||
onBehalfOfUser = authToken.activeIdentifyToken
|
onBehalfOfUser = authToken.activeIdentifyToken
|
||||||
|
profileNode = authToken.profileNode
|
||||||
end if
|
end if
|
||||||
|
|
||||||
metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, {
|
metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, {
|
||||||
"cancellation": cancellation
|
"cancellation": cancellation
|
||||||
"credentialTransferToken": loungeServiceNode.credentialTransferToken
|
"credentialTransferToken": loungeServiceNode.credentialTransferToken
|
||||||
"visitorData": visitorData
|
"visitorData": sessionData.visitorData
|
||||||
|
"livingRoomPoTokenId": sessionData.livingRoomPoTokenId
|
||||||
"accessToken": accessToken
|
"accessToken": accessToken
|
||||||
"onBehalfOfUser": onBehalfOfUser
|
"onBehalfOfUser": onBehalfOfUser
|
||||||
|
"profileNode": profileNode
|
||||||
|
"profilesService": profilesService
|
||||||
})
|
})
|
||||||
|
if IsAssociativeArray(metadata)
|
||||||
|
contentNode.addFields({
|
||||||
|
potAttached: ValidBool(metadata.potAttached)
|
||||||
|
potSource: ValidString(metadata.potSource)
|
||||||
|
loggedIn: not StringUtils.IsNullOrEmpty(accessToken)
|
||||||
|
})
|
||||||
|
end if
|
||||||
else
|
else
|
||||||
metadata = service.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation })
|
metadata = service.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation })
|
||||||
end if
|
end if
|
||||||
@@ -154,6 +165,42 @@ function ExecuteJob() as void
|
|||||||
end if
|
end if
|
||||||
end function
|
end function
|
||||||
|
|
||||||
|
function GetSessionData(innertubeNode as object, cancellation as object) as object
|
||||||
|
sessionData = innertubeNode.sessionData
|
||||||
|
if SessionDataComplete(sessionData)
|
||||||
|
return sessionData
|
||||||
|
end if
|
||||||
|
|
||||||
|
port = CreateObject("roMessagePort")
|
||||||
|
MessagePortUtils.ObserveFieldScopedExSafe(innertubeNode, "sessionData", port)
|
||||||
|
CancellationUtils.ObserveCancellationScoped(cancellation, port)
|
||||||
|
|
||||||
|
innertubeNode.requestSessionData = true
|
||||||
|
message = wait(30000, port)
|
||||||
|
|
||||||
|
innertubeNode.unobserveFieldScoped("sessionData")
|
||||||
|
CancellationUtils.UnobserveCancellationScoped(cancellation)
|
||||||
|
|
||||||
|
if message <> invalid and CancellationUtils.IsCancellationEvent(cancellation, message)
|
||||||
|
return {
|
||||||
|
cancel: true
|
||||||
|
}
|
||||||
|
end if
|
||||||
|
|
||||||
|
sessionData = innertubeNode.sessionData
|
||||||
|
if SessionDataComplete(sessionData)
|
||||||
|
return sessionData
|
||||||
|
end if
|
||||||
|
|
||||||
|
return {
|
||||||
|
error: "Failed to get session data. Please try again later."
|
||||||
|
}
|
||||||
|
end function
|
||||||
|
|
||||||
|
function SessionDataComplete(sessionData as object) as boolean
|
||||||
|
return IsAssociativeArray(sessionData) and not StringUtils.IsNullOrEmpty(sessionData.visitorData) and not StringUtils.IsNullOrEmpty(sessionData.livingRoomPoTokenId)
|
||||||
|
end function
|
||||||
|
|
||||||
function CreateStreamUrls(metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object
|
function CreateStreamUrls(metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object
|
||||||
instance = service.GetInstance()
|
instance = service.GetInstance()
|
||||||
proxyVideos = preferences["invidious.proxy_videos"]
|
proxyVideos = preferences["invidious.proxy_videos"]
|
||||||
@@ -342,6 +389,10 @@ function SetCaptions(metadata as object, service as object, contentNode as objec
|
|||||||
end if
|
end if
|
||||||
|
|
||||||
isoLanguageList = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/ISO-639-1-to-ISO-639-2T.json5"))
|
isoLanguageList = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/ISO-639-1-to-ISO-639-2T.json5"))
|
||||||
|
if not IsAssociativeArray(isoLanguageList)
|
||||||
|
LogError("Failed to load ISO-639 language map; skipping captions")
|
||||||
|
return
|
||||||
|
end if
|
||||||
instance = service.GetInstance()
|
instance = service.GetInstance()
|
||||||
|
|
||||||
subtitleTracks = []
|
subtitleTracks = []
|
||||||
|
|||||||
@@ -187,6 +187,7 @@ function StartVideoContentJob(videoContentNode as object)
|
|||||||
preferences: m.top.preferences
|
preferences: m.top.preferences
|
||||||
loungeService: m.top.loungeService
|
loungeService: m.top.loungeService
|
||||||
playletServerPort: m.top.webServer.port
|
playletServerPort: m.top.webServer.port
|
||||||
|
profilesService: m.top.profilesService
|
||||||
}
|
}
|
||||||
|
|
||||||
m.videoContentJob = JobSystem.CreateCallback(OnVideoContentJobDone)
|
m.videoContentJob = JobSystem.CreateCallback(OnVideoContentJobDone)
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
<field id="invidious" type="node" bind="../../Invidious" />
|
<field id="invidious" type="node" bind="../../Invidious" />
|
||||||
<field id="webServer" type="node" bind="../../WebServer" />
|
<field id="webServer" type="node" bind="../../WebServer" />
|
||||||
<field id="loungeService" type="node" bind="../../LoungeService" />
|
<field id="loungeService" type="node" bind="../../LoungeService" />
|
||||||
|
<field id="profilesService" type="node" bind="../../ProfilesService" />
|
||||||
<field id="previousPlayer" type="node" />
|
<field id="previousPlayer" type="node" />
|
||||||
<field id="minRect" type="rect2D" value="[834,460,426,240]" />
|
<field id="minRect" type="rect2D" value="[834,460,426,240]" />
|
||||||
<field id="maxRect" type="rect2D" value="[0,0,1280,720]" />
|
<field id="maxRect" type="rect2D" value="[0,0,1280,720]" />
|
||||||
|
|||||||
@@ -1075,6 +1075,7 @@ function StartVideoContentJob(videoContentNode as object)
|
|||||||
preferences: m.top.preferences
|
preferences: m.top.preferences
|
||||||
loungeService: m.top.loungeService
|
loungeService: m.top.loungeService
|
||||||
playletServerPort: m.top.webServer.port
|
playletServerPort: m.top.webServer.port
|
||||||
|
profilesService: m.top.profilesService
|
||||||
}
|
}
|
||||||
|
|
||||||
m.videoContentJob = JobSystem.CreateCallback(OnVideoContentJobDone)
|
m.videoContentJob = JobSystem.CreateCallback(OnVideoContentJobDone)
|
||||||
@@ -1114,19 +1115,20 @@ function OnVideoContentJobDone(event as object) as void
|
|||||||
' live floor: how far back the DVR window reaches (0 = unknown -> the brain keeps the [0, edge] clamp).
|
' live floor: how far back the DVR window reaches (0 = unknown -> the brain keeps the [0, edge] clamp).
|
||||||
' The generated DASH anchors t=0 to the window start, so floor = edge - window as the session outlives it.
|
' The generated DASH anchors t=0 to the window start, so floor = edge - window as the session outlives it.
|
||||||
' The same window decides rewindability: a buffer-sized window means no live trickplay at all.
|
' The same window decides rewindability: a buffer-sized window means no live trickplay at all.
|
||||||
m.transport.SetLiveDvrWindow(ValidInt(metadata.liveDvrWindowSec) * 1000)
|
' Use the seekable depth (window - cushion) to match the manifest's timeShiftBufferDepth.
|
||||||
|
m.transport.SetLiveDvrWindow(ValidInt(metadata.liveSeekableWindowSec) * 1000)
|
||||||
m.trickPlayBar.isLive = isLive
|
m.trickPlayBar.isLive = isLive
|
||||||
m.trickPlayBar.canRewind = m.transport.CanRewindLive()
|
m.trickPlayBar.canRewind = m.transport.CanRewindLive()
|
||||||
m.bifDisplay.tileSet = invalid
|
m.bifDisplay.tileSet = invalid
|
||||||
|
|
||||||
' anchor the live edge clock at the manifest's availabilityStartTime and start the 1s heartbeat: the brain
|
' anchor the live edge clock at the cushioned availabilityStartTime and start the 1s heartbeat: the brain
|
||||||
' gets a continuous edge (OnLiveEdge) that keeps advancing through pauses, so the time-behind offset is
|
' gets a continuous edge (OnLiveEdge) that keeps advancing through pauses, so the time-behind offset is
|
||||||
' always current — including the moment the chrome reveals.
|
' always current — including the moment the chrome reveals.
|
||||||
m.liveAstSeconds = -1
|
m.liveAstSeconds = -1
|
||||||
m.liveFallbackEdgeMs = -1
|
m.liveFallbackEdgeMs = -1
|
||||||
m.liveFallbackAtSeconds = 0
|
m.liveFallbackAtSeconds = 0
|
||||||
if isLive
|
if isLive
|
||||||
ast = ValidString(metadata.liveAvailabilityStartUtc)
|
ast = ValidString(metadata.liveCushionedAvailabilityStartUtc)
|
||||||
if ast <> ""
|
if ast <> ""
|
||||||
astDate = CreateObject("roDateTime")
|
astDate = CreateObject("roDateTime")
|
||||||
astDate.FromISO8601String(ast)
|
astDate.FromISO8601String(ast)
|
||||||
@@ -1403,6 +1405,21 @@ function ReportVideoError(errorData as object, url as dynamic, urls as object, u
|
|||||||
data: ValidString(ReadAsciiFile("cachefs:/last_player_response.json"))
|
data: ValidString(ReadAsciiFile("cachefs:/last_player_response.json"))
|
||||||
}]
|
}]
|
||||||
end if
|
end if
|
||||||
|
potAttached = "false"
|
||||||
|
potSource = "none"
|
||||||
|
loggedIn = "false"
|
||||||
|
content = m.top.content
|
||||||
|
if content <> invalid
|
||||||
|
if ValidBool(content.potAttached)
|
||||||
|
potAttached = "true"
|
||||||
|
end if
|
||||||
|
if not StringUtils.IsNullOrEmpty(content.potSource)
|
||||||
|
potSource = content.potSource
|
||||||
|
end if
|
||||||
|
if ValidBool(content.loggedIn)
|
||||||
|
loggedIn = "true"
|
||||||
|
end if
|
||||||
|
end if
|
||||||
message = [
|
message = [
|
||||||
errorData.title
|
errorData.title
|
||||||
errorData.body
|
errorData.body
|
||||||
@@ -1412,8 +1429,14 @@ function ReportVideoError(errorData as object, url as dynamic, urls as object, u
|
|||||||
`Url: ${url}`
|
`Url: ${url}`
|
||||||
"Urls: " + FormatJson(urls)
|
"Urls: " + FormatJson(urls)
|
||||||
`Url index: ${urlIndex}`
|
`Url index: ${urlIndex}`
|
||||||
|
`pot_attached: ${potAttached}`
|
||||||
|
`pot_source: ${potSource}`
|
||||||
|
`logged_in: ${loggedIn}`
|
||||||
].Join(Chr(10))
|
].Join(Chr(10))
|
||||||
errorData.fingerprint.Push(shownInDialog)
|
errorData.fingerprint.Push(shownInDialog)
|
||||||
|
errorData.fingerprint.Push(potAttached)
|
||||||
|
errorData.fingerprint.Push(potSource)
|
||||||
|
errorData.fingerprint.Push(loggedIn)
|
||||||
if shownInDialog
|
if shownInDialog
|
||||||
level = "error"
|
level = "error"
|
||||||
else
|
else
|
||||||
|
|||||||
@@ -24,6 +24,7 @@
|
|||||||
<field id="invidious" type="node" bind="../../Invidious" />
|
<field id="invidious" type="node" bind="../../Invidious" />
|
||||||
<field id="webServer" type="node" bind="../../WebServer" />
|
<field id="webServer" type="node" bind="../../WebServer" />
|
||||||
<field id="loungeService" type="node" bind="../../LoungeService" />
|
<field id="loungeService" type="node" bind="../../LoungeService" />
|
||||||
|
<field id="profilesService" type="node" bind="../../ProfilesService" />
|
||||||
<field id="previousPlayer" type="node" />
|
<field id="previousPlayer" type="node" />
|
||||||
<!-- PiP rects: minRect/maxRect drive width/height/translation. -->
|
<!-- PiP rects: minRect/maxRect drive width/height/translation. -->
|
||||||
<field id="minRect" type="rect2D" value="[834,460,426,240]" />
|
<field id="minRect" type="rect2D" value="[834,460,426,240]" />
|
||||||
|
|||||||
@@ -21,12 +21,18 @@ function ExecuteJob() as void
|
|||||||
|
|
||||||
backend = preferencesNode["backend.selected"]
|
backend = preferencesNode["backend.selected"]
|
||||||
|
|
||||||
|
visitorData = ""
|
||||||
|
sessionData = innertubeNode.sessionData
|
||||||
|
if IsAssociativeArray(sessionData)
|
||||||
|
visitorData = ValidString(sessionData.visitorData)
|
||||||
|
end if
|
||||||
|
|
||||||
requestOptions = {
|
requestOptions = {
|
||||||
cacheSeconds: 8640000 ' 100 days
|
cacheSeconds: 8640000 ' 100 days
|
||||||
cancellation: cancellation
|
cancellation: cancellation
|
||||||
tryCount: 1
|
tryCount: 1
|
||||||
fetchNext: false
|
fetchNext: false
|
||||||
visitorData: innertubeNode.visitorData
|
visitorData: visitorData
|
||||||
}
|
}
|
||||||
|
|
||||||
' TODO:P1: Use InnertubeService.GetVideoInfoBatched with an array instead of loading each video individually
|
' TODO:P1: Use InnertubeService.GetVideoInfoBatched with an array instead of loading each video individually
|
||||||
|
|||||||
@@ -10,6 +10,22 @@ import "pkg:/source/utils/Types.bs"
|
|||||||
' playback; when the player asks for them the Await is short/instant. Small on
|
' playback; when the player asks for them the Await is short/instant. Small on
|
||||||
' purpose to bound concurrent roUrlTransfers (x2 representations).
|
' purpose to bound concurrent roUrlTransfers (x2 representations).
|
||||||
const LIVE_PREFETCH_SEGMENTS = 2
|
const LIVE_PREFETCH_SEGMENTS = 2
|
||||||
|
' Immediate refetches (no sleep) for transient network errors (reset/5xx) before surfacing 503.
|
||||||
|
' 204/timeout/4xx surface at once: an in-handler sleep would stall the queued audio request ~600ms
|
||||||
|
' on the single thread (measured).
|
||||||
|
const LIVE_SEG_MAX_ATTEMPTS = 3
|
||||||
|
|
||||||
|
' Why a live-segment fetch failed. The string values double as the telemetry message
|
||||||
|
' and fingerprint (see ReportSegmentFailure), so they must stay stable - changing one
|
||||||
|
' forks its Bugsink issue and orphans the history.
|
||||||
|
enum LiveSegFailure
|
||||||
|
NoFormatUrl = "no live format url"
|
||||||
|
FormatsNotArray = "adaptiveFormats not an array"
|
||||||
|
FetchFailed = "fragment fetch failed"
|
||||||
|
EmptyFragment = "empty fragment file"
|
||||||
|
NoMoov = "no moov in fragment"
|
||||||
|
NoMoof = "no moof in fragment"
|
||||||
|
end enum
|
||||||
|
|
||||||
namespace Http
|
namespace Http
|
||||||
|
|
||||||
@@ -50,7 +66,7 @@ namespace Http
|
|||||||
m.cachedInitSeqnum = 0 ' live-edge fragment to source the init from
|
m.cachedInitSeqnum = 0 ' live-edge fragment to source the init from
|
||||||
m.probeByteCount = m.INITIAL_PROBE_BYTE_COUNT ' current box-walk probe; only grows
|
m.probeByteCount = m.INITIAL_PROBE_BYTE_COUNT ' current box-walk probe; only grows
|
||||||
m.reportedFailures = {} ' per-video telemetry dedupe (see ReportSegmentFailure)
|
m.reportedFailures = {} ' per-video telemetry dedupe (see ReportSegmentFailure)
|
||||||
' Prefetch cache: "itag|nativeSq" -> in-flight StartSegmentFetch entry,
|
' Prefetch cache: "itag|sq" -> in-flight StartSegmentFetch entry,
|
||||||
' warmed ahead of the player so awaits hit already-downloading fragments.
|
' warmed ahead of the player so awaits hit already-downloading fragments.
|
||||||
m.prefetch = {}
|
m.prefetch = {}
|
||||||
' Last itag served per media kind. When the player switches representation
|
' Last itag served per media kind. When the player switches representation
|
||||||
@@ -58,6 +74,13 @@ namespace Http
|
|||||||
' so they don't leak until the next video change.
|
' so they don't leak until the next video change.
|
||||||
m.lastVideoItag = invalid
|
m.lastVideoItag = invalid
|
||||||
m.lastAudioItag = invalid
|
m.lastAudioItag = invalid
|
||||||
|
' itag -> transformed init bytes (ftyp+moov). moov is constant per
|
||||||
|
' representation, so fetch once and serve later init requests from memory.
|
||||||
|
' Cleared per video in RebuildLiveCache.
|
||||||
|
m.cachedInit = {}
|
||||||
|
' Highest native sq requested; sources the init from a current fragment (the
|
||||||
|
' load-time live edge ages out of the DVR window over a long session).
|
||||||
|
m.lastSeenSq = 0
|
||||||
end function
|
end function
|
||||||
|
|
||||||
' Returns the cached metadata AA for video id `v`, digging the videoQueue
|
' Returns the cached metadata AA for video id `v`, digging the videoQueue
|
||||||
@@ -227,7 +250,7 @@ namespace Http
|
|||||||
'
|
'
|
||||||
' Endpoint (see DashManifest live SegmentTemplate); segments map 1:1 to native
|
' Endpoint (see DashManifest live SegmentTemplate); segments map 1:1 to native
|
||||||
' fragments, so the DASH segment number is the native sq:
|
' fragments, so the DASH segment number is the native sq:
|
||||||
' /api/dash/live-seg?v=<id>&itag=<itag>&sq=init -> ftyp+moov of the live-edge fragment
|
' /api/dash/live-seg?v=<id>&itag=<itag>&init=true -> ftyp+moov of the live-edge fragment
|
||||||
' /api/dash/live-seg?v=<id>&itag=<itag>&sq=<N> -> moof+mdat of fragment N
|
' /api/dash/live-seg?v=<id>&itag=<itag>&sq=<N> -> moof+mdat of fragment N
|
||||||
'
|
'
|
||||||
' This is a hot path (called for every audio + video segment, continuously),
|
' This is a hot path (called for every audio + video segment, continuously),
|
||||||
@@ -243,10 +266,14 @@ namespace Http
|
|||||||
|
|
||||||
v = request.query.v
|
v = request.query.v
|
||||||
itag = request.query.itag
|
itag = request.query.itag
|
||||||
sq = request.query.sq
|
isInit = ValidString(request.query.init) = "true"
|
||||||
|
sq = -1
|
||||||
|
if not isInit
|
||||||
|
sq = ValidString(request.query.sq).ToInt()
|
||||||
|
end if
|
||||||
|
|
||||||
if StringUtils.IsNullOrEmpty(itag) or StringUtils.IsNullOrEmpty(sq) or StringUtils.IsNullOrEmpty(v)
|
if StringUtils.IsNullOrEmpty(itag) or StringUtils.IsNullOrEmpty(v) or (not isInit and sq <= 0)
|
||||||
response.Default(400, "Missing v, itag or sq")
|
response.Default(400, "Missing or invalid v, itag, or sq")
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
|
|
||||||
@@ -257,30 +284,37 @@ namespace Http
|
|||||||
baseUrl = m.cachedUrls[itag]
|
baseUrl = m.cachedUrls[itag]
|
||||||
if StringUtils.IsNullOrEmpty(baseUrl)
|
if StringUtils.IsNullOrEmpty(baseUrl)
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] no live format url for v:", v, "itag:", itag, "-> 404")
|
LogErrorNoTelemetry("[LIVE-SEG] no live format url for v:", v, "itag:", itag, "-> 404")
|
||||||
m.ReportSegmentFailure("no live format url", { v: v, itag: itag, sq: sq })
|
m.ReportSegmentFailure(LiveSegFailure.NoFormatUrl, { v: v, itag: itag, sq: sq })
|
||||||
response.Default(404, "No live format url for itag " + itag)
|
response.Default(404, "No live format url for itag " + itag)
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
|
|
||||||
if sq = "init"
|
if isInit
|
||||||
' Init segment: ftyp+moov. We must NOT use fragment 0 - for a
|
' ftyp+moov, served from the per-itag cache after the first fetch.
|
||||||
' long-running live stream (e.g. a 24/7 channel up for weeks) sq=0 is
|
output = m.cachedInit[itag]
|
||||||
' far outside the DVR window and googlevideo 404s it. Every live
|
|
||||||
' fragment is self-initializing with an identical moov (constant
|
|
||||||
' codec config), so we source the init from the live-edge fragment
|
|
||||||
' (cachedInitSeqnum), which is always within the DVR window.
|
|
||||||
output = m.AwaitTransformedSegment(m.StartSegmentFetch(baseUrl, m.cachedInitSeqnum, v, itag), true)
|
|
||||||
if output = invalid
|
if output = invalid
|
||||||
' Root-cause telemetry already emitted by AwaitTransformedSegment.
|
' Source from a current fragment: sq=0 is outside the DVR window (404)
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] INIT fetch failed v:", v, "itag:", itag, "-> 502")
|
' and the load-time edge ages out, so prefer lastSeenSq; fall back to
|
||||||
response.Default(502, "Failed to fetch live init segment")
|
' the load-time seqnum only before any media segment is served.
|
||||||
|
initSq = m.cachedInitSeqnum
|
||||||
|
if m.lastSeenSq > 0
|
||||||
|
initSq = m.lastSeenSq
|
||||||
|
end if
|
||||||
|
output = m.AwaitSegmentWithRetry(baseUrl, initSq, v, itag, true, invalid)
|
||||||
|
if output = invalid
|
||||||
|
LogErrorNoTelemetry("[LIVE-SEG] INIT fetch failed v:", v, "itag:", itag, "-> 503")
|
||||||
|
response.Default(503, "Live init segment not ready")
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
|
m.cachedInit[itag] = output
|
||||||
|
end if
|
||||||
else
|
else
|
||||||
' Media DASH segment = one native YouTube fragment, reduced to moof+mdat
|
' Media DASH segment = one native YouTube fragment, reduced to moof+mdat
|
||||||
' so Roku reads the init segment only once. The manifest addresses the
|
' so Roku reads the init segment only once. The manifest addresses the
|
||||||
' proxy 1:1, so the DASH segment number is the native sq.
|
' proxy 1:1, so the DASH segment number is the native sq.
|
||||||
nativeSq = sq.ToInt()
|
if sq > m.lastSeenSq
|
||||||
|
m.lastSeenSq = sq
|
||||||
|
end if
|
||||||
|
|
||||||
' Representation switch (ABR video / audio track): the previous itag of
|
' Representation switch (ABR video / audio track): the previous itag of
|
||||||
' this kind stops being requested, so evict its warmed fragments now -
|
' this kind stops being requested, so evict its warmed fragments now -
|
||||||
@@ -302,15 +336,16 @@ namespace Http
|
|||||||
' (Send, no Await) BEFORE blocking here so their downloads overlap this
|
' (Send, no Await) BEFORE blocking here so their downloads overlap this
|
||||||
' fragment's await + playback; then drop entries now outside the window
|
' fragment's await + playback; then drop entries now outside the window
|
||||||
' (played past, or stranded by a seek) so the cache + temp files stay bounded.
|
' (played past, or stranded by a seek) so the cache + temp files stay bounded.
|
||||||
entry = m.GetOrStartFetch(baseUrl, nativeSq, v, itag)
|
entry = m.GetOrStartFetch(baseUrl, sq, v, itag)
|
||||||
m.PrefetchAhead(baseUrl, v, itag, nativeSq, LIVE_PREFETCH_SEGMENTS)
|
m.PrefetchAhead(baseUrl, v, itag, sq, LIVE_PREFETCH_SEGMENTS)
|
||||||
m.EvictPrefetchOutside(itag, nativeSq + 1, nativeSq + LIVE_PREFETCH_SEGMENTS)
|
m.EvictPrefetchOutside(itag, sq + 1, sq + LIVE_PREFETCH_SEGMENTS)
|
||||||
|
|
||||||
output = m.AwaitTransformedSegment(entry, false)
|
output = m.AwaitSegmentWithRetry(baseUrl, sq, v, itag, false, entry)
|
||||||
if output = invalid
|
if output = invalid
|
||||||
' Root-cause telemetry already emitted by AwaitTransformedSegment.
|
' 503 makes Roku re-request the same sq and hold the bitrate (verified); the
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] media fragment failed v:", v, "itag:", itag, "sq:", nativeSq, "-> 502")
|
' fragment will exist within ~one re-request.
|
||||||
response.Default(502, "Failed to fetch live media segment")
|
LogErrorNoTelemetry("[LIVE-SEG] media fragment not ready v:", v, "itag:", itag, "sq:", sq, "-> 503")
|
||||||
|
response.Default(503, "Live media segment not ready")
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
end if
|
end if
|
||||||
@@ -338,6 +373,9 @@ namespace Http
|
|||||||
m.CleanupTempSegments()
|
m.CleanupTempSegments()
|
||||||
' Re-arm the per-video telemetry dedupe (see ReportSegmentFailure).
|
' Re-arm the per-video telemetry dedupe (see ReportSegmentFailure).
|
||||||
m.reportedFailures = {}
|
m.reportedFailures = {}
|
||||||
|
' Init bytes and the sq high-water mark belong to the previous video.
|
||||||
|
m.cachedInit = {}
|
||||||
|
m.lastSeenSq = 0
|
||||||
|
|
||||||
urls = {}
|
urls = {}
|
||||||
types = {}
|
types = {}
|
||||||
@@ -355,7 +393,7 @@ namespace Http
|
|||||||
end for
|
end for
|
||||||
else
|
else
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] RebuildLiveCache: adaptiveFormats not an array for v:", metadata.videoId)
|
LogErrorNoTelemetry("[LIVE-SEG] RebuildLiveCache: adaptiveFormats not an array for v:", metadata.videoId)
|
||||||
m.ReportSegmentFailure("adaptiveFormats not an array", { v: ValidString(metadata.videoId) })
|
m.ReportSegmentFailure(LiveSegFailure.FormatsNotArray, { v: ValidString(metadata.videoId) })
|
||||||
end if
|
end if
|
||||||
|
|
||||||
m.cachedUrls = urls
|
m.cachedUrls = urls
|
||||||
@@ -475,22 +513,66 @@ namespace Http
|
|||||||
DeleteFile(entry.tmpPath)
|
DeleteFile(entry.tmpPath)
|
||||||
end function
|
end function
|
||||||
|
|
||||||
' Await a fetch started by StartSegmentFetch and return just the bytes Roku
|
' Await `entry` (invalid -> fetch fresh), transform to the bytes Roku needs (wantInit ->
|
||||||
' needs:
|
' ftyp+moov, else moof+mdat), retrying transient failures up to LIVE_SEG_MAX_ATTEMPTS. Each
|
||||||
' wantInit = true -> ftyp+moov (init segment)
|
' retry refetches the same sq, which also un-poisons a prefetched 204. Telemetry fires once.
|
||||||
' wantInit = false -> moof+mdat (media segment)
|
function AwaitSegmentWithRetry(baseUrl as string, sq as integer, v as string, itag as string, wantInit as boolean, entry as object) as dynamic
|
||||||
' Reads only the required byte range from the temp file and always deletes
|
if entry = invalid
|
||||||
' it. Returns invalid on failure.
|
entry = m.StartSegmentFetch(baseUrl, sq, v, itag)
|
||||||
function AwaitTransformedSegment(entry as object, wantInit as boolean) as dynamic
|
end if
|
||||||
|
|
||||||
|
attempt = 1
|
||||||
|
while true
|
||||||
|
result = m.AttemptSegment(entry, wantInit)
|
||||||
|
if result.ok
|
||||||
|
return result.bytes
|
||||||
|
end if
|
||||||
|
|
||||||
|
' 204 = sq not produced yet. Return 503 and let Roku re-ask (same sq, then resyncs);
|
||||||
|
' a sleep+refetch here would stall the queued audio ~600ms on the single thread
|
||||||
|
' (measured). Evict the warmed siblings - fetched too early, they 204'd too.
|
||||||
|
if result.reason = LiveSegFailure.EmptyFragment
|
||||||
|
if not wantInit
|
||||||
|
m.EvictPrefetchItag(itag)
|
||||||
|
end if
|
||||||
|
m.ReportSegmentFailure(result.reason, { v: v, itag: itag, sq: sq, head: m.liveHeadSeqnum, segUrl: entry.segUrl, response: result.response })
|
||||||
|
return invalid
|
||||||
|
end if
|
||||||
|
|
||||||
|
if (not result.retryable) or attempt >= LIVE_SEG_MAX_ATTEMPTS
|
||||||
|
m.ReportSegmentFailure(result.reason, { v: v, itag: itag, sq: sq, head: m.liveHeadSeqnum, segUrl: entry.segUrl, response: result.response })
|
||||||
|
return invalid
|
||||||
|
end if
|
||||||
|
|
||||||
|
' Network/5xx: transient; discard and refetch immediately (no sleep).
|
||||||
|
LogWarnNoTelemetry("[LIVE-SEG] retry sq", sq, "itag", itag, "(", result.reason, ") attempt", attempt + 1, "of", LIVE_SEG_MAX_ATTEMPTS)
|
||||||
|
|
||||||
|
attempt += 1
|
||||||
|
entry = m.StartSegmentFetch(baseUrl, sq, v, itag)
|
||||||
|
end while
|
||||||
|
|
||||||
|
return invalid
|
||||||
|
end function
|
||||||
|
|
||||||
|
' One fetch+transform attempt. Reads only the needed byte range from the temp
|
||||||
|
' file and always deletes it. Returns:
|
||||||
|
' { ok: true, bytes } - the transformed segment bytes
|
||||||
|
' { ok: false, retryable, reason, response } - failed; `retryable` marks fast transient
|
||||||
|
' NETWORK errors (reset/-10001, 5xx) worth an immediate refetch. 204/empty is handled
|
||||||
|
' specially by the caller (immediate 503); timeout/4xx/malformed are not retried.
|
||||||
|
function AttemptSegment(entry as object, wantInit as boolean) as object
|
||||||
tmpPath = entry.tmpPath
|
tmpPath = entry.tmpPath
|
||||||
sq = entry.sq
|
sq = entry.sq
|
||||||
|
|
||||||
response = entry.req.Await()
|
response = entry.req.Await()
|
||||||
|
m.liveHeadSeqnum = m.ReadHeadSeqnum(response)
|
||||||
if not response.IsSuccess()
|
if not response.IsSuccess()
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "failed:", response.StatusCode())
|
status = response.StatusCode()
|
||||||
m.ReportSegmentFailure("fragment fetch failed", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response })
|
LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "failed:", status)
|
||||||
DeleteFile(tmpPath)
|
DeleteFile(tmpPath)
|
||||||
return invalid
|
' status<0 = active error event (reset/-10001), 5xx = server error: both
|
||||||
|
' transient -> retried. status 0 = timeout (slow/hung) -> not retried.
|
||||||
|
return { ok: false, retryable: status < 0 or status >= 500, reason: LiveSegFailure.FetchFailed, response: response }
|
||||||
end if
|
end if
|
||||||
|
|
||||||
stat = m.fs.Stat(tmpPath)
|
stat = m.fs.Stat(tmpPath)
|
||||||
@@ -499,10 +581,10 @@ namespace Http
|
|||||||
fileLen = ValidInt(stat.size)
|
fileLen = ValidInt(stat.size)
|
||||||
end if
|
end if
|
||||||
if fileLen <= 0
|
if fileLen <= 0
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "empty file")
|
LogErrorNoTelemetry("[LIVE-SEG] fetch sq", sq, "empty file (status", response.StatusCode(), ")")
|
||||||
m.ReportSegmentFailure("empty fragment file", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response })
|
|
||||||
DeleteFile(tmpPath)
|
DeleteFile(tmpPath)
|
||||||
return invalid
|
' 204/empty handled specially by the caller (immediate 503, no in-handler retry).
|
||||||
|
return { ok: false, retryable: false, reason: LiveSegFailure.EmptyFragment, response: response }
|
||||||
end if
|
end if
|
||||||
|
|
||||||
boxes = m.LocateBoxes(tmpPath, fileLen)
|
boxes = m.LocateBoxes(tmpPath, fileLen)
|
||||||
@@ -511,23 +593,32 @@ namespace Http
|
|||||||
if wantInit
|
if wantInit
|
||||||
if boxes.moovEnd <= 0 or boxes.moovEnd > fileLen
|
if boxes.moovEnd <= 0 or boxes.moovEnd > fileLen
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] no moov in fragment sq", sq, "(moovEnd:", boxes.moovEnd, ")")
|
LogErrorNoTelemetry("[LIVE-SEG] no moov in fragment sq", sq, "(moovEnd:", boxes.moovEnd, ")")
|
||||||
m.ReportSegmentFailure("no moov in fragment", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response })
|
|
||||||
DeleteFile(tmpPath)
|
DeleteFile(tmpPath)
|
||||||
return invalid
|
return { ok: false, retryable: false, reason: LiveSegFailure.NoMoov, response: response }
|
||||||
end if
|
end if
|
||||||
out.ReadFile(tmpPath, 0, boxes.moovEnd)
|
out.ReadFile(tmpPath, 0, boxes.moovEnd)
|
||||||
else
|
else
|
||||||
if boxes.moofStart <= 0 or boxes.moofStart >= fileLen
|
if boxes.moofStart <= 0 or boxes.moofStart >= fileLen
|
||||||
LogErrorNoTelemetry("[LIVE-SEG] no moof in fragment sq", sq, "(moofStart:", boxes.moofStart, ")")
|
LogErrorNoTelemetry("[LIVE-SEG] no moof in fragment sq", sq, "(moofStart:", boxes.moofStart, ")")
|
||||||
m.ReportSegmentFailure("no moof in fragment", { v: entry.v, itag: entry.itag, sq: sq, segUrl: entry.segUrl, response: response })
|
|
||||||
DeleteFile(tmpPath)
|
DeleteFile(tmpPath)
|
||||||
return invalid
|
return { ok: false, retryable: false, reason: LiveSegFailure.NoMoof, response: response }
|
||||||
end if
|
end if
|
||||||
out.ReadFile(tmpPath, boxes.moofStart, fileLen - boxes.moofStart)
|
out.ReadFile(tmpPath, boxes.moofStart, fileLen - boxes.moofStart)
|
||||||
end if
|
end if
|
||||||
|
|
||||||
DeleteFile(tmpPath)
|
DeleteFile(tmpPath)
|
||||||
return out
|
return { ok: true, bytes: out }
|
||||||
|
end function
|
||||||
|
|
||||||
|
' Live head sequence number from a fragment response's X-Head-Seqnum header (-1 if
|
||||||
|
' absent). Stashed (m.liveHeadSeqnum) so ReportSegmentFailure records how far ahead of
|
||||||
|
' the real edge a failed sq was (delta = sq - head) - the field signal for edge overshoot.
|
||||||
|
function ReadHeadSeqnum(response as object) as integer
|
||||||
|
headers = response.Headers()
|
||||||
|
if IsAssociativeArray(headers) and headers.DoesExist("X-Head-Seqnum")
|
||||||
|
return ValidString(headers["X-Head-Seqnum"]).ToInt()
|
||||||
|
end if
|
||||||
|
return -1
|
||||||
end function
|
end function
|
||||||
|
|
||||||
' Read the leading boxes of a fragment temp file and return moov/moof offsets.
|
' Read the leading boxes of a fragment temp file and return moov/moof offsets.
|
||||||
@@ -584,7 +675,7 @@ namespace Http
|
|||||||
' capture a transient blip and a later persistent failure separately, without
|
' capture a transient blip and a later persistent failure separately, without
|
||||||
' flooding identical failures every few seconds (Sentry quota). Re-armed per
|
' flooding identical failures every few seconds (Sentry quota). Re-armed per
|
||||||
' video in RebuildLiveCache.
|
' video in RebuildLiveCache.
|
||||||
function ReportSegmentFailure(reason as string, info as object) as void
|
function ReportSegmentFailure(reason as LiveSegFailure, info as object) as void
|
||||||
statusText = "n/a"
|
statusText = "n/a"
|
||||||
errorMessage = ""
|
errorMessage = ""
|
||||||
response = info.response
|
response = info.response
|
||||||
@@ -599,11 +690,21 @@ namespace Http
|
|||||||
end if
|
end if
|
||||||
m.reportedFailures[dedupeKey] = true
|
m.reportedFailures[dedupeKey] = true
|
||||||
|
|
||||||
|
' Edge overshoot: how far past the live head (X-Head-Seqnum at the failing fetch, via
|
||||||
|
' info.head) the failed sq was. delta > 0 = a not-yet-produced fragment (the 503 cause).
|
||||||
|
head = ValidInt(info.head)
|
||||||
|
sqNum = ValidInt(info.sq)
|
||||||
|
deltaText = "n/a"
|
||||||
|
if head > 0 and sqNum > 0
|
||||||
|
deltaText = (sqNum - head).ToStr()
|
||||||
|
end if
|
||||||
details = [
|
details = [
|
||||||
"reason: " + reason
|
"reason: " + reason
|
||||||
"videoId: " + ValidString(info.v)
|
"videoId: " + ValidString(info.v)
|
||||||
"itag: " + ValidString(info.itag)
|
"itag: " + ValidString(info.itag)
|
||||||
"sq: " + ToString(info.sq)
|
"sq: " + ToString(info.sq)
|
||||||
|
"head: " + head.ToStr()
|
||||||
|
"delta: " + deltaText
|
||||||
"status: " + statusText
|
"status: " + statusText
|
||||||
"error: " + errorMessage
|
"error: " + errorMessage
|
||||||
"url: " + ValidString(info.segUrl)
|
"url: " + ValidString(info.segUrl)
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import "pkg:/components/Services/Innertube/Constants.bs"
|
import "pkg:/components/Services/Innertube/Constants.bs"
|
||||||
import "pkg:/components/Services/Innertube/SessionData.bs"
|
import "pkg:/components/Services/Innertube/InnertubeService.bs"
|
||||||
|
import "pkg:/components/Services/Innertube/PoTokens.bs"
|
||||||
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
|
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
|
||||||
import "pkg:/source/services/HttpClient.bs"
|
import "pkg:/source/services/HttpClient.bs"
|
||||||
|
import "pkg:/source/utils/Types.bs"
|
||||||
|
|
||||||
namespace Http
|
namespace Http
|
||||||
|
|
||||||
@@ -14,21 +16,37 @@ namespace Http
|
|||||||
m.profilesService = server.sceneNodes.profilesService
|
m.profilesService = server.sceneNodes.profilesService
|
||||||
end function
|
end function
|
||||||
|
|
||||||
@get("/api/innertube/session")
|
@get("/api/innertube/potoken")
|
||||||
function GetSessionData(context as object) as object
|
function GetPoToken(context as object) as object
|
||||||
response = context.response
|
response = context.response
|
||||||
|
|
||||||
sessionData = {
|
identity = ""
|
||||||
"timestamp": m.innertube.timestamp
|
sessionData = m.innertube.sessionData
|
||||||
"visitorData": m.innertube.visitorData
|
if IsAssociativeArray(sessionData)
|
||||||
}
|
identity = ValidString(sessionData.livingRoomPoTokenId)
|
||||||
|
end if
|
||||||
|
|
||||||
response.Json(sessionData)
|
if StringUtils.IsNullOrEmpty(identity)
|
||||||
|
response.Default(503, "No current identity")
|
||||||
|
return true
|
||||||
|
end if
|
||||||
|
|
||||||
|
result = {
|
||||||
|
"identity": identity
|
||||||
|
}
|
||||||
|
entry = Innertube.PoTokens.GetPoTokenEntryForIdentity(identity)
|
||||||
|
if IsAssociativeArray(entry)
|
||||||
|
result["poToken"] = entry.token
|
||||||
|
result["mintedAt"] = entry.mintedAt
|
||||||
|
result["expiresAt"] = entry.expiresAt
|
||||||
|
end if
|
||||||
|
|
||||||
|
response.Json(result)
|
||||||
return true
|
return true
|
||||||
end function
|
end function
|
||||||
|
|
||||||
@post("/api/innertube/session")
|
@post("/api/innertube/potoken")
|
||||||
function SetSessionData(context as object) as object
|
function SetPoToken(context as object) as object
|
||||||
request = context.request
|
request = context.request
|
||||||
response = context.response
|
response = context.response
|
||||||
|
|
||||||
@@ -37,24 +55,49 @@ namespace Http
|
|||||||
response.Default(400, "Invalid payload")
|
response.Default(400, "Invalid payload")
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
|
if StringUtils.IsNullOrEmpty(payload.poToken)
|
||||||
if not IsInt(payload.timestamp)
|
response.Default(400, "Invalid poToken")
|
||||||
response.Default(400, "Invalid timestamp")
|
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
if StringUtils.IsNullOrEmpty(payload.visitorData)
|
if StringUtils.IsNullOrEmpty(payload.identity)
|
||||||
response.Default(400, "Invalid visitorData")
|
response.Default(400, "Invalid identity")
|
||||||
return true
|
return true
|
||||||
end if
|
end if
|
||||||
|
|
||||||
Innertube.SaveSessionDataToRegistry({
|
if not IsInt(payload.mintedAt) or not IsInt(payload.expiresAt)
|
||||||
"timestamp": payload.timestamp
|
response.Default(400, "Invalid mintedAt/expiresAt")
|
||||||
"visitorData": payload.visitorData
|
return true
|
||||||
})
|
end if
|
||||||
|
|
||||||
m.innertube.timestamp = payload.timestamp
|
|
||||||
m.innertube.visitorData = payload.visitorData
|
identity = ""
|
||||||
response.Default(204, "Session data updated successfully")
|
sessionData = m.innertube.sessionData
|
||||||
|
if IsAssociativeArray(sessionData)
|
||||||
|
identity = ValidString(sessionData.livingRoomPoTokenId)
|
||||||
|
end if
|
||||||
|
|
||||||
|
if StringUtils.IsNullOrEmpty(identity)
|
||||||
|
response.Default(503, "No current identity")
|
||||||
|
return true
|
||||||
|
end if
|
||||||
|
|
||||||
|
' Reject identities other than the device's current one (guards the shared registry).
|
||||||
|
if payload.identity <> identity
|
||||||
|
response.Default(409, "identity is not the device's current identity")
|
||||||
|
return true
|
||||||
|
end if
|
||||||
|
|
||||||
|
Innertube.PoTokens.StorePoToken(payload.identity, payload.poToken, payload.expiresAt, payload.mintedAt)
|
||||||
|
response.Default(204, "PoToken updated successfully")
|
||||||
|
return true
|
||||||
|
end function
|
||||||
|
|
||||||
|
@delete("/api/innertube/potoken/all")
|
||||||
|
function ClearPoTokens(context as object) as object
|
||||||
|
response = context.response
|
||||||
|
|
||||||
|
Innertube.PoTokens.ClearAllPoTokens()
|
||||||
|
response.Default(204, "PoTokens cleared")
|
||||||
return true
|
return true
|
||||||
end function
|
end function
|
||||||
|
|
||||||
@@ -70,8 +113,8 @@ namespace Http
|
|||||||
end if
|
end if
|
||||||
|
|
||||||
requestHeaders = requestArgs.Headers
|
requestHeaders = requestArgs.Headers
|
||||||
' Ytjs can send requests without specifying a User-Agent.
|
' Proxied web-app requests (e.g. BotGuard attestation) may omit a
|
||||||
' In this case, Roku would use its default User-Agent.
|
' User-Agent; fall back to ours instead of Roku's default.
|
||||||
if StringUtils.IsNullOrEmpty(requestHeaders["User-Agent"])
|
if StringUtils.IsNullOrEmpty(requestHeaders["User-Agent"])
|
||||||
requestHeaders["User-Agent"] = VIDEO_PLAYER_USER_AGENT
|
requestHeaders["User-Agent"] = VIDEO_PLAYER_USER_AGENT
|
||||||
end if
|
end if
|
||||||
@@ -120,7 +163,7 @@ namespace Http
|
|||||||
if currentProfile <> invalid and currentProfile.type = "youtube"
|
if currentProfile <> invalid and currentProfile.type = "youtube"
|
||||||
options["accessToken"] = currentProfile.accessToken
|
options["accessToken"] = currentProfile.accessToken
|
||||||
else
|
else
|
||||||
options["visitorData"] = m.innertube.visitorData
|
options["visitorData"] = m.innertube.sessionData.visitorData
|
||||||
end if
|
end if
|
||||||
|
|
||||||
drmResponse = InnertubeService.GetDrmLicense(options)
|
drmResponse = InnertubeService.GetDrmLicense(options)
|
||||||
|
|||||||
+7
-1
@@ -548,9 +548,15 @@ namespace Http
|
|||||||
raw = request.query.raw <> invalid
|
raw = request.query.raw <> invalid
|
||||||
videoInfoBatched = request.query.video_info_batched <> invalid
|
videoInfoBatched = request.query.video_info_batched <> invalid
|
||||||
|
|
||||||
|
visitorData = ""
|
||||||
|
sessionData = m.innertube.sessionData
|
||||||
|
if IsAssociativeArray(sessionData)
|
||||||
|
visitorData = ValidString(sessionData.visitorData)
|
||||||
|
end if
|
||||||
|
|
||||||
options = {
|
options = {
|
||||||
"raw": raw
|
"raw": raw
|
||||||
"visitorData": m.innertube.visitorData
|
"visitorData": visitorData
|
||||||
}
|
}
|
||||||
|
|
||||||
if videoInfoBatched
|
if videoInfoBatched
|
||||||
|
|||||||
@@ -56,10 +56,16 @@ namespace Http
|
|||||||
return true
|
return true
|
||||||
end function
|
end function
|
||||||
|
|
||||||
function Default(errcode as integer, reason as string)
|
function Default(errcode as integer, reason as string) as void
|
||||||
errname = m.server.utils.HttpTitle(errcode)
|
|
||||||
m.http_code = errcode
|
m.http_code = errcode
|
||||||
|
|
||||||
|
if errcode = 204
|
||||||
|
' 204 No Content carries no body.
|
||||||
|
m.SetBodyDataString("")
|
||||||
|
return
|
||||||
|
end if
|
||||||
|
|
||||||
|
errname = m.server.utils.HttpTitle(errcode)
|
||||||
buffer = `<html><head><title>${errcode} ${errname}</title></head><body>
|
buffer = `<html><head><title>${errcode} ${errname}</title></head><body>
|
||||||
<h1>${errname}</h1>
|
<h1>${errname}</h1>
|
||||||
${reason}
|
${reason}
|
||||||
|
|||||||
@@ -311,6 +311,20 @@
|
|||||||
visibility: "tv",
|
visibility: "tv",
|
||||||
rokuComponent: "ClearCacheControl",
|
rokuComponent: "ClearCacheControl",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
displayText: "Mint PoToken",
|
||||||
|
key: "dev.mint_potoken",
|
||||||
|
description: "Mint a PoToken for the current identity.",
|
||||||
|
visibility: "off",
|
||||||
|
svelteComponent: "MintPoTokenControl",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
displayText: "Clear PoTokens",
|
||||||
|
key: "dev.clear_potokens",
|
||||||
|
description: "Clear all stored PoTokens.",
|
||||||
|
visibility: "off",
|
||||||
|
svelteComponent: "ClearPoTokensControl",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
displayText: "Enable Diagnostics",
|
displayText: "Enable Diagnostics",
|
||||||
key: "dev.diagnostics.enabled",
|
key: "dev.diagnostics.enabled",
|
||||||
|
|||||||
@@ -1380,6 +1380,18 @@
|
|||||||
<source>Cache cleared.</source>
|
<source>Cache cleared.</source>
|
||||||
<translation>Cache cleared.</translation>
|
<translation>Cache cleared.</translation>
|
||||||
</message>
|
</message>
|
||||||
|
<message>
|
||||||
|
<source>Clear PoTokens</source>
|
||||||
|
<translation>Clear PoTokens</translation>
|
||||||
|
</message>
|
||||||
|
<message>
|
||||||
|
<source>Clear all stored PoTokens.</source>
|
||||||
|
<translation>Clear all stored PoTokens.</translation>
|
||||||
|
</message>
|
||||||
|
<message>
|
||||||
|
<source>PoTokens cleared.</source>
|
||||||
|
<translation>PoTokens cleared.</translation>
|
||||||
|
</message>
|
||||||
<message>
|
<message>
|
||||||
<source>Enable Diagnostics</source>
|
<source>Enable Diagnostics</source>
|
||||||
<translation>Enable Diagnostics</translation>
|
<translation>Enable Diagnostics</translation>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ title=PlayletLib
|
|||||||
# Do not update version manually, it is auto updated from package.json
|
# Do not update version manually, it is auto updated from package.json
|
||||||
major_version=0
|
major_version=0
|
||||||
minor_version=47
|
minor_version=47
|
||||||
build_version=00001
|
build_version=00005
|
||||||
|
|
||||||
ui_resolutions=hd
|
ui_resolutions=hd
|
||||||
uri_resolution_autosub=$$RES$$,480p,720p,1080p
|
uri_resolution_autosub=$$RES$$,480p,720p,1080p
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import "pkg:/components/Services/Innertube/SessionData.bs"
|
||||||
|
|
||||||
|
namespace Tests
|
||||||
|
|
||||||
|
@suite
|
||||||
|
class InnertubeExtractEscapedJsonStringTests extends Rooibos.BaseTestSuite
|
||||||
|
|
||||||
|
@describe("Innertube.ExtractEscapedJsonString")
|
||||||
|
|
||||||
|
@it("extracts a plain value")
|
||||||
|
function plain()
|
||||||
|
text = `noise "visitorData":"AbCd123" noise`
|
||||||
|
m.assertEqual(Innertube.ExtractEscapedJsonString(text, "visitorData"), "AbCd123")
|
||||||
|
end function
|
||||||
|
|
||||||
|
@it("decodes the escaped = padding")
|
||||||
|
function decodesPadding()
|
||||||
|
bs = Chr(92)
|
||||||
|
text = `"LIVING_ROOM_PO_TOKEN_ID":"THWY0ox3FA4${bs}u003d"`
|
||||||
|
m.assertEqual(Innertube.ExtractEscapedJsonString(text, "LIVING_ROOM_PO_TOKEN_ID"), "THWY0ox3FA4=")
|
||||||
|
end function
|
||||||
|
|
||||||
|
@it("decodes any escape, not just the padding")
|
||||||
|
function decodesAnyEscape()
|
||||||
|
bs = Chr(92)
|
||||||
|
text = `"key":"a${bs}u002fb"`
|
||||||
|
m.assertEqual(Innertube.ExtractEscapedJsonString(text, "key"), "a/b")
|
||||||
|
end function
|
||||||
|
|
||||||
|
@it("returns empty string when the key is absent")
|
||||||
|
function keyAbsent()
|
||||||
|
m.assertEqual(Innertube.ExtractEscapedJsonString(`"other":"x"`, "visitorData"), "")
|
||||||
|
end function
|
||||||
|
|
||||||
|
end class
|
||||||
|
|
||||||
|
end namespace
|
||||||
@@ -310,6 +310,9 @@ namespace Locale
|
|||||||
ClearCache = "Clear cache"
|
ClearCache = "Clear cache"
|
||||||
ClearCacheDescription = "Clear cache from cachefs: and tmp:"
|
ClearCacheDescription = "Clear cache from cachefs: and tmp:"
|
||||||
CacheCleared = "Cache cleared."
|
CacheCleared = "Cache cleared."
|
||||||
|
ClearPoTokens = "Clear PoTokens"
|
||||||
|
ClearPoTokensDescription = "Clear all stored PoTokens."
|
||||||
|
PoTokensCleared = "PoTokens cleared."
|
||||||
EnableDiagnostics = "Enable Diagnostics"
|
EnableDiagnostics = "Enable Diagnostics"
|
||||||
EnableDiagnosticsDescription = "Help improve Playlet by enabling diagnostics. This will send anonymous diagnotics data to the developer."
|
EnableDiagnosticsDescription = "Help improve Playlet by enabling diagnostics. This will send anonymous diagnotics data to the developer."
|
||||||
end enum
|
end enum
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ namespace RegistryUtils
|
|||||||
const MESSAGES = "messages"
|
const MESSAGES = "messages"
|
||||||
|
|
||||||
const INNERTUBE_SESSION_DATA = "innertube_session_data"
|
const INNERTUBE_SESSION_DATA = "innertube_session_data"
|
||||||
|
const INNERTUBE_POTOKENS = "innertube_potokens"
|
||||||
const LAST_LOUNGE_DATA = "last_lounge_data"
|
const LAST_LOUNGE_DATA = "last_lounge_data"
|
||||||
|
|
||||||
' "invidious_instances" is deprecated, but we keep for migration purposes
|
' "invidious_instances" is deprecated, but we keep for migration purposes
|
||||||
|
|||||||
Generated
+69
-35
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "playlet-web",
|
"name": "playlet-web",
|
||||||
"version": "0.47.1",
|
"version": "0.47.5",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "playlet-web",
|
"name": "playlet-web",
|
||||||
"version": "0.47.1",
|
"version": "0.47.5",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@sveltejs/vite-plugin-svelte": "^7.1.2",
|
"@sveltejs/vite-plugin-svelte": "^7.1.2",
|
||||||
"@tailwindcss/postcss": "^4.3.1",
|
"@tailwindcss/postcss": "^4.3.1",
|
||||||
@@ -29,8 +29,7 @@
|
|||||||
"tslib": "^2.8.1",
|
"tslib": "^2.8.1",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
"vite": "^8.0.16",
|
"vite": "^8.0.16",
|
||||||
"vite-plugin-compression": "^0.5.1",
|
"vite-plugin-compression": "^0.5.1"
|
||||||
"youtubei.js": "^17.0.1"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@alloc/quick-lru": {
|
"node_modules/@alloc/quick-lru": {
|
||||||
@@ -1578,13 +1577,6 @@
|
|||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@bufbuild/protobuf": {
|
|
||||||
"version": "2.11.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.11.0.tgz",
|
|
||||||
"integrity": "sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "(Apache-2.0 AND BSD-3-Clause)"
|
|
||||||
},
|
|
||||||
"node_modules/@emnapi/core": {
|
"node_modules/@emnapi/core": {
|
||||||
"version": "1.10.0",
|
"version": "1.10.0",
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
|
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
|
||||||
@@ -2236,6 +2228,72 @@
|
|||||||
"node": ">=14.0.0"
|
"node": ">=14.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
|
||||||
|
"version": "1.10.0",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@emnapi/wasi-threads": "1.2.1",
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
|
||||||
|
"version": "1.10.0",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
|
||||||
|
"version": "1.2.1",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
|
||||||
|
"version": "1.1.4",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@tybys/wasm-util": "^0.10.1"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@emnapi/core": "^1.7.1",
|
||||||
|
"@emnapi/runtime": "^1.7.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
|
||||||
|
"version": "0.10.2",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
|
||||||
|
"version": "2.8.1",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "0BSD",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
|
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
|
||||||
"version": "4.3.1",
|
"version": "4.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.1.tgz",
|
||||||
@@ -3593,16 +3651,6 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/meriyah": {
|
|
||||||
"version": "6.1.4",
|
|
||||||
"resolved": "https://registry.npmjs.org/meriyah/-/meriyah-6.1.4.tgz",
|
|
||||||
"integrity": "sha512-Sz8FzjzI0kN13GK/6MVEsVzMZEPvOhnmmI1lU5+/1cGOiK3QUahntrNNtdVeihrO7t9JpoH75iMNXg6R6uWflQ==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "ISC",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=18.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/mri": {
|
"node_modules/mri": {
|
||||||
"version": "1.2.0",
|
"version": "1.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
|
||||||
@@ -4617,20 +4665,6 @@
|
|||||||
"node": "^20.19.0 || ^22.12.0 || >=23"
|
"node": "^20.19.0 || ^22.12.0 || >=23"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/youtubei.js": {
|
|
||||||
"version": "17.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/youtubei.js/-/youtubei.js-17.0.1.tgz",
|
|
||||||
"integrity": "sha512-1lO4b8UqMDzE0oh2qEGzbBOd4UYRdxn/4PdpRM7BGTHxM6ddsEsKZTu90jp8V9FHVgC2h1UirQyqoqLiKwl+Zg==",
|
|
||||||
"dev": true,
|
|
||||||
"funding": [
|
|
||||||
"https://github.com/sponsors/LuanRT"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@bufbuild/protobuf": "^2.0.0",
|
|
||||||
"meriyah": "^6.1.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/zimmerframe": {
|
"node_modules/zimmerframe": {
|
||||||
"version": "1.1.4",
|
"version": "1.1.4",
|
||||||
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "playlet-web",
|
"name": "playlet-web",
|
||||||
"version": "0.47.1",
|
"version": "0.47.5",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
@@ -30,7 +30,6 @@
|
|||||||
"tslib": "^2.8.1",
|
"tslib": "^2.8.1",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
"vite": "^8.0.16",
|
"vite": "^8.0.16",
|
||||||
"vite-plugin-compression": "^0.5.1",
|
"vite-plugin-compression": "^0.5.1"
|
||||||
"youtubei.js": "^17.0.1"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -24,6 +24,7 @@
|
|||||||
import BookmarksScreen from "lib/Screens/BookmarksScreen.svelte";
|
import BookmarksScreen from "lib/Screens/BookmarksScreen.svelte";
|
||||||
import RemoteControlScreen from "lib/Screens/RemoteControlScreen.svelte";
|
import RemoteControlScreen from "lib/Screens/RemoteControlScreen.svelte";
|
||||||
import { fetchLocale } from "lib/Api/Locale";
|
import { fetchLocale } from "lib/Api/Locale";
|
||||||
|
import Toast from "lib/Toast.svelte";
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
PlayletApi.getState().then((value) => {
|
PlayletApi.getState().then((value) => {
|
||||||
@@ -93,3 +94,5 @@
|
|||||||
</div>
|
</div>
|
||||||
<BottomNavigation />
|
<BottomNavigation />
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
<Toast />
|
||||||
@@ -164,6 +164,27 @@ export class PlayletApi {
|
|||||||
return await fetch(`${PlayletApi.host()}/api/cache`, { method: "DELETE" });
|
return await fetch(`${PlayletApi.host()}/api/cache`, { method: "DELETE" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static async getDevicePoToken() {
|
||||||
|
const response = await fetch(`${PlayletApi.host()}/api/innertube/potoken`);
|
||||||
|
if (!response.ok) {
|
||||||
|
const body = await response.text().catch(() => "");
|
||||||
|
throw new Error(`Failed to read device poToken (HTTP ${response.status}): ${body}`);
|
||||||
|
}
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
static async sendPoToken(identity: string, poToken: string, mintedAt: number, expiresAt: number) {
|
||||||
|
const response = await PlayletApi.postJson(`${PlayletApi.host()}/api/innertube/potoken`, { identity, poToken, mintedAt, expiresAt });
|
||||||
|
if (!response.ok) {
|
||||||
|
const body = await response.text().catch(() => "");
|
||||||
|
throw new Error(`Device rejected poToken (HTTP ${response.status}): ${body}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async clearPoTokens() {
|
||||||
|
return await fetch(`${PlayletApi.host()}/api/innertube/potoken/all`, { method: "DELETE" });
|
||||||
|
}
|
||||||
|
|
||||||
static async getBookmarkFeeds() {
|
static async getBookmarkFeeds() {
|
||||||
const response = await fetch(`${PlayletApi.host()}/api/bookmarks/feeds`);
|
const response = await fetch(`${PlayletApi.host()}/api/bookmarks/feeds`);
|
||||||
return await response.json();
|
return await response.json();
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
import { getHost } from "lib/Api/Host";
|
||||||
|
import { PlayletApi } from "lib/Api/PlayletApi";
|
||||||
|
import { BG, buildURL, GOOG_API_KEY, type WebPoSignalOutput, type BgConfig } from "bgutils-js";
|
||||||
|
|
||||||
|
// Fallback lifetime when GenerateIT reports no TTL.
|
||||||
|
const DEFAULT_POTOKEN_TTL_SECONDS = 60 * 60 * 6;
|
||||||
|
|
||||||
|
// Re-mint when the device's token is older than this; the web app owns the refresh cadence.
|
||||||
|
const REFRESH_AGE_SECONDS = 60 * 60;
|
||||||
|
|
||||||
|
export type EnsurePoTokenResult =
|
||||||
|
| { status: "minted" }
|
||||||
|
| { status: "current" }
|
||||||
|
| { status: "no-session" }
|
||||||
|
| { status: "failed"; error: string };
|
||||||
|
|
||||||
|
interface DevicePoToken {
|
||||||
|
identity?: string;
|
||||||
|
poToken?: string;
|
||||||
|
mintedAt?: number;
|
||||||
|
expiresAt?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mints a GVS poToken in the browser (BotGuard) and hands it to the Roku.
|
||||||
|
export class PoTokenMinter {
|
||||||
|
static webPoMinter: BG.WebPoMinter;
|
||||||
|
static webPoMinterPromise: Promise<void>;
|
||||||
|
static integrityTokenExpiresAtMs = 0;
|
||||||
|
|
||||||
|
// Proxied through the Roku to dodge browser CORS.
|
||||||
|
static async fetch(input: RequestInfo | URL, init?: RequestInit) {
|
||||||
|
const method = init?.method
|
||||||
|
? init.method
|
||||||
|
: input instanceof Request
|
||||||
|
? input.method
|
||||||
|
: 'GET';
|
||||||
|
|
||||||
|
const url = typeof input === 'string'
|
||||||
|
? new URL(input)
|
||||||
|
: input instanceof URL
|
||||||
|
? input
|
||||||
|
: new URL(input.url);
|
||||||
|
|
||||||
|
const headers = init?.headers
|
||||||
|
? new Headers(init.headers)
|
||||||
|
: input instanceof Request
|
||||||
|
? input.headers
|
||||||
|
: new Headers();
|
||||||
|
|
||||||
|
const headersObject = {};
|
||||||
|
headers.forEach((value, key) => {
|
||||||
|
headersObject[key] = value;
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = init?.body;
|
||||||
|
|
||||||
|
const args = {
|
||||||
|
Method: method,
|
||||||
|
Url: url,
|
||||||
|
Headers: headersObject,
|
||||||
|
Body: body,
|
||||||
|
CacheSeconds: -1,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch(`http://${getHost()}/api/innertube/proxy`, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(args)
|
||||||
|
});
|
||||||
|
|
||||||
|
const responseData = await response.json();
|
||||||
|
|
||||||
|
return new Response(responseData.body, {
|
||||||
|
status: responseData.status,
|
||||||
|
statusText: `${responseData.status}`,
|
||||||
|
headers: responseData.headers,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static async initWebPoMinter() {
|
||||||
|
// Re-attest once the integrity token nears expiry.
|
||||||
|
if (PoTokenMinter.webPoMinter && Date.now() < PoTokenMinter.integrityTokenExpiresAtMs - 60_000) {
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (PoTokenMinter.webPoMinterPromise) {
|
||||||
|
return PoTokenMinter.webPoMinterPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
PoTokenMinter.webPoMinterPromise = new Promise(async (resolve, reject) => {
|
||||||
|
try {
|
||||||
|
const requestKey = 'O43z0dpjhgX20SCx4KAo';
|
||||||
|
|
||||||
|
const bgConfig: BgConfig = {
|
||||||
|
fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => PoTokenMinter.fetch(input, init),
|
||||||
|
globalObj: globalThis,
|
||||||
|
requestKey,
|
||||||
|
identifier: ''
|
||||||
|
};
|
||||||
|
|
||||||
|
const bgChallenge = await BG.Challenge.create(bgConfig);
|
||||||
|
if (!bgChallenge) {
|
||||||
|
throw new Error('Could not get challenge');
|
||||||
|
}
|
||||||
|
|
||||||
|
const interpreterJavascript = bgChallenge.interpreterJavascript.privateDoNotAccessOrElseSafeScriptWrappedValue;
|
||||||
|
if (interpreterJavascript) {
|
||||||
|
new Function(interpreterJavascript)();
|
||||||
|
} else {
|
||||||
|
throw new Error('Could not load VM');
|
||||||
|
}
|
||||||
|
|
||||||
|
const botguard = await BG.BotGuardClient.create({
|
||||||
|
globalName: bgChallenge.globalName,
|
||||||
|
globalObj: globalThis,
|
||||||
|
program: bgChallenge.program
|
||||||
|
});
|
||||||
|
|
||||||
|
const webPoSignalOutput: WebPoSignalOutput = [];
|
||||||
|
const botguardResponse = await botguard.snapshot({ webPoSignalOutput });
|
||||||
|
|
||||||
|
const integrityTokenResponse = await bgConfig.fetch(buildURL('GenerateIT', true), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'content-type': 'application/json+protobuf',
|
||||||
|
'x-goog-api-key': GOOG_API_KEY,
|
||||||
|
'x-user-agent': 'grpc-web-javascript/0.1'
|
||||||
|
},
|
||||||
|
body: JSON.stringify([requestKey, botguardResponse])
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await integrityTokenResponse.json() as unknown[];
|
||||||
|
|
||||||
|
if (typeof response[0] !== 'string')
|
||||||
|
throw new Error('Could not get integrity token');
|
||||||
|
|
||||||
|
// GenerateIT returns the integrity token's estimated TTL (seconds) as body[1].
|
||||||
|
const ttlSeconds = typeof response[1] === 'number' && response[1] > 0
|
||||||
|
? Math.floor(response[1])
|
||||||
|
: DEFAULT_POTOKEN_TTL_SECONDS;
|
||||||
|
PoTokenMinter.integrityTokenExpiresAtMs = Date.now() + ttlSeconds * 1000;
|
||||||
|
|
||||||
|
PoTokenMinter.webPoMinter = await BG.WebPoMinter.create({ integrityToken: response[0] }, webPoSignalOutput);
|
||||||
|
PoTokenMinter.webPoMinterPromise = null;
|
||||||
|
resolve();
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
PoTokenMinter.webPoMinter = null;
|
||||||
|
PoTokenMinter.integrityTokenExpiresAtMs = 0;
|
||||||
|
PoTokenMinter.webPoMinterPromise = null;
|
||||||
|
reject(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return PoTokenMinter.webPoMinterPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async mintPoToken(identity: string) {
|
||||||
|
await PoTokenMinter.initWebPoMinter();
|
||||||
|
|
||||||
|
if (!PoTokenMinter.webPoMinter) {
|
||||||
|
throw new Error('WebPoMinter is not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
return await PoTokenMinter.webPoMinter.mintAsWebsafeString(identity);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-mint when the device has no token, it expired, or it is older than the refresh window.
|
||||||
|
static shouldRefresh(device: DevicePoToken): boolean {
|
||||||
|
if (!device.poToken || typeof device.mintedAt !== "number" || typeof device.expiresAt !== "number") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
if (now >= device.expiresAt) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return now - device.mintedAt >= REFRESH_AGE_SECONDS;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mints + uploads a poToken when the device's token needs refreshing.
|
||||||
|
static async ensureDevicePoToken(): Promise<EnsurePoTokenResult> {
|
||||||
|
let device: DevicePoToken;
|
||||||
|
try {
|
||||||
|
device = await PlayletApi.getDevicePoToken();
|
||||||
|
} catch (error) {
|
||||||
|
return { status: "failed", error: String(error) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Identity = what the device sends to the decipher server (empty = nothing to mint for).
|
||||||
|
const identity = device?.identity;
|
||||||
|
if (!identity) {
|
||||||
|
return { status: "no-session" };
|
||||||
|
}
|
||||||
|
if (!PoTokenMinter.shouldRefresh(device)) {
|
||||||
|
return { status: "current" };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const poToken = await PoTokenMinter.mintPoToken(identity);
|
||||||
|
// The token is valid until the integrity token expires; fall back to a default TTL.
|
||||||
|
const mintedAt = Math.floor(Date.now() / 1000);
|
||||||
|
const expiresAt = PoTokenMinter.integrityTokenExpiresAtMs > 0
|
||||||
|
? Math.floor(PoTokenMinter.integrityTokenExpiresAtMs / 1000)
|
||||||
|
: mintedAt + DEFAULT_POTOKEN_TTL_SECONDS;
|
||||||
|
await PlayletApi.sendPoToken(identity, poToken, mintedAt, expiresAt);
|
||||||
|
return { status: "minted" };
|
||||||
|
} catch (error) {
|
||||||
|
return { status: "failed", error: String(error) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,411 +0,0 @@
|
|||||||
import { Innertube, Platform, UniversalCache, type Types } from 'youtubei.js/web';
|
|
||||||
import { getHost } from "lib/Api/Host";
|
|
||||||
import { BG, buildURL, GOOG_API_KEY, type WebPoSignalOutput } from "bgutils-js";
|
|
||||||
import { type BgConfig } from "bgutils-js";
|
|
||||||
import type { VideoInfo } from 'node_modules/youtubei.js/dist/src/parser/youtube';
|
|
||||||
import type { StoryboardData } from 'node_modules/youtubei.js/dist/src/parser/classes/PlayerStoryboardSpec';
|
|
||||||
import type { PlayerLiveStoryboardSpec, PlayerStoryboardSpec } from 'node_modules/youtubei.js/dist/src/parser/nodes';
|
|
||||||
import type { Format } from 'node_modules/youtubei.js/dist/src/parser/misc';
|
|
||||||
|
|
||||||
export class YoutubeJs {
|
|
||||||
static host = () => `http://${getHost()}`
|
|
||||||
|
|
||||||
static innerTube: Innertube;
|
|
||||||
static innerTubePromise: Promise<void>;
|
|
||||||
|
|
||||||
static webPoMinter: BG.WebPoMinter;
|
|
||||||
static webPoMinterPromise: Promise<void>;
|
|
||||||
|
|
||||||
static visitorData?: string = undefined;
|
|
||||||
|
|
||||||
static async fetch(input: RequestInfo | URL, init?: RequestInit) {
|
|
||||||
const method = init?.method
|
|
||||||
? init.method
|
|
||||||
: input instanceof Request
|
|
||||||
? input.method
|
|
||||||
: 'GET';
|
|
||||||
|
|
||||||
const url = typeof input === 'string'
|
|
||||||
? new URL(input)
|
|
||||||
: input instanceof URL
|
|
||||||
? input
|
|
||||||
: new URL(input.url);
|
|
||||||
|
|
||||||
const headers = init?.headers
|
|
||||||
? new Headers(init.headers)
|
|
||||||
: input instanceof Request
|
|
||||||
? input.headers
|
|
||||||
: new Headers();
|
|
||||||
|
|
||||||
const headersObject = {};
|
|
||||||
headers.forEach((value, key) => {
|
|
||||||
headersObject[key] = value;
|
|
||||||
});
|
|
||||||
|
|
||||||
let body = init?.body
|
|
||||||
|
|
||||||
const args = {
|
|
||||||
Method: method,
|
|
||||||
Url: url,
|
|
||||||
Headers: headersObject,
|
|
||||||
Body: body,
|
|
||||||
CacheSeconds: -1,
|
|
||||||
};
|
|
||||||
|
|
||||||
const response = await fetch(`http://${getHost()}/api/innertube/proxy`, {
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify(args)
|
|
||||||
})
|
|
||||||
|
|
||||||
const responseData = await response.json();
|
|
||||||
|
|
||||||
return new Response(responseData.body, {
|
|
||||||
status: responseData.status,
|
|
||||||
statusText: `${responseData.status}`,
|
|
||||||
headers: responseData.headers,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
static async initVisitorData() {
|
|
||||||
if (YoutubeJs.visitorData) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
const sessionData = await YoutubeJs.getSessionData();
|
|
||||||
if (sessionData.visitorData) {
|
|
||||||
YoutubeJs.visitorData = sessionData.visitorData;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
YoutubeJs.visitorData = await YoutubeJs.generateVisitorData();
|
|
||||||
|
|
||||||
await YoutubeJs.setSessionData({
|
|
||||||
visitorData: YoutubeJs.visitorData,
|
|
||||||
timestamp: Math.floor(Date.now() / 1000)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getSessionData() {
|
|
||||||
const response = await fetch(`http://${getHost()}/api/innertube/session`)
|
|
||||||
return await response.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
static async setSessionData(sessionData: any) {
|
|
||||||
await fetch(`http://${getHost()}/api/innertube/session`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify(sessionData)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getInnertube() {
|
|
||||||
await YoutubeJs.initInnertube();
|
|
||||||
return YoutubeJs.innerTube;
|
|
||||||
}
|
|
||||||
|
|
||||||
static async initInnertube() {
|
|
||||||
if (YoutubeJs.innerTube) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (YoutubeJs.innerTubePromise) {
|
|
||||||
return YoutubeJs.innerTubePromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
YoutubeJs.innerTubePromise = new Promise(async (resolve, reject) => {
|
|
||||||
try {
|
|
||||||
this.initJsEvaluator();
|
|
||||||
await YoutubeJs.initVisitorData()
|
|
||||||
YoutubeJs.innerTube = await Innertube.create({
|
|
||||||
fetch: YoutubeJs.fetch,
|
|
||||||
cache: new UniversalCache(true),
|
|
||||||
visitor_data: YoutubeJs.visitorData,
|
|
||||||
});
|
|
||||||
YoutubeJs.innerTubePromise = null;
|
|
||||||
resolve();
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
YoutubeJs.innerTube = null;
|
|
||||||
YoutubeJs.innerTubePromise = null;
|
|
||||||
reject(error);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return YoutubeJs.innerTubePromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
static initJsEvaluator() {
|
|
||||||
Platform.shim.eval = async (data: Types.BuildScriptResult, env: Record<string, Types.VMPrimative>) => {
|
|
||||||
return new Function(data.output)();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
static async generateVisitorData() {
|
|
||||||
const innertube = await Innertube.create({ retrieve_player: false });
|
|
||||||
const visitorData = innertube.session.context.client.visitorData;
|
|
||||||
if (!visitorData) {
|
|
||||||
throw new Error('Could not get visitor data');
|
|
||||||
}
|
|
||||||
return visitorData;
|
|
||||||
}
|
|
||||||
|
|
||||||
static async initWebPoMinter() {
|
|
||||||
if (YoutubeJs.webPoMinter) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (YoutubeJs.webPoMinterPromise) {
|
|
||||||
return YoutubeJs.webPoMinterPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
YoutubeJs.webPoMinterPromise = new Promise(async (resolve, reject) => {
|
|
||||||
try {
|
|
||||||
const requestKey = 'O43z0dpjhgX20SCx4KAo';
|
|
||||||
|
|
||||||
const bgConfig: BgConfig = {
|
|
||||||
fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => YoutubeJs.fetch(input, init),
|
|
||||||
globalObj: globalThis,
|
|
||||||
requestKey,
|
|
||||||
identifier: ''
|
|
||||||
};
|
|
||||||
|
|
||||||
const bgChallenge = await BG.Challenge.create(bgConfig);
|
|
||||||
if (!bgChallenge) {
|
|
||||||
throw new Error('Could not get challenge');
|
|
||||||
}
|
|
||||||
|
|
||||||
const interpreterJavascript = bgChallenge.interpreterJavascript.privateDoNotAccessOrElseSafeScriptWrappedValue;
|
|
||||||
if (interpreterJavascript) {
|
|
||||||
new Function(interpreterJavascript)();
|
|
||||||
} else {
|
|
||||||
throw new Error('Could not load VM');
|
|
||||||
}
|
|
||||||
|
|
||||||
const botguard = await BG.BotGuardClient.create({
|
|
||||||
globalName: bgChallenge.globalName,
|
|
||||||
globalObj: globalThis,
|
|
||||||
program: bgChallenge.program
|
|
||||||
});
|
|
||||||
|
|
||||||
const webPoSignalOutput: WebPoSignalOutput = [];
|
|
||||||
const botguardResponse = await botguard.snapshot({ webPoSignalOutput });
|
|
||||||
|
|
||||||
const integrityTokenResponse = await bgConfig.fetch(buildURL('GenerateIT', true), {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'content-type': 'application/json+protobuf',
|
|
||||||
'x-goog-api-key': GOOG_API_KEY,
|
|
||||||
'x-user-agent': 'grpc-web-javascript/0.1'
|
|
||||||
},
|
|
||||||
body: JSON.stringify([requestKey, botguardResponse])
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await integrityTokenResponse.json() as unknown[];
|
|
||||||
|
|
||||||
if (typeof response[0] !== 'string')
|
|
||||||
throw new Error('Could not get integrity token');
|
|
||||||
|
|
||||||
YoutubeJs.webPoMinter = await BG.WebPoMinter.create({ integrityToken: response[0] }, webPoSignalOutput);
|
|
||||||
YoutubeJs.webPoMinterPromise = null;
|
|
||||||
resolve();
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
YoutubeJs.webPoMinter = null;
|
|
||||||
YoutubeJs.webPoMinterPromise = null;
|
|
||||||
reject(error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return YoutubeJs.webPoMinterPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
static async generatePoToken(videoId: string) {
|
|
||||||
await YoutubeJs.initWebPoMinter();
|
|
||||||
|
|
||||||
if (!YoutubeJs.webPoMinter) {
|
|
||||||
throw new Error('WebPoMinter is not initialized');
|
|
||||||
}
|
|
||||||
|
|
||||||
return await YoutubeJs.webPoMinter.mintAsWebsafeString(videoId);
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getVideoInfo(videoId: string) {
|
|
||||||
await YoutubeJs.initInnertube();
|
|
||||||
|
|
||||||
const info = await YoutubeJs.innerTube.getBasicInfo(videoId, {
|
|
||||||
client: 'TV',
|
|
||||||
po_token: await YoutubeJs.generatePoToken(videoId),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (info.playability_status.status !== 'OK') {
|
|
||||||
throw new Error(`Video is not playable: ${info.playability_status.status}\nReason: ${info.playability_status.reason}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// We can't generate a proper dash from live videos.
|
|
||||||
// By returning null, we're telling Playlet to fetch video info itself.
|
|
||||||
if (info.basic_info.is_live) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
YoutubeJs.innerTube.session.player.po_token = YoutubeJs.innerTube.session.po_token;
|
|
||||||
|
|
||||||
// Populate a video object that is similar to Invidious format.
|
|
||||||
// Mostly populate only fields we care about, enough to make it work.
|
|
||||||
return {
|
|
||||||
type: "video",
|
|
||||||
title: info.basic_info.title,
|
|
||||||
videoId: info.basic_info.id,
|
|
||||||
videoThumbnails: [],
|
|
||||||
storyboards: YoutubeJs.getStoryboards(info),
|
|
||||||
description: "",
|
|
||||||
published: 0,
|
|
||||||
publishedText: "",
|
|
||||||
keywords: [],
|
|
||||||
viewCount: 0,
|
|
||||||
likeCount: 0,
|
|
||||||
dislikeCount: 0,
|
|
||||||
paid: false,
|
|
||||||
premium: false,
|
|
||||||
isFamilyFriendly: true,
|
|
||||||
allowedRegions: [],
|
|
||||||
genre: "",
|
|
||||||
genreUrl: null,
|
|
||||||
author: info.basic_info.author,
|
|
||||||
authorId: info.basic_info.channel_id,
|
|
||||||
authorUrl: "",
|
|
||||||
authorVerified: false,
|
|
||||||
authorThumbnails: [],
|
|
||||||
subCountText: "",
|
|
||||||
lengthSeconds: info.basic_info.duration,
|
|
||||||
allowRatings: true,
|
|
||||||
rating: 0,
|
|
||||||
isListed: true,
|
|
||||||
liveNow: info.basic_info.is_live,
|
|
||||||
isPostLiveDvr: info.basic_info.is_post_live_dvr,
|
|
||||||
isUpcoming: info.basic_info.is_upcoming,
|
|
||||||
dashUrl: info.streaming_data.dash_manifest_url || "",
|
|
||||||
hlsUrl: info.streaming_data.hls_manifest_url,
|
|
||||||
adaptiveFormats: await YoutubeJs.transformFormats(info.streaming_data?.adaptive_formats),
|
|
||||||
formatStreams: await YoutubeJs.transformFormats(info.streaming_data?.formats),
|
|
||||||
captions: YoutubeJs.getCaptions(info),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static async transformFormats(formats: Format[]) {
|
|
||||||
if (!formats) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.all(formats.map(format =>
|
|
||||||
YoutubeJs.transformStreamFormat(format)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
static async transformStreamFormat(format: Format): Promise<any> {
|
|
||||||
const result: any = {
|
|
||||||
init: format.init_range ? `${format.init_range.start}-${format.init_range.end}` : "",
|
|
||||||
index: format.index_range ? `${format.index_range.start}-${format.index_range.end}` : "",
|
|
||||||
bitrate: `${format.bitrate}`,
|
|
||||||
itag: `${format.itag}`,
|
|
||||||
type: format.mime_type,
|
|
||||||
clen: `${format.approx_duration_ms}`,
|
|
||||||
lmt: `${format.last_modified}`,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (format.url || format.signature_cipher || format.cipher) {
|
|
||||||
result.url = await format.decipher(YoutubeJs.innerTube.session.player);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (format.audio_quality) {
|
|
||||||
result.audioQuality = format.audio_quality;
|
|
||||||
}
|
|
||||||
if (format.audio_sample_rate) {
|
|
||||||
result.audioSampleRate = format.audio_sample_rate;
|
|
||||||
}
|
|
||||||
if (format.audio_channels) {
|
|
||||||
result.audioChannels = format.audio_channels;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (format.quality_label) {
|
|
||||||
result.qualityLabel = format.quality_label;
|
|
||||||
}
|
|
||||||
if (format.fps) {
|
|
||||||
result.fps = format.fps;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (format.width) {
|
|
||||||
result.width = format.width;
|
|
||||||
}
|
|
||||||
if (format.height) {
|
|
||||||
result.height = format.height;
|
|
||||||
}
|
|
||||||
if (format.height && format.width) {
|
|
||||||
result.size = `${format.width}x${format.height}`;
|
|
||||||
result.resolution = `${format.height}p`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
static getStoryboards(videoInfo: VideoInfo) {
|
|
||||||
if (!videoInfo.storyboards) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (videoInfo.storyboards.type === 'PlayerLiveStoryboardSpec') {
|
|
||||||
const board = (videoInfo.storyboards as PlayerLiveStoryboardSpec).board
|
|
||||||
return [{
|
|
||||||
templateUrl: board.template_url,
|
|
||||||
width: board.thumbnail_width,
|
|
||||||
height: board.thumbnail_height,
|
|
||||||
count: -1,
|
|
||||||
interval: 5000,
|
|
||||||
storyboardWidth: board.columns,
|
|
||||||
storyboardHeight: board.rows,
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
|
|
||||||
const storyboards = (videoInfo.storyboards as PlayerStoryboardSpec).boards;
|
|
||||||
return storyboards.map((board: StoryboardData) => {
|
|
||||||
return {
|
|
||||||
templateUrl: board.template_url,
|
|
||||||
width: board.thumbnail_width,
|
|
||||||
height: board.thumbnail_height,
|
|
||||||
count: board.thumbnail_count,
|
|
||||||
interval: board.interval,
|
|
||||||
storyboardWidth: board.columns,
|
|
||||||
storyboardHeight: board.rows,
|
|
||||||
storyboardCount: board.storyboard_count
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
static getCaptions(videoInfo: VideoInfo) {
|
|
||||||
if (!videoInfo.captions?.caption_tracks) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return videoInfo.captions.caption_tracks.map(track => {
|
|
||||||
const baseUrl = track.base_url;
|
|
||||||
if (!baseUrl) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryComponents = new URLSearchParams(baseUrl.split('?')[1]);
|
|
||||||
queryComponents.set('fmt', 'vtt');
|
|
||||||
const modifiedBaseUrl = `${baseUrl.split('?')[0]}?${queryComponents.toString()}`;
|
|
||||||
|
|
||||||
return {
|
|
||||||
label: track.name.toString(),
|
|
||||||
language_code: track.language_code || '',
|
|
||||||
url: modifiedBaseUrl
|
|
||||||
};
|
|
||||||
}).filter(caption => !!caption);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { PlayletApi } from "lib/Api/PlayletApi";
|
||||||
|
import { translate } from "lib/Stores";
|
||||||
|
import { get } from "svelte/store";
|
||||||
|
|
||||||
|
const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"];
|
||||||
|
|
||||||
|
export let displayText: string = "";
|
||||||
|
// svelte-ignore unused-export-let
|
||||||
|
export let key: string = "";
|
||||||
|
export let description: string = "";
|
||||||
|
export let level: number = 0;
|
||||||
|
|
||||||
|
async function clearPoTokens() {
|
||||||
|
await PlayletApi.clearPoTokens();
|
||||||
|
alert(get(translate)("PoTokens cleared."));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="m-5">
|
||||||
|
<div class={textSizes[level]}>{$translate(displayText)}</div>
|
||||||
|
<div class="text-xs text-gray-500">{@html $translate(description)}</div>
|
||||||
|
<button class="btn m-1" on:click={clearPoTokens}
|
||||||
|
>{$translate("Clear PoTokens")}</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { translate } from "lib/Stores";
|
||||||
|
import { ensureDevicePoTokenWithToast } from "lib/ensureDevicePoToken";
|
||||||
|
|
||||||
|
const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"];
|
||||||
|
|
||||||
|
export let displayText: string = "";
|
||||||
|
// svelte-ignore unused-export-let
|
||||||
|
export let key: string = "";
|
||||||
|
export let description: string = "";
|
||||||
|
export let level: number = 0;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="m-5">
|
||||||
|
<div class={textSizes[level]}>{$translate(displayText)}</div>
|
||||||
|
<div class="text-xs text-gray-500">{@html $translate(description)}</div>
|
||||||
|
<button class="btn m-1" on:click={() => ensureDevicePoTokenWithToast()}
|
||||||
|
>{$translate("Mint PoToken")}</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
@@ -7,6 +7,8 @@
|
|||||||
import StringControl from "lib/Screens/Settings/SettingControls/StringControl.svelte";
|
import StringControl from "lib/Screens/Settings/SettingControls/StringControl.svelte";
|
||||||
import NumberControl from "./SettingControls/NumberControl.svelte";
|
import NumberControl from "./SettingControls/NumberControl.svelte";
|
||||||
import ClearCacheControl from "./SettingControls/ClearCacheControl.svelte";
|
import ClearCacheControl from "./SettingControls/ClearCacheControl.svelte";
|
||||||
|
import ClearPoTokensControl from "./SettingControls/ClearPoTokensControl.svelte";
|
||||||
|
import MintPoTokenControl from "./SettingControls/MintPoTokenControl.svelte";
|
||||||
import EditQualityControl from "./SettingControls/EditQualityControl.svelte";
|
import EditQualityControl from "./SettingControls/EditQualityControl.svelte";
|
||||||
import SponsorBlockCategoriesControl from "./SettingControls/SponsorBlockCategoriesControl.svelte";
|
import SponsorBlockCategoriesControl from "./SettingControls/SponsorBlockCategoriesControl.svelte";
|
||||||
import { translate } from "lib/Stores";
|
import { translate } from "lib/Stores";
|
||||||
@@ -34,6 +36,8 @@
|
|||||||
const customComponents = {
|
const customComponents = {
|
||||||
ClearSearchHistoryControl,
|
ClearSearchHistoryControl,
|
||||||
ClearCacheControl,
|
ClearCacheControl,
|
||||||
|
ClearPoTokensControl,
|
||||||
|
MintPoTokenControl,
|
||||||
EditHomeScreenControl,
|
EditHomeScreenControl,
|
||||||
PlayletLibVersionControl,
|
PlayletLibVersionControl,
|
||||||
EditQualityControl,
|
EditQualityControl,
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { toastStore, removeToast } from "lib/Toast";
|
||||||
|
|
||||||
|
const alertClass: Record<string, string> = {
|
||||||
|
success: "alert-success",
|
||||||
|
error: "alert-error",
|
||||||
|
info: "alert-info",
|
||||||
|
warning: "alert-warning",
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="toast toast-end toast-bottom z-50">
|
||||||
|
{#each $toastStore as toast (toast.id)}
|
||||||
|
<div class="alert {alertClass[toast.type] ?? 'alert-info'}">
|
||||||
|
<span>{toast.message}</span>
|
||||||
|
<button
|
||||||
|
class="btn btn-ghost btn-xs"
|
||||||
|
on:click={() => removeToast(toast.id)}>✕</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { writable } from "svelte/store";
|
||||||
|
|
||||||
|
export type ToastType = "success" | "error" | "info" | "warning";
|
||||||
|
|
||||||
|
export interface Toast {
|
||||||
|
id: number;
|
||||||
|
type: ToastType;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const toastStore = writable<Toast[]>([]);
|
||||||
|
|
||||||
|
let nextId = 0;
|
||||||
|
|
||||||
|
export function addToast(message: string, type: ToastType = "info", durationMs = 5000) {
|
||||||
|
const id = nextId++;
|
||||||
|
toastStore.update((toasts) => [...toasts, { id, type, message }]);
|
||||||
|
if (durationMs > 0) {
|
||||||
|
setTimeout(() => removeToast(id), durationMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeToast(id: number) {
|
||||||
|
toastStore.update((toasts) => toasts.filter((toast) => toast.id !== id));
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@
|
|||||||
import { playletStateStore, translate } from "lib/Stores";
|
import { playletStateStore, translate } from "lib/Stores";
|
||||||
import VideoStartAt from "./VideoStartAt.svelte";
|
import VideoStartAt from "./VideoStartAt.svelte";
|
||||||
import VideoThumbnail from "./VideoThumbnail.svelte";
|
import VideoThumbnail from "./VideoThumbnail.svelte";
|
||||||
import { YoutubeJs } from "lib/Api/YoutubeJs";
|
|
||||||
|
|
||||||
export let videoId: string | undefined = undefined;
|
export let videoId: string | undefined = undefined;
|
||||||
export let title: string | undefined = undefined;
|
export let title: string | undefined = undefined;
|
||||||
@@ -58,26 +57,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function playOnTvYtjs() {
|
|
||||||
try {
|
|
||||||
const videoInfo = getVideoInfo() as any;
|
|
||||||
|
|
||||||
// measure length of time it takes to get video info
|
|
||||||
const start = performance.now();
|
|
||||||
const metadata = await YoutubeJs.getVideoInfo(videoId);
|
|
||||||
const end = performance.now();
|
|
||||||
console.log(`Time to get video info: ${end - start}ms`);
|
|
||||||
|
|
||||||
if (metadata) {
|
|
||||||
videoInfo.metadata = metadata;
|
|
||||||
}
|
|
||||||
await PlayletApi.playVideo(videoInfo);
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
alert(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function queueOnTv() {
|
async function queueOnTv() {
|
||||||
try {
|
try {
|
||||||
const videoInfo = getVideoInfo();
|
const videoInfo = getVideoInfo();
|
||||||
@@ -168,9 +147,6 @@
|
|||||||
<button class="btn join-item hover:btn-accent" on:click={playOnTv}>
|
<button class="btn join-item hover:btn-accent" on:click={playOnTv}>
|
||||||
{$translate("Play on %1").replace("%1", tvName)}
|
{$translate("Play on %1").replace("%1", tvName)}
|
||||||
</button>
|
</button>
|
||||||
<button class="btn join-item hover:btn-accent" on:click={playOnTvYtjs}>
|
|
||||||
{$translate("Play on %1").replace("%1", tvName)} (ytjs)
|
|
||||||
</button>
|
|
||||||
<button class="btn join-item hover:btn-accent" on:click={queueOnTv}>
|
<button class="btn join-item hover:btn-accent" on:click={queueOnTv}>
|
||||||
{$translate("Queue on %1").replace("%1", tvName)}
|
{$translate("Queue on %1").replace("%1", tvName)}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { PoTokenMinter } from "lib/Api/PoTokenMinter";
|
||||||
|
import { addToast } from "lib/Toast";
|
||||||
|
|
||||||
|
// Mints for the current identity if needed, surfacing the outcome as a toast.
|
||||||
|
export async function ensureDevicePoTokenWithToast() {
|
||||||
|
const result = await PoTokenMinter.ensureDevicePoToken();
|
||||||
|
switch (result.status) {
|
||||||
|
case "minted":
|
||||||
|
addToast("PoToken minted on device", "success");
|
||||||
|
break;
|
||||||
|
case "current":
|
||||||
|
addToast("PoToken already up to date on device", "info");
|
||||||
|
break;
|
||||||
|
case "no-session":
|
||||||
|
addToast("No identity available to mint a PoToken yet", "warning");
|
||||||
|
break;
|
||||||
|
case "failed":
|
||||||
|
addToast(`PoToken minting failed: ${result.error}`, "error");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user