@resolveio/server-lib 20.3.27 → 20.4.0

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.
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,o,r,i){return new(r=r||Promise)(function(t,n){function fulfilled(e){try{step(i.next(e))}catch(e){n(e)}}function rejected(e){try{step(i.throw(e))}catch(e){n(e)}}function step(e){var n;e.done?t(e.value):((n=e.value)instanceof r?n:new r(function(e){e(n)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,r){var i,a,s,c={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},_={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function verb(t){return function(e){var n=[t,e];if(i)throw new TypeError("Generator is already executing.");for(;c=_&&n[_=0]?0:c;)try{if(i=1,a&&(s=2&n[0]?a.return:n[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,n[1])).done)return s;switch(a=0,(n=s?[2&n[0],s.value]:n)[0]){case 0:case 1:s=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,a=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(s=0<(s=c.trys).length&&s[s.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3]))c.label=n[1];else if(6===n[0]&&c.label<s[1])c.label=s[1],s=n;else{if(!(s&&c.label<s[2])){s[2]&&c.ops.pop(),c.trys.pop();continue}c.label=s[2],c.ops.push(n)}}n=r.call(o,c)}catch(e){n=[6,e],a=0}finally{i=s=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}}},cron_job_collection_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.CronManager=void 0,require("../collections/cron-job.collection")),cron_1=require("../cron/cron"),cron_job_history_collection_1=require("../collections/cron-job-history.collection"),mongo_manager_1=require("../managers/mongo.manager"),CronManager=function(){function CronManager(e){this._jobs=[],this._mainServer=e,this._cronManager=new cron_1.CronJobManager,this.watchCrons()}return CronManager.prototype.watchCrons=function(){return __awaiter(this,void 0,void 0,function(){var n=this;return __generator(this,function(e){switch(e.label){case 0:return this._watchCrons$&&!this._watchCrons$.closed&&(this._watchCrons$.removeAllListeners(),this._watchCrons$.close(),this._watchCrons$=null),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 1:return e.sent(),this._watchCrons$&&!this._watchCrons$.closed||(cron_job_collection_1.CronJobs.find().then(function(e){n._jobs=e,n._jobs.forEach(function(e){n.addCronJob(e),e.running&&cron_job_collection_1.CronJobs.updateOne({_id:e._id},{$set:{running:!1}})})}),this._watchCrons$=cron_job_collection_1.CronJobs.watchCollection([],{fullDocument:"updateLookup"}),this._watchCrons$.on("change",function(o){return __awaiter(n,void 0,void 0,function(){var n,t;return __generator(this,function(e){return"insert"===o.operationType?o.fullDocument&&(this._jobs.some(function(e){return e._id===o.documentKey._id})||this._jobs.push(o.fullDocument),this.addCronJob(o.fullDocument)):"replace"===o.operationType||"update"===o.operationType?o.fullDocument?(n=this._jobs.filter(function(e){return e._id===o.documentKey._id})[0])?(this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1,o.fullDocument),n.name!==o.fullDocument.name?(this.removeCronJob(n.name),this.addCronJob(o.fullDocument)):(typeof n.time_to_run!=typeof o.fullDocument.time_to_run||"string"==typeof n.time_to_run&&n.time_to_run!==o.fullDocument.time_to_run||n.time_to_run instanceof Date&&n.time_to_run.getTime()!==o.fullDocument.time_to_run.getTime()||n.timezone!==o.fullDocument.timezone)&&this.updateCronJob(o.fullDocument)):(this._jobs.push(o.fullDocument),this.addCronJob(o.fullDocument)):this._jobs.some(function(e){return e._id===o.documentKey._id})&&(t=this._jobs.filter(function(e){return e._id===o.documentKey._id})[0],this.removeCronJob(t.name),this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1)):"delete"===o.operationType&&this._jobs.some(function(e){return e._id===o.documentKey._id})&&(t=this._jobs.filter(function(e){return e._id===o.documentKey._id})[0],this.removeCronJob(t.name),this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1)),[2]})})}).on("error",function(e){n._watchCrons$.removeAllListeners(),n._watchCrons$.close(),n._watchCrons$=null,n.watchCrons()}).on("end",function(){n._watchCrons$.removeAllListeners(),n._watchCrons$.close(),n._watchCrons$=null,n.watchCrons()}).on("close",function(){n._watchCrons$.removeAllListeners(),n._watchCrons$=null,n.watchCrons()})),[2]}})})},CronManager.prototype.doesCronJobExist=function(e){return this._cronManager.exists(e.name)},CronManager.prototype.doesCronJobNameExist=function(e){return this._cronManager.exists(e)},CronManager.prototype.addCronJob=function(n){var e=this;if(!this.doesCronJobExist(n))try{this._cronManager.add(n.name,n.time_to_run,function(){return e.runCronJob(n)},null,!0,n.timezone,null,!1);var t=new Date(this._cronManager.getJob(n.name).nextDate().ts);(n.running||t&&!n.next_run||t.getTime()!==n.next_run.getTime())&&cron_job_collection_1.CronJobs.updateOne({_id:n._id},{$set:{running:!1,next_run:t||null}})}catch(e){console.log("Cron error",e),n.time_to_run instanceof Date&&this.runCronJob(n)}},CronManager.prototype.updateCronJob=function(e){var n,t=this;this.doesCronJobExist(e)&&(this._cronManager.update(e.name,e.time_to_run,function(){return t.runCronJob(e)},null,!0,e.timezone),!(n=new Date(this._cronManager.getJob(e.name).nextDate().ts))||e.next_run&&n.getTime()===e.next_run.getTime()||cron_job_collection_1.CronJobs.updateOne({_id:e._id},{$set:{next_run:n}}))},CronManager.prototype.removeCronJob=function(e){this.doesCronJobNameExist(e)&&this._cronManager.delete(e)},CronManager.prototype.startCronJob=function(e){this.doesCronJobExist(e)&&this._cronManager.start(e.name)},CronManager.prototype.stopCronJob=function(e){this.doesCronJobExist(e)&&this._cronManager.stop(e.name)},CronManager.prototype.stopAllCronJobs=function(){this._cronManager.stopAll()},CronManager.prototype.runCronJob=function(s){var e=this,n=new Date;cron_job_collection_1.CronJobs.findOneAndUpdate({$and:[{_id:s._id},{running:!1},{$or:[{next_run:{$exists:!1}},{next_run:null},{next_run:{$lte:n}}]}]},{$set:{running:!0}}).then(function(a){return __awaiter(e,void 0,void 0,function(){var t,n,o,r,i=this;return __generator(this,function(e){switch(e.label){case 0:return a?(t={_id:(0,mongo_manager_1.objectIdHexString)(),name:a.name,reoccuring:a.repeat,time_to_run:a.time_to_run,method_name:a.method_run,id_cronjob:a._id,server_restart:!0,passed:!0,error:"",date_scheduled:a.next_run,date_start:new Date,date_end:null,date_next:null},[4,cron_job_history_collection_1.CronJobHistories.create(t)]):[3,14];case 1:e.sent(),n=setTimeout(function(){return __awaiter(i,void 0,void 0,function(){var n;return __generator(this,function(e){return console.log(new Date,"Cron Timeout",JSON.stringify(s,null,2)),a.repeat?(n=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=n,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:n}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),[2]})})},3e5),e.label=2;case 2:return(e.trys.push([2,11,12,13]),a.method_run_data)?[4,this._mainServer.getMethodManager().callMethodCron(a.method_run,a.method_run_data)]:[3,4];case 3:return e.sent(),[3,6];case 4:return[4,this._mainServer.getMethodManager().callMethodCron(a.method_run)];case 5:e.sent(),e.label=6;case 6:return a.method_complete?a.method_complete_data?[4,this._mainServer.getMethodManager().callMethodCron(a.method_complete,a.method_complete_data)]:[3,8]:[3,10];case 7:return e.sent(),[3,10];case 8:return[4,this._mainServer.getMethodManager().callMethodCron(a.method_complete)];case 9:e.sent(),e.label=10;case 10:return[3,13];case 11:return o=e.sent(),console.log(new Date,"Cron Error",JSON.stringify(o,null,2)),t.error=JSON.stringify(o,null,2),t.passed=!1,a.repeat?(r=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=r,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:r}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),[3,13];case 12:return clearTimeout(n),[7];case 13:a.repeat?(r=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=r,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:r}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),cron_job_history_collection_1.CronJobHistories.updateOne({_id:t._id},{$set:{server_restart:!1,passed:t.passed,error:t.error,date_end:new Date,date_next:t.date_next}}),e.label=14;case 14:return[2]}})})},function(){})},CronManager}();exports.CronManager=CronManager;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,o,r,i){return new(r=r||Promise)(function(t,n){function fulfilled(e){try{step(i.next(e))}catch(e){n(e)}}function rejected(e){try{step(i.throw(e))}catch(e){n(e)}}function step(e){var n;e.done?t(e.value):((n=e.value)instanceof r?n:new r(function(e){e(n)})).then(fulfilled,rejected)}step((i=i.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,r){var i,a,s,c={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},_={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function verb(t){return function(e){var n=[t,e];if(i)throw new TypeError("Generator is already executing.");for(;c=_&&n[_=0]?0:c;)try{if(i=1,a&&(s=2&n[0]?a.return:n[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,n[1])).done)return s;switch(a=0,(n=s?[2&n[0],s.value]:n)[0]){case 0:case 1:s=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,a=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(s=0<(s=c.trys).length&&s[s.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3]))c.label=n[1];else if(6===n[0]&&c.label<s[1])c.label=s[1],s=n;else{if(!(s&&c.label<s[2])){s[2]&&c.ops.pop(),c.trys.pop();continue}c.label=s[2],c.ops.push(n)}}n=r.call(o,c)}catch(e){n=[6,e],a=0}finally{i=s=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}}},cron_job_collection_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.CronManager=void 0,require("../collections/cron-job.collection")),cron_1=require("../cron/cron"),cron_job_history_collection_1=require("../collections/cron-job-history.collection"),mongo_manager_1=require("../managers/mongo.manager"),CronManager=function(){function CronManager(e){this._jobs=[],this._mainServer=e,this._cronManager=new cron_1.CronJobManager,this.watchCrons()}return CronManager.prototype.watchCrons=function(){return __awaiter(this,void 0,void 0,function(){var n=this;return __generator(this,function(e){switch(e.label){case 0:return this._watchCrons$&&!this._watchCrons$.closed&&(this._watchCrons$.removeAllListeners(),this._watchCrons$.close(),this._watchCrons$=null),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 1:return e.sent(),this._watchCrons$&&!this._watchCrons$.closed||(cron_job_collection_1.CronJobs.find().then(function(e){n._jobs=e,n._jobs.forEach(function(e){n.addCronJob(e),e.running&&cron_job_collection_1.CronJobs.updateOne({_id:e._id},{$set:{running:!1}})})}),this._watchCrons$=cron_job_collection_1.CronJobs.watchCollection([],{fullDocument:"updateLookup"}),this._watchCrons$.on("change",function(o){return __awaiter(n,void 0,void 0,function(){var n,t;return __generator(this,function(e){return"insert"===o.operationType?o.fullDocument&&(this._jobs.some(function(e){return e._id===o.documentKey._id})||this._jobs.push(o.fullDocument),this.addCronJob(o.fullDocument)):"replace"===o.operationType||"update"===o.operationType?o.fullDocument?(n=this._jobs.find(function(e){return e._id===o.documentKey._id}))?(this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1,o.fullDocument),n.name!==o.fullDocument.name?(this.removeCronJob(n.name),this.addCronJob(o.fullDocument)):(typeof n.time_to_run!=typeof o.fullDocument.time_to_run||"string"==typeof n.time_to_run&&n.time_to_run!==o.fullDocument.time_to_run||n.time_to_run instanceof Date&&n.time_to_run.getTime()!==o.fullDocument.time_to_run.getTime()||n.timezone!==o.fullDocument.timezone)&&this.updateCronJob(o.fullDocument)):(this._jobs.push(o.fullDocument),this.addCronJob(o.fullDocument)):this._jobs.some(function(e){return e._id===o.documentKey._id})&&(t=this._jobs.find(function(e){return e._id===o.documentKey._id}),this.removeCronJob(t.name),this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1)):"delete"===o.operationType&&this._jobs.some(function(e){return e._id===o.documentKey._id})&&(t=this._jobs.find(function(e){return e._id===o.documentKey._id}),this.removeCronJob(t.name),this._jobs.splice(this._jobs.map(function(e){return e._id}).indexOf(o.documentKey._id),1)),[2]})})}).on("error",function(e){n._watchCrons$.removeAllListeners(),n._watchCrons$.close(),n._watchCrons$=null,n.watchCrons()}).on("end",function(){n._watchCrons$.removeAllListeners(),n._watchCrons$.close(),n._watchCrons$=null,n.watchCrons()}).on("close",function(){n._watchCrons$.removeAllListeners(),n._watchCrons$=null,n.watchCrons()})),[2]}})})},CronManager.prototype.doesCronJobExist=function(e){return this._cronManager.exists(e.name)},CronManager.prototype.doesCronJobNameExist=function(e){return this._cronManager.exists(e)},CronManager.prototype.addCronJob=function(n){var e=this;if(!this.doesCronJobExist(n))try{this._cronManager.add(n.name,n.time_to_run,function(){return e.runCronJob(n)},null,!0,n.timezone,null,!1);var t=new Date(this._cronManager.getJob(n.name).nextDate().ts);(n.running||t&&!n.next_run||t.getTime()!==n.next_run.getTime())&&cron_job_collection_1.CronJobs.updateOne({_id:n._id},{$set:{running:!1,next_run:t||null}})}catch(e){console.log("Cron error",e),n.time_to_run instanceof Date&&this.runCronJob(n)}},CronManager.prototype.updateCronJob=function(e){var n,t=this;this.doesCronJobExist(e)&&(this._cronManager.update(e.name,e.time_to_run,function(){return t.runCronJob(e)},null,!0,e.timezone),!(n=new Date(this._cronManager.getJob(e.name).nextDate().ts))||e.next_run&&n.getTime()===e.next_run.getTime()||cron_job_collection_1.CronJobs.updateOne({_id:e._id},{$set:{next_run:n}}))},CronManager.prototype.removeCronJob=function(e){this.doesCronJobNameExist(e)&&this._cronManager.delete(e)},CronManager.prototype.startCronJob=function(e){this.doesCronJobExist(e)&&this._cronManager.start(e.name)},CronManager.prototype.stopCronJob=function(e){this.doesCronJobExist(e)&&this._cronManager.stop(e.name)},CronManager.prototype.stopAllCronJobs=function(){this._cronManager.stopAll()},CronManager.prototype.runCronJob=function(s){var e=this,n=new Date;cron_job_collection_1.CronJobs.findOneAndUpdate({$and:[{_id:s._id},{running:!1},{$or:[{next_run:{$exists:!1}},{next_run:null},{next_run:{$lte:n}}]}]},{$set:{running:!0}}).then(function(a){return __awaiter(e,void 0,void 0,function(){var t,n,o,r,i=this;return __generator(this,function(e){switch(e.label){case 0:return a?(t={_id:(0,mongo_manager_1.objectIdHexString)(),name:a.name,reoccuring:a.repeat,time_to_run:a.time_to_run,method_name:a.method_run,id_cronjob:a._id,server_restart:!0,passed:!0,error:"",date_scheduled:a.next_run,date_start:new Date,date_end:null,date_next:null},[4,cron_job_history_collection_1.CronJobHistories.create(t)]):[3,14];case 1:e.sent(),n=setTimeout(function(){return __awaiter(i,void 0,void 0,function(){var n;return __generator(this,function(e){return console.log(new Date,"Cron Timeout",JSON.stringify(s,null,2)),a.repeat?(n=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=n,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:n}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),[2]})})},3e5),e.label=2;case 2:return(e.trys.push([2,11,12,13]),a.method_run_data)?[4,this._mainServer.getMethodManager().callMethodCron(a.method_run,a.method_run_data)]:[3,4];case 3:return e.sent(),[3,6];case 4:return[4,this._mainServer.getMethodManager().callMethodCron(a.method_run)];case 5:e.sent(),e.label=6;case 6:return a.method_complete?a.method_complete_data?[4,this._mainServer.getMethodManager().callMethodCron(a.method_complete,a.method_complete_data)]:[3,8]:[3,10];case 7:return e.sent(),[3,10];case 8:return[4,this._mainServer.getMethodManager().callMethodCron(a.method_complete)];case 9:e.sent(),e.label=10;case 10:return[3,13];case 11:return o=e.sent(),console.log(new Date,"Cron Error",JSON.stringify(o,null,2)),t.error=JSON.stringify(o,null,2),t.passed=!1,a.repeat?(r=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=r,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:r}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),[3,13];case 12:return clearTimeout(n),[7];case 13:a.repeat?(r=new Date(this._cronManager.getJob(a.name).nextDate().ts),t.date_next=r,cron_job_collection_1.CronJobs.updateOne({_id:a._id},{$set:{running:!1,next_run:r}})):cron_job_collection_1.CronJobs.deleteOne({_id:a._id}),cron_job_history_collection_1.CronJobHistories.updateOne({_id:t._id},{$set:{server_restart:!1,passed:t.passed,error:t.error,date_end:new Date,date_next:t.date_next}}),e.label=14;case 14:return[2]}})})},function(){})},CronManager}();exports.CronManager=CronManager;
2
2
  //# sourceMappingURL=cron.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/cron.manager.ts"],"names":["cron_job_collection_1","require","cron_1","cron_job_history_collection_1","mongo_manager_1","CronManager","mainServer","this","_jobs","_mainServer","_cronManager","CronJobManager","watchCrons","prototype","_watchCrons$","closed","removeAllListeners","close","Promise","resolve","setTimeout","_a","sent","CronJobs","find","then","res","_this","forEach","job","addCronJob","running","updateOne","_id","$set","watchCollection","fullDocument","on","doc","__awaiter","operationType","some","a","documentKey","push","oldDoc","filter","splice","map","indexOf","name","removeCronJob","time_to_run","Date","getTime","timezone","updateCronJob","err","doesCronJobExist","cron","exists","doesCronJobNameExist","cron_name","add","runCronJob","nextDate","getJob","next_run","e","console","log","update","delete","startCronJob","start","stopCronJob","stop","stopAllCronJobs","stopAll","now","findOneAndUpdate","$and","$or","$exists","$lte","cronHistory_1","objectIdHexString","reoccuring","repeat","method_name","method_run","id_cronjob","server_restart","passed","error","date_scheduled","date_start","date_end","date_next","CronJobHistories","create","timeoutHandle","JSON","stringify","deleteOne","method_run_data","getMethodManager","callMethodCron","method_complete","method_complete_data","err_1","clearTimeout","exports"],"mappings":"k8CACAA,uB,kFAAAC,QAAA,oCAAA,GAEAC,OAAAD,QAAA,cAAA,EAGAE,8BAAAF,QAAA,4CAAA,EACAG,gBAAAH,QAAA,2BAAA,EAGAI,YAAA,WAMC,SAAAA,YAAYC,GAFJC,KAAAC,MAAwB,GAG/BD,KAAKE,YAAcH,EACnBC,KAAKG,aAAe,IAAIR,OAAAS,eAExBJ,KAAKK,WAAU,CAChB,CA6QD,OA3QcP,YAAAQ,UAAAD,WAAb,W,qHAOC,OANIL,KAAKO,cAAgB,CAACP,KAAKO,aAAaC,SAC3CR,KAAKO,aAAaE,mBAAkB,EACpCT,KAAKO,aAAaG,MAAK,EACvBV,KAAKO,aAAe,MAGrB,CAAA,EAAM,IAAII,QAAQ,SAAAC,GAAW,OAAAC,WAAWD,EAAS,GAAI,CAAxB,CAAyB,G,cAAtDE,EAAAC,KAAA,EAEKf,KAAKO,cAAgBP,CAAAA,KAAKO,aAAaC,SAC3Cf,sBAAAuB,SAASC,KAAI,EAAGC,KAAK,SAAAC,GACpBC,EAAKnB,MAAQkB,EAEbC,EAAKnB,MAAMoB,QAAQ,SAAAC,GAClBF,EAAKG,WAAWD,CAAG,EACfA,EAAIE,SACP/B,sBAAAuB,SAASS,UAAU,CAACC,IAAKJ,EAAII,GAAG,EAAG,CAACC,KAAM,CAACH,QAAS,CAAA,CAAK,CAAC,CAAC,CAE7D,CAAC,CACF,CAAC,EAEDxB,KAAKO,aAAed,sBAAAuB,SAASY,gBAAgB,GAAI,CAACC,aAAc,cAAc,CAAC,EAE/E7B,KAAKO,aAAauB,GAAG,SAAU,SAAOC,GAAuC,OAAAC,UAAAZ,EAAA,KAAA,EAAA,KAAA,EAAA,W,kDAClD,WAAt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IZ,KAAK9C,KAAKG,aAAawD,OAAOxC,EAAIwB,IAAI,EAAEe,SAAQ,EAAO,EAAC,EAC3EoB,EAAYa,UAAYjC,EACxBjE,sBAAAuB,SAASS,UAAU,CAACC,IAAKP,EAAIO,GAAG,EAAG,CAACC,KAAM,CAACH,QAAS,CAAA,EAAOoC,SAAUF,CAAQ,CAAC,CAAC,GAG/EjE,sBAAAuB,SAASiF,UAAU,CAACvE,IAAKP,EAAIO,GAAG,CAAC,E,sBAKlC8E,aAAaV,CAAa,E,YAGvB3E,EAAI8D,QACHvB,EAAW,IAAIZ,KAAK9C,KAAKG,aAAawD,OAAOxC,EAAIwB,IAAI,EAAEe,SAAQ,EAAO,EAAC,EAC3EoB,EAAYa,UAAYjC,EACxBjE,sBAAAuB,SAASS,UAAU,CAACC,IAAKP,EAAIO,GAAG,EAAG,CAACC,KAAM,CAACH,QAAS,CAAA,EAAOoC,SAAUF,CAAQ,CAAC,CAAC,GAG/EjE,sBAAAuB,SAASiF,UAAU,CAACvE,IAAKP,EAAIO,GAAG,CAAC,EAGlC9B,8BAAAgG,iBAAiBnE,UAAU,CAACC,IAAKoD,EAAYpD,GAAG,EAAG,CAACC,KAAM,CACzD0D,eAAgB,CAAA,EAChBC,OAAQR,EAAYQ,OACpBC,MAAOT,EAAYS,MACnBG,SAAU,IAAI5C,KACd6C,UAAWb,EAAYa,S,CACvB,CAAC,E,mCAED,YAAQ,CACZ,EACD7F,WAAA,EAAC,EAxRY2G,QAAA3G,YAAAA","file":"cron.manager.js","sourcesContent":["import { CronJobModel } from '../models/cron-job.model';\nimport { CronJobs } from '../collections/cron-job.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { CronJobManager } from '../cron/cron';\nimport * as moment from 'moment-timezone';\nimport { ChangeStream, ChangeStreamDocument } from 'mongodb';\nimport { CronJobHistories } from '../collections/cron-job-history.collection';\nimport { objectIdHexString } from '../managers/mongo.manager';\nimport { CronJobHistoryModel } from '../models/cron-job-history.model';\n\nexport class CronManager {\n\tprivate _cronManager: CronJobManager;\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _watchCrons$: ChangeStream;\n\tprivate _jobs: CronJobModel[] = [];\n\n\tconstructor(mainServer) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._cronManager = new CronJobManager();\n\n\t\tthis.watchCrons();\n\t}\n\n\tpublic async watchCrons() {\n\t\tif (this._watchCrons$ && !this._watchCrons$.closed) {\n\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\tthis._watchCrons$.close();\n\t\t\tthis._watchCrons$ = null;\n\t\t}\n\t\n\t\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\t\n\t\tif (!this._watchCrons$ || this._watchCrons$.closed) {\t\t\t\n\t\t\tCronJobs.find().then(res => {\n\t\t\t\tthis._jobs = res;\n\n\t\t\t\tthis._jobs.forEach(job => {\n\t\t\t\t\tthis.addCronJob(job);\n\t\t\t\t\tif (job.running) {\n\t\t\t\t\t\tCronJobs.updateOne({_id: job._id}, {$set: {running: false}});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tthis._watchCrons$ = CronJobs.watchCollection([], {fullDocument: 'updateLookup'});\n\n\t\t\tthis._watchCrons$.on('change', async (doc: ChangeStreamDocument<CronJobModel>) => {\n\t\t\t\tif (doc.operationType === 'insert') {\n\t\t\t\t\tif (doc.fullDocument) {\n\t\t\t\t\t\tif (!this._jobs.some(a => a._id === <any>doc.documentKey['_id'])) {\n\t\t\t\t\t\t\tthis._jobs.push(doc.fullDocument);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (doc.operationType === 'replace' || doc.operationType === 'update') {\n\t\t\t\t\tif (doc.fullDocument) {\n\t\t\t\t\t\tlet oldDoc = this._jobs.filter(a => a._id === <any>doc.documentKey['_id'])[0];\n\t\t\t\t\t\tif (oldDoc) {\n\t\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1, doc.fullDocument);\n\n\t\t\t\t\t\t\tif (oldDoc.name !== doc.fullDocument.name) {\n\t\t\t\t\t\t\t\tthis.removeCronJob(oldDoc.name);\n\t\t\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (typeof oldDoc.time_to_run !== typeof doc.fullDocument.time_to_run || (typeof oldDoc.time_to_run === 'string' && oldDoc.time_to_run !== doc.fullDocument.time_to_run) ||\n\t\t\t\t\t\t\t\t(oldDoc.time_to_run instanceof Date && oldDoc.time_to_run.getTime() !== (<Date>doc.fullDocument.time_to_run).getTime()) || \n\t\t\t\t\t\t\t\toldDoc.timezone !== doc.fullDocument.timezone\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthis.updateCronJob(doc.fullDocument);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._jobs.push(doc.fullDocument);\n\t\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (this._jobs.some(a => a._id === <any>doc.documentKey['_id'])) {\n\t\t\t\t\t\t\tlet job = this._jobs.filter(a => a._id === <any>doc.documentKey['_id'])[0];\n\t\t\t\t\t\t\tthis.removeCronJob(job.name);\n\t\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (doc.operationType === 'delete') {\n\t\t\t\t\tif (this._jobs.some(a => a._id === (<any>doc).documentKey['_id'])) {\n\t\t\t\t\t\tlet job = this._jobs.filter(a => a._id === <any>doc.documentKey['_id'])[0];\n\t\t\t\t\t\tthis.removeCronJob(job.name);\n\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', (err) => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$.close();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$.close();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate doesCronJobExist(cron: CronJobModel) {\n\t\treturn this._cronManager.exists(cron.name);\n\t}\n\n\tprivate doesCronJobNameExist(cron_name: string) {\n\t\treturn this._cronManager.exists(cron_name);\n\t}\n\n\tprivate addCronJob(cron: CronJobModel) {\n\t\tif (!this.doesCronJobExist(cron)) {\n\t\t\ttry {\n\t\t\t\tthis._cronManager.add(\n\t\t\t\t\tcron.name,\n\t\t\t\t\tcron.time_to_run,\n\t\t\t\t\t() => this.runCronJob(cron),\n\t\t\t\t\tnull,\n\t\t\t\t\ttrue,\n\t\t\t\t\tcron.timezone,\n\t\t\t\t\tnull, \n\t\t\t\t\tfalse\n\t\t\t\t);\n\n\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(cron.name).nextDate()['ts']);\n\n\t\t\t\tif (cron.running || (nextDate && !cron.next_run || nextDate.getTime() !== cron.next_run.getTime())) {\n\t\t\t\t\tCronJobs.updateOne({_id: cron._id}, {$set: {running: false, next_run: nextDate || null}});\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(e) {\n\t\t\t\tconsole.log('Cron error', e);\n\n\t\t\t\tif (cron.time_to_run instanceof Date) {\n\t\t\t\t\tthis.runCronJob(cron);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate updateCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.update(cron.name, cron.time_to_run, () => this.runCronJob(cron), null, true, cron.timezone);\n\n\t\t\tlet nextDate = new Date(this._cronManager.getJob(cron.name).nextDate()['ts']);\n\n\t\t\tif (nextDate && (!cron.next_run || nextDate.getTime() !== cron.next_run.getTime())) {\n\t\t\t\tCronJobs.updateOne({_id: cron._id}, {$set: {next_run: nextDate}});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate removeCronJob(cron_name: string) {\n\t\tif (this.doesCronJobNameExist(cron_name)) {\n\t\t\tthis._cronManager.delete(cron_name);\n\t\t}\n\t}\n\n\tprivate startCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.start(cron.name);\n\t\t}\n\t}\n\n\tprivate stopCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.stop(cron.name);\n\t\t}\n\t}\n\n\tprivate stopAllCronJobs() {\n\t\tthis._cronManager.stopAll();\n\t}\n\n\tprivate runCronJob(cron: CronJobModel) {\n\t\tlet now = new Date();\n\n\t\tCronJobs.findOneAndUpdate({\n\t\t\t$and: [\n\t\t\t\t{_id: cron._id},\n\t\t\t\t{running: false},\n\t\t\t\t{\n\t\t\t\t\t$or: [\n\t\t\t\t\t\t{next_run: {$exists: false}},\n\t\t\t\t\t\t{next_run: null},\n\t\t\t\t\t\t{next_run: {$lte: now}}\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t]\n\t\t}, {$set: {running: true}}).then(async res => {\n\t\t\tif (res) {\n\t\t\t\tlet cronHistory: CronJobHistoryModel = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\tname: res.name,\n\t\t\t\t\treoccuring: res.repeat,\n\t\t\t\t\ttime_to_run: res.time_to_run,\n\t\t\t\t\tmethod_name: res.method_run,\n\t\t\t\t\tid_cronjob: res._id,\n\t\t\t\t\tserver_restart: true,\n\t\t\t\t\tpassed: true,\n\t\t\t\t\terror: '',\n\t\t\t\t\tdate_scheduled: res.next_run,\n\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\tdate_end: null,\n\t\t\t\t\tdate_next: null\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tawait CronJobHistories.create(cronHistory);\n\n\t\t\t\tlet timeoutHandle = setTimeout(async () => {\n\t\t\t\t\tconsole.log(new Date(), 'Cron Timeout', JSON.stringify(cron, null, 2));\n\n\t\t\t\t\tif (res.repeat) {\n\t\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t\t} \n\t\t\t\t\telse {\n\t\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t\t}\n\t\t\t\t}, 5 * 60 * 1000); // 5 minutes in milliseconds\n\n\t\t\t\ttry {\n\t\t\t\t\tif (res.method_run_data) {\n\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_run, res.method_run_data);\t\n\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_run);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (res.method_complete) {\n\t\t\t\t\t\tif (res.method_complete_data) {\n\t\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_complete, res.method_complete_data);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_complete);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.log(new Date(), 'Cron Error', JSON.stringify(err, null, 2));\n\t\t\t\t\tcronHistory.error = JSON.stringify(err, null, 2);\n\t\t\t\t\tcronHistory.passed = false;\n\n\t\t\t\t\tif (res.repeat) {\n\t\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t\t} \n\t\t\t\t\telse {\n\t\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\t// Clear the timeout if the job completes or fails before the timeout\n\t\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\t}\n\n\t\t\t\tif (res.repeat) {\n\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t} \n\t\t\t\telse {\n\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t}\n\n\t\t\t\tCronJobHistories.updateOne({_id: cronHistory._id}, {$set: {\n\t\t\t\t\tserver_restart: false,\n\t\t\t\t\tpassed: cronHistory.passed,\n\t\t\t\t\terror: cronHistory.error,\n\t\t\t\t\tdate_end: new Date(),\n\t\t\t\t\tdate_next: cronHistory.date_next\n\t\t\t\t}});\n\t\t\t}\n\t\t}, () => {});\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/managers/cron.manager.ts"],"names":["cron_job_collection_1","require","cron_1","cron_job_history_collection_1","mongo_manager_1","CronManager","mainServer","this","_jobs","_mainServer","_cronManager","CronJobManager","watchCrons","prototype","_watchCrons$","closed","removeAllListeners","close","Promise","resolve","setTimeout","_a","sent","CronJobs","find","then","res","_this","forEach","job","addCronJob","running","updateOne","_id","$set","watchCollection","fullDocument","on","doc","__awaiter","operationType","some","a","documentKey","push","oldDoc","splice","map","indexOf","name","removeCronJob","time_to_run","Date","getTime","timezone","updateCronJob","err","doesCronJobExist","cron","exists","doesCronJobNameExist","cron_name","add","runCronJob","nextDate","getJob","next_run","e","console","log","update","delete","startCronJob","start","stopCronJob","stop","stopAllCronJobs","stopAll","now","findOneAndUpdate","$and","$or","$exists","$lte","cronHistory_1","objectIdHexString","reoccuring","repeat","method_name","method_run","id_cronjob","server_restart","passed","error","date_scheduled","date_start","date_end","date_next","CronJobHistories","create","timeoutHandle","JSON","stringify","deleteOne","method_run_data","getMethodManager","callMethodCron","method_complete","method_complete_data","err_1","clearTimeout","exports"],"mappings":"k8CACAA,uB,kFAAAC,QAAA,oCAAA,GAEAC,OAAAD,QAAA,cAAA,EAGAE,8BAAAF,QAAA,4CAAA,EACAG,gBAAAH,QAAA,2BAAA,EAGAI,YAAA,WAMC,SAAAA,YAAYC,GAFJC,KAAAC,MAAwB,GAG/BD,KAAKE,YAAcH,EACnBC,KAAKG,aAAe,IAAIR,OAAAS,eAExBJ,KAAKK,WAAU,CAChB,CA6QD,OA3QcP,YAAAQ,UAAAD,WAAb,W,qHAOC,OANIL,KAAKO,cAAgB,CAACP,KAAKO,aAAaC,SAC3CR,KAAKO,aAAaE,mBAAkB,EACpCT,KAAKO,aAAaG,MAAK,EACvBV,KAAKO,aAAe,MAGrB,CAAA,EAAM,IAAII,QAAQ,SAAAC,GAAW,OAAAC,WAAWD,EAAS,GAAI,CAAxB,CAAyB,G,cAAtDE,EAAAC,KAAA,EAEKf,KAAKO,cAAgBP,CAAAA,KAAKO,aAAaC,SAC3Cf,sBAAAuB,SAASC,KAAI,EAAGC,KAAK,SAAAC,GACpBC,EAAKnB,MAAQkB,EAEbC,EAAKnB,MAAMoB,QAAQ,SAAAC,GAClBF,EAAKG,WAAWD,CAAG,EACfA,EAAIE,SACP/B,sBAAAuB,SAASS,UAAU,CAACC,IAAKJ,EAAII,GAAG,EAAG,CAACC,KAAM,CAACH,Q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5EtF,EAAAC,KAAA,E,0DAKF8C,QAAQC,IAAI,IAAIjB,KAAQ,aAAciD,KAAKC,UAAUO,EAAK,KAAM,CAAC,CAAC,EAClEzB,EAAYS,MAAQQ,KAAKC,UAAUO,EAAK,KAAM,CAAC,EAC/CzB,EAAYQ,OAAS,CAAA,EAEjBlE,EAAI6D,QACHvB,EAAW,IAAIZ,KAAK7C,KAAKG,aAAauD,OAAOvC,EAAIuB,IAAI,EAAEe,SAAQ,EAAO,EAAC,EAC3EoB,EAAYa,UAAYjC,EACxBhE,sBAAAuB,SAASS,UAAU,CAACC,IAAKP,EAAIO,GAAG,EAAG,CAACC,KAAM,CAACH,QAAS,CAAA,EAAOmC,SAAUF,CAAQ,CAAC,CAAC,GAG/EhE,sBAAAuB,SAASgF,UAAU,CAACtE,IAAKP,EAAIO,GAAG,CAAC,E,sBAKlC6E,aAAaV,CAAa,E,YAGvB1E,EAAI6D,QACHvB,EAAW,IAAIZ,KAAK7C,KAAKG,aAAauD,OAAOvC,EAAIuB,IAAI,EAAEe,SAAQ,EAAO,EAAC,EAC3EoB,EAAYa,UAAYjC,EACxBhE,sBAAAuB,SAASS,UAAU,CAACC,IAAKP,EAAIO,GAAG,EAAG,CAACC,KAAM,CAACH,QAAS,CAAA,EAAOmC,SAAUF,CAAQ,CAAC,CAAC,GAG/EhE,sBAAAuB,SAASgF,UAAU,CAACtE,IAAKP,EAAIO,GAAG,CAAC,EAGlC9B,8BAAA+F,iBAAiBlE,UAAU,CAACC,IAAKmD,EAAYnD,GAAG,EAAG,CAACC,KAAM,CACzDyD,eAAgB,CAAA,EAChBC,OAAQR,EAAYQ,OACpBC,MAAOT,EAAYS,MACnBG,SAAU,IAAI5C,KACd6C,UAAWb,EAAYa,S,CACvB,CAAC,E,mCAED,YAAQ,CACZ,EACD5F,WAAA,EAAC,EAxRY0G,QAAA1G,YAAAA","file":"cron.manager.js","sourcesContent":["import { CronJobModel } from '../models/cron-job.model';\nimport { CronJobs } from '../collections/cron-job.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { CronJobManager } from '../cron/cron';\nimport * as moment from 'moment-timezone';\nimport { ChangeStream, ChangeStreamDocument } from 'mongodb';\nimport { CronJobHistories } from '../collections/cron-job-history.collection';\nimport { objectIdHexString } from '../managers/mongo.manager';\nimport { CronJobHistoryModel } from '../models/cron-job-history.model';\n\nexport class CronManager {\n\tprivate _cronManager: CronJobManager;\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _watchCrons$: ChangeStream;\n\tprivate _jobs: CronJobModel[] = [];\n\n\tconstructor(mainServer) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._cronManager = new CronJobManager();\n\n\t\tthis.watchCrons();\n\t}\n\n\tpublic async watchCrons() {\n\t\tif (this._watchCrons$ && !this._watchCrons$.closed) {\n\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\tthis._watchCrons$.close();\n\t\t\tthis._watchCrons$ = null;\n\t\t}\n\t\n\t\tawait new Promise(resolve => setTimeout(resolve, 1000));\n\t\n\t\tif (!this._watchCrons$ || this._watchCrons$.closed) {\t\t\t\n\t\t\tCronJobs.find().then(res => {\n\t\t\t\tthis._jobs = res;\n\n\t\t\t\tthis._jobs.forEach(job => {\n\t\t\t\t\tthis.addCronJob(job);\n\t\t\t\t\tif (job.running) {\n\t\t\t\t\t\tCronJobs.updateOne({_id: job._id}, {$set: {running: false}});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tthis._watchCrons$ = CronJobs.watchCollection([], {fullDocument: 'updateLookup'});\n\n\t\t\tthis._watchCrons$.on('change', async (doc: ChangeStreamDocument<CronJobModel>) => {\n\t\t\t\tif (doc.operationType === 'insert') {\n\t\t\t\t\tif (doc.fullDocument) {\n\t\t\t\t\t\tif (!this._jobs.some(a => a._id === <any>doc.documentKey['_id'])) {\n\t\t\t\t\t\t\tthis._jobs.push(doc.fullDocument);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (doc.operationType === 'replace' || doc.operationType === 'update') {\n\t\t\t\t\tif (doc.fullDocument) {\n\t\t\t\t\t\tlet oldDoc = this._jobs.find(a => a._id === <any>doc.documentKey['_id']);\n\t\t\t\t\t\tif (oldDoc) {\n\t\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1, doc.fullDocument);\n\n\t\t\t\t\t\t\tif (oldDoc.name !== doc.fullDocument.name) {\n\t\t\t\t\t\t\t\tthis.removeCronJob(oldDoc.name);\n\t\t\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (typeof oldDoc.time_to_run !== typeof doc.fullDocument.time_to_run || (typeof oldDoc.time_to_run === 'string' && oldDoc.time_to_run !== doc.fullDocument.time_to_run) ||\n\t\t\t\t\t\t\t\t(oldDoc.time_to_run instanceof Date && oldDoc.time_to_run.getTime() !== (<Date>doc.fullDocument.time_to_run).getTime()) || \n\t\t\t\t\t\t\t\toldDoc.timezone !== doc.fullDocument.timezone\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthis.updateCronJob(doc.fullDocument);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._jobs.push(doc.fullDocument);\n\t\t\t\t\t\t\tthis.addCronJob(doc.fullDocument);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (this._jobs.some(a => a._id === <any>doc.documentKey['_id'])) {\n\t\t\t\t\t\t\tlet job = this._jobs.find(a => a._id === <any>doc.documentKey['_id']);\n\t\t\t\t\t\t\tthis.removeCronJob(job.name);\n\t\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (doc.operationType === 'delete') {\n\t\t\t\t\tif (this._jobs.some(a => a._id === (<any>doc).documentKey['_id'])) {\n\t\t\t\t\t\tlet job = this._jobs.find(a => a._id === <any>doc.documentKey['_id']);\n\t\t\t\t\t\tthis.removeCronJob(job.name);\n\t\t\t\t\t\tthis._jobs.splice(this._jobs.map(a => a._id).indexOf(<any>doc.documentKey['_id']), 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', (err) => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$.close();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$.close();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis._watchCrons$.removeAllListeners();\n\t\t\t\tthis._watchCrons$ = null;\n\t\t\t\tthis.watchCrons();\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate doesCronJobExist(cron: CronJobModel) {\n\t\treturn this._cronManager.exists(cron.name);\n\t}\n\n\tprivate doesCronJobNameExist(cron_name: string) {\n\t\treturn this._cronManager.exists(cron_name);\n\t}\n\n\tprivate addCronJob(cron: CronJobModel) {\n\t\tif (!this.doesCronJobExist(cron)) {\n\t\t\ttry {\n\t\t\t\tthis._cronManager.add(\n\t\t\t\t\tcron.name,\n\t\t\t\t\tcron.time_to_run,\n\t\t\t\t\t() => this.runCronJob(cron),\n\t\t\t\t\tnull,\n\t\t\t\t\ttrue,\n\t\t\t\t\tcron.timezone,\n\t\t\t\t\tnull, \n\t\t\t\t\tfalse\n\t\t\t\t);\n\n\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(cron.name).nextDate()['ts']);\n\n\t\t\t\tif (cron.running || (nextDate && !cron.next_run || nextDate.getTime() !== cron.next_run.getTime())) {\n\t\t\t\t\tCronJobs.updateOne({_id: cron._id}, {$set: {running: false, next_run: nextDate || null}});\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(e) {\n\t\t\t\tconsole.log('Cron error', e);\n\n\t\t\t\tif (cron.time_to_run instanceof Date) {\n\t\t\t\t\tthis.runCronJob(cron);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate updateCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.update(cron.name, cron.time_to_run, () => this.runCronJob(cron), null, true, cron.timezone);\n\n\t\t\tlet nextDate = new Date(this._cronManager.getJob(cron.name).nextDate()['ts']);\n\n\t\t\tif (nextDate && (!cron.next_run || nextDate.getTime() !== cron.next_run.getTime())) {\n\t\t\t\tCronJobs.updateOne({_id: cron._id}, {$set: {next_run: nextDate}});\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate removeCronJob(cron_name: string) {\n\t\tif (this.doesCronJobNameExist(cron_name)) {\n\t\t\tthis._cronManager.delete(cron_name);\n\t\t}\n\t}\n\n\tprivate startCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.start(cron.name);\n\t\t}\n\t}\n\n\tprivate stopCronJob(cron: CronJobModel) {\n\t\tif (this.doesCronJobExist(cron)) {\n\t\t\tthis._cronManager.stop(cron.name);\n\t\t}\n\t}\n\n\tprivate stopAllCronJobs() {\n\t\tthis._cronManager.stopAll();\n\t}\n\n\tprivate runCronJob(cron: CronJobModel) {\n\t\tlet now = new Date();\n\n\t\tCronJobs.findOneAndUpdate({\n\t\t\t$and: [\n\t\t\t\t{_id: cron._id},\n\t\t\t\t{running: false},\n\t\t\t\t{\n\t\t\t\t\t$or: [\n\t\t\t\t\t\t{next_run: {$exists: false}},\n\t\t\t\t\t\t{next_run: null},\n\t\t\t\t\t\t{next_run: {$lte: now}}\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t]\n\t\t}, {$set: {running: true}}).then(async res => {\n\t\t\tif (res) {\n\t\t\t\tlet cronHistory: CronJobHistoryModel = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\tname: res.name,\n\t\t\t\t\treoccuring: res.repeat,\n\t\t\t\t\ttime_to_run: res.time_to_run,\n\t\t\t\t\tmethod_name: res.method_run,\n\t\t\t\t\tid_cronjob: res._id,\n\t\t\t\t\tserver_restart: true,\n\t\t\t\t\tpassed: true,\n\t\t\t\t\terror: '',\n\t\t\t\t\tdate_scheduled: res.next_run,\n\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\tdate_end: null,\n\t\t\t\t\tdate_next: null\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tawait CronJobHistories.create(cronHistory);\n\n\t\t\t\tlet timeoutHandle = setTimeout(async () => {\n\t\t\t\t\tconsole.log(new Date(), 'Cron Timeout', JSON.stringify(cron, null, 2));\n\n\t\t\t\t\tif (res.repeat) {\n\t\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t\t} \n\t\t\t\t\telse {\n\t\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t\t}\n\t\t\t\t}, 5 * 60 * 1000); // 5 minutes in milliseconds\n\n\t\t\t\ttry {\n\t\t\t\t\tif (res.method_run_data) {\n\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_run, res.method_run_data);\t\n\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_run);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (res.method_complete) {\n\t\t\t\t\t\tif (res.method_complete_data) {\n\t\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_complete, res.method_complete_data);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tawait this._mainServer.getMethodManager().callMethodCron(res.method_complete);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.log(new Date(), 'Cron Error', JSON.stringify(err, null, 2));\n\t\t\t\t\tcronHistory.error = JSON.stringify(err, null, 2);\n\t\t\t\t\tcronHistory.passed = false;\n\n\t\t\t\t\tif (res.repeat) {\n\t\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t\t} \n\t\t\t\t\telse {\n\t\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\t// Clear the timeout if the job completes or fails before the timeout\n\t\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\t}\n\n\t\t\t\tif (res.repeat) {\n\t\t\t\t\tlet nextDate = new Date(this._cronManager.getJob(res.name).nextDate()['ts']);\n\t\t\t\t\tcronHistory.date_next = nextDate;\n\t\t\t\t\tCronJobs.updateOne({_id: res._id}, {$set: {running: false, next_run: nextDate}});\n\t\t\t\t} \n\t\t\t\telse {\n\t\t\t\t\tCronJobs.deleteOne({_id: res._id});\n\t\t\t\t}\n\n\t\t\t\tCronJobHistories.updateOne({_id: cronHistory._id}, {$set: {\n\t\t\t\t\tserver_restart: false,\n\t\t\t\t\tpassed: cronHistory.passed,\n\t\t\t\t\terror: cronHistory.error,\n\t\t\t\t\tdate_end: new Date(),\n\t\t\t\t\tdate_next: cronHistory.date_next\n\t\t\t\t}});\n\t\t\t}\n\t\t}, () => {});\n\t}\n}"]}
