Compare commits

...
55 Commits
Author SHA1 Message Date
Brahim Hadriche 68fd91bed2 Release 0.5.0 (#21) 2022-12-02 16:37:20 -05:00
Brahim Hadriche e027c8cf47 Formatting 2022-12-02 15:57:27 -05:00
Brahim Hadriche f63d8e5a18 Fix dialog 2022-12-02 15:56:49 -05:00
Brahim Hadriche 4428baae41 Bug fixes 2022-12-02 15:51:26 -05:00
Brahim Hadriche 6ec392a4fe Picture in picture (#20)
* Refactor and fix player

* Rename functions, fix video loading indicator

* Hide loading indicator on exit

* Picture in picture, exit dialog, fix spinner

* Set launch and input args

* Deep linking support

* Update changelog

* Support dialog multiline

* Comments and changelog
2022-12-02 14:24:07 -05:00
Brahim Hadriche 68a8d61eb0 Refactor and fix player (#19)
* Refactor and fix player

* Rename functions, fix video loading indicator

* Hide loading indicator on exit
2022-12-02 10:46:48 -05:00
Brahim Hadriche 2d1490f925 Invidious calls cleanup, add fields, fix subscriptions 2022-12-01 16:50:06 -05:00
Brahim Hadriche 58d2fc7041 Add spinner 2022-12-01 12:59:07 -05:00
Brahim Hadriche b739742006 Fix Bug where playing and exiting a video too quickly would cause the video to play in the background 2022-12-01 12:13:38 -05:00
Brahim Hadriche 953403f952 Command api refactor 2022-12-01 12:00:48 -05:00
Brahim Hadriche 0409e61b5f Remove unused var 2022-11-30 22:39:10 -05:00
Brahim Hadriche d88c1c087f Fix arg count 2022-11-30 22:35:22 -05:00
Brahim Hadriche 58ce258509 Use POST to update instances 2022-11-30 20:29:58 -05:00
Brahim Hadriche 16797a5144 Formatting 2022-11-30 19:48:36 -05:00
Brahim Hadriche 64cf7b54a0 Sponsorblock progressbar (#18)
* Generate sponsorblock bar

* Sponsorblock chapter label

* Add comment

* Fix typo

* Changelog
2022-11-30 19:41:07 -05:00
Brahim Hadriche 21593001ae Better debugging 2022-11-30 10:16:44 -05:00
Brahim Hadriche ce04a1af1a Move bs_const to manifest 2022-11-30 09:11:31 -05:00
Brahim Hadriche 78a7c937ae Add routers for tmp and cachefs 2022-11-29 23:20:00 -05:00
Brahim Hadriche a059702a0e Add debug web server 2022-11-29 23:13:52 -05:00
Brahim Hadriche 68a32afc38 Fix keep alive header 2022-11-29 22:07:57 -05:00
Brahim Hadriche 2f5ac709ba Check if dash already has thumbnails 2022-11-29 21:43:18 -05:00
Brahim Hadriche 5b10696400 Inject thumbnails in DASH (#15)
* [Test] inject thumbnails in DASH

* Address wrong storyboard hight

* Better dash

* Feature flag it for now

* Add a small safety check and some comments

* Fix thumbnails

* Fix content type

* Fix dash router

* Remove comment

* Move function, add null check
2022-11-29 21:24:37 -05:00
Brahim Hadriche 301cfe1b82 Add basic auth (#17) 2022-11-29 21:04:46 -05:00
Brahim Hadriche 1734425b9c [Refactor] web server header cleanups (#16)
* Rename variables

* Content type headers

* Headers cleanup
2022-11-29 18:43:23 -05:00
Brahim Hadriche 27b4ad90d3 Router cleanup 2022-11-28 12:19:40 -05:00
Brahim Hadriche e0cc6970ab Add error dialog 2022-11-28 11:49:33 -05:00
Brahim Hadriche 52fd7c87aa Improve search 2022-11-27 19:58:59 -05:00
Brahim Hadriche 1b121d9ace Bug fix for when video is restarted, remove embedded video dead code 2022-11-27 18:30:46 -05:00
Brahim Hadriche b1efa457a2 Button color fix 2022-11-26 17:36:44 -05:00
Brahim Hadriche 85209cb22e Web-server refactor (#14)
* rename field

* Parse body support

* Changelog

* Parse query params

* Error handling for larger than content-length body
2022-11-26 17:25:40 -05:00
Brahim Hadriche 3f5cb84696 Sponsorblock add mute sections 2022-11-25 14:34:21 -05:00
Brahim Hadriche 7fd466fb25 Screenshots! 2022-11-25 13:52:08 -05:00
Brahim Hadriche 02e44960b7 Add CORS middleware 2022-11-25 13:29:48 -05:00
Brahim Hadriche 386dfc1419 Use hash video for SponsorBlock 2022-11-25 12:56:26 -05:00
Brahim Hadriche 25b2ea7091 Add version check (#13) 2022-11-25 11:50:52 -05:00
Brahim Hadriche a1484c01eb Fix config 2022-11-25 10:57:22 -05:00
Brahim Hadriche 5724f0c026 Update README.md 2022-11-24 22:27:31 -05:00
Brahim Hadriche fb857c0281 Update README.md 2022-11-24 22:23:44 -05:00
Brahim Hadriche ef971e1c19 Add banner 2022-11-24 22:21:31 -05:00
Brahim Hadriche 38dfb5ca06 New logo 2022-11-24 22:12:19 -05:00
Brahim Hadriche f3fbe68db0 Release 0.4.0 (#12) 2022-11-24 20:06:52 -05:00
Brahim Hadriche a248318c54 Ground work for invidious instance selection (#11)
* Ground work for invidious instance selection

* Display logged in instance

* Show instances

* Reorder instances

* Instance management

* Add todos

* Changelog

* Add instances link, trim trailing slash

* Small tweaks
2022-11-24 18:40:27 -05:00
Brahim Hadriche 1d9dc3ecda Add sponsorblock categories and action types as json 2022-11-23 21:14:09 -05:00
Brahim Hadriche 740440c3a7 Search screen (#10)
* Search screen with keyboard and suggestions

* Clear search on visibility change

* Search page works

* Local search history

* Use built-in delete function

* Changelog

* Animation

* Adjust suggestions

* Web play video always goes to home
2022-11-23 09:02:05 -05:00
Brahim Hadriche 22dfe785f1 Add logout support (#9)
* Add logout support

* Use token as json payload

* Comment
2022-11-22 18:33:55 -05:00
Brahim Hadriche 8aa1d1ae51 Live banner on live videos 2022-11-22 17:39:50 -05:00
Brahim Hadriche b113fcfe7e DASH support 2022-11-22 15:55:46 -05:00
Brahim Hadriche adfcfabad1 add meta data to video player 2022-11-22 12:48:13 -05:00
Brahim Hadriche 651bb54dee Play API prototype (#8)
* Play API prototype

* Web app

* Drag and drop support

* Handle different urls

* Fix redirect

* Increase max connections

* changelog

* Limit timeout

* Use fetch

* Redirects

* Formatting
2022-11-21 18:47:12 -05:00
Brahim Hadriche 192eec9519 Update README.md 2022-11-19 15:53:14 -05:00
Brahim Hadriche 713d7fba5d Update README.md 2022-11-19 15:50:37 -05:00
Brahim Hadriche cb0a5d0e17 Update README.md 2022-11-19 15:30:57 -05:00
Brahim Hadriche b5f01a10e9 Fix bug with double screens visible 2022-11-19 14:34:38 -05:00
Brahim Hadriche 93e59fee65 Add screenshot to readme 2022-11-19 14:23:31 -05:00
Brahim Hadriche 069b8377d6 add screenshot 2022-11-19 14:20:57 -05:00
93 changed files with 2914 additions and 855 deletions

No files matched your search

+2 -1
View File
@@ -2,4 +2,5 @@ dist/
out/ out/
node_modules node_modules
.vscode/.env .vscode/.env
**/roku_modules/** **/roku_modules/**
release/playlet.zip
+2 -1
View File
@@ -11,13 +11,14 @@
"enableDebuggerAutoRecovery": false, "enableDebuggerAutoRecovery": false,
"stopDebuggerOnAppExit": false, "stopDebuggerOnAppExit": false,
"rootDir": "${workspaceFolder}/dist/build", "rootDir": "${workspaceFolder}/dist/build",
"preLaunchTask": "build", "preLaunchTask": "build-dev",
"name": "Launch playlet (dev)", "name": "Launch playlet (dev)",
"injectRdbOnDeviceComponent": true "injectRdbOnDeviceComponent": true
}, },
{ {
"type": "brightscript", "type": "brightscript",
"request": "launch", "request": "launch",
"envFile": "${workspaceFolder}/.vscode/.env",
"host": "${env:ROKU_DEV_TARGET}", "host": "${env:ROKU_DEV_TARGET}",
"password": "${env:ROKU_DEVPASSWORD}", "password": "${env:ROKU_DEVPASSWORD}",
"stopOnEntry": false, "stopOnEntry": false,
+2 -2
View File
@@ -2,13 +2,13 @@
"version": "2.0.0", "version": "2.0.0",
"tasks": [ "tasks": [
{ {
"label": "build", "label": "build-dev",
"presentation": { "presentation": {
"close": true, "close": true,
"reveal": "silent", "reveal": "silent",
"revealProblems": "onProblem" "revealProblems": "onProblem"
}, },
"script": "build", "script": "build:dev",
"type": "npm" "type": "npm"
}, },
{ {
+33
View File
@@ -4,6 +4,39 @@ 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.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.5.0] - 2022-12-02
### Added
- Version check in settings page
- Support for web request body parsing
- Error dialog for video load fail
- SponsorBlock sections and category info
- Loading spinner
- Picture in picture support
- [Deep linking support](https://developer.roku.com/en-ca/docs/developer-program/discovery/implementing-deep-linking.md)
- Both Launch arguments and Input arguments are supported, using the "contentId" key as the Youtube video id
- Error and Exit dialogs
### Fixed
- Bug where playing and exiting a video too quickly would cause the video to play in the background.
- Bug where logging in causes issues if a video is already playing
- Bug where casting from web app while playing a video from the search
- Spinner for the video
- Bug where search sugggestions selected index is higher than total count
- Race condition where button group gains focus before suggestions are set in Search Page
## [0.4.0] - 2022-11-24
### Added
- Play video API
- Play video by ID/URL in web app
- Metadata to Video Player
- Support for DASH and Live videos
- Log out button to web app
- Search Screen
- Very basic UI to customize/change invidious instance
### Fixed
- Bug where Settings page and home page are both visible, if settings page is selected, and user logs in.
## [0.3.0] - 2022-11-19 ## [0.3.0] - 2022-11-19
### Changed ### Changed
- App name! new name: **Playlet** - App name! new name: **Playlet**
+49 -6
View File
@@ -1,10 +1,33 @@
<p align="center">
<img src="banner.png" style="display:block;text-align:center" alt="Playlet Logo" width="800"/>
</p>
# Playlet # Playlet
Unofficial Youtube client for Roku.
Unofficial Youtube client for Roku 📺
## Features ## Features
- No Ads (I guess that's a feature) - 🔥 No Ads (Not now, not ever)
- Privacy driven (uses Invidious backend) - 🕵️ No Tracking
- SponsorBlock integration (skips undesirable sections in videos) - 🛡️ Privacy driven (uses Invidious backend)
- ⚔️ SponsorBlock integration (skips undesirable sections in videos)
- 📱 Cast from phone
- 🔮 Picture-in-picture mode
### Cast from phone
1. Open settings in Playlet
1. Scan QR Code with Phone
1. Enter video ID or video url, and press Play button
### Picture-in-picture
- When viewing a video in full screen, press ⬇️ (down) button on your remote to shrink the video
- You can browser or search for videos while you watch
- To restore currently playing video to full screen, press the ✳️ (options) button
## Screenshots
<img src="screenshot1.jpg" alt="Screenshot of Playlet" width="350"/>
<img src="screenshot2.jpg" alt="Screenshot of Playlet" width="350"/>
<img src="screenshot3.jpg" alt="Screenshot of Playlet" width="350"/>
## Installation ## Installation
@@ -13,14 +36,14 @@ First, you need to enable developer mode on your Roku TV (if you have not done t
Using your Roku remote, enter the following sequence: Using your Roku remote, enter the following sequence:
![DevSequence](https://image.roku.com/ZHZscHItMTc2/dev-startup1.png) <img src="https://image.roku.com/ZHZscHItMTc2/dev-startup1.png" alt="DevSequence" width="350"/>
For full instructions, see [Set up your Roku device to enable Developer Settings](https://developer.roku.com/en-ca/docs/developer-program/getting-started/developer-setup.md#step-1-set-up-your-roku-device-to-enable-developer-settings) For full instructions, see [Set up your Roku device to enable Developer Settings](https://developer.roku.com/en-ca/docs/developer-program/getting-started/developer-setup.md#step-1-set-up-your-roku-device-to-enable-developer-settings)
Make sure to remember the password you set during this step, you will need it later. Make sure to remember the password you set during this step, you will need it later.
### Gather your info ### Gather your info
By now, you show have the following By now, you should have the following
- Your Roku Dev password (setup in the previous step) - Your Roku Dev password (setup in the previous step)
- Your Roku TV local IP address - Your Roku TV local IP address
- You can find this information in your TV network settings. It should look like 192.168.X.X or so - You can find this information in your TV network settings. It should look like 192.168.X.X or so
@@ -63,3 +86,23 @@ ROKU_DEVPASSWORD=REPLACE_PASSWORD_HERE
``` ```
Then you can open the project using VS Code and deploy to your Roku TV using the Debug button. Then you can open the project using VS Code and deploy to your Roku TV using the Debug button.
## Why Playlet
```
playlet - noun
play•let /ˈplālət/
: a short play
```
**Playlet** is about keeping the time you spend on Youtube short and useful. It values your time, so it does not show you ads, and allows you to skip sponsored sections and other irrelevant information that's designed to monitize you and/or waste your time.
There's a cliché about how a lot of open source software is **`"Made with ♡"`**. This project in particular is **not**.<br/>
**Playlet** was created out of **spite**, because I believe I have watched enough back-to-back, unskippable Youtube ads for a lifetime.
By removing all the bloat, the ads, the tracking, we could end up with an even faster app than the official one.
In any case, I hope you find **Playlet** useful, and pleasant to use.
## Disclaimer
**Playlet** does not serve or distribute any material from unauthorized sources.<br/>
**Playlet** is simply a frontend to other systems (such as https://github.com/iv-org/invidious), bringing the watching experience to the TV, as opposed to the existing frontends that are web and mobile focused.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

+4 -3
View File
@@ -4,7 +4,8 @@
"diagnosticFilters": [ "diagnosticFilters": [
{ {
"src": "**/roku_modules/**/*.*" "src": "**/roku_modules/**/*.*"
} },
1090
], ],
"diagnosticLevel": "error", "diagnosticLevel": "error",
"files": [ "files": [
@@ -21,7 +22,7 @@
"roku-log-bsc-plugin", "roku-log-bsc-plugin",
"@rokucommunity/bslint" "@rokucommunity/bslint"
], ],
"retainStagingFolder": true, "retainStagingDir": true,
"rokuLog": { "rokuLog": {
"insertPkgPath": true, "insertPkgPath": true,
"removeComments": false, "removeComments": false,
@@ -29,5 +30,5 @@
}, },
"rootDir": "../src/", "rootDir": "../src/",
"sourceMap": true, "sourceMap": true,
"stagingFolderPath": "dist/build" "stagingDir": "dist/build"
} }
+1 -1
View File
@@ -2,6 +2,6 @@
"createPackage": false, "createPackage": false,
"deploy": false, "deploy": false,
"extends": "bsconfig.base.json", "extends": "bsconfig.base.json",
"retainStagingFolder": false, "retainStagingDir": false,
"sourceMap": false "sourceMap": false
} }
+18 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet", "name": "playlet",
"version": "0.3.0", "version": "0.4.0",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet", "name": "playlet",
"version": "0.3.0", "version": "0.4.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"bslib": "npm:@rokucommunity/bslib@^0.1.1", "bslib": "npm:@rokucommunity/bslib@^0.1.1",
@@ -19,6 +19,7 @@
"brighterscript": "^0.60.6", "brighterscript": "^0.60.6",
"brighterscript-formatter": "^1.6.19", "brighterscript-formatter": "^1.6.19",
"convert-svg-to-png": "^0.6.4", "convert-svg-to-png": "^0.6.4",
"dotenv": "^16.0.3",
"roku-log-bsc-plugin": "^0.6.1", "roku-log-bsc-plugin": "^0.6.1",
"ropm": "^0.10.10", "ropm": "^0.10.10",
"semver": "^7.3.8" "semver": "^7.3.8"
@@ -1266,6 +1267,15 @@
"url": "https://github.com/fb55/domutils?sponsor=1" "url": "https://github.com/fb55/domutils?sponsor=1"
} }
}, },
"node_modules/dotenv": {
"version": "16.0.3",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.3.tgz",
"integrity": "sha512-7GO6HghkA5fYG9TYnNxi14/7K9f5occMlp3zXAuSxn7CKCxt9xbNWG7yF8hTCSUchlfWSe3uLmlPfigevRItzQ==",
"dev": true,
"engines": {
"node": ">=12"
}
},
"node_modules/ecc-jsbn": { "node_modules/ecc-jsbn": {
"version": "0.1.2", "version": "0.1.2",
"resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz",
@@ -4563,6 +4573,12 @@
"domhandler": "^5.0.1" "domhandler": "^5.0.1"
} }
}, },
"dotenv": {
"version": "16.0.3",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.0.3.tgz",
"integrity": "sha512-7GO6HghkA5fYG9TYnNxi14/7K9f5occMlp3zXAuSxn7CKCxt9xbNWG7yF8hTCSUchlfWSe3uLmlPfigevRItzQ==",
"dev": true
},
"ecc-jsbn": { "ecc-jsbn": {
"version": "0.1.2", "version": "0.1.2",
"resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz",
+8 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet", "name": "playlet",
"version": "0.3.0", "version": "0.5.0",
"description": "Unofficial Youtube client for Roku", "description": "Unofficial Youtube client for Roku",
"dependencies": { "dependencies": {
"bslib": "npm:@rokucommunity/bslib@^0.1.1", "bslib": "npm:@rokucommunity/bslib@^0.1.1",
@@ -13,6 +13,7 @@
"brighterscript": "^0.60.6", "brighterscript": "^0.60.6",
"brighterscript-formatter": "^1.6.19", "brighterscript-formatter": "^1.6.19",
"convert-svg-to-png": "^0.6.4", "convert-svg-to-png": "^0.6.4",
"dotenv": "^16.0.3",
"roku-log-bsc-plugin": "^0.6.1", "roku-log-bsc-plugin": "^0.6.1",
"ropm": "^0.10.10", "ropm": "^0.10.10",
"semver": "^7.3.8" "semver": "^7.3.8"
@@ -27,7 +28,9 @@
"scripts": { "scripts": {
"prebuild": "rm -rf dist", "prebuild": "rm -rf dist",
"build": "bsc", "build": "bsc",
"build:prod": "npm run build -- --sourceMap=false", "build:dev": "npm run manifest-symbols -- DEBUG=true && npm run build",
"build:prod": "npm run manifest-symbols -- DEBUG=false && npm run build -- --sourceMap=false",
"build:release": "npm run format:fix && npm run lint:fix && npm run manifest-version && npm run generate-images && npm run build:prod && npm run zip-package",
"lint": "bslint --project config/bsconfig.lint.json --lintConfig config/bslint.jsonc", "lint": "bslint --project config/bsconfig.lint.json --lintConfig config/bslint.jsonc",
"lint:fix": "npm run lint -- --fix", "lint:fix": "npm run lint -- --fix",
"format:base": "bsfmt \"src/**/*.brs\" \"src/**/*.bs\" \"!src/components/lib/**/*\" \"!src/source/lib/**/*\" \"!**/bslib.brs\" \"!**/roku_modules/**/*\" --bsfmt-path \"config/bsfmt.jsonc\"", "format:base": "bsfmt \"src/**/*.brs\" \"src/**/*.bs\" \"!src/components/lib/**/*\" \"!src/source/lib/**/*\" \"!**/bslib.brs\" \"!**/roku_modules/**/*\" --bsfmt-path \"config/bsfmt.jsonc\"",
@@ -35,6 +38,9 @@
"format:fix": "npm run format:base -- --write", "format:fix": "npm run format:base -- --write",
"generate-images": "node scripts/generate-images.js", "generate-images": "node scripts/generate-images.js",
"manifest-version": "node scripts/update-manifest-version.js", "manifest-version": "node scripts/update-manifest-version.js",
"zip-package": "node scripts/zip-package.js",
"screenshot": "node scripts/screenshot.js",
"manifest-symbols": "node scripts/update-manifest-symbols.js",
"postinstall": "npx ropm copy" "postinstall": "npx ropm copy"
} }
} }
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

+22 -9
View File
@@ -2,33 +2,46 @@ const fs = require('fs')
const path = require('path') const path = require('path')
const { convertFile } = require('convert-svg-to-png'); const { convertFile } = require('convert-svg-to-png');
const logoInput = './src/images/vector/logo.svg'; const logoPoster = './src/images/vector/logo-light.svg';
const logoSplash = './src/images/vector/logo-dark.svg';
logoOutput = { logoOutput = {
// Logo // Logo
"splash-screen_fhd.jpg": { "splash-screen_fhd.jpg": {
width: 1920, width: 1920,
height: 1080 height: 1080,
background: "#242424",
from: logoSplash
}, },
"splash-screen_hd.jpg": { "splash-screen_hd.jpg": {
width: 1280, width: 1280,
height: 720 height: 720,
background: "#242424",
from: logoSplash
}, },
"splash-screen_sd.jpg": { "splash-screen_sd.jpg": {
width: 720, width: 720,
height: 480 height: 480,
background: "#242424",
from: logoSplash
}, },
"channel-poster_fhd.png": { "channel-poster_fhd.png": {
width: 540, width: 540,
height: 405 height: 405,
background: "#FFFFFF",
from: logoPoster
}, },
"channel-poster_hd.png": { "channel-poster_hd.png": {
width: 290, width: 290,
height: 218 height: 218,
background: "#FFFFFF",
from: logoPoster
}, },
"channel-poster_sd.png": { "channel-poster_sd.png": {
width: 214, width: 214,
height: 144 height: 144,
background: "#FFFFFF",
from: logoPoster
}, },
}; };
@@ -38,9 +51,9 @@ const iconsOutput = './src/images/icons';
(async () => { (async () => {
for (var logo in logoOutput) { for (var logo in logoOutput) {
await convertFile(logoInput, { await convertFile(logoOutput[logo].from, {
outputFilePath: './src/images/' + logo, outputFilePath: './src/images/' + logo,
background: "#242424", background: logoOutput[logo].background,
height: logoOutput[logo].height, height: logoOutput[logo].height,
width: logoOutput[logo].width, width: logoOutput[logo].width,
}); });
+23
View File
@@ -0,0 +1,23 @@
const rokuDeploy = require('roku-deploy');
const dotenv = require('dotenv')
const fs = require('fs');
const { exit } = require('process');
if(process.argv.length !== 3) {
console.error("Invalid usage! usage: npm run screenshot -- filename")
exit(-1)
}
const filename = process.argv[2]
const config = dotenv.parse(fs.readFileSync('.vscode/.env'))
rokuDeploy.takeScreenshot({
host: config.ROKU_DEV_TARGET,
password: config.ROKU_DEVPASSWORD,
outDir: '.',
outFile: filename
}).then(function(filename){
console.log(`${filename} created`)
}, function(error) {
console.error(error);
});
+33
View File
@@ -0,0 +1,33 @@
const fs = require('fs');
if (process.argv.length < 3) {
console.error("Invalid usage! usage: npm run manifest-symbols -- SYMBOL1=true [SYMBOL2=false]")
exit(-1)
}
function argsToSymbolsObject(arr) {
return arr.reduce(function (acc, value) {
keyValue = value.split("=")
acc[keyValue[0]] = keyValue[1]
return acc
}, {})
}
const newSymbols = argsToSymbolsObject(process.argv.slice(2))
let currentSymbols = {}
const appManifestLines = fs.readFileSync("./src/manifest", { encoding: 'utf8', flag: 'r' }).split('\n')
const bsConstIndex = appManifestLines.findIndex(line => line.startsWith("bs_const="))
if (bsConstIndex !== -1) {
let bsConst = appManifestLines[bsConstIndex]
bsConst = bsConst.substring("bs_const=".length)
currentSymbols = argsToSymbolsObject(bsConst.split(";"))
}
mergedSymbols = {...currentSymbols, ...newSymbols}
bsConst = "bs_const=" + Object.keys(mergedSymbols).map(key => `${key}=${mergedSymbols[key]}`).join(";")
appManifestLines[bsConstIndex] = bsConst
fs.writeFileSync("./src/manifest", appManifestLines.join("\n"))
+14
View File
@@ -0,0 +1,14 @@
var rokuDeploy = require('roku-deploy');
const zip_name = 'playlet.zip'
rokuDeploy.zipPackage({
outDir: 'release',
outFile: zip_name,
//BUG: rokuDeploy does not read stagingDir properly fron config
stagingDir: 'dist/build'
}).then(function(){
console.log(`${zip_name} created`)
}, function(error) {
console.error(error);
});
+7
View File
@@ -0,0 +1,7 @@
function Init()
m.top.observeField("buttonSelected", "CloseDialog")
end function
function CloseDialog()
m.top.close = true
end function
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8" ?>
<component name="Dialog" extends="StandardMessageDialog" >
</component>
+15
View File
@@ -0,0 +1,15 @@
function ShowDialog(message as dynamic, title as string) as object
return ShowDialogButtons(message, title, ["Ok"])
end function
function ShowDialogButtons(message as dynamic, title as string, buttons as object) as object
dialog = CreateObject("roSGNode", "Dialog")
if GetInterface(message, "ifArray") = invalid
message = message.Tokenize(UnixNL()).ToArray()
end if
dialog.message = message
dialog.title = title
dialog.buttons = buttons
m.top.getScene().dialog = dialog
return dialog
end function
+16 -61
View File
@@ -5,6 +5,8 @@ function Init()
m.rowList = m.top.FindNode("rowList") m.rowList = m.top.FindNode("rowList")
m.top.ObserveField("rowItemSelected", "OnHomeGridScreenVideoSelected") m.top.ObserveField("rowItemSelected", "OnHomeGridScreenVideoSelected")
m.top.ObserveField("focus", "OnFocusChange") m.top.ObserveField("focus", "OnFocusChange")
m.top.ObserveField("playvideo", "OnPlayVideoCommand")
m.top.ObserveField("refresh", "OnRefresh")
m.top.focus = true m.top.focus = true
@@ -17,6 +19,10 @@ function OnFocusChange()
end if end if
end function end function
function OnRefresh()
InitContent()
end function
function InitContent() function InitContent()
m.sortedContent = [] m.sortedContent = []
contentNode = CreateObject("roSGNode", "ContentNode") contentNode = CreateObject("roSGNode", "ContentNode")
@@ -45,8 +51,6 @@ function StartFetchTask() as void
if m.sortedContent.Count() = m.defaultLayout.Count() if m.sortedContent.Count() = m.defaultLayout.Count()
' All tasks are done ' All tasks are done
m.Delete("sortedContent") m.Delete("sortedContent")
' TODO: uncommment if auto-play
' m.top.ObserveField("rowItemFocused", "OnHomeGridScreenVideoFocused")
end if end if
return return
end if end if
@@ -92,7 +96,6 @@ function StartFetchTask() as void
end function end function
function OnHomeGridScreenContentLoaded() function OnHomeGridScreenContentLoaded()
m.top.SetFocus(true)
m.global.loadingIndicator.visible = false m.global.loadingIndicator.visible = false
end function end function
@@ -106,73 +109,25 @@ function OnHomeGridScreenVideoSelected(event as object) as void
rowContent = grid.content.GetChild(selectedRow) rowContent = grid.content.GetChild(selectedRow)
itemContent = rowContent.GetChild(selectedRowItem) itemContent = rowContent.GetChild(selectedRowItem)
videoId = itemContent.id videoId = itemContent.videoId
if m.videoPlayer <> invalid PlayVideo(videoId, m.top)
if m.videoPlayer.videoId = videoId
ExpandVideoScreenFull()
return
else
m.videoPlayer.control = "stop"
m.videoPlayer.visible = false
m.videoPlayer.getParent().removeChild(m.videoPlayer)
m.videoPlayer = invalid
end if
end if
ShowVideoScreenFull(videoId)
end function end function
function CloseVideo() function OnPlayVideoCommand()
if m.videoPlayer <> invalid videoId = m.top.playvideo
m.videoPlayer.control = "stop" PlayVideo(videoId)
m.videoPlayer.visible = false
m.videoPlayer.getParent().removeChild(m.videoPlayer)
m.videoPlayer = invalid
end if
end function
function OnHomeGridScreenVideoFocused(event as object) as void
' Skip loading the video after first load
if m.firstFocus = invalid
m.firstFocus = true
return
end if
if m.videoPlayer <> invalid
m.videoPlayer.control = "stop"
m.videoPlayer.visible = false
m.videoPlayer.getParent().removeChild(m.videoPlayer)
m.videoPlayer = invalid
end if
grid = event.GetRoSGNode()
selectedPair = event.GetData()
selectedRow = selectedPair[0]
selectedRowItem = selectedPair[1]
rowContent = grid.content.GetChild(selectedRow)
itemContent = rowContent.GetChild(selectedRowItem)
videoId = itemContent.id
thumbnail = GetThumbnailPoster(videoId)
ShowVideoScreenEmbedded(videoId, thumbnail)
end function
function GetThumbnailPoster(videoId as string) as object
' TODO: make this faster
all = m.top.getAll()
for each item in all
if item.id = `thumbnail-${videoId}`
return item
end if
end for
return invalid
end function end function
function OnkeyEvent(key as string, press as boolean) as boolean function OnkeyEvent(key as string, press as boolean) as boolean
if press = false if press = false
return false return false
end if end if
if key = "options"
if ToggleVideoPictureInPicture(m.top)
return true
end if
end if
if key = "left" or key = "back" if key = "left" or key = "back"
m.top.escape = key m.top.escape = key
return true return true
@@ -8,6 +8,8 @@
<field id="jumpToRowItem" type="intarray" alias="RowList.jumpToRowItem" /> <field id="jumpToRowItem" type="intarray" alias="RowList.jumpToRowItem" />
<field id="escape" type="string" alwaysNotify="true" /> <field id="escape" type="string" alwaysNotify="true" />
<field id="focus" type="boolean" alwaysNotify="true" /> <field id="focus" type="boolean" alwaysNotify="true" />
<field id="playvideo" type="string" alwaysNotify="true" />
<field id="refresh" type="boolean" alwaysNotify="true" />
</interface> </interface>
<children> <children>
<RowList <RowList
@@ -56,27 +56,7 @@ function GetItemData(video as object) as object
if video.videoId = invalid if video.videoId = invalid
return invalid return invalid
end if end if
item = {}
item.title = video.title return video
item.description = video.description
item.hdPosterURL = GetThumbnailUrl(video.videoThumbnails)
item.releaseDate = video.publishedText
item.id = video.videoId
item.length = video.lengthSeconds
item.author = video.author
item.viewCount = video.viewCount
return item
end function end function
function GetThumbnailUrl(videoThumbnails as object, quality = "medium" as string) as string
if videoThumbnails.Count() = 0
return ""
end if
for each thumbnail in videoThumbnails
if thumbnail.quality = quality
return thumbnail.url
end if
end for
return videoThumbnails[0].url
end function
@@ -0,0 +1,26 @@
function Init()
m.busySpinner = m.top.findNode("busySpinner")
m.busyspinner.poster.width = 150
m.busyspinner.poster.height = 150
m.busyspinner.poster.observeField("loadStatus", "PositionSpinner")
m.busySpinner.poster.uri = "pkg:/images/spinner.png"
m.top.observeField("visible", "OnVisibleChange")
end function
function PositionSpinner()
if m.busyspinner.poster.loadStatus = "ready"
centerx = (1280 - m.busyspinner.poster.width) / 2
centery = (720 - m.busyspinner.poster.height) / 2
m.busyspinner.translation = [centerx, centery]
m.busyspinner.visible = true
end if
end function
function OnVisibleChange()
m.busyspinner.visible = m.top.visible
if m.busyspinner.visible
m.busyspinner.control = "start"
else
m.busyspinner.control = "stop"
end if
end function
@@ -6,17 +6,11 @@
width="1280" width="1280"
height="720" height="720"
color="#000000" color="#000000"
opacity="0.5" opacity="0.5">
> <BusySpinner
<Label id="busySpinner"
text="Loading..." inheritParentOpacity="false"
width="1280" spinInterval="1" />
height="720"
translation="[0, 0]"
horizAlign="center"
vertAlign="center"
font="font:MediumBoldSystemFont"
/>
</Rectangle> </Rectangle>
</children> </children>
</component> </component>
+37 -12
View File
@@ -1,4 +1,5 @@
import "pkg:/source/roku_modules/log/LogMixin.brs" import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/components/VideoPlayer/Video.bs"
function Init() function Init()
log.initializeLogManager(["log_PrintTransport"], 2) log.initializeLogManager(["log_PrintTransport"], 2)
@@ -6,16 +7,22 @@ function Init()
m.top.backgroundColor = "0x242424FF" m.top.backgroundColor = "0x242424FF"
m.top.backgroundURI = "" m.top.backgroundURI = ""
loadingIndicator = m.top.findNode("LoadingIndicator") m.loadingIndicator = m.top.findNode("LoadingIndicator")
m.global.addFields({ loadingIndicator: loadingIndicator }) m.videoContainer = m.top.findNode("VideoContainer")
m.global.loadingIndicator.visible = true m.global.addFields({
loadingIndicator: m.loadingIndicator,
videoContainer: m.videoContainer
})
m.loadingIndicator.visible = true
m.homeGridScreen = m.top.findNode("HomeGridScreen") m.homeGridScreen = m.top.findNode("HomeGridScreen")
m.homeGridScreen.ObserveField("escape", "OnHomeGridScreenEscape") m.homeGridScreen.ObserveField("escape", "OnHomeGridScreenEscape")
m.homeGridScreen.SetFocus(true) m.homeGridScreen.SetFocus(true)
m.settingsScreen = m.top.findNode("SettingsScreen") m.settingsScreen = m.top.findNode("SettingsScreen")
m.searchScreen = m.top.findNode("SearchScreen") m.searchScreen = m.top.findNode("SearchScreen")
m.searchScreen.ObserveField("escape", "OnSearchScreenEscape")
m.navBar = m.top.findNode("NavBar") m.navBar = m.top.findNode("NavBar")
m.navBar.ObserveField("escapeIndex", "OnNavBarEscape") m.navBar.ObserveField("escapeIndex", "OnNavBarEscape")
@@ -28,9 +35,15 @@ function InitWebServer()
m.serverTask = createObject("roSGNode", "WebServerTask") m.serverTask = createObject("roSGNode", "WebServerTask")
m.serverTask.id = "WebServerTask" m.serverTask.id = "WebServerTask"
m.serverTask.ObserveField("login", "OnWebServerLogin") m.serverTask.ObserveField("login", "OnWebServerLogin")
m.serverTask.ObserveField("command", "OnWebServerCommand")
m.serverTask.control = "RUN" m.serverTask.control = "RUN"
end function end function
function OnSearchScreenEscape()
m.navBar.SetFocus(true)
m.navBar.focusIndex = 0
end function
function OnHomeGridScreenEscape() function OnHomeGridScreenEscape()
m.navBar.SetFocus(true) m.navBar.SetFocus(true)
m.navBar.focusIndex = 1 m.navBar.focusIndex = 1
@@ -68,15 +81,13 @@ function OnNavIndexChange() as void
end function end function
function OnWebServerLogin() function OnWebServerLogin()
' TODO: refresh same component instead of creating a new one m.homeGridScreen.refresh = true
m.global.loadingIndicator.visible = true end function
homeIndex = GetIndexOfChild(m.top, m.homeGridScreen.id)
newHomeGridScreen = CreateObject("roSGNode", "HomeGridScreen") function OnWebServerCommand()
m.top.replaceChild(newHomeGridScreen, homeIndex) if m.serverTask.command.StartsWith("play:")
m.homeGridScreen = newHomeGridScreen PlayVideo(m.serverTask.command.Mid(5))
m.homeGridScreen.id = "HomeGridScreen" end if
m.homeGridScreen.ObserveField("escape", "OnHomeGridScreenEscape")
m.homeGridScreen.SetFocus(true)
end function end function
function GetIndexOfChild(parent as object, childId as string) as integer function GetIndexOfChild(parent as object, childId as string) as integer
@@ -89,3 +100,17 @@ function GetIndexOfChild(parent as object, childId as string) as integer
end for end for
return -1 return -1
end function end function
function LaunchArgumentsReceived()
? "LaunchArgumentsReceived" m.top.launchArgs
if m.top.launchArgs <> invalid and m.top.launchArgs.contentId <> invalid
PlayVideo(m.top.launchArgs.contentId, m.homeGridScreen)
end if
end function
function InputArgumentsReceived()
? "InputArgumentsReceived" m.top.inputArgs
if m.top.inputArgs <> invalid and m.top.inputArgs.contentId <> invalid
PlayVideo(m.top.inputArgs.contentId)
end if
end function
+6
View File
@@ -1,11 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<component name="MainScene" extends="Scene"> <component name="MainScene" extends="Scene">
<interface>
<field id="exitChannel" type="bool" alwaysNotify="true" />
<field id="launchArgs" type="assocarray" onChange="LaunchArgumentsReceived" />
<field id="inputArgs" type="assocarray" onChange="InputArgumentsReceived" />
</interface>
<children> <children>
<SearchScreen id="SearchScreen" visible="false" /> <SearchScreen id="SearchScreen" visible="false" />
<HomeGridScreen id="HomeGridScreen" /> <HomeGridScreen id="HomeGridScreen" />
<SettingsScreen id="SettingsScreen" visible="false" /> <SettingsScreen id="SettingsScreen" visible="false" />
<NavBar id="NavBar" /> <NavBar id="NavBar" />
<VideoContainer id="VideoContainer" />
<LoadingIndicator id="LoadingIndicator" /> <LoadingIndicator id="LoadingIndicator" />
</children> </children>
</component> </component>
+21 -2
View File
@@ -1,3 +1,5 @@
import "pkg:/components/VideoPlayer/Video.bs"
function Init() function Init()
m.buttonGroup = m.top.findNode("NavBarButtonGroup") m.buttonGroup = m.top.findNode("NavBarButtonGroup")
m.top.observeField("focusIndex", "OnFocusIndexChange") m.top.observeField("focusIndex", "OnFocusIndexChange")
@@ -7,6 +9,11 @@ function onKeyEvent(key as string, press as boolean) as boolean
if not press if not press
return false return false
end if end if
if key = "options"
if ToggleVideoPictureInPicture(m.top)
return true
end if
end if
if key = "down" if key = "down"
i = m.top.focusIndex i = m.top.focusIndex
target = i + 1 target = i + 1
@@ -24,18 +31,30 @@ function onKeyEvent(key as string, press as boolean) as boolean
m.top.focusIndex = target m.top.focusIndex = target
return true return true
else if key = "right" else if key = "right"
' Can only escape to home screen, at index 1 ' Can only escape to search screen or home screen
allowedEscapes = { "1": true } allowedEscapes = { "0": true, "1": true }
if allowedEscapes[StrI(m.top.focusIndex).Trim()] = true if allowedEscapes[StrI(m.top.focusIndex).Trim()] = true
m.top.escapeIndex = m.top.focusIndex m.top.escapeIndex = m.top.focusIndex
m.top.focusIndex = -1 m.top.focusIndex = -1
return true return true
end if end if
else if key = "back"
dialog = ShowDialogButtons("Do you want to exit Playlet?", "Exit", ["Exit", "Cancel"])
dialog.observeField("buttonSelected", "OnExitDialog", ["buttonSelected"])
return true
end if end if
return false return false
end function end function
function OnExitDialog(event as object)
buttonIndex = event.GetData()
if buttonIndex = 0 ' Exit
? "EXITING APP"
m.top.GetScene().exitChannel = true
end if
end function
function OnFocusIndexChange() function OnFocusIndexChange()
focusIndex = m.top.focusIndex focusIndex = m.top.focusIndex
childCount = m.buttonGroup.getChildCount() childCount = m.buttonGroup.getChildCount()
+3 -3
View File
@@ -18,7 +18,7 @@
<IconButton <IconButton
id="searchButton" id="searchButton"
background="#242424" background="#242424"
focusBackground="#E5252B" focusBackground="#ff1c30"
padding="20" padding="20"
icon="pkg:/images/icons/search.png" icon="pkg:/images/icons/search.png"
text="Search" text="Search"
@@ -27,7 +27,7 @@
<IconButton <IconButton
id="homeButton" id="homeButton"
background="#242424" background="#242424"
focusBackground="#E5252B" focusBackground="#ff1c30"
padding="20" padding="20"
icon="pkg:/images/icons/home.png" icon="pkg:/images/icons/home.png"
text="Home" text="Home"
@@ -36,7 +36,7 @@
<IconButton <IconButton
id="settingsButton" id="settingsButton"
background="#242424" background="#242424"
focusBackground="#E5252B" focusBackground="#ff1c30"
padding="20" padding="20"
icon="pkg:/images/icons/settings.png" icon="pkg:/images/icons/settings.png"
text="Settings" text="Settings"
@@ -0,0 +1,41 @@
function SaveSearchHistory(q as string, maxItems = 10 as integer)
history = RegistryUtils.Read("search_history")
if history <> invalid
history = ParseJson(history)
else
history = []
end if
index = ArrayIndexOf(history, q)
if index <> -1
history.Delete(index)
end if
history.Unshift(q)
if history.Count() > maxItems
history.Pop()
end if
history = FormatJson(history)
RegistryUtils.Write("search_history", history)
end function
function GetSavedSearchHistory(q as string) as object
history = RegistryUtils.Read("search_history")
if history = invalid
return []
end if
history = ParseJson(history)
if q = ""
return history
end if
result = []
for each keyword in history
if keyword.InStr(q) = 0
result.push(keyword)
end if
end for
return result
end function
+213
View File
@@ -0,0 +1,213 @@
import "pkg:/source/roku_modules/rokupromise/Promise.brs"
import "pkg:/components/VideoPlayer/Video.bs"
import "pkg:/components/SearchScreen/SearchHistory.bs"
function Init()
m.container = m.top.FindNode("container")
m.scrollAnimation = m.top.FindNode("scrollAnimation")
m.scrollAnimationInterpolator = m.top.FindNode("scrollAnimationInterpolator")
m.keyboard = m.top.FindNode("keyboard")
m.suggestions = m.top.FindNode("suggestions")
m.rowList = m.top.FindNode("rowList")
m.keyboard.ObserveField("text", "OnTextChange")
m.suggestions.ObserveField("buttonSelected", "OnSearchButtonSelected")
m.suggestions.ObserveField("buttonFocused", "OnSearchButtonFocused")
m.rowList.ObserveField("rowItemSelected", "OnSearchVideoSelected")
m.top.ObserveField("focus", "OnFocusChange")
m.top.ObserveField("visible", "OnVisibilityChange")
' Trigger suggestions
OnTextChange()
end function
function OnFocusChange() as void
if m.top.focus = true
if m.rowlist.content <> invalid
m.rowlist.SetFocus(true)
ScrollDown()
return
end if
if m.suggestions.buttons.Count() > 0
if m.suggestions.buttonFocused >= m.suggestions.buttons.Count()
m.suggestions.focusButton = 0
end if
m.suggestions.SetFocus(true)
return
end if
m.keyboard.SetFocus(true)
end if
end function
function OnTextChange() as void
if IsNodeFocused("suggestions")
return
end if
text = m.keyboard.text
createTaskPromise("SearchSuggestionsTask", {
input: {
q: text
}
}).then(function(task as object) as void
' In case this is an old request, discard suggestions
if task.output.q <> m.keyboard.text
return
end if
q = task.output.q
suggestions = task.output.response
if suggestions <> invalid
if q.len() > 0 and ArrayIndexOf(suggestions, q) = -1
suggestions.Unshift(q)
end if
' Capture current focused button and restore it after resetting the buttons
buttonFocused = -1
if IsNodeFocused("suggestions")
buttonFocused = m.suggestions.buttonFocused
end if
if buttonFocused >= m.suggestions.buttons.Count()
buttonFocused = m.suggestions.buttons.Count() - 1
end if
m.suggestions.buttons = suggestions
if buttonFocused <> -1
m.suggestions.focusButton = buttonFocused
end if
end if
end function)
end function
function OnSearchButtonSelected()
selected = m.suggestions.buttonSelected
text = m.suggestions.buttons[selected]
Search(text)
end function
function OnSearchButtonFocused() as void
if not IsNodeFocused("suggestions")
return
end if
selected = m.suggestions.buttonFocused
text = m.suggestions.buttons[selected]
m.keyboard.text = text
end function
function Search(text as string)
SaveSearchHistory(text)
createTaskPromise("SearchTask", {
input: {
q: text
}
}).then(function(task as object) as void
rootChildren = task.output.rootChildren
contentNode = CreateObject("roSGNode", "ContentNode")
contentNode.Update({
children: rootChildren
}, true)
m.rowList.content = contentNode
m.rowList.SetFocus(true)
m.rowList.jumpToRowItem = [0, 0]
ScrollDown()
end function)
end function
function OnVisibilityChange()
if m.top.visible = false
ClearSearch()
end if
end function
function ClearSearch()
m.keyboard.text = ""
m.rowlist.content = invalid
ScrollUp()
end function
function IsNodeFocused(id as string) as boolean
return m.top.focusedChild?.id = id or m.container.focusedChild?.id = id
end function
function ScrollUp() as void
destination = m.scrollAnimationInterpolator.keyValue[0][1]
current = m.container.translation[1]
if current = destination
return
end if
m.scrollAnimationInterpolator.reverse = true
m.scrollAnimation.control = "start"
end function
function ScrollDown() as void
destination = m.scrollAnimationInterpolator.keyValue[2][1]
current = m.container.translation[1]
if current = destination
return
end if
m.scrollAnimationInterpolator.reverse = false
m.scrollAnimation.control = "start"
end function
function OnSearchVideoSelected(event as object)
grid = event.GetRoSGNode()
selectedPair = event.GetData()
selectedRow = selectedPair[0]
selectedRowItem = selectedPair[1]
rowContent = grid.content.GetChild(selectedRow)
itemContent = rowContent.GetChild(selectedRowItem)
videoId = itemContent.videoId
PlayVideo(videoId, m.top)
end function
function OnkeyEvent(key as string, press as boolean) as boolean
if press = false
return false
end if
if key = "options"
if ToggleVideoPictureInPicture(m.top)
return true
end if
end if
if key = "back"
ScrollUp()
m.top.escape = key
return true
end if
if key = "left"
if IsNodeFocused("keyboard") and m.suggestions.buttons.Count() > 0
m.suggestions.SetFocus(true)
return true
end if
ScrollUp()
m.top.escape = key
return true
end if
if key = "right"
if IsNodeFocused("suggestions")
m.keyboard.SetFocus(true)
return true
end if
return false
end if
if key = "down"
if m.rowlist.content <> invalid
ScrollDown()
m.rowlist.SetFocus(true)
return true
end if
return false
end if
if key = "up"
if IsNodeFocused("rowList")
ScrollUp()
m.suggestions.SetFocus(true)
return true
end if
return false
end if
return false
end function
+41 -9
View File
@@ -1,15 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<component name="SearchScreen" extends="Group"> <component name="SearchScreen" extends="Group">
<interface>
<field id="escape" type="string" alwaysNotify="true" />
<field id="focus" type="boolean" alwaysNotify="true" />
</interface>
<children> <children>
<Label <Group id="container">
text="Search feature coming soon..." <MiniKeyboard
width="1280" id="keyboard"
height="720" translation="[670,110]"
translation="[0, 0]" />
horizAlign="center" <ButtonGroup
vertAlign="center" id="suggestions"
font="font:MediumBoldSystemFont" maxWidth="450"
/> buttonHeight="50"
translation="[160,100]"
/>
<RowList
itemComponentName="VideoRowCell"
id="rowList"
translation="[0,620]"
numRows="1"
rowitemSize="[[350,196]]"
rowItemSpacing="[[25,0]]"
itemSize="[1280,326]"
itemSpacing="[0,65]"
rowLabelOffset="[[95,20]]"
focusXOffset="[95]"
showRowLabel="[true]"
rowFocusAnimationStyle="floatingfocus"
focusBitmapUri="pkg:/images/focus_grid.9.png"
/>
<Animation
id="scrollAnimation"
duration="0.3">
<Vector2DFieldInterpolator
id="scrollAnimationInterpolator"
key="[ 0.0, 0.5, 1.0 ]"
keyValue="[ [0.0,0.0], [0.0,-160.0], [0.0,-320.0]]"
fieldToInterp="container.translation" />
</Animation>
</Group>
</children> </children>
</component> </component>
@@ -0,0 +1,34 @@
import "pkg:/source/services/Invidious.bs"
import "pkg:/components/SearchScreen/SearchHistory.bs"
function Init()
m.top.functionName = "TaskMain"
end function
function TaskMain()
input = m.top.getField("input")
q = input.q
searchSuggestsions = q <> "" ? Invidious.SearchSuggestions(q) : invalid
history = GetSavedSearchHistory(q)
if searchSuggestsions <> invalid
history = MergeSearchSuggestions(history, searchSuggestsions.suggestions)
end if
m.top.setField("output", {
q: q,
response: history
})
end function
function MergeSearchSuggestions(history as object, queryResults as object, maxItems = 10 as integer) as object
if queryResults = invalid
return history
end if
while history.Count() < maxItems and queryResults.Count() > 0
history.push(queryResults.shift())
end while
return history
end function
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="SearchSuggestionsTask" extends="Task">
<interface>
<field id="input" type="assocarray" />
<field id="output" type="assocarray" />
</interface>
</component>
+49
View File
@@ -0,0 +1,49 @@
import "pkg:/source/services/Invidious.bs"
function Init()
m.top.functionName = "TaskMain"
end function
function TaskMain()
input = m.top.getField("input")
q = input.q
rootChildren = []
response = Invidious.Search(q, { type: "video" })
rowContent = GetCategoryContent(`Search - ${q}`, response)
if rowContent <> invalid
rootChildren.Push(rowContent)
end if
m.top.setField("output", {
q: q,
rootChildren: rootChildren
})
end function
function GetCategoryContent(category as string, json as object) as object
if json <> invalid and json.Count() > 0
row = {}
row.title = category
row.children = []
for each item in json ' parse items and push them to row
itemData = GetItemData(item)
if itemData <> invalid
row.children.Push(itemData)
end if
end for
return row
end if
return invalid
end function
function GetItemData(video as object) as object
' TODO: handle playlists and channels
if video.videoId = invalid
return invalid
end if
return video
end function
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="SearchTask" extends="Task">
<interface>
<field id="input" type="assocarray" />
<field id="output" type="assocarray" />
</interface>
</component>
@@ -0,0 +1,25 @@
import "pkg:/source/utils/General.bs"
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
function Init()
m.top.functionName = "TaskMain"
end function
function TaskMain()
latest = "N/A"
response = Requests().request("HEAD", "https://github.com/iBicha/playlet/releases/latest", invalid)
if response.statusCode = 200
if response.headers.location <> invalid
regex = CreateObject("roRegex", "/v?(\d+\.\d+\.\d+)", "")
match = regex.match(response.headers.location)
if match.Count() = 2
latest = match[1]
end if
end if
end if
m.top.setField("output", {
latest: latest
})
end function
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="AppVersionTask" extends="Task">
<interface>
<field id="input" type="assocarray" />
<field id="output" type="assocarray" />
</interface>
</component>
@@ -1,7 +1,13 @@
import "pkg:/source/utils/General.bs" import "pkg:/source/utils/General.bs"
import "pkg:/source/roku_modules/rokupromise/Promise.brs"
function Init() function Init()
m.top.url = `http:/${GetLocalIpAddress()}:8888/index.html?tab=settings` m.versionLabel = m.top.findNode("VersionLabel")
m.top.url = `http://${GetLocalIpAddress()}:8888`
appInfo = GetAppInfo()
m.currentVersion = appInfo.version
SetVersionLabel(m.currentVersion, "N/A")
GetLatestVersion()
end function end function
function OnUrlSet() function OnUrlSet()
@@ -13,3 +19,17 @@ function OnUrlSet()
urlLabel = m.top.findNode("urlLabel") urlLabel = m.top.findNode("urlLabel")
urlLabel.text = url urlLabel.text = url
end function end function
function GetLatestVersion()
createTaskPromise("AppVersionTask", {
input: {}
}).then(function(task as object) as void
if task.output.latest <> invalid
SetVersionLabel(m.currentVersion, task.output.latest)
end if
end function)
end function
function SetVersionLabel(current as string, latest as string)
m.versionLabel.text = `Version: ${current} | Latest: ${latest}`
end function
@@ -5,12 +5,20 @@
<field id="url" type="string" onChange="OnUrlSet" /> <field id="url" type="string" onChange="OnUrlSet" />
</interface> </interface>
<children> <children>
<Label
id='VersionLabel'
height='50'
width='1280'
font='font:MediumBoldSystemFont'
horizAlign="center"
translation="[0,100]"
/>
<QRPoster <QRPoster
id='SettingsQRPoster' id='SettingsQRPoster'
loadWidth='500' loadWidth='400'
loadHeight='500' loadHeight='400'
loadPadding='20' loadPadding='20'
translation='[395, 60]' /> translation='[440, 160]' />
<Label <Label
id='UrlLabel' id='UrlLabel'
@@ -1,18 +1,20 @@
import "pkg:/source/services/SponsorBlock.bs" import "pkg:/source/services/SponsorBlock.bs"
function Init()
m.top.functionName = "TaskMain"
end function
function TaskMain() function TaskMain()
input = m.top.getField("input") input = m.top.getField("input")
videoId = input.videoId videoId = input.videoId
skipSegments = SponsorBlock.GetSkipSegmentsForVideo(videoId) skipSegments = SponsorBlock.GetSkipSegmentsForVideo(videoId)
barPath = invalid
if skipSegments <> invalid
barPath = `tmp:/sponsorblock_bar_${videoId}.png`
SponsorBlock.GenerateProgressBarBackground(skipSegments, barPath)
end if
m.top.setField("output", { m.top.setField("output", {
videoId: videoId, videoId: videoId,
skipSegments: skipSegments skipSegments: skipSegments,
barPath: barPath
}) })
end function end function
+45 -182
View File
@@ -1,197 +1,60 @@
import "pkg:/source/services/Invidious.bs" import "pkg:/source/services/Invidious.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/source/roku_modules/rokupromise/Promise.brs"
function ShowVideoScreenEmbedded(videoId as string, thumbnailNode as object) function PlayVideo(videoId as string, sender = invalid as object)
m.videoPlayer = CreateObject("roSGNode", "VideoPlayer") CloseVideo(false)
AddVideoFields() videoContainer = GetVideoContainer()
m.videoPlayer.embedded = true if sender <> invalid
videoContainer.sender = sender
m.videoPlayer.enableUI = false
m.videoPlayer.width = thumbnailNode.width
m.videoPlayer.height = thumbnailNode.height
thumbnailNode.AppendChild(m.videoPlayer)
ShowVideoScreen(videoId)
end function
function ShowVideoScreenFull(videoId as string)
m.videoPlayer = CreateObject("roSGNode", "VideoPlayer")
AddVideoFields()
m.videoPlayer.embedded = false
' TODO: make sure video is at right node
m.top.getParent().AppendChild(m.videoPlayer)
ShowVideoScreen(videoId)
end function
function AddVideoFields()
m.videoPlayer.addFields({
embedded: false,
sponsorBlockTask: false,
videoPlayingSuccess: false,
ignoreNextFinishedState: false
})
end function
function ExpandVideoScreenFull()
m.videoPlayer.embedded = true
m.videoPlayer.reparent(m.top, false)
m.videoPlayer.enableUI = true
m.videoPlayer.width = 1280
m.videoPlayer.height = 720
m.videoPlayer.SetFocus(true)
StartSponsorBlockTask(m.videoPlayer.videoId)
end function
function ShowVideoScreen(videoId as string)
m.videoPlayer.addFields({ videoId: videoId })
m.videoPlayer.trickPlayBar.filledBarBlendColor = "0xFF0000FF"
m.videoPlayer.bufferingBar.filledBarBlendColor = "0xFF0000FF"
m.videoPlayer.retrievingBar.filledBarBlendColor = "0xFF0000FF"
if not m.videoPlayer.embedded
m.videoPlayer.visible = true
m.videoPlayer.SetFocus(true)
else
m.videoPlayer.visible = false
end if end if
videoContainer.videoPlayer = videoContainer.createChild("VideoPlayer")
m.videoPlayer.ObserveField("state", "OnVideoPlayerStateChange") videoContainer.videoPlayer.videoId = videoId
if videoContainer.fullscreen
StartVideoDetailsTask(videoId) videoContainer.videoPlayer.SetFocus(true)
if not m.videoPlayer.embedded
StartSponsorBlockTask(videoId)
end if end if
end function end function
function OnVideoPlayerStateChange() as void function CloseVideo(setFocus = true as boolean)
state = m.videoPlayer.state videoContainer = GetVideoContainer()
if videoContainer.videoPlayer <> invalid
' If we successfully played the video, then any error that comes later is not due to rate limiting. videoContainer.videoPlayer.control = "stop"
' This is to reduce false positives, as we do not want retry another link if the first link is working fine. videoContainer.RemoveChild(videoContainer.videoPlayer)
if state = "playing" videoContainer.videoPlayer = invalid
m.videoPlayer.videoPlayingSuccess = true
if m.videoPlayer.visible = false and m.videoPlayer.embedded = true
m.videoPlayer.visible = true
end if
end if end if
if setFocus and videoContainer.sender <> invalid
if state = "error" if videoContainer.sender.hasField("focus")
' A hack to see if we could use the proxy here videoContainer.sender.focus = true
if m.videoPlayingSuccess <> true
errorInfo = m.videoPlayer.errorInfo
if errorInfo.category = "http"
videoId = m.videoPlayer.videoId
itag = m.videoPlayer.content.itag
url = m.videoPlayer.content.url
if url.InStr("local=true") = -1
print(`Video ${url} failed to play. Trying a proxy (local=true)`)
m.videoPlayer.content.url = Invidious.GetVideoUrl(videoId, itag, true)
' This video errored, and is about to finish, so don't close the video yet
' TODO: perhaps creating a second player is better?
m.videoPlayer.ignoreNextFinishedState = true
m.videoPlayer.control = "play"
return
end if
end if
end if
end if
if state = "finished" and m.videoPlayer.ignoreNextFinishedState = true
m.videoPlayer.ignoreNextFinishedState = false
return
end if
if state = "error" or state = "finished"
CloseVideoPlayer()
end if
end function
function CloseVideoPlayer()
m.videoPlayer.control = "stop"
m.videoPlayer.visible = false
m.videoPlayer.getParent().RemoveChild(m.videoPlayer)
m.videoPlayer = invalid
m.top.focus = true
end function
function StartVideoDetailsTask(videoId as string)
createTaskPromise("VideoDetailsTask", {
input: {
videoId: videoId
}
}).then(function(task as object)
videoId = task.output.videoId
metadata = task.output.metadata
if metadata <> invalid
stream = metadata.formatStreams[metadata.formatStreams.Count() - 1]
contentNode = CreateObject("roSGNode", "ContentNode")
contentNode.addFields({ videoId: videoId, itag: stream.itag })
contentNode.url = stream.url
SetCaptions(metadata, m.videoPlayer, contentNode)
m.videoPlayer.content = contentNode
m.videoPlayer.control = "play"
else else
print "FAILED TO LOAD VIDEO " + videoId videoContainer.sender.SetFocus(true)
CloseVideoPlayer()
end if end if
end function)
end function
function StartSponsorBlockTask(videoId as string)
m.videoPlayer.sponsorBlockTask = true
createTaskPromise("SponsorBlockTask", {
input: {
videoId: videoId
}
}).then(function(task as object)
skipSegments = task.output.skipSegments
if skipSegments <> invalid
m.videoPlayer.addFields({ skipSegments: skipSegments })
m.videoPlayer.seekMode = "accurate"
m.videoPlayer.ObserveField("position", "OnPositionChangeSkipSponsorBlockSections")
end if
end function)
end function
function SetCaptions(metadata as object, videoPlayer as object, contentNode as object) as void
' TODO: check if we have caption settings ON
' TODO: read favorate language from system settings
' TODO: populate list of caption tracks
if metadata.captions.Count() = 0
return
end if end if
videoPlayer.globalCaptionMode = "ON"
contentNode.ClosedCaptions = True
selectedCaption = metadata.captions[0]
' Use favorite caption langauage, or the first one
for each caption in metadata.captions
if caption.language_code = "en"
selectedCaption = caption
exit for
end if
end for
contentNode.SubtitleConfig = {
ShowSubtitle: 1,
TrackName: Invidious.GetCurrentHost() + selectedCaption.url
}
end function end function
function OnPositionChangeSkipSponsorBlockSections() as void function ToggleVideoPictureInPicture(sender = invalid as object) as boolean
segments = m.videoPlayer.skipSegments videoContainer = GetVideoContainer()
for each segment in segments if videoContainer.videoPlayer = invalid
if segment["actionType"] = "skip" return false
segmentRange = segment["segment"] end if
segmentStart = segmentRange[0] videoContainer.fullscreen = not videoContainer.fullscreen
segmentEnd = segmentRange[1] if sender <> invalid
currentPosition = m.videoPlayer.position videoContainer.sender = sender
if (segmentStart < currentPosition) and ((segmentEnd - 1) > currentPosition) end if
' TODO: if segmentEnd is at the end of the video, close video if videoContainer.fullscreen
m.videoPlayer.seek = segmentEnd videoContainer.videoPlayer.SetFocus(true)
print("Skiping section:" + segment["category"]) else
return if videoContainer.sender <> invalid
if videoContainer.sender.hasField("focus")
videoContainer.sender.focus = true
else
videoContainer.sender.SetFocus(true)
end if end if
end if end if
end for videoContainer.sender = invalid
end if
return true
end function
function GetVideoContainer() as object
return m.global.videoContainer
end function end function
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="VideoContainer" extends="Group">
<interface>
<field id="videoPlayer" type="node" />
<field id="sender" type="node" />
<field id="fullscreen" type="boolean" value="true" />
</interface>
</component>
+227 -6
View File
@@ -1,10 +1,49 @@
import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/source/services/SponsorBlock.bs"
import "pkg:/components/VideoPlayer/Video.bs"
function Init() function Init()
SetupSponsorBlock()
m.videoDetailsTask = m.top.findNode("VideoDetailsTask")
' busySpinner is our spinner, shown when loading the video details (like links, title, etc)
m.busySpinner = m.top.findNode("BusySpinner")
' Once the Content is ready, the rokuBusySpinner shows up, which is loading the video feed
m.rokuBusySpinner = FindChildNodeOfType(m.top, "BusySpinner")
' The label that shows the buffering percentage
m.rokuBusySpinnerLabel = FindChildNodeOfType(m.rokuBusySpinner, "Label")
SetupBusySpinner()
m.busySpinner.visible = true
m.busySpinner.control = "start"
m.videoPlayingSuccess = false
m.ignoreNextFinishedState = false
m.top.trickPlayBar.filledBarBlendColor = "0xFF0000FF"
m.top.bufferingBar.filledBarBlendColor = "0xFF0000FF"
m.top.retrievingBar.filledBarBlendColor = "0xFF0000FF"
m.top.observeField("control", "OnControlChange")
m.top.observeField("videoId", "StartVideoDetailsTask")
m.videoContainer = GetVideoContainer()
m.videoContainer.observeFieldScoped("fullscreen", "OnFullScreenChange")
OnFullScreenChange()
m.top.ObserveField("state", "OnVideoPlayerStateChange")
end function end function
function OnkeyEvent(key as string, press as boolean) as boolean function OnkeyEvent(key as string, press as boolean) as boolean
if press = false if press = false
return false return false
end if end if
' Unfortunately, a Video node cannot capture the "options" key (because, Roku...)
' https://community.roku.com/t5/Roku-Developer-Program/Bug-in-10-0-1-Options-key-is-not-being-consumed-by-onKeyEvent-when-Video-node-is-in-focus/m-p/709200/highlight/true#M49312
' Because of that, the button "down" is used to shrink the video for picture in picture mode
if key = "down"
if ToggleVideoPictureInPicture()
return true
end if
end if
if key = "back" if key = "back"
CloseVideo() CloseVideo()
return true return true
@@ -12,10 +51,192 @@ function OnkeyEvent(key as string, press as boolean) as boolean
return false return false
end function end function
function CloseVideo() function OnControlChange()
homeGridScreen = m.top.getParent().findNode("HomeGridScreen") if m.top.control = "stop"
m.top.control = "stop" m.sponsorBlockTask.control = "stop"
m.top.visible = false m.videoDetailsTask.control = "stop"
m.top.getParent().removeChild(m.videoPlayer) end if
homeGridScreen.focus = true end function
function StartVideoDetailsTask()
m.videoDetailsTask.input = { videoId: m.top.videoId }
m.videoDetailsTask.observeField("output", "OnVideoDetailsTaskResults")
m.videoDetailsTask.control = "run"
end function
function OnVideoDetailsTaskResults() as void
task = m.videoDetailsTask
videoId = task.output.videoId
metadata = task.output.metadata
if videoId <> m.top.videoId
return
end if
if metadata = invalid
m.busySpinner.visible = false
m.busySpinner.control = "stop"
ShowDialog(`Failed to load video information for ${videoId}`, "Video load fail")
CloseVideo()
end if
contentNode = CreateObject("roSGNode", "ContentNode")
contentNode.addFields({ metadata: metadata })
if metadata.hlsUrl <> invalid
contentNode.url = metadata.hlsUrl
else if metadata.dashUrl <> invalid
#if DASH_THUMBNAILS
' Redirect to our server so we can inject thumbnails (storyboards) into the DASH manifest
contentNode.url = `http://${GetLocalIpAddress()}:8888/dash?v=${videoId}`
#else
contentNode.url = metadata.dashUrl
#end if
else
stream = metadata.formatStreams[metadata.formatStreams.Count() - 1]
itag = stream.itag
' Use an url relative to the host, so we can proxy(local=true) in case it fails
contentNode.url = Invidious.GetVideoUrl(videoId, itag, false)
end if
contentNode.title = metadata.title
contentNode.secondaryTitle = metadata.author
SetCaptions(metadata, m.top, contentNode)
m.busySpinner.visible = false
m.busySpinner.control = "stop"
m.top.content = contentNode
m.top.control = "play"
end function
function FindChildNodeOfType(node as object, nodeType as string) as object
if node.subtype() = nodeType
return node
end if
childCount = node.getChildCount()
children = node.getChildren(childCount, 0)
for i = 0 to childCount - 1
child = FindChildNodeOfType(children[i], nodeType)
if child <> invalid
return child
end if
end for
return invalid
end function
function SetupBusySpinner()
m.rokuBusySpinner.poster.width = 150
m.rokuBusySpinner.poster.height = 150
m.rokuBusySpinner.poster.uri = "pkg:/images/spinner.png"
m.rokuBusySpinner.observeField("translation", "OnRokuSpinnerMoved")
m.rokuBusySpinnerLabel.width = 150
m.rokuBusySpinnerLabel.height = 150
m.rokuBusySpinnerLabel.translation = [0, 0]
m.rokuBusySpinnerLabel.observeField("translation", "OnRokuSpinnerLabelMoved")
m.busySpinner.poster.width = 150
m.busySpinner.poster.height = 150
m.busySpinner.poster.uri = "pkg:/images/spinner.png"
end function
function OnRokuSpinnerMoved()
currentTranslation = m.rokuBusySpinner.translation
parentRect = m.top.boundingRect()
centerx = (parentRect.width - m.rokuBusySpinner.poster.width) / 2
centery = (parentRect.height - m.rokuBusySpinner.poster.height) / 2
if currentTranslation[0] <> centerx or currentTranslation[1] <> centery
m.rokuBusySpinner.translation = [centerx, centery]
end if
end function
function OnRokuSpinnerLabelMoved()
currentTranslation = m.rokuBusySpinnerLabel.translation
if currentTranslation[0] <> 0 or currentTranslation[1] <> 0
m.rokuBusySpinnerLabel.translation = [0, 0]
end if
end function
function OnVideoPlayerStateChange() as void
state = m.top.state
' If we successfully played the video, then any error that comes later is not due to a 403 (FORBIDDEN).
' This is to reduce false positives, as we do not want retry another link if the first link is working fine.
if state = "playing"
m.videoPlayingSuccess = true
end if
if state = "error"
' A hack to see if we could use the proxy here
if m.videoPlayingSuccess <> true
errorInfo = m.top.errorInfo
' http for stream format, mediaerror for DASH
if errorInfo.category = "http" or errorInfo.category = "mediaerror"
url = m.top.content.url
if url.InStr("local=true") = -1
print(`Video ${url} failed to play. Trying a proxy (local=true)`)
if url.InStr("?") = -1
url += "?local=true"
else
url += "&local=true"
end if
m.top.content.url = url
' This video errored, and is about to finish, so don't close the video yet
' TODO: perhaps creating a second player is better?
m.ignoreNextFinishedState = true
m.top.control = "play"
return
end if
end if
end if
end if
if state = "finished" and m.ignoreNextFinishedState = true
m.ignoreNextFinishedState = false
return
end if
if state = "finished"
CloseVideo()
end if
if state = "error"
errorInfo = m.top.errorInfo
messageLines = [`VideoId: ${m.top.videoId}`]
for each info in errorInfo
messageLines.push(`${info}: ${errorInfo[info]}`)
end for
ShowDialog(messageLines, "Error playing video")
CloseVideo()
end if
end function
function OnFullScreenChange()
margin = 20
width = 1280
height = 720
if m.videoContainer.fullscreen
m.top.translation = [0, 0]
m.top.width = width
m.top.height = height
else
small_width = width / 3
small_height = height / 3
x = width - small_width - margin
y = height - small_height - margin
m.top.translation = [x, y]
m.top.width = small_width
m.top.height = small_height
end if
m.top.enableUI = m.videoContainer.fullscreen
PositionSpinner()
end function
function PositionSpinner()
centerx = (m.top.width - m.busySpinner.poster.width) / 2
centery = (m.top.height - m.busySpinner.poster.height) / 2
m.busySpinner.translation = [centerx, centery]
end function end function
@@ -1,4 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<component name="VideoPlayer" extends="Video"> <component name="VideoPlayer" extends="Video">
<script type="text/brightscript" uri="VideoPlayerSponsorBlock.bs" />
<script type="text/brightscript" uri="VideoPlayerCaptions.bs" />
<interface>
<field id="chapter" type="string" alias="chapterLabel.text" />
<field id="videoId" type="string" />
</interface>
<children>
<SponsorBlockTask
functionName="TaskMain"
id="SponsorBlockTask" />
<VideoDetailsTask
functionName="TaskMain"
id="VideoDetailsTask" />
<Label
id="chapterLabel"
width="350"
height="25"
horizAlign="center"
vertAlign="center"
font="font:SmallestSystemFont"
/>
<Timer
id="chapterLabelTimer"
repeat="true"
duration="0.25"
/>
<BusySpinner
id="busySpinner"
spinInterval="1" />
</children>
</component> </component>
@@ -0,0 +1,24 @@
function SetCaptions(metadata as object, videoPlayer as object, contentNode as object) as void
' TODO: check if we have caption settings ON
' TODO: read favorate language from system settings
' TODO: populate list of caption tracks
if metadata.captions.Count() = 0
return
end if
videoPlayer.globalCaptionMode = "ON"
contentNode.ClosedCaptions = True
selectedCaption = metadata.captions[0]
' Use favorite caption langauage, or the first one
for each caption in metadata.captions
if caption.language_code = "en"
selectedCaption = caption
exit for
end if
end for
contentNode.SubtitleConfig = {
ShowSubtitle: 1,
TrackName: InvidiousSettings.GetSelectedInstance() + selectedCaption.url
}
end function
@@ -0,0 +1,143 @@
function SetupSponsorBlock()
PositionChapterLabel()
m.timeLabel = FindTimeLabel()
m.top.trickPlayBar.observeField("visible", "OnTrickPlayBarVisible")
m.chapterLabelTimer = m.top.findNode("chapterLabelTimer")
m.chapterLabelTimer.observeField("fire", "OnChapterLabelTimer")
m.sponsorBlockTask = m.top.findNode("SponsorBlockTask")
m.top.observeField("videoId", "StartSponsorBlockTask")
end function
function PositionChapterLabel()
m.chapterLabel = m.top.findNode("chapterLabel")
m.chapterLabel.reparent(m.top.trickPlayBar, false)
trickPlayBarWidth = m.top.trickPlayBar.boundingRect().width
#if DASH_THUMBNAILS
yPos = 25
#else
yPos = 55
#end if
m.chapterLabel.translation = [trickPlayBarWidth / 2 - m.chapterLabel.width / 2, yPos]
end function
' This is a hack to access the position of the trickplay
function FindTimeLabel() as object
children = m.top.trickPlayBar.getChildren(m.top.trickPlayBar.getChildCount(), 0)
label = invalid
for each child in children
' It's very unfortunate to have to find a label with 0:00 text,
' and that's on the left side of the screen. This might need completely custom trickPlayBar
if child.isSubtype("Label") and child.text = "0:00"
if label = invalid
label = child
else
if child.translation[0] < label.translation[0]
label = child
end if
end if
end if
end for
return label
end function
function OnTrickPlayBarVisible()
if m.top.trickPlayBar.visible
m.top.chapter = ""
m.chapterLabelTimer.control = "start"
else
m.chapterLabelTimer.control = "stop"
end if
end function
function OnChapterLabelTimer() as void
if m.timeLabel = invalid or m.skipSegments = invalid
return
end if
if m.sponsorBlockLastTime = m.timeLabel.text
return
end if
m.sponsorBlockLastTime = m.timeLabel.text
time = TimeUtils.ParseTime(m.timeLabel.text)
UpdateSponsorBlockChapter(time)
end function
function UpdateSponsorBlockChapter(time as integer) as void
segments = m.skipSegments
for each segment in segments
segmentRange = segment["segment"]
segmentStart = segmentRange[0]
segmentEnd = segmentRange[1]
if (segmentStart <= time) and (segmentEnd >= time)
m.top.chapter = SponsorBlock.SegmentTitle(segment["category"])
return
end if
end for
m.top.chapter = ""
end function
function StartSponsorBlockTask()
m.sponsorBlockTask.input = { videoId: m.top.videoId }
m.sponsorBlockTask.observeField("output", "OnSponsorBlockTaskResults")
m.sponsorBlockTask.control = "run"
end function
function OnSponsorBlockTaskResults()
task = m.sponsorBlockTask
skipSegments = task.output.skipSegments
barPath = task.output.barPath
if skipSegments <> invalid
m.skipSegments = skipSegments
m.top.seekMode = "accurate"
if barPath <> invalid
m.top.trickPlayBar.trackImageUri = barPath
m.top.trickPlayBar.filledBarBlendColor = "0xFF000080"
end if
m.top.ObserveField("position", "OnPositionChangeSkipSponsorBlockSections")
end if
end function
function OnPositionChangeSkipSponsorBlockSections() as void
shouldMute = false
muteCategory = ""
segments = m.skipSegments
if segments = invalid
return
end if
for each segment in segments
' TODO: handle other action types
if segment["actionType"] = "skip"
segmentRange = segment["segment"]
segmentStart = segmentRange[0]
segmentEnd = segmentRange[1]
currentPosition = m.top.position
if (segmentStart < currentPosition) and ((segmentEnd - 1) > currentPosition)
' TODO: if segmentEnd is at the end of the video, close video
m.top.seek = segmentEnd
print("Skiping section:" + segment["category"])
return
end if
end if
if segment["actionType"] = "mute"
segmentRange = segment["segment"]
segmentStart = segmentRange[0]
segmentEnd = segmentRange[1]
currentPosition = m.top.position
if (segmentStart < currentPosition) and (segmentEnd > currentPosition)
shouldMute = true
muteCategory = segment["category"]
exit for
end if
end if
end for
if m.top.mute <> shouldMute
print(`Muting section: ${muteCategory} - ${shouldMute}`)
m.top.mute = shouldMute
end if
end function
+36 -8
View File
@@ -7,25 +7,53 @@ function OnContentSet()
m.top.FindNode("titleLabel").text = content.title m.top.FindNode("titleLabel").text = content.title
m.top.FindNode("authorLabel").text = content.author m.top.FindNode("authorLabel").text = content.author
releaseDate = validstr(content.releaseDate) publishedText = validstr(content.publishedText)
viewCount = FormatViewCount(content.viewCount) viewCount = FormatViewCount(content.viewCount)
if releaseDate = "" and viewCount = "" if publishedText = "" and viewCount = ""
m.top.FindNode("viewCountDateLabel").text = "" m.top.FindNode("viewCountDateLabel").text = ""
else else
m.top.FindNode("viewCountDateLabel").text = `${releaseDate} • ${viewCount}` m.top.FindNode("viewCountDateLabel").text = `${publishedText} • ${viewCount}`
end if end if
thumbnail = m.top.FindNode("thumbnail") thumbnail = m.top.FindNode("thumbnail")
thumbnail.uri = content.hdPosterUrl thumbnail.uri = GetThumbnailUrl(content.videoThumbnails)
thumbnail.id = `thumbnail-${content.id}` thumbnail.id = `thumbnail-${content.videoId}`
if content.length <> invalid and content.length <> 0
m.top.FindNode("durationLabel").text = TimeUtils.GetFormattedTime(content.length) if IsVideoLive(content)
else m.top.FindNode("liveRect").visible = true
m.top.FindNode("durationRect").visible = false m.top.FindNode("durationRect").visible = false
else
m.top.FindNode("liveRect").visible = false
if content.lengthSeconds <> invalid and content.lengthSeconds <> 0
m.top.FindNode("durationLabel").text = TimeUtils.GetFormattedTime(content.lengthSeconds)
m.top.FindNode("durationRect").visible = true
else
m.top.FindNode("durationRect").visible = false
end if
end if end if
end if end if
end function end function
function GetThumbnailUrl(videoThumbnails as object, quality = "medium" as string) as string
if videoThumbnails.Count() = 0
return ""
end if
for each thumbnail in videoThumbnails
if thumbnail.quality = quality
return thumbnail.url
end if
end for
return videoThumbnails[0].url
end function
function IsVideoLive(metadata as object) as boolean
if metadata.liveNow = true
return true
end if
' TODO: metadata.liveNow is returning false for live videos...
return metadata.lengthSeconds = 0 and metadata.viewCount = 0
end function
function FormatViewCount(viewCount as dynamic) as string function FormatViewCount(viewCount as dynamic) as string
if viewCount = invalid if viewCount = invalid
return "" return ""
+17 -1
View File
@@ -29,7 +29,23 @@
horizAlign="center" horizAlign="center"
vertAlign="center" vertAlign="center"
font="font:SmallestSystemFont" font="font:SmallestSystemFont"
inheritParentOpacity="true" />
</Rectangle>
<Rectangle
id="liveRect"
width="60"
height="25"
color="0xFF0000"
translation="[290, 162]"
>
<Label
width="60"
height="25"
id="liveLabel"
horizAlign="center"
vertAlign="center"
font="font:SmallestBoldSystemFont"
text="LIVE"
/> />
</Rectangle> </Rectangle>
</Poster> </Poster>
+4 -4
View File
@@ -79,9 +79,9 @@ namespace Http
' append to connection request ' append to connection request
m.request.Add(rcvStr) m.request.Add(rcvStr)
if m.request.IsComplete() if m.request.ProcessNext(m)
server.num_requests = validint(server.num_requests) + 1 if m.request.state = Http.HttpRequestState.DONE
if m.request.Process(m) server.num_requests = validint(server.num_requests) + 1
m.response = new HttpResponse(m.request, m.server, m.settings) m.response = new HttpResponse(m.request, m.server, m.settings)
m.response.Process() m.response.Process()
m.SetState(Http.HttpConnectionState.SEND_HEADER) m.SetState(Http.HttpConnectionState.SEND_HEADER)
@@ -90,7 +90,7 @@ namespace Http
m.close = true m.close = true
m.log.error("couldn't process request or response, closing @" + m.client) m.log.error("couldn't process request or response, closing @" + m.client)
end if end if
else if m.request.buf.len() > m.settings.MaxRequestLength ' die if it's too long else if m.request.buffer.len() > m.settings.MaxRequestLength ' die if it's too long
m.response = new HttpResponse(m.request, m.server, m.settings) m.response = new HttpResponse(m.request, m.server, m.settings)
m.response.Default(413, "Your request was dropped because it was too long.") m.response.Default(413, "Your request was dropped because it was too long.")
m.SetState(Http.HttpConnectionState.SEND_HEADER) m.SetState(Http.HttpConnectionState.SEND_HEADER)
+175 -48
View File
@@ -1,3 +1,5 @@
import "pkg:/components/WebServer/HttpRequestState.bs"
namespace Http namespace Http
function GetHttpRequestId() as integer function GetHttpRequestId() as integer
@@ -8,82 +10,181 @@ namespace Http
class HttpRequest class HttpRequest
private log as log.Logger private log as log.Logger
Unix2NewLine = UnixNL() + UnixNL()
Windows2NewLine = WinNL() + WinNL()
' members ' members
private method = invalid private method = invalid
private uri = invalid private uri = invalid
private route = invalid
private query = invalid
private protocol = invalid private protocol = invalid
private buf = invalid private buffer = invalid
private fields = invalid private buffer_index = 0
private headers = invalid
private body = invalid
private state = Http.HttpRequestState.INIT
private id = 0 private id = 0
' copied members ' copied members
private range_begin = 0 private range_begin = 0
private range_end = 0 private range_end = 0
private range_begin_given = false private range_begin_given = false
private range_end_given = false private range_end_given = false
private ok = true private ready_for_response = false
function new() function new()
m.log = new log.Logger("HttpRequest") m.log = new log.Logger("HttpRequest")
m.id = Http.GetHttpRequestId() m.id = Http.GetHttpRequestId()
m.fields = CreateObject("roAssociativeArray") m.headers = CreateObject("roAssociativeArray")
end function end function
function Add(incoming as string) function Add(incoming as string)
if isstr(m.buf) if isstr(m.buffer)
m.buf = m.buf + incoming m.buffer = m.buffer + incoming
else else
m.buf = incoming m.buffer = incoming
end if end if
end function end function
function IsComplete() as boolean function ProcessNext(connection as HttpConnection) as boolean
' TODO: this function is correct only if request does not have a body if m.state = Http.HttpRequestState.DONE
' Need read and process line by line return m.ready_for_response
' Once there's an empty line, we've read all headers end if
' Check for Content-Length header, and read that amount of data
' If header is missing, error out
buf = m.buf
complete = isstr(buf) and (right(buf, 2) = m.Unix2NewLine) or (right(buf, 4) = m.Windows2NewLine)
'if complete then info(m,"header:"+UnixNL()+buf)
return complete
if m.state = Http.HttpRequestState.INIT
m.state = Http.HttpRequestState.READING_OPERATION
end if
if m.state = Http.HttpRequestState.READING_OPERATION
if m.ParseOperation()
m.ProcessOperation()
m.state = Http.HttpRequestState.READING_HEADERS
end if
end if
if m.state = Http.HttpRequestState.READING_HEADERS
if m.ParseHeaders()
m.ProcessHeaders(connection)
m.state = Http.HttpRequestState.READING_BODY
end if
end if
if m.state = Http.HttpRequestState.READING_BODY
if m.ParseBody()
m.state = Http.HttpRequestState.DONE
end if
end if
return m.ready_for_response
end function end function
function Parse(connection as HttpConnection) as boolean function ParseOperation() as boolean
lines = m.buf.tokenize(WinNL()) if m.buffer_index <> 0
operation = lines.RemoveHead() m.log.error(`invalid state: reading operation, but request is at index ${m.buffer_index}`)
if operation <> invalid m.ready_for_response = true
parts = operation.tokenize(" ") return false
if parts.count() = 3 end if
m.method = Ucase(parts.RemoveHead())
m.uri = parts.RemoveHead() if m.buffer.len() = 0
m.protocol = Ucase(parts.RemoveHead()) return false
m.log.info(m.method + " '" + m.uri + "'") end if
for each line in lines
av = line.tokenize(": ") operation = m.ReadHeaderLine()
if av.count() = 2
m.fields[av.GetHead()] = av.GetTail() if operation = invalid or operation = ""
end if m.log.error("empty request")
end for m.ready_for_response = true
' interpret some fields if present return false
m.ParseRange() end if
m.ParseConnection(connection)
parts = operation.tokenize(" ")
if parts.count() = 3
m.method = Ucase(parts[0])
m.uri = parts[1]
m.protocol = Ucase(parts[2])
m.log.info(m.method + " '" + m.uri + "'")
else
m.log.error("invalid request: " + operation)
m.ready_for_response = true
end if
return not m.ready_for_response
end function
function ParseHeaders() as boolean
line = m.ReadHeaderLine()
while line <> invalid and line <> ""
splitIndex = line.InStr(": ")
if splitIndex > 0
key = line.Left(splitIndex)
value = line.Mid(splitIndex + 2)
m.headers[key] = value
end if
line = m.ReadHeaderLine()
end while
' Unfinished line, we wait for the rest
if line = invalid
return false
end if
' Empty line, we're done with headers
if line = ""
return true
end if
return not m.ready_for_response
end function
function ParseBody() as boolean
data = m.ReadBufferToEnd()
if isstr(m.body)
m.body = m.body + data
else
m.body = data
end if
if m.headers["Content-Length"] = invalid
m.ready_for_response = true
if m.body.len() > 0
m.log.error("invalid request: request body found, but no Content-Length header")
return false
else else
m.log.error("invalid request: " + operation) return true
m.ok = false
end if end if
else else
m.log.error("empty request") contentLength = m.headers["Content-Length"].toInt()
m.ok = false if not isstr(m.body)
return false
end if
if m.body.len() > contentLength
m.log.error("invalid request: request body is larger than Content-Length")
m.ready_for_response = true
return false
end if
m.ready_for_response = m.body.len() = contentLength
return m.ready_for_response
end if end if
return m.ok
end function end function
function ProcessHeaders(connection as HttpConnection)
m.ParseRange()
m.ParseConnection(connection)
end function
function ProcessOperation()
m.route = m.uri
split = m.route.Instr("?")
if split <> -1
m.route = m.route.Left(split)
m.query = WebUtils.UrlQueryComponents(m.uri)
else
m.query = {}
end if
end function
' TODO: this function does not take into account multiple ranges.
function ParseRange() function ParseRange()
range = m.fields.range range = m.headers.range
if range <> invalid if range <> invalid
endpoints = lcase(range).tokenize("=") endpoints = lcase(range).tokenize("=")
if endpoints.count() = 2 and endpoints.GetHead() = "bytes" if endpoints.count() = 2 and endpoints.GetHead() = "bytes"
@@ -104,14 +205,40 @@ namespace Http
end function end function
function ParseConnection(connection as HttpConnection) function ParseConnection(connection as HttpConnection)
connectionStr = m.fields.connection connectionStr = m.headers.connection
if connectionStr <> invalid if connectionStr <> invalid
connection.close = (lcase(connectionStr.trim()) = "close") connection.close = (lcase(connectionStr.trim()) = "close")
end if end if
end function end function
function Process(connection as HttpConnection) as boolean function ReadHeaderLine() as dynamic
return m.Parse(connection) index = m.buffer.Instr(m.buffer_index, WinNL())
if index = -1
return invalid
end if
length = index - m.buffer_index
line = m.buffer.Mid(m.buffer_index, length)
m.buffer_index += length + 2 'WinNL().len() = 2
return line
end function
function ReadBufferToEnd() as dynamic
if m.buffer_index = m.buffer.len()
return ""
end if
data = m.buffer.Mid(m.buffer_index)
m.buffer_index += data.len()
return data
end function
function Json() as dynamic
if m.body = invalid
return invalid
end if
return ParseJson(m.body)
end function end function
end class end class
@@ -0,0 +1,11 @@
namespace Http
enum HttpRequestState
INIT = 0
READING_OPERATION = 1
READING_HEADERS = 2
READING_BODY = 3
DONE = 4
end enum
end namespace
+66 -56
View File
@@ -17,20 +17,19 @@ namespace Http
private source = Http.HttpResponseSource.NONE private source = Http.HttpResponseSource.NONE
' members ' members
private buf = invalid private body_buffer = invalid
private header = invalid private header_buffer = invalid
private path = invalid private path = invalid
private request = invalid private request = invalid
private id = 0 private id = 0
' copy-initializable members ' copy-initializable members
private start = 0 private start = 0
private length = 0 private body_buffer_length = 0
private sent = 0 private sent = 0
private header_sent = 0 private header_sent = 0
private header_only = false private header_only = false
private buf_start = 0 private buf_start = 0
private http_code = 0 private http_code = 0
private mimetype = "text/html" ' for errors
private server private server
private settings private settings
@@ -38,14 +37,11 @@ namespace Http
function new(request as HttpRequest, server as HttpServer, settings as HttpSettings) function new(request as HttpRequest, server as HttpServer, settings as HttpSettings)
m.log = new log.Logger("HttpResponse") m.log = new log.Logger("HttpResponse")
m.id = Http.GetHttpResponseId() m.id = Http.GetHttpResponseId()
m.request = request
m.server = server m.server = server
m.settings = settings m.settings = settings
m.Init(request) m.body_buffer = CreateObject("roByteArray")
end function m.headers = {}
function Init(request as HttpRequest)
m.buf = CreateObject("roByteArray")
m.request = request
end function end function
function Process() as boolean function Process() as boolean
@@ -63,60 +59,69 @@ namespace Http
errname = WebUtils.HttpTitle(errcode) errname = WebUtils.HttpTitle(errcode)
m.http_code = errcode m.http_code = errcode
buf = "<html><head><title>" + Stri(errcode).trim() + " " + errname + "</title></head><body>" + UnixNL() buffer = "<html><head><title>" + Stri(errcode).trim() + " " + errname + "</title></head><body>" + UnixNL()
buf = buf + "<h1>" + errname + "</h1>" + UnixNL() buffer = buffer + "<h1>" + errname + "</h1>" + UnixNL()
buf = buf + reason + UnixNL() buffer = buffer + reason + UnixNL()
buf = buf + "<hr>" + UnixNL() buffer = buffer + "<hr>" + UnixNL()
buf = buf + m.GeneratedBy() + UnixNL() buffer = buffer + m.GeneratedBy() + UnixNL()
buf = buf + "</body></html>" + UnixNL() buffer = buffer + "</body></html>" + UnixNL()
m.buf.fromasciistring(buf) m.SetBodyDataString(buffer)
m.length = m.buf.count() m.ContentType("text/html")
m.GenerateHeader(true)
m.source = Http.HttpResponseSource.GENERATED m.source = Http.HttpResponseSource.GENERATED
end function end function
function Redirect(where as string) function Redirect(where as string, code = 301 as integer)
m.location = where m.headers["Location"] = where
message = "Moved to: <a href=" + Quote() + where + Quote() + ">" + where + "</a>" message = "Moved to: <a href=" + Quote() + where + Quote() + ">" + where + "</a>"
m.Default(301, message) m.Default(code, message)
end function end function
function Json(data as object) function Json(data as object)
m.http_code = 200 m.http_code = 200
buf = FormatJson(data) buffer = FormatJson(data)
m.SetBodyDataString(buffer)
m.ContentType("application/json")
m.buf.fromasciistring(buf)
m.length = m.buf.count()
m.mimetype = "application/json"
m.GenerateHeader(true)
m.source = Http.HttpResponseSource.GENERATED m.source = Http.HttpResponseSource.GENERATED
end function end function
function SetBodyDataString(data as string)
m.body_buffer.fromasciistring(data)
m.body_buffer_length = m.body_buffer.count()
m.ContentLength(m.body_buffer_length)
end function
function ContentLength(length as integer)
m.headers["Content-Length"] = Stri(length).trim()
end function
function ContentType(mimeType as string)
m.headers["Content-Type"] = mimeType
end function
function Send(sock as object, bufsize as integer) as integer function Send(sock as object, bufsize as integer) as integer
sent = -1 sent = -1
if m.source = Http.HttpResponseSource.FROMFILE if m.source = Http.HttpResponseSource.FROMFILE
if m.start + m.sent >= m.buf_start + m.buf.count() if m.start + m.sent >= m.buf_start + m.body_buffer.count()
m.buf_start = m.start + m.sent m.buf_start = m.start + m.sent
m.buf.ReadFile(m.path, m.buf_start, bufsize) m.body_buffer.ReadFile(m.path, m.buf_start, bufsize)
m.log.info("Read" + Stri(m.buf.count()) + " bytes from source file @" + itostr(m.buf_start)) m.log.info("Read" + Stri(m.body_buffer.count()) + " bytes from source file @" + itostr(m.buf_start))
end if end if
end if end if
buf_pos = m.start + m.sent - m.buf_start buf_pos = m.start + m.sent - m.buf_start
buf_remaining = m.buf.count() - buf_pos buf_remaining = m.body_buffer.count() - buf_pos
if buf_remaining = 0 if buf_remaining = 0
m.log.info("source buf is empty") m.log.info("source buffer is empty")
end if end if
req_remaining = m.length - m.sent req_remaining = m.body_buffer_length - m.sent
if buf_remaining > req_remaining if buf_remaining > req_remaining
buf_remaining = req_remaining buf_remaining = req_remaining
end if end if
sent = sock.send(m.buf, buf_pos, buf_remaining) sent = sock.send(m.body_buffer, buf_pos, buf_remaining)
m.LogInfo(sent, m.buf_start + buf_pos, m.length) m.LogInfo(sent, m.buf_start + buf_pos, m.body_buffer_length)
if sent > 0 if sent > 0
m.sent = m.sent + sent m.sent = m.sent + sent
end if end if
@@ -124,6 +129,10 @@ namespace Http
end function end function
function SendHeader(sock as object, bufsize as integer) as integer function SendHeader(sock as object, bufsize as integer) as integer
if m.header = invalid
m.GenerateHeader()
end if
if m.header_sent = 0 if m.header_sent = 0
sent = sock.sendStr(m.header) sent = sock.sendStr(m.header)
else else
@@ -136,28 +145,28 @@ namespace Http
return sent return sent
end function end function
function GenerateHeader(close = false as boolean) function GenerateHeader()
code = m.http_code code = m.http_code
title = WebUtils.HttpTitle(code) title = WebUtils.HttpTitle(code)
m.headers["Date"] = m.Now()
m.headers["Server"] = m.settings.PackageName
if not m.headers.DoesExist("Connection")
m.KeepAlive(false)
end if
m.header = "HTTP/1.1" + Stri(code) + " " + title + WinNL() m.header = "HTTP/1.1" + Stri(code) + " " + title + WinNL()
m.header = m.header + "Date: " + m.Now() + WinNL() for each header in m.headers
m.header = m.header + "Server: " + m.settings.PackageName + WinNL() m.header = m.header + header + ": " + m.headers[header] + WinNL()
if isstr(m.location) end for
m.header = m.header + "Location: " + m.location + WinNL()
end if
m.header = m.header + m.KeepAlive(close) + WinNL()
m.header = m.header + "Content-Length:" + Stri(m.length) + WinNL()
if code = 206
m.header = m.header + "Content-Range: bytes" + m.MakeRange(m.start, m.length, m.filelength) + WinNL()
end if
m.header = m.header + "Content-Type: " + m.mimetype + WinNL()
m.header = m.header + "Accept-Ranges: bytes" + WinNL()
m.header = m.header + WinNL() m.header = m.header + WinNL()
m.header_length = m.header.len() m.header_length = m.header.len()
end function end function
function Done() as boolean function Done() as boolean
return m.sent = m.length return m.sent = m.body_buffer_length
end function end function
function DoneHeader() as boolean function DoneHeader() as boolean
@@ -168,13 +177,14 @@ namespace Http
m.log.info("Sent" + Stri(recent) + " [" + m.MakeRange(from, recent, total) + "]") m.log.info("Sent" + Stri(recent) + " [" + m.MakeRange(from, recent, total) + "]")
end function end function
function KeepAlive(close as boolean) as string function KeepAlive(keepAlive as boolean)
if close if keepAlive
base = "Connection: close" m.headers["Connection"] = "keep-alive"
m.headers["Keep-Alive"] = "timeout=" + Stri(m.settings.Idletime).trim()
else else
base = "Keep-Alive: timeout=" + Stri(m.settings.Idletime).trim() m.headers["Connection"] = "close"
m.headers.Delete("Keep-Alive")
end if end if
return base
end function end function
function Now() as string function Now() as string
+1 -1
View File
@@ -53,7 +53,7 @@ namespace Http
return false return false
end if end if
if route.path <> "*" and route.path <> request.uri if route.path <> "*" and route.path <> request.route
return false return false
end if end if
+2 -2
View File
@@ -5,9 +5,9 @@ namespace Http
PackageName = "Playlet" PackageName = "Playlet"
Port = 8888 Port = 8888
MessagePort = invalid MessagePort = invalid
MaxConnections = 3 MaxConnections = 10
Timeout = 60 * 1000 Timeout = 60 * 1000
MaxRequestLength = 4000 MaxRequestLength = 2097152
Idletime = 60 Idletime = 60
WwwRoot = "pkg:/" WwwRoot = "pkg:/"
IndexName = "index.html" IndexName = "index.html"
@@ -0,0 +1,53 @@
namespace Http
class BasicAuthMiddleware extends HttpRouter
public Username = "playlet"
public Password = "1234"
function new()
super()
m.All("*", function(context as object) as boolean
router = context.router
request = context.request
response = context.response
if not router.IsAuthorized(request, router)
response.headers["WWW-Authenticate"] = `Basic realm="Playlet web app"`
response.Default(401, "Unauthorized")
return true
end if
return false
end function)
end function
function IsAuthorized(request as HttpRequest, router as HttpRouter) as boolean
authHeader = request.headers["Authorization"]
if authHeader = invalid
return false
end if
if not authHeader.StartsWith("Basic ")
return false
end if
encoded = authHeader.Mid(6)
buffer = createObject("roByteArray")
buffer.FromBase64String(encoded)
decoded = buffer.ToAsciiString()
components = decoded.Tokenize(":")
if components.Count() = 2
return components[0] = router.Username and components[1] = router.Password
end if
return false
end function
end class
end namespace
@@ -0,0 +1,39 @@
namespace Http
class CommandsApiRouter extends HttpRouter
function new()
super()
m.Post("/api/command", function(context as object) as boolean
request = context.request
response = context.response
server = context.server
payload = request.Json()
if payload = invalid
response.Default(400, "Invalid payload")
return true
end if
if payload.command = "logout"
if Invidious.Logout()
server.task.top.login = false
end if
response.Default(204, "OK")
return true
else if payload.command = "play"
videoId = payload.videoId
server.task.top.command = `play:${videoId}`
response.Default(204, "OK")
return true
end if
response.Default(400, `Invalid command: ${payload.command}`)
return true
end function)
end function
end class
end namespace
@@ -0,0 +1,21 @@
namespace Http
class CorsMiddleware extends HttpRouter
private origin
function new(origin = "*" as string)
super()
m.origin = origin
m.All("*", function(context as object) as boolean
router = context.router
response = context.response
response.headers["Access-Control-Allow-Origin"] = router.origin
return false
end function)
end function
end class
end namespace
@@ -0,0 +1,156 @@
import "pkg:/source/utils/WebUtils.bs"
import "pkg:/source/services/InvidiousSettings.bs"
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
namespace Http
class DashRouter extends HttpRouter
function new()
super()
m.Get("/dash", function(context as object) as boolean
request = context.request
response = context.response
router = context.router
v = request.query.v
local = request.query.local
instance = InvidiousSettings.GetSelectedInstance()
metadata = router.GetVideoMetadata(context, v)
dashUrl = `${instance}/api/manifest/dash/id/${v}`
if metadata = invalid and local = invalid
response.Redirect(dashUrl, 302)
return true
end if
if local <> invalid
dashUrl = `${dashUrl}?local=${local}`
end if
resp = Requests().get(dashUrl)
text = resp.text ?? ""
if resp.statuscode = 200 and local = "true"
text = text.Replace("<BaseURL>/videoplayback", `<BaseURL>${instance}/videoplayback`)
end if
if resp.statuscode = 200 and metadata <> invalid
text = router.InjectStoryBoard(router, text, metadata)
end if
response.http_code = resp.statuscode
response.SetBodyDataString(text)
response.ContentType("application/dash+xml")
response.source = Http.HttpResponseSource.GENERATED
return true
end function)
end function
function GetVideoMetadata(context as object, videoId as string) as object
scene = context.server.task.top.getScene()
videoPlayer = scene.findNode("VideoPlayer")
metadata = videoPlayer?.content?.metadata
if metadata <> invalid and metadata.videoId = videoId
return metadata
end if
metadata = Invidious.GetVideoMetadata(videoId)
return metadata
end function
function InjectStoryBoard(router as object, dash as string, metadata as object) as string
xml = CreateObject ("roXMLElement")
if not xml.Parse(dash)
return dash
end if
thumb_id = 0
period = xml.GetChildNodes()[0]
sets = period.GetChildNodes()
for each set in sets
attributes = set.GetAttributes()
contentType = attributes.contentType
mimeType = attributes.mimeType
' If the DASH already has thumbnails, abort
if contentType = "image" or (mimeType <> invalid and mimeType.StartsWith("image"))
return ""
end if
id = attributes.id
idInt = id.toInt()
if idInt >= thumb_id
thumb_id = idInt + 1
end if
end for
thumbnails = router.GenerateThumbnailAdaptationSet(router, metadata, thumb_id)
injectPoint = StringLastIndexOf(dash, "</AdaptationSet>") + "</AdaptationSet>".Len()
newDash = dash.Left(injectPoint) + thumbnails + dash.Mid(injectPoint)
return newDash
end function
function GenerateThumbnailAdaptationSet(router as object, metadata as object, id as integer) as string
result = ""
storyboards = metadata.storyboards
for each storyboard in storyboards
' BUG: Broken storyboards have interval = 0 https://github.com/iv-org/invidious/issues/3441
if storyboard.interval > 0
' BUG: storyboardHeight can be wrong https://github.com/iv-org/invidious/issues/3440
' TODO: this fix/assumption is only if we have storyboard.storyboardCount = 1
storyboardHeight = storyboard.storyboardHeight
if storyboard.storyboardCount = 1
storyboardHeight = storyboard.count \ storyboard.storyboardWidth
if storyboard.count mod storyboard.storyboardWidth > 0
storyboardHeight += 1
end if
end if
tilesPerPage = storyboard.storyboardWidth * storyboardHeight
intervalSeconds = (storyboard.interval / 1000)
' If the template changed from known format, abort.
if storyboard.templateUrl.Instr("$M") = -1
return ""
end if
' Youtube template uses the var $M for tile pages
' DASH-IF uses $Number$ in the SegmentTemplate
url = WebUtils.EscapeUrlForXml(storyboard.templateUrl.Replace("$M", "$Number$"))
tileCount = tilesPerPage
duration = tileCount * intervalSeconds
width = storyboard.width * storyboard.storyboardWidth
height = storyboard.height * storyboardHeight
' Bandwidth is kind of a guess...
bandwidth = Int((width * height * 0.5) / duration)
result += `<AdaptationSet id="${id}" mimeType="image/jpeg" contentType="image">`
result += `<SegmentTemplate media="${url}" duration="${duration}" startNumber="0" />`
result += `<Representation id="thumbnails_${id}" bandwidth="${bandwidth}" `
result += ` width="${width}" height="${height}">`
' TODO: the last image in the list is usually smaller than the others. For example:
' Consider a video with 85 thumbnails, in tiles of 5x5
' 1st tile is 5x5 (25)
' 2nd tile is 5x5 (50)
' 3rd tile is 5x5 (75)
' 4th tile is 5x2 (85)
' This makes the display always misinterpret the the last tile if it is smaller
result += `<EssentialProperty schemeIdUri="http://dashif.org/guidelines/thumbnail_tile" value="${storyboard.storyboardWidth}x${storyboardHeight}"/>`
result += `</Representation>`
result += `</AdaptationSet>`
id += 1
end if
end for
return result
end function
end class
end namespace
@@ -10,12 +10,12 @@ namespace Http
response = context.response response = context.response
method = request.method method = request.method
route = request.uri uri = request.uri
if method = "" if method = ""
response.Default(400, "You sent a request that the server couldn't understand.") response.Default(400, "You sent a request that the server couldn't understand.")
else else
response.Default(404, `Cannot ${method} ${route}`) response.Default(404, `Cannot ${method} ${uri}`)
end if end if
return true return true
@@ -4,26 +4,34 @@ namespace Http
private log as log.Logger private log as log.Logger
private root private root
private filesOnly private route
private showDirectories
private showHidden
function new(root as string, filesOnly = false as boolean) function new(route as string, root as string, showDirectories = false as boolean, showHidden = false as boolean)
super() super()
m.log = new log.Logger("HttpStaticFilesRouter") m.log = new log.Logger("HttpStaticFilesRouter")
m.root = root m.root = root
m.filesOnly = filesOnly m.route = route
m.showDirectories = showDirectories
m.showHidden = showHidden
m.Get("*", function(context as object) as boolean m.Get("*", function(context as object) as boolean
router = context.router router = context.router
request = context.request request = context.request
response = context.response response = context.response
uri = request.uri if not request.route.StartsWith(router.route)
decoded_uri = WebUtils.UrlUnescape(uri) return false
if decoded_uri.instr("?")
decoded_uri = decoded_uri.Tokenize("?")[0]
end if end if
path = CreateObject("roPath", router.root + decoded_uri)
path_in_route = request.route.Mid(router.route.Len())
decoded_path = WebUtils.UrlUnescape(path_in_route)
full_path = PathJoin(router.root, decoded_path)
path = CreateObject("roPath", full_path)
fs = CreateObject("roFilesystem") fs = CreateObject("roFilesystem")
if not path.isValid() if not path.isValid()
@@ -41,17 +49,18 @@ namespace Http
end if end if
if stat.type = "directory" if stat.type = "directory"
if router.filesOnly if not router.showDirectories
response.Default(403, "Forbidden") response.Default(403, "Forbidden")
return false return true
end if end if
response.mimetype = "text/html" response.ContentType("text/html")
router.GenerateDirectoryListing(path, router, request, response) router.GenerateDirectoryListing(path, router, request, response)
return true return true
else if stat.type = "file" else if stat.type = "file"
response.mimetype = WebUtils.MimeType(decoded_uri) mimetype = WebUtils.MimeType(decoded_path)
response.ContentType(mimetype)
response.fileLength = stat.size response.fileLength = stat.size
router.log.info("uri=" + uri + ", target=" + path + ", content-type=" + response.mimetype + ", content-length=" + Stri(response.fileLength).trim()) router.log.info("uri=" + request.uri + ", target=" + path + ", content-type=" + mimetype + ", content-length=" + Stri(response.fileLength).trim())
router.GenerateFile(path, router, request, response) router.GenerateFile(path, router, request, response)
return true return true
else else
@@ -94,16 +103,20 @@ namespace Http
end if end if
response.start = start response.start = start
response.length = finish - start + 1 response.body_buffer_length = finish - start + 1
response.ContentLength(response.body_buffer_length)
response.headers["Content-Range"] = "bytes " + response.MakeRange(response.start, response.body_buffer_length, response.filelength)
response.http_code = 206 response.http_code = 206
router.log.info("sending range " + response.MakeRange(start, response.length, response.fileLength)) router.log.info("sending range " + response.MakeRange(start, response.body_buffer_length, response.fileLength))
else ' no range stuff else ' no range stuff
response.length = response.fileLength response.body_buffer_length = response.fileLength
response.ContentLength(response.body_buffer_length)
response.http_code = 200 response.http_code = 200
end if end if
response.GenerateHeader() response.headers["Accept-Ranges"] = "bytes"
response.KeepAlive(true)
return true return true
end function end function
@@ -140,8 +153,19 @@ namespace Http
if uriDir.len() > 0 and uriDir.right(1) <> "/" if uriDir.len() > 0 and uriDir.right(1) <> "/"
uriDir = uriDir + "/" uriDir = uriDir + "/"
end if end if
routeDir = router.route
if routeDir.len() > 0 and routeDir.right(1) <> "/"
routeDir = routeDir + "/"
end if
if not uriDir = routeDir
uri = uriDir + ".."
listing = listing + "<a href=" + Quote() + uri + Quote() + ">" + ".." + "</a>" + UnixNL()
end if
for each item in dirList for each item in dirList
if item.left(1) <> "." if router.showHidden or item.left(1) <> "."
indicator = invalid indicator = invalid
stat = fs.stat(dir + item) stat = fs.stat(dir + item)
if stat <> invalid if stat <> invalid
@@ -170,11 +194,9 @@ namespace Http
listing = listing + "</body>" + UnixNL() listing = listing + "</body>" + UnixNL()
listing = listing + "</html>" + UnixNL() listing = listing + "</html>" + UnixNL()
response.buf.FromAsciiString(listing) response.SetBodyDataString(listing)
response.length = response.buf.count()
response.http_code = 200 response.http_code = 200
response.GenerateHeader() response.KeepAlive(true)
response.source = Http.HttpResponseSource.GENERATED response.source = Http.HttpResponseSource.GENERATED
return true return true
end function end function
@@ -5,25 +5,42 @@ namespace Http
function new() function new()
super() super()
m.Get("*", function(context as object) as boolean m.Post("/invidious/instances", function(context as object) as boolean
request = context.request
response = context.response
instances = request.Json()
if GetInterface(instances, "ifArray") = invalid
response.Default(400, "Expected json array")
return true
end if
for i = 0 to instances.Count() - 1
if instances[i].right(1) = "/"
instances[i] = instances[i].left(instances[i].len() - 1)
end if
end for
InvidiousSettings.SetRegistryInstances(instances)
response.Default(200, "OK")
return true
end function)
m.Get(Invidious.TOKEN_CALLBACK, function(context as object) as boolean
request = context.request request = context.request
response = context.response response = context.response
server = context.server server = context.server
uri = request.uri if request.query["token"] <> invalid and request.query["referer"] <> invalid
if uri.StartsWith(Invidious.TOKEN_CALLBACK) ' Token is encoded twice for some reason
components = WebUtils.UrlQueryComponents(uri) token = WebUtils.UrlUnescape(request.query["token"]).DecodeUriComponent()
if components["token"] <> invalid referer = WebUtils.UrlUnescape(request.query["referer"])
' Token is encoded twice for some reason InvidiousSettings.SetAuthToken(token, referer)
token = WebUtils.UrlUnescape(components["token"]).DecodeUriComponent() server.task.top.login = true
print(`Got Token: ${token}`)
RegistryUtils.Write("invidious_token", token)
server.task.top.login = true
end if
response.Redirect("/index.html?tab=settings")
return true
end if end if
return false response.Redirect("/", 302)
return true
end function) end function)
end function end function
@@ -9,17 +9,39 @@ namespace Http
super() super()
m.Get("/api/state", function(context as object) as boolean m.Get("/api/state", function(context as object) as boolean
request = context.request
response = context.response response = context.response
state = { keys = ["app", "device", "invidious"]
app: GetAppInfo(),
device: GetDeviceInfo(), if request.query.DoesExist("key")
invidious: { keys = request.query["key"]
host: Invidious.GetCurrentHost(), if GetInterface(keys, "ifArray") = invalid
keys = [keys]
end if
end if
state = {}
if ArrayIndexOf(keys, "app") <> -1
state["app"] = GetAppInfo()
end if
if ArrayIndexOf(keys, "device") <> -1
state["device"] = GetDeviceInfo()
end if
if ArrayIndexOf(keys, "invidious") <> -1
authToken = InvidiousSettings.GetAuthToken()
state["invidious"] = {
instances: InvidiousSettings.GetCurrentInstances(),
selected_instance: InvidiousSettings.GetSelectedInstance(),
auth_url: Invidious.GetAuthorizeTokenLink(), auth_url: Invidious.GetAuthorizeTokenLink(),
logged_in: Invidious.GetAuthenticationHeaders() <> invalid logged_in: authToken <> invalid,
logged_in_instance: authToken <> invalid ? authToken.instance : invalid
} }
} end if
response.Json(state) response.Json(state)
return true return true
end function) end function)
+26 -2
View File
@@ -5,6 +5,10 @@ import "pkg:/components/WebServer/Middleware/HttpDefaultRouter.bs"
import "pkg:/components/WebServer/Middleware/InvidiousRouter.bs" import "pkg:/components/WebServer/Middleware/InvidiousRouter.bs"
import "pkg:/components/WebServer/Middleware/RegistryApiRouter.bs" import "pkg:/components/WebServer/Middleware/RegistryApiRouter.bs"
import "pkg:/components/WebServer/Middleware/StateApiRouter.bs" import "pkg:/components/WebServer/Middleware/StateApiRouter.bs"
import "pkg:/components/WebServer/Middleware/CommandsApiRouter.bs"
import "pkg:/components/WebServer/Middleware/CorsMiddleware.bs"
import "pkg:/components/WebServer/Middleware/BasicAuthMiddleware.bs"
import "pkg:/components/WebServer/Middleware/DashRouter.bs"
function Init() function Init()
m.top.functionName = "WebServerLoop" m.top.functionName = "WebServerLoop"
@@ -16,12 +20,32 @@ function WebServerLoop()
m.settings = new Http.HttpSettings(m.webServerPort) m.settings = new Http.HttpSettings(m.webServerPort)
' Root at www to get http://IP_ADDRESS:PORT/index.html ' Root at www to get http://IP_ADDRESS:PORT/index.html
m.settings.WwwRoot = "pkg:/www" m.settings.WwwRoot = "pkg:/www"
m.settings.Timeout = 2000
m.server = new Http.HttpServer(m.settings, m) m.server = new Http.HttpServer(m.settings, m)
homeRouter = new Http.HttpRouter()
homeRouter.Get("/", function(context as object) as boolean
response = context.response
response.Redirect("/index.html?tab=settings", 302)
return true
end function)
m.server.UseRouter(new Http.CorsMiddleware(`http://${GetLocalIpAddress()}:8888`))
m.server.UseRouter(homeRouter)
m.server.UseRouter(new Http.DashRouter())
m.server.UseRouter(new Http.CommandsApiRouter())
m.server.UseRouter(new Http.StateApiRouter()) m.server.UseRouter(new Http.StateApiRouter())
m.server.UseRouter(new Http.RegistryApiRouter())
m.server.UseRouter(new Http.InvidiousRouter()) m.server.UseRouter(new Http.InvidiousRouter())
m.server.UseRouter(new Http.HttpStaticFilesRouter(m.settings.WwwRoot)) m.server.UseRouter(new Http.HttpStaticFilesRouter("/", m.settings.WwwRoot))
#if DEBUG
m.server.UseRouter(new Http.HttpStaticFilesRouter("/debug/pkg", "pkg:/", true, true))
m.server.UseRouter(new Http.HttpStaticFilesRouter("/debug/tmp", "tmp:/", true, true))
m.server.UseRouter(new Http.HttpStaticFilesRouter("/debug/cachefs", "cachefs:/", true, true))
#end if
#if WEB_SERVER_BASIC_AUTH
m.server.UseRouter(new Http.BasicAuthMiddleware())
#end if
m.server.UseRouter(new Http.RegistryApiRouter())
m.server.UseRouter(new Http.HttpDefaultRouter()) m.server.UseRouter(new Http.HttpDefaultRouter())
timeout = m.settings.Timeout timeout = m.settings.Timeout
@@ -3,5 +3,6 @@
<component name="WebServerTask" extends="Task"> <component name="WebServerTask" extends="Task">
<interface> <interface>
<field id="login" type="boolean" alwaysNotify="true" /> <field id="login" type="boolean" alwaysNotify="true" />
<field id="command" type="string" alwaysNotify="true" />
</interface> </interface>
</component> </component>
-16
View File
@@ -1,16 +0,0 @@
import "pkg:/source/services/Invidious.bs"
sub init()
m.instructions = m.top.findNode("instructions")
text = "- Scan the QR Code" + chr(10)
text += "- Login (Create account if needed)" + chr(10)
text += "- Scan the QR Code again" + chr(10)
text += "- Click ""Authorize""" + chr(10)
text += "- If the error ""Invalid signature"" shows, press back and ""Authorize"" again" + chr(10)
text += "- Your TV should go to home screen automatically" + chr(10)
text += chr(10) + chr(10) + chr(10)
text += "Invidious instance: " + Invidious.GetCurrentHost()
m.instructions.text = text
end sub
-30
View File
@@ -1,30 +0,0 @@
<?xml version='1.0' encoding='utf-8'?>
<component
name='QRTestScene'
extends='Scene'>
<children>
<!-- This is example use of QRPoster: show QRCode centered on screen -->
<QRPoster
id='TestQRPoster'
loadWidth='500'
loadHeight='500'
loadPadding='20'
translation='[100, 110]' />
<Label
id='instructionsTitle'
height='50'
width='500'
text='Instructions'
font='font:MediumBoldSystemFont'
wrap='true'
translation='[650,110]' />
<Label
id='instructions'
height='500'
width='500'
font='font:MediumSystemFont'
wrap='true'
translation='[650,160]' />
</children>
</component>
+18 -1
View File
@@ -18,6 +18,11 @@
"required": false, "required": false,
"type": "#ISO3166", "type": "#ISO3166",
"default": "GetUserCountryCode" "default": "GetUserCountryCode"
},
"fields": {
"required": false,
"type": "string",
"default": "title,videoId,videoThumbnails,lengthSeconds,viewCount,author,publishedText,liveNow"
} }
} }
}, },
@@ -25,7 +30,14 @@
"name": "popular", "name": "popular",
"displayName": "Popular", "displayName": "Popular",
"url": "/api/v1/popular", "url": "/api/v1/popular",
"authenticated": false "authenticated": false,
"queryParams": {
"fields": {
"required": false,
"type": "string",
"default": "title,videoId,videoThumbnails,lengthSeconds,viewCount,author,publishedText,liveNow"
}
}
}, },
{ {
"name": "search", "name": "search",
@@ -90,6 +102,11 @@
"required": false, "required": false,
"type": "#ISO3166", "type": "#ISO3166",
"default": "GetUserCountryCode" "default": "GetUserCountryCode"
},
"fields": {
"required": false,
"type": "string",
"default": "title,videoId,videoThumbnails,lengthSeconds,viewCount,author,publishedText,liveNow"
} }
} }
}, },
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 12 KiB

