diff --git a/bsconfig.json b/bsconfig.json index 32dd123d..7b8a2180 100644 --- a/bsconfig.json +++ b/bsconfig.json @@ -6,7 +6,8 @@ "images/**/*.*", "meta/**/*.*", "components/**/*.*", - "!**/*.spec.bs" + "!**/*.spec.bs", + "www/**/*.*" ], "autoImportComponentScript": true, "createPackage": false, diff --git a/src/source/webserver/Demo.txt b/src/source/webserver/Demo.txt new file mode 100644 index 00000000..5a0b781e --- /dev/null +++ b/src/source/webserver/Demo.txt @@ -0,0 +1,52 @@ +' Ported from https://sourceforge.net/p/rokusdkexamples/code/HEAD/tree/trunk/rokusdkexamples-code/web_server/ + +' function Main(args as dynamic) +' m.msgPort = CreateObject("roMessagePort") + +' settings = new RokuYoutube.Http.HttpSettings(m.msgPort) + +' ' Root at www to get http://192.168.1.107:8888/index.html +' settings.WwwRoot = "pkg:/www" + +' print `Using settings: ${settings}` + +' server = new RokuYoutube.Http.HttpServer(settings) + +' m.running = true +' timeout = validint(settings.Timeout) +' timer = CreateObject("roTimespan") +' update = true + +' while (m.running) +' if update +' timer.mark() +' PrintServerStatus(server) +' update = false +' end if +' server.PreWait() +' msg = wait(timeout, settings.MessagePort) +' tm = type(msg) +' if tm="roSocketEvent" or msg=invalid +' server.PostWait() +' end if +' if timer.totalSeconds()>=5 then update = true +' end while + +' server.Close() +' end function + +' function PrintServerStatus(server as HttpServer) +' print("-------") +' print(server.stats()) +' connections = server.connections +' count=0 +' for each connID in connections +' conn = connections[connID] +' print (` - Client: ${conn.client}; Total sent: ${conn.total_sent}; ID: ${conn.id}`) +' count++ +' end for +' if count = 0 +' print(" No active connections") +' end if +' print("-------") +' end function \ No newline at end of file diff --git a/src/source/webserver/HttpConnection.bs b/src/source/webserver/HttpConnection.bs new file mode 100644 index 00000000..2033ca14 --- /dev/null +++ b/src/source/webserver/HttpConnection.bs @@ -0,0 +1,165 @@ +namespace RokuYoutube.Http + class HttpConnection + const BUFSIZE = 65536 + + private total_received = 0 + private total_sent = 0 + private id = "" + private close = true + private state = HttpConnectionState.INIT + + private settings = invalid as HttpSettings + + function new(settings as HttpSettings) + 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-reply + m.last_active = CreateObject("roTimespan") + m.request = new HttpRequest() + m.header = invalid + m.reply = invalid + m.header_only = false + m.http_code = 0 + m.close = true + m.SetState(HttpConnectionState.INIT) + end function + + function Recycle() + info(m, "recycle") + m.Restart() + m.SetState(HttpConnectionState.RECV_REQUEST) ' ready for another + end function + + function Accepted(server as HttpServer, socket as object) + m.socket = socket + m.id = Stri(socket.getID()).trim() + m.SetState(HttpConnectionState.RECV_REQUEST) + m.client = m.socket.getReceivedFromAddress().getAddress() + + info(m, "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 <> HttpConnectionState.RECV_REQUEST then errx(m, "illegal request state @" + m.client) + + rcvStr = m.socket.receiveStr(m.BUFSIZE) + received = rcvStr.len() + + 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) + + if m.request.IsComplete() + server.num_requests = validint(server.num_requests) + 1 + if m.request.Process(m) + m.reply = new HttpReply(m.request, m.settings) + m.reply.Process() + m.SetState(HttpConnectionState.SEND_HEADER) + else + m.setState(HttpConnectionState.DONE) + m.close = true + err(m, "couldn't process request or reply, closing @" + m.client) + end if + else if m.request.buf.len() > m.settings.MaxRequestLength ' die if it's too long + m.reply = new HttpReply(m.request, m.settings) + m.reply.Default(413, "Your request was dropped because it was too long.") + m.SetState(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 = HttpConnectionState.SEND_HEADER then m.PollHeader(server) + + end function + + function PollHeader(server as HttpServer) as boolean + if m.state <> HttpConnectionState.SEND_HEADER errx(m, "illegal header state @" + m.client) + + sent = m.reply.SendHeader(m.socket, m.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.reply.DoneHeader() + if m.reply.header_only + m.SetState(HttpConnectionState.DONE) + else + m.SetState(HttpConnectionState.SEND_REPLY) + m.PollReply(server) + end if + end if + end function + + function PollReply(server as HttpServer) + if m.state <> HttpConnectionState.SEND_REPLY or m.reply.header_only then errx(m, "illegal reply state @" + m.client) + + sent = m.reply.Send(m.socket, m.BUFSIZE) + if m.CheckResult(sent, "send reply") + m.total_sent = m.total_sent + sent + server.total_out = server.total_out + sent + end if + + if m.reply.Done() then m.SetState(HttpConnectionState.DONE) + end function + + function CheckTimeout(timeout as integer) + if m.last_active.totalSeconds() > timeout + m.close = true + m.SetState(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() + info(m, op + " peer closed @" + m.client) + else + err(m, op + " transfer error @" + m.client, m.socket.status()) + end if + m.close = true + m.SetState(HttpConnectionState.DONE) + end if + return gotSome + end function + + function SetState(newState as HttpConnectionState) + if m.state <> newState + 'info(m,"state change" + Stri(m.state) + " ->" + Stri(newState)) + m.state = newState + end if + end function + + function Log() + if m.http_code <> 0 and isnonemptystr(m.method) + print 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 \ No newline at end of file diff --git a/src/source/webserver/HttpConnectionState.bs b/src/source/webserver/HttpConnectionState.bs new file mode 100644 index 00000000..2600deca --- /dev/null +++ b/src/source/webserver/HttpConnectionState.bs @@ -0,0 +1,7 @@ +enum HttpConnectionState + INIT = 0 ' initial state; shouldn't last long + RECV_REQUEST = 1 ' receiving request + SEND_HEADER = 2 ' sending generated header + SEND_REPLY = 3 ' sending reply + DONE = 4 ' reply sent, close or reuse as indicated +end enum \ No newline at end of file diff --git a/src/source/webserver/HttpReply.bs b/src/source/webserver/HttpReply.bs new file mode 100644 index 00000000..32fc29d9 --- /dev/null +++ b/src/source/webserver/HttpReply.bs @@ -0,0 +1,314 @@ +namespace RokuYoutube.Http + function GetHttpReplyId() + m.http_reply_id = validint(m.http_reply_id) + 1 + return m.http_reply_id + end function + + class HttpReply + private source = HttpReplySource.NONE + + ' members + private buf = invalid + private header = invalid + private path = invalid + private request = invalid + private id = 0 + ' copy-initializable members + private start = 0 + private length = 0 + private sent = 0 + private header_sent = 0 + private header_only = false + private buf_start = 0 + private http_code = 0 + private mimetype = "text/html" ' for errors + + private settings = invalid as HttpSettings + + function new(request as HttpRequest, settings as HttpSettings) + m.id = GetHttpReplyId() + m.settings = settings + m.Init(request) + end function + + function Init(request as HttpRequest) + m.buf = CreateObject("roByteArray") + m.request = request + end function + + function Process() + m.now = rfc1123_date(Now()) + method = m.request.method + if method = "" + m.Default(400, "You sent a request that the server couldn't understand.") + else if method = "GET" + m.ProcessGetOrHead() + else if method = "HEAD" + m.ProcessGetOrHead() + m.header_only = true + else if method = "OPTIONS" or method = "POST" or method = "PUT" or method = "DELETE" or method = "TRACE" or method = "CONNECT" + m.Default(501, "The method you specified (" + method + ") is not implemented.") + else + m.Default(400, method + " is not a valid HTTP/1.1 method.") + end if + + end function + + function ProcessGetOrHead() as Boolean + ' work out path of file being requested + req = m.request + uri = req.uri + decoded_uri = UrlUnescape(uri) + path = CreateObject("roPath", m.settings.WwwRoot + decoded_uri) + fs = CreateObject("roFilesystem") + + ' make sure it's safe + if not path.isValid() + m.Default(400, "You requested an invalid URI: " + uri) + return false + else if not fs.exists(path) + m.Default(404, "The URI you requested (" + uri + ") was not found.") + return false + end if + + stat = fs.stat(path) + if stat = invalid + m.Default(500, "fstat() failed.") + return false + end if + m.path = path + + if stat.type = "directory" + m.mimetype = MimeType(m.settings.IndexName) + m.GenerateDirectoryListing() + return true + else if stat.type = "file" + m.mimetype = MimeType(decoded_uri) + m.fileLength = stat.size + info(m, "uri=" + uri + ", target=" + path + ", content-type=" + m.mimetype + ", content-length=" + Stri(m.fileLength).trim()) + else + m.Default(403, "Not a regular file.") + return false + end if + + m.source = HttpReplySource.FROMFILE + m.lastmod = Now() ' stat.mtime (mod date not yet available) + fileFinish = m.fileLength - 1 + + ' check for If-Modified-Since, may not have to send */ + if_mod_since = req.fields["If-Modified-Since"] + if if_mod_since <> invalid + reqDate = date_rfc1123(if_mod_since) + if reqDate <> invalid and reqDate.toSeconds() >= m.lastMod.toSeconds() + m.header_only = true + lastMod = rfc1123_date(m.lastMod) + info(m, "not modified since " + lastMod) + m.Default(304, "not modified since " + lastMod) + return true + end if + end if + + if req.range_begin_given or req.range_end_given + if req.range_begin_given and req.range_end_given + ' 100-200 + start = req.range_begin + finish = req.range_end + ' clamp finish to fileFinish + if finish > fileFinish then finish = fileFinish + else if req.range_begin_given and not req.range_end_given + ' 100- :: yields 100 to end + start = req.range_begin + finish = fileFinish + else if not req.range_begin_given and req.range_end_given + ' -200 :: yields last 200 + finish = fileFinish + start = finish - req.range_end + 1 + ' check for wrapping + if start > finish start = 0 + else + errx(1, "internal error - range start/finish logic inconsistency") + end if + + m.start = start + m.length = finish - start + 1 + m.http_code = 206 + + info(m, "sending range " + MakeRange(start, m.length, m.fileLength)) + else ' no range stuff + m.length = m.fileLength + m.http_code = 200 + end if + + m.GenerateHeader() + return true + end function + + function Default(errcode as integer, reason as string) + if m.now = invalid + m.now = rfc1123_date(Now()) + end if + + errname = HttpTitle(errcode) + m.http_code = errcode + + buf = "" + Stri(errcode).trim() + " " + errname + "" + UnixNL() + buf = buf + "

