-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathnode_helper.js
88 lines (77 loc) · 2.51 KB
/
node_helper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/* Magic Mirror
* Node Helper: Newsfeed
*
* By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed.
*/
const NodeHelper = require("node_helper");
const validUrl = require("valid-url");
const Fetcher = require("./fetcher.js");
module.exports = NodeHelper.create({
// Subclass start method.
start () {
console.log(`Starting module: ${this.name}`);
this.fetchers = [];
},
// Subclass socketNotificationReceived received.
socketNotificationReceived (notification, payload) {
if (notification === "ADD_FEED") {
this.createFetcher(payload.feed, payload.config);
}
},
/* createFetcher(feed, config)
* Creates a fetcher for a new feed if it doesn't exist yet.
* Otherwise it reuses the existing one.
*
* attribute feed object - A feed object.
* attribute config object - A configuration object containing reload interval in milliseconds.
*/
createFetcher (feed, config) {
const self = this;
// var defaultLogo = feed.image || "";
const url = feed.url || "";
const encoding = feed.encoding || "UTF-8";
const reloadInterval = feed.reloadInterval || config.reloadInterval || 5 * 60 * 1000;
if (!validUrl.isUri(url)) {
self.sendSocketNotification("INCORRECT_URL", url);
return;
}
let fetcher;
if (typeof self.fetchers[url] === "undefined") {
console.log(`Create new news fetcher for url: ${url} - Interval: ${reloadInterval} logo = ${feed.customLogo}`);
fetcher = new Fetcher(url, reloadInterval, encoding, config.logFeedWarnings, feed.customLogo);
fetcher.onReceive(((fetcher) => {
const items = fetcher.items();
for (const i in items) {
const item = items[i];
// item.image=this.feed_def.image;
}
self.broadcastFeeds();
}).bind({feed_var_in_function: feed}));
fetcher.onError((fetcher, error) => {
self.sendSocketNotification("FETCH_ERROR", {
url: fetcher.url(),
error
});
});
self.fetchers[url] = fetcher;
} else {
console.log(`Use existing news fetcher for url: ${url}`);
fetcher = self.fetchers[url];
fetcher.setReloadInterval(reloadInterval);
fetcher.broadcastItems();
}
fetcher.startFetch();
},
/* broadcastFeeds()
* Creates an object with all feed items of the different registered feeds,
* and broadcasts these using sendSocketNotification.
*/
broadcastFeeds () {
const feeds = {};
for (const f in this.fetchers) {
feeds[f] = this.fetchers[f].items();
}
this.sendSocketNotification("NEWS_ITEMS", feeds);
}
});