+140
View File
@@ -0,0 +1,140 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="1920"
height="1080"
viewBox="0 0 508 285.75"
version="1.1"
id="svg10011"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs10008">
<rect
x="180.21565"
y="328.72668"
width="570.68286"
height="243.62486"
id="rect418-2-51" />
<rect
x="180.21565"
y="328.72668"
width="570.68286"
height="243.62486"
id="rect418-2-8-2" />
<rect
x="180.21565"
y="328.72668"
width="570.68286"
height="243.62486"
id="rect418-2-53-6" />
<rect
x="180.21565"
y="328.72668"
width="570.68286"
height="243.62486"
id="rect418-2-6-6" />
<rect
x="180.21565"
y="328.72668"
width="570.68286"
height="243.62486"
id="rect418-2-5-5" />
<rect
x="180.21565"
y="328.72668"
width="570.68286"
height="243.62486"
id="rect418-2-1-4" />
<rect
x="180.21565"
y="328.72668"
width="570.68286"
height="243.62486"
id="rect418-2-3-1" />
</defs>
<g
id="layer1"
transform="matrix(0.8999741,0,0,0.8999741,25.406579,14.291204)">
<rect
style="fill:#f0f9f2;fill-opacity:1;stroke:none;stroke-width:3.68071;stroke-linejoin:round;stroke-dasharray:none"
id="rect8445-7"
width="192.9267"
height="108.94424"
x="109.70631"
y="88.402878"
rx="20.13974"
ry="19.408449" />
<text
xml:space="preserve"
transform="matrix(1.3208994,0,0,1.3208994,-115.36013,-354.38654)"
id="text416-2-13"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-51);display:inline;fill:#ff1c30;fill-opacity:1;stroke:none;stroke-width:1.06591;stroke-linejoin:round;stroke-dasharray:none"><tspan
x="180.21484"
y="397.45387"
id="tspan11055"><tspan
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="tspan11053">P</tspan></tspan></text>
<text
xml:space="preserve"
transform="matrix(1.3208994,0,0,1.3208994,-65.866935,-354.45042)"
id="text416-2-1-4"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-8-2);display:inline;fill:#ff1c30;fill-opacity:1;stroke:none;stroke-width:1.06591;stroke-linejoin:round;stroke-dasharray:none"><tspan
x="180.21484"
y="397.45387"
id="tspan11059"><tspan
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="tspan11057">l</tspan></tspan></text>
<text
xml:space="preserve"
transform="matrix(1.3208994,0,0,1.3208994,87.108046,-354.30193)"
id="text416-2-5-8"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-53-6);display:inline;fill:#ff1c30;fill-opacity:1;stroke:none;stroke-width:1.06591;stroke-linejoin:round;stroke-dasharray:none"><tspan
x="180.21484"
y="397.45387"
id="tspan11063"><tspan
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="tspan11061">e</tspan></tspan></text>
<text
xml:space="preserve"
transform="matrix(1.3208994,0,0,1.3208994,138.55003,-354.31168)"
id="text416-2-59-6"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-6-6);display:inline;fill:#ff1c30;fill-opacity:1;stroke:none;stroke-width:1.06591;stroke-linejoin:round;stroke-dasharray:none"><tspan
x="180.21484"
y="397.45387"
id="tspan11067"><tspan
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="tspan11065">t</tspan></tspan></text>
<text
xml:space="preserve"
transform="matrix(1.3208994,0,0,1.3208994,69.600141,-354.30583)"
id="text416-2-8-1"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-5-5);display:inline;fill:#ff1c30;fill-opacity:1;stroke:none;stroke-width:1.06591;stroke-linejoin:round;stroke-dasharray:none"><tspan
x="180.21484"
y="397.45387"
id="tspan11071"><tspan
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="tspan11069">l</tspan></tspan></text>
<text
xml:space="preserve"
transform="matrix(1.3208994,0,0,1.3208994,-48.469095,-354.51494)"
id="text416-2-4-5"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-1-4);display:inline;fill:#ff1c30;fill-opacity:1;stroke:none;stroke-width:1.06591;stroke-linejoin:round;stroke-dasharray:none"><tspan
x="180.21484"
y="397.45387"
id="tspan11075"><tspan
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="tspan11073">a</tspan></tspan></text>
<text
xml:space="preserve"
transform="matrix(1.3208994,0,0,1.3208994,9.0695965,-354.11012)"
id="text416-2-84-0"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-3-1);display:inline;fill:#ff1c30;fill-opacity:1;stroke:none;stroke-width:1.06591;stroke-linejoin:round;stroke-dasharray:none"><tspan
x="180.21484"
y="397.45387"
id="tspan11079"><tspan
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="tspan11077">y</tspan></tspan></text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 6.1 KiB

