-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
1413 lines (1302 loc) · 46.4 KB
/
index.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
/*!
* easy-web-gui
* Copyright(c) 2018 ma-ha
* MIT Licensed
*/
var gui = exports = module.exports = {
pages : {}
,userTokens : {}
,pullDownMenu : {}
,appRoot: '/'
,decor: 'decor'
};
// logger
var log = require( 'npmlog' );
// use express for REST services
var express = require( 'express' );
var webservices = express();
var router = express.Router();
gui.express = webservices
var jwt = require( 'jsonwebtoken' )
var bodyParser = require( 'body-parser' );
// body-parser for JSON payload:
var jsonParser = bodyParser.json();
// body-parser for parsing application/x-www-form-urlencoded:
var formParser = bodyParser.urlencoded( { extended: true } );
var cookieParser = require( 'cookie-parser' )
webservices.use( cookieParser() )
// support external confugation
var config = require( 'config' )
if ( config.staging ) { log.info( 'Web GUI', 'config stage: '+config.staging ) }
var cfg = {}
if ( config.has('easy-web-app') ) {
cfg = config.get( 'easy-web-app' )
if ( cfg.enableCustomCSS ) {
router.use( '/css-custom', express.static( process.cwd()+'/css' ) )
log.info( 'Web GUI', 'use '+process.cwd() +'/custom.css' )
}
if ( cfg['img-cust'] ) {
router.use( '/img-cust', express.static( process.cwd() +'/'+ cfg['img-cust'] ) )
log.info( 'Web GUI', 'get "/img-cust" from folder '+process.cwd() +'/'+ cfg['img-cust'] )
}
}
log.info( 'Web GUI', 'config port: '+cfg.port )
if ( config.loglevel ) {
log.info( 'Web GUI', 'switch to log level: '+config.loglevel )
log.level = config.loglevel
}
/** Initialize the Web GUI */
gui.init = function init( logoText, port, rootPath, options ) {
this.appRoot = rootPath || cfg.rootPath || '/'
if ( this.appRoot.indexOf('/') != 0 ) { this.appRoot = '/'+this.appRoot }
var mainPage = this.setDefaults( options )
mainPage.header.logoText = cfg.logoText || logoText
mainPage.title = cfg.title || mainPage.title
mainPage.footer.copyrightText = cfg.copyrightText || mainPage.footer.copyrightText
if ( cfg.logoURL ) { mainPage.setLogoURL( cfg.logoURL ) }
var wsPort = port || cfg.port || 8888
if ( typeof WEB_SERVER_PORT !== 'undefined' ) {
wsPort = WEB_SERVER_PORT // global setting override
}
webservices.use( this.appRoot, router )
webservices.listen( wsPort )
log.info( 'Web GUI', 'http://localhost:' + wsPort + this.appRoot )
if ( cfg.enableSecurity === true ) {
gui.enableSecurity()
if ( cfg.loginTimeout ) {
gui.loginTimeout = cfg.loginTimeout
}
}
return mainPage
}
gui.getExpress = function getExpress() {
return router;
}
/** Set defaults for all required configurations */
gui.setDefaults = function setDefaults( options ) {
// create a default "main" page minimum config
var navUrl = ( this.appRoot=='/' ? '/svc/nav' : this.appRoot+'/svc/nav' )
this.pages[ 'main' ] = {
title : 'Main Page'
, version: '2'
, header : {
logoText : 'Test'
,frameWarning: "true"
,modules : [ ]
}
, rows : []
, footer : {
copyrightText : 'powered by '+
'<a href="https://github.com/ma-ha/rest-web-ui">ReST-Web-GUI</a>'
, modules: []
}
}
this.pages[ 'main' ].setLogo =
function( text, imgLink ) {
if ( ! text ) return
this.header['logo'] = { text: text, url: gui.appRoot + '/index.html' }
if ( imgLink ) this.header['logo']['img'] = imgLink
}
this.pages[ 'main' ].setLogoText =
function( text ) {
this.header['logoText'] = text
}
this.pages[ 'main' ].setLogoURL =
function( url ) {
this.header['logoURL'] = url
}
this.pages[ 'main' ].setTitle =
function( text ) {
this.title = text
}
this.pages[ 'main' ].addColumnsRow =
function ( id, height ) {
return gui.addColumnsRow( id, this.rows, height )
}
this.pages[ 'main' ].addView =
function ( def, config ) {
if ( def.id ) { def.id = def.id.replace( ' ', '' ) }
def.rowId = def.rowId || def.id;
return gui.addViewIn( def, config, this.rows )
}
this.pages[ 'main' ].addTabContainer =
function( def ) { return addTabCont( def, 'row', this.rows ) }
/** set page width attribute and override CSS */
this.pages[ 'main' ].setPageWidth =
function setPageWidth( width ) {
this[ 'page_width' ] = width
}
this.pages[ 'main' ].setCopyright =
function( text ) {
this.footer['copyrightText'] = text
}
this.pages[ 'main' ].addFooterLink =
function( linkText, linkURL, linkTarget ) {
if ( ! this.footer['linkList'] ) { this.footer['linkList'] = [] }
if ( linkTarget ) {
this.footer['linkList'].push( { text:linkText, url:linkURL, target:linkTarget } )
} else {
this.footer['linkList'].push( { text:linkText, url:linkURL } )
}
}
this.pages[ 'main' ].addInfo =
function( text ) {
this.info = text
}
this.pages[ 'main' ].delInfo =
function( ) {
this.info = null
}
this.pages[ 'main' ].dynamicRow =
function( dynamicRowCallback ) {
this.dynamicRowCallback = dynamicRowCallback
}
if ( options && options.nav == 'embedded' ) {
var navView = {
id : 'Nav', title:'',
type:'pong-nav-embed',
resourceURL:'/svc/nav-embed',
height:'XX', decor:"none"
}
this.pages[ 'main' ].addView ( navView )
options.decor = 'none'
this.pages[ 'main' ].header.embedNav = true
} else {
var navbar = {
id : 'MainNav' , type : 'pong-navbar'
, param : {
confURL : navUrl
}
}
this.pages[ 'main' ].header.modules.push( navbar )
}
if ( options && options.decor != 'none' ) {
this.pages[ 'main' ].decor = gui.decor
}
return this.pages[ 'main' ]
}
gui.dynamicTitle =
function( dynamicTitleCallback ) {
this.dynamicTitleCallback = dynamicTitleCallback
}
gui.dynamicHeader =
function( dynamicHeaderCallback ) {
this.dynamicHeaderCallback = dynamicHeaderCallback
}
gui.dynamicFooter =
function( dynamicFooterCallback ) {
this.dynamicFooterCallback = dynamicFooterCallback
}
function addTabCont( def, type, arr ) {
var tabDiv = {}
tabDiv.tabs = []
if ( type == 'row' ) {
tabDiv.height = def.height || '400px'
tabDiv.rowId = def.rowId || def.id
} else {
tabDiv.width = def.width || '100%'
tabDiv.columnId = def.columnId || def.id
}
tabDiv.addView = ( def, vConfig ) => {
var view = {
tabId : def.id,
title : def.title || def.id || ' ',
resourceURL : def.resourceURL || null
}
if ( def.type ) { view.type = def.type }
if ( def. actions ) { view.actions = def.actions }
if ( vConfig ) { view.moduleConfig = vConfig }
tabDiv.tabs.push( view )
return view
}
tabDiv.addRows = ( id, title ) => {
var rows = gui.addRowsColumn( id, null, '100%' )
rows.title = title
rows.tabId = id
delete rows.columnId
delete rows.width
tabDiv.tabs.push( rows )
return rows
}
arr.push( tabDiv )
return tabDiv
}
/** add new pull down menu */
gui.addPullDownMenu = function addPullDownMenu( menuId, menuLabel ) {
var newMenu =
{ id: menuId,
type: 'pong-pulldown',
moduleConfig: {
title: menuLabel,
menuItems : [ ]
}
}
this.pullDownMenu[ menuId ] = newMenu
this.pages[ 'main' ].header.modules.push( newMenu )
}
/** add a new pull down menu header module */
gui.addPullDownMenuHtmlItem = function addPullDownMenuHtmlItem( menuId, htmlString ) {
if ( this.pullDownMenu[ menuId ] ) {
this.pullDownMenu[ menuId ].moduleConfig.menuItems.push( { html:htmlString } )
} else {
log.warn( 'addPullDownMenuHtmlItem: Menu "'+menuId+'" not available!')
}
}
gui.dynamicNav = function dynamicNav( dynamicNavCallback ) {
this.dynamicNavCallback = dynamicNavCallback
}
/** add new page to portal, navigation tabs included */
gui.addPage = function addPage( pageId, title, viewDef, viewConfig ) {
if ( ! pageId ) {
log.warn( 'gui.addPage', 'pageID not defined propperly' );
} else if ( this.pages[ pageId ] ) {
log.warn( 'gui.addPage', 'Page "' + pageId + '" already exists in GUI.' );
} else {
var pgObj = {
title : pageId
, version: '2'
, header : this.pages[ 'main' ].header
, rows : []
, footer : this.pages[ 'main' ].footer
}
if ( title )
pgObj.title = title
pgObj.addColumnsRow =
function ( id, height) {
// log.info( 'pages[].addColumns', id )
return gui.addColumnsRow( id, this.rows, height )
}
pgObj.addView =
function ( def, config ) {
def.rowId = def.rowId || def.id;
if ( def.rowId ) { def.rowId = def.rowId.replace( ' ','' ) }
return gui.addViewIn( def, config, pgObj.rows )
}
pgObj.addTabContainer =
function( def ) { return addTabCont( def, 'row', pgObj.rows ) }
/** set page width attribute and override CSS */
pgObj.setPageWidth =
function setPageWidth( width ) {
this[ 'page_width' ] = width
}
pgObj.addInfo =
function( text ) {
this.info = text
}
pgObj.delInfo =
function( ) {
this.info = null
}
pgObj.dynamicRow =
function( dynamicRowCallback ) {
this.dynamicRowCallback = dynamicRowCallback
}
if ( this.pages[ 'main' ].header.embedNav ) {
var navView = {
id : 'Nav', title:'',
type:'pong-nav-embed',
resourceURL:'/svc/nav-embed',
height:'XX', decor:"none"
}
pgObj.addView ( navView )
}
pgObj.addSubNav =
function( ) {
var navView = {
id : 'SubNav', title:'',
type:'pong-nav-embed',
resourceURL:'/svc/nav-embed-sub',
height:'XX', decor:"none"
}
pgObj.addView ( navView )
}
if ( viewDef ) {
if ( viewDef.id ) { viewDef.id = viewDef.id.replace( ' ', '' ) }
pgObj.addView( viewDef, viewConfig )
}
this.pages[ pageId ] = pgObj
// check if pag is for pull down menu:
if ( pageId.indexOf( '/' ) != -1 ) {
var menuId = pageId.substr( 0 , pageId.indexOf( '/' ) )
// log.info( ' ... '+menuId )
if ( menuId == 'user' ) {
if ( gui.secParams ) { // only if security is enabled
//log.info( 'menu "'+menuId +'": '+pageId)
if ( ! gui.secParams.userPages ) { gui.secParams.userPages = {} }
gui.secParams.userPages[ title ] = pageId
}
} else if ( this.pullDownMenu[ menuId ] ) {
// log.info( 'pullDownMenu: '+menuId )
this.pullDownMenu[ menuId ].moduleConfig.menuItems.push(
{ pageLink:pageId, label:title }
)
}
}
return pgObj
}
}
/** split the column into a rows, to add views */
gui.addColumnsRow = function addColumnsRow( id, colArr, height ) {
// log.info( 'addColumns', id )
var rowObj = {
rowId : id
, height: height || "300px"
, cols : []
}
rowObj.addRowsColumn =
function ( id, width ) {
return gui.addRowsColumn( id, this.cols, width )
}
rowObj.addView =
function ( def, config ) {
if ( def.id && ! def.columnId ) {
def.columnId = def.id
}
if ( def.columnId ) { def.columnId = def.columnId .replace( ' ', '' ) }
return gui.addViewIn( def, config, this.cols )
}
rowObj.addTabContainer =
function( def ) { return addTabCont( def , 'col', rowObj.cols ) }
colArr.push( rowObj )
// log.info( 'addColumns', 'rowObj='+JSON.stringify( rowObj ) )
return rowObj
}
/** split the row into a columns, to add views */
gui.addRowsColumn = function addRowsColumn( id, cols, width ) {
var newCol = {
columnId: id
, width: width || "300px"
, rows : []
}
newCol.addColumnsRow =
function ( id, height) {
// log.info( 'pages[].addColumns', id )
return gui.addColumnsRow( id, this.rows, height )
}
newCol.addRows =
function ( height ) {
return gui.addColumns( this.rows, height )
}
newCol.addView =
function ( def, config ) {
if ( def.id && ! def.rowId ) {
def.rowId = def.id
}
if ( def.rowId ) { def.rowId = def.rowId.replace( ' ', '' ) }
return gui.addViewIn( def, config, this.rows )
}
newCol.addTabContainer =
function( def ) { return addTabCont( def , 'row', this.rows ) }
if ( cols ) cols.push( newCol )
return newCol
}
gui.addViewIn = function addViewIn( def, config, arr ) {
var view = JSON.parse( JSON.stringify( def ) ) // clone it
if ( def.title == '' ) { view.title = null }
else { view.title = def.title || def.id || "View:" }
view.decor = def.decor || this.decor
view.resourceURL = def.resourceURL || "none"
view.height = def.height || '400px'
if ( config ) {
view.moduleConfig = config
}
if ( view.id ) { view.id = view.id.replace( ' ', '' ) }
arr.push( view )
return view
}
/** add a view (new row) to the page */
gui.addView = function addView( def, config, page ) {
var pg = page || 'main';
// pg = encodeURIComponent ( pg );
var view = {};
if ( !this.pages[ pg ] ) {
log.warn( 'gui.addView', 'Page "' + pg + '" not found in GUI!' );
return null;
}
if ( !def ) {
log.warn( 'gui.addView', '"def" is required parameter!' );
return null;
}
if ( !def.id ) {
log.warn( 'gui.addView','"def.id" is required!' );
return null;
} else { // OK, add view
view[ 'rowId' ] = def.id.replace( ' ', '' ) ;
view[ 'title' ] = def.title || def.id || "View:";
view[ 'decor' ] = def.decor || this.decor;
view[ 'height' ] = def.height || '400px';
view[ 'resourceURL' ] = def.resourceURL || "none";
if ( def.type ) {
view[ 'type' ] = def.type;
}
if ( config ) {
view[ 'moduleConfig' ] = config;
}
if (def. actions ) {
view[ 'actions' ] = def.actions;
}
this.pages[ pg ].rows.push ( view );
}
// console.log( JSON.stringify( this.pages[ pg ] ) );
return view;
};
/* define static directories to load the framework into the web page */
var fs = require('fs')
var staticDir = __dirname + '/rest-web-gui/html'
if ( fs.existsSync( staticDir ) ) {
log.info(' Init', 'Using static in '+staticDir )
} else {
var path =require('path')
staticDir = path.resolve( __dirname, '../rest-web-gui/html' )
if ( fs.existsSync( staticDir ) ) {
log.info(' Init', 'Using static in '+staticDir )
} else {
staticDir = __dirname + '/node_modules/rest-web-gui/html'
if ( fs.existsSync( staticDir ) ) {
log.info(' Init', 'Using static in '+staticDir )
} else {
log.error(' Init', 'No path to "rest-web-gui" found! ' )
log.error(' Init', 'Tried: '+__dirname + '/rest-web-gui/html' )
log.error(' Init', 'Tried: '+path.resolve( __dirname, '../rest-web-gui/html' ) )
log.error(' Init', 'Tried: '+staticDir )
process.exit(1)
}
}
}
router.use ( '/css', express.static( staticDir + '/css' ) );
router.use ( '/js', express.static( staticDir + '/js' ) );
router.use ( '/img', express.static( staticDir + '/img' ) );
router.use ( '/modules', express.static( staticDir + '/modules' ) );
// router.use ( '/i18n', express.static( staticDir + '/i18n' ) );
function getBasePageName( page ) {
var len2 = page.length -2
if ( page.indexOf( '-m' ) == len2 || page.indexOf( '-t' ) == len2 ) {
return page.substring( 0, len2 )
} else {
return page
}
}
/** REST web service to GET layout structure: */
router.get(
'/svc/layout/:id/structure',
async function( req, res ) {
var pgId = getBasePageName( req.params.id )
var userId = null
try { userId = await gui.getUserIdFromReq( req ) }
catch( exc ) { log.warn( 'easy-web-app /svc/layout/:id/structure', exc ) }
if ( gui.authorize && ! await gui.authorize( userId, pgId, req ) ) {
// not authorized for this page
var redirectPage = 'main'
if ( gui.secParams && gui.secParams.needLoginPage ) {
redirectPage = gui.secParams.needLoginPage
}
var pg = JSON.parse( JSON.stringify( gui.pages[ redirectPage ] ) ) // cloned
if ( gui.authorize && pg.header ) { // check authorization for header modules
var user = await gui.getUserIdFromReq( req )
for ( var i = pg.header.modules.length-1; i >= 0; i-- ) {
//log.info( '>>>>', pg.header.modules[i].type)
let allowedModules = [ 'pong-security', 'pong-security2', 'pong-navbar' ]
if ( allowedModules.indexOf( pg.header.modules[i].type ) == -1 ) {
// all others should be checked for authorization
if ( pg.header.modules[i].id && ! await gui.authorize( user, pg.header.modules[i].id, req ) ) {
delete pg.header.modules[i] // not a
}
}
}
}
pg = await dynamicStructureCallbacks( pg, gui.pages[ redirectPage ].dynamicRowCallback, req, pgId )
var layout = {
'layout' : pg
}
// console.log( layout )
return res.json( layout )
} else
if ( gui.pages[ req.params.id ] ) {
var pg = JSON.parse( JSON.stringify( gui.pages[ req.params.id ] ) ) // cloned
if ( gui.authorize && pg.header ) { // check authorization for header modules
var user = await gui.getUserIdFromReq( req )
for ( var i = pg.header.modules.length-1; i >= 0; i-- ) {
let allowedModules = [ 'pong-security', 'pong-security2', 'pong-navbar' ]
if ( allowedModules.indexOf( pg.header.modules[i].type ) == -1 ) {
// all others should be checked for authorization
if ( pg.header.modules[i].id && ! await gui.authorize( user, pg.header.modules[i].id, req ) ) {
delete pg.header.modules[i] // not authorized
}
}
}
}
pg = await dynamicStructureCallbacks( pg, gui.pages[ req.params.id ].dynamicRowCallback, req, pgId )
//log.info( "structure", req.params.id )
var layout = {
'layout' : pg
}
return res.json( layout )
} else {
res.statusCode = 404
return res.send( 'Error 404: No quote found' )
}
}
);
/** REST web service to GET layout structure for sub menu pages: */
router.get(
'/svc/layout/:id/:subid/structure',
async function( req, res ) {
var page = req.params.id +'/'+ req.params.subid
// console.log( '>>'+req.params.subid );
var userId = null
try { userId = await gui.getUserIdFromReq( req ) }
catch( exc ) { log.warn( 'easy-web-app /svc/layout/:id/:subid/structure', exc ) }
if ( gui.authorize && ! gui.authorize( userId, page, req ) ) {
// not authorized for this page
var redirectPage = 'main'
if ( gui.secParams && gui.secParams.needLoginPage ) {
redirectPage = gui.secParams.needLoginPage
}
var pg = JSON.parse( JSON.stringify( gui.pages[ redirectPage ] ) ) // cloned
if ( gui.authorize && pg.header ) { // check authorization for header modules
var user = await gui.getUserIdFromReq( req )
for ( var i = pg.header.modules.length-1; i >= 0; i-- ) {
//log.info( '>>>>', pg.header.modules[i].type)
let allowedModules = [ 'pong-security', 'pong-security2', 'pong-navbar' ]
if ( allowedModules.indexOf( pg.header.modules[i].type ) == -1 ) {
// all others should be checked for authorization
if ( pg.header.modules[i].id && ! gui.authorize( user, pg.header.modules[i].id, req ) ) {
delete pg.header.modules[i] // not a
}
}
}
}
pg = await dynamicStructureCallbacks( pg, gui.pages[ redirectPage ].dynamicRowCallback, req, page )
var layout = {
'layout' : pg
};
return res.json( layout );
} else
if ( gui.pages[ page ] ) {
var pg = JSON.parse( JSON.stringify( gui.pages[ page] ) ) // cloned
pg = await dynamicStructureCallbacks( pg, gui.pages[ page ].dynamicRowCallback, req, page )
var layout = {
'layout' : pg
};
res.json( layout );
} else {
res.statusCode = 404;
return res.send( 'Error 404: Page "'+page+'" not found' );
}
}
);
// enable to replace the static structure of header, rows and footer per request using calbacks
async function dynamicStructureCallbacks( pg, dynamicRowCallback, req, page ) {
if ( gui.dynamicTitleCallback ) { // manipulate title on the fly
try {
let newTitle = await gui.dynamicTitleCallback( pg.title, req, page )
if ( newTitle ) {
pg.title = newTitle
}
} catch( exc ) { log.warn( 'easy-web-app /svc/layout/:id/structure dynamicRowCallback', exc ) }
}
if ( gui.dynamicHeaderCallback ) { // manipulate header content on the fly via callback
try {
let newHeader = await gui.dynamicHeaderCallback( pg.header, req, page )
if ( newHeader ) {
pg.header = newHeader
}
} catch( exc ) { log.warn( 'easy-web-app /svc/layout/:id/structure dynamicRowCallback', exc ) }
}
if ( dynamicRowCallback ) { // generate rows content on the fly via callback
try {
let newRows = await dynamicRowCallback( pg.rows, req, page )
if ( newRows ) {
pg.rows = newRows
}
} catch( exc ) { log.warn( 'easy-web-app /svc/layout/:id/structure dynamicRowCallback', exc ) }
}
if ( gui.dynamicFooterCallback ) { // manipulate footer content on the fly via callback
try {
let newFooter = await gui.dynamicFooterCallback( pg.footer, req, page )
if ( newFooter ) {
pg.footer = newFooter
}
} catch( exc ) { log.warn( 'easy-web-app /svc/layout/:id/structure dynamicRowCallback', exc ) }
}
return pg
}
/**
* Single page does it all, the layout parameter references the "page". Default
* is the "main" page
*/
router.get (
'/',
function( req, res ) {
if ( gui.appRoot == '/' ) {
res.redirect( '/index.html' );
} else {
res.redirect( gui.appRoot+'/index.html' );
}
}
);
router.get(
'/index.html',
function( req, res ) {
res.sendFile( __dirname + '/index.html' );
}
);
/** web service to assemble top level menu items for embedded navigation bar */
router.get(
'/svc/nav-embed',
async function( req, res ) {
var navTabs = []
var layout = req.query.page
// main menu
for ( var layoutId in gui.pages ) {
if ( gui.pages.hasOwnProperty ( layoutId ) ) {
if (( layoutId.indexOf( '-nonav' ) == -1 ||
layoutId.indexOf( '-nonav' ) != layoutId.length -6 ) &&
( layoutId.indexOf( '-m' ) == -1 ||
layoutId.indexOf( '-m' ) != layoutId.length -2 ) &&
( layoutId.indexOf( '-t' ) == -1 ||
layoutId.indexOf( '-t' ) != layoutId.length -2 ) &&
( layoutId.indexOf( 'user/' ) != 0 ) ) {
// check authorization for page
if ( gui.authorize && ! await gui.authorize( userId, layoutId, req ) ) {
// not visible for this user
} else if ( layoutId == 'main' && gui.pages['main'].header.logo ) {
// not displayed, because header link
} else {
var nav = {
'layout' : layoutId,
'label' : ( gui.pages[ layoutId ].navLabel ?
gui.pages[ layoutId ].navLabel : gui.pages[ layoutId ].title )
}
if ( gui.pages[ layoutId ].info ) { nav.info = gui.pages[ layoutId ].info }
navTabs.push( nav )
}
}
}
}
if ( gui.dynamicNavCallback ) { // generate nav on the fly via callback
try {
let newNavTabs = await gui.dynamicNavCallback( 'nav-embed', navTabs, req )
if ( newNavTabs ) { navTabs = newNavTabs }
} catch( exc ) { log.warn( 'easy-web-app /svc/nav-embed dynamicNavCallback', exc ) }
}
res.json( { 'navigations' : navTabs } )
}
)
/** web service to assemble sub level menu items for embedded navigation bar */
router.get(
'/svc/nav-embed-sub',
async function( req, res ) {
var navTabs = []
var layout = req.query.page
var masterPage = layout + '/'
if ( layout && layout.indexOf( '/' ) > 0 ){
masterPage = layout.substr( 0, ( layout.indexOf( '/' )+1) )
}
//log.info( 'nav-embed-sub', masterPage )
for ( var layoutId in gui.pages ) {
//log.info( 'nav-embed-sub', layoutId +' -> '+layoutId.indexOf( masterPage ) )
if ( layoutId.indexOf( masterPage ) == 0 ) {
if ( ( layoutId.indexOf( '-nonav' ) == -1 ||
layoutId.indexOf( '-nonav' ) != layoutId.length -6 ) &&
( layoutId.indexOf( '-m' ) == -1 ||
layoutId.indexOf( '-m' ) != layoutId.length -2 ) &&
( layoutId.indexOf( '-t' ) == -1 ||
layoutId.indexOf( '-t' ) != layoutId.length -2 ) &&
( layoutId.indexOf( 'user/' ) != 0 ) ) { // check authorization for page
if ( gui.authorize && ! await gui.authorize( userId, layoutId, req ) ) {
// not visible for this user
} else if ( layoutId == 'main' && gui.pages['main'].header.logo ) {
// not displayed, because header link
} else {
var nav = {
'layout' : layoutId,
'label' : ( gui.pages[ layoutId ].navLabel ?
gui.pages[ layoutId ].navLabel : gui.pages[ layoutId ].title )
}
if ( gui.pages[ layoutId ].info ) { nav.info = gui.pages[ layoutId ].info }
navTabs.push( nav )
}
}
}
}
if ( gui.dynamicNavCallback ) { // generate nav on the fly via callback
try {
let newNavTabs = await gui.dynamicNavCallback( 'nav-embed-sub', navTabs, req )
if ( newNavTabs ) { navTabs = newNavTabs }
} catch( exc ) { log.warn( 'easy-web-app /svc/nav-embed-sub dynamicNavCallback', exc ) }
}
res.json( { 'navigations' : navTabs } )
}
)
/** web service for multi page navigation bar */
router.get(
'/svc/nav',
async function( req, res ) {
try {
var navTabs = []
var subMenus = {}
var userId = await gui.getUserIdFromReq( req )
// console.log( 'GET /svc/nav '+gui.pages.length )
for ( var layoutId in gui.pages ) {
// console.log( '>>'+layoutId )
if ( gui.pages.hasOwnProperty ( layoutId ) ) {
if ( layoutId.indexOf( '/' ) == -1 ) {
// ignore alternate mobile and tablet layouts
if ( ( layoutId.indexOf( '-nonav' ) == -1 ||
layoutId.indexOf( '-nonav' ) != layoutId.length -6 ) &&
( layoutId.indexOf( '-m' ) == -1 ||
layoutId.indexOf( '-m' ) != layoutId.length -2 ) &&
( layoutId.indexOf( '-t' ) == -1 ||
layoutId.indexOf( '-t' ) != layoutId.length -2 ) ) {
// check authorization for page
if ( gui.authorize && ! await gui.authorize( userId,layoutId, req ) ) {
// not visible for this user
} else if ( layoutId == 'main' && gui.pages['main'].header.logo ) {
// not displayed, because header link
} else {
var nav = {
'layout' : layoutId,
'label' : ( gui.pages[ layoutId ].navLabel ?
gui.pages[ layoutId ].navLabel : gui.pages[ layoutId ].title )
}
if ( gui.pages[ layoutId ].info ) { nav.info = gui.pages[ layoutId ].info }
navTabs.push( nav )
}
}
} else { // sub-menu
var subMenu = layoutId.substr( 0 , layoutId.indexOf( '/' ) )
if ( ! gui.pullDownMenu[ subMenu ] && subMenu != 'user' ) { // if this is not a pull down
if ( ! subMenus[ subMenu ] ) { // first sub menu item creates menu
// ignore alternate mobile and tablet layouts
if ( layoutId.indexOf( '-m' ) != layoutId.length -2 &&
layoutId.indexOf( '-t' ) != layoutId.length -2 ) {
if ( gui.authorize && ! await gui.authorize( userId, layoutId, req ) ) {
// not visible for this user
} else {
subMenus[ subMenu ] = navTabs.length
navTabs.push( {
label : subMenu,
menuItems: []
} )
}
}
}
if ( ( gui.authorize && ! await gui.authorize( userId, layoutId, req ) ) ) {
// not visible for this user
} else if ( subMenu == 'user' ) {
//log.verbose( 'nav','hide user in nav tabs' )
} else {
var nav = {
'layout' : layoutId,
'label' : ( gui.pages[ layoutId ].navLabel ?
gui.pages[ layoutId ].navLabel : gui.pages[ layoutId ].title )
}
if ( gui.pages[ layoutId ].info ) {
nav.info = gui.pages[ layoutId ].info
navTabs[ subMenus[ subMenu ] ].info = '!'
//log.info('nav', navTabs )
}
navTabs[ subMenus[ subMenu ] ].menuItems.push( nav )
}
}
}
}
}
if ( gui.dynamicNavCallback ) { // generate nav on the fly via callback
try {
let newNavTabs = await gui.dynamicNavCallback( 'nav', navTabs, req )
if ( newNavTabs ) { navTabs = newNavTabs }
} catch( exc ) { log.warn( 'easy-web-app /svc/nav dynamicNavCallback', exc ) }
}
// show menu only, if it's more than one page
if ( navTabs.length == 1 && ! Object.keys( gui.pullDownMenu ).length > 0 ) navTabs = []
res.json( { 'navigations' : navTabs } )
} catch ( exc ) {
log.warn( 'easy-web-app /svc/nav', exc )
res.json( { 'navigations' : [] } )
}
}
);
// ----------------------------------------------------------------------------
// i18n:
/** first call switches on i18n, further calls add supported languages */
gui.addLang = function addLang( langCode, translations ) {
var trnsl = {}
if ( translations ) { trnsl = translations }
if ( ! this.lang ) {
this.lang = { }
this.lang[ langCode ] = trnsl
this.pages[ 'main' ].header.modules.push(
{
'id': 'LangSel', 'type': 'i18n'
,'param': { 'langList': [ langCode ] }
}
)
} else {
this.lang[ langCode ] = trnsl
for (var i = 0; i < this.pages[ 'main' ].header.modules.length; i++) {
var mod = this.pages[ 'main' ].header.modules[i]
if ( mod.id == 'LangSel' ) {
mod.param.langList.push( langCode )
}
}
}
}
gui.addTranslation = function addTranslation( langCode, label, translation ) {
if ( gui.lang && gui.lang[ langCode ] ) {
gui.lang[ langCode ][label] = translation
}
}
router.get(
'/i18n/:lang',
async function( req, res ) {
if ( req.params.lang ) {
var langCode = req.params.lang.substring( 0, 2 )
if ( gui.getTranslation ) {
var translation = await gui.getTranslation( req, langCode )
res.json( translation )
} else if ( gui.lang && gui.lang[ langCode ] ) {
res.json( gui.lang[ langCode ] )
} else {
res.json( {} ) // don't offer any translations
}
} else {
res.json( {} ) // don't offer any translations
}
}
)
// ----------------------------------------------------------------------------
/** High level API to add a IO view */
gui.addIoView = function addIoView( page ) {
if ( !this.io ) { // first initialization
this.io = [];
/** REST web service to GET IO data */
router.get (
'/svc/io/:ioId',
function ( req, res ) {
// console.log( 'ping: ' + req.params.ioId );
res.json( gui.io[ req.params.ioId ] );
}
);
router.post(
'/svc/io/:ioId',
jsonParser,
function ( req, res ) {
// console.log( JSON.stringify( req.body ) );
if ( req.body && req.body.id && req.params.ioId ) {
var ioID = req.params.ioId;
var ctlID = req.body.id;
if ( gui.io[ ioID ][ ctlID ] ) {
if ( req.body.value ) {
gui.io[ ioID ][ ctlID ].value = req.body.value;
}
if ( gui.io[ ioID ][ ctlID ].callBack ) {
gui.io[ ioID ][ ctlID ].callBack ( req.body.value , ctlID )
} else {
log.warn( 'POST /svc/io', 'CallBack undefined: "' + ctlID + '"' )
}
} else {
log.warn( 'POST /svc/io', 'Not defined: gui.io[ '+ioID+' ][ '+ctlID+' ]' )
}
} else {
log.warn( 'POST /svc/io', 'Not valid: req.body && req.body.id && req.params.ioId' )
}
res.statusCode = 200;
return res.json( gui.io[ req.params.ioId ] );
}
);
}
var ioId = this.io.length;
this.io.push( {} );
// define IO Object
var io = gui.addView( {
'id' : 'io' + ioId,
'type' : 'pong-io'
},
{