Language Support #2

Merged
grey merged 4 commits from language into master 2022-05-12 21:03:14 +02:00
12 changed files with 191 additions and 32 deletions
Showing only changes of commit f3bcf63860 - Show all commits

2
.gitignore vendored
View File

@ -2,3 +2,5 @@ node_modules
rename.sh rename.sh
data-persistence.json data-persistence.json
log-journal.json log-journal.json
config.json
log-journal.json

View File

@ -29,4 +29,27 @@ function wrapBooleanConverter(stringBoolean, res) {
} }
} }
module.exports = { convertStringBooleanToBoolean, wrapBooleanConverter }; /**
* Tries to parse a string to a JSON object. Returns false if invalid. Taken from https://stackoverflow.com/a/20392392/11317151
* @param {String} jsonString A JSON String to parse
* @returns {Object/Boolean} JSON Object if valid or false otherwise
*/
function tryToParseJson(jsonString) {
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns null, and typeof null === "object",
// so we must check for that, too. Thankfully, null is falsey, so this suffices:
if (o && typeof o === "object") {
return o;
}
}
catch (e) { }
return false;
}
module.exports = { convertStringBooleanToBoolean, wrapBooleanConverter, tryToParseJson };

View File

@ -5,6 +5,7 @@ const ws = require('ws');
const helper = require("./helpers.js"); const helper = require("./helpers.js");
const loggy = require("./logging") const loggy = require("./logging")
const Eta = require("eta"); const Eta = require("eta");
const _ = require("underscore")
loggy.init(true) loggy.init(true)
@ -51,16 +52,34 @@ currentState = {
srvTime: 0, srvTime: 0,
enableColoredText: true, enableColoredText: true,
debug: false, debug: false,
sessionToken: Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15), sessionToken: Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
}; };
const dataToBeWritten = {}; let configObject = {
language: "en_uk"
}
const tempJsonText = JSON.parse(fs.readFileSync("config.json", "utf8"));
configObject = _.extend(configObject, tempJsonText);
fs.writeFileSync("config.json", JSON.stringify(configObject));
currentState = Object.assign({}, currentState, loadedData); currentState = Object.assign({}, currentState, loadedData);
currentState.textColors = currentState.colorSegments currentState.textColors = currentState.colorSegments
loggy.log("Searching for languages", "info", "Language")
const languagesRaw = fs.readdirSync("./lang");
const languages = [];
for (let i = 0; i < languagesRaw.length; i++) {
if (languagesRaw[i].endsWith(".json")) {
languages.push(languagesRaw[i].replace(".json", ""));
}
}
loggy.log("Found " + languages.length + " languages", "info", "Language")
loggy.log("Reading language file", "info", "Language") loggy.log("Reading language file", "info", "Language")
const languageProfile = JSON.parse(fs.readFileSync("lang/en_uk.json", "utf8")); let languageProfile = JSON.parse(fs.readFileSync("lang/" + configObject.language + ".json", "utf8"));
loggy.log("Preparing websocket", "info", "Websocket"); loggy.log("Preparing websocket", "info", "Websocket");
const wsServer = new ws.Server({ noServer: true }); const wsServer = new ws.Server({ noServer: true });
@ -95,11 +114,20 @@ app.get("/", function (req, res) {
try { try {
res.send( res.send(
Eta.render(data, { Eta.render(data, {
lang: languageProfile lang: languageProfile,
additional: {
languages: languages
}
})); }));
} catch (e) { } catch (e) {
const data = fs.readFileSync("templates/brokenTranslation.html", "utf8"); loggy.log("Error rendering template", "error", "Server");
res.send(data); const dataN = fs.readFileSync("templates/brokenTranslation.html", "utf8");
res.send(
Eta.render(dataN, {
additional: {
languages: languages
}
}));
} }
}); });
@ -311,6 +339,48 @@ app.get("/api/v1/storage/delete", function (req, res) {
updatedData() updatedData()
}); });
// UI Routes
// Returns an object containg all available languages
app.get("/api/ui/v1/lang/list", function handleLangList(req, res){
const tempRespObject = {
status: "ok",
languages: languages
}
res.json(tempRespObject);
})
app.get("/api/ui/v1/lang/set", function (req, res) {
if(req.query.lang == undefined || req.query.lang == ""){
res.json({ status: "error", reason: "Missing language" });
return;
}
const testLang = req.query.lang;
loggy.log("Reloading language file", "info", "Language")
if(!fs.existsSync("lang/" + testLang + ".json")){
loggy.log("Language reload failed, file does not exist", "error", "Language")
res.status(500).json({ status: "error", reason: "Language file not found" });
return
}
const tempLang = fs.readFileSync("lang/" + testLang + ".json", "utf8");
const tempLangObj = helper.tryToParseJson(tempLang);
if(!tempLangObj){
loggy.log("Language reload failed, file is not valid", "error", "Language")
res.status(500).json({ status: "error", reason: "Language file is not valid" });
return
}
if(tempLangObj._metadata == undefined){
loggy.log("Language reload failed, file is not valid, metadata missing", "error", "Language")
res.status(500).json({ status: "error", reason: "Language file is not valid" });
return
}
loggy.log("Language reloaded, loaded " + tempLangObj._metadata.lang + "@" + tempLangObj._metadata.version, "info", "Language")
configObject.language = req.query.lang;
languageProfile = tempLangObj;
res.status(200).json({ status: "ok" });
fs.writeFileSync("config.json", JSON.stringify(configObject));
});
app.use(function (req, res, next) { app.use(function (req, res, next) {
res.status(404); res.status(404);
loggy.log("Server responded with 404 error", "warn", "Server", true); loggy.log("Server responded with 404 error", "warn", "Server", true);

View File

@ -21,7 +21,7 @@
"messagingHint": "Zeigt eine Nachricht auf der Timeransicht an.", "messagingHint": "Zeigt eine Nachricht auf der Timeransicht an.",
"copyHint": "Kopiert den Link zu der Countdown-Seite.", "copyHint": "Kopiert den Link zu der Countdown-Seite.",
"openInNewTab": "Öffnet den Link in einem neuen Tab.", "openInNewTab": "Öffnet den Link in einem neuen Tab.",
"selectMode": "Wählt einen Modus für die Timeransicht.", "selectMode": "Wählt einen Modus für die Timeransicht."
}, },
"placeholders": { "placeholders": {
"msgHere": "Message here" "msgHere": "Message here"

View File

@ -6,7 +6,8 @@
"messaging": "Messaging", "messaging": "Messaging",
"countdownToTime": "Countdown to time", "countdownToTime": "Countdown to time",
"attention": "Attention", "attention": "Attention",
"hostinfo": "Host information" "hostinfo": "Host information",
"uiSettings": "UI settings"
}, },
"sidebar": { "sidebar": {
"home": "Home", "home": "Home",
@ -45,7 +46,9 @@
"enableTextClrs": "Enable Text Colours:", "enableTextClrs": "Enable Text Colours:",
"textClrs": "Text Colours", "textClrs": "Text Colours",
"addRow": "Add Row", "addRow": "Add Row",
"timeVar": "Enable time variance display:" "timeVar": "Enable time variance display:",
"language": "Select a language",
"apply": "Apply"
}, },
"untis": "untis":
{ {

View File

@ -1 +1 @@
[{"timestamp":"2022-05-10 19:38:52.853","level":"info","module":"Logging","message":"2022-05-10 19:38:52.853 [info] [Logging] Logging initialized"},{"timestamp":"2022-05-10 19:38:52.854","level":"info","module":"Server","message":"2022-05-10 19:38:52.854 [info] [Server] Preparing server"},{"timestamp":"2022-05-10 19:38:52.856","level":"info","module":"Server","message":"2022-05-10 19:38:52.856 [info] [Server] Preparing static routes"},{"timestamp":"2022-05-10 19:38:52.857","level":"info","module":"Server","message":"2022-05-10 19:38:52.857 [info] [Server] Preparing middlewares"},{"timestamp":"2022-05-10 19:38:52.857","level":"info","module":"Config","message":"2022-05-10 19:38:52.857 [info] [Config] Loading config"},{"timestamp":"2022-05-10 19:38:52.857","level":"info","module":"Language","message":"2022-05-10 19:38:52.857 [info] [Language] Reading language file"},{"timestamp":"2022-05-10 19:38:52.858","level":"info","module":"Websocket","message":"2022-05-10 19:38:52.858 [info] [Websocket] Preparing websocket"},{"timestamp":"2022-05-10 19:38:52.858","level":"info","module":"Server","message":"2022-05-10 19:38:52.858 [info] [Server] Preparing routes"},{"timestamp":"2022-05-10 19:38:52.859","level":"info","module":"Server","message":"2022-05-10 19:38:52.859 [info] [Server] Starting server"},{"timestamp":"2022-05-10 19:48:56.465","level":"info","module":"Shutdown","message":"2022-05-10 19:48:56.465 [info] [Shutdown] Caught interrupt signal and shutting down gracefully"}] [{"timestamp":"2022-05-12 18:53:40.121","level":"info","module":"Logging","message":"2022-05-12 18:53:40.121 [info] [Logging] Logging initialized"},{"timestamp":"2022-05-12 18:53:40.122","level":"info","module":"Server","message":"2022-05-12 18:53:40.122 [info] [Server] Preparing server"},{"timestamp":"2022-05-12 18:53:40.123","level":"info","module":"Server","message":"2022-05-12 18:53:40.123 [info] [Server] Preparing static routes"},{"timestamp":"2022-05-12 18:53:40.125","level":"info","module":"Server","message":"2022-05-12 18:53:40.125 [info] [Server] Preparing middlewares"},{"timestamp":"2022-05-12 18:53:40.125","level":"info","module":"Config","message":"2022-05-12 18:53:40.125 [info] [Config] Loading config"},{"timestamp":"2022-05-12 18:53:40.127","level":"info","module":"Language","message":"2022-05-12 18:53:40.127 [info] [Language] Searching for languages"},{"timestamp":"2022-05-12 18:53:40.127","level":"info","module":"Language","message":"2022-05-12 18:53:40.127 [info] [Language] Found 3 languages"},{"timestamp":"2022-05-12 18:53:40.127","level":"info","module":"Language","message":"2022-05-12 18:53:40.127 [info] [Language] Reading language file"},{"timestamp":"2022-05-12 18:53:40.128","level":"info","module":"Websocket","message":"2022-05-12 18:53:40.128 [info] [Websocket] Preparing websocket"},{"timestamp":"2022-05-12 18:53:40.128","level":"info","module":"Server","message":"2022-05-12 18:53:40.128 [info] [Server] Preparing routes"},{"timestamp":"2022-05-12 18:53:40.129","level":"info","module":"Server","message":"2022-05-12 18:53:40.129 [info] [Server] Starting server"},{"timestamp":"2022-05-12 18:53:41.756","level":"error","module":"Server","message":"2022-05-12 18:53:41.756 [error] [Server] Error rendering template"},{"timestamp":"2022-05-12 18:54:18.336","level":"error","module":"Server","message":"2022-05-12 18:54:18.336 [error] [Server] Error rendering template"},{"timestamp":"2022-05-12 18:54:20.275","level":"info","module":"Shutdown","message":"2022-05-12 18:54:20.275 [info] [Shutdown] Caught interrupt signal and shutting down gracefully"}]

11
package-lock.json generated
View File

@ -22,6 +22,7 @@
"js-cookie": "^3.0.1", "js-cookie": "^3.0.1",
"less": "^3.13", "less": "^3.13",
"mdbootstrap": "^4.20.0", "mdbootstrap": "^4.20.0",
"underscore": "^1.13.3",
"ws": "^8.5.0" "ws": "^8.5.0"
} }
}, },
@ -706,6 +707,11 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/underscore": {
"version": "1.13.3",
"resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.3.tgz",
"integrity": "sha512-QvjkYpiD+dJJraRA8+dGAU4i7aBbb2s0S3jA45TFOvg2VgqvdCDd/3N6CqA8gluk1W91GLoXg5enMUx560QzuA=="
},
"node_modules/unpipe": { "node_modules/unpipe": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
@ -1255,6 +1261,11 @@
"mime-types": "~2.1.24" "mime-types": "~2.1.24"
} }
}, },
"underscore": {
"version": "1.13.3",
"resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.3.tgz",
"integrity": "sha512-QvjkYpiD+dJJraRA8+dGAU4i7aBbb2s0S3jA45TFOvg2VgqvdCDd/3N6CqA8gluk1W91GLoXg5enMUx560QzuA=="
},
"unpipe": { "unpipe": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",

View File

@ -22,6 +22,7 @@
"js-cookie": "^3.0.1", "js-cookie": "^3.0.1",
"less": "^3.13", "less": "^3.13",
"mdbootstrap": "^4.20.0", "mdbootstrap": "^4.20.0",
"underscore": "^1.13.3",
"ws": "^8.5.0" "ws": "^8.5.0"
} }
} }