+36
View File
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="100"
height="100"
viewBox="0 0 26.458333 26.458333"
version="1.1"
id="svg9602"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs9599" />
<g
id="layer1">
<rect
style="fill:#242424;fill-opacity:1;stroke:none;stroke-width:0.671348;stroke-linejoin:round;stroke-dasharray:none"
id="rect8445"
width="26.378244"
height="26.508022"
x="0.059478253"
y="0.0009513023"
rx="4"
ry="4" />
<g
aria-label="P"
transform="matrix(0.3883926,0,0,0.3883926,-64.217943,-131.42398)"
id="text416-2"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2);display:inline;fill:#ff1c30;stroke-width:1.06591;stroke-linejoin:round">
<path
d="m 182.08151,397.45387 v -50.02669 h 15.38134 q 4.032,0 7.54134,1.49333 3.50933,1.49334 6.12267,4.18134 2.61333,2.61333 4.10667,6.12267 1.49333,3.50933 1.49333,7.54133 0,3.95734 -1.49333,7.46667 -1.49334,3.50934 -4.10667,6.12267 -2.61334,2.53867 -6.12267,4.03201 -3.50934,1.49333 -7.54134,1.49333 h -8.81067 v 11.57334 z m 6.57067,-18.14401 h 8.81067 q 2.61334,0 4.928,-0.97067 2.31467,-1.04533 4.03201,-2.688 1.71733,-1.71733 2.688,-3.95733 1.04533,-2.31467 1.04533,-4.92801 0,-2.688 -1.04533,-5.00267 -0.97067,-2.31466 -2.688,-4.032 -1.71734,-1.71733 -4.03201,-2.688 -2.31466,-0.97067 -4.928,-0.97067 h -8.81067 z"
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="path9573" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

