Compare commits

...
58 Commits
Author SHA1 Message Date
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
70 changed files with 1135 additions and 478 deletions

No files matched your search

+7 -3
View File
@@ -2,7 +2,11 @@ name: Linter
on:
pull_request:
branches: [ "main" ]
branches: ["main"]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
@@ -23,8 +27,8 @@ jobs:
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: 'npm'
cache: "npm"
- name: Install dependencies
run: npm ci
+39 -9
View File
@@ -2,12 +2,16 @@ name: Release
on:
push:
branches: [ "main" ]
branches: ["main"]
jobs:
release:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
@@ -16,20 +20,46 @@ jobs:
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: 'npm'
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Build Playlet
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
uses: dev-drprasad/delete-tag-and-release@v1.0
with:
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
run: gh release create unstable ./release/playlet.zip ./playlet/src/lib/playlet-lib.zip --notes-file docs/unstable-changelog.md --prerelease --title unstable
env:
+1 -1
View File
@@ -1,7 +1,7 @@
dist/
out/
node_modules
.vscode/.env
.env
**/roku_modules/**
playlet-lib/src/www
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",
"request": "launch",
"envFile": "${workspaceFolder}/.vscode/.env",
"envFile": "${workspaceFolder}/.env",
"host": "${env:ROKU_DEV_TARGET}",
"password": "${env:ROKU_DEVPASSWORD}",
"stopOnEntry": false,
@@ -35,7 +35,7 @@
{
"type": "brightscript",
"request": "launch",
"envFile": "${workspaceFolder}/.vscode/.env",
"envFile": "${workspaceFolder}/.env",
"host": "${env:ROKU_DEV_TARGET}",
"password": "${env:ROKU_DEVPASSWORD}",
"stopOnEntry": false,
@@ -57,6 +57,19 @@
"name": "Playlet Web (Dev)",
"request": "launch",
"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.bsdk": "node_modules/brighterscript",
"editor.formatOnSave": true
}
+18
View File
@@ -5,6 +5,24 @@ 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/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [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
+30 -58
View File
@@ -1,6 +1,8 @@
# Playlet
<!-- markdownlint-disable MD033 -->
<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/>
<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"/>
@@ -17,10 +19,25 @@
</a>
</p>
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
- 🔥 No Ads (Not now, not ever)
- 🕵️ No Tracking
- 🛡️ Privacy driven (uses Invidious backend)
@@ -30,80 +47,32 @@ Playlet is an unofficial Youtube client for Roku 📺
- ⚡ Fast! [Check out how we compare with the official Youtube app](https://youtu.be/qmSvA-QQW20)
### Cast from phone
1. Open "Web app" tab in Playlet
1. Scan QR Code with Phone
1. Browse or search videos
1. Click the video and choose the "Play on TV" option
### Picture-in-picture
- When viewing a video in full screen, press ⬇️ (down) button on your remote to shrink the video
- You can browser or search for videos while you watch
- You can browser or search for videos while you watch
- To restore currently playing video to full screen, press the ✳️ (options) button
### Customize Invidious instance
1. Open settings in Playlet
1. Scan QR Code with Phone
1. Change the Invidious instance
1. You can also do this from the settings tab
## Screenshots
<a href="./screenshots/README.md">
| ![](screenshots/screenshot1.jpg) | ![](screenshots/screenshot2.jpg) | ![](screenshots/screenshot3.jpg) |
|----------------------------------|----------------------------------|----------------------------------|
</a>
More under [Screenshots](./screenshots/README.md)
## 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
1. `git clone https://github.com/iBicha/playlet.git`
1. `cd playlet`
1. `npm install`
Create a file under `playlet/.vscode/.env` containing:
```
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.
For everything related to Playlet app development, please see the [documentation](./docs/README.md)
## Why Playlet
```
```none
playlet - noun
play•let /ˈplālət/
: a short play
@@ -119,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.
## Disclaimer
**Playlet** does not serve or distribute any material from unauthorized sources.<br/>
**Playlet** is simply a frontend to other systems (such as https://github.com/iv-org/invidious), bringing the watching experience to the TV, as opposed to the existing frontends that are web and mobile focused.
**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": [
"roku-log-bsc-plugin",
"@rokucommunity/bslint",
"../tools/asynctask-plugin.ts",
"../tools/manifest-bsconst-debug-plugin.ts"
"../tools/bs-plugins/asynctask-plugin.ts",
"../tools/bs-plugins/manifest-bsconst-debug-plugin.ts"
],
"retainStagingDir": true,
"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.
+8
View File
@@ -2,6 +2,13 @@
# 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
@@ -21,6 +28,7 @@ These are mostly the steps when releasing a new version:
- 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`
View File
File renamed without changes.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 36 KiB

File renamed without changes.
File renamed without changes.

Before

Width:  |  Height:  |  Size: 83 KiB

After

Width:  |  Height:  |  Size: 83 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 80 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 30 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 52 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 43 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 358 KiB

After

Width:  |  Height:  |  Size: 358 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 362 KiB

After

Width:  |  Height:  |  Size: 362 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 99 KiB

After

Width:  |  Height:  |  Size: 99 KiB

+43 -16
View File
@@ -1,12 +1,12 @@
{
"name": "playlet",
"version": "0.10.1",
"version": "0.10.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet",
"version": "0.10.1",
"version": "0.10.2",
"hasInstallScript": true,
"dependencies": {
"bslib": "npm:@rokucommunity/bslib@^0.1.1",
@@ -14,12 +14,13 @@
"roku-requests": "^1.2.0"
},
"devDependencies": {
"@rokucommunity/bslint": "^0.8.6",
"@rokucommunity/bslint": "^0.8.7",
"@types/node": "^20.3.1",
"argparse": "^2.0.1",
"brighterscript": "^0.65.1",
"brighterscript-formatter": "^1.6.29",
"convert-svg-to-png": "^0.6.4",
"cross-fetch": "^4.0.0",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"ip": "^1.1.8",
@@ -29,9 +30,6 @@
"shelljs": "^0.8.5",
"ts-node": "^10.9.1",
"typescript": "^5.1.3"
},
"engines": {
"node": "<19.0.0"
}
},
"node_modules/@cspotcode/source-map-support": {
@@ -163,9 +161,9 @@
"dev": true
},
"node_modules/@rokucommunity/bslint": {
"version": "0.8.6",
"resolved": "https://registry.npmjs.org/@rokucommunity/bslint/-/bslint-0.8.6.tgz",
"integrity": "sha512-PsxZvOI9AvXO1SisJtSKLZUIosE1qhaoN8CgoLYqh4E2j72eL43cVCBj7Bhm1X3I9ykPEd9Wws8c+joca0m2uw==",
"version": "0.8.7",
"resolved": "https://registry.npmjs.org/@rokucommunity/bslint/-/bslint-0.8.7.tgz",
"integrity": "sha512-GitkBck0mSSyksR/YQ9NUn+fZTWmk7+6hq2oyFM7F9zyx72zG1gNo/dM2WzrLf2UzVG5uSF2fMqizcYNI6IZRA==",
"dev": true,
"dependencies": {
"fs-extra": "^10.0.0",
@@ -1341,12 +1339,12 @@
"dev": true
},
"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==",
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.0.0.tgz",
"integrity": "sha512-e4a5N8lVvuLgAWgnCrLr2PP0YyDOTHa9H/Rj54dirp61qXnNq46m82bRhNqIA5VccJtWBvPTFRV3TtvHUKPB1g==",
"dev": true,
"dependencies": {
"node-fetch": "2.6.7"
"node-fetch": "^2.6.12"
}
},
"node_modules/cross-platform-clear-console": {
@@ -2826,9 +2824,9 @@
}
},
"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==",
"version": "2.6.12",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.12.tgz",
"integrity": "sha512-C/fGU2E8ToujUivIO0H+tpQ6HWo4eEmchoPIoXtxCrVghxdKq+QOHqEZW7tuP3KlV3bC8FRMO5nMCC7Zm1VP6g==",
"dev": true,
"dependencies": {
"whatwg-url": "^5.0.0"
@@ -3308,6 +3306,15 @@
"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": {
"version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
@@ -3331,6 +3338,26 @@
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
"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": {
"version": "6.11.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz",
+6 -3
View File
@@ -1,6 +1,6 @@
{
"name": "playlet",
"version": "0.10.1",
"version": "0.10.2",
"description": "Unofficial Youtube client for Roku",
"dependencies": {
"bslib": "npm:@rokucommunity/bslib@^0.1.1",
@@ -14,6 +14,7 @@
"brighterscript": "^0.65.1",
"brighterscript-formatter": "^1.6.29",
"convert-svg-to-png": "^0.6.4",
"cross-fetch": "^4.0.0",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"ip": "^1.1.8",
@@ -44,8 +45,10 @@
"build:lib:dev": "npm run build:lib -- --debug=true",
"build:lib:prod": "npm run build:lib -- --debug=false --sourceMap=false",
"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:fix": "npm run lint -- --fix",
"lint:app": "bslint --project playlet/bsconfig.lint.json --lintConfig config/bslint.jsonc",
"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": "npm run format:base -- --check",
"format:fix": "npm run format:base -- --write",
@@ -59,7 +59,7 @@ function StartFetchTask() as void
' TODO: this whole logic is not good.
' The view should have placeholder, and child nodes get replaced as
' They get ready.
if output = invalid
if output = invalid or not output.success
StartFetchTask()
return
end if
@@ -275,18 +275,22 @@ function OnkeyEvent(key as string, press as boolean) as boolean
end function
function GetFocusedControl() as object
focusedChild = m.top.focusedChild
if focusedChild = invalid
node = m.top.focusedChild
if node = invalid
return invalid
end if
while not focusedChild.id.StartsWith("Control")
focusedChild = focusedChild.focusedChild
if focusedChild = invalid
while not node.id.StartsWith("Control")
child = node.focusedChild
if child = invalid
return invalid
end if
if node.isSameNode(child)
return invalid
end if
node = child
end while
return focusedChild
return node
end function
function MenuGoLeft() as boolean
@@ -299,6 +303,9 @@ end function
function MenuNavigate(direction as integer) as boolean
focusedControl = GetFocusedControl()
if focusedControl = invalid
return false
end if
container = focusedControl.getParent()
containerParent = container.getParent()
containerCount = containerParent.getChildCount()
@@ -3,7 +3,6 @@ function Init()
m.top.observeField("focusedChild", "OnFocusChanged")
m.top.observeField("value", "OnValueChanged")
m.top.observeField("settings", "OnSettingsScreen")
m.keyboardWasClosedByButton = false
end function
function OnSettingsScreen()
@@ -45,15 +44,9 @@ function OnButtonSelected(event as object)
if buttonSelected = 0
m.top.value = keyboard.text
end if
m.keyboardWasClosedByButton = true
keyboard.close = true
end function
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)
end function
@@ -3,26 +3,14 @@ import "pkg:/source/services/SponsorBlock.bs"
@asynctask
function SponsorBlockTask(input as object) as object
videoId = input.videoId
lengthSeconds = input.metadata.lengthSeconds
sponsorBlockResponse = SponsorBlock.GetSkipSegmentsForVideo(videoId)
skipSegments = SponsorBlock.GetSkipSegmentsForVideo(videoId)
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
barPath = `tmp:/sponsorblock_bar_${videoId}.png`
SponsorBlock.GenerateProgressBarBackground(skipSegments, barPath)
SponsorBlock.GenerateProgressBarBackground(skipSegments, lengthSeconds, barPath)
end if
return {
@@ -97,6 +97,9 @@ function OnVideoDetailsTaskResults(output as object) as void
else if isAssocArray(metadata.data)
message += `\nError: ${FormatJson(metadata.data)}`
end if
if isstr(metadata.failureReason)
message += `\nError: ${metadata.failureReason}`
end if
ShowDialog(message, "Video load fail")
CloseVideo()
return
@@ -150,6 +153,8 @@ function OnVideoDetailsTaskResults(output as object) as void
m.top.control = "play"
m.videoContainer@.watchedVideosAdd(videoId)
StartSponsorBlockTask()
end function
function AddDashUrls(playletStreamUrls as object, metadata as object, settings as object) as void
@@ -18,7 +18,6 @@ function SetupSponsorBlock() as void
m.top.trickPlayBar.observeField("visible", "OnTrickPlayBarVisible")
m.chapterLabelTimer = m.top.findNode("chapterLabelTimer")
m.chapterLabelTimer.observeField("fire", "OnChapterLabelTimer")
m.top.observeField("videoId", "StartSponsorBlockTask")
end function
function LoadSponsorBlockSettings() as void
@@ -103,12 +102,19 @@ function UpdateSponsorBlockChapter(time as integer) as void
m.top.chapter = ""
end function
function StartSponsorBlockTask()
function StartSponsorBlockTask() as void
if not m.sponsorBlockEnabled = true
return
end if
if m.sponsorBlockTask <> invalid
m.sponsorBlockTask.control = "stop"
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
function OnSponsorBlockTaskResults(output as object)
@@ -17,7 +17,6 @@ namespace Http
v = request.query.v
local = request.query.local
instance = InvidiousSettings.GetCurrentInstance()
metadata = router.GetVideoMetadata(context, v)
dashUrl = Invidious.GetVideoDashUrl(v, local <> invalid)
@@ -28,10 +27,6 @@ namespace Http
resp = Requests().get(dashUrl, { parseJson: false })
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
text = router.InjectStoryBoard(router, text, metadata)
@@ -19,12 +19,17 @@ namespace Http
token = request.query["token"].DecodeUri().DecodeUriComponent()
referer = request.query["ref"].DecodeUri()
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
username = username.DecodeUriComponent().DecodeUriComponent()
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
end if
response.Redirect("/")
@@ -24,11 +24,15 @@ function WebServerLoop()
m.settings = new Http.HttpSettings(m.webServerPort)
' Root at www to get http://IP_ADDRESS:PORT/index.html
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)
' TODO: server hangs sometimes when timeout is long. Need to investigate
m.settings.Timeout = 500
#if WEB_SOCKETS
' Short interval to keep polling on web socket messages
m.settings.Timeout = 500
m.websocket = new Web.WebSocketServer()
m.websocket.OnMessage(function(context as object)
connection = context.connection
@@ -45,6 +49,14 @@ function WebServerLoop()
return true
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
allowedOrigin = "*"
#else
@@ -84,9 +96,10 @@ function WebServerLoop()
while true
m.server.PreWait()
m.websocket.Poll()
#if WEB_SOCKETS
m.websocket.Poll()
#end if
msg = wait(timeout, msgPort)
msg = wait(0, m.port)
msgType = type(msg)
if msgType = "roSocketEvent" or msg = invalid
m.server.PostWait()
@@ -17,10 +17,9 @@ end function
function QRModes() as object
return {
MODE_NUMERIC : 1 << 0
MODE_ALPHANUMERIC : 1 << 1
MODE_BYTE : 1 << 2
MODE_KANJI : 1 << 3
MODE_NUMERIC: 1 << 0
MODE_ALPHANUMERIC: 1 << 1
MODE_BYTE: 1 << 2
}
end function
@@ -59,7 +58,7 @@ function QRMath() as object
LOG_TABLE[EXP_TABLE[i]] = i
end for
m.QRMath.glog = function (n as integer) as dynamic
m.QRMath.glog = function(n as integer) as dynamic
if n < 1
' print "ERROR: invalid n passed to glog", n
return invalid
@@ -68,7 +67,7 @@ function QRMath() as object
return m.LOG_TABLE[n]
end function
m.QRMath.gexp = function (n as integer) as integer
m.QRMath.gexp = function(n as integer) as integer
while n < 0
n += 255
end while
@@ -112,7 +111,7 @@ function QRPolynomial(num as object, shift as integer) as object
QRMath: QRMath()
}
result.getAt = function (index as integer) as integer
result.getAt = function(index as integer) as integer
if m._num[index] = invalid
return 0
else
@@ -120,11 +119,11 @@ function QRPolynomial(num as object, shift as integer) as object
end if
end function
result.getLength = function () as integer
result.getLength = function() as integer
return m._num.count()
end function
result.multiply = function (e) as object
result.multiply = function(e) as object
num = createObject("roArray", m.getLength() + e.getLength() - 1, false)
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
num[i + j] = 0
end if
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
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
return QRPolynomial(num, 0)
end function
result.modulo = function (e) as object
result.modulo = function(e) as object
if m.getLength() - e.getLength() < 0
return m
end if
@@ -165,36 +164,36 @@ end function
function QRMaskFunctions() as object
result = {}
result.PATTERN000 = function (i, j) as boolean
return (i + j) MOD 2 = 0
result.PATTERN000 = function(i, j) as boolean
return (i + j) mod 2 = 0
end function
result.PATTERN001 = function (i, _j) as boolean
return i MOD 2 = 0
result.PATTERN001 = function(i, _j) as boolean
return i mod 2 = 0
end function
result.PATTERN010 = function (_i, j) as boolean
return j MOD 3 = 0
result.PATTERN010 = function(_i, j) as boolean
return j mod 3 = 0
end function
result.PATTERN011 = function (i, j) as boolean
return (i + j) MOD 3 = 0
result.PATTERN011 = function(i, j) as boolean
return (i + j) mod 3 = 0
end function
result.PATTERN100 = function (i, j) as boolean
return ((i \ 2) + (j \ 3)) MOD 2 = 0
result.PATTERN100 = function(i, j) as boolean
return ((i \ 2) + (j \ 3)) mod 2 = 0
end function
result.PATTERN101 = function (i, j) as boolean
return ((i * j) MOD 2) + ((i * j) MOD 3) = 0
result.PATTERN101 = function(i, j) as boolean
return ((i * j) mod 2) + ((i * j) mod 3) = 0
end function
result.PATTERN110 = function (i, j) as boolean
return (((i * j) MOD 2) + ((i * j) MOD 3)) MOD 2 = 0
result.PATTERN110 = function(i, j) as boolean
return (((i * j) mod 2) + ((i * j) mod 3)) mod 2 = 0
end function
result.PATTERN111 = function (i, j) as boolean
return (((i * j) MOD 3) + ((i + j) MOD 2)) MOD 2 = 0
result.PATTERN111 = function(i, j) as boolean
return (((i * j) mod 3) + ((i + j) mod 2)) mod 2 = 0
end function
return result
@@ -266,7 +265,7 @@ function QRUtil() as object
m.QRUtil = util
util.getBCHDigit = function (data as integer) as integer
util.getBCHDigit = function(data as integer) as integer
digit = 0
data = abs(data)
while data <> 0
@@ -279,15 +278,15 @@ function QRUtil() as object
util.G15_BCHDigit = util.getBCHDigit(util.G15)
util.G18_BCHDigit = util.getBCHDigit(util.G18)
util.getBCHTypeInfo = function (data as integer) as integer
d = data << 10
while m.getBCHDigit(d) - m.G15_BCHDigit >= 0
d = qrXOR(d, (m.G15 << (m.getBCHDigit(d) - m.G15_BCHDigit)))
end while
return qrXOR((data << 10) or d, m.G15_MASK)
util.getBCHTypeInfo = function(data as integer) as integer
d = data << 10
while m.getBCHDigit(d) - m.G15_BCHDigit >= 0
d = qrXOR(d, (m.G15 << (m.getBCHDigit(d) - m.G15_BCHDigit)))
end while
return qrXOR((data << 10) or d, m.G15_MASK)
end function
util.getBCHTypeNumber = function (data as integer) as integer
util.getBCHTypeNumber = function(data as integer) as integer
d = data << 12
while m.getBCHDigit(d) - m.G18_BCHDigit >= 0
d = qrXOR(d, (m.G18 << (m.getBCHDigit(d) - m.G18_BCHDigit)))
@@ -295,11 +294,11 @@ function QRUtil() as object
return (data << 12) or d
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]
end function
util.getMaskFunction = function (maskPattern as integer) as function
util.getMaskFunction = function(maskPattern as integer) as function
masks = QRMaskFunctions()
patterns = QRMaskPatterns()
@@ -315,7 +314,7 @@ function QRUtil() as object
return masks[maskId]
end function
util.getErrorCorrectPolynomial = function (errorCorrectLength as integer) as object
util.getErrorCorrectPolynomial = function(errorCorrectLength as integer) as object
a = QRPolynomial([1], 0)
for i = 0 to errorCorrectLength - 1 step 1
a = a.multiply(QRPolynomial([1, m.QRMath.gexp(i)], 0))
@@ -323,7 +322,7 @@ function QRUtil() as object
return a
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()
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_ALPHANUMERIC then return 9
if mode = modes.MODE_BYTE then return 8
if mode = modes.MODE_KANJI then return 8
else if typeNumber < 27
' 10 - 26
if mode = modes.MODE_NUMERIC then return 12
if mode = modes.MODE_ALPHANUMERIC then return 11
if mode = modes.MODE_BYTE then return 16
if mode = modes.MODE_KANJI then return 10
else if typeNumber < 41
' 27 - 40
if mode = modes.MODE_NUMERIC then return 14
if mode = modes.MODE_ALPHANUMERIC then return 13
if mode = modes.MODE_BYTE then return 16
if mode = modes.MODE_KANJI then return 12
end if
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' -->
<!-- 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="isDark" /><!-- row integer, col integer, returns boolean -->
</interface>
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="utf-8"?>
<component name="QRData" extends="Node">
<interface>
@@ -10,7 +10,6 @@
<field id="MODE_NUMERIC" type="integer" value="1" />
<field id="MODE_ALPHANUMERIC" type="integer" value="2" />
<field id="MODE_BYTE" type="integer" value="4" />
<field id="MODE_KANJI" type="integer" value="8" />
<function name="setData" /><!-- string -->
<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",
"key": "invidious.instance",
"description": "Invidious instance to use",
"description": "Invidious instance to use. Example: https://vid.puffyan.us",
"type": "string"
},
{
+2 -2
View File
@@ -3,11 +3,11 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=10
build_version=00001
build_version=00002
sg_component_libs_provided=PlayletLib
hidden=1
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
+76 -9
View File
@@ -18,10 +18,13 @@ namespace Invidious
const SEARCH_SUGGEST_ENDPOINT = "/api/v1/search/suggestions"
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_PLAYLISTS = "/api/v1/auth/playlists"
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
return {
@@ -72,7 +75,8 @@ namespace Invidious
return {
success: response.ok,
statusCode: response.statuscode,
data: response.json
data: response.json,
failureReason: response.GetFailureReason
}
end function
@@ -151,10 +155,10 @@ namespace Invidious
localIp = GetLocalIpAddress()
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()
scope = `${Invidious.AUTH_SCOPE}`.EncodeUriComponent()
scope = `${Invidious.AUTH_SCOPES}`.EncodeUriComponent()
return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
end function
@@ -164,11 +168,63 @@ namespace Invidious
}
end function
function Logout() as boolean
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
function RefreshAuthToken() as boolean
currentAuthToken = InvidiousSettings.GetAuthToken()
if currentAuthToken = invalid
return false
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)
url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
@@ -177,10 +233,21 @@ namespace Invidious
headers["Content-Type"] = "application/json"
args = {
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)
return true
@@ -147,35 +147,12 @@ class InvidiousService
function DeleteExpiredToken(response as object)
if response.statuscode = 403
print(`Server responded with 403: ${response.text}`)
if m.IsTokenMaybeExpired() = true
print("deleting token...")
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
end if
print(`Invidious instance responded with 403: ${response.text}`)
print("Deleting Invidious token...")
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
end if
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
' TODO: this happens because instance owners do not set hmac_key https://github.com/iv-org/invidious/issues/3854
' Once hmac_key is enforced, this check can be removed.
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)
cacheKey = FormatJson(requestData)
cacheKey = GetMd5(cacheKey)
@@ -21,7 +21,7 @@ namespace InvidiousSettings
return InvidiousSettings.DEFAULT_INSTANCE
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 = {
token: token,
instance: instance
@@ -29,6 +29,12 @@ namespace InvidiousSettings
if username <> invalid
obj.username = username
end if
if scopes <> invalid
obj.scopes = scopes
end if
if expire <> invalid
obj.expire = expire
end if
json = FormatJson(obj)
RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json)
@@ -81,14 +81,24 @@ namespace SponsorBlock
return response.statuscode = 200
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.Clear(&hFFFFFF80)
width = bar.GetWidth()
height = bar.GetHeight()
for each segment in segments
pixelStart = (segment.segment[0] / segment.videoDuration) * width
pixelEnd = (segment.segment[1] / segment.videoDuration) * width
videoDuration = lengthSeconds
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)
' highlight's duration is zero, so it is not visble on the bar.
' Add a couple of pixels to see it
+3 -1
View File
@@ -1,3 +1,5 @@
# 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",
"version": "0.10.1",
"version": "0.10.2",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-web",
"version": "0.10.1",
"version": "0.10.2",
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^2.4.2",
"@tailwindcss/typography": "^0.5.9",
"@tsconfig/svelte": "^4.0.1",
"@tsconfig/svelte": "^5.0.0",
"autoprefixer": "^10.4.14",
"daisyui": "^3.1.6",
"dotenv": "^16.3.1",
@@ -553,9 +553,9 @@
}
},
"node_modules/@tsconfig/svelte": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-4.0.1.tgz",
"integrity": "sha512-B+XlGpmuAQzJqDoBATNCvEPqQg0HkO7S8pM14QDI5NsmtymzRexQ1N+nX2H6RTtFbuFgaZD4I8AAi8voGg0GLg==",
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-5.0.0.tgz",
"integrity": "sha512-iu5BqFjU0+OcLTNQp7fHe6Bf6zdNeJ9IZjLZMqWLuGzVFm/xx+lm//Tf6koPyRmxo55/Snm6RRQ990n89cRKFw==",
"dev": true
},
"node_modules/@types/estree": {
@@ -2609,9 +2609,9 @@
}
},
"@tsconfig/svelte": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-4.0.1.tgz",
"integrity": "sha512-B+XlGpmuAQzJqDoBATNCvEPqQg0HkO7S8pM14QDI5NsmtymzRexQ1N+nX2H6RTtFbuFgaZD4I8AAi8voGg0GLg==",
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-5.0.0.tgz",
"integrity": "sha512-iu5BqFjU0+OcLTNQp7fHe6Bf6zdNeJ9IZjLZMqWLuGzVFm/xx+lm//Tf6koPyRmxo55/Snm6RRQ990n89cRKFw==",
"dev": true
},
"@types/estree": {
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.10.1",
"version": "0.10.2",
"type": "module",
"scripts": {
"dev": "vite",
@@ -11,7 +11,7 @@
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^2.4.2",
"@tailwindcss/typography": "^0.5.9",
"@tsconfig/svelte": "^4.0.1",
"@tsconfig/svelte": "^5.0.0",
"autoprefixer": "^10.4.14",
"daisyui": "^3.1.6",
"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>
import { onMount } from "svelte";
import { PlayletApi } from "./PlayletApi";
import { playletStateStore } from "./Stores";
let selectedRelease = ''
let selectedRelease = "";
let releases = [];
let libUrl;
let libUrlType;
onMount(async () => {
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() {
const response = await fetch(
"https://api.github.com/repos/iBicha/playlet/releases"
@@ -28,7 +60,11 @@
if (version === "") {
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);
alert("Playlet Library version set. Restart playlet to apply changes.");
}
@@ -51,7 +87,10 @@
</div>
<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>
{#each releases as release}
<option disabled={!release.enabled} value={release.name}
-1
View File
@@ -103,7 +103,6 @@
}
// Share/Short url
// TODO: use regex, and support timestamped videos
const YoutubeUrls = [
"https://youtu.be/",
"http://youtu.be/",
+17 -3
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import playletLogoDark from "../assets/logo-dark.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 { appThemeStore, playletStateStore } from "./Stores";
import ThemeSelect from "./ThemeToggle.svelte";
@@ -15,6 +15,16 @@
playletStateStore.subscribe((value) => {
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;
auth_url = value?.invidious?.auth_url;
currentInstance = value?.invidious?.current_instance;
@@ -39,7 +49,11 @@
<div class="navbar bg-base-100 sticky top-0 z-40">
<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>
</div>
<div class="flex-none">
@@ -52,7 +66,7 @@
<div class="dropdown dropdown-end">
<div tabindex="-1" class="btn btn-ghost btn-circle avatar">
<div class="w-8 rounded-full">
<img src={userIcon} alt="User" />
<UserIcon />
</div>
</div>
<ul
+39 -8
View File
@@ -1,14 +1,31 @@
<script lang="ts">
import { InvidiousApi } from "./InvidiousApi";
import {
invidiousVideoApiStore,
playletStateStore,
} from "./Stores";
import { invidiousVideoApiStore, playletStateStore } from "./Stores";
import VideoCell from "./VideoCell.svelte";
export let requestData: any = 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();
playletStateStore.subscribe((value) => {
@@ -29,6 +46,14 @@
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>
{#if videoRowData}
@@ -37,13 +62,19 @@
<svelte:self videoRowData={child} />
{/each}
{: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
class="carousel carousel-center rounded-box w-full space-x-4"
bind:this={carouselElement}
on:scroll={recalculateVisibileCells}
>
{#each videoRowData.videos as video}
<div class="carousel-item">
<VideoCell {...video} />
{#each videoRowData.videos as video, i}
<div class="carousel-item w-80 p-2">
{#if i >= scrollStart && i <= scrollEnd}
<VideoCell {...video} />
{/if}
</div>
{/each}
</div>
+49 -8
View File
@@ -14,23 +14,45 @@
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 deviceInfo = {};
let invidiousInfo = {};
let preferencesInfo = {};
const feedbackTitle = encodeURIComponent("[Feedback] Playlet");
let githubUrlIssue = "https://github.com/iBicha/playlet/issues/new";
let mailToUrl = "mailto:brahim.hadriche@gmail.com";
playletStateStore.subscribe((value) => {
appInfo = value.app || {};
deviceInfo = value.device || {};
invidiousInfo = value.invidious || {};
preferencesInfo = value.preferences || {};
githubUrlIssue = CreateGithubIssueUrl();
githubUrlIssue = createGithubIssueUrl();
mailToUrl = createMailToUrl();
});
function CreateGithubIssueUrl() {
let title = "[Feedback] Playlet";
let body = `### Feedback
function createFeedbackBody() {
return `### Feedback
_insert feedback here_
#### App Info
@@ -52,13 +74,32 @@ ${JSON.stringify(invidiousInfo, 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>
<div class={visibility ? "" : "hidden"}>
<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 class="overflow-x-auto">
<table class="table">
@@ -72,10 +113,10 @@ ${JSON.stringify(preferencesInfo, null, 2)}
{#each Object.entries(displayNames) as [key, value]}
<tr>
<td>{value}</td>
<td>{appInfo[key]}</td>
<td>{@html transformValue(key, appInfo[key])}</td>
</tr>
{/each}
</tbody>
</table>
</div>
</div>
</div>
+39 -19
View File
@@ -1,9 +1,9 @@
<script lang="ts">
import { onMount } from "svelte";
import { InvidiousApi } from "./InvidiousApi";
import { PlayletApi } from "./PlayletApi";
import { playletStateStore, searchHistoryStore } from "./Stores";
import VideoCell from "./VideoCell.svelte";
import SearchThinIcon from "../assets/search-thin-icon.svg.svelte";
export let visibility: boolean;
@@ -14,6 +14,7 @@
let suggestions: { suggestions: any[] } = { suggestions: [] };
let videos = [];
let searchHistory = [];
let isLoading = false;
playletStateStore.subscribe((value) => {
invidiousApi.instance = value?.invidious?.current_instance;
@@ -76,7 +77,13 @@
return;
}
videos = await invidiousApi.search(searchBoxText);
try {
isLoading = true;
videos = await invidiousApi.search(searchBoxText);
} finally {
isLoading = false;
}
const newSearchHistory = await PlayletApi.putSearchHistory(searchBoxText);
searchHistoryStore.set(newSearchHistory);
}
@@ -90,23 +97,30 @@
await searchVideos();
}}
>
<input
type="search"
dir="auto"
placeholder="Search..."
class="input w-full border border-neutral rounded-full"
bind:this={searchBox}
bind:value={searchBoxText}
on:input={searchSuggestions}
on:focus={searchSuggestions}
on:blur={() => {
// A delay before clearing the suggestions allows the user to click on a suggestion
// Clicking the suggestion will trigger the blur event immediately, and the search won't happen
setTimeout(() => {
suggestions = { suggestions: [] };
}, 200);
}}
/>
<div class="join w-full border border-neutral rounded-full">
<input
type="search"
dir="auto"
placeholder="Search..."
class="join-item input w-full border border-neutral rounded-full"
bind:this={searchBox}
bind:value={searchBoxText}
on:input={searchSuggestions}
on:focus={searchSuggestions}
on:blur={() => {
// A delay before clearing the suggestions allows the user to click on a suggestion
// Clicking the suggestion will trigger the blur event immediately, and the search won't happen
setTimeout(() => {
suggestions = { suggestions: [] };
}, 200);
}}
/>
<button class="join-item btn" on:click={searchVideos}>
<div class="h-6">
<SearchThinIcon />
</div>
</button>
</div>
{#if suggestions.suggestions.length > 0}
<ul
class="dropdown-content menu z-10 p-2 shadow-xl bg-base-200 rounded-box"
@@ -127,6 +141,12 @@
</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
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"
>
+1 -1
View File
@@ -192,7 +192,7 @@
<div class="card card-compact bg-base-100 shadow-xl border border-neutral">
<figure class="relative">
<img
class="w-full rounded-box"
class="w-full rounded-box aspect-video object-cover"
loading="lazy"
width="320"
height="180"
+35 -16
View File
@@ -9,7 +9,7 @@
$: {
if (document.activeElement !== textInputElemet) {
timestampText = getTimeStampText(timestamp);
timestampText = getFormattedTime(timestamp);
}
}
@@ -19,27 +19,38 @@
if (timestampText === "") {
return 0;
}
const match = /^(\d{1,3}):(\d{1,2})$/.exec(timestampText);
const match = /^((\d+):)?(\d{1,2}):(\d{1,2})$/.exec(timestampText);
if (match) {
const minutes = parseInt(match[1]);
const seconds = parseInt(match[2]);
if (seconds < 60) {
return minutes * 60 + seconds;
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 getTimeStampText(timestamp) {
if (timestamp === undefined) {
return "";
function getFormattedTime(length) {
if (length === undefined) {
return undefined;
}
const minutes = Math.floor(timestamp / 60);
const remainingSeconds = timestamp % 60;
const hours = Math.floor(length / 3600);
const minutes = Math.floor((length / 60) % 60);
const seconds = length % 60;
const formattedMinutes = String(minutes);
const formattedSeconds = String(remainingSeconds).padStart(2, "0");
const secondsString = seconds < 10 ? `0${seconds}` : seconds.toString();
const minutesString =
minutes < 10 && hours > 0 ? `0${minutes}` : minutes.toString();
return `${formattedMinutes}:${formattedSeconds}`;
let formattedTime = minutesString + ":" + secondsString;
if (hours > 0) {
formattedTime = hours.toString() + ":" + formattedTime;
}
return formattedTime;
}
</script>
@@ -52,11 +63,19 @@
<input
bind:this={textInputElemet}
disabled={!checked}
class="input w-24"
class="input w-28"
placeholder="0:00"
bind:value={timestampText}
on:input={(e) => {
timestamp = getTimeStamp(e.currentTarget.value);
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}
+19 -4
View File
@@ -1,8 +1,9 @@
import { defineConfig, UserConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import { readFileSync, existsSync } from 'fs'
import { parse as dotEnvParse } from 'dotenv'
import ip from 'ip';
import { existsSync, readFileSync } from 'fs'
import { join as joinPath } from 'path'
import { parse as dotEnvParse } from 'dotenv'
const PORT = 5173
@@ -14,8 +15,22 @@ const config: UserConfig = {
}
}
if (existsSync('../.vscode/.env')) {
const envVars = dotEnvParse(readFileSync('../.vscode/.env'))
// TODO: refactor this with the same code in tools/get-env-vars.js
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 = {
host: true,
port: PORT,
+2 -2
View File
@@ -3,7 +3,7 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=10
build_version=00001
build_version=00002
## Channel Assets
### 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
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"
}
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 path = require('path');
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 path = require('path');
const { ArgumentParser } = require('argparse')
if (process.argv.length !== 3) {
console.error("Invalid usage! usage: npm run generate-sponsorblock-config -- sponsorblock_root");
exit(-1);
function getArgumentParser() {
const parser = new ArgumentParser({
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 sponsorblockRoot = process.argv[2];
const sponsorblockRoot = args.sponsorblock_root;
const configExamplePath = path.join(sponsorblockRoot, "config.json.example")
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
// and imports them into invidious.
// Description: Read recommendations, subscriptions, watch later, liked, and history from Youtube
// and import them into invidious. Requires yt-dlp to be installed.
const { ArgumentParser } = require('argparse')
const fs = require('fs');
const dotenv = require('dotenv');
const getEnvVars = require('./get-env-vars');
const spawn = require('child_process').spawn;
const express = require('express')
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 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) {
console.log(`Importing Invidious profile`)
await fetch(`${invidiousInstance}/api/v1/auth/import/invidious`, {
headers: {
"Authorization": `Bearer ${token}`,
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(profile)
})
const pieces = splitProfile(profile);
console.log(`Importing Invidious profile (${pieces.length} items)`)
for (let i = 0; i < pieces.length; i++) {
const piece = pieces[i];
console.log(`Importing "${piece.name}" (${i + 1}/${pieces.length})`)
await fetch(`${invidiousInstance}/api/v1/auth/import/invidious`, {
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) {
@@ -30,7 +85,7 @@ async function generatePlaylist(sourceUrl, playlistName, browser = undefined, li
return {
title: playlistName,
description: "Imported from Youtube",
description: PLAYLIST_DESCRIPTION,
privacy: "private",
videos: videos
};
@@ -38,7 +93,8 @@ async function generatePlaylist(sourceUrl, playlistName, browser = undefined, li
async function deletePlaylists(invidiousInstance, token, playlistNames) {
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++) {
const playlist = playlistsToDelete[i];
@@ -136,9 +192,10 @@ async function extractYtDlp(sourceUrl, browser = undefined, limit = 100) {
.map(item => item.trim())
.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) {
ytDlpProcess.kill()
@@ -167,8 +224,8 @@ async function getInvidiousInstance() {
throw new Error("Playlet not logged in")
}
console.log(`Invidious instance: ${state.invidious.logged_in_instance}`)
return state.invidious.logged_in_instance;
console.log(`Invidious instance: ${state.invidious.current_instance}`)
return state.invidious.current_instance;
}
async function getAccessToken(invidiousInstance) {
@@ -189,10 +246,10 @@ async function getAccessToken(invidiousInstance) {
server.close()
})
const scope = ":*"
const scopes = encodeURIComponent(INVIDIOUS_SCOPES)
const expire = Date.now() + 60 * 60 * 2;
const callbackUrl = `http://${ip.address()}:${port}/invidious/token_callback`
const authLink = `${invidiousInstance}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
const callbackUrl = encodeURIComponent(`http://${ip.address()}:${port}/invidious/token_callback`)
const authLink = `${invidiousInstance}/authorize_token?scopes=${scopes}&callback_url=${callbackUrl}&expire=${expire}`
server = app.listen(port, () => {
console.log(`server is listening on http://localhost:${port}`);
@@ -216,16 +273,9 @@ async function deleteAccessToken(invidiousInstance, token) {
let invidiousInstance = undefined
let token = undefined;
try {
const parser = new ArgumentParser({
description: 'Sync Youtube profile with Invidious'
});
const parser = getArgumentParser()
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
browser = args.browser
outputFile = args.output_file
+24 -9
View File
@@ -1,15 +1,29 @@
const rokuDeploy = require('roku-deploy');
const dotenv = require('dotenv');
const fs = require('fs');
const { exit } = require('process');
// Description: Take a screenshot of the Roku device
if(process.argv.length !== 3) {
console.error("Invalid usage! usage: npm run screenshot -- filename");
exit(-1);
const { ArgumentParser } = require('argparse')
const rokuDeploy = require('roku-deploy');
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 config = dotenv.parse(fs.readFileSync('.vscode/.env'));
const parser = getArgumentParser();
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 = {
host: config.ROKU_DEV_TARGET,
@@ -25,5 +39,6 @@ const options = {
}
catch (error) {
console.error(error);
throw error;
}
})();
+14 -3
View File
@@ -1,8 +1,15 @@
const dotenv = require('dotenv');
const fs = require('fs');
// Description: Publish, sign the package and retrieve it from the Roku device
// It expects release/playelt.zip to exist
const getEnvVars = require('./get-env-vars');
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 = {
host: config.ROKU_DEV_TARGET,
@@ -17,12 +24,16 @@ const options = {
(async () => {
try {
// Sideload playlet.zip
await rokuDeploy.publish(options);
// Sign the package
const remotePkgPath = await rokuDeploy.signExistingPackage(options);
// Retrieve the signed package
const localPkgFilePath = await rokuDeploy.retrieveSignedPackage(remotePkgPath, options);
console.log(`Created signed package: ${localPkgFilePath}`)
}
catch (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 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 { execSync } = require("child_process");