-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
289 lines (248 loc) · 7.52 KB
/
server.js
File metadata and controls
289 lines (248 loc) · 7.52 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
/* global clearTimeout, console, process, require, setTimeout */
(function () {
'use strict';
var exec = require('child_process').exec;
var express = require('express');
var formidable = require('formidable');
var fs = require('fs');
var http = require('http');
var os = require('os');
var unoconv = require('unoconv');
// config
var serverPort = 8084;
var unoconvPort = 8085;
var apiKey = process.env.PDFER_API_KEY;
var maxRetries = 5;
var supportedFiles = [
'csv',
'doc',
'doc6',
'doc95',
'docx',
'met' ,
'odd',
'odg',
'odp',
'odt',
'ott',
'pct',
'pot',
'ppm',
'ppsm',
'ppsx',
'ppt',
'pptm',
'pptx',
'sldm',
'sldx',
'stc',
'sti',
'stp',
'svg',
'sxc',
'sxd',
'sxi',
'wmf',
'xls',
'xls5',
'xls95',
'xlsx',
'xlt',
'xlt5',
'xlt95'
];
// queue variables
var queuedFiles = [];
var processing = false;
var queueTimeout;
// basic authentication middleware
var checkApiKey = function (req, res, next) {
if (!apiKey) return next();
if (req.headers.authorization === 'Bearer ' + apiKey) return next();
if (req.query.authorization === apiKey) return next();
res.status(401);
next('API key incorrect');
};
// kill LibreOffice processes completely
var killLibreOffice = function (cb) {
var command = 'ps aux | grep -i \'LibreOffice.*' + unoconvPort +
'\' | grep -v grep | awk \'{print $2}\'';
exec(command, function (err, stdout) {
if (err || !stdout) return cb();
var pids = stdout.split('\n');
pids.forEach(function (pid) {
if (!pid || !parseInt(pid, 10)) return;
console.info('Killing LibreOffice process:', pid);
try {
process.kill(pid);
} catch (err) {
console.error('Error killing LibreOffice process:', pid);
}
});
cb();
});
};
// load LibreOffice
var startUnoconvListener = function () {
var unoconvListener = unoconv.listen({port: unoconvPort});
unoconvListener.once('close', function () {
// sometimes LibreOffice crashes, so we restart the listener, otherwise after the
// crash it goes back to (re)lauching LibreOffice on every conversion.
killLibreOffice(startUnoconvListener);
});
processing = false;
};
startUnoconvListener();
// check a file exists and delete from disk
var deleteFile = function (filePath) {
fs.access(filePath, function (err) {
if (err) return console.error('Unable to access file for deletion', filePath + ':', err);
fs.unlink(filePath, function (err) {
if (err) return console.error('Unable to delete', filePath + ':', err);
console.info('Successfully deleted', filePath);
});
});
};
// convert document to PDF and save to disk
var generatePdf = function (itemPath, pdfPath, cb) {
var hashFileName;
// try/catch just in case unoconv crashes
try {
unoconv.convert(itemPath, 'pdf', {port: unoconvPort}, function (err, data) {
if (err) {
console.error('Unoconv failed to convert', itemPath + ':', err);
return cb(err);
}
fs.writeFile(pdfPath, data, cb);
});
} catch (err) {
console.error('Unoconv crashed', err);
return cb(err);
}
};
// queue system used to only create one pdf at a time
// unoconv/LibreOffice will crash if too many requests are made at once
var processQueue = function () {
if (!queuedFiles.length) return;
// throttle the process queue attempts
if (processing) {
clearTimeout(queueTimeout);
queueTimeout = setTimeout(function () {
processQueue();
}, 500);
return;
}
var file = queuedFiles.shift();
processing = true;
generatePdf(file.itemPath, file.pdfPath, function (err, hashFileName) {
// retry if there is an error and the file type is supported (within maximum retries limit)
// don't retry when the file could not be opened (not supported)
if (err && err.message && err.message.indexOf('could not be opened') < 0 &&
file.retries < maxRetries) {
file.retries++;
queuedFiles.push(file);
} else if (err) {
file.callback('Error converting the file to PDF');
} else {
file.callback(null, hashFileName);
}
// continue processing the queue
processing = false;
processQueue();
});
};
// add file to queue
var queueFile = function (itemPath, pdfPath, cb) {
queuedFiles.push({
itemPath: itemPath,
pdfPath: pdfPath,
retries: 0,
callback: cb
});
processQueue();
};
// handle conversion requests
var convert = function (req, res) {
var form = new formidable.IncomingForm();
form.keepExtensions = true;
form.hash = 'sha1';
form.parse(req, function(err, fields, files) {
if (err) return res.status(500).send('Error parsing request');
var hashFileName = files.attachment.hash;
var inputPath = files.attachment.path;
var outputPath = os.tmpDir() + '/' + Date.now() + '_' + hashFileName + '.pdf';
var ext = inputPath.substring(inputPath.lastIndexOf('.') + 1, inputPath.length);
// check if file type can be converted to pdf
if (supportedFiles.indexOf(ext) < 0) {
return res.status(415).send('The extension .' + ext + ' is not supported');
}
console.info('Queueing file', files.attachment.name);
// add to queue
queueFile(inputPath, outputPath, function (err) {
deleteFile(inputPath);
if (err) {
console.error('Error converting', files.attachment.name + ':', err);
return res.status(500).send('Error converting file to PDF');
} else {
console.info('Successfully converted', files.attachment.name);
}
// send converted file
res.status(200).sendFile(outputPath, function (err) {
if (err) {
console.error('Error sending PDF file for', files.attachment.name + ':', err);
} else {
console.info('Successfully sent PDF file for', files.attachment.name);
}
deleteFile(outputPath);
});
});
});
};
// simple status page for monitoring
var status = function (req, res) {
console.log('Status request:', queuedFiles.length, 'files queued');
res.status(200).send('Queued files: ' + queuedFiles.length);
};
// simple reset request
var reset = function (req, res) {
console.log('Reset request: Removing', queuedFiles.length, 'files from queue');
res.status(200).send('Removed files: ' + queuedFiles.length);
queuedFiles = [];
processing = false;
};
// start server
var app = express();
var server = http.createServer(app);
server.setTimeout(0);
server.listen(serverPort);
// server status logging
server.on('listening', function () {
console.info('PDF server listening on port', serverPort);
});
server.on('error', function (err) {
console.error('Error starting PDF server on port', serverPort + ':', err.message);
});
// routes
app.route('/convert')
.post(
checkApiKey,
convert
);
app.route('/reset')
.get(
checkApiKey,
reset
);
app.route('/status')
.get(status);
// error handling
app.use(function (errMsg, req, res, next) {
res.send(errMsg);
console.error(errMsg);
});
// 404 error when path is incorrect
app.use(function (req, res) {
res.status(404).send('Page not found');
console.error('Page not found:', req.url);
});
}());