Use template literals instead of string concatenation (#3066)

We have used it inconsistently till now. Template literals are more
modern and easier to maintain in my opinion.

Because that's a large amount of changes, here's a way to reproduce it:
I added the rule `"prefer-template": "error"` to the `.eslintrc.json`
and did an autofix. Since this caused a new problem in line 409 of
`newsfeed.js`, I reversed it in that line and also removed the rule from
the eslint config file.

The rule is described here:
https://eslint.org/docs/latest/rules/prefer-template

Note: I've played around with some other linter rules as well, and some
seem to point to some specific, non-cosmetic, issues. But before I dive
even deeper and then introduce even bigger and hardly understandable
changes at once, I thought I'd start with this simple cosmetic rule.
This commit is contained in:
Kristjan ESPERANTO 2023-03-19 14:32:23 +01:00 committed by GitHub
parent 8f8945d418
commit d276a7ddb9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 222 additions and 237 deletions

View File

@ -22,10 +22,10 @@
}
},
"rules": {
"prettier/prettier": "error",
"eqeqeq": "error",
"no-prototype-builtins": "off",
"no-unused-vars": "off",
"no-useless-return": "error"
"no-useless-return": "error",
"prefer-template": "error"
}
}

View File

@ -55,6 +55,7 @@ _This release is scheduled to be released on 2023-04-01._
- Fix wrong vertical alignment of calendar title column when wrapEvents is true (#3053)
- Fix empty news feed stopping the reload forever
- Fix e2e tests (failed after async changes) by running calendar and newsfeed tests last
- Lint: Use template literals instead of string concatenation
- Fix default alert module to render HTML for title and message
## [2.22.0] - 2023-01-01

View File

@ -18,7 +18,7 @@ const envsub = require("envsub");
// Get version number.
global.version = require(`${__dirname}/../package.json`).version;
Log.log("Starting MagicMirror: v" + global.version);
Log.log(`Starting MagicMirror: v${global.version}`);
// global absolute root path
global.root_path = path.resolve(`${__dirname}/../`);
@ -64,7 +64,7 @@ function App() {
// 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";
let templateFile = `${configFilename}.template`;
// check if templateFile exists
try {
@ -78,21 +78,21 @@ function App() {
// save current config.js
try {
if (fs.existsSync(configFilename)) {
fs.copyFileSync(configFilename, configFilename + "_" + Date.now());
fs.copyFileSync(configFilename, `${configFilename}_${Date.now()}`);
}
} catch (err) {
Log.warn("Could not copy " + configFilename + ": " + err.message);
Log.warn(`Could not copy ${configFilename}: ${err.message}`);
}
// check if config.env exists
const envFiles = [];
const configEnvFile = configFilename.substr(0, configFilename.lastIndexOf(".")) + ".env";
const configEnvFile = `${configFilename.substr(0, configFilename.lastIndexOf("."))}.env`;
try {
if (fs.existsSync(configEnvFile)) {
envFiles.push(configEnvFile);
}
} catch (err) {
Log.debug(configEnvFile + " does not exist. " + err.message);
Log.debug(`${configEnvFile} does not exist. ${err.message}`);
}
let options = {
@ -110,7 +110,7 @@ function App() {
try {
await envsub({ templateFile, outputFile, options });
} catch (err) {
Log.error("Could not envsubst variables: " + err.message);
Log.error(`Could not envsubst variables: ${err.message}`);
}
}

View File

@ -44,7 +44,7 @@ const Loader = (function () {
// Starting modules also hides any modules that have requested to be initially hidden
for (const thisModule of moduleObjects) {
if (thisModule.data.hiddenOnStartup) {
Log.info("Initially hiding " + thisModule.name);
Log.info(`Initially hiding ${thisModule.name}`);
thisModule.hide();
}
}
@ -73,10 +73,10 @@ const Loader = (function () {
const elements = module.split("/");
const moduleName = elements[elements.length - 1];
let moduleFolder = config.paths.modules + "/" + module;
let moduleFolder = `${config.paths.modules}/${module}`;
if (defaultModules.indexOf(moduleName) !== -1) {
moduleFolder = config.paths.modules + "/default/" + module;
moduleFolder = `${config.paths.modules}/default/${module}`;
}
if (moduleData.disabled === true) {
@ -85,16 +85,16 @@ const Loader = (function () {
moduleFiles.push({
index: index,
identifier: "module_" + index + "_" + module,
identifier: `module_${index}_${module}`,
name: moduleName,
path: moduleFolder + "/",
file: moduleName + ".js",
path: `${moduleFolder}/`,
file: `${moduleName}.js`,
position: moduleData.position,
hiddenOnStartup: moduleData.hiddenOnStartup,
header: moduleData.header,
configDeepMerge: typeof moduleData.configDeepMerge === "boolean" ? moduleData.configDeepMerge : false,
config: moduleData.config,
classes: typeof moduleData.classes !== "undefined" ? moduleData.classes + " " + module : module
classes: typeof moduleData.classes !== "undefined" ? `${moduleData.classes} ${module}` : module
});
});
@ -136,17 +136,17 @@ const Loader = (function () {
* @param {Module} mObj Modules instance.
*/
const bootstrapModule = async function (module, mObj) {
Log.info("Bootstrapping module: " + module.name);
Log.info(`Bootstrapping module: ${module.name}`);
mObj.setData(module);
await mObj.loadScripts();
Log.log("Scripts loaded for: " + module.name);
Log.log(`Scripts loaded for: ${module.name}`);
await mObj.loadStyles();
Log.log("Styles loaded for: " + module.name);
Log.log(`Styles loaded for: ${module.name}`);
await mObj.loadTranslations();
Log.log("Translations loaded for: " + module.name);
Log.log(`Translations loaded for: ${module.name}`);
moduleObjects.push(mObj);
};
@ -164,7 +164,7 @@ const Loader = (function () {
switch (extension.toLowerCase()) {
case "js":
return new Promise((resolve) => {
Log.log("Load script: " + fileName);
Log.log(`Load script: ${fileName}`);
script = document.createElement("script");
script.type = "text/javascript";
script.src = fileName;
@ -179,7 +179,7 @@ const Loader = (function () {
});
case "css":
return new Promise((resolve) => {
Log.log("Load stylesheet: " + fileName);
Log.log(`Load stylesheet: ${fileName}`);
stylesheet = document.createElement("link");
stylesheet.rel = "stylesheet";
@ -236,7 +236,7 @@ const Loader = (function () {
*/
loadFileForModule: async function (fileName, module) {
if (loadedFiles.indexOf(fileName.toLowerCase()) !== -1) {
Log.log("File already loaded: " + fileName);
Log.log(`File already loaded: ${fileName}`);
return;
}
@ -251,7 +251,7 @@ const Loader = (function () {
// This file is available in the vendor folder.
// Load it from this vendor folder.
loadedFiles.push(fileName.toLowerCase());
return loadFile(config.paths.vendor + "/" + vendor[fileName]);
return loadFile(`${config.paths.vendor}/${vendor[fileName]}`);
}
// File not loaded yet.

View File

@ -29,7 +29,7 @@ const MM = (function () {
dom.className = module.name;
if (typeof module.data.classes === "string") {
dom.className = "module " + dom.className + " " + module.data.classes;
dom.className = `module ${dom.className} ${module.data.classes}`;
}
dom.opacity = 0;
@ -243,7 +243,7 @@ const MM = (function () {
const moduleWrapper = document.getElementById(module.identifier);
if (moduleWrapper !== null) {
moduleWrapper.style.transition = "opacity " + speed / 1000 + "s";
moduleWrapper.style.transition = `opacity ${speed / 1000}s`;
moduleWrapper.style.opacity = 0;
moduleWrapper.classList.add("hidden");
@ -291,7 +291,7 @@ const MM = (function () {
// Check if there are no more lockstrings set, or the force option is set.
// Otherwise cancel show action.
if (module.lockStrings.length !== 0 && options.force !== true) {
Log.log("Will not show " + module.name + ". LockStrings active: " + module.lockStrings.join(","));
Log.log(`Will not show ${module.name}. LockStrings active: ${module.lockStrings.join(",")}`);
if (typeof options.onError === "function") {
options.onError(new Error("LOCK_STRING_ACTIVE"));
}
@ -302,13 +302,13 @@ const MM = (function () {
// If forced show, clean current lockstrings.
if (module.lockStrings.length !== 0 && options.force === true) {
Log.log("Force show of module: " + module.name);
Log.log(`Force show of module: ${module.name}`);
module.lockStrings = [];
}
const moduleWrapper = document.getElementById(module.identifier);
if (moduleWrapper !== null) {
moduleWrapper.style.transition = "opacity " + speed / 1000 + "s";
moduleWrapper.style.transition = `opacity ${speed / 1000}s`;
// Restore the position. See hideModule() for more info.
moduleWrapper.style.position = "static";
moduleWrapper.classList.remove("hidden");

View File

@ -41,7 +41,7 @@ const Module = Class.extend({
* Called when the module is started.
*/
start: async function () {
Log.info("Starting module: " + this.name);
Log.info(`Starting module: ${this.name}`);
},
/**
@ -127,7 +127,7 @@ const Module = Class.extend({
* @returns {string} The template string of filename.
*/
getTemplate: function () {
return '<div class="normal">' + this.name + '</div><div class="small dimmed">' + this.identifier + "</div>";
return `<div class="normal">${this.name}</div><div class="small dimmed">${this.identifier}</div>`;
},
/**
@ -185,21 +185,21 @@ const Module = Class.extend({
* @param {*} payload The payload of the notification.
*/
socketNotificationReceived: function (notification, payload) {
Log.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload);
Log.log(`${this.name} received a socket notification: ${notification} - Payload: ${payload}`);
},
/**
* Called when the module is hidden.
*/
suspend: function () {
Log.log(this.name + " is suspended.");
Log.log(`${this.name} is suspended.`);
},
/**
* Called when the module is shown.
*/
resume: function () {
Log.log(this.name + " is resumed.");
Log.log(`${this.name} is resumed.`);
},
/*********************************************
@ -255,7 +255,7 @@ const Module = Class.extend({
* @returns {string} the file path
*/
file: function (file) {
return (this.data.path + "/" + file).replace("//", "/");
return `${this.data.path}/${file}`.replace("//", "/");
},
/**
@ -491,15 +491,15 @@ Module.create = function (name) {
Module.register = function (name, moduleDefinition) {
if (moduleDefinition.requiresVersion) {
Log.log("Check MagicMirror² version for module '" + name + "' - Minimum version: " + moduleDefinition.requiresVersion + " - Current version: " + window.mmVersion);
Log.log(`Check MagicMirror² version for module '${name}' - Minimum version: ${moduleDefinition.requiresVersion} - Current version: ${window.mmVersion}`);
if (cmpVersions(window.mmVersion, moduleDefinition.requiresVersion) >= 0) {
Log.log("Version is ok!");
} else {
Log.warn("Version is incorrect. Skip module: '" + name + "'");
Log.warn(`Version is incorrect. Skip module: '${name}'`);
return;
}
}
Log.log("Module registered: " + name);
Log.log(`Module registered: ${name}`);
Module.definitions[name] = moduleDefinition;
};

View File

@ -30,7 +30,7 @@ async function cors(req, res) {
const match = new RegExp(urlRegEx, "g").exec(req.url);
if (!match) {
url = "invalid url: " + req.url;
url = `invalid url: ${req.url}`;
Log.error(url);
res.send(url);
} else {
@ -39,7 +39,7 @@ async function cors(req, res) {
const headersToSend = getHeadersToSend(req.url);
const expectedRecievedHeaders = geExpectedRecievedHeaders(req.url);
Log.log("cors url: " + url);
Log.log(`cors url: ${url}`);
const response = await fetch(url, { headers: headersToSend });
for (const header of expectedRecievedHeaders) {
@ -62,7 +62,7 @@ async function cors(req, res) {
* @returns {object} An object specifying name and value of the headers.
*/
function getHeadersToSend(url) {
const headersToSend = { "User-Agent": "Mozilla/5.0 MagicMirror/" + global.version };
const headersToSend = { "User-Agent": `Mozilla/5.0 MagicMirror/${global.version}` };
const headersToSendMatch = new RegExp("sendheaders=(.+?)(&|$)", "g").exec(url);
if (headersToSendMatch) {
const headers = headersToSendMatch[1].split(",");

View File

@ -18,8 +18,8 @@ const MMSocket = function (moduleName) {
if (typeof config !== "undefined" && typeof config.basePath !== "undefined") {
base = config.basePath;
}
this.socket = io("/" + this.moduleName, {
path: base + "socket.io"
this.socket = io(`/${this.moduleName}`, {
path: `${base}socket.io`
});
let notificationCallback = function () {};

View File

@ -26,7 +26,7 @@ const Translator = (function () {
fileinfo = JSON.parse(xhr.responseText);
} catch (exception) {
// nothing here, but don't die
Log.error(" loading json file =" + file + " failed");
Log.error(` loading json file =${file} failed`);
}
resolve(fileinfo);
}
@ -70,7 +70,7 @@ const Translator = (function () {
template = variables.fallback;
}
return template.replace(new RegExp("{([^}]+)}", "g"), function (_unused, varName) {
return varName in variables ? variables[varName] : "{" + varName + "}";
return varName in variables ? variables[varName] : `{${varName}}`;
});
}
@ -123,7 +123,7 @@ const Translator = (function () {
*/
loadCoreTranslations: async function (lang) {
if (lang in translations) {
Log.log("Loading core translation file: " + translations[lang]);
Log.log(`Loading core translation file: ${translations[lang]}`);
this.coreTranslations = await loadJSON(translations[lang]);
} else {
Log.log("Configured language not found in core translations.");
@ -139,7 +139,7 @@ const Translator = (function () {
loadCoreTranslationsFallback: async function () {
let first = Object.keys(translations)[0];
if (first) {
Log.log("Loading core translation fallback file: " + translations[first]);
Log.log(`Loading core translation fallback file: ${translations[first]}`);
this.coreTranslationsFallback = await loadJSON(translations[first]);
}
}

View File

@ -80,7 +80,7 @@
NotificationFx.prototype._init = function () {
// create HTML structure
this.ntf = document.createElement("div");
this.ntf.className = this.options.al_no + " ns-" + this.options.layout + " ns-effect-" + this.options.effect + " ns-type-" + this.options.type;
this.ntf.className = `${this.options.al_no} ns-${this.options.layout} ns-effect-${this.options.effect} ns-type-${this.options.type}`;
let strinner = '<div class="ns-box-inner">';
strinner += this.options.message;
strinner += "</div>";

View File

@ -94,7 +94,7 @@ Module.register("calendar", {
start: function () {
const ONE_MINUTE = 60 * 1000;
Log.info("Starting module: " + this.name);
Log.info(`Starting module: ${this.name}`);
if (this.config.colored) {
Log.warn("Your are using the deprecated config values 'colored'. Please switch to 'coloredSymbol' & 'coloredText'!");
@ -203,13 +203,13 @@ Module.register("calendar", {
if (this.error) {
wrapper.innerHTML = this.error;
wrapper.className = this.config.tableClass + " dimmed";
wrapper.className = `${this.config.tableClass} dimmed`;
return wrapper;
}
if (events.length === 0) {
wrapper.innerHTML = this.loaded ? this.translate("EMPTY") : this.translate("LOADING");
wrapper.className = this.config.tableClass + " dimmed";
wrapper.className = `${this.config.tableClass} dimmed`;
return wrapper;
}
@ -259,7 +259,7 @@ Module.register("calendar", {
const eventWrapper = document.createElement("tr");
if (this.config.coloredText) {
eventWrapper.style.cssText = "color:" + this.colorForUrl(event.url, false);
eventWrapper.style.cssText = `color:${this.colorForUrl(event.url, false)}`;
}
if (this.config.coloredBackground) {
@ -281,11 +281,11 @@ Module.register("calendar", {
if (this.config.displaySymbol) {
if (this.config.coloredSymbol) {
symbolWrapper.style.cssText = "color:" + this.colorForUrl(event.url, false);
symbolWrapper.style.cssText = `color:${this.colorForUrl(event.url, false)}`;
}
const symbolClass = this.symbolClassForUrl(event.url);
symbolWrapper.className = "symbol align-right " + symbolClass;
symbolWrapper.className = `symbol align-right ${symbolClass}`;
const symbols = this.symbolsForEvent(event);
symbols.forEach((s, index) => {
@ -313,7 +313,7 @@ Module.register("calendar", {
const thisYear = new Date(parseInt(event.startDate)).getFullYear(),
yearDiff = thisYear - event.firstYear;
repeatingCountTitle = ", " + yearDiff + ". " + repeatingCountTitle;
repeatingCountTitle = `, ${yearDiff}. ${repeatingCountTitle}`;
}
}
@ -325,11 +325,11 @@ Module.register("calendar", {
if (needle.test(event.title)) {
// Respect parameter ColoredSymbolOnly also for custom events
if (this.config.coloredText) {
eventWrapper.style.cssText = "color:" + this.config.customEvents[ev].color;
titleWrapper.style.cssText = "color:" + this.config.customEvents[ev].color;
eventWrapper.style.cssText = `color:${this.config.customEvents[ev].color}`;
titleWrapper.style.cssText = `color:${this.config.customEvents[ev].color}`;
}
if (this.config.displaySymbol && this.config.coloredSymbol) {
symbolWrapper.style.cssText = "color:" + this.config.customEvents[ev].color;
symbolWrapper.style.cssText = `color:${this.config.customEvents[ev].color}`;
}
break;
}
@ -342,9 +342,9 @@ Module.register("calendar", {
const titleClass = this.titleClassForUrl(event.url);
if (!this.config.coloredText) {
titleWrapper.className = "title bright " + titleClass;
titleWrapper.className = `title bright ${titleClass}`;
} else {
titleWrapper.className = "title " + titleClass;
titleWrapper.className = `title ${titleClass}`;
}
if (this.config.timeFormat === "dateheaders") {
@ -355,14 +355,14 @@ Module.register("calendar", {
titleWrapper.classList.add("align-left");
} else {
const timeWrapper = document.createElement("td");
timeWrapper.className = "time light " + (this.config.flipDateHeaderTitle ? "align-right " : "align-left ") + this.timeClassForUrl(event.url);
timeWrapper.className = `time light ${this.config.flipDateHeaderTitle ? "align-right " : "align-left "}${this.timeClassForUrl(event.url)}`;
timeWrapper.style.paddingLeft = "2px";
timeWrapper.style.textAlign = this.config.flipDateHeaderTitle ? "right" : "left";
timeWrapper.innerHTML = moment(event.startDate, "x").format("LT");
// Add endDate to dataheaders if showEnd is enabled
if (this.config.showEnd) {
timeWrapper.innerHTML += " - " + this.capFirst(moment(event.endDate, "x").format("LT"));
timeWrapper.innerHTML += ` - ${this.capFirst(moment(event.endDate, "x").format("LT"))}`;
}
eventWrapper.appendChild(timeWrapper);
@ -393,7 +393,7 @@ Module.register("calendar", {
// Ongoing and getRelative is set
timeWrapper.innerHTML = this.capFirst(
this.translate("RUNNING", {
fallback: this.translate("RUNNING") + " {timeUntilEnd}",
fallback: `${this.translate("RUNNING")} {timeUntilEnd}`,
timeUntilEnd: moment(event.endDate, "x").fromNow(true)
})
);
@ -424,8 +424,8 @@ Module.register("calendar", {
} else {
timeWrapper.innerHTML = this.capFirst(
moment(event.startDate, "x").calendar(null, {
sameDay: this.config.showTimeToday ? "LT" : "[" + this.translate("TODAY") + "]",
nextDay: "[" + this.translate("TOMORROW") + "]",
sameDay: this.config.showTimeToday ? "LT" : `[${this.translate("TODAY")}]`,
nextDay: `[${this.translate("TOMORROW")}]`,
nextWeek: "dddd",
sameElse: event.fullDayEvent ? this.config.fullDayEventDateFormat : this.config.dateFormat
})
@ -456,13 +456,13 @@ Module.register("calendar", {
// Ongoing event
timeWrapper.innerHTML = this.capFirst(
this.translate("RUNNING", {
fallback: this.translate("RUNNING") + " {timeUntilEnd}",
fallback: `${this.translate("RUNNING")} {timeUntilEnd}`,
timeUntilEnd: moment(event.endDate, "x").fromNow(true)
})
);
}
}
timeWrapper.className = "time light " + this.timeClassForUrl(event.url);
timeWrapper.className = `time light ${this.timeClassForUrl(event.url)}`;
eventWrapper.appendChild(timeWrapper);
}
@ -489,7 +489,7 @@ Module.register("calendar", {
}
if (this.config.coloredText) {
locationRow.style.cssText = "color:" + this.colorForUrl(event.url, false);
locationRow.style.cssText = `color:${this.colorForUrl(event.url, false)}`;
}
if (this.config.coloredBackground) {
@ -619,7 +619,7 @@ Module.register("calendar", {
thisEvent.today = thisEvent.startDate >= today && thisEvent.startDate < today + ONE_DAY;
thisEvent.tomorrow = !thisEvent.today && thisEvent.startDate >= today + ONE_DAY && thisEvent.startDate < today + 2 * ONE_DAY;
thisEvent.endDate = midnight;
thisEvent.title += " (" + count + "/" + maxCount + ")";
thisEvent.title += ` (${count}/${maxCount})`;
splitEvents.push(thisEvent);
event.startDate = midnight;
@ -627,7 +627,7 @@ Module.register("calendar", {
midnight = moment(midnight, "x").add(1, "day").format("x"); // next day
}
// Last day
event.title += " (" + count + "/" + maxCount + ")";
event.title += ` (${count}/${maxCount})`;
event.today += event.startDate >= today && event.startDate < today + ONE_DAY;
event.tomorrow = !event.today && event.startDate >= today + ONE_DAY && event.startDate < today + 2 * ONE_DAY;
splitEvents.push(event);
@ -894,7 +894,7 @@ Module.register("calendar", {
const word = words[i];
if (currentLine.length + word.length < (typeof maxLength === "number" ? maxLength : 25) - 1) {
// max - 1 to account for a space
currentLine += word + " ";
currentLine += `${word} `;
} else {
line++;
if (line > maxTitleLines - 1) {
@ -905,9 +905,9 @@ Module.register("calendar", {
}
if (currentLine.length > 0) {
temp += currentLine + "<br>" + word + " ";
temp += `${currentLine}<br>${word} `;
} else {
temp += word + "<br>";
temp += `${word}<br>`;
}
currentLine = "";
}
@ -916,7 +916,7 @@ Module.register("calendar", {
return (temp + currentLine).trim();
} else {
if (maxLength && typeof maxLength === "number" && string.length > maxLength) {
return string.trim().slice(0, maxLength) + "…";
return `${string.trim().slice(0, maxLength)}`;
} else {
return string.trim();
}

View File

@ -41,7 +41,7 @@ const CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEn
let fetcher = null;
let httpsAgent = null;
let headers = {
"User-Agent": "Mozilla/5.0 (Node.js " + nodeVersion + ") MagicMirror/" + global.version
"User-Agent": `Mozilla/5.0 (Node.js ${nodeVersion}) MagicMirror/${global.version}`
};
if (selfSignedCert) {
@ -51,11 +51,11 @@ const CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEn
}
if (auth) {
if (auth.method === "bearer") {
headers.Authorization = "Bearer " + auth.pass;
headers.Authorization = `Bearer ${auth.pass}`;
} else if (auth.method === "digest") {
fetcher = new digest(auth.user, auth.pass).fetch(url, { headers: headers, agent: httpsAgent });
} else {
headers.Authorization = "Basic " + Buffer.from(auth.user + ":" + auth.pass).toString("base64");
headers.Authorization = `Basic ${Buffer.from(`${auth.user}:${auth.pass}`).toString("base64")}`;
}
}
if (fetcher === null) {
@ -70,7 +70,7 @@ const CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEn
try {
data = ical.parseICS(responseData);
Log.debug("parsed data=" + JSON.stringify(data));
Log.debug(`parsed data=${JSON.stringify(data)}`);
events = CalendarUtils.filterEvents(data, {
excludedEvents,
includePastEvents,
@ -114,7 +114,7 @@ const CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEn
* Broadcast the existing events.
*/
this.broadcastEvents = function () {
Log.info("Calendar-Fetcher: Broadcasting " + events.length + " events.");
Log.info(`Calendar-Fetcher: Broadcasting ${events.length} events.`);
eventsReceivedCallback(this);
};

View File

@ -29,7 +29,7 @@ const CalendarUtils = {
Log.debug(" if no tz, guess based on now");
event.start.tz = moment.tz.guess();
}
Log.debug("initial tz=" + event.start.tz);
Log.debug(`initial tz=${event.start.tz}`);
// if there is a start date specified
if (event.start.tz) {
@ -37,7 +37,7 @@ const CalendarUtils = {
if (event.start.tz.includes(" ")) {
// use the lookup table to get theIANA name as moment and date don't know MS timezones
let tz = CalendarUtils.getIanaTZFromMS(event.start.tz);
Log.debug("corrected TZ=" + tz);
Log.debug(`corrected TZ=${tz}`);
// watch out for unregistered windows timezone names
// if we had a successful lookup
if (tz) {
@ -46,7 +46,7 @@ const CalendarUtils = {
// Log.debug("corrected timezone="+event.start.tz)
}
}
Log.debug("corrected tz=" + event.start.tz);
Log.debug(`corrected tz=${event.start.tz}`);
let current_offset = 0; // offset from TZ string or calculated
let mm = 0; // date with tz or offset
let start_offset = 0; // utc offset of created with tz
@ -57,18 +57,18 @@ const CalendarUtils = {
let start_offset = parseInt(start_offsetString[0]);
start_offset *= event.start.tz[1] === "-" ? -1 : 1;
adjustHours = start_offset;
Log.debug("defined offset=" + start_offset + " hours");
Log.debug(`defined offset=${start_offset} hours`);
current_offset = start_offset;
event.start.tz = "";
Log.debug("ical offset=" + current_offset + " date=" + date);
Log.debug(`ical offset=${current_offset} date=${date}`);
mm = moment(date);
let x = parseInt(moment(new Date()).utcOffset());
Log.debug("net mins=" + (current_offset * 60 - x));
Log.debug(`net mins=${current_offset * 60 - x}`);
mm = mm.add(x - current_offset * 60, "minutes");
adjustHours = (current_offset * 60 - x) / 60;
event.start = mm.toDate();
Log.debug("adjusted date=" + event.start);
Log.debug(`adjusted date=${event.start}`);
} else {
// get the start time in that timezone
let es = moment(event.start);
@ -76,18 +76,18 @@ const CalendarUtils = {
if (es.format("YYYY") < 2007) {
es.set("year", 2013); // if so, use a closer date
}
Log.debug("start date/time=" + es.toDate());
Log.debug(`start date/time=${es.toDate()}`);
start_offset = moment.tz(es, event.start.tz).utcOffset();
Log.debug("start offset=" + start_offset);
Log.debug(`start offset=${start_offset}`);
Log.debug("start date/time w tz =" + moment.tz(moment(event.start), event.start.tz).toDate());
Log.debug(`start date/time w tz =${moment.tz(moment(event.start), event.start.tz).toDate()}`);
// get the specified date in that timezone
mm = moment.tz(moment(date), event.start.tz);
Log.debug("event date=" + mm.toDate());
Log.debug(`event date=${mm.toDate()}`);
current_offset = mm.utcOffset();
}
Log.debug("event offset=" + current_offset + " hour=" + mm.format("H") + " event date=" + mm.toDate());
Log.debug(`event offset=${current_offset} hour=${mm.format("H")} event date=${mm.toDate()}`);
// if the offset is greater than 0, east of london
if (current_offset !== start_offset) {
@ -113,7 +113,7 @@ const CalendarUtils = {
}
}
}
Log.debug("adjustHours=" + adjustHours);
Log.debug(`adjustHours=${adjustHours}`);
return adjustHours;
},
@ -138,7 +138,7 @@ const CalendarUtils = {
return CalendarUtils.isFullDayEvent(event) ? moment(event[time], "YYYYMMDD") : moment(new Date(event[time]));
};
Log.debug("There are " + Object.entries(data).length + " calendar entries.");
Log.debug(`There are ${Object.entries(data).length} calendar entries.`);
Object.entries(data).forEach(([key, event]) => {
Log.debug("Processing entry...");
const now = new Date();
@ -160,7 +160,7 @@ const CalendarUtils = {
}
if (event.type === "VEVENT") {
Log.debug("Event:\n" + JSON.stringify(event));
Log.debug(`Event:\n${JSON.stringify(event)}`);
let startDate = eventDate(event, "start");
let endDate;
@ -177,12 +177,12 @@ const CalendarUtils = {
}
}
Log.debug("start: " + startDate.toDate());
Log.debug("end:: " + endDate.toDate());
Log.debug(`start: ${startDate.toDate()}`);
Log.debug(`end:: ${endDate.toDate()}`);
// Calculate the duration of the event for use with recurring events.
let duration = parseInt(endDate.format("x")) - parseInt(startDate.format("x"));
Log.debug("duration: " + duration);
Log.debug(`duration: ${duration}`);
// FIXME: Since the parsed json object from node-ical comes with time information
// this check could be removed (?)
@ -191,7 +191,7 @@ const CalendarUtils = {
}
const title = CalendarUtils.getTitleFromEvent(event);
Log.debug("title: " + title);
Log.debug(`title: ${title}`);
let excluded = false,
dateFilter = null;
@ -271,8 +271,8 @@ const CalendarUtils = {
pastLocal = pastMoment.toDate();
futureLocal = futureMoment.toDate();
Log.debug("pastLocal: " + pastLocal);
Log.debug("futureLocal: " + futureLocal);
Log.debug(`pastLocal: ${pastLocal}`);
Log.debug(`futureLocal: ${futureLocal}`);
} else {
// if we want past events
if (config.includePastEvents) {
@ -284,9 +284,9 @@ const CalendarUtils = {
}
futureLocal = futureMoment.toDate(); // future
}
Log.debug("Search for recurring events between: " + pastLocal + " and " + futureLocal);
Log.debug(`Search for recurring events between: ${pastLocal} and ${futureLocal}`);
const dates = rule.between(pastLocal, futureLocal, true, limitFunction);
Log.debug("Title: " + event.summary + ", with dates: " + JSON.stringify(dates));
Log.debug(`Title: ${event.summary}, with dates: ${JSON.stringify(dates)}`);
// The "dates" array contains the set of dates within our desired date range range that are valid
// for the recurrence rule. *However*, it's possible for us to have a specific recurrence that
// had its date changed from outside the range to inside the range. For the time being,
@ -294,7 +294,7 @@ const CalendarUtils = {
// because the logic below will filter out any recurrences that don't actually belong within
// our display range.
// Would be great if there was a better way to handle this.
Log.debug("event.recurrences: " + event.recurrences);
Log.debug(`event.recurrences: ${event.recurrences}`);
if (event.recurrences !== undefined) {
for (let r in event.recurrences) {
// Only add dates that weren't already in the range we added from the rrule so that
@ -323,10 +323,10 @@ const CalendarUtils = {
let dateoffset = date.getTimezoneOffset();
// Reduce the time by the following offset.
Log.debug(" recurring date is " + date + " offset is " + dateoffset);
Log.debug(` recurring date is ${date} offset is ${dateoffset}`);
let dh = moment(date).format("HH");
Log.debug(" recurring date is " + date + " offset is " + dateoffset / 60 + " Hour is " + dh);
Log.debug(` recurring date is ${date} offset is ${dateoffset / 60} Hour is ${dh}`);
if (CalendarUtils.isFullDayEvent(event)) {
Log.debug("Fullday");
@ -342,7 +342,7 @@ const CalendarUtils = {
// the duration was calculated way back at the top before we could correct the start time..
// fix it for this event entry
//duration = 24 * 60 * 60 * 1000;
Log.debug("new recurring date1 fulldate is " + date);
Log.debug(`new recurring date1 fulldate is ${date}`);
}
} else {
// if the timezones are the same, correct date if needed
@ -357,7 +357,7 @@ const CalendarUtils = {
// the duration was calculated way back at the top before we could correct the start time..
// fix it for this event entry
//duration = 24 * 60 * 60 * 1000;
Log.debug("new recurring date2 fulldate is " + date);
Log.debug(`new recurring date2 fulldate is ${date}`);
}
//}
}
@ -376,7 +376,7 @@ const CalendarUtils = {
// the duration was calculated way back at the top before we could correct the start time..
// fix it for this event entry
//duration = 24 * 60 * 60 * 1000;
Log.debug("new recurring date1 is " + date);
Log.debug(`new recurring date1 is ${date}`);
}
} else {
// if the timezones are the same, correct date if needed
@ -391,13 +391,13 @@ const CalendarUtils = {
// the duration was calculated way back at the top before we could correct the start time..
// fix it for this event entry
//duration = 24 * 60 * 60 * 1000;
Log.debug("new recurring date2 is " + date);
Log.debug(`new recurring date2 is ${date}`);
}
//}
}
}
startDate = moment(date);
Log.debug("Corrected startDate: " + startDate.toDate());
Log.debug(`Corrected startDate: ${startDate.toDate()}`);
let adjustDays = CalendarUtils.calculateTimezoneAdjustment(event, date);
@ -413,7 +413,7 @@ const CalendarUtils = {
// This date is an exception date, which means we should skip it in the recurrence pattern.
showRecurrence = false;
}
Log.debug("duration: " + duration);
Log.debug(`duration: ${duration}`);
endDate = moment(parseInt(startDate.format("x")) + duration, "x");
if (startDate.format("x") === endDate.format("x")) {
@ -433,7 +433,7 @@ const CalendarUtils = {
}
if (showRecurrence === true) {
Log.debug("saving event: " + description);
Log.debug(`saving event: ${description}`);
addedEvents++;
newEvents.push({
title: recurrenceTitle,
@ -573,7 +573,7 @@ const CalendarUtils = {
if (filter) {
const until = filter.split(" "),
value = parseInt(until[0]),
increment = until[1].slice(-1) === "s" ? until[1] : until[1] + "s", // Massage the data for moment js
increment = until[1].slice(-1) === "s" ? until[1] : `${until[1]}s`, // Massage the data for moment js
filterUntil = moment(endDate.format()).subtract(value, increment);
return now < filterUntil.format("x");

View File

@ -11,7 +11,7 @@ const Log = require("logger");
module.exports = NodeHelper.create({
// Override start method.
start: function () {
Log.log("Starting node helper for: " + this.name);
Log.log(`Starting node helper for: ${this.name}`);
this.fetchers = [];
},
@ -55,7 +55,7 @@ module.exports = NodeHelper.create({
let fetcher;
if (typeof this.fetchers[identifier + url] === "undefined") {
Log.log("Create new calendarfetcher for url: " + url + " - Interval: " + fetchInterval);
Log.log(`Create new calendarfetcher for url: ${url} - Interval: ${fetchInterval}`);
fetcher = new CalendarFetcher(url, fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth, broadcastPastEvents, selfSignedCert);
fetcher.onReceive((fetcher) => {
@ -73,7 +73,7 @@ module.exports = NodeHelper.create({
this.fetchers[identifier + url] = fetcher;
} else {
Log.log("Use existing calendarfetcher for url: " + url);
Log.log(`Use existing calendarfetcher for url: ${url}`);
fetcher = this.fetchers[identifier + url];
fetcher.broadcastEvents();
}

View File

@ -45,7 +45,7 @@ Module.register("clock", {
},
// Define start sequence.
start: function () {
Log.info("Starting module: " + this.name);
Log.info(`Starting module: ${this.name}`);
// Schedule update interval.
this.second = moment().second();
@ -137,9 +137,9 @@ Module.register("clock", {
}
if (this.config.clockBold) {
timeString = now.format(hourSymbol + '[<span class="bold">]mm[</span>]');
timeString = now.format(`${hourSymbol}[<span class="bold">]mm[</span>]`);
} else {
timeString = now.format(hourSymbol + ":mm");
timeString = now.format(`${hourSymbol}:mm`);
}
if (this.config.showDate) {
@ -172,7 +172,7 @@ Module.register("clock", {
* @returns {string} The formatted time string
*/
function formatTime(config, time) {
let formatString = hourSymbol + ":mm";
let formatString = `${hourSymbol}:mm`;
if (config.showPeriod && config.timeFormat !== 24) {
formatString += config.showPeriodUpper ? "A" : "a";
}
@ -195,19 +195,11 @@ Module.register("clock", {
nextEvent = tomorrowSunTimes.sunrise;
}
const untilNextEvent = moment.duration(moment(nextEvent).diff(now));
const untilNextEventString = untilNextEvent.hours() + "h " + untilNextEvent.minutes() + "m";
const untilNextEventString = `${untilNextEvent.hours()}h ${untilNextEvent.minutes()}m`;
sunWrapper.innerHTML =
'<span class="' +
(isVisible ? "bright" : "") +
'"><i class="fas fa-sun" aria-hidden="true"></i> ' +
untilNextEventString +
"</span>" +
'<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ' +
formatTime(this.config, sunTimes.sunrise) +
"</span>" +
'<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ' +
formatTime(this.config, sunTimes.sunset) +
"</span>";
`<span class="${isVisible ? "bright" : ""}"><i class="fas fa-sun" aria-hidden="true"></i> ${untilNextEventString}</span>` +
`<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ${formatTime(this.config, sunTimes.sunrise)}</span>` +
`<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ${formatTime(this.config, sunTimes.sunset)}</span>`;
digitalWrapper.appendChild(sunWrapper);
}
@ -226,19 +218,11 @@ Module.register("clock", {
moonSet = nextMoonTimes.set;
}
const isVisible = now.isBetween(moonRise, moonSet) || moonTimes.alwaysUp === true;
const illuminatedFractionString = Math.round(moonIllumination.fraction * 100) + "%";
const illuminatedFractionString = `${Math.round(moonIllumination.fraction * 100)}%`;
moonWrapper.innerHTML =
'<span class="' +
(isVisible ? "bright" : "") +
'"><i class="fas fa-moon" aria-hidden="true"></i> ' +
illuminatedFractionString +
"</span>" +
'<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ' +
(moonRise ? formatTime(this.config, moonRise) : "...") +
"</span>" +
'<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ' +
(moonSet ? formatTime(this.config, moonSet) : "...") +
"</span>";
`<span class="${isVisible ? "bright" : ""}"><i class="fas fa-moon" aria-hidden="true"></i> ${illuminatedFractionString}</span>` +
`<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ${moonRise ? formatTime(this.config, moonRise) : "..."}</span>` +
`<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ${moonSet ? formatTime(this.config, moonSet) : "..."}</span>`;
digitalWrapper.appendChild(moonWrapper);
}
@ -266,7 +250,7 @@ Module.register("clock", {
analogWrapper.style.height = this.config.analogSize;
if (this.config.analogFace !== "" && this.config.analogFace !== "simple" && this.config.analogFace !== "none") {
analogWrapper.style.background = "url(" + this.data.path + "faces/" + this.config.analogFace + ".svg)";
analogWrapper.style.background = `url(${this.data.path}faces/${this.config.analogFace}.svg)`;
analogWrapper.style.backgroundSize = "100%";
// The following line solves issue: https://github.com/MichMich/MagicMirror/issues/611
@ -280,11 +264,11 @@ Module.register("clock", {
const clockHour = document.createElement("div");
clockHour.id = "clock-hour";
clockHour.style.transform = "rotate(" + hour + "deg)";
clockHour.style.transform = `rotate(${hour}deg)`;
clockHour.className = "clock-hour";
const clockMinute = document.createElement("div");
clockMinute.id = "clock-minute";
clockMinute.style.transform = "rotate(" + minute + "deg)";
clockMinute.style.transform = `rotate(${minute}deg)`;
clockMinute.className = "clock-minute";
// Combine analog wrappers
@ -294,7 +278,7 @@ Module.register("clock", {
if (this.config.displaySeconds) {
const clockSecond = document.createElement("div");
clockSecond.id = "clock-second";
clockSecond.style.transform = "rotate(" + second + "deg)";
clockSecond.style.transform = `rotate(${second}deg)`;
clockSecond.className = "clock-second";
clockSecond.style.backgroundColor = this.config.secondsColor;
clockFace.appendChild(clockSecond);
@ -316,7 +300,7 @@ Module.register("clock", {
} else if (this.config.displayType === "digital") {
wrapper.appendChild(digitalWrapper);
} else if (this.config.displayType === "both") {
wrapper.classList.add("clock-grid-" + this.config.analogPlacement);
wrapper.classList.add(`clock-grid-${this.config.analogPlacement}`);
wrapper.appendChild(analogWrapper);
wrapper.appendChild(digitalWrapper);
}

View File

@ -34,7 +34,7 @@ Module.register("compliments", {
// Define start sequence.
start: async function () {
Log.info("Starting module: " + this.name);
Log.info(`Starting module: ${this.name}`);
this.lastComplimentIndex = -1;

View File

@ -44,7 +44,7 @@ Module.register("newsfeed", {
getUrlPrefix: function (item) {
if (item.useCorsProxy) {
return location.protocol + "//" + location.host + "/cors?url=";
return `${location.protocol}//${location.host}/cors?url=`;
} else {
return "";
}
@ -70,7 +70,7 @@ Module.register("newsfeed", {
// Define start sequence.
start: function () {
Log.info("Starting module: " + this.name);
Log.info(`Starting module: ${this.name}`);
// Set locale.
moment.locale(config.language);
@ -346,7 +346,7 @@ Module.register("newsfeed", {
this.activeItem = 0;
}
this.resetDescrOrFullArticleAndTimer();
Log.debug(this.name + " - going from article #" + before + " to #" + this.activeItem + " (of " + this.newsItems.length + ")");
Log.debug(`${this.name} - going from article #${before} to #${this.activeItem} (of ${this.newsItems.length})`);
this.updateDom(100);
} else if (notification === "ARTICLE_PREVIOUS") {
this.activeItem--;
@ -354,7 +354,7 @@ Module.register("newsfeed", {
this.activeItem = this.newsItems.length - 1;
}
this.resetDescrOrFullArticleAndTimer();
Log.debug(this.name + " - going from article #" + before + " to #" + this.activeItem + " (of " + this.newsItems.length + ")");
Log.debug(`${this.name} - going from article #${before} to #${this.activeItem} (of ${this.newsItems.length})`);
this.updateDom(100);
}
// if "more details" is received the first time: show article summary, on second time show full article
@ -363,8 +363,8 @@ Module.register("newsfeed", {
if (this.config.showFullArticle === true) {
this.scrollPosition += this.config.scrollLength;
window.scrollTo(0, this.scrollPosition);
Log.debug(this.name + " - scrolling down");
Log.debug(this.name + " - ARTICLE_MORE_DETAILS, scroll position: " + this.config.scrollLength);
Log.debug(`${this.name} - scrolling down`);
Log.debug(`${this.name} - ARTICLE_MORE_DETAILS, scroll position: ${this.config.scrollLength}`);
} else {
this.showFullArticle();
}
@ -372,12 +372,12 @@ Module.register("newsfeed", {
if (this.config.showFullArticle === true) {
this.scrollPosition -= this.config.scrollLength;
window.scrollTo(0, this.scrollPosition);
Log.debug(this.name + " - scrolling up");
Log.debug(this.name + " - ARTICLE_SCROLL_UP, scroll position: " + this.config.scrollLength);
Log.debug(`${this.name} - scrolling up`);
Log.debug(`${this.name} - ARTICLE_SCROLL_UP, scroll position: ${this.config.scrollLength}`);
}
} else if (notification === "ARTICLE_LESS_DETAILS") {
this.resetDescrOrFullArticleAndTimer();
Log.debug(this.name + " - showing only article titles again");
Log.debug(`${this.name} - showing only article titles again`);
this.updateDom(100);
} else if (notification === "ARTICLE_TOGGLE_FULL") {
if (this.config.showFullArticle) {
@ -406,7 +406,7 @@ Module.register("newsfeed", {
}
clearInterval(this.timer);
this.timer = null;
Log.debug(this.name + " - showing " + this.isShowingDescription ? "article description" : "full article");
Log.debug(`${this.name} - showing ${this.isShowingDescription ? "article description" : "full article"}`);
this.updateDom(100);
}
});

View File

@ -64,9 +64,9 @@ const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings
} else if (logFeedWarnings) {
Log.warn("Can't parse feed item:");
Log.warn(item);
Log.warn("Title: " + title);
Log.warn("Description: " + description);
Log.warn("Pubdate: " + pubdate);
Log.warn(`Title: ${title}`);
Log.warn(`Description: ${description}`);
Log.warn(`Pubdate: ${pubdate}`);
}
});
@ -90,16 +90,16 @@ const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings
const ttlms = Math.min(minutes * 60 * 1000, 86400000);
if (ttlms > reloadInterval) {
reloadInterval = ttlms;
Log.info("Newsfeed-Fetcher: reloadInterval set to ttl=" + reloadInterval + " for url " + url);
Log.info(`Newsfeed-Fetcher: reloadInterval set to ttl=${reloadInterval} for url ${url}`);
}
} catch (error) {
Log.warn("Newsfeed-Fetcher: feed ttl is no valid integer=" + minutes + " for url " + url);
Log.warn(`Newsfeed-Fetcher: feed ttl is no valid integer=${minutes} for url ${url}`);
}
});
const nodeVersion = Number(process.version.match(/^v(\d+\.\d+)/)[1]);
const headers = {
"User-Agent": "Mozilla/5.0 (Node.js " + nodeVersion + ") MagicMirror/" + global.version,
"User-Agent": `Mozilla/5.0 (Node.js ${nodeVersion}) MagicMirror/${global.version}`,
"Cache-Control": "max-age=0, no-cache, no-store, must-revalidate",
Pragma: "no-cache"
};
@ -159,7 +159,7 @@ const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings
Log.info("Newsfeed-Fetcher: No items to broadcast yet.");
return;
}
Log.info("Newsfeed-Fetcher: Broadcasting " + items.length + " items.");
Log.info(`Newsfeed-Fetcher: Broadcasting ${items.length} items.`);
itemsReceivedCallback(this);
};

View File

@ -12,7 +12,7 @@ const Log = require("logger");
module.exports = NodeHelper.create({
// Override start method.
start: function () {
Log.log("Starting node helper for: " + this.name);
Log.log(`Starting node helper for: ${this.name}`);
this.fetchers = [];
},
@ -47,7 +47,7 @@ module.exports = NodeHelper.create({
let fetcher;
if (typeof this.fetchers[url] === "undefined") {
Log.log("Create new newsfetcher for url: " + url + " - Interval: " + reloadInterval);
Log.log(`Create new newsfetcher for url: ${url} - Interval: ${reloadInterval}`);
fetcher = new NewsfeedFetcher(url, reloadInterval, encoding, config.logFeedWarnings, useCorsProxy);
fetcher.onReceive(() => {
@ -64,7 +64,7 @@ module.exports = NodeHelper.create({
this.fetchers[url] = fetcher;
} else {
Log.log("Use existing newsfetcher for url: " + url);
Log.log(`Use existing newsfetcher for url: ${url}`);
fetcher = this.fetchers[url];
fetcher.setReloadInterval(reloadInterval);
fetcher.broadcastItems();

View File

@ -131,7 +131,7 @@ class GitHelper {
// this is the default if there was no match from "git fetch -n --dry-run".
// Its a fallback because if there was a real "git fetch", the above "git fetch -n --dry-run" would deliver nothing.
let refDiff = gitInfo.current + "..origin/" + gitInfo.current;
let refDiff = `${gitInfo.current}..origin/${gitInfo.current}`;
if (matches && matches[0]) {
refDiff = matches[0];
}

View File

@ -138,7 +138,7 @@ WeatherProvider.register("envcanada", {
// being accessed. This is only pertinent when using the EC data elements that contain a textual forecast.
//
getUrl() {
return "https://dd.weather.gc.ca/citypage_weather/xml/" + this.config.provCode + "/" + this.config.siteCode + "_e.xml";
return `https://dd.weather.gc.ca/citypage_weather/xml/${this.config.provCode}/${this.config.siteCode}_e.xml`;
},
//

View File

@ -264,9 +264,9 @@ WeatherProvider.register("openmeteo", {
switch (key) {
case "hourly":
case "daily":
return encodeURIComponent(key) + "=" + params[key].join(",");
return `${encodeURIComponent(key)}=${params[key].join(",")}`;
default:
return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
return `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`;
}
})
.join("&");

View File

@ -413,8 +413,8 @@ WeatherProvider.register("openweathermap", {
getParams() {
let params = "?";
if (this.config.weatherEndpoint === "/onecall") {
params += "lat=" + this.config.lat;
params += "&lon=" + this.config.lon;
params += `lat=${this.config.lat}`;
params += `&lon=${this.config.lon}`;
if (this.config.type === "current") {
params += "&exclude=minutely,hourly,daily";
} else if (this.config.type === "hourly") {
@ -425,23 +425,23 @@ WeatherProvider.register("openweathermap", {
params += "&exclude=minutely";
}
} else if (this.config.lat && this.config.lon) {
params += "lat=" + this.config.lat + "&lon=" + this.config.lon;
params += `lat=${this.config.lat}&lon=${this.config.lon}`;
} else if (this.config.locationID) {
params += "id=" + this.config.locationID;
params += `id=${this.config.locationID}`;
} else if (this.config.location) {
params += "q=" + this.config.location;
params += `q=${this.config.location}`;
} else if (this.firstEvent && this.firstEvent.geo) {
params += "lat=" + this.firstEvent.geo.lat + "&lon=" + this.firstEvent.geo.lon;
params += `lat=${this.firstEvent.geo.lat}&lon=${this.firstEvent.geo.lon}`;
} else if (this.firstEvent && this.firstEvent.location) {
params += "q=" + this.firstEvent.location;
params += `q=${this.firstEvent.location}`;
} else {
this.hide(this.config.animationSpeed, { lockString: this.identifier });
return;
}
params += "&units=metric"; // WeatherProviders should use metric internally and use the units only for when displaying data
params += "&lang=" + this.config.lang;
params += "&APPID=" + this.config.apiKey;
params += `&lang=${this.config.lang}`;
params += `&APPID=${this.config.apiKey}`;
return params;
}

View File

@ -33,7 +33,7 @@ WeatherProvider.register("smhi", {
this.setFetchedLocation(this.config.location || `(${coordinates.lat},${coordinates.lon})`);
this.setCurrentWeather(weatherObject);
})
.catch((error) => Log.error("Could not load data: " + error.message))
.catch((error) => Log.error(`Could not load data: ${error.message}`))
.finally(() => this.updateAvailable());
},
@ -48,7 +48,7 @@ WeatherProvider.register("smhi", {
this.setFetchedLocation(this.config.location || `(${coordinates.lat},${coordinates.lon})`);
this.setWeatherForecast(weatherObjects);
})
.catch((error) => Log.error("Could not load data: " + error.message))
.catch((error) => Log.error(`Could not load data: ${error.message}`))
.finally(() => this.updateAvailable());
},
@ -63,7 +63,7 @@ WeatherProvider.register("smhi", {
this.setFetchedLocation(this.config.location || `(${coordinates.lat},${coordinates.lon})`);
this.setWeatherHourly(weatherObjects);
})
.catch((error) => Log.error("Could not load data: " + error.message))
.catch((error) => Log.error(`Could not load data: ${error.message}`))
.finally(() => this.updateAvailable());
},
@ -75,7 +75,7 @@ WeatherProvider.register("smhi", {
setConfig(config) {
this.config = config;
if (!config.precipitationValue || ["pmin", "pmean", "pmedian", "pmax"].indexOf(config.precipitationValue) === -1) {
Log.log("invalid or not set: " + config.precipitationValue);
Log.log(`invalid or not set: ${config.precipitationValue}`);
config.precipitationValue = this.defaults.precipitationValue;
}
},

View File

@ -195,8 +195,8 @@ WeatherProvider.register("ukmetoffice", {
*/
getParams(forecastType) {
let params = "?";
params += "res=" + forecastType;
params += "&key=" + this.config.apiKey;
params += `res=${forecastType}`;
params += `&key=${this.config.apiKey}`;
return params;
}
});

View File

@ -55,9 +55,9 @@ WeatherProvider.register("ukmetofficedatahub", {
// Build URL with query strings according to DataHub API (https://metoffice.apiconnect.ibmcloud.com/metoffice/production/api)
getUrl(forecastType) {
let queryStrings = "?";
queryStrings += "latitude=" + this.config.lat;
queryStrings += "&longitude=" + this.config.lon;
queryStrings += "&includeLocationName=" + true;
queryStrings += `latitude=${this.config.lat}`;
queryStrings += `&longitude=${this.config.lon}`;
queryStrings += `&includeLocationName=${true}`;
// Return URL, making sure there is a trailing "/" in the base URL.
return this.config.apiBase + (this.config.apiBase.endsWith("/") ? "" : "/") + forecastType + queryStrings;
@ -104,7 +104,7 @@ WeatherProvider.register("ukmetofficedatahub", {
})
// Catch any error(s)
.catch((error) => Log.error("Could not load data: " + error.message))
.catch((error) => Log.error(`Could not load data: ${error.message}`))
// Let the module know there is data available
.finally(() => this.updateAvailable());
@ -173,7 +173,7 @@ WeatherProvider.register("ukmetofficedatahub", {
})
// Catch any error(s)
.catch((error) => Log.error("Could not load data: " + error.message))
.catch((error) => Log.error(`Could not load data: ${error.message}`))
// Let the module know there is new data available
.finally(() => this.updateAvailable());

View File

@ -55,7 +55,7 @@ WeatherProvider.register("weatherbit", {
const forecast = this.generateWeatherObjectsFromForecast(data.data);
this.setWeatherForecast(forecast);
this.fetchedLocationName = data.city_name + ", " + data.state_code;
this.fetchedLocationName = `${data.city_name}, ${data.state_code}`;
})
.catch(function (request) {
Log.error("Could not load data ... ", request);
@ -111,7 +111,7 @@ WeatherProvider.register("weatherbit", {
currentWeather.sunrise = moment(currentWeatherData.data[0].sunrise, "HH:mm").add(tzOffset, "m");
currentWeather.sunset = moment(currentWeatherData.data[0].sunset, "HH:mm").add(tzOffset, "m");
this.fetchedLocationName = currentWeatherData.data[0].city_name + ", " + currentWeatherData.data[0].state_code;
this.fetchedLocationName = `${currentWeatherData.data[0].city_name}, ${currentWeatherData.data[0].state_code}`;
return currentWeather;
},

View File

@ -129,10 +129,10 @@ WeatherProvider.register("weathergov", {
// points URL did not respond with usable data.
return;
}
this.fetchedLocationName = data.properties.relativeLocation.properties.city + ", " + data.properties.relativeLocation.properties.state;
Log.log("Forecast location is " + this.fetchedLocationName);
this.forecastURL = data.properties.forecast + "?units=si";
this.forecastHourlyURL = data.properties.forecastHourly + "?units=si";
this.fetchedLocationName = `${data.properties.relativeLocation.properties.city}, ${data.properties.relativeLocation.properties.state}`;
Log.log(`Forecast location is ${this.fetchedLocationName}`);
this.forecastURL = `${data.properties.forecast}?units=si`;
this.forecastHourlyURL = `${data.properties.forecastHourly}?units=si`;
this.forecastGridDataURL = data.properties.forecastGridData;
this.observationStationsURL = data.properties.observationStations;
// with this URL, we chain another promise for the station obs URL
@ -143,7 +143,7 @@ WeatherProvider.register("weathergov", {
// obs station URL did not respond with usable data.
return;
}
this.stationObsURL = obsData.features[0].id + "/observations/latest";
this.stationObsURL = `${obsData.features[0].id}/observations/latest`;
})
.catch((err) => {
Log.error(err);

View File

@ -252,12 +252,12 @@ WeatherProvider.register("yr", {
this.cacheStellarData(stellarData);
resolve(stellarData);
} else {
reject("No stellar data returned from Yr for " + tomorrow);
reject(`No stellar data returned from Yr for ${tomorrow}`);
}
})
.catch((err) => {
Log.error(err);
reject("Unable to get stellar data from Yr for " + tomorrow);
reject(`Unable to get stellar data from Yr for ${tomorrow}`);
})
.finally(() => {
localStorage.removeItem("yrIsFetchingStellarData");
@ -275,7 +275,7 @@ WeatherProvider.register("yr", {
this.cacheStellarData(stellarData);
resolve(stellarData);
} else {
Log.error("Something went wrong when fetching stellar data. Responses: " + stellarData);
Log.error(`Something went wrong when fetching stellar data. Responses: ${stellarData}`);
reject(stellarData);
}
})

View File

@ -60,13 +60,13 @@ Module.register("weather", {
// Return the scripts that are necessary for the weather module.
getScripts: function () {
return ["moment.js", this.file("../utils.js"), "weatherutils.js", "weatherprovider.js", "weatherobject.js", "suncalc.js", this.file("providers/" + this.config.weatherProvider.toLowerCase() + ".js")];
return ["moment.js", this.file("../utils.js"), "weatherutils.js", "weatherprovider.js", "weatherobject.js", "suncalc.js", this.file(`providers/${this.config.weatherProvider.toLowerCase()}.js`)];
},
// Override getHeader method.
getHeader: function () {
if (this.config.appendLocationNameToHeader && this.weatherProvider) {
if (this.data.header) return this.data.header + " " + this.weatherProvider.fetchedLocation();
if (this.data.header) return `${this.data.header} ${this.weatherProvider.fetchedLocation()}`;
else return this.weatherProvider.fetchedLocation();
}
@ -233,7 +233,7 @@ Module.register("weather", {
"unit",
function (value, type, valueUnit) {
if (type === "temperature") {
value = this.roundValue(WeatherUtils.convertTemp(value, this.config.tempUnits)) + "°";
value = `${this.roundValue(WeatherUtils.convertTemp(value, this.config.tempUnits))}°`;
if (this.config.degreeLabel) {
if (this.config.tempUnits === "metric") {
value += "C";

View File

@ -4,5 +4,5 @@ const Log = require("logger");
app.start().then((config) => {
const bindAddress = config.address ? config.address : "localhost";
const httpType = config.useHttps ? "https" : "http";
Log.log("\nReady to go! Please point your browser to: " + httpType + "://" + bindAddress + ":" + config.port);
Log.log(`\nReady to go! Please point your browser to: ${httpType}://${bindAddress}:${config.port}`);
});

View File

@ -3,7 +3,7 @@
* By Rodrigo Ramírez Norambuena https://rodrigoramirez.com
* MIT Licensed.
*/
let config = require(process.cwd() + "/tests/configs/default.js").configFactory({
let config = require(`${process.cwd()}/tests/configs/default.js`).configFactory({
ipWhitelist: []
});

View File

@ -14,7 +14,7 @@ let config = {
module: "helloworld",
position: positions[idx],
config: {
text: "Text in " + positions[idx]
text: `Text in ${positions[idx]}`
}
});
}

View File

@ -3,7 +3,7 @@
* By Rodrigo Ramírez Norambuena https://rodrigoramirez.com
* MIT Licensed.
*/
let config = require(process.cwd() + "/tests/configs/default.js").configFactory({
let config = require(`${process.cwd()}/tests/configs/default.js`).configFactory({
ipWhitelist: ["x.x.x.x"]
});

View File

@ -3,7 +3,7 @@
* By Rodrigo Ramírez Norambuena https://rodrigoramirez.com
* MIT Licensed.
*/
let config = require(process.cwd() + "/tests/configs/default.js").configFactory({
let config = require(`${process.cwd()}/tests/configs/default.js`).configFactory({
port: 8090
});

View File

@ -3,7 +3,7 @@ const helpers = require("./helpers/global-setup");
describe("All font files from roboto.css should be downloadable", () => {
const fontFiles = [];
// Statements below filters out all 'url' lines in the CSS file
const fileContent = require("fs").readFileSync(__dirname + "/../../fonts/roboto.css", "utf8");
const fileContent = require("fs").readFileSync(`${__dirname}/../../fonts/roboto.css`, "utf8");
const regex = /\burl\(['"]([^'"]+)['"]\)/g;
let match = regex.exec(fileContent);
while (match !== null) {
@ -21,7 +21,7 @@ describe("All font files from roboto.css should be downloadable", () => {
});
test.each(fontFiles)("should return 200 HTTP code for file '%s'", async (fontFile) => {
const fontUrl = "http://localhost:8080/fonts/" + fontFile;
const fontUrl = `http://localhost:8080/fonts/${fontFile}`;
const res = await helpers.fetch(fontUrl);
expect(res.status).toBe(200);
});

View File

@ -12,7 +12,7 @@ app.use(basicAuth);
// Set available directories
const directories = ["/tests/configs", "/tests/mocks"];
const rootPath = path.resolve(__dirname + "/../../../");
const rootPath = path.resolve(`${__dirname}/../../../`);
for (let directory of directories) {
app.use(directory, express.static(path.resolve(rootPath + directory)));

View File

@ -28,7 +28,7 @@ exports.stopApplication = async () => {
exports.getDocument = () => {
return new Promise((resolve) => {
const url = "http://" + (config.address || "localhost") + ":" + (config.port || "8080");
const url = `http://${config.address || "localhost"}:${config.port || "8080"}`;
jsdom.JSDOM.fromURL(url, { resources: "usable", runScripts: "dangerously" }).then((dom) => {
dom.window.name = "jsdom";
dom.window.fetch = corefetch;

View File

@ -91,7 +91,7 @@ describe("Calendar module", () => {
await helpers.getDocument();
});
it('should contain text "Mar 25th" in timezone UTC ' + -i, async () => {
it(`should contain text "Mar 25th" in timezone UTC ${-i}`, async () => {
await testTextContain(".calendar", "Mar 25th");
});
});

View File

@ -89,7 +89,7 @@ describe("Clock module", () => {
it("should show the week with the correct number of week of year", async () => {
const currentWeekNumber = moment().week();
const weekToShow = "Week " + currentWeekNumber;
const weekToShow = `Week ${currentWeekNumber}`;
const elem = await helpers.waitForElement(".clock .week");
expect(elem).not.toBe(null);
expect(elem.textContent).toBe(weekToShow);

View File

@ -13,14 +13,14 @@ describe("Weather module: Weather Forecast", () => {
const days = ["Today", "Tomorrow", "Sun", "Mon", "Tue"];
for (const [index, day] of days.entries()) {
it("should render day " + day, async () => {
it(`should render day ${day}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(1)`, day);
});
}
const icons = ["day-cloudy", "rain", "day-sunny", "day-sunny", "day-sunny"];
for (const [index, icon] of icons.entries()) {
it("should render icon " + icon, async () => {
it(`should render icon ${icon}`, async () => {
const elem = await helpers.waitForElement(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(2) span.wi-${icon}`);
expect(elem).not.toBe(null);
});
@ -28,21 +28,21 @@ describe("Weather module: Weather Forecast", () => {
const maxTemps = ["24.4°", "21.0°", "22.9°", "23.4°", "20.6°"];
for (const [index, temp] of maxTemps.entries()) {
it("should render max temperature " + temp, async () => {
it(`should render max temperature ${temp}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(3)`, temp);
});
}
const minTemps = ["15.3°", "13.6°", "13.8°", "13.9°", "10.9°"];
for (const [index, temp] of minTemps.entries()) {
it("should render min temperature " + temp, async () => {
it(`should render min temperature ${temp}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(4)`, temp);
});
}
const opacities = [1, 1, 0.8, 0.5333333333333333, 0.2666666666666667];
for (const [index, opacity] of opacities.entries()) {
it("should render fading of rows with opacity=" + opacity, async () => {
it(`should render fading of rows with opacity=${opacity}`, async () => {
const elem = await helpers.waitForElement(`.weather table.small tr:nth-child(${index + 1})`);
expect(elem).not.toBe(null);
expect(elem.outerHTML).toContain(`<tr style="opacity: ${opacity};">`);
@ -57,7 +57,7 @@ describe("Weather module: Weather Forecast", () => {
const days = ["Fri", "Sat", "Sun", "Mon", "Tue"];
for (const [index, day] of days.entries()) {
it("should render day " + day, async () => {
it(`should render day ${day}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(1)`, day);
});
}
@ -83,7 +83,7 @@ describe("Weather module: Weather Forecast", () => {
const precipitations = [undefined, "2.51 mm"];
for (const [index, precipitation] of precipitations.entries()) {
if (precipitation) {
it("should render precipitation amount " + precipitation, async () => {
it(`should render precipitation amount ${precipitation}`, async () => {
await weatherFunc.getText(`.weather table tr:nth-child(${index + 1}) td.precipitation-amount`, precipitation);
});
}
@ -98,7 +98,7 @@ describe("Weather module: Weather Forecast", () => {
describe("Temperature units", () => {
const temperatures = ["75_9°", "69_8°", "73_2°", "74_1°", "69_1°"];
for (const [index, temp] of temperatures.entries()) {
it("should render custom decimalSymbol = '_' for temp " + temp, async () => {
it(`should render custom decimalSymbol = '_' for temp ${temp}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(3)`, temp);
});
}
@ -108,7 +108,7 @@ describe("Weather module: Weather Forecast", () => {
const precipitations = [undefined, "0.10 in"];
for (const [index, precipitation] of precipitations.entries()) {
if (precipitation) {
it("should render precipitation amount " + precipitation, async () => {
it(`should render precipitation amount ${precipitation}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.precipitation-amount`, precipitation);
});
}

View File

@ -13,10 +13,10 @@ describe("Position of modules", () => {
for (const position of positions) {
const className = position.replace("_", ".");
it("should show text in " + position, async () => {
const elem = await helpers.waitForElement("." + className);
it(`should show text in ${position}`, async () => {
const elem = await helpers.waitForElement(`.${className}`);
expect(elem).not.toBe(null);
expect(elem.textContent).toContain("Text in " + position);
expect(elem.textContent).toContain(`Text in ${position}`);
});
}
});

View File

@ -9,11 +9,11 @@ describe("Vendors", () => {
});
describe("Get list vendors", () => {
const vendors = require(__dirname + "/../../vendor/vendor.js");
const vendors = require(`${__dirname}/../../vendor/vendor.js`);
Object.keys(vendors).forEach((vendor) => {
it(`should return 200 HTTP code for vendor "${vendor}"`, async () => {
const urlVendor = "http://localhost:8080/vendor/" + vendors[vendor];
const urlVendor = `http://localhost:8080/vendor/${vendors[vendor]}`;
const res = await helpers.fetch(urlVendor);
expect(res.status).toBe(200);
});
@ -21,7 +21,7 @@ describe("Vendors", () => {
Object.keys(vendors).forEach((vendor) => {
it(`should return 404 HTTP code for vendor https://localhost/"${vendor}"`, async () => {
const urlVendor = "http://localhost:8080/" + vendors[vendor];
const urlVendor = `http://localhost:8080/${vendors[vendor]}`;
const res = await helpers.fetch(urlVendor);
expect(res.status).toBe(404);
});

View File

@ -7,7 +7,7 @@ describe("Calendar module", () => {
* @param {string} cssClass css selector
*/
const doTest = async (cssClass) => {
let elem = await helpers.getElement(".calendar .module-content .event" + cssClass);
let elem = await helpers.getElement(`.calendar .module-content .event${cssClass}`);
expect(await elem.isVisible()).toBe(true);
};

View File

@ -23,7 +23,7 @@ const readMockData = (type, extendedData = {}) => {
break;
}
return JSON.stringify(_.merge({}, JSON.parse(fs.readFileSync(path.resolve(__dirname + "/../mocks/" + fileName)).toString()), extendedData));
return JSON.stringify(_.merge({}, JSON.parse(fs.readFileSync(path.resolve(`${__dirname}/../mocks/${fileName}`)).toString()), extendedData));
};
const injectMockData = (configFileName, extendedData = {}) => {
@ -35,9 +35,9 @@ const injectMockData = (configFileName, extendedData = {}) => {
} else {
mockWeather = readMockData("current", extendedData);
}
let content = fs.readFileSync(path.resolve(__dirname + "../../../" + configFileName)).toString();
let content = fs.readFileSync(path.resolve(`${__dirname}../../../${configFileName}`)).toString();
content = content.replace("#####WEATHERDATA#####", mockWeather);
fs.writeFileSync(path.resolve(__dirname + "../../../config/config.js"), content);
fs.writeFileSync(path.resolve(`${__dirname}../../../config/config.js`), content);
};
module.exports = { injectMockData };