forked from geneontology/noctua
-
Notifications
You must be signed in to change notification settings - Fork 1
/
noctua.js
1707 lines (1477 loc) · 51.9 KB
/
noctua.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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Package: noctua.js
*
* This is a Heroku/NodeJS/local script, using the require environment.
*
* A server that will render GO graphs into jsPlumb.
*
* : node noctua.js -c "RO:0002333 BFO:0000066 RO:0002233 RO:0002488" -g http://golr.geneontology.org/solr/ -b http://localhost:3400 -m minerva_local
*/
// Let jshint pass over over our external globals or oddities.
/* global unescape */
/* global parseInt */
// Required shareable Node libs.
var md = require('markdown');
var mustache = require('mustache');
var fs = require('fs');
var path = require('path');
var tilde = require('expand-home-dir');
var yaml = require('yamljs');
var mime = require('mime');
var url = require('url');
var querystring = require('querystring');
// Required add-on libs.
var amigo = require('amigo2');
var golr_conf = require('golr-conf');
var us = require('underscore');
var bbop = require('bbop-core');
var barista_response = require('bbop-response-barista');
var minerva_requests = require('minerva-requests');
// Extra manager stuff for exports.
var node_engine = require('bbop-rest-manager').node;
var minerva_manager = require('bbop-manager-minerva');
///
/// Helpers.
///
function _die(str){
console.error(str);
process.exit(-1);
}
function _tilde_expand(ufile){
return tilde(ufile);
}
function _tilde_expand_list(list){
return us.map(list, function(ufile){
//console.log('ufile: ' + ufile);
return tilde(ufile);
});
}
// Aliases.
var each = us.each;
var what_is = bbop.what_is;
var is_defined = bbop.is_defined;
var dump = bbop.dump;
///
/// CLI arguments and runtime environment.
///
// CLI handling.
var argv = require('minimist')(process.argv.slice(2));
// Collapsible relations.
var collapsible_raw =
argv['c'] || argv['collapsible-relations'] || '';
var collapsible_reverse_raw =
argv['r'] || argv['collapsible-reverse-relations'] || '';
// GOlr server.
var golr_server_location =
argv['g'] || argv['golr'] || 'http://golr.geneontology.org/';
var golr_neo_server_location =
argv['n'] || argv['golr-neo'] || 'http://noctua-golr.geneontology.org/';
// Barista server.
var barloc =
argv['b'] || argv['barista'] || 'http://barista.berkeleybop.org/';
// Main minerva app definition.
var min_def_name =
argv['m'] || argv['minerva-definition'] || 'minerva_public';
// Work benches; will check and process a little later.
// Default to local workbenches.
var workbench_maybe_raw =
argv['w'] || argv['workbenches'] || './workbenches/';
// Noctua's real location.
var noctua_context =
argv['t'] || argv['noctua-context'] || 'go';
var noctua_location =
argv['s'] || argv['noctua-self'] || 'http://localhost:8910';
// Noctua's self/public location (optional).
var noctua_frontend = argv['p'] || argv['noctua-public'];
// External browser location for models.
var external_browser_location =
argv['e'] || argv['external-browser-location'] || null;
// External browser location for models.
var github_api = argv['github-api'] || null;
var github_org = argv['github-org'] || null;
var github_repo = argv['github-repo'] || null;
// Process strings to usable lists.
var collapsible_relations = [];
if( collapsible_raw ){
collapsible_relations = collapsible_raw.split(/\s+/) || [];
}
var collapsible_reverse_relations = [];
if( collapsible_reverse_raw ){
collapsible_reverse_relations = collapsible_reverse_raw.split(/\s+/) || [];
}
var workbench_maybe_dirs = workbench_maybe_raw.split(/\s+/) || [];
console.log('Will fold: ', collapsible_relations);
console.log('Will fold (reverse): ', collapsible_reverse_relations);
console.log('Using GOlr lookup server at: ', golr_server_location);
console.log('Using GOlr NEO lookup server at: ', golr_neo_server_location);
console.log('Barista location: ' + barloc);
console.log('Minerva definition name: ' + min_def_name);
console.log('External model browser: ' + external_browser_location);
var use_github_p = false;
if( github_api && github_org && github_repo ){
console.log('Use GitHub API: ' +
[github_api, github_org, github_repo].join(', '));
use_github_p = true;
}else{
console.log('Will not use GitHub API');
}
// Figure out our base and URLs we'll need to aim this locally.
var linker = new amigo.linker();
var sd = new amigo.data.server();
var app_base = sd.app_base();
// The name we're using this week.
var notw = 'Noctua (Beta)';
///
/// Define the loadable application.
///
var NoctuaLauncher = function(){
var self = this;
// Monitor some stats.
var monitor_internal_kicks = 0;
var monitor_external_kicks = 0;
///
/// Process CLI environmental variables.
///
// Get the location(s) of the workbench plugins.
var workbenches_all_ids = {};
var workbenches_universal = [];
var workbenches_model = [];
var workbenches_individual = [];
var workbenches_edge = [];
each(workbench_maybe_dirs, function(dir){
//console.log('dir', dir);
// Look at all of the listed directories.
var maybe_dir_files = fs.readdirSync(dir);
each(maybe_dir_files, function(subdir){
//console.log('subdir', subdir);
var dstats = null;
try {
//console.log(dir + '/' + subdir);
dstats = fs.statSync(dir + '/' + subdir);
} catch(e) {
// Pass.
}
if( ! dstats || ! dstats.isDirectory() ){
//console.log(subdir + ' not a directory.');
}else{
var wbpath = dir + '/' + subdir;
var wbid = subdir; // also the ID of our workbench
//console.log('Checking ' + wbid + ' (' + wbpath + ')');
// Check that the file looks right.
var wb = null;
try {
wb = yaml.load(wbpath + '/config.yaml');
} catch(e) {
// Pass.
}
if( ! wb ){
console.log('Rejected workbench: ' + wbid + '; ' +
'no good config.yaml');
}else if( ! ( wb['menu-name'] &&
wb['page-name'] &&
wb['help-link'] &&
wb['type'] ) ){
console.log('Rejected workbench: ' + wbid + '; ' +
'insufficient fields.');
}else if( ! /^[a-zA-Z0-9-_]+$/.test(wbid) ){
console.log('Rejected workbench: ' + wbid + '; ' +
'workbench ID not alphanum.');
}else if( workbenches_all_ids[wbid] ){
console.log('Rejected workbench: ' + wbid + '; ' +
'workbench ID not unique.');
}else{
/// Get ready a second battery of more invasive
/// filesystem tests.
wb['workbench-id'] = wbid;
// Files and directories to test.
var wbpath_try_public = wbpath + '/public';
var wbpath_try_tmpl = wbpath_try_public + '/inject.tmpl';
// Test said entities.
var tmpl_fstats = null;
try {
// We know the probably at least one of these
// isn't gunna work, so the is the order of
// criticality.
tmpl_fstats = fs.statSync(wbpath_try_tmpl);
} catch(e) {
// Pass.
} finally {
// Pass.
}
if( ! tmpl_fstats || ! tmpl_fstats.isFile() ){
console.log('Rejected workbench: ' + wbid + '; ' +
'no public/inject.tmpl');
}else{
/// It looks like we are probably going to be
/// good to go.
// Ensure that we don't hit this one again.
workbenches_all_ids[wbid] = true;
// Add things to the permenent record.
wb['template-injectable'] = wbpath_try_tmpl;
wb['public-directory'] = wbpath_try_public;
// Load workbench for later.
if( wb['type'] === 'universal' ){
workbenches_universal.push(wb);
console.log('Added workbench (u: '+wbid+')');
}else if( wb['type'] === 'model' ){
workbenches_model.push(wb);
console.log('Added workbench (m: '+wbid+')');
}else if( wb['type'] === 'individual' ){
workbenches_individual.push(wb);
console.log('Added workbench (i: '+wbid+')');
}else if( wb['type'] === 'edge' ){
workbenches_edge.push(wb);
console.log('Added workbench (e: '+wbid+')');
}else{
console.log('Rejected workbench (type)');
}
}
}
}
});
});
// Apply external to internal variables.
var all_workbenches = workbenches_universal.concat(workbenches_model).concat(workbenches_individual).concat(workbenches_edge);
if( us.isEmpty(all_workbenches) ){
console.log('No workbenches defined.');
}else{
console.log(all_workbenches.length + ' workbench(es) defined.');
}
// Barista location setting.
//var barloc = config['BARISTA_LOOKUP_URL'].value;
self.barista_location = barloc;
// Initial setup of which minerva definition to use (to pass to
// barista for translation).
// var min_def_name = config['DEFAULT_APP_DEFINITION'].value;
self.minerva_definition_name = min_def_name;
// Now that we have some context, try and grab context-specific
// SPARQL queries.
var sparql_templates_named = {};
var sparql_templates_universal = [];
var sparql_templates_model = [];
var sparql_templates_individual = [];
var sparql_templates_edge = [];
var read_templates_count = 0;
var ignored_templates_count = 0;
var sparql_templates_path = 'context/'+ noctua_context +'/sparql-templates/';
//console.log('Have canned SPARQL templates? '+sparql_templates_path);
try {
// Try and read the directory for files.
var stp_stats = fs.statSync(sparql_templates_path);
if( ! stp_stats.isDirectory() ){
console.log('No SPARQL templates for this context: '+noctua_context);
}else{
var sparql_template_files = fs.readdirSync(sparql_templates_path);
each(sparql_template_files, function(sparql_template_file_base){
var sparql_template_file =
sparql_templates_path + sparql_template_file_base;
// Try and read the individual files.
var stf_stats = fs.statSync(sparql_template_file);
if( ! stf_stats.isFile() ){
console.log('WARNING: Skipping: ' + sparql_template_file);
}else{
var stf = null;
try {
stf = yaml.load(sparql_template_file);
} catch(e) {
console.log('WARNING: Not YAML: '+sparql_template_file);
}
// Okay: we seem to have a thing.
if( stf ){
//console.log('stf', stf);
var read_p = false;
// Store an named/addressable SPARQL template.
if( stf['handle'] ){
sparql_templates_named[stf['handle']] = stf;
read_p = true;
}
// Scan the variable for Noctua location signals.
if( ! stf['variables'] || us.isEmpty(stf['variables'] )){
sparql_templates_universal.push(stf);
read_p = true;
console.log('Gosling (universal): ' +
sparql_template_file);
}else{
if( stf['variables'] ){
// Edge, individual, and model.
if( stf['variables']['model_id'] &&
stf['variables']['subject_id'] &&
stf['variables']['object_id'] &&
stf['variables']['relation_id'] ){
sparql_templates_edge.push(stf);
read_p = true;
console.log('Gosling (edge): ' +
sparql_template_file);
}else if( stf['variables']['model_id'] &&
stf['variables']['individual_id'] ){
sparql_templates_individual.push(stf);
read_p = true;
console.log('Gosling (individual): ' +
sparql_template_file);
}else if( stf['variables']['model_id'] ){
sparql_templates_model.push(stf);
read_p = true;
console.log('Gosling (model): '+
sparql_template_file);
}else{
console.log('Gosling (skip, missed var)): '+
sparql_template_file);
}
}else{
console.log('Gosling (skip, empty var)): '+
sparql_template_file);
}
}
// Increment how/if the template was read.
if( read_p ){
read_templates_count++;
}else{
ignored_templates_count++;
}
}
}
});
}
} catch(e) {
console.log('WARNING: Issue while trying to get SPARQL templates ' +
'for this context: ' + noctua_context, e);
}
console.log( read_templates_count +
' SPARQL template(s) read; ' +
ignored_templates_count +' ignored.');
///
/// Environment helpers for deployment; also changing some of the
/// default values depending on the environment to help with
/// deployment.
///
// Set up server IP address and port # using env variables/defaults.
// WARNING: Port stuff gets weird:
// https://www.openshift.com/forums/openshift/nodejs-websockets-sockjs-and-other-client-hostings
self.IS_ENV_OPENSHIFT = false;
self.IS_ENV_HEROKU = false;
self.IS_ENV_LOCAL = false;
if( process.env.OPENSHIFT_APP_DNS ){
self.IS_ENV_OPENSHIFT = true;
// Try and setup hostname and port as best we can.
self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
self.port = process.env.OPENSHIFT_NODEJS_PORT;
self.hostport = 'http://' + process.env.OPENSHIFT_APP_DNS;
// Also, we need to use the public version or minerva or badness.
//self.barista_location = barloc_public;
console.log('Changing Barista location to: ' +
self.barista_location + ' for openshift');
console.log('Changing Minerva definition to: ' +
self.minerva_definition_name + ' for openshift');
console.log('Running as: OPENSHIFT_NODEJS');
}else if( process.env.PORT ){
self.IS_ENV_HEROKU = true;
// Try and setup port as best we can.
self.port = process.env.PORT || 8910; // why this default?
self.hostport = '';
// Also, we need to use the public version or minerva or badness.
//self.barista_location = barloc_public;
console.log('Changing Barista location to: ' +
self.barista_location + ' for heroku');
console.log('Changing Minerva definition to: ' +
self.minerva_definition_name + ' for heroku');
console.log('Running as: HEROKU_NODEJS');
}else{
self.IS_ENV_LOCAL = true;
// If Noctua host is env defined, use that, or sane default.
var u = url.parse(noctua_location);
self.ipaddress = u.hostname || '127.0.0.1';
self.port = u.port;
self.hostport = 'http://'+ self.ipaddress +':'+ self.port;
console.log('Running as: LOCAL_NODEJS');
}
// This allows the links available to be optionally
// different than the literal operating address of noctua.
self.frontend = noctua_frontend || self.hostport;
console.log('Detected frontend: ' + self.frontend);
// Attempt to intelligently add a token to an input URL.
// BUG: This code is repeated in bbop_mme_widgets.build_token_link()
// and barista.js.
function _build_token_link(url, token, token_name){
var new_url = url;
// Default to "barista_token".
if( ! token_name ){ token_name = 'barista_token'; }
if( token ){
if( new_url.indexOf('?') === -1 ){
new_url = new_url + '?' + token_name + '=' + token;
}else{
new_url = new_url + '&' + token_name + '=' + token;
}
}
return new_url;
}
///
/// Response helper.
///
self.get_token = function(req){
var ret = null;
if( req && req.query && req.query['barista_token'] ){
ret = req.query['barista_token'];
}
return ret;
};
self.get_qp = function(req, query_parameter){
var ret = null;
if( req && req.query && req.query[query_parameter] ){
ret = req.query[query_parameter];
}
return ret;
};
self.standard_response = function(res, code, type, body){
res.setHeader('Content-Type', type);
res.setHeader('Content-Length', body.length);
res.end(body);
return res;
};
// Standard template arguments payload.
self.standard_variable_load = function(app_path, app_name, req,
model_id, model_obj,
individual_id, subject_individual_id,
object_individual_id, relation_id,
additional_args) {
// Setup branding, driven by external variable.
var noctua_branding = 'Noctua (?)'; // self-name
var noctua_minimal_p = false; // use of side panel in graph editor
if( noctua_context === 'go' ){
noctua_branding = 'Noctua';
}else if( noctua_context === 'monarch' ){
noctua_branding = 'WebPhenote';
}else if( noctua_context === 'open' ){
noctua_branding = 'Noctua';
noctua_minimal_p = true;
}else{
// Unknown miss.
console.log('WARNING: unknown context "' + noctua_context + '"');
}
// Try and see if we have an API token from the request.
var barista_token = self.get_token(req);
var noctua_landing = _build_token_link(self.frontend, barista_token);
var barista_loc = self.barista_location;
var barista_login = null;
var barista_logout = null;
if( app_path === '' || app_path === '/' ){ // non-id based pages.
barista_login = barista_loc + '/login' + '?return=' +
self.frontend + app_path;
// Make sure that _build_token_link() doesn't get the '?' from
// barista_loc when determining whether to use ? or &
barista_logout = barista_loc + '/logout' +
'?barista_token=' + barista_token +
'&return=' + _build_token_link(self.frontend + app_path,
barista_token);
}else{
barista_login = barista_loc + '/login' + '?return=' +
self.frontend + app_path;
// Make sure that _build_token_link() doesn't get the '?' from
// barista_loc when determining whether to use ? or &
barista_logout = barista_loc + '/logout' +
'?barista_token=' + barista_token +
'&return=' + _build_token_link(self.frontend + app_path,
barista_token);
}
var barista_users =
_build_token_link(self.barista_location +'/user_info',
barista_token);
var out_known_rels = self.known_relations;
// Limit out variables in some cases.
if( app_path === '' || app_path === '/' ){
out_known_rels = null;
}
var tmpl_args = {
'pup_tent_js_variables': [
{name: 'global_model',
value: (model_obj || null)},
// BUG/TODO: Three (historical) ways of referring to
// model id--fix this.
{name: 'global_id',
value: model_id },
{name: 'model_id',
value: model_id },
{name: 'global_model_id',
value: model_id },
{name: 'global_individual_id',
value: individual_id },
{name: 'global_subject_individual_id',
value: subject_individual_id },
{name: 'global_object_individual_id',
value: object_individual_id },
{name: 'global_relation_id',
value: relation_id },
{name: 'global_golr_server',
value: golr_server_location},
{name: 'global_golr_neo_server',
value: golr_neo_server_location},
{name: 'global_minerva_definition_name',
value: self.minerva_definition_name },
{name: 'global_barista_location',
value: self.barista_location },
{name: 'global_noctua_context',
value: noctua_context },
{name: 'global_noctua_minimal_p',
value: noctua_minimal_p },
{name: 'global_external_browser_location',
value: external_browser_location },
{name: 'global_known_relations',
value: out_known_rels },
{name: 'global_collapsible_relations',
value: collapsible_relations },
{name: 'global_collapsible_reverse_relations',
value: collapsible_reverse_relations },
{name: 'global_barista_token',
value: barista_token },
// Workbenches.
{name: 'global_workbenches_universal',
value: workbenches_universal },
{name: 'global_workbenches_model',
value: workbenches_model },
{name: 'global_workbenches_individual',
value: workbenches_individual },
{name: 'global_workbenches_edge',
value: workbenches_edge },
// SPARQL templates.
{name: 'global_sparql_templates_named',
value: sparql_templates_named },
{name: 'global_sparql_templates_universal',
value: sparql_templates_universal },
{name: 'global_sparql_templates_model',
value: sparql_templates_model },
{name: 'global_sparql_templates_individual',
value: sparql_templates_individual },
{name: 'global_sparql_templates_edge',
value: sparql_templates_edge },
// GitHub.
{name: 'global_github_api',
value: github_api },
{name: 'global_github_org',
value: github_org },
{name: 'global_github_repo',
value: github_repo },
{name: 'global_use_github_p',
value: use_github_p }
],
'title': notw + ' ' + app_name,
'model_id': model_id,
'individual_id': individual_id,
'subject_individual_id': subject_individual_id,
'object_individual_id': object_individual_id,
'relation_id': relation_id,
'barista_token': barista_token,
'barista_location': self.barista_location,
'barista_users': barista_users,
'noctua_dev_tabs': noctua_context !== 'monarch',
'noctua_context': noctua_context,
'external_browser_location': external_browser_location,
'github_api': github_api,
'github_org': github_org,
'github_repo': github_repo,
'use_github_p': use_github_p,
'noctua_minimal_p': noctua_minimal_p,
'noctua_landing': noctua_landing,
'noctua_branding': noctua_branding,
'barista_login': barista_login,
'barista_logout': barista_logout,
'noctua_workbenches_universal': workbenches_universal,
'noctua_workbenches_model': workbenches_model,
'noctua_workbenches_individual': workbenches_individual,
'noctua_workbenches_edge': workbenches_edge
};
// Load in the additions.
each(additional_args, function(val, key){
tmpl_args[key] = val;
});
return tmpl_args;
};
// Assemble return doc.
self.bootstrap_editor = function(req, res, model_id, model_obj){
// Assemble return doc.
res.setHeader('Content-Type', 'text/html');
var tmpl_args = self.standard_variable_load(
'/editor/graph/'+ model_id, 'Editor', req,
model_id, model_obj,
null, null,
null, null,
{
'pup_tent_css_libraries': [
'/toastr.css',
'/noctua_common.css',
'/NoctuaEditor.css'
],
'pup_tent_js_libraries': [
'/jquery.jsPlumb-1.5.5.js',
//'/jsPlumb-1.5.5.js',
//'/jsPlumb-1.7.10-min.js',
//'/jsPlumb-2.1.7-min.js',
'/jquery.tablesorter.min.js',
self.barista_location + '/socket.io/socket.io.js',
'/connectors-sugiyama.js',
'/NoctuaEditor.js'
]
});
var ret = pup_tent.render('noctua_editor.tmpl',
tmpl_args, 'noctua_base.tmpl');
self.standard_response(res, 200, 'text/html', ret);
};
///
/// Cache and template rendering.
///
// Will pick things up recursively.
var ppaths = ['static', 'deploy', 'css', 'templates', 'external_js'];
// Add the paths for the workbenches. While we don't need these
// for the asset delivery (that is taken care of directly by
// express in the dynamic route creation below), we need it to
// allow pup-tent to render the templates.
each(all_workbenches, function(wb){
// We know these are good.
var path = wb['public-directory'];
ppaths.push(path);
});
var pup_tent = require('pup-tent')(ppaths, null, true);
pup_tent.use_cache_p(false);
pup_tent.set_common('css_libs', [
'/bootstrap.min.css',
'/jquery-ui-1.10.3.custom.min.css',
'/bbop.css',
'/amigo.css']);
pup_tent.set_common('js_libs', [
'/jquery.min.js',
'/bootstrap.min.js',
'/jquery-ui-1.10.3.custom.min.js',
]);
//console.log('pup_tent', pup_tent.cached_list().sort());
///
/// Termination functions.
///
// terminator === the termination handler
// Terminate server on receipt of the specified signal.
// @param {string} sig Signal to terminate on.
self.terminator = function(sig){
if (typeof sig === "string") {
console.log('%s: Received %s - terminating noctua...',
Date(Date.now()), sig);
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()) );
};
// Setup termination handlers (for exit and a list of signals).
self.setupTerminationHandlers = function(){
// Process on exit and signals.
process.on('exit', function() { self.terminator(); });
// Removed 'SIGPIPE' from the list - bugz 852598.
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
].forEach(function(element, index, array) {
process.on(element, function() { self.terminator(element); });
});
};
///
/// App server functions (main app logic here).
///
// Initialize the server (launcher_app) and create the routes and register
// the handlers.
self.initializeServer = function(){
var launcher_app = require('express');
var body_parser = require('body-parser');
self.app = launcher_app();
// Middleware needed for POST and browserid
//self.app.use(launcher_app.bodyParser());
self.app.use(body_parser.json());
self.app.use(body_parser.urlencoded({ extended: true }));
///
/// Static routes.
///
self.app.get('/', function(req, res) {
// Grab markdown renderable file.
var landing_raw = fs.readFileSync('./OVERVIEW.' + noctua_context + '.md').toString();
var landing_md = md.markdown.toHTML(landing_raw);
var about_raw = fs.readFileSync('./ABOUT.' + noctua_context + '.md').toString();
var about_md = md.markdown.toHTML(about_raw);
var tmpl_args = self.standard_variable_load(
'/', 'Landing', req,
null, null,
null, null,
null, null,
{
'pup_tent_css_libraries': [
'/toastr.css',
'jquery.dataTables.min.css',
'/noctua_common.css',
'/noctua_landing.css'
],
'pup_tent_js_libraries': [
'jquery.dataTables.min.js',
'/NoctuaLanding.js'
],
'landing_html': landing_md,
'about_html': about_md
});
// Render.
var o = pup_tent.render('noctua_landing.tmpl',
tmpl_args,
'noctua_base_landing.tmpl');
self.standard_response(res, 200, 'text/html', o);
});
// General markdown documentation.
self.app.get('/doc/:fname', function(req, res) {
var final_content = '???';
var fname = req.params['fname'] || '';
if( ! fname || fname === '' ){
// Catch error here if no proper fname.
final_content = '<h5>doc/name required</h5>';
}else{
// Optionally, remove .html (for now).
fname = path.basename(fname, '.html');
// For now, map this to a markdown doc in the context
// directory.
var mapped_fname = './context/' + noctua_context +
'/markdown-docs/' + fname + '.md';
// Detect if file exists.
try {
var fstats = fs.statSync(mapped_fname);
if( ! fstats.isFile() ){
// Catch error here if not found.
final_content = '<h5>' + fname + '" not file</h5>';
}else{
// Grab markdown renderable file.
var fname_raw = fs.readFileSync(mapped_fname).toString();
final_content = md.markdown.toHTML(fname_raw);
}
} catch(e) {
// Catch error here if not found.
final_content = '<h5>no "' + fname + '" for "' +
noctua_context + '"</h5>: ' + mapped_fname;
}
}
//
var tmpl_args = self.standard_variable_load(
'/doc/' + fname, fname, req,
null, null,
null, null,
null, null,
{
'pup_tent_css_libraries': [
//'/toastr.css',
//'jquery.dataTables.min.css',
'/noctua_common.css'//,
//'/noctua_landing.css'
],
'pup_tent_js_libraries': [
//'jquery.dataTables.min.js',
],
'content_insert': final_content
});
// Render.
var o = pup_tent.render('noctua_markdoc.tmpl',
tmpl_args,
'noctua_base_content_frame.tmpl');
self.standard_response(res, 200, 'text/html', o);
});
//
self.app.get('/basic/:model_type/:query', function(req, res) {
// Try and see if we have an API token.
var barista_token = self.get_token(req);
var model_type = req.params['model_type'] || '';
var model_id = req.params['query'] || '';
var noctua_landing = _build_token_link(self.frontend, barista_token);
var noctua_branding = 'Noctua';
if( noctua_context === 'monarch' ){ noctua_branding = 'WebPhenote'; }
var barista_login = self.barista_location + '/login?return=' +
self.frontend + '/basic/' + model_type + '/' + model_id;
var barista_logout =
_build_token_link(self.barista_location + '/logout' +
'?barista_token=' + barista_token +
'&return=' + self.frontend + '/basic/' +
model_type +'/'+ model_id, barista_token);
//
var model_obj = null;
var tmpl_args = self.standard_variable_load(
'/basic/' + model_type + '/' + model_id, 'FormEditor', req,
model_id, model_obj,
null, null,
null, null,
{
'pup_tent_js_libraries': [
'/deploy/js/NoctuaBasic/NoctuaBasicApp.js',
'/deploy/angular-toastr.tpls.min.js'
],
'pup_tent_css_libraries': [
'/noctua_common.css',
'/NoctuaBasic.css',
'/selectize.css',
'/selectize.bootstrap3.css',
'/selectize.custom.css',
'/angular-toastr.css',
'/ui-grid.css',
'/select.min.css',
'/toastr_custom.css'
],
'model_type': model_type
});
tmpl_args.pup_tent_js_variables.push(
{name: 'global_model_type',
value: model_type });
var ind = pup_tent.render('noctua_basic.tmpl',
tmpl_args,
'noctua_base_landing.tmpl');
self.standard_response(res, 200, 'text/html', ind);
});
// Routes for all static cache items.
each(pup_tent.cached_list(), function(thing) {
var ctype = mime.lookup(thing);
// This will skip cached templates.
if (ctype !== null) {
self.app.get('/' + thing, function(req, res) {
res.setHeader('Content-Type', ctype);
res.send(pup_tent.get(thing) );
});
}
});
// Fonts are special!
self.app.use('/fonts', launcher_app.static('static/fonts'));
self.app.use('/ui-grid.svg', launcher_app.static('./node_modules/angular-ui-grid/ui-grid.svg'));
self.app.use('/ui-grid.ttf', launcher_app.static('./node_modules/angular-ui-grid/ui-grid.ttf'));
self.app.use('/ui-grid.woff', launcher_app.static('./node_modules/angular-ui-grid/ui-grid.woff'));
// Other static routes.
// BUG/TODO: Hardcoded--likely need a pathname getter in pup_tent.
// Probably use _path_cache(key).
var static_images = [ // BUG/TODO: Hack.
['go_logo.png', 'png'],
['open_logo.png', 'png'],
['monarch_logo.png', 'png'],
['waiting_ac.gif', 'gif'],
['ui-bg_flat_100_ffffff_40x100.png', 'png'],
['ui-bg_flat_75_d0ffee_40x100.png', 'png'],
['sort_asc.png', 'png'],
['sort_desc.png', 'png'],
['sort_both.png', 'png']
];
each(static_images, function(item){
var fname = item[0];
var type = item[1];
self.app.get('/images/' + fname, function(req, res){
res.setHeader('Content-Type', 'image/' + type);
res.sendfile('static/' + fname);
});
});
// TODO: This obviously does not do anything than supress some types
// of error messages.
self.app.get('/favicon.ico', function(req, res){
self.standard_response(res, 200, 'image/x-icon', '');
});
// Error redirect catch.
self.app.get('/error', function(req, res) {
console.log('caught intentional redirect for error report');
//console.log(req.route);
//console.log(req.params['query']);
var etype = self.get_qp(req, 'type') || 'unclassified error';
var emessage = self.get_qp(req, 'message') || 'unknown error';
var fin = [