From a248318c548cfbfd2d54c7b34ac918adbd52d764 Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Thu, 24 Nov 2022 18:40:27 -0500 Subject: [PATCH] Ground work for invidious instance selection (#11) * Ground work for invidious instance selection * Display logged in instance * Show instances * Reorder instances * Instance management * Add todos * Changelog * Add instances link, trim trailing slash * Small tweaks --- CHANGELOG.md | 1 + src/components/MainScene.bs | 2 + src/components/VideoPlayer/Video.bs | 3 +- .../WebServer/Middleware/CommandsApiRouter.bs | 2 +- .../WebServer/Middleware/InvidiousRouter.bs | 58 ++++-- .../WebServer/Middleware/StateApiRouter.bs | 45 ++++- src/components/lib/QRCode/QRTestScene.bs | 16 -- src/components/lib/QRCode/QRTestScene.xml | 30 --- src/source/services/Invidious.bs | 72 ++++---- src/source/services/InvidiousService.bs | 22 +-- src/source/services/InvidiousSettings.bs | 95 ++++++++++ src/source/utils/RegistryUtils.bs | 3 + src/source/utils/WebUtils.bs | 20 +- src/www/index.html | 172 +++++++++++++++++- 14 files changed, 411 insertions(+), 130 deletions(-) delete mode 100644 src/components/lib/QRCode/QRTestScene.bs delete mode 100644 src/components/lib/QRCode/QRTestScene.xml create mode 100644 src/source/services/InvidiousSettings.bs diff --git a/CHANGELOG.md b/CHANGELOG.md index 94008295..d1f4dfce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Support for DASH and Live videos - Log out button to web app - Search Screen +- Very basic UI to customize/change invidious instance ### Fixed - Bug where Settings page and home page are both visible, if settings page is selected, and user logs in. diff --git a/src/components/MainScene.bs b/src/components/MainScene.bs index c0e841fa..df22dc5c 100644 --- a/src/components/MainScene.bs +++ b/src/components/MainScene.bs @@ -105,6 +105,8 @@ function OnWebServerCommand() m.settingsScreen.visible = false ' Trigger play video from home ' TODO: allow returning to current screen, instead of home + ' BUG: if current video is playing in search screen, new video does not play + ' TODO: Owner of video player needs to be independant m.homeGridScreen.playvideo = m.serverTask.command.Mid(5) end if end function diff --git a/src/components/VideoPlayer/Video.bs b/src/components/VideoPlayer/Video.bs index ed1e5413..b7d322f0 100644 --- a/src/components/VideoPlayer/Video.bs +++ b/src/components/VideoPlayer/Video.bs @@ -191,13 +191,14 @@ function SetCaptions(metadata as object, videoPlayer as object, contentNode as o contentNode.SubtitleConfig = { ShowSubtitle: 1, - TrackName: Invidious.GetCurrentHost() + selectedCaption.url + TrackName: InvidiousSettings.GetSelectedInstance() + selectedCaption.url } end function function OnPositionChangeSkipSponsorBlockSections() as void segments = m.videoPlayer.skipSegments for each segment in segments + ' TODO: handle other action types if segment["actionType"] = "skip" segmentRange = segment["segment"] segmentStart = segmentRange[0] diff --git a/src/components/WebServer/Middleware/CommandsApiRouter.bs b/src/components/WebServer/Middleware/CommandsApiRouter.bs index 5e4c2aea..11e5eafb 100644 --- a/src/components/WebServer/Middleware/CommandsApiRouter.bs +++ b/src/components/WebServer/Middleware/CommandsApiRouter.bs @@ -34,7 +34,7 @@ namespace Http server.task.top.command = `play:${components["v"]}` if components["redirect"] = "true" ' 302 to prevent redirection to current host permanently - response.Redirect(`${Invidious.GetCurrentHost()}/watch?v=${components["v"]}`, 302) + response.Redirect(`${InvidiousSettings.GetSelectedInstance()}/watch?v=${components["v"]}`, 302) else response.Default(204, "OK") end if diff --git a/src/components/WebServer/Middleware/InvidiousRouter.bs b/src/components/WebServer/Middleware/InvidiousRouter.bs index ce8e80a6..2d3615fa 100644 --- a/src/components/WebServer/Middleware/InvidiousRouter.bs +++ b/src/components/WebServer/Middleware/InvidiousRouter.bs @@ -5,25 +5,57 @@ namespace Http function new() super() + ' TODO: use POST once supported + m.Get("*", function(context as object) as boolean + request = context.request + response = context.response + + route = request.uri + if not route.StartsWith("/invidious/set-instances") + return false + end if + + components = WebUtils.UrlQueryComponents(route) + + instances = [] + if components.DoesExist("instances") + instances = components["instances"] + if GetInterface(instances, "ifArray") = invalid + instances = [instances] + end if + end if + + for i = 0 to instances.Count() - 1 + if instances[i].right(1) = "/" + instances[i] = instances[i].left(instances[i].len() - 1) + end if + end for + + InvidiousSettings.SetRegistryInstances(instances) + response.Default(200, "OK") + return true + end function) + m.Get("*", function(context as object) as boolean request = context.request response = context.response server = context.server - uri = request.uri - if uri.StartsWith(Invidious.TOKEN_CALLBACK) - components = WebUtils.UrlQueryComponents(uri) - if components["token"] <> invalid - ' Token is encoded twice for some reason - token = WebUtils.UrlUnescape(components["token"]).DecodeUriComponent() - print(`Got Token: ${token}`) - RegistryUtils.Write("invidious_token", token) - server.task.top.login = true - end if - response.Redirect("/", 302) - return true + route = request.uri + if not route.StartsWith(Invidious.TOKEN_CALLBACK) + return false end if - return false + + components = WebUtils.UrlQueryComponents(route) + if components["token"] <> invalid and components["referer"] <> invalid + ' Token is encoded twice for some reason + token = WebUtils.UrlUnescape(components["token"]).DecodeUriComponent() + referer = WebUtils.UrlUnescape(components["referer"]) + InvidiousSettings.SetAuthToken(token, referer) + server.task.top.login = true + end if + response.Redirect("/", 302) + return true end function) end function diff --git a/src/components/WebServer/Middleware/StateApiRouter.bs b/src/components/WebServer/Middleware/StateApiRouter.bs index 0b1879fd..be700a3a 100644 --- a/src/components/WebServer/Middleware/StateApiRouter.bs +++ b/src/components/WebServer/Middleware/StateApiRouter.bs @@ -8,18 +8,47 @@ namespace Http function new() super() - m.Get("/api/state", function(context as object) as boolean + m.Get("*", function(context as object) as boolean + request = context.request response = context.response - state = { - app: GetAppInfo(), - device: GetDeviceInfo(), - invidious: { - host: Invidious.GetCurrentHost(), + route = request.uri + ' TODO: this is not the right filtering. /api/state/something will go through, which is not correct + if not route.StartsWith("/api/state") + return false + end if + + keys = ["app", "device", "invidious"] + + components = WebUtils.UrlQueryComponents(route) + if components.DoesExist("key") + keys = components["key"] + if GetInterface(keys, "ifArray") = invalid + keys = [keys] + end if + end if + + state = {} + + if ArrayIndexOf(keys, "app") <> -1 + state["app"] = GetAppInfo() + end if + + if ArrayIndexOf(keys, "device") <> -1 + state["device"] = GetDeviceInfo() + end if + + if ArrayIndexOf(keys, "invidious") <> -1 + authToken = InvidiousSettings.GetAuthToken() + state["invidious"] = { + instances: InvidiousSettings.GetCurrentInstances(), + selected_instance: InvidiousSettings.GetSelectedInstance(), auth_url: Invidious.GetAuthorizeTokenLink(), - logged_in: Invidious.GetAuthenticationHeaders() <> invalid + logged_in: authToken <> invalid, + logged_in_instance: authToken <> invalid ? authToken.instance : invalid } - } + end if + response.Json(state) return true end function) diff --git a/src/components/lib/QRCode/QRTestScene.bs b/src/components/lib/QRCode/QRTestScene.bs deleted file mode 100644 index f96b1837..00000000 --- a/src/components/lib/QRCode/QRTestScene.bs +++ /dev/null @@ -1,16 +0,0 @@ -import "pkg:/source/services/Invidious.bs" - -sub init() - m.instructions = m.top.findNode("instructions") - - text = "- Scan the QR Code" + chr(10) - text += "- Login (Create account if needed)" + chr(10) - text += "- Scan the QR Code again" + chr(10) - text += "- Click ""Authorize""" + chr(10) - text += "- If the error ""Invalid signature"" shows, press back and ""Authorize"" again" + chr(10) - text += "- Your TV should go to home screen automatically" + chr(10) - text += chr(10) + chr(10) + chr(10) - text += "Invidious instance: " + Invidious.GetCurrentHost() - - m.instructions.text = text -end sub \ No newline at end of file diff --git a/src/components/lib/QRCode/QRTestScene.xml b/src/components/lib/QRCode/QRTestScene.xml deleted file mode 100644 index f50b5190..00000000 --- a/src/components/lib/QRCode/QRTestScene.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/src/source/services/Invidious.bs b/src/source/services/Invidious.bs index 36065550..9cc92634 100644 --- a/src/source/services/Invidious.bs +++ b/src/source/services/Invidious.bs @@ -4,11 +4,10 @@ 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 ' TODO: query server status, check if it supports APIs and/or signups - const API_URL = "https://vid.puffyan.us" - const TOKEN_CALLBACK = "/invidious/token_callback" const POPULAR_ENDPOINT = "/api/v1/popular" @@ -33,7 +32,8 @@ namespace Invidious end function function GetPopular() as object - url = `${Invidious.API_URL}${Invidious.POPULAR_ENDPOINT}` + instance = InvidiousSettings.GetSelectedInstance() + url = `${instance}${Invidious.POPULAR_ENDPOINT}` args = Invidious.DefaultArgs() response = Requests().get(url, args) @@ -45,7 +45,8 @@ namespace Invidious end function function GetTrending(trendingType = "" as string) as object - url = `${Invidious.API_URL}${Invidious.TRENDING_ENDPOINT}` + instance = InvidiousSettings.GetSelectedInstance() + url = `${instance}${Invidious.TRENDING_ENDPOINT}` args = Invidious.DefaultArgs() if trendingType <> "" @@ -61,7 +62,8 @@ namespace Invidious end function function GetVideoUrl(videoId as string, itag as string, local as boolean) as string - url = `${Invidious.API_URL}/latest_version?id=${videoId}&itag=${itag}` + instance = InvidiousSettings.GetSelectedInstance() + url = `${instance}/latest_version?id=${videoId}&itag=${itag}` if local url = url + "&local=true" end if @@ -69,7 +71,8 @@ namespace Invidious end function function GetVideoMetadata(videoId as string) as object - url = `${Invidious.API_URL}${Invidious.VIDEOS_ENDPOINT}/${videoId}` + instance = InvidiousSettings.GetSelectedInstance() + url = `${instance}${Invidious.VIDEOS_ENDPOINT}/${videoId}` args = Invidious.DefaultArgs() response = Requests().get(url, args) @@ -82,7 +85,8 @@ namespace Invidious end function function SearchSuggestions(q as string) as object 'SearchSuggestionResult - url = `${Invidious.API_URL}${Invidious.SEARCH_SUGGEST_ENDPOINT}` + instance = InvidiousSettings.GetSelectedInstance() + url = `${instance}${Invidious.SEARCH_SUGGEST_ENDPOINT}` args = Invidious.DefaultArgs() args.params.q = q @@ -95,7 +99,8 @@ namespace Invidious end function function Search(q as string, args = invalid as dynamic) as object - url = `${Invidious.API_URL}${Invidious.SEARCH_ENDPOINT}` + instance = InvidiousSettings.GetSelectedInstance() + url = `${instance}${Invidious.SEARCH_ENDPOINT}` _args = Invidious.DefaultArgs() _args.params.q = q @@ -128,39 +133,33 @@ namespace Invidious return invalid end function - function GetCurrentHost() as string - return Invidious.API_URL - end function - function GetAuthorizeTokenLink() as string + instance = InvidiousSettings.GetSelectedInstance() ' Make sure the host is not on https, because https cannot redirect to http, which is our local server - invidiousHost = `${Invidious.API_URL}`.Replace("https://", "http://") + invidiousHost = instance.Replace("https://", "http://") localIp = GetLocalIpAddress() webServerPort = 8888 expire = TimeUtils.Now().AsSeconds() + 60 * 60 * 24 * 30 'A month from now - callbackUrl = WebUtils.UrlEncode(`http://${localIp}:${webServerPort}${Invidious.TOKEN_CALLBACK}`) + callbackUrl = WebUtils.UrlEncode(`http://${localIp}:${webServerPort}${Invidious.TOKEN_CALLBACK}?referer=${instance}`) return `${invidiousHost}/authorize_token?scopes=${Invidious.AUTH_SCOPE}&callback_url=${callbackUrl}&expire=${expire}` end function - function GetAuthenticationHeaders() as object - token = RegistryUtils.Read("invidious_token") - if token = invalid - return invalid - end if + function GetAuthenticationHeaders(token as string) as object return { "Authorization": `Bearer ${token}` } end function function GetUserFeed() as object - headers = Invidious.GetAuthenticationHeaders() - if headers = invalid - return invalid + authToken = InvidiousSettings.GetAuthToken() + if authToken = invalid + return false end if + headers = Invidious.GetAuthenticationHeaders(authToken.token) - url = `${Invidious.API_URL}${Invidious.AUTH_FEED}` + url = `${authToken.instance}${Invidious.AUTH_FEED}` args = { headers: headers, @@ -170,7 +169,7 @@ namespace Invidious response = Requests().get(url, args) if response.statuscode = 403 - RegistryUtils.Delete("invidious_token") + RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN) end if if response.statuscode = 200 return response.json.videos @@ -179,12 +178,13 @@ namespace Invidious end function function GetUserPlaylists() as object - headers = Invidious.GetAuthenticationHeaders() - if headers = invalid - return invalid + authToken = InvidiousSettings.GetAuthToken() + if authToken = invalid + return false end if + headers = Invidious.GetAuthenticationHeaders(authToken.token) - url = `${Invidious.API_URL}${Invidious.AUTH_PLAYLISTS}` + url = `${authToken.instance}${Invidious.AUTH_PLAYLISTS}` args = { headers: headers, @@ -194,7 +194,7 @@ namespace Invidious response = Requests().get(url, args) if response.statuscode = 403 - RegistryUtils.Delete("invidious_token") + RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN) end if if response.statuscode = 200 return response.json @@ -203,24 +203,24 @@ namespace Invidious end function function Logout() as boolean - headers = Invidious.GetAuthenticationHeaders() - if headers = invalid + authToken = InvidiousSettings.GetAuthToken() + if authToken = invalid return false end if + headers = Invidious.GetAuthenticationHeaders(authToken.token) - url = `${Invidious.API_URL}${Invidious.AUTH_TOKENS_UNREGISTER}` + url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}` - ' token is already valid json that contains the "session" key needed by the unregister endpoint - token = RegistryUtils.Read("invidious_token") + ' 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: token + data: authToken.token } Requests().post(url, args) - RegistryUtils.Delete("invidious_token") + RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN) return true end function end namespace diff --git a/src/source/services/InvidiousService.bs b/src/source/services/InvidiousService.bs index ea763e51..519c76a0 100644 --- a/src/source/services/InvidiousService.bs +++ b/src/source/services/InvidiousService.bs @@ -1,10 +1,9 @@ import "pkg:/source/roku_modules/rokurequests/Requests.brs" import "pkg:/source/utils/RegistryUtils.bs" import "pkg:/source/utils/General.bs" +import "pkg:/source/services/InvidiousSettings.bs" class InvidiousService - API_URL = "https://vid.puffyan.us" - private endpoints private responseHanlders @@ -29,16 +28,19 @@ class InvidiousService return invalid end if - url = m.API_URL + endpoint.url + instance = InvidiousSettings.GetSelectedInstance() + + url = instance + endpoint.url args = { params: {} } if endpoint.authenticated = true - auth_headers = m.GetAuthenticationHeaders() - if auth_headers = invalid + authToken = InvidiousSettings.GetAuthToken() + if authToken = invalid return invalid end if - args.headers = auth_headers + url = authToken.instance + endpoint.url + args.headers = m.GetAuthenticationHeaders(authToken.token) end if if endpoint.queryParams <> invalid @@ -73,11 +75,7 @@ class InvidiousService return responseHandler(m, requestData, response) end function - function GetAuthenticationHeaders() as object - token = RegistryUtils.Read("invidious_token") - if token = invalid - return invalid - end if + function GetAuthenticationHeaders(token as string) as object return { "Authorization": `Bearer ${token}` } @@ -118,7 +116,7 @@ class InvidiousService if response.statuscode = 403 print(`Server responded with 403: ${response.text}`) print("deleting token...") - RegistryUtils.Delete("invidious_token") + RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN) end if end function diff --git a/src/source/services/InvidiousSettings.bs b/src/source/services/InvidiousSettings.bs new file mode 100644 index 00000000..e988546e --- /dev/null +++ b/src/source/services/InvidiousSettings.bs @@ -0,0 +1,95 @@ +namespace InvidiousSettings + + const DEFAULT_INSTANCE = "https://vid.puffyan.us" + + const INSTANCES_API = "https://api.invidious.io/instances.json?sort_by=type,health,users,api" + + function GetCurrentInstances() as object + ' TODO: cache this call to avoid json parsing every time + instances = InvidiousSettings.GetRegistryInstances() + if instances.Count() > 0 + return instances + end if + + publicInstances = InvidiousSettings.GetPublicInstances() + if publicInstances <> invalid + for i = 0 to 4 + if i < publicInstances.Count() + instances.push(publicInstances[i].uri) + end if + end for + end if + + if instances.Count() > 0 + InvidiousSettings.SetRegistryInstances(instances) + return instances + end if + + return [InvidiousSettings.DEFAULT_INSTANCE] + end function + + function GetSelectedInstance() as string + instances = InvidiousSettings.GetCurrentInstances() + return instances[0] + end function + + function SetAuthToken(token as string, instance as string) + json = FormatJson({ + token: token, + instance: instance + }) + RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json) + + instances = InvidiousSettings.GetCurrentInstances() + index = ArrayIndexOf(instances, instance) + if index = -1 + instances.push(instance) + InvidiousSettings.SetRegistryInstances(instances) + end if + end function + + function GetAuthToken() as dynamic + tokenPayload = RegistryUtils.Read(RegistryUtils.INVIDIOUS_TOKEN) + if tokenPayload = invalid + return invalid + end if + return ParseJson(tokenPayload) + end function + + function GetRegistryInstances() as object + instances = RegistryUtils.Read(RegistryUtils.INVIDIOUS_INSTANCES) + if instances = invalid + return [] + end if + return ParseJson(instances) + end function + + function SetRegistryInstances(instances as object) + RegistryUtils.Write(RegistryUtils.INVIDIOUS_INSTANCES, FormatJson(instances)) + end function + + function GetPublicInstances() as object + if m.invidiousPublicInstances <> invalid + return m.invidiousPublicInstances + end if + response = Requests().get(InvidiousSettings.INSTANCES_API) + if response.statuscode = 200 + json = response.json + instances = [] + + 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 + + m.invidiousPublicInstances = instances + end if + + return m.invidiousPublicInstances + end function + +end namespace diff --git a/src/source/utils/RegistryUtils.bs b/src/source/utils/RegistryUtils.bs index a30d852a..be8d70a2 100644 --- a/src/source/utils/RegistryUtils.bs +++ b/src/source/utils/RegistryUtils.bs @@ -2,6 +2,9 @@ namespace RegistryUtils const DEFAULT_SECTION = "Playlet" + const INVIDIOUS_INSTANCES = "invidious_instances" + const INVIDIOUS_TOKEN = "invidious_token" + function Read(key as string, section = DEFAULT_SECTION as string) as dynamic sec = CreateObject("roRegistrySection", section) if sec.Exists(key) diff --git a/src/source/utils/WebUtils.bs b/src/source/utils/WebUtils.bs index e5adde10..c965f232 100644 --- a/src/source/utils/WebUtils.bs +++ b/src/source/utils/WebUtils.bs @@ -34,12 +34,26 @@ namespace WebUtils url = Mid(url, index + 1) components = url.split("&") for each component in components + key = component + value = "" + hasValue = false if Instr(0, component, "=") keyValue = component.split("=") - query[keyValue[0]] = keyValue[1] - else - query[component] = "" + key = keyValue[0] + value = keyValue[1] + hasValue = true end if + + if query.DoesExist(key) and hasValue + oldValue = query[key] + if GetInterface(oldValue, "ifArray") = invalid + oldValue = [oldValue] + end if + oldValue.push(value) + value = oldValue + end if + + query[key] = value end for return query end function diff --git a/src/www/index.html b/src/www/index.html index fc96543e..4bd5be34 100644 --- a/src/www/index.html +++ b/src/www/index.html @@ -5,13 +5,26 @@ Playlet + - +

Playlet - Youtube Player for Roku

Version:

-

Invidious Instance: None

- +

Invidious Instance: None

@@ -20,6 +33,31 @@ +
+ + + + + + + + + + + + + + + +
Instances - find more at api.invidious.io
+ + + +
+
+ +
Instructions