forked from pvyParts/MMM-jokes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_helper.js
222 lines (189 loc) · 6.37 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/* Magic Mirror
* Node Helper: Jokes
*
* Aaron Kable
* MIT Licensed.
*/
var NodeHelper = require('node_helper');
var request = require('request');
var validUrl = require('valid-url');
var validAPIs = ["ticndb", "tambal", "jonsamazingjokes"];
var apiUrls = ["http://api.icndb.com/jokes/random", "http://tambal.azurewebsites.net/joke/random", "http://jonsamazingjokes.appspot.com/fetchjokes/randomsingle"];
var JokeFetcher = function(url, api, reloadInterval) {
var self = this;
var reloadTimer = null;
var joke = '';
var fetchFailedCallback = function() {};
var eventsReceivedCallback = function() {};
/* fetchJoke()
* Initiates joke fetch.
*/
var fetchJoke = function() {
clearTimeout(reloadTimer);
reloadTimer = null;
//console.log('Getting data: ' + url);
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Jokes_Helper: '+ body);
var data = JSON.parse(body);
console.log(data);
console.log(api);
switch (api){
case "ticndb":
joke = data.value.joke; //TODO custom fields
break;
case "tambal":
joke = data.joke;
break;
case "webknox":
joke = data.joke;
break;
case "jonsamazingjokes":
joke = data[0].content; // a string array
break;
}
//console.log('got data: '+ joke);
self.broadcastEvents();
scheduleTimer();
} else {
//console.error("Jokes_Helper: Could not load Jokes.");
console.error("Jokes_Helper: Could not load Jokes, HTTP:" + response.statusCode);
scheduleTimer();
}
});
};
/* scheduleTimer()
* Schedule the timer for the next update.
*/
var scheduleTimer = function() {
//console.log('Schedule update timer.');
clearTimeout(reloadTimer);
reloadTimer = setTimeout(function() {
fetchJoke();
}, reloadInterval);
};
/* public methods */
/* startFetch()
* Initiate startFetch();
*/
this.startFetch = function() {
fetchJoke();
};
/* broadcastItems()
* Broadcast the exsisting events.
*/
this.broadcastEvents = function() {
if (joke === '') {
//console.log('No events to broadcast yet.');
return;
}
//console.log('Broadcasting: ' + joke);
eventsReceivedCallback(self);
};
/* onReceive(callback)
* Sets the on success callback
*
* argument callback function - The on success callback.
*/
this.onReceive = function(callback) {
eventsReceivedCallback = callback;
};
/* onError(callback)
* Sets the on error callback
*
* argument callback function - The on error callback.
*/
this.onError = function(callback) {
fetchFailedCallback = callback;
};
/* url()
* Returns the url of this fetcher.
*
* return string - The url of this fetcher.
*/
this.url = function() {
return url;
};
/* api()
* Returns the api of this fetcher.
*
* return string - The api of this fetcher.
*/
this.api = function() {
return api;
};
/* events()
* Returns current available events for this fetcher.
*
* return array - The current available events for this fetcher.
*/
this.joke = function() {
return joke;
};
};
module.exports = NodeHelper.create({
// Override start method.
start: function() {
var self = this;
var joke = '';
this.fetchers = [];
console.log('Starting node helper for: ' + this.name);
},
// Override socketNotificationReceived method.
socketNotificationReceived: function(notification, payload) {
if (notification === 'ADD_JOKE') {
//console.log('ADD_JOKE: ');
var apiUrl = apiUrls[0];
var currentAPI = validAPIs[0];
for (index = 0; index < validAPIs.length; ++index) {
if (validAPIs[index] === payload.api){
//console.log(validAPIs[index]);
apiUrl = apiUrls[index];
currentAPI = validAPIs[index];
}
}
this.createFetcher(apiUrl, currentAPI, payload.fetchInterval);
}
},
/* createFetcher(url, reloadInterval)
* Creates a fetcher for a new url if it doesn't exsist yet.
* Otherwise it reuses the exsisting one.
*
* attribute url string - URL of the news feed.
* attribute reloadInterval number - Reload interval in milliseconds.
*/
createFetcher: function(url, api, fetchInterval) {
var self = this;
//console.log('processing joke fetcher for url: ' + url + ' - Interval: ' + fetchInterval);
if (!validUrl.isUri(url)){
self.sendSocketNotification('INCORRECT_URL', {url:url});
return;
}
var fetcher;
//console.log('processing joke fetcher for url: ' + url + ' - Interval: ' + fetchInterval);
if (typeof self.fetchers[url] === 'undefined') {
console.log('Create new joke fetcher for url: ' + url + ' - Interval: ' + fetchInterval);
fetcher = new JokeFetcher(url, api, fetchInterval);
fetcher.onReceive(function(fetcher) {
//console.log('Broadcast events.');
//console.log(fetcher.events());
self.sendSocketNotification('JOKE_EVENT', {
url: fetcher.url(),
joke: fetcher.joke()
});
});
fetcher.onError(function(fetcher, error) {
self.sendSocketNotification('FETCH_ERROR', {
url: fetcher.url(),
error: error
});
});
self.fetchers[url] = fetcher;
} else {
//console.log('Use exsisting news fetcher for url: ' + url);
fetcher = self.fetchers[url];
fetcher.broadcastEvents();
}
fetcher.startFetch();
}
});