Merge pull request #2017 from rejas/config_logger

Make logger a little more configurable
This commit is contained in:
Michael Teeuw 2020-06-14 14:33:06 +02:00 committed by GitHub
commit 6d3308621f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 124 additions and 114 deletions

View File

@ -12,6 +12,7 @@ _This release is scheduled to be released on 2020-07-01._
### Added ### Added
- Compliments Module - Add Advice API (https://api.adviceslip.com/) Option - Compliments Module - Add Advice API (https://api.adviceslip.com/) Option
- Added option to config the level of logging
- Added prettier for an even cleaner codebase - Added prettier for an even cleaner codebase
- Hide Sunrise/Sunset in Weather module - Hide Sunrise/Sunset in Weather module

View File

@ -28,6 +28,7 @@ var config = {
httpsCertificate: "", // HTTPS Certificate path, only require when useHttps is true httpsCertificate: "", // HTTPS Certificate path, only require when useHttps is true
language: "en", language: "en",
logLevel: ["INFO", "LOG", "WARN", "ERROR"],
timeFormat: 24, timeFormat: 24,
units: "metric", units: "metric",
// serverOnly: true/false/"local" , // serverOnly: true/false/"local" ,

View File

@ -5,20 +5,18 @@
* MIT Licensed. * MIT Licensed.
*/ */
var fs = require("fs"); var fs = require("fs");
var path = require("path");
var Log = require(__dirname + "/logger.js");
var Server = require(__dirname + "/server.js"); var Server = require(__dirname + "/server.js");
var Utils = require(__dirname + "/utils.js"); var Utils = require(__dirname + "/utils.js");
var defaultModules = require(__dirname + "/../modules/default/defaultmodules.js"); var defaultModules = require(__dirname + "/../modules/default/defaultmodules.js");
var path = require("path");
// Alias modules mentioned in package.js under _moduleAliases. // Alias modules mentioned in package.js under _moduleAliases.
require("module-alias/register"); require("module-alias/register");
// add timestamps in front of log messages
require("console-stamp")(console, "yyyy-mm-dd HH:MM:ss.l");
// Get version number. // Get version number.
global.version = JSON.parse(fs.readFileSync("package.json", "utf8")).version; global.version = JSON.parse(fs.readFileSync("package.json", "utf8")).version;
console.log("Starting MagicMirror: v" + global.version); Log.log("Starting MagicMirror: v" + global.version);
// global absolute root path // global absolute root path
global.root_path = path.resolve(__dirname + "/../"); global.root_path = path.resolve(__dirname + "/../");
@ -36,10 +34,10 @@ if (process.env.MM_PORT) {
// The next part is here to prevent a major exception when there // The next part is here to prevent a major exception when there
// is no internet connection. This could probable be solved better. // is no internet connection. This could probable be solved better.
process.on("uncaughtException", function (err) { process.on("uncaughtException", function (err) {
console.log("Whoops! There was an uncaught exception..."); Log.error("Whoops! There was an uncaught exception...");
console.error(err); Log.error(err);
console.log("MagicMirror will not quit, but it might be a good idea to check why this happened. Maybe no internet connection?"); Log.error("MagicMirror will not quit, but it might be a good idea to check why this happened. Maybe no internet connection?");
console.log("If you think this really is an issue, please open an issue on GitHub: https://github.com/MichMich/MagicMirror/issues"); Log.error("If you think this really is an issue, please open an issue on GitHub: https://github.com/MichMich/MagicMirror/issues");
}); });
/* App - The core app. /* App - The core app.
@ -54,7 +52,7 @@ var App = function () {
* argument callback function - The callback function. * argument callback function - The callback function.
*/ */
var loadConfig = function (callback) { var loadConfig = function (callback) {
console.log("Loading config ..."); Log.log("Loading config ...");
var defaults = require(__dirname + "/defaults.js"); var defaults = require(__dirname + "/defaults.js");
// For this check proposed to TestSuite // For this check proposed to TestSuite
@ -72,11 +70,11 @@ var App = function () {
callback(config); callback(config);
} catch (e) { } catch (e) {
if (e.code === "ENOENT") { if (e.code === "ENOENT") {
console.error(Utils.colors.error("WARNING! Could not find config file. Please create one. Starting with default configuration.")); Log.error(Utils.colors.error("WARNING! Could not find config file. Please create one. Starting with default configuration."));
} else if (e instanceof ReferenceError || e instanceof SyntaxError) { } else if (e instanceof ReferenceError || e instanceof SyntaxError) {
console.error(Utils.colors.error("WARNING! Could not validate config file. Starting with default configuration. Please correct syntax errors at or above this line: " + e.stack)); Log.error(Utils.colors.error("WARNING! Could not validate config file. Starting with default configuration. Please correct syntax errors at or above this line: " + e.stack));
} else { } else {
console.error(Utils.colors.error("WARNING! Could not load config file. Starting with default configuration. Error found: " + e)); Log.error(Utils.colors.error("WARNING! Could not load config file. Starting with default configuration. Error found: " + e));
} }
callback(defaults); callback(defaults);
} }
@ -94,7 +92,7 @@ var App = function () {
} }
}); });
if (usedDeprecated.length > 0) { if (usedDeprecated.length > 0) {
console.warn(Utils.colors.warn("WARNING! Your config is using deprecated options: " + usedDeprecated.join(", ") + ". Check README and CHANGELOG for more up-to-date ways of getting the same functionality.")); Log.warn(Utils.colors.warn("WARNING! Your config is using deprecated options: " + usedDeprecated.join(", ") + ". Check README and CHANGELOG for more up-to-date ways of getting the same functionality."));
} }
}; };
@ -119,7 +117,7 @@ var App = function () {
fs.accessSync(helperPath, fs.R_OK); fs.accessSync(helperPath, fs.R_OK);
} catch (e) { } catch (e) {
loadModule = false; loadModule = false;
console.log("No helper found for module: " + moduleName + "."); Log.log("No helper found for module: " + moduleName + ".");
} }
if (loadModule) { if (loadModule) {
@ -127,11 +125,11 @@ var App = function () {
var m = new Module(); var m = new Module();
if (m.requiresVersion) { if (m.requiresVersion) {
console.log("Check MagicMirror version for node helper '" + moduleName + "' - Minimum version: " + m.requiresVersion + " - Current version: " + global.version); Log.log("Check MagicMirror version for node helper '" + moduleName + "' - Minimum version: " + m.requiresVersion + " - Current version: " + global.version);
if (cmpVersions(global.version, m.requiresVersion) >= 0) { if (cmpVersions(global.version, m.requiresVersion) >= 0) {
console.log("Version is ok!"); Log.log("Version is ok!");
} else { } else {
console.log("Version is incorrect. Skip module: '" + moduleName + "'"); Log.log("Version is incorrect. Skip module: '" + moduleName + "'");
return; return;
} }
} }
@ -152,7 +150,7 @@ var App = function () {
* argument module string - The name of the module (including subpath). * argument module string - The name of the module (including subpath).
*/ */
var loadModules = function (modules, callback) { var loadModules = function (modules, callback) {
console.log("Loading module helpers ..."); Log.log("Loading module helpers ...");
var loadNextModule = function () { var loadNextModule = function () {
if (modules.length > 0) { if (modules.length > 0) {
@ -163,7 +161,7 @@ var App = function () {
}); });
} else { } else {
// All modules are loaded // All modules are loaded
console.log("All module helpers loaded."); Log.log("All module helpers loaded.");
callback(); callback();
} }
}; };
@ -215,7 +213,7 @@ var App = function () {
loadModules(modules, function () { loadModules(modules, function () {
var server = new Server(config, function (app, io) { var server = new Server(config, function (app, io) {
console.log("Server started ..."); Log.log("Server started ...");
for (var h in nodeHelpers) { for (var h in nodeHelpers) {
var nodeHelper = nodeHelpers[h]; var nodeHelper = nodeHelpers[h];
@ -224,7 +222,7 @@ var App = function () {
nodeHelper.start(); nodeHelper.start();
} }
console.log("Sockets connected & modules started ..."); Log.log("Sockets connected & modules started ...");
if (typeof callback === "function") { if (typeof callback === "function") {
callback(config); callback(config);
@ -255,7 +253,7 @@ var App = function () {
* this.stop() is called by app.on("before-quit"... in `electron.js` * this.stop() is called by app.on("before-quit"... in `electron.js`
*/ */
process.on("SIGINT", () => { process.on("SIGINT", () => {
console.log("[SIGINT] Received. Shutting down server..."); Log.log("[SIGINT] Received. Shutting down server...");
setTimeout(() => { setTimeout(() => {
process.exit(0); process.exit(0);
}, 3000); // Force quit after 3 seconds }, 3000); // Force quit after 3 seconds
@ -266,7 +264,7 @@ var App = function () {
/* We also need to listen to SIGTERM signals so we stop everything when we are asked to stop by the OS. /* We also need to listen to SIGTERM signals so we stop everything when we are asked to stop by the OS.
*/ */
process.on("SIGTERM", () => { process.on("SIGTERM", () => {
console.log("[SIGTERM] Received. Shutting down server..."); Log.log("[SIGTERM] Received. Shutting down server...");
setTimeout(() => { setTimeout(() => {
process.exit(0); process.exit(0);
}, 3000); // Force quit after 3 seconds }, 3000); // Force quit after 3 seconds

View File

@ -13,6 +13,7 @@ const fs = require("fs");
const rootPath = path.resolve(__dirname + "/../"); const rootPath = path.resolve(__dirname + "/../");
const config = require(rootPath + "/.eslintrc.json"); const config = require(rootPath + "/.eslintrc.json");
const Log = require(rootPath + "/js/logger.js");
const Utils = require(rootPath + "/js/utils.js"); const Utils = require(rootPath + "/js/utils.js");
/* getConfigFile() /* getConfigFile()
@ -33,7 +34,7 @@ function checkConfigFile() {
// Check if file is present // Check if file is present
if (fs.existsSync(configFileName) === false) { if (fs.existsSync(configFileName) === false) {
console.error(Utils.colors.error("File not found: "), configFileName); Log.error(Utils.colors.error("File not found: "), configFileName);
throw new Error("No config file present!"); throw new Error("No config file present!");
} }
@ -41,14 +42,12 @@ function checkConfigFile() {
try { try {
fs.accessSync(configFileName, fs.F_OK); fs.accessSync(configFileName, fs.F_OK);
} catch (e) { } catch (e) {
console.log(Utils.colors.error(e)); Log.log(Utils.colors.error(e));
throw new Error("No permission to access config file!"); throw new Error("No permission to access config file!");
} }
// Validate syntax of the configuration file. // Validate syntax of the configuration file.
// In case the there errors show messages and Log.info(Utils.colors.info("Checking file... "), configFileName);
// return
console.info(Utils.colors.info("Checking file... "), configFileName);
// I'm not sure if all ever is utf-8 // I'm not sure if all ever is utf-8
fs.readFile(configFileName, "utf-8", function (err, data) { fs.readFile(configFileName, "utf-8", function (err, data) {
@ -57,11 +56,12 @@ function checkConfigFile() {
} }
const messages = linter.verify(data, config); const messages = linter.verify(data, config);
if (messages.length === 0) { if (messages.length === 0) {
console.log("Your configuration file doesn't contain syntax errors :)"); Log.log("Your configuration file doesn't contain syntax errors :)");
return true; return true;
} else { } else {
// In case the there errors show messages and return
messages.forEach((error) => { messages.forEach((error) => {
console.log("Line", error.line, "col", error.column, error.message); Log.log("Line", error.line, "col", error.column, error.message);
}); });
throw new Error("Wrong syntax in config file!"); throw new Error("Wrong syntax in config file!");
} }

View File

@ -1,7 +1,8 @@
"use strict"; "use strict";
const electron = require("electron"); const electron = require("electron");
const core = require(__dirname + "/app.js"); const core = require("./app.js");
const Log = require("./logger.js");
// Config // Config
var config = process.env.config ? JSON.parse(process.env.config) : {}; var config = process.env.config ? JSON.parse(process.env.config) : {};
@ -86,7 +87,7 @@ function createWindow() {
// This method will be called when Electron has finished // This method will be called when Electron has finished
// initialization and is ready to create browser windows. // initialization and is ready to create browser windows.
app.on("ready", function () { app.on("ready", function () {
console.log("Launching application."); Log.log("Launching application.");
createWindow(); createWindow();
}); });
@ -110,7 +111,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", (event) => { app.on("before-quit", (event) => {
console.log("Shutting down server..."); Log.log("Shutting down server...");
event.preventDefault(); event.preventDefault();
setTimeout(() => { setTimeout(() => {
process.exit(0); process.exit(0);

View File

@ -182,7 +182,7 @@ var Loader = (function () {
} }
}; };
script.onerror = function () { script.onerror = function () {
console.error("Error on loading script:", fileName); Log.error("Error on loading script:", fileName);
if (typeof callback === "function") { if (typeof callback === "function") {
callback(); callback();
} }
@ -202,7 +202,7 @@ var Loader = (function () {
} }
}; };
stylesheet.onerror = function () { stylesheet.onerror = function () {
console.error("Error on loading stylesheet:", fileName); Log.error("Error on loading stylesheet:", fileName);
if (typeof callback === "function") { if (typeof callback === "function") {
callback(); callback();
} }

View File

@ -1,13 +1,25 @@
/* Magic Mirror /* Magic Mirror
* Logger * Log
*
* This logger is very simple, but needs to be extended. * This logger is very simple, but needs to be extended.
* This system can eventually be used to push the log messages to an external target. * This system can eventually be used to push the log messages to an external target.
* *
* By Michael Teeuw https://michaelteeuw.nl * By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed. * MIT Licensed.
*/ */
const Log = (function () { (function (root, factory) {
return { if (typeof exports === "object") {
// add timestamps in front of log messages
require("console-stamp")(console, "yyyy-mm-dd HH:MM:ss.l");
// Node, CommonJS-like
module.exports = factory(root.config);
} else {
// Browser globals (root is window)
root.Log = factory(root.config);
}
})(this, function (config) {
let logLevel = {
info: Function.prototype.bind.call(console.info, console), info: Function.prototype.bind.call(console.info, console),
log: Function.prototype.bind.call(console.log, console), log: Function.prototype.bind.call(console.log, console),
error: Function.prototype.bind.call(console.error, console), error: Function.prototype.bind.call(console.error, console),
@ -19,4 +31,14 @@ const Log = (function () {
timeEnd: Function.prototype.bind.call(console.timeEnd, console), timeEnd: Function.prototype.bind.call(console.timeEnd, console),
timeStamp: Function.prototype.bind.call(console.timeStamp, console) timeStamp: Function.prototype.bind.call(console.timeStamp, console)
}; };
})();
if (config && config.logLevel) {
Object.keys(logLevel).forEach(function (key, index) {
if (!config.logLevel.includes(key.toLocaleUpperCase())) {
logLevel[key] = function () {};
}
});
}
return logLevel;
});

View File

@ -5,20 +5,21 @@
* MIT Licensed. * MIT Licensed.
*/ */
const Class = require("./class.js"); const Class = require("./class.js");
const Log = require("./logger.js");
const express = require("express"); const express = require("express");
var NodeHelper = Class.extend({ var NodeHelper = Class.extend({
init: function () { init: function () {
console.log("Initializing new module helper ..."); Log.log("Initializing new module helper ...");
}, },
loaded: function (callback) { loaded: function (callback) {
console.log("Module helper loaded: " + this.name); Log.log("Module helper loaded: " + this.name);
callback(); callback();
}, },
start: function () { start: function () {
console.log("Starting module helper: " + this.name); Log.log("Starting module helper: " + this.name);
}, },
/* stop() /* stop()
@ -28,7 +29,7 @@ var NodeHelper = Class.extend({
* *
*/ */
stop: function () { stop: function () {
console.log("Stopping module helper: " + this.name); Log.log("Stopping module helper: " + this.name);
}, },
/* socketNotificationReceived(notification, payload) /* socketNotificationReceived(notification, payload)
@ -38,7 +39,7 @@ var NodeHelper = Class.extend({
* argument payload mixed - The payload of the notification. * argument payload mixed - The payload of the notification.
*/ */
socketNotificationReceived: function (notification, payload) { socketNotificationReceived: function (notification, payload) {
console.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload); Log.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload);
}, },
/* setName(name) /* setName(name)
@ -92,7 +93,7 @@ var NodeHelper = Class.extend({
var self = this; var self = this;
self.io = io; self.io = io;
console.log("Connecting socket for: " + this.name); Log.log("Connecting socket for: " + this.name);
var namespace = this.name; var namespace = this.name;
io.of(namespace).on("connection", function (socket) { io.of(namespace).on("connection", function (socket) {
// add a catch all event. // add a catch all event.
@ -107,7 +108,7 @@ var NodeHelper = Class.extend({
// register catch all. // register catch all.
socket.on("*", function (notification, payload) { socket.on("*", function (notification, payload) {
if (notification !== "*") { if (notification !== "*") {
//console.log('received message in namespace: ' + namespace); //Log.log('received message in namespace: ' + namespace);
self.socketNotificationReceived(notification, payload); self.socketNotificationReceived(notification, payload);
} }
}); });

View File

@ -4,14 +4,15 @@
* By Michael Teeuw https://michaelteeuw.nl * By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed. * MIT Licensed.
*/ */
var express = require("express"); var express = require("express");
var app = require("express")(); var app = require("express")();
var path = require("path"); var path = require("path");
var ipfilter = require("express-ipfilter").IpFilter; var ipfilter = require("express-ipfilter").IpFilter;
var fs = require("fs"); var fs = require("fs");
var helmet = require("helmet"); var helmet = require("helmet");
var Utils = require(__dirname + "/utils.js");
var Log = require("./logger.js");
var Utils = require("./utils.js");
var Server = function (config, callback) { var Server = function (config, callback) {
var port = config.port; var port = config.port;
@ -31,12 +32,12 @@ var Server = function (config, callback) {
} }
var io = require("socket.io")(server); var io = require("socket.io")(server);
console.log("Starting server on port " + port + " ... "); Log.log("Starting server on port " + port + " ... ");
server.listen(port, config.address ? config.address : "localhost"); server.listen(port, config.address ? config.address : "localhost");
if (config.ipWhitelist instanceof Array && config.ipWhitelist.length === 0) { if (config.ipWhitelist instanceof Array && config.ipWhitelist.length === 0) {
console.info(Utils.colors.warn("You're using a full whitelist configuration to allow for all IPs")); Log.info(Utils.colors.warn("You're using a full whitelist configuration to allow for all IPs"));
} }
app.use(function (req, res, next) { app.use(function (req, res, next) {
@ -44,7 +45,7 @@ var Server = function (config, callback) {
if (err === undefined) { if (err === undefined) {
return next(); return next();
} }
console.log(err.message); Log.log(err.message);
res.status(403).send("This device is not allowed to access your mirror. <br> Please check your config.js or config.js.sample to change this."); res.status(403).send("This device is not allowed to access your mirror. <br> Please check your config.js or config.js.sample to change this.");
}); });
}); });

View File

@ -282,7 +282,6 @@ Module.register("calendar", {
timeWrapper = document.createElement("td"); timeWrapper = document.createElement("td");
eventWrapper.appendChild(titleWrapper); eventWrapper.appendChild(titleWrapper);
//console.log(event.today);
var now = new Date(); var now = new Date();
// Define second, minute, hour, and day variables // Define second, minute, hour, and day variables
var oneSecond = 1000; // 1,000 milliseconds var oneSecond = 1000; // 1,000 milliseconds
@ -373,7 +372,6 @@ Module.register("calendar", {
} }
} }
//timeWrapper.innerHTML += ' - '+ moment(event.startDate,'x').format('lll'); //timeWrapper.innerHTML += ' - '+ moment(event.startDate,'x').format('lll');
//console.log(event);
timeWrapper.className = "time light " + this.timeClassForUrl(event.url); timeWrapper.className = "time light " + this.timeClassForUrl(event.url);
eventWrapper.appendChild(timeWrapper); eventWrapper.appendChild(timeWrapper);
} }

View File

@ -4,7 +4,7 @@
* By Michael Teeuw https://michaelteeuw.nl * By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed. * MIT Licensed.
*/ */
const Log = require("../../../js/logger.js");
const ical = require("./vendor/ical.js"); const ical = require("./vendor/ical.js");
const moment = require("moment"); const moment = require("moment");
@ -58,7 +58,6 @@ var CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEntr
return; return;
} }
// console.log(data);
var newEvents = []; var newEvents = [];
// limitFunction doesn't do much limiting, see comment re: the dates array in rrule section below as to why we need to do the filtering ourselves // limitFunction doesn't do much limiting, see comment re: the dates array in rrule section below as to why we need to do the filtering ourselves
@ -275,29 +274,28 @@ var CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEntr
} }
// end recurring event parsing // end recurring event parsing
} else { } else {
// console.log("Single event ...");
// Single event. // Single event.
var fullDayEvent = isFacebookBirthday ? true : isFullDayEvent(event); var fullDayEvent = isFacebookBirthday ? true : isFullDayEvent(event);
if (includePastEvents) { if (includePastEvents) {
// Past event is too far in the past, so skip.
if (endDate < past) { if (endDate < past) {
//console.log("Past event is too far in the past. So skip: " + title);
continue; continue;
} }
} else { } else {
// It's not a fullday event, and it is in the past, so skip.
if (!fullDayEvent && endDate < new Date()) { if (!fullDayEvent && endDate < new Date()) {
//console.log("It's not a fullday event, and it is in the past. So skip: " + title);
continue; continue;
} }
// It's a fullday event, and it is before today, So skip.
if (fullDayEvent && endDate <= today) { if (fullDayEvent && endDate <= today) {
//console.log("It's a fullday event, and it is before today. So skip: " + title);
continue; continue;
} }
} }
// It exceeds the maximumNumberOfDays limit, so skip.
if (startDate > future) { if (startDate > future) {
//console.log("It exceeds the maximumNumberOfDays limit. So skip: " + title);
continue; continue;
} }
@ -305,13 +303,12 @@ var CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEntr
continue; continue;
} }
// adjust start date so multiple day events will be displayed as happening today even though they started some days ago already // Adjust start date so multiple day events will be displayed as happening today even though they started some days ago already
if (fullDayEvent && startDate <= today) { if (fullDayEvent && startDate <= today) {
startDate = moment(today); startDate = moment(today);
} }
// Every thing is good. Add it to the list. // Every thing is good. Add it to the list.
newEvents.push({ newEvents.push({
title: title, title: title,
startDate: startDate.format("x"), startDate: startDate.format("x"),
@ -330,8 +327,6 @@ var CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEntr
return a.startDate - b.startDate; return a.startDate - b.startDate;
}); });
//console.log(newEvents);
events = newEvents.slice(0, maximumEntries); events = newEvents.slice(0, maximumEntries);
self.broadcastEvents(); self.broadcastEvents();
@ -343,7 +338,6 @@ var CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEntr
* Schedule the timer for the next update. * Schedule the timer for the next update.
*/ */
var scheduleTimer = function () { var scheduleTimer = function () {
//console.log('Schedule update timer.');
clearTimeout(reloadTimer); clearTimeout(reloadTimer);
reloadTimer = setTimeout(function () { reloadTimer = setTimeout(function () {
fetchCalendar(); fetchCalendar();
@ -442,7 +436,7 @@ var CalendarFetcher = function (url, reloadInterval, excludedEvents, maximumEntr
* Broadcast the existing events. * Broadcast the existing events.
*/ */
this.broadcastEvents = function () { this.broadcastEvents = function () {
//console.log('Broadcasting ' + events.length + ' events.'); Log.info("Calendar-Fetcher: Broadcasting " + events.length + " events.");
eventsReceivedCallback(self); eventsReceivedCallback(self);
}; };

View File

@ -5,24 +5,21 @@
* MIT Licensed. * MIT Licensed.
*/ */
var NodeHelper = require("node_helper"); const NodeHelper = require("node_helper");
var validUrl = require("valid-url"); const validUrl = require("valid-url");
var CalendarFetcher = require("./calendarfetcher.js"); const CalendarFetcher = require("./calendarfetcher.js");
const Log = require("../../../js/logger");
module.exports = NodeHelper.create({ module.exports = NodeHelper.create({
// Override start method. // Override start method.
start: function () { start: function () {
var events = []; Log.log("Starting node helper for: " + this.name);
this.fetchers = []; this.fetchers = [];
console.log("Starting node helper for: " + this.name);
}, },
// Override socketNotificationReceived method. // Override socketNotificationReceived method.
socketNotificationReceived: function (notification, payload) { socketNotificationReceived: function (notification, payload) {
if (notification === "ADD_CALENDAR") { if (notification === "ADD_CALENDAR") {
//console.log('ADD_CALENDAR: ');
this.createFetcher(payload.url, payload.fetchInterval, payload.excludedEvents, payload.maximumEntries, payload.maximumNumberOfDays, payload.auth, payload.broadcastPastEvents, payload.id); this.createFetcher(payload.url, payload.fetchInterval, payload.excludedEvents, payload.maximumEntries, payload.maximumNumberOfDays, payload.auth, payload.broadcastPastEvents, payload.id);
} }
}, },
@ -34,7 +31,6 @@ module.exports = NodeHelper.create({
* attribute url string - URL of the news feed. * attribute url string - URL of the news feed.
* attribute reloadInterval number - Reload interval in milliseconds. * attribute reloadInterval number - Reload interval in milliseconds.
*/ */
createFetcher: function (url, fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth, broadcastPastEvents, identifier) { createFetcher: function (url, fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth, broadcastPastEvents, identifier) {
var self = this; var self = this;
@ -45,13 +41,10 @@ module.exports = NodeHelper.create({
var fetcher; var fetcher;
if (typeof self.fetchers[identifier + url] === "undefined") { if (typeof self.fetchers[identifier + url] === "undefined") {
console.log("Create new calendar fetcher for url: " + url + " - Interval: " + fetchInterval); Log.log("Create new calendar fetcher for url: " + url + " - Interval: " + fetchInterval);
fetcher = new CalendarFetcher(url, fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth, broadcastPastEvents); fetcher = new CalendarFetcher(url, fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth, broadcastPastEvents);
fetcher.onReceive(function (fetcher) { fetcher.onReceive(function (fetcher) {
//console.log('Broadcast events.');
//console.log(fetcher.events());
self.sendSocketNotification("CALENDAR_EVENTS", { self.sendSocketNotification("CALENDAR_EVENTS", {
id: identifier, id: identifier,
url: fetcher.url(), url: fetcher.url(),
@ -60,7 +53,7 @@ module.exports = NodeHelper.create({
}); });
fetcher.onError(function (fetcher, error) { fetcher.onError(function (fetcher, error) {
console.error("Calendar Error. Could not fetch calendar: ", fetcher.url(), error); Log.error("Calendar Error. Could not fetch calendar: ", fetcher.url(), error);
self.sendSocketNotification("FETCH_ERROR", { self.sendSocketNotification("FETCH_ERROR", {
id: identifier, id: identifier,
url: fetcher.url(), url: fetcher.url(),
@ -70,7 +63,7 @@ module.exports = NodeHelper.create({
self.fetchers[identifier + url] = fetcher; self.fetchers[identifier + url] = fetcher;
} else { } else {
//console.log('Use existing news fetcher for url: ' + url); Log.log("Use existing calendar fetcher for url: " + url);
fetcher = self.fetchers[identifier + url]; fetcher = self.fetchers[identifier + url];
fetcher.broadcastEvents(); fetcher.broadcastEvents();
} }

View File

@ -5,9 +5,10 @@
* MIT Licensed. * MIT Licensed.
*/ */
var FeedMe = require("feedme"); const Log = require("../../../js/logger.js");
var request = require("request"); const FeedMe = require("feedme");
var iconv = require("iconv-lite"); const request = require("request");
const iconv = require("iconv-lite");
/* Fetcher /* Fetcher
* Responsible for requesting an update on the set interval and broadcasting the data. * Responsible for requesting an update on the set interval and broadcasting the data.
@ -34,7 +35,6 @@ var Fetcher = function (url, reloadInterval, encoding, logFeedWarnings) {
/* fetchNews() /* fetchNews()
* Request the new items. * Request the new items.
*/ */
var fetchNews = function () { var fetchNews = function () {
clearTimeout(reloadTimer); clearTimeout(reloadTimer);
reloadTimer = null; reloadTimer = null;
@ -59,16 +59,15 @@ var Fetcher = function (url, reloadInterval, encoding, logFeedWarnings) {
url: url url: url
}); });
} else if (logFeedWarnings) { } else if (logFeedWarnings) {
console.log("Can't parse feed item:"); Log.warn("Can't parse feed item:");
console.log(item); Log.warn(item);
console.log("Title: " + title); Log.warn("Title: " + title);
console.log("Description: " + description); Log.warn("Description: " + description);
console.log("Pubdate: " + pubdate); Log.warn("Pubdate: " + pubdate);
} }
}); });
parser.on("end", function () { parser.on("end", function () {
//console.log("end parsing - " + url);
self.broadcastItems(); self.broadcastItems();
scheduleTimer(); scheduleTimer();
}); });
@ -93,9 +92,7 @@ var Fetcher = function (url, reloadInterval, encoding, logFeedWarnings) {
/* scheduleTimer() /* scheduleTimer()
* Schedule the timer for the next update. * Schedule the timer for the next update.
*/ */
var scheduleTimer = function () { var scheduleTimer = function () {
//console.log('Schedule update timer.');
clearTimeout(reloadTimer); clearTimeout(reloadTimer);
reloadTimer = setTimeout(function () { reloadTimer = setTimeout(function () {
fetchNews(); fetchNews();
@ -127,10 +124,10 @@ var Fetcher = function (url, reloadInterval, encoding, logFeedWarnings) {
*/ */
this.broadcastItems = function () { this.broadcastItems = function () {
if (items.length <= 0) { if (items.length <= 0) {
//console.log('No items to broadcast yet.'); Log.info("Newsfeed-Fetcher: No items to broadcast yet.");
return; return;
} }
//console.log('Broadcasting ' + items.length + ' items.'); Log.info("Newsfeed-Fetcher: Broadcasting " + items.length + " items.");
itemsReceivedCallback(self); itemsReceivedCallback(self);
}; };

View File

@ -5,22 +5,22 @@
* MIT Licensed. * MIT Licensed.
*/ */
var NodeHelper = require("node_helper"); const NodeHelper = require("node_helper");
var validUrl = require("valid-url"); const validUrl = require("valid-url");
var Fetcher = require("./fetcher.js"); const Fetcher = require("./fetcher.js");
const Log = require("../../../js/logger");
module.exports = NodeHelper.create({ module.exports = NodeHelper.create({
// Subclass start method. // Override start method.
start: function () { start: function () {
console.log("Starting module: " + this.name); Log.log("Starting node helper for: " + this.name);
this.fetchers = []; this.fetchers = [];
}, },
// Subclass socketNotificationReceived received. // Override socketNotificationReceived received.
socketNotificationReceived: function (notification, payload) { socketNotificationReceived: function (notification, payload) {
if (notification === "ADD_FEED") { if (notification === "ADD_FEED") {
this.createFetcher(payload.feed, payload.config); this.createFetcher(payload.feed, payload.config);
return;
} }
}, },
@ -45,7 +45,7 @@ module.exports = NodeHelper.create({
var fetcher; var fetcher;
if (typeof self.fetchers[url] === "undefined") { if (typeof self.fetchers[url] === "undefined") {
console.log("Create new news fetcher for url: " + url + " - Interval: " + reloadInterval); Log.log("Create new news fetcher for url: " + url + " - Interval: " + reloadInterval);
fetcher = new Fetcher(url, reloadInterval, encoding, config.logFeedWarnings); fetcher = new Fetcher(url, reloadInterval, encoding, config.logFeedWarnings);
fetcher.onReceive(function (fetcher) { fetcher.onReceive(function (fetcher) {
@ -61,7 +61,7 @@ module.exports = NodeHelper.create({
self.fetchers[url] = fetcher; self.fetchers[url] = fetcher;
} else { } else {
console.log("Use existing news fetcher for url: " + url); Log.log("Use existing news fetcher for url: " + url);
fetcher = self.fetchers[url]; fetcher = self.fetchers[url];
fetcher.setReloadInterval(reloadInterval); fetcher.setReloadInterval(reloadInterval);
fetcher.broadcastItems(); fetcher.broadcastItems();

View File

@ -1,9 +1,10 @@
var SimpleGit = require("simple-git"); const SimpleGit = require("simple-git");
var simpleGits = []; const simpleGits = [];
var fs = require("fs"); const fs = require("fs");
var path = require("path"); const path = require("path");
var defaultModules = require(__dirname + "/../defaultmodules.js"); const defaultModules = require(__dirname + "/../defaultmodules.js");
var NodeHelper = require("node_helper"); const Log = require(__dirname + "/../../../js/logger.js");
const NodeHelper = require("node_helper");
module.exports = NodeHelper.create({ module.exports = NodeHelper.create({
config: {}, config: {},
@ -27,7 +28,7 @@ module.exports = NodeHelper.create({
var moduleFolder = path.normalize(__dirname + "/../../" + moduleName); var moduleFolder = path.normalize(__dirname + "/../../" + moduleName);
try { try {
//console.log("checking git for module="+moduleName) Log.info("Checking git for module: " + moduleName);
let stat = fs.statSync(path.join(moduleFolder, ".git")); let stat = fs.statSync(path.join(moduleFolder, ".git"));
promises.push(this.resolveRemote(moduleName, moduleFolder)); promises.push(this.resolveRemote(moduleName, moduleFolder));
} catch (err) { } catch (err) {

View File

@ -1,6 +1,8 @@
var app = require("../js/app.js"); const app = require("../js/app.js");
const Log = require("../js/logger.js");
app.start(function (config) { app.start(function (config) {
var bindAddress = config.address ? config.address : "localhost"; var bindAddress = config.address ? config.address : "localhost";
var httpType = config.useHttps ? "https" : "http"; var httpType = config.useHttps ? "https" : "http";
console.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);
}); });