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,127 @@
import "pkg:/source/utils/StringUtils.bs"
class ApplicationInfo
public node as object
public roDeviceInfo as object
public roAppInfo as object
function new(node as object)
m.node = node
m.roDeviceInfo = CreateObject("roDeviceInfo")
m.roAppInfo = CreateObject("roAppInfo")
end function
function GetLocalIpAddress() as dynamic
if StringUtils.IsNullOrEmpty(m.ipAddress)
ips = m.roDeviceInfo.GetIPAddrs()
for each ip in ips
m.ipAddress = ips[ip]
return m.ipAddress
end for
end if
return m.ipAddress
end function
function GetUserCountryCode() as string
if StringUtils.IsNullOrEmpty(m.countryCode)
m.countryCode = m.roDeviceInfo.GetUserCountryCode()
end if
return m.countryCode
end function
function GetAppInfo() as object
if m.appInfo = invalid
m.appInfo = {
id: m.roAppInfo.GetID(),
version: m.roAppInfo.GetVersion(),
git_commit_hash: m.roAppInfo.GetValue("git_commit_sha"),
lib_version: m.GetLibVersion(),
lib_git_commit_hash: m.GetLibGitCommitHash()
}
m.appInfo["lib_version_latest"] = "N/A"
m.appInfo["lib_url"] = "N/A"
m.appInfo["lib_url_type"] = "N/A"
scene = m.node.getScene()
if scene.playletLibLoadedUrl <> invalid
m.appInfo["lib_url"] = scene.playletLibLoadedUrl.link
m.appInfo["lib_url_type"] = scene.playletLibLoadedUrl.type
end if
end if
if m.appInfo.lib_version_latest = "N/A"
if not StringUtils.IsNullOrEmpty(m.node.lib_version_latest)
m.appInfo["lib_version_latest"] = m.node.lib_version_latest
else
m.node@.GetLatestPlayletLibVersion(invalid)
end if
end if
return m.appInfo
end function
function GetDeviceInfo() as object
if m.deviceInfo = invalid
m.deviceInfo = {
model: m.roDeviceInfo.GetModel(),
model_display_name: m.roDeviceInfo.GetModelDisplayName(),
model_type: m.roDeviceInfo.GetModelType(),
model_details: m.roDeviceInfo.GetModelDetails(),
os_version: m.roDeviceInfo.GetOSVersion(),
display_type: m.roDeviceInfo.GetDisplayType(),
display_mode: m.roDeviceInfo.GetDisplayMode(),
display_aspect_ratio: m.roDeviceInfo.GetDisplayAspectRatio(),
display_size: m.roDeviceInfo.GetDisplaySize(),
video_mode: m.roDeviceInfo.GetVideoMode(),
ui_resolution: m.roDeviceInfo.GetUIResolution(),
graphics_platform: m.roDeviceInfo.GetGraphicsPlatform(),
internet_status: m.roDeviceInfo.GetInternetStatus(),
user_country_code: m.roDeviceInfo.GetUserCountryCode(),
friendly_name: m.roDeviceInfo.GetFriendlyName()
}
end if
return m.deviceInfo
end function
function GetLibVersion() as string
values = m.GetLibManifestValues()
Major = values["major_version"].toInt()
Minor = values["minor_version"].toInt()
Build = values["build_version"].toInt()
return `${Major}.${Minor}.${Build}`
end function
function GetLibGitCommitHash() as string
values = m.GetLibManifestValues()
if values.doesexist("git_commit_sha")
return values["git_commit_sha"]
end if
return ""
end function
function GetLibManifestValues() as object
if m.libManifestValues = invalid
libManifest = ReadAsciiFile("libpkg:/manifest")
lines = libManifest.Tokenize(`\n`)
values = {}
for each line in lines
if line.left(1) = "#"
continue for
end if
keyValuePair = line.Tokenize("=")
if keyValuePair.Count() <> 2
continue for
end if
values[keyValuePair[0]] = keyValuePair[1]
end for
m.libManifestValues = values
end if
return m.libManifestValues
end function
end class
@@ -0,0 +1,690 @@
#const DISABLE_CACHE = false
import "pkg:/source/roku_modules/log/LogMixin.brs"
import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
namespace HttpClient
enum QueryParamArrayType
CommaSeparated
Repeated
end enum
function Get(url as string) as HttpRequest
return (new HttpRequest()).Method("GET").Url(url)
end function
function Post(url as string, data as string) as HttpRequest
return (new HttpRequest()).Method("POST").Url(url).Body(data)
end function
function PostJson(url as string, data as object) as HttpRequest
return (new HttpRequest()).Method("POST").Url(url).Json(data)
end function
function Put(url as string, data as string) as HttpRequest
return (new HttpRequest()).Method("PUT").Url(url).Body(data)
end function
function PutJson(url as string, data as object) as HttpRequest
return (new HttpRequest()).Method("PUT").Url(url).Json(data)
end function
function Delete(url as string) as HttpRequest
return (new HttpRequest()).Method("DELETE").Url(url)
end function
function Head(url as string) as HttpRequest
return (new HttpRequest()).Method("HEAD").Url(url)
end function
class HttpRequest
public urlTransfer as object
function new()
m.log = new log.Logger("HttpRequest")
m._timeoutSeconds = 30
end function
function Method(method as string) as HttpRequest
m._method = Ucase(method)
return m
end function
function Url(url as string) as HttpRequest
m._url = url
return m
end function
function QueryParam(key as string, value as dynamic) as HttpRequest
if value = invalid
return m
end if
if m._queryParams = invalid
m._queryParams = {}
end if
m._queryParams[key] = value
return m
end function
function QueryParamArray(key as string, valueArray as dynamic, arrayType as HttpClient.QueryParamArrayType) as HttpRequest
if valueArray = invalid
return m
end if
if m._queryParams = invalid
m._queryParams = {}
end if
m._queryParams[key] = {
value: valueArray,
__arrayType: arrayType
}
return m
end function
function QueryParams(queryParams as object) as HttpRequest
if m._queryParams = invalid
m._queryParams = {}
end if
m._queryParams.append(queryParams)
return m
end function
function PathParam(key as string, value as string) as HttpRequest
if m._pathParams = invalid
m._pathParams = {}
end if
m._pathParams[key] = value
return m
end function
function PathParams(pathParams as object) as HttpRequest
if m._pathParams = invalid
m._pathParams = {}
end if
m._pathParams.append(pathParams)
return m
end function
function Header(key as string, value as string) as HttpRequest
if m._headers = invalid
m._headers = {}
end if
m._headers[key] = value
return m
end function
function Headers(headers as object) as HttpRequest
if m._headers = invalid
m._headers = {}
end if
m._headers.append(headers)
return m
end function
function Body(body as dynamic) as HttpRequest
m._body = ValidString(body)
return m
end function
function Json(body as object) as HttpRequest
m.Body(FormatJson(body))
m.Header("Content-Type", "application/json")
return m
end function
function TimeoutSeconds(timeoutSeconds as integer) as HttpRequest
m._timeoutSeconds = timeoutSeconds
return m
end function
function NoCache() as HttpRequest
m._noCache = true
return m
end function
function CacheSeconds(expireSeconds as integer) as HttpRequest
m._expireSeconds = expireSeconds
if expireSeconds < 0
m.NoCache()
end if
return m
end function
function Cancellation(cancellation as object) as HttpRequest
m._cancellation = cancellation
return m
end function
function ToCurlCommand() as string
command = `curl "${m.BuildUrl()}"`
command += ` \\\n -X ${m._method}`
command += ` \\\n --max-time ${m._timeoutSeconds}`
if m._headers <> invalid
for each key in m._headers
command += ` \\\n -H '${key}: ${m._headers[key]}'`
end for
end if
if not StringUtils.IsNullOrEmpty(m._body)
command += ` \\\n -d '${m._body}'`
end if
return command
end function
function Send() as HttpRequest
return m.DoSend(false)
end function
function SendAndForget() as HttpRequest
return m.DoSend(true)
end function
private function DoSend(forget as boolean) as HttpRequest
if m.urlTransfer <> invalid or m._cache <> invalid
return m
end if
#if DISABLE_CACHE
m._noCache = true
#end if
if m._noCache <> true
cache = HttpClientCache.Get(m)
if cache <> invalid
m.log.info("Cache hit", m._method, m.BuildUrl())
m._cache = cache
return m
end if
end if
m.urlTransfer = m.CreateRoUrlTransfer()
m.urlTransfer.setUrl(m.BuildUrl())
if m._headers <> invalid
m.urlTransfer.SetHeaders(m._headers)
end if
if not forget
m.urlTransfer.SetMessagePort(CreateObject("roMessagePort"))
end if
m.log.info("Sending", m._method, m.urlTransfer.GetURL(), "ID:", m.urlTransfer.GetIdentity())
#if DEBUG
? `════════ curl command ════════\n${m.ToCurlCommand()}\n══════════════════════════════`
#end if
if m._method = "POST"
m._sent = m.urlTransfer.AsyncPostFromString(m._body)
else if m._method = "GET"
m._sent = m.urlTransfer.AsyncGetToString()
else if m._method = "HEAD"
m._sent = m.urlTransfer.AsyncHead()
else
m.urlTransfer.SetRequest(m._method)
m._sent = m.urlTransfer.AsyncPostFromString(m._body)
end if
if m._sent <> true
m.log.error("Failed to send request")
end if
return m
end function
function IsCancelled() as boolean
if m._cancelled = true
return m._cancelled
end if
if m._cancellation = invalid or m._cancellation.node = invalid or m._cancellation.field = invalid
return false
end if
if m._cancellation.node[m._cancellation.field] = m._cancellation.value
m._cancelled = true
end if
return m._cancelled = true
end function
function Await() as HttpResponse
if m.urlTransfer = invalid and m._cache = invalid
m.Send()
end if
if m._sent <> true or m._cache <> invalid
return new HttpResponse(m, invalid)
end if
if m.IsCancelled()
return new HttpResponse(m, invalid)
end if
messagePort = m.urlTransfer.GetMessagePort()
if messagePort = invalid
throw "Can't await request without a message port. use Send(andForget=false) in order to await request."
end if
if m._cancellation <> invalid
if m._cancellation.node <> invalid and m._cancellation.field <> invalid
m._cancellation.node.ObserveFieldScoped(m._cancellation.field, messagePort)
end if
end if
msg = wait(m._timeoutSeconds * 1000, messagePort)
if m._cancellation <> invalid
if m._cancellation.node <> invalid and m._cancellation.field <> invalid
' TODO:P2 use a separate node as a cancellation token
' This is to avoid removing observers other than our own
m._cancellation.node.UnobserveFieldScoped(m._cancellation.field)
end if
end if
if msg = invalid
' timeout
m.log.info("Timeout", "ID:", m.urlTransfer.GetIdentity())
m.urlTransfer.AsyncCancel()
else
eventType = type(msg)
if eventType = "roUrlEvent"
m.log.info("Finished", "ID:", m.urlTransfer.GetIdentity())
else if eventType = "roSGNodeEvent"
node = msg.getRoSGNode()
field = msg.getField()
value = msg.getData()
' cancellation
if node.isSameNode(m._cancellation.node) and field = m._cancellation.field and value = m._cancellation.value
m.log.info("Cancelled", "ID:", m.urlTransfer.GetIdentity())
m._cancelled = true
m.urlTransfer.AsyncCancel()
end if
end if
end if
response = new HttpResponse(m, msg)
if m.IsCancelled()
return response
end if
HttpClientCache.Set(response)
return response
end function
private function CreateRoUrlTransfer() as object
urlTransfer = CreateObject("roUrlTransfer")
urlTransfer.EnableEncodings(true)
urlTransfer.RetainBodyOnError(true)
if LCase(left(m._url, 6)).StartsWith("https:")
urlTransfer.SetCertificatesFile("common:/certs/ca-bundle.crt")
urlTransfer.InitClientCertificates()
end if
return urlTransfer
end function
' TODO:P2 refactor this monstrosity of a function
function BuildUrl() as string
if m._fullUrl <> invalid
return m._fullUrl
end if
url = m._url
if m._pathParams <> invalid
for each key in m._pathParams
value = m._pathParams[key]
if value = invalid
continue for
end if
if not IsString(value)
value = `${value}`
end if
url = url.Replace(`{${key}}`, value.EncodeUriComponent())
end for
end if
if m._queryParams <> invalid
hasQueryParams = url.InStr("?") <> -1
for each key in m._queryParams
value = m._queryParams[key]
if value = invalid
continue for
end if
if not IsString(value)
if IsAssociativeArray(value) and IsArray(value.value)
if value.__arrayType = HttpClient.QueryParamArrayType.Repeated
valueArray = value.value
for each item in valueArray
itemString = item
if not IsString(itemString)
itemString = `${itemString}`
end if
if hasQueryParams
url += "&" + key.EncodeUriComponent() + "=" + itemString.EncodeUriComponent()
else
url += "?" + key.EncodeUriComponent() + "=" + itemString.EncodeUriComponent()
hasQueryParams = true
end if
end for
else if value.__arrayType = HttpClient.QueryParamArrayType.CommaSeparated
valueArray = value.value
for i = 0 to valueArray.Count() - 1
itemString = valueArray[i]
if not IsString(itemString)
itemString = `${itemString}`
end if
itemString = itemString.EncodeUriComponent()
valueArray[i] = itemString
end for
joined = valueArray.join(",")
if hasQueryParams
url += "&" + key.EncodeUriComponent() + "=" + joined
else
url += "?" + key.EncodeUriComponent() + "=" + joined
hasQueryParams = true
end if
end if
else
value = `${value}`
if hasQueryParams
url += "&" + key.EncodeUriComponent() + "=" + value.EncodeUriComponent()
else
url += "?" + key.EncodeUriComponent() + "=" + value.EncodeUriComponent()
hasQueryParams = true
end if
end if
else
if hasQueryParams
url += "&" + key.EncodeUriComponent() + "=" + value.EncodeUriComponent()
else
url += "?" + key.EncodeUriComponent() + "=" + value.EncodeUriComponent()
hasQueryParams = true
end if
end if
end for
end if
m._fullUrl = url
return m._fullUrl
end function
end class
class HttpResponse
public request as HttpRequest
public event as object
function new(request as HttpRequest, event as object)
m.request = request
m.event = event
end function
function StatusCode() as integer
if m._statusCode <> invalid
return m._statusCode
end if
if m.IsCached()
m._statusCode = m.request._cache.statusCode
return m._statusCode
end if
if type(m.event) <> "roUrlEvent"
m._statusCode = 0
else
m._statusCode = m.event.GetResponseCode()
end if
return m._statusCode
end function
function IsSuccess() as boolean
statusCode = m.StatusCode()
return statusCode >= 200 and statusCode < 400
end function
function IsCached() as boolean
return m.request._cache <> invalid
end function
function TimedOut() as boolean
return not m.IsCached() and m.event = invalid
end function
function IsCancelled() as boolean
return m.request.IsCancelled()
end function
function Text() as dynamic
if m._text <> invalid
return m._text
end if
if m.IsCached()
m._text = m.request._cache.body
return m._text
end if
if not m.IsSuccess()
return invalid
end if
m._text = m.event.GetString()
return m._text
end function
function Json() as object
if m._json <> invalid
return m._json
end if
text = m.Text()
if text = invalid
return invalid
end if
m._json = ParseJson(text)
return m._json
end function
function Headers() as object
if m._headers <> invalid
return m._headers
end if
if m.IsCached()
m._headers = m.request._cache.headers
return m._headers
end if
if type(m.event) = "roUrlEvent"
m._headers = m.event.GetResponseHeaders()
else
m._headers = {}
end if
return m._headers
end function
function ErrorMessage() as string
if m._errorMessage <> invalid
return m._errorMessage
end if
if m.IsSuccess()
m._errorMessage = ""
else
if m.request._sent <> true
m._errorMessage = "Request not sent."
else if m.TimedOut()
m._errorMessage = "Request timed out."
else if m.IsCancelled()
m._errorMessage = "Request cancelled."
else if type(m.event) = "roUrlEvent"
m._errorMessage = `Reason :${m.event.GetFailureReason() }\nStatusCode: ${m.StatusCode()}\nBody: ${m.event.GetString()}`
end if
end if
return m._errorMessage
end function
end class
end namespace
' TODO:P2 introduce the concept of "loose" cache
' For playlists that show in a feed or in a search, we don't want to make a request to get the playlist details
' But if we have that information in the cache already, it can be used
namespace HttpClientCache
function GetLocation(request as HttpClient.HttpRequest) as dynamic
if request._cacheLocation <> invalid
return request._cacheLocation
end if
cacheKey = request.BuildUrl()
if request._headers <> invalid
headersString = FormatJson(request._headers)
cacheKey = cacheKey + headersString
end if
hash = CryptoUtils.GetMd5(cacheKey)
request._cacheLocation = `cachefs:/request_v1_${hash}.json`
return request._cacheLocation
end function
function GetFileSystem(request as HttpClient.HttpRequest) as object
if request._fileSystem = invalid
request._fileSystem = CreateObject("roFileSystem")
end if
return request._fileSystem
end function
function Exists(request as HttpClient.HttpRequest) as boolean
fileSystem = GetFileSystem(request)
if fileSystem = invalid
return false
end if
cacheLocation = GetLocation(request)
return fileSystem.Exists(cacheLocation)
end function
function Get(request as HttpClient.HttpRequest) as object
if request._noCache = true
return invalid
end if
if request._method <> "GET"
return invalid
end if
if not Exists(request)
return invalid
end if
cacheLocation = GetLocation(request)
cacheText = ReadAsciiFile(cacheLocation)
cacheObject = ParseJson(cacheText)
if cacheObject = invalid
Delete(request)
return invalid
end if
expireSeconds = request._expireSeconds
if expireSeconds = invalid and cacheObject.headers <> invalid
expireSeconds = ParseHeadersForCacheControl(cacheObject.headers)
end if
if expireSeconds = invalid
return invalid
end if
date = CreateObject("roDateTime")
nowTimestamp = date.AsSeconds()
if cacheObject.timestamp + expireSeconds < nowTimestamp
Delete(request)
return invalid
end if
return cacheObject
end function
function Set(response as HttpClient.HttpResponse) as void
if response.request._noCache = true or response.request._method <> "GET"
return
end if
if not response.IsSuccess()
return
end if
if response.request._expireSeconds = invalid
headers = response.Headers()
if headers = invalid
return
end if
if ParseHeadersForCacheControl(headers) = invalid
return
end if
end if
fileSystem = GetFileSystem(response.request)
if fileSystem = invalid
return
end if
date = CreateObject("roDateTime")
timestamp = date.AsSeconds()
cacheObject = {
timestamp: timestamp,
statusCode: response.StatusCode(),
headers: response.Headers(),
body: response.Text()
}
cacheLocation = GetLocation(response.request)
' TODO:P2 use a diferent format other than json for better performance
cacheText = FormatJson(cacheObject)
WriteAsciiFile(cacheLocation, cacheText)
end function
function Delete(request as HttpClient.HttpRequest) as boolean
fileSystem = GetFileSystem(request)
if fileSystem = invalid
return false
end if
cacheLocation = GetLocation(request)
return fileSystem.Delete(cacheLocation)
end function
function ParseHeadersForCacheControl(headers as object) as dynamic
cacheControl = headers["cache-control"]
if cacheControl = invalid
return invalid
end if
cacheControlDirectives = cacheControl.split(",")
for each cacheControlDirective in cacheControlDirectives
keyValue = cacheControlDirective.Trim().split("=")
name = keyValue[0].Trim()
if keyValue.Count() > 1
value = keyValue[1].Trim()
else
value = invalid
end if
if name = "no-store" or name = "no-cache"
return invalid
else if name = "max-age"
return val(value)
end if
end for
return invalid
end function
end namespace
@@ -1,268 +0,0 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/General.bs"
import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/source/utils/WebUtils.bs"
import "pkg:/source/services/InvidiousSettings.bs"
namespace Invidious
const TOKEN_CALLBACK = "/invidious/token_callback"
' TODO: query server status, check if it supports APIs and/or signups
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 SEARCH_ENDPOINT = "/api/v1/search"
const AUTH_SCOPES = "GET:feed,GET:playlists,POST:tokens/register,POST:tokens/unregister,POST:history*"
const AUTH_FEED = "/api/v1/auth/feed"
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
function DefaultArgs() as object
return {
params: {
region: GetUserCountryCode()
}
}
end function
function GetServerStats() as object
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.STATS_ENDPOINT}`
response = Requests().get(url)
if response.statuscode = 200
return response.json
end if
return invalid
end function
function GetVideoStreamUrl(videoId as string, local as boolean) as string
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}/latest_version?id=${videoId}`
if local
url = url + "&local=true"
end if
return url
end function
function GetVideoDashUrl(videoId as string, local as boolean) as string
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}/api/manifest/dash/id/${videoId}`
if local
url = url + "?local=true"
end if
return url
end function
function GetVideoMetadata(videoId as string) as object
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}`
args = Invidious.DefaultArgs()
args.cacheSeconds = 60 * 60 * 6 ' 6 hours
response = Requests().get(url, args)
return {
success: response.ok,
statusCode: response.statuscode,
data: response.json,
failureReason: response.GetFailureReason
}
end function
function GetPlaylist(playlistId as string) as object
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}`
args = Invidious.DefaultArgs()
response = Requests().get(url, args)
if not response.ok
return invalid
end if
return response.json
end function
function MarkVideoWatched(videoId as string) as boolean
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
return false
end if
url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}`
headers = Invidious.GetAuthenticationHeaders(authToken.token)
args = {
headers: headers,
parseJson: false
}
response = Requests().post(url, args)
return response.ok
end function
function SearchSuggestions(q as string) as object 'SearchSuggestionResult
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.SEARCH_SUGGEST_ENDPOINT}`
args = Invidious.DefaultArgs()
args.params.q = q
args.cacheSeconds = 60 * 60 * 6 ' 6 hours
response = Requests().get(url, args)
if response.statuscode = 200
return response.json
end if
return invalid
end function
function Search(q as string, args = invalid as dynamic) as object
instance = InvidiousSettings.GetCurrentInstance()
url = `${instance}${Invidious.SEARCH_ENDPOINT}`
_args = Invidious.DefaultArgs()
_args.params.q = q
if args <> invalid
if args.page <> invalid
_args.params.page = Str(args.page).Trim()
end if
if args.sort_by <> invalid
_args.params.sort_by = args.sort_by
end if
if args.date <> invalid
_args.params.date = args.date
end if
if args.duration <> invalid
_args.params.duration = args.duration
end if
if args.type <> invalid
_args.params.type = args.type
end if
if args.features <> invalid
_args.params.features = args.features.join(",")
end if
end if
response = Requests().get(url, _args)
if response.statuscode = 200
return response.json
end if
return invalid
end function
function GetAuthorizeTokenLink() as string
instance = InvidiousSettings.GetCurrentInstance()
' Make sure the host is not on https, because https cannot redirect to http, which is our local server
invidiousHost = instance.Replace("https://", "http://")
localIp = GetLocalIpAddress()
webServerPort = 8888
expire = TimeUtils.Now().AsSeconds() + TOKEN_TIMESPAN
callbackUrl = `http://${localIp}:${webServerPort}${Invidious.TOKEN_CALLBACK}?ref=${instance}`.EncodeUriComponent()
scope = `${Invidious.AUTH_SCOPES}`.EncodeUriComponent()
return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
end function
function GetAuthenticationHeaders(token as string) as object
return {
"Authorization": `Bearer ${token}`
}
end function
function RefreshAuthToken() as boolean
currentAuthToken = InvidiousSettings.GetAuthToken()
if currentAuthToken = invalid
return false
end if
expire = TimeUtils.Now().AsSeconds() + TOKEN_TIMESPAN
newToken = RegisterToken(currentAuthToken, expire)
if newToken = invalid
return false
end if
InvidiousSettings.SetAuthToken(newToken.token, newToken.instance, newToken.username, newToken.scopes, newToken.expire)
UnregisterToken(currentAuthToken)
return true
end function
function RegisterToken(authToken as object, expire as integer) as dynamic
headers = Invidious.GetAuthenticationHeaders(authToken.token)
url = `${authToken.instance}${Invidious.AUTH_TOKENS_REGISTER}`
scopes = authToken.scopes
if scopes = invalid
parsedToken = ParseJson(authToken.token)
if GetInterface(parsedToken.scopes, "ifArray") <> invalid
scopes = parsedToken.scopes.join(",")
else
scopes = Invidious.AUTH_SCOPES
end if
end if
args = {
headers: headers,
json: {
"scopes": scopes.Split(","),
"expire": expire
},
parseJson: false
}
response = Requests().post(url, args)
if not response.ok
return invalid
end if
return {
token: response.text,
instance: authToken.instance,
username: authToken.username,
scopes: scopes,
expire: expire
}
end function
function UnregisterToken(authToken as object) as boolean
headers = Invidious.GetAuthenticationHeaders(authToken.token)
url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
' authToken.token is already valid json that contains the "session" key needed by the unregister endpoint
headers["Content-Type"] = "application/json"
args = {
headers: headers,
data: authToken.token,
parseJson: false
}
response = Requests().post(url, args)
return response.ok
end function
function Logout() as boolean
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
return false
end if
UnregisterToken(authToken)
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
return true
end function
end namespace
@@ -1,170 +0,0 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/General.bs"
import "pkg:/source/utils/Crypto.bs"
import "pkg:/source/services/InvidiousSettings.bs"
import "pkg:/source/services/Invidious.bs"
class InvidiousService
private endpoints
private responseHanlders
function new()
apiDefnitions = ParseJson(ReadAsciiFile("libpkg:/config/invidious_video_api.json"))
m.endpoints = {}
for each apiDefnition in apiDefnitions.endpoints
m.endpoints[apiDefnition.name] = apiDefnition
end for
m.responseHanlders = {
DefaultHandler: m.DefaultHandler,
AuthFeedHandler: m.AuthFeedHandler,
AuthPlaylistsHandler: m.AuthPlaylistsHandler,
PlaylistHandler: m.PlaylistHandler
}
end function
function MakeRequest(requestData as object) as object
endpoint = m.endpoints[requestData.endpoint]
if endpoint = invalid
return invalid
end if
instance = InvidiousSettings.GetCurrentInstance()
url = instance + endpoint.url
args = { params: {} }
if endpoint.authenticated = true
authToken = InvidiousSettings.GetAuthToken()
if authToken = invalid
return invalid
end if
url = authToken.instance + endpoint.url
args.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 queryParam.type = "string"
args.params[queryParamKey] = queryParam.default
else if queryParam.type = "#ISO3166"
if queryParam.default = "GetUserCountryCode"
args.params[queryParamKey] = GetUserCountryCode()
else
args.params[queryParamKey] = queryParam.default
end if
end if
end if
end for
end if
if requestData.queryParams <> invalid
args.params.append(requestData.queryParams)
end if
if requestData.pathParams <> invalid
for each param in requestData.pathParams
url = url.Replace(`:${param}`, requestData.pathParams[param])
end for
end if
response = Requests().get(url, args)
responseHandler = endpoint.responseHandler <> invalid ? m.responseHanlders[endpoint.responseHandler] : m.responseHanlders["DefaultHandler"]
result = responseHandler(m, requestData, response)
if result <> invalid and endpoint.authenticated = true
' Cache response for use by web app
m.CacheResponse(requestData, result)
end if
return result
end function
function GetAuthenticationHeaders(token as string) as object
return {
"Authorization": `Bearer ${token}`
}
end function
function DefaultHandler(m as object, requestData as object, response as object) as object
if response.statuscode = 200
return [{ title: requestData.title, videos: response.json }]
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
videos = []
videos.Append(response.json.notifications)
videos.Append(response.json.videos)
return [{ title: requestData.title, videos: videos }]
end if
return invalid
end function
function AuthPlaylistsHandler(m as object, requestData as object, response as object) as object
m.DeleteExpiredToken(response)
if response.statuscode = 200
playlists = response.json
result = []
for each playlist in playlists
' Saved playlists are not included in the response
' https://github.com/iv-org/invidious/issues/3995
if playlist.videos.count() = 0 and playlist.authorId = invalid and not playlist.playlistId.StartsWith("IV")
playlist = Invidious.GetPlaylist(playlist.playlistId)
end if
if playlist <> invalid
result.push(m.ProcessPlaylist(requestData, playlist))
end if
end for
return result
end if
return invalid
end function
function PlaylistHandler(m as object, requestData as object, response as object) as object
if response.statuscode = 200
playlist = response.json
return [m.ProcessPlaylist(requestData, playlist)]
end if
return invalid
end function
function ProcessPlaylist(requestData as object, playlist as object) as object
title = m.ProcessTemplate(requestData.title, playlist)
return { title: title, videos: playlist.videos }
end function
function ProcessTemplate(template as string, data as object) as string
for each key in data
template = template.Replace(`%${key}%`, `${data[key]}`)
end for
return template
end function
function DeleteExpiredToken(response as object)
if response.statuscode = 403
print(`Invidious instance responded with 403: ${response.text}`)
print("Deleting Invidious token...")
RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN)
end if
end function
function CacheResponse(requestData as object, result as object)
cacheKey = FormatJson(requestData)
cacheKey = GetMd5(cacheKey)
value = FormatJson(result)
WriteAsciiFile(`tmp:/${cacheKey}.json`, value)
end function
end class
@@ -1,107 +0,0 @@
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/components/SettingsScreen/Settings.bs"
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
namespace InvidiousSettings
const DEFAULT_INSTANCE = "https://vid.puffyan.us"
const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,users"
function GetCurrentInstance() as object
settings = FindAndGetPreferenceValues(["invidious.instance"])
if settings <> invalid and settings["invidious.instance"] <> invalid and settings["invidious.instance"] <> ""
return settings["invidious.instance"]
end if
backupInstances = InvidiousSettings.GetBackupInstances()
if backupInstances.Count() > 0
return backupInstances[0]
end if
return InvidiousSettings.DEFAULT_INSTANCE
end function
function SetAuthToken(token as string, instance as string, username as dynamic, scopes as dynamic, expire as dynamic)
obj = {
token: token,
instance: instance
}
if username <> invalid
obj.username = username
end if
if scopes <> invalid
obj.scopes = scopes
end if
if expire <> invalid
obj.expire = expire
end if
json = FormatJson(obj)
RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json)
end function
function GetAuthToken() as dynamic
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 GetBackupInstances() as object
if m.global.hasField("invidiousBackupInstances")
return m.global.invidiousBackupInstances
end if
return []
end function
function FetchBackupInstances() as object
backupInstances = []
publicInstances = InvidiousSettings.GetPublicInstances()
for i = 0 to publicInstances.Count() - 1
if InvidiousSettings.IsValidPublicInstance(publicInstances[i])
backupInstances.push(publicInstances[i].uri)
end if
if backupInstances.Count() >= 5
exit for
end if
end for
return backupInstances
end function
function GetPublicInstances() as object
instances = []
response = Requests().get(InvidiousSettings.INSTANCES_API)
if response.statuscode = 200
json = response.json
for each instance in json
data = instance[1]
if data.monitor <> invalid and data.monitor.dailyRatios <> invalid
data.monitor.dailyRatios = invalid
end if
data["name"] = instance[0]
instances.push(data)
end for
end if
return instances
end function
function IsValidPublicInstance(instance as object) as boolean
if instance = invalid
return false
end if
return instance.type = "https" and instance.api = true
end function
end namespace
@@ -1,122 +0,0 @@
import "pkg:/source/utils/RegistryUtils.bs"
class PreferencesService
private version = 1
private prefs_model
private user_prefs
function new()
m.LoadConfigFile()
m.LoadUserPreferences()
end function
function LoadConfigFile()
m.prefs_model = ParseJson(ReadAsciiFile("libpkg:/config/preferences.json"))
end function
function LoadUserPreferences()
' Step 1: Load user preferences from registry
m.user_prefs = RegistryUtils.Read(RegistryUtils.USER_PREFERENCES)
if m.user_prefs = invalid
m.user_prefs = "{}"
end if
m.user_prefs = ParseJson(m.user_prefs)
' Step 2: Migrate existing preferences to new format (if needed)
isDirty = m.MigrateExistingPreferences()
' Step 3: Apply defaults to user preferences (if needed)
isDirty = m.ApplyDefaultsToUserPreferences() or isDirty
if isDirty
m.SaveUserPreferences()
end if
end function
function SaveUserPreferences()
m.user_prefs.__version = m.version
RegistryUtils.Write(RegistryUtils.USER_PREFERENCES, FormatJson(m.user_prefs))
end function
function MigrateExistingPreferences() as boolean
isDirty = false
' v0 -> v1
instances = RegistryUtils.Read(RegistryUtils.INVIDIOUS_INSTANCES)
if instances <> invalid
currentInstance = m.user_prefs["invidious.instance"]
if currentInstance = invalid or currentInstance = ""
instances = ParseJson(instances)
if instances.Count() > 0
instance = instances[0]
if instance <> invalid and instance <> ""
m.user_prefs["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 m.user_prefs.__version = 1
' 'do stuff
' end if
' TODO: handle case where saved preferences version is higher than current version (e.g. user downgraded)
return isDirty
end function
function ApplyDefaultsToUserPreferences() as boolean
isDirty = false
for each child in m.prefs_model
isDirty = m.ApplyToUserPreferences(m.user_prefs, 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 = m.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() as object
return m.user_prefs
end function
function ApplyUserPreferences(preferences as object) as void
if preferences = invalid
return
end if
' TODO: user input validation
for each key in preferences
m.user_prefs[key] = preferences[key]
end for
m.SaveUserPreferences()
end function
function ClearUserPreferences() as void
m.user_prefs = {}
m.ApplyDefaultsToUserPreferences()
m.SaveUserPreferences()
end function
function GetValue(key as string) as dynamic
return m.user_prefs[key]
end function
function SetValue(key as string, value as dynamic) as void
if m.user_prefs[key] = value
return
end if
m.user_prefs[key] = value
m.SaveUserPreferences()
end function
end class
@@ -1,10 +1,11 @@
import "pkg:/source/utils/General.bs"
import "pkg:/source/utils/ArrayUtils.bs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
namespace SearchHistory
function Save(q as string, maxItems = 10 as integer)
history = GetAllSaved()
index = ArrayIndexOf(history, q)
index = ArrayUtils.IndexOfString(history, q)
if index <> -1
history.Delete(index)
end if
@@ -26,7 +27,7 @@ namespace SearchHistory
return []
end if
if q = ""
if StringUtils.IsNullOrEmpty(q)
return history
end if
result = []
@@ -1,115 +0,0 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/utils/WebUtils.bs"
import "pkg:/source/utils/Crypto.bs"
import "pkg:/source/utils/ColorUtils.bs"
namespace SponsorBlock
const API_URL = "https://sponsor.ajay.app"
const SKIP_SEGMENT_ENDPOINT = "/api/skipSegments"
const VIEWED_SEGMENT_ENDPOINT = "/api/viewedVideoSponsorTime"
function GetSponsorBlockConfig() as object
if m.sponsorBlockConfig = invalid
m.sponsorBlockConfig = ParseJson(ReadAsciiFile("libpkg:/config/sponsorblock_config.json"))
end if
return m.sponsorBlockConfig
end function
function SegmentColor(category as string) as integer
config = SponsorBlock.GetSponsorBlockConfig()
if config = invalid
return 0
end if
if config.categories.doesexist(category)
color = config.categories[category].color
return ColorUtils.HexToInt(color)
end if
return 0
end function
function SegmentTitle(category as string) as string
config = SponsorBlock.GetSponsorBlockConfig()
if config = invalid
return ""
end if
if config.categories.doesexist(category)
return config.categories[category].title
end if
return ""
end function
function SegmentShortTitle(category as string) as string
config = SponsorBlock.GetSponsorBlockConfig()
if config = invalid
return ""
end if
if config.categories.doesexist(category)
return config.categories[category].short_title
end if
return ""
end function
function GetSkipSegmentsForVideo(videoId as string) as object
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 = GetSha256(videoId).Left(4)
url = `${SponsorBlock.API_URL}${SponsorBlock.SKIP_SEGMENT_ENDPOINT}/${hashPrefix}?categories=${categoriesJson}&actionTypes=${actionTypesJson}`
response = Requests().get(url)
if response.statuscode = 200
results = response.json
for each item in results
if item.videoId = videoId
return item.segments
end if
end for
end if
return invalid
end function
function PostSegmentViewed(segmentId as string) as boolean
url = `${SponsorBlock.API_URL}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}`
response = Requests().post(url, { parseJson: false })
return response.statuscode = 200
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 = SponsorBlock.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 namespace