+96
View File
@@ -0,0 +1,96 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="540"
height="405"
viewBox="0 0 142.875 107.15625"
version="1.1"
id="svg9602"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs9599" />
<g
id="layer1">
<rect
style="fill:#242424;fill-opacity:0.99;stroke:none;stroke-width:1.24539;stroke-linejoin:round;stroke-dasharray:none"
id="rect8445"
width="65.39537"
height="36.795055"
x="22.703459"
y="35.180595"
rx="6.8266635"
ry="6.5550508" />
<g
aria-label="P"
transform="matrix(0.44612332,0,0,0.44612332,-53.310985,-114.20369)"
id="text416-2"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2);display:inline;fill:#ff1c30;stroke-width:1.06591;stroke-linejoin:round">
<path
d="m 182.08151,397.45387 v -50.02669 h 15.38134 q 4.032,0 7.54134,1.49333 3.50933,1.49334 6.12267,4.18134 2.61333,2.61333 4.10667,6.12267 1.49333,3.50933 1.49333,7.54133 0,3.95734 -1.49333,7.46667 -1.49334,3.50934 -4.10667,6.12267 -2.61334,2.53867 -6.12267,4.03201 -3.50934,1.49333 -7.54134,1.49333 h -8.81067 v 11.57334 z m 6.57067,-18.14401 h 8.81067 q 2.61334,0 4.928,-0.97067 2.31467,-1.04533 4.03201,-2.688 1.71733,-1.71733 2.688,-3.95733 1.04533,-2.31467 1.04533,-4.92801 0,-2.688 -1.04533,-5.00267 -0.97067,-2.31466 -2.688,-4.032 -1.71734,-1.71733 -4.03201,-2.688 -2.31466,-0.97067 -4.928,-0.97067 h -8.81067 z"
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="path9573" />
</g>
<g
aria-label="l"
transform="matrix(0.44612332,0,0,0.44612332,-36.59502,-114.22526)"
id="text416-2-1"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-8);display:inline;fill:#ff1c30;stroke-width:1.06591;stroke-linejoin:round">
<path
d="m 189.92152,349.36851 v 48.08536 h -6.27201 v -48.08536 z"
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="path9570" />
</g>
<g
aria-label="e"
transform="matrix(0.44612332,0,0,0.44612332,15.071073,-114.17511)"
id="text416-2-5"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-53);display:inline;fill:#ff1c30;stroke-width:1.06591;stroke-linejoin:round">
<path
d="m 216.35353,388.8672 q -3.06134,4.55467 -7.24267,6.64533 -4.10667,2.09067 -8.96001,2.09067 -3.808,0 -7.168,-1.41867 -3.36,-1.49333 -5.824,-3.95733 -2.464,-2.464 -3.95734,-5.824 -1.41867,-3.36001 -1.41867,-7.16801 0,-3.88267 1.41867,-7.24267 1.49334,-3.36 3.95734,-5.824 2.464,-2.53867 5.824,-3.95734 3.36,-1.49333 7.168,-1.49333 4.85334,0 9.10934,2.24 4.33067,2.24 7.46667,6.944 l -21.65334,20.16001 q 1.19466,0.82134 2.98667,1.19467 1.792,0.29867 3.584,0.0747 3.136,-0.37334 5.824,-2.09067 2.76267,-1.792 4.62934,-4.48 z m -28.59735,-10.60267 q -0.224,2.83733 0.74667,5.22666 0.97066,2.38934 2.76267,3.73334 l 17.09867,-16.65067 q -1.41867,-1.71734 -3.808,-2.76267 -2.38934,-1.12 -5.22667,-0.97067 -2.31467,0.14933 -4.33067,1.04533 -2.016,0.896 -3.584,2.46401 -1.49333,1.49333 -2.464,3.50933 -0.97067,2.016 -1.19467,4.40534 z"
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="path9558" />
</g>
<g
aria-label="t"
transform="matrix(0.44612332,0,0,0.44612332,32.445174,-114.17841)"
id="text416-2-59"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-6);display:inline;fill:#ff1c30;stroke-width:1.06591;stroke-linejoin:round">
<path
d="m 180.21484,360.71785 h 3.43467 v -11.34934 h 6.34667 v 11.34934 h 6.64534 v 5.22667 h -6.64534 v 20.23468 q 0,2.61333 1.64267,4.256 1.64267,1.568 4.256,1.568 v 5.6 q -6.048,0 -9.184,-2.912 -3.06134,-2.912 -3.06134,-8.512 v -20.23468 h -3.43467 z"
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="path9555" />
</g>
<g
aria-label="l"
transform="matrix(0.44612332,0,0,0.44612332,9.157916,-114.17642)"
id="text416-2-8"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-5);display:inline;fill:#ff1c30;stroke-width:1.06591;stroke-linejoin:round">
<path
d="m 189.92152,349.36851 v 48.08536 h -6.27201 v -48.08536 z"
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="path9561" />
</g>
<g
aria-label="a"
transform="matrix(0.44612332,0,0,0.44612332,-30.719029,-114.24707)"
id="text416-2-4"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-1);display:inline;fill:#ff1c30;stroke-width:1.06591;stroke-linejoin:round">
<path
d="m 181.85751,379.23519 q 0,-3.88267 1.344,-7.24267 1.344,-3.36 3.584,-5.824 2.31467,-2.53867 5.37601,-3.95734 3.136,-1.49333 6.72,-1.49333 4.256,0 7.76534,2.09067 3.50933,2.016 5.74933,5.45067 v -7.39201 h 6.34667 v 36.58669 h -6.34667 v -7.31734 q -2.24,3.43467 -5.74933,5.45067 -3.50934,2.016 -7.76534,2.016 -3.584,0 -6.72,-1.41867 -3.06134,-1.49333 -5.37601,-3.95733 -2.24,-2.464 -3.584,-5.824 -1.344,-3.36001 -1.344,-7.16801 z m 6.34667,0 q 0,2.464 0.896,4.704 0.97067,2.16534 2.53867,3.80801 1.64267,1.64266 3.808,2.61333 2.24,0.896 4.77867,0.896 2.464,0 4.62934,-0.896 2.24,-0.97067 3.88266,-2.61333 1.64267,-1.64267 2.61334,-3.80801 0.97067,-2.24 0.97067,-4.704 0,-2.464 -0.97067,-4.704 -0.97067,-2.24 -2.61334,-3.88267 -1.64266,-1.64267 -3.88266,-2.61333 -2.16534,-0.97067 -4.62934,-0.97067 -2.53867,0 -4.77867,0.97067 -2.16533,0.97066 -3.808,2.61333 -1.568,1.64267 -2.53867,3.88267 -0.896,2.24 -0.896,4.704 z"
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="path9567" />
</g>
<g
aria-label="y"
transform="matrix(0.44612332,0,0,0.44612332,-11.285794,-114.11033)"
id="text416-2-84"
style="font-size:74.6667px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;shape-inside:url(#rect418-2-3);display:inline;fill:#ff1c30;stroke-width:1.06591;stroke-linejoin:round">
<path
d="m 186.56151,360.86718 10.97601,28.07468 10.752,-28.07468 h 6.72001 l -18.74135,47.56269 h -6.272 l 4.256,-10.82667 -14.48534,-36.73602 z"
style="font-family:'Bunya PERSONAL';-inkscape-font-specification:'Bunya PERSONAL, Normal'"
id="path9564" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 7.0 KiB

