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

@@ -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