Fresh start (#110)

* Fresh start

* Create an xml include plugin (#111)

* Restructure and add testing (#114)

* rooibos setup

* Restructure and add testing

* docs

* Restore manifestpipi

* Description in tools

* A bit of docs

* Auto bind feature (#115)

* Auto bind feature

* Fix children merge

* bs plugin fix

* Feature/app controller (#120)

* Initial layout

* Restructuring and plugin work

* A couple of tweaks in binding stuff

* tweaks

* basic stack

* Add basic app controller

* Support json5/yaml in playlet config files (#123)

* Support json5 in playlet config files

* Add yaml to the mix

* Delete old lib project

* plugin fix

* plugin tweak

* verbose logging

* Revert "verbose logging"

This reverts commit 25867f4226703d83102519a0d48d1cc46a9876de.

* One idea to fix the include plugin

* Fix instability in plugins

* Feature/navbar (#126)

* Navbar

* typo

* comment

* Single content node, and tests

* Remove unused field

* tweaks

* update dependencies command

* tweak formatting

* Add web app screen

* Set id in created screens

* Search screen

* Tests

* Show playlists and channels in search results

* Move screen stuff to app controller

* Home screen (wip)

* Add preferences node

* README.md copyedits (#130)

* README.md: Fix typos

* README.md: Standardize capitalization and punctuation

* Update docs/README.md

---------

Co-authored-by: Brahim Hadriche <brahim.hadriche@gmail.com>

* Web server: round 1 (#131)

* web server object

* Logging

* Web server round 1

* Lint fix

* Small tweaks

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>

* Logging to file

* Leftover

* Add logs file to web server

* Fix for timeout

* Disable keepalive connection

* add openapi spec file

* Lint fix

* add prefs version in api

* Add ecp api definition

* Lint fix

* Settings rework (#135)

* Settings rework

* Standard OnFocusChange event

* Video player stuff (#136)

* Video player stuff

* Restructure things so that focus is better handled

* Lint fix

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>

* Exit dialog

* A bunch of changes

* New http client

* Set TODO priorities

* picture in picture

* mark video watched

* Video player stuff mostly there

* update spec file

* Sponsorblock

* FuncName

* SponsorBlock notifications

* Lint fix

* misc

* remove basic auth feature flag (until we start using it)

* Play queue part 1

* type fix

* handle unicode in request body

* SponsorBlock chapter label

* modal base

* remove a hack

* Invidious settings

* web server reduce timeout

* Test for captions

* Lint fix

* remove rpc stuff

* small change

* Solve focus management

* a couple of fixes

* Remove a bunch of todos

* feed error handling wip

* Lint fix

* navigation in instance settings

* home screen pagination support

* Refactor feed to support pagination on search page

* cell loading animation

* Tweak caching

* delete test screen

* playlist support part 1

* Basic playlist view

* Restore playlist/channel handler

* Refactor some content node stuff, and add an auth popup dialog

* A bad implementation of a playqueue

* Lint fix

* playlist cast fix

* Feature/web app catch up (#139)

* playlist cast fix

* Move things around

* support playlists in web app

* update api

* Bump deps

* Downgrade todo

---------

Co-authored-by: Bryce Harrington <bryce@bryceharrington.org>
Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
authored and GitHub committed 2023-09-07 17:18:25 -04:00
1 parent 79f74141c5
commit 43166fb43b
349 files changed
+12784 -7660

No files matched your search

@@ -8,22 +8,22 @@ end function
function CreateAsyncTask(taskFunc as object, input as object, callback = invalid as object) as object
id = StrI(rnd(2147483647), 36)
task = createObject("roSGNode", GetFunctionName(taskFunc))
task = createObject("roSGNode", GetComponentName(taskFunc))
task.id = id
task.input = input
m[`asynctask_${id}`] = task
m[`asynctask_${id}_callback`] = callback
task.ObserveField("state", "OnTaskState")
task.ObserveField("state", FuncName(OnTaskState))
return task
end function
function GetFunctionName(taskFunc as object) as string
if IsStr(taskFunc)
return LCase(`${taskFunc}_asynctask`)
function GetComponentName(taskFunc as object) as string
if IsString(taskFunc)
return `${taskFunc}_asynctask`
end if
return (LCase(`${taskFunc}_asynctask`)).replace("function:", "").trim()
return `${FuncName(taskFunc)}_asynctask`
end function
function OnTaskState(e as object) as void
@@ -38,7 +38,6 @@ function OnTaskState(e as object) as void
if output <> invalid
callback = m[`asynctask_${id}_callback`]
if callback <> invalid
output = task.output
callback(output)
end if
end if
@@ -0,0 +1,37 @@
namespace Tests
@SGNode("ApplicationInfo")
@suite
class ApplicationInfoTests extends Rooibos.BaseTestSuite
protected override function setup()
m.ipAddressRegex = CreateObject("roRegex", "\d+\.\d+\.\d+.\d+", "")
end function
protected override function beforeEach()
m.node.service = new ApplicationInfo(m.top)
end function
@describe("ApplicationInfo")
@it("Returns a valid local ip address")
function _()
ip = m.top@.GetLocalIpAddress(invalid)
m.assertTrue(m.ipAddressRegex.IsMatch(ip))
end function
@it("Returns an invalid if no ip address is available")
function _()
m.node.service.roDeviceInfo = {
GetIPAddrs: function() as dynamic
return []
end function
}
ip = m.top@.GetLocalIpAddress(invalid)
m.assertInvalid(ip)
end function
end class
end namespace
@@ -0,0 +1,68 @@
namespace Tests
@suite
class NavBarTests extends Rooibos.BaseTestSuite
@describe("NavBar")
@beforeEach
function _()
m.navBar = CreateObject("roSGNode", "NavBar")
m.navbar.appController = CreateObject("roSGNode", "AppController")
m.navBar@.BindNode(invalid)
end function
@it("Populates the buttons based on content node")
function _()
items = [
{
text: "Item1"
},
{
text: "Item2"
}
]
m.navBar.items = m.CreateContentNode(items)
buttonGroup = m.navBar.buttonGroup.getChildren(-1, 0)
m.assertArrayCount(buttonGroup, 2)
m.assertEqual(buttonGroup[0].text, "Item1")
m.assertEqual(buttonGroup[1].text, "Item2")
end function
@it("Clears the buttons when content node is invalid")
function _()
items = [
{
text: "Item1"
},
{
text: "Item2"
}
]
m.navBar.items = m.CreateContentNode(items)
buttonGroup = m.navBar.buttonGroup.getChildren(-1, 0)
m.assertArrayCount(buttonGroup, 2)
m.navBar.items = invalid
buttonGroup = m.navBar.buttonGroup.getChildren(-1, 0)
m.assertArrayCount(buttonGroup, 0)
end function
function CreateContentNode(items as object) as object
contentNode = CreateObject("roSGNode", "ContentNode")
for each item in items
navBarItem = CreateObject("roSGNode", "NavBarItem")
navBarItem.text = item.text
contentNode.appendChild(navBarItem)
end for
return contentNode
end function
end class
end namespace
@@ -0,0 +1,55 @@
namespace Tests
@SGNode("NavigationTestNode")
@suite
class NavigationTests extends Rooibos.BaseTestSuite
@describe("Navigation")
@afterEach
function _()
m.node._navigation = invalid
end function
@it("save data of the navigation")
function _()
node1 = CreateObject("roSGNode", "Node")
node2 = CreateObject("roSGNode", "Node")
m.top@.SetNavigation(node1, "right", node2)
m.assertAAHasKey(m.node._navigation, "right")
end function
@it("navigates to the right node")
function _()
node1 = CreateObject("roSGNode", "Node")
node2 = CreateObject("roSGNode", "Node")
m.top@.SetNavigation(node1, "right", node2)
NodeSetFocus(node1, true)
node2.focusable = true
m.top@.NavigationKeyHandler("right", true)
m.assertFalse(node1.hasFocus())
m.assertTrue(node2.hasFocus())
end function
@it("navigates to the right node from anywhere")
function _()
node2 = CreateObject("roSGNode", "Node")
m.top@.SetNavigation(invalid, "right", node2)
node2.focusable = true
m.top@.NavigationKeyHandler("right", true)
m.assertTrue(node2.hasFocus())
end function
end class
end namespace
@@ -1,43 +0,0 @@
namespace Invidious.SearchFilter
enum SortBy
Relevance = "relevance"
Rating = "rating"
UploadDate = "upload_date"
ViewCount = "view_count"
end enum
enum Date
Hour = "hour"
Today = "today"
Week = "week"
Month = "month"
Year = "year"
end enum
enum Duration
Short = "short"
Long = "long"
end enum
enum SearchType
Video = "video"
Playlist = "playlist"
Channel = "channel"
All = "all"
end enum
enum Features
HD = "hd"
Subtitles = "subtitles"
CreativeCommons = "creative_commons"
ThreeD = "3d"
Live = "live"
Purchased = "purchased"
FourK = "4k"
Three60 = "360"
Location = "location"
HDR = "hdr"
end enum
end namespace
@@ -1,10 +0,0 @@
namespace Invidious
class SearchSuggestionResult
public query as string
public suggestions as object
end class
end namespace
@@ -0,0 +1,127 @@
import "pkg:/source/utils/StringUtils.bs"
class ApplicationInfo
public node as object
public roDeviceInfo as object
public roAppInfo as object
function new(node as object)
m.node = node
m.roDeviceInfo = CreateObject("roDeviceInfo")
m.roAppInfo = CreateObject("roAppInfo")
end function
function GetLocalIpAddress() as dynamic
if StringUtils.IsNullOrEmpty(m.ipAddress)
ips = m.roDeviceInfo.GetIPAddrs()
for each ip in ips
m.ipAddress = ips[ip]
return m.ipAddress
end for
end if
return m.ipAddress
end function
function GetUserCountryCode() as string
if StringUtils.IsNullOrEmpty(m.countryCode)
m.countryCode = m.roDeviceInfo.GetUserCountryCode()
end if
return m.countryCode
end function
function GetAppInfo() as object
if m.appInfo = invalid
m.appInfo = {
id: m.roAppInfo.GetID(),
version: m.roAppInfo.GetVersion(),
git_commit_hash: m.roAppInfo.GetValue("git_commit_sha"),
lib_version: m.GetLibVersion(),
lib_git_commit_hash: m.GetLibGitCommitHash()
}
m.appInfo["lib_version_latest"] = "N/A"
m.appInfo["lib_url"] = "N/A"
m.appInfo["lib_url_type"] = "N/A"
scene = m.node.getScene()
if scene.playletLibLoadedUrl <> invalid
m.appInfo["lib_url"] = scene.playletLibLoadedUrl.link
m.appInfo["lib_url_type"] = scene.playletLibLoadedUrl.type
end if
end if
if m.appInfo.lib_version_latest = "N/A"
if not StringUtils.IsNullOrEmpty(m.node.lib_version_latest)
m.appInfo["lib_version_latest"] = m.node.lib_version_latest
else
m.node@.GetLatestPlayletLibVersion(invalid)
end if
end if
return m.appInfo
end function
function GetDeviceInfo() as object
if m.deviceInfo = invalid
m.deviceInfo = {
model: m.roDeviceInfo.GetModel(),
model_display_name: m.roDeviceInfo.GetModelDisplayName(),
model_type: m.roDeviceInfo.GetModelType(),
model_details: m.roDeviceInfo.GetModelDetails(),
os_version: m.roDeviceInfo.GetOSVersion(),
display_type: m.roDeviceInfo.GetDisplayType(),
display_mode: m.roDeviceInfo.GetDisplayMode(),
display_aspect_ratio: m.roDeviceInfo.GetDisplayAspectRatio(),
display_size: m.roDeviceInfo.GetDisplaySize(),
video_mode: m.roDeviceInfo.GetVideoMode(),
ui_resolution: m.roDeviceInfo.GetUIResolution(),
graphics_platform: m.roDeviceInfo.GetGraphicsPlatform(),
internet_status: m.roDeviceInfo.GetInternetStatus(),
user_country_code: m.roDeviceInfo.GetUserCountryCode(),
friendly_name: m.roDeviceInfo.GetFriendlyName()
}
end if
return m.deviceInfo
end function
function GetLibVersion() as string
values = m.GetLibManifestValues()
Major = values["major_version"].toInt()
Minor = values["minor_version"].toInt()
Build = values["build_version"].toInt()
return `${Major}.${Minor}.${Build}`
end function
function GetLibGitCommitHash() as string
values = m.GetLibManifestValues()
if values.doesexist("git_commit_sha")
return values["git_commit_sha"]
end if
return ""
end function
function GetLibManifestValues() as object
if m.libManifestValues = invalid
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
m.libManifestValues = values
end if
return m.libManifestValues
end function
end class
@@ -0,0 +1,690 @@
#const DISABLE_CACHE = false
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
namespace HttpClient
enum QueryParamArrayType
CommaSeparated
Repeated
end enum
function Get(url as string) as HttpRequest
return (new HttpRequest()).Method("GET").Url(url)
end function
function Post(url as string, data as string) as HttpRequest
return (new HttpRequest()).Method("POST").Url(url).Body(data)
end function
function PostJson(url as string, data as object) as HttpRequest
return (new HttpRequest()).Method("POST").Url(url).Json(data)
end function
function Put(url as string, data as string) as HttpRequest
return (new HttpRequest()).Method("PUT").Url(url).Body(data)
end function
function PutJson(url as string, data as object) as HttpRequest
return (new HttpRequest()).Method("PUT").Url(url).Json(data)
end function
function Delete(url as string) as HttpRequest
return (new HttpRequest()).Method("DELETE").Url(url)
end function
function Head(url as string) as HttpRequest
return (new HttpRequest()).Method("HEAD").Url(url)
end function
class HttpRequest
public urlTransfer as object
function new()
m.log = new log.Logger("HttpRequest")
m._timeoutSeconds = 30
end function
function Method(method as string) as HttpRequest
m._method = Ucase(method)
return m
end function
function Url(url as string) as HttpRequest
m._url = url
return m
end function
function QueryParam(key as string, value as dynamic) as HttpRequest
if value = invalid
return m
end if
if m._queryParams = invalid
m._queryParams = {}
end if
m._queryParams[key] = value
return m
end function
function QueryParamArray(key as string, valueArray as dynamic, arrayType as HttpClient.QueryParamArrayType) as HttpRequest
if valueArray = invalid
return m
end if
if m._queryParams = invalid
m._queryParams = {}
end if
m._queryParams[key] = {
value: valueArray,
__arrayType: arrayType
}
return m
end function
function QueryParams(queryParams as object) as HttpRequest
if m._queryParams = invalid
m._queryParams = {}
end if
m._queryParams.append(queryParams)
return m
end function
function PathParam(key as string, value as string) as HttpRequest
if m._pathParams = invalid
m._pathParams = {}
end if
m._pathParams[key] = value
return m
end function
function PathParams(pathParams as object) as HttpRequest
if m._pathParams = invalid
m._pathParams = {}
end if
m._pathParams.append(pathParams)
return m
end function
function Header(key as string, value as string) as HttpRequest
if m._headers = invalid
m._headers = {}
end if
m._headers[key] = value
return m
end function
function Headers(headers as object) as HttpRequest
if m._headers = invalid
m._headers = {}
end if
m._headers.append(headers)
return m
end function
function Body(body as dynamic) as HttpRequest
m._body = ValidString(body)
return m
end function
function Json(body as object) as HttpRequest
m.Body(FormatJson(body))
m.Header("Content-Type", "application/json")
return m
end function
function TimeoutSeconds(timeoutSeconds as integer) as HttpRequest
m._timeoutSeconds = timeoutSeconds
return m
end function
function NoCache() as HttpRequest
m._noCache = true
return m
end function
function CacheSeconds(expireSeconds as integer) as HttpRequest
m._expireSeconds = expireSeconds
if expireSeconds < 0
m.NoCache()
end if
return m
end function
function Cancellation(cancellation as object) as HttpRequest
m._cancellation = cancellation
return m
end function
function ToCurlCommand() as string
command = `curl "${m.BuildUrl()}"`
command += ` \\\n -X ${m._method}`
command += ` \\\n --max-time ${m._timeoutSeconds}`
if m._headers <> invalid
for each key in m._headers
command += ` \\\n -H '${key}: ${m._headers[key]}'`
end for
end if
if not StringUtils.IsNullOrEmpty(m._body)
command += ` \\\n -d '${m._body}'`
end if
return command
end function
function Send() as HttpRequest
return m.DoSend(false)
end function
function SendAndForget() as HttpRequest
return m.DoSend(true)
end function
private function DoSend(forget as boolean) as HttpRequest
if m.urlTransfer <> invalid or m._cache <> invalid
return m
end if
#if DISABLE_CACHE
m._noCache = true
#end if
if m._noCache <> true
cache = HttpClientCache.Get(m)
if cache <> invalid
m.log.info("Cache hit", m._method, m.BuildUrl())
m._cache = cache
return m
end if
end if
m.urlTransfer = m.CreateRoUrlTransfer()
m.urlTransfer.setUrl(m.BuildUrl())
if m._headers <> invalid
m.urlTransfer.SetHeaders(m._headers)
end if
if not forget
m.urlTransfer.SetMessagePort(CreateObject("roMessagePort"))
end if
m.log.info("Sending", m._method, m.urlTransfer.GetURL(), "ID:", m.urlTransfer.GetIdentity())
#if DEBUG
? `════════ curl command ════════\n${m.ToCurlCommand()}\n══════════════════════════════`
#end if
if m._method = "POST"
m._sent = m.urlTransfer.AsyncPostFromString(m._body)
else if m._method = "GET"
m._sent = m.urlTransfer.AsyncGetToString()
else if m._method = "HEAD"
m._sent = m.urlTransfer.AsyncHead()
else
m.urlTransfer.SetRequest(m._method)
m._sent = m.urlTransfer.AsyncPostFromString(m._body)
end if
if m._sent <> true
m.log.error("Failed to send request")
end if
return m
end function
function IsCancelled() as boolean
if m._cancelled = true
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
m._cancelled = true
end if
return m._cancelled = true
end function
function Await() as HttpResponse
if m.urlTransfer = invalid and m._cache = invalid
m.Send()
end if
if m._sent <> true or m._cache <> invalid
return new HttpResponse(m, invalid)
end if
if m.IsCancelled()
return new HttpResponse(m, invalid)
end if
messagePort = m.urlTransfer.GetMessagePort()
if messagePort = invalid
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
msg = wait(m._timeoutSeconds * 1000, messagePort)
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
if msg = invalid
' timeout
m.log.info("Timeout", "ID:", m.urlTransfer.GetIdentity())
m.urlTransfer.AsyncCancel()
else
eventType = type(msg)
if eventType = "roUrlEvent"
m.log.info("Finished", "ID:", m.urlTransfer.GetIdentity())
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
m.log.info("Cancelled", "ID:", m.urlTransfer.GetIdentity())
m._cancelled = true
m.urlTransfer.AsyncCancel()
end if
end if
end if
response = new HttpResponse(m, msg)
if m.IsCancelled()
return response
end if
HttpClientCache.Set(response)
return response
end function
private function CreateRoUrlTransfer() as object
urlTransfer = CreateObject("roUrlTransfer")
urlTransfer.EnableEncodings(true)
urlTransfer.RetainBodyOnError(true)
if LCase(left(m._url, 6)).StartsWith("https:")
urlTransfer.SetCertificatesFile("common:/certs/ca-bundle.crt")
urlTransfer.InitClientCertificates()
end if
return urlTransfer
end function
' TODO:P2 refactor this monstrosity of a function
function BuildUrl() as string
if m._fullUrl <> invalid
return m._fullUrl
end if
url = m._url
if m._pathParams <> invalid
for each key in m._pathParams
value = m._pathParams[key]
if value = invalid
continue for
end if
if not IsString(value)
value = `${value}`
end if
url = url.Replace(`{${key}}`, value.EncodeUriComponent())
end for
end if
if m._queryParams <> invalid
hasQueryParams = url.InStr("?") <> -1
for each key in m._queryParams
value = m._queryParams[key]
if value = invalid
continue for
end if
if not IsString(value)
if IsAssociativeArray(value) and IsArray(value.value)
if value.__arrayType = HttpClient.QueryParamArrayType.Repeated
valueArray = value.value
for each item in valueArray
itemString = item
if not IsString(itemString)
itemString = `${itemString}`
end if
if hasQueryParams
url += "&" + key.EncodeUriComponent() + "=" + itemString.EncodeUriComponent()
else
url += "?" + key.EncodeUriComponent() + "=" + itemString.EncodeUriComponent()
hasQueryParams = true
end if
end for
else if value.__arrayType = HttpClient.QueryParamArrayType.CommaSeparated
valueArray = value.value
for i = 0 to valueArray.Count() - 1
itemString = valueArray[i]
if not IsString(itemString)
itemString = `${itemString}`
end if
itemString = itemString.EncodeUriComponent()
valueArray[i] = itemString
end for
joined = valueArray.join(",")
if hasQueryParams
url += "&" + key.EncodeUriComponent() + "=" + joined
else
url += "?" + key.EncodeUriComponent() + "=" + joined
hasQueryParams = true
end if
end if
else
value = `${value}`
if hasQueryParams
url += "&" + key.EncodeUriComponent() + "=" + value.EncodeUriComponent()
else
url += "?" + key.EncodeUriComponent() + "=" + value.EncodeUriComponent()
hasQueryParams = true
end if
end if
else
if hasQueryParams
url += "&" + key.EncodeUriComponent() + "=" + value.EncodeUriComponent()
else
url += "?" + key.EncodeUriComponent() + "=" + value.EncodeUriComponent()
hasQueryParams = true
end if
end if
end for
end if
m._fullUrl = url
return m._fullUrl
end function
end class
class HttpResponse
public request as HttpRequest
public event as object
function new(request as HttpRequest, event as object)
m.request = request
m.event = event
end function
function StatusCode() as integer
if m._statusCode <> invalid
return m._statusCode
end if
if m.IsCached()
m._statusCode = m.request._cache.statusCode
return m._statusCode
end if
if type(m.event) <> "roUrlEvent"
m._statusCode = 0
else
m._statusCode = m.event.GetResponseCode()
end if
return m._statusCode
end function
function IsSuccess() as boolean
statusCode = m.StatusCode()
return statusCode >= 200 and statusCode < 400
end function
function IsCached() as boolean
return m.request._cache <> invalid
end function
function TimedOut() as boolean
return not m.IsCached() and m.event = invalid
end function
function IsCancelled() as boolean
return m.request.IsCancelled()
end function
function Text() as dynamic
if m._text <> invalid
return m._text
end if
if m.IsCached()
m._text = m.request._cache.body
return m._text
end if
if not m.IsSuccess()
return invalid
end if
m._text = m.event.GetString()
return m._text
end function
function Json() as object
if m._json <> invalid
return m._json
end if
text = m.Text()
if text = invalid
return invalid
end if
m._json = ParseJson(text)
return m._json
end function
function Headers() as object
if m._headers <> invalid
return m._headers
end if
if m.IsCached()
m._headers = m.request._cache.headers
return m._headers
end if
if type(m.event) = "roUrlEvent"
m._headers = m.event.GetResponseHeaders()
else
m._headers = {}
end if
return m._headers
end function
function ErrorMessage() as string
if m._errorMessage <> invalid
return m._errorMessage
end if
if m.IsSuccess()
m._errorMessage = ""
else
if m.request._sent <> true
m._errorMessage = "Request not sent."
else if m.TimedOut()
m._errorMessage = "Request timed out."
else if m.IsCancelled()
m._errorMessage = "Request cancelled."
else if type(m.event) = "roUrlEvent"
m._errorMessage = `Reason :${m.event.GetFailureReason() }\nStatusCode: ${m.StatusCode()}\nBody: ${m.event.GetString()}`
end if
end if
return m._errorMessage
end function
end class
end namespace
' TODO:P2 introduce the concept of "loose" cache
' For playlists that show in a feed or in a search, we don't want to make a request to get the playlist details
' But if we have that information in the cache already, it can be used
namespace HttpClientCache
function GetLocation(request as HttpClient.HttpRequest) as dynamic
if request._cacheLocation <> invalid
return request._cacheLocation
end if
cacheKey = request.BuildUrl()
if request._headers <> invalid
headersString = FormatJson(request._headers)
cacheKey = cacheKey + headersString
end if
hash = CryptoUtils.GetMd5(cacheKey)
request._cacheLocation = `cachefs:/request_v1_${hash}.json`
return request._cacheLocation
end function
function GetFileSystem(request as HttpClient.HttpRequest) as object
if request._fileSystem = invalid
request._fileSystem = CreateObject("roFileSystem")
end if
return request._fileSystem
end function
function Exists(request as HttpClient.HttpRequest) as boolean
fileSystem = GetFileSystem(request)
if fileSystem = invalid
return false
end if
cacheLocation = GetLocation(request)
return fileSystem.Exists(cacheLocation)
end function
function Get(request as HttpClient.HttpRequest) as object
if request._noCache = true
return invalid
end if
if request._method <> "GET"
return invalid
end if
if not Exists(request)
return invalid
end if
cacheLocation = GetLocation(request)
cacheText = ReadAsciiFile(cacheLocation)
cacheObject = ParseJson(cacheText)
if cacheObject = invalid
Delete(request)
return invalid
end if
expireSeconds = request._expireSeconds
if expireSeconds = invalid and cacheObject.headers <> invalid
expireSeconds = ParseHeadersForCacheControl(cacheObject.headers)
end if
if expireSeconds = invalid
return invalid
end if
date = CreateObject("roDateTime")
nowTimestamp = date.AsSeconds()
if cacheObject.timestamp + expireSeconds < nowTimestamp
Delete(request)
return invalid
end if
return cacheObject
end function
function Set(response as HttpClient.HttpResponse) as void
if response.request._noCache = true or response.request._method <> "GET"
return
end if
if not response.IsSuccess()
return
end if
if response.request._expireSeconds = invalid
headers = response.Headers()
if headers = invalid
return
end if
if ParseHeadersForCacheControl(headers) = invalid
return
end if
end if
fileSystem = GetFileSystem(response.request)
if fileSystem = invalid
return
end if
date = CreateObject("roDateTime")
timestamp = date.AsSeconds()
cacheObject = {
timestamp: timestamp,
statusCode: response.StatusCode(),
headers: response.Headers(),
body: response.Text()
}
cacheLocation = GetLocation(response.request)
' TODO:P2 use a diferent format other than json for better performance
cacheText = FormatJson(cacheObject)
WriteAsciiFile(cacheLocation, cacheText)
end function
function Delete(request as HttpClient.HttpRequest) as boolean
fileSystem = GetFileSystem(request)
if fileSystem = invalid
return false
end if
cacheLocation = GetLocation(request)
return fileSystem.Delete(cacheLocation)
end function
function ParseHeadersForCacheControl(headers as object) as dynamic
cacheControl = headers["cache-control"]
if cacheControl = invalid
return invalid
end if
cacheControlDirectives = cacheControl.split(",")
for each cacheControlDirective in cacheControlDirectives
keyValue = cacheControlDirective.Trim().split("=")
name = keyValue[0].Trim()
if keyValue.Count() > 1
value = keyValue[1].Trim()
else
value = invalid
end if
if name = "no-store" or name = "no-cache"
return invalid
else if name = "max-age"
return val(value)
end if
end for
return invalid
end function
end namespace
@@ -1,268 +0,0 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/General.bs"
import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/source/utils/WebUtils.bs"
import "pkg:/source/services/InvidiousSettings.bs"
namespace Invidious
const TOKEN_CALLBACK = "/invidious/token_callback"
' TODO: query server status, check if it supports APIs and/or signups
const STATS_ENDPOINT = "/api/v1/stats"
const VIDEOS_ENDPOINT = "/api/v1/videos"
const PLAYLISTS_ENDPOINT = "/api/v1/playlists"
const HISTORY_ENDPOINT = "/api/v1/auth/history"
const SEARCH_SUGGEST_ENDPOINT = "/api/v1/search/suggestions"
const SEARCH_ENDPOINT = "/api/v1/search"
const AUTH_SCOPES = "GET:feed,GET:playlists,POST:tokens/register,POST:tokens/unregister,POST:history*"
const AUTH_FEED = "/api/v1/auth/feed"
const AUTH_PLAYLISTS = "/api/v1/auth/playlists"
const AUTH_TOKENS_UNREGISTER = "/api/v1/auth/tokens/unregister"
const AUTH_TOKENS_REGISTER = "/api/v1/auth/tokens/register"
const TOKEN_TIMESPAN = 60 * 60 * 24 * 365 * 2 '2 years
function DefaultArgs() as object
return {
params: {
region: GetUserCountryCode()
}
}
end function
function GetServerStats() as object
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.STATS_ENDPOINT}`
response = Requests().get(url)
if response.statuscode = 200
return response.json
end if
return invalid
end function
function GetVideoStreamUrl(videoId as string, local as boolean) as string
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}/latest_version?id=${videoId}`
if local
url = url + "&local=true"
end if
return url
end function
function GetVideoDashUrl(videoId as string, local as boolean) as string
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}/api/manifest/dash/id/${videoId}`
if local
url = url + "?local=true"
end if
return url
end function
function GetVideoMetadata(videoId as string) as object
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}`
args = Invidious.DefaultArgs()
args.cacheSeconds = 60 * 60 * 6 ' 6 hours
response = Requests().get(url, args)
return {
success: response.ok,
statusCode: response.statuscode,
data: response.json,
failureReason: response.GetFailureReason
}
end function
function GetPlaylist(playlistId as string) as object
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}`
args = Invidious.DefaultArgs()
response = Requests().get(url, args)
if not response.ok
return invalid
end if
return response.json
end function
function MarkVideoWatched(videoId as string) as boolean
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
return false
end if
url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}`
headers = Invidious.GetAuthenticationHeaders(authToken.token)
args = {
headers: headers,
parseJson: false
}
response = Requests().post(url, args)
return response.ok
end function
function SearchSuggestions(q as string) as object 'SearchSuggestionResult
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.SEARCH_SUGGEST_ENDPOINT}`
args = Invidious.DefaultArgs()
args.params.q = q
args.cacheSeconds = 60 * 60 * 6 ' 6 hours
response = Requests().get(url, args)
if response.statuscode = 200
return response.json
end if
return invalid
end function
function Search(q as string, args = invalid as dynamic) as object
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.SEARCH_ENDPOINT}`
_args = Invidious.DefaultArgs()
_args.params.q = q
if args <> invalid
if args.page <> invalid
_args.params.page = Str(args.page).Trim()
end if
if args.sort_by <> invalid
_args.params.sort_by = args.sort_by
end if
if args.date <> invalid
_args.params.date = args.date
end if
if args.duration <> invalid
_args.params.duration = args.duration
end if
if args.type <> invalid
_args.params.type = args.type
end if
if args.features <> invalid
_args.params.features = args.features.join(",")
end if
end if
response = Requests().get(url, _args)
if response.statuscode = 200
return response.json
end if
return invalid
end function
function GetAuthorizeTokenLink() as string
instance = InvidiousSettings.GetCurrentInstance()
' Make sure the host is not on https, because https cannot redirect to http, which is our local server
invidiousHost = instance.Replace("https://", "http://")
localIp = GetLocalIpAddress()
webServerPort = 8888
expire = TimeUtils.Now().AsSeconds() + TOKEN_TIMESPAN
callbackUrl = `http://${localIp}:${webServerPort}${Invidious.TOKEN_CALLBACK}?ref=${instance}`.EncodeUriComponent()
scope = `${Invidious.AUTH_SCOPES}`.EncodeUriComponent()
return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
end function
function GetAuthenticationHeaders(token as string) as object
return {
"Authorization": `Bearer ${token}`
}
end function
function RefreshAuthToken() as boolean
currentAuthToken = InvidiousSettings.GetAuthToken()
if currentAuthToken = invalid
return false
end if
expire = TimeUtils.Now().AsSeconds() + TOKEN_TIMESPAN
newToken = RegisterToken(currentAuthToken, expire)
if newToken = invalid
return false
end if
InvidiousSettings.SetAuthToken(newToken.token, newToken.instance, newToken.username, newToken.scopes, newToken.expire)
UnregisterToken(currentAuthToken)
return true
end function
function RegisterToken(authToken as object, expire as integer) as dynamic
headers = Invidious.GetAuthenticationHeaders(authToken.token)
url = `${authToken.instance}${Invidious.AUTH_TOKENS_REGISTER}`
scopes = authToken.scopes
if scopes = invalid
parsedToken = ParseJson(authToken.token)
if GetInterface(parsedToken.scopes, "ifArray") <> invalid
scopes = parsedToken.scopes.join(",")
else
scopes = Invidious.AUTH_SCOPES
end if
end if
args = {
headers: headers,
json: {
"scopes": scopes.Split(","),
"expire": expire
},
parseJson: false
}
response = Requests().post(url, args)
if not response.ok
return invalid
end if
return {
token: response.text,
instance: authToken.instance,
username: authToken.username,
scopes: scopes,
expire: expire
}
end function
function UnregisterToken(authToken as object) as boolean
headers = Invidious.GetAuthenticationHeaders(authToken.token)
url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
' authToken.token is already valid json that contains the "session" key needed by the unregister endpoint
headers["Content-Type"] = "application/json"
args = {
headers: headers,
data: authToken.token,
parseJson: false
}
response = Requests().post(url, args)
return response.ok
end function
function Logout() as boolean
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
return false
end if
UnregisterToken(authToken)
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
return true
end function
end namespace
@@ -1,170 +0,0 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/General.bs"
import "pkg:/source/utils/Crypto.bs"
import "pkg:/source/services/InvidiousSettings.bs"
import "pkg:/source/services/Invidious.bs"
class InvidiousService
private endpoints
private responseHanlders
function new()
apiDefnitions = ParseJson(ReadAsciiFile("libpkg:/config/invidious_video_api.json"))
m.endpoints = {}
for each apiDefnition in apiDefnitions.endpoints
m.endpoints[apiDefnition.name] = apiDefnition
end for
m.responseHanlders = {
DefaultHandler: m.DefaultHandler,
AuthFeedHandler: m.AuthFeedHandler,
AuthPlaylistsHandler: m.AuthPlaylistsHandler,
PlaylistHandler: m.PlaylistHandler
}
end function
function MakeRequest(requestData as object) as object
endpoint = m.endpoints[requestData.endpoint]
if endpoint = invalid
return invalid
end if
instance = InvidiousSettings.GetCurrentInstance()
url = instance + endpoint.url
args = { params: {} }
if endpoint.authenticated = true
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
return invalid
end if
url = authToken.instance + endpoint.url
args.headers = m.GetAuthenticationHeaders(authToken.token)
end if
if endpoint.queryParams <> invalid
for each queryParamKey in endpoint.queryParams
queryParam = endpoint.queryParams[queryParamKey]
if queryParam.default <> invalid
if queryParam.type = "string"
args.params[queryParamKey] = queryParam.default
else if queryParam.type = "#ISO3166"
if queryParam.default = "GetUserCountryCode"
args.params[queryParamKey] = GetUserCountryCode()
else
args.params[queryParamKey] = queryParam.default
end if
end if
end if
end for
end if
if requestData.queryParams <> invalid
args.params.append(requestData.queryParams)
end if
if requestData.pathParams <> invalid
for each param in requestData.pathParams
url = url.Replace(`:${param}`, requestData.pathParams[param])
end for
end if
response = Requests().get(url, args)
responseHandler = endpoint.responseHandler <> invalid ? m.responseHanlders[endpoint.responseHandler] : m.responseHanlders["DefaultHandler"]
result = responseHandler(m, requestData, response)
if result <> invalid and endpoint.authenticated = true
' Cache response for use by web app
m.CacheResponse(requestData, result)
end if
return result
end function
function GetAuthenticationHeaders(token as string) as object
return {
"Authorization": `Bearer ${token}`
}
end function
function DefaultHandler(m as object, requestData as object, response as object) as object
if response.statuscode = 200
return [{ title: requestData.title, videos: response.json }]
end if
return invalid
end function
function AuthFeedHandler(m as object, requestData as object, response as object) as object
m.DeleteExpiredToken(response)
if response.statuscode = 200
videos = []
videos.Append(response.json.notifications)
videos.Append(response.json.videos)
return [{ title: requestData.title, videos: videos }]
end if
return invalid
end function
function AuthPlaylistsHandler(m as object, requestData as object, response as object) as object
m.DeleteExpiredToken(response)
if response.statuscode = 200
playlists = response.json
result = []
for each playlist in playlists
' Saved playlists are not included in the response
' https://github.com/iv-org/invidious/issues/3995
if playlist.videos.count() = 0 and playlist.authorId = invalid and not playlist.playlistId.StartsWith("IV")
playlist = Invidious.GetPlaylist(playlist.playlistId)
end if
if playlist <> invalid
result.push(m.ProcessPlaylist(requestData, playlist))
end if
end for
return result
end if
return invalid
end function
function PlaylistHandler(m as object, requestData as object, response as object) as object
if response.statuscode = 200
playlist = response.json
return [m.ProcessPlaylist(requestData, playlist)]
end if
return invalid
end function
function ProcessPlaylist(requestData as object, playlist as object) as object
title = m.ProcessTemplate(requestData.title, playlist)
return { title: title, videos: playlist.videos }
end function
function ProcessTemplate(template as string, data as object) as string
for each key in data
template = template.Replace(`%${key}%`, `${data[key]}`)
end for
return template
end function
function DeleteExpiredToken(response as object)
if response.statuscode = 403
print(`Invidious instance responded with 403: ${response.text}`)
print("Deleting Invidious token...")
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
end if
end function
function CacheResponse(requestData as object, result as object)
cacheKey = FormatJson(requestData)
cacheKey = GetMd5(cacheKey)
value = FormatJson(result)
WriteAsciiFile(`tmp:/${cacheKey}.json`, value)
end function
end class
@@ -1,107 +0,0 @@
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/components/SettingsScreen/Settings.bs"
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
namespace InvidiousSettings
const DEFAULT_INSTANCE = "https://vid.puffyan.us"
const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,users"
function GetCurrentInstance() as object
settings = FindAndGetPreferenceValues(["invidious.instance"])
if settings <> invalid and settings["invidious.instance"] <> invalid and settings["invidious.instance"] <> ""
return settings["invidious.instance"]
end if
backupInstances = InvidiousSettings.GetBackupInstances()
if backupInstances.Count() > 0
return backupInstances[0]
end if
return InvidiousSettings.DEFAULT_INSTANCE
end function
function SetAuthToken(token as string, instance as string, username as dynamic, scopes as dynamic, expire as dynamic)
obj = {
token: token,
instance: instance
}
if username <> invalid
obj.username = username
end if
if scopes <> invalid
obj.scopes = scopes
end if
if expire <> invalid
obj.expire = expire
end if
json = FormatJson(obj)
RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json)
end function
function GetAuthToken() as dynamic
tokenPayload = RegistryUtils.Read(RegistryUtils.INVIDIOUS_TOKEN)
if tokenPayload = invalid
return invalid
end if
authData = ParseJson(tokenPayload)
if authData = invalid or authData.instance = invalid or authData.token = invalid
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
return invalid
end if
return authData
end function
function GetBackupInstances() as object
if m.global.hasField("invidiousBackupInstances")
return m.global.invidiousBackupInstances
end if
return []
end function
function FetchBackupInstances() as object
backupInstances = []
publicInstances = InvidiousSettings.GetPublicInstances()
for i = 0 to publicInstances.Count() - 1
if InvidiousSettings.IsValidPublicInstance(publicInstances[i])
backupInstances.push(publicInstances[i].uri)
end if
if backupInstances.Count() >= 5
exit for
end if
end for
return backupInstances
end function
function GetPublicInstances() as object
instances = []
response = Requests().get(InvidiousSettings.INSTANCES_API)
if response.statuscode = 200
json = response.json
for each instance in json
data = instance[1]
if data.monitor <> invalid and data.monitor.dailyRatios <> invalid
data.monitor.dailyRatios = invalid
end if
data["name"] = instance[0]
instances.push(data)
end for
end if
return instances
end function
function IsValidPublicInstance(instance as object) as boolean
if instance = invalid
return false
end if
return instance.type = "https" and instance.api = true
end function
end namespace
@@ -1,122 +0,0 @@
import "pkg:/source/utils/RegistryUtils.bs"
class PreferencesService
private version = 1
private prefs_model
private user_prefs
function new()
m.LoadConfigFile()
m.LoadUserPreferences()
end function
function LoadConfigFile()
m.prefs_model = ParseJson(ReadAsciiFile("libpkg:/config/preferences.json"))
end function
function LoadUserPreferences()
' Step 1: Load user preferences from registry
m.user_prefs = RegistryUtils.Read(RegistryUtils.USER_PREFERENCES)
if m.user_prefs = invalid
m.user_prefs = "{}"
end if
m.user_prefs = ParseJson(m.user_prefs)
' Step 2: Migrate existing preferences to new format (if needed)
isDirty = m.MigrateExistingPreferences()
' Step 3: Apply defaults to user preferences (if needed)
isDirty = m.ApplyDefaultsToUserPreferences() or isDirty
if isDirty
m.SaveUserPreferences()
end if
end function
function SaveUserPreferences()
m.user_prefs.__version = m.version
RegistryUtils.Write(RegistryUtils.USER_PREFERENCES, FormatJson(m.user_prefs))
end function
function MigrateExistingPreferences() as boolean
isDirty = false
' v0 -> v1
instances = RegistryUtils.Read(RegistryUtils.INVIDIOUS_INSTANCES)
if instances <> invalid
currentInstance = m.user_prefs["invidious.instance"]
if currentInstance = invalid or currentInstance = ""
instances = ParseJson(instances)
if instances.Count() > 0
instance = instances[0]
if instance <> invalid and instance <> ""
m.user_prefs["invidious.instance"] = instance
isDirty = true
end if
end if
end if
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_INSTANCES)
end if
' v1 -> v2 goes here (if needed)
' if m.user_prefs.__version = 1
' 'do stuff
' end if
' TODO: handle case where saved preferences version is higher than current version (e.g. user downgraded)
return isDirty
end function
function ApplyDefaultsToUserPreferences() as boolean
isDirty = false
for each child in m.prefs_model
isDirty = m.ApplyToUserPreferences(m.user_prefs, child) or isDirty
end for
return isDirty
end function
function ApplyToUserPreferences(userPrefs as object, model as object) as boolean
isDirty = false
if model.children <> invalid
for each child in model.children
isDirty = m.ApplyToUserPreferences(userPrefs, child) or isDirty
end for
end if
if model.defaultValue <> invalid and (not userPrefs.DoesExist(model.key) or userPrefs[model.key] = invalid)
userPrefs[model.key] = model.defaultValue
isDirty = true
end if
return isDirty
end function
function GetUserPreferences() as object
return m.user_prefs
end function
function ApplyUserPreferences(preferences as object) as void
if preferences = invalid
return
end if
' TODO: user input validation
for each key in preferences
m.user_prefs[key] = preferences[key]
end for
m.SaveUserPreferences()
end function
function ClearUserPreferences() as void
m.user_prefs = {}
m.ApplyDefaultsToUserPreferences()
m.SaveUserPreferences()
end function
function GetValue(key as string) as dynamic
return m.user_prefs[key]
end function
function SetValue(key as string, value as dynamic) as void
if m.user_prefs[key] = value
return
end if
m.user_prefs[key] = value
m.SaveUserPreferences()
end function
end class
@@ -1,10 +1,11 @@
import "pkg:/source/utils/General.bs"
import "pkg:/source/utils/ArrayUtils.bs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
namespace SearchHistory
function Save(q as string, maxItems = 10 as integer)
history = GetAllSaved()
index = ArrayIndexOf(history, q)
index = ArrayUtils.IndexOfString(history, q)
if index <> -1
history.Delete(index)
end if
@@ -26,7 +27,7 @@ namespace SearchHistory
return []
end if
if q = ""
if StringUtils.IsNullOrEmpty(q)
return history
end if
result = []
@@ -1,115 +0,0 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/utils/WebUtils.bs"
import "pkg:/source/utils/Crypto.bs"
import "pkg:/source/utils/ColorUtils.bs"
namespace SponsorBlock
const API_URL = "https://sponsor.ajay.app"
const SKIP_SEGMENT_ENDPOINT = "/api/skipSegments"
const VIEWED_SEGMENT_ENDPOINT = "/api/viewedVideoSponsorTime"
function GetSponsorBlockConfig() as object
if m.sponsorBlockConfig = invalid
m.sponsorBlockConfig = ParseJson(ReadAsciiFile("libpkg:/config/sponsorblock_config.json"))
end if
return m.sponsorBlockConfig
end function
function SegmentColor(category as string) as integer
config = SponsorBlock.GetSponsorBlockConfig()
if config = invalid
return 0
end if
if config.categories.doesexist(category)
color = config.categories[category].color
return ColorUtils.HexToInt(color)
end if
return 0
end function
function SegmentTitle(category as string) as string
config = SponsorBlock.GetSponsorBlockConfig()
if config = invalid
return ""
end if
if config.categories.doesexist(category)
return config.categories[category].title
end if
return ""
end function
function SegmentShortTitle(category as string) as string
config = SponsorBlock.GetSponsorBlockConfig()
if config = invalid
return ""
end if
if config.categories.doesexist(category)
return config.categories[category].short_title
end if
return ""
end function
function GetSkipSegmentsForVideo(videoId as string) as object
categories = ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "poi_highlight", "chapter", "filler", "exclusive_access"]
actionTypes = ["skip", "mute", "chapter", "full", "poi"]
categoriesJson = FormatJson(categories).EncodeUriComponent()
actionTypesJson = FormatJson(actionTypes).EncodeUriComponent()
' From SponsorBlock docs: It should be the first 4 - 32 characters (4 is recommended).
hashPrefix = GetSha256(videoId).Left(4)
url = `${SponsorBlock.API_URL}${SponsorBlock.SKIP_SEGMENT_ENDPOINT}/${hashPrefix}?categories=${categoriesJson}&actionTypes=${actionTypesJson}`
response = Requests().get(url)
if response.statuscode = 200
results = response.json
for each item in results
if item.videoId = videoId
return item.segments
end if
end for
end if
return invalid
end function
function PostSegmentViewed(segmentId as string) as boolean
url = `${SponsorBlock.API_URL}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}`
response = Requests().post(url, { parseJson: false })
return response.statuscode = 200
end function
function GenerateProgressBarBackground(segments as object, lengthSeconds as integer, path as string)
bar = CreateObject("roBitmap", { width: 1000, height: 20, AlphaEnable: true })
bar.Clear(&hFFFFFF80)
width = bar.GetWidth()
height = bar.GetHeight()
for each segment in segments
videoDuration = lengthSeconds
if videoDuration = 0 or videoDuration = invalid
' We should ignore segment.videoDuration https://github.com/iBicha/playlet/pull/23#issuecomment-1431520676
' But in case where we don't have lengthSeconds from Invidious, it's better than nothing
videoDuration = segment.videoDuration
end if
if videoDuration = 0 or videoDuration = invalid
continue for
end if
pixelStart = (segment.segment[0] / videoDuration) * width
pixelEnd = (segment.segment[1] / videoDuration) * width
color = SponsorBlock.SegmentColor(segment.category)
' highlight's duration is zero, so it is not visble on the bar.
' Add a couple of pixels to see it
if pixelStart = pixelEnd
pixelEnd += 2
end if
bar.DrawRect(pixelStart, 0, pixelEnd - pixelStart, height, color)
end for
bar.Finish()
buffer = bar.GetPng(0, 0, width, height)
buffer.WriteFile(path)
end function
end namespace
@@ -0,0 +1,30 @@
import "pkg:/source/utils/Types.bs"
namespace ArrayUtils
function IndexOfString(array as object, value as dynamic) as integer
if not IsString(value)
return -1
end if
for i = 0 to array.Count() - 1
if array[i] = value
return i
end if
end for
return -1
end function
function Insert(array as object, value as dynamic, index as integer) as void
if index = 0
array.Unshift(value)
return
end if
if index < array.Count()
for i = array.Count() - 1 to index step -1
array[i + 1] = array[i]
end for
end if
array[index] = value
end function
end namespace
@@ -0,0 +1,21 @@
namespace Tests
@suite
class ArrayUtilsTests extends Rooibos.BaseTestSuite
@describe("ArrayUtils")
@it("Returns the index of a string in an array")
@params("", -1)
@params(invalid, -1)
@params(1, -1)
@params("1", 0)
@params("3", 2)
function _(value as dynamic, expectedIndex as integer)
array = ["1", "2", "3"]
m.assertEqual(ArrayUtils.IndexOfString(array, value), expectedIndex)
end function
end class
end namespace
@@ -27,4 +27,17 @@ namespace ColorUtils
return hexString
end function
function RgbaToInt(r as integer, g as integer, b as integer, a = 255 as integer) as integer
return r * 16777216 + g * 65536 + b * 256 + a
end function
function RandomColorInt() as integer
return RgbaToInt(Rnd(256), Rnd(256), Rnd(256))
end function
function RandomSoftColorInt() as integer
return RgbaToInt(Rnd(100) + 100, Rnd(100) + 100, Rnd(100) + 100)
end function
end namespace
@@ -0,0 +1,28 @@
namespace Tests
@suite
class ColorUtilsTests extends Rooibos.BaseTestSuite
@describe("ColorUtils")
@it("Converts from hex to int")
@params("#00d400B3", 13893811)
@params("#ffff00B3", -65357)
@params("#008a5cB3", 9067699)
@params("#cc00ffB3", -872349773)
function _(hexColor as string, expectedInt as integer)
m.assertEqual(ColorUtils.HexToInt(hexColor), expectedInt)
end function
@it("Converts from int to hex")
@params(13893811, "#00D400B3")
@params(-65357, "#FFFF00B3")
@params(9067699, "#008A5CB3")
@params(-872349773, "#CC00FFB3")
function _(intColor as integer, expectedHex as string)
m.assertEqual(ColorUtils.IntToHex(intColor), expectedHex)
end function
end class
end namespace
-20
View File
@@ -1,20 +0,0 @@
function GetSha256(input as string) as string
return GetEvpDigest(input, "sha256")
end function
function GetSha1(input as string) as string
return GetEvpDigest(input, "sha1")
end function
function GetMd5(input as string) as string
return GetEvpDigest(input, "md5")
end function
function GetEvpDigest(input as string, method as string) as string
buffer = CreateObject("roByteArray")
buffer.FromAsciiString(input)
digest = CreateObject("roEVPDigest")
digest.Setup(method)
return digest.Process(buffer)
end function
@@ -0,0 +1,22 @@
namespace CryptoUtils
function GetSha256(input as string) as string
return GetEvpDigest(input, "sha256")
end function
function GetSha1(input as string) as string
return GetEvpDigest(input, "sha1")
end function
function GetMd5(input as string) as string
return GetEvpDigest(input, "md5")
end function
function GetEvpDigest(input as string, method as string) as string
buffer = CreateObject("roByteArray")
buffer.FromAsciiString(input)
digest = CreateObject("roEVPDigest")
digest.Setup(method)
return digest.Process(buffer)
end function
end namespace
@@ -0,0 +1,37 @@
namespace DebugUtils
function PrintStackTrace(message = invalid as dynamic)
#if DEBUG
try
throw "Handled throw in DebugUtils.PrintStackTrace()"
catch error
lines = []
if message <> invalid
lines.push(`${message}`)
end if
lines.push(`Stacktrace:`)
for i = error.backtrace.count() - 2 to 0 step -1
backtrace = error.backtrace[i]
lines.push(` ${backtrace.function} @ ${backtrace.filename}:${backtrace.line_number}`)
end for
PrintInABox(lines)
end try
#end if
end function
function PrintInABox(lines as object)
#if DEBUG
maxLen = 0
for each line in lines
if line.len() > maxLen
maxLen = line.len()
end if
end for
out = "╔" + string(maxLen + 2, "═") + "╗"
for each line in lines
out += `\n` + "║ " + line + string(maxLen - line.len(), " ") + " ║"
end for
out += `\n` + "╚" + string(maxLen + 2, "═") + "╝"
? out
#end if
end function
end namespace
@@ -0,0 +1,24 @@
import "pkg:/source/utils/Types.bs"
namespace ErrorUtils
function Format(error as dynamic) as string
if error = invalid
return "<invalid>"
end if
if IsString(error)
return error
end if
if IsAssociativeArray(error) and error.DoesExist("message") and error.DoesExist("number") and error.DoesExist("backtrace")
result = `${error.message} (0x${StrI(error.number, 16)}). backtrace:`
for i = error.backtrace.count() - 1 to 0 step -1
backtrace = error.backtrace[i]
result += `\n ${backtrace.function} @ ${backtrace.filename}:${backtrace.line_number}\n`
end for
return result
end if
return `${error}`
end function
end namespace
@@ -0,0 +1,24 @@
function NodeSetFocus(node as object, focus as boolean) as void
if node = invalid
return
end if
if node.hasField("focus")
node.focus = focus
return
end if
' bs:disable-next-line NO_SET_FOCUS
node.SetFocus(focus)
end function
function GetFocusedNode() as object
node = m.top.getScene()
while true
child = node.focusedChild
if child <> invalid and not node.isSameNode(child)
node = child
else
exit while
end if
end while
return node
end function
@@ -0,0 +1,35 @@
namespace Tests
@suite
class FocusManagementTests extends Rooibos.BaseTestSuite
@describe("FocusManagement")
@it("Sets the focus field on the node")
@params(true)
@params(false)
function _(expected as boolean)
node1 = CreateObject("roSGNode", "Node")
node1.addField("focus", "boolean", false)
node1.focus = not expected
NodeSetFocus(node1, expected)
m.assertEqual(node1.focus, expected)
m.assertFalse(node1.hasFocus())
end function
@it("Sets the focus when focus field is not present")
@params(true)
@params(false)
function _(expected as boolean)
node1 = CreateObject("roSGNode", "Node")
m.assertFalse(node1.hasField("focus"))
NodeSetFocus(node1, expected)
m.assertEqual(node1.hasFocus(), expected)
end function
end class
end namespace
-130
View File
@@ -1,130 +0,0 @@
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
function GetLocalIpAddress() as dynamic
if m.ipAddress = invalid or m.ipAddress = ""
di = CreateObject("roDeviceInfo")
ips = di.GetIPAddrs()
for each ip in ips
m.ipAddress = ips[ip]
return m.ipAddress
end for
end if
return m.ipAddress
end function
function GetUserCountryCode() as string
if m.countryCode = invalid or m.countryCode = ""
m.countryCode = CreateObject("roDeviceInfo").GetUserCountryCode()
end if
return m.countryCode
end function
function GetAppInfo() as object
if m.appInfo = invalid
appInfo = CreateObject("roAppInfo")
m.appInfo = {
id: appInfo.GetID(),
version: appInfo.GetVersion(),
git_commit_hash: appInfo.GetValue("git_commit_sha"),
lib_version: GetLibVersion(),
lib_git_commit_hash: GetLibGitCommitHash()
}
end if
return m.appInfo
end function
function GetLatestPlayletLibVersion() as dynamic
if m.latestPlayletLibVersion = invalid
args = {
parseJson: false
}
response = Requests().request("HEAD", "https://github.com/iBicha/playlet/releases/latest", args)
if response.statusCode = 200
if response.headers.location <> invalid
regex = CreateObject("roRegex", "/v?(\d+\.\d+\.\d+)", "")
match = regex.match(response.headers.location)
if match.Count() = 2
m.latestPlayletLibVersion = match[1]
return m.latestPlayletLibVersion
end if
end if
end if
m.latestPlayletLibVersion = "N/A"
end if
return m.latestPlayletLibVersion
end function
function GetLibVersion() as string
values = GetLibManifestValues()
Major = values["major_version"].toInt()
Minor = values["minor_version"].toInt()
Build = values["build_version"].toInt()
return `${Major}.${Minor}.${Build}`
end function
function GetLibGitCommitHash() as string
values = GetLibManifestValues()
if values.doesexist("git_commit_sha")
return values["git_commit_sha"]
end if
return ""
end function
function GetLibManifestValues() as object
if m.linManifestValues = invalid
libManifest = ReadAsciiFile("libpkg:/manifest")
lines = libManifest.Tokenize(UnixNL())
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
m.linManifestValues = values
end if
return m.linManifestValues
end function
function GetDeviceInfo() as object
if m.deviceInfo = invalid
devInfo = CreateObject("roDeviceInfo")
m.deviceInfo = {
model: devInfo.GetModel(),
model_display_name: devInfo.GetModelDisplayName(),
model_type: devInfo.GetModelType(),
model_details: devInfo.GetModelDetails(),
os_version: devInfo.GetOSVersion(),
display_type: devInfo.GetDisplayType(),
display_mode: devInfo.GetDisplayMode(),
display_aspect_ratio: devInfo.GetDisplayAspectRatio(),
display_size: devInfo.GetDisplaySize(),
video_mode: devInfo.GetVideoMode(),
ui_resolution: devInfo.GetUIResolution(),
graphics_platform: devInfo.GetGraphicsPlatform(),
internet_status: devInfo.GetInternetStatus(),
user_country_code: devInfo.GetUserCountryCode(),
friendly_name: devInfo.GetFriendlyName()
}
end if
return m.deviceInfo
end function
function ArrayIndexOf(array as object, value as string) as integer
for i = 0 to array.Count() - 1
if array[i] = value
return i
end if
end for
return -1
end function
@@ -0,0 +1,7 @@
function ShowLoadingScreen()
m.global.loadingIndicator.visible = true
end function
function HideLoadingScreen()
m.global.loadingIndicator.visible = false
end function
@@ -0,0 +1,43 @@
namespace Tests
@suite
class LoadingScreenTests extends Rooibos.BaseTestSuite
protected override function setup()
m.hasLoadingIndicator = m.global.hasField("loadingIndicator")
if m.hasLoadingIndicator
m.currentLoadingIndicator = m.global.loadingIndicator
else
m.global.addField("loadingIndicator", "node", false)
end if
if m.global.loadingIndicator = invalid
m.global.loadingIndicator = CreateObject("roSGNode", "Group")
end if
end function
protected override function tearDown()
if m.hasLoadingIndicator
m.global.loadingIndicator = m.currentLoadingIndicator
else
m.global.removeField("loadingIndicator")
end if
end function
@describe("LoadingScreen")
@it("Shows loading screen")
function _()
ShowLoadingScreen()
m.assertEqual(m.global.loadingIndicator.visible, true)
end function
@it("Hides loading screen")
function _()
HideLoadingScreen()
m.assertEqual(m.global.loadingIndicator.visible, false)
end function
end class
end namespace
+17
View File
@@ -0,0 +1,17 @@
import "pkg:/source/roku_modules/log/LogMixin.brs"
enum LogLevel
ERROR = 0
WARN = 1
INFO = 2
VERBOSE = 3
DEBUG = 3
end enum
function InitializeLogging() as void
instance = log.getLogInstance()
if instance <> invalid
return
end if
log.initializeLogManager(["log_PrintTransport", "log_FileTransport"], LogLevel.INFO)
end function
+10 -3
View File
@@ -1,4 +1,5 @@
import "pkg:/source/utils/General.bs"
import "pkg:/source/utils/ArrayUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
class RingBuffer
private array
@@ -11,12 +12,18 @@ class RingBuffer
m.index = 0
end function
function Push(tvalue as dynamic)
function Push(tvalue as dynamic) as void
if StringUtils.IsNullOrEmpty(tvalue)
return
end if
m.array[m.index] = tvalue
m.index = (m.index + 1) mod m.size
end function
function Contains(tvalue as dynamic) as boolean
return ArrayIndexOf(m.array, tvalue) <> -1
if StringUtils.IsNullOrEmpty(tvalue)
return false
end if
return ArrayUtils.IndexOfString(m.array, tvalue) <> -1
end function
end class
+23 -144
View File
@@ -1,149 +1,28 @@
REM Functions in this file:
REM isnonemptystr
REM isnullorempty
REM strtobool
REM itostr
REM strTrim
REM strTokenize
REM
namespace StringUtils
function IsNullOrEmpty(obj as dynamic) as boolean
return ((obj = invalid) or (GetInterface(obj, "ifString") = invalid) or (Len(obj) = 0))
end function
'******************************************************
'isnonemptystr
'
'Determine if the given object supports the ifString interface
'and returns a string of non zero length
'******************************************************
function isnonemptystr(obj as dynamic) as boolean
return ((obj <> invalid) and (GetInterface(obj, "ifString") <> invalid) and (Len(obj) > 0))
end function
'******************************************************
'isnullorempty
'
'Determine if the given object is invalid or supports
'the ifString interface and returns a string of zero length
'******************************************************
function isnullorempty(obj as dynamic) as boolean
return ((obj = invalid) or (GetInterface(obj, "ifString") = invalid) or (Len(obj) = 0))
end function
'******************************************************
'strtobool
'
'Convert string to boolean safely. Don't crash
'Looks for certain string values
'******************************************************
function strtobool(obj as dynamic) as boolean
if obj = invalid
return false
end if
if type(obj) <> "roString" and type(obj) <> "String"
return false
end if
o = strTrim(obj)
o = Lcase(o)
if o = "true"
return true
end if
if o = "t"
return true
end if
if o = "y"
return true
end if
if o = "1"
return true
end if
return false
end function
'******************************************************
'booltostr
'
'Converts a boolean value to a cannonical string value
'******************************************************
function booltostr(bool as boolean) as string
if bool = true
return "true"
end if
return "false"
end function
'******************************************************
'itostr
'
'Convert int to string. This is necessary because
'the builtin Stri(x) prepends whitespace
'******************************************************
function itostr(i as integer) as string
str = Stri(i)
return strTrim(str)
end function
'******************************************************
'Trim a string
'******************************************************
function strTrim(str as string) as string
st = CreateObject("roString")
st.SetString(str)
return st.Trim()
end function
'******************************************************
'Tokenize a string. Return roList of strings
'******************************************************
function strTokenize(str as string, delim as string) as object
st = CreateObject("roString")
st.SetString(str)
return st.Tokenize(delim)
end function
function UnixNL() as string
return chr(10)
end function
function WinNL() as string
return chr(13) + chr(10)
end function
function Quote() as string
return chr(34)
end function
function StringLastIndexOf(str as string, substr as string) as integer
index = str.InStr(substr)
while index <> -1
newIndex = str.InStr(index + 1, substr)
if newIndex = -1
return index
function PathJoin(path1 as string, path2 as string) as string
if path1.EndsWith("/")
path1 = path1.left(path1.len() - 1)
end if
index = newIndex
end while
return index
end function
if path2.StartsWith("/")
path2 = path2.Mid(1)
end if
return path1 + "/" + path2
end function
function PathJoin(path1 as string, path2 as string) as string
if path1.EndsWith("/")
path1 = path1.left(path1.len() - 1)
end if
if path2.StartsWith("/")
path2 = path2.Mid(1)
end if
return path1 + "/" + path2
end function
function ToBase64(input as string) as string
buffer = createObject("roByteArray")
buffer.FromAsciiString(input)
return buffer.ToBase64String()
end function
function ToBase64(input as string) as string
buffer = createObject("roByteArray")
buffer.FromAsciiString(input)
return buffer.ToBase64String()
end function
function FromBase64(input as string) as string
buffer = createObject("roByteArray")
buffer.FromBase64String(input)
return buffer.ToAsciiString()
end function
end namespace
function FromBase64(input as string) as string
buffer = createObject("roByteArray")
buffer.FromBase64String(input)
return buffer.ToAsciiString()
end function
@@ -0,0 +1,19 @@
namespace Tests
@suite
class StringUtilsTests extends Rooibos.BaseTestSuite
@describe("StringUtils")
@it("Checks if a string is null or empty")
@params("test", false)
@params("", true)
@params(invalid, true)
@params(-5, true)
function _(obj as dynamic, expected as boolean)
m.assertEqual(StringUtils.IsNullOrEmpty(obj), expected)
end function
end class
end namespace
+16 -27
View File
@@ -1,9 +1,14 @@
import "pkg:/source/utils/Types.bs"
import "Types.bs"
namespace TimeUtils
' Helper function convert seconds to [hh:]mm:ss format
' getTime(138) returns 2:18
function GetFormattedTime(length as integer) as string
' GetFormattedTime(138) returns 2:18
function GetFormattedTime(length as dynamic) as string
if length = invalid or length < 0
return "0:00"
end if
hours = length \ 3600
minutes = (length \ 60) mod 60
seconds = length mod 60
@@ -29,7 +34,7 @@ namespace TimeUtils
return formattedTime
end function
function GetFormattedTimeLeft(unixTimestamp as integer) as string
function GetFormattedTimeLeft(unixTimestamp as dynamic) as string
if unixTimestamp = invalid
return "N/A"
end if
@@ -89,13 +94,13 @@ namespace TimeUtils
function RFC1123_Date(when as object) as string
wd = when.getWeekday().left(3)
dom = Stri(when.getDayOfMonth()).trim()
dom = when.getDayOfMonth()
mon = Ucase(TimeUtils.MonthStr(when.getMonth()).left(3))
yr = Stri(when.getYear()).trim()
hr = Stri(when.getHours()).trim()
mn = Stri(when.getMinutes()).trim()
sc = Stri(when.getSeconds()).trim()
date = wd + ", " + dom + " " + mon + " " + yr + " " + hr + ":" + mn + ":" + sc + " GMT"
yr = when.getYear()
hr = when.getHours()
mn = when.getMinutes()
sc = when.getSeconds()
date = `${wd}, ${dom} ${mon} ${yr} ${hr}:${mn}:${sc} GMT"`
return date
end function
@@ -105,23 +110,7 @@ namespace TimeUtils
ma = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
m.Num2Month = ma
end if
return validstr(ma[mNum - 1])
end function
function ParseTime(time as string) as integer
hours = 0
minutes = 0
seconds = 0
tokens = time.Tokenize(":")
if tokens.Count() = 3
hours = tokens[0].ToInt()
minutes = tokens[1].ToInt()
seconds = tokens[2].ToInt()
else if tokens.Count() = 2
minutes = tokens[0].ToInt()
seconds = tokens[1].ToInt()
end if
return hours * 3600 + minutes * 60 + seconds
return ValidString(ma[mNum - 1])
end function
end namespace
@@ -0,0 +1,38 @@
namespace Tests
@suite
class TimeUtilsTests extends Rooibos.BaseTestSuite
@describe("TimeUtils")
@it("formats the time correctly")
@params(invalid, "0:00")
@params(-1, "0:00")
@params(0, "0:00")
@params(7, "0:07")
@params(138, "2:18")
@params(8285, "2:18:05")
@params(1282085, "356:08:05")
function _(length as dynamic, formattedString as string)
m.assertEqual(TimeUtils.GetFormattedTime(length), formattedString)
end function
@it("formats the time left correctly")
@params(invalid, "N/A")
@params(-1, "now")
@params(0, "now")
@params(1, "1 second")
@params(7, "7 seconds")
@params(8285, "2 hours")
@params(1282085, "15 days")
function _(length as dynamic, formattedString as string)
time = invalid
if length <> invalid
time = TimeUtils.Now().AsSeconds() + length
end if
m.assertEqual(TimeUtils.GetFormattedTimeLeft(time), formattedString)
end function
end class
end namespace
+16 -123
View File
@@ -1,108 +1,24 @@
REM Functions in this file:
REM isxmlelement
REM islist
REM isint
REM isfunc
REM isstr
REM isbool
REM isfloat
REM validstr
REM validateParam
REM
'******************************************************
'isxmlelement
'
'Determine if the given object supports the ifXMLElement interface
'******************************************************
function isxmlelement(obj as dynamic) as boolean
return obj <> invalid and GetInterface(obj, "ifXMLElement") <> invalid
end function
'******************************************************
'islist
'
'Determine if the given object supports the ifList interface
'******************************************************
function islist(obj as dynamic) as boolean
return obj <> invalid and GetInterface(obj, "ifArray") <> invalid
end function
'******************************************************
'isint
'
'Determine if the given object supports the ifInt interface
'******************************************************
function isint(obj as dynamic) as boolean
return obj <> invalid and GetInterface(obj, "ifInt") <> invalid
end function
'******************************************************
'isfunc
'
'Determine if the given object supports the function interface
'******************************************************
function isfunc(obj as dynamic) as boolean
tf = type(obj)
return tf = "Function" or tf = "roFunction"
end function
'******************************************************
'isstr
'
'Determine if the given object supports the ifString interface
'******************************************************
function isstr(obj as dynamic) as boolean
function IsString(obj as dynamic) as boolean
return obj <> invalid and GetInterface(obj, "ifString") <> invalid
end function
function isAssocArray(obj as dynamic) as boolean
function IsArray(obj as dynamic) as boolean
return obj <> invalid and GetInterface(obj, "ifArray") <> invalid
end function
function IsAssociativeArray(obj as dynamic) as boolean
return obj <> invalid and GetInterface(obj, "ifAssociativeArray") <> invalid
end function
'******************************************************
'isbool
'
'Determine if the given object supports the ifBoolean interface
'******************************************************
function isbool(obj as dynamic) as boolean
if obj = invalid
return false
end if
if GetInterface(obj, "ifBoolean") = invalid
return false
end if
return true
function IsInt(obj as dynamic) as boolean
return obj <> invalid and GetInterface(obj, "ifInt") <> invalid
end function
'******************************************************
'isfloat
'
'Determine if the given object supports the ifFloat interface
'******************************************************
function isfloat(obj as dynamic) as boolean
if obj = invalid
return false
end if
if GetInterface(obj, "ifFloat") = invalid
return false
end if
return true
function IsDouble(obj as dynamic) as boolean
return obj <> invalid and GetInterface(obj, "ifDouble") <> invalid
end function
'******************************************************
' validstr
'
' always return a valid string. if the argument is
' invalid or not a string, return an empty string.
'******************************************************
function validstr(obj as object) as string
function ValidString(obj as object) as string
if obj <> invalid and GetInterface(obj, "ifString") <> invalid
return obj
else
@@ -110,14 +26,7 @@ function validstr(obj as object) as string
end if
end function
'******************************************************
' validint
'
' Always return a valid integer. If the argument is
' invalid or not an integer, return zero.
'******************************************************
function validint(obj as dynamic) as integer
function ValidInt(obj as dynamic) as integer
if obj <> invalid and GetInterface(obj, "ifInt") <> invalid
return obj
else
@@ -125,26 +34,10 @@ function validint(obj as dynamic) as integer
end if
end function
'******************************************************
'Validate parameter is the correct type
'******************************************************
function validateParam(param as object, paramType as string, functionName as string, allowInvalid = false as boolean) as boolean
if paramType = "roString" or paramType = "String"
if type(param) = "roString" or type(param) = "String"
return true
end if
else if type(param) = paramType
return true
function FuncName(func as function) as string
if func <> invalid and GetInterface(func, "ifToStr") <> invalid
return func.toStr().replace("Function: ", "")
end if
if allowInvalid = true
if type(param) = invalid
return true
end if
end if
print "invalid parameter of type "; type(param); " for "; paramType; " in function "; functionName
return false
return ""
end function
@@ -0,0 +1,28 @@
namespace Tests
@suite
class TypesTests extends Rooibos.BaseTestSuite
@describe("Types")
@it("Checks if an object is a string")
@params("test", true)
@params("", true)
@params(invalid, false)
@params(-5, false)
function _(obj as dynamic, expected as boolean)
m.assertEqual(IsString(obj), expected)
end function
@it("Returns a valid string")
@params("test", "test")
@params("", "")
@params(invalid, "")
@params(-5, "")
function _(obj as dynamic, expected as dynamic)
m.assertEqual(ValidString(obj), expected)
end function
end class
end namespace
-119
View File
@@ -1,119 +0,0 @@
import "pkg:/source/utils/Types.bs"
namespace WebUtils
function UrlQueryComponents(url as string) as object
query = {}
index = Instr(0, url, "?")
url = Mid(url, index + 1)
components = url.split("&")
for each component in components
key = component
value = ""
hasValue = false
if Instr(0, component, "=")
keyValue = component.split("=")
key = keyValue[0]
value = keyValue[1].DecodeUriComponent()
hasValue = true
end if
if query.DoesExist(key) and hasValue
oldValue = query[key]
if GetInterface(oldValue, "ifArray") = invalid
oldValue = [oldValue]
end if
oldValue.push(value.DecodeUriComponent())
value = oldValue
end if
if key <> ""
query[key] = value
end if
end for
return query
end function
function MimeType(uri = "" as string) as string
map = m.MimeTypes
if map = invalid
map = {
' Default mimetype mappings
ogg: "application/ogg",
pdf: "application/pdf",
xsl: "application/xml",
xml: "application/xml",
dtd: "application/xml-dtd",
xslt: "application/xslt+xml",
zip: "application/zip",
mp2: "audio/mpeg",
mp3: "audio/mpeg",
mpga: "audio/mpeg",
gif: "image/gif",
jpeg: "image/jpeg",
jpe: "image/jpeg",
jpg: "image/jpeg",
png: "image/png",
svg: "image/svg+xml",
css: "text/css",
html: "text/html",
js: "text/javascript",
txt: "text/plain",
asc: "text/plain",
brs: "text/plain",
bs: "text/plain",
map: "text/plain",
mpeg: "video/mpeg",
mpe: "video/mpeg",
mpg: "video/mpeg",
qt: "video/quicktime",
mov: "video/quicktime",
avi: "video/x-msvideo",
default: "application/octet-stream"
}
m.MimeTypes = map
end if
ext = WebUtils.GetExtension(uri)
if map.doesexist(ext)
return map[ext]
else
return map.default
end if
end function
function GetExtension(fn as string) as string
l = fn.tokenize(".")
if l.count() > 0
return l.GetTail()
else
return ""
end if
end function
function HttpTitle(code = 0 as integer) as string
hcm = m.HttpTitles
if hcm = invalid
hcm = { n101: "Switching Protocols" }
hcm.append({ n200: "OK", n206: "Partial Content" })
hcm.append({ n301: "Moved Permanently", n304: "Not Modified" })
hcm.append({ n400: "Bad Request", n401: "Unauthorized", n403: "Forbidden", n404: "Not Found", n413: "Request Entity Too Large" })
hcm.append({ n500: "Internal Server Error", n501: "Not Implemented" })
m.HttpTitles = hcm
end if
return validstr(hcm["n" + Stri(code).trim()])
end function
function EscapeUrlForXml(url as string) as string
urlEscapeChars = {}
urlEscapeChars["&"] = "&amp;"
urlEscapeChars["'"] = "&apos;"
urlEscapeChars[`"`] = "&quot;"
urlEscapeChars["<"] = "&lt;"
urlEscapeChars[">"] = "&gt;"
for each escapeChar in urlEscapeChars
url = url.Replace(escapeChar, urlEscapeChars[escapeChar])
end for
return url
end function
end namespace