-144
View File
@@ -1,144 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="1920"
height="1080"
viewBox="0 0 507.99997 285.75"
version="1.1"
id="svg5"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs2">
<linearGradient
id="linearGradient1156">
<stop
style="stop-color:#505050;stop-opacity:0.30202579;"
offset="0"
id="stop1152" />
<stop
style="stop-color:#c7c7c7;stop-opacity:0.16758747;"
offset="1"
id="stop1154" />
</linearGradient>
<radialGradient
xlink:href="#linearGradient1156"
id="radialGradient5833"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,0.31128638,0,13.805446)"
cx="168.40327"
cy="20.045263"
fx="168.40327"
fy="20.045263"
r="8.3192425" />
<radialGradient
xlink:href="#linearGradient1156"
id="radialGradient5835"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,0.31128638,0,13.805446)"
cx="168.40327"
cy="20.045263"
fx="168.40327"
fy="20.045263"
r="8.3192425" />
<radialGradient
xlink:href="#linearGradient1156"
id="radialGradient5837"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,0.31128638,0,13.805446)"
cx="168.40327"
cy="20.045263"
fx="168.40327"
fy="20.045263"
r="8.3192425" />
<radialGradient
xlink:href="#linearGradient1156"
id="radialGradient5839"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,0.31128638,0,13.805446)"
cx="168.40327"
cy="20.045263"
fx="168.40327"
fy="20.045263"
r="8.3192425" />
<radialGradient
xlink:href="#linearGradient1156"
id="radialGradient5841"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,0.31128638,0,13.805446)"
cx="168.40327"
cy="20.045263"
fx="168.40327"
fy="20.045263"
r="8.3192425" />
<radialGradient
xlink:href="#linearGradient1156"
id="radialGradient5843"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,0.31128638,0,13.805446)"
cx="168.40327"
cy="20.045263"
fx="168.40327"
fy="20.045263"
r="8.3192425" />
<radialGradient
xlink:href="#linearGradient1156"
id="radialGradient5845"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,0.31128638,0,13.805446)"
cx="168.40327"
cy="20.045263"
fx="168.40327"
fy="20.045263"
r="8.3192425" />
<radialGradient
xlink:href="#linearGradient1156"
id="radialGradient5847"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,0.31128638,0,13.805446)"
cx="168.40327"
cy="20.045263"
fx="168.40327"
fy="20.045263"
r="8.3192425" />
</defs>
<g
id="layer1">
<g
aria-label="Playlet"
transform="matrix(18.534073,0,0,21.199658,-2867.2105,-282.0651)"
id="text484"
style="font-size:3.175px;font-family:'The Amaranth';-inkscape-font-specification:'The Amaranth, Normal';white-space:pre;inline-size:111.711;opacity:1;fill:#ff0000;stroke:url(#radialGradient5847);stroke-width:0.264494;stroke-linejoin:round">
<path
d="m 161.15529,20.959066 c 0.80222,0.347114 2.36423,-0.674942 2.83476,-1.858985 0.6518,-1.631434 -1.01049,-2.055683 -2.80005,-0.713511 -0.70965,0.536097 -1.13776,1.164758 -0.91407,1.353742 0.0926,0.07714 0.23527,-0.03857 0.18513,-0.146559 -0.15041,-0.3394 1.02591,-1.349886 1.91684,-1.64686 1.26118,-0.42425 1.85513,0.150415 1.29203,1.245751 -0.49753,0.975775 -1.8667,1.882127 -2.45679,1.62372 -0.0771,-0.03085 0.62095,-1.592865 0.79836,-1.785706 0.11571,-0.127275 0.10799,-0.323972 -0.0154,-0.3394 -0.0849,-0.01157 -0.15427,0.09256 -0.4551,0.6788 -0.58624,1.133904 -0.91407,2.395083 -0.66337,2.549356 0.0617,0.03857 0.13499,0.0039 0.15427,-0.07714 0.0116,-0.05014 0.004,-0.08485 -0.027,-0.09642 -0.0231,-0.0039 -0.0231,-0.0077 -0.0116,-0.138845 0.027,-0.258407 0.12728,-0.663373 0.16199,-0.647946 z"
style="font-size:4.62818px;stroke:url(#radialGradient5833)"
id="path1162" />
<path
d="m 165.26279,18.101165 c -0.0848,-0.115704 -0.26226,0.05014 -0.63637,0.605521 -0.96035,1.430878 -1.31132,2.973605 -0.69809,3.085453 0.28927,0.05014 0.7058,-0.246836 1.48102,-1.064482 0.28155,-0.289261 0.30083,-0.320115 0.25455,-0.374111 -0.0501,-0.05785 -0.054,-0.054 -0.55538,0.451248 -0.58624,0.590093 -0.82921,0.782934 -1.03748,0.825359 -0.58624,0.115704 0.0193,-1.731711 1.04905,-3.193445 0.18127,-0.258406 0.18899,-0.273834 0.1427,-0.335543 z"
style="font-size:4.62818px;stroke:url(#radialGradient5835)"
id="path1164" />
<path
d="m 167.789,20.561814 c 0.2237,-0.242979 0.24684,-0.27769 0.20056,-0.323972 -0.0386,-0.03857 -0.0617,-0.02314 -0.26227,0.18127 -0.6248,0.644088 -1.04905,0.921779 -1.22647,0.817645 -0.21212,-0.119561 -0.0656,-0.77522 0.28155,-1.376883 0.16199,-0.277691 0.0154,-0.416537 -0.18513,-0.154273 -0.0386,0.04628 -0.0386,0.04628 -0.054,0.02314 -0.20441,-0.289261 -0.5361,-0.165843 -0.85236,0.285404 -0.5978,0.856214 -0.22369,1.589009 0.40497,0.786791 0.0386,-0.05014 0.0733,-0.09256 0.0733,-0.08871 0,0 -0.004,0.03085 -0.008,0.06942 -0.0386,0.343257 0.0347,0.601663 0.2507,0.651802 0.2854,0.06557 0.72122,-0.173557 1.37688,-0.871641 z m -1.48487,-0.335543 c -0.0733,0.181271 -0.38954,0.574666 -0.53996,0.6788 -0.0964,0.06171 -0.1157,0.05785 -0.11185,-0.027 0,-0.185127 0.15813,-0.566952 0.3394,-0.813788 0.17742,-0.239123 0.32398,-0.327829 0.42811,-0.26612 0.0694,0.04242 0.0694,0.04628 -0.0154,0.212125 -0.0386,0.08099 -0.0849,0.177413 -0.10027,0.215981 z"
style="font-size:4.62818px;stroke:url(#radialGradient5837)"
id="path1166" />
<path
d="m 170.10694,20.233985 c -0.027,-0.05014 -0.0694,-0.03857 -0.1697,0.05785 -0.25069,0.231409 -0.60552,0.447391 -0.94878,0.628661 -0.16584,0.08485 -0.16198,0.08871 -0.10413,-0.027 0.18513,-0.381825 0.53995,-1.172473 0.55152,-1.288177 0.0193,-0.185127 -0.16198,-0.146559 -0.26226,0.05785 -0.0424,0.08485 -0.10799,0.165843 -0.38954,0.512957 -0.39339,0.474388 -0.6518,0.70194 -0.77136,0.686513 -0.13499,-0.01928 0.0347,-0.624804 0.29697,-1.056768 0.10028,-0.165843 0.0964,-0.258406 -0.0193,-0.293118 -0.25069,-0.07328 -0.65566,0.894782 -0.53224,1.288177 0.11956,0.389538 0.46282,0.250693 1.05291,-0.42425 0.054,-0.06171 0.10028,-0.111848 0.10028,-0.111848 0,0.0077 -0.10414,0.239123 -0.16585,0.374112 -0.2314,0.489815 -0.27769,0.574665 -0.35097,0.613234 -0.61323,0.320115 -0.9642,0.613233 -1.06062,0.894781 -0.0656,0.18127 -0.0193,0.308545 0.12342,0.347113 0.32397,0.08485 0.85621,-0.470531 1.25346,-1.249608 0.004,-0.01157 0.0771,-0.054 0.16199,-0.100277 0.49753,-0.258407 0.69808,-0.358684 0.9912,-0.601664 0.21213,-0.177413 0.27384,-0.250693 0.24298,-0.308545 z m -1.8397,1.330602 c -0.2237,0.370254 -0.45896,0.632518 -0.65952,0.732795 -0.13884,0.07328 -0.18898,0.01157 -0.12341,-0.142702 0.0887,-0.212125 0.41653,-0.489816 0.7945,-0.682657 0.0617,-0.03085 0.0617,-0.03085 -0.0116,0.09256 z"
style="font-size:4.62818px;stroke:url(#radialGradient5839)"
id="path1168" />
<path
d="m 171.39126,18.101165 c -0.0848,-0.115704 -0.26226,0.05014 -0.63637,0.605521 -0.96035,1.430878 -1.31132,2.973605 -0.69809,3.085453 0.28926,0.05014 0.7058,-0.246836 1.48102,-1.064482 0.28155,-0.289261 0.30083,-0.320115 0.25455,-0.374111 -0.0501,-0.05785 -0.054,-0.054 -0.55538,0.451248 -0.58624,0.590093 -0.82922,0.782934 -1.03749,0.825359 -0.58623,0.115704 0.0193,-1.731711 1.04906,-3.193445 0.18127,-0.258406 0.18898,-0.273834 0.1427,-0.335543 z"
style="font-size:4.62818px;stroke:url(#radialGradient5841)"
id="path1170" />
<path
d="m 171.81936,21.14805 c 0.27383,0.054 0.69423,-0.142702 1.22261,-0.578522 0.24298,-0.200555 0.27383,-0.239123 0.21598,-0.277691 -0.0347,-0.02314 -0.0579,-0.0077 -0.21598,0.123418 -0.59781,0.49753 -1.1339,0.725082 -1.23804,0.524527 -0.0463,-0.09642 0.0347,-0.493672 0.10028,-0.478245 0.25841,0.054 0.56309,-0.219838 0.67494,-0.597806 0.10028,-0.3394 -0.1967,-0.455105 -0.50524,-0.192841 -0.55153,0.470531 -0.70965,1.388454 -0.25455,1.47716 z m 0.4551,-1.303604 c 0.11957,-0.119561 0.1697,-0.127275 0.16199,-0.02314 -0.0116,0.177413 -0.16199,0.412679 -0.31626,0.489815 -0.0617,0.03085 -0.17741,0.05014 -0.17741,0.027 0,-0.05785 0.21598,-0.381825 0.33168,-0.493673 z"
style="font-size:4.62818px;stroke:url(#radialGradient5843)"
id="path1172" />
<path
d="m 174.17587,18.899526 c 0.0501,-0.0077 0.29697,-0.05785 0.54381,-0.107991 1.14162,-0.227552 1.56201,-0.250693 1.71243,-0.100277 0.0656,0.06557 0.15813,0.027 0.15813,-0.06942 -0.004,-0.223696 -0.40883,-0.258407 -1.25347,-0.100278 -0.081,0.01543 -0.2854,0.054 -0.4551,0.08485 -0.54381,0.100278 -0.6788,0.127275 -0.6788,0.123418 -0.004,-0.0039 0.15427,-0.250693 0.22755,-0.358684 0.18127,-0.258406 0.18898,-0.273834 0.1427,-0.335543 -0.0887,-0.119561 -0.26226,0.05014 -0.64409,0.617091 -0.10799,0.161986 -0.0771,0.150416 -0.49753,0.204411 -0.84078,0.107991 -1.36917,0.05785 -1.43859,-0.142702 -0.054,-0.146559 -0.22369,-0.123418 -0.21212,0.027 0.0231,0.323972 0.66337,0.416536 1.76642,0.262263 0.1967,-0.027 0.18513,-0.04628 0.0926,0.115705 -0.75208,1.322888 -0.93335,2.510788 -0.40111,2.607208 0.28926,0.05014 0.70194,-0.250693 1.48488,-1.064481 0.32011,-0.331687 0.3394,-0.362541 0.29311,-0.416537 -0.0501,-0.05785 -0.054,-0.054 -0.5978,0.493673 -0.58624,0.590093 -0.82922,0.782934 -1.03749,0.825359 -0.46667,0.09256 -0.20055,-1.068339 0.55153,-2.395083 0.15813,-0.277691 0.13113,-0.250694 0.24298,-0.269978 z"
style="font-size:4.62818px;stroke:url(#radialGradient5845)"
id="path1174" />
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 9.9 KiB

