forked from ralyodio/kimsufi-alert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·238 lines (188 loc) · 5.48 KB
/
index.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env node
var request = require('request-promise');
var _ = require('lodash');
var nodemailer = require('nodemailer');
var fs = require('fs');
var hdiff = require('hdiff');
var cfg = require('./config.json');
var cmd = require('commander');
var provider;
//arguments
cmd
.option('-p, --provider [type]', 'Server provider to run alerts for', 'kimsufi')
.option('-f, --force', 'Force a run regardless of last run', false)
.option('-d, --debug', 'Output debugging messages', false)
.option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
.parse(process.argv);
//set provider
provider = require('./'+cmd.provider+".json");
if ( cmd.verbose > 2 ) console.dir(provider);
check();
function increaseVerbosity(v, total) {
return total + 1;
}
function check(){
request({ json: true, uri: provider.api })
.then(function(data){
parse(data);
})
.catch(function(err){
console.error(err);
})
}
function isEqual(prev, curr){
//var isEq = JSON.stringify(prev) == JSON.stringify(curr) || _.isEqual(prev, curr);
var isEq = _.isEqual(prev, curr);
if ( cmd.verbose > 1 ) {
console.log('Previous:', prev);
console.log('Current: ', curr);
}
if ( cmd.verbose ) console.log('isEqual', isEq);
return isEq;
}
function parse(data){
var results = [];
switch(cmd.provider){
case 'kimsufi':
results = parseKimsufi(data);
break;
}
//save the results
getJson('./tmp/last-run', function(lastResults){
if ( !cmd.force && isEqual(lastResults, results) ) {
if ( cmd.verbose ) console.log('This run produced same results as last run.');
return;
}
saveJson('./tmp/last-run', results, function(err){
if ( err ) {
console.error('Could not save last run data');
}
sendNotifications(results);
});
});
}
function parseKimsufi(data){
var items = data.answer.availability;
var results = [];
//loop over all results
items.forEach(function(item){
//only check my servers
cfg.kimsufi.servers.forEach(function(myServer){
//is this item one of my servers?
if ( item.reference === provider.serverMap[myServer] ) {
//only check my zones
cfg.kimsufi.zones.forEach(function(myZone){
var zone = _.where(item.zones, { zone: myZone }).shift() || false;
if ( !zone || zone.availability === 'unavailable' ) {
return;
}
results.push({
server: {
code: item.reference,
name: myServer
},
zone: {
code: myZone,
location: provider.zoneMap[myZone]
},
status: zone.availability
});
});
}
});
});
return results;
}
function sendNotifications(results){
sendEmail(results);
sendSms(results);
}
function getMessage(results){
var text = [];
results.forEach(function(item){
text.push('server: ' + item.server.name);
text.push('code: ' + item.server.code);
text.push('zone: ' + item.zone.code);
text.push('location: ' + item.zone.location);
text.push('status: ' + item.status);
text.push('\n');
});
text.push('Visit kimsufi at http://kimsufi.com');
text.push('\n');
return text;
}
function sendEmail(results){
if ( !results.length || !cfg.email.enabled ) return;
var user = process.env[cfg.env.smtp.user];
var pass = process.env[cfg.env.smtp.pass];
var host = cfg.env.smtp.host;
var port = cfg.env.smtp.port;
if ( !user || !pass || !host || !port ) {
console.error('Please set `SMTP_USER` and `SMTP_PASS` environment variables.');
return;
}
var transporter = nodemailer.createTransport({
host: host,
port: port,
// service: 'Gmail', //see https://github.com/andris9/nodemailer-wellknown#supported-services
auth: {
user: user,
pass: pass
}
});
var text = getMessage(results);
var mailOptions = {
from: cfg.email.from,
to: cfg.email.to,
subject: cfg.email.subject,
text: text.join('\n')
};
transporter.sendMail(mailOptions, function(err, data){
if (err) return console.trace(err);
if ( cmd.verbose ) console.log('Email sent: ' + data.response);
});
}
function sendSms(results){
if ( !results.length || !cfg.sms.enabled ) return;
var sid = process.env[cfg.env.sms.sid];
var auth = process.env[cfg.env.sms.auth];
if ( !sid || !auth ) {
console.error('Please set `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` environment variables.');
return;
}
var client = require('twilio')(sid, auth);
var text = getMessage(results);
client.sendMessage({
to: cfg.sms.to, // Any number Twilio can deliver to
from: cfg.sms.from, // A number you bought from Twilio and can use for outbound communication
body: text.join('\n') // body of the SMS message
}, function(err, data) { //this function is executed when a response is received from Twilio
if ( err ) return console.trace(err);
// "responseData" is a JavaScript object containing data received from Twilio.
// A sample response from sending an SMS message is here (click "JSON" to see how the data appears in JavaScript):
// http://www.twilio.com/docs/api/rest/sending-sms#example-1
if ( cmd.verbose ) console.log('SMS sent from: ', data.from); // outputs "+14506667788"
//console.log(data.body); // outputs "word to your mother."
});
}
function saveJson(file, data, cb){
var dir = './tmp';
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
fs.writeFile(file+'.json', JSON.stringify(data), function(err) {
if (err) {
console.trace(err);
return cb(err);
}
cb();
});
}
function getJson(file, cb){
if (fs.existsSync(file+'.json')) {
var data = require(file+'.json');
if ( cmd.verbose ) console.log('Loaded last run from %s', file);
return cb(data);
}
cb();
}