Create Component Library (#43)

* Move src under playlet-lib

* Update configuration

* Update script

* Update script

* Working version

* Vs code config WIP

* Package lock sync

* Lint fix

* Fix images

* Reuse config files

* Kind of a working setup

* Lock node version

* Rename scripts to tools

* Fix build scripts, lib url system

* Lint fix

* rale

* Fix args and web server

* Load fallbacks and build script cleanups

* Remove unused method

* no message

* no message

* Remove generic message field

* Lint fix

* no message

* Use loading indicator on main app

* Add playlet lib version to settings

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
Brahim Hadricheandgithub-action linter authored and GitHub committed 2023-01-29 16:50:28 -05:00
1 parent 90df81df4b
commit 9d8a3d1cea
156 files changed
+3341 -213

No files matched your search

@@ -0,0 +1,48 @@
import "pkg:/source/utils/Types.bs"
function StartAsyncTask(taskFunc as object, input as object, callback = invalid as object) as object
task = CreateAsyncTask(taskFunc, input, callback)
task.control = "RUN"
return task
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.id = id
task.input = input
m[`asynctask_${id}`] = task
m[`asynctask_${id}_callback`] = callback
task.ObserveField("state", "OnTaskState")
return task
end function
function GetFunctionName(taskFunc as object) as string
if IsStr(taskFunc)
return LCase(`${taskFunc}_asynctask`)
end if
return (LCase(`${taskFunc}_asynctask`)).replace("function:", "").trim()
end function
function OnTaskState(e as object) as void
task = e.getRoSGNode()
if task.state = "init" or task.state = "run"
return
end if
id = task.id
output = task.output
' if output is invalid, it means the task was interrupted before the result is ready
if output <> invalid
callback = m[`asynctask_${id}_callback`]
if callback <> invalid
output = task.output
callback(output)
end if
end if
m.delete(`asynctask_${id}`)
m.delete(`asynctask_${id}_callback`)
end function
@@ -0,0 +1,43 @@
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
@@ -0,0 +1,10 @@
namespace Invidious
class SearchSuggestionResult
public query as string
public suggestions as object
end class
end namespace
@@ -0,0 +1,160 @@
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 SEARCH_SUGGEST_ENDPOINT = "/api/v1/search/suggestions"
const SEARCH_ENDPOINT = "/api/v1/search"
const AUTH_SCOPE = "GET:feed,GET:playlists,POST:tokens/unregister"
const AUTH_FEED = "/api/v1/auth/feed"
const AUTH_PLAYLISTS = "/api/v1/auth/playlists"
const AUTH_TOKENS_UNREGISTER = "/api/v1/auth/tokens/unregister"
function DefaultArgs() as object
return {
params: {
region: GetUserCountryCode()
}
}
end function
function GetServerStats() as object
instance = InvidiousSettings.GetSelectedInstance()
url = `${instance}${Invidious.STATS_ENDPOINT}`
response = Requests().get(url)
if response.statuscode = 200
return response.json
end if
return invalid
end function
function GetVideoUrl(videoId as string, itag as string, local as boolean) as string
instance = InvidiousSettings.GetSelectedInstance()
url = `${instance}/latest_version?id=${videoId}&itag=${itag}`
if local
url = url + "&local=true"
end if
return url
end function
function GetVideoMetadata(videoId as string) as object
instance = InvidiousSettings.GetSelectedInstance()
url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}`
args = Invidious.DefaultArgs()
args.cacheSeconds = 60 * 60 * 6 ' 6 hours
response = Requests().get(url, args)
return {
success: response.statuscode = 200,
statusCode: response.statuscode,
data: response.json ?? response.text
}
end function
function SearchSuggestions(q as string) as object 'SearchSuggestionResult
instance = InvidiousSettings.GetSelectedInstance()
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.GetSelectedInstance()
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.GetSelectedInstance()
' 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() + 60 * 60 * 24 * 365 * 2 '2 years from now
callbackUrl = `http://${localIp}:${webServerPort}${Invidious.TOKEN_CALLBACK}?ref=${instance}`.EncodeUriComponent()
return `${invidiousHost}/authorize_token?scopes=${Invidious.AUTH_SCOPE}&callback_url=${callbackUrl}&expire=${expire}`
end function
function GetAuthenticationHeaders(token as string) as object
return {
"Authorization": `Bearer ${token}`
}
end function
function Logout() as boolean
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
return false
end if
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
}
Requests().post(url, args)
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
return true
end function
end namespace
@@ -0,0 +1,175 @@
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/services/InvidiousSettings.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.GetSelectedInstance()
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
if endpoint.requestArgs <> invalid
args.append(endpoint.requestArgs)
end if
response = Requests().get(url, args)
responseHandler = endpoint.responseHandler <> invalid ? m.responseHanlders[endpoint.responseHandler] : m.responseHanlders["DefaultHandler"]
return responseHandler(m, requestData, response)
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 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 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
result.append(m.ProcessPlaylist(requestData, playlist))
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 = requestData.title
title = m.ProcessTemplate(title, playlist)
result = {}
result[title] = playlist.videos
return result
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(`Server responded with 403: ${response.text}`)
if m.IsTokenMaybeExpired() = true
print("deleting token...")
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
end if
end if
end function
' Public Invidious instances fail a lot randomly, even with valid tokens
' For that reason, it's better to make sure the token actually expired by date
function IsTokenMaybeExpired() as dynamic
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
return invalid
end if
token = ParseJson(authToken.token)
if token = invalid
return invalid
end if
if not token.DoesExist("expire")
return invalid
end if
expire = token["expire"]
currentTime = TimeUtils.Now().AsSeconds()
return expire < currentTime
end function
end class
@@ -0,0 +1,107 @@
namespace InvidiousSettings
const DEFAULT_INSTANCE = "https://vid.puffyan.us"
const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,users"
function GetCurrentInstances() as object
' TODO: cache this call to avoid json parsing every time
instances = InvidiousSettings.GetRegistryInstances()
if instances.Count() > 0
return instances
end if
publicInstances = InvidiousSettings.GetPublicInstances()
if publicInstances <> invalid
for i = 0 to publicInstances.Count() - 1
if InvidiousSettings.IsValidPublicInstance(publicInstances[i])
instances.push(publicInstances[i].uri)
end if
if instances.Count() >= 5
exit for
end if
end for
end if
if instances.Count() > 0
InvidiousSettings.SetRegistryInstances(instances)
return instances
end if
return [InvidiousSettings.DEFAULT_INSTANCE]
end function
function GetSelectedInstance() as string
instances = InvidiousSettings.GetCurrentInstances()
return instances[0]
end function
function SetAuthToken(token as string, instance as string)
json = FormatJson({
token: token,
instance: instance
})
RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json)
instances = InvidiousSettings.GetCurrentInstances()
index = ArrayIndexOf(instances, instance)
if index = -1
instances.push(instance)
InvidiousSettings.SetRegistryInstances(instances)
end if
end function
function GetAuthToken() as dynamic
tokenPayload = RegistryUtils.Read(RegistryUtils.INVIDIOUS_TOKEN)
if tokenPayload = invalid
return invalid
end if
return ParseJson(tokenPayload)
end function
function GetRegistryInstances() as object
instances = RegistryUtils.Read(RegistryUtils.INVIDIOUS_INSTANCES)
if instances = invalid
return []
end if
return ParseJson(instances)
end function
function SetRegistryInstances(instances as object)
RegistryUtils.Write(RegistryUtils.INVIDIOUS_INSTANCES, FormatJson(instances))
end function
function GetPublicInstances() as object
if m.invidiousPublicInstances <> invalid
return m.invidiousPublicInstances
end if
response = Requests().get(InvidiousSettings.INSTANCES_API)
if response.statuscode = 200
json = response.json
instances = []
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
m.invidiousPublicInstances = instances
end if
return m.invidiousPublicInstances
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
@@ -0,0 +1,106 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/utils/WebUtils.bs"
import "pkg:/source/utils/Crypto.bs"
namespace SponsorBlock
const API_URL = "https://sponsor.ajay.app"
const SKIP_SEGMENT_ENDPOINT = "/api/skipSegments"
const VIEWED_SEGMENT_ENDPOINT = "/api/viewedVideoSponsorTime"
function SegmentColor(category as string) as integer
map = m.SponsorBlockColors
if map = invalid
map = {
sponsor: &h00D400FF,
selfpromo: &hFFFF00FF,
exclusive_access: &h008A5CFF,
interaction: &hCC00FFFF,
poi_highlight: &hFF1684FF,
intro: &h00FFFFFF,
outro: &h0202EDFF,
preview: &h008FD6FF,
filler: &h7300FFFF,
music_offtopic: &hFF9900FF
}
m.SponsorBlockColors = map
end if
if map.doesexist(category)
return map[category]
end if
return 0
end function
function SegmentTitle(category as string) as string
map = m.SponsorBlockTitles
if map = invalid
map = {
sponsor: "Sponsor",
selfpromo: "Unpaid/Self Promotion",
exclusive_access: "Exclusive Access",
interaction: "Interaction Reminder (Subscribe)",
poi_highlight: "Highlight",
intro: "Intermission/Intro Animation",
outro: "Endcards/Credits",
preview: "Preview/Recap",
filler: "Filler Tangent/Jokes",
music_offtopic: "Non-Music Section"
}
m.SponsorBlockTitles = map
end if
if map.doesexist(category)
return map[category]
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, 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
pixelStart = (segment.segment[0] / segment.videoDuration) * width
pixelEnd = (segment.segment[1] / segment.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
+17
View File
@@ -0,0 +1,17 @@
function GetSha256(input as string) as string
buffer = CreateObject("roByteArray")
buffer.FromAsciiString(input)
digest = CreateObject("roEVPDigest")
digest.Setup("sha256")
return digest.Process(buffer)
end function
function GetSha1(input as string) as string
buffer = CreateObject("roByteArray")
buffer.FromAsciiString(input)
digest = CreateObject("roEVPDigest")
digest.Setup("sha1")
return digest.Process(buffer)
end function
+17
View File
@@ -0,0 +1,17 @@
function IsDebugMode() as boolean
appInfo = CreateObject("roAppInfo")
bsConst = appInfo.GetValue("bs_const")
symbols = bsConst.Tokenize(";")
for each symbol in symbols
keyValuePair = symbol.Tokenize("=")
if keyValuePair.Count() <> 2
continue for
end if
if UCase(keyValuePair[0]) = "DEBUG"
return UCase(keyValuePair[1]) = "TRUE"
end if
end for
return false
end function
+89
View File
@@ -0,0 +1,89 @@
function GetLocalIpAddress() as string
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(),
lib_version: GetLibVersion()
}
end if
return m.appInfo
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 GetLibManifestValues() as object
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
return values
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()
}
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,41 @@
namespace RegistryUtils
const DEFAULT_SECTION = "Playlet"
const INVIDIOUS_INSTANCES = "invidious_instances"
const INVIDIOUS_TOKEN = "invidious_token"
function Read(key as string, section = DEFAULT_SECTION as string) as dynamic
sec = CreateObject("roRegistrySection", section)
if sec.Exists(key)
return sec.Read(key)
end if
return invalid
end function
function Write(key as string, value as string, section = DEFAULT_SECTION as string)
sec = CreateObject("roRegistrySection", section)
sec.Write(key, value)
sec.Flush()
end function
function Delete(key as string, section = DEFAULT_SECTION as string)
sec = CreateObject("roRegistrySection", section)
sec.Delete(key)
sec.Flush()
end function
function ReadAll() as object
result = {}
registry = CreateObject("roRegistry")
sectionNames = registry.GetSectionList()
for each sectionName in sectionNames
section = CreateObject("roRegistrySection", sectionName)
keys = section.GetKeyList()
values = section.ReadMulti(keys)
result[sectionName] = values
end for
return result
end function
end namespace
+149
View File
@@ -0,0 +1,149 @@
REM Functions in this file:
REM isnonemptystr
REM isnullorempty
REM strtobool
REM itostr
REM strTrim
REM strTokenize
REM
'******************************************************
'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
end if
index = newIndex
end while
return index
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 FromBase64(input as string) as string
buffer = createObject("roByteArray")
buffer.FromBase64String(input)
return buffer.ToAsciiString()
end function
+112
View File
@@ -0,0 +1,112 @@
import "pkg:/source/utils/Types.bs"
namespace TimeUtils
' Helper function convert seconds to mm:ss format
' getTime(138) returns 2:18
function GetFormattedTime(length as integer) as string
minutes = (length \ 60).ToStr()
seconds = length mod 60
if seconds < 10
seconds = "0" + seconds.ToStr()
else
seconds = seconds.ToStr()
end if
return minutes + ":" + seconds
end function
function GetFormattedTimeLeft(unixTimestamp as integer) as string
if unixTimestamp = invalid
return "N/A"
end if
currentTime = TimeUtils.Now().AsSeconds()
timeLeft = unixTimestamp - currentTime
if timeLeft <= 0
return "now"
end if
if timeLeft < 60
result = `${timeLeft} second`
if timeLeft > 1
result += "s"
end if
return result
end if
timeLeft = timeLeft / 60.0
if timeLeft < 60
timeLeft = Cint(timeLeft)
result = `${timeLeft} minute`
if timeLeft > 1
result += "s"
end if
return result
end if
timeLeft = timeLeft / 60.0
if timeLeft < 24
timeLeft = Cint(timeLeft)
result = `${timeLeft} hour`
if timeLeft > 1
result += "s"
end if
return result
else
timeLeft = timeLeft / 24.0
timeLeft = Cint(timeLeft)
result = `${timeLeft} day`
if timeLeft > 1
result += "s"
end if
return result
end if
end function
function Now() as object
this = m.now
if this = invalid
this = CreateObject("roDateTime")
m.now = this
end if
this.mark()
return this
end function
function RFC1123_Date(when as object) as string
wd = when.getWeekday().left(3)
dom = Stri(when.getDayOfMonth()).trim()
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"
return date
end function
function MonthStr(mNum as integer) as string
ma = m.Num2Month
if ma = invalid
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
end function
end namespace
+150
View File
@@ -0,0 +1,150 @@
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
return obj <> invalid and GetInterface(obj, "ifString") <> invalid
end function
function isAssocArray(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
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
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
if obj <> invalid and GetInterface(obj, "ifString") <> invalid
return obj
else
return ""
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
if obj <> invalid and GetInterface(obj, "ifInt") <> invalid
return obj
else
return 0
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
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
end function
+117
View File
@@ -0,0 +1,117 @@
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]
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)
value = oldValue
end if
query[key] = value
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