Fresh start (#110)

* Fresh start

* Create an xml include plugin (#111)

* Restructure and add testing (#114)

* rooibos setup

* Restructure and add testing

* docs

* Restore manifestpipi

* Description in tools

* A bit of docs

* Auto bind feature (#115)

* Auto bind feature

* Fix children merge

* bs plugin fix

* Feature/app controller (#120)

* Initial layout

* Restructuring and plugin work

* A couple of tweaks in binding stuff

* tweaks

* basic stack

* Add basic app controller

* Support json5/yaml in playlet config files (#123)

* Support json5 in playlet config files

* Add yaml to the mix

* Delete old lib project

* plugin fix

* plugin tweak

* verbose logging

* Revert "verbose logging"

This reverts commit 25867f4226703d83102519a0d48d1cc46a9876de.

* One idea to fix the include plugin

* Fix instability in plugins

* Feature/navbar (#126)

* Navbar

* typo

* comment

* Single content node, and tests

* Remove unused field

* tweaks

* update dependencies command

* tweak formatting

* Add web app screen

* Set id in created screens

* Search screen

* Tests

* Show playlists and channels in search results

* Move screen stuff to app controller

* Home screen (wip)

* Add preferences node

* README.md copyedits (#130)

* README.md: Fix typos

* README.md: Standardize capitalization and punctuation

* Update docs/README.md

---------

Co-authored-by: Brahim Hadriche <brahim.hadriche@gmail.com>

* Web server: round 1 (#131)

* web server object

* Logging

* Web server round 1

* Lint fix

* Small tweaks

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>

* Logging to file

* Leftover

* Add logs file to web server

* Fix for timeout

* Disable keepalive connection

* add openapi spec file

* Lint fix

* add prefs version in api

* Add ecp api definition

* Lint fix

* Settings rework (#135)

* Settings rework

* Standard OnFocusChange event

* Video player stuff (#136)

* Video player stuff

* Restructure things so that focus is better handled

* Lint fix

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>

* Exit dialog

* A bunch of changes

* New http client

* Set TODO priorities

* picture in picture

* mark video watched

* Video player stuff mostly there

* update spec file

* Sponsorblock

* FuncName

* SponsorBlock notifications

* Lint fix

* misc

* remove basic auth feature flag (until we start using it)

* Play queue part 1

* type fix

* handle unicode in request body

* SponsorBlock chapter label

* modal base

* remove a hack

* Invidious settings

* web server reduce timeout

* Test for captions

* Lint fix

* remove rpc stuff

* small change

* Solve focus management

* a couple of fixes

* Remove a bunch of todos

* feed error handling wip

* Lint fix

* navigation in instance settings

* home screen pagination support

* Refactor feed to support pagination on search page

* cell loading animation

* Tweak caching

* delete test screen

* playlist support part 1

* Basic playlist view

* Restore playlist/channel handler

* Refactor some content node stuff, and add an auth popup dialog

* A bad implementation of a playqueue

* Lint fix

* playlist cast fix

* Feature/web app catch up (#139)

* playlist cast fix

* Move things around

* support playlists in web app

* update api

* Bump deps

* Downgrade todo

---------

Co-authored-by: Bryce Harrington <bryce@bryceharrington.org>
Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
authored and GitHub committed 2023-09-07 17:18:25 -04:00
1 parent 79f74141c5
commit 43166fb43b
349 files changed
+12784 -7660

No files matched your search

@@ -0,0 +1,43 @@
import "pkg:/source/asyncTask/asyncTask.bs"
import "LatestLibVersionTask.bs"
import "pkg:/source/services/ApplicationInfo.bs"
function Init()
m.service = new ApplicationInfo(m.top)
end function
function GetAppInfo(unused as dynamic) as object
return m.service.GetAppInfo()
end function
function GetDeviceInfo(unused as dynamic) as object
return m.service.GetDeviceInfo()
end function
function GetUserCountryCode(unused as dynamic) as string
return m.service.GetUserCountryCode()
end function
function GetLocalIpAddress(unused as dynamic) as dynamic
return m.service.GetLocalIpAddress()
end function
function GetLatestPlayletLibVersion(unused as dynamic) as dynamic
if not StringUtils.IsNullOrEmpty(m.top.lib_version_latest)
return m.top.lib_version_latest
end if
if m.latestLibVersionTask <> invalid and m.latestLibVersionTask.state = "run"
return invalid
end if
m.latestLibVersionTask = StartAsyncTask(LatestLibVersionTask, {}, function(output as object) as void
m.latestLibVersionTask = invalid
if output.success and output.result.latest <> invalid
m.top.lib_version_latest = output.result.latest
end if
end function)
return invalid
end function
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="ApplicationInfo" extends="Node">
<interface>
<field id="lib_version_latest" type="string" />
<function name="GetUserCountryCode" />
<function name="GetLocalIpAddress" />
<function name="GetAppInfo" />
<function name="GetLatestPlayletLibVersion" />
<function name="GetDeviceInfo" />
</interface>
</component>
@@ -0,0 +1,25 @@
import "pkg:/source/services/HttpClient.bs"
@asynctask
function LatestLibVersionTask() as object
latest = GetLatestPlayletLibVersionFromGithubReleases()
return {
latest: latest
}
end function
function GetLatestPlayletLibVersionFromGithubReleases() as string
response = HttpClient.Head("https://github.com/iBicha/playlet/releases/latest").Await()
if response.StatusCode() = 200
headers = response.Headers()
if headers.location <> invalid
regex = CreateObject("roRegex", "/v?(\d+\.\d+\.\d+)", "")
match = regex.match(headers.location)
if match.Count() = 2
return match[1]
end if
end if
end if
return "N/A"
end function
@@ -0,0 +1,23 @@
import "InvidiousService.bs"
function Init()
m.top.apiDefinitions = ParseJson(ReadAsciiFile("libpkg:/config/invidious_video_api.json5"))
m.service = new Invidious.InvidiousService(m.top)
m.top.authToken = m.service.GetAuthToken()
end function
function GetCurrentInstance(unused as dynamic) as string
return m.service.GetInstance()
end function
function GetAuthorizeTokenLink(unused as dynamic) as dynamic
return m.service.GetAuthorizeTokenLink()
end function
function Logout(unused as dynamic)
m.service.Logout()
end function
function SetAuthToken(token as string, instance as string, username as dynamic)
m.service.SetAuthToken(token, instance, username)
end function
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="Invidious" extends="Node">
<interface>
<field id="applicationInfo" type="node" />
<field id="preferences" type="node" />
<field id="webServer" type="node" />
<field id="authToken" type="assocarray" />
<field id="apiDefinitions" type="assocarray" />
<function name="Logout" />
<function name="GetCurrentInstance" />
<function name="GetAuthorizeTokenLink" />
<function name="SetAuthToken" />
</interface>
</component>
@@ -0,0 +1,358 @@
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/roku_modules/log/LogMixin.brs"
namespace Invidious
const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,users"
const DEFAULT_INSTANCE = "https://vid.puffyan.us"
const TOKEN_CALLBACK = "/invidious/token_callback"
const STATS_ENDPOINT = "/api/v1/stats"
const VIDEOS_ENDPOINT = "/api/v1/videos"
const PLAYLISTS_ENDPOINT = "/api/v1/playlists"
const HISTORY_ENDPOINT = "/api/v1/auth/history"
const SEARCH_SUGGEST_ENDPOINT = "/api/v1/search/suggestions"
const AUTH_SCOPES = "GET:feed,GET:playlists*,POST:tokens/register,POST:tokens/unregister,POST:history*"
const AUTH_PLAYLISTS = "/api/v1/auth/playlists"
const AUTH_TOKENS_UNREGISTER = "/api/v1/auth/tokens/unregister"
const AUTH_TOKENS_REGISTER = "/api/v1/auth/tokens/register"
const TOKEN_TIMESPAN = 60 * 60 * 24 * 365 * 2 '2 years
const ERROR_NOT_AUTHENTICATED = "Not authenticated"
class InvidiousService
public node as object
function new(node as object)
m.log = new log.Logger("InvidiousService")
m.node = node
' TODO:P2 api definitions are not needed everytime, move them to a separate function and lazy load
apiDefinitions = node.apiDefinitions
m.endpoints = {}
for each apiDefinition in apiDefinitions.endpoints
m.endpoints[apiDefinition.name] = apiDefinition
end for
m.responseHanlders = {
DefaultHandler: m.DefaultHandler,
AuthFeedHandler: m.AuthFeedHandler,
PlaylistHandler: m.PlaylistHandler,
ChannelHandler: m.ChannelHandler
}
end function
function DefaultQueryParams() as object
return {
region: m.node.applicationInfo@.GetUserCountryCode(invalid)
}
end function
function GetAuthenticationHeaders(token as string) as object
return {
"Authorization": `Bearer ${token}`
}
end function
function GetInstance() as string
instance = m.node.preferences["invidious.instance"]
if not StringUtils.IsNullOrEmpty(instance)
return instance
end if
return DEFAULT_INSTANCE
end function
function MarkVideoWatched(videoId as dynamic) as void
if StringUtils.IsNullOrEmpty(videoId)
return
end if
authToken = m.node.authToken
if authToken = invalid
return
end if
url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}`
request = HttpClient.Post(url, "")
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.SendAndForget()
end function
function SearchSuggestions(q as string, cancellation = invalid as object) as object
instance = m.GetInstance()
url = `${instance}${Invidious.SEARCH_SUGGEST_ENDPOINT}`
request = HttpClient.Get(url)
request.QueryParams(m.DefaultQueryParams())
request.QueryParam("q", q)
request.CacheSeconds(60 * 60 * 6)' 6 hours
request.Cancellation(cancellation)
response = request.Await()
return response.Json()
end function
function GetVideoMetadata(videoId as string, cancellation = invalid as object) as object
instance = m.GetInstance()
url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}`
request = HttpClient.Get(url)
request.QueryParams(m.DefaultQueryParams())
request.CacheSeconds(60 * 60 * 6)' 6 hours
request.Cancellation(cancellation)
return request.Await()
end function
function GetPlaylist(playlistId as string, index = 0 as integer, cancellation = invalid as object) as object
authToken = m.node.authToken
if authToken = invalid
instance = m.GetInstance()
url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}`
request = HttpClient.Get(url)
else
url = `${authToken.instance}${Invidious.AUTH_PLAYLISTS}/${playlistId}`
request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
end if
request.QueryParams(m.DefaultQueryParams())
request.QueryParam("index", index)
request.Cancellation(cancellation)
return request.Await()
end function
function GetVideoStreamUrl(videoId as string) as string
instance = m.GetInstance()
return `${instance}/latest_version?id=${videoId}`
end function
function MarkFeedPagination(contentNode as object) as void
requestData = contentNode.feed
endpoint = m.endpoints[requestData.endpoint]
if endpoint = invalid or endpoint.pagination <> true
return
end if
contentNode.pagination = true
contentNode.page += 1
if not requestData.DoesExist("queryParams")
requestData.queryParams = {}
end if
requestData.queryParams.page = contentNode.page
contentNode.feed = requestData
end function
function MakeRequest(requestData as object, cancellation = invalid as object) as object
endpoint = m.endpoints[requestData.endpoint]
if endpoint = invalid
return {
success: false,
error: `Endpoint ${requestData.endpoint} not found`
}
end if
instance = m.GetInstance()
request = HttpClient.Get(instance + endpoint.url)
if endpoint.authenticated = true
authToken = m.node.authToken
if authToken = invalid
return {
success: false,
error: ERROR_NOT_AUTHENTICATED
}
end if
request.Url(authToken.instance + endpoint.url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
end if
if endpoint.queryParams <> invalid
for each queryParamKey in endpoint.queryParams
queryParam = endpoint.queryParams[queryParamKey]
if queryParam.default <> invalid
if IsString(queryParam.type) and queryParam.type = "#ISO3166"
if queryParam.default = "GetUserCountryCode"
request.QueryParam(queryParamKey, m.node.applicationInfo@.GetUserCountryCode(invalid))
else
request.QueryParam(queryParamKey, queryParam.default)
end if
else if IsArray(queryParam.default)
if queryParam.arrayType = "repeat"
request.QueryParamArray(queryParamKey, queryParam.default, HttpClient.QueryParamArrayType.Repeated)
else if queryParam.arrayType = "comma-separated"
request.QueryParamArray(queryParamKey, queryParam.default, HttpClient.QueryParamArrayType.CommaSeparated)
end if
else
request.QueryParam(queryParamKey, queryParam.default)
end if
end if
end for
end if
if requestData.cacheSeconds <> invalid
request.CacheSeconds(requestData.cacheSeconds)
else if endpoint.cacheSeconds <> invalid
request.CacheSeconds(endpoint.cacheSeconds)
end if
if requestData.queryParams <> invalid
request.QueryParams(requestData.queryParams)
end if
if requestData.pathParams <> invalid
request.PathParams(requestData.pathParams)
end if
request.Cancellation(cancellation)
response = request.Await()
responseHandler = endpoint.responseHandler <> invalid ? m.responseHanlders[endpoint.responseHandler] : m.responseHanlders["DefaultHandler"]
result = responseHandler(m, requestData, response)
if response.IsSuccess() and result <> invalid
return {
success: true,
result: result
}
else
return {
success: false,
error: response.ErrorMessage()
}
end if
end function
function DefaultHandler(m as object, requestData as object, response as object) as object
return response.Json()
end function
function PlaylistHandler(m as object, requestData as object, response as object) as object
if response.StatusCode() = 200
json = response.Json()
return json.videos
end if
return invalid
end function
function ChannelHandler(m as object, requestData as object, response as object) as object
if response.StatusCode() = 200
json = response.Json()
return json.videos
end if
return invalid
end function
function AuthFeedHandler(m as object, requestData as object, response as object) as object
m.DeleteExpiredToken(response)
if response.StatusCode() = 200
json = response.Json()
videos = []
videos.Append(json.notifications)
videos.Append(json.videos)
return videos
end if
return invalid
end function
function DeleteExpiredToken(response as object)
if response.StatusCode() = 403
m.log.warn(`Invidious instance responded with 403: ${response.Text()}`)
m.log.warn("Deleting Invidious token...")
m.DeleteAuthToken()
end if
end function
function GetAuthToken() as object
tokenPayload = RegistryUtils.Read(RegistryUtils.INVIDIOUS_TOKEN)
if tokenPayload = invalid
return invalid
end if
authData = ParseJson(tokenPayload)
if authData = invalid or authData.instance = invalid or authData.token = invalid
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
return invalid
end if
return authData
end function
function SetAuthToken(token as string, instance as string, username as dynamic)
obj = {
token: token,
instance: instance,
username: username
}
json = FormatJson(obj)
RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json)
m.node.authToken = obj
end function
function DeleteAuthToken()
m.node.authToken = invalid
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
end function
function Logout() as boolean
authToken = m.node.authToken
if authToken = invalid
return false
end if
m.UnregisterToken(authToken)
m.DeleteAuthToken()
return true
end function
function UnregisterToken(authToken as object) as void
url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
request = HttpClient.Post(url, authToken.token)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Header("Content-Type", "application/json")
request.SendAndForget()
end function
function GetAuthorizeTokenLink() as dynamic
instance = m.GetInstance()
' Make sure the host is not on https, because https cannot redirect to http, which is our local server
invidiousHost = instance.Replace("https://", "http://")
address = m.node.webServer@.GetServerAddress()
if address = invalid
return invalid
end if
expire = TimeUtils.Now().AsSeconds() + Invidious.TOKEN_TIMESPAN
callbackUrl = `${address}${Invidious.TOKEN_CALLBACK}?ref=${instance}`.EncodeUriComponent()
scope = `${Invidious.AUTH_SCOPES}`.EncodeUriComponent()
return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
end function
end class
end namespace
@@ -0,0 +1,211 @@
import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/components/VideoFeed/FeedLoadState.bs"
namespace InvidiousContent
function ToRowCellContentNode(item as object, instance as dynamic) as object
if item.videoId <> invalid and (item.type = invalid or item.type = "shortVideo")
item.type = "video"
end if
if item.playlistId <> invalid and (item.type = invalid or item.type = "invidiousPlaylist")
item.type = "playlist"
end if
if item.type <> "video" and item.type <> "playlist" and item.type <> "channel"
return invalid
end if
if item.type = "video"
return ToVideoContentNode(invalid, item, instance)
else if item.type = "playlist"
return ToPlaylistContentNode(invalid, item, instance)
else if item.type = "channel"
return invalid
' return ToChannelContentNode(item, instance)
else
return invalid
end if
end function
function ToVideoContentNode(node as object, item as object, instance as dynamic) as object
if node = invalid
node = CreateObject("roSGNode", "VideoContentNode")
end if
node.type = "video"
SetIfExists(node, "author", item, "author")
SetIfExists(node, "hlsUrl", item, "hlsUrl")
SetIfExists(node, "isUpcoming", item, "isUpcoming")
SetIfExists(node, "lengthSeconds", item, "lengthSeconds")
node.lengthText = TimeUtils.GetFormattedTime(item.lengthSeconds)
node.liveNow = VideoIsLive(item)
VideoSetPremiereTimestampText(node, item)
SetIfExists(node, "publishedText", item, "publishedText")
if not StringUtils.IsNullOrEmpty(instance)
node.thumbnail = VideoGetThumbnail(item, instance) ?? "pkg:/images/thumbnail-missing.jpg"
end if
SetIfExists(node, "title", item, "title")
SetIfExists(node, "timestamp", item, "timestamp")
SetIfExists(node, "videoId", item, "videoId")
node.viewCountText = VideoGetViewCountText(item)
SetIfExists(node, "index", item, "index")
return node
end function
function ToPlaylistContentNode(node as object, item as object, instance as dynamic) as object
if node = invalid
node = CreateObject("roSGNode", "PlaylistContentNode")
node.loadState = FeedLoadState.None
end if
node.type = "playlist"
' NOTE: "_author" not "author". See PlaylistContentNode.xml for explanation.
SetIfExists(node, "_author", item, "author")
SetIfExists(node, "description", item, "description")
SetIfExists(node, "playlistId", item, "playlistId")
SetIfExists(node, "title", item, "title")
SetIfExists(node, "videoCount", item, "videoCount")
node.videoCountText = PlaylistGetVideoCountText(item)
SetIfExists(node, "viewCount", item, "viewCount")
node.viewCountText = PlaylistGetViewCountText(item)
if item.videos <> invalid
childCount = node.getChildCount()
newNodes = []
for each video in item.videos
video.type = "video"
videoNode = ToVideoContentNode(invalid, video, instance)
if videoNode <> invalid
index = video.index
if index <> invalid and index > -1 and index < childCount
node.replaceChild(videoNode, index)
else
newNodes.push(videoNode)
end if
end if
end for
if newNodes.Count() > 0
node.appendChildren(newNodes)
end if
end if
PlaylistSetThumbnail(node, "thumbnail", item, instance)
PlaylistSetThumbnail(node, "thumbnailBackground", item, instance, "maxres")
return node
end function
function ToChannelContentNode(item as object, instance as dynamic) as object
node = CreateObject("roSGNode", "ChannelContentNode")
node.type = "channel"
return node
end function
function SetIfExists(dst as object, dstField as string, src as object, srcField as string)
if src.DoesExist(srcField)
dst[dstField] = src[srcField]
end if
end function
function VideoGetThumbnail(videoItem as object, instance as dynamic, quality = "medium" as string) as dynamic
videoThumbnails = videoItem.videoThumbnails
if videoThumbnails = invalid or videoThumbnails.Count() = 0
return invalid
end if
url = invalid
for each thumbnail in videoThumbnails
if thumbnail.quality = quality
url = thumbnail.url
exit for
end if
end for
if url = invalid
url = videoThumbnails[0].url
end if
if url.startsWith("/") and not StringUtils.IsNullOrEmpty(instance)
url = instance + url
end if
return url
end function
function VideoIsLive(videoItem as object) as boolean
if videoItem.liveNow = true
return true
end if
' TODO:P2 metadata.liveNow is returning false for live videos...
return videoItem.lengthSeconds = 0 and videoItem.viewCount = 0
end function
function VideoIsUpcoming(videoItem as object) as boolean
return videoItem.isUpcoming = true
end function
function VideoSetPremiereTimestampText(node as object, videoItem as object)
if VideoIsUpcoming(videoItem) and videoItem.premiereTimestamp <> invalid
node.premiereTimestampText = `Premeres in ${TimeUtils.GetFormattedTimeLeft(videoItem.premiereTimestamp)}`
end if
end function
function VideoGetViewCountText(videoItem as object) as string
viewCount = videoItem.viewCount
if viewCount = invalid
return ""
end if
if viewCount < 1000
return `${FormatFloat(viewCount)} views`
end if
viewCount = viewCount / 1000
if viewCount < 1000
return `${FormatFloat(viewCount)}K views`
end if
viewCount = viewCount / 1000
if viewCount < 1000
return `${FormatFloat(viewCount)}M views`
end if
viewCount = viewCount / 1000
return `${FormatFloat(viewCount)}B views`
end function
function FormatFloat(X as float) as float
X = X * 10
X = X + 0.5
X = Fix(X)
X = X / 10
return X
end function
function PlaylistSetThumbnail(node as object, nodeField as string, playlistItem as object, instance as dynamic, quality = "medium" as string) as void
thumbnail = ""
if IsString(playlistItem.playlistThumbnail)
thumbnailUrl = playlistItem.playlistThumbnail
if thumbnailUrl.startsWith("/") and not StringUtils.IsNullOrEmpty(playlistItem.instance)
thumbnailUrl = playlistItem.instance + thumbnailUrl
end if
thumbnail = thumbnailUrl
else if playlistItem.videos <> invalid and playlistItem.videos.Count() > 0 and playlistItem.videos[0].index = 0
thumbnail = VideoGetThumbnail(playlistItem.videos[0], instance, quality)
else if node.getChildCount() > 0
thumbnail = node.getChild(0).thumbnail
end if
if StringUtils.IsNullOrEmpty(thumbnail)
thumbnail = "pkg:/images/thumbnail-missing.jpg"
end if
node[nodeField] = thumbnail
end function
function PlaylistGetVideoCountText(playlistItem as object) as string
videoCount = ValidInt(playlistItem.videoCount)
return videoCount = 1 ? "1 video" : `${videoCount} videos`
end function
function PlaylistGetViewCountText(playlistItem as object) as string
return VideoGetViewCountText(playlistItem)
end function
end namespace
@@ -0,0 +1,169 @@
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.disableSavingToRegistry = false
LoadPreferencesFile()
AddNodeFields()
LoadUserPreferencesFromRegistry()
AddNodeFieldsObservers()
end function
function LoadPreferencesFile()
m.top.prefsModel = ParseJson(ReadAsciiFile("libpkg:/config/preferences.json5"))
end function
function AddNodeFields()
fields = {}
prefsModel = m.top.prefsModel
for each child in prefsModel
AddNodeFieldsFromPreference(child, fields)
end for
' We keep reference to fields specific to preferences, to avoid default fields like focusedChild
m.top.preferenceFields = fields
end function
function AddNodeFieldsFromPreference(pref as object, fields as object)
if pref.key <> invalid and pref.type <> invalid
fieldType = ""
if pref.type = "boolean"
fieldType = "boolean"
else if pref.type = "string"
fieldType = "string"
else if pref.type = "radio"
fieldType = "string"
end if
m.top.addField(pref.key, fieldType, false)
fields[pref.key] = true
end if
if pref.children <> invalid
for each child in pref.children
AddNodeFieldsFromPreference(child, fields)
end for
end if
end function
function AddNodeFieldsObservers()
prefsFields = m.top.preferenceFields
for each key in prefsFields
m.top.observeField(key, FuncName(SaveUserPreferencesToRegistry))
end for
end function
function LoadUserPreferencesFromRegistry()
' Step 1: Load user preferences from registry
userPrefs = RegistryUtils.Read(RegistryUtils.USER_PREFERENCES)
if userPrefs = invalid
userPrefs = {}
else
userPrefs = ParseJson(userPrefs)
end if
' Step 2: Migrate existing preferences to new format (if needed)
isDirty = MigrateExistingPreferences(userPrefs)
' Step 3: Apply defaults to user preferences (if needed)
isDirty = ApplyDefaultsToUserPreferences(userPrefs) or isDirty
' Step 4: set field values in node
for each key in userPrefs
m.top[key] = userPrefs[key]
end for
' Step 5: Save user preferences (if needed)
if isDirty
SaveUserPreferencesToRegistry()
end if
end function
function SaveUserPreferencesToRegistry() as void
if m.disableSavingToRegistry
return
end if
userPrefs = {}
prefsFields = m.top.preferenceFields
for each key in prefsFields
userPrefs[key] = m.top[key]
end for
userPrefs.__version = m.top.__version
RegistryUtils.Write(RegistryUtils.USER_PREFERENCES, FormatJson(userPrefs))
end function
function MigrateExistingPreferences(userPrefs as object) as boolean
isDirty = false
' v0 -> v1
instances = RegistryUtils.Read(RegistryUtils.INVIDIOUS_INSTANCES)
if instances <> invalid
currentInstance = userPrefs["invidious.instance"]
if currentInstance = invalid or currentInstance = ""
instances = ParseJson(instances)
if instances.Count() > 0
instance = instances[0]
if instance <> invalid and instance <> ""
userPrefs["invidious.instance"] = instance
isDirty = true
end if
end if
end if
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_INSTANCES)
end if
' v1 -> v2 goes here (if needed)
' if userPrefs.__version = 1
' 'do stuff
' end if
' TODO:PX handle case where saved preferences version is higher than current version (e.g. user downgraded)
return isDirty
end function
function ApplyDefaultsToUserPreferences(userPrefs as object) as boolean
isDirty = false
prefsModel = m.top.prefsModel
for each child in prefsModel
isDirty = ApplyToUserPreferences(userPrefs, child) or isDirty
end for
return isDirty
end function
function ApplyToUserPreferences(userPrefs as object, model as object) as boolean
isDirty = false
if model.children <> invalid
for each child in model.children
isDirty = ApplyToUserPreferences(userPrefs, child) or isDirty
end for
end if
if model.defaultValue <> invalid and (not userPrefs.DoesExist(model.key) or userPrefs[model.key] = invalid)
userPrefs[model.key] = model.defaultValue
isDirty = true
end if
return isDirty
end function
function GetUserPreferences(unused as dynamic) as object
userPrefs = {}
prefsFields = m.top.preferenceFields
for each key in prefsFields
userPrefs[key] = m.top[key]
end for
userPrefs.__version = m.top.__version
return userPrefs
end function
function ApplyUserPreferences(preferences as object) as void
if preferences = invalid
return
end if
' TODO:P2 user input validation
m.disableSavingToRegistry = true
m.top.setFields(preferences)
m.disableSavingToRegistry = false
SaveUserPreferencesToRegistry()
end function
function ClearUserPreferences(unused as dynamic) as void
userPrefs = {}
ApplyDefaultsToUserPreferences(userPrefs)
ApplyUserPreferences(userPrefs)
end function
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="Preferences" extends="Node">
<interface>
<field id="__version" type="integer" value="1" />
<field id="prefsModel" type="array" />
<field id="preferenceFields" type="assocarray" />
<function name="GetUserPreferences" />
<function name="ApplyUserPreferences" />
<function name="ClearUserPreferences" />
</interface>
</component>
@@ -0,0 +1,60 @@
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
function Init()
m.categoryLabel = m.top.findNode("categoryLabel")
m.translationAnimation = m.top.findNode("translationAnimation")
m.translationAnimationInterpolator = m.top.findNode("translationAnimationInterpolator")
m.animationTimer = m.top.findNode("animationTimer")
m.top.translation = [1280, 20]
m.translationAnimation.observeField("state", "OnAnimationState")
m.animationTimer.observeField("fire", "OnAnimationTimer")
m.service = SponsorBlock.SponsorBlockService()
end function
function OnActionSet()
action = m.top.action
category = m.top.segment.category
categoryTitle = m.service.SegmentShortTitle(category)
if action = "AutoSkip"
m.categoryLabel.text = `Skipped\n${categoryTitle}`
else
m.categoryLabel.text = categoryTitle
end if
AnimateIn()
end function
function OnAnimationTimer()
AnimateOut()
end function
function AnimateIn()
m.translationAnimation.unobserveField("state")
m.animationTimer.control = "stop"
m.animationTimer.control = "start"
m.translationAnimation.observeField("state", "OnAnimationState")
Animate(false)
end function
function AnimateOut()
Animate(true)
end function
function Animate(reverse as boolean) as void
' We are already animating in the requested direction
if m.translationAnimationInterpolator.reverse = reverse and m.translationAnimation.control <> "none"
return
end if
m.translationAnimationInterpolator.reverse = reverse
m.translationAnimation.control = "start"
end function
function OnAnimationState()
if m.translationAnimation.state = "stopped" and m.translationAnimationInterpolator.reverse = true
m.top.getParent().removeChild(m.top)
end if
end function
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="SponsorBlockNotification" extends="Group">
<interface>
<field id="segment" type="assocarray" onChange="OnSegmentSet" />
<field id="action" type="string" onChange="OnActionSet" alwaysNotify="true" />
</interface>
<children>
<Poster
width="250"
height="70"
opacity="0.8"
blendColor="#414141"
uri="pkg:/images/white.9.png">
<Poster
uri="libpkg:/images/LogoSponsorBlockSimple256px.png"
width="50"
height="50"
translation="[10,10]">
</Poster>
<Label
id="categoryLabel"
text="..."
font="font:SmallestBoldSystemFont"
lineSpacing="5"
horizAlign="center"
vertAlign="center"
wrap="true"
width="170"
height="70"
translation="[70,0]">
</Label>
</Poster>
<Animation
id="translationAnimation"
duration="0.3"
optional="true">
<Vector2DFieldInterpolator
id="translationAnimationInterpolator"
key="[0.0, 0.5, 1.0]"
keyValue="[ [1280.0, 20.0], [1140.0, 20.0], [1000.0, 20.0] ]"
fieldToInterp="SponsorBlockNotification.translation" />
</Animation>
<Timer
id="animationTimer"
duration="3"
/>
</children>
</component>
@@ -0,0 +1,32 @@
import "pkg:/components/VideoPlayer/VideoUtils.bs"
namespace SponsorBlock
const NOTIFICATION_NODE_ID = "SponsorBlockNotification"
function ShowNotifcation(notifications as object, segment as object, action as dynamic) as void
' TODO:P2 avoid finding the node over and over
' The video player can probably own a single notification, and destroy it when the video is closed
notification = notifications.findNode(NOTIFICATION_NODE_ID)
if notification = invalid
notification = notifications.createChild("SponsorBlockNotification")
notification.id = NOTIFICATION_NODE_ID
end if
notification.segment = segment
notification.action = action
end function
function RemoveNotifcation(notifications as object) as void
notification = notifications.findNode(NOTIFICATION_NODE_ID)
if notification <> invalid
notifications.RemoveChild(notification)
end if
end function
function SetVisible(notifications as object, visible as boolean)
notification = notifications.findNode(NOTIFICATION_NODE_ID)
if notification <> invalid
notification.visible = visible
end if
end function
end namespace
@@ -0,0 +1,9 @@
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
@asynctask
function SponsorBlockSegmentViewedTask(input as object)
segmentId = input.segmentId
service = new SponsorBlock.SponsorBlockService()
service.PostSegmentViewed(segmentId)
end function
@@ -0,0 +1,122 @@
import "pkg:/source/utils/ColorUtils.bs"
import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/services/HttpClient.bs"
namespace SponsorBlock
const SKIP_SEGMENT_ENDPOINT = "/api/skipSegments"
const VIEWED_SEGMENT_ENDPOINT = "/api/viewedVideoSponsorTime"
class SponsorBlockService
function new()
m.sponsorBlockConfig = ParseJson(ReadAsciiFile("libpkg:/config/sponsorblock_config.json5"))
end function
function SegmentColor(category as string) as integer
if m.sponsorBlockConfig = invalid
return 0
end if
if not m.sponsorBlockConfig.categories.doesexist(category)
return 0
end if
color = m.sponsorBlockConfig.categories[category].color
return ColorUtils.HexToInt(color)
end function
function SegmentTitle(category as string) as string
if m.sponsorBlockConfig = invalid
return category
end if
if not m.sponsorBlockConfig.categories.doesexist(category)
return category
end if
return m.sponsorBlockConfig.categories[category].title
end function
function SegmentShortTitle(category as string) as string
if m.sponsorBlockConfig = invalid
return category
end if
if not m.sponsorBlockConfig.categories.doesexist(category)
return category
end if
return m.sponsorBlockConfig.categories[category].short_title
end function
function GetSkipSegmentsForVideo(videoId as string) as object
if m.sponsorBlockConfig = invalid or StringUtils.IsNullOrEmpty(m.sponsorBlockConfig.serverAddress)
return invalid
end if
categories = ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "poi_highlight", "chapter", "filler", "exclusive_access"]
actionTypes = ["skip", "mute", "chapter", "full", "poi"]
categoriesJson = FormatJson(categories).EncodeUriComponent()
actionTypesJson = FormatJson(actionTypes).EncodeUriComponent()
' From SponsorBlock docs: It should be the first 4 - 32 characters (4 is recommended).
hashPrefix = CryptoUtils.GetSha256(videoId).Left(4)
url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.SKIP_SEGMENT_ENDPOINT}/${hashPrefix}?categories=${categoriesJson}&actionTypes=${actionTypesJson}`
response = HttpClient.Get(url).Await()
json = response.Json()
if json = invalid
return invalid
end if
for each item in json
if item.videoId = videoId
return item.segments
end if
end for
return invalid
end function
function PostSegmentViewed(segmentId as string) as void
if m.sponsorBlockConfig = invalid or StringUtils.IsNullOrEmpty(m.sponsorBlockConfig.serverAddress)
return
end if
url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}`
HttpClient.Post(url, "").SendAndForget()
end function
function GenerateProgressBarBackground(segments as object, lengthSeconds as integer, path as string)
bar = CreateObject("roBitmap", { width: 1000, height: 20, AlphaEnable: true })
bar.Clear(&hFFFFFF80)
width = bar.GetWidth()
height = bar.GetHeight()
for each segment in segments
videoDuration = lengthSeconds
if videoDuration = 0 or videoDuration = invalid
' We should ignore segment.videoDuration https://github.com/iBicha/playlet/pull/23#issuecomment-1431520676
' But in case where we don't have lengthSeconds from Invidious, it's better than nothing
videoDuration = segment.videoDuration
end if
if videoDuration = 0 or videoDuration = invalid
continue for
end if
pixelStart = (segment.segment[0] / videoDuration) * width
pixelEnd = (segment.segment[1] / videoDuration) * width
color = m.SegmentColor(segment.category)
' highlight's duration is zero, so it is not visble on the bar.
' Add a couple of pixels to see it
if pixelStart = pixelEnd
pixelEnd += 2
end if
bar.DrawRect(pixelStart, 0, pixelEnd - pixelStart, height, color)
end for
bar.Finish()
buffer = bar.GetPng(0, 0, width, height)
buffer.WriteFile(path)
end function
end class
end namespace
@@ -0,0 +1,22 @@
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
@asynctask
function SponsorBlockTask(input as object) as object
videoId = input.metadata.videoId
lengthSeconds = input.metadata.lengthSeconds
service = new SponsorBlock.SponsorBlockService()
skipSegments = service.GetSkipSegmentsForVideo(videoId)
barPath = invalid
if skipSegments <> invalid
barPath = `tmp:/sponsorblock_bar_${videoId}.png`
service.GenerateProgressBarBackground(skipSegments, lengthSeconds, barPath)
end if
return {
videoId: videoId,
skipSegments: skipSegments,
barPath: barPath
}
end function