Compare commits

..

2 Commits

Author SHA1 Message Date
c0cfc04fef more fallback fixes 2022-03-10 20:55:23 +01:00
4156786b27 add websocket update 2022-03-10 18:56:51 +01:00
9 changed files with 241 additions and 38 deletions

View File

@ -1,6 +1,7 @@
const express = require("express");
const fs = require("fs");
const bodyParser = require("body-parser");
const ws = require('ws');
const helper = require("./helpers.js");
console.log("Preparing server...");
@ -43,19 +44,43 @@ currentState = {
textColors: {},
srvTime: 0,
enableColoredText: true,
debug: false
debug: false,
sessionToken: Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15),
};
const dataToBeWritten = {};
currentState = Object.assign({}, currentState, loadedData);
console.log(currentState)
currentState.textColors = currentState.colorSegments
const wsServer = new ws.Server({ noServer: true });
wsServer.on('connection', socket => {
socket.on('message', function incoming(data) {
if(data.toString() == "new client"){
updatedData()
}
});
});
wsServer.broadcast = function broadcast(data) {
wsServer.clients.forEach(function each(client) {
// The data is coming in correctly
// console.log(data);
client.send(data);
});
};
let updatey = undefined;
function updatedData() {
currentState.srvTime = new Date().getTime()
wsServer.broadcast(JSON.stringify(currentState));
clearTimeout(updatey);
setTimeout(updatedData, 5000 );
}
console.log("Preparing routes...");
app.get("/", function (req, res) {
const data = fs.readFileSync("templates/newAdminPanel.html", "utf8");
@ -78,8 +103,29 @@ app.get("/api/v1/data", function (req, res) {
res.json(currentState);
});
app.get("/api/v1/system", function (req, res) {
const systemData = {
uptime: process.uptime(),
memoryUsage: process.memoryUsage(),
cpuUsage: process.cpuUsage(),
platform: process.platform,
arch: process.arch,
nodeVersion: process.version,
nodePath: process.execPath,
nodeArgv: process.argv,
nodeExecArgv: process.execArgv,
nodeCwd: process.cwd(),
nodeEnv: process.env,
nodeConfig: process.config,
nodeTitle: process.title,
}
res.json(systemData);
});
app.get("/api/v1/set/mode", function (req, res) {
currentState.mode = req.query.mode;
updatedData()
res.json({ status: "ok" });
});
@ -92,24 +138,28 @@ app.get("/api/v1/set/layout/showMillis", function (req, res) {
}
res.json({ status: "ok" });
}
updatedData()
});
app.get("/api/v1/set/timerGoal", function (req, res) {
currentState.countdownGoal = new Date(parseInt(req.query.time)).getTime(); // ToDO error handling
res.json({ status: "ok" });
updatedData()
});
app.get("/api/v1/set/addMillisToTimer", function (req, res) {
currentState.timeAmountInital = req.query.time;
currentState.countdownGoal = new Date().getTime() + parseInt(req.query.time)
res.json({ status: "ok" });
updatedData()
});
app.get("/api/v1/ctrl/timer/pause", function (req, res) {
currentState.timerRunState = false;
currentState.pauseMoment = new Date().getTime();
res.json({ status: "ok" });
updatedData()
});
app.get("/api/v1/ctrl/timer/play", function (req, res) {
@ -119,11 +169,13 @@ app.get("/api/v1/ctrl/timer/play", function (req, res) {
currentState.countdownGoal += new Date().getTime() - currentState.pauseMoment;
}
res.json({ status: "ok" });
updatedData()
});
app.get("/api/v1/ctrl/timer/restart", function (req, res) {
currentState.countdownGoal = new Date().getTime() + parseInt(currentState.timeAmountInital)
res.json({ status: "ok" });
updatedData()
});
app.get("/api/v1/set/layout/showTime", function (req, res) {
@ -135,6 +187,7 @@ app.get("/api/v1/set/layout/showTime", function (req, res) {
}
res.json({ status: "ok" });
}
updatedData()
});
app.get("/api/v1/set/progressbar/show", function (req, res) {
@ -143,6 +196,7 @@ app.get("/api/v1/set/progressbar/show", function (req, res) {
dataToBeWritten.showProgressbar = currentState.showProgressbar
}
res.json({ status: "ok" });
updatedData()
});
app.get("/api/v1/set/progressbar/colors", function (req, res) {
@ -160,6 +214,7 @@ app.get("/api/v1/set/progressbar/colors", function (req, res) {
res.json({ status: "error", message: error });
console.error(error)
}
updatedData()
});
app.get("/api/v1/set/text/colors", function (req, res) {
@ -178,6 +233,7 @@ app.get("/api/v1/set/text/colors", function (req, res) {
res.json({ status: "error", message: error });
console.error(error)
}
updatedData()
});
app.get("/api/v1/set/text/enableColoring", function (req, res) {
@ -186,6 +242,7 @@ app.get("/api/v1/set/text/enableColoring", function (req, res) {
dataToBeWritten.enableColoredText = currentState.enableColoredText
}
res.json({ status: "ok" });
updatedData()
});
app.get("/api/v1/ctrl/message/show", function (req, res) {
@ -193,16 +250,19 @@ app.get("/api/v1/ctrl/message/show", function (req, res) {
currentState.showMessage = true
currentState.messageAppearTime = new Date().getTime()
res.json({ status: "ok" });
updatedData()
});
app.get("/api/v1/debug", function (req, res) {
currentState.debug = (req.query.enable === 'true');
res.json({ status: "ok" });
updatedData()
});
app.get("/api/v1/ctrl/message/hide", function (req, res) {
currentState.showMessage = false
res.json({ status: "ok" });
updatedData()
});
app.get("/api/v1/storage/commit", function (req, res) {
@ -213,6 +273,7 @@ app.get("/api/v1/storage/commit", function (req, res) {
} catch (error) {
res.json({ status: "error", reason: error });
}
updatedData()
});
@ -228,13 +289,20 @@ app.get("/api/v1/storage/delete", function (req, res) {
} else {
} res.json({ status: "error", reason: "Missing delete argument" });
updatedData()
});
console.log("Starting server...");
const port = 8005
app.listen(port);
const port = 3006
const server = app.listen(port);
server.on('upgrade', (request, socket, head) => {
wsServer.handleUpgrade(request, socket, head, socket => {
wsServer.emit('connection', socket, request);
});
});
console.info("Server running on port " + port);
console.info("Visit localhost:" + port + "/timer for the timer page");

46
package-lock.json generated
View File

@ -15,11 +15,13 @@
"bootstrap-icons": "^1.8.1",
"countdown": "^2.6.0",
"darkreader": "^4.9.44",
"eta": "^1.12.3",
"express": "^4.17.3",
"jquery": "^3.6.0",
"js-cookie": "^3.0.1",
"mdbootstrap": "^4.20.0",
"moment": "^2.29.1"
"moment": "^2.29.1",
"ws": "^8.5.0"
}
},
"node_modules/@popperjs/core": {
@ -192,6 +194,17 @@
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
},
"node_modules/eta": {
"version": "1.12.3",
"resolved": "https://registry.npmjs.org/eta/-/eta-1.12.3.tgz",
"integrity": "sha512-qHixwbDLtekO/d51Yr4glcaUJCIjGVJyTzuqV4GPlgZo1YpgOKG+avQynErZIYrfM6JIJdtiG2Kox8tbb+DoGg==",
"engines": {
"node": ">=6.0.0"
},
"funding": {
"url": "https://github.com/eta-dev/eta?sponsor=1"
}
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
@ -603,6 +616,26 @@
"engines": {
"node": ">= 0.8"
}
},
"node_modules/ws": {
"version": "8.5.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.5.0.tgz",
"integrity": "sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg==",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
},
"dependencies": {
@ -735,6 +768,11 @@
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
},
"eta": {
"version": "1.12.3",
"resolved": "https://registry.npmjs.org/eta/-/eta-1.12.3.tgz",
"integrity": "sha512-qHixwbDLtekO/d51Yr4glcaUJCIjGVJyTzuqV4GPlgZo1YpgOKG+avQynErZIYrfM6JIJdtiG2Kox8tbb+DoGg=="
},
"etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
@ -1033,6 +1071,12 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw="
},
"ws": {
"version": "8.5.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.5.0.tgz",
"integrity": "sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg==",
"requires": {}
}
}
}

View File

@ -19,6 +19,7 @@
"jquery": "^3.6.0",
"js-cookie": "^3.0.1",
"mdbootstrap": "^4.20.0",
"moment": "^2.29.1"
"moment": "^2.29.1",
"ws": "^8.5.0"
}
}

