Merge pull request 'Add proper Electron launcher and building process' (#6) from electron into master

Reviewed-on: #6
This commit is contained in:
Sören Oesterwind 2022-11-15 18:28:59 +01:00
commit 2e1fc97f6f
11 changed files with 6777 additions and 3157 deletions

2
.gitignore vendored
View File

@ -8,3 +8,5 @@ bom.json
log-journal.json log-journal.json
openCountdown openCountdown
openCountdown.exe openCountdown.exe
buildout
package-lock.json

View File

@ -10,19 +10,19 @@ Support for companion is currently being worked on [here](https://github.com/bit
You can download complete binaries from the release tab. You can download complete binaries from the release tab.
## Development build ## Development build
1. Download the repository 1. Download the repository
2. `npm install` to install dependecies 2. `npm install` to install dependencies
3. `npm start` to launch 3. `npm start` to launch
### Startup Arguments ### Startup Arguments
One can pass a `--headless` argument to start the server in headless mode. This will disable the GUI. One can pass a `--headless` argument to start the server in headless mode. This will disable the GUI.
## Packaging ## Packaging
This is more a comment for the future version of me. There is one command for packaging using nexe. We've introduced a new packaging system. It is based on [electron-builder](https://www.electron.build/). This allows for easy packaging of the application for different platforms.
```bash ```bash
npx nexe index.js --build --python python3 --resource "./{lang,templates,static}/**/*" --ouput "openCountdown.exe” chmod +x ./build.sh
./build.sh
``` ```
Where `--python` is only needed in some envoirments for some reason. Also adjust `--output` for your target OS.
> Binary Builds may be faulty or non-working. They are not offically supported. > Binary Builds may be faulty or non-working. They are not officially supported.
*Small disclaimer: Please do not use openCountdown for military or life-depending applications. Please also refrain from using openCountdown for launching rockets.* *Small disclaimer: Please do not use openCountdown for military or life-depending applications. Please also refrain from using openCountdown for launching rockets.*

19
build.sh Executable file
View File

@ -0,0 +1,19 @@
#!/bin/bash
#npx electron-packager . --platform=win32 --overwrite --out=./buildout
npx electron-packager . --platform=win32,linux --overwrite --out=./buildout
cd "./buildout/" || exit 1
resources=(
"electronAssets"
"lang"
"static"
"templates"
"package.json"
)
for dir in */; do
for i in "${resources[@]}"; do
echo "$dir -> $i"
cp -r "$dir/resources/app/$i" "$dir"
done
done

View File

@ -1 +0,0 @@
nexe index.js --build --python python3 --resource "./static/*" --resource "./templates/*"

19
build_win.sh Normal file
View File

@ -0,0 +1,19 @@
#!/bin/bash
#npx electron-packager . --platform=win32 --overwrite --out=./buildout
npx electron-packager . --platform=win32,linux --overwrite --out=./buildout
cd "./buildout/" || exit 1
resources=(
"electronAssets"
"lang"
"static"
"templates"
"package.json"
)
for dir in */; do
for i in "${resources[@]}"; do
echo "$dir -> $i"
cp -r "$dir\resources/app/$i" "$dir"
done
done

View File

@ -25,7 +25,7 @@ function close(){
/** /**
* A simple logging function * A simple logging function
* @param {String} message A messaged to be logged * @param {String} message A messaged to be logged
* @param {String} level Logleve, may either be warn, error, magic or info * @param {String} level Loglevel, may either be warn, error, magic or info
* @param {String} module Kinda the source * @param {String} module Kinda the source
*/ */
function log(message, level, module, ignore = false) { function log(message, level, module, ignore = false) {

View File

@ -1,191 +0,0 @@
const { app, BrowserWindow, ipcMain, Tray, Menu, nativeImage, MenuItem, dialog } = require('electron')
const path = require('path')
const fs = require('fs')
const _ = require("underscore")
const open = require('open');
const childProcess = require('child_process');
const packageJson = JSON.parse(fs.readFileSync("package.json"))
// a minimal config
let configObject = {
language: "en_uk",
startMinimised: false,
port: 3000
}
if (!fs.existsSync("config.json")) {
fs.writeFileSync("config.json", "{}");
}
const tempJsonText = JSON.parse(fs.readFileSync("config.json", "utf8"));
configObject = _.extend(configObject, tempJsonText);
fs.writeFileSync("config.json", JSON.stringify(configObject));
const processArgs = process.argv;
// Check if --headless is passed as an argument
if (processArgs.includes("--headless")) {
startServer()
} else {
// Start electron
app.whenReady().then(() => {
startServer()
createTray()
createWindow()
})
ipcMain.on('info', function () {
if (win) {
win.webContents.send('info', { "appStatus": "Testing", "appURL": "http://127.0.0.1:" + configObject.port, "appName": "openCountdown " + packageJson.version, "startMinimised": configObject.startMinimised, "port": configObject.port })
}
})
ipcMain.on('skeleton-close', function (req, cb) {
trayQuit()
})
ipcMain.on('skeleton-minimize', function (req, cb) {
win.hide()
})
ipcMain.on('skeleton-launch-gui', function () {
launchUI()
})
ipcMain.on('skeleton-start-minimised', function (e, msg) {
configObject.startMinimised = msg
fs.writeFileSync("config.json", JSON.stringify(configObject));
})
ipcMain.on('skeleton-bind-port', function (e, msg) {
configObject.port = msg
console.log("Update port")
fs.writeFileSync("config.json", JSON.stringify(configObject));
dialog.showMessageBoxSync({
message: "Port changed. Restart openCountdown to apply change.",
buttons: ["OK"]})
})
}
var win, tray = null;
const createWindow = () => {
win = new BrowserWindow({
width: 370,
height: 500,
transparent: true,
frame: false,
resizable: false,
icon: path.join(__dirname, 'static/logo/faviconLogo.svg'),
webPreferences: {
pageVisibility: true,
nodeIntegration: true,
contextIsolation: true,
preload: path.join(__dirname, 'electronAssets/windowPreload.js'),
}
})
win.loadFile('electronAssets/index2.html')
if (configObject.startMinimised) {
win.hide()
}
}
function createTray() {
tray = new Tray('static/logo/faviconLogo.png')
tray.setIgnoreDoubleClickEvents(true)
const menu = new Menu()
menu.append(
new MenuItem({
label: 'Show window',
click: showScreen,
})
)
menu.append(
new MenuItem({
label: 'Launch GUI',
click: launchUI,
})
)
menu.append(
new MenuItem({
label: 'Quit',
accelerator: 'Command+Q',
click: trayQuit,
})
)
tray.setToolTip('openCountdown ' + packageJson.version)
tray.setContextMenu(menu)
tray.on('click', function (e) {
if (win.isVisible()) {
win.hide()
} else {
win.show()
}
});
}
function showScreen(){
win.show()
}
function launchUI(){
open("http://127.0.0.1:" + configObject.port)
}
function trayQuit(){
let options = {
buttons: ["Yes","No"],
message: "Do you really want to quit openCountdown?"
}
let response = dialog.showMessageBoxSync(options)
if(response == 0){
srvProc.kill("SIGINT")
setTimeout(app.quit, 1000)
}
}
// taken from https://stackoverflow.com/a/22649812/11317151
function runScript(scriptPath, callback, valueCb) {
// keep track of whether callback has been invoked to prevent multiple invocations
var invoked = false;
var process = childProcess.fork(scriptPath);
valueCb(process)
// listen for errors as they may prevent the exit event from firing
process.on('error', function (err) {
if (invoked) return;
invoked = true;
callback(err);
});
// execute the callback once the process has finished running
process.on('exit', function (code) {
if (invoked) return;
invoked = true;
// var err = code === 0 ? null : new Error('exit code ' + code);
callback(code);
});
}
srvProc = null;
function setServer(process){
srvProc = process
}
function startServer(){
runScript(path.join(__dirname, 'index.js'), function (err) {
if (err) throw err;
}, setServer)
}

4075
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,34 +1,39 @@
{ {
"name": "opencountdown", "name": "opencountdown",
"version": "1.0.3", "version": "1.0.5",
"description": "An opensource countdown", "description": "An opensource countdown",
"main": "index.js", "main": "startHandler.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"build": "nexe index.js --build", "start": "electron startHandler.js"
"start": "electron newStartHandler.js"
}, },
"author": "TheGreydiamond", "author": "TheGreydiamond",
"license": "LGPL-3.0", "license": "LGPL-3.0",
"dependencies": { "dependencies": {
"body-parser": "^1.19.2", "body-parser": "^1.20.1",
"bootstrap": "^5.1.3", "bootstrap": "^5.2.2",
"bootstrap-duration-picker": "^2.1.3", "bootstrap-duration-picker": "^2.1.3",
"bootstrap-icons": "^1.8.1", "bootstrap-icons": "^1.10.1",
"colors": "^1.4.0", "colors": "^1.4.0",
"darkreader": "^4.9.44", "darkreader": "^4.9.58",
"eta": "^1.12.3", "eta": "^1.12.3",
"express": "^4.17.3", "express": "^4.18.2",
"flatpickr": "^4.6.11", "flatpickr": "^4.6.13",
"jquery": "^3.6.0", "jquery": "^3.6.1",
"js-cookie": "^3.0.1", "js-cookie": "^3.0.1",
"less": "^3.13", "less": "^4.1.3",
"mdbootstrap": "^4.20.0", "mdbootstrap": "^4.20.0",
"open": "^8.4.0", "open": "^8.4.0",
"underscore": "^1.13.3", "underscore": "^1.13.6",
"ws": "^8.5.0" "ws": "^8.11.0"
}, },
"devDependencies": { "devDependencies": {
"electron": "^20.0.3" "electron": "^21.2.3",
"electron-builder": "^23.6.0"
},
"build": {
"extraMetadata": {
"main": "startHandler.js"
}
} }
} }

226
startHandler.js Normal file
View File

@ -0,0 +1,226 @@
const { app, BrowserWindow, ipcMain, Tray, Menu, MenuItem, dialog } = require('electron')
const path = require('path')
const fs = require('fs')
const _ = require("underscore")
const open = require('open');
const childProcess = require('child_process');
const http = require('http');
const packageJson = JSON.parse(fs.readFileSync("package.json"))
// a minimal config
let configObject = {
language: "en_uk",
startMinimised: false,
port: 3000
}
if (!fs.existsSync("config.json")) {
fs.writeFileSync("config.json", "{}");
}
const tempJsonText = JSON.parse(fs.readFileSync("config.json", "utf8"));
configObject = _.extend(configObject, tempJsonText);
fs.writeFileSync("config.json", JSON.stringify(configObject));
// Set a serverStatus
let serverStatus = "Starting"
// Check if --headless is passed as an argument
const processArgs = process.argv;
if (processArgs.includes("--headless")) {
startServer()
} else {
// Start electron
app.whenReady().then(() => {
startServer()
createTray()
createWindow()
setInterval(() => {
// Check if the server is running
http.get('http://127.0.0.1:' + configObject.port + "/api/v1/system", (resp) => {
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
// If we have a valid response, set the serverStatus to "Running"
let parsed = JSON.parse(data)
console.log(parsed)
serverStatus = "Running"
// Send the serverStatus to the window
if (win) {
win.webContents.send('info', { "appStatus": serverStatus, "appURL": "http://127.0.0.1:" + configObject.port, "appName": "openCountdown " + packageJson.version, "startMinimised": configObject.startMinimised, "port": configObject.port })
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}, 2000);
})
ipcMain.on('info', function () {
// Send inital data to the window
if (win) {
win.webContents.send('info', { "appStatus": serverStatus, "appURL": "http://127.0.0.1:" + configObject.port, "appName": "openCountdown " + packageJson.version, "startMinimised": configObject.startMinimised, "port": configObject.port })
}
})
ipcMain.on('skeleton-close', function (req, cb) {
trayQuit()
})
ipcMain.on('skeleton-minimize', function (req, cb) {
win.hide()
})
ipcMain.on('skeleton-launch-gui', function () {
launchUI()
})
ipcMain.on('skeleton-start-minimised', function (e, msg) {
configObject.startMinimised = msg
fs.writeFileSync("config.json", JSON.stringify(configObject));
})
ipcMain.on('skeleton-bind-port', function (e, msg) {
configObject.port = msg
console.log("Update port")
fs.writeFileSync("config.json", JSON.stringify(configObject));
dialog.showMessageBoxSync({
message: "Port changed. Restart openCountdown to apply change.",
buttons: ["OK"]
})
})
}
var win, tray = null;
const createWindow = () => {
win = new BrowserWindow({
width: 370,
height: 500,
transparent: true,
frame: false,
resizable: false,
icon: path.join(__dirname, 'static/logo/faviconLogo.svg'),
webPreferences: {
pageVisibility: true,
nodeIntegration: true,
contextIsolation: true,
preload: path.join(__dirname, 'electronAssets/windowPreload.js'),
}
})
win.loadFile('electronAssets/index.html')
if (configObject.startMinimised) {
win.hide()
}
}
function createTray() {
tray = new Tray('static/logo/faviconLogo.png')
tray.setIgnoreDoubleClickEvents(true)
const menu = new Menu()
menu.append(
new MenuItem({
label: 'Show window',
click: showScreen,
})
)
menu.append(
new MenuItem({
label: 'Launch GUI',
click: launchUI,
})
)
menu.append(
new MenuItem({
label: 'Quit',
accelerator: 'Command+Q',
click: trayQuit,
})
)
tray.setToolTip('openCountdown ' + packageJson.version)
tray.setContextMenu(menu)
tray.on('click', function (e) {
if (win.isVisible()) {
win.hide()
} else {
win.show()
}
});
}
function showScreen() {
win.show()
}
function launchUI() {
open("http://127.0.0.1:" + configObject.port)
}
function trayQuit() {
let options = {
buttons: ["Yes", "No"],
message: "Do you really want to quit openCountdown?"
}
let response = dialog.showMessageBoxSync(options)
if (response == 0) {
serverStatus = "Stopping"
if (win) {
win.webContents.send('info', { "appStatus": serverStatus, "appURL": "http://127.0.0.1:" + configObject.port, "appName": "openCountdown " + packageJson.version, "startMinimised": configObject.startMinimised, "port": configObject.port })
}
srvProc.kill("SIGINT")
setTimeout(app.quit, 1000)
}
}
// taken from https://stackoverflow.com/a/22649812/11317151
function runScript(scriptPath, callback, valueCb) {
// keep track of whether callback has been invoked to prevent multiple invocations
var invoked = false;
var process = childProcess.fork(scriptPath);
valueCb(process)
// listen for errors as they may prevent the exit event from firing
process.on('error', function (err) {
if (invoked) return;
invoked = true;
callback(err);
});
// execute the callback once the process has finished running
process.on('exit', function (code) {
if (invoked) return;
invoked = true;
// var err = code === 0 ? null : new Error('exit code ' + code);
callback(code);
});
}
srvProc = null;
function setServer(process) {
srvProc = process
}
function startServer() {
runScript(path.join(__dirname, 'index.js'), function (err) {
if (err) throw err;
}, setServer)
}