" + errname + "

" + UnixNL() + buf = buf + reason + UnixNL() + buf = buf + "
" + UnixNL() + buf = buf + m.GeneratedBy() + UnixNL() + buf = buf + "" + UnixNL() + + m.buf.fromasciistring(buf) + m.length = m.buf.count() + + m.GenerateHeader(true) + m.source = HttpReplySource.GENERATED + end function + + function Redirect(where as string) + m.location = where + message = "Moved to: " + where + "" + m.Default(301, message) + end function + + function Send(sock as object, bufsize as integer) as integer + sent = -1 + if m.source = HttpReplySource.FROMFILE + if m.start + m.sent >= m.buf_start + m.buf.count() + m.buf_start = m.start + m.sent + m.buf.ReadFile(m.path, m.buf_start, bufsize) + info(m, "Read" + Stri(m.buf.count()) + " bytes from source file @" + itostr(m.buf_start)) + end if + end if + buf_pos = m.start + m.sent - m.buf_start + buf_remaining = m.buf.count() - buf_pos + if buf_remaining = 0 then info(m, "source buf is empty") + req_remaining = m.length - m.sent + if buf_remaining > req_remaining then buf_remaining = req_remaining + sent = sock.send(m.buf, buf_pos, buf_remaining) + m.Log(sent, m.buf_start + buf_pos, m.length) + if sent > 0 then m.sent = m.sent + sent + return sent + end function + + function SendHeader(sock as object, bufsize as integer) as integer + if m.header_sent = 0 + sent = sock.sendStr(m.header) + else + sent = sock.sendStr(m.header.mid(m.header_sent)) + end if + m.log(sent, m.header_sent, m.header_length) + if sent > 0 then m.header_sent = m.header_sent + sent + return sent + end function + + function GenerateDirectoryListing() + fs = CreateObject("roFilesystem") + dirList = fs.GetDirectoryListing(m.path) + if dirList = invalid + m.default(500, "Couldn't list directory") + return false + end if + + ' for tabbed alignment of file sizes + maxlen = 0 + for each item in dirList + il = item.len() + if maxlen < il maxlen = il + end for + + listing = "" + UnixNL() + listing = listing + "" + UnixNL() + listing = listing + "" + m.settings.ServerName + "" + UnixNL() + listing = listing + "" + UnixNL() + listing = listing + "" + UnixNL() + listing = listing + "

