Add "add" html page

This commit is contained in:
Alexey Khit
2023-03-19 16:38:36 +03:00
parent e728643aad
commit bd79b24db3
10 changed files with 272 additions and 231 deletions

View File

@@ -144,3 +144,23 @@ func exitHandler(w http.ResponseWriter, r *http.Request) {
code, _ := strconv.Atoi(s)
os.Exit(code)
}
type Stream struct {
Name string `json:"name"`
URL string `json:"url"`
}
func ResponseStreams(w http.ResponseWriter, streams []Stream) {
if len(streams) == 0 {
http.Error(w, "no streams", http.StatusNotFound)
return
}
var response struct {
Streams []Stream `json:"streams"`
}
response.Streams = streams
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

View File

@@ -1,7 +1,6 @@
package device
import (
"encoding/json"
"github.com/AlexxIT/go2rtc/cmd/api"
"github.com/AlexxIT/go2rtc/cmd/app"
"github.com/AlexxIT/go2rtc/pkg/core"
@@ -72,12 +71,21 @@ func handle(w http.ResponseWriter, r *http.Request) {
loadMedias()
}
data, err := json.Marshal(medias)
if err != nil {
log.Error().Err(err).Msg("[api.ffmpeg]")
return
var items []api.Stream
var iv, ia int
for _, media := range medias {
var source string
switch media.Kind {
case core.KindVideo:
source = "ffmpeg:device?video=" + strconv.Itoa(iv)
iv++
case core.KindAudio:
source = "ffmpeg:device?audio=" + strconv.Itoa(ia)
ia++
}
if _, err = w.Write(data); err != nil {
log.Error().Err(err).Msg("[api.ffmpeg]")
items = append(items, api.Stream{Name: media.ID, URL: source})
}
api.ResponseStreams(w, items)
}

View File

@@ -3,11 +3,13 @@ package hass
import (
"encoding/json"
"fmt"
"github.com/AlexxIT/go2rtc/cmd/api"
"github.com/AlexxIT/go2rtc/cmd/app"
"github.com/AlexxIT/go2rtc/cmd/roborock"
"github.com/AlexxIT/go2rtc/cmd/streams"
"github.com/AlexxIT/go2rtc/pkg/core"
"github.com/rs/zerolog"
"net/http"
"os"
"path"
)
@@ -39,6 +41,14 @@ func Init() {
urls := map[string]string{}
api.HandleFunc("api/hass", func(w http.ResponseWriter, r *http.Request) {
var items []api.Stream
for name, url := range urls {
items = append(items, api.Stream{Name: name, URL: url})
}
api.ResponseStreams(w, items)
})
streams.HandleFunc("hass", func(url string) (core.Producer, error) {
if hurl := urls[url[5:]]; hurl != "" {
return streams.GetProducer(hurl)

View File

@@ -1,7 +1,6 @@
package roborock
import (
"encoding/json"
"fmt"
"github.com/AlexxIT/go2rtc/cmd/api"
"github.com/AlexxIT/go2rtc/cmd/streams"
@@ -85,17 +84,7 @@ func apiHandle(w http.ResponseWriter, r *http.Request) {
return
}
if len(devices) == 0 {
http.Error(w, "no devices in the account", http.StatusNotFound)
return
}
var response struct {
Devices []struct {
Name string `json:"name"`
Source string `json:"source"`
} `json:"devices"`
}
var items []api.Stream
for _, device := range devices {
source := fmt.Sprintf(
@@ -104,17 +93,8 @@ func apiHandle(w http.ResponseWriter, r *http.Request) {
Auth.UserData.IoT.User, Auth.UserData.IoT.Pass, Auth.UserData.IoT.Domain,
device.DID, device.Key,
)
response.Devices = append(response.Devices, struct {
Name string `json:"name"`
Source string `json:"source"`
}{
Name: device.Name,
Source: source,
})
items = append(items, api.Stream{Name: device.Name, URL: source})
}
if err = json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
api.ResponseStreams(w, items)
}

222
www/add.html Normal file
View File

@@ -0,0 +1,222 @@
<!DOCTYPE html>
<html>
<head>
<title>Add Stream</title>
<meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
body {
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
html, body {
width: 100%;
height: 100%;
}
.module {
display: none;
padding: 10px;
}
table {
background-color: white;
text-align: left;
border-collapse: collapse;
}
table td, table th {
border: 1px solid black;
padding: 5px 5px;
}
table tbody td {
font-size: 13px;
}
table thead {
background: #CFCFCF;
background: linear-gradient(to bottom, #dbdbdb 0%, #d3d3d3 66%, #CFCFCF 100%);
border-bottom: 3px solid black;
}
table thead th {
font-size: 15px;
font-weight: bold;
color: black;
text-align: center;
}
</style>
</head>
<body>
<script src="main.js"></script>
<script>
async function getStreams(url, tableID) {
const table = document.getElementById(tableID)
const r = typeof url === 'string' ? await fetch(url, {cache: 'no-cache'}) : url
if (!r.ok) {
table.innerText = await r.text()
return
}
/** @type {{streams:Array<{name:string,url:string}>}} */
const data = await r.json()
table.innerHTML = data.streams.reduce((html, item) => {
return html + `<tr><td>${item.name}</td><td>${item.url}</td></tr>`
}, '<thead><tr><th>Name</th><th>Source</th></tr></thead><tbody>') + '</tbody>'
}
</script>
<button id="stream">Temporary stream</button>
<div class="module">
<form id="stream-form" style="padding: 10px">
<input type="text" name="name" placeholder="name">
<input type="text" name="src" placeholder="url">
<input type="submit" value="add">
</form>
</div>
<script>
document.getElementById('stream').addEventListener('click', async ev => {
ev.target.nextElementSibling.style.display = 'block'
})
document.getElementById('stream-form').addEventListener('submit', async ev => {
ev.preventDefault()
const url = new URL('api/streams', location.href)
url.searchParams.set('name', ev.target.elements['name'].value)
url.searchParams.set('src', ev.target.elements['src'].value)
const r = await fetch(url, {method: 'PUT'})
alert(r.ok ? 'OK' : 'ERROR')
})
</script>
<button id="homekit">Apple HomeKit</button>
<div class="module">
<div style="margin-bottom: 10px">
<label for="pin">PIN</label>
<input id="pin" type="text">
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Model</th>
<th>Commands</th>
</tr>
</thead>
<tbody id="homekit-body">
</tbody>
</table>
</div>
<script>
document.getElementById('homekit').addEventListener('click', async ev => {
ev.target.nextElementSibling.style.display = 'block'
const r = await fetch('api/homekit', {cache: 'no-cache'})
/** @type {Array<{id:string,name:string,addr:string,model:string,paired:boolean}>} */
const data = await r.json()
const tbody = document.getElementById('homekit-body')
tbody.innerHTML =
data.reduce((res, item) => {
let commands = ''
if (item.id === "") {
commands = `<a href="#" onclick="unpair('${item.name}')">unpair</a>`
} else if (item.paired === false) {
commands = `<a href="#" onclick="pair('${item.id}','${item.name}')">pair</a>`
}
return res + `<tr>
<td>${item.name}</td>
<td>${item.addr}</td>
<td>${item.model}</td>
<td>${commands}</td>
</tr>`
}, '')
})
function pair(id, name) {
const pin = document.querySelector('#pin').value
fetch(`api/homekit?id=${id}&name=${name}&pin=${pin}`, {method: 'POST'})
.then(r => r.text())
.then(data => {
if (data.length > 0) alert(data)
else window.location.reload()
})
.catch(console.error)
}
function unpair(src) {
fetch(`api/homekit?src=${src}`, {method: 'DELETE'})
.then(r => r.text())
.then(data => {
if (data.length > 0) alert(data)
else window.location.reload()
})
.catch(console.error)
}
</script>
<button id="hass">Home Assistant</button>
<div class="module">
<table id="hass-table"></table>
</div>
<script>
document.getElementById('hass').addEventListener('click', async ev => {
ev.target.nextElementSibling.style.display = 'block'
await getStreams('api/hass', 'hass-table')
})
</script>
<button id="roborock">Roborock</button>
<div class="module">
<form id="roborock-form" style="margin-bottom: 10px">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<input type="submit" value="Login">
</form>
<table id="roborock-table">
</table>
</div>
<script>
document.getElementById('roborock').addEventListener('click', async ev => {
ev.target.nextElementSibling.style.display = 'block'
await getStreams('api/roborock', 'roborock-table')
})
document.getElementById('roborock-form').addEventListener('submit', async ev => {
ev.preventDefault()
const r = await fetch('api/roborock', {method: 'POST', body: new FormData(ev.target)})
await getStreams(r, 'roborock-table')
})
</script>
<button id="devices">USB Devices</button>
<div class="module">
<table id="devices-table">
</table>
</div>
<script>
document.getElementById('devices').addEventListener('click', async ev => {
ev.target.nextElementSibling.style.display = 'block'
await getStreams('api/devices', 'devices-table')
})
</script>
</body>
</html>

View File

@@ -1,75 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>go2rtc</title>
<style>
table {
background-color: white;
text-align: left;
border-collapse: collapse;
}
table td, table th {
border: 1px solid black;
padding: 5px 5px;
}
table tbody td {
font-size: 13px;
}
table thead {
background: #CFCFCF;
background: linear-gradient(to bottom, #dbdbdb 0%, #d3d3d3 66%, #CFCFCF 100%);
border-bottom: 3px solid black;
}
table thead th {
font-size: 15px;
font-weight: bold;
color: black;
text-align: center;
}
.header {
padding: 5px 5px;
}
</style>
</head>
<body>
<script src="main.js"></script>
<table>
<thead>
<tr>
<th>Kind</th>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
const baseUrl = location.origin + location.pathname.substr(
0, location.pathname.lastIndexOf("/")
);
fetch(`${baseUrl}/api/devices`, {cache: 'no-cache'})
.then(r => r.json())
.then(data => {
document.querySelector("body > table > tbody").innerHTML =
data.reduce((html, item) => {
return html + `<tr>
<td>${item.kind}</td>
<td>${item.title}</td>
</tr>`;
}, '');
})
.catch(console.error);
</script>
</body>
</html>

View File

@@ -1,111 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>go2rtc</title>
<style>
table {
background-color: white;
text-align: left;
border-collapse: collapse;
}
table td, table th {
border: 1px solid black;
padding: 5px 5px;
}
table tbody td {
font-size: 13px;
}
table thead {
background: #CFCFCF;
background: linear-gradient(to bottom, #dbdbdb 0%, #d3d3d3 66%, #CFCFCF 100%);
border-bottom: 3px solid black;
}
table thead th {
font-size: 15px;
font-weight: bold;
color: black;
text-align: center;
}
.header {
padding: 5px 5px;
}
</style>
</head>
<body>
<script src="main.js"></script>
<div class="header">
<label for="pin">PIN</label>
<input id="pin" type="text">
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Model</th>
<th>Commands</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
const baseUrl = location.origin + location.pathname.substr(
0, location.pathname.lastIndexOf("/")
);
fetch(`${baseUrl}/api/homekit`, {cache: 'no-cache'})
.then(r => r.json())
.then(data => {
document.querySelector("body > table > tbody").innerHTML =
data.reduce((res, item) => {
let commands = '';
if (item.id === "") {
commands = `<a href="#" onclick="unpair('${item.name}')">unpair</a>`;
} else if (item.paired === false) {
commands = `<a href="#" onclick="pair('${item.id}','${item.name}')">pair</a>`;
}
return res + `<tr>
<td>${item.name}</td>
<td>${item.addr}</td>
<td>${item.model}</td>
<td>${commands}</td>
</tr>`;
}, '');
})
.catch(console.error);
function pair(id, name) {
const pin = document.querySelector("#pin").value;
fetch(`${baseUrl}/api/homekit?id=${id}&name=${name}&pin=${pin}`, {method: 'POST'})
.then(r => r.text())
.then(data => {
if (data.length > 0) alert(data);
else window.location.reload();
})
.catch(console.error);
}
function unpair(src) {
fetch(`${baseUrl}/api/homekit?src=${src}`, {method: 'DELETE'})
.then(r => r.text())
.then(data => {
if (data.length > 0) alert(data);
else window.location.reload();
})
.catch(console.error);
}
</script>
</body>
</html>

View File

@@ -63,10 +63,6 @@
<body>
<script src="main.js"></script>
<div class="info"></div>
<div class="header">
<input id="src" type="text" placeholder="url">
<a id="add" href="#">add</a>
</div>
<div class="controls">
<button>stream</button>
<label><input type="checkbox" name="webrtc" checked>webrtc</label>
@@ -93,14 +89,6 @@
'<a href="#" data-name="{name}">delete</a>',
];
document.querySelector("#add")
.addEventListener("click", () => {
const src = document.querySelector("#src");
const url = new URL("api/streams", location.href);
url.searchParams.set("src", src.value);
fetch(url, {method: "PUT"}).then(reload);
});
document.querySelector(".controls > button")
.addEventListener("click", () => {
const url = new URL("stream.html", location.href);

View File

@@ -45,8 +45,7 @@ nav li {
<nav>
<ul>
<li><a href="index.html">Streams</a></li>
<li><a href="devices.html">Devices</a></li>
<li><a href="homekit.html">HomeKit</a></li>
<li><a href="add.html">Add</a></li>
<li><a href="editor.html">Config</a></li>
</ul>
</nav>