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:
349 files changed
+12784
-7660
No files matched your search
@@ -0,0 +1,194 @@
|
||||
import "HttpSettings.bs"
|
||||
import "HttpRequest.bs"
|
||||
import "HttpResponse.bs"
|
||||
import "pkg:/source/utils/Types.bs"
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
import "pkg:/source/roku_modules/log/LogMixin.brs"
|
||||
|
||||
namespace Http
|
||||
const BUFSIZE = 65536
|
||||
|
||||
class HttpConnection
|
||||
private log as log.Logger
|
||||
|
||||
private total_received = 0
|
||||
private total_sent = 0
|
||||
private id = "<uninit>"
|
||||
private close = true
|
||||
private ws_upgrade = false
|
||||
private state = Http.HttpConnectionState.INIT
|
||||
|
||||
private server as HttpServer
|
||||
private settings as HttpSettings
|
||||
|
||||
function new(server as HttpServer, settings as HttpSettings)
|
||||
m.log = new log.Logger("HttpConnection")
|
||||
m.server = server
|
||||
m.settings = settings
|
||||
m.Reset()
|
||||
end function
|
||||
|
||||
function Reset()
|
||||
' re-initializes all instance members
|
||||
m.socket = invalid
|
||||
m.addr = invalid
|
||||
m.Restart()
|
||||
end function
|
||||
|
||||
function Restart()
|
||||
' re-initializes members for next request-response
|
||||
m.last_active = CreateObject("roTimespan")
|
||||
m.request = new HttpRequest()
|
||||
m.header = invalid
|
||||
m.response = invalid
|
||||
m.header_only = false
|
||||
m.http_code = 0
|
||||
m.close = true
|
||||
m.ws_upgrade = false
|
||||
m.SetState(Http.HttpConnectionState.INIT)
|
||||
end function
|
||||
|
||||
function Recycle()
|
||||
m.log.info("recycle")
|
||||
m.Restart()
|
||||
m.SetState(Http.HttpConnectionState.RECV_REQUEST) ' ready for another
|
||||
end function
|
||||
|
||||
function Accepted(server as HttpServer, socket as object)
|
||||
m.socket = socket
|
||||
m.id = socket.getID().ToStr()
|
||||
m.SetState(Http.HttpConnectionState.RECV_REQUEST)
|
||||
m.client = m.socket.getReceivedFromAddress().getAddress()
|
||||
|
||||
m.log.info("accepted connection @" + m.client)
|
||||
|
||||
' try to read right away rather than going through another iteration
|
||||
' of the poll loop.
|
||||
m.PollRequest(server)
|
||||
end function
|
||||
|
||||
function PollRequest(server as HttpServer)
|
||||
if m.state <> Http.HttpConnectionState.RECV_REQUEST
|
||||
m.log.error("illegal request state @" + m.client)
|
||||
end if
|
||||
|
||||
rcvStrByteLen = m.socket.GetCountRcvBuf()
|
||||
rcvStr = m.socket.receiveStr(Http.BUFSIZE)
|
||||
received = rcvStr.len()
|
||||
rcvStrByteLen -= m.socket.GetCountRcvBuf()
|
||||
|
||||
maybeUnicode = rcvStrByteLen <> received
|
||||
|
||||
if m.CheckResult(received, "receive request")
|
||||
m.total_received = m.total_received + received
|
||||
server.total_in = server.total_in + received
|
||||
end if
|
||||
|
||||
' append to connection request
|
||||
m.request.Add(rcvStr, maybeUnicode)
|
||||
|
||||
if m.request.ProcessNext(m)
|
||||
if m.request.state = Http.HttpRequestState.DONE
|
||||
server.num_requests = validint(server.num_requests) + 1
|
||||
m.response = new HttpResponse(m.request, m.server, m.settings)
|
||||
m.response.Process(m)
|
||||
m.SetState(Http.HttpConnectionState.SEND_HEADER)
|
||||
else
|
||||
m.setState(Http.HttpConnectionState.DONE)
|
||||
m.close = true
|
||||
m.log.error("couldn't process request or response, closing @" + m.client)
|
||||
end if
|
||||
else if m.request.buffer.len() > m.settings.MaxRequestLength ' die if it's too long
|
||||
m.response = new HttpResponse(m.request, m.server, m.settings)
|
||||
m.response.Default(413, "Your request was dropped because it was too long.")
|
||||
m.SetState(Http.HttpConnectionState.SEND_HEADER)
|
||||
end if
|
||||
|
||||
' if we've moved on to the next state, try to send right away, instead of
|
||||
' going through another iteration of the poll loop.
|
||||
'
|
||||
if m.state = Http.HttpConnectionState.SEND_HEADER
|
||||
m.PollHeader(server)
|
||||
end if
|
||||
end function
|
||||
|
||||
function PollHeader(server as HttpServer) as void
|
||||
if m.state <> Http.HttpConnectionState.SEND_HEADER
|
||||
m.log.error("illegal header state @" + m.client)
|
||||
end if
|
||||
|
||||
sent = m.response.SendHeader(m.socket, Http.BUFSIZE)
|
||||
|
||||
if m.CheckResult(sent, "send header")
|
||||
m.total_sent = m.total_sent + sent
|
||||
server.total_out = server.total_out + sent
|
||||
end if
|
||||
|
||||
if m.response.DoneHeader()
|
||||
if m.response.header_only
|
||||
m.SetState(Http.HttpConnectionState.DONE)
|
||||
else
|
||||
m.SetState(Http.HttpConnectionState.SEND_RESPONSE)
|
||||
m.PollResponse(server)
|
||||
end if
|
||||
end if
|
||||
end function
|
||||
|
||||
function PollResponse(server as HttpServer)
|
||||
if m.state <> Http.HttpConnectionState.SEND_RESPONSE or m.response.header_only
|
||||
m.log.error("illegal response state @" + m.client)
|
||||
end if
|
||||
|
||||
sent = m.response.Send(m.socket, Http.BUFSIZE)
|
||||
if m.CheckResult(sent, "send response")
|
||||
m.total_sent = m.total_sent + sent
|
||||
server.total_out = server.total_out + sent
|
||||
end if
|
||||
|
||||
if m.response.Done()
|
||||
m.SetState(Http.HttpConnectionState.DONE)
|
||||
end if
|
||||
end function
|
||||
|
||||
function CheckTimeout(timeoutInMs as integer)
|
||||
if m.last_active.TotalMilliseconds() > timeoutInMs
|
||||
m.close = true
|
||||
m.SetState(Http.HttpConnectionState.DONE)
|
||||
end if
|
||||
end function
|
||||
|
||||
function CheckResult(byteCount as integer, op as string) as boolean
|
||||
gotSome = false
|
||||
if byteCount > 0
|
||||
m.last_active.mark()
|
||||
gotSome = true
|
||||
else if m.socket.eOK() and not m.socket.eSuccess()
|
||||
'info(m,op + " would have blocked @"+m.client)
|
||||
else
|
||||
if m.socket.eSuccess()
|
||||
m.log.info(op + " peer closed @" + m.client)
|
||||
else
|
||||
m.log.error(op + " transfer error @" + m.client, m.socket.status())
|
||||
end if
|
||||
m.close = true
|
||||
m.SetState(Http.HttpConnectionState.DONE)
|
||||
end if
|
||||
return gotSome
|
||||
end function
|
||||
|
||||
function SetState(newState as Http.HttpConnectionState)
|
||||
if m.state <> newState
|
||||
' m.log.debug(m, "state change" + Stri(m.state) + " ->" + Stri(newState))
|
||||
m.state = newState
|
||||
end if
|
||||
end function
|
||||
|
||||
function LogInfo()
|
||||
if m.http_code <> 0 and not StringUtils.IsNullOrEmpty(m.method)
|
||||
m.log.info(m.last_active.totalSeconds(), " client:", m.client, " meth:", m.method, " uri:", m.uri, " code:", m.code, " sent:", m.total_sent, " referer:", m.referer, " user agent:", m.user_agent)
|
||||
end if
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Http
|
||||
|
||||
enum HttpConnectionState
|
||||
INIT = 0 ' initial state; shouldn't last long
|
||||
RECV_REQUEST = 1 ' receiving request
|
||||
SEND_HEADER = 2 ' sending generated header
|
||||
SEND_RESPONSE = 3 ' sending response
|
||||
DONE = 4 ' response sent, close or reuse as indicated
|
||||
end enum
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,278 @@
|
||||
import "HttpRequestState.bs"
|
||||
import "pkg:/source/utils/Types.bs"
|
||||
import "pkg:/components/Web/WebServer/Http/HttpUtils.bs"
|
||||
|
||||
namespace Http
|
||||
|
||||
function GetHttpRequestId() as integer
|
||||
m.http_request_id = ValidInt(m.http_request_id) + 1
|
||||
return m.http_request_id
|
||||
end function
|
||||
|
||||
class HttpRequest
|
||||
private log as log.Logger
|
||||
|
||||
' members
|
||||
private method = invalid
|
||||
private uri = invalid
|
||||
private route = invalid
|
||||
private query = invalid
|
||||
private protocol = invalid
|
||||
private encoder = invalid
|
||||
private buffer = invalid
|
||||
private buffer_index = 0
|
||||
private headers = invalid
|
||||
private body = invalid
|
||||
private state = Http.HttpRequestState.INIT
|
||||
private id = 0
|
||||
' copied members
|
||||
private range_begin = 0
|
||||
private range_end = 0
|
||||
private range_begin_given = false
|
||||
private range_end_given = false
|
||||
private ready_for_response = false
|
||||
|
||||
function new()
|
||||
m.log = new log.Logger("HttpRequest")
|
||||
m.id = Http.GetHttpRequestId()
|
||||
m.headers = CreateObject("roAssociativeArray")
|
||||
end function
|
||||
|
||||
function Add(incoming as string, maybeUnicode as boolean)
|
||||
if IsString(m.buffer)
|
||||
m.buffer = m.buffer + incoming
|
||||
else
|
||||
m.buffer = incoming
|
||||
end if
|
||||
m.maybe_unicode = maybeUnicode
|
||||
end function
|
||||
|
||||
function ProcessNext(connection as HttpConnection) as boolean
|
||||
if m.state = Http.HttpRequestState.DONE
|
||||
return m.ready_for_response
|
||||
end if
|
||||
|
||||
if m.state = Http.HttpRequestState.INIT
|
||||
m.state = Http.HttpRequestState.READING_OPERATION
|
||||
end if
|
||||
|
||||
if m.state = Http.HttpRequestState.READING_OPERATION
|
||||
if m.ParseOperation()
|
||||
m.ProcessOperation(connection.server.utils)
|
||||
m.state = Http.HttpRequestState.READING_HEADERS
|
||||
end if
|
||||
end if
|
||||
|
||||
if m.state = Http.HttpRequestState.READING_HEADERS
|
||||
if m.ParseHeaders()
|
||||
m.ProcessHeaders(connection)
|
||||
m.state = Http.HttpRequestState.READING_BODY
|
||||
end if
|
||||
end if
|
||||
|
||||
if m.state = Http.HttpRequestState.READING_BODY
|
||||
if m.ParseBody()
|
||||
m.state = Http.HttpRequestState.DONE
|
||||
end if
|
||||
end if
|
||||
|
||||
return m.ready_for_response
|
||||
end function
|
||||
|
||||
function ParseOperation() as boolean
|
||||
if m.buffer_index <> 0
|
||||
m.log.error(`invalid state: reading operation, but request is at index ${m.buffer_index}`)
|
||||
m.ready_for_response = true
|
||||
return false
|
||||
end if
|
||||
|
||||
if m.buffer.len() = 0
|
||||
return false
|
||||
end if
|
||||
|
||||
operation = m.ReadHeaderLine()
|
||||
|
||||
if operation = invalid or operation = ""
|
||||
m.log.error("empty request")
|
||||
m.ready_for_response = true
|
||||
return false
|
||||
end if
|
||||
|
||||
parts = operation.tokenize(" ")
|
||||
if parts.count() = 3
|
||||
m.method = Ucase(parts[0])
|
||||
m.uri = parts[1]
|
||||
m.protocol = Ucase(parts[2])
|
||||
m.log.info(`${m.method} '${m.uri}'`)
|
||||
else
|
||||
m.log.error("invalid request: " + operation)
|
||||
m.ready_for_response = true
|
||||
end if
|
||||
|
||||
return not m.ready_for_response
|
||||
end function
|
||||
|
||||
function ParseHeaders() as boolean
|
||||
line = m.ReadHeaderLine()
|
||||
while line <> invalid and line <> ""
|
||||
splitIndex = line.InStr(": ")
|
||||
if splitIndex > 0
|
||||
key = line.Left(splitIndex)
|
||||
value = line.Mid(splitIndex + 2)
|
||||
m.headers[key] = value
|
||||
end if
|
||||
line = m.ReadHeaderLine()
|
||||
end while
|
||||
|
||||
' Unfinished line, we wait for the rest
|
||||
if line = invalid
|
||||
return false
|
||||
end if
|
||||
|
||||
' Empty line, we're done with headers
|
||||
if line = ""
|
||||
return true
|
||||
end if
|
||||
|
||||
return not m.ready_for_response
|
||||
end function
|
||||
|
||||
function ParseBody() as boolean
|
||||
data = m.ReadBufferToEnd()
|
||||
if IsString(m.body)
|
||||
m.body = m.body + data
|
||||
else
|
||||
m.body = data
|
||||
end if
|
||||
|
||||
if m.headers["Content-Length"] = invalid
|
||||
m.ready_for_response = true
|
||||
if m.body.len() > 0
|
||||
m.log.error("invalid request: request body found, but no Content-Length header")
|
||||
return false
|
||||
else
|
||||
return true
|
||||
end if
|
||||
else
|
||||
contentLength = m.headers["Content-Length"].toInt()
|
||||
if not IsString(m.body)
|
||||
return false
|
||||
end if
|
||||
|
||||
if m.body.len() > contentLength
|
||||
m.log.error("invalid request: request body is larger than Content-Length")
|
||||
m.ready_for_response = true
|
||||
return false
|
||||
end if
|
||||
|
||||
m.ready_for_response = m.body.len() = contentLength
|
||||
|
||||
if not m.ready_for_response and m.maybe_unicode = true
|
||||
' If we have a body smaller than Content-Length, there are two possibliities:
|
||||
' 1. The body is not yet complete
|
||||
' 2. The body is complete, but the body has Unicode characters, causing the string length
|
||||
' to be smaller than the byte length.
|
||||
'
|
||||
' When that happens, unfortunately, we have to convert the string to a byte array just
|
||||
' to get the byte length.
|
||||
'
|
||||
' The alternative is to receive data as bytes in the first place (as we should) but this makes
|
||||
' 1. parsing method, url, and headers slightly worse
|
||||
' 2. requires us to convert most things to strings anyway
|
||||
' 3. there are bugs https://community.roku.com/t5/Roku-Developer-Program/Help-with-roStreamSocket-data/td-p/249286
|
||||
'
|
||||
' Currently there's no indication that this has terrible performance (since it's rare that we upload unicode
|
||||
' text, at least for Playlet) and payloads are usually so small that this encoding thing will either not happen,
|
||||
' or will happen only once. The small payload size also means that the performance impact is minimal.
|
||||
'
|
||||
' Finally, we use the flag `maybe_unicode` so we're less wasteful doing this encoding.
|
||||
if m.encoder = invalid
|
||||
m.encoder = CreateObject("roByteArray")
|
||||
end if
|
||||
m.encoder.FromAsciiString(m.body)
|
||||
if m.encoder.Count() = contentLength
|
||||
m.ready_for_response = true
|
||||
end if
|
||||
end if
|
||||
|
||||
return m.ready_for_response
|
||||
end if
|
||||
end function
|
||||
|
||||
function ProcessHeaders(connection as HttpConnection)
|
||||
m.ParseRange()
|
||||
m.ParseConnection(connection)
|
||||
end function
|
||||
|
||||
function ProcessOperation(utils as Http.Utils)
|
||||
m.route = m.uri
|
||||
split = m.route.Instr("?")
|
||||
if split <> -1
|
||||
m.route = m.route.Left(split)
|
||||
m.query = utils.ParseUrlQueryComponents(m.uri)
|
||||
else
|
||||
m.query = {}
|
||||
end if
|
||||
end function
|
||||
|
||||
' TODO:P2 this function does not take into account multiple ranges.
|
||||
function ParseRange()
|
||||
range = m.headers.range
|
||||
if range <> invalid
|
||||
endpoints = lcase(range).tokenize("=")
|
||||
if endpoints.count() = 2 and endpoints.GetHead() = "bytes"
|
||||
range = endpoints.GetTail().Trim()
|
||||
hyphen = range.instr("-")
|
||||
if hyphen > 0
|
||||
m.range_begin = strtoi(range.left(hyphen))
|
||||
m.range_begin_given = true
|
||||
end if
|
||||
last = range.len() - 1
|
||||
if hyphen < last
|
||||
m.range_end = strtoi(range.right(last - hyphen))
|
||||
m.range_end_given = true
|
||||
end if
|
||||
end if
|
||||
m.log.info("range request begin" + Stri(m.range_begin) + " end" + Stri(m.range_end))
|
||||
end if
|
||||
end function
|
||||
|
||||
function ParseConnection(connection as HttpConnection)
|
||||
connectionStr = m.headers.connection
|
||||
if connectionStr <> invalid
|
||||
connection.close = (lcase(connectionStr.trim()) = "close")
|
||||
end if
|
||||
end function
|
||||
|
||||
function ReadHeaderLine() as dynamic
|
||||
index = m.buffer.Instr(m.buffer_index, `\r\n`)
|
||||
if index = -1
|
||||
return invalid
|
||||
end if
|
||||
|
||||
length = index - m.buffer_index
|
||||
line = m.buffer.Mid(m.buffer_index, length)
|
||||
m.buffer_index += length + 2 '`\r\n`.len() = 2
|
||||
return line
|
||||
end function
|
||||
|
||||
function ReadBufferToEnd() as dynamic
|
||||
if m.buffer_index = m.buffer.len()
|
||||
return ""
|
||||
end if
|
||||
|
||||
data = m.buffer.Mid(m.buffer_index)
|
||||
m.buffer_index += data.len()
|
||||
return data
|
||||
end function
|
||||
|
||||
function Json() as dynamic
|
||||
if m.body = invalid
|
||||
return invalid
|
||||
end if
|
||||
|
||||
return ParseJson(m.body)
|
||||
end function
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Http
|
||||
|
||||
enum HttpRequestState
|
||||
INIT = 0
|
||||
READING_OPERATION = 1
|
||||
READING_HEADERS = 2
|
||||
READING_BODY = 3
|
||||
DONE = 4
|
||||
end enum
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,210 @@
|
||||
import "pkg:/source/utils/TimeUtils.bs"
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
import "HttpResponseSource.bs"
|
||||
|
||||
namespace Http
|
||||
function GetHttpResponseId() as integer
|
||||
m.http_response_id = ValidInt(m.http_response_id) + 1
|
||||
return m.http_response_id
|
||||
end function
|
||||
|
||||
class HttpResponse
|
||||
private log as log.Logger
|
||||
|
||||
private source = Http.HttpResponseSource.NONE
|
||||
|
||||
' members
|
||||
private body_buffer = invalid
|
||||
private header_buffer = invalid
|
||||
private path = invalid
|
||||
private request = invalid
|
||||
private id = 0
|
||||
' copy-initializable members
|
||||
private start = 0
|
||||
private body_buffer_length = 0
|
||||
private sent = 0
|
||||
private header_sent = 0
|
||||
private header_only = false
|
||||
private buf_start = 0
|
||||
private http_code = 0
|
||||
|
||||
private server
|
||||
private settings
|
||||
|
||||
function new(request as HttpRequest, server as HttpServer, settings as HttpSettings)
|
||||
m.log = new log.Logger("HttpResponse")
|
||||
m.id = Http.GetHttpResponseId()
|
||||
m.request = request
|
||||
m.server = server
|
||||
m.settings = settings
|
||||
m.body_buffer = CreateObject("roByteArray")
|
||||
m.headers = {}
|
||||
end function
|
||||
|
||||
function Process(connection as HttpConnection) as boolean
|
||||
routers = m.server.routers
|
||||
for each router in routers
|
||||
if router.OnRequest(m.request, m, connection)
|
||||
return true
|
||||
end if
|
||||
end for
|
||||
|
||||
return true
|
||||
end function
|
||||
|
||||
function Default(errcode as integer, reason as string)
|
||||
errname = m.server.utils.HttpTitle(errcode)
|
||||
m.http_code = errcode
|
||||
|
||||
buffer = `<html><head><title>${errcode} ${errname}</title></head><body>
|
||||
<h1>${errname}</h1>
|
||||
${reason}
|
||||
<hr>
|
||||
${m.GeneratedBy()}
|
||||
</body></html>`
|
||||
|
||||
m.SetBodyDataString(buffer)
|
||||
m.ContentType("text/html")
|
||||
|
||||
m.source = Http.HttpResponseSource.GENERATED
|
||||
end function
|
||||
|
||||
function Redirect(where as string, code = 302 as integer)
|
||||
m.headers["Location"] = where
|
||||
message = `Moved to: <a href="${where}">${where}</a>`
|
||||
m.Default(code, message)
|
||||
end function
|
||||
|
||||
function Json(data as object)
|
||||
m.http_code = 200
|
||||
|
||||
buffer = FormatJson(data)
|
||||
m.SetBodyDataString(buffer)
|
||||
m.ContentType("application/json")
|
||||
|
||||
m.source = Http.HttpResponseSource.GENERATED
|
||||
end function
|
||||
|
||||
function SetBodyDataBuffer(buffer as object)
|
||||
m.body_buffer = buffer
|
||||
m.body_buffer_length = m.body_buffer.count()
|
||||
m.ContentLength(m.body_buffer_length)
|
||||
end function
|
||||
|
||||
function SetBodyDataString(data as string)
|
||||
m.body_buffer.fromasciistring(data)
|
||||
m.body_buffer_length = m.body_buffer.count()
|
||||
m.ContentLength(m.body_buffer_length)
|
||||
end function
|
||||
|
||||
function ContentLength(length as integer)
|
||||
m.headers["Content-Length"] = Stri(length).trim()
|
||||
end function
|
||||
|
||||
function ContentType(mimeType as string)
|
||||
m.headers["Content-Type"] = mimeType
|
||||
end function
|
||||
|
||||
function Send(sock as object, bufsize as integer) as integer
|
||||
sent = -1
|
||||
if m.source = Http.HttpResponseSource.FROMFILE
|
||||
if m.start + m.sent >= m.buf_start + m.body_buffer.count()
|
||||
m.buf_start = m.start + m.sent
|
||||
m.body_buffer.ReadFile(m.path, m.buf_start, bufsize)
|
||||
m.log.info(`Read ${m.body_buffer.count()} bytes from source file @${m.buf_start}`)
|
||||
end if
|
||||
end if
|
||||
buf_pos = m.start + m.sent - m.buf_start
|
||||
buf_remaining = m.body_buffer.count() - buf_pos
|
||||
if buf_remaining = 0
|
||||
m.log.info("source buffer is empty")
|
||||
end if
|
||||
req_remaining = m.body_buffer_length - m.sent
|
||||
if buf_remaining > req_remaining
|
||||
buf_remaining = req_remaining
|
||||
end if
|
||||
sent = sock.send(m.body_buffer, buf_pos, buf_remaining)
|
||||
m.LogInfo(sent, m.buf_start + buf_pos, m.body_buffer_length)
|
||||
if sent > 0
|
||||
m.sent = m.sent + sent
|
||||
end if
|
||||
return sent
|
||||
end function
|
||||
|
||||
function SendHeader(sock as object, bufsize as integer) as integer
|
||||
if m.header = invalid
|
||||
m.GenerateHeader()
|
||||
end if
|
||||
|
||||
if m.header_sent = 0
|
||||
sent = sock.sendStr(m.header)
|
||||
else
|
||||
sent = sock.sendStr(m.header.mid(m.header_sent))
|
||||
end if
|
||||
m.LogInfo(sent, m.header_sent, m.header_length)
|
||||
if sent > 0
|
||||
m.header_sent = m.header_sent + sent
|
||||
end if
|
||||
return sent
|
||||
end function
|
||||
|
||||
function GenerateHeader()
|
||||
code = m.http_code
|
||||
title = m.server.utils.HttpTitle(code)
|
||||
|
||||
m.headers["Date"] = m.Now()
|
||||
m.headers["Server"] = m.settings.serverName
|
||||
|
||||
if not m.headers.DoesExist("Connection")
|
||||
m.KeepAlive(false)
|
||||
end if
|
||||
|
||||
m.header = `HTTP/1.1 ${code} ${title}\r\n`
|
||||
for each header in m.headers
|
||||
m.header += `${header}: ${m.headers[header]}\r\n`
|
||||
end for
|
||||
|
||||
m.header += `\r\n`
|
||||
m.header_length = m.header.len()
|
||||
end function
|
||||
|
||||
function Done() as boolean
|
||||
return m.sent = m.body_buffer_length
|
||||
end function
|
||||
|
||||
function DoneHeader() as boolean
|
||||
return m.header_sent = m.header_length
|
||||
end function
|
||||
|
||||
function LogInfo(recent as integer, from as integer, total as integer)
|
||||
m.log.info(`Sent ${recent} [${m.MakeRange(from, recent, total)}]`)
|
||||
end function
|
||||
|
||||
function KeepAlive(keepAlive as boolean)
|
||||
if keepAlive
|
||||
m.headers["Connection"] = "keep-alive"
|
||||
timeout = Int(m.settings.TimeoutInMs / 1000)
|
||||
m.headers["Keep-Alive"] = `timeout=${timeout}`
|
||||
else
|
||||
m.headers["Connection"] = "close"
|
||||
m.headers.Delete("Keep-Alive")
|
||||
end if
|
||||
end function
|
||||
|
||||
function Now() as string
|
||||
if m._now = invalid
|
||||
m._now = TimeUtils.RFC1123_Date(TimeUtils.Now())
|
||||
end if
|
||||
return m._now
|
||||
end function
|
||||
|
||||
function GeneratedBy() as string
|
||||
return `generated by ${m.settings.PackageName} on ${m.Now()}`
|
||||
end function
|
||||
|
||||
function MakeRange(start as integer, length as integer, total as integer) as string
|
||||
return `${start}-${start + length - 1}/${total}`
|
||||
end function
|
||||
|
||||
end class
|
||||
end namespace
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Http
|
||||
|
||||
enum HttpResponseSource
|
||||
NONE = 0
|
||||
GENERATED = 1
|
||||
FROMFILE = 2
|
||||
end enum
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,65 @@
|
||||
namespace Http
|
||||
|
||||
class HttpRouter
|
||||
|
||||
private routes
|
||||
|
||||
function new()
|
||||
m.routes = []
|
||||
end function
|
||||
|
||||
function Get(path as string, handler as function)
|
||||
m.routes.push({ method: "GET", path: path, handler: handler })
|
||||
end function
|
||||
|
||||
function Head(path as string, handler as function)
|
||||
m.routes.push({ method: "HEAD", path: path, handler: handler })
|
||||
end function
|
||||
|
||||
function Post(path as string, handler as function)
|
||||
m.routes.push({ method: "POST", path: path, handler: handler })
|
||||
end function
|
||||
|
||||
function Put(path as string, handler as function)
|
||||
m.routes.push({ method: "PUT", path: path, handler: handler })
|
||||
end function
|
||||
|
||||
function Delete(path as string, handler as function)
|
||||
m.routes.push({ method: "DELETE", path: path, handler: handler })
|
||||
end function
|
||||
|
||||
function All(path as string, handler as function)
|
||||
m.routes.push({ method: "*", path: path, handler: handler })
|
||||
end function
|
||||
|
||||
private function OnRequest(request as object, response as HttpResponse, connection as HttpConnection) as boolean
|
||||
for each route in m.routes
|
||||
if m.RouteMatchesRequest(route, request)
|
||||
if route.handler({
|
||||
router: m,
|
||||
request: request,
|
||||
response: response,
|
||||
connection: connection,
|
||||
server: response.server
|
||||
}) = true
|
||||
return true
|
||||
end if
|
||||
end if
|
||||
end for
|
||||
return false
|
||||
end function
|
||||
|
||||
private function RouteMatchesRequest(route as object, request as HttpRequest) as boolean
|
||||
if route.method <> "*" and route.method <> request.method
|
||||
return false
|
||||
end if
|
||||
|
||||
if route.path <> "*" and route.path <> request.route
|
||||
return false
|
||||
end if
|
||||
|
||||
return true
|
||||
end function
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,185 @@
|
||||
import "HttpUtils.bs"
|
||||
import "HttpSettings.bs"
|
||||
import "HttpRouter.bs"
|
||||
import "HttpConnectionState.bs"
|
||||
import "HttpConnection.bs"
|
||||
|
||||
namespace Http
|
||||
|
||||
class HttpServer
|
||||
private log as log.Logger
|
||||
|
||||
' members
|
||||
private connections = invalid
|
||||
private sockin = invalid
|
||||
private uptime = invalid
|
||||
|
||||
' initializable (copied) members
|
||||
private num_requests = 0
|
||||
private total_in = 0
|
||||
private total_out = 0
|
||||
|
||||
private routers
|
||||
|
||||
public success as boolean
|
||||
public settings as Http.HttpSettings
|
||||
public task as object
|
||||
|
||||
function new(settings as HttpSettings, task as object)
|
||||
m.log = new log.Logger("HttpServer")
|
||||
m.settings = settings
|
||||
m.task = task
|
||||
m.routers = []
|
||||
m.utils = new Utils()
|
||||
m.success = m.Init()
|
||||
end function
|
||||
|
||||
function Init() as boolean
|
||||
m.uptime = CreateObject("roTimespan")
|
||||
m.connections = CreateObject("roAssociativeArray")
|
||||
|
||||
success = true
|
||||
|
||||
' create incoming socket
|
||||
sockin = CreateObject("roStreamSocket")
|
||||
if sockin = invalid
|
||||
success = false
|
||||
m.log.error("socket()")
|
||||
end if
|
||||
|
||||
' reuse address
|
||||
if not sockin.setReuseAddr(true)
|
||||
success = false
|
||||
m.log.error("setsockopt(SO_REUSEADDR)", sockin.status())
|
||||
end if
|
||||
|
||||
' bind socket
|
||||
addrin = CreateObject("roSocketAddress")
|
||||
addrin.setPort(m.settings.Port)
|
||||
if not sockin.setAddress(addrin)
|
||||
success = false
|
||||
m.log.error("bind(port" + Stri(m.settings.Port) + ")", sockin.status())
|
||||
end if
|
||||
' listen on socket
|
||||
if not sockin.listen(m.settings.MaxConnections)
|
||||
success = false
|
||||
m.log.error("listen()", sockin.status())
|
||||
end if
|
||||
' monitor socket
|
||||
sockin.setMessagePort(m.settings.MessagePort)
|
||||
sockin.notifyReadable(true)
|
||||
|
||||
m.sockin = sockin
|
||||
|
||||
m.log.info("listening on " + addrin.getAddress())
|
||||
return success
|
||||
end function
|
||||
|
||||
function UseRouter(router as HttpRouter)
|
||||
m.routers.Push(router)
|
||||
end function
|
||||
|
||||
function PreWait()
|
||||
connections = m.connections
|
||||
for each id in connections
|
||||
conn = connections[id]
|
||||
conn.CheckTimeout(m.settings.TimeoutInMs)
|
||||
cs = conn.state
|
||||
if cs = Http.HttpConnectionState.DONE
|
||||
conn.socket.notifyReadable(false)
|
||||
conn.socket.notifyWritable(false)
|
||||
else if cs = Http.HttpConnectionState.RECV_REQUEST
|
||||
conn.socket.notifyReadable(true)
|
||||
conn.socket.notifyWritable(false)
|
||||
else if cs = Http.HttpConnectionState.SEND_HEADER or cs = Http.HttpConnectionState.SEND_RESPONSE
|
||||
conn.socket.notifyWritable(true)
|
||||
conn.socket.notifyReadable(false)
|
||||
else
|
||||
m.log.error("invalid state")
|
||||
end if
|
||||
end for
|
||||
end function
|
||||
|
||||
function PostWait()
|
||||
connections = m.connections
|
||||
if m.sockin.isReadable()
|
||||
conn = m.AcceptHttpConnection()
|
||||
if conn <> invalid
|
||||
connections[conn.id] = conn
|
||||
end if
|
||||
end if
|
||||
for each id in connections
|
||||
conn = connections[id]
|
||||
cs = conn.state
|
||||
if cs = Http.HttpConnectionState.RECV_REQUEST
|
||||
if conn.socket.isReadable()
|
||||
conn.PollRequest(m)
|
||||
end if
|
||||
else if cs = Http.HttpConnectionState.SEND_HEADER
|
||||
if conn.socket.isWritable()
|
||||
conn.PollHeader(m)
|
||||
end if
|
||||
else if cs = Http.HttpConnectionState.SEND_RESPONSE
|
||||
if conn.socket.isWritable()
|
||||
conn.PollResponse(m)
|
||||
end if
|
||||
else if cs = Http.HttpConnectionState.DONE
|
||||
' handle with other connections that might transition to done
|
||||
else
|
||||
m.log.error("invalid state")
|
||||
end if
|
||||
cs = conn.state
|
||||
if cs = Http.HttpConnectionState.DONE
|
||||
if conn.close
|
||||
conn.socket.close()
|
||||
connections.delete(id)
|
||||
else if conn.ws_upgrade and m.websocket <> invalid
|
||||
m.log.info("upgrading connection to web socket")
|
||||
m.websocket.AddConnection(conn.socket)
|
||||
connections.delete(id)
|
||||
else
|
||||
conn.Recycle()
|
||||
conn.PollRequest(m)
|
||||
end if
|
||||
end if
|
||||
end for
|
||||
end function
|
||||
|
||||
function AcceptHttpConnection() as HttpConnection
|
||||
sockin = m.sockin
|
||||
socket = sockin.accept()
|
||||
if not sockin.eOK()
|
||||
m.log.error("accept()", sockin.status())
|
||||
end if
|
||||
if socket = invalid
|
||||
return invalid
|
||||
end if
|
||||
conn = new HttpConnection(m, m.settings)
|
||||
conn.Accepted(m, socket)
|
||||
return conn
|
||||
end function
|
||||
|
||||
function Close()
|
||||
' close all the sockets
|
||||
m.sockin.close()
|
||||
connections = m.connections
|
||||
for each id in connections
|
||||
conn = connections[id]
|
||||
conn.socket.close()
|
||||
end for
|
||||
if m.websocket <> invalid
|
||||
m.websocket.Close()
|
||||
end if
|
||||
' final stats
|
||||
m.log.info(`\n` + m.stats())
|
||||
end function
|
||||
|
||||
function Stats() as string
|
||||
stats = " Uptime" + Stri(m.uptime.totalSeconds()) + " secs" + `\n`
|
||||
stats = stats + " Requests" + Stri(m.num_requests) + `\n`
|
||||
stats = stats + " Bytes" + Stri(m.total_in) + " in," + Stri(m.total_out) + " out"
|
||||
return stats
|
||||
end function
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace Http
|
||||
|
||||
class HttpSettings
|
||||
|
||||
public MaxConnections = 10
|
||||
public MaxRequestLength = 2097152
|
||||
public PackageName as string = "Roku app"
|
||||
public Port as integer = 8888
|
||||
public ServerName = "Roku Server"
|
||||
public TimeoutInMs = 60 * 1000
|
||||
|
||||
public MessagePort = invalid
|
||||
|
||||
function new(messagePort as object)
|
||||
m.MessagePort = messagePort
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,73 @@
|
||||
import "pkg:/source/utils/Types.bs"
|
||||
|
||||
namespace Http
|
||||
|
||||
class Utils
|
||||
|
||||
function ParseUrlQueryComponents(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 = ParseJson(ReadAsciiFile("libpkg:/config/mime-types.json5"))
|
||||
m.MimeTypes = map
|
||||
end if
|
||||
ext = m.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 = ParseJson(ReadAsciiFile("libpkg:/config/http-codes.json5"))
|
||||
m.HttpTitles = hcm
|
||||
end if
|
||||
return ValidString(hcm[`${code}`])
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
end namespace
|
||||
Reference in new issue
Block a user