flexbiz-server 12.7.7 → 12.7.8
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.
- package/package.json +1 -1
- package/server/app.js +19 -23
- package/server/global.js +1 -2
- package/server/models/assabcihandler.js +1 -1
- package/server/route.js +1 -1
package/package.json
CHANGED
package/server/app.js
CHANGED
|
@@ -1,27 +1,23 @@
|
|
|
1
1
|
require("events").EventEmitter.defaultMaxListeners=1E7;const os=require("os"),express=require("express"),bodyParser=require("body-parser"),crypto=require("crypto"),passport=require("passport"),https=require("https"),http=require("http"),fs=require("fs"),cors=require("cors");require("./global");
|
|
2
|
-
const defaultConfigs=require("./defaultConfigs"),mainServer=function($app$$,$options$$={
|
|
3
|
-
"flex.public.token");var $
|
|
4
|
-
|
|
5
|
-
require("
|
|
6
|
-
|
|
7
|
-
$req$jscomp$
|
|
8
|
-
$app$$.use(cors({credentials:!0,exposedHeaders:["set-cookie","uid"],origin:($origin$$,$callback$$)=>{$callback$$(null,!0)}}));$configs$$.paths||($configs$$.paths={});$options$$.lite!==!0&&($app$$.use("/",express.static($configs$$.paths.public||__dirname+
|
|
9
|
-
"/
|
|
10
|
-
$
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
global.
|
|
19
|
-
|
|
20
|
-
$
|
|
21
|
-
configs:JSON.stringify($configs$$)},()=>{Logger.info("[app] Import pool ready")}));$cpus_report_cpus_server_sslConfig$$&&($StaticPool$$=require("./libs/WorkerStaticPool"),global.reportMainPool=new $StaticPool$$(__dirname+"/workers/reportWorker.js",$options$$.max_queue_reports||0,$cpus_report_cpus_server_sslConfig$$,$timeout_report$$,2,"report pool"),global.reportMainPool.exec({load:!0,configs:JSON.stringify($configs$$)},()=>{Logger.info("[app] Report pool ready")}));$callbackServer$$&&$callbackServer$$()})}else require("./route")($app$$,
|
|
22
|
-
()=>{$callbackServer$$&&$callbackServer$$()},!0)})}).catch($err$$=>{Logger.info("[app] Not Connected to Database ERROR! ",$err$$);process.exit(1)});return $app$$},gracefulShutdown=async $signal$$=>{Logger.warn(`[app] Nh\u1eadn t\u00edn hi\u1ec7u ${$signal$$}. \u0110ang ti\u1ebfn h\u00e0nh t\u1eaft h\u1ec7 th\u1ed1ng an to\u00e0n...`);global.accessLogBuffer&&typeof global.accessLogBuffer.flush==="function"&&(Logger.info("[app] \u0110ang flush n\u1ed1t log buffer..."),await global.accessLogBuffer.flush());
|
|
23
|
-
if(global.mongoose&&global.mongoose.connection.readyState===1)try{await global.mongoose.disconnect(),Logger.info("[app] \u0110\u00e3 ng\u1eaft k\u1ebft n\u1ed1i MongoDB an to\u00e0n.")}catch($dbErr$$){Logger.error("[app] L\u1ed7i khi ng\u1eaft k\u1ebft n\u1ed1i MongoDB:",$dbErr$$.message)}if(global.sharedRedisConnection)try{await global.sharedRedisConnection.quit(),Logger.info("[app] \u0110\u00e3 ng\u1eaft k\u1ebft n\u1ed1i Redis an to\u00e0n.")}catch($redisErr$$){Logger.error("[app] L\u1ed7i khi ng\u1eaft k\u1ebft n\u1ed1i Redis:",
|
|
24
|
-
$redisErr$$.message)}Logger.info("[app] H\u1ec7 th\u1ed1ng \u0111\u00e3 t\u1eaft ho\u00e0n to\u00e0n. Goodbye!");process.exit(0)};process.on("SIGINT",()=>gracefulShutdown("SIGINT"));process.on("SIGTERM",()=>gracefulShutdown("SIGTERM"));process.on("uncaughtException",function($err$jscomp$3_error$$){Logger.error((new Date).toUTCString()+" uncaughtException:",$err$jscomp$3_error$$.message);Logger.error($err$jscomp$3_error$$.stack);$err$jscomp$3_error$$=`
|
|
2
|
+
const defaultConfigs=require("./defaultConfigs"),mainServer=function($app$$,$options$$={port:443,useSocket:!0},$callbackServer$$=null){const $configs$$=global.configs={...defaultConfigs,...$options$$.configs,lite:$options$$.lite};$configs$$.database.url=process.env.MONGO_URI||$configs$$.database.url;$configs$$.admins||($configs$$.admins=$configs$$.adminUsers.map($u$$=>$u$$.email));$configs$$.supportUsers||($configs$$.supportUsers=[...$configs$$.admins]);$configs$$.public_token||($configs$$.public_token=
|
|
3
|
+
"flex.public.token");var $_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$=$options$$.port||$configs$$.port||$configs$$.PORT||443;$configs$$.port=$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$;global.port=$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$;const $User$$=global.getModel("user");require("moment-timezone").tz.setDefault($configs$$.timezone||"Asia/Ho_Chi_Minh");$app$$||=express();
|
|
4
|
+
$app$$.set("trust proxy",1);const $maxLagMs$$=$configs$$.maxLag||70;let $currentLagMs$$=0;(function $scheduleLagCheck$$(){const $expectedFireAt$$=Date.now()+500;setTimeout(()=>{$currentLagMs$$=Math.max(0,Date.now()-$expectedFireAt$$);$scheduleLagCheck$$()},500).unref()})();$app$$.use(function($req$$,$res$$,$next$$){$currentLagMs$$>$maxLagMs$$?(Logger.error("Server is busy right now. This request has been cancel:",$req$$.originalUrl,"lag:",$currentLagMs$$+"ms"),$res$$.status(503).send({error:"Server is busy right now, sorry."})):
|
|
5
|
+
$next$$()});$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$=require("express-session");$app$$.use($_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$({secret:"QV098PVT123456HLBN",resave:!1,saveUninitialized:!0,cookie:{secure:!1}}));$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$=require("cookie-parser");$app$$.use($_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$());
|
|
6
|
+
$app$$.use(function($req$$,$res$$,$next$$){let $uid$$=$req$$.cookies.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$$()});$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$=require("compression");$app$$.use($_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$());
|
|
7
|
+
$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$=$configs$$.paths.uploads||__dirname+"/uploads";const $limitFileSize$$=$configs$$.limitFileSize||5242880;Logger.warn("[app] [limitFileSize]",$limitFileSize$$);$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$$()});$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$=
|
|
8
|
+
require("multer")({dest:$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$,limits:{files:1,fileSize:$limitFileSize$$}});$app$$.use($_port_compress_cookieParser_limitRequestSize_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={});$options$$.lite!==!0&&($app$$.use("/",express.static($configs$$.paths.public||__dirname+
|
|
9
|
+
"/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")));$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$=$configs$$.limitRequestSize||"1mb";Logger.warn("[app] [limitRequestSize]",$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$);
|
|
10
|
+
$app$$.use(bodyParser.json({limit:$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$}));$app$$.use(bodyParser.urlencoded({limit:$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$,extended:!0}));$app$$.use(passport.initialize());$_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$=require("morgan");var $accessLogStream_rfs$$=require("rotating-file-stream");const $logDirectory$$=$configs$$.paths.log||
|
|
11
|
+
__dirname+"/log";fs.existsSync($logDirectory$$)||fs.mkdirSync($logDirectory$$);$accessLogStream_rfs$$=$accessLogStream_rfs$$("access.log",{interval:"1d",path:$logDirectory$$});$app$$.use($_port_compress_cookieParser_limitRequestSize_morgan_multer_root_dir_uploads_session$$("combined",{stream:$accessLogStream_rfs$$,skip:function($req$$,$res$$){return $res$$.statusCode<400}}));$app$$.use(function($err$$,$req$$,$res$$,$next$$){Logger.error($err$$.stack);$res$$.status(500).send("Server Error!")});Logger.info("[app] connect to mongodb",
|
|
12
|
+
$configs$$.database.url);$configs$$.database.url||(Logger.error("[app] thi\u1ebfu \u0111\u01b0\u1eddng d\u1eabn k\u1ebft n\u1ed1i v\u1edbi database trong file config"),process.exit(1));typeof global.mongoose.set==="function"&&global.mongoose.set("strictQuery",!0);global.mongoose.connect($configs$$.database.url).then(async()=>{if(!$options$$.lite){var $redis_transactionLifetimeLimitSeconds$$=$configs$$.transactionLifetimeLimitSeconds||600,$result_retryStrategyRedis$$=await mongoose.connection.getClient().db().admin().command({setParameter:1,
|
|
13
|
+
transactionLifetimeLimitSeconds:$redis_transactionLifetimeLimitSeconds$$});Logger.warn("[app] T\u0103ng th\u1eddi gian ho\u1ea1t \u0111\u1ed9ng c\u1ee7a m\u1ed9t transaction l\u00ean",$redis_transactionLifetimeLimitSeconds$$,$result_retryStrategyRedis$$)}Logger.info("[app] Connected to Database");$redis_transactionLifetimeLimitSeconds$$=require("redis");({retryStrategyRedis:$result_retryStrategyRedis$$}=require("./libs/utils"));global.clientRedis=$redis_transactionLifetimeLimitSeconds$$.createClient({host:"127.0.0.1",
|
|
14
|
+
port:6379,retry_strategy:$result_retryStrategyRedis$$});global.clientRedis.on("error",$err$$=>{Logger.error("Redis Client Error",$err$$);process.exit(1)});global.clientRedis.on("end",()=>{Logger.error("[app] Redis connection closed.")});global.clientRedis.on("connect",function(){Logger.info("[app] redis connected");$User$$.initClientSockets();if($options$$.lite!==!0){$options$$.createRedisCache&&require("./libs/redis-cache").set();global.getModel("schedule").start();const {recoverBackgroundTasks:$recoverBackgroundTasks$$}=
|
|
15
|
+
require("./libs/optimizeBookkeeping");$recoverBackgroundTasks$$().catch(console.error);require("./route")($app$$,()=>{if($options$$.createServer!==!1){if($configs$$.use_ssl&&$options$$.sslDir){var $StaticPool$$=require("./sslConfig");$StaticPool$$=https.createServer($StaticPool$$($options$$.sslDir),$app$$)}else $StaticPool$$=http.createServer($app$$);$StaticPool$$.timeout=6E5;$options$$.useSocket!==!1&&$User$$.initSocket($StaticPool$$);$StaticPool$$.listen(global.port,()=>{Logger.info("[app] server start at "+
|
|
16
|
+
global.port+" port")})}var $cpus_report_cpus$$=os.cpus().length;$StaticPool$$=$options$$.import_cpus||($options$$.start_import_data_pool?$options$$.start_report_pool||$options$$.start_input_data_pool?1:Math.round($cpus_report_cpus$$/2):0);var $StaticPool$jscomp$0$$=$options$$.input_cpus||($options$$.start_input_data_pool?Math.max(Math.round($cpus_report_cpus$$/2),2):0);$cpus_report_cpus$$=$options$$.report_cpus||($options$$.start_import_data_pool?Math.max(Math.min($cpus_report_cpus$$-$StaticPool$jscomp$0$$-
|
|
17
|
+
$StaticPool$$,Math.round($cpus_report_cpus$$/2))-1,2):0);const $timeout_input$$=$options$$.timeout_input||$options$$.timeout||3E5,$timeout_import$$=$options$$.timeout_import||$options$$.timeout||36E5,$timeout_report$$=$options$$.timeout_report||$options$$.timeout||3E5;if($StaticPool$jscomp$0$$){const $StaticPool$$=require("./libs/WorkerStaticPool");global.inputMainPool=new $StaticPool$$(__dirname+"/workers/inputWorker.js",$options$$.max_queue_imports||0,$StaticPool$jscomp$0$$,$timeout_input$$,$StaticPool$jscomp$0$$,
|
|
18
|
+
"input pool");global.inputMainPool.exec({load:!0,configs:JSON.stringify($configs$$)},()=>{Logger.info("\ud83d\udd25 [app] Crud pool ready")})}$StaticPool$$&&($StaticPool$jscomp$0$$=require("./libs/WorkerStaticPool"),global.importDataMainPool=new $StaticPool$jscomp$0$$(__dirname+"/workers/inputWorker.js",$options$$.max_queue_imports||0,$StaticPool$$,$timeout_import$$,1,"import pool"),global.importDataMainPool.exec({load:!0,configs:JSON.stringify($configs$$)},()=>{Logger.info("[app] Import pool ready")}));
|
|
19
|
+
$cpus_report_cpus$$&&($StaticPool$$=require("./libs/WorkerStaticPool"),global.reportMainPool=new $StaticPool$$(__dirname+"/workers/reportWorker.js",$options$$.max_queue_reports||0,$cpus_report_cpus$$,$timeout_report$$,2,"report pool"),global.reportMainPool.exec({load:!0,configs:JSON.stringify($configs$$)},()=>{Logger.info("[app] Report pool ready")}));$callbackServer$$&&$callbackServer$$()})}else require("./route")($app$$,()=>{$callbackServer$$&&$callbackServer$$()},!0)})}).catch($err$$=>{Logger.info("[app] Not Connected to Database ERROR! ",
|
|
20
|
+
$err$$);process.exit(1)});return $app$$};process.on("SIGINT",async()=>{global.sharedRedisConnection&&await global.sharedRedisConnection.quit();process.exit(0)});process.on("uncaughtException",function($err$jscomp$3_error$$){Logger.error((new Date).toUTCString()+" uncaughtException:",$err$jscomp$3_error$$.message);Logger.error($err$jscomp$3_error$$.stack);$err$jscomp$3_error$$=`
|
|
25
21
|
Error: ${$err$jscomp$3_error$$.message}
|
|
26
22
|
Stack: ${$err$jscomp$3_error$$.stack}
|
|
27
23
|
`;try{const $logDirectory$$=__dirname+"/log";fs.existsSync($logDirectory$$)||fs.mkdirSync($logDirectory$$);fs.writeFile(`${$logDirectory$$}/error-${(new Date).getTime()}.txt`,$err$jscomp$3_error$$,()=>{Logger.info("[app] wrote log error")})}catch($e$$){Logger.info($e$$)}process.exit(1)});module.exports=mainServer;
|
package/server/global.js
CHANGED
|
@@ -11,8 +11,7 @@ const pointSchema=new global.mongoose.Schema({type:{type:String,enum:["Point"],r
|
|
|
11
11
|
global.getSysConfig=async $cf_code$$=>{if($cf_code$$=await global.getModel("sysconfig").findOne({code:$cf_code$$}))return $cf_code$$.value};global.asyncCountUnRead=async $email$$=>global.getModel("message").countDocuments({email:$email$$,read:!1});
|
|
12
12
|
global.alertMessage=function($email$$,$id_app$$){onAfterCommit(async()=>{var $Message$jscomp$1_count$$=global.getModel("message");const $User$$=global.getModel("user");let $query$$={email_owner:$email$$,read:!1};$id_app$$&&($query$$["exfields.id_app"]=$id_app$$);$Message$jscomp$1_count$$=await $Message$jscomp$1_count$$.countDocuments($query$$);$User$$.emitEvent($email$$,"message:count",$Message$jscomp$1_count$$,!1)})};
|
|
13
13
|
global.createNotification=function($email_sender$$,$email_receiver$$,$title$$,$content$$,$fn$$,$exfields$$,$emitEvent$$,$c_token$$,$send_email$$){global.getModel("notification").createNotification($email_sender$$,$email_receiver$$,$title$$,$content$$,$fn$$,$exfields$$,$emitEvent$$,$c_token$$,$send_email$$)};
|
|
14
|
-
global.getNotifies=function($email$$,$fn$$,$id_app$$){if(!$id_app$$)return $fn$$(null,{notifications:[],colls:[],apps:[]});const $Notification$$=global.getModel("notification");async.parallel({colls:function(
|
|
15
|
-
$colls_raw_query$$)})},apps:function($callback$$){$callback$$(null,[])}},function($error$$,$rs$$){setImmediate(()=>{$fn$$($error$$,$rs$$)})})};
|
|
14
|
+
global.getNotifies=function($email$$,$fn$$,$id_app$$){if(!$id_app$$)return $fn$$(null,{notifications:[],colls:[],apps:[]});const $Notification$$=global.getModel("notification");async.parallel({colls:function(){return[]},notifications:async function(){let $query$$={email_owner:$email$$,read:!1};$id_app$$&&($query$$["exfields.id_app"]=$id_app$$);return await $Notification$$.find($query$$).lean()},apps:function(){return[]}},function($error$$,$rs$$){$fn$$($error$$,$rs$$)})};
|
|
16
15
|
global.sendNotification=function($email$$,$_id_obj_notify$$,$notify$$,$push_to_mobile_and_web$$=!0){const $User$$=global.getModel("user");$notify$$||={email_sender:"H\u1ec7 th\u1ed1ng"};$_id_obj_notify$$={_id:$_id_obj_notify$$,code:"notification",action:"view"};$_id_obj_notify$$.body=$notify$$.content||$notify$$.title||"";$_id_obj_notify$$.sender=$notify$$.email_sender;$_id_obj_notify$$.title=$notify$$.title||"";$_id_obj_notify$$.content=$notify$$.content||"";$User$$.emitEvent($email$$,"notify:new",
|
|
17
16
|
$_id_obj_notify$$,$push_to_mobile_and_web$$)};
|
|
18
17
|
global.alertNotification=async function($email$$,$id_app$$){var $Notification$jscomp$2_count$$=global.getModel("notification");const $User$$=global.getModel("user");let $condition$$={email_owner:$email$$,read:!1};$id_app$$&&($condition$$["exfields.id_app"]=$id_app$$);$Notification$jscomp$2_count$$=await $Notification$jscomp$2_count$$.countDocuments($condition$$);Logger.warn("[global][alertNotification]",{email:$email$$,id_app:$id_app$$,count:$Notification$jscomp$2_count$$});$User$$.emitEvent($email$$,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const assabcihandlerSchema=new Schema({id_app:{type:String,required:!0},event:{type:String,required:!0,uppercase:!0},id:{type:String,required:!0},trang_thai:{type:String,default:"0"},date_created:{type:Date,default:Date.now},data:Schema.Types.Mixed});(global.configs||{}).createIndexes&&assabcihandlerSchema.index({id_app:1,event:1,id:1},{unique:!0});const model=mongoose.models.assabcihandler||mongoose.model("assabcihandler",assabcihandlerSchema),moment=require("moment"),async=require("
|
|
1
|
+
const assabcihandlerSchema=new Schema({id_app:{type:String,required:!0},event:{type:String,required:!0,uppercase:!0},id:{type:String,required:!0},trang_thai:{type:String,default:"0"},date_created:{type:Date,default:Date.now},data:Schema.Types.Mixed});(global.configs||{}).createIndexes&&assabcihandlerSchema.index({id_app:1,event:1,id:1},{unique:!0});const model=mongoose.models.assabcihandler||mongoose.model("assabcihandler",assabcihandlerSchema),moment=require("moment"),async=require("../libs/asyncCompat");
|
|
2
2
|
model.start=()=>{Logger.info("abci handler is started");async.forever(function($next$$){setTimeout(async()=>{const $now$$=new Date,$withdraws$$=await global.getModel("asswithdraw").find({trang_thai:"0",status:!0,ngay_xu_ly:{$lte:$now$$}});await new Promise($resolve$$=>{async.mapSeries($withdraws$$,($Withdraw$$,$callback$$)=>{setImmediate(async()=>{let $query_abci$$={id_app:$Withdraw$$.id_app,event:"WITHDRAW",id:$Withdraw$$.id},$abci$$=await model.findOne($query_abci$$);if($abci$$&&$abci$$.trang_thai==
|
|
3
3
|
"0"&&moment().diff(moment($abci$$.date_created),"hours")<1)return $callback$$();try{$abci$$=new model($query_abci$$),await $abci$$.save()}catch($e$$){return $callback$$()}try{await global.getModel("assbank").sendCoins($Withdraw$$.id_app,$Withdraw$$.product_owner,$Withdraw$$.creator,$Withdraw$$.von,$Withdraw$$.denom,{...$Withdraw$$.toObject(),event:"WITHDRAW",memo:"R\u00fat v\u1ed1n"})}catch($e$$){return $callback$$()}try{$Withdraw$$.lai_truoc_han&&await global.getModel("assbank").sendCoins($Withdraw$$.id_app,
|
|
4
4
|
$Withdraw$$.product_owner,$Withdraw$$.creator,$Withdraw$$.lai_truoc_han,$Withdraw$$.denom,{...$Withdraw$$.toObject(),event:"INTEREST",memo:"L\u00e3i t\u1eeb \u0111\u1ea7u t\u01b0"}),$Withdraw$$.da_rut_von=!0,$Withdraw$$.trang_thai="5",await $Withdraw$$.save(),$abci$$.data={note:"R\u00fat v\u1ed1n th\u00e0nh c\u00f4ng",obj:$Withdraw$$.toObject()},$abci$$.trang_thai="5",await $abci$$.save(),Logger.info("lenh rut von nay da duoc thuc hien thanh cong:",$Withdraw$$.id)}catch($e$$){await global.getModel("assbank").sendCoins($Withdraw$$.id_app,
|
package/server/route.js
CHANGED
|
@@ -18,7 +18,7 @@ const $ip$$=$req$$.ip||$req$$.headers["x-forwarded-for"]||$req$$.socket.remoteAd
|
|
|
18
18
|
$err$$});var $originalname_p$$=$req$$.files.fileupload.originalname.split(" ").join("_");$err$$=configs.paths.images||$path$$.dirname($path$$.dirname(__dirname))+"/images";$err$$+="/";fs.existsSync($err$$+$folder$$)||fs.mkdirSync($err$$+$folder$$);$id_app$$&&$folder$$!="avatar"&&($folder$$=$folder$$+"/"+$id_app$$,fs.existsSync($err$$+$folder$$)||fs.mkdirSync($err$$+$folder$$));let $newPath$$=$folder$$+"/"+$user$$._id.toString()+"_"+(new Date).getTime().toString()+"_"+$originalname_p$$,$path_image$$;
|
|
19
19
|
if($ext$$!==".png"&&$ext$$!==".jpeg"&&$ext$$!==".jpg"&&$ext$$!==".gif"&&$ext$$!==".webp")$path_image$$=$err$$+$newPath$$,fs.writeFile($path_image$$,$data$$,function($err$$){if($err$$)return $res$$.status(400).send({error:$err$$.message||$err$$.error||$err$$});fs.unlink($req$$.files.fileupload.path,$e$$=>{$e$$&&Logger.error($e$$)});$req$$.query.json?$res$$.send({fileUrl:"/getfile/"+$newPath$$}):($res$$.writeHead(200,{"Content-Type":"text/html"}),$res$$.end("<html><head><title>/getfile/"+$newPath$$+
|
|
20
20
|
"</title></head><body>success</body></html>"))});else{$ext$$!==".webp"&&($newPath$$+=".webp");$path_image$$=$err$$+$newPath$$;$originalname_p$$=$originalname_p$$.split(".");var $thumbPath$$=$newPath$$+".thumb."+$originalname_p$$[$originalname_p$$.length-1],$path_image_thumb$$=$err$$+$thumbPath$$,$_gm$$=sharp($req$$.files.fileupload.path,{failOnError:!1});($err$$=await $_gm$$.metadata())&&$err$$.format!="webp"&&($thumbPath$$+=".webp",$path_image_thumb$$+=".webp",$_gm$$=$_gm$$.webp({lossless:!1}));
|
|
21
|
-
async.parallel([function($callback$$){setImmediate(async()=>{let $orgin_file_size$$=await $_gm$$.metadata();$orgin_file_size$$&&$orgin_file_size$$.width>4096?$_gm$$.resize({width:4096}).rotate().toFile($path_image$$,async function($error$$){$error$$?(Logger.error("save resize image:",$error$$.message,". Ch\u01b0\u01a1ng tr\u00ecnh s\u1ebd s\u1eed d\u1ee5ng file g\u1ed1c\n",$req$$.header("user-agent")),fs.writeFile($path_image$$,$data$$,$e$$=>{if($e$$)return $callback$$($error$$);$callback$$()})):
|
|
21
|
+
async.parallel([async function($callback$$){setImmediate(async()=>{let $orgin_file_size$$=await $_gm$$.metadata();$orgin_file_size$$&&$orgin_file_size$$.width>4096?$_gm$$.resize({width:4096}).rotate().toFile($path_image$$,async function($error$$){$error$$?(Logger.error("save resize image:",$error$$.message,". Ch\u01b0\u01a1ng tr\u00ecnh s\u1ebd s\u1eed d\u1ee5ng file g\u1ed1c\n",$req$$.header("user-agent")),fs.writeFile($path_image$$,$data$$,$e$$=>{if($e$$)return $callback$$($error$$);$callback$$()})):
|
|
22
22
|
(Logger.info("resize image",$path_image$$),$callback$$())}):fs.writeFile($path_image$$,$data$$,function($err$$){$callback$$($err$$)})})}],function($err$$){if($err$$)return $res$$.status(400).send({error:$err$$.message||$err$$.error||$err$$});$_gm$$.resize({width:350}).rotate().toFile($path_image_thumb$$,async function($error$$){if($error$$){Logger.error("Kh\u00f4ng th\u1ec3 t\u1ea1o thumbnail cho h\u00ecnh \u1ea3nh n\u00e0y\n"+$error$$,$req$$.files.fileupload.path,". Ch\u01b0\u01a1ng tr\u00ecnh s\u1ebd s\u1eed d\u1ee5ng file g\u1ed1c l\u00e0m thubnail\n",
|
|
23
23
|
$req$$.header("user-agent"));try{await new Promise(($res$$,$rej$$)=>{fs.writeFile($path_image_thumb$$,$data$$,$e$$=>{if($e$$)return $rej$$($e$$);$res$$()})})}catch($error$$){return $res$$.status(400).send({error:"Kh\u00f4ng th\u1ec3 t\u1ea1o thumbnail cho h\u00ecnh \u1ea3nh n\u00e0y. L\u1ed7i: "+($error$$.message||$error$$.error||$error$$)})}}fs.unlink($req$$.files.fileupload.path,$e$$=>{$e$$&&Logger.error($e$$)});let $path_avatar$$="/getfile/"+$newPath$$,$path_thumb$$="/getfile/"+$thumbPath$$;$folder$$==
|
|
24
24
|
"avatars"?($user$$.local.picture=$path_avatar$$,$user$$.picture=$user$$.local.picture,$user$$.save(function($error$$){if($error$$)return $res$$.status(400).send($error$$);$redisCache$$.set("user",$user$$.toObject(),function($e$$){$e$$?Logger.error($e$$):Logger.info("cache user infomation to redis");$res$$.send("\u0110\u00e3 c\u1eadp nh\u1eadt th\u00e0nh c\u00f4ng")});$req$$.query.json?$res$$.send({image:$path_avatar$$,thumb:$path_thumb$$,fileUrl:$path_avatar$$}):($res$$.writeHead(200,{"Content-Type":"text/html"}),
|