Started Work on Web UI

This commit is contained in:
Elia Zammuto
2021-05-09 18:55:34 +02:00
parent 661c8260e5
commit 4fe90dcbd6
12 changed files with 498 additions and 14 deletions

View File

@@ -167,6 +167,8 @@ set(SUNSHINE_TARGET_FILES
sunshine/crypto.h
sunshine/nvhttp.cpp
sunshine/nvhttp.h
sunshine/confighttp.cpp
sunshine/confighttp.h
sunshine/rtsp.cpp
sunshine/rtsp.h
sunshine/stream.cpp

124
assets/web/apps.html Normal file
View File

@@ -0,0 +1,124 @@
<div id="app" class="container">
<h1>Applications</h1>
<div>Applications are refreshed only when Client is restarted</div>
<table class="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="(app,i) in apps" :key="i">
<td>{{app.name}}</td>
<td><button class="btn btn-primary" @click="editApp(i)">Edit</button>
<button class="btn btn-danger" @click="showDeleteForm(i)">Delete</button></td>
</tr>
</tbody>
</table>
<div class="edit-form" v-if="showEditForm">
<div class="mb-3">
<label for="appName" class="form-label">Application Name</label>
<input type="text" class="form-control" id="appName" aria-describedby="appNameHelp" v-model="editForm.name">
<div id="appNameHelp" class="form-text">Application Name, as shown on Moonlight</div>
</div>
<div class="mb-3">
<label for="appName" class="form-label">Output</label>
<input type="text" class="form-control" id="appOutput" aria-describedby="appOutputHelp" v-model="editForm.output">
<div id="appOutputHelp" class="form-text">The file where the output of the command is stored, if it is not specified, the output is ignored</div>
</div>
<div class="mb-3">
<label for="appName" class="form-label">Command Preparations</label>
<div class="form-text">A list of commands to be run before/after the application. <br> If any of the prep-commands fail, starting the application is aborted</div>
<table>
<thead>
<th class="precmd-head">Do</th>
<th class="precmd-head">Undo</th>
<th></th>
</thead>
<tbody>
<tr v-for="(c,i) in editForm['prep-cmd']">
<td><input type="text" class="form-control" v-model="c.do"></td>
<td><input type="text" class="form-control" v-model="c.undo"></td>
<td><button class="btn btn-danger" @click="editForm['prep-cmd'].splice(i,1)">&times;</button></td>
</tr>
</tbody>
</table>
<button class="btn btn-success" @click="addPrepCmd">&plus;</button>
</div>
<div class="mb-3">
<label for="appCmd" class="form-label">Command</label>
<input type="text" class="form-control" id="appCmd" aria-describedby="appCmdHelp" v-model="editForm.cmd">
<div id="appCmdHelp" class="form-text">The main application, if it is not specified, a processs is started that sleeps indefinitely</div>
</div>
<div class="d-flex">
<button @click="showEditForm = false" class="btn btn-secondary m-2">Cancel</button>
<button class="btn btn-primary m-2" @click="save">Save</button>
</div>
</div>
<button class="btn btn-primary" v-else @click="newApp">+ Add New</button>
</div>
<script>
new Vue({
el: '#app',
data() {
return {
apps: [],
showEditForm: false,
editForm: null,
}
},
created() {
fetch("/api/apps").then(r => r.json()).then((r) => {
console.log(r);
this.apps = r.apps;
})
},
methods: {
newApp(){
this.editForm = {
name: '',
output: '',
cmd: [],
index: -1,
"prep-cmd": []
};
this.editForm.index = -1;
this.showEditForm = true;
},
editApp(id){
this.editForm = JSON.parse(JSON.stringify(this.apps[id]));
this.$set(this.editForm,"index",id);
if(this.editForm["prep-cmd"] === undefined)this.$set(this.editForm,"prep-cmd",[]);
this.showEditForm = true;
},
showDeleteForm(id){
let resp = confirm("Are you sure to delete " + this.apps[id].name + "?");
if(resp){
fetch("/api/apps/" + id,{method: "DELETE"}).then((r)=>{
if(r.status == 200)document.location.reload();
});
}
},
addPrepCmd(){
this.editForm['prep-cmd'].push({
do: '',
undo: '',
});
},
save(){
console.log("AAAAAAA")
fetch("/api/apps",{method: "POST",body: JSON.stringify(this.editForm)}).then((r)=>{
if(r.status == 200)document.location.reload();
});
}
}
})
</script>
<style>
.precmd-head {
width: 200px;
}
</style>

3
assets/web/clients.html Normal file
View File

@@ -0,0 +1,3 @@
<div id="content" class="container">
<h1>Clients</h1>
</div>

4
assets/web/config.html Normal file
View File

@@ -0,0 +1,4 @@
<div id="content" class="container">
<h1>Hello, Sunshine!</h1>
<p>Placeholer for config page</p>
</div>

45
assets/web/header.html Normal file
View File

@@ -0,0 +1,45 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sunshine</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light" style="background-color: #ffc400;">
<div class="container-fluid">
<span class="navbar-brand">Sunshine</span>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/pin">PIN</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/apps">Applications</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/clients">Clients</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config">Configuration</a>
</li>
</ul>
</div>
</nav>

4
assets/web/index.html Normal file
View File

@@ -0,0 +1,4 @@
<div id="content" class="container">
<h1>Hello, Sunshine!</h1>
<p>Sunshine is a Gamestream host for Moonlight</p>
</div>

22
assets/web/pin.html Normal file
View File

@@ -0,0 +1,22 @@
<div id="content" class="container">
<form action="" class="form" id="form">
<input type="number" placeholder="PIN" id="pin-input">
<button class="btn btn-primary">Send</button>
<div id="status"></div>
</form>
</div>
<script>
document.querySelector("#form").addEventListener("submit", (e) => {
e.preventDefault();
let pin = document.querySelector("#pin-input").value;
document.querySelector("#status").innerHTML = "";
fetch("/pin/" + pin).then((response)=>{
if(response.status == 200){
document.querySelector("#status").innerHTML = `<div class="alert alert-success" role="alert">Success! Please check Moonlight to continue</div>`;
} else if(response.status == 418){
document.querySelector("#status").innerHTML = `<div class="alert alert-danger" role="alert">PIN does not match, please check if it's typed correctly</div>`;
}
})
})
</script>

262
sunshine/confighttp.cpp Normal file
View File

@@ -0,0 +1,262 @@
//
// Created by TheElixZammuto on 2021-05-09.
// TODO: Authentication, better handling of routes common to nvhttp, cleanup
#include "process.h"
#include <filesystem>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/asio/ssl/context.hpp>
#include <Simple-Web-Server/server_http.hpp>
#include <boost/asio/ssl/context_base.hpp>
#include "config.h"
#include "utility.h"
#include "rtsp.h"
#include "crypto.h"
#include "confighttp.h"
#include "platform/common.h"
#include "network.h"
#include "nvhttp.h"
#include "uuid.h"
#include "main.h"
std::string read_file(std::string path);
namespace confighttp
{
using namespace std::literals;
constexpr auto PORT_HTTP = 47990;
namespace fs = std::filesystem;
namespace pt = boost::property_tree;
using https_server_t = SimpleWeb::Server<SimpleWeb::HTTPS>;
using args_t = SimpleWeb::CaseInsensitiveMultimap;
using resp_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Response>;
using req_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Request>;
enum class op_e
{
ADD,
REMOVE
};
template <class T>
void not_found(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request)
{
pt::ptree tree;
tree.put("root.<xmlattr>.status_code", 404);
std::ostringstream data;
pt::write_xml(data, tree);
response->write(data.str());
*response << "HTTP/1.1 404 NOT FOUND\r\n"
<< data.str();
}
void getIndexPage(resp_https_t response, req_https_t request)
{
std::string header = read_file(WEB_DIR "header.html");
std::string content = read_file(WEB_DIR "index.html");
response->write(header + content);
}
template <class T>
void getPinPage(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request)
{
std::string header = read_file(WEB_DIR "header.html");
std::string content = read_file(WEB_DIR "pin.html");
response->write(header + content);
}
template <class T>
void getAppsPage(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request)
{
std::string header = read_file(WEB_DIR "header.html");
std::string content = read_file(WEB_DIR "apps.html");
response->write(header + content);
}
template <class T>
void getClientsPage(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request)
{
std::string header = read_file(WEB_DIR "header.html");
std::string content = read_file(WEB_DIR "clients.html");
response->write(header + content);
}
template <class T>
void getConfigPage(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request)
{
std::string header = read_file(WEB_DIR "header.html");
std::string content = read_file(WEB_DIR "config.html");
response->write(header + content);
}
void getApps(resp_https_t response, req_https_t request)
{
std::string content = read_file(SUNSHINE_ASSETS_DIR "/" APPS_JSON);
response->write(content);
}
void saveApp(resp_https_t response, req_https_t request)
{
std::stringstream ss;
ss << request->content.rdbuf();
pt::ptree outputTree;
auto g = util::fail_guard([&]() {
std::ostringstream data;
pt::write_json(data, outputTree);
response->write(data.str());
});
pt::ptree inputTree,fileTree;
try {
//TODO: Input Validation
pt::read_json(ss, inputTree);
pt::read_json(SUNSHINE_ASSETS_DIR "/" APPS_JSON, fileTree);
auto &apps_node = fileTree.get_child("apps"s);
int index = inputTree.get<int>("index");
BOOST_LOG(info) << inputTree.get_child("prep-cmd").empty();
if(inputTree.get_child("prep-cmd").empty())inputTree.erase("prep-cmd");
inputTree.erase("index");
if(index == -1){
apps_node.push_back(std::make_pair("",inputTree));
} else {
//Unfortuantely Boost PT does not allow to directly edit the array, copt should do the trick
pt::ptree newApps;
int i = 0;
for (const auto& kv : apps_node) {
if(i == index){
newApps.push_back(std::make_pair("",inputTree));
} else {
newApps.push_back(std::make_pair("",kv.second));
}
i++;
}
fileTree.erase("apps");
fileTree.push_back(std::make_pair("apps",newApps));
}
pt::write_json(SUNSHINE_ASSETS_DIR "/" APPS_JSON, fileTree);
outputTree.put("status","true");
proc::refresh(SUNSHINE_ASSETS_DIR "/" APPS_JSON);
} catch (std::exception &e) {
BOOST_LOG(warning) << e.what();
outputTree.put("status","false");
outputTree.put("error","Invalid Input JSON");
return;
}
}
void deleteApp(resp_https_t response, req_https_t request)
{
pt::ptree outputTree;
auto g = util::fail_guard([&]() {
std::ostringstream data;
pt::write_json(data, outputTree);
response->write(data.str());
});
pt::ptree fileTree;
try {
pt::read_json(SUNSHINE_ASSETS_DIR "/" APPS_JSON, fileTree);
auto &apps_node = fileTree.get_child("apps"s);
int index = stoi(request->path_match[1]);
BOOST_LOG(info) << index;
if(index <= 0){
outputTree.put("status","false");
outputTree.put("error","Invalid Index");
return;
} else {
//Unfortuantely Boost PT does not allow to directly edit the array, copt should do the trick
pt::ptree newApps;
int i = 0;
for (const auto& kv : apps_node) {
if(i != index){
newApps.push_back(std::make_pair("",kv.second));
}
i++;
}
fileTree.erase("apps");
fileTree.push_back(std::make_pair("apps",newApps));
}
pt::write_json(SUNSHINE_ASSETS_DIR "/" APPS_JSON, fileTree);
outputTree.put("status","true");
proc::refresh(SUNSHINE_ASSETS_DIR "/" APPS_JSON);
} catch (std::exception &e) {
BOOST_LOG(warning) << e.what();
outputTree.put("status","false");
outputTree.put("error","Invalid File JSON");
return;
}
}
void start(std::shared_ptr<safe::signal_t> shutdown_event)
{
auto ctx = std::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::tls);
ctx->use_certificate_chain_file(config::nvhttp.cert);
ctx->use_private_key_file(config::nvhttp.pkey, boost::asio::ssl::context::pem);
https_server_t http_server { ctx, 0 };
http_server.default_resource = not_found<SimpleWeb::HTTPS>;
http_server.resource["^/$"]["GET"] = getIndexPage;
http_server.resource["^/pin$"]["GET"] = getPinPage<SimpleWeb::HTTPS>;
http_server.resource["^/apps$"]["GET"] = getAppsPage<SimpleWeb::HTTPS>;
http_server.resource["^/api/apps$"]["GET"] = getApps;
http_server.resource["^/api/apps$"]["POST"] = saveApp;
http_server.resource["^/api/apps/([0-9]+)$"]["DELETE"] = deleteApp;
http_server.resource["^/clients$"]["GET"] = getClientsPage<SimpleWeb::HTTPS>;
http_server.resource["^/config$"]["GET"] = getConfigPage<SimpleWeb::HTTPS>;
http_server.resource["^/pin/([0-9]+)$"]["GET"] = nvhttp::pin<SimpleWeb::HTTPS>;
http_server.config.reuse_address = true;
http_server.config.address = "0.0.0.0"s;
http_server.config.port = PORT_HTTP;
try
{
http_server.bind();
BOOST_LOG(info) << "Configuration UI available at [https://localhost:"sv << PORT_HTTP << "]";
}
catch (boost::system::system_error &err)
{
BOOST_LOG(fatal) << "Couldn't bind http server to ports ["sv << PORT_HTTP << "]: "sv << err.what();
shutdown_event->raise(true);
return;
}
std::thread tcp{&https_server_t::accept_and_run, &http_server};
// Wait for any event
shutdown_event->view();
http_server.stop();
tcp.join();
}
}
std::string read_file(std::string path)
{
std::ifstream in(path);
std::string input;
std::string base64_cert;
//FIXME: Being unable to read file could result in infinite loop
while (!in.eof())
{
std::getline(in, input);
base64_cert += input + '\n';
}
return base64_cert;
}

