Compare commits

...
66 Commits
Author SHA1 Message Date
Brahim Hadriche f5b81eff4d Release v0.44.9 (#848) 2026-04-25 09:52:15 -04:00
Brahim Hadriche b6bdbee42f [skip ci] updated dependencies and innertube versions 2026-04-25 09:49:22 -04:00
Brahim Hadriche 0fc9fbb79a [skip ci] Update PRIVACY.md with telemetry details
Added detailed explanation of current telemetry implementation, including data collected and its usage.
2026-04-24 17:15:33 -04:00
Brahim Hadriche f3c159218a [skip ci] log job name in errors 2026-04-24 16:34:01 -04:00
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
Brahim Hadriche c034dfe109 Release v0.43.8 (#782) 2025-11-07 08:40:47 -05:00
Brahim Hadriche 129f0a8adb [skip ci] document OTF 2025-11-07 08:40:32 -05:00
Brahim Hadriche a42c7221c6 [skip ci] Redo OTF processing 2025-11-07 08:29:45 -05:00
Brahim Hadriche c602fe3ed2 [skip ci] add more info in otf telemetry 2025-11-06 16:24:57 -05:00
Brahim Hadriche 33bb74d976 [skip ci] Fix in url decipher logic 2025-11-06 12:26:28 -05:00
87 changed files with 2500 additions and 3506 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", "args": "--log-level info --project bsconfig.tests.json --create-package --sourceMap=true --debug --test-mode --lintConfig ../config/bslint.jsonc",
"cwd": "${workspaceFolder}/playlet-lib", "cwd": "${workspaceFolder}/playlet-lib",
"console": "integratedTerminal" "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": [ "compounds": [
+5
View File
@@ -49,6 +49,11 @@
"label": "build-web", "label": "build-web",
"script": "build:web", "script": "build:web",
"type": "npm" "type": "npm"
},
{
"label": "build-playground",
"script": "build:playground",
"type": "npm"
} }
] ]
} }
+83
View File
@@ -5,6 +5,89 @@ 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.44.9] - 2026-04-25
### Fixed
- Updated dependencies and innertube versions
## [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
- Fix in url decipher logic
- Redo OTF segment processing
## [0.43.7] - 2025-11-06 ## [0.43.7] - 2025-11-06
### Fixed ### Fixed
+20
View File
@@ -8,6 +8,26 @@ Playlet does not show advertising, whether personalized or non personalized.
Playlet may integrate with 3rd party telemetry services in order to capture anonymous diagnostics data. The only purpose of this data is to diagnose issues and improve the app. Playlet may integrate with 3rd party telemetry services in order to capture anonymous diagnostics data. The only purpose of this data is to diagnose issues and improve the app.
### Current telemetry implementation
> This section tries to explain in more detail what data is collected and how it is used. Due to the granularity and details of the following explanation, it might be slightly out of date, but mostly represents the reality of the "Playlet may integrate with 3rd party telemetry services"
Currently, Playlet captures a bunch of errors through the [telemetry client code](https://github.com/iBicha/playlet/tree/f3c159218ac8e3eec08eb7b62cbd45ad6c451b99/playlet-lib/src/components/Telemetry).
It's mostly OS info (version, device model, etc), app info, user country code, locale, error messages, and stack traces. Nothing more than necessary is captured to debug problems.
In addition to that, an anonymous user id (just a guid stable across app launches of Playlet) and a session id (generated on every launch) are collected.
The user id is used to understand how many people an error affects. Sometimes one issue is spread out evenly among users, sometimes it's a handful of users (or even just one) spamming the same errors. This helps investigate that aspect.
The session id is used to understand how an error happened. By isolating a specific error to a session, it helps understand what led to said error.
This data is currently sent to a server, then forwarded to a self-hosted instance [Glitch-Tip](https://gitlab.com/glitchtip/glitchtip) which provides a simple dashboard showing how frequent errors are, and on which versions they occur.
This data is anonymous. The data is not collected in a way that can be linked back to a real person, or a YouTube profile for example.
The data is stored on a local hard drive, does not leave said hard drive, and accessed only by the currently single developer of Playlet, and frequently purged (because honestly I don't have the disk space).
The data is used to investigate errors, like playback errors, feed load errors, login errors, and so on.
## Invidious ## Invidious
Playlet may request information from one or more [Invidious](https://invidious.io/) Playlet may request information from one or more [Invidious](https://invidious.io/)
+3
View File
@@ -27,6 +27,9 @@
Playlet is an unofficial YouTube client for Roku 📺 Playlet is an unofficial YouTube client for Roku 📺
**[Playlet February 2026 Update](https://github.com/iBicha/playlet/discussions/827)**
## Screenshots ## Screenshots
<a href="./docs/screenshots/README.md"> <a href="./docs/screenshots/README.md">
+6
View File
@@ -58,6 +58,12 @@
"regex": "\\bTr\\s*\\(\\s*\"[^\\\"]*\"\\s*\\)", "regex": "\\bTr\\s*\\(\\s*\"[^\\\"]*\"\\s*\\)",
"regexFlags": "ig", "regexFlags": "ig",
"message": "Tr(\"String\") is not allowed. Use Tr(Locale.Key) instead." "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": [ "files": [
+208 -1227
View File
File diff suppressed because it is too large. Load diff
+20 -19
View File
@@ -1,38 +1,38 @@
{ {
"name": "playlet", "name": "playlet",
"version": "0.43.7", "version": "0.44.9",
"description": "Unofficial YouTube client for Roku", "description": "Unofficial YouTube client for Roku",
"devDependencies": { "devDependencies": {
"@rokucommunity/bslint": "^0.8.38", "@rokucommunity/bslint": "^0.8.41",
"@types/crypto-js": "^4.2.2", "@types/crypto-js": "^4.2.2",
"@types/fs-extra": "^11.0.4", "@types/fs-extra": "^11.0.4",
"@types/node": "^24.9.2", "@types/node": "^25.6.0",
"@types/xml2js": "^0.4.14", "@types/xml2js": "^0.4.14",
"argparse": "^2.0.1", "argparse": "^2.0.1",
"brighterscript": "0.70.3", "brighterscript": "0.71.1",
"brighterscript-formatter": "^1.7.19", "brighterscript-formatter": "^1.7.23",
"convert-svg-to-png": "^0.7.1", "convert-svg-to-png": "^0.7.1",
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"dotenv": "^17.2.3", "dotenv": "^17.4.2",
"fs-extra": "^11.3.2", "fs-extra": "^11.3.4",
"glob": "^11.0.3", "glob": "^13.0.6",
"imap": "^0.8.19", "imap": "^0.8.19",
"ip": "^2.0.1", "ip": "^2.0.1",
"json5": "^2.2.3", "json5": "^2.2.3",
"mailparser": "^3.7.5", "mailparser": "^3.9.8",
"protocol-buffers-schema": "^3.6.0", "protocol-buffers-schema": "^3.6.1",
"puppeteer": "^24.27.0", "puppeteer": "^24.42.0",
"roku-deploy": "^3.14.4", "roku-deploy": "^3.16.5",
"roku-test-automation": "^2.2.1", "roku-test-automation": "^2.2.2",
"rooibos-roku": "5.15.5", "rooibos-roku": "5.15.5",
"rounded-rect-9patch": "^1.1.2", "rounded-rect-9patch": "^1.1.2",
"semver": "^7.7.3", "semver": "^7.7.4",
"shelljs": "^0.10.0", "shelljs": "^0.10.0",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"typescript": "5.9.3", "typescript": "6.0.3",
"telnet-client": "^2.2.6", "telnet-client": "^2.2.13",
"xml2js": "^0.6.2", "xml2js": "^0.6.2",
"yaml": "^2.8.1" "yaml": "^2.8.3"
}, },
"engines": { "engines": {
"node": "22" "node": "22"
@@ -48,6 +48,7 @@
"build:lib:dev": "cd playlet-lib && npm run build:dev", "build:lib:dev": "cd playlet-lib && npm run build:dev",
"build:lib:prod": "cd playlet-lib && npm run build:prod", "build:lib:prod": "cd playlet-lib && npm run build:prod",
"build:web": "cd playlet-web && npm run build", "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": "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", "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", "format": "cd playlet-lib && npm run format && cd ../playlet-app && npm run format",
@@ -65,7 +66,7 @@
"screenshot": "node tools/screenshot.js", "screenshot": "node tools/screenshot.js",
"convert-images": "node tools/convert-images.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", "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", "update-deps": "npx npm-check-updates --deep --upgrade --install always --reject rooibos-roku",
"registry:write": "node tools/registry.js --input registry.json", "registry:write": "node tools/registry.js --input registry.json",
"registry:read": "node tools/registry.js --output registry.json", "registry:read": "node tools/registry.js --output registry.json",
@@ -75,6 +76,6 @@
"shutdown": "node tools/shutdown.js" "shutdown": "node tools/shutdown.js"
}, },
"optionalDependencies": { "optionalDependencies": {
"@rollup/rollup-linux-x64-gnu": "^4.52.5" "@rollup/rollup-linux-x64-gnu": "^4.60.2"
} }
} }
+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", "name": "playlet-app",
"version": "0.43.7", "version": "0.44.9",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-app", "name": "playlet-app",
"version": "0.43.7" "version": "0.44.9"
} }
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-app", "name": "playlet-app",
"version": "0.43.7", "version": "0.44.9",
"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",
@@ -37,6 +37,7 @@ function GetLoadingMessagesFromCache() as object
if messagesFile = "" if messagesFile = ""
return invalid return invalid
end if end if
' bs:disable-next-line NO_PARSE_JSON
return ParseJson(messagesFile) return ParseJson(messagesFile)
end function end function
+2 -2
View File
@@ -2,8 +2,8 @@ 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=43 minor_version=44
build_version=00007 build_version=00009
ui_resolutions=hd ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p uri_resolution_autosub=$$RES$$,480p,720p,1080p
+1
View File
@@ -28,6 +28,7 @@ namespace Registry
if urlsJson = invalid if urlsJson = invalid
return invalid return invalid
end if end if
' bs:disable-next-line NO_PARSE_JSON
urls = ParseJson(urlsJson) urls = ParseJson(urlsJson)
return urls return urls
end function end function
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.43.7", "version": "0.44.9",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.43.7" "version": "0.44.9"
} }
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.43.7", "version": "0.44.9",
"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",
@@ -125,7 +125,7 @@ namespace DialogUtils
if hasMessageId if hasMessageId
messages = RegistryUtils.Read(RegistryUtils.MESSAGES) messages = RegistryUtils.Read(RegistryUtils.MESSAGES)
if not StringUtils.IsNullOrEmpty(messages) if not StringUtils.IsNullOrEmpty(messages)
messages = ParseJson(messages) messages = StringUtils.ParseJsonSafe(messages)
if IsAssociativeArray(messages) if IsAssociativeArray(messages)
savedMessageId = ValidString(messages["messageId"]) savedMessageId = ValidString(messages["messageId"])
if savedMessageId = messageId if savedMessageId = messageId
@@ -50,7 +50,7 @@ end function
function JobError(error as dynamic) as void function JobError(error as dynamic) as void
error = ErrorUtils.Format(error) error = ErrorUtils.Format(error)
LogError(error) LogError(`[${m.top.subtype}]${error}`)
callbackNode = JobGetCallbackNode() callbackNode = JobGetCallbackNode()
if callbackNode = invalid if callbackNode = invalid
return return
+10 -10
View File
@@ -145,11 +145,11 @@ function OnLineLogMonitorMemoryWarning(event as object, dateTime as object, logs
return return
end if end if
LogTelemetryEvent({ ' LogTelemetryEvent({
level: "warning" ' level: "warning"
message: line + `\nCurrentTime: ${m.eventThrottleTimer.TotalSeconds()}` ' message: line + `\nCurrentTime: ${m.eventThrottleTimer.TotalSeconds()}`
fingerprint: [message] ' fingerprint: [message]
}) ' })
end function end function
function OnLineLogDeviceInfoMemoryWarning(event as object, dateTime as object, logsFile as string, buffer as object) as void 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.FromAsciiString(line + `\n`)
buffer.AppendFile(logsFile) buffer.AppendFile(logsFile)
LogTelemetryEvent({ ' LogTelemetryEvent({
level: "warning" ' level: "warning"
message: line + `\nCurrentTime: ${m.eventThrottleTimer.TotalSeconds()}` ' message: line + `\nCurrentTime: ${m.eventThrottleTimer.TotalSeconds()}`
fingerprint: [message] ' fingerprint: [message]
}) ' })
end function end function
' Returns true if the event should be throttled ' Returns true if the event should be throttled
@@ -1,9 +1,10 @@
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/Types.bs"
namespace HomeScreenUtils namespace HomeScreenUtils
function GetFeed(feedFileName as string, preferences as object) as object function GetFeed(feedFileName as string, preferences as object) as object
feed = ParseJson(ReadAsciiFile(feedFileName)) feed = StringUtils.ParseJsonSafe(ReadAsciiFile(feedFileName))
for each item in feed for each item in feed
item.title = Tr(item.title) 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/Logging.bs"
import "pkg:/source/utils/MathUtils.bs" import "pkg:/source/utils/MathUtils.bs"
import "pkg:/source/utils/RemoteKeys.bs" import "pkg:/source/utils/RemoteKeys.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/Types.bs"
function Init() function Init()
m.homeLayout = {} 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 for each item in homeLayout
m.homeLayout[item.id] = item m.homeLayout[item.id] = item
end for end for
@@ -324,7 +324,7 @@ end function
function CanFetchWithCors(instance as string, testNode as object, cancellation as object) as void function CanFetchWithCors(instance as string, testNode as object, cancellation as object) as void
try try
url = `${instance}/api/v1/trending` url = `${instance}/api/v1/popular`
response = HttpClient.Get(url).NoCache().Cancellation(cancellation).Await() response = HttpClient.Get(url).NoCache().Cancellation(cancellation).Await()
if not response.IsSuccess() if not response.IsSuccess()
@@ -20,7 +20,7 @@ function Load() as void
end if end if
m.bookmarksString = bookmarksString m.bookmarksString = bookmarksString
bookmarks = ParseJson(bookmarksString) bookmarks = StringUtils.ParseJsonSafe(bookmarksString)
if bookmarks = invalid if bookmarks = invalid
LogWarn("Failed to parse bookmarks json") LogWarn("Failed to parse bookmarks json")
return return
@@ -82,6 +82,7 @@ class DashManifest
xml = new XmlObject() xml = new XmlObject()
xml.Comment(`Generated by Playlet - Video ID: ${metadata.videoId}`) xml.Comment(`Generated by Playlet - Video ID: ${metadata.videoId}`)
xml.Comment(`Parser: ${ValidString(metadata.parser)}`)
if xml.Node("MPD", { if xml.Node("MPD", {
"xmlns": "urn:mpeg:dash:schema:mpd:2011" "xmlns": "urn:mpeg:dash:schema:mpd:2011"
@@ -288,8 +289,13 @@ class DashManifest
"contentType": "audio" "contentType": "audio"
} }
if IsAssociativeArray(firstFormat.audioTrack) and IsString(firstFormat.audioTrack.languageCode) if IsAssociativeArray(firstFormat.audioTrack)
if IsString(firstFormat.audioTrack.languageCode)
adaptationSetAttributes["lang"] = 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 end if
' Hoist common attributes ' Hoist common attributes
@@ -496,11 +502,7 @@ class DashManifest
xml.Comment(`[ERROR] OTF stream has empty otfSegmentDurations for itag: ${stream.itag}`) xml.Comment(`[ERROR] OTF stream has empty otfSegmentDurations for itag: ${stream.itag}`)
end if end if
for each segment in segmentDurations for each segment in segmentDurations
sAttributes = { "d": segment.duration } xml.EmptyNode("S", segment)
if segment.repeatCount <> invalid
sAttributes["r"] = segment.repeatCount
end if
xml.EmptyNode("S", sAttributes)
end for end for
xml.End() xml.End()
end if end if
@@ -1,23 +1,23 @@
const PLAYLET_SUPPORT_SERVER = "https://playlet-v8556.ondigitalocean.app" const PLAYLET_SUPPORT_SERVER = "https://playlet-v8556.ondigitalocean.app"
const VIDEO_PLAYER_USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:139.0) Gecko/20100101 Firefox/139.0" const VIDEO_PLAYER_USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0"
const INNERTUBE_IOS_CLIENT_NAME = "5" const INNERTUBE_IOS_CLIENT_NAME = "5"
const INNERTUBE_IOS_CLIENT_VERSION = "20.39.4" const INNERTUBE_IOS_CLIENT_VERSION = "21.16.2"
const INNERTUBE_IOS_DEVICE_MODEL = "iPhone16,2" const INNERTUBE_IOS_DEVICE_MODEL = "iPhone16,2"
const INNERTUBE_IOS_OS_VERSION = "18.1" const INNERTUBE_IOS_OS_VERSION = "18.1"
const INNERTUBE_IOS_USER_AGENT = "com.google.ios.youtube/20.39.4 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X)" const INNERTUBE_IOS_USER_AGENT = "com.google.ios.youtube/21.16.2 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X)"
const INNERTUBE_WEB_BROWSER_NAME = "Chrome" const INNERTUBE_WEB_BROWSER_NAME = "Chrome"
const INNERTUBE_WEB_BROWSER_VERSION = "140.0.0.0" const INNERTUBE_WEB_BROWSER_VERSION = "147.0.0.0"
const INNERTUBE_WEB_CLIENT_NAME = "1" const INNERTUBE_WEB_CLIENT_NAME = "1"
const INNERTUBE_WEB_CLIENT_VERSION = "2.20250927.00.01" const INNERTUBE_WEB_CLIENT_VERSION = "2.20260424.01.00"
const INNERTUBE_WEB_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0" const INNERTUBE_WEB_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36"
const INNERTUBE_TV_BROWSER_NAME = "SamsungBrowser" const INNERTUBE_TV_BROWSER_NAME = "SamsungBrowser"
const INNERTUBE_TV_BROWSER_VERSION = "9.2" const INNERTUBE_TV_BROWSER_VERSION = "9.2"
const INNERTUBE_TV_CLIENT_NAME = "2" const INNERTUBE_TV_CLIENT_NAME = "2"
const INNERTUBE_TV_CLIENT_VERSION = "7.20251015.07.00" const INNERTUBE_TV_CLIENT_VERSION = "7.20260422.12.00"
const INNERTUBE_TV_DEVICE_MAKE = "Samsung" const INNERTUBE_TV_DEVICE_MAKE = "Samsung"
const INNERTUBE_TV_DEVICE_MODEL = "SmartTV" const INNERTUBE_TV_DEVICE_MODEL = "SmartTV"
const INNERTUBE_TV_OS_NAME = "Tizen" const INNERTUBE_TV_OS_NAME = "Tizen"
@@ -267,61 +267,6 @@ namespace InnertubeService
return Innertube.Search(query, options) return Innertube.Search(query, options)
end function 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 function GetHome(options = invalid as object) as object
return GetBrowseAuthenticatedPage("FEwhat_to_watch", options) return GetBrowseAuthenticatedPage("FEwhat_to_watch", options)
end function end function
@@ -338,12 +283,12 @@ namespace InnertubeService
return GetBrowseAuthenticatedPage("FEplaylist_aggregation", options) return GetBrowseAuthenticatedPage("FEplaylist_aggregation", options)
end function 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") cancellation = OptionUtils.Get(options, "cancellation")
accessToken = OptionUtils.Get(options, "accessToken") accessToken = OptionUtils.Get(options, "accessToken")
disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false) 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 if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken) request.Header("Authorization", "Bearer " + accessToken)
@@ -360,6 +305,7 @@ namespace InnertubeService
feeds = Innertube.ParseResponseDataForFeeds(response.Json(), { feeds = Innertube.ParseResponseDataForFeeds(response.Json(), {
response: response response: response
disableShorts: disableShorts disableShorts: disableShorts
browseId: browseId
}) })
result = { result = {
@@ -416,6 +362,7 @@ namespace InnertubeService
cancellation = OptionUtils.Get(options, "cancellation") cancellation = OptionUtils.Get(options, "cancellation")
accessToken = OptionUtils.Get(options, "accessToken") accessToken = OptionUtils.Get(options, "accessToken")
onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser") onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser")
cpn = OptionUtils.Get(options, "cpn")
videostatsPlaybackUrl = videostatsPlaybackUrl.replace("https://s.", "https://www.") videostatsPlaybackUrl = videostatsPlaybackUrl.replace("https://s.", "https://www.")
queryParams = UrlUtils.ParseQueryComponents(videostatsPlaybackUrl) queryParams = UrlUtils.ParseQueryComponents(videostatsPlaybackUrl)
@@ -423,8 +370,8 @@ namespace InnertubeService
queryParams["cbrver"] = INNERTUBE_TV_CLIENT_VERSION queryParams["cbrver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["cver"] = INNERTUBE_TV_CLIENT_VERSION queryParams["cver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["ver"] = "2" queryParams["ver"] = "2"
queryParams["cpn"] = InnertubeService.CreateClientPlaybackNonce() queryParams["cmt"] = "0"
queryParams["cmt"] = 0 queryParams["cpn"] = cpn
queryParams["final"] = "1" queryParams["final"] = "1"
videostatsPlaybackUrl = UrlUtils.SetQueryParams(videostatsPlaybackUrl, queryParams) videostatsPlaybackUrl = UrlUtils.SetQueryParams(videostatsPlaybackUrl, queryParams)
@@ -453,6 +400,7 @@ namespace InnertubeService
onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser") onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser")
timeStr = time.ToStr("%.3f") timeStr = time.ToStr("%.3f")
cpn = OptionUtils.Get(options, "cpn")
videostatsWatchtimeUrl = videostatsWatchtimeUrl.replace("https://s.", "https://www.") videostatsWatchtimeUrl = videostatsWatchtimeUrl.replace("https://s.", "https://www.")
queryParams = UrlUtils.ParseQueryComponents(videostatsWatchtimeUrl) queryParams = UrlUtils.ParseQueryComponents(videostatsWatchtimeUrl)
@@ -460,11 +408,11 @@ namespace InnertubeService
queryParams["cbrver"] = INNERTUBE_TV_CLIENT_VERSION queryParams["cbrver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["cver"] = INNERTUBE_TV_CLIENT_VERSION queryParams["cver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["ver"] = "2" queryParams["ver"] = "2"
queryParams["cpn"] = InnertubeService.CreateClientPlaybackNonce() queryParams["cpn"] = cpn
queryParams["cmt"] = 0 queryParams["cmt"] = "0"
queryParams["final"] = "1"
queryParams["st"] = timeStr queryParams["st"] = timeStr
queryParams["et"] = timeStr queryParams["et"] = timeStr
queryParams["final"] = "1"
videostatsWatchtimeUrl = UrlUtils.SetQueryParams(videostatsWatchtimeUrl, queryParams) videostatsWatchtimeUrl = UrlUtils.SetQueryParams(videostatsWatchtimeUrl, queryParams)
request = HttpClient.Get(videostatsWatchtimeUrl) request = HttpClient.Get(videostatsWatchtimeUrl)
@@ -521,7 +469,7 @@ namespace InnertubeService
return response.Json() return response.Json()
end if end if
result = Innertube.ParseChannelPageResponseData(response.Json(), response) result = Innertube.ParseChannelPageResponseData(channelId, response.Json(), response)
if result.authorId = invalid and result.error = invalid if result.authorId = invalid and result.error = invalid
result["authorId"] = channelId result["authorId"] = channelId
end if end if
@@ -663,7 +611,7 @@ namespace InnertubeService
return response.Json() return response.Json()
end if end if
result = Innertube.ParsePlaylistPageResponseData(response.Json(), response) result = Innertube.ParsePlaylistPageResponseData(playlistId, response.Json(), response)
if result.playlistId = invalid and result.error = invalid if result.playlistId = invalid and result.error = invalid
result["playlistId"] = playlistId result["playlistId"] = playlistId
@@ -86,6 +86,7 @@ namespace Innertube
"richGridRenderer": ParseRichGridRenderer "richGridRenderer": ParseRichGridRenderer
"richItemRenderer": ParseRichItemRenderer "richItemRenderer": ParseRichItemRenderer
"feedFilterChipBarRenderer": ParseFeedFilterChipBarRenderer "feedFilterChipBarRenderer": ParseFeedFilterChipBarRenderer
"chipBarViewModel": ParseChipBarViewModel
"continuationItemRenderer": ParseContinuationItemRenderer "continuationItemRenderer": ParseContinuationItemRenderer
"appendContinuationItemsAction": ParseAppendContinuationItemsAction "appendContinuationItemsAction": ParseAppendContinuationItemsAction
"reloadContinuationItemsCommand": ParseReloadContinuationItemsCommand "reloadContinuationItemsCommand": ParseReloadContinuationItemsCommand
@@ -103,9 +104,8 @@ namespace Innertube
' Ignored nodes: ' Ignored nodes:
' TODO:P2 handle navigateAction - which are usually a redirect ' TODO:P2 handle navigateAction - which are usually a redirect
' "navigateAction": ParseNotImplemented ' "navigateAction": ParseNotImplemented
' TODO:P2 radioRenderer seems like a Mix https://github.com/iBicha/playlet/issues/709
"radioRenderer": ParseRadioRenderer "radioRenderer": ParseRadioRenderer
' "compactRadioRenderer": ParseNotImplemented "compactRadioRenderer": ParseCompactRadioRenderer
' TODO:P2 A carousel of videos, found on the home tab of a channel. ' TODO:P2 A carousel of videos, found on the home tab of a channel.
' Should probably be parsed. ' Should probably be parsed.
' "carouselItemRenderer": ParseNotImplemented ' "carouselItemRenderer": ParseNotImplemented
@@ -164,6 +164,7 @@ namespace Innertube
"emergencyOneboxRenderer": ParseNotImplemented "emergencyOneboxRenderer": ParseNotImplemented
' Suicide & crisis lifeline, within search ' Suicide & crisis lifeline, within search
"searchFrictionViewModel": ParseNotImplemented "searchFrictionViewModel": ParseNotImplemented
"shoppingTimelyShelfViewModel": ParseNotImplemented
"backstagePostRenderer": ParseNotImplemented "backstagePostRenderer": ParseNotImplemented
"backstagePostThreadRenderer": ParseNotImplemented "backstagePostThreadRenderer": ParseNotImplemented
"counterfactualRenderer": ParseNotImplemented "counterfactualRenderer": ParseNotImplemented
@@ -252,6 +253,15 @@ namespace Innertube
context.currentFeed.sortOptions = sortOptions context.currentFeed.sortOptions = sortOptions
end if end if
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"] return nodeData["contents"]
end function end function
@@ -277,6 +287,17 @@ namespace Innertube
end if end if
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.title
' TODO: handle shelfRenderer.headerRenderer.shelfHeaderRenderer.avatarLockup.avatarLockupRenderer.title ' TODO: handle shelfRenderer.headerRenderer.shelfHeaderRenderer.avatarLockup.avatarLockupRenderer.title
return nodeData["content"] return nodeData["content"]
@@ -1025,6 +1046,36 @@ namespace Innertube
return invalid return invalid
end function 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 function ParseGridShelfViewModel(nodeData as object, _context as object) as object
return nodeData["contents"] return nodeData["contents"]
end function end function
@@ -1400,6 +1451,10 @@ namespace Innertube
return TileRendererTypeChannel(nodeData, context) return TileRendererTypeChannel(nodeData, context)
else if contentType = "TILE_CONTENT_TYPE_EDU" else if contentType = "TILE_CONTENT_TYPE_EDU"
' Not implemented yet - https://github.com/iBicha/playlet/issues/751 ' 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 end if
Warning(`Unknown content type: ${contentType}`, nodeData, context) Warning(`Unknown content type: ${contentType}`, nodeData, context)
@@ -1666,13 +1721,64 @@ namespace Innertube
end function end function
function ParseRichGridRenderer(nodeData as object, context as object) as object 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 if feedFilterChipBarRenderer <> invalid
ParseFeedFilterChipBarRenderer(feedFilterChipBarRenderer, context) ParseFeedFilterChipBarRenderer(feedFilterChipBarRenderer, context)
else if chipBarViewModel <> invalid
ParseChipBarViewModel(chipBarViewModel, context)
end if end if
return nodeData["contents"] return nodeData["contents"]
end function 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 function ParseRichItemRenderer(nodeData as object, _context as object) as object
return nodeData["content"] return nodeData["content"]
end function end function
@@ -1893,6 +1999,8 @@ namespace Innertube
function ParseCompactMovieRenderer(nodeData as object, context as object) as object function ParseCompactMovieRenderer(nodeData as object, context as object) as object
videoId = nodeData["videoId"] videoId = nodeData["videoId"]
if not IsString(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) Warning("Invalid videoId in compactMovieRenderer", nodeData, context)
return invalid return invalid
end if end if
@@ -0,0 +1,195 @@
import "pkg:/components/Services/Innertube/Context.bs"
namespace Innertube
' OTF (On-The-Fly?) segment info retrieval and parsing
' When innertube returns adaptive formats, sometimes there's a property
' attached to the object: adaptiveFormats[].type = "FORMAT_STREAM_TYPE_OTF".
' When that happens, the segment info (durations, repeat counts) is not included
' in the response. Instead, they are appended to the media init segment itself.
' The init segment would contain video init information, which is binary, appended
' with a text section in this format:
' `Segment-Count: 731\r\n` +
' `Segment-Durations-Ms: 5333,5334,5333(r=1),5334,5333(r=1),\r\n`
' Because of this, the init segment needs to be downloaded to a tmp file, loaded in
' a byte array, converted to hex, and parsed. Loading the file to ascii string directly
' would not work because it would be truncated at the first null byte.
const OTF_MAX_REQUEST_COUNT = 8
function OTFGetSegmentInfo(adaptiveFormats as object, client as Innertube.ClientType, cancellation as object) as void
errors = {
message: ""
attachments: []
}
formatsToProcess = []
for i = 0 to adaptiveFormats.Count() - 1
formatsToProcess.Push({
format: adaptiveFormats[i]
filePath: `tmp:/otf_segments/${i}.bin`
})
end for
pendingFormats = []
requestHeaders = Innertube.CreateHeaders(client)
requestHeaders["origin"] = "https://www.youtube.com"
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")
while true
while formatsToProcess.Count() > 0 and pendingFormats.Count() < OTF_MAX_REQUEST_COUNT
formatToProcess = formatsToProcess.Pop()
request = OTFMakeSegmentInfoRequest(formatToProcess.format, formatToProcess.filePath, requestHeaders, errors, cancellation)
if request <> invalid
formatToProcess.request = request
pendingFormats.Push(formatToProcess)
end if
end while
if pendingFormats.Count() = 0
exit while
end if
pendingFormat = pendingFormats.Shift()
' returns false if processing should stop (e.g., cancelled)
if not OTFProcessPendingFormat(pendingFormat.format, pendingFormat.request, pendingFormat.filePath, segmentDurationsRegex, errors)
exit while
end if
end while
fs.Delete("tmp:/otf_segments")
if not StringUtils.IsNullOrEmpty(errors.message) or errors.attachments.Count() > 0
LogTelemetryEvent({
level: "error"
message: `OTF errors during segment info retrieval: \n${errors.message}`
fingerprint: ["OTF errors during segment info retrieval"]
attachments: errors.attachments
})
end if
end function
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`
return invalid
end if
queryComponents = UrlUtils.ParseQueryComponents(url)
queryComponents["rn"] = "0"
queryComponents["sq"] = "0"
otfUrl = UrlUtils.SetQueryParams(url, queryComponents)
request = HttpClient.Get(otfUrl)
request.Headers(requestHeaders)
request.ToFile(filePath)
request.Cancellation(cancellation)
request.Send()
return request
end function
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()
return false
end if
if not response.IsSuccess()
errors.message += `Failed to get segment info for itag ${format.itag}: ${response.ErrorMessage()}\n`
return true
end if
segmentDurations = OTFParseFileForSegmentDurations(filePath, segmentDurationsRegex, errors)
if segmentDurations = invalid
errors.message += `Failed to parse segment durations for itag ${format.itag}.\n`
errors.message += `Headers: ${ToString(response.Headers())}\n`
return true
end if
format["otfSegmentDurations"] = segmentDurations
return true
end function
function OTFParseFileForSegmentDurations(filePath as string, segmentDurationsRegex as object, errors as object) as dynamic
buffer = CreateObject("roByteArray")
buffer.FromAsciiString("Segment-Durations-Ms:")
startMarkerHex = buffer.ToHexString()
buffer.FromAsciiString(`\r\n`)
endMarkerHex = buffer.ToHexString()
if not buffer.ReadFile(filePath)
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 filePath ${filePath}.\n`
errors.attachments.Push({
filename: filePath
content_type: "plain/text"
data: contentHex
})
return invalid
end if
endIndex = contentHex.InStr(startIndex, endMarkerHex)
if endIndex = -1
errors.message += `End marker not found in filePath ${filePath}.\n`
errors.attachments.Push({
filename: filePath
content_type: "plain/text"
data: contentHex
})
return invalid
end if
segmentDurationsMsHex = contentHex.Mid(startIndex + startMarkerHex.len(), endIndex - (startIndex + startMarkerHex.len()))
buffer.FromHexString(segmentDurationsMsHex)
segmentDurationsMs = buffer.ToAsciiString()
matches = segmentDurationsRegex.MatchAll(segmentDurationsMs)
if not IsArray(matches) or matches.Count() = 0
errors.message += `No segment duration matches found in filePath ${filePath}.\n`
errors.attachments.Push({
filename: filePath
content_type: "plain/text"
data: contentHex
})
return invalid
end if
segmentDurations = CreateObject("roArray", matches.Count(), false)
for i = 0 to matches.Count() - 1
match = matches[i]
segment = {}
' We set duration and repeatCount to "d" and "r" so that we can feed
' them directly into the DashManifest generation code.
if match.Count() >= 2
segment["d"] = match[1].ToInt()
end if
if match.Count() >= 3
segment["r"] = match[2].ToInt()
end if
segmentDurations[i] = segment
end for
return segmentDurations
end function
end namespace
@@ -44,7 +44,7 @@ namespace Innertube
return context.feeds return context.feeds
end function 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 if responseData = invalid
return { return {
error: "Invalid response data" error: "Invalid response data"
@@ -63,6 +63,9 @@ namespace Innertube
author = ObjectUtils.Dig(responseData, ["header", "pageHeaderRenderer", "pageTitle"]) author = ObjectUtils.Dig(responseData, ["header", "pageHeaderRenderer", "pageTitle"])
end if end if
authorId = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "externalId"]) authorId = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "externalId"])
if StringUtils.IsNullOrEmpty(authorId)
authorId = browseId
end if
thumbnails = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "avatar", "thumbnails"]) thumbnails = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "avatar", "thumbnails"])
if thumbnails = invalid if thumbnails = invalid
@@ -149,6 +152,7 @@ namespace Innertube
response: response response: response
"currentAuthor": author "currentAuthor": author
"currentAuthorId": authorId "currentAuthorId": authorId
browseId: browseId
}) })
if feeds.Count() > 0 if feeds.Count() > 0
items = ValidArray(feeds[0].items) items = ValidArray(feeds[0].items)
@@ -183,7 +187,7 @@ namespace Innertube
return channel return channel
end function 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 if responseData = invalid
return { return {
error: "Invalid response data" error: "Invalid response data"
@@ -251,13 +255,16 @@ namespace Innertube
end if end if
end if end if
if StringUtils.IsNullOrEmpty(playlistId)
playlistId = browseId
end if
playlist = { playlist = {
"playlistId": playlistId
"videoCount": videoCount "videoCount": videoCount
"videos": [] "videos": []
} }
if playlistId <> invalid
playlist["playlistId"] = playlistId
end if
if title <> invalid if title <> invalid
playlist["title"] = title playlist["title"] = title
end if end if
@@ -279,6 +286,7 @@ namespace Innertube
feeds = ParseResponseDataForFeeds(responseData, { feeds = ParseResponseDataForFeeds(responseData, {
response: response response: response
browseId: browseId
}) })
if feeds.Count() > 0 if feeds.Count() > 0
playlist["videos"] = ValidArray(feeds[0].items) playlist["videos"] = ValidArray(feeds[0].items)
@@ -1,5 +1,6 @@
import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/components/Services/Innertube/NodesParser.bs" import "pkg:/components/Services/Innertube/NodesParser.bs"
import "pkg:/components/Services/Innertube/OTFSegmentInfo.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"
@@ -12,8 +13,6 @@ 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")
doSignatureTimestamp = ValidBool(OptionUtils.Get(options, "signatureTimestamp"))
cpn = InnertubeService.CreateClientPlaybackNonce() cpn = InnertubeService.CreateClientPlaybackNonce()
useAccessToken = client = Innertube.ClientType.TV and not StringUtils.IsNullOrEmpty(accessToken) useAccessToken = client = Innertube.ClientType.TV and not StringUtils.IsNullOrEmpty(accessToken)
@@ -51,13 +50,10 @@ namespace Innertube
"contentCheckOk": true "contentCheckOk": true
} }
signatureTimestamp = invalid
if doSignatureTimestamp
signatureTimestamp = GetSignatureTimestamp(cancellation) signatureTimestamp = GetSignatureTimestamp(cancellation)
if signatureTimestamp <> invalid if signatureTimestamp <> invalid
payload["playbackContext"]["contentPlaybackContext"]["signatureTimestamp"] = signatureTimestamp payload["playbackContext"]["contentPlaybackContext"]["signatureTimestamp"] = signatureTimestamp
end if end if
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))
@@ -121,6 +117,7 @@ namespace Innertube
formats = TransformFormats(formats) formats = TransformFormats(formats)
parsedResponse["type"] = "video" parsedResponse["type"] = "video"
parsedResponse["parser"] = "playlet"
parsedResponse["videoId"] = videoDetails["videoId"] parsedResponse["videoId"] = videoDetails["videoId"]
parsedResponse["videoThumbnails"] = videoDetails["thumbnail"]["thumbnails"] parsedResponse["videoThumbnails"] = videoDetails["thumbnail"]["thumbnails"]
parsedResponse["storyboards"] = ParseStoryboards(payload, lengthSeconds) parsedResponse["storyboards"] = ParseStoryboards(payload, lengthSeconds)
@@ -168,7 +165,7 @@ namespace Innertube
if isOTF if isOTF
LogDebug("Fetching OTF segment info") LogDebug("Fetching OTF segment info")
GetOTFSegmentInfo(adaptiveFormats, client, cancellation) OTFGetSegmentInfo(adaptiveFormats, client, cancellation)
end if end if
return parsedResponse return parsedResponse
@@ -315,6 +312,7 @@ namespace Innertube
end if end if
captions = [] captions = []
autoCaptions = []
for each track in tracks for each track in tracks
if not IsAssociativeArray(track) if not IsAssociativeArray(track)
continue for continue for
@@ -340,13 +338,22 @@ namespace Innertube
label = ParseText(track["name"]) label = ParseText(track["name"])
captions.Push({ thisCaption = {
"label": label "label": label
"language_code": languageCode "language_code": languageCode
"url": baseUrl "url": baseUrl
}) }
if track["kind"] = "asr"
autoCaptions.Push(thisCaption)
continue for
end if
captions.Push(thisCaption)
end for end for
' Put automatically generated captions at the end so human-generated ones take priority
captions.Append(autoCaptions)
return captions return captions
end function end function
@@ -442,7 +449,7 @@ namespace Innertube
LogDebug(`ReadAsciiFile("tmp:/sts_cache.json")`) LogDebug(`ReadAsciiFile("tmp:/sts_cache.json")`)
cache = ReadAsciiFile("tmp:/sts_cache.json") cache = ReadAsciiFile("tmp:/sts_cache.json")
if not StringUtils.IsNullOrEmpty(cache) if not StringUtils.IsNullOrEmpty(cache)
json = ParseJson(cache) json = StringUtils.ParseJsonSafe(cache)
return json["sts"] return json["sts"]
end if end if
@@ -547,8 +554,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"] = decipheredFmt["url"]
end for end for
decipheredAdaptiveFormats = json["adaptiveFormats"] decipheredAdaptiveFormats = json["adaptiveFormats"]
@@ -562,11 +568,34 @@ 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"] = decipheredFmt["url"] fmt["url"] = ResetUrlClientVersion(decipheredFmt["url"])
end for end for
return invalid return invalid
end function end function
' 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,
' but it makes sense to keep it consistent.
function ResetUrlClientVersion(url as dynamic) as dynamic
if StringUtils.IsNullOrEmpty(url)
return url
end if
queryComponents = UrlUtils.ParseQueryComponents(url)
client = ValidString(queryComponents["c"])
if client = "TVHTML5"
queryComponents["cver"] = INNERTUBE_TV_CLIENT_VERSION
else if client = "IOS"
queryComponents["cver"] = INNERTUBE_IOS_CLIENT_VERSION
else if client = "WEB"
queryComponents["cver"] = INNERTUBE_WEB_CLIENT_VERSION
else
return url
end if
return UrlUtils.SetQueryParams(url, queryComponents)
end function
function ParseIsLoggedIn(payload as object) as boolean function ParseIsLoggedIn(payload as object) as boolean
trackingParams = ObjectUtils.Dig(payload, ["responseContext", "serviceTrackingParams"]) trackingParams = ObjectUtils.Dig(payload, ["responseContext", "serviceTrackingParams"])
if not IsArray(trackingParams) if not IsArray(trackingParams)
@@ -616,6 +645,10 @@ namespace Innertube
return true return true
end if end if
if ValidBool(ObjectUtils.Dig(payload, ["videoDetails", "isPostLiveDvr"]))
return false
end if
adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"])) adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"]))
if FormatsHaveLiveStreamingData(adaptiveFormats) if FormatsHaveLiveStreamingData(adaptiveFormats)
return true return true
@@ -695,7 +728,13 @@ namespace Innertube
headers = response.Headers() headers = response.Headers()
if not headers.DoesExist("X-Head-Time-Millis") or not headers.DoesExist("X-Head-Seqnum") 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 end if
durationMs = ValidString(headers["X-Head-Time-Millis"]).ToInt() durationMs = ValidString(headers["X-Head-Time-Millis"]).ToInt()
@@ -709,149 +748,4 @@ namespace Innertube
end if end if
end function end function
function GetOTFSegmentInfo(adaptiveFormats as object, client as Innertube.ClientType, cancellation as object) as void
requests = CreateObject("roArray", adaptiveFormats.Count(), false)
requestHeaders = Innertube.CreateHeaders(client)
requestHeaders["origin"] = "https://www.youtube.com"
requestHeaders["referer"] = "https://www.youtube.com"
requestHeaders["DNT"] = "?1"
for i = 0 to adaptiveFormats.Count() - 1
format = adaptiveFormats[i]
if format.isTypeOTF <> true
continue for
end if
url = format.url
if StringUtils.IsNullOrEmpty(url)
LogError("GetOTFSegmentInfo: URL is empty for itag", format.itag)
continue for
end if
queryComponents = UrlUtils.ParseQueryComponents(url)
queryComponents["rn"] = "0"
queryComponents["sq"] = "0"
otfUrl = UrlUtils.SetQueryParams(url, queryComponents)
request = HttpClient.Get(otfUrl)
request.Headers(requestHeaders)
request.TryCount(2)
request.Cancellation(cancellation)
request.Send()
requests[i] = request
end for
for i = 0 to requests.Count() - 1
request = requests[i]
if request = invalid
continue for
end if
format = adaptiveFormats[i]
response = request.Await()
if response.IsCancelled()
return
end if
if not response.IsSuccess()
LogErrorNoTelemetry("Failed to fetch OTF segment info for itag", format.itag, response.ErrorMessage())
LogTelemetryEvent({
level: "error"
message: `Failed to fetch OTF segment info for itag ${format.itag}`
fingerprint: ["OTF Fetch Error"]
attachments: [{
filename: "otf.txt"
content_type: "plain/text"
data: response.ErrorMessage()
}]
})
continue for
end if
responseText = response.Text()
segmentDurationsMs = StringUtils.GetBetween(responseText, "Segment-Durations-Ms:", `\r\n`)
if StringUtils.IsNullOrEmpty(segmentDurationsMs)
LogErrorNoTelemetry("Failed to extract Segment-Durations-Ms from OTF stream for itag", format.itag)
LogTelemetryEvent({
level: "error"
message: `Failed to extract Segment-Durations-Ms from OTF stream for itag ${format.itag}`
fingerprint: ["OTF Missing Segment Durations"]
attachments: [{
filename: "otf.txt"
content_type: "plain/text"
data: responseText
}, {
filename: "headers.json"
content_type: "application/json"
data: FormatJson(response.Headers())
}]
})
continue for
end if
segmentDurationStrings = segmentDurationsMs.Split(",")
segmentDurations = []
for each segmentDurationString in segmentDurationStrings
trimmedSegmentDuration = segmentDurationString.Trim()
if trimmedSegmentDuration.Len() = 0
continue for
end if
repeatCount = invalid
repeatCountString = StringUtils.GetBetween(trimmedSegmentDuration, "(r=", ")")
if not StringUtils.IsNullOrEmpty(repeatCountString)
repeatCount = repeatCountString.ToInt()
end if
duration = trimmedSegmentDuration.ToInt()
if duration <= 0
LogErrorNoTelemetry("Invalid OTF segment duration parsed", trimmedSegmentDuration, "for itag", format.itag)
LogTelemetryEvent({
level: "error"
message: `Invalid OTF segment duration parsed: ${trimmedSegmentDuration} for itag ${format.itag}`
fingerprint: ["OTF Invalid Segment Duration"]
attachments: [{
filename: "otf.txt"
content_type: "plain/text"
data: responseText
}, {
filename: "headers.json"
content_type: "application/json"
data: FormatJson(response.Headers())
}]
})
continue for
end if
segmentDurations.Push({
duration: duration
repeatCount: repeatCount
})
end for
format["otfSegmentDurations"] = segmentDurations
if segmentDurations.Count() = 0
LogErrorNoTelemetry("No OTF segment durations found for itag", format.itag)
LogTelemetryEvent({
level: "error"
message: `No OTF segment durations found for itag ${format.itag}`
fingerprint: ["OTF No Segment Durations"]
attachments: [{
filename: "otf.txt"
content_type: "plain/text"
data: responseText
}, {
filename: "headers.json"
content_type: "application/json"
data: FormatJson(response.Headers())
}]
})
end if
end for
end function
end namespace end namespace
@@ -87,7 +87,7 @@ namespace Innertube
text = response.Text() text = response.Text()
text = text.Replace(`)]}'`, "") text = text.Replace(`)]}'`, "")
parsed = ParseJson(text) parsed = StringUtils.ParseJsonSafe(text)
if not IsArray(parsed) or parsed.Count() < 2 if not IsArray(parsed) or parsed.Count() < 2
return { return {
error: "Failed to parse search suggestions" error: "Failed to parse search suggestions"
@@ -46,7 +46,7 @@ namespace Innertube
text = response.Text() text = response.Text()
text = text.Replace(`)]}'`, "") text = text.Replace(`)]}'`, "")
json = ParseJson(text) json = StringUtils.ParseJsonSafe(text)
if json = invalid if json = invalid
return { return {
"error": "Failed to parse session data: " + text "error": "Failed to parse session data: " + text
@@ -78,7 +78,7 @@ namespace Innertube
return invalid return invalid
end if end if
sessionData = ParseJson(sessionData) sessionData = StringUtils.ParseJsonSafe(sessionData)
if sessionData = invalid if sessionData = invalid
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA) RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
return invalid return invalid
@@ -1,7 +1,7 @@
import "InvidiousService.bs" import "InvidiousService.bs"
function Init() 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) m.service = new Invidious.InvidiousService(m.top)
end function end function
@@ -698,7 +698,7 @@ namespace Invidious
end function end function
function VerifyTokenScope(token as string) as boolean function VerifyTokenScope(token as string) as boolean
tokenObject = ParseJson(token) tokenObject = StringUtils.ParseJsonSafe(token)
if tokenObject = invalid if tokenObject = invalid
LogWarn("Failed to json parse token:", token) LogWarn("Failed to json parse token:", token)
return false return false
@@ -68,6 +68,7 @@ class LoungeApi
commandHandlers[COMMAND_TYPE_GRACEFUL_RECONNECT] = m.HandleIgnoreCommand commandHandlers[COMMAND_TYPE_GRACEFUL_RECONNECT] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_GET_RECEIVER_STATUS] = m.HandleIgnoreCommand commandHandlers[COMMAND_TYPE_GET_RECEIVER_STATUS] = m.HandleIgnoreCommand
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_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
@@ -211,7 +212,7 @@ class LoungeApi
text = text.Mid(text.instr(`\n`) + 1) text = text.Mid(text.instr(`\n`) + 1)
messagesToSend = [] messagesToSend = []
commands = ParseJson(text) commands = StringUtils.ParseJsonSafe(text)
m.ProcessCommands(commands, messagesToSend) m.ProcessCommands(commands, messagesToSend)
m.SendMessages(messagesToSend) m.SendMessages(messagesToSend)
return true return true
@@ -267,7 +268,7 @@ class LoungeApi
payloadSize = chunk.Left(newLineIndex).trim() payloadSize = chunk.Left(newLineIndex).trim()
payloadSize = payloadSize.ToInt() payloadSize = payloadSize.ToInt()
payload = chunk.Mid(newLineIndex + 1, payloadSize) payload = chunk.Mid(newLineIndex + 1, payloadSize)
commands = ParseJson(payload) commands = StringUtils.ParseJsonSafe(payload)
m.ProcessCommands(commands, messagesToSend) m.ProcessCommands(commands, messagesToSend)
chunk = chunk.Mid(newLineIndex + payloadSize + 1) chunk = chunk.Mid(newLineIndex + payloadSize + 1)
newLineIndex = chunk.InStr(`\n`) newLineIndex = chunk.InStr(`\n`)
@@ -324,9 +325,16 @@ class LoungeApi
LogInfo(commandIndex, commandType) LogInfo(commandIndex, commandType)
m[handler](commandIndex, commandType, commandArgs, messagesToSend) m[handler](commandIndex, commandType, commandArgs, messagesToSend)
else 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 #if DEBUG
throw `Unknown command type: ${commandType} command: ${ToString(command)}` throw message
#end if #end if
end if end if
end for end for
@@ -368,7 +376,7 @@ class LoungeApi
if not IsString(devices) if not IsString(devices)
return return
end if end if
devices = ParseJson(devices) devices = StringUtils.ParseJsonSafe(devices)
if devices = invalid if devices = invalid
return return
end if end if
@@ -610,7 +618,7 @@ class LoungeApi
RegistryUtils.Delete(RegistryUtils.LAST_LOUNGE_DATA) RegistryUtils.Delete(RegistryUtils.LAST_LOUNGE_DATA)
loungeData = ParseJson(loungeData) loungeData = StringUtils.ParseJsonSafe(loungeData)
if not IsAssociativeArray(loungeData) if not IsAssociativeArray(loungeData)
LogWarn("Can't disconnect from lounge. Invalid data:", loungeData) LogWarn("Can't disconnect from lounge. Invalid data:", loungeData)
return return
@@ -30,6 +30,7 @@ const COMMAND_TYPE_GET_DISCOVERT_DEVICE_ID = "getDiscoveryDeviceId"
const COMMAND_TYPE_GRACEFUL_RECONNECT = "gracefulReconnect" const COMMAND_TYPE_GRACEFUL_RECONNECT = "gracefulReconnect"
const COMMAND_TYPE_GET_RECEIVER_STATUS = "getReceiverStatus" 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"
' 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"
@@ -86,7 +86,7 @@ namespace LoungeVideoQueue
' - eventDetails is of the form {"eventType":"VIDEO_REMOVED","videoId":"<videoId>"} ' - eventDetails is of the form {"eventType":"VIDEO_REMOVED","videoId":"<videoId>"}
eventDetails = playlistData[FIELD_EVENT_DETAILS] eventDetails = playlistData[FIELD_EVENT_DETAILS]
if IsString(eventDetails) if IsString(eventDetails)
eventDetails = ParseJson(eventDetails) eventDetails = StringUtils.ParseJsonSafe(eventDetails)
end if end if
if eventDetails <> invalid and eventDetails["eventType"] = "VIDEO_ADDED" if eventDetails <> invalid and eventDetails["eventType"] = "VIDEO_ADDED"
eventVideoId = eventDetails[FIELD_VIDEO_ID] eventVideoId = eventDetails[FIELD_VIDEO_ID]
@@ -21,7 +21,7 @@ function Init()
end function end function
function LoadPreferencesFile() function LoadPreferencesFile()
m.top.prefsModel = ParseJson(ReadAsciiFile("libpkg:/config/preferences.json5")) m.top.prefsModel = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/preferences.json5"))
end function end function
function AddNodeFields() function AddNodeFields()
@@ -60,7 +60,7 @@ function LoadUserPreferencesFromRegistry()
if userPrefs = invalid if userPrefs = invalid
userPrefs = {} userPrefs = {}
else else
userPrefs = ParseJson(userPrefs) userPrefs = StringUtils.ParseJsonSafe(userPrefs)
end if end if
' Step 2: Migrate existing preferences to new format (if needed) ' 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) if not StringUtils.IsNullOrEmpty(instances)
currentInstance = userPrefs["invidious.instance"] currentInstance = userPrefs["invidious.instance"]
if StringUtils.IsNullOrEmpty(currentInstance) if StringUtils.IsNullOrEmpty(currentInstance)
instances = ParseJson(instances) instances = StringUtils.ParseJsonSafe(instances)
if IsArray(instances) and instances.Count() > 0 if IsArray(instances) and instances.Count() > 0
instance = instances[0] instance = instances[0]
if not StringUtils.IsNullOrEmpty(instance) if not StringUtils.IsNullOrEmpty(instance)
@@ -162,6 +162,20 @@ function MigrateExistingPreferences(userPrefs as object) as boolean
isDirty = true isDirty = true
end if 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) ' TODO:P2 handle case where saved preferences version is higher than current version (e.g. user downgraded)
#if DEBUG #if DEBUG
@@ -5,7 +5,7 @@
user prefs saved need to be migrated. If the version is less than the user prefs saved need to be migrated. If the version is less than the
current version, a migration is needed. 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="prefsModel" type="array" />
<field id="preferenceFields" type="assocarray" /> <field id="preferenceFields" type="assocarray" />
<function name="GetUserPreferences" /> <function name="GetUserPreferences" />
@@ -31,7 +31,7 @@ function LoadProfilesFromRegistry()
currentProfile: invalid currentProfile: invalid
} }
else else
userProfiles = ParseJson(userProfiles) userProfiles = StringUtils.ParseJsonSafe(userProfiles)
end if end if
' Step 2: Migrate existing profiles to new format (if needed) ' Step 2: Migrate existing profiles to new format (if needed)
@@ -98,7 +98,7 @@ function MigrateExistingProfiles(userProfiles as object) as boolean
return false return false
end if end if
authToken = ParseJson(tokenPayload) authToken = StringUtils.ParseJsonSafe(tokenPayload)
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN) RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
if authToken = invalid or authToken.instance = invalid or authToken.token = invalid or authToken.username = invalid if authToken = invalid or authToken.instance = invalid or authToken.token = invalid or authToken.username = invalid
@@ -55,7 +55,7 @@ namespace SearchHistoryUtils
return [] return []
end if end if
history = ParseJson(history) history = StringUtils.ParseJsonSafe(history)
if not IsArray(history) if not IsArray(history)
return [] return []
end if end if
@@ -9,7 +9,7 @@ namespace SponsorBlock
class SponsorBlockService class SponsorBlockService
function new() function new()
' TODO:P2 this is being read and parsed on every skipped segment. It should be cached. ' 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 end function
function GetCategories() as object function GetCategories() as object
@@ -65,33 +65,11 @@ function ExecuteJob() as void
}) })
if not response.success if not response.success
if response.error = Invidious.ERROR_NOT_AUTHENTICATED if RemoveSingleFailedRow(response.error, feedSource, feedSources, feedContentNode)
if feedSources.Count() = 1
parent = feedContentNode.getParent()
if parent <> invalid
parent.removeChild(feedContentNode)
end if
JobSuccess() JobSuccess()
return return
end if 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
end if
feedSource.state.loadState = FeedLoadState.Error feedSource.state.loadState = FeedLoadState.Error
feedSources[feedSourcesIndex] = feedSource feedSources[feedSourcesIndex] = feedSource
feedContentNode.feedSources = feedSources feedContentNode.feedSources = feedSources
@@ -243,6 +221,32 @@ function DeduplicateAppendAuthPlaylists(feedContentNode as object, itemNodes as
return nodesToAdd.Count() return nodesToAdd.Count()
end function 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 function HandleFeedLoadErrorDialog(error as object, isCancelled as boolean, rowList as object) as void
error = ErrorUtils.Format(error) error = ErrorUtils.Format(error)
if isCancelled if isCancelled
@@ -11,6 +11,7 @@ function ExecuteJob() as void
authToken = input.authToken authToken = input.authToken
profileType = input.profileType profileType = input.profileType
playbackTrackingUrls = input.playbackTrackingUrls playbackTrackingUrls = input.playbackTrackingUrls
cpn = input.cpn
cancellation = JobGetCancellation() cancellation = JobGetCancellation()
@@ -43,9 +44,14 @@ function ExecuteJob() as void
return return
end if end if
if StringUtils.IsNullOrEmpty(cpn)
cpn = InnertubeService.CreateClientPlaybackNonce()
end if
markedAsWatched = InnertubeService.AuthMarkVideoWatched(playbackTrackingUrls.videostatsPlaybackUrl, { markedAsWatched = InnertubeService.AuthMarkVideoWatched(playbackTrackingUrls.videostatsPlaybackUrl, {
accessToken: authToken.token accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken onBehalfOfUser: authToken.activeIdentifyToken
cpn: cpn
cancellation: cancellation cancellation: cancellation
}) })
if not markedAsWatched if not markedAsWatched
@@ -93,6 +99,7 @@ function ExecuteJob() as void
success = InnertubeService.AuthMarkVideoWatchTime(watchTime, playbackTrackingUrls.videostatsWatchtimeUrl, { success = InnertubeService.AuthMarkVideoWatchTime(watchTime, playbackTrackingUrls.videostatsWatchtimeUrl, {
accessToken: authToken.token accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken onBehalfOfUser: authToken.activeIdentifyToken
cpn: cpn
' TODO:P1 if we pass cancellation here, http client will remove scoped ' TODO:P1 if we pass cancellation here, http client will remove scoped
' observer, which is stored on the current node. ' observer, which is stored on the current node.
' This requires an extra observer node to be independent. ' This requires an extra observer node to be independent.
@@ -61,7 +61,6 @@ function ExecuteJob() as void
"visitorData": visitorData "visitorData": visitorData
"accessToken": accessToken "accessToken": accessToken
"onBehalfOfUser": onBehalfOfUser "onBehalfOfUser": onBehalfOfUser
"signatureTimestamp": true
}) })
else else
metadata = service.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation }) metadata = service.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation })
@@ -99,7 +98,19 @@ function ExecuteJob() as void
streamUrls = CreateStreamUrls(metadata, service, preferencesNode, backend, playletServerPort) streamUrls = CreateStreamUrls(metadata, service, preferencesNode, backend, playletServerPort)
if streamUrls.Count() = 0 if streamUrls.Count() = 0
contentNode.addFields({ metadata: metadata }) 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 return
end if end if
@@ -329,7 +340,7 @@ function SetCaptions(metadata as object, service as object, contentNode as objec
return return
end if 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() instance = service.GetInstance()
subtitleTracks = [] subtitleTracks = []
@@ -13,6 +13,18 @@ import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RemoteKeys.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() function Init()
SetPlayerStyle() SetPlayerStyle()
SetupAnimation() SetupAnimation()
@@ -214,7 +226,7 @@ function OnVideoContentJobDone(event as object) as void
SeekToInitialPosition(content) SeekToInitialPosition(content)
PlayAfterPreviousPlayerHasStopped() PlayAfterPreviousPlayerHasStopped()
MarkVideoWatched(content.videoId, metadata.playbackTrackingUrls) MarkVideoWatched(content.videoId, metadata.playbackTrackingUrls, metadata.cpn)
end function end function
function SeekToInitialPosition(content as object) as void function SeekToInitialPosition(content as object) as void
@@ -317,6 +329,9 @@ function OnVideoContentJobErrorDialogResponse(event as object)
shouldPlayNext = false shouldPlayNext = false
if event <> invalid if event <> invalid
dialog = event.getRoSGNode() dialog = event.getRoSGNode()
if m.errorDialog <> invalid and dialog.isSameNode(m.errorDialog)
m.errorDialog = invalid
end if
dialog.unobserveFieldScoped("wasClosed") dialog.unobserveFieldScoped("wasClosed")
shouldPlayNext = dialog.actualButtonSelected = 0 shouldPlayNext = dialog.actualButtonSelected = 0
end if end if
@@ -330,7 +345,7 @@ function OnVideoContentJobErrorDialogResponse(event as object)
Lounge.SendOnStateChange() Lounge.SendOnStateChange()
end function 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) if StringUtils.IsNullOrEmpty(videoId)
return return
end if end if
@@ -353,6 +368,7 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic) a
authToken: authToken authToken: authToken
profileType: profileType profileType: profileType
playbackTrackingUrls: playbackTrackingUrls playbackTrackingUrls: playbackTrackingUrls
cpn: cpn
} }
m.markVideoWatchedJob = JobSystem.CreateCallback() m.markVideoWatchedJob = JobSystem.CreateCallback()
@@ -432,6 +448,14 @@ function OnVideoPlayerStateChange() as void
' Reset isSeekingPosition when started to play the video ' Reset isSeekingPosition when started to play the video
if state = "playing" if state = "playing"
m.isSeekingPosition = false 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 end if
' If we successfully played the video, then any error that comes later is not due to a 403 (FORBIDDEN). ' 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 m.videoPlayingSuccess = true
end if end if
errorReported = false errorData = invalid
if state = "error" if state = "error"
errorInfo = m.top.errorInfo errorInfo = m.top.errorInfo
errorData = GetPlayerErrorData(content.videoId, errorInfo) errorData = GetPlayerErrorData(content.videoId, errorInfo)
LogErrorNoTelemetry(errorData.title, errorData.body) LogErrorNoTelemetry(errorData.title, errorData.body)
ReportVideoError(errorData, content.url)
errorReported = true
if m.videoPlayingSuccess <> true if m.videoPlayingSuccess <> true
' http for stream format, mediaerror for DASH ' http for stream format, mediaerror for DASH
if errorInfo.category = "http" or errorInfo.category = "mediaerror" if errorInfo.category = "http" or errorInfo.category = "mediaerror"
currentUrl = content.url
playletStreamUrls = content.playletStreamUrls playletStreamUrls = content.playletStreamUrls
playletStreamUrlIndex = content.playletStreamUrlIndex currentUrlIndex = content.playletStreamUrlIndex
playletStreamUrlIndex++ nextUrlIndex = currentUrlIndex + 1
content.playletStreamUrlIndex = playletStreamUrlIndex content.playletStreamUrlIndex = nextUrlIndex
if playletStreamUrlIndex < playletStreamUrls.Count() if nextUrlIndex < playletStreamUrls.Count()
nextUrl = playletStreamUrls[playletStreamUrlIndex] currentUrl = content.url
msg = `Stream ${currentUrl} failed to play. Trying next stream ${nextUrl}` nextUrl = playletStreamUrls[nextUrlIndex]
LogErrorNoTelemetry(msg)
LogTelemetryEvent({
level: "error"
message: msg
fingerprint: ["Stream <URL> failed to play. Trying next stream <URL>"]
})
if StringUtils.IsNullOrEmpty(nextUrl) if StringUtils.IsNullOrEmpty(nextUrl)
LogError("Next stream URL is empty, cannot try next stream") LogError("Next stream URL is empty, cannot try next stream")
@@ -487,6 +502,12 @@ function OnVideoPlayerStateChange() as void
if hasTimestamp and timestamp > 0 if hasTimestamp and timestamp > 0
m.top.seek = content.timestamp m.top.seek = content.timestamp
end if 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 return
end if end if
end if end if
@@ -504,18 +525,14 @@ function OnVideoPlayerStateChange() as void
end if end if
if state = "error" if state = "error"
errorInfo = m.top.errorInfo
errorData = GetPlayerErrorData(content.videoId, errorInfo)
LogErrorNoTelemetry(errorData.title, errorData.body) LogErrorNoTelemetry(errorData.title, errorData.body)
if not errorReported ReportVideoError(errorData, content.url, content.playletStreamUrls, content.playletStreamUrlIndex, true)
ReportVideoError(errorData, content.url)
end if
buttons = [Tr(Locale.Buttons.PlayNextVideo), Tr(Locale.Buttons.Cancel)] buttons = [Tr(Locale.Buttons.PlayNextVideo), Tr(Locale.Buttons.Cancel)]
dialog = DialogUtils.ShowTimedDialogButtons(errorData.body, errorData.title, buttons, 0, 10, true) dialog = DialogUtils.ShowTimedDialogButtons(errorData.body, errorData.title, buttons, 0, 10, true)
if dialog <> invalid if dialog <> invalid
m.errorDialog = dialog
dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentJobErrorDialogResponse)) dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentJobErrorDialogResponse))
else else
OnVideoContentJobErrorDialogResponse(invalid) OnVideoContentJobErrorDialogResponse(invalid)
@@ -557,7 +574,7 @@ function GetPlayerErrorData(videoId as string, errorInfo as object) as object
} }
end function 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 attachments = invalid
if errorData.body.Instr("malformed data") <> -1 or errorData.body.Instr("invalid pathname") <> -1 if errorData.body.Instr("malformed data") <> -1 or errorData.body.Instr("invalid pathname") <> -1
lastGeneratedDash = ValidString(ReadAsciiFile("cachefs:/last_generated_dash.xml")) 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 position = m.top.position
duration = m.top.duration 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({ LogTelemetryEvent({
level: "error" level: level
message: errorData.title + " " + errorData.body + `\nurl: ${url}\nposition: ${position}\nduration: ${duration}` message: message
fingerprint: errorData.fingerprint fingerprint: errorData.fingerprint
attachments: attachments attachments: attachments
}) })
@@ -66,7 +66,7 @@ namespace Http
return true return true
end if end if
feedSource = ParseJson(feedSource) feedSource = StringUtils.ParseJsonSafe(feedSource)
if feedSource = invalid if feedSource = invalid
response.Default(400, "Expected valid JSON for feed-source") response.Default(400, "Expected valid JSON for feed-source")
return true return true
@@ -253,9 +253,8 @@ namespace Http
return true return true
end function end function
@get("/playlet-invidious-backend/api/v1/trending")
@get("/playlet-invidious-backend/api/v1/popular") @get("/playlet-invidious-backend/api/v1/popular")
function GetTrending(context as object) as boolean function GetPopular(context as object) as boolean
request = context.request request = context.request
response = context.response response = context.response
@@ -264,40 +263,10 @@ namespace Http
return m.GetAuthRecommended(context) return m.GetAuthRecommended(context)
end if 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({ response.Json({
"error": "Failed to get trending feed" "error": "Playlet built-in Invidious backend does not support popular videos."
}) })
response.http_code = 500 response.http_code = 400
return true
end if
response.Json(ValidArray(result.feeds[0].items))
if result.DoesExist("cache-control")
response.headers["cache-control"] = result["cache-control"]
end if
return true return true
end function end function
@@ -346,10 +315,6 @@ namespace Http
response.Json(result.feeds[0]) response.Json(result.feeds[0])
if result.DoesExist("cache-control")
response.headers["cache-control"] = result["cache-control"]
end if
return true return true
end function end function
@@ -619,7 +584,6 @@ namespace Http
} }
end if end if
else else
options["signatureTimestamp"] = true
options["credentialTransferToken"] = m.loungeService.credentialTransferToken options["credentialTransferToken"] = m.loungeService.credentialTransferToken
metadata = InnertubeService.GetVideoMetadata(videoId, options) metadata = InnertubeService.GetVideoMetadata(videoId, options)
end if end if
@@ -804,7 +768,7 @@ namespace Http
' (such as "newest", "oldest", etc.), we'll ignore it, as it is not supported. ' (such as "newest", "oldest", etc.), we'll ignore it, as it is not supported.
sortBy = request.query.sort_by sortBy = request.query.sort_by
if not StringUtils.IsNullOrEmpty(sortBy) and sortBy.StartsWith("{") if not StringUtils.IsNullOrEmpty(sortBy) and sortBy.StartsWith("{")
sortBy = ParseJson(sortBy) sortBy = StringUtils.ParseJsonSafe(sortBy)
if IsAssociativeArray(sortBy) if IsAssociativeArray(sortBy)
if sortBy.DoesExist("params") if sortBy.DoesExist("params")
options.params = sortBy.params options.params = sortBy.params
@@ -19,7 +19,7 @@ namespace Http
saved = RegistryUtils.Read(RegistryUtils.PLAYLET_LIB_URLS) saved = RegistryUtils.Read(RegistryUtils.PLAYLET_LIB_URLS)
if saved <> invalid if saved <> invalid
saved = ParseJson(saved) saved = StringUtils.ParseJsonSafe(saved)
end if end if
response.Json({ response.Json({
@@ -272,7 +272,7 @@ namespace Http
return invalid return invalid
end if end if
m.body_json = ParseJson(text) m.body_json = StringUtils.ParseJsonSafe(text)
return m.body_json return m.body_json
end function end function
end class end class
@@ -11,7 +11,7 @@ namespace Http
if StringUtils.IsNullOrEmpty(json) if StringUtils.IsNullOrEmpty(json)
return "application/octet-stream" return "application/octet-stream"
end if end if
map = ParseJson(json) map = StringUtils.ParseJsonSafe(json)
if not IsAssociativeArray(map) if not IsAssociativeArray(map)
return "application/octet-stream" return "application/octet-stream"
end if end if
@@ -41,7 +41,7 @@ namespace Http
if StringUtils.IsNullOrEmpty(json) if StringUtils.IsNullOrEmpty(json)
return "" return ""
end if end if
map = ParseJson(json) map = StringUtils.ParseJsonSafe(json)
if not IsAssociativeArray(map) if not IsAssociativeArray(map)
return "" return ""
end if end if
@@ -14,44 +14,6 @@
apiType: Invidious apiType: Invidious
endpoint: auth_recommended 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 - title: Popular
id: popular id: popular
feedSources: 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: popular:
title: Popular title: Popular
url: /api/v1/popular url: /api/v1/popular
-16
View File
@@ -243,22 +243,6 @@
id: "recommended", id: "recommended",
enabled: true, enabled: true,
}, },
{
id: "trending",
enabled: true,
},
{
id: "trending_music",
enabled: true,
},
{
id: "trending_gaming",
enabled: true,
},
{
id: "trending_movies",
enabled: true,
},
{ {
id: "popular", id: "popular",
enabled: true, enabled: true,
@@ -312,22 +312,6 @@
<source>Watch history</source> <source>Watch history</source>
<translation>Wiedergabeverlauf</translation> <translation>Wiedergabeverlauf</translation>
</message> </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> <message>
<source>Popular</source> <source>Popular</source>
<translation>Populär</translation> <translation>Populär</translation>
@@ -88,22 +88,6 @@
<source>Watch history</source> <source>Watch history</source>
<translation>Watch history</translation> <translation>Watch history</translation>
</message> </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> <message>
<source>Popular</source> <source>Popular</source>
<translation>Popular</translation> <translation>Popular</translation>
@@ -80,22 +80,6 @@
<source>Watch history</source> <source>Watch history</source>
<translation>Ver el historial</translation> <translation>Ver el historial</translation>
</message> </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> <message>
<source>Popular</source> <source>Popular</source>
<translation>Popular</translation> <translation>Popular</translation>
@@ -36,10 +36,6 @@
<source>Filters</source> <source>Filters</source>
<translation>Filtros</translation> <translation>Filtros</translation>
</message> </message>
<message>
<source>Trending - Music</source>
<translation>Tendencias - Música</translation>
</message>
<message> <message>
<source>Login to Invidious in order to view Subscriptions, Playlists, and use the Watch history.</source> <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> <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> <source>Watch history</source>
<translation>Historial de reproducción</translation> <translation>Historial de reproducción</translation>
</message> </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> <message>
<source>Edit</source> <source>Edit</source>
<translation>Editar</translation> <translation>Editar</translation>
@@ -76,22 +76,6 @@
<source>Watch history</source> <source>Watch history</source>
<translation>Historique</translation> <translation>Historique</translation>
</message> </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> <message>
<source>Popular</source> <source>Popular</source>
<translation>Populaire</translation> <translation>Populaire</translation>
@@ -140,22 +140,6 @@
<source>Watch history</source> <source>Watch history</source>
<translation>Histórico de assistidos</translation> <translation>Histórico de assistidos</translation>
</message> </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> <message>
<source>Popular</source> <source>Popular</source>
<translation>Popular</translation> <translation>Popular</translation>
+2 -2
View File
@@ -2,8 +2,8 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json # Do not update version manually, it is auto updated from package.json
major_version=0 major_version=0
minor_version=43 minor_version=44
build_version=00007 build_version=00009
ui_resolutions=hd ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p uri_resolution_autosub=$$RES$$,480p,720p,1080p
+17 -4
View File
@@ -299,6 +299,11 @@ namespace HttpClient
return m return m
end function end function
function ToFile(filePath as string) as HttpRequest
m._toFilePath = filePath
return m
end function
function ToCurlCommand() as string function ToCurlCommand() as string
command = `curl "${m.BuildUrl()}"` command = `curl "${m.BuildUrl()}"`
if m._method = "HEAD" if m._method = "HEAD"
@@ -387,6 +392,10 @@ namespace HttpClient
end if end if
#end if #end if
if m._toFilePath <> invalid and m._method <> "GET"
throw "ToFile() can only be used with GET requests."
end if
if m._method = "POST" if m._method = "POST"
body = m._body body = m._body
if body = invalid if body = invalid
@@ -394,7 +403,11 @@ namespace HttpClient
end if end if
m._sent = m.urlTransfer.AsyncPostFromString(body) m._sent = m.urlTransfer.AsyncPostFromString(body)
else if m._method = "GET" else if m._method = "GET"
if m._toFilePath <> invalid
m._sent = m.urlTransfer.AsyncGetToFile(m._toFilePath)
else
m._sent = m.urlTransfer.AsyncGetToString() m._sent = m.urlTransfer.AsyncGetToString()
end if
else if m._method = "HEAD" else if m._method = "HEAD"
m._sent = m.urlTransfer.AsyncHead() m._sent = m.urlTransfer.AsyncHead()
else else
@@ -441,7 +454,7 @@ namespace HttpClient
backoffMs = 1000 + Rnd(2000) backoffMs = 1000 + Rnd(2000)
tryNumber = m._tryCount - triesLeft + 1 tryNumber = m._tryCount - triesLeft + 1
LogWarnNoTelemetry("Request failed ID:", m.urlTransfer.GetIdentity(), "ErrorMessage:", response.ErrorMessage(), `\nRetrying: (`, tryNumber, "/", m._tryCount, ") in", backoffMs, "ms") 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) if IsFunction(m._retryCallback)
try try
@@ -690,7 +703,7 @@ namespace HttpClient
if text = invalid if text = invalid
return invalid return invalid
end if end if
m._json = ParseJson(text) m._json = StringUtils.ParseJsonSafe(text)
return m._json return m._json
end function end function
@@ -800,7 +813,7 @@ namespace HttpClientCache
end if end if
metadataText = cacheText.Left(firstLineIndex) metadataText = cacheText.Left(firstLineIndex)
metadata = ParseJson(metadataText) metadata = StringUtils.ParseJsonSafe(metadataText)
if metadata = invalid if metadata = invalid
LogWarn("Failed to parse metadata from cache.") LogWarn("Failed to parse metadata from cache.")
Delete(request) Delete(request)
@@ -808,7 +821,7 @@ namespace HttpClientCache
end if end if
headersText = cacheText.Mid(firstLineIndex + 1, metadata.headers) headersText = cacheText.Mid(firstLineIndex + 1, metadata.headers)
headers = ParseJson(headersText) headers = StringUtils.ParseJsonSafe(headersText)
if headers = invalid if headers = invalid
LogWarn("Failed to parse headers from cache.") LogWarn("Failed to parse headers from cache.")
Delete(request) Delete(request)
+3 -4
View File
@@ -1,6 +1,7 @@
#if DEBUG
namespace DebugUtils namespace DebugUtils
function PrintStackTrace(message = invalid as dynamic) function PrintStackTrace(message = invalid as dynamic)
#if DEBUG
try try
throw "Handled throw in DebugUtils.PrintStackTrace()" throw "Handled throw in DebugUtils.PrintStackTrace()"
catch error catch error
@@ -15,11 +16,9 @@ namespace DebugUtils
end for end for
PrintInABox(lines) PrintInABox(lines)
end try end try
#end if
end function end function
function PrintInABox(lines as object) function PrintInABox(lines as object)
#if DEBUG
maxLen = 0 maxLen = 0
for each line in lines for each line in lines
if line.len() > maxLen if line.len() > maxLen
@@ -32,6 +31,6 @@ namespace DebugUtils
end for end for
out += `\n` + "╚" + string(maxLen + 2, "═") + "╝" out += `\n` + "╚" + string(maxLen + 2, "═") + "╝"
print out print out
#end if
end function end function
end namespace end namespace
#end if
-4
View File
@@ -41,10 +41,6 @@ namespace Locale
Recommended = "Recommended" Recommended = "Recommended"
Playlists = "Playlists" Playlists = "Playlists"
WatchHistory = "Watch history" WatchHistory = "Watch history"
Trending = "Trending"
TrendingMovies = "Trending - Movies"
TrendingMusic = "Trending - Music"
TrendingGaming = "Trending - Gaming"
Popular = "Popular" Popular = "Popular"
Videos = "Videos" Videos = "Videos"
Shorts = "Shorts" Shorts = "Shorts"
@@ -29,5 +29,18 @@ namespace StringUtils
function RandomId() as string function RandomId() as string
return StrI(rnd(2147483647), 36) return StrI(rnd(2147483647), 36)
end function 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 end namespace
+1306 -1660
View File
File diff suppressed because it is too large. Load diff
+16 -17
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-web", "name": "playlet-web",
"version": "0.43.7", "version": "0.44.9",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -9,29 +9,28 @@
"lint": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings" "lint": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings"
}, },
"devDependencies": { "devDependencies": {
"@sveltejs/vite-plugin-svelte": "^6.2.1", "@sveltejs/vite-plugin-svelte": "^7.0.0",
"@tailwindcss/postcss": "^4.1.16", "@tailwindcss/postcss": "^4.2.4",
"@tailwindcss/typography": "^0.5.19", "@tailwindcss/typography": "^0.5.19",
"@tsconfig/svelte": "^5.0.5", "@tsconfig/svelte": "^5.0.8",
"@vitejs/plugin-legacy": "^7.2.1", "@vitejs/plugin-legacy": "^8.0.1",
"autoprefixer": "^10.4.21", "autoprefixer": "^10.5.0",
"bgutils-js": "^3.2.0", "bgutils-js": "^3.2.0",
"daisyui": "^5.3.10", "daisyui": "^5.5.19",
"dotenv": "^17.2.3", "dotenv": "^17.4.2",
"ip": "^2.0.1", "ip": "^2.0.1",
"jszip": "^3.10.1", "jszip": "^3.10.1",
"postcss": "^8.5.6", "postcss": "^8.5.10",
"rollup-plugin-visualizer": "^6.0.5", "rollup-plugin-visualizer": "^7.0.1",
"svelte": "^5.43.2", "svelte": "^5.55.5",
"svelte-check": "^4.3.3", "svelte-check": "^4.4.6",
"svelte-preprocess": "^6.0.3", "svelte-preprocess": "^6.0.3",
"tailwindcss": "^4.1.16", "tailwindcss": "^4.2.4",
"terser": "^5.44.0", "terser": "^5.46.2",
"tslib": "^2.8.1", "tslib": "^2.8.1",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"vite": "^7.1.12", "vite": "^8.0.10",
"vite-plugin-compression": "^0.5.1", "vite-plugin-compression": "^0.5.1",
"vite-tsconfig-paths": "^5.1.4", "youtubei.js": "^17.0.1"
"youtubei.js": "^16.0.1"
} }
} }
+11 -15
View File
@@ -141,20 +141,8 @@ export class YoutubeJs {
static initJsEvaluator() { static initJsEvaluator() {
Platform.shim.eval = async (data: Types.BuildScriptResult, env: Record<string, Types.VMPrimative>) => { Platform.shim.eval = async (data: Types.BuildScriptResult, env: Record<string, Types.VMPrimative>) => {
const properties = []; return new Function(data.output)();
};
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)();
}
} }
static async generateVisitorData() { static async generateVisitorData() {
@@ -255,6 +243,10 @@ export class YoutubeJs {
po_token: await YoutubeJs.generatePoToken(videoId), 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. // We can't generate a proper dash from live videos.
// By returning null, we're telling Playlet to fetch video info itself. // By returning null, we're telling Playlet to fetch video info itself.
if (info.basic_info.is_live) { 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}` : "", init: format.init_range ? `${format.init_range.start}-${format.init_range.end}` : "",
index: format.index_range ? `${format.index_range.start}-${format.index_range.end}` : "", index: format.index_range ? `${format.index_range.start}-${format.index_range.end}` : "",
bitrate: `${format.bitrate}`, bitrate: `${format.bitrate}`,
url: await format.decipher(YoutubeJs.innerTube.session.player),
itag: `${format.itag}`, itag: `${format.itag}`,
type: format.mime_type, type: format.mime_type,
clen: `${format.approx_duration_ms}`, clen: `${format.approx_duration_ms}`,
lmt: `${format.last_modified}`, 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) { if (format.audio_quality) {
result.audioQuality = format.audio_quality; result.audioQuality = format.audio_quality;
} }
@@ -49,11 +49,17 @@
}); });
async function playOnTv() { async function playOnTv() {
try {
const videoInfo = getVideoInfo(); const videoInfo = getVideoInfo();
await PlayletApi.playVideo(videoInfo); await PlayletApi.playVideo(videoInfo);
} catch (error) {
console.error(error);
alert(error);
}
} }
async function playOnTvYtjs() { async function playOnTvYtjs() {
try {
const videoInfo = getVideoInfo() as any; const videoInfo = getVideoInfo() as any;
// measure length of time it takes to get video info // measure length of time it takes to get video info
@@ -66,11 +72,20 @@
videoInfo.metadata = metadata; videoInfo.metadata = metadata;
} }
await PlayletApi.playVideo(videoInfo); await PlayletApi.playVideo(videoInfo);
} catch (error) {
console.error(error);
alert(error);
}
} }
async function queueOnTv() { async function queueOnTv() {
try {
const videoInfo = getVideoInfo(); const videoInfo = getVideoInfo();
await PlayletApi.queueVideo(videoInfo); await PlayletApi.queueVideo(videoInfo);
} catch (error) {
console.error(error);
alert(error);
}
} }
function openInvidious() { function openInvidious() {
+3 -2
View File
@@ -2,7 +2,6 @@ import { visualizer } from 'rollup-plugin-visualizer';
import { defineConfig, UserConfig } from 'vite' import { defineConfig, UserConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte' import { svelte } from '@sveltejs/vite-plugin-svelte'
import viteCompression from 'vite-plugin-compression'; import viteCompression from 'vite-plugin-compression';
import tsconfigPaths from 'vite-tsconfig-paths'
import ip from 'ip'; import ip from 'ip';
import { existsSync, readFileSync } from 'fs' import { existsSync, readFileSync } from 'fs'
import { join as joinPath } from 'path' import { join as joinPath } from 'path'
@@ -13,7 +12,6 @@ const PORT = 5173
const config: UserConfig = { const config: UserConfig = {
plugins: [ plugins: [
tsconfigPaths(),
svelte(), svelte(),
legacy({ legacy({
targets: ['defaults', 'not IE 11'], targets: ['defaults', 'not IE 11'],
@@ -23,6 +21,9 @@ const config: UserConfig = {
deleteOriginFile: true deleteOriginFile: true
}) })
], ],
resolve: {
tsconfigPaths: true
},
build: { build: {
outDir: "../playlet-lib/src/www", outDir: "../playlet-lib/src/www",
emptyOutDir: true emptyOutDir: true
+1 -1
View File
@@ -15,6 +15,6 @@ INVIDIOUS_HMAC_KEY=PASSWORD_1
INVIDIOUS_COMPANION_KEY=PASSWORD_2 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. 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 # Use the key generated in the 2nd step
hmac_key: $INVIDIOUS_HMAC_KEY hmac_key: $INVIDIOUS_HMAC_KEY
healthcheck: 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 interval: 30s
timeout: 5s timeout: 5s
retries: 2 retries: 2