" + URLUnescape(m.request.uri) + "

" + UnixNL() + listing = listing + "
" + UnixNL()
+
+      dir = m.path.getString()
+      if dir.len() > 0 and dir.right(1) <> "/" then dir = dir + "/"
+      uriDir = m.request.uri
+      if uriDir.len() > 0 and uriDir.right(1) <> "/" then uriDir = uriDir + "/"
+
+      for each item in dirList
+        if item.left(1) <> "."
+          indicator = invalid
+          stat = fs.stat(dir + item)
+          if stat <> invalid
+            if stat.doesexist("type") and stat.type = "directory"
+              indicator = "/"
+            else if stat.doesexist("size")
+              indicator = string(maxlen - item.len(), " ") + Stri(stat.size)
+            end if
+          end if
+          if indicator <> invalid
+            uri = uriDir + item
+            safe_url = uri ' UrlEncode(uri) ' too much encoding
+            listing = listing + "" + item
+            listing = listing + indicator
+            listing = listing + "" + UnixNL()
+          else
+            warn(m, "insufficient stat info to include '" + dir + item + "'")
+          end if
+        end if
+      end for
+
+      listing = listing + "
" + UnixNL() + listing = listing + "
" + UnixNL() + + listing = listing + m.GeneratedBy() + UnixNL() + listing = listing + "" + UnixNL() + listing = listing + "" + UnixNL() + + m.buf.FromAsciiString(listing) + m.length = m.buf.count() + + m.http_code = 200 + m.GenerateHeader() + m.source = HttpReplySource.GENERATED + return true + end function + + function GenerateHeader(close = false as boolean) + code = m.http_code + title = HttpTitle(code) + m.header = "HTTP/1.1" + Stri(code) + " " + title + WinNL() + m.header = m.header + "Date: " + m.now + WinNL() + m.header = m.header + "Server: " + m.settings.PackageName + WinNL() + if isstr(m.location) then m.header = m.header + "Location: " + m.location + WinNL() + m.header = m.header + m.KeepAlive(close) + WinNL() + m.header = m.header + "Content-Length:" + Stri(m.length) + WinNL() + if code = 206 then m.header = m.header + "Content-Range: bytes" + m.MakeRange(m.start, m.length, m.filelength) + WinNL() + m.header = m.header + "Content-Type: " + m.mimetype + WinNL() + m.header = m.header + "Accept-Ranges: bytes" + WinNL() + m.header = m.header + WinNL() + m.header_length = m.header.len() + end function + + function Done() + return m.sent = m.length + end function + + function DoneHeader() + return m.header_sent = m.header_length + end function + + function Log(recent as integer, from as integer, total as integer) + info(m, "Sent" + Stri(recent) + " [" + m.MakeRange(from, recent, total) + "]") + end function + + function KeepAlive(close as boolean) as string + if close then base = "Connection: close" else base = "Keep-Alive: timeout=" + Stri(m.settings.Idletime).trim() + return base + end function + + function GeneratedBy() + return "generated by " + m.settings.PackageName + " on " + m.now + end function + + function MakeRange(start as integer, length as integer, total as integer) + return itostr(start) + "-" + itostr(start + length - 1) + "/" + itostr(total) + end function + + end class +end namespace diff --git a/src/source/webserver/HttpReplySource.bs b/src/source/webserver/HttpReplySource.bs new file mode 100644 index 00000000..f96b6a0c --- /dev/null +++ b/src/source/webserver/HttpReplySource.bs @@ -0,0 +1,5 @@ +enum HttpReplySource + NONE = 0 + GENERATED = 1 + FROMFILE = 2 +end enum \ No newline at end of file diff --git a/src/source/webserver/HttpRequest.bs b/src/source/webserver/HttpRequest.bs new file mode 100644 index 00000000..58f1089b --- /dev/null +++ b/src/source/webserver/HttpRequest.bs @@ -0,0 +1,100 @@ +namespace RokuYoutube.Http + function GetHttpRequestId() + m.http_request_id = validint(m.http_request_id) + 1 + return m.http_request_id + end function + + class HttpRequest + const Unix2NewLine = UnixNL() + UnixNL() + const Windows2NewLine = WinNL() + WinNL() + + ' members + private method = invalid + private uri = invalid + private protocol = invalid + private buf = invalid + private fields = invalid + private id = 0 + ' copied members + private range_begin = 0 + private range_end = 0 + private range_begin_given = false + private range_end_given = false + private ok = true + + function new() + m.id = GetHttpRequestId() + m.fields = CreateObject("roAssociativeArray") + end function + + function Add(incoming as string) + if isstr(m.buf) then m.buf = m.buf + incoming else m.buf = incoming + end function + + function IsComplete() as boolean + buf = m.buf + complete = isstr(buf) and (right(buf, 2) = m.Unix2NewLine) or (right(buf, 4) = m.Windows2NewLine) + 'if complete then info(m,"header:"+UnixNL()+buf) + return complete + + end function + + function Parse(connection as HttpConnection) as boolean + lines = m.buf.tokenize(WinNL()) + operation = lines.RemoveHead() + if operation <> invalid + parts = operation.tokenize(" ") + if parts.count() = 3 + m.method = Ucase(parts.RemoveHead()) + m.uri = parts.RemoveHead() + m.protocol = Ucase(parts.RemoveHead()) + info(m, m.method + " '" + m.uri + "'") + for each line in lines + av = line.tokenize(": ") + if av.count() = 2 then m.fields[av.GetHead()] = av.GetTail() + end for + ' interpret some fields if present + m.ParseRange() + m.ParseConnection(connection) + else + err(m, "invalid request: " + operation) + m.ok = false + end if + else + err(m, "empty request") + m.ok = false + end if + return m.ok + end function + + function ParseRange() + range = m.fields.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 + info(m, "range request begin" + Stri(m.range_begin) + " end" + Stri(m.range_end)) + end if + end function + + function ParseConnection(connection as HttpConnection) as boolean + connectionStr = m.fields.connection + if connectionStr <> invalid then connection.close = (lcase(connectionStr.trim()) = "close") + end function + + function Process(connection as HttpConnection) as boolean + return m.Parse(connection) + end function + end class +end namespace diff --git a/src/source/webserver/HttpServer.bs b/src/source/webserver/HttpServer.bs new file mode 100644 index 00000000..8a044afe --- /dev/null +++ b/src/source/webserver/HttpServer.bs @@ -0,0 +1,137 @@ +namespace RokuYoutube.Http + function InitGlobals() + MimeType() + HttpTitle() + end function + + class HttpServer + ' 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 settings = invalid as HttpSettings + + function new(settings as HttpSettings) + m.settings = settings + InitGlobals() + m.Init() + end function + + function Init() + m.uptime = CreateObject("roTimespan") + m.connections = CreateObject("roAssociativeArray") + + ' create incoming socket + sockin = CreateObject("roStreamSocket") + if sockin = invalid then errx(m, "socket()") + + ' reuse address + if not sockin.setReuseAddr(true) then errx(m, "setsockopt(SO_REUSEADDR)", sockin.status()) + + ' bind socket + addrin = CreateObject("roSocketAddress") + addrin.setPort(m.settings.Port) + if not sockin.setAddress(addrin) then errx(m, "bind(port" + Stri(m.settings.Port) + ")", sockin.status()) + + ' listen on socket + if not sockin.listen(m.settings.MaxConnections) then errx(m, "listen()", sockin.status()) + + ' monitor socket + sockin.setMessagePort(m.settings.MessagePort)) + sockin.notifyReadable(true) + + m.sockin = sockin + + info(m, "listening on " + addrin.getAddress()) + end function + + function PreWait() + connections = m.connections + for each id in connections + conn = connections[id] + conn.CheckTimeout(m.settings.Timeout) + cs = conn.state + if cs = HttpConnectionState.DONE + conn.socket.notifyReadable(false) + conn.socket.notifyWritable(false) + else if cs = HttpConnectionState.RECV_REQUEST + conn.socket.notifyReadable(true) + conn.socket.notifyWritable(false) + else if cs = HttpConnectionState.SEND_HEADER or cs = HttpConnectionState.SEND_REPLY + conn.socket.notifyWritable(true) + conn.socket.notifyReadable(false) + else + errx(m, "invalid state") + end if + end for + end function + + function PostWait() + connections = m.connections + if m.sockin.isReadable() + conn = m.AcceptHttpConnection() + if conn <> invalid then connections[conn.id] = conn + end if + for each id in connections + conn = connections[id] + cs = conn.state + if cs = HttpConnectionState.RECV_REQUEST + if conn.socket.isReadable() then conn.PollRequest(m) + else if cs = HttpConnectionState.SEND_HEADER + if conn.socket.isWritable() then conn.PollHeader(m) + else if cs = HttpConnectionState.SEND_REPLY + if conn.socket.isWritable() then conn.PollReply(m) + else if cs = HttpConnectionState.DONE + ' handle with other connections that might transition to done + else + errx(m, "invalid state") + end if + cs = conn.state + if cs = HttpConnectionState.DONE + if conn.close + conn.socket.close() + 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() err(m, "accept()", sockin.status()) + if socket = invalid then return invalid + conn = new HttpConnection(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 + ' final stats + info(m, UnixNL() + m.stats()) + end function + + function Stats() as string + stats = " Uptime" + Stri(m.uptime.totalSeconds()) + " secs" + UnixNL() + stats = stats + " Requests" + Stri(m.num_requests) + UnixNL() + stats = stats + " Bytes" + Stri(m.total_in) + " in," + Stri(m.total_out) + " out" + return stats + end function + end class +end namespace \ No newline at end of file diff --git a/src/source/webserver/HttpSettings.bs b/src/source/webserver/HttpSettings.bs new file mode 100644 index 00000000..55c24d3f --- /dev/null +++ b/src/source/webserver/HttpSettings.bs @@ -0,0 +1,20 @@ +namespace RokuYoutube.Http + class HttpSettings + + PackageName = "Youtube for Roku" + Port = 8888 + MessagePort = invalid + MaxConnections = 3 + Timeout = 60 + MaxRequestLength = 4000 + Idletime = 60 + WwwRoot = "pkg:/" + IndexName = "index.html" + ServerName = "Roku Youtube Server" + + function new(messagePort) + m.MessagePort = messagePort + end function + + end class +end namespace \ No newline at end of file diff --git a/src/source/webserver/common/General.brs b/src/source/webserver/common/General.brs new file mode 100644 index 00000000..41cc4ed8 --- /dev/null +++ b/src/source/webserver/common/General.brs @@ -0,0 +1,39 @@ +REM This file has no dependencies on other common files. +REM +REM Functions in this file: +REM GetDeviceVersion +REM GetDeviceESN +REM IsHD +REM + +'****************************************************** +'Get our device version +'****************************************************** +Function GetDeviceVersion() + if m.softwareVersion = invalid OR m.softwareVersion = "" then + m.softwareVersion = CreateObject("roDeviceInfo").GetVersion() + end if + return m.softwareVersion +End Function + + +'****************************************************** +'Get our serial number +'****************************************************** +Function GetDeviceESN() + if m.serialNumber = invalid OR m.serialNumber = "" then + m.serialNumber = CreateObject("roDeviceInfo").GetDeviceUniqueId() + end if + return m.serialNumber +End Function + + +'****************************************************** +'Determine if the UI is displayed in SD or HD mode +'****************************************************** +Function IsHD() + di = CreateObject("roDeviceInfo") + if di.GetDisplayMode() = "720p" then return true + return false +End Function + diff --git a/src/source/webserver/common/StringUtils.brs b/src/source/webserver/common/StringUtils.brs new file mode 100644 index 00000000..08cb8493 --- /dev/null +++ b/src/source/webserver/common/StringUtils.brs @@ -0,0 +1,117 @@ +REM Functions in this file: +REM isnonemptystr +REM isnullorempty +REM strtobool +REM itostr +REM strTrim +REM strTokenize +REM strReplace +REM + +'****************************************************** +'isnonemptystr +' +'Determine if the given object supports the ifString interface +'and returns a string of non zero length +'****************************************************** +Function isnonemptystr(obj) + 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) + 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 + if type(obj) <> "roString" and type(obj) <> "String" return false + o = strTrim(obj) + o = Lcase(o) + if o = "true" return true + if o = "t" return true + if o = "y" return true + if o = "1" return true + return false +End Function + +'****************************************************** +'booltostr +' +'Converts a boolean value to a cannonical string value +'****************************************************** +Function booltostr(bool As Boolean) As String + if bool = true then return "true" + 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 + + +'****************************************************** +'Replace substrings in a string. Return new string +'****************************************************** +Function strReplace(basestr As String, oldsub As String, newsub As String) As String + newstr = "" + + i = 1 + while i <= Len(basestr) + x = Instr(i, basestr, oldsub) + if x = 0 then + newstr = newstr + Mid(basestr, i) + exit while + endif + + if x > i then + newstr = newstr + Mid(basestr, i, x-i) + i = x + endif + + newstr = newstr + newsub + i = i + Len(oldsub) + end while + + return newstr +End Function diff --git a/src/source/webserver/common/Types.brs b/src/source/webserver/common/Types.brs new file mode 100644 index 00000000..ef534315 --- /dev/null +++ b/src/source/webserver/common/Types.brs @@ -0,0 +1,139 @@ +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 + + +'****************************************************** +'isbool +' +'Determine if the given object supports the ifBoolean interface +'****************************************************** +Function isbool(obj as dynamic) As Boolean + if obj = invalid return false + if GetInterface(obj, "ifBoolean") = invalid return false + 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 + if GetInterface(obj, "ifFloat") = invalid return false + 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 "" + endif +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 + if paramType = "roString" or paramType = "String" then + if type(param) = "roString" or type(param) = "String" then + return true + end if + else if type(param) = paramType then + return true + endif + + if allowInvalid = true then + if type(param) = invalid then + return true + endif + endif + + print "invalid parameter of type "; type(param); " for "; paramType; " in function "; functionName + return false +End Function + diff --git a/src/source/webserver/utils.brs b/src/source/webserver/utils.brs new file mode 100644 index 00000000..b1c5b0b2 --- /dev/null +++ b/src/source/webserver/utils.brs @@ -0,0 +1,203 @@ +function min(a as Integer, b as Integer) as Integer + if ainvalid then tag = tag + class + if isint(id) + tag = tag +"[" + itostr(id) + "]" + else if isstr(id) + tag = tag +"[" + id + "]" + end if + end if + print tag; "."; level; ": "; + if code<>0 then print "*"; Stri(code).trim(); "* "; + print message +end function + +function info(obj as Object, message as String, code=0 as Integer) + dbg(obj, "info", message, code) +end function + +function warn(obj as Object, message as String, code=0 as Integer) + dbg(obj, "warning", message, code) +end function + +function err(obj as Object, message as String, code=0 as Integer) + dbg(obj, "error", message, code) +end function + +function errx(obj as Object, message as String, code=0 as Integer) + dbg(obj, "fatal", message, code) + stop +end function + +function UnixNL() + return chr(10) +end function + +function WinNL() + return chr(13) + chr(10) +end function + +function Quote() + return chr(34) +end function + +function rfc1123_date(when as Object) + wd = when.getWeekday().left(3) + dom = Stri(when.getDayOfMonth()).trim() + mon = Ucase(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 date_rfc1123(when as String) + date = CreateObject("roDateTime") + parts = when.tokenize(", ") + if parts.count()=8 + iso8601 = parts.GetIndex(3) + "-" + monthNum(parts.GetIndex(2)) + "-" + parts.GetIndex(1) + " " + parts.GetIndex(4) + ":" + parts.GetIndex(5) + ":" + parts.GetIndex(6) + date.fromISO8601String(iso8601) + end if + return date +end function + +function monthNum(mStr as String) + mm = m.Month2Num + if mm=invalid + mm = {jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12} + m.Month2Num = mm + end if + return validint(mm[lcase(mStr.left(3))]) +end function + +function monthStr(mNum as Integer) + 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 HttpTitle(code=0 as Integer) as String + hcm = m.HttpTitles + if hcm=invalid + hcm = {n200:"OK",n206:"Partial Content"} + hcm.append({n301:"Moved Permanently",n304:"Not Modified"}) + hcm.append({n400:"Bad Request",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 Now() as Object + this = m.now + if this = invalid + this = CreateObject("roDateTime") + m.now = this + end if + this.mark() + return this +end function + +function UrlEncode(url as String) as String + ue = m.UrlEncoder + if ue = invalid + ue = CreateObject("roUrlTransfer") + m.UrlEncoder = ue + end if + return ue.UrlEncode(url) +end function + +function UrlEscape(url as String) as String + ue = m.UrlEncoder + if ue = invalid + ue = CreateObject("roUrlTransfer") + m.UrlEncoder = ue + end if + return ue.escape(url) +end function + +function UrlUnescape(url as String) as String + ue = m.UrlEncoder + if ue = invalid + ue = CreateObject("roUrlTransfer") + m.UrlEncoder = ue + end if + return ue.unescape(url) +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", + 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 = GetExtension(uri) + if map.doesexist(ext) then return map[ext] else return map.default +end function + +function GetExtension(fn as String) as String + l = fn.tokenize(".") + if l.count()>0 then return l.GetTail() else return "" +end function + +function deduceType(val as String, force=invalid as Dynamic) as Dynamic + if isstr(force) + tforce = lcase(force) + if tforce.right(6)="string" then return val + if tforce.left(3)="int" then return strtoi(val) + if tforce.left(4)="bool" then return (lcase(val)="true" or strtoi(val)=1) + end if + tval = lcase(val) + if tval="false" then return false + if tval="true" then return true + if tval="0" then return 0 + tval = strtoi(val) + if tval<>0 then return tval + return val +end function \ No newline at end of file diff --git a/src/www/index.html b/src/www/index.html new file mode 100644 index 00000000..417c9c3f --- /dev/null +++ b/src/www/index.html @@ -0,0 +1,11 @@ + + + + + + Invidious + + +
Hello! This is an HTML file served from Roku app.
+ +