-
Notifications
You must be signed in to change notification settings - Fork 2
/
node_helper.js
68 lines (60 loc) · 2.47 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
/* Magic Mirror
* Module: MMM-XKCD
*
* By jupadin
* MIT Licensed.
*/
const NodeHelper = require('node_helper');
const request = require('request');
module.exports = NodeHelper.create({
start: function() {
this.config = null;
},
socketNotificationReceived: function(notification, payload) {
var self = this;
if (notification === "SET_CONFIG") {
self.config = payload;
}
if (self.config.dailyJSONURL) {
self.getComic();
}
},
getComic: function() {
const self = this;
const comicJSONURL = self.config.dailyJSONURL;
request(comicJSONURL, function(error, response, body) {
if (error || (response.statusCode != 200)) {
return;
}
// If we are not replacing "old" comics with random ones
if (!self.config.randomComic) {
self.sendSocketNotification("COMIC", JSON.parse(body));
return;
}
const date = new Date();
const dayOfWeek = date.getDay();
// Otherwise select a random comic based on the day of week (Since there are only new comics on specific days)
// New comics appear on Monday, Wednesday and Friday.
if (!self.config.alwaysRandom && (dayOfWeek == 1 || dayOfWeek == 3 || dayOfWeek == 5)) {
self.sendSocketNotification("COMIC", JSON.parse(body));
return;
} else {
const comic = JSON.parse(body);
// Math.random() returns a number between 0 and 1 (exclusive),
// multiplied by the current comic number to get a "real" random number,
// increased by 1 before rounding the number
// - Since a number below 1 may multiplied by 1, would still be below 1 and floored to 0 (which would be the current comic).
const randomNumber = Math.floor((Math.random() * comic.num) + 1);
const randomURL = "https://xkcd.com/" + randomNumber + "/info.0.json";
request(randomURL, function (error, response, body) {
if (error || (response.statusCode != 200)) {
return;
}
self.sendSocketNotification("COMIC", JSON.parse(body));
return;
});
}
});
setTimeout(function() { self.getComic(); }, self.config.updateInterval);
},
})