logger: add calling filename as prefix on server side (#3926)

This commit is contained in:
Karsten Hassel
2025-10-22 22:50:31 +02:00
committed by GitHub
parent a1c1e9560c
commit bc0d36503a
15 changed files with 119 additions and 97 deletions

View File

@@ -29,7 +29,7 @@ planned for 2026-01-01
### Updated ### Updated
- [core] Update dependencies (#3909, #3916, #3921, #3925) - [core] Update dependencies (#3909, #3916, #3921, #3925)
- [logger] Add prefixes to most Log messages (#3923) - [logger] Add prefixes to most Log messages (#3923, #3926)
## [2.33.0] - 2025-10-01 ## [2.33.0] - 2025-10-01

View File

@@ -132,7 +132,7 @@ function addAnimateCSS (element, animation, animationTime) {
const node = document.getElementById(element); const node = document.getElementById(element);
if (!node) { if (!node) {
// don't execute animate: we don't find div // don't execute animate: we don't find div
Log.warn("[animateCSS] node not found for adding", element); Log.warn("node not found for adding", element);
return; return;
} }
node.style.setProperty("--animate-duration", `${animationTime}s`); node.style.setProperty("--animate-duration", `${animationTime}s`);
@@ -149,7 +149,7 @@ function removeAnimateCSS (element, animation) {
const node = document.getElementById(element); const node = document.getElementById(element);
if (!node) { if (!node) {
// don't execute animate: we don't find div // don't execute animate: we don't find div
Log.warn("[animateCSS] node not found for removing", element); Log.warn("node not found for removing", element);
return; return;
} }
node.classList.remove("animate__animated", animationName); node.classList.remove("animate__animated", animationName);

View File

@@ -44,7 +44,7 @@ function checkConfigFile () {
} }
// Validate syntax of the configuration file. // Validate syntax of the configuration file.
Log.info(`[checkconfig] Checking config file ${configFileName} ...`); Log.info(`Checking config file ${configFileName} ...`);
// I'm not sure if all ever is utf-8 // I'm not sure if all ever is utf-8
const configFile = fs.readFileSync(configFileName, "utf-8"); const configFile = fs.readFileSync(configFileName, "utf-8");
@@ -67,7 +67,7 @@ function checkConfigFile () {
); );
if (errors.length === 0) { if (errors.length === 0) {
Log.info(styleText("green", "[checkconfig] Your configuration file doesn't contain syntax errors :)")); Log.info(styleText("green", "Your configuration file doesn't contain syntax errors :)"));
validateModulePositions(configFileName); validateModulePositions(configFileName);
} else { } else {
let errorMessage = "Your configuration file contains syntax errors :("; let errorMessage = "Your configuration file contains syntax errors :(";
@@ -84,7 +84,7 @@ function checkConfigFile () {
* @param {string} configFileName - The path and filename of the configuration file to validate. * @param {string} configFileName - The path and filename of the configuration file to validate.
*/ */
function validateModulePositions (configFileName) { function validateModulePositions (configFileName) {
Log.info("[checkconfig] Checking modules structure configuration ..."); Log.info("Checking modules structure configuration ...");
const positionList = Utils.getModulePositions(); const positionList = Utils.getModulePositions();
@@ -118,7 +118,7 @@ function validateModulePositions (configFileName) {
const valid = validate(data); const valid = validate(data);
if (valid) { if (valid) {
Log.info(styleText("green", "[checkconfig] Your modules structure configuration doesn't contain errors :)")); Log.info(styleText("green", "Your modules structure configuration doesn't contain errors :)"));
} else { } else {
const module = validate.errors[0].instancePath.split("/")[2]; const module = validate.errors[0].instancePath.split("/")[2];
const position = validate.errors[0].instancePath.split("/")[3]; const position = validate.errors[0].instancePath.split("/")[3];

View File

@@ -40,7 +40,7 @@ function createWindow () {
try { try {
electronSize = electron.screen.getPrimaryDisplay().workAreaSize; electronSize = electron.screen.getPrimaryDisplay().workAreaSize;
} catch { } catch {
Log.warn("[electron] Could not get display size, using defaults ..."); Log.warn("Could not get display size, using defaults ...");
} }
let electronSwitchesDefaults = ["autoplay-policy", "no-user-gesture-required"]; let electronSwitchesDefaults = ["autoplay-policy", "no-user-gesture-required"];
@@ -196,7 +196,7 @@ app.on("activate", function () {
* core.stop() is called by process.on("SIGINT"... in `app.js` * core.stop() is called by process.on("SIGINT"... in `app.js`
*/ */
app.on("before-quit", async (event) => { app.on("before-quit", async (event) => {
Log.log("[electron] Shutting down server..."); Log.log("Shutting down server...");
event.preventDefault(); event.preventDefault();
setTimeout(() => { setTimeout(() => {
process.exit(0); process.exit(0);
@@ -215,7 +215,7 @@ app.on("certificate-error", (event, webContents, url, error, certificate, callba
if (process.env.clientonly) { if (process.env.clientonly) {
app.whenReady().then(() => { app.whenReady().then(() => {
Log.log("[electron] Launching client viewer application."); Log.log("Launching client viewer application.");
createWindow(); createWindow();
}); });
} }
@@ -228,7 +228,7 @@ if (["localhost", "127.0.0.1", "::1", "::ffff:127.0.0.1", undefined].includes(co
core.start().then((c) => { core.start().then((c) => {
config = c; config = c;
app.whenReady().then(() => { app.whenReady().then(() => {
Log.log("[electron] Launching application."); Log.log("Launching application.");
createWindow(); createWindow();
}); });
}); });

View File

@@ -6,8 +6,30 @@
// add timestamps in front of log messages // add timestamps in front of log messages
require("console-stamp")(console, { require("console-stamp")(console, {
format: ":date(yyyy-mm-dd HH:MM:ss.l) :label(7) :msg", format: ":date(yyyy-mm-dd HH:MM:ss.l) :label(7) :pre() :msg",
tokens: { tokens: {
pre: () => {
const err = new Error();
Error.prepareStackTrace = (_, stack) => stack;
const stack = err.stack;
Error.prepareStackTrace = undefined;
try {
for (const line of stack) {
const file = line.getFileName();
if (file && !file.includes("node:") && !file.includes("js/logger.js") && !file.includes("node_modules")) {
const filename = file.replace(/.*\/(.*).js/, "$1");
const filepath = file.replace(/.*\/(.*)\/.*.js/, "$1");
if (filepath === "js") {
return styleText("grey", `[${filename}]`);
} else {
return styleText("grey", `[${filepath}]`);
}
}
}
} catch (err) {
return styleText("grey", "[unknown]");
}
},
label: (arg) => { label: (arg) => {
const { method, defaultTokens } = arg; const { method, defaultTokens } = arg;
let label = defaultTokens.label(arg); let label = defaultTokens.label(arg);

View File

@@ -4,15 +4,15 @@ const Class = require("./class");
const NodeHelper = Class.extend({ const NodeHelper = Class.extend({
init () { init () {
Log.log("[nodehelper] Initializing new module helper ..."); Log.log("Initializing new module helper ...");
}, },
loaded () { loaded () {
Log.log(`[nodehelper] Module helper loaded: ${this.name}`); Log.log(`Module helper loaded: ${this.name}`);
}, },
start () { start () {
Log.log(`[nodehelper] Starting module helper: ${this.name}`); Log.log(`Starting module helper: ${this.name}`);
}, },
/** /**
@@ -21,7 +21,7 @@ const NodeHelper = Class.extend({
* gracefully exit the module. * gracefully exit the module.
*/ */
stop () { stop () {
Log.log(`[nodehelper] Stopping module helper: ${this.name}`); Log.log(`Stopping module helper: ${this.name}`);
}, },
/** /**
@@ -30,7 +30,7 @@ const NodeHelper = Class.extend({
* @param {object} payload The payload of the notification. * @param {object} payload The payload of the notification.
*/ */
socketNotificationReceived (notification, payload) { socketNotificationReceived (notification, payload) {
Log.log(`[nodehelper] ${this.name} received a socket notification: ${notification} - Payload: ${payload}`); Log.log(`${this.name} received a socket notification: ${notification} - Payload: ${payload}`);
}, },
/** /**
@@ -83,7 +83,7 @@ const NodeHelper = Class.extend({
setSocketIO (io) { setSocketIO (io) {
this.io = io; this.io = io;
Log.log(`[nodehelper] Connecting socket for: ${this.name}`); Log.log(`Connecting socket for: ${this.name}`);
io.of(this.name).on("connection", (socket) => { io.of(this.name).on("connection", (socket) => {
// register catch all. // register catch all.

View File

@@ -57,7 +57,7 @@ const CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEn
try { try {
data = ical.parseICS(responseData); data = ical.parseICS(responseData);
Log.debug(`[calendar] parsed data=${JSON.stringify(data, null, 2)}`); Log.debug(`parsed data=${JSON.stringify(data, null, 2)}`);
events = CalendarFetcherUtils.filterEvents(data, { events = CalendarFetcherUtils.filterEvents(data, {
excludedEvents, excludedEvents,
includePastEvents, includePastEvents,
@@ -91,7 +91,7 @@ const CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEn
* Broadcast the existing events. * Broadcast the existing events.
*/ */
this.broadcastEvents = function () { this.broadcastEvents = function () {
Log.info(`[calendar] Fetcher: Broadcasting ${events.length} events from ${url}.`); Log.info(`Fetcher: Broadcasting ${events.length} events from ${url}.`);
eventsReceivedCallback(this); eventsReceivedCallback(this);
}; };

View File

@@ -95,26 +95,26 @@ const CalendarFetcherUtils = {
const oneDayInMs = 24 * 60 * 60000; const oneDayInMs = 24 * 60 * 60000;
let searchFromDate = pastLocalMoment.clone().subtract(Math.max(durationInMs, oneDayInMs), "milliseconds").toDate(); let searchFromDate = pastLocalMoment.clone().subtract(Math.max(durationInMs, oneDayInMs), "milliseconds").toDate();
let searchToDate = futureLocalMoment.clone().add(1, "days").toDate(); let searchToDate = futureLocalMoment.clone().add(1, "days").toDate();
Log.debug(`[calendar] Search for recurring events between: ${searchFromDate} and ${searchToDate}`); Log.debug(`Search for recurring events between: ${searchFromDate} and ${searchToDate}`);
// if until is set, and its a full day event, force the time to midnight. rrule gets confused with non-00 offset // if until is set, and its a full day event, force the time to midnight. rrule gets confused with non-00 offset
// looks like MS Outlook sets the until time incorrectly for fullday events // looks like MS Outlook sets the until time incorrectly for fullday events
if ((rule.options.until !== undefined) && CalendarFetcherUtils.isFullDayEvent(event)) { if ((rule.options.until !== undefined) && CalendarFetcherUtils.isFullDayEvent(event)) {
Log.debug("[calendar] fixup rrule until"); Log.debug("fixup rrule until");
rule.options.until = moment(rule.options.until).clone().startOf("day").add(1, "day") rule.options.until = moment(rule.options.until).clone().startOf("day").add(1, "day")
.toDate(); .toDate();
} }
Log.debug("[calendar] fix rrule start=", rule.options.dtstart); Log.debug("fix rrule start=", rule.options.dtstart);
Log.debug("[calendar] event before rrule.between=", JSON.stringify(event, null, 2), "exdates=", event.exdate); Log.debug("event before rrule.between=", JSON.stringify(event, null, 2), "exdates=", event.exdate);
Log.debug(`[calendar] RRule: ${rule.toString()}`); Log.debug(`RRule: ${rule.toString()}`);
rule.options.tzid = null; // RRule gets *very* confused with timezones rule.options.tzid = null; // RRule gets *very* confused with timezones
let dates = rule.between(searchFromDate, searchToDate, true, () => { let dates = rule.between(searchFromDate, searchToDate, true, () => {
return true; return true;
}); });
Log.debug(`[calendar] Title: ${event.summary}, with dates: \n\n${JSON.stringify(dates)}\n`); Log.debug(`Title: ${event.summary}, with dates: \n\n${JSON.stringify(dates)}\n`);
// shouldn't need this anymore, as RRULE not passed junk // shouldn't need this anymore, as RRULE not passed junk
dates = dates.filter((d) => { dates = dates.filter((d) => {
@@ -140,7 +140,7 @@ const CalendarFetcherUtils = {
return CalendarFetcherUtils.isFullDayEvent(event) ? startMoment.startOf("day") : startMoment; return CalendarFetcherUtils.isFullDayEvent(event) ? startMoment.startOf("day") : startMoment;
}; };
Log.debug(`[calendar] There are ${Object.entries(data).length} calendar entries.`); Log.debug(`There are ${Object.entries(data).length} calendar entries.`);
const now = moment(); const now = moment();
const pastLocalMoment = config.includePastEvents ? now.clone().startOf("day").subtract(config.maximumNumberOfDays, "days") : now; const pastLocalMoment = config.includePastEvents ? now.clone().startOf("day").subtract(config.maximumNumberOfDays, "days") : now;
@@ -153,10 +153,10 @@ const CalendarFetcherUtils = {
.subtract(1, "seconds"); .subtract(1, "seconds");
Object.entries(data).forEach(([key, event]) => { Object.entries(data).forEach(([key, event]) => {
Log.debug("[calendar] Processing entry..."); Log.debug("Processing entry...");
const title = CalendarFetcherUtils.getTitleFromEvent(event); const title = CalendarFetcherUtils.getTitleFromEvent(event);
Log.debug(`[calendar] title: ${title}`); Log.debug(`title: ${title}`);
// Return quickly if event should be excluded. // Return quickly if event should be excluded.
let { excluded, eventFilterUntil } = this.shouldEventBeExcluded(config, title); let { excluded, eventFilterUntil } = this.shouldEventBeExcluded(config, title);
@@ -174,7 +174,7 @@ const CalendarFetcherUtils = {
} }
if (event.type === "VEVENT") { if (event.type === "VEVENT") {
Log.debug(`[calendar] Event:\n${JSON.stringify(event, null, 2)}`); Log.debug(`Event:\n${JSON.stringify(event, null, 2)}`);
let eventStartMoment = eventDate(event, "start"); let eventStartMoment = eventDate(event, "start");
let eventEndMoment; let eventEndMoment;
@@ -191,12 +191,12 @@ const CalendarFetcherUtils = {
} }
} }
Log.debug(`[calendar] start: ${eventStartMoment.toDate()}`); Log.debug(`start: ${eventStartMoment.toDate()}`);
Log.debug(`[calendar] end: ${eventEndMoment.toDate()}`); Log.debug(`end: ${eventEndMoment.toDate()}`);
// Calculate the duration of the event for use with recurring events. // Calculate the duration of the event for use with recurring events.
const durationMs = eventEndMoment.valueOf() - eventStartMoment.valueOf(); const durationMs = eventEndMoment.valueOf() - eventStartMoment.valueOf();
Log.debug(`[calendar] duration: ${durationMs}`); Log.debug(`duration: ${durationMs}`);
const location = event.location || false; const location = event.location || false;
const geo = event.geo || false; const geo = event.geo || false;
@@ -217,12 +217,12 @@ const CalendarFetcherUtils = {
let dateKey = recurringEventStartMoment.tz("UTC").format("YYYY-MM-DD"); let dateKey = recurringEventStartMoment.tz("UTC").format("YYYY-MM-DD");
Log.debug("[calendar] event date dateKey=", dateKey); Log.debug("event date dateKey=", dateKey);
// For each date that we're checking, it's possible that there is a recurrence override for that one day. // For each date that we're checking, it's possible that there is a recurrence override for that one day.
if (curEvent.recurrences !== undefined) { if (curEvent.recurrences !== undefined) {
Log.debug("[calendar] have recurrences=", curEvent.recurrences); Log.debug("have recurrences=", curEvent.recurrences);
if (curEvent.recurrences[dateKey] !== undefined) { if (curEvent.recurrences[dateKey] !== undefined) {
Log.debug("[calendar] have a recurrence match for dateKey=", dateKey); Log.debug("have a recurrence match for dateKey=", dateKey);
// We found an override, so for this recurrence, use a potentially different title, start date, and duration. // We found an override, so for this recurrence, use a potentially different title, start date, and duration.
curEvent = curEvent.recurrences[dateKey]; curEvent = curEvent.recurrences[dateKey];
// Some event start/end dates don't have timezones // Some event start/end dates don't have timezones
@@ -237,12 +237,12 @@ const CalendarFetcherUtils = {
recurringEventEndMoment = moment(curEvent.end).tz(CalendarFetcherUtils.getLocalTimezone()); recurringEventEndMoment = moment(curEvent.end).tz(CalendarFetcherUtils.getLocalTimezone());
} }
} else { } else {
Log.debug("[calendar] recurrence key ", dateKey, " doesn't match"); Log.debug("recurrence key ", dateKey, " doesn't match");
} }
} }
// If there's no recurrence override, check for an exception date. Exception dates represent exceptions to the rule. // If there's no recurrence override, check for an exception date. Exception dates represent exceptions to the rule.
if (curEvent.exdate !== undefined) { if (curEvent.exdate !== undefined) {
Log.debug("[calendar] have datekey=", dateKey, " exdates=", curEvent.exdate); Log.debug("have datekey=", dateKey, " exdates=", curEvent.exdate);
if (curEvent.exdate[dateKey] !== undefined) { if (curEvent.exdate[dateKey] !== undefined) {
// This date is an exception date, which means we should skip it in the recurrence pattern. // This date is an exception date, which means we should skip it in the recurrence pattern.
showRecurrence = false; showRecurrence = false;
@@ -266,7 +266,7 @@ const CalendarFetcherUtils = {
} }
if (showRecurrence === true) { if (showRecurrence === true) {
Log.debug(`[calendar] saving event: ${recurrenceTitle}`); Log.debug(`saving event: ${recurrenceTitle}`);
newEvents.push({ newEvents.push({
title: recurrenceTitle, title: recurrenceTitle,
startDate: recurringEventStartMoment.format("x"), startDate: recurringEventStartMoment.format("x"),
@@ -280,7 +280,7 @@ const CalendarFetcherUtils = {
description: description description: description
}); });
} else { } else {
Log.debug("[calendar] not saving event ", recurrenceTitle, eventStartMoment); Log.debug("not saving event ", recurrenceTitle, eventStartMoment);
} }
} }
// End recurring event parsing. // End recurring event parsing.

View File

@@ -21,20 +21,20 @@ const auth = {
pass: pass pass: pass
}; };
Log.log("[calendar] Create fetcher ..."); Log.log("Create fetcher ...");
const fetcher = new CalendarFetcher(url, fetchInterval, [], maximumEntries, maximumNumberOfDays, auth); const fetcher = new CalendarFetcher(url, fetchInterval, [], maximumEntries, maximumNumberOfDays, auth);
fetcher.onReceive(function (fetcher) { fetcher.onReceive(function (fetcher) {
Log.log("[calendar] ", fetcher.events()); Log.log(fetcher.events());
process.exit(0); process.exit(0);
}); });
fetcher.onError(function (fetcher, error) { fetcher.onError(function (fetcher, error) {
Log.log("[calendar] Fetcher error:", error); Log.log("Fetcher error:", error);
process.exit(1); process.exit(1);
}); });
fetcher.startFetch(); fetcher.startFetch();
Log.log("[calendar] Create fetcher done! "); Log.log("Create fetcher done! ");

View File

@@ -5,7 +5,7 @@ const CalendarFetcher = require("./calendarfetcher");
module.exports = NodeHelper.create({ module.exports = NodeHelper.create({
// Override start method. // Override start method.
start () { start () {
Log.log(`[calendar] Starting node helper for: ${this.name}`); Log.log(`Starting node helper for: ${this.name}`);
this.fetchers = []; this.fetchers = [];
}, },
@@ -16,7 +16,7 @@ module.exports = NodeHelper.create({
} else if (notification === "FETCH_CALENDAR") { } else if (notification === "FETCH_CALENDAR") {
const key = payload.id + payload.url; const key = payload.id + payload.url;
if (typeof this.fetchers[key] === "undefined") { if (typeof this.fetchers[key] === "undefined") {
Log.error("[calendar] No fetcher exists with key: ", key); Log.error("No fetcher exists with key: ", key);
this.sendSocketNotification("CALENDAR_ERROR", { error_type: "MODULE_ERROR_UNSPECIFIED" }); this.sendSocketNotification("CALENDAR_ERROR", { error_type: "MODULE_ERROR_UNSPECIFIED" });
return; return;
} }
@@ -41,7 +41,7 @@ module.exports = NodeHelper.create({
try { try {
new URL(url); new URL(url);
} catch (error) { } catch (error) {
Log.error("[calendar] Malformed calendar url: ", url, error); Log.error("Malformed calendar url: ", url, error);
this.sendSocketNotification("CALENDAR_ERROR", { error_type: "MODULE_ERROR_MALFORMED_URL" }); this.sendSocketNotification("CALENDAR_ERROR", { error_type: "MODULE_ERROR_MALFORMED_URL" });
return; return;
} }
@@ -50,10 +50,10 @@ module.exports = NodeHelper.create({
let fetchIntervalCorrected; let fetchIntervalCorrected;
if (typeof this.fetchers[identifier + url] === "undefined") { if (typeof this.fetchers[identifier + url] === "undefined") {
if (fetchInterval < 60000) { if (fetchInterval < 60000) {
Log.warn(`[calendar] fetchInterval for url ${url} must be >= 60000`); Log.warn(`fetchInterval for url ${url} must be >= 60000`);
fetchIntervalCorrected = 60000; fetchIntervalCorrected = 60000;
} }
Log.log(`[calendar] Create new calendarfetcher for url: ${url} - Interval: ${fetchIntervalCorrected || fetchInterval}`); Log.log(`Create new calendarfetcher for url: ${url} - Interval: ${fetchIntervalCorrected || fetchInterval}`);
fetcher = new CalendarFetcher(url, fetchIntervalCorrected || fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth, broadcastPastEvents, selfSignedCert); fetcher = new CalendarFetcher(url, fetchIntervalCorrected || fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth, broadcastPastEvents, selfSignedCert);
fetcher.onReceive((fetcher) => { fetcher.onReceive((fetcher) => {
@@ -61,7 +61,7 @@ module.exports = NodeHelper.create({
}); });
fetcher.onError((fetcher, error) => { fetcher.onError((fetcher, error) => {
Log.error("[calendar] Calendar Error. Could not fetch calendar: ", fetcher.url(), error); Log.error("Calendar Error. Could not fetch calendar: ", fetcher.url(), error);
let error_type = NodeHelper.checkFetchError(error); let error_type = NodeHelper.checkFetchError(error);
this.sendSocketNotification("CALENDAR_ERROR", { this.sendSocketNotification("CALENDAR_ERROR", {
id: identifier, id: identifier,
@@ -71,7 +71,7 @@ module.exports = NodeHelper.create({
this.fetchers[identifier + url] = fetcher; this.fetchers[identifier + url] = fetcher;
} else { } else {
Log.log(`[calendar] Use existing calendarfetcher for url: ${url}`); Log.log(`Use existing calendarfetcher for url: ${url}`);
fetcher = this.fetchers[identifier + url]; fetcher = this.fetchers[identifier + url];
fetcher.broadcastEvents(); fetcher.broadcastEvents();
} }

View File

@@ -67,10 +67,10 @@ const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings
hash: crypto.createHash("sha256").update(`${pubdate} :: ${title} :: ${url}`).digest("hex") hash: crypto.createHash("sha256").update(`${pubdate} :: ${title} :: ${url}`).digest("hex")
}); });
} else if (logFeedWarnings) { } else if (logFeedWarnings) {
Log.warn("[newsfeed] Can't parse feed item:", item); Log.warn("Can't parse feed item:", item);
Log.warn(`[newsfeed] Title: ${title}`); Log.warn(`Title: ${title}`);
Log.warn(`[newsfeed] Description: ${description}`); Log.warn(`Description: ${description}`);
Log.warn(`[newsfeed] Pubdate: ${pubdate}`); Log.warn(`Pubdate: ${pubdate}`);
} }
}); });
@@ -94,10 +94,10 @@ const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings
const ttlms = Math.min(minutes * 60 * 1000, 86400000); const ttlms = Math.min(minutes * 60 * 1000, 86400000);
if (ttlms > reloadIntervalMS) { if (ttlms > reloadIntervalMS) {
reloadIntervalMS = ttlms; reloadIntervalMS = ttlms;
Log.info(`[newsfeed] reloadInterval set to ttl=${reloadIntervalMS} for url ${url}`); Log.info(`reloadInterval set to ttl=${reloadIntervalMS} for url ${url}`);
} }
} catch (error) { } catch (error) {
Log.warn(`[newsfeed] feed ttl is no valid integer=${minutes} for url ${url}`); Log.warn(`feed ttl is no valid integer=${minutes} for url ${url}`);
} }
}); });
@@ -148,10 +148,10 @@ const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings
*/ */
this.broadcastItems = function () { this.broadcastItems = function () {
if (items.length <= 0) { if (items.length <= 0) {
Log.info("[newsfeed] No items to broadcast yet."); Log.info("No items to broadcast yet.");
return; return;
} }
Log.info(`[newsfeed] Broadcasting ${items.length} items.`); Log.info(`Broadcasting ${items.length} items.`);
itemsReceivedCallback(this); itemsReceivedCallback(this);
}; };

View File

@@ -32,14 +32,14 @@ module.exports = NodeHelper.create({
try { try {
new URL(url); new URL(url);
} catch (error) { } catch (error) {
Log.error("[newsfeed] Error: Malformed newsfeed url: ", url, error); Log.error("Error: Malformed newsfeed url: ", url, error);
this.sendSocketNotification("NEWSFEED_ERROR", { error_type: "MODULE_ERROR_MALFORMED_URL" }); this.sendSocketNotification("NEWSFEED_ERROR", { error_type: "MODULE_ERROR_MALFORMED_URL" });
return; return;
} }
let fetcher; let fetcher;
if (typeof this.fetchers[url] === "undefined") { if (typeof this.fetchers[url] === "undefined") {
Log.log(`[newsfeed] 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 = new NewsfeedFetcher(url, reloadInterval, encoding, config.logFeedWarnings, useCorsProxy);
fetcher.onReceive(() => { fetcher.onReceive(() => {
@@ -47,7 +47,7 @@ module.exports = NodeHelper.create({
}); });
fetcher.onError((fetcher, error) => { fetcher.onError((fetcher, error) => {
Log.error("[newsfeed] Error: Could not fetch newsfeed: ", url, error); Log.error("Error: Could not fetch newsfeed: ", url, error);
let error_type = NodeHelper.checkFetchError(error); let error_type = NodeHelper.checkFetchError(error);
this.sendSocketNotification("NEWSFEED_ERROR", { this.sendSocketNotification("NEWSFEED_ERROR", {
error_type error_type
@@ -56,7 +56,7 @@ module.exports = NodeHelper.create({
this.fetchers[url] = fetcher; this.fetchers[url] = fetcher;
} else { } else {
Log.log(`[newsfeed] Use existing newsfetcher for url: ${url}`); Log.log(`Use existing newsfetcher for url: ${url}`);
fetcher = this.fetchers[url]; fetcher = this.fetchers[url];
fetcher.setReloadInterval(reloadInterval); fetcher.setReloadInterval(reloadInterval);
fetcher.broadcastItems(); fetcher.broadcastItems();

View File

@@ -24,7 +24,7 @@ class GitHelper {
const { stderr } = await this.execShell(`cd ${moduleFolder} && git remote -v`); const { stderr } = await this.execShell(`cd ${moduleFolder} && git remote -v`);
if (stderr) { if (stderr) {
Log.error(`[updatenotification] Failed to fetch git data for ${moduleFolder}: ${stderr}`); Log.error(`Failed to fetch git data for ${moduleFolder}: ${stderr}`);
return false; return false;
} }
@@ -40,7 +40,7 @@ class GitHelper {
} }
try { try {
Log.info(`[updatenotification] Checking git for module: ${moduleName}`); Log.info(`Checking git for module: ${moduleName}`);
// Throws error if file doesn't exist // Throws error if file doesn't exist
fs.statSync(path.join(moduleFolder, ".git")); fs.statSync(path.join(moduleFolder, ".git"));
@@ -72,7 +72,7 @@ class GitHelper {
const { stderr, stdout } = await this.execShell(`cd ${repo.folder} && git rev-parse HEAD`); const { stderr, stdout } = await this.execShell(`cd ${repo.folder} && git rev-parse HEAD`);
if (stderr) { if (stderr) {
Log.error(`[updatenotification] Failed to get current commit hash for ${repo.module}: ${stderr}`); Log.error(`Failed to get current commit hash for ${repo.module}: ${stderr}`);
} }
gitInfo.hash = stdout; gitInfo.hash = stdout;
@@ -81,7 +81,7 @@ class GitHelper {
const { stderr, stdout } = await this.execShell(`cd ${repo.folder} && git status -sb`); const { stderr, stdout } = await this.execShell(`cd ${repo.folder} && git status -sb`);
if (stderr) { if (stderr) {
Log.error(`[updatenotification] Failed to get git status for ${repo.module}: ${stderr}`); Log.error(`Failed to get git status for ${repo.module}: ${stderr}`);
// exit without git status info // exit without git status info
return; return;
} }
@@ -151,7 +151,7 @@ class GitHelper {
const { stdout } = await this.execShell(`cd ${repo.folder} && git ls-remote -q --tags --refs`); const { stdout } = await this.execShell(`cd ${repo.folder} && git ls-remote -q --tags --refs`);
tagList = stdout.trim(); tagList = stdout.trim();
} catch (err) { } catch (err) {
Log.error(`[updatenotification] Failed to get tag list for ${repo.module}: ${err}`); Log.error(`Failed to get tag list for ${repo.module}: ${err}`);
} }
// check if tag is between commits and only report behind > 0 if so // check if tag is between commits and only report behind > 0 if so
try { try {
@@ -162,13 +162,13 @@ class GitHelper {
} }
if (cnt === 0) gitInfo.behind = 0; if (cnt === 0) gitInfo.behind = 0;
} catch (err) { } catch (err) {
Log.error(`[updatenotification] Failed to get git revisions for ${repo.module}: ${err}`); Log.error(`Failed to get git revisions for ${repo.module}: ${err}`);
} }
} }
return gitInfo; return gitInfo;
} catch (err) { } catch (err) {
Log.error(`[updatenotification] Failed to get git revisions for ${repo.module}: ${err}`); Log.error(`Failed to get git revisions for ${repo.module}: ${err}`);
} }
} }
@@ -183,7 +183,7 @@ class GitHelper {
this.gitResultList.push(gitInfo); this.gitResultList.push(gitInfo);
} }
} catch (e) { } catch (e) {
Log.error(`[updatenotification] Failed to retrieve repo info for ${repo.module}: ${e}`); Log.error(`Failed to retrieve repo info for ${repo.module}: ${e}`);
} }
} }
@@ -196,7 +196,7 @@ class GitHelper {
const allRepos = await this.gitResultList.map((module) => { const allRepos = await this.gitResultList.map((module) => {
return new Promise((resolve) => { return new Promise((resolve) => {
if (module.behind > 0 && module.module !== "MagicMirror") { if (module.behind > 0 && module.module !== "MagicMirror") {
Log.info(`[updatenotification] Update found for module: ${module.module}`); Log.info(`Update found for module: ${module.module}`);
updates.push(module); updates.push(module);
} }
resolve(module); resolve(module);

View File

@@ -51,7 +51,7 @@ class Updater {
this.PM2Id = null; // pm2 process number this.PM2Id = null; // pm2 process number
this.version = global.version; this.version = global.version;
this.root_path = global.root_path; this.root_path = global.root_path;
Log.info("[updatenotification] Updater Class Loaded!"); Log.info("Updater Class Loaded!");
} }
// [main command] parse if module update is needed // [main command] parse if module update is needed
@@ -81,7 +81,7 @@ class Updater {
await Promise.all(parser); await Promise.all(parser);
let updater = Object.values(this.moduleList); let updater = Object.values(this.moduleList);
Log.debug("[updatenotification] Update Result:", updater); Log.debug("Update Result:", updater);
return updater; return updater;
} }
@@ -107,24 +107,24 @@ class Updater {
if (module.updateCommand) { if (module.updateCommand) {
Command = module.updateCommand; Command = module.updateCommand;
} else { } else {
Log.warn(`[updatenotification] Update of ${module.name} is not supported.`); Log.warn(`Update of ${module.name} is not supported.`);
return Result; return Result;
} }
Log.info(`[updatenotification] Updating ${module.name}...`); Log.info(`Updating ${module.name}...`);
return new Promise((resolve) => { return new Promise((resolve) => {
Exec(Command, { cwd: modulePath, timeout: this.timeout }, (error, stdout, stderr) => { Exec(Command, { cwd: modulePath, timeout: this.timeout }, (error, stdout, stderr) => {
if (error) { if (error) {
Log.error(`[updatenotification] exec error: ${error}`); Log.error(`exec error: ${error}`);
Result.error = true; Result.error = true;
} else { } else {
Log.info(`[updatenotification]:Update logs of ${module.name}: ${stdout}`); Log.info(`Update logs of ${module.name}: ${stdout}`);
Result.updated = true; Result.updated = true;
if (this.autoRestart) { if (this.autoRestart) {
Log.info("[updatenotification] Update done"); Log.info("Update done");
setTimeout(() => this.restart(), 3000); setTimeout(() => this.restart(), 3000);
} else { } else {
Log.info("[updatenotification] Update done, don't forget to restart MagicMirror!"); Log.info("Update done, don't forget to restart MagicMirror!");
Result.needRestart = true; Result.needRestart = true;
} }
} }
@@ -141,18 +141,18 @@ class Updater {
// restart MagicMirror with "pm2": use PM2Id for restart it // restart MagicMirror with "pm2": use PM2Id for restart it
pm2Restart () { pm2Restart () {
Log.info("[updatenotification] [PM2] restarting MagicMirror..."); Log.info("[PM2] restarting MagicMirror...");
const pm2 = require("pm2"); const pm2 = require("pm2");
pm2.restart(this.PM2Id, (err, proc) => { pm2.restart(this.PM2Id, (err, proc) => {
if (err) { if (err) {
Log.error("[updatenotification] [PM2] restart Error", err); Log.error("[PM2] restart Error", err);
} }
}); });
} }
// restart MagicMirror with "node --run start" // restart MagicMirror with "node --run start"
nodeRestart () { nodeRestart () {
Log.info("[updatenotification] Restarting MagicMirror..."); Log.info("Restarting MagicMirror...");
const out = process.stdout; const out = process.stdout;
const err = process.stderr; const err = process.stderr;
const subprocess = Spawn("node --run start", { cwd: this.root_path, shell: true, detached: true, stdio: ["ignore", out, err] }); const subprocess = Spawn("node --run start", { cwd: this.root_path, shell: true, detached: true, stdio: ["ignore", out, err] });
@@ -162,49 +162,49 @@ class Updater {
// Check using pm2 // Check using pm2
check_PM2_Process () { check_PM2_Process () {
Log.info("[updatenotification] Checking PM2 using..."); Log.info("Checking PM2 using...");
return new Promise((resolve) => { return new Promise((resolve) => {
if (fs.existsSync("/.dockerenv")) { if (fs.existsSync("/.dockerenv")) {
Log.info("[updatenotification] Running in docker container, not using PM2 ..."); Log.info("[PM2] Running in docker container, not using PM2 ...");
resolve(false); resolve(false);
return; return;
} }
if (process.env.unique_id === undefined) { if (process.env.unique_id === undefined) {
Log.info("[updatenotification] [PM2] You are not using pm2"); Log.info("[PM2] You are not using pm2");
resolve(false); resolve(false);
return; return;
} }
Log.debug(`[updatenotification] [PM2] Search for pm2 id: ${process.env.pm_id} -- name: ${process.env.name} -- unique_id: ${process.env.unique_id}`); Log.debug(`[PM2] Search for pm2 id: ${process.env.pm_id} -- name: ${process.env.name} -- unique_id: ${process.env.unique_id}`);
const pm2 = require("pm2"); const pm2 = require("pm2");
pm2.connect((err) => { pm2.connect((err) => {
if (err) { if (err) {
Log.error("[updatenotification] [PM2]", err); Log.error("[PM2]", err);
resolve(false); resolve(false);
return; return;
} }
pm2.list((err, list) => { pm2.list((err, list) => {
if (err) { if (err) {
Log.error("[updatenotification] [PM2] Can't get process List!"); Log.error("[PM2] Can't get process List!");
resolve(false); resolve(false);
return; return;
} }
list.forEach((pm) => { list.forEach((pm) => {
Log.debug(`[updatenotification] [PM2] found pm2 process id: ${pm.pm_id} -- name: ${pm.name} -- unique_id: ${pm.pm2_env.unique_id}`); Log.debug(`[PM2] found pm2 process id: ${pm.pm_id} -- name: ${pm.name} -- unique_id: ${pm.pm2_env.unique_id}`);
if (pm.pm2_env.status === "online" && process.env.name === pm.name && +process.env.pm_id === +pm.pm_id && process.env.unique_id === pm.pm2_env.unique_id) { if (pm.pm2_env.status === "online" && process.env.name === pm.name && +process.env.pm_id === +pm.pm_id && process.env.unique_id === pm.pm2_env.unique_id) {
this.PM2Id = pm.pm_id; this.PM2Id = pm.pm_id;
this.usePM2 = true; this.usePM2 = true;
Log.info(`[updatenotification] [PM2] You are using pm2 with id: ${this.PM2Id} (${pm.name})`); Log.info(`[PM2] You are using pm2 with id: ${this.PM2Id} (${pm.name})`);
resolve(true); resolve(true);
} else { } else {
Log.debug(`[updatenotification] [PM2] pm2 process id: ${pm.pm_id} don't match...`); Log.debug(`[PM2] pm2 process id: ${pm.pm_id} don't match...`);
} }
}); });
pm2.disconnect(); pm2.disconnect();
if (!this.usePM2) { if (!this.usePM2) {
Log.info("[updatenotification] [PM2] You are not using pm2"); Log.info("[PM2] You are not using pm2");
resolve(false); resolve(false);
} }
}); });

View File

@@ -106,7 +106,7 @@ describe("Updatenotification", () => {
expect(repos).toHaveLength(0); expect(repos).toHaveLength(0);
const { error } = require("logger"); const { error } = require("logger");
expect(error).toHaveBeenCalledWith(`[updatenotification] Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`); expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
}); });
}); });
@@ -145,7 +145,7 @@ describe("Updatenotification", () => {
expect(repos).toHaveLength(0); expect(repos).toHaveLength(0);
const { error } = require("logger"); const { error } = require("logger");
expect(error).toHaveBeenCalledWith(`[updatenotification] Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`); expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
}); });
}); });
@@ -186,7 +186,7 @@ describe("Updatenotification", () => {
expect(repos).toHaveLength(0); expect(repos).toHaveLength(0);
const { error } = require("logger"); const { error } = require("logger");
expect(error).toHaveBeenCalledWith(`[updatenotification] Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`); expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
}); });
}); });
@@ -227,7 +227,7 @@ describe("Updatenotification", () => {
expect(repos).toHaveLength(0); expect(repos).toHaveLength(0);
const { error } = require("logger"); const { error } = require("logger");
expect(error).toHaveBeenCalledWith(`[updatenotification] Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`); expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
}); });
}); });