This repository has been archived by the owner on Jan 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
277 lines (245 loc) · 8.11 KB
/
app.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
var queue = require('queue-async'),
nodemailer = require('nodemailer'),
tvConfig = {
username: process.env.TV_USER,
password: process.env.TV_PASSWORD,
client_id: process.env.TV_CLIENT_ID,
client_secret: process.env.TV_CLIENT_SECRET
},
ftpAuth = process.env.FTP_USER + ':' + process.env.FTP_PASSWORD,
tv = require('trackvia')(tvConfig),
configs = require('./config.json'),
CSV = require('comma-separated-values'),
fs = require('fs'),
_ = require('underscore'),
tasks = queue(1),
emailConfig = {
to: process.env.EMAIL_TO,
from: process.env.EMAIL_FROM,
host: process.env.EMAIL_HOST,
username: process.env.EMAIL_USER,
password: process.env.EMAIL_PASSWORD,
subject: '[CCHP Automation] Files Updated',
message: "<p>The automation script just finished. Here's the log:</p><p>------</p>"
},
mailer = nodemailer.createTransport({
service: process.env.EMAIL_SERVICE,
auth: {
user: emailConfig.username,
pass: emailConfig.password
}
}),
images = [],
logs = '',
log = console.log,
timeout = 1000 * 30; // 30 seconds
// Capture console.log
console.log = function(){
logs += '<p>' + Array.prototype.slice.call(arguments).join(' ') + '</p>';
log.apply(this, arguments)
}
// Queue config tasks
configs.forEach(function(config) {
tasks.defer(runTask, config);
});
// Send notifications
tasks.awaitAll(function(err, data) {
if (err) {
console.warn(err);
}
var subject = (images.length) ? 'Import Error: ' + emailConfig.subject :
'Success: ' + emailConfig.subject;
var mailOptions = {
from: emailConfig.from || emailConfig.username,
to: emailConfig.to,
subject: subject,
attachments: images,
html: emailConfig.message + logs
};
mailer.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
}
});
});
// Process for each task
function runTask(config, nextTask) {
var input = [],
q = queue();
// Load each source
if (typeof config.source === 'string') config.source = [config.source];
config.sources.forEach(function(source, index) {
q.defer(loadSource, source);
});
q.awaitAll(combineSources);
// Process for loading source files
function loadSource(source, cb) {
var output = '',
downloadRetries = 0,
page = 1,
results = [];
// Download records from TrackVia
if (source.type && source.type.toLowerCase() === 'trackvia') {
getRecords(function(data) {
output = data;
fs.writeFile('./tmp/' + source.name + '.csv', output, function(err) {
if (err) {
cb(err, null);
} else {
cb(null, true);
}
});
});
function getRecords(cb) {
tv.views(source.view, { limit: 100, page: page }, function(err, res) {
if (err) throw err;
if (res.records && res.records.length) {
results = results.concat(res.records);
page = page + 1;
getRecords(cb);
} else {
results = _(results).chain()
.map(function(item) { return item.fields; })
.sortBy(function(item) { return -_(item).size(); })
.value();
var csv = new CSV(results, { header: true, cast: false }).encode()
.replace(/"undefined"/g, '""')
.replace(/<!--tvia_br--><br><!--tvia_br-->/g, '\n');
cb(csv);
}
});
}
} else {
downloadFile();
}
// Download files from FTP server
function downloadFile() {
downloadRetries++;
output = '';
var spawn = require('child_process').spawn,
child = spawn('curl', [
'-s', '--ssl-reqd', '-u', ftpAuth , source.url
], { maxBuffer: 200 * 1024 * 1024 });
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', function (data) { output += data; });
child.stderr.on('data', function (data) { cb(data, null); });
child.on('exit', function (code, signal) {
if (!output.length && downloadRetries < 5) {
setTimeout(downloadFile, timeout);
} else if (!output.length) {
cb('File downloaded from FTP is empty. Is the FTP available?', null);
} else {
fs.writeFile('./tmp/' + source.name + '.csv', output, function(err) {
if (err) {
cb(err, null);
} else {
cb(null, true);
}
});
}
});
}
}
// Handle errors in source files
function combineSources(err, data) {
if (!err && !data) err = 'Sources returned no data.';
if (err) throw err;
runProcess();
}
// Run R script on source files
function runProcess() {
var spawn = require('child_process').spawn,
args = [config.script],
child = spawn('Rscript', args),
output = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', function(data) {
output += data;
});
child.stderr.on('data', function(data) {
console.log(data);
});
child.on('error', function(data) {
throw data;
});
child.on('exit', function(data) {
sendOutput(output);
});
}
// Handle output from R script
function sendOutput(data) {
var exec = require('child_process').exec;
// Save CSV file
fs.writeFile(config.outputFile, data, function(err) {
if (err) throw err;
var xlsFile = config.outputFile.replace(/\.csv$/, '.xls'),
cmd = 'csv2xls "' + config.outputFile + '" -o "' + xlsFile + '"';
console.log('Saved file: ' + config.outputFile);
// Save copy as XLS
exec(cmd, function(stdout, stderr, err) {
if (err) throw err;
console.log('Saved file: ' + xlsFile);
// Upload to FTPS
var spawn = require('child_process').spawn,
child = spawn('curl', [
'-s', '--ssl-reqd',
'-T', xlsFile,
'-u', ftpAuth,
'ftp://camdenhie.careevolution.com/CCHPProcessed/'
], { maxBuffer: 200 * 1024 * 1024 }),
output = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) { cb(data, null); });
child.on('exit', function (code, signal) {
console.log('Uploaded file to FTP: ' + xlsFile);
// Upload to TrackVia
var child = spawn('casperjs', [
'./tv-upload.js',
config.output.table,
config.outputFile.replace(/\.csv$/, '.xls'),
config.output.fields
]),
scriptName = config.script.split('/')[1].replace(/\.R$/, ''),
out = '',
err = ''
console.log('Uploading ' + scriptName + ' to table: ' + config.output.tableName);
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', function (data) {
console.log(data.replace(/\[37;41;1m/, '').replace(/\[0m/, ''));
});
child.stderr.on('data', function (data) {
err += data;
console.warn(data);
});
child.on('exit', function (code, signal) {
var errImg = 'tmp/error' + config.output.table + '.jpg';
if (fs.existsSync(errImg)) {
images.push({
filename: config.output.table + '.jpg',
path: errImg,
cid: config.output.table
});
console.log('<img src="cid:' + config.output.table + '"/>');
}
console.log('------');
if (err.length) {
nextTask(err, null);
} else {
nextTask(null, true);
}
});
});
});
});
}
}
process.on('exit', function() {
// Remove temp and output files
require('child_process').exec('srm -sr ./tmp/*');
require('child_process').exec('srm -sr ./output/*');
console.log('Cleaning up temp files');
});