initial commit

This commit is contained in:
Brahim Hadriche committed 2022-10-30 16:17:37 -04:00
commit 0eadc5da55
37 files changed
+1286

No files matched your search

+1
View File
@@ -0,0 +1 @@
* text=auto eol=lf
+43
View File
@@ -0,0 +1,43 @@
.DS_Store
build
###BrightScript specific
dist/apps
out/
#Rooibos generated
rooibosFunctionMap.brs
### Eclipse project files
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# Eclipse Core
.project
.classpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
node_modules/
out
**/roku_modules/
package-lock.json
!.vscode
.vscode/.env
dist/
.history
+32
View File
@@ -0,0 +1,32 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "brightscript",
"request": "launch",
"name": "Roku Youtube App",
"preLaunchTask": "roku-youtube",
"internalConsoleOptions": "neverOpen",
"envFile": "${workspaceFolder}/.vscode/.env",
"host": "${env:ROKU_DEV_TARGET}",
"password": "${env:ROKU_DEVPASSWORD}",
"outDir": "${workspaceFolder}/out",
"rootDir": "${workspaceFolder}/build",
"consoleOutput": "normal",
"stopOnEntry": false,
"retainDeploymentArchive": true,
"retainStagingFolder": true,
"autoRunSgDebugCommands": [],
"files": [
"manifest",
"*.*",
"**/*.*",
"!*.zip",
"!**/*.zip"
]
}
]
}
+25
View File
@@ -0,0 +1,25 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "roku-youtube",
"type": "shell",
"command": "npm run build",
"problemMatcher": [],
"presentation": {
"echo": true,
"reveal": "silent",
"focus": false,
"panel": "shared",
"showReuseMessage": false,
"clear": true
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
+11
View File
@@ -0,0 +1,11 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- Initial version
- Reads feeds from popular and trending videos using Invidious APIs
- Skips sections using SponsorBlock
+13
View File
@@ -0,0 +1,13 @@
# Youbtube for Roku
Unofficial Youtube client for Roku.
## Features
- No Ads (I guess that's a feature)
- Privacy driven (uses Invidious backend)
- SponsorBlock integration (skips undesirable sections in videos)
## Installation
Install as a dev channel using this command
```
TODO
```
+53
View File
@@ -0,0 +1,53 @@
{
"rootDir": "src",
"files": [
"manifest",
"source/**/*.*",
"images/**/*.*",
"meta/**/*.*",
"components/**/*.*",
"!**/*.spec.bs"
],
"autoImportComponentScript": true,
"createPackage": false,
"stagingFolderPath": "build",
"diagnosticFilters": [
{
"src": "**/roku_modules/**/*.*"
},
{
"src": "**/*spec.bs",
"codes": ["LINT3011"]
},
{
"src": "**/RALETrackerTask.*"
},
{
"src": "**/*.*"
}
],
"emitDefinitions": true,
"plugins": [
"maestro-roku-bsc-plugin",
"roku-log-bsc-plugin",
"@rokucommunity/bslint"
],
"rooibos": {
"isRecordingCodeCoverage": false,
"testsFilePattern": null,
"tags": ["!integration", "!deprecated", "!fixme"],
"showOnlyFailures": true,
"catchCrashes": true,
"lineWidth": 70
},
"rokuLog": {
"strip": false,
"insertPkgPath": true
},
"sourceMap": true,
"maestro": {
"excludeFilters": ["**/roku_modules/**/*", "**/rooibos/**/*"],
"buildForIDE": false,
"paramStripExceptions": ["onKeyEvent"]
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"rules": {
"inline-if-style": "no-then",
"block-if-style": "no-then",
"condition-style": "no-group",
"named-function-style": "no-sub",
"anon-function-style": "no-sub",
"type-annotations": "args",
"assign-all-paths": "off",
"unsafe-path-loop": "error",
"unsafe-iterators": "error",
"unreachable-code": "warn",
"case-sensitivity": "warn",
"unused-variable": "warn",
"consistent-return": "error",
"aa-comma-style": "never"
}
}
+35
View File
@@ -0,0 +1,35 @@
{
"name": "youtube-roku",
"version": "0.1.0",
"description": "Unofficial Youtube client for Roku",
"dependencies": {
"bslib": "npm:@rokucommunity/bslib@^0.1.1",
"log": "npm:roku-log@^0.8.0",
"maestro": "npm:maestro-roku@^0.47.0",
"roku-requests": "^0.2.0"
},
"devDependencies": {
"@rokucommunity/bslint": "^0.7.5",
"brighterscript": "^0.60.4",
"maestro-roku-bsc-plugin": "^0.25.7",
"roku-log-bsc-plugin": "^0.6.1",
"rooibos-roku": "^5.2.3",
"ropm": "^0.10.10"
},
"ropm": {
"rootDir": "src",
"packageRootDir": "dist",
"noprefix": [
"maestro"
]
},
"scripts": {
"build": "node scripts/run-roku-youtube.js",
"test": "echo \"Error: no test specified\" && exit 1",
"postinstall": "npx ropm copy",
"lint": "npx bsc"
},
"optionalDependencies": {
"fsevents": "^2.3.2"
}
}
+18
View File
@@ -0,0 +1,18 @@
const path = require('path');
const ProgramBuilder = require('brighterscript').ProgramBuilder;
const DiagnosticSeverity = require('brighterscript').DiagnosticSeverity;
let programBuilder = new ProgramBuilder();
programBuilder.run({
project: path.join(__dirname, '../', 'bsconfig.json')
}).then(() => {
//fail if there are diagnostics
if (programBuilder.program.getDiagnostics().filter((x) => x.severity === DiagnosticSeverity.Error).length > 0) {
throw new Error('Encountered error diagnostics');
} else {
console.log('\nBuild is finished');
}
}).catch(e => {
console.log('error', e.message);
process.exit(1);
});
+13
View File
@@ -0,0 +1,13 @@
import "pkg:/source/utils/Utils.bs"
sub Init()
m.rowList = m.top.FindNode("rowList")
m.rowList.SetFocus(true)
m.top.ObserveField("visible", "onVisibleChange")
end sub
sub OnVisibleChange() ' invoked when GridScreen change visibility
if m.top.visible = true
m.rowList.SetFocus(true) ' set focus to rowList if GridScreen visible
end if
end sub
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="GridScreen" extends="Group" initialFocus="RowList">
<script type="text/brightscript" uri="GridScreen.brs" />
<interface>
<field id="content" type="node" alias="RowList.content" />
<field id="rowItemSelected" type="intarray" alwaysnotify="true" alias="RowList.rowItemSelected" />
<field id="jumpToRowItem" type="intarray" alias="RowList.jumpToRowItem" />
</interface>
<children>
<RowList
itemComponentName="RowListItemComponent"
id="rowList"
translation="[50,50]"
numRows="2"
rowitemSize="[[320,180]]"
rowItemSpacing="[[20,0]]"
itemSize="[1160,270]"
rowLabelOffset="[[50,20]]"
focusXOffset="[50]"
showRowLabel="[true]"
rowFocusAnimationStyle="floatingfocus"
/>
</children>
</component>
+26
View File
@@ -0,0 +1,26 @@
sub Init()
m.top.backgroundColor = "0x1c1c1c"
m.loadingIndicator = m.top.FindNode("loadingIndicator")
InitScreenStack()
ShowGridScreen()
RunContentTask()
end sub
' The OnKeyEvent() function receives remote control key events
function OnkeyEvent(key as string, press as boolean) as boolean
result = false
if press
' handle "back" key press
if key = "back"
numberOfScreens = m.screenStack.Count()
' close top screen if there are two or more screens in the screen stack
if numberOfScreens > 1
CloseScreen(invalid)
result = true
end if
end if
end if
' The OnKeyEvent() function must return true if the component handled the event,
' or false if it did not handle the event.
return result
end function
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="MainScene" extends="Scene">
<script type="text/brightscript" uri="MainScene.brs" />
<script type="text/brightscript" uri="UILogic/VideoPlayerLogic.brs" />
<script type="text/brightscript" uri="UILogic/ScreenStackLogic.brs" />
<script type="text/brightscript" uri="UILogic/ContentTaskLogic.brs" />
<script type="text/brightscript" uri="UILogic/VideoDetailsTaskLogic.brs" />
<script type="text/brightscript" uri="UILogic/GridScreenLogic.brs" />
<children>
<!-- LoadingIndicator should be visible only in case of waiting for content -->
<Label
id="loadingIndicator"
text="Loading..."
width="1280"
height="720"
translation="[0, 0]"
horizAlign="center"
vertAlign="center"
visible="false"
font="font:MediumBoldSystemFont"
/>
</children>
</component>
@@ -0,0 +1,15 @@
import "pkg:/source/utils/Utils.bs"
sub OnContentSet()
content = m.top.itemContent
if content <> invalid
m.top.FindNode("titleLabel").text = content.title
m.top.FindNode("poster").uri = content.hdPosterUrl
if content.length <> invalid and content.length <> 0
m.top.FindNode("durationLabel").text = RokuYoutube.Utils.GetFormattedTime(content.length)
else
m.top.FindNode("durationRect").visible = false
end if
end if
end sub
@@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="RowListItemComponent" extends="Group" xsi:noNamespaceSchemaLocation="https://devtools.web.roku.com/schema/RokuSceneGraph.xsd">
<interface>
<field id="itemContent" type="node" onChange="OnContentSet" />
</interface>
<script type="text/brightscript" uri="RowListItemComponent.brs" />
<children>
<Poster
id="poster"
loadDisplayMode="scaleToFit"
width="320"
height="180"
loadWidth="320"
loadHeight="180"
/>
<Rectangle
id="durationRect"
width="60"
height="25"
color="0x000000"
opacity="0.8"
translation="[260, 145]"
>
<Label
width="60"
height="25"
id="durationLabel"
horizAlign="center"
vertAlign="center"
font="font:SmallestSystemFont"
inheritParentOpacity="true"
/>
</Rectangle>
<Label
id="titleLabel"
width="320"
height="25"
font="font:SmallestSystemFont"
translation="[0, 200]"
/>
</children>
</component>
@@ -0,0 +1,13 @@
sub RunContentTask()
m.contentTask = CreateObject("roSGNode", "MainLoaderTask")
m.contentTask.ObserveField("content", "OnMainContentLoaded")
m.contentTask.control = "run"
m.loadingIndicator.visible = true
end sub
sub OnMainContentLoaded()
m.GridScreen.SetFocus(true)
m.loadingIndicator.visible = false
m.GridScreen.content = m.contentTask.content
end sub
@@ -0,0 +1,20 @@
sub ShowGridScreen()
m.GridScreen = CreateObject("roSGNode", "GridScreen")
m.GridScreen.ObserveField("rowItemSelected", "OnGridScreenItemSelected")
ShowScreen(m.GridScreen)
end sub
sub OnGridScreenItemSelected(event as object)
grid = event.GetRoSGNode()
selectedPair = event.GetData()
selectedRow = selectedPair[0]
selectedRowItem = selectedPair[1]
rowContent = grid.content.GetChild(selectedRow)
itemContent = rowContent.GetChild(selectedRowItem)
videoId = itemContent.id
RunVideoDetailsTask(videoId)
end sub
@@ -0,0 +1,34 @@
sub InitScreenStack()
m.screenStack = []
end sub
sub ShowScreen(node as object)
prev = m.screenStack.Peek() ' take current screen from screen stack but don't delete it
if prev <> invalid
prev.visible = false ' hide current screen if it exist
end if
' show new screen
m.top.AppendChild(node)
node.visible = true
node.SetFocus(true)
m.screenStack.Push(node) ' add new screen to the screen stack
end sub
sub CloseScreen(node as object)
if node = invalid or (m.screenStack.Peek() <> invalid and m.screenStack.Peek().IsSameNode(node))
last = m.screenStack.Pop() ' remove screen from screenStack
last.visible = false ' hide screen
m.top.RemoveChild(node) ' remove screen from scene
' take previous screen and make it visible
prev = m.screenStack.Peek()
if prev <> invalid
prev.visible = true
prev.SetFocus(true)
end if
end if
end sub
function GetCurrentScreen()
return m.screenStack.Peek()
end function
@@ -0,0 +1,12 @@
sub RunVideoDetailsTask(videoId)
m.videoDetailsTask = CreateObject("roSGNode", "VideoDetailsLoaderTask")
m.videoDetailsTask.setField("videoid", videoId)
m.videoDetailsTask.ObserveField("content", "OnVideoDetailsLoaded")
m.videoDetailsTask.control = "run"
m.loadingIndicator.visible = true ' show loading indicator while content is loading
end sub
sub OnVideoDetailsLoaded()
m.loadingIndicator.visible = false
ShowVideoScreen(m.videoDetailsTask.content.metadata, m.videoDetailsTask.content.sponsorblock)
end sub
@@ -0,0 +1,87 @@
sub ShowVideoScreen(videoMetadata as object, videoSponsorBlock as object)
m.videoPlayer = CreateObject("roSGNode", "Video")
rowNode = CreateObject("roSGNode", "ContentNode")
rowNode.url = videoMetadata.formatStreams[videoMetadata.formatStreams.Count() - 1].url
SetCaptions(videoMetadata, m.videoPlayer, rowNode)
m.videoPlayer.content = rowNode
ShowScreen(m.videoPlayer)
m.videoPlayer.control = "play"
m.videoPlayer.ObserveField("state", "OnVideoPlayerStateChange")
m.videoPlayer.ObserveField("visible", "OnVideoVisibleChange")
if videoSponsorBlock <> invalid
newFields = {}
newFields["sponsorblock"] = videoSponsorBlock
m.videoPlayer.addFields(newFields)
m.videoPlayer.seekMode = "accurate"
m.videoPlayer.ObserveField("position", "OnVideoPositionChange")
end if
end sub
sub SetCaptions(videoMetadata as object, videoPlayer as object, contentNode as object)
' TODO: check if we have caption settings ON
' TODO: read favorate language from system settings
' TODO: populate list of caption tracks
if videoMetadata.captions.Count() = 0
return
end if
videoPlayer.globalCaptionMode = "ON"
contentNode.ClosedCaptions = True
selectedCaption = videoMetadata.captions[0]
' Use favorite caption langauage, or the first one
for each caption in videoMetadata.captions
if caption.language_code = "en"
selectedCaption = caption
exit for
end if
end for
contentNode.SubtitleConfig = {
ShowSubtitle: 1,
TrackName: "https://invidious.esmailelbob.xyz" + selectedCaption.url
}
end sub
sub OnVideoPlayerStateChange()
state = m.videoPlayer.state
if state = "error" or state = "finished"
CloseScreen(m.videoPlayer)
end if
end sub
sub OnVideoVisibleChange()
if m.videoPlayer.visible = false and m.top.visible = true
m.videoPlayer.control = "stop"
m.videoPlayer.content = invalid
screen = GetCurrentScreen()
screen.SetFocus(true)
end if
end sub
sub OnVideoPositionChange()
SkipSponsorBlockSections()
end sub
sub SkipSponsorBlockSections()
segments = m.videoPlayer.getField("sponsorblock")
for each segment in segments
if segment["actionType"] = "skip"
segmentRange = segment["segment"]
segmentStart = segmentRange[0]
segmentEnd = segmentRange[1]
currentPosition = m.videoPlayer.position
if (segmentStart < currentPosition) and ((segmentEnd - 1) > currentPosition)
' TODO: if segmentEnd is at the end of the video, close video
m.videoPlayer.seek = segmentEnd
print("Skiping section:" + segment["category"])
return
end if
end if
end for
end sub
+57
View File
@@ -0,0 +1,57 @@
import "pkg:/source/services/Invidious.bs"
sub Init()
' set the name of the function in the Task node component to be executed when the state field changes to RUN
' in our case this method executed after the following cmd: m.contentTask.control = "run"(see Init method in MainScene)
m.top.functionName = "GetContent"
end sub
sub GetContent()
rootChildren = []
trendingJson = RokuYoutube.Services.Invidious.GetTrending()
trending = GetCategoryContent("Trending", trendingJson)
if trending <> invalid
rootChildren.Push(trending)
end if
popularJson = RokuYoutube.Services.Invidious.GetPopular()
popular = GetCategoryContent("Popular", popularJson)
if popular <> invalid
rootChildren.Push(popular)
end if
' set up a root ContentNode to represent rowList on the GridScreen
contentNode = CreateObject("roSGNode", "ContentNode")
contentNode.Update({
children: rootChildren
}, true)
' populate content field with root content node.
' Observer(see OnMainContentLoaded in MainScene.brs) is invoked at that moment
m.top.content = contentNode
end sub
function GetCategoryContent(category as string, json as object) as object
if json <> invalid
row = {}
row.title = category
row.children = []
for each item in json ' parse items and push them to row
itemData = GetItemData(item)
row.children.Push(itemData)
end for
return row
end if
end function
function GetItemData(video as object) as object
item = {}
item.title = video.title
item.description = video.description
item.hdPosterURL = video.videoThumbnails[0].url
item.releaseDate = video.publishedText
item.id = video.videoId
item.length = video.lengthSeconds
return item
end function
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="MainLoaderTask" extends="Task">
<interface>
<field id="content" type="node" />
</interface>
<script type="text/brightscript" uri="MainLoaderTask.brs" />
</component>
@@ -0,0 +1,33 @@
import "pkg:/source/services/SponsorBlock.bs"
import "pkg:/source/services/Invidious.bs"
sub Init()
' set the name of the function in the Task node component to be executed when the state field changes to RUN
' in our case this method executed after the following cmd: m.contentTask.control = "run"(see Init method in MainScene)
m.top.functionName = "GetVideoContent"
end sub
sub GetVideoContent()
metadata = GetVideoMetadata()
sponsorBlock = GetVideoSponsorBlock()
contentNode = CreateObject("roSGNode", "ContentNode")
content = {}
content["metadata"] = metadata
content["sponsorblock"] = sponsorBlock
contentNode.addFields(content)
m.top.content = contentNode
end sub
function GetVideoMetadata()
videoId = m.top.getField("videoid")
return RokuYoutube.Services.Invidious.GetVideoMetadataForVideo(videoId)
end function
function GetVideoSponsorBlock()
videoId = m.top.getField("videoid")
return RokuYoutube.Services.SponsorBlock.GetSkipSegmentsForVideo(videoId)
end function
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="VideoDetailsLoaderTask" extends="Task">
<interface>
<field id="content" type="node" />
<field id="videoid" type="string" />
</interface>
<script type="text/brightscript" uri="VideoDetailsLoaderTask.brs" />
</component>
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+20
View File
@@ -0,0 +1,20 @@
title=Roku Youtube
major_version=1
minor_version=0
build_version=00001
## Channel Assets
### Main Menu Icons / Channel Poster Artwork
#### Image sizes are FHD: 540x405px | HD: 290x218px | SD: 214x144px
mm_icon_focus_fhd=pkg:/images/channel-poster_fhd.png
mm_icon_focus_hd=pkg:/images/channel-poster_hd.png
mm_icon_focus_sd=pkg:/images/channel-poster_sd.png
### Splash Screen + Loading Screen Artwork
#### Image sizes are FHD: 1920x1080px | HD: 1280x720px | SD: 720x480px
splash_screen_fhd=pkg:/images/splash-screen_fhd.jpg
splash_screen_hd=pkg:/images/splash-screen_hd.jpg
splash_screen_sd=pkg:/images/splash-screen_sd.jpg
splash_color=#000000
splash_min_time=1
+47
View File
@@ -0,0 +1,47 @@
' TODO:
' - New template
' - Use brighterscript
' - Use classes and tests
' - Use vs code config
' - Use unit tests
' - Use bs promises
' - Check tools under roku community (linter, etc)
' - Use RALE app to make UIs
' - Fix non-Latin characters (Unicode on Roku sucks)
' FEATURES:
' - Sign in with account
' - Youtube backend abstraction (Invidious vs TubeArchvist)
' - Settings page
' - Configure SponsorBlock
' - Configure Invidious Backend (allow self-hosted)
' - Closed caption settings?
' - Search page
' - Channel page
' - Comments page? (especially on live videos)
' - Dislike count?
' - Closed caption
' - Launch app to specific video (deep link)
' - Youtube android app -> share -> custom app -> push to tv
function Main(args as dynamic)
initScreen()
end function
sub initScreen()
screen = CreateObject("roSGScreen")
m.port = CreateObject("roMessagePort")
screen.setMessagePort(m.port)
scene = screen.CreateScene("MainScene")
screen.show()
while(true)
msg = wait(0, m.port)
msgType = type(msg)
if msgType = "roSGScreenEvent"
if msg.isScreenClosed() then return
end if
end while
end sub
+38
View File
@@ -0,0 +1,38 @@
' TODO: remove Requests.brs and import it from installed package
import "pkg:/source/services/Requests.brs"
namespace RokuYoutube.Services.Invidious
const API_URL = "https://invidious.esmailelbob.xyz"
const POPULAR_ENDPOINT = "/api/v1/popular"
const TRENDING_ENDPOINT = "/api/v1/trending"
const VIDEOS_ENDPOINT = "/api/v1/videos"
function GetPopular()
url = `${API_URL}${POPULAR_ENDPOINT}`
response = Requests().get(url)
if response.statuscode = 200
return response.json
end if
end function
function GetTrending()
url = `${API_URL}${TRENDING_ENDPOINT}`
response = Requests().get(url)
if response.statuscode = 200
return response.json
end if
end function
function GetVideoMetadataForVideo(videoId as string)
url = `${API_URL}${VIDEOS_ENDPOINT}/${videoId}`
response = Requests().get(url)
' TODO: handle 500 {"error":"This video is unavailable"}
if response.statuscode = 200
return response.json
end if
end function
end namespace
+479
View File
@@ -0,0 +1,479 @@
' /**
' * @module requests
' */
' /**
' * @memberof module:requests
' * @name Requests
' * @function
' * @description Main Class for Requests
' * @param {Dynamic} args - Associative array of args to pass into Alacrity
function Requests() as Object
return {
request : Requests_request
get: Requests_getRequest
post: Requests_postRequest
}
end function
function Requests_getRequest(url as String, args=invalid)
return m.request("GET", url, args)
end function
function Requests_postRequest(url as String, args=invalid)
return m.request("POST", url, args)
end function
function Requests_request(method, url as String, args as Object)
_params = {}
_headers = {}
' _cookies = invalid
_data = invalid
_json = invalid
_timeout = 30000
_retryCount = 0
' _allow_redirects = true
_verify = "common:/certs/ca-bundle.crt"
_useCache = true
_cacheSeconds = invalid
if args <> invalid and type(args) = "roAssociativeArray"
if args.params <> invalid and type(args.params) = "roAssociativeArray"
_params = args.params
end if
if args.headers <> invalid and type(args.headers) = "roAssociativeArray"
_headers = args.headers
end if
if args.data <> invalid and (type(args.data) = "String" or type(args.data) = "roString")
_data = args.data
end if
if args.json <> invalid and type(args.json) = "roAssociativeArray"
_json = FormatJson(args.json)
end if
if args.timeout <> invalid and (type(args.timeout) = "Integer" or type(args.timeout) = "roInteger")
_timeout = args.timeout
end if
if args.retryCount <> invalid and (type(args.retryCount) = "Integer" or type(args.retryCount) = "roInteger")
_retryCount = args.retryCount
end if
if args.verify <> invalid and (type(args.verify) = "String" or type(args.verify) = "roString")
_verify = args.verify
end if
if args.useCache <> invalid and (type(args.useCache) = "Boolean" or type(args.useCache) = "roBoolean")
_useCache = args.useCache
end if
if args.cacheSeconds <> invalid and (type(args.cacheSeconds) = "Integer" or type(args.cacheSeconds) = "roInteger")
_cacheSeconds = args.cacheSeconds
end if
end if
' Constructs and sends a Request.
' :param method: method for the new Request object.
' :param url: URL for the new Request object.
' :param params: (optional) AA to append as a query string to the Request.
' :param data: (optional) String to send in the body of the Request.
' :param json: (optional) A JSON serializable object to send in the body of the Request.
' :param headers: (optional) AA of HTTP Headers to send with the Request.
' :param cookies: (optional) Dict or CookieJar object to send with the Request.
' :param timeout: (optional) How many seconds to wait for the server to send data
' before giving up, as a float
' :param retryCount: (optional) How many times to retry a failed response.
' :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection.
' :param verify: (optional) String to specify SSL cert bundle.
' If this is set to empty string `InitClientCertificates` is not called on roUrlTransfer.
' Defaults to `common:/certs/ca-bundle.crt`
' :param useCache: (optional) Boolean. Enable/Disable caching. Defaults to true
' :param cacheSeconds: (optional) Integer. Enable/Disable caching. Defaults to response's Cache-Control if it exists
' :return: :class:`Requests <Response>` object
' Usage::
' req = Requests().get('http://httpbin.org/get')
requestHeaders = Requests_headers()
requestHeaders.addHeadersAA(_headers)
requestQueryString = Requests_queryString()
requestQueryString.addParamsAA(_params)
' Setup the data (we overwrite JSON if it's provided)
if _data <> invalid
data = _data
else if _json <> invalid
data = _json
requestHeaders.addHeader("Content-Type", "application/json")
else
data = ""
end if
'TODO: Add Cookies Support
'urlTransfer.EnableCookies()
'urlTransfer.GetCookies(domain, path)
'urlTransfer.AddCookies(cookies)
'urlTransfer.ClearCookies()
url = requestQueryString.append(url)
headers = requestHeaders._headers
rc = Requests_cache(method, url, headers)
response = invalid
if rc <> invalid and _useCache
response = rc.get(_cacheSeconds)
end if
if response = invalid
response = Requests_run(method, url, headers, data, _timeout, _retryCount, _verify)
if rc <> invalid and _useCache
rc.put(response)
end if
end if
return response
end function
function Requests_run(method, url, headers, data, timeout, retryCount, verify)
urlTransfer = RequestsUrlTransfer(true, true, verify)
urlTransfer.setUrl(url)
urlTransfer.SetHeaders(headers)
? "[http] ------ START HTTP REQUEST ------"
? "[http] URL:", urlTransfer.GetURL()
? "[http] Timeout= ", timeout
? "[http] Headers: ", headers
cancel_and_return = false
responseEvent = invalid
requestDetails = {
timesTried : 0,
}
'while we still have try times
while retryCount >= 0
'deincrement the number of retries
retryCount = retryCount - 1
requestDetails.timesTried = requestDetails.timesTried + 1
? "[http] Method: ", method
if method="POST"
sent = urlTransfer.AsyncPostFromString(data)
else if method = "GET"
sent = urlTransfer.AsyncGetToString()
else if method = "HEAD"
sent = urlTransfer.AsyncHead()
else
'PUT, PATCH, DELETE
urlTransfer.SetRequest(method)
sent = urlTransfer.AsyncPostFromString(data)
end if
if sent = true
clock = CreateObject("roTimespan")
timeout_call = clock.TotalMilliseconds() + timeout
while true and cancel_and_return = false
if m.top <> invalid
if m.top.quit <> invalid
cancel_and_return = m.top.quit
end if
end if
event = urlTransfer.GetPort().GetMessage()
if type(event) = "roUrlEvent"
exit while
end if
if clock.TotalMilliseconds() > timeout_call
exit while
end if
end while
if type(event) = "roUrlEvent"
responseEvent = event
responseCode = event.GetResponseCode()
? "[http] Response Code", responseCode
if responseCode > 0 and responseCode < 400
'Response was good, so we break the while
exit while
else
'We have a bad response
? "[http] Bad response", responseCode
? "[http] Will Retry ", retryCount
end if
else
if m.cancel_and_return = true
? "[http] Killing the Task"
exit while
else
'We timed out so we should cancel the request
? "[http] Event Timed Out"
urlTransfer.AsyncCancel()
'Exponential backoff timeouts
timeout = timeout * 2
? "[http] Timeout=", timeout
end if
end if
end if
end while
? "[http] ------ END HTTP REQUEST ------"
return Requests_response(urlTransfer, responseEvent, requestDetails)
end function
function Requests_cache(method as String, url as String, headers as Object)
if method <> "GET"
return invalid
end if
cacheKey = url
headersString = FormatJson(headers)
if headersString <> invalid
cacheKey = cacheKey + headersString
end if
ba = CreateObject("roByteArray")
ba.FromAsciiString(cacheKey)
digest = CreateObject("roEVPDigest")
digest.Setup("md5")
md5Key = digest.Process(ba)
fileLocation = "cachefs:/" + md5Key
return {
_cacheKey: cacheKey
_md5Key: md5Key
location: fileLocation
exists: function() as Boolean
fs = CreateObject("roFileSystem")
return fs.Exists(m.location)
end function
get: function(expireSeconds) as Object
if m.exists()
fileData = ReadAsciiFile(m.location)
if fileData <> ""
dataSplit = fileData.Split(chr(10))
if dataSplit.count() = 2
fileTimeastamp = dataSplit[0].toInt()
date = CreateObject("roDateTime")
nowTimestamp = date.AsSeconds()
response = ParseJson(dataSplit[1])
if response <> invalid
if expireSeconds = invalid and response.headers <> invalid
cacheControl = response.headers["cache-control"]
if cacheControl <> invalid
cacheControlSplit = cacheControl.split(",")
if cacheControlSplit.count() > 1
cacheControlMaxAgeSplit = cacheControlSplit[1].split("=")
if cacheControlMaxAgeSplit.count() > 1
expireSeconds = val(cacheControlMaxAgeSplit[1])
end if
end if
end if
end if
if expireSeconds <> invalid
if fileTimeastamp + expireSeconds >= nowTimestamp
response.cacheHit = true
return response
end if
end if
end if
end if
end if
end if
return invalid
end function
put: function(response) as Boolean
date = CreateObject("roDateTime")
timestamp = date.AsSeconds()
putString = stri(timestamp) + chr(10)
jsonResponse = FormatJson(response)
if jsonResponse <> invalid
putString = putString + jsonResponse
return WriteAsciiFile(m.location, putString)
end if
return false
end function
delete: function() as Boolean
fs = CreateObject("roFileSystem")
return fs.Delete(m.location)
end function
}
end function
function Requests_headers()
return {
_headers: {}
addHeader: function(key as String, value as String)
m._headers[key] = value
end function
addHeadersAA: function(headers as Object)
m._headers.Append(headers)
end function
build: m.get
get: m._headers
}
end function
function Requests_queryString()
return {
_urlTransfer: CreateObject("roUrlTransfer")
_qs_array: []
addString: function(params as String)
if Requests_Utils_inString("&", params)
split_params = params.split("&")
for each param in split_params
if Requests_Utils_inString("=", param)
split_param = param.split("=")
m.addParamKeyValue(split_param[0], split_param[1])
else
m.addParamKeyValue(param, "")
end if
end for
else if Requests_Utils_inString("=", params)
split_params = params.split("=")
m.addParamKeyValue(split_params[0], split_params[1])
else
m.addParamKeyValue(params, "")
end if
end function
addParamKeyValue: function(param as String, key as String)
m._qs_array.push([param, key])
end function
addParamsAA: function(params as Object)
for each item in params.Items()
m.addParamKeyValue(item.key, item.value)
end for
end function
addParamsArray: function(params as Object)
if params.Count() > 0
for each item in params
if item.Count() > 1
m.addParamKeyValue(item[0], item[1])
else if item.Count() > 0
m.addParamKeyValue(item[0], "")
end if
end for
end if
end function
build: function() as String
' "build the QS output from the added params"
output = ""
c = 0
for each qs in m._qs_array
if c = 0
output = qs[0] + "=" + m._urlTransfer.Escape(qs[1])
else
output = output + "&" + qs[0] + "=" + m._urlTransfer.Escape(qs[1])
end if
c += 1
end for
return output
end function
append: function(url as String) as String
' "append the QS on a provided URL"
if m._qs_array.Count() > 0
if Requests_Utils_inString("?", url)
if url.right(1) = "?"
return url + m.build()
else
return url + "&" + m.build()
end if
else
return url + "?" + m.build()
end if
end if
return url
end function
}
end function
function Requests_response(urlTransfer as Object, responseEvent as Object, requestDetails as Object)
rr = {}
rr.timesTried = requestDetails.timesTried
rr.url = urlTransfer.GetUrl()
rr.ok = false
rr.cacheHit = false
if responseEvent <> invalid
rr.statusCode = responseEvent.GetResponseCode()
rr.text = responseEvent.GetString()
rr.headers = responseEvent.GetResponseHeaders()
rr.headersArray = responseEvent.GetResponseHeadersArray()
rr.GetSourceIdentity = responseEvent.GetSourceIdentity()
rr.GetFailureReason = responseEvent.GetFailureReason()
rr.target_ip = responseEvent.GetTargetIpAddress()
if rr.statusCode > 0 and rr.statusCode < 400
rr.ok = true
end if
end if
if rr.text <> invalid
rr.json = parseJson(rr.text)
rr.body = rr.text
end if
return rr
end function
function RequestsUrlTransfer(EnableEncodings as Boolean, retainBodyOnError as Boolean, verify as String)
_urlTransfer = CreateObject("roUrlTransfer")
_urlTransfer.SetPort(CreateObject("roMessagePort"))
_urlTransfer.EnableEncodings(enableEncodings)
_urlTransfer.RetainBodyOnError(retainBodyOnError)
if verify <> ""
_urlTransfer.SetCertificatesFile(verify)
_urlTransfer.InitClientCertificates()
end if
return _urlTransfer
end function
function Requests_Utils_inString(char as String, strValue as String)
for each single_char in strValue.split("")
if single_char = char
return true
end if
end for
return false
end function
+18
View File
@@ -0,0 +1,18 @@
' TODO: remove Requests.brs and import it from installed package
import "pkg:/source/services/Requests.brs"
namespace RokuYoutube.Services.SponsorBlock
const API_URL = "https://sponsor.ajay.app"
const SKIP_SEGMENT_ENDPOINT = "/api/skipSegments"
const CATEGORIES = "&category=sponsor&category=selfpromo&category=interaction&category=intro&category=outro&category=preview&category=music_offtopic"
function GetSkipSegmentsForVideo(videoId as string)
url = `${API_URL}${SKIP_SEGMENT_ENDPOINT}?videoID=${videoId}${CATEGORIES}`
response = Requests().get(url)
if response.statuscode = 200
return response.json
end if
end function
end namespace
+14
View File
@@ -0,0 +1,14 @@
namespace RokuYoutube.Utils
' Helper function convert seconds to mm:ss format
' getTime(138) returns 2:18
function GetFormattedTime(length as integer) as string
minutes = (length \ 60).ToStr()
seconds = length mod 60
if seconds < 10
seconds = "0" + seconds.ToStr()
else
seconds = seconds.ToStr()
end if
return minutes + ":" + seconds
end function
end namespace