View File

@ -1,9 +1,10 @@
function convertTimeOffset(){
function convertTimeOffset() {
selTime = new Date().getTime() + document.getElementById('time2').valueAsNumber
document.getElementById("time").value = selTime
}
function convertColorSegments(elementId) {
const raw = document.getElementById(elementId);
console.log(raw)
@ -36,6 +37,16 @@ $(document).ready(function () {
}
}
saveOption("/api/v1/system", function systemInfo(event) {
const dataSystem = JSON.parse(event.originalTarget.response)
document.getElementById("nodejsVers").innerHTML = dataSystem.nodeVersion
const tree2 = jsonview.create(dataSystem);
jsonview.render(tree2, document.getElementById("systemInfo"));
jsonview.expand(tree2);
// console.log(dataSystem)
})
$("#addRow").click(function (event) {
$("#colors1").append(
'<tr>' +
@ -45,7 +56,7 @@ $(document).ready(function () {
'</tr>'
);
$('.colorPicky').colorpicker();
});
$("#addRow2").click(function (event) {
@ -61,11 +72,11 @@ $(document).ready(function () {
$("#copyColors").click(function CopyTextColors(event) {
event.target.innerHTML = '<div class="spinner-border-sm spinner-border"></div>'
saveOption("/api/v1/set/text/colors?copy=true", function finishCopyColors(event){
setTimeout(function(){
saveOption("/api/v1/set/text/colors?copy=true", function finishCopyColors(event) {
setTimeout(function () {
document.getElementById("copyColors").innerHTML = "Copy from progressbar colors"
}, 500)
})
});
@ -96,7 +107,10 @@ $(document).ready(function () {
</td></tr>'
const jsonResult = JSON.parse(xmlHttp.response)
document.getElementById("responeSnippet").innerHTML = JSON.stringify(jsonResult)
//.innerHTML = JSON.stringify(jsonResult, null, 4)
const tree = jsonview.create(jsonResult);
jsonview.render(tree, document.getElementById("responeSnippet"));
jsonview.expand(tree);
// Restore mode radio
const currentModeInt = modes.indexOf(jsonResult.mode);
$("#btnradio" + (currentModeInt + 1))[0].checked = true

1
static/js/jsonview.js Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
!function(a,b){"function"==typeof define&&define.amd?define([],b):"undefined"!=typeof module&&module.exports?module.exports=b():a.ReconnectingWebSocket=b()}(this,function(){function a(b,c,d){function l(a,b){var c=document.createEvent("CustomEvent");return c.initCustomEvent(a,!1,!1,b),c}var e={debug:!1,automaticOpen:!0,reconnectInterval:1e3,maxReconnectInterval:3e4,reconnectDecay:1.5,timeoutInterval:2e3};d||(d={});for(var f in e)this[f]="undefined"!=typeof d[f]?d[f]:e[f];this.url=b,this.reconnectAttempts=0,this.readyState=WebSocket.CONNECTING,this.protocol=null;var h,g=this,i=!1,j=!1,k=document.createElement("div");k.addEventListener("open",function(a){g.onopen(a)}),k.addEventListener("close",function(a){g.onclose(a)}),k.addEventListener("connecting",function(a){g.onconnecting(a)}),k.addEventListener("message",function(a){g.onmessage(a)}),k.addEventListener("error",function(a){g.onerror(a)}),this.addEventListener=k.addEventListener.bind(k),this.removeEventListener=k.removeEventListener.bind(k),this.dispatchEvent=k.dispatchEvent.bind(k),this.open=function(b){h=new WebSocket(g.url,c||[]),b||k.dispatchEvent(l("connecting")),(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","attempt-connect",g.url);var d=h,e=setTimeout(function(){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","connection-timeout",g.url),j=!0,d.close(),j=!1},g.timeoutInterval);h.onopen=function(){clearTimeout(e),(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onopen",g.url),g.protocol=h.protocol,g.readyState=WebSocket.OPEN,g.reconnectAttempts=0;var d=l("open");d.isReconnect=b,b=!1,k.dispatchEvent(d)},h.onclose=function(c){if(clearTimeout(e),h=null,i)g.readyState=WebSocket.CLOSED,k.dispatchEvent(l("close"));else{g.readyState=WebSocket.CONNECTING;var d=l("connecting");d.code=c.code,d.reason=c.reason,d.wasClean=c.wasClean,k.dispatchEvent(d),b||j||((g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onclose",g.url),k.dispatchEvent(l("close")));var e=g.reconnectInterval*Math.pow(g.reconnectDecay,g.reconnectAttempts);setTimeout(function(){g.reconnectAttempts++,g.open(!0)},e>g.maxReconnectInterval?g.maxReconnectInterval:e)}},h.onmessage=function(b){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onmessage",g.url,b.data);var c=l("message");c.data=b.data,k.dispatchEvent(c)},h.onerror=function(b){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onerror",g.url,b),k.dispatchEvent(l("error"))}},1==this.automaticOpen&&this.open(!1),this.send=function(b){if(h)return(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","send",g.url,b),h.send(b);throw"INVALID_STATE_ERR : Pausing to reconnect websocket"},this.close=function(a,b){"undefined"==typeof a&&(a=1e3),i=!0,h&&h.close(a,b)},this.refresh=function(){h&&h.close()}}return a.prototype.onopen=function(){},a.prototype.onclose=function(){},a.prototype.onconnecting=function(){},a.prototype.onmessage=function(){},a.prototype.onerror=function(){},a.debugAll=!1,a.CONNECTING=WebSocket.CONNECTING,a.OPEN=WebSocket.OPEN,a.CLOSING=WebSocket.CLOSING,a.CLOSED=WebSocket.CLOSED,a});

View File

@ -1,6 +1,77 @@
var newDateObj = new Date();
newDateObj = new Date(newDateObj.getTime() + 1000 * 20)
backReqInt = 0;
websocketFailed = false
recoveryAttempts = 0;
let socket = new ReconnectingWebSocket("ws://localhost:" + location.port);
let ackdSessionToken = false
let isFirstPacket = true
socket.onopen = function (e) {
// alert("[open] Connection established");
//alert("Sending to server");
socket.send("new client");
};
socket.onmessage = function (event) {
// alert(`[message] Data received from server: ${event.data}`);
let inData = JSON.parse(event.data)
if (isFirstPacket) {
isFirstPacket = false
dataFame = JSON.parse(event.data);
timeDiff = new Date().getTime() - dataFame.srvTime
} else {
if (inData.sessionToken == dataFame.sessionToken) {
dataFame = JSON.parse(event.data);
timeDiff = new Date().getTime() - dataFame.srvTime
} else {
if (ackdSessionToken == false) {
ackdSessionToken = true
if (confirm("Session token mismatch, reload the page?")) {
location.reload();
}
}
}
}
};
socket.onclose = function (event) {
if (event.wasClean) {
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
console.error('[close] Connection died');
/*websocketFailed = true
if (recoveryAttempts < 5) {
setTimeout(function handleWebsocketRecovery() {
// requestBackend()
websocketFailed = false
recoveryAttempts++;
console.warn("Trying to recover websocket connection")
socket.onopen = function (e) {
// alert("[open] Connection established");
//alert("Sending to server");
socket.send("new client");
};
}, 1000)
} else {
backReqInt = setInterval(requestBackend, 500);
}
*/
}
};
socket.onerror = function (error) {
// alert(`[error] ${error.message}`);
};
allowFullscreen = true
let dataFame = {}
let timeDiff = 0
@ -87,11 +158,10 @@ let isSlowed = false
function handleRecovery() {
var img = document.body.appendChild(document.createElement("img"));
img.onload = function()
{
location.reload();
};
img.src = "SMPTE_Color_Bars.svg";
img.onload = function () {
location.reload();
};
img.src = "SMPTE_Color_Bars.svg";
}
let recoInter = -1
@ -101,20 +171,20 @@ function handleUpdate() {
document.getElementById("incomeData").innerHTML = JSON.stringify(data)
document.getElementById("timediff").innerHTML = timeDiff + "<br>" + String(new Date().getTime() - data.srvTime);
if (new Date().getTime() - data.srvTime > 1000 * 5) {
if (!isSlowed) {
console.error("Server timeout")
clearInterval(updateInter)
updateInter = setInterval(handleUpdate, 900)
// clearInterval(updateInter)
// updateInter = setInterval(handleUpdate, 900)
document.getElementById("warningBanner").style.display = "block"
isSlowed = true
recoInter = setInterval(handleRecovery, 10000)
// recoInter = setInterval(handleRecovery, 10000)
}
} else {
if(isSlowed){
clearInterval(updateInter)
clearInterval(recoInter)
updateInter = setInterval(handleUpdate, 2)
if (isSlowed) {
//clearInterval(updateInter)
//clearInterval(recoInter)
//updateInter = setInterval(handleUpdate, 2)
document.getElementById("warningBanner").style.display = "none"
isSlowed = false
}
@ -222,7 +292,7 @@ function getTime() {
}
setInterval(requestBackend, 500);
// setInterval(requestBackend, 500);
updateInter = setInterval(handleUpdate, 2);
let temp = new URLSearchParams(window.location.search).get("smaller");

View File

@ -342,7 +342,7 @@
<label for="progBarShow">Show progressbar:</label>
<input type="checkbox" name="progBarShow" id="progBarShow"><br>
<details>
<summary>Progressbar Colors</summary>
<p>
@ -357,7 +357,7 @@
<th class="text-center">Remove</th>
</tr>
</thead>
</tbody>
</tbody>
</table>
</div>
@ -380,7 +380,7 @@
<th class="text-center">Remove</th>
</tr>
</thead>
</tbody>
</tbody>
</table>
</div>
<button type="button" class="btn btn-outline-success" id="copyColors">Copy from progressbar
@ -399,7 +399,7 @@
</page>
<page id="debug" class="pageC hidden flex-fill">
<page id="debug" class="pageC hidden flex-fill overflow-auto">
<h1>Debug page</h1>
<div class="alert alert-warning" role="alert">
<h4 class="alert-heading">Attention</h4>
@ -414,7 +414,7 @@
<button type="button" class="btn btn-outline-success" id="applyDebug">Apply settings</button>
<br><br>
<h3>Raw server reponse</h3>
<code id="responeSnippet" style="width: 40%; display: inline-block;">
<code id="responeSnippet" style="width: 40%; display: inline-block;" class="overflow-auto">
</code>
@ -424,15 +424,18 @@
</div>
</page>
<page id="about" class="pageC hidden flex-fill">
<page id="about" class="pageC hidden flex-fill overflow-auto">
<h1>About</h1>
Version: 1.0.0<br>
NodeJS Version: UNKNOWN<br>
Express Version: UNKNOWN<br>
NodeJS Version: <i id="nodejsVers"></i><br>
<code id="systemInfo" class="overflow-auto">
</code>
</page>
</pages>
</main>
<script src="/js/interface.js"> </script>
<script type="text/javascript" src="js/jsonview.js"></script>
<script type="text/javascript" src="/js/interface.js"> </script>
</body>

View File

@ -45,6 +45,7 @@
</div>
</div>
<script src="js/reconnecting-websocket.min.js" async defer></script>
<script src="js/countdown.js"></script>
<script src="js/script.js"></script>
</body>