Compare commits

..
48 Commits
Author SHA1 Message Date
Brahim Hadriche 1e28ee4e27 Release v0.35.1 (#523) 2024-12-25 20:12:32 -05:00
Brahim Hadriche 339066ff4e [skip-ci] use built-in cache value in search suggestions 2024-12-25 19:10:30 -05:00
Brahim Hadriche 11290146e8 Fix video thumbnail when adding to queue from lounge 2024-12-25 17:07:55 -05:00
Brahim Hadriche e05a02933e Formatting 2024-12-25 14:56:33 -05:00
Brahim Hadriche 31a4669c79 Fix resolve url functionality 2024-12-25 14:53:23 -05:00
Brahim Hadriche e23da56b37 Innertube continuations (#522)
* Search continuations

* add another type of playlists

* Continuation for search and channels working

* Playlist continuation

* Fix pagination - what a fucking mess I've created

* web app fix

* Changelog
2024-12-25 14:07:48 -05:00
Brahim Hadriche f6e23ad7d9 Mark unused vars 2024-12-24 17:02:26 -05:00
Brahim Hadriche ce7f51c403 Fix channels sub count in web app 2024-12-24 16:57:53 -05:00
Brahim Hadriche 889a502731 Support for auto-generated channels in Playlet backend 2024-12-24 16:35:49 -05:00
Brahim Hadriche 0f6266afa4 Remove youtube.js from web app 2024-12-24 11:36:57 -05:00
Brahim Hadriche e20fb7df90 small tweak to proto stuff 2024-12-24 11:04:59 -05:00
Brahim Hadriche 1ce9410565 Change playlist loading when logged in 2024-12-24 10:26:35 -05:00
Brahim Hadriche 43807b67ff Release v0.35.0 (#521) 2024-12-23 22:31:28 -05:00
Brahim Hadriche a17dd5c0cc [skip ci] plugin docs 2024-12-23 19:30:34 -05:00
Brahim Hadriche 564afd9685 Search filters protobuf (#516)
* [Wip] search filters protobuf

* Filters work

* Small tweaks

* changelog
2024-12-23 18:12:31 -05:00
Brahim Hadriche c6853cd2fc Content region and locale for playlet backend 2024-12-23 13:29:23 -05:00
Brahim Hadriche 82e55d7030 [skip ci] validation rule 2024-12-23 12:22:16 -05:00
Brahim Hadriche 2c1306c563 Fixed start up crash on older OS version (11.5) 2024-12-23 12:13:35 -05:00
Brahim Hadriche 010d86f34e Release v0.34.1 (#518) 2024-12-23 09:47:38 -05:00
Brahim Hadriche 27d915c027 App version 2024-12-23 09:42:15 -05:00
Brahim Hadriche e864a6d351 Add mix error dialog 2024-12-22 21:25:22 -05:00
Brahim Hadriche 93d660e978 Fix web app views when using new backend 2024-12-22 20:43:22 -05:00
Brahim Hadriche 51fa4c0540 Fixed regression caused watch history thumbnails to break 2024-12-22 18:58:15 -05:00
Brahim Hadriche 5efe9a4e94 Release v0.34.0 (#514) 2024-12-22 16:18:18 -05:00
Brahim Hadriche 416a87028c Fix tests 2024-12-22 16:08:10 -05:00
Brahim Hadricheandgithub-action linter bed8223e76 [Part 2] Innertube (#513)
* Parse author in videoRenderer

* Parse more fields

* Parse live badge

* playlist video count

* Parse more things

* parse playlists and albums

* More parsing work

* announcement and changelog

* Lint fix

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2024-12-22 16:04:36 -05:00
Brahim Hadricheandgithub-action linter 9f3eee900f [Part 1] Innertube (#502)
* innertube structure

* Basic search results parsing

* Lint fix

* Fix ctt

* adjust parser, parse trending pages

* Lint fix

* channel wip

* channel parsing - wip

* OAuth support

* cancellation utils

* Lint fix

* Home feed with tv client

* Lint fix

* add some browse endpoints

* oauth adjust

* refactor

* Add nodes

* More parsing

* oauth refactor

* playlist

* WIP: built-in instance

* WIP: Channels now kinda load

* Channel view

* workaround for playlist pagination

* default instance and display name

* video thumbnails

* changelog

* privacy

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2024-12-21 15:22:42 -05:00
Brahim Hadriche a9c8ee6eb6 update dependencies (#512) 2024-12-21 10:02:44 -05:00
Brahim Hadriche 070d72a4ad Add json workaround 2024-12-20 18:26:10 -05:00
Brahim Hadriche 031601d49c fix usage of deprecated api 2024-12-17 18:55:16 -05:00
Brahim Hadriche e1bcfc053a Release v0.33.2 (#508) 2024-12-17 18:40:58 -05:00
Brahim Hadriche 711e0faf51 change default Invidious instance 2024-12-17 18:27:26 -05:00
Brahim Hadriche cf54a10803 Release v0.33.1 (#507) 2024-12-17 09:09:05 -05:00
Brahim Hadriche 980781c453 UI to clarify how to enable Control by mobile apps in the web app 2024-12-16 18:20:19 -05:00
Brahim Hadriche 657b6c9818 Fix error when opening a mix 2024-12-16 17:42:59 -05:00
Brahim Hadriche b49557a5a6 Web app compression (#505) 2024-12-15 16:50:26 -05:00
Brahim Hadriche c2abcc5478 Release v0.33.0 (#504) 2024-12-14 14:23:52 -05:00
Brahim Hadriche 8307f577fd update dependencies (#503) 2024-12-14 10:22:48 -05:00
Brahim Hadriche 0ce0dc43c3 [skip ci] typo 2024-12-12 20:19:03 -05:00
Brahim Hadriche 357019d74b Improvements for very long HLS playlists 2024-12-12 19:26:45 -05:00
Brahim Hadriche bfc1439d1a [skip ci] curl command 2024-12-12 17:48:12 -05:00
Brahim Hadriche dd2262ec28 Improve validation plugin 2024-12-12 10:18:50 -05:00
Brahim Hadriche 0c3f8cea2a reuse sponsorblock bar png 2024-12-10 16:48:41 -05:00
Brahim Hadriche 4682d4f3e4 [skip ci] changelog adjustment 2024-12-09 20:55:47 -05:00
Brahim Hadriche 1e161e8a77 Use credentialTransferToken to play age restricted videos (#498)
* Use credentialTransferToken to play age restricted videos

* changelog
2024-12-09 20:48:56 -05:00
Brahim Hadriche ee239c3ea9 deps 2024-12-06 22:06:07 -05:00
Brahim Hadriche 1daddc9b91 Handle preferences v0 to v1 migration 2024-12-05 20:41:53 -05:00
Brahim Hadriche 335761aa8e search suggestions 2024-12-04 20:07:06 -05:00
101 changed files with 5536 additions and 1256 deletions

No files matched your search

+76
View File
@@ -5,6 +5,82 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.35.1] - 2024-12-26
### Added
- Support for auto-generated channels in Playlet backend
- Support for continuation/pagination in Playlet backend: search, channels and playlists load more content as you scroll
### Fixed
- Channels sub count in web app
- Channel drag and drop in web app
- Video thumbnail when adding to queue from lounge
### Removed
- [YouTube.js](https://github.com/LuanRT/YouTube.js) from web app. It is no longer needed, so this reduces app size.
## [0.35.0] - 2024-12-24
### Added
- Region and locale support for Playlet backend
- Search filters support for Playlet backend
### Fixed
- Start up crash on older OS version (11.5)
## [0.34.1] - 2024-12-23
### Fixed
- Regression caused watch history thumbnails to break
- Web app views when using new backend
## [0.34.0] - 2024-12-22
### Added
- Built-in Playlet backend, which supports channels, playlists, and search
- This backend is experimental, and has a few missing features.
- To use it, set the Invidious instance to an empty string.
### Fixed
- Added a workaround for an issue where json parsing fails due to unicode characters
## [0.33.2] - 2024-12-17
### Changed
- Default Invidious instance
## [0.33.1] - 2024-12-17
### Added
- Compression (gzip) to static web app files. Reduces app size significantly
- UI to clarify how to enable `Control by mobile apps` in the web app
### Fixed
- Error when opening a mix
## [0.33.0] - 2024-12-14
### Added
- Search suggestions to Playlet backend
- Support for age restrcited videos and private videos when cast from YouTube app (logged in)
- Note: it works when the video is explicitely cast. If it was added to queue, or added as part of a playlist, this might not work.
### Fixed
- Improved on issue with long videos (10+ hours) showing as 2:30 only. They now show about 5 hours.
## [0.32.1] - 2024-12-03
### Fixed
+8
View File
@@ -24,6 +24,14 @@ know the IP address of a user, the identifiers of watched video, and search
keywords. In case the user has privacy concerns, they can host their own
Invidious instance and use it from Playlet.
## Innertube
When the Playlet built-in backend is in use, instead of an Invidious instance,
Playlet makes requests directly to Innertube instead of Invidious.
Similar to Invidious requests, only the bare minimum and necessary information
is sent, which is used to enable the viewing of content.
## SponsorBlock
Playlet may request information from a [SponsorBlock](https://github.com/ajayyy/SponsorBlock)
+9 -1
View File
@@ -26,6 +26,12 @@
"regexFlags": "ig",
"message": "observeField(\"field\", \"callback\") is not allowed. Use observeField(\"field\", FuncName(callback)) instead."
},
{
"code": "NO_OBSERVE_FIELD_SCOPED_EX",
"regex": "\\.observeFieldScopedEx\\s*\\(",
"regexFlags": "ig",
"message": "observeFieldScopedEx is not allowed. Use MessagePortUtils.ObserveFieldScopedExSafe instead."
},
{
"code": "NO_INVALID_CALLFUNC_ARG",
"regex": "@\\.\\w+\\(invalid\\)",
@@ -62,6 +68,7 @@
"!**/*.psd",
"!**/*.svg",
"!**/*.svg.meta.json5",
"!**/*.proto",
"locale/**",
"config/**",
"lib/**",
@@ -87,7 +94,8 @@
"../tools/bs-plugins/image-gen-plugin.ts",
"../tools/bs-plugins/type-gen-plugin.ts",
"../tools/bs-plugins/web-server-plugin.ts",
"../tools/bs-plugins/locale-validation-plugin.ts"
"../tools/bs-plugins/locale-validation-plugin.ts",
"../tools/bs-plugins/proto-gen-plugin.ts"
],
"retainStagingDir": true,
"require": [
+3 -1
View File
@@ -8,6 +8,7 @@
"!**/*.psd",
"!**/*.svg",
"!**/*.svg.meta.json5",
"!**/*.proto",
"locale/**",
"config/**",
"lib/**",
@@ -31,7 +32,8 @@
"../tools/bs-plugins/image-gen-plugin.ts",
"../tools/bs-plugins/type-gen-plugin.ts",
"../tools/bs-plugins/web-server-plugin.ts",
"../tools/bs-plugins/locale-validation-plugin.ts"
"../tools/bs-plugins/locale-validation-plugin.ts",
"../tools/bs-plugins/proto-gen-plugin.ts"
],
"rooibos": {
"logLevel": 2,
+1 -1
View File
@@ -2,7 +2,7 @@ openapi: 3.0.0
info:
title: Playlet Web API
version: 0.32.1
version: 0.35.1
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
+17
View File
@@ -13,6 +13,7 @@
- [Type Gen](#type-gen)
- [Web Server](#web-server)
- [Locale validation](#locale-validation)
- [Protobuf Generator](#protobuf-generator)
Playlet implements a few [Brighterscript Plugins](https://github.com/rokucommunity/brighterscript/blob/master/docs/plugins.md). The plugins inject themselves in the compilation process, allowing the modification of bs scripts, xml components, and even assets or the app manifest. Let's start with a simple one:
@@ -623,3 +624,19 @@ The plugin checks for the following:
- `en_US` must have matching source and translation values, so it can act as a fallback translation.
- All `source` translations from all languages must be present in the `@locale` enums. This is to prevent renaming the values in the code without updating translation files.
- Translation `source` keys can't be used except for certain fields such as `"text"` and `"title"`. This is to prevent the accidental localization of non-display fields, such as node ids.
## Protobuf Generator
**[Source](/tools/bs-plugins/proto-gen-plugin.ts)**
### Why
To generate BrighterScript encoding/decoding functions for Protobuf types.
These are needed for some functionality (e.g. Search filters in Innertube backend)
### How
The plugin scans for `.proto` files, and parse them into plain objects using [protocol-buffers-schema](https://www.npmjs.com/package/protocol-buffers-schema)
Then the right functions that get generated to serialize/deserialize types.
Please note this generator is VERY bare bone: only features necessary for Playlet were implemented.
The generation can be improved as needed.
+1191 -383
View File
File diff suppressed because it is too large. Load diff
+11 -10
View File
@@ -1,30 +1,31 @@
{
"name": "playlet",
"version": "0.32.1",
"version": "0.35.1",
"description": "Unofficial YouTube client for Roku",
"devDependencies": {
"@rokucommunity/bslint": "^0.8.26",
"@rokucommunity/bslint": "^0.8.27",
"@types/crypto-js": "^4.2.2",
"@types/fs-extra": "^11.0.4",
"@types/node": "^22.10.1",
"@types/node": "^22.10.2",
"@types/xml2js": "^0.4.14",
"argparse": "^2.0.1",
"brighterscript": "0.68.1",
"brighterscript-formatter": "^1.7.6",
"brighterscript": "0.68.2",
"brighterscript-formatter": "^1.7.7",
"convert-svg-to-png": "^0.6.4",
"cross-fetch": "^4.0.0",
"crypto-js": "^4.2.0",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"fs-extra": "^11.2.0",
"glob": "^11.0.0",
"imap": "^0.8.19",
"ip": "^2.0.1",
"json5": "^2.2.3",
"mailparser": "^3.7.2",
"roku-deploy": "^3.12.2",
"protocol-buffers-schema": "^3.6.0",
"roku-deploy": "^3.12.3",
"rooibos-roku": "5.14.0",
"rounded-rect-9patch": "^1.0.1",
"rounded-rect-9patch": "^1.1.2",
"semver": "^7.6.3",
"shelljs": "^0.8.5",
"ts-node": "^10.9.2",
@@ -64,7 +65,7 @@
"generate-sponsorblock-config": "node tools/generate-sponsorblock-config.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",
"postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playlet-web && npm install",
"update-deps": "npx npm-check-updates --deep --upgrade --install always --reject @sveltejs/vite-plugin-svelte,svelte",
"update-deps": "npx npm-check-updates --deep --upgrade --install always --reject @sveltejs/vite-plugin-svelte,svelte,vite,@vitejs/plugin-legacy",
"registry:write": "node tools/registry.js --input registry.json",
"registry:read": "node tools/registry.js --output registry.json",
"registry:clear": "node tools/registry.js --clear"
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-app",
"version": "0.32.1",
"version": "0.35.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-app",
"version": "0.32.1"
"version": "0.35.1"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-app",
"version": "0.32.1",
"version": "0.35.1",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "rm -rf ../build/playlet-app",
+1 -1
View File
@@ -2,7 +2,7 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=32
minor_version=35
build_version=00001
ui_resolutions=hd
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-lib",
"version": "0.32.1",
"version": "0.35.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-lib",
"version": "0.32.1"
"version": "0.35.1"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-lib",
"version": "0.32.1",
"version": "0.35.1",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "rm -rf ../build/playlet-lib",
@@ -66,7 +66,13 @@ function OnContentSet() as void
' NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation.
m.authorLabel.text = content._author
m.subCountLabel.text = content.subCountText
subCountText = content.authorSubTitle
if StringUtils.IsNullOrEmpty(subCountText)
subCountText = content.subCountText
end if
m.subCountLabel.text = subCountText
m.banner.uri = content.banner
if StringUtils.IsNullOrEmpty(content.thumbnail)
m.thumbnail.uri = ""
@@ -86,11 +92,11 @@ function OnContentSet() as void
if (authorId <> m.authorId or author <> m.author) and IsArray(content.tabs)
m.authorId = authorId
m.author = author
m.rowList.feeds = CreateChannelFeeds(m.authorId, author, content.tabs)
m.rowList.feeds = CreateChannelFeeds(m.authorId, author, content.tabs, content.tabsParams)
end if
end function
function CreateChannelFeeds(authorId as string, author as string, tabs as object) as object
function CreateChannelFeeds(authorId as string, author as string, tabs as object, tabsParams as object) as object
if authorId = ""
return invalid
end if
@@ -99,9 +105,22 @@ function CreateChannelFeeds(authorId as string, author as string, tabs as object
for i = 0 to tabs.count() - 1
tabName = tabs[i]
if m.tabs.DoesExist(tabName)
feeds.Push(m.tabs[tabName](authorId, author))
if tabsParams <> invalid and tabsParams.DoesExist(tabName)
params = tabsParams[tabName]
else
params = ""
end if
feeds.Push(m.tabs[tabName](authorId, author, params))
end if
end for
' If we're dealing with an auto-generated channel, we might not have any tabs at all.
' In this case, it's better to show "home" instead of nothing at all.
if feeds.Count() = 0 and tabs.Count() > 0 and tabsParams <> invalid and tabsParams["featured"] <> invalid
feeds.Push(CreateChannelFeed("Home", "channel_featured", authorId, author, tabsParams["featured"]))
end if
return feeds
end function
@@ -178,23 +197,23 @@ end function
function InitializeTabs()
m.tabs = {
"videos": function(authorId as string, author as string) as object
return CreateChannelFeed("Videos", "channel_videos", authorId, author)
"videos": function(authorId as string, author as string, params as string) as object
return CreateChannelFeed("Videos", "channel_videos", authorId, author, params)
end function
"shorts": function(authorId as string, author as string) as object
return CreateChannelFeed("Shorts", "channel_shorts", authorId, author)
"shorts": function(authorId as string, author as string, params as string) as object
return CreateChannelFeed("Shorts", "channel_shorts", authorId, author, params)
end function
"streams": function(authorId as string, author as string) as object
return CreateChannelFeed("Live", "channel_streams", authorId, author)
"streams": function(authorId as string, author as string, params as string) as object
return CreateChannelFeed("Live", "channel_streams", authorId, author, params)
end function
"releases": function(authorId as string, author as string) as object
return CreateChannelFeed("Releases", "channel_releases", authorId, author)
"releases": function(authorId as string, author as string, params as string) as object
return CreateChannelFeed("Releases", "channel_releases", authorId, author, params)
end function
"podcasts": function(authorId as string, author as string) as object
return CreateChannelFeed("Podcasts", "channel_podcasts", authorId, author)
"podcasts": function(authorId as string, author as string, params as string) as object
return CreateChannelFeed("Podcasts", "channel_podcasts", authorId, author, params)
end function
"playlists": function(authorId as string, author as string) as object
return CreateChannelFeed("Playlists", "channel_playlists", authorId, author)
"playlists": function(authorId as string, author as string, params as string) as object
return CreateChannelFeed("Playlists", "channel_playlists", authorId, author, params)
end function
}
end function
@@ -241,19 +260,27 @@ function InitializeSortOptions()
}
end function
function CreateChannelFeed(title as string, endpoint as string, ucid as string, author as string) as object
function CreateChannelFeed(title as string, endpoint as string, ucid as string, author as string, params as string) as object
title = Tr(title)
feedSource = {
"id": `inv_${endpoint}_${ucid}`
"title": `${author} - ${title}`
"apiType": "Invidious"
"endpoint": endpoint
"pathParams": {
"ucid": ucid
}
}
if not StringUtils.IsNullOrEmpty(params)
feedSource["queryParams"] = {
"params": params
}
end if
return {
title: title
feedSources: [{
"id": `inv_${endpoint}_${ucid}`
"title": `${author} - ${title}`
"apiType": "Invidious"
"endpoint": endpoint
"pathParams": {
"ucid": ucid
}
}]
feedSources: [feedSource]
}
end function
@@ -10,12 +10,14 @@
<!-- NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation -->
<field id="_author" type="string" />
<field id="authorId" type="string" />
<field id="authorSubTitle" type="string" />
<field id="banner" type="string" />
<field id="channelHandle" type="string" />
<field id="description" type="string" />
<field id="subCount" type="integer" />
<field id="subCountText" type="string" />
<field id="tabs" type="array" />
<field id="tabsParams" type="assocarray" />
<field id="thumbnail" type="string" />
<field id="videoCount" type="integer" />
<field id="videoCountText" type="string" />
@@ -7,7 +7,8 @@
<field id="loadState" type="string" />
<!-- index in a feed -->
<field id="feedSourcesIndex" type="integer" value="-1" />
<!--
<field id="continuation" type="string" />
<!--
For some strange reason, the "author" field can only be set once.
If you try to set it again, it will not be updated, with type mismatch warning:
@@ -39,5 +40,6 @@
<field id="videoCountText" type="string" />
<field id="viewCount" type="integer" />
<field id="viewCountText" type="string" />
<field id="statsText" type="string" />
</interface>
</component>
@@ -18,7 +18,10 @@ function PlaylistContentTask(input as object) as object
while true
index = contentNode.getChildCount()
response = service.GetPlaylist(contentNode.playlistId, index, m.top.cancellation)
continuation = contentNode.continuation
hadContinuation = not StringUtils.IsNullOrEmpty(continuation)
response = service.GetPlaylist(contentNode.playlistId, index, continuation, m.top.cancellation)
if m.top.cancel
contentNode.loadState = FeedLoadState.None
@@ -35,10 +38,32 @@ function PlaylistContentTask(input as object) as object
}
end if
if metadata.DoesExist("error")
contentNode.loadState = FeedLoadState.Error
return {
success: false
error: metadata.error
}
end if
' TODO:P2 To remove after https://github.com/iv-org/invidious/pull/5116
if IsString(metadata["mixId"]) and IsArray(metadata["videos"])
videos = metadata["videos"]
for i = 0 to videos.Count() - 1
thumbnails = videos[i].videoThumbnails
if thumbnails.Count() = 1 and IsArray(thumbnails[0])
videos[i].videoThumbnails = thumbnails[0]
end if
end for
end if
InvidiousContent.ToPlaylistContentNode(contentNode, metadata, instance)
childCount = contentNode.getChildCount()
if metadata.videos.Count() = 0 or childCount >= metadata.videoCount
videoCount = ValidInt(metadata.videoCount)
hasContinuation = not StringUtils.IsNullOrEmpty(metadata.continuation)
if (hadContinuation and not hasContinuation) or (metadata.videos.Count() = 0 or childCount >= videoCount)
contentNode.loadState = FeedLoadState.Loaded
return {
success: true
+2 -1
View File
@@ -1,4 +1,5 @@
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
@@ -10,7 +11,7 @@ function Init()
m.top.ObserveField("logLine", port)
scene = m.top.getScene()
scene.ObserveFieldScoped("systemLogEvent", port)
MessagePortUtils.ObserveFieldScopedExSafe(scene, "systemLogEvent", port)
m.port = port
+23
View File
@@ -2,6 +2,7 @@ import "pkg:/components/EcpArgs.bs"
import "pkg:/components/parts/AutoBind/AutoBind.part.bs"
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/source/utils/LoadingScreen.bs"
import "pkg:/source/utils/Locale.bs"
function Init()
m.scene = m.top.getScene()
@@ -18,6 +19,7 @@ function MainSceneContainerChanged()
InitEcpArgs()
m.scene.signalBeacon("AppLaunchComplete")
CopyLoadingMessagesToCache()
ShowAnnouncement()
end function
function StartWebServer()
@@ -30,3 +32,24 @@ function StartWebServer()
m.dialServer = m.top.findNode("DialServer")
m.dialServer@.StartServer()
end function
function ShowAnnouncement()
title = "Announcement - Playlet backend"
message = [
"An experimental built-in backend has been added to Playlet."
"This allows you to access YouTube content without the need for an Invidious instance."
"To use it, go to the Settings > Invidious > Instance and set the field to empty (Edit, and delete the url)."
"Please note that it's missing some features and may not work as expected."
"Thank you for using Playlet!"
]
buttons = [Tr(Locale.Buttons.OK)]
dialog = CreateObject("roSGNode", "SimpleDialog")
dialog.title = title
dialog.message = message
dialog.buttons = buttons
deviceInfo = CreateObject("roDeviceInfo")
displaySize = deviceInfo.GetDisplaySize()
dialog.width = displaySize.w - 180
m.top.getScene().dialog = dialog
end function
@@ -2,6 +2,7 @@
'import "pkg:/components/parts/AutoBind/AutoBind.part.bs"
'import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
'import "pkg:/source/utils/LoadingScreen.bs"
'import "pkg:/source/utils/Locale.bs"
function Init()
InitializeBindings() ' auto-generated!
@@ -19,6 +20,7 @@ function MainSceneContainerChanged()
InitEcpArgs()
m.scene.signalBeacon("AppLaunchComplete")
CopyLoadingMessagesToCache()
ShowAnnouncement()
end function
function StartWebServer()
@@ -29,4 +31,26 @@ function StartWebServer()
m.dialServer = m.top.findNode("DialServer")
m.dialServer.callfunc("StartServer", invalid)
end function
function ShowAnnouncement()
title = "Announcement - Playlet backend"
message = [
"An experimental built-in backend has been added to Playlet."
"This allows you to access YouTube content without the need for an Invidious instance."
"To use it, go to the Settings > Invidious > Instance and set the field to empty (Edit, and delete the url)."
"Please note that it's missing some features and may not work as expected."
"Thank you for using Playlet!"
]
buttons = [
Tr("OK")
]
dialog = CreateObject("roSGNode", "SimpleDialog")
dialog.title = title
dialog.message = message
dialog.buttons = buttons
deviceInfo = CreateObject("roDeviceInfo")
displaySize = deviceInfo.GetDisplaySize()
dialog.width = displaySize.w - 180
m.top.getScene().dialog = dialog
end function
'//# sourceMappingURL=./MainScene.brs.map
@@ -0,0 +1,83 @@
import "pkg:/source/utils/Types.bs"
const LIB_CANARY_ZIP_URL = "https://github.com/iBicha/playlet/releases/download/canary/playlet-lib.zip"
const LIB_CANARY_SQUASHFS_URL = "https://github.com/iBicha/playlet/releases/download/canary/playlet-lib.squashfs.pkg"
function Init()
m.top.text = GetAppVersion()
end function
' TODO:P2: refactor and move to appropriate place, reuse with web app
function GetAppVersion() as string
version = "v" + GetLibVersion()
roAppInfo = CreateObject("roAppInfo")
appId = roAppInfo.GetID()
if appId = "dev"
version += "-dev"
end if
scene = m.top.getScene()
if scene.playletLibLoadedUrl <> invalid
libUrl = scene.playletLibLoadedUrl.link
libUrlType = scene.playletLibLoadedUrl.type
if libUrlType = "custom" and (libUrl = LIB_CANARY_ZIP_URL or libUrl = LIB_CANARY_SQUASHFS_URL)
version += "-canary"
end if
end if
return version
end function
function GetLibVersion() as string
values = GetLibManifestValues()
if values = invalid
return "0.0.0"
end if
major = 0
minor = 0
build = 0
if values.DoesExist("major_version")
value = values["major_version"]
if IsString(value)
major = value.toInt()
end if
end if
if values.DoesExist("minor_version")
value = values["minor_version"]
if IsString(value)
minor = value.toInt()
end if
end if
if values.DoesExist("build_version")
value = values["build_version"]
if IsString(value)
build = value.toInt()
end if
end if
return `${major}.${minor}.${build}`
end function
function GetLibManifestValues() as object
libManifest = ReadAsciiFile("libpkg:/manifest")
lines = libManifest.Tokenize(`\n`)
values = {}
for each line in lines
if line.left(1) = "#"
continue for
end if
keyValuePair = line.Tokenize("=")
if keyValuePair.Count() <> 2
continue for
end if
values[keyValuePair[0]] = keyValuePair[1]
end for
return values
end function
@@ -0,0 +1,2 @@
<component name="AppVersionLabel" extends="SimpleLabel">
</component>
+8 -2
View File
@@ -38,7 +38,13 @@
height="42"
translation="[20, 48]"
opacity="0"
uri="pkg:/images/logo-dark.png" />
uri="pkg:/images/logo-dark.png">
<AppVersionLabel
fontUri="font:BoldSystemFontFile"
fontSize="16"
translation="[0, 48]"
/>
</Poster>
<MarkupList
id="ItemsList"
@@ -51,7 +57,7 @@
numRows="7"
scrollSpeed="99999"
itemSpacing="[0, 16]"
translation="[15, 120]">
translation="[15, 150]">
</MarkupList>
</Rectangle>
@@ -42,8 +42,18 @@ function OnContentSet() as void
end if
m.titleLabel.text = content.title
' NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation.
m.subtitleLabel.text = `${content._author} • ${content.videoCountText} • ${content.viewCountText}`
' Starts with RD means a mix, not a playlist
if content.playlistId.StartsWith("RD")
m.subtitleLabel.text = ""
else
statsText = content.statsText
if statsText.Len() > 0
m.subtitleLabel.text = statsText
else
' NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation.
m.subtitleLabel.text = `${content._author} • ${content.videoCountText} • ${content.viewCountText}`
end if
end if
m.updatedLabel.text = content.updatedText
m.descriptionLabel.text = content.description
@@ -1,3 +1,4 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/components/Services/SearchHistory/SearchHistoryUtils.bs"
@@ -7,13 +8,17 @@ function SearchSuggestionsTask(input as object) as object
invidiousNode = input.invidious
preferencesNode = input.preferences
service = new Invidious.InvidiousService(invidiousNode)
if m.top.cancel
return invalid
end if
searchSuggestsions = StringUtils.IsNullOrEmpty(q) ? invalid : service.SearchSuggestions(q, m.top.cancellation)
backend = preferencesNode["playback.backend"]
if backend = "playlet"
searchSuggestsions = StringUtils.IsNullOrEmpty(q) ? invalid : InnertubeService.SearchSuggestions(q, m.top.cancellation)
else
service = new Invidious.InvidiousService(invidiousNode)
searchSuggestsions = StringUtils.IsNullOrEmpty(q) ? invalid : service.SearchSuggestions(q, m.top.cancellation)
end if
if m.top.cancel
return invalid
@@ -9,7 +9,7 @@ function Init()
m.top.itemSpacings = [8]
m.button = m.top.findNode("button")
m.button.text = Invidious.DEFAULT_INSTANCE
m.button.text = Invidious.DEFAULT_INSTANCE_NAME
AdjustButtonLabel(m.button)
m.button.observeField("buttonSelected", FuncName(OpenInvidiousInstanceSettings))
@@ -81,7 +81,7 @@ function OnValueChange() as void
m.preferences[m.key] = value
if StringUtils.IsNullOrEmpty(value)
m.button.text = Invidious.DEFAULT_INSTANCE
m.button.text = Invidious.DEFAULT_INSTANCE_NAME
else
m.button.text = value
end if
@@ -33,7 +33,7 @@ function Init()
SetNavigation(m.testButton, RemoteKeys.Right, m.saveButton)
m.currentNavigtionNode = m.editButton
m.textEditBox.hintText = `e.g. ${Invidious.DEFAULT_INSTANCE}`
m.textEditBox.hintText = `e.g. ${Invidious.INSTANCE_EXAMPLE}`
SetButtonPositions()
@@ -106,7 +106,7 @@ function OnEditButtonSelected()
' TODO:P2 localize
keyboardDialog.title = "Edit Instance"
' TODO:P2 localize
keyboardDialog.message = [`Enter the instance url (e.g. ${Invidious.DEFAULT_INSTANCE})`]
keyboardDialog.message = [`Enter the instance url (e.g. ${Invidious.INSTANCE_EXAMPLE})`]
keyboardDialog.text = m.top.text
keyboardDialog.buttons = [Tr(Locale.Buttons.OK), Tr(Locale.Buttons.Cancel)]
keyboardDialog.observeField("buttonSelected", FuncName(OnKeyboardButton))
@@ -0,0 +1,30 @@
namespace Innertube
function CreateBrowseRequest(browseId as string, clienType as Innertube.ClientType, params = "" as string, continuation = "" as string) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"context": Innertube.CreateContext(clienType, deviceInfo, "")
}
if not StringUtils.IsNullOrEmpty(continuation)
payload["continuation"] = continuation
else
payload["browseId"] = browseId
if not StringUtils.IsNullOrEmpty(params)
payload["params"] = params
end if
end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/browse?prettyPrint=false&alt=json", payload)
headers = {
"accept": "*/*"
"accept-language": "*"
}
headers.Append(Innertube.CreateHeaders(clienType))
request.Headers(headers)
return request
end function
end namespace
@@ -0,0 +1,20 @@
const INNERTUBE_IOS_CLIENT_NAME = "5"
const INNERTUBE_IOS_CLIENT_VERSION = "19.09.3"
const INNERTUBE_IOS_OS_VERSION = "15.6"
const INNERTUBE_IOS_USER_AGENT = "com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)"
const INNERTUBE_WEB_CLIENT_NAME = "1"
const INNERTUBE_WEB_CLIENT_VERSION = "2.20241126.01.00"
const INNERTUBE_WEB_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0"
const INNERTUBE_WEB_BROWSER_NAME = "Chrome"
const INNERTUBE_WEB_BROWSER_VERSION = "131.0.0.0"
const INNERTUBE_TV_CLIENT_NAME = "2"
const INNERTUBE_TV_CLIENT_VERSION = "7.20241211.14.00"
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_DEVICE_MAKE = "LGE"
const INNERTUBE_TV_DEVICE_MODEL = "24LF4820-BU"
const INNERTUBE_TV_OS_NAME = "webOS"
const INNERTUBE_TV_OS_VERSION = "2015"
const INNERTUBE_TV_BROWSER_NAME = "LG Browser"
const INNERTUBE_TV_BROWSER_VERSION = "7.00.00"
@@ -0,0 +1,168 @@
import "pkg:/components/Services/Innertube/Constants.bs"
namespace Innertube
enum ClientType
Web = "WEB"
IOS = "IOS"
Tv = "TV"
end enum
function CreateHeaders(clienType as Innertube.ClientType) as object
if clienType = ClientType.Web
return {
"user-agent": INNERTUBE_WEB_USER_AGENT
"x-youtube-client-name": INNERTUBE_WEB_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_WEB_CLIENT_VERSION
}
else if clienType = ClientType.IOS
return {
"user-agent": INNERTUBE_IOS_USER_AGENT
"x-youtube-client-name": INNERTUBE_IOS_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_IOS_CLIENT_VERSION
}
else if clienType = ClientType.Tv
return {
"user-agent": INNERTUBE_TV_USER_AGENT
"x-youtube-client-name": INNERTUBE_TV_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_TV_CLIENT_VERSION
}
else
throw "Invalid client type"
end if
end function
function CreateContext(clienType as Innertube.ClientType, deviceInfo as object, ctt as string) as object
client = invalid
if clienType = ClientType.Web
client = CreateContextClientWeb(deviceInfo)
else if clienType = ClientType.IOS
client = CreateContextClientIOS(deviceInfo)
else if clienType = ClientType.Tv
client = CreateContextClientTv(deviceInfo)
else
throw "Invalid client type"
end if
context = {
"client": client
"user": {
"enableSafetyMode": false
"lockedSafetyMode": false
}
"request": {
"useSsl": true
"internalExperimentFlags": []
}
}
if not StringUtils.IsNullOrEmpty(ctt)
context["user"]["credentialTransferTokens"] = [{
"token": ctt
"scope": "VIDEO"
}]
end if
return context
end function
function CreateContextClientWeb(deviceInfo as object) as object
return {
"hl": deviceInfo.GetCurrentLocale()
"gl": GetContentRegion(deviceInfo)
"remoteHost": ""
"screenDensityFloat": 1
"screenHeightPoints": 1440
"screenPixelDensity": 1
"screenWidthPoints": 2560
"visitorData": ""
"clientName": "WEB"
"clientVersion": INNERTUBE_WEB_CLIENT_VERSION
"osName": "Windows"
"osVersion": "10.0"
"platform": "DESKTOP"
"clientFormFactor": "UNKNOWN_FORM_FACTOR"
"userInterfaceTheme": "USER_INTERFACE_THEME_LIGHT"
"timeZone": deviceInfo.GetTimeZone()
"originalUrl": "https://www.youtube.com"
"deviceMake": ""
"deviceModel": ""
"browserName": INNERTUBE_WEB_BROWSER_NAME
"browserVersion": INNERTUBE_WEB_BROWSER_VERSION
"utcOffsetMinutes": -240
"memoryTotalKbytes": "8000000"
"mainAppWebInfo": {
"graftUrl": "https://www.youtube.com"
"pwaInstallabilityStatus": "PWA_INSTALLABILITY_STATUS_UNKNOWN"
"webDisplayMode": "WEB_DISPLAY_MODE_BROWSER"
"isWebNativeShareAvailable": true
}
}
end function
function CreateContextClientIOS(deviceInfo as object) as object
return {
"hl": deviceInfo.GetCurrentLocale()
"gl": GetContentRegion(deviceInfo)
"remoteHost": ""
"screenDensityFloat": 1
"screenHeightPoints": 1440
"screenPixelDensity": 1
"screenWidthPoints": 2560
"visitorData": ""
"clientName": "iOS"
"clientVersion": INNERTUBE_IOS_CLIENT_VERSION
"osName": "iOS"
"osVersion": INNERTUBE_IOS_OS_VERSION
"platform": "MOBILE"
"clientFormFactor": "UNKNOWN_FORM_FACTOR"
"userInterfaceTheme": "USER_INTERFACE_THEME_LIGHT"
"timeZone": deviceInfo.GetTimeZone()
"originalUrl": "https://www.youtube.com"
"deviceMake": "Apple"
"deviceModel": "iPhone10,6"
"utcOffsetMinutes": -240
"memoryTotalKbytes": "8000000"
}
end function
function CreateContextClientTv(deviceInfo as object) as object
return {
"hl": deviceInfo.GetCurrentLocale()
"gl": GetContentRegion(deviceInfo)
"remoteHost": ""
"deviceMake": INNERTUBE_TV_DEVICE_MAKE
"deviceModel": INNERTUBE_TV_DEVICE_MODEL
"userAgent": INNERTUBE_TV_USER_AGENT
"clientName": "TVHTML5"
"clientVersion": INNERTUBE_TV_CLIENT_VERSION
"osName": INNERTUBE_TV_OS_NAME
"osVersion": INNERTUBE_TV_OS_VERSION
"originalUrl": "https://www.youtube.com/tv"
"theme": "CLASSIC"
"platform": "TV"
"clientFormFactor": "UNKNOWN_FORM_FACTOR"
"webpSupport": false
"tvAppInfo": {
"appQuality": "TV_APP_QUALITY_LIMITED_MEMORY"
"useStartPlaybackPreviewCommand": false
"supportsNativeScrolling": false
}
"browserName": INNERTUBE_TV_BROWSER_NAME
"browserVersion": INNERTUBE_TV_BROWSER_VERSION
"acceptHeader": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
"screenHeightPoints": 1440
"screenWidthPoints": 2560
"screenPixelDensity": 2
"utcOffsetMinutes": -300
}
end function
function GetContentRegion(deviceInfo as object) as string
region = deviceInfo.GetUserCountryCode()
if region.len() <> 2 or region = "OT"
region = "US"
end if
return region
end function
end namespace
@@ -1,23 +1,23 @@
import "pkg:/components/Services/Innertube/BrowseEndpoint.bs"
import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/components/Services/Innertube/NextEndpoint.bs"
import "pkg:/components/Services/Innertube/OAuth.bs"
import "pkg:/components/Services/Innertube/PlayerEndpoint.bs"
import "pkg:/components/Services/Innertube/ResolveUrl.bs"
import "pkg:/components/Services/Innertube/Search.bs"
import "pkg:/components/Services/Innertube/SearchFilters.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
const INNERTUBE_IOS_CLIENT_NAME = "5"
const INNERTUBE_IOS_CLIENT_VERSION = "19.09.3"
const INNERTUBE_IOS_OS_VERSION = "15.6"
const INNERTUBE_IOS_USER_AGENT = "com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)"
const INNERTUBE_WEB_CLIENT_NAME = "1"
const INNERTUBE_WEB_CLIENT_VERSION = "2.20241126.01.00"
const INNERTUBE_WEB_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0"
const INNERTUBE_WEB_BROWSER_NAME = "Chrome"
const INNERTUBE_WEB_BROWSER_VERSION = "131.0.0.0"
namespace InnertubeService
function GetVideoMetadata(videoId as string, options = invalid as object) as object
cancellation = invalid
fetchNext = true
ctt = ""
if options <> invalid
if options.DoesExist("cancellation")
@@ -26,16 +26,19 @@ namespace InnertubeService
if options.DoesExist("fetchNext")
fetchNext = options.fetchNext
end if
if options.DoesExist("ctt")
ctt = options.ctt
end if
end if
playerRequest = CreatePlayerRequest(videoId)
playerRequest = Innertube.CreatePlayerRequest(videoId, ctt)
playerRequest.Cancellation(cancellation)
playerRequest.Send()
nextRequest = invalid
nextResponse = invalid
if fetchNext
nextRequest = CreateNextRequest(videoId)
nextRequest = Innertube.CreateNextRequest(videoId, ctt)
nextRequest.Cancellation(cancellation)
nextRequest.Send()
end if
@@ -45,14 +48,18 @@ namespace InnertubeService
return playerResponse
end if
if CancellationUtils.IsCancelled(cancellation)
return invalid
end if
if fetchNext
nextResponse = nextRequest.Await()
end if
parsedResponse = ParseInnertubePlayerResponse(playerResponse.Json())
parsedResponse = Innertube.ParseInnertubePlayerResponse(playerResponse.Json())
if fetchNext
parsedResponse = ParseInnertubeNextResponse(nextResponse.Json(), parsedResponse)
parsedResponse = Innertube.ParseInnertubeNextResponse(nextResponse.Json(), parsedResponse)
end if
if parsedResponse <> invalid
@@ -67,402 +74,247 @@ namespace InnertubeService
return playerResponse
end function
function CreatePlayerRequest(videoId as string) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"playbackContext": {
"contentPlaybackContext": {
"vis": 0
"splay": false
"referer": "https://www.youtube.com/watch?v=" + videoId
"currentUrl": "/watch?v=" + videoId
"autonavState": "STATE_ON"
"autoCaptionsDefaultOn": false
"html5Preference": "HTML5_PREF_WANTS"
"lactMilliseconds": "-1"
}
}
"attestationRequest": {
"omitBotguardData": true
}
"racyCheckOk": true
"contentCheckOk": true
"videoId": videoId
"context": {
"client": {
"hl": "en"
"gl": "US"
"remoteHost": ""
"screenDensityFloat": 1
"screenHeightPoints": 1440
"screenPixelDensity": 1
"screenWidthPoints": 2560
"visitorData": ""
"clientName": "iOS"
"clientVersion": INNERTUBE_IOS_CLIENT_VERSION
"osName": "iOS"
"osVersion": INNERTUBE_IOS_OS_VERSION
"platform": "MOBILE"
"clientFormFactor": "UNKNOWN_FORM_FACTOR"
"userInterfaceTheme": "USER_INTERFACE_THEME_LIGHT"
"timeZone": deviceInfo.GetTimeZone()
"originalUrl": "https://www.youtube.com"
"deviceMake": "Apple"
"deviceModel": "iPhone10,6"
"utcOffsetMinutes": -240
"memoryTotalKbytes": "8000000"
}
"user": {
"enableSafetyMode": false
"lockedSafetyMode": false
}
"request": {
"useSsl": true
"internalExperimentFlags": []
}
}
}
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", FormatJson(payload))
request.Headers({
"accept": "*/*"
"accept-language": "*"
"content-type": "application/json"
"user-agent": INNERTUBE_IOS_USER_AGENT
"x-youtube-client-name": INNERTUBE_IOS_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_IOS_CLIENT_VERSION
})
return request
end function
function CreateNextRequest(videoId as string) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"videoId": videoId
"context": {
"client": {
"hl": "en"
"gl": "US"
"remoteHost": ""
"screenDensityFloat": 1
"screenHeightPoints": 1440
"screenPixelDensity": 1
"screenWidthPoints": 2560
"visitorData": ""
"clientName": "WEB"
"clientVersion": INNERTUBE_WEB_CLIENT_VERSION
"osName": "Windows"
"osVersion": "10.0"
"platform": "DESKTOP"
"clientFormFactor": "UNKNOWN_FORM_FACTOR"
"userInterfaceTheme": "USER_INTERFACE_THEME_LIGHT"
"timeZone": deviceInfo.GetTimeZone()
"originalUrl": "https://www.youtube.com"
"deviceMake": ""
"deviceModel": ""
"browserName": INNERTUBE_WEB_BROWSER_NAME
"browserVersion": INNERTUBE_WEB_BROWSER_VERSION
"utcOffsetMinutes": -240
"memoryTotalKbytes": "8000000"
"mainAppWebInfo": {
"graftUrl": "https://www.youtube.com"
"pwaInstallabilityStatus": "PWA_INSTALLABILITY_STATUS_UNKNOWN"
"webDisplayMode": "WEB_DISPLAY_MODE_BROWSER"
"isWebNativeShareAvailable": true
}
}
"user": {
"enableSafetyMode": false
"lockedSafetyMode": false
}
"request": {
"useSsl": true
"internalExperimentFlags": []
}
}
}
request = HttpClient.Post("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json", FormatJson(payload))
request.Headers({
"accept": "*/*"
"accept-language": "*"
"content-type": "application/json"
"user-agent": INNERTUBE_WEB_USER_AGENT
"x-youtube-client-name": INNERTUBE_WEB_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_WEB_CLIENT_VERSION
})
return request
end function
function ParseInnertubePlayerResponse(payload as object) as object
if not IsAssociativeArray(payload)
return {
Success: false
Error: "Invalid payload"
}
function SearchSuggestions(q as string, cancellation = invalid as object) as object
suggestions = Innertube.SearchSuggestions(q, cancellation)
if suggestions = invalid
suggestions = []
end if
playabilityStatus = payload["playabilityStatus"]
if not IsAssociativeArray(playabilityStatus)
return {
Success: false
Error: "Invalid playability status"
}
end if
if playabilityStatus["status"] <> "OK"
errorMessage = ""
if IsString(playabilityStatus["reason"])
errorMessage = playabilityStatus["reason"]
end if
subreason = ObjectUtils.Dig(playabilityStatus, ["errorScreen", "playerErrorMessageRenderer", "subreason"])
if IsAssociativeArray(subreason)
subreasonText = ""
runs = subreason["runs"]
if IsArray(runs)
for each rn in runs
text = rn["text"]
if IsString(text)
subreasonText += text
end if
end for
end if
subreason = subreasonText
end if
if IsString(subreason)
errorMessage += `\n` + subreason
end if
if errorMessage = ""
errorMessage = "Video not available"
end if
return {
Success: false
Error: errorMessage
}
end if
videoDetails = payload["videoDetails"]
if not IsAssociativeArray(videoDetails)
return {
Success: false
Error: "Invalid video details"
}
end if
streamingData = payload["streamingData"]
if not IsAssociativeArray(streamingData)
return {
Success: false
Error: "Invalid streaming data"
}
end if
lengthSeconds = videoDetails["lengthSeconds"].ToInt()
videoInfo = {
"type": "video"
"title": videoDetails["title"]
"videoId": videoDetails["videoId"]
"videoThumbnails": videoDetails["thumbnail"]["thumbnails"]
"storyboards": ParseStoryboards(payload, lengthSeconds)
"viewCount": videoDetails["viewCount"].ToInt()
"author": videoDetails["author"]
"authorId": videoDetails["channelId"]
"lengthSeconds": lengthSeconds
"liveNow": ValidBool(videoDetails["isLive"])
"hlsUrl": streamingData["hlsManifestUrl"]
"adaptiveFormats": []
"formatStreams": []
"captions": ParseCaptions(payload)
"recommendedVideos": []
}
return {
Success: true
Metadata: videoInfo
suggestions: suggestions
}
end function
function ParseStoryboards(payload as object, lengthSeconds as integer) as object
storyboard = ObjectUtils.Dig(payload, ["storyboards", "playerLiveStoryboardSpecRenderer", "spec"])
if IsString(storyboard)
storyboard = storyboard.Split("#")
if storyboard.Count() <> 5
return []
function Search(query as string, options = invalid as object) as object
searchFilters = invalid
continuation = ""
cancellation = invalid
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
return [{
"templateUrl": storyboard[0]
"width": storyboard[1].ToInt()
"height": storyboard[2].ToInt()
"count": -1
"interval": 5000
"storyboardHeight": storyboard[3].ToInt()
"storyboardWidth": storyboard[4].ToInt()
}]
end if
storyboards = ObjectUtils.Dig(payload, ["storyboards", "playerStoryboardSpecRenderer", "spec"])
if not IsString(storyboards)
return []
end if
storyboardsData = storyboards.Split("|")
if storyboardsData.Count() < 2
return []
end if
baseUrl = storyboardsData.Shift()
storyboards = []
index = 0
for each sb in storyboardsData
sbData = sb.Split("#")
if sbData.Count() <> 8
index += 1
continue for
end if
width = sbData[0].ToInt()
height = sbData[1].ToInt()
_count = sbData[2].ToInt()
columns = sbData[3].ToInt()
rows = sbData[4].ToInt()
interval = sbData[5].ToInt()
name = sbData[6]
sigh = sbData[7]
url = baseUrl
url = url.Replace("$L", `${index}`)
url = url.Replace("$N", name)
queryComponents = UrlUtils.ParseQueryComponents(url)
queryComponents["sigh"] = sigh.DecodeUriComponent()
url = UrlUtils.SetQueryParams(url, queryComponents)
thumbnailsPerImage = columns * rows
imagesCount = _count \ thumbnailsPerImage
if _count mod thumbnailsPerImage > 0
imagesCount += 1
end if
if interval = 0 and _count > 0
interval = Cint(Cdbl(lengthSeconds) * 1000.0 / Cdbl(_count))
end if
storyboards.Push({
"templateUrl": url
"width": width
"height": height
"count": _count
"interval": interval
"storyboardWidth": columns
"storyboardHeight": rows
"storyboardCount": imagesCount
})
index += 1
end for
return storyboards
return Innertube.Search(query, searchFilters, continuation, cancellation)
end function
function ParseCaptions(payload as object) as object
tracks = ObjectUtils.Dig(payload, ["captions", "playerCaptionsTracklistRenderer", "captionTracks"])
if not IsArray(tracks)
return []
end if
function GetTrending(options = invalid as object) as object
cancellation = invalid
params = ""
captions = []
for each track in tracks
if not IsAssociativeArray(track)
continue for
if options <> invalid
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("type")
trendingType = LCase(ValidString(options.type))
baseUrl = track["baseUrl"]
if not IsString(baseUrl)
continue for
end if
queryComponents = UrlUtils.ParseQueryComponents(baseUrl)
queryComponents["fmt"] = "vtt"
baseUrl = UrlUtils.SetQueryParams(baseUrl, queryComponents)
languageCode = track["languageCode"]
if not IsString(languageCode)
continue for
end if
label = ""
name = track["name"]
if IsAssociativeArray(name)
runs = name["runs"]
if IsArray(runs)
for each rn in runs
text = rn["text"]
if IsString(text)
label += text
end if
end for
if trendingType = "music"
params = "4gINGgt5dG1hX2NoYXJ0cw%3D%3D"
else if trendingType = "gaming"
params = "4gIcGhpnYW1pbmdfY29ycHVzX21vc3RfcG9wdWxhcg%3D%3D"
else if trendingType = "movies"
params = "4gIKGgh0cmFpbGVycw%3D%3D"
end if
end if
end if
captions.Push({
"label": label
"language_code": languageCode
"url": baseUrl
})
end for
request = Innertube.CreateBrowseRequest("FEtrending", Innertube.ClientType.WEB, params)
request.Cancellation(cancellation)
return captions
response = request.Await()
if not response.IsSuccess()
return invalid
end if
json = response.Json()
return Innertube.ParseResponse(json)
end function
function ParseInnertubeNextResponse(payload as object, parsedResponse as object) as object
if not parsedResponse.Success
LogWarn("Invalid parsed response", parsedResponse)
return parsedResponse
end if
function GetHome(options = invalid as object) as object
return GetBrowseAuthenticatedPage("FEwhat_to_watch", options)
end function
if not IsArray(parsedResponse.Metadata.recommendedVideos)
LogWarn("Invalid recommended videos", parsedResponse.Metadata.recommendedVideos)
return parsedResponse
end if
function GetSubscriptions(options = invalid as object) as object
return GetBrowseAuthenticatedPage("FEsubscriptions", options)
end function
if not IsAssociativeArray(payload)
LogWarn("Invalid payload", payload)
return parsedResponse
end if
function GetWatchHistory(options = invalid as object) as object
return GetBrowseAuthenticatedPage("FEhistory", options)
end function
endScreenVideos = ObjectUtils.Dig(payload, ["playerOverlays", "playerOverlayRenderer", "endScreen", "watchNextEndScreenRenderer", "results"])
if not IsArray(endScreenVideos)
LogWarn("Invalid end screen videos", endScreenVideos)
return parsedResponse
end if
function GetPlaylists(options = invalid as object) as object
return GetBrowseAuthenticatedPage("FEplaylist_aggregation", options)
end function
for each video in endScreenVideos
videoId = ObjectUtils.Dig(video, ["endScreenVideoRenderer", "videoId"])
if videoId = invalid
LogWarn("Invalid video ID in end screen video", video)
continue for
function GetBrowseAuthenticatedPage(browserId as string, options = invalid as object) as object
cancellation = invalid
access_token = invalid
if options <> invalid
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
if options.DoesExist("access_token")
access_token = options.access_token
end if
end if
title = ValidString(ObjectUtils.Dig(video, ["endScreenVideoRenderer", "title", "simpleText"]))
author = ValidString(ObjectUtils.Dig(video, ["endScreenVideoRenderer", "shortBylineText", "runs", 0, "text"]))
request = Innertube.CreateBrowseRequest(browserId, Innertube.ClientType.Tv)
if access_token <> invalid
request.Header("Authorization", "Bearer " + access_token)
end if
request.Cancellation(cancellation)
parsedResponse.Metadata.recommendedVideos.Push({
"type": "video"
"videoId": videoId
"title": title
"author": author
})
end for
response = request.Await()
if not response.IsSuccess()
return invalid
end if
return parsedResponse
json = response.Json()
return Innertube.ParseResponse(json)
end function
function GetChannel(channelId as string, options = invalid as object) as object
continuation = ""
params = ""
cancellation = invalid
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")
cancellation = options.cancellation
end if
end if
request = Innertube.CreateBrowseRequest(channelId, Innertube.ClientType.Web, params, continuation)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
return invalid
end if
json = response.Json()
return Innertube.ParseChannelPageResponse(json)
end function
function GetPlaylist(playlistId as string, options = invalid as object) as object
continuation = ""
cancellation = invalid
if options <> invalid
if options.DoesExist("continuation")
continuation = options.continuation
end if
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
end if
if not playlistId.StartsWith("VL")
playlistId = "VL" + playlistId
end if
request = Innertube.CreateBrowseRequest(playlistId, Innertube.ClientType.Web, "", continuation)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
return invalid
end if
json = response.Json()
return Innertube.ParsePlaylistPageResponse(json)
end function
function ResolveUrl(url as string, options = invalid as object) as object
cancellation = invalid
if options <> invalid
if options.DoesExist("cancellation")
cancellation = options.cancellation
end if
end if
request = Innertube.CreateResolveUrlRequest(url)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
return invalid
end if
json = response.Json()
return json
end function
function AuthGetCode(cancellation = invalid as object) as object
result = Innertube.GetClientIdentity(cancellation)
if CancellationUtils.IsCancelled(cancellation)
return invalid
end if
result2 = Innertube.GetDeviceAndUserCode(result.client_id, cancellation)
if CancellationUtils.IsCancelled(cancellation)
return invalid
end if
result.Append(result2)
return result
end function
function AuthGetActivationUrl(code as object) as string
return `https://www.youtube.com/tv/activate?user_code=${code.user_code}`
end function
function AuthPollForAccessToken(code as object, cancellation = invalid as object) as object
return Innertube.PollForAccessToken(code, code, cancellation)
end function
function AuthRefreshAccessTokenIfNeeded(accessToken as object, cancellation = invalid as object) as boolean
if not IsAssociativeArray(accessToken)
return false
end if
nowSeconds = TimeUtils.Now().AsSeconds()
expiresTimestamp = accessToken["expires_timestamp"]
if expiresTimestamp = invalid or expiresTimestamp < nowSeconds
refreshed = Innertube.RefreshAccessToken(accessToken, cancellation)
if IsAssociativeArray(refreshed) and refreshed.DoesExist("access_token")
accessToken.Append(refreshed)
if accessToken.DoesExist("expires_in")
accessToken["expires_timestamp"] = TimeUtils.Now().AsSeconds() + accessToken["expires_in"]
end if
return true
end if
end if
return false
end function
function AuthRevokeAccessToken(accessToken as object, cancellation = invalid as object) as boolean
if not IsAssociativeArray(accessToken)
return false
end if
return Innertube.RevokeAccessToken(accessToken["access_token"], cancellation)
end function
end namespace
@@ -0,0 +1,66 @@
namespace Innertube
function CreateNextRequest(videoId as string, ctt as string) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"videoId": videoId
"context": Innertube.CreateContext(Innertube.ClientType.Web, deviceInfo, ctt)
}
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/next?prettyPrint=false&alt=json", payload)
request.Headers({
"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
})
return request
end function
function ParseInnertubeNextResponse(payload as object, parsedResponse as object) as object
if not parsedResponse.Success
LogWarn("Invalid parsed response", parsedResponse)
return parsedResponse
end if
if not IsArray(parsedResponse.Metadata.recommendedVideos)
LogWarn("Invalid recommended videos", parsedResponse.Metadata.recommendedVideos)
return parsedResponse
end if
if not IsAssociativeArray(payload)
LogWarn("Invalid payload", payload)
return parsedResponse
end if
endScreenVideos = ObjectUtils.Dig(payload, ["playerOverlays", "playerOverlayRenderer", "endScreen", "watchNextEndScreenRenderer", "results"])
if not IsArray(endScreenVideos)
LogWarn("Invalid end screen videos", endScreenVideos)
return parsedResponse
end if
for each video in endScreenVideos
videoId = ObjectUtils.Dig(video, ["endScreenVideoRenderer", "videoId"])
if videoId = invalid
LogWarn("Invalid video ID in end screen video", video)
continue for
end if
title = ValidString(ObjectUtils.Dig(video, ["endScreenVideoRenderer", "title", "simpleText"]))
author = ValidString(ObjectUtils.Dig(video, ["endScreenVideoRenderer", "shortBylineText", "runs", 0, "text"]))
parsedResponse.Metadata.recommendedVideos.Push({
"type": "video"
"videoId": videoId
"title": title
"author": author
})
end for
return parsedResponse
end function
end namespace
@@ -0,0 +1,877 @@
import "pkg:/source/utils/ObjectUtils.bs"
namespace Innertube
function ParseNode(nodeData as object, context as object) as void
if IsArray(nodeData)
for each item in nodeData
ParseNode(item, context)
end for
return
end if
if not IsAssociativeArray(nodeData)
return
end if
directives = context["directives"]
for each key in nodeData
directive = directives[key]
if directive = invalid
LogWarn("Unknown node", key)
continue for
end if
subdata = directive(nodeData[key], context)
ParseNode(subdata, context)
end for
end function
function GetParsingDirectives() as object
return {
"twoColumnSearchResultsRenderer": ParseTwoColumnSearchResultsRenderer
"twoColumnBrowseResultsRenderer": ParseTwoColumnBrowseResultsRenderer
"tabRenderer": ParseTabRenderer
"sectionListRenderer": ParseSectionListRenderer
"itemSectionRenderer": ParseItemSectionRenderer
"shelfRenderer": ParseShelfRenderer
"reelShelfRenderer": ParseReelShelfRenderer
"verticalListRenderer": ParseVerticalListRenderer
"horizontalListRenderer": ParseHorizontalListRenderer
"expandedShelfContentsRenderer": ParseExpandedShelfContentsRenderer
"channelFeaturedContentRenderer": ParseChannelFeaturedContentRenderer
"playlistVideoListRenderer": ParsePlaylistVideoListRenderer
"videoRenderer": ParseVideoRenderer
"gridVideoRenderer": ParseGridVideoRenderer
"channelVideoPlayerRenderer": ParseChannelVideoPlayerRenderer
"playlistVideoRenderer": ParsePlaylistVideoRenderer
"channelRenderer": ParseChannelRenderer
"gridChannelRenderer": ParseGridChannelRenderer
"playlistRenderer": ParsePlaylistRenderer
"gridPlaylistRenderer": ParseGridPlaylistRenderer
"lockupViewModel": ParseLockupViewModel
"shortsLockupViewModel": ParseShortsLockupViewModel
"tvBrowseRenderer": ParseTvBrowseRenderer
"tvSurfaceContentRenderer": ParseTvSurfaceContentRenderer
"tvSecondaryNavRenderer": ParseTvSecondaryNavRenderer
"tvSecondaryNavSectionRenderer": ParseTvSecondaryNavSectionRenderer
"tileRenderer": ParseTileRenderer
"gridRenderer": ParseGridRenderer
"richGridRenderer": ParseRichGridRenderer
"richItemRenderer": ParseRichItemRenderer
"continuationItemRenderer": ParseContinuationItemRenderer
"appendContinuationItemsAction": ParseAppendContinuationItemsAction
' Posts not yet supported
"postRenderer": ParseNotImplemented
' a "View all posts" button
"buttonCardViewModel": ParseNotImplemented
' to show chapters of a particular video in the search results
"horizontalCardListRenderer": ParseNotImplemented
' expandableTabRenderer contains the search tab with a channel. Ignored.
"expandableTabRenderer": ParseNotImplemented
"clickTrackingParams": ParseNotImplemented
}
end function
function ParseTwoColumnSearchResultsRenderer(nodeData as object, _context as object) as object
return nodeData["primaryContents"]
end function
function ParseTwoColumnBrowseResultsRenderer(nodeData as object, _context as object) as object
return nodeData["tabs"]
end function
function ParseTabRenderer(nodeData as object, context as object) as object
selected = nodeData["selected"]
if not ValidBool(selected)
return invalid
end if
StartNewFeed(ParseText(nodeData["title"]), context)
return nodeData["content"]
end function
function ParseSectionListRenderer(nodeData as object, _context as object) as object
return nodeData["contents"]
end function
function ParseItemSectionRenderer(nodeData as object, _context as object) as object
return nodeData["contents"]
end function
function ParseShelfRenderer(nodeData as object, _context as object) as object
' TODO: handle shelfRenderer.title
' TODO: handle shelfRenderer.headerRenderer.shelfHeaderRenderer.avatarLockup.avatarLockupRenderer.title
return nodeData["content"]
end function
function ParseReelShelfRenderer(nodeData as object, _context as object) as object
' TODO: handle reelShelfRenderer.title
return nodeData["items"]
end function
function ParseVerticalListRenderer(nodeData as object, _context as object) as object
return nodeData["items"]
end function
function ParseHorizontalListRenderer(nodeData as object, _context as object) as object
' TODO: handle continuations
return nodeData["items"]
end function
function ParseExpandedShelfContentsRenderer(nodeData as object, _context as object) as object
return nodeData["items"]
end function
function ParseChannelFeaturedContentRenderer(nodeData as object, _context as object) as object
return nodeData["items"]
end function
function ParsePlaylistVideoListRenderer(nodeData as object, _context as object) as object
return nodeData["contents"]
end function
function ParseVideoRenderer(nodeData as object, context as object) as object
videoId = nodeData["videoId"]
if not IsString(videoId)
LogWarn("Invalid video ID", nodeData)
return invalid
end if
author = invalid
authorId = invalid
authorPossibleNodes = ["ownerText", "shortBylineText", "longBylineText"]
for each authorPossibleNode in authorPossibleNodes
node = nodeData[authorPossibleNode]
author = ParseText(node)
authorId = ObjectUtils.Dig(node, ["runs", 0, "navigationEndpoint", "browseEndpoint", "browseId"])
if author <> "" and authorId <> invalid
exit for
end if
end for
if StringUtils.IsNullOrEmpty(author) and StringUtils.IsNullOrEmpty(authorId)
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
end if
viewCountText = ParseText(nodeData["shortViewCountText"])
if viewCountText = ""
viewCountText = ParseText(nodeData["viewCountText"])
end if
publishedText = ParseText(nodeData["publishedTimeText"])
lengthText = ParseText(nodeData["lengthText"])
if context.generateVideoThumbnails = true
videoThumbnails = GenerateVideoThumbnails(videoId)
else
videoThumbnails = ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails"])
if videoThumbnails = invalid
videoThumbnails = GenerateVideoThumbnails(videoId)
end if
end if
liveNow = ValidString(ObjectUtils.Dig(nodeData, ["badges", 0, "metadataBadgeRenderer", "icon", "iconType"])) = "LIVE"
if not liveNow
thumbnailOverlays = nodeData["thumbnailOverlays"]
if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays
if ValidString(ObjectUtils.Dig(overlay, ["thumbnailOverlayTimeStatusRenderer", "style"])) = "LIVE"
liveNow = true
exit for
end if
end for
end if
end if
isUpcoming = false
premiereTimestamp = ObjectUtils.Dig(nodeData, ["upcomingEventData", "startTime"])
if IsString(premiereTimestamp)
premiereTimestamp = premiereTimestamp.ToInt()
isUpcoming = true
end if
video = {
"type": "video"
"videoId": videoId
"author": author
"authorId": authorId
"title": ParseText(nodeData["title"])
"videoThumbnails": videoThumbnails
"viewCountText": viewCountText
"publishedText": publishedText
"lengthText": lengthText
"liveNow": liveNow
}
if author <> ""
video["author"] = author
end if
if authorId <> invalid
video["authorId"] = authorId
end if
if isUpcoming
video["isUpcoming"] = true
video["premiereTimestamp"] = premiereTimestamp
end if
PushFeedItem(video, context)
return invalid
end function
function ParseGridVideoRenderer(nodeData as object, context as object) as object
videoId = nodeData["videoId"]
if not IsString(videoId)
LogWarn("Invalid video ID", nodeData)
return invalid
end if
author = invalid
authorId = invalid
authorPossibleNodes = ["ownerText", "shortBylineText", "longBylineText"]
for each authorPossibleNode in authorPossibleNodes
node = nodeData[authorPossibleNode]
author = ParseText(node)
authorId = ObjectUtils.Dig(node, ["runs", 0, "navigationEndpoint", "browseEndpoint", "browseId"])
if author <> "" and authorId <> invalid
exit for
end if
end for
if StringUtils.IsNullOrEmpty(author) and StringUtils.IsNullOrEmpty(authorId)
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
end if
viewCountText = ParseText(nodeData["shortViewCountText"])
if viewCountText = ""
viewCountText = ParseText(nodeData["viewCountText"])
end if
publishedText = ParseText(nodeData["publishedTimeText"])
lengthText = ParseText(nodeData["lengthText"])
if lengthText = ""
thumbnailOverlays = nodeData["thumbnailOverlays"]
if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays
lengthText = ParseText(ObjectUtils.Dig(overlay, ["thumbnailOverlayTimeStatusRenderer", "text"]))
if lengthText <> ""
exit for
end if
end for
end if
end if
if context.generateVideoThumbnails = true
videoThumbnails = GenerateVideoThumbnails(videoId)
else
videoThumbnails = ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails"])
if videoThumbnails = invalid
videoThumbnails = GenerateVideoThumbnails(videoId)
end if
end if
isUpcoming = false
premiereTimestamp = ObjectUtils.Dig(nodeData, ["upcomingEventData", "startTime"])
if IsString(premiereTimestamp)
premiereTimestamp = premiereTimestamp.ToInt()
isUpcoming = true
end if
video = {
"type": "video"
"videoId": videoId
"author": author
"authorId": authorId
"title": ParseText(nodeData["title"])
"videoThumbnails": videoThumbnails
"publishedText": publishedText
"viewCountText": viewCountText
"lengthText": lengthText
}
if isUpcoming
video["isUpcoming"] = true
video["premiereTimestamp"] = premiereTimestamp
end if
PushFeedItem(video, context)
return invalid
end function
function ParseChannelVideoPlayerRenderer(nodeData as object, context as object) as object
videoId = nodeData["videoId"]
if not IsString(videoId)
LogWarn("Invalid video ID", nodeData)
return invalid
end if
author = invalid
authorId = invalid
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
video = {
"type": "video"
"videoId": videoId
"author": author
"authorId": authorId
"title": ParseText(nodeData["title"])
"videoThumbnails": GenerateVideoThumbnails(videoId)
"viewCountText": ParseText(nodeData["viewCountText"])
"publishedText": ParseText(nodeData["publishedTimeText"])
}
PushFeedItem(video, context)
return invalid
end function
function ParsePlaylistVideoRenderer(nodeData as object, context as object) as object
videoId = nodeData["videoId"]
if not IsString(videoId)
LogWarn("Invalid video ID", nodeData)
return invalid
end if
lengthText = ParseText(nodeData["lengthText"])
lengthSeconds = ValidString(nodeData["lengthSeconds"]).ToInt()
author = invalid
authorId = invalid
authorPossibleNodes = ["shortBylineText", "ownerText", "longBylineText"]
for each authorPossibleNode in authorPossibleNodes
node = nodeData[authorPossibleNode]
author = ParseText(node)
authorId = ObjectUtils.Dig(node, ["runs", 0, "navigationEndpoint", "browseEndpoint", "browseId"])
if author <> "" and authorId <> invalid
exit for
end if
end for
if context.generateVideoThumbnails = true
videoThumbnails = GenerateVideoThumbnails(videoId)
else
videoThumbnails = ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails"])
if videoThumbnails = invalid
videoThumbnails = GenerateVideoThumbnails(videoId)
end if
end if
video = {
"type": "video"
"videoId": videoId
"author": author
"authorId": authorId
"title": ParseText(nodeData["title"])
"videoThumbnails": videoThumbnails
"index": ParseText(nodeData["index"]).ToInt()
"lengthText": lengthText
"lengthSeconds": lengthSeconds
}
PushFeedItem(video, context)
return invalid
end function
function ParseChannelRenderer(nodeData as object, context as object) as object
channelId = nodeData["channelId"]
if not IsString(channelId)
LogWarn("Invalid channel ID", nodeData)
return invalid
end if
channel = {
"type": "channel"
"authorId": channelId
"author": ParseText(nodeData["title"])
"authorThumbnails": ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails"])
"subCountText": ParseText(nodeData["subscriberCountText"])
"videoCountText": ParseText(nodeData["videoCountText"])
}
PushFeedItem(channel, context)
return invalid
end function
function ParseGridChannelRenderer(nodeData as object, context as object) as object
channelId = nodeData["channelId"]
if not IsString(channelId)
LogWarn("Invalid channel ID", nodeData)
return invalid
end if
channel = {
"type": "channel"
"authorId": channelId
"author": ParseText(nodeData["title"])
"authorThumbnails": ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails"])
"subCountText": ParseText(nodeData["subscriberCountText"])
"videoCountText": ParseText(nodeData["videoCountText"])
}
PushFeedItem(channel, context)
return invalid
end function
function ParsePlaylistRenderer(nodeData as object, context as object) as object
playlistId = nodeData["playlistId"]
if not IsString(playlistId)
LogWarn("Invalid playlist ID", nodeData)
return invalid
end if
author = invalid
authorId = invalid
authorPossibleNodes = ["shortBylineText", "ownerText", "longBylineText"]
for each authorPossibleNode in authorPossibleNodes
node = nodeData[authorPossibleNode]
author = ParseText(node)
authorId = ObjectUtils.Dig(node, ["runs", 0, "navigationEndpoint", "browseEndpoint", "browseId"])
if author <> "" and authorId <> invalid
exit for
end if
end for
videoCountText = ""
thumbnailOverlays = nodeData["thumbnailOverlays"]
if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays
videoCountText = ParseText(ObjectUtils.Dig(overlay, ["thumbnailOverlayBottomPanelRenderer", "text"]))
if videoCountText <> ""
exit for
end if
end for
end if
if videoCountText = ""
videoCountText = ParseText(nodeData["videoCountText"])
end if
videoCount = ParseText(nodeData["videoCount"]).ToInt()
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": ParseText(nodeData["title"])
"playlistThumbnail": ObjectUtils.Dig(nodeData, ["thumbnails", 0, "thumbnails", 0, "url"])
"author": author
"authorId": authorId
"videoCount": videoCount
"videoCountText": videoCountText
}
PushFeedItem(playlist, context)
return invalid
end function
function ParseGridPlaylistRenderer(nodeData as object, context as object) as object
playlistId = nodeData["playlistId"]
if not IsString(playlistId)
LogWarn("Invalid playlist ID", nodeData)
return invalid
end if
author = invalid
authorId = invalid
authorPossibleNodes = ["shortBylineText", "ownerText", "longBylineText"]
for each authorPossibleNode in authorPossibleNodes
node = nodeData[authorPossibleNode]
author = ParseText(node)
authorId = ObjectUtils.Dig(node, ["runs", 0, "navigationEndpoint", "browseEndpoint", "browseId"])
if author <> "" and authorId <> invalid
exit for
end if
end for
if StringUtils.IsNullOrEmpty(author) and StringUtils.IsNullOrEmpty(authorId)
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
end if
videoCountText = ""
thumbnailOverlays = nodeData["thumbnailOverlays"]
if IsArray(thumbnailOverlays)
for each overlay in thumbnailOverlays
videoCountText = ParseText(ObjectUtils.Dig(overlay, ["thumbnailOverlayBottomPanelRenderer", "text"]))
if videoCountText <> ""
exit for
end if
end for
end if
if videoCountText = ""
videoCountText = ParseText(nodeData["videoCountText"])
end if
if videoCountText = ""
videoCountText = ParseText(nodeData["videoCountShortText"])
end if
videoCount = ParseText(nodeData["videoCount"])
if videoCount = ""
videoCount = ParseText(nodeData["videoCountShortText"])
end if
videoCount = videoCount.ToInt()
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": ParseText(nodeData["title"])
"playlistThumbnail": ObjectUtils.Dig(nodeData, ["thumbnail", "thumbnails", 0, "url"])
"author": author
"authorId": authorId
"videoCount": videoCount
"videoCountText": videoCountText
}
PushFeedItem(playlist, context)
return invalid
end function
function ParseLockupViewModel(nodeData as object, context as object) as object
contentType = ValidString(nodeData["contentType"])
if contentType = "LOCKUP_CONTENT_TYPE_PLAYLIST"
return LockupViewModelTypePlaylist(nodeData, context)
else if contentType = "LOCKUP_CONTENT_TYPE_PODCAST"
return LockupViewModelTypePodcast(nodeData, context)
else if contentType = "LOCKUP_CONTENT_TYPE_ALBUM"
return LockupViewModelTypeAlbum(nodeData, context)
end if
LogWarn("Unknown content type:", contentType, `\n`, nodeData)
return invalid
end function
function LockupViewModelTypePlaylist(nodeData as object, context as object) as object
playlistId = nodeData["contentId"]
if not IsString(playlistId)
LogWarn("Invalid playlist ID", nodeData)
return invalid
end if
metadata = ObjectUtils.Dig(nodeData, ["metadata", "lockupMetadataViewModel"])
title = ObjectUtils.Dig(metadata, ["title", "content"])
thumbnailViewModel = ObjectUtils.Dig(nodeData, ["contentImage", "collectionThumbnailViewModel", "primaryThumbnail", "thumbnailViewModel"])
thumbnail = ObjectUtils.Dig(thumbnailViewModel, ["image", "sources", 0, "url"])
videoCountText = ObjectUtils.Dig(thumbnailViewModel, ["overlays", 0, "thumbnailOverlayBadgeViewModel", "thumbnailBadges", 0, "thumbnailBadgeViewModel", "text"])
author = invalid
authorId = invalid
maybeAuthorNode = ObjectUtils.Dig(nodeData, ["metadata", "lockupMetadataViewModel", "metadata", "contentMetadataViewModel", "metadataRows", 0, "metadataParts", 0, "text"])
maybeAuthorId = ObjectUtils.Dig(maybeAuthorNode, ["commandRuns", 0, "onTap", "innertubeCommand", "browseEndpoint", "browseId"])
if IsString(maybeAuthorId) and maybeAuthorId.StartsWith("UC")
authorId = maybeAuthorId
author = ValidString(maybeAuthorNode["content"])
else if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": title
"author": author
"authorId": authorId
"playlistThumbnail": thumbnail
"videoCountText": videoCountText
}
PushFeedItem(playlist, context)
return invalid
end function
function LockupViewModelTypePodcast(nodeData as object, context as object) as object
playlistId = nodeData["contentId"]
if not IsString(playlistId)
LogWarn("Invalid playlist ID", nodeData)
return invalid
end if
metadata = ObjectUtils.Dig(nodeData, ["metadata", "lockupMetadataViewModel"])
title = ObjectUtils.Dig(metadata, ["title", "content"])
thumbnailViewModel = ObjectUtils.Dig(nodeData, ["contentImage", "collectionThumbnailViewModel", "primaryThumbnail", "thumbnailViewModel"])
thumbnail = ObjectUtils.Dig(thumbnailViewModel, ["image", "sources", 0, "url"])
videoCountText = ObjectUtils.Dig(thumbnailViewModel, ["overlays", 0, "thumbnailOverlayBadgeViewModel", "thumbnailBadges", 0, "thumbnailBadgeViewModel", "text"])
author = invalid
authorId = invalid
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": title
"author": author
"authorId": authorId
"playlistThumbnail": thumbnail
"videoCountText": videoCountText
}
PushFeedItem(playlist, context)
return invalid
end function
function LockupViewModelTypeAlbum(nodeData as object, context as object) as object
playlistId = nodeData["contentId"]
if not IsString(playlistId)
LogWarn("Invalid playlist ID", nodeData)
return invalid
end if
metadata = ObjectUtils.Dig(nodeData, ["metadata", "lockupMetadataViewModel"])
title = ObjectUtils.Dig(metadata, ["title", "content"])
thumbnailViewModel = ObjectUtils.Dig(nodeData, ["contentImage", "collectionThumbnailViewModel", "primaryThumbnail", "thumbnailViewModel"])
thumbnail = ObjectUtils.Dig(thumbnailViewModel, ["image", "sources", 0, "url"])
videoCountText = ObjectUtils.Dig(thumbnailViewModel, ["overlays", 0, "thumbnailOverlayBadgeViewModel", "thumbnailBadges", 0, "thumbnailBadgeViewModel", "text"])
author = invalid
authorId = invalid
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": title
"author": author
"authorId": authorId
"playlistThumbnail": thumbnail
"videoCountText": videoCountText
}
PushFeedItem(playlist, context)
return invalid
end function
function ParseShortsLockupViewModel(nodeData as object, context as object) as object
videoId = ObjectUtils.Dig(nodeData, ["onTap", "innertubeCommand", "reelWatchEndpoint", "videoId"])
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, ["thumbnail", "sources"])
if videoThumbnails = invalid
videoThumbnails = GenerateVideoThumbnails(videoId)
end if
end if
author = invalid
authorId = invalid
if IsString(context.currentAuthor) and IsString(context.currentAuthorId)
author = context.currentAuthor
authorId = context.currentAuthorId
end if
video = {
"type": "video"
"videoId": videoId
"author": author
"authorId": authorId
"title": ObjectUtils.Dig(nodeData, ["overlayMetadata", "primaryText", "content"])
"viewCountText": ObjectUtils.Dig(nodeData, ["overlayMetadata", "secondaryText", "content"])
"videoThumbnails": videoThumbnails
}
PushFeedItem(video, context)
return invalid
end function
function ParseTvBrowseRenderer(nodeData as object, _context as object) as object
return nodeData["content"]
end function
function ParseTvSurfaceContentRenderer(nodeData as object, _context as object) as object
' TODO: handle tvSurfaceContentRenderer.continuation
return nodeData["content"]
end function
function ParseTvSecondaryNavRenderer(nodeData as object, _context as object) as object
return nodeData["sections"]
end function
function ParseTvSecondaryNavSectionRenderer(nodeData as object, _context as object) as object
return nodeData["tabs"]
end function
function ParseTileRenderer(nodeData as object, context as object) as object
contentType = ValidString(nodeData["contentType"])
if contentType = "TILE_CONTENT_TYPE_VIDEO"
return TileRendererTypeVideo(nodeData, context)
else if contentType = "TILE_CONTENT_TYPE_PLAYLIST"
return TileRendererTypePlaylist(nodeData, context)
end if
LogWarn("Unknown content type:", contentType, `\n`, nodeData)
return invalid
end function
function TileRendererTypeVideo(nodeData as object, context as object) as object
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
video = {
"type": "video"
"videoId": videoId
"title": ParseText(ObjectUtils.Dig(nodeData, ["metadata", "tileMetadataRenderer", "title"]))
"videoThumbnails": videoThumbnails
}
PushFeedItem(video, context)
return invalid
end function
function TileRendererTypePlaylist(nodeData as object, context as object) as object
playlistId = nodeData["contentId"]
if not IsString(playlistId)
LogWarn("Invalid playlist ID", nodeData)
return invalid
end if
playlist = {
"type": "playlist"
"playlistId": playlistId
"title": ParseText(ObjectUtils.Dig(nodeData, ["metadata", "tileMetadataRenderer", "title"]))
"playlistThumbnail": ObjectUtils.Dig(nodeData, ["header", "tileHeaderRenderer", "thumbnail", "thumbnails"])
}
PushFeedItem(playlist, context)
return invalid
end function
function ParseGridRenderer(nodeData as object, _context as object) as object
' TODO: handle gridRenderer.continuations
return nodeData["items"]
end function
function ParseRichGridRenderer(nodeData as object, _context as object) as object
return nodeData["contents"]
end function
function ParseRichItemRenderer(nodeData as object, _context as object) as object
return nodeData["content"]
end function
function ParseContinuationItemRenderer(nodeData as object, context as object) as object
continuation = ObjectUtils.Dig(nodeData, ["continuationEndpoint", "continuationCommand", "token"])
if IsString(continuation)
' In Playlists there are 2 continuation items, and one of them is useless...
' TODO:P1 figure this out
if StringUtils.IsNullOrEmpty(context.currentFeed.continuation)
context.currentFeed.continuation = continuation
end if
end if
return invalid
end function
function ParseAppendContinuationItemsAction(nodeData as object, context as object) as object
return nodeData["continuationItems"]
end function
function ParseText(data as object) as string
if data = invalid
return ""
end if
if IsString(data)
return data
end if
if data.DoesExist("simpleText")
return data["simpleText"]
end if
if data.DoesExist("runs")
text = ""
for each _run in data["runs"]
text += _run["text"]
end for
return text
end if
return ""
end function
function StartNewFeed(title as string, context as object) as void
if context.currentFeed <> invalid
if context.currentFeed.items.Count() = 0 and context.currentFeed.title = ""
context.currentFeed.title = title
return
end if
context.feeds.Push(context.currentFeed)
end if
context.currentFeed = {
"title": title
"items": []
}
end function
function PushFeedItem(item as object, context as object) as void
if context.currentFeed = invalid
context.currentFeed = {
"title": ""
"items": []
}
end if
context.currentFeed.items.Push(item)
end function
function ParseNotImplemented(_data as object, _context as object) as object
return invalid
end function
function GenerateVideoThumbnails(videoId as string) as object
return [
{
"quality": "maxres"
"url": `https://i.ytimg.com/vi/${videoId}/maxresdefault.jpg`
"width": 1280
"height": 720
}
{
"quality": "sddefault"
"url": `https://i.ytimg.com/vi/${videoId}/sddefault.jpg`
"width": 640
"height": 480
}
{
"quality": "high"
"url": `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`
"width": 480
"height": 360
}
{
"quality": "medium"
"url": `https://i.ytimg.com/vi/${videoId}/mqdefault.jpg`
"width": 320
"height": 180
}
]
end function
end namespace
@@ -0,0 +1,179 @@
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/TimeUtils.bs"
namespace Innertube
function GetClientIdentity(cancellation = invalid as dynamic) as object
request = HttpClient.Get("https://www.youtube.com/tv")
request.Headers({
"User-Agent": "Mozilla/5.0 (ChromiumStylePlatform) Cobalt/Version"
"Referer": "https://www.youtube.com/tv"
"Accept-Language": "en-US"
})
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
throw `Failed to get client id: ${response.ErrorMessage()}`
end if
text = response.Text()
scriptRegex = /<script\s+id="base-js"\s+src="([^"]+)"[^>]*><\/script>/
match = scriptRegex.Match(text)
if match.Count() < 2
throw "Could not find base-js script"
end if
baseJsUrl = "https://www.youtube.com" + match[1]
request = HttpClient.Get(baseJsUrl)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
throw `Failed to get base js: ${response.ErrorMessage()}`
end if
text = response.Text()
clientIdRegex = /clientId:"(?<client_id>[^"]+)",[^"]*?:"(?<client_secret>[^"]+)"/
match = clientIdRegex.Match(text)
if match.Count() < 3
throw "Could not find client id"
end if
return {
"client_id": match[1]
"client_secret": match[2]
}
end function
function GetDeviceAndUserCode(clientId as string, cancellation = invalid as dynamic) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"client_id": clientId
"scope": "http://gdata.youtube.com https://www.googleapis.com/auth/youtube-paid-content"
"device_id": deviceInfo.GetRandomUUID()
"device_model": "ytlr::"
}
request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/device/code", payload)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
throw `Failed to get device code: ${response.ErrorMessage()}`
end if
responseData = response.Json()
if responseData.DoesExist("error_code")
throw "Failed to get device code: " + ToString(responseData)
end if
if responseData.DoesExist("expires_in")
responseData["expires_timestamp"] = TimeUtils.Now().AsSeconds() + responseData["expires_in"]
end if
return responseData
end function
function PollForAccessToken(clientIdentity as object, deviceAndUserCode as object, cancellation = invalid as dynamic) as object
payload = {
"client_id": clientIdentity.client_id
"client_secret": clientIdentity.client_secret
"code": deviceAndUserCode.device_code
"grant_type": "http://oauth.net/grant_type/device/1.0"
}
intervalMs = deviceAndUserCode.interval * 1000
while true
request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/token", payload)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
errorMessage = response.ErrorMessage()
LogError(errorMessage)
return {
"error": errorMessage
}
end if
responseData = response.Json()
if not responseData.DoesExist("error")
if responseData.DoesExist("expires_in")
responseData["expires_timestamp"] = TimeUtils.Now().AsSeconds() + responseData["expires_in"]
end if
responseData["client_id"] = clientIdentity.client_id
responseData["client_secret"] = clientIdentity.client_secret
return responseData
end if
if responseData.error = "authorization_pending"
LogInfo("Waiting for user to authorize device", responseData)
sleep(intervalMs)
if CancellationUtils.IsCancelled(cancellation)
return invalid
end if
continue while
else if responseData.error = "slow_down"
LogWarn("Polling too fast, slowing down", responseData)
sleep(intervalMs + 3000)
if CancellationUtils.IsCancelled(cancellation)
return invalid
end if
continue while
else if responseData.error = "expired_token"
throw "Failed to get access token: " + ToString(responseData)
else if responseData.error = "access_denied"
throw "Failed to get access token: " + ToString(responseData)
else
throw "Failed to get access token: " + ToString(responseData)
end if
end while
return invalid
end function
function RefreshAccessToken(accessToken as object, cancellation = invalid as dynamic) as object
payload = {
"client_id": accessToken.client_id
"client_secret": accessToken.client_secret
"refresh_token": accessToken.refresh_token
"grant_type": "refresh_token"
}
request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/token", payload)
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
throw `Failed to refresh token: ${response.ErrorMessage()}`
end if
responseData = response.Json()
if responseData.DoesExist("error_code")
throw "Failed to refresh token: " + ToString(responseData)
end if
return responseData
end function
function RevokeAccessToken(accessToken as string, cancellation = invalid as dynamic) as boolean
request = HttpClient.Post("https://www.youtube.com/o/oauth2/revoke", "")
request.QueryParam("token", accessToken)
request.Cancellation(cancellation)
response = request.Await()
success = response.IsSuccess()
if success
LogError(`Failed to revoke token: ${response.ErrorMessage()}`)
end if
return success
end function
end namespace
@@ -0,0 +1,228 @@
import "pkg:/components/Services/Innertube/NodesParser.bs"
import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
namespace Innertube
function ParseResponse(responseData as object, context = invalid as object) as object
if responseData = invalid
return []
end if
containers = GetContainers(responseData)
if containers.Count() = 0
return []
end if
if context = invalid
context = {}
end if
context.Append({
directives: Innertube.GetParsingDirectives()
feeds: []
currentFeed: {
title: ""
items: []
}
generateVideoThumbnails: true
})
Innertube.ParseNode(containers, context)
if context.currentFeed <> invalid and (context.currentFeed.items.Count() > 0 or context.currentFeed.title <> "")
context.feeds.Push(context.currentFeed)
context.currentFeed = invalid
end if
return context.feeds
end function
function ParseChannelPageResponse(responseData as object) as object
if responseData = invalid
return invalid
end if
alert = ObjectUtils.Dig(responseData, ["alerts", 0, "alertRenderer"])
if IsAssociativeArray(alert) and alert.type = "ERROR"
return {
error: ParseText(alert.text)
}
end if
author = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "title"])
authorId = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "externalId"])
thumbnails = ObjectUtils.Dig(responseData, ["metadata", "channelMetadataRenderer", "avatar", "thumbnails"])
if thumbnails = invalid
thumbnails = ObjectUtils.Dig(responseData, ["header", "pageHeaderRenderer", "content", "pageHeaderViewModel", "image", "decoratedAvatarViewModel", "avatar", "avatarViewModel", "image", "sources"])
if thumbnails = invalid
thumbnails = ObjectUtils.Dig(responseData, ["microformat", "microformatDataRenderer", "thumbnail", "thumbnails"])
if thumbnails = invalid
thumbnails = []
end if
end if
end if
banners = ObjectUtils.Dig(responseData, ["header", "pageHeaderRenderer", "content", "pageHeaderViewModel", "banner", "imageBannerViewModel", "image", "sources"])
if banners = invalid
banners = []
end if
authorSubTitle = ""
contentMetadata = ObjectUtils.Dig(responseData, ["header", "pageHeaderRenderer", "content", "pageHeaderViewModel", "metadata", "contentMetadataViewModel"])
if contentMetadata <> invalid
metadataRows = contentMetadata["metadataRows"]
delimiter = ` ${ValidString(contentMetadata["delimiter"])} `
if metadataRows <> invalid
parts = []
for each row in metadataRows
metadataParts = row["metadataParts"]
if metadataParts = invalid
continue for
end if
for each part in metadataParts
text = ObjectUtils.Dig(part, ["text", "content"])
if IsString(text)
parts.Push(text)
end if
end for
end for
if parts.Count() > 0
authorSubTitle = parts.Join(delimiter)
end if
end if
end if
tabsNames = []
tabsParams = {}
tabs = ObjectUtils.Dig(responseData, ["contents", "twoColumnBrowseResultsRenderer", "tabs"])
if tabs <> invalid
for each t in tabs
tabRenderer = t["tabRenderer"]
if tabRenderer = invalid
continue for
end if
tabName = ObjectUtils.Dig(tabRenderer, ["endpoint", "commandMetadata", "webCommandMetadata", "url"])
if tabName = invalid
continue for
end if
tabName = tabName.Split("?")[0]
tabName = tabName.Split("/")
tabName = tabName[tabName.Count() - 1]
if StringUtils.IsNullOrEmpty(tabName)
continue for
end if
tabParams = ObjectUtils.Dig(tabRenderer, ["endpoint", "browseEndpoint", "params"])
if tabParams = invalid
continue for
end if
tabsNames.Push(tabName)
tabsParams[tabName] = tabParams
end for
end if
items = []
continuation = invalid
feeds = ParseResponse(responseData, { "currentAuthor": author, "currentAuthorId": authorId })
if feeds.Count() > 0
items = ValidArray(feeds[0].items)
if feeds[0].DoesExist("continuation")
continuation = feeds[0].continuation
end if
end if
channel = {
"author": author
"authorId": authorId
"authorThumbnails": thumbnails
"authorBanners": banners
"authorSubTitle": authorSubTitle
"tabs": tabsNames
"tabsParams": tabsParams
"items": items
}
if continuation <> invalid
channel["continuation"] = continuation
end if
return channel
end function
function ParsePlaylistPageResponse(responseData as object) as object
if responseData = invalid
return invalid
end if
alert = ObjectUtils.Dig(responseData, ["alerts", 0, "alertRenderer"])
if IsAssociativeArray(alert) and alert.type = "ERROR"
return {
error: ParseText(alert.text)
}
end if
playlistSidebarRendererItems = ObjectUtils.Dig(responseData, ["sidebar", "playlistSidebarRenderer", "items"])
primaryInfo = ObjectUtils.Dig(playlistSidebarRendererItems, [0, "playlistSidebarPrimaryInfoRenderer"])
secondaryInfo = ObjectUtils.Dig(playlistSidebarRendererItems, [1, "playlistSidebarSecondaryInfoRenderer"])
playlistId = ObjectUtils.Dig(primaryInfo, ["navigationEndpoint", "watchEndpoint", "playlistId"])
title = ParseText(ObjectUtils.Dig(primaryInfo, ["title"]))
description = ParseText(ObjectUtils.Dig(primaryInfo, ["description"]))
videoCount = ParseText(ObjectUtils.Dig(primaryInfo, ["stats", 0, "runs", 0, "text"])).ToInt()
thumbnail = ObjectUtils.Dig(primaryInfo, ["thumbnailRenderer", "playlistVideoThumbnailRenderer", "thumbnail", "thumbnails", 0, "url"])
author = ParseText(ObjectUtils.Dig(secondaryInfo, ["videoOwner", "videoOwnerRenderer", "title"]))
authorId = ObjectUtils.Dig(secondaryInfo, ["videoOwner", "videoOwnerRenderer", "navigationEndpoint", "browseEndpoint", "browseId"])
statsText = ""
stats = ObjectUtils.Dig(primaryInfo, ["stats"])
if IsArray(stats)
statsTexts = []
for each stat in stats
statText = ParseText(stat)
if statText <> ""
statsTexts.Push(statText)
end if
end for
statsText = statsTexts.Join(" • ")
end if
playlist = {
"playlistId": playlistId
"title": title
"author": author
"authorId": authorId
"description": description
"videoCount": videoCount
"thumbnail": thumbnail
"videos": []
"statsText": statsText
}
feeds = ParseResponse(responseData)
if feeds.Count() > 0
playlist["videos"] = ValidArray(feeds[0].items)
if feeds[0].DoesExist("continuation")
playlist["continuation"] = feeds[0].continuation
end if
end if
return playlist
end function
function GetContainers(responseData as object) as object
return [
responseData["contents"]
responseData["response"]
responseData["onResponseReceivedActions"]
responseData["onResponseReceivedCommands"]
]
end function
end namespace
@@ -0,0 +1,264 @@
namespace Innertube
function CreatePlayerRequest(videoId as string, ctt as string) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"videoId": videoId
"context": Innertube.CreateContext(Innertube.ClientType.IOS, deviceInfo, ctt)
"playbackContext": {
"contentPlaybackContext": {
"vis": 0
"splay": false
"referer": "https://www.youtube.com/watch?v=" + videoId
"currentUrl": "/watch?v=" + videoId
"autonavState": "STATE_ON"
"autoCaptionsDefaultOn": false
"html5Preference": "HTML5_PREF_WANTS"
"lactMilliseconds": "-1"
}
}
"attestationRequest": {
"omitBotguardData": true
}
"racyCheckOk": true
"contentCheckOk": true
}
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json", payload)
request.Headers({
"accept": "*/*"
"accept-language": "*"
"user-agent": INNERTUBE_IOS_USER_AGENT
"x-youtube-client-name": INNERTUBE_IOS_CLIENT_NAME
"x-youtube-client-version": INNERTUBE_IOS_CLIENT_VERSION
})
return request
end function
function ParseInnertubePlayerResponse(payload as object) as object
if not IsAssociativeArray(payload)
return {
Success: false
Error: "Invalid payload"
}
end if
playabilityStatus = payload["playabilityStatus"]
if not IsAssociativeArray(playabilityStatus)
return {
Success: false
Error: "Invalid playability status"
}
end if
if playabilityStatus["status"] <> "OK"
errorMessage = ""
if IsString(playabilityStatus["reason"])
errorMessage = playabilityStatus["reason"]
end if
subreason = ObjectUtils.Dig(playabilityStatus, ["errorScreen", "playerErrorMessageRenderer", "subreason"])
if IsAssociativeArray(subreason)
subreasonText = ""
runs = subreason["runs"]
if IsArray(runs)
for each rn in runs
text = rn["text"]
if IsString(text)
subreasonText += text
end if
end for
end if
subreason = subreasonText
end if
if IsString(subreason)
errorMessage += `\n` + subreason
end if
if errorMessage = ""
errorMessage = "Video not available"
end if
return {
Success: false
Error: errorMessage
}
end if
videoDetails = payload["videoDetails"]
if not IsAssociativeArray(videoDetails)
return {
Success: false
Error: "Invalid video details"
}
end if
streamingData = payload["streamingData"]
if not IsAssociativeArray(streamingData)
return {
Success: false
Error: "Invalid streaming data"
}
end if
lengthSeconds = videoDetails["lengthSeconds"].ToInt()
videoInfo = {
"type": "video"
"title": videoDetails["title"]
"videoId": videoDetails["videoId"]
"videoThumbnails": videoDetails["thumbnail"]["thumbnails"]
"storyboards": ParseStoryboards(payload, lengthSeconds)
"viewCount": videoDetails["viewCount"].ToInt()
"author": videoDetails["author"]
"authorId": videoDetails["channelId"]
"lengthSeconds": lengthSeconds
"liveNow": ValidBool(videoDetails["isLive"])
"hlsUrl": streamingData["hlsManifestUrl"]
"adaptiveFormats": []
"formatStreams": []
"captions": ParseCaptions(payload)
"recommendedVideos": []
}
return {
Success: true
Metadata: videoInfo
}
end function
function ParseStoryboards(payload as object, lengthSeconds as integer) as object
storyboard = ObjectUtils.Dig(payload, ["storyboards", "playerLiveStoryboardSpecRenderer", "spec"])
if IsString(storyboard)
storyboard = storyboard.Split("#")
if storyboard.Count() <> 5
return []
end if
return [{
"templateUrl": storyboard[0]
"width": storyboard[1].ToInt()
"height": storyboard[2].ToInt()
"count": -1
"interval": 5000
"storyboardHeight": storyboard[3].ToInt()
"storyboardWidth": storyboard[4].ToInt()
}]
end if
storyboards = ObjectUtils.Dig(payload, ["storyboards", "playerStoryboardSpecRenderer", "spec"])
if not IsString(storyboards)
return []
end if
storyboardsData = storyboards.Split("|")
if storyboardsData.Count() < 2
return []
end if
baseUrl = storyboardsData.Shift()
storyboards = []
index = 0
for each sb in storyboardsData
sbData = sb.Split("#")
if sbData.Count() <> 8
index += 1
continue for
end if
width = sbData[0].ToInt()
height = sbData[1].ToInt()
_count = sbData[2].ToInt()
columns = sbData[3].ToInt()
rows = sbData[4].ToInt()
interval = sbData[5].ToInt()
name = sbData[6]
sigh = sbData[7]
url = baseUrl
url = url.Replace("$L", `${index}`)
url = url.Replace("$N", name)
queryComponents = UrlUtils.ParseQueryComponents(url)
queryComponents["sigh"] = sigh.DecodeUriComponent()
url = UrlUtils.SetQueryParams(url, queryComponents)
thumbnailsPerImage = columns * rows
imagesCount = _count \ thumbnailsPerImage
if _count mod thumbnailsPerImage > 0
imagesCount += 1
end if
if interval = 0 and _count > 0
interval = Cint(Cdbl(lengthSeconds) * 1000.0 / Cdbl(_count))
end if
storyboards.Push({
"templateUrl": url
"width": width
"height": height
"count": _count
"interval": interval
"storyboardWidth": columns
"storyboardHeight": rows
"storyboardCount": imagesCount
})
index += 1
end for
return storyboards
end function
function ParseCaptions(payload as object) as object
tracks = ObjectUtils.Dig(payload, ["captions", "playerCaptionsTracklistRenderer", "captionTracks"])
if not IsArray(tracks)
return []
end if
captions = []
for each track in tracks
if not IsAssociativeArray(track)
continue for
end if
baseUrl = track["baseUrl"]
if not IsString(baseUrl)
continue for
end if
queryComponents = UrlUtils.ParseQueryComponents(baseUrl)
queryComponents["fmt"] = "vtt"
baseUrl = UrlUtils.SetQueryParams(baseUrl, queryComponents)
languageCode = track["languageCode"]
if not IsString(languageCode)
continue for
end if
label = ""
name = track["name"]
if IsAssociativeArray(name)
runs = name["runs"]
if IsArray(runs)
for each rn in runs
text = rn["text"]
if IsString(text)
label += text
end if
end for
end if
end if
captions.Push({
"label": label
"language_code": languageCode
"url": baseUrl
})
end for
return captions
end function
end namespace
@@ -0,0 +1,20 @@
namespace Innertube
function CreateResolveUrlRequest(url as string) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
"context": CreateContext(ClientType.Web, deviceInfo, "")
"url": url
}
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/navigation/resolve_url?prettyPrint=false&alt=json", payload)
headers = {
"accept": "*/*"
"accept-language": "*"
}
headers.Append(CreateHeaders(ClientType.Web))
request.Headers(headers)
return request
end function
end namespace
@@ -0,0 +1,79 @@
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/components/Services/Innertube/Parser.bs"
namespace Innertube
function Search(query as string, searchFilters as object, continuation = "" as string, cancellation = invalid as object) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
context: Innertube.CreateContext(Innertube.ClientType.WEB, deviceInfo, "")
}
if continuation <> ""
payload["continuation"] = continuation
else
payload["query"] = query
if searchFilters <> invalid and searchFilters.Count() > 0
params = Innertube.GetEncodedSearchFilters(searchFilters)
if params <> ""
payload["params"] = Innertube.GetEncodedSearchFilters(searchFilters)
end if
end if
end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json", payload)
request.Headers({
"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)
response = request.Await()
if not response.IsSuccess()
return invalid
end if
json = response.Json()
return ParseResponse(json)
end function
function SearchSuggestions(query as string, cancellation = invalid as object) as object
request = HttpClient.Get("https://suggestqueries.google.com/complete/search?hl=en&gl=US&ds=yt&client=youtube&xssi=t&oe=UTF&q=" + query.EncodeUriComponent())
request.Headers({
"user-agent": INNERTUBE_WEB_USER_AGENT
})
request.Cancellation(cancellation)
response = request.Await()
if not response.IsSuccess()
return invalid
end if
text = response.Text()
text = text.Replace(`)]}'`, "")
parsed = ParseJson(text)
if not IsArray(parsed) or parsed.Count() < 2
return invalid
end if
parsed = parsed[1]
suggestions = []
for each suggestion in parsed
sugg = suggestion[0]
if not IsString(sugg)
continue for
end if
suggestions.Push(sugg)
end for
return suggestions
end function
end namespace
@@ -0,0 +1,93 @@
import "pkg:/components/Services/Innertube/protos/params.proto.gen.bs"
namespace Innertube
function GetEncodedSearchFilters(searchFilters as object) as string
searchFiltersObj = {
filters: {}
}
if searchFilters.DoesExist("sort")
sort = searchFilters["sort"]
if sort = "relevance"
searchFiltersObj["sort_by"] = Protobuf.Generated.misc.SortBy.RELEVANCE
else if sort = "rating"
searchFiltersObj["sort_by"] = Protobuf.Generated.misc.SortBy.RATING
else if sort = "views"
searchFiltersObj["sort_by"] = Protobuf.Generated.misc.SortBy.VIEW_COUNT
else if sort = "date"
searchFiltersObj["sort_by"] = Protobuf.Generated.misc.SortBy.UPLOAD_DATE
end if
end if
if searchFilters.DoesExist("date")
date = searchFilters["date"]
if date = "hour"
searchFiltersObj["filters"]["upload_date"] = Protobuf.Generated.misc.UploadDate.HOUR
else if date = "today"
searchFiltersObj["filters"]["upload_date"] = Protobuf.Generated.misc.UploadDate.TODAY
else if date = "week"
searchFiltersObj["filters"]["upload_date"] = Protobuf.Generated.misc.UploadDate.WEEK
else if date = "month"
searchFiltersObj["filters"]["upload_date"] = Protobuf.Generated.misc.UploadDate.MONTH
else if date = "year"
searchFiltersObj["filters"]["upload_date"] = Protobuf.Generated.misc.UploadDate.YEAR
end if
end if
if searchFilters.DoesExist("type")
_type = searchFilters["type"]
if _type = "video"
searchFiltersObj["filters"]["type"] = Protobuf.Generated.misc.SearchType.VIDEO
else if _type = "channel"
searchFiltersObj["filters"]["type"] = Protobuf.Generated.misc.SearchType.CHANNEL
else if _type = "playlist"
searchFiltersObj["filters"]["type"] = Protobuf.Generated.misc.SearchType.PLAYLIST
else if _type = "movie"
searchFiltersObj["filters"]["type"] = Protobuf.Generated.misc.SearchType.MOVIE
end if
end if
if searchFilters.DoesExist("duration")
duration = searchFilters["duration"]
if duration = "short"
searchFiltersObj["filters"]["duration"] = Protobuf.Generated.misc.Duration.SHORT
else if duration = "long"
searchFiltersObj["filters"]["duration"] = Protobuf.Generated.misc.Duration.LONG
else if duration = "medium"
searchFiltersObj["filters"]["duration"] = Protobuf.Generated.misc.Duration.MEDIUM
end if
end if
if searchFilters.DoesExist("features")
features = searchFilters["features"]
for each feature in features
if feature = "hd"
searchFiltersObj["filters"]["features_hd"] = true
else if feature = "subtitles"
searchFiltersObj["filters"]["features_subtitles"] = true
else if feature = "creative_commons"
searchFiltersObj["filters"]["features_creative_commons"] = true
else if feature = "3d"
searchFiltersObj["filters"]["features_3d"] = true
else if feature = "live"
searchFiltersObj["filters"]["features_live"] = true
else if feature = "purchased"
searchFiltersObj["filters"]["features_purchased"] = true
else if feature = "4k"
searchFiltersObj["filters"]["features_4k"] = true
else if feature = "360"
searchFiltersObj["filters"]["features_360"] = true
else if feature = "location"
searchFiltersObj["filters"]["features_location"] = true
else if feature = "hdr"
searchFiltersObj["filters"]["features_hdr"] = true
else if feature = "vr180"
searchFiltersObj["filters"]["features_vr180"] = true
end if
end for
end if
return Protobuf.Generated.misc.encodeSearchFilter(searchFiltersObj)
end function
end namespace
@@ -0,0 +1,58 @@
syntax = "proto3";
package misc;
// https://github.com/LuanRT/YouTube.js/blob/5f83a7416d5dc3167e6af2767e9b90f4bf89f3dc/protos/misc/params.proto#L9-L71
message SearchFilter {
optional SortBy sort_by = 1;
enum SortBy {
RELEVANCE = 0;
RATING = 1;
UPLOAD_DATE = 2;
VIEW_COUNT = 3;
}
message Filters {
optional UploadDate upload_date = 1;
optional SearchType type = 2;
optional Duration duration = 3;
optional bool features_hd = 4;
optional bool features_subtitles = 5;
optional bool features_creative_commons = 6;
optional bool features_3d = 7;
optional bool features_live = 8;
optional bool features_purchased = 9;
optional bool features_4k = 14;
optional bool features_360 = 15;
optional bool features_location = 23;
optional bool features_hdr = 25;
optional bool features_vr180 = 26;
enum UploadDate {
ANY_DATE = 0;
HOUR = 1;
TODAY = 2;
WEEK = 3;
MONTH = 4;
YEAR = 5;
}
enum SearchType {
ANY_TYPE = 0;
VIDEO = 1;
CHANNEL = 2;
PLAYLIST = 3;
MOVIE = 4;
}
enum Duration {
ANY_DURATION = 0;
SHORT = 1;
LONG = 2;
MEDIUM = 3;
}
}
optional Filters filters = 2;
}
@@ -0,0 +1,138 @@
' Auto-generated file - do not modify manually
' md5:dfefe3075a9c6332b6072e7c02fdccf8
import "pkg:/source/Protobuf/BinaryReader.bs"
import "pkg:/source/Protobuf/BinaryWriter.bs"
import "pkg:/source/Protobuf/Decoder.bs"
import "pkg:/source/Protobuf/Encoder.bs"
namespace Protobuf
namespace Generated
namespace misc
enum SortBy
RELEVANCE = 0
RATING = 1
UPLOAD_DATE = 2
VIEW_COUNT = 3
end enum
enum UploadDate
ANY_DATE = 0
HOUR = 1
TODAY = 2
WEEK = 3
MONTH = 4
YEAR = 5
end enum
enum SearchType
ANY_TYPE = 0
VIDEO = 1
CHANNEL = 2
PLAYLIST = 3
MOVIE = 4
end enum
enum Duration
ANY_DURATION = 0
SHORT = 1
LONG = 2
MEDIUM = 3
end enum
function encodeFilters(message as dynamic, asByteArray = false as boolean) as dynamic
buffer = CreateObject("roByteArray")
writer = new Protobuf.BinaryWriter()
writer.SetBuffer(buffer)
encoder = new Protobuf.Encoder(writer)
if message.DoesExist("upload_date")
value = message["upload_date"]
encoder.EncodeInt32(1, value)
end if
if message.DoesExist("type")
value = message["type"]
encoder.EncodeInt32(2, value)
end if
if message.DoesExist("duration")
value = message["duration"]
encoder.EncodeInt32(3, value)
end if
if message.DoesExist("features_hd")
value = message["features_hd"]
encoder.EncodeBool(4, value)
end if
if message.DoesExist("features_subtitles")
value = message["features_subtitles"]
encoder.EncodeBool(5, value)
end if
if message.DoesExist("features_creative_commons")
value = message["features_creative_commons"]
encoder.EncodeBool(6, value)
end if
if message.DoesExist("features_3d")
value = message["features_3d"]
encoder.EncodeBool(7, value)
end if
if message.DoesExist("features_live")
value = message["features_live"]
encoder.EncodeBool(8, value)
end if
if message.DoesExist("features_purchased")
value = message["features_purchased"]
encoder.EncodeBool(9, value)
end if
if message.DoesExist("features_4k")
value = message["features_4k"]
encoder.EncodeBool(14, value)
end if
if message.DoesExist("features_360")
value = message["features_360"]
encoder.EncodeBool(15, value)
end if
if message.DoesExist("features_location")
value = message["features_location"]
encoder.EncodeBool(23, value)
end if
if message.DoesExist("features_hdr")
value = message["features_hdr"]
encoder.EncodeBool(25, value)
end if
if message.DoesExist("features_vr180")
value = message["features_vr180"]
encoder.EncodeBool(26, value)
end if
if asByteArray
return buffer
else
return buffer.ToBase64String().EncodeUriComponent()
end if
end function
function encodeSearchFilter(message as dynamic, asByteArray = false as boolean) as dynamic
buffer = CreateObject("roByteArray")
writer = new Protobuf.BinaryWriter()
writer.SetBuffer(buffer)
encoder = new Protobuf.Encoder(writer)
if message.DoesExist("sort_by")
value = message["sort_by"]
encoder.EncodeInt32(1, value)
end if
if message.DoesExist("filters")
value = message["filters"]
encoder.EncodeMessage(2, Protobuf.Generated.misc.encodeFilters(value, true))
end if
if asByteArray
return buffer
else
return buffer.ToBase64String().EncodeUriComponent()
end if
end function
end namespace
end namespace
end namespace
@@ -0,0 +1,6 @@
<component name="SearchFiltersTestNode" extends="Node">
<interface>
<function name="Innertube_GetEncodedSearchFilters" />
</interface>
<script type="text/brightscript" uri="pkg:/components/Services/Innertube/SearchFilters.bs" />
</component>
@@ -12,7 +12,9 @@ import "pkg:/source/utils/TimeUtils.bs"
namespace Invidious
const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,users"
const DEFAULT_INSTANCE = "https://invidious.nerdvpn.de"
const DEFAULT_INSTANCE = "http://127.0.0.1:8888/playlet-invidious-backend"
const DEFAULT_INSTANCE_NAME = "Playlet built-in backend"
const INSTANCE_EXAMPLE = "https://invidious.example.com"
const TOKEN_CALLBACK = "/invidious/token_callback"
@@ -71,7 +73,13 @@ namespace Invidious
return instance
end if
return DEFAULT_INSTANCE
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
return instance
end function
function MarkVideoWatched(videoId as dynamic) as void
@@ -154,19 +162,25 @@ namespace Invidious
return request.Await()
end function
function GetPlaylist(playlistId as string, index = 0 as integer, 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
if authToken = invalid
instance = m.GetInstance()
url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}`
request = HttpClient.Get(url)
else
' There's no need to use auth, unless the playlist is from Invidious
' (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}`
request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
else
instance = m.GetInstance()
url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}`
request = HttpClient.Get(url)
end if
request.QueryParam("index", index)
if continuation <> ""
request.QueryParam("continuation", continuation)
else
request.QueryParam("index", index)
end if
request.Cancellation(cancellation)
return request.Await()
@@ -205,19 +219,24 @@ namespace Invidious
end if
feedSourceState.paginationType = endpoint.paginationType
if feedSourceState.paginationType = PaginationType.Pages
continuation = feedSourceState.continuation
hasContinuation = not StringUtils.IsNullOrEmpty(continuation)
if not hasContinuation
feedSourceState.queryParams.Delete("continuation")
end if
if feedSourceState.paginationType = PaginationType.Continuation or hasContinuation
if hasContinuation
feedSourceState.queryParams.continuation = continuation
end if
feedSourceState.queryParams.Delete("page")
else if feedSourceState.paginationType = PaginationType.Pages
if not IsInt(feedSourceState.page)
feedSourceState.page = 0
end if
feedSourceState.page += 1
feedSourceState.queryParams.page = feedSourceState.page
else if feedSourceState.paginationType = PaginationType.Continuation
continuation = feedSourceState.continuation
if not StringUtils.IsNullOrEmpty(continuation)
feedSourceState.queryParams.continuation = continuation
else
feedSourceState.queryParams.Delete("continuation")
end if
end if
feedSource.state = feedSourceState
@@ -335,9 +354,12 @@ namespace Invidious
if response.StatusCode() = 200
json = response.Json()
return {
items: json
}
if IsArray(json)
json = {
items: json
}
end if
return json
end if
return invalid
end function
@@ -362,9 +384,13 @@ namespace Invidious
if statusCode = 200
json = response.Json()
return {
result = {
items: json.videos
}
if json.continuation <> invalid
result.continuation = json.continuation
end if
return result
end if
return invalid
end function
@@ -545,6 +571,12 @@ namespace Invidious
videos.push({
"type": "video"
"videoId": item
"videoThumbnails": [{
"quality": "medium"
"url": `https://i.ytimg.com/vi/${item}/mqdefault.jpg`
"width": 320
"height": 180
}]
})
end for
@@ -40,7 +40,7 @@ namespace InvidiousContent
SetIfExists(node, "_author", item, "author")
SetIfExists(node, "authorId", item, "authorId")
SetIfExists(node, "lengthSeconds", item, "lengthSeconds")
node.lengthText = TimeUtils.GetFormattedTime(item.lengthSeconds)
node.lengthText = VideoGetLengthText(item)
node.liveNow = VideoIsLive(item)
VideoSetPremiereTimestampText(node, item)
node.publishedText = VideoGetPublishedText(item)
@@ -75,6 +75,7 @@ namespace InvidiousContent
node.viewCountText = PlaylistGetViewCountText(item)
SetIfExists(node, "updated", item, "updated")
node.updatedText = PlaylistGetUpdatedText(item)
SetIfExists(node, "statsText", item, "statsText")
if item.videos <> invalid
childCount = node.getChildCount()
@@ -99,6 +100,8 @@ namespace InvidiousContent
PlaylistSetThumbnail(node, "thumbnail", item, instance)
PlaylistSetThumbnail(node, "thumbnailBackground", item, instance, "maxres")
node.continuation = ValidString(item.continuation)
return node
end function
@@ -116,11 +119,14 @@ namespace InvidiousContent
SetIfExists(node, "channelHandle", item, "channelHandle")
SetIfExists(node, "description", item, "description")
SetIfExists(node, "subCount", item, "subCount")
SetIfExists(node, "authorSubTitle", item, "authorSubTitle")
node.subCountText = GetChannelSubCountText(item)
SetIfExists(node, "videoCount", item, "videoCount")
node.videoCountText = GetVideoCountText(item)
node.thumbnail = GetChannelThumbnail(item.authorThumbnails)
node.banner = GetChannelBanner(item.authorBanners)
' Important: tabsParams should be set first, because settings that tabs triggers the ChannelView to load feeds
SetIfExists(node, "tabsParams", item, "tabsParams")
SetIfExists(node, "tabs", item, "tabs")
return node
@@ -136,7 +142,7 @@ namespace InvidiousContent
videoThumbnails = videoItem.videoThumbnails
if videoThumbnails = invalid or videoThumbnails.Count() = 0
if StringUtils.IsNullOrEmpty(instance)
node.thumbnail = "pkg:/images/thumbnail-missing.jpg"
node.thumbnail = `https://i.ytimg.com/vi/${videoItem.videoId}/mqdefault.jpg`
else
node.thumbnail = `${instance}/vi/${videoItem.videoId}/mqdefault.jpg`
end if
@@ -230,6 +236,11 @@ namespace InvidiousContent
end function
function VideoGetViewCountText(videoItem as object) as string
viewCountText = videoItem.viewCountText
if not StringUtils.IsNullOrEmpty(viewCountText)
return viewCountText
end if
viewCount = videoItem.viewCount
if viewCount = invalid
return ""
@@ -239,6 +250,11 @@ namespace InvidiousContent
end function
function PlaylistSetThumbnail(node as object, nodeField as string, playlistItem as object, instance as dynamic, quality = "medium" as string) as void
currentThumbnail = node[nodeField]
if currentThumbnail <> "" and currentThumbnail <> "pkg:/images/thumbnail-missing.jpg"
return
end if
thumbnail = ""
if IsString(playlistItem.playlistThumbnail)
thumbnailUrl = playlistItem.playlistThumbnail
@@ -278,6 +294,9 @@ namespace InvidiousContent
end function
function GetVideoCountText(item as object) as string
if not StringUtils.IsNullOrEmpty(item.videoCountText)
return item.videoCountText
end if
videoCount = ValidInt(item.videoCount)
return LocaleUtils.GetPluralString(videoCount, Locale.RowCell.ZeroVideos, Locale.RowCell.OneVideo, Locale.RowCell.NVideos)
end function
@@ -349,6 +368,13 @@ namespace InvidiousContent
end if
end function
function VideoGetLengthText(videoItem as object) as string
if not StringUtils.IsNullOrEmpty(videoItem.lengthText)
return videoItem.lengthText
end if
return TimeUtils.GetFormattedTime(videoItem.lengthSeconds)
end function
function PlaylistGetUpdatedText(playlistItem as object) as string
updated = playlistItem.updated
if not IsInt(updated)
@@ -404,6 +404,17 @@ class LoungeApi
function HandleSetPlaylist(_commandId as integer, commandType as string, commandArgs as object, _messagesToSend as object)
LogDebug(commandType, commandArgs)
' TODO:P2 ctt: credentialTransferToken
' We receive credentialTransferTokens here that can be attached to innertube requests.
' The tokens belong to the user logged in on the mobile app.
' These allow us to watch age restricted videos and private videos.
' They are scoped by video.
' 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.
' These tokens need to be managed better, based on the video they belong to.
if not StringUtils.IsNullOrEmpty(commandArgs.ctt)
m.loungeServiceNode.ctt = commandArgs.ctt
end if
LoungeVideoQueue.SetPlaylist(m.videoQueueNode, m.invService, commandArgs)
end function
@@ -1,5 +1,6 @@
import "pkg:/components/Services/LoungeService/LoungeApi.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
@asynctask
@@ -8,7 +9,7 @@ function LoungeGenerateManualPairingCodeTask(input as object) as object
if StringUtils.IsNullOrEmpty(input.loungeToken)
messagePort = CreateObject("roMessagePort")
loungeService.observeFieldScoped("loungeToken", messagePort)
MessagePortUtils.ObserveFieldScopedExSafe(loungeService, "loungeToken", messagePort)
loungeService.join = true
message = wait(30000, messagePort)
loungeService.unobserveFieldScoped("loungeToken")
@@ -5,6 +5,7 @@
<field id="deviceName" type="string" />
<field id="screenId" type="string" />
<field id="loungeToken" type="string" />
<field id="ctt" type="string" />
<field id="join" type="boolean" alwaysNotify="true" />
<field id="outgoingMessages" type="array" alwaysNotify="true" />
@@ -33,10 +33,7 @@ namespace LoungeVideoQueue
if queueNodesDict.DoesExist(vId)
newQueueNodes.Push(queueNodesDict[vId])
else
payload = {
"type": "video"
"videoId": vId
}
payload = CreateVideoPayload(vId)
if instance = invalid
instance = invService.GetInstance()
@@ -97,10 +94,7 @@ namespace LoungeVideoQueue
preferences = videoQueueNode.preferences
queueNotifications = preferences["misc.queue_notifications"]
if queueNotifications
payload = {
"type": "video"
"videoId": eventVideoId
}
payload = CreateVideoPayload(eventVideoId)
if instance = invalid
instance = invService.GetInstance()
@@ -117,4 +111,36 @@ namespace LoungeVideoQueue
end if
end function
function CreateVideoPayload(videoId as string) as object
return {
"type": "video"
"videoId": videoId
"videoThumbnails": [
{
"quality": "maxres"
"url": `https://i.ytimg.com/vi/${videoId}/maxresdefault.jpg`
"width": 1280
"height": 720
}
{
"quality": "sddefault"
"url": `https://i.ytimg.com/vi/${videoId}/sddefault.jpg`
"width": 640
"height": 480
}
{
"quality": "high"
"url": `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`
"width": 480
"height": 360
}
{
"quality": "medium"
"url": `https://i.ytimg.com/vi/${videoId}/mqdefault.jpg`
"width": 320
"height": 180
}
]
}
end function
end namespace
@@ -109,6 +109,11 @@ function MigrateExistingPreferences(userPrefs as object) as boolean
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_INSTANCES)
end if
if ValidInt(userPrefs.__version) = 0
userPrefs.__version = 1
isDirty = true
end if
if userPrefs.__version = 1
if ValidString(userPrefs["playback.preferred_quality"]) = "medium"
userPrefs["playback.preferred_quality"] = "480p,360p"
@@ -10,7 +10,7 @@ function SponsorBlockTask(input as object) as object
barPath = invalid
if skipSegments <> invalid
barPath = `tmp:/sponsorblock_bar_${videoId}.png`
barPath = `tmp:/sponsorblock_bar.png`
service.GenerateProgressBarBackground(skipSegments, lengthSeconds, barPath)
end if
@@ -1,3 +1,5 @@
import "pkg:/source/utils/StringUtils.bs"
function OnContentSet() as void
content = m.top.itemContent
@@ -7,7 +9,21 @@ function OnContentSet() as void
' NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation.
m.top._author = content._author
m.top.subCountText = content.subCountText
subCountText = content.authorSubTitle
if StringUtils.IsNullOrEmpty(subCountText)
if content.subCount > 0
subCountText = content.subCountText
if StringUtils.IsNullOrEmpty(subCountText)
subCountText = content.videoCountText
end if
else
subCountText = content.videoCountText
if StringUtils.IsNullOrEmpty(subCountText)
subCountText = content.subCountText
end if
end if
end if
m.top.subCountText = subCountText
m.top.channelHandle = content.channelHandle
m.top.thumbnail = content.thumbnail
end function
@@ -20,13 +20,14 @@
<Label
id="authorLabel"
width="196"
font="font:SmallestBoldSystemFont"
maxLines="2"
wrap="true" />
wrap="true"
font="font:SmallestBoldSystemFont" />
<Label
id="subCountLabel"
width="196"
height="25"
maxLines="2"
wrap="true"
font="font:SmallestSystemFont" />
<Label
id="handleLabel"
@@ -19,7 +19,13 @@ function OnContentSet() as void
m.top.thumbnailUri = content.thumbnail
SetVideoCount(content.videoCountText)
videoCountText = content.videoCountText
if content.videoCount = -1 and videoCountText = ""
m.top.videoCountLabelVisible = false
else
m.top.videoCountLabelVisible = true
SetVideoCount(videoCountText)
end if
end function
function SetVideoCount(videoCountText as string) as void
@@ -7,6 +7,7 @@
<field id="updated" type="string" alias="updatedLabel.text" />
<field id="thumbnailUri" type="uri" alias="thumbnail.uri" />
<field id="videoCount" type="string" alias="videoCountLabel.text" />
<field id="videoCountLabelVisible" type="boolean" alias="videoCountLabel.visible" />
</interface>
<children>
<LayoutGroup
@@ -23,19 +23,22 @@ function OnContentSet() as void
if content.isUpcoming = true
m.top.viewCountDate = content.premiereTimestampText
else if not StringUtils.IsNullOrEmpty(content.publishedText)
label = content.publishedText
if not StringUtils.IsNullOrEmpty(content.viewCountText)
label = `${label} • ${content.viewCountText}`
end if
m.top.viewCountDate = label
else
m.top.viewCountDate = ""
publishedText = content.publishedText
viewCountText = content.viewCountText
label = publishedText
if publishedText.Len() > 0 and viewCountText.Len() > 0
label += " • "
end if
label += viewCountText
m.top.viewCountDate = label
end if
m.top.thumbnailUri = content.thumbnail
if ValidInt(content.lengthSeconds) <> 0
if not StringUtils.IsNullOrEmpty(content.lengthText)
SetDurationLabel(content.lengthText, "#161616FF", 0.8, m.smallestSystemFont)
m.top.durationRectVisible = true
else
@@ -55,6 +55,7 @@ function VideoRowListRowContentTask(input as object) as object
end if
feedSource = service.MarkFeedPagination(feedContentNode)
hadContinuation = not StringUtils.IsNullOrEmpty(feedSource.state.continuation)
response = service.MakeRequest(feedSource, feedSource.state.queryParams, m.top.cancellation)
@@ -109,15 +110,13 @@ function VideoRowListRowContentTask(input as object) as object
feedContentNode.appendChildren(itemNodes)
hasContinuation = not StringUtils.IsNullOrEmpty(response.result.continuation)
if hasContinuation
feedSource.state.continuation = response.result.continuation
end if
feedSource.state.continuation = ValidString(response.result.continuation)
if response.result.items.Count() > 0
pageType = feedSource.state.paginationType
if response.result.isLastPage = true
if response.result.isLastPage = true or (hadContinuation and not hasContinuation)
feedSource.state.loadState = FeedLoadState.Loaded
else if pageType = PaginationType.Continuation and hasContinuation
else if hasContinuation
feedSource.state.loadState = FeedLoadState.LoadedPage
else if pageType = PaginationType.Pages
feedSource.state.loadState = FeedLoadState.LoadedPage
@@ -6,6 +6,7 @@ function VideoContentTask(input as object) as object
contentNode = input.content
invidiousNode = input.invidious
preferencesNode = input.preferences
loungeServiceNode = input.loungeService
playletServerPort = input.playletServerPort
if m.top.cancel
@@ -20,7 +21,10 @@ function VideoContentTask(input as object) as object
backend = preferencesNode["playback.backend"]
if backend = "playlet"
response = InnertubeService.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation })
response = InnertubeService.GetVideoMetadata(contentNode.videoId, {
cancellation: m.top.cancellation
ctt: loungeServiceNode.ctt
})
else
response = service.GetVideoMetadata(contentNode.videoId, { cancellation: m.top.cancellation })
end if
@@ -60,6 +64,10 @@ function VideoContentTask(input as object) as object
end if
streamUrls = CreateStreamUrls(metadata, service, preferencesNode, backend, playletServerPort)
' Forwarding query params to HLS playlists is not needed. In fact, it can cause issues
' because the playlist is limited to 4MB, and on large playlists the query params
' significantly increase the size of the playlist, making it cropped.
contentNode.ForwardQueryStringParams = false
contentNode.addFields({
metadata: metadata
' StreamUrls is taken
@@ -152,6 +152,7 @@ function StartVideoContentTask(videoContentNode as object)
content: videoContentNode
invidious: m.top.invidious
preferences: m.top.preferences
loungeService: m.top.loungeService
playletServerPort: m.top.webServer.port
}, OnVideoContentTaskResults)
end function
@@ -1,4 +1,5 @@
import "pkg:/source/services/XmlObject.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
namespace Http
@@ -67,7 +68,7 @@ namespace Http
loungeToken = m.loungeService.loungeToken
if StringUtils.IsNullOrEmpty(loungeToken)
messagePort = CreateObject("roMessagePort")
m.loungeService.observeFieldScoped("loungeToken", messagePort)
MessagePortUtils.ObserveFieldScopedExSafe(m.loungeService, "loungeToken", messagePort)
m.loungeService.join = true
message = wait(30000, messagePort)
m.loungeService.unobserveFieldScoped("loungeToken")
@@ -24,6 +24,7 @@ namespace Http
hlsRequest = HttpClient.Get(url)
headers = request.headers
' Host is probably 127.0.0.1 so we should remove it before hitting the server
headers.Delete("Host")
hlsRequest.Headers(headers)
@@ -43,7 +44,10 @@ namespace Http
hlsManifest = m.AppendStoryboardPlaylists(hlsManifest)
response.http_code = hlsResponse.StatusCode()
response.headers = hlsResponse.Headers()
headers = hlsResponse.Headers()
' We responding with uncompressed data
headers.Delete("Content-Encoding")
response.headers = headers
response.SetBodyDataString(ValidString(hlsManifest))
return true
@@ -0,0 +1,306 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs"
namespace Http
class PlayletInvidiousBackendRouter extends HttpRouter
function new()
super()
end function
@get("/playlet-invidious-backend/authorize_token")
function AuthorizeToken(context as object) as boolean
response = context.response
error = "Playlet built-in Invidious backend is not a real Invidious instance, and does not support accounts."
response.Default(400, error)
return true
end function
@get("/playlet-invidious-backend/api/v1/stats")
function GetStats(context as object) as boolean
response = context.response
error = "Playlet built-in Invidious backend is not a real Invidious instance, and does not support stats."
response.Default(400, error)
return true
end function
@get("/playlet-invidious-backend/api/v1/trending")
function GetTrending(context as object) as boolean
request = context.request
response = context.response
feeds = InnertubeService.GetTrending({ type: request.query.type })
if not IsArray(feeds) or feeds.Count() = 0
response.Default(500, "Failed to get trending feed")
return true
end if
response.Json(ValidArray(feeds[0].items))
return true
end function
@get("/playlet-invidious-backend/api/v1/popular")
function GetPopular(context as object) as boolean
return m.GetTrending(context)
end function
@get("/playlet-invidious-backend/api/v1/search/suggestions")
function GetSearchSuggestions(context as object) as boolean
request = context.request
response = context.response
query = request.query.q
suggestions = InnertubeService.SearchSuggestions(query)
suggestions.query = query
response.Json(suggestions)
return true
end function
@get("/playlet-invidious-backend/api/v1/search")
function GetSearch(context as object) as boolean
request = context.request
response = context.response
query = request.query.q
continuation = request.query.continuation
searchFilters = {}
sort = request.query.sort
if not StringUtils.IsNullOrEmpty(sort)
searchFilters.sort = sort
end if
date = request.query.date
if not StringUtils.IsNullOrEmpty(date)
searchFilters.date = date
end if
_type = request.query.type
if not StringUtils.IsNullOrEmpty(_type)
searchFilters.type = _type
end if
duration = request.query.duration
if not StringUtils.IsNullOrEmpty(duration)
searchFilters.duration = duration
end if
features = request.query.features
if not StringUtils.IsNullOrEmpty(features)
searchFilters.features = features.Split(",")
end if
options = {}
if searchFilters.Count() > 0
options.searchFilters = searchFilters
end if
if not StringUtils.IsNullOrEmpty(continuation)
options.continuation = continuation
end if
feeds = InnertubeService.Search(query, options)
if not IsArray(feeds) or feeds.Count() = 0
response.Default(500, "Failed to search")
return true
end if
response.Json(feeds[0])
return true
end function
@get("/playlet-invidious-backend/api/v1/resolveurl")
function ResolveUrl(context as object) as boolean
request = context.request
response = context.response
url = request.query.url
if StringUtils.IsNullOrEmpty(url)
response.Default(400, "Missing 'url' query parameter")
return true
end if
json = InnertubeService.ResolveUrl(url, response)
if json = invalid
response.Default(500, "Failed to resolve URL")
return true
end if
endpoint = json["endpoint"]
pageType = ValidString(ObjectUtils.Dig(endpoint, ["commandMetadata", "webCommandMetadata", "webPageType"]))
if pageType = "WEB_PAGE_TYPE_UNKNOWN" or pageType = ""
response.Default(400, "Unknown url")
return true
end if
subEndpoint = endpoint["watchEndpoint"]
if subEndpoint = invalid
subEndpoint = endpoint["browseEndpoint"]
if subEndpoint = invalid
subEndpoint = endpoint
end if
end if
params = ObjectUtils.Dig(subEndpoint, ["params"])
result = {
"pageType": pageType
}
browseId = ObjectUtils.Dig(subEndpoint, ["browseId"])
if not StringUtils.IsNullOrEmpty(browseId)
result["ucid"] = browseId
end if
videoId = ObjectUtils.Dig(subEndpoint, ["videoId"])
if not StringUtils.IsNullOrEmpty(videoId)
result["videoId"] = videoId
end if
playlistId = ObjectUtils.Dig(subEndpoint, ["playlistId"])
if not StringUtils.IsNullOrEmpty(playlistId)
result["playlistId"] = playlistId
end if
startTimeSeconds = ObjectUtils.Dig(subEndpoint, ["startTimeSeconds"])
if ValidInt(startTimeSeconds) > 0
result["startTimeSeconds"] = startTimeSeconds
end if
if IsString(params)
result["params"] = params
end if
response.Json(result)
return true
end function
@get("*")
function GetAll(context as object) as boolean
request = context.request
route = request.route
if route.StartsWith("/playlet-invidious-backend/api/v1/videos/")
return m.GetVideo(context)
else if route.StartsWith("/playlet-invidious-backend/api/v1/playlists/")
return m.GetPlaylist(context)
else if route.StartsWith("/playlet-invidious-backend/api/v1/channels/")
return m.GetChannel(context)
end if
return false
end function
function GetVideo(context as object) as boolean
request = context.request
response = context.response
route = request.route
videoId = route.Mid("/playlet-invidious-backend/api/v1/videos/".Len())
playerResponse = InnertubeService.GetVideoMetadata(videoId)
if not playerResponse.IsSuccess()
response.Default(playerResponse.StatusCode(), playerResponse.ErrorMessage())
return true
end if
response.Json(playerResponse.Json())
return true
end function
function GetPlaylist(context as object) as boolean
request = context.request
response = context.response
route = request.route
playlistId = route.Mid("/playlet-invidious-backend/api/v1/playlists/".Len())
options = {}
continuation = request.query.continuation
if not StringUtils.IsNullOrEmpty(continuation)
options.continuation = continuation
end if
playlist = InnertubeService.GetPlaylist(playlistId, options)
if playlist = invalid
response.Default(500, "Failed to get playlist")
return true
end if
index = request.query.index
if not StringUtils.IsNullOrEmpty(index)
index = index.ToInt()
if index > 1
LogError("Playlet backend does not use playlist pagination (use continuation instead)")
playlist.videos = []
end if
end if
response.Json(playlist)
return true
end function
function GetChannel(context as object) as boolean
request = context.request
response = context.response
route = request.route
channelAndTab = route.Mid("/playlet-invidious-backend/api/v1/channels/".Len())
channelAndTab = channelAndTab.Split("/")
options = {}
continuation = request.query.continuation
if not StringUtils.IsNullOrEmpty(continuation)
options.continuation = continuation
end if
if channelAndTab.Count() = 1
channelId = channelAndTab[0]
channel = InnertubeService.GetChannel(channelId, options)
if channel = invalid
response.Default(500, "Failed to get channel")
return true
end if
response.Json(channel)
return true
else if channelAndTab.Count() = 2
channelId = channelAndTab[0]
_tab = channelAndTab[1]
params = request.query.params
if not StringUtils.IsNullOrEmpty(params)
options.params = params
end if
channel = InnertubeService.GetChannel(channelId, options)
if channel = invalid
response.Default(500, "Failed to get channel")
return true
end if
if _tab = "playlists" or _tab = "podcasts" or _tab = "releases"
result = {
"playlists": channel.items
}
if channel.DoesExist("continuation")
result.continuation = channel.continuation
end if
response.Json(result)
else
result = {
"videos": channel.items
}
if channel.DoesExist("continuation")
result.continuation = channel.continuation
end if
response.Json(result)
end if
return true
end if
return false
end function
end class
end namespace
@@ -1,41 +0,0 @@
import "pkg:/source/services/HttpClient.bs"
namespace Http
class ProxyRouter extends HttpRouter
function new(server as object)
super()
task = server.task
m.invidiousNode = task.invidious
m.invidiousService = new Invidious.InvidiousService(m.invidiousNode)
end function
@post("/api/proxy")
function ProxyRequest(context as object) as boolean
request = context.request
response = context.response
requestArgs = request.Json()
if requestArgs = invalid
response.Default(400, "Invalid request body")
return true
end if
httpReq = HttpClient.FromObject(requestArgs)
httpRes = httpReq.Await()
result = {
"status": httpRes.StatusCode()
"headers": httpRes.Headers()
"body": httpRes.Text()
}
response.Json(result)
return true
end function
end class
end namespace
@@ -1,3 +1,4 @@
import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/Types.bs"
namespace Http
@@ -42,7 +43,7 @@ namespace Http
' If the lib_version_latest field is not available, we can give it a few seconds
' To make a request to Github to get the latest version.
msgPort = CreateObject("roMessagePort")
m.applicationInfoNode.observeFieldScoped("lib_version_latest", msgPort)
MessagePortUtils.ObserveFieldScopedExSafe(m.applicationInfoNode, "lib_version_latest", msgPort)
wait(5000, msgPort)
m.applicationInfoNode.unobserveFieldScoped("lib_version_latest")
@@ -7,10 +7,10 @@ import "pkg:/components/Web/PlayletWebServer/Middleware/HlsRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/HomeLayoutRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/HomeRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PlayletLibUrlsRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/PreferencesRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/ProfilesRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/ProxyRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/RegistryRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/SearchHistoryRouter.bs"
import "pkg:/components/Web/PlayletWebServer/Middleware/StateApiRouter.bs"
@@ -55,11 +55,11 @@ function SetupRoutes(server as object)
server.UseRouter(new Http.PlayletLibUrlsRouter(server))
server.UseRouter(new Http.DialRouter(server))
server.UseRouter(new Http.CacheRouter())
server.UseRouter(new Http.ProxyRouter(server))
server.UseRouter(new Http.RegistryRouter(server))
server.UseRouter(new Http.PlayletInvidiousBackendRouter())
etags = new Http.EtagUtils()
server.UseRouter(new Http.HttpStaticFilesRouter("/", "libpkg:/www", etags, { staticFiles: true }))
server.UseRouter(new Http.HttpStaticFilesRouter("/", "libpkg:/www", etags, { staticFiles: true, staticCompressed: true }))
server.UseRouter(new Http.HttpStaticFilesRouter("/config", "libpkg:/config", etags, { staticFiles: true }))
server.UseRouter(new Http.HttpStaticFilesRouter("/locale", "libpkg:/locale", etags, { staticFiles: true }))
server.UseRouter(new Http.HttpStaticFilesRouter("/logs", "cachefs:/logs", etags, { fsCheck: true }))
@@ -11,6 +11,7 @@ namespace Http
private showHidden
private fsCheck
private staticFiles
private staticCompressed
function new(route as string, root as string, etags as object, options = {} as object)
super()
@@ -30,6 +31,8 @@ namespace Http
m.fsCheck = ValidBool(options.fsCheck)
' staticFiles: if true, Etag tags will be cached to skip reading the file entirely.
m.staticFiles = ValidBool(options.staticFiles)
' staticCompressed: the files are .gz and already compressed.
m.staticCompressed = m.staticFiles and ValidBool(options.staticCompressed)
end function
@get("*")
@@ -47,6 +50,10 @@ namespace Http
decoded_path = path_in_route.DecodeUri()
full_path = StringUtils.PathJoin(m.root, decoded_path)
if m.staticCompressed
full_path += ".gz"
end if
if m.staticFiles
' Although we have an Etag middleware, having a check here allows us to
' skip reading the file entirely if the Etag matches.
@@ -69,6 +76,10 @@ namespace Http
if m.staticFiles
m.etags.AddEtagFromBody(request, response, full_path)
end if
if m.staticCompressed
response.headers["Content-Encoding"] = "gzip"
end if
return true
end if
end if
@@ -110,6 +121,9 @@ namespace Http
if m.staticFiles
m.etags.AddEtagFromBody(request, response, full_path)
end if
if m.staticCompressed
response.headers["Content-Encoding"] = "gzip"
end if
return true
else
response.Default(403, "Not a regular file.")
@@ -47,10 +47,6 @@ search:
- channel
- all
arrayType: CommaSeparated
default:
- video
- playlist
- channel
features:
type:
- hd
@@ -169,6 +165,14 @@ channel_releases:
paginationType: Continuation
tryCount: 3
# This is implemented only by Playlet backend.
# Created because auto-generated channels don't have tabs except for "featured"
channel_featured:
title: Channel Home
url: /api/v1/channels/{ucid}/featured
responseHandler: ChannelVideosHandler
paginationType: Continuation
watch_history:
title: Watch history
url: /api/v1/auth/history
+1 -1
View File
@@ -2,7 +2,7 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=32
minor_version=35
build_version=00001
ui_resolutions=hd
@@ -0,0 +1,96 @@
namespace Protobuf
class BinaryReader
private buffer
private position
function SetBuffer(buffer as dynamic) as void
if buffer = invalid
return
end if
if GetInterface(buffer, "ifString") <> invalid
b = CreateObject("roByteArray")
b.FromBase64String(buffer.DecodeUriComponent())
buffer = b
end if
m.buffer = buffer
m.position = 0
end function
function ReadVarInt() as dynamic
value = 0
_shift = 0
while true
byte = m.ReadByte()
if byte = invalid
return invalid
end if
if _shift < 32
value = value or ((byte and &h7F) << _shift)
else
value = value + ((byte and &h7F) * (2 ^ _shift))
end if
_shift += 7
if (byte and &h80) = 0
return value
end if
end while
return invalid
end function
function ReadByte() as dynamic
if m.position >= m.buffer.Count()
return invalid
end if
byte = m.buffer[m.position]
m.position += 1
return byte
end function
function ReadInt32() as dynamic
if m.position + 4 > m.buffer.Count()
return invalid
end if
value = m.buffer[m.position] or (m.buffer[m.position + 1] << 8) or (m.buffer[m.position + 2] << 16) or (m.buffer[m.position + 3] << 24)
m.position += 4
return value
end function
function ReadInt64() as dynamic
if m.position + 8 > m.buffer.Count()
return invalid
end if
value = m.buffer[m.position] or (m.buffer[m.position + 1] << 8) or (m.buffer[m.position + 2] << 16) or (m.buffer[m.position + 3] << 24) or (m.buffer[m.position + 4] << 32) or (m.buffer[m.position + 5] << 40) or (m.buffer[m.position + 6] << 48) or (m.buffer[m.position + 7] << 56)
m.position += 8
return value
end function
function ReadBytes() as dynamic
length = m.ReadVarInt()
if length = invalid
return invalid
end if
endPosition = m.position + length
if endPosition > m.buffer.Count()
return invalid
end if
value = m.buffer.Slice(m.position, endPosition)
m.position += length
return value
end function
function ReadString() as dynamic
bytes = m.ReadBytes()
if bytes = invalid
return invalid
end if
return bytes.ToAsciiString()
end function
end class
end namespace
@@ -0,0 +1,76 @@
namespace Protobuf
class BinaryWriter
private buffer
private position
function SetBuffer(buffer as dynamic) as void
if buffer = invalid
return
end if
if GetInterface(buffer, "ifString") <> invalid
b = CreateObject("roByteArray")
b.FromBase64String(buffer.DecodeUriComponent())
buffer = b
end if
m.buffer = buffer
m.position = 0
end function
function WriteByte(byte as dynamic) as void
m.buffer[m.position] = byte
m.position += 1
end function
function WriteInt32(value as dynamic) as void
m.buffer[m.position] = value and &hFF
m.buffer[m.position + 1] = (value >> 8) and &hFF
m.buffer[m.position + 2] = (value >> 16) and &hFF
m.buffer[m.position + 3] = (value >> 24) and &hFF
m.position += 4
end function
function WriteVarInt(value as dynamic) as void
while true
byte = value and &h7F
value >>= 7
if value = 0
m.WriteByte(byte)
return
end if
m.WriteByte(byte or &h80)
end while
end function
function WriteString(value as dynamic) as void
strBuffer = CreateObject("roByteArray")
strBuffer.FromAsciiString(value)
m.WriteVarInt(strBuffer.Count())
m.WriteByteArrayRaw(strBuffer, 0, strBuffer.Count())
end function
function WriteProtoByteArray(value as dynamic) as void
m.WriteVarInt(value.Count())
m.WriteByteArrayRaw(value, 0, value.Count())
end function
function WriteBool(value as dynamic) as void
if value = true
m.WriteByte(1)
else
m.WriteByte(0)
end if
end function
function WriteByteArrayRaw(buffer as dynamic, index as dynamic, size as dynamic) as void
position = m.position
for i = 0 to size - 1
m.buffer[position + i] = buffer[index + i]
end for
m.position += size
end function
end class
end namespace
@@ -0,0 +1,54 @@
namespace Protobuf
class Decoder
private reader
function new(reader as object)
m.reader = reader
end function
' TODO:P2 decoder is not finished, does not work properly
function DecodeMessage(buffer as object) as dynamic
m.reader.SetBuffer(buffer)
message = {}
while true
field = m.reader.ReadByte()
if field = invalid
exit while
end if
tag = field >> 3
wire_type = field and &h7
value = invalid
if wire_type = 0
value = m.reader.ReadVarInt()
else if wire_type = 1
value = m.reader.ReadInt64()
else if wire_type = 2
value = m.reader.ReadString()
else if wire_type = 5
value = m.reader.ReadInt32()
end if
if value = invalid
return invalid
end if
tagStr = `${tag}`
if message[tagStr] = invalid
message[tagStr] = value
else if GetInterface(message[tagStr], "ifArray") <> invalid
message[tagStr].Push(value)
else
message[tagStr] = [message[tagStr], value]
end if
end while
return message
end function
end class
end namespace
@@ -0,0 +1,47 @@
namespace Protobuf
class Encoder
private writer
function new(writer as object) as void
m.writer = writer
end function
function EncodeString(tag as integer, value as dynamic) as void
m.writer.WriteByte((tag << 3) or 2)
m.writer.WriteString(value)
end function
function EncodeInt32(tag as integer, value as dynamic) as void
m.writer.WriteByte((tag << 3) or 0)
m.writer.WriteVarInt(value)
end function
function EncodeInt64(tag as integer, value as dynamic) as void
m.writer.WriteByte((tag << 3) or 0)
m.writer.WriteInt64(value)
end function
function EncodeFloat(tag as integer, value as dynamic) as void
m.writer.WriteByte((tag << 3) or 5)
m.writer.WriteFloat(value)
end function
function EncodeDouble(tag as integer, value as dynamic) as void
m.writer.WriteByte((tag << 3) or 1)
m.writer.WriteDouble(value)
end function
function EncodeBool(tag as integer, value as dynamic) as void
m.writer.WriteByte((tag << 3) or 0)
m.writer.WriteBool(value)
end function
function EncodeMessage(tag as integer, value as dynamic) as void
m.writer.WriteByte((tag << 3) or 2)
m.writer.WriteProtoByteArray(value)
end function
end class
end namespace
@@ -0,0 +1,40 @@
namespace Tests
@SGNode("SearchFiltersTestNode")
@suite
class SearchFiltersTests extends Rooibos.BaseTestSuite
@describe("SearchFilters")
@it("Encodes search filters")
function _()
testCases = m.GetEncodingTestCases()
for each testCase in testCases
encoded = m.top@.Innertube_GetEncodedSearchFilters(testCase.input)
m.assertEqual(encoded, testCase.encoded)
end for
end function
function GetEncodingTestCases() as object
return [{
input: {
"sort": "date"
}
encoded: "CAISAA%3D%3D"
}, {
input: {
"sort": "views"
"features": ["3d", "hd", "live"]
}
encoded: "CAMSBiABOAFAAQ%3D%3D"
}, {
input: {
"type": "playlist"
}
encoded: "EgIQAw%3D%3D"
}]
end function
end class
end namespace
+24 -29
View File
@@ -5,6 +5,8 @@
' Only use this for debugging purposes.
#const NETWORK_THROTTLE = false
import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Locale.bs"
@@ -281,12 +283,14 @@ namespace HttpClient
function ToCurlCommand() as string
command = `curl "${m.BuildUrl()}"`
if m._method = "HEAD"
command += ` \\\n -I`
command += ` \\\n --head`
else if m._method <> "GET"
command += ` \\\n -X ${m._method}`
command += ` \\\n --request ${m._method}`
end if
command += ` \\\n --max-time ${m._timeoutSeconds}`
command += ` \\\n --location`
command += ` \\\n --show-error`
if COMPRESSION_ENABLED
command += ` \\\n --compressed`
@@ -383,11 +387,7 @@ namespace HttpClient
return m._cancelled
end if
if m._cancellation = invalid or m._cancellation.node = invalid or m._cancellation.field = invalid
return false
end if
if m._cancellation.node[m._cancellation.field] = m._cancellation.value
if CancellationUtils.IsCancelled(m._cancellation)
m._cancelled = true
end if
@@ -471,11 +471,7 @@ namespace HttpClient
throw "Can't await request without a message port. use Send(andForget=false) in order to await request."
end if
if m._cancellation <> invalid
if m._cancellation.node <> invalid and m._cancellation.field <> invalid
m._cancellation.node.ObserveFieldScoped(m._cancellation.field, messagePort)
end if
end if
CancellationUtils.ObserveCancellationScoped(m._cancellation, messagePort)
msg = wait(m._timeoutSeconds * 1000, messagePort)
@@ -485,13 +481,7 @@ namespace HttpClient
#end if
#end if
if m._cancellation <> invalid
if m._cancellation.node <> invalid and m._cancellation.field <> invalid
' TODO:P2 use a separate node as a cancellation token
' This is to avoid removing observers other than our own
m._cancellation.node.UnobserveFieldScoped(m._cancellation.field)
end if
end if
CancellationUtils.UnobserveCancellationScoped(m._cancellation)
if msg = invalid
' timeout
@@ -501,16 +491,10 @@ namespace HttpClient
eventType = type(msg)
if eventType = "roUrlEvent"
LogInfo("Finished ID:", m.urlTransfer.GetIdentity(), "after", m._timer.TotalMilliseconds(), "ms")
else if eventType = "roSGNodeEvent"
node = msg.getRoSGNode()
field = msg.getField()
value = msg.getData()
' cancellation
if node.isSameNode(m._cancellation.node) and field = m._cancellation.field and value = m._cancellation.value
LogInfo("Cancelled", "ID:", m.urlTransfer.GetIdentity())
m._cancelled = true
m.urlTransfer.AsyncCancel()
end if
else if CancellationUtils.IsCancellationEvent(m._cancellation, msg)
LogInfo("Cancelled", "ID:", m.urlTransfer.GetIdentity())
m._cancelled = true
m.urlTransfer.AsyncCancel()
end if
end if
@@ -669,6 +653,17 @@ namespace HttpClient
return invalid
end if
m._json = ParseJson(text)
' TODO:P2 remove workaround after a fix has landed
if m._json = invalid and m.IsSuccess() and not m._json_workaround_tried = true
' A bug was introduced in Roku OS 14.1 that causes ParseJson to return invalid parsing some unicode characters.
' So we filter out \uXXXX characters and try to parse again.
' These characters are mostly emojis, and can't render anyway.
m._json_workaround_tried = true
filter = /\\u[0-9a-fA-F]{4}/
text = filter.ReplaceAll(text, "")
m._json = ParseJson(text)
LogWarn("Failed to parse JSON. Workaround applied. Success:", m._json <> invalid)
end if
return m._json
end function
@@ -0,0 +1,47 @@
import "pkg:/source/utils/Types.bs"
namespace CancellationUtils
function IsCancelled(cancellation as dynamic) as boolean
if cancellation = invalid or cancellation.node = invalid or cancellation.field = invalid
return false
end if
return cancellation.node[cancellation.field] = cancellation.value
end function
function ObserveCancellationScoped(cancellation as dynamic, messagePort as dynamic) as void
if cancellation = invalid or cancellation.node = invalid or cancellation.field = invalid
return
end if
cancellation.node.ObserveFieldScoped(cancellation.field, messagePort)
end function
function UnobserveCancellationScoped(cancellation as dynamic) as void
if cancellation = invalid or cancellation.node = invalid or cancellation.field = invalid
return
end if
cancellation.node.UnobserveFieldScoped(cancellation.field)
end function
function IsCancellationEvent(cancellation as dynamic, message as dynamic) as boolean
messageType = type(message)
if messageType <> "roSGNodeEvent"
return false
end if
if cancellation = invalid or cancellation.node = invalid or cancellation.field = invalid
return false
end if
node = message.getRoSGNode()
if node = invalid or not node.isSameNode(cancellation.node)
return false
end if
return cancellation.field = message.getField() and cancellation.value = message.getData()
end function
end namespace
@@ -0,0 +1,13 @@
namespace MessagePortUtils
function ObserveFieldScopedExSafe(node as dynamic, field as string, port as dynamic)
' ObserveFieldScopedEx was added in 12.0
if FindMemberFunction(node, "ObserveFieldScopedEx") <> invalid
' bs:disable-next-line NO_OBSERVE_FIELD_SCOPED_EX
node.ObserveFieldScopedEx(field, port)
else
node.ObserveFieldScoped(field, port)
end if
end function
end namespace
+6 -2
View File
@@ -1,13 +1,17 @@
namespace ObjectUtils
function Dig(obj as object, keys as object) as object
if obj = invalid
return invalid
end if
for each key in keys
if IsArray(obj) and IsInt(key) and key >= 0 and key < obj.Count()
if (GetInterface(obj, "ifAssociativeArray") <> invalid) and (GetInterface(key, "ifString") <> invalid) and obj.DoesExist(key)
obj = obj[key]
continue for
end if
if IsAssociativeArray(obj) and obj.DoesExist(key)
if (GetInterface(obj, "ifArray") <> invalid) and (GetInterface(key, "ifInt") <> invalid) and key >= 0 and key < obj.Count()
obj = obj[key]
continue for
end if
+2 -2
View File
@@ -5,8 +5,8 @@ namespace TimeUtils
' Helper function convert seconds to [hh:]mm:ss format
' GetFormattedTime(138) returns 2:18
function GetFormattedTime(length as dynamic) as string
if length = invalid or length < 0
return "0:00"
if length = invalid or length <= 0
return ""
end if
hours = length \ 3600
@@ -6,9 +6,9 @@ namespace Tests
@describe("TimeUtils")
@it("formats the time correctly")
@params(invalid, "0:00")
@params(-1, "0:00")
@params(0, "0:00")
@params(invalid, "")
@params(-1, "")
@params(0, "")
@params(7, "0:07")
@params(138, "2:18")
@params(8285, "2:18:05")
+147 -94
View File
@@ -1,34 +1,32 @@
{
"name": "playlet-web",
"version": "0.32.1",
"version": "0.35.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet-web",
"version": "0.32.1",
"dependencies": {
"youtubei.js": "^11.0.1"
},
"version": "0.35.1",
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "3.1.2",
"@tailwindcss/typography": "^0.5.15",
"@tsconfig/svelte": "^5.0.4",
"@vitejs/plugin-legacy": "^5.4.3",
"autoprefixer": "^10.4.20",
"daisyui": "^4.12.14",
"dotenv": "^16.4.5",
"daisyui": "^4.12.22",
"dotenv": "^16.4.7",
"ip": "^2.0.1",
"postcss": "^8.4.49",
"svelte": "4.2.19",
"svelte-check": "^4.1.0",
"svelte-check": "^4.1.1",
"svelte-preprocess": "^6.0.3",
"tailwindcss": "^3.4.15",
"terser": "^5.36.0",
"tailwindcss": "^3.4.17",
"terser": "^5.37.0",
"tslib": "^2.8.1",
"typescript": "^5.7.2",
"vite": "^5.4.11",
"vite-tsconfig-paths": "^5.1.3"
"vite-plugin-compression": "^0.5.1",
"vite-tsconfig-paths": "^5.1.4"
}
},
"node_modules/@alloc/quick-lru": {
@@ -1493,11 +1491,6 @@
"node": ">=6.9.0"
}
},
"node_modules/@bufbuild/protobuf": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.1.0.tgz",
"integrity": "sha512-+2Mx67Y3skJ4NCD/qNSdBJNWtu6x6Qr53jeNg+QcwiL6mt0wK+3jwHH2x1p7xaYH6Ve2JKOVn0OxU35WsmqI9A=="
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.21.5",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
@@ -1866,14 +1859,6 @@
"node": ">=12"
}
},
"node_modules/@fastify/busboy": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz",
"integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==",
"engines": {
"node": ">=14"
}
},
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
@@ -2317,6 +2302,7 @@
"version": "8.11.2",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz",
"integrity": "sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w==",
"dev": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -2592,6 +2578,37 @@
}
]
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"dev": true,
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/chalk/node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dev": true,
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
@@ -2745,10 +2762,11 @@
}
},
"node_modules/daisyui": {
"version": "4.12.14",
"resolved": "https://registry.npmjs.org/daisyui/-/daisyui-4.12.14.tgz",
"integrity": "sha512-hA27cdBasdwd4/iEjn+aidoCrRroDuo3G5W9NDKaVCJI437Mm/3eSL/2u7MkZ0pt8a+TrYF3aT2pFVemTS3how==",
"version": "4.12.22",
"resolved": "https://registry.npmjs.org/daisyui/-/daisyui-4.12.22.tgz",
"integrity": "sha512-HDLWbmTnXxhE1MrMgSWjVgdRt+bVYHvfNbW3GTsyIokRSqTHonUTrxV3RhpPDjGIWaHt+ELtDCTYCtUFgL2/Nw==",
"dev": true,
"license": "MIT",
"dependencies": {
"css-selector-tokenizer": "^0.8",
"culori": "^3",
@@ -2811,9 +2829,9 @@
"dev": true
},
"node_modules/dotenv": {
"version": "16.4.5",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz",
"integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==",
"version": "16.4.7",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz",
"integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==",
"dev": true,
"engines": {
"node": ">=12"
@@ -2977,6 +2995,20 @@
"url": "https://github.com/sponsors/rawify"
}
},
"node_modules/fs-extra": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
"dev": true,
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -3056,6 +3088,21 @@
"integrity": "sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==",
"dev": true
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"dev": true
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"engines": {
"node": ">=8"
}
},
"node_modules/hasown": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz",
@@ -3167,17 +3214,6 @@
"@pkgjs/parseargs": "^0.11.0"
}
},
"node_modules/jintr": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/jintr/-/jintr-3.0.2.tgz",
"integrity": "sha512-5g2EBudeJFOopjAX4exAv5OCCW1DgUISfoioCsm1h9Q9HJ41LmnZ6J52PCsqBlQihsmp0VDuxreAVzM7yk5nFA==",
"funding": [
"https://github.com/sponsors/LuanRT"
],
"dependencies": {
"acorn": "^8.8.0"
}
},
"node_modules/jiti": {
"version": "1.21.6",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.6.tgz",
@@ -3217,6 +3253,18 @@
"node": ">=6"
}
},
"node_modules/jsonfile": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"dev": true,
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
},
"node_modules/kleur": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
@@ -3227,12 +3275,15 @@
}
},
"node_modules/lilconfig": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz",
"integrity": "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==",
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
"integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==",
"dev": true,
"engines": {
"node": ">=10"
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/antonk52"
}
},
"node_modules/lines-and-columns": {
@@ -3629,15 +3680,6 @@
}
}
},
"node_modules/postcss-load-config/node_modules/lilconfig": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.0.0.tgz",
"integrity": "sha512-K2U4W2Ff5ibV7j7ydLr+zLAkIg5JJ4lPn1Ltsdt+Tz/IjQ8buJ55pZAxoP34lqIiwtF9iAvtLv3JGv7CAyAg+g==",
"dev": true,
"engines": {
"node": ">=14"
}
},
"node_modules/postcss-nested": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz",
@@ -4091,6 +4133,18 @@
"node": ">=16 || 14 >=14.17"
}
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/supports-preserve-symlinks-flag": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
@@ -4130,9 +4184,9 @@
}
},
"node_modules/svelte-check": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/svelte-check/-/svelte-check-4.1.0.tgz",
"integrity": "sha512-AflEZYqI578KuDZcpcorPSf597LStxlkN7XqXi38u09zlHODVKd7c+7OuubGzbhgGRUqNTdQCZ+Ga96iRXEf2g==",
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/svelte-check/-/svelte-check-4.1.1.tgz",
"integrity": "sha512-NfaX+6Qtc8W/CyVGS/F7/XdiSSyXz+WGYA9ZWV3z8tso14V2vzjfXviKaTFEzB7g8TqfgO2FOzP6XT4ApSTUTw==",
"dev": true,
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.25",
@@ -4287,10 +4341,11 @@
"dev": true
},
"node_modules/tailwindcss": {
"version": "3.4.15",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.15.tgz",
"integrity": "sha512-r4MeXnfBmSOuKUWmXe6h2CcyfzJCEk4F0pptO5jlnYSIViUkVmsawj80N5h2lO3gwcmSb4n3PuN+e+GC1Guylw==",
"version": "3.4.17",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
"dev": true,
"license": "MIT",
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
"arg": "^5.0.2",
@@ -4301,7 +4356,7 @@
"glob-parent": "^6.0.2",
"is-glob": "^4.0.3",
"jiti": "^1.21.6",
"lilconfig": "^2.1.0",
"lilconfig": "^3.1.3",
"micromatch": "^4.0.8",
"normalize-path": "^3.0.0",
"object-hash": "^3.0.0",
@@ -4349,11 +4404,10 @@
}
},
"node_modules/terser": {
"version": "5.36.0",
"resolved": "https://registry.npmjs.org/terser/-/terser-5.36.0.tgz",
"integrity": "sha512-IYV9eNMuFAV4THUspIRXkLakHnV6XO7FEdtKjf/mDyrnqUg9LnlOn6/RwRvM9SZjR4GUq8Nk8zj67FzVARr74w==",
"version": "5.37.0",
"resolved": "https://registry.npmjs.org/terser/-/terser-5.37.0.tgz",
"integrity": "sha512-B8wRRkmre4ERucLM/uXx4MOV5cbnOlVAqUst+1+iLKPI0dOgFO28f84ptoQt9HEI537PMzfYa/d+GEPKTRXmYA==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"@jridgewell/source-map": "^0.3.3",
"acorn": "^8.8.2",
@@ -4435,7 +4489,8 @@
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true
},
"node_modules/typescript": {
"version": "5.7.2",
@@ -4450,17 +4505,6 @@
"node": ">=14.17"
}
},
"node_modules/undici": {
"version": "5.28.4",
"resolved": "https://registry.npmjs.org/undici/-/undici-5.28.4.tgz",
"integrity": "sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==",
"dependencies": {
"@fastify/busboy": "^2.0.0"
},
"engines": {
"node": ">=14.0"
}
},
"node_modules/unicode-canonical-property-names-ecmascript": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.1.tgz",
@@ -4501,6 +4545,15 @@
"node": ">=4"
}
},
"node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
"dev": true,
"engines": {
"node": ">= 10.0.0"
}
},
"node_modules/update-browserslist-db": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.1.tgz",
@@ -4596,10 +4649,24 @@
}
}
},
"node_modules/vite-plugin-compression": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/vite-plugin-compression/-/vite-plugin-compression-0.5.1.tgz",
"integrity": "sha512-5QJKBDc+gNYVqL/skgFAP81Yuzo9R+EAf19d+EtsMF/i8kFUpNi3J/H01QD3Oo8zBQn+NzoCIFkpPLynoOzaJg==",
"dev": true,
"dependencies": {
"chalk": "^4.1.2",
"debug": "^4.3.3",
"fs-extra": "^10.0.0"
},
"peerDependencies": {
"vite": ">=2.0.0"
}
},
"node_modules/vite-tsconfig-paths": {
"version": "5.1.3",
"resolved": "https://registry.npmjs.org/vite-tsconfig-paths/-/vite-tsconfig-paths-5.1.3.tgz",
"integrity": "sha512-0bz+PDlLpGfP2CigeSKL9NFTF1KtXkeHGZSSaGQSuPZH77GhoiQaA8IjYgOaynSuwlDTolSUEU0ErVvju3NURg==",
"version": "5.1.4",
"resolved": "https://registry.npmjs.org/vite-tsconfig-paths/-/vite-tsconfig-paths-5.1.4.tgz",
"integrity": "sha512-cYj0LRuLV2c2sMqhqhGpaO3LretdtMn/BVX4cPLanIZuwwrkVl+lK84E/miEXkCHWXuq65rhNN4rXsBcOB3S4w==",
"dev": true,
"dependencies": {
"debug": "^4.1.1",
@@ -4749,20 +4816,6 @@
"engines": {
"node": ">= 14"
}
},
"node_modules/youtubei.js": {
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/youtubei.js/-/youtubei.js-11.0.1.tgz",
"integrity": "sha512-ZsbOd+5XF2Ofi3FrLMfYd+f9g9H8xswlouFhjhOqbwT68dMJtX6CRGsHNj5VTFCR/+L/865x1lnUlllB2dDDTA==",
"funding": [
"https://github.com/sponsors/LuanRT"
],
"dependencies": {
"@bufbuild/protobuf": "^2.0.0",
"jintr": "^3.0.2",
"tslib": "^2.5.0",
"undici": "^5.19.1"
}
}
}
}
+8 -10
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.32.1",
"version": "0.35.1",
"type": "module",
"scripts": {
"dev": "vite",
@@ -14,21 +14,19 @@
"@tsconfig/svelte": "^5.0.4",
"@vitejs/plugin-legacy": "^5.4.3",
"autoprefixer": "^10.4.20",
"daisyui": "^4.12.14",
"dotenv": "^16.4.5",
"daisyui": "^4.12.22",
"dotenv": "^16.4.7",
"ip": "^2.0.1",
"postcss": "^8.4.49",
"svelte": "4.2.19",
"svelte-check": "^4.1.0",
"svelte-check": "^4.1.1",
"svelte-preprocess": "^6.0.3",
"tailwindcss": "^3.4.15",
"terser": "^5.36.0",
"tailwindcss": "^3.4.17",
"terser": "^5.37.0",
"tslib": "^2.8.1",
"typescript": "^5.7.2",
"vite": "^5.4.11",
"vite-tsconfig-paths": "^5.1.3"
},
"dependencies": {
"youtubei.js": "^11.0.1"
"vite-plugin-compression": "^0.5.1",
"vite-tsconfig-paths": "^5.1.4"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.
+33 -12
View File
@@ -1,5 +1,7 @@
import { PlayletApi } from "lib/Api/PlayletApi";
const DISABLE_CACHE = true;
export class InvidiousApi {
public instance: string;
public endpoints: any;
@@ -26,7 +28,8 @@ export class InvidiousApi {
return await this.cachedFetch(url, 60 * 60 * 24);
}
public async search(query: string, filters: any, page: number = 1) {
// need to change this
public async search(query: string, filters: any, page: number, continuation: string | undefined) {
// TODO:P2 use a FeedSource similar to brightscript version
let url = `${this.instance}/api/v1/search?q=${encodeURIComponent(query)}&region=${this.userCountryCode}`;
for (let filter in filters) {
@@ -42,9 +45,18 @@ export class InvidiousApi {
url += `&${filter}=${filters[filter].join(',')}`;
}
}
url += `&page=${page}`;
if (continuation) {
url += `&continuation=${encodeURIComponent(continuation)}`;
} else {
url += `&page=${page}`;
}
const response = await fetch(url);
return await response.json();
let json = await response.json();
if (Array.isArray(json)) {
json = { items: json };
}
return json;
}
public async getVideoMetadata(videoId: string) {
@@ -87,19 +99,20 @@ export class InvidiousApi {
feedSourceState.paginationType = endpoint.paginationType
if (feedSourceState.paginationType === "Pages") {
if (!Number.isInteger(feedSourceState.page)) {
feedSourceState.page = 0;
}
feedSourceState.page += 1;
feedSourceState.queryParams.page = feedSourceState.page;
} else if (feedSourceState.paginationType === "Continuation") {
const continuation = feedSourceState.continuation;
const continuation = feedSourceState.continuation;
if (feedSourceState.paginationType === "Continuation" || continuation) {
if (continuation) {
feedSourceState.queryParams.continuation = continuation;
} else {
delete feedSourceState.queryParams.continuation;
}
delete feedSourceState.queryParams.page;
} else if (feedSourceState.paginationType === "Pages") {
if (!Number.isInteger(feedSourceState.page)) {
feedSourceState.page = 0;
}
feedSourceState.page += 1;
feedSourceState.queryParams.page = feedSourceState.page;
}
}
@@ -186,12 +199,17 @@ export class InvidiousApi {
}
private async DefaultHandler(feedSource, responseJson) {
return { items: responseJson };
// if is array
if (Array.isArray(responseJson)) {
responseJson = { items: responseJson };
}
return responseJson;
}
private async PlaylistHandler(feedSource, responseJson) {
return {
items: responseJson.videos,
continuation: responseJson.continuation
};
}
@@ -290,6 +308,9 @@ export class InvidiousApi {
// TODO:P2 use more appropriate cache storage
private getCache(url: string, cacheSeconds: number) {
if (DISABLE_CACHE) {
return null;
}
const cacheKey = this.getCacheKey(url);
const cache = localStorage.getItem(cacheKey);
if (!cache) {
+5
View File
@@ -3,6 +3,11 @@ import { getHost } from "lib/Api/Host";
export class PlayletApi {
static host = () => `http://${getHost()}`
static async getVideoInfo(videoId) {
const response = await fetch(`${PlayletApi.host()}/playlet-invidious-backend/api/v1/videos/${videoId}`);
return await response.json();
}
static async getState() {
const response = await fetch(`${PlayletApi.host()}/api/state`);
return await response.json();
-151
View File
@@ -1,151 +0,0 @@
import { Innertube } from 'youtubei.js/web';
import { getHost } from "lib/Api/Host";
export class YoutubeJs {
static host = () => `http://${getHost()}`
static innerTube: Innertube;
static initPromise: Promise<void>;
static async init() {
if (YoutubeJs.innerTube) {
return;
}
if (YoutubeJs.initPromise) {
return YoutubeJs.initPromise;
}
YoutubeJs.initPromise = new Promise(async (resolve, reject) => {
try {
YoutubeJs.innerTube = await Innertube.create({
// @ts-ignore
fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
const method = init?.method
? init.method
: input instanceof Request
? input.method
: 'GET';
const url = typeof input === 'string'
? new URL(input)
: input instanceof URL
? input
: new URL(input.url);
const headers = init?.headers
? new Headers(init.headers)
: input instanceof Request
? input.headers
: new Headers();
const headersObject = {};
headers.forEach((value, key) => {
headersObject[key] = value;
});
const body = init?.body;
const args = {
Method: method,
Url: url,
Headers: headersObject,
Body: body,
CacheSeconds: -1,
};
const response = await fetch(`http://${getHost()}/api/proxy`, {
headers: {
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(args)
})
const responseData = await response.json();
return new Response(responseData.body, {
status: responseData.status,
statusText: `${responseData.status}`,
headers: responseData.headers,
});
}
});
resolve();
} catch (error) {
console.error(error);
YoutubeJs.innerTube = null;
reject(error);
}
YoutubeJs.initPromise = null;
});
await YoutubeJs.initPromise;
}
static async getVideoInfo(videoId: string) {
await this.init();
const info = await YoutubeJs.innerTube.getBasicInfo(videoId, 'IOS');
console.log('[YTJS] info:', info);
if (info.playability_status.status !== 'OK') {
let errorMessage = "";
if (info.playability_status.reason) {
errorMessage = info.playability_status.reason;
}
if (info.playability_status.error_screen) {
if (info.playability_status.error_screen.hasKey('subreason')) {
const subreason = info.playability_status.error_screen.subreason;
if (subreason?.text && typeof subreason.text === 'string') {
errorMessage += `\n` + subreason.text;
}
}
}
throw new Error(errorMessage);
}
// Populate a video object that is similar to Invidious format.
// Mostly populate only fields we care about, enough to make it work.
return {
type: "video",
title: info.basic_info.title,
videoId: info.basic_info.id,
videoThumbnails: [],
storyboards: [],
description: "",
published: 0,
publishedText: "",
keywords: [],
viewCount: 0,
likeCount: 0,
dislikeCount: 0,
paid: false,
premium: false,
isFamilyFriendly: true,
allowedRegions: [],
genre: "",
genreUrl: null,
author: info.basic_info.author,
authorId: info.basic_info.channel_id,
authorUrl: "",
authorVerified: false,
authorThumbnails: [],
subCountText: "",
lengthSeconds: info.basic_info.duration,
allowRatings: true,
rating: 0,
isListed: true,
liveNow: info.basic_info.is_live,
isPostLiveDvr: info.basic_info.is_post_live_dvr,
isUpcoming: info.basic_info.is_upcoming,
dashUrl: "",
hlsUrl: info.streaming_data.hls_manifest_url,
adaptiveFormats: [],
formatStreams: [],
captions: [],
recommendedVideos: [],
}
}
}
+3 -2
View File
@@ -2,7 +2,7 @@
import { onDestroy, onMount } from "svelte";
import { playletStateStore, tr } from "lib/Stores";
import { InvidiousApi } from "lib/Api/InvidiousApi";
import { YoutubeJs } from "./Api/YoutubeJs";
import { PlayletApi } from "./Api/PlayletApi";
import VideoCastDialog from "./VideoFeed/VideoCastDialog.svelte";
import ChannelCastDialog from "./VideoFeed/ChannelCastDialog.svelte";
import PlaylistCastDialog from "./VideoFeed/PlaylistCastDialog.svelte";
@@ -109,7 +109,7 @@
async function searchForVideoById(videoId, timestamp) {
try {
isLoading = true;
videoMetadata = await YoutubeJs.getVideoInfo(videoId);
videoMetadata = await PlayletApi.getVideoInfo(videoId);
videoStartAtChecked = timestamp !== undefined;
if (videoStartAtChecked) {
videoStartAtTimestamp = timestamp;
@@ -258,6 +258,7 @@
videoThumbnails={videoMetadata?.videoThumbnails}
author={videoMetadata?.author}
lengthSeconds={videoMetadata?.lengthSeconds}
lengthText={videoMetadata?.lengthText}
liveNow={videoMetadata?.liveNow}
isUpcoming={videoMetadata?.isUpcoming}
premiereTimestamp={videoMetadata?.premiereTimestamp}
+5
View File
@@ -43,6 +43,11 @@
) {
version += "-canary";
}
if (version) {
version = `v${version}`;
}
return version;
}
</script>
@@ -100,6 +100,19 @@
);
}
}
function showRemoteNotWorkingDialog() {
// show dialog with instructions
let content = `If the remote control is not working, please check your device settings. Go to:
- Settings
- System
- Advanced System Settings
- Control by mobile apps
- Network access
And set it to "Enabled".`;
alert(content);
}
</script>
<div bind:this={screen} tabindex="-1" class={visibility ? "" : "hidden"}>
@@ -144,5 +157,9 @@
<RemoteButton key={BUTTONS.volumeDown} icon={VolumeDownIcon} small />
<RemoteButton key={BUTTONS.volumeUp} icon={VolumeUpIcon} small />
</div>
<button
on:click={showRemoteNotWorkingDialog}
class="btn btn-xs btn-accent m-4">Remote not working?</button
>
</div>
</div>
@@ -21,6 +21,7 @@
let searchBoxText = "";
let suggestions: { suggestions: any[] } = { suggestions: [] };
let page = 1;
let searchContinuation = "";
let videos = [];
let searchHistory = [];
let isLoading = false;
@@ -85,11 +86,12 @@
async function suggestionClicked(query) {
searchBoxText = query;
page = 1;
searchContinuation = "";
videos = [];
await searchVideos();
await searchVideos("");
}
async function searchVideos() {
async function searchVideos(continuation: string | undefined) {
suggestions = { suggestions: [] };
if (searchBoxText.length === 0) {
return;
@@ -97,12 +99,14 @@
try {
isLoading = true;
const newVideos = await invidiousApi.search(
const response = await invidiousApi.search(
searchBoxText,
searchFilters,
page
page,
continuation
);
videos = [...videos, ...newVideos];
videos = [...videos, ...response.items];
searchContinuation = response.continuation || "";
} finally {
isLoading = false;
}
@@ -122,7 +126,7 @@
e.preventDefault();
page = 1;
videos = [];
await searchVideos();
await searchVideos("");
}}
>
<div class="join w-full border border-neutral rounded-full">
@@ -148,7 +152,7 @@
on:click={async () => {
page = 1;
videos = [];
await searchVideos();
await searchVideos("");
}}
>
<div class="h-6">
@@ -206,7 +210,7 @@
class="btn w-1/2"
on:click={async () => {
page++;
await searchVideos();
await searchVideos(searchContinuation);
}}
>
{$tr("Load more")}
@@ -8,6 +8,9 @@
export let authorThumbnails: any[] | undefined = undefined;
export let channelHandle: string | undefined = undefined;
export let subCount: number | undefined = undefined;
export let subCountText: string | undefined = undefined;
export let videoCountText: string | undefined = undefined;
export let authorSubTitle: string | undefined = undefined;
// svelte-ignore unused-export-let
export let type: string = undefined;
@@ -15,7 +18,17 @@
let modal;
function getSubCountText() {
if (authorSubTitle) {
return authorSubTitle;
}
if (isNaN(subCount) || subCount < 0) {
if (videoCountText) {
return videoCountText;
}
if (subCountText) {
return subCountText;
}
return "";
}
@@ -32,7 +45,7 @@
<div class="card card-compact bg-base-100 shadow-xl border border-neutral">
<ChannelThumbnail bind:author bind:authorThumbnails />
<div class="card-body">
<h3 class="card-title text-base line-clamp-1 min-h-8">{author}</h3>
<h3 class="card-title text-base line-clamp-2 min-h-8">{author}</h3>
<div>{getSubCountText()}</div>
<div>{channelHandle || ""}</div>
</div>
@@ -6,6 +6,7 @@
export let title: string | undefined = undefined;
export let playlistId: string | undefined = undefined;
export let videoCount: number | undefined = undefined;
export let videoCountText: string | undefined = undefined;
export let playlistThumbnail: string | undefined = undefined;
export let videos: any[] | undefined = undefined;
@@ -50,6 +51,7 @@
title,
playlistThumbnail: getPlaylistThumbnail(),
videoCount,
videoCountText,
videos,
};
}
@@ -75,7 +77,7 @@
}
}
if (url === "") {
url = `${invidiousInstance}/vi/-----------/mqdefault.jpg`;
url = `https://i.ytimg.com/vi/-----------/mqdefault.jpg`;
}
return url;
}
@@ -89,6 +91,7 @@
bind:title
bind:playlistThumbnail
bind:videoCount
bind:videoCountText
bind:videos
bind:invidiousInstance
/>
@@ -9,6 +9,7 @@
export let playlistId: string | undefined = undefined;
export let playlistThumbnail: string | undefined = undefined;
export let videoCount: number | undefined = undefined;
export let videoCountText: string | undefined = undefined;
export let videos: any[] | undefined = undefined;
export let updated: number | undefined = undefined;
@@ -84,6 +85,7 @@
bind:title
bind:playlistThumbnail
bind:videoCount
bind:videoCountText
bind:videos
bind:invidiousInstance
/>
@@ -100,5 +102,6 @@
bind:playlistId
bind:playlistThumbnail
bind:videoCount
bind:videoCountText
bind:videos
/>
@@ -3,6 +3,7 @@
export let title: string | undefined = undefined;
export let videoCount: number | undefined = undefined;
export let videoCountText: string | undefined = undefined;
export let playlistThumbnail: string | undefined = undefined;
export let videos: any[] | undefined = undefined;
@@ -31,12 +32,15 @@
}
}
if (url === "") {
url = `${invidiousInstance}/vi/-----------/mqdefault.jpg`;
url = `https://i.ytimg.com/vi/-----------/mqdefault.jpg`;
}
thumbnailUrl = url;
}
function getVideoCountText() {
if (videoCountText) {
return videoCountText;
}
if (isNaN(videoCount) || videoCount < 0) {
return "";
}
@@ -9,6 +9,7 @@
export let videoThumbnails: any[] | undefined = undefined;
export let author: string | undefined = undefined;
export let lengthSeconds: number = undefined;
export let lengthText: string | undefined = undefined;
export let liveNow: boolean = undefined;
export let viewCount: number | undefined = undefined;
export let isUpcoming: boolean = undefined;
@@ -64,6 +65,7 @@
videoThumbnails: getVideoThumbnails(),
author,
lengthSeconds,
lengthText,
liveNow,
viewCount,
timestamp,
@@ -96,6 +98,7 @@
bind:videoThumbnails
bind:liveNow
bind:lengthSeconds
bind:lengthText
bind:viewCount
bind:isUpcoming
bind:premiereTimestamp
@@ -109,6 +112,7 @@
bind:checked={videoStartAtChecked}
bind:timestamp={videoStartAtTimestamp}
{lengthSeconds}
{lengthText}
/>
<div class="join join-vertical m-2">
<button class="btn join-item hover:btn-accent" on:click={playOnTv}>
@@ -16,6 +16,7 @@
export let isUpcoming: boolean = undefined;
export let premiereTimestamp: number | undefined = undefined;
export let lengthSeconds: number = undefined;
export let lengthText: string | undefined = undefined;
export let liveNow: boolean = undefined;
// svelte-ignore unused-export-let
@@ -190,6 +191,7 @@
bind:isUpcoming
bind:premiereTimestamp
bind:lengthSeconds
bind:lengthText
bind:viewCount
bind:invidiousInstance
/>
@@ -214,6 +216,7 @@
bind:title
bind:author
bind:lengthSeconds
bind:lengthText
bind:videoThumbnails
bind:liveNow
bind:isUpcoming
@@ -151,6 +151,7 @@
}
invidiousApi.markFeedSourcePagination(feedSource);
let hadContinuation = !!feedSource.state.continuation;
try {
const result = await invidiousApi.makeRequest(feedSource);
@@ -163,14 +164,14 @@
continue;
}
const hasContinuation = !!result.continuation;
if (hasContinuation) {
feedSource.state.continuation = result.continuation;
}
let hasContinuation = !!result.continuation;
feedSource.state.continuation = result.continuation || "";
if (result.items.length > 0) {
const paginationType = feedSource.state.paginationType;
if (paginationType === "Continuation" && hasContinuation) {
if (hadContinuation && !hasContinuation) {
feedSource.state.loadState = FeedLoadState.Loaded;
} else if (paginationType === "Continuation" && hasContinuation) {
feedSource.state.loadState = FeedLoadState.LoadedPage;
} else if (paginationType === "Pages") {
feedSource.state.loadState = FeedLoadState.LoadedPage;
@@ -3,6 +3,7 @@
export let checked = false;
export let lengthSeconds = undefined;
export let lengthText = undefined;
export let timestamp = 0;
let textInputElemet;
@@ -15,6 +16,12 @@
}
}
$: {
if (lengthSeconds === undefined && lengthText) {
lengthSeconds = getTimeStamp(lengthText);
}
}
$: timestampRange = timestamp !== undefined ? timestamp : 0;
function getTimeStamp(timestampText) {
@@ -6,6 +6,7 @@
export let videoThumbnails: any[] | undefined = undefined;
export let liveNow: boolean = undefined;
export let lengthSeconds: number = undefined;
export let lengthText: string | undefined = undefined;
export let viewCount: number | undefined = undefined;
export let isUpcoming: boolean | undefined = undefined;
export let premiereTimestamp: number | undefined = undefined;
@@ -29,7 +30,11 @@
}
}
function getFormattedTime(length) {
function getFormattedTime(text, length) {
if (text) {
return text;
}
const hours = Math.floor(length / 3600);
const minutes = Math.floor((length / 60) % 60);
const seconds = length % 60;
@@ -80,11 +85,11 @@
>
{$tr("LIVE")}
</div>
{:else if lengthSeconds}
{:else if lengthSeconds || lengthText}
<div
class="absolute bottom-2 right-0 bg-black/70 text-white text-sm rounded-sm pt-1 pb-1 pr-2 pl-2"
>
{getFormattedTime(lengthSeconds)}
{getFormattedTime(lengthText, lengthSeconds)}
</div>
{/if}
</figure>
+4
View File
@@ -1,5 +1,6 @@
import { defineConfig, UserConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import viteCompression from 'vite-plugin-compression';
import tsconfigPaths from 'vite-tsconfig-paths'
import ip from 'ip';
import { existsSync, readFileSync } from 'fs'
@@ -15,6 +16,9 @@ const config: UserConfig = {
svelte(),
legacy({
targets: ['defaults', 'not IE 11'],
}),
viteCompression({
deleteOriginFile: true
})
],
build: {
+255
View File
@@ -0,0 +1,255 @@
// This plugin generate brighterscript proto from .proto files
import {
CompilerPlugin,
Program,
} from 'brighterscript';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { globSync } from 'glob';
import path from 'path';
import md5 from 'crypto-js/md5';
import { Formatter, Runner } from 'brighterscript-formatter';
const protobufSchema = require('protocol-buffers-schema')
export class ProtoGenPlugin implements CompilerPlugin {
public name = 'ProtoGenPlugin';
afterProgramCreate(program: Program) {
// @ts-ignore
program.options.forceGenerateProtos = true;
// Force generate flag
// @ts-ignore
const forceGenerateProtos = !!program.options.forceGenerateProtos;
const rootDir = program.options.rootDir!;
const protoFiles = globSync(`**/*.proto`, { cwd: rootDir })
.map((protoFile) => path.join(rootDir, protoFile));
const formatter = this.createFormatter(rootDir);
protoFiles.forEach((protoFile) => {
this.generateProtoIfNeeded(program, protoFile, protoFile + '.gen.bs', formatter, forceGenerateProtos);
});
}
generateProtoIfNeeded(program: Program, protoFile: string, outputFile: string, formatter: Formatter, forceGenerateProtos: boolean) {
program.logger.info(`Generating proto from ${protoFile}`);
const protoContent = readFileSync(protoFile, 'binary');
const protoHash = md5(protoContent).toString();
if (!forceGenerateProtos && existsSync(outputFile)) {
const firstLine = readFileSync(outputFile, 'utf8').split('\n')[1];
const outputHash = firstLine?.split('md5:')[1]?.trim();
if (outputHash === protoHash) {
return;
}
}
const generatedContent = this.generateProto(protoContent, protoHash, outputFile);
const formattedContent = formatter.format(generatedContent);
writeFileSync(outputFile, formattedContent);
}
generateProto(protoContent: any, protoHash: string, outputFile: string): string {
const protoSchema = protobufSchema.parse(protoContent);
const fullNameSpace = `Protobuf.Generated.${protoSchema.package}`;
const content = `' Auto-generated file - do not modify manually
' md5:${protoHash}
import "pkg:/source/Protobuf/Decoder.bs"
import "pkg:/source/Protobuf/Encoder.bs"
import "pkg:/source/Protobuf/BinaryReader.bs"
import "pkg:/source/Protobuf/BinaryWriter.bs"
namespace Protobuf
namespace Generated
namespace ${protoSchema.package}
${this.generateEnums(protoSchema)}
${this.generateCreateFunctions(protoSchema, fullNameSpace)}
${this.generateEncodeFunctions(protoSchema, fullNameSpace)}
${this.generateDecodeFunctions(protoSchema, fullNameSpace)}
end namespace
end namespace
end namespace
`;
return content;
}
generateEnums(protoSchema: any) {
const enums = this.getAllEnums(protoSchema);
return enums.map((enumType: any) => {
return `enum ${enumType.name}
${Object.entries(enumType.values).map(([key, value]: [string, any]) => {
return `${key} = ${value.value}`;
}).join('\n')}
end enum`;
}).join('\n\n');
}
getAllEnums(protoSchema: any) {
function collectEnums(messages: any[]): any[] {
return messages.reduce((acc: any, message: any) => {
return acc.concat(message.enums, collectEnums(message.messages));
}, []);
}
return collectEnums(protoSchema.messages).concat(protoSchema.enums);
}
generateCreateFunctions(protoSchema: any, fullNameSpace: string): string {
// not needed for now
return "";
function generateCreateFunction(message: any): string {
const innerTypes = message.messages.map((msg: any) => msg.name);
const fieldsInitialization = message.fields.map((field: any) => {
if (innerTypes.includes(field.type)) {
return `${field.name}: ${fullNameSpace}.create${field.type}()`;
} else {
return `${field.name}: ${ProtoGenPlugin.getDefaultValue(field.type)}`;
}
}).join('\n');
return `function create${message.name}() as dynamic
return {
${fieldsInitialization}
}
end function`;
}
const createFunctions = protoSchema.messages.map((message: any) => {
return this.generateCreateFunctions(message, fullNameSpace);
})
if (protoSchema.name) {
createFunctions.push(generateCreateFunction(protoSchema));
}
return createFunctions.join('\n\n');
}
generateEncodeFunctions(protoSchema: any, fullNameSpace: string) {
const enums = this.getAllEnums(protoSchema).map((enumType: any) => enumType.name);
function generateEncodeFunction(message: any): string {
const innerTypes = message.messages.map((msg: any) => msg.name);
const encodeFields = message.fields.map((field: any) => {
let fieldEncode = `if message.DoesExist("${field.name}")\n`;
if (field.repeated) {
fieldEncode += `for each value in message["${field.name}"]\n`;
} else {
fieldEncode += `value = message["${field.name}"]\n`;
}
if (innerTypes.includes(field.type)) {
fieldEncode += `encoder.EncodeMessage(${field.tag}, ${fullNameSpace}.encode${field.type}(value, true))\n`;
}
else if (enums.includes(field.type)) {
fieldEncode += `encoder.EncodeInt32(${field.tag}, value)\n`;
} else {
fieldEncode += `encoder.${ProtoGenPlugin.getEncoderFunction(field.type)}(${field.tag}, value)\n`;
}
if (field.repeated) {
fieldEncode += 'end for\n';
}
return fieldEncode + 'end if';
}).join('\n');
return `function encode${message.name}(message as dynamic, asByteArray = false as boolean) as dynamic
buffer = CreateObject("roByteArray")
writer = new Protobuf.BinaryWriter()
writer.SetBuffer(buffer)
encoder = new Protobuf.Encoder(writer)
${encodeFields}
if asByteArray
return buffer
else
return buffer.ToBase64String().EncodeUriComponent()
end if
end function`;
}
const encodeFunctions = protoSchema.messages.map((message: any) => {
return this.generateEncodeFunctions(message, fullNameSpace);
});
if (protoSchema.name) {
encodeFunctions.push(generateEncodeFunction(protoSchema));
}
return encodeFunctions.join('\n\n');
}
generateDecodeFunctions(protoSchema: any, fullNameSpace: string) {
// unfinished, and not needed for now
return "";
let decodeFunctions = protoSchema.messages.map((message: any) => {
return `function decode${message.name}(data as dynamic) as dynamic
obj = ${fullNameSpace}.create${message.name}()
decoder = new Protobuf.Decoder(new Protobuf.BinaryReader())
decoded = decoder.DecodeMessage(data)
` + message.fields.map((field: any) => {
return `if decoded.DoesExist("${field.tag}")
obj["${field.name}"] = decoded["${field.tag}"]
end if`;
}).join('\n') + `
return obj
end function`;
}).join('\n\n');
return decodeFunctions;
}
static getDefaultValue(type: string): any {
switch (type) {
case 'string': return '""';
case 'int32': return '0';
case 'int64': return '0';
case 'float': return '0.0';
case 'double': return '0.0';
case 'bool': return 'false';
default: return 'invalid';
}
}
static getEncoderFunction(type: string): string {
switch (type) {
case 'string': return 'EncodeString';
case 'int32': return 'EncodeInt32';
case 'int64': return 'EncodeInt64';
case 'float': return 'EncodeFloat';
case 'double': return 'EncodeDouble';
case 'bool': return 'EncodeBool';
default: throw new Error(`Unknown type ${type}`);
}
}
createFormatter(rootDir: string) {
const bsfmtPath = path.join(rootDir, '../../config/bsfmt.jsonc');
const runner = new Runner();
const options = runner.getBsfmtOptions({
files: [],
bsfmtPath: bsfmtPath
});
return new Formatter(options);
}
}
export default () => {
return new ProtoGenPlugin();
};
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more