Compare commits

...
11 Commits
72 changed files with 2128 additions and 1733 deletions

No files matched your search

+13 -14
View File
@@ -42,23 +42,22 @@ jobs:
ROKU_DEVPASSWORD: ${{ secrets.ROKU_DEVPASSWORD }}
ROKU_SIGN_PASSWORD: ${{ secrets.ROKU_SIGN_PASSWORD }}
# Static Channel Analysis disabled: errors on the missing rsg_version=1.3 manifest flag.
# - name: Use Java 21
# uses: actions/setup-java@v4
# with:
# distribution: "temurin"
# java-version: "21"
- name: Use Java 21
uses: actions/setup-java@v4
with:
distribution: "temurin"
java-version: "21"
# - name: Download the Static Channel Analysis CLI
# run: |
# curl -sSL "https://devtools.web.roku.com/static-channel-analysis/sca-cmd.zip" -o sca-cmd.zip
# unzip sca-cmd.zip
- name: Download the Static Channel Analysis CLI
run: |
curl -sSL "https://devtools.web.roku.com/static-channel-analysis/sca-cmd.zip" -o sca-cmd.zip
unzip sca-cmd.zip
# - name: Run Analysis on Playlet Lib
# run: ./sca-cmd/bin/sca-cmd ./release/playlet-lib.zip --exit error
- name: Run Analysis on Playlet Lib
run: ./sca-cmd/bin/sca-cmd ./release/playlet-lib.zip --exit error
# - name: Run Analysis on Playlet App
# run: ./sca-cmd/bin/sca-cmd ./release/playlet.zip --exit error
- name: Run Analysis on Playlet App
run: ./sca-cmd/bin/sca-cmd ./release/playlet.zip --exit error
- name: Delete Canary release
uses: dev-drprasad/delete-tag-and-release@v1.0
+12
View File
@@ -5,6 +5,18 @@ 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.48.10] - 2026-10-17
### Added
- Support for base transport commands (certification)
### Fixed
- Error message when account requires age verification
- Live stream fixes
- Capture additional fields to investigate DRM errors
## [0.48.9] - 2026-10-14
### Fixed
+9 -1
View File
@@ -12,7 +12,15 @@
},
// 1010 - Function overrides function in ancestor scope
// These overrides are intentional
1010
1010,
{
"src": "manifest",
"codes": [
// 1151 - rsg_version=1.3 requires Roku firmware version 15.0.0 or higher
// Certification requires rsg_version=1.3; older devices still load the lib
1151
]
}
],
"diagnosticLevel": "hint",
"minFirmwareVersion": "11.5.0",
+177 -104
View File
@@ -1,35 +1,35 @@
{
"name": "playlet",
"version": "0.48.9",
"version": "0.48.10",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet",
"version": "0.48.9",
"version": "0.48.10",
"hasInstallScript": true,
"devDependencies": {
"@rokucommunity/bslint": "^0.8.46",
"@types/crypto-js": "^4.2.2",
"@types/fs-extra": "^11.0.4",
"@types/node": "^26.6.3",
"@types/node": "^26.6.5",
"@types/xml2js": "^0.4.14",
"argparse": "^3.0.2",
"brighterscript": "0.73.5",
"brighterscript-formatter": "^1.8.3",
"argparse": "^3.0.3",
"brighterscript": "0.73.7",
"brighterscript-formatter": "^1.8.4",
"convert-svg-to-png": "^0.7.1",
"crypto-js": "^4.2.0",
"dotenv": "^18.0.4",
"dotenv": "^18.0.8",
"fs-extra": "^11.4.1",
"glob": "^13.0.6",
"imap": "^0.8.19",
"ip": "^2.0.1",
"json5": "^2.2.3",
"mailparser": "^3.9.28",
"mailparser": "^3.9.39",
"protocol-buffers-schema": "^3.6.1",
"roku-deploy": "^3.18.4",
"roku-test-automation": "^2.2.2",
"rooibos-roku": "5.16.5",
"rooibos-roku": "5.17.0",
"semver": "^7.8.5",
"shelljs": "^0.10.0",
"telnet-client": "^2.2.14",
@@ -447,9 +447,9 @@
"license": "MIT"
},
"node_modules/@types/node": {
"version": "26.6.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.3.tgz",
"integrity": "sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg==",
"version": "26.6.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -551,15 +551,15 @@
}
},
"node_modules/@zone-eu/mailsplit": {
"version": "5.4.17",
"resolved": "https://registry.npmjs.org/@zone-eu/mailsplit/-/mailsplit-5.4.17.tgz",
"integrity": "sha512-LOMzdrKRVgaghLaezIPdHRhsGpfDiWNQo1RptWc84CRllI4dWLwqX/L4x1iTt1CaeyvyUfMXM/6mjIsEisT3Tg==",
"version": "5.4.21",
"resolved": "https://registry.npmjs.org/@zone-eu/mailsplit/-/mailsplit-5.4.21.tgz",
"integrity": "sha512-a7DjD8zysu77OeLuAZRTMC6NDALc3smuKkaZv1QTJkq2kMa5CbEgVQuC7Nfd9LfMO92bkjxT41t8L3mkWDZe1Q==",
"dev": true,
"license": "(MIT OR EUPL-1.1+)",
"dependencies": {
"libbase64": "1.3.0",
"libmime": "5.4.4",
"libqp": "2.1.1"
"libbase64": "1.3.3",
"libmime": "5.4.8",
"libqp": "2.1.2"
}
},
"node_modules/accepts": {
@@ -658,9 +658,9 @@
"dev": true
},
"node_modules/argparse": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.2.tgz",
"integrity": "sha512-mFdDM6WqWKraGLsVb+C9CahPnzTXOefAOLq3jYcca2YZ8bEWpr++Tzj+zSaKW9+X9L5uSxcm1AZ3Y6aZJ09OhQ==",
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.3.tgz",
"integrity": "sha512-Sn98ftV3KfsO8xfLPHG6oT8y+b0yvbrLgZjgPDXsharNY15tTAjqIsIju4S32nl6/iEUNNE4v+yL2Zhm8ooP3w==",
"dev": true,
"funding": [
{
@@ -969,9 +969,9 @@
}
},
"node_modules/brighterscript": {
"version": "0.73.5",
"resolved": "https://registry.npmjs.org/brighterscript/-/brighterscript-0.73.5.tgz",
"integrity": "sha512-Du94fkEPBB6q8wYPpkreZWUPgG3Jd+VndrBKtmFgeLrGZztgiKfc63irwEcET1MqM+4DfIBaMT4r85GJF4/nHA==",
"version": "0.73.7",
"resolved": "https://registry.npmjs.org/brighterscript/-/brighterscript-0.73.7.tgz",
"integrity": "sha512-hlnMsNOsb8RbY1ZHQ6MQqeV0H9oPj+5tPzmI6fssJyy9vp1XHSY9D20qAAIYWgtu69ZpXnpBtVqtF0RMJDCi5A==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1008,14 +1008,15 @@
}
},
"node_modules/brighterscript-formatter": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/brighterscript-formatter/-/brighterscript-formatter-1.8.3.tgz",
"integrity": "sha512-ucwBBg3FVShkWyDzDlFTznhIAaeI0qBGcIYEjGNOLYFsXLAoT+N2yPimpMDG9pYhHiP7BdrQfdnXgHTp4gyALg==",
"version": "1.8.4",
"resolved": "https://registry.npmjs.org/brighterscript-formatter/-/brighterscript-formatter-1.8.4.tgz",
"integrity": "sha512-cuBi1iyKyg5pPEcTT2RWpVJMr6jzRKYZUYtSUHOVCLv6YFCkXoC5iPbKt3B+LWO4sqO+kByx5VJx4CIRceMglw==",
"dev": true,
"license": "MIT",
"dependencies": {
"brighterscript": "^0.73.3",
"glob-all": "^3.3.0",
"brighterscript": "^0.73.6",
"fast-glob": "^3.2.12",
"fs-extra": "^10.0.0",
"jsonc-parser": "^3.0.0",
"source-map": "0.7.4",
"yargs": "^17.2.1"
@@ -1039,6 +1040,21 @@
"node": ">=12"
}
},
"node_modules/brighterscript-formatter/node_modules/fs-extra": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/brighterscript-formatter/node_modules/jsonc-parser": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz",
@@ -1887,9 +1903,9 @@
}
},
"node_modules/dotenv": {
"version": "18.0.4",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-18.0.4.tgz",
"integrity": "sha512-jGt9uI5BIxpVO15kvy+iEFqNAwxYClKWnkptLjSNPnFLC003Imd0ofr3aEVsbpHdSBdSsbcApNIlz4nbyGMwdA==",
"version": "18.0.8",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-18.0.8.tgz",
"integrity": "sha512-2KDeoFoK/zRtcnbunCDlLG5VWVMcyqeQc6iK65o231nfNAcuGrKoqUQfJFUtBI+QlShk5HKIHxwebBtUl3rEfA==",
"dev": true,
"license": "BSD-2-Clause",
"bin": {
@@ -2512,7 +2528,8 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
"dev": true
"dev": true,
"license": "ISC"
},
"node_modules/fsevents": {
"version": "2.3.3",
@@ -2642,40 +2659,6 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/glob-all": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/glob-all/-/glob-all-3.3.1.tgz",
"integrity": "sha512-Y+ESjdI7ZgMwfzanHZYQ87C59jOO0i+Hd+QYtVt9PhLi6d8wlOpzQnfBxWUlaTuAoR3TkybLqqbIoWveU4Ji7Q==",
"dev": true,
"dependencies": {
"glob": "^7.2.3",
"yargs": "^15.3.1"
},
"bin": {
"glob-all": "bin/glob-all"
}
},
"node_modules/glob-all/node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
"deprecated": "Glob versions prior to v9 are no longer supported",
"dev": true,
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.1.1",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"engines": {
"node": "*"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/glob-parent": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
@@ -2789,6 +2772,13 @@
"he": "bin/he"
}
},
"node_modules/html-escaper": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true,
"license": "MIT"
},
"node_modules/html-to-text": {
"version": "10.0.1",
"resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-10.0.1.tgz",
@@ -2987,6 +2977,7 @@
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
"deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
"dev": true,
"license": "ISC",
"dependencies": {
"once": "^1.3.0",
"wrappy": "1"
@@ -3131,6 +3122,68 @@
"integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==",
"dev": true
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
"integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
"integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
"make-dir": "^4.0.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-lib-report/node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report/node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-reports": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
"integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"html-escaper": "^2.0.0",
"istanbul-lib-report": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/jsbn": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz",
@@ -3262,23 +3315,23 @@
}
},
"node_modules/libbase64": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/libbase64/-/libbase64-1.3.0.tgz",
"integrity": "sha512-GgOXd0Eo6phYgh0DJtjQ2tO8dc0IVINtZJeARPeiIJqge+HdsWSuaDTe8ztQ7j/cONByDZ3zeB325AHiv5O0dg==",
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/libbase64/-/libbase64-1.3.3.tgz",
"integrity": "sha512-6n4p3TUeQPimN4ANBTYQ5P4IpFx8p6cdanknnOBfw05XGtaG/k1LAtTSu79w7S07D1esy4qUfM8G4qvQncDWcw==",
"dev": true,
"license": "MIT"
},
"node_modules/libmime": {
"version": "5.4.4",
"resolved": "https://registry.npmjs.org/libmime/-/libmime-5.4.4.tgz",
"integrity": "sha512-d3zZ2k8s6iO+8u9Vfkl6HfhD5lSVocGcmOViTz/i0CJcwhJADyubEJ/+TkBhuLDUSIBOiG+D8G5kJKwXwKbXXA==",
"version": "5.4.8",
"resolved": "https://registry.npmjs.org/libmime/-/libmime-5.4.8.tgz",
"integrity": "sha512-nsBApAZkontkOI4Kmg/7GyctCRraQ9Yxn7vZnzpHSOfqCmkt5/WTXpu5jk7a14REzW8OghKcbTY4bxx6rR9wSQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"encoding-japanese": "2.4.0",
"iconv-lite": "0.7.3",
"libbase64": "1.3.0",
"libqp": "2.1.1"
"libbase64": "1.3.3",
"libqp": "2.1.2"
}
},
"node_modules/libmime/node_modules/iconv-lite": {
@@ -3299,9 +3352,9 @@
}
},
"node_modules/libqp": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/libqp/-/libqp-2.1.1.tgz",
"integrity": "sha512-0Wd+GPz1O134cP62YU2GTOPNA7Qgl09XwCqM5zpBv87ERCXdfDtyKXvV7c9U22yWJh44QZqBocFnXN11K96qow==",
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/libqp/-/libqp-2.1.2.tgz",
"integrity": "sha512-rp+U80tl9Os4K7GnVbPzPRmghPu6eqB8rcF+ontvNAnoga0JhMFG/bkTD/reC8yoznKMgOc5/ttZHJasiWeFPw==",
"dev": true,
"license": "MIT"
},
@@ -3365,20 +3418,20 @@
}
},
"node_modules/mailparser": {
"version": "3.9.28",
"resolved": "https://registry.npmjs.org/mailparser/-/mailparser-3.9.28.tgz",
"integrity": "sha512-O7oCYzWW9YH5lHk/y3Z8R8dFnUq8wqaH146BuU2NDt/3MGjdfMLzGF2Ft7WksTCeq00covNKpwxQabcG3zJFqQ==",
"version": "3.9.39",
"resolved": "https://registry.npmjs.org/mailparser/-/mailparser-3.9.39.tgz",
"integrity": "sha512-tFIEhwsNR4Xs5aq/8oBtd8aQZv42oLoDGWrne6rT/b3e0hN+o/k1KjaedWLh1NydVK35FiDaOTmGg9ZFhIsfYw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@zone-eu/mailsplit": "5.4.17",
"@zone-eu/mailsplit": "5.4.21",
"encoding-japanese": "2.4.0",
"he": "1.2.0",
"html-to-text": "10.0.1",
"iconv-lite": "0.7.3",
"libmime": "5.4.4",
"libmime": "5.4.8",
"linkify-it": "5.0.2",
"nodemailer": "10.0.10",
"nodemailer": "10.1.1",
"punycode.js": "2.3.1",
"tlds": "1.261.0"
},
@@ -3403,6 +3456,22 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/make-dir": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
"integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"semver": "^7.5.3"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/make-error": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
@@ -3641,9 +3710,9 @@
}
},
"node_modules/nodemailer": {
"version": "10.0.10",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.10.tgz",
"integrity": "sha512-He9XskOFms62SyAKkLu8CcGcYHAo+BSHSsORI8s4PJH8qZgZY4L4lDfvyN0twvmbpyG+eGrxpyBlskj9d9rJ8A==",
"version": "10.1.1",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.1.tgz",
"integrity": "sha512-pbqZRoeYUO+1E8TJ/11WeY4D2EVujj1hsYjz3qff/vUFDtGnmi7p3iqzTFslYOfQ6PnjVcWxx/CIUSHCSrO/QA==",
"dev": true,
"license": "MIT-0",
"engines": {
@@ -3940,6 +4009,7 @@
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
@@ -4524,16 +4594,16 @@
}
},
"node_modules/roku-debug": {
"version": "0.24.4",
"resolved": "https://registry.npmjs.org/roku-debug/-/roku-debug-0.24.4.tgz",
"integrity": "sha512-HcwIZOIeLqLigObOBCLTwwi+oJOCOYgSJ5yYlCm9JdU5Mu04J2v819wJDG6IZDdARx63n404rC37YDX2JRHtKQ==",
"version": "0.24.6",
"resolved": "https://registry.npmjs.org/roku-debug/-/roku-debug-0.24.6.tgz",
"integrity": "sha512-Js0/hXAKKUAQ8jpRIg4SYgobGh9msKZBvY+KyHbgN97ehQdLGoRZ7VnDk3BnicOGDd3BrhPYvTBq4R+DE6TCKg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@rokucommunity/logger": "^0.4.2",
"@vscode/debugadapter": "^1.68.0",
"@vscode/debugprotocol": "^1.68.0",
"brighterscript": "^0.73.3",
"brighterscript": "^0.73.5",
"debounce": "^1.2.1",
"eventemitter3": "^4.0.7",
"fast-glob": "^3.2.11",
@@ -4543,7 +4613,7 @@
"needle": "^3.5.0",
"portfinder": "^1.0.32",
"replace-in-file": "^6.3.2",
"roku-deploy": "^4.0.0-alpha.8",
"roku-deploy": "4.0.0-alpha.9",
"semver": "^7.5.4",
"smart-buffer": "^4.2.0",
"source-map": "^0.7.4",
@@ -4608,9 +4678,9 @@
}
},
"node_modules/roku-debug/node_modules/roku-deploy": {
"version": "4.0.0-alpha.8",
"resolved": "https://registry.npmjs.org/roku-deploy/-/roku-deploy-4.0.0-alpha.8.tgz",
"integrity": "sha512-9qz1wlixZ1eljbOqyvphbhzkjr/NfDfJ61T1ZtsmszvcHhhu41IS+jcjdjCzepu6UqAmngEt/iGMcsRF76ZkWA==",
"version": "4.0.0-alpha.9",
"resolved": "https://registry.npmjs.org/roku-deploy/-/roku-deploy-4.0.0-alpha.9.tgz",
"integrity": "sha512-g63xcli1F6cfeu/OOrg0WcPeTkz3HGBCq3sJ8uSaDHrhwSmkWi7IfAnBupM6sJYFCZfeC2kATUI82wFrBvNcLA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4929,18 +4999,21 @@
"license": "MIT"
},
"node_modules/rooibos-roku": {
"version": "5.16.5",
"resolved": "https://registry.npmjs.org/rooibos-roku/-/rooibos-roku-5.16.5.tgz",
"integrity": "sha512-iQ23H8yX+DmruOB6L0az1C/4H6S73YzsEWk9QrfbxS0Kt4myeD77iHC43KeKjO9NmKae+gkTnqsgF93GN/Fonw==",
"version": "5.17.0",
"resolved": "https://registry.npmjs.org/rooibos-roku/-/rooibos-roku-5.17.0.tgz",
"integrity": "sha512-eo1l3hLrfqkG0A4Jv8KbgGFD2pArLkHQ6zJ3fI9cHRfWL78tzLwd3z5YaMZn4tVB5Ttj8YesOcbQEk1aVYpeyA==",
"dev": true,
"license": "MIT",
"dependencies": {
"brighterscript": "^0.73.3",
"brighterscript": "^0.73.5",
"fast-glob": "^3.2.12",
"fs-extra": "^10.1.0",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.0",
"istanbul-reports": "^3.0.2",
"minimatch": "^3.0.4",
"roku-debug": "^0.24.3",
"roku-deploy": "^4.0.0-alpha.5",
"roku-debug": "^0.24.6",
"roku-deploy": "^4.0.0-alpha.9",
"rooibos_promises": "npm:@rokucommunity/promises@^0.5.0",
"source-map": "^0.7.3",
"undent": "^1.0.1",
@@ -4997,9 +5070,9 @@
}
},
"node_modules/rooibos-roku/node_modules/roku-deploy": {
"version": "4.0.0-alpha.8",
"resolved": "https://registry.npmjs.org/roku-deploy/-/roku-deploy-4.0.0-alpha.8.tgz",
"integrity": "sha512-9qz1wlixZ1eljbOqyvphbhzkjr/NfDfJ61T1ZtsmszvcHhhu41IS+jcjdjCzepu6UqAmngEt/iGMcsRF76ZkWA==",
"version": "4.0.0-alpha.9",
"resolved": "https://registry.npmjs.org/roku-deploy/-/roku-deploy-4.0.0-alpha.9.tgz",
"integrity": "sha512-g63xcli1F6cfeu/OOrg0WcPeTkz3HGBCq3sJ8uSaDHrhwSmkWi7IfAnBupM6sJYFCZfeC2kATUI82wFrBvNcLA==",
"dev": true,
"license": "MIT",
"dependencies": {
+8 -8
View File
@@ -1,29 +1,29 @@
{
"name": "playlet",
"version": "0.48.9",
"version": "0.48.10",
"description": "Unofficial YouTube client for Roku",
"devDependencies": {
"@rokucommunity/bslint": "^0.8.46",
"@types/crypto-js": "^4.2.2",
"@types/fs-extra": "^11.0.4",
"@types/node": "^26.6.3",
"@types/node": "^26.6.5",
"@types/xml2js": "^0.4.14",
"argparse": "^3.0.2",
"brighterscript": "0.73.5",
"brighterscript-formatter": "^1.8.3",
"argparse": "^3.0.3",
"brighterscript": "0.73.7",
"brighterscript-formatter": "^1.8.4",
"convert-svg-to-png": "^0.7.1",
"crypto-js": "^4.2.0",
"dotenv": "^18.0.4",
"dotenv": "^18.0.8",
"fs-extra": "^11.4.1",
"glob": "^13.0.6",
"imap": "^0.8.19",
"ip": "^2.0.1",
"json5": "^2.2.3",
"mailparser": "^3.9.28",
"mailparser": "^3.9.39",
"protocol-buffers-schema": "^3.6.1",
"roku-deploy": "^3.18.4",
"roku-test-automation": "^2.2.2",
"rooibos-roku": "5.16.5",
"rooibos-roku": "5.17.0",
"semver": "^7.8.5",
"shelljs": "^0.10.0",
"telnet-client": "^2.2.14",
+2
View File
@@ -4,6 +4,8 @@ major_version=0
minor_version=1
build_version=00000
rsg_version=1.3
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-app",
"version": "0.48.9",
"version": "0.48.10",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-app",
"version": "0.48.9"
"version": "0.48.10"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-app",
"version": "0.48.9",
"version": "0.48.10",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-app",
@@ -70,6 +70,7 @@ function OnLoadStatusChanged() as void
m.scene.playletLibLoadedUrl = libUrl
container = m.scene.findNode("MainSceneContainer")
container.createChild("PlayletLib:MainScene")
m.scene.libSceneCreated = true
return
end if
@@ -81,6 +82,10 @@ function OnLoadStatusChanged() as void
end if
end function
function CreateInputTransportEventsHandler(_unused as dynamic) as object
return CreateObject("roSGNode", "PlayletLib:InputTransportEventsHandler")
end function
function RemoveComponentLibrary() as void
if m.lib = invalid
return
@@ -4,9 +4,11 @@
<field id="launchArgs" type="assocarray" />
<field id="inputArgs" type="assocarray" alwaysNotify="true" />
<field id="playletLibLoadedUrl" type="assocarray" />
<field id="libSceneCreated" type="bool" />
<field id="systemLogEvent" type="assocarray" alwaysNotify="true" />
<field id="enableSystemLogType" type="string" />
<field id="lastExitInfo" type="assocarray" />
<function name="CreateInputTransportEventsHandler" />
</interface>
<script type="text/brightscript" uri="pkg:/source/Dialog.bs" />
<script type="text/brightscript" uri="pkg:/source/Manifest.bs" />
+7 -1
View File
@@ -3,7 +3,9 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=48
build_version=00009
build_version=00010
rsg_version=1.3
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
@@ -28,6 +30,10 @@ confirm_partner_button=1
supports_input_launch=1
supports_voice_roinput=1
supports_etc_seek=1
supports_etc_next=1
requires_widevine_drm=1
requires_widevine_version=1.0
+17 -1
View File
@@ -27,6 +27,7 @@ function Main(args as object) as void
scene = screen.CreateScene("BootstrapScene")
screen.show()
scene.ObserveField("libSceneCreated", port)
AppManager.CaptureLastExitInfo(scene)
@@ -49,6 +50,8 @@ function Main(args as object) as void
input = CreateObject("roInput")
input.setMessagePort(port)
input.EnableTransportEvents()
transportEventsHandler = invalid
systemLog = CreateObject("roSystemLog")
systemLog.SetMessagePort(port)
@@ -83,8 +86,21 @@ function Main(args as object) as void
if field = "enableSystemLogType"
systemLog.EnableType(data)
end if
if field = "libSceneCreated"
scene.unobserveField("libSceneCreated")
transportEventsHandler = scene@.CreateInputTransportEventsHandler()
end if
else if msgType = "roInputEvent"
scene.inputArgs = msg.getInfo()
info = msg.getInfo()
if info.type = "transport"
status = "unhandled"
if transportEventsHandler <> invalid
status = transportEventsHandler@.HandleTransportEvent(info)
end if
input.EventResponse({ id: info.id, status: status })
else
scene.inputArgs = info
end if
end if
end while
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-lib",
"version": "0.48.9",
"version": "0.48.10",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-lib",
"version": "0.48.9"
"version": "0.48.10"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-lib",
"version": "0.48.9",
"version": "0.48.10",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "node ../tools/rm.js ../build/playlet-lib",
@@ -0,0 +1,121 @@
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
import "TransportEvents.types.bs"
function Init()
m.appManager = CreateObject("roAppManager")
m.videoQueue = m.top.getScene().findNode("VideoQueue")
' TODO:P2 ok, forward, rewind, replay, next and skip need support in the player or the queue. Until then they
' have no entry here, and answer unhandled.
m.commandHandlers = {}
m.commandHandlers[TransportCommand.Play] = PlayCommand
m.commandHandlers[TransportCommand.Pause] = PauseCommand
m.commandHandlers[TransportCommand.Stop] = PauseCommand
m.commandHandlers[TransportCommand.Seek] = SeekCommand
m.commandHandlers[TransportCommand.StartOver] = StartOverCommand
m.commandHandlers[TransportCommand.NowPlaying] = NowPlayingCommand
m.commandHandlers[TransportCommand.Like] = NotSupportedCommand
m.commandHandlers[TransportCommand.Dislike] = NotSupportedCommand
m.commandHandlers[TransportCommand.Shuffle] = NotSupportedCommand
m.commandHandlers[TransportCommand.Loop] = NotSupportedCommand
end function
function HandleTransportEvent(event as object) as string
status = RouteTransportEvent(event)
LogInfo("transport event", event, "->", status)
return status
end function
function RouteTransportEvent(event as object) as string
commandHandler = m.commandHandlers[ValidString(event.command)]
if commandHandler = invalid
return TransportStatus.Unhandled
end if
return commandHandler(event)
end function
function PlayCommand(_event as object) as string
player = m.videoQueue.player
if player = invalid
return TransportStatus.Unhandled
end if
if player.state = "paused"
m.videoQueue.play = true
end if
return TransportStatus.Success
end function
function PauseCommand(_event as object) as string
player = m.videoQueue.player
if player = invalid
return TransportStatus.Unhandled
end if
if player.state = "paused"
return TransportStatus.ErrorRedundant
end if
m.videoQueue.pause = true
return TransportStatus.Success
end function
function SeekCommand(event as object) as string
player = m.videoQueue.player
if player = invalid
return TransportStatus.Unhandled
end if
deltaSeconds = ValidString(event.duration).ToInt()
if deltaSeconds <= 0
return TransportStatus.Error
end if
if event.direction = TransportSeekDirection.Backward
deltaSeconds = -deltaSeconds
end if
targetSeconds = player.position + deltaSeconds
status = TransportStatus.Success
if targetSeconds < 0
targetSeconds = 0
status = TransportStatus.SuccessSeekStart
else if player.duration > 0 and targetSeconds > player.duration
targetSeconds = player.duration
status = TransportStatus.SuccessSeekEnd
end if
player.setSeek = targetSeconds
return status
end function
function StartOverCommand(_event as object) as string
player = m.videoQueue.player
if player = invalid
return TransportStatus.Unhandled
end if
player.setSeek = 0
return TransportStatus.Success
end function
function NowPlayingCommand(_event as object) as string
player = m.videoQueue.player
if player = invalid
m.appManager.SetNowPlayingContentMetaData(invalid)
return TransportStatus.Success
end if
content = player.content
if content = invalid or StringUtils.IsNullOrEmpty(content.title)
m.appManager.SetNowPlayingContentMetaData(invalid)
return TransportStatus.ErrorGeneric
end if
m.appManager.SetNowPlayingContentMetaData({ title: content.title, contentType: "movie" })
return TransportStatus.Success
end function
function NotSupportedCommand(_event as object) as string
return TransportStatus.ErrorChannel
end function
@@ -0,0 +1,5 @@
<component name="InputTransportEventsHandler" extends="Node">
<interface>
<function name="HandleTransportEvent" />
</interface>
</component>
@@ -0,0 +1,39 @@
' https://developer.roku.com/docs/developer/media-playback/voice-controls/transport-controls.md
enum TransportCommand
Play = "play"
Pause = "pause"
stop = "stop"
Ok = "ok"
Forward = "forward"
Rewind = "rewind"
Replay = "replay"
StartOver = "startover"
Seek = "seek"
next = "next"
Skip = "skip"
NowPlaying = "nowplaying"
Like = "like"
Dislike = "dislike"
Shuffle = "shuffle"
Loop = "loop"
end enum
enum TransportSeekDirection
Forward = "forward"
Backward = "backward"
end enum
' https://developer.roku.com/docs/references/brightscript/interfaces/ifinput.md#eventresponseroassociativearray-aa-as-boolean
enum TransportStatus
Success = "success"
SuccessSeekStart = "success.seek-start"
SuccessSeekEnd = "success.seek-end"
Unhandled = "unhandled"
Error = "error"
ErrorGeneric = "error.generic"
ErrorAd = "error.ad"
ErrorChannel = "error.channel"
ErrorLive = "error.live"
ErrorNoMedia = "error.no-media"
ErrorRedundant = "error.redundant"
end enum
@@ -54,7 +54,6 @@ class DashManifest
adaptiveFormats = m.ProxyFormatsThroughInvidious(adaptiveFormats)
end if
duration = m.GetDuration(metadata)
isLive = ValidBool(metadata.liveNow)
groupings = m.CreateFormatGroupings(adaptiveFormats, metadata.isPostLiveDvr, isLive)
@@ -119,7 +118,7 @@ class DashManifest
else
mpdAttributes["profiles"] = "urn:mpeg:dash:profile:full:2011"
mpdAttributes["type"] = "static"
mpdAttributes["mediaPresentationDuration"] = `PT${duration}S`
mpdAttributes["mediaPresentationDuration"] = m.FormatDuration(m.GetDurationMs(metadata))
end if
' Live needs an explicit Period start to anchor the timeline against availabilityStartTime.
@@ -169,17 +168,17 @@ class DashManifest
return proxied
end function
function GetDuration(metadata as object) as dynamic
if metadata["isPostLiveDvr"] = true and IsInt(metadata["postLiveDvrDurationMs"])
return metadata["postLiveDvrDurationMs"] / 1000.0
function GetDurationMs(metadata as object) as longinteger
if metadata["isPostLiveDvr"] = true and metadata["postLiveDvrDurationMs"] <> invalid
return metadata["postLiveDvrDurationMs"]
end if
approxDurationMs = ValidString(ObjectUtils.Dig(metadata, ["adaptiveFormats", 0, "approxDurationMs"])).ToInt()
if approxDurationMs > 0
return approxDurationMs / 1000.0
approxDurationMs = StringUtils.ParseJsonSafe(ObjectUtils.Dig(metadata, ["adaptiveFormats", 0, "approxDurationMs"]))
if IsNumber(approxDurationMs) and approxDurationMs > 0
return approxDurationMs
end if
return ValidInt(metadata["lengthSeconds"])
return ValidInt(metadata["lengthSeconds"]) * 1000&
end function
' `durationRuns` ascending.
@@ -246,7 +245,7 @@ class DashManifest
return seqnum
end function
function FormatDuration(ms as integer) as string
function FormatDuration(ms as longinteger) as string
return `PT${ms \ 1000}.${Right("00" + (ms mod 1000).ToStr(), 3)}S`
end function
@@ -638,8 +637,7 @@ class DashManifest
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)
postLiveDvrSegmentCount = MathUtils.Max(Fix(m.GetDurationMs(metadata) / (stream.targetDurationSec * 1000)), 1)
xml.Comment(`[INFO] Guessing postLiveDvrSegmentCount as ${postLiveDvrSegmentCount} for itag: ${stream.itag}`)
end if
@@ -1,3 +0,0 @@
' The head check counts of the latest live video load, as { video_load_id, counts }. One file,
' overwritten by each live load: tmp:/ lasts as long as the app.
const LIVE_HEAD_COUNTS_PATH = "tmp:/live_head_counts.json"
@@ -0,0 +1,3 @@
' The head check and timeline counts of the latest live video load, as { live_head, live_timeline }.
' One file, overwritten by each live load: tmp:/ lasts as long as the app.
const LIVE_LOAD_COUNTS_PATH = "tmp:/live_load_counts.json"
@@ -0,0 +1,37 @@
import "pkg:/components/Services/Innertube/GetDrmLicenseEndpoint.types.bs"
import "pkg:/components/Telemetry/VideoLoadHandoff.bs"
const DRM_LICENSE_REQUESTS_PATH = "tmp:/drm_license_requests.json"
const DRM_LICENSE_RESPONSE_SAMPLE_CAP = 10
namespace DrmLicenseRequests
function RecordSent(videoLoadId as string) as void
requests = DrmLicenseRequests.Load(videoLoadId)
requests["sent"] += 1
VideoLoadHandoff.Write(DRM_LICENSE_REQUESTS_PATH, videoLoadId, requests)
end function
function RecordResponse(videoLoadId as string, response as Innertube.DrmLicenseResponse) as void
requests = DrmLicenseRequests.Load(videoLoadId)
responses = requests["responses"]
if responses.Count() >= DRM_LICENSE_RESPONSE_SAMPLE_CAP
return
end if
if response.payload <> invalid
responses.Push({ "payload": response.payload })
else
responses.Push({ "error": response.error })
end if
VideoLoadHandoff.Write(DRM_LICENSE_REQUESTS_PATH, videoLoadId, requests)
end function
function Load(videoLoadId as string) as object
requests = VideoLoadHandoff.Read(DRM_LICENSE_REQUESTS_PATH, videoLoadId)
if not IsAssociativeArray(requests)
return { "sent": 0, "responses": [] }
end if
return requests
end function
end namespace
@@ -1,3 +1,5 @@
import "pkg:/components/Services/Innertube/GetDrmLicenseEndpoint.types.bs"
namespace Innertube
function CreateGetDrmLicenceRequest(options as object) as HttpClient.Request
@@ -39,7 +41,7 @@ namespace Innertube
return request
end function
function ParseGetDrmLicenseResponse(payload as object) as dynamic
function ParseGetDrmLicenseResponse(payload as object) as Innertube.DrmLicenseResponse
if not IsAssociativeArray(payload)
return {
"error": "Invalid JSON response"
@@ -50,6 +52,7 @@ namespace Innertube
if status <> "LICENSE_STATUS_OK"
return {
"error": "DRM license request failed with status: " + status
"payload": payload
}
end if
@@ -57,12 +60,24 @@ namespace Innertube
if StringUtils.IsNullOrEmpty(license)
return {
"error": "DRM license is missing in the response"
"payload": payload
}
end if
buffer = createObject("roByteArray")
buffer.FromBase64String(license.Replace("-", "+").Replace("_", "/"))
return buffer
if buffer.Count() = 0
return {
"error": "DRM license decodes to no bytes"
"payload": payload
}
end if
payload.Delete("license")
return {
"license": buffer
"payload": payload
}
end function
function GenerateDrmSessionId() as string
@@ -0,0 +1,10 @@
namespace Innertube
interface DrmLicenseResponse
optional license as roByteArray
' The response, without the license once it decoded.
optional payload as object
optional error as string
end interface
end namespace
@@ -810,7 +810,7 @@ namespace InnertubeService
return Innertube.ListAccounts(accessToken, cancellation)
end function
function GetDrmLicense(options as object) as dynamic
function GetDrmLicense(options as object) as Innertube.DrmLicenseResponse
request = Innertube.CreateGetDrmLicenceRequest(options)
response = request.Await()
@@ -33,33 +33,17 @@ namespace Innertube
end if
headUrl = GetLiveHeadUrl(adaptiveFormats[0]["url"], cpn)
request = CreateLiveHeadRequest(headUrl)
request.RetryCount(1)
request.RetryIf(function(response as HttpClient.Response) as string
if Innertube.ReadLiveHeadSeqnum(response) < 0 or (Innertube.ReadLiveHeadTimeMs(response) = invalid and Innertube.ReadLiveHeadTimeSecAsMs(response) = invalid)
return `no X-Head-* in the response (HTTP ${response.StatusCode()})`
end if
return ""
end function)
request.Cancellation(cancellation)
response = request.Await()
headSeqnum = ReadLiveHeadSeqnum(response)
headTimeMs = ReadLiveHeadTimeMs(response)
averagedTimeMs = headTimeMs
if averagedTimeMs = invalid
averagedTimeMs = ReadLiveHeadTimeSecAsMs(response)
end if
if headSeqnum < 0 or averagedTimeMs = invalid
response = FetchLiveHead(headUrl, cancellation)
if not HasLiveHead(response)
parsedResponse["error"] = `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP ${response.StatusCode()})\n${response.ErrorMessage()}`
return
end if
now = CreateObject("roDateTime")
timeline = GetLiveTimeline(headSeqnum, averagedTimeMs, ValidInt(adaptiveFormats[0]["targetDurationSec"]), ValidInt(adaptiveFormats[0]["maxDvrDurationSec"]), chunkReadahead, now.AsSeconds(), now.GetMilliseconds())
timeline = GetLiveTimeline(ReadLiveHeadSeqnum(response), ReadLiveHeadAnyTimeMs(response), ValidInt(adaptiveFormats[0]["targetDurationSec"]), ValidInt(adaptiveFormats[0]["maxDvrDurationSec"]), chunkReadahead, now.AsSeconds(), now.GetMilliseconds())
parsedResponse.Append(timeline)
parsedResponse["liveHeadUrl"] = headUrl
parsedResponse["liveHeadTimeMs"] = headTimeMs
parsedResponse["liveHeadTimeMs"] = ReadLiveHeadTimeMs(response)
end function
' The live timeline fields for a stream whose head (newest segment) is
@@ -148,6 +132,25 @@ namespace Innertube
return request
end function
' The head check's answer, sent once more when it lacks the head (HasLiveHead), whatever its HTTP status.
function FetchLiveHead(headUrl as string, cancellation as object) as HttpClient.Response
request = CreateLiveHeadRequest(headUrl)
request.RetryCount(1)
request.RetryIf(function(response as HttpClient.Response) as string
if not Innertube.HasLiveHead(response)
return `no X-Head-* in the response (HTTP ${response.StatusCode()})`
end if
return ""
end function)
request.Cancellation(cancellation)
return request.Await()
end function
' Whether a head check's answer carries the head's seqnum and time.
function HasLiveHead(response as HttpClient.Response) as boolean
return ReadLiveHeadSeqnum(response) >= 0 and ReadLiveHeadAnyTimeMs(response) <> invalid
end function
' X-Head-Seqnum of a live head response, -1 if absent. Not gated on HTTP status: a
' head check can come back non-2xx yet still carry the X-Head-* headers
' (observed: one stream returns 500, another 200; both include them).
@@ -167,6 +170,15 @@ namespace Innertube
return StringUtils.ParseJsonSafe(ValidString(response.Headers()["X-Head-Time-Millis"]))
end function
' X-Head-Time-Millis, else X-Head-Time-Sec in ms, invalid if neither.
function ReadLiveHeadAnyTimeMs(response as HttpClient.Response) as dynamic
timeMs = ReadLiveHeadTimeMs(response)
if timeMs = invalid
timeMs = ReadLiveHeadTimeSecAsMs(response)
end if
return timeMs
end function
' X-Head-Time-Sec in ms, invalid if absent: whole seconds, too coarse to average a
' young stream's few segments or to time the head between checks.
function ReadLiveHeadTimeSecAsMs(response as HttpClient.Response) as dynamic
@@ -190,7 +190,7 @@ namespace Innertube
if isPostLiveDvr
LogDebug("Fetching Post-Live DVR info")
GetPostLiveDvrInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, client, cancellation)
GetPostLiveDvrInfo(parsedResponse, adaptiveFormats, playerRequest.cpn, cancellation)
end if
if isOTF
@@ -235,7 +235,13 @@ namespace Innertube
errorLines.Push(subreason)
end if
playerErrorCommand = ObjectUtils.Dig(playabilityStatus, ["errorScreen", "playerErrorCommandRenderer"])
if IsAssociativeArray(playerErrorCommand)
errorLines.Append(ParsePlayerErrorCommandRenderer(playerErrorCommand))
end if
if errorLines.Count() = 0
Warning(`Unparsed playability status: ${status}`, playabilityStatus, { request: playerRequest })
errorLines.Push("Video not available (Unknown)")
end if
@@ -258,6 +264,47 @@ namespace Innertube
return errorLines.Join(`\n`)
end function
function ParsePlayerErrorCommandRenderer(renderer as object) as object
lines = []
errorMessage = ParseText(renderer["errorMessage"])
if errorMessage <> ""
lines.Push(errorMessage)
end if
lines.Append(ParseOpenPopupAction(ObjectUtils.Dig(renderer, ["command", "openPopupAction"])))
return lines
end function
function ParseOpenPopupAction(openPopupAction as object) as object
lines = []
panel = ObjectUtils.Dig(openPopupAction, ["popup", "overlaySectionRenderer", "overlay", "overlayTwoPanelRenderer", "actionPanel", "overlayPanelRenderer"])
if not IsAssociativeArray(panel)
return lines
end if
header = ObjectUtils.Dig(panel, ["header", "overlayPanelHeaderRenderer"])
title = ParseText(ObjectUtils.Dig(header, ["title"]))
if title <> ""
lines.Push(title)
end if
subtitle = ParseText(ObjectUtils.Dig(header, ["subtitle"]))
if subtitle <> ""
lines.Push(subtitle)
end if
items = ObjectUtils.Dig(panel, ["content", "overlayPanelItemListRenderer", "items"])
if not IsArray(items)
return lines
end if
for each item in items
url = ParseText(ObjectUtils.Dig(item, ["secondScreenActionRenderer", "url"]))
if url <> ""
lines.Push(url)
end if
lines.Append(ParseOpenPopupAction(ObjectUtils.Dig(item, ["compactLinkRenderer", "serviceEndpoint", "openPopupAction"])))
end for
return lines
end function
function PlayerResponseRequiresPageReload(payload as object) as boolean
signal = ObjectUtils.Dig(payload, ["playabilityStatus", "errorScreen", "playerErrorMessageRenderer", "proceedButton", "buttonRenderer", "command", "signalAction", "signal"])
return IsString(signal) and signal = "RELOAD_PAGE"
@@ -1,11 +1,11 @@
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/UrlUtils.bs"
namespace Innertube
function GetPostLiveDvrInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as void
function GetPostLiveDvrInfo(parsedResponse as object, adaptiveFormats as object, cpn as dynamic, cancellation as object) as void
if adaptiveFormats.Count() = 0
LogWarn("GetPostLiveDvrInfo: No adaptive formats available")
return
@@ -19,25 +19,16 @@ namespace Innertube
' Query the live edge (no sq): that response is Cache-Control: no-cache, always
' served fresh, so it carries X-Head-*. A finished stream's head is its final
' segment, so X-Head-Seqnum is the total count and X-Head-Time-Millis the duration.
primary = FetchPostLiveDvrHead(formatUrl, invalid, cpn, client, cancellation)
headers = invalid
' segment, so X-Head-Seqnum is the total count and X-Head-Time-* the duration.
headUrl = GetLiveHeadUrl(formatUrl, cpn)
response = FetchLiveHead(headUrl, cancellation)
if HasPostLiveDvrHead(primary)
headers = primary.headers
else
' sq=0 is cacheable, so an edge can return it missing X-Head-* (#359); fall
' back to it only when the live-edge query misses.
fallback = FetchPostLiveDvrHead(formatUrl, "0", cpn, client, cancellation)
diagnostics = PostLiveDvrDiagnostics(parsedResponse["videoId"], primary, fallback)
if HasPostLiveDvrHead(fallback)
headers = fallback.headers
LogTelemetryEvent({
level: "warning"
message: `GetPostLiveDvrInfo: no-sq missing head, sq=0 fallback recovered\n${diagnostics}`
fingerprint: ["GetPostLiveDvrInfo: sq=0 fallback recovered"]
})
else
if not HasLiveHead(response)
' sq=0 is cacheable, so an edge can return it missing X-Head-*; fall back to it
' only when the live-edge query misses.
fallback = FetchLiveHead(UrlUtils.AppendQueryParams(headUrl, { "sq": "0" }), cancellation)
diagnostics = PostLiveDvrDiagnostics(parsedResponse["videoId"], headUrl, response, fallback)
if not HasLiveHead(fallback)
' Warning, not error: a known transport-failure tail where playback fails regardless.
LogTelemetryEvent({
level: "warning"
@@ -46,10 +37,16 @@ namespace Innertube
})
return
end if
LogTelemetryEvent({
level: "warning"
message: `GetPostLiveDvrInfo: no-sq missing head, sq=0 fallback recovered\n${diagnostics}`
fingerprint: ["GetPostLiveDvrInfo: sq=0 fallback recovered"]
})
response = fallback
end if
durationMs = ValidString(headers["X-Head-Time-Millis"]).ToInt()
segmentCount = ValidString(headers["X-Head-Seqnum"]).ToInt()
durationMs = ReadLiveHeadAnyTimeMs(response)
segmentCount = ReadLiveHeadSeqnum(response)
if durationMs > 0
parsedResponse["postLiveDvrDurationMs"] = durationMs
@@ -59,40 +56,8 @@ namespace Innertube
end if
end function
function FetchPostLiveDvrHead(formatUrl as string, sq as dynamic, cpn as dynamic, client as Innertube.ClientType, cancellation as object) as object
queryComponents = UrlUtils.ParseQueryComponents(formatUrl)
queryComponents["rn"] = "0"
if sq <> invalid
queryComponents["sq"] = sq
end if
if not StringUtils.IsNullOrEmpty(cpn)
queryComponents["cpn"] = cpn
end if
url = UrlUtils.SetQueryParams(formatUrl, 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.RetryCount(1)
request.Cancellation(cancellation)
response = request.Await()
return {
url: url
statusCode: response.StatusCode()
headers: response.Headers()
}
end function
function HasPostLiveDvrHead(result as object) as boolean
return IsAssociativeArray(result) and IsAssociativeArray(result.headers) and result.headers.DoesExist("X-Head-Time-Millis") and result.headers.DoesExist("X-Head-Seqnum")
end function
function PostLiveDvrDiagnostics(videoId as dynamic, primary as object, fallback as object) as string
return `VideoID: ${ValidString(videoId)}` + Chr(10) + `URL (no-sq; sq=0 appends &sq=0): ${primary.url}` + Chr(10) + `no-sq HEAD status: ${primary.statusCode.ToStr()} headers: ${FormatJson(primary.headers)}` + Chr(10) + `sq=0 HEAD status: ${fallback.statusCode.ToStr()} headers: ${FormatJson(fallback.headers)}`
function PostLiveDvrDiagnostics(videoId as dynamic, headUrl as string, primary as HttpClient.Response, fallback as HttpClient.Response) as string
return `VideoID: ${ValidString(videoId)}` + Chr(10) + `URL (no-sq; sq=0 appends &sq=0): ${headUrl}` + Chr(10) + `no-sq HEAD status: ${primary.StatusCode().ToStr()} headers: ${FormatJson(primary.Headers())}` + Chr(10) + `sq=0 HEAD status: ${fallback.StatusCode().ToStr()} headers: ${FormatJson(fallback.Headers())}`
end function
end namespace
@@ -1,271 +0,0 @@
import "pkg:/components/Services/LoungeService/LoungeBytes.bs"
import "pkg:/source/utils/ByteArrayUtils.bs"
enum HttpDecoderState
Head
ChunkSize
ChunkData
Done
Redirect
Error
end enum
enum HttpDecoderError
None = ""
MalformedStatus = "malformed_status"
UnsupportedEncoding = "unsupported_encoding"
ChunkOverflow = "chunk_overflow"
ShortRead = "short_read"
end enum
const HTTP_DECODER_COMPACT_THRESHOLD = 32768
const HTTP_DECODER_READ_LENGTH = 65536
class HttpChunkedDecoder
public statusCode = 0
public statusText = ""
public errorReason = HttpDecoderError.None
public headers
private buffer
private cursor = 0
private state = HttpDecoderState.Head
private chunkRemaining = 0
private headCheckedSize = 0
function new()
m.buffer = CreateObject("roByteArray")
m.headers = {}
end function
function Pump(socket as object, output as object) as integer
received = m.ReceiveFrom(socket)
if received > 0
m.Process(output)
end if
return received
end function
function IsDone() as boolean
return m.state = HttpDecoderState.Done
end function
function IsError() as boolean
return m.state = HttpDecoderState.Error
end function
function IsRedirect() as boolean
return m.state = HttpDecoderState.Redirect
end function
function Location() as dynamic
return m.headers["location"]
end function
private function ReceiveFrom(socket as object) as integer
available = socket.GetCountRcvBuf()
if available <= 0
return 0
end if
lengthToRead = available
if lengthToRead > HTTP_DECODER_READ_LENGTH
lengthToRead = HTTP_DECODER_READ_LENGTH
end if
writeIndex = m.buffer.Count()
m.buffer[writeIndex + lengthToRead - 1] = 0
received = socket.Receive(m.buffer, writeIndex, lengthToRead)
if received > 0 and received < lengthToRead
' GetCountRcvBuf reported more than Receive delivered, leaving uninitialised slack.
m.errorReason = HttpDecoderError.ShortRead
m.state = HttpDecoderState.Error
end if
return received
end function
private function Process(output as object) as void
running = true
while running
if m.state = HttpDecoderState.Head
running = m.ParseHead()
else if m.state = HttpDecoderState.ChunkSize
running = m.ParseChunkSize()
else if m.state = HttpDecoderState.ChunkData
running = m.ParseChunkData(output)
else
running = false
end if
end while
m.Compact()
end function
' Status line and headers are ASCII, so they parse as a string; the chunk body that follows is
' not, so it stays in bytes.
private function ParseHead() as boolean
bufferSize = m.buffer.Count()
if bufferSize = m.headCheckedSize
return false
end if
head = m.buffer.ToAsciiString()
delimiter = head.InStr(`\r\n\r\n`)
if delimiter = -1
m.headCheckedSize = bufferSize
return false
end if
contentStart = delimiter + 4
if m.buffer[contentStart - 4] <> 13 or m.buffer[contentStart - 3] <> 10 or m.buffer[contentStart - 2] <> 13 or m.buffer[contentStart - 1] <> 10
m.statusText = "Invalid header delimiter - is there unicode text in headers?"
m.errorReason = HttpDecoderError.MalformedStatus
m.state = HttpDecoderState.Error
return false
end if
lines = head.Left(delimiter).Split(`\r\n`)
if not m.ParseStatusLine(lines[0])
return false
end if
for i = 1 to lines.Count() - 1
m.ParseHeaderLine(lines[i])
end for
m.cursor = contentStart
return m.FinishHead()
end function
private function ParseStatusLine(line as string) as boolean
if not line.StartsWith("HTTP/1.1 ") and not line.StartsWith("HTTP/1.0 ")
m.statusText = "Malformed status line"
m.errorReason = HttpDecoderError.MalformedStatus
m.state = HttpDecoderState.Error
return false
end if
rest = line.Mid(9).Trim()
spaceIndex = rest.InStr(" ")
if spaceIndex = -1
m.statusCode = Int(Val(rest, 10))
m.statusText = ""
else
m.statusCode = Int(Val(rest.Left(spaceIndex), 10))
m.statusText = rest.Mid(spaceIndex + 1)
end if
return true
end function
private function ParseHeaderLine(line as string) as void
colon = line.InStr(":")
if colon > 0
key = LCase(line.Left(colon).Trim())
m.headers[key] = line.Mid(colon + 1).Trim()
end if
end function
private function FinishHead() as boolean
if m.IsRedirectStatus(m.statusCode)
m.state = HttpDecoderState.Redirect
return false
end if
if m.statusCode <> 200
m.state = HttpDecoderState.Error
return false
end if
transferEncoding = m.headers["transfer-encoding"]
if transferEncoding = invalid or LCase(transferEncoding).InStr("chunked") = -1
m.statusText = "Unsupported transfer-encoding"
m.errorReason = HttpDecoderError.UnsupportedEncoding
m.state = HttpDecoderState.Error
return false
end if
m.state = HttpDecoderState.ChunkSize
return true
end function
private function IsRedirectStatus(code as integer) as boolean
return code = 301 or code = 302 or code = 303 or code = 307 or code = 308
end function
private function ParseChunkSize() as boolean
' Skip the CRLF trailing the previous chunk's data (and any stray newlines).
while m.cursor < m.buffer.Count() and (m.buffer[m.cursor] = 13 or m.buffer[m.cursor] = 10)
m.cursor += 1
end while
crlf = LoungeBytes.IndexOfCrlf(m.buffer, m.cursor)
if crlf = -1
return false
end if
sizeLine = LoungeBytes.RangeToString(m.buffer, m.cursor, crlf)
m.cursor = crlf + 2
' A chunk-size line may carry ';ext' extensions; the size is the leading hex token.
semicolon = sizeLine.InStr(";")
if semicolon > 0
sizeLine = sizeLine.Left(semicolon)
end if
m.chunkRemaining = Int(Val(sizeLine.Trim(), 16))
if m.chunkRemaining < 0
' A size that doesn't fit a 32-bit int is a corrupt size line or a parse desync.
m.errorReason = HttpDecoderError.ChunkOverflow
m.state = HttpDecoderState.Error
return false
end if
if m.chunkRemaining = 0
m.state = HttpDecoderState.Done
return false
end if
m.state = HttpDecoderState.ChunkData
return true
end function
private function ParseChunkData(output as object) as boolean
available = m.buffer.Count() - m.cursor
if available <= 0
return false
end if
take = available
if take > m.chunkRemaining
take = m.chunkRemaining
end if
chunk = ByteArrayUtils.Slice(m.buffer, m.cursor, m.cursor + take)
output.Append(chunk)
m.cursor += take
m.chunkRemaining -= take
if m.chunkRemaining = 0
m.state = HttpDecoderState.ChunkSize
return true
end if
return false
end function
' A fully consumed buffer Clears for free; a partial one waits until the dead prefix is worth a slice.
private function Compact() as void
if m.cursor = 0
return
end if
if m.cursor >= m.buffer.Count()
m.buffer.Clear()
else if m.cursor >= HTTP_DECODER_COMPACT_THRESHOLD
m.buffer = LoungeBytes.Tail(m.buffer, m.cursor)
else
return
end if
m.cursor = 0
m.headCheckedSize = 0
end function
end class
@@ -1,8 +1,6 @@
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs"
import "pkg:/components/Services/LoungeService/LoungeConstants.bs"
import "pkg:/components/Services/LoungeService/LoungeFraming.bs"
import "pkg:/components/Services/LoungeService/LoungeMessages.bs"
import "pkg:/components/Services/LoungeService/LoungeVideoQueue.bs"
import "pkg:/components/Services/LoungeService/Notifications/DeviceConnectedNotificationUtils.bs"
@@ -10,7 +8,7 @@ import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/UrlUtils.bs"
import "pkg:/source/utils/Types.bs"
const COMMAND_HANDLER_PREFIX = "_Handle_"
@@ -37,14 +35,14 @@ class LoungeApi
' Set by a send's failure, until the next bind.
public sessionGone = false
public tokenExpired = false
public backchannel as LoungeBackchannel
private ofs
private lastProcessedCommandIndex = -1
private backchannel
private messagePort
private pendingOutgoingMessages
private lastLoungeDisconnect
function new(loungeServiceNode as object, videoQueueNode as object, notificationsNode as object, invidiousNode as object)
function new(loungeServiceNode as object, videoQueueNode as object, notificationsNode as object, invidiousNode as object, messagePort as object)
m.loungeServiceNode = loungeServiceNode
m.videoQueueNode = videoQueueNode
m.notificationsNode = notificationsNode
@@ -55,7 +53,8 @@ class LoungeApi
m.deviceName = deviceName
m.screenName = deviceName
m.ofs = 0
m.backchannel = invalid
m.messagePort = messagePort
m.backchannel = new LoungeBackchannel()
m.pendingOutgoingMessages = []
m.devices = {}
@@ -119,23 +118,13 @@ class LoungeApi
response = request.Await()
if not response.IsSuccess()
error = Tr(Locale.Dialogs.LoungeFailedToGetScreenId) + `\n${response.ErrorMessage()}`
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Dialogs.LoungeServiceSetupError)
})
LogError(`Failed to get lounge screen ID\n${response.ErrorMessage()}`)
return invalid
end if
id = response.Text()
if not IsString(id)
error = Tr(Locale.Dialogs.LoungeFailedToGetScreenId) + `\n` = Tr(Locale.Dialogs.LoungeNotAValidScreenId).Replace("%1", `${id}`)
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Dialogs.LoungeServiceSetupError)
})
if StringUtils.IsNullOrEmpty(id)
LogError("Failed to get lounge screen ID: empty response")
return invalid
end if
@@ -155,24 +144,14 @@ class LoungeApi
response = request.Await()
if not response.IsSuccess()
error = Tr(Locale.Dialogs.LoungeFailedToGetLoungeToken) + `\n${response.ErrorMessage()}`
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Dialogs.LoungeServiceSetupError)
})
LogError(`Failed to get lounge token\n${response.ErrorMessage()}`)
return invalid
end if
json = response.Json()
screens = json.screens
screens = ValidAssociativeArray(json).screens
if not IsArray(screens) or screens.Count() <> 1
error = Tr(Locale.Dialogs.LoungeFailedToGetLoungeToken) + `\n` + Tr(Locale.Dialogs.LoungeInvalidResponse).Replace("%1", `${json}`)
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Dialogs.LoungeServiceSetupError)
})
LogError(`Failed to get lounge token: invalid response\nBody: ${response.Text()}`)
return invalid
end if
@@ -181,8 +160,8 @@ class LoungeApi
return m.loungeToken
end function
function GetSessionData() as boolean
queryParams = {
private function BindQueryParams(loungeData as object) as object
return {
"device": "LOUNGE_SCREEN"
"theme": "cl"
"capabilities": "vsp"
@@ -191,13 +170,16 @@ class LoungeApi
"v": "2"
"t": "1"
"app": "lb-v4"
"RID": "1337"
"name": loungeData.screenName
"id": loungeData.deviceId
"loungeIdToken": loungeData.loungeToken
"zx": m.Zx()
}
end function
queryParams["name"] = m.screenName
queryParams["id"] = m.deviceId
queryParams["loungeIdToken"] = m.loungeToken
queryParams["zx"] = m.Zx()
function GetSessionData() as boolean
queryParams = m.BindQueryParams(m)
queryParams["RID"] = "1337"
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams)
@@ -207,28 +189,16 @@ class LoungeApi
response = request.Await()
if not response.IsSuccess()
error = Tr(Locale.Dialogs.LoungeFailedToGetSessionData) + `\n${response.ErrorMessage()}`
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Dialogs.LoungeServiceSetupError)
})
LogError(`Failed to get lounge session data\n${response.ErrorMessage()}`)
return false
end if
body = CreateObject("roByteArray")
body.FromAsciiString(response.Text())
' A new session restarts command indices from 0; clear the high-water mark so its commands
' aren't skipped as duplicates. Its outbound offset restarts from 0 too.
m.lastProcessedCommandIndex = -1
m.ofs = 0
m.sessionGone = false
m.tokenExpired = false
messagesToSend = []
result = LoungeFraming.Extract(body, 0)
for each frame in result.frames
m.ProcessFrame(frame, messagesToSend)
for each command in m.backchannel.StartSession(response.Text())
m.ProcessCommand(command, messagesToSend)
end for
if StringUtils.IsNullOrEmpty(m.sessionId) or StringUtils.IsNullOrEmpty(m.gSessionId)
LogTelemetryEvent({
@@ -241,52 +211,35 @@ class LoungeApi
return true
end function
function FetchCommandsRpc(messagePort as object) as void
' Plain HTTP: LoungeBackchannel streams this response over a raw socket, which has no TLS
baseUrl = "http://www.youtube.com/api/lounge/bc/bind"
queryParams = {
"device": "LOUNGE_SCREEN"
"theme": "cl"
"capabilities": "vsp"
"mdxVersion": "2"
"VER": "8"
"v": "2"
"t": "1"
"app": "lb-v4"
"RID": "rpc"
"CI": "0"
}
queryParams["name"] = m.screenName
queryParams["id"] = m.deviceId
queryParams["loungeIdToken"] = m.loungeToken
function StartPoll() as void
queryParams = m.BindQueryParams(m)
queryParams["RID"] = "rpc"
queryParams["SID"] = m.sessionId
queryParams["gsessionid"] = m.gSessionId
queryParams["zx"] = m.Zx()
queryParams["CI"] = "1"
queryParams["TYPE"] = "xmlhttp"
url = UrlUtils.BuildUrl(baseUrl, invalid, queryParams)
if m.backchannel = invalid
m.backchannel = new LoungeBackchannel()
end if
m.backchannel.Open(url, messagePort)
request = HttpClient.Get("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams)
m.backchannel.Open(request, m.messagePort)
end function
function Poll(socketMessages as object, messagesToSend as object) as boolean
frames = m.backchannel.Poll(socketMessages)
for each frame in frames
m.ProcessFrame(frame, messagesToSend)
function HandleMessage(message as dynamic, messagesToSend as object) as void
for each command in m.backchannel.Handle(message)
m.ProcessCommand(command, messagesToSend)
end for
return m.backchannel.IsOpen()
m.HandleSends(message)
end function
function GetCloseInfo() as object
if m.backchannel = invalid
return { statusCode: 0, reason: "", target: "" }
end if
return { statusCode: m.backchannel.statusCode, reason: m.backchannel.closeReason, target: m.backchannel.redirectTarget }
function MaxWaitMs() as integer
waitMs = m.backchannel.MaxWaitMs()
for each pending in m.pendingOutgoingMessages
pendingWaitMs = pending.MaxWaitMs()
if waitMs = 0 or pendingWaitMs < waitMs
waitMs = pendingWaitMs
end if
end for
return waitMs
end function
function RefreshToken() as dynamic
@@ -303,10 +256,7 @@ class LoungeApi
end function
function Rebind(withNewToken as boolean) as boolean
for each pending in m.pendingOutgoingMessages
pending.Cancel()
end for
m.pendingOutgoingMessages = []
m.CancelSends()
if withNewToken
LogWarnNoTelemetry("Lounge token expired, refreshing")
@@ -319,58 +269,38 @@ class LoungeApi
return m.Bind()
end function
function ProcessFrame(frame as string, messagesToSend as object) as void
commands = StringUtils.ParseJsonSafe(frame)
if not IsArray(commands)
LogTelemetryEvent({
level: "error"
message: "Lounge frame did not parse to a command array: " + frame.Left(256)
fingerprint: "lounge-unparseable-frame"
})
return
end if
m.ProcessCommands(commands, messagesToSend)
function EndSession() as void
m.backchannel.Close()
m.CancelSends()
m.loungeToken = invalid
end function
function ProcessCommands(commands as object, messagesToSend as object) as void
for each command in commands
if not IsArray(command) or command.Count() <> 2
continue for
end if
commandIndex = command[0]
commandData = command[1]
commandType = commandData[0]
if commandIndex <= m.lastProcessedCommandIndex and commandType <> COMMAND_TYPE_G_SESSION_ID and commandType <> COMMAND_TYPE_SESSION_ID
LogDebug("Skipping command already processed:", command)
continue for
end if
m.lastProcessedCommandIndex = commandIndex
commandArgs = invalid
if commandData.Count() > 1
commandArgs = commandData[1]
end if
handler = COMMAND_HANDLER_PREFIX + commandType
if m.DoesExist(handler)
LogInfo(commandIndex, commandType)
m[handler](commandIndex, commandType, commandArgs, messagesToSend)
else
fingerprint = "Unknown command type:" + ToString(commandType)
message = fingerprint + " command:" + ToString(command)
LogWarnNoTelemetry(message)
LogTelemetryEvent({
level: "warning"
message: message
fingerprint: fingerprint
})
#if DEBUG
throw message
#end if
end if
private function CancelSends() as void
for each pending in m.pendingOutgoingMessages
pending.Cancel()
end for
m.pendingOutgoingMessages = []
end function
function ProcessCommand(command as LoungeCommand, messagesToSend as object) as void
handler = COMMAND_HANDLER_PREFIX + command.type
if m.DoesExist(handler)
LogInfo(command.index, command.type)
m[handler](command.index, command.type, command.args, messagesToSend)
return
end if
fingerprint = "Unknown command type:" + command.type
message = fingerprint + " command:" + ToString(command)
LogWarnNoTelemetry(message)
LogTelemetryEvent({
level: "warning"
message: message
fingerprint: fingerprint
})
#if DEBUG
throw message
#end if
end function
function HandleIgnoreCommand(_commandId as integer, commandType as string, commandArgs as object, _messagesToSend as object)
@@ -387,20 +317,11 @@ class LoungeApi
LogInfo("gSessionId:", m.gSessionId)
end function
function HandleGetPlayingNow(commandId as integer, _commandType as string, _commandArgs as object, messagesToSend as object) as void
function HandleGetPlayingNow(_commandId as integer, _commandType as string, _commandArgs as object, messagesToSend as object) as void
player = m.videoQueueNode.player
message = LoungeMessages.OnHasPreviousNextChanged(m.videoQueueNode.hasPrevious, m.videoQueueNode.hasNext)
message["commandId"] = commandId
messagesToSend.Push(message)
message = LoungeMessages.NowPlaying(player)
message["commandId"] = commandId
messagesToSend.Push(message)
message = LoungeMessages.OnStateChange(player)
message["commandId"] = commandId
messagesToSend.Push(message)
messagesToSend.Push(LoungeMessages.OnHasPreviousNextChanged(m.videoQueueNode.hasPrevious, m.videoQueueNode.hasNext))
messagesToSend.Push(LoungeMessages.NowPlaying(player))
messagesToSend.Push(LoungeMessages.OnStateChange(player))
end function
function HandleLoungeStatus(_commandId as integer, commandType as string, commandArgs as object, _messagesToSend as object) as void
@@ -556,7 +477,7 @@ class LoungeApi
messagesToSend.Push(LoungeMessages.OnPlaybackSpeedChanged(speed, true))
end function
function HandleGetPlaybackSpeed(commandId as integer, _commandType as string, _commandArgs as object, messagesToSend as object) as void
function HandleGetPlaybackSpeed(_commandId as integer, _commandType as string, _commandArgs as object, messagesToSend as object) as void
player = m.videoQueueNode.player
if player = invalid
return
@@ -572,39 +493,23 @@ class LoungeApi
speed = 1.0
end if
message = LoungeMessages.OnPlaybackSpeedChanged(speed)
message["commandId"] = commandId
messagesToSend.Push(message)
messagesToSend.Push(LoungeMessages.OnPlaybackSpeedChanged(speed))
end function
function SendMessages(messages as object) as void
if messages.Count() = 0
return
end if
m.pendingOutgoingMessages.Push(m.SendMessagesTo(m, messages))
m.pendingOutgoingMessages.Push(m.SendRequest(m, messages, m.backchannel.ackedCommandIndex).SendOn(m.messagePort))
end function
private function SendMessagesTo(loungeData as object, messages as object) as HttpClient.PendingResponse
queryParams = {
"device": "LOUNGE_SCREEN"
"theme": "cl"
"capabilities": "vsp"
"mdxVersion": "2"
"VER": "8"
"v": "2"
"t": "1"
"app": "lb-v4"
"RID": "1337"
}
queryParams["name"] = loungeData.screenName
queryParams["id"] = loungeData.deviceId
queryParams["loungeIdToken"] = loungeData.loungeToken
private function SendRequest(loungeData as object, messages as object, ackedCommandIndex as integer) as HttpClient.Request
queryParams = m.BindQueryParams(loungeData)
queryParams["RID"] = "1337"
queryParams["SID"] = loungeData.sessionId
queryParams["gsessionid"] = loungeData.gSessionId
queryParams["zx"] = m.Zx()
if messages[0].commandId <> invalid
queryParams["AID"] = messages[0].commandId
if ackedCommandIndex >= 0
queryParams["AID"] = ackedCommandIndex
end if
postData = [
@@ -633,64 +538,51 @@ class LoungeApi
request = HttpClient.Post("https://www.youtube.com/api/lounge/bc/bind")
request.QueryParams(queryParams)
request.FormBody(postData)
return request.Send()
return request
end function
function HasPendingOutgoingMessages() as boolean
return m.pendingOutgoingMessages.Count() > 0
end function
function ProcessPendingOutgoingMessages() as object
results = []
stillPending = []
for each pending in m.pendingOutgoingMessages
response = pending.Poll()
if response = invalid
stillPending.Push(pending)
else
status = response.StatusCode()
error = response.ErrorMessage()
results.Push({
"status": status
"error": error
})
private function HandleSends(message as dynamic) as void
for i = m.pendingOutgoingMessages.Count() - 1 to 0 step -1
response = m.pendingOutgoingMessages[i].Handle(message)
if response <> invalid
m.pendingOutgoingMessages.Delete(i)
if not response.IsSuccess()
isGone = response.StatusCode() = 410
unknownSid = response.StatusCode() = 400 and response.ErrorMessage().InStr("Unknown SID") <> -1
expiredToken = response.StatusCode() = 401 and response.ErrorMessage().InStr("Expired lounge id token") <> -1
isKnownError = isGone or unknownSid or expiredToken
if isGone or unknownSid
m.sessionGone = true
else if expiredToken
m.tokenExpired = true
end if
if isKnownError
' NoTelemetry: the body carries a volatile token; logging it would fragment these.
LogErrorNoTelemetry(response.ErrorMessage())
if expiredToken
LogTelemetryEvent({
level: "warning"
message: "Lounge id token expired"
fingerprint: "lounge-expired-token"
})
end if
else
LogErrorNoTelemetry(error)
LogTelemetryEvent({
level: "error"
message: error
fingerprint: ["lounge-send-failure", status]
})
end if
m.OnSendFailed(response)
end if
end if
end for
m.pendingOutgoingMessages = stillPending
end function
return results
private function OnSendFailed(response as HttpClient.Response) as void
status = response.StatusCode()
error = response.ErrorMessage()
isGone = status = 410
unknownSid = status = 400 and error.InStr("Unknown SID") <> -1
expiredToken = status = 401 and error.InStr("Expired lounge id token") <> -1
if isGone or unknownSid
m.sessionGone = true
else if expiredToken
m.tokenExpired = true
end if
if isGone or unknownSid or expiredToken
' NoTelemetry: the body carries a volatile token; logging it would fragment these.
LogErrorNoTelemetry(error)
if expiredToken
LogTelemetryEvent({
level: "warning"
message: "Lounge id token expired"
fingerprint: "lounge-expired-token"
})
end if
else
LogErrorNoTelemetry(error)
LogTelemetryEvent({
level: "error"
message: error
fingerprint: ["lounge-send-failure", status]
})
end if
end function
function SaveCurrentLoungeData() as void
@@ -750,7 +642,7 @@ class LoungeApi
' This is the last message we'll be sending to this lounge.
loungeData.ofs = 99999999
' Held: dropping it releases its transfer, which aborts the send.
m.lastLoungeDisconnect = m.SendMessagesTo(loungeData, messages)
m.lastLoungeDisconnect = m.SendRequest(loungeData, messages, -1).Send()
end function
end class
@@ -1,242 +1,166 @@
import "pkg:/components/Services/LoungeService/HttpChunkedDecoder.bs"
import "pkg:/components/Services/LoungeService/LoungeBytes.bs"
import "pkg:/components/Services/LoungeService/LoungeFraming.bs"
import "pkg:/components/Services/LoungeService/LoungeService.types.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/UrlUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
' Server sends periodic noop keepalives, so no data for this long means a dead connection.
const LOUNGE_BACKCHANNEL_TIMEOUT_MS = 60000
const LOUNGE_BACKCHANNEL_BODY_COMPACT = 32768
const LOUNGE_BACKCHANNEL_MAX_REDIRECTS = 10
' The server answers a poll with a noop after at most ~30 s idle, and drops a session that goes 55-60 s without a poll.
' Giving up on a dead connection by 40 s lets the next poll, after the first backoff, land before the session is gone.
const LOUNGE_POLL_TIMEOUT_MS = 40000
' Raw socket on plain HTTP: roUrlTransfer can't read a streaming body incrementally, and
' roStreamSocket has no TLS.
class LoungeBackchannel
public statusCode = 0
public closeReason = ""
public redirectTarget = ""
public closeReason as LoungeCloseReason
public ackedCommandIndex = -1
public stalledPolls = 0
public pollTimeoutMs = LOUNGE_POLL_TIMEOUT_MS
private socket
private decoder
private body
private bodyCursor = 0
private timer
private url = ""
private messagePort
private redirectCount = 0
private pending = invalid
private polledCommandIndex = -1
function new()
m.timer = CreateObject("roTimespan")
' A new session restarts command indices from 0.
function StartSession(bindResponseText as string) as LoungeCommand[]
m.ackedCommandIndex = -1
m.stalledPolls = 0
return m.Receive(m.ExtractFrames(bindResponseText))
end function
function Open(url as string, messagePort as object) as boolean
m.messagePort = messagePort
m.redirectCount = 0
m.redirectTarget = ""
return m.Connect(url)
end function
private function Connect(url as string) as boolean
' A redirect or reconnect reuses Connect; close the previous socket so it doesn't leak.
if m.socket <> invalid
m.socket.NotifyReadable(false)
m.socket.Close()
m.socket = invalid
end if
m.url = url
function Open(request as HttpClient.Request, messagePort as object) as void
m.statusCode = 0
m.closeReason = ""
urlObject = UrlUtils.ParseUrl(url)
if urlObject.protocol <> "http"
m.closeReason = "invalid_protocol"
LogError("Lounge backchannel needs http, got:", urlObject.protocol)
return false
end if
portValue = urlObject.port
if portValue = invalid or portValue = ""
portValue = "80"
end if
address = CreateObject("roSocketAddress")
address.SetAddress(urlObject.host + ":" + portValue)
socket = CreateObject("roStreamSocket")
socket.SetSendToAddress(address)
if not socket.Connect()
m.closeReason = "connect_failed"
LogWarnNoTelemetry("Lounge backchannel connect failed:", urlObject.host)
return false
end if
CRLF = Chr(13) + Chr(10)
request = "GET " + urlObject.path + " HTTP/1.1" + CRLF
request += "Host: " + urlObject.host + CRLF
request += "Connection: keep-alive" + CRLF
request += CRLF
socket.SendStr(request)
socket.NotifyReadable(true)
socket.SetMessagePort(m.messagePort)
m.socket = socket
m.decoder = new HttpChunkedDecoder()
m.body = CreateObject("roByteArray")
m.bodyCursor = 0
m.timer.Mark()
LogInfo("Lounge backchannel open, socket", socket.GetID())
return true
end function
function IsOpen() as boolean
return m.socket <> invalid and m.closeReason = ""
end function
function Poll(socketEvents as object) as object
frames = []
if m.socket = invalid
return frames
end if
if not m.socket.IsConnected()
m.CloseWith("disconnected")
return frames
end if
if m.timer.TotalMilliseconds() > LOUNGE_BACKCHANNEL_TIMEOUT_MS
m.CloseWith("timeout")
return frames
end if
if not m.HasReadableEvent(socketEvents)
return frames
end if
received = m.decoder.Pump(m.socket, m.body)
if received = 0
m.CloseWith("eof")
return frames
else if received < 0
if not m.socket.eOK()
m.CloseWith("receive_error")
end if
return frames
end if
m.timer.Mark()
if m.decoder.IsRedirect()
return m.FollowRedirect()
end if
result = LoungeFraming.Extract(m.body, m.bodyCursor)
m.bodyCursor = result.nextPos
for each frame in result.frames
frames.Push(frame)
end for
m.CompactBody()
if m.decoder.IsError()
m.statusCode = m.decoder.statusCode
if m.decoder.errorReason <> HttpDecoderError.None
m.CloseWith(m.decoder.errorReason)
else
m.CloseWith("http_" + StrI(m.statusCode).Trim())
end if
else if m.decoder.IsDone()
m.CloseWith("complete")
end if
return frames
m.closeReason = invalid
m.polledCommandIndex = m.ackedCommandIndex
m.pending = request.QueryParam("AID", m.ackedCommandIndex).NoCache().RetryCount(0).AttemptTimeoutMs(m.pollTimeoutMs).SendOn(messagePort)
end function
function Close() as void
m.CloseWith("closed")
end function
private function HasReadableEvent(socketEvents as object) as boolean
id = m.socket.GetID()
for each event in socketEvents
if event.GetSocketID() = id
return true
end if
end for
return false
end function
private function CloseWith(reason as string) as void
if m.socket <> invalid
m.socket.NotifyReadable(false)
m.socket.Close()
m.socket = invalid
end if
if m.closeReason = ""
m.closeReason = reason
if m.pending <> invalid
m.pending.Cancel()
m.pending = invalid
end if
end function
private function CompactBody() as void
if m.bodyCursor = 0
return
function IsPolling() as boolean
return m.pending <> invalid
end function
function MaxWaitMs() as integer
if m.pending = invalid
return 0
end if
if m.bodyCursor >= m.body.Count()
m.body.Clear()
else if m.bodyCursor >= LOUNGE_BACKCHANNEL_BODY_COMPACT
m.body = LoungeBytes.Tail(m.body, m.bodyCursor)
return m.pending.MaxWaitMs()
end function
function Handle(message as dynamic) as LoungeCommand[]
if m.pending = invalid
return []
end if
response = m.pending.Handle(message)
if response = invalid
return []
end if
m.pending = invalid
m.statusCode = response.StatusCode()
if response.IsTimedOut()
m.closeReason = LoungeCloseReason.Timeout
return []
end if
if m.statusCode = 0
m.closeReason = LoungeCloseReason.NotSent
return []
end if
if m.statusCode < 0
m.closeReason = LoungeCloseReason.Curl
return []
end if
if m.statusCode < 200 or m.statusCode >= 300
m.closeReason = LoungeCloseReason.Http
return []
end if
frames = m.ExtractFrames(response.Text())
if frames.Count() = 0
m.closeReason = LoungeCloseReason.Empty
return []
end if
commands = m.Receive(frames)
' Nothing acknowledged: the next poll is answered with the same frames.
if m.ackedCommandIndex = m.polledCommandIndex
m.closeReason = LoungeCloseReason.Stalled
m.stalledPolls += 1
else
return
m.closeReason = LoungeCloseReason.Complete
m.stalledPolls = 0
end if
m.bodyCursor = 0
return commands
end function
private function FollowRedirect() as object
frames = []
location = m.decoder.Location()
if not IsString(location) or location = ""
m.CloseWith("redirect_no_location")
return frames
function CloseLabel() as string
if m.closeReason = LoungeCloseReason.Curl or m.closeReason = LoungeCloseReason.Http
return `${m.closeReason}_${Abs(m.statusCode)}`
end if
return m.closeReason
end function
nextUrl = LoungeRedirect.Resolve(m.url, location)
m.redirectTarget = nextUrl
m.redirectCount += 1
if m.redirectCount > LOUNGE_BACKCHANNEL_MAX_REDIRECTS
m.CloseWith("redirect_limit")
return frames
private function ExtractFrames(text as string) as object
body = CreateObject("roByteArray")
body.FromAsciiString(text)
result = LoungeFraming.Extract(body, 0)
if result.nextPos < body.Count()
LogTelemetryEvent({
level: "warning"
message: `Lounge answer ended mid-frame, ${body.Count() - result.nextPos} bytes left: ${text}`
fingerprint: "lounge-partial-frame"
})
end if
return result.frames
end function
LogInfo("Lounge backchannel following redirect to", m.redirectTarget)
m.Connect(nextUrl)
return frames
private function Receive(frames as object) as LoungeCommand[]
commands = []
for each frame in frames
entries = StringUtils.ParseJsonSafe(frame)
if not IsArray(entries)
LogTelemetryEvent({
level: "error"
message: "Lounge frame did not parse to a command array: " + frame.Left(256)
fingerprint: "lounge-unparseable-frame"
})
continue for
end if
for each entry in entries
if not IsArray(entry) or entry.Count() = 0 or not IsInt(entry[0])
m.LogMalformedCommand(entry)
continue for
end if
index = entry[0]
if index <= m.ackedCommandIndex
LogDebug("Skipping command already received:", entry)
continue for
end if
' Acknowledged before validation: the server answers an unacknowledged command again, at once.
m.ackedCommandIndex = index
data = entry[1]
if not IsArray(data) or data.Count() = 0 or not IsString(data[0])
m.LogMalformedCommand(entry)
continue for
end if
commands.Push({ index: index, type: data[0], args: data[1] })
end for
end for
return commands
end function
private function LogMalformedCommand(entry as dynamic) as void
LogTelemetryEvent({
level: "error"
message: "Malformed lounge command: " + FormatJson(entry).Left(256)
fingerprint: "lounge-malformed-command"
})
end function
end class
namespace LoungeRedirect
' Force the target to plain HTTP - a raw socket has no TLS, so an https redirect is followed over http.
function Resolve(currentUrl as string, location as string) as string
if location.StartsWith("http://") or location.StartsWith("https://")
parts = UrlUtils.ParseUrl(location)
else
parts = UrlUtils.ParseUrl(currentUrl)
if not location.StartsWith("/")
location = "/" + location
end if
parts.path = location
end if
parts.protocol = "http"
if parts.port = "80" or parts.port = "443"
parts.port = invalid
end if
return UrlUtils.BuildUrlFromParts(parts)
end function
end namespace
@@ -6,16 +6,6 @@ namespace LoungeBytes
return ByteArrayUtils.Slice(bytes, fromIndex, toIndex).ToAsciiString()
end function
function IndexOfCrlf(bytes as object, fromIndex as integer) as integer
last = bytes.Count() - 2
for i = fromIndex to last
if bytes[i] = 13 and bytes[i + 1] = 10
return i
end if
end for
return -1
end function
function IndexOfByte(bytes as object, fromIndex as integer, value as integer) as integer
last = bytes.Count() - 1
for i = fromIndex to last
@@ -26,8 +16,4 @@ namespace LoungeBytes
return -1
end function
function Tail(bytes as object, fromIndex as integer) as object
return ByteArrayUtils.Slice(bytes, fromIndex)
end function
end namespace
@@ -1,8 +1,7 @@
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/components/Services/LoungeService/LoungeApi.bs"
const IDLE_WAIT_MS = 60000
const SENDS_IN_FLIGHT_WAIT_MS = 500
import "pkg:/components/Services/LoungeService/LoungeService.types.bs"
import "pkg:/components/Services/LoungeService/LoungeSession.bs"
function Init()
m.top.functionName = "LoungeServiceLoop"
@@ -21,6 +20,7 @@ function StartService(_unused as dynamic) as boolean
return true
end if
m.top.isRunning = true
m.top.control = "run"
return true
end function
@@ -34,65 +34,83 @@ function StopService(_unused as dynamic) as void
end function
function LoungeServiceLoop() as void
api = new LoungeApi(m.top, m.top.videoQueue, m.top.notifications, m.top.invidious)
messagePort = CreateObject("roMessagePort")
m.top.observeField("shouldQuit", messagePort)
api = new LoungeApi(m.top, m.top.videoQueue, m.top.notifications, m.top.invidious, messagePort)
' Mobile app can remain connected to devices even after restarts.
' Since we create a new lounge every time, we signal to the last lounge
' that we're no longer there, and we're not coming back.
api.DisconnectFromLastLounge()
messagePort = CreateObject("roMessagePort")
' We do not join a lounge until something asks us to like
' - A remote connects through DIAL
' - Generating a TV link code
' Both join only while loungeToken is empty: a session that ends clears it.
while WaitForJoin(messagePort)
quitRequested = RunSession(api, messagePort)
api.EndSession()
m.top.unobserveField("outgoingMessages")
m.top.loungeToken = ""
if quitRequested
exit while
end if
end while
LogInfo("Lounge service stopped")
m.top.unobserveField("shouldQuit")
m.top.isRunning = false
end function
function WaitForJoin(messagePort as object) as boolean
m.top.observeField("join", messagePort)
wait(0, messagePort)
joinRequested = false
while true
message = wait(0, messagePort)
if IsQuitRequested([message])
exit while
end if
if type(message) = "roSGNodeEvent" and message.GetField() = "join"
joinRequested = true
exit while
end if
end while
m.top.unobserveField("join")
return joinRequested
end function
function RunSession(api as LoungeApi, messagePort as object) as boolean
screenId = api.GetScreenId()
if StringUtils.IsNullOrEmpty(screenId)
Shutdown("No screen ID found")
return
LogInfo("Lounge session ended: no screen ID")
return false
end if
m.top.screenId = screenId
loungeToken = api.GetToken()
if StringUtils.IsNullOrEmpty(loungeToken)
Shutdown("No lounge token found")
return
LogInfo("Lounge session ended: no lounge token")
return false
end if
m.top.loungeToken = loungeToken
m.top.observeField("outgoingMessages", messagePort)
if not api.Bind()
Shutdown("Failed to bind")
return
LogInfo("Lounge session ended: bind failed")
return false
end if
api.FetchCommandsRpc(messagePort)
api.StartPoll()
m.top.shouldQuit = false
isOpen = false
backchannel = api.backchannel
reconnectAttempts = 0
sinceDelivered = CreateObject("roTimespan")
outgoingLoungeMessages = []
portMessages = []
socketMessages = []
while true
if m.top.shouldQuit = true
exit while
end if
' Sends answer on ports of their own, read only when the loop wakes.
waitMs = IDLE_WAIT_MS
if api.HasPendingOutgoingMessages()
waitMs = SENDS_IN_FLIGHT_WAIT_MS
end if
message = wait(waitMs, messagePort)
portMessages.Clear()
portMessages.Push(message)
portMessages.Push(wait(api.MaxWaitMs(), messagePort))
' There's a chance messages were piling up while we were sending messages to the lounge
' This could happen if we were sending things to the lounge and the player state
@@ -100,75 +118,81 @@ function LoungeServiceLoop() as void
while messagePort.PeekMessage() <> invalid
portMessages.Push(messagePort.GetMessage())
end while
if IsQuitRequested(portMessages)
return true
end if
' At this point:
' - We check if we need to send messages to the lounge based on player state
' - We check the lounge for new commands, which might need responding to
' - Finally, we send the outgoing messages to the lounge in one go
outgoingLoungeMessages.Clear()
socketMessages.Clear()
for each portMessage in portMessages
messageType = type(portMessage)
if messageType = "roSocketEvent"
socketMessages.Push(portMessage)
else if messageType = "roSGNodeEvent"
field = portMessage.GetField()
if field = "outgoingMessages"
messages = portMessage.GetData()
outgoingLoungeMessages.Append(messages)
end if
if type(portMessage) = "roSGNodeEvent" and portMessage.GetField() = "outgoingMessages"
outgoingLoungeMessages.Append(portMessage.GetData())
end if
api.HandleMessage(portMessage, outgoingLoungeMessages)
end for
isOpen = api.Poll(socketMessages, outgoingLoungeMessages)
api.SendMessages(outgoingLoungeMessages)
api.ProcessPendingOutgoingMessages()
' A send's failure is acted on once the backchannel closes, which a dead session's does too.
if not isOpen
closeInfo = api.GetCloseInfo()
needsRebind = closeInfo.statusCode = 410 or closeInfo.statusCode = 400 or api.sessionGone
needsTokenRefresh = closeInfo.statusCode = 401 or api.tokenExpired
LogDebug("Backchannel closed:", closeInfo.reason)
if IsActionableCloseFailure(closeInfo.reason, needsRebind, needsTokenRefresh)
message = "Lounge backchannel failure: " + closeInfo.reason
if not StringUtils.IsNullOrEmpty(closeInfo.target)
message += " -> " + closeInfo.target
end if
LogTelemetryEvent({
level: "warning"
message: message
fingerprint: "lounge-backchannel-" + closeInfo.reason
})
end if
sleep(ComputeReconnectBackoffMs(reconnectAttempts))
reconnectAttempts += 1
if needsRebind or needsTokenRefresh
if not api.Rebind(needsTokenRefresh)
Shutdown("Failed to rebind")
return
end if
m.top.loungeToken = api.loungeToken
end if
api.FetchCommandsRpc(messagePort)
else
reconnectAttempts = 0
if backchannel.IsPolling()
continue while
end if
if backchannel.closeReason = LoungeCloseReason.Complete
sinceDelivered.Mark()
end if
' A send's failure is acted on once the poll ends, which a dead session's does too.
nextStep = LoungeSession.StepAfterPoll(backchannel.closeReason, backchannel.statusCode, backchannel.stalledPolls, api.sessionGone, api.tokenExpired, sinceDelivered.TotalMilliseconds())
if nextStep = LoungeSessionStep.Poll
reconnectAttempts = 0
api.StartPoll()
continue while
end if
closeLabel = backchannel.CloseLabel()
LogDebug("Backchannel closed:", closeLabel, "next:", nextStep)
if nextStep = LoungeSessionStep.Drop
LogTelemetryEvent({
level: "error"
message: `Lounge session dropped: no poll delivered for ${sinceDelivered.TotalSeconds()} s, last close: ${closeLabel}`
fingerprint: ["lounge-session-dropped", closeLabel]
})
return false
end if
if nextStep = LoungeSessionStep.Retry and backchannel.closeReason <> LoungeCloseReason.Timeout
LogTelemetryEvent({
level: "warning"
message: "Lounge backchannel failure: " + closeLabel
fingerprint: "lounge-backchannel-" + closeLabel
})
end if
sleep(ComputeReconnectBackoffMs(reconnectAttempts))
reconnectAttempts += 1
if nextStep <> LoungeSessionStep.Retry
if not api.Rebind(nextStep = LoungeSessionStep.RebindWithNewToken)
LogInfo("Lounge session ended: rebind failed")
return false
end if
m.top.loungeToken = api.loungeToken
end if
api.StartPoll()
end while
Shutdown("Service stopped")
return false
end function
function Shutdown(reason as string)
LogInfo("Shutting down:", reason)
m.top.unobserveField("outgoingMessages")
m.top.isRunning = false
function IsQuitRequested(portMessages as object) as boolean
for each portMessage in portMessages
if type(portMessage) = "roSGNodeEvent" and portMessage.GetField() = "shouldQuit" and portMessage.GetData() = true
return true
end if
end for
return false
end function
' Full jitter (random in [0, window)) avoids a fleet-wide thundering-herd reconnect.
@@ -183,13 +207,3 @@ function ComputeReconnectBackoffMs(attempts as integer) as integer
end if
return 500 + Int(Rnd(0) * windowMs)
end function
function IsActionableCloseFailure(reason as string, needsRebind as boolean, needsTokenRefresh as boolean) as boolean
if needsRebind or needsTokenRefresh
return false
end if
if reason = "complete" or reason = "eof" or reason = "closed" or reason = "timeout" or reason = "disconnected" or reason = ""
return false
end if
return true
end function
@@ -0,0 +1,23 @@
enum LoungeCloseReason
Complete = "complete"
Empty = "empty"
Stalled = "stalled"
Timeout = "timeout"
NotSent = "not_sent"
Curl = "curl"
Http = "http"
end enum
enum LoungeSessionStep
Poll = "poll"
Retry = "retry"
Rebind = "rebind"
RebindWithNewToken = "rebind_with_new_token"
Drop = "drop"
end enum
interface LoungeCommand
index as integer
type as string
args as dynamic
end interface
@@ -0,0 +1,26 @@
import "pkg:/components/Services/LoungeService/LoungeService.types.bs"
namespace LoungeSession
const GIVE_UP_MS = 300000
function StepAfterPoll(closeReason as LoungeCloseReason, statusCode as integer, stalledPolls as integer, sessionGone as boolean, tokenExpired as boolean, msSinceDelivered as integer) as LoungeSessionStep
' A new session doesn't answer the frames a stalled one keeps answering.
needsRebind = statusCode = 400 or statusCode = 410 or sessionGone or stalledPolls > 1
needsNewToken = statusCode = 401 or tokenExpired
if closeReason = LoungeCloseReason.Complete and not needsRebind and not needsNewToken
return LoungeSessionStep.Poll
end if
if msSinceDelivered >= LoungeSession.GIVE_UP_MS
return LoungeSessionStep.Drop
end if
if needsNewToken
return LoungeSessionStep.RebindWithNewToken
end if
if needsRebind
return LoungeSessionStep.Rebind
end if
return LoungeSessionStep.Retry
end function
end namespace
@@ -0,0 +1,26 @@
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
namespace VideoLoadHandoff
function Read(path as string, videoLoadId as string) as dynamic
handoff = StringUtils.ParseJsonSafe(ReadAsciiFile(path))
if not IsAssociativeArray(handoff) or handoff["video_load_id"] <> videoLoadId
return invalid
end if
return handoff["value"]
end function
function Write(path as string, videoLoadId as string, value as dynamic) as void
WriteAsciiFile(path, FormatJson({ "video_load_id": videoLoadId, "value": value }))
end function
function ReadAndDelete(path as string, videoLoadId as string) as dynamic
value = VideoLoadHandoff.Read(path, videoLoadId)
if value <> invalid
DeleteFile(path)
end if
return value
end function
end namespace
@@ -155,6 +155,7 @@ function ExecuteJob() as void
if isDrm
licenseServerURL = UrlUtils.BuildUrl(`http://127.0.0.1:${playletServerPort}/api/innertube/get_drm_license`, invalid, {
videoId: metadata.videoId
videoLoadId: videoLoadId
drmParams: metadata.drmParams
drmSessionId: metadata.drmSessionId
cpn: metadata.cpn
@@ -1,4 +1,6 @@
import "pkg:/components/Services/Dash/LiveHeadCounts.bs"
import "pkg:/components/Services/Dash/LiveLoadCounts.bs"
import "pkg:/components/Services/Innertube/DrmLicenseRequests.bs"
import "pkg:/components/Telemetry/VideoLoadHandoff.bs"
import "pkg:/components/VideoPlayerDev/VideoNode.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Locale.bs"
@@ -345,11 +347,9 @@ namespace PlaybackTelemetry
"tail_resolve_samples": m.tailResolveSamples
}
if m.transport.isLive
liveHead = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH))
if liveHead <> invalid and liveHead["video_load_id"] = summary["video_load_id"]
summary["live_head"] = liveHead["counts"]
DeleteFile(LIVE_HEAD_COUNTS_PATH)
end if
liveLoadCounts = ValidAssociativeArray(VideoLoadHandoff.ReadAndDelete(LIVE_LOAD_COUNTS_PATH, summary["video_load_id"]))
summary["live_head"] = liveLoadCounts["live_head"]
summary["live_timeline"] = liveLoadCounts["live_timeline"]
summary["start_segment_bitrate_bps"] = m.startSegmentBitrateBps
summary["start_measured_bitrate_bps"] = m.startMeasuredBitrateBps
end if
@@ -358,6 +358,14 @@ namespace PlaybackTelemetry
summary["stream_source"] = content.playletStreamSource
summary["drm"] = not StringUtils.IsNullOrEmpty(ValidAssociativeArray(content.drmParams).keySystem)
summary["stream_url_index"] = content.playletStreamUrlIndex
if summary["drm"]
summary["drm_license_requests"] = VideoLoadHandoff.ReadAndDelete(DRM_LICENSE_REQUESTS_PATH, summary["video_load_id"])
summary["widevine_security_level"] = ValidAssociativeArray(CreateObject("roDeviceInfo").GetDrmInfoEx().Widevine).securityLevel
hdmiStatus = CreateObject("roHdmiStatus")
if hdmiStatus <> invalid
summary["hdcp_version"] = hdmiStatus.GetHdcpVersion()
end if
end if
end if
LogTelemetryEvent({
level: "info"
@@ -13,7 +13,6 @@ import "pkg:/components/VideoPlayerDev/VideoNode.bs"
import "pkg:/components/VideoQueue/VideoQueueUtils.bs"
import "pkg:/source/utils/Locale.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"
@@ -55,7 +54,6 @@ function Initialize()
m.watchTimeMarker = -1
m.reportWatchTime = false
m.onCloseCalled = false
m.seekToPercent = invalid
' a setSeek that arrived while the content loads (ms, -1 = none): the content-load seek goes there instead.
m.loadingSetSeekMs = -1
@@ -869,11 +867,12 @@ function OnVideoError() as void
LogInfo("error retry -> next stream url=", decision.nextUrl)
m.playbackTelemetry.ReportVideoError(errorData, errorInfo, failedUrl, failedUrlIndex, false)
' the controller already advanced content.url/index; replay it from the initial position (live edge /
' timestamp / percent watched). Swallow the next finished edge.
' timestamp / percent watched), seeked before play so it is the start position. Swallow the next
' finished edge.
m.ignoreNextFinished = true
m.repauseAfterSeek = false ' the retry plays fresh; drop any pending re-pause
m.top.control = VideoControl.Play
SeekToInitialPosition(content)
m.top.control = VideoControl.Play
return
end if
@@ -931,8 +930,6 @@ function OnDuration(event as object) as void
PushLiveEdge()
end if
ApplyTransport()
' a percent-of-duration initial seek waits on a known duration.
SeekToPercentOfDuration()
end function
' Current wall-clock epoch seconds, off the cached roDateTime.
@@ -1078,7 +1075,6 @@ function OnSetSeek(event as object) as void
m.loadingSetSeekMs = seekMs
return
end if
m.seekToPercent = invalid
wasTransport = (m.transport.transportMode <> TransportController.Mode.Idle)
m.transport.ForceIdleSeek(seekMs, not wasTransport)
ApplyTransport()
@@ -1302,31 +1298,22 @@ function SeekToInitialPosition(content as object) as void
return
end if
percentDurationWatched = ValidFloat(content.percentDurationWatched)
if percentDurationWatched > 0
m.seekToPercent = percentDurationWatched
SeekToPercentOfDuration()
end if
end function
function SeekToPercentOfDuration() as void
seekToPercent = m.seekToPercent
if seekToPercent = invalid
if percentDurationWatched <= 0
return
end if
duration = m.top.duration
if duration = 0
return ' OnDuration re-calls this when duration arrives
end if
if duration < 30
m.seekToPercent = invalid
' the metadata's length, not the Video's duration (known only once playing): a seek into a started DRM play
' errors on some Roku TVs.
lengthSeconds = ValidInt(ValidAssociativeArray(content.metadata).lengthSeconds)
if lengthSeconds <= 0
LogWarn("no lengthSeconds to resume the percent watched from; starting from the beginning. videoId:", content.videoId)
return
end if
m.seekToPercent = invalid
seek = (MathUtils.Clamp(seekToPercent, 0, 100) / 100.0) * duration
if seek > 0
LogDebug("seeking to percent watched ->", seek)
ApplySeek(Int(seek * 1000))
if lengthSeconds < 30
return
end if
seekMs = Int(percentDurationWatched / 100.0 * lengthSeconds * 1000)
LogDebug("seeking to percent watched ->", seekMs)
ApplySeek(seekMs)
end function
function PlayAfterPreviousPlayerHasStopped() as void
@@ -89,6 +89,10 @@ function TestSetup() as void
OnNodeReady()
' after OnNodeReady (the loop above drops it per TestSetup, along with the coordinator's control observer).
m.top.seekAtPlay = -1
m.top.ObserveField("control", FuncName(OnTestControl))
' the children survive across tests too: clear what a previous test's transport or live content left.
m.transportTimer.control = "none"
m.trickPlayBar.isLive = false
@@ -98,6 +102,13 @@ function OnTestNudge() as void
m.top.nudgeCount += 1
end function
' a seek written before control=play is the play's start position; one written after is a seek into the started play.
function OnTestControl() as void
if m.top.control = VideoControl.Play
m.top.seekAtPlay = m.top.seek
end if
end function
function OnTestJobRequest(event as object) as void
if event.getData().jobName = Jobs.SponsorBlockSegmentViewedJob
m.top.sponsorViewedCount += 1
@@ -144,6 +155,16 @@ function TestSeekToInitialPosition(content as object) as void
SeekToInitialPosition(content)
end function
' TestErrorRetry — a stream error before the first frame, with a next stream url to retry: runs the REAL
' OnVideoError and returns the seek the device held when the retry wrote control=play.
function TestErrorRetry(content as object) as float
m.videoPlayedSuccessfully = false ' the seam spec's first-frame setup marked the stream played
m.top.content = content
m.top.errorInfo = { category: "http", source: "buffer:reader", ignored: false }
OnVideoError()
return m.top.seekAtPlay
end function
' TestSetContentLoading — a VideoContentJob in flight (or not), minus the job.
function TestSetContentLoading(loading as boolean) as void
if loading
@@ -50,6 +50,8 @@
<field id="nudgeCount" type="integer" />
<!-- test-only probe: how many SponsorBlock viewed-segment reports the coordinator queued. -->
<field id="sponsorViewedCount" type="integer" />
<!-- test-only probe: the seek the device held when the coordinator last wrote control=play. -->
<field id="seekAtPlay" type="float" />
<!-- the Video-only method Initialize calls, plus the spec's drivers (callFunc reaches only interface funcs). -->
<function name="getHttpAgent" />
<function name="TestSetup" />
@@ -62,6 +64,7 @@
<function name="TestSetLive" />
<function name="TestSeedSponsorBlock" />
<function name="TestSeekToInitialPosition" />
<function name="TestErrorRetry" />
<function name="TestSetContentLoading" />
<function name="TestFireLiveBadgeHold" />
<function name="TestKillAutoHide" />
@@ -312,17 +312,6 @@ namespace Tests
m.assertEqual(Int(m.top.seek * 1000), 42000)
end function
@it("setSeek before the duration is known cancels the pending percent-watched seek")
function _()
m.ArmSeekState("first load")
content = CreateObject("roSGNode", "ContentNode")
content.AddFields({ percentDurationWatched: 50.0 })
m.top.callFunc("TestSeekToInitialPosition", content)
m.top.setSeek = 30.5
m.top.duration = 600.0
m.assertEqual(Int(m.top.seek * 1000), 30500, "the percent seek did not override the setSeek")
end function
@it("setSeek while the content loads becomes the content-load seek, over the resume timestamp")
function _()
m.top.callFunc("TestSetContentLoading", true)
@@ -357,16 +346,50 @@ namespace Tests
m.assertEqual(Int(m.top.seek * 1000), 42000)
end function
@it("the content-load seek goes to the percent watched once the duration is known")
@it("the content-load seek goes to the percent watched of the video's length")
function _()
content = CreateObject("roSGNode", "ContentNode")
content.AddFields({ percentDurationWatched: 25.0 })
content.AddFields({ percentDurationWatched: 25.0, metadata: { lengthSeconds: 600 } })
m.top.callFunc("TestSeekToInitialPosition", content)
m.assertEqual(m.top.seek, 0.0, "no seek before the duration is known")
m.top.duration = 600.0
m.assertEqual(Int(m.top.seek * 1000), 150000)
end function
@it("the content-load seek skips the percent watched when the video's length is unknown")
function _()
for each metadata in [{}, { lengthSeconds: 0 }]
m.top.seek = -1
content = CreateObject("roSGNode", "ContentNode")
content.AddFields({ percentDurationWatched: 25.0, metadata: metadata })
m.top.callFunc("TestSeekToInitialPosition", content)
m.top.duration = 600.0
m.assertEqual(m.top.seek, -1.0, FormatJson(metadata))
end for
end function
@it("the content-load seek skips the percent watched on a video shorter than 30 seconds")
function _()
m.top.seek = -1
content = CreateObject("roSGNode", "ContentNode")
content.AddFields({ percentDurationWatched: 50.0, metadata: { lengthSeconds: 29 } })
m.top.callFunc("TestSeekToInitialPosition", content)
m.assertEqual(m.top.seek, -1.0)
end function
@it("an error retry seeks to the percent watched before it plays")
function _()
content = CreateObject("roSGNode", "ContentNode")
content.AddFields({
videoId: "vid1"
playletStreamUrls: ["http://a", "http://b"]
playletStreamUrlIndex: 0
percentDurationWatched: 25.0
metadata: { lengthSeconds: 600 }
})
content.url = "http://a"
m.assertEqual(m.top.callFunc("TestErrorRetry", content), 150.0)
m.assertEqual(content.url, "http://b", "retried the next stream url")
end function
@it("the error dialog displays every captured error field, not just the category")
function _()
' Real Roku Video error captured on device (an http stream failure, 502 manifest).
@@ -1072,7 +1095,7 @@ namespace Tests
classified[name] = "axis"
end for
' flags / scratch — one-shot latches and counters with a single consuming path.
for each name in ["onCloseCalled", "ignoreNextFinished", "videoPlayedSuccessfully", "firstFrameSeen", "showFullScreenHint", "repauseAfterSeek", "seekToPercent", "loadingSetSeekMs", "watchTimeMarker", "reportWatchTime", "errorDialogNode", "lastCommitSeq", "lastFinishSeq", "liveAstSeconds", "liveFallbackEdgeMs", "liveFallbackAtSeconds", "liveBadgeHoldActive"]
for each name in ["onCloseCalled", "ignoreNextFinished", "videoPlayedSuccessfully", "firstFrameSeen", "showFullScreenHint", "repauseAfterSeek", "loadingSetSeekMs", "watchTimeMarker", "reportWatchTime", "errorDialogNode", "lastCommitSeq", "lastFinishSeq", "liveAstSeconds", "liveFallbackEdgeMs", "liveFallbackAtSeconds", "liveBadgeHoldActive"]
classified[name] = "flag"
end for
' NOT coordinator state — node-scope + test-environment entries, pinned EXPLICITLY (no hidden
@@ -1,9 +1,10 @@
import "pkg:/components/Services/Dash/DashManifest.bs"
import "pkg:/components/Services/Dash/LiveHeadChecks.bs"
import "pkg:/components/Services/Dash/LiveHeadCounts.bs"
import "pkg:/components/Services/Dash/LiveLoadCounts.bs"
import "pkg:/components/Services/Dash/LiveTimeline.types.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/components/Telemetry/VideoLoadHandoff.bs"
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/MathUtils.bs"
@@ -52,6 +53,7 @@ namespace Http
m.liveLeadMs = 0
m.liveDriftMs = 0
m.liveLastCheckJumped = false
m.liveTimelineCounts = invalid
m.reportedLiveCorrection = false
m.liveManifestTemplate = ""
m.liveManifestTemplateKey = invalid
@@ -250,13 +252,13 @@ namespace Http
newest = head
end if
end for
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": m.cachedVideoLoadId, "counts": m.liveHeadChecks.counts }))
' Listed segments can't be withdrawn: the head only moves forward.
if newest <> invalid and newest.seqnum > m.liveHeadSeqnum
m.AlignLiveTimeline(newest)
m.liveHeadSeqnum = newest.seqnum
end if
VideoLoadHandoff.Write(LIVE_LOAD_COUNTS_PATH, ValidString(m.cachedVideoLoadId), { "live_head": m.liveHeadChecks.counts, "live_timeline": m.liveTimelineCounts })
end function
' Segments are listed at the duration at load, the stream's lifetime average: off
@@ -272,11 +274,23 @@ namespace Http
if head.timeMs = invalid or m.liveBaseTimeMs = invalid
return
end if
' The cadence since the base.
sinceBaseDurationMs = Cint((head.timeMs - m.liveBaseTimeMs) / (head.seqnum - m.liveBaseSeqnum))
if sinceBaseDurationMs <= 0
LogWarnNoTelemetry("Live head time went back:", head.timeMs, "ms at", head.seqnum, "after", m.liveBaseTimeMs, "ms at", m.liveBaseSeqnum)
return
end if
durationRuns = m.liveDurationRuns
headEndMs = m.liveBaseEndMs + Cint(head.timeMs - m.liveBaseTimeMs)
driftMs = m.dashManifest.LiveSegmentStartMs(durationRuns, head.seqnum + 1) - headEndMs - m.liveLeadMs
stepMs = driftMs - m.liveDriftMs
m.liveDriftMs = driftMs
counts = m.liveTimelineCounts
counts["timed_checks"] += 1
counts["drift_ms_min"] = MathUtils.Min(counts["drift_ms_min"], driftMs)
counts["drift_ms_max"] = MathUtils.Max(counts["drift_ms_max"], driftMs)
counts["step_ms_min"] = MathUtils.Min(counts["step_ms_min"], stepMs)
counts["step_ms_max"] = MathUtils.Max(counts["step_ms_max"], stepMs)
lastCheckJumped = m.liveLastCheckJumped
m.liveLastCheckJumped = false
listedDurationMs = durationRuns[durationRuns.Count() - 1].durationMs
@@ -288,14 +302,9 @@ namespace Http
' large cadence error can leap too (a young stream between sparse checks): the
' next check measures it.
isStall = stepMs < -LIVE_STALL_JUMP_MS and not lastCheckJumped
durationMs = sinceBaseDurationMs
if isStall
durationMs = listedDurationMs
else
durationMs = Cint((head.timeMs - m.liveBaseTimeMs) / (head.seqnum - m.liveBaseSeqnum))
if durationMs <= 0
LogWarnNoTelemetry("Live head time went back:", head.timeMs, "ms at", head.seqnum, "after", m.liveBaseTimeMs, "ms at", m.liveBaseSeqnum)
return
end if
end if
fromSeqnum = m.dashManifest.LiveLastListedSeqnum(durationRuns, m.liveHeadSeqnum) + 1
@@ -316,6 +325,11 @@ namespace Http
durationRuns.Shift()
end while
durationRuns.Push({ fromSeqnum: fromSeqnum, startMs: startMs, durationMs: durationMs })
counts["corrections"] += 1
if isStall
counts["stall_corrections"] += 1
end if
counts["duration_runs_max"] = MathUtils.Max(counts["duration_runs_max"], durationRuns.Count())
m.ReportLiveCorrection(head, durationMs, driftMs, stepMs, isStall)
end function
@@ -393,6 +407,16 @@ namespace Http
m.liveLeadMs = 0
m.liveDriftMs = 0
m.liveLastCheckJumped = false
m.liveTimelineCounts = {
"timed_checks": 0
"corrections": 0
"stall_corrections": 0
"drift_ms_min": 0
"drift_ms_max": 0
"step_ms_min": 0
"step_ms_max": 0
"duration_runs_max": m.liveDurationRuns.Count()
}
m.reportedLiveCorrection = false
m.liveManifestTemplate = ""
m.liveManifestTemplateKey = invalid
@@ -1,5 +1,6 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/components/Services/Innertube/DrmLicenseRequests.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Innertube/PoTokens.bs"
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
@@ -161,7 +162,7 @@ namespace Http
request = context.request
response = context.response
drmStringQueryParams = ["videoId", "drmParams", "drmSessionId", "cpn"]
drmStringQueryParams = ["videoId", "videoLoadId", "drmParams", "drmSessionId", "cpn"]
for each paramName in drmStringQueryParams
if StringUtils.IsNullOrEmpty(request.query[paramName])
response.Default(400, "Missing " + paramName)
@@ -194,29 +195,25 @@ namespace Http
options["visitorData"] = m.innertube.sessionData.visitorData
end if
drmResponse = InnertubeService.GetDrmLicense(options)
DrmLicenseRequests.RecordSent(request.query.videoLoadId)
licenseResponse = InnertubeService.GetDrmLicense(options)
DrmLicenseRequests.RecordResponse(request.query.videoLoadId, licenseResponse)
if IsByteArray(drmResponse)
response.http_code = 200
response.SetBodyDataBuffer(drmResponse)
response.ContentType("text/html; charset=utf-8")
response.headers["Cache-Control"] = "no-cache"
else if IsAssociativeArray(drmResponse)
license = licenseResponse.license
if not IsByteArray(license) or license.Count() = 0
LogTelemetryEvent({
level: "error"
message: `DRM license request failed: ${ValidString(drmResponse.error)}\nvideoId: ${request.query.videoId}`
message: `DRM license request failed: ${ValidString(licenseResponse.error)}\nvideoId: ${request.query.videoId}\nvideo_load_id: ${request.query.videoLoadId}`
fingerprint: ["DRM license request failed"]
})
response.Default(500, FormatJson(drmResponse))
else
LogTelemetryEvent({
level: "error"
message: `DRM license request returned an unexpected response type\nvideoId: ${request.query.videoId}`
fingerprint: ["DRM license request failed"]
})
response.Default(500, "Invalid DRM license response")
response.Default(500, FormatJson(licenseResponse))
return true
end if
response.http_code = 200
response.SetBodyDataBuffer(license)
response.ContentType("text/html; charset=utf-8")
response.headers["Cache-Control"] = "no-cache"
return true
end function
@@ -7,7 +7,8 @@ import "pkg:/source/utils/Types.bs"
' /delay/<ms> 200 after <ms>
' /echo 200 with the request's { method, path, headers, body } as JSON
' /maxage/<seconds>/<id> 200 with Cache-Control: max-age=<seconds>
' A path in routes (its query aside) responds as its route says instead: { status, headers, body, delayMs }.
' A path in routes responds as its route says instead: { status, headers, body, delayMs }. A route keyed
' with a query answers that query only, ahead of the route keyed with the bare path.
' A route { drop: true } closes the connection without a response.
' Every response carries X-Hit, the request's count for its path. Connections are read and responded to
' without blocking each other, so a slow or abandoned one holds up nothing.
@@ -162,7 +163,11 @@ function BuildResponse(item as object) as object
m.top.lastRequest = request
delayMs = MIN_RESPONSE_DELAY_MS
route = ValidAssociativeArray(m.top.routes)[path.Split("?")[0]]
routes = ValidAssociativeArray(m.top.routes)
route = routes[path]
if route = invalid
route = routes[path.Split("?")[0]]
end if
if route <> invalid
if ValidInt(route.delayMs) > delayMs
delayMs = route.delayMs
+1 -25
View File
@@ -68,14 +68,6 @@
<source>Premieres in 1 minute</source>
<translation>Premiere in 1 Minute</translation>
</message>
<message>
<source>Lounge service setup error</source>
<translation>Fehler beim Setup des Lounge-Services</translation>
</message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>Lounge Token konnte nicht geladen werden. Bitte starten Sie Playlet erneut, um die Cast-Funktion nutzen zu können.</translation>
</message>
<message>
<source>name</source>
<translation>Name</translation>
@@ -424,22 +416,6 @@
<source>Failed to load feed</source>
<translation>Feed konnte nicht geladen werden</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>Bildschirm ID konnte nicht gefunden werden. Bitte starten sie Playlet neu, um die Cast-Funktion nutzen zu können.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>Ungültige Bildschirm-ID: %1</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Ungültige Antwort: %1</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>Session-Daten konnten nicht geladen werden. Bitte starten Sie Playlet neu, um die Cast-Funktion nutzen zu können.</translation>
</message>
<message>
<source>Invidious custom instance</source>
<translation>Benutzerdefinierte Invidious-Instanz</translation>
@@ -874,7 +850,7 @@
</message>
<message>
<source>No thumbnails found in JSON from %1</source>
<translation>Keine Vorschaubilder im JSON von 1% gefunden</translation>
<translation>Keine Vorschaubilder im JSON von %1 gefunden</translation>
</message>
<message>
<source>%1 is not reachable</source>
@@ -248,30 +248,6 @@
<source>Backend changed to Playlet, because no Invidious instance is set.</source>
<translation>Backend changed to Playlet, because no Invidious instance is set.</translation>
</message>
<message>
<source>Lounge service setup error</source>
<translation>Lounge service setup error</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>Failed to get screen ID. Please restart Playlet to use the cast function.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>Not a valid screen id: %1</translation>
</message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>Failed to get lounge token. Please restart Playlet to use the cast function.</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Invalid response: %1</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>Failed to get session data. Please restart Playlet to use the cast function.</translation>
</message>
<message>
<source>Select a service to login</source>
<translation>Select a service to login</translation>
@@ -208,30 +208,6 @@
<source>Failed to load feed</source>
<translation>Fallo al cargar el feed</translation>
</message>
<message>
<source>Lounge service setup error</source>
<translation>Error de configuración del servicio Lounge</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>No se pudo obtener el ID de tu pantalla. Por favor reinicia Playlet para usar la función de transmitir.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>Id de pantalla no válida: %1</translation>
</message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>No se ha podido obtener el token dela sala. Por favor, reinicia Playlet para utilizar la función de la transmisión.</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>No se han podido obtener los datos de la sesión. Por favor, reinicia Playlet para utilizar la función de transmisión.</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Respuesta no válida: %1</translation>
</message>
<message>
<source>Invidious custom instance</source>
<translation>Instancia personalizada de Invidious</translation>
@@ -840,18 +840,6 @@
<source>Failed to load Invidious public instances</source>
<translation>No se pudieron cargar las instancias públicas de Invidious</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>No se pudo obtener el ID de tu pantalla. Por favor reinicia Playlet para usar la función de transmitir.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>La ID de pantalla no es válida: %1</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Respuesta inválida: %1</translation>
</message>
<message>
<source>Invidious public instances</source>
<translation>Instancias públicas de Invidious</translation>
@@ -944,14 +932,6 @@
<source>Latest (default)</source>
<translation>Más reciente (por defecto)</translation>
</message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>No se ha podido obtener el token de Lounge. Por favor reinicia Playlet para usar la función de transmión.</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>No se han podido obtener los datos de sesión. Por favor reinicia Playlet para usar la función de transmisión.</translation>
</message>
<message>
<source>Invidious custom instance</source>
<translation>Instancia personalizada de Invidious</translation>
@@ -1020,10 +1000,6 @@
<source>Invalid caption data from %1 (response is not a valid vtt file)</source>
<translation>Datos de subtítulos inválidos de %1 (la respuesta no es un archivo vtt válido)</translation>
</message>
<message>
<source>Lounge service setup error</source>
<translation>Error de configuración del servicio Lounge</translation>
</message>
<message>
<source>signup</source>
<translation>registro</translation>
@@ -208,30 +208,6 @@
<source>Failed to load feed</source>
<translation>Échec du chargement du flux</translation>
</message>
<message>
<source>Lounge service setup error</source>
<translation>Erreur de configuration du service Lounge</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>Impossible d&apos;obtenir l&apos;identifiant de l&apos;écran. Veuillez redémarrer Playlet pour utiliser la fonction de diffusion.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>Identifiant d&apos;écran non valide : %1</translation>
</message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>Échec de l&apos;obtention du jeton Lounge. Veuillez redémarrer Playlet pour utiliser la fonction de diffusion.</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Réponse non valide : %1</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>Échec de l&apos;obtention des données de session. Veuillez redémarrer Playlet pour utiliser la fonction de diffusion.</translation>
</message>
<message>
<source>Invidious custom instance</source>
<translation>Instance personnalisée d&apos;Invidious</translation>
@@ -128,10 +128,6 @@
<source>Failed to load channel %1</source>
<translation>Falha ao carregar o canal %1</translation>
</message>
<message>
<source>Failed to get lounge token. Please restart Playlet to use the cast function.</source>
<translation>Não conseguiu obter token lounge. Por favor, reinicie Playlet para usar a função de transmitir.</translation>
</message>
<message>
<source>Subscriptions</source>
<translation>Inscrições</translation>
@@ -216,18 +212,6 @@
<source>Failed to load feed</source>
<translation>Erro ao carregar o feed</translation>
</message>
<message>
<source>Lounge service setup error</source>
<translation>Erro ao configurar o serviço de lounge</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>Falha ao obter o ID da tela. Por favor, reinicie Playlet para usar a função de transmitir.</translation>
</message>
<message>
<source>Not a valid screen id: %1</source>
<translation>Não é um id de tela válido: %1</translation>
</message>
<message>
<source>Invidious instance to use. Example: https://example.com. Find more instances at %INVIDIOUS_PUBLIC_INSTANCES%</source>
<translation>Instância Invidious para usar. Exemplo: https://example.com. Encontre mais casos em %INVIDIOUS_PUBLIC_INSTANCES%</translation>
@@ -504,10 +488,6 @@
<source>This will restart Playlet.</source>
<translation>Isso vai reiniciar o Playlet.</translation>
</message>
<message>
<source>Invalid response: %1</source>
<translation>Resposta inválida: %1</translation>
</message>
<message>
<source>Test</source>
<translation>Teste</translation>
@@ -712,10 +692,6 @@
<source>Queue Playlist</source>
<translation>Lista dereprodução em fila</translation>
</message>
<message>
<source>Failed to get session data. Please restart Playlet to use the cast function.</source>
<translation>Não conseguimos obter dados da sessão. Por favor, reinicie Playlet para usar a função transmitir.</translation>
</message>
<message>
<source>Invalid JSON from %1 (couldn&apos;t read %2)</source>
<translation>JSON inválido de %1 (Não conseguiu ler %2)</translation>
+3 -1
View File
@@ -3,7 +3,9 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=48
build_version=00009
build_version=00010
rsg_version=1.3
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
@@ -1,176 +0,0 @@
import "pkg:/components/Services/LoungeService/HttpChunkedDecoder.bs"
namespace Tests
@suite
class HttpChunkedDecoderTests extends Rooibos.BaseTestSuite
@describe("HttpChunkedDecoder.Pump")
@it("decodes a single-chunk 200 response and reaches Done")
function singleChunk()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello")
m.assertEqual(r.decoder.statusCode, 200)
m.assertTrue(r.decoder.IsDone())
m.assertFalse(r.decoder.IsError())
end function
@it("concatenates multiple chunks into one body")
function multipleChunks()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello world")
m.assertTrue(r.decoder.IsDone())
end function
' A chunk boundary need not align with a socket read: the same response delivered one byte
' per read must reassemble identically.
@it("reassembles a response delivered one byte per socket read")
function bytewise()
r = m.Drive(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n`, 1)
m.assertEqual(r.body, "hello world")
m.assertTrue(r.decoder.IsDone())
end function
@it("parses a hex chunk size greater than 9")
function hexChunkSize()
payload = "0123456789abcdef" ' 16 bytes -> chunk size "10" in hex
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n10\r\n` + payload + `\r\n0\r\n\r\n`)
m.assertEqual(r.body, payload)
end function
@it("ignores chunk-size extensions after a semicolon")
function chunkExtensions()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5;foo=bar\r\nhello\r\n0\r\n\r\n`)
m.assertEqual(r.body, "hello")
end function
@it("extracts a chunk byte-exactly when the body holds multi-byte UTF-8")
function utf8Chunk()
' "café" is 4 characters but 5 UTF-8 bytes; the chunk size counts bytes.
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\ncafé\r\n0\r\n\r\n`)
m.assertEqual(r.body, "café")
m.assertTrue(r.decoder.IsDone())
end function
@it("flags a non-200 status as an error carrying the code")
@params("410 Gone", 410)
@params("400 Bad Request", 400)
@params("401 Unauthorized", 401)
function non200(statusLine as string, expectedCode as integer)
r = m.DecodeWhole(`HTTP/1.1 ` + statusLine + `\r\n\r\n`)
m.assertTrue(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.decoder.statusCode, expectedCode)
m.assertEqual(r.decoder.errorReason, "", "an HTTP status error is fingerprinted by code, not a slug")
end function
@it("surfaces a 3xx as a redirect carrying the Location, not an error")
@params("301 Moved Permanently", 301)
@params("302 Found", 302)
@params("303 See Other", 303)
@params("307 Temporary Redirect", 307)
@params("308 Permanent Redirect", 308)
function redirect(statusLine as string, expectedCode as integer)
r = m.DecodeWhole(`HTTP/1.1 ` + statusLine + `\r\nLocation: https://rr4.youtube.com/api/lounge/bc/bind?SID=x\r\n\r\n`)
m.assertTrue(r.decoder.IsRedirect())
m.assertFalse(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.decoder.statusCode, expectedCode)
m.assertEqual(r.decoder.Location(), "https://rr4.youtube.com/api/lounge/bc/bind?SID=x")
end function
@it("treats an HTTP/1.0 307 as a redirect")
function redirectHttp10()
r = m.DecodeWhole(`HTTP/1.0 307 Temporary Redirect\r\nLocation: http://portal.example/login\r\n\r\n`)
m.assertTrue(r.decoder.IsRedirect())
m.assertFalse(r.decoder.IsError())
m.assertEqual(r.decoder.Location(), "http://portal.example/login")
end function
@it("flags a 200 response that is not chunked as an error rather than crashing")
function nonChunked()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "unsupported_encoding")
end function
@it("flags a malformed status line with a stable error reason")
function malformedStatus()
r = m.DecodeWhole(`HELLO not http\r\n\r\n`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "malformed_status")
end function
@it("waits for more bytes when the status line is incomplete")
function partialStatus()
r = m.Drive("HTTP/1.1 20", 0)
m.assertFalse(r.decoder.IsError())
m.assertFalse(r.decoder.IsDone())
m.assertEqual(r.body, "")
end function
@it("errors on a chunk size that overflows a 32-bit int")
function chunkOverflow()
r = m.DecodeWhole(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nFFFFFFFF\r\nx`)
m.assertTrue(r.decoder.IsError())
m.assertEqual(r.decoder.errorReason, "chunk_overflow")
end function
function DecodeWhole(response as string) as object
return m.Drive(response, 0)
end function
function Drive(response as string, readSize as integer) as object
decoder = new HttpChunkedDecoder()
socket = new LoungeMockSocket(m.Bytes(response), readSize)
out = CreateObject("roByteArray")
while socket.GetCountRcvBuf() > 0 and not decoder.IsDone() and not decoder.IsError() and not decoder.IsRedirect()
decoder.Pump(socket, out)
end while
return { decoder: decoder, body: out.ToAsciiString() }
end function
function Bytes(text as string) as object
bytes = CreateObject("roByteArray")
bytes.FromAsciiString(text)
return bytes
end function
end class
' Feeds `bytes` to the decoder, at most `readSize` per Receive (0 = all at once), so a test
' can drive fragmented reads.
class LoungeMockSocket
private data
private readPos = 0
private readSize = 0
function new(bytes as object, readSize as integer)
m.data = bytes
m.readSize = readSize
end function
function GetCountRcvBuf() as integer
remaining = m.data.Count() - m.readPos
if remaining <= 0
return 0
end if
if m.readSize > 0 and m.readSize < remaining
return m.readSize
end if
return remaining
end function
function Receive(ba as object, index as integer, length as integer) as integer
count = 0
while count < length and m.readPos < m.data.Count()
ba[index + count] = m.data[m.readPos]
count += 1
m.readPos += 1
end while
return count
end function
end class
end namespace
@@ -0,0 +1,209 @@
import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs"
import "pkg:/components/Services/LoungeService/LoungeService.types.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
namespace Tests
@suite
class LoungeBackchannelTests extends Rooibos.BaseTestSuite
protected override function setup()
m.server = Tests.StartHttpTestServer()
end function
protected override function tearDown()
Tests.StopHttpTestServer(m.server)
m.server = invalid
end function
protected override function beforeEach()
Tests.SetUpLoggingGlobals()
m.global.telemetry.LogEvent = {}
end function
function PollOnce(backchannel as LoungeBackchannel, path as string, route as dynamic) as object
if route <> invalid
routes = {}
routes[path] = route
m.server.routes = routes
end if
port = CreateObject("roMessagePort")
backchannel.Open(HttpClient.Get(Tests.HttpTestServerUrl(path)), port)
commands = []
timer = CreateObject("roTimespan")
while backchannel.IsPolling() and timer.TotalMilliseconds() < 5000
commands.Append(backchannel.Handle(wait(backchannel.MaxWaitMs(), port)))
end while
return commands
end function
function Frame(json as string) as string
body = CreateObject("roByteArray")
body.FromAsciiString(json)
return `${body.Count()}\n${json}`
end function
@describe("LoungeBackchannel")
@it("returns the commands of a 2xx answer, complete, and acknowledges the last one in the next poll")
function _()
backchannel = new LoungeBackchannel()
body = m.Frame(`[[7,["noop"]]]\n`) + m.Frame(`[[8,["seekTo",{"newTime":"12"}]]]\n`) + `\n`
commands = m.PollOnce(backchannel, "/lounge/frames", { status: 200, body: body })
m.assertEqual(commands.Count(), 2)
m.assertEqual(commands[0].index, 7)
m.assertEqual(commands[0].type, "noop")
m.assertInvalid(commands[0].args)
m.assertEqual(commands[1].index, 8)
m.assertEqual(commands[1].type, "seekTo")
m.assertEqual(commands[1].args, { newTime: "12" })
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
m.assertEqual(backchannel.statusCode, 200)
m.assertEqual(backchannel.ackedCommandIndex, 8)
m.assertFalse(backchannel.IsPolling())
m.assertEmpty(m.global.telemetry.LogEvent)
m.PollOnce(backchannel, "/lounge/next", { status: 200, body: m.Frame(`[[9,["noop"]]]`) })
m.assertEqual(Tests.HttpTestServerHits(m.server, "/lounge/next?AID=8"), 1)
end function
@it("ends a 2xx answer without frames as empty")
function _()
backchannel = new LoungeBackchannel()
m.assertEmpty(m.PollOnce(backchannel, "/lounge/empty", { status: 200, body: "" }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Empty)
end function
@it("returns the commands of the whole frames of an answer that ends mid-frame, and reports what is left")
function _()
backchannel = new LoungeBackchannel()
commands = m.PollOnce(backchannel, "/lounge/partial", { status: 200, body: m.Frame(`[[7,["noop"]]]`) + `40\n[[8,` })
m.assertEqual(commands.Count(), 1)
m.assertEqual(commands[0].index, 7)
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
event = m.global.telemetry.LogEvent
m.assertEqual(event.fingerprint, "lounge-partial-frame")
m.assertTrue(event.message.InStr("7 bytes left") <> -1, event.message)
end function
@it("skips the commands it already received")
function _()
backchannel = new LoungeBackchannel()
m.PollOnce(backchannel, "/lounge/first", { status: 200, body: m.Frame(`[[7,["noop"]]]`) })
commands = m.PollOnce(backchannel, "/lounge/resent", { status: 200, body: m.Frame(`[[7,["noop"]],[8,["play"]]]`) })
m.assertEqual(commands.Count(), 1)
m.assertEqual(commands[0].index, 8)
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
end function
@it("acknowledges a malformed command it can read the index of, and reports it")
function _()
backchannel = new LoungeBackchannel()
commands = m.PollOnce(backchannel, "/lounge/malformed", { status: 200, body: m.Frame(`[[7],[8,{"not":"an array"}]]`) })
m.assertEmpty(commands)
m.assertEqual(backchannel.ackedCommandIndex, 8)
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
m.assertEqual(m.global.telemetry.LogEvent.fingerprint, "lounge-malformed-command")
end function
@it("ends a 2xx answer that acknowledges nothing as stalled")
function _()
backchannel = new LoungeBackchannel()
body = m.Frame(`[[7,["noop"]]]`)
m.PollOnce(backchannel, "/lounge/stalled", { status: 200, body: body })
m.assertEmpty(m.PollOnce(backchannel, "/lounge/stalled", invalid))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Stalled)
m.assertEqual(backchannel.stalledPolls, 1)
m.assertEqual(backchannel.ackedCommandIndex, 7)
m.assertEmpty(m.PollOnce(backchannel, "/lounge/unparseable", { status: 200, body: m.Frame(`[[8,["noop"]`) }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Stalled)
m.assertEqual(backchannel.stalledPolls, 2)
m.assertEqual(m.global.telemetry.LogEvent.fingerprint, "lounge-unparseable-frame")
m.PollOnce(backchannel, "/lounge/unstalled", { status: 200, body: m.Frame(`[[8,["noop"]]]`) })
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete)
m.assertEqual(backchannel.stalledPolls, 0)
end function
@it("restarts the acknowledged index for the session a bind starts")
function _()
backchannel = new LoungeBackchannel()
m.PollOnce(backchannel, "/lounge/old-session", { status: 200, body: m.Frame(`[[7,["noop"]]]`) })
m.PollOnce(backchannel, "/lounge/old-session", invalid)
commands = backchannel.StartSession(m.Frame(`[[0,["c","SID"]],[1,["S","GSID"]]]`))
m.assertEqual(commands.Count(), 2)
m.assertEqual(commands[0].type, "c")
m.assertEqual(commands[0].args, "SID")
m.assertEqual(backchannel.ackedCommandIndex, 1)
m.assertEqual(backchannel.stalledPolls, 0)
end function
@it("ends a non-2xx answer with its status")
function _()
backchannel = new LoungeBackchannel()
m.assertEmpty(m.PollOnce(backchannel, "/lounge/unknownsid", { status: 400, body: "Unknown SID" }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Http)
m.assertEqual(backchannel.CloseLabel(), "http_400")
m.assertEqual(backchannel.statusCode, 400)
end function
@it("ends a poll the server drops with its curl code")
function _()
backchannel = new LoungeBackchannel()
m.assertEmpty(m.PollOnce(backchannel, "/lounge/dropped", { drop: true }))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Curl)
m.assertEqual(backchannel.CloseLabel(), "curl_52")
m.assertEqual(backchannel.statusCode, HttpClient.CurlErrors.CURLE_GOT_NOTHING)
end function
@it("ends a poll the server holds past the poll timeout as timeout")
function _()
backchannel = new LoungeBackchannel()
backchannel.pollTimeoutMs = 300
m.assertEmpty(m.PollOnce(backchannel, "/delay/3000", invalid))
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Timeout)
m.assertEqual(backchannel.statusCode, 0)
end function
@it("ends a poll that can't be sent as not_sent")
function _()
backchannel = new LoungeBackchannel()
' A transfer already in progress refuses another.
busyTransfer = CreateObject("roUrlTransfer")
busyTransfer.SetUrl(Tests.HttpTestServerUrl("/delay/2000"))
busyTransfer.SetMessagePort(CreateObject("roMessagePort"))
busyTransfer.AsyncGetToString()
m.stubCall(HttpClient.CreateUrlTransfer, busyTransfer)
m.assertEmpty(m.PollOnce(backchannel, "/lounge/not-sent", invalid))
busyTransfer.AsyncCancel()
m.assertEqual(backchannel.closeReason, LoungeCloseReason.NotSent)
m.assertEqual(backchannel.statusCode, 0)
end function
@it("cancels the poll in flight when closed")
function _()
backchannel = new LoungeBackchannel()
port = CreateObject("roMessagePort")
backchannel.Open(HttpClient.Get(Tests.HttpTestServerUrl("/delay/3000")), port)
backchannel.Close()
m.assertFalse(backchannel.IsPolling())
m.assertEmpty(backchannel.Handle(wait(500, port)))
m.assertInvalid(backchannel.closeReason)
end function
@it("resets the status and reason of the previous poll when it opens the next")
function _()
backchannel = new LoungeBackchannel()
m.PollOnce(backchannel, "/lounge/gone", { status: 410, body: "" })
m.assertEqual(backchannel.closeReason, LoungeCloseReason.Http)
backchannel.Open(HttpClient.Get(Tests.HttpTestServerUrl("/delay/3000")), CreateObject("roMessagePort"))
m.assertTrue(backchannel.IsPolling())
m.assertInvalid(backchannel.closeReason)
m.assertEqual(backchannel.statusCode, 0)
end function
end class
end namespace
@@ -15,18 +15,6 @@ namespace Tests
m.assertEqual(LoungeBytes.RangeToString(bytes, 1, bytes.Count()), cafe)
end function
@it("finds the first CRLF at or after a position")
function indexOfCrlf()
bytes = m.Bytes(`ab\r\ncd\r\n`)
m.assertEqual(LoungeBytes.IndexOfCrlf(bytes, 0), 2)
m.assertEqual(LoungeBytes.IndexOfCrlf(bytes, 3), 6)
end function
@it("returns -1 when no CRLF is present")
function indexOfCrlfMissing()
m.assertEqual(LoungeBytes.IndexOfCrlf(m.Bytes("abc"), 0), -1)
end function
@it("finds the first byte value at or after a position, or -1")
function indexOfByte()
bytes = m.Bytes("a,b,c")
@@ -35,12 +23,6 @@ namespace Tests
m.assertEqual(LoungeBytes.IndexOfByte(bytes, 0, Asc("z")), -1)
end function
@it("returns a tail copy from a position to the end")
function tail()
tail = LoungeBytes.Tail(m.Bytes("hello"), 2)
m.assertEqual(tail.ToAsciiString(), "llo")
end function
function Bytes(text as string) as object
bytes = CreateObject("roByteArray")
bytes.FromAsciiString(text)
@@ -1,44 +0,0 @@
import "pkg:/components/Services/LoungeService/LoungeBackchannel.bs"
namespace Tests
@suite
class LoungeRedirectTests extends Rooibos.BaseTestSuite
@describe("LoungeRedirect.Resolve")
@it("downgrades an https target to http, keeping host, path and query")
function downgradesHttps()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind?SID=a", "https://rr4.youtube.com/api/lounge/bc/bind?SID=a&gsessionid=b")
m.assertEqual(resolved, "http://rr4.youtube.com/api/lounge/bc/bind?SID=a&gsessionid=b")
end function
@it("keeps an http target as-is")
function keepsHttp()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/x", "http://other.host/y?z=1")
m.assertEqual(resolved, "http://other.host/y?z=1")
end function
@it("drops a default 80 or 443 port")
@params("https://host:443/p", "http://host/p")
@params("http://host:80/p", "http://host/p")
@params("http://host:8080/p", "http://host:8080/p")
function dropsDefaultPort(location as string, expected as string)
m.assertEqual(LoungeRedirect.Resolve("http://www.youtube.com/x", location), expected)
end function
@it("resolves a root-relative Location against the current host")
function relativeLocation()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind?SID=a", "/api/lounge/bc/bind?SID=a&AID=5")
m.assertEqual(resolved, "http://www.youtube.com/api/lounge/bc/bind?SID=a&AID=5")
end function
@it("prefixes a slash onto a bare relative Location")
function bareRelativeLocation()
resolved = LoungeRedirect.Resolve("http://www.youtube.com/api/lounge/bc/bind", "elsewhere?x=1")
m.assertEqual(resolved, "http://www.youtube.com/elsewhere?x=1")
end function
end class
end namespace
@@ -51,23 +51,39 @@ namespace Tests
end function
@slow(30000)
@it("sends the messages a bind calls for, and reports each one's status once it completes")
@it("sends the messages a bind calls for, each completing on the service loop's port")
function _()
api = m.CreateLiveApi()
api.GetScreenId()
api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed")
sends = []
sends.Append(api.pendingOutgoingMessages)
m.assertNotEmpty(sends, "the bind sent no messages")
m.RunLoop(api, 10000, function(api as object) as boolean
return api.pendingOutgoingMessages.Count() = 0
end function)
m.AssertSendsSucceeded(sends)
end function
@slow(60000)
@it("polls the backchannel over HTTPS: the server holds the poll, then answers with a frame")
function _()
api = m.CreateLiveApi()
api.GetScreenId()
api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed")
results = []
api.StartPoll()
m.assertTrue(api.backchannel.IsPolling())
timer = CreateObject("roTimespan")
while results.Count() = 0 and timer.TotalMilliseconds() < 10000
results.Append(api.ProcessPendingOutgoingMessages())
sleep(50)
end while
m.assertNotEmpty(results, "no outgoing message completed")
for each result in results
m.assertEqual(result.status, 200, result.error)
end for
m.RunLoop(api, 50000, function(api as object) as boolean
return not api.backchannel.IsPolling()
end function)
m.assertEqual(api.backchannel.closeReason, LoungeCloseReason.Complete, `status ${api.backchannel.statusCode}`)
m.assertEqual(api.backchannel.statusCode, 200)
m.assertTrue(timer.TotalMilliseconds() > 5000, `answered after ${timer.TotalMilliseconds()} ms: AID didn't acknowledge the bind's commands`)
end function
@slow(30000)
@@ -77,27 +93,37 @@ namespace Tests
api.GetScreenId()
api.GetToken()
m.assertTrue(api.GetSessionData(), "bind failed")
m.assertTrue(api.HasPendingOutgoingMessages(), "the bind sent no messages")
replacedSends = []
replacedSends.Append(api.pendingOutgoingMessages)
m.assertNotEmpty(replacedSends, "the bind sent no messages")
m.assertTrue(api.Rebind(true), "rebind failed")
m.assertNotEmpty(replacedSends)
for each pending in replacedSends
m.assertTrue(pending.Poll().IsCancelled(), "a send of the replaced session was not cancelled")
m.assertTrue(pending.Handle(invalid).IsCancelled(), "a send of the replaced session was not cancelled")
end for
results = []
sends = []
sends.Append(api.pendingOutgoingMessages)
m.assertNotEmpty(sends, "the rebind sent no messages")
m.RunLoop(api, 10000, function(api as object) as boolean
return api.pendingOutgoingMessages.Count() = 0
end function)
m.AssertSendsSucceeded(sends)
end function
private function RunLoop(api as object, limitMs as integer, done as function) as void
timer = CreateObject("roTimespan")
while api.HasPendingOutgoingMessages() and timer.TotalMilliseconds() < 10000
results.Append(api.ProcessPendingOutgoingMessages())
sleep(50)
while not done(api) and timer.TotalMilliseconds() < limitMs
api.HandleMessage(wait(api.MaxWaitMs(), m.messagePort), [])
end while
m.assertFalse(api.HasPendingOutgoingMessages(), "the new session's sends did not complete")
m.assertNotEmpty(results, "the rebind sent no messages")
for each result in results
m.assertEqual(result.status, 200, result.error)
end function
private function AssertSendsSucceeded(sends as object) as void
for each pending in sends
response = pending.Handle(invalid)
m.assertNotInvalid(response, "a send did not complete")
m.assertEqual(response.StatusCode(), 200, response.ErrorMessage())
end for
end function
@@ -111,7 +137,8 @@ namespace Tests
queueStub = CreateObject("roSGNode", "Node")
queueStub.addFields({ hasPrevious: false, hasNext: false })
notifyStub = CreateObject("roSGNode", "Node")
return new LoungeApi(loungeServiceNode, queueStub, notifyStub, invalid)
m.messagePort = CreateObject("roMessagePort")
return new LoungeApi(loungeServiceNode, queueStub, notifyStub, invalid, m.messagePort)
end function
end class
@@ -0,0 +1,63 @@
import "pkg:/components/Services/LoungeService/LoungeSession.bs"
namespace Tests
@suite
class LoungeSessionTests extends Rooibos.BaseTestSuite
@describe("LoungeSession.StepAfterPoll")
@it("polls again after a complete poll")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, false, false, 0), LoungeSessionStep.Poll)
end function
@it("retries a failed poll")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, 1000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Timeout, 0, 0, false, false, 40000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Http, 503, 0, false, false, 1000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Empty, 200, 0, false, false, 1000), LoungeSessionStep.Retry)
end function
@it("retries the first stall, and rebinds on the second in a row")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Stalled, 200, 1, false, false, 1000), LoungeSessionStep.Retry)
m.assertEqual(m.Step(LoungeCloseReason.Stalled, 200, 2, false, false, 2000), LoungeSessionStep.Rebind)
end function
@it("rebinds a session the server no longer has")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Http, 400, 0, false, false, 1000), LoungeSessionStep.Rebind)
m.assertEqual(m.Step(LoungeCloseReason.Http, 410, 0, false, false, 1000), LoungeSessionStep.Rebind)
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, true, false, 0), LoungeSessionStep.Rebind)
end function
@it("rebinds with a new token when the token expired")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Http, 401, 0, false, false, 1000), LoungeSessionStep.RebindWithNewToken)
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, false, true, 0), LoungeSessionStep.RebindWithNewToken)
m.assertEqual(m.Step(LoungeCloseReason.Http, 400, 0, false, true, 1000), LoungeSessionStep.RebindWithNewToken)
end function
@it("drops a session that delivered no poll for the give-up time, whatever the failure")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Http, 400, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Http, 401, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Stalled, 200, 3, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop)
m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, LoungeSession.GIVE_UP_MS - 1), LoungeSessionStep.Retry)
end function
@it("never drops a session whose poll just delivered")
function _()
m.assertEqual(m.Step(LoungeCloseReason.Complete, 200, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Poll)
end function
function step(closeReason as LoungeCloseReason, statusCode as integer, stalledPolls as integer, sessionGone as boolean, tokenExpired as boolean, msSinceDelivered as integer) as LoungeSessionStep
return LoungeSession.StepAfterPoll(closeReason, statusCode, stalledPolls, sessionGone, tokenExpired, msSinceDelivered)
end function
end class
end namespace
+72 -37
View File
@@ -23,18 +23,21 @@ import "pkg:/source/utils/UrlUtils.bs"
' response = pending.Wait(2000) ' the response, or invalid after 2s; the fetch goes on
' response = pending.Poll() ' the response, or invalid; never blocks
'
' pending = HttpClient.Post(url).Send() ' in a task loop, which blocks only on its own port
' pending = HttpClient.Post(url).SendOn(port) ' in a task loop: a Fetch on the loop's own port
' while true
' message = wait(500, port)
' response = pending.Poll() ' at each wake: the response once it is in, up to 500ms late
' message = wait(pending.MaxWaitMs(), port) ' wakes for the answer, the attempt's deadline or a retry
' response = pending.Handle(message) ' the response once it is in; the loop's messages are ignored
' ... ' the loop's own messages
' if response <> invalid then exit while
'
' Retries run inside the fetch, on the thread that started it, while Await, Wait or Poll runs.
' Retries run inside the fetch, on the thread that started it, while Await, Wait, Poll or Handle runs.
namespace HttpClient
const COMPRESSION_ENABLED = true
const DEFAULT_ATTEMPT_TIMEOUT_MS = 30000
const DEFAULT_RETRY_DELAY_MS = 1000
' The id of every cancellation observer, which tells its events from the other node events on a shared port.
const CANCELLATION_OBSERVER_ID = "HttpClient.CancellationObserver"
' https://developer.roku.com/en-ca/docs/references/brightscript/events/rourlevent.md#getresponsecode-as-integer
' Seem to mirror the curl error codes https://curl.se/libcurl/c/libcurl-errors.html
@@ -385,11 +388,21 @@ namespace HttpClient
' Starts a fetch on a port of its own, which Await, Wait or Poll runs: a request never waited on or polled may
' be dropped when its task ends, and its retries never run.
function Send() as PendingResponse
messagePort = CreateObject("roMessagePort")
return m.StartFetch(CreateObject("roMessagePort"), true)
end function
' Starts a fetch on a task loop's port: the loop caps each wait with MaxWaitMs and hands Handle every message
' it takes, so it wakes as soon as the answer is in, and the fetch's deadline and retries run on time.
function SendOn(messagePort as object) as PendingResponse
return m.StartFetch(messagePort, false)
end function
private function StartFetch(messagePort as object, ownsPort as boolean) as PendingResponse
' Observed before the fetch starts, so a cancellation set between its check and the observation isn't missed.
cancellationObserver = invalid
if m._cancellation <> invalid
cancellationObserver = CreateObject("roSGNode", "NodeObserver")
cancellationObserver.id = CANCELLATION_OBSERVER_ID
' Observed before the target is set: the NodeObserver's callback on the render-thread cancellation moves the
' NodeObserver to the render thread, after which each access to it is a rendezvous.
cancellationObserver.ObserveField("changed", messagePort)
@@ -397,13 +410,13 @@ namespace HttpClient
end if
startedFetch = new Fetch(m, messagePort)
startedFetch.Start()
return new PendingResponse(startedFetch, messagePort, m._cancellation, cancellationObserver)
return new PendingResponse(startedFetch, messagePort, ownsPort, m._cancellation, cancellationObserver)
end function
end class
' A request being sent: its attempts, timeouts, retries and cache, run by the PendingResponse that Send returns.
' It reads the request as it goes, so the request isn't changed after it is sent. Its port is its own: it gets
' only the attempts' answers and the cancellation's events.
' A request being sent: its attempts, timeouts, retries and cache, run by the PendingResponse that Send or SendOn
' returns. It reads the request as it goes, so the request isn't changed after it is sent. Of the messages it is
' handed, it takes only its current attempt's answer.
class Fetch
function new(request as Request, messagePort as object)
m._request = request
@@ -446,10 +459,14 @@ namespace HttpClient
m.StartAttempt()
end function
' How long a wait on the port may last before the next HandleMessage, while the response isn't in: until the
' attempt's deadline while it is sent, until the retry is due between attempts. At least 1, as wait(0) has no
' How long a wait on the port may last before the next HandleMessage: until the attempt's deadline while it is
' sent, until the retry is due between attempts, 1 once complete, as a cache hit, a request not sent and a
' cancellation before the first attempt complete with no message on the port. At least 1, as wait(0) has no
' time limit.
function MaxWaitMs() as integer
if m._response <> invalid
return 1
end if
if m._urlTransfer <> invalid
waitMs = m._attemptDeadlineMs - m._clock.TotalMilliseconds()
else
@@ -689,12 +706,14 @@ namespace HttpClient
end function
end class
' A fetch on a port of its own, which Await, Wait and Poll wait on. They return the same response once it is in.
' Whoever sends the request takes its response or calls Cancel(): either ends the observation of its cancellation.
' A fetch on a port of its own (Send), which Await, Wait and Poll wait on, or on a task loop's port (SendOn), whose
' messages the loop hands to Handle. Each returns the same response once it is in. Whoever sends the request takes
' its response or calls Cancel(): either ends the observation of its cancellation.
class PendingResponse
function new(startedFetch as Fetch, messagePort as object, cancellation as dynamic, cancellationObserver as dynamic)
function new(startedFetch as Fetch, messagePort as object, ownsPort as boolean, cancellation as dynamic, cancellationObserver as dynamic)
m._fetch = startedFetch
m._messagePort = messagePort
m._ownsPort = ownsPort
m._cancellation = cancellation
m._cancellationObserver = cancellationObserver
m._clock = CreateObject("roTimespan")
@@ -716,6 +735,27 @@ namespace HttpClient
return m.WaitForResponse(0)
end function
' message: what the loop took from the port, invalid when its wait timed out. Returns the response once it is
' in, invalid until then.
function Handle(message as dynamic) as dynamic
if m._response <> invalid
return m._response
end if
if type(message) = "roSGNodeEvent" and message.GetNode() = CANCELLATION_OBSERVER_ID and CancellationUtils.IsCancelled(m._cancellation)
m._fetch.Cancel()
end if
m._response = m._fetch.HandleMessage(message)
if m._response <> invalid
m.StopObservingCancellation()
end if
return m._response
end function
' How long the loop may wait on the port before the next Handle; 1 once the response is in.
function MaxWaitMs() as integer
return m._fetch.MaxWaitMs()
end function
function Cancel() as void
m._fetch.Cancel()
m.StopObservingCancellation()
@@ -723,34 +763,30 @@ namespace HttpClient
' timeoutMs: -1 for as long as it takes, 0 to take only what is already on the port.
private function WaitForResponse(timeoutMs as integer) as dynamic
#if DEBUG
Assert.IsTrue(m._ownsPort, "Await, Wait or Poll on a SendOn fetch: they would take the loop's messages; hand them to Handle")
#end if
m._clock.Mark()
' Messages already on the port go first: an answer there is taken even past the deadline.
message = m._messagePort.GetMessage()
while m._response = invalid
' The port's only node events are the cancellation observer's.
if type(message) = "roSGNodeEvent" and CancellationUtils.IsCancelled(m._cancellation)
m._fetch.Cancel()
end if
m._response = m._fetch.HandleMessage(message)
if m._response = invalid
message = m._messagePort.GetMessage()
if message = invalid
waitMs = m._fetch.MaxWaitMs()
if timeoutMs >= 0
remainingMs = timeoutMs - m._clock.TotalMilliseconds()
if remainingMs <= 0
return invalid
end if
if remainingMs < waitMs
waitMs = remainingMs
end if
response = m.Handle(m._messagePort.GetMessage())
while response = invalid
message = m._messagePort.GetMessage()
if message = invalid
waitMs = m.MaxWaitMs()
if timeoutMs >= 0
remainingMs = timeoutMs - m._clock.TotalMilliseconds()
if remainingMs <= 0
return invalid
end if
if remainingMs < waitMs
waitMs = remainingMs
end if
message = wait(waitMs, m._messagePort)
end if
message = wait(waitMs, m._messagePort)
end if
response = m.Handle(message)
end while
m.StopObservingCancellation()
return m._response
return response
end function
private function StopObservingCancellation() as void
@@ -896,7 +932,6 @@ namespace HttpClient
urlTransfer.RetainBodyOnError(true)
if LCase(Left(url, 6)) = "https:"
urlTransfer.SetCertificatesFile("common:/certs/ca-bundle.crt")
urlTransfer.InitClientCertificates()
end if
urlTransfer.SetUrl(url)
urlTransfer.SetHeaders(headers)
@@ -122,6 +122,26 @@ namespace Tests
return invalid
end function
' Waits on the loop's own port, shared with the fetch, the way a task loop does: each wait capped by MaxWaitMs,
' every message handed to Handle, until it returns the response or limitMs passed.
function RunSharedLoop(loop as object, pending as object, limitMs as integer) as dynamic
timer = CreateObject("roTimespan")
while timer.TotalMilliseconds() < limitMs
message = wait(pending.MaxWaitMs(), loop.port)
if type(message) = "roSGNodeEvent" and message.GetField() = "ping"
loop.pings += 1
end if
response = pending.Handle(message)
if response <> invalid
return response
end if
if loop.pingEveryMessage
loop.node.ping = loop.pings + 1
end if
end while
return invalid
end function
function CacheFilePath(request as HttpClient.Request) as string
return HttpCache.GetFilePath(request.GetFullUrl(), request.GetHeaders(), request._saveBodyToFilePath)
end function
@@ -762,6 +782,8 @@ namespace Tests
cancellation.node.cancel = true
pending.Await()
HttpClient.Get(m.ServerUrl("/status/200")).Cancellation(cancellation).Await()
loop = m.CreateLoop()
m.RunSharedLoop(loop, HttpClient.Get(m.ServerUrl("/status/200")).NoCache().Cancellation(m.CreateCancellation()).SendOn(loop.port), 3000)
m.assertEqual(RunGarbageCollector().orphaned, 0)
end function
@@ -864,6 +886,114 @@ namespace Tests
m.assertTrue(loop.pings > 1)
end function
@describe("HttpClient.PendingResponse on a task loop's port (SendOn)")
@it("wakes the loop as soon as the response is in, its own messages left to it")
function _()
loop = m.CreateLoop()
timer = CreateObject("roTimespan")
pending = HttpClient.Get(m.ServerUrl("/delay/200")).SendOn(loop.port)
loop.node.ping = 1
response = m.RunSharedLoop(loop, pending, 3000)
m.assertEqual(response.StatusCode(), 200)
m.AssertTook(timer, 200, 300)
m.assertEqual(loop.pings, 1)
end function
@it("times out at the deadline, its port idle or busy with the loop's messages")
function _()
for each busy in [false, true]
loop = m.CreateLoop()
loop.pingEveryMessage = busy
timer = CreateObject("roTimespan")
pending = HttpClient.Get(m.ServerUrl("/delay/2000")).AttemptTimeoutMs(300).SendOn(loop.port)
loop.node.ping = 1
response = m.RunSharedLoop(loop, pending, 3000)
m.AssertTook(timer, 300, 400)
m.assertTrue(response.IsTimedOut())
end for
end function
@it("sends a retry when it is due")
function _()
loop = m.CreateLoop()
timer = CreateObject("roTimespan")
pending = HttpClient.Get(m.ServerUrl("/seq/sharedretry/503,200")).RetryCount(1).RetryDelayMs(300).SendOn(loop.port)
response = m.RunSharedLoop(loop, pending, 3000)
m.assertEqual(response.StatusCode(), 200)
m.AssertTook(timer, 300, 750)
m.assertEqual(m.Hits("/seq/sharedretry/503,200"), 2)
end function
@it("takes only its own answer when fetches share the port")
function _()
port = CreateObject("roMessagePort")
timer = CreateObject("roTimespan")
slow = HttpClient.Get(m.ServerUrl("/seq/sharedslow/202@500")).SendOn(port)
fast = HttpClient.Get(m.ServerUrl("/seq/sharedfast/201@100")).SendOn(port)
fastResponse = invalid
fastMs = -1
slowResponse = invalid
while slowResponse = invalid and timer.TotalMilliseconds() < 3000
waitMs = slow.MaxWaitMs()
if fastResponse = invalid and fast.MaxWaitMs() < waitMs
waitMs = fast.MaxWaitMs()
end if
message = wait(waitMs, port)
if fastResponse = invalid
fastResponse = fast.Handle(message)
if fastResponse <> invalid
fastMs = timer.TotalMilliseconds()
end if
end if
slowResponse = slow.Handle(message)
end while
m.assertEqual(fastResponse.StatusCode(), 201)
m.assertTrue(fastMs >= 100 and fastMs < 250, `fast took ${fastMs} ms`)
m.assertEqual(slowResponse.StatusCode(), 202)
m.AssertTook(timer, 500, 700)
end function
@it("is cancelled at its cancellation's event, not at the loop's own node events")
function _()
cancellation = m.CreateCancellation()
loop = m.CreateLoop()
pending = HttpClient.Get(m.ServerUrl("/delay/3000")).Cancellation(cancellation).SendOn(loop.port)
loop.node.ping = 1
m.assertInvalid(pending.Handle(wait(1000, loop.port)))
cancellation.node.cancel = true
m.assertTrue(pending.Handle(wait(1000, loop.port)).IsCancelled())
end function
@it("ignores another fetch's cancellation event when it has no cancellation of its own")
function _()
loop = m.CreateLoop()
cancellation = m.CreateCancellation()
cancelled = HttpClient.Get(m.ServerUrl("/delay/3000")).Cancellation(cancellation).SendOn(loop.port)
uncancellable = HttpClient.Get(m.ServerUrl("/delay/200")).SendOn(loop.port)
cancellation.node.cancel = true
message = wait(1000, loop.port)
m.assertEqual(message.GetNode(), "HttpClient.CancellationObserver")
m.assertInvalid(uncancellable.Handle(message))
m.assertTrue(cancelled.Handle(message).IsCancelled())
m.assertEqual(m.RunSharedLoop(loop, uncancellable, 3000).StatusCode(), 200)
end function
@it("completes a cache hit, a request not sent or a cancellation before it starts with no message, MaxWaitMs 1")
function _()
port = CreateObject("roMessagePort")
cached = m.GetWithoutCacheEntry("/maxage/60/shared")
cached.Await()
cancellation = m.CreateCancellation()
cancellation.node.cancel = true
m.stubCall(HttpClient.CreateUrlTransfer, invalid)
for each pending in [cached.SendOn(port), HttpClient.Get(m.ServerUrl("/status/200")).SendOn(port), HttpClient.Get(m.ServerUrl("/status/200")).Cancellation(cancellation).SendOn(port)]
m.assertEqual(pending.MaxWaitMs(), 1)
m.assertNotInvalid(pending.Handle(invalid))
end for
m.assertInvalid(port.GetMessage())
end function
@describe("HttpClient cancellation")
@it("sends nothing when cancelled before Send")
@@ -1523,6 +1653,22 @@ namespace Tests
pending.Await()
end function
@it("Await, Wait or Poll on a SendOn fetch")
function _()
port = CreateObject("roMessagePort")
pending = HttpClient.Get(m.ServerUrl("/status/200")).SendOn(port)
m.AssertContains(m.ThrownMessage(function(pending as object) as void
pending.Await()
end function, pending), "Await, Wait or Poll on a SendOn fetch")
m.AssertContains(m.ThrownMessage(function(pending as object) as void
pending.Wait(100)
end function, pending), "Await, Wait or Poll on a SendOn fetch")
m.AssertContains(m.ThrownMessage(function(pending as object) as void
pending.Poll()
end function, pending), "Await, Wait or Poll on a SendOn fetch")
pending.Cancel()
end function
@it("Text or Json on a response whose body was saved to a file")
function _()
response = HttpClient.Get(m.ServerUrl("/status/200")).SaveBodyToFile("tmp:/http-misuse.txt").Await()
@@ -140,6 +140,24 @@ namespace Tests
m.assertEqual(manifest.FormatDuration(999), "PT0.999S")
m.assertEqual(manifest.FormatDuration(1500), "PT1.500S")
m.assertEqual(manifest.FormatDuration(10000), "PT10.000S")
m.assertEqual(manifest.FormatDuration(17900000123&), "PT17900000.123S")
end function
@describe("DashManifest.GetDurationMs")
@it("returns a post-live DVR duration past 32 bits")
function _()
manifest = new DashManifest("")
m.assertEqual(manifest.GetDurationMs({ isPostLiveDvr: true, postLiveDvrDurationMs: 17900000123& }), 17900000123&)
end function
@it("falls back to the first format's approxDurationMs, then to lengthSeconds")
function _()
manifest = new DashManifest("")
m.assertEqual(manifest.GetDurationMs({ adaptiveFormats: [{ approxDurationMs: "17900000123" }], lengthSeconds: 60 }), 17900000123&)
m.assertEqual(manifest.GetDurationMs({ adaptiveFormats: [{ approxDurationMs: "0" }], lengthSeconds: 60 }), 60000&)
m.assertEqual(manifest.GetDurationMs({ adaptiveFormats: [{}], lengthSeconds: 60 }), 60000&)
m.assertEqual(manifest.GetDurationMs({ isPostLiveDvr: true, adaptiveFormats: [], lengthSeconds: 60 }), 60000&)
end function
end class
@@ -0,0 +1,89 @@
import "pkg:/components/Services/Innertube/DrmLicenseRequests.bs"
import "pkg:/components/Services/Innertube/GetDrmLicenseEndpoint.bs"
namespace Tests
@suite
class DrmLicenseTests extends Rooibos.BaseTestSuite
protected override function afterEach()
DeleteFile(DRM_LICENSE_REQUESTS_PATH)
end function
function Requests(videoLoadId as string) as object
return VideoLoadHandoff.Read(DRM_LICENSE_REQUESTS_PATH, videoLoadId)
end function
@describe("Innertube.ParseGetDrmLicenseResponse")
@it("decodes the web-safe base64 license and keeps the rest of the response")
function _()
authorizedFormats = [{ "trackType": "DRM_TRACK_TYPE_HD", "keyId": "a" }]
responseContext = { "serviceTrackingParams": [{ "service": "GFEEDBACK", "params": [{ "key": "logged_in", "value": "1" }] }] }
parsed = Innertube.ParseGetDrmLicenseResponse({
"responseContext": responseContext
"status": "LICENSE_STATUS_OK"
"license": "AQID-_8="
"authorizedFormats": authorizedFormats
"canRenew": false
})
m.assertEqual(parsed.license.ToHexString(), "010203FBFF")
m.assertEqual(parsed.payload, { "responseContext": responseContext, "status": "LICENSE_STATUS_OK", "authorizedFormats": authorizedFormats, "canRenew": false })
end function
@it("a license that decodes to no bytes is an error, with the response as sent")
function _()
' Roku decodes a length that isn't a multiple of 4 to nothing.
parsed = Innertube.ParseGetDrmLicenseResponse({ "status": "LICENSE_STATUS_OK", "license": "AQI" })
m.assertEqual(parsed.error, "DRM license decodes to no bytes")
m.assertEqual(parsed.payload, { "status": "LICENSE_STATUS_OK", "license": "AQI" })
end function
@it("a status other than OK is an error, with the response as sent")
function _()
parsed = Innertube.ParseGetDrmLicenseResponse({ "status": "LICENSE_STATUS_DENIED", "license": "AQID", "reason": "r" })
m.assertEqual(parsed.error, "DRM license request failed with status: LICENSE_STATUS_DENIED")
m.assertEqual(parsed.payload, { "status": "LICENSE_STATUS_DENIED", "license": "AQID", "reason": "r" })
end function
@describe("DrmLicenseRequests")
@it("counts the video load's requests and keeps each response in order")
function _()
DrmLicenseRequests.RecordSent("load1")
DrmLicenseRequests.RecordResponse("load1", { payload: { "status": "LICENSE_STATUS_OK" } })
DrmLicenseRequests.RecordSent("load1")
DrmLicenseRequests.RecordResponse("load1", { error: "timeout" })
DrmLicenseRequests.RecordSent("load1")
m.assertEqual(m.Requests("load1"), {
"sent": 3
"responses": [
{ "payload": { "status": "LICENSE_STATUS_OK" } }
{ "error": "timeout" }
]
})
end function
@it("keeps the first responses, counting every request")
function _()
for i = 1 to DRM_LICENSE_RESPONSE_SAMPLE_CAP + 2
DrmLicenseRequests.RecordSent("load1")
DrmLicenseRequests.RecordResponse("load1", { error: `e${i}` })
end for
requests = m.Requests("load1")
m.assertEqual(requests["sent"], DRM_LICENSE_RESPONSE_SAMPLE_CAP + 2)
m.assertEqual(requests["responses"].Count(), DRM_LICENSE_RESPONSE_SAMPLE_CAP)
m.assertEqual(requests["responses"][0], { "error": "e1" })
end function
@it("a new video load starts over")
function _()
DrmLicenseRequests.RecordSent("load1")
DrmLicenseRequests.RecordSent("load2")
m.assertInvalid(m.Requests("load1"))
m.assertEqual(m.Requests("load2"), { "sent": 1, "responses": [] })
end function
end class
end namespace
@@ -160,6 +160,22 @@ namespace Tests
m.assertEqual(parsedResponse.error, `Live stream head check returned no X-Head-Seqnum / X-Head-Time (HTTP 200)\n`)
end function
@describe("Innertube.FetchLiveHead")
@it("sends the check once more when the answer lacks the head, whatever its status")
function _()
m.server.routes = {
"/live/failing": { status: 503 }
"/live/failingwithhead": { status: 503, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } }
}
failing = Tests.HttpTestServerUrl("/live/failing?itag=1")
m.assertFalse(Innertube.HasLiveHead(Innertube.FetchLiveHead(failing, invalid)))
m.assertEqual(Tests.HttpTestServerHits(m.server, failing), 2)
failingWithHead = Tests.HttpTestServerUrl("/live/failingwithhead?itag=1")
m.assertTrue(Innertube.HasLiveHead(Innertube.FetchLiveHead(failingWithHead, invalid)))
m.assertEqual(Tests.HttpTestServerHits(m.server, failingWithHead), 1)
end function
@describe("Innertube.ReadLiveHeadSeqnum")
@it("reads X-Head-Seqnum")
@@ -187,6 +203,15 @@ namespace Tests
m.assertInvalid(Innertube.ReadLiveHeadTimeSecAsMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123" })))
end function
@describe("Innertube.ReadLiveHeadAnyTimeMs")
@it("reads X-Head-Time-Millis, else X-Head-Time-Sec")
function _()
m.assertEqual(Innertube.ReadLiveHeadAnyTimeMs(m.ResponseWithHeaders({ "X-Head-Time-Millis": "17900000123", "X-Head-Time-Sec": "17900000" })), 17900000123&)
m.assertEqual(Innertube.ReadLiveHeadAnyTimeMs(m.ResponseWithHeaders({ "X-Head-Time-Sec": "17900000" })), 17900000000&)
m.assertInvalid(Innertube.ReadLiveHeadAnyTimeMs(m.ResponseWithHeaders({ "X-Head-Seqnum": "40" })))
end function
function ResponseWithHeaders(headers as object) as HttpClient.Response
return new HttpClient.Response({ headers: headers })
end function
@@ -1,6 +1,7 @@
import "pkg:/components/Services/Innertube/PostLiveDvrInfo.bs"
import "pkg:/source/tests/HttpTestServer.bs"
import "pkg:/source/tests/LoggingGlobals.bs"
import "pkg:/source/utils/UrlUtils.bs"
namespace Tests
@@ -21,37 +22,52 @@ namespace Tests
m.global.telemetry.LogEvent = {}
end function
@describe("Innertube.FetchPostLiveDvrHead")
@it("reads a HEAD's status and headers")
function _()
m.server.routes = { "/dvr/head": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } }
result = Innertube.FetchPostLiveDvrHead(Tests.HttpTestServerUrl("/dvr/head?itag=1"), invalid, "cpn1", Innertube.ClientType.Tv, invalid)
m.assertEqual(result.statusCode, 200)
m.assertTrue(Innertube.HasPostLiveDvrHead(result))
m.assertEqual(Tests.HttpTestServerHits(m.server, result.url), 1)
end function
@it("sends a failed HEAD once more")
function _()
m.server.routes = { "/dvr/failing": { status: 503 } }
result = Innertube.FetchPostLiveDvrHead(Tests.HttpTestServerUrl("/dvr/failing?itag=1"), "0", invalid, Innertube.ClientType.Tv, invalid)
m.assertEqual(result.statusCode, 503)
m.assertFalse(Innertube.HasPostLiveDvrHead(result))
m.assertEqual(Tests.HttpTestServerHits(m.server, result.url), 2)
end function
@describe("Innertube.GetPostLiveDvrInfo")
@it("reads the duration and segment count from the live edge's head")
function _()
m.server.routes = { "/dvr/ended": { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } } }
parsedResponse = {}
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/ended?itag=1") }], invalid, Innertube.ClientType.Tv, invalid)
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/ended?itag=1") }], invalid, invalid)
m.assertEqual(parsedResponse.postLiveDvrDurationMs, 80000)
m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 40)
end function
@it("reads a duration past 32 bits")
function _()
m.server.routes = { "/dvr/long": { status: 200, headers: { "X-Head-Seqnum": "3580000", "X-Head-Time-Millis": "17900000123" } } }
parsedResponse = {}
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: Tests.HttpTestServerUrl("/dvr/long?itag=1") }], invalid, invalid)
m.assertEqual(parsedResponse.postLiveDvrDurationMs, 17900000123&)
m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 3580000)
end function
@it("reads the head from sq=0 when the live edge has none")
function _()
formatUrl = Tests.HttpTestServerUrl("/dvr/cached?itag=1")
fallbackUrl = UrlUtils.AppendQueryParams(Innertube.GetLiveHeadUrl(formatUrl, "cpn1"), { "sq": "0" })
routes = { "/dvr/cached": { status: 200 } }
routes[fallbackUrl.Replace(Tests.HttpTestServerUrl(""), "")] = { status: 200, headers: { "X-Head-Seqnum": "40", "X-Head-Time-Millis": "80000" } }
m.server.routes = routes
parsedResponse = {}
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: formatUrl }], "cpn1", invalid)
m.assertEqual(Tests.HttpTestServerHits(m.server, Innertube.GetLiveHeadUrl(formatUrl, "cpn1")), 2)
m.assertEqual(Tests.HttpTestServerHits(m.server, fallbackUrl), 1)
m.assertEqual(parsedResponse.postLiveDvrDurationMs, 80000)
m.assertEqual(parsedResponse.postLiveDvrSegmentCount, 40)
end function
@it("sets nothing when neither the live edge nor sq=0 has a head")
function _()
m.server.routes = { "/dvr/nohead": { status: 200 } }
formatUrl = Tests.HttpTestServerUrl("/dvr/nohead?itag=1")
parsedResponse = {}
Innertube.GetPostLiveDvrInfo(parsedResponse, [{ url: formatUrl }], "cpn1", invalid)
m.assertEqual(Tests.HttpTestServerHits(m.server, UrlUtils.AppendQueryParams(Innertube.GetLiveHeadUrl(formatUrl, "cpn1"), { "sq": "0" })), 2)
m.assertFalse(parsedResponse.DoesExist("postLiveDvrDurationMs"))
m.assertFalse(parsedResponse.DoesExist("postLiveDvrSegmentCount"))
end function
end class
end namespace
@@ -38,6 +38,11 @@ namespace Tests
m.recorder = new PlaybackTelemetry.Recorder({ playerTimer: m.playerClock, transport: m.fakeTransport, top: m.fakeTop })
end function
protected override function afterEach()
DeleteFile(LIVE_LOAD_COUNTS_PATH)
DeleteFile(DRM_LICENSE_REQUESTS_PATH)
end function
function At(ms as integer) as void
m.playerClock.ms = ms
end function
@@ -292,6 +297,27 @@ namespace Tests
m.assertEqual(summary.stream_url_index, 1)
end function
@it("DRM content: the video load's license requests, read once")
function _()
m.fakeTop.content = { videoId: "vid1", videoLoadId: "load1", backend: "playlet", playletStreamSource: "adaptiveFormats", drmParams: { keySystem: "Widevine" } }
requests = { "sent": 2, "responses": [{ "error": "timeout" }, { "payload": { "status": "LICENSE_STATUS_OK", "authorizedFormats": [{ "trackType": "DRM_TRACK_TYPE_SD", "keyId": "a" }] } }] }
VideoLoadHandoff.Write(DRM_LICENSE_REQUESTS_PATH, "load1", requests)
summary = m.SendAt(1000)
m.assertEqual(summary.drm_license_requests, requests)
m.assertEqual(summary.widevine_security_level, CreateObject("roDeviceInfo").GetDrmInfoEx().Widevine.securityLevel)
m.assertFalse(m.SendAt(2000).DoesExist("drm_license_requests"), "read once")
end function
@it("content without DRM sends no DRM fields")
function _()
m.fakeTop.content.videoLoadId = "load1"
VideoLoadHandoff.Write(DRM_LICENSE_REQUESTS_PATH, "load1", { "sent": 1, "responses": [] })
summary = m.SendAt(1000)
for each field in ["drm", "drm_license_requests", "widevine_security_level", "hdcp_version"]
m.assertFalse(summary.DoesExist(field), field)
end for
end function
@it("content that never loaded sends no stream fields")
function _()
m.fakeTop.content = { videoId: "vid1", backend: "playlet" }
@@ -388,34 +414,41 @@ namespace Tests
m.assertFalse(summary.DoesExist("stream_source"))
end function
@it("the live head check counts of the video load, without defaults, read once")
@it("the live head check and timeline counts of the video load, without defaults, read once")
function _()
m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1"
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, FormatJson({ "video_load_id": "live1", "counts": { "checks_sent": 6, "answered_after_wait": 1, "timed_out": 0 } }))
VideoLoadHandoff.Write(LIVE_LOAD_COUNTS_PATH, "live1", {
"live_head": { "checks_sent": 6, "answered_after_wait": 1, "timed_out": 0 }
"live_timeline": { "timed_checks": 3, "corrections": 1, "stall_corrections": 0, "drift_ms_min": -3425, "drift_ms_max": 0, "duration_runs_max": 2 }
})
summary = m.SendAt(1000)
m.assertEqual(summary.live_head, { "checks_sent": 6, "answered_after_wait": 1 })
m.assertFalse(CreateObject("roFileSystem").Exists(LIVE_HEAD_COUNTS_PATH), "read once")
m.assertFalse(m.SendAt(2000).DoesExist("live_head"))
m.assertEqual(summary.live_timeline, { "timed_checks": 3, "corrections": 1, "drift_ms_min": -3425, "duration_runs_max": 2 })
summary = m.SendAt(2000)
m.assertFalse(summary.DoesExist("live_head"), "read once")
m.assertFalse(summary.DoesExist("live_timeline"), "read once")
end function
@it("a live play without live head check counts has none")
@it("a live play without live load counts has none")
function _()
m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1"
DeleteFile(LIVE_HEAD_COUNTS_PATH)
m.assertFalse(m.SendAt(1000).DoesExist("live_head"))
summary = m.SendAt(1000)
m.assertFalse(summary.DoesExist("live_head"))
m.assertFalse(summary.DoesExist("live_timeline"))
end function
@it("leaves the live head check counts of another video load")
@it("leaves the live load counts of another video load")
function _()
m.fakeTransport.isLive = true
m.fakeTop.content.videoLoadId = "live1"
handoff = FormatJson({ "video_load_id": "live2", "counts": { "checks_sent": 6 } })
WriteAsciiFile(LIVE_HEAD_COUNTS_PATH, handoff)
m.assertFalse(m.SendAt(1000).DoesExist("live_head"))
m.assertEqual(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH), handoff)
DeleteFile(LIVE_HEAD_COUNTS_PATH)
counts = { "live_head": { "checks_sent": 6 }, "live_timeline": { "corrections": 1 } }
VideoLoadHandoff.Write(LIVE_LOAD_COUNTS_PATH, "live2", counts)
summary = m.SendAt(1000)
m.assertFalse(summary.DoesExist("live_head"))
m.assertFalse(summary.DoesExist("live_timeline"))
m.assertEqual(VideoLoadHandoff.Read(LIVE_LOAD_COUNTS_PATH, "live2"), counts)
end function
@it("a live play: the first video segment's bitrate and the network's at the first playing")
@@ -32,7 +32,7 @@ namespace Tests
end function
protected override function afterEach()
DeleteFile(LIVE_HEAD_COUNTS_PATH)
DeleteFile(LIVE_LOAD_COUNTS_PATH)
end function
' What VideoContentJob sets on the player's content for a video load.
@@ -172,15 +172,16 @@ namespace Tests
m.assertInvalid(pending["_fetch"]["_urlTransfer"])
end function
@it("writes the load's head check counts at every refresh")
@it("writes the load's head check and timeline counts at every refresh, after its correction")
function _()
m.LoadLive([{ seqnum: 10, timeMs: 18630 }, { seqnum: -1, timeMs: invalid }])
m.RefreshDue()
m.assertEqual(VideoLoadHandoff.Read(LIVE_LOAD_COUNTS_PATH, "live1")["live_timeline"]["corrections"], 1)
m.RefreshDue()
handoff = StringUtils.ParseJsonSafe(ReadAsciiFile(LIVE_HEAD_COUNTS_PATH))
m.assertEqual(handoff["video_load_id"], "live1")
m.assertEqual(handoff["counts"]["checks_sent"], 2)
m.assertEqual(handoff["counts"]["answered_without_head"], 1)
counts = VideoLoadHandoff.Read(LIVE_LOAD_COUNTS_PATH, "live1")
m.assertEqual(counts["live_head"]["checks_sent"], 2)
m.assertEqual(counts["live_head"]["answered_without_head"], 1)
m.assertEqual(counts["live_timeline"], m.router.liveTimelineCounts)
end function
@it("gives a list behind the head the cadence since load; the load head ended where the list stays ahead")
@@ -220,6 +221,16 @@ namespace Tests
' head 5: 600 ms behind, within half a segment
m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns.Count(), 1)
m.assertEqual(m.router.liveTimelineCounts, {
"timed_checks": 1
"corrections": 0
"stall_corrections": 0
"drift_ms_min": -600
"drift_ms_max": 0
"step_ms_min": -600
"step_ms_max": 0
"duration_runs_max": 1
})
' head 15 ends at 6000 + 28600 = 34600, listed at 32000: 5 onwards (4 is the last
' listed) take 2200 ms, placed to end 15 there: from 10400, past 4's end (10000)
m.global.telemetry.LogEvent = {}
@@ -233,6 +244,17 @@ namespace Tests
m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns, [{ fromSeqnum: 5, startMs: 10400, durationMs: 2200 }, { fromSeqnum: 15, startMs: 91600 - 26 * 2253, durationMs: 2253 }])
m.assertEmpty(m.global.telemetry.LogEvent)
' drift -600, -2600, then -2000 off the realigned list
m.assertEqual(m.router.liveTimelineCounts, {
"timed_checks": 3
"corrections": 2
"stall_corrections": 0
"drift_ms_min": -2600
"drift_ms_max": 0
"step_ms_min": -2000
"step_ms_max": 0
"duration_runs_max": 2
})
end function
@it("takes a stall as a gap: the cadence stays, and the list stays on the head after it")
@@ -256,6 +278,9 @@ namespace Tests
end for
m.assertEqual(m.router.liveDurationRuns.Count(), 2)
m.assertEqual(m.router.liveLeadMs, 0)
m.assertEqual(m.router.liveTimelineCounts["corrections"], 1)
m.assertEqual(m.router.liveTimelineCounts["stall_corrections"], 1)
m.assertEqual(m.router.liveTimelineCounts["step_ms_min"], -90000)
end function
@it("takes a list ahead by more than the stall bound as cadence: a stall before load heals at once")
@@ -264,6 +289,9 @@ namespace Tests
m.LoadLive([{ seqnum: 10, timeMs: 40000 }, { seqnum: 15, timeMs: 50000 }], { liveHeadSeqnum: 5, liveHeadTimeMs: 30000, liveSegmentDurationMs: 6000 })
m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns[1].durationMs, 2000)
' head 10 ends at 36000 + 10000, listed to end at 11 x 6000
m.assertEqual(m.router.liveTimelineCounts["drift_ms_max"], 20000)
m.assertEqual(m.router.liveTimelineCounts["step_ms_max"], 20000)
m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns.Count(), 2)
end function
@@ -318,8 +346,25 @@ namespace Tests
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 7)
m.assertEqual(m.router.liveDurationRuns.Count(), 1)
m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 0)
m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns.Count(), 2)
m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 1)
end function
@it("skips a head check whose time went back, unmeasured, and corrects at a later one")
function _()
' the load head (2) is at 2630 ms; head 7 claims 2000
m.LoadLive([{ seqnum: 7, timeMs: 2000 }, { seqnum: 12, timeMs: 22630 }])
m.RefreshDue()
m.assertEqual(m.router.liveHeadSeqnum, 7)
m.assertEqual(m.router.liveDurationRuns.Count(), 1)
m.assertEqual(m.router.liveDriftMs, 0)
m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 0)
m.assertEqual(m.router.liveTimelineCounts["drift_ms_max"], 0)
m.RefreshDue()
m.assertEqual(m.router.liveDurationRuns.Count(), 2)
m.assertEqual(m.router.liveTimelineCounts["timed_checks"], 1)
end function
@it("times the head of a stream live for 111 days (head time past 32 bits)")
-6
View File
@@ -82,12 +82,6 @@ namespace Locale
ProfileNeedsReauthMessageLine2 = "Please sign in again with this profile, or switch to another profile."
BackendSwitchedToPlayletTitle = "Backend changed"
BackendSwitchedToPlayletMessage = "Backend changed to Playlet, because no Invidious instance is set."
LoungeServiceSetupError = "Lounge service setup error"
LoungeFailedToGetScreenId = "Failed to get screen ID. Please restart Playlet to use the cast function."
LoungeNotAValidScreenId = "Not a valid screen id: %1"
LoungeFailedToGetLoungeToken = "Failed to get lounge token. Please restart Playlet to use the cast function."
LoungeInvalidResponse = "Invalid response: %1"
LoungeFailedToGetSessionData = "Failed to get session data. Please restart Playlet to use the cast function."
' YouTube login
SelectServiceToLogin = "Select a service to login"
LoginToYouTube = "Login to YouTube"
+2 -2
View File
@@ -58,9 +58,9 @@ function ValidDouble(obj as dynamic) as double
end if
end function
' Returns true if the given object is numeric (Integer, Float, or Double)
' Returns true if the given object is numeric (Integer, LongInteger, Float, or Double)
function IsNumber(obj as dynamic) as boolean
return obj <> invalid and (GetInterface(obj, "ifInt") <> invalid or GetInterface(obj, "ifFloat") <> invalid or GetInterface(obj, "ifDouble") <> invalid)
return obj <> invalid and (GetInterface(obj, "ifInt") <> invalid or GetInterface(obj, "ifLongInt") <> invalid or GetInterface(obj, "ifFloat") <> invalid or GetInterface(obj, "ifDouble") <> invalid)
end function
' Returns true if the given object is of type String, false otherwise
@@ -23,6 +23,16 @@ namespace Tests
m.assertEqual(ValidString(obj), expected)
end function
@it("Checks if an object is a number")
function _()
m.assertTrue(IsNumber(-5))
m.assertTrue(IsNumber(17900000123&))
m.assertTrue(IsNumber(1.5!))
m.assertTrue(IsNumber(1.5#))
m.assertFalse(IsNumber("5"))
m.assertFalse(IsNumber(invalid))
end function
end class
end namespace
+103 -103
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-web",
"version": "0.48.9",
"version": "0.48.10",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet-web",
"version": "0.48.9",
"version": "0.48.10",
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^7.3.1",
"@tailwindcss/postcss": "^4.3.3",
@@ -15,20 +15,20 @@
"@vitejs/plugin-legacy": "^8.2.3",
"autoprefixer": "^10.6.1",
"bgutils-js": "^4.0.3",
"daisyui": "^5.7.46",
"dotenv": "^18.0.4",
"daisyui": "^5.7.50",
"dotenv": "^18.0.8",
"ip": "^2.0.1",
"jszip": "^3.10.2",
"postcss": "^8.5.28",
"postcss": "^8.5.30",
"rollup-plugin-visualizer": "^7.1.1",
"svelte": "^5.57.1",
"svelte": "^5.57.2",
"svelte-check": "^4.7.6",
"svelte-preprocess": "^6.0.5",
"tailwindcss": "^4.3.3",
"terser": "^5.51.2",
"tslib": "^2.8.1",
"typescript": "^5.9.3",
"vite": "^8.3.1",
"typescript": "^6.0.3",
"vite": "^8.3.4",
"vite-plugin-compression": "^0.5.1"
}
},
@@ -1692,9 +1692,9 @@
}
},
"node_modules/@oxc-project/types": {
"version": "0.151.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.151.0.tgz",
"integrity": "sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==",
"version": "0.153.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz",
"integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==",
"dev": true,
"license": "MIT",
"funding": {
@@ -1702,9 +1702,9 @@
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.11.tgz",
"integrity": "sha512-A5kXfGKvKWWZE0TtPrfsvT+q4Y5d1QG8gGUzpYjGydM+fARM9MuX90PrXYXe0XbsDVgyxxNzHo6giCj90bsFNw==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz",
"integrity": "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==",
"cpu": [
"arm"
],
@@ -1719,9 +1719,9 @@
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.11.tgz",
"integrity": "sha512-z6cTycz+iJ4PVkuL4HHW4DfTfoeU/2nqYYuSOrTmH7yHK5Y0LCOnA03V4ZNxavyVaU1oOqUgIg2klN/s+USGOA==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.13.tgz",
"integrity": "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==",
"cpu": [
"arm64"
],
@@ -1736,9 +1736,9 @@
}
},
"node_modules/@rolldown/binding-darwin-arm64": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.11.tgz",
"integrity": "sha512-jShvqNtP6vDC6/A5JOAzbVV+DkgHqhl/ScVCJEbt+TUY6QYz7YnXcrg3sLtFBniro0f/Ld50ZwCWA6f7KYD1nQ==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.13.tgz",
"integrity": "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==",
"cpu": [
"arm64"
],
@@ -1753,9 +1753,9 @@
}
},
"node_modules/@rolldown/binding-darwin-x64": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.11.tgz",
"integrity": "sha512-f2i2xiNWq1Z1l2++q2fuhZRdLAT3aqxD6vRNm1RAxpUoBcdqNB3C0s1Bt+K+PbEx2F5F4gQp6hqKkphCY/xF9w==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.13.tgz",
"integrity": "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==",
"cpu": [
"x64"
],
@@ -1770,9 +1770,9 @@
}
},
"node_modules/@rolldown/binding-freebsd-x64": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.11.tgz",
"integrity": "sha512-4Ir5FSOKIAMr4r0kExpt1s3bMgzJU3rA45AYOHtQpls0oNeqcYBKrWMlckrYH4KCfGLfkfn1tN1dmZPMVsdXow==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.13.tgz",
"integrity": "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==",
"cpu": [
"x64"
],
@@ -1787,9 +1787,9 @@
}
},
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.11.tgz",
"integrity": "sha512-/gnRDM+39BROzAN/k1OZjDPnDMcZxB/0EUxKjONO5yVkNEvlsoMDrxGNKgZi/ttFriS2gwlDNzB65pvNbFOXIQ==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.13.tgz",
"integrity": "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==",
"cpu": [
"arm"
],
@@ -1804,9 +1804,9 @@
}
},
"node_modules/@rolldown/binding-linux-arm64-gnu": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.11.tgz",
"integrity": "sha512-PFaK8HwvAHbaKbBcDNQihjMKYvFnA5hiENx/l5tphTDz1E0WFp32l0A7aq7lyUwGsRw/xSrNIy/gIK4thrSCrw==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.13.tgz",
"integrity": "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==",
"cpu": [
"arm64"
],
@@ -1821,9 +1821,9 @@
}
},
"node_modules/@rolldown/binding-linux-arm64-musl": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.11.tgz",
"integrity": "sha512-AskzJUIKRLPxkruR1wLKewGbOw+EYfU/9lOrBFj4AFrEA8hPpKFnODWNu2WLaNs0QNkEb9QIJufmVZZIL/bJlg==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.13.tgz",
"integrity": "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==",
"cpu": [
"arm64"
],
@@ -1838,9 +1838,9 @@
}
},
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.11.tgz",
"integrity": "sha512-qlUGAheh2yh8afH7QBgx0PrRHN85hKnNd78x8MeMhXivuevgd8vgf6/CstOzmNKY/lLTHvNTrPy98cLnAugzJw==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.13.tgz",
"integrity": "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==",
"cpu": [
"ppc64"
],
@@ -1855,9 +1855,9 @@
}
},
"node_modules/@rolldown/binding-linux-s390x-gnu": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.11.tgz",
"integrity": "sha512-secpEad+0vCbSfn8upFySkDskv+bGPk3THSDS9Y89yc4rb4kzqHp8Dmyd9BkQW4SnhNXBZCl/6CrO//hZahNJQ==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.13.tgz",
"integrity": "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==",
"cpu": [
"s390x"
],
@@ -1872,9 +1872,9 @@
}
},
"node_modules/@rolldown/binding-linux-x64-gnu": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.11.tgz",
"integrity": "sha512-mOVBT3dPpkWm8XBWPmU4bf+U6dYDLeMo/9ojUmis4N0L5uu10qra5vOyngZ7/PSdoE4G9KvRt4bloRxNjLas7A==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.13.tgz",
"integrity": "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==",
"cpu": [
"x64"
],
@@ -1889,9 +1889,9 @@
}
},
"node_modules/@rolldown/binding-linux-x64-musl": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.11.tgz",
"integrity": "sha512-Is78i9A8Ui4SqcxUwFJ9uMmjDn58IbVTjFWYdQestFEgeuEmHMLGNriXnVJKkwG2YiZjw8cP0zCTyDMdDGtOOg==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.13.tgz",
"integrity": "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==",
"cpu": [
"x64"
],
@@ -1906,9 +1906,9 @@
}
},
"node_modules/@rolldown/binding-openharmony-arm64": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.11.tgz",
"integrity": "sha512-dUCXneZ87INUMyQ0D+C0HrEBNUPNXHaPmU5GTjyKTJEiussw9Kaj5Ln8UztPe4epV/ffvgNBEadksdYhmW6xJA==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.13.tgz",
"integrity": "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==",
"cpu": [
"arm64"
],
@@ -1923,9 +1923,9 @@
}
},
"node_modules/@rolldown/binding-win32-arm64-msvc": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.11.tgz",
"integrity": "sha512-jByxb6qfd+bH1xUd0qnfFnb17i9sWBPY2tOavJ0l3tdr3OTu+Kvtm8cd/JV5nFt657b1VqGltxg9olOEfofXWw==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.13.tgz",
"integrity": "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==",
"cpu": [
"arm64"
],
@@ -1940,9 +1940,9 @@
}
},
"node_modules/@rolldown/binding-win32-x64-msvc": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.11.tgz",
"integrity": "sha512-/PzKqzAJ03i19oy2ItPvyvaVjOjBCNnfaJs8yvUdGBKmiESgnrJSQ2awd81QzFbbnAmu7YO9ZnJrDCb9VSJPRA==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.13.tgz",
"integrity": "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==",
"cpu": [
"x64"
],
@@ -2781,9 +2781,9 @@
}
},
"node_modules/daisyui": {
"version": "5.7.46",
"resolved": "https://registry.npmjs.org/daisyui/-/daisyui-5.7.46.tgz",
"integrity": "sha512-z/tfVXLpLRe1ojGeokzxauHA9Ij5CGfk+83EdatQbFSVr02h5mUcp4nkgQJOw68wH1wAAPu/SY+MWbDdJG2R4w==",
"version": "5.7.50",
"resolved": "https://registry.npmjs.org/daisyui/-/daisyui-5.7.50.tgz",
"integrity": "sha512-+/LRqnTCoc7s/bJEKKwtJSwzeXCVdAmRdNmZeZzgHCaQ9PJyl7j+2V2U32GQDMyD+VDkP9e/+JGoC72Y1hLk7w==",
"dev": true,
"license": "MIT",
"funding": {
@@ -2879,9 +2879,9 @@
"license": "MIT"
},
"node_modules/dotenv": {
"version": "18.0.4",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-18.0.4.tgz",
"integrity": "sha512-jGt9uI5BIxpVO15kvy+iEFqNAwxYClKWnkptLjSNPnFLC003Imd0ofr3aEVsbpHdSBdSsbcApNIlz4nbyGMwdA==",
"version": "18.0.8",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-18.0.8.tgz",
"integrity": "sha512-2KDeoFoK/zRtcnbunCDlLG5VWVMcyqeQc6iK65o231nfNAcuGrKoqUQfJFUtBI+QlShk5HKIHxwebBtUl3rEfA==",
"dev": true,
"license": "BSD-2-Clause",
"bin": {
@@ -3635,9 +3635,9 @@
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
"version": "3.3.20",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
"integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
"dev": true,
"funding": [
{
@@ -3730,9 +3730,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
"integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
"version": "8.5.30",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz",
"integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==",
"dev": true,
"funding": [
{
@@ -3750,9 +3750,9 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.18",
"nanoid": "^3.3.20",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
"source-map-js": "^1.2.2"
},
"engines": {
"node": "^10 || ^12 || >=14"
@@ -3917,13 +3917,13 @@
}
},
"node_modules/rolldown": {
"version": "1.2.11",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.11.tgz",
"integrity": "sha512-qpSwIyz0jHQq5qXBTNxFmE6664rJ7O+4TvPFOiOaBSrz8IOHc1koKKSqTM2H6u1UG1+TveuC6vaDHKXFOvb1Kw==",
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz",
"integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@oxc-project/types": "=0.151.0",
"@oxc-project/types": "=0.153.0",
"@rolldown/pluginutils": "^1.0.0"
},
"bin": {
@@ -3933,21 +3933,21 @@
"node": "^20.19.0 || >=22.12.0"
},
"optionalDependencies": {
"@rolldown/binding-android-arm-eabi": "1.2.11",
"@rolldown/binding-android-arm64": "1.2.11",
"@rolldown/binding-darwin-arm64": "1.2.11",
"@rolldown/binding-darwin-x64": "1.2.11",
"@rolldown/binding-freebsd-x64": "1.2.11",
"@rolldown/binding-linux-arm-gnueabihf": "1.2.11",
"@rolldown/binding-linux-arm64-gnu": "1.2.11",
"@rolldown/binding-linux-arm64-musl": "1.2.11",
"@rolldown/binding-linux-ppc64-gnu": "1.2.11",
"@rolldown/binding-linux-s390x-gnu": "1.2.11",
"@rolldown/binding-linux-x64-gnu": "1.2.11",
"@rolldown/binding-linux-x64-musl": "1.2.11",
"@rolldown/binding-openharmony-arm64": "1.2.11",
"@rolldown/binding-win32-arm64-msvc": "1.2.11",
"@rolldown/binding-win32-x64-msvc": "1.2.11"
"@rolldown/binding-android-arm-eabi": "1.2.13",
"@rolldown/binding-android-arm64": "1.2.13",
"@rolldown/binding-darwin-arm64": "1.2.13",
"@rolldown/binding-darwin-x64": "1.2.13",
"@rolldown/binding-freebsd-x64": "1.2.13",
"@rolldown/binding-linux-arm-gnueabihf": "1.2.13",
"@rolldown/binding-linux-arm64-gnu": "1.2.13",
"@rolldown/binding-linux-arm64-musl": "1.2.13",
"@rolldown/binding-linux-ppc64-gnu": "1.2.13",
"@rolldown/binding-linux-s390x-gnu": "1.2.13",
"@rolldown/binding-linux-x64-gnu": "1.2.13",
"@rolldown/binding-linux-x64-musl": "1.2.13",
"@rolldown/binding-openharmony-arm64": "1.2.13",
"@rolldown/binding-win32-arm64-msvc": "1.2.13",
"@rolldown/binding-win32-x64-msvc": "1.2.13"
}
},
"node_modules/rollup-plugin-visualizer": {
@@ -4042,9 +4042,9 @@
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
@@ -4142,9 +4142,9 @@
}
},
"node_modules/svelte": {
"version": "5.57.1",
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.1.tgz",
"integrity": "sha512-Uqj49lWKB+iSSnneuwiYYJ7MZgkB+eXr0LXBhv4uDuAkXqnWmq65Sxflfvp0Lc6MdKjMUxGaeOKWJqz5SNiVIA==",
"version": "5.57.2",
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.2.tgz",
"integrity": "sha512-1YiPCAXT0Ct6g1vOMmSLa0Nsc3QRMvtDF32ihgglGVrugIuIK38RyDiFNXVDhtQ81TJjSO57NdMw6DyYLqSGDQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4321,9 +4321,9 @@
"license": "0BSD"
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
@@ -4427,16 +4427,16 @@
"license": "MIT"
},
"node_modules/vite": {
"version": "8.3.1",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.1.tgz",
"integrity": "sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==",
"version": "8.3.4",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz",
"integrity": "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"lightningcss": "^1.33.0",
"picomatch": "^4.0.7",
"postcss": "^8.5.28",
"rolldown": "~1.2.9",
"postcss": "^8.5.29",
"rolldown": "~1.2.12",
"tinyglobby": "^0.2.17"
},
"bin": {
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.48.9",
"version": "0.48.10",
"type": "module",
"scripts": {
"dev": "vite",
@@ -16,20 +16,20 @@
"@vitejs/plugin-legacy": "^8.2.3",
"autoprefixer": "^10.6.1",
"bgutils-js": "^4.0.3",
"daisyui": "^5.7.46",
"dotenv": "^18.0.4",
"daisyui": "^5.7.50",
"dotenv": "^18.0.8",
"ip": "^2.0.1",
"jszip": "^3.10.2",
"postcss": "^8.5.28",
"postcss": "^8.5.30",
"rollup-plugin-visualizer": "^7.1.1",
"svelte": "^5.57.1",
"svelte": "^5.57.2",
"svelte-check": "^4.7.6",
"svelte-preprocess": "^6.0.5",
"tailwindcss": "^4.3.3",
"terser": "^5.51.2",
"tslib": "^2.8.1",
"typescript": "^5.9.3",
"vite": "^8.3.1",
"typescript": "^6.0.3",
"vite": "^8.3.4",
"vite-plugin-compression": "^0.5.1"
}
}
+2 -3
View File
@@ -4,13 +4,12 @@
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"baseUrl": ".",
"paths": {
"lib/*": [
"src/lib/*"
"./src/lib/*"
],
"assets/*": [
"src/assets/*"
"./src/assets/*"
],
},
/**
@@ -67,6 +67,11 @@ export class LocaleValidationPlugin implements CompilerPlugin {
return;
}
// Rooibos generates its test-runner components in test builds
if (file.pkgPath.replace(/\\/g, '/').startsWith('components/rooibos/')) {
return;
}
if (this.enums.length === 0 || this.localeValues.length === 0) {
return;
}