[refactor] web server routing system (#270)
* [refactor] web server routing system * regex literal * Docs
This commit is contained in:
1 parent
a710a23444
commit
7e5b2246fa
25 files changed
+820
-656
No files matched your search
@@ -72,7 +72,8 @@
|
||||
"../tools/bs-plugins/validation-plugin.ts",
|
||||
"../tools/bs-plugins/logger-plugin.ts",
|
||||
"../tools/bs-plugins/image-gen-plugin.ts",
|
||||
"../tools/bs-plugins/type-gen-plugin.ts"
|
||||
"../tools/bs-plugins/type-gen-plugin.ts",
|
||||
"../tools/bs-plugins/web-server-plugin.ts"
|
||||
],
|
||||
"retainStagingDir": true,
|
||||
"require": [
|
||||
|
||||
@@ -28,7 +28,8 @@
|
||||
"../tools/bs-plugins/validation-plugin.ts",
|
||||
"../tools/bs-plugins/logger-plugin.ts",
|
||||
"../tools/bs-plugins/image-gen-plugin.ts",
|
||||
"../tools/bs-plugins/type-gen-plugin.ts"
|
||||
"../tools/bs-plugins/type-gen-plugin.ts",
|
||||
"../tools/bs-plugins/web-server-plugin.ts"
|
||||
],
|
||||
"rooibos": {
|
||||
"logLevel": 2,
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
- [Tracking transpilied files](#tracking-transpilied-files)
|
||||
- [Logger](#logger)
|
||||
- [Type Gen](#type-gen)
|
||||
- [Web Server](#web-server)
|
||||
|
||||
Playlet implements a few [Brighterscript Plugins](https://github.com/rokucommunity/brighterscript/blob/master/docs/plugins.md). The plugins inject themselves in the compilation process, allowing the modification of bs scripts, xml components, and even assets or the app manifest. Let's start with a simple one:
|
||||
|
||||
@@ -571,3 +572,33 @@ function ValidBool(obj as dynamic) as boolean
|
||||
end if
|
||||
end function
|
||||
```
|
||||
|
||||
## Web Server
|
||||
|
||||
**[Source](/tools/bs-plugins/web-server-plugin.ts)**
|
||||
|
||||
### Why
|
||||
|
||||
Handles routing annotations (e.g. `@get("/api/something")) so that they are handled by the routers/middlewares. It's nicer than having to register things by hand.
|
||||
|
||||
### How
|
||||
|
||||
Routers need to inherit from `Http.HttpRouter`. Then, once a request handled is annotated, e.g.
|
||||
|
||||
```bs
|
||||
@get("/")
|
||||
function GoHome(context as object) as boolean
|
||||
response = context.response
|
||||
response.Redirect("/index.html")
|
||||
return true
|
||||
end function
|
||||
```
|
||||
|
||||
The route and the handler are added to the router. In this example, the `/` route redirects to `index/html`.
|
||||
|
||||
There one special annotation, and one special route:
|
||||
|
||||
- `@all` matches all methods
|
||||
- `*` matches all paths
|
||||
|
||||
So `@all(*)` would be a middleware that will be matched with any request.
|
||||
@@ -14,7 +14,7 @@ function GetLatestPlayletLibVersionFromGithubReleases() as string
|
||||
if response.StatusCode() = 200
|
||||
headers = response.Headers()
|
||||
if headers.location <> invalid
|
||||
regex = CreateObject("roRegex", "/v?(\d+\.\d+\.\d+)", "")
|
||||
regex = /\/v?(\d+\.\d+\.\d+)/
|
||||
match = regex.match(headers.location)
|
||||
if match.Count() = 2
|
||||
return match[1]
|
||||
|
||||
@@ -8,9 +8,11 @@ class DashManifest
|
||||
public invidiousInstance as dynamic
|
||||
|
||||
function new(invidiousInstance as string)
|
||||
m.utils = new Http.Utils()
|
||||
m.invidiousInstance = invidiousInstance
|
||||
|
||||
m.utils = new Http.Utils()
|
||||
m.urlRegex = /https?:\/\/\S+(\/\S+)/i
|
||||
|
||||
' https://github.com/LuanRT/YouTube.js/blob/6082b4a52ee07a622735e6e9128a0531a5ae3bfb/src/utils/StreamingInfo.ts#L332-L349
|
||||
m.colorInfo = {
|
||||
primaries: {
|
||||
@@ -35,10 +37,8 @@ class DashManifest
|
||||
adaptiveFormats.Append (metadata.adaptiveFormats)
|
||||
|
||||
if local
|
||||
urlRegex = CreateObject("roRegex", "https?:\/\/\S+(\/\S+)", "i")
|
||||
|
||||
for i = 0 to adaptiveFormats.Count() - 1
|
||||
adaptiveFormats[i].url = urlRegex.replace(adaptiveFormats[i].url, m.invidiousInstance + "\1")
|
||||
adaptiveFormats[i].url = m.urlRegex.replace(adaptiveFormats[i].url, m.invidiousInstance + "\1")
|
||||
end for
|
||||
end if
|
||||
|
||||
|
||||
@@ -4,38 +4,40 @@ namespace Http
|
||||
|
||||
class BookmarksRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
function new(server as object)
|
||||
super()
|
||||
|
||||
m.Get("/api/bookmarks", function(context as object) as boolean
|
||||
response = context.response
|
||||
m.bookmarksNode = server.task.bookmarks
|
||||
end function
|
||||
|
||||
bookmarksString = RegistryUtils.Read(RegistryUtils.BOOKMARKS)
|
||||
if bookmarksString = invalid
|
||||
response.Json({
|
||||
groups: []
|
||||
})
|
||||
return true
|
||||
end if
|
||||
|
||||
response.SetBodyDataString(bookmarksString)
|
||||
response.ContentType("application/json")
|
||||
response.http_code = 200
|
||||
@get("/api/bookmarks")
|
||||
function GetBookmarks(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
bookmarksString = RegistryUtils.Read(RegistryUtils.BOOKMARKS)
|
||||
if bookmarksString = invalid
|
||||
response.Json({
|
||||
groups: []
|
||||
})
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
m.Get("/api/bookmarks/feeds", function(context as object) as boolean
|
||||
response = context.response
|
||||
router = context.router
|
||||
bookmarks = context.server.task.bookmarks
|
||||
response.SetBodyDataString(bookmarksString)
|
||||
response.ContentType("application/json")
|
||||
response.http_code = 200
|
||||
|
||||
feeds = router.BookmarksContentToFeeds(bookmarks.content)
|
||||
return true
|
||||
end function
|
||||
|
||||
response.Json(feeds)
|
||||
@get("/api/bookmarks/feeds")
|
||||
function GetBookmarksFeeds(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
return true
|
||||
end function)
|
||||
feeds = m.BookmarksContentToFeeds(m.bookmarksNode.content)
|
||||
|
||||
response.Json(feeds)
|
||||
|
||||
return true
|
||||
end function
|
||||
|
||||
' TODO:P1 refactor to share code with Bookmarks screen
|
||||
|
||||
@@ -5,43 +5,45 @@ import "pkg:/source/utils/Types.bs"
|
||||
namespace Http
|
||||
|
||||
class DashRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
function new(server as object)
|
||||
super()
|
||||
|
||||
m.Get("/api/dash", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
invidiousNode = task.invidious
|
||||
m.invidiousNode = server.task.invidious
|
||||
m.invidiousService = new Invidious.InvidiousService(m.invidiousNode)
|
||||
' No need to pass the invidious instance here, we will refresh it for
|
||||
' each request to make sure we are using the latest one
|
||||
m.dashManifest = new DashManifest("")
|
||||
end function
|
||||
|
||||
v = request.query.v
|
||||
local = request.query.local
|
||||
@get("/api/dash")
|
||||
function GenerateDashManifest(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
if StringUtils.IsNullOrEmpty(v)
|
||||
response.Default(400, "Missing video id")
|
||||
return true
|
||||
end if
|
||||
|
||||
service = new Invidious.InvidiousService(invidiousNode)
|
||||
metadataRequest = service.GetVideoMetadata(v)
|
||||
if not metadataRequest.IsSuccess()
|
||||
response.Default(metadataRequest.StatusCode(), metadataRequest.ErrorMessage())
|
||||
return true
|
||||
end if
|
||||
|
||||
metadata = metadataRequest.Json()
|
||||
instance = service.GetInstance()
|
||||
|
||||
dash = new DashManifest(instance)
|
||||
xmlContent = dash.fromVideoMetadata(metadata, ValidString(local) = "true")
|
||||
|
||||
response.http_code = 200
|
||||
response.SetBodyDataString(xmlContent)
|
||||
response.ContentType("application/dash+xml")
|
||||
v = request.query.v
|
||||
local = request.query.local
|
||||
|
||||
if StringUtils.IsNullOrEmpty(v)
|
||||
response.Default(400, "Missing video id")
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
metadataRequest = m.invidiousService.GetVideoMetadata(v)
|
||||
if not metadataRequest.IsSuccess()
|
||||
response.Default(metadataRequest.StatusCode(), metadataRequest.ErrorMessage())
|
||||
return true
|
||||
end if
|
||||
|
||||
metadata = metadataRequest.Json()
|
||||
m.dashManifest.invidiousInstance = m.invidiousService.GetInstance()
|
||||
|
||||
xmlContent = m.dashManifest.fromVideoMetadata(metadata, ValidString(local) = "true")
|
||||
|
||||
response.http_code = 200
|
||||
response.SetBodyDataString(xmlContent)
|
||||
response.ContentType("application/dash+xml")
|
||||
|
||||
return true
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
@@ -4,20 +4,20 @@ namespace Http
|
||||
|
||||
class HomeLayoutRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
function new(server as object)
|
||||
super()
|
||||
|
||||
m.Get("/api/home-layout", function(context as object) as boolean
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
preferences = task.preferences
|
||||
m.preferencesNode = server.task.preferences
|
||||
end function
|
||||
|
||||
feed = HomeScreenUtils.GetFeed("libpkg:/config/default_home_layout.yaml", preferences)
|
||||
response.Json(feed)
|
||||
@get("/api/home-layout")
|
||||
function GetHomeLayout(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
return true
|
||||
end function)
|
||||
feed = HomeScreenUtils.GetFeed("libpkg:/config/default_home_layout.yaml", m.preferencesNode)
|
||||
response.Json(feed)
|
||||
|
||||
return true
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Http
|
||||
|
||||
class HomeRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
super()
|
||||
end function
|
||||
|
||||
@get("/")
|
||||
function GoHome(context as object) as boolean
|
||||
response = context.response
|
||||
response.Redirect("/index.html")
|
||||
return true
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -5,89 +5,88 @@ namespace Http
|
||||
|
||||
class InvidiousRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
function new(server as object)
|
||||
super()
|
||||
|
||||
m.Get("/invidious/login", function(context as object) as boolean
|
||||
response = context.response
|
||||
invidiousNode = context.server.task.invidious
|
||||
m.invidiousNode = server.task.invidious
|
||||
m.invidiousService = new Invidious.InvidiousService(m.invidiousNode)
|
||||
end function
|
||||
|
||||
authLink = invidiousNode@.GetAuthorizeTokenLink()
|
||||
response.Redirect(authLink)
|
||||
@get("/invidious/login")
|
||||
function Login(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
authLink = m.invidiousNode@.GetAuthorizeTokenLink()
|
||||
response.Redirect(authLink)
|
||||
return true
|
||||
end function
|
||||
|
||||
@get("/invidious/logout")
|
||||
function Logout(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
m.invidiousService.Logout()
|
||||
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function
|
||||
|
||||
@get("/invidious/token_callback")
|
||||
function OnTokenReceived(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
if request.query["token"] <> invalid and request.query["ref"] <> invalid
|
||||
' Invidious encodes token and username twice
|
||||
token = request.query["token"].DecodeUriComponent().DecodeUriComponent()
|
||||
username = request.query["username"].DecodeUriComponent().DecodeUriComponent()
|
||||
referer = request.query["ref"].DecodeUriComponent()
|
||||
|
||||
m.invidiousNode@.SetAuthToken(token, referer, username)
|
||||
end if
|
||||
response.Redirect("/")
|
||||
return true
|
||||
end function
|
||||
|
||||
' This is an endpoint allowing the web app to make an authenticated request
|
||||
' without needing the Invidious token
|
||||
' This is a GET not a POST for better caching
|
||||
@get("/invidious/authenticated-request")
|
||||
function AuthRequestProxy(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
token = m.invidiousNode.authToken
|
||||
if token = invalid
|
||||
response.Default(403, "No token, not logged in")
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
m.Get("/invidious/logout", function(context as object) as boolean
|
||||
response = context.response
|
||||
invidiousNode = context.server.task.invidious
|
||||
|
||||
service = new Invidious.InvidiousService(invidiousNode)
|
||||
service.Logout()
|
||||
|
||||
response.Default(204, "OK")
|
||||
feedSource = request.query["feed-source"]
|
||||
if feedSource = invalid
|
||||
response.Default(400, "Expected feed-source")
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
m.Get(Invidious.TOKEN_CALLBACK, function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
invidiousNode = context.server.task.invidious
|
||||
|
||||
if request.query["token"] <> invalid and request.query["ref"] <> invalid
|
||||
' Invidious encodes token and username twice
|
||||
token = request.query["token"].DecodeUriComponent().DecodeUriComponent()
|
||||
username = request.query["username"].DecodeUriComponent().DecodeUriComponent()
|
||||
referer = request.query["ref"].DecodeUriComponent()
|
||||
|
||||
invidiousNode@.SetAuthToken(token, referer, username)
|
||||
end if
|
||||
response.Redirect("/")
|
||||
feedSource = ParseJson(feedSource)
|
||||
if feedSource = invalid
|
||||
response.Default(400, "Expected valid JSON for feed-source")
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
' This is an endpoint allowing the web app to make an authenticated request
|
||||
' without needing the Invidious token
|
||||
' This is a GET not a POST for better caching
|
||||
m.Get("/invidious/authenticated-request", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
invidiousNode = context.server.task.invidious
|
||||
additionalQueryParams = invalid
|
||||
if feedSource.state <> invalid and feedSource.state.queryParams <> invalid
|
||||
additionalQueryParams = feedSource.state.queryParams
|
||||
end if
|
||||
|
||||
token = invidiousNode.authToken
|
||||
if token = invalid
|
||||
response.Default(403, "No token, not logged in")
|
||||
return true
|
||||
end if
|
||||
|
||||
feedSource = request.query["feed-source"]
|
||||
if feedSource = invalid
|
||||
response.Default(400, "Expected feed-source")
|
||||
return true
|
||||
end if
|
||||
|
||||
feedSource = ParseJson(feedSource)
|
||||
if feedSource = invalid
|
||||
response.Default(400, "Expected valid JSON for feed-source")
|
||||
return true
|
||||
end if
|
||||
|
||||
invService = new Invidious.InvidiousService(invidiousNode)
|
||||
|
||||
additionalQueryParams = invalid
|
||||
if feedSource.state <> invalid and feedSource.state.queryParams <> invalid
|
||||
additionalQueryParams = feedSource.state.queryParams
|
||||
end if
|
||||
|
||||
invResponse = invService.MakeRequest(feedSource, additionalQueryParams)
|
||||
if not invResponse.success
|
||||
response.Default(500, `Failed to make request: ${invResponse.error}`)
|
||||
return true
|
||||
end if
|
||||
|
||||
response.Json(invResponse.result)
|
||||
invResponse = m.invidiousService.MakeRequest(feedSource, additionalQueryParams)
|
||||
if not invResponse.success
|
||||
response.Default(500, `Failed to make request: ${invResponse.error}`)
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
response.Json(invResponse.result)
|
||||
return true
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
@@ -5,109 +5,96 @@ namespace Http
|
||||
|
||||
class PlayQueueRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
function new(server as object)
|
||||
super()
|
||||
|
||||
' Get queue
|
||||
m.Get("/api/queue", function(context as object) as boolean
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
playQueue = task.playQueue
|
||||
task = server.task
|
||||
m.playQueueNode = task.playQueue
|
||||
m.invidiousNode = task.invidious
|
||||
m.invidiousService = new Invidious.InvidiousService(m.invidiousNode)
|
||||
end function
|
||||
|
||||
queue = playQueue@.GetQueue()
|
||||
response.Json(queue)
|
||||
@get("/api/queue")
|
||||
function GetQueue(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
queue = m.playQueueNode@.GetQueue()
|
||||
response.Json(queue)
|
||||
return true
|
||||
end function
|
||||
|
||||
@post("/api/queue")
|
||||
function AddToQueue(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
payload = request.Json()
|
||||
if payload = invalid
|
||||
response.Default(400, `Invalid JSON payload`)
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
' Add to queue
|
||||
m.Post("/api/queue", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
playQueue = task.playQueue
|
||||
invidiousNode = task.invidious
|
||||
|
||||
payload = request.Json()
|
||||
if payload = invalid
|
||||
response.Default(400, `Invalid JSON payload`)
|
||||
return true
|
||||
end if
|
||||
|
||||
videoId = payload.videoId
|
||||
playlistId = payload.playlistId
|
||||
if StringUtils.IsNullOrEmpty(videoId) and StringUtils.IsNullOrEmpty(playlistId)
|
||||
response.Default(400, `Missing "videoId" or "playlistId" in payload`)
|
||||
return true
|
||||
end if
|
||||
|
||||
service = new Invidious.InvidiousService(invidiousNode)
|
||||
instance = service.GetInstance()
|
||||
|
||||
contentNode = InvidiousContent.ToRowCellContentNode(payload, instance)
|
||||
playQueue@.AddToQueue(contentNode)
|
||||
|
||||
queue = playQueue@.GetQueue()
|
||||
response.Json(queue)
|
||||
videoId = payload.videoId
|
||||
playlistId = payload.playlistId
|
||||
if StringUtils.IsNullOrEmpty(videoId) and StringUtils.IsNullOrEmpty(playlistId)
|
||||
response.Default(400, `Missing "videoId" or "playlistId" in payload`)
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
' Play a video
|
||||
m.Post("/api/queue/play", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
playQueue = task.playQueue
|
||||
invidiousNode = task.invidious
|
||||
instance = m.invidiousService.GetInstance()
|
||||
|
||||
payload = request.Json()
|
||||
if payload = invalid
|
||||
response.Default(400, `Invalid JSON payload`)
|
||||
return true
|
||||
end if
|
||||
contentNode = InvidiousContent.ToRowCellContentNode(payload, instance)
|
||||
m.playQueueNode@.AddToQueue(contentNode)
|
||||
|
||||
videoId = payload.videoId
|
||||
playlistId = payload.playlistId
|
||||
if StringUtils.IsNullOrEmpty(videoId) and StringUtils.IsNullOrEmpty(playlistId)
|
||||
response.Default(400, `Missing "videoId" or "playlistId" in payload`)
|
||||
return true
|
||||
end if
|
||||
queue = m.playQueueNode@.GetQueue()
|
||||
response.Json(queue)
|
||||
return true
|
||||
end function
|
||||
|
||||
if IsString(payload.timestamp)
|
||||
payload.timestamp = payload.timestamp.toInt()
|
||||
end if
|
||||
@post("/api/queue/play")
|
||||
function Play(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
service = new Invidious.InvidiousService(invidiousNode)
|
||||
instance = service.GetInstance()
|
||||
|
||||
contentNode = InvidiousContent.ToRowCellContentNode(payload, instance)
|
||||
playlistIndex = IsInt(payload.playlistIndex) ? payload.playlistIndex : -1
|
||||
if contentNode.type = "playlist" and playlistIndex = -1
|
||||
playlistIndex = 0
|
||||
end if
|
||||
|
||||
'TODO:P1 play existing item by index instead of new item inserted
|
||||
playQueue@.Play(contentNode, playlistIndex)
|
||||
|
||||
response.Default(204, "OK")
|
||||
payload = request.Json()
|
||||
if payload = invalid
|
||||
response.Default(400, `Invalid JSON payload`)
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
' clear queue
|
||||
m.Delete("/api/queue", function(context as object) as boolean
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
playQueue = task.playQueue
|
||||
|
||||
if playQueue = invalid
|
||||
response.Default(500, `Reference to "playQueue" object was invalid`)
|
||||
return true
|
||||
end if
|
||||
|
||||
playQueue@.Clear()
|
||||
response.Default(204, "OK")
|
||||
videoId = payload.videoId
|
||||
playlistId = payload.playlistId
|
||||
if StringUtils.IsNullOrEmpty(videoId) and StringUtils.IsNullOrEmpty(playlistId)
|
||||
response.Default(400, `Missing "videoId" or "playlistId" in payload`)
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
if IsString(payload.timestamp)
|
||||
payload.timestamp = payload.timestamp.toInt()
|
||||
end if
|
||||
|
||||
instance = m.invidiousService.GetInstance()
|
||||
|
||||
contentNode = InvidiousContent.ToRowCellContentNode(payload, instance)
|
||||
playlistIndex = IsInt(payload.playlistIndex) ? payload.playlistIndex : -1
|
||||
if contentNode.type = "playlist" and playlistIndex = -1
|
||||
playlistIndex = 0
|
||||
end if
|
||||
|
||||
'TODO:P1 play existing item by index instead of new item inserted
|
||||
m.playQueueNode@.Play(contentNode, playlistIndex)
|
||||
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function
|
||||
|
||||
@delete("/api/queue")
|
||||
function ClearQueue(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
m.playQueueNode@.Clear()
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
+57
-55
@@ -4,65 +4,67 @@ namespace Http
|
||||
|
||||
class PlayletLibUrlsRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
function new(server as object)
|
||||
super()
|
||||
|
||||
m.Get("/api/playlet-lib-urls", function(context as object) as boolean
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
scene = task.getScene()
|
||||
|
||||
saved = RegistryUtils.Read(RegistryUtils.PLAYLET_LIB_URLS)
|
||||
if saved <> invalid
|
||||
saved = ParseJson(saved)
|
||||
end if
|
||||
|
||||
response.Json({
|
||||
loaded: scene.playletLibLoadedUrl
|
||||
saved: saved
|
||||
})
|
||||
return true
|
||||
end function)
|
||||
|
||||
m.Post("/api/playlet-lib-urls", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
payload = request.Json()
|
||||
if payload = invalid or not IsArray(payload)
|
||||
response.Default(400, "Invalid payload")
|
||||
return true
|
||||
end if
|
||||
|
||||
if payload.Count() = 0
|
||||
response.Default(400, "Payload must contain at least one item")
|
||||
return true
|
||||
end if
|
||||
|
||||
for each item in payload
|
||||
if StringUtils.IsNullOrEmpty(item.link) or StringUtils.IsNullOrEmpty(item.type)
|
||||
response.Default(400, `Invalid item in array (must have "link" and "type" properties)`)
|
||||
return true
|
||||
end if
|
||||
end for
|
||||
|
||||
RegistryUtils.Write(RegistryUtils.PLAYLET_LIB_URLS, request.body)
|
||||
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function)
|
||||
|
||||
m.Delete("/api/playlet-lib-urls", function(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
RegistryUtils.Delete(RegistryUtils.PLAYLET_LIB_URLS)
|
||||
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function)
|
||||
|
||||
task = server.task
|
||||
m.scene = task.getScene()
|
||||
end function
|
||||
|
||||
@get("/api/playlet-lib-urls")
|
||||
function GetPlayletLibUrls(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
saved = RegistryUtils.Read(RegistryUtils.PLAYLET_LIB_URLS)
|
||||
if saved <> invalid
|
||||
saved = ParseJson(saved)
|
||||
end if
|
||||
|
||||
response.Json({
|
||||
loaded: m.scene.playletLibLoadedUrl
|
||||
saved: saved
|
||||
})
|
||||
return true
|
||||
end function
|
||||
|
||||
@post("/api/playlet-lib-urls")
|
||||
function SetPlayletLibUrls(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
payload = request.Json()
|
||||
if payload = invalid or not IsArray(payload)
|
||||
response.Default(400, "Invalid payload")
|
||||
return true
|
||||
end if
|
||||
|
||||
if payload.Count() = 0
|
||||
response.Default(400, "Payload must contain at least one item")
|
||||
return true
|
||||
end if
|
||||
|
||||
for each item in payload
|
||||
if StringUtils.IsNullOrEmpty(item.link) or StringUtils.IsNullOrEmpty(item.type)
|
||||
response.Default(400, `Invalid item in array (must have "link" and "type" properties)`)
|
||||
return true
|
||||
end if
|
||||
end for
|
||||
|
||||
RegistryUtils.Write(RegistryUtils.PLAYLET_LIB_URLS, request.body)
|
||||
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function
|
||||
|
||||
@delete("/api/playlet-lib-urls")
|
||||
function DeletePlayletLibUrls(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
RegistryUtils.Delete(RegistryUtils.PLAYLET_LIB_URLS)
|
||||
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -2,64 +2,44 @@ namespace Http
|
||||
|
||||
class PreferencesRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
function new(server as object)
|
||||
super()
|
||||
|
||||
' Get preferences
|
||||
m.Get("/api/preferences", function(context as object) as boolean
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
preferences = task.preferences
|
||||
m.preferencesNode = server.task.preferences
|
||||
end function
|
||||
|
||||
if preferences = invalid
|
||||
response.Default(500, `Reference to "preferences" object was invalid`)
|
||||
return true
|
||||
end if
|
||||
@get("/api/preferences")
|
||||
function GetPreferences(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
userPrefs = preferences@.GetUserPreferences()
|
||||
response.Json(userPrefs)
|
||||
userPrefs = m.preferencesNode@.GetUserPreferences()
|
||||
response.Json(userPrefs)
|
||||
return true
|
||||
end function
|
||||
|
||||
@put("/api/preferences")
|
||||
function UpdatePreferences(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
payload = request.Json()
|
||||
if payload = invalid
|
||||
response.Default(400, `Invalid JSON payload`)
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
' Update preferences
|
||||
m.Put("/api/preferences", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
preferences = task.preferences
|
||||
m.preferencesNode@.ApplyUserPreferences(payload)
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function
|
||||
|
||||
payload = request.Json()
|
||||
if payload = invalid
|
||||
response.Default(400, `Invalid JSON payload`)
|
||||
return true
|
||||
end if
|
||||
|
||||
if preferences = invalid
|
||||
response.Default(500, `Reference to "preferences" object was invalid`)
|
||||
return true
|
||||
end if
|
||||
|
||||
preferences@.ApplyUserPreferences(payload)
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function)
|
||||
|
||||
' Reset default preferences
|
||||
m.Delete("/api/preferences", function(context as object) as boolean
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
preferences = task.preferences
|
||||
|
||||
if preferences = invalid
|
||||
response.Default(500, `Reference to "preferences" object was invalid`)
|
||||
return true
|
||||
end if
|
||||
|
||||
preferences@.ClearUserPreferences()
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function)
|
||||
@delete("/api/preferences")
|
||||
function ResetPreferences(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
m.preferencesNode@.ClearUserPreferences()
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
@@ -4,49 +4,50 @@ namespace Http
|
||||
|
||||
class SearchHistoryRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
function new(server as object)
|
||||
super()
|
||||
|
||||
m.Get("/api/search-history", function(context as object) as boolean
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
preferences = task.preferences
|
||||
m.preferencesNode = server.task.preferences
|
||||
end function
|
||||
|
||||
response.Json(SearchHistoryUtils.GetAllSaved(preferences))
|
||||
@get("/api/search-history")
|
||||
function GetSearchHistory(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
response.Json(SearchHistoryUtils.GetAllSaved(m.preferencesNode))
|
||||
return true
|
||||
end function
|
||||
|
||||
' TODO:P1 should be POST
|
||||
@put("/api/search-history")
|
||||
function AddSearchHistory(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
payload = request.Json()
|
||||
if payload = invalid
|
||||
response.Default(400, `Invalid JSON payload`)
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
m.Put("/api/search-history", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
preferences = task.preferences
|
||||
|
||||
payload = request.Json()
|
||||
if payload = invalid
|
||||
response.Default(400, `Invalid JSON payload`)
|
||||
return true
|
||||
end if
|
||||
|
||||
query = payload.query
|
||||
if query = invalid
|
||||
response.Default(400, `missing "query" property in JSON payload`)
|
||||
return true
|
||||
end if
|
||||
|
||||
SearchHistoryUtils.Save(preferences, query)
|
||||
response.Json(SearchHistoryUtils.GetAllSaved(preferences))
|
||||
query = payload.query
|
||||
if query = invalid
|
||||
response.Default(400, `missing "query" property in JSON payload`)
|
||||
return true
|
||||
end function)
|
||||
end if
|
||||
|
||||
m.Delete("/api/search-history", function(context as object) as boolean
|
||||
response = context.response
|
||||
SearchHistoryUtils.Save(m.preferencesNode, query)
|
||||
response.Json(SearchHistoryUtils.GetAllSaved(m.preferencesNode))
|
||||
return true
|
||||
end function
|
||||
|
||||
SearchHistoryUtils.Clear()
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function)
|
||||
@delete("/api/search-history")
|
||||
function ClearSearchHistory(context as object) as boolean
|
||||
response = context.response
|
||||
|
||||
SearchHistoryUtils.Clear()
|
||||
response.Default(204, "OK")
|
||||
return true
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
@@ -4,67 +4,69 @@ namespace Http
|
||||
|
||||
class StateApiRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
function new(server as object)
|
||||
super()
|
||||
|
||||
m.Get("/api/state", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
task = context.server.task
|
||||
applicationInfoNode = task.applicationInfo
|
||||
preferencesNode = task.preferences
|
||||
invidiousNode = task.invidious
|
||||
task = server.task
|
||||
m.applicationInfoNode = task.applicationInfo
|
||||
m.invidiousNode = task.invidious
|
||||
m.preferencesNode = task.preferences
|
||||
end function
|
||||
|
||||
keys = ["app", "device", "invidious", "preferences"]
|
||||
@get("/api/state")
|
||||
function GetState(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
if request.query.DoesExist("key")
|
||||
keys = request.query["key"]
|
||||
if not IsArray(keys)
|
||||
keys = [keys]
|
||||
end if
|
||||
keys = ["app", "device", "invidious", "preferences"]
|
||||
|
||||
if request.query.DoesExist("key")
|
||||
keys = request.query["key"]
|
||||
if not IsArray(keys)
|
||||
keys = [keys]
|
||||
end if
|
||||
end if
|
||||
|
||||
state = {}
|
||||
|
||||
if ArrayUtils.IndexOfString(keys, "app") <> -1
|
||||
appInfo = m.applicationInfoNode@.GetAppInfo()
|
||||
|
||||
if appInfo.lib_version_latest = "N/A"
|
||||
' If the lib_version_latest field is not available, we can give it a few seconds
|
||||
' To make a request to Github to get the latest version.
|
||||
msgPort = CreateObject("roMessagePort")
|
||||
m.applicationInfoNode.observeFieldScoped("lib_version_latest", msgPort)
|
||||
wait(5000, msgPort)
|
||||
m.applicationInfoNode.unobserveFieldScoped("lib_version_latest")
|
||||
|
||||
appInfo.lib_version_latest = m.applicationInfoNode.lib_version_latest
|
||||
end if
|
||||
|
||||
state = {}
|
||||
state["app"] = appInfo
|
||||
end if
|
||||
|
||||
if ArrayUtils.IndexOfString(keys, "app") <> -1
|
||||
appInfo = applicationInfoNode@.GetAppInfo()
|
||||
if ArrayUtils.IndexOfString(keys, "device") <> -1
|
||||
state["device"] = m.applicationInfoNode@.GetDeviceInfo()
|
||||
end if
|
||||
|
||||
if appInfo.lib_version_latest = "N/A"
|
||||
' If the lib_version_latest field is not available, we can give it a few seconds
|
||||
' To make a request to Github to get the latest version.
|
||||
msgPort = CreateObject("roMessagePort")
|
||||
applicationInfoNode.observeFieldScoped("lib_version_latest", msgPort)
|
||||
wait(5000, msgPort)
|
||||
applicationInfoNode.unobserveFieldScoped("lib_version_latest")
|
||||
if ArrayUtils.IndexOfString(keys, "invidious") <> -1
|
||||
authToken = m.invidiousNode.authToken
|
||||
state["invidious"] = {
|
||||
current_instance: m.invidiousNode@.GetCurrentInstance()
|
||||
auth_url: m.invidiousNode@.GetAuthorizeTokenLink()
|
||||
logged_in: authToken <> invalid
|
||||
logged_in_instance: authToken <> invalid ? authToken.instance : invalid
|
||||
logged_in_username: authToken <> invalid ? authToken.username : invalid
|
||||
}
|
||||
end if
|
||||
|
||||
appInfo.lib_version_latest = applicationInfoNode.lib_version_latest
|
||||
end if
|
||||
if ArrayUtils.IndexOfString(keys, "preferences") <> -1
|
||||
state["preferences"] = m.preferencesNode@.GetUserPreferences()
|
||||
end if
|
||||
|
||||
state["app"] = appInfo
|
||||
end if
|
||||
|
||||
if ArrayUtils.IndexOfString(keys, "device") <> -1
|
||||
state["device"] = applicationInfoNode@.GetDeviceInfo()
|
||||
end if
|
||||
|
||||
if ArrayUtils.IndexOfString(keys, "invidious") <> -1
|
||||
authToken = invidiousNode.authToken
|
||||
state["invidious"] = {
|
||||
current_instance: invidiousNode@.GetCurrentInstance()
|
||||
auth_url: invidiousNode@.GetAuthorizeTokenLink()
|
||||
logged_in: authToken <> invalid
|
||||
logged_in_instance: authToken <> invalid ? authToken.instance : invalid
|
||||
logged_in_username: authToken <> invalid ? authToken.username : invalid
|
||||
}
|
||||
end if
|
||||
|
||||
if ArrayUtils.IndexOfString(keys, "preferences") <> -1
|
||||
state["preferences"] = preferencesNode@.GetUserPreferences()
|
||||
end if
|
||||
|
||||
response.Json(state)
|
||||
return true
|
||||
end function)
|
||||
response.Json(state)
|
||||
return true
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
@@ -6,37 +6,39 @@ namespace Http
|
||||
|
||||
class ViewRouter extends HttpRouter
|
||||
|
||||
function new()
|
||||
function new(server as object)
|
||||
super()
|
||||
|
||||
m.Get("/api/view/open", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
appController = context.server.task.appController
|
||||
m.appController = server.task.appController
|
||||
end function
|
||||
|
||||
playlistId = request.query.playlistId
|
||||
authorId = request.query.authorId
|
||||
@get("/api/view/open")
|
||||
function OpenView(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
if not StringUtils.IsNullOrEmpty(playlistId)
|
||||
contentNode = InvidiousContent.ToPlaylistContentNode(invalid, { playlistId: playlistId }, invalid)
|
||||
PlaylistUtils.Open(contentNode, appController)
|
||||
if VideoUtils.IsVideoPlayerOpen() and VideoUtils.IsVideoPlayerFullScreen()
|
||||
VideoUtils.ToggleVideoPictureInPicture()
|
||||
end if
|
||||
response.Default(204, "OK")
|
||||
else if not StringUtils.IsNullOrEmpty(authorId)
|
||||
contentNode = InvidiousContent.ToChannelContentNode(invalid, { authorId: authorId }, invalid)
|
||||
ChannelUtils.Open(contentNode, appController)
|
||||
if VideoUtils.IsVideoPlayerOpen() and VideoUtils.IsVideoPlayerFullScreen()
|
||||
VideoUtils.ToggleVideoPictureInPicture()
|
||||
end if
|
||||
response.Default(204, "OK")
|
||||
else
|
||||
response.Default(400, "Invalid request")
|
||||
playlistId = request.query.playlistId
|
||||
authorId = request.query.authorId
|
||||
|
||||
if not StringUtils.IsNullOrEmpty(playlistId)
|
||||
contentNode = InvidiousContent.ToPlaylistContentNode(invalid, { playlistId: playlistId }, invalid)
|
||||
PlaylistUtils.Open(contentNode, m.appController)
|
||||
if VideoUtils.IsVideoPlayerOpen() and VideoUtils.IsVideoPlayerFullScreen()
|
||||
VideoUtils.ToggleVideoPictureInPicture()
|
||||
end if
|
||||
response.Default(204, "OK")
|
||||
else if not StringUtils.IsNullOrEmpty(authorId)
|
||||
contentNode = InvidiousContent.ToChannelContentNode(invalid, { authorId: authorId }, invalid)
|
||||
ChannelUtils.Open(contentNode, m.appController)
|
||||
if VideoUtils.IsVideoPlayerOpen() and VideoUtils.IsVideoPlayerFullScreen()
|
||||
VideoUtils.ToggleVideoPictureInPicture()
|
||||
end if
|
||||
response.Default(204, "OK")
|
||||
else
|
||||
response.Default(400, "Invalid request")
|
||||
end if
|
||||
|
||||
return true
|
||||
end function)
|
||||
return true
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
@@ -2,6 +2,7 @@ import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
|
||||
import "pkg:/components/Web/PlayletWebServer/Middleware/BookmarksRouter.bs"
|
||||
import "pkg:/components/Web/PlayletWebServer/Middleware/DashRouter.bs"
|
||||
import "pkg:/components/Web/PlayletWebServer/Middleware/HomeLayoutRouter.bs"
|
||||
import "pkg:/components/Web/PlayletWebServer/Middleware/HomeRouter.bs"
|
||||
import "pkg:/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs"
|
||||
import "pkg:/components/Web/PlayletWebServer/Middleware/PlayletLibUrlsRouter.bs"
|
||||
import "pkg:/components/Web/PlayletWebServer/Middleware/PlayQueueRouter.bs"
|
||||
@@ -29,28 +30,21 @@ function GetServerAddress(_unused as dynamic) as dynamic
|
||||
end function
|
||||
|
||||
function SetupRoutes(server as object)
|
||||
homeRouter = new Http.HttpRouter()
|
||||
homeRouter.Get("/", function(context as object) as boolean
|
||||
response = context.response
|
||||
response.Redirect("/index.html")
|
||||
return true
|
||||
end function)
|
||||
|
||||
server.UseRouter(new Http.CorsMiddleware())
|
||||
if server.settings.WebSocketsEnabled
|
||||
server.UseRouter(new Http.WebSocketMiddleware())
|
||||
end if
|
||||
server.UseRouter(homeRouter)
|
||||
server.UseRouter(new Http.StateApiRouter())
|
||||
server.UseRouter(new Http.DashRouter())
|
||||
server.UseRouter(new Http.PreferencesRouter())
|
||||
server.UseRouter(new Http.InvidiousRouter())
|
||||
server.UseRouter(new Http.PlayQueueRouter())
|
||||
server.UseRouter(new Http.BookmarksRouter())
|
||||
server.UseRouter(new Http.HomeLayoutRouter())
|
||||
server.UseRouter(new Http.ViewRouter())
|
||||
server.UseRouter(new Http.SearchHistoryRouter())
|
||||
server.UseRouter(new Http.PlayletLibUrlsRouter())
|
||||
server.UseRouter(new Http.HomeRouter())
|
||||
server.UseRouter(new Http.StateApiRouter(server))
|
||||
server.UseRouter(new Http.DashRouter(server))
|
||||
server.UseRouter(new Http.PreferencesRouter(server))
|
||||
server.UseRouter(new Http.InvidiousRouter(server))
|
||||
server.UseRouter(new Http.PlayQueueRouter(server))
|
||||
server.UseRouter(new Http.BookmarksRouter(server))
|
||||
server.UseRouter(new Http.HomeLayoutRouter(server))
|
||||
server.UseRouter(new Http.ViewRouter(server))
|
||||
server.UseRouter(new Http.SearchHistoryRouter(server))
|
||||
server.UseRouter(new Http.PlayletLibUrlsRouter(server))
|
||||
|
||||
etags = new Http.EtagUtils()
|
||||
server.UseRouter(new Http.HttpStaticFilesRouter("/", "libpkg:/www", etags, { staticFiles: true }))
|
||||
|
||||
@@ -2,48 +2,36 @@ namespace Http
|
||||
|
||||
class HttpRouter
|
||||
|
||||
' [{
|
||||
' method: "GET"
|
||||
' path: "/example"
|
||||
' router: router as HttpRouter
|
||||
' func: func as string
|
||||
' }]
|
||||
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
|
||||
try
|
||||
if route.router[route.func]({
|
||||
request: request
|
||||
response: response
|
||||
connection: connection
|
||||
server: response.server
|
||||
}) = true
|
||||
return true
|
||||
end if
|
||||
catch error
|
||||
formattedError = ErrorUtils.Format(error)
|
||||
LogError(formattedError)
|
||||
response.Default(500, formattedError)
|
||||
return true
|
||||
end if
|
||||
end try
|
||||
end if
|
||||
end for
|
||||
return false
|
||||
|
||||
@@ -11,24 +11,24 @@ namespace Http
|
||||
m.origin = origin
|
||||
m.headers = headers
|
||||
m.methods = methods
|
||||
|
||||
m.All("*", function(context as object) as boolean
|
||||
router = context.router
|
||||
request = context.request
|
||||
response = context.response
|
||||
response.headers["Access-Control-Allow-Origin"] = router.origin
|
||||
response.headers["Access-Control-Allow-Headers"] = router.headers
|
||||
response.headers["Access-Control-Allow-Methods"] = router.methods
|
||||
|
||||
if request.method = "OPTIONS"
|
||||
response.header_only = true
|
||||
response.http_code = 200
|
||||
return true
|
||||
end if
|
||||
return false
|
||||
end function)
|
||||
end function
|
||||
|
||||
@all("*")
|
||||
function AddAccessControlHeaders(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
response.headers["Access-Control-Allow-Origin"] = m.origin
|
||||
response.headers["Access-Control-Allow-Headers"] = m.headers
|
||||
response.headers["Access-Control-Allow-Methods"] = m.methods
|
||||
|
||||
if request.method = "OPTIONS"
|
||||
response.header_only = true
|
||||
response.http_code = 200
|
||||
return true
|
||||
end if
|
||||
return false
|
||||
end function
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -11,21 +11,21 @@ namespace Http
|
||||
super()
|
||||
|
||||
m.etags = etags
|
||||
end function
|
||||
|
||||
m.Get("*", function(context as object) as boolean
|
||||
router = context.router
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
if response.http_code <> 200
|
||||
return false
|
||||
end if
|
||||
|
||||
router.etags.AddEtagFromBody(request, response)
|
||||
router.etags.ClearContentIfNoneMatch(request, response)
|
||||
@get("*")
|
||||
function HandleEtag(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
if response.http_code <> 200
|
||||
return false
|
||||
end function)
|
||||
end if
|
||||
|
||||
m.etags.AddEtagFromBody(request, response)
|
||||
m.etags.ClearContentIfNoneMatch(request, response)
|
||||
|
||||
return false
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
@@ -4,24 +4,24 @@ namespace Http
|
||||
|
||||
function new()
|
||||
super()
|
||||
|
||||
m.All("*", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
method = request.method
|
||||
uri = request.uri
|
||||
|
||||
if method = ""
|
||||
response.Default(400, "You sent a request that the server couldn't understand.")
|
||||
else
|
||||
response.Default(404, `Cannot ${method} ${uri}`)
|
||||
end if
|
||||
|
||||
return true
|
||||
end function)
|
||||
end function
|
||||
|
||||
@all("*")
|
||||
function HandleDefault(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
|
||||
method = request.method
|
||||
uri = request.uri
|
||||
|
||||
if method = ""
|
||||
response.Default(400, "You sent a request that the server couldn't understand.")
|
||||
else
|
||||
response.Default(404, `Cannot ${method} ${uri}`)
|
||||
end if
|
||||
|
||||
return true
|
||||
end function
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -30,98 +30,98 @@ namespace Http
|
||||
m.fsCheck = ValidBool(options.fsCheck)
|
||||
' staticFiles: if true, Etag tags will be cached to skip reading the file entirely.
|
||||
m.staticFiles = ValidBool(options.staticFiles)
|
||||
|
||||
m.Get("*", function(context as object) as boolean
|
||||
router = context.router
|
||||
request = context.request
|
||||
response = context.response
|
||||
server = context.server
|
||||
|
||||
if not request.route.StartsWith(router.route)
|
||||
return false
|
||||
end if
|
||||
|
||||
path_in_route = request.route.Mid(router.route.Len())
|
||||
|
||||
decoded_path = path_in_route.DecodeUri()
|
||||
full_path = StringUtils.PathJoin(router.root, decoded_path)
|
||||
|
||||
if router.staticFiles
|
||||
' Although we have an Etag middleware, having a check here allows us to
|
||||
' skip reading the file entirely if the Etag matches.
|
||||
if router.etags.AddFileEtagFromCache(request, response, full_path)
|
||||
if router.etags.ClearContentIfNoneMatch(request, response)
|
||||
return true
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
|
||||
if not router.fsCheck
|
||||
' libpkg:/ does not work with roFilesystem...
|
||||
buffer = createObject("roByteArray")
|
||||
if buffer.ReadFile(full_path) and buffer.count() > 0
|
||||
mimetype = server.utils.MimeType(decoded_path)
|
||||
response.SetBodyDataBuffer(buffer)
|
||||
response.ContentType(mimetype)
|
||||
response.http_code = 200
|
||||
|
||||
if router.staticFiles
|
||||
router.etags.AddEtagFromBody(request, response, full_path)
|
||||
end if
|
||||
return true
|
||||
end if
|
||||
end if
|
||||
|
||||
path = CreateObject("roPath", full_path)
|
||||
fs = CreateObject("roFilesystem")
|
||||
|
||||
if not path.isValid()
|
||||
' Skip, let next middleware handle it
|
||||
return false
|
||||
else if not fs.exists(path)
|
||||
' Skip, let next middleware handle it
|
||||
return false
|
||||
end if
|
||||
|
||||
stat = fs.stat(path)
|
||||
if stat = invalid
|
||||
response.Default(500, "fstat() failed.")
|
||||
return true
|
||||
end if
|
||||
|
||||
if stat.type = "directory"
|
||||
if not router.showDirectories
|
||||
response.Default(403, "Forbidden")
|
||||
return true
|
||||
end if
|
||||
response.ContentType("text/html")
|
||||
router.GenerateDirectoryListing(path, router, request, response)
|
||||
if router.staticFiles
|
||||
router.etags.AddEtagFromBody(request, response, full_path)
|
||||
end if
|
||||
return true
|
||||
else if stat.type = "file"
|
||||
mimetype = server.utils.MimeType(decoded_path)
|
||||
response.ContentType(mimetype)
|
||||
response.SetBodyDataFile(path)
|
||||
response.http_code = 200
|
||||
LogInfo("uri:", request.uri, "target:", path, "content-type:", mimetype, "content-length", stat.size)
|
||||
if router.staticFiles
|
||||
router.etags.AddEtagFromBody(request, response, full_path)
|
||||
end if
|
||||
return true
|
||||
else
|
||||
response.Default(403, "Not a regular file.")
|
||||
return true
|
||||
end if
|
||||
end function)
|
||||
end function
|
||||
|
||||
function GenerateDirectoryListing(path as object, router as object, request as HttpRequest, response as HttpResponse) as boolean
|
||||
@get("*")
|
||||
function GetFileOrFolder(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
server = context.server
|
||||
|
||||
if not request.route.StartsWith(m.route)
|
||||
return false
|
||||
end if
|
||||
|
||||
path_in_route = request.route.Mid(m.route.Len())
|
||||
|
||||
decoded_path = path_in_route.DecodeUri()
|
||||
full_path = StringUtils.PathJoin(m.root, decoded_path)
|
||||
|
||||
if m.staticFiles
|
||||
' Although we have an Etag middleware, having a check here allows us to
|
||||
' skip reading the file entirely if the Etag matches.
|
||||
if m.etags.AddFileEtagFromCache(request, response, full_path)
|
||||
if m.etags.ClearContentIfNoneMatch(request, response)
|
||||
return true
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
|
||||
if not m.fsCheck
|
||||
' libpkg:/ does not work with roFilesystem...
|
||||
buffer = createObject("roByteArray")
|
||||
if buffer.ReadFile(full_path) and buffer.count() > 0
|
||||
mimetype = server.utils.MimeType(decoded_path)
|
||||
response.SetBodyDataBuffer(buffer)
|
||||
response.ContentType(mimetype)
|
||||
response.http_code = 200
|
||||
|
||||
if m.staticFiles
|
||||
m.etags.AddEtagFromBody(request, response, full_path)
|
||||
end if
|
||||
return true
|
||||
end if
|
||||
end if
|
||||
|
||||
path = CreateObject("roPath", full_path)
|
||||
fs = CreateObject("roFilesystem")
|
||||
|
||||
if not path.isValid()
|
||||
' Skip, let next middleware handle it
|
||||
return false
|
||||
else if not fs.exists(path)
|
||||
' Skip, let next middleware handle it
|
||||
return false
|
||||
end if
|
||||
|
||||
stat = fs.stat(path)
|
||||
if stat = invalid
|
||||
response.Default(500, "fstat() failed.")
|
||||
return true
|
||||
end if
|
||||
|
||||
if stat.type = "directory"
|
||||
if not m.showDirectories
|
||||
response.Default(403, "Forbidden")
|
||||
return true
|
||||
end if
|
||||
response.ContentType("text/html")
|
||||
m.GenerateDirectoryListing(path, request, response)
|
||||
if m.staticFiles
|
||||
m.etags.AddEtagFromBody(request, response, full_path)
|
||||
end if
|
||||
return true
|
||||
else if stat.type = "file"
|
||||
mimetype = server.utils.MimeType(decoded_path)
|
||||
response.ContentType(mimetype)
|
||||
response.SetBodyDataFile(path)
|
||||
response.http_code = 200
|
||||
LogInfo("uri:", request.uri, "target:", path, "content-type:", mimetype, "content-length", stat.size)
|
||||
if m.staticFiles
|
||||
m.etags.AddEtagFromBody(request, response, full_path)
|
||||
end if
|
||||
return true
|
||||
else
|
||||
response.Default(403, "Not a regular file.")
|
||||
return true
|
||||
end if
|
||||
end function
|
||||
|
||||
function GenerateDirectoryListing(path as object, request as HttpRequest, response as HttpResponse) as boolean
|
||||
fs = CreateObject("roFilesystem")
|
||||
dirList = fs.GetDirectoryListing(path)
|
||||
if dirList = invalid
|
||||
response.default(500, "Couldn't list directory")
|
||||
response.Default(500, "Couldn't list directory")
|
||||
return false
|
||||
end if
|
||||
|
||||
@@ -151,7 +151,7 @@ namespace Http
|
||||
uriDir = uriDir + "/"
|
||||
end if
|
||||
|
||||
routeDir = router.route
|
||||
routeDir = m.route
|
||||
if routeDir.len() > 0 and routeDir.right(1) <> "/"
|
||||
routeDir = routeDir + "/"
|
||||
end if
|
||||
@@ -162,7 +162,7 @@ namespace Http
|
||||
end if
|
||||
|
||||
for each item in dirList
|
||||
if router.showHidden or item.left(1) <> "."
|
||||
if m.showHidden or item.left(1) <> "."
|
||||
indicator = invalid
|
||||
stat = fs.stat(dir + item)
|
||||
if stat <> invalid
|
||||
|
||||
@@ -8,42 +8,43 @@ namespace Http
|
||||
|
||||
function new()
|
||||
super()
|
||||
end function
|
||||
|
||||
m.Get("*", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
connection = context.connection
|
||||
@get("*")
|
||||
function HandleWebSocketHeaders(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
connection = context.connection
|
||||
|
||||
if LCase(ValidString(request.headers["Connection"])) <> "upgrade"
|
||||
return false
|
||||
end if
|
||||
if LCase(ValidString(request.headers["Connection"])) <> "upgrade"
|
||||
return false
|
||||
end if
|
||||
|
||||
if LCase(ValidString(request.headers["Upgrade"])) <> "websocket"
|
||||
return false
|
||||
end if
|
||||
if LCase(ValidString(request.headers["Upgrade"])) <> "websocket"
|
||||
return false
|
||||
end if
|
||||
|
||||
webSocketKey = request.headers["Sec-WebSocket-Key"]
|
||||
if webSocketKey = invalid
|
||||
return false
|
||||
end if
|
||||
webSocketKey = request.headers["Sec-WebSocket-Key"]
|
||||
if webSocketKey = invalid
|
||||
return false
|
||||
end if
|
||||
|
||||
sha1Hash = CryptoUtils.GetSha1(webSocketKey + Http.WEB_SOCKET_MAGIC_STRING)
|
||||
buffer = CreateObject("roByteArray")
|
||||
buffer.FromHexString(sha1Hash)
|
||||
webSocketAccept = StringUtils.ToBase64(buffer.ToAsciiString())
|
||||
sha1Hash = CryptoUtils.GetSha1(webSocketKey + Http.WEB_SOCKET_MAGIC_STRING)
|
||||
buffer = CreateObject("roByteArray")
|
||||
buffer.FromHexString(sha1Hash)
|
||||
webSocketAccept = StringUtils.ToBase64(buffer.ToAsciiString())
|
||||
|
||||
response.http_code = 101
|
||||
response.headers["Connection"] = "Upgrade"
|
||||
response.headers["Upgrade"] = "websocket"
|
||||
response.headers["Sec-WebSocket-Accept"] = webSocketAccept
|
||||
response.header_only = true
|
||||
response.http_code = 101
|
||||
response.headers["Connection"] = "Upgrade"
|
||||
response.headers["Upgrade"] = "websocket"
|
||||
response.headers["Sec-WebSocket-Accept"] = webSocketAccept
|
||||
response.header_only = true
|
||||
|
||||
' We want this connection to be upgraded to a WebSocket connection
|
||||
' The connection will stop being handled by the HTTP server and will be handled by the WebSocket server
|
||||
connection.ws_upgrade = true
|
||||
' We want this connection to be upgraded to a WebSocket connection
|
||||
' The connection will stop being handled by the HTTP server and will be handled by the WebSocket server
|
||||
connection.ws_upgrade = true
|
||||
|
||||
return true
|
||||
end function)
|
||||
return true
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
@@ -5,7 +5,7 @@ namespace Tests
|
||||
class ApplicationInfoTests extends Rooibos.BaseTestSuite
|
||||
|
||||
protected override function setup()
|
||||
m.ipAddressRegex = CreateObject("roRegex", "\d+\.\d+\.\d+.\d+", "")
|
||||
m.ipAddressRegex = /\d+\.\d+\.\d+.\d+/
|
||||
end function
|
||||
|
||||
protected override function beforeEach()
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
// This plugin handles router annotations (@get, @post, etc) and register
|
||||
// associated functions with the router.
|
||||
|
||||
import {
|
||||
BeforeFileTranspileEvent,
|
||||
BscFile,
|
||||
ClassStatement,
|
||||
CompilerPlugin,
|
||||
FunctionExpression,
|
||||
FunctionStatement,
|
||||
MethodStatement,
|
||||
OnFileValidateEvent,
|
||||
TokenKind,
|
||||
WalkMode,
|
||||
createVisitor,
|
||||
isBrsFile
|
||||
} from "brighterscript";
|
||||
import { RawCodeStatement } from "./Classes/RawCodeStatement";
|
||||
|
||||
const annotationNames = ['all', 'get', 'post', 'put', 'delete', 'patch', 'head', 'options'];
|
||||
const httpRouterBaseClass = 'HttpRouter';
|
||||
|
||||
export class WebServerPlugin implements CompilerPlugin {
|
||||
public name = 'WebServerPlugin';
|
||||
|
||||
onFileValidate(event: OnFileValidateEvent<BscFile>) {
|
||||
if (!isBrsFile(event.file)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure each class that inherits from HttpRouter has a constructor
|
||||
event.file.ast.walk(createVisitor({
|
||||
ClassStatement: (classStmt) => {
|
||||
if (!classStmt.parentClassName) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parentClass = classStmt.parentClassName.expression.name.text;
|
||||
if (parentClass !== httpRouterBaseClass) {
|
||||
return;
|
||||
}
|
||||
|
||||
const classConstructor = this.getClassConstructor(classStmt);
|
||||
if (!classConstructor) {
|
||||
event.file.addDiagnostics([{
|
||||
file: event.file,
|
||||
range: classStmt.name.range,
|
||||
message: `Class ${classStmt.name.text} extends ${httpRouterBaseClass} and must have a constructor`,
|
||||
severity: 1,
|
||||
code: 'HTTP_ROUTER_NO_CONSTRUCTOR',
|
||||
}]);
|
||||
}
|
||||
},
|
||||
}), {
|
||||
walkMode: WalkMode.visitStatementsRecursive
|
||||
});
|
||||
}
|
||||
|
||||
beforeFileTranspile(event: BeforeFileTranspileEvent<BscFile>) {
|
||||
if (!isBrsFile(event.file)) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.file.ast.walk(createVisitor({
|
||||
FunctionExpression: (func) => {
|
||||
if (!this.isHttpRouterFunction(func)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const functionStatement = func.functionStatement;
|
||||
if (!functionStatement) {
|
||||
return;
|
||||
}
|
||||
|
||||
const routeInfo = this.getRouteInfo(functionStatement);
|
||||
if (!routeInfo) {
|
||||
return;
|
||||
}
|
||||
|
||||
const classStmt = this.getClass(func);
|
||||
if (!classStmt) {
|
||||
return;
|
||||
}
|
||||
const classConstructor = this.getClassConstructor(classStmt) as MethodStatement;
|
||||
|
||||
const method = routeInfo.method === 'ALL' ? '*' : routeInfo.method;
|
||||
const stmt = new RawCodeStatement(`m.routes.push({ method: "${method}", path: "${routeInfo.route}", router: m, func: "${func.functionStatement?.name.text}" })`)
|
||||
event.editor.arrayPush(classConstructor.func.body.statements, stmt);
|
||||
},
|
||||
}), {
|
||||
walkMode: WalkMode.visitExpressionsRecursive
|
||||
});
|
||||
}
|
||||
|
||||
isHttpRouterFunction(func: FunctionExpression) {
|
||||
const classStmt = this.getClass(func);
|
||||
if (!classStmt || !classStmt.parentClassName) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parentClass = classStmt.parentClassName.expression.name.text;
|
||||
return parentClass === httpRouterBaseClass;
|
||||
}
|
||||
|
||||
getRouteInfo(functionStatement: FunctionStatement | undefined) {
|
||||
const annotations = functionStatement?.annotations
|
||||
if (!annotations || annotations.length === 0) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
for (let index = 0; index < annotations.length; index++) {
|
||||
const annotation = annotations[index];
|
||||
if (annotationNames.includes(annotation.name)) {
|
||||
const args = annotation.getArguments()
|
||||
if (args.length !== 1) {
|
||||
throw new Error(`Expected 1 argument for annotation ${annotation.name}`)
|
||||
}
|
||||
|
||||
if (typeof args[0] !== 'string') {
|
||||
throw new Error(`Expected string argument for annotation ${annotation.name}`)
|
||||
}
|
||||
|
||||
return {
|
||||
method: annotation.name.toUpperCase(),
|
||||
route: args[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getClass(func: FunctionExpression) {
|
||||
const functionStatement = func.functionStatement;
|
||||
if (!functionStatement) {
|
||||
return;
|
||||
}
|
||||
|
||||
return functionStatement.parent as ClassStatement;
|
||||
}
|
||||
|
||||
getClassConstructor(classStmt: ClassStatement) {
|
||||
return classStmt.body.find((stmt) => {
|
||||
const methodStmt = stmt as MethodStatement;
|
||||
// @ts-ignore
|
||||
if (methodStmt.name?.kind === TokenKind.New) {
|
||||
return stmt;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default () => {
|
||||
return new WebServerPlugin();
|
||||
};
|
||||
Reference in new issue
Block a user