+5 -1
View File
@@ -2,7 +2,7 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json # Do not update version manually, it is auto updated from package.json
major_version=0 major_version=0
minor_version=3 minor_version=5
build_version=00000 build_version=00000
## Channel Assets ## Channel Assets
@@ -20,3 +20,7 @@ splash_screen_sd=pkg:/images/splash-screen_sd.jpg
splash_color=#242424 splash_color=#242424
splash_min_time=0 splash_min_time=0
supports_input_launch=1
bs_const=DEBUG=true;WEB_SERVER_BASIC_AUTH=false;DASH_THUMBNAILS=false
+18 -4
View File
@@ -1,16 +1,22 @@
function main() as void function main(args as object) as void
screen = CreateObject("roSGScreen") screen = CreateObject("roSGScreen")
m.port = CreateObject("roMessagePort") m.port = CreateObject("roMessagePort")
screen.setMessagePort(m.port) screen.setMessagePort(m.port)
m.global = screen.getGlobalNode() m.global = screen.getGlobalNode()
screen.CreateScene("MainScene") scene = screen.CreateScene("MainScene")
screen.show() screen.show()
scene.ObserveField("exitChannel", m.port)
scene.launchArgs = args
input = CreateObject("roInput")
input.setMessagePort(m.port)
' The following comment is to enable the SceneGraph inspector ' The following comment is to enable the SceneGraph inspector
' on the VSCode BrightScript plugin. ' on the VSCode BrightScript plugin.
#if DEBUG
' vscode_rdb_on_device_component_entry ' vscode_rdb_on_device_component_entry
#end if
while true while true
msg = wait(0, m.port) msg = wait(0, m.port)
@@ -19,6 +25,14 @@ function main() as void
if msg.isScreenClosed() if msg.isScreenClosed()
return return
end if end if
else if msgType = "roSGNodeEvent"
field = msg.getField()
data = msg.getData()
if field = "exitChannel" and data = true
END
end if
else if msgType = "roInputEvent"
scene.inputArgs = msg.getInfo()
end if end if
end while end while
end function end function
+29 -96
View File
@@ -4,10 +4,10 @@ import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/General.bs" import "pkg:/source/utils/General.bs"
import "pkg:/source/utils/TimeUtils.bs" import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/source/utils/WebUtils.bs" import "pkg:/source/utils/WebUtils.bs"
import "pkg:/source/services/InvidiousSettings.bs"
namespace Invidious namespace Invidious
const API_URL = "https://vid.puffyan.us" ' TODO: query server status, check if it supports APIs and/or signups
const TOKEN_CALLBACK = "/invidious/token_callback" const TOKEN_CALLBACK = "/invidious/token_callback"
const POPULAR_ENDPOINT = "/api/v1/popular" const POPULAR_ENDPOINT = "/api/v1/popular"
@@ -18,9 +18,10 @@ namespace Invidious
const SEARCH_SUGGEST_ENDPOINT = "/api/v1/search/suggestions" const SEARCH_SUGGEST_ENDPOINT = "/api/v1/search/suggestions"
const SEARCH_ENDPOINT = "/api/v1/search" const SEARCH_ENDPOINT = "/api/v1/search"
const AUTH_SCOPE = "GET:feed,GET:playlists" const AUTH_SCOPE = "GET:feed,GET:playlists,POST:tokens/unregister"
const AUTH_FEED = "/api/v1/auth/feed" const AUTH_FEED = "/api/v1/auth/feed"
const AUTH_PLAYLISTS = "/api/v1/auth/playlists" const AUTH_PLAYLISTS = "/api/v1/auth/playlists"
const AUTH_TOKENS_UNREGISTER = "/api/v1/auth/tokens/unregister"
function DefaultArgs() as object function DefaultArgs() as object
return { return {
@@ -30,36 +31,9 @@ namespace Invidious
} }
end function end function
function GetPopular() as object
url = `${Invidious.API_URL}${Invidious.POPULAR_ENDPOINT}`
args = Invidious.DefaultArgs()
response = Requests().get(url, args)
if response.statuscode = 200
return response.json
end if
return invalid
end function
function GetTrending(trendingType = "" as string) as object
url = `${Invidious.API_URL}${Invidious.TRENDING_ENDPOINT}`
args = Invidious.DefaultArgs()
if trendingType <> ""
args.params.type = trendingType
end if
response = Requests().get(url, args)
if response.statuscode = 200
return response.json
end if
return invalid
end function
function GetVideoUrl(videoId as string, itag as string, local as boolean) as string function GetVideoUrl(videoId as string, itag as string, local as boolean) as string
url = `${Invidious.API_URL}/latest_version?id=${videoId}&itag=${itag}` instance = InvidiousSettings.GetSelectedInstance()
url = `${instance}/latest_version?id=${videoId}&itag=${itag}`
if local if local
url = url + "&local=true" url = url + "&local=true"
end if end if
@@ -67,31 +41,22 @@ namespace Invidious
end function end function
function GetVideoMetadata(videoId as string) as object function GetVideoMetadata(videoId as string) as object
url = `${Invidious.API_URL}${Invidious.VIDEOS_ENDPOINT}/${videoId}` instance = InvidiousSettings.GetSelectedInstance()
url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}`
args = Invidious.DefaultArgs() args = Invidious.DefaultArgs()
response = Requests().get(url, args) response = Requests().get(url, args)
' TODO: handle 500 {"error":"This video is unavailable"} ' TODO: handle 500 {"error":"This video is unavailable"}
if response.statuscode = 200 if response.statuscode = 200
videoMetadata = response.json return response.json
lastItag = videoMetadata.formatStreams[videoMetadata.formatStreams.Count() - 1].itag
' GetVideoUrl returns a url that redirects to the video stream
' TODO: is this reliable?
videoUrl = Invidious.GetVideoUrl(videoId, lastItag, false)
videoMetadata.formatStreams.push({
itag: lastItag,
url: videoUrl
})
return videoMetadata
end if end if
return invalid return invalid
end function end function
function SearchSuggestions(q as string) as object 'SearchSuggestionResult function SearchSuggestions(q as string) as object 'SearchSuggestionResult
url = `${Invidious.API_URL}${Invidious.SEARCH_SUGGEST_ENDPOINT}` instance = InvidiousSettings.GetSelectedInstance()
url = `${instance}${Invidious.SEARCH_SUGGEST_ENDPOINT}`
args = Invidious.DefaultArgs() args = Invidious.DefaultArgs()
args.params.q = q args.params.q = q
@@ -104,7 +69,8 @@ namespace Invidious
end function end function
function Search(q as string, args = invalid as dynamic) as object function Search(q as string, args = invalid as dynamic) as object
url = `${Invidious.API_URL}${Invidious.SEARCH_ENDPOINT}` instance = InvidiousSettings.GetSelectedInstance()
url = `${instance}${Invidious.SEARCH_ENDPOINT}`
_args = Invidious.DefaultArgs() _args = Invidious.DefaultArgs()
_args.params.q = q _args.params.q = q
@@ -137,77 +103,44 @@ namespace Invidious
return invalid return invalid
end function end function
function GetCurrentHost() as string
return Invidious.API_URL
end function
function GetAuthorizeTokenLink() as string function GetAuthorizeTokenLink() as string
instance = InvidiousSettings.GetSelectedInstance()
' Make sure the host is not on https, because https cannot redirect to http, which is our local server ' Make sure the host is not on https, because https cannot redirect to http, which is our local server
invidiousHost = `${Invidious.API_URL}`.Replace("https://", "http://") invidiousHost = instance.Replace("https://", "http://")
localIp = GetLocalIpAddress() localIp = GetLocalIpAddress()
webServerPort = 8888 webServerPort = 8888
expire = TimeUtils.Now().AsSeconds() + 60 * 60 * 24 * 30 'A month from now expire = TimeUtils.Now().AsSeconds() + 60 * 60 * 24 * 30 'A month from now
callbackUrl = WebUtils.UrlEncode(`http://${localIp}:${webServerPort}${Invidious.TOKEN_CALLBACK}`) callbackUrl = WebUtils.UrlEncode(`http://${localIp}:${webServerPort}${Invidious.TOKEN_CALLBACK}?referer=${instance}`)
return `${invidiousHost}/authorize_token?scopes=${Invidious.AUTH_SCOPE}&callback_url=${callbackUrl}&expire=${expire}` return `${invidiousHost}/authorize_token?scopes=${Invidious.AUTH_SCOPE}&callback_url=${callbackUrl}&expire=${expire}`
end function end function
function GetAuthenticationHeaders() as object function GetAuthenticationHeaders(token as string) as object
token = RegistryUtils.Read("invidious_token")
if token = invalid
return invalid
end if
return { return {
"Authorization": `Bearer ${token}` "Authorization": `Bearer ${token}`
} }
end function end function
function GetUserFeed() as object function Logout() as boolean
headers = Invidious.GetAuthenticationHeaders() authToken = InvidiousSettings.GetAuthToken()
if headers = invalid if authToken = invalid
return invalid return false
end if end if
headers = Invidious.GetAuthenticationHeaders(authToken.token)
url = `${Invidious.API_URL}${Invidious.AUTH_FEED}` url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
' authToken.token is already valid json that contains the "session" key needed by the unregister endpoint
headers["Content-Type"] = "application/json"
args = { args = {
headers: headers, headers: headers,
retryCount: 3 'Sometimes authentication fails randomly with a valid token... data: authToken.token
} }
response = Requests().get(url, args) Requests().post(url, args)
if response.statuscode = 403 RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
RegistryUtils.Delete("invidious_token") return true
end if
if response.statuscode = 200
return response.json.videos
end if
return invalid
end function
function GetUserPlaylists() as object
headers = Invidious.GetAuthenticationHeaders()
if headers = invalid
return invalid
end if
url = `${Invidious.API_URL}${Invidious.AUTH_PLAYLISTS}`
args = {
headers: headers,
retryCount: 3 'Sometimes authentication fails randomly with a valid token...
}
response = Requests().get(url, args)
if response.statuscode = 403
RegistryUtils.Delete("invidious_token")
end if
if response.statuscode = 200
return response.json
end if
return invalid
end function end function
end namespace end namespace
+14 -13
View File
@@ -1,10 +1,9 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs" import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/utils/RegistryUtils.bs" import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/General.bs" import "pkg:/source/utils/General.bs"
import "pkg:/source/services/InvidiousSettings.bs"
class InvidiousService class InvidiousService
API_URL = "https://vid.puffyan.us"
private endpoints private endpoints
private responseHanlders private responseHanlders
@@ -29,16 +28,19 @@ class InvidiousService
return invalid return invalid
end if end if
url = m.API_URL + endpoint.url instance = InvidiousSettings.GetSelectedInstance()
url = instance + endpoint.url
args = { params: {} } args = { params: {} }
if endpoint.authenticated = true if endpoint.authenticated = true
auth_headers = m.GetAuthenticationHeaders() authToken = InvidiousSettings.GetAuthToken()
if auth_headers = invalid if authToken = invalid
return invalid return invalid
end if end if
args.headers = auth_headers url = authToken.instance + endpoint.url
args.headers = m.GetAuthenticationHeaders(authToken.token)
end if end if
if endpoint.queryParams <> invalid if endpoint.queryParams <> invalid
@@ -73,11 +75,7 @@ class InvidiousService
return responseHandler(m, requestData, response) return responseHandler(m, requestData, response)
end function end function
function GetAuthenticationHeaders() as object function GetAuthenticationHeaders(token as string) as object
token = RegistryUtils.Read("invidious_token")
if token = invalid
return invalid
end if
return { return {
"Authorization": `Bearer ${token}` "Authorization": `Bearer ${token}`
} }
@@ -94,7 +92,10 @@ class InvidiousService
m.DeleteExpiredToken(response) m.DeleteExpiredToken(response)
if response.statuscode = 200 if response.statuscode = 200
return response.json.videos videos = []
videos.Append(response.json.notifications)
videos.Append(response.json.videos)
return videos
end if end if
return invalid return invalid
end function end function
@@ -118,7 +119,7 @@ class InvidiousService
if response.statuscode = 403 if response.statuscode = 403
print(`Server responded with 403: ${response.text}`) print(`Server responded with 403: ${response.text}`)
print("deleting token...") print("deleting token...")
RegistryUtils.Delete("invidious_token") RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
end if end if
end function end function
+95
View File
@@ -0,0 +1,95 @@
namespace InvidiousSettings
const DEFAULT_INSTANCE = "https://vid.puffyan.us"
const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,health,users,api"
function GetCurrentInstances() as object
' TODO: cache this call to avoid json parsing every time
instances = InvidiousSettings.GetRegistryInstances()
if instances.Count() > 0
return instances
end if
publicInstances = InvidiousSettings.GetPublicInstances()
if publicInstances <> invalid
for i = 0 to 4
if i < publicInstances.Count()
instances.push(publicInstances[i].uri)
end if
end for
end if
if instances.Count() > 0
InvidiousSettings.SetRegistryInstances(instances)
return instances
end if
return [InvidiousSettings.DEFAULT_INSTANCE]
end function
function GetSelectedInstance() as string
instances = InvidiousSettings.GetCurrentInstances()
return instances[0]
end function
function SetAuthToken(token as string, instance as string)
json = FormatJson({
token: token,
instance: instance
})
RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json)
instances = InvidiousSettings.GetCurrentInstances()
index = ArrayIndexOf(instances, instance)
if index = -1
instances.push(instance)
InvidiousSettings.SetRegistryInstances(instances)
end if
end function
function GetAuthToken() as dynamic
tokenPayload = RegistryUtils.Read(RegistryUtils.INVIDIOUS_TOKEN)
if tokenPayload = invalid
return invalid
end if
return ParseJson(tokenPayload)
end function
function GetRegistryInstances() as object
instances = RegistryUtils.Read(RegistryUtils.INVIDIOUS_INSTANCES)
if instances = invalid
return []
end if
return ParseJson(instances)
end function
function SetRegistryInstances(instances as object)
RegistryUtils.Write(RegistryUtils.INVIDIOUS_INSTANCES, FormatJson(instances))
end function
function GetPublicInstances() as object
if m.invidiousPublicInstances <> invalid
return m.invidiousPublicInstances
end if
response = Requests().get(InvidiousSettings.INSTANCES_API)
if response.statuscode = 200
json = response.json
instances = []
for each instance in json
data = instance[1]
if data.monitor <> invalid and data.monitor.dailyRatios <> invalid
data.monitor.dailyRatios = invalid
end if
data["name"] = instance[0]
instances.push(data)
end for
m.invidiousPublicInstances = instances
end if
return m.invidiousPublicInstances
end function
end namespace
+84 -3
View File
@@ -1,18 +1,99 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs" import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/utils/WebUtils.bs"
import "pkg:/source/utils/Crypto.bs"
namespace SponsorBlock namespace SponsorBlock
const API_URL = "https://sponsor.ajay.app" const API_URL = "https://sponsor.ajay.app"
const SKIP_SEGMENT_ENDPOINT = "/api/skipSegments" const SKIP_SEGMENT_ENDPOINT = "/api/skipSegments"
const CATEGORIES = "&category=sponsor&category=selfpromo&category=interaction&category=intro&category=outro&category=preview&category=music_offtopic"
function SegmentColor(category as string) as integer
map = m.SponsorBlockColors
if map = invalid
map = {
sponsor: &h00D400FF,
selfpromo: &hFFFF00FF,
exclusive_access: &h008A5CFF,
interaction: &hCC00FFFF,
poi_highlight: &hFF1684FF,
intro: &h00FFFFFF,
outro: &h0202EDFF,
preview: &h008FD6FF,
filler: &h7300FFFF,
music_offtopic: &hFF9900FF
}
m.SponsorBlockColors = map
end if
if map.doesexist(category)
return map[category]
end if
return 0
end function
function SegmentTitle(category as string) as string
map = m.SponsorBlockTitles
if map = invalid
map = {
sponsor: "Sponsor",
selfpromo: "Unpaid/Self Promotion",
exclusive_access: "Exclusive Access",
interaction: "Interaction Reminder (Subscribe)",
poi_highlight: "Highlight",
intro: "Intermission/Intro Animation",
outro: "Endcards/Credits",
preview: "Preview/Recap",
filler: "Filler Tangent/Jokes",
music_offtopic: "Non-Music Section"
}
m.SponsorBlockTitles = map
end if
if map.doesexist(category)
return map[category]
end if
return ""
end function
function GetSkipSegmentsForVideo(videoId as string) as object function GetSkipSegmentsForVideo(videoId as string) as object
url = `${SponsorBlock.API_URL}${SponsorBlock.SKIP_SEGMENT_ENDPOINT}?videoID=${videoId}${SponsorBlock.CATEGORIES}` categories = ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "poi_highlight", "chapter", "filler", "exclusive_access"]
actionTypes = ["skip", "mute", "chapter", "full", "poi"]
categoriesJson = WebUtils.UrlEscape(FormatJson(categories))
actionTypesJson = WebUtils.UrlEscape(FormatJson(actionTypes))
' From SponsorBlock docs: It should be the first 4 - 32 characters (4 is recommended).
hashPrefix = GetSha256(videoId).Left(4)
url = `${SponsorBlock.API_URL}${SponsorBlock.SKIP_SEGMENT_ENDPOINT}/${hashPrefix}?categories=${categoriesJson}&actionTypes=${actionTypesJson}`
response = Requests().get(url) response = Requests().get(url)
if response.statuscode = 200 if response.statuscode = 200
return response.json results = response.json
for each item in results
if item.videoId = videoId
return item.segments
end if
end for
end if end if
return invalid return invalid
end function end function
function GenerateProgressBarBackground(segments as object, path as string)
bar = CreateObject("roBitmap", { width: 1000, height: 20, AlphaEnable: true })
bar.Clear(&hFFFFFF80)
width = bar.GetWidth()
height = bar.GetHeight()
for each segment in segments
pixelStart = (segment.segment[0] / segment.videoDuration) * width
pixelEnd = (segment.segment[1] / segment.videoDuration) * width
color = SponsorBlock.SegmentColor(segment.category)
' highlight's duration is zero, so it is not visble on the bar.
' Add a couple of pixels to see it
if pixelStart = pixelEnd
pixelEnd += 2
end if
bar.DrawRect(pixelStart, 0, pixelEnd - pixelStart, height, color)
end for
bar.Finish()
buffer = bar.GetPng(0, 0, width, height)
buffer.WriteFile(path)
end function
end namespace end namespace
+8
View File
@@ -0,0 +1,8 @@
function GetSha256(input as string) as string
buffer = CreateObject("roByteArray")
buffer.FromAsciiString(input)
digest = CreateObject("roEVPDigest")
digest.Setup("sha256")
return digest.Process(buffer)
end function
+9
View File
@@ -49,3 +49,12 @@ function GetDeviceInfo() as object
end if end if
return m.deviceInfo return m.deviceInfo
end function end function
function ArrayIndexOf(array as object, value as string) as integer
for i = 0 to array.Count() - 1
if array[i] = value
return i
end if
end for
return -1
end function
+3
View File
@@ -2,6 +2,9 @@ namespace RegistryUtils
const DEFAULT_SECTION = "Playlet" const DEFAULT_SECTION = "Playlet"
const INVIDIOUS_INSTANCES = "invidious_instances"
const INVIDIOUS_TOKEN = "invidious_token"
function Read(key as string, section = DEFAULT_SECTION as string) as dynamic function Read(key as string, section = DEFAULT_SECTION as string) as dynamic
sec = CreateObject("roRegistrySection", section) sec = CreateObject("roRegistrySection", section)
if sec.Exists(key) if sec.Exists(key)
+22
View File
@@ -113,3 +113,25 @@ end function
function Quote() as string function Quote() as string
return chr(34) return chr(34)
end function end function
function StringLastIndexOf(str as string, substr as string) as integer
index = str.InStr(substr)
while index <> -1
newIndex = str.InStr(index + 1, substr)
if newIndex = -1
return index
end if
index = newIndex
end while
return index
end function
function PathJoin(path1 as string, path2 as string) as string
if path1.EndsWith("/")
path1 = path1.left(path1.len() - 1)
end if
if path2.StartsWith("/")
path2 = path2.Mid(1)
end if
return path1 + "/" + path2
end function
+16
View File
@@ -45,4 +45,20 @@ namespace TimeUtils
return validstr(ma[mNum - 1]) return validstr(ma[mNum - 1])
end function end function
function ParseTime(time as string) as integer
hours = 0
minutes = 0
seconds = 0
tokens = time.Tokenize(":")
if tokens.Count() = 3
hours = tokens[0].ToInt()
minutes = tokens[1].ToInt()
seconds = tokens[2].ToInt()
else if tokens.Count() = 2
minutes = tokens[0].ToInt()
seconds = tokens[1].ToInt()
end if
return hours * 3600 + minutes * 60 + seconds
end function
end namespace end namespace
+34 -4
View File
@@ -1,3 +1,5 @@
import "pkg:/source/utils/Types.bs"
namespace WebUtils namespace WebUtils
function UrlEncode(url as string) as string function UrlEncode(url as string) as string
ue = m.UrlEncoder ue = m.UrlEncoder
@@ -32,12 +34,26 @@ namespace WebUtils
url = Mid(url, index + 1) url = Mid(url, index + 1)
components = url.split("&") components = url.split("&")
for each component in components for each component in components
key = component
value = ""
hasValue = false
if Instr(0, component, "=") if Instr(0, component, "=")
keyValue = component.split("=") keyValue = component.split("=")
query[keyValue[0]] = keyValue[1] key = keyValue[0]
else value = keyValue[1]
query[keyValue[0]] = "" hasValue = true
end if end if
if query.DoesExist(key) and hasValue
oldValue = query[key]
if GetInterface(oldValue, "ifArray") = invalid
oldValue = [oldValue]
end if
oldValue.push(value)
value = oldValue
end if
query[key] = value
end for end for
return query return query
end function end function
@@ -102,11 +118,25 @@ namespace WebUtils
if hcm = invalid if hcm = invalid
hcm = { n200: "OK", n206: "Partial Content" } hcm = { n200: "OK", n206: "Partial Content" }
hcm.append({ n301: "Moved Permanently", n304: "Not Modified" }) hcm.append({ n301: "Moved Permanently", n304: "Not Modified" })
hcm.append({ n400: "Bad Request", n403: "Forbidden", n404: "Not Found", n413: "Request Entity Too Large" }) hcm.append({ n400: "Bad Request", n401: "Unauthorized", n403: "Forbidden", n404: "Not Found", n413: "Request Entity Too Large" })
hcm.append({ n500: "Internal Server Error", n501: "Not Implemented" }) hcm.append({ n500: "Internal Server Error", n501: "Not Implemented" })
m.HttpTitles = hcm m.HttpTitles = hcm
end if end if
return validstr(hcm["n" + Stri(code).trim()]) return validstr(hcm["n" + Stri(code).trim()])
end function end function
function EscapeUrlForXml(url as string) as string
urlEscapeChars = {}
urlEscapeChars["&"] = "&amp;"
urlEscapeChars["'"] = "&apos;"
urlEscapeChars[`"`] = "&quot;"
urlEscapeChars["<"] = "&lt;"
urlEscapeChars[">"] = "&gt;"
for each escapeChar in urlEscapeChars
url = url.Replace(escapeChar, urlEscapeChars[escapeChar])
end for
return url
end function
end namespace end namespace
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+273 -32
View File
@@ -5,15 +5,58 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Playlet</title> <title>Playlet</title>
<style>
table,
th,
td {
border: 1px solid;
cursor: all-scroll;
}
table {
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
</head> </head>
<body> <body ondrop="OnBodyDrop(event);" ondragover="OnBodyDragover(event);">
<h2>Playlet - Youtube Player for Roku</h2> <h2>Playlet - Youtube Player for Roku</h2>
<h4 id="app-version">Version: </h4> <h4 id="app-version">Version: </h4>
<h4>Invidious Instance: <a id="host" target="_blank">None</a></h4> <h4>Invidious Instance: <a id="instance" target="_blank">None</a></h4>
<button onclick="PlayVideo()">Play Video</button>
<label for="video-id">Video ID:</label>
<input type="text" id="video-id" name="video-id" style="min-width:300px;">
<h4 id="logged-in">Logged In: </h4> <h4 id="logged-in">Logged In: </h4>
<button style="visibility: hidden" id="login-button" onclick="Login()">Login</button> <button style="display: none" id="login-button" onclick="Login()">Login</button>
<button style="visibility: hidden" id="logout-button">Logout</button> <button style="display: none" id="logout-button" onclick="Logout()">Logout</button>
<br />
<table id="instances">
<thead>
<tr>
<th>Instances - find more at <a href="https://api.invidious.io/" target="_blank">api.invidious.io</a></th>
</tr>
</thead>
<tbody>
</tbody>
<tbody>
<tr id="instance-input-row">
<td>
<input type="text" id="instance-input" name="new-instance" oninput="OnNewInstanceTextChanged()"
style="min-width:300px;">
</td>
<td>
<button id="instance-add" disabled="true" onclick="AddInstance()">Add</button>
</td>
</tr>
</tbody>
</table>
</br>
<button style="display: none" id="update-instances" onclick="UpdateInstances()">Update Instances</button>
<h5>Instructions</h5> <h5>Instructions</h5>
<ul> <ul>
@@ -31,20 +74,6 @@
target="_blank">https://github.com/iBicha/playlet</a></h5> target="_blank">https://github.com/iBicha/playlet</a></h5>
<script> <script>
function RequestGet(url, cb) {
const req = new XMLHttpRequest();
req.addEventListener("load", function () {
try {
cb(null, JSON.parse(this.responseText));
}
catch (err) {
cb(err)
}
});
req.open("GET", url);
req.send();
}
function Login() { function Login() {
if (!window.appState) { if (!window.appState) {
alert("Error with login, please refresh the page.") alert("Error with login, please refresh the page.")
@@ -52,6 +81,31 @@
window.location = window.appState.invidious.auth_url window.location = window.appState.invidious.auth_url
} }
function Logout() {
PostJson('/api/command', { command: "logout" })
.then(function (response) {
window.location.reload();
})
.catch(function (err) {
alert(err)
});
}
function PlayVideo() {
let v = document.getElementById('video-id').value
if (IsValidHttpUrl(v)) {
v = GetVideoId(v)
}
if (!v || v.length < 8) {
alert("Please set video id")
return
}
PostJson('/api/command', { command: "play", videoId: v })
.catch(function (err) {
alert(err)
});
}
function CreateGithubIssueUrl() { function CreateGithubIssueUrl() {
title = "[Feedback] Playlet" title = "[Feedback] Playlet"
body = `### Feedback body = `### Feedback
@@ -69,24 +123,211 @@ ${JSON.stringify(window.appState.device, null, 2)}
return `https://github.com/iBicha/playlet/issues/new?title=${encodeURIComponent(title)}&body=${encodeURIComponent(body)}` return `https://github.com/iBicha/playlet/issues/new?title=${encodeURIComponent(title)}&body=${encodeURIComponent(body)}`
} }
RequestGet("/api/state", function (err, response) { function IsValidHttpUrl(string) {
if (err) { let url;
alert(err) try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
function GetVideoId(url) {
// Share/Short url
const YoutubeUrls = [
"https://youtu.be/",
"http://youtu.be/",
"https://www.youtu.be/",
"http://www.youtu.be/",
"https://youtube.com/shorts/",
"http://youtube.com/shorts/",
"https://www.youtube.com/shorts/",
"http://www.youtube.com/shorts/",
]
for (var i in YoutubeUrls) {
let youtubeUrl = YoutubeUrls[i];
if (url.startsWith(youtubeUrl)) {
url = url.replace(youtubeUrl, "")
if (url.includes("?")) {
url = url.substring(0, url.indexOf("?"))
}
return url
}
}
// regular url
url = new URL(url)
const urlSearchParams = new URLSearchParams(url.search);
return urlSearchParams.get('v')
}
function OnNewInstanceTextChanged() {
document.getElementById("instance-add").disabled = !IsValidHttpUrl(document.getElementById("instance-input").value)
}
function AddInstance() {
instance = document.getElementById("instance-input").value
AddInstanceRow(instance)
document.getElementById("instance-input").value = ""
document.getElementById("update-instances").style.display = "block";
}
function AddInstanceRow(instance) {
instances = document.getElementById("instances").getElementsByTagName('tbody')[0];
var row = instances.insertRow();
row.draggable = true
row.addEventListener('dragstart', OnTableRowDragStart);
row.addEventListener('dragover', OnTableRowDragover);
row.addEventListener('drop', OnTableRowDrop);
var cell = row.insertCell();
style = instance === window.appState.invidious.selected_instance ? `style="font-weight:bold"` : ""
cell.innerHTML = `<a href="${instance}" ${style} target="_blank">${instance}</a>`
cell = row.insertCell();
cell.innerHTML = `<button onclick="RemoveInstance('${instance}')">Remove</button>`
}
function RemoveInstance(instance) {
instanceRows = Array.from(document.getElementById("instances")
.getElementsByTagName('tbody')[0]
.getElementsByTagName('tr'));
for (const i in instanceRows) {
currentInstance = instanceRows[i].getElementsByTagName('a')[0].innerText
if (currentInstance === instance) {
instanceRows[i].remove()
document.getElementById("update-instances").style.display = "block";
return;
}
}
}
function UpdateInstances() {
instances = Array.from(document.getElementById("instances")
.getElementsByTagName('tbody')[0]
.getElementsByTagName('td'))
.map(el => el.getElementsByTagName('a')[0])
.filter(a => !!a)
.map(a => a.innerText);
PostJson('/invidious/instances', instances)
.then(function (response) {
alert("Instances updated. Restart Playlet to reflect changes.")
window.location.reload();
})
.catch(function (err) {
alert(err)
});
}
function PostJson(url, payload) {
return fetch(url,
{
headers: {
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(payload)
})
}
function Initialize() {
fetch("/api/state")
.then(function (response) {
return response.json();
})
.then(function (appState) {
window.appState = appState
console.log(appState)
document.getElementById("app-version").innerText = `Version: ${appState.app.version}`
if (appState.invidious.logged_in) {
document.getElementById("logged-in").innerHTML = `Logged In: true (<a href="${appState.invidious.logged_in_instance}" target="_blank">${appState.invidious.logged_in_instance}</a>)`
} else {
document.getElementById("logged-in").innerHTML = "Logged In: false"
}
instanceEl = document.getElementById("instance")
instanceEl.innerText = instanceEl.href = appState.invidious.selected_instance
for (var i in appState.invidious.instances) {
AddInstanceRow(appState.invidious.instances[i])
}
loginButton = document.getElementById("login-button")
loginButton.innerText = `Login (${appState.invidious.selected_instance})`
loginButton.style.display = appState.invidious.logged_in ? "none" : "block";
document.getElementById("logout-button").style.display = !appState.invidious.logged_in ? "none" : "block";
document.getElementById("feedback-url").href = CreateGithubIssueUrl()
})
.catch(function (err) {
alert(err)
});
}
var tableRow;
function OnTableRowDragStart(event) {
target = event.target;
while (target && target.tagName !== 'TR') {
target = target.parentNode
}
if (target.id === "instance-input-row") {
return return
} }
window.appState = response tableRow = target
console.log(response) }
document.getElementById("app-version").innerText = `Version: ${response.app.version}`
document.getElementById("logged-in").innerText = `Logged In: ${response.invidious.logged_in}`
document.getElementById("host").innerText = response.invidious.host
document.getElementById("host").href = response.invidious.host
document.getElementById("login-button").style.visibility = response.invidious.logged_in ? "hidden" : "visible"; function OnTableRowDragover(event) {
// TODO: log out feature event.preventDefault();
// document.getElementById("logout-button").style.visibility = response.invidious.logged_in ? "hidden" : "visible";
document.getElementById("feedback-url").href = CreateGithubIssueUrl() if (!tableRow) {
}) return
}
target = event.target;
while (target && target.tagName !== 'TR') {
target = target.parentNode
}
if (!target || target.id === "instance-input-row") {
return
}
let children = Array.from(target.parentNode.children);
if (children.indexOf(target) > children.indexOf(tableRow))
target.after(tableRow);
else
target.before(tableRow);
}
function OnTableRowDrop(event) {
event.preventDefault();
tableRow = undefined
document.getElementById("update-instances").style.display = "block";
}
function OnBodyDrop(event) {
for (var i in event.dataTransfer.items) {
let item = event.dataTransfer.items[i]
if (item.kind = 'string' && item.getAsString) {
item.getAsString((dataString) => {
if (IsValidHttpUrl(dataString) && GetVideoId(dataString)) {
document.getElementById('video-id').value = dataString
}
});
}
}
event.preventDefault();
}
function OnBodyDragover(event) {
event.preventDefault();
}
Initialize();
</script> </script>
</body> </body>