Compare commits

..
6 Commits
Author SHA1 Message Date
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
35 changed files with 980 additions and 37 deletions

No files matched your search

+11
View File
@@ -5,6 +5,17 @@ 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.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
+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.34.1
version: 0.35.0
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.
+9 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet",
"version": "0.34.1",
"version": "0.35.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet",
"version": "0.34.1",
"version": "0.35.0",
"hasInstallScript": true,
"devDependencies": {
"@rokucommunity/bslint": "^0.8.27",
@@ -28,6 +28,7 @@
"ip": "^2.0.1",
"json5": "^2.2.3",
"mailparser": "^3.7.2",
"protocol-buffers-schema": "^3.6.0",
"roku-deploy": "^3.12.3",
"rooibos-roku": "5.14.0",
"rounded-rect-9patch": "^1.1.2",
@@ -4825,6 +4826,12 @@
"node": ">=0.4.0"
}
},
"node_modules/protocol-buffers-schema": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.0.tgz",
"integrity": "sha512-TdDRD+/QNdrCGCE7v8340QyuXd4kIWIgapsE2+n/SaGiSSbomYl4TjHlvIoCWRpE7wFt02EpB35VVA2ImcBVqw==",
"dev": true
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet",
"version": "0.34.1",
"version": "0.35.0",
"description": "Unofficial YouTube client for Roku",
"devDependencies": {
"@rokucommunity/bslint": "^0.8.27",
@@ -22,6 +22,7 @@
"ip": "^2.0.1",
"json5": "^2.2.3",
"mailparser": "^3.7.2",
"protocol-buffers-schema": "^3.6.0",
"roku-deploy": "^3.12.3",
"rooibos-roku": "5.14.0",
"rounded-rect-9patch": "^1.1.2",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-app",
"version": "0.34.1",
"version": "0.35.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-app",
"version": "0.34.1"
"version": "0.35.0"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-app",
"version": "0.34.1",
"version": "0.35.0",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "rm -rf ../build/playlet-app",
+2 -2
View File
@@ -2,8 +2,8 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=34
build_version=00001
minor_version=35
build_version=00000
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-lib",
"version": "0.34.1",
"version": "0.35.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-lib",
"version": "0.34.1"
"version": "0.35.0"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-lib",
"version": "0.34.1",
"version": "0.35.0",
"description": "Unofficial YouTube client for Roku",
"scripts": {
"prebuild": "rm -rf ../build/playlet-lib",
+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.ObserveFieldScopedEx("systemLogEvent", port)
MessagePortUtils.ObserveFieldScopedExSafe(scene, "systemLogEvent", port)
m.port = port
@@ -68,8 +68,8 @@ namespace Innertube
function CreateContextClientWeb(deviceInfo as object) as object
return {
"hl": "en"
"gl": "US"
"hl": deviceInfo.GetCurrentLocale()
"gl": GetContentRegion(deviceInfo)
"remoteHost": ""
"screenDensityFloat": 1
"screenHeightPoints": 1440
@@ -102,8 +102,8 @@ namespace Innertube
function CreateContextClientIOS(deviceInfo as object) as object
return {
"hl": "en"
"gl": "US"
"hl": deviceInfo.GetCurrentLocale()
"gl": GetContentRegion(deviceInfo)
"remoteHost": ""
"screenDensityFloat": 1
"screenHeightPoints": 1440
@@ -128,8 +128,8 @@ namespace Innertube
function CreateContextClientTv(deviceInfo as object) as object
return {
"hl": "en"
"gl": "US"
"hl": deviceInfo.GetCurrentLocale()
"gl": GetContentRegion(deviceInfo)
"remoteHost": ""
"deviceMake": INNERTUBE_TV_DEVICE_MAKE
"deviceModel": INNERTUBE_TV_DEVICE_MODEL
@@ -157,4 +157,12 @@ namespace Innertube
"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
@@ -5,6 +5,7 @@ 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/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"
@@ -83,8 +84,8 @@ namespace InnertubeService
}
end function
function Search(query as string, cancellation = invalid as object) as object
return Innertube.Search(query, cancellation)
function Search(query as string, searchFilters as object, cancellation = invalid as object) as object
return Innertube.Search(query, searchFilters, cancellation)
end function
function GetTrending(options = invalid as object) as object
@@ -3,7 +3,7 @@ import "pkg:/components/Services/Innertube/Parser.bs"
namespace Innertube
function Search(query as string, cancellation = invalid as object) as object
function Search(query as string, searchFilters as object, cancellation = invalid as object) as object
deviceInfo = CreateObject("roDeviceInfo")
payload = {
@@ -11,6 +11,13 @@ namespace Innertube
context: Innertube.CreateContext(Innertube.ClientType.WEB, deviceInfo, "")
}
if searchFilters <> invalid and searchFilters.Count() > 0
params = Innertube.GetEncodedSearchFilters(searchFilters)
if params <> ""
payload["params"] = Innertube.GetEncodedSearchFilters(searchFilters)
end if
end if
request = HttpClient.PostJson("https://www.youtube.com/youtubei/v1/search?prettyPrint=false&alt=json", payload)
request.Headers({
"accept": "*/*"
@@ -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,130 @@
' 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) as string
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
return buffer.ToBase64String().EncodeUriComponent()
end function
function encodeSearchFilter(message as dynamic) as string
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))
end if
return buffer.ToBase64String().EncodeUriComponent()
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>
@@ -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.observeFieldScopedEx("loungeToken", messagePort)
MessagePortUtils.ObserveFieldScopedExSafe(loungeService, "loungeToken", messagePort)
loungeService.join = true
message = wait(30000, messagePort)
loungeService.unobserveFieldScoped("loungeToken")
@@ -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.observeFieldScopedEx("loungeToken", messagePort)
MessagePortUtils.ObserveFieldScopedExSafe(m.loungeService, "loungeToken", messagePort)
m.loungeService.join = true
message = wait(30000, messagePort)
m.loungeService.unobserveFieldScoped("loungeToken")
@@ -66,7 +66,29 @@ namespace Http
query = request.query.q
feeds = InnertubeService.Search(query)
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
feeds = InnertubeService.Search(query, searchFilters)
if not IsArray(feeds) or feeds.Count() = 0
response.Default(500, "Failed to search")
return true
@@ -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.observeFieldScopedEx("lib_version_latest", msgPort)
MessagePortUtils.ObserveFieldScopedExSafe(m.applicationInfoNode, "lib_version_latest", msgPort)
wait(5000, msgPort)
m.applicationInfoNode.unobserveFieldScoped("lib_version_latest")
@@ -47,10 +47,6 @@ search:
- channel
- all
arrayType: CommaSeparated
default:
- video
- playlist
- channel
features:
type:
- hd
+2 -2
View File
@@ -2,8 +2,8 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=34
build_version=00001
minor_version=35
build_version=00000
ui_resolutions=hd
uri_resolution_autosub=$$RES$$,480p,720p,1080p
@@ -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,66 @@
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())
for i = 0 to strBuffer.Count() - 1
m.buffer[m.position + i] = strBuffer[i]
end for
m.position += strBuffer.Count()
end function
function WriteBool(value as dynamic) as void
if value = true
m.WriteByte(1)
else
m.WriteByte(0)
end if
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,52 @@
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)
buffer = CreateObject("roByteArray")
buffer.FromBase64String(value.DecodeUriComponent())
m.writer.WriteVarInt(buffer.Count())
for i = 0 to buffer.Count() - 1
m.writer.WriteByte(buffer[i])
end for
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
@@ -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
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-web",
"version": "0.34.1",
"version": "0.35.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet-web",
"version": "0.34.1",
"version": "0.35.0",
"dependencies": {
"youtubei.js": "^12.2.0"
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.34.1",
"version": "0.35.0",
"type": "module",
"scripts": {
"dev": "vite",
+251
View File
@@ -0,0 +1,251 @@
// 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))\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) as string
buffer = CreateObject("roByteArray")
writer = new Protobuf.BinaryWriter()
writer.SetBuffer(buffer)
encoder = new Protobuf.Encoder(writer)
${encodeFields}
return buffer.ToBase64String().EncodeUriComponent()
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();
};