20
sunshine/confighttp.h Normal file
View File

@@ -0,0 +1,20 @@
//
// Created by loki on 6/3/19.
//
#ifndef SUNSHINE_CONFIGHTTP_H
#define SUNSHINE_CONFIGHTTP_H
#include <functional>
#include <string>
#include "thread_safe.h"
#define WEB_DIR SUNSHINE_ASSETS_DIR "/web/"
namespace confighttp {
void start(std::shared_ptr<safe::signal_t> shutdown_event);
}
#endif //SUNSHINE_CONFIGHTTP_H

View File

@@ -17,6 +17,7 @@
#include "video.h"
#include "input.h"
#include "nvhttp.h"
#include "confighttp.h"
#include "rtsp.h"
#include "config.h"
#include "thread_pool.h"
@@ -124,19 +125,8 @@ int main(int argc, char *argv[]) {
shutdown_event->raise(true);
});
auto proc_opt = proc::parse(config::stream.file_apps);
if(!proc_opt) {
return 7;
}
{
proc::ctx_t ctx;
ctx.name = "Desktop"s;
proc_opt->get_apps().emplace(std::begin(proc_opt->get_apps()), std::move(ctx));
}
proc::proc = std::move(*proc_opt);
proc::refresh(config::stream.file_apps);
auto deinit_guard = platf::init();
input::init();
reed_solomon_init();
@@ -147,6 +137,7 @@ int main(int argc, char *argv[]) {
task_pool.start(1);
std::thread httpThread { nvhttp::start, shutdown_event };
std::thread configThread { confighttp::start, shutdown_event };
stream::rtpThread(shutdown_event);
httpThread.join();

View File

@@ -7,7 +7,8 @@
#include <functional>
#include <string>
#include <Simple-Web-Server/server_http.hpp>
#include <Simple-Web-Server/server_https.hpp>
#include "thread_safe.h"
#define CA_DIR SUNSHINE_ASSETS_DIR "/demoCA"
@@ -16,6 +17,7 @@
namespace nvhttp {
void start(std::shared_ptr<safe::signal_t> shutdown_event);
template<class T> void pin(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request);
}
#endif //SUNSHINE_NVHTTP_H

View File

@@ -302,6 +302,11 @@ void refresh(const std::string &file_name) {
auto proc_opt = proc::parse(file_name);
if(proc_opt) {
{
proc::ctx_t ctx;
ctx.name = "Desktop"s;
proc_opt->get_apps().emplace(std::begin(proc_opt->get_apps()), std::move(ctx));
}
proc = std::move(*proc_opt);
}
}