Remove asynctask code (#666)
* Remove asynctask code * add job test example * Fix testing * Fix a couple of imports
This commit is contained in:
1 parent
9ef741292e
commit
82dea9af37
36 files changed
+325
-443
No files matched your search
@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
### Removed
|
||||
|
||||
- "Use dev video player" option from the settings
|
||||
- `@asynctask` in favor of newer job system
|
||||
|
||||
## [0.40.7] - 2025-06-21
|
||||
|
||||
|
||||
@@ -82,7 +82,6 @@
|
||||
"lintConfig": "./config/bslint.jsonc",
|
||||
"plugins": [
|
||||
"@rokucommunity/bslint",
|
||||
"../tools/bs-plugins/asynctask-plugin.ts",
|
||||
"../tools/bs-plugins/jobsystem-plugin.ts",
|
||||
"../tools/bs-plugins/manifest-edit-plugin.ts",
|
||||
"../tools/bs-plugins/component-includes-plugin.ts",
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
"plugins": [
|
||||
"@rokucommunity/bslint",
|
||||
"rooibos-roku",
|
||||
"../tools/bs-plugins/asynctask-plugin.ts",
|
||||
"../tools/bs-plugins/jobsystem-plugin.ts",
|
||||
"../tools/bs-plugins/manifest-edit-plugin.ts",
|
||||
"../tools/bs-plugins/component-includes-plugin.ts",
|
||||
|
||||
+43
-53
@@ -6,7 +6,6 @@
|
||||
- [Includes](#includes)
|
||||
- [@oninit](#oninit)
|
||||
- [Bindings](#bindings)
|
||||
- [Async Task Generator](#async-task-generator)
|
||||
- [Job System Generator](#job-system-generator)
|
||||
- [Tracking transpilied files](#tracking-transpilied-files)
|
||||
- [Logger](#logger)
|
||||
@@ -422,62 +421,53 @@ myNode@.BindNode()
|
||||
|
||||
calling `BindNode` will trigger all the binding steps just for this node. But it is expected that all its dependencies are already in the scene and can be found.
|
||||
|
||||
## Async Task Generator
|
||||
|
||||
**[Source](/tools/bs-plugins/asynctask-plugin.ts)**
|
||||
|
||||
This plugin generates `Task` components a scripts that makes it simpler to call a function in a background thread, and get the result in a callback function.
|
||||
|
||||
### Why
|
||||
|
||||
To implement functionality that runs in background threads, [Task](https://developer.roku.com/en-ca/docs/references/scenegraph/control-nodes/task.md)s must be used.
|
||||
|
||||
Setting up a task involves lots of boilerplate: setting up the task in an xml file, defining inputs and outputs, code to listen for a task to finish, and so on.
|
||||
|
||||
Additionally, there's no standard way to do error handling, cancellation, and so on.
|
||||
|
||||
### How
|
||||
|
||||
Use a function with the attribute `@asynctask`.
|
||||
|
||||
In a separate file, define the task function:
|
||||
|
||||
```brighterscript
|
||||
@asynctask
|
||||
function MyBackgroundTask(input as object) as object
|
||||
myVar = input.myVar
|
||||
|
||||
value = DoWork(myVar)
|
||||
|
||||
return {
|
||||
value: value
|
||||
}
|
||||
end function
|
||||
```
|
||||
|
||||
And use the function like so
|
||||
|
||||
```brighterscript
|
||||
import "pkg:/source/AsyncTask/Tasks.bs"
|
||||
import "pkg:/source/AsyncTask/AsyncTask.bs"
|
||||
|
||||
AsyncTask.Start(Tasks.MyBackgroundTask, {myVar: "some input"}, function(output as object) as void
|
||||
if output.success
|
||||
print(output.result.value)
|
||||
end if
|
||||
end function)
|
||||
```
|
||||
|
||||
The rest will be taken care of by the plugin, which will generate an `xml` file containing the task component, and a script that handles calling the function.
|
||||
|
||||
Although very useful, this pattern might not be the best for long running tasks (like the Web Server) or other tasks that require task reuse. This is because `AsyncTask.Start` create a new instance of the task every time.
|
||||
|
||||
## Job System Generator
|
||||
|
||||
**[Source](/tools/bs-plugins/jobsystem-plugin.ts)**
|
||||
|
||||
This plugin is very similar to the `Async Task Generator` and aims to be a replacement for it.
|
||||
A work in progress for now.
|
||||
The Job System simplifies the creation of background jobs without the risk of creating too many threads.
|
||||
It manages a number of Tasks which are capable of executing jobs from a queue.
|
||||
|
||||
### Why
|
||||
|
||||
To implement functionality that runs in background threads, [Tasks](https://developer.roku.com/en-ca/docs/references/scenegraph/control-nodes/task.md) must be used.
|
||||
|
||||
Setting up a task involves lots of boilerplate: setting up the task in an xml file, defining inputs and outputs, code to listen for a task to finish, and so on.
|
||||
|
||||
Additionally, there's no standard way to do error handling and cancellation.
|
||||
|
||||
Another concern is managing too many threads across the application, and managing rendezvous(s).
|
||||
|
||||
### How
|
||||
|
||||
Define a function in its own file called `ExecuteJob` annotated with `@job("JobName")`:
|
||||
|
||||
```brighterscript
|
||||
@job("MyJob")
|
||||
function ExecuteJob() as void
|
||||
' input is an associative array set when the job is queued.
|
||||
input = JobGetInput()
|
||||
|
||||
value = DoWork(myVar)
|
||||
|
||||
JobSuccessData({result: value})
|
||||
end function
|
||||
```
|
||||
|
||||
by doing this, the generator will generate a component named "MyJob" and will inherit from "BaseJob".
|
||||
|
||||
The job can now queued for execution:
|
||||
|
||||
```brighterscript
|
||||
callback = JobSystem.CreateCallback()
|
||||
JobSystem.QueueJob(m.jobQueue, Jobs.MyJob, input, callback)
|
||||
```
|
||||
|
||||
And the job system will take care of queueing, scheduling, and scaling up the available tasks in order to execute jobs.
|
||||
The job system creates job nodes inside task threads, which reduces the amount of rendezvous necessary. Some rendezvous are still necessary, such as when a task node is signaling that it is ready to take on a new job, or when the job is returning results to render thread.
|
||||
The job system will auto scale up to a maximum number of tasks, in order to avoid `Too many threads` errors. Once the job system activity settles down, the job system will release task nodes that has been idle for a certain amount of time.
|
||||
|
||||
Although very useful, this pattern might not be the best for long running tasks (like the Web Server) and it is simpler to create dedicated tasks for those.
|
||||
|
||||
## Tracking transpilied files
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import "pkg:/source/utils/MessagePortUtils.bs"
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
|
||||
' Maximum number of JobTasks that can be created
|
||||
const MAX_JOB_TASK_COUNT = 20
|
||||
const MAX_JOB_TASK_COUNT = 25
|
||||
' Minimum number of JobTasks that will be kept alive
|
||||
const MIN_JOB_TASK_COUNT = 2
|
||||
' Time in milliseconds to wait before scaling down JobTasks
|
||||
@@ -45,6 +45,10 @@ function JobQueueTaskLoop() as void
|
||||
m.busyJobTasks[jobTaskId] = jobTaskObject
|
||||
MessagePortUtils.ObserveFieldScopedExSafe(jobTask, "ready", messagePort)
|
||||
jobTask.control = "run"
|
||||
else
|
||||
#if DEBUG
|
||||
LogWarn("Cannot create new JobTask. Idle:", m.idleJobTasks.Count(), ", Busy:", m.busyJobTasks.Count())
|
||||
#end if
|
||||
end if
|
||||
|
||||
exit while
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import "pkg:/source/utils/AssertUtils.bs"
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
|
||||
namespace JobRequest
|
||||
function Execute(request as object) as void
|
||||
#if DEBUG
|
||||
Assert.NotNullOrEmpty(request, "JobRequest.Execute: request cannot be null or empty")
|
||||
Assert.NotNullOrEmpty(request.jobName, "JobRequest.Execute: request cannot be null or empty")
|
||||
#end if
|
||||
|
||||
job = CreateObject("roSGNode", request.jobName)
|
||||
if job = invalid
|
||||
error = "Failed to create job node: " + request.jobName
|
||||
LogError(error)
|
||||
' Usually callback is fired by the job itself, but if it fails to create, we can call it here
|
||||
if request.input <> invalid and request.input._callback <> invalid
|
||||
request.input._callback.error = error
|
||||
request.input._callback.success = false
|
||||
request.input._callback.done = true
|
||||
end if
|
||||
return
|
||||
end if
|
||||
job.id = request.jobName + "-" + StringUtils.RandomId()
|
||||
|
||||
if request.input <> invalid
|
||||
job.input = request.input
|
||||
end if
|
||||
|
||||
#if DEBUG
|
||||
LogDebug("Executing job:", request.jobName)
|
||||
time = CreateObject("roTimespan")
|
||||
#end if
|
||||
|
||||
job@.Execute()
|
||||
|
||||
#if DEBUG
|
||||
LogDebug("Job executed:", request.jobName, "in", time.TotalMilliseconds(), "ms")
|
||||
#end if
|
||||
|
||||
job.input = invalid
|
||||
end function
|
||||
end namespace
|
||||
@@ -1,3 +1,4 @@
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
import "pkg:/source/utils/Types.bs"
|
||||
|
||||
namespace JobSystem
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import "pkg:/components/JobSystem/JobRequest.bs"
|
||||
import "pkg:/source/utils/Logging.bs"
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
|
||||
@@ -25,35 +26,9 @@ function JobTaskLoop() as void
|
||||
end if
|
||||
if field = "request"
|
||||
request = msg.getData()
|
||||
ExecuteJobRequest(request)
|
||||
JobRequest.Execute(request)
|
||||
m.top.ready = true
|
||||
end if
|
||||
end if
|
||||
end while
|
||||
end function
|
||||
|
||||
function ExecuteJobRequest(request as object) as void
|
||||
job = CreateObject("roSGNode", request.jobName)
|
||||
job.id = request.jobName + "-" + StringUtils.RandomId()
|
||||
if job = invalid
|
||||
LogError("Failed to create job node:", request.jobName)
|
||||
return
|
||||
end if
|
||||
|
||||
if request.input <> invalid
|
||||
job.input = request.input
|
||||
end if
|
||||
|
||||
#if DEBUG
|
||||
LogDebug("Executing job:", request.jobName)
|
||||
time = CreateObject("roTimespan")
|
||||
#end if
|
||||
|
||||
job@.Execute()
|
||||
|
||||
#if DEBUG
|
||||
LogDebug("Job executed:", request.jobName, "in", time.TotalMilliseconds(), "ms")
|
||||
#end if
|
||||
|
||||
job.input = invalid
|
||||
end function
|
||||
@@ -16,14 +16,16 @@ function Init()
|
||||
m.top.ObserveField("logLine", port)
|
||||
|
||||
scene = m.top.getScene()
|
||||
MessagePortUtils.ObserveFieldScopedExSafe(scene, "systemLogEvent", port)
|
||||
if scene.hasField("enableSystemLogType")
|
||||
scene.enableSystemLogType = "http.error"
|
||||
#if DEBUG
|
||||
scene.enableSystemLogType = "http.connect"
|
||||
scene.enableSystemLogType = "http.complete"
|
||||
scene.enableSystemLogType = "bandwidth.minute"
|
||||
#end if
|
||||
if scene.hasField("systemLogEvent")
|
||||
MessagePortUtils.ObserveFieldScopedExSafe(scene, "systemLogEvent", port)
|
||||
if scene.hasField("enableSystemLogType")
|
||||
scene.enableSystemLogType = "http.error"
|
||||
#if DEBUG
|
||||
scene.enableSystemLogType = "http.connect"
|
||||
scene.enableSystemLogType = "http.complete"
|
||||
scene.enableSystemLogType = "bandwidth.minute"
|
||||
#end if
|
||||
end if
|
||||
end if
|
||||
|
||||
m.port = port
|
||||
|
||||
@@ -3,8 +3,6 @@ import "pkg:/components/ContextMenu/ContextMenuUtils.bs"
|
||||
import "pkg:/components/Navigation/LongPress.bs"
|
||||
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
|
||||
import "pkg:/components/VideoFeed/FeedLoadState.bs"
|
||||
import "pkg:/source/AsyncTask/AsyncTask.bs"
|
||||
import "pkg:/source/AsyncTask/Tasks.bs"
|
||||
import "pkg:/source/utils/ErrorUtils.bs"
|
||||
import "pkg:/source/utils/FocusManagement.bs"
|
||||
import "pkg:/source/utils/Logging.bs"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import "pkg:/source/QrCode/QrImage.bs"
|
||||
import "pkg:/source/QrCode/QrMode.bs"
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
|
||||
@job("GenerateQrCodeJob")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import "pkg:/source/AsyncTask/AsyncTask.bs"
|
||||
import "pkg:/source/utils/Types.bs"
|
||||
|
||||
function Init()
|
||||
' TODO:P2 Add tooltip to each field with description of what it means
|
||||
|
||||
@@ -591,7 +591,11 @@ namespace Innertube
|
||||
if not IsString(videoId)
|
||||
videoId = ObjectUtils.Dig(nodeData, ["updatedMetadataEndpoint", "updatedMetadataEndpoint", "videoId"])
|
||||
if not IsString(videoId)
|
||||
LogWarn("Invalid video ID", `\n`, FormatJson(nodeData))
|
||||
#if DEBUG
|
||||
LogWarn("Invalid video ID in videoPrimaryInfoRenderer", `\n`, FormatJson(nodeData))
|
||||
#else
|
||||
LogWarn("Invalid video ID in videoPrimaryInfoRenderer")
|
||||
#end if
|
||||
return invalid
|
||||
end if
|
||||
end if
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import "pkg:/components/Services/Innertube/Constants.bs"
|
||||
import "pkg:/components/Services/Innertube/Context.bs"
|
||||
import "pkg:/components/Services/Innertube/NodesParser.bs"
|
||||
import "pkg:/source/services/HttpClient.bs"
|
||||
import "pkg:/source/utils/ObjectUtils.bs"
|
||||
import "pkg:/source/utils/TimeUtils.bs"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import "pkg:/components/Services/Innertube/Context.bs"
|
||||
import "pkg:/source/services/HttpClient.bs"
|
||||
import "pkg:/source/utils/Types.bs"
|
||||
|
||||
namespace Innertube
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import "InvidiousService.bs"
|
||||
import "pkg:/source/AsyncTask/AsyncTask.bs"
|
||||
import "pkg:/source/AsyncTask/Tasks.bs"
|
||||
|
||||
function Init()
|
||||
m.top.apiDefinitions = ParseJson(ReadAsciiFile("libpkg:/config/invidious_video_api.yaml"))
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import "pkg:/components/Dialog/DialogUtils.bs"
|
||||
import "pkg:/components/Services/Innertube/InnertubeService.bs"
|
||||
import "pkg:/components/VideoFeed/PaginationType.bs"
|
||||
import "pkg:/source/AsyncTask/AsyncTask.bs"
|
||||
import "pkg:/source/AsyncTask/Tasks.bs"
|
||||
import "pkg:/source/services/HttpClient.bs"
|
||||
import "pkg:/source/utils/CryptoUtils.bs"
|
||||
import "pkg:/source/utils/Logging.bs"
|
||||
|
||||
@@ -6,8 +6,6 @@ import "pkg:/components/Navigation/LongPress.bs"
|
||||
import "pkg:/components/PlaylistView/PlaylistUtils.bs"
|
||||
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
|
||||
import "pkg:/components/VideoFeed/FeedLoadState.bs"
|
||||
import "pkg:/source/AsyncTask/AsyncTask.bs"
|
||||
import "pkg:/source/AsyncTask/Tasks.bs"
|
||||
import "pkg:/source/utils/DisposableObserve.bs"
|
||||
import "pkg:/source/utils/ErrorUtils.bs"
|
||||
import "pkg:/source/utils/Logging.bs"
|
||||
|
||||
+19
-25
@@ -1,8 +1,10 @@
|
||||
import "pkg:/components/Services/Innertube/InnertubeService.bs"
|
||||
import "pkg:/components/Services/Invidious/InvidiousService.bs"
|
||||
|
||||
@asynctask
|
||||
function VideoContentTask(input as object) as object
|
||||
@job("VideoContentJob")
|
||||
function ExecuteJob() as void
|
||||
input = JobGetInput()
|
||||
|
||||
contentNode = input.content
|
||||
invidiousNode = input.invidious
|
||||
innertubeNode = input.innertube
|
||||
@@ -10,12 +12,14 @@ function VideoContentTask(input as object) as object
|
||||
loungeServiceNode = input.loungeService
|
||||
playletServerPort = input.playletServerPort
|
||||
|
||||
if m.top.cancel
|
||||
return invalid
|
||||
if JobIsCancelled()
|
||||
JobCancel()
|
||||
return
|
||||
end if
|
||||
|
||||
if StringUtils.IsNullOrEmpty(contentNode.videoId)
|
||||
throw "Can't load video information: videoId is missing"
|
||||
JobError("Can't load video information: videoId is missing")
|
||||
return
|
||||
end if
|
||||
|
||||
service = new Invidious.InvidiousService(invidiousNode)
|
||||
@@ -23,6 +27,7 @@ function VideoContentTask(input as object) as object
|
||||
|
||||
metadata = contentNode.metadata
|
||||
if not IsAssociativeArray(metadata)
|
||||
cancellation = CancellationUtils.CreateCancellation(JobGetCallbackNode(), "cancel", true)
|
||||
if backend = "playlet"
|
||||
visitorData = innertubeNode.visitorData
|
||||
if StringUtils.IsNullOrEmpty(visitorData)
|
||||
@@ -32,16 +37,14 @@ function VideoContentTask(input as object) as object
|
||||
message = wait(20000, messagePort)
|
||||
innertubeNode.unobserveFieldScoped("visitorData")
|
||||
if message = invalid
|
||||
return {
|
||||
success: false
|
||||
error: "Failed to get visitor data. Please try again later."
|
||||
}
|
||||
JobError("Failed to get visitor data. Please try again later.")
|
||||
return
|
||||
end if
|
||||
visitorData = message.getData()
|
||||
end if
|
||||
|
||||
metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, {
|
||||
"cancellation": m.top.cancellation
|
||||
"cancellation": cancellation
|
||||
"credentialTransferToken": loungeServiceNode.credentialTransferToken
|
||||
"visitorData": visitorData
|
||||
})
|
||||
@@ -51,14 +54,12 @@ function VideoContentTask(input as object) as object
|
||||
end if
|
||||
|
||||
if metadata = invalid
|
||||
return {
|
||||
success: false
|
||||
error: "Failed to get video metadata"
|
||||
}
|
||||
JobError("Failed to get video metadata")
|
||||
end if
|
||||
|
||||
if m.top.cancel
|
||||
return invalid
|
||||
if JobIsCancelled()
|
||||
JobCancel()
|
||||
return
|
||||
end if
|
||||
|
||||
contentNode.title = metadata.title
|
||||
@@ -68,11 +69,8 @@ function VideoContentTask(input as object) as object
|
||||
if metadata.error <> invalid
|
||||
' Adding metadata allows us to play next recommended video after displaying the error
|
||||
contentNode.addFields({ metadata: metadata })
|
||||
|
||||
return {
|
||||
success: false
|
||||
error: metadata.error
|
||||
}
|
||||
JobError(metadata.error)
|
||||
return
|
||||
end if
|
||||
|
||||
streamUrls = CreateStreamUrls(metadata, service, preferencesNode, backend, playletServerPort)
|
||||
@@ -95,10 +93,6 @@ function VideoContentTask(input as object) as object
|
||||
if metadata.liveNow = true
|
||||
contentNode.Live = true
|
||||
end if
|
||||
|
||||
return {
|
||||
success: true
|
||||
}
|
||||
end function
|
||||
|
||||
function CreateStreamUrls(metadata as object, service as Invidious.InvidiousService, preferences as object, backend as string, playletServerPort as integer) as object
|
||||
@@ -1,14 +1,14 @@
|
||||
#const DEBUG_LOG_VIDEO_QUALITY = false
|
||||
|
||||
import "pkg:/components/Dialog/DialogUtils.bs"
|
||||
import "pkg:/components/JobSystem/Jobs.bs"
|
||||
import "pkg:/components/JobSystem/JobSystem.bs"
|
||||
import "pkg:/components/Services/Innertube/Constants.bs"
|
||||
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
|
||||
import "pkg:/components/VideoPlayer/Lounge.bs"
|
||||
import "pkg:/components/VideoPlayer/SponsorBlock.bs"
|
||||
import "pkg:/components/VideoPlayer/VideoPlayerStyle.bs"
|
||||
import "pkg:/components/VideoQueue/VideoQueueUtils.bs"
|
||||
import "pkg:/source/AsyncTask/AsyncTask.bs"
|
||||
import "pkg:/source/AsyncTask/Tasks.bs"
|
||||
import "pkg:/source/utils/ErrorUtils.bs"
|
||||
import "pkg:/source/utils/Logging.bs"
|
||||
import "pkg:/source/utils/RemoteKeys.bs"
|
||||
@@ -46,7 +46,7 @@ function Init()
|
||||
' It is set to true because stopping synchronously causes timeout and crash
|
||||
' Usually we would need to wait for the video state to move to "stopping" then to "stopped"
|
||||
' before considering the video node closed, and creating a new one.
|
||||
' However, since we have a task to load video details, there should be enough time for the
|
||||
' However, since we have a job to load video details, there should be enough time for the
|
||||
' video node to close before we create a new one.
|
||||
if m.top.hasField("asyncStopSemantics")
|
||||
m.top.asyncStopSemantics = true
|
||||
@@ -144,60 +144,63 @@ function PlayWithContent(contentNode as object)
|
||||
videoContentNode.AddFields({ metadata: metadata })
|
||||
end if
|
||||
|
||||
StartVideoContentTask(videoContentNode)
|
||||
StartVideoContentJob(videoContentNode)
|
||||
Lounge.SendNowPlayingLoading(contentNode.videoId)
|
||||
end function
|
||||
|
||||
function StartVideoContentTask(videoContentNode as object)
|
||||
if m.videoContentTask <> invalid
|
||||
m.videoContentTask.cancel = true
|
||||
function StartVideoContentJob(videoContentNode as object)
|
||||
if m.videoContentJob <> invalid
|
||||
m.videoContentJob.cancel = true
|
||||
end if
|
||||
|
||||
m.top.content = videoContentNode
|
||||
|
||||
m.videoContentTask = AsyncTask.Start(Tasks.VideoContentTask, {
|
||||
|
||||
input = {
|
||||
content: videoContentNode
|
||||
invidious: m.top.invidious
|
||||
innertube: m.top.innertube
|
||||
preferences: m.top.preferences
|
||||
loungeService: m.top.loungeService
|
||||
playletServerPort: m.top.webServer.port
|
||||
}, OnVideoContentTaskResults)
|
||||
}
|
||||
|
||||
m.videoContentJob = JobSystem.CreateCallback(OnVideoContentJobDone)
|
||||
JobSystem.QueueJob(m.jobQueue, Jobs.VideoContentJob, input, m.videoContentJob)
|
||||
end function
|
||||
|
||||
function OnVideoContentTaskResults(output as object) as void
|
||||
m.videoContentTask = invalid
|
||||
if output.cancelled or m.onCloseCalled = true
|
||||
function OnVideoContentJobDone(event as object) as void
|
||||
JobSystem.UnobserveCallback(event.getRoSGNode())
|
||||
m.videoContentJob = invalid
|
||||
|
||||
info = event.getInfo()
|
||||
if info.cancel or m.onCloseCalled = true
|
||||
return
|
||||
end if
|
||||
|
||||
if not output.success or not output.result.success
|
||||
' output.error for unhandled exception
|
||||
error = output.error
|
||||
if error = invalid
|
||||
' output.result.error for network errors
|
||||
error = output.result.error
|
||||
content = m.top.content
|
||||
|
||||
if not info.success
|
||||
videoId = ""
|
||||
if content <> invalid
|
||||
videoId = content.videoId
|
||||
end if
|
||||
error = ErrorUtils.Format(error)
|
||||
LogError(error)
|
||||
videoId = `${output.task.input.content.videoId}`
|
||||
|
||||
title = Tr(Locale.VideoPlayer.VideoLoadError)
|
||||
message = Tr(Locale.VideoPlayer.VideoLoadErrorMessage).Replace("%1", videoId) + `\n${error}`
|
||||
message = Tr(Locale.VideoPlayer.VideoLoadErrorMessage).Replace("%1", videoId) + `\n${info.error}`
|
||||
buttons = [Tr(Locale.Buttons.PlayNextVideo), Tr(Locale.Buttons.Cancel)]
|
||||
|
||||
dialog = DialogUtils.ShowTimedDialogButtons(message, title, buttons, 0, 10, true)
|
||||
if dialog <> invalid
|
||||
dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentTaskErrorDialogResponse))
|
||||
dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentJobErrorDialogResponse))
|
||||
else
|
||||
OnVideoContentTaskErrorDialogResponse(invalid)
|
||||
OnVideoContentJobErrorDialogResponse(invalid)
|
||||
end if
|
||||
|
||||
Lounge.SendOnStateChange()
|
||||
return
|
||||
end if
|
||||
|
||||
content = m.top.content
|
||||
SponsorBlock.FetchSponsorBlock(content.metadata)
|
||||
|
||||
SeekToInitialPosition(content)
|
||||
@@ -302,7 +305,7 @@ function OnPreviousPlayerState(event as object) as void
|
||||
end if
|
||||
end function
|
||||
|
||||
function OnVideoContentTaskErrorDialogResponse(event as object)
|
||||
function OnVideoContentJobErrorDialogResponse(event as object)
|
||||
shouldPlayNext = false
|
||||
if event <> invalid
|
||||
dialog = event.getRoSGNode()
|
||||
@@ -380,9 +383,9 @@ function OnClose()
|
||||
m.markVideoWatchedJob.cancel = true
|
||||
m.markVideoWatchedJob = invalid
|
||||
end if
|
||||
if m.videoContentTask <> invalid
|
||||
m.videoContentTask.cancel = true
|
||||
m.videoContentTask = invalid
|
||||
if m.videoContentJob <> invalid
|
||||
m.videoContentJob.cancel = true
|
||||
m.videoContentJob = invalid
|
||||
end if
|
||||
if m.sponsorBlockSegmentsJob <> invalid
|
||||
m.sponsorBlockSegmentsJob.cancel = true
|
||||
@@ -495,9 +498,9 @@ function OnVideoPlayerStateChange() as void
|
||||
|
||||
dialog = DialogUtils.ShowTimedDialogButtons(messageLines, title, buttons, 0, 10, true)
|
||||
if dialog <> invalid
|
||||
dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentTaskErrorDialogResponse))
|
||||
dialog.observeFieldScoped("wasClosed", FuncName(OnVideoContentJobErrorDialogResponse))
|
||||
else
|
||||
OnVideoContentTaskErrorDialogResponse(invalid)
|
||||
OnVideoContentJobErrorDialogResponse(invalid)
|
||||
end if
|
||||
m.ignoreNextFinishedState = true
|
||||
end if
|
||||
|
||||
+14
-15
@@ -2,8 +2,10 @@ import "pkg:/components/Services/Innertube/InnertubeService.bs"
|
||||
import "pkg:/components/Services/Invidious/InvidiousService.bs"
|
||||
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
|
||||
|
||||
@asynctask
|
||||
function VideoContentTaskDev(input as object) as object
|
||||
@job("VideoContentDevJob")
|
||||
function ExecuteJob() as void
|
||||
input = JobGetInput()
|
||||
|
||||
titleLabel = input.titleLabel
|
||||
secondaryTitleLabel = input.secondaryTitleLabel
|
||||
backgroundPoster = input.backgroundPoster
|
||||
@@ -17,7 +19,8 @@ function VideoContentTaskDev(input as object) as object
|
||||
videoId = contentNode.videoId
|
||||
|
||||
if StringUtils.IsNullOrEmpty(videoId)
|
||||
throw "Can't load video information: videoId is missing"
|
||||
JobError("Can't load video information: videoId is missing")
|
||||
return
|
||||
end if
|
||||
|
||||
service = new Invidious.InvidiousService(invidiousNode)
|
||||
@@ -25,22 +28,22 @@ function VideoContentTaskDev(input as object) as object
|
||||
|
||||
backgroundPoster.uri = `${instance}/vi/${videoId}/maxresdefault.jpg`
|
||||
|
||||
cancellation = CancellationUtils.CreateCancellation(JobGetCallbackNode(), "cancel", true)
|
||||
backend = preferencesNode["backend.selected"]
|
||||
if backend = "playlet"
|
||||
metadata = InnertubeService.GetVideoMetadata(videoId, { cancellation: m.top.cancellation })
|
||||
metadata = InnertubeService.GetVideoMetadata(videoId, { cancellation: cancellation })
|
||||
else
|
||||
metadata = service.GetVideoMetadata(videoId, { cancellation: m.top.cancellation })
|
||||
metadata = service.GetVideoMetadata(videoId, { cancellation: cancellation })
|
||||
end if
|
||||
|
||||
if m.top.cancel
|
||||
return invalid
|
||||
if JobIsCancelled()
|
||||
JobCancel()
|
||||
return
|
||||
end if
|
||||
|
||||
if metadata.error <> invalid
|
||||
return {
|
||||
success: false
|
||||
error: metadata.error
|
||||
}
|
||||
JobError(metadata.error)
|
||||
return
|
||||
end if
|
||||
|
||||
contentNode.title = metadata.title
|
||||
@@ -69,10 +72,6 @@ function VideoContentTaskDev(input as object) as object
|
||||
playletStreamUrls: streamUrls
|
||||
playletStreamUrlIndex: 0
|
||||
})
|
||||
|
||||
return {
|
||||
success: true
|
||||
}
|
||||
end function
|
||||
|
||||
function CreateStreamUrls(metadata as object) as object
|
||||
@@ -1,10 +1,10 @@
|
||||
import "pkg:/components/JobSystem/Jobs.bs"
|
||||
import "pkg:/components/JobSystem/JobSystem.bs"
|
||||
import "pkg:/components/Navigation/Navigation.bs"
|
||||
import "pkg:/components/Services/Innertube/Constants.bs"
|
||||
import "pkg:/components/VideoPlayerDev/PictureInPicture.bs"
|
||||
import "pkg:/components/VideoPlayerDev/PlayerUi.bs"
|
||||
import "pkg:/components/VideoQueue/VideoQueueUtils.bs"
|
||||
import "pkg:/source/AsyncTask/AsyncTask.bs"
|
||||
import "pkg:/source/AsyncTask/Tasks.bs"
|
||||
import "pkg:/source/utils/DisposableObserve.bs"
|
||||
import "pkg:/source/utils/ErrorUtils.bs"
|
||||
import "pkg:/source/utils/FocusManagement.bs"
|
||||
@@ -76,12 +76,12 @@ function PlayWithContent(contentNode as object)
|
||||
m.backgroundPosterSmall.uri = thumbnail
|
||||
end if
|
||||
|
||||
StartVideoContentTask(videoContentNode)
|
||||
StartVideoContentDevJob(videoContentNode)
|
||||
end function
|
||||
|
||||
function StartVideoContentTask(videoContentNode as object)
|
||||
if m.videoContentTask <> invalid
|
||||
m.videoContentTask.cancel = true
|
||||
function StartVideoContentDevJob(videoContentNode as object)
|
||||
if m.videoContentDevJob <> invalid
|
||||
m.videoContentDevJob.cancel = true
|
||||
end if
|
||||
|
||||
m.top.content = videoContentNode
|
||||
@@ -91,31 +91,29 @@ function StartVideoContentTask(videoContentNode as object)
|
||||
m.loadingUi.visible = true
|
||||
m.loadingSpinner.control = "start"
|
||||
|
||||
m.videoContentTask = AsyncTask.Start(Tasks.VideoContentTaskDev, {
|
||||
input = {
|
||||
titleLabel: m.titleLabel
|
||||
secondaryTitleLabel: m.secondaryTitleLabel
|
||||
content: videoContentNode
|
||||
invidious: m.top.invidious
|
||||
preferences: m.top.preferences
|
||||
backgroundPoster: m.backgroundPoster
|
||||
}, OnVideoContentTaskResults)
|
||||
}
|
||||
|
||||
m.videoContentDevJob = JobSystem.CreateCallback(OnVideoContentDevJobDone)
|
||||
JobSystem.QueueJob(m.jobQueue, Jobs.VideoContentDevJob, input, m.videoContentDevJob)
|
||||
end function
|
||||
|
||||
function OnVideoContentTaskResults(output as object) as void
|
||||
m.videoContentTask = invalid
|
||||
if output.cancelled
|
||||
function OnVideoContentDevJobDone(event as object) as void
|
||||
JobSystem.UnobserveCallback(event.getRoSGNode())
|
||||
m.videoContentDevJob = invalid
|
||||
|
||||
info = event.getInfo()
|
||||
if info.cancel
|
||||
return
|
||||
end if
|
||||
|
||||
if not output.success or not output.result.success
|
||||
' output.error for unhandled exception
|
||||
error = output.error
|
||||
if error = invalid
|
||||
' output.result.error for network errors
|
||||
error = output.result.error
|
||||
end if
|
||||
error = ErrorUtils.Format(error)
|
||||
LogError(error)
|
||||
if not info.success
|
||||
m.top.close = true
|
||||
return
|
||||
end if
|
||||
@@ -126,9 +124,9 @@ end function
|
||||
function OnClose()
|
||||
m.top.previousPlayer = invalid
|
||||
|
||||
if m.videoContentTask <> invalid
|
||||
m.videoContentTask.cancel = true
|
||||
m.videoContentTask = invalid
|
||||
if m.videoContentDevJob <> invalid
|
||||
m.videoContentDevJob.cancel = true
|
||||
m.videoContentDevJob = invalid
|
||||
end if
|
||||
|
||||
parent = m.top.getParent()
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
-->
|
||||
<component name="VideoPlayerDev" extends="Video" includes="AutoBind,Disposable">
|
||||
<interface>
|
||||
<field id="jobQueue" type="node" bind="/JobQueue" />
|
||||
<field id="container" type="node" bind=".." />
|
||||
<field id="videoQueue" type="node" bind="../../VideoQueue" />
|
||||
<field id="preferences" type="node" bind="../../Preferences" />
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
import "pkg:/components/Services/LoungeService/LoungeMessages.bs"
|
||||
import "pkg:/components/VideoFeed/FeedLoadState.bs"
|
||||
import "pkg:/components/VideoQueue/Notifications/VideoQueueNotificationUtils.bs"
|
||||
import "pkg:/source/AsyncTask/AsyncTask.bs"
|
||||
import "pkg:/source/AsyncTask/Tasks.bs"
|
||||
import "pkg:/source/utils/FocusManagement.bs"
|
||||
import "pkg:/source/utils/Logging.bs"
|
||||
import "pkg:/source/utils/MathUtils.bs"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import "pkg:/components/JobSystem/Jobs.bs"
|
||||
import "pkg:/components/JobSystem/JobSystem.bs"
|
||||
import "pkg:/components/Navigation/Navigation.bs"
|
||||
import "pkg:/source/AsyncTask/AsyncTask.bs"
|
||||
import "pkg:/source/AsyncTask/Tasks.bs"
|
||||
import "pkg:/source/utils/DisposableObserve.bs"
|
||||
import "pkg:/source/utils/FocusManagement.bs"
|
||||
import "pkg:/source/utils/Locale.bs"
|
||||
@@ -37,9 +37,9 @@ end function
|
||||
function OnContentSet() as void
|
||||
content = m.top.content
|
||||
if content = invalid
|
||||
if m.loadDetailsTask <> invalid
|
||||
m.loadDetailsTask.cancel = true
|
||||
m.loadDetailsTask = invalid
|
||||
if m.videoQueueViewContentJob <> invalid
|
||||
m.videoQueueViewContentJob.cancel = true
|
||||
m.videoQueueViewContentJob = invalid
|
||||
end if
|
||||
return
|
||||
end if
|
||||
@@ -141,17 +141,20 @@ function LoadVideoDetailsIfNeeded() as void
|
||||
|
||||
LogInfo("Loading video details for", m.videosDetailsToLoad.Count(), "videos")
|
||||
|
||||
if m.loadDetailsTask <> invalid
|
||||
m.loadDetailsTask.cancel = true
|
||||
if m.videoQueueViewContentJob <> invalid
|
||||
m.videoQueueViewContentJob.cancel = true
|
||||
end if
|
||||
|
||||
m.loadDetailsTask = AsyncTask.Start(Tasks.VideoQueueViewContentTask, {
|
||||
input = {
|
||||
videoNodes: m.videosDetailsToLoad
|
||||
innertube: m.top.innertube
|
||||
invidious: m.top.invidious
|
||||
preferences: m.top.preferences
|
||||
index: indexInLoadingArray
|
||||
})
|
||||
}
|
||||
|
||||
m.videoQueueViewContentJob = JobSystem.CreateCallback()
|
||||
JobSystem.QueueJob(m.jobQueue, Jobs.VideoQueueViewContentJob, input, m.videoQueueViewContentJob)
|
||||
end function
|
||||
|
||||
function AdjustFocus(videoCount as integer)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<field id="jumpToItem" type="integer" alias="queueList.jumpToItem" />
|
||||
<field id="videoQueue" type="node" />
|
||||
<field id="appController" type="node" />
|
||||
<field id="jobQueue" type="node" />
|
||||
<field id="innertube" type="node" />
|
||||
<field id="invidious" type="node" />
|
||||
<field id="preferences" type="node" />
|
||||
|
||||
+13
-8
@@ -2,17 +2,20 @@ import "pkg:/components/Services/Innertube/InnertubeService.bs"
|
||||
import "pkg:/components/Services/Invidious/InvidiousService.bs"
|
||||
import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs"
|
||||
import "pkg:/source/services/HttpClient.bs"
|
||||
import "pkg:/source/utils/CancellationUtils.bs"
|
||||
import "pkg:/source/utils/MathUtils.bs"
|
||||
|
||||
@asynctask
|
||||
function VideoQueueViewContentTask(input as object) as object
|
||||
@job("VideoQueueViewContentJob")
|
||||
function ExecuteJob() as void
|
||||
input = JobGetInput()
|
||||
|
||||
videoNodes = input.videoNodes
|
||||
innertubeNode = input.innertube
|
||||
invidiousNode = input.invidious
|
||||
preferencesNode = input.preferences
|
||||
service = new Invidious.InvidiousService(invidiousNode)
|
||||
instance = service.GetInstance()
|
||||
cancellation = m.top.cancellation
|
||||
cancellation = CancellationUtils.CreateCancellation(JobGetCallbackNode(), "cancel", true)
|
||||
|
||||
index = MathUtils.Clamp(input.index - 2, 0, videoNodes.Count() - 1)
|
||||
|
||||
@@ -38,8 +41,9 @@ function VideoQueueViewContentTask(input as object) as object
|
||||
sleep(500)
|
||||
end if
|
||||
|
||||
if m.top.cancel = true
|
||||
return invalid
|
||||
if JobIsCancelled()
|
||||
JobCancel()
|
||||
return
|
||||
end if
|
||||
end for
|
||||
|
||||
@@ -50,12 +54,13 @@ function VideoQueueViewContentTask(input as object) as object
|
||||
sleep(1000)
|
||||
end if
|
||||
|
||||
if m.top.cancel = true
|
||||
return invalid
|
||||
if JobIsCancelled()
|
||||
JobCancel()
|
||||
return
|
||||
end if
|
||||
end for
|
||||
|
||||
return invalid
|
||||
return
|
||||
end function
|
||||
|
||||
function LoadVideoDetail(videoNode as object, service as object, instance as string, requestOptions as object, backend as string) as boolean
|
||||
@@ -6,6 +6,7 @@ namespace VideoQueueViewUtils
|
||||
videoQueueView = CreateObject("roSGNode", "VideoQueueView")
|
||||
videoQueueView.videoQueue = videoQueue
|
||||
videoQueueView.appController = appController
|
||||
videoQueueView.jobQueue = videoQueue.jobQueue
|
||||
videoQueueView.innertube = videoQueue.innertube
|
||||
videoQueueView.invidious = videoQueue.invidious
|
||||
videoQueueView.preferences = videoQueue.preferences
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import "pkg:/components/Services/Innertube/SessionData.bs"
|
||||
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
|
||||
import "pkg:/source/services/HttpClient.bs"
|
||||
|
||||
namespace Http
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
import "pkg:/source/utils/Types.bs"
|
||||
|
||||
namespace AsyncTask
|
||||
|
||||
function Start(taskName as string, input as object, callback = invalid as object) as object
|
||||
task = Create(taskName, input, callback)
|
||||
task.control = "RUN"
|
||||
return task
|
||||
end function
|
||||
|
||||
function Create(taskName as string, input as object, callback = invalid as object) as object
|
||||
id = StringUtils.RandomId()
|
||||
task = createObject("roSGNode", taskName)
|
||||
task.id = id
|
||||
task.input = input
|
||||
|
||||
m[`asynctask_${id}`] = task
|
||||
m[`asynctask_${id}_callback`] = callback
|
||||
task.ObserveFieldScoped("state", FuncName(internal_OnTaskState))
|
||||
|
||||
return task
|
||||
end function
|
||||
|
||||
function internal_OnTaskState(e as object) as void
|
||||
task = e.getRoSGNode()
|
||||
if task.state = "init" or task.state = "run"
|
||||
return
|
||||
end if
|
||||
|
||||
task.UnobserveFieldScoped("state")
|
||||
|
||||
id = task.id
|
||||
output = task.output
|
||||
' if output is invalid, it means the task was interrupted before the result is ready
|
||||
if output <> invalid
|
||||
callback = m[`asynctask_${id}_callback`]
|
||||
if callback <> invalid
|
||||
callback(output)
|
||||
end if
|
||||
end if
|
||||
|
||||
task.input = invalid
|
||||
task.output = invalid
|
||||
m.delete(`asynctask_${id}`)
|
||||
m.delete(`asynctask_${id}_callback`)
|
||||
end function
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,42 @@
|
||||
import "pkg:/components/JobSystem/JobRequest.bs"
|
||||
import "pkg:/components/JobSystem/JobSystem.bs"
|
||||
|
||||
namespace Tests
|
||||
|
||||
@suite
|
||||
class GenerateQrCodeJobTests extends Rooibos.BaseTestSuite
|
||||
|
||||
protected override function setup()
|
||||
m.logger = CreateObject("roSGNode", "Logger")
|
||||
m.logger.logLevel = -1
|
||||
end function
|
||||
|
||||
@describe("GenerateQrCodeJob")
|
||||
@it("Generates QR codes correctly")
|
||||
function _()
|
||||
poster = CreateObject("roSGNode", "Node")
|
||||
poster.addField("uri", "uri", false)
|
||||
|
||||
JobRequest.Execute({
|
||||
jobName: "GenerateQrCodeJob"
|
||||
input: {
|
||||
poster: poster
|
||||
text: "http://127.0.0.1:1234/some/path/to/resource?query=string"
|
||||
size: 300
|
||||
padding: 10
|
||||
}
|
||||
})
|
||||
|
||||
m.assertNotEmpty(poster.uri, "Poster URI should not be empty after generating QR code")
|
||||
|
||||
buffer = CreateObject("roByteArray")
|
||||
buffer.ReadFile(poster.uri)
|
||||
digest = CreateObject("roEVPDigest")
|
||||
digest.Setup("md5")
|
||||
md5 = digest.Process(buffer)
|
||||
|
||||
m.assertEqual(md5, "45ad1dbc361f47d267ab89e23d45a1d5")
|
||||
end function
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -8,6 +8,7 @@ namespace Tests
|
||||
|
||||
protected override function setup()
|
||||
m.logger = CreateObject("roSGNode", "Logger")
|
||||
m.logger.logLevel = -1
|
||||
end function
|
||||
|
||||
protected override function beforeEach()
|
||||
@@ -28,7 +29,7 @@ namespace Tests
|
||||
messagePort = CreateObject("roMessagePort")
|
||||
|
||||
for i = 1 to 100
|
||||
callbackNode = CreateObject("roSGNode", "JobCallback")
|
||||
callbackNode = JobSystem.CreateCallback()
|
||||
callbackNode.observeField("done", messagePort, ["success"])
|
||||
JobSystem.QueueJob(m.jobQueue, Jobs.SimpleTestJob, { sleep: 50, success: i mod 2 = 0 }, callbackNode)
|
||||
end for
|
||||
@@ -66,7 +67,7 @@ namespace Tests
|
||||
|
||||
callbacks = []
|
||||
for i = 1 to 10
|
||||
callbackNode = CreateObject("roSGNode", "JobCallback")
|
||||
callbackNode = JobSystem.CreateCallback()
|
||||
callbackNode.observeField("done", messagePort, ["success", "cancel"])
|
||||
callbacks.push(callbackNode)
|
||||
JobSystem.QueueJob(m.jobQueue, Jobs.SimpleTestJob, { sleep: 5000, success: true }, callbackNode)
|
||||
@@ -114,7 +115,7 @@ namespace Tests
|
||||
|
||||
callbacks = []
|
||||
for i = 1 to 10
|
||||
callbackNode = CreateObject("roSGNode", "JobCallback")
|
||||
callbackNode = JobSystem.CreateCallback()
|
||||
callbackNode.observeField("done", messagePort, ["success", "cancel"])
|
||||
callbacks.push(callbackNode)
|
||||
JobSystem.QueueJob(m.jobQueue, Jobs.SimpleTestJob, { sleep: 5000, success: true }, callbackNode)
|
||||
@@ -147,6 +148,34 @@ namespace Tests
|
||||
end while
|
||||
end function
|
||||
|
||||
@it("Handles invalid job names gracefully")
|
||||
function _()
|
||||
messagePort = CreateObject("roMessagePort")
|
||||
callbackNode = JobSystem.CreateCallback()
|
||||
callbackNode.observeField("done", messagePort, ["success", "error"])
|
||||
|
||||
' Attempt to queue a job with an invalid name
|
||||
JobSystem.QueueJob(m.jobQueue, "InvalidJobName", {}, callbackNode)
|
||||
|
||||
' Wait for the error message
|
||||
msg = wait(1000, messagePort)
|
||||
|
||||
if msg = invalid
|
||||
m.testSuite.fail("Waiting for job error message timed out after 1000ms")
|
||||
end if
|
||||
|
||||
if type(msg) <> "roSGNodeEvent" or msg.getField() <> "done"
|
||||
m.testSuite.fail("Expected a done event for the job error")
|
||||
end if
|
||||
|
||||
done = msg.getData()
|
||||
info = msg.getInfo()
|
||||
|
||||
m.assertTrue(done, "Job should be done")
|
||||
m.assertFalse(info.success, "Job should not succeed with an invalid job name")
|
||||
m.assertNotEmpty(info.error, "Error message should not be empty")
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -35,4 +35,17 @@ namespace Assert
|
||||
throw "Assertion failed: Node does not have field '" + field + "'. " + ToString(message)
|
||||
end if
|
||||
end function
|
||||
|
||||
function NotNullOrEmpty(value as dynamic, message = invalid as dynamic) as void
|
||||
if value = invalid
|
||||
throw "Assertion failed: Value is invalid. " + ToString(message)
|
||||
end if
|
||||
if IsString(value) and (Len(value) = 0)
|
||||
throw "Assertion failed: Value is an empty string. " + ToString(message)
|
||||
else if IsArray(value) and (value.Count() = 0)
|
||||
throw "Assertion failed: Value is an empty array. " + ToString(message)
|
||||
else if IsAssociativeArray(value) and (value.ifAssociativeArray.count() = 0)
|
||||
throw "Assertion failed: Value is an empty associative array. " + ToString(message)
|
||||
end if
|
||||
end function
|
||||
end namespace
|
||||
@@ -1,3 +1,4 @@
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
import "pkg:/source/utils/Types.bs"
|
||||
|
||||
namespace UrlUtils
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
// This plugin generates a task component for each function annotated with @asynctask
|
||||
|
||||
import {
|
||||
CompilerPlugin,
|
||||
BscFile,
|
||||
isBrsFile,
|
||||
WalkMode,
|
||||
createVisitor,
|
||||
Program,
|
||||
FunctionStatement,
|
||||
DiagnosticSeverity,
|
||||
} from 'brighterscript';
|
||||
|
||||
export class AsyncTaskPlugin implements CompilerPlugin {
|
||||
public name = 'AsyncTaskPlugin';
|
||||
|
||||
afterFileParse(file: BscFile) {
|
||||
if (!isBrsFile(file)) {
|
||||
return
|
||||
}
|
||||
|
||||
const program = file.program
|
||||
|
||||
file.ast.walk(createVisitor({
|
||||
FunctionExpression: (func) => {
|
||||
if (!this.isAsyncTask(func.functionStatement)) {
|
||||
return
|
||||
}
|
||||
|
||||
const functionName = func.functionStatement!.name.text
|
||||
const hasParams = func.functionStatement!.func.parameters.length > 0
|
||||
const taskName = `${functionName}_AsyncTask`
|
||||
|
||||
const bs = this.generateBsTask(functionName, hasParams, file)
|
||||
const bsFile = `components/AsyncTask/generated/${taskName}.bs`
|
||||
|
||||
const xml = this.generateXmlTask(taskName, bsFile)
|
||||
const xmlFile = `components/AsyncTask/generated/${taskName}.xml`
|
||||
|
||||
if (program.hasFile(xmlFile)) {
|
||||
const currentContent = program.getFile(xmlFile).fileContents
|
||||
if (currentContent !== xml) {
|
||||
file.addDiagnostics([{
|
||||
file: file,
|
||||
range: func.range,
|
||||
message: `AsyncTaskPlugin: file ${xmlFile} already exists`,
|
||||
severity: DiagnosticSeverity.Error,
|
||||
code: 'ASYNC_TASK_FILE_EXISTS',
|
||||
}]);
|
||||
}
|
||||
}
|
||||
file.program.setFile(xmlFile, xml)
|
||||
|
||||
if (program.hasFile(bsFile)) {
|
||||
const currentContent = program.getFile(bsFile).fileContents
|
||||
if (currentContent !== bs) {
|
||||
file.addDiagnostics([{
|
||||
file: file,
|
||||
range: func.range,
|
||||
message: `AsyncTaskPlugin: file ${bsFile} already exists`,
|
||||
severity: DiagnosticSeverity.Error,
|
||||
code: 'ASYNC_TASK_FILE_EXISTS',
|
||||
}]);
|
||||
}
|
||||
}
|
||||
file.program.setFile(bsFile, bs)
|
||||
},
|
||||
}), {
|
||||
walkMode: WalkMode.visitExpressionsRecursive
|
||||
});
|
||||
}
|
||||
|
||||
beforeProgramValidate(program: Program) {
|
||||
this.generateTaskListEnum(program);
|
||||
}
|
||||
|
||||
isAsyncTask(functionStatement: FunctionStatement | undefined) {
|
||||
const annotations = functionStatement?.annotations
|
||||
if (!annotations || annotations.length === 0) {
|
||||
return false
|
||||
}
|
||||
for (let index = 0; index < annotations.length; index++) {
|
||||
const annotation = annotations[index];
|
||||
if (annotation.name === "asynctask") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
generateBsTask(functionName: string, hasInput: boolean, file: BscFile): string {
|
||||
return `
|
||||
import "pkg:/${file.pkgPath}"
|
||||
import "pkg:/source/utils/ErrorUtils.bs"
|
||||
|
||||
function Init()
|
||||
m.top.functionName = "TaskMain"
|
||||
m.top.cancellation = {
|
||||
node: m.top
|
||||
field: "cancel"
|
||||
value: true
|
||||
}
|
||||
end function
|
||||
|
||||
function TaskMain()
|
||||
try
|
||||
result = ${functionName}(${(hasInput ? "m.top.input" : "")})
|
||||
m.top.setField("output", {
|
||||
success: true
|
||||
task: m.top
|
||||
cancelled: m.top.cancel
|
||||
result: result
|
||||
})
|
||||
catch e
|
||||
#if DEBUG
|
||||
print "ERROR in ${functionName}: "
|
||||
print ErrorUtils.Format(e)
|
||||
#end if
|
||||
m.top.setField("output", {
|
||||
success: false
|
||||
task: m.top
|
||||
cancelled: m.top.cancel
|
||||
error: e
|
||||
})
|
||||
end try
|
||||
end function
|
||||
`
|
||||
}
|
||||
|
||||
generateXmlTask(taskName: string, bsFile: string): string {
|
||||
|
||||
return `<?xml version="1.0" encoding="UTF-8" ?>
|
||||
|
||||
<component name="${taskName}" extends="Task">
|
||||
<interface>
|
||||
<field id="input" type="assocarray" />
|
||||
<field id="output" type="assocarray" />
|
||||
<field id="cancel" type="boolean" alwaysNotify="true" />
|
||||
<field id="cancellation" type="assocarray" />
|
||||
</interface>
|
||||
</component>`
|
||||
}
|
||||
|
||||
generateTaskListEnum(program: Program) {
|
||||
const asyncTasks = Object.values(program.files).reduce((acc, file) => {
|
||||
if (!isBrsFile(file)) {
|
||||
return acc
|
||||
}
|
||||
|
||||
file.ast.walk(createVisitor({
|
||||
FunctionExpression: (func) => {
|
||||
if (!this.isAsyncTask(func.functionStatement)) {
|
||||
return
|
||||
}
|
||||
|
||||
acc.add(func.functionStatement!.name.text)
|
||||
},
|
||||
}), {
|
||||
walkMode: WalkMode.visitExpressionsRecursive
|
||||
});
|
||||
|
||||
return acc
|
||||
}, new Set<string>());
|
||||
|
||||
const enumItems = Array.from(asyncTasks).map((task) => {
|
||||
return `${task} = "${task}_AsyncTask"`
|
||||
})
|
||||
|
||||
const content = 'enum Tasks\n ' + enumItems.join('\n ') + '\nend enum\n';
|
||||
|
||||
program.setFile('source/AsyncTask/Tasks.bs', content);
|
||||
}
|
||||
}
|
||||
|
||||
export default () => {
|
||||
return new AsyncTaskPlugin();
|
||||
};
|
||||
@@ -24,6 +24,11 @@ export class ImportValidationPlugin implements CompilerPlugin {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip job files
|
||||
if (file.srcPath.endsWith('Job.bs')) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.generateXmlComponent(file);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user