-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathdocument.js
844 lines (757 loc) · 34 KB
/
document.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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
const rp = require('request-promise-native');
const _ = require('lodash');
const defaultLog = require('winston').loggers.get('default');
const mongoose = require('mongoose');
const mime = require('mime-types');
const FlakeIdGen = require('flake-idgen');
const intformat = require('biguint-format');
const fs = require('fs');
const uploadDir = process.env.UPLOAD_DIRECTORY || './uploads/';
const constants = require('../helpers/constants');
const Actions = require('../helpers/actions');
const Utils = require('../helpers/utils');
const MinioController = require('../helpers/minio');
const ENABLE_VIRUS_SCANNING = process.env.ENABLE_VIRUS_SCANNING ? process.env.ENABLE_VIRUS_SCANNING.toLowerCase() == 'true' : false;
const generator = new FlakeIdGen;
var getSanitizedFields = function (fields) {
return _.remove(fields, function (f) {
return (_.indexOf(['displayName',
'_addedBy',
'documentFileName',
'internalExt',
'internalOriginalName',
'displayName',
'labels',
'documentType',
'datePosted',
'dateUploaded',
'dateReceived',
'documentFileSize',
'documentSource',
'eaoStatus',
'internalURL',
'internalMime',
'internalSize',
'checkbox',
'project',
'type',
'documentAuthor',
'documentAuthorType',
'milestone',
'projectPhase',
'legislation',
'description',
'keywords',
'isPublished',
'internalMime',
'isFeatured',
'sortOrder',
'publicHitCount',
'secureHitCount'], f) !== -1);
});
};
exports.protectedOptions = function (args, res,) {
res.status(200).send();
};
exports.publicGet = async function (args, res,) {
// Build match query if on docId route
var query = {};
if (args.swagger.params.docId && args.swagger.params.docId.value) {
query = Utils.buildQuery('_id', args.swagger.params.docId.value, query);
} else if (args.swagger.params.docIds && args.swagger.params.docIds.value && args.swagger.params.docIds.value.length > 0) {
query = Utils.buildQuery('_id', args.swagger.params.docIds.value);
}
if (args.swagger.params.project && args.swagger.params.project.value) {
query = Utils.buildQuery('project', args.swagger.params.project.value, query);
}
// Set query type
_.assignIn(query, { '_schemaName': 'Document' });
try {
var data = await Utils.runDataQuery('Document',
['public'],
query,
getSanitizedFields(args.swagger.params.fields.value), // Fields
null, // sort warmup
null, // sort
null, // skip
null, // limit
false); // count
defaultLog.info('Got document(s):', data);
Utils.recordAction('Get', 'Document', 'public', args.swagger.params.docId && args.swagger.params.docId.value ? args.swagger.params.docId.value : null);
return Actions.sendResponse(res, 200, data);
} catch (e) {
defaultLog.info('Error:', e);
return Actions.sendResponse(res, 400, e);
}
};
exports.unProtectedPost = async function (args, res) {
console.log('Creating new object', args.swagger.params);
if (args.swagger.params._comment && args.swagger.params._comment.value && !mongoose.Types.ObjectId.isValid(args.swagger.params._comment.value)) {
return Actions.sendResponse(res, 400, { });
}
if (args.swagger.params.project && args.swagger.params.project.value && !mongoose.Types.ObjectId.isValid(args.swagger.params.project.value)) {
return Actions.sendResponse(res, 400, { });
}
var _comment = args.swagger.params._comment.value;
var project = args.swagger.params.project.value;
var upfile = args.swagger.params.upfile.value;
var guid = intformat(generator.next(), 'dec');
var ext = mime.extension(args.swagger.params.upfile.value.mimetype);
var tempFilePath = uploadDir + guid + '.' + ext;
try {
console.log('Uploading');
Promise.resolve()
.then(async function () {
if (ENABLE_VIRUS_SCANNING) {
console.log('AVScan');
return Utils.avScan(args.swagger.params.upfile.value.buffer);
} else {
return true;
}
})
.then(async function (valid) {
if (!valid) {
defaultLog.warn('File failed virus check.');
return Actions.sendResponse(res, 400, { 'message': 'File failed virus check.' });
} else {
console.log('writing file.');
fs.writeFileSync(tempFilePath, args.swagger.params.upfile.value.buffer);
console.log('wrote file successfully.');
console.log(MinioController.BUCKETS.DOCUMENTS_BUCKET,
mongoose.Types.ObjectId(project),
upfile.originalname,
tempFilePath);
MinioController.putDocument(MinioController.BUCKETS.DOCUMENTS_BUCKET,
project,
upfile.originalname,
tempFilePath)
.then(async function (minioFile) {
console.log('putDocument:', minioFile);
// remove file from temp folder
fs.unlinkSync(tempFilePath);
console.log('unlink');
var Document = mongoose.model('Document');
var doc = new Document();
// Define security tag defaults
doc.project = mongoose.Types.ObjectId(project);
doc._comment = mongoose.Types.ObjectId(_comment);
doc._addedBy = 'public';
doc._createdDate = new Date();
doc.read = ['sysadmin', 'staff'];
doc.write = ['sysadmin', 'staff'];
doc.delete = ['sysadmin', 'staff'];
doc.internalOriginalName = upfile.originalname;
doc.internalURL = minioFile.path;
doc.internalExt = minioFile.extension;
doc.internalSize = upfile.size;
doc.passedAVCheck = true;
doc.internalMime = upfile.mimetype;
doc.documentSource = 'COMMENT';
doc.displayName = upfile.originalname;
doc.documentFileName = upfile.originalname;
doc.dateUploaded = new Date();
doc.datePosted = new Date();
doc.documentAuthor = args.body.documentAuthor;
doc.documentAuthorType = mongoose.Types.ObjectId(args.body.documentAuthorType);
doc.save()
.then(async function (d) {
defaultLog.info('Saved new document object:', d._id);
var Comment = mongoose.model('Comment');
var c = await Comment.update({ _id: _comment }, { $addToSet: { documents: d._id } });
defaultLog.info('Comment updated:', c);
Utils.recordAction('Post', 'Document', 'public', d._id);
return Actions.sendResponse(res, 200, d);
})
.catch(async function (error) {
console.log('error:', error);
// the model failed to be created - delete the document from minio so the database and minio remain in sync.
MinioController.deleteDocument(MinioController.BUCKETS.DOCUMENTS_BUCKET, doc.project, doc.internalURL);
return Actions.sendResponse(res, 400, error);
});
});
}
});
} catch (e) {
defaultLog.info('Error:', e);
// Delete the path details before we return to the caller.
delete e['path'];
return Actions.sendResponse(res, 400, e);
}
};
exports.protectedHead = function (args, res) {
defaultLog.info('args.swagger.params:', args.swagger.params.auth_payload.realm_access.roles);
// Build match query if on docId route
var query = {};
if (args.swagger.params.docId && args.swagger.params.docId.value) {
query = Utils.buildQuery('_id', args.swagger.params.docId.value, query);
}
if (args.swagger.params._application && args.swagger.params._application.value) {
query = Utils.buildQuery('_application', args.swagger.params._application.value, query);
}
if (args.swagger.params._comment && args.swagger.params._comment.value) {
query = Utils.buildQuery('_comment', args.swagger.params._comment.value, query);
}
// Unless they specifically ask for it, hide deleted results.
if (args.swagger.params.isDeleted && args.swagger.params.isDeleted.value != undefined) {
_.assignIn(query, { isDeleted: args.swagger.params.isDeleted.value });
}
// Set query type
_.assignIn(query, { '_schemaName': 'Document' });
Utils.runDataQuery('Document',
args.swagger.params.auth_payload.realm_access.roles,
query,
['_id',
'read'], // Fields
null, // sort warmup
null, // sort
null, // skip
null, // limit
true) // count
.then(function (data) {
Utils.recordAction('Head', 'Document', args.swagger.params.auth_payload.preferred_username, args.swagger.params.docId && args.swagger.params.docId.value ? args.swagger.params.docId.value : null);
// /api/commentperiod/ route, return 200 OK with 0 items if necessary
if (!(args.swagger.params.docId && args.swagger.params.docId.value) || (data && data.length > 0)) {
res.setHeader('x-total-count', data && data.length > 0 ? data[0].total_items : 0);
return Actions.sendResponse(res, 200, data);
} else {
return Actions.sendResponse(res, 404, data);
}
});
};
exports.protectedGet = async function (args, res) {
defaultLog.info('Getting document(s)');
if (args.swagger.params.docId && args.swagger.params.docId.value && !mongoose.Types.ObjectId.isValid(args.swagger.params.docId.value)) {
return Actions.sendResponse(res, 400, { });
}
var query = {}, skip = null, limit = null, count = false;
// Build match query if on docId route
if (args.swagger.params.docId && args.swagger.params.docId.value) {
_.assignIn(query, { _id: mongoose.Types.ObjectId(args.swagger.params.docId.value) });
} else if (args.swagger.params.docIds && args.swagger.params.docIds.value && args.swagger.params.docIds.value.length > 0) {
query = Utils.buildQuery('_id', args.swagger.params.docIds.value);
}
if (args.swagger.params.project && args.swagger.params.project.value) {
query = Utils.buildQuery('project', args.swagger.params.project.value, query);
}
// Set query type
_.assignIn(query, { '_schemaName': 'Document' });
try {
var data = await Utils.runDataQuery('Document',
args.swagger.params.auth_payload.realm_access.roles,
query,
getSanitizedFields(args.swagger.params.fields.value), // Fields
null, // sort warmup
null, // sort
skip, // skip
limit, // limit
count); // count
Utils.recordAction('Get', 'Document', args.swagger.params.auth_payload.preferred_username, args.swagger.params.docId && args.swagger.params.docId.value ? args.swagger.params.docId.value : null);
defaultLog.info('Got document(s):', data);
return Actions.sendResponse(res, 200, data);
} catch (e) {
defaultLog.info('Error:', e);
return Actions.sendResponse(res, 400, e);
}
};
exports.publicDownload = function (args, res) {
// Build match query if on docId route
var query = {};
if (args.swagger.params.docId && args.swagger.params.docId.value) {
query = Utils.buildQuery('_id', args.swagger.params.docId.value, query);
} else {
return Actions.sendResponse(res, 404, {});
}
// Set query type
_.assignIn(query, { '_schemaName': 'Document' });
Utils.runDataQuery('Document',
['public'],
query,
['internalURL', 'documentFileName', 'internalMime', 'internalExt'], // Fields
null, // sort warmup
null, // sort
null, // skip
null, // limit
false) // count
.then(function (data) {
if (data && data.length === 1) {
var blob = data[0];
// Make the filename returned match dislplay name, not blob name
// make sure the filename is VALID!
// Add project name to front, date uploaded to back if it will fit! 240 chars max
var fileName = blob.documentFileName;
var fileType = blob.internalExt;
if (fileName.slice(- fileType.length) !== fileType) {
fileName = fileName + '.' + fileType;
}
var fileMeta;
// Allow override
if (args.swagger.params.filename) {
fileName = args.swagger.params.filename.value;
}
// clean the filename
fileName = encodeURIComponent(fileName).replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\\/g, '_').replace(/\//g, '_').replace(/%2F/g, '_').replace(/ /g, '_');
// update document public hit count
mongoose.model('Document').findById(args.swagger.params.docId.value)
.then(doc => {
doc.publicHitCount++;
doc.save();
});
// check if the file exists in Minio
return MinioController.statObject(MinioController.BUCKETS.DOCUMENTS_BUCKET, blob.internalURL)
.then(function (objectMeta) {
fileMeta = objectMeta;
// get the download URL
return MinioController.getPresignedGETUrl(MinioController.BUCKETS.DOCUMENTS_BUCKET, blob.internalURL);
}, function () {
return Actions.sendResponse(res, 404, {});
})
.then(function (docURL) {
Utils.recordAction('Download', 'Document', 'public', args.swagger.params.docId && args.swagger.params.docId.value ? args.swagger.params.docId.value : null);
// stream file from Minio to client
// Size is undefined on related documents on pcps
if (!fileMeta) {
return;
}
res.setHeader('Content-Length', fileMeta.size);
res.setHeader('Content-Type', fileMeta.metaData['content-type']);
res.setHeader('Content-Disposition', 'inline;filename="' + fileName + '"');
return rp(docURL).pipe(res);
});
} else {
return Actions.sendResponse(res, 404, {});
}
});
};
exports.protectedDownload = function (args, res) {
var self = this;
self.scopes = args.swagger.params.auth_payload.realm_access.roles;
defaultLog.info('args.swagger.params:', args.swagger.params.auth_payload.realm_access.roles);
// Build match query if on docId route
var query = {};
if (args.swagger.params.docId && args.swagger.params.docId.value) {
query = Utils.buildQuery('_id', args.swagger.params.docId.value, query);
}
// Set query type
_.assignIn(query, { '_schemaName': 'Document' });
Utils.runDataQuery('Document',
args.swagger.params.auth_payload.realm_access.roles,
query,
['internalURL', 'documentFileName', 'internalMime', 'internalExt'], // Fields
null, // sort warmup
null, // sort
null, // skip
null, // limit
false) // count
.then(function (data) {
if (data && data.length === 1) {
var blob = data[0];
var fileName = blob.documentFileName;
var fileType = blob.internalExt;
if (fileName.slice(- fileType.length) !== fileType) {
fileName = fileName + '.' + fileType;
}
var fileMeta;
// update document secure hit count
mongoose.model('Document').findById(args.swagger.params.docId.value)
.then(doc => {
doc.secureHitCount++;
doc.save();
});
// check if the file exists in Minio
return MinioController.statObject(MinioController.BUCKETS.DOCUMENTS_BUCKET, blob.internalURL)
.then(function (objectMeta) {
fileMeta = objectMeta;
// get the download URL
return MinioController.getPresignedGETUrl(MinioController.BUCKETS.DOCUMENTS_BUCKET, blob.internalURL);
}, function () {
return Actions.sendResponse(res, 404, {});
})
.then(function (docURL) {
Utils.recordAction('Download', 'Document', args.swagger.params.auth_payload.preferred_username, args.swagger.params.docId && args.swagger.params.docId.value ? args.swagger.params.docId.value : null);
// stream file from Minio to client
if (!fileMeta) {
return;
}
res.setHeader('Content-Length', fileMeta.size);
res.setHeader('Content-Type', fileMeta.metaData['content-type']);
res.setHeader('Content-Disposition', 'attachment;filename="' + encodeURIComponent(fileName) + '"');
return rp(docURL).pipe(res);
});
} else {
return Actions.sendResponse(res, 404, {});
}
});
};
exports.protectedOpen = function (args, res) {
var self = this;
self.scopes = args.swagger.params.auth_payload.realm_access.roles;
defaultLog.info('args.swagger.params:', args.swagger.params.auth_payload.realm_access.roles);
// Build match query if on docId route
var query = {};
if (args.swagger.params.docId && args.swagger.params.docId.value) {
query = Utils.buildQuery('_id', args.swagger.params.docId.value, query);
}
// Set query type
_.assignIn(query, { '_schemaName': 'Document' });
Utils.runDataQuery('Document',
args.swagger.params.auth_payload.realm_access.roles,
query,
['internalURL', 'documentFileName', 'internalMime', 'internalExt'], // Fields
null, // sort warmup
null, // sort
null, // skip
null, // limit
false) // count
.then(function (data) {
if (data && data.length === 1) {
var blob = data[0];
var fileName = blob.documentFileName;
var fileType = blob.internalExt;
if (fileName.slice(- fileType.length) !== fileType) {
fileName = fileName + '.' + fileType;
}
// Allow override
if (args.swagger.params.filename) {
fileName = args.swagger.params.filename.value;
}
var fileMeta;
// update document secure hit count
mongoose.model('Document').findById(args.swagger.params.docId.value)
.then(doc => {
doc.secureHitCount++;
doc.save();
});
// check if the file exists in Minio
return MinioController.statObject(MinioController.BUCKETS.DOCUMENTS_BUCKET, blob.internalURL)
.then(function (objectMeta) {
fileMeta = objectMeta;
// get the download URL
return MinioController.getPresignedGETUrl(MinioController.BUCKETS.DOCUMENTS_BUCKET, blob.internalURL);
}, function () {
return Actions.sendResponse(res, 404, {});
})
.then(function (docURL) {
if (fileMeta) {
Utils.recordAction(
'Open',
'Document',
args.swagger.params.auth_payload.preferred_username,
args.swagger.params.docId && args.swagger.params.docId.value ? args.swagger.params.docId.value : null
);
// stream file from Minio to client
res.setHeader('Content-Length', fileMeta.size);
res.setHeader('Content-Type', fileMeta.metaData['content-type']);
res.setHeader('Content-Disposition', 'inline;filename="' + fileName + '"');
return rp(docURL).pipe(res);
}
});
} else {
return Actions.sendResponse(res, 404, {});
}
});
};
// Create a new document
exports.protectedPost = async function (args, res) {
console.log('Creating new protected document object');
var project = args.swagger.params.project.value;
var _comment = args.swagger.params._comment.value;
if (args.swagger.params._comment && args.swagger.params._comment.value && !mongoose.Types.ObjectId.isValid(_comment)) {
return Actions.sendResponse(res, 400, { });
}
if (args.swagger.params.project && args.swagger.params.project.value && !mongoose.Types.ObjectId.isValid(project)) {
return Actions.sendResponse(res, 400, { });
}
var upfile = args.swagger.params.upfile.value;
var guid = intformat(generator.next(), 'dec');
var ext = mime.extension(args.swagger.params.upfile.value.mimetype);
var tempFilePath = uploadDir + guid + '.' + ext;
try {
Promise.resolve()
.then(function () {
if (ENABLE_VIRUS_SCANNING) {
return Utils.avScan(args.swagger.params.upfile.value.buffer);
} else {
return true;
}
})
.then(function (valid) {
if (!valid) {
defaultLog.warn('File failed virus check.');
return Actions.sendResponse(res, 400, { 'message': 'File failed virus check.' });
} else {
console.log('writing file.');
fs.writeFileSync(tempFilePath, args.swagger.params.upfile.value.buffer);
console.log('wrote file successfully.');
console.log(MinioController.BUCKETS.DOCUMENTS_BUCKET,
mongoose.Types.ObjectId(project),
args.swagger.params.documentFileName.value,
tempFilePath);
MinioController.putDocument(MinioController.BUCKETS.DOCUMENTS_BUCKET,
project,
args.swagger.params.documentFileName.value,
tempFilePath)
.then(async function (minioFile) {
console.log('putDocument:', minioFile);
// remove file from temp folder
fs.unlinkSync(tempFilePath);
console.log('unlink');
var Document = mongoose.model('Document');
var doc = new Document();
// Define security tag defaults
doc.project = mongoose.Types.ObjectId(project);
doc._comment = _comment;
doc._addedBy = args.swagger.params.auth_payload.preferred_username;
doc._createdDate = new Date();
doc.read = ['sysadmin', 'staff'];
doc.write = ['sysadmin', 'staff'];
doc.delete = ['sysadmin', 'staff'];
doc.documentFileName = args.swagger.params.documentFileName.value;
doc.internalOriginalName = args.swagger.params.internalOriginalName.value;
doc.internalURL = minioFile.path;
doc.internalExt = minioFile.extension;
doc.internalSize = upfile.size;
doc.passedAVCheck = true;
doc.internalMime = upfile.mimetype;
let formattedLeg = null;
if ((args.swagger.params.legislation && typeof args.swagger.params.legislation.value === 'string') ||
(args.swagger.params.legislation && typeof args.swagger.params.legislation.value === 'number')) {
formattedLeg = parseInt(args.swagger.params.legislation.value, 10);
}
doc.legislation = formattedLeg;
doc.documentSource = args.swagger.params.documentSource.value;
// TODO Not Yet
// doc.labels = JSON.parse(args.swagger.params.labels.value);
doc.displayName = args.swagger.params.displayName.value;
if (args.swagger.params.eaoStatus && args.swagger.params.eaoStatus.value) {
doc.eaoStatus = args.swagger.params.eaoStatus.value;
if (args.swagger.params.eaoStatus.value == 'Published') {
doc.read.push('public');
}
} else {
doc.eaoStatus = null;
}
if (args.swagger.params.publish && args.swagger.params.publish.value === true) {
doc.read.push('public');
}
doc.milestone = args.swagger.params.milestone.value && args.swagger.params.milestone.value !== "null" ? mongoose.Types.ObjectId(args.swagger.params.milestone.value) : null;
doc.type = args.swagger.params.type.value && args.swagger.params.type.value !== "null" ? mongoose.Types.ObjectId(args.swagger.params.type.value) : null;
doc.documentAuthor = args.swagger.params.documentAuthor.value && args.swagger.params.documentAuthor.value !== "null" ? args.swagger.params.documentAuthor.value : null;
doc.documentAuthorType = args.swagger.params.documentAuthorType.value && args.swagger.params.documentAuthorType.value !== "null" ? mongoose.Types.ObjectId(args.swagger.params.documentAuthorType.value) : null;
doc.dateUploaded = args.swagger.params.dateUploaded.value;
doc.datePosted = args.swagger.params.datePosted.value;
doc.description = args.swagger.params.description.value;
doc.projectPhase = args.swagger.params.projectPhase.value && args.swagger.params.projectPhase.value !== "null" ? mongoose.Types.ObjectId(args.swagger.params.projectPhase.value) : null;
// Update who did this?
console.log('unlink');
doc.save()
.then(function (d) {
defaultLog.info('Saved new document object:', d._id);
Utils.recordAction('Post', 'Document', args.swagger.params.auth_payload.preferred_username, d._id);
return Actions.sendResponse(res, 200, d);
})
.catch(function (error) {
console.log('error:', error);
// the model failed to be created - delete the document from minio so the database and minio remain in sync.
MinioController.deleteDocument(MinioController.BUCKETS.DOCUMENTS_BUCKET, doc.project, doc.internalURL);
return Actions.sendResponse(res, 400, error);
});
});
}
});
} catch (e) {
defaultLog.info('Error:', e);
// Delete the path details before we return to the caller.
delete e['path'];
return Actions.sendResponse(res, 400, e);
}
};
exports.protectedPublish = async function (args, res) {
var objId = args.swagger.params.docId.value;
defaultLog.info('Publish Document:', objId);
if (args.swagger.params.docId && args.swagger.params.docId.value && !mongoose.Types.ObjectId.isValid(args.swagger.params.docId.value)) {
return Actions.sendResponse(res, 400, { });
}
var Document = require('mongoose').model('Document');
try {
var document = await Document.findOne({ _id: objId });
if (document) {
defaultLog.info('Document:', document);
document.eaoStatus = 'Published';
var published = await Actions.publish(await document.save());
Utils.recordAction('Publish', 'Document', args.swagger.params.auth_payload.preferred_username, objId);
return Actions.sendResponse(res, 200, published);
} else {
defaultLog.info('Couldn\'t find that document!');
return Actions.sendResponse(res, 404, {});
}
} catch (e) {
return Actions.sendResponse(res, 400, e);
}
};
exports.protectedUnPublish = async function (args, res) {
var objId = args.swagger.params.docId.value;
defaultLog.info('UnPublish Document:', objId);
if (args.swagger.params.docId && args.swagger.params.docId.value && !mongoose.Types.ObjectId.isValid(args.swagger.params.docId.value)) {
return Actions.sendResponse(res, 400, { });
}
var Document = require('mongoose').model('Document');
try {
var document = await Document.findOne({ _id: objId });
if (document) {
defaultLog.info('Document:', document);
document.eaoStatus = 'Rejected';
var unPublished = await Actions.unPublish(await document.save());
Utils.recordAction('Unpublish', 'Document', args.swagger.params.auth_payload.preferred_username, objId);
return Actions.sendResponse(res, 200, unPublished);
} else {
defaultLog.info('Couldn\'t find that document!');
return Actions.sendResponse(res, 404, {});
}
} catch (e) {
return Actions.sendResponse(res, 400, e);
}
};
// Update an existing document
exports.protectedPut = async function (args, res) {
console.log('args:', args.swagger.params);
var objId = args.swagger.params.docId.value;
if (args.swagger.params.docId && args.swagger.params.docId.value && !mongoose.Types.ObjectId.isValid(args.swagger.params.docId.value)) {
return Actions.sendResponse(res, 400, { });
}
if (args.swagger.params.milestone && args.swagger.params.milestone.value && !mongoose.Types.ObjectId.isValid(args.swagger.params.milestone.value)) {
return Actions.sendResponse(res, 400, { });
}
if (args.swagger.params.type && args.swagger.params.type.value && !mongoose.Types.ObjectId.isValid(args.swagger.params.type.value)) {
return Actions.sendResponse(res, 400, { });
}
if (args.swagger.params.documentAuthorType && args.swagger.params.documentAuthorType.value && !mongoose.Types.ObjectId.isValid(args.swagger.params.documentAuthorType.value)) {
return Actions.sendResponse(res, 400, { });
}
if (args.swagger.params.projectPhase && args.swagger.params.projectPhase.value && !mongoose.Types.ObjectId.isValid(args.swagger.params.projectPhase.value)) {
return Actions.sendResponse(res, 400, { });
}
var obj = {};
defaultLog.info('Put document:', objId);
obj._updatedBy = args.swagger.params.auth_payload.preferred_username;
if (args.swagger.params.displayName && args.swagger.params.displayName.value ) {
obj.displayName = args.swagger.params.displayName.value;
}
if ( args.swagger.params.milestone && args.swagger.params.milestone.value ) {
obj.milestone = mongoose.Types.ObjectId(args.swagger.params.milestone.value);
}
if ( args.swagger.params.type && args.swagger.params.type.value ) {
obj.type = mongoose.Types.ObjectId(args.swagger.params.type.value);
}
if ( args.swagger.params.documentAuthorType && args.swagger.params.documentAuthorType.value ) {
obj.documentAuthorType = mongoose.Types.ObjectId(args.swagger.params.documentAuthorType.value);
}
if ( args.swagger.params.projectPhase && args.swagger.params.projectPhase.value ) {
obj.projectPhase = mongoose.Types.ObjectId(args.swagger.params.projectPhase.value);
}
if ( args.swagger.params.dateUploaded && args.swagger.params.dateUploaded.value ) {
obj.dateUploaded = args.swagger.params.dateUploaded.value;
}
if ( args.swagger.params.datePosted && args.swagger.params.datePosted.value ) {
obj.datePosted = args.swagger.params.datePosted.value;
}
if ( args.swagger.params.description && args.swagger.params.description.value ) {
obj.description = args.swagger.params.description.value;
}
if ( args.swagger.params.keywords && args.swagger.params.keywords.value ) {
obj.keywords = args.swagger.params.keywords.value;
}
if ( args.swagger.params.legislation && args.swagger.params.legislation.value ) {
obj.legislation = parseInt(args.swagger.params.legislation.value, 10);
}
// only order application documents for now
if ( args.swagger.params.sortOrder && args.swagger.params.sortOrder.value ) {
obj.sortOrder = args.swagger.params.sortOrder.value;
}
if ( args.swagger.params.eaoStatus && args.swagger.params.eaoStatus.value ){
obj.eaoStatus = args.swagger.params.eaoStatus.value;
}
if (args.swagger.params.eaoStatus && args.swagger.params.eaoStatus.value === 'Published') {
obj.read = ['public', 'staff', 'sysadmin'];
} else if (args.swagger.params.eaoStatus && args.swagger.params.eaoStatus.value === 'Rejected') {
obj.read = ['staff', 'sysadmin'];
}
// TODO Not Yet
// obj.labels = JSON.parse(args.swagger.params.labels.value);
defaultLog.info('ObjectID:', objId);
// Update who did this?
var Document = mongoose.model('Document');
try {
var doc = await Document.findOneAndUpdate({ _id: objId }, obj, { upsert: false, new: true });
if (doc) {
Utils.recordAction('put', 'document', args.swagger.params.auth_payload.preferred_username, objId);
defaultLog.info('Document updated:', doc);
return Actions.sendResponse(res, 200, doc);
} else {
defaultLog.info('Couldn\'t find that object!');
return Actions.sendResponse(res, 404, {});
}
} catch (e) {
defaultLog.info('Error:', e);
return Actions.sendResponse(res, 400, e);
}
};
// Delete a Document
exports.protectedDelete = async function (args, res) {
var objId = args.swagger.params.docId.value;
defaultLog.info('Delete Document:', objId);
if (args.swagger.params.docId && args.swagger.params.docId.value && !mongoose.Types.ObjectId.isValid(args.swagger.params.docId.value)) {
return Actions.sendResponse(res, 400, { });
}
var Document = require('mongoose').model('Document');
try {
var doc = await Document.findOneAndRemove({ _id: objId });
console.log('deleting document', doc);
await MinioController.deleteDocument(MinioController.BUCKETS.DOCUMENTS_BUCKET, doc.project, doc.internalURL);
Utils.recordAction('Delete', 'Document', args.swagger.params.auth_payload.preferred_username, objId);
return Actions.sendResponse(res, 200, {});
} catch (e) {
console.log('Error:', e);
return Actions.sendResponse(res, 400, e);
}
};
exports.featureDocument = async function (args, res) {
try {
if (args.swagger.params.docId && args.swagger.params.docId.value) {
if (!mongoose.Types.ObjectId.isValid(args.swagger.params.docId.value)) {
return Actions.sendResponse(res, 400, { });
}
let document = await mongoose.model('Document').findById(mongoose.Types.ObjectId(args.swagger.params.docId.value));
let project = await mongoose.model('Project').findById(mongoose.Types.ObjectId(document.project));
if(project) {
let featuredDocumentsCount = await mongoose.model('Document').count({ project: project._id, isFeatured: true });
// Move the magic number into a config
if(featuredDocumentsCount < constants.MAX_FEATURE_DOCS) {
document.isFeatured = true;
let result = await document.save();
return Actions.sendResponse(res, 200, result);
} else {
return Actions.sendResponse(res, 403, { status: 403, message: 'Feature document limit reached', limit: constants.MAX_FEATURE_DOCS});
}
}
}
return Actions.sendResponse(res, 404, { status: 404, message: 'Document does not exist'});
} catch(e) {
return Actions.sendResponse(res, 500, {});
}
};
exports.unfeatureDocument = async function (args, res) {
try {
if (args.swagger.params.docId && args.swagger.params.docId.value) {
if (!mongoose.Types.ObjectId.isValid(args.swagger.params.docId.value)) {
return Actions.sendResponse(res, 400, { });
}
let document = await mongoose.model('Document').findById(mongoose.Types.ObjectId(args.swagger.params.docId.value));
document.isFeatured = false;
let result = await document.save();
return Actions.sendResponse(res, 200, result);
}
return Actions.sendResponse(res, 404, {});
} catch(e) {
return Actions.sendResponse(res, 500, {});
}
};