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