Compare commits

..
81 Commits
Author SHA1 Message Date
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
Brahim Hadriche 422c867c00 Release v0.43.7 (#781) 2025-11-06 11:52:24 -05:00
Brahim Hadriche 6e43528802 [skip ci] Adjust telemetry for OTF streams to debug 2025-11-06 11:48:20 -05:00
Brahim Hadriche 61d4baa181 [skip ci] Remove redundant log 2025-11-06 11:39:44 -05:00
Brahim Hadriche 7f451af418 Release v0.43.6 (#780) 2025-11-06 08:44:23 -05:00
Brahim Hadriche b72a1522a4 [skip ci] adjust gvs headers 2025-11-06 08:43:59 -05:00
Brahim Hadriche 86b1afe243 [skip ci] adjust error check 2025-11-06 08:25:33 -05:00
Brahim Hadriche 67bf473dda [skip ci] Fix bug in processing OTF streams info 2025-11-06 08:13:50 -05:00
Brahim Hadriche 5f744fa7bc Release v0.43.5 (#779) 2025-11-05 21:14:55 -05:00
Brahim Hadriche 5a8762c7e5 Feature/dash improvements (#778)
* Parse post live dvr info

* add otf info

* dash rework

* Bug in detecting live videos in HLS streams

* small refactor

* otf support (maybe)

* remove indexRangeExact

* tweak

* Enable OTF, and hope for the best

* Fix OTF and post live dvr

* logs

* tweaks and error handling

* change profile

* dash tweaks

* hls tweak
2025-11-05 20:54:28 -05:00
Brahim Hadriche b80b067afb Release v0.43.4 (#777) 2025-11-03 13:36:02 -05:00
Brahim Hadriche 777b36852f Fallback for post live dvr and OTF videos 2025-11-03 13:23:05 -05:00
Brahim Hadriche dd1cd8db97 update dependencies (#773) 2025-11-02 09:27:27 -05:00
Brahim Hadriche a1caa78e6e [skip ci] Fallback to iOS HLS for post dvr videos 2025-10-30 16:44:47 -04:00
Brahim Hadriche 4d1e46cbcc Fix playback error when regular videos are returned with DRM protection 2025-10-30 16:00:16 -04:00
Brahim Hadriche f59ed85b62 [skip ci] capture player error position and duration 2025-10-30 12:14:09 -04:00
Brahim Hadriche ad0c363ae0 Release v0.43.3 (#772) 2025-10-30 09:23:04 -04:00
Brahim Hadriche d8a86f88e1 [skip ci] channel parsing 2025-10-30 09:18:15 -04:00
Brahim Hadriche 9dd634e8dd [skip ci] capture url errors 2025-10-30 08:58:11 -04:00
Brahim Hadriche ba876be76d Filter out promo tiles 2025-10-29 20:21:13 -04:00
Brahim Hadriche 2fa3df7aae test fix 2025-10-29 20:20:53 -04:00
Brahim Hadriche 0d1da36e28 Release v0.43.2 (#770) 2025-10-29 13:43:15 -04:00
Brahim Hadriche c61c8aecc6 [skip ci] req id filtering 2025-10-29 13:37:53 -04:00
Brahim Hadriche 7a63b26c73 grid movie renderer 2025-10-29 13:35:24 -04:00
Brahim Hadriche 0d949b1752 byte array slice fix 2025-10-29 09:29:34 -04:00
Brahim Hadriche 33518607c5 parse radioRenderer 2025-10-28 20:25:59 -04:00
Brahim Hadriche 8a47c02179 capture different tiles 2025-10-28 19:46:01 -04:00
Brahim Hadriche a1251c065d Tweak LOCKUP_CONTENT_TYPE_SHORT 2025-10-28 19:45:50 -04:00
88 changed files with 2320 additions and 2229 deletions

No files matched your search

+23
View File
@@ -76,6 +76,29 @@
"args": "--log-level info --project bsconfig.tests.json --create-package --sourceMap=true --debug --test-mode --lintConfig ../config/bslint.jsonc",
"cwd": "${workspaceFolder}/playlet-lib",
"console": "integratedTerminal"
},
{
"name": "Playground",
"type": "brightscript",
"request": "launch",
"envFile": "${workspaceFolder}/.env",
"host": "${env:ROKU_DEV_TARGET}",
"password": "${env:ROKU_DEVPASSWORD}",
"stopOnEntry": false,
"enableDebuggerAutoRecovery": false,
"stopDebuggerOnAppExit": false,
"rootDir": "${workspaceFolder}/build/playground",
"sourceDirs": [
"${workspaceFolder}/playground/src"
],
"files": [
"**"
],
"preLaunchTask": "build-playground",
"injectRdbOnDeviceComponent": true,
"injectRaleTrackerTask": true,
"raleTrackerTaskFileLocation": "${workspaceFolder}/tools/RALE/TrackerTask.xml",
"enableDebugProtocol": true
}
],
"compounds": [
+5
View File
@@ -49,6 +49,11 @@
"label": "build-web",
"script": "build:web",
"type": "npm"
},
{
"label": "build-playground",
"script": "build:playground",
"type": "npm"
}
]
}
+107
View File
@@ -5,8 +5,115 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.44.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
### Fixed
- Adjust telemetry for OTF streams to debug
## [0.43.6] - 2025-11-06
### Fixed
- Bug in processing OTF streams info
## [0.43.5] - 2025-11-06
### Fixed
- Post live DVR video support
- Attempted OTF stream support
- Better parsing of audio track metadata
- Bug in detecting live videos in HLS streams
## [0.43.4] - 2025-11-03
### Fixed
- Playback error when regular videos are returned with DRM protection (unless they are OTF)
- Fallback to iOS HLS for post dvr and OTF videos
## [0.43.3] - 2025-10-30
### Fixed
- Improve channel parsing in Recommended feed
## [0.43.2] - 2025-10-29
### Fixed
- Crash on older Roku OS version due to `roByteArray.Slice` not being available
## [0.43.1] - 2025-10-28
### Added
- Support for additional nodes parsing
### Fixed
- Trickplay storyboards on DRM videos
+3
View File
@@ -27,6 +27,9 @@
Playlet is an unofficial YouTube client for Roku 📺
**[Playlet February 2026 Update](https://github.com/iBicha/playlet/discussions/827)**
## Screenshots
<a href="./docs/screenshots/README.md">
+6
View File
@@ -58,6 +58,12 @@
"regex": "\\bTr\\s*\\(\\s*\"[^\\\"]*\"\\s*\\)",
"regexFlags": "ig",
"message": "Tr(\"String\") is not allowed. Use Tr(Locale.Key) instead."
},
{
"code": "NO_PARSE_JSON",
"regex": "\\s*ParseJson\\(",
"regexFlags": "ig",
"message": "ParseJson is not allowed. Use StringUtils.ParseJsonSafe() instead."
}
],
"files": [
+131 -1167
View File
File diff suppressed because it is too large. Load diff
+16 -15
View File
@@ -1,38 +1,38 @@
{
"name": "playlet",
"version": "0.43.1",
"version": "0.44.6",
"description": "Unofficial YouTube client for Roku",
"devDependencies": {
"@rokucommunity/bslint": "^0.8.37",
"@rokucommunity/bslint": "^0.8.38",
"@types/crypto-js": "^4.2.2",
"@types/fs-extra": "^11.0.4",
"@types/node": "^24.9.1",
"@types/node": "^25.2.1",
"@types/xml2js": "^0.4.14",
"argparse": "^2.0.1",
"brighterscript": "0.70.2",
"brighterscript": "0.70.3",
"brighterscript-formatter": "^1.7.19",
"convert-svg-to-png": "^0.7.1",
"crypto-js": "^4.2.0",
"dotenv": "^17.2.3",
"fs-extra": "^11.3.2",
"glob": "^11.0.3",
"dotenv": "^17.2.4",
"fs-extra": "^11.3.3",
"glob": "^13.0.1",
"imap": "^0.8.19",
"ip": "^2.0.1",
"json5": "^2.2.3",
"mailparser": "^3.7.5",
"mailparser": "^3.9.3",
"protocol-buffers-schema": "^3.6.0",
"puppeteer": "^24.26.1",
"roku-deploy": "^3.13.0",
"puppeteer": "^24.37.2",
"roku-deploy": "^3.16.1",
"roku-test-automation": "^2.2.1",
"rooibos-roku": "5.15.5",
"rounded-rect-9patch": "^1.1.2",
"semver": "^7.7.3",
"semver": "^7.7.4",
"shelljs": "^0.10.0",
"ts-node": "^10.9.2",
"typescript": "5.9.3",
"telnet-client": "^2.2.6",
"telnet-client": "^2.2.9",
"xml2js": "^0.6.2",
"yaml": "^2.8.1"
"yaml": "^2.8.2"
},
"engines": {
"node": "22"
@@ -48,6 +48,7 @@
"build:lib:dev": "cd playlet-lib && npm run build:dev",
"build:lib:prod": "cd playlet-lib && npm run build:prod",
"build:web": "cd playlet-web && npm run build",
"build:playground": "cd playground && npm run build",
"lint": "cd playlet-lib && npm run lint && cd ../playlet-app && npm run lint && cd ../playlet-web && npm run lint",
"lint:fix": "cd playlet-lib && npm run lint:fix && cd ../playlet-app && npm run lint:fix && cd ../playlet-web && npm run lint",
"format": "cd playlet-lib && npm run format && cd ../playlet-app && npm run format",
@@ -65,7 +66,7 @@
"screenshot": "node tools/screenshot.js",
"convert-images": "node tools/convert-images.js",
"update-rale-component": "cd tools/RALE && rm TrackerTask.xml && curl -o TrackerTask.zip https://devtools.web.roku.com/roku-advanced-layout-editor/app/TrackerTask.zip && unzip TrackerTask.zip && rm TrackerTask.zip",
"postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playlet-web && npm install",
"postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playground && npm install && cd ../playlet-web && npm install",
"update-deps": "npx npm-check-updates --deep --upgrade --install always --reject rooibos-roku",
"registry:write": "node tools/registry.js --input registry.json",
"registry:read": "node tools/registry.js --output registry.json",
@@ -75,6 +76,6 @@
"shutdown": "node tools/shutdown.js"
},
"optionalDependencies": {
"@rollup/rollup-linux-x64-gnu": "^4.52.5"
"@rollup/rollup-linux-x64-gnu": "^4.57.1"
}
}
+7
View File
@@ -0,0 +1,7 @@
# Playground
Playground is a test project to try things out or iterate on a concept.
Playlet app relies on playlet lib, and playlet lib relies on web app, so sometimes iteration speed can be slower when building everything everytime.
Just like Playlet, Playground can be launched from the VSCode "Run and debug" menu.
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../config/bsconfig.base.jsonc",
"rootDir": "src/",
"stagingDir": "../build/playground",
"outFile": "../dist/playground.zip"
}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "bsconfig.json",
"createPackage": false,
"deploy": false,
"retainStagingDir": false,
"sourceMap": false
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../config/bsconfig.tests.base.jsonc",
"rootDir": "src/",
"stagingDir": "../build/playground-tests",
"outFile": "../build/playground-tests.zip"
}
+12
View File
@@ -0,0 +1,12 @@
{
"name": "playground",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playground",
"version": "0.1.0"
}
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"name": "playground",
"version": "0.1.0",
"description": "A playground for testing Roku development",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playground",
"build": "bsc --debug --create-package --sourceMap=true --lintConfig ../config/bslint.jsonc",
"lint": "bslint --project bsconfig.lint.json --lintConfig ../config/bslint.jsonc",
"lint:fix": "npm run lint -- --fix",
"format:base": "bsfmt \"src/**/*.brs\" \"src/**/*.bs\" \"!**/bslib.brs\" \"!**/roku_modules/**/*\" --bsfmt-path ../config/bsfmt.jsonc",
"format": "npm run format:base -- --check",
"format:fix": "npm run format:base -- --write",
"test": "npm run test:build && npm run test:run",
"test:build": "bsc --project bsconfig.tests.json --create-package --sourceMap=true --debug --test-mode --lintConfig ../config/bslint.jsonc",
"test:run": "node ../tools/run-test-app.js --package ../build/playground-tests.zip"
}
}
+3
View File
@@ -0,0 +1,3 @@
function Init()
print "Playground Init"
end function
+10
View File
@@ -0,0 +1,10 @@
<component name="Playground" extends="Scene">
<interface>
<field id="exitChannel" type="bool" alwaysNotify="true" />
<field id="launchArgs" type="assocarray" />
<field id="inputArgs" type="assocarray" alwaysNotify="true" />
</interface>
<children>
<Label text="Welcome to Playlet Playground!" />
</children>
</component>
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+31
View File
@@ -0,0 +1,31 @@
title=Playlet Playground
major_version=0
minor_version=1
build_version=00000
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
## Channel Assets
### Main Menu Icons / Channel Poster Artwork
#### Image sizes are FHD: 540x405px | HD: 290x218px | SD: 246x140px
mm_icon_focus_fhd=pkg:/images/channel-poster_fhd.png
mm_icon_focus_hd=pkg:/images/channel-poster_hd.png
mm_icon_focus_sd=pkg:/images/channel-poster_sd.png
### Splash Screen + Loading Screen Artwork
#### Image sizes are FHD: 1920x1080px | HD: 1280x720px | SD: 720x480px
splash_screen_fhd=pkg:/images/splash-screen_fhd.jpg
splash_screen_hd=pkg:/images/splash-screen_hd.jpg
splash_screen_sd=pkg:/images/splash-screen_sd.jpg
splash_color=#242424
splash_min_time=0
confirm_partner_button=1
supports_input_launch=1
requires_widevine_drm=1
requires_widevine_version=1.0
+56
View File
@@ -0,0 +1,56 @@
' Playlet (App to play videos from an Invidious server on Roku TVs)
' Copyright (C) 2025 Brahim Hadriche
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU Affero General Public License as published by
' the Free Software Foundation, either version 3 of the License, or
' (at your option) any later version.
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' GNU Affero General Public License for more details.
' You should have received a copy of the GNU Affero General Public License
' along with this program. If not, see <https://www.gnu.org/licenses/>.
function Main(args as object) as void
screen = CreateObject("roSGScreen")
port = CreateObject("roMessagePort")
screen.setMessagePort(port)
scene = screen.CreateScene("Playground")
screen.show()
scene.ObserveField("exitChannel", port)
scene.launchArgs = args
input = CreateObject("roInput")
input.setMessagePort(port)
' The following comment is to enable the SceneGraph inspector
' on the VSCode BrightScript plugin.
' vscode_rdb_on_device_component_entry
' The following comment is to enable RALE tracking
' vscode_rale_tracker_entry
while true
msg = wait(0, port)
msgType = type(msg)
if msgType = "roSGScreenEvent"
if msg.isScreenClosed()
return
end if
else if msgType = "roSGNodeEvent"
field = msg.getField()
data = msg.getData()
if field = "exitChannel" and data = true
return
end if
else if msgType = "roInputEvent"
scene.inputArgs = msg.getInfo()
end if
end while
end function
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-app",
"version": "0.43.1",
"version": "0.44.6",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-app",
"version": "0.43.1"
"version": "0.44.6"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-app",
"version": "0.43.1",
"version": "0.44.6",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-app",
@@ -37,6 +37,7 @@ function GetLoadingMessagesFromCache() as object
if messagesFile = ""
return invalid
end if
' bs:disable-next-line NO_PARSE_JSON
return ParseJson(messagesFile)
end function
+3 -3
View File
@@ -2,8 +2,8 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=43
build_version=00001
minor_version=44
build_version=00006
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
@@ -38,4 +38,4 @@ playlet_lib_zip_debug_url=http://DEBUG_HOST_IP_ADDRESS:8086/playlet-lib.zip
git_commit_sha=unknown
bs_const=DEBUG=false;DEBUG_FALLBACK_TO_EMBEDDED=true
bs_const=DEBUG=false;TEST_MODE=false;DEBUG_FALLBACK_TO_EMBEDDED=true
+8 -1
View File
@@ -35,7 +35,14 @@ namespace Logger
msg += `app_state: ${lastExitInfo.app_state}\n`
msg += `media_player_state: ${lastExitInfo.media_player_state}\n`
msg += `mem_limit: ${lastExitInfo.mem_limit}\n`
msg += `console_log:\n${lastExitInfo.console_log}\n`
' Sometimes lastExitInfo.console_log would contain 'AppExitComplete', which
' is used to detect test runner exits. So we don't log it in test mode.
#if TEST_MODE
#else
msg += `console_log:\n${lastExitInfo.console_log}\n`
#end if
msg += `********** End Last Exit Info **********\n`
print msg
+1
View File
@@ -28,6 +28,7 @@ namespace Registry
if urlsJson = invalid
return invalid
end if
' bs:disable-next-line NO_PARSE_JSON
urls = ParseJson(urlsJson)
return urls
end function
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-lib",
"version": "0.43.1",
"version": "0.44.6",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-lib",
"version": "0.43.1"
"version": "0.44.6"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-lib",
"version": "0.43.1",
"version": "0.44.6",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-lib",
@@ -125,7 +125,7 @@ namespace DialogUtils
if hasMessageId
messages = RegistryUtils.Read(RegistryUtils.MESSAGES)
if not StringUtils.IsNullOrEmpty(messages)
messages = ParseJson(messages)
messages = StringUtils.ParseJsonSafe(messages)
if IsAssociativeArray(messages)
savedMessageId = ValidString(messages["messageId"])
if savedMessageId = messageId
+13 -8
View File
@@ -59,14 +59,19 @@ function LoggerLoop()
DeleteFile(previousLogsFile)
MoveFile(logsFile, previousLogsFile)
startUpLogs = ReadAsciiFile(FILENAME_STARTUP)
if not StringUtils.IsNullOrEmpty(startUpLogs)
line = `************* Startup Logs *************\n${startUpLogs}*********** End Startup Logs ***********\n`
print line
buffer.FromAsciiString(line)
buffer.AppendFile(logsFile)
end if
' Sometimes lastExitInfo.console_log (which would be contained in startUpLogs)
' would contain 'AppExitComplete', which is used to detect test runner exits.
' So we don't log it in test mode.
#if TEST_MODE
#else
startUpLogs = ReadAsciiFile(FILENAME_STARTUP)
if not StringUtils.IsNullOrEmpty(startUpLogs)
line = `************* Startup Logs *************\n${startUpLogs}*********** End Startup Logs ***********\n`
print line
buffer.FromAsciiString(line)
buffer.AppendFile(logsFile)
end if
#end if
m.eventThrottleTimer = CreateObject("roTimespan")
appMemoryMonitor = CreateObject("roAppMemoryMonitor")
@@ -1,9 +1,10 @@
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
namespace HomeScreenUtils
function GetFeed(feedFileName as string, preferences as object) as object
feed = ParseJson(ReadAsciiFile(feedFileName))
feed = StringUtils.ParseJsonSafe(ReadAsciiFile(feedFileName))
for each item in feed
item.title = Tr(item.title)
@@ -3,11 +3,12 @@ import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/MathUtils.bs"
import "pkg:/source/utils/RemoteKeys.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.homeLayout = {}
homeLayout = ParseJson(ReadAsciiFile("libpkg:/config/default_home_layout.yaml"))
homeLayout = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/default_home_layout.yaml"))
for each item in homeLayout
m.homeLayout[item.id] = item
end for
@@ -324,7 +324,7 @@ end function
function CanFetchWithCors(instance as string, testNode as object, cancellation as object) as void
try
url = `${instance}/api/v1/trending`
url = `${instance}/api/v1/popular`
response = HttpClient.Get(url).NoCache().Cancellation(cancellation).Await()
if not response.IsSuccess()
@@ -20,7 +20,7 @@ function Load() as void
end if
m.bookmarksString = bookmarksString
bookmarks = ParseJson(bookmarksString)
bookmarks = StringUtils.ParseJsonSafe(bookmarksString)
if bookmarks = invalid
LogWarn("Failed to parse bookmarks json")
return
@@ -32,7 +32,7 @@ class DashManifest
}
end function
function fromVideoMetadata(metadata as object, qualityFilter as object, local as boolean) as string
function FromVideoMetadata(metadata as object, qualityFilter as object, local as boolean) as string
adaptiveFormats = []
adaptiveFormats.Append(metadata.adaptiveFormats)
@@ -48,14 +48,19 @@ class DashManifest
end for
end if
audioStreams = m.getAudioStreams(adaptiveFormats)
videoStreams = m.getVideoStreams(adaptiveFormats, qualityFilter)
if videoStreams.Count() = 0
duration = m.GetDuration(metadata)
groupings = m.CreateFormatGroupings(adaptiveFormats, metadata.isPostLiveDvr)
audioGroups = groupings.audio
videoGroups = groupings.video
filteredVideoGroups = m.FilterVideoGroups(videoGroups, qualityFilter)
if filteredVideoGroups.Count() = 0 and videoGroups.Count() > 0
LogWarnNoTelemetry("No video streams found using quality filter:", qualityFilter, "Falling back to all video streams")
videoStreams = m.getVideoStreams(adaptiveFormats, {})
filteredVideoGroups = videoGroups
end if
if videoStreams.Count() = 0
if filteredVideoGroups.Count() = 0
lastPlayerResponse = ValidString(ReadAsciiFile("cachefs:/last_player_response.json"))
LogTelemetryEvent({
level: "error"
@@ -72,169 +77,372 @@ class DashManifest
}]
})
end if
videoMimeTypes = m.getMimeTypes(videoStreams)
audioSets = m.getMimeTypeLanguageCombos(audioStreams)
storyboards = metadata.storyboards
xml = new XmlObject()
xml.Comment(`Generated by Playlet - Video ID: ${metadata.videoId}`)
xml.Comment(`Parser: ${ValidString(metadata.parser)}`)
if xml.Node("MPD", {
"xmlns": "urn:mpeg:dash:schema:mpd:2011"
"profiles": "urn:mpeg:dash:profile:full:2011"
"minBufferTime": "PT1.5S"
"type": "static"
"mediaPresentationDuration": `PT${metadata.lengthSeconds ?? 0}S`
"mediaPresentationDuration": `PT${duration}S`
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance"
"xsi:schemaLocation": "urn:mpeg:dash:schema:mpd:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd"
})
if xml.Node("Period")
id = 0
id = m.generateAudioAdaptationSets(xml, audioSets, audioStreams, id)
id = m.generateVideoAdaptationSets(xml, videoMimeTypes, videoStreams, id)
m.generateImageAdaptationSets(xml, storyboards, id)
id = m.GenerateAudioAdaptationSets(xml, audioGroups, id, metadata)
id = m.GenerateVideoAdaptationSets(xml, filteredVideoGroups, id, metadata)
m.GenerateImageAdaptationSets(xml, storyboards, id)
xml.End()
end if
xml.End()
end if
return xml.ToXmlString()
end function
function generateAudioAdaptationSets(xml as object, audioSets as object, audioStreams as object, id as integer) as integer
for each audioSet in audioSets
function GetDuration(metadata as object) as dynamic
if metadata["isPostLiveDvr"] = true and IsInt(metadata["postLiveDvrDurationMs"])
return metadata["postLiveDvrDurationMs"] / 1000.0
end if
approxDurationMs = ValidString(ObjectUtils.Dig(metadata, ["adaptiveFormats", 0, "approxDurationMs"])).ToInt()
if approxDurationMs > 0
return approxDurationMs / 1000.0
end if
return ValidInt(metadata["lengthSeconds"])
end function
function CreateFormatGroupings(formats as object, isPostLiveDvr as boolean) as object
groupInfo = {}
for each format in formats
isOtf = format.isTypeOTF = true
hasInit = not StringUtils.IsNullOrEmpty(format.init)
hasIndex = not StringUtils.IsNullOrEmpty(format.index)
isValid = (hasInit and hasIndex) or isOtf or isPostLiveDvr
if not isValid
continue for
end if
if not IsString(format.type)
continue for
end if
if (format.width = invalid or format.height = invalid) and not StringUtils.IsNullOrEmpty(format.size)
if format.size.instr("x") > 0
parts = format.size.Tokenize("x")
if parts.Count() = 2
format.width = ValidInt(parts[0].toInt())
format.height = ValidInt(parts[1].toInt())
end if
end if
end if
codecs = ""
mimeType = format.type.Tokenize(";")[0]
if format.type.inStr("codecs=") <> -1
codecs = format.type.split("codecs=")[1]
if codecs.startsWith(`"`)
codecs = codecs.mid(1)
end if
if codecs.endsWith(`"`)
codecs = codecs.left(codecs.len() - 1)
end if
end if
justCodec = codecs.split(".")[0]
colorInfo = ""
if IsAssociativeArray(format.colorInfo)
colorInfo = `${format.colorInfo.primaries}-${format.colorInfo.transferCharacteristics}-${format.colorInfo.matrixCoefficients}`
end if
audioTrackId = ""
if IsAssociativeArray(format.audioTrack) and IsString(format.audioTrack.id)
audioTrackId = format.audioTrack.id
end if
if format.type.startsWith("audio")
xtagsInfo = m.GetXtagsInfo(format)
format.xtagsInfo = xtagsInfo
format.isDrc = xtagsInfo.isDrc
format.isDubbed = xtagsInfo.isDubbed
format.isAutoDubbed = xtagsInfo.isAutoDubbed
format.isDescriptive = xtagsInfo.isDescriptive
format.isSecondary = xtagsInfo.isSecondary
format.isOriginal = xtagsInfo.isOriginal
end if
drc = ""
if format.isDrc = true
drc = "drc"
end if
groupId = `${mimeType}-${justCodec}-${colorInfo}-${audioTrackId}-${drc}`
if groupInfo[groupId] = invalid
groupInfo[groupId] = []
end if
groupInfo[groupId].Push(format)
end for
audioGroups = []
videoGroups = []
for each key in groupInfo
group = groupInfo[key]
if group[0].type.startsWith("audio")
audioGroups.Push(group)
else if group[0].type.startsWith("video")
videoGroups.Push(group)
end if
end for
return { audio: audioGroups, video: videoGroups }
end function
function FilterVideoGroups(videoGroups as object, qualityFilter as object) as object
if qualityFilter.Count() = 0
return videoGroups
end if
filteredGroups = []
for each group in videoGroups
filteredStreams = []
for each stream in group
if m.IsVideoFormatIncluded(stream, qualityFilter)
filteredStreams.Push(stream)
end if
end for
if filteredStreams.Count() > 0
filteredGroups.Push(filteredStreams)
end if
end for
return filteredGroups
end function
function IsVideoFormatIncluded(stream as object, qualityFilter as object) as boolean
if qualityFilter.Count() = 0
return true
end if
qualityLabel = stream.qualityLabel
if not StringUtils.IsNullOrEmpty(qualityLabel)
pIndex = qualityLabel.InStr("p")
if pIndex <> -1
qualityLabel = qualityLabel.Mid(0, pIndex)
end if
if qualityFilter[qualityLabel] = true
return true
end if
end if
if stream.height <> invalid
if qualityFilter[ToString(stream.height)] = true
return true
end if
end if
resolution = stream.resolution
if not StringUtils.IsNullOrEmpty(resolution)
pIndex = resolution.InStr("p")
if pIndex <> -1
resolution = resolution.Mid(0, pIndex)
end if
if qualityFilter[resolution] = true
return true
end if
end if
size = stream.size
if not StringUtils.IsNullOrEmpty(size)
sizeParts = size.Split("x")
if sizeParts.Count() = 2
if qualityFilter[sizeParts[1]] = true
return true
end if
end if
end if
return false
end function
function GenerateAudioAdaptationSets(xml as object, audioGroups as object, id as integer, metadata as object) as integer
for each group in audioGroups
firstFormat = group[0]
hoisted = {}
adaptationSetAttributes = {
"id": `${id}`
"mimeType": audioSet.mimeType
"mimeType": firstFormat.type.Tokenize(";")[0]
"startWithSAP": "1"
"subsegmentAlignment": "true"
"contentType": "audio"
}
if not StringUtils.IsNullOrEmpty(audioSet.lang)
adaptationSetAttributes["lang"] = audioSet.lang
if IsAssociativeArray(firstFormat.audioTrack)
if IsString(firstFormat.audioTrack.languageCode)
adaptationSetAttributes["lang"] = firstFormat.audioTrack.languageCode
else if IsString(firstFormat.audioTrack.id)
' ID is in the format "CODE.DIGIT" e.g. "en.4"
adaptationSetAttributes["lang"] = firstFormat.audioTrack.id.split(".")[0]
end if
end if
' Hoist common attributes
codecs = m.HoistCodecs(group, hoisted)
if IsString(codecs)
adaptationSetAttributes["codecs"] = codecs
end if
audioSampleRate = m.HoistNumberAttribute(group, "audioSampleRate", hoisted)
if IsInt(audioSampleRate)
adaptationSetAttributes["audioSamplingRate"] = audioSampleRate
end if
if xml.Node("AdaptationSet", adaptationSetAttributes)
xml.EmptyNode("Role", {
"schemeIdUri": "urn:mpeg:dash:role:2011"
"value": audioSet.acont = "original" ? "main" : "alternate"
})
for i = 0 to audioStreams.Count() - 1
stream = audioStreams[i]
streamMimeType = stream.type.Tokenize(";")[0]
if streamMimeType <> audioSet.mimeType or stream.languageInfo.lang <> audioSet.lang or stream.languageInfo.acont <> audioSet.acont
continue for
end if
codecs = stream.type.split("codecs=")[1]
if codecs.startsWith(`"`)
codecs = codecs.mid(1)
end if
if codecs.endsWith(`"`)
codecs = codecs.left(codecs.len() - 1)
end if
if xml.Node("Representation", {
"id": stream.itag
"codecs": codecs
"bandwidth": stream.bitrate
})
xml.EmptyNode("AudioChannelConfiguration", {
"schemeIdUri": "urn:mpeg:dash:23003:3:audio_channel_configuration:2011"
"value": `${stream.audioChannels}`
})
if StringUtils.IsNullOrEmpty(stream.url)
xml.Comment(`[ERROR] Stream.url is null or empty for itag: ${stream.itag}`)
else if stream.url.InStr("yt_live_broadcast") <> -1 or stream.url.InStr("yt_premiere_broadcast") <> -1
xml.Comment(`[WARN] Stream URL indicates a live broadcast for itag: ${stream.itag}`)
if IsArray(firstFormat.drmFamilies)
for each drmFamily in firstFormat.drmFamilies
systemId = m.GetDrmSystemId(drmFamily)
if IsString(systemId)
xml.EmptyNode("ContentProtection", { "schemeIdUri": `urn:uuid:${systemId}` })
end if
xml.TextNode("BaseURL", ValidString(stream.url))
end for
end if
if StringUtils.IsNullOrEmpty(stream.index) or StringUtils.IsNullOrEmpty(stream.init)
xml.Comment(`[ERROR] Stream index: ${stream.index}, init: ${stream.init} is invalid for itag: ${stream.itag}`)
if IsAssociativeArray(firstFormat.audioTrack) or firstFormat.isDrc = true
' Roles
roles = m.GetTrackRoles(firstFormat)
for each role in roles
xml.EmptyNode("Role", { "schemeIdUri": "urn:mpeg:dash:role:2011", "value": role })
end for
' Label
if IsAssociativeArray(firstFormat.audioTrack) and IsString(firstFormat.audioTrack.displayName)
displayName = firstFormat.audioTrack.displayName
if firstFormat.isDrc = true
displayName = `${displayName} (Stable Volume)`
end if
if xml.Node("SegmentBase", { "indexRange": stream.index })
xml.EmptyNode("Initialization", { "range": stream.init })
xml.End()
end if
xml.Node("Label", { "id": id })
xml.Text(displayName)
xml.End()
end if
end for
end if
xml.End()
end if
' AudioChannelConfiguration
channels = m.HoistAudioChannels(group, hoisted)
if IsInt(channels)
xml.EmptyNode("AudioChannelConfiguration", {
"schemeIdUri": "urn:mpeg:dash:23003:3:audio_channel_configuration:2011"
"value": channels
})
end if
id += 1
end for
return id
end function
function generateVideoAdaptationSets(xml as object, videoMimeTypes as object, videoStreams as object, id as integer) as integer
for each mimeType in videoMimeTypes
if xml.Node("AdaptationSet", {
"id": `${id}`
"mimeType": mimeType
"startWithSAP": "1"
"subsegmentAlignment": "true"
})
for i = 0 to videoStreams.Count() - 1
stream = videoStreams[i]
streamMimeType = stream.type.Tokenize(";")[0]
if streamMimeType <> mimeType
continue for
for each stream in group
representationId = stream.itag
if IsAssociativeArray(stream.audioTrack) and IsString(stream.audioTrack.id)
representationId = `${representationId}-${stream.audioTrack.id}`
end if
codecs = stream.type.split("codecs=")[1]
if codecs.startsWith(`"`)
codecs = codecs.mid(1)
end if
if codecs.endsWith(`"`)
codecs = codecs.left(codecs.len() - 1)
if stream.isDrc = true
representationId = `${representationId}-drc`
end if
representationAttributes = {
"id": stream.itag
"codecs": codecs
"startWithSAP": "1"
"maxPlayoutRate": "1"
"id": representationId
"bandwidth": stream.bitrate
}
if stream.width <> invalid
representationAttributes["width"] = `${stream.width}`
if hoisted["codecs"] = invalid and (stream.type.inStr("codecs=") <> -1)
representationAttributes["codecs"] = stream.type.split("codecs=")[1].replace(`"`, "").replace(`"`, "")
end if
if stream.height <> invalid
representationAttributes["height"] = `${stream.height}`
end if
if stream.fps <> invalid
representationAttributes["frameRate"] = `${stream.fps}`
if hoisted["audioSampleRate"] = invalid
representationAttributes["audioSamplingRate"] = stream.audioSampleRate
end if
if xml.Node("Representation", representationAttributes)
m.AddColorInfo(stream, xml)
if StringUtils.IsNullOrEmpty(stream.url)
xml.Comment(`[ERROR] Stream.url is null or empty for itag: ${stream.itag}`)
else if stream.url.InStr("yt_live_broadcast") <> -1 or stream.url.InStr("yt_premiere_broadcast") <> -1
xml.Comment(`[WARN] Stream URL indicates a live broadcast for itag: ${stream.itag}`)
end if
xml.TextNode("BaseURL", ValidString(stream.url))
if StringUtils.IsNullOrEmpty(stream.index) or StringUtils.IsNullOrEmpty(stream.init)
xml.Comment(`[ERROR] Stream index: ${stream.index}, init: ${stream.init} is invalid for itag: ${stream.itag}`)
end if
if xml.Node("SegmentBase", { "indexRange": stream.index })
xml.EmptyNode("Initialization", { "range": stream.init })
xml.End()
if hoisted["AudioChannelConfiguration"] = invalid and IsInt(stream.audioChannels)
xml.EmptyNode("AudioChannelConfiguration", {
"schemeIdUri": "urn:mpeg:dash:23003:3:audio_channel_configuration:2011"
"value": stream.audioChannels
})
end if
m.GenerateSegmentInformation(xml, stream, metadata)
xml.End()
end if
end for
xml.End()
end if
id += 1
end for
return id
end function
function GenerateVideoAdaptationSets(xml as object, videoGroups as object, id as integer, metadata as object) as integer
for each group in videoGroups
firstFormat = group[0]
hoisted = {}
adaptationSetAttributes = {
"id": `${id}`
"mimeType": firstFormat.type.Tokenize(";")[0]
"startWithSAP": "1"
"subsegmentAlignment": "true"
"maxPlayoutRate": "1"
"contentType": "video"
}
' Hoist common attributes
codecs = m.HoistCodecs(group, hoisted)
if IsString(codecs)
adaptationSetAttributes["codecs"] = codecs
end if
fps = m.HoistNumberAttribute(group, "fps", hoisted)
if fps <> invalid
adaptationSetAttributes["frameRate"] = fps
end if
if xml.Node("AdaptationSet", adaptationSetAttributes)
if IsArray(firstFormat.drmFamilies)
for each drmFamily in firstFormat.drmFamilies
systemId = m.GetDrmSystemId(drmFamily)
if IsString(systemId)
xml.EmptyNode("ContentProtection", { "schemeIdUri": `urn:uuid:${systemId}` })
end if
end for
end if
m.AddColorInfo(firstFormat, xml)
for each stream in group
representationAttributes = {
"id": stream.itag
"bandwidth": stream.bitrate
}
if stream.width <> invalid
representationAttributes["width"] = stream.width
end if
if stream.height <> invalid
representationAttributes["height"] = stream.height
end if
if hoisted["codecs"] = invalid and (stream.type.inStr("codecs=") <> -1)
representationAttributes["codecs"] = stream.type.split("codecs=")[1].replace(`"`, "").replace(`"`, "")
end if
if hoisted["fps"] = invalid
representationAttributes["frameRate"] = stream.fps
end if
if xml.Node("Representation", representationAttributes)
m.GenerateSegmentInformation(xml, stream, metadata)
xml.End()
end if
end for
@@ -247,7 +455,159 @@ class DashManifest
return id
end function
function generateImageAdaptationSets(xml as object, storyboards as object, id as integer) as integer
function GenerateSegmentInformation(xml as object, stream as object, metadata as object) as void
if StringUtils.IsNullOrEmpty(stream.url)
xml.Comment(`[ERROR] Stream.url is null or empty for itag: ${stream.itag}`)
end if
if metadata.isPostLiveDvr = true
if not IsInt(stream.targetDurationSec)
xml.Comment(`[ERROR] Post-Live DVR stream missing targetDurationSec for itag: ${stream.itag}`)
return
end if
if stream.targetDurationSec < 1
xml.Comment(`[ERROR] Post-Live DVR stream has invalid targetDurationSec (${stream.targetDurationSec}) for itag: ${stream.itag}`)
return
end if
postLiveDvrSegmentCount = metadata.postLiveDvrSegmentCount
if not IsInt(postLiveDvrSegmentCount)
xml.Comment(`[ERROR] Post-Live DVR metadata missing postLiveDvrSegmentCount for itag: ${stream.itag}`)
' We're going to guess segment count from targetDurationSec and total duration
totalDurationMs = m.GetDuration(metadata) * 1000.0
postLiveDvrSegmentCount = MathUtils.Max(Fix(totalDurationMs / (stream.targetDurationSec * 1000)), 1)
xml.Comment(`[INFO] Guessing postLiveDvrSegmentCount as ${postLiveDvrSegmentCount} for itag: ${stream.itag}`)
end if
duration = stream.targetDurationSec * 1000
repeatCount = postLiveDvrSegmentCount - 1
if xml.Node("SegmentTemplate", { "initialization": `${stream.url}&sq=0`, "media": `${stream.url}&sq=$Number$`, "timescale": "1000" })
if xml.Node("SegmentTimeline")
xml.EmptyNode("S", { "d": duration, "r": repeatCount })
xml.End()
end if
xml.End()
end if
else if stream.isTypeOTF = true
segmentDurations = stream.otfSegmentDurations
if not IsArray(segmentDurations)
xml.Comment(`[ERROR] OTF stream missing otfSegmentDurations for itag: ${stream.itag}`)
return
end if
if xml.Node("SegmentTemplate", { "initialization": `${stream.url}&sq=0`, "media": `${stream.url}&sq=$Number$`, "timescale": "1000" })
if xml.Node("SegmentTimeline")
if segmentDurations.Count() = 0
xml.Comment(`[ERROR] OTF stream has empty otfSegmentDurations for itag: ${stream.itag}`)
end if
for each segment in segmentDurations
xml.EmptyNode("S", segment)
end for
xml.End()
end if
xml.End()
end if
else
xml.TextNode("BaseURL", ValidString(stream.url))
if StringUtils.IsNullOrEmpty(stream.index) or StringUtils.IsNullOrEmpty(stream.init)
xml.Comment(`[ERROR] Stream index: ${stream.index}, init: ${stream.init} is invalid for itag: ${stream.itag}`)
end if
if xml.Node("SegmentBase", { "indexRange": stream.index })
xml.EmptyNode("Initialization", { "range": stream.init })
xml.End()
end if
end if
end function
function HoistCodecs(formats as object, hoisted as object) as dynamic
if formats.Count() < 2
return invalid
end if
firstCodec = formats[0].type.split("codecs=")[1]
for i = 1 to formats.Count() - 1
currentCodec = formats[i].type.split("codecs=")[1]
if firstCodec <> currentCodec
return invalid
end if
end for
hoisted["codecs"] = true
return firstCodec.replace(`"`, "").replace(`"`, "")
end function
function HoistNumberAttribute(formats as object, property as string, hoisted as object) as dynamic
if formats.Count() < 2
return invalid
end if
firstFormat = formats[0]
if firstFormat[property] = invalid
return invalid
end if
firstValue = firstFormat[property]
for i = 1 to formats.Count() - 1
otherValue = formats[i][property]
if type(otherValue) <> type(firstValue) or otherValue <> firstValue
return invalid
end if
end for
hoisted[property] = true
return firstValue
end function
function HoistAudioChannels(formats as object, hoisted as object) as dynamic
if formats.Count() < 2
return invalid
end if
firstValue = formats[0].audioChannels
if firstValue = invalid
firstValue = 2
end if
for i = 1 to formats.Count() - 1
currentValue = formats[i].audioChannels
if currentValue = invalid
currentValue = 2
end if
if currentValue <> firstValue
return invalid
end if
end for
hoisted["AudioChannelConfiguration"] = true
return firstValue
end function
function GetTrackRoles(format as object) as object
roles = []
if format.isOriginal = true
roles.Push("main")
else
roles.Push("alternate")
end if
if format.isDubbed = true or format.isAutoDubbed = true
roles.Push("dub")
end if
if format.isDescriptive = true
roles.Push("description")
end if
if format.isDrc = true
roles.Push("enhanced-audio-intelligibility")
end if
return roles
end function
function GenerateImageAdaptationSets(xml as object, storyboards as object, id as integer) as integer
' https://developer.roku.com/en-ca/docs/developer-program/media-playback/trick-mode/hls-and-dash.md#dash-standard-thumbnail-tiles
for i = storyboards.Count() - 1 to 0 step -1
storyboard = storyboards[i]
@@ -322,169 +682,6 @@ class DashManifest
return id
end function
function getAudioStreams(streams as object) as object
audioStreams = []
for i = 0 to streams.Count() - 1
stream = streams[i]
if stream.type.startsWith("audio/")
if StringUtils.IsNullOrEmpty(stream.bitrate)
LogWarnNoTelemetry("Invalid audio stream bitrate, itag:", stream.itag)
continue for
end if
if StringUtils.IsNullOrEmpty(stream.init)
LogWarnNoTelemetry("Invalid audio stream init, itag:", stream.itag)
continue for
end if
if StringUtils.IsNullOrEmpty(stream.index)
LogWarnNoTelemetry("Invalid audio stream index, itag:", stream.itag)
continue for
end if
stream.languageInfo = m.ParseAudioLanguage(stream.url)
audioStreams.Push(stream)
end if
end for
audioStreams.SortBy("bitrate", "r")
return audioStreams
end function
function getVideoStreams(streams as object, qualityFilter as object) as object
videoStreams = []
for i = 0 to streams.Count() - 1
if not m.isVideoFormatIncluded(streams[i], qualityFilter)
continue for
end if
stream = streams[i]
if stream.type.startsWith("video/")
if StringUtils.IsNullOrEmpty(stream.bitrate)
LogWarnNoTelemetry("Invalid video stream bitrate, itag:", stream.itag)
continue for
end if
if StringUtils.IsNullOrEmpty(stream.init)
LogWarnNoTelemetry("Invalid video stream init, itag:", stream.itag)
continue for
end if
if StringUtils.IsNullOrEmpty(stream.index)
LogWarnNoTelemetry("Invalid video stream index, itag:", stream.itag)
continue for
end if
if (stream.width = invalid or stream.height = invalid) and not StringUtils.IsNullOrEmpty(stream.size)
if stream.size.instr("x") > 0
parts = stream.size.Tokenize("x")
if parts.Count() = 2
stream.width = ValidInt(parts[0].toInt())
stream.height = ValidInt(parts[1].toInt())
end if
end if
end if
videoStreams.Push(stream)
end if
end for
videoStreams.SortBy("bitrate", "r")
return videoStreams
end function
function isVideoFormatIncluded(stream as object, qualityFilter as object) as boolean
if qualityFilter.Count() = 0
return true
end if
qualityLabel = stream.qualityLabel
if not StringUtils.IsNullOrEmpty(qualityLabel)
pIndex = qualityLabel.InStr("p")
if pIndex <> -1
qualityLabel = qualityLabel.Mid(0, pIndex)
end if
if qualityFilter[qualityLabel] = true
return true
end if
end if
resolution = stream.resolution
if not StringUtils.IsNullOrEmpty(resolution)
pIndex = resolution.InStr("p")
if pIndex <> -1
resolution = resolution.Mid(0, pIndex)
end if
if qualityFilter[resolution] = true
return true
end if
end if
size = stream.size
if not StringUtils.IsNullOrEmpty(size)
size = size.Split("x")
if size.Count() = 2
if qualityFilter[size[1]] = true
return true
end if
end if
end if
return false
end function
function getMimeTypes(streams as object) as object
mimeTypes = {}
for i = 0 to streams.Count() - 1
stream = streams[i]
mimeType = stream.type.Tokenize(";")[0]
mimeTypes[mimeType] = true
end for
return mimeTypes.Keys()
end function
function getMimeTypeLanguageCombos(streams as object) as object
types = {}
for i = 0 to streams.Count() - 1
stream = streams[i]
mimeType = stream.type.Tokenize(";")[0]
types[`${mimeType}-${stream.languageInfo.lang}-${stream.languageInfo.acont}`] = {
"mimeType": mimeType
"lang": stream.languageInfo.lang
"acont": stream.languageInfo.acont
}
end for
combos = []
for each t in types
combos.Push(types[t])
end for
return combos
end function
function ParseAudioLanguage(url as dynamic) as object
result = { lang: "", acont: "" }
if StringUtils.IsNullOrEmpty(url)
return result
end if
queryParams = UrlUtils.ParseQueryComponents(url)
if StringUtils.IsNullOrEmpty(queryParams["xtags"])
return result
end if
xtags = queryParams["xtags"].split(":")
for each xtag in xtags
if xtag.instr("=") > 0
parts = xtag.split("=")
if parts.Count() = 2
if parts[0] = "lang"
result["lang"] = parts[1]
end if
if parts[0] = "acont"
result["acont"] = parts[1]
end if
end if
end if
end for
return result
end function
function AddColorInfo(videoStream as object, xml as object) as void
if videoStream.colorInfo = invalid
return
@@ -493,7 +690,7 @@ class DashManifest
if videoStream.colorInfo.primaries <> invalid
primaries = m.colorInfo.primaries[videoStream.colorInfo.primaries]
if primaries <> invalid
xml.EmptyNode("EssentialProperty", {
xml.EmptyNode("SupplementalProperty", {
"schemeIdUri": "urn:mpeg:mpegB:cicp:ColourPrimaries"
"value": primaries
})
@@ -505,7 +702,7 @@ class DashManifest
if videoStream.colorInfo.transferCharacteristics <> invalid
transferCharacteristics = m.colorInfo.transferCharacteristics[videoStream.colorInfo.transferCharacteristics]
if transferCharacteristics <> invalid
xml.EmptyNode("EssentialProperty", {
xml.EmptyNode("SupplementalProperty", {
"schemeIdUri": "urn:mpeg:mpegB:cicp:TransferCharacteristics"
"value": transferCharacteristics
})
@@ -517,7 +714,7 @@ class DashManifest
if videoStream.colorInfo.matrixCoefficients <> invalid
matrixCoefficients = m.colorInfo.matrixCoefficients[videoStream.colorInfo.matrixCoefficients]
if matrixCoefficients <> invalid
xml.EmptyNode("EssentialProperty", {
xml.EmptyNode("SupplementalProperty", {
"schemeIdUri": "urn:mpeg:mpegB:cicp:MatrixCoefficients"
"value": matrixCoefficients
})
@@ -527,4 +724,81 @@ class DashManifest
end if
end function
function GetXtagsInfo(format as object) as object
result = {
lang: ""
acont: ""
isDrc: false
isDubbed: false
isAutoDubbed: false
isDescriptive: false
isSecondary: false
isOriginal: false
}
if StringUtils.IsNullOrEmpty(format.url)
return result
end if
' Technically format.xtags can be used, but it is protobuf encoded
' so this is simpler. Also, this is consistent for both local
' Innertube and Invidious.
queryParams = UrlUtils.ParseQueryComponents(format.url)
xtagsString = queryParams["xtags"]
if StringUtils.IsNullOrEmpty(xtagsString)
return result
end if
tags = {}
xtagsList = xtagsString.split(":")
for each xtag in xtagsList
pair = xtag.split("=")
if pair.Count() = 2
tags[pair[0]] = pair[1]
end if
end for
for each key in tags
if key = "lang"
result.lang = tags[key]
else if key = "acont"
result.acont = tags[key]
else if key = "drc" and tags[key] = "1"
result.isDrc = true
end if
end for
if format.isDrc = true
result.isDrc = true
end if
if result.acont = "dubbed"
result.isDubbed = true
else if result.acont = "dubbed-auto"
result.isAutoDubbed = true
else if result.acont = "descriptive"
result.isDescriptive = true
else if result.acont = "secondary"
result.isSecondary = true
end if
if result.acont = "original" or (not result.isDubbed and not result.isAutoDubbed and not result.isDescriptive and not result.isSecondary)
result.isOriginal = true
end if
return result
end function
function GetDrmSystemId(drmFamily as dynamic) as dynamic
if not IsString(drmFamily)
return invalid
end if
if drmFamily = "WIDEVINE"
return "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
else if drmFamily = "PLAYREADY"
return "9a04f079-9840-4286-ab92-e65be0885f95"
end if
return invalid
end function
end class
@@ -81,16 +81,16 @@ namespace InnertubeService
end if
playerResponseJson = playerResponse.Json()
isLive = Innertube.IsLiveStream(playerResponseJson)
if isLive and client = Innertube.ClientType.Tv
LogDebug("Live video detected, falling back to iOS for HLS streams.")
notDashSupported = Innertube.IsLiveStream(playerResponseJson)
if notDashSupported and client = Innertube.ClientType.Tv
LogDebug("Falling back to iOS client for live video.")
isLoggedIn = Innertube.ParseIsLoggedIn(playerResponseJson)
playbackTrackingUrls = Innertube.ParsePlaybackTrackingUrls(playerResponseJson, isLoggedIn)
client = Innertube.ClientType.IOS
continue while
end if
parsedResponse = Innertube.ParseInnertubePlayerResponse(playerRequest, playerResponse, {}, cancellation)
parsedResponse = Innertube.ParseInnertubePlayerResponse(playerRequest, playerResponse, client, cancellation)
if parsedResponse.error = invalid
exit while
@@ -267,61 +267,6 @@ namespace InnertubeService
return Innertube.Search(query, options)
end function
function GetTrending(options = invalid as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
trendingType = LCase(OptionUtils.GetOrDefault(options, "type", ""))
disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false)
raw = OptionUtils.GetOrDefault(options, "raw", false)
params = ""
if trendingType = "music"
' {"44:proto": {"3:string": "ytma_charts"}}
params = "4gINGgt5dG1hX2NoYXJ0cw%3D%3D"
else if trendingType = "gaming"
' {"44:proto": {"3:string": "gaming_corpus_most_popular"}}
params = "4gIcGhpnYW1pbmdfY29ycHVzX21vc3RfcG9wdWxhcg%3D%3D"
else if trendingType = "movies"
' {"44:proto": {"3:string": "trailers"}}
params = "4gIKGgh0cmFpbGVycw%3D%3D"
end if
request = Innertube.CreateBrowseRequest("FEtrending", Innertube.ClientType.WEB, { params: params })
request.Cancellation(cancellation)
if raw
request.LogCurlCommand(true)
request.NoCache()
end if
response = request.Await()
if not response.IsSuccess()
return {
error: response.ErrorMessage()
}
end if
if raw
return response.Json()
end if
feeds = Innertube.ParseResponseDataForFeeds(response.Json(), {
response: response
disableCreatorOnTheRise: true
disableShorts: disableShorts
})
result = {
feeds: feeds
}
cacheControl = Innertube.ParseResponseForCacheControl(response)
if cacheControl <> invalid
result["cache-control"] = cacheControl
end if
return result
end function
function GetHome(options = invalid as object) as object
return GetBrowseAuthenticatedPage("FEwhat_to_watch", options)
end function
@@ -338,12 +283,12 @@ namespace InnertubeService
return GetBrowseAuthenticatedPage("FEplaylist_aggregation", options)
end function
function GetBrowseAuthenticatedPage(browserId as string, options = invalid as object) as object
function GetBrowseAuthenticatedPage(browseId as string, options = invalid as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
accessToken = OptionUtils.Get(options, "accessToken")
disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false)
request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv, options)
request = Innertube.CreateBrowseRequest(browseId, Innertube.ClientType.Tv, options)
if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken)
@@ -360,6 +305,7 @@ namespace InnertubeService
feeds = Innertube.ParseResponseDataForFeeds(response.Json(), {
response: response
disableShorts: disableShorts
browseId: browseId
})
result = {
@@ -521,7 +467,7 @@ namespace InnertubeService
return response.Json()
end if
result = Innertube.ParseChannelPageResponseData(response.Json(), response)
result = Innertube.ParseChannelPageResponseData(channelId, response.Json(), response)
if result.authorId = invalid and result.error = invalid
result["authorId"] = channelId
end if
@@ -663,7 +609,7 @@ namespace InnertubeService
return response.Json()
end if
result = Innertube.ParsePlaylistPageResponseData(response.Json(), response)
result = Innertube.ParsePlaylistPageResponseData(playlistId, response.Json(), response)
if result.playlistId = invalid and result.error = invalid
result["playlistId"] = playlistId
@@ -93,18 +93,18 @@ namespace Innertube
"tvSurfaceContentContinuation": ParseTvSurfaceContentContinuation
"gridButtonRenderer": ParseGridButtonRenderer
"movieRenderer": ParseMovieRenderer
"gridMovieRenderer": ParseGridMovieRenderer
"compactMovieRenderer": ParseCompactMovieRenderer
"horizontalMovieListRenderer": ParseHorizontalMovieListRenderer
' Movies and shows are partially supported, but these renderers are not yet implemented.
' "horizontalMovieListRenderer": ParseNotImplemented
' "gridMovieRenderer": ParseNotImplemented
' "gridShowRenderer": ParseNotImplemented
' "playlistShowMetadataRenderer": ParseNotImplemented
' Ignored nodes:
' TODO:P2 handle navigateAction - which are usually a redirect
' "navigateAction": ParseNotImplemented
' TODO:P2 radioRenderer seems like a Mix https://github.com/iBicha/playlet/issues/709
' "radioRenderer": ParseNotImplemented
' "compactRadioRenderer": ParseNotImplemented
"radioRenderer": ParseRadioRenderer
"compactRadioRenderer": ParseCompactRadioRenderer
' TODO:P2 A carousel of videos, found on the home tab of a channel.
' Should probably be parsed.
' "carouselItemRenderer": ParseNotImplemented
@@ -163,6 +163,7 @@ namespace Innertube
"emergencyOneboxRenderer": ParseNotImplemented
' Suicide & crisis lifeline, within search
"searchFrictionViewModel": ParseNotImplemented
"shoppingTimelyShelfViewModel": ParseNotImplemented
"backstagePostRenderer": ParseNotImplemented
"backstagePostThreadRenderer": ParseNotImplemented
"counterfactualRenderer": ParseNotImplemented
@@ -251,6 +252,15 @@ namespace Innertube
context.currentFeed.sortOptions = sortOptions
end if
end if
continuation = ObjectUtils.Dig(nodeData, ["continuations", 0, "nextContinuationData", "continuation"])
if IsString(continuation)
if not StringUtils.IsNullOrEmpty(context.currentFeed.continuation)
StartNewFeed("", context)
end if
context.currentFeed.continuation = continuation
end if
return nodeData["contents"]
end function
@@ -276,6 +286,17 @@ namespace Innertube
end if
end if
if ValidString(context.browseId) = "FEwhat_to_watch"
' shelfs with a heroCarouselHeaderRenderer are usually big carousels at the top of the home page
' to advertise some paid content.
' They hijack the shelf we want to parse (e.g. Recommended videos).
heroCarouselHeader = ObjectUtils.Dig(nodeData, ["headerRenderer", "heroCarouselHeaderRenderer"])
if heroCarouselHeader <> invalid
LogInfo("Skipping shelf with heroCarouselHeaderRenderer")
return invalid
end if
end if
' TODO: handle shelfRenderer.title
' TODO: handle shelfRenderer.headerRenderer.shelfHeaderRenderer.avatarLockup.avatarLockupRenderer.title
return nodeData["content"]
@@ -997,6 +1018,63 @@ namespace Innertube
return invalid
end function
function ParseRadioRenderer(nodeData as object, context as object) as object
playlistId = nodeData["playlistId"]
if not IsString(playlistId)
Warning("Invalid playlist ID in radioRenderer", nodeData, context)
return invalid
end if
videoCountText = ParseText(nodeData["videoCountText"])
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 ParseCompactRadioRenderer(nodeData as object, context as object) as object
playlistId = nodeData["playlistId"]
if not IsString(playlistId)
Warning("Invalid playlist ID in compactRadioRenderer", nodeData, context)
return invalid
end if
videoCountText = ParseText(nodeData["videoCountText"])
if videoCountText = ""
videoCountText = ParseText(nodeData["videoCountShortText"])
end if
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": ParseText(nodeData["title"])
"playlistThumbnail": ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails", 0, "url"])
"videoCountText": videoCountText
}
' Mixes have a videoId, which is the first video in the mix
videoId = ObjectUtils.Dig(nodeData, ["navigationEndpoint", "watchEndpoint", "videoId"])
if IsString(videoId)
playlist["videoId"] = videoId
end if
PushFeedItem(playlist, context)
return invalid
end function
function ParseGridShelfViewModel(nodeData as object, _context as object) as object
return nodeData["contents"]
end function
@@ -1006,8 +1084,6 @@ namespace Innertube
if contentType = "LOCKUP_CONTENT_TYPE_VIDEO"
return LockupViewModelTypeVideo(nodeData, context)
else if contentType = "LOCKUP_CONTENT_TYPE_SHORT"
' Additional capture for LOCKUP_CONTENT_TYPE_SHORT
Warning(`Unknown content type: ${contentType}`, nodeData, context)
return LockupViewModelTypeShort(nodeData, context)
else if contentType = "LOCKUP_CONTENT_TYPE_PLAYLIST"
return LockupViewModelTypePlaylist(nodeData, context)
@@ -1102,6 +1178,16 @@ namespace Innertube
title = ObjectUtils.Dig(metadata, ["title", "content"])
authorId = ObjectUtils.Dig(metadata, ["image", "decoratedAvatarViewModel", "rendererContext", "commandContext", "onTap", "innertubeCommand", "browseEndpoint", "browseId"])
thumbnailViewModel = ObjectUtils.Dig(nodeData, ["contentImage", "thumbnailViewModel"])
if context.generateVideoThumbnails = true
videoThumbnails = GenerateVideoThumbnails(videoId)
else
videoThumbnails = ObjectUtils.Dig(thumbnailViewModel, ["image", "sources"])
if videoThumbnails = invalid
videoThumbnails = GenerateVideoThumbnails(videoId)
end if
end if
lines = invalid
contentMetadataViewModel = ObjectUtils.Dig(metadata, ["metadata", "contentMetadataViewModel"])
metadataRows = ObjectUtils.Dig(contentMetadataViewModel, ["metadataRows"])
@@ -1128,7 +1214,7 @@ namespace Innertube
"title": title
"authorId": authorId
"lines": lines
"videoThumbnails": GenerateVideoThumbnails(videoId)
"videoThumbnails": videoThumbnails
}
PushFeedItem(video, context)
@@ -1332,6 +1418,13 @@ namespace Innertube
return invalid
end if
' YouTube promo (purchase premium, etc) tileRenderer
thumbailUrl = ValidString(ObjectUtils.Dig(nodeData, ["header", "tileHeaderRenderer", "thumbnail", "thumbnails", 0, "url"]))
if thumbailUrl.InStr("gstatic.com/youtube/img/promos") <> -1
LogWarnNoTelemetry("Skipping tileRenderer without contentType for YouTube promo")
return invalid
end if
' "More news" tileRenderer
browseId = ValidString(ObjectUtils.Dig(nodeData, ["onSelectCommand", "browseEndpoint", "browseId"]))
if browseId = "FEtopics_news"
@@ -1354,10 +1447,12 @@ namespace Innertube
else if contentType = "TILE_CONTENT_TYPE_PLAYLIST"
return TileRendererTypePlaylist(nodeData, context)
else if contentType = "TILE_CONTENT_TYPE_CHANNEL"
' Not implemented yet - https://github.com/iBicha/playlet/issues/724
return invalid
return TileRendererTypeChannel(nodeData, context)
else if contentType = "TILE_CONTENT_TYPE_EDU"
' Not implemented yet - https://github.com/iBicha/playlet/issues/751
' Basically a tile that redirects to a search with predifined querty.
' To support, Playlet will probably need to implement an independent
' search view that can be opened from anywhere.
return invalid
end if
@@ -1558,6 +1653,42 @@ namespace Innertube
return invalid
end function
function TileRendererTypeChannel(nodeData as object, context as object) as object
channelId = nodeData["contentId"]
if not IsString(channelId)
Warning("Invalid channel ID in tileRendererTypeChannel", nodeData, context)
return invalid
end if
' TODO:P1 Channel IDs starting with "SC" are shows, not supported yet.
if channelId.StartsWith("SC")
LogWarnNoTelemetry("Shows are not supported yet in TileRendererTypeChannel")
return invalid
end if
renderedLines = []
lines = ObjectUtils.Dig(nodeData, ["metadata", "tileMetadataRenderer", "lines"])
if IsArray(lines)
for each line in lines
if not IsAssociativeArray(line)
continue for
end if
renderedLines.Push(ParseLineRenderer(line["lineRenderer"]))
end for
end if
channel = {
"type": "channel"
"authorId": channelId
"author": ParseText(ObjectUtils.Dig(nodeData, ["metadata", "tileMetadataRenderer", "title"]))
"authorThumbnails": ObjectUtils.Dig(nodeData, ["header", "tileHeaderRenderer", "thumbnail", "thumbnails"])
"lines": renderedLines
}
PushFeedItem(channel, context)
return invalid
end function
function ParseTileRendererAuthorId(nodeData as object) as dynamic
' We're checking in the long press menu if there's a browseId that starts with "UC".
' This is usually the the id of the channel.
@@ -1760,9 +1891,64 @@ namespace Innertube
return invalid
end function
function ParseGridMovieRenderer(nodeData as object, context as object) as object
videoId = nodeData["videoId"]
if not IsString(videoId)
Warning("Invalid videoId in gridMovieRenderer", nodeData, context)
return invalid
end if
title = ParseText(nodeData["title"])
metadata = ParseText(nodeData["metadata"])
author = invalid
authorId = invalid
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
lines = invalid
if metadata <> ""
lines = [author, metadata]
end if
lengthText = ParseText(nodeData["lengthText"])
if lengthText = ""
thumbnailOverlays = nodeData["thumbnailOverlays"]
if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays
parsedTimeStatusRenderer = ParseThumbnailOverlayTimeStatusRenderer(overlay)
if parsedTimeStatusRenderer <> invalid
lengthText = parsedTimeStatusRenderer.text
if lengthText <> ""
exit for
end if
end if
end for
end if
end if
video = {
"type": "video"
"videoId": videoId
"title": title
"author": author
"authorId": authorId
"videoThumbnails": GenerateVideoThumbnails(videoId)
"lines": lines
"lengthText": lengthText
}
PushFeedItem(video, context)
return invalid
end function
function ParseCompactMovieRenderer(nodeData as object, context as object) as object
videoId = nodeData["videoId"]
if not IsString(videoId)
' TODO:P2 Can be a show, example
' {"badges":[{"metadataBadgeRenderer":{"accessibilityData":{"label":"Free with ads"},"label":"Free with ads","style":"BADGE_STYLE_TYPE_YPC","trackingParams":"CKQBEJaLARgJIhMI15bJgdLnkAMVoHtMCB0nGTYG"}},{"metadataBadgeRenderer":{"accessibilityData":{"label":"tv-g"},"label":"TV-G","style":"BADGE_STYLE_TYPE_MEDIA","trackingParams":"CKQBEJaLARgJIhMI15bJgdLnkAMVoHtMCB0nGTYG"}}],"navigationEndpoint":{"browseEndpoint":{"browseId":"SCLKZr4NmdhyFZXLCYhehRmg","params":"kgYcGhoSGFVDTEtacjRObWRoeUZaWExDWWhlaFJtZw%3D%3D"},"clickTrackingParams":"CKQBEJaLARgJIhMI15bJgdLnkAMVoHtMCB0nGTYGygEEl7wVRg==","commandMetadata":{"webCommandMetadata":{"apiUrl":"/youtubei/v1/browse","rootVe":6827,"url":"/show/SCLKZr4NmdhyFZXLCYhehRmg?sbp=GhoSGFVDTEtacjRObWRoeUZaWExDWWhlaFJtZw%253D%253D","webPageType":"WEB_PAGE_TYPE_BROWSE"}}},"thumbnail":{"thumbnails":[{"height":596,"url":"https://yt3.ggpht.com/KPRERPv8FmjHUtaEip00aL1RuIkU-0_YR4XrbzG_66s6kkm1sx9MtSJgzeYexpRVtXoN1P1OjQ=w1060-fcrop64=1,00000000ffffffff-k-c0xffffffff-no-nd-rj","width":1060}]},"thumbnailOverlays":[{"thumbnailOverlayBottomPanelRenderer":{"text":{"runs":[{"text":"4"},{"text":" seasons"}]}}}],"title":{"accessibility":{"accessibilityData":{"label":"Everything's Rosie 4 seasons"}},"simpleText":"Everything's Rosie"},"topMetadataItems":[{"simpleText":"Animation \u2022 2011"}],"trackingParams":"CKQBEJaLARgJIhMI15bJgdLnkAMVoHtMCB0nGTYG"}
Warning("Invalid videoId in compactMovieRenderer", nodeData, context)
return invalid
end if
@@ -1802,6 +1988,10 @@ namespace Innertube
return invalid
end function
function ParseHorizontalMovieListRenderer(nodeData as object, _context as object) as object
return nodeData["items"]
end function
function ParseText(data as dynamic) as string
if IsString(data)
return data
@@ -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
end function
function ParseChannelPageResponseData(responseData as object, response as object) as object
function ParseChannelPageResponseData(browseId as string, responseData as object, response as object) as object
if responseData = invalid
return {
error: "Invalid response data"
@@ -63,6 +63,9 @@ namespace Innertube
author = ObjectUtils.Dig(responseData, ["header", "pageHeaderRenderer", "pageTitle"])
end if
authorId = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "externalId"])
if StringUtils.IsNullOrEmpty(authorId)
authorId = browseId
end if
thumbnails = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "avatar", "thumbnails"])
if thumbnails = invalid
@@ -149,6 +152,7 @@ namespace Innertube
response: response
"currentAuthor": author
"currentAuthorId": authorId
browseId: browseId
})
if feeds.Count() > 0
items = ValidArray(feeds[0].items)
@@ -183,7 +187,7 @@ namespace Innertube
return channel
end function
function ParsePlaylistPageResponseData(responseData as object, response as object) as object
function ParsePlaylistPageResponseData(browseId as string, responseData as object, response as object) as object
if responseData = invalid
return {
error: "Invalid response data"
@@ -251,13 +255,16 @@ namespace Innertube
end if
end if
if StringUtils.IsNullOrEmpty(playlistId)
playlistId = browseId
end if
playlist = {
"playlistId": playlistId
"videoCount": videoCount
"videos": []
}
if playlistId <> invalid
playlist["playlistId"] = playlistId
end if
if title <> invalid
playlist["title"] = title
end if
@@ -279,6 +286,7 @@ namespace Innertube
feeds = ParseResponseDataForFeeds(responseData, {
response: response
browseId: browseId
})
if feeds.Count() > 0
playlist["videos"] = ValidArray(feeds[0].items)
@@ -1,5 +1,6 @@
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/components/Services/Innertube/NodesParser.bs"
import "pkg:/components/Services/Innertube/OTFSegmentInfo.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/Types.bs"
@@ -22,6 +23,12 @@ namespace Innertube
context = Innertube.CreateContext(client, deviceInfo, options)
if client = Innertube.ClientType.TV
referer = "https://www.youtube.com/tv#/watch?v=" + videoId
else
referer = "https://www.youtube.com/watch?v=" + videoId
end if
payload = {
"videoId": videoId
"context": context
@@ -30,13 +37,12 @@ namespace Innertube
"contentPlaybackContext": {
"vis": 0
"splay": false
"referer": "https://www.youtube.com/watch?v=" + videoId
"referer": referer
"currentUrl": "/watch?v=" + videoId
"autonavState": "STATE_ON"
"autoCaptionsDefaultOn": false
"html5Preference": "HTML5_PREF_WANTS"
"lactMilliseconds": "-1"
"isInlinePlaybackNoAd": true
}
}
"attestationRequest": {
@@ -67,9 +73,9 @@ namespace Innertube
return request
end function
function ParseInnertubePlayerResponse(playerRequest as dynamic, playerResponse as dynamic, parsedResponse as object, cancellation as object) as object
function ParseInnertubePlayerResponse(playerRequest as dynamic, playerResponse as dynamic, client as Innertube.ClientType, cancellation as object) as object
WriteAsciiFile("cachefs:/last_player_response.json", playerResponse.Text())
parsedResponse = {}
payload = playerResponse.Json()
error = ParsePlayerResponseForError(payload, playerRequest)
@@ -92,6 +98,7 @@ namespace Innertube
lengthSeconds = videoDetails["lengthSeconds"].ToInt()
isLive = ValidBool(videoDetails["isLive"])
isPostLiveDvr = ValidBool(videoDetails["isPostLiveDvr"])
adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"]))
formats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "formats"]))
@@ -108,13 +115,14 @@ namespace Innertube
end if
hasLiveStreamingData = FormatsHaveLiveStreamingData(adaptiveFormats) or FormatsHaveLiveStreamingData(formats)
isOTF = FormatsHasTypeOTF(adaptiveFormats)
hasDrm = (not StringUtils.IsNullOrEmpty(streamingData.drmParams)) or IsArray(streamingData.licenseInfos)
shouldAnalyze = (not isLive) and (not hasLiveStreamingData) and (not hasDrm)
adaptiveFormats = TransformFormats(adaptiveFormats, shouldAnalyze)
formats = TransformFormats(formats, false)
adaptiveFormats = TransformFormats(adaptiveFormats)
formats = TransformFormats(formats)
parsedResponse["type"] = "video"
parsedResponse["parser"] = "playlet"
parsedResponse["videoId"] = videoDetails["videoId"]
parsedResponse["videoThumbnails"] = videoDetails["thumbnail"]["thumbnails"]
parsedResponse["storyboards"] = ParseStoryboards(payload, lengthSeconds)
@@ -122,6 +130,7 @@ namespace Innertube
parsedResponse["authorId"] = videoDetails["channelId"]
parsedResponse["lengthSeconds"] = lengthSeconds
parsedResponse["liveNow"] = isLive
parsedResponse["isPostLiveDvr"] = isPostLiveDvr
parsedResponse["hasLiveStreamingData"] = hasLiveStreamingData
parsedResponse["hlsUrl"] = streamingData["hlsManifestUrl"]
parsedResponse["dashUrl"] = streamingData["dashManifestUrl"]
@@ -154,6 +163,16 @@ namespace Innertube
parsedResponse["isLoggedIn"] = ParseIsLoggedIn(payload)
parsedResponse["playbackTrackingUrls"] = ParsePlaybackTrackingUrls(payload, parsedResponse.isLoggedIn)
if isPostLiveDvr
LogDebug("Fetching Post-Live DVR info")
GetPostLiveDvrInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, client, cancellation)
end if
if isOTF
LogDebug("Fetching OTF segment info")
OTFGetSegmentInfo(adaptiveFormats, client, cancellation)
end if
return parsedResponse
end function
@@ -298,6 +317,7 @@ namespace Innertube
end if
captions = []
autoCaptions = []
for each track in tracks
if not IsAssociativeArray(track)
continue for
@@ -323,67 +343,52 @@ namespace Innertube
label = ParseText(track["name"])
captions.Push({
thisCaption = {
"label": label
"language_code": languageCode
"url": baseUrl
})
}
if track["kind"] = "asr"
autoCaptions.Push(thisCaption)
continue for
end if
captions.Push(thisCaption)
end for
' Put automatically generated captions at the end so human-generated ones take priority
captions.Append(autoCaptions)
return captions
end function
function TransformFormats(formats as object, analyze as boolean) as object
analysis = invalid
if analyze
analysis = {
"issueDetected": false
}
end if
function TransformFormats(formats as object) as object
result = []
for i = 0 to formats.Count() - 1
result.Push(TransformFormat(formats[i], analysis))
result.Push(TransformFormat(formats[i]))
end for
if analyze and analysis.issueDetected
' Are these OTF streams?
LogTelemetryEvent({
level: "error"
message: `Some formats are missing initRange or indexRange\nFormats: ${FormatJson(formats)}`
fingerprint: ["Some formats are missing initRange or indexRange"]
})
end if
return result
end function
function TransformFormat(fmt as object, analysis as object) as object
function TransformFormat(fmt as object) as object
itag = `${fmt["itag"]}`
result = {
"bitrate": `${fmt["bitrate"]}`
"url": fmt["url"]
"itag": itag
"type": fmt["mimeType"]
"clen": `${fmt["approxDurationMs"]}`
"lmt": `${fmt["lastModified"]}`
}
if fmt["approxDurationMs"] <> invalid
result["approxDurationMs"] = fmt["approxDurationMs"]
end if
if IsAssociativeArray(fmt["initRange"])
result["init"] = `${fmt["initRange"]["start"]}-${fmt["initRange"]["end"]}`
else
result["init"] = ""
if analysis <> invalid
analysis.issueDetected = true
end if
end if
if IsAssociativeArray(fmt["indexRange"])
result["index"] = `${fmt["indexRange"]["start"]}-${fmt["indexRange"]["end"]}`
else
result["index"] = ""
if analysis <> invalid
analysis.issueDetected = true
end if
end if
if fmt["audioQuality"] <> invalid
@@ -403,6 +408,31 @@ namespace Innertube
result["fps"] = ToString(fmt["fps"])
end if
if fmt["colorInfo"] <> invalid
result["colorInfo"] = fmt["colorInfo"]
end if
if fmt["audioTrack"] <> invalid
result["audioTrack"] = fmt["audioTrack"]
end if
if fmt["isDrc"] <> invalid
result["isDrc"] = fmt["isDrc"]
end if
if fmt["targetDurationSec"] <> invalid
result["targetDurationSec"] = fmt["targetDurationSec"]
end if
if ValidString(fmt["type"]) = "FORMAT_STREAM_TYPE_OTF"
result["isTypeOTF"] = true
end if
if fmt["drmFamilies"] <> invalid
result["drmFamilies"] = fmt["drmFamilies"]
end if
if fmt["xtags"] <> invalid
result["xtags"] = fmt["xtags"]
end if
result["width"] = fmt["width"]
result["height"] = fmt["height"]
@@ -424,7 +454,7 @@ namespace Innertube
LogDebug(`ReadAsciiFile("tmp:/sts_cache.json")`)
cache = ReadAsciiFile("tmp:/sts_cache.json")
if not StringUtils.IsNullOrEmpty(cache)
json = ParseJson(cache)
json = StringUtils.ParseJsonSafe(cache)
return json["sts"]
end if
@@ -529,8 +559,7 @@ namespace Innertube
for i = 0 to decipheredFormats.Count() - 1
fmt = formats[i]
decipheredFmt = decipheredFormats[i]
fmt["url"] = decipheredFmt["url"]
fmt["url"] = ResetUrlClientVersion(decipheredFmt["url"])
end for
decipheredAdaptiveFormats = json["adaptiveFormats"]
@@ -544,11 +573,34 @@ namespace Innertube
for i = 0 to decipheredAdaptiveFormats.Count() - 1
fmt = adaptiveFormats[i]
decipheredFmt = decipheredAdaptiveFormats[i]
fmt["url"] = decipheredFmt["url"]
fmt["url"] = ResetUrlClientVersion(decipheredFmt["url"])
end for
return invalid
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
trackingParams = ObjectUtils.Dig(payload, ["responseContext", "serviceTrackingParams"])
if not IsArray(trackingParams)
@@ -598,6 +650,10 @@ namespace Innertube
return true
end if
if ValidBool(ObjectUtils.Dig(payload, ["videoDetails", "isPostLiveDvr"]))
return false
end if
adaptiveFormats = ValidArray(ObjectUtils.Dig(payload, ["streamingData", "adaptiveFormats"]))
if FormatsHaveLiveStreamingData(adaptiveFormats)
return true
@@ -623,4 +679,78 @@ namespace Innertube
return false
end function
function FormatsHasTypeOTF(formats as object) as boolean
if not IsArray(formats)
return false
end if
for each fmt in formats
if ValidString(fmt["type"]) = "FORMAT_STREAM_TYPE_OTF"
return true
end if
end for
return false
end function
function GetPostLiveDvrInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as void
if adaptiveFormats.Count() = 0
LogWarn("GetPostLiveDvrInfo: No adaptive formats available")
return
end if
url = adaptiveFormats[0]["url"]
if StringUtils.IsNullOrEmpty(url)
LogWarn("GetPostLiveDvrInfo: URL is empty")
return
end if
queryComponents = UrlUtils.ParseQueryComponents(url)
queryComponents["rn"] = "0"
queryComponents["sq"] = "0"
if not StringUtils.IsNullOrEmpty(cpn)
queryComponents["cpn"] = cpn
end if
url = UrlUtils.SetQueryParams(url, queryComponents)
request = HttpClient.Head(url)
requestHeaders = Innertube.CreateHeaders(client)
requestHeaders["origin"] = "https://www.youtube.com"
requestHeaders["referer"] = "https://www.youtube.com"
requestHeaders["DNT"] = "?1"
request.Headers(requestHeaders)
request.TryCount(2)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
LogError("Failed to fetch Post-Live DVR info", response.ErrorMessage())
return
end if
headers = response.Headers()
if not headers.DoesExist("X-Head-Time-Millis") or not headers.DoesExist("X-Head-Seqnum")
msg = "GetPostLiveDvrInfo: Missing Post-Live DVR info in headers"
LogErrorNoTelemetry(msg, url, headers)
LogTelemetryEvent({
level: "error"
message: msg + `\nVideoID: ${parsedResponse["videoId"]}\nUrl: ${url}\nHeaders: ${FormatJson(headers)}`
fingerprint: [msg]
})
end if
durationMs = ValidString(headers["X-Head-Time-Millis"]).ToInt()
segmentCount = ValidString(headers["X-Head-Seqnum"]).ToInt()
if durationMs > 0
parsedResponse["postLiveDvrDurationMs"] = durationMs
end if
if segmentCount > 0
parsedResponse["postLiveDvrSegmentCount"] = segmentCount
end if
end function
end namespace
@@ -87,7 +87,7 @@ namespace Innertube
text = response.Text()
text = text.Replace(`)]}'`, "")
parsed = ParseJson(text)
parsed = StringUtils.ParseJsonSafe(text)
if not IsArray(parsed) or parsed.Count() < 2
return {
error: "Failed to parse search suggestions"
@@ -46,7 +46,7 @@ namespace Innertube
text = response.Text()
text = text.Replace(`)]}'`, "")
json = ParseJson(text)
json = StringUtils.ParseJsonSafe(text)
if json = invalid
return {
"error": "Failed to parse session data: " + text
@@ -78,7 +78,7 @@ namespace Innertube
return invalid
end if
sessionData = ParseJson(sessionData)
sessionData = StringUtils.ParseJsonSafe(sessionData)
if sessionData = invalid
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
return invalid
@@ -1,7 +1,7 @@
import "InvidiousService.bs"
function Init()
m.top.apiDefinitions = ParseJson(ReadAsciiFile("libpkg:/config/invidious_video_api.yaml"))
m.top.apiDefinitions = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/invidious_video_api.yaml"))
m.service = new Invidious.InvidiousService(m.top)
end function
@@ -698,7 +698,7 @@ namespace Invidious
end function
function VerifyTokenScope(token as string) as boolean
tokenObject = ParseJson(token)
tokenObject = StringUtils.ParseJsonSafe(token)
if tokenObject = invalid
LogWarn("Failed to json parse token:", token)
return false
@@ -68,6 +68,7 @@ class LoungeApi
commandHandlers[COMMAND_TYPE_GRACEFUL_RECONNECT] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_GET_RECEIVER_STATUS] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_SEND_DEBUG_COMMAND] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_SET_AUTOPLAY_MODE] = m.HandleIgnoreCommand
commandHandlers[COMMAND_TYPE_GET_NOW_PLAYING] = m.HandleGetPlayingNow
commandHandlers[COMMAND_TYPE_SESSION_ID] = m.HandleSessionId
@@ -211,7 +212,7 @@ class LoungeApi
text = text.Mid(text.instr(`\n`) + 1)
messagesToSend = []
commands = ParseJson(text)
commands = StringUtils.ParseJsonSafe(text)
m.ProcessCommands(commands, messagesToSend)
m.SendMessages(messagesToSend)
return true
@@ -267,7 +268,7 @@ class LoungeApi
payloadSize = chunk.Left(newLineIndex).trim()
payloadSize = payloadSize.ToInt()
payload = chunk.Mid(newLineIndex + 1, payloadSize)
commands = ParseJson(payload)
commands = StringUtils.ParseJsonSafe(payload)
m.ProcessCommands(commands, messagesToSend)
chunk = chunk.Mid(newLineIndex + payloadSize + 1)
newLineIndex = chunk.InStr(`\n`)
@@ -324,9 +325,16 @@ class LoungeApi
LogInfo(commandIndex, commandType)
m[handler](commandIndex, commandType, commandArgs, messagesToSend)
else
LogWarn("Unknown command type:", commandType, "command:", command)
fingerprint = "Unknown command type:" + ToString(commandType)
message = fingerprint + " command:" + ToString(command)
LogWarnNoTelemetry(message)
LogTelemetryEvent({
level: "warning"
message: message
fingerprint: fingerprint
})
#if DEBUG
throw `Unknown command type: ${commandType} command: ${ToString(command)}`
throw message
#end if
end if
end for
@@ -368,7 +376,7 @@ class LoungeApi
if not IsString(devices)
return
end if
devices = ParseJson(devices)
devices = StringUtils.ParseJsonSafe(devices)
if devices = invalid
return
end if
@@ -610,7 +618,7 @@ class LoungeApi
RegistryUtils.Delete(RegistryUtils.LAST_LOUNGE_DATA)
loungeData = ParseJson(loungeData)
loungeData = StringUtils.ParseJsonSafe(loungeData)
if not IsAssociativeArray(loungeData)
LogWarn("Can't disconnect from lounge. Invalid data:", loungeData)
return
@@ -30,6 +30,7 @@ const COMMAND_TYPE_GET_DISCOVERT_DEVICE_ID = "getDiscoveryDeviceId"
const COMMAND_TYPE_GRACEFUL_RECONNECT = "gracefulReconnect"
const COMMAND_TYPE_GET_RECEIVER_STATUS = "getReceiverStatus"
const COMMAND_TYPE_SEND_DEBUG_COMMAND = "sendDebugCommand"
const COMMAND_TYPE_SET_AUTOPLAY_MODE = "setAutoplayMode"
' Special commands
const COMMAND_TYPE_SESSION_ID = "c"
const COMMAND_TYPE_G_SESSION_ID = "S"
@@ -86,7 +86,7 @@ namespace LoungeVideoQueue
' - eventDetails is of the form {"eventType":"VIDEO_REMOVED","videoId":"<videoId>"}
eventDetails = playlistData[FIELD_EVENT_DETAILS]
if IsString(eventDetails)
eventDetails = ParseJson(eventDetails)
eventDetails = StringUtils.ParseJsonSafe(eventDetails)
end if
if eventDetails <> invalid and eventDetails["eventType"] = "VIDEO_ADDED"
eventVideoId = eventDetails[FIELD_VIDEO_ID]
@@ -21,7 +21,7 @@ function Init()
end function
function LoadPreferencesFile()
m.top.prefsModel = ParseJson(ReadAsciiFile("libpkg:/config/preferences.json5"))
m.top.prefsModel = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/preferences.json5"))
end function
function AddNodeFields()
@@ -60,7 +60,7 @@ function LoadUserPreferencesFromRegistry()
if userPrefs = invalid
userPrefs = {}
else
userPrefs = ParseJson(userPrefs)
userPrefs = StringUtils.ParseJsonSafe(userPrefs)
end if
' Step 2: Migrate existing preferences to new format (if needed)
@@ -101,7 +101,7 @@ function MigrateExistingPreferences(userPrefs as object) as boolean
if not StringUtils.IsNullOrEmpty(instances)
currentInstance = userPrefs["invidious.instance"]
if StringUtils.IsNullOrEmpty(currentInstance)
instances = ParseJson(instances)
instances = StringUtils.ParseJsonSafe(instances)
if IsArray(instances) and instances.Count() > 0
instance = instances[0]
if not StringUtils.IsNullOrEmpty(instance)
@@ -162,6 +162,20 @@ function MigrateExistingPreferences(userPrefs as object) as boolean
isDirty = true
end if
if userPrefs.__version = 5
filteredLayout = []
homeScreenLayout = ValidArray(userPrefs["misc.home_screen_layout"])
for each item in homeScreenLayout
if item.id = "trending" or item.id = "trending_music" or item.id = "trending_gaming" or item.id = "trending_movies"
continue for
end if
filteredLayout.Push(item)
end for
userPrefs["misc.home_screen_layout"] = filteredLayout
userPrefs.__version = 6
isDirty = true
end if
' TODO:P2 handle case where saved preferences version is higher than current version (e.g. user downgraded)
#if DEBUG
@@ -5,7 +5,7 @@
user prefs saved need to be migrated. If the version is less than the
current version, a migration is needed.
-->
<field id="__version" type="integer" value="5" />
<field id="__version" type="integer" value="6" />
<field id="prefsModel" type="array" />
<field id="preferenceFields" type="assocarray" />
<function name="GetUserPreferences" />
@@ -31,7 +31,7 @@ function LoadProfilesFromRegistry()
currentProfile: invalid
}
else
userProfiles = ParseJson(userProfiles)
userProfiles = StringUtils.ParseJsonSafe(userProfiles)
end if
' Step 2: Migrate existing profiles to new format (if needed)
@@ -98,7 +98,7 @@ function MigrateExistingProfiles(userProfiles as object) as boolean
return false
end if
authToken = ParseJson(tokenPayload)
authToken = StringUtils.ParseJsonSafe(tokenPayload)
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
if authToken = invalid or authToken.instance = invalid or authToken.token = invalid or authToken.username = invalid
@@ -55,7 +55,7 @@ namespace SearchHistoryUtils
return []
end if
history = ParseJson(history)
history = StringUtils.ParseJsonSafe(history)
if not IsArray(history)
return []
end if
@@ -9,7 +9,7 @@ namespace SponsorBlock
class SponsorBlockService
function new()
' TODO:P2 this is being read and parsed on every skipped segment. It should be cached.
m.sponsorBlockConfig = ParseJson(ReadAsciiFile("libpkg:/config/sponsorblock_config.json5"))
m.sponsorBlockConfig = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/sponsorblock_config.json5"))
end function
function GetCategories() as object
+13 -28
View File
@@ -129,37 +129,22 @@ namespace Sentry
end function
function ReplaceRequestId(message as string) as dynamic
reqIdStart = `\nRequestId: `
reqIdPlaceholder = "<REQUEST_ID>"
result = message
replaced = false
searchIndex = 0
while true
requestIdIndex = result.InStr(searchIndex, reqIdStart)
if requestIdIndex = -1
exit while
end if
requestIdRegex = m.requestIdRegex
if requestIdRegex = invalid
requestIdRegex = /RequestId:\s*[0-9]+/
m.requestIdRegex = requestIdRegex
end if
reqIdStartIndex = requestIdIndex + reqIdStart.Len()
newLineIndex = result.InStr(reqIdStartIndex, `\n`)
if newLineIndex = -1
exit while
end if
reqIdEndIndex = newLineIndex - 1
if (reqIdEndIndex <= reqIdStartIndex) or ((reqIdEndIndex - reqIdStartIndex) > 20)
exit while
end if
result = result.Mid(0, reqIdStartIndex) + reqIdPlaceholder + result.Mid(reqIdEndIndex + 1)
replaced = true
searchIndex = reqIdStartIndex + reqIdPlaceholder.Len()
end while
if not replaced
matches = requestIdRegex.MatchAll(message)
if not IsArray(matches) or matches.Count() = 0
return invalid
end if
return result
for each match in matches
fullMatch = match[0]
message = message.Replace(fullMatch, "RequestId: <REQUEST_ID>")
end for
return message
end function
end namespace
@@ -65,31 +65,9 @@ function ExecuteJob() as void
})
if not response.success
if response.error = Invidious.ERROR_NOT_AUTHENTICATED
if feedSources.Count() = 1
parent = feedContentNode.getParent()
if parent <> invalid
parent.removeChild(feedContentNode)
end if
JobSuccess()
return
end if
continue while
end if
if response.error.instr("Administrator has disabled this endpoint.") > -1
LogWarnNoTelemetry(feedSource.endpoint, "feedSource not available:", response.error)
if feedSources.Count() = 1
parent = feedContentNode.getParent()
if parent <> invalid
parent.removeChild(feedContentNode)
end if
JobSuccess()
return
end if
continue while
if RemoveSingleFailedRow(response.error, feedSource, feedSources, feedContentNode)
JobSuccess()
return
end if
feedSource.state.loadState = FeedLoadState.Error
@@ -243,6 +221,32 @@ function DeduplicateAppendAuthPlaylists(feedContentNode as object, itemNodes as
return nodesToAdd.Count()
end function
function RemoveSingleFailedRow(error as dynamic, feedSource as object, feedSources as object, feedContentNode as object) as boolean
error = ValidString(error)
LogWarnNoTelemetry(feedSource.id, "feedSource not available:", error)
if feedSources.Count() <> 1
return false
end if
isError = error = Invidious.ERROR_NOT_AUTHENTICATED
' Invidious admins disable endpoints sometimes
isError = isError or error.instr("Administrator has disabled this endpoint") <> -1
isError = isError or error.instr("API disabled") <> -1
' Playlet not supporting popular
isError = isError or feedSource.id = "inv_popular"
if not isError
return false
end if
parent = feedContentNode.getParent()
if parent <> invalid
parent.removeChild(feedContentNode)
end if
return true
end function
function HandleFeedLoadErrorDialog(error as object, isCancelled as boolean, rowList as object) as void
error = ErrorUtils.Format(error)
if isCancelled
@@ -99,12 +99,24 @@ function ExecuteJob() as void
streamUrls = CreateStreamUrls(metadata, service, preferencesNode, backend, playletServerPort)
if streamUrls.Count() = 0
contentNode.addFields({ metadata: metadata })
JobError("No playable streams found for this video.")
error = "No playable streams found for this video."
lastPlayerResponse = ValidString(ReadAsciiFile("cachefs:/last_player_response.json"))
LogTelemetryEvent({
level: "error"
message: error
fingerprint: error
attachments: [{
filename: "last_player_response.json"
content_type: "application/json"
data: lastPlayerResponse
}]
})
JobError(error)
return
end if
isDrmDash = SupportsDrmDashManifest(metadata)
if isDrmDash
isDrm = not StringUtils.IsNullOrEmpty(metadata.drmParams)
if isDrm
licenseServerURL = UrlUtils.BuildUrl(`http://127.0.0.1:${playletServerPort}/api/innertube/get_drm_license`, invalid, {
videoId: metadata.videoId
drmParams: metadata.drmParams
@@ -129,8 +141,12 @@ function ExecuteJob() as void
playletStreamUrlIndex: 0
})
LogDebug("Setting first url:", streamUrls[0])
contentNode.url = streamUrls[0]
firstUrl = streamUrls[0]
LogDebug("Setting first url:", firstUrl)
if StringUtils.IsNullOrEmpty(firstUrl)
LogError("First stream URL is empty!")
end if
contentNode.url = firstUrl
SetCaptions(metadata, service, contentNode)
@@ -146,7 +162,7 @@ function CreateStreamUrls(metadata as object, service as Invidious.InvidiousServ
streamUrls = []
if SupportsDrmDashManifest(metadata)
if SupportsDrmDashManifestUrl(metadata)
dashUrl = UrlUtils.AppendQueryParams(`http://127.0.0.1:${playletServerPort}/api/dash`, {
url: metadata.dashUrl
})
@@ -191,11 +207,15 @@ function SupportsMuxedFormats(metadata as object) as boolean
return IsArray(metadata.formatStreams) and metadata.formatStreams.Count() > 0
end function
function SupportsDrmDashManifest(metadata as object) as boolean
function SupportsDrmDashManifestUrl(metadata as object) as boolean
if StringUtils.IsNullOrEmpty(metadata.drmParams)
return false
end if
if StringUtils.IsNullOrEmpty(metadata.dashUrl)
return false
end if
if StringUtils.IsNullOrEmpty(metadata.drmSessionId)
return false
end if
@@ -208,10 +228,6 @@ function SupportsDrmDashManifest(metadata as object) as boolean
return false
end if
if StringUtils.IsNullOrEmpty(metadata.dashUrl)
return false
end if
return true
end function
@@ -325,7 +341,7 @@ function SetCaptions(metadata as object, service as object, contentNode as objec
return
end if
isoLanguageList = ParseJson(ReadAsciiFile("libpkg:/config/ISO-639-1-to-ISO-639-2T.json5"))
isoLanguageList = StringUtils.ParseJsonSafe(ReadAsciiFile("libpkg:/config/ISO-639-1-to-ISO-639-2T.json5"))
instance = service.GetInstance()
subtitleTracks = []
@@ -13,6 +13,18 @@ import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RemoteKeys.bs"
enum DownloadErrors
Unknown = 900
TimeoutByCurl = 950
TimeoutBySelector = 951
Abort = 960
AbortByServer = 961
AbortBySelector = 962
AbortByParallel = 963
ParallelFragmentError = 964
BadMedia = 970
end enum
function Init()
SetPlayerStyle()
SetupAnimation()
@@ -317,6 +329,9 @@ function OnVideoContentJobErrorDialogResponse(event as object)
shouldPlayNext = false
if event <> invalid
dialog = event.getRoSGNode()
if m.errorDialog <> invalid and dialog.isSameNode(m.errorDialog)
m.errorDialog = invalid
end if
dialog.unobserveFieldScoped("wasClosed")
shouldPlayNext = dialog.actualButtonSelected = 0
end if
@@ -432,6 +447,14 @@ function OnVideoPlayerStateChange() as void
' Reset isSeekingPosition when started to play the video
if state = "playing"
m.isSeekingPosition = false
' If we somehow was able to recover playback after an error dialog, close the dialog
errorDialog = m.errorDialog
if errorDialog <> invalid
m.errorDialog = invalid
errorDialog.unobserveFieldScoped("wasClosed")
errorDialog.close = true
end if
end if
' If we successfully played the video, then any error that comes later is not due to a 403 (FORBIDDEN).
@@ -441,31 +464,23 @@ function OnVideoPlayerStateChange() as void
m.videoPlayingSuccess = true
end if
errorReported = false
errorData = invalid
if state = "error"
errorInfo = m.top.errorInfo
errorData = GetPlayerErrorData(content.videoId, errorInfo)
LogErrorNoTelemetry(errorData.title, errorData.body)
ReportVideoError(errorData, content.url)
errorReported = true
if m.videoPlayingSuccess <> true
' http for stream format, mediaerror for DASH
if errorInfo.category = "http" or errorInfo.category = "mediaerror"
currentUrl = content.url
playletStreamUrls = content.playletStreamUrls
playletStreamUrlIndex = content.playletStreamUrlIndex
playletStreamUrlIndex++
content.playletStreamUrlIndex = playletStreamUrlIndex
if playletStreamUrlIndex < playletStreamUrls.Count()
nextUrl = playletStreamUrls[playletStreamUrlIndex]
LogErrorNoTelemetry(`Stream ${currentUrl} failed to play. Trying next stream ${nextUrl}`)
LogTelemetryEvent({
level: "error"
message: `Stream ${currentUrl} failed to play. Trying next stream ${nextUrl}`
fingerprint: ["Stream <URL> failed to play. Trying next stream <URL>"]
})
currentUrlIndex = content.playletStreamUrlIndex
nextUrlIndex = currentUrlIndex + 1
content.playletStreamUrlIndex = nextUrlIndex
if nextUrlIndex < playletStreamUrls.Count()
currentUrl = content.url
nextUrl = playletStreamUrls[nextUrlIndex]
if StringUtils.IsNullOrEmpty(nextUrl)
LogError("Next stream URL is empty, cannot try next stream")
@@ -486,6 +501,12 @@ function OnVideoPlayerStateChange() as void
if hasTimestamp and timestamp > 0
m.top.seek = content.timestamp
end if
msg = `Stream ${currentUrl} failed to play. Trying next stream ${nextUrl}`
LogErrorNoTelemetry(msg)
errorData.title = msg + `\n` + errorData.title
ReportVideoError(errorData, currentUrl, playletStreamUrls, currentUrlIndex, false)
return
end if
end if
@@ -503,18 +524,14 @@ function OnVideoPlayerStateChange() as void
end if
if state = "error"
errorInfo = m.top.errorInfo
errorData = GetPlayerErrorData(content.videoId, errorInfo)
LogErrorNoTelemetry(errorData.title, errorData.body)
if not errorReported
ReportVideoError(errorData, content.url)
end if
ReportVideoError(errorData, content.url, content.playletStreamUrls, content.playletStreamUrlIndex, true)
buttons = [Tr(Locale.Buttons.PlayNextVideo), Tr(Locale.Buttons.Cancel)]
dialog = DialogUtils.ShowTimedDialogButtons(errorData.body, errorData.title, buttons, 0, 10, true)
if dialog <> invalid
m.errorDialog = dialog
dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentJobErrorDialogResponse))
else
OnVideoContentJobErrorDialogResponse(invalid)
@@ -556,7 +573,7 @@ function GetPlayerErrorData(videoId as string, errorInfo as object) as object
}
end function
function ReportVideoError(errorData as object, url as string) as void
function ReportVideoError(errorData as object, url as dynamic, urls as object, urlIndex as dynamic, shownInDialog as boolean) as void
attachments = invalid
if errorData.body.Instr("malformed data") <> -1 or errorData.body.Instr("invalid pathname") <> -1
lastGeneratedDash = ValidString(ReadAsciiFile("cachefs:/last_generated_dash.xml"))
@@ -578,9 +595,30 @@ function ReportVideoError(errorData as object, url as string) as void
}]
end if
position = m.top.position
duration = m.top.duration
message = [
errorData.title
errorData.body
`Dialog shown: ${shownInDialog}`
`Position: ${position}`
`Duration: ${duration}`
`Url: ${url}`
`Urls: ` + ToString(urls)
`Url index: ${urlIndex}`
].Join(`\n`)
errorData.fingerprint.push(shownInDialog)
if shownInDialog
level = "error"
else
level = "warning"
end if
LogTelemetryEvent({
level: "error"
message: errorData.title + " " + errorData.body + `\nurl: ${url}`
level: level
message: message
fingerprint: errorData.fingerprint
attachments: attachments
})
@@ -53,7 +53,25 @@ namespace Http
m.dashManifest.invidiousInstance = m.invidiousService.GetInstance()
qualityFilter = m.CreateQualityFilter(quality)
xmlContent = m.dashManifest.fromVideoMetadata(metadata, qualityFilter, ValidString(local) = "true")
xmlContent = m.dashManifest.FromVideoMetadata(metadata, qualityFilter, ValidString(local) = "true")
if xmlContent.InStr("[ERROR]") <> -1
LogErrorNoTelemetry("Dash manifest generated with errors")
lastPlayerResponse = ValidString(ReadAsciiFile("cachefs:/last_player_response.json"))
LogTelemetryEvent({
level: "error"
message: "Dash manifest generated with errors"
attachments: [{
filename: "dash.xml"
content_type: "text/plain"
data: xmlContent
}, {
filename: "last_player_response.json"
content_type: "application/json"
data: lastPlayerResponse
}]
})
end if
response.http_code = 200
response.SetBodyDataString(xmlContent)
@@ -115,7 +133,7 @@ namespace Http
xml = new XmlObject()
manifestObj = new DashManifest("")
manifestObj.generateImageAdaptationSets(xml, storyboards, 100)
manifestObj.GenerateImageAdaptationSets(xml, storyboards, 100)
storyboardXml = xml.ToXmlString(false)
newDashContent = dashContent.Left(storyboardIndex) + storyboardXml + dashContent.Mid(storyboardIndex)
@@ -127,6 +127,9 @@ namespace Http
if ValidBool(metadata.liveNow) or ValidBool(metadata.hasLiveStreamingData)
return hlsManifest
end if
if hlsManifest.InStr("/source/yt_live_broadcast") <> -1 or hlsManifest.InStr("/live/1") <> -1
return hlsManifest
end if
storyboards = metadata.storyboards
if not IsArray(storyboards)
@@ -66,7 +66,7 @@ namespace Http
return true
end if
feedSource = ParseJson(feedSource)
feedSource = StringUtils.ParseJsonSafe(feedSource)
if feedSource = invalid
response.Default(400, "Expected valid JSON for feed-source")
return true
@@ -253,9 +253,8 @@ namespace Http
return true
end function
@get("/playlet-invidious-backend/api/v1/trending")
@get("/playlet-invidious-backend/api/v1/popular")
function GetTrending(context as object) as boolean
function GetPopular(context as object) as boolean
request = context.request
response = context.response
@@ -264,40 +263,10 @@ namespace Http
return m.GetAuthRecommended(context)
end if
raw = request.query.raw <> invalid
options = {
"disableShorts": m.preferences["content_feed.disable_shorts"]
raw: raw
type: request.query.type
}
result = InnertubeService.GetTrending(options)
if raw
response.Json(result)
return true
end if
if result.error <> invalid
response.Json(result)
response.http_code = 500
return true
end if
if not IsArray(result.feeds) or result.feeds.Count() = 0
response.Json({
"error": "Failed to get trending feed"
})
response.http_code = 500
return true
end if
response.Json(ValidArray(result.feeds[0].items))
if result.DoesExist("cache-control")
response.headers["cache-control"] = result["cache-control"]
end if
response.Json({
"error": "Playlet built-in Invidious backend does not support popular videos."
})
response.http_code = 400
return true
end function
@@ -804,7 +773,7 @@ namespace Http
' (such as "newest", "oldest", etc.), we'll ignore it, as it is not supported.
sortBy = request.query.sort_by
if not StringUtils.IsNullOrEmpty(sortBy) and sortBy.StartsWith("{")
sortBy = ParseJson(sortBy)
sortBy = StringUtils.ParseJsonSafe(sortBy)
if IsAssociativeArray(sortBy)
if sortBy.DoesExist("params")
options.params = sortBy.params
@@ -19,7 +19,7 @@ namespace Http
saved = RegistryUtils.Read(RegistryUtils.PLAYLET_LIB_URLS)
if saved <> invalid
saved = ParseJson(saved)
saved = StringUtils.ParseJsonSafe(saved)
end if
response.Json({
@@ -1,6 +1,7 @@
import "HttpRequestState.bs"
import "pkg:/components/Web/WebServer/Http/HttpConnection.bs"
import "pkg:/components/Web/WebServer/Http/HttpUtils.bs"
import "pkg:/source/utils/ByteArrayUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/MathUtils.bs"
import "pkg:/source/utils/Types.bs"
@@ -207,7 +208,7 @@ namespace Http
return false
end if
m.body_bytes = m.buffer.Slice(m.content_index)
m.body_bytes = ByteArrayUtils.Slice(m.buffer, m.content_index)
m.ready_for_response = true
return true
end function
@@ -271,7 +272,7 @@ namespace Http
return invalid
end if
m.body_json = ParseJson(text)
m.body_json = StringUtils.ParseJsonSafe(text)
return m.body_json
end function
end class
@@ -11,7 +11,7 @@ namespace Http
if StringUtils.IsNullOrEmpty(json)
return "application/octet-stream"
end if
map = ParseJson(json)
map = StringUtils.ParseJsonSafe(json)
if not IsAssociativeArray(map)
return "application/octet-stream"
end if
@@ -41,7 +41,7 @@ namespace Http
if StringUtils.IsNullOrEmpty(json)
return ""
end if
map = ParseJson(json)
map = StringUtils.ParseJsonSafe(json)
if not IsAssociativeArray(map)
return ""
end if
@@ -14,44 +14,6 @@
apiType: Invidious
endpoint: auth_recommended
- title: Trending
id: trending
feedSources:
- id: inv_trending
title: Trending
apiType: Invidious
endpoint: trending
- title: Trending - Music
id: trending_music
feedSources:
- id: inv_trending_music
title: Trending - Music
apiType: Invidious
endpoint: trending
queryParams:
type: Music
- title: Trending - Gaming
id: trending_gaming
feedSources:
- id: inv_trending_gaming
title: Trending - Gaming
apiType: Invidious
endpoint: trending
queryParams:
type: Gaming
- title: Trending - Movies
id: trending_movies
feedSources:
- id: inv_trending_movies
title: Trending - Movies
apiType: Invidious
endpoint: trending
queryParams:
type: Movies
- title: Popular
id: popular
feedSources:
@@ -1,18 +1,3 @@
trending:
title: Trending
url: /api/v1/trending
cacheSeconds: 21600 # 6 hours
queryParams:
type:
type:
- Music
- Gaming
- Movies
region:
type: "#ISO3166"
default: GetUserCountryCode
tryCount: 3 # trending is being phased out, sometimes it returns a 400 INVALID_ARGUMENT
popular:
title: Popular
url: /api/v1/popular
-16
View File
@@ -243,22 +243,6 @@
id: "recommended",
enabled: true,
},
{
id: "trending",
enabled: true,
},
{
id: "trending_music",
enabled: true,
},
{
id: "trending_gaming",
enabled: true,
},
{
id: "trending_movies",
enabled: true,
},
{
id: "popular",
enabled: true,
@@ -312,22 +312,6 @@
<source>Watch history</source>
<translation>Wiedergabeverlauf</translation>
</message>
<message>
<source>Trending</source>
<translation>Trends</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Trends - Filme</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Trends - Musik</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Trends - Gaming</translation>
</message>
<message>
<source>Popular</source>
<translation>Populär</translation>
@@ -88,22 +88,6 @@
<source>Watch history</source>
<translation>Watch history</translation>
</message>
<message>
<source>Trending</source>
<translation>Trending</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Trending - Movies</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Trending - Music</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Trending - Gaming</translation>
</message>
<message>
<source>Popular</source>
<translation>Popular</translation>
@@ -80,22 +80,6 @@
<source>Watch history</source>
<translation>Ver el historial</translation>
</message>
<message>
<source>Trending</source>
<translation>Tendencias</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Tendencias - Películas</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Tendencias - Música</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Tendencias - Juegos</translation>
</message>
<message>
<source>Popular</source>
<translation>Popular</translation>
@@ -36,10 +36,6 @@
<source>Filters</source>
<translation>Filtros</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Tendencias - Música</translation>
</message>
<message>
<source>Login to Invidious in order to view Subscriptions, Playlists, and use the Watch history.</source>
<translation>Accede a Invidious para ver tus suscripciones, playlists, y usar el historial de reproducción.</translation>
@@ -80,18 +76,6 @@
<source>Watch history</source>
<translation>Historial de reproducción</translation>
</message>
<message>
<source>Trending</source>
<translation>Tendencias</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Tendencias - Películas</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Tendencias - Videojuegos</translation>
</message>
<message>
<source>Edit</source>
<translation>Editar</translation>
@@ -76,22 +76,6 @@
<source>Watch history</source>
<translation>Historique</translation>
</message>
<message>
<source>Trending</source>
<translation>Tendances</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Tendances - Films</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Tendances - Musique</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Tendances - Jeux vidéo</translation>
</message>
<message>
<source>Popular</source>
<translation>Populaire</translation>
@@ -140,22 +140,6 @@
<source>Watch history</source>
<translation>Histórico de assistidos</translation>
</message>
<message>
<source>Trending</source>
<translation>Em alta</translation>
</message>
<message>
<source>Trending - Movies</source>
<translation>Em alta - Flimes</translation>
</message>
<message>
<source>Trending - Music</source>
<translation>Em alta - Música</translation>
</message>
<message>
<source>Trending - Gaming</source>
<translation>Em alta - Jogos</translation>
</message>
<message>
<source>Popular</source>
<translation>Popular</translation>
+3 -3
View File
@@ -2,8 +2,8 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=43
build_version=00001
minor_version=44
build_version=00006
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
@@ -13,4 +13,4 @@ hidden=1
git_commit_sha=unknown
bs_const=DEBUG=false
bs_const=DEBUG=false;TEST_MODE=false
@@ -1,3 +1,5 @@
import "pkg:/source/utils/ByteArrayUtils.bs"
namespace Protobuf
class BinaryReader
@@ -79,7 +81,7 @@ namespace Protobuf
if endPosition > m.buffer.Count()
return invalid
end if
value = m.buffer.Slice(m.position, endPosition)
value = ByteArrayUtils.Slice(m.buffer, m.position, endPosition)
m.position += length
return value
end function
+18 -5
View File
@@ -299,6 +299,11 @@ namespace HttpClient
return m
end function
function ToFile(filePath as string) as HttpRequest
m._toFilePath = filePath
return m
end function
function ToCurlCommand() as string
command = `curl "${m.BuildUrl()}"`
if m._method = "HEAD"
@@ -387,6 +392,10 @@ namespace HttpClient
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"
body = m._body
if body = invalid
@@ -394,7 +403,11 @@ namespace HttpClient
end if
m._sent = m.urlTransfer.AsyncPostFromString(body)
else if m._method = "GET"
m._sent = m.urlTransfer.AsyncGetToString()
if m._toFilePath <> invalid
m._sent = m.urlTransfer.AsyncGetToFile(m._toFilePath)
else
m._sent = m.urlTransfer.AsyncGetToString()
end if
else if m._method = "HEAD"
m._sent = m.urlTransfer.AsyncHead()
else
@@ -441,7 +454,7 @@ namespace HttpClient
backoffMs = 1000 + Rnd(2000)
tryNumber = m._tryCount - triesLeft + 1
LogWarnNoTelemetry("Request failed ID:", m.urlTransfer.GetIdentity(), "ErrorMessage:", response.ErrorMessage(), `\nRetrying: (`, tryNumber, "/", m._tryCount, ") in", backoffMs, "ms")
LogWarnTelemetry(response.ErrorMessage())
LogWarnTelemetry(response.ErrorMessage() + `\n` + m.ToCurlCommand())
if IsFunction(m._retryCallback)
try
@@ -690,7 +703,7 @@ namespace HttpClient
if text = invalid
return invalid
end if
m._json = ParseJson(text)
m._json = StringUtils.ParseJsonSafe(text)
return m._json
end function
@@ -800,7 +813,7 @@ namespace HttpClientCache
end if
metadataText = cacheText.Left(firstLineIndex)
metadata = ParseJson(metadataText)
metadata = StringUtils.ParseJsonSafe(metadataText)
if metadata = invalid
LogWarn("Failed to parse metadata from cache.")
Delete(request)
@@ -808,7 +821,7 @@ namespace HttpClientCache
end if
headersText = cacheText.Mid(firstLineIndex + 1, metadata.headers)
headers = ParseJson(headersText)
headers = StringUtils.ParseJsonSafe(headersText)
if headers = invalid
LogWarn("Failed to parse headers from cache.")
Delete(request)
@@ -0,0 +1,65 @@
import "StringUtils.bs"
namespace ByteArrayUtils
function Slice(bytearray as object, start_pos = 0 as dynamic, end_pos = invalid as dynamic) as object
if FindMemberFunction(bytearray, "Slice") <> invalid
start_pos = ValidInt(start_pos)
if end_pos = invalid
return bytearray.Slice(start_pos)
end if
return bytearray.Slice(start_pos, end_pos)
end if
return SliceFallback(bytearray, start_pos, end_pos)
end function
function SliceFallback(bytearray as object, start_pos = 0 as dynamic, end_pos = invalid as dynamic) as object
copy = CreateObject("roByteArray")
arrCount = bytearray.Count()
' default end_pos is array length
if end_pos = invalid
end_pos = arrCount
end if
start_pos = ValidInt(start_pos)
' handle negative start_pos
if start_pos < 0
start_pos = arrCount + start_pos
end if
' handle negative end_pos
if end_pos < 0
end_pos = arrCount + end_pos
end if
' clamp start_pos to bounds
if start_pos < 0
start_pos = 0
else if start_pos > arrCount
start_pos = arrCount
end if
' clamp end_pos to bounds
if end_pos < 0
end_pos = 0
else if end_pos > arrCount
end_pos = arrCount
end if
count = end_pos - start_pos
if count <= 0
return copy
end if
tmp = `tmp:/${StringUtils.RandomId()}.bin`
if not bytearray.WriteFile(tmp, start_pos, count)
DeleteFile(tmp)
return copy
end if
copy.ReadFile(tmp)
DeleteFile(tmp)
return copy
end function
end namespace
@@ -0,0 +1,45 @@
namespace Tests
@suite
class ByteArrayUtilsTests extends Rooibos.BaseTestSuite
protected override function beforeEach()
m.ba = CreateObject("roByteArray")
m.ba.FromHexString("00010203040506070809")
end function
@describe("ByteArrayUtils.Slice and SliceFallback")
@it("slices a byte array correctly")
@params("positive start and end", 2, 5, "020304")
@params("to the end if end is not provided", 7, invalid, "070809")
@params("the whole array if no params provided", invalid, invalid, "00010203040506070809")
@params("with negative start", -4, invalid, "06070809")
@params("with negative end", 0, -3, "00010203040506")
@params("with negative start and negative end", -5, -2, "050607")
@params("returns empty array for start greater than end", 5, 2, "")
@params("returns empty for start out of bounds", 20, invalid, "")
@params("clamps end to array length", 8, 20, "0809")
@params("handles empty slice", 3, 3, "")
function testSlice(description as string, start_pos as dynamic, end_pos as dynamic, expectedHex as string)
resultBa = ByteArrayUtils.Slice(m.ba, start_pos, end_pos)
m.assertEqual(resultBa.ToHexString(), expectedHex, "Slice failed for: " + description)
resultBaFallback = ByteArrayUtils.SliceFallback(m.ba, start_pos, end_pos)
m.assertEqual(resultBaFallback.ToHexString(), expectedHex, "SliceFallback failed for: " + description)
end function
@it("handles empty byte array")
function handles_empty_byte_array()
emptyBa = CreateObject("roByteArray")
resultBa = ByteArrayUtils.Slice(emptyBa, 0, 0)
m.assertEqual(resultBa.ToHexString(), "")
resultBaFallback = ByteArrayUtils.SliceFallback(emptyBa, 0, 0)
m.assertEqual(resultBaFallback.ToHexString(), "")
end function
end class
end namespace
-4
View File
@@ -41,10 +41,6 @@ namespace Locale
Recommended = "Recommended"
Playlists = "Playlists"
WatchHistory = "Watch history"
Trending = "Trending"
TrendingMovies = "Trending - Movies"
TrendingMusic = "Trending - Music"
TrendingGaming = "Trending - Gaming"
Popular = "Popular"
Videos = "Videos"
Shorts = "Shorts"
@@ -29,5 +29,18 @@ namespace StringUtils
function RandomId() as string
return StrI(rnd(2147483647), 36)
end function
function ParseJsonSafe(jsonString as dynamic) as dynamic
if IsNullOrEmpty(jsonString)
return invalid
end if
' bs:disable-next-line NO_PARSE_JSON
json = ParseJson(jsonString)
if json <> invalid
return json
end if
' bs:disable-next-line NO_PARSE_JSON
return ParseJson(jsonString.Replace("\u0000", ""))
end function
end namespace
+305 -269
View File
File diff suppressed because it is too large. Load diff
+13 -13
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.43.1",
"version": "0.44.6",
"type": "module",
"scripts": {
"dev": "vite",
@@ -9,29 +9,29 @@
"lint": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/postcss": "^4.1.16",
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/postcss": "^4.1.18",
"@tailwindcss/typography": "^0.5.19",
"@tsconfig/svelte": "^5.0.5",
"@tsconfig/svelte": "^5.0.7",
"@vitejs/plugin-legacy": "^7.2.1",
"autoprefixer": "^10.4.21",
"autoprefixer": "^10.4.24",
"bgutils-js": "^3.2.0",
"daisyui": "^5.3.9",
"dotenv": "^17.2.3",
"daisyui": "^5.5.18",
"dotenv": "^17.2.4",
"ip": "^2.0.1",
"jszip": "^3.10.1",
"postcss": "^8.5.6",
"rollup-plugin-visualizer": "^6.0.5",
"svelte": "^5.41.4",
"svelte-check": "^4.3.3",
"svelte": "^5.50.0",
"svelte-check": "^4.3.6",
"svelte-preprocess": "^6.0.3",
"tailwindcss": "^4.1.16",
"terser": "^5.44.0",
"tailwindcss": "^4.1.18",
"terser": "^5.46.0",
"tslib": "^2.8.1",
"typescript": "^5.9.3",
"vite": "^7.1.12",
"vite": "^7.3.1",
"vite-plugin-compression": "^0.5.1",
"vite-tsconfig-paths": "^5.1.4",
"vite-tsconfig-paths": "^6.0.5",
"youtubei.js": "^16.0.1"
}
}
+5 -1
View File
@@ -320,12 +320,16 @@ export class YoutubeJs {
init: format.init_range ? `${format.init_range.start}-${format.init_range.end}` : "",
index: format.index_range ? `${format.index_range.start}-${format.index_range.end}` : "",
bitrate: `${format.bitrate}`,
url: await format.decipher(YoutubeJs.innerTube.session.player),
itag: `${format.itag}`,
type: format.mime_type,
clen: `${format.approx_duration_ms}`,
lmt: `${format.last_modified}`,
};
if (format.url || format.signature_cipher || format.cipher) {
result.url = await format.decipher(YoutubeJs.innerTube.session.player);
}
if (format.audio_quality) {
result.audioQuality = format.audio_quality;
}
+2
View File
@@ -42,6 +42,8 @@ export class ManifestEditPlugin implements CompilerPlugin {
// Test flag
// @ts-ignore
const testMode = !!builder.options.testMode;
builder.logger.log(`Setting bs_const TEST_MODE to ${testMode}`)
manifestContent = manifestContent.replace(/TEST_MODE=(true|false)/i, `TEST_MODE=${testMode}`);
if (testMode) {
builder.logger.log(`Commenting out "sg_component_libs_provided"`)
manifestContent = manifestContent.replace(/sg_component_libs_provided=/i, `# sg_component_libs_provided=`);
+1 -1
View File
@@ -15,6 +15,6 @@ INVIDIOUS_HMAC_KEY=PASSWORD_1
INVIDIOUS_COMPANION_KEY=PASSWORD_2
```
- Run `docker-compose up`
- Run `docker compose up -d --pull always`
Invidious should now be running locally on port 3000.
+1 -1
View File
@@ -32,7 +32,7 @@ services:
# Use the key generated in the 2nd step
hmac_key: $INVIDIOUS_HMAC_KEY
healthcheck:
test: wget -nv --tries=1 --spider http://127.0.0.1:3000/api/v1/trending || exit 1
test: wget -nv --tries=1 --spider http://127.0.0.1:3000/api/v1/popular || exit 1
interval: 30s
timeout: 5s
retries: 2