flexbiz-server 12.3.18 → 12.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/package.json +1 -1
  2. package/server/app.js +18 -255
  3. package/server/cluster.js +22 -303
  4. package/server/controllers/controller.js +77 -2510
  5. package/server/controllers/controllerRPT.js +22 -857
  6. package/server/controllers/controllerRPT_v1.js +71 -0
  7. package/server/controllers/controllerUtils.js +65 -1173
  8. package/server/controllers/controller_v1.js +361 -6970
  9. package/server/controllers/createHandler.js +32 -717
  10. package/server/controllers/createRouteHandler.js +4 -0
  11. package/server/controllers/deleteHandler.js +11 -0
  12. package/server/controllers/exportHandler.js +18 -390
  13. package/server/controllers/findHandler.js +44 -881
  14. package/server/controllers/historyHandler.js +2 -0
  15. package/server/controllers/importFromExcelHandler.js +14 -0
  16. package/server/controllers/importFromGsHandler.js +10 -0
  17. package/server/controllers/importFromJsonHandler.js +6 -0
  18. package/server/controllers/importHandler.js +19 -344
  19. package/server/controllers/logHandler.js +3 -0
  20. package/server/controllers/rptCreateRouteHandler.js +4 -0
  21. package/server/controllers/rptExcelHandler.js +33 -0
  22. package/server/controllers/rptHandler.js +11 -0
  23. package/server/controllers/taskQueue.js +25 -0
  24. package/server/controllers/updateBookHandler.js +12 -0
  25. package/server/controllers/updateFieldHandler.js +12 -0
  26. package/server/controllers/updateHandler.js +34 -731
  27. package/server/controllers/updateKeyHandler.js +12 -0
  28. package/server/controllers/viewHandler.js +12 -208
  29. package/server/global.js +1 -1
  30. package/server/models/customer.js +3 -3
  31. package/server/route.js +2 -2
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "flexbiz-server",
3
3
  "main": "./server/app.js",
4
4
  "description": "Flexible Server",
