-
Notifications
You must be signed in to change notification settings - Fork 196
/
file.js
379 lines (357 loc) · 11 KB
/
file.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
var path = require('path');
var fs = require('fs');
var params = require('./params');
var yauzl = require('yauzl');
var unzipEmbeddedFileTypes = ['.xlsx', '.ods'];
var yazl = require('yazl');
var debug = require('debug')('carbone');
var file = {
/**
* is Zipped return callback(true) if the file is zipped
* @param {String} filePath file path
* @param {Function} callback(err, isZipped)
*/
isZipped : function (filePath, callback) {
var _buf = Buffer.allocUnsafe(10);
fs.open(filePath, 'r', function (err, fd) {
if (err) {
return callback(err, false);
}
fs.read(fd, _buf, 0, 10, 0, function (err, bytesRead, buffer) {
fs.close(fd, function () {
callback(err, (buffer.slice(0, 2).toString() === 'PK'));
});
});
});
},
/**
* Unzip a file
* @param {String} filePath file to unzip
* @param {Function} callback(err, files) files is an array of files ['name':'filename', 'buffer':Buffer]
*/
unzip : function (filePath, callback) {
var _unzippedFiles = [];
var _unzipFn = yauzl.open;
if (Buffer.isBuffer(filePath) === true) {
_unzipFn = yauzl.fromBuffer;
}
_unzipFn(filePath, {lazyEntries : true, decodeStrings : true}, function (err, zipfile) {
if (err) {
return callback(err);
}
zipfile.on('end', function () {
zipfile.close();
return callback(null, _unzippedFiles);
});
zipfile.on('error', callback);
zipfile.readEntry();
zipfile.on('entry', function (entry) {
var _unzippedFile = {
name : entry.fileName,
data : Buffer.from([])
};
_unzippedFiles.push(_unzippedFile);
if (/\/$/.test(entry.fileName)) {
// directory file names end with '/'
zipfile.readEntry();
}
else {
zipfile.openReadStream(entry, function (err, readStream) {
if (err) {
zipfile.close();
return callback(err);
}
var buffers = [];
readStream.on('data', function (data) {
buffers.push(data);
});
readStream.on('end', function () {
_unzippedFile.data = Buffer.concat(buffers);
zipfile.readEntry();
});
readStream.on('error', function (err) {
zipfile.close();
return callback(err);
});
});
}
});
});
},
/**
* Zip a group of files
* @param {Array} files files is an array of files ['name':'filename', 'data':Buffer]
* @param {Function} callback(err, result) result is a buffer (the zip file)
*/
zip : function (files, callback) {
var _buffer = [];
var _zip = new yazl.ZipFile();
_zip.outputStream.on('data', function (data) {
_buffer.push(data);
});
_zip.outputStream.on('error', function (err) {
debug('Error when building zip file ' + err);
});
_zip.outputStream.on('end', function () {
var _finalBuffer = Buffer.concat(_buffer);
callback(null, _finalBuffer);
});
for (var i = 0; i < files.length; i++) {
var _file = files[i];
if (_file.name.endsWith('/') === true) {
_zip.addEmptyDirectory(_file.name);
}
else {
_zip.addBuffer(Buffer.from(_file.data), _file.name);
}
}
_zip.end();
},
/**
* Open a template (zipped or not). It will find the template and convert the buffer into strings if it contains xml
* @param {String} templateId template name (with or without the path)
* @param {Function} callback(err, template)
*/
openTemplate : function (templateId, callback) {
var _template = {
isZipped : false,
filename : templateId,
embeddings : [],
files : []
};
// security, remove access on parent directory
// if (/\.\./.test(path.dirname(templateId)) === true) {
// return callback('access forbidden');
// }
// and then use path instead of resolve
var _templateFile = path.resolve(params.templatePath, templateId);
file.isZipped(_templateFile, function (err, isZipped) {
if (err) {
return callback(err, _template);
}
if (isZipped === true) {
_template.isZipped = true;
var _filesToUnzip = [{
name : '',
data : _templateFile
}];
return unzipFiles(_template, _filesToUnzip, callback);
}
else {
fs.readFile(_templateFile, 'utf8', function (err, data) {
var _file = {
name : path.basename(templateId),
data : data,
isMarked : true,
parent : ''
};
_template.files.push(_file);
return callback(err, _template);
});
}
});
},
/**
* Check the extension of template
* @param {Object} template Template to analyze
*/
detectType : function (template) {
if (this._checkWordInFilename(template, 'word/')) {
return 'docx';
}
if (this._checkWordInFilename(template, 'xl/')) {
return 'xlsx';
}
if (this._checkWordInFilename(template, 'ppt/')) {
return 'pptx';
}
if (this._checkMimetypeFile(template, 'application/vnd.oasis.opendocument.text')) {
return 'odt';
}
if (this._checkMimetypeFile(template, 'application/vnd.oasis.opendocument.spreadsheet')) {
return 'ods';
}
if (this._checkMimetypeFile(template, 'application/vnd.oasis.opendocument.presentation')) {
return 'odp';
}
if (this._isXHTMLFile(template)) {
return 'xhtml';
}
if (this._isHTMLFile(template)) {
return 'html';
}
if (this._isXMLFile(template)) {
return 'xml';
}
var _extname = path.extname(template.filename).slice(1);
if (template.isZipped === false && _extname !== '') {
return _extname;
}
return null;
},
/**
* Check if the file is a XML file
* @param {Object} template File content to analyze
*/
_isXMLFile : function (template) {
for (var i = 0; i < template.files.length; i++) {
var _trimmedTemplate = template.files[i].data.trim();
if (_trimmedTemplate.startsWith('<')) {
return true;
}
}
return false;
},
/**
* Check if the file is an XHTML file
* @param {Object} template File content to analyze
*/
_isXHTMLFile : function (template) {
for (var i = 0; i < template.files.length; i++) {
var _trimmedTemplate = template.files[i].data.trim();
var _xmlnsRegex = /<html xmlns="/gm;
if (_trimmedTemplate.startsWith('<!DOCTYPE')) {
if (_xmlnsRegex.test(_trimmedTemplate)) {
return true;
}
}
}
return false;
},
/**
* Check if the file is an HTML file
* @param {Object} template File content to analyze
*/
_isHTMLFile : function (template) {
for (var i = 0; i < template.files.length; i++) {
var _trimmedTemplate = template.files[i].data.trim();
var _htmlRegex = /<html/gm;
if (_trimmedTemplate.startsWith('<!DOCTYPE')) {
if (_htmlRegex.test(_trimmedTemplate)) {
return true;
}
}
}
return false;
},
/**
* Check if a string exists in a mimetype file
* @param {Object} template Template object if unzipped. Else it's a string
* @param {String} string String to match in mimetype file
*/
_checkMimetypeFile : function (template, string) {
for (var i = 0; i < template.files.length; i++) {
if (template.files[i].name === 'mimetype') {
if (template.files[i].data.toString() === string) {
return true;
}
return false;
}
}
return false;
},
/**
* Check if a string is included in one of the filename
* @param {Object} template Template object if unzipped. Else it's a string
* @param {String} string String to check
*/
_checkWordInFilename : function (template, string) {
for (var i = 0; i < template.files.length; i++) {
if (template.files[i].name.startsWith(string)) {
return true;
}
}
return false;
},
/**
* Transform a report object into a zipped buffer (if it is a docx, odt, ...) or a string (it if is a basic xml...)
* @warning `report`is modified
* @param {Object} report report object. Example: {'isZipped': true, files:[{'name': 'bla', 'data': 'buffer or string'}]}
* @param {Function} callback(err, data) data can be a buffer (docx,...) or a string (xml)
*/
buildFile : function (report, callback) {
if (report.isZipped===true) {
return zipFiles(report.files, callback);
}
else {
if (report.files.length !== 1) {
throw Error('This report is not zipped and does not contain exactly one file');
}
return callback(null, report.files[0].data);
}
}
};
/**
* Recursive function, which unzip embedded files if necessary
* @param {Object} template
* @param {Array} filesToUnzip
* @param {Function} callback(err, template)
*/
function unzipFiles (template, filesToUnzip, callback) {
if (filesToUnzip.length === 0) {
return callback(null, template);
}
var _fileToUnzip = filesToUnzip.pop();
file.unzip(_fileToUnzip.data, function (err, files) {
if (err) {
return callback(err, template);
}
for (var i = 0; i < files.length; i++) {
var _file = files[i];
var _extname = path.extname(_file.name);
_file.isMarked = false;
_file.parent = _fileToUnzip.name;
if (_extname === '.xml' || _extname === '.rels') {
_file.isMarked = true;
_file.data = _file.data.toString();
template.files.push(_file);
}
// only unzip first level
else if (_file.parent === '' && unzipEmbeddedFileTypes.indexOf(_extname) !== -1) {
template.embeddings.push(_file.name);
filesToUnzip.push(_file);
}
else {
template.files.push(_file);
}
}
return unzipFiles(template, filesToUnzip, callback);
});
}
/**
* Recursive function, which zip all embedded file first, and the whole file at the end
* @param {Array} filesToZip
* @param {Function} callback(err, buffer)
*/
function zipFiles (filesToZip, callback) {
var _previousParentName = null;
var _index = filesToZip.length - 1;
for (; _index >= 0; _index--) {
var _file = filesToZip[_index];
if (_file.parent !== _previousParentName && _previousParentName !== null) {
break;
}
if (Buffer.isBuffer(_file.data) === false) {
try {
_file.data = Buffer.from(_file.data, 'utf8');
}
catch (e) {
_file.data = Buffer.from('', 'utf8');
}
}
_previousParentName = _file.parent;
}
var _groupOfFileToZip = filesToZip.splice(_index + 1);
file.zip(_groupOfFileToZip, function (err, buffer) {
if (filesToZip.length === 0 || err) {
return callback(err, buffer);
}
filesToZip.unshift({
name : _previousParentName,
data : buffer,
parent : ''
});
return zipFiles(filesToZip, callback);
});
}
module.exports = file;