View File

@ -55,7 +55,7 @@ html, body {
.progBar { .progBar {
appearance: none; appearance: none;
height: 100%; height: 100%;
width: 80%; width: 0%;
border-radius: 0px; border-radius: 0px;
background-color: darkcyan; background-color: darkcyan;
} }

View File

@ -50,6 +50,19 @@ $(function () {
jsonview.expand(tree2); jsonview.expand(tree2);
}) })
$("#applyLang").on("click", function (event) {
const lang = $("#lang").val()
saveOption("/api/ui/v1/lang/set?lang=" + lang, function handleLangSelect(event, xmlHttp) {
const temp = JSON.parse(xmlHttp.responseText)
if(temp.status == "error") {
alert("Request failed reason: " + temp.reason)
} else {
location.reload()
}
console.log(JSON.parse(xmlHttp.responseText))
})
})
$("#addRow").on("click", function (event) { $("#addRow").on("click", function (event) {
const tableEntryDom = document.getElementById("tableCopySource").cloneNode(true) const tableEntryDom = document.getElementById("tableCopySource").cloneNode(true)
let temp = tableEntryDom.innerHTML let temp = tableEntryDom.innerHTML

View File

@ -81,24 +81,37 @@
</div> </div>
</div> </div>
<pages class="d-flex flex-fill" id="pageCont" class="z-index: 50;"> <pages class="d-flex flex-fill" id="pageCont" class="z-index: 50;">
<page id="homeP" class="pageC flex-fill overflow-auto"> <page id="homeP" class="pageC flex-fill overflow-auto">
<div class="container" > <div class="container">
<div class="" style=" display: flex;align-items: center;justify-content: center; flex-wrap: wrap; flex-direction: column;"> <div class=""
style=" display: flex;align-items: center;justify-content: center; flex-wrap: wrap; flex-direction: column;">
<h1>Oh no!</h1>
<h1> <h1>Oh no!</h1>
<i class="bi bi-translate"></i> <h1>
</h1> <i class="bi bi-translate"></i>
<h5> </h1>
There is a critical error with the current language template. Please select a diffrent language. <h5>
</h5> There is a critical error with the current language template. Please select a diffrent
language.
</h5>
<label for="lang">Please choose a language: </label>
<select name="lang" id="lang">
<% it.additional.languages.forEach(function(lang){ %>
<option value="<%= lang %>">
<%= lang %>
</option>
<% }) %>
</select>
<button id="applyLang" class="btn btn-outline-success">
Apply & Reload
</button>
</div> </div>
</div> </div>
</page> </page>
</pages> </pages>
</main> </main>
@ -112,7 +125,20 @@
}); });
$(function () { $(function () {
$('[data-toggle="tooltip"]').tooltip({ container: "body" }) $('[data-toggle="tooltip"]').tooltip({ container: "body" })
}) })
$("#applyLang").on("click", function (event) {
const lang = $("#lang").val()
saveOption("/api/ui/v1/lang/set?lang=" + lang, function handleLangSelect(event, xmlHttp) {
const temp = JSON.parse(xmlHttp.responseText)
if (temp.status == "error") {
alert("Request failed reason: " + temp.reason)
} else {
location.reload()
}
console.log(JSON.parse(xmlHttp.responseText))
})
})
</script> </script>
</body> </body>