5
- "version": "12.3.18",
5
+ "version": "12.3.20",
6
6
  "author": {
7
7
  "name": "Van Truong Pham",
8
8
  "email": "invncur@gmail.com"
package/server/app.js CHANGED
@@ -1,255 +1,18 @@
1
- //require('events').EventEmitter.prototype._maxListeners = 10000;
2
- require('events').EventEmitter.defaultMaxListeners = 10000000;
3
-
4
- const express = require('express');
5
- const bodyParser = require('body-parser');
6
-
7
- const passport = require('passport');
8
- const https = require("https");
9
- const http = require('http');
10
- const fs = require("fs");
11
- const cors=require('cors');
12
- //const path = require("path");
13
- // eslint-disable-next-line no-unused-vars
14
- const _global = require('./global');
15
- const User = global.getModel('user');
16
- const defaultConfigs = require('./defaultConfigs');
17
- const crypto = require("crypto");
18
-
19
- const mainServer = function(app,options={cluster:true,port:443,useSocket:true},callbackServer= null) {
20
- const configs = global.configs = {...defaultConfigs,...options.configs};
21
- //console.log("request size",configs.limitRequestSize,configs.limitFileSize)
22
-
23
- if(!configs.admins) configs.admins = configs.adminUsers.map(u=>u.email);
24
- if(!configs.supportUsers) configs.supportUsers =[...configs.admins];
25
-
26
- if(!configs.public_token) configs.public_token = "flex.public.token";
27
- global.port = options.port || configs.PORT || 443;
28
-
29
- //set timezone
30
- const moment = require('moment-timezone');
31
- moment.tz.setDefault(configs.timezone || 'Asia/Ho_Chi_Minh');
32
- //app
33
- if(!app) app = express();
34
- app.set('trust proxy', 1);
35
- //check too busy
36
- const toobusy = require('toobusy-js');
37
- if(configs.maxLag) toobusy.maxLag(configs.maxLag);
38
-
39
- toobusy.onLag(function(currentLag) {
40
- console.log("Event loop lag detected! Latency: " + currentLag + "ms. maxLag",configs.maxLag);
41
- });
42
- app.use(function(req, res, next) {
43
- if (toobusy()) {
44
- console.error("Server is busy right now. This request has been cancel:",req.originalUrl);
45
- res.status(503).send({error:"Server is busy right now, sorry."});
46
- } else {
47
- next();
48
- }
49
- });
50
- //
51
- const session = require('express-session');
52
- app.use(session({secret: 'QV098PVT123456HLBN', resave: false, saveUninitialized: true,cookie: { secure: false }}));
53
-
54
- //cookie uid
55
- const cookieParser = require('cookie-parser')
56
- app.use(cookieParser())
57
- app.use(function (req, res, next) {
58
- let uid = req.cookies.uid;
59
- if(!uid){
60
- uid = req.headers["uid"];
61
- }
62
- if(!uid){
63
- uid = "uid:" + crypto.randomBytes(20).toString('hex')
64
- res.cookie("uid",uid,{
65
- expires: new Date(Date.now() + 365 * 24 * 3600000), // cookie will be removed after 24 hours,
66
- sameSite: 'none',
67
- secure:true
68
- });
69
- }
70
- res.set('uid', uid);
71
- //console.log("uid",uid,req.originalUrl,req.method);
72
- req.cookies.uid = uid;
73
- next();
74
- })
75
- //compression
76
- const compress = require('compression');
77
- app.use(compress());
78
- //allow upload file to server
79
- const root_dir_uploads = configs.paths.uploads || (__dirname + '/uploads');
80
- const limitFileSize = configs.limitFileSize || 1024 * 1024 * 1;
81
- app.use(function (req, res, next) {
82
- const size = req.headers['content-lenght'];
83
- if(size && size> limitFileSize){
84
- return res.status(400).send({error:"File too large"});
85
- }
86
- next()
87
- })
88
- const multer = require('multer')({
89
- dest: root_dir_uploads,
90
- limits: {files:1,fileSize: limitFileSize }
91
- });
92
- app.use(multer);
93
- //allow cross domain
94
- const corsOptions = {
95
- credentials: true,
96
- exposedHeaders: ["set-cookie","uid"],
97
- origin: (origin, callback) => {
98
- callback(null, true);
99
- }
100
- }
101
- app.use(cors(corsOptions));
102
- if(!configs.paths) configs.paths={}
103
- //static
104
- if(options.lite!==true){
105
- app.use('/', express.static(configs.paths.public || __dirname + '/public'));
106
- app.use('/admin', express.static(configs.paths.admin || (__dirname + '/admin')));
107
- app.use('/templates', express.static(configs.paths.templates|| (__dirname + '/templates')));
108
- app.use('/images', express.static(configs.paths.images || (__dirname + '/images')));
109
- }
110
- //
111
- app.use(bodyParser.json({limit: (configs.limitRequestSize||'1mb')}));
112
- app.use(bodyParser.urlencoded({limit: (configs.limitRequestSize||'1mb'),extended: true}));
113
-
114
- app.use(passport.initialize());
115
- //log access
116
- const morgan = require('morgan')
117
- const rfs = require('rotating-file-stream')
118
- const logDirectory = configs.paths.log || (__dirname + '/log');
119
- fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
120
- const accessLogStream = rfs('access.log', {
121
- interval: '1d', // rotate daily
122
- path: logDirectory
123
- })
124
- app.use(morgan('combined', {
125
- stream: accessLogStream,
126
- skip: function(req, res) {
127
- return res.statusCode < 400
128
- }
129
- }))
130
- //handle error default
131
- // eslint-disable-next-line no-unused-vars
132
- app.use(function (err, req, res, next) {
133
- console.error(err.stack)
134
- res.status(500).send('Server Error!')
135
- })
136
- //connect to mongodb
137
- global.mongoose.connect(configs.database.url,{ useNewUrlParser: true }).then(async () => {
138
- console.log("Connected to Database");
139
- //connect to redis
140
- const redis = require('redis');
141
- global.clientRedis = redis.createClient();
142
- global.clientRedis.on("error", (err) => console.error("Redis Client Error", err));
143
- global.clientRedis.on("end", () => {
144
- console.error("Redis connection closed.");
145
- });
146
- global.clientRedis.on("connect", function() {
147
- console.log("redis connected");
148
- if(options.createRedisCache!=false){
149
- const redisCache = require('./libs/redis-cache');
150
- redisCache.set();
151
- }
152
- //start abci. xu ly cac su kien lien quan den dau tu
153
- if(options.start_abci_handler){
154
- const assabcihandler = global.getModel("assabcihandler");
155
- assabcihandler.start();
156
- }
157
- //
158
- if(options.lite!==true){
159
- //routes
160
- const route = require('./route');
161
- route(app,()=>{
162
- //create server
163
- if(options.createServer!==false){
164
- const sticky = require('sticky-session');
165
- let server;
166
- if (configs.use_ssl) {
167
- const sslConfig = require("./sslConfig");
168
- server = https.createServer(sslConfig(options.sslDir), app);
169
- } else {
170
- server = http.createServer(app);
171
- }
172
- server.timeout = 10*60*1000;
173
- //init socket
174
- if(options.useSocket!==false){
175
- User.initSocket(server);
176
- }else{
177
- User.initClientSockets();
178
- }
179
- if(options.cluster!==false){
180
- //start server with cluster
181
- if (!sticky.listen(server, global.port)) {
182
- // Master code
183
- server.once('listening', function() {
184
- console.log('server started on',global.port);
185
- });
186
- } else {
187
- // Worker code
188
- }
189
- const cluster = require('cluster');
190
- cluster.on('exit', function(worker, code, signal) {
191
- console.error('worker ' + worker.process.pid + ' died', code, signal);
192
- });
193
- cluster.on('online', function(worker) {
194
- console.info('worker ' + worker.process.pid + ' is online');
195
- });
196
- }else{
197
- server.listen(global.port, () => {
198
- console.log('server start at ' + global.port + ' port');
199
- });
200
- }
201
- }
202
- if(options.start_import_data_pool){
203
- const StaticPool = require("./libs/WorkerStaticPool");
204
- global.importDataMainPool = new StaticPool(__dirname + '/workers/inputWorker.js',options.max_queue_imports||0);
205
- global.importDataMainPool.exec({
206
- load:true,
207
- configs: JSON.stringify(configs),
208
- },()=>{
209
- console.log("load import data pool");
210
- })
211
- }
212
- if(options.start_report_pool){
213
- const StaticPool = require("./libs/WorkerStaticPool");
214
- global.reportMainPool = new StaticPool(__dirname + '/workers/reportWorker.js',options.max_queue_reports||0);
215
- global.reportMainPool.exec({
216
- load:true,
217
- configs: JSON.stringify(configs),
218
- },()=>{
219
- console.log("load report pool");
220
- })
221
- }
222
- if(callbackServer) callbackServer();
223
- });
224
- }else{
225
- //routes
226
- const route = require('./route');
227
- route(app,()=>{
228
- if(callbackServer) callbackServer();
229
- },true);
230
- }
231
- });
232
- }).catch((err) => {
233
- console.log("Not Connected to Database ERROR! ", err);
234
- });
235
- return app;
236
- }
237
- process.on('uncaughtException', function (err) {
238
- console.error((new Date).toUTCString() + ' uncaughtException:', err.message);
239
- console.error(err.stack);
240
- let error = `
241
- Error: ${err.message}
242
- Stack: ${err.stack}
243
- `
244
- try{
245
- const logDirectory = (__dirname + '/log');
246
- fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
247
- fs.writeFile(`${logDirectory}/error-${new Date().getTime()}.txt`,error,()=>{
248
- console.log("wrote log error");
249
- });
250
- }catch(e){
251
- console.log(e);
252
- }
253
- process.exit(1)
254
- })
255
- module.exports = mainServer
1
+ 'use strict';require("events").EventEmitter.defaultMaxListeners=1E7;
2
+ const express=require("express"),bodyParser=require("body-parser"),passport=require("passport"),https=require("https"),http=require("http"),fs=require("fs"),cors=require("cors"),_global=require("./global"),User=global.getModel("user"),defaultConfigs=require("./defaultConfigs"),crypto=require("crypto"),mainServer=function($app$$,$options$$={cluster:!0,port:443,useSocket:!0},$callbackServer$$=null){const $configs$$=global.configs={...defaultConfigs,...$options$$.configs};$configs$$.admins||($configs$$.admins=
3
+ $configs$$.adminUsers.map($u$$=>$u$$.email));$configs$$.supportUsers||($configs$$.supportUsers=[...$configs$$.admins]);$configs$$.public_token||($configs$$.public_token="flex.public.token");global.port=$options$$.port||$configs$$.PORT||443;require("moment-timezone").tz.setDefault($configs$$.timezone||"Asia/Ho_Chi_Minh");$app$$||($app$$=express());$app$$.set("trust proxy",1);const $toobusy$$=require("toobusy-js");$configs$$.maxLag&&$toobusy$$.maxLag($configs$$.maxLag);$toobusy$$.onLag(function($currentLag$$){console.log("Event loop lag detected! Latency: "+
4
+ $currentLag$$+"ms. maxLag",$configs$$.maxLag)});$app$$.use(function($req$$,$res$$,$next$$){$toobusy$$()?(console.error("Server is busy right now. This request has been cancel:",$req$$.originalUrl),$res$$.status(503).send({error:"Server is busy right now, sorry."})):$next$$()});var $compress_cookieParser_morgan_multer_root_dir_uploads_session$$=require("express-session");$app$$.use($compress_cookieParser_morgan_multer_root_dir_uploads_session$$({secret:"QV098PVT123456HLBN",resave:!1,saveUninitialized:!0,
5
+ cookie:{secure:!1}}));$compress_cookieParser_morgan_multer_root_dir_uploads_session$$=require("cookie-parser");$app$$.use($compress_cookieParser_morgan_multer_root_dir_uploads_session$$());$app$$.use(function($req$$,$res$$,$next$$){let $uid$$=$req$$.cookies.uid;$uid$$||($uid$$=$req$$.headers.uid);$uid$$||($uid$$="uid:"+crypto.randomBytes(20).toString("hex"),$res$$.cookie("uid",$uid$$,{expires:new Date(Date.now()+31536E6),sameSite:"none",secure:!0}));$res$$.set("uid",$uid$$);$req$$.cookies.uid=$uid$$;
6
+ $next$$()});$compress_cookieParser_morgan_multer_root_dir_uploads_session$$=require("compression");$app$$.use($compress_cookieParser_morgan_multer_root_dir_uploads_session$$());$compress_cookieParser_morgan_multer_root_dir_uploads_session$$=$configs$$.paths.uploads||__dirname+"/uploads";const $limitFileSize$$=$configs$$.limitFileSize||1048576;$app$$.use(function($req$jscomp$2_size$$,$res$$,$next$$){if(($req$jscomp$2_size$$=$req$jscomp$2_size$$.headers["content-lenght"])&&$req$jscomp$2_size$$>$limitFileSize$$)return $res$$.status(400).send({error:"File too large"});
7
+ $next$$()});$compress_cookieParser_morgan_multer_root_dir_uploads_session$$=require("multer")({dest:$compress_cookieParser_morgan_multer_root_dir_uploads_session$$,limits:{files:1,fileSize:$limitFileSize$$}});$app$$.use($compress_cookieParser_morgan_multer_root_dir_uploads_session$$);$app$$.use(cors({credentials:!0,exposedHeaders:["set-cookie","uid"],origin:($origin$$,$callback$$)=>{$callback$$(null,!0)}}));$configs$$.paths||($configs$$.paths={});!0!==$options$$.lite&&($app$$.use("/",express.static($configs$$.paths.public||
8
+ __dirname+"/public")),$app$$.use("/admin",express.static($configs$$.paths.admin||__dirname+"/admin")),$app$$.use("/templates",express.static($configs$$.paths.templates||__dirname+"/templates")),$app$$.use("/images",express.static($configs$$.paths.images||__dirname+"/images")));$app$$.use(bodyParser.json({limit:$configs$$.limitRequestSize||"1mb"}));$app$$.use(bodyParser.urlencoded({limit:$configs$$.limitRequestSize||"1mb",extended:!0}));$app$$.use(passport.initialize());$compress_cookieParser_morgan_multer_root_dir_uploads_session$$=
9
+ require("morgan");var $accessLogStream_rfs$$=require("rotating-file-stream");const $logDirectory$$=$configs$$.paths.log||__dirname+"/log";fs.existsSync($logDirectory$$)||fs.mkdirSync($logDirectory$$);$accessLogStream_rfs$$=$accessLogStream_rfs$$("access.log",{interval:"1d",path:$logDirectory$$});$app$$.use($compress_cookieParser_morgan_multer_root_dir_uploads_session$$("combined",{stream:$accessLogStream_rfs$$,skip:function($req$$,$res$$){return 400>$res$$.statusCode}}));$app$$.use(function($err$$,
10
+ $req$$,$res$$,$next$$){console.error($err$$.stack);$res$$.status(500).send("Server Error!")});global.mongoose.connect($configs$$.database.url,{useNewUrlParser:!0}).then(async()=>{console.log("Connected to Database");const $redis$$=require("redis");global.clientRedis=$redis$$.createClient();global.clientRedis.on("error",$err$$=>console.error("Redis Client Error",$err$$));global.clientRedis.on("end",()=>{console.error("Redis connection closed.")});global.clientRedis.on("connect",function(){console.log("redis connected");
11
+ 0!=$options$$.createRedisCache&&require("./libs/redis-cache").set();$options$$.start_abci_handler&&global.getModel("assabcihandler").start();!0!==$options$$.lite?(require("./controllers/taskQueue")(),require("./route")($app$$,()=>{if(!1!==$options$$.createServer){var $StaticPool_StaticPool$$=require("sticky-session");if($configs$$.use_ssl){var $server_sslConfig$$=require("./sslConfig");$server_sslConfig$$=https.createServer($server_sslConfig$$($options$$.sslDir),$app$$)}else $server_sslConfig$$=http.createServer($app$$);
12
+ $server_sslConfig$$.timeout=6E5;!1!==$options$$.useSocket?User.initSocket($server_sslConfig$$):User.initClientSockets();if(!1!==$options$$.cluster){if(!$StaticPool_StaticPool$$.listen($server_sslConfig$$,global.port))$server_sslConfig$$.once("listening",function(){console.log("server started on",global.port)});$StaticPool_StaticPool$$=require("cluster");$StaticPool_StaticPool$$.on("exit",function($worker$$,$code$$,$signal$$){console.error("worker "+$worker$$.process.pid+" died",$code$$,$signal$$)});
13
+ $StaticPool_StaticPool$$.on("online",function($worker$$){console.info("worker "+$worker$$.process.pid+" is online")})}else $server_sslConfig$$.listen(global.port,()=>{console.log("server start at "+global.port+" port")})}$options$$.start_import_data_pool&&($StaticPool_StaticPool$$=require("./libs/WorkerStaticPool"),global.importDataMainPool=new $StaticPool_StaticPool$$(__dirname+"/workers/inputWorker.js",$options$$.max_queue_imports||0),global.importDataMainPool.exec({load:!0,configs:JSON.stringify($configs$$)},
14
+ ()=>{console.log("load import data pool")}));$options$$.start_report_pool&&($StaticPool_StaticPool$$=require("./libs/WorkerStaticPool"),global.reportMainPool=new $StaticPool_StaticPool$$(__dirname+"/workers/reportWorker.js",$options$$.max_queue_reports||0),global.reportMainPool.exec({load:!0,configs:JSON.stringify($configs$$)},()=>{console.log("load report pool")}));$callbackServer$$&&$callbackServer$$()})):require("./route")($app$$,()=>{$callbackServer$$&&$callbackServer$$()},!0)})}).catch($err$$=>
15
+ {console.log("Not Connected to Database ERROR! ",$err$$)});return $app$$};process.on("SIGINT",async()=>{global.sharedRedisConnection&&await global.sharedRedisConnection.quit();process.exit(0)});process.on("uncaughtException",function($err$jscomp$3_error$$){console.error((new Date).toUTCString()+" uncaughtException:",$err$jscomp$3_error$$.message);console.error($err$jscomp$3_error$$.stack);$err$jscomp$3_error$$=`
16
+ Error: ${$err$jscomp$3_error$$.message}
17
+ Stack: ${$err$jscomp$3_error$$.stack}
18
+ `;try{const $logDirectory$$=__dirname+"/log";fs.existsSync($logDirectory$$)||fs.mkdirSync($logDirectory$$);fs.writeFile(`${$logDirectory$$}/error-${(new Date).getTime()}.txt`,$err$jscomp$3_error$$,()=>{console.log("wrote log error")})}catch($e$$){console.log($e$$)}process.exit(1)});module.exports=mainServer;
package/server/cluster.js CHANGED
@@ -1,303 +1,22 @@
1
- //require('events').EventEmitter.prototype._maxListeners = 10000;
2
- require('events').EventEmitter.defaultMaxListeners = 10000000;
3
-
4
- const express = require('express');
5
- const bodyParser = require('body-parser');
6
-
7
- const passport = require('passport');
8
- const https = require("https");
9
- const http = require('http');
10
- const fs = require("fs");
11
- const cors=require('cors');
12
- const crypto = require("crypto");
13
- // eslint-disable-next-line no-unused-vars
14
- const _global = require('./global');
15
- const defaultConfigs = require('./defaultConfigs');
16
- const sslConfig = require("./sslConfig");
17
- const clusterServer = function(app,sslDir,_configs={},_port = 9999,options ={start_import_data_pool:false,start_report_pool:true,useAgenda:true,createRedisCache:true}){
18
- const configs = global.configs = {...defaultConfigs,..._configs,cluster:options.cluster!=false};
19
-
20
- if(!configs.admins) configs.admins = configs.adminUsers.map(u=>u.email);
21
- if(!configs.supportUsers) configs.supportUsers =[...configs.admins];
22
-
23
- if(!configs.public_token) configs.public_token = "flex.public.token";
24
- global.port = _port;
25
- //set timezone
26
- const moment = require('moment-timezone');
27
- moment.tz.setDefault(configs.timezone || 'Asia/Ho_Chi_Minh');
28
- //app
29
- if(!app) app = express();
30
- app.set('trust proxy', 1);
31
- //check too busy
32
- const toobusy = require('toobusy-js');
33
- if(configs.maxLag) toobusy.maxLag(configs.maxLag);
34
- toobusy.onLag(function(currentLag) {
35
- console.log("Event loop lag detected! Latency: " + currentLag + "ms. maxlag",configs.maxLag);
36
- });
37
- app.use(function(req, res, next) {
38
- if (toobusy()) {
39
- console.error("Server is busy right now. This request has been cancel:",req.originalUrl);
40
- res.status(503).send({error:"Server is busy right now, sorry."});
41
- } else {
42
- next();
43
- }
44
- });
45
- //
46
- const session = require('express-session');
47
- app.use(session({secret: 'QV098PVT123456HLBN',resave: false,saveUninitialized: true,cookie: { secure: false }}));
48
- //cookie uid
49
- const cookieParser = require('cookie-parser')
50
- app.use(cookieParser())
51
- app.use(function (req, res, next) {
52
- let uid = req.cookies.uid;
53
- if(!uid){
54
- uid = req.headers["uid"];
55
- }
56
- if(!uid){
57
- uid = "uid:" + crypto.randomBytes(20).toString('hex')
58
- res.cookie("uid",uid,{
59
- expires: new Date(Date.now() + 365 * 24 * 3600000), // cookie will be removed after 24 hours,
60
- sameSite: 'none',
61
- secure:true
62
- });
63
- }
64
- res.set('uid', uid);
65
- //console.log("uid",uid,req.originalUrl,req.method);
66
- req.cookies.uid = uid;
67
- next();
68
- })
69
-
70
- const compress = require('compression');
71
- app.use(compress());
72
- //upload file
73
- const root_dir_uploads = configs.paths.uploads || (__dirname + '/uploads');
74
- const limitFileSize = configs.limitFileSize || 1024 * 1024 * 1;
75
- app.use(function (req, res, next) {
76
- const size = req.headers['content-lenght'];
77
- if(size && size> limitFileSize){
78
- return res.status(400).send({error:"File too large"});
79
- }
80
- next()
81
- })
82
- const multer = require('multer')({
83
- dest: root_dir_uploads,
84
- limits: {files:1,fileSize: limitFileSize }
85
- });
86
- app.use(multer);
87
- //allow cross domain
88
- const corsOptions = {
89
- credentials: true,
90
- exposedHeaders: ["set-cookie","uid"],
91
- origin: (origin, callback) => {
92
- callback(null, true);
93
- }
94
- }
95
- app.use(cors(corsOptions));
96
-
97
- if(!configs.paths) configs.paths={}
98
- app.use('/', express.static(configs.paths.public || __dirname + '/public'));
99
- app.use('/admin', express.static(configs.paths.admin || (__dirname + '/admin')));
100
- app.use('/templates', express.static(configs.paths.templates|| (__dirname + '/templates')));
101
- app.use('/images', express.static(configs.paths.images || (__dirname + '/images')));
102
-
103
- app.use(bodyParser.json({limit: (configs.limitRequestSize||'1mb')}));
104
- app.use(bodyParser.urlencoded({limit: (configs.limitRequestSize||'1mb'),extended: true}));
105
-
106
- app.use(passport.initialize());
107
- //log access
108
- const morgan = require('morgan');
109
- const rfs = require('rotating-file-stream');
110
-
111
- const logDirectory = configs.paths.log || (__dirname + '/log');
112
- fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
113
- const accessLogStream = rfs('access-cluster.log', {
114
- interval: '1d', // rotate daily
115
- path: logDirectory
116
- })
117
- app.use(morgan('combined', {
118
- stream: accessLogStream,
119
- skip: function (req, res) { return res.statusCode < 400 }
120
- }))
121
- //handle error default
122
- // eslint-disable-next-line no-unused-vars
123
- app.use(function (err, req, res, next) {
124
- console.error(err.stack)
125
- res.status(500).send('Server error!')
126
- })
127
- //connect to mongodb
128
- global.mongoose.connect(configs.database.url,{ useNewUrlParser: true }).then(async (clientMongo) => {
129
- console.log("Connected to Database");
130
- global.clientMongo = clientMongo;
131
- //connect to redis
132
- const redis = require('redis');
133
- global.clientRedis = redis.createClient();
134
- global.clientRedis.on("error", (err) => console.error("Redis Client Error", err));
135
- global.clientRedis.on("end", () => {
136
- console.error("Redis connection closed.");
137
- });
138
- global.clientRedis.on("connect",async function(){
139
- console.log("redis connected");
140
- if(options.createRedisCache!=false){
141
- const redisCache = require('./libs/redis-cache');
142
- redisCache.set();
143
- }
144
- //start schedule
145
- const new_schedule = global.getModel('schedule');
146
- new_schedule.start();
147
- //start abci. xu ly cac su kien lien quan den dau tu
148
- if(options.start_abci_handler){
149
- const assabcihandler = global.getModel("assabcihandler");
150
- assabcihandler.start();
151
- }
152
- const User = global.getModel('user');
153
- let init_system_data = configs.initSysData;
154
- if(!init_system_data){
155
- let u = await User.findOne({});
156
- if(!u) init_system_data = true;
157
- }
158
- //create ADMIN user
159
- for(let i =0;i<configs.adminUsers.length;i++){
160
- let adminUser = configs.adminUsers[i];
161
- let u = await User.findOne({email: adminUser.email});
162
- if (!u) {
163
- adminUser.local = {
164
- name: adminUser.name,
165
- email: adminUser.email,
166
- active: true
167
- };
168
- u = new User(adminUser);
169
- u.local.password = u.generateHash(adminUser.email + adminUser.defaultPassword);
170
- u.save(function(error, user) {
171
- if (error)
172
- return console.error(error);
173
- if (user)
174
- console.log('da tao thanh cong user ' + user.email);
175
- }
176
- )
177
- }
178
- }
179
- //create system data
180
- const async = require("async");
181
- function initSysData(){
182
- console.log("creating system data...");
183
- const files = fs.readdirSync(__dirname + '/data/sys');
184
- async.mapSeries(files, function(file, callback) {
185
- setImmediate(()=>{
186
- if (file.substr(-3) == '.js') {
187
- const data = JSON.parse(JSON.stringify(require('./data/sys/' + file).data));
188
- const model = global.getModel('' + file);
189
- console.log("creating system data...",file);
190
- model.deleteMany({},(e)=>{
191
- console.error(e);
192
- async.mapSeries(data, function(r, callback) {
193
- delete r._id;
194
- delete r.__v;
195
- delete r.collection_name;
196
- delete r.pkey;
197
- model.create(r, function(error) {
198
- if (error)
199
- return callback(error);
200
- callback();
201
- });
202
- }, function(error, rs) {
203
- callback(error, rs);
204
- });
205
- })
206
- } else {
207
- callback();
208
- }
209
- })
210
- }, function(error) {
211
- if (error) return console.log(error);
212
- console.log("created system data");
213
- });
214
- }
215
- if(init_system_data){
216
- initSysData();
217
- }
218
- //routes
219
- const route = require('./route');
220
- route(app);
221
- //create server
222
- let server;
223
- if(configs.use_ssl){
224
- server = https.createServer(sslConfig(sslDir), app);
225
- }else{
226
- server = http.createServer(app);
227
- }
228
- server.timeout = 10*60*1000;
229
- //init socket
230
- User.initSocket(server);
231
- if(options.cluster!==false){
232
- //fork workers
233
- const sticky = require('sticky-session');
234
- if (!sticky.listen(server, global.port)) {
235
- // Master code
236
- server.once('listening', function() {
237
- console.log('server cluster started on',global.port);
238
- });
239
- } else {
240
- // Worker code
241
- }
242
- const cluster = require('cluster');
243
- cluster.on('exit', function(worker, code, signal) {
244
- console.error('worker ' + worker.process.pid + ' died', code, signal);
245
- });
246
- cluster.on('online', function(worker) {
247
- console.info('worker ' + worker.process.pid + ' is online');
248
- //
249
- global.clientRedis.set("lastworker",JSON.stringify({pid:worker.process.pid}));
250
- });
251
- }else{
252
- server.listen(global.port, () => {
253
- //global.clientRedis.set("lastworker",JSON.stringify({pid:process.pid}));
254
- console.log('server start at ' + global.port + ' port');
255
- });
256
- }
257
- //
258
- if(options.start_import_data_pool){
259
- const StaticPool = require("./libs/WorkerStaticPool");
260
- global.importDataMainPool = new StaticPool(__dirname + '/workers/inputWorker.js',options.max_queue_imports||0);
261
- global.importDataMainPool.exec({
262
- load:true,
263
- configs: JSON.parse(JSON.stringify(configs)),
264
- },()=>{
265
- console.log("load import data pool");
266
- })
267
- }
268
- if(options.start_report_pool){
269
- const StaticPool = require("./libs/WorkerStaticPool");
270
- global.reportMainPool = new StaticPool(__dirname + '/workers/reportWorker.js',options.max_queue_reports||0);
271
- global.reportMainPool.exec({
272
- load:true,
273
- configs: JSON.parse(JSON.stringify(configs)),
274
- },()=>{
275
- console.log("load report pool");
276
- })
277
- }
278
- });
279
- }).catch((err) => {
280
- console.error("Not Connected to Database ERROR!", err);
281
- });
282
- }
283
-
284
- process.on('uncaughtException', function (err) {
285
- console.error((new Date).toUTCString() + ' uncaughtException:', err.message);
286
- console.error(err.stack);
287
- let error = `
288
- Error: ${err.message}
289
- Stack: ${err.stack}
290
- `
291
- try{
292
- const logDirectory = (__dirname + '/log');
293
- fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
294
- fs.writeFile(`${logDirectory}/error-${new Date().getTime()}.txt`,error,()=>{
295
- console.log("wrote log error");
296
- });
297
- }catch(e){
298
- console.log(e);
299
- }
300
- process.exit(1)
301
- })
302
-
303
- module.exports =clusterServer;
1
+ 'use strict';require("events").EventEmitter.defaultMaxListeners=1E7;
2
+ const express=require("express"),bodyParser=require("body-parser"),passport=require("passport"),https=require("https"),http=require("http"),fs=require("fs"),cors=require("cors"),crypto=require("crypto"),_global=require("./global"),defaultConfigs=require("./defaultConfigs"),sslConfig=require("./sslConfig"),clusterServer=function($app$$,$sslDir$$,$_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$={},$_port_accessLogStream_rfs$$=9999,$options$$={start_import_data_pool:!1,start_report_pool:!0,
3
+ useAgenda:!0,createRedisCache:!0}){const $configs$$=global.configs={...defaultConfigs,...$_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$,cluster:0!=$options$$.cluster};$configs$$.admins||($configs$$.admins=$configs$$.adminUsers.map($u$$=>$u$$.email));$configs$$.supportUsers||($configs$$.supportUsers=[...$configs$$.admins]);$configs$$.public_token||($configs$$.public_token="flex.public.token");global.port=$_port_accessLogStream_rfs$$;require("moment-timezone").tz.setDefault($configs$$.timezone||
4
+ "Asia/Ho_Chi_Minh");$app$$||($app$$=express());$app$$.set("trust proxy",1);const $toobusy$$=require("toobusy-js");$configs$$.maxLag&&$toobusy$$.maxLag($configs$$.maxLag);$toobusy$$.onLag(function($currentLag$$){console.log("Event loop lag detected! Latency: "+$currentLag$$+"ms. maxlag",$configs$$.maxLag)});$app$$.use(function($req$$,$res$$,$next$$){$toobusy$$()?(console.error("Server is busy right now. This request has been cancel:",$req$$.originalUrl),$res$$.status(503).send({error:"Server is busy right now, sorry."})):
5
+ $next$$()});$_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$=require("express-session");$app$$.use($_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$({secret:"QV098PVT123456HLBN",resave:!1,saveUninitialized:!0,cookie:{secure:!1}}));$_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$=require("cookie-parser");$app$$.use($_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$());$app$$.use(function($req$$,$res$$,$next$$){let $uid$$=
6
+ $req$$.cookies.uid;$uid$$||($uid$$=$req$$.headers.uid);$uid$$||($uid$$="uid:"+crypto.randomBytes(20).toString("hex"),$res$$.cookie("uid",$uid$$,{expires:new Date(Date.now()+31536E6),sameSite:"none",secure:!0}));$res$$.set("uid",$uid$$);$req$$.cookies.uid=$uid$$;$next$$()});$_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$=require("compression");$app$$.use($_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$());$_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$=
7
+ $configs$$.paths.uploads||__dirname+"/uploads";const $limitFileSize$$=$configs$$.limitFileSize||1048576;$app$$.use(function($req$jscomp$2_size$$,$res$$,$next$$){if(($req$jscomp$2_size$$=$req$jscomp$2_size$$.headers["content-lenght"])&&$req$jscomp$2_size$$>$limitFileSize$$)return $res$$.status(400).send({error:"File too large"});$next$$()});$_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$=require("multer")({dest:$_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$,
8
+ limits:{files:1,fileSize:$limitFileSize$$}});$app$$.use($_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$);$app$$.use(cors({credentials:!0,exposedHeaders:["set-cookie","uid"],origin:($origin$$,$callback$$)=>{$callback$$(null,!0)}}));$configs$$.paths||($configs$$.paths={});$app$$.use("/",express.static($configs$$.paths.public||__dirname+"/public"));$app$$.use("/admin",express.static($configs$$.paths.admin||__dirname+"/admin"));$app$$.use("/templates",express.static($configs$$.paths.templates||
9
+ __dirname+"/templates"));$app$$.use("/images",express.static($configs$$.paths.images||__dirname+"/images"));$app$$.use(bodyParser.json({limit:$configs$$.limitRequestSize||"1mb"}));$app$$.use(bodyParser.urlencoded({limit:$configs$$.limitRequestSize||"1mb",extended:!0}));$app$$.use(passport.initialize());$_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$=require("morgan");$_port_accessLogStream_rfs$$=require("rotating-file-stream");const $logDirectory$$=$configs$$.paths.log||__dirname+
10
+ "/log";fs.existsSync($logDirectory$$)||fs.mkdirSync($logDirectory$$);$_port_accessLogStream_rfs$$=$_port_accessLogStream_rfs$$("access-cluster.log",{interval:"1d",path:$logDirectory$$});$app$$.use($_configs_compress_cookieParser_morgan_multer_root_dir_uploads_session$$("combined",{stream:$_port_accessLogStream_rfs$$,skip:function($req$$,$res$$){return 400>$res$$.statusCode}}));$app$$.use(function($err$$,$req$$,$res$$,$next$$){console.error($err$$.stack);$res$$.status(500).send("Server error!")});
11
+ global.mongoose.connect($configs$$.database.url,{useNewUrlParser:!0}).then(async $clientMongo_redis$$=>{console.log("Connected to Database");global.clientMongo=$clientMongo_redis$$;$clientMongo_redis$$=require("redis");global.clientRedis=$clientMongo_redis$$.createClient();global.clientRedis.on("error",$err$$=>console.error("Redis Client Error",$err$$));global.clientRedis.on("end",()=>{console.error("Redis connection closed.")});global.clientRedis.on("connect",async function(){function $initSysData$$(){console.log("creating system data...");
12
+ const $files$$=fs.readdirSync(__dirname+"/data/sys");$async$$.mapSeries($files$$,function($file$$,$callback$jscomp$0$$){setImmediate(()=>{if(".js"==$file$$.substr(-3)){const $data$$=JSON.parse(JSON.stringify(require("./data/sys/"+$file$$).data)),$model$$=global.getModel(""+$file$$);console.log("creating system data...",$file$$);$model$$.deleteMany({},$e$$=>{console.error($e$$);$async$$.mapSeries($data$$,function($r$$,$callback$$){delete $r$$._id;delete $r$$.__v;delete $r$$.collection_name;delete $r$$.pkey;
13
+ $model$$.create($r$$,function($error$$){if($error$$)return $callback$$($error$$);$callback$$()})},function($error$$,$rs$$){$callback$jscomp$0$$($error$$,$rs$$)})})}else $callback$jscomp$0$$()})},function($error$$){if($error$$)return console.log($error$$);console.log("created system data")})}console.log("redis connected");0!=$options$$.createRedisCache&&require("./libs/redis-cache").set();global.getModel("schedule").start();$options$$.start_abci_handler&&global.getModel("assabcihandler").start();var $StaticPool_StaticPool$$=
14
+ global.getModel("user"),$init_system_data_server$$=$configs$$.initSysData;$init_system_data_server$$||await $StaticPool_StaticPool$$.findOne({})||($init_system_data_server$$=!0);for(let $i$$=0;$i$$<$configs$$.adminUsers.length;$i$$++){let $adminUser$$=$configs$$.adminUsers[$i$$],$u$$=await $StaticPool_StaticPool$$.findOne({email:$adminUser$$.email});$u$$||($adminUser$$.local={name:$adminUser$$.name,email:$adminUser$$.email,active:!0},$u$$=new $StaticPool_StaticPool$$($adminUser$$),$u$$.local.password=
15
+ $u$$.generateHash($adminUser$$.email+$adminUser$$.defaultPassword),$u$$.save(function($error$$,$user$$){if($error$$)return console.error($error$$);$user$$&&console.log("da tao thanh cong user "+$user$$.email)}))}const $async$$=require("async");$init_system_data_server$$&&$initSysData$$();require("./controllers/taskQueue")();require("./route")($app$$);$init_system_data_server$$=$configs$$.use_ssl?https.createServer(sslConfig($sslDir$$),$app$$):http.createServer($app$$);$init_system_data_server$$.timeout=
16
+ 6E5;$StaticPool_StaticPool$$.initSocket($init_system_data_server$$);if(!1!==$options$$.cluster){if(!require("sticky-session").listen($init_system_data_server$$,global.port))$init_system_data_server$$.once("listening",function(){console.log("server cluster started on",global.port)});$StaticPool_StaticPool$$=require("cluster");$StaticPool_StaticPool$$.on("exit",function($worker$$,$code$$,$signal$$){console.error("worker "+$worker$$.process.pid+" died",$code$$,$signal$$)});$StaticPool_StaticPool$$.on("online",
17
+ function($worker$$){console.info("worker "+$worker$$.process.pid+" is online");global.clientRedis.set("lastworker",JSON.stringify({pid:$worker$$.process.pid}))})}else $init_system_data_server$$.listen(global.port,()=>{console.log("server start at "+global.port+" port")});$options$$.start_import_data_pool&&($StaticPool_StaticPool$$=require("./libs/WorkerStaticPool"),global.importDataMainPool=new $StaticPool_StaticPool$$(__dirname+"/workers/inputWorker.js",$options$$.max_queue_imports||0),global.importDataMainPool.exec({load:!0,
18
+ configs:JSON.parse(JSON.stringify($configs$$))},()=>{console.log("load import data pool")}));$options$$.start_report_pool&&($StaticPool_StaticPool$$=require("./libs/WorkerStaticPool"),global.reportMainPool=new $StaticPool_StaticPool$$(__dirname+"/workers/reportWorker.js",$options$$.max_queue_reports||0),global.reportMainPool.exec({load:!0,configs:JSON.parse(JSON.stringify($configs$$))},()=>{console.log("load report pool")}))})}).catch($err$$=>{console.error("Not Connected to Database ERROR!",$err$$)})};
19
+ process.on("SIGINT",async()=>{global.sharedRedisConnection&&await global.sharedRedisConnection.quit();process.exit(0)});process.on("uncaughtException",function($err$jscomp$3_error$$){console.error((new Date).toUTCString()+" uncaughtException:",$err$jscomp$3_error$$.message);console.error($err$jscomp$3_error$$.stack);$err$jscomp$3_error$$=`
20
+ Error: ${$err$jscomp$3_error$$.message}
21
+ Stack: ${$err$jscomp$3_error$$.stack}
22
+ `;try{const $logDirectory$$=__dirname+"/log";fs.existsSync($logDirectory$$)||fs.mkdirSync($logDirectory$$);fs.writeFile(`${$logDirectory$$}/error-${(new Date).getTime()}.txt`,$err$jscomp$3_error$$,()=>{console.log("wrote log error")})}catch($e$$){console.log($e$$)}process.exit(1)});module.exports=clusterServer;