Compare commits

...
79 Commits
Author SHA1 Message Date
Brahim Hadriche 57d39a6bb1 Release v0.10.3 (#122) 2023-07-24 08:56:15 -04:00
Brahim Hadriche f2f8baa6b1 Support saved playlists (#121) 2023-07-24 08:48:07 -04:00
Brahim Hadriche 1a72c69b8e Release 0.10.2 (#112) 2023-07-10 09:20:48 -04:00
Brahim Hadriche 6ac8d54144 Add validation to env vars 2023-07-10 09:15:21 -04:00
Brahim Hadriche e5a932f62f [no ci] an example of invidious instance 2023-07-08 18:56:57 -04:00
Brahim Hadriche 2b147bbecf Had language server misconfigued 2023-07-08 18:05:36 -04:00
Brahim Hadriche 630668cff4 move expiry to const 2023-07-08 17:28:49 -04:00
Brahim Hadriche 1e98e98c04 Reduce token scope 2023-07-08 15:47:31 -04:00
Brahim Hadriche a5af36ddc0 fix for playlist limit 2023-07-08 15:35:46 -04:00
Brahim Hadriche 11aef3e3aa split profile into pieces 2023-07-08 15:34:54 -04:00
Brahim Hadriche 1b1a9e3cce profile-sync: only delete playlists created by this script 2023-07-08 14:51:18 -04:00
Brahim Hadriche 6da878edf9 Remove wrong reactive function 2023-07-07 17:48:44 -04:00
Brahim Hadriche fef8df454a dev menu tweak 2023-07-07 17:43:19 -04:00
Brahim Hadriche a8c693852e Add unstable tag 2023-07-07 17:31:03 -04:00
Brahim Hadriche 725cf59508 Reduce web server timeout again 2023-07-07 17:19:30 -04:00
Brahim Hadriche a6710d3510 append -dev to dev version 2023-07-07 17:15:58 -04:00
Brahim Hadriche e8b48611ca Disable web sockets since they are not used yet 2023-07-07 16:48:45 -04:00
Brahim Hadriche 3add083f6b Save scope and expire fields with auth token 2023-07-07 13:28:42 -04:00
Brahim Hadriche e49aa9b7d8 Fix for input field focus 2023-07-06 16:08:54 -04:00
Brahim Hadriche 5d38b325c5 Remove unused qrcode kanji, to remove warning 2023-07-06 12:20:58 -04:00
Brahim Hadriche fdc3434f15 Update README.md 2023-07-06 11:05:51 -04:00
Brahim Hadriche 77170edc0d Concurrency for workflows 2023-07-05 22:56:51 -04:00
renovate[bot] ea5531f1c8 Update dependency @tsconfig/svelte to v5 (#108)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-05 22:47:22 -04:00
Brahim Hadriche 581beb5d32 Renovate settings 2023-07-05 22:40:08 -04:00
renovate[bot] 2e8cdd2cec Update dependency @rokucommunity/bslint to v0.8.7 (#104)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-05 22:33:04 -04:00
renovate[bot] eb9bf48127 Add renovate.json (#103)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-05 22:31:05 -04:00
Brahim Hadriche dccbf76c1a Tooling 2023-07-05 22:08:44 -04:00
Brahim Hadriche 70d66f874d Some tooling cleanup 2023-07-05 21:00:10 -04:00
Brahim Hadriche 80bcd4c870 Fix commonjs export 2023-07-05 17:18:30 -04:00
Brahim Hadriche bd312484a9 couple of tweaks 2023-07-05 16:48:19 -04:00
Brahim Hadriche 6531650a39 json file formatting 2023-07-04 22:54:04 -04:00
Brahim Hadriche 3342e9f4da Fix lint call 2023-07-04 22:51:10 -04:00
Brahim Hadriche 3179fad19f Optimize icon for web app 2023-07-04 18:58:50 -04:00
Brahim Hadriche 00df78d862 Add email feedback form 2023-07-04 18:26:34 -04:00
Brahim Hadriche 016d6de6d6 Add debug target for playlet web 2023-07-04 17:20:55 -04:00
Brahim Hadriche a224b86fca Fix SponsorBlock segments where video duration is not provided (#102)
* Fix SponsorBlock segments where video duration is not provided

* add another null check
2023-07-04 15:21:19 -04:00
Brahim Hadriche 936eefeeb9 Set java version 2023-07-03 18:19:06 -04:00
Brahim Hadriche 7b53ec820d Ci/static analysis (#101)
* Add static analysis to the release job

* Analyse lib and app

* Update docs
2023-07-03 18:16:35 -04:00
Brahim Hadriche 25eccde5c3 Loading indicator for search page in web app 2023-07-03 11:53:28 -04:00
Brahim Hadriche 093953c113 Small tweak 2023-07-03 11:30:53 -04:00
Brahim Hadriche 60e8b9200e Redirect from old ui to new UI 2023-07-03 11:17:47 -04:00
Brahim Hadriche a070343a78 An attempt to fix list performance with virtual list (#100) 2023-07-03 11:14:03 -04:00
Brahim Hadriche d9dd6bc2f7 Fix home screen crash (#99) 2023-07-02 19:34:27 -04:00
Brahim Hadriche e65749e0de Update README.md 2023-07-02 19:23:22 -04:00
Brahim Hadriche 9cc12508cc Update README.md 2023-07-02 17:40:10 -04:00
Brahim Hadriche 37e43b5b32 Update README.md 2023-07-02 17:38:43 -04:00
Brahim Hadriche d3fba0a8be Update README.md 2023-07-02 17:33:47 -04:00
Brahim Hadriche 05799b4932 Update README.md 2023-07-02 17:31:56 -04:00
Brahim Hadriche 3191bfe425 docs structure (#95)
* docs structure

* More docs work

* Update readme

* link fix

* Update README.md

* Update README.md

* Update README.md
2023-07-02 17:30:33 -04:00
Brahim Hadriche 52d4222b5e Remove a couple of TODOs 2023-07-01 23:00:24 -04:00
Brahim Hadriche 5c2a590877 Remove a hack that's no longer needed 2023-07-01 22:57:02 -04:00
Brahim Hadriche 8bc9cec570 Remove workaround for Invidious token expiring due to misconfigured instance (#98)
* Remove workaround for Invidious token expiring

* Changelog
2023-07-01 17:55:31 -04:00
Brahim Hadriche 55fd1ba43c Add links to the app info in web app 2023-07-01 13:17:08 -04:00
Brahim Hadriche b1d8caf5c7 Update release.yml 2023-06-30 14:04:44 -04:00
Brahim Hadriche 80dcc322cf Update README.md 2023-06-30 12:21:12 -04:00
Brahim Hadriche f89bb2bbf1 Fix thumbnail 2023-06-29 17:59:53 -04:00
Brahim Hadriche 581d5a8a42 Add failure reason to popup 2023-06-29 17:36:35 -04:00
Brahim Hadriche f38c0b4106 format on save 2023-06-29 15:33:16 -04:00
Brahim Hadriche 191b88f4d0 Add search button to search bar (#97) 2023-06-29 14:11:53 -04:00
Brahim Hadriche c705ce86d3 Fix time input for casting (#94) 2023-06-28 17:04:07 -04:00
Brahim Hadriche cc78fb0ec1 Release Release v0.10.1 (#93) 2023-06-28 15:00:15 -04:00
Brahim Hadricheandgithub-action linter 05f2481f87 Fix a focus bug (#92)
* Fix a focus bug

* Lint fix

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2023-06-28 14:55:31 -04:00
Brahim Hadricheandgithub-action linter bdaaf17785 Fix duration formatting (#91)
* Fix duration formatting

* Lint fix

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2023-06-28 13:42:23 -04:00
Brahim Hadriche a675811488 Fix for bad auth token (#90) 2023-06-28 09:27:04 -04:00
Brahim Hadriche d80240130d Update README.md 2023-06-27 20:04:29 -04:00
Brahim Hadriche 459a009293 Update README.md 2023-06-27 20:03:54 -04:00
Brahim Hadriche cf08c67de5 Remove node version limitation 2023-06-25 17:53:17 -04:00
Brahim Hadriche 9cd664fdd7 Missed this bit 2023-06-25 16:33:05 -04:00
Brahim Hadriche ad753deac7 Small fix 2023-06-25 16:27:34 -04:00
Brahim Hadriche 3acf733eec Support playing a video from a specific time (cast from phone, drag a… (#88)
* Support playing a video from a specific time (cast from phone, drag and drop, open in Invidious)

* Remove a console log
2023-06-25 16:17:12 -04:00
Brahim Hadriche 6c84630cec Better changelogs for automated releases 2023-06-25 11:37:46 -04:00
Brahim Hadriche 682e0bae7f Update RELEASING.md 2023-06-25 11:21:21 -04:00
Brahim Hadriche 02e206ad22 Update RELEASING.md 2023-06-25 11:20:15 -04:00
Brahim Hadriche c40428f2d6 Update README.md 2023-06-25 10:59:03 -04:00
Brahim Hadriche cb45732965 Update RELEASING.md 2023-06-25 06:01:39 -04:00
Brahim Hadriche 9ccf1efee9 Add release steps 2023-06-25 05:58:43 -04:00
Brahim Hadriche 5a7ebf95bc Update README.md 2023-06-25 05:37:58 -04:00
Brahim Hadriche fef289a201 Screenshots (#87)
* Screenshots

* Update README.md

* fix links

* Web app

* Update README.md
2023-06-25 05:34:10 -04:00
Brahim Hadriche 98de5f223e Screenshots 2023-06-25 05:17:50 -04:00
84 changed files with 1499 additions and 515 deletions

No files matched your search

+7 -3
View File
@@ -2,7 +2,11 @@ name: Linter
on: on:
pull_request: pull_request:
branches: [ "main" ] branches: ["main"]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs: jobs:
lint: lint:
@@ -23,8 +27,8 @@ jobs:
uses: actions/setup-node@v3 uses: actions/setup-node@v3
with: with:
node-version: 18.x node-version: 18.x
cache: 'npm' cache: "npm"
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
+40 -10
View File
@@ -2,12 +2,16 @@ name: Release
on: on:
push: push:
branches: [ "main" ] branches: ["main"]
jobs: concurrency:
release: group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v3
@@ -16,21 +20,47 @@ jobs:
uses: actions/setup-node@v3 uses: actions/setup-node@v3
with: with:
node-version: 18.x node-version: 18.x
cache: 'npm' cache: "npm"
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Build Playlet - name: Build Playlet
run: npm run build:release:ci run: npm run build:release:ci
- name: Use Java 17
uses: actions/setup-java@v3
with:
distribution: "temurin"
java-version: "17"
- name: Download the Static Channel Analysis CLI
run: |
curl -sSL "https://devtools.web.roku.com/static-channel-analysis/sca-cmd.zip" -o sca-cmd.zip
unzip sca-cmd.zip
- name: Run Analysis on Playlet Lib
# Note: we don't set the exit code to on error, because sca treats the lib
# as a standalone app, and logs all sorts of errors that are not relevant to
# a Component Library.
# This run is simply to check if there's any interesting output comes up.
run: ./sca-cmd/bin/sca-cmd ./playlet/src/lib/playlet-lib.zip
- name: Run Analysis on Playlet App
run: ./sca-cmd/bin/sca-cmd ./release/playlet.zip --exit error
- name: Delete unstable release - name: Delete unstable release
uses: dev-drprasad/delete-tag-and-release@v1.0 uses: dev-drprasad/delete-tag-and-release@v1.0
with: with:
tag_name: unstable tag_name: unstable
github_token: ${{ secrets.GH_TOKEN }} github_token: ${{ secrets.GH_TOKEN }}
- name: Extract changelog
run: |
latest_release=$(awk 'BEGIN { RS="## \\[" } NR==2 { print "## ["$0 }' CHANGELOG.md)
echo -e "\n$latest_release" >> docs/unstable-changelog.md
- name: Create unstable release - name: Create unstable release
run: gh release create unstable ./release/playlet.zip ./playlet/src/lib/playlet-lib.zip --notes "This is an automated release." --prerelease --title unstable run: gh release create unstable ./release/playlet.zip ./playlet/src/lib/playlet-lib.zip --notes-file docs/unstable-changelog.md --prerelease --title unstable
env: env:
GH_TOKEN: ${{ secrets.GH_TOKEN }} GH_TOKEN: ${{ secrets.GH_TOKEN }}
+1 -1
View File
@@ -1,7 +1,7 @@
dist/ dist/
out/ out/
node_modules node_modules
.vscode/.env .env
**/roku_modules/** **/roku_modules/**
playlet-lib/src/www playlet-lib/src/www
playlet/src/lib/playlet-lib.zip playlet/src/lib/playlet-lib.zip
-1
View File
@@ -1 +0,0 @@
engine-strict=true
+15 -2
View File
@@ -4,7 +4,7 @@
{ {
"type": "brightscript", "type": "brightscript",
"request": "launch", "request": "launch",
"envFile": "${workspaceFolder}/.vscode/.env", "envFile": "${workspaceFolder}/.env",
"host": "${env:ROKU_DEV_TARGET}", "host": "${env:ROKU_DEV_TARGET}",
"password": "${env:ROKU_DEVPASSWORD}", "password": "${env:ROKU_DEVPASSWORD}",
"stopOnEntry": false, "stopOnEntry": false,
@@ -35,7 +35,7 @@
{ {
"type": "brightscript", "type": "brightscript",
"request": "launch", "request": "launch",
"envFile": "${workspaceFolder}/.vscode/.env", "envFile": "${workspaceFolder}/.env",
"host": "${env:ROKU_DEV_TARGET}", "host": "${env:ROKU_DEV_TARGET}",
"password": "${env:ROKU_DEVPASSWORD}", "password": "${env:ROKU_DEVPASSWORD}",
"stopOnEntry": false, "stopOnEntry": false,
@@ -57,6 +57,19 @@
"name": "Playlet Web (Dev)", "name": "Playlet Web (Dev)",
"request": "launch", "request": "launch",
"type": "node-terminal" "type": "node-terminal"
},
{
"type": "chrome",
"request": "launch",
"name": "Playlet Web (Chrome)",
"webRoot": "${workspaceFolder}/playlet-web/src"
}
],
"compounds": [
{
"name": "Playlet Web (Debug)",
"configurations": ["Playlet Web (Dev)", "Playlet Web (Chrome)"],
"stopAll": true
} }
] ]
} }
+2 -1
View File
@@ -1,4 +1,5 @@
{ {
"brightscript.bsdk": "node_modules/brightscript",
"brightscript.output.clearConsoleOnChannelStart": false, "brightscript.output.clearConsoleOnChannelStart": false,
"brightscript.bsdk": "node_modules/brighterscript",
"editor.formatOnSave": true
} }
+36
View File
@@ -5,6 +5,42 @@ 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.10.3] - 2023-07-24
### Added
- Support for saved playlists. By adding a playlist from a youtube channel to your Invidious profile, you can see the playlist on Playlet.
## [0.10.2] - 2023-07-10
### Added
- Links to the app info in web app
- Loading indicator for search page in web app
- Feedback link through email
- Scopes and expire fields to the Invidious auth token. This is to detect when a token is close to expiry, or if we have missing permissions.
### Fixed
- Video duration formatting in cast dialog
- (Removed) Workaround for Invidious token expiring due to misconfigured instance
- Crash when loading the home screen [#83](https://github.com/iBicha/playlet/issues/83)
- Performance of home screen in web app
- SponsorBlock segments where video duration is not provided (follow up to [#23](https://github.com/iBicha/playlet/pull/23))
- Focus with the settings input field
## [0.10.1] - 2023-06-28
### Added
- Support playing a video from a specific time (cast from phone, drag and drop, open in Invidious)
### Fixed
- A crash where the saved auth token is not in a valid format
- Video duration formatting for long videos
- A bug where app would lose focus when playing the next video (0.10.0 regression)
## [0.10.0] - 2023-06-25 ## [0.10.0] - 2023-06-25
### Added ### Added
+35 -55
View File
@@ -1,6 +1,8 @@
# Playlet # Playlet
<!-- markdownlint-disable MD033 -->
<p align="center"> <p align="center">
<img src="banner.png" style="display:block;text-align:center" alt="Playlet Logo" width="800"/> <img src="docs/banner.png" style="display:block;text-align:center" alt="Playlet Logo" width="800"/>
<br/><br/> <br/><br/>
<a href="https://github.com/iBicha/playlet/actions/workflows/release.yml?query=branch%3Amain"> <a href="https://github.com/iBicha/playlet/actions/workflows/release.yml?query=branch%3Amain">
<img alt="Build Status" src="https://img.shields.io/github/actions/workflow/status/iBicha/playlet/release.yml.svg?branch=main"/> <img alt="Build Status" src="https://img.shields.io/github/actions/workflow/status/iBicha/playlet/release.yml.svg?branch=main"/>
@@ -17,85 +19,60 @@
</a> </a>
</p> </p>
Playlet is an unofficial Youtube client for Roku 📺 Playlet is an unofficial Youtube client for Roku 📺
## Screenshots
<a href="./docs/screenshots/README.md">
| ![Screenshot](docs/screenshots/screenshot1.jpg) | ![Screenshot](docs/screenshots/screenshot2.jpg) | ![Screenshot](docs/screenshots/screenshot3.jpg) |
|-------------------------------------------------|-------------------------------------------------|-------------------------------------------------|
</a>
More under [Screenshots](./docs/screenshots/README.md)
## Installation
[Playlet on Roku channel store](https://channelstore.roku.com/en-ca/details/840aec36f51bfe6d96cf6db9055a372a/playlet)
## Features ## Features
- 🔥 No Ads (Not now, not ever) - 🔥 No Ads (Not now, not ever)
- 🕵️ No Tracking - 🕵️ No Tracking
- 🛡️ Privacy driven (uses Invidious backend) - 🛡️ Privacy driven (uses Invidious backend)
- ⚔️ SponsorBlock integration (skips undesirable sections in videos) - ⚔️ SponsorBlock integration (skips undesirable sections in videos)
- 📱 Cast from phone - 📱 Browse, search, and cast from phone using the web app
- 🔮 Picture-in-picture mode - 🔮 Picture-in-picture mode
- ⚡ Fast! [Check out how we compare with the official Youtube app](https://youtu.be/qmSvA-QQW20) - ⚡ Fast! [Check out how we compare with the official Youtube app](https://youtu.be/qmSvA-QQW20)
### Cast from phone ### Cast from phone
1. Open settings in Playlet
1. Open "Web app" tab in Playlet
1. Scan QR Code with Phone 1. Scan QR Code with Phone
1. Enter video ID or video url, and press Play button 1. Browse or search videos
1. Click the video and choose the "Play on TV" option
### Picture-in-picture ### Picture-in-picture
- When viewing a video in full screen, press ⬇️ (down) button on your remote to shrink the video - 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 - You can browser or search for videos while you watch
- To restore currently playing video to full screen, press the ✳️ (options) button - To restore currently playing video to full screen, press the ✳️ (options) button
### Customize Invidious instance ### Customize Invidious instance
1. Open settings in Playlet 1. Open settings in Playlet
1. Scan QR Code with Phone 1. Scan QR Code with Phone
1. Change the Invidious instance 1. Change the Invidious instance
1. You can also do this from the settings tab
## Screenshots
| ![](screenshot1.jpg) | ![](screenshot2.jpg) | ![](screenshot3.jpg) |
|----------------------|----------------------|----------------------|
## Installation
### Roku Store (Published app)
[Playlet on Roku channel store](https://channelstore.roku.com/en-ca/details/840aec36f51bfe6d96cf6db9055a372a/playlet)
Or use the link https://my.roku.com/account/add?channel=PLAYLET
### Sideloaded (Dev app)
#### Enable Roku Developer Mode
First, you need to enable developer mode on your Roku TV (if you have not done that already).
Using your Roku remote, enter the following sequence:
<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)
Make sure to remember the password you set during this step, you will need it later.
#### Gather your info
By now, you should have the following
- Your Roku Dev password (setup in the previous step)
- 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
#### Install Playlet (Manual)
1. Go to `https://github.com/iBicha/playlet/releases` and download `playlet.zip`
2. Open `http://REPLACE_IP_ADDRESS_HERE/` (e.g. http://192.168.1.2/) in your browser
3. If prompted for username and password
- The username is `rokudev`
- The password is whatever you set when you enabled Developer mode
4. Click on `Upload` button and select the `playlet.zip` file you downloaded in step 1
6. Click `Install with zip` button
- If you're updating the app (or you already have a dev channel) the button would say `Replace with zip`
## Development ## Development
1. `git clone https://github.com/iBicha/playlet.git`
1. `cd playlet`
1. `npm install`
Create a file under `playlet/.vscode/.env` containing: For everything related to Playlet app development, please see the [documentation](./docs/README.md)
```
ROKU_DEV_TARGET=REPLACE_IP_ADDRESS_HERE
ROKU_DEVPASSWORD=REPLACE_PASSWORD_HERE
```
Then you can open the project using VS Code and deploy to your Roku TV using the Debug button.
## Why Playlet ## Why Playlet
```
```none
playlet - noun playlet - noun
play•let /ˈplālət/ play•let /ˈplālət/
: a short play : a short play
@@ -111,5 +88,8 @@ By removing all the bloat, the ads, the tracking, we could end up with an even f
In any case, I hope you find **Playlet** useful, and pleasant to use. In any case, I hope you find **Playlet** useful, and pleasant to use.
## Disclaimer ## Disclaimer
**Playlet** does not serve or distribute any material from unauthorized sources.<br/> **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. **Playlet** is simply a frontend to other systems (such as [Invidious](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.
<!-- markdownlint-configure-file {"MD024": { "siblings_only": true } } -->
+2 -2
View File
@@ -23,8 +23,8 @@
"plugins": [ "plugins": [
"roku-log-bsc-plugin", "roku-log-bsc-plugin",
"@rokucommunity/bslint", "@rokucommunity/bslint",
"../tools/asynctask-plugin.ts", "../tools/bs-plugins/asynctask-plugin.ts",
"../tools/manifest-bsconst-debug-plugin.ts" "../tools/bs-plugins/manifest-bsconst-debug-plugin.ts"
], ],
"retainStagingDir": true, "retainStagingDir": true,
"require": [ "require": [
+324
View File
@@ -0,0 +1,324 @@
# Playlet documentation
This documents contains verious kinds of information related to Playlet development. It's a bit of a [brain dump](https://en.wiktionary.org/wiki/brain_dump) that I tried to keep structured.
- [Environment setup](#environment-setup)
- [Project setup](#project-setup)
- [Roku Developer mode](#roku-developer-mode)
- [Setting up Visual Studio Code](#setting-up-visual-studio-code)
- [Tools](#tools)
- [BrightScript Language Extension for VS Code](#brightscript-language-extension-for-vs-code)
- [RALE (Roku Advanced Layout Editor)](#rale-roku-advanced-layout-editor)
- [BrighterScript](#brighterscript)
- [BrighterScript Linter/Formatter](#brighterscript-linterformatter)
- [Playlet App](#playlet-app)
- [Why separate between Playlet and Playlet Lib?](#why-separate-between-playlet-and-playlet-lib)
- [Playlet Lib](#playlet-lib)
- [WebServer](#webserver)
- [Debug endpoints](#debug-endpoints)
- [Releases from Github](#releases-from-github)
- [Dev library hosted by VS Code Extension](#dev-library-hosted-by-vs-code-extension)
- [AsyncAwait Task Generator](#asyncawait-task-generator)
- [Feature flags](#feature-flags)
- [User preferences](#user-preferences)
- [Home page layout](#home-page-layout)
- [Playlet Web App](#playlet-web-app)
- [Svelte development](#svelte-development)
- [Tailwind/Daisy UI](#tailwinddaisy-ui)
- [API calls (proxy authenticated)](#api-calls-proxy-authenticated)
- [Developer settings](#developer-settings)
- [In case of a softlock](#in-case-of-a-softlock)
- [CI/CD](#cicd)
## Environment setup
### Project setup
```bash
git clone https://github.com/iBicha/playlet.git
cd playlet
npm install
```
### Roku Developer mode
To develop Roku applications, you need to enable Developer mode on your Roku device.
Using your Roku remote, enter the following sequence:
<!-- markdownlint-disable-next-line -->
<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)
Make sure to remember the password you set during this step, you will need it later.
### Setting up Visual Studio Code
Visual Studio Code is pretty much necessary for development.
> apologies if this is not your favorite IDE. Please do [share](https://github.com/iBicha/playlet/issues/new?title=I%20don%27t%20like%20VS%20Code) if you feel this should not be a requirement.
Once you have it installed, you probably want to install the recommened plugins for this project, such as [BrightScript Language extension for VSCode](https://marketplace.visualstudio.com/items?itemName=RokuCommunity.brightscript) and [Svelte for VS Code](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode)
Next, create a file `.env` containing the following:
```makefile
ROKU_DEV_TARGET=INSERT_IP_HERE
ROKU_DEVPASSWORD=INSERT_PASSWORD_HERE
```
Where `ROKU_DEV_TARGET` is the local ip address of your Roku device, and `ROKU_DEVPASSWORD` is the developer password from [Roku Developer mode](#roku-developer-mode).
Now from VS Code, press the Play button with the target `Playlet (dev)` selected. This should build and run Playlet on your device in dev mode.
## Tools
### BrightScript Language Extension for VS Code
The [BrightScript Language extension for VSCode](https://marketplace.visualstudio.com/items?itemName=RokuCommunity.brightscript) includes many useful tools for development and debugging. Includes things like
- Sending commands to the App
- Like getting the focused node, inspecting values, etc
- SceneGraph inspector
- Allows you to see the hiearchy of the scene, and even modify elements at runtime. Useful for quick tweaks or adjusting UI.
- Roku Registry
- Allows you to inspect the content of the [Registry](https://developer.roku.com/en-ca/docs/references/brightscript/components/roregistry.md)
Playlet is configured to have all these features available when ran in debug mode.
### RALE (Roku Advanced Layout Editor)
[The Roku Advanced Layout Editor, aka RALE](https://devtools.web.roku.com/roku-advanced-layout-editor/), is a tool that provides a hierarchical view of the node tree in a Roku Scene Graph channel.
It's a standalone application that you can optionally install.
It's sometimes useful when designing UI and inspecting values of nodes.
Well, if you do happen to use it, Playlet is configured to connect to RALE.
### BrighterScript
[BrighterScript](https://github.com/rokucommunity/brighterscript) is a community driven programming language compiles to BrightScript and has [useful features](https://github.com/rokucommunity/BrighterScript/blob/master/docs/readme.md). Playlet uses BrighterScript features a lot across the code base, and even implements a couple of BrighterScript plugins (More on that later).
### BrighterScript Linter/Formatter
Playlet uses [bslint](https://github.com/rokucommunity/bslint) and [brighterscript-formatter](https://github.com/rokucommunity/brighterscript-formatter).
You can use these commands to lint/format Playlet code:
```bash
npm run format
npm run format:fix
npm run lint
npm run lint:fix
```
## Playlet App
Playlet is split into two parts: `Playlet (the app)` and `Playlet Lib`.
Playlet (the app) is a regular Roku app, that uses a [ComponentLibrary](https://developer.roku.com/en-ca/docs/references/scenegraph/control-nodes/componentlibrary.md) to load the rest of the app from [Playlet Lib](#playlet-lib).
In a way, Playlet (the app) is a thin loader, while most of the logic lives in [Playlet Lib](#playlet-lib).
Playlet app is responsible for a few things:
- Load Playlet lib
- By default, it tries to load the latest version from Github
- If that fails (for example, if Github was down), it fallsback to loading an embedded copy of Playlet Lib
- `if Github was down` -> yes, this has happened in the past, and it did not stop Playlet for working.
- In dev mode, it loads playlet lib that's being served by [BrightScript Language Extension for VS Code](#brightscript-language-extension-for-vs-code)
- Once loaded, Playlet loads the `MainScene` from Playlet Lib
- Pass Launch parameters and Input parameters to Playlet Lib
- Show a loading screen and wait for Playlet Lib to hide it
That's pretty much it.
### Why separate between Playlet and Playlet Lib?
There are a few reasons we made this separation:
- Playlet relies on [Invidious](https://github.com/iv-org/invidious). Invidious tries to keep up with Youtube making changes to their platform, but sometimes, a breaking change happens the requires Playlet to react quickly. Releasing through the Roku Channel store can take days, or a week. During this time, Playlet would be not functional, and that's not acceptable.
- The ability to roll back: Sometimes an app breaking bug gets released. Allowing users to choose a seperate version is a flexible way to keep things working. Although right now rollbacks are behind a - hidden by default - developer menu, the reasoning still stands.
- It is simply easier to release: Releasing Playlet Lib on Github, and everyone receiving the latest version immediately, is very conveninct and less of a hassle, than going through the Roku Channel store.
- I've had instances where I was trying to pass the certfication for Playlet to publish it. One of the criterias is to pass a some automated tests. But the tests were failing because their system could not connect to their Roku test devices (connection keeps timing out). My only option was to keep trying over and over until it worked.
It might sound that Playlet Lib is just a workaround for the Roku Channel release process. But phrased differently, Roku Channel release process is not good enough of what we need for Playlet.
## Playlet Lib
Playlet Lib is a [ComponentLibrary](https://developer.roku.com/en-ca/docs/references/scenegraph/control-nodes/componentlibrary.md) that gets loaded by [Playlet App](#playlet-app). It containes pretty much all the logic needed to run the app.
### WebServer
Playlet lib comes equipped with a web server that runs on 8888 when the app starts. This server enables:
- The communication between Playlet and [Playlet Web App](#playlet-web-app)
- Through http calls, and even through web sockets for real time events
- Allows remotely casting videos, change preferences, etc
- Authentication using Invidious
The web server runs on a continiously running [Task](https://developer.roku.com/en-ca/docs/references/scenegraph/control-nodes/task.md) and uses a middeware system to manage routes, serving static files, [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), and more
#### Debug endpoints
Additionally, the web server exposes Web APIs in debug mode to help with debugging. To name a few examples:
- `/debug/pkg` to inspect files under Playlet App
- `/debug/libpkg` to inspect files under Playlet Lib
- `/debug/tmp` and `/debug/cachefs` to inspect files in temporary and cache
These are useful to see if the files and caching are working as expected
### Releases from Github
Since Component Libraries are simply zip files hosted some https endpoint, Github releases are used to host and deliever Playet Lib to users. By default, Playlet grabs `https://github.com/iBicha/playlet/releases/latest/download/playlet-lib.zip` and loads it, but this can be pointed to somewhere else, if for some reason the Github repository becomes unavailable.
### Dev library hosted by VS Code Extension
When in debug mode, Playlet lib is packaged and served locally on port 8080, and Playlet app would use it instead of the Playlet lib from Github. This is an important detail, because once you stop debugging in VS Code, the dev app on your Roku TV won't function anymore, with an error:
> Could not load Playlet component library from any of the following urls:
>
> - \[debug\] http://192.168.1.x:8080/playlet-lib.zip <!-- markdownlint-disable-line -->
> Please restart Playlet.
> If the problem persist, contact Playlet authors.
### AsyncAwait Task Generator
To implement functionality that runs in background threads, [Task](https://developer.roku.com/en-ca/docs/references/scenegraph/control-nodes/task.md)s must be used.
Setting up a task involes lots of boilerplate: setting up the task in an xml file, defining inputs and outputs, code to listen for a task to finish, and so on.
That's why there's a BrighterScript plugin that generates a task for a function with the attribute `@asynctask`.
In a separate file, define the task function:
```brighterscript
@asynctask
function MyBackgroundTask(input as object) as object
myVar = input.myVar
value = DoWork(myVar)
return {
value: value
}
end function
```
And use the function like so
```brighterscript
StartAsyncTask(MyBackgroundTask, {myVar: "some input"}, function(output as object) as void
if output.success
print(output.result.value)
end if
end function)
```
Although very useful, but this pattern might not be the best for long running tasks (like the Web Server) or other tasks that require task reuse. This is because `StartAsyncTask` create a new instance of the task every time.
### Feature flags
Playlet uses [bs_const](https://developer.roku.com/en-ca/docs/references/brightscript/language/conditional-compilation.md#manifest-constant) to define feature flags. The flags are usually for features that introduce a downside, or require further refinement.
### User preferences
Playlet uses a json file that lists user preferences. It should be under [playlet-lib/src/config/preferences.json](/playlet-lib/src/config/preferences.json)
This file defines the kind of preferences that users can change, such as autoplay, preferred quality, and so on.
This file is parsed at runtime and UI for the settings is generated. The same mechanism is used to Playlet and the Web App.
Additionally, The web server exposes the settings under `/api/preferences`, which can enable importing/exporting user preferences.
### Home page layout
When playlet starts, it shows a video feed in the screen. Subscription, Trending videos, and so on.
The layout is defined under [playlet-lib/src/config/default_home_layout.json](/playlet-lib/src/config/default_home_layout.json).
This could allow users to define custom layouts, so they can see what they find relevant in the home page. This can include Subscription, Trending, Popular videos, Search per keywords, or Playlists.
Additionally each feed has information on how it is fetched. For now, only Invidious can be data source, but other systems should be configured in the same way.
Invidious API definitions are defined under [playlet-lib/src/config/invidious_video_api.json](/playlet-lib/src/config/invidious_video_api.json), and Playlet parses these at runtime and make the right api calls to fetch the data.
Finally, this layout system is what allows both the BrightScript app and the Web app to display the same homepage.
## Playlet Web App
Playlet comes with a web app built with [Svelte](https://svelte.dev/). The web app can be used to browse videos, search, cast videos to TV, and even change preferences.
The web app gets served using the Playlet Web server. It also interact with the web apis from web server.
It's important to note that if Playlet is not ON (on your Roku device) or the TV is in screen saver mode, then the web app can't be used.
When Playlet gets built, several steps happen:
1. The web app gets kicked off first. The web app artifacts gets written to `playlet-lib/src/www`
1. Playlet lib gets built second. As part of the build pipeline, a copy of `playlet-lib.zip` is made under `playlet/src/lib/playlet-lib.zip`
1. Finally, Playlet app is built.
### Svelte development
The web app uses [Svelte](https://svelte.dev/), [Vite](https://vitejs.dev/) and [Typescript](https://www.typescriptlang.org/) primarily. It currently does not use [SvelteKit](https://kit.svelte.dev/), since it doesn't need some of the more advanced features that SvelteKit offers, such as routing or server-side rendering (SSR)
Since modifying the web app code requires building all three projects (playlet, playlet lib, and web app) this makes the iteration speed very slow, and we lose the benefits of web development, such as hot reloads.
For that reason, the recommeneded iteration when working on the dev app is:
1. Start `Playlet (dev)` (by selecting `Playlet (dev)` and pressing Play in VS Code)
1. Once Playlet starts, switch to `Playlet Web (dev)` and press play. Do not stop `Playlet (dev)`
1. The web app should start in the browser
You will notice that thr browser tab that just opened shows an url like `http://192.168.1.X:5173/?host=192.168.1.Y:8888`
This is because the web app will be served from Vite, while API calls to the playlet will be done to the Playlet lib webserver.
For debugging, choose the compound target `Playlet Web (Debug)`.
### Tailwind/Daisy UI
Playlet web app uses [Tailwind CSS](https://tailwindcss.com/) as its base styling library. Additionally, it uses [DaisyUI](https://daisyui.com/) as it offers a versatile set of components, and has built-in supports for themes.
### API calls (proxy authenticated)
When making authenticated calls to Invidious (for example to fetch the user Subscription feed) the Bearer token is needed.
In this case specifically, the web server acts as a proxy between Invidious and the web app. This is for a few reasons:
- CORS: Bearer token can't go through to Invidious from the web app (due to missing `Access-Control-Allow-Credentials` header)
- The web server is not secure: it's not on HTTPS
- It's best if the Invidious access token would not be served to the web app, and remain on the Roku device
For API calls that don't require authentication, the web app fetches data from invidious directly.
### Developer settings
To access developer settings, open the web app, and append the parameter `dev=1` to the url. Example:
```bash
http://192.168.1.107:8888/index.html?dev=1
```
This reveals an additional settings section in preferences. For now, it allows you to point to a different Github release other than the default `latest`.
This is mostly useful to QA the `unstable` release in a "production" setting before making it available to all users as the official "latest" version.
#### In case of a softlock
If the dev menu is used to load a custom Playlet lib url, but the lib does not have a functionality to revert back:
```bash
curl -d '' "http://$ROKU_DEV_TARGET:8060/launch/dev?clearPlayletLibUrls=true"
```
This will remove the custom lib, and revert to using default (latest release from Github).
## CI/CD
On pull requests, a Github action will run `lint:fix` and `format:fix` and push changes to the PR branch, to keep things tidy.
When merged to main branch, a Github action will build Playlet, run static analysis using Roku's [Static Channel Analysis tool](https://devtools.web.roku.com/#static-channel-analysis-tool), and release a new version tagged `unstable`, with the build artifacts attached, and changelog included.
Existing `unstable` release will be removed before creating a new one.
This makes [Releasing](./RELEASING.md) simpler.
+48
View File
@@ -0,0 +1,48 @@
<!-- markdownlint-disable MD036 -->
# Releasing
The release process for Playlet is very simple, since most of the work is automated.
The automation makes `unstable` releases.
```makefile
unstable release + QA = stable version
```
These are mostly the steps when releasing a new version:
## Playlet lib
- Create local branch `release/$VERSION` e.g. `release/0.10.0`
- Set version in package.json
- Update CHANGELOG.md section from `[Unreleased]` to `[$VERSION] - DATE`
- `npm run build:release`
- This should fail because there are uncommitted changes. This is expected.
- Commit changes
- Create pull request
- Title: `Release v$VERSION`
- Comment: `Release $VERSION \nIt should contain everything planned from #6`
- Wait for CI and merge
- Wait for CI on main branch to create the `unstable` release
- Edit `unstable` release
- Tag: `v$VERSION`
- Title: `v$VERSION`
- Body: the content from CHANGELOG.md for this version
- This should be already included, just remove the notes about testing the unstable release
- Uncheck `Set as a pre-release`
- Check `Set as the latest release`
- Click `update release`
- Update [Roadmap](https://github.com/iBicha/playlet/issues/6)
- If current versions says `Planned for $VERSION`, change it to `Released in $VERSION`
- Add a `Planned for $VERSION` for the next version
**The newest Playlet lib is now LIVE**
## Playlet
For releasing to the store (when needed), this is done following a Playlet lib release:
- Switch to main branch and pull changes - **match commit corresponding to the release.**
- `npm run build:release`
- This should create the signed package under `release/playlet.pkg`
- Upload to dashboard, and schedule a release (takes a couple of days)
View File
File renamed without changes.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 36 KiB

+15
View File
@@ -0,0 +1,15 @@
## Screenshots
### Home
![](./screenshot1.jpg)
### Search
![](./screenshot2.jpg)
### Settings
![](./screenshot3.jpg)
### Link to web app
![](./screenshot4.jpg)
### App info
![](./screenshot5.jpg)
### Web app
| ![](./screenshot6.png) | ![](./screenshot7.png) | ![](./screenshot8.png) |
|----------------------------------|----------------------------------|----------------------------------|
Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 358 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 362 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

+11
View File
@@ -0,0 +1,11 @@
<!-- markdownlint-disable MD041 -->
This is an automated release. It is generated when new code is pushed to the main branch.
To test this release:
- Open Playlet web app in dev mode (`http://ROKU_IP_ADDRESS:8888/index.html?dev=1`)
- Go to settings, and scroll down to `Developer settings`
- Set `Playlet Library version` to `unstable` and click `Apply`
- Restart Playlet
- You can verify that you're testing the `unstable` release in the `Info` tab in Playlet or the web app
+43 -16
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet", "name": "playlet",
"version": "0.10.0", "version": "0.10.3",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet", "name": "playlet",
"version": "0.10.0", "version": "0.10.3",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"bslib": "npm:@rokucommunity/bslib@^0.1.1", "bslib": "npm:@rokucommunity/bslib@^0.1.1",
@@ -14,12 +14,13 @@
"roku-requests": "^1.2.0" "roku-requests": "^1.2.0"
}, },
"devDependencies": { "devDependencies": {
"@rokucommunity/bslint": "^0.8.6", "@rokucommunity/bslint": "^0.8.7",
"@types/node": "^20.3.1", "@types/node": "^20.3.1",
"argparse": "^2.0.1", "argparse": "^2.0.1",
"brighterscript": "^0.65.1", "brighterscript": "^0.65.1",
"brighterscript-formatter": "^1.6.29", "brighterscript-formatter": "^1.6.29",
"convert-svg-to-png": "^0.6.4", "convert-svg-to-png": "^0.6.4",
"cross-fetch": "^4.0.0",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"express": "^4.18.2", "express": "^4.18.2",
"ip": "^1.1.8", "ip": "^1.1.8",
@@ -29,9 +30,6 @@
"shelljs": "^0.8.5", "shelljs": "^0.8.5",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"typescript": "^5.1.3" "typescript": "^5.1.3"
},
"engines": {
"node": "<19.0.0"
} }
}, },
"node_modules/@cspotcode/source-map-support": { "node_modules/@cspotcode/source-map-support": {
@@ -163,9 +161,9 @@
"dev": true "dev": true
}, },
"node_modules/@rokucommunity/bslint": { "node_modules/@rokucommunity/bslint": {
"version": "0.8.6", "version": "0.8.7",
"resolved": "https://registry.npmjs.org/@rokucommunity/bslint/-/bslint-0.8.6.tgz", "resolved": "https://registry.npmjs.org/@rokucommunity/bslint/-/bslint-0.8.7.tgz",
"integrity": "sha512-PsxZvOI9AvXO1SisJtSKLZUIosE1qhaoN8CgoLYqh4E2j72eL43cVCBj7Bhm1X3I9ykPEd9Wws8c+joca0m2uw==", "integrity": "sha512-GitkBck0mSSyksR/YQ9NUn+fZTWmk7+6hq2oyFM7F9zyx72zG1gNo/dM2WzrLf2UzVG5uSF2fMqizcYNI6IZRA==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"fs-extra": "^10.0.0", "fs-extra": "^10.0.0",
@@ -1341,12 +1339,12 @@
"dev": true "dev": true
}, },
"node_modules/cross-fetch": { "node_modules/cross-fetch": {
"version": "3.1.5", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz", "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.0.0.tgz",
"integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==", "integrity": "sha512-e4a5N8lVvuLgAWgnCrLr2PP0YyDOTHa9H/Rj54dirp61qXnNq46m82bRhNqIA5VccJtWBvPTFRV3TtvHUKPB1g==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"node-fetch": "2.6.7" "node-fetch": "^2.6.12"
} }
}, },
"node_modules/cross-platform-clear-console": { "node_modules/cross-platform-clear-console": {
@@ -2826,9 +2824,9 @@
} }
}, },
"node_modules/node-fetch": { "node_modules/node-fetch": {
"version": "2.6.7", "version": "2.6.12",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.12.tgz",
"integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", "integrity": "sha512-C/fGU2E8ToujUivIO0H+tpQ6HWo4eEmchoPIoXtxCrVghxdKq+QOHqEZW7tuP3KlV3bC8FRMO5nMCC7Zm1VP6g==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"whatwg-url": "^5.0.0" "whatwg-url": "^5.0.0"
@@ -3308,6 +3306,15 @@
"node": ">=10.18.1" "node": ">=10.18.1"
} }
}, },
"node_modules/puppeteer/node_modules/cross-fetch": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz",
"integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==",
"dev": true,
"dependencies": {
"node-fetch": "2.6.7"
}
},
"node_modules/puppeteer/node_modules/debug": { "node_modules/puppeteer/node_modules/debug": {
"version": "4.3.4", "version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
@@ -3331,6 +3338,26 @@
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
"dev": true "dev": true
}, },
"node_modules/puppeteer/node_modules/node-fetch": {
"version": "2.6.7",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
"integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
"dev": true,
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/qs": { "node_modules/qs": {
"version": "6.11.0", "version": "6.11.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz",
+6 -6
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet", "name": "playlet",
"version": "0.10.0", "version": "0.10.3",
"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",
@@ -14,6 +14,7 @@
"brighterscript": "^0.65.1", "brighterscript": "^0.65.1",
"brighterscript-formatter": "^1.6.29", "brighterscript-formatter": "^1.6.29",
"convert-svg-to-png": "^0.6.4", "convert-svg-to-png": "^0.6.4",
"cross-fetch": "^4.0.0",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"express": "^4.18.2", "express": "^4.18.2",
"ip": "^1.1.8", "ip": "^1.1.8",
@@ -24,9 +25,6 @@
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"typescript": "^5.1.3" "typescript": "^5.1.3"
}, },
"engines": {
"node": "<19.0.0"
},
"ropm": { "ropm": {
"rootDir": "playlet-lib/src", "rootDir": "playlet-lib/src",
"noprefix": [ "noprefix": [
@@ -47,8 +45,10 @@
"build:lib:dev": "npm run build:lib -- --debug=true", "build:lib:dev": "npm run build:lib -- --debug=true",
"build:lib:prod": "npm run build:lib -- --debug=false --sourceMap=false", "build:lib:prod": "npm run build:lib -- --debug=false --sourceMap=false",
"build:web": "cd playlet-web && npm run build", "build:web": "cd playlet-web && npm run build",
"lint": "bslint --project playlet-lib/bsconfig.lint.json --lintConfig config/bslint.jsonc && bslint --project playlet/bsconfig.lint.json --lintConfig config/bslint.jsonc", "lint:app": "bslint --project playlet/bsconfig.lint.json --lintConfig config/bslint.jsonc",
"lint:fix": "npm run lint -- --fix", "lint:lib": "bslint --project playlet-lib/bsconfig.lint.json --lintConfig config/bslint.jsonc",
"lint": "npm run lint:lib && npm run lint:app",
"lint:fix": "npm run lint:lib -- --fix && npm run lint:app -- --fix",
"format:base": "bsfmt \"playlet/src/**/*.brs\" \"playlet/src/**/*.bs\" \"!playlet/src/components/lib/**/*\" \"!playlet/src/source/lib/**/*\" \"!**/bslib.brs\" \"!**/roku_modules/**/*\" \"playlet-lib/src/**/*.brs\" \"playlet-lib/src/**/*.bs\" \"!playlet-lib/src/components/lib/**/*\" \"!playlet-lib/src/source/lib/**/*\" \"!**/bslib.brs\" \"!**/roku_modules/**/*\" --bsfmt-path \"config/bsfmt.jsonc\"", "format:base": "bsfmt \"playlet/src/**/*.brs\" \"playlet/src/**/*.bs\" \"!playlet/src/components/lib/**/*\" \"!playlet/src/source/lib/**/*\" \"!**/bslib.brs\" \"!**/roku_modules/**/*\" \"playlet-lib/src/**/*.brs\" \"playlet-lib/src/**/*.bs\" \"!playlet-lib/src/components/lib/**/*\" \"!playlet-lib/src/source/lib/**/*\" \"!**/bslib.brs\" \"!**/roku_modules/**/*\" --bsfmt-path \"config/bsfmt.jsonc\"",
"format": "npm run format:base -- --check", "format": "npm run format:base -- --check",
"format:fix": "npm run format:base -- --write", "format:fix": "npm run format:base -- --write",
@@ -59,7 +59,7 @@ function StartFetchTask() as void
' TODO: this whole logic is not good. ' TODO: this whole logic is not good.
' The view should have placeholder, and child nodes get replaced as ' The view should have placeholder, and child nodes get replaced as
' They get ready. ' They get ready.
if output = invalid if output = invalid or not output.success
StartFetchTask() StartFetchTask()
return return
end if end if
+7 -4
View File
@@ -113,8 +113,11 @@ function OnWebServerLogin()
m.homeGridScreen.refresh = true m.homeGridScreen.refresh = true
end function end function
function OnWebServerCommand() function OnWebServerCommand() as void
if m.serverTask.command.StartsWith("play:") if m.serverTask.command = invalid or m.serverTask.command.command = invalid
return
end if
if m.serverTask.command.command = "play"
sender = m.videoContainer.sender ?? m.currentFocued sender = m.videoContainer.sender ?? m.currentFocued
if m.videoContainer.fullscreen if m.videoContainer.fullscreen
dialog = m.top.getScene().dialog dialog = m.top.getScene().dialog
@@ -122,7 +125,7 @@ function OnWebServerCommand()
dialog.close = true dialog.close = true
end if end if
end if end if
PlayVideo(m.serverTask.command.Mid(5), { sender: sender }) PlayVideo(m.serverTask.command.videoId, { sender: sender, timestamp: m.serverTask.command.timestamp })
end if end if
end function end function
@@ -146,5 +149,5 @@ function PlayVideoFromArgs(args as object) as void
end if end if
sender = m.videoContainer.sender ?? m.currentFocued sender = m.videoContainer.sender ?? m.currentFocued
PlayVideo(args.contentId, { sender: sender }) PlayVideo(args.contentId, { sender: sender, timestamp: args.timestamp })
end function end function
@@ -275,18 +275,22 @@ function OnkeyEvent(key as string, press as boolean) as boolean
end function end function
function GetFocusedControl() as object function GetFocusedControl() as object
focusedChild = m.top.focusedChild node = m.top.focusedChild
if focusedChild = invalid if node = invalid
return invalid return invalid
end if end if
while not focusedChild.id.StartsWith("Control") while not node.id.StartsWith("Control")
focusedChild = focusedChild.focusedChild child = node.focusedChild
if focusedChild = invalid if child = invalid
return invalid return invalid
end if end if
if node.isSameNode(child)
return invalid
end if
node = child
end while end while
return focusedChild return node
end function end function
function MenuGoLeft() as boolean function MenuGoLeft() as boolean
@@ -299,6 +303,9 @@ end function
function MenuNavigate(direction as integer) as boolean function MenuNavigate(direction as integer) as boolean
focusedControl = GetFocusedControl() focusedControl = GetFocusedControl()
if focusedControl = invalid
return false
end if
container = focusedControl.getParent() container = focusedControl.getParent()
containerParent = container.getParent() containerParent = container.getParent()
containerCount = containerParent.getChildCount() containerCount = containerParent.getChildCount()
@@ -3,7 +3,6 @@ function Init()
m.top.observeField("focusedChild", "OnFocusChanged") m.top.observeField("focusedChild", "OnFocusChanged")
m.top.observeField("value", "OnValueChanged") m.top.observeField("value", "OnValueChanged")
m.top.observeField("settings", "OnSettingsScreen") m.top.observeField("settings", "OnSettingsScreen")
m.keyboardWasClosedByButton = false
end function end function
function OnSettingsScreen() function OnSettingsScreen()
@@ -45,15 +44,9 @@ function OnButtonSelected(event as object)
if buttonSelected = 0 if buttonSelected = 0
m.top.value = keyboard.text m.top.value = keyboard.text
end if end if
m.keyboardWasClosedByButton = true
keyboard.close = true keyboard.close = true
end function end function
function OnKeyboardClosed() as void function OnKeyboardClosed() as void
' The keyboard was closed by something else (like cast from web app)
' In this case, we do nothing, since the focus might be moved to the video player
if not m.keyboardWasClosedByButton
return
end if
m.top.settings@.MenuNavigate(-1) m.top.settings@.MenuNavigate(-1)
end function end function
@@ -3,26 +3,14 @@ import "pkg:/source/services/SponsorBlock.bs"
@asynctask @asynctask
function SponsorBlockTask(input as object) as object function SponsorBlockTask(input as object) as object
videoId = input.videoId videoId = input.videoId
lengthSeconds = input.metadata.lengthSeconds
sponsorBlockResponse = SponsorBlock.GetSkipSegmentsForVideo(videoId) skipSegments = SponsorBlock.GetSkipSegmentsForVideo(videoId)
barPath = invalid barPath = invalid
skipSegments = []
if sponsorBlockResponse <> invalid
for each segment in sponsorBlockResponse
if segment.videoDuration > 0
skipSegments.push(segment)
end if
end for
end if
if skipSegments.Count() = 0
skipSegments = invalid
end if
if skipSegments <> invalid if skipSegments <> invalid
barPath = `tmp:/sponsorblock_bar_${videoId}.png` barPath = `tmp:/sponsorblock_bar_${videoId}.png`
SponsorBlock.GenerateProgressBarBackground(skipSegments, barPath) SponsorBlock.GenerateProgressBarBackground(skipSegments, lengthSeconds, barPath)
end if end if
return { return {
@@ -7,11 +7,16 @@ import "pkg:/components/VideoPlayer/MarkVideoWatchedTask.bs"
function PlayVideo(videoId as string, args = invalid as object) function PlayVideo(videoId as string, args = invalid as object)
sender = args?.sender sender = args?.sender
metadata = args?.metadata metadata = args?.metadata
timestamp = args?.timestamp
if metadata <> invalid and GetInterface(metadata, "ifSGNodeField") <> invalid if metadata <> invalid and GetInterface(metadata, "ifSGNodeField") <> invalid
metadata = args.metadata.getFields() metadata = args.metadata.getFields()
end if end if
if timestamp = invalid
timestamp = 0
end if
width = 1280 width = 1280
height = 720 height = 720
translation = [0.0, 0.0] translation = [0.0, 0.0]
@@ -21,14 +26,18 @@ function PlayVideo(videoId as string, args = invalid as object)
height = videoContainer.videoPlayer.height height = videoContainer.videoPlayer.height
translation = videoContainer.videoPlayer.translation translation = videoContainer.videoPlayer.translation
end if end if
previousSender = videoContainer.sender
CloseVideo(false) CloseVideo(false)
if sender <> invalid if sender <> invalid
videoContainer.sender = sender videoContainer.sender = sender
else
videoContainer.sender = previousSender
end if end if
videoContainer.videoPlayer = videoContainer.createChild("VideoPlayer") videoContainer.videoPlayer = videoContainer.createChild("VideoPlayer")
videoContainer.insertChild(videoContainer.videoPlayer, 0) videoContainer.insertChild(videoContainer.videoPlayer, 0)
videoContainer.videoPlayer.id = "VideoPlayer" videoContainer.videoPlayer.id = "VideoPlayer"
videoContainer.videoPlayer.metadata = metadata videoContainer.videoPlayer.metadata = metadata
videoContainer.videoPlayer.timestamp = timestamp
videoContainer.videoPlayer.videoId = videoId videoContainer.videoPlayer.videoId = videoId
videoContainer.videoPlayer.width = width videoContainer.videoPlayer.width = width
videoContainer.videoPlayer.height = height videoContainer.videoPlayer.height = height
@@ -97,6 +97,9 @@ function OnVideoDetailsTaskResults(output as object) as void
else if isAssocArray(metadata.data) else if isAssocArray(metadata.data)
message += `\nError: ${FormatJson(metadata.data)}` message += `\nError: ${FormatJson(metadata.data)}`
end if end if
if isstr(metadata.failureReason)
message += `\nError: ${metadata.failureReason}`
end if
ShowDialog(message, "Video load fail") ShowDialog(message, "Video load fail")
CloseVideo() CloseVideo()
return return
@@ -150,6 +153,8 @@ function OnVideoDetailsTaskResults(output as object) as void
m.top.control = "play" m.top.control = "play"
m.videoContainer@.watchedVideosAdd(videoId) m.videoContainer@.watchedVideosAdd(videoId)
StartSponsorBlockTask()
end function end function
function AddDashUrls(playletStreamUrls as object, metadata as object, settings as object) as void function AddDashUrls(playletStreamUrls as object, metadata as object, settings as object) as void
@@ -286,8 +291,11 @@ function OnVideoPlayerStateChange() as void
' If we successfully played the video, then any error that comes later is not due to a 403 (FORBIDDEN). ' If we successfully played the video, then any error that comes later is not due to a 403 (FORBIDDEN).
' This is to reduce false positives, as we do not want retry another link if the first link is working fine. ' This is to reduce false positives, as we do not want retry another link if the first link is working fine.
if state = "playing" if state = "playing" and not m.videoPlayingSuccess
m.videoPlayingSuccess = true m.videoPlayingSuccess = true
if m.top.timestamp <> 0
m.top.seek = m.top.timestamp
end if
end if end if
if state = "error" if state = "error"
@@ -7,6 +7,7 @@
<field id="chapter" type="string" alias="chapterLabel.text" /> <field id="chapter" type="string" alias="chapterLabel.text" />
<field id="videoId" type="string" /> <field id="videoId" type="string" />
<field id="metadata" type="assocarray" /> <field id="metadata" type="assocarray" />
<field id="timestamp" type="integer" />
</interface> </interface>
<children> <children>
<Label <Label
@@ -18,7 +18,6 @@ function SetupSponsorBlock() as void
m.top.trickPlayBar.observeField("visible", "OnTrickPlayBarVisible") m.top.trickPlayBar.observeField("visible", "OnTrickPlayBarVisible")
m.chapterLabelTimer = m.top.findNode("chapterLabelTimer") m.chapterLabelTimer = m.top.findNode("chapterLabelTimer")
m.chapterLabelTimer.observeField("fire", "OnChapterLabelTimer") m.chapterLabelTimer.observeField("fire", "OnChapterLabelTimer")
m.top.observeField("videoId", "StartSponsorBlockTask")
end function end function
function LoadSponsorBlockSettings() as void function LoadSponsorBlockSettings() as void
@@ -103,12 +102,19 @@ function UpdateSponsorBlockChapter(time as integer) as void
m.top.chapter = "" m.top.chapter = ""
end function end function
function StartSponsorBlockTask() function StartSponsorBlockTask() as void
if not m.sponsorBlockEnabled = true
return
end if
if m.sponsorBlockTask <> invalid if m.sponsorBlockTask <> invalid
m.sponsorBlockTask.control = "stop" m.sponsorBlockTask.control = "stop"
end if end if
m.sponsorBlockTask = StartAsyncTask(SponsorBlockTask, { videoId: m.top.videoId }, OnSponsorBlockTaskResults) m.sponsorBlockTask = StartAsyncTask(SponsorBlockTask, {
videoId: m.top.videoId,
metadata: m.top.content.metadata
}, OnSponsorBlockTaskResults)
end function end function
function OnSponsorBlockTaskResults(output as object) function OnSponsorBlockTaskResults(output as object)
@@ -33,7 +33,7 @@ function OnContentSet() as void
else else
m.top.FindNode("liveRect").visible = false m.top.FindNode("liveRect").visible = false
if content.lengthSeconds <> invalid and content.lengthSeconds <> 0 if content.lengthSeconds <> invalid and content.lengthSeconds <> 0
m.top.FindNode("durationLabel").text = TimeUtils.GetFormattedTime(content.lengthSeconds) SetDurationText(TimeUtils.GetFormattedTime(content.lengthSeconds))
m.top.FindNode("durationRect").visible = true m.top.FindNode("durationRect").visible = true
else else
m.top.FindNode("durationRect").visible = false m.top.FindNode("durationRect").visible = false
@@ -42,6 +42,18 @@ function OnContentSet() as void
end function end function
function SetDurationText(text as string)
label = m.top.FindNode("durationLabel")
rect = m.top.FindNode("durationRect")
rectParent = rect.getParent()
label.text = text
size = label.localBoundingRect()
rect.width = size.width + 16
rect.translation = [rectParent.width - rect.width, 162]
end function
function OnThumbnailLoadFailed() as void function OnThumbnailLoadFailed() as void
if m.thumbnail.loadStatus <> "failed" if m.thumbnail.loadStatus <> "failed"
return return
@@ -17,18 +17,18 @@
<Rectangle <Rectangle
id="durationRect" id="durationRect"
width="60" width="60"
height="25" height="26"
color="0x000000" color="0x000000"
opacity="0.8" opacity="0.8"
translation="[290, 162]" translation="[290, 162]"
> >
<Label <Label
width="60" height="26"
height="25"
id="durationLabel" id="durationLabel"
horizAlign="center" horizAlign="center"
vertAlign="center" vertAlign="center"
font="font:SmallestSystemFont" font="font:SmallestSystemFont"
translation="[8, 0]"
/> />
</Rectangle> </Rectangle>
<Rectangle <Rectangle
@@ -23,8 +23,7 @@ namespace Http
response.Default(204, "OK") response.Default(204, "OK")
return true return true
else if payload.command = "play" else if payload.command = "play"
videoId = payload.videoId server.task.top.command = payload
server.task.top.command = `play:${videoId}`
response.Default(204, "OK") response.Default(204, "OK")
return true return true
else if payload.command = "set-playlet-lib-urls" else if payload.command = "set-playlet-lib-urls"
@@ -17,7 +17,6 @@ namespace Http
v = request.query.v v = request.query.v
local = request.query.local local = request.query.local
instance = InvidiousSettings.GetCurrentInstance()
metadata = router.GetVideoMetadata(context, v) metadata = router.GetVideoMetadata(context, v)
dashUrl = Invidious.GetVideoDashUrl(v, local <> invalid) dashUrl = Invidious.GetVideoDashUrl(v, local <> invalid)
@@ -28,10 +27,6 @@ namespace Http
resp = Requests().get(dashUrl, { parseJson: false }) resp = Requests().get(dashUrl, { parseJson: false })
text = resp.text ?? "" text = resp.text ?? ""
if resp.statuscode = 200 and local = "true"
' TODO: no longer needed, remove after 6 months of https://github.com/iv-org/invidious/pull/3554
text = text.Replace("<BaseURL>/videoplayback", `<BaseURL>${instance}/videoplayback`)
end if
if resp.statuscode = 200 and metadata <> invalid if resp.statuscode = 200 and metadata <> invalid
text = router.InjectStoryBoard(router, text, metadata) text = router.InjectStoryBoard(router, text, metadata)
@@ -19,12 +19,17 @@ namespace Http
token = request.query["token"].DecodeUri().DecodeUriComponent() token = request.query["token"].DecodeUri().DecodeUriComponent()
referer = request.query["ref"].DecodeUri() referer = request.query["ref"].DecodeUri()
username = request.query["username"] username = request.query["username"]
' TODO: remove null check after 6 months of https://github.com/iv-org/invidious/pull/3603 scopes = request.query["scopes"]
expire = request.query["expire"]
if username <> invalid if username <> invalid
username = username.DecodeUriComponent().DecodeUriComponent() username = username.DecodeUriComponent().DecodeUriComponent()
end if end if
if scopes <> invalid
scopes = scopes.DecodeUriComponent()
end if
InvidiousSettings.SetAuthToken(token, referer, username) InvidiousSettings.SetAuthToken(token, referer, username, scopes, expire)
server.task.top.login = true server.task.top.login = true
end if end if
response.Redirect("/") response.Redirect("/")
@@ -24,11 +24,15 @@ 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 = "libpkg:/www" m.settings.WwwRoot = "libpkg:/www"
' Short interval to keep polling on web socket messages
m.settings.Timeout = 500
m.server = new Http.HttpServer(m.settings, m) m.server = new Http.HttpServer(m.settings, m)
' TODO: server hangs sometimes when timeout is long. Need to investigate
m.settings.Timeout = 500
#if WEB_SOCKETS #if WEB_SOCKETS
' Short interval to keep polling on web socket messages
m.settings.Timeout = 500
m.websocket = new Web.WebSocketServer() m.websocket = new Web.WebSocketServer()
m.websocket.OnMessage(function(context as object) m.websocket.OnMessage(function(context as object)
connection = context.connection connection = context.connection
@@ -45,6 +49,14 @@ function WebServerLoop()
return true return true
end function) end function)
' Redirect to new UI in case someone opens this
' TODO: Remove this on September 2023
homeRouter.Get("/index.v1.html", function(context as object) as boolean
response = context.response
response.Redirect("/index.html")
return true
end function)
#if DEBUG #if DEBUG
allowedOrigin = "*" allowedOrigin = "*"
#else #else
@@ -84,9 +96,10 @@ function WebServerLoop()
while true while true
m.server.PreWait() m.server.PreWait()
m.websocket.Poll() #if WEB_SOCKETS
m.websocket.Poll()
#end if
msg = wait(timeout, msgPort) msg = wait(timeout, msgPort)
msg = wait(0, m.port)
msgType = type(msg) msgType = type(msg)
if msgType = "roSocketEvent" or msg = invalid if msgType = "roSocketEvent" or msg = invalid
m.server.PostWait() m.server.PostWait()
@@ -3,6 +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" /> <field id="command" type="assocarray" alwaysNotify="true" />
</interface> </interface>
</component> </component>
@@ -17,10 +17,9 @@ end function
function QRModes() as object function QRModes() as object
return { return {
MODE_NUMERIC : 1 << 0 MODE_NUMERIC: 1 << 0
MODE_ALPHANUMERIC : 1 << 1 MODE_ALPHANUMERIC: 1 << 1
MODE_BYTE : 1 << 2 MODE_BYTE: 1 << 2
MODE_KANJI : 1 << 3
} }
end function end function
@@ -59,7 +58,7 @@ function QRMath() as object
LOG_TABLE[EXP_TABLE[i]] = i LOG_TABLE[EXP_TABLE[i]] = i
end for end for
m.QRMath.glog = function (n as integer) as dynamic m.QRMath.glog = function(n as integer) as dynamic
if n < 1 if n < 1
' print "ERROR: invalid n passed to glog", n ' print "ERROR: invalid n passed to glog", n
return invalid return invalid
@@ -68,7 +67,7 @@ function QRMath() as object
return m.LOG_TABLE[n] return m.LOG_TABLE[n]
end function end function
m.QRMath.gexp = function (n as integer) as integer m.QRMath.gexp = function(n as integer) as integer
while n < 0 while n < 0
n += 255 n += 255
end while end while
@@ -112,7 +111,7 @@ function QRPolynomial(num as object, shift as integer) as object
QRMath: QRMath() QRMath: QRMath()
} }
result.getAt = function (index as integer) as integer result.getAt = function(index as integer) as integer
if m._num[index] = invalid if m._num[index] = invalid
return 0 return 0
else else
@@ -120,11 +119,11 @@ function QRPolynomial(num as object, shift as integer) as object
end if end if
end function end function
result.getLength = function () as integer result.getLength = function() as integer
return m._num.count() return m._num.count()
end function end function
result.multiply = function (e) as object result.multiply = function(e) as object
num = createObject("roArray", m.getLength() + e.getLength() - 1, false) num = createObject("roArray", m.getLength() + e.getLength() - 1, false)
for i = 0 to m.getLength() - 1 step 1 for i = 0 to m.getLength() - 1 step 1
@@ -132,14 +131,14 @@ function QRPolynomial(num as object, shift as integer) as object
if num[i + j] = invalid if num[i + j] = invalid
num[i + j] = 0 num[i + j] = 0
end if end if
num[i + j] = qrXOR(num[i + j], m.QRMath.gexp(m.QRMath.glog(m.getAt(i)) + m.QRMath.glog(e.getAt(j)))) num[i + j] = qrXOR(num[i + j], m.QRMath.gexp(m.QRMath.glog(m.getAt(i)) + m.QRMath.glog(e.getAt(j))))
end for end for
end for end for
return QRPolynomial(num, 0) return QRPolynomial(num, 0)
end function end function
result.modulo = function (e) as object result.modulo = function(e) as object
if m.getLength() - e.getLength() < 0 if m.getLength() - e.getLength() < 0
return m return m
end if end if
@@ -165,36 +164,36 @@ end function
function QRMaskFunctions() as object function QRMaskFunctions() as object
result = {} result = {}
result.PATTERN000 = function (i, j) as boolean result.PATTERN000 = function(i, j) as boolean
return (i + j) MOD 2 = 0 return (i + j) mod 2 = 0
end function end function
result.PATTERN001 = function (i, _j) as boolean result.PATTERN001 = function(i, _j) as boolean
return i MOD 2 = 0 return i mod 2 = 0
end function end function
result.PATTERN010 = function (_i, j) as boolean result.PATTERN010 = function(_i, j) as boolean
return j MOD 3 = 0 return j mod 3 = 0
end function end function
result.PATTERN011 = function (i, j) as boolean result.PATTERN011 = function(i, j) as boolean
return (i + j) MOD 3 = 0 return (i + j) mod 3 = 0
end function end function
result.PATTERN100 = function (i, j) as boolean result.PATTERN100 = function(i, j) as boolean
return ((i \ 2) + (j \ 3)) MOD 2 = 0 return ((i \ 2) + (j \ 3)) mod 2 = 0
end function end function
result.PATTERN101 = function (i, j) as boolean result.PATTERN101 = function(i, j) as boolean
return ((i * j) MOD 2) + ((i * j) MOD 3) = 0 return ((i * j) mod 2) + ((i * j) mod 3) = 0
end function end function
result.PATTERN110 = function (i, j) as boolean result.PATTERN110 = function(i, j) as boolean
return (((i * j) MOD 2) + ((i * j) MOD 3)) MOD 2 = 0 return (((i * j) mod 2) + ((i * j) mod 3)) mod 2 = 0
end function end function
result.PATTERN111 = function (i, j) as boolean result.PATTERN111 = function(i, j) as boolean
return (((i * j) MOD 3) + ((i + j) MOD 2)) MOD 2 = 0 return (((i * j) mod 3) + ((i + j) mod 2)) mod 2 = 0
end function end function
return result return result
@@ -266,7 +265,7 @@ function QRUtil() as object
m.QRUtil = util m.QRUtil = util
util.getBCHDigit = function (data as integer) as integer util.getBCHDigit = function(data as integer) as integer
digit = 0 digit = 0
data = abs(data) data = abs(data)
while data <> 0 while data <> 0
@@ -279,15 +278,15 @@ function QRUtil() as object
util.G15_BCHDigit = util.getBCHDigit(util.G15) util.G15_BCHDigit = util.getBCHDigit(util.G15)
util.G18_BCHDigit = util.getBCHDigit(util.G18) util.G18_BCHDigit = util.getBCHDigit(util.G18)
util.getBCHTypeInfo = function (data as integer) as integer util.getBCHTypeInfo = function(data as integer) as integer
d = data << 10 d = data << 10
while m.getBCHDigit(d) - m.G15_BCHDigit >= 0 while m.getBCHDigit(d) - m.G15_BCHDigit >= 0
d = qrXOR(d, (m.G15 << (m.getBCHDigit(d) - m.G15_BCHDigit))) d = qrXOR(d, (m.G15 << (m.getBCHDigit(d) - m.G15_BCHDigit)))
end while end while
return qrXOR((data << 10) or d, m.G15_MASK) return qrXOR((data << 10) or d, m.G15_MASK)
end function end function
util.getBCHTypeNumber = function (data as integer) as integer util.getBCHTypeNumber = function(data as integer) as integer
d = data << 12 d = data << 12
while m.getBCHDigit(d) - m.G18_BCHDigit >= 0 while m.getBCHDigit(d) - m.G18_BCHDigit >= 0
d = qrXOR(d, (m.G18 << (m.getBCHDigit(d) - m.G18_BCHDigit))) d = qrXOR(d, (m.G18 << (m.getBCHDigit(d) - m.G18_BCHDigit)))
@@ -295,11 +294,11 @@ function QRUtil() as object
return (data << 12) or d return (data << 12) or d
end function end function
util.getPatternPosition = function (typeNumber as integer) as object util.getPatternPosition = function(typeNumber as integer) as object
return m.PATTERN_POSITION_TABLE[typeNumber - 1] return m.PATTERN_POSITION_TABLE[typeNumber - 1]
end function end function
util.getMaskFunction = function (maskPattern as integer) as function util.getMaskFunction = function(maskPattern as integer) as function
masks = QRMaskFunctions() masks = QRMaskFunctions()
patterns = QRMaskPatterns() patterns = QRMaskPatterns()
@@ -315,7 +314,7 @@ function QRUtil() as object
return masks[maskId] return masks[maskId]
end function end function
util.getErrorCorrectPolynomial = function (errorCorrectLength as integer) as object util.getErrorCorrectPolynomial = function(errorCorrectLength as integer) as object
a = QRPolynomial([1], 0) a = QRPolynomial([1], 0)
for i = 0 to errorCorrectLength - 1 step 1 for i = 0 to errorCorrectLength - 1 step 1
a = a.multiply(QRPolynomial([1, m.QRMath.gexp(i)], 0)) a = a.multiply(QRPolynomial([1, m.QRMath.gexp(i)], 0))
@@ -323,7 +322,7 @@ function QRUtil() as object
return a return a
end function end function
util.getLengthInBits = function (mode as integer, typeNumber as integer) as integer util.getLengthInBits = function(mode as integer, typeNumber as integer) as integer
modes = QRModes() modes = QRModes()
if 1 <= typeNumber and typeNumber < 10 if 1 <= typeNumber and typeNumber < 10
@@ -331,19 +330,16 @@ function QRUtil() as object
if mode = modes.MODE_NUMERIC then return 10 if mode = modes.MODE_NUMERIC then return 10
if mode = modes.MODE_ALPHANUMERIC then return 9 if mode = modes.MODE_ALPHANUMERIC then return 9
if mode = modes.MODE_BYTE then return 8 if mode = modes.MODE_BYTE then return 8
if mode = modes.MODE_KANJI then return 8
else if typeNumber < 27 else if typeNumber < 27
' 10 - 26 ' 10 - 26
if mode = modes.MODE_NUMERIC then return 12 if mode = modes.MODE_NUMERIC then return 12
if mode = modes.MODE_ALPHANUMERIC then return 11 if mode = modes.MODE_ALPHANUMERIC then return 11
if mode = modes.MODE_BYTE then return 16 if mode = modes.MODE_BYTE then return 16
if mode = modes.MODE_KANJI then return 10
else if typeNumber < 41 else if typeNumber < 41
' 27 - 40 ' 27 - 40
if mode = modes.MODE_NUMERIC then return 14 if mode = modes.MODE_NUMERIC then return 14
if mode = modes.MODE_ALPHANUMERIC then return 13 if mode = modes.MODE_ALPHANUMERIC then return 13
if mode = modes.MODE_BYTE then return 16 if mode = modes.MODE_BYTE then return 16
if mode = modes.MODE_KANJI then return 12
end if end if
print "Invalid mode and/or type", mode, typeNumber print "Invalid mode and/or type", mode, typeNumber
@@ -12,7 +12,7 @@
<field id="status" type="string" value="init" /><!-- can be one of: 'init', 'loading', 'ready' --> <field id="status" type="string" value="init" /><!-- can be one of: 'init', 'loading', 'ready' -->
<!-- Public --> <!-- Public -->
<function name="addData" /><!-- params: data string, typeName (NUMERIC, ALPHANUMERIC, BYTE or KANJI) string --> <function name="addData" /><!-- params: data string, typeName (NUMERIC, ALPHANUMERIC or BYTE) string -->
<function name="make" /><!-- call AFTER all data is added, to generate modules --> <function name="make" /><!-- call AFTER all data is added, to generate modules -->
<function name="isDark" /><!-- row integer, col integer, returns boolean --> <function name="isDark" /><!-- row integer, col integer, returns boolean -->
</interface> </interface>
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8"?>
<component name="QRData" extends="Node"> <component name="QRData" extends="Node">
<interface> <interface>
@@ -10,7 +10,6 @@
<field id="MODE_NUMERIC" type="integer" value="1" /> <field id="MODE_NUMERIC" type="integer" value="1" />
<field id="MODE_ALPHANUMERIC" type="integer" value="2" /> <field id="MODE_ALPHANUMERIC" type="integer" value="2" />
<field id="MODE_BYTE" type="integer" value="4" /> <field id="MODE_BYTE" type="integer" value="4" />
<field id="MODE_KANJI" type="integer" value="8" />
<function name="setData" /><!-- string --> <function name="setData" /><!-- string -->
<function name="writeToBuffer" /><!-- QRBitBuffer --> <function name="writeToBuffer" /><!-- QRBitBuffer -->
@@ -1,115 +0,0 @@
sub init()
m.top.mode = m.top.MODE_KANJI
initUnicodeMap()
end sub
' @public
' @param textual representation of value
sub setData(data as string)
m.bytes = stringToBytes(data)
m.top.length = m.bytes.count() \ 2
end sub
' @public
' @param buffer QRBitBuffer
sub writeToBuffer(buffer as object)
i = 0
data = m.bytes
length = data.count()
while i + 1 < length
c = ((&Hff and data[i]) << 8) or (&Hff and data[i + 1])
if &H8140 <= c and c <= &H9FFC
c -= &H8140
else if &HE040 <= c and c <= &HEBBF
c -= &HC140
else
print "illegal character at", i + 1, "/", c
end if
c = ((c >> 8) and &Hff) * &HC0 + (c and &Hff)
buffer.callFunc("put", c, 13)
i += 2
end while
if i < length
print "illegal character at", i + 1
end if
end sub
' @private
sub initUnicodeMap()
if m.UNICODE_MAP <> invalid
return
end if
m.UNICODE_MAP = m.global.QR_KANJI_MAP
if m.UNICODE_MAP = invalid
m.UNICODE_MAP = initQRKanjiMap()
end if
end sub
' @private
function stringToBytes(text as string) as object
result = []
chars = text.split("")
unknownChar = asc("?")
unicodeMap = m.UNICODE_MAP
for i = 0 to chars.count() - 1 step 1
charcode = asc(chars[i])
if charcode < 128
result.push(charcode)
else
byte = unicodeMap[chars[i]]
if byte = invalid
result.push(unknownChar)
else if (byte and &Hff) = byte
' 1 byte
result.push(byte)
else
' 2 bytes
result.push(byte >> 8)
result.push(byte and &Hff)
end if
end if
end for
return result
end function
' @private
function initQRKanjiMap() as object
kanjiMap = {}
ba = createObject("roByteArray")
if ba = invalid
print "roByteArray is no available"
goto finish
end if
data = "AAAAAAABAAEAAgACAAMAAwAEAAQABQAFAAYABgAHAAcACAAIAAkACQAKAAoACwALAAwADAANAA0ADgAOAA8ADwAQABAAEQARABIAEgATABMAFAAUABUAFQAWABYAFwAXABgAGAAZABkAGgAaABsAGwAcABwAHQAdAB4AHgAfAB8AIAAgACEAIQAiACIAIwAjACQAJAAlACUAJgAmACcAJwAoACgAKQApACoAKgArACsALAAsAC0ALQAuAC4ALwAvADAAMAAxADEAMgAyADMAMwA0ADQANQA1ADYANgA3ADcAOAA4ADkAOQA6ADoAOwA7ADwAPAA9AD0APgA+AD8APwBAAEAAQQBBAEIAQgBDAEMARABEAEUARQBGAEYARwBHAEgASABJAEkASgBKAEsASwBMAEwATQBNAE4ATgBPAE8AUABQAFEAUQBSAFIAUwBTAFQAVABVAFUAVgBWAFcAVwBYAFgAWQBZAFoAWgBbAFsAXABcAF0AXQBeAF4AXwBfAGAAYABhAGEAYgBiAGMAYwBkAGQAZQBlAGYAZgBnAGcAaABoAGkAaQBqAGoAawBrAGwAbABtAG0AbgBuAG8AbwBwAHAAcQBxAHIAcgBzAHMAdAB0AHUAdQB2AHYAdwB3AHgAeAB5AHkAegB6AHsAewB8AHwAfQB9AH4AfgB\/AH8AooGRAKOBkgCngZgAqIFOAKyBygCwgYsAsYF9ALSBTAC2gfcA14F+APeBgAORg58DkoOgA5ODoQOUg6IDlYOjA5aDpAOXg6UDmIOmA5mDpwOag6gDm4OpA5yDqgOdg6sDnoOsA5+DrQOgg64DoYOvA6ODsAOkg7EDpYOyA6aDswOng7QDqIO1A6mDtgOxg78DsoPAA7ODwQO0g8IDtYPDA7aDxAO3g8UDuIPGA7mDxwO6g8gDu4PJA7yDygO9g8sDvoPMA7+DzQPAg84DwYPPA8OD0APEg9EDxYPSA8aD0wPHg9QDyIPVA8mD1gQBhEYEEIRABBGEQQQShEIEE4RDBBSERAQVhEUEFoRHBBeESAQYhEkEGYRKBBqESwQbhEwEHIRNBB2ETgQehE8EH4RQBCCEUQQhhFIEIoRTBCOEVAQkhFUEJYRWBCaEVwQnhFgEKIRZBCmEWgQqhFsEK4RcBCyEXQQthF4ELoRfBC+EYAQwhHAEMYRxBDKEcgQzhHMENIR0BDWEdQQ2hHcEN4R4BDiEeQQ5hHoEOoR7BDuEfAQ8hH0EPYR+BD6EgAQ\/hIEEQISCBEGEgwRChIQEQ4SFBESEhgRFhIcERoSIBEeEiQRIhIoESYSLBEqEjARLhI0ETISOBE2EjwROhJAET4SRBFGEdiAQgV0gFIFcIBaBYSAYgWUgGYFmIByBZyAdgWggIIH1ICGB9iAlgWQgJoFjIDCB8SAygYwgM4GNIDuBpiEDgY4hK4HwIZCBqSGRgaohkoGoIZOBqyHSgcsh1IHMIgCBzSICgd0iA4HOIgeB3iIIgbgiC4G5IhKBfCIageMiHYHlIh6BhyIggdoiJ4HIIiiBySIpgb8iKoG+IiuB5yIsgegiNIGIIjWB5iI9geQiUoHgImCBgiJhgd8iZoGFImeBhiJqgeEia4HiIoKBvCKDgb0ihoG6IoeBuyKlgdsjEoHcJQCEnyUBhKolAoSgJQOEqyUMhKElD4SsJRCEoiUThK0lFISkJReEryUYhKMlG4SuJRyEpSUdhLolIIS1JSOEsCUkhKclJYS8JSiEtyUrhLIlLISmJS+EtiUwhLslM4SxJTSEqCU3hLglOIS9JTuEsyU8hKklP4S5JUKEviVLhLQloIGhJaGBoCWygaMls4GiJbyBpSW9gaQlxoGfJceBniXLgZslzoGdJc+BnCXvgfwmBYGaJgaBmSZAgYomQoGJJmqB9CZtgfMmb4HyMACBQDABgUEwAoFCMAOBVjAFgVgwBoFZMAeBWjAIgXEwCYFyMAqBczALgXQwDIF1MA2BdjAOgXcwD4F4MBCBeTARgXowEoGnMBOBrDAUgWswFYFsMByBYDBBgp8wQoKgMEOCoTBEgqIwRYKjMEaCpDBHgqUwSIKmMEmCpzBKgqgwS4KpMEyCqjBNgqswToKsME+CrTBQgq4wUYKvMFKCsDBTgrEwVIKyMFWCszBWgrQwV4K1MFiCtjBZgrcwWoK4MFuCuTBcgrowXYK7MF6CvDBfgr0wYIK+MGGCvzBigsAwY4LBMGSCwjBlgsMwZoLEMGeCxTBogsYwaYLHMGqCyDBrgskwbILKMG2CyzBugswwb4LNMHCCzjBxgs8wcoLQMHOC0TB0gtIwdYLTMHaC1DB3gtUweILWMHmC1zB6gtgwe4LZMHyC2jB9gtswfoLcMH+C3TCAgt4wgYLfMIKC4DCDguEwhILiMIWC4zCGguQwh4LlMIiC5jCJgucwioLoMIuC6TCMguowjYLrMI6C7DCPgu0wkILuMJGC7zCSgvAwk4LxMJuBSjCcgUswnYFUMJ6BVTChg0AwooNBMKODQjCkg0MwpYNEMKaDRTCng0YwqINHMKmDSDCqg0kwq4NKMKyDSzCtg0wwroNNMK+DTjCwg08wsYNQMLKDUTCzg1IwtINTMLWDVDC2g1Uwt4NWMLiDVzC5g1gwuoNZMLuDWjC8g1swvYNcML6DXTC\/g14wwINfMMGDYDDCg2Eww4NiMMSDYzDFg2QwxoNlMMeDZjDIg2cwyYNoMMqDaTDLg2owzINrMM2DbDDOg20wz4NuMNCDbzDRg3Aw0oNxMNODcjDUg3Mw1YN0MNaDdTDXg3Yw2IN3MNmDeDDag3kw24N6MNyDezDdg3ww3oN9MN+DfjDgg4Aw4YOBMOKDgjDjg4Mw5IOEMOWDhTDmg4Yw54OHMOiDiDDpg4kw6oOKMOuDizDsg4ww7YONMO6DjjDvg48w8IOQMPGDkTDyg5Iw84OTMPSDlDD1g5Uw9oOWMPuBRTD8gVsw\/YFSMP6BU04AiOpOAZKaTgOOtU4HlpxOCI\/kTgmOT04Kj+NOC4m6Tg2Vc04Ol15OEJigThGJTk4Uio5OFZihThaQok4XmcBOGIt1ThmVuE4ej+VOIZe8TiaVwE4qmKJOLZKGTjGYo04yi\/hONpikTjiK2045kk9OO47lTjyYpU4\/mKZOQpinTkOUVE5Fi3ZOS5RWTk2T4U5OjMFOT5ZSTlXlaE5WmKhOV4\/mTliYqU5ZibNOXYvjTl6M7k5fludOYpukTnGXkE5zk\/tOfoqjToCLVE6CmKpOhZirToaXuU6Il1xOiZGIToqYrU6LjpZOjJPxTo6YsE6RiV1OkozdTpSM3E6ViOROmJhqTpmYaU6bjbFOnIifTp6YsU6fmLJOoJizTqGWU06imLROpIzwTqWI5U6mlpJOqIucTquLnU6si55OrZLgTq6Xuk6wmLVOs5i2TraYt066kGxOwI9ZTsGQbU7CmLxOxJi6TsaYu07Hi3dOyo2hTsuJ7k7NmLlOzpi4Ts+Vp07UjmVO1Y5kTtaRvE7XmL1O2JV0TtmQ5U7dgVdO3pi+Tt+YwE7jkeNO5JffTuWIyE7tmL9O7om8TvCLwk7ykodO9oyPTveYwU77lENPAYrpTwmYwk8KiMlPDYzeTw6K6k8PlZpPEJSwTxGLeE8aie9PHJjlTx2TYE8vlIxPMJjETzSUuk82l+BPOJBMTzqOZk88jpdPPYm+T0OSz09GkkFPR5jIT02Iyk9OkuFPT49aT1CNsk9Rl0NPU5HMT1WJvU9XmMdPWZddT1qYw09bmMVPXI3sT12Yxk9em0NPaZjOT2+Y0U9wmM9Pc4nAT3WVuU92mMlPe5jNT3yM8U9\/jmdPg4qkT4aY0k+ImMpPi5fhT42OmE+PmMtPkZjQT5aY00+YmMxPm4ufT52Iy0+gi6BPoYm\/T6ubRE+tlplPrpWOT6+M8k+1kE5Ptpe1T7+V1k\/CjFdPw5GjT8SJ4k\/Kj3JPzpjXT9CY3E\/RmNpP1JjVT9eRrU\/YmNhP2pjbT9uY2U\/dldtP35jWT+GQTU\/jlpNP5JjdT+WY3k\/uj0NP75jrT\/OUb0\/1lVVP9pjmT\/iV7k\/6ibRP\/pjqUAWY5FAGmO1QCZFxUAuMwlANlHtQD+DFUBGY7FASk3xQFJjhUBaM9FAZjPNQGpjfUB+O2FAhmOdQI5XtUCSSbFAlmONQJoyRUCiY4FApmOhQKpjiUCuXz1AsmOlQLZhgUDaL5FA5jJBQQ5juUEeY71BImPNQSYjMUE+VzlBQmPJQVZjxUFaY9VBamPRQXJLiUGWMklBsmPZQco7DUHSRpFB1kuNQdov0UHiY91B9i1VQgJj4UIWY+lCNllRQkYyGUJiOUFCZlPVQmpj5UKyNw1Ctl2JQspj8ULOZQlC0mPtQtY3CULePnVC+jFhQwplDUMWLzVDJmUBQyplBUM2TrVDPkZxQ0YuhUNWWbFDWmURQ2pe7UN6ZRVDjmUhQ5ZlGUOeRbVDtmUdQ7plJUPWZS1D5mUpQ+5XGUQCLVlEBmU1RAplOUQSJrVEJmUxREo7yURSZUVEVmVBRFplPURiY1FEamVJRH4+eUSGZU1Eql0RRMpbXUTeZVVE6mVRRO5lXUTyZVlE\/mVhRQJlZUUGI8lFDjLNRRIxaUUWPW1FGkptRR4uiUUiQ5lFJjPVRS42OUUyZW1FNlsZRTpNlUVCOmVFSmVpRVJlcUVqTfVFcipVRYpldUWWT\/FFokVNRaZlfUWqZYFFrlKpRbIz2UW2YWlFumWFRcYukUXWVulF2kbRRd4vvUXiTVFF8jJNRgJliUYKZY1GFk+BRhol+UYmZZlGKjftRjJllUY2NxFGPmWdRkOPsUZGZaFGSlmBRk5lpUZWZalGWmWtRl4\/nUZmOylGgiqVRopluUaSZbFGllrtRppltUaiVeVGpmW9RqplwUauZcVGsk35RsJl1UbGZc1GymXRRs5lyUbSN4VG1mXZRtpboUbeXLine truncated
' count = 7070
ba.fromBase64String(data)
for i = 0 to ba.count() - 1 step 4
b0 = ba[i]
b1 = ba[i + 1]
b2 = ba[i + 2]
b3 = ba[i + 3]
k = chr((b0 << 8) or b1)
v = (b2 << 8) or b3
kanjiMap[k] = v
end for
finish:
m.global.QR_KANJI_MAP = kanjiMap
return kanjiMap
end function
@@ -1,3 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<component name="QRData_Kanji" extends="QRData">
</component>
+1 -1
View File
@@ -38,7 +38,7 @@
{ {
"displayText": "Instance", "displayText": "Instance",
"key": "invidious.instance", "key": "invidious.instance",
"description": "Invidious instance to use", "description": "Invidious instance to use. Example: https://vid.puffyan.us",
"type": "string" "type": "string"
}, },
{ {
+2 -2
View File
@@ -3,11 +3,11 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json # Do not update version manually, it is auto updated from package.json
major_version=0 major_version=0
minor_version=10 minor_version=10
build_version=00000 build_version=00003
sg_component_libs_provided=PlayletLib sg_component_libs_provided=PlayletLib
hidden=1 hidden=1
git_commit_sha=unknown git_commit_sha=unknown
bs_const=DEBUG=false;WEB_SERVER_BASIC_AUTH=false;DASH_THUMBNAILS=false;WEB_SOCKETS=true;CAPTION_INSTANCE_SEARCH=false bs_const=DEBUG=false;WEB_SERVER_BASIC_AUTH=false;DASH_THUMBNAILS=false;WEB_SOCKETS=false;CAPTION_INSTANCE_SEARCH=false
+89 -9
View File
@@ -13,15 +13,19 @@ namespace Invidious
const STATS_ENDPOINT = "/api/v1/stats" const STATS_ENDPOINT = "/api/v1/stats"
const VIDEOS_ENDPOINT = "/api/v1/videos" const VIDEOS_ENDPOINT = "/api/v1/videos"
const PLAYLISTS_ENDPOINT = "/api/v1/playlists"
const HISTORY_ENDPOINT = "/api/v1/auth/history" const HISTORY_ENDPOINT = "/api/v1/auth/history"
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,POST:tokens/unregister,POST:history*" const AUTH_SCOPES = "GET:feed,GET:playlists,POST:tokens/register,POST:tokens/unregister,POST:history*"
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" const AUTH_TOKENS_UNREGISTER = "/api/v1/auth/tokens/unregister"
const AUTH_TOKENS_REGISTER = "/api/v1/auth/tokens/register"
const TOKEN_TIMESPAN = 60 * 60 * 24 * 365 * 2 '2 years
function DefaultArgs() as object function DefaultArgs() as object
return { return {
@@ -72,10 +76,23 @@ namespace Invidious
return { return {
success: response.ok, success: response.ok,
statusCode: response.statuscode, statusCode: response.statuscode,
data: response.json data: response.json,
failureReason: response.GetFailureReason
} }
end function end function
function GetPlaylist(playlistId as string) as object
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}`
args = Invidious.DefaultArgs()
response = Requests().get(url, args)
if not response.ok
return invalid
end if
return response.json
end function
function MarkVideoWatched(videoId as string) as boolean function MarkVideoWatched(videoId as string) as boolean
authToken = InvidiousSettings.GetAuthToken() authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid if authToken = invalid
@@ -151,10 +168,10 @@ namespace Invidious
localIp = GetLocalIpAddress() localIp = GetLocalIpAddress()
webServerPort = 8888 webServerPort = 8888
expire = TimeUtils.Now().AsSeconds() + 60 * 60 * 24 * 365 * 2 '2 years from now expire = TimeUtils.Now().AsSeconds() + TOKEN_TIMESPAN
callbackUrl = `http://${localIp}:${webServerPort}${Invidious.TOKEN_CALLBACK}?ref=${instance}`.EncodeUriComponent() callbackUrl = `http://${localIp}:${webServerPort}${Invidious.TOKEN_CALLBACK}?ref=${instance}`.EncodeUriComponent()
scope = `${Invidious.AUTH_SCOPE}`.EncodeUriComponent() scope = `${Invidious.AUTH_SCOPES}`.EncodeUriComponent()
return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}` return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
end function end function
@@ -164,11 +181,63 @@ namespace Invidious
} }
end function end function
function Logout() as boolean function RefreshAuthToken() as boolean
authToken = InvidiousSettings.GetAuthToken() currentAuthToken = InvidiousSettings.GetAuthToken()
if authToken = invalid if currentAuthToken = invalid
return false return false
end if end if
expire = TimeUtils.Now().AsSeconds() + TOKEN_TIMESPAN
newToken = RegisterToken(currentAuthToken, expire)
if newToken = invalid
return false
end if
InvidiousSettings.SetAuthToken(newToken.token, newToken.instance, newToken.username, newToken.scopes, newToken.expire)
UnregisterToken(currentAuthToken)
return true
end function
function RegisterToken(authToken as object, expire as integer) as dynamic
headers = Invidious.GetAuthenticationHeaders(authToken.token)
url = `${authToken.instance}${Invidious.AUTH_TOKENS_REGISTER}`
scopes = authToken.scopes
if scopes = invalid
parsedToken = ParseJson(authToken.token)
if GetInterface(parsedToken.scopes, "ifArray") <> invalid
scopes = parsedToken.scopes.join(",")
else
scopes = Invidious.AUTH_SCOPES
end if
end if
args = {
headers: headers,
json: {
"scopes": scopes.Split(","),
"expire": expire
},
parseJson: false
}
response = Requests().post(url, args)
if not response.ok
return invalid
end if
return {
token: response.text,
instance: authToken.instance,
username: authToken.username,
scopes: scopes,
expire: expire
}
end function
function UnregisterToken(authToken as object) as boolean
headers = Invidious.GetAuthenticationHeaders(authToken.token) headers = Invidious.GetAuthenticationHeaders(authToken.token)
url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}` url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
@@ -177,10 +246,21 @@ namespace Invidious
headers["Content-Type"] = "application/json" headers["Content-Type"] = "application/json"
args = { args = {
headers: headers, headers: headers,
data: authToken.token data: authToken.token,
parseJson: false
} }
Requests().post(url, args) response = Requests().post(url, args)
return response.ok
end function
function Logout() as boolean
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
return false
end if
UnregisterToken(authToken)
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN) RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
return true return true
@@ -4,6 +4,7 @@ import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/General.bs" import "pkg:/source/utils/General.bs"
import "pkg:/source/utils/Crypto.bs" import "pkg:/source/utils/Crypto.bs"
import "pkg:/source/services/InvidiousSettings.bs" import "pkg:/source/services/InvidiousSettings.bs"
import "pkg:/source/services/Invidious.bs"
class InvidiousService class InvidiousService
private endpoints private endpoints
@@ -118,7 +119,14 @@ class InvidiousService
playlists = response.json playlists = response.json
result = [] result = []
for each playlist in playlists for each playlist in playlists
result.push(m.ProcessPlaylist(requestData, playlist)) ' Saved playlists are not included in the response
' https://github.com/iv-org/invidious/issues/3995
if playlist.videos.count() = 0 and playlist.authorId = invalid and not playlist.playlistId.StartsWith("IV")
playlist = Invidious.GetPlaylist(playlist.playlistId)
end if
if playlist <> invalid
result.push(m.ProcessPlaylist(requestData, playlist))
end if
end for end for
return result return result
end if end if
@@ -147,33 +155,12 @@ class InvidiousService
function DeleteExpiredToken(response as object) function DeleteExpiredToken(response as object)
if response.statuscode = 403 if response.statuscode = 403
print(`Server responded with 403: ${response.text}`) print(`Invidious instance responded with 403: ${response.text}`)
if m.IsTokenMaybeExpired() = true print("Deleting Invidious token...")
print("deleting token...") RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
end if
end if end if
end function end function
' Public Invidious instances fail a lot randomly, even with valid tokens
' For that reason, it's better to make sure the token actually expired by date
function IsTokenMaybeExpired() as dynamic
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
return invalid
end if
token = ParseJson(authToken.token)
if token = invalid
return invalid
end if
if not token.DoesExist("expire")
return invalid
end if
expire = token["expire"]
currentTime = TimeUtils.Now().AsSeconds()
return expire < currentTime
end function
function CacheResponse(requestData as object, result as object) function CacheResponse(requestData as object, result as object)
cacheKey = FormatJson(requestData) cacheKey = FormatJson(requestData)
cacheKey = GetMd5(cacheKey) cacheKey = GetMd5(cacheKey)
@@ -21,7 +21,7 @@ namespace InvidiousSettings
return InvidiousSettings.DEFAULT_INSTANCE return InvidiousSettings.DEFAULT_INSTANCE
end function end function
function SetAuthToken(token as string, instance as string, username as dynamic) function SetAuthToken(token as string, instance as string, username as dynamic, scopes as dynamic, expire as dynamic)
obj = { obj = {
token: token, token: token,
instance: instance instance: instance
@@ -29,6 +29,12 @@ namespace InvidiousSettings
if username <> invalid if username <> invalid
obj.username = username obj.username = username
end if end if
if scopes <> invalid
obj.scopes = scopes
end if
if expire <> invalid
obj.expire = expire
end if
json = FormatJson(obj) json = FormatJson(obj)
RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json) RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json)
@@ -39,7 +45,12 @@ namespace InvidiousSettings
if tokenPayload = invalid if tokenPayload = invalid
return invalid return invalid
end if end if
return ParseJson(tokenPayload) authData = ParseJson(tokenPayload)
if authData = invalid or authData.instance = invalid or authData.token = invalid
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
return invalid
end if
return authData
end function end function
function GetBackupInstances() as object function GetBackupInstances() as object
@@ -81,14 +81,24 @@ namespace SponsorBlock
return response.statuscode = 200 return response.statuscode = 200
end function end function
function GenerateProgressBarBackground(segments as object, path as string) function GenerateProgressBarBackground(segments as object, lengthSeconds as integer, path as string)
bar = CreateObject("roBitmap", { width: 1000, height: 20, AlphaEnable: true }) bar = CreateObject("roBitmap", { width: 1000, height: 20, AlphaEnable: true })
bar.Clear(&hFFFFFF80) bar.Clear(&hFFFFFF80)
width = bar.GetWidth() width = bar.GetWidth()
height = bar.GetHeight() height = bar.GetHeight()
for each segment in segments for each segment in segments
pixelStart = (segment.segment[0] / segment.videoDuration) * width videoDuration = lengthSeconds
pixelEnd = (segment.segment[1] / segment.videoDuration) * width if videoDuration = 0 or videoDuration = invalid
' We should ignore segment.videoDuration https://github.com/iBicha/playlet/pull/23#issuecomment-1431520676
' But in case where we don't have lengthSeconds from Invidious, it's better than nothing
videoDuration = segment.videoDuration
end if
if videoDuration = 0 or videoDuration = invalid
continue for
end if
pixelStart = (segment.segment[0] / videoDuration) * width
pixelEnd = (segment.segment[1] / videoDuration) * width
color = SponsorBlock.SegmentColor(segment.category) color = SponsorBlock.SegmentColor(segment.category)
' highlight's duration is zero, so it is not visble on the bar. ' highlight's duration is zero, so it is not visble on the bar.
' Add a couple of pixels to see it ' Add a couple of pixels to see it
+18 -3
View File
@@ -1,17 +1,32 @@
import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/Types.bs"
namespace TimeUtils namespace TimeUtils
' Helper function convert seconds to mm:ss format ' Helper function convert seconds to [hh:]mm:ss format
' getTime(138) returns 2:18 ' getTime(138) returns 2:18
function GetFormattedTime(length as integer) as string function GetFormattedTime(length as integer) as string
minutes = (length \ 60).ToStr() hours = length \ 3600
minutes = (length \ 60) mod 60
seconds = length mod 60 seconds = length mod 60
if seconds < 10 if seconds < 10
seconds = "0" + seconds.ToStr() seconds = "0" + seconds.ToStr()
else else
seconds = seconds.ToStr() seconds = seconds.ToStr()
end if end if
return minutes + ":" + seconds
if minutes < 10 and hours > 0
minutes = "0" + minutes.ToStr()
else
minutes = minutes.ToStr()
end if
formattedTime = minutes + ":" + seconds
if hours > 0
formattedTime = hours.ToStr() + ":" + formattedTime
end if
return formattedTime
end function end function
function GetFormattedTimeLeft(unixTimestamp as integer) as string function GetFormattedTimeLeft(unixTimestamp as integer) as string
+3 -1
View File
@@ -1,3 +1,5 @@
# Playlet web # Playlet web
This is the Playlet companion web app, which allows the configuration and control of the playlet app. This is the Playlet companion web app, which allows the configuration and control of the playlet app.
Find out more on the [documentation](/docs/README.md#playlet-web-app) page
+9 -9
View File
@@ -1,16 +1,16 @@
{ {
"name": "playlet-web", "name": "playlet-web",
"version": "0.10.0", "version": "0.10.3",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-web", "name": "playlet-web",
"version": "0.10.0", "version": "0.10.3",
"devDependencies": { "devDependencies": {
"@sveltejs/vite-plugin-svelte": "^2.4.2", "@sveltejs/vite-plugin-svelte": "^2.4.2",
"@tailwindcss/typography": "^0.5.9", "@tailwindcss/typography": "^0.5.9",
"@tsconfig/svelte": "^4.0.1", "@tsconfig/svelte": "^5.0.0",
"autoprefixer": "^10.4.14", "autoprefixer": "^10.4.14",
"daisyui": "^3.1.6", "daisyui": "^3.1.6",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
@@ -553,9 +553,9 @@
} }
}, },
"node_modules/@tsconfig/svelte": { "node_modules/@tsconfig/svelte": {
"version": "4.0.1", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-4.0.1.tgz", "resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-5.0.0.tgz",
"integrity": "sha512-B+XlGpmuAQzJqDoBATNCvEPqQg0HkO7S8pM14QDI5NsmtymzRexQ1N+nX2H6RTtFbuFgaZD4I8AAi8voGg0GLg==", "integrity": "sha512-iu5BqFjU0+OcLTNQp7fHe6Bf6zdNeJ9IZjLZMqWLuGzVFm/xx+lm//Tf6koPyRmxo55/Snm6RRQ990n89cRKFw==",
"dev": true "dev": true
}, },
"node_modules/@types/estree": { "node_modules/@types/estree": {
@@ -2609,9 +2609,9 @@
} }
}, },
"@tsconfig/svelte": { "@tsconfig/svelte": {
"version": "4.0.1", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-4.0.1.tgz", "resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-5.0.0.tgz",
"integrity": "sha512-B+XlGpmuAQzJqDoBATNCvEPqQg0HkO7S8pM14QDI5NsmtymzRexQ1N+nX2H6RTtFbuFgaZD4I8AAi8voGg0GLg==", "integrity": "sha512-iu5BqFjU0+OcLTNQp7fHe6Bf6zdNeJ9IZjLZMqWLuGzVFm/xx+lm//Tf6koPyRmxo55/Snm6RRQ990n89cRKFw==",
"dev": true "dev": true
}, },
"@types/estree": { "@types/estree": {
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-web", "name": "playlet-web",
"version": "0.10.0", "version": "0.10.3",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -11,7 +11,7 @@
"devDependencies": { "devDependencies": {
"@sveltejs/vite-plugin-svelte": "^2.4.2", "@sveltejs/vite-plugin-svelte": "^2.4.2",
"@tailwindcss/typography": "^0.5.9", "@tailwindcss/typography": "^0.5.9",
"@tsconfig/svelte": "^4.0.1", "@tsconfig/svelte": "^5.0.0",
"autoprefixer": "^10.4.14", "autoprefixer": "^10.4.14",
"daisyui": "^3.1.6", "daisyui": "^3.1.6",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
@@ -0,0 +1,6 @@
<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false" style="pointer-events: none; display: block; width: 100%; height: 100%;">
<g class="fill-current">
<path d="m20.87 20.17-5.59-5.59C16.35 13.35 17 11.75 17 10c0-3.87-3.13-7-7-7s-7 3.13-7 7 3.13 7 7 7c1.75 0 3.35-.65 4.58-1.71l5.59 5.59.7-.71zM10 16c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"></path>
</g>
</svg>

After

Width:  |  Height:  |  Size: 528 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

+1
View File
@@ -0,0 +1 @@
<svg viewBox="0 0 190.516 190.516" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><defs><clipPath clipPathUnits="userSpaceOnUse" id="a"><circle style="display:inline;fill:red;stroke-width:.808149;stroke-linejoin:round" cx="99.697" cy="190.975" r="67.373"/></clipPath></defs><g style="display:inline" transform="translate(-5.483 -14.747)"><circle style="display:inline;fill:#000;stroke:none;stroke-width:1.2888;stroke-linejoin:round" cx="100.741" cy="110.005" r="95.258"/><circle style="display:inline;fill:#fff;stroke:none;stroke-width:1.2888;stroke-linejoin:round" cx="100.741" cy="110.005" r="95.258" clip-path="url(#a)"/><circle style="display:inline;fill:#fff;stroke:none;stroke-width:.907953;stroke-linejoin:round" cx="99.6" cy="85.809" r="38.136"/></g></svg>

After

Width:  |  Height:  |  Size: 773 B

+42 -3
View File
@@ -1,13 +1,45 @@
<script> <script>
import { onMount } from "svelte"; import { onMount } from "svelte";
import { PlayletApi } from "./PlayletApi"; import { PlayletApi } from "./PlayletApi";
import { playletStateStore } from "./Stores";
let selectedRelease = '' let selectedRelease = "";
let releases = []; let releases = [];
let libUrl;
let libUrlType;
onMount(async () => { onMount(async () => {
releases = await fetchReleaseTags(); releases = await fetchReleaseTags();
setCurrentlyUsedRelease();
}); });
playletStateStore.subscribe((value) => {
libUrl = value?.app?.lib_url;
libUrlType = value?.app?.lib_url_type;
setCurrentlyUsedRelease();
});
function setCurrentlyUsedRelease() {
if (libUrlType !== "custom") {
return;
}
if (releases.length === 0) {
return;
}
for (let i = 0; i < releases.length; i++) {
const release = releases[i].name;
if (
libUrl ===
`https://github.com/iBicha/playlet/releases/download/${release}/playlet-lib.zip`
) {
selectedRelease = release;
break;
}
}
}
async function fetchReleaseTags() { async function fetchReleaseTags() {
const response = await fetch( const response = await fetch(
"https://api.github.com/repos/iBicha/playlet/releases" "https://api.github.com/repos/iBicha/playlet/releases"
@@ -28,7 +60,11 @@
if (version === "") { if (version === "") {
version = "latest"; version = "latest";
} }
if (confirm(`Are you sure you want to change the Playlet Library version to "${version}"?`)) { if (
confirm(
`Are you sure you want to change the Playlet Library version to "${version}"?`
)
) {
await PlayletApi.setPlayletLibVersion(selectedRelease); await PlayletApi.setPlayletLibVersion(selectedRelease);
alert("Playlet Library version set. Restart playlet to apply changes."); alert("Playlet Library version set. Restart playlet to apply changes.");
} }
@@ -51,7 +87,10 @@
</div> </div>
<div class="join w-full m-1"> <div class="join w-full m-1">
<select bind:value={selectedRelease} class="select select-bordered join-item w-full mr-1"> <select
bind:value={selectedRelease}
class="select select-bordered join-item w-full mr-1"
>
<option selected value="">latest (default)</option> <option selected value="">latest (default)</option>
{#each releases as release} {#each releases as release}
<option disabled={!release.enabled} value={release.name} <option disabled={!release.enabled} value={release.name}
+58 -18
View File
@@ -3,12 +3,16 @@
import { PlayletApi } from "./PlayletApi"; import { PlayletApi } from "./PlayletApi";
import { playletStateStore } from "./Stores"; import { playletStateStore } from "./Stores";
import { InvidiousApi } from "./InvidiousApi"; import { InvidiousApi } from "./InvidiousApi";
import VideoStartAt from "./VideoStartAt.svelte";
let modal; let modal;
let isDragging; let isDragging;
let isLoading; let isLoading;
let dragEndTimeout; let dragEndTimeout;
let videoStartAtChecked;
let videoStartAtTimestamp;
let videoMetadata; let videoMetadata;
let tvName = "Roku TV"; let tvName = "Roku TV";
@@ -43,10 +47,10 @@
let dataString = await new Promise((resolve) => let dataString = await new Promise((resolve) =>
item.getAsString(resolve) item.getAsString(resolve)
); );
if (IsValidHttpUrl(dataString)) { if (isValidHttpUrl(dataString)) {
const videoId = GetVideoId(dataString); const videoInfo = parseYouTubeUrl(dataString);
if (videoId) { if (videoInfo.videoId) {
searchForVideoById(videoId); searchForVideoById(videoInfo.videoId, videoInfo.timestamp);
return; return;
} }
} }
@@ -54,10 +58,14 @@
} }
} }
async function searchForVideoById(videoId) { async function searchForVideoById(videoId, timestamp) {
try { try {
isLoading = true; isLoading = true;
videoMetadata = await invidiousApi.getVideoMetadata(videoId); videoMetadata = await invidiousApi.getVideoMetadata(videoId);
videoStartAtChecked = timestamp !== undefined;
if (videoStartAtChecked) {
videoStartAtTimestamp = timestamp;
}
modal.showModal(); modal.showModal();
} finally { } finally {
isLoading = false; isLoading = false;
@@ -74,7 +82,7 @@
event.preventDefault(); event.preventDefault();
} }
function IsValidHttpUrl(string) { function isValidHttpUrl(string) {
let url; let url;
try { try {
url = new URL(string); url = new URL(string);
@@ -84,9 +92,17 @@
return url.protocol === "http:" || url.protocol === "https:"; return url.protocol === "http:" || url.protocol === "https:";
} }
function GetVideoId(url) { function parseYouTubeUrl(url) {
const urlSearchParams = new URLSearchParams(new URL(url).search);
function getTimestamp() {
const timestamp = urlSearchParams.get("t");
if (timestamp) {
return timestamp.endsWith("s") ? timestamp.slice(0, -1) : timestamp;
}
}
// Share/Short url // Share/Short url
// TODO: use regex, and support timestamped videos
const YoutubeUrls = [ const YoutubeUrls = [
"https://youtu.be/", "https://youtu.be/",
"http://youtu.be/", "http://youtu.be/",
@@ -100,33 +116,52 @@
for (var i in YoutubeUrls) { for (var i in YoutubeUrls) {
let youtubeUrl = YoutubeUrls[i]; let youtubeUrl = YoutubeUrls[i];
if (url.startsWith(youtubeUrl)) { if (url.startsWith(youtubeUrl)) {
url = url.replace(youtubeUrl, ""); let videoId = url.replace(youtubeUrl, "");
if (url.includes("?")) { if (videoId.includes("?")) {
url = url.substring(0, url.indexOf("?")); videoId = videoId.substring(0, videoId.indexOf("?"));
} }
return url; const result: any = {
videoId,
};
const timestamp = getTimestamp();
if (timestamp) {
result.timestamp = timestamp;
}
return result;
} }
} }
// regular url // regular url
url = new URL(url); const result: any = {
const urlSearchParams = new URLSearchParams(url.search); videoId: urlSearchParams.get("v"),
return urlSearchParams.get("v"); };
const timestamp = getTimestamp();
if (timestamp) {
result.timestamp = timestamp;
}
return result;
} }
async function playVideoOnTv() { async function playVideoOnTv() {
await PlayletApi.playVideo(videoMetadata?.videoId); await PlayletApi.playVideo(videoMetadata?.videoId, videoStartAtTimestamp);
} }
function openInvidiousInNewTab() { function openInvidiousInNewTab() {
window.open(`${invidiousInstance}/watch?v=${videoMetadata?.videoId}`); let url = `${invidiousInstance}/watch?v=${videoMetadata?.videoId}`;
if (videoStartAtChecked && videoStartAtTimestamp) {
url += `&t=${videoStartAtTimestamp}`;
}
window.open(url);
} }
</script> </script>
<div <div
class="{isDragging || isLoading class="{isDragging || isLoading
? '' ? ''
: 'hidden'} absolute w-full h-full bg-base-100/80 z-50 flex justify-center items-center" : 'hidden'} fixed w-full h-full bg-base-100/80 z-50 flex justify-center items-center"
> >
{#if isDragging} {#if isDragging}
<div class="text-2xl font-bold">Drop a Youtube link here</div> <div class="text-2xl font-bold">Drop a Youtube link here</div>
@@ -139,6 +174,11 @@
<form method="dialog" class="modal-box bg-base-100"> <form method="dialog" class="modal-box bg-base-100">
<h3 class="text-lg m-5">{videoMetadata?.title}</h3> <h3 class="text-lg m-5">{videoMetadata?.title}</h3>
<div class="flex flex-col"> <div class="flex flex-col">
<VideoStartAt
bind:checked={videoStartAtChecked}
bind:timestamp={videoStartAtTimestamp}
lengthSeconds={videoMetadata?.lengthSeconds}
/>
<button class="btn m-2" on:click={playVideoOnTv}>Play on {tvName}</button> <button class="btn m-2" on:click={playVideoOnTv}>Play on {tvName}</button>
<button class="btn m-2" on:click={openInvidiousInNewTab} <button class="btn m-2" on:click={openInvidiousInNewTab}
>Open in Invidious</button >Open in Invidious</button
+17 -3
View File
@@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import playletLogoDark from "../assets/logo-dark.svg"; import playletLogoDark from "../assets/logo-dark.svg";
import playletLogoLight from "../assets/logo-light.svg"; import playletLogoLight from "../assets/logo-light.svg";
import userIcon from "../assets/user.png"; import UserIcon from "../assets/user.svg.svelte";
import { PlayletApi } from "./PlayletApi"; import { PlayletApi } from "./PlayletApi";
import { appThemeStore, playletStateStore } from "./Stores"; import { appThemeStore, playletStateStore } from "./Stores";
import ThemeSelect from "./ThemeToggle.svelte"; import ThemeSelect from "./ThemeToggle.svelte";
@@ -15,6 +15,16 @@
playletStateStore.subscribe((value) => { playletStateStore.subscribe((value) => {
version = value?.app?.lib_version ?? ""; version = value?.app?.lib_version ?? "";
if (value?.app?.id === "dev") {
version += "-dev";
}
if (
value?.app?.lib_url_type === "custom" &&
value?.app?.lib_url ===
"https://github.com/iBicha/playlet/releases/download/unstable/playlet-lib.zip"
) {
version += "-unstable";
}
loggedIn = value?.invidious?.logged_in; loggedIn = value?.invidious?.logged_in;
auth_url = value?.invidious?.auth_url; auth_url = value?.invidious?.auth_url;
currentInstance = value?.invidious?.current_instance; currentInstance = value?.invidious?.current_instance;
@@ -39,7 +49,11 @@
<div class="navbar bg-base-100 sticky top-0 z-40"> <div class="navbar bg-base-100 sticky top-0 z-40">
<div class="flex-1"> <div class="flex-1">
<img src={$appThemeStore === 'dark' ? playletLogoDark : playletLogoLight} class="h-8" alt="Playlet Logo" /> <img
src={$appThemeStore === "dark" ? playletLogoDark : playletLogoLight}
class="h-8"
alt="Playlet Logo"
/>
<h4 class="label brightness-75">{version}</h4> <h4 class="label brightness-75">{version}</h4>
</div> </div>
<div class="flex-none"> <div class="flex-none">
@@ -52,7 +66,7 @@
<div class="dropdown dropdown-end"> <div class="dropdown dropdown-end">
<div tabindex="-1" class="btn btn-ghost btn-circle avatar"> <div tabindex="-1" class="btn btn-ghost btn-circle avatar">
<div class="w-8 rounded-full"> <div class="w-8 rounded-full">
<img src={userIcon} alt="User" /> <UserIcon />
</div> </div>
</div> </div>
<ul <ul
+6 -2
View File
@@ -43,11 +43,15 @@ export class PlayletApi {
return await PlayletApi.postJson(`${PlayletApi.host()}/api/command`, { command: "logout" }); return await PlayletApi.postJson(`${PlayletApi.host()}/api/command`, { command: "logout" });
} }
static async playVideo(videoId) { static async playVideo(videoId, timestamp) {
if (!videoId) { if (!videoId) {
return; return;
} }
return await PlayletApi.postJson(`${PlayletApi.host()}/api/command`, { command: "play", videoId: videoId }); const payload = { command: "play", videoId: videoId };
if (timestamp !== undefined) {
payload["timestamp"] = timestamp;
}
return await PlayletApi.postJson(`${PlayletApi.host()}/api/command`, payload);
} }
static async getSearchHistory() { static async getSearchHistory() {
+39 -8
View File
@@ -1,14 +1,31 @@
<script lang="ts"> <script lang="ts">
import { InvidiousApi } from "./InvidiousApi"; import { InvidiousApi } from "./InvidiousApi";
import { import { invidiousVideoApiStore, playletStateStore } from "./Stores";
invidiousVideoApiStore,
playletStateStore,
} from "./Stores";
import VideoCell from "./VideoCell.svelte"; import VideoCell from "./VideoCell.svelte";
export let requestData: any = undefined; export let requestData: any = undefined;
export let videoRowData = undefined; export let videoRowData = undefined;
let carouselElement;
let scrollStart = 0;
let scrollEnd = 0;
// w-80 p-2: 320px + 16px padding on each side
const itemWidth = 320 + 16 * 2;
$: {
if (videoRowData && !Array.isArray(videoRowData)) {
if (
carouselElement &&
videoRowData.videos &&
videoRowData.videos.length
) {
recalculateVisibileCells();
}
}
}
let invidiousApi = new InvidiousApi(); let invidiousApi = new InvidiousApi();
playletStateStore.subscribe((value) => { playletStateStore.subscribe((value) => {
@@ -29,6 +46,14 @@
videoRowData = result; videoRowData = result;
} }
} }
function recalculateVisibileCells() {
const scrollLeft = carouselElement.scrollLeft;
const clientWidth = carouselElement.clientWidth || window.innerWidth;
scrollStart = Math.floor(scrollLeft / itemWidth) - 1;
scrollEnd = Math.ceil((scrollLeft + clientWidth) / itemWidth) + 1;
}
</script> </script>
{#if videoRowData} {#if videoRowData}
@@ -37,13 +62,19 @@
<svelte:self videoRowData={child} /> <svelte:self videoRowData={child} />
{/each} {/each}
{:else if videoRowData.title && videoRowData.videos} {:else if videoRowData.title && videoRowData.videos}
<div class="text-lg font-semibold m-4">{videoRowData.title}</div> <div class="text-lg font-semibold m-4">
{videoRowData.title}
</div>
<div <div
class="carousel carousel-center rounded-box w-full space-x-4" class="carousel carousel-center rounded-box w-full space-x-4"
bind:this={carouselElement}
on:scroll={recalculateVisibileCells}
> >
{#each videoRowData.videos as video} {#each videoRowData.videos as video, i}
<div class="carousel-item"> <div class="carousel-item w-80 p-2">
<VideoCell {...video} /> {#if i >= scrollStart && i <= scrollEnd}
<VideoCell {...video} />
{/if}
</div> </div>
{/each} {/each}
</div> </div>
+49 -8
View File
@@ -14,23 +14,45 @@
id: "App ID", id: "App ID",
}; };
function transformValue(key, value) {
switch (key) {
case "version":
case "lib_version":
case "lib_version_latest":
return `<a class="link" href="https://github.com/iBicha/playlet/releases/tag/v${value}" target="_blank" rel="noopener noreferrer">${value}</a>`;
case "lib_url":
return `<a class="link" href="${value}" target="_blank" rel="noopener noreferrer">${value}</a>`;
case "git_commit_hash":
case "lib_git_commit_hash":
if (value === "unknown") {
return value;
}
return `<a class="link" href="https://github.com/iBicha/playlet/commit/${value}" target="_blank" rel="noopener noreferrer">${value}</a>`;
default:
break;
}
return value;
}
let appInfo = {}; let appInfo = {};
let deviceInfo = {}; let deviceInfo = {};
let invidiousInfo = {}; let invidiousInfo = {};
let preferencesInfo = {}; let preferencesInfo = {};
const feedbackTitle = encodeURIComponent("[Feedback] Playlet");
let githubUrlIssue = "https://github.com/iBicha/playlet/issues/new"; let githubUrlIssue = "https://github.com/iBicha/playlet/issues/new";
let mailToUrl = "mailto:brahim.hadriche@gmail.com";
playletStateStore.subscribe((value) => { playletStateStore.subscribe((value) => {
appInfo = value.app || {}; appInfo = value.app || {};
deviceInfo = value.device || {}; deviceInfo = value.device || {};
invidiousInfo = value.invidious || {}; invidiousInfo = value.invidious || {};
preferencesInfo = value.preferences || {}; preferencesInfo = value.preferences || {};
githubUrlIssue = CreateGithubIssueUrl(); githubUrlIssue = createGithubIssueUrl();
mailToUrl = createMailToUrl();
}); });
function CreateGithubIssueUrl() { function createFeedbackBody() {
let title = "[Feedback] Playlet"; return `### Feedback
let body = `### Feedback
_insert feedback here_ _insert feedback here_
#### App Info #### App Info
@@ -52,13 +74,32 @@ ${JSON.stringify(invidiousInfo, null, 2)}
\`\`\` \`\`\`
${JSON.stringify(preferencesInfo, null, 2)} ${JSON.stringify(preferencesInfo, null, 2)}
\`\`\``; \`\`\``;
return `https://github.com/iBicha/playlet/issues/new?title=${encodeURIComponent(title)}&body=${encodeURIComponent(body)}`; }
function createGithubIssueUrl() {
const body = encodeURIComponent(createFeedbackBody());
return `https://github.com/iBicha/playlet/issues/new?title=${feedbackTitle}&body=${body}`;
}
function createMailToUrl() {
const body = encodeURIComponent(createFeedbackBody());
return `mailto:brahim.hadriche@gmail.com?subject=${feedbackTitle}&body=${body}`;
} }
</script> </script>
<div class={visibility ? "" : "hidden"}> <div class={visibility ? "" : "hidden"}>
<div class="text-base text-center m-8"> <div class="text-base text-center m-8">
Thank you for using Playlet.<br/> You have feedback? Let us know by <a class="link" href={githubUrlIssue} target="_blank" rel="noopener noreferrer">creating an issue on Github</a>. Thank you for using Playlet.<br /> You have feedback? Let us know by
<a
class="link"
href={githubUrlIssue}
target="_blank"
rel="noopener noreferrer">creating an issue on Github</a
>
or by
<a class="link" href={mailToUrl} target="_blank" rel="noopener noreferrer"
>sending an email</a
>.
</div> </div>
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="table"> <table class="table">
@@ -72,10 +113,10 @@ ${JSON.stringify(preferencesInfo, null, 2)}
{#each Object.entries(displayNames) as [key, value]} {#each Object.entries(displayNames) as [key, value]}
<tr> <tr>
<td>{value}</td> <td>{value}</td>
<td>{appInfo[key]}</td> <td>{@html transformValue(key, appInfo[key])}</td>
</tr> </tr>
{/each} {/each}
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
+39 -19
View File
@@ -1,9 +1,9 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte";
import { InvidiousApi } from "./InvidiousApi"; import { InvidiousApi } from "./InvidiousApi";
import { PlayletApi } from "./PlayletApi"; import { PlayletApi } from "./PlayletApi";
import { playletStateStore, searchHistoryStore } from "./Stores"; import { playletStateStore, searchHistoryStore } from "./Stores";
import VideoCell from "./VideoCell.svelte"; import VideoCell from "./VideoCell.svelte";
import SearchThinIcon from "../assets/search-thin-icon.svg.svelte";
export let visibility: boolean; export let visibility: boolean;
@@ -14,6 +14,7 @@
let suggestions: { suggestions: any[] } = { suggestions: [] }; let suggestions: { suggestions: any[] } = { suggestions: [] };
let videos = []; let videos = [];
let searchHistory = []; let searchHistory = [];
let isLoading = false;
playletStateStore.subscribe((value) => { playletStateStore.subscribe((value) => {
invidiousApi.instance = value?.invidious?.current_instance; invidiousApi.instance = value?.invidious?.current_instance;
@@ -76,7 +77,13 @@
return; return;
} }
videos = await invidiousApi.search(searchBoxText); try {
isLoading = true;
videos = await invidiousApi.search(searchBoxText);
} finally {
isLoading = false;
}
const newSearchHistory = await PlayletApi.putSearchHistory(searchBoxText); const newSearchHistory = await PlayletApi.putSearchHistory(searchBoxText);
searchHistoryStore.set(newSearchHistory); searchHistoryStore.set(newSearchHistory);
} }
@@ -90,23 +97,30 @@
await searchVideos(); await searchVideos();
}} }}
> >
<input <div class="join w-full border border-neutral rounded-full">
type="search" <input
dir="auto" type="search"
placeholder="Search..." dir="auto"
class="input w-full border border-neutral rounded-full" placeholder="Search..."
bind:this={searchBox} class="join-item input w-full border border-neutral rounded-full"
bind:value={searchBoxText} bind:this={searchBox}
on:input={searchSuggestions} bind:value={searchBoxText}
on:focus={searchSuggestions} on:input={searchSuggestions}
on:blur={() => { on:focus={searchSuggestions}
// A delay before clearing the suggestions allows the user to click on a suggestion on:blur={() => {
// Clicking the suggestion will trigger the blur event immediately, and the search won't happen // A delay before clearing the suggestions allows the user to click on a suggestion
setTimeout(() => { // Clicking the suggestion will trigger the blur event immediately, and the search won't happen
suggestions = { suggestions: [] }; setTimeout(() => {
}, 200); suggestions = { suggestions: [] };
}} }, 200);
/> }}
/>
<button class="join-item btn" on:click={searchVideos}>
<div class="h-6">
<SearchThinIcon />
</div>
</button>
</div>
{#if suggestions.suggestions.length > 0} {#if suggestions.suggestions.length > 0}
<ul <ul
class="dropdown-content menu z-10 p-2 shadow-xl bg-base-200 rounded-box" class="dropdown-content menu z-10 p-2 shadow-xl bg-base-200 rounded-box"
@@ -127,6 +141,12 @@
</div> </div>
<div> <div>
{#if isLoading}
<div class="fixed w-full h-1/2 z-50 flex justify-center items-center">
<span class="loading loading-spinner loading-md" />
</div>
{/if}
<div <div
class="grid grid-flow-row-dense gap-4 items-center justify-center sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 m-4" class="grid grid-flow-row-dense gap-4 items-center justify-center sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 m-4"
> >
+2
View File
@@ -18,6 +18,8 @@
// svelte-ignore unused-export-let // svelte-ignore unused-export-let
export let defaultValue: any = undefined; export let defaultValue: any = undefined;
// svelte-ignore unused-export-let
export let rokuComponent: any = undefined;
const customComponents = { const customComponents = {
ClearSearchHistoryControl ClearSearchHistoryControl
+57 -19
View File
@@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import { PlayletApi } from "./PlayletApi"; import { PlayletApi } from "./PlayletApi";
import { playletStateStore } from "./Stores"; import { playletStateStore } from "./Stores";
import VideoStartAt from "./VideoStartAt.svelte";
export let title: string | undefined = undefined; export let title: string | undefined = undefined;
export let videoId: string | undefined = undefined; export let videoId: string | undefined = undefined;
@@ -39,6 +40,8 @@
let modal; let modal;
let tvName = "Roku TV"; let tvName = "Roku TV";
let invidiousInstance; let invidiousInstance;
let videoStartAtChecked;
let videoStartAtTimestamp;
playletStateStore.subscribe((value) => { playletStateStore.subscribe((value) => {
tvName = value?.device?.friendly_name ?? "Roku TV"; tvName = value?.device?.friendly_name ?? "Roku TV";
@@ -49,14 +52,14 @@
if (isUpcoming) { if (isUpcoming) {
return `Premeres in ${getFormattedTimeLeft(premiereTimestamp)}`; return `Premeres in ${getFormattedTimeLeft(premiereTimestamp)}`;
} }
const pubText = publishedText || ''; const pubText = publishedText || "";
const viewCountText = formatViewCount(viewCount); const viewCountText = formatViewCount(viewCount);
if (pubText === '' && viewCountText === '') { if (pubText === "" && viewCountText === "") {
return ''; return "";
} }
return `${pubText} • ${viewCountText}`; return `${pubText} • ${viewCountText}`;
} }
function getFormattedTimeLeft(unixTimestamp) { function getFormattedTimeLeft(unixTimestamp) {
@@ -148,10 +151,21 @@
} }
function getFormattedTime(length) { function getFormattedTime(length) {
const minutes = Math.floor(length / 60).toString(); const hours = Math.floor(length / 3600);
const seconds = (length % 60); const minutes = Math.floor((length / 60) % 60);
const seconds = length % 60;
const secondsString = seconds < 10 ? `0${seconds}` : seconds.toString(); const secondsString = seconds < 10 ? `0${seconds}` : seconds.toString();
return minutes + ":" + secondsString; const minutesString =
minutes < 10 && hours > 0 ? `0${minutes}` : minutes.toString();
let formattedTime = minutesString + ":" + secondsString;
if (hours > 0) {
formattedTime = hours.toString() + ":" + formattedTime;
}
return formattedTime;
} }
function isVideoLive() { function isVideoLive() {
@@ -162,24 +176,41 @@
} }
async function playVideoOnTv() { async function playVideoOnTv() {
await PlayletApi.playVideo(videoId); await PlayletApi.playVideo(videoId, videoStartAtTimestamp);
} }
function openInvidiousInNewTab() { function openInvidiousInNewTab() {
window.open(`${invidiousInstance}/watch?v=${videoId}`) let url = `${invidiousInstance}/watch?v=${videoId}`;
if (videoStartAtChecked && videoStartAtTimestamp) {
url += `&t=${videoStartAtTimestamp}`;
}
window.open(url);
} }
</script> </script>
<button class="w-80 p-2" on:click="{modal.showModal()}"> <button class="w-80 p-2" on:click={modal.showModal()}>
<div class="card card-compact bg-base-100 shadow-xl border border-neutral"> <div class="card card-compact bg-base-100 shadow-xl border border-neutral">
<figure class="relative"> <figure class="relative">
<img class="w-full rounded-box" loading="lazy" width="320" height="180" src={getThumbnailUrl()} alt={title} /> <img
class="w-full rounded-box aspect-video object-cover"
loading="lazy"
width="320"
height="180"
src={getThumbnailUrl()}
alt={title}
/>
{#if isVideoLive()} {#if isVideoLive()}
<div class="absolute bottom-2 right-0 bg-red-500 text-white text-sm rounded-sm font-bold pt-1 pb-1 pr-2 pl-2">LIVE</div> <div
{:else} class="absolute bottom-2 right-0 bg-red-500 text-white text-sm rounded-sm font-bold pt-1 pb-1 pr-2 pl-2"
{#if lengthSeconds} >
<div class="absolute bottom-2 right-0 bg-black/70 text-white text-sm rounded-sm pt-1 pb-1 pr-2 pl-2">{getFormattedTime(lengthSeconds)}</div> LIVE
{/if} </div>
{:else if lengthSeconds}
<div
class="absolute bottom-2 right-0 bg-black/70 text-white text-sm rounded-sm pt-1 pb-1 pr-2 pl-2"
>
{getFormattedTime(lengthSeconds)}
</div>
{/if} {/if}
</figure> </figure>
<div class="card-body"> <div class="card-body">
@@ -194,12 +225,19 @@
<form method="dialog" class="modal-box bg-base-100"> <form method="dialog" class="modal-box bg-base-100">
<h3 class="text-lg m-5">{title}</h3> <h3 class="text-lg m-5">{title}</h3>
<div class="flex flex-col"> <div class="flex flex-col">
<VideoStartAt
bind:checked={videoStartAtChecked}
bind:timestamp={videoStartAtTimestamp}
{lengthSeconds}
/>
<button class="btn m-2" on:click={playVideoOnTv}>Play on {tvName}</button> <button class="btn m-2" on:click={playVideoOnTv}>Play on {tvName}</button>
<button class="btn m-2" on:click={openInvidiousInNewTab}>Open in Invidious</button> <button class="btn m-2" on:click={openInvidiousInNewTab}
>Open in Invidious</button
>
<button class="btn m-2">Cancel</button> <button class="btn m-2">Cancel</button>
</div> </div>
</form> </form>
<form method="dialog" class="modal-backdrop"> <form method="dialog" class="modal-backdrop">
<button>close</button> <button>close</button>
</form> </form>
</dialog> </dialog>
+102
View File
@@ -0,0 +1,102 @@
<script lang="ts">
export let checked = false;
export let lengthSeconds = undefined;
export let timestamp = 0;
let textInputElemet;
let timestampText = "";
let timestampRange = 0;
$: {
if (document.activeElement !== textInputElemet) {
timestampText = getFormattedTime(timestamp);
}
}
$: timestampRange = timestamp !== undefined ? timestamp : 0;
function getTimeStamp(timestampText) {
if (timestampText === "") {
return 0;
}
const match = /^((\d+):)?(\d{1,2}):(\d{1,2})$/.exec(timestampText);
if (match) {
const hours = match[2] ? parseInt(match[2]) : 0;
const minutes = parseInt(match[3]);
const seconds = parseInt(match[4]);
if (minutes < 60 && seconds < 60) {
return hours * 3600 + minutes * 60 + seconds;
}
}
}
function getFormattedTime(length) {
if (length === undefined) {
return undefined;
}
const hours = Math.floor(length / 3600);
const minutes = Math.floor((length / 60) % 60);
const seconds = length % 60;
const secondsString = seconds < 10 ? `0${seconds}` : seconds.toString();
const minutesString =
minutes < 10 && hours > 0 ? `0${minutes}` : minutes.toString();
let formattedTime = minutesString + ":" + secondsString;
if (hours > 0) {
formattedTime = hours.toString() + ":" + formattedTime;
}
return formattedTime;
}
</script>
<div class="form-control">
<div class="flex flex-row items-center">
<label class="label justify-start cursor-pointer">
<input type="checkbox" bind:checked class="checkbox" />
<span class="label-text m-2">Start at</span>
</label>
<input
bind:this={textInputElemet}
disabled={!checked}
class="input w-28"
placeholder="0:00"
bind:value={timestampText}
on:input={(e) => {
let newTimestamp = getTimeStamp(e.currentTarget.value);
if (newTimestamp !== undefined && lengthSeconds) {
newTimestamp = Math.min(newTimestamp, lengthSeconds);
}
timestamp = newTimestamp;
}}
on:change={(e) => {
timestampText = getFormattedTime(timestamp) ?? "0:00";
timestamp = getTimeStamp(timestampText);
}}
/>
{#if checked}
{#if timestamp !== undefined}
<span class="label-text m-2">({timestamp}s)</span>
{:else}
<span class="label-text m-2 text-error">(Invalid time)</span>
{/if}
{/if}
</div>
{#if lengthSeconds && checked}
<input
type="range"
min="0"
max={lengthSeconds}
bind:value={timestampRange}
on:input={(e) => {
// @ts-ignore
timestamp = e.currentTarget.value;
}}
class="range range-xs range-primary"
/>
{/if}
</div>
+19 -4
View File
@@ -1,8 +1,9 @@
import { defineConfig, UserConfig } from 'vite' import { defineConfig, UserConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte' import { svelte } from '@sveltejs/vite-plugin-svelte'
import { readFileSync, existsSync } from 'fs'
import { parse as dotEnvParse } from 'dotenv'
import ip from 'ip'; import ip from 'ip';
import { existsSync, readFileSync } from 'fs'
import { join as joinPath } from 'path'
import { parse as dotEnvParse } from 'dotenv'
const PORT = 5173 const PORT = 5173
@@ -14,8 +15,22 @@ const config: UserConfig = {
} }
} }
if (existsSync('../.vscode/.env')) { // TODO: refactor this with the same code in tools/get-env-vars.js
const envVars = dotEnvParse(readFileSync('../.vscode/.env')) function getEnvVars() {
const envFile = joinPath(__dirname, '../.env');
let envVars = process.env;
if (existsSync(envFile)) {
const envConfig = dotEnvParse(readFileSync(envFile));
envVars = { ...envVars, ...envConfig };
}
return envVars;
}
const envVars = getEnvVars();
if (envVars.ROKU_DEV_TARGET) {
config.server = { config.server = {
host: true, host: true,
port: PORT, port: PORT,
+2 -2
View File
@@ -3,7 +3,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=10 minor_version=10
build_version=00000 build_version=00003
## Channel Assets ## Channel Assets
### Main Menu Icons / Channel Poster Artwork ### Main Menu Icons / Channel Poster Artwork
@@ -29,4 +29,4 @@ playlet_lib_debug_url=http://DEBUG_HOST_IP_ADDRESS:8080/playlet-lib.zip
git_commit_sha=unknown git_commit_sha=unknown
bs_const=DEBUG=false;WEB_SERVER_BASIC_AUTH=false;DASH_THUMBNAILS=false;WEB_SOCKETS=true bs_const=DEBUG=false
+7
View File
@@ -0,0 +1,7 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base"
],
"rangeStrategy": "replace"
}
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

File renamed without changes.
+3
View File
@@ -1,3 +1,6 @@
// Description: Generates images for the project.
// Converts SVGs to PNGs and resizes them to the correct dimensions.
const fs = require('fs'); 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');
+15 -4
View File
@@ -1,14 +1,25 @@
// Description: Generates the SponsorBlock config for Playlet
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const { ArgumentParser } = require('argparse')
if (process.argv.length !== 3) { function getArgumentParser() {
console.error("Invalid usage! usage: npm run generate-sponsorblock-config -- sponsorblock_root"); const parser = new ArgumentParser({
exit(-1); description: 'Generate SponsorBlock config'
});
parser.add_argument('--sponsorblock-root', { help: 'Local path to the SponsorBlock repository', required: true });
return parser;
} }
const parser = getArgumentParser();
const args = parser.parse_args()
const PLAYLEY_CONFIG_PATH = "./playlet-lib/src/config/sponsorblock_config.json" const PLAYLEY_CONFIG_PATH = "./playlet-lib/src/config/sponsorblock_config.json"
const sponsorblockRoot = process.argv[2]; const sponsorblockRoot = args.sponsorblock_root;
const configExamplePath = path.join(sponsorblockRoot, "config.json.example") const configExamplePath = path.join(sponsorblockRoot, "config.json.example")
const englishLocalePath = path.join(sponsorblockRoot, "public/_locales/en/messages.json") const englishLocalePath = path.join(sponsorblockRoot, "public/_locales/en/messages.json")
+17
View File
@@ -0,0 +1,17 @@
const dotenv = require('dotenv');
const fs = require('fs');
const path = require('path');
const envFile = path.join(__dirname, '../.env');
function getEnvVars() {
let envVars = process.env;
if (fs.existsSync(envFile)) {
const envConfig = dotenv.parse(fs.readFileSync(envFile));
envVars = { ...envVars, ...envConfig };
}
return envVars;
}
module.exports = getEnvVars
+82 -32
View File
@@ -1,26 +1,81 @@
// This script reads recommendations, subscriptions, watch later, liked, and history from Youtube // Description: Read recommendations, subscriptions, watch later, liked, and history from Youtube
// and imports them into invidious. // and import them into invidious. Requires yt-dlp to be installed.
const { ArgumentParser } = require('argparse') const { ArgumentParser } = require('argparse')
const fs = require('fs'); const fs = require('fs');
const dotenv = require('dotenv'); const getEnvVars = require('./get-env-vars');
const spawn = require('child_process').spawn; const spawn = require('child_process').spawn;
const express = require('express') const express = require('express')
const ip = require('ip'); const ip = require('ip');
const fetch = require('cross-fetch');
const config = dotenv.parse(fs.readFileSync('.vscode/.env')); function getArgumentParser() {
const parser = new ArgumentParser({
description: 'Sync Youtube profile with Invidious'
});
parser.add_argument('--browser', { help: 'Use cookies from browser' });
parser.add_argument('--invidious', { help: 'Invidious instance to sync to' });
parser.add_argument('--output-file', { help: 'Write profile to Invidious JSON compatible file' });
parser.add_argument('--playlist-limit', { help: 'Maximum playlist video count', type: 'int', default: 500 });
return parser;
}
const config = getEnvVars();
const PLAYLEY_SERVER = `http://${config.ROKU_DEV_TARGET}:8888`; const PLAYLEY_SERVER = `http://${config.ROKU_DEV_TARGET}:8888`;
const PLAYLIST_DESCRIPTION = "[Automatically imported from Youtube using profile-sync script]"
const INVIDIOUS_SCOPES = "POST:tokens/unregister,POST:import/invidious,GET:playlists,DELETE:playlists*"
async function importInvidiousProfile(invidiousInstance, token, profile) { async function importInvidiousProfile(invidiousInstance, token, profile) {
console.log(`Importing Invidious profile`) const pieces = splitProfile(profile);
await fetch(`${invidiousInstance}/api/v1/auth/import/invidious`, { console.log(`Importing Invidious profile (${pieces.length} items)`)
headers: { for (let i = 0; i < pieces.length; i++) {
"Authorization": `Bearer ${token}`, const piece = pieces[i];
'Content-Type': 'application/json' console.log(`Importing "${piece.name}" (${i + 1}/${pieces.length})`)
},
method: "POST", await fetch(`${invidiousInstance}/api/v1/auth/import/invidious`, {
body: JSON.stringify(profile) headers: {
}) "Authorization": `Bearer ${token}`,
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(piece.profile)
})
}
}
function splitProfile(profile) {
const pieces = []
if (profile.subscriptions) {
pieces.push({
name: "Subscriptions",
profile: {
subscriptions: profile.subscriptions
}
})
}
if (profile.watch_history) {
pieces.push({
name: "Watch History",
profile: {
watch_history: profile.watch_history
}
})
}
if (profile.playlists) {
profile.playlists.forEach(playlist => {
pieces.push({
name: `Playlist: ${playlist.title}`,
profile: {
playlists: [playlist]
}
})
})
}
return pieces;
} }
async function generatePlaylist(sourceUrl, playlistName, browser = undefined, limit = 100) { async function generatePlaylist(sourceUrl, playlistName, browser = undefined, limit = 100) {
@@ -30,7 +85,7 @@ async function generatePlaylist(sourceUrl, playlistName, browser = undefined, li
return { return {
title: playlistName, title: playlistName,
description: "Imported from Youtube", description: PLAYLIST_DESCRIPTION,
privacy: "private", privacy: "private",
videos: videos videos: videos
}; };
@@ -38,7 +93,8 @@ async function generatePlaylist(sourceUrl, playlistName, browser = undefined, li
async function deletePlaylists(invidiousInstance, token, playlistNames) { async function deletePlaylists(invidiousInstance, token, playlistNames) {
const playlistsToDelete = (await getPlaylists(invidiousInstance, token)) const playlistsToDelete = (await getPlaylists(invidiousInstance, token))
.filter(playlist => playlistNames.indexOf(playlist.title) !== -1); .filter(playlist => playlistNames.indexOf(playlist.title) !== -1)
.filter(playlist => playlist.description === PLAYLIST_DESCRIPTION);
for (let i = 0; i < playlistsToDelete.length; i++) { for (let i = 0; i < playlistsToDelete.length; i++) {
const playlist = playlistsToDelete[i]; const playlist = playlistsToDelete[i];
@@ -136,9 +192,10 @@ async function extractYtDlp(sourceUrl, browser = undefined, limit = 100) {
.map(item => item.trim()) .map(item => item.trim())
.filter(i => i); .filter(i => i);
newItems.forEach(item => {
items.push(item) for (let i = 0; i < newItems.length && (items.length < limit || limit === -1); i++) {
}); items.push(newItems[i])
}
if (limit > 0 && items.length >= limit) { if (limit > 0 && items.length >= limit) {
ytDlpProcess.kill() ytDlpProcess.kill()
@@ -167,8 +224,8 @@ async function getInvidiousInstance() {
throw new Error("Playlet not logged in") throw new Error("Playlet not logged in")
} }
console.log(`Invidious instance: ${state.invidious.logged_in_instance}`) console.log(`Invidious instance: ${state.invidious.current_instance}`)
return state.invidious.logged_in_instance; return state.invidious.current_instance;
} }
async function getAccessToken(invidiousInstance) { async function getAccessToken(invidiousInstance) {
@@ -189,10 +246,10 @@ async function getAccessToken(invidiousInstance) {
server.close() server.close()
}) })
const scope = ":*" const scopes = encodeURIComponent(INVIDIOUS_SCOPES)
const expire = Date.now() + 60 * 60 * 2; const expire = Date.now() + 60 * 60 * 2;
const callbackUrl = `http://${ip.address()}:${port}/invidious/token_callback` const callbackUrl = encodeURIComponent(`http://${ip.address()}:${port}/invidious/token_callback`)
const authLink = `${invidiousInstance}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}` const authLink = `${invidiousInstance}/authorize_token?scopes=${scopes}&callback_url=${callbackUrl}&expire=${expire}`
server = app.listen(port, () => { server = app.listen(port, () => {
console.log(`server is listening on http://localhost:${port}`); console.log(`server is listening on http://localhost:${port}`);
@@ -216,16 +273,9 @@ async function deleteAccessToken(invidiousInstance, token) {
let invidiousInstance = undefined let invidiousInstance = undefined
let token = undefined; let token = undefined;
try { try {
const parser = new ArgumentParser({ const parser = getArgumentParser()
description: 'Sync Youtube profile with Invidious' const args = parser.parse_args()
});
parser.add_argument('--browser', { help: 'Use cookies from browser' });
parser.add_argument('--invidious', { help: 'Invidious instance to sync to' });
parser.add_argument('--output-file', { help: 'Write profile to Invidious JSON compatible file' });
parser.add_argument('--playlist-limit', { help: 'Maximum playlist video count', default: 500 });
let args = parser.parse_args()
invidiousInstance = args.invidious invidiousInstance = args.invidious
browser = args.browser browser = args.browser
outputFile = args.output_file outputFile = args.output_file
+24 -9
View File
@@ -1,15 +1,29 @@
const rokuDeploy = require('roku-deploy'); // Description: Take a screenshot of the Roku device
const dotenv = require('dotenv');
const fs = require('fs');
const { exit } = require('process');
if(process.argv.length !== 3) { const { ArgumentParser } = require('argparse')
console.error("Invalid usage! usage: npm run screenshot -- filename"); const rokuDeploy = require('roku-deploy');
exit(-1); const getEnvVars = require('./get-env-vars');
function getArgumentParser() {
const parser = new ArgumentParser({
description: 'Take a screenshot of the Roku device'
});
parser.add_argument('filename', { help: 'Path where the screenshot will be saved (without extension)' });
return parser;
} }
const filename = process.argv[2]; const parser = getArgumentParser();
const config = dotenv.parse(fs.readFileSync('.vscode/.env')); const args = parser.parse_args()
const filename = args.filename;
const config = getEnvVars();
['ROKU_DEV_TARGET', 'ROKU_DEVPASSWORD'].forEach((key) => {
if (!config[key]) {
throw new Error(`Missing environment variable ${key}`);
}
});
const options = { const options = {
host: config.ROKU_DEV_TARGET, host: config.ROKU_DEV_TARGET,
@@ -25,5 +39,6 @@ const options = {
} }
catch (error) { catch (error) {
console.error(error); console.error(error);
throw error;
} }
})(); })();
+14 -3
View File
@@ -1,8 +1,15 @@
const dotenv = require('dotenv'); // Description: Publish, sign the package and retrieve it from the Roku device
const fs = require('fs'); // It expects release/playelt.zip to exist
const getEnvVars = require('./get-env-vars');
const rokuDeploy = require('roku-deploy'); const rokuDeploy = require('roku-deploy');
const config = dotenv.parse(fs.readFileSync('.vscode/.env')); const config = getEnvVars();
['ROKU_DEV_TARGET', 'ROKU_DEVPASSWORD', 'ROKU_SIGN_PASSWORD'].forEach((key) => {
if (!config[key]) {
throw new Error(`Missing environment variable ${key}`);
}
});
const options = { const options = {
host: config.ROKU_DEV_TARGET, host: config.ROKU_DEV_TARGET,
@@ -17,12 +24,16 @@ const options = {
(async () => { (async () => {
try { try {
// Sideload playlet.zip
await rokuDeploy.publish(options); await rokuDeploy.publish(options);
// Sign the package
const remotePkgPath = await rokuDeploy.signExistingPackage(options); const remotePkgPath = await rokuDeploy.signExistingPackage(options);
// Retrieve the signed package
const localPkgFilePath = await rokuDeploy.retrieveSignedPackage(remotePkgPath, options); const localPkgFilePath = await rokuDeploy.retrieveSignedPackage(remotePkgPath, options);
console.log(`Created signed package: ${localPkgFilePath}`) console.log(`Created signed package: ${localPkgFilePath}`)
} }
catch (error) { catch (error) {
console.error(error); console.error(error);
throw error;
} }
})(); })();
+4
View File
@@ -1,3 +1,7 @@
// Description: Updates the git commit hash in the manifest files.
// It will update both Playlet and Playlet-lib manifest files.
// It will abort if there are any changes in the working directory.
const fs = require('fs'); const fs = require('fs');
const shell = require('shelljs'); const shell = require('shelljs');
+4
View File
@@ -1,3 +1,7 @@
// Description: Updates the version in the manifest files.
// Reads the version from the root package.json and updates the manifest files,
// as well as the package.json files in the playlet-web folder.
const fs = require('fs'); const fs = require('fs');
const { execSync } = require("child_process"); const { execSync } = require("child_process");