-
Notifications
You must be signed in to change notification settings - Fork 0
/
attapis.js
612 lines (558 loc) · 18.8 KB
/
attapis.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
const axios = require("axios");
const fs = require("fs-extra");
const FormData = require('form-data');
var PDFImage = require("pdf-image").PDFImage;
const logr = require("./logging");
const path = require("path");
const mkdirp = require("mkdirp");
const xml2js = require('xml2js');
const urihelper = require("./utils/UriHelper");
const generalhelper = require("./utils/GeneralHelper");
const componentsHelper = require("./utils/ComponentsHelper");
const servicehelper = require("./utils/ServiceHelper");
const constants = require("./constants");
const generalConfigs = require("./configs/generalConfigs");
/**
* Restructures the formObject to a standard form.
* @param {object} req.body object
*/
const constructFormObject = (bodyObject) => {
var formObject = bodyObject;
var newObj = Object.assign({}, formObject);
for (const key in formObject) {
if (key.startsWith("doc")) {
newObj[key] = JSON.parse(formObject[key]);
}
}
return formObject = {
pkgIdentity: newObj,
pkgAttachments: JSON.parse(formObject["pkgAttachments"])
};
};
/**
* Receives the submitted data. This particular API expects multipart form data.
* @param {*} req
* @param {*} res
* @param {*} next
*/
const receiveFilesSubmitData = (req, res, next) => {
// convert the formdata multipart object to use the json object form expected in formObject.
console.log(" IN: receiveFilesSubmitData");
res.locals.formObject = constructFormObject(req.body) ;
res.locals.formFiles = req.files ;
next();
};
/**
* Get the next file index available for embeddedContents
* Checks components stored in eXist, not in the filesystem.
* We allow only upto MAX_ATTACHMENTS (Default = 10)
*
* @param {*} existing components
*/
const getFileIndexDB = (components) => {
let ind = 1;
let indices = components.map(comp => comp.index);
while (ind <= constants.MAX_ATTACHMENTS) {
if (indices.includes(ind)) {
ind += 1;
} else {
break;
}
}
return ind;
};
/**
* Writes the uploaded attachment to the filesystem.
*
* @param {*} file parameters
* @param {*} response message
*/
const writeFile = (fileParams, responseMsg) => {
const {index, newPath, newFileName, buffer, attTitle, embeddedIri, origName, fileExt} = fileParams;
return new Promise(function(resolve, reject) {
fs.writeFile(path.join(newPath, newFileName), buffer, function(err) {
if (err) {
logr.error(generalhelper.serverMsg("ERROR while writing to file "), err) ;
responseMsg.step_1.status = "failure";
responseMsg.step_1.msg.push(
{
"originalname": origName,
"err": err
}
);
reject(err);
} else {
logr.info(generalhelper.serverMsg(" File was written to file system "));
responseMsg.step_1.msg.push(
{
"index": index,
"showAs": attTitle,
"iriThis": embeddedIri,
"origFileName": origName,
"fileName": newFileName,
"fileType": fileExt,
"type": "embedded"
}
);
responseMsg.step_1.status = "write_to_fs_success";
resolve(responseMsg);
}
});
});
};
/**
* Writes a binary file to file system.
* Single uploads only, they are processed from the file
* provided by multer
*
* @param {*} req
* @param {*} res
* @param {*} next
*/
const writeSubmittedFiletoFS = (req, res, next) => {
console.log(" IN: writeSubmittedFiletoFS", res.locals.formFiles.length,
res.locals.formObject.pkgIdentity["docIri"].value);
let aknObj = res.locals.formObject.pkgIdentity;
let attachments = res.locals.formObject.pkgAttachments.value;
let iri = aknObj["docIri"].value;
let formFile = res.locals.formFiles[0];
let arrIri = iri.split("/");
let subPath = arrIri.slice(1, arrIri.length - 1 ).join("/");
let newPath = path.join(constants.AKN_ATTACHMENTS(), subPath);
// to fix
//let aknFileName = urihelper.fileNameFromIRI(iri, "doc");
var responseMsg = {
"step_1": {"status": "", "msg": [] },
"step_2": {"status": "", "msg": [] }
};
if (formFile === undefined) {
// There is no file upload. This is an edit operation.
const embeddedIri = `${iri}_${aknObj["index"]}`;
const newFileName = `${urihelper.fileNamePrefixFromIRI(iri)}_${aknObj["index"]}${aknObj["fileType"]}`;
responseMsg.step_1.msg.push(
{
"index": aknObj["index"],
"showAs": aknObj["title"],
"iriThis": embeddedIri,
"origFileName": aknObj["fileName"],
"fileName": newFileName,
"fileType": aknObj["fileType"],
"type": "embedded"
}
);
responseMsg.step_1.status = "write_to_fs_success";
res.locals.binaryFilesWriteResponse = responseMsg;
next();
} else {
mkdirp(newPath, function(err) {
if (err) {
logr.error(generalhelper.serverMsg(" ERROR while creating folder "), err) ;
responseMsg.step_1.status = "failure";
responseMsg.step_1.msg.push(
{
"originalname": formFile.originalname,
"err": err
}
);
res.locals.binaryFilesWriteResponse = responseMsg;
next();
} else {
const fileParams = {
index: aknObj["index"],
attTitle: aknObj["title"],
origName: formFile.originalname,
mimeType: formFile.mimetype,
buffer: formFile.buffer,
fileExt: path.extname(formFile.originalname),
filePrefix: urihelper.fileNamePrefixFromIRI(iri),
newPath: newPath,
};
//Generate index for new uploads.
if (!fileParams.index) {
fileParams.index = getFileIndexDB(attachments);
}
fileParams.embeddedIri = `${iri}_${fileParams.index}`;
fileParams.newFileName = `${fileParams.filePrefix}_${fileParams.index}${fileParams.fileExt}`;
writeFile(fileParams, responseMsg)
.then(result => {
console.log(" RESPONSE MSG = ", JSON.stringify(result));
res.locals.binaryFilesWriteResponse = responseMsg;
next();
})
.catch(err => {
res.locals.binaryFilesWriteResponse = responseMsg;
console.log(err);
});
}
});
}
};
const addAttInfoToAknObject = (req, res, next) => {
console.log(" IN: addAttInfoToAknObject");
const writeResponse = res.locals.binaryFilesWriteResponse;
var attachments = res.locals.formObject.pkgAttachments.value || [];
if (writeResponse.step_1.status === "write_to_fs_success") {
// see msg object shape below in comment.
const writeInfo = writeResponse.step_1.msg[0];
/*
responseMsg.step_1.msg.push (
{
'title': attTitle,
'originalname': origName,
'newname': newFileName,
'extension': fileExt,
'iri': embeddedIri
}
)
;
*/
var pos = componentsHelper.posOfComp(writeInfo.index, attachments);
//Case Update: Remove the old item before pushing the new one.
if (pos > -1) {
attachments.splice(pos, 1);
}
attachments.push(writeInfo);
}
res.locals.attPackage = {
"docIri": res.locals.formObject.pkgIdentity["docIri"].value,
"attachments": attachments
};
res.locals.returnResponse = {success: "finished"};
next();
};
/**
* Receives the submitted data.
* Data: attachment info to be removed and parent document data.
* @param {*} req
* @param {*} res
* @param {*} next
*/
const receiveAttSubmitData = (req, res, next) => {
console.log(" IN: receiveAttSubmitData");
res.locals.emDoc = req.body.data.emDoc;
res.locals.formObject = req.body.data.pkg;
next();
};
/**
* Removes the given file from the filesystem.
*
* @param {*} full path
* @param {*} response message
*/
const removeFile = (fullPath, responseMsg) => {
return new Promise(function(resolve, reject) {
fs.unlink(fullPath, (err) => {
if (err) {
logr.error(generalhelper.serverMsg("ERROR while removing file "), err);
responseMsg.step_1.status = "failure";
responseMsg.step_1.msg.push(
{
"File": fullPath,
"err": err
}
);
reject(err);
} else {
logr.info(generalhelper.serverMsg(" File was written to file system "));
responseMsg.step_1.msg.push(
{
"File": fullPath
}
);
responseMsg.step_1.status = "remove_from_fs_success";
resolve(responseMsg);
}
});
});
};
/**
* Remove attachment from FS.
*/
const removeAttFromFS = (req, res, next) => {
console.log("IN: removeAttFromFS");
let fullPath = getAttFSPath(res.locals.emDoc, res.locals.formObject);
var responseMsg = {
"step_1": {"status": "", "msg": [] }
};
removeFile(fullPath, responseMsg)
.then(result => {
console.log(" RESPONSE MSG = ", JSON.stringify(result));
res.locals.binaryFileRemoveResponse = responseMsg;
next();
})
.catch(err => {
res.locals.binaryFileRemoveResponse = responseMsg;
console.log(err);
});
};
const deleteAttFromFS =(attachments) => {
console.log("attachments are " + JSON.stringify(attachments));
for(let att of attachments){
let arrIri = att.iriThis.split("/");
let subPath = arrIri.slice(1, arrIri.length - 1 ).join("/");
let attPath = path.join(constants.AKN_ATTACHMENTS(), subPath);
let fileExt = path.extname(att.origFileName);
let filePrefix = urihelper.fileNamePrefixFromIRI(att.iriThis);
let attFileName = `${filePrefix}${fileExt}`;
let fullPath = path.join(attPath, attFileName);
var responseMsg = {
"step_1": {"status": "", "msg": [] }
};
removeFile(fullPath, responseMsg)
.then(result => {
console.log(" RESPONSE MSG = ", JSON.stringify(result));
})
.catch(err => {
console.log(err);
});
}
}
/**
* Remove attachment from attachments list.
*/
const removeAttInfoFromAknObject = (req, res, next) => {
console.log("IN: removeAttInfoFromAknObject");
const removeResponse = res.locals.binaryFileRemoveResponse;
var attachments = res.locals.formObject.pkgAttachments.value || [];
if (removeResponse.step_1.status === "remove_from_fs_success") {
const fileInfo = res.locals.emDoc;
var pos = componentsHelper.posOfComp(fileInfo.index, attachments);
//Case Remove: Remove the attachment.
if (pos > -1) {
attachments.splice(pos, 1);
}
}
res.locals.attPackage = {
"docIri": res.locals.formObject.pkgIdentity["docIri"].value,
"attachments": attachments
};
res.locals.returnResponse = {success: "finished"};
next();
};
/**
* Saves the attachments for a particular document to the database
* @param {*} req
* @param {*} res
* @param {*} next
*/
const saveAttToXmlDb = (req, res, next) => {
console.log(" IN: saveAttToXmlDb");
const saveAttApi = servicehelper.getApi("xmlServer", "saveAttachments");
const {url, method} = saveAttApi;
axios({
method: method,
url: url,
data: res.locals.attPackage
}).then(
(response) => {
res.locals.returnResponse = response.data;
next();
}
).catch(
(err) => {
res.locals.returnResponse = err;
next();
}
);
};
/**
* Retrieves the FS full path of an existing attachment.
*/
const getAttFSPath = (emDoc, pkg) => {
console.log(" IN: getAttFSPath");
let aknObj = pkg.pkgIdentity;
let iri = aknObj["docIri"].value;
let arrIri = iri.split("/");
let subPath = arrIri.slice(1, arrIri.length - 1 ).join("/");
let attPath = path.join(constants.AKN_ATTACHMENTS(), subPath);
let fileExt = path.extname(emDoc.origFileName);
let filePrefix = urihelper.fileNamePrefixFromIRI(iri);
let attFileName = `${filePrefix}_${emDoc.index}${fileExt}`;
let fullPath = path.join(attPath, attFileName);
return fullPath
}
const contentTypes = {
".pdf": "application/pdf",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".png": "image/png"
}
/**
* Read attachment from FS.
*/
const readAtt = (req, res, next) => {
let iri = req.query.iri;
let arrIri = iri.split("/");
let subPath = arrIri.slice(1, arrIri.length - 1 ).join("/");
let attPath = path.join(constants.AKN_ATTACHMENTS(), subPath);
let fileExt = path.extname(req.query.originalFileName);
let filePrefix = urihelper.fileNamePrefixFromIRI(iri);
let attFileName = `${filePrefix}_${req.query.index}${fileExt}`;
let fullPath = path.join(attPath, attFileName);
debugger;
fs.readFile(fullPath, function (err, data){
res.contentType(contentTypes[fileExt]);
res.send(data);
})
};
/**
* Calls the extractor service to get text for the attachment.
*/
const extractText = (req, res, next) => {
console.log(" IN: extractText");
let fullPath = getAttFSPath(res.locals.emDoc, res.locals.formObject);
const extractTextApi = servicehelper.getApi("extractText", "pdf2txt");
const {url, method} = extractTextApi;
let data = new FormData();
data.append('file', fs.createReadStream(fullPath));
axios({
method: method,
url: url,
data: data,
headers: data.getHeaders()
}).then(
(response) => {
res.locals.text = response.data["text"];
res.locals.returnResponse = {
"step_1": {"status": "extract_text_success"}
};
next();
}
).catch(
(err) => {
res.locals.returnResponse = {
"step_1": {"status": "failure"}
};
next();
}
);
};
/**
* Inject tags into the fulltext xml
*/
const injectTags = (filepath, xml, tags) => {
return new Promise(function(resolve, reject) {
xml2js.parseString(xml, (error, ftJSON) => {
if (error) reject(err);
else {
ftJSON.pages.tags = tags.join(",");
let builder = new xml2js.Builder();
const resultXML = builder.buildObject(ftJSON);
resolve(resultXML);
}
});
});
}
/**
* Get gawati-tagit compliant input filename from fulltext filepath
*/
const getTagitFilename = (ftFilepath) => {
console.log(" IN: getTagitFilename");
let fname = path.basename(ftFilepath, path.extname(ftFilepath))
fname = fname.replace(/main.*/, "main") + '.xml';
return fname;
}
/**
* Calls the tagit service to get tags for the attachment.
*/
const tagText = (req, res, next) => {
console.log(" IN: tagText");
let ftXML = res.locals.text;
const extractTextApi = servicehelper.getApi("tagText", "tag");
const {url, method} = extractTextApi;
const ftFilepath = getAttFSPath(res.locals.emDoc, res.locals.formObject);
const tagsInputFile = getTagitFilename(ftFilepath);
let data = new FormData();
data.append('file', new Buffer(ftXML), { filename: tagsInputFile });
res.locals.returnResponse = { "step_2": {"status": "failure"} };
axios({
method: method,
url: url,
data: data,
headers: data.getHeaders()
}).then((response) => {
if (response.data.hasOwnProperty('tags')) {
tags = [res.locals.emDoc.showAs].concat(response.data["tags"]);
return injectTags(ftFilepath, ftXML, tags);
}
}).then((xmlWithTags) => {
res.locals.text = xmlWithTags;
res.locals.returnResponse = {
"step_2": {"status": "tag_text_success"}
};
next();
}).catch((err) => {
console.log(err);
next();
});
};
/**
* Saves the full text for attachment to the database
* @param {*} req
* @param {*} res
* @param {*} next
*/
const saveFTtoXmlDb = (req, res, next) => {
console.log(" IN: saveFTtoXmlDb");
const {iriThis} = res.locals.emDoc;
let iri = iriThis.replace('/akn', '/akn_ft');
if (res.locals.returnResponse.step_2.status === 'tag_text_success') {
const saveFTApi = servicehelper.getApi("xmlServer", "saveXml");
const {url, method} = saveFTApi;
let data = {
'fileXml': urihelper.fileNameFromIRI(iri, "xml"),
'update': true,
'iri': iri,
'data': res.locals.text,
}
axios({
method: method,
url: url,
data: data
}).then(
(response) => {
res.locals.returnResponse = response.data;
next();
}
).catch(
(err) => {
res.locals.returnResponse = err;
next();
}
);
} else {
res.locals.returnResponse = {
'error': { 'code': iri, 'message': 'Error while extracting and tagging text' }
}
next();
}
};
/**
*
* @param {*} req
* @param {*} res
* @param {*} next
*/
const returnResponse = (req, res) => {
console.log(" IN: returnResponse");
res.json(res.locals.returnResponse);
};
module.exports = {
//Create and Update attachment methods
receiveFilesSubmitData: receiveFilesSubmitData,
writeSubmittedFiletoFS: writeSubmittedFiletoFS,
addAttInfoToAknObject: addAttInfoToAknObject,
//Remove attachment methods
receiveAttSubmitData: receiveAttSubmitData,
removeAttFromFS: removeAttFromFS,
removeAttInfoFromAknObject: removeAttInfoFromAknObject,
deleteAttFromFS: deleteAttFromFS,
//Read attachment method
readAtt : readAtt,
//Extract text from attachment methods
extractText: extractText,
tagText: tagText,
saveFTtoXmlDb: saveFTtoXmlDb,
//Common methods
saveAttToXmlDb: saveAttToXmlDb,
returnResponse: returnResponse
};