-
Notifications
You must be signed in to change notification settings - Fork 6
/
application.js
executable file
·987 lines (871 loc) · 45.3 KB
/
application.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
var express = require('express');
var router = express.Router();
var block_access = require('../utils/block_access');
var multer = require('multer');
var moment = require('moment');
var request = require('request');
var docBuilder = require('../utils/api_doc_builder');
var upload = multer().single('file');
var Jimp = require("jimp");
var logger = require('../utils/logger');
var process_manager = require('../services/process_manager.js');
var process_server_per_app = process_manager.process_server_per_app;
var session_manager = require('../services/session.js');
var designer = require('../services/designer.js');
var fs = require('fs-extra');
var parser = require('../services/bot.js');
var globalConf = require('../config/global.js');
var gitlabConf = require('../config/gitlab.js');
// Gitlab API
const gitlab = require('../services/gitlab_api');
var helpers = require('../utils/helpers');
var attrHelper = require('../utils/attr_helper');
var gitHelper = require('../utils/git_helper');
var models = require('../models/');
var readline = require('readline');
var structure_application = require('../structure/structure_application');
var pourcent_generation = {};
// Exclude from Editor
var excludeFolder = ["node_modules", "sql", "services", "upload", ".git"];
var excludeFile = [".git_keep", "application.json", "database.js", "global.js", "icon_list.json", "webdav.js"];
function initPreviewData(idApplication, data){
return new Promise(function(resolve, reject) {
var innerPromises = [];
// Editor
var workspacePath = __dirname + "/../workspace/" + idApplication + "/";
var folder = helpers.readdirSyncRecursive(workspacePath, excludeFolder, excludeFile);
/* Sort folder first, file after */
data.workspaceFolder = helpers.sortEditorFolder(folder);
// UI designer entity list
innerPromises.push(new Promise(function(innerResolve, innerReject) {
models.Module.findAll({where: {id_application: idApplication}, include: [{model: models.DataEntity}]}).then(function(modules) {
data.entities = [];
for (var i = 0; i < modules.length; i++) {
for (var j = 0; j < modules[i].DataEntities.length; j++)
data.entities.push(modules[i].DataEntities[j]);
}
function sortEntities(entities, idx) {
if (entities.length == 0 || !entities[idx+1])
return entities;
if (entities[idx].dataValues.name > entities[idx+1].dataValues.name) {
var swap = entities[idx];
entities[idx] = entities[idx+1];
entities[idx+1] = swap;
return sortEntities(entities, idx == 0 ? 0 : idx-1);
}
return sortEntities(entities, idx+1);
}
data.entities = sortEntities(data.entities, 0);
innerResolve();
});
}));
Promise.all(innerPromises).then(function() {
return resolve(data);
}).catch(function(err) {
console.error(err);
reject(err);
});
});
}
var chats = {};
function setChat(req, idApp, idUser, user, content, params, isError){
// Init if necessary
if(!chats[idApp])
chats[idApp] = {};
if(!chats[idApp][idUser])
chats[idApp][idUser] = {items: []};
// Add chat
if(content != "chat.welcome" || chats[idApp][idUser].items.length < 1){
chats[idApp][idUser].items.push({
user: user,
dateEmission: req.moment().format("DD MMM HH:mm"),
content: content,
params: params || [],
isError: isError || false
});
}
}
function execute(req, instruction) {
return new Promise(function(resolve, reject) {
try {
/* Lower the first word for the basic parser jison */
instruction = attrHelper.lowerFirstWord(instruction);
// Instruction to be executed
var attr = parser.parse(instruction);
/* Rework the attr to get value for the code / url / show */
attr = attrHelper.reworkAttr(attr);
attr.id_project = req.session.id_project;
attr.id_application = req.session.id_application;
attr.id_module = req.session.id_module;
attr.id_data_entity = req.session.id_data_entity;
attr.googleTranslate = req.session.toTranslate || false;
attr.lang_user = req.session.lang_user;
attr.currentUser = req.session.passport.user;
if(typeof req.session.gitlab !== "undefined" && typeof req.session.gitlab.user !== "undefined" && !isNaN(req.session.gitlab.user.id))
attr.gitlabUser = req.session.gitlab.user;
else
attr.gitlabUser = null;
var __ = require("../services/language")(req.session.lang_user).__;
if (typeof attr.error !== 'undefined')
throw attr.error;
// Function is finally executed as "global()" using the static dialog designer
// "Options" and "Session values" are sent using the attr attribute
return designer[attr.function](attr, function(err, info) {
if (err) {
var msgErr = __(err.message, err.messageParams || []);
// Error handling code goes here
console.error(err);
return reject(msgErr);
}
switch(attr.function){
case "selectProject":
case "createNewProject":
req.session.id_project = info.insertId;
req.session.id_application = null;
req.session.id_module = null;
req.session.id_data_entity = null;
break;
case "selectApplication":
case "createNewApplication":
req.session.id_application = info.insertId;
req.session.name_application = info.name_application;
req.session.id_module = null;
req.session.id_data_entity = null;
break;
case "selectModule":
case "createNewModule":
req.session.id_module = info.insertId;
req.session.id_data_entity = null;
break;
case "createNewEntity":
case "selectEntity":
case "createNewEntityWithBelongsTo":
case "createNewEntityWithHasMany":
case "createNewBelongsTo":
case "createNewHasMany":
case "createNewFieldRelatedTo":
req.session.id_data_entity = info.insertId;
break;
case "deleteProject":
req.session.id_project = null;
req.session.id_application = null;
req.session.id_module = null;
req.session.id_data_entity = null;
break;
case "deleteApplication":
req.session.id_application = null;
req.session.id_module = null;
req.session.id_data_entity = null;
break;
case "deleteModule":
req.session.id_module = info.homeID;
req.session.id_data_entity = null;
break;
}
var msgInfo = __(info.message, info.messageParams || []);
resolve();
});
} catch (e) {
reject(e);
}
});
}
// Preview Get
router.get('/preview', block_access.hasAccessApplication, function(req, res) {
var id_application = req.query.id_application;
var timeoutServer = 30000;
if(typeof req.query.timeout !== "undefined")
timeoutServer = req.query.timeout;
var currentUserID = req.session.passport.user.id;
req.session.id_application = id_application;
req.session.id_data_entity = null;
var data = {
error: 1,
profile: req.session.passport.user,
menu: "project",
sub_menu: "list_project",
application: "",
answers: "",
instruction: "",
iframe_url: "",
session: ""
};
if (!id_application && typeof process_server_per_app[req.session.id_application] === 'undefined') {
req.session.toastr.push({level: "warning", message: "application.not_started"});
return res.redirect('/application/list');
}
setChat(req, id_application, currentUserID, "Mipsy", "chat.welcome", []);
models.Application.findOne({where: {id: id_application}}).then(function(application) {
req.session.id_project = application.id_project;
models.Module.findAll({where: {id_application: application.id}, order: [["id_application", "ASC"]]}).then(function(modules) {
let currentModule = modules[0];
req.session.id_module = currentModule.id;
var math = require('math');
var port = math.add(9000, application.id);
var env = Object.create(process.env);
env.PORT = port;
var timer = 50;
var serverCheckCount = 0;
if (process_server_per_app[application.id] == null || typeof process_server_per_app[application.id] === "undefined") {
// Launch server for preview
process_server_per_app[application.id] = process_manager.launchChildProcess(req, application.id, env);
timer = 500;
}
// var protocol = globalConf.protocol;
var protocol_iframe = globalConf.protocol_iframe;
var host = globalConf.host;
var attr = new Array();
attr.id_project = req.session.id_project;
attr.id_application = req.session.id_application;
attr.id_module = req.session.id_module;
attr.id_data_entity = req.session.id_data_entity;
attr.currentUser = req.session.passport.user;
if(typeof req.session.gitlab !== "undefined" && typeof req.session.gitlab.user !== "undefined" && !isNaN(req.session.gitlab.user.id))
attr.gitlabUser = req.session.gitlab.user;
else
attr.gitlabUser = null;
session_manager.getSession(attr, req, function(err, info) {
data.session = info;
initPreviewData(req.session.id_application, data).then(function(data) {
let initialTimestamp = new Date().getTime();
let iframe_status_url;
function checkServer() {
if (new Date().getTime() - initialTimestamp > timeoutServer) {
// Get last error from app logs
let lastError = helpers.getLastLoggedError(id_application);
let chatKey = "structure.global.restart.error";
let chatParams = [lastError];
// If missing module error
if(typeof lastError === "string" && lastError.indexOf("Cannot find module") != -1){
chatKey = "structure.global.restart.missing_module";
lastError = lastError.split("Cannot find module")[1].replace(/'/g, "").trim();
chatParams = [lastError, lastError];
}
setChat(req, id_application, currentUserID, "Mipsy", chatKey, chatParams, true);
data.iframe_url = -1;
data.chat = chats[id_application][currentUserID];
return res.render('front/preview', data);
}
iframe_status_url = protocol_iframe + '://';
if (globalConf.env == 'cloud')
iframe_status_url += globalConf.sub_domain + '-' + application.codeName.substring(2) + "." + globalConf.dns + '/default/status';
else
iframe_status_url += host + ":" + port + "/default/status";
let rejectUnauthorized = globalConf.env == 'cloud' ? true : false;
request({
rejectUnauthorized: rejectUnauthorized,
url: iframe_status_url,
method: "GET"
}, function(error, response, body) {
if (error)
return setTimeout(checkServer, 100);
//Check for right status code
if (response.statusCode !== 200) {
console.warn('Server not ready - Invalid Status Code Returned:', response.statusCode);
return setTimeout(checkServer, 100);
}
//All is good. Print the body
console.log("Server status is OK"); // Show the HTML for the Modulus homepage.
data.error = 0;
data.application = currentModule;
data.iframe_url = iframe_status_url.split("/default/status")[0]+"/default/home";
data.idApp = application.id;
// Let's do git init or commit depending the env (only on cloud env for now)
gitHelper.doGit(attr, function(err){
if(err)
setChat(req, id_application, currentUserID, "Mipsy", err.message, [], true);
data.chat = chats[id_application][currentUserID];
res.render('front/preview', data);
});
});
}
// Check server has started every 50 ms
console.log('Waiting for server to start');
checkServer();
});
});
});
}).catch(function(err) {
initPreviewData(req.session.id_application, data).then(function(data) {
data.code = 500;
console.error(err);
res.render('common/error', data);
}).catch(function(err) {
data.code = 500;
console.error(err);
res.render('common/error', data);
});
});
});
// AJAX Preview Post
router.post('/fastpreview', block_access.hasAccessApplication, function(req, res) {
var math = require('math');
var port = math.add(9000, req.session.id_application);
var env = Object.create(process.env);
env.PORT = port;
var protocol_iframe = globalConf.protocol_iframe;
var host = globalConf.host;
var timeoutServer = 30000;
// Parse instruction and set results
models.Application.findById(req.session.id_application).then(function(application) {
req.session.name_application = application.codeName.substring(2);
var instruction = req.body.instruction.trim() || "";
var currentUserID = req.session.passport.user.id;
var currentAppID = application.id;
var data = {
error: 1,
profile: req.session.passport.user,
instruction: instruction,
session: {
id_project: req.session.id_project,
id_application: req.session.id_application,
id_module: req.session.id_module,
id_data_entity: req.session.id_data_entity
}
};
try {
/* Add instruction in chat */
setChat(req, currentAppID, currentUserID, req.session.passport.user.login, instruction, []);
/* Lower the first word for the basic parser json */
instruction = attrHelper.lowerFirstWord(instruction);
/* Parse the instruction to get an object for the designer */
var attr = parser.parse(instruction);
/* Rework the attr to get value for the code / url / show */
attr = attrHelper.reworkAttr(attr);
data.iframe_url = process_manager.childUrl(req, attr.function);
// We simply add session values in attributes array
attr.instruction = instruction;
attr.id_project = req.session.id_project;
attr.id_application = req.session.id_application;
attr.id_module = req.session.id_module;
attr.id_data_entity = req.session.id_data_entity;
attr.googleTranslate = req.session.toTranslate || false;
attr.lang_user = req.session.lang_user;
attr.currentUser = req.session.passport.user;
attr.gitlabUser = null;
if(typeof req.session.gitlab !== "undefined" && typeof req.session.gitlab.user !== "undefined" && !isNaN(req.session.gitlab.user.id))
attr.gitlabUser = req.session.gitlab.user;
if (typeof attr.error !== 'undefined'){
var err = new Error();
err.message = attr.error;
err.messageParams = attr.errorParams;
throw err;
}
if (typeof designer[attr.function] !== 'function')
throw new Error("Designer doesn't have function "+attr.function);
// Function is finally executed as "globalConf()" using the static dialog designer
// "Options" and "Session values" are sent using the attr attribute
designer[attr.function](attr, function(err, info) {
var answer;
/* If restart server then redirect to /application/preview?id_application=? */
var toRestart = false;
if (err) {
// Error handling code goes here
console.error(err);
if(typeof err.message === "undefined")
answer = err;
else
answer = err.message;
// Winston log file
logger.debug(answer);
//Generator answer
setChat(req, currentAppID, currentUserID, "Mipsy", answer, err.messageParams, true);
/* Save ERROR an instruction history in the history script in workspace folder */
if(attr.function != 'restart'){
var historyScriptPath = __dirname+'/../workspace/'+req.session.id_application+'/history_script.nps';
var historyScript = fs.readFileSync(historyScriptPath, 'utf8');
historyScript += "\n//ERROR: "+instruction+" ("+answer+")";
fs.writeFileSync(historyScriptPath, historyScript);
}
// Load session values
session_manager.getSession(attr, req, function(err, infoSession) {
data.session = infoSession;
data.chat = chats[currentAppID][currentUserID];
initPreviewData(req.session.id_application, data).then(function(data) {
//res.render('front/preview', data);
res.send(data);
});
});
} else {
/* Save an instruction history in the history script in workspace folder */
if(attr.function != 'restart'){
var historyScriptPath = __dirname+'/../workspace/'+req.session.id_application+'/history_script.nps';
var historyScript = fs.readFileSync(historyScriptPath, 'utf8');
historyScript += "\n"+instruction;
fs.writeFileSync(historyScriptPath, historyScript);
}
// Store key entities in session for futur instruction
session_manager.setSession(attr.function, req, info, data);
if (attr.function == "deleteApplication"){
return res.send({
toRedirect: true,
url: "/default/home"
});
} else if (attr.function == 'restart' || attr.function == 'installNodePackage'){
toRestart = true;
}
// Generator answer
setChat(req, currentAppID, currentUserID, "Mipsy", info.message, info.messageParams);
var sessionID = req.sessionID;
var timer = 50;
var serverCheckCount = 0;
// Relaunch server
var env = Object.create(process.env);
env.PORT = port;
// If we stop the server manually we loose some stored data, so we just need to redirect.
if(typeof process_server_per_app[req.session.id_application] === "undefined"){
return res.send({
toRedirect: true,
url: "/application/preview?id_application="+req.session.id_application
});
}
// Kill server first
process_manager.killChildProcess(process_server_per_app[req.session.id_application].pid, function() {
// Launch a new server instance to reload resources
process_server_per_app[req.session.id_application] = process_manager.launchChildProcess(req, req.session.id_application, env);
// Load session values
var newAttr = {};
newAttr.id_project = req.session.id_project;
newAttr.id_application = req.session.id_application;
newAttr.id_module = req.session.id_module;
newAttr.id_data_entity = req.session.id_data_entity;
session_manager.getSession(newAttr, req, function(err, info) {
docBuilder.build(req.session.id_application).catch(function(err){
console.error(err);
});
data.session = info;
initPreviewData(req.session.id_application, data).then(function(data) {
let initialTimestamp = new Date().getTime();
let iframe_status_url;
function checkServer() {
// Server Timeout
if (new Date().getTime() - initialTimestamp > timeoutServer) {
// Get last error from app logs
let lastError = helpers.getLastLoggedError(currentAppID);
let chatKey = "structure.global.restart.error";
let chatParams = [lastError];
// If missing module error
if(typeof lastError === "string" && lastError.indexOf("Cannot find module") != -1){
chatKey = "structure.global.restart.missing_module";
lastError = lastError.split("Cannot find module")[1].replace(/'/g, "").trim();
chatParams = [lastError, lastError];
}
setChat(req, currentAppID, currentUserID, "Mipsy", chatKey, chatParams, true);
data.iframe_url = -1;
data.chat = chats[currentAppID][currentUserID];
return res.send(data);
}
iframe_status_url = protocol_iframe + '://';
if (globalConf.env == 'cloud')
iframe_status_url += globalConf.sub_domain + '-' + req.session.name_application + "." + globalConf.dns + '/default/status';
else
iframe_status_url += host + ":" + port + "/default/status";
let rejectUnauthorized = globalConf.env == 'cloud' ? true : false;
request({
rejectUnauthorized: rejectUnauthorized,
url: iframe_status_url,
method: "GET"
}, function(error, response, body) {
// Check for error
if (error)
return setTimeout(checkServer, 100);
// Check for right status code
if (response.statusCode !== 200) {
console.warn('Server not ready - Invalid Status Code Returned:', response.statusCode);
return setTimeout(checkServer, 100);
}
// Everything's ok
console.log("Server status is OK");
if(toRestart) {
data.chat = chats[currentAppID][currentUserID];
data.isRestart = true;
return res.send(data);
} else {
// Let's do git init or commit depending the env (only on cloud env for now)
gitHelper.doGit(attr, function(err){
if(err)
setChat(req, currentAppID, currentUserID, "Mipsy", err.message, [], true);
// Call preview page
data.chat = chats[currentAppID][currentUserID];
res.send(data);
});
}
});
}
// Check if the server has started
console.log('Waiting for server to start');
checkServer();
});
});
});
}
});
} catch(error){
setChat(req, currentAppID, currentUserID, "Mipsy", error.message, error.messageParams, true);
// Load session values
var attr = {};
attr.id_project = req.session.id_project;
attr.id_application = req.session.id_application;
attr.id_module = req.session.id_module;
attr.id_data_entity = req.session.id_data_entity;
session_manager.getSession(attr, req, function(err, info) {
data.chat = chats[currentAppID][currentUserID];
data.session = info;
initPreviewData(req.session.id_application, data).then(function(data) {
res.send(data);
});
});
}
});
});
// Dropzone FIELD ajax upload file
router.post('/set_logo', block_access.hasAccessApplication, function (req, res) {
upload(req, res, function (err) {
if (!err) {
if (req.body.storageType == 'local') {
var configLogo = {
folder: 'thumbnail/',
height: 30,
width: 30,
quality: 60
};
var dataEntity = req.body.dataEntity;
if (!!dataEntity) {
var basePath = __dirname + "/../workspace/" + req.body.idApp + "/public/img/" + dataEntity + '/';
fs.mkdirs(basePath, function (err) {
if (!err) {
var uploadPath = basePath + req.file.originalname;
var outStream = fs.createWriteStream(uploadPath);
outStream.write(req.file.buffer);
outStream.end();
outStream.on('finish', function (err) {
res.json({
success: true
});
});
if (req.body.dataType == 'picture') {
//We make thumbnail and reuse it in datalist
basePath = __dirname + "/../workspace/"+req.body.idApp+"/public/img/"+ dataEntity + '/' + configLogo.folder ;
fs.mkdirs(basePath, function (err) {
if (!err) {
Jimp.read(uploadPath, function (err, imgThumb) {
if (!err) {
imgThumb.resize(configLogo.height, configLogo.width)
.quality(configLogo.quality) // set JPEG quality
.write(basePath + req.file.originalname);
} else {
console.error(err);
}
});
} else {
console.error(err);
}
});
}
} else{
console.error(err);
res.status(500).end(err);
}
});
} else{
var err = new Error();
err.message = 'Internal error, entity not found.';
res.status(500).end(err);
}
} else{
var err = new Error();
err.message = 'Storage type not found.';
res.status(500).end(err);
}
} else{
console.error(err);
res.status(500).end(err);
}
});
});
// List all applications
router.get('/list', block_access.isLoggedIn, function(req, res) {
(async () => {
let projects = await models.Project.findAll({
include: [{
model: models.Application,
required: true,
include: [{
model: models.User,
as: "users",
where: {
id: req.session.passport.user.id
},
required: true
}]
}],
order: [
[models.Application, 'id', 'DESC']
]
});
let iframe_status_url;
let host = globalConf.host;
let port;
let appName;
let data = {};
// Get user project for clone url generation
let gitlabProjects = [];
if(gitlabConf.doGit && req.session.gitlab && req.session.gitlab.user)
gitlabProjects = await gitlab.getAllProjects(req.session.gitlab.user.id);
for (var i = 0; i < projects.length; i++) {
for (var j = 0; j < projects[i].Applications.length; j++) {
iframe_status_url = globalConf.protocol_iframe + '://';
port = 9000 + parseInt(projects[i].Applications[j].id);
appName = projects[i].Applications[j].codeName.substring(2);
if (globalConf.env == 'cloud'){
iframe_status_url += globalConf.sub_domain + '-' + appName + "." + globalConf.dns + '/';
} else {
iframe_status_url += host + ":" + port + "/";
}
if(gitlabConf.doGit){
let project = gitlabProjects.filter(x => x.name == globalConf.host + "-" + appName)[0];
if(project) {
// projects[i].dataValues.Applications[j].dataValues.repo_url = gitlabConf.protocol + "://" + gitlabConf.url + "/" + req.session.gitlab.user.username + "/" + globalConf.host.replace(/\./g, "-") + "-" + appName + ".git"
projects[i].dataValues.Applications[j].dataValues.repo_url = project.http_url_to_repo;
data.gitlabUser = req.session.gitlab.user;
}
}
projects[i].dataValues.Applications[j].dataValues.url = iframe_status_url;
}
}
data.projects = projects
return data;
})().then(data => {
res.render('front/application', data);
}).catch(err => {
console.error(err);
data.code = 500;
res.render('common/error', data);
})
});
router.post('/execute', block_access.isLoggedIn, function(req, res) {
var instruction = req.body.instruction || '';
var data = {
instruction: instruction
};
instruction = instruction.split(';');
var done = 0;
for (var i = 0; i < instruction.length; i++) {
execute(req, instruction[i]).then(function() {
if (++done == instruction.length) {
data.id_application = req.session.id_application;
res.send(data);
}
}).catch(function(err) {
console.error(err);
if (++done == instruction.length) {
data.id_application = req.session.id_application;
res.status(500).send(err);
}
});
}
});
router.post('/initiate', block_access.isLoggedIn, function(req, res) {
pourcent_generation[req.session.passport.user.id] = 1;
var name_project = req.body.project || '';
var name_application = req.body.application || '';
var select_project = req.body.selectProject || '';
if(select_project == "" && (name_project == "" || name_application == "")){
console.error("Une erreur est survenue. Projet et/ou application non renseigné.");
req.session.toastr = [{
message: "Une erreur est survenue. Projet et/ou application non renseigné.",
level: "error"
}];
return res.redirect('/default/home');
}
else if(name_application == ""){
console.error("Une erreur est survenue. Nom d'application non renseigné.");
req.session.toastr = [{
message: "Une erreur est survenue. Nom d'application non renseigné.",
level: "error"
}];
return res.redirect('/default/home');
}
var data = {
"error": 1,
"menu": "live",
"answers": "",
"instruction": instructions
};
var done = 0;
var instructions = [];
if(select_project != "")
instructions.push("select project " + select_project);
else
instructions.push("create project " + name_project);
instructions.push("create application " + name_application);
instructions.push("create module home");
// Authentication module
instructions.push("create module Administration");
instructions.push("create entity User");
instructions.push("add field login");
instructions.push("set field login required");
instructions.push("set field login unique");
instructions.push("add field password");
instructions.push("add field email with type email");
instructions.push("add field token_password_reset");
instructions.push("add field enabled with type number");
instructions.push("set icon user");
instructions.push("create entity Role");
instructions.push("add field label");
instructions.push("set field label required");
instructions.push("set field label unique");
instructions.push("set icon asterisk");
instructions.push("create entity Group");
instructions.push("add field label");
instructions.push("set field label required");
instructions.push("set field label unique");
instructions.push("set icon users");
instructions.push("select entity User");
instructions.push("add field Role related to many Role using label");
instructions.push("add field Group related to many Group using label");
instructions.push("set field Role required");
instructions.push("set field Group required");
instructions.push("entity Role has many user");
instructions.push("entity Group has many user");
instructions.push("add entity API credentials");
instructions.push("add field Client Name");
instructions.push("add field Client Key");
instructions.push("add field Client Secret");
instructions.push("set icon key");
instructions.push("add field role related to many Role using label");
instructions.push("add field group related to many Group using label");
instructions.push("add field Token");
instructions.push("add field Token timeout TMSP");
instructions.push("add entity Synchronization");
instructions.push("entity Synchronization has one API credentials");
instructions.push("add field Journal backup file");
instructions.push("add entity Synchro credentials");
instructions.push("add field Cloud host with type url");
instructions.push("add field Client key");
instructions.push("add field Client secret");
instructions.push("set icon unlink");
instructions.push("add widget stat on entity User");
// Component status base
instructions.push("add entity Status");
instructions.push("set icon tags");
instructions.push("add field Entity");
instructions.push("add field Field");
instructions.push("add field Name");
instructions.push("add field Color with type color");
instructions.push("add field Accepted group related to many Group using Label");
instructions.push("add field Button label");
instructions.push("add field Position with type number");
instructions.push("add field Default with type boolean");
instructions.push("add field Comment with type boolean");
instructions.push("entity Status has many Status called Children");
instructions.push("entity status has many Translation called Translations");
instructions.push("select entity translation");
instructions.push("add field Language");
instructions.push("add field Value");
instructions.push("create entity Robot");
instructions.push("set icon android");
instructions.push("add field Current status with type enum and values CONNECTED, DISCONNECTED, WORKING");
instructions.push("add field Name");
instructions.push("add field Api credentials related to api credentials using client name");
instructions.push("add field Comment with type regular text");
instructions.push("create entity Task");
instructions.push("set icon cogs");
instructions.push("add component status with name State");
instructions.push("add field Title");
instructions.push("set field Title required");
instructions.push("add field Type with type enum and values Manual, Automatic and default value Manual");
instructions.push("add field Planned date with type date");
instructions.push("add field Execution start date with type date");
instructions.push("add field Execution finish date with type date");
instructions.push("add field Duration with type decimal");
instructions.push("add field Data flow with type regular text");
instructions.push("add field Robot related to Robot using Name");
instructions.push("add field Program file with type file");
instructions.push("add field Procedure with type regular text");
instructions.push("add component localfilestorage with name Documents");
instructions.push("create entity Media");
instructions.push("set icon envelope");
instructions.push("add field Type with type enum and values Mail, Notification, SMS, Task");
instructions.push("add field Name");
instructions.push("set field Name required");
instructions.push("add field Target entity");
instructions.push("entity Media has one Media Mail");
instructions.push("entity Media has one Media Notification");
instructions.push("entity Media has one Media SMS");
instructions.push("entity Media has one Media Task");
instructions.push("select entity media task");
instructions.push("add field Task name");
instructions.push("add field Task type with type enum and values Manual, Automatic and default value Manual");
instructions.push("add field Assignment logic");
instructions.push("add field Program file with type file");
instructions.push("add field Data flow with type text");
instructions.push("entity status has many Action called Actions");
instructions.push("select entity action");
instructions.push("add field Media related to Media using name");
instructions.push("add field Order with type number");
instructions.push("add field Execution with type enum and values Immédiate, Différée with default value Immédiate");
instructions.push("select entity media mail");
instructions.push("add field To");
instructions.push("add field Cc");
instructions.push("add field Cci");
instructions.push("add field From");
instructions.push("add field Attachments");
instructions.push("add field Subject");
instructions.push("add field Content with type text");
instructions.push("select entity media notification");
instructions.push("add field Title");
instructions.push("add field Description");
instructions.push("add field Icon");
instructions.push("add field Color with type color");
instructions.push("add field targets");
instructions.push("add entity Notification");
instructions.push("add field Title");
instructions.push("add field Description");
instructions.push("add field URL");
instructions.push("add field Color with type color");
instructions.push("add field Icon");
instructions.push("select entity media SMS");
instructions.push("add field Message with type text");
instructions.push("add field Phone numbers");
instructions.push("entity user has many notification");
instructions.push("entity notification has many user");
// Inline help
instructions.push("add entity Inline Help");
instructions.push("set icon question-circle-o");
instructions.push("add field Entity");
instructions.push("add field Field");
instructions.push("add field Content with type text");
// Set default theme if different than blue-light
if(typeof req.session.defaultTheme !== "undefined" && req.session.defaultTheme != "blue-light")
instructions.push("set theme "+req.session.defaultTheme);
// Set home module selected
instructions.push("select module home");
function recursiveExecute(recurInstructions, idx) {
// All instructions executed
if (recurInstructions.length == idx) {
structure_application.initializeApplication(req.session.id_application, req.session.passport.user.id, req.session.name_application).then(function() {
docBuilder.build(req.session.id_application);
res.redirect('/application/preview?id_application=' + req.session.id_application);
})
return;
}
execute(req, recurInstructions[idx]).then(function(){
pourcent_generation[req.session.passport.user.id] = idx == 0 ? 1 : Math.floor(idx * 100 / recurInstructions.length);
recursiveExecute(recurInstructions, ++idx);
}).catch(function(err){
req.session.toastr = [{
message: err,
level: "error"
}];
return res.redirect('/default/home');
});
}
recursiveExecute(instructions, 0);
});
router.get('/get_pourcent_generation', block_access.isLoggedIn, function(req, res) {
var data = {};
data.pourcent = pourcent_generation[req.session.passport.user.id];
res.json(data);
});
module.exports = router;