flexbiz-server
Version:
Flexible Server
17 lines (16 loc) • 7.06 kB
JavaScript
'use strict';const Moment=require("moment"),fs=require("fs"),path=require("path"),app=require("./app"),schedule_log=require("./schedule_log"),time_check=6E4,async=require("async"),_=require("lodash"),Controller=require("../controllers/controller"),actions={sendNotification:async $data_schedule$$=>{if(($data_schedule$$=$data_schedule$$.data)&&"string"==typeof $data_schedule$$)try{$data_schedule$$=JSON.parse($data_schedule$$)}catch($e$$){console.error("data of schedule is not valid",$data_schedule$$,
$e$$);return}if($data_schedule$$&&$data_schedule$$.users_will_receive&&$data_schedule$$.title){var $notificationData$$={_id:$data_schedule$$._id,trang_thai:$data_schedule$$.trang_thai,id_app:$data_schedule$$.id_app,title:$data_schedule$$.title,body:$data_schedule$$.body,code:$data_schedule$$.ma_ct||$data_schedule$$.code,event:$data_schedule$$.event||"reminder",action:($data_schedule$$.event||"reminder").toUpperCase()};app.emitEvent($data_schedule$$.id_app,$data_schedule$$.event,$notificationData$$,
null,$data_schedule$$.users_will_receive,!0)}},updateData:async $module_name_schedule$$=>{let $data$$=$module_name_schedule$$.data;_.isString($data$$)&&($data$$=JSON.parse($data$$));if($data$$&&$data$$._id&&global.mongoose.Types.ObjectId.isValid($data$$._id)&&($module_name_schedule$$=$data$$.module||$data$$.model)&&!(0<=["token","tokens","user","asskey"].indexOf($module_name_schedule$$.toLowerCase()))){var $module$$=global.controllers[$module_name_schedule$$.toUpperCase()];if($module$$){let $_model$$=
$module$$.model||global.getModel("module_name");delete $data$$.module;delete $data$$.model;$_model$$.updateOne({id_app:$data$$.id_app,_id:$data$$._id},$data$$,async $e$jscomp$1_obj$$=>{if($e$jscomp$1_obj$$)return console.error("error update data",$e$jscomp$1_obj$$);$e$jscomp$1_obj$$=await $_model$$.findOne({_id:$data$$._id});Controller.postData($e$jscomp$1_obj$$,$module$$,$e$$=>{$e$$&&console.error($e$$)})})}else console.log("module"+$data$$.module,"is not exists")}},runScript:$processPath_schedule$$=>
{let $script$$=$processPath_schedule$$.script;if($script$$){$processPath_schedule$$=path.dirname(__dirname)+"/workers/runScript.js";if(!fs.existsSync($processPath_schedule$$))return console.error("runScript process is not exitst");if(!global.runScriptPool){const $StaticPool$$=require("../libs/WorkerStaticPool");global.runScriptPool=new $StaticPool$$($processPath_schedule$$,0,1)}return new Promise(($rs$$,$rj$$)=>{global.runScriptPool.exec({script:$script$$,configs:global.configs},$response$$=>{$response$$.error?
(console.error($response$$.error),$rj$$($response$$.error)):(console.log("run script result:",$response$$),$rs$$($response$$))})})}}},scheduleSchema=new Schema({id_link:{type:String},title:{type:String,required:!0},action:{type:String,required:!0},data:{type:Schema.Types.Mixed},script:String,time_run:{type:Date,required:!0},repeat:{type:Number,default:0},next_run:Date,finish_run:Date,trang_thai:{type:String,default:"0"},exfields:Schema.Types.Mixed,status:{type:Boolean,default:!0},date_created:{type:Date,
default:Date.now},date_updated:{type:Date,default:Date.now},user_created:{type:String,default:""},user_updated:{type:String,default:""}});(global.configs||{}).createIndexes&&(scheduleSchema.index({trang_thai:1}),scheduleSchema.index({time_run:1}),scheduleSchema.index({action:1}),scheduleSchema.index({id_link:1}),scheduleSchema.index({title:"text"}),scheduleSchema.index({status:1}),scheduleSchema.index({user_created:1,visible_to:1,visible_to_users:1}));
const model=mongoose.models.schedule||mongoose.model("schedule",scheduleSchema),redis_key="schedule_key";model.loadFromRedis=async()=>new Promise(($resolve$$,$reject$$)=>{global.clientRedis.get(redis_key,($e$jscomp$0$$,$string_rs$$)=>{if($e$jscomp$0$$)return $reject$$($e$jscomp$0$$);if($string_rs$$)try{const $rs$$=JSON.parse($string_rs$$);$resolve$$($rs$$)}catch($e$$){$resolve$$([])}else $resolve$$([])})});
model.saveToRedis=async $rs$$=>new Promise(($resolve$$,$reject$$)=>{global.clientRedis.set(redis_key,JSON.stringify($rs$$),$e$$=>{if($e$$)return $reject$$($e$$);$resolve$$()})});
model.addSchedule=$schedule$$=>{model.create($schedule$$,async($e$jscomp$0$$,$rs$$)=>{if($e$jscomp$0$$)return console.error("error add schedule to db",$e$jscomp$0$$);try{const $schedules$$=await model.loadFromRedis();$schedules$$.push($rs$$.toObject());await model.saveToRedis($schedules$$);console.log("added a schedule, time state at",$schedule$$.time_run)}catch($e$$){console.error("error add schedule to redis",$e$$)}})};
model.removeSchedule=async $id$$=>{await model.deleteOne({_id:$id$$});try{let $schedules$$=await model.loadFromRedis();$schedules$$=$schedules$$.filter($s$$=>$s$$._id!==$id$$);await model.saveToRedis($schedules$$)}catch($e$$){console.error("error remove schedule",$e$$)}};
model.removeScheduleLink=async $id_link$$=>{await model.deleteOne({id_link:$id_link$$});try{let $schedules$$=await model.loadFromRedis();$schedules$$=$schedules$$.filter($s$$=>$s$$.id_link!==$id_link$$);await model.saveToRedis($schedules$$)}catch($e$$){console.error("error remove schedule",$e$$)}};
model.check=async($callback$$=()=>{})=>{try{let $schedules$$=await model.loadFromRedis(),$handle_schedules$$=$schedules$$.filter($s$$=>{if("9"===$s$$.trang_thai||!$s$$.repeat&&"1"===$s$$.trang_thai)return!1;let $current$$=Moment().toDate();return Moment($s$$.next_run||$s$$.time_run).toDate().getTime()<=$current$$.getTime()});async.mapSeries($handle_schedules$$,($schedule$$,$cb$$)=>{if($schedule$$.repeat){let $next_run$$=Moment();switch($schedule$$.repeat){case 1:$next_run$$=$next_run$$.add(1,"days");
break;case 2:$next_run$$=$next_run$$.add(1,"weeks");break;case 3:$next_run$$=$next_run$$.add(1,"months");break;case 4:$next_run$$=$next_run$$.add(1,"quarters");break;case 7:$next_run$$=$next_run$$.add(1,"hours");break;default:$next_run$$=$next_run$$.add(1,"years")}let $finish_run$$=$schedule$$.finish_run;$finish_run$$&&($finish_run$$=Moment($finish_run$$).startOf("date"));$finish_run$$&&$finish_run$$.toDate()<$next_run$$.toDate()?$schedule$$.trang_thai="9":$schedule$$.trang_thai="0";$schedule$$.next_run=
$next_run$$}else $schedule$$.trang_thai="9";let $action$$=$schedule$$.action;actions[$action$$]&&model.findOneAndUpdate({_id:$schedule$$._id},$schedule$$).then(async()=>{try{await actions[$action$$]($schedule$$),schedule_log.create({id_schedule:$schedule$$._id,message:"ok"})}catch($e$$){schedule_log.create({id_schedule:$schedule$$._id,message:"Error: "+($e$$.message||$e$$.error||$e$$)}),console.error($e$$)}});$cb$$()},async()=>{$schedules$$=$schedules$$.filter($s$$=>"0"===$s$$.trang_thai);await model.saveToRedis($schedules$$);
setTimeout(()=>{$callback$$()},time_check)})}catch($e$$){console.error($e$$),setTimeout(()=>{$callback$$()},time_check)}};model.start=()=>{model.find({trang_thai:"0"}).lean().then($rs$$=>{global.clientRedis.set(redis_key,JSON.stringify($rs$$),()=>{async.forever(function($next$$){setImmediate(()=>{model.check($e$$=>{$next$$($e$$)})})},function($err$$){$err$$&&console.error($err$$)})})})};module.exports=model;