Play API prototype (#8)

* Play API prototype

* Web app

* Drag and drop support

* Handle different urls

* Fix redirect

* Increase max connections

* changelog

* Limit timeout

* Use fetch

* Redirects

* Formatting
This commit is contained in:
Brahim Hadriche authored and GitHub committed 2022-11-21 18:47:12 -05:00
1 parent 192eec9519
commit 651bb54dee
15 files changed
+180 -39

No files matched your search

@@ -5,6 +5,7 @@ function Init()
m.rowList = m.top.FindNode("rowList")
m.top.ObserveField("rowItemSelected", "OnHomeGridScreenVideoSelected")
m.top.ObserveField("focus", "OnFocusChange")
m.top.ObserveField("playvideo", "OnPlayVideoCommand")
m.top.focus = true
@@ -132,6 +133,12 @@ function CloseVideo()
end if
end function
function OnPlayVideoCommand()
videoId = m.top.playvideo
CloseVideo()
ShowVideoScreenFull(videoId)
end function
function OnHomeGridScreenVideoFocused(event as object) as void
' Skip loading the video after first load
if m.firstFocus = invalid
@@ -8,6 +8,7 @@
<field id="jumpToRowItem" type="intarray" alias="RowList.jumpToRowItem" />
<field id="escape" type="string" alwaysNotify="true" />
<field id="focus" type="boolean" alwaysNotify="true" />
<field id="playvideo" type="string" alwaysNotify="true" />
</interface>
<children>
<RowList
+7
View File
@@ -28,6 +28,7 @@ function InitWebServer()
m.serverTask = createObject("roSGNode", "WebServerTask")
m.serverTask.id = "WebServerTask"
m.serverTask.ObserveField("login", "OnWebServerLogin")
m.serverTask.ObserveField("command", "OnWebServerCommand")
m.serverTask.control = "RUN"
end function
@@ -85,6 +86,12 @@ function OnWebServerLogin()
m.settingsScreen.visible = false
end function
function OnWebServerCommand()
if m.serverTask.command.StartsWith("play:")
m.homeGridScreen.playvideo = m.serverTask.command.Mid(5)
end if
end function
function GetIndexOfChild(parent as object, childId as string) as integer
count = parent.getChildCount()
for i = 0 to count - 1
@@ -1,7 +1,7 @@
import "pkg:/source/utils/General.bs"
function Init()
m.top.url = `http:/${GetLocalIpAddress()}:8888/index.html?tab=settings`
m.top.url = `http:/${GetLocalIpAddress()}:8888`
end function
function OnUrlSet()
+2 -2
View File
@@ -77,10 +77,10 @@ namespace Http
m.source = Http.HttpResponseSource.GENERATED
end function
function Redirect(where as string)
function Redirect(where as string, code = 301 as integer)
m.location = where
message = "Moved to: <a href=" + Quote() + where + Quote() + ">" + where + "</a>"
m.Default(301, message)
m.Default(code, message)
end function
function Json(data as object)
+1 -1
View File
@@ -5,7 +5,7 @@ namespace Http
PackageName = "Playlet"
Port = 8888
MessagePort = invalid
MaxConnections = 3
MaxConnections = 10
Timeout = 60 * 1000
MaxRequestLength = 4000
Idletime = 60
@@ -0,0 +1,38 @@
namespace Http
class CommandsApiRouter extends HttpRouter
function new()
super()
m.Get("*", function(context as object) as boolean
request = context.request
response = context.response
server = context.server
route = request.uri
if route.StartsWith("/api/command/play")
components = WebUtils.UrlQueryComponents(route)
if components["v"] = invalid
response.Default(400, "Missing arg 'v'")
return true
end if
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)
else
response.Default(200, "OK")
end if
return true
end if
return false
end function)
end function
end class
end namespace
@@ -10,12 +10,12 @@ namespace Http
response = context.response
method = request.method
route = request.uri
uri = request.uri
if method = ""
response.Default(400, "You sent a request that the server couldn't understand.")
else
response.Default(404, `Cannot ${method} ${route}`)
response.Default(404, `Cannot ${method} ${uri}`)
end if
return true
@@ -20,7 +20,7 @@ namespace Http
RegistryUtils.Write("invidious_token", token)
server.task.top.login = true
end if
response.Redirect("/index.html?tab=settings")
response.Redirect("/", 302)
return true
end if
return false
@@ -5,6 +5,7 @@ import "pkg:/components/WebServer/Middleware/HttpDefaultRouter.bs"
import "pkg:/components/WebServer/Middleware/InvidiousRouter.bs"
import "pkg:/components/WebServer/Middleware/RegistryApiRouter.bs"
import "pkg:/components/WebServer/Middleware/StateApiRouter.bs"
import "pkg:/components/WebServer/Middleware/CommandsApiRouter.bs"
function Init()
m.top.functionName = "WebServerLoop"
@@ -16,8 +17,18 @@ function WebServerLoop()
m.settings = new Http.HttpSettings(m.webServerPort)
' Root at www to get http://IP_ADDRESS:PORT/index.html
m.settings.WwwRoot = "pkg:/www"
m.settings.Timeout = 5000
m.server = new Http.HttpServer(m.settings, m)
homeRouter = new Http.HttpRouter()
homeRouter.Get("/", function(context as object) as boolean
response = context.response
response.Redirect("/index.html?tab=settings", 302)
return true
end function)
m.server.UseRouter(homeRouter)
m.server.UseRouter(new Http.CommandsApiRouter())
m.server.UseRouter(new Http.StateApiRouter())
m.server.UseRouter(new Http.RegistryApiRouter())
m.server.UseRouter(new Http.InvidiousRouter())
@@ -3,5 +3,6 @@
<component name="WebServerTask" extends="Task">
<interface>
<field id="login" type="boolean" alwaysNotify="true" />
<field id="command" type="string" alwaysNotify="true" />
</interface>
</component>
+1
View File
@@ -6,6 +6,7 @@ import "pkg:/source/utils/TimeUtils.bs"
import "pkg:/source/utils/WebUtils.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"
+1 -1
View File
@@ -36,7 +36,7 @@ namespace WebUtils
keyValue = component.split("=")
query[keyValue[0]] = keyValue[1]
else
query[keyValue[0]] = ""
query[component] = ""
end if
end for
return query
+101 -30
View File
@@ -7,10 +7,15 @@
<title>Playlet</title>
</head>
<body>
<body ondrop="OnDrop(event);" ondragover="OnDragover(event);">
<h2>Playlet - Youtube Player for Roku</h2>
<h4 id="app-version">Version: </h4>
<h4>Invidious Instance: <a id="host" target="_blank">None</a></h4>
<button onclick="PlayVideo()">Play Video</button>
<label for="video-id">Video ID:</label>
<input type="text" id="video-id" name="video-id" style="min-width:300px;">
<h4 id="logged-in">Logged In: </h4>
<button style="visibility: hidden" id="login-button" onclick="Login()">Login</button>
<button style="visibility: hidden" id="logout-button">Logout</button>
@@ -31,20 +36,6 @@
target="_blank">https://github.com/iBicha/playlet</a></h5>
<script>
function RequestGet(url, cb) {
const req = new XMLHttpRequest();
req.addEventListener("load", function () {
try {
cb(null, JSON.parse(this.responseText));
}
catch (err) {
cb(err)
}
});
req.open("GET", url);
req.send();
}
function Login() {
if (!window.appState) {
alert("Error with login, please refresh the page.")
@@ -52,6 +43,21 @@
window.location = window.appState.invidious.auth_url
}
function PlayVideo() {
let v = document.getElementById('video-id').value
if (IsValidHttpUrl(v)) {
v = GetVideoId(v)
}
if (!v || v.length < 8) {
alert("Please set video id")
return
}
fetch(`/api/command/play?v=${v}`)
.catch(function (err) {
alert(err)
});
}
function CreateGithubIssueUrl() {
title = "[Feedback] Playlet"
body = `### Feedback
@@ -69,24 +75,89 @@ ${JSON.stringify(window.appState.device, null, 2)}
return `https://github.com/iBicha/playlet/issues/new?title=${encodeURIComponent(title)}&body=${encodeURIComponent(body)}`
}
RequestGet("/api/state", function (err, response) {
if (err) {
alert(err)
return
function IsValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
window.appState = response
console.log(response)
document.getElementById("app-version").innerText = `Version: ${response.app.version}`
document.getElementById("logged-in").innerText = `Logged In: ${response.invidious.logged_in}`
document.getElementById("host").innerText = response.invidious.host
document.getElementById("host").href = response.invidious.host
return url.protocol === "http:" || url.protocol === "https:";
}
document.getElementById("login-button").style.visibility = response.invidious.logged_in ? "hidden" : "visible";
// TODO: log out feature
// document.getElementById("logout-button").style.visibility = response.invidious.logged_in ? "hidden" : "visible";
function GetVideoId(url) {
// Share/Short url
const YoutubeUrls = [
"https://youtu.be/",
"http://youtu.be/",
"https://www.youtu.be/",
"http://www.youtu.be/",
"https://youtube.com/shorts/",
"http://youtube.com/shorts/",
"https://www.youtube.com/shorts/",
"http://www.youtube.com/shorts/",
]
for (var i in YoutubeUrls) {
let youtubeUrl = YoutubeUrls[i];
if (url.startsWith(youtubeUrl)) {
url = url.replace(youtubeUrl, "")
if (url.includes("?")) {
url = url.substring(0, url.indexOf("?"))
}
return url
}
}
document.getElementById("feedback-url").href = CreateGithubIssueUrl()
})
// regular url
url = new URL(url)
const urlSearchParams = new URLSearchParams(url.search);
return urlSearchParams.get('v')
}
function Initialize() {
fetch("/api/state")
.then(function (response) {
return response.json();
})
.then(function (appState) {
window.appState = appState
console.log(appState)
document.getElementById("app-version").innerText = `Version: ${appState.app.version}`
document.getElementById("logged-in").innerText = `Logged In: ${appState.invidious.logged_in}`
document.getElementById("host").innerText = appState.invidious.host
document.getElementById("host").href = appState.invidious.host
document.getElementById("login-button").style.visibility = appState.invidious.logged_in ? "hidden" : "visible";
// TODO: log out feature
// document.getElementById("logout-button").style.visibility = appState.invidious.logged_in ? "hidden" : "visible";
document.getElementById("feedback-url").href = CreateGithubIssueUrl()
})
.catch(function (err) {
alert(err)
});
}
function OnDrop(event) {
for (var i in event.dataTransfer.items) {
let item = event.dataTransfer.items[i]
if (item.kind = 'string' && item.getAsString) {
item.getAsString((dataString) => {
if (IsValidHttpUrl(dataString)) {
document.getElementById('video-id').value = dataString
}
});
}
}
event.preventDefault();
}
function OnDragover(event) {
event.preventDefault();
}
Initialize();
</script>
</body>