Feature/logger (#147)

* todos

* New logger

* Remove roku-log
This commit is contained in:
Brahim Hadriche authored and GitHub committed 2023-09-19 17:49:48 -04:00
1 parent cf6d89f44f
commit 190dcdffe3
37 files changed
+417 -291

No files matched your search

@@ -2,7 +2,7 @@ import "pkg:/source/utils/Types.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/FocusManagement.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/components/VideoPlayer/VideoUtils.bs"
function Init()
@@ -10,8 +10,6 @@ function Init()
end function
function OnNodeReady()
m.log = new log.Logger("AppController")
NodeSetFocus(m.top.root, true)
end function
@@ -97,7 +95,7 @@ end function
function OnExitDialog(event as object)
buttonIndex = event.GetData()
if buttonIndex = 0 ' Exit
m.log.info("Exiting app")
LogInfo("Exiting app")
m.top.getScene().exitChannel = true
end if
end function
@@ -1,11 +1,8 @@
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/FocusManagement.bs"
import "pkg:/source/utils/Types.bs"
import "pkg:/source/utils/StringUtils.bs"
function Init()
m.log = new log.Logger("ChannelView")
m.banner = m.top.findNode("banner")
m.thumbnail = m.top.findNode("thumbnail")
m.authorLabel = m.top.findNode("authorLabel")
@@ -39,7 +39,7 @@ function OnChannelContentTaskResult(output as object) as void
error = output.result.error
end if
error = ErrorUtils.Format(error)
m.log.error(error)
LogError(error)
playlistId = output.task.input.content.playlistId
message = `Failed to load playlist ${playlistId}\n${error}`
DialogUtils.ShowDialog(message, "Playlist load fail", true)
+2 -2
View File
@@ -14,13 +14,13 @@ end function
function LaunchArgumentsReceived() as void
launchArgs = m.scene.launchArgs
m.log.info("LaunchArgumentsReceived", launchArgs)
LogInfo("LaunchArgumentsReceived", launchArgs)
ProcessArguments(launchArgs)
end function
function InputArgumentsReceived() as void
inputArgs = m.scene.inputArgs
m.log.info("InputArgumentsReceived", inputArgs)
LogInfo("InputArgumentsReceived", inputArgs)
ProcessArguments(inputArgs)
end function
@@ -0,0 +1,63 @@
import "pkg:/source/utils/Types.bs"
function Init()
m.top.functionName = "LoggerLoop"
port = CreateObject("roMessagePort")
m.top.ObserveField("logLine", port)
scene = m.top.getScene()
if scene.hasField("systemLogEvent")
scene.ObserveFieldScoped("systemLogEvent", port)
end if
m.port = port
end function
function LoggerLoop()
port = m.port
buffer = CreateObject("roByteArray")
previousLogsFile = m.top.folder + "/" + m.top.filenamePrevious
logsFile = m.top.folder + "/" + m.top.filename
CreateDirectory(m.top.folder)
DeleteFile(previousLogsFile)
MoveFile(logsFile, previousLogsFile)
while true
msg = wait(0, port)
msgType = type(msg)
if msgType = "roSGNodeEvent"
field = msg.getField()
if field = "logLine"
OnLineLog(msg, logsFile, buffer)
else if field = "systemLogEvent"
OnLineSysLog(msg, logsFile, buffer)
end if
end if
end while
end function
function OnLineLog(event as object, logsFile as string, buffer as object)
line = event.getData()
' bs:disable-next-line LINT3012
print line
buffer.FromAsciiString(line + `\n`)
buffer.AppendFile(logsFile)
end function
function OnLineSysLog(event as object, logsFile as string, buffer as object) as void
info = event.getData()
if info.LogType <> "http.error"
return
end if
line = `[SysLog] ${FormatJson(info)}`
' bs:disable-next-line LINT3012
print line
buffer.FromAsciiString(line + `\n`)
buffer.AppendFile(logsFile)
end function
@@ -1,10 +1,10 @@
<?xml version='1.0' encoding='UTF-8'?>
<component name='log_FileTransport' extends='Node'>
<component name='Logger' extends='Task'>
<interface>
<field id='logLevel' type='int' value='2' />
<field id='logLine' type='string' />
<field id='folder' type='string' value='cachefs:/logs' />
<field id='filename' type='string' value='app_logs.txt' />
<field id='filenamePrevious' type='string' value='app_logs_previous.txt' />
<function name='logItem' />
</interface>
<children />
</component>
@@ -1,19 +0,0 @@
import "pkg:/source/asyncTask/asyncTask.bs"
function Init()
m.buffer = CreateObject("roByteArray")
previousLogs = m.top.folder + "/" + m.top.filenamePrevious
newLogs = m.top.folder + "/" + m.top.filename
CreateDirectory(m.top.folder)
DeleteFile(previousLogs)
MoveFile(newLogs, previousLogs)
m.logsPath = newLogs
end function
function logItem(name as string, levelNum as integer, text as string) as void
m.buffer.FromAsciiString(`[${name}] ${text}\n`)
m.buffer.AppendFile(m.logsPath)
end function
+2 -2
View File
@@ -4,8 +4,8 @@ import "pkg:/source/utils/Logging.bs"
import "pkg:/components/EcpArgs.bs"
function Init()
InitializeLogging()
m.log = new log.Logger("MainScene")
InitializeLogger()
m.scene = m.top.getScene()
' At this point, the "MainScene" node is not yet added to the scene, and does not have a parent yet.
' Let's wait until it has one.
@@ -5,9 +5,7 @@
function Init()
InitializeBindings() ' auto-generated!
InitializeLogging()
m.log = log_Logger("MainScene")
m.__le = m.log.enabled
InitializeLogger()
m.scene = m.top.getScene()
' At this point, the "MainScene" node is not yet added to the scene, and does not have a parent yet.
' Let's wait until it has one.
@@ -11,7 +11,6 @@
<script type="text/brightscript" uri="pkg:/components/MainScene_bindings.brs" />
<script type="text/brightscript" uri="pkg:/components/MainScene.brs" />
<script type="text/brightscript" uri="pkg:/source/utils/Logging.brs" />
<script type="text/brightscript" uri="pkg:/source/roku_modules/log/LogMixin.brs" />
<script type="text/brightscript" uri="pkg:/source/utils/LoadingScreen.brs" />
<script type="text/brightscript" uri="pkg:/components/EcpArgs.brs" />
<script type="text/brightscript" uri="pkg:/source/utils/Types.brs" />
@@ -3,13 +3,12 @@ import "pkg:/components/VideoPlayer/VideoUtils.bs"
import "pkg:/source/asyncTask/asyncTask.bs"
import "pkg:/components/VideoFeed/FeedLoadState.bs"
import "pkg:/components/PlaylistView/PlaylistContentTask.bs"
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/source/utils/ArrayUtils.bs"
function Init()
m.log = new log.Logger("PlayQueue")
m.pendingLoadTasks = {}
' TODO:P1 prevent adding duplicates of the same video/playlist
m.queue = CreateObject("roArray", 0, true)
@@ -163,7 +162,7 @@ function OnPlaylistContentTaskResult(output as object) as void
error = output.result.error
end if
error = ErrorUtils.Format(error)
m.log.error(error)
LogError(error)
playlistId = playlist.playlistId
message = `Failed to load playlist ${playlistId}\n${error}`
' TODO:P1 play next upon closing the dialog
@@ -2,7 +2,7 @@ import "pkg:/source/utils/FocusManagement.bs"
import "pkg:/source/utils/Types.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/components/VideoPlayer/VideoUtils.bs"
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/asyncTask/asyncTask.bs"
import "pkg:/components/PlaylistView/PlaylistContentTask.bs"
import "pkg:/components/VideoFeed/FeedLoadState.bs"
@@ -10,8 +10,6 @@ import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
function Init()
m.log = new log.Logger("PlaylistView")
m.background = m.top.findNode("background")
m.backgroundSmall = m.top.findNode("backgroundSmall")
m.titleLabel = m.top.findNode("titleLabel")
@@ -90,7 +88,7 @@ function OnItemSelected(event as object)
video = playlist.getChild(index)
videoId = video.videoId
if not StringUtils.IsNullOrEmpty(videoId)
m.log.info("Play playlist: " + playlistId + " video: " + videoId)
LogInfo("Play playlist: " + playlistId + " video: " + videoId)
m.playQueue@.Play(playlist, index)
end if
end function
@@ -146,7 +144,7 @@ function OnPlaylistContentTaskResult(output as object) as void
error = output.result.error
end if
error = ErrorUtils.Format(error)
m.log.error(error)
LogError(error)
playlistId = output.task.input.content.playlistId
message = `Failed to load playlist ${playlistId}\n${error}`
DialogUtils.ShowDialog(message, "Playlist load fail", true)
@@ -1,6 +1,5 @@
import "pkg:/components/Navigation/Navigation.bs"
import "pkg:/source/utils/Types.bs"
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/ArrayUtils.bs"
function Init()
@@ -151,8 +150,6 @@ function PopulateLists(contentNodes as object, options as object)
end function
function OnNodeReady()
m.log = new log.Logger("SearchFilters")
RefreshUI()
m.controls.date.ObserveField("checkedItem", FuncName(OnListChecked))
@@ -4,7 +4,7 @@ import "pkg:/source/asyncTask/asyncTask.bs"
import "pkg:/source/services/SearchHistory.bs"
import "pkg:/source/utils/LoadingScreen.bs"
import "pkg:/source/utils/FocusManagement.bs"
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/ErrorUtils.bs"
function Init()
@@ -32,8 +32,6 @@ function Init()
end function
function OnNodeReady()
m.log = new log.Logger("SearchScreen")
m.rowlist@.BindNode(invalid)
m.keyboard.ObserveField("text", FuncName(OnTextChange))
m.suggestions.ObserveField("buttonFocused", FuncName(OnSearchButtonFocused))
@@ -112,7 +110,7 @@ function OnSearchSuggestionsTaskResults(output as object) as void
end if
if not output.success
m.log.error(ErrorUtils.Format(output.error))
LogError(ErrorUtils.Format(output.error))
return
end if
' In case this is an old request, discard suggestions
@@ -1,13 +1,11 @@
import "pkg:/source/asyncTask/asyncTask.bs"
import "pkg:/components/Screens/SettingsScreen/InvidiousInstance/InvidiousPublicInstances/InvidiousPublicInstancesTask.bs"
import "pkg:/source/utils/FocusManagement.bs"
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
function Init()
m.log = new log.Logger("InvidiousPublicInstances")
m.failedLabel = m.top.findNode("failedLabel")
m.refreshButton = m.top.findNode("refreshButton")
m.instances = m.top.findNode("instances")
@@ -71,7 +69,7 @@ function OnInvidiousPublicInstancesTaskResults(output as object) as void
error = output.result.error
end if
error = ErrorUtils.Format(error)
m.log.error(output.error)
LogError(output.error)
message = `Failed to load Invidious public instances\n${error}`
DialogUtils.ShowDialog(message, "Invidious public instances load error", true)
@@ -3,7 +3,7 @@ import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/Logging.bs"
namespace Invidious
const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,users"
@@ -34,8 +34,6 @@ namespace Invidious
public node as object
function new(node as object)
m.log = new log.Logger("InvidiousService")
m.node = node
' TODO:P2 api definitions are not needed everytime, move them to a separate function and lazy load
apiDefinitions = node.apiDefinitions
@@ -290,8 +288,8 @@ namespace Invidious
function DeleteExpiredToken(response as object)
if response.StatusCode() = 403
m.log.warn(`Invidious instance responded with 403: ${response.Text()}`)
m.log.warn("Deleting Invidious token...")
LogWarn(`Invidious instance responded with 403: ${response.Text()}`)
LogWarn("Deleting Invidious token...")
m.DeleteAuthToken()
end if
end function
@@ -1,5 +1,5 @@
import "pkg:/source/utils/Types.bs"
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/asyncTask/asyncTask.bs"
import "pkg:/components/VideoFeed/VideoRowListContentTask.bs"
import "pkg:/components/VideoFeed/VideoRowListRowContentTask.bs"
@@ -14,8 +14,6 @@ function Init()
end function
function OnNodeReady()
m.log = new log.Logger("VideoRowList")
m.top.ObserveField("itemFocused", FuncName(OnItemFocused))
m.top.ObserveField("rowItemFocused", FuncName(OnRowItemFocused))
m.top.ObserveField("rowItemSelected", FuncName(OnRowItemSelected))
@@ -70,15 +68,15 @@ function OnRowItemSelected(event as object)
if rowItem.type = "video"
videoId = rowItem.videoId
m.log.info("Play video: " + videoId)
LogInfo("Play video: " + videoId)
m.playQueue@.Play(rowItem, -1)
else if rowItem.type = "playlist"
playlistId = rowItem.playlistId
m.log.info("Open playlist: " + playlistId)
LogInfo("Open playlist: " + playlistId)
PlaylistUtils.Open(rowItem)
else if rowItem.type = "channel"
authorId = rowItem.authorId
m.log.info("Open channel: " + authorId)
LogInfo("Open channel: " + authorId)
ChannelUtils.Open(rowItem)
else if rowItem.type = "action"
if rowItem.action = "LoginDialog"
@@ -90,7 +88,7 @@ function OnRowItemSelected(event as object)
end function
function OnAuthTokenChange()
' TODO:P1: Reload only content that is authenticated
' TODO:P2: Reload only content that is authenticated
' Should not reload if the page is not visible. Instead, capture state and reload when the page becomes visible
InitContent()
end function
@@ -197,7 +195,7 @@ function OnVideoRowListRowContentTaskResult(output as object) as void
error = output.result.error
end if
error = ErrorUtils.Format(error)
m.log.error(error)
LogError(error)
m.top.onError = error
message = `Failed to load feed\n${error}`
DialogUtils.ShowDialog(message, "Feed load fail", true)
@@ -95,7 +95,7 @@ namespace SponsorBlock
if not output.success
error = ErrorUtils.Format(output.error)
m.log.error(error)
LogError(error)
return
end if
@@ -136,7 +136,7 @@ namespace SponsorBlock
if action = "AutoSkip"
m.top.seek = segmentEnd
m.log.info("Skipping section:", segment["category"])
LogInfo("Skipping section:", segment["category"])
SendSkippedSectionEvent(segment.UUID)
return
end if
@@ -10,7 +10,6 @@ import "pkg:/components/VideoPlayer/SponsorBlock.bs"
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
function Init()
m.log = new log.Logger("VideoPlayer")
SetPlayerStyle()
SetupAnimation()
@@ -90,7 +89,7 @@ function OnVideoContentTaskResults(output as object) as void
error = output.result.error
end if
error = ErrorUtils.Format(error)
m.log.error(error)
LogError(error)
videoId = output.task.input.content.videoId
message = `Failed to load video information for ${videoId}\n${error}`
DialogUtils.ShowDialog(message, "Video load fail", true)
@@ -145,13 +144,13 @@ function OnVideoPlayerStateChange() as void
' If we successfully played the video, then any error that comes later is not due to a 403 (FORBIDDEN).
' This is to reduce false positives, as we do not want retry another link if the first link is working fine.
if state = "playing" and not m.videoPlayingSuccess
m.log.info(`Now playing video ${m.top.content.url}`)
LogInfo(`Now playing video ${m.top.content.url}`)
m.videoPlayingSuccess = true
end if
if state = "error"
errorInfo = m.top.errorInfo
m.log.error(`Error playing video ${m.top.content.videoId}`, errorInfo)
LogError(`Error playing video ${m.top.content.videoId}`, errorInfo)
if m.videoPlayingSuccess <> true
' http for stream format, mediaerror for DASH
if errorInfo.category = "http" or errorInfo.category = "mediaerror"
@@ -162,7 +161,7 @@ function OnVideoPlayerStateChange() as void
m.top.content.playletStreamUrlIndex = playletStreamUrlIndex
if playletStreamUrlIndex < playletStreamUrls.Count()
nextUrl = playletStreamUrls[playletStreamUrlIndex]
m.log.error(`Stream ${currentUrl} failed to play. Trying next stream ${nextUrl}`)
LogError(`Stream ${currentUrl} failed to play. Trying next stream ${nextUrl}`)
m.top.content.url = nextUrl
' This video errored, and is about to finish, so don't close the video yet
@@ -231,7 +230,7 @@ function PlayNextRecommendedVideo(recommendedVideos as object) as boolean
continue for
end if
if not m.container@.watchedVideosContain(videoId)
m.log.info(`Playing next recommended video (${videoId})`)
LogInfo(`Playing next recommended video (${videoId})`)
node = InvidiousContent.ToVideoContentNode(invalid, metadata, invalid)
VideoUtils.PlayVideo(node)
return true
@@ -3,14 +3,12 @@ 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"
import "pkg:/source/utils/Logging.bs"
namespace Http
const BUFSIZE = 65536
class HttpConnection
private log as log.Logger
private total_received = 0
private total_sent = 0
private id = "<uninit>"
@@ -22,7 +20,6 @@ namespace Http
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()
@@ -42,14 +39,13 @@ namespace Http
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")
LogInfo("recycle")
m.Restart()
m.SetState(Http.HttpConnectionState.RECV_REQUEST) ' ready for another
end function
@@ -60,7 +56,7 @@ namespace Http
m.SetState(Http.HttpConnectionState.RECV_REQUEST)
m.client = m.socket.getReceivedFromAddress().getAddress()
m.log.info("accepted connection @" + m.client)
LogInfo("accepted connection @" + m.client)
' try to read right away rather than going through another iteration
' of the poll loop.
@@ -69,7 +65,7 @@ namespace Http
function PollRequest(server as HttpServer)
if m.state <> Http.HttpConnectionState.RECV_REQUEST
m.log.error("illegal request state @" + m.client)
LogError("illegal request state @" + m.client)
end if
rcvStrByteLen = m.socket.GetCountRcvBuf()
@@ -96,7 +92,7 @@ namespace Http
else
m.setState(Http.HttpConnectionState.DONE)
m.close = true
m.log.error("couldn't process request or response, closing @" + m.client)
LogError("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)
@@ -114,7 +110,7 @@ namespace Http
function PollHeader(server as HttpServer) as void
if m.state <> Http.HttpConnectionState.SEND_HEADER
m.log.error("illegal header state @" + m.client)
LogError("illegal header state @" + m.client)
end if
sent = m.response.SendHeader(m.socket, Http.BUFSIZE)
@@ -136,7 +132,7 @@ namespace Http
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)
LogError("illegal response state @" + m.client)
end if
sent = m.response.Send(m.socket, Http.BUFSIZE)
@@ -166,9 +162,9 @@ namespace Http
'info(m,op + " would have blocked @"+m.client)
else
if m.socket.eSuccess()
m.log.info(op + " peer closed @" + m.client)
LogInfo(op + " peer closed @" + m.client)
else
m.log.error(op + " transfer error @" + m.client, m.socket.status())
LogError(op + " transfer error @" + m.client, m.socket.status())
end if
m.close = true
m.SetState(Http.HttpConnectionState.DONE)
@@ -178,17 +174,11 @@ namespace Http
function SetState(newState as Http.HttpConnectionState)
if m.state <> newState
' m.log.debug(m, "state change" + Stri(m.state) + " ->" + Stri(newState))
LogDebug(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
@@ -10,8 +10,6 @@ namespace Http
end function
class HttpRequest
private log as log.Logger
' members
private method = invalid
private uri = invalid
@@ -33,7 +31,6 @@ namespace Http
private ready_for_response = false
function new()
m.log = new log.Logger("HttpRequest")
m.id = Http.GetHttpRequestId()
m.headers = CreateObject("roAssociativeArray")
end function
@@ -81,7 +78,7 @@ namespace Http
function ParseOperation() as boolean
if m.buffer_index <> 0
m.log.error(`invalid state: reading operation, but request is at index ${m.buffer_index}`)
LogError(`invalid state: reading operation, but request is at index ${m.buffer_index}`)
m.ready_for_response = true
return false
end if
@@ -93,7 +90,7 @@ namespace Http
operation = m.ReadHeaderLine()
if operation = invalid or operation = ""
m.log.error("empty request")
LogError("empty request")
m.ready_for_response = true
return false
end if
@@ -103,9 +100,9 @@ namespace Http
m.method = Ucase(parts[0])
m.uri = parts[1]
m.protocol = Ucase(parts[2])
m.log.info(`${m.method} '${m.uri}'`)
LogInfo(`${m.method} '${m.uri}'`)
else
m.log.error("invalid request: " + operation)
LogError("invalid request: " + operation)
m.ready_for_response = true
end if
@@ -148,7 +145,7 @@ namespace Http
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")
LogError("invalid request: request body found, but no Content-Length header")
return false
else
return true
@@ -160,7 +157,7 @@ namespace Http
end if
if m.body.len() > contentLength
m.log.error("invalid request: request body is larger than Content-Length")
LogError("invalid request: request body is larger than Content-Length")
m.ready_for_response = true
return false
end if
@@ -233,7 +230,7 @@ namespace Http
m.range_end_given = true
end if
end if
m.log.info("range request begin" + Stri(m.range_begin) + " end" + Stri(m.range_end))
LogInfo("range request begin" + Stri(m.range_begin) + " end" + Stri(m.range_end))
end if
end function
@@ -9,8 +9,6 @@ namespace Http
end function
class HttpResponse
private log as log.Logger
private source = Http.HttpResponseSource.NONE
' members
@@ -32,7 +30,6 @@ namespace Http
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
@@ -111,20 +108,20 @@ namespace Http
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}`)
LogDebug(`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")
LogInfo("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)
m.LogSentRange(sent, m.buf_start + buf_pos, m.body_buffer_length)
if sent > 0
m.sent = m.sent + sent
end if
@@ -141,7 +138,7 @@ namespace Http
else
sent = sock.sendStr(m.header.mid(m.header_sent))
end if
m.LogInfo(sent, m.header_sent, m.header_length)
m.LogSentRange(sent, m.header_sent, m.header_length)
if sent > 0
m.header_sent = m.header_sent + sent
end if
@@ -176,8 +173,8 @@ namespace Http
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)}]`)
function LogSentRange(recent as integer, from as integer, total as integer)
LogDebug(`Sent ${recent} [${m.MakeRange(from, recent, total)}]`)
end function
function KeepAlive(keepAlive as boolean)
@@ -7,8 +7,6 @@ import "HttpConnection.bs"
namespace Http
class HttpServer
private log as log.Logger
' members
private connections = invalid
private sockin = invalid
@@ -26,7 +24,6 @@ namespace Http
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 = []
@@ -44,13 +41,13 @@ namespace Http
sockin = CreateObject("roStreamSocket")
if sockin = invalid
success = false
m.log.error("socket()")
LogError("socket()")
end if
' reuse address
if not sockin.setReuseAddr(true)
success = false
m.log.error("setsockopt(SO_REUSEADDR)", sockin.status())
LogError("setsockopt(SO_REUSEADDR)", sockin.status())
end if
' bind socket
@@ -58,12 +55,12 @@ namespace Http
addrin.setPort(m.settings.Port)
if not sockin.setAddress(addrin)
success = false
m.log.error("bind(port" + Stri(m.settings.Port) + ")", sockin.status())
LogError("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())
LogError("listen()", sockin.status())
end if
' monitor socket
sockin.setMessagePort(m.settings.MessagePort)
@@ -71,7 +68,7 @@ namespace Http
m.sockin = sockin
m.log.info("listening on " + addrin.getAddress())
LogInfo("listening on " + addrin.getAddress())
return success
end function
@@ -95,7 +92,7 @@ namespace Http
conn.socket.notifyWritable(true)
conn.socket.notifyReadable(false)
else
m.log.error("invalid state")
LogError("invalid state")
end if
end for
end function
@@ -126,7 +123,7 @@ namespace Http
else if cs = Http.HttpConnectionState.DONE
' handle with other connections that might transition to done
else
m.log.error("invalid state")
LogError("invalid state")
end if
cs = conn.state
if cs = Http.HttpConnectionState.DONE
@@ -134,7 +131,7 @@ namespace Http
conn.socket.close()
connections.delete(id)
else if conn.ws_upgrade and m.websocket <> invalid
m.log.info("upgrading connection to web socket")
LogInfo("upgrading connection to web socket")
m.websocket.AddConnection(conn.socket)
connections.delete(id)
else
@@ -149,7 +146,7 @@ namespace Http
sockin = m.sockin
socket = sockin.accept()
if not sockin.eOK()
m.log.error("accept()", sockin.status())
LogError("accept()", sockin.status())
end if
if socket = invalid
return invalid
@@ -171,7 +168,7 @@ namespace Http
m.websocket.Close()
end if
' final stats
m.log.info(`\n` + m.stats())
LogInfo(`\n` + m.stats())
end function
function Stats() as string
@@ -3,8 +3,6 @@ import "pkg:/source/utils/StringUtils.bs"
namespace Http
class HttpStaticFilesRouter extends HttpRouter
private log as log.Logger
private root
private route
private showDirectories
@@ -13,7 +11,6 @@ namespace Http
function new(route as string, root as string, showDirectories = false as boolean, showHidden = false as boolean, fsCheck = true as boolean)
super()
m.log = new log.Logger("HttpStaticFilesRouter")
m.root = root
m.route = route
@@ -78,7 +75,7 @@ namespace Http
mimetype = server.utils.MimeType(decoded_path)
response.ContentType(mimetype)
response.fileLength = stat.size
router.log.info(`uri=${request.uri}, target=${path}, content-type=${mimetype}, content-length=${response.fileLength}`)
LogInfo(`uri=${request.uri}, target=${path}, content-type=${mimetype}, content-length=${response.fileLength}`)
router.GenerateFile(path, router, request, response)
return true
else
@@ -117,7 +114,7 @@ namespace Http
start = 0
end if
else
router.log.error(1, "internal error - range start/finish logic inconsistency")
LogError(1, "internal error - range start/finish logic inconsistency")
end if
response.start = start
@@ -126,7 +123,7 @@ namespace Http
response.headers["Content-Range"] = "bytes " + response.MakeRange(response.start, response.body_buffer_length, response.filelength)
response.http_code = 206
router.log.info("sending range " + response.MakeRange(start, response.body_buffer_length, response.fileLength))
LogInfo("sending range " + response.MakeRange(start, response.body_buffer_length, response.fileLength))
else ' no range stuff
response.body_buffer_length = response.fileLength
response.ContentLength(response.body_buffer_length)
@@ -198,7 +195,7 @@ namespace Http
safe_url = uri ' UrlEncode(uri) ' too much encoding
listing += `<a href="${safe_url}">${item}${indicator}</a>\n`
else
router.log.warn("insufficient stat info to include '" + dir + item + "'")
LogWarn("insufficient stat info to include '" + dir + item + "'")
end if
end if
end for
@@ -3,9 +3,6 @@ import "pkg:/components/Web/WebServer/Middleware/HttpDefaultRouter.bs"
import "pkg:/source/utils/Logging.bs"
function Init()
InitializeLogging()
m.log = new log.Logger("WebServer")
m.top.functionName = "WebServerLoop"
end function
@@ -40,7 +37,7 @@ function WebServerLoop() as void
server = new Http.HttpServer(settings, m.top)
if not server.success
m.top.isRunning = false
m.log.error("Failed to start server")
LogError("Failed to start server")
return
end if
@@ -73,12 +70,12 @@ function WebServerLoop() as void
end if
end while
m.log.info("closing server")
LogInfo("closing server")
server.Close()
m.top.isRunning = false
m.top.unobserveField("shouldQuit")
end function
function SetupRoutes(server as object)
m.log.warn("No routes configured")
LogWarn("No routes configured")
end function