86 lines
2.2 KiB
JavaScript
Raw Normal View History

2016-03-31 11:05:32 +02:00
/* Magic Mirror
* Node Helper: Newsfeed
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
2016-04-05 14:35:11 -04:00
var NodeHelper = require("node_helper");
var validUrl = require("valid-url");
var Fetcher = require("./fetcher.js");
2016-03-30 14:49:37 +02:00
module.exports = NodeHelper.create({
// Subclass start method.
start: function() {
2016-04-05 14:35:11 -04:00
console.log("Starting module: " + this.name);
2016-03-30 14:49:37 +02:00
this.fetchers = [];
},
2016-03-30 14:49:37 +02:00
// Subclass socketNotificationReceived received.
socketNotificationReceived: function(notification, payload) {
2016-04-05 14:35:11 -04:00
if (notification === "ADD_FEED") {
this.createFetcher(payload.feed, payload.config);
return;
2016-03-30 14:49:37 +02:00
}
},
2016-03-30 14:49:37 +02:00
/* createFetcher(url, reloadInterval)
* Creates a fetcher for a new url if it doesn't exist yet.
* Otherwise it reoses the existing one.
*
2016-03-30 14:49:37 +02:00
* attribute url string - URL of the news feed.
* attribute reloadInterval number - Reload interval in milliseconds.
*/
createFetcher: function(feed, config) {
2016-03-30 14:49:37 +02:00
var self = this;
var url = feed.url || "";
var encoding = feed.encoding || "UTF-8";
var reloadInterval = config.reloadInterval || 5 * 60 * 1000;
2016-04-05 14:35:11 -04:00
if (!validUrl.isUri(url)) {
self.sendSocketNotification("INCORRECT_URL", url);
return;
}
2016-03-29 15:44:43 +02:00
2016-03-30 14:49:37 +02:00
var fetcher;
2016-04-05 14:35:11 -04:00
if (typeof self.fetchers[url] === "undefined") {
console.log("Create new news fetcher for url: " + url + " - Interval: " + reloadInterval);
2016-04-05 13:16:23 +02:00
fetcher = new Fetcher(url, reloadInterval, encoding);
2016-03-30 14:49:37 +02:00
fetcher.onReceive(function(fetcher) {
self.broadcastFeeds();
2016-03-30 14:49:37 +02:00
});
fetcher.onError(function(fetcher, error) {
2016-04-05 14:35:11 -04:00
self.sendSocketNotification("FETCH_ERROR", {
2016-03-30 14:49:37 +02:00
url: fetcher.url(),
error: error
});
});
self.fetchers[url] = fetcher;
} else {
console.log("Use existing news fetcher for url: " + url);
2016-03-30 14:49:37 +02:00
fetcher = self.fetchers[url];
fetcher.setReloadInterval(reloadInterval);
fetcher.broadcastItems();
}
2016-03-29 15:44:43 +02:00
2016-03-30 14:49:37 +02:00
fetcher.startFetch();
},
/* broadcastFeeds()
* Creates an object with all feed items of the different registered feeds,
* and broadcasts these using sendSocketNotification.
*/
broadcastFeeds: function() {
var feeds = {};
for (var f in this.fetchers) {
feeds[f] = this.fetchers[f].items();
}
this.sendSocketNotification("NEWS_ITEMS", feeds);
2016-03-30 14:49:37 +02:00
}
});