mirror of
https://github.com/MichMich/MagicMirror.git
synced 2025-06-27 17:01:08 -04:00
## [2.29.0] - 2024-10-01 Thanks to: @bugsounet, @dkallen78, @jargordon, @khassel, @KristjanESPERANTO, @MarcLandis, @rejas, @ryan-d-williams, @sdetweil, @skpanagiotis. > ⚠️ This release needs nodejs version `v20` or `v22`, minimum version is `v20.9.0` ### Added - [compliments] Added support for cron type date/time format entries mm hh DD MM dow (minutes/hours/days/months and day of week) see https://crontab.cronhub.io for construction (#3481) - [core] Check config at every start of MagicMirror² (#3450) - [core] Add spelling check (cspell): `npm run test:spelling` and handle spelling issues (#3544) - [core] removed `config.paths.vendor` (could not work because `vendor` is hardcoded in `index.html`), renamed `config.paths.modules` to `config.foreignModulesDir`, added variable `MM_CUSTOMCSS_FILE` which - if set - overrides `config.customCss`, added variable `MM_MODULES_DIR` which - if set - overrides `config.foreignModulesDir`, added test for `MM_MODULES_DIR` (#3530) - [core] elements are now removed from `index.html` when loading script or stylesheet files fails - [core] Added `MODULE_DOM_UPDATED` notification each time the DOM is re-rendered via `updateDom` (#3534) - [tests] added minimal needed node version to tests (currently v20.9.0) to avoid releases with wrong node version info - [tests] Added `node-libgpiod` library to electron-rebuild tests (#3563) ### Removed - [core] removed installer only files (#3492) - [core] removed raspberry object from systeminformation (#3505) - [linter] removed `eslint-plugin-import`, because it doesn't support ESLint v9. We will reenter it later when it does. - [tests] removed `onoff` library from electron-rebuild tests (#3563) ### Updated - [weather] Updated `apiVersion` default from 2.5 to 3.0 (#3424) - [core] Updated dependencies including stylistic-eslint - [core] nail down `node-ical` version to `0.18.0` with exception `allow-ghsas: GHSA-8hc4-vh64-cxmj` in `dep-review.yaml` (which should removed after next `node-ical` update) - [core] Updated SocketIO catch all to new API - [core] Allow custom modules positions by scanning index.html for the defined regions, instead of hard coded (PR #3518 fixes issue #3504) - [core] Detail optimizations in `config_check.js` - [core] Updated minimal needed node version in `package.json` (currently v20.9.0) (#3559) and except for v21 (no security updates) (#3561) - [linter] Switch to ESLint v9 and flat config and replace `eslint-plugin-unicorn` by `@eslint/js` - [core] fix discovering module positions twice after #3450 ### Fixed - Fixed `checks` badge in README.md - [weather] Fixed issue with the UK Met Office provider following a change in their API paths and header info. - [core] add check for node_helper loading for multiple instances of same module (#3502) - [weather] Fixed issue for respecting unit config on broadcasted notifications - [tests] Fixes calendar test by moving it from e2e to electron with fixed date (#3532) - [calendar] fixed sliceMultiDayEvents getting wrong count and displaying incorrect entries, Europe/Berlin (#3542) - [tests] ignore `js/positions.js` when linting (this file is created at runtime) - [calendar] fixed sliceMultiDayEvents showing previous day without config enabled --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Michael Teeuw <michael@xonaymedia.nl> Co-authored-by: Kristjan ESPERANTO <35647502+KristjanESPERANTO@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Ross Younger <crazyscot@gmail.com> Co-authored-by: Veeck <github@veeck.de> Co-authored-by: Bugsounet - Cédric <github@bugsounet.fr> Co-authored-by: jkriegshauser <joshuakr@nvidia.com> Co-authored-by: illimarkangur <116028111+illimarkangur@users.noreply.github.com> Co-authored-by: sam detweiler <sdetweil@gmail.com> Co-authored-by: vppencilsharpener <tim.pray@gmail.com> Co-authored-by: veeck <michael.veeck@nebenan.de> Co-authored-by: Paranoid93 <6515818+Paranoid93@users.noreply.github.com> Co-authored-by: Brian O'Connor <btoconnor@users.noreply.github.com> Co-authored-by: WallysWellies <59727507+WallysWellies@users.noreply.github.com> Co-authored-by: Jason Stieber <jrstieber@gmail.com> Co-authored-by: jargordon <50050429+jargordon@users.noreply.github.com> Co-authored-by: Daniel <32464403+dkallen78@users.noreply.github.com> Co-authored-by: Ryan Williams <65094007+ryan-d-williams@users.noreply.github.com> Co-authored-by: Panagiotis Skias <panagiotis.skias@gmail.com> Co-authored-by: Marc Landis <dirk.rettschlag@gmail.com>
395 lines
12 KiB
JavaScript
395 lines
12 KiB
JavaScript
// Alias modules mentioned in package.js under _moduleAliases.
|
|
require("module-alias/register");
|
|
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const envsub = require("envsub");
|
|
const Log = require("logger");
|
|
|
|
const Server = require(`${__dirname}/server`);
|
|
const Utils = require(`${__dirname}/utils`);
|
|
const defaultModules = require(`${__dirname}/../modules/default/defaultmodules`);
|
|
const { getEnvVarsAsObj } = require(`${__dirname}/server_functions`);
|
|
|
|
// Get version number.
|
|
global.version = require(`${__dirname}/../package.json`).version;
|
|
Log.log(`Starting MagicMirror: v${global.version}`);
|
|
|
|
// Log system information.
|
|
Utils.logSystemInformation();
|
|
|
|
// global absolute root path
|
|
global.root_path = path.resolve(`${__dirname}/../`);
|
|
|
|
if (process.env.MM_CONFIG_FILE) {
|
|
global.configuration_file = process.env.MM_CONFIG_FILE.replace(`${global.root_path}/`, "");
|
|
}
|
|
|
|
// FIXME: Hotfix Pull Request
|
|
// https://github.com/MagicMirrorOrg/MagicMirror/pull/673
|
|
if (process.env.MM_PORT) {
|
|
global.mmPort = process.env.MM_PORT;
|
|
}
|
|
|
|
// The next part is here to prevent a major exception when there
|
|
// is no internet connection. This could probable be solved better.
|
|
process.on("uncaughtException", function (err) {
|
|
// ignore strange exceptions under aarch64 coming from systeminformation:
|
|
if (!err.stack.includes("node_modules/systeminformation")) {
|
|
Log.error("Whoops! There was an uncaught exception...");
|
|
Log.error(err);
|
|
Log.error("MagicMirror² will not quit, but it might be a good idea to check why this happened. Maybe no internet connection?");
|
|
Log.error("If you think this really is an issue, please open an issue on GitHub: https://github.com/MagicMirrorOrg/MagicMirror/issues");
|
|
}
|
|
});
|
|
|
|
/**
|
|
* The core app.
|
|
* @class
|
|
*/
|
|
function App () {
|
|
let nodeHelpers = [];
|
|
let httpServer;
|
|
|
|
/**
|
|
* Loads the config file. Combines it with the defaults and returns the config
|
|
* @async
|
|
* @returns {Promise<object>} the loaded config or the defaults if something goes wrong
|
|
*/
|
|
async function loadConfig () {
|
|
Log.log("Loading config ...");
|
|
const defaults = require(`${__dirname}/defaults`);
|
|
if (process.env.JEST_WORKER_ID !== undefined) {
|
|
// if we are running with jest
|
|
defaults.address = "0.0.0.0";
|
|
}
|
|
|
|
// For this check proposed to TestSuite
|
|
// https://forum.magicmirror.builders/topic/1456/test-suite-for-magicmirror/8
|
|
const configFilename = path.resolve(global.configuration_file || `${global.root_path}/config/config.js`);
|
|
let templateFile = `${configFilename}.template`;
|
|
|
|
// check if templateFile exists
|
|
try {
|
|
fs.accessSync(templateFile, fs.F_OK);
|
|
} catch (err) {
|
|
templateFile = null;
|
|
Log.log("config template file not exists, no envsubst");
|
|
}
|
|
|
|
if (templateFile) {
|
|
// save current config.js
|
|
try {
|
|
if (fs.existsSync(configFilename)) {
|
|
fs.copyFileSync(configFilename, `${configFilename}-old`);
|
|
}
|
|
} catch (err) {
|
|
Log.warn(`Could not copy ${configFilename}: ${err.message}`);
|
|
}
|
|
|
|
// check if config.env exists
|
|
const envFiles = [];
|
|
const configEnvFile = `${configFilename.substr(0, configFilename.lastIndexOf("."))}.env`;
|
|
try {
|
|
if (fs.existsSync(configEnvFile)) {
|
|
envFiles.push(configEnvFile);
|
|
}
|
|
} catch (err) {
|
|
Log.log(`${configEnvFile} does not exist. ${err.message}`);
|
|
}
|
|
|
|
let options = {
|
|
all: true,
|
|
diff: false,
|
|
envFiles: envFiles,
|
|
protect: false,
|
|
syntax: "default",
|
|
system: true
|
|
};
|
|
|
|
// envsubst variables in templateFile and create new config.js
|
|
// naming for envsub must be templateFile and outputFile
|
|
const outputFile = configFilename;
|
|
try {
|
|
await envsub({ templateFile, outputFile, options });
|
|
} catch (err) {
|
|
Log.error(`Could not envsubst variables: ${err.message}`);
|
|
}
|
|
}
|
|
|
|
require(`${global.root_path}/js/check_config.js`);
|
|
|
|
try {
|
|
fs.accessSync(configFilename, fs.F_OK);
|
|
const c = require(configFilename);
|
|
if (Object.keys(c).length === 0) {
|
|
Log.error("WARNING! Config file appears empty, maybe missing module.exports last line?");
|
|
}
|
|
checkDeprecatedOptions(c);
|
|
return Object.assign(defaults, c);
|
|
} catch (e) {
|
|
if (e.code === "ENOENT") {
|
|
Log.error("WARNING! Could not find config file. Please create one. Starting with default configuration.");
|
|
} else if (e instanceof ReferenceError || e instanceof SyntaxError) {
|
|
Log.error(`WARNING! Could not validate config file. Starting with default configuration. Please correct syntax errors at or above this line: ${e.stack}`);
|
|
} else {
|
|
Log.error(`WARNING! Could not load config file. Starting with default configuration. Error found: ${e}`);
|
|
}
|
|
}
|
|
|
|
return defaults;
|
|
}
|
|
|
|
/**
|
|
* Checks the config for deprecated options and throws a warning in the logs
|
|
* if it encounters one option from the deprecated.js list
|
|
* @param {object} userConfig The user config
|
|
*/
|
|
function checkDeprecatedOptions (userConfig) {
|
|
const deprecated = require(`${global.root_path}/js/deprecated`);
|
|
const deprecatedOptions = deprecated.configs;
|
|
|
|
const usedDeprecated = deprecatedOptions.filter((option) => userConfig.hasOwnProperty(option));
|
|
if (usedDeprecated.length > 0) {
|
|
Log.warn(`WARNING! Your config is using deprecated options: ${usedDeprecated.join(", ")}. Check README and CHANGELOG for more up-to-date ways of getting the same functionality.`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Loads a specific module.
|
|
* @param {string} module The name of the module (including subpath).
|
|
*/
|
|
function loadModule (module) {
|
|
const elements = module.split("/");
|
|
const moduleName = elements[elements.length - 1];
|
|
const env = getEnvVarsAsObj();
|
|
let moduleFolder = `${__dirname}/../${env.modulesDir}/${module}`;
|
|
|
|
if (defaultModules.includes(moduleName)) {
|
|
const defaultModuleFolder = `${__dirname}/../modules/default/${module}`;
|
|
if (process.env.JEST_WORKER_ID === undefined) {
|
|
moduleFolder = defaultModuleFolder;
|
|
} else {
|
|
// running in Jest, allow defaultModules placed under moduleDir for testing
|
|
if (env.modulesDir === "modules") {
|
|
moduleFolder = defaultModuleFolder;
|
|
}
|
|
}
|
|
}
|
|
|
|
const moduleFile = `${moduleFolder}/${module}.js`;
|
|
|
|
try {
|
|
fs.accessSync(moduleFile, fs.R_OK);
|
|
} catch (e) {
|
|
Log.warn(`No ${moduleFile} found for module: ${moduleName}.`);
|
|
}
|
|
|
|
const helperPath = `${moduleFolder}/node_helper.js`;
|
|
|
|
let loadHelper = true;
|
|
try {
|
|
fs.accessSync(helperPath, fs.R_OK);
|
|
} catch (e) {
|
|
loadHelper = false;
|
|
Log.log(`No helper found for module: ${moduleName}.`);
|
|
}
|
|
|
|
// if the helper was found
|
|
if (loadHelper) {
|
|
const Module = require(helperPath);
|
|
let m = new Module();
|
|
|
|
if (m.requiresVersion) {
|
|
Log.log(`Check MagicMirror² version for node helper '${moduleName}' - Minimum version: ${m.requiresVersion} - Current version: ${global.version}`);
|
|
if (cmpVersions(global.version, m.requiresVersion) >= 0) {
|
|
Log.log("Version is ok!");
|
|
} else {
|
|
Log.warn(`Version is incorrect. Skip module: '${moduleName}'`);
|
|
return;
|
|
}
|
|
}
|
|
|
|
m.setName(moduleName);
|
|
m.setPath(path.resolve(moduleFolder));
|
|
nodeHelpers.push(m);
|
|
|
|
m.loaded();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Loads all modules.
|
|
* @param {Module[]} modules All modules to be loaded
|
|
* @returns {Promise} A promise that is resolved when all modules been loaded
|
|
*/
|
|
async function loadModules (modules) {
|
|
Log.log("Loading module helpers ...");
|
|
|
|
for (let module of modules) {
|
|
await loadModule(module);
|
|
}
|
|
|
|
Log.log("All module helpers loaded.");
|
|
}
|
|
|
|
/**
|
|
* Compare two semantic version numbers and return the difference.
|
|
* @param {string} a Version number a.
|
|
* @param {string} b Version number b.
|
|
* @returns {number} A positive number if a is larger than b, a negative
|
|
* number if a is smaller and 0 if they are the same
|
|
*/
|
|
function cmpVersions (a, b) {
|
|
let i, diff;
|
|
const regExStrip0 = /(\.0+)+$/;
|
|
const segmentsA = a.replace(regExStrip0, "").split(".");
|
|
const segmentsB = b.replace(regExStrip0, "").split(".");
|
|
const l = Math.min(segmentsA.length, segmentsB.length);
|
|
|
|
for (i = 0; i < l; i++) {
|
|
diff = parseInt(segmentsA[i], 10) - parseInt(segmentsB[i], 10);
|
|
if (diff) {
|
|
return diff;
|
|
}
|
|
}
|
|
return segmentsA.length - segmentsB.length;
|
|
}
|
|
|
|
/**
|
|
* Start the core app.
|
|
*
|
|
* It loads the config, then it loads all modules.
|
|
* @async
|
|
* @returns {Promise<object>} the config used
|
|
*/
|
|
this.start = async function () {
|
|
config = await loadConfig();
|
|
|
|
Log.setLogLevel(config.logLevel);
|
|
|
|
// get the used module positions
|
|
Utils.getModulePositions();
|
|
|
|
let modules = [];
|
|
for (const module of config.modules) {
|
|
if (module.disabled) continue;
|
|
if (module.module) {
|
|
if (Utils.moduleHasValidPosition(module.position) || typeof (module.position) === "undefined") {
|
|
// Only add this module to be loaded if it is not a duplicate (repeated instance of the same module)
|
|
if (!modules.includes(module.module)) {
|
|
modules.push(module.module);
|
|
}
|
|
} else {
|
|
Log.warn("Invalid module position found for this configuration:" + `\n${JSON.stringify(module, null, 2)}`);
|
|
}
|
|
} else {
|
|
Log.warn("No module name found for this configuration:" + `\n${JSON.stringify(module, null, 2)}`);
|
|
}
|
|
}
|
|
|
|
await loadModules(modules);
|
|
|
|
httpServer = new Server(config);
|
|
const { app, io } = await httpServer.open();
|
|
Log.log("Server started ...");
|
|
|
|
const nodePromises = [];
|
|
for (let nodeHelper of nodeHelpers) {
|
|
nodeHelper.setExpressApp(app);
|
|
nodeHelper.setSocketIO(io);
|
|
|
|
try {
|
|
nodePromises.push(nodeHelper.start());
|
|
} catch (error) {
|
|
Log.error(`Error when starting node_helper for module ${nodeHelper.name}:`);
|
|
Log.error(error);
|
|
}
|
|
}
|
|
|
|
const results = await Promise.allSettled(nodePromises);
|
|
|
|
// Log errors that happened during async node_helper startup
|
|
results.forEach((result) => {
|
|
if (result.status === "rejected") {
|
|
Log.error(result.reason);
|
|
}
|
|
});
|
|
|
|
Log.log("Sockets connected & modules started ...");
|
|
|
|
return config;
|
|
};
|
|
|
|
/**
|
|
* Stops the core app. This calls each node_helper's STOP() function, if it
|
|
* exists.
|
|
*
|
|
* Added to fix #1056
|
|
* @returns {Promise} A promise that is resolved when all node_helpers and
|
|
* the http server has been closed
|
|
*/
|
|
this.stop = async function () {
|
|
const nodePromises = [];
|
|
for (let nodeHelper of nodeHelpers) {
|
|
try {
|
|
if (typeof nodeHelper.stop === "function") {
|
|
nodePromises.push(nodeHelper.stop());
|
|
}
|
|
} catch (error) {
|
|
Log.error(`Error when stopping node_helper for module ${nodeHelper.name}:`);
|
|
console.error(error);
|
|
}
|
|
}
|
|
|
|
const results = await Promise.allSettled(nodePromises);
|
|
|
|
// Log errors that happened during async node_helper stopping
|
|
results.forEach((result) => {
|
|
if (result.status === "rejected") {
|
|
Log.error(result.reason);
|
|
}
|
|
});
|
|
|
|
Log.log("Node_helpers stopped ...");
|
|
|
|
// To be able to stop the app even if it hasn't been started (when
|
|
// running with Electron against another server)
|
|
if (!httpServer) {
|
|
return Promise.resolve();
|
|
}
|
|
|
|
return httpServer.close();
|
|
};
|
|
|
|
/**
|
|
* Listen for SIGINT signal and call stop() function.
|
|
*
|
|
* Added to fix #1056
|
|
* Note: this is only used if running `server-only`. Otherwise
|
|
* this.stop() is called by app.on("before-quit"... in `electron.js`
|
|
*/
|
|
process.on("SIGINT", async () => {
|
|
Log.log("[SIGINT] Received. Shutting down server...");
|
|
setTimeout(() => {
|
|
process.exit(0);
|
|
}, 3000); // Force quit after 3 seconds
|
|
await this.stop();
|
|
process.exit(0);
|
|
});
|
|
|
|
/**
|
|
* Listen to SIGTERM signals so we can stop everything when we
|
|
* are asked to stop by the OS.
|
|
*/
|
|
process.on("SIGTERM", async () => {
|
|
Log.log("[SIGTERM] Received. Shutting down server...");
|
|
setTimeout(() => {
|
|
process.exit(0);
|
|
}, 3000); // Force quit after 3 seconds
|
|
await this.stop();
|
|
process.exit(0);
|
|
});
|
|
}
|
|
|
|
module.exports = new App();
|