Add the ability to find a working caption (#67)

* Add the ability to find a working caption

* Lint fix

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
Brahim Hadricheandgithub-action linter authored and GitHub committed 2023-04-06 15:19:53 -04:00
1 parent 71045bf944
commit 7d2d403e3f
4 files changed
+98 -1

No files matched your search

@@ -1,3 +1,5 @@
import "pkg:/components/VideoPlayer/VideoPlayerCaptionsTask.bs"
function SetCaptions(metadata as object, videoPlayer as object, contentNode as object) as void
if metadata.captions.Count() = 0
return
@@ -18,4 +20,35 @@ function SetCaptions(metadata as object, videoPlayer as object, contentNode as o
end for
contentNode.ClosedCaptions = True
contentNode.SubtitleTracks = subtitleTracks
' Searching for a working caption could cause a delay in the video player start.
' This is why it is behind a feature flag.
#if CAPTION_INSTANCE_SEARCH
StartAsyncTask(VideoPlayerCaptionsTask, {
videoId: metadata.videoId,
instance: instance,
subtitleTracks: subtitleTracks
}, OnVideoPlayerCaptionsTaskResults)
#end if
end function
function OnVideoPlayerCaptionsTaskResults(output as object) as void
changed = output.result.changed
if not changed
return
end if
videoId = output.result.videoId
if m.top.videoId <> videoId
return
end if
state = m.top.state
contentNode = m.top.content
contentNode.Update({
SubtitleTracks: output.result.subtitleTracks
})
if state = "buffering" or state = "playing"
m.top.control = "play"
end if
end function
@@ -0,0 +1,62 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/services/InvidiousSettings.bs"
@asynctask
function VideoPlayerCaptionsTask(input as object) as object
originalInstance = input.instance
subtitleTracks = input.subtitleTracks
if subtitleTracks.Count() = 0
return {
changed: false
}
end if
track = subtitleTracks[0]
url = track.TrackName
if IsValidSubtitleTrack(url)
return {
changed: false
}
end if
failedInstances = {}
failedInstances[originalInstance] = true
instances = InvidiousSettings.GetCurrentInstances()
for each instance in instances
if failedInstances[instance] = true
continue for
end if
instanceUrl = url.Replace(originalInstance, instance)
if IsValidSubtitleTrack(instanceUrl)
for i = 0 to subtitleTracks.Count() - 1
subtitleTracks[i].TrackName = subtitleTracks[i].TrackName.Replace(originalInstance, instance)
end for
return {
changed: true,
videoId: input.videoId,
subtitleTracks: subtitleTracks
}
else
failedInstances[instance] = true
end if
end for
return {
changed: false
}
end function
function IsValidSubtitleTrack(url as string) as boolean
response = Requests().get(url, { parseJson: false })
' A popular instance will return a valid format
' WEBVTT
' Kind: captions
' Language: en
' But won't include any caption items
return response.ok and response.text.StartsWith("WEBVTT") and response.text.len() > 50
end function