Compare commits

..
57 Commits
Author SHA1 Message Date
Brahim Hadriche e8624cdb1f Release v0.44.8 (#847) 2026-04-24 11:01:28 -04:00
Brahim Hadriche d427989576 Watch history fix 2026-04-23 15:08:25 -04:00
Brahim Hadriche 4706d71639 Fix warning 2026-04-23 14:31:38 -04:00
Brahim Hadriche 16df893c2c Release v0.44.7 (#845) 2026-04-23 08:52:58 -04:00
Brahim Hadriche 6129afd695 [chore] update dependencies (#835)
* update dependencies

* Disable memory related telemetry warnings
2026-04-23 08:45:41 -04:00
Brahim Hadriche 84504a5931 fix channel sort 2026-04-08 19:33:27 -04:00
Brahim Hadriche 0123f9fa8e [chore] update dependencies (#832)
* update dependencies

* Update deps and fix
2026-03-18 09:15:04 -04:00
Brahim Hadriche 7227d4e26b Fix for watch progress 2026-03-10 21:07:36 -04:00
Brahim Hadriche 58fe601b25 Release v0.44.6 (#828) 2026-02-08 12:55:16 -05:00
Brahim Hadriche a61d132b57 update dependencies (#825) 2026-02-08 12:55:06 -05:00
Brahim Hadriche ee4acfc8e7 [skip ci] Add February 2026 update link to README 2026-02-08 11:39:20 -05:00
Brahim Hadriche fcd798a2fa update dependencies (#817) 2026-01-31 17:58:42 -05:00
Brahim Hadriche f5be0e5842 Close dialog on play state success (#821) 2026-01-31 17:57:46 -05:00
Brahim Hadriche 2d9f3abe5d Fix audio track display names (#820) 2026-01-31 17:56:51 -05:00
Brahim Hadriche 69fe737006 Release v0.44.5 (#814) 2026-01-17 14:04:46 -05:00
Brahim Hadriche ac6c9122c2 update dependencies (#800) 2026-01-17 13:56:27 -05:00
Brahim Hadriche d3e0883332 Fix/ytjs missing urls (#811)
* ytjs fix

* ignore shoppingTimelyShelfViewModel
2026-01-08 19:30:47 -05:00
Brahim Hadriche 5c39405255 [chore] update dependencies (#799)
* update dependencies

* Update CHANGELOG.md
2025-11-30 20:33:18 -05:00
Brahim Hadriche 6535006d66 Release v0.44.4 (#798) 2025-11-23 14:07:41 -05:00
Brahim Hadriche a43cb91e1e update dependencies (#796) 2025-11-23 13:21:11 -05:00
Brahim Hadriche 58ce807e42 Fix subscriptions looping instead of loading older videos (#797) 2025-11-23 13:20:49 -05:00
Brahim Hadriche 2319ae7025 [skip ci] update invidious readme 2025-11-16 09:23:27 -05:00
Brahim Hadriche 1f2058abce Remove Trending endpoints from code base 2025-11-16 09:16:03 -05:00
Brahim Hadriche aadbde330d update dependencies (#795) 2025-11-15 16:39:02 -05:00
Brahim Hadriche 60df07c95c [skip ci] missing lock file 2025-11-15 16:38:54 -05:00
Brahim Hadriche 71757bb9d5 [skip ci] add readme 2025-11-15 14:57:07 -05:00
Brahim Hadriche 630176d8aa [skip ci] Add playground 2025-11-15 14:53:09 -05:00
Brahim Hadriche 03c7f9afe6 [skip ci] changelog 2025-11-14 22:22:50 -05:00
Brahim Hadriche 3c58f90cc9 Release v0.44.3 (#794) 2025-11-14 16:06:59 -05:00
Brahim Hadriche b5261d900f Fix json parsing with invalid chars like \u0000 preventing some channels from loading 2025-11-14 15:47:49 -05:00
Brahim Hadriche 9a319eab75 Release v0.44.2 (#792) 2025-11-13 09:07:43 -05:00
Brahim Hadriche aca9cb890d [skip ci] small refactor 2025-11-12 20:55:03 -05:00
Brahim Hadriche c77eb30985 [skip ci] Removed retry on trending feeds 2025-11-12 15:52:49 -05:00
Brahim Hadriche 6fc842ca37 Release v0.44.1 (#791) 2025-11-12 15:02:44 -05:00
Brahim Hadriche a1ce7aa9fc [skip ci] errors related to loading the trending feeds. 2025-11-12 14:56:10 -05:00
Brahim Hadriche 9e3363f22c Fix for recommended feed (UPCOMING) (#790)
* Fix for recommended feed (UPCOMING)

* Rename var

* typo
2025-11-12 09:34:03 -05:00
Brahim Hadriche d42d783738 [skip ci] download error codes 2025-11-11 10:57:07 -05:00
Brahim Hadriche 5f1a4c8eb6 [skip ci] add parser field to metadata 2025-11-11 09:22:29 -05:00
Brahim Hadriche c3494a7f5d [skip ci] better log for http retries 2025-11-10 08:55:01 -05:00
Brahim Hadriche 103b7f2a71 Small change in post-live dvr detection 2025-11-10 08:39:18 -05:00
Brahim Hadriche c7377e0e06 [skip ci] comment 2025-11-10 08:21:48 -05:00
Brahim Hadriche 58f521f923 Release v0.44.0 (#787) 2025-11-08 21:10:21 -05:00
Brahim Hadriche 4293a958d0 [skip ci] Comment for TILE_CONTENT_TYPE_EDU 2025-11-08 20:54:07 -05:00
Brahim Hadriche 4a89fd0aa9 changelog 2025-11-08 14:26:37 -05:00
Dave Wickham f1a3df81b2 Add code to prioritise human-made subtitles (#786) 2025-11-08 14:25:57 -05:00
Brahim Hadriche d876f819fc [skip ci] mark transient playback error as a warning 2025-11-08 14:09:59 -05:00
Brahim Hadriche 757dc6069e [skip ci] OTF small refactor 2025-11-08 14:03:14 -05:00
Brahim Hadriche e7f4b3fee1 [skip ci] adjust telemetry events 2025-11-08 13:52:57 -05:00
Brahim Hadriche 319457bada update dependencies (#785) 2025-11-08 13:37:57 -05:00
Brahim Hadriche c91f5e49c0 [skip ci] Ignore setAutoplayMode 2025-11-08 11:43:07 -05:00
Brahim Hadriche 45e320abe4 [skip ci] remove todo 2025-11-07 17:23:11 -05:00
Brahim Hadriche 4d1673ecfb [skip ci] Implemented compactRadioRenderer node 2025-11-07 17:19:16 -05:00
Brahim Hadriche 3eb3c0854a [skip ci] more error tweaks 2025-11-07 16:31:37 -05:00
Brahim Hadriche 24cf06bf44 [skip ci] adjust player errors 2025-11-07 15:55:24 -05:00
Brahim Hadriche 9318db7762 Release v0.43.9 (#783) 2025-11-07 14:27:26 -05:00
Brahim Hadriche 42ca2d1b30 [skip ci] another otf fix 2025-11-07 14:24:40 -05:00
Brahim Hadriche 446bba67c9 [skip ci] video error capture 2025-11-07 09:09:23 -05:00
84 changed files with 2218 additions and 3356 deletions

No files matched your search

+23
View File
@@ -76,6 +76,29 @@
"args": "--log-level info --project bsconfig.tests.json --create-package --sourceMap=true --debug --test-mode --lintConfig ../config/bslint.jsonc",
"cwd": "${workspaceFolder}/playlet-lib",
"console": "integratedTerminal"
},
{
"name": "Playground",
"type": "brightscript",
"request": "launch",
"envFile": "${workspaceFolder}/.env",
"host": "${env:ROKU_DEV_TARGET}",
"password": "${env:ROKU_DEVPASSWORD}",
"stopOnEntry": false,
"enableDebuggerAutoRecovery": false,
"stopDebuggerOnAppExit": false,
"rootDir": "${workspaceFolder}/build/playground",
"sourceDirs": [
"${workspaceFolder}/playground/src"
],
"files": [
"**"
],
"preLaunchTask": "build-playground",
"injectRdbOnDeviceComponent": true,
"injectRaleTrackerTask": true,
"raleTrackerTaskFileLocation": "${workspaceFolder}/tools/RALE/TrackerTask.xml",
"enableDebugProtocol": true
}
],
"compounds": [
+5
View File
@@ -49,6 +49,11 @@
"label": "build-web",
"script": "build:web",
"type": "npm"
},
{
"label": "build-playground",
"script": "build:playground",
"type": "npm"
}
]
}
+70
View File
@@ -5,6 +5,76 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.44.8] - 2026-04-24
### Fixed
- Always use `signatureTimestamp` in `/player` calls to prevent "reload page" errors. This affects watch history.
- Attempt 2 to fix watch history and watch progress
## [0.44.7] - 2026-04-23
### Fixed
- Attempt to fix watch history and watch progress
- Channel sort
## [0.44.6] - 2026-02-08
### Fixed
- Error dialog doesn't close automatically when playback recovers after an error
- All audio track names are shown as "Other" in multi audio track videos
## [0.44.5] - 2026-01-17
### Fixed
- Error handling when ytjs formats have missing urls
## [0.44.4] - 2025-11-23
### Fixed
- Subscriptions looping instead of loading older videos
### Removed
- Trending endpoints from code base
## [0.44.3] - 2025-11-14
### Fixed
- Json parsing with invalid chars like `\u0000` preventing some channels from loading
## [0.44.2] - 2025-11-13
### Fixed
- Removed retry on trending feeds
## [0.44.1] - 2025-11-12
### Fixed
- Small change in post-live dvr detection
- Issue where recommended videos are all "UPCOMING" paid content
- Errors related to loading the trending feeds. Trending will be removed from Playlet in a future release.
## [0.44.0] - 2025-11-09
### Added
- Implemented compactRadioRenderer node
- Prioritise manually created subtitles over auto-generated ones
## [0.43.9] - 2025-11-07
### Fixed
- Another mistake in OTF streams
## [0.43.8] - 2025-11-07
### Fixed
+3
View File
@@ -27,6 +27,9 @@
Playlet is an unofficial YouTube client for Roku 📺
**[Playlet February 2026 Update](https://github.com/iBicha/playlet/discussions/827)**
## Screenshots
<a href="./docs/screenshots/README.md">
+6
View File
@@ -58,6 +58,12 @@
"regex": "\\bTr\\s*\\(\\s*\"[^\\\"]*\"\\s*\\)",
"regexFlags": "ig",
"message": "Tr(\"String\") is not allowed. Use Tr(Locale.Key) instead."
},
{
"code": "NO_PARSE_JSON",
"regex": "\\s*ParseJson\\(",
"regexFlags": "ig",
"message": "ParseJson is not allowed. Use StringUtils.ParseJsonSafe() instead."
}
],
"files": [
+181 -1214
View File
File diff suppressed because it is too large. Load diff
+16 -15
View File
@@ -1,38 +1,38 @@
{
"name": "playlet",
"version": "0.43.8",
"version": "0.44.8",
"description": "Unofficial YouTube client for Roku",
"devDependencies": {
"@rokucommunity/bslint": "^0.8.38",
"@rokucommunity/bslint": "^0.8.39",
"@types/crypto-js": "^4.2.2",
"@types/fs-extra": "^11.0.4",
"@types/node": "^24.9.2",
"@types/node": "^25.5.0",
"@types/xml2js": "^0.4.14",
"argparse": "^2.0.1",
"brighterscript": "0.70.3",
"brighterscript-formatter": "^1.7.19",
"brighterscript-formatter": "^1.7.21",
"convert-svg-to-png": "^0.7.1",
"crypto-js": "^4.2.0",
"dotenv": "^17.2.3",
"fs-extra": "^11.3.2",
"glob": "^11.0.3",
"dotenv": "^17.3.1",
"fs-extra": "^11.3.4",
"glob": "^13.0.6",
"imap": "^0.8.19",
"ip": "^2.0.1",
"json5": "^2.2.3",
"mailparser": "^3.7.5",
"mailparser": "^3.9.4",
"protocol-buffers-schema": "^3.6.0",
"puppeteer": "^24.27.0",
"roku-deploy": "^3.14.4",
"puppeteer": "^24.40.0",
"roku-deploy": "^3.16.2",
"roku-test-automation": "^2.2.1",
"rooibos-roku": "5.15.5",
"rounded-rect-9patch": "^1.1.2",
"semver": "^7.7.3",
"semver": "^7.7.4",
"shelljs": "^0.10.0",
"ts-node": "^10.9.2",
"typescript": "5.9.3",
"telnet-client": "^2.2.6",
"telnet-client": "^2.2.11",
"xml2js": "^0.6.2",
"yaml": "^2.8.1"
"yaml": "^2.8.2"
},
"engines": {
"node": "22"
@@ -48,6 +48,7 @@
"build:lib:dev": "cd playlet-lib && npm run build:dev",
"build:lib:prod": "cd playlet-lib && npm run build:prod",
"build:web": "cd playlet-web && npm run build",
"build:playground": "cd playground && npm run build",
"lint": "cd playlet-lib && npm run lint && cd ../playlet-app && npm run lint && cd ../playlet-web && npm run lint",
"lint:fix": "cd playlet-lib && npm run lint:fix && cd ../playlet-app && npm run lint:fix && cd ../playlet-web && npm run lint",
"format": "cd playlet-lib && npm run format && cd ../playlet-app && npm run format",
@@ -65,7 +66,7 @@
"screenshot": "node tools/screenshot.js",
"convert-images": "node tools/convert-images.js",
"update-rale-component": "cd tools/RALE && rm TrackerTask.xml && curl -o TrackerTask.zip https://devtools.web.roku.com/roku-advanced-layout-editor/app/TrackerTask.zip && unzip TrackerTask.zip && rm TrackerTask.zip",
"postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playlet-web && npm install",
"postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playground && npm install && cd ../playlet-web && npm install",
"update-deps": "npx npm-check-updates --deep --upgrade --install always --reject rooibos-roku",
"registry:write": "node tools/registry.js --input registry.json",
"registry:read": "node tools/registry.js --output registry.json",
@@ -75,6 +76,6 @@
"shutdown": "node tools/shutdown.js"
},
"optionalDependencies": {
"@rollup/rollup-linux-x64-gnu": "^4.52.5"
"@rollup/rollup-linux-x64-gnu": "^4.59.0"
}
}
+7
View File
@@ -0,0 +1,7 @@
# Playground
Playground is a test project to try things out or iterate on a concept.
Playlet app relies on playlet lib, and playlet lib relies on web app, so sometimes iteration speed can be slower when building everything everytime.
Just like Playlet, Playground can be launched from the VSCode "Run and debug" menu.
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../config/bsconfig.base.jsonc",
"rootDir": "src/",
"stagingDir": "../build/playground",
"outFile": "../dist/playground.zip"
}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "bsconfig.json",
"createPackage": false,
"deploy": false,
"retainStagingDir": false,
"sourceMap": false
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../config/bsconfig.tests.base.jsonc",
"rootDir": "src/",
"stagingDir": "../build/playground-tests",
"outFile": "../build/playground-tests.zip"
}
+12
View File
@@ -0,0 +1,12 @@
{
"name": "playground",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playground",
"version": "0.1.0"
}
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"name": "playground",
"version": "0.1.0",
"description": "A playground for testing Roku development",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playground",
"build": "bsc --debug --create-package --sourceMap=true --lintConfig ../config/bslint.jsonc",
"lint": "bslint --project bsconfig.lint.json --lintConfig ../config/bslint.jsonc",
"lint:fix": "npm run lint -- --fix",
"format:base": "bsfmt \"src/**/*.brs\" \"src/**/*.bs\" \"!**/bslib.brs\" \"!**/roku_modules/**/*\" --bsfmt-path ../config/bsfmt.jsonc",
"format": "npm run format:base -- --check",
"format:fix": "npm run format:base -- --write",
"test": "npm run test:build && npm run test:run",
"test:build": "bsc --project bsconfig.tests.json --create-package --sourceMap=true --debug --test-mode --lintConfig ../config/bslint.jsonc",
"test:run": "node ../tools/run-test-app.js --package ../build/playground-tests.zip"
}
}
+3
View File
@@ -0,0 +1,3 @@
function Init()
print "Playground Init"
end function
+10
View File
@@ -0,0 +1,10 @@
<component name="Playground" extends="Scene">
<interface>
<field id="exitChannel" type="bool" alwaysNotify="true" />
<field id="launchArgs" type="assocarray" />
<field id="inputArgs" type="assocarray" alwaysNotify="true" />
</interface>
<children>
<Label text="Welcome to Playlet Playground!" />
</children>
</component>
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+31
View File
@@ -0,0 +1,31 @@
title=Playlet Playground
major_version=0
minor_version=1
build_version=00000
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
## Channel Assets
### Main Menu Icons / Channel Poster Artwork
#### Image sizes are FHD: 540x405px | HD: 290x218px | SD: 246x140px
mm_icon_focus_fhd=pkg:/images/channel-poster_fhd.png
mm_icon_focus_hd=pkg:/images/channel-poster_hd.png
mm_icon_focus_sd=pkg:/images/channel-poster_sd.png
### Splash Screen + Loading Screen Artwork
#### Image sizes are FHD: 1920x1080px | HD: 1280x720px | SD: 720x480px
splash_screen_fhd=pkg:/images/splash-screen_fhd.jpg
splash_screen_hd=pkg:/images/splash-screen_hd.jpg
splash_screen_sd=pkg:/images/splash-screen_sd.jpg
splash_color=#242424
splash_min_time=0
confirm_partner_button=1
supports_input_launch=1
requires_widevine_drm=1
requires_widevine_version=1.0
+56
View File
@@ -0,0 +1,56 @@
' Playlet (App to play videos from an Invidious server on Roku TVs)
' Copyright (C) 2025 Brahim Hadriche
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU Affero General Public License as published by
' the Free Software Foundation, either version 3 of the License, or
' (at your option) any later version.
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' GNU Affero General Public License for more details.
' You should have received a copy of the GNU Affero General Public License
' along with this program. If not, see <https://www.gnu.org/licenses/>.
function Main(args as object) as void
screen = CreateObject("roSGScreen")
port = CreateObject("roMessagePort")
screen.setMessagePort(port)
scene = screen.CreateScene("Playground")
screen.show()
scene.ObserveField("exitChannel", port)
scene.launchArgs = args
input = CreateObject("roInput")
input.setMessagePort(port)
' The following comment is to enable the SceneGraph inspector
' on the VSCode BrightScript plugin.
' vscode_rdb_on_device_component_entry
' The following comment is to enable RALE tracking
' vscode_rale_tracker_entry
while true
msg = wait(0, port)
msgType = type(msg)
if msgType = "roSGScreenEvent"
if msg.isScreenClosed()
return
end if
else if msgType = "roSGNodeEvent"
field = msg.getField()
data = msg.getData()
if field = "exitChannel" and data = true
return
end if
else if msgType = "roInputEvent"
scene.inputArgs = msg.getInfo()
end if
end while
end function
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-app",
"version": "0.43.8",
"version": "0.44.8",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-app",
"version": "0.43.8"
"version": "0.44.8"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-app",
"version": "0.43.8",
"version": "0.44.8",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-app",
@@ -37,6 +37,7 @@ function GetLoadingMessagesFromCache() as object
if messagesFile = ""
return invalid
end if
' bs:disable-next-line NO_PARSE_JSON
return ParseJson(messagesFile)
end function
+1 -1
View File
@@ -2,7 +2,7 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=43
minor_version=44
build_version=00008
ui_resolutions=hd
+1
View File
@@ -28,6 +28,7 @@ namespace Registry
if urlsJson = invalid
return invalid
end if
' bs:disable-next-line NO_PARSE_JSON
urls = ParseJson(urlsJson)
return urls
end function
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-lib",
"version": "0.43.8",
"version": "0.44.8",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-lib",
"version": "0.43.8"
"version": "0.44.8"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-lib",
"version": "0.43.8",
"version": "0.44.8",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-lib",
@@ -125,7 +125,7 @@ namespace DialogUtils
if hasMessageId
messages = RegistryUtils.Read(RegistryUtils.MESSAGES)
if not StringUtils.IsNullOrEmpty(messages)
messages = ParseJson(messages)
messages = StringUtils.ParseJsonSafe(messages)
if IsAssociativeArray(messages)
savedMessageId = ValidString(messages["messageId"])
if savedMessageId = messageId
+10 -10
View File
@@ -145,11 +145,11 @@ function OnLineLogMonitorMemoryWarning(event as object, dateTime as object, logs
return
end if
LogTelemetryEvent({
level: "warning"
message: line + `\nCurrentTime: ${m.eventThrottleTimer.TotalSeconds()}`
fingerprint: [message]
})
' LogTelemetryEvent({
' level: "warning"
' message: line + `\nCurrentTime: ${m.eventThrottleTimer.TotalSeconds()}`
' fingerprint: [message]
' })
end function
function OnLineLogDeviceInfoMemoryWarning(event as object, dateTime as object, logsFile as string, buffer as object) as void
@@ -168,11 +168,11 @@ function OnLineLogDeviceInfoMemoryWarning(event as object, dateTime as object, l
buffer.FromAsciiString(line + `\n`)
buffer.AppendFile(logsFile)
LogTelemetryEvent({
level: "warning"
message: line + `\nCurrentTime: ${m.eventThrottleTimer.TotalSeconds()}`
fingerprint: [message]
})
' LogTelemetryEvent({
' level: "warning"
' message: line + `\nCurrentTime: ${m.eventThrottleTimer.TotalSeconds()}`
' fingerprint: [message]
' })
end function
' Returns true if the event should be throttled
@@ -1,9 +1,10 @@
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
namespace HomeScreenUtils
function GetFeed(feedFileName as string, preferences as object) as object
feed = ParseJson(ReadAsciiFile(feedFileName))
feed = StringUtils.ParseJsonSafe(ReadAsciiFile(feedFileName))
for each item in feed
item.title = Tr(item.title)
@@ -3,11 +3,12 @@ import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/MathUtils.bs"
import "pkg:/source/utils/RemoteKeys.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.homeLayout = {}
homeLayout = ParseJson(ReadAsciiFile("libpkg:/config/default_home_layout.yaml"))
homeLayout = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/default_home_layout.yaml"))
for each item in homeLayout
m.homeLayout[item.id] = item
end for
@@ -324,7 +324,7 @@ end function
function CanFetchWithCors(instance as string, testNode as object, cancellation as object) as void
try
url = `${instance}/api/v1/trending`
url = `${instance}/api/v1/popular`
response = HttpClient.Get(url).NoCache().Cancellation(cancellation).Await()
if not response.IsSuccess()
@@ -20,7 +20,7 @@ function Load() as void
end if
m.bookmarksString = bookmarksString
bookmarks = ParseJson(bookmarksString)
bookmarks = StringUtils.ParseJsonSafe(bookmarksString)
if bookmarks = invalid
LogWarn("Failed to parse bookmarks json")
return
@@ -82,6 +82,7 @@ class DashManifest
xml = new XmlObject()
xml.Comment(`Generated by Playlet - Video ID: ${metadata.videoId}`)
xml.Comment(`Parser: ${ValidString(metadata.parser)}`)
if xml.Node("MPD", {
"xmlns": "urn:mpeg:dash:schema:mpd:2011"
@@ -288,8 +289,13 @@ class DashManifest
"contentType": "audio"
}
if IsAssociativeArray(firstFormat.audioTrack) and IsString(firstFormat.audioTrack.languageCode)
adaptationSetAttributes["lang"] = firstFormat.audioTrack.languageCode
if IsAssociativeArray(firstFormat.audioTrack)
if IsString(firstFormat.audioTrack.languageCode)
adaptationSetAttributes["lang"] = firstFormat.audioTrack.languageCode
else if IsString(firstFormat.audioTrack.id)
' ID is in the format "CODE.DIGIT" e.g. "en.4"
adaptationSetAttributes["lang"] = firstFormat.audioTrack.id.split(".")[0]
end if
end if
' Hoist common attributes
@@ -267,61 +267,6 @@ namespace InnertubeService
return Innertube.Search(query, options)
end function
function GetTrending(options = invalid as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
trendingType = LCase(OptionUtils.GetOrDefault(options, "type", ""))
disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false)
raw = OptionUtils.GetOrDefault(options, "raw", false)
params = ""
if trendingType = "music"
' {"44:proto": {"3:string": "ytma_charts"}}
params = "4gINGgt5dG1hX2NoYXJ0cw%3D%3D"
else if trendingType = "gaming"
' {"44:proto": {"3:string": "gaming_corpus_most_popular"}}
params = "4gIcGhpnYW1pbmdfY29ycHVzX21vc3RfcG9wdWxhcg%3D%3D"
else if trendingType = "movies"
' {"44:proto": {"3:string": "trailers"}}
params = "4gIKGgh0cmFpbGVycw%3D%3D"
end if
request = Innertube.CreateBrowseRequest("FEtrending", Innertube.ClientType.WEB, { params: params })
request.Cancellation(cancellation)
if raw
request.LogCurlCommand(true)
request.NoCache()
end if
response = request.Await()
if not response.IsSuccess()
return {
error: response.ErrorMessage()
}
end if
if raw
return response.Json()
end if
feeds = Innertube.ParseResponseDataForFeeds(response.Json(), {
response: response
disableCreatorOnTheRise: true
disableShorts: disableShorts
})
result = {
feeds: feeds
}
cacheControl = Innertube.ParseResponseForCacheControl(response)
if cacheControl <> invalid
result["cache-control"] = cacheControl
end if
return result
end function
function GetHome(options = invalid as object) as object
return GetBrowseAuthenticatedPage("FEwhat_to_watch", options)
end function
@@ -338,12 +283,12 @@ namespace InnertubeService
return GetBrowseAuthenticatedPage("FEplaylist_aggregation", options)
end function
function GetBrowseAuthenticatedPage(browserId as string, options = invalid as object) as object
function GetBrowseAuthenticatedPage(browseId as string, options = invalid as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
accessToken = OptionUtils.Get(options, "accessToken")
disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false)
request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv, options)
request = Innertube.CreateBrowseRequest(browseId, Innertube.ClientType.Tv, options)
if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken)
@@ -360,6 +305,7 @@ namespace InnertubeService
feeds = Innertube.ParseResponseDataForFeeds(response.Json(), {
response: response
disableShorts: disableShorts
browseId: browseId
})
result = {
@@ -416,6 +362,7 @@ namespace InnertubeService
cancellation = OptionUtils.Get(options, "cancellation")
accessToken = OptionUtils.Get(options, "accessToken")
onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser")
cpn = OptionUtils.Get(options, "cpn")
videostatsPlaybackUrl = videostatsPlaybackUrl.replace("https://s.", "https://www.")
queryParams = UrlUtils.ParseQueryComponents(videostatsPlaybackUrl)
@@ -423,8 +370,8 @@ namespace InnertubeService
queryParams["cbrver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["cver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["ver"] = "2"
queryParams["cpn"] = InnertubeService.CreateClientPlaybackNonce()
queryParams["cmt"] = 0
queryParams["cmt"] = "0"
queryParams["cpn"] = cpn
queryParams["final"] = "1"
videostatsPlaybackUrl = UrlUtils.SetQueryParams(videostatsPlaybackUrl, queryParams)
@@ -453,6 +400,7 @@ namespace InnertubeService
onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser")
timeStr = time.ToStr("%.3f")
cpn = OptionUtils.Get(options, "cpn")
videostatsWatchtimeUrl = videostatsWatchtimeUrl.replace("https://s.", "https://www.")
queryParams = UrlUtils.ParseQueryComponents(videostatsWatchtimeUrl)
@@ -460,11 +408,11 @@ namespace InnertubeService
queryParams["cbrver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["cver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["ver"] = "2"
queryParams["cpn"] = InnertubeService.CreateClientPlaybackNonce()
queryParams["cmt"] = 0
queryParams["final"] = "1"
queryParams["cpn"] = cpn
queryParams["cmt"] = "0"
queryParams["st"] = timeStr
queryParams["et"] = timeStr
queryParams["final"] = "1"
videostatsWatchtimeUrl = UrlUtils.SetQueryParams(videostatsWatchtimeUrl, queryParams)
request = HttpClient.Get(videostatsWatchtimeUrl)
@@ -521,7 +469,7 @@ namespace InnertubeService
return response.Json()
end if
result = Innertube.ParseChannelPageResponseData(response.Json(), response)
result = Innertube.ParseChannelPageResponseData(channelId, response.Json(), response)
if result.authorId = invalid and result.error = invalid
result["authorId"] = channelId
end if
@@ -663,7 +611,7 @@ namespace InnertubeService
return response.Json()
end if
result = Innertube.ParsePlaylistPageResponseData(response.Json(), response)
result = Innertube.ParsePlaylistPageResponseData(playlistId, response.Json(), response)
if result.playlistId = invalid and result.error = invalid
result["playlistId"] = playlistId
@@ -86,6 +86,7 @@ namespace Innertube
"richGridRenderer": ParseRichGridRenderer
"richItemRenderer": ParseRichItemRenderer
"feedFilterChipBarRenderer": ParseFeedFilterChipBarRenderer
"chipBarViewModel": ParseChipBarViewModel
"continuationItemRenderer": ParseContinuationItemRenderer
"appendContinuationItemsAction": ParseAppendContinuationItemsAction
"reloadContinuationItemsCommand": ParseReloadContinuationItemsCommand
@@ -103,9 +104,8 @@ namespace Innertube
' Ignored nodes:
' TODO:P2 handle navigateAction - which are usually a redirect
' "navigateAction": ParseNotImplemented
' TODO:P2 radioRenderer seems like a Mix https://github.com/iBicha/playlet/issues/709
"radioRenderer": ParseRadioRenderer
' "compactRadioRenderer": ParseNotImplemented
"compactRadioRenderer": ParseCompactRadioRenderer
' TODO:P2 A carousel of videos, found on the home tab of a channel.
' Should probably be parsed.
' "carouselItemRenderer": ParseNotImplemented
@@ -164,6 +164,7 @@ namespace Innertube
"emergencyOneboxRenderer": ParseNotImplemented
' Suicide & crisis lifeline, within search
"searchFrictionViewModel": ParseNotImplemented
"shoppingTimelyShelfViewModel": ParseNotImplemented
"backstagePostRenderer": ParseNotImplemented
"backstagePostThreadRenderer": ParseNotImplemented
"counterfactualRenderer": ParseNotImplemented
@@ -252,6 +253,15 @@ namespace Innertube
context.currentFeed.sortOptions = sortOptions
end if
end if
continuation = ObjectUtils.Dig(nodeData, ["continuations", 0, "nextContinuationData", "continuation"])
if IsString(continuation)
if not StringUtils.IsNullOrEmpty(context.currentFeed.continuation)
StartNewFeed("", context)
end if
context.currentFeed.continuation = continuation
end if
return nodeData["contents"]
end function
@@ -277,6 +287,17 @@ namespace Innertube
end if
end if
if ValidString(context.browseId) = "FEwhat_to_watch"
' shelfs with a heroCarouselHeaderRenderer are usually big carousels at the top of the home page
' to advertise some paid content.
' They hijack the shelf we want to parse (e.g. Recommended videos).
heroCarouselHeader = ObjectUtils.Dig(nodeData, ["headerRenderer", "heroCarouselHeaderRenderer"])
if heroCarouselHeader <> invalid
LogInfo("Skipping shelf with heroCarouselHeaderRenderer")
return invalid
end if
end if
' TODO: handle shelfRenderer.title
' TODO: handle shelfRenderer.headerRenderer.shelfHeaderRenderer.avatarLockup.avatarLockupRenderer.title
return nodeData["content"]
@@ -1025,6 +1046,36 @@ namespace Innertube
return invalid
end function
function ParseCompactRadioRenderer(nodeData as object, context as object) as object
playlistId = nodeData["playlistId"]
if not IsString(playlistId)
Warning("Invalid playlist ID in compactRadioRenderer", nodeData, context)
return invalid
end if
videoCountText = ParseText(nodeData["videoCountText"])
if videoCountText = ""
videoCountText = ParseText(nodeData["videoCountShortText"])
end if
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": ParseText(nodeData["title"])
"playlistThumbnail": ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails", 0, "url"])
"videoCountText": videoCountText
}
' Mixes have a videoId, which is the first video in the mix
videoId = ObjectUtils.Dig(nodeData, ["navigationEndpoint", "watchEndpoint", "videoId"])
if IsString(videoId)
playlist["videoId"] = videoId
end if
PushFeedItem(playlist, context)
return invalid
end function
function ParseGridShelfViewModel(nodeData as object, _context as object) as object
return nodeData["contents"]
end function
@@ -1400,6 +1451,10 @@ namespace Innertube
return TileRendererTypeChannel(nodeData, context)
else if contentType = "TILE_CONTENT_TYPE_EDU"
' Not implemented yet - https://github.com/iBicha/playlet/issues/751
' Basically a tile that redirects to a search with predifined querty.
' To support, Playlet will probably need to implement an independent
' search view that can be opened from anywhere.
return invalid
end if
Warning(`Unknown content type: ${contentType}`, nodeData, context)
@@ -1666,13 +1721,64 @@ namespace Innertube
end function
function ParseRichGridRenderer(nodeData as object, context as object) as object
feedFilterChipBarRenderer = ObjectUtils.Dig(nodeData, ["header", "feedFilterChipBarRenderer"])
header = nodeData["header"]
feedFilterChipBarRenderer = invalid
chipBarViewModel = invalid
if IsAssociativeArray(header)
feedFilterChipBarRenderer = header["feedFilterChipBarRenderer"]
chipBarViewModel = header["chipBarViewModel"]
end if
if feedFilterChipBarRenderer <> invalid
ParseFeedFilterChipBarRenderer(feedFilterChipBarRenderer, context)
else if chipBarViewModel <> invalid
ParseChipBarViewModel(chipBarViewModel, context)
end if
return nodeData["contents"]
end function
function ParseChipBarViewModel(nodeData as object, context as object) as object
chips = ObjectUtils.Dig(nodeData, ["chips"])
if not IsArray(chips)
return invalid
end if
sortOptions = []
for each chip in chips
chipViewModel = chip["chipViewModel"]
if not IsAssociativeArray(chipViewModel)
continue for
end if
title = ValidString(chipViewModel["text"])
isSelected = ValidBool(chipViewModel["selected"])
token = invalid
tapCommand = chipViewModel["tapCommand"]
if IsAssociativeArray(tapCommand)
innertubeCommand = tapCommand["innertubeCommand"]
if IsAssociativeArray(innertubeCommand)
continuationCommand = innertubeCommand["continuationCommand"]
if IsAssociativeArray(continuationCommand)
token = ValidString(continuationCommand["token"])
end if
end if
end if
if title = "" or StringUtils.IsNullOrEmpty(token)
continue for
end if
sortOptions.Push({
"title": title
"continuation": token
"isSelected": isSelected
})
end for
if sortOptions.Count() > 0
context.currentFeed.sortOptions = sortOptions
end if
return invalid
end function
function ParseRichItemRenderer(nodeData as object, _context as object) as object
return nodeData["content"]
end function
@@ -1893,6 +1999,8 @@ namespace Innertube
function ParseCompactMovieRenderer(nodeData as object, context as object) as object
videoId = nodeData["videoId"]
if not IsString(videoId)
' TODO:P2 Can be a show, example
' {"badges":[{"metadataBadgeRenderer":{"accessibilityData":{"label":"Free with ads"},"label":"Free with ads","style":"BADGE_STYLE_TYPE_YPC","trackingParams":"CKQBEJaLARgJIhMI15bJgdLnkAMVoHtMCB0nGTYG"}},{"metadataBadgeRenderer":{"accessibilityData":{"label":"tv-g"},"label":"TV-G","style":"BADGE_STYLE_TYPE_MEDIA","trackingParams":"CKQBEJaLARgJIhMI15bJgdLnkAMVoHtMCB0nGTYG"}}],"navigationEndpoint":{"browseEndpoint":{"browseId":"SCLKZr4NmdhyFZXLCYhehRmg","params":"kgYcGhoSGFVDTEtacjRObWRoeUZaWExDWWhlaFJtZw%3D%3D"},"clickTrackingParams":"CKQBEJaLARgJIhMI15bJgdLnkAMVoHtMCB0nGTYGygEEl7wVRg==","commandMetadata":{"webCommandMetadata":{"apiUrl":"/youtubei/v1/browse","rootVe":6827,"url":"/show/SCLKZr4NmdhyFZXLCYhehRmg?sbp=GhoSGFVDTEtacjRObWRoeUZaWExDWWhlaFJtZw%253D%253D","webPageType":"WEB_PAGE_TYPE_BROWSE"}}},"thumbnail":{"thumbnails":[{"height":596,"url":"https://yt3.ggpht.com/KPRERPv8FmjHUtaEip00aL1RuIkU-0_YR4XrbzG_66s6kkm1sx9MtSJgzeYexpRVtXoN1P1OjQ=w1060-fcrop64=1,00000000ffffffff-k-c0xffffffff-no-nd-rj","width":1060}]},"thumbnailOverlays":[{"thumbnailOverlayBottomPanelRenderer":{"text":{"runs":[{"text":"4"},{"text":" seasons"}]}}}],"title":{"accessibility":{"accessibilityData":{"label":"Everything's Rosie 4 seasons"}},"simpleText":"Everything's Rosie"},"topMetadataItems":[{"simpleText":"Animation \u2022 2011"}],"trackingParams":"CKQBEJaLARgJIhMI15bJgdLnkAMVoHtMCB0nGTYG"}
Warning("Invalid videoId in compactMovieRenderer", nodeData, context)
return invalid
end if
@@ -27,7 +27,7 @@ namespace Innertube
for i = 0 to adaptiveFormats.Count() - 1
formatsToProcess.Push({
format: adaptiveFormats[i]
file: `tmp:/otf_segments/${i}.bin`
filePath: `tmp:/otf_segments/${i}.bin`
})
end for
@@ -38,6 +38,8 @@ namespace Innertube
requestHeaders["referer"] = "https://www.youtube.com"
requestHeaders["DNT"] = "?1"
segmentDurationsRegex = CreateObject("roRegex", "(\d+)(?:\(r=(\d+)\))?", "g")
fs = CreateObject("roFileSystem")
fs.Delete("tmp:/otf_segments")
fs.CreateDirectory("tmp:/otf_segments")
@@ -45,7 +47,7 @@ namespace Innertube
while true
while formatsToProcess.Count() > 0 and pendingFormats.Count() < OTF_MAX_REQUEST_COUNT
formatToProcess = formatsToProcess.Pop()
request = OTFMakeSegmentInfoRequest(formatToProcess.format, formatToProcess.file, requestHeaders, errors, cancellation)
request = OTFMakeSegmentInfoRequest(formatToProcess.format, formatToProcess.filePath, requestHeaders, errors, cancellation)
if request <> invalid
formatToProcess.request = request
pendingFormats.Push(formatToProcess)
@@ -58,7 +60,7 @@ namespace Innertube
pendingFormat = pendingFormats.Shift()
' returns false if processing should stop (e.g., cancelled)
if not OTFProcessPendingFormat(pendingFormat.format, pendingFormat.request, pendingFormat.file, errors)
if not OTFProcessPendingFormat(pendingFormat.format, pendingFormat.request, pendingFormat.filePath, segmentDurationsRegex, errors)
exit while
end if
end while
@@ -75,7 +77,7 @@ namespace Innertube
end if
end function
function OTFMakeSegmentInfoRequest(format as object, file as string, requestHeaders as object, errors as object, cancellation as object) as object
function OTFMakeSegmentInfoRequest(format as object, filePath as string, requestHeaders as object, errors as object, cancellation as object) as object
url = format.url
if StringUtils.IsNullOrEmpty(url)
errors.message += `URL is empty for itag ${format.itag}.\n`
@@ -89,14 +91,14 @@ namespace Innertube
request = HttpClient.Get(otfUrl)
request.Headers(requestHeaders)
request.ToFile(file)
request.ToFile(filePath)
request.Cancellation(cancellation)
request.Send()
return request
end function
function OTFProcessPendingFormat(format as object, request as object, file as string, errors as object) as boolean
function OTFProcessPendingFormat(format as object, request as object, filePath as string, segmentDurationsRegex as object, errors as object) as boolean
response = request.Await()
if response.IsCancelled()
@@ -108,18 +110,18 @@ namespace Innertube
return true
end if
segmentDurations = OTFParseFileForSegmentInfo(file, errors)
segmentDurations = OTFParseFileForSegmentDurations(filePath, segmentDurationsRegex, errors)
if segmentDurations = invalid
errors.message += `Failed to parse segment info for itag ${format.itag}.\n`
errors.message += `Failed to parse segment durations for itag ${format.itag}.\n`
errors.message += `Headers: ${ToString(response.Headers())}\n`
return true
end if
format.otfSegmentInfo = segmentDurations
format["otfSegmentDurations"] = segmentDurations
return true
end function
function OTFParseFileForSegmentInfo(filePath as string, errors as object) as dynamic
function OTFParseFileForSegmentDurations(filePath as string, segmentDurationsRegex as object, errors as object) as dynamic
buffer = CreateObject("roByteArray")
buffer.FromAsciiString("Segment-Durations-Ms:")
@@ -129,14 +131,14 @@ namespace Innertube
endMarkerHex = buffer.ToHexString()
if not buffer.ReadFile(filePath)
errors.message += `Failed to read file at path ${filePath}.\n`
errors.message += `Failed to read filePath ${filePath}.\n`
return invalid
end if
contentHex = buffer.ToHexString()
startIndex = contentHex.InStr(startMarkerHex)
if startIndex = -1
errors.message += `Start marker not found in file at path ${filePath}.\n`
errors.message += `Start marker not found in filePath ${filePath}.\n`
errors.attachments.Push({
filename: filePath
content_type: "plain/text"
@@ -147,7 +149,7 @@ namespace Innertube
endIndex = contentHex.InStr(startIndex, endMarkerHex)
if endIndex = -1
errors.message += `End marker not found in file at path ${filePath}.\n`
errors.message += `End marker not found in filePath ${filePath}.\n`
errors.attachments.Push({
filename: filePath
content_type: "plain/text"
@@ -160,10 +162,9 @@ namespace Innertube
buffer.FromHexString(segmentDurationsMsHex)
segmentDurationsMs = buffer.ToAsciiString()
regex = CreateObject("roRegex", "(\d+)(?:\(r=(\d+)\))?", "g")
matches = regex.MatchAll(segmentDurationsMs)
matches = segmentDurationsRegex.MatchAll(segmentDurationsMs)
if not IsArray(matches) or matches.Count() = 0
errors.message += `No segment duration matches found in file at path ${filePath}.\n`
errors.message += `No segment duration matches found in filePath ${filePath}.\n`
errors.attachments.Push({
filename: filePath
content_type: "plain/text"
@@ -44,7 +44,7 @@ namespace Innertube
return context.feeds
end function
function ParseChannelPageResponseData(responseData as object, response as object) as object
function ParseChannelPageResponseData(browseId as string, responseData as object, response as object) as object
if responseData = invalid
return {
error: "Invalid response data"
@@ -63,6 +63,9 @@ namespace Innertube
author = ObjectUtils.Dig(responseData, ["header", "pageHeaderRenderer", "pageTitle"])
end if
authorId = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "externalId"])
if StringUtils.IsNullOrEmpty(authorId)
authorId = browseId
end if
thumbnails = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "avatar", "thumbnails"])
if thumbnails = invalid
@@ -149,6 +152,7 @@ namespace Innertube
response: response
"currentAuthor": author
"currentAuthorId": authorId
browseId: browseId
})
if feeds.Count() > 0
items = ValidArray(feeds[0].items)
@@ -183,7 +187,7 @@ namespace Innertube
return channel
end function
function ParsePlaylistPageResponseData(responseData as object, response as object) as object
function ParsePlaylistPageResponseData(browseId as string, responseData as object, response as object) as object
if responseData = invalid
return {
error: "Invalid response data"
@@ -251,13 +255,16 @@ namespace Innertube
end if
end if
if StringUtils.IsNullOrEmpty(playlistId)
playlistId = browseId
end if
playlist = {
"playlistId": playlistId
"videoCount": videoCount
"videos": []
}
if playlistId <> invalid
playlist["playlistId"] = playlistId
end if
if title <> invalid
playlist["title"] = title
end if
@@ -279,6 +286,7 @@ namespace Innertube
feeds = ParseResponseDataForFeeds(responseData, {
response: response
browseId: browseId
})
if feeds.Count() > 0
playlist["videos"] = ValidArray(feeds[0].items)
@@ -13,8 +13,6 @@ namespace Innertube
cancellation = OptionUtils.Get(options, "cancellation")
visitorData = OptionUtils.Get(options, "visitorData")
accessToken = OptionUtils.Get(options, "accessToken")
doSignatureTimestamp = ValidBool(OptionUtils.Get(options, "signatureTimestamp"))
cpn = InnertubeService.CreateClientPlaybackNonce()
useAccessToken = client = Innertube.ClientType.TV and not StringUtils.IsNullOrEmpty(accessToken)
@@ -52,12 +50,9 @@ namespace Innertube
"contentCheckOk": true
}
signatureTimestamp = invalid
if doSignatureTimestamp
signatureTimestamp = GetSignatureTimestamp(cancellation)
if signatureTimestamp <> invalid
payload["playbackContext"]["contentPlaybackContext"]["signatureTimestamp"] = signatureTimestamp
end if
signatureTimestamp = GetSignatureTimestamp(cancellation)
if signatureTimestamp <> invalid
payload["playbackContext"]["contentPlaybackContext"]["signatureTimestamp"] = signatureTimestamp
end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload)
@@ -122,6 +117,7 @@ namespace Innertube
formats = TransformFormats(formats)
parsedResponse["type"] = "video"
parsedResponse["parser"] = "playlet"
parsedResponse["videoId"] = videoDetails["videoId"]
parsedResponse["videoThumbnails"] = videoDetails["thumbnail"]["thumbnails"]
parsedResponse["storyboards"] = ParseStoryboards(payload, lengthSeconds)
@@ -316,6 +312,7 @@ namespace Innertube
end if
captions = []
autoCaptions = []
for each track in tracks
if not IsAssociativeArray(track)
continue for
@@ -341,13 +338,22 @@ namespace Innertube
label = ParseText(track["name"])
captions.Push({
thisCaption = {
"label": label
"language_code": languageCode
"url": baseUrl
})
}
if track["kind"] = "asr"
autoCaptions.Push(thisCaption)
continue for
end if
captions.Push(thisCaption)
end for
' Put automatically generated captions at the end so human-generated ones take priority
captions.Append(autoCaptions)
return captions
end function
@@ -443,7 +449,7 @@ namespace Innertube
LogDebug(`ReadAsciiFile("tmp:/sts_cache.json")`)
cache = ReadAsciiFile("tmp:/sts_cache.json")
if not StringUtils.IsNullOrEmpty(cache)
json = ParseJson(cache)
json = StringUtils.ParseJsonSafe(cache)
return json["sts"]
end if
@@ -639,6 +645,10 @@ namespace Innertube
return true
end if
if ValidBool(ObjectUtils.Dig(payload, ["videoDetails", "isPostLiveDvr"]))
return false
end if
adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"]))
if FormatsHaveLiveStreamingData(adaptiveFormats)
return true
@@ -718,7 +728,13 @@ namespace Innertube
headers = response.Headers()
if not headers.DoesExist("X-Head-Time-Millis") or not headers.DoesExist("X-Head-Seqnum")
LogError("GetPostLiveDvrInfo: Missing Post-Live DVR info in headers", headers)
msg = "GetPostLiveDvrInfo: Missing Post-Live DVR info in headers"
LogErrorNoTelemetry(msg, url, headers)
LogTelemetryEvent({
level: "error"
message: msg + `\nVideoID: ${parsedResponse["videoId"]}\nUrl: ${url}\nHeaders: ${FormatJson(headers)}`
fingerprint: [msg]
})
end if
durationMs = ValidString(headers["X-Head-Time-Millis"]).ToInt()
@@ -87,7 +87,7 @@ namespace Innertube
text = response.Text()
text = text.Replace(`)]}'`, "")
parsed = ParseJson(text)
parsed = StringUtils.ParseJsonSafe(text)
if not IsArray(parsed) or parsed.Count() < 2
return {
error: "Failed to parse search suggestions"
@@ -46,7 +46,7 @@ namespace Innertube
text = response.Text()
text = text.Replace(`)]}'`, "")
json = ParseJson(text)
json = StringUtils.ParseJsonSafe(text)
if json = invalid
return {
"error": "Failed to parse session data: " + text
@@ -78,7 +78,7 @@ namespace Innertube
return invalid
end if
sessionData = ParseJson(sessionData)
sessionData = StringUtils.ParseJsonSafe(sessionData)
if sessionData = invalid
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
return invalid
@@ -1,7 +1,7 @@
import "InvidiousService.bs"
function Init()
m.top.apiDefinitions = ParseJson(ReadAsciiFile("libpkg:/config/invidious_video_api.yaml"))
m.top.apiDefinitions = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/invidious_video_api.yaml"))
m.service = new Invidious.InvidiousService(m.top)
end function
@@ -698,7 +698,7 @@ namespace Invidious
end function
function VerifyTokenScope(token as string) as boolean
tokenObject = ParseJson(token)
tokenObject = StringUtils.ParseJsonSafe(token)
if tokenObject = invalid
LogWarn("Failed to json parse token:", token)
return false
@@ -68,6 +68,7 @@ class LoungeApi
commandHandlers[COMMAND_TYPE_GRACEFUL_RECONNECT] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_GET_RECEIVER_STATUS] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_SEND_DEBUG_COMMAND] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_SET_AUTOPLAY_MODE] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_GET_NOW_PLAYING] = m.HandleGetPlayingNow
commandHandlers[COMMAND_TYPE_SESSION_ID] = m.HandleSessionId
@@ -211,7 +212,7 @@ class LoungeApi
text = text.Mid(text.instr(`\n`) + 1)
messagesToSend = []
commands = ParseJson(text)
commands = StringUtils.ParseJsonSafe(text)
m.ProcessCommands(commands, messagesToSend)
m.SendMessages(messagesToSend)
return true
@@ -267,7 +268,7 @@ class LoungeApi
payloadSize = chunk.Left(newLineIndex).trim()
payloadSize = payloadSize.ToInt()
payload = chunk.Mid(newLineIndex + 1, payloadSize)
commands = ParseJson(payload)
commands = StringUtils.ParseJsonSafe(payload)
m.ProcessCommands(commands, messagesToSend)
chunk = chunk.Mid(newLineIndex + payloadSize + 1)
newLineIndex = chunk.InStr(`\n`)
@@ -324,9 +325,16 @@ class LoungeApi
LogInfo(commandIndex, commandType)
m[handler](commandIndex, commandType, commandArgs, messagesToSend)
else
LogWarn("Unknown command type:", commandType, "command:", command)
fingerprint = "Unknown command type:" + ToString(commandType)
message = fingerprint + " command:" + ToString(command)
LogWarnNoTelemetry(message)
LogTelemetryEvent({
level: "warning"
message: message
fingerprint: fingerprint
})
#if DEBUG
throw `Unknown command type: ${commandType} command: ${ToString(command)}`
throw message
#end if
end if
end for
@@ -368,7 +376,7 @@ class LoungeApi
if not IsString(devices)
return
end if
devices = ParseJson(devices)
devices = StringUtils.ParseJsonSafe(devices)
if devices = invalid
return
end if
@@ -610,7 +618,7 @@ class LoungeApi
RegistryUtils.Delete(RegistryUtils.LAST_LOUNGE_DATA)
loungeData = ParseJson(loungeData)
loungeData = StringUtils.ParseJsonSafe(loungeData)
if not IsAssociativeArray(loungeData)
LogWarn("Can't disconnect from lounge. Invalid data:", loungeData)
return
@@ -30,6 +30,7 @@ const COMMAND_TYPE_GET_DISCOVERT_DEVICE_ID = "getDiscoveryDeviceId"
const COMMAND_TYPE_GRACEFUL_RECONNECT = "gracefulReconnect"
const COMMAND_TYPE_GET_RECEIVER_STATUS = "getReceiverStatus"
const COMMAND_TYPE_SEND_DEBUG_COMMAND = "sendDebugCommand"
const COMMAND_TYPE_SET_AUTOPLAY_MODE = "setAutoplayMode"
' Special commands
const COMMAND_TYPE_SESSION_ID = "c"
const COMMAND_TYPE_G_SESSION_ID = "S"
@@ -86,7 +86,7 @@ namespace LoungeVideoQueue
' - eventDetails is of the form {"eventType":"VIDEO_REMOVED","videoId":"<videoId>"}
eventDetails = playlistData[FIELD_EVENT_DETAILS]
if IsString(eventDetails)
eventDetails = ParseJson(eventDetails)
eventDetails = StringUtils.ParseJsonSafe(eventDetails)
end if
if eventDetails <> invalid and eventDetails["eventType"] = "VIDEO_ADDED"
eventVideoId = eventDetails[FIELD_VIDEO_ID]
@@ -21,7 +21,7 @@ function Init()
end function
function LoadPreferencesFile()
m.top.prefsModel = ParseJson(ReadAsciiFile("libpkg:/config/preferences.json5"))
m.top.prefsModel = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/preferences.json5"))
end function
function AddNodeFields()
@@ -60,7 +60,7 @@ function LoadUserPreferencesFromRegistry()
if userPrefs = invalid
userPrefs = {}
else
userPrefs = ParseJson(userPrefs)
userPrefs = StringUtils.ParseJsonSafe(userPrefs)
end if
' Step 2: Migrate existing preferences to new format (if needed)
@@ -101,7 +101,7 @@ function MigrateExistingPreferences(userPrefs as object) as boolean
if not StringUtils.IsNullOrEmpty(instances)
currentInstance = userPrefs["invidious.instance"]
if StringUtils.IsNullOrEmpty(currentInstance)
instances = ParseJson(instances)
instances = StringUtils.ParseJsonSafe(instances)
if IsArray(instances) and instances.Count() > 0
instance = instances[0]
if not StringUtils.IsNullOrEmpty(instance)
@@ -162,6 +162,20 @@ function MigrateExistingPreferences(userPrefs as object) as boolean
isDirty = true
end if
if userPrefs.__version = 5
filteredLayout = []
homeScreenLayout = ValidArray(userPrefs["misc.home_screen_layout"])
for each item in homeScreenLayout
if item.id = "trending" or item.id = "trending_music" or item.id = "trending_gaming" or item.id = "trending_movies"
continue for
end if
filteredLayout.Push(item)
end for
userPrefs["misc.home_screen_layout"] = filteredLayout
userPrefs.__version = 6
isDirty = true
end if
' TODO:P2 handle case where saved preferences version is higher than current version (e.g. user downgraded)
#if DEBUG
@@ -5,7 +5,7 @@
user prefs saved need to be migrated. If the version is less than the
current version, a migration is needed.
-->
<field id="__version" type="integer" value="5" />
<field id="__version" type="integer" value="6" />
<field id="prefsModel" type="array" />
<field id="preferenceFields" type="assocarray" />
<function name="GetUserPreferences" />
@@ -31,7 +31,7 @@ function LoadProfilesFromRegistry()
currentProfile: invalid
}
else
userProfiles = ParseJson(userProfiles)
userProfiles = StringUtils.ParseJsonSafe(userProfiles)
end if
' Step 2: Migrate existing profiles to new format (if needed)
@@ -98,7 +98,7 @@ function MigrateExistingProfiles(userProfiles as object) as boolean
return false
end if
authToken = ParseJson(tokenPayload)
authToken = StringUtils.ParseJsonSafe(tokenPayload)
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
if authToken = invalid or authToken.instance = invalid or authToken.token = invalid or authToken.username = invalid
@@ -55,7 +55,7 @@ namespace SearchHistoryUtils
return []
end if
history = ParseJson(history)
history = StringUtils.ParseJsonSafe(history)
if not IsArray(history)
return []
end if
@@ -9,7 +9,7 @@ namespace SponsorBlock
class SponsorBlockService
function new()
' TODO:P2 this is being read and parsed on every skipped segment. It should be cached.
m.sponsorBlockConfig = ParseJson(ReadAsciiFile("libpkg:/config/sponsorblock_config.json5"))
m.sponsorBlockConfig = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/sponsorblock_config.json5"))
end function
function GetCategories() as object
@@ -65,31 +65,9 @@ function ExecuteJob() as void
})
if not response.success
if response.error = Invidious.ERROR_NOT_AUTHENTICATED
if feedSources.Count() = 1
parent = feedContentNode.getParent()
if parent <> invalid
parent.removeChild(feedContentNode)
end if
JobSuccess()
return
end if
continue while
end if
if response.error.instr("Administrator has disabled this endpoint.") > -1
LogWarnNoTelemetry(feedSource.endpoint, "feedSource not available:", response.error)
if feedSources.Count() = 1
parent = feedContentNode.getParent()
if parent <> invalid
parent.removeChild(feedContentNode)
end if
JobSuccess()
return
end if
continue while
if RemoveSingleFailedRow(response.error, feedSource, feedSources, feedContentNode)
JobSuccess()
return
end if
feedSource.state.loadState = FeedLoadState.Error
@@ -243,6 +221,32 @@ function DeduplicateAppendAuthPlaylists(feedContentNode as object, itemNodes as
return nodesToAdd.Count()
end function
function RemoveSingleFailedRow(error as dynamic, feedSource as object, feedSources as object, feedContentNode as object) as boolean
error = ValidString(error)
LogWarnNoTelemetry(feedSource.id, "feedSource not available:", error)
if feedSources.Count() <> 1
return false
end if
isError = error = Invidious.ERROR_NOT_AUTHENTICATED
' Invidious admins disable endpoints sometimes
isError = isError or error.instr("Administrator has disabled this endpoint") <> -1
isError = isError or error.instr("API disabled") <> -1
' Playlet not supporting popular
isError = isError or feedSource.id = "inv_popular"
if not isError
return false
end if
parent = feedContentNode.getParent()
if parent <> invalid
parent.removeChild(feedContentNode)
end if
return true
end function
function HandleFeedLoadErrorDialog(error as object, isCancelled as boolean, rowList as object) as void
error = ErrorUtils.Format(error)
if isCancelled
@@ -11,6 +11,7 @@ function ExecuteJob() as void
authToken = input.authToken
profileType = input.profileType
playbackTrackingUrls = input.playbackTrackingUrls
cpn = input.cpn
cancellation = JobGetCancellation()
@@ -43,9 +44,14 @@ function ExecuteJob() as void
return
end if
if StringUtils.IsNullOrEmpty(cpn)
cpn = InnertubeService.CreateClientPlaybackNonce()
end if
markedAsWatched = InnertubeService.AuthMarkVideoWatched(playbackTrackingUrls.videostatsPlaybackUrl, {
accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
cpn: cpn
cancellation: cancellation
})
if not markedAsWatched
@@ -93,6 +99,7 @@ function ExecuteJob() as void
success = InnertubeService.AuthMarkVideoWatchTime(watchTime, playbackTrackingUrls.videostatsWatchtimeUrl, {
accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
cpn: cpn
' TODO:P1 if we pass cancellation here, http client will remove scoped
' observer, which is stored on the current node.
' This requires an extra observer node to be independent.
@@ -61,7 +61,6 @@ function ExecuteJob() as void
"visitorData": visitorData
"accessToken": accessToken
"onBehalfOfUser": onBehalfOfUser
"signatureTimestamp": true
})
else
metadata = service.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation })
@@ -99,7 +98,19 @@ function ExecuteJob() as void
streamUrls = CreateStreamUrls(metadata, service, preferencesNode, backend, playletServerPort)
if streamUrls.Count() = 0
contentNode.addFields({ metadata: metadata })
JobError("No playable streams found for this video.")
error = "No playable streams found for this video."
lastPlayerResponse = ValidString(ReadAsciiFile("cachefs:/last_player_response.json"))
LogTelemetryEvent({
level: "error"
message: error
fingerprint: error
attachments: [{
filename: "last_player_response.json"
content_type: "application/json"
data: lastPlayerResponse
}]
})
JobError(error)
return
end if
@@ -329,7 +340,7 @@ function SetCaptions(metadata as object, service as object, contentNode as objec
return
end if
isoLanguageList = ParseJson(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"))
instance = service.GetInstance()
subtitleTracks = []
@@ -13,6 +13,18 @@ import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RemoteKeys.bs"
enum DownloadErrors
Unknown = 900
TimeoutByCurl = 950
TimeoutBySelector = 951
Abort = 960
AbortByServer = 961
AbortBySelector = 962
AbortByParallel = 963
ParallelFragmentError = 964
BadMedia = 970
end enum
function Init()
SetPlayerStyle()
SetupAnimation()
@@ -214,7 +226,7 @@ function OnVideoContentJobDone(event as object) as void
SeekToInitialPosition(content)
PlayAfterPreviousPlayerHasStopped()
MarkVideoWatched(content.videoId, metadata.playbackTrackingUrls)
MarkVideoWatched(content.videoId, metadata.playbackTrackingUrls, metadata.cpn)
end function
function SeekToInitialPosition(content as object) as void
@@ -317,6 +329,9 @@ function OnVideoContentJobErrorDialogResponse(event as object)
shouldPlayNext = false
if event <> invalid
dialog = event.getRoSGNode()
if m.errorDialog <> invalid and dialog.isSameNode(m.errorDialog)
m.errorDialog = invalid
end if
dialog.unobserveFieldScoped("wasClosed")
shouldPlayNext = dialog.actualButtonSelected = 0
end if
@@ -330,7 +345,7 @@ function OnVideoContentJobErrorDialogResponse(event as object)
Lounge.SendOnStateChange()
end function
function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic) as void
function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, cpn as dynamic) as void
if StringUtils.IsNullOrEmpty(videoId)
return
end if
@@ -353,6 +368,7 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic) a
authToken: authToken
profileType: profileType
playbackTrackingUrls: playbackTrackingUrls
cpn: cpn
}
m.markVideoWatchedJob = JobSystem.CreateCallback()
@@ -432,6 +448,14 @@ function OnVideoPlayerStateChange() as void
' Reset isSeekingPosition when started to play the video
if state = "playing"
m.isSeekingPosition = false
' If we somehow was able to recover playback after an error dialog, close the dialog
errorDialog = m.errorDialog
if errorDialog <> invalid
m.errorDialog = invalid
errorDialog.unobserveFieldScoped("wasClosed")
errorDialog.close = true
end if
end if
' If we successfully played the video, then any error that comes later is not due to a 403 (FORBIDDEN).
@@ -441,32 +465,23 @@ function OnVideoPlayerStateChange() as void
m.videoPlayingSuccess = true
end if
errorReported = false
errorData = invalid
if state = "error"
errorInfo = m.top.errorInfo
errorData = GetPlayerErrorData(content.videoId, errorInfo)
LogErrorNoTelemetry(errorData.title, errorData.body)
ReportVideoError(errorData, content.url)
errorReported = true
if m.videoPlayingSuccess <> true
' http for stream format, mediaerror for DASH
if errorInfo.category = "http" or errorInfo.category = "mediaerror"
currentUrl = content.url
playletStreamUrls = content.playletStreamUrls
playletStreamUrlIndex = content.playletStreamUrlIndex
playletStreamUrlIndex++
content.playletStreamUrlIndex = playletStreamUrlIndex
if playletStreamUrlIndex < playletStreamUrls.Count()
nextUrl = playletStreamUrls[playletStreamUrlIndex]
msg = `Stream ${currentUrl} failed to play. Trying next stream ${nextUrl}`
LogErrorNoTelemetry(msg)
LogTelemetryEvent({
level: "error"
message: msg
fingerprint: ["Stream <URL> failed to play. Trying next stream <URL>"]
})
currentUrlIndex = content.playletStreamUrlIndex
nextUrlIndex = currentUrlIndex + 1
content.playletStreamUrlIndex = nextUrlIndex
if nextUrlIndex < playletStreamUrls.Count()
currentUrl = content.url
nextUrl = playletStreamUrls[nextUrlIndex]
if StringUtils.IsNullOrEmpty(nextUrl)
LogError("Next stream URL is empty, cannot try next stream")
@@ -487,6 +502,12 @@ function OnVideoPlayerStateChange() as void
if hasTimestamp and timestamp > 0
m.top.seek = content.timestamp
end if
msg = `Stream ${currentUrl} failed to play. Trying next stream ${nextUrl}`
LogErrorNoTelemetry(msg)
errorData.title = msg + `\n` + errorData.title
ReportVideoError(errorData, currentUrl, playletStreamUrls, currentUrlIndex, false)
return
end if
end if
@@ -504,18 +525,14 @@ function OnVideoPlayerStateChange() as void
end if
if state = "error"
errorInfo = m.top.errorInfo
errorData = GetPlayerErrorData(content.videoId, errorInfo)
LogErrorNoTelemetry(errorData.title, errorData.body)
if not errorReported
ReportVideoError(errorData, content.url)
end if
ReportVideoError(errorData, content.url, content.playletStreamUrls, content.playletStreamUrlIndex, true)
buttons = [Tr(Locale.Buttons.PlayNextVideo), Tr(Locale.Buttons.Cancel)]
dialog = DialogUtils.ShowTimedDialogButtons(errorData.body, errorData.title, buttons, 0, 10, true)
if dialog <> invalid
m.errorDialog = dialog
dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentJobErrorDialogResponse))
else
OnVideoContentJobErrorDialogResponse(invalid)
@@ -557,7 +574,7 @@ function GetPlayerErrorData(videoId as string, errorInfo as object) as object
}
end function
function ReportVideoError(errorData as object, url as string) as void
function ReportVideoError(errorData as object, url as dynamic, urls as object, urlIndex as dynamic, shownInDialog as boolean) as void
attachments = invalid
if errorData.body.Instr("malformed data") <> -1 or errorData.body.Instr("invalid pathname") <> -1
lastGeneratedDash = ValidString(ReadAsciiFile("cachefs:/last_generated_dash.xml"))
@@ -581,9 +598,28 @@ function ReportVideoError(errorData as object, url as string) as void
position = m.top.position
duration = m.top.duration
message = [
errorData.title
errorData.body
`Dialog shown: ${shownInDialog}`
`Position: ${position}`
`Duration: ${duration}`
`Url: ${url}`
`Urls: ` + ToString(urls)
`Url index: ${urlIndex}`
].Join(`\n`)
errorData.fingerprint.push(shownInDialog)
if shownInDialog
level = "error"
else
level = "warning"
end if
LogTelemetryEvent({
level: "error"
message: errorData.title + " " + errorData.body + `\nurl: ${url}\nposition: ${position}\nduration: ${duration}`
level: level
message: message
fingerprint: errorData.fingerprint
attachments: attachments
})
@@ -66,7 +66,7 @@ namespace Http
return true
end if
feedSource = ParseJson(feedSource)
feedSource = StringUtils.ParseJsonSafe(feedSource)
if feedSource = invalid
response.Default(400, "Expected valid JSON for feed-source")
return true
@@ -253,9 +253,8 @@ namespace Http
return true
end function
@get("/playlet-invidious-backend/api/v1/trending")
@get("/playlet-invidious-backend/api/v1/popular")
function GetTrending(context as object) as boolean
function GetPopular(context as object) as boolean
request = context.request
response = context.response
@@ -264,40 +263,10 @@ namespace Http
return m.GetAuthRecommended(context)
end if
raw = request.query.raw <> invalid
options = {
"disableShorts": m.preferences["content_feed.disable_shorts"]
raw: raw
type: request.query.type
}
result = InnertubeService.GetTrending(options)
if raw
response.Json(result)
return true
end if
if result.error <> invalid
response.Json(result)
response.http_code = 500
return true
end if
if not IsArray(result.feeds) or result.feeds.Count() = 0
response.Json({
"error": "Failed to get trending feed"
})
response.http_code = 500
return true
end if
response.Json(ValidArray(result.feeds[0].items))
if result.DoesExist("cache-control")
response.headers["cache-control"] = result["cache-control"]
end if
response.Json({
"error": "Playlet built-in Invidious backend does not support popular videos."
})
response.http_code = 400
return true
end function
@@ -346,10 +315,6 @@ namespace Http
response.Json(result.feeds[0])
if result.DoesExist("cache-control")
response.headers["cache-control"] = result["cache-control"]
end if
return true
end function
@@ -619,7 +584,6 @@ namespace Http
}
end if
else
options["signatureTimestamp"] = true
options["credentialTransferToken"] = m.loungeService.credentialTransferToken
metadata = InnertubeService.GetVideoMetadata(videoId, options)
end if
@@ -804,7 +768,7 @@ namespace Http
' (such as "newest", "oldest", etc.), we'll ignore it, as it is not supported.
sortBy = request.query.sort_by
if not StringUtils.IsNullOrEmpty(sortBy) and sortBy.StartsWith("{")
sortBy = ParseJson(sortBy)
sortBy = StringUtils.ParseJsonSafe(sortBy)
if IsAssociativeArray(sortBy)
if sortBy.DoesExist("params")
options.params = sortBy.params
@@ -19,7 +19,7 @@ namespace Http
saved = RegistryUtils.Read(RegistryUtils.PLAYLET_LIB_URLS)
if saved <> invalid
saved = ParseJson(saved)
saved = StringUtils.ParseJsonSafe(saved)
end if
response.Json({
@@ -272,7 +272,7 @@ namespace Http
return invalid
end if
m.body_json = ParseJson(text)
m.body_json = StringUtils.ParseJsonSafe(text)
return m.body_json
end function
end class
@@ -11,7 +11,7 @@ namespace Http
if StringUtils.IsNullOrEmpty(json)
return "application/octet-stream"
end if
map = ParseJson(json)
map = StringUtils.ParseJsonSafe(json)
if not IsAssociativeArray(map)
return "application/octet-stream"
end if
@@ -41,7 +41,7 @@ namespace Http
if StringUtils.IsNullOrEmpty(json)
return ""
end if
map = ParseJson(json)
map = StringUtils.ParseJsonSafe(json)
if not IsAssociativeArray(map)
return ""
end if
@@ -14,44 +14,6 @@
apiType: Invidious
endpoint: auth_recommended
- title: Trending
id: trending
feedSources:
- id: inv_trending
title: Trending
apiType: Invidious
endpoint: trending
- title: Trending - Music
id: trending_music
feedSources:
- id: inv_trending_music
title: Trending - Music
apiType: Invidious
endpoint: trending
queryParams:
type: Music
- title: Trending - Gaming
id: trending_gaming
feedSources:
- id: inv_trending_gaming
title: Trending - Gaming
apiType: Invidious
endpoint: trending
queryParams:
type: Gaming
- title: Trending - Movies
id: trending_movies
feedSources:
- id: inv_trending_movies
title: Trending - Movies
apiType: Invidious
endpoint: trending
queryParams:
type: Movies
- title: Popular
id: popular
feedSources:
@@ -1,18 +1,3 @@
trending:
title: Trending
url: /api/v1/trending
cacheSeconds: 21600 # 6 hours
queryParams:
type:
type:
- Music
- Gaming
- Movies
region:
type: "#ISO3166"
default: GetUserCountryCode
tryCount: 3 # trending is being phased out, sometimes it returns a 400 INVALID_ARGUMENT
popular:
title: Popular
url: /api/v1/popular
-16
View File
@@ -243,22 +243,6 @@
id: "recommended",
enabled: true,
},
{
id: "trending",
enabled: true,
},
{
id: "trending_music",
enabled: true,
},
{
id: "trending_gaming",
enabled: true,
},
{
id: "trending_movies",
enabled: true,
},
{
id: "popular",
enabled: true,
@@ -312,22 +312,6 @@
<source>Watch history</source>
<translation>Wiedergabeverlauf</translation>
</message>
<message>
<source>Trending</source>
<translation>Trends</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Trends - Filme</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Trends - Musik</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Trends - Gaming</translation>
</message>
<message>
<source>Popular</source>
<translation>Populär</translation>
@@ -88,22 +88,6 @@
<source>Watch history</source>
<translation>Watch history</translation>
</message>
<message>
<source>Trending</source>
<translation>Trending</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Trending - Movies</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Trending - Music</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Trending - Gaming</translation>
</message>
<message>
<source>Popular</source>
<translation>Popular</translation>
@@ -80,22 +80,6 @@
<source>Watch history</source>
<translation>Ver el historial</translation>
</message>
<message>
<source>Trending</source>
<translation>Tendencias</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Tendencias - Películas</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Tendencias - Música</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Tendencias - Juegos</translation>
</message>
<message>
<source>Popular</source>
<translation>Popular</translation>
@@ -36,10 +36,6 @@
<source>Filters</source>
<translation>Filtros</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Tendencias - Música</translation>
</message>
<message>
<source>Login to Invidious in order to view Subscriptions, Playlists, and use the Watch history.</source>
<translation>Accede a Invidious para ver tus suscripciones, playlists, y usar el historial de reproducción.</translation>
@@ -80,18 +76,6 @@
<source>Watch history</source>
<translation>Historial de reproducción</translation>
</message>
<message>
<source>Trending</source>
<translation>Tendencias</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Tendencias - Películas</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Tendencias - Videojuegos</translation>
</message>
<message>
<source>Edit</source>
<translation>Editar</translation>
@@ -76,22 +76,6 @@
<source>Watch history</source>
<translation>Historique</translation>
</message>
<message>
<source>Trending</source>
<translation>Tendances</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Tendances - Films</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Tendances - Musique</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Tendances - Jeux vidéo</translation>
</message>
<message>
<source>Popular</source>
<translation>Populaire</translation>
@@ -140,22 +140,6 @@
<source>Watch history</source>
<translation>Histórico de assistidos</translation>
</message>
<message>
<source>Trending</source>
<translation>Em alta</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Em alta - Flimes</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Em alta - Música</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Em alta - Jogos</translation>
</message>
<message>
<source>Popular</source>
<translation>Popular</translation>
+1 -1
View File
@@ -2,7 +2,7 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=43
minor_version=44
build_version=00008
ui_resolutions=hd
@@ -454,7 +454,7 @@ namespace HttpClient
backoffMs = 1000 + Rnd(2000)
tryNumber = m._tryCount - triesLeft + 1
LogWarnNoTelemetry("Request failed ID:", m.urlTransfer.GetIdentity(), "ErrorMessage:", response.ErrorMessage(), `\nRetrying: (`, tryNumber, "/", m._tryCount, ") in", backoffMs, "ms")
LogWarnTelemetry(response.ErrorMessage())
LogWarnTelemetry(response.ErrorMessage() + `\n` + m.ToCurlCommand())
if IsFunction(m._retryCallback)
try
@@ -703,7 +703,7 @@ namespace HttpClient
if text = invalid
return invalid
end if
m._json = ParseJson(text)
m._json = StringUtils.ParseJsonSafe(text)
return m._json
end function
@@ -813,7 +813,7 @@ namespace HttpClientCache
end if
metadataText = cacheText.Left(firstLineIndex)
metadata = ParseJson(metadataText)
metadata = StringUtils.ParseJsonSafe(metadataText)
if metadata = invalid
LogWarn("Failed to parse metadata from cache.")
Delete(request)
@@ -821,7 +821,7 @@ namespace HttpClientCache
end if
headersText = cacheText.Mid(firstLineIndex + 1, metadata.headers)
headers = ParseJson(headersText)
headers = StringUtils.ParseJsonSafe(headersText)
if headers = invalid
LogWarn("Failed to parse headers from cache.")
Delete(request)
+9 -10
View File
@@ -1,6 +1,7 @@
namespace DebugUtils
function PrintStackTrace(message = invalid as dynamic)
#if DEBUG
#if DEBUG
namespace DebugUtils
function PrintStackTrace(message = invalid as dynamic)
try
throw "Handled throw in DebugUtils.PrintStackTrace()"
catch error
@@ -15,11 +16,9 @@ namespace DebugUtils
end for
PrintInABox(lines)
end try
#end if
end function
end function
function PrintInABox(lines as object)
#if DEBUG
function PrintInABox(lines as object)
maxLen = 0
for each line in lines
if line.len() > maxLen
@@ -32,6 +31,6 @@ namespace DebugUtils
end for
out += `\n` + "╚" + string(maxLen + 2, "═") + "╝"
print out
#end if
end function
end namespace
end function
end namespace
#end if
-4
View File
@@ -41,10 +41,6 @@ namespace Locale
Recommended = "Recommended"
Playlists = "Playlists"
WatchHistory = "Watch history"
Trending = "Trending"
TrendingMovies = "Trending - Movies"
TrendingMusic = "Trending - Music"
TrendingGaming = "Trending - Gaming"
Popular = "Popular"
Videos = "Videos"
Shorts = "Shorts"
@@ -29,5 +29,18 @@ namespace StringUtils
function RandomId() as string
return StrI(rnd(2147483647), 36)
end function
function ParseJsonSafe(jsonString as dynamic) as dynamic
if IsNullOrEmpty(jsonString)
return invalid
end if
' bs:disable-next-line NO_PARSE_JSON
json = ParseJson(jsonString)
if json <> invalid
return json
end if
' bs:disable-next-line NO_PARSE_JSON
return ParseJson(jsonString.Replace("\u0000", ""))
end function
end namespace
+1290 -1648
View File
File diff suppressed because it is too large. Load diff
+16 -17
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.43.8",
"version": "0.44.8",
"type": "module",
"scripts": {
"dev": "vite",
@@ -9,29 +9,28 @@
"lint": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/postcss": "^4.1.16",
"@sveltejs/vite-plugin-svelte": "^7.0.0",
"@tailwindcss/postcss": "^4.2.2",
"@tailwindcss/typography": "^0.5.19",
"@tsconfig/svelte": "^5.0.5",
"@vitejs/plugin-legacy": "^7.2.1",
"autoprefixer": "^10.4.21",
"@tsconfig/svelte": "^5.0.8",
"@vitejs/plugin-legacy": "^8.0.0",
"autoprefixer": "^10.4.27",
"bgutils-js": "^3.2.0",
"daisyui": "^5.3.10",
"dotenv": "^17.2.3",
"daisyui": "^5.5.19",
"dotenv": "^17.3.1",
"ip": "^2.0.1",
"jszip": "^3.10.1",
"postcss": "^8.5.6",
"rollup-plugin-visualizer": "^6.0.5",
"svelte": "^5.43.2",
"svelte-check": "^4.3.3",
"postcss": "^8.5.8",
"rollup-plugin-visualizer": "^7.0.1",
"svelte": "^5.54.0",
"svelte-check": "^4.4.5",
"svelte-preprocess": "^6.0.3",
"tailwindcss": "^4.1.16",
"terser": "^5.44.0",
"tailwindcss": "^4.2.2",
"terser": "^5.46.1",
"tslib": "^2.8.1",
"typescript": "^5.9.3",
"vite": "^7.1.12",
"vite": "^8.0.1",
"vite-plugin-compression": "^0.5.1",
"vite-tsconfig-paths": "^5.1.4",
"youtubei.js": "^16.0.1"
"youtubei.js": "^17.0.1"
}
}
+11 -15
View File
@@ -141,20 +141,8 @@ export class YoutubeJs {
static initJsEvaluator() {
Platform.shim.eval = async (data: Types.BuildScriptResult, env: Record<string, Types.VMPrimative>) => {
const properties = [];
if (env.n) {
properties.push(`n: exportedVars.nFunction("${env.n}")`)
}
if (env.sig) {
properties.push(`sig: exportedVars.sigFunction("${env.sig}")`)
}
const code = `${data.output}\nreturn { ${properties.join(', ')} }`;
return new Function(code)();
}
return new Function(data.output)();
};
}
static async generateVisitorData() {
@@ -255,6 +243,10 @@ export class YoutubeJs {
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) {
@@ -320,12 +312,16 @@ export class YoutubeJs {
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}`,
url: await format.decipher(YoutubeJs.innerTube.session.player),
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;
}
@@ -49,28 +49,43 @@
});
async function playOnTv() {
const videoInfo = getVideoInfo();
await PlayletApi.playVideo(videoInfo);
try {
const videoInfo = getVideoInfo();
await PlayletApi.playVideo(videoInfo);
} catch (error) {
console.error(error);
alert(error);
}
}
async function playOnTvYtjs() {
const videoInfo = getVideoInfo() as any;
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`);
// 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;
if (metadata) {
videoInfo.metadata = metadata;
}
await PlayletApi.playVideo(videoInfo);
} catch (error) {
console.error(error);
alert(error);
}
await PlayletApi.playVideo(videoInfo);
}
async function queueOnTv() {
const videoInfo = getVideoInfo();
await PlayletApi.queueVideo(videoInfo);
try {
const videoInfo = getVideoInfo();
await PlayletApi.queueVideo(videoInfo);
} catch (error) {
console.error(error);
alert(error);
}
}
function openInvidious() {
+3 -2
View File
@@ -2,7 +2,6 @@ import { visualizer } from 'rollup-plugin-visualizer';
import { defineConfig, UserConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import viteCompression from 'vite-plugin-compression';
import tsconfigPaths from 'vite-tsconfig-paths'
import ip from 'ip';
import { existsSync, readFileSync } from 'fs'
import { join as joinPath } from 'path'
@@ -13,7 +12,6 @@ const PORT = 5173
const config: UserConfig = {
plugins: [
tsconfigPaths(),
svelte(),
legacy({
targets: ['defaults', 'not IE 11'],
@@ -23,6 +21,9 @@ const config: UserConfig = {
deleteOriginFile: true
})
],
resolve: {
tsconfigPaths: true
},
build: {
outDir: "../playlet-lib/src/www",
emptyOutDir: true
+1 -1
View File
@@ -15,6 +15,6 @@ INVIDIOUS_HMAC_KEY=PASSWORD_1
INVIDIOUS_COMPANION_KEY=PASSWORD_2
```
- Run `docker-compose up`
- Run `docker compose up -d --pull always`
Invidious should now be running locally on port 3000.
+1 -1
View File
@@ -32,7 +32,7 @@ services:
# Use the key generated in the 2nd step
hmac_key: $INVIDIOUS_HMAC_KEY
healthcheck:
test: wget -nv --tries=1 --spider http://127.0.0.1:3000/api/v1/trending || exit 1
test: wget -nv --tries=1 --spider http://127.0.0.1:3000/api/v1/popular || exit 1
interval: 30s
timeout: 5s
retries: 2