@@ -2,6 +2,7 @@ import { MethodModel } from '../models/method.model';
2
2
  import ResolveIOMainServer from '../server-app';
3
3
  import { MonitorManagerFunction } from './monitor.manager';
4
4
  import { S3 } from '@aws-sdk/client-s3';
5
+ import * as WebSocket from 'ws';
5
6
  export declare class AWS {
6
7
  private _serverConfig;
7
8
  private _s3;
@@ -12,13 +13,12 @@ export declare class AWS {
12
13
  }
13
14
  export declare class MethodManager {
14
15
  private _mainServer;
16
+ private _websocketManager;
15
17
  _methods: MethodModel;
16
18
  private _mailer;
17
19
  private _aws;
18
20
  private serverConfig;
19
21
  private clientDir;
20
- private _sendQueue;
21
- private _runningQueue;
22
22
  private _monitorManagerFunction;
23
23
  private _isWorkersEnabled;
24
24
  private _isWorkerInstance;
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,r,n,i){return new(n=n||Promise)(function(o,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){var i,s,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,s=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(r,c)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var r,n=0,i=t.length;n<i;n++)!r&&n in t||((r=r||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),method_response_collection_1=require("../collections/method-response.collection"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),worker_task_request_collection_1=require("../collections/worker-task-request.collection"),worker_task_response_collection_1=require("../collections/worker-task-response.collection"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,o,r,n,i){var s=this;this._methods={},this._sendQueue=[],this._runningQueue=!1,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this.serverConfig=t,this.clientDir=o,this._monitorManagerFunction=r,this._isWorkersEnabled=n,this._isWorkerInstance=i,(0,init_1.loadServerInit)(),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){s._mainServer.getSubscriptionManager()&&s._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Length",s._sendQueue.length),console.log(new Date,"Method Manager","Send Queue Hits",s._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",s._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",s._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",s._debugCallMethodCronJobHits)),s._debugCallMethodInternalHits=0,s._debugCallMethodHits=0,s._debugCallMethodCronJobHits=0,s._debugSendQueueHits=0,s._debugSendQueueHits=0},6e4),setInterval(function(){if(!s._runningQueue&&s._sendQueue.length){s._runningQueue=!0;for(var e=s._sendQueue.length-1;0<=e;e--)!function(e){s._debugSendQueueHits+=1;var t,o=s._mainServer.getWS(s._sendQueue[e].id_ws);o&&o.readyState===o.OPEN?o.bufferedAmount<20480&&(t=s._sendQueue.pop(),o.send(JSON.stringify(t.data),function(e){e&&s._mainServer.unsubscribeWS(o)}),"reportBuilderGetResults"!==t.method&&"reportBuilderGetDistinctValue"!==t.method&&"reportBuilderBuildTree"!==t.method&&"generatePDF"!==t.method&&"getWOOfflineData"!==t.method&&"countQuery"!==t.method&&"countWithQuery"!==t.method&&"countCollectionWithQuery"!==t.method&&"find"!==t.method&&"findOne"!==t.method&&"findWithOptions"!==t.method&&"uploadFileAndSave"!==t.method&&"getDrivers"!==t.method&&"processAirdropDistribution"!==t.method&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([t.methodData,t.data]))<2e5?JSON.stringify([t.methodData,t.data],null,2):"Too Big",method:t.method,id_user:o.id_user||"",user:o.user||"",messageId:t.data.messageId,route:""}),method_response_collection_1.MethodResponses.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,id_user:o.id_user||"",message_id:t.data.messageId,response:(0,common_1.getBinarySize)(JSON.stringify(t.data))<2e5?t.data:{error:"Too Big"},method:t.method,date:t.date})):s._sendQueue.splice(e,1)}(e);s._runningQueue=!1}},1)}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<o.length||o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<o.length;a++)i[s[a]]=o[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c,l,d,h=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t?(c=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),l=(0,mongo_manager_1.objectIdHexString)(),h=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":l}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(c),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:l,method:t,params:o,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],o,!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(d),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(d),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),h}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(r,n,i,s,a){for(var c,e,l,d,t=this,h=[],o=5;o<arguments.length;o++)h[o-5]=arguments[o];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<h.length||h[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),u={messageId:s,hasError:!0,data:"Internal Error"},r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),void this.sendWS(n,i,a,h,u);for(var u,_={},g=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),m=0;m<h.length;m++)_[g[m]]=h[m];try{this._methods[a].check.validate(_)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(_,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}))}}this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==a&&"countQuery"!==a&&"incCounter"!==a&&"supportCreateBillingUser"!==a&&"find"!==a&&"insertDocument"!==a&&"countWithQuery"!==a&&"findOne"!==a&&"updateDocumentProps"!==a&&"findWithOptions"!==a&&"getSignedUrl"!==a&&"updateDocument"!==a&&"insertErrorLog"!==a&&"getSignedUrls"!==a&&"removeDocument"!==a&&"getSignedUrlWithId"!==a?(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),e=(0,mongo_manager_1.objectIdHexString)(),(l=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":e}}],{fullDocument:"updateLookup"})).on("change",function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==o.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(c),t=o.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(n,new Date,a,h,t),r?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:l.close(),e.label=3;case 3:return[2]}})})}),l.on("error",function(e){console.error("Error watching worker responses:",e),l.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:e,method:a,params:h,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],h,!1)).then(function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(d),t={messageId:s,hasError:!1,data:o},this.sendWS(n,i,a,h,t),r)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(d),t.sendWS(n,i,a,h,{messageId:s,hasError:!0,data:e}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(h,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),u={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(n,new Date,a,h,u),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r})},MethodManager.prototype.callMethodInternal=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<o.length||o[0]&&"function"!=typeof o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var i,s,a,c="function"==typeof o[o.length-1]?o.slice(0,-1):o,l=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),s=(0,mongo_manager_1.objectIdHexString)(),l=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:c,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(a=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),l=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],c,!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(a),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(a),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),o[o.length-1]&&"function"==typeof o[o.length-1]&&l.then(function(e){return o[o.length-1](null,e)},function(e){return o[o.length-1](e,null)}),l},MethodManager.prototype.sendWS=function(e,t,o,r,n){this._sendQueue.splice(0,0,{id_ws:e.id_socket,method:o,methodData:r,data:n,date:t})},MethodManager.prototype.sendEmail=function(r,n,i,s,a,c,l,d){var o=this;return void 0===d&&(d=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(r=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||r.match(new RegExp(/\@resolveio\.com/))?r:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||d?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:c||this.serverConfig.MAIL_FROM,to:r,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+n,text:i,html:s,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!0,verified:!1})}):console.log("Send email",r,n,i,s,a,c),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?r(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?r(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,r,n,i){return new(n=n||Promise)(function(o,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,r||[])).next())})},__generator=this&&this.__generator||function(r,n){var i,s,a,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,s=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))c.label=t[1];else if(6===t[0]&&c.label<a[1])c.label=a[1],a=t;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(t)}}t=n.call(r,c)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var r,n=0,i=t.length;n<i;n++)!r&&n in t||((r=r||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),method_response_collection_1=require("../collections/method-response.collection"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),worker_task_request_collection_1=require("../collections/worker-task-request.collection"),worker_task_response_collection_1=require("../collections/worker-task-response.collection"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,o,r,n,i){var s=this;this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this._websocketManager=this._mainServer.getWebSocketManager(),this.serverConfig=t,this.clientDir=o,this._monitorManagerFunction=r,this._isWorkersEnabled=n,this._isWorkerInstance=i,(0,init_1.loadServerInit)(),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){s._mainServer.getSubscriptionManager()&&s._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",s._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",s._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",s._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",s._debugCallMethodCronJobHits)),s._debugCallMethodInternalHits=0,s._debugCallMethodHits=0,s._debugCallMethodCronJobHits=0,s._debugSendQueueHits=0},6e4)}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<o.length||o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<o.length;a++)i[s[a]]=o[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var c,l,d,h=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(c=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),l=(0,mongo_manager_1.objectIdHexString)(),h=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":l}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(c),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:l,method:t,params:o,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",o),h=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],o,!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(d),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(d),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),h}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(r,n,i,s,a){for(var c,e,l,d,t=this,h=[],o=5;o<arguments.length;o++)h[o-5]=arguments[o];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<h.length||h[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Schema For Method "+a),u={messageId:s,hasError:!0,data:"Internal Error"},r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),void this.sendWS(n,i,a,h,u);for(var u,_={},g=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),m=0;m<h.length;m++)_[g[m]]=h[m];try{this._methods[a].check.validate(_)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(_,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(n,i,a,h,u={messageId:s,hasError:!0,data:"Internal Error"}),void(r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}))}}this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==a&&"countQuery"!==a&&"incCounter"!==a&&"supportCreateBillingUser"!==a&&"find"!==a&&"insertDocument"!==a&&"countWithQuery"!==a&&"findOne"!==a&&"updateDocumentProps"!==a&&"findWithOptions"!==a&&"getSignedUrl"!==a&&"updateDocument"!==a&&"insertErrorLog"!==a&&"getSignedUrls"!==a&&"removeDocument"!==a&&"getSignedUrlWithId"!==a&&"incorrectUser"!==a&&"reloadWS"!==a&&"reconnectWS"!==a&&"disconnectWS"!==a?(c=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),e=(0,mongo_manager_1.objectIdHexString)(),(l=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":e}}],{fullDocument:"updateLookup"})).on("change",function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"!==o.operationType?[3,3]:(this._monitorManagerFunction.finishMonitorFunction(c),t=o.fullDocument,t={messageId:s,hasError:t.has_error,data:t.data},this.sendWS(n,new Date,a,h,t),r?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2]);case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:l.close(),e.label=3;case 3:return[2]}})})}),l.on("error",function(e){console.error("Error watching worker responses:",e),l.close()}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:e,method:a,params:h,status:"pending",id_user:n.id_user,user:n.user,id_ws:n.id_socket})):(d=this._monitorManagerFunction.startMonitorFunction("Method",a,n.user||"",n.id_socket||"",h),(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:n.id_user,user:n.user,id_ws:n.id_socket})],h,!1)).then(function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(d),t={messageId:s,hasError:!1,data:o},this.sendWS(n,i,a,h,t),r)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(r)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:r},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(d),t.sendWS(n,i,a,h,{messageId:s,hasError:!0,data:e}),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(h,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}))}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),u={messageId:s,hasError:!0,data:"Internal Error"},this.sendWS(n,new Date,a,h,u),r&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:r})},MethodManager.prototype.callMethodInternal=function(t){for(var e,n=this,o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<o.length||o[0]&&"function"!=typeof o[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([o]))<2e5?JSON.stringify([o],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var i,s,a,c="function"==typeof o[o.length-1]?o.slice(0,-1):o,l=null;return this._isWorkersEnabled&&!this._isWorkerInstance&&"insertSubscriptionLog"!==t&&"countQuery"!==t&&"incCounter"!==t&&"supportCreateBillingUser"!==t&&"find"!==t&&"insertDocument"!==t&&"countWithQuery"!==t&&"findOne"!==t&&"updateDocumentProps"!==t&&"findWithOptions"!==t&&"getSignedUrl"!==t&&"updateDocument"!==t&&"insertErrorLog"!==t&&"getSignedUrls"!==t&&"removeDocument"!==t&&"getSignedUrlWithId"!==t&&"incorrectUser"!==t&&"reloadWS"!==t&&"reconnectWS"!==t&&"disconnectWS"!==t?(i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),s=(0,mongo_manager_1.objectIdHexString)(),l=new Promise(function(t,o){var r=worker_task_response_collection_1.WorkerTaskResponses.watchCollection([{$match:{"fullDocument.id_request":s}}],{fullDocument:"updateLookup"});r.on("change",function(e){"insert"===e.operationType&&(n._monitorManagerFunction.finishMonitorFunction(i),((e=e.fullDocument).has_error?o:t)(e.data),r.close())}),r.on("error",function(e){console.error("Error watching worker responses:",e),o(e),r.close()})}),worker_task_request_collection_1.WorkerTaskRequests.create({_id:s,method:t,params:c,status:"pending",id_user:this.id_user,user:this.user,id_ws:this.id_socket})):(a=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",c),l=(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype)],c,!1)).then(function(e){return n._monitorManagerFunction.finishMonitorFunction(a),e},function(e){return n._monitorManagerFunction.finishMonitorFunction(a),n.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+n.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(o,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})),o[o.length-1]&&"function"==typeof o[o.length-1]&&l.then(function(e){return o[o.length-1](null,e)},function(e){return o[o.length-1](e,null)}),l},MethodManager.prototype.sendWS=function(e,t,o,r,n){this._websocketManager.send(e,n),"reportBuilderGetResults"!==o&&"reportBuilderGetDistinctValue"!==o&&"reportBuilderBuildTree"!==o&&"generatePDF"!==o&&"getWOOfflineData"!==o&&"countQuery"!==o&&"countWithQuery"!==o&&"countCollectionWithQuery"!==o&&"find"!==o&&"findOne"!==o&&"findWithOptions"!==o&&"uploadFileAndSave"!==o&&"getDrivers"!==o&&"processAirdropDistribution"!==o&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([r,n]))<2e5?JSON.stringify([r,n],null,2):"Too Big",method:o,id_user:e.id_user||"",user:e.user||"",messageId:n.messageId,route:""}),method_response_collection_1.MethodResponses.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,id_user:e.id_user||"",message_id:n.messageId,response:(0,common_1.getBinarySize)(JSON.stringify(n))<2e5?n:{error:"Too Big"},method:o,date:t})},MethodManager.prototype.sendEmail=function(r,n,i,s,a,c,l,d){var o=this;return void 0===d&&(d=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(r=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||r.match(new RegExp(/\@resolveio\.com/))?r:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||d?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:c||this.serverConfig.MAIL_FROM,to:r,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+n,text:i,html:s,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:r,success:!0,verified:!1})}):console.log("Send email",r,n,i,s,a,c),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?r(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,r){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?r(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?r(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
2
2
  //# sourceMappingURL=method.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","method_response_collection_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","worker_task_request_collection_1","worker_task_response_collection_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_sendQueue","_runningQueue","_isWorkersEnabled","_isWorkerInstance","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_monitorManagerFunction","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","console","log","Date","length","i","sendItem","ws","getWS","id_ws","readyState","OPEN","bufferedAmount","pop","send","JSON","stringify","data","error","unsubscribeWS","method","Logs","insertOne","_id","objectIdHexString","type","collection","id_document","payload","getBinarySize","methodData","id_user","messageId","route","MethodResponses","create","__v","message_id","response","date","splice","getMainServer","methods","Object","assign","callMethodCron","_i","arguments","skipValidation","check","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","validate","errors","monitor_2","taskId_1","monitor_3","promise","startMonitorFunction","Promise","resolve","reject","changeStream","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","finishMonitorFunction","taskResponse","has_error","close","WorkerTaskRequests","params","status","_a","function","call","apply","__spreadArray","then","res","methodErrs","callMethod","id_methodLatency","messageDate","monitor_4","taskId","changeStream_1","monitor_5","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","monitor_6","taskId_2","monitor_7","functionMethodData","slice","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","email","success","verified","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"wqDACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,6BAAAd,QAAA,2CAAA,EACAe,SAAAf,QAAA,gBAAA,EACAgB,iBAAAhB,QAAA,+BAAA,EAEAiB,gCAAAjB,QAAA,8CAAA,EACAkB,OAAAlB,QAAA,iBAAA,EACAmB,iBAAAnB,QAAA,2BAAA,EACAoB,UAAApB,QAAA,oBAAA,EACAqB,UAAArB,QAAA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,GACrExO,GAAGuO,SAASxO,KAAK2O,KAAK1L,EAAKJ,UAAY,aAAe4L,CAAS,EAAG,QAAS,SAAC9B,EAAKxB,GAC5EwB,EACH/C,EAAO+C,CAAG,EAGVhD,EAAQwB,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EAEOzI,cAAAd,UAAAiN,UAAP,SAAiBJ,GAAjB,IAAAxL,EAAAzB,KACC,OAAO,IAAIkI,QAAQ,SAACC,EAASC,GACxB3J,GAAGyO,WAAW1O,KAAK2O,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjExO,GAAGuO,SAASxO,KAAK2O,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAAC9B,EAAKxB,GACzEwB,EACH/C,EAAO+C,CAAG,EAGVhD,EAAQwB,CAAG,CAEb,CAAC,EAGGlL,GAAGyO,WAAW1O,KAAK2O,KAAK1L,EAAKJ,UAAY,aAAe4L,CAAS,CAAC,GACrExO,GAAGuO,SAASxO,KAAK2O,KAAK1L,EAAKJ,UAAY,aAAe4L,CAAS,EAAG,SAAU,SAAC9B,EAAKxB,GAC7EwB,EACH/C,EAAO+C,CAAG,EAGVhD,EAAQwB,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACDzI,aAAA,EAAC,GAtuBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { MethodResponses } from '../collections/method-response.collection';\nimport { getBinarySize } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport * as moment from 'moment-timezone';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { objectIdHexString } from './mongo.manager';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WorkerTaskRequests } from '../collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from '../collections/worker-task-response.collection';\n\nexport class AWS {\n\tprivate _serverConfig = null;\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor(serverConfig) {\n\t\tthis._serverConfig = serverConfig;\n\t}\n\n\tpublic s3() : S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1() : S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _mainServer: ResolveIOMainServer;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _sendQueue = [];\n\tprivate _runningQueue = false;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _debugCallMethodInternalHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tconstructor(mainServer, serverConfig, clientDir, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._mainServer = mainServer;\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.clientDir = clientDir;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\n\t\t// Fixtures\n\t\tloadServerInit();\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(serverConfig);\n\n\t\tif (mainServer.sesMail) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: this.serverConfig['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: this.serverConfig['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: this.serverConfig['MAIL_USERNAME'],\n\t\t\t\t\tpass: this.serverConfig['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsetInterval(() => {\n\t\t\tif (this._mainServer.getSubscriptionManager() && this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Length', this._sendQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._runningQueue) {\n\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tthis._mainServer.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\tif (sendItem.method !== 'reportBuilderGetResults' && sendItem.method !== 'reportBuilderGetDistinctValue' && sendItem.method !== 'reportBuilderBuildTree' && sendItem.method !== 'generatePDF' && sendItem.method !== 'getWOOfflineData' && sendItem.method !== 'countQuery' && sendItem.method !== 'countWithQuery' && sendItem.method !== 'countCollectionWithQuery' && sendItem.method !== 'find' && sendItem.method !== 'findOne' && sendItem.method !== 'findWithOptions' && sendItem.method !== 'uploadFileAndSave' && sendItem.method !== 'getDrivers' && sendItem.method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([sendItem.methodData, sendItem.data])) < 200000 ? JSON.stringify([sendItem.methodData, sendItem.data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\t\tmessageId: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\troute: ''\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tMethodResponses.create({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tmessage_id: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\tresponse: getBinarySize(JSON.stringify(sendItem.data)) < 200000 ? sendItem.data : {error: 'Too Big'},\n\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\tdate: sendItem.date\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tthis._runningQueue = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 1);\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet promise = null;\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId'\n\t\t) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\t\t\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\t// changeStream.on('close', () => {\n\t\t\t\t// \tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t// });\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t}, methodErrs => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\treturn methodErrs;\n\t\t\t});\n\t\t}\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\t\t\t\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId'\n\t\t) {\t\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\t\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\t\t\t// console.log('Workers are enabled. Delegating task to worker.', taskId);\n\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\tchangeStream.on('change', async (change) => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t// console.log('Task response found', taskId, taskResponse.data);\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\t\n\t\t\t\t\t\tif (latency) {\n\t\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log('Sent on WS', ws['id_socket'], new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\tchangeStream.close();\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: ws['id_user'],\n\t\t\t\tuser: ws['user'],\n\t\t\t\tid_ws: ws['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, err => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: err\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof(methodData[0]) !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution') {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'callMethodInternal',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\tuser: this['user'] || '',\n\t\t\t\tmessageId: 0,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\t\tlet promise = null;\n\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId'\n\t\t) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', (error) => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\n\t\t\t\t// changeStream.on('close', () => {\n\t\t\t\t// \tconsole.log('Change stream closed for task:', taskId);\n\t\t\t\t// });\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: functionMethodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\treturn res;\n\t\t\t\t}, methodErrs => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\t\treturn methodErrs;\n\t\t\t\t});\n\t\t}\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tmethod: method,\n\t\t\tmethodData: methodData,\n\t\t\tdata: data,\n\t\t\tdate: messageDate\n\t\t});\n\t}\n\n\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + subject,\n\t\t\t\t\t\ttext: text,\n\t\t\t\t\t\thtml: html,\n\t\t\t\t\t\tattachments: attachments\n\t\t\t\t\t}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","method_response_collection_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","worker_task_request_collection_1","worker_task_response_collection_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","_this","_methods","_isWorkersEnabled","_isWorkerInstance","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_websocketManager","getWebSocketManager","_monitorManagerFunction","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","console","log","Date","getMainServer","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","skipValidation","check","error","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","i","validate","errors","JSON","stringify","monitor_2","taskId_1","monitor_3","promise","startMonitorFunction","objectIdHexString","Promise","resolve","reject","changeStream","WorkerTaskResponses","watchCollection","$match","fullDocument.id_request","fullDocument","on","change","operationType","finishMonitorFunction","taskResponse","has_error","data","close","WorkerTaskRequests","create","_id","params","status","id_user","id_ws","_a","function","call","apply","__spreadArray","then","res","methodErrs","callMethod","id_methodLatency","ws","messageDate","messageId","monitor_4","taskId","changeStream_1","monitor_5","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","Logs","insertOne","type","collection","id_document","payload","getBinarySize","route","monitor_6","taskId_2","monitor_7","functionMethodData","slice","send","MethodResponses","__v","message_id","response","date","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","email","success","verified","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"wqDACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,6BAAAd,QAAA,2CAAA,EACAe,SAAAf,QAAA,gBAAA,EACAgB,iBAAAhB,QAAA,+BAAA,EAEAiB,gCAAAjB,QAAA,8CAAA,EACAkB,OAAAlB,QAAA,iBAAA,EACAmB,iBAAAnB,QAAA,2B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qG,QAAQ,SAACC,EAASC,GACxB9H,GAAGiO,WAAWlO,KAAKmO,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjEhO,GAAG+N,SAAShO,KAAKmO,KAAKC,UAAY,cAAgBH,CAAS,EAAG,QAAS,SAAC5C,EAAK1B,GACxE0B,EACHtD,EAAOsD,CAAG,EAGVvD,EAAQ6B,CAAG,CAEb,CAAC,EAGG1J,GAAGiO,WAAWlO,KAAKmO,KAAKlL,EAAKJ,UAAY,aAAeoL,CAAS,CAAC,GACrEhO,GAAG+N,SAAShO,KAAKmO,KAAKlL,EAAKJ,UAAY,aAAeoL,CAAS,EAAG,QAAS,SAAC5C,EAAK1B,GAC5E0B,EACHtD,EAAOsD,CAAG,EAGVvD,EAAQ6B,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EAEOjH,cAAAd,UAAAyM,UAAP,SAAiBJ,GAAjB,IAAAhL,EAAAzB,KACC,OAAO,IAAIqG,QAAQ,SAACC,EAASC,GACxB9H,GAAGiO,WAAWlO,KAAKmO,KAAKC,UAAY,cAAgBH,CAAS,CAAC,EACjEhO,GAAG+N,SAAShO,KAAKmO,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAAC5C,EAAK1B,GACzE0B,EACHtD,EAAOsD,CAAG,EAGVvD,EAAQ6B,CAAG,CAEb,CAAC,EAGG1J,GAAGiO,WAAWlO,KAAKmO,KAAKlL,EAAKJ,UAAY,aAAeoL,CAAS,CAAC,GACrEhO,GAAG+N,SAAShO,KAAKmO,KAAKlL,EAAKJ,UAAY,aAAeoL,CAAS,EAAG,SAAU,SAAC5C,EAAK1B,GAC7E0B,EACHtD,EAAOsD,CAAG,EAGVvD,EAAQ6B,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACDjH,aAAA,EAAC,GArtBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { MethodResponses } from '../collections/method-response.collection';\nimport { getBinarySize } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport * as moment from 'moment-timezone';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { objectIdHexString } from './mongo.manager';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\nimport { WorkerTaskRequests } from '../collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from '../collections/worker-task-response.collection';\nimport { WebSocketManager } from './websocket.manager';\nimport * as WebSocket from 'ws';\n\nexport class AWS {\n\tprivate _serverConfig = null;\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor(serverConfig) {\n\t\tthis._serverConfig = serverConfig;\n\t}\n\n\tpublic s3(): S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1(): S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _mainServer: ResolveIOMainServer;\n\tprivate _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _debugCallMethodInternalHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tconstructor(mainServer, serverConfig, clientDir, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._mainServer = mainServer;\n\t\tthis._websocketManager = this._mainServer.getWebSocketManager();\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.clientDir = clientDir;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\n\t\t// Fixtures\n\t\tloadServerInit();\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(serverConfig);\n\n\t\tif (mainServer.sesMail) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: this.serverConfig['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: this.serverConfig['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: this.serverConfig['MAIL_USERNAME'],\n\t\t\t\t\tpass: this.serverConfig['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsetInterval(() => {\n\t\t\tif (this._mainServer.getSubscriptionManager() && this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet promise = null;\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', change => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', error => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t\t.then(res => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\treturn res;\n\t\t\t}, methodErrs => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\treturn methodErrs;\n\t\t\t});\n\t\t}\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Schema For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t}\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({ _id: id_methodLatency });\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if workers are enabled and this is not a worker instance\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\t\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\t\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\tchangeStream.on('change', async change => {\n\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\thasError: taskResponse.has_error,\n\t\t\t\t\t\tdata: taskResponse.data\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.sendWS(ws, new Date(), method, methodData, serverRes);\n\n\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\t\tif (latency) {\n\t\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchangeStream.on('error', error => {\n\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\tchangeStream.close();\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: methodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: ws['id_user'],\n\t\t\t\tuser: ws['user'],\n\t\t\t\tid_ws: ws['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t\t.then(async (res) => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: res\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\t\tif (latency) {\n\t\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\terr => {\n\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: err\n\t\t\t\t};\n\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution') {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'callMethodInternal',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\tuser: this['user'] || '',\n\t\t\t\tmessageId: 0,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\t\tlet promise = null;\n\n\t\tif (this._isWorkersEnabled && \n\t\t\t!this._isWorkerInstance && \n\t\t\tmethod !== 'insertSubscriptionLog' && \n\t\t\tmethod !== 'countQuery' && method !== 'incCounter' && \n\t\t\tmethod !== 'supportCreateBillingUser' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'insertDocument' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'updateDocumentProps' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'getSignedUrl' &&\n\t\t\tmethod !== 'updateDocument' &&\n\t\t\tmethod !== 'insertErrorLog' &&\n\t\t\tmethod !== 'getSignedUrls' &&\n\t\t\tmethod !== 'removeDocument' &&\n\t\t\tmethod !== 'getSignedUrlWithId' &&\n\t\t\tmethod !== 'incorrectUser' &&\n\t\t\tmethod !== 'reloadWS' &&\n\t\t\tmethod !== 'reconnectWS' &&\n\t\t\tmethod !== 'disconnectWS'\n\t\t) {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\n\t\t\t// Push task to worker-task-reqs collection\n\t\t\tconst taskId = objectIdHexString();\n\n\t\t\t// Watch worker-task-resps for result\n\t\t\tpromise = new Promise((resolve, reject) => {\n\t\t\t\tlet changeStream = WorkerTaskResponses.watchCollection([{ $match: { 'fullDocument.id_request': taskId } }], { fullDocument: 'updateLookup' });\n\n\t\t\t\tchangeStream.on('change', (change) => {\n\t\t\t\t\tif (change.operationType === 'insert') {\n\t\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\t\t\t\tconst taskResponse = change.fullDocument;\n\n\t\t\t\t\t\tif (taskResponse.has_error) {\n\t\t\t\t\t\t\treject(taskResponse.data); // Task failed, return error\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(taskResponse.data); // Task succeeded, return result\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchangeStream.close(); // Close the cursor after receiving response\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tchangeStream.on('error', error => {\n\t\t\t\t\tconsole.error('Error watching worker responses:', error);\n\t\t\t\t\treject(error);\n\t\t\t\t\tchangeStream.close();\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tWorkerTaskRequests.create({\n\t\t\t\t_id: taskId,\n\t\t\t\tmethod: method,\n\t\t\t\tparams: functionMethodData,\n\t\t\t\tstatus: 'pending',\n\t\t\t\tid_user: this['id_user'],\n\t\t\t\tuser: this['user'],\n\t\t\t\tid_ws: this['id_socket']\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\t\tpromise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t\t\t.then(res => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\treturn res;\n\t\t\t\t},\n\t\t\t\tmethodErrs => {\n\t\t\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\t\t\treturn methodErrs;\n\t\t\t\t});\n\t\t}\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._websocketManager.send(ws, data);\n\n\t\tif (\n\t\t\tmethod !== 'reportBuilderGetResults' &&\n\t\t\tmethod !== 'reportBuilderGetDistinctValue' &&\n\t\t\tmethod !== 'reportBuilderBuildTree' &&\n\t\t\tmethod !== 'generatePDF' &&\n\t\t\tmethod !== 'getWOOfflineData' &&\n\t\t\tmethod !== 'countQuery' &&\n\t\t\tmethod !== 'countWithQuery' &&\n\t\t\tmethod !== 'countCollectionWithQuery' &&\n\t\t\tmethod !== 'find' &&\n\t\t\tmethod !== 'findOne' &&\n\t\t\tmethod !== 'findWithOptions' &&\n\t\t\tmethod !== 'uploadFileAndSave' &&\n\t\t\tmethod !== 'getDrivers' &&\n\t\t\tmethod !== 'processAirdropDistribution'\n\t\t) {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'client-response',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload:\n\t\t\t\t\tgetBinarySize(JSON.stringify([methodData, data])) < 200000\n\t\t\t\t\t\t? JSON.stringify([methodData, data], null, 2)\n\t\t\t\t\t\t: 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\tuser: ws['user'] || '',\n\t\t\t\tmessageId: data.messageId,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\tMethodResponses.create({\n\t\t\t_id: objectIdHexString(),\n\t\t\t__v: 0,\n\t\t\tid_user: ws['id_user'] || '',\n\t\t\tmessage_id: data.messageId,\n\t\t\tresponse: getBinarySize(JSON.stringify(data)) < 200000 ? data : { error: 'Too Big' },\n\t\t\tmethod: method,\n\t\t\tdate: messageDate\n\t\t});\n\t}\n\n\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + subject,\n\t\t\t\t\t\ttext: text,\n\t\t\t\t\t\thtml: html,\n\t\t\t\t\t\tattachments: attachments\n\t\t\t\t\t}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}