SponsorBlock categories (#634)

* SponsorBlock categories

* perf

* remove todo

* tweak

* UI is working

* Lint fix

* changelog

* Bug fix

* Restore timer

* Locale

* Comment

* tweaks

* web app

* remove unsued svelte ignore

* lint web app

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
Brahim Hadricheandgithub-action linter authored and GitHub committed 2025-06-01 15:30:58 -04:00
1 parent 0bc5ab6117
commit fcae05a0da
34 files changed
+1039 -422

No files matched your search

+2
View File
@@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- German translations - German translations
- Support for multi-accounts, such as brand accounts - Support for multi-accounts, such as brand accounts
- Support for manual skip in SponsorBlock
- Customize SponsorBlock categories from the settings
### Fixed ### Fixed
+2 -3
View File
@@ -47,8 +47,8 @@
"build:lib:dev": "cd playlet-lib && npm run build:dev", "build:lib:dev": "cd playlet-lib && npm run build:dev",
"build:lib:prod": "cd playlet-lib && npm run build:prod", "build:lib:prod": "cd playlet-lib && npm run build:prod",
"build:web": "cd playlet-web && npm run build", "build:web": "cd playlet-web && npm run build",
"lint": "cd playlet-lib && npm run lint && cd ../playlet-app && npm run lint", "lint": "cd playlet-lib && npm run lint && cd ../playlet-app && npm run lint && cd ../playlet-web && npm run lint",
"lint:fix": "cd playlet-lib && npm run lint:fix && cd ../playlet-app && npm run lint:fix", "lint:fix": "cd playlet-lib && npm run lint:fix && cd ../playlet-app && npm run lint:fix && cd ../playlet-web && npm run lint",
"format": "cd playlet-lib && npm run format && cd ../playlet-app && npm run format", "format": "cd playlet-lib && npm run format && cd ../playlet-app && npm run format",
"format:fix": "cd playlet-lib && npm run format:fix && cd ../playlet-app && npm run format:fix", "format:fix": "cd playlet-lib && npm run format:fix && cd ../playlet-app && npm run format:fix",
"test": "npm run test:lib && npm run test:app", "test": "npm run test:lib && npm run test:app",
@@ -62,7 +62,6 @@
"manifest-git-hash": "node tools/update-manifest-git-hash.js", "manifest-git-hash": "node tools/update-manifest-git-hash.js",
"sign-released-package": "node tools/sign-released-package.js", "sign-released-package": "node tools/sign-released-package.js",
"screenshot": "node tools/screenshot.js", "screenshot": "node tools/screenshot.js",
"generate-sponsorblock-config": "node tools/generate-sponsorblock-config.js",
"convert-images": "node tools/convert-images.js", "convert-images": "node tools/convert-images.js",
"update-rale-component": "cd tools/RALE && rm TrackerTask.xml && curl -o TrackerTask.zip https://devtools.web.roku.com/roku-advanced-layout-editor/app/TrackerTask.zip && unzip TrackerTask.zip && rm TrackerTask.zip", "update-rale-component": "cd tools/RALE && rm TrackerTask.xml && curl -o TrackerTask.zip https://devtools.web.roku.com/roku-advanced-layout-editor/app/TrackerTask.zip && unzip TrackerTask.zip && rm TrackerTask.zip",
"postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playlet-web && npm install", "postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playlet-web && npm install",
@@ -24,8 +24,6 @@ end function
function PrepareTests() as object function PrepareTests() as object
content = CreateObject("roSGNode", "ContentNode") content = CreateObject("roSGNode", "ContentNode")
' TODO:P2 test if video data is reachable (head?)
' TODO:P2 test if video data is reachable in proxy mode (local=true)
content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.ValidUrl), IsValidUrl)) content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.ValidUrl), IsValidUrl))
content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.InstanceReachable), IsReachable)) content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.InstanceReachable), IsReachable))
content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.FetchVideoDetails), CanFetchVideoDetails)) content.AppendChild(CreateTestNode(Tr(Locale.InvidiousTesting.FetchVideoDetails), CanFetchVideoDetails))
@@ -0,0 +1,79 @@
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/source/utils/FocusManagement.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.top.focusable = true
m.top.itemSpacings = [8]
m.button = m.top.findNode("button")
m.button.observeField("buttonSelected", FuncName(OpenSponsorBlockCategories))
AdjustButtonLabel(m.button)
end function
function OnFocusChange() as void
if not m.top.focus
return
end if
NodeSetFocus(m.button, true)
end function
function AdjustButtonLabel(button as object) as void
children = button.getChildren(-1, 0)
for each child in children
if child.isSubtype("Label") and child.hasField("horizAlign")
child.observeField("horizAlign", FuncName(OnButtonLabelHorizAlignChanged))
child.horizAlign = "left"
return
end if
end for
end function
function OnButtonLabelHorizAlignChanged(event as object)
label = event.getRoSGNode()
if label.horizAlign <> "left"
label.horizAlign = "left"
end if
end function
function BindPreference(preferences as object, key as string)
if m.preferences <> invalid and m.key <> invalid
m.preferences.unobserveFieldScoped(m.key)
end if
m.preferences = preferences
m.key = key
if preferences <> invalid and key <> invalid
preferences.observeFieldScoped(key, FuncName(OnPreferenceChange))
OnPreferenceChange()
end if
end function
function OpenSponsorBlockCategories()
categoriesPrefs = CreateObject("roSGNode", "SponsorBlockCategoriesPreferences")
m.appController@.PushScreen(categoriesPrefs)
categoriesPrefs@.BindNode()
categoriesPrefs.value = m.top.value
categoriesPrefs.observeField("save", FuncName(OnSaveCategoriesPreferences))
end function
function OnSaveCategoriesPreferences(event as object)
categoriesPrefs = event.GetRoSGNode()
m.top.value = categoriesPrefs.value
end function
function OnPreferenceChange()
m.top.value = m.preferences[m.key]
end function
function OnValueChange() as void
if m.preferences = invalid or m.key = invalid
return
end if
m.preferences[m.key] = m.top.value
end function
@@ -0,0 +1,21 @@
<component name="SponsorBlockCategoriesControl" extends="LayoutGroup" includes="AutoBind,Focus">
<interface>
<field id="displayText" type="string" alias="Button.text" />
<field id="description" type="string" alias="DescriptionLabel.text" />
<field id="value" type="assocarray" onChange="OnValueChange" />
<field id="appController" type="node" bind="/AppController" />
<function name="BindPreference" />
</interface>
<children>
<Button
id="button"
minWidth="300"
showFocusFootprint="true" />
<Label id="DescriptionLabel"
width="450"
color="0xb4b4b4ff"
wrap="true">
<Font role="font" uri="font:SystemFontFile" size="18" />
</Label>
</children>
</component>
@@ -0,0 +1,181 @@
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Navigation/Navigation.bs"
import "pkg:/components/parts/AutoBind/OnNodeReadyNoOp.bs"
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
import "pkg:/components/VideoPlayer/SponsorBlockSegmentAction.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/RemoteKeys.bs"
import "pkg:/source/utils/Types.bs"
function Init()
m.categoryList = m.top.findNode("categoryList")
m.categoryList.ObserveField("itemSelected", FuncName(OnCategorySelected))
m.service = new SponsorBlock.SponsorBlockService()
optionTitles = {}
optionTitles[SponsorBlock.SegmentAction.Disable] = Tr(Locale.SponsorBlock.Disable)
optionTitles[SponsorBlock.SegmentAction.AutoSkip] = Tr(Locale.SponsorBlock.AutoSkip)
optionTitles[SponsorBlock.SegmentAction.ManualSkip] = Tr(Locale.SponsorBlock.ManualSkip)
optionTitles[SponsorBlock.SegmentAction.ShowInSeekbar] = Tr(Locale.SponsorBlock.ShowInSeekbar)
m.optionTitles = optionTitles
SetupCategoriesUi()
m.closeButton = m.top.findNode("closeButton")
m.saveButton = m.top.findNode("saveButton")
SetButtonPositions()
SetNavigation(m.saveButton, RemoteKeys.Right, m.closeButton)
SetNavigation(m.closeButton, RemoteKeys.Left, m.saveButton)
SetNavigation(m.saveButton, RemoteKeys.Up, m.categoryList)
SetNavigation(m.closeButton, RemoteKeys.Up, m.categoryList)
SetNavigation(m.categoryList, RemoteKeys.Down, m.saveButton)
m.saveButton.observeField("buttonSelected", FuncName(OnSaveButtonSelected))
m.closeButton.observeField("buttonSelected", FuncName(Close))
end function
function SetupCategoriesUi() as void
categories = m.service.GetCategories()
if categories.Count() = 0
return
end if
content = CreateObject("roSGNode", "ContentNode")
categoryContentNodes = []
for each category in categories
categoryNode = CreateObject("roSGNode", "SponsorBlockCategoryContent")
categoryNode.category = category
categoryNode.categoryTitle = Tr(m.service.SegmentTitle(category))
categoryNode.selectedOption = SponsorBlock.SegmentAction.Disable
categoryNode.options = m.service.GetOptionsForCategory(category)
categoryNode.optionTitles = m.optionTitles
categoryNode.color = m.service.SegmentColor(category)
categoryContentNodes.push(categoryNode)
end for
content.appendChildren(categoryContentNodes)
m.categoryList.content = content
end function
function SetButtonPositions()
saveButtonWidth = m.saveButton.width
closeButtonWidth = m.closeButton.width
buttonsWith = closeButtonWidth + saveButtonWidth + 20
m.saveButton.translation = [720 / 2 - buttonsWith / 2, m.saveButton.translation[1]]
m.closeButton.translation = [720 / 2 + buttonsWith / 2 - closeButtonWidth, m.closeButton.translation[1]]
end function
function OnFocusChange() as void
if not m.top.focus
return
end if
NodeSetFocus(m.categoryList, true)
end function
function OnKeyEvent(key as string, press as boolean) as boolean
if NavigationKeyHandler(key, press).handled
return true
end if
if key = RemoteKeys.Options or key = RemoteKeys.Play or key = RemoteKeys.Pause or key = RemoteKeys.PlayOnly
' A pass-through to the app controller, so it can toggle picture-in-picture and pause/play
return false
end if
if key = RemoteKeys.Back and press
Close()
return true
end if
return true
end function
function OnValueChange() as void
content = m.categoryList.content
if content = invalid
return
end if
value = m.top.value
if not IsAssociativeArray(value)
return
end if
categoryContentNodes = content.getChildren(-1, 0)
categoryNodeMap = {}
for each categoryContentNode in categoryContentNodes
categoryNodeMap[categoryContentNode.category] = categoryContentNode
end for
for each category in value
if not categoryNodeMap.DoesExist(category)
continue for
end if
categoryNode = categoryNodeMap[category]
if categoryNode = invalid
continue for
end if
categoryNode.selectedOption = value[category].option
end for
end function
function OnSaveButtonSelected()
m.top.save = true
Close()
end function
function Close()
m.appController@.PopScreen()
end function
function OnCategorySelected(event as object) as void
itemSelected = m.categoryList.itemSelected
itemNode = m.categoryList.content.GetChild(itemSelected)
if itemNode = invalid
LogError("Invalid item selected:", itemSelected)
return
end if
options = itemNode.options
optionTitles = itemNode.optionTitles
optionTitlesArray = []
for each option in options
optionTitlesArray.push(optionTitles[option])
end for
dialog = DialogUtils.ShowDialogEx({
title: itemNode.categoryTitle
message: Tr(Locale.Settings.SelectOptionFor).Replace("%1", itemNode.categoryTitle)
buttons: optionTitlesArray
})
if dialog = invalid
return
end if
dialog.addFields({
"categoryContentNode": itemNode
"options": options
})
dialog.observeField("buttonSelected", FuncName(OnCategoryDialogResult), ["buttonSelected"])
end function
function OnCategoryDialogResult(event as object) as void
dialog = event.getRoSGNode()
options = dialog.options
buttonIndex = event.GetData()
if not IsInt(buttonIndex) or buttonIndex < 0 or buttonIndex >= options.Count()
return
end if
selectedOption = options[buttonIndex]
category = dialog.categoryContentNode.category
value = m.top.value
value[category].option = selectedOption
m.top.value = value
LogInfo("SponsorBlock category", category, "set to", selectedOption)
end function
@@ -0,0 +1,52 @@
<component name="SponsorBlockCategoriesPreferences" extends="Group" includes="AutoBind,Focus">
<interface>
<field id="value" type="assocarray" onChange="OnValueChange" />
<field id="save" type="boolean" alwaysNotify="true" />
<field id="appController" type="node" bind="/AppController" />
</interface>
<children>
<Rectangle
width="1280"
height="720"
color="#000000"
opacity="0.5">
</Rectangle>
<Rectangle
width="720"
height="600"
translation="[300,60]"
color="#242424">
<Label
width="720"
horizAlign="center"
translation="[0,38]"
text="Categories">
<Font role="font" uri="font:SystemFontFile" size="24" />
</Label>
<MarkupGrid
id="categoryList"
itemComponentName="SponsorBlockCategoryListItem"
itemSize="[640,32]"
itemSpacing="[0,10]"
numColumns="1"
numRows="10"
vertFocusAnimationStyle="floatingFocus"
translation="[40,100]"
focusBitmapUri="pkg:/images/focus-glow-padding-19.9.png" />
<ButtonEx
id="saveButton"
iconVisible="false"
text="Save"
padding="[30,30]"
translation="[340,500]" />
<ButtonEx
id="closeButton"
iconVisible="false"
text="Close"
padding="[30,30]"
translation="[496,500]" />
</Rectangle>
</children>
</component>
@@ -0,0 +1,10 @@
<component name="SponsorBlockCategoryContent" extends="ContentNode">
<interface>
<field id="category" type="string" />
<field id="categoryTitle" type="string" />
<field id="selectedOption" type="string" />
<field id="options" type="stringarray" />
<field id="optionTitles" type="assocarray" />
<field id="color" type="color" />
</interface>
</component>
@@ -0,0 +1,11 @@
function OnContentSet() as void
content = m.top.itemContent
if content = invalid
return
end if
m.top.categoryTitle = content.categoryTitle
optionTitles = content.optionTitles
m.top.optionTitle = optionTitles[content.selectedOption]
m.top.color = content.color
end function
@@ -0,0 +1,30 @@
<component name="SponsorBlockCategoryListItem" extends="Group">
<interface>
<field id="itemContent" type="node" onChange="OnContentSet" />
<field id="categoryTitle" type="string" alias="categoryLabel.text" />
<field id="optionTitle" type="string" alias="optionLabel.text" />
<field id="color" type="color" alias="colorRect.color" />
</interface>
<children>
<Rectangle id="colorRect"
width="52"
height="28"
translation="[10, 2]" />
<Label id="categoryLabel"
font="font:SmallestSystemFont"
width="320"
height="32"
vertAlign="center"
horizAlign="left"
translation="[80, 0]" />
<Label id="optionLabel"
width="320"
height="32"
font="font:SmallestSystemFont"
vertAlign="center"
horizAlign="right"
translation="[310, 0]" />
</children>
</component>
@@ -9,6 +9,7 @@ function Init()
"number": "integer" "number": "integer"
"radio": "string" "radio": "string"
"array": "array" "array": "array"
"assocarray": "assocarray"
} }
m.disableSavingToRegistry = false m.disableSavingToRegistry = false
@@ -1,4 +1,5 @@
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs" import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
import "pkg:/components/VideoPlayer/SponsorBlockSegmentAction.bs"
function Init() function Init()
m.categoryLabel = m.top.findNode("categoryLabel") m.categoryLabel = m.top.findNode("categoryLabel")
@@ -13,16 +14,7 @@ function Init()
m.service = SponsorBlock.SponsorBlockService() m.service = SponsorBlock.SponsorBlockService()
end function end function
function OnActionSet() function OnDoShow() as void
action = m.top.action
category = m.top.segment.category
categoryTitle = Tr(ValidString(m.service.SegmentShortTitle(category)))
if action = "AutoSkip"
m.categoryLabel.text = Tr(Locale.SponsorBlock.Skipped) + `\n` + categoryTitle
else
m.categoryLabel.text = categoryTitle
end if
AnimateIn() AnimateIn()
end function end function
@@ -1,7 +1,9 @@
<component name="SponsorBlockNotification" extends="Group"> <component name="SponsorBlockNotification" extends="Group">
<interface> <interface>
<field id="segment" type="assocarray" /> <field id="segmentId" type="string" />
<field id="action" type="string" onChange="OnActionSet" alwaysNotify="true" /> <field id="categoryText" type="string" alias="categoryLabel.text" />
<field id="actionText" type="string" alias="actionLabel.text" />
<field id="doShow" type="boolean" onChange="OnDoShow" alwaysNotify="true" />
</interface> </interface>
<children> <children>
<Poster <Poster
@@ -16,18 +18,26 @@
height="50" height="50"
translation="[10,10]"> translation="[10,10]">
</Poster> </Poster>
<!-- bs:disable-next-line LOCALE_MISSING_TRANSLATIONS --> <LayoutGroup vertAlignment="center" translation="[70,35]">
<Label text="..." <Label
id="categoryLabel" id="categoryLabel"
font="font:SmallestBoldSystemFont" font="font:TinyBoldSystemFont"
lineSpacing="5" horizAlign="center"
horizAlign="center" width="170"
vertAlign="center" lineSpacing="0"
wrap="true" maxLines="2"
width="170" wrap="true">
height="70" </Label>
translation="[70,0]"> <Label
</Label> id="actionLabel"
font="font:TinySystemFont"
horizAlign="center"
width="170"
lineSpacing="0"
maxLines="2"
wrap="true">
</Label>
</LayoutGroup>
</Poster> </Poster>
<Animation <Animation
id="translationAnimation" id="translationAnimation"
@@ -1,27 +1,43 @@
namespace SponsorBlock namespace SponsorBlock
const NOTIFICATION_NODE_ID = "SponsorBlockNotification" const NOTIFICATION_NODE_ID = "SponsorBlockNotification"
function GetCurrentNotification(notifications as object) as object
childCount = notifications.getChildCount()
for i = 0 to childCount - 1
child = notifications.getChild(i)
if child.id = NOTIFICATION_NODE_ID
return child
end if
end for
return invalid
end function
function ShowNotifcation(notifications as object, segment as object, action as dynamic) as void function ShowNotifcation(notifications as object, segment as object, action as dynamic) as void
' TODO:P2 avoid finding the node over and over ' 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 ' The video player can probably own a single notification, and destroy it when the video is closed
notification = notifications.findNode(NOTIFICATION_NODE_ID) notification = GetCurrentNotification(notifications)
if notification = invalid if notification = invalid
notification = notifications.createChild("SponsorBlockNotification") notification = notifications.createChild("SponsorBlockNotification")
notification.id = NOTIFICATION_NODE_ID notification.id = NOTIFICATION_NODE_ID
end if end if
notification.segment = segment
notification.action = action notification.segmentId = segment.UUID
notification.categoryText = segment.shortTitle
notification.actionText = segment.actionText
notification.doShow = true
end function end function
function RemoveNotifcation(notifications as object) as void function RemoveNotifcation(notifications as object) as void
notification = notifications.findNode(NOTIFICATION_NODE_ID) notification = GetCurrentNotification(notifications)
if notification <> invalid if notification <> invalid
notifications.RemoveChild(notification) notifications.RemoveChild(notification)
end if end if
end function end function
function SetVisible(notifications as object, visible as boolean) function SetVisible(notifications as object, visible as boolean)
notification = notifications.findNode(NOTIFICATION_NODE_ID) notification = GetCurrentNotification(notifications)
if notification <> invalid if notification <> invalid
notification.visible = visible notification.visible = visible
end if end if
@@ -5,5 +5,5 @@ function SponsorBlockSegmentViewedTask(input as object)
segmentId = input.segmentId segmentId = input.segmentId
service = new SponsorBlock.SponsorBlockService() service = new SponsorBlock.SponsorBlockService()
service.PostSegmentViewed(segmentId) service.PostSegmentViewed(segmentId, m.top.cancellation)
end function end function
@@ -12,6 +12,26 @@ namespace SponsorBlock
m.sponsorBlockConfig = ParseJson(ReadAsciiFile("libpkg:/config/sponsorblock_config.json5")) m.sponsorBlockConfig = ParseJson(ReadAsciiFile("libpkg:/config/sponsorblock_config.json5"))
end function end function
function GetCategories() as object
if m.sponsorBlockConfig = invalid
return []
end if
return ValidArray(m.sponsorBlockConfig.categoryList)
end function
function GetOptionsForCategory(category as string) as object
if m.sponsorBlockConfig = invalid
return []
end if
if not m.sponsorBlockConfig.categories.doesexist(category)
return []
end if
return ValidArray(m.sponsorBlockConfig.categories[category].options)
end function
function SegmentColor(category as string) as integer function SegmentColor(category as string) as integer
if m.sponsorBlockConfig = invalid if m.sponsorBlockConfig = invalid
return 0 return 0
@@ -54,8 +74,10 @@ namespace SponsorBlock
return invalid return invalid
end if end if
categories = ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "poi_highlight", "filler", "exclusive_access"] ' categories = ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "poi_highlight", "filler", "exclusive_access"]
actionTypes = ["skip", "mute", "chapter", "full", "poi"] categories = ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "poi_highlight", "filler"]
' actionTypes = ["skip", "mute", "chapter", "full", "poi"]
actionTypes = ["skip", "mute", "poi"]
categoriesJson = FormatJson(categories).EncodeUriComponent() categoriesJson = FormatJson(categories).EncodeUriComponent()
actionTypesJson = FormatJson(actionTypes).EncodeUriComponent() actionTypesJson = FormatJson(actionTypes).EncodeUriComponent()
@@ -64,6 +86,11 @@ namespace SponsorBlock
hashPrefix = CryptoUtils.GetSha256(videoId).Left(4) hashPrefix = CryptoUtils.GetSha256(videoId).Left(4)
url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.SKIP_SEGMENT_ENDPOINT}/${hashPrefix}?categories=${categoriesJson}&actionTypes=${actionTypesJson}` url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.SKIP_SEGMENT_ENDPOINT}/${hashPrefix}?categories=${categoriesJson}&actionTypes=${actionTypesJson}`
response = HttpClient.Get(url).Await() response = HttpClient.Get(url).Await()
if not response.IsSuccess()
LogError("SponsorBlockService: GetSkipSegmentsForVideo failed", response.ErrorMessage())
return invalid
end if
json = response.Json() json = response.Json()
if json = invalid if json = invalid
return invalid return invalid
@@ -78,13 +105,13 @@ namespace SponsorBlock
return invalid return invalid
end function end function
function PostSegmentViewed(segmentId as string) as void function PostSegmentViewed(segmentId as string, cancellation = invalid as object) as void
if m.sponsorBlockConfig = invalid or StringUtils.IsNullOrEmpty(m.sponsorBlockConfig.serverAddress) if m.sponsorBlockConfig = invalid or StringUtils.IsNullOrEmpty(m.sponsorBlockConfig.serverAddress)
return return
end if end if
url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}` url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}`
HttpClient.Post(url, "").Await() HttpClient.Post(url, "").Cancellation(cancellation).Await()
end function end function
function GenerateProgressBarBackground(segments as object, lengthSeconds as integer, path as string) function GenerateProgressBarBackground(segments as object, lengthSeconds as integer, path as string)
@@ -103,8 +130,8 @@ namespace SponsorBlock
continue for continue for
end if end if
pixelStart = (segment.segment[0] / videoDuration) * width pixelStart = (segment.start / videoDuration) * width
pixelEnd = (segment.segment[1] / videoDuration) * width pixelEnd = (segment.end / videoDuration) * width
color = m.SegmentColor(segment.category) color = m.SegmentColor(segment.category)
' highlight's duration is zero, so it is not visble on the bar. ' highlight's duration is zero, so it is not visble on the bar.
' Add a few pixels to see it ' Add a few pixels to see it
@@ -1,22 +1,135 @@
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs" import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
import "pkg:/components/VideoPlayer/SponsorBlockSegmentAction.bs"
import "pkg:/source/utils/Types.bs"
@asynctask @asynctask
function SponsorBlockTask(input as object) as object function SponsorBlockTask(input as object) as object
videoId = input.metadata.videoId videoId = input.metadata.videoId
lengthSeconds = input.metadata.lengthSeconds lengthSeconds = input.metadata.lengthSeconds
showNotifications = input.showNotifications
categories = input.categories
service = new SponsorBlock.SponsorBlockService() service = new SponsorBlock.SponsorBlockService()
skipSegments = service.GetSkipSegmentsForVideo(videoId) skipSegments = service.GetSkipSegmentsForVideo(videoId)
barPath = invalid
skipSegments = ProcessSkipSegments(skipSegments, showNotifications, categories, service)
barPath = invalid
if skipSegments <> invalid if skipSegments <> invalid
barPath = `tmp:/sponsorblock_bar.png` barPath = `tmp:/sponsorblock_bar.png`
service.GenerateProgressBarBackground(skipSegments, lengthSeconds, barPath) service.GenerateProgressBarBackground(skipSegments, lengthSeconds, barPath)
end if end if
' Usually segment.start and segment.end are equal for poi_highlight
' We pad the duration for poi_highlight segments so that the chapter label
' can be visible when seeking in trickplay.
' Padding poi_highlight is done after generating the progress bar, so that the
' highlight is not too long in the bar.
skipSegments = PadHightlightSegment(skipSegments, lengthSeconds)
' Sort the segments by start time, so we can binary search them later.
if skipSegments <> invalid
skipSegments.SortBy("start")
end if
return { return {
videoId: videoId videoId: videoId
skipSegments: skipSegments skipSegments: skipSegments
barPath: barPath barPath: barPath
} }
end function end function
function ProcessSkipSegments(skipSegments as object, showNotifications as boolean, categories as object, service as SponsorBlock.SponsorBlockService) as object
if skipSegments = invalid
return invalid
end if
processedSegments = []
for each segment in skipSegments
' When a submission reaches the score of -2 or lower, it gets removed and will not appear anymore for users
' https://wiki.sponsor.ajay.app/w/FAQ#How_does_voting_work_and_what_do_certain_amounts_of_votes_mean?
if ValidInt(segment.votes) < -1
continue for
end if
option = GetOptionForSegment(segment, categories)
if option = SponsorBlock.SegmentAction.Disable
continue for
end if
segment.option = option
segment.showNotification = showNotifications and ShouldShowNotification(segment, categories)
if segment.showNotification
if option = SponsorBlock.SegmentAction.AutoSkip
segment.actionText = Tr(Locale.SponsorBlock.Skipped)
else if option = SponsorBlock.SegmentAction.ManualSkip
segment.actionText = Tr(Locale.SponsorBlock.PressOkToSkip)
else
segment.actionText = ""
end if
end if
segmentRange = segment["segment"]
segmentStart = segmentRange[0]
segmentEnd = segmentRange[1]
segment.Delete("segment")
segment.start = segmentStart
segment.end = segmentEnd
segment.title = Tr(ValidString(service.SegmentTitle(segment.category)))
segment.shortTitle = Tr(ValidString(service.SegmentShortTitle(segment.category)))
processedSegments.push(segment)
end for
return processedSegments
end function
function GetOptionForSegment(segment as object, categories as object) as string
category = categories[segment.category]
if not IsAssociativeArray(category)
return false
end if
option = category.option
if StringUtils.IsNullOrEmpty(option)
option = SponsorBlock.SegmentAction.Disable
end if
return option
end function
function ShouldShowNotification(segment as object, categories as object) as boolean
option = GetOptionForSegment(segment, categories)
return option = SponsorBlock.SegmentAction.AutoSkip or option = SponsorBlock.SegmentAction.ManualSkip
end function
function PadHightlightSegment(segments as object, lengthSeconds as integer) as object
for each segment in segments
if not segment.category = "poi_highlight"
continue for
end if
segmentPaddedDuration = 5
if lengthSeconds > 0
if lengthSeconds < 120
segmentPaddedDuration = 1
else if lengthSeconds < 300
segmentPaddedDuration = 2
else if lengthSeconds < 900
segmentPaddedDuration = 5
else
segmentPaddedDuration = 10
end if
end if
segmentDuration = Abs(segment.end - segment.start)
padding = Abs(segmentPaddedDuration - segmentDuration) / 2
segment.start = segment.start - padding
segment.end = segment.end + padding
end for
return segments
end function
@@ -2,6 +2,7 @@ import "pkg:/components/Services/SponsorBlock/Notifications/SponsorBlockNotifica
import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs" import "pkg:/components/Services/SponsorBlock/SponsorBlockService.bs"
import "pkg:/source/AsyncTask/AsyncTask.bs" import "pkg:/source/AsyncTask/AsyncTask.bs"
import "pkg:/source/AsyncTask/Tasks.bs" import "pkg:/source/AsyncTask/Tasks.bs"
import "SponsorBlockSegmentAction.bs"
import "VideoPlayer.bs" import "VideoPlayer.bs"
namespace SponsorBlock namespace SponsorBlock
@@ -12,18 +13,62 @@ namespace SponsorBlock
end if end if
m.sponsorBlockService = new SponsorBlock.SponsorBlockService() m.sponsorBlockService = new SponsorBlock.SponsorBlockService()
PositionChapterLabel()
m.top.trickPlayBar.observeField("visible", FuncName(OnTrickPlayBarVisible))
m.chapterLabelTimer = m.top.findNode("chapterLabelTimer")
m.chapterLabelTimer.observeField("fire", FuncName(OnChapterLabelTimer))
m._sponsorBlockLastTime = 0.0#
' TODO:P1 more precision on when notifications should be visible
' Should notifcations be visible when the video is not fullscreen?
SponsorBlock.SetVisible(m.notifications, m.container.fullscreen) SponsorBlock.SetVisible(m.notifications, m.container.fullscreen)
end function end function
function FetchSponsorBlock(metadata as object) as void
if not m.preferences["sponsorblock.enabled"]
return
end if
if m.sponsorBlockTask <> invalid
m.sponsorBlockTask.cancel = true
end if
m.sponsorBlockTask = AsyncTask.Start(Tasks.SponsorBlockTask, {
metadata: metadata
showNotifications: m.preferences["sponsorblock.show_notifications"]
categories: m.preferences["sponsorblock.categories"]
}, OnSponsorBlockTaskResults)
end function
function OnSponsorBlockTaskResults(output as object) as void
m.sponsorBlockTask = invalid
if output.cancelled or m.onCloseCalled = true
return
end if
if not output.success
error = ErrorUtils.Format(output.error)
LogError(error)
return
end if
skipSegments = output.result.skipSegments
if skipSegments = invalid or skipSegments.Count() = 0
return
end if
m.skipSegments = skipSegments
m.top.seekMode = "accurate"
barPath = output.result.barPath
if barPath <> invalid
m.top.trickPlayBar.trackImageUri = barPath
m.top.trickPlayBar.filledBarBlendColor = "#FF000080"
end if
m.top.ObserveFieldScoped("position", FuncName(OnPositionChangeSkipSponsorBlockSections))
if m.top.hasField("trickPlayPosition")
PositionChapterLabel()
m.chapterLabelTimer = m.top.findNode("chapterLabelTimer")
m.chapterLabelTimer.observeField("fire", FuncName(OnChapterLabelTimer))
m._sponsorBlockLastTimeChapterUpdated = 0.0#
m.top.trickPlayBar.observeField("visible", FuncName(OnTrickPlayBarVisible))
end if
end function
function PositionChapterLabel() function PositionChapterLabel()
m.chapterLabel = m.top.findNode("chapterLabel") m.chapterLabel = m.top.findNode("chapterLabel")
' We move the chapter label under m.top.trickPlayBar ' We move the chapter label under m.top.trickPlayBar
@@ -43,162 +88,137 @@ namespace SponsorBlock
end function end function
function OnChapterLabelTimer() as void function OnChapterLabelTimer() as void
if m.skipSegments = invalid trickPlayPosition = m.top.trickPlayPosition
if m._sponsorBlockLastTimeChapterUpdated = trickPlayPosition
return return
end if end if
' trickPlayPosition is not documented on Roku website, this is why we're checking m._sponsorBlockLastTimeChapterUpdated = trickPlayPosition
if not IsDouble(m.top.trickPlayPosition) UpdateSponsorBlockChapter(trickPlayPosition)
return
end if
if m._sponsorBlockLastTime = m.top.trickPlayPosition
return
end if
m._sponsorBlockLastTime = m.top.trickPlayPosition
UpdateSponsorBlockChapter(m._sponsorBlockLastTime)
end function end function
function UpdateSponsorBlockChapter(time as double) as void function UpdateSponsorBlockChapter(time as double) as void
segments = m.skipSegments segments = m.skipSegments
for each segment in segments segment = FindSegmentByTime(segments, time, 0)
category = segment["category"] if segment = invalid
segmentRange = segment["segment"] m.top.chapter = ""
segmentStart = segmentRange[0] return
segmentEnd = segmentRange[1] end if
m.top.chapter = segment.title
' Usually segmentStart and segmentEnd are equal for poi_highlight
' We pad the duration for poi_highlight segments so that the chapter label
' can be visible when seeking in trickplay
if category = "poi_highlight"
segmentPaddedDuration = 5
duration = m.top.duration
if duration > 0
if duration < 120
segmentPaddedDuration = 1
else if duration < 300
segmentPaddedDuration = 2
else if duration < 900
segmentPaddedDuration = 5
else
segmentPaddedDuration = 10
end if
end if
segmentDuration = Abs(segmentEnd - segmentStart)
padding = Abs(segmentPaddedDuration - segmentDuration) / 2
segmentStart = segmentStart - padding
segmentEnd = segmentEnd + padding
end if
if (segmentStart <= time) and (segmentEnd >= time)
m.top.chapter = Tr(ValidString(m.sponsorBlockService.SegmentTitle(category)))
return
end if
end for
m.top.chapter = ""
end function end function
function FetchSponsorBlock(metadata as object) as void function FindSegmentByTime(segments as object, time as dynamic, endOffset as integer) as dynamic
if not m.preferences["sponsorblock.enabled"] ' Binary search for the segment that contains the time.
return ' This search sometimes fails if the segments overlap.
end if ' For most cases, this is acceptable, since it is not common for segments to overlap.
low = 0
if m.sponsorBlockTask <> invalid high = segments.Count() - 1
m.sponsorBlockTask.cancel = true while low <= high
end if middle = (low + high) \ 2
segment = segments[middle]
m.sponsorBlockTask = AsyncTask.Start(Tasks.SponsorBlockTask, { metadata: metadata }, OnSponsorBlockTaskResults) if time < segment.start
end function high = middle - 1
else if time > (segment.end + endOffset)
function OnSponsorBlockTaskResults(output as object) as void low = middle + 1
m.sponsorBlockTask = invalid else
if output.cancelled or m.onCloseCalled = true return segment
return end if
end if end while
return invalid
if not output.success
error = ErrorUtils.Format(output.error)
LogError(error)
return
end if
skipSegments = output.result.skipSegments
if skipSegments = invalid
return
end if
m.skipSegments = skipSegments
m.top.seekMode = "accurate"
barPath = output.result.barPath
if barPath <> invalid
m.top.trickPlayBar.trackImageUri = barPath
m.top.trickPlayBar.filledBarBlendColor = "#FF000080"
end if
m.top.ObserveFieldScoped("position", FuncName(OnPositionChangeSkipSponsorBlockSections))
end function end function
function OnPositionChangeSkipSponsorBlockSections() as void function OnPositionChangeSkipSponsorBlockSections() as void
segments = m.skipSegments segments = m.skipSegments
if segments = invalid position = m.top.position
' We add a small offset to the end position of the segment.
' This is so that when we skip a segment, we don't get
' another notification to skip it.
' Seeking accuracy is not perfect, so we need to account for that.
segment = FindSegmentByTime(segments, position, -1)
if segment = invalid
return return
end if end if
for each segment in segments action = segment.option
segmentRange = segment["segment"]
segmentStart = segmentRange[0]
segmentEnd = segmentRange[1]
currentPosition = m.top.position
if (segmentStart < currentPosition) and ((segmentEnd - 1) > currentPosition)
action = GetActionForSegment(segment)
if m.preferences["sponsorblock.show_notifications"] = true
SponsorBlock.ShowNotifcation(m.notifications, segment, action)
end if
if action = "AutoSkip" if segment.showNotification
duration = m.top.duration SponsorBlock.ShowNotifcation(m.notifications, segment, action)
' Sometimes segmentEnd is greater than duration
if duration > 0 and segmentEnd > duration if action = SegmentAction.ManualSkip
segmentEnd = duration ' We'll save the segment here, and handle it in case the user
end if ' presses the OK button on the notification.
' If the segment is at the end of the video, skip the video instead of seeking m.manualSkipSegment = segment
if duration > 0 and Abs(segmentEnd - duration) < 2 return
LogInfo("Skipping section:", segment["category"], "at end of video")
SendSkippedSectionEvent(segment.UUID)
OnVideoFinished()
return
else
LogInfo("Skipping section:", segment["category"])
SendSkippedSectionEvent(segment.UUID)
m.top.seek = segmentEnd
return
end if
end if
end if end if
end for end if
if action = SegmentAction.AutoSkip
SkipSegment(segment, position)
end if
end function end function
function GetActionForSegment(segment as object) as dynamic function SkipSegment(segment as object, position as dynamic) as void
category = segment["category"] segmentEnd = segment.end
if category = "sponsor"
return "AutoSkip" duration = m.top.duration
else if category = "poi_highlight" ' Sometimes segmentEnd is greater than duration
return "ManualSkip" if duration > 0 and segmentEnd > duration
else if category = "exclusive_access" segmentEnd = duration
return "ShowOverlay"
else if category = "chapter"
return "ShowOverlay"
end if end if
return ""
' If we're skipping a very short distance, it's not worth it
' since we can cause rebuffering
if Abs(segmentEnd - position) < 2
LogInfo("Skip position is within 2 seconds of segment end, not skipping")
return
end if
' If the segment is at the end of the video, skip the video instead of seeking
if duration > 0 and Abs(segmentEnd - duration) < 2
LogInfo("Skipping section:", segment.category, "at end of video")
OnVideoFinished()
else
LogInfo("Skipping section:", segment.category)
m.top.seek = segmentEnd
end if
SendSkippedSectionEvent(segment.UUID)
end function
function ManualSkipSegment() as boolean
segment = m.manualSkipSegment
if segment = invalid
return false
end if
m.manualSkipSegment = invalid
notification = SponsorBlock.GetCurrentNotification(m.notifications)
if notification = invalid
return false
end if
notificationSegmentId = notification.segmentId
if notificationSegmentId <> segment.UUID
return false
end if
position = m.top.position
if (position < segment.start) or (segment.end < position)
return false
end if
SkipSegment(segment, position)
SponsorBlock.RemoveNotifcation(m.notifications)
return true
end function end function
function SendSkippedSectionEvent(segmentId as string) function SendSkippedSectionEvent(segmentId as string)
AsyncTask.Start(Tasks.SponsorBlockSegmentViewedTask, { segmentId: segmentId }) if m.sponsorSkipEventTask <> invalid
m.sponsorSkipEventTask.cancel = true
end if
m.sponsorSkipEventTask = AsyncTask.Start(Tasks.SponsorBlockSegmentViewedTask, { segmentId: segmentId })
end function end function
end namespace end namespace
@@ -0,0 +1,16 @@
namespace SponsorBlock
enum SegmentAction
' Disable: we do not care about this segment.
Disable = "disable"
' AutoSkip: we want to skip this segment automatically.
AutoSkip = "auto_skip"
' ManualSkip: we want to skip this segment manually, by showing a notification.
' The user would have to press the skip button on the notification.
ManualSkip = "manual_skip"
' ShowInSeekbar: we want to show this segment in the seekbar, but not skip it.
' No notification will be shown
ShowInSeekbar = "show_in_seekbar"
end enum
end namespace
@@ -518,6 +518,10 @@ function HideUIAndStopTimer()
end function end function
function HandleOKPress() as boolean function HandleOKPress() as boolean
if SponsorBlock.ManualSkipSegment()
return false
end if
if not m.showUIEnabled if not m.showUIEnabled
return false return false
end if end if
@@ -19,7 +19,7 @@
</interface> </interface>
<children> <children>
<Label id="chapterLabel" width="350" height="25" horizAlign="center" vertAlign="center" font="font:SmallestSystemFont" /> <Label id="chapterLabel" width="350" height="25" horizAlign="center" vertAlign="center" font="font:SmallestSystemFont" />
<Timer id="chapterLabelTimer" repeat="true" duration="0.25" /> <Timer id="chapterLabelTimer" repeat="true" duration="0.5" />
<Animation id="minimizeAnimation" duration="0.3" optional="true"> <Animation id="minimizeAnimation" duration="0.3" optional="true">
<FloatFieldInterpolator id="widthInterpolator" key="[0.0, 0.5, 1.0]" fieldToInterp="VideoPlayer.width" /> <FloatFieldInterpolator id="widthInterpolator" key="[0.0, 0.5, 1.0]" fieldToInterp="VideoPlayer.width" />
<FloatFieldInterpolator id="heightInterpolator" key="[0.0, 0.5, 1.0]" fieldToInterp="VideoPlayer.height" /> <FloatFieldInterpolator id="heightInterpolator" key="[0.0, 0.5, 1.0]" fieldToInterp="VideoPlayer.height" />
+46
View File
@@ -128,6 +128,52 @@
type: "boolean", type: "boolean",
defaultValue: true, defaultValue: true,
}, },
{
displayText: "Categories",
key: "sponsorblock.categories",
description: "Configure which segments to skip",
type: "assocarray",
visibility: "tv",
rokuComponent: "SponsorBlockCategoriesControl",
defaultValue: {
// TODO:P1 support for exclusive_access and chapter
// TODO:P1 support for manual skip for poi_highlight
sponsor: {
option: "auto_skip",
},
selfpromo: {
option: "manual_skip",
},
interaction: {
option: "manual_skip",
},
poi_highlight: {
option: "show_in_seekbar",
},
intro: {
option: "manual_skip",
},
outro: {
option: "manual_skip",
},
preview: {
option: "manual_skip",
},
filler: {
option: "manual_skip",
},
music_offtopic: {
option: "manual_skip",
},
},
},
{
displayText: "Categories",
key: "sponsorblock.categories",
description: "Configure which segments to skip",
visibility: "web",
svelteComponent: "SponsorBlockCategoriesControl",
},
], ],
}, },
{ {
@@ -1,116 +1,70 @@
{ {
serverAddress: 'https://sponsor.ajay.app', serverAddress: "https://sponsor.ajay.app",
categoryList: [ categoryList: [
'sponsor', "sponsor",
'selfpromo', "selfpromo",
'exclusive_access', "interaction",
'interaction', "poi_highlight",
'poi_highlight', "intro",
'intro', "outro",
'outro', "preview",
'preview', "filler",
'filler', "music_offtopic",
'chapter',
'music_offtopic',
], ],
categories: { categories: {
sponsor: { sponsor: {
title: 'Sponsor', title: "Sponsor",
short_title: 'Sponsor', short_title: "Sponsor",
categorySupport: [ options: ["auto_skip", "manual_skip", "show_in_seekbar", "disable"],
'skip', color: "#00D400B3",
'mute',
'full',
],
color: '#00D400B3',
}, },
selfpromo: { selfpromo: {
title: 'Unpaid/Self Promotion', title: "Unpaid/Self Promotion",
short_title: 'Unpaid/Self Promotion', short_title: "Unpaid/Self Promotion",
categorySupport: [ options: ["auto_skip", "manual_skip", "show_in_seekbar", "disable"],
'skip', color: "#FFFF00B3",
'mute',
'full',
],
color: '#FFFF00B3',
},
exclusive_access: {
title: 'Exclusive Access',
short_title: 'Exclusive Access',
categorySupport: [
'full',
],
color: '#008A5CB3',
}, },
interaction: { interaction: {
title: 'Interaction Reminder (Subscribe)', title: "Interaction Reminder (Subscribe)",
short_title: 'Interaction Reminder', short_title: "Interaction Reminder",
categorySupport: [ options: ["auto_skip", "manual_skip", "show_in_seekbar", "disable"],
'skip', color: "#CC00FFB3",
'mute',
],
color: '#CC00FFB3',
}, },
poi_highlight: { poi_highlight: {
title: 'Highlight', title: "Highlight",
short_title: 'Highlight', short_title: "Highlight",
categorySupport: [ options: ["show_in_seekbar", "disable"],
'poi', color: "#FF1684B3",
],
color: '#FF1684B3',
}, },
intro: { intro: {
title: 'Intermission/Intro Animation', title: "Intermission/Intro Animation",
short_title: 'Intermission', short_title: "Intermission",
categorySupport: [ options: ["auto_skip", "manual_skip", "show_in_seekbar", "disable"],
'skip', color: "#00FFFFB3",
'mute',
],
color: '#00FFFFB3',
}, },
outro: { outro: {
title: 'Endcards/Credits', title: "Endcards/Credits",
short_title: 'Endcards/Credits', short_title: "Endcards/Credits",
categorySupport: [ options: ["auto_skip", "manual_skip", "show_in_seekbar", "disable"],
'skip', color: "#0202EDB3",
'mute',
],
color: '#0202EDB3',
}, },
preview: { preview: {
title: 'Preview/Recap/Hook', title: "Preview/Recap/Hook",
// Note: short title renamed from "Preview/Recap/Hook" to "Preview/Recap" to fit in the UI short_title: "Preview/Recap",
short_title: 'Preview/Recap', options: ["auto_skip", "manual_skip", "show_in_seekbar", "disable"],
categorySupport: [ color: "#008FD6B3",
'skip',
'mute',
],
color: '#008FD6B3',
}, },
filler: { filler: {
title: 'Filler Tangent/Jokes', title: "Filler Tangent/Jokes",
short_title: 'Filler', short_title: "Filler",
categorySupport: [ options: ["auto_skip", "manual_skip", "show_in_seekbar", "disable"],
'skip', color: "#7300FFE6",
'mute',
],
color: '#7300FFE6',
},
chapter: {
title: 'Chapter',
short_title: 'Chapter',
categorySupport: [
'chapter',
],
color: '#FFFFFFC8',
}, },
music_offtopic: { music_offtopic: {
title: 'Music: Non-Music Section', title: "Music: Non-Music Section",
short_title: 'Non-Music', short_title: "Non-Music",
categorySupport: [ options: ["auto_skip", "manual_skip", "show_in_seekbar", "disable"],
'skip', color: "#FF9900B3",
],
color: '#FF9900B3',
}, },
}, },
} }
@@ -884,6 +884,18 @@
<source>Show notifications when a segment is skipped</source> <source>Show notifications when a segment is skipped</source>
<translation>Show notifications when a segment is skipped</translation> <translation>Show notifications when a segment is skipped</translation>
</message> </message>
<message>
<source>Categories</source>
<translation>Categories</translation>
</message>
<message>
<source>Configure which segments to skip</source>
<translation>Configure which segments to skip</translation>
</message>
<message>
<source>Select option for %1</source>
<translation>Select option for %1</translation>
</message>
<message> <message>
<source>Search History</source> <source>Search History</source>
<translation>Search History</translation> <translation>Search History</translation>
@@ -1004,6 +1016,26 @@
<source>Skipped</source> <source>Skipped</source>
<translation>Skipped</translation> <translation>Skipped</translation>
</message> </message>
<message>
<source>Press OK to skip</source>
<translation>Press OK to skip</translation>
</message>
<message>
<source>Disable</source>
<translation>Disable</translation>
</message>
<message>
<source>Auto Skip</source>
<translation>Auto Skip</translation>
</message>
<message>
<source>Manual Skip</source>
<translation>Manual Skip</translation>
</message>
<message>
<source>Show in Seekbar</source>
<translation>Show in Seekbar</translation>
</message>
<message> <message>
<source>Sponsor</source> <source>Sponsor</source>
<translation>Sponsor</translation> <translation>Sponsor</translation>
+9
View File
@@ -285,6 +285,9 @@ namespace Locale
EnabledDescription = "Enable SponsorBlock" EnabledDescription = "Enable SponsorBlock"
ShowNotifications = "Show notifications" ShowNotifications = "Show notifications"
ShowNotificationsDescription = "Show notifications when a segment is skipped" ShowNotificationsDescription = "Show notifications when a segment is skipped"
Categories = "Categories"
CategoriesDescription = "Configure which segments to skip"
SelectOptionFor = "Select option for %1"
SearchHistory = "Search History" SearchHistory = "Search History"
SearchHistoryPreferences = "Search history preferences" SearchHistoryPreferences = "Search history preferences"
@@ -333,6 +336,12 @@ namespace Locale
@locale @locale
enum SponsorBlock enum SponsorBlock
Skipped = "Skipped" Skipped = "Skipped"
PressOkToSkip = "Press OK to skip"
Disable = "Disable"
AutoSkip = "Auto Skip"
ManualSkip = "Manual Skip"
ShowInSeekbar = "Show in Seekbar"
SponsorTitle = "Sponsor" SponsorTitle = "Sponsor"
SelfPromoTitle = "Unpaid/Self Promotion" SelfPromoTitle = "Unpaid/Self Promotion"
+1 -1
View File
@@ -6,7 +6,7 @@
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"preview": "vite preview", "preview": "vite preview",
"check": "svelte-check --tsconfig ./tsconfig.json" "lint": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings"
}, },
"devDependencies": { "devDependencies": {
"@sveltejs/vite-plugin-svelte": "^5.0.3", "@sveltejs/vite-plugin-svelte": "^5.0.3",
+5
View File
@@ -11,6 +11,7 @@
playletStateStore, playletStateStore,
preferencesModelStore, preferencesModelStore,
searchHistoryStore, searchHistoryStore,
sponsorBlockConfigStore,
userPreferencesStore, userPreferencesStore,
} from "lib/Stores"; } from "lib/Stores";
import BottomNavigation from "lib/BottomNavigation.svelte"; import BottomNavigation from "lib/BottomNavigation.svelte";
@@ -38,6 +39,10 @@
homeLayoutFileStore.set(value); homeLayoutFileStore.set(value);
}); });
PlayletApi.getSponsorBlockConfigFile().then((value) => {
sponsorBlockConfigStore.set(value);
});
PlayletApi.getInvidiousVideoApiFile().then((apiDefinitions) => { PlayletApi.getInvidiousVideoApiFile().then((apiDefinitions) => {
invidiousVideoApiStore.set(apiDefinitions); invidiousVideoApiStore.set(apiDefinitions);
}); });
+5
View File
@@ -34,6 +34,11 @@ export class PlayletApi {
return await response.json(); return await response.json();
} }
static async getSponsorBlockConfigFile() {
const response = await fetch(`${PlayletApi.host()}/config/sponsorblock_config.json5`);
return await response.json();
}
static async getInvidiousVideoApiFile() { static async getInvidiousVideoApiFile() {
const response = await fetch(`${PlayletApi.host()}/config/invidious_video_api.yaml`); const response = await fetch(`${PlayletApi.host()}/config/invidious_video_api.yaml`);
return await response.json(); return await response.json();
@@ -12,7 +12,6 @@
const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"]; const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"];
export let displayText: string = ""; export let displayText: string = "";
// svelte-ignore unused-export-let
export let key: string = ""; export let key: string = "";
export let description: string = ""; export let description: string = "";
export let level: number = 0; export let level: number = 0;
@@ -92,7 +91,7 @@
<div class={textSizes[level]}>{$translate(displayText)}</div> <div class={textSizes[level]}>{$translate(displayText)}</div>
<div class="text-xs text-gray-500">{@html $translate(description)}</div> <div class="text-xs text-gray-500">{@html $translate(description)}</div>
<button class="btn m-1" on:click={openHomeScreenEditor} <button class="btn m-1" on:click={openHomeScreenEditor}
>{$translate("Edit home screen")}</button >{$translate(displayText)}</button
> >
</div> </div>
@@ -0,0 +1,123 @@
<script lang="ts">
import {
sponsorBlockConfigStore,
translate,
userPreferencesStore,
} from "lib/Stores";
import { PlayletApi } from "lib/Api/PlayletApi";
const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"];
const optionTitles = {
disable: "Disable",
auto_skip: "Auto Skip",
manual_skip: "Manual Skip",
show_in_seekbar: "Show in Seekbar",
};
export let displayText: string = "";
export let key: string = "";
export let description: string = "";
export let level: number = 0;
let value;
let originalValue;
userPreferencesStore.subscribe((userPreferences) => {
originalValue = userPreferences[key];
});
let sponsorBlockConfig;
sponsorBlockConfigStore.subscribe((config) => {
sponsorBlockConfig = config;
});
let modal;
async function openEditor() {
value = JSON.parse(JSON.stringify(originalValue));
modal.showModal();
}
async function save() {
if (key !== "" && value) {
await PlayletApi.saveUserPreference(key, value);
const userPreferences = await PlayletApi.getUserPreferences();
userPreferencesStore.set(userPreferences);
}
}
export function close() {
modal.close();
}
function onClose() {
// Reset value to original value to avoid weird animation on show
value = JSON.parse(JSON.stringify(originalValue));
}
</script>
<div class="m-5">
<div class={textSizes[level]}>{$translate(displayText)}</div>
<div class="text-xs text-gray-500">{@html $translate(description)}</div>
<button class="btn m-1" on:click={openEditor}
>{$translate(displayText)}</button
>
</div>
<dialog bind:this={modal} class="modal" on:close={onClose}>
<div class="modal-box bg-base-100">
{#if value && sponsorBlockConfig}
<table class="w-full">
<tbody>
{#each sponsorBlockConfig.categoryList as category}
{#if value[category]}
<tr>
<td>
<div
style="
width: 32px;
height: 24px;
border-radius: 2px;
background: {sponsorBlockConfig.categories[category]
.color};
border: 1px solid #ccc;
display: inline-block;
"
></div>
</td>
<td>
<div>
{$translate(sponsorBlockConfig.categories[category].title)}
</div>
</td>
<td>
<div>
<select
bind:value={value[category].option}
class="select select-bordered select-sm"
>
{#each sponsorBlockConfig.categories[category].options as option}
<option value={option}
>{$translate(optionTitles[option])}</option
>
{/each}
</select>
</div>
</td>
</tr>
{/if}
{/each}
</tbody>
</table>
<form method="dialog" class="flex justify-center space-x-2 m-2">
<button class="btn btn-primary" on:click={save}
>{$translate("Save")}</button
>
<button class="btn btn-primary">{$translate("Close")}</button>
</form>
{/if}
</div>
<form method="dialog" class="modal-backdrop">
<button>{$translate("Close")}</button>
</form>
</dialog>
@@ -8,6 +8,7 @@
import NumberControl from "./SettingControls/NumberControl.svelte"; import NumberControl from "./SettingControls/NumberControl.svelte";
import ClearCacheControl from "./SettingControls/ClearCacheControl.svelte"; import ClearCacheControl from "./SettingControls/ClearCacheControl.svelte";
import EditQualityControl from "./SettingControls/EditQualityControl.svelte"; import EditQualityControl from "./SettingControls/EditQualityControl.svelte";
import SponsorBlockCategoriesControl from "./SettingControls/SponsorBlockCategoriesControl.svelte";
import { translate } from "lib/Stores"; import { translate } from "lib/Stores";
const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"]; const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"];
@@ -36,6 +37,7 @@
EditHomeScreenControl, EditHomeScreenControl,
PlayletLibVersionControl, PlayletLibVersionControl,
EditQualityControl, EditQualityControl,
SponsorBlockCategoriesControl,
}; };
</script> </script>
+2
View File
@@ -19,6 +19,8 @@ export const homeLayoutStore = writable([] as any);
export const homeLayoutFileStore = writable([] as any); export const homeLayoutFileStore = writable([] as any);
export const sponsorBlockConfigStore = writable({} as any);
export const bookmarksStore = writable([] as any); export const bookmarksStore = writable([] as any);
export const searchHistoryStore = writable([] as any); export const searchHistoryStore = writable([] as any);
@@ -23,7 +23,6 @@
// svelte-ignore unused-export-let // svelte-ignore unused-export-let
export let type: string = undefined; export let type: string = undefined;
// svelte-ignore unused-export-let
export let authorId: string = undefined; export let authorId: string = undefined;
// svelte-ignore unused-export-let // svelte-ignore unused-export-let
export let authorUrl: string = undefined; export let authorUrl: string = undefined;
-141
View File
@@ -1,141 +0,0 @@
// Description: Generates the SponsorBlock config for Playlet
const fs = require('fs');
const path = require('path');
const { ArgumentParser } = require('argparse')
const json5 = require('json5');
function getArgumentParser() {
const parser = new ArgumentParser({
description: 'Generate SponsorBlock config'
});
parser.add_argument('--sponsorblock-root', { help: 'Local path to the SponsorBlock repository', required: true });
return parser;
}
const parser = getArgumentParser();
const args = parser.parse_args()
const PLAYLEY_CONFIG_PATH = "./playlet-lib/src/config/sponsorblock_config.json5"
const sponsorblockRoot = args.sponsorblock_root;
const configExamplePath = path.join(sponsorblockRoot, "config.json.example")
const englishLocalePath = path.join(sponsorblockRoot, "public/_locales/en/messages.json")
let configExample = JSON.parse(fs.readFileSync(configExamplePath, { encoding: 'utf8', flag: 'r' }))
let englishLocale = JSON.parse(fs.readFileSync(englishLocalePath, { encoding: 'utf8', flag: 'r' }))
// https://github.com/ajayyy/SponsorBlock/blob/f4d80d88438ff31bc067ff480fd94112d972718d/src/config.ts#L251
const barTypes = {
"preview-chooseACategory": {
color: "#ffffff",
opacity: "0.7"
},
"sponsor": {
color: "#00d400",
opacity: "0.7"
},
"preview-sponsor": {
color: "#007800",
opacity: "0.7"
},
"selfpromo": {
color: "#ffff00",
opacity: "0.7"
},
"preview-selfpromo": {
color: "#bfbf35",
opacity: "0.7"
},
"exclusive_access": {
color: "#008a5c",
opacity: "0.7"
},
"interaction": {
color: "#cc00ff",
opacity: "0.7"
},
"preview-interaction": {
color: "#6c0087",
opacity: "0.7"
},
"intro": {
color: "#00ffff",
opacity: "0.7"
},
"preview-intro": {
color: "#008080",
opacity: "0.7"
},
"outro": {
color: "#0202ed",
opacity: "0.7"
},
"preview-outro": {
color: "#000070",
opacity: "0.7"
},
"preview": {
color: "#008fd6",
opacity: "0.7"
},
"preview-preview": {
color: "#005799",
opacity: "0.7"
},
"music_offtopic": {
color: "#ff9900",
opacity: "0.7"
},
"preview-music_offtopic": {
color: "#a6634a",
opacity: "0.7"
},
"poi_highlight": {
color: "#ff1684",
opacity: "0.7"
},
"preview-poi_highlight": {
color: "#9b044c",
opacity: "0.7"
},
"filler": {
color: "#7300FF",
opacity: "0.9"
},
"preview-filler": {
color: "#2E0066",
opacity: "0.7"
}
}
function getColor(obj) {
if (!obj) {
return "#FFFFFFC8"
}
const opacity = (Math.round(parseFloat(obj.opacity) * 255)).toString(16).toUpperCase().padStart(2, "0")
return obj.color + opacity;
}
let playletConfig = {
serverAddress: configExample.serverAddress,
categoryList: configExample.categoryList,
categories: {}
}
playletConfig.categoryList.forEach(categoryId => {
const category = {}
category.title = englishLocale[`category_${categoryId}`].message
category.short_title = englishLocale[`category_${categoryId}_short`]?.message ?? category.title;
category.categorySupport = configExample.categorySupport[categoryId];
category.color = getColor(barTypes[categoryId]).toUpperCase();
playletConfig.categories[categoryId] = category;
});
fs.writeFileSync(PLAYLEY_CONFIG_PATH, json5.stringify(playletConfig, null, 2));