View File

@ -137,7 +137,7 @@
</div> </div>
<div class="col"> <div class="col">
<h3><%= it.lang.titles.mode %> <span class="helperTip" data-placement="right" <h3><%= it.lang.titles.mode %> <span class="helperTip" data-placement="right"
title=<%= it.lang.hints.selectMode %> data-toggle="tooltip"> title="<%= it.lang.hints.selectMode %>" data-toggle="tooltip">
<i class="bi bi-question-circle-fill"></i> <i class="bi bi-question-circle-fill"></i>
</span></h3> </span></h3>
<div class="btn-group" role="group" aria-label="Basic radio toggle button group"> <div class="btn-group" role="group" aria-label="Basic radio toggle button group">
@ -311,8 +311,21 @@
<button type="button" class="btn btn-outline-success" id="saveLayout"><i class="bi bi-save"></i> Save as <button type="button" class="btn btn-outline-success" id="saveLayout"><i class="bi bi-save"></i> Save as
startup settings (Layout startup settings (Layout
only)</button> only)</button>
<hr>
<h2><%= it.lang.titles.uiSettings %></h2>
<label for="lang"><%= it.lang.labels.language %>:</label>
<select name="lang" id="lang">-
<% it.additional.languages.forEach(function(lang){ %>
<option value="<%= lang %>"><%= lang %></option>
<% }) %>
</select>
<button id="applyLang" class="btn btn-outline-success">
<%= it.lang.labels.apply %>
</button>
</page> </page>
<page id="debug" class="pageC hidden flex-fill overflow-auto"> <page id="debug" class="pageC hidden flex-fill overflow-auto">
<h1>Debug page</h1> <h1>Debug page</h1>
<div class="alert alert-danger" role="alert"> <div class="alert alert-danger" role="alert">
@ -343,7 +356,7 @@
<templateObj> <templateObj>
<table class="table table-bordered table-responsive-md table-striped text-center" id="colors1"> <table class="table table-bordered table-responsive-md table-striped text-center" id="colors1">
<thead> <thead>
<tr> <tr><%= it.lang.labels.time %>
<th class="text-center"><%= it.lang.labels.time %></th> <th class="text-center"><%= it.lang.labels.time %></th>
<th class="text-center"><%= it.lang.labels.color %></th> <th class="text-center"><%= it.lang.labels.color %></th>
<th class="text-center"><%= it.lang.labels.remove %></th> <th class="text-center"><%= it.lang.labels.remove %></th>
@ -370,9 +383,6 @@
</tr> </tr>
</tbody> </tbody>
</table> </table>
<tr> <tr>
<td class="pt-3-half numVal" contenteditable="true">#VALUE#</td> <td class="pt-3-half numVal" contenteditable="true">#VALUE#</td>
<td class="pt-3-half full" contenteditable="false"> <td class="pt-3-half full" contenteditable="false">