Compare commits

...
109 Commits
Author SHA1 Message Date
Brahim Hadriche 13cd469400 Release v0.40.4 (#658) 2025-06-16 20:45:22 -04:00
Brahim Hadriche c66f1376a1 Remove announcement 2025-06-16 20:08:14 -04:00
Brahim Hadriche 840474c20c Fix app launch and app dialog events 2025-06-16 19:35:24 -04:00
Brahim Hadriche 6095901939 [skip ci] delete existing package 2025-06-16 13:40:58 -04:00
Brahim Hadriche 04ed2f82c0 Release v0.40.3 (#657) 2025-06-16 11:39:14 -04:00
Brahim Hadriche 932a629793 [pref] more granular sys logs for better performance 2025-06-16 11:30:37 -04:00
Brahim Hadriche 0fb3759c50 [skip ci] small optm 2025-06-16 11:16:03 -04:00
Brahim Hadriche 7b4306914d Revert "Tools update"
This reverts commit fb2ac53ab6.
2025-06-15 15:36:13 -04:00
Brahim Hadriche fb2ac53ab6 Tools update 2025-06-15 15:33:48 -04:00
Brahim Hadriche fd00c7bb11 update dependencies (#653) 2025-06-13 23:03:57 -04:00
Brahim Hadriche a244cdee05 [skip ci] small cleanup 2025-06-12 09:40:34 -04:00
Brahim Hadriche 8e71ededd2 Add a hint to error message when login is required to view video (#652)
* Add a hint to error message when login is required to view video

* changelog
2025-06-12 09:29:55 -04:00
Brahim Hadriche 8051458df7 Release v0.40.2 (#650) 2025-06-11 21:47:03 -04:00
Brahim Hadriche 4dae928a03 [skip ci] remove no-op call for no caching 2025-06-10 13:43:53 -04:00
Brahim Hadriche d054dd64a5 Playlet backend channel sort options (#649)
* Playlet backend channel sort options

* tweak
2025-06-10 09:29:55 -04:00
Brahim Hadriche 68aeec3d6f Parse authorId from authenticated feeds (#648) 2025-06-09 19:38:51 -04:00
Brahim Hadriche fc2ffd8c23 Revert "[skip ci][perf] do not listen on tasks that have no callbacks" (#647)
* Revert "[skip ci][perf] do not listen on tasks that have no callbacks"

This reverts commit 0bc5ab6117.

* changelog
2025-06-09 16:25:27 -04:00
Brahim Hadriche 4906b69f4a [skip ci] small refactor 2025-06-09 16:19:47 -04:00
Brahim Hadriche 2c513afafd Release v0.40.1 (#646) 2025-06-07 15:13:48 -04:00
Brahim Hadriche 8e156b27f9 update dependencies (#643) 2025-06-07 15:04:45 -04:00
Brahim Hadriche 58e2b48409 Fix a bug where searching in web app using iOS causes page to reload (#645)
* Fix a bug where searching in web app using iOS causes page to reload

* Add cors handler in prod
2025-06-07 10:55:07 -04:00
Brahim Hadriche 06326d084e Refactor potoken 2025-06-05 20:48:23 -04:00
Brahim Hadriche 0b5bed45cf changelog 2025-06-04 17:39:44 -04:00
Weblate (bot)andLacey Anaya 957ac66d70 Translated using Weblate (German) (#639)
Currently translated at 99.4% (344 of 346 strings)

Translation: Playlet/Playlet
Translate-URL: https://hosted.weblate.org/projects/playlet/playlet/de/

Co-authored-by: Lacey Anaya <yecakeh263@anawalls.com>
2025-06-04 17:39:29 -04:00
Brahim Hadriche 03679b781c [Spike] ytjs and botguard in web app (#638)
* [Spike] ytjs and boguard in web app

* storyboards and captions

* cache potoken

* captions fix

* Increase session data to 7 days

* changelog

* Fix missing timestamp issue
2025-06-04 17:34:56 -04:00
Brahim Hadriche 002307c45b Small fix on http request hanging 2025-06-03 22:06:37 -04:00
Brahim Hadriche fcfda78f2c update node version 2025-06-03 22:05:38 -04:00
Brahim Hadriche 384f41ba99 [skip ci] update user agent, small locale fix 2025-06-03 11:29:52 -04:00
Brahim Hadriche e070fc2df1 Refactor inital seeking 2025-06-02 13:34:53 -04:00
Brahim Hadriche 51d63d2019 Fix small bug with sponsorblock task 2025-06-02 13:32:58 -04:00
Brahim Hadriche 1eeaced04b Fix a bug where it says "(Failed to load)" when switching profiles 2025-06-01 17:53:27 -04:00
Brahim Hadriche 891a5f8405 Release v0.40.0 (#636) 2025-06-01 16:56:02 -04:00
Brahim Hadriche 7ab98024c1 [skip ci] tweak sponsorblock notification timing 2025-06-01 16:43:51 -04:00
Brahim Hadriche c2b6b75f94 navbar tweak 2025-06-01 16:01:57 -04:00
Weblate (bot)andEttore Atalan 2e09239123 Translated using Weblate (German) (#635)
Currently translated at 97.9% (331 of 338 strings)

Translation: Playlet/Playlet
Translate-URL: https://hosted.weblate.org/projects/playlet/playlet/de/

Co-authored-by: Ettore Atalan <atalanttore@googlemail.com>
2025-06-01 15:38:08 -04:00
Brahim Hadricheandgithub-action linter fcae05a0da SponsorBlock categories (#634)
* SponsorBlock categories

* perf

* remove todo

* tweak

* UI is working

* Lint fix

* changelog

* Bug fix

* Restore timer

* Locale

* Comment

* tweaks

* web app

* remove unsued svelte ignore

* lint web app

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2025-06-01 15:30:58 -04:00
Brahim Hadriche 0bc5ab6117 [skip ci][perf] do not listen on tasks that have no callbacks 2025-06-01 08:04:09 -04:00
Brahim Hadriche cfd6bc8ec8 [skip ci] rename stat titles to match dashboard 2025-06-01 07:59:45 -04:00
Brahim Hadriche 47896ae9dc UI adjustment 2025-05-31 15:11:36 -04:00
Brahim Hadricheandgithub-action linter 9e3da6b67d Refactor for activeIdentityToken (#631)
* Refactor for activeIdentityToken

* Account selector stuff

* Small refactor

* Tweak

* That's a wrap

* comment

* Lint fix

* Localize

* Lint fix

* Close view on error

* parse error when gathering tracking urls

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2025-05-31 14:40:33 -04:00
Brahim Hadriche 4c94db2c03 [skip ci] support previous/next buttons in the browser to switch between tabs 2025-05-31 10:43:38 -04:00
Brahim Hadriche 8ff4847977 update dependencies (#625) 2025-05-31 10:22:24 -04:00
Brahim Hadriche 65a4a855a1 changelog 2025-05-30 16:44:21 -04:00
Weblate (bot)andLacey Anaya 40e7014e55 Translated using Weblate (German) (#632)
Currently translated at 100.0% (328 of 328 strings)

Translation: Playlet/Playlet
Translate-URL: https://hosted.weblate.org/projects/playlet/playlet/de/

Co-authored-by: Lacey Anaya <yecakeh263@anawalls.com>
2025-05-30 16:43:58 -04:00
Brahim Hadriche d5f74d41c0 [skip ci][tech debt] Fix localization plugin and missing items (#633)
* Fix localization plugin and missing items

* changelog fix

* Testing validation for config files
2025-05-30 16:39:00 -04:00
Brahim Hadriche 91081e09d5 [skip ci] small optimization 2025-05-30 16:24:07 -04:00
Brahim Hadriche e7fbe5c189 [skip ci] small tweak 2025-05-30 12:39:41 -04:00
Brahim Hadriche 0151f4c81c [skip ci] log innertube alerts 2025-05-23 18:32:04 -04:00
Brahim Hadriche e28c92c3d4 Show videos watch progress in playlist view 2025-05-23 18:11:46 -04:00
Brahim Hadriche 4676b45567 Release v0.39.1 (#624) 2025-05-23 17:50:25 -04:00
Brahim Hadriche 438050fcca [skip ci] Fix regression with watch progress introduced in previous release 2025-05-23 17:47:40 -04:00
Brahim Hadriche 70e2608e59 Release v0.39.0 (#622) 2025-05-23 12:35:18 -04:00
Brahim Hadriche d2d875f124 Fix a couple of regressions 2025-05-23 12:29:53 -04:00
Brahim Hadriche 6a1069337d Ignore statementBannerRenderer 2025-05-23 10:58:10 -04:00
Brahim Hadriche eb67d9e4c0 Disable shorts (#620)
* Disable shorts

* Rename setting

* changelog
2025-05-22 22:13:44 -04:00
Brahim Hadriche 6d9117a2a0 [skip ci] Avoid loading old preferences every time if not needed 2025-05-22 18:36:10 -04:00
Brahim Hadriche ab246e8080 Release v0.38.2 (#619) 2025-05-22 18:06:24 -04:00
Brahim Hadriche 7f3591409e [skip ci] delete openapi spec 2025-05-22 18:03:08 -04:00
Brahim Hadriche 650e70f271 [skip ci] locale 2025-05-22 17:58:55 -04:00
Brahim Hadriche a9f70b48aa Remove open api spec 2025-05-22 17:46:52 -04:00
Brahim Hadriche becb8b04f5 Refactor settings 2025-05-22 17:41:47 -04:00
Brahim Hadriche 68a4f9fade Show lines in playlist view 2025-05-21 21:21:42 -04:00
Brahim Hadriche 07ebd011cf Refresh client versions 2025-05-21 20:17:53 -04:00
Brahim Hadriche d210d84d63 changelog 2025-05-21 12:08:48 -04:00
Weblate (bot)andLacey Anaya 1e129e9a73 Translated using Weblate (German) (#616)
Currently translated at 100.0% (320 of 320 strings)

Translation: Playlet/Playlet
Translate-URL: https://hosted.weblate.org/projects/playlet/playlet/de/

Co-authored-by: Lacey Anaya <yecakeh263@anawalls.com>
2025-05-21 12:08:35 -04:00
Brahim Hadriche 1c6b47a5a6 Handle TILE_CONTENT_TYPE_SHORTS 2025-05-21 09:06:17 -04:00
Brahim Hadriche 013e2f49ca Release v0.38.1 (#614) 2025-05-20 12:30:45 -04:00
Brahim Hadriche d2fbd59d6a Fix video does not continuing from previous progress when opened 2025-05-20 12:27:21 -04:00
Brahim Hadriche f681a7024c Fix history cache, show percent watched in web app 2025-05-19 18:56:07 -04:00
Brahim Hadriche e9c2ab9f76 Release v0.38.0 (#613) 2025-05-19 18:02:20 -04:00
Brahim Hadriche aed102f57a Fix a bug where watch history videos repeat indefinitely 2025-05-19 17:50:50 -04:00
Brahim Hadricheandgithub-action linter 8b123b18f5 Watching progress (#609)
* Watching progress

* watch time endpoint

* Lint fix

* Changelog

* options mandatory

* tweak

* tweak

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2025-05-19 17:35:35 -04:00
Brahim Hadriche 158788b42e [skip ci] typo 2025-05-17 17:37:21 -04:00
Brahim Hadriche 8d42c0213b Fix proxying in dash manifest (#607)
* Fix proxying in dash manifest

* Changelog
2025-05-17 16:25:24 -04:00
Brahim Hadriche 7c1aa80819 Fix a bug where playlists with small number of videos has duplicates 2025-05-17 15:17:43 -04:00
Brahim Hadriche 30ea007502 A couple of fixes 2025-05-17 09:42:19 -04:00
Brahim Hadriche fc7a029147 [chore] update dependencies (#606)
* update dependencies

* Backend changes
2025-05-16 23:43:10 -04:00
Brahim Hadriche cbb34d45fc Release v0.37.0 (#605)
* Release v0.37.0

* web app adjustments
2025-05-16 18:19:52 -04:00
Brahim Hadriche beeb21283d [skip ci] error formatting tweak 2025-05-16 11:59:02 -04:00
Brahim Hadriche 89ec969c40 YouTube account support enabled 2025-05-15 22:44:41 -04:00
Brahim Hadriche 0e226cfc42 CORS change 2025-05-15 22:22:52 -04:00
Brahim Hadriche 5762de656c Ignore videoSurveyShelfRenderer 2025-05-15 22:18:01 -04:00
Brahim Hadriche a721cd3f0a [skip ci] YouTube account disclaimer 2025-05-15 22:11:24 -04:00
Brahim Hadriche 8c0692dc10 Fix formatting 2025-05-15 21:56:38 -04:00
Brahim Hadriche 21c7aee907 [skip ci] Update Privacy 2025-05-15 21:55:01 -04:00
Brahim Hadriche 227a5157a5 Parse metadata lines on tv feeds 2025-05-15 21:50:40 -04:00
Brahim Hadriche 4fc44becd2 OAuth: mark video watched (#604)
* OAuth: mark video watched

* remove comment

* Tweaks
2025-05-15 18:29:18 -04:00
Brahim Hadricheandgithub-action linter 918b763384 OAuth: subscribe/unsubscribe (#603)
* OAuth: subscribe/unsubscribe

* Lint fix

* Cancel fetch status when subscribe button is clicked

* tweak

* error handling

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2025-05-14 20:11:18 -04:00
Brahim Hadriche e821464451 OAuth: recommended feed 2025-05-13 18:08:34 -04:00
Brahim Hadriche fb030cee97 OAuth: Fix auth playlist duplication issue 2025-05-13 13:56:32 -04:00
Brahim Hadriche 6e13e3009a [skip ci] Make username label wider 2025-05-12 22:18:15 -04:00
Brahim Hadriche b38f105e02 Private playlists, continuation 2025-05-12 19:58:07 -04:00
Brahim Hadriche 9b58bf47ad Do not print auth token to logs 2025-05-11 20:05:10 -04:00
Brahim Hadriche af12ac43be [skip ci] Display YouTube profile in web app 2025-05-11 19:47:38 -04:00
Brahim Hadriche 32f0477f36 OAuth fix lock from web app in case Invidious instance is not Playlet backend 2025-05-11 19:47:16 -04:00
Brahim Hadriche dcadb1ec17 Add Canadian english locale file 2025-05-11 15:58:10 -04:00
Brahim Hadriche 02c9358eb1 [skip ci] ignore adsControlFlowOpportunityReceivedCommand 2025-05-11 15:47:46 -04:00
Brahim Hadriche dea178f78e [skip ci] ignore adSlotRenderer 2025-05-11 15:42:25 -04:00
Brahim Hadriche 1268f63bbc Fix isue with web app fetching translation for locale en_CA 2025-05-11 12:41:37 -04:00
Brahim Hadriche cd10f237f4 [skip ci] Handle singleColumnBrowseResultsRenderer 2025-05-10 22:39:01 -04:00
Brahim Hadriche 64c23ade48 update dependencies (#600) 2025-05-10 21:12:01 -04:00
Brahim Hadricheandgithub-action linter 1dcd88a9a4 OAuth refresh token (#601)
* OAuth refresh token

* Lint fix

* tweak refresh logic

* error handling cancelled request

* Ignore endScreenPlaylistRenderer

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2025-05-10 21:04:07 -04:00
Brahim Hadriche b040b2997c Rotate visitor data every day 2025-05-08 21:48:52 -04:00
Brahim Hadriche 21a10705f1 Handle unauthorized case in backend 2025-05-06 17:05:01 -04:00
Brahim Hadriche 1120d40085 [skip ci] skip genericPromoRenderer 2025-05-05 21:56:16 -04:00
Brahim Hadriche 2b633888f4 [skip ci] TODO for adding "mark as watched" 2025-05-05 20:06:47 -04:00
Brahim Hadriche af4a6ee726 placeholder 2025-05-05 20:05:26 -04:00
Brahim Hadricheandgithub-action linter f3f9327c1c Process local http request (#599)
* Local http?

* option utils

* Fix for hanging web app

* Lint fix

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2025-05-05 17:21:12 -04:00
Brahim Hadriche fae875845a Remove workaround no longer needed 2025-05-04 10:47:19 -04:00
174 changed files with 5406 additions and 2301 deletions

No files matched your search

+2 -2
View File
@@ -24,10 +24,10 @@ jobs:
git config --local user.email "githubaction@githubaction.com" git config --local user.email "githubaction@githubaction.com"
git config --local user.name "github-action linter" git config --local user.name "github-action linter"
- name: Use Node.js 20.x - name: Use Node.js 22.x
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20.x node-version: 22.x
cache: "npm" cache: "npm"
- name: Install dependencies - name: Install dependencies
+2 -2
View File
@@ -19,10 +19,10 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Use Node.js 20.x - name: Use Node.js 22.x
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20.x node-version: 22.x
cache: "npm" cache: "npm"
- name: Install dependencies - name: Install dependencies
+2 -2
View File
@@ -17,10 +17,10 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Use Node.js 20.x - name: Use Node.js 22.x
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20.x node-version: 22.x
cache: "npm" cache: "npm"
- name: Install dependencies - name: Install dependencies
+2 -2
View File
@@ -24,10 +24,10 @@ jobs:
git config --local user.name "github-action wiki updater" git config --local user.name "github-action wiki updater"
working-directory: ./playlet.wiki working-directory: ./playlet.wiki
- name: Use Node.js 20.x - name: Use Node.js 22.x
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20.x node-version: 22.x
cache: "npm" cache: "npm"
- name: Install dependencies - name: Install dependencies
+2 -2
View File
@@ -12,10 +12,10 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Use Node.js 20.x - name: Use Node.js 22.x
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20.x node-version: 22.x
cache: "npm" cache: "npm"
- name: Install dependencies - name: Install dependencies
+138 -1
View File
@@ -5,6 +5,143 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.40.4] - 2025-06-17
### Fixed
- Few changes preparing for app store submission
## [0.40.3] - 2025-06-16
### Fixed
- Added a "hint" in the error message when playing a video and login is required.
- Various performance improvements
## [0.40.2] - 2025-06-12
### Added
- Channel sort options in Playlet backend (sort videos by Newest, Oldest, Popular)
### Fixed
- [Perf] reverted a perf fix that wasn't helping
- A bug where "Open channel" didn't show up in videos and playlists from logged user
## [0.40.1] - 2025-06-07
### Added
- A way to play longer videos using the web app (Play using ytjs)
- German translations
### Fixed
- A bug where it says "(Failed to load)" when switching profiles
- A bug where searching in web app using iOS causes page to reload
### Changed
- Session data duration: increased to 7 days, to avoid Innertube errors
## [0.40.0] - 2025-06-01
### Added
- German translations
- Support for multi-accounts, such as brand accounts
- Support for manual skip in SponsorBlock
- Customize SponsorBlock categories from the settings
### Fixed
- Show videos watch progress in playlist view
- Missing localization in certain views
## [0.39.1] - 2025-05-23
### Fixed
- Regression with watch progress introduced in previous release
## [0.39.0] - 2025-05-23
### Added
- New settings category: `Content Feed`
- New setting: `Disable Shorts`
### Fixed
- A regression with thumbnails not showing from previous release
- Inability to login to Invidious when selected backend is Playlet (local)
## [0.38.2] - 2025-05-22
### Added
- German translation
### Changed
- Settings: Added a "backend" section, and removed backend selection from Playback to avoid confusion
### Removed
- [advanced users]: `playlet-web-api.yml` was removed. It was getting outdated, and too hard to maintain to justify keeping it
### Fixed
- Display issue in playlist view
## [0.38.1] - 2025-05-20
### Fixed
- Cache issue for watch history
- Video progress not showing in web app
- Video does not continuing from previous progress when opened
## [0.38.0] - 2025-05-19
### Added
- Watch progress for YouTube accounts: Progress is saved as you watch. Progress bar is shown on video thumbnails (only on user feeds, such as recommendations, subscriptions, and watch history)
- Known bug: Watch progress doesn't update for all videos.
### Fixed
- A few issues related to Playlet backend feeds and caching
- An error when Invidious doesn't return valid video metadata
- A bug where playlists with small number of videos has duplicates
- A bug where DASH manifest was not generated correctly for proxied Invidious videos
- A bug where watch history videos repeat indefinitely
## [0.37.0] - 2025-05-16
### Added
- YouTube account support. The following features are now available:
- The ability to login to one or multiple accounts
- Both YouTube accounts and Invidious accounts are supported side-by-side
- Subscriptions
- User playlists
- Watch History
- Watched videos on Playlet are added to the watch history
- Subscribe/Unsubscribe
- Recommended videos for logged in YouTube user are available in the home screen
- This feed can be enabled/disabled from the settings
- When an Invidious user is logged in, this becomes "popular" since Invidious does not support recommendations
### Fixed
- A bug where Session data did not refresh after 24 hours
### Changed
- [advanced users]: the Playlet web server's CORS headers are no longer set to `*`, for security reasons.
## [0.36.7] - 2025-05-04 ## [0.36.7] - 2025-05-04
### Fixed ### Fixed
@@ -671,7 +808,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Removed ### Removed
- Xmas theme logo - can't publish it before end of year... ([link](https://blog.roku.com/developer/channel-store-blackouts-2023)) - Xmas theme logo - can't publish it before end of year... ([channel-store-blackouts-2023](https://blog.roku.com/developer/channel-store-blackouts-2023))
## [0.17.3] - 2023-12-13 ## [0.17.3] - 2023-12-13
+5
View File
@@ -32,6 +32,11 @@ Playlet makes requests directly to Innertube instead of Invidious.
Similar to Invidious requests, only the bare minimum and necessary information Similar to Invidious requests, only the bare minimum and necessary information
is sent, which is used to enable the viewing of content. is sent, which is used to enable the viewing of content.
Additionally, when a YouTube account is used in Playlet, Innertube traffic can
become associated with the account, which further reduces user privacy. This
is necessary to use features associated with YouTube accounts, such as
subscriptions, playlists, and watch history.
## SponsorBlock ## SponsorBlock
Playlet may request information from a [SponsorBlock](https://github.com/ajayyy/SponsorBlock) Playlet may request information from a [SponsorBlock](https://github.com/ajayyy/SponsorBlock)
+1
View File
@@ -49,6 +49,7 @@ Can't install from the store? See [How to install Playlet as a sideloaded/dev ap
- 🔥 No Ads (Not now, not ever) - 🔥 No Ads (Not now, not ever)
- 🕵️ No Tracking - 🕵️ No Tracking
- 🛡️ Privacy driven (uses [Invidious](https://invidious.io/) backend) - 🛡️ Privacy driven (uses [Invidious](https://invidious.io/) backend)
- 🙋 User accounts (YouTube and Invidious accounts)
- ⚔️ [SponsorBlock](https://sponsor.ajay.app/) integration (skips undesirable sections in videos) - ⚔️ [SponsorBlock](https://sponsor.ajay.app/) integration (skips undesirable sections in videos)
- 📱 Browse, search, and cast from phone using the YouTube app or the browser - 📱 Browse, search, and cast from phone using the YouTube app or the browser
- 🔮 Picture-in-picture mode - 🔮 Picture-in-picture mode
+1 -3
View File
@@ -166,8 +166,6 @@ Playlet lib comes equipped with a web server that runs on port 8888 when the app
The web server runs on a continuously running [Task](https://developer.roku.com/en-ca/docs/references/scenegraph/control-nodes/task.md) and uses a middeware system to manage routes, serve static files, [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), and more. The web server runs on a continuously running [Task](https://developer.roku.com/en-ca/docs/references/scenegraph/control-nodes/task.md) and uses a middeware system to manage routes, serve static files, [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), and more.
The server's API enpoints are described through the Open API spec file [playlet-web-api.yml](./playlet-web-api.yml)
Please note: while we would like to keep the API stable as much as possible, Playlet can't reasonbly maintain multiple versions of the API like traditional web apis, because it adds complexity and maintainablity burden on an app the runs in constrained environment. In short, we'll try not to break the API, but we might from time to time. Please note: while we would like to keep the API stable as much as possible, Playlet can't reasonbly maintain multiple versions of the API like traditional web apis, because it adds complexity and maintainablity burden on an app the runs in constrained environment. In short, we'll try not to break the API, but we might from time to time.
#### Debug endpoints #### Debug endpoints
@@ -276,7 +274,7 @@ The Playlet web app uses [Tailwind CSS](https://tailwindcss.com/) as its base st
### API calls ### API calls
The Playlet web app communicates with the Playlet Roku app using web APIs. Most of the APIs used are described in the OpenAPI spec [playlet-web-api.yml](./playlet-web-api.yml). The web app also uses Invidious apis documented at [https://docs.invidious.io/api](https://docs.invidious.io/api) The Playlet web app communicates with the Playlet Roku app using web APIs. The web app also uses Invidious apis documented at [https://docs.invidious.io/api](https://docs.invidious.io/api)
#### API calls (proxy authenticated) #### API calls (proxy authenticated)
-644
View File
@@ -1,644 +0,0 @@
openapi: 3.0.0
info:
title: Playlet Web API
version: 0.36.7
description:
Playlet Web API is a RESTful API for controlling the Playlet app on
Roku devices. The API is intended to be used by the Playlet web app, but can
also be used by other apps.
contact:
name: Brahim Hadriche
url: https://github.com/iBicha
email: brahim.hadriche@gmail.com
servers:
- url: http://{ROKU_DEV_TARGET}:{PORT}
description: Playlet server
variables:
ROKU_DEV_TARGET:
description: The IP address of the Roku device
default: 192.168.1.x
PORT:
description: The port number of the Playlet server
default: "8888"
paths:
/api/state:
get:
summary: Get Playlet app state
description: >
Get the current state of the Playlet app. The `key` parameter is
optional and can be omitted to get the entire state. If the `key`
parameter is specified, only the specified key(s) will be returned.
operationId: getPlayletState
parameters:
- name: key
in: query
description: specific key(s) to get
required: false
schema:
type: array
items:
type: string
enum:
- app
- device
- invidious
- preferences
- profiles
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/PlayletAppState"
/api/preferences:
get:
summary: Get preferences
description: |
Get the current user preferences.
operationId: getPreferences
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/PreferencesObject"
put:
summary: Set preferences
description: >
Set the current user preferences. The request body can contain some or
all of the preferences. Any preferences not specified in the request
body will be left unchanged.
operationId: setPreferences
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/PreferencesObject"
responses:
"204":
description: No Content
"400":
description: Bad Request
delete:
summary: Reset preferences
description: |
Reset the current user preferences to their default values.
operationId: resetPreferences
responses:
"204":
description: No Content
/api/search-history:
get:
summary: Get search history
description: |
Get the current search history.
operationId: getSearchHistory
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
type: string
post:
summary: Add to search history
description: |
Add a query to the search history.
operationId: addToSearchHistory
requestBody:
content:
application/json:
schema:
type: object
properties:
query:
type: string
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
type: string
"400":
description: Bad Request
delete:
summary: Clear search history
description: |
Clear the search history.
operationId: clearSearchHistory
responses:
"204":
description: No Content
/api/queue:
get:
summary: Get video queue
description: Get the current videos in the queue.
operationId: getVideoQueue
responses:
"200":
description: OK
content:
application/json:
schema:
type: object
properties:
items:
type: array
items:
$ref: "#/components/schemas/VideoQueueObject"
index:
type: integer
nowPlaying:
$ref: "#/components/schemas/VideoQueueObject"
post:
summary: Add to video queue
description: Add a video or a playlist to the queue.
operationId: addToVideoQueue
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/VideoQueueObject"
responses:
"204":
description: No Content
delete:
summary: Clear video queue
description: Clear the video queue.
operationId: clearVideoQueue
responses:
"204":
description: No Content
/api/queue/play:
post:
summary: Play video
description: Play a video or playlist. This adds the video or playlist to the current position in the queue and plays it.
operationId: playVideoQueue
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/VideoQueueObject"
responses:
"204":
description: No Content
/api/view/open:
get:
summary: Open a channel view or a playlist view
description: Open a channel view or a playlist view. If a video is playing in full screen, it is shrinked.
operationId: openView
parameters:
- name: channelId
in: query
description: The ID of the channel to open
required: false
schema:
type: string
- name: playlistId
in: query
description: The ID of the playlist to open
required: false
schema:
type: string
responses:
"204":
description: No Content
"400":
description: Bad Request
/api/home-layout:
get:
summary: Get home layout
description: Get the current home layout. This is the layout of the home screen, based on user preferences.
operationId: getHomeLayout
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
type: object
properties:
id:
type: string
title:
type: string
feedSources:
type: array
items:
type: object
properties:
apiType:
type: string
endpoint:
type: string
id:
type: string
queryParams:
type: object
additionalProperties: true
title:
type: string
/api/playlet-lib-urls:
get:
summary: Get Playlet lib URLs
description: Get the currently loaded Playlet lib url, and the saved ones to be loaded on next start.
operationId: getPlayletLibUrls
responses:
"200":
description: OK
content:
application/json:
schema:
type: object
properties:
loaded:
type: object
properties:
link:
type: string
type:
type: string
saved:
type: array
items:
type: object
properties:
link:
type: string
type:
type: string
post:
summary: Set Playlet lib URLs
description: >
Set a list of Playlet lib URLs to be loaded on next start. Playlet will try to load them one after the other
until one succeeds.
operationId: setPlayletLibUrls
requestBody:
content:
application/json:
schema:
type: array
items:
type: object
properties:
link:
type: string
type:
type: string
responses:
"204":
description: No Content
"400":
description: Bad Request
delete:
summary: Clear Playlet lib URLs
description: Clear the Playlet lib URLs. This affects the saved links in the registry, and will take effect on next start.
operationId: clearPlayletLibUrls
responses:
"204":
description: No Content
/invidious/login:
get:
summary: Redirect to the Invidious auth URL
description: Redirect to the Invidious auth URL, to allow authorizing an access token. Redirects to the Invidious auth URL.
operationId: invidiousLoginUrl
responses:
"302":
description: Found
headers:
Location:
schema:
type: string
format: uri
/api/profiles:
get:
summary: Get profiles
description: Get the logged profiles, and the currently active profile.
operationId: getProfiles
responses:
"200":
description: OK
content:
application/json:
schema:
type: object
properties:
currentProfile:
type: string
profiles:
type: array
items:
$ref: "#/components/schemas/ProfileObject"
delete:
summary: Logout from a profile
description: Logout from a profile. This will remove the profile from the list of logged profiles.
operationId: logoutProfile
parameters:
- name: id
in: query
description: The ID of the profile to logout
required: true
schema:
type: string
responses:
"200":
description: OK
"400":
description: Bad Request
"404":
description: Not Found
/api/profiles/activate:
post:
summary: Activate a profile
description: Activate a profile. This will set the profile as the active profile.
operationId: activateProfile
requestBody:
content:
application/json:
schema:
type: object
properties:
id:
type: string
responses:
"200":
description: OK
"400":
description: Bad Request
"404":
description: Not Found
# Roku External Control Protocol (ECP)
/input/{appId}:
servers:
- url: http://{ROKU_DEV_TARGET}:8060
description: Roku ECP endpoint
variables:
ROKU_DEV_TARGET:
description: The IP address of the Roku device
default: 192.168.1.x
parameters:
- $ref: "#/components/parameters/ecpAppId"
post:
summary: Send input to Playlet through ECP
description: Send input to Playlet through Roku External Control Protocol (ECP). This enables the deep-linking functionality.
operationId: ecpInput
parameters:
- $ref: "#/components/parameters/ecpContentId"
- $ref: "#/components/parameters/ecpMediaType"
- $ref: "#/components/parameters/ecpVideoId"
- $ref: "#/components/parameters/ecpTimestamp"
- $ref: "#/components/parameters/ecpTitle"
- $ref: "#/components/parameters/ecpAuthor"
responses:
"200":
description: OK
/launch/{appId}:
servers:
- url: http://{ROKU_DEV_TARGET}:8060
description: Roku ECP endpoint
variables:
ROKU_DEV_TARGET:
description: The IP address of the Roku device
default: 192.168.1.x
parameters:
- $ref: "#/components/parameters/ecpAppId"
post:
summary: Launch Playlet using ECP with arguments
description: Launch Playlet through Roku External Control Protocol (ECP) with arguments. This enables the deep-linking functionality.
operationId: ecpLaunch
parameters:
- $ref: "#/components/parameters/ecpClearPlayletLibUrls"
- $ref: "#/components/parameters/ecpContentId"
- $ref: "#/components/parameters/ecpMediaType"
- $ref: "#/components/parameters/ecpVideoId"
- $ref: "#/components/parameters/ecpTimestamp"
- $ref: "#/components/parameters/ecpTitle"
- $ref: "#/components/parameters/ecpAuthor"
responses:
"200":
description: OK
components:
parameters:
ecpAppId:
name: appId
in: path
description: The app ID of the Playlet app
required: true
schema:
type: string
enum:
- "693751" # Playlet app id
- dev
default: "693751"
ecpContentId:
name: contentId
in: query
description: The ID of the content to play. If specified with mediaType=video, this is the videoId.
required: false
schema:
type: string
ecpMediaType:
name: mediaType
in: query
description: The type of the content of ContentId. To be used with the contentId argument.
required: false
schema:
type: string
enum:
- video
ecpVideoId:
name: videoId
in: query
description: The video ID of the video to play. If specified, the video will be played.
required: false
schema:
type: string
ecpTimestamp:
name: timestamp
in: query
description: The timestamp of the video to play. To be used with the contentId argument.
required: false
schema:
type: integer
ecpTitle:
name: title
in: query
description: The title of the video. This is optionally added so we can display the title while loading, or when displaying the "Added to queue" notification.
required: false
schema:
type: string
ecpAuthor:
name: author
in: query
description: The author of the video. This is optionally added so we can display the author while loading, or when displaying the "Added to queue" notification.
required: false
schema:
type: string
ecpClearPlayletLibUrls:
name: clearPlayletLibUrls
in: query
description: If specified, the Playlet lib URLs will be cleared.
required: false
schema:
type: string
schemas:
PlayletAppState:
type: object
properties:
app:
type: object
properties:
id:
type: string
version:
type: string
git_commit_hash:
type: string
lib_version:
type: string
lib_git_commit_hash:
type: string
lib_version_latest:
type: string
lib_url_type:
type: string
device:
type: object
properties:
model:
type: string
model_display_name:
type: string
model_type:
type: string
model_details:
type: object
additionalProperties: true
os_version:
type: object
properties:
build:
type: string
major:
type: string
minor:
type: string
revision:
type: string
display_type:
type: string
display_mode:
type: string
display_aspect_ratio:
type: string
display_size:
type: object
properties:
w:
type: integer
h:
type: integer
video_mode:
type: string
ui_resolution:
type: object
properties:
height:
type: integer
name:
type: string
width:
type: integer
graphics_platform:
type: string
internet_status:
type: boolean
user_country_code:
type: string
friendly_name:
type: string
current_locale:
type: string
invidious:
type: object
properties:
current_instance:
type: string
auth_url:
type: string
preferences:
$ref: "#/components/schemas/PreferencesObject"
profiles:
type: object
properties:
currentProfile:
type: string
profiles:
type: array
items:
$ref: "#/components/schemas/ProfileObject"
PreferencesObject:
type: object
properties:
invidious.instance:
type: string
invidious.proxy_videos:
type: string
enum:
- always
- if_needed
- never
playback.autoplay:
type: string
enum:
- auto
- 720p
playback.preferred_quality:
type: string
sponsorblock.enabled:
type: boolean
sponsorblock.show_notifications:
type: boolean
ProfileObject:
type: object
properties:
id:
type: string
type:
type: string
username:
type: string
serverUrl:
type: string
# TODO:P1 add the rest of properties
VideoQueueObject:
type: object
properties:
videoId:
type: string
playlistId:
type: string
playlistIndex:
type: integer
timestamp:
type: integer
title:
type: string
author:
type: string
+229 -306
View File
File diff suppressed because it is too large. Load diff
+14 -15
View File
@@ -1,40 +1,40 @@
{ {
"name": "playlet", "name": "playlet",
"version": "0.36.7", "version": "0.40.4",
"description": "Unofficial YouTube client for Roku", "description": "Unofficial YouTube client for Roku",
"devDependencies": { "devDependencies": {
"@rokucommunity/bslint": "^0.8.29", "@rokucommunity/bslint": "^0.8.32",
"@types/crypto-js": "^4.2.2", "@types/crypto-js": "^4.2.2",
"@types/fs-extra": "^11.0.4", "@types/fs-extra": "^11.0.4",
"@types/node": "^22.15.3", "@types/node": "^24.0.1",
"@types/xml2js": "^0.4.14", "@types/xml2js": "^0.4.14",
"argparse": "^2.0.1", "argparse": "^2.0.1",
"brighterscript": "0.68.5", "brighterscript": "0.68.5",
"brighterscript-formatter": "^1.7.12", "brighterscript-formatter": "^1.7.15",
"cheerio": "1.0.0-rc.11", "cheerio": "1.0.0-rc.11",
"convert-svg-to-png": "^0.6.4", "convert-svg-to-png": "^0.6.4",
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"dotenv": "^16.5.0", "dotenv": "^16.5.0",
"fs-extra": "^11.3.0", "fs-extra": "^11.3.0",
"glob": "^11.0.2", "glob": "^11.0.3",
"imap": "^0.8.19", "imap": "^0.8.19",
"ip": "^2.0.1", "ip": "^2.0.1",
"json5": "^2.2.3", "json5": "^2.2.3",
"mailparser": "^3.7.2", "mailparser": "^3.7.3",
"protocol-buffers-schema": "^3.6.0", "protocol-buffers-schema": "^3.6.0",
"roku-deploy": "^3.12.4", "roku-deploy": "^3.12.6",
"roku-test-automation": "^2.0.13", "roku-test-automation": "^2.0.13",
"rooibos-roku": "5.15.7", "rooibos-roku": "5.15.7",
"rounded-rect-9patch": "^1.1.2", "rounded-rect-9patch": "^1.1.2",
"semver": "^7.7.1", "semver": "^7.7.2",
"shelljs": "^0.9.2", "shelljs": "^0.10.0",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"typescript": "5.8.3", "typescript": "5.8.3",
"xml2js": "^0.6.2", "xml2js": "^0.6.2",
"yaml": "^2.7.1" "yaml": "^2.8.0"
}, },
"engines": { "engines": {
"node": "20" "node": "22"
}, },
"scripts": { "scripts": {
"dev:web": "cd playlet-web && npm run dev", "dev:web": "cd playlet-web && npm run dev",
@@ -47,8 +47,8 @@
"build:lib:dev": "cd playlet-lib && npm run build:dev", "build:lib:dev": "cd playlet-lib && npm run build:dev",
"build:lib:prod": "cd playlet-lib && npm run build:prod", "build:lib:prod": "cd playlet-lib && npm run build:prod",
"build:web": "cd playlet-web && npm run build", "build:web": "cd playlet-web && npm run build",
"lint": "cd playlet-lib && npm run lint && cd ../playlet-app && npm run lint", "lint": "cd playlet-lib && npm run lint && cd ../playlet-app && npm run lint && cd ../playlet-web && npm run lint",
"lint:fix": "cd playlet-lib && npm run lint:fix && cd ../playlet-app && npm run lint:fix", "lint:fix": "cd playlet-lib && npm run lint:fix && cd ../playlet-app && npm run lint:fix && cd ../playlet-web && npm run lint",
"format": "cd playlet-lib && npm run format && cd ../playlet-app && npm run format", "format": "cd playlet-lib && npm run format && cd ../playlet-app && npm run format",
"format:fix": "cd playlet-lib && npm run format:fix && cd ../playlet-app && npm run format:fix", "format:fix": "cd playlet-lib && npm run format:fix && cd ../playlet-app && npm run format:fix",
"test": "npm run test:lib && npm run test:app", "test": "npm run test:lib && npm run test:app",
@@ -62,7 +62,6 @@
"manifest-git-hash": "node tools/update-manifest-git-hash.js", "manifest-git-hash": "node tools/update-manifest-git-hash.js",
"sign-released-package": "node tools/sign-released-package.js", "sign-released-package": "node tools/sign-released-package.js",
"screenshot": "node tools/screenshot.js", "screenshot": "node tools/screenshot.js",
"generate-sponsorblock-config": "node tools/generate-sponsorblock-config.js",
"convert-images": "node tools/convert-images.js", "convert-images": "node tools/convert-images.js",
"update-rale-component": "cd tools/RALE && rm TrackerTask.xml && curl -o TrackerTask.zip https://devtools.web.roku.com/roku-advanced-layout-editor/app/TrackerTask.zip && unzip TrackerTask.zip && rm TrackerTask.zip", "update-rale-component": "cd tools/RALE && rm TrackerTask.xml && curl -o TrackerTask.zip https://devtools.web.roku.com/roku-advanced-layout-editor/app/TrackerTask.zip && unzip TrackerTask.zip && rm TrackerTask.zip",
"postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playlet-web && npm install", "postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playlet-web && npm install",
@@ -75,6 +74,6 @@
"shutdown": "node tools/shutdown.js" "shutdown": "node tools/shutdown.js"
}, },
"optionalDependencies": { "optionalDependencies": {
"@rollup/rollup-linux-x64-gnu": "^4.40.1" "@rollup/rollup-linux-x64-gnu": "^4.43.0"
} }
} }
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet-app", "name": "playlet-app",
"version": "0.36.7", "version": "0.40.4",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-app", "name": "playlet-app",
"version": "0.36.7" "version": "0.40.4"
} }
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-app", "name": "playlet-app",
"version": "0.36.7", "version": "0.40.4",
"description": "Unofficial YouTube client for Roku", "description": "Unofficial YouTube client for Roku",
"scripts": { "scripts": {
"prebuild": "rm -rf ../build/playlet-app", "prebuild": "rm -rf ../build/playlet-app",
@@ -5,6 +5,7 @@
<field id="inputArgs" type="assocarray" alwaysNotify="true" /> <field id="inputArgs" type="assocarray" alwaysNotify="true" />
<field id="playletLibLoadedUrl" type="assocarray" /> <field id="playletLibLoadedUrl" type="assocarray" />
<field id="systemLogEvent" type="assocarray" alwaysNotify="true" /> <field id="systemLogEvent" type="assocarray" alwaysNotify="true" />
<field id="enableSystemLogType" type="string" />
</interface> </interface>
<script type="text/brightscript" uri="pkg:/source/Dialog.bs" /> <script type="text/brightscript" uri="pkg:/source/Dialog.bs" />
<script type="text/brightscript" uri="pkg:/source/Manifest.bs" /> <script type="text/brightscript" uri="pkg:/source/Manifest.bs" />
+2 -2
View File
@@ -2,8 +2,8 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json # Do not update version manually, it is auto updated from package.json
major_version=0 major_version=0
minor_version=36 minor_version=40
build_version=00007 build_version=00004
ui_resolutions=hd ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p uri_resolution_autosub=$$RES$$,480p,720p,1080p
+4 -5
View File
@@ -51,11 +51,7 @@ function Main(args as object) as void
systemLog = CreateObject("roSystemLog") systemLog = CreateObject("roSystemLog")
systemLog.SetMessagePort(port) systemLog.SetMessagePort(port)
' Although all types are enabled, they are filtered in Playlet Lib to avoid spamming the logs scene.ObserveField("enableSystemLogType", port)
systemLog.EnableType("http.connect")
systemLog.EnableType("http.error")
systemLog.EnableType("http.complete")
systemLog.EnableType("bandwidth.minute")
#if DEBUG #if DEBUG
' The following comment is to enable the SceneGraph inspector ' The following comment is to enable the SceneGraph inspector
@@ -83,6 +79,9 @@ function Main(args as object) as void
if field = "exitChannel" and data = true if field = "exitChannel" and data = true
return return
end if end if
if field = "enableSystemLogType"
systemLog.EnableType(data)
end if
else if msgType = "roInputEvent" else if msgType = "roInputEvent"
scene.inputArgs = msg.getInfo() scene.inputArgs = msg.getInfo()
end if end if
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.36.7", "version": "0.40.4",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.36.7" "version": "0.40.4"
} }
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "playlet-lib", "name": "playlet-lib",
"version": "0.36.7", "version": "0.40.4",
"description": "Unofficial YouTube client for Roku", "description": "Unofficial YouTube client for Roku",
"scripts": { "scripts": {
"prebuild": "rm -rf ../build/playlet-lib", "prebuild": "rm -rf ../build/playlet-lib",
@@ -101,9 +101,16 @@ function CreateChannelFeeds(authorId as string, author as string, tabs as object
return invalid return invalid
end if end if
disableShorts = m.preferences["content_feed.disable_shorts"]
feeds = [] feeds = []
for i = 0 to tabs.count() - 1 for i = 0 to tabs.count() - 1
tabName = tabs[i] tabName = tabs[i]
if tabName = "shorts" and disableShorts
LogInfo(`Skipping "Shorts" tab based on user settings`)
continue for
end if
if m.tabs.DoesExist(tabName) if m.tabs.DoesExist(tabName)
if tabsParams <> invalid and tabsParams.DoesExist(tabName) if tabsParams <> invalid and tabsParams.DoesExist(tabName)
params = tabsParams[tabName] params = tabsParams[tabName]
@@ -159,18 +166,25 @@ function OnDispose()
m.subscribeTask.cancel = true m.subscribeTask.cancel = true
m.subscribeTask = invalid m.subscribeTask = invalid
end if end if
if m.fetchSubscriptionStatusTask <> invalid
m.fetchSubscriptionStatusTask.cancel = true
m.fetchSubscriptionStatusTask = invalid
end if
end function end function
function OnSubscribeButtonSelected() function OnSubscribeButtonSelected()
if m.subscribeTask <> invalid if m.subscribeTask <> invalid
m.subscribeTask.cancel = true m.subscribeTask.cancel = true
end if end if
if m.fetchSubscriptionStatusTask <> invalid
m.fetchSubscriptionStatusTask.cancel = true
end if
isSubbed = IsSubscribed()
m.subscribeTask = AsyncTask.Start(Tasks.SubscribeTask, { m.subscribeTask = AsyncTask.Start(Tasks.SubscribeTask, {
channelView: m.top
invidious: m.invidious invidious: m.invidious
ucid: m.authorId ucid: m.authorId
subscribe: not isSubbed subscribe: not m.top.isSubscribed
}) })
end function end function
@@ -335,14 +349,17 @@ function GetSortingContextMenuOptionsForItem(video as object) as object
end if end if
feedSource = feedSources[0] feedSource = feedSources[0]
sortOptions = feedSource.state.sortOptions
if not IsArray(sortOptions)
endpoint = feedSource.endpoint endpoint = feedSource.endpoint
if not m.sortOptions.DoesExist(endpoint) if not m.sortOptions.DoesExist(endpoint)
return [] return []
end if end if
title = Tr(Locale.Dialogs.SortFeedBy).replace("%1", `"${feedSource.title}"`)
sortOptions = m.sortOptions[endpoint] sortOptions = m.sortOptions[endpoint]
end if
title = Tr(Locale.Dialogs.SortFeedBy).replace("%1", `"${feedSource.title}"`)
return [ContextMenuUtils.CreateOption(title + "...", m.top, "ShowSortDialog", [title, sortOptions, feedContentNode])] return [ContextMenuUtils.CreateOption(title + "...", m.top, "ShowSortDialog", [title, sortOptions, feedContentNode])]
end function end function
@@ -350,25 +367,10 @@ function IsLoggedIn() as boolean
return m.invidious.authToken <> invalid return m.invidious.authToken <> invalid
end function end function
function IsSubscribed() as boolean
authorId = m.top.authorId
if StringUtils.IsNullOrEmpty(authorId)
return false
end if
subscriptions = m.invidious.subscriptions
if subscriptions = invalid
return false
end if
if not subscriptions.DoesExist(authorId)
return false
end if
return subscriptions[authorId]
end function
function OnAuthorIdChange() function OnAuthorIdChange()
SetSubscribeButtonVisibility() SetSubscribeButtonVisibility()
OnSubscriptionChanged() OnSubscriptionChanged()
FetchSubscriptionStatus()
end function end function
function SetSubscribeButtonVisibility() function SetSubscribeButtonVisibility()
@@ -380,9 +382,34 @@ function SetSubscribeButtonVisibility()
end if end if
end function end function
function FetchSubscriptionStatus() as void
if not IsLoggedIn()
return
end if
authorId = m.top.authorId
if StringUtils.IsNullOrEmpty(authorId)
return
end if
if m.fetchSubscriptionStatusTask <> invalid
return
end if
m.fetchSubscriptionStatusTask = AsyncTask.Start(Tasks.FetchSubscriptionStatusTask, {
channelView: m.top
ucid: authorId
authToken: m.invidious.authToken
invidious: m.invidious
})
end function
function OnFetchSubscriptionStatusResult(_output as object) as void
m.fetchSubscriptionStatusTask = invalid
end function
function OnSubscriptionChanged() function OnSubscriptionChanged()
isSubbed = IsSubscribed() if m.top.isSubscribed
if isSubbed
m.subscribeButton.text = Tr(Locale.Buttons.Unsubscribe) m.subscribeButton.text = Tr(Locale.Buttons.Unsubscribe)
else else
m.subscribeButton.text = Tr(Locale.Buttons.Subscribe) m.subscribeButton.text = Tr(Locale.Buttons.Subscribe)
@@ -2,8 +2,10 @@
<interface> <interface>
<field id="content" type="node" onChange="OnContentSet" /> <field id="content" type="node" onChange="OnContentSet" />
<field id="authorId" type="string" onChange="OnAuthorIdChange" /> <field id="authorId" type="string" onChange="OnAuthorIdChange" />
<field id="isSubscribed" type="boolean" onChange="OnSubscriptionChanged" />
<field id="appController" type="node" bind="/AppController" /> <field id="appController" type="node" bind="/AppController" />
<field id="invidious" type="node" bind="/Invidious" /> <field id="invidious" type="node" bind="/Invidious" />
<field id="preferences" type="node" bind="/Preferences" />
<field id="bookmarksService" type="node" bind="/BookmarksService" /> <field id="bookmarksService" type="node" bind="/BookmarksService" />
<function name="ShowSortDialog" /> <function name="ShowSortDialog" />
</interface> </interface>
@@ -0,0 +1,49 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
@asynctask
function FetchSubscriptionStatusTask(input as object) as object
channelView = input.channelView
ucid = input.ucid
invidiousNode = input.invidious
authToken = input.authToken
if m.top.cancel
return invalid
end if
isInnertubeProfile = authToken.profileNode.type = "youtube"
if isInnertubeProfile
subscriptionStatus = InnertubeService.GetSubscriptionStatusForChannel(ucid, {
cancellation: m.top.cancellation
accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
})
if subscriptionStatus.error <> invalid
LogError("Failed to fetch subscription status:", subscriptionStatus.error)
return invalid
end if
channelView.isSubscribed = subscriptionStatus.isSubscribed
else
service = new Invidious.InvidiousService(invidiousNode)
subscriptionsRequest = service.GetSubscriptions(m.top.cancellation)
if not subscriptionsRequest.IsSuccess()
error = subscriptionsRequest.ErrorMessage()
LogError("Failed to fetch subscriptions:", error)
return invalid
end if
subscriptions = subscriptionsRequest.Json()
isSubscribed = false
for each subscription in subscriptions
if subscription.authorId = ucid
isSubscribed = true
exit for
end if
end for
channelView.isSubscribed = isSubscribed
end if
return invalid
end function
@@ -2,6 +2,7 @@ import "pkg:/components/Services/Invidious/InvidiousService.bs"
@asynctask @asynctask
function SubscribeTask(input as object) as object function SubscribeTask(input as object) as object
channelView = input.channelView
invidiousNode = input.invidious invidiousNode = input.invidious
ucid = input.ucid ucid = input.ucid
subscribe = input.subscribe subscribe = input.subscribe
@@ -13,23 +14,17 @@ function SubscribeTask(input as object) as object
service = new Invidious.InvidiousService(invidiousNode) service = new Invidious.InvidiousService(invidiousNode)
if subscribe if subscribe
response = service.Subscribe(ucid) response = service.Subscribe(ucid, m.top.cancellation)
else else
response = service.Unsubscribe(ucid) response = service.Unsubscribe(ucid, m.top.cancellation)
end if end if
if not response.IsSuccess() if not response.IsSuccess()
error = response.ErrorMessage() error = response.ErrorMessage()
LogError("Failed to subscribe/unsubscribe to channel:", error) LogError("Failed to subscribe/unsubscribe to channel:", error)
return { return invalid
success: false
error: error
}
end if end if
invidiousNode.refreshSubscribtions = true channelView.isSubscribed = subscribe
return invalid
return {
success: true
}
end function end function
+3 -11
View File
@@ -44,19 +44,11 @@ function Update()
end if end if
if hours > 12 if hours > 12
hours = hours - 12 hours -= 12
end if end if
hoursStr = hours.ToStr() hoursStr = hours.ToStr("%02d")
minutesStr = minutes.ToStr() minutesStr = minutes.ToStr("%02d")
if hours < 10
hoursStr = "0" + hoursStr
end if
if minutes < 10
minutesStr = "0" + minutesStr
end if
m.top.text = hoursStr + ":" + minutesStr + " " + ampm m.top.text = hoursStr + ":" + minutesStr + " " + ampm
end function end function
@@ -43,5 +43,6 @@
<field id="statsText" type="string" /> <field id="statsText" type="string" />
<!-- videoId is Mix continuation (playlistId starts with "RD") --> <!-- videoId is Mix continuation (playlistId starts with "RD") -->
<field id="videoId" type="string" /> <field id="videoId" type="string" />
<field id="lines" type="stringarray" />
</interface> </interface>
</component> </component>
@@ -54,13 +54,19 @@ function PlaylistContentTask(input as object) as object
} }
end if end if
beforeChildCount = contentNode.getChildCount()
InvidiousContent.ToPlaylistContentNode(contentNode, metadata, instance) InvidiousContent.ToPlaylistContentNode(contentNode, metadata, instance)
childCount = contentNode.getChildCount() afterChildCount = contentNode.getChildCount()
videoCount = ValidInt(metadata.videoCount) videoCount = ValidInt(metadata.videoCount)
hasContinuation = not StringUtils.IsNullOrEmpty(metadata.continuation) hasContinuation = not StringUtils.IsNullOrEmpty(metadata.continuation)
if (hadContinuation and not hasContinuation) or (metadata.videos.Count() = 0 or childCount >= videoCount)
noMoreContinuation = hadContinuation and not hasContinuation
noVideosAdded = afterChildCount = beforeChildCount
reachedVideoCount = videoCount <> -1 and afterChildCount >= videoCount
if noMoreContinuation or noVideosAdded or reachedVideoCount
contentNode.loadState = FeedLoadState.Loaded contentNode.loadState = FeedLoadState.Loaded
return { return {
success: true success: true
@@ -0,0 +1,56 @@
import "pkg:/source/AsyncTask/AsyncTask.bs"
import "pkg:/source/AsyncTask/Tasks.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
function HasValidAccessToken(_unused as dynamic) as boolean
serverType = m.top.type
accessToken = m.top.accessToken
if StringUtils.IsNullOrEmpty(accessToken)
return false
end if
if serverType = "invidious"
return true
end if
nowSeconds = TimeUtils.Now().AsSeconds()
expiresTimestamp = m.top.expiresTimestamp
' We should refresh the token if it's about to expire in 30 minutes
' Although the current token might be valid, we can let current request
' wait for the new token
shouldRefreshToken = expiresTimestamp < nowSeconds + 60 * 30
if shouldRefreshToken
RefreshAccessToken()
end if
return not shouldRefreshToken
end function
function RefreshAccessToken() as void
if m.refreshTokenTask <> invalid
return
end if
if m.profilesService = invalid
m.profilesService = m.top.getScene().findNode("ProfilesService")
end if
LogInfo("Refreshing access token for profile:", m.top.username)
m.refreshTokenTask = AsyncTask.Start(Tasks.ProfileRefreshTokenTask, {
profile: m.top
profilesService: m.profilesService
accessTokenObject: {
clientId: m.top.clientId
clientSecret: m.top.clientSecret
refreshToken: m.top.refreshToken
}
}, OnProfileRefreshTokenTaskResult)
end function
function OnProfileRefreshTokenTaskResult(_output as object) as void
m.refreshTokenTask = invalid
end function
@@ -8,6 +8,7 @@
<field id="accessToken" type="string" /> <field id="accessToken" type="string" />
<!-- Innertube fields --> <!-- Innertube fields -->
<field id="activeIdentifyToken" type="string" />
<field id="thumbnail" type="uri" /> <field id="thumbnail" type="uri" />
<field id="refreshToken" type="string" /> <field id="refreshToken" type="string" />
<field id="scope" type="string" /> <field id="scope" type="string" />
@@ -18,5 +19,7 @@
<field id="clientSecret" type="string" /> <field id="clientSecret" type="string" />
<field id="color" type="color" /> <field id="color" type="color" />
<function name="HasValidAccessToken" />
</interface> </interface>
</component> </component>
@@ -0,0 +1,25 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/source/utils/ErrorUtils.bs"
@asynctask
function ProfileRefreshTokenTask(input as object) as object
profileNode = input.profile
accessTokenObject = input.accessTokenObject
profilesService = input.profilesService
try
if InnertubeService.AuthRefreshAccessToken(accessTokenObject)
profileNode.expiresIn = accessTokenObject.expiresIn
profileNode.expiresTimestamp = accessTokenObject.expiresTimestamp
profileNode.accessToken = accessTokenObject.accessToken
profilesService@.SaveUserProfilesToRegistry()
else
LogError("Failed to refresh access token")
profileNode.accessToken = invalid
end if
catch error
LogError("Failed to refresh access token:", ErrorUtils.Format(error))
profileNode.accessToken = invalid
end try
return invalid
end function
@@ -22,5 +22,10 @@
<field id="title" type="string" /> <field id="title" type="string" />
<field id="videoId" type="string" /> <field id="videoId" type="string" />
<field id="viewCountText" type="string" /> <field id="viewCountText" type="string" />
<!-- lines is from the tv client (author name + video info) -->
<field id="lines" type="stringarray" />
<!-- videoInfo is from web client -->
<field id="videoInfo" type="string" />
<field id="percentDurationWatched" type="float" />
</interface> </interface>
</component> </component>
@@ -22,7 +22,7 @@
showDivider="false"> showDivider="false">
<Label <Label
id="scanLabel" id="scanLabel"
text="Scan the QR Code" text="Scan the QR code"
horizAlign="center" horizAlign="center"
wrap="true" width="400"> wrap="true" width="400">
<Font role="font" uri="font:SystemFontFile" size="24" /> <Font role="font" uri="font:SystemFontFile" size="24" />
@@ -0,0 +1,27 @@
import "pkg:/source/utils/StringUtils.bs"
namespace YouTubeLoginAccountItemUtils
function CreateProfileContentNode(accountItem as object, accessToken as object) as object
profile = CreateObject("roSGNode", "ProfileContentNode")
profile.type = "youtube"
profile.serverUrl = "http://127.0.0.1:8888/playlet-invidious-backend"
username = accountItem.channelHandle
if StringUtils.IsNullOrEmpty(username)
username = accountItem.accountByline
end if
profile.username = username
profile.activeIdentifyToken = accountItem.activeIdentifyToken
profile.thumbnail = accountItem.accountPhoto
profile.accessToken = accessToken.accessToken
profile.refreshToken = accessToken.refreshToken
profile.scope = accessToken.scope
profile.tokenType = accessToken.tokenType
profile.expiresIn = accessToken.expiresIn
profile.expiresTimestamp = accessToken.expiresTimestamp
profile.clientId = accessToken.clientId
profile.clientSecret = accessToken.clientSecret
return profile
end function
end namespace
@@ -1,6 +1,10 @@
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Screens/ProfileScreen/YouTubeAccountSelectionView/YouTubeAccountSelectionViewUtils.bs"
import "pkg:/source/AsyncTask/AsyncTask.bs" import "pkg:/source/AsyncTask/AsyncTask.bs"
import "pkg:/source/AsyncTask/Tasks.bs" import "pkg:/source/AsyncTask/Tasks.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Locale.bs" import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/Types.bs"
function Init() function Init()
@@ -19,15 +23,56 @@ function Init()
m.top.observeFieldScoped("buttonSelected", FuncName(Close)) m.top.observeFieldScoped("buttonSelected", FuncName(Close))
m.top.observeFieldScoped("wasClosed", FuncName(OnWasClosed)) m.top.observeFieldScoped("wasClosed", FuncName(OnWasClosed))
scanLabel = m.top.findNode("scanLabel") scanLabel = m.top.findNode("scanLabel")
' TODO:P2 localize all dialog items
scanLabel.text = Tr(Locale.Dialogs.ScanTheQrCode) scanLabel.text = Tr(Locale.Dialogs.ScanTheQrCode)
linkInstructionLabel = m.top.findNode("linkInstructionLabel")
linkInstructionLabel.text = Tr(Locale.Dialogs.OpenLinkAndEnterFollowingCode).replace("%1", `'https://yt.be/activate'`)
end function end function
function OnNodeReady() function OnNodeReady()
m.task = AsyncTask.Start(Tasks.YouTubeLoginTask, { m.task = AsyncTask.Start(Tasks.YouTubeLoginTask, {
dialog: m.top dialog: m.top
profilesService: m.top.profilesService profilesService: m.top.profilesService
}, OnYouTubeLoginTaskResult)
end function
function OnYouTubeLoginTaskResult(output as object) as void
m.task = invalid
if output.cancelled
Close()
return
end if
if not output.success or not output.result.success
' output.error for unhandled exception
error = output.error
if error = invalid
' output.result.error for network errors
error = output.result.error
end if
error = ErrorUtils.Format(error)
LogError(error)
DialogUtils.ShowDialogEx({
message: error
title: Tr(Locale.Generic.Error)
large: true
}) })
return
end if
accounts = output.result.accounts
accessToken = output.result.accessToken
' if accounts is invalid, we're going to assume a profile is already created.
if accounts = invalid or accessToken = invalid
Close()
return
end if
' The accountSelectionView will take over the creation of the profile.
accountSelectionView = YouTubeAccountSelectionViewUtils.Open(m.top.appController)
accountSelectionView.accessToken = accessToken
accountSelectionView.accounts = accounts
Close()
end function end function
function OnCodeSet(event as object) function OnCodeSet(event as object)
@@ -1,6 +1,7 @@
<component name="YouTubeLoginDialog" extends="StandardDialog" initialFocus="buttonArea" includes="AutoBind"> <component name="YouTubeLoginDialog" extends="StandardDialog" initialFocus="buttonArea" includes="AutoBind">
<interface> <interface>
<field id="profilesService" type="node" bind="/ProfilesService" /> <field id="profilesService" type="node" bind="/ProfilesService" />
<field id="appController" type="node" bind="/AppController" />
<field id="code" type="string" alias="codeLabel.text" /> <field id="code" type="string" alias="codeLabel.text" />
<field id="url" type="string" onChange="OnUrlSet" /> <field id="url" type="string" onChange="OnUrlSet" />
<field id="alwaysOnTop" type="boolean" /> <field id="alwaysOnTop" type="boolean" />
@@ -10,7 +11,8 @@
<StdDlgTitleArea primaryTitle="Login to YouTube" /> <StdDlgTitleArea primaryTitle="Login to YouTube" />
<StdDlgContentArea> <StdDlgContentArea>
<StdDlgTextItem text="Open the link 'https://yt.be/activate' and enter the following code:" /> <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<StdDlgTextItem id="linkInstructionLabel" text="Open the link 'https://yt.be/activate' and enter the following code:" />
<StdDlgTextItem id="codeLabel" text="Loading..." /> <StdDlgTextItem id="codeLabel" text="Loading..." />
</StdDlgContentArea> </StdDlgContentArea>
<StdDlgButtonArea id="buttonArea"> <StdDlgButtonArea id="buttonArea">
@@ -24,7 +26,7 @@
showDivider="false"> showDivider="false">
<Label <Label
id="scanLabel" id="scanLabel"
text="Scan the QR Code" text="Scan the QR code"
horizAlign="center" horizAlign="center"
wrap="true" width="400"> wrap="true" width="400">
<Font role="font" uri="font:SystemFontFile" size="24" /> <Font role="font" uri="font:SystemFontFile" size="24" />
@@ -37,11 +39,11 @@
loadHeight="300" loadHeight="300"
padding="10" padding="10"
translation="[50, 50]" /> translation="[50, 50]" />
<Label <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<Label text="https://yt.be/activate"
horizAlign="center" horizAlign="center"
width="400" width="400"
translation="[0, 380]" translation="[0, 380]">
text="https://yt.be/activate">
<Font role="font" uri="font:MediumSystemFontFile" size="18" /> <Font role="font" uri="font:MediumSystemFontFile" size="18" />
</Label> </Label>
</StdDlgSideCardArea> </StdDlgSideCardArea>
@@ -1,4 +1,5 @@
import "pkg:/components/Dialog/DialogUtils.bs" import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Dialog/YouTubeLoginAccountItemUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs" import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/Logging.bs"
@@ -17,13 +18,10 @@ function YouTubeLoginTask(input as object) as object
end if end if
if authCode.error <> invalid if authCode.error <> invalid
LogError(authCode.error) return {
DialogUtils.ShowDialogEx({ success: false
title: "Error" error: authCode.error
message: authCode.error }
large: true
})
return invalid
end if end if
url = InnertubeService.AuthGetActivationUrl(authCode) url = InnertubeService.AuthGetActivationUrl(authCode)
@@ -40,13 +38,10 @@ function YouTubeLoginTask(input as object) as object
end if end if
if accessToken.error <> invalid if accessToken.error <> invalid
LogError(accessToken.error) return {
DialogUtils.ShowDialogEx({ success: false
title: "Error" error: accessToken.error
message: accessToken.error }
large: true
})
return invalid
end if end if
accounts = InnertubeService.AuthListAccounts(accessToken.accessToken, cancellation) accounts = InnertubeService.AuthListAccounts(accessToken.accessToken, cancellation)
@@ -56,63 +51,33 @@ function YouTubeLoginTask(input as object) as object
end if end if
if IsAssociativeArray(accounts) and accounts.error <> invalid if IsAssociativeArray(accounts) and accounts.error <> invalid
LogError(accounts.error) return {
DialogUtils.ShowDialogEx({ success: false
title: "Error" error: accounts.error
message: accounts.error }
large: true
})
return invalid
end if end if
if not IsArray(accounts) or accounts.Count() = 0 if not IsArray(accounts) or accounts.Count() = 0
LogError("No accounts found") return {
DialogUtils.ShowDialogEx({ success: false
title: "Error" error: Tr(Locale.Dialogs.NoValidAccountsFound)
message: "No accounts found" }
large: true
})
return invalid
end if end if
selectedAccount = invalid ' If there is only one account, we can skip the selection screen
for each account in accounts ' and just create a profile
if ValidBool(account.isSelected) if accounts.Count() = 1
selectedAccount = account profile = YouTubeLoginAccountItemUtils.CreateProfileContentNode(accounts[0], accessToken)
exit for
end if
end for
if selectedAccount = invalid
selectedAccount = accounts[0]
end if
profile = CreateProfileContentNode(selectedAccount, accessToken)
profilesNode@.LoginWithProfile(profile) profilesNode@.LoginWithProfile(profile)
dialogNode.close = true return {
success: true
return invalid }
end function
function CreateProfileContentNode(account as object, accessToken as object) as object
profile = CreateObject("roSGNode", "ProfileContentNode")
profile.type = "youtube"
profile.serverUrl = "http://127.0.0.1:8888/playlet-invidious-backend"
username = account.channelHandle
if StringUtils.IsNullOrEmpty(username)
username = account.accountByline
end if end if
profile.username = username
profile.thumbnail = account.accountPhoto
profile.accessToken = accessToken.accessToken
profile.refreshToken = accessToken.refreshToken
profile.scope = accessToken.scope
profile.tokenType = accessToken.tokenType
profile.expiresIn = accessToken.expiresIn
profile.expiresTimestamp = accessToken.expiresTimestamp
profile.clientId = accessToken.clientId
profile.clientSecret = accessToken.clientSecret
return profile return {
success: true
accounts: accounts
accessToken: accessToken
}
end function end function
+12 -21
View File
@@ -12,6 +12,14 @@ function Init()
scene = m.top.getScene() scene = m.top.getScene()
MessagePortUtils.ObserveFieldScopedExSafe(scene, "systemLogEvent", port) MessagePortUtils.ObserveFieldScopedExSafe(scene, "systemLogEvent", port)
if scene.hasField("enableSystemLogType")
scene.enableSystemLogType = "http.error"
#if DEBUG
scene.enableSystemLogType = "http.connect"
scene.enableSystemLogType = "http.complete"
scene.enableSystemLogType = "bandwidth.minute"
#end if
end if
m.port = port m.port = port
@@ -143,27 +151,10 @@ function FormatTime(dateTime as object) as string
dateTime.Mark() dateTime.Mark()
dateTime.ToLocalTime() dateTime.ToLocalTime()
hours = dateTime.GetHours().ToStr() hours = dateTime.GetHours().ToStr("%02d")
if hours.Len() = 1 minutes = dateTime.GetMinutes().ToStr("%02d")
hours = "0" + hours seconds = dateTime.GetSeconds().ToStr("%02d")
end if milliseconds = dateTime.GetMilliseconds().ToStr("%03d")
minutes = dateTime.GetMinutes().ToStr()
if minutes.Len() = 1
minutes = "0" + minutes
end if
seconds = dateTime.GetSeconds().ToStr()
if seconds.Len() = 1
seconds = "0" + seconds
end if
milliseconds = dateTime.GetMilliseconds().ToStr()
if milliseconds.Len() = 1
milliseconds = "00" + milliseconds
else if milliseconds.Len() = 2
milliseconds = "0" + milliseconds
end if
return "[" + hours + ":" + minutes + ":" + seconds + "." + milliseconds + "]" return "[" + hours + ":" + minutes + ":" + seconds + "." + milliseconds + "]"
end function end function
+20 -10
View File
@@ -33,12 +33,20 @@ function SetScenePalette(scene as object) as void
scene.palette = palette scene.palette = palette
end function end function
const HAS_ANNOUNCEMENT = false
function MainSceneContainerChanged() function MainSceneContainerChanged()
AutoBindSceneGraph() AutoBindSceneGraph()
StartWebServer() StartWebServer()
HideLoadingScreen() HideLoadingScreen()
InitEcpArgs() InitEcpArgs()
if HAS_ANNOUNCEMENT
if not ShowAnnouncement()
m.scene.signalBeacon("AppLaunchComplete") m.scene.signalBeacon("AppLaunchComplete")
end if
else
m.scene.signalBeacon("AppLaunchComplete")
end if
CopyLoadingMessagesToCache() CopyLoadingMessagesToCache()
end function end function
@@ -53,29 +61,31 @@ function StartWebServer()
m.dialServer@.StartServer() m.dialServer@.StartServer()
end function end function
function ShowAnnouncement() as void function ShowAnnouncement() as boolean
dialog = DialogUtils.ShowDialogOnce({ dialog = DialogUtils.ShowDialogOnce({
messageId: "1736288537" messageId: "1747362859"
title: "Announcement - Playlet backend" title: "Announcement - YouTube account support"
message: [ message: [
"An experimental built-in backend has been added to Playlet." "YouTube account support is now available in Playlet!"
"This allows you to access YouTube content without the need for an Invidious instance." `Subscriptions, playlists, watch history and "Recommended" are now available in the app.`
"To use it, go to the Settings > Invidious > Instance and set the field to empty (Edit, and delete the url)." "If you encounter any issues, please report them on GitHub."
"Please note that it's missing some features and may not work as expected." "https://github.com/iBicha/playlet/issues"
"Thank you for using Playlet!" "Thank you."
] ]
alwaysOnTop: true alwaysOnTop: true
marginWidth: 180 marginWidth: 180
}) })
if dialog = invalid if dialog = invalid
return return false
end if end if
m.scene.signalBeacon("AppDialogInitiate") m.scene.signalBeacon("AppDialogInitiate")
m.top.observeField("wasClosed", FuncName(OnAnnouncementDialogClosed)) dialog.observeField("wasClosed", FuncName(OnAnnouncementDialogClosed))
return true
end function end function
function OnAnnouncementDialogClosed() function OnAnnouncementDialogClosed()
m.scene.signalBeacon("AppDialogComplete") m.scene.signalBeacon("AppDialogComplete")
m.scene.signalBeacon("AppLaunchComplete")
end function end function
@@ -32,12 +32,19 @@ function SetScenePalette(scene as object) as void
scene.palette = palette scene.palette = palette
end function end function
function MainSceneContainerChanged() function MainSceneContainerChanged()
AutoBindSceneGraph() AutoBindSceneGraph()
StartWebServer() StartWebServer()
HideLoadingScreen() HideLoadingScreen()
InitEcpArgs() InitEcpArgs()
if false
if not ShowAnnouncement()
m.scene.signalBeacon("AppLaunchComplete") m.scene.signalBeacon("AppLaunchComplete")
end if
else
m.scene.signalBeacon("AppLaunchComplete")
end if
CopyLoadingMessagesToCache() CopyLoadingMessagesToCache()
end function end function
@@ -50,28 +57,30 @@ function StartWebServer()
m.dialServer.callfunc("StartServer", invalid) m.dialServer.callfunc("StartServer", invalid)
end function end function
function ShowAnnouncement() as void function ShowAnnouncement() as boolean
dialog = DialogUtils_ShowDialogOnce({ dialog = DialogUtils_ShowDialogOnce({
messageId: "1736288537" messageId: "1747362859"
title: "Announcement - Playlet backend" title: "Announcement - YouTube account support"
message: [ message: [
"An experimental built-in backend has been added to Playlet." "YouTube account support is now available in Playlet!"
"This allows you to access YouTube content without the need for an Invidious instance." "Subscriptions, playlists, watch history and " + chr(34) + "Recommended" + chr(34) + " are now available in the app."
"To use it, go to the Settings > Invidious > Instance and set the field to empty (Edit, and delete the url)." "If you encounter any issues, please report them on GitHub."
"Please note that it's missing some features and may not work as expected." "https://github.com/iBicha/playlet/issues"
"Thank you for using Playlet!" "Thank you."
] ]
alwaysOnTop: true alwaysOnTop: true
marginWidth: 180 marginWidth: 180
}) })
if dialog = invalid if dialog = invalid
return return false
end if end if
m.scene.signalBeacon("AppDialogInitiate") m.scene.signalBeacon("AppDialogInitiate")
m.top.observeField("wasClosed", FuncName(OnAnnouncementDialogClosed)) dialog.observeField("wasClosed", FuncName(OnAnnouncementDialogClosed))
return true
end function end function
function OnAnnouncementDialogClosed() function OnAnnouncementDialogClosed()
m.scene.signalBeacon("AppDialogComplete") m.scene.signalBeacon("AppDialogComplete")
m.scene.signalBeacon("AppLaunchComplete")
end function end function
'//# sourceMappingURL=./MainScene.brs.map '//# sourceMappingURL=./MainScene.brs.map
+1 -2
View File
@@ -42,8 +42,7 @@
<AppVersionLabel <AppVersionLabel
fontUri="font:BoldSystemFontFile" fontUri="font:BoldSystemFontFile"
fontSize="16" fontSize="16"
translation="[0, 48]" translation="[0, 48]" />
/>
</Poster> </Poster>
<MarkupList <MarkupList
@@ -1,9 +1,12 @@
import "pkg:/source/utils/MathUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs" import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/Types.bs"
function Init() function Init()
m.durationRect = m.top.FindNode("durationRect") m.durationRect = m.top.FindNode("durationRect")
m.durationLabel = m.top.FindNode("durationLabel") m.durationLabel = m.top.FindNode("durationLabel")
m.progressRect = m.top.FindNode("progressRect")
end function end function
function OnContentSet() as void function OnContentSet() as void
@@ -15,9 +18,27 @@ function OnContentSet() as void
m.top.title = content.title m.top.title = content.title
' NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation. ' NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation.
m.top.author = content._author author = content._author
if not StringUtils.IsNullOrEmpty(author)
videoInfo = content.videoInfo
if not StringUtils.IsNullOrEmpty(videoInfo)
author += `\n` + videoInfo
end if
else
lines = content.lines
if IsArray(lines) and lines.Count() > 0
author = lines[0]
if lines.Count() > 1
author += `\n` + lines[1]
end if
end if
end if
m.top.author = author
m.top.thumbnailUri = content.thumbnail m.top.thumbnailUri = content.thumbnail
m.top.percentDurationWatched = content.percentDurationWatched
SetDurationText(content.lengthText) SetDurationText(content.lengthText)
end function end function
@@ -43,3 +64,12 @@ function SetDurationText(text as string) as void
rect.width = size.width + 16 rect.width = size.width + 16
rect.translation = [rectParent.width - rect.width, rect.translation[1]] rect.translation = [rectParent.width - rect.width, rect.translation[1]]
end function end function
function OnPercentDurationWatched() as void
if m.progressRect = invalid
return
end if
percent = MathUtils.Clamp(m.top.percentDurationWatched, 0, 100) / 100.0
m.progressRect.scale = [percent, 1]
end function
@@ -6,6 +6,7 @@
<field id="thumbnailUri" type="uri" alias="thumbnailPoster.uri" /> <field id="thumbnailUri" type="uri" alias="thumbnailPoster.uri" />
<field id="duration" type="string" alias="durationLabel.text" /> <field id="duration" type="string" alias="durationLabel.text" />
<field id="durationRectVisible" type="boolean" alias="durationRect.visible" /> <field id="durationRectVisible" type="boolean" alias="durationRect.visible" />
<field id="percentDurationWatched" type="float" onChange="OnPercentDurationWatched" />
</interface> </interface>
<children> <children>
<Poster <Poster
@@ -29,6 +30,14 @@
font="font:SmallestSystemFont" font="font:SmallestSystemFont"
translation="[8, 0]" /> translation="[8, 0]" />
</Rectangle> </Rectangle>
<Rectangle
id="progressRect"
width="190"
height="5"
color="#FF0000"
translation="[0, 102]"
scale="[0, 1]">
</Rectangle>
</Poster> </Poster>
@@ -44,8 +53,9 @@
<Label <Label
id="authorLabel" id="authorLabel"
width="350" width="350"
height="25" font="font:SmallestSystemFont"
font="font:SmallestSystemFont" /> maxLines="2"
wrap="true" />
</LayoutGroup> </LayoutGroup>
</children> </children>
@@ -43,8 +43,7 @@
showRowLabel="[true]" showRowLabel="[true]"
rowFocusAnimationStyle="floatingfocus" rowFocusAnimationStyle="floatingfocus"
variableWidthItems="true" variableWidthItems="true"
focusBitmapUri="pkg:/images/focus-glow-padding-19.9.png" focusBitmapUri="pkg:/images/focus-glow-padding-19.9.png" />
/>
</Group> </Group>
</children> </children>
</component> </component>
@@ -36,7 +36,9 @@
focusBitmapUri="pkg:/images/focus-glow-padding-19.9.png"> focusBitmapUri="pkg:/images/focus-glow-padding-19.9.png">
<ContentNode role="content"> <ContentNode role="content">
<ContentNode> <ContentNode>
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<BackendTypeContentNode id="BackendTypeYouTube" title="YouTube" backendLogoUri="pkg:/images/youtube-logo.png" /> <BackendTypeContentNode id="BackendTypeYouTube" title="YouTube" backendLogoUri="pkg:/images/youtube-logo.png" />
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<BackendTypeContentNode id="BackendTypeInvidious" title="Invidious" backendLogoUri="pkg:/images/invidious-logo.png" /> <BackendTypeContentNode id="BackendTypeInvidious" title="Invidious" backendLogoUri="pkg:/images/invidious-logo.png" />
</ContentNode> </ContentNode>
</ContentNode> </ContentNode>
@@ -65,8 +65,7 @@
id="backendTypePoster" id="backendTypePoster"
width="60" width="60"
height="60" height="60"
translation="[110,110]" translation="[110,110]" />
/>
</CirclePoster> </CirclePoster>
<Poster <Poster
id="CrownPoster" id="CrownPoster"
@@ -79,9 +78,9 @@
</Poster> </Poster>
<Label <Label
id="UsernameLabel" id="UsernameLabel"
width="200" width="300"
horizAlign="center" horizAlign="center"
translation="[0,250]"> translation="[-50,250]">
</Label> </Label>
<Label <Label
id="ServerLabel" id="ServerLabel"
@@ -40,14 +40,9 @@ function OnRowItemSelected() as void
row = m.profileRowList.content.GetChild(0) row = m.profileRowList.content.GetChild(0)
selectedProfile = row.GetChild(index) selectedProfile = row.GetChild(index)
if selectedProfile.type = "login" if selectedProfile.type = "login"
#if YT_OAUTH_SUPPORT
backendTypeSelectionView = BackendTypeSelectionViewUtils.Open(m.appController) backendTypeSelectionView = BackendTypeSelectionViewUtils.Open(m.appController)
backendTypeSelectionView.observeFieldScoped("selectedBackendType", FuncName(OnBackEndSelected)) backendTypeSelectionView.observeFieldScoped("selectedBackendType", FuncName(OnBackEndSelected))
return return
#else
LoginWithInvidious()
return
#end if
end if end if
ProfileViewUtils.Open(selectedProfile, m.appController) ProfileViewUtils.Open(selectedProfile, m.appController)
@@ -86,10 +81,14 @@ function LoginWithInvidious() as void
end function end function
function ShowLoginWithYouTubeDialog() as void function ShowLoginWithYouTubeDialog() as void
' TODO:P2 localize
dialog = DialogUtils.ShowDialogEx({ dialog = DialogUtils.ShowDialogEx({
title: "Disclaimer" title: Tr(Locale.Dialogs.Disclaimer)
message: "Playlet authors acknowledge that all trademarks and registered trademarks mentioned in this application and related pages are the property of their respective owners. The use of these trademarks or trade names is for identification purposes only and does not imply any endorsement, affiliation, or sponsorship by the trademark owner." message: [
Tr(Locale.Dialogs.YouTubeLoginDisclaimer1)
Tr(Locale.Dialogs.YouTubeLoginDisclaimer2)
Tr(Locale.Dialogs.YouTubeLoginDisclaimer3)
]
large: true
buttons: [ buttons: [
Tr(Locale.Buttons.OK) Tr(Locale.Buttons.OK)
Tr(Locale.Buttons.Cancel) Tr(Locale.Buttons.Cancel)
@@ -52,8 +52,7 @@
id="backendTypePoster" id="backendTypePoster"
width="60" width="60"
height="60" height="60"
translation="[110,110]" translation="[110,110]" />
/>
</CirclePoster> </CirclePoster>
<Poster <Poster
id="CrownPoster" id="CrownPoster"
@@ -66,9 +65,9 @@
</Poster> </Poster>
<Label <Label
id="UsernameLabel" id="UsernameLabel"
width="200" width="400"
horizAlign="center" horizAlign="center"
translation="[0,210]"> translation="[-100,210]">
<Font role="font" uri="font:MediumSystemFontFile" size="26" /> <Font role="font" uri="font:MediumSystemFontFile" size="26" />
</Label> </Label>
<Label <Label
@@ -0,0 +1,17 @@
import "pkg:/source/utils/Types.bs"
function OnContentSet() as void
content = m.top.itemContent
if content = invalid
return
end if
accountItem = content.accountItem
if not IsAssociativeArray(accountItem)
return
end if
m.top.accountPhoto = accountItem.accountPhoto
m.top.text1 = accountItem.accountName
m.top.text2 = accountItem.channelHandle
end function
@@ -0,0 +1,31 @@
<component name="YouTubeAccountListItem" extends="Group">
<interface>
<field id="itemContent" type="node" onChange="OnContentSet" />
<field id="accountPhoto" type="uri" alias="accountPhoto.uri" />
<field id="text1" type="string" alias="text1Label.text" />
<field id="text2" type="string" alias="text2Label.text" />
</interface>
<children>
<LayoutGroup layoutDirection="horiz" translation="[0, 2]" itemSpacings="[10]">
<Poster
width="64"
height="64"
blendColor="#DDDDDDFF"
uri="pkg:/images/white-circle.png">
<CirclePoster
id="accountPhoto"
width="60"
height="60"
translation="[2,2]"
failedBitmapUri="pkg:/images/thumbnail-missing.jpg" />
</Poster>
<LayoutGroup layoutDirection="vert" translation="[8, 0]" itemSpacings="[10]">
<Label id="text1Label" font="font:SmallestBoldSystemFont" />
<Label id="text2Label" font="font:SmallestSystemFont" />
</LayoutGroup>
</LayoutGroup>
</children>
</component>
@@ -0,0 +1,100 @@
import "pkg:/components/Dialog/YouTubeLoginAccountItemUtils.bs"
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/source/utils/FocusManagement.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RemoteKeys.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.accountList = m.top.FindNode("accountList")
m.accountList.ObserveField("itemSelected", FuncName(OnAccountSelected))
end function
function OnFocusChange() as void
if not m.top.focus
return
end if
NodeSetFocus(m.accountList, true)
end function
function OnKeyEvent(key as string, press as boolean) as boolean
if key = RemoteKeys.Options or key = RemoteKeys.Play or key = RemoteKeys.Pause or key = RemoteKeys.PlayOnly
' A pass-through to the app controller, so it can toggle picture-in-picture and pause/play
return false
end if
if key = RemoteKeys.Back and press
Close()
return true
end if
return true
end function
function Close()
m.top.appController@.PopScreen()
end function
function OnAccountsChanged() as void
accounts = m.top.accounts
if not IsArray(accounts) or accounts.Count() = 0
m.accountList.content = invalid
LogError(Tr(Locale.Dialogs.NoValidAccountsFound))
Close()
return
end if
content = CreateObject("roSGNode", "ContentNode")
accountNodes = []
for each accountItem in accounts
if not IsAssociativeArray(accountItem)
continue for
end if
accountNode = CreateObject("roSGNode", "ContentNode")
accountNode.addField("accountItem", "assocarray", false)
accountNode.accountItem = accountItem
accountNodes.Push(accountNode)
end for
if accountNodes.Count() = 0
m.accountList.content = invalid
LogError(Tr(Locale.Dialogs.NoValidAccountsFound))
Close()
return
end if
content.appendChildren(accountNodes)
m.accountList.content = content
end function
function OnAccountSelected() as void
itemSelected = m.accountList.itemSelected
itemNode = m.accountList.content.GetChild(itemSelected)
if itemNode = invalid
LogError("Invalid item selected:", itemSelected)
Close()
return
end if
accountItem = itemNode.accountItem
if not IsAssociativeArray(accountItem)
LogError("Invalid account item selected:", accountItem)
Close()
return
end if
accessToken = m.top.accessToken
if accessToken = invalid or not IsAssociativeArray(accessToken)
LogError("No valid access token available for YouTube login.")
Close()
return
end if
profileNode = YouTubeLoginAccountItemUtils.CreateProfileContentNode(accountItem, accessToken)
m.top.profilesService@.LoginWithProfile(profileNode)
Close()
end function
@@ -0,0 +1,41 @@
<component name="YouTubeAccountSelectionView" extends="Group" includes="AutoBind,Focus">
<interface>
<field id="accessToken" type="assocarray" />
<field id="accounts" type="array" onChange="OnAccountsChanged" />
<field id="appController" type="node" bind="/AppController" />
<field id="profilesService" type="node" bind="/ProfilesService" />
</interface>
<children>
<Rectangle
width="1280"
height="720"
color="#000000"
opacity="0.5">
</Rectangle>
<Rectangle
width="720"
height="520"
translation="[280,100]"
color="#242424">
<Label
width="720"
horizAlign="center"
translation="[0,45]"
text="Who's watching?">
<Font role="font" uri="font:SystemFontFile" size="24" />
</Label>
<MarkupGrid
id="accountList"
itemComponentName="YouTubeAccountListItem"
itemSize="[640,70]"
itemSpacing="[0,20]"
numColumns="1"
numRows="4"
vertFocusAnimationStyle="floatingFocus"
translation="[40,120]"
focusBitmapUri="pkg:/images/focus-glow-padding-27.9.png" />
</Rectangle>
</children>
</component>
@@ -0,0 +1,11 @@
namespace YouTubeAccountSelectionViewUtils
function Open(appController as object) as object
youTubeAccountSelectionView = CreateObject("roSGNode", "YouTubeAccountSelectionView")
appController@.PushScreen(youTubeAccountSelectionView)
youTubeAccountSelectionView@.BindNode()
return youTubeAccountSelectionView
end function
end namespace
@@ -16,8 +16,7 @@
vertAlign="center" vertAlign="center"
text="Could not get IP address: are we connected to the internet?" text="Could not get IP address: are we connected to the internet?"
wrap="true" wrap="true"
translation="[145,0]" translation="[145,0]" />
/>
</Group> </Group>
<Group id="yesInternet" visible="false"> <Group id="yesInternet" visible="false">
<LayoutGroup <LayoutGroup
@@ -83,9 +82,9 @@
vertAlignment="center" vertAlignment="center"
translation="[0,245]"> translation="[0,245]">
<LayoutGroup layoutDirection="horiz" itemSpacings="[15]"> <LayoutGroup layoutDirection="horiz" itemSpacings="[15]">
<Label <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
font="font:SmallSystemFont" <Label text="1."
text="1." /> font="font:SmallSystemFont" />
<Label <Label
font="font:SmallSystemFont" font="font:SmallSystemFont"
width="380" width="380"
@@ -93,9 +92,9 @@
text="On your phone, connect to the same Wi-Fi network as this device." /> text="On your phone, connect to the same Wi-Fi network as this device." />
</LayoutGroup> </LayoutGroup>
<LayoutGroup layoutDirection="horiz" itemSpacings="[15]"> <LayoutGroup layoutDirection="horiz" itemSpacings="[15]">
<Label <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
font="font:SmallSystemFont" <Label text="2."
text="2." /> font="font:SmallSystemFont" />
<Label <Label
font="font:SmallSystemFont" font="font:SmallSystemFont"
width="380" width="380"
@@ -103,14 +102,14 @@
text="Open the YouTube app on your phone." /> text="Open the YouTube app on your phone." />
</LayoutGroup> </LayoutGroup>
<LayoutGroup layoutDirection="horiz" itemSpacings="[15]"> <LayoutGroup layoutDirection="horiz" itemSpacings="[15]">
<Label <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
font="font:SmallSystemFont" <Label text="3."
text="3." /> font="font:SmallSystemFont" />
<MultiStyleLabel <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<MultiStyleLabel text="Tap the cast icon and select this device."
id="WifiInstructionWithDeviceNameLabel" id="WifiInstructionWithDeviceNameLabel"
width="380" width="380"
wrap="true" wrap="true" />
text="Tap the cast icon and select this device." />
</LayoutGroup> </LayoutGroup>
<Label <Label
text="Roku connected to:" text="Roku connected to:"
@@ -131,9 +130,9 @@
vertAlignment="center" vertAlignment="center"
translation="[0,245]"> translation="[0,245]">
<LayoutGroup layoutDirection="horiz" itemSpacings="[15]"> <LayoutGroup layoutDirection="horiz" itemSpacings="[15]">
<Label <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
font="font:SmallSystemFont" <Label text="1."
text="1." /> font="font:SmallSystemFont" />
<Label <Label
font="font:SmallSystemFont" font="font:SmallSystemFont"
width="380" width="380"
@@ -141,9 +140,9 @@
text="On your phone, open the YouTube app." /> text="On your phone, open the YouTube app." />
</LayoutGroup> </LayoutGroup>
<LayoutGroup layoutDirection="horiz" itemSpacings="[15]"> <LayoutGroup layoutDirection="horiz" itemSpacings="[15]">
<Label <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
font="font:SmallSystemFont" <Label text="2."
text="2." /> font="font:SmallSystemFont" />
<Label <Label
font="font:SmallSystemFont" font="font:SmallSystemFont"
width="380" width="380"
@@ -151,9 +150,9 @@
text="Tap the cast icon." /> text="Tap the cast icon." />
</LayoutGroup> </LayoutGroup>
<LayoutGroup layoutDirection="horiz" itemSpacings="[15]"> <LayoutGroup layoutDirection="horiz" itemSpacings="[15]">
<Label <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
font="font:SmallSystemFont" <Label text="3."
text="3." /> font="font:SmallSystemFont" />
<Label <Label
font="font:SmallSystemFont" font="font:SmallSystemFont"
width="380" width="380"
@@ -18,16 +18,14 @@
<DynamicMiniKeyboard <DynamicMiniKeyboard
id="keyboard" id="keyboard"
translation="[695,110]" translation="[695,110]" />
/>
<ButtonGroup <ButtonGroup
id="suggestions" id="suggestions"
focusable="false" focusable="false"
minWidth="400" minWidth="400"
maxWidth="480" maxWidth="480"
buttonHeight="50" buttonHeight="50"
translation="[125,100]" translation="[125,100]" />
/>
<VideoRowList <VideoRowList
itemComponentName="RowCell" itemComponentName="RowCell"
id="rowList" id="rowList"
@@ -43,8 +41,7 @@
showRowLabel="[true]" showRowLabel="[true]"
rowFocusAnimationStyle="floatingfocus" rowFocusAnimationStyle="floatingfocus"
variableWidthItems="true" variableWidthItems="true"
focusBitmapUri="pkg:/images/focus-glow-padding-19.9.png" focusBitmapUri="pkg:/images/focus-glow-padding-19.9.png" />
/>
<Animation <Animation
id="scrollAnimation" id="scrollAnimation"
duration="0.3"> duration="0.3">
@@ -17,7 +17,7 @@ function SearchSuggestionsTask(input as object) as object
suggestions: [] suggestions: []
} }
else else
backend = preferencesNode["playback.backend"] backend = preferencesNode["backend.selected"]
if backend = "playlet" if backend = "playlet"
searchSuggestsions = InnertubeService.SearchSuggestions(q, m.top.cancellation) searchSuggestsions = InnertubeService.SearchSuggestions(q, m.top.cancellation)
else else
@@ -19,7 +19,7 @@
<CheckList <CheckList
id="checkList" id="checkList"
vertFocusAnimationStyle="floatingFocus" vertFocusAnimationStyle="floatingFocus"
translation="[164,70]"> translation="[164,40]">
<ContentNode role="content" /> <ContentNode role="content" />
</CheckList> </CheckList>
@@ -77,8 +77,8 @@ function ShowTestDetails() as void
state = itemContent.state state = itemContent.state
displayStates = { displayStates = {
"passed": Locale.InvidiousTesting.Passed "passed": Tr(Locale.InvidiousTesting.Passed)
"failed": Locale.InvidiousTesting.Failed "failed": Tr(Locale.InvidiousTesting.Failed)
} }
message = Tr(Locale.InvidiousTesting.Status) + ": " + Tr(ValidString(displayStates[state])) + `\n` message = Tr(Locale.InvidiousTesting.Status) + ": " + Tr(ValidString(displayStates[state])) + `\n`
@@ -24,8 +24,6 @@ end function
function PrepareTests() as object function PrepareTests() as object
content = CreateObject("roSGNode", "ContentNode") content = CreateObject("roSGNode", "ContentNode")
' TODO:P2 test if video data is reachable (head?)
' TODO:P2 test if video data is reachable in proxy mode (local=true)
content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.ValidUrl), IsValidUrl)) content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.ValidUrl), IsValidUrl))
content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.InstanceReachable), IsReachable)) content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.InstanceReachable), IsReachable))
content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.FetchVideoDetails), CanFetchVideoDetails)) content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.FetchVideoDetails), CanFetchVideoDetails))
@@ -10,7 +10,7 @@
translation="[380,96]" /> translation="[380,96]" />
<Label <Label
id="failedLabel" id="failedLabel"
text="Failed to load Invidious public instances." text="Failed to load Invidious public instances"
horizAlign="center" horizAlign="center"
translation="[0,60]" translation="[0,60]"
width="960" /> width="960" />
@@ -16,29 +16,29 @@
<Font role="font" uri="font:SystemFontFile" size="18" /> <Font role="font" uri="font:SystemFontFile" size="18" />
</Label> </Label>
<LayoutGroup layoutDirection="horiz"> <LayoutGroup layoutDirection="horiz">
<Button <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<Button text="-"
id="MinusButton" id="MinusButton"
iconUri="" iconUri=""
focusedIconUri="" focusedIconUri=""
minWidth="64" minWidth="64"
maxWidth="64" maxWidth="64"
showFocusFootprint="true" showFocusFootprint="true" />
text="-" /> <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<Button <Button text="0"
id="NumberButton" id="NumberButton"
iconUri="" iconUri=""
focusedIconUri="" focusedIconUri=""
minWidth="150" minWidth="150"
showFocusFootprint="true" showFocusFootprint="true" />
text="0" /> <!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<Button <Button text="+"
id="PlusButton" id="PlusButton"
iconUri="" iconUri=""
focusedIconUri="" focusedIconUri=""
minWidth="64" minWidth="64"
maxWidth="64" maxWidth="64"
showFocusFootprint="true" showFocusFootprint="true" />
text="+" />
</LayoutGroup> </LayoutGroup>
</children> </children>
</component> </component>
@@ -23,11 +23,17 @@
<ContentNode role="content"> <ContentNode role="content">
<ContentNode id="auto" title="Auto" /> <ContentNode id="auto" title="Auto" />
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<ContentNode id="1080p" title="1080p" /> <ContentNode id="1080p" title="1080p" />
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<ContentNode id="720p" title="720p" /> <ContentNode id="720p" title="720p" />
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<ContentNode id="480p" title="480p" /> <ContentNode id="480p" title="480p" />
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<ContentNode id="360p" title="360p" /> <ContentNode id="360p" title="360p" />
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<ContentNode id="240p" title="240p" /> <ContentNode id="240p" title="240p" />
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS -->
<ContentNode id="144p" title="144p" /> <ContentNode id="144p" title="144p" />
</ContentNode> </ContentNode>
</CheckList> </CheckList>
@@ -0,0 +1,79 @@
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/source/utils/FocusManagement.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.top.focusable = true
m.top.itemSpacings = [8]
m.button = m.top.findNode("button")
m.button.observeField("buttonSelected", FuncName(OpenSponsorBlockCategories))
AdjustButtonLabel(m.button)
end function
function OnFocusChange() as void
if not m.top.focus
return
end if
NodeSetFocus(m.button, true)
end function
function AdjustButtonLabel(button as object) as void
children = button.getChildren(-1, 0)
for each child in children
if child.isSubtype("Label") and child.hasField("horizAlign")
child.observeField("horizAlign", FuncName(OnButtonLabelHorizAlignChanged))
child.horizAlign = "left"
return
end if
end for
end function
function OnButtonLabelHorizAlignChanged(event as object)
label = event.getRoSGNode()
if label.horizAlign <> "left"
label.horizAlign = "left"
end if
end function
function BindPreference(preferences as object, key as string)
if m.preferences <> invalid and m.key <> invalid
m.preferences.unobserveFieldScoped(m.key)
end if
m.preferences = preferences
m.key = key
if preferences <> invalid and key <> invalid
preferences.observeFieldScoped(key, FuncName(OnPreferenceChange))
OnPreferenceChange()
end if
end function
function OpenSponsorBlockCategories()
categoriesPrefs = CreateObject("roSGNode", "SponsorBlockCategoriesPreferences")
m.appController@.PushScreen(categoriesPrefs)
categoriesPrefs@.BindNode()
categoriesPrefs.value = m.top.value
categoriesPrefs.observeField("save", FuncName(OnSaveCategoriesPreferences))
end function
function OnSaveCategoriesPreferences(event as object)
categoriesPrefs = event.GetRoSGNode()
m.top.value = categoriesPrefs.value
end function
function OnPreferenceChange()
m.top.value = m.preferences[m.key]
end function
function OnValueChange() as void
if m.preferences = invalid or m.key = invalid
return
end if
m.preferences[m.key] = m.top.value
end function
@@ -0,0 +1,21 @@
<component name="SponsorBlockCategoriesControl" extends="LayoutGroup" includes="AutoBind,Focus">
<interface>
<field id="displayText" type="string" alias="Button.text" />
<field id="description" type="string" alias="DescriptionLabel.text" />
<field id="value" type="assocarray" onChange="OnValueChange" />
<field id="appController" type="node" bind="/AppController" />
<function name="BindPreference" />
</interface>
<children>
<Button
id="button"
minWidth="300"
showFocusFootprint="true" />
<Label id="DescriptionLabel"
width="450"
color="0xb4b4b4ff"
wrap="true">
<Font role="font" uri="font:SystemFontFile" size="18" />
</Label>
</children>
</component>
@@ -0,0 +1,181 @@
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Navigation/Navigation.bs"
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
import "pkg:/components/VideoPlayer/SponsorBlockSegmentAction.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RemoteKeys.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.categoryList = m.top.findNode("categoryList")
m.categoryList.ObserveField("itemSelected", FuncName(OnCategorySelected))
m.service = new SponsorBlock.SponsorBlockService()
optionTitles = {}
optionTitles[SponsorBlock.SegmentAction.Disable] = Tr(Locale.SponsorBlock.Disable)
optionTitles[SponsorBlock.SegmentAction.AutoSkip] = Tr(Locale.SponsorBlock.AutoSkip)
optionTitles[SponsorBlock.SegmentAction.ManualSkip] = Tr(Locale.SponsorBlock.ManualSkip)
optionTitles[SponsorBlock.SegmentAction.ShowInSeekbar] = Tr(Locale.SponsorBlock.ShowInSeekbar)
m.optionTitles = optionTitles
SetupCategoriesUi()
m.closeButton = m.top.findNode("closeButton")
m.saveButton = m.top.findNode("saveButton")
SetButtonPositions()
SetNavigation(m.saveButton, RemoteKeys.Right, m.closeButton)
SetNavigation(m.closeButton, RemoteKeys.Left, m.saveButton)
SetNavigation(m.saveButton, RemoteKeys.Up, m.categoryList)
SetNavigation(m.closeButton, RemoteKeys.Up, m.categoryList)
SetNavigation(m.categoryList, RemoteKeys.Down, m.saveButton)
m.saveButton.observeField("buttonSelected", FuncName(OnSaveButtonSelected))
m.closeButton.observeField("buttonSelected", FuncName(Close))
end function
function SetupCategoriesUi() as void
categories = m.service.GetCategories()
if categories.Count() = 0
return
end if
content = CreateObject("roSGNode", "ContentNode")
categoryContentNodes = []
for each category in categories
categoryNode = CreateObject("roSGNode", "SponsorBlockCategoryContent")
categoryNode.category = category
categoryNode.categoryTitle = Tr(m.service.SegmentTitle(category))
categoryNode.selectedOption = SponsorBlock.SegmentAction.Disable
categoryNode.options = m.service.GetOptionsForCategory(category)
categoryNode.optionTitles = m.optionTitles
categoryNode.color = m.service.SegmentColor(category)
categoryContentNodes.push(categoryNode)
end for
content.appendChildren(categoryContentNodes)
m.categoryList.content = content
end function
function SetButtonPositions()
saveButtonWidth = m.saveButton.width
closeButtonWidth = m.closeButton.width
buttonsWith = closeButtonWidth + saveButtonWidth + 20
m.saveButton.translation = [720 / 2 - buttonsWith / 2, m.saveButton.translation[1]]
m.closeButton.translation = [720 / 2 + buttonsWith / 2 - closeButtonWidth, m.closeButton.translation[1]]
end function
function OnFocusChange() as void
if not m.top.focus
return
end if
NodeSetFocus(m.categoryList, true)
end function
function OnKeyEvent(key as string, press as boolean) as boolean
if NavigationKeyHandler(key, press).handled
return true
end if
if key = RemoteKeys.Options or key = RemoteKeys.Play or key = RemoteKeys.Pause or key = RemoteKeys.PlayOnly
' A pass-through to the app controller, so it can toggle picture-in-picture and pause/play
return false
end if
if key = RemoteKeys.Back and press
Close()
return true
end if
return true
end function
function OnValueChange() as void
content = m.categoryList.content
if content = invalid
return
end if
value = m.top.value
if not IsAssociativeArray(value)
return
end if
categoryContentNodes = content.getChildren(-1, 0)
categoryNodeMap = {}
for each categoryContentNode in categoryContentNodes
categoryNodeMap[categoryContentNode.category] = categoryContentNode
end for
for each category in value
if not categoryNodeMap.DoesExist(category)
continue for
end if
categoryNode = categoryNodeMap[category]
if categoryNode = invalid
continue for
end if
categoryNode.selectedOption = value[category].option
end for
end function
function OnSaveButtonSelected()
m.top.save = true
Close()
end function
function Close()
m.appController@.PopScreen()
end function
function OnCategorySelected(event as object) as void
itemSelected = m.categoryList.itemSelected
itemNode = m.categoryList.content.GetChild(itemSelected)
if itemNode = invalid
LogError("Invalid item selected:", itemSelected)
return
end if
options = itemNode.options
optionTitles = itemNode.optionTitles
optionTitlesArray = []
for each option in options
optionTitlesArray.push(optionTitles[option])
end for
dialog = DialogUtils.ShowDialogEx({
title: itemNode.categoryTitle
message: Tr(Locale.Settings.SelectOptionFor).Replace("%1", itemNode.categoryTitle)
buttons: optionTitlesArray
})
if dialog = invalid
return
end if
dialog.addFields({
"categoryContentNode": itemNode
"options": options
})
dialog.observeField("buttonSelected", FuncName(OnCategoryDialogResult), ["buttonSelected"])
end function
function OnCategoryDialogResult(event as object) as void
dialog = event.getRoSGNode()
options = dialog.options
buttonIndex = event.GetData()
if not IsInt(buttonIndex) or buttonIndex < 0 or buttonIndex >= options.Count()
return
end if
selectedOption = options[buttonIndex]
category = dialog.categoryContentNode.category
value = m.top.value
value[category].option = selectedOption
m.top.value = value
LogInfo("SponsorBlock category", category, "set to", selectedOption)
end function
@@ -0,0 +1,52 @@
<component name="SponsorBlockCategoriesPreferences" extends="Group" includes="AutoBind,Focus">
<interface>
<field id="value" type="assocarray" onChange="OnValueChange" />
<field id="save" type="boolean" alwaysNotify="true" />
<field id="appController" type="node" bind="/AppController" />
</interface>
<children>
<Rectangle
width="1280"
height="720"
color="#000000"
opacity="0.5">
</Rectangle>
<Rectangle
width="720"
height="600"
translation="[300,60]"
color="#242424">
<Label
width="720"
horizAlign="center"
translation="[0,38]"
text="Categories">
<Font role="font" uri="font:SystemFontFile" size="24" />
</Label>
<MarkupGrid
id="categoryList"
itemComponentName="SponsorBlockCategoryListItem"
itemSize="[640,32]"
itemSpacing="[0,10]"
numColumns="1"
numRows="10"
vertFocusAnimationStyle="floatingFocus"
translation="[40,100]"
focusBitmapUri="pkg:/images/focus-glow-padding-19.9.png" />
<ButtonEx
id="saveButton"
iconVisible="false"
text="Save"
padding="[30,30]"
translation="[340,500]" />
<ButtonEx
id="closeButton"
iconVisible="false"
text="Close"
padding="[30,30]"
translation="[496,500]" />
</Rectangle>
</children>
</component>
@@ -0,0 +1,10 @@
<component name="SponsorBlockCategoryContent" extends="ContentNode">
<interface>
<field id="category" type="string" />
<field id="categoryTitle" type="string" />
<field id="selectedOption" type="string" />
<field id="options" type="stringarray" />
<field id="optionTitles" type="assocarray" />
<field id="color" type="color" />
</interface>
</component>
@@ -0,0 +1,11 @@
function OnContentSet() as void
content = m.top.itemContent
if content = invalid
return
end if
m.top.categoryTitle = content.categoryTitle
optionTitles = content.optionTitles
m.top.optionTitle = optionTitles[content.selectedOption]
m.top.color = content.color
end function
@@ -0,0 +1,30 @@
<component name="SponsorBlockCategoryListItem" extends="Group">
<interface>
<field id="itemContent" type="node" onChange="OnContentSet" />
<field id="categoryTitle" type="string" alias="categoryLabel.text" />
<field id="optionTitle" type="string" alias="optionLabel.text" />
<field id="color" type="color" alias="colorRect.color" />
</interface>
<children>
<Rectangle id="colorRect"
width="52"
height="28"
translation="[10, 2]" />
<Label id="categoryLabel"
font="font:SmallestSystemFont"
width="320"
height="32"
vertAlign="center"
horizAlign="left"
translation="[80, 0]" />
<Label id="optionLabel"
width="320"
height="32"
font="font:SmallestSystemFont"
vertAlign="center"
horizAlign="right"
translation="[310, 0]" />
</children>
</component>
@@ -12,7 +12,6 @@ class DashManifest
m.invidiousInstance = invidiousInstance m.invidiousInstance = invidiousInstance
m.utils = new Http.Utils() m.utils = new Http.Utils()
m.urlRegex = /https?:\/\/\S+(\/\S+)/i
' https://github.com/LuanRT/YouTube.js/blob/6082b4a52ee07a622735e6e9128a0531a5ae3bfb/src/utils/StreamingInfo.ts#L332-L349 ' https://github.com/LuanRT/YouTube.js/blob/6082b4a52ee07a622735e6e9128a0531a5ae3bfb/src/utils/StreamingInfo.ts#L332-L349
m.colorInfo = { m.colorInfo = {
@@ -38,8 +37,11 @@ class DashManifest
adaptiveFormats.Append(metadata.adaptiveFormats) adaptiveFormats.Append(metadata.adaptiveFormats)
if local if local
parsedInvidiousUrl = UrlUtils.ParseUrl(m.invidiousInstance)
for i = 0 to adaptiveFormats.Count() - 1 for i = 0 to adaptiveFormats.Count() - 1
adaptiveFormats[i].url = m.urlRegex.replace(adaptiveFormats[i].url, m.invidiousInstance + "\1") parsedUrl = UrlUtils.ParseUrl(adaptiveFormats[i].url)
parsedInvidiousUrl.path = UrlUtils.AppendQueryParams(parsedUrl.path, { host: parsedUrl.host })
adaptiveFormats[i].url = UrlUtils.BuildUrlFromParts(parsedInvidiousUrl)
end for end for
end if end if
@@ -1,14 +1,18 @@
import "pkg:/components/Services/Innertube/Context.bs" import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
namespace Innertube namespace Innertube
function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, params = "" as string, continuation = "" as string) as object function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, options = invalid as object) as object
params = OptionUtils.GetOrDefault(options, "params", "")
continuation = OptionUtils.GetOrDefault(options, "continuation", "")
deviceInfo = CreateObject("roDeviceInfo") deviceInfo = CreateObject("roDeviceInfo")
payload = { payload = {
"context": Innertube.CreateContext(clienType, deviceInfo, "", "") "context": Innertube.CreateContext(clienType, deviceInfo, options)
} }
if not StringUtils.IsNullOrEmpty(continuation) if not StringUtils.IsNullOrEmpty(continuation)
@@ -21,12 +25,7 @@ namespace Innertube
end if end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json", payload) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json", payload)
headers = { request.Headers(Innertube.CreateHeaders(clienType))
"accept": "*/*"
"accept-language": "*"
}
headers.Append(Innertube.CreateHeaders(clienType))
request.Headers(headers)
return request return request
end function end function
@@ -1,21 +1,23 @@
const VIDEO_PLAYER_USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:139.0) Gecko/20100101 Firefox/139.0"
const INNERTUBE_IOS_CLIENT_NAME = "5" const INNERTUBE_IOS_CLIENT_NAME = "5"
const INNERTUBE_IOS_CLIENT_VERSION = "19.49.7" const INNERTUBE_IOS_CLIENT_VERSION = "20.20.5"
const INNERTUBE_IOS_DEVICE_MODEL = "iPhone16,2" const INNERTUBE_IOS_DEVICE_MODEL = "iPhone16,2"
const INNERTUBE_IOS_OS_VERSION = "18.1" const INNERTUBE_IOS_OS_VERSION = "18.1"
const INNERTUBE_IOS_USER_AGENT = "com.google.ios.youtube/19.49.7 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X)" const INNERTUBE_IOS_USER_AGENT = "com.google.ios.youtube/20.20.5 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X)"
const INNERTUBE_WEB_BROWSER_NAME = "Chrome" const INNERTUBE_WEB_BROWSER_NAME = "Chrome"
const INNERTUBE_WEB_BROWSER_VERSION = "135.0.0.0" const INNERTUBE_WEB_BROWSER_VERSION = "136.0.0.0"
const INNERTUBE_WEB_CLIENT_NAME = "1" const INNERTUBE_WEB_CLIENT_NAME = "1"
const INNERTUBE_WEB_CLIENT_VERSION = "2.20250502.01.00" const INNERTUBE_WEB_CLIENT_VERSION = "2.20250520.05.00"
const INNERTUBE_WEB_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0" const INNERTUBE_WEB_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0"
const INNERTUBE_TV_BROWSER_NAME = "LG Browser" const INNERTUBE_TV_BROWSER_NAME = "SamsungBrowser"
const INNERTUBE_TV_BROWSER_VERSION = "7.00.00" const INNERTUBE_TV_BROWSER_VERSION = "9.2"
const INNERTUBE_TV_CLIENT_NAME = "2" const INNERTUBE_TV_CLIENT_NAME = "2"
const INNERTUBE_TV_CLIENT_VERSION = "7.20241211.14.01" const INNERTUBE_TV_CLIENT_VERSION = "7.20250519.12.01"
const INNERTUBE_TV_DEVICE_MAKE = "LGE" const INNERTUBE_TV_DEVICE_MAKE = "Samsung"
const INNERTUBE_TV_DEVICE_MODEL = "24LF4820-BU" const INNERTUBE_TV_DEVICE_MODEL = "SmartTV"
const INNERTUBE_TV_OS_NAME = "webOS" const INNERTUBE_TV_OS_NAME = "Tizen"
const INNERTUBE_TV_OS_VERSION = "2015" const INNERTUBE_TV_OS_VERSION = "4.0.0.2"
const INNERTUBE_TV_USER_AGENT = "Mozilla/5.0 (Web0S; Linux/SmartTV) AppleWebKit/538.2 (KHTML, like Gecko) Large Screen Safari/538.2 LG Browser/7.00.00(LGE; 24LF4820-BU; 03.20.14; 1; DTV_W15L); webOS.TV-2015; LG NetCast.TV-2013 Compatible (LGE, 24LF4820-BU, wireless)" const INNERTUBE_TV_USER_AGENT = "Mozilla/5.0(SMART-TV; Linux; Tizen 4.0.0.2) AppleWebkit/605.1.15 (KHTML, like Gecko) SamsungBrowser/9.2 TV Safari/605.1.15"
@@ -1,4 +1,5 @@
import "pkg:/components/Services/Innertube/Constants.bs" import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
namespace Innertube namespace Innertube
@@ -12,18 +13,24 @@ namespace Innertube
function CreateHeaders(clienType as Innertube.ClientType) as object function CreateHeaders(clienType as Innertube.ClientType) as object
if clienType = ClientType.Web if clienType = ClientType.Web
return { return {
"accept": "*/*"
"accept-language": "*"
"user-agent": INNERTUBE_WEB_USER_AGENT "user-agent": INNERTUBE_WEB_USER_AGENT
"x-youtube-client-name": INNERTUBE_WEB_CLIENT_NAME "x-youtube-client-name": INNERTUBE_WEB_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_WEB_CLIENT_VERSION "x-youtube-client-version": INNERTUBE_WEB_CLIENT_VERSION
} }
else if clienType = ClientType.IOS else if clienType = ClientType.IOS
return { return {
"accept": "*/*"
"accept-language": "*"
"user-agent": INNERTUBE_IOS_USER_AGENT "user-agent": INNERTUBE_IOS_USER_AGENT
"x-youtube-client-name": INNERTUBE_IOS_CLIENT_NAME "x-youtube-client-name": INNERTUBE_IOS_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_IOS_CLIENT_VERSION "x-youtube-client-version": INNERTUBE_IOS_CLIENT_VERSION
} }
else if clienType = ClientType.Tv else if clienType = ClientType.Tv
return { return {
"accept": "*/*"
"accept-language": "*"
"user-agent": INNERTUBE_TV_USER_AGENT "user-agent": INNERTUBE_TV_USER_AGENT
"x-youtube-client-name": INNERTUBE_TV_CLIENT_NAME "x-youtube-client-name": INNERTUBE_TV_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_TV_CLIENT_VERSION "x-youtube-client-version": INNERTUBE_TV_CLIENT_VERSION
@@ -33,7 +40,7 @@ namespace Innertube
end if end if
end function end function
function CreateContext(clienType as Innertube.ClientType, deviceInfo as object, ctt as string, visitorData as string) as object function CreateContext(clienType as Innertube.ClientType, deviceInfo as object, options = invalid as object) as object
client = invalid client = invalid
if clienType = ClientType.Web if clienType = ClientType.Web
client = CreateContextClientWeb(deviceInfo) client = CreateContextClientWeb(deviceInfo)
@@ -45,6 +52,10 @@ namespace Innertube
throw "Invalid client type" throw "Invalid client type"
end if end if
credentialTransferToken = OptionUtils.Get(options, "credentialTransferToken")
visitorData = OptionUtils.Get(options, "visitorData")
onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser")
context = { context = {
"client": client "client": client
"user": { "user": {
@@ -57,9 +68,9 @@ namespace Innertube
} }
} }
if not StringUtils.IsNullOrEmpty(ctt) if not StringUtils.IsNullOrEmpty(credentialTransferToken)
context["user"]["credentialTransferTokens"] = [{ context["user"]["credentialTransferTokens"] = [{
"token": ctt "token": credentialTransferToken
"scope": "VIDEO" "scope": "VIDEO"
}] }]
end if end if
@@ -68,6 +79,10 @@ namespace Innertube
context["client"]["visitorData"] = visitorData context["client"]["visitorData"] = visitorData
end if end if
if not StringUtils.IsNullOrEmpty(onBehalfOfUser)
context["user"]["onBehalfOfUser"] = onBehalfOfUser
end if
return context return context
end function end function
@@ -147,6 +162,7 @@ namespace Innertube
"clientFormFactor": "UNKNOWN_FORM_FACTOR" "clientFormFactor": "UNKNOWN_FORM_FACTOR"
"webpSupport": false "webpSupport": false
"tvAppInfo": { "tvAppInfo": {
' "appQuality": "TV_APP_QUALITY_FULL_ANIMATION"
"appQuality": "TV_APP_QUALITY_LIMITED_MEMORY" "appQuality": "TV_APP_QUALITY_LIMITED_MEMORY"
"useStartPlaybackPreviewCommand": false "useStartPlaybackPreviewCommand": false
"supportsNativeScrolling": false "supportsNativeScrolling": false
@@ -1,5 +1,7 @@
<component name="Innertube" extends="Node"> <component name="Innertube" extends="Node">
<interface> <interface>
<field id="timestamp" type="int" />
<field id="visitorData" type="string" /> <field id="visitorData" type="string" />
<field id="poToken" type="string" />
</interface> </interface>
</component> </component>
@@ -9,7 +9,17 @@ function InnertubeInitTask(input as object) as object
return invalid return invalid
end if end if
if IsInt(sessionData.timestamp)
innertubeNode.timestamp = sessionData.timestamp
end if
if not StringUtils.IsNullOrEmpty(sessionData.visitorData)
innertubeNode.visitorData = sessionData.visitorData innertubeNode.visitorData = sessionData.visitorData
end if
if not StringUtils.IsNullOrEmpty(sessionData.poToken)
innertubeNode.poToken = sessionData.poToken
end if
return invalid return invalid
end function end function
@@ -7,54 +7,34 @@ import "pkg:/components/Services/Innertube/PlayerEndpoint.bs"
import "pkg:/components/Services/Innertube/ResolveUrlEndpoint.bs" import "pkg:/components/Services/Innertube/ResolveUrlEndpoint.bs"
import "pkg:/components/Services/Innertube/SearchEndpoint.bs" import "pkg:/components/Services/Innertube/SearchEndpoint.bs"
import "pkg:/components/Services/Innertube/SearchFilters.bs" import "pkg:/components/Services/Innertube/SearchFilters.bs"
import "pkg:/components/Services/Innertube/SubscriptionEndpoint.bs"
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CancellationUtils.bs" import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/ObjectUtils.bs" import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/TimeUtils.bs" import "pkg:/source/utils/TimeUtils.bs"
namespace InnertubeService namespace InnertubeService
function GetVideoMetadata(videoId as string, options = invalid as object) as object function GetVideoMetadata(videoId as string, options = invalid as object) as object
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
fetchNext = true fetchNext = OptionUtils.GetOrDefault(options, "fetchNext", true)
ctt = "" raw = OptionUtils.GetOrDefault(options, "raw", false)
visitorData = ""
raw = false
if options <> invalid playerRequest = Innertube.CreatePlayerRequest(videoId, Innertube.ClientType.IOS, options)
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("fetchNext")
fetchNext = options.fetchNext
end if
if options.DoesExist("ctt")
ctt = options.ctt
end if
if options.DoesExist("raw")
raw = options.raw
end if
if options.DoesExist("visitorData")
visitorData = options.visitorData
end if
end if
playerRequest = Innertube.CreatePlayerRequest(videoId, ctt, visitorData)
playerRequest.Cancellation(cancellation) playerRequest.Cancellation(cancellation)
if raw if raw
playerRequest.LogCurlCommand() playerRequest.LogCurlCommand()
playerRequest.NoCache()
end if end if
playerRequest.Send() playerRequest.Send()
nextRequest = invalid nextRequest = invalid
nextResponse = invalid nextResponse = invalid
if fetchNext if fetchNext
nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, ctt) nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, options)
nextRequest.Cancellation(cancellation) nextRequest.Cancellation(cancellation)
if raw if raw
nextRequest.LogCurlCommand() nextRequest.LogCurlCommand()
nextRequest.NoCache()
end if end if
nextRequest.Send() nextRequest.Send()
end if end if
@@ -110,20 +90,11 @@ namespace InnertubeService
} }
end if end if
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
retry = true retry = OptionUtils.GetOrDefault(options, "retry", true)
if options <> invalid
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("retry")
retry = options.retry
end if
end if
params = Innertube.GetEncodedNextParams(videoIds) params = Innertube.GetEncodedNextParams(videoIds)
request = Innertube.CreateNextRequest({ "params": params }, "") request = Innertube.CreateNextRequest({ "params": params })
request.Cancellation(cancellation) request.Cancellation(cancellation)
response = request.Await() response = request.Await()
@@ -181,41 +152,16 @@ namespace InnertubeService
end function end function
function Search(query as string, options = invalid as object) as object function Search(query as string, options = invalid as object) as object
searchFilters = invalid return Innertube.Search(query, options)
continuation = ""
cancellation = invalid
raw = false
if options <> invalid
if options.DoesExist("searchFilters")
searchFilters = options.searchFilters
end if
if options.DoesExist("continuation")
continuation = options.continuation
end if
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("raw")
raw = options.raw
end if
end if
return Innertube.Search(query, searchFilters, continuation, cancellation, raw)
end function end function
function GetTrending(options = invalid as object) as object function GetTrending(options = invalid as object) as object
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
trendingType = LCase(OptionUtils.GetOrDefault(options, "type", ""))
disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false)
raw = OptionUtils.GetOrDefault(options, "raw", false)
params = "" params = ""
raw = false
if options <> invalid
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("type")
trendingType = LCase(ValidString(options.type))
if trendingType = "music" if trendingType = "music"
' {"44:proto": {"3:string": "ytma_charts"}} ' {"44:proto": {"3:string": "ytma_charts"}}
params = "4gINGgt5dG1hX2NoYXJ0cw%3D%3D" params = "4gINGgt5dG1hX2NoYXJ0cw%3D%3D"
@@ -226,13 +172,8 @@ namespace InnertubeService
' {"44:proto": {"3:string": "trailers"}} ' {"44:proto": {"3:string": "trailers"}}
params = "4gIKGgh0cmFpbGVycw%3D%3D" params = "4gIKGgh0cmFpbGVycw%3D%3D"
end if end if
end if
if options.DoesExist("raw")
raw = options.raw
end if
end if
request = Innertube.CreateBrowseRequest("FEtrending", Innertube.ClientType.WEB, params) request = Innertube.CreateBrowseRequest("FEtrending", Innertube.ClientType.WEB, { params: params })
request.Cancellation(cancellation) request.Cancellation(cancellation)
if raw if raw
@@ -251,7 +192,10 @@ namespace InnertubeService
return response.Json() return response.Json()
end if end if
feeds = Innertube.ParseResponseDataForFeeds(response.Json(), { skipCreatorOnTheRise: true }) feeds = Innertube.ParseResponseDataForFeeds(response.Json(), {
disableCreatorOnTheRise: true
disableShorts: disableShorts
})
result = { result = {
feeds: feeds feeds: feeds
@@ -282,23 +226,12 @@ namespace InnertubeService
end function end function
function GetBrowseAuthenticatedPage(browserId as string, options = invalid as object) as object function GetBrowseAuthenticatedPage(browserId as string, options = invalid as object) as object
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
accessToken = invalid accessToken = OptionUtils.Get(options, "accessToken")
continuation = "" disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false)
if options <> invalid request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv, options)
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("accessToken")
accessToken = options.accessToken
end if
if options.DoesExist("continuation")
continuation = options.continuation
end if
end if
request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv, "", continuation)
if accessToken <> invalid if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken) request.Header("Authorization", "Bearer " + accessToken)
end if end if
@@ -311,32 +244,149 @@ namespace InnertubeService
} }
end if end if
json = response.Json() feeds = Innertube.ParseResponseDataForFeeds(response.Json(), { disableShorts: disableShorts })
return Innertube.ParseResponseDataForFeeds(json)
result = {
feeds: feeds
}
cacheControl = Innertube.ParseResponseForCacheControl(response)
if cacheControl <> invalid
result["cache-control"] = cacheControl
end if
return result
end function end function
function GetChannel(channelId as string, options = invalid as object) as object function AuthGetPlaybackTrackingUrls(videoId as string, options as object) as object
continuation = ""
params = ""
cancellation = invalid cancellation = invalid
raw = false accessToken = options.accessToken
if options <> invalid
if options.DoesExist("continuation")
continuation = options.continuation
end if
if options.DoesExist("params")
params = options.params
end if
if options.DoesExist("cancellation") if options.DoesExist("cancellation")
cancellation = options.cancellation cancellation = options.cancellation
end if end if
if options.DoesExist("raw")
raw = options.raw playerRequest = Innertube.CreatePlayerRequest(videoId, Innertube.ClientType.Tv, options)
end if playerRequest.Cancellation(cancellation)
playerRequest.Header("Authorization", "Bearer " + accessToken)
playerResponse = playerRequest.Await()
if not playerResponse.IsSuccess()
return {
error: playerResponse.ErrorMessage()
}
end if end if
request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, params, continuation) json = playerResponse.Json()
error = Innertube.ParsePlayerResponseForError(json)
if error <> ""
return {
error: error
}
end if
videostatsPlaybackUrl = ObjectUtils.Dig(json, ["playbackTracking", "videostatsPlaybackUrl", "baseUrl"])
videostatsWatchtimeUrl = ObjectUtils.Dig(json, ["playbackTracking", "videostatsWatchtimeUrl", "baseUrl"])
return {
videostatsPlaybackUrl: videostatsPlaybackUrl
videostatsWatchtimeUrl: videostatsWatchtimeUrl
}
end function
function AuthMarkVideoWatched(videostatsPlaybackUrl as string, options as object) as boolean
cancellation = OptionUtils.Get(options, "cancellation")
accessToken = OptionUtils.Get(options, "accessToken")
onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser")
videostatsPlaybackUrl = videostatsPlaybackUrl.replace("https://s.", "https://www.")
queryParams = UrlUtils.ParseQueryComponents(videostatsPlaybackUrl)
queryParams["c"] = "TVHTML5"
queryParams["cbrver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["cver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["ver"] = "2"
queryParams["cpn"] = InnertubeService.CreateClientPlaybackNonce()
queryParams["cmt"] = 0
queryParams["final"] = "1"
videostatsPlaybackUrl = UrlUtils.SetQueryParams(videostatsPlaybackUrl, queryParams)
request = HttpClient.Get(videostatsPlaybackUrl)
request.Cancellation(cancellation)
request.NoCache()
request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv))
request.Header("Authorization", "Bearer " + accessToken)
if not StringUtils.IsNullOrEmpty(onBehalfOfUser)
request.Header("X-Goog-Pageid", onBehalfOfUser)
end if
response = request.Await()
if not response.IsSuccess()
LogError("Error marking video as watched:", response.ErrorMessage())
return false
end if
LogDebug("Marked video as watched")
return true
end function
function AuthMarkVideoWatchTime(time as float, videostatsWatchtimeUrl as string, options = invalid as object) as boolean
cancellation = OptionUtils.Get(options, "cancellation")
accessToken = OptionUtils.Get(options, "accessToken")
onBehalfOfUser = OptionUtils.Get(options, "onBehalfOfUser")
timeStr = time.ToStr("%.3f")
videostatsWatchtimeUrl = videostatsWatchtimeUrl.replace("https://s.", "https://www.")
queryParams = UrlUtils.ParseQueryComponents(videostatsWatchtimeUrl)
queryParams["c"] = "TVHTML5"
queryParams["cbrver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["cver"] = INNERTUBE_TV_CLIENT_VERSION
queryParams["ver"] = "2"
queryParams["cpn"] = InnertubeService.CreateClientPlaybackNonce()
queryParams["cmt"] = 0
queryParams["final"] = "1"
queryParams["st"] = timeStr
queryParams["et"] = timeStr
videostatsWatchtimeUrl = UrlUtils.SetQueryParams(videostatsWatchtimeUrl, queryParams)
request = HttpClient.Get(videostatsWatchtimeUrl)
request.Cancellation(cancellation)
request.NoCache()
request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv))
request.Header("Authorization", "Bearer " + accessToken)
if not StringUtils.IsNullOrEmpty(onBehalfOfUser)
request.Header("X-Goog-Pageid", onBehalfOfUser)
end if
response = request.Await()
if not response.IsSuccess()
LogError("Error marking video watch time:", response.ErrorMessage())
return false
end if
LogDebug("Marked video watch time:", timeStr)
return true
end function
function CreateClientPlaybackNonce() as string
length = 16
result = []
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
alphabetLen = alphabet.len()
for i = 1 to length
result.push(alphabet.mid(Rnd(alphabetLen - 1), 1))
end for
return result.join("")
end function
function GetChannel(channelId as string, options = invalid as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
raw = OptionUtils.GetOrDefault(options, "raw", false)
request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, options)
request.Cancellation(cancellation) request.Cancellation(cancellation)
if raw if raw
request.LogCurlCommand() request.LogCurlCommand()
@@ -367,29 +417,119 @@ namespace InnertubeService
return result return result
end function end function
function GetPlaylist(playlistId as string, options = invalid as object) as object function GetSubscriptionStatusForChannel(channelId as string, options = invalid as object) as object
continuation = "" cancellation = OptionUtils.Get(options, "cancellation")
cancellation = invalid accessToken = OptionUtils.Get(options, "accessToken")
raw = false
if options <> invalid request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Tv, options)
if options.DoesExist("continuation") request.Cancellation(cancellation)
continuation = options.continuation if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken)
end if end if
if options.DoesExist("cancellation")
cancellation = options.cancellation response = request.Await()
if not response.IsSuccess()
return {
error: response.ErrorMessage()
}
end if end if
if options.DoesExist("raw")
raw = options.raw responseData = response.Json()
error = Innertube.ParseResponseDataForError(responseData)
if error <> ""
return {
error: error
}
end if end if
channelHeaderButtons = ObjectUtils.Dig(responseData, ["contents", "tvBrowseRenderer", "content", "tvSurfaceContentRenderer", "header", "channelHeaderRenderer", "buttons"])
if not IsArray(channelHeaderButtons)
return {
error: "Node 'contents.tvBrowseRenderer.content.tvSurfaceContentRenderer.header.channelHeaderRenderer.buttons' not found"
}
end if end if
subscribeButtonRenderer = invalid
for each button in channelHeaderButtons
if not IsAssociativeArray(button) or not button.DoesExist("subscribeButtonRenderer")
continue for
end if
subscribeButtonRenderer = button.subscribeButtonRenderer
exit for
end for
if subscribeButtonRenderer = invalid
return {
error: "no 'subscribeButtonRenderer' found under 'buttons'"
}
end if
if not IsBool(subscribeButtonRenderer["subscribed"])
return {
error: "no 'subscribed' status found under 'subscribeButtonRenderer'"
}
end if
return {
success: true
isSubscribed: subscribeButtonRenderer["subscribed"]
}
end function
function SubscribeToChannel(channelId as string, options = invalid as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
accessToken = OptionUtils.Get(options, "accessToken")
request = Innertube.CreateSubscribeRequest(channelId, options)
request.Cancellation(cancellation)
if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken)
end if
response = request.Await()
return {
success: response.IsSuccess()
error: response.ErrorMessage()
}
end function
function UnsubscribeFromChannel(channelId as string, options = invalid as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
accessToken = OptionUtils.Get(options, "accessToken")
request = Innertube.CreateUnsubscribeRequest(channelId, options)
request.Cancellation(cancellation)
if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken)
end if
response = request.Await()
return {
success: response.IsSuccess()
error: response.ErrorMessage()
}
end function
function GetPlaylist(playlistId as string, options = invalid as object) as object
cancellation = OptionUtils.Get(options, "cancellation")
raw = OptionUtils.GetOrDefault(options, "raw", false)
accessToken = OptionUtils.Get(options, "accessToken")
if not playlistId.StartsWith("VL") if not playlistId.StartsWith("VL")
playlistId = "VL" + playlistId playlistId = "VL" + playlistId
end if end if
request = Innertube.CreateBrowseRequest(playlistId, Innertube.ClientType.Web, "", continuation) client = Innertube.ClientType.Web
if accessToken <> invalid
client = Innertube.ClientType.Tv
end if
request = Innertube.CreateBrowseRequest(playlistId, client, options)
request.Cancellation(cancellation) request.Cancellation(cancellation)
if accessToken <> invalid
request.Header("Authorization", "Bearer " + accessToken)
end if
if raw if raw
request.LogCurlCommand() request.LogCurlCommand()
request.NoCache() request.NoCache()
@@ -408,6 +548,10 @@ namespace InnertubeService
result = Innertube.ParsePlaylistPageResponseData(response.Json()) result = Innertube.ParsePlaylistPageResponseData(response.Json())
if result.playlistId = invalid and result.error = invalid
result["playlistId"] = playlistId
end if
cacheControl = Innertube.ParseResponseForCacheControl(response) cacheControl = Innertube.ParseResponseForCacheControl(response)
if cacheControl <> invalid if cacheControl <> invalid
result["cache-control"] = cacheControl result["cache-control"] = cacheControl
@@ -417,27 +561,15 @@ namespace InnertubeService
end function end function
function GetMix(mixId as string, options = invalid as object) as object function GetMix(mixId as string, options = invalid as object) as object
videoId = "" videoId = OptionUtils.Get(options, "videoId")
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
raw = false raw = OptionUtils.GetOrDefault(options, "raw", false)
if options <> invalid
if options.DoesExist("videoId")
videoId = options.videoId
end if
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("raw")
raw = options.raw
end if
end if
args = { "playlistId": mixId } args = { "playlistId": mixId }
if videoId <> "" if not StringUtils.IsNullOrEmpty(videoId)
args["videoId"] = videoId args["videoId"] = videoId
end if end if
request = Innertube.CreateNextRequest(args, "") request = Innertube.CreateNextRequest(args)
request.Cancellation(cancellation) request.Cancellation(cancellation)
if raw if raw
request.LogCurlCommand() request.LogCurlCommand()
@@ -455,17 +587,18 @@ namespace InnertubeService
return response.Json() return response.Json()
end if end if
return Innertube.ParseMixPageResponseData(response.Json()) result = Innertube.ParseMixPageResponseData(response.Json())
cacheControl = Innertube.ParseResponseForCacheControl(response)
if cacheControl <> invalid
result["cache-control"] = cacheControl
end if
return result
end function end function
function ResolveUrl(url as string, options = invalid as object) as object function ResolveUrl(url as string, options = invalid as object) as object
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
if options <> invalid
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
end if
request = Innertube.CreateResolveUrlRequest(url) request = Innertube.CreateResolveUrlRequest(url)
request.Cancellation(cancellation) request.Cancellation(cancellation)
@@ -506,15 +639,11 @@ namespace InnertubeService
return Innertube.PollForAccessToken(code, code, cancellation) return Innertube.PollForAccessToken(code, code, cancellation)
end function end function
function AuthRefreshAccessTokenIfNeeded(accessToken as object, cancellation = invalid as object) as boolean function AuthRefreshAccessToken(accessToken as object, cancellation = invalid as object) as boolean
if not IsAssociativeArray(accessToken) if not IsAssociativeArray(accessToken)
return false return false
end if end if
nowSeconds = TimeUtils.Now().AsSeconds()
expiresTimestamp = accessToken["expires_timestamp"]
if expiresTimestamp = invalid or expiresTimestamp < nowSeconds
refreshed = Innertube.RefreshAccessToken(accessToken, cancellation) refreshed = Innertube.RefreshAccessToken(accessToken, cancellation)
if IsAssociativeArray(refreshed) and refreshed.DoesExist("accessToken") if IsAssociativeArray(refreshed) and refreshed.DoesExist("accessToken")
@@ -524,7 +653,6 @@ namespace InnertubeService
end if end if
return true return true
end if end if
end if
return false return false
end function end function
@@ -8,21 +8,18 @@ import "pkg:/source/utils/Types.bs"
namespace Innertube namespace Innertube
function CreateNextRequest(payloadArgs as object, ctt as string) as object function CreateNextRequest(payloadArgs as object, options = invalid as object) as object
deviceInfo = CreateObject("roDeviceInfo") deviceInfo = CreateObject("roDeviceInfo")
context = Innertube.CreateContext(Innertube.ClientType.Web, deviceInfo, options)
payload = { payload = {
"context": Innertube.CreateContext(Innertube.ClientType.Web, deviceInfo, ctt, "") "context": context
} }
payload.Append(payloadArgs) payload.Append(payloadArgs)
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json", payload) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json", payload)
headers = { request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Web))
"accept": "*/*"
"accept-language": "*"
}
headers.Append(Innertube.CreateHeaders(Innertube.ClientType.Web))
request.Headers(headers)
return request return request
end function end function
@@ -42,6 +42,7 @@ namespace Innertube
function GetParsingDirectives() as object function GetParsingDirectives() as object
return { return {
"twoColumnSearchResultsRenderer": ParseTwoColumnSearchResultsRenderer "twoColumnSearchResultsRenderer": ParseTwoColumnSearchResultsRenderer
"singleColumnBrowseResultsRenderer": ParseSingleColumnBrowseResultsRenderer
"twoColumnBrowseResultsRenderer": ParseTwoColumnBrowseResultsRenderer "twoColumnBrowseResultsRenderer": ParseTwoColumnBrowseResultsRenderer
"watchNextEndScreenRenderer": ParseWatchNextEndScreenRenderer "watchNextEndScreenRenderer": ParseWatchNextEndScreenRenderer
"tabRenderer": ParseTabRenderer "tabRenderer": ParseTabRenderer
@@ -53,9 +54,11 @@ namespace Innertube
"reelShelfRenderer": ParseReelShelfRenderer "reelShelfRenderer": ParseReelShelfRenderer
"verticalListRenderer": ParseVerticalListRenderer "verticalListRenderer": ParseVerticalListRenderer
"horizontalListRenderer": ParseHorizontalListRenderer "horizontalListRenderer": ParseHorizontalListRenderer
"horizontalListContinuation": ParseHorizontalListContinuation
"expandedShelfContentsRenderer": ParseExpandedShelfContentsRenderer "expandedShelfContentsRenderer": ParseExpandedShelfContentsRenderer
"channelFeaturedContentRenderer": ParseChannelFeaturedContentRenderer "channelFeaturedContentRenderer": ParseChannelFeaturedContentRenderer
"playlistVideoListRenderer": ParsePlaylistVideoListRenderer "playlistVideoListRenderer": ParsePlaylistVideoListRenderer
"playlistVideoListContinuation": ParsePlaylistVideoListContinuation
"videoRenderer": ParseVideoRenderer "videoRenderer": ParseVideoRenderer
"gridVideoRenderer": ParseGridVideoRenderer "gridVideoRenderer": ParseGridVideoRenderer
"channelVideoPlayerRenderer": ParseChannelVideoPlayerRenderer "channelVideoPlayerRenderer": ParseChannelVideoPlayerRenderer
@@ -73,15 +76,20 @@ namespace Innertube
"tvSurfaceContentRenderer": ParseTvSurfaceContentRenderer "tvSurfaceContentRenderer": ParseTvSurfaceContentRenderer
"tvSecondaryNavRenderer": ParseTvSecondaryNavRenderer "tvSecondaryNavRenderer": ParseTvSecondaryNavRenderer
"tvSecondaryNavSectionRenderer": ParseTvSecondaryNavSectionRenderer "tvSecondaryNavSectionRenderer": ParseTvSecondaryNavSectionRenderer
"twoColumnRenderer": ParseTwoColumnRenderer
"tileRenderer": ParseTileRenderer "tileRenderer": ParseTileRenderer
"gridRenderer": ParseGridRenderer "gridRenderer": ParseGridRenderer
"richGridRenderer": ParseRichGridRenderer "richGridRenderer": ParseRichGridRenderer
"richItemRenderer": ParseRichItemRenderer "richItemRenderer": ParseRichItemRenderer
"feedFilterChipBarRenderer": ParseFeedFilterChipBarRenderer
"continuationItemRenderer": ParseContinuationItemRenderer "continuationItemRenderer": ParseContinuationItemRenderer
"appendContinuationItemsAction": ParseAppendContinuationItemsAction "appendContinuationItemsAction": ParseAppendContinuationItemsAction
"reloadContinuationItemsCommand": ParseReloadContinuationItemsCommand
"gridContinuation": ParseGridContinuation "gridContinuation": ParseGridContinuation
"tvSurfaceContentContinuation": ParseTvSurfaceContentContinuation "tvSurfaceContentContinuation": ParseTvSurfaceContentContinuation
' Ignored nodes: ' Ignored nodes:
' A playlist at the end of a video. We don't need that for now.
"endScreenPlaylistRenderer": ParseNotImplemented
' Posts not yet supported ' Posts not yet supported
"postRenderer": ParseNotImplemented "postRenderer": ParseNotImplemented
' a "View all posts" button ' a "View all posts" button
@@ -96,8 +104,19 @@ namespace Innertube
"officialCardViewModel": ParseNotImplemented "officialCardViewModel": ParseNotImplemented
' Usually contains a "X unavailable video(s) are hidden" message. Ignored. ' Usually contains a "X unavailable video(s) are hidden" message. Ignored.
"messageRenderer": ParseNotImplemented "messageRenderer": ParseNotImplemented
' Messages like "Videos you watch will be saved here"
"genericPromoRenderer": ParseNotImplemented
' "Sign in to see the latest videos tailored to your interests"
"feedNudgeRenderer": ParseNotImplemented
' "No results found, Try different keywords or remove search filters"
"backgroundPromoRenderer": ParseNotImplemented
"videoSurveyShelfRenderer": ParseNotImplemented
"searchBarRenderer": ParseNotImplemented
"clickTrackingParams": ParseNotImplemented "clickTrackingParams": ParseNotImplemented
"promoShelfRenderer": ParseNotImplemented "promoShelfRenderer": ParseNotImplemented
"statementBannerRenderer": ParseNotImplemented
"adSlotRenderer": ParseNotImplemented
"adsControlFlowOpportunityReceivedCommand": ParseNotImplemented
} }
end function end function
@@ -105,6 +124,10 @@ namespace Innertube
return nodeData["primaryContents"] return nodeData["primaryContents"]
end function end function
function ParseSingleColumnBrowseResultsRenderer(nodeData as object, _context as object) as object
return nodeData["tabs"]
end function
function ParseTwoColumnBrowseResultsRenderer(nodeData as object, _context as object) as object function ParseTwoColumnBrowseResultsRenderer(nodeData as object, _context as object) as object
return nodeData["tabs"] return nodeData["tabs"]
end function end function
@@ -123,7 +146,26 @@ namespace Innertube
return nodeData["content"] return nodeData["content"]
end function end function
function ParseSectionListRenderer(nodeData as object, _context as object) as object function ParseSectionListRenderer(nodeData as object, context as object) as object
sortSubMenuItems = ObjectUtils.Dig(nodeData, ["subMenu", "channelSubMenuRenderer", "sortSetting", "sortFilterSubMenuRenderer", "subMenuItems"])
if IsArray(sortSubMenuItems)
sortOptions = []
for each item in sortSubMenuItems
params = ValidString(ObjectUtils.Dig(item, ["navigationEndpoint", "browseEndpoint", "params"]))
title = ParseText(item["title"])
isSelected = ValidBool(item["selected"])
if params <> "" and title <> ""
sortOptions.Push({
"title": title
"params": params
"isSelected": isSelected
})
end if
end for
if sortOptions.Count() > 0
context.currentFeed.sortOptions = sortOptions
end if
end if
return nodeData["contents"] return nodeData["contents"]
end function end function
@@ -136,13 +178,13 @@ namespace Innertube
end function end function
function ParseShelfRenderer(nodeData as object, context as object) as object function ParseShelfRenderer(nodeData as object, context as object) as object
if context.skipCreatorOnTheRise = true if context.disableCreatorOnTheRise = true
badges = nodeData["badges"] badges = nodeData["badges"]
if IsArray(badges) if IsArray(badges)
for each badge in badges for each badge in badges
if ValidString(ObjectUtils.Dig(badge, ["metadataBadgeRenderer", "style"])) = "BADGE_STYLE_TYPE_FEATURED" if ValidString(ObjectUtils.Dig(badge, ["metadataBadgeRenderer", "style"])) = "BADGE_STYLE_TYPE_FEATURED"
label = ParseText(ObjectUtils.Dig(badge, ["metadataBadgeRenderer", "label"])) label = ParseText(ObjectUtils.Dig(badge, ["metadataBadgeRenderer", "label"]))
LogInfo(`Skipping 'Create on the Rise' shelf (${label})`) LogInfo(`Skipping 'Creator on the Rise' shelf (${label})`)
return invalid return invalid
end if end if
end for end for
@@ -159,7 +201,11 @@ namespace Innertube
return nodeData["contents"] return nodeData["contents"]
end function end function
function ParseReelShelfRenderer(nodeData as object, _context as object) as object function ParseReelShelfRenderer(nodeData as object, context as object) as object
if context.disableShorts = true
LogInfo("Skipping ReelShelfRenderer based on user settings")
return invalid
end if
' TODO: handle reelShelfRenderer.title ' TODO: handle reelShelfRenderer.title
return nodeData["items"] return nodeData["items"]
end function end function
@@ -168,8 +214,25 @@ namespace Innertube
return nodeData["items"] return nodeData["items"]
end function end function
function ParseHorizontalListRenderer(nodeData as object, _context as object) as object function ParseHorizontalListRenderer(nodeData as object, context as object) as object
' TODO: handle continuations continuation = ObjectUtils.Dig(nodeData, ["continuations", 0, "nextContinuationData", "continuation"])
if IsString(continuation)
if not StringUtils.IsNullOrEmpty(context.currentFeed.continuation)
StartNewFeed("", context)
end if
context.currentFeed.continuation = continuation
end if
return nodeData["items"]
end function
function ParseHorizontalListContinuation(nodeData as object, context as object) as object
continuation = ObjectUtils.Dig(nodeData, ["continuations", 0, "nextContinuationData", "continuation"])
if IsString(continuation)
if not StringUtils.IsNullOrEmpty(context.currentFeed.continuation)
StartNewFeed("", context)
end if
context.currentFeed.continuation = continuation
end if
return nodeData["items"] return nodeData["items"]
end function end function
@@ -181,7 +244,19 @@ namespace Innertube
return nodeData["items"] return nodeData["items"]
end function end function
function ParsePlaylistVideoListRenderer(nodeData as object, _context as object) as object function ParsePlaylistVideoListRenderer(nodeData as object, context as object) as object
continuation = ObjectUtils.Dig(nodeData, ["continuations", 0, "nextContinuationData", "continuation"])
if IsString(continuation)
context.currentFeed.continuation = continuation
end if
return nodeData["contents"]
end function
function ParsePlaylistVideoListContinuation(nodeData as object, context as object) as object
continuation = ObjectUtils.Dig(nodeData, ["continuations", 0, "nextContinuationData", "continuation"])
if IsString(continuation)
context.currentFeed.continuation = continuation
end if
return nodeData["contents"] return nodeData["contents"]
end function end function
@@ -227,20 +302,31 @@ namespace Innertube
end if end if
end if end if
liveNow = ValidString(ObjectUtils.Dig(nodeData, ["badges", 0, "metadataBadgeRenderer", "icon", "iconType"])) = "LIVE" isUpcoming = false
if not liveNow liveNow = false
thumbnailOverlays = nodeData["thumbnailOverlays"] thumbnailOverlays = nodeData["thumbnailOverlays"]
if IsArray(thumbnailOverlays) if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays for each overlay in thumbnailOverlays
if ValidString(ObjectUtils.Dig(overlay, ["thumbnailOverlayTimeStatusRenderer", "style"])) = "LIVE" parsedTimeStatusRenderer = ParseThumbnailOverlayTimeStatusRenderer(overlay)
liveNow = true if parsedTimeStatusRenderer <> invalid
exit for if parsedTimeStatusRenderer.isShort
end if if context.disableShorts = true
end for LogInfo("Skipping Short based on user settings")
return invalid
end if end if
end if end if
isUpcoming = false liveNow = liveNow or parsedTimeStatusRenderer.isLive
isUpcoming = isUpcoming or parsedTimeStatusRenderer.isUpcoming
end if
end for
end if
if ValidString(ObjectUtils.Dig(nodeData, ["badges", 0, "metadataBadgeRenderer", "icon", "iconType"])) = "LIVE"
liveNow = true
end if
premiereTimestamp = ObjectUtils.Dig(nodeData, ["upcomingEventData", "startTime"]) premiereTimestamp = ObjectUtils.Dig(nodeData, ["upcomingEventData", "startTime"])
if IsString(premiereTimestamp) if IsString(premiereTimestamp)
premiereTimestamp = premiereTimestamp.ToInt() premiereTimestamp = premiereTimestamp.ToInt()
@@ -313,10 +399,13 @@ namespace Innertube
thumbnailOverlays = nodeData["thumbnailOverlays"] thumbnailOverlays = nodeData["thumbnailOverlays"]
if IsArray(thumbnailOverlays) if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays for each overlay in thumbnailOverlays
lengthText = ParseText(ObjectUtils.Dig(overlay, ["thumbnailOverlayTimeStatusRenderer", "text"])) parsedTimeStatusRenderer = ParseThumbnailOverlayTimeStatusRenderer(overlay)
if parsedTimeStatusRenderer <> invalid
lengthText = parsedTimeStatusRenderer.text
if lengthText <> "" if lengthText <> ""
exit for exit for
end if end if
end if
end for end for
end if end if
end if end if
@@ -396,6 +485,7 @@ namespace Innertube
lengthText = ParseText(nodeData["lengthText"]) lengthText = ParseText(nodeData["lengthText"])
lengthSeconds = ValidString(nodeData["lengthSeconds"]).ToInt() lengthSeconds = ValidString(nodeData["lengthSeconds"]).ToInt()
videoInfo = ParseText(nodeData["videoInfo"])
author = invalid author = invalid
authorId = invalid authorId = invalid
@@ -428,6 +518,7 @@ namespace Innertube
"index": ParseText(nodeData["index"]).ToInt() "index": ParseText(nodeData["index"]).ToInt()
"lengthText": lengthText "lengthText": lengthText
"lengthSeconds": lengthSeconds "lengthSeconds": lengthSeconds
"videoInfo": videoInfo
} }
PushFeedItem(video, context) PushFeedItem(video, context)
@@ -467,8 +558,18 @@ namespace Innertube
thumbnailOverlays = nodeData["thumbnailOverlays"] thumbnailOverlays = nodeData["thumbnailOverlays"]
if IsArray(thumbnailOverlays) if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays for each overlay in thumbnailOverlays
liveNow = liveNow or (ValidString(ObjectUtils.Dig(overlay, ["thumbnailOverlayTimeStatusRenderer", "style"])) = "LIVE") parsedTimeStatusRenderer = ParseThumbnailOverlayTimeStatusRenderer(overlay)
isUpcoming = isUpcoming or (ValidString(ObjectUtils.Dig(overlay, ["thumbnailOverlayTimeStatusRenderer", "style"])) = "UPCOMING") if parsedTimeStatusRenderer <> invalid
if parsedTimeStatusRenderer.isShort
if context.disableShorts = true
LogInfo("Skipping Short based on user settings")
return invalid
end if
end if
liveNow = liveNow or parsedTimeStatusRenderer.isLive
isUpcoming = isUpcoming or parsedTimeStatusRenderer.isUpcoming
end if
end for end for
end if end if
@@ -818,6 +919,11 @@ namespace Innertube
end function end function
function ParseShortsLockupViewModel(nodeData as object, context as object) as object function ParseShortsLockupViewModel(nodeData as object, context as object) as object
if context.disableShorts = true
LogInfo("Skipping Short based on user settings")
return invalid
end if
videoId = ObjectUtils.Dig(nodeData, ["onTap", "innertubeCommand", "reelWatchEndpoint", "videoId"]) videoId = ObjectUtils.Dig(nodeData, ["onTap", "innertubeCommand", "reelWatchEndpoint", "videoId"])
if not IsString(videoId) if not IsString(videoId)
LogWarn("Invalid video ID", nodeData) LogWarn("Invalid video ID", nodeData)
@@ -871,10 +977,26 @@ namespace Innertube
return nodeData["tabs"] return nodeData["tabs"]
end function end function
function ParseTwoColumnRenderer(nodeData as object, _context as object) as object
' twoColumnRenderer is used for Playlists on TV.
' The right column has the videos (and continuation)
' The left column has the playlist info (title, description, etc) which was already parsed
return nodeData["rightColumn"]
end function
function ParseTileRenderer(nodeData as object, context as object) as object function ParseTileRenderer(nodeData as object, context as object) as object
contentType = ValidString(nodeData["contentType"]) contentType = ValidString(nodeData["contentType"])
' A tileRenderer can be without a contentType, such as a
' button that says "Open YouTube Kids" or similar CTAs
if contentType = ""
LogWarn(`TileRenderer without contentType:\n`, nodeData)
return invalid
end if
if contentType = "TILE_CONTENT_TYPE_VIDEO" if contentType = "TILE_CONTENT_TYPE_VIDEO"
return TileRendererTypeVideo(nodeData, context) return TileRendererTypeVideo(nodeData, context)
else if contentType = "TILE_CONTENT_TYPE_SHORTS"
return TileRendererTypeShorts(nodeData, context)
else if contentType = "TILE_CONTENT_TYPE_PLAYLIST" else if contentType = "TILE_CONTENT_TYPE_PLAYLIST"
return TileRendererTypePlaylist(nodeData, context) return TileRendererTypePlaylist(nodeData, context)
end if end if
@@ -907,21 +1029,50 @@ namespace Innertube
lengthText = "" lengthText = ""
isUpcoming = false isUpcoming = false
liveNow = false liveNow = false
percentDurationWatched = 0
thumbnailOverlays = ObjectUtils.Dig(nodeData, ["header", "tileHeaderRenderer", "thumbnailOverlays"]) thumbnailOverlays = ObjectUtils.Dig(nodeData, ["header", "tileHeaderRenderer", "thumbnailOverlays"])
if IsArray(thumbnailOverlays) if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays for each overlay in thumbnailOverlays
maybeLengthText = ParseText(ObjectUtils.Dig(overlay, ["thumbnailOverlayTimeStatusRenderer", "text"])) parsedTimeStatusRenderer = ParseThumbnailOverlayTimeStatusRenderer(overlay)
if parsedTimeStatusRenderer <> invalid
if parsedTimeStatusRenderer.isShort
if context.disableShorts = true
LogInfo("Skipping Short based on user settings")
return invalid
end if
end if
maybeLengthText = parsedTimeStatusRenderer.text
if maybeLengthText <> "" if maybeLengthText <> ""
lengthText = maybeLengthText lengthText = maybeLengthText
end if end if
liveNow = liveNow or (ValidString(ObjectUtils.Dig(overlay, ["thumbnailOverlayTimeStatusRenderer", "style"])) = "LIVE")
isUpcoming = isUpcoming or (ValidString(ObjectUtils.Dig(overlay, ["thumbnailOverlayTimeStatusRenderer", "style"])) = "UPCOMING") liveNow = liveNow or parsedTimeStatusRenderer.isLive
isUpcoming = isUpcoming or parsedTimeStatusRenderer.isUpcoming
end if
maybePercentDurationWatched = ObjectUtils.Dig(overlay, ["thumbnailOverlayResumePlaybackRenderer", "percentDurationWatched"])
if maybePercentDurationWatched <> invalid
percentDurationWatched = maybePercentDurationWatched
end if
end for end for
if liveNow or isUpcoming if liveNow or isUpcoming
lengthText = "" lengthText = ""
end if end if
end if end if
renderedLines = []
lines = ObjectUtils.Dig(nodeData, ["metadata", "tileMetadataRenderer", "lines"])
if IsArray(lines)
for each line in lines
if not IsAssociativeArray(line)
continue for
end if
renderedLines.Push(ParseLineRenderer(line["lineRenderer"]))
end for
end if
video = { video = {
"type": "video" "type": "video"
"videoId": videoId "videoId": videoId
@@ -930,8 +1081,63 @@ namespace Innertube
"lengthText": lengthText "lengthText": lengthText
"liveNow": liveNow "liveNow": liveNow
"isUpcoming": isUpcoming "isUpcoming": isUpcoming
"lines": renderedLines
"percentDurationWatched": percentDurationWatched
} }
authorId = ParseTileRendererAuthorId(nodeData)
if authorId <> invalid
video["authorId"] = authorId
end if
PushFeedItem(video, context)
return invalid
end function
function TileRendererTypeShorts(nodeData as object, context as object) as object
if context.disableShorts = true
LogInfo("Skipping Short based on user settings")
return invalid
end if
videoId = nodeData["contentId"]
if not IsString(videoId)
LogWarn("Invalid video ID", nodeData)
return invalid
end if
if context.generateVideoThumbnails = true
videoThumbnails = GenerateVideoThumbnails(videoId)
else
videoThumbnails = ObjectUtils.Dig(nodeData, ["header", "tileHeaderRenderer", "thumbnail", "thumbnails"])
if videoThumbnails = invalid
videoThumbnails = GenerateVideoThumbnails(videoId)
end if
end if
title = ""
thumbnailOverlays = ObjectUtils.Dig(nodeData, ["header", "tileHeaderRenderer", "thumbnailOverlays"])
if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays
title = ParseText(ObjectUtils.Dig(overlay, ["tileMetadataRenderer", "title"]))
if title <> ""
exit for
end if
end for
end if
video = {
"type": "video"
"videoId": videoId
"title": title
"videoThumbnails": videoThumbnails
}
authorId = ParseTileRendererAuthorId(nodeData)
if authorId <> invalid
video["authorId"] = authorId
end if
PushFeedItem(video, context) PushFeedItem(video, context)
return invalid return invalid
end function end function
@@ -954,18 +1160,57 @@ namespace Innertube
end for end for
end if end if
renderedLines = []
lines = ObjectUtils.Dig(nodeData, ["metadata", "tileMetadataRenderer", "lines"])
if IsArray(lines)
for each line in lines
if not IsAssociativeArray(line)
continue for
end if
renderedLines.Push(ParseLineRenderer(line["lineRenderer"]))
end for
end if
playlist = { playlist = {
"type": "playlist" "type": "playlist"
"playlistId": playlistId "playlistId": playlistId
"title": ParseText(ObjectUtils.Dig(nodeData, ["metadata", "tileMetadataRenderer", "title"])) "title": ParseText(ObjectUtils.Dig(nodeData, ["metadata", "tileMetadataRenderer", "title"]))
"playlistThumbnail": ObjectUtils.Dig(nodeData, ["header", "tileHeaderRenderer", "thumbnail", "thumbnails", 0, "url"]) "playlistThumbnail": ObjectUtils.Dig(nodeData, ["header", "tileHeaderRenderer", "thumbnail", "thumbnails", 0, "url"])
"videoCountText": videoCountText "videoCountText": videoCountText
"lines": renderedLines
} }
authorId = ParseTileRendererAuthorId(nodeData)
if authorId <> invalid
playlist["authorId"] = authorId
end if
PushFeedItem(playlist, context) PushFeedItem(playlist, context)
return invalid return invalid
end function end function
function ParseTileRendererAuthorId(nodeData as object) as dynamic
' We're checking in the long press menu if there's a browseId that starts with "UC".
' This is usually the the id of the channel.
menuItems = ObjectUtils.Dig(nodeData, ["onLongPressCommand", "showMenuCommand", "menu", "menuRenderer", "items"])
if not IsArray(menuItems)
return invalid
end if
for each item in menuItems
if not IsAssociativeArray(item) or not item.DoesExist("menuNavigationItemRenderer")
continue for
end if
menuNavigationItemRenderer = item["menuNavigationItemRenderer"]
browseId = ObjectUtils.Dig(menuNavigationItemRenderer, ["navigationEndpoint", "browseEndpoint", "browseId"])
if not IsString(browseId) or not browseId.StartsWith("UC")
continue for
end if
return browseId
end for
return invalid
end function
function ParseGridRenderer(nodeData as object, context as object) as object function ParseGridRenderer(nodeData as object, context as object) as object
continuation = ObjectUtils.Dig(nodeData, ["continuations", 0, "nextContinuationData", "continuation"]) continuation = ObjectUtils.Dig(nodeData, ["continuations", 0, "nextContinuationData", "continuation"])
if IsString(continuation) if IsString(continuation)
@@ -974,7 +1219,11 @@ namespace Innertube
return nodeData["items"] return nodeData["items"]
end function end function
function ParseRichGridRenderer(nodeData as object, _context as object) as object function ParseRichGridRenderer(nodeData as object, context as object) as object
feedFilterChipBarRenderer = ObjectUtils.Dig(nodeData, ["header", "feedFilterChipBarRenderer"])
if feedFilterChipBarRenderer <> invalid
ParseFeedFilterChipBarRenderer(feedFilterChipBarRenderer, context)
end if
return nodeData["contents"] return nodeData["contents"]
end function end function
@@ -982,6 +1231,47 @@ namespace Innertube
return nodeData["content"] return nodeData["content"]
end function end function
function ParseFeedFilterChipBarRenderer(nodeData as object, context as object) as object
contents = ObjectUtils.Dig(nodeData, ["contents"])
if not IsArray(contents)
return invalid
end if
sortOptions = []
for each item in contents
if not IsAssociativeArray(item) or not item.DoesExist("chipCloudChipRenderer")
continue for
end if
chipCloudChipRenderer = item["chipCloudChipRenderer"]
if not IsAssociativeArray(chipCloudChipRenderer)
continue for
end if
continuationCommand = ObjectUtils.Dig(chipCloudChipRenderer, ["navigationEndpoint", "continuationCommand"])
if not IsAssociativeArray(continuationCommand) or ValidString(continuationCommand["request"]) <> "CONTINUATION_REQUEST_TYPE_BROWSE"
continue for
end if
title = ParseText(chipCloudChipRenderer["text"])
token = ValidString(continuationCommand["token"])
isSelected = ValidBool(chipCloudChipRenderer["isSelected"])
if title = "" or token = ""
continue for
end if
sortOptions.Push({
"title": title
"continuation": token
"isSelected": isSelected
})
end for
if sortOptions.Count() > 0
context.currentFeed.sortOptions = sortOptions
end if
return invalid
end function
function ParseContinuationItemRenderer(nodeData as object, context as object) as object function ParseContinuationItemRenderer(nodeData as object, context as object) as object
continuation = ObjectUtils.Dig(nodeData, ["continuationEndpoint", "continuationCommand", "token"]) continuation = ObjectUtils.Dig(nodeData, ["continuationEndpoint", "continuationCommand", "token"])
if IsString(continuation) if IsString(continuation)
@@ -998,6 +1288,10 @@ namespace Innertube
return nodeData["continuationItems"] return nodeData["continuationItems"]
end function end function
function ParseReloadContinuationItemsCommand(nodeData as object, _context as object) as object
return nodeData["continuationItems"]
end function
function ParseGridContinuation(nodeData as object, context as object) as object function ParseGridContinuation(nodeData as object, context as object) as object
continuation = ObjectUtils.Dig(nodeData, ["continuations", 0, "nextContinuationData", "continuation"]) continuation = ObjectUtils.Dig(nodeData, ["continuations", 0, "nextContinuationData", "continuation"])
if IsString(continuation) if IsString(continuation)
@@ -1031,6 +1325,72 @@ namespace Innertube
return "" return ""
end function end function
function ParseLineRenderer(data as object) as string
if data = invalid
return ""
end if
if IsString(data)
return data
end if
if not IsAssociativeArray(data) or not data.DoesExist("items")
return ""
end if
items = data["items"]
if not IsArray(items)
return ""
end if
texts = []
for each item in items
if IsString(item)
texts.Push(item)
else if IsAssociativeArray(item) and item.DoesExist("lineItemRenderer")
texts.Push(ParseLineItemRenderer(item["lineItemRenderer"]))
end if
end for
return texts.Join(" ")
end function
function ParseLineItemRenderer(data as object) as string
if data = invalid
return ""
end if
if IsString(data)
return data
end if
if not IsAssociativeArray(data) or not data.DoesExist("text")
return ""
end if
return ParseText(data["text"])
end function
function ParseThumbnailOverlayTimeStatusRenderer(data as object) as object
if data = invalid
return invalid
end if
if not IsAssociativeArray(data) or not data.DoesExist("thumbnailOverlayTimeStatusRenderer")
return invalid
end if
renderer = data["thumbnailOverlayTimeStatusRenderer"]
if not IsAssociativeArray(renderer)
return invalid
end if
text = ParseText(renderer["text"])
overlayStyle = ValidString(renderer["style"])
isLive = overlayStyle = "LIVE"
isUpcoming = overlayStyle = "UPCOMING"
isShort = overlayStyle = "SHORTS"
return {
"text": text
"isLive": isLive
"isUpcoming": isUpcoming
"isShort": isShort
}
end function
function StartNewFeed(title as string, context as object) as void function StartNewFeed(title as string, context as object) as void
if context.currentFeed <> invalid if context.currentFeed <> invalid
if context.currentFeed.items.Count() = 0 and context.currentFeed.title = "" if context.currentFeed.items.Count() = 0 and context.currentFeed.title = ""
@@ -7,7 +7,7 @@ namespace Innertube
function GetClientIdentity(cancellation = invalid as dynamic) as object function GetClientIdentity(cancellation = invalid as dynamic) as object
request = HttpClient.Get("https://www.youtube.com/tv") request = HttpClient.Get("https://www.youtube.com/tv")
request.Headers({ request.Headers({
"User-Agent": "Mozilla/5.0 (ChromiumStylePlatform) Cobalt/Version" "User-Agent": INNERTUBE_TV_USER_AGENT
"Referer": "https://www.youtube.com/tv" "Referer": "https://www.youtube.com/tv"
"Accept-Language": "en-US" "Accept-Language": "en-US"
}) })
@@ -196,7 +196,7 @@ namespace Innertube
deviceInfo = CreateObject("roDeviceInfo") deviceInfo = CreateObject("roDeviceInfo")
payload = { payload = {
"context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, "", "") "context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo)
"accountReadMask": { "accountReadMask": {
"returnOwner": true "returnOwner": true
"returnBrandAccounts": true "returnBrandAccounts": true
@@ -243,6 +243,7 @@ namespace Innertube
"hasChannel": ValidBool(accountItem["hasChannel"]) "hasChannel": ValidBool(accountItem["hasChannel"])
"accountByline": ParseText(accountItem["accountByline"]) "accountByline": ParseText(accountItem["accountByline"])
"channelHandle": ParseText(accountItem["channelHandle"]) "channelHandle": ParseText(accountItem["channelHandle"])
"activeIdentifyToken": ParseAccountItemIdentityToken(accountItem)
} }
parsedAccounts.Push(parsedAccount) parsedAccounts.Push(parsedAccount)
end for end for
@@ -250,6 +251,48 @@ namespace Innertube
return parsedAccounts return parsedAccounts
end function end function
function ParseAccountItemIdentityToken(accountItem as object) as string
' Although selected (default) account would have a token, we usually don't
' need it, since we don't need to pass the "onBehalfOfUser" argument
' when using selected account.
if ValidBool(accountItem.isSelected)
return ""
end if
supportedTokens = ObjectUtils.Dig(accountItem, ["serviceEndpoint", "selectActiveIdentityEndpoint", "supportedTokens"])
if not IsArray(supportedTokens) or supportedTokens.Count() = 0
return ""
end if
for each supportedToken in supportedTokens
if not IsAssociativeArray(supportedToken)
continue for
end if
' TODO:P2 should we stick with pageId, and ignore the rest?
pageId = ObjectUtils.Dig(supportedToken, ["pageIdToken", "pageId"])
if not StringUtils.IsNullOrEmpty(pageId)
return pageId
end if
obfuscatedGaiaId = ObjectUtils.Dig(supportedToken, ["accountStateToken", "obfuscatedGaiaId"])
if not StringUtils.IsNullOrEmpty(obfuscatedGaiaId)
return obfuscatedGaiaId
end if
datasyncIdToken = ObjectUtils.Dig(supportedToken, ["datasyncIdToken", "datasyncIdToken"])
if not StringUtils.IsNullOrEmpty(datasyncIdToken)
' "datasyncIdToken": "123456789012345678901||123456789012345678901"
match = /(\d+)\|\|(\d+)/.match(datasyncIdToken)
if match.Count() = 3
return match[1]
end if
end if
end for
return ""
end function
function ToCamelCase(obj as object) as object function ToCamelCase(obj as object) as object
if not IsAssociativeArray(obj) if not IsAssociativeArray(obj)
return obj return obj
@@ -10,9 +10,7 @@ namespace Innertube
return [] return []
end if end if
if context = invalid context = ValidAssociativeArray(context)
context = {}
end if
if not ValidBool(context.noContainers) if not ValidBool(context.noContainers)
containers = GetContainers(responseData) containers = GetContainers(responseData)
@@ -143,12 +141,16 @@ namespace Innertube
items = [] items = []
continuation = invalid continuation = invalid
sortOptions = invalid
feeds = ParseResponseDataForFeeds(responseData, { "currentAuthor": author, "currentAuthorId": authorId }) feeds = ParseResponseDataForFeeds(responseData, { "currentAuthor": author, "currentAuthorId": authorId })
if feeds.Count() > 0 if feeds.Count() > 0
items = ValidArray(feeds[0].items) items = ValidArray(feeds[0].items)
if feeds[0].DoesExist("continuation") if feeds[0].DoesExist("continuation")
continuation = feeds[0].continuation continuation = feeds[0].continuation
end if end if
if feeds[0].DoesExist("sortOptions")
sortOptions = feeds[0].sortOptions
end if
end if end if
channel = { channel = {
@@ -163,9 +165,13 @@ namespace Innertube
"items": items "items": items
} }
' continuation and sort options are specific to certain tabs of the channel
if continuation <> invalid if continuation <> invalid
channel["continuation"] = continuation channel["continuation"] = continuation
end if end if
if sortOptions <> invalid
channel["sortOptions"] = sortOptions
end if
return channel return channel
end function end function
@@ -184,8 +190,17 @@ namespace Innertube
} }
end if end if
playlistSidebarRendererItems = ObjectUtils.Dig(responseData, ["sidebar", "playlistSidebarRenderer", "items"]) playlistId = invalid
title = invalid
author = invalid
authorId = invalid
description = invalid
videoCount = -1
thumbnail = invalid
statsText = invalid
playlistSidebarRendererItems = ObjectUtils.Dig(responseData, ["sidebar", "playlistSidebarRenderer", "items"])
if playlistSidebarRendererItems <> invalid
primaryInfo = ObjectUtils.Dig(playlistSidebarRendererItems, [0, "playlistSidebarPrimaryInfoRenderer"]) primaryInfo = ObjectUtils.Dig(playlistSidebarRendererItems, [0, "playlistSidebarPrimaryInfoRenderer"])
secondaryInfo = ObjectUtils.Dig(playlistSidebarRendererItems, [1, "playlistSidebarSecondaryInfoRenderer"]) secondaryInfo = ObjectUtils.Dig(playlistSidebarRendererItems, [1, "playlistSidebarSecondaryInfoRenderer"])
@@ -197,8 +212,6 @@ namespace Innertube
author = ParseText(ObjectUtils.Dig(secondaryInfo, ["videoOwner", "videoOwnerRenderer", "title"])) author = ParseText(ObjectUtils.Dig(secondaryInfo, ["videoOwner", "videoOwnerRenderer", "title"]))
authorId = ObjectUtils.Dig(secondaryInfo, ["videoOwner", "videoOwnerRenderer", "navigationEndpoint", "browseEndpoint", "browseId"]) authorId = ObjectUtils.Dig(secondaryInfo, ["videoOwner", "videoOwnerRenderer", "navigationEndpoint", "browseEndpoint", "browseId"])
statsText = ""
stats = ObjectUtils.Dig(primaryInfo, ["stats"]) stats = ObjectUtils.Dig(primaryInfo, ["stats"])
if IsArray(stats) if IsArray(stats)
statsTexts = [] statsTexts = []
@@ -210,18 +223,52 @@ namespace Innertube
end for end for
statsText = statsTexts.Join(" • ") statsText = statsTexts.Join(" • ")
end if end if
end if
twoColumnRenderer = ObjectUtils.Dig(responseData, ["contents", "tvBrowseRenderer", "content", "tvSurfaceContentRenderer", "content", "twoColumnRenderer"])
if twoColumnRenderer <> invalid
entityMetadataRenderer = ObjectUtils.Dig(twoColumnRenderer, ["leftColumn", "entityMetadataRenderer"])
if entityMetadataRenderer <> invalid
if title = invalid
title = ParseText(entityMetadataRenderer["title"])
end if
if statsText = invalid
statsText = ParseLineRenderer(ObjectUtils.Dig(entityMetadataRenderer, ["bylines", 0, "lineRenderer"]))
end if
if description = invalid
description = ParseText(entityMetadataRenderer["description"])
end if
if playlistId = invalid
playlistId = ObjectUtils.Dig(twoColumnRenderer, ["rightColumn", "playlistVideoListRenderer", "playlistId"])
end if
end if
end if
playlist = { playlist = {
"playlistId": playlistId
"title": title
"author": author
"authorId": authorId
"description": description
"videoCount": videoCount "videoCount": videoCount
"thumbnail": thumbnail
"videos": [] "videos": []
"statsText": statsText
} }
if playlistId <> invalid
playlist["playlistId"] = playlistId
end if
if title <> invalid
playlist["title"] = title
end if
if author <> invalid
playlist["author"] = author
end if
if authorId <> invalid
playlist["authorId"] = authorId
end if
if description <> invalid
playlist["description"] = description
end if
if thumbnail <> invalid
playlist["thumbnail"] = thumbnail
end if
if statsText <> invalid
playlist["statsText"] = statsText
end if
feeds = ParseResponseDataForFeeds(responseData) feeds = ParseResponseDataForFeeds(responseData)
if feeds.Count() > 0 if feeds.Count() > 0
@@ -231,6 +278,10 @@ namespace Innertube
end if end if
end if end if
if playlist["thumbnail"] = invalid and playlist["videos"].Count() > 0
playlist["thumbnail"] = ObjectUtils.Dig(playlist, ["videos", 0, "thumbnails", 0, "url"])
end if
return playlist return playlist
end function end function
@@ -288,16 +339,37 @@ namespace Innertube
end function end function
function ParseResponseDataForError(responseData as object) as string function ParseResponseDataForError(responseData as object) as string
error = ""
if responseData = invalid if responseData = invalid
return "" return error
end if end if
alert = ObjectUtils.Dig(responseData, ["alerts", 0, "alertRenderer"]) alerts = responseData["alerts"]
if IsAssociativeArray(alert) and alert.type = "ERROR" if not IsArray(alerts) or alerts.Count() = 0
return ParseText(alert.text) return error
end if end if
return "" for each alert in alerts
if not IsAssociativeArray(alert)
continue for
end if
alertRenderer = alert["alertRenderer"]
if alertRenderer = invalid
alertRenderer = alert["alertWithButtonRenderer"]
end if
if not IsAssociativeArray(alertRenderer)
continue for
end if
alertText = ParseText(alertRenderer.text)
LogWarn("Innertube Alert:", `[${alertRenderer.type}]`, alertText)
if alertRenderer.type = "ERROR"
error += alertText
end if
end for
return error
end function end function
function ParseResponseForCacheControl(response as object) as dynamic function ParseResponseForCacheControl(response as object) as dynamic
@@ -6,12 +6,16 @@ import "pkg:/source/utils/Types.bs"
namespace Innertube namespace Innertube
function CreatePlayerRequest(videoId as string, ctt as string, visitorData as string) as object function CreatePlayerRequest(videoId as string, client as Innertube.ClientType, options = invalid as object) as object
visitorData = OptionUtils.Get(options, "visitorData")
deviceInfo = CreateObject("roDeviceInfo") deviceInfo = CreateObject("roDeviceInfo")
context = Innertube.CreateContext(client, deviceInfo, options)
payload = { payload = {
"videoId": videoId "videoId": videoId
"context": Innertube.CreateContext(Innertube.ClientType.IOS, deviceInfo, ctt, visitorData) "context": context
"playbackContext": { "playbackContext": {
"contentPlaybackContext": { "contentPlaybackContext": {
"vis": 0 "vis": 0
@@ -32,48 +36,19 @@ namespace Innertube
} }
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload)
headers = { request.Headers(Innertube.CreateHeaders(client))
"accept": "*/*" if not StringUtils.IsNullOrEmpty(visitorData)
"accept-language": "*" request.Header("x-goog-visitor-id", visitorData)
} end if
headers.Append(Innertube.CreateHeaders(Innertube.ClientType.IOS))
request.Headers(headers)
return request return request
end function end function
function ParseInnertubePlayerResponse(payload as object) as object function ParseInnertubePlayerResponse(payload as object) as object
if not IsAssociativeArray(payload) error = ParsePlayerResponseForError(payload)
if error <> ""
return { return {
error: "Invalid payload" error: error
}
end if
playabilityStatus = payload["playabilityStatus"]
if not IsAssociativeArray(playabilityStatus)
return {
error: "Invalid playability status"
}
end if
if playabilityStatus["status"] <> "OK"
errorMessage = ""
if IsString(playabilityStatus["reason"])
errorMessage = playabilityStatus["reason"]
end if
subreason = ParseText(ObjectUtils.Dig(playabilityStatus, ["errorScreen", "playerErrorMessageRenderer", "subreason"]))
if subreason <> ""
errorMessage += `\n` + subreason
end if
if errorMessage = ""
errorMessage = "Video not available"
end if
return {
error: errorMessage
} }
end if end if
@@ -92,6 +67,7 @@ namespace Innertube
end if end if
lengthSeconds = videoDetails["lengthSeconds"].ToInt() lengthSeconds = videoDetails["lengthSeconds"].ToInt()
videoInfo = { videoInfo = {
"type": "video" "type": "video"
"title": videoDetails["title"] "title": videoDetails["title"]
@@ -113,6 +89,47 @@ namespace Innertube
return videoInfo return videoInfo
end function end function
function ParsePlayerResponseForError(payload as object) as string
if not IsAssociativeArray(payload)
return "Invalid payload"
end if
playabilityStatus = payload["playabilityStatus"]
if not IsAssociativeArray(playabilityStatus)
return "Invalid playability status"
end if
status = ValidString(playabilityStatus["status"])
if status = "OK"
return ""
end if
errorLines = []
if not StringUtils.IsNullOrEmpty(playabilityStatus["reason"])
errorLines.Push(playabilityStatus["reason"])
end if
if not StringUtils.IsNullOrEmpty(playabilityStatus["reasonTitle"])
errorLines.Push(playabilityStatus["reasonTitle"])
end if
subreason = ParseText(ObjectUtils.Dig(playabilityStatus, ["errorScreen", "playerErrorMessageRenderer", "subreason"]))
if subreason <> ""
errorLines.Push(subreason)
end if
if errorLines.Count() = 0
errorLines.Push("Video not available (Unknown)")
end if
if status = "LOGIN_REQUIRED"
' TODO:P2 localize
errorLines.Push("Hint: Log in to the YouTube app on your phone, then cast the video to Playlet.")
end if
return errorLines.Join(`\n`)
end function
function ParseStoryboards(payload as object, lengthSeconds as integer) as object function ParseStoryboards(payload as object, lengthSeconds as integer) as object
storyboard = ObjectUtils.Dig(payload, ["storyboards", "playerLiveStoryboardSpecRenderer", "spec"]) storyboard = ObjectUtils.Dig(payload, ["storyboards", "playerLiveStoryboardSpecRenderer", "spec"])
if IsString(storyboard) if IsString(storyboard)
@@ -6,17 +6,12 @@ namespace Innertube
deviceInfo = CreateObject("roDeviceInfo") deviceInfo = CreateObject("roDeviceInfo")
payload = { payload = {
"context": CreateContext(ClientType.Web, deviceInfo, "", "") "context": CreateContext(ClientType.Web, deviceInfo)
"url": url "url": url
} }
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/navigation/resolve_url?prettyPrint=false&alt=json", payload) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/navigation/resolve_url?prettyPrint=false&alt=json", payload)
headers = { request.Headers(Innertube.CreateHeaders(ClientType.Web))
"accept": "*/*"
"accept-language": "*"
}
headers.Append(CreateHeaders(ClientType.Web))
request.Headers(headers)
return request return request
end function end function
@@ -2,18 +2,25 @@ import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/components/Services/Innertube/Parser.bs" import "pkg:/components/Services/Innertube/Parser.bs"
import "pkg:/components/Services/Innertube/SearchFilters.bs" import "pkg:/components/Services/Innertube/SearchFilters.bs"
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/Types.bs"
namespace Innertube namespace Innertube
function Search(query as string, searchFilters as object, continuation = "" as string, cancellation = invalid as object, raw = false as boolean) as object function Search(query as string, options = invalid as object) as object
searchFilters = OptionUtils.Get(options, "searchFilters")
continuation = OptionUtils.Get(options, "continuation")
cancellation = OptionUtils.Get(options, "cancellation")
disableShorts = OptionUtils.GetOrDefault(options, "disableShorts", false)
raw = OptionUtils.GetOrDefault(options, "raw", false)
deviceInfo = CreateObject("roDeviceInfo") deviceInfo = CreateObject("roDeviceInfo")
payload = { payload = {
context: Innertube.CreateContext(Innertube.ClientType.WEB, deviceInfo, "", "") context: Innertube.CreateContext(Innertube.ClientType.WEB, deviceInfo)
} }
if continuation <> "" if not StringUtils.IsNullOrEmpty(continuation)
payload["continuation"] = continuation payload["continuation"] = continuation
else else
payload["query"] = query payload["query"] = query
@@ -26,13 +33,7 @@ namespace Innertube
end if end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json", payload) request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json", payload)
request.Headers({ request.Headers(Innertube.CreateHeaders(ClientType.Web))
"accept": "*/*"
"accept-language": "*"
"user-agent": INNERTUBE_WEB_USER_AGENT
"x-youtube-client-name": INNERTUBE_WEB_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_WEB_CLIENT_VERSION
})
request.Cancellation(cancellation) request.Cancellation(cancellation)
if raw if raw
@@ -51,7 +52,7 @@ namespace Innertube
return response.Json() return response.Json()
end if end if
feeds = ParseResponseDataForFeeds(response.Json()) feeds = ParseResponseDataForFeeds(response.Json(), { disableShorts: disableShorts })
result = { result = {
feeds: feeds feeds: feeds
@@ -9,7 +9,7 @@ import "pkg:/source/utils/TimeUtils.bs"
namespace Innertube namespace Innertube
const SESSION_DATA_VERSION = 1 const SESSION_DATA_VERSION = 1
const INNERTUBE_VISITOR_DATA_LIFESPAN = 1000 * 60 * 60 * 24 const INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS = 60 * 60 * 24 * 7 ' 7 days
function GetSessionData() as object function GetSessionData() as object
sessionData = ReadSessionDataFromRegistry() sessionData = ReadSessionDataFromRegistry()
@@ -18,11 +18,7 @@ namespace Innertube
end if end if
sessionData = RequestSessionData() sessionData = RequestSessionData()
if sessionData = invalid SaveSessionDataToRegistry(sessionData)
return invalid
end if
RegistryUtils.Write(RegistryUtils.INNERTUBE_SESSION_DATA, FormatJson(sessionData))
return sessionData return sessionData
end function end function
@@ -61,12 +57,21 @@ namespace Innertube
end if end if
return { return {
"__version": SESSION_DATA_VERSION
"timestamp": TimeUtils.Now().AsSeconds() "timestamp": TimeUtils.Now().AsSeconds()
"visitorData": visitorData "visitorData": visitorData
} }
end function end function
function SaveSessionDataToRegistry(sessionData as object) as void
if sessionData = invalid
return
end if
sessionData.__version = SESSION_DATA_VERSION
RegistryUtils.Write(RegistryUtils.INNERTUBE_SESSION_DATA, FormatJson(sessionData))
end function
function ReadSessionDataFromRegistry() as object function ReadSessionDataFromRegistry() as object
sessionData = RegistryUtils.Read(RegistryUtils.INNERTUBE_SESSION_DATA) sessionData = RegistryUtils.Read(RegistryUtils.INNERTUBE_SESSION_DATA)
if StringUtils.IsNullOrEmpty(sessionData) if StringUtils.IsNullOrEmpty(sessionData)
@@ -81,7 +86,7 @@ namespace Innertube
timestamp = sessionData.timestamp timestamp = sessionData.timestamp
nowSeconds = TimeUtils.Now().AsSeconds() nowSeconds = TimeUtils.Now().AsSeconds()
if nowSeconds - timestamp > INNERTUBE_VISITOR_DATA_LIFESPAN if nowSeconds - timestamp > INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA) RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
return invalid return invalid
end if end if
@@ -0,0 +1,42 @@
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/source/utils/Types.bs"
namespace Innertube
function CreateSubscribeRequest(channelIds as dynamic, options = invalid as object) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, options)
}
if IsString(channelIds)
channelIds = [channelIds]
end if
payload["channelIds"] = channelIds
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/subscription/subscribe?prettyPrint=false&alt=json", payload)
request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv))
return request
end function
function CreateUnsubscribeRequest(channelIds as dynamic, options = invalid as object) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"context": Innertube.CreateContext(Innertube.ClientType.Tv, deviceInfo, options)
}
if IsString(channelIds)
channelIds = [channelIds]
end if
payload["channelIds"] = channelIds
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/subscription/unsubscribe?prettyPrint=false&alt=json", payload)
request.Headers(Innertube.CreateHeaders(Innertube.ClientType.Tv))
return request
end function
end namespace
@@ -7,25 +7,14 @@ function Init()
m.service = new Invidious.InvidiousService(m.top) m.service = new Invidious.InvidiousService(m.top)
end function end function
function GetCurrentInstance(_unused as dynamic) as string function GetInstance(_unused as dynamic) as string
return m.service.GetInstance() return m.service.GetInstance()
end function end function
function GetInvidiousInstance(_unused as dynamic) as string
return m.service.GetInvidiousInstance()
end function
function GetAuthorizeTokenLink(_unused as dynamic) as dynamic function GetAuthorizeTokenLink(_unused as dynamic) as dynamic
return m.service.GetAuthorizeTokenLink() return m.service.GetAuthorizeTokenLink()
end function end function
function OnAuthTokenChange() as void
m.top.refreshSubscribtions = true
end function
function GetSubscriptions() as void
if m.subscriptionsTask <> invalid
m.subscriptionsTask.cancel = true
end if
if m.top.authToken = invalid
m.top.subscriptions = invalid
return
end if
m.subscriptionsTask = AsyncTask.Start(Tasks.InvidiousSubscriptionsTask, { invidious: m.top })
end function
@@ -5,12 +5,11 @@
<field id="webServer" type="node" /> <field id="webServer" type="node" />
<field id="profilesService" type="node" /> <field id="profilesService" type="node" />
<field id="authToken" type="assocarray" onChange="OnAuthTokenChange" /> <field id="authToken" type="assocarray" />
<field id="apiDefinitions" type="assocarray" /> <field id="apiDefinitions" type="assocarray" />
<field id="refreshSubscribtions" type="boolean" alwaysNotify="true" onChange="GetSubscriptions" />
<field id="subscriptions" type="assocarray" />
<function name="GetCurrentInstance" /> <function name="GetInstance" />
<function name="GetInvidiousInstance" />
<function name="GetAuthorizeTokenLink" /> <function name="GetAuthorizeTokenLink" />
</interface> </interface>
</component> </component>
@@ -6,6 +6,9 @@ import "pkg:/source/AsyncTask/Tasks.bs"
import "pkg:/source/services/HttpClient.bs" import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CryptoUtils.bs" import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/RegistryUtils.bs" import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs" import "pkg:/source/utils/TimeUtils.bs"
@@ -13,7 +16,7 @@ import "pkg:/source/utils/TimeUtils.bs"
namespace Invidious namespace Invidious
const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,users" const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,users"
const DEFAULT_INSTANCE = "http://127.0.0.1:8888/playlet-invidious-backend" const PLAYLET_BUILT_IN_INSTANCE = "http://127.0.0.1:8888/playlet-invidious-backend"
const INSTANCE_EXAMPLE = "https://invidious.example.com" const INSTANCE_EXAMPLE = "https://invidious.example.com"
const TOKEN_CALLBACK = "/invidious/token_callback" const TOKEN_CALLBACK = "/invidious/token_callback"
@@ -68,21 +71,34 @@ namespace Invidious
if m.preferences = invalid if m.preferences = invalid
m.preferences = m.invidiousNode.preferences m.preferences = m.invidiousNode.preferences
end if end if
instance = m.preferences["invidious.instance"]
backend = m.preferences["backend.selected"]
if backend = "invidious"
instance = m.GetInvidiousInstance()
if not StringUtils.IsNullOrEmpty(instance) if not StringUtils.IsNullOrEmpty(instance)
return instance return instance
end if end if
instance = DEFAULT_INSTANCE
if instance.StartsWith("http://127.0.0.1:8888")
address = m.invidiousNode.webServer@.GetServerAddress()
instance = instance.Replace("http://127.0.0.1:8888", address)
end if end if
return m.GetPlayletBuiltinInstance()
end function
function GetInvidiousInstance() as string
if m.preferences = invalid
m.preferences = m.invidiousNode.preferences
end if
return m.preferences["invidious.instance"]
end function
function GetPlayletBuiltinInstance() as string
instance = PLAYLET_BUILT_IN_INSTANCE
address = m.invidiousNode.webServer@.GetServerAddress()
instance = instance.Replace("http://127.0.0.1:8888", address)
return instance return instance
end function end function
function MarkVideoWatched(videoId as dynamic) as void function MarkVideoWatched(videoId as dynamic, cancellation = invalid as object) as void
if StringUtils.IsNullOrEmpty(videoId) if StringUtils.IsNullOrEmpty(videoId)
return return
end if end if
@@ -95,6 +111,7 @@ namespace Invidious
url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}` url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}`
request = HttpClient.Post(url, "") request = HttpClient.Post(url, "")
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation)
request.Await() request.Await()
end function end function
@@ -124,21 +141,9 @@ namespace Invidious
' have the exact expiration time, we'll use 5 hours. Invidious currently ' have the exact expiration time, we'll use 5 hours. Invidious currently
' Does a fresh fetch if the cache is older than 10 minutes. ' Does a fresh fetch if the cache is older than 10 minutes.
' https://github.com/iv-org/invidious/blob/069e91d2a609b1df94bdfbb693335969b2a281d8/src/invidious/videos.cr#L349 ' https://github.com/iv-org/invidious/blob/069e91d2a609b1df94bdfbb693335969b2a281d8/src/invidious/videos.cr#L349
cacheSeconds = 18000 ' 5 hours cacheSeconds = OptionUtils.GetOrDefault(options, "cacheSeconds", 18000) ' 5 hours
cancellation = invalid cancellation = OptionUtils.Get(options, "cancellation")
tryCount = 2 tryCount = OptionUtils.GetOrDefault(options, "tryCount", 2)
if options <> invalid
if options.DoesExist("cacheSeconds")
cacheSeconds = options.cacheSeconds
end if
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("tryCount")
tryCount = options.tryCount
end if
end if
instance = m.GetInstance() instance = m.GetInstance()
url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}` url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}`
@@ -177,12 +182,13 @@ namespace Invidious
function GetPlaylist(playlistId as string, index = 0 as integer, continuation = "" as string, cancellation = invalid as object) as object function GetPlaylist(playlistId as string, index = 0 as integer, continuation = "" as string, cancellation = invalid as object) as object
authToken = m.invidiousNode.authToken authToken = m.invidiousNode.authToken
' There's no need to use auth, unless the playlist is from Invidious if authToken <> invalid
' (starts with "IV") because it can be a private playlist from logged user.
if playlistId.StartsWith("IV") and authToken <> invalid
url = `${authToken.instance}${Invidious.AUTH_PLAYLISTS}/${playlistId}` url = `${authToken.instance}${Invidious.AUTH_PLAYLISTS}/${playlistId}`
request = HttpClient.Get(url) request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
end if
else else
instance = m.GetInstance() instance = m.GetInstance()
url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}` url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}`
@@ -258,7 +264,11 @@ namespace Invidious
return feedSource return feedSource
end function end function
function MakeRequest(feedSource as object, additionalQueryParams = invalid as object, cancellation = invalid as object) as object function MakeRequest(feedSource as object, options = invalid as dynamic) as object
additionalQueryParams = OptionUtils.Get(options, "additionalQueryParams")
cancellation = OptionUtils.Get(options, "cancellation")
httpServer = OptionUtils.Get(options, "httpServer")
if m.endpoints = invalid if m.endpoints = invalid
m.endpoints = m.invidiousNode.apiDefinitions m.endpoints = m.invidiousNode.apiDefinitions
end if end if
@@ -285,8 +295,25 @@ namespace Invidious
error: ERROR_NOT_AUTHENTICATED error: ERROR_NOT_AUTHENTICATED
} }
end if end if
profileNode = authToken.profileNode
' This is not the right place for a token refresh,
' but it needs a refactor to be done properly.
if not profileNode@.HasValidAccessToken()
messagePort = CreateObject("roMessagePort")
MessagePortUtils.ObserveFieldScopedExSafe(profileNode, "accessToken", messagePort)
msg = wait(10000, messagePort)
profileNode.unobserveFieldScoped("accessToken")
if msg <> invalid
authToken.token = profileNode.accessToken
m.invidiousNode.authToken = authToken
end if
end if
request.Url(authToken.instance + endpoint.url) request.Url(authToken.instance + endpoint.url)
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
end if
end if end if
if endpoint.queryParams <> invalid if endpoint.queryParams <> invalid
@@ -334,7 +361,7 @@ namespace Invidious
request.Cancellation(cancellation) request.Cancellation(cancellation)
response = request.Await() response = m.SendRequest(request, httpServer)
responseHandler = invalid responseHandler = invalid
if IsString(endpoint.responseHandler) and m.DoesExist(endpoint.responseHandler) if IsString(endpoint.responseHandler) and m.DoesExist(endpoint.responseHandler)
@@ -358,10 +385,39 @@ namespace Invidious
return { return {
success: false success: false
error: response.ErrorMessage() error: response.ErrorMessage()
cancelled: response.IsCancelled()
} }
end if end if
end function end function
function SendRequest(request as HttpClient.HttpRequest, httpServer as dynamic) as dynamic
if httpServer = invalid
return request.Await()
end if
url = request.BuildUrl()
isUrlToLocalServer = url.StartsWith("http://127.0.0.1:8888") or url.StartsWith(m.invidiousNode.webServer@.GetServerAddress())
if not isUrlToLocalServer
return request.Await()
end if
parsedUrl = UrlUtils.ParseUrl(url)
method = request.GetMethod()
uri = parsedUrl.path
headers = request.GetHeaders()
body = ValidString(request.GetBody())
responseObj = httpServer.ProcessRequestLocal(method, uri, headers, body)
response = new HttpClient.HttpResponse(request, invalid)
response.OverrideStatusCode(responseObj.http_code)
response.OverrideHeaders(responseObj.headers)
body = ""
if responseObj.body <> invalid
body = responseObj.body.ToAsciiString()
end if
response.OverrideText(body)
return response
end function
function DefaultHandler(context as object) as object function DefaultHandler(context as object) as object
response = context.response response = context.response
@@ -431,6 +487,7 @@ namespace Invidious
return { return {
items: json.videos items: json.videos
continuation: json.continuation continuation: json.continuation
sortOptions: json.sortOptions
} }
end if end if
return invalid return invalid
@@ -454,6 +511,7 @@ namespace Invidious
return { return {
items: json.playlists items: json.playlists
continuation: json.continuation continuation: json.continuation
sortOptions: json.sortOptions
} }
end if end if
return invalid return invalid
@@ -683,7 +741,11 @@ namespace Invidious
end function end function
function GetAuthorizeTokenLink() as dynamic function GetAuthorizeTokenLink() as dynamic
instance = m.GetInstance() instance = m.GetInvidiousInstance()
if StringUtils.IsNullOrEmpty(instance)
instance = m.GetPlayletBuiltinInstance()
end if
' Make sure the host is not on https, because https cannot redirect to http, which is our local server ' Make sure the host is not on https, because https cannot redirect to http, which is our local server
invidiousHost = instance.Replace("https://", "http://") invidiousHost = instance.Replace("https://", "http://")
@@ -721,6 +783,9 @@ namespace Invidious
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}` url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Post(url, "") request = HttpClient.Post(url, "")
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
end if
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation) request.Cancellation(cancellation)
@@ -735,6 +800,9 @@ namespace Invidious
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}` url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Delete(url) request = HttpClient.Delete(url)
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
end if
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation) request.Cancellation(cancellation)
@@ -1,42 +0,0 @@
import "InvidiousService.bs"
import "pkg:/source/utils/Logging.bs"
@asynctask
function InvidiousSubscriptionsTask(input as object) as object
invidiousNode = input.invidious
service = new Invidious.InvidiousService(invidiousNode)
response = service.GetSubscriptions(m.top.cancellation)
if m.top.cancel
return invalid
end if
subscriptions = response.Json()
if not response.IsSuccess() or subscriptions = invalid
error = response.ErrorMessage()
LogError("Error getting subscriptions:", error)
return {
success: false
error: response.ErrorMessage()
}
end if
if m.top.cancel
return invalid
end if
subscriptionsDict = {}
for each subscription in subscriptions
subscriptionsDict[subscription.authorId] = true
end for
invidiousNode.subscriptions = subscriptionsDict
return {
success: true
}
end function
@@ -51,6 +51,9 @@ namespace InvidiousContent
SetIfExists(node, "videoId", item, "videoId") SetIfExists(node, "videoId", item, "videoId")
node.viewCountText = VideoGetViewCountText(item) node.viewCountText = VideoGetViewCountText(item)
SetIfExists(node, "index", item, "index") SetIfExists(node, "index", item, "index")
SetIfExists(node, "lines", item, "lines")
SetIfExists(node, "videoInfo", item, "videoInfo")
SetIfExists(node, "percentDurationWatched", item, "percentDurationWatched")
return node return node
end function end function
@@ -77,20 +80,40 @@ namespace InvidiousContent
SetIfExists(node, "updated", item, "updated") SetIfExists(node, "updated", item, "updated")
node.updatedText = PlaylistGetUpdatedText(item) node.updatedText = PlaylistGetUpdatedText(item)
SetIfExists(node, "statsText", item, "statsText") SetIfExists(node, "statsText", item, "statsText")
SetIfExists(node, "lines", item, "lines")
if item.videos <> invalid if IsArray(item.videos) and item.videos.Count() > 0
childCount = node.getChildCount() childCount = node.getChildCount()
' Innertube's TV client doesn't return the index for videos in playlists.
' So we rely on video ids to detect duplicates.
videosHasIndex = IsInt(item.videos[0].index)
videoIds = invalid
if not videosHasIndex
videoIds = {}
childVideos = node.getChildren(-1, 0)
for each child in childVideos
videoIds[child.videoId] = true
end for
end if
newNodes = [] newNodes = []
for each video in item.videos for each video in item.videos
' TODO:P1 sometimes we're parsing "recommended playlists" that ' Sometimes we're parsing "recommended playlists" that show up
' show up in the end of the playlist. We should ignore them, ' in the end of the playlist. In this context they are ignored.
' until the parsing is fixed.
if ValidString(video.type) = "playlist" if ValidString(video.type) = "playlist"
continue for continue for
end if end if
video.type = "video" video.type = "video"
videoNode = ToVideoContentNode(invalid, video, instance) videoNode = ToVideoContentNode(invalid, video, instance)
if videoNode <> invalid if videoNode <> invalid
if not videosHasIndex
if videoIds[video.videoId] = true
continue for
end if
end if
index = video.index index = video.index
if index <> invalid and index > -1 and index < childCount if index <> invalid and index > -1 and index < childCount
node.replaceChild(videoNode, index) node.replaceChild(videoNode, index)
@@ -99,6 +122,7 @@ namespace InvidiousContent
end if end if
end if end if
end for end for
if newNodes.Count() > 0 if newNodes.Count() > 0
node.appendChildren(newNodes) node.appendChildren(newNodes)
end if end if
@@ -146,15 +170,16 @@ namespace InvidiousContent
end if end if
end function end function
function VideoSetThumbnail(node as object, videoItem as object, instance as dynamic, quality = "medium" as string) as boolean function VideoSetThumbnail(node as object, videoItem as object, instance as dynamic, quality = "medium" as string) as void
videoThumbnails = videoItem.videoThumbnails videoThumbnails = videoItem.videoThumbnails
hasValidInstance = not StringUtils.IsNullOrEmpty(instance) and instance.InStr(":8888/playlet-invidious-backend") = -1
if videoThumbnails = invalid or videoThumbnails.Count() = 0 if videoThumbnails = invalid or videoThumbnails.Count() = 0
if StringUtils.IsNullOrEmpty(instance) if hasValidInstance
node.thumbnail = `https://i.ytimg.com/vi/${videoItem.videoId}/mqdefault.jpg`
else
node.thumbnail = `${instance}/vi/${videoItem.videoId}/mqdefault.jpg` node.thumbnail = `${instance}/vi/${videoItem.videoId}/mqdefault.jpg`
else
node.thumbnail = `https://i.ytimg.com/vi/${videoItem.videoId}/mqdefault.jpg`
end if end if
return false return
end if end if
url = invalid url = invalid
for each thumbnail in videoThumbnails for each thumbnail in videoThumbnails
@@ -167,13 +192,13 @@ namespace InvidiousContent
url = videoThumbnails[0].url url = videoThumbnails[0].url
end if end if
if url.startsWith("/") if url.startsWith("/")
if StringUtils.IsNullOrEmpty(instance) if hasValidInstance
return false
end if
url = instance + url url = instance + url
else
url = `https://i.ytimg.com/vi/${videoItem.videoId}/mqdefault.jpg`
end if
end if end if
node.thumbnail = url node.thumbnail = url
return true
end function end function
function VideoIsLive(videoItem as object) as boolean function VideoIsLive(videoItem as object) as boolean
@@ -264,16 +289,16 @@ namespace InvidiousContent
end if end if
thumbnail = "" thumbnail = ""
hasValidInstance = not StringUtils.IsNullOrEmpty(instance) and instance.InStr(":8888/playlet-invidious-backend") = -1
if IsString(playlistItem.playlistThumbnail) if IsString(playlistItem.playlistThumbnail)
thumbnailUrl = playlistItem.playlistThumbnail thumbnailUrl = playlistItem.playlistThumbnail
if thumbnailUrl.startsWith("/") and not StringUtils.IsNullOrEmpty(playlistItem.instance) if thumbnailUrl.startsWith("/") and hasValidInstance
thumbnailUrl = playlistItem.instance + thumbnailUrl thumbnailUrl = playlistItem.instance + thumbnailUrl
end if end if
thumbnail = thumbnailUrl thumbnail = thumbnailUrl
else if playlistItem.videos <> invalid and playlistItem.videos.Count() > 0 and playlistItem.videos[0].index = 0 else if playlistItem.videos <> invalid and playlistItem.videos.Count() > 0 and playlistItem.videos[0].index = 0
if VideoSetThumbnail(node, playlistItem.videos[0], instance, quality) VideoSetThumbnail(node, playlistItem.videos[0], instance, quality)
return return
end if
else if node.getChildCount() > 0 else if node.getChildCount() > 0
thumbnail = node.getChild(0).thumbnail thumbnail = node.getChild(0).thumbnail
end if end if
@@ -307,6 +332,10 @@ namespace InvidiousContent
node.videoCountText = videoCountText node.videoCountText = videoCountText
return return
end if end if
' If we already have this information, we should not override it.
if not StringUtils.IsNullOrEmpty(node.videoCountText)
return
end if
videoCount = ValidInt(item.videoCount) videoCount = ValidInt(item.videoCount)
if videoCount = -1 if videoCount = -1
return return
@@ -49,7 +49,7 @@ class LongPoller
LogInfo(`Sending long polling GET ${url}`, "ID:", socket.GetID()) LogInfo(`Sending long polling GET ${url}`, "ID:", socket.GetID())
#if DEBUG #if DEBUG
? `════════ curl command ════════\n${m.ToCurlCommand()}\n══════════════════════════════` ? `======== curl command ========\n${m.ToCurlCommand()}\n==============================`
#end if #end if
message = `GET ${urlObject.path} HTTP/1.1\r\n` message = `GET ${urlObject.path} HTTP/1.1\r\n`
@@ -427,8 +427,8 @@ class LoungeApi
' Right now we just store only the last ctt, which works ok if we're casting one video at a time. ' Right now we just store only the last ctt, which works ok if we're casting one video at a time.
' But if the age restrcited video is added to the queue, we don't capture a token and playing the video would fail. ' But if the age restrcited video is added to the queue, we don't capture a token and playing the video would fail.
' These tokens need to be managed better, based on the video they belong to. ' These tokens need to be managed better, based on the video they belong to.
if not StringUtils.IsNullOrEmpty(commandArgs.ctt) if not StringUtils.IsNullOrEmpty(commandArgs[FIELD_CTT])
m.loungeServiceNode.ctt = commandArgs.ctt m.loungeServiceNode.credentialTransferToken = commandArgs[FIELD_CTT]
end if end if
LoungeVideoQueue.SetPlaylist(m.videoQueueNode, m.invService, commandArgs) LoungeVideoQueue.SetPlaylist(m.videoQueueNode, m.invService, commandArgs)
end function end function
@@ -5,7 +5,7 @@
<field id="deviceName" type="string" /> <field id="deviceName" type="string" />
<field id="screenId" type="string" /> <field id="screenId" type="string" />
<field id="loungeToken" type="string" /> <field id="loungeToken" type="string" />
<field id="ctt" type="string" /> <field id="credentialTransferToken" type="string" />
<field id="join" type="boolean" alwaysNotify="true" /> <field id="join" type="boolean" alwaysNotify="true" />
<field id="outgoingMessages" type="array" alwaysNotify="true" /> <field id="outgoingMessages" type="array" alwaysNotify="true" />
@@ -1,4 +1,5 @@
import "pkg:/source/utils/RegistryUtils.bs" import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/Types.bs"
function Init() function Init()
@@ -8,6 +9,7 @@ function Init()
"number": "integer" "number": "integer"
"radio": "string" "radio": "string"
"array": "array" "array": "array"
"assocarray": "assocarray"
} }
m.disableSavingToRegistry = false m.disableSavingToRegistry = false
@@ -93,23 +95,21 @@ function MigrateExistingPreferences(userPrefs as object) as boolean
isDirty = false isDirty = false
' v0 -> v1 ' v0 -> v1
if ValidInt(userPrefs.__version) = 0
instances = RegistryUtils.Read(RegistryUtils.INVIDIOUS_INSTANCES) instances = RegistryUtils.Read(RegistryUtils.INVIDIOUS_INSTANCES)
if instances <> invalid if not StringUtils.IsNullOrEmpty(instances)
currentInstance = userPrefs["invidious.instance"] currentInstance = userPrefs["invidious.instance"]
if currentInstance = invalid or currentInstance = "" if StringUtils.IsNullOrEmpty(currentInstance)
instances = ParseJson(instances) instances = ParseJson(instances)
if instances.Count() > 0 if IsArray(instances) and instances.Count() > 0
instance = instances[0] instance = instances[0]
if instance <> invalid and instance <> "" if not StringUtils.IsNullOrEmpty(instance)
userPrefs["invidious.instance"] = instance userPrefs["invidious.instance"] = instance
isDirty = true
end if end if
end if end if
end if end if
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_INSTANCES) RegistryUtils.Delete(RegistryUtils.INVIDIOUS_INSTANCES)
end if end if
if ValidInt(userPrefs.__version) = 0
userPrefs.__version = 1 userPrefs.__version = 1
isDirty = true isDirty = true
end if end if
@@ -122,7 +122,44 @@ function MigrateExistingPreferences(userPrefs as object) as boolean
isDirty = true isDirty = true
end if end if
if userPrefs.__version = 2
if IsArray(userPrefs["misc.home_screen_layout"])
homeScreenLayout = userPrefs["misc.home_screen_layout"]
hasRecommended = false
for each item in homeScreenLayout
if item.id = "recommended"
hasRecommended = true
exit for
end if
end for
if not hasRecommended
homeScreenLayout.Unshift({
id: "recommended"
enabled: true
})
end if
end if
userPrefs.__version = 3
isDirty = true
end if
if userPrefs.__version = 3
if IsString(userPrefs["playback.backend"])
backend = userPrefs["playback.backend"]
userPrefs.Delete("playback.backend")
userPrefs["backend.selected"] = backend
end if
userPrefs.__version = 4
isDirty = true
end if
' TODO:P2 handle case where saved preferences version is higher than current version (e.g. user downgraded) ' TODO:P2 handle case where saved preferences version is higher than current version (e.g. user downgraded)
#if DEBUG
if userPrefs.__version <> m.top.__version
throw "Preferences version mismatch. Expected: " + m.top.__version + ", found: " + userPrefs.__version
end if
#end if
return isDirty return isDirty
end function end function
@@ -5,7 +5,7 @@
user prefs saved need to be migrated. If the version is less than the user prefs saved need to be migrated. If the version is less than the
current version, a migration is needed. current version, a migration is needed.
--> -->
<field id="__version" type="integer" value="2" /> <field id="__version" type="integer" value="4" />
<field id="prefsModel" type="array" /> <field id="prefsModel" type="array" />
<field id="preferenceFields" type="assocarray" /> <field id="preferenceFields" type="assocarray" />
<function name="GetUserPreferences" /> <function name="GetUserPreferences" />
@@ -39,7 +39,7 @@ function LoadProfilesFromRegistry()
' Step 3: Save user preferences (if needed) ' Step 3: Save user preferences (if needed)
if isDirty if isDirty
SaveUserProfilesToRegistry() SaveUserProfilesToRegistry(invalid)
end if end if
' Step 4: Load user profiles into content nodes ' Step 4: Load user profiles into content nodes
@@ -53,6 +53,7 @@ function LoadProfilesFromRegistry()
profileNode.thumbnail = profile.thumbnail profileNode.thumbnail = profile.thumbnail
profileNode.accessToken = profile.accessToken profileNode.accessToken = profile.accessToken
profileNode.activeIdentifyToken = profile.activeIdentifyToken
profileNode.refreshToken = profile.refreshToken profileNode.refreshToken = profile.refreshToken
profileNode.scope = profile.scope profileNode.scope = profile.scope
profileNode.tokenType = profile.tokenType profileNode.tokenType = profile.tokenType
@@ -103,7 +104,7 @@ function MigrateExistingProfiles(userProfiles as object) as boolean
return false return false
end if end if
id = CreateProfileId(authToken.username, authToken.instance) id = CreateProfileId(authToken.username, "", authToken.instance)
for each profile in userProfiles.profiles for each profile in userProfiles.profiles
if profile.id = id if profile.id = id
return false return false
@@ -127,7 +128,7 @@ function MigrateExistingProfiles(userProfiles as object) as boolean
return true return true
end function end function
function SaveUserProfilesToRegistry() as void function SaveUserProfilesToRegistry(_unused as dynamic) as void
if m.disableSavingToRegistry if m.disableSavingToRegistry
return return
end if end if
@@ -161,6 +162,7 @@ function GetProfilesDto(includeAccessToken as boolean) as object
"id": profileNode.id "id": profileNode.id
"type": profileNode.type "type": profileNode.type
"username": profileNode.username "username": profileNode.username
"activeIdentifyToken": profileNode.activeIdentifyToken
"serverUrl": profileNode.serverUrl "serverUrl": profileNode.serverUrl
"thumbnail": profileNode.thumbnail "thumbnail": profileNode.thumbnail
"color": color "color": color
@@ -191,7 +193,7 @@ end function
function LoginWithProfile(newProfile as object) function LoginWithProfile(newProfile as object)
isNewProfile = true isNewProfile = true
if StringUtils.IsNullOrEmpty(newProfile.id) if StringUtils.IsNullOrEmpty(newProfile.id)
newProfile.id = CreateProfileId(newProfile.username, newProfile.serverUrl) newProfile.id = CreateProfileId(newProfile.username, newProfile.activeIdentifyToken, newProfile.serverUrl)
end if end if
existingProfile = invalid existingProfile = invalid
@@ -206,6 +208,7 @@ function LoginWithProfile(newProfile as object)
if not isNewProfile if not isNewProfile
existingProfile.username = newProfile.username existingProfile.username = newProfile.username
existingProfile.activeIdentifyToken = newProfile.activeIdentifyToken
existingProfile.thumbnail = newProfile.thumbnail existingProfile.thumbnail = newProfile.thumbnail
existingProfile.accessToken = newProfile.accessToken existingProfile.accessToken = newProfile.accessToken
existingProfile.refreshToken = newProfile.refreshToken existingProfile.refreshToken = newProfile.refreshToken
@@ -322,7 +325,7 @@ function SetCurrentProfile(newActiveProfile as object) as void
m.top.currentProfile = invalid m.top.currentProfile = invalid
m.invidious.authToken = invalid m.invidious.authToken = invalid
LogInfo("Current profile set to <invalid>") LogInfo("Current profile set to <invalid>")
SaveUserProfilesToRegistry() SaveUserProfilesToRegistry(invalid)
return return
end if end if
@@ -333,9 +336,11 @@ function SetCurrentProfile(newActiveProfile as object) as void
token: newActiveProfile.accessToken token: newActiveProfile.accessToken
instance: newActiveProfile.serverUrl instance: newActiveProfile.serverUrl
username: newActiveProfile.username username: newActiveProfile.username
activeIdentifyToken: newActiveProfile.activeIdentifyToken
profileNode: newActiveProfile
} }
LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl) LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl)
SaveUserProfilesToRegistry() SaveUserProfilesToRegistry(invalid)
end function end function
function RefreshActiveProfileState(activeProfile as object) as void function RefreshActiveProfileState(activeProfile as object) as void
@@ -352,6 +357,6 @@ function RefreshActiveProfileState(activeProfile as object) as void
end for end for
end function end function
function CreateProfileId(username as string, serverUrl as string) as string function CreateProfileId(username as string, activeIdentifyToken as string, serverUrl as string) as string
return "v1:" + CryptoUtils.GetMd5(username + serverUrl) return "v1:" + CryptoUtils.GetMd5(username + activeIdentifyToken + serverUrl)
end function end function
@@ -18,6 +18,7 @@
<function name="LogoutWithProfiles" /> <function name="LogoutWithProfiles" />
<function name="LogoutWithAccessToken" /> <function name="LogoutWithAccessToken" />
<function name="SetCurrentProfile" /> <function name="SetCurrentProfile" />
<function name="SaveUserProfilesToRegistry" />
</interface> </interface>
<children> <children>
<!-- Note: two content nodes because we're rendering profiles in a RowList on the ProfilesScreen --> <!-- Note: two content nodes because we're rendering profiles in a RowList on the ProfilesScreen -->
@@ -1,4 +1,5 @@
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs" import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
import "pkg:/components/VideoPlayer/SponsorBlockSegmentAction.bs"
function Init() function Init()
m.categoryLabel = m.top.findNode("categoryLabel") m.categoryLabel = m.top.findNode("categoryLabel")
@@ -13,16 +14,7 @@ function Init()
m.service = SponsorBlock.SponsorBlockService() m.service = SponsorBlock.SponsorBlockService()
end function end function
function OnActionSet() function OnDoShow() as void
action = m.top.action
category = m.top.segment.category
categoryTitle = Tr(ValidString(m.service.SegmentShortTitle(category)))
if action = "AutoSkip"
m.categoryLabel.text = Tr(Locale.SponsorBlock.Skipped) + `\n` + categoryTitle
else
m.categoryLabel.text = categoryTitle
end if
AnimateIn() AnimateIn()
end function end function
@@ -1,7 +1,9 @@
<component name="SponsorBlockNotification" extends="Group"> <component name="SponsorBlockNotification" extends="Group">
<interface> <interface>
<field id="segment" type="assocarray" /> <field id="segmentId" type="string" />
<field id="action" type="string" onChange="OnActionSet" alwaysNotify="true" /> <field id="categoryText" type="string" alias="categoryLabel.text" />
<field id="actionText" type="string" alias="actionLabel.text" />
<field id="doShow" type="boolean" onChange="OnDoShow" alwaysNotify="true" />
</interface> </interface>
<children> <children>
<Poster <Poster
@@ -16,18 +18,26 @@
height="50" height="50"
translation="[10,10]"> translation="[10,10]">
</Poster> </Poster>
<LayoutGroup vertAlignment="center" translation="[70,35]">
<Label <Label
id="categoryLabel" id="categoryLabel"
text="..." font="font:TinyBoldSystemFont"
font="font:SmallestBoldSystemFont"
lineSpacing="5"
horizAlign="center" horizAlign="center"
vertAlign="center"
wrap="true"
width="170" width="170"
height="70" lineSpacing="0"
translation="[70,0]"> maxLines="2"
wrap="true">
</Label> </Label>
<Label
id="actionLabel"
font="font:TinySystemFont"
horizAlign="center"
width="170"
lineSpacing="0"
maxLines="2"
wrap="true">
</Label>
</LayoutGroup>
</Poster> </Poster>
<Animation <Animation
id="translationAnimation" id="translationAnimation"
@@ -1,27 +1,43 @@
namespace SponsorBlock namespace SponsorBlock
const NOTIFICATION_NODE_ID = "SponsorBlockNotification" const NOTIFICATION_NODE_ID = "SponsorBlockNotification"
function ShowNotifcation(notifications as object, segment as object, action as dynamic) as void function GetCurrentNotification(notifications as object) as object
childCount = notifications.getChildCount()
for i = 0 to childCount - 1
child = notifications.getChild(i)
if child.id = NOTIFICATION_NODE_ID
return child
end if
end for
return invalid
end function
function ShowNotifcation(notifications as object, segment as object) as void
' TODO:P2 avoid finding the node over and over ' TODO:P2 avoid finding the node over and over
' The video player can probably own a single notification, and destroy it when the video is closed ' The video player can probably own a single notification, and destroy it when the video is closed
notification = notifications.findNode(NOTIFICATION_NODE_ID) notification = GetCurrentNotification(notifications)
if notification = invalid if notification = invalid
notification = notifications.createChild("SponsorBlockNotification") notification = notifications.createChild("SponsorBlockNotification")
notification.id = NOTIFICATION_NODE_ID notification.id = NOTIFICATION_NODE_ID
end if end if
notification.segment = segment
notification.action = action notification.segmentId = segment.UUID
notification.categoryText = segment.shortTitle
notification.actionText = segment.actionText
notification.doShow = true
end function end function
function RemoveNotifcation(notifications as object) as void function RemoveNotifcation(notifications as object) as void
notification = notifications.findNode(NOTIFICATION_NODE_ID) notification = GetCurrentNotification(notifications)
if notification <> invalid if notification <> invalid
notifications.RemoveChild(notification) notifications.RemoveChild(notification)
end if end if
end function end function
function SetVisible(notifications as object, visible as boolean) function SetVisible(notifications as object, visible as boolean)
notification = notifications.findNode(NOTIFICATION_NODE_ID) notification = GetCurrentNotification(notifications)
if notification <> invalid if notification <> invalid
notification.visible = visible notification.visible = visible
end if end if
@@ -5,5 +5,5 @@ function SponsorBlockSegmentViewedTask(input as object)
segmentId = input.segmentId segmentId = input.segmentId
service = new SponsorBlock.SponsorBlockService() service = new SponsorBlock.SponsorBlockService()
service.PostSegmentViewed(segmentId) service.PostSegmentViewed(segmentId, m.top.cancellation)
end function end function
@@ -12,6 +12,26 @@ namespace SponsorBlock
m.sponsorBlockConfig = ParseJson(ReadAsciiFile("libpkg:/config/sponsorblock_config.json5")) m.sponsorBlockConfig = ParseJson(ReadAsciiFile("libpkg:/config/sponsorblock_config.json5"))
end function end function
function GetCategories() as object
if m.sponsorBlockConfig = invalid
return []
end if
return ValidArray(m.sponsorBlockConfig.categoryList)
end function
function GetOptionsForCategory(category as string) as object
if m.sponsorBlockConfig = invalid
return []
end if
if not m.sponsorBlockConfig.categories.doesexist(category)
return []
end if
return ValidArray(m.sponsorBlockConfig.categories[category].options)
end function
function SegmentColor(category as string) as integer function SegmentColor(category as string) as integer
if m.sponsorBlockConfig = invalid if m.sponsorBlockConfig = invalid
return 0 return 0
@@ -54,8 +74,10 @@ namespace SponsorBlock
return invalid return invalid
end if end if
categories = ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "poi_highlight", "filler", "exclusive_access"] ' categories = ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "poi_highlight", "filler", "exclusive_access"]
actionTypes = ["skip", "mute", "chapter", "full", "poi"] categories = ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "poi_highlight", "filler"]
' actionTypes = ["skip", "mute", "chapter", "full", "poi"]
actionTypes = ["skip", "mute", "poi"]
categoriesJson = FormatJson(categories).EncodeUriComponent() categoriesJson = FormatJson(categories).EncodeUriComponent()
actionTypesJson = FormatJson(actionTypes).EncodeUriComponent() actionTypesJson = FormatJson(actionTypes).EncodeUriComponent()
@@ -64,6 +86,11 @@ namespace SponsorBlock
hashPrefix = CryptoUtils.GetSha256(videoId).Left(4) hashPrefix = CryptoUtils.GetSha256(videoId).Left(4)
url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.SKIP_SEGMENT_ENDPOINT}/${hashPrefix}?categories=${categoriesJson}&actionTypes=${actionTypesJson}` url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.SKIP_SEGMENT_ENDPOINT}/${hashPrefix}?categories=${categoriesJson}&actionTypes=${actionTypesJson}`
response = HttpClient.Get(url).Await() response = HttpClient.Get(url).Await()
if not response.IsSuccess()
LogError("SponsorBlockService: GetSkipSegmentsForVideo failed", response.ErrorMessage())
return invalid
end if
json = response.Json() json = response.Json()
if json = invalid if json = invalid
return invalid return invalid
@@ -78,13 +105,13 @@ namespace SponsorBlock
return invalid return invalid
end function end function
function PostSegmentViewed(segmentId as string) as void function PostSegmentViewed(segmentId as string, cancellation = invalid as object) as void
if m.sponsorBlockConfig = invalid or StringUtils.IsNullOrEmpty(m.sponsorBlockConfig.serverAddress) if m.sponsorBlockConfig = invalid or StringUtils.IsNullOrEmpty(m.sponsorBlockConfig.serverAddress)
return return
end if end if
url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}` url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}`
HttpClient.Post(url, "").Await() HttpClient.Post(url, "").Cancellation(cancellation).Await()
end function end function
function GenerateProgressBarBackground(segments as object, lengthSeconds as integer, path as string) function GenerateProgressBarBackground(segments as object, lengthSeconds as integer, path as string)
@@ -103,8 +130,8 @@ namespace SponsorBlock
continue for continue for
end if end if
pixelStart = (segment.segment[0] / videoDuration) * width pixelStart = (segment.start / videoDuration) * width
pixelEnd = (segment.segment[1] / videoDuration) * width pixelEnd = (segment.end / videoDuration) * width
color = m.SegmentColor(segment.category) color = m.SegmentColor(segment.category)
' highlight's duration is zero, so it is not visble on the bar. ' highlight's duration is zero, so it is not visble on the bar.
' Add a few pixels to see it ' Add a few pixels to see it
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more