@resolveio/server-lib 20.7.106 → 20.7.108

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 __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,n,s){return new(n=n||Promise)(function(r,t){function fulfilled(e){try{step(s.next(e))}catch(e){t(e)}}function rejected(e){try{step(s.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var s,i,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(r){return function(e){var t=[r,e];if(s)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(s=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=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++,i=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(o,c)}catch(e){t=[6,e],i=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,s=r.call(e),i=[];try{for(;(void 0===t||0<t--)&&!(o=s.next()).done;)i.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,s=t.length;n<s;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},client_s3_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("@aws-sdk/client-s3")),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),path=require("path"),email_history_collection_1=require("../collections/email-history.collection"),log_collection_1=require("../collections/log.collection"),cron_jobs_1=require("../fixtures/cron-jobs"),init_1=require("../fixtures/init"),accounts_1=require("../methods/accounts"),aws_1=require("../methods/aws"),collections_1=require("../methods/collections"),counters_1=require("../methods/counters"),cron_jobs_2=require("../methods/cron-jobs"),flag_updates_1=require("../methods/flag-updates"),flags_1=require("../methods/flags"),logs_1=require("../methods/logs"),monitor_1=require("../methods/monitor"),pdf_1=require("../methods/pdf"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),resolveio_server_app_1=require("../resolveio-server-app"),common_1=require("../util/common"),AWS=function(){function AWS(){this._s3=null,this._s3USEast1=null}return AWS.prototype.create=function(){var e=new AWS;return e.initialize(),e},AWS.prototype.initialize=function(){},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(){this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugcallMethodHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this.clientDir="",this.serverConfig=""}return MethodManager.create=function(e,t,r,o){var n=new MethodManager;return n.initialize(e,t,r,o),n},MethodManager.prototype.initialize=function(e,t,r,o){var n=this;this._websocketManager=e,this._monitorManagerFunction=t,this._isWorkersEnabled=r,this._isWorkerInstance=o,this.clientDir=resolveio_server_app_1.ResolveIOServer.getClientDir(),this.serverConfig=resolveio_server_app_1.ResolveIOServer.getServerConfig(),process.env.IS_WORKERS_ENABLED&&"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.log(new Date,"Start Server Fixture"),[4,(0,init_1.loadServerInit)()];case 1:return e.sent(),console.log(new Date,"End Server Fixture"),[2]}})})},5e3),setImmediate(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,(0,cron_jobs_1.loadServerCronJobs)()];case 1:return e.sent(),(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,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),[2]}})})}),this._aws=new AWS,resolveio_server_app_1.ResolveIOServer.getSESMail()?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:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_HOST,port:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PORT,secure:!1,auth:{user:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_USERNAME,pass:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",n._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",n._debugcallMethodHits),console.log(new Date,"Method Manager","Call Method Hits",n._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",n._debugCallMethodCronJobHits)),n._debugcallMethodHits=0,n._debugCallMethodHits=0,n._debugCallMethodCronJobHits=0,n._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||setImmediate(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.setupEmailWatcher()];case 1:return e.sent(),[2]}})})})},MethodManager.prototype.getMethod=function(e){return this._methods[e]},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(c){for(var l=[],e=1;e<arguments.length;e++)l[e-1]=arguments[e];return __awaiter(this,void 0,void 0,function(){var t,r,o,n,s,i,a;return __generator(this,function(e){switch(e.label){case 0:return(this._debugCallMethodCronJobHits+=1,this._methods[c])?[3,2]:(console.log("No Method: "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Method: "+c)]);case 1:throw e.sent(),new Error("No Method: "+c);case 2:return!(1<l.length||l[0])||this._methods[c].skipValidation?[3,10]:this._methods[c].check?[3,4]:(console.error(new Date,"No Check Function For Cron Method "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Cron Method "+c)]);case 3:throw e.sent(),new Error("No Check Function For Cron Method "+c);case 4:return this._methods[c].check._schema?[3,6]:(console.error(new Date,"No Check Schema For Cron Method "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Cron Method "+c)]);case 5:throw e.sent(),new Error("No Check Schema For Cron Method "+c);case 6:for(t={},a=Object.keys(this._methods[c].check._schema),r=a.filter(function(e){return!e.includes(".")}),o=0;o<l.length;o++)t[r[o]]=l[o];e.label=7;case 7:return e.trys.push([7,8,,10]),this._methods[c].check.validate(t),[3,10];case 8:return n=e.sent(),console.error(new Date,"Error in Cron Method Check ("+c+")",n),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Match Error On Cron Method "+c+"\n\nData Being Checked\n"+JSON.stringify(t,null,2)+"\n\nErrors\n"+JSON.stringify(n,null,2))];case 9:throw e.sent(),n.message="".concat((new Date).toISOString()," - Error in Cron Method Check (").concat(c,"): ").concat(n.message),n;case 10:s=this._monitorManagerFunction.startMonitorFunction("Cron Method",c,"","",l),e.label=11;case 11:return e.trys.push([11,13,15,17]),[4,(a=this._methods[c].function).call.apply(a,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(l),!1))];case 12:return[2,e.sent()];case 13:return i=e.sent(),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Cron Method "+c+" - (callMethodCron)\n\nData \n"+JSON.stringify(l,null,2)+"\n\nErrors\n"+JSON.stringify(i,null,2))];case 14:throw e.sent(),i.message="".concat((new Date).toISOString()," - Error in Cron Method (").concat(c,"): ").concat(i.message),i;case 15:return[4,this._monitorManagerFunction.finishMonitorFunction(s)];case 16:return e.sent(),[7];case 17:return[2]}})})},MethodManager.prototype.callMethod=function(l){for(var u=[],e=1;e<arguments.length;e++)u[e-1]=arguments[e];return __awaiter(this,void 0,void 0,function(){var o,n,s,t,r,i,a,c=this;return __generator(this,function(e){switch(e.label){case 0:if(this._debugcallMethodHits+=1,!(o=this.getMethod(l)))throw console.log("No Method: "+l),new Error("No Method: ".concat(l));if((1<u.length||u[0]&&"function"!=typeof u[0])&&!o.skipValidation){if(!o.check)throw console.error(new Date,"No Check Function For Method "+l),new Error("No Check Function For Method: ".concat(l));if(!o.check._schema)throw console.error(new Date,"No Check Schema For Method "+l),new Error("No Check Schema For Method: ".concat(l))}return"insertSubscriptionLog"===l||"getDataURIfromURL"===l||"processAirdropDistribution"===l||"incCounter"===l||"supportCreateBillingUser"===l||"countCollectionWithQuery"===l?[3,4]:"https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?[3,1]:(resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([u]))<1e6?JSON.stringify([u],null,2):"Too Big",methodName:l,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""}}),[3,3]);case 1:return[4,log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([u]))<1e6?JSON.stringify([u],null,2):"Too Big",method:l,id_user:this.id_user||"",user:this.user||"",messageId:0,route:"",client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 2:e.sent(),e.label=3;case 3:e.label=4;case 4:return(n="function"==typeof u[u.length-1]?u.slice(0,-1):u,a=resolveio_server_app_1.ResolveIOServer.getMongoManager().getSession(),o.bypassSession||a||["insertErrorLog","countWithQuery","sendEmail"].includes(l)||l.startsWith("monitor-")||l.startsWith("log"))?[3,5]:(s=null,[2,resolveio_server_app_1.ResolveIOServer.getMongoManager().oneTimeTransaction(function(){return __awaiter(c,void 0,void 0,function(){var t,r;return __generator(this,function(e){switch(e.label){case 0:s=this._monitorManagerFunction.startMonitorFunction("Method",l,this.user||"","",n),e.label=1;case 1:return e.trys.push([1,3,7,9]),[4,(r=o.function).call.apply(r,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(n),!1))];case 2:return r=e.sent(),u[u.length-1]&&"function"==typeof u[u.length-1]&&u[u.length-1](null,r),[2,r];case 3:if(112===(t=e.sent()).code||"WriteConflict"===t.codeName)throw t;return console.log(JSON.stringify([new Date,"Error Method Manager - Run Method - New Session",l,{code:t.code,codeName:t.codeName,message:t.message,stack:t.stack}],null,2)),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+l+" - (callMethod)\n\nData \n"+JSON.stringify(u,null,2)+"\n\nErrors\n"+JSON.stringify(t,null,2))];case 4:return e.sent(),t.message="".concat((new Date).toISOString()," - Error in Method With Session (").concat(l,") - New Session: ").concat(t.message),u[u.length-1]&&"function"==typeof u[u.length-1]&&u[u.length-1](t,null),process.env.IS_WORKER_INSTANCE?[3,6]:[4,this.callMethod("insertErrorLog","Error in Method: ".concat(l," - ").concat(JSON.stringify(u,null,2)))];case 5:e.sent(),e.label=6;case 6:throw t;case 7:return[4,this._monitorManagerFunction.finishMonitorFunction(s)];case 8:return e.sent(),[7];case 9:return[2]}})})})]);case 5:t=this._monitorManagerFunction.startMonitorFunction("Method",l,this.user||"","",n),e.label=6;case 6:return e.trys.push([6,8,12,14]),[4,(a=o.function).call.apply(a,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(n),!1))];case 7:return r=e.sent(),u[u.length-1]&&"function"==typeof u[u.length-1]&&u[u.length-1](null,r),[2,r];case 8:if(112===(i=e.sent()).code||"WriteConflict"===i.codeName)throw i;return console.log(JSON.stringify([new Date,"Error Method Manager - Run Method - Existing Session",l,{code:i.code,codeName:i.codeName,message:i.message,stack:i.stack}],null,2)),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+l+" - (callMethod)\n\nData \n"+JSON.stringify(u,null,2)+"\n\nErrors\n"+JSON.stringify(i,null,2))];case 9:return e.sent(),i.message="".concat((new Date).toISOString()," - Error in Method (").concat(l,") - Existing Session: ").concat(i.message),u[u.length-1]&&"function"==typeof u[u.length-1]&&u[u.length-1](i,null),process.env.IS_WORKER_INSTANCE?[3,11]:[4,this.callMethod("insertErrorLog","Error in Method: ".concat(l," - ").concat(JSON.stringify(u,null,2)))];case 10:e.sent(),e.label=11;case 11:throw i;case 12:return[4,this._monitorManagerFunction.finishMonitorFunction(t)];case 13:return e.sent(),[7];case 14:return[2]}})})},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var r,o=this;return __generator(this,function(e){switch(e.label){case 0:return(r=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(o,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),[4,this.tryProcessEmail()]):[3,2];case 1:return e.sent(),[3,3];case 2:"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),e.label=3;case 3:return[2]}})})}).on("error",function(t){return __awaiter(o,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.error("Email history changestream error",t),[4,r.close()];case 1:return e.sent(),[2]}})})}).on("close",function(){return __awaiter(o,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.setupEmailWatcher()];case 1:return e.sent(),[2]}})})}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,o,n,s,i;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),o=r.next();!o.done;o=r.next())n=o.value,this.emailQueue.add(n._id.toString())}catch(e){s={error:e}}finally{try{o&&!o.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return[4,this.tryProcessEmail()];case 2:return e.sent(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,u,r,h=this;return __generator(this,function(e){switch(e.label){case 0:if(this.isEmailProcessing||0===this.emailQueue.size)return[2];this.isEmailProcessing=!0,e.label=1;case 1:e.trys.push([1,5,6,9]),t=function(){var o,t,r,n,s,i,a,c,l;return __generator(this,function(e){switch(e.label){case 0:return s=u.emailQueue.values().next().value,u.emailQueue.delete(s),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:s,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:if(!(o=e.sent()))return[2,"continue"];if(!(o.attachments&&0<o.attachments.length))return[3,14];e.label=2;case 2:e.trys.push([2,12,,14]),e.label=3;case 3:e.trys.push([3,9,10,11]),c=void 0,t=__values(o.attachments),r=t.next(),e.label=4;case 4:return r.done?[3,8]:(n=r.value).path&&n.path.startsWith("http")?[4,fetch(n.path)]:[3,7];case 5:if((s=e.sent()).ok)return[4,s.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(n.path));case 6:i=e.sent(),i=Buffer.from(i),i.length<=20971520&&(n.content=i,delete n.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return i=e.sent(),c={error:i},[3,11];case 10:try{r&&!r.done&&(l=t.return)&&l.call(t)}finally{if(c)throw c.error}return[7];case 11:return[3,14];case 12:return a=e.sent(),console.error("Failed to fetch attachment:",a),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof a?a:u.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(a={replyTo:o.reply_to||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_REPLY_TO||void 0,from:o.send_from||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_FROM,to:o.email,subject:(resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)||resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+o.subject,text:"string"==typeof o.text?o.text:"",html:"string"==typeof o.html?o.html:"",attachments:o.attachments||[]}).attachments&&0<a.attachments.length&&(a.attachments=a.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),u._mailer.sendMail(a,function(r){return __awaiter(h,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(e.trys.push([0,7,,9]),r)?(console.error("Failed to send email:",r),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof r?r:this.safeStringify(r),completedAt:new Date}})]):[3,2];case 1:return e.sent(),[3,6];case 2:return"dev@resolveio.com"!==o.email?[3,4]:[4,email_history_collection_1.EmailHistories.deleteOne({_id:o._id})];case 3:return e.sent(),[3,6];case 4:return[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"completed",completedAt:new Date}})];case 5:e.sent(),e.label=6;case 6:return[3,9];case 7:return t=e.sent(),console.error("Error in sendMail callback:",t),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})];case 8:return e.sent(),[3,9];case 9:return[2]}})})}),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 15:return e.sent(),[2]}})},u=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,9];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,9];case 6:return(this.isEmailProcessing=!1,0<this.emailQueue.size)?[4,this.tryProcessEmail()]:[3,8];case 7:e.sent(),e.label=8;case 8:return[7];case 9:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(o,n,s,i,a,c,l,u){return void 0===u&&(u=!1),__awaiter(this,void 0,void 0,function(){var t,r;return __generator(this,function(e){switch(e.label){case 0:if(!(o=!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)&&!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||o.match(/\@resolveio\.com/)?o:"dev@resolveio.com"))return[3,7];if("http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&!u)return[3,5];a=a||[],a=(a=Array.isArray(a)?a:[a]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:o,subject:n||"",text:s||"",html:i||"",attachments:a||[],send_from:c||"",reply_to:l||"",status:"pending",error:""},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,email_history_collection_1.EmailHistories.insertOne(t)];case 2:return[2,e.sent()];case 3:throw r=e.sent(),console.error("Failed to queue email:",r),r.message="Failed to queue email: ".concat(r.message),r;case 4:return[3,6];case 5:return console.log("Send email",o,n,s,i,a,c),[2,!0];case 6:return[3,8];case 7:return[2,!0];case 8:return[2]}})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){if(fs.existsSync(path.join(__dirname,"../private/"+e)))try{return fs.readFileSync(path.join(__dirname,"../private/"+e),"utf-8")}catch(e){throw e.message="Error in readFile: ".concat(e.message),e}else if(fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e)))try{return fs.readFileSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"utf-8")}catch(e){throw e.message="Error in readFile: ".concat(e.message),e}throw new Error("Error in readFile: File Not Found")},MethodManager.prototype.readImage=function(e){if(fs.existsSync(path.join(__dirname,"../private/"+e)))try{return fs.readFileSync(path.join(__dirname,"../private/"+e),"base64")}catch(e){throw e.message="Error in readImage: ".concat(e.message),e}else if(fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e)))try{return fs.readFileSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"base64")}catch(e){throw e.message="Error in readImage: ".concat(e.message),e}throw new Error("Error in readImage: File Not Found")},MethodManager}());exports.MethodManager=MethodManager;
1
+ "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,n,s){return new(n=n||Promise)(function(r,t){function fulfilled(e){try{step(s.next(e))}catch(e){t(e)}}function rejected(e){try{step(s.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?r(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(fulfilled,rejected)}step((s=s.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,n){var s,i,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(r){return function(e){var t=[r,e];if(s)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(s=1,i&&(a=2&t[0]?i.return:t[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,t[1])).done)return a;switch(i=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++,i=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(o,c)}catch(e){t=[6,e],i=0}finally{s=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,s=r.call(e),i=[];try{for(;(void 0===t||0<t--)&&!(o=s.next()).done;)i.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,s=t.length;n<s;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},client_s3_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("@aws-sdk/client-s3")),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),path=require("path"),email_history_collection_1=require("../collections/email-history.collection"),log_collection_1=require("../collections/log.collection"),cron_jobs_1=require("../fixtures/cron-jobs"),init_1=require("../fixtures/init"),accounts_1=require("../methods/accounts"),aws_1=require("../methods/aws"),collections_1=require("../methods/collections"),counters_1=require("../methods/counters"),cron_jobs_2=require("../methods/cron-jobs"),flag_updates_1=require("../methods/flag-updates"),flags_1=require("../methods/flags"),logs_1=require("../methods/logs"),monitor_1=require("../methods/monitor"),pdf_1=require("../methods/pdf"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),resolveio_server_app_1=require("../resolveio-server-app"),common_1=require("../util/common"),AWS=function(){function AWS(){this._s3=null,this._s3USEast1=null}return AWS.prototype.create=function(){var e=new AWS;return e.initialize(),e},AWS.prototype.initialize=function(){},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(){this._methods={},this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this.emailQueue=new Set,this.isEmailProcessing=!1,this._debugcallMethodHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this.clientDir="",this.serverConfig=""}return MethodManager.create=function(e,t,r,o){var n=new MethodManager;return n.initialize(e,t,r,o),n},MethodManager.prototype.initialize=function(e,t,r,o){var n=this;this._websocketManager=e,this._monitorManagerFunction=t,this._isWorkersEnabled=r,this._isWorkerInstance=o,this.clientDir=resolveio_server_app_1.ResolveIOServer.getClientDir(),this.serverConfig=resolveio_server_app_1.ResolveIOServer.getServerConfig(),process.env.IS_WORKERS_ENABLED&&"false"!==process.env.IS_WORKERS_ENABLED&&("true"!==process.env.IS_WORKER_INSTANCE||"0"!==process.env.WORKER_INDEX)||process.env.NODE_APP_INSTANCE&&"0"!==process.env.NODE_APP_INSTANCE||setTimeout(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.log(new Date,"Start Server Fixture"),[4,(0,init_1.loadServerInit)()];case 1:return e.sent(),console.log(new Date,"End Server Fixture"),[2]}})})},5e3),setImmediate(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,(0,cron_jobs_1.loadServerCronJobs)()];case 1:return e.sent(),(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,flag_updates_1.loadFlagUpdatesMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),[2]}})})}),this._aws=new AWS,resolveio_server_app_1.ResolveIOServer.getSESMail()?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:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_HOST,port:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PORT,secure:!1,auth:{user:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_USERNAME,pass:resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&resolveio_server_app_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Hits",n._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",n._debugcallMethodHits),console.log(new Date,"Method Manager","Call Method Hits",n._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",n._debugCallMethodCronJobHits)),n._debugcallMethodHits=0,n._debugCallMethodHits=0,n._debugCallMethodCronJobHits=0,n._debugSendQueueHits=0},6e4),this._isWorkersEnabled&&!this._isWorkerInstance||setImmediate(function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.setupEmailWatcher()];case 1:return e.sent(),[2]}})})})},MethodManager.prototype.getMethod=function(e){return this._methods[e]},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(c){for(var l=[],e=1;e<arguments.length;e++)l[e-1]=arguments[e];return __awaiter(this,void 0,void 0,function(){var t,r,o,n,s,i,a;return __generator(this,function(e){switch(e.label){case 0:return(this._debugCallMethodCronJobHits+=1,this._methods[c])?[3,2]:(console.log("No Method: "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Method: "+c)]);case 1:throw e.sent(),new Error("No Method: "+c);case 2:return!(1<l.length||l[0])||this._methods[c].skipValidation?[3,10]:this._methods[c].check?[3,4]:(console.error(new Date,"No Check Function For Cron Method "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Cron Method "+c)]);case 3:throw e.sent(),new Error("No Check Function For Cron Method "+c);case 4:return this._methods[c].check._schema?[3,6]:(console.error(new Date,"No Check Schema For Cron Method "+c),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"No Check Function For Cron Method "+c)]);case 5:throw e.sent(),new Error("No Check Schema For Cron Method "+c);case 6:for(t={},a=Object.keys(this._methods[c].check._schema),r=a.filter(function(e){return!e.includes(".")}),o=0;o<l.length;o++)t[r[o]]=l[o];e.label=7;case 7:return e.trys.push([7,8,,10]),this._methods[c].check.validate(t),[3,10];case 8:return n=e.sent(),console.error(new Date,"Error in Cron Method Check ("+c+")",n),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Match Error On Cron Method "+c+"\n\nData Being Checked\n"+JSON.stringify(t,null,2)+"\n\nErrors\n"+JSON.stringify(n,null,2))];case 9:throw e.sent(),n.message="".concat((new Date).toISOString()," - Error in Cron Method Check (").concat(c,"): ").concat(n.message),n;case 10:s=this._monitorManagerFunction.startMonitorFunction("Cron Method",c,"","",l),e.label=11;case 11:return e.trys.push([11,13,15,17]),[4,(a=this._methods[c].function).call.apply(a,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],__read(l),!1))];case 12:return[2,e.sent()];case 13:return i=e.sent(),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Cron Method "+c+" - (callMethodCron)\n\nData \n"+JSON.stringify(l,null,2)+"\n\nErrors\n"+JSON.stringify(i,null,2))];case 14:throw e.sent(),i.message="".concat((new Date).toISOString()," - Error in Cron Method (").concat(c,"): ").concat(i.message),i;case 15:return[4,this._monitorManagerFunction.finishMonitorFunction(s)];case 16:return e.sent(),[7];case 17:return[2]}})})},MethodManager.prototype.callMethod=function(l){for(var u=[],e=1;e<arguments.length;e++)u[e-1]=arguments[e];return __awaiter(this,void 0,void 0,function(){var o,n,s,t,r,i,a,c=this;return __generator(this,function(e){switch(e.label){case 0:if(this._debugcallMethodHits+=1,!(o=this.getMethod(l)))throw console.log("No Method: "+l),new Error("No Method: ".concat(l));if((1<u.length||u[0]&&"function"!=typeof u[0])&&!o.skipValidation){if(!o.check)throw console.error(new Date,"No Check Function For Method "+l),new Error("No Check Function For Method: ".concat(l));if(!o.check._schema)throw console.error(new Date,"No Check Schema For Method "+l),new Error("No Check Schema For Method: ".concat(l))}return"insertSubscriptionLog"===l||"getDataURIfromURL"===l||"processAirdropDistribution"===l||"incCounter"===l||"supportCreateBillingUser"===l||"countCollectionWithQuery"===l?[3,4]:"https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?[3,1]:(resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([u]))<1e6?JSON.stringify([u],null,2):"Too Big",methodName:l,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""}}),[3,3]);case 1:return[4,log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"callMethod",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([u]))<1e6?JSON.stringify([u],null,2):"Too Big",method:l,id_user:this.id_user||"",user:this.user||"",messageId:0,route:"",client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 2:e.sent(),e.label=3;case 3:e.label=4;case 4:return(n="function"==typeof u[u.length-1]?u.slice(0,-1):u,a=resolveio_server_app_1.ResolveIOServer.getMongoManager().getSession(),o.bypassSession||a||["insertErrorLog","countWithQuery","sendEmail"].includes(l)||l.startsWith("monitor-")||l.startsWith("log"))?[3,5]:(s=null,[2,resolveio_server_app_1.ResolveIOServer.getMongoManager().oneTimeTransaction(function(){return __awaiter(c,void 0,void 0,function(){var t,r;return __generator(this,function(e){switch(e.label){case 0:s=this._monitorManagerFunction.startMonitorFunction("Method",l,this.user||"","",n),e.label=1;case 1:return e.trys.push([1,3,7,9]),[4,(r=o.function).call.apply(r,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(n),!1))];case 2:return r=e.sent(),u[u.length-1]&&"function"==typeof u[u.length-1]&&u[u.length-1](null,r),[2,r];case 3:if(112===(t=e.sent()).code||"WriteConflict"===t.codeName||251===t.code||"NoSuchTransaction"===t.codeName)throw t;return console.log(JSON.stringify([new Date,"Error Method Manager - Run Method - New Session",l,{code:t.code,codeName:t.codeName,message:t.message,stack:t.stack}],null,2)),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+l+" - (callMethod)\n\nData \n"+JSON.stringify(u,null,2)+"\n\nErrors\n"+JSON.stringify(t,null,2))];case 4:return e.sent(),t.message="".concat((new Date).toISOString()," - Error in Method With Session (").concat(l,") - New Session: ").concat(t.message),u[u.length-1]&&"function"==typeof u[u.length-1]&&u[u.length-1](t,null),process.env.IS_WORKER_INSTANCE?[3,6]:[4,this.callMethod("insertErrorLog","Error in Method: ".concat(l," - ").concat(JSON.stringify(u,null,2)))];case 5:e.sent(),e.label=6;case 6:throw t;case 7:return[4,this._monitorManagerFunction.finishMonitorFunction(s)];case 8:return e.sent(),[7];case 9:return[2]}})})})]);case 5:t=this._monitorManagerFunction.startMonitorFunction("Method",l,this.user||"","",n),e.label=6;case 6:return e.trys.push([6,8,12,14]),[4,(a=o.function).call.apply(a,__spreadArray([Object.assign({},this,MethodManager.prototype)],__read(n),!1))];case 7:return r=e.sent(),u[u.length-1]&&"function"==typeof u[u.length-1]&&u[u.length-1](null,r),[2,r];case 8:if(112===(i=e.sent()).code||"WriteConflict"===i.codeName)throw i;return console.log(JSON.stringify([new Date,"Error Method Manager - Run Method - Existing Session",l,{code:i.code,codeName:i.codeName,message:i.message,stack:i.stack}],null,2)),[4,this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,"Error Detected During Method "+l+" - (callMethod)\n\nData \n"+JSON.stringify(u,null,2)+"\n\nErrors\n"+JSON.stringify(i,null,2))];case 9:return e.sent(),i.message="".concat((new Date).toISOString()," - Error in Method (").concat(l,") - Existing Session: ").concat(i.message),u[u.length-1]&&"function"==typeof u[u.length-1]&&u[u.length-1](i,null),process.env.IS_WORKER_INSTANCE?[3,11]:[4,this.callMethod("insertErrorLog","Error in Method: ".concat(l," - ").concat(JSON.stringify(u,null,2)))];case 10:e.sent(),e.label=11;case 11:throw i;case 12:return[4,this._monitorManagerFunction.finishMonitorFunction(t)];case 13:return e.sent(),[7];case 14:return[2]}})})},MethodManager.prototype.setupEmailWatcher=function(){return __awaiter(this,void 0,void 0,function(){var r,o=this;return __generator(this,function(e){switch(e.label){case 0:return(r=email_history_collection_1.EmailHistories.watchCollection([])).on("change",function(r){return __awaiter(o,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return"insert"===r.operationType&&r.fullDocument&&"pending"===r.fullDocument.status?(this.emailQueue.add(r.fullDocument._id.toString()),[4,this.tryProcessEmail()]):[3,2];case 1:return e.sent(),[3,3];case 2:"update"!==r.operationType&&"replace"!==r.operationType||(t=r.fullDocument)&&"pending"!==t.status&&this.emailQueue.has(t._id.toString())&&this.emailQueue.delete(t._id.toString()),e.label=3;case 3:return[2]}})})}).on("error",function(t){return __awaiter(o,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return console.error("Email history changestream error",t),[4,r.close()];case 1:return e.sent(),[2]}})})}).on("close",function(){return __awaiter(o,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.setupEmailWatcher()];case 1:return e.sent(),[2]}})})}),[4,this.loadPendingEmails()];case 1:return e.sent(),[2]}})})},MethodManager.prototype.loadPendingEmails=function(){return __awaiter(this,void 0,void 0,function(){var t,r,o,n,s,i;return __generator(this,function(e){switch(e.label){case 0:return[4,email_history_collection_1.EmailHistories.find({status:"pending"},{sort:{_id:1}})];case 1:t=e.sent();try{for(r=__values(t),o=r.next();!o.done;o=r.next())n=o.value,this.emailQueue.add(n._id.toString())}catch(e){s={error:e}}finally{try{o&&!o.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return[4,this.tryProcessEmail()];case 2:return e.sent(),[2]}})})},MethodManager.prototype.tryProcessEmail=function(){return __awaiter(this,void 0,void 0,function(){var t,u,r,h=this;return __generator(this,function(e){switch(e.label){case 0:if(this.isEmailProcessing||0===this.emailQueue.size)return[2];this.isEmailProcessing=!0,e.label=1;case 1:e.trys.push([1,5,6,9]),t=function(){var o,t,r,n,s,i,a,c,l;return __generator(this,function(e){switch(e.label){case 0:return s=u.emailQueue.values().next().value,u.emailQueue.delete(s),[4,email_history_collection_1.EmailHistories.findOneAndUpdate({_id:s,status:"pending"},{$set:{status:"processing",processingAt:new Date}})];case 1:if(!(o=e.sent()))return[2,"continue"];if(!(o.attachments&&0<o.attachments.length))return[3,14];e.label=2;case 2:e.trys.push([2,12,,14]),e.label=3;case 3:e.trys.push([3,9,10,11]),c=void 0,t=__values(o.attachments),r=t.next(),e.label=4;case 4:return r.done?[3,8]:(n=r.value).path&&n.path.startsWith("http")?[4,fetch(n.path)]:[3,7];case 5:if((s=e.sent()).ok)return[4,s.arrayBuffer()];throw new Error("Failed to fetch attachment: ".concat(n.path));case 6:i=e.sent(),i=Buffer.from(i),i.length<=20971520&&(n.content=i,delete n.path),e.label=7;case 7:return r=t.next(),[3,4];case 8:return[3,11];case 9:return i=e.sent(),c={error:i},[3,11];case 10:try{r&&!r.done&&(l=t.return)&&l.call(t)}finally{if(c)throw c.error}return[7];case 11:return[3,14];case 12:return a=e.sent(),console.error("Failed to fetch attachment:",a),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof a?a:u.safeStringify(a),completedAt:new Date}})];case 13:return e.sent(),[2,"continue"];case 14:return(a={replyTo:o.reply_to||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_REPLY_TO||void 0,from:o.send_from||resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_FROM,to:o.email,subject:(resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)||resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)?"(DEV SERVER) - ":"")+o.subject,text:"string"==typeof o.text?o.text:"",html:"string"==typeof o.html?o.html:"",attachments:o.attachments||[]}).attachments&&0<a.attachments.length&&(a.attachments=a.attachments.map(function(e){e=__assign({},e);return!e.content||"object"!=typeof e.content||e.content instanceof Buffer?"string"==typeof e.content&&"base64"===e.encoding?(e.content=Buffer.from(e.content,"base64"),delete e.encoding):"string"==typeof e.content&&(e.content=Buffer.from(e.content)):"Binary"===e.content._bsontype&&0===e.content.sub_type?e.content=Buffer.from(e.content.buffer):e.content=Buffer.from(e.content),e})),u._mailer.sendMail(a,function(r){return __awaiter(h,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(e.trys.push([0,7,,9]),r)?(console.error("Failed to send email:",r),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof r?r:this.safeStringify(r),completedAt:new Date}})]):[3,2];case 1:return e.sent(),[3,6];case 2:return"dev@resolveio.com"!==o.email?[3,4]:[4,email_history_collection_1.EmailHistories.deleteOne({_id:o._id})];case 3:return e.sent(),[3,6];case 4:return[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"completed",completedAt:new Date}})];case 5:e.sent(),e.label=6;case 6:return[3,9];case 7:return t=e.sent(),console.error("Error in sendMail callback:",t),[4,email_history_collection_1.EmailHistories.updateOne({_id:o._id},{$set:{status:"failed",error:"string"==typeof t?t:this.safeStringify(t),completedAt:new Date}})];case 8:return e.sent(),[3,9];case 9:return[2]}})})}),[4,new Promise(function(e){return setTimeout(e,1e3)})];case 15:return e.sent(),[2]}})},u=this,e.label=2;case 2:return 0<this.emailQueue.size?[5,t()]:[3,4];case 3:return e.sent(),[3,2];case 4:return[3,9];case 5:return r=e.sent(),console.error("Error processing email queue:",r),[3,9];case 6:return(this.isEmailProcessing=!1,0<this.emailQueue.size)?[4,this.tryProcessEmail()]:[3,8];case 7:e.sent(),e.label=8;case 8:return[7];case 9:return[2]}})})},MethodManager.prototype.safeStringify=function(e){try{return JSON.stringify(e,this.getCircularReplacer())}catch(e){return"Error in JSON stringifying: ".concat(e.message)}},MethodManager.prototype.getCircularReplacer=function(){var r=new WeakSet;return function(e,t){if("object"==typeof t&&null!==t){if(r.has(t))return"[Circular]";r.add(t)}return t}},MethodManager.prototype.sendEmail=function(o,n,s,i,a,c,l,u){return void 0===u&&(u=!1),__awaiter(this,void 0,void 0,function(){var t,r;return __generator(this,function(e){switch(e.label){case 0:if(!(o=!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/dev\./)&&!resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL.match(/https:\/\/www\.dev\./)&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||o.match(/\@resolveio\.com/)?o:"dev@resolveio.com"))return[3,7];if("http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&!u)return[3,5];a=a||[],a=(a=Array.isArray(a)?a:[a]).map(function(e){e=__assign({},e);return Buffer.isBuffer(e.content)&&(e.content=e.content.toString("base64"),e.encoding="base64"),e}),t={_id:(0,common_1.objectIdHexString)(),__v:0,date:new Date,id_user:this.id_user||"",user:this.user||"",email:o,subject:n||"",text:s||"",html:i||"",attachments:a||[],send_from:c||"",reply_to:l||"",status:"pending",error:""},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,email_history_collection_1.EmailHistories.insertOne(t)];case 2:return[2,e.sent()];case 3:throw r=e.sent(),console.error("Failed to queue email:",r),r.message="Failed to queue email: ".concat(r.message),r;case 4:return[3,6];case 5:return console.log("Send email",o,n,s,i,a,c),[2,!0];case 6:return[3,8];case 7:return[2,!0];case 8:return[2]}})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){if(fs.existsSync(path.join(__dirname,"../private/"+e)))try{return fs.readFileSync(path.join(__dirname,"../private/"+e),"utf-8")}catch(e){throw e.message="Error in readFile: ".concat(e.message),e}else if(fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e)))try{return fs.readFileSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"utf-8")}catch(e){throw e.message="Error in readFile: ".concat(e.message),e}throw new Error("Error in readFile: File Not Found")},MethodManager.prototype.readImage=function(e){if(fs.existsSync(path.join(__dirname,"../private/"+e)))try{return fs.readFileSync(path.join(__dirname,"../private/"+e),"base64")}catch(e){throw e.message="Error in readImage: ".concat(e.message),e}else if(fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e)))try{return fs.readFileSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(),"./private/"+e),"base64")}catch(e){throw e.message="Error in readImage: ".concat(e.message),e}throw new Error("Error in readImage: File Not Found")},MethodManager}());exports.MethodManager=MethodManager;
2
2
  //# sourceMappingURL=method.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["client_s3_1","require","fs","nodemailer","sesTransport","path","email_history_collection_1","log_collection_1","cron_jobs_1","init_1","accounts_1","aws_1","collections_1","counters_1","cron_jobs_2","flag_updates_1","flags_1","logs_1","monitor_1","pdf_1","report_builder_1","support_1","resolveio_server_app_1","common_1","AWS","this","_s3","_s3USEast1","prototype","create","aws","initialize","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","_methods","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugcallMethodHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","clientDir","serverConfig","websocketManager","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","methodManager","_this","_websocketManager","_monitorManagerFunction","ResolveIOServer","getClientDir","getServerConfig","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","__awaiter","console","log","Date","loadServerInit","_a","sent","setImmediate","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","getSESMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getMainServer","getSubscriptionManager","getEnableDebug","setupEmailWatcher","getMethod","methodName","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","sendEmail","_b","Error","skipValidation","check","error","_schema","valObj","valKeys","keys","rootKeys","filter","a","includes","i","validate","err_1","JSON","stringify","message","concat","toISOString","monitor","startMonitorFunction","function","call","apply","__spreadArray","id_user","id_ws","__read","err_2","finishMonitorFunction","callMethod","getLocalLogManager","writeLog","type","data","_id","objectIdHexString","createdAt","collection","id_document","payload","getBinarySize","messageId","route","Logs","insertOne","client","instance","instance_index","functionMethodData","slice","session","getMongoManager","getSession","bypassSession","startsWith","monitor_2","oneTimeTransaction","res","code","err_4","codeName","stack","err_3","changeStream","EmailHistories","watchCollection","on","change","operationType","fullDocument","status","add","toString","tryProcessEmail","updatedEmail","has","delete","err","close","loadPendingEmails","find","sort","pendingEmails","pendingEmails_1","__values","pendingEmails_1_1","next","done","email","value","size","emailId","this_1","values","findOneAndUpdate","$set","processingAt","emailHistory","_e","attachments","e_2","_c","att","fetch","response","ok","arrayBuffer","buffer","Buffer","from","content","err_6","updateOne","safeStringify","completedAt","mailOptions","replyTo","reply_to","undefined","send_from","MAIL_FROM","to","subject","match","text","html","map","newAtt","__assign","encoding","_bsontype","sub_type","sendMail","deleteOne","error_1","Promise","resolve","err_5","obj","getCircularReplacer","e","seen","WeakSet","key","sendTo","local_override","Array","isArray","isBuffer","__v","date","err_7","getAWS","readFile","fileName","existsSync","join","__dirname","readFileSync","readImage"],"mappings":"ihFAAAA,a,gGAAAC,QAAA,oBAAA,GACAC,GAAAD,QAAA,IAAA,EACAE,WAAAF,QAAA,YAAA,EACAG,aAAAH,QAAA,0BAAA,EACAI,KAAAJ,QAAA,MAAA,EACAK,2BAAAL,Q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,EAAK,aAAeuN,CAAS,EAAG,QAAQ,C,CAEtG,MAAO7E,GAEN,MADAA,EAAI9D,QAAU,uBAAAC,OAAuB6D,EAAI9D,OAAO,EAC1C8D,C,CAKT,MAAM,IAAI/E,MAAO,oCAAoC,CACtD,EACDlF,aAAA,EAAC,GA9tBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { S3 } from '@aws-sdk/client-s3';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport * as path from 'path';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { Logs } from '../collections/log.collection';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadAWSMethods } from '../methods/aws';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { loadFlagMethods } from '../methods/flags';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { EmailHistoryModel } from '../models/email-history.model';\nimport { MethodAllModel, MethodModel } from '../models/method.model';\nimport { ResolveIOServer } from '../resolveio-server-app';\nimport { getBinarySize, objectIdHexString } from '../util/common';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { WebSocketManager } from './websocket.manager';\n\nexport class AWS {\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor() {}\n\n\tpublic create() {\n\t\tconst aws = new AWS();\n\t\taws.initialize();\n\t\treturn aws;\n\t}\n\n\tprivate initialize() {\n\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 _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate emailQueue: Set<string> = new Set(); // Set to store pending email IDs\n\tprivate isEmailProcessing = false;\n\n\tprivate _debugcallMethodHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tpublic clientDir = '';\n\tpublic serverConfig = '';\n\n\tconstructor() {}\n\n\tstatic create(websocketManager: WebSocketManager, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tconst methodManager = new MethodManager();\n\t\tmethodManager.initialize(websocketManager, monitorManagerFunction, isWorkersEnabled, isWorkerInstance);\n\t\treturn methodManager;\n\t}\n\n\tprivate initialize(websocketManager: WebSocketManager, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._websocketManager = websocketManager;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\t\t\n\t\tthis.clientDir = ResolveIOServer.getClientDir();\n\t\tthis.serverConfig = ResolveIOServer.getServerConfig();\n\n\t\t// Fixtures\n\t\tif (!process.env.IS_WORKERS_ENABLED || process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {\n\t\t\tif (!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') {\n\t\t\t\tsetTimeout(async () => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tawait loadServerInit();\n\t\t\t\t\tconsole.log(new Date(), 'End Server Fixture');\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t}\n\t\t\n\t\tsetImmediate(async () => {\n\t\t\t// Methods\n\t\t\tawait loadServerCronJobs();\n\n\t\t\tloadAccountMethods(this);\n\t\t\tloadAWSMethods(this);\n\t\t\tloadCollectionMethods(this);\n\t\t\tloadCounterMethods(this);\n\t\t\tloadLogMethods(this);\n\t\t\tloadPDFMethods(this);\n\t\t\tloadCronJobMethods(this);\n\t\t\tloadFlagMethods(this);\n\t\t\tloadFlagUpdatesMethods(this);\n\t\t\tloadReportBuilderMethods(this);\n\t\t\tloadSupportMethods(this);\n\t\t\tloadMonitorMethods(this);\n\t\t});\n\t\t\n\t\tthis._aws = new AWS();\n\t\t\n\t\tif (ResolveIOServer.getSESMail()) {\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: ResolveIOServer.getServerConfig()['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: ResolveIOServer.getServerConfig()['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: ResolveIOServer.getServerConfig()['MAIL_USERNAME'],\n\t\t\t\t\tpass: ResolveIOServer.getServerConfig()['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 (ResolveIOServer.getMainServer().getSubscriptionManager() && ResolveIOServer.getMainServer().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._debugcallMethodHits);\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._debugcallMethodHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.setupEmailWatcher();\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic getMethod(methodName: string): MethodAllModel {\n\t\treturn this._methods[methodName];\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 async 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\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\tthrow new Error('No Method: ' + method);\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 Cron Method ' + method);\n\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Cron Method ' + method);\n\t\n\t\t\t\tthrow new Error('No Check Function For Cron Method ' + method);\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 Cron Method ' + method);\n\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Cron Method ' + method);\n\t\n\t\t\t\tthrow new Error('No Check Schema For Cron Method ' + method);\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 (err) {\n\t\t\t\t\tconsole.error(new Date(), 'Error in Cron Method Check (' + method + ')', err);\n\n\t\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Match Error On Cron Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t\terr.message = `${new Date().toISOString()} - Error in Cron Method Check (${method}): ${err.message}`;\n\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\n\t\ttry {\n\t\t\tlet res = await this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData);\n\t\t\treturn res;\n\t\t}\n\t\tcatch (err) {\n\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Cron Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\n\t\t\terr.message = `${new Date().toISOString()} - Error in Cron Method (${method}): ${err.message}`;\n\t\t\t\n\t\t\tthrow err;\n\t\t}\n\t\tfinally {\n\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic async callMethod(methodName: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugcallMethodHits += 1;\n\n\t\tlet method = this.getMethod(methodName);\n\n\t\tif (!method) {\n\t\t\tconsole.log('No Method: ' + methodName);\n\t\t\tthrow new Error(`No Method: ${methodName}`);\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !method.skipValidation) {\n\t\t\tif (!method.check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + methodName);\n\t\t\t\tthrow new Error(`No Check Function For Method: ${methodName}`);\n\t\t\t}\n\t\t\telse if (!method.check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + methodName);\n\t\t\t\tthrow new Error(`No Check Schema For Method: ${methodName}`);\n\t\t\t}\n\t\t}\n\n\t\tif (methodName !== 'insertSubscriptionLog' && methodName !== 'getDataURIfromURL' && methodName !== 'processAirdropDistribution' && methodName !== 'incCounter' && methodName !== 'supportCreateBillingUser' && methodName !== 'countCollectionWithQuery') {\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\ttype: 'log',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 1000000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\t\tmethodName: methodName,\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '', \n\t\t\t\t\t\tmessageId: 0,\n\t\t\t\t\t\troute: ''\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tawait Logs.insertOne({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tid_document: '',\n\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 1000000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\tmethod: methodName,\n\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\tmessageId: 0,\n\t\t\t\t\troute: '',\n\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || ''\n\t\t\t\t})\n\t\t\t};\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\n\t\tconst session = ResolveIOServer.getMongoManager().getSession();\n\n\t\tif (!method.bypassSession &&\n\t\t\t!session && \n\t\t\t![\n\t\t\t\t'insertErrorLog', // CIRCULAR LOOP - DO NOT REMOVE\n\t\t\t\t'countWithQuery', // MONGO SESSIONS/TRANSACTIONS DONT WORTH WITH COUNTS\n\t\t\t\t'sendEmail' // ALWAYS SEND SO ALWAYS HAVE RECORD - DONT ROLL BACK - BYPASS SESSION\n\t\t\t].includes(methodName) &&\n\t\t\t!methodName.startsWith('monitor-') &&\n\t\t\t!methodName.startsWith('log')\n\t\t) {\n\t\t\tlet monitor = null;\n\t\t\t\n\t\t\treturn ResolveIOServer.getMongoManager().oneTimeTransaction(async () => {\n\t\t\t\tmonitor = this._monitorManagerFunction.startMonitorFunction('Method', methodName, this['user'] || '', '', functionMethodData);\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tlet res = await method.function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);\n\n\t\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\t\tmethodData[methodData.length - 1](null, res);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tif (err.code === 112 || err.codeName === 'WriteConflict') {\n\t\t\t\t\t\tthrow err; // Write error, retry\n\t\t\t\t\t}\n\n\t\t\t\t\tconsole.log(JSON.stringify([new Date(), 'Error Method Manager - Run Method - New Session', methodName, {\n\t\t\t\t\t\tcode: err.code,\n\t\t\t\t\t\tcodeName: err.codeName,\n\t\t\t\t\t\tmessage: err.message,\n\t\t\t\t\t\tstack: err.stack\n\t\t\t\t\t}], null, 2));\n\n\t\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Method ' + methodName + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t\terr.message = `${new Date().toISOString()} - Error in Method With Session (${methodName}) - New Session: ${err.message}`;\n\n\t\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\t\tmethodData[methodData.length - 1](err, null);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!process.env.IS_WORKER_INSTANCE) {\n\t\t\t\t\t\tawait this.callMethod('insertErrorLog', `Error in Method: ${methodName} - ${JSON.stringify(methodData, null, 2)}`);\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', methodName, this['user'] || '', '', functionMethodData);\n\t\t\t\n\t\t\ttry {\n\t\t\t\tlet res = await method.function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);\n\n\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\tmethodData[methodData.length - 1](null, res);\n\t\t\t\t}\n\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tif (err.code === 112 || err.codeName === 'WriteConflict') {\n\t\t\t\t\tthrow err; // Write error, retry\n\t\t\t\t}\n\n\t\t\t\tconsole.log(JSON.stringify([new Date(), 'Error Method Manager - Run Method - Existing Session', methodName, {\n\t\t\t\t\tcode: err.code,\n\t\t\t\t\tcodeName: err.codeName,\n\t\t\t\t\tmessage: err.message,\n\t\t\t\t\tstack: err.stack\n\t\t\t\t}], null, 2));\n\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Method ' + methodName + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\terr.message = `${new Date().toISOString()} - Error in Method (${methodName}) - Existing Session: ${err.message}`;\n\t\t\t\t\n\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\tmethodData[methodData.length - 1](err, null);\n\t\t\t\t}\n\n\t\t\t\tif (!process.env.IS_WORKER_INSTANCE) {\n\t\t\t\t\tawait this.callMethod('insertErrorLog', `Error in Method: ${methodName} - ${JSON.stringify(methodData, null, 2)}`);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync setupEmailWatcher() {\n\t\tconst changeStream = EmailHistories.watchCollection([]);\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending') {\n\t\t\t\tthis.emailQueue.add(change.fullDocument._id.toString());\n\t\t\t\tawait this.tryProcessEmail();\n\t\t\t}\n\t\t\telse if (change.operationType === 'update' || change.operationType === 'replace') {\n\t\t\t\tconst updatedEmail = change.fullDocument;\n\t\t\t\tif (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {\n\t\t\t\t\tthis.emailQueue.delete(updatedEmail._id.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.on('error', async err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tawait changeStream.close();\n\t\t})\n\t\t.on('close', async () => {\n\t\t\tawait this.setupEmailWatcher();\n\t\t});\n\n\t\tawait this.loadPendingEmails();\n\t}\n\n\tasync loadPendingEmails() {\n\t\t// Load any pending emails on startup\n\t\tconst pendingEmails = await EmailHistories.find({ status: 'pending' }, {sort: {_id: 1}});\n\t\tfor (const email of pendingEmails) {\n\t\t\tthis.emailQueue.add(email._id.toString());\n\t\t}\n\t\t// Try to process emails\n\t\tawait this.tryProcessEmail();\n\t}\n\n\tasync tryProcessEmail() {\n\t\tif (this.isEmailProcessing || this.emailQueue.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tthis.isEmailProcessing = true;\n\t\n\t\ttry {\n\t\t\twhile (this.emailQueue.size > 0) {\n\t\t\t\tconst emailId = this.emailQueue.values().next().value;\n\t\t\t\tthis.emailQueue.delete(emailId);\n\t\n\t\t\t\tconst emailHistory = await EmailHistories.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\t_id: emailId,\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$set: { status: 'processing', processingAt: new Date() },\n\t\t\t\t\t}\n\t\t\t\t);\n\t\n\t\t\t\tif (!emailHistory) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\n\t\t\t\t// Fetch and process attachments\n\t\t\t\tif (emailHistory.attachments && emailHistory.attachments.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (let att of emailHistory.attachments) {\n\t\t\t\t\t\t\tif (att.path && att.path.startsWith('http')) {\n\t\t\t\t\t\t\t\tconst response = await fetch(att.path);\n\t\t\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Failed to fetch attachment: ${att.path}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst arrayBuffer = await response.arrayBuffer();\n\t\t\t\t\t\t\t\tconst buffer = Buffer.from(arrayBuffer);\n\t\n\t\t\t\t\t\t\t\t// Check the size of the attachment\n\t\t\t\t\t\t\t\tconst maxSize = 20 * 1024 * 1024; // 20MB in bytes\n\t\t\t\t\t\t\t\tif (buffer.length <= maxSize) {\n\t\t\t\t\t\t\t\t\t// Attachment is within size limits, include it\n\t\t\t\t\t\t\t\t\tatt.content = buffer;\n\t\t\t\t\t\t\t\t\tdelete att.path;\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}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.error('Failed to fetch attachment:', err);\n\t\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\tcompletedAt: new 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\t// Skip to the next email\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t\t// Prepare email options\n\t\t\t\tconst mailOptions: any = {\n\t\t\t\t\treplyTo: emailHistory.reply_to || (ResolveIOServer.getServerConfig()['MAIL_REPLY_TO'] || undefined),\n\t\t\t\t\tfrom: emailHistory.send_from || ResolveIOServer.getServerConfig().MAIL_FROM,\n\t\t\t\t\tto: emailHistory.email,\n\t\t\t\t\tsubject:\n\t\t\t\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./)\n\t\t\t\t\t\t\t? '(DEV SERVER) - '\n\t\t\t\t\t\t\t: '') + emailHistory.subject,\n\t\t\t\t\ttext: typeof emailHistory.text === 'string' ? emailHistory.text : '',\n\t\t\t\t\thtml: typeof emailHistory.html === 'string' ? emailHistory.html : '',\n\t\t\t\t\tattachments: emailHistory.attachments || [],\n\t\t\t\t};\n\t\n\t\t\t\t// Process attachments before sending\n\t\t\t\tif (mailOptions.attachments && mailOptions.attachments.length > 0) {\n\t\t\t\t\tmailOptions.attachments = mailOptions.attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\t// Handle attachments stored as BinData or Buffer\n\t\t\t\t\t\tif (newAtt.content && typeof newAtt.content === 'object' && !(newAtt.content instanceof Buffer)) {\n\t\t\t\t\t\t\t// Convert MongoDB's Binary data to Buffer\n\t\t\t\t\t\t\tif (newAtt.content._bsontype === 'Binary' && newAtt.content.sub_type === 0) {\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content.buffer);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t// Handle other types if necessary\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Handle attachments stored as Base64 strings\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string' && newAtt.encoding === 'base64') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content, 'base64');\n\t\t\t\t\t\t\tdelete newAtt.encoding;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Ensure the content is a Buffer\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\n\t\t\t\t// Send the email\n\t\t\t\tthis._mailer.sendMail(mailOptions, async err => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t},\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\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\tawait EmailHistories.deleteOne({ _id: emailHistory._id });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\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}\n\t\t\t\t\tcatch (error) {\n\t\t\t\t\t\tconsole.error('Error in sendMail callback:', error);\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof error === 'string' ? error : this.safeStringify(error),\n\t\t\t\t\t\t\t\t\tcompletedAt: new 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} \n\t\t\t\t});\n\t\n\t\t\t\t// Wait for at least one second before sending the next email\n\t\t\t\t// eslint-disable-next-line no-restricted-syntax\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Error processing email queue:', err);\n\t\t}\n\t\tfinally {\n\t\t\tthis.isEmailProcessing = false;\n\t\t\t// Check if new emails arrived while processing\n\t\t\tif (this.emailQueue.size > 0) {\n\t\t\t\tawait this.tryProcessEmail();\n\t\t\t}\n\t\t}\n\t}\n\n\tsafeStringify(obj)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn JSON.stringify(obj, this.getCircularReplacer());\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\treturn `Error in JSON stringifying: ${e.message}`;\n\t\t}\n\t}\n\n\tgetCircularReplacer()\n\t{\n\t\tconst seen = new WeakSet();\n\t\treturn (key, value) =>\n\t\t{\n\t\t\tif (typeof value === \"object\" && value !== null)\n\t\t\t{\n\t\t\t\tif (seen.has(value))\n\t\t\t\t{\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tseen.add(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t};\n\t}\n\n\tpublic async sendEmail(\n\t\tsendTo: string,\n\t\tsubject: string,\n\t\ttext?: string,\n\t\thtml?: string,\n\t\tattachments?: any[],\n\t\tsend_from?: string,\n\t\treply_to?: string,\n\t\tlocal_override = false\n\t) {\n\t\t// Modify sendTo in development environments\n\t\tif (\n\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t) {\n\t\t\tsendTo = 'dev@resolveio.com';\n\t\t}\n\n\t\tif (sendTo) {\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\tlocal_override\n\t\t\t) {\n\t\t\t\tif (!attachments) {\n\t\t\t\t\tattachments = [];\n\t\t\t\t}\n\n\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\tattachments = [attachments];\n\t\t\t\t}\n\n\t\t\t\t// Process attachments before saving\n\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t}\n\t\t\t\t\treturn newAtt;\n\t\t\t\t});\n\n\t\t\t\t// Queue the email in MongoDB\n\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate: new Date(),\n\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\temail: sendTo,\n\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\ttext: text || '',\n\t\t\t\t\thtml: html || '',\n\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\terror: ''\n\t\t\t\t};\n\n\t\t\t\ttry {\n\t\t\t\t\tlet history = await EmailHistories.insertOne(emailHistory);\n\t\t\t\t\treturn history;\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\terr.message = `Failed to queue email: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log(\n\t\t\t\t\t'Send email',\n\t\t\t\t\tsendTo,\n\t\t\t\t\tsubject,\n\t\t\t\t\ttext,\n\t\t\t\t\thtml,\n\t\t\t\t\tattachments,\n\t\t\t\t\tsend_from\n\t\t\t\t);\n\t\t\t\t\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\ttry {\n\t\t\t\treturn fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'utf-8');\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\terr.message = `Error in readFile: ${err.message}`;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\ttry {\n\t\t\t\t\treturn fs.readFileSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'utf-8');\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\terr.message = `Error in readFile: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error ('Error in readFile: File Not Found');\n\t}\n\n\tpublic readImage(fileName) {\n\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\ttry {\n\t\t\t\treturn fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'base64');\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\terr.message = `Error in readImage: ${err.message}`;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\ttry {\n\t\t\t\t\treturn fs.readFileSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'base64');\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\terr.message = `Error in readImage: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error ('Error in readImage: File Not Found');\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["client_s3_1","require","fs","nodemailer","sesTransport","path","email_history_collection_1","log_collection_1","cron_jobs_1","init_1","accounts_1","aws_1","collections_1","counters_1","cron_jobs_2","flag_updates_1","flags_1","logs_1","monitor_1","pdf_1","report_builder_1","support_1","resolveio_server_app_1","common_1","AWS","this","_s3","_s3USEast1","prototype","create","aws","initialize","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","_methods","_isWorkersEnabled","_isWorkerInstance","emailQueue","Set","isEmailProcessing","_debugcallMethodHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","clientDir","serverConfig","websocketManager","monitorManagerFunction","isWorkersEnabled","isWorkerInstance","methodManager","_this","_websocketManager","_monitorManagerFunction","ResolveIOServer","getClientDir","getServerConfig","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","WORKER_INDEX","NODE_APP_INSTANCE","setTimeout","__awaiter","console","log","Date","loadServerInit","_a","sent","setImmediate","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadFlagUpdatesMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","getSESMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getMainServer","getSubscriptionManager","getEnableDebug","setupEmailWatcher","getMethod","methodName","methods","method","Object","assign","callMethodCron","methodData","_i","arguments","length","sendEmail","_b","Error","skipValidation","check","error","_schema","valObj","valKeys","keys","rootKeys","filter","a","includes","i","validate","err_1","JSON","stringify","message","concat","toISOString","monitor","startMonitorFunction","function","call","apply","__spreadArray","id_user","id_ws","__read","err_2","finishMonitorFunction","callMethod","getLocalLogManager","writeLog","type","data","_id","objectIdHexString","createdAt","collection","id_document","payload","getBinarySize","messageId","route","Logs","insertOne","client","instance","instance_index","functionMethodData","slice","session","getMongoManager","getSession","bypassSession","startsWith","monitor_2","oneTimeTransaction","res","code","err_4","codeName","stack","err_3","changeStream","EmailHistories","watchCollection","on","change","operationType","fullDocument","status","add","toString","tryProcessEmail","updatedEmail","has","delete","err","close","loadPendingEmails","find","sort","pendingEmails","pendingEmails_1","__values","pendingEmails_1_1","next","done","email","value","size","emailId","this_1","values","findOneAndUpdate","$set","processingAt","emailHistory","_e","attachments","e_2","_c","att","fetch","response","ok","arrayBuffer","buffer","Buffer","from","content","err_6","updateOne","safeStringify","completedAt","mailOptions","replyTo","reply_to","undefined","send_from","MAIL_FROM","to","subject","match","text","html","map","newAtt","__assign","encoding","_bsontype","sub_type","sendMail","deleteOne","error_1","Promise","resolve","err_5","obj","getCircularReplacer","e","seen","WeakSet","key","sendTo","local_override","Array","isArray","isBuffer","__v","date","err_7","getAWS","readFile","fileName","existsSync","join","__dirname","readFileSync","readImage"],"mappings":"ihFAAAA,a,gGAAAC,QAAA,oBAAA,GACAC,GAAAD,QAAA,IAAA,EACAE,WAAAF,QAAA,YAAA,EACAG,aAAAH,QAAA,0BAAA,EACAI,KAAAJ,QAAA,MAAA,EACAK,2BAAAL,QAAA,yCAAA,EACAM,iBAAAN,QAAA,+BAAA,EACAO,YAAAP,QAAA,uBAAA,EACAQ,OAAAR,QAAA,kBAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,MAAAV,QAAA,gBAAA,EACAW,cAAAX,QAAA,wBAAA,EACAY,WAAAZ,QAAA,qBAAA,EACAa,YAAAb,QAAA,sBAAA,EACAc,eAAAd,QAAA,yBAAA,EACAe,QAAAf,QAAA,kBAAA,EACAg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ws-sdk/client-s3';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport * as path from 'path';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { Logs } from '../collections/log.collection';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadAWSMethods } from '../methods/aws';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagUpdatesMethods } from '../methods/flag-updates';\nimport { loadFlagMethods } from '../methods/flags';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { EmailHistoryModel } from '../models/email-history.model';\nimport { MethodAllModel, MethodModel } from '../models/method.model';\nimport { ResolveIOServer } from '../resolveio-server-app';\nimport { getBinarySize, objectIdHexString } from '../util/common';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { WebSocketManager } from './websocket.manager';\n\nexport class AWS {\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor() {}\n\n\tpublic create() {\n\t\tconst aws = new AWS();\n\t\taws.initialize();\n\t\treturn aws;\n\t}\n\n\tprivate initialize() {\n\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 _websocketManager: WebSocketManager;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate emailQueue: Set<string> = new Set(); // Set to store pending email IDs\n\tprivate isEmailProcessing = false;\n\n\tprivate _debugcallMethodHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tpublic clientDir = '';\n\tpublic serverConfig = '';\n\n\tconstructor() {}\n\n\tstatic create(websocketManager: WebSocketManager, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tconst methodManager = new MethodManager();\n\t\tmethodManager.initialize(websocketManager, monitorManagerFunction, isWorkersEnabled, isWorkerInstance);\n\t\treturn methodManager;\n\t}\n\n\tprivate initialize(websocketManager: WebSocketManager, monitorManagerFunction: MonitorManagerFunction, isWorkersEnabled, isWorkerInstance) {\n\t\tthis._websocketManager = websocketManager;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\t\tthis._isWorkersEnabled = isWorkersEnabled;\n\t\tthis._isWorkerInstance = isWorkerInstance;\n\t\t\n\t\tthis.clientDir = ResolveIOServer.getClientDir();\n\t\tthis.serverConfig = ResolveIOServer.getServerConfig();\n\n\t\t// Fixtures\n\t\tif (!process.env.IS_WORKERS_ENABLED || process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {\n\t\t\tif (!process.env.NODE_APP_INSTANCE || process.env.NODE_APP_INSTANCE === '0') {\n\t\t\t\tsetTimeout(async () => {\n\t\t\t\t\tconsole.log(new Date(), 'Start Server Fixture');\n\t\t\t\t\tawait loadServerInit();\n\t\t\t\t\tconsole.log(new Date(), 'End Server Fixture');\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t}\n\t\t\n\t\tsetImmediate(async () => {\n\t\t\t// Methods\n\t\t\tawait loadServerCronJobs();\n\n\t\t\tloadAccountMethods(this);\n\t\t\tloadAWSMethods(this);\n\t\t\tloadCollectionMethods(this);\n\t\t\tloadCounterMethods(this);\n\t\t\tloadLogMethods(this);\n\t\t\tloadPDFMethods(this);\n\t\t\tloadCronJobMethods(this);\n\t\t\tloadFlagMethods(this);\n\t\t\tloadFlagUpdatesMethods(this);\n\t\t\tloadReportBuilderMethods(this);\n\t\t\tloadSupportMethods(this);\n\t\t\tloadMonitorMethods(this);\n\t\t});\n\t\t\n\t\tthis._aws = new AWS();\n\t\t\n\t\tif (ResolveIOServer.getSESMail()) {\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: ResolveIOServer.getServerConfig()['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: ResolveIOServer.getServerConfig()['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: ResolveIOServer.getServerConfig()['MAIL_USERNAME'],\n\t\t\t\t\tpass: ResolveIOServer.getServerConfig()['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 (ResolveIOServer.getMainServer().getSubscriptionManager() && ResolveIOServer.getMainServer().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._debugcallMethodHits);\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._debugcallMethodHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tif (!this._isWorkersEnabled || this._isWorkerInstance) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.setupEmailWatcher();\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic getMethod(methodName: string): MethodAllModel {\n\t\treturn this._methods[methodName];\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 async 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\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\tthrow new Error('No Method: ' + method);\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 Cron Method ' + method);\n\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Cron Method ' + method);\n\t\n\t\t\t\tthrow new Error('No Check Function For Cron Method ' + method);\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 Cron Method ' + method);\n\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'No Check Function For Cron Method ' + method);\n\t\n\t\t\t\tthrow new Error('No Check Schema For Cron Method ' + method);\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 (err) {\n\t\t\t\t\tconsole.error(new Date(), 'Error in Cron Method Check (' + method + ')', err);\n\n\t\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Match Error On Cron Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t\terr.message = `${new Date().toISOString()} - Error in Cron Method Check (${method}): ${err.message}`;\n\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\n\t\ttry {\n\t\t\tlet res = await this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData);\n\t\t\treturn res;\n\t\t}\n\t\tcatch (err) {\n\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Cron Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\n\t\t\terr.message = `${new Date().toISOString()} - Error in Cron Method (${method}): ${err.message}`;\n\t\t\t\n\t\t\tthrow err;\n\t\t}\n\t\tfinally {\n\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t}\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic async callMethod(methodName: string, ...methodData: any[]): Promise<any> {\n\t\tthis._debugcallMethodHits += 1;\n\n\t\tlet method = this.getMethod(methodName);\n\n\t\tif (!method) {\n\t\t\tconsole.log('No Method: ' + methodName);\n\t\t\tthrow new Error(`No Method: ${methodName}`);\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !method.skipValidation) {\n\t\t\tif (!method.check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + methodName);\n\t\t\t\tthrow new Error(`No Check Function For Method: ${methodName}`);\n\t\t\t}\n\t\t\telse if (!method.check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + methodName);\n\t\t\t\tthrow new Error(`No Check Schema For Method: ${methodName}`);\n\t\t\t}\n\t\t}\n\n\t\tif (methodName !== 'insertSubscriptionLog' && methodName !== 'getDataURIfromURL' && methodName !== 'processAirdropDistribution' && methodName !== 'incCounter' && methodName !== 'supportCreateBillingUser' && methodName !== 'countCollectionWithQuery') {\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t) {\n\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\ttype: 'log',\n\t\t\t\t\tdata: {\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 1000000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\t\tmethodName: methodName,\n\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\tuser: this['user'] || '', \n\t\t\t\t\t\tmessageId: 0,\n\t\t\t\t\t\troute: ''\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tawait Logs.insertOne({\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\ttype: 'callMethod',\n\t\t\t\t\tcollection: '',\n\t\t\t\t\tid_document: '',\n\t\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 1000000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\t\tmethod: methodName,\n\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\tmessageId: 0,\n\t\t\t\t\troute: '',\n\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || ''\n\t\t\t\t})\n\t\t\t};\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\n\t\tconst session = ResolveIOServer.getMongoManager().getSession();\n\n\t\tif (!method.bypassSession &&\n\t\t\t!session && \n\t\t\t![\n\t\t\t\t'insertErrorLog', // CIRCULAR LOOP - DO NOT REMOVE\n\t\t\t\t'countWithQuery', // MONGO SESSIONS/TRANSACTIONS DONT WORTH WITH COUNTS\n\t\t\t\t'sendEmail' // ALWAYS SEND SO ALWAYS HAVE RECORD - DONT ROLL BACK - BYPASS SESSION\n\t\t\t].includes(methodName) &&\n\t\t\t!methodName.startsWith('monitor-') &&\n\t\t\t!methodName.startsWith('log')\n\t\t) {\n\t\t\tlet monitor = null;\n\t\t\t\n\t\t\treturn ResolveIOServer.getMongoManager().oneTimeTransaction(async () => {\n\t\t\t\tmonitor = this._monitorManagerFunction.startMonitorFunction('Method', methodName, this['user'] || '', '', functionMethodData);\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tlet res = await method.function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);\n\n\t\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\t\tmethodData[methodData.length - 1](null, res);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tif (err.code === 112 || err.codeName === 'WriteConflict' || err.code === 251 || err.codeName === 'NoSuchTransaction') {\n\t\t\t\t\t\tthrow err; // Write error, retry\n\t\t\t\t\t}\n\n\t\t\t\t\tconsole.log(JSON.stringify([new Date(), 'Error Method Manager - Run Method - New Session', methodName, {\n\t\t\t\t\t\tcode: err.code,\n\t\t\t\t\t\tcodeName: err.codeName,\n\t\t\t\t\t\tmessage: err.message,\n\t\t\t\t\t\tstack: err.stack\n\t\t\t\t\t}], null, 2));\n\n\t\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Method ' + methodName + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\t\terr.message = `${new Date().toISOString()} - Error in Method With Session (${methodName}) - New Session: ${err.message}`;\n\n\t\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\t\tmethodData[methodData.length - 1](err, null);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!process.env.IS_WORKER_INSTANCE) {\n\t\t\t\t\t\tawait this.callMethod('insertErrorLog', `Error in Method: ${methodName} - ${JSON.stringify(methodData, null, 2)}`);\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', methodName, this['user'] || '', '', functionMethodData);\n\t\t\t\n\t\t\ttry {\n\t\t\t\tlet res = await method.function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData);\n\n\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\tmethodData[methodData.length - 1](null, res);\n\t\t\t\t}\n\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tif (err.code === 112 || err.codeName === 'WriteConflict') {\n\t\t\t\t\tthrow err; // Write error, retry\n\t\t\t\t}\n\n\t\t\t\tconsole.log(JSON.stringify([new Date(), 'Error Method Manager - Run Method - Existing Session', methodName, {\n\t\t\t\t\tcode: err.code,\n\t\t\t\t\tcodeName: err.codeName,\n\t\t\t\t\tmessage: err.message,\n\t\t\t\t\tstack: err.stack\n\t\t\t\t}], null, 2));\n\n\t\t\t\tawait this.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], 'Error Detected During Method ' + methodName + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t\terr.message = `${new Date().toISOString()} - Error in Method (${methodName}) - Existing Session: ${err.message}`;\n\t\t\t\t\n\t\t\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\t\t\tmethodData[methodData.length - 1](err, null);\n\t\t\t\t}\n\n\t\t\t\tif (!process.env.IS_WORKER_INSTANCE) {\n\t\t\t\t\tawait this.callMethod('insertErrorLog', `Error in Method: ${methodName} - ${JSON.stringify(methodData, null, 2)}`);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tawait this._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync setupEmailWatcher() {\n\t\tconst changeStream = EmailHistories.watchCollection([]);\n\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending') {\n\t\t\t\tthis.emailQueue.add(change.fullDocument._id.toString());\n\t\t\t\tawait this.tryProcessEmail();\n\t\t\t}\n\t\t\telse if (change.operationType === 'update' || change.operationType === 'replace') {\n\t\t\t\tconst updatedEmail = change.fullDocument;\n\t\t\t\tif (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {\n\t\t\t\t\tthis.emailQueue.delete(updatedEmail._id.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.on('error', async err => {\n\t\t\tconsole.error('Email history changestream error', err);\n\t\t\tawait changeStream.close();\n\t\t})\n\t\t.on('close', async () => {\n\t\t\tawait this.setupEmailWatcher();\n\t\t});\n\n\t\tawait this.loadPendingEmails();\n\t}\n\n\tasync loadPendingEmails() {\n\t\t// Load any pending emails on startup\n\t\tconst pendingEmails = await EmailHistories.find({ status: 'pending' }, {sort: {_id: 1}});\n\t\tfor (const email of pendingEmails) {\n\t\t\tthis.emailQueue.add(email._id.toString());\n\t\t}\n\t\t// Try to process emails\n\t\tawait this.tryProcessEmail();\n\t}\n\n\tasync tryProcessEmail() {\n\t\tif (this.isEmailProcessing || this.emailQueue.size === 0) {\n\t\t\treturn;\n\t\t}\n\t\n\t\tthis.isEmailProcessing = true;\n\t\n\t\ttry {\n\t\t\twhile (this.emailQueue.size > 0) {\n\t\t\t\tconst emailId = this.emailQueue.values().next().value;\n\t\t\t\tthis.emailQueue.delete(emailId);\n\t\n\t\t\t\tconst emailHistory = await EmailHistories.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\t_id: emailId,\n\t\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$set: { status: 'processing', processingAt: new Date() },\n\t\t\t\t\t}\n\t\t\t\t);\n\t\n\t\t\t\tif (!emailHistory) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\n\t\t\t\t// Fetch and process attachments\n\t\t\t\tif (emailHistory.attachments && emailHistory.attachments.length > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (let att of emailHistory.attachments) {\n\t\t\t\t\t\t\tif (att.path && att.path.startsWith('http')) {\n\t\t\t\t\t\t\t\tconst response = await fetch(att.path);\n\t\t\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Failed to fetch attachment: ${att.path}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst arrayBuffer = await response.arrayBuffer();\n\t\t\t\t\t\t\t\tconst buffer = Buffer.from(arrayBuffer);\n\t\n\t\t\t\t\t\t\t\t// Check the size of the attachment\n\t\t\t\t\t\t\t\tconst maxSize = 20 * 1024 * 1024; // 20MB in bytes\n\t\t\t\t\t\t\t\tif (buffer.length <= maxSize) {\n\t\t\t\t\t\t\t\t\t// Attachment is within size limits, include it\n\t\t\t\t\t\t\t\t\tatt.content = buffer;\n\t\t\t\t\t\t\t\t\tdelete att.path;\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}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.error('Failed to fetch attachment:', err);\n\t\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\tcompletedAt: new 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\t// Skip to the next email\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t\t// Prepare email options\n\t\t\t\tconst mailOptions: any = {\n\t\t\t\t\treplyTo: emailHistory.reply_to || (ResolveIOServer.getServerConfig()['MAIL_REPLY_TO'] || undefined),\n\t\t\t\t\tfrom: emailHistory.send_from || ResolveIOServer.getServerConfig().MAIL_FROM,\n\t\t\t\t\tto: emailHistory.email,\n\t\t\t\t\tsubject:\n\t\t\t\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./)\n\t\t\t\t\t\t\t? '(DEV SERVER) - '\n\t\t\t\t\t\t\t: '') + emailHistory.subject,\n\t\t\t\t\ttext: typeof emailHistory.text === 'string' ? emailHistory.text : '',\n\t\t\t\t\thtml: typeof emailHistory.html === 'string' ? emailHistory.html : '',\n\t\t\t\t\tattachments: emailHistory.attachments || [],\n\t\t\t\t};\n\t\n\t\t\t\t// Process attachments before sending\n\t\t\t\tif (mailOptions.attachments && mailOptions.attachments.length > 0) {\n\t\t\t\t\tmailOptions.attachments = mailOptions.attachments.map((att) => {\n\t\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\t\t// Handle attachments stored as BinData or Buffer\n\t\t\t\t\t\tif (newAtt.content && typeof newAtt.content === 'object' && !(newAtt.content instanceof Buffer)) {\n\t\t\t\t\t\t\t// Convert MongoDB's Binary data to Buffer\n\t\t\t\t\t\t\tif (newAtt.content._bsontype === 'Binary' && newAtt.content.sub_type === 0) {\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content.buffer);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t// Handle other types if necessary\n\t\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Handle attachments stored as Base64 strings\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string' && newAtt.encoding === 'base64') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content, 'base64');\n\t\t\t\t\t\t\tdelete newAtt.encoding;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Ensure the content is a Buffer\n\t\t\t\t\t\telse if (typeof newAtt.content === 'string') {\n\t\t\t\t\t\t\tnewAtt.content = Buffer.from(newAtt.content);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn newAtt;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\n\t\t\t\t// Send the email\n\t\t\t\tthis._mailer.sendMail(mailOptions, async err => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.error('Failed to send email:', err);\n\t\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\t\terror: typeof err === 'string' ? err : this.safeStringify(err),\n\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t},\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\tif (emailHistory.email === 'dev@resolveio.com') {\n\t\t\t\t\t\t\t\tawait EmailHistories.deleteOne({ _id: emailHistory._id });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\t\t\t\t\t\tcompletedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\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}\n\t\t\t\t\tcatch (error) {\n\t\t\t\t\t\tconsole.error('Error in sendMail callback:', error);\n\t\t\t\t\t\tawait EmailHistories.updateOne(\n\t\t\t\t\t\t\t{ _id: emailHistory._id },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t\t\terror: typeof error === 'string' ? error : this.safeStringify(error),\n\t\t\t\t\t\t\t\t\tcompletedAt: new 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} \n\t\t\t\t});\n\t\n\t\t\t\t// Wait for at least one second before sending the next email\n\t\t\t\t// eslint-disable-next-line no-restricted-syntax\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Error processing email queue:', err);\n\t\t}\n\t\tfinally {\n\t\t\tthis.isEmailProcessing = false;\n\t\t\t// Check if new emails arrived while processing\n\t\t\tif (this.emailQueue.size > 0) {\n\t\t\t\tawait this.tryProcessEmail();\n\t\t\t}\n\t\t}\n\t}\n\n\tsafeStringify(obj)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn JSON.stringify(obj, this.getCircularReplacer());\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\treturn `Error in JSON stringifying: ${e.message}`;\n\t\t}\n\t}\n\n\tgetCircularReplacer()\n\t{\n\t\tconst seen = new WeakSet();\n\t\treturn (key, value) =>\n\t\t{\n\t\t\tif (typeof value === \"object\" && value !== null)\n\t\t\t{\n\t\t\t\tif (seen.has(value))\n\t\t\t\t{\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tseen.add(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t};\n\t}\n\n\tpublic async sendEmail(\n\t\tsendTo: string,\n\t\tsubject: string,\n\t\ttext?: string,\n\t\thtml?: string,\n\t\tattachments?: any[],\n\t\tsend_from?: string,\n\t\treply_to?: string,\n\t\tlocal_override = false\n\t) {\n\t\t// Modify sendTo in development environments\n\t\tif (\n\t\t\t(ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/dev\\./) ||\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\\/\\/www\\.dev\\./) ||\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200') &&\n\t\t\t!sendTo.match(/\\@resolveio\\.com/)\n\t\t) {\n\t\t\tsendTo = 'dev@resolveio.com';\n\t\t}\n\n\t\tif (sendTo) {\n\t\t\tif (\n\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200' ||\n\t\t\t\tlocal_override\n\t\t\t) {\n\t\t\t\tif (!attachments) {\n\t\t\t\t\tattachments = [];\n\t\t\t\t}\n\n\t\t\t\tif (!Array.isArray(attachments)) {\n\t\t\t\t\tattachments = [attachments];\n\t\t\t\t}\n\n\t\t\t\t// Process attachments before saving\n\t\t\t\tattachments = attachments.map((att) => {\n\t\t\t\t\tconst newAtt = { ...att };\n\t\t\t\t\tif (Buffer.isBuffer(newAtt.content)) {\n\t\t\t\t\t\tnewAtt.content = newAtt.content.toString('base64');\n\t\t\t\t\t\tnewAtt.encoding = 'base64';\n\t\t\t\t\t}\n\t\t\t\t\treturn newAtt;\n\t\t\t\t});\n\n\t\t\t\t// Queue the email in MongoDB\n\t\t\t\tconst emailHistory: EmailHistoryModel = {\n\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t__v: 0,\n\t\t\t\t\tdate: new Date(),\n\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\temail: sendTo,\n\t\t\t\t\tsubject: subject || '',\n\t\t\t\t\ttext: text || '',\n\t\t\t\t\thtml: html || '',\n\t\t\t\t\tattachments: attachments || [],\n\t\t\t\t\tsend_from: send_from || '',\n\t\t\t\t\treply_to: reply_to || '',\n\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\terror: ''\n\t\t\t\t};\n\n\t\t\t\ttry {\n\t\t\t\t\tlet history = await EmailHistories.insertOne(emailHistory);\n\t\t\t\t\treturn history;\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error('Failed to queue email:', err);\n\t\t\t\t\terr.message = `Failed to queue email: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log(\n\t\t\t\t\t'Send email',\n\t\t\t\t\tsendTo,\n\t\t\t\t\tsubject,\n\t\t\t\t\ttext,\n\t\t\t\t\thtml,\n\t\t\t\t\tattachments,\n\t\t\t\t\tsend_from\n\t\t\t\t);\n\t\t\t\t\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\ttry {\n\t\t\t\treturn fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'utf-8');\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\terr.message = `Error in readFile: ${err.message}`;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\ttry {\n\t\t\t\t\treturn fs.readFileSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'utf-8');\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\terr.message = `Error in readFile: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error ('Error in readFile: File Not Found');\n\t}\n\n\tpublic readImage(fileName) {\n\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\ttry {\n\t\t\t\treturn fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'base64');\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\terr.message = `Error in readImage: ${err.message}`;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (fs.existsSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {\n\t\t\t\ttry {\n\t\t\t\t\treturn fs.readFileSync(path.join(ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'base64');\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\terr.message = `Error in readImage: ${err.message}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error ('Error in readImage: File Not Found');\n\t}\n}"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@resolveio/server-lib",
3
- "version": "20.7.106",
3
+ "version": "20.7.108",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "package": "./build_package.sh",
package/server-app.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,n,s,o){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((o=o.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,s){var o,i,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(t){return function(e){var r=[t,e];if(o)throw new TypeError("Generator is already executing.");for(;c=l&&r[l=0]?0:c;)try{if(o=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return c.label++,{value:r[1],done:!1};case 5:c.label++,i=r[1],r=[0];continue;case 7:r=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){c=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))c.label=r[1];else if(6===r[0]&&c.label<a[1])c.label=a[1],a=r;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(r)}}r=s.call(n,c)}catch(e){r=[6,e],i=0}finally{o=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var n,s,o=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(n=o.next()).done;)i.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(t=o.return)&&t.call(o)}finally{if(s)throw s.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var n,s=0,o=r.length;s<o;s++)!n&&s in r||((n=n||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(n||Array.prototype.slice.call(r))},bodyParser=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("body-parser")),express=require("express"),xmlParser=require("express-xml-bodyparser"),http_1=require("http"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),WebSocket=require("ws"),log_collection_1=require("./collections/log.collection"),user_collection_1=require("./collections/user.collection"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),monitor_manager_1=require("./managers/monitor.manager"),subscription_manager_1=require("./managers/subscription.manager"),common_1=require("./util/common"),mongodb_1=require("mongodb"),auth_1=require("./http/auth"),health_1=require("./http/health"),home_1=require("./http/home"),websocket_manager_1=require("./managers/websocket.manager"),worker_dispatcher_manager_1=require("./managers/worker-dispatcher.manager"),worker_server_manager_1=require("./managers/worker-server.manager"),resolveio_server_app_1=require("./resolveio-server-app"),ResolveIOMainServer=function(){function ResolveIOMainServer(){this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._safeShutdown=!1}return ResolveIOMainServer.create=function(){return __awaiter(this,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return[4,(r=new ResolveIOMainServer).initialize()];case 1:return e.sent(),[2,r]}})})},ResolveIOMainServer.prototype.initialize=function(){return __awaiter(this,void 0,void 0,function(){var r,o,i=this;return __generator(this,function(e){switch(e.label){case 0:return this._serverStartTime=new Date,this._lastErrorMsg=null,r=this,[4,monitor_manager_1.MonitorManager.create()];case 1:return r._monitorManager=e.sent(),this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){i._subscriptionManager&&i._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",i._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",i._debugMsgQueue)),i._debugMsgQueue=0,i._debugMsgRecv=0},6e4),o=!1,setTimeout(function(){o=!0},5e3),process.removeAllListeners("unhandledRejection"),process.on("unhandledRejection",function(n,s){return __awaiter(i,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return!n||"MongoError"!==n.name||48!==n.code&&26!==n.code&&11e3!==n.code&&251!==n.code?!n||"MongoServerError"!==n.name||o&&26!==n.code&&11e3!==n.code&&86!==n.code&&251!==n.code?(console.error(new Date,"Unhandled Rejection at Promise",[n,s]),r=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.stack},null,2))]):[3,2]:[3,3]):[2]:[2];case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,11];case 3:return n&&"MongoError"===n.name&&"not master"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,11];case 6:return n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,11];case 9:return n?"StatusError"!==n.name&&""!==n.message&&60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,11]:[3,11];case 10:e.sent(),e.label=11;case 11:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(i,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){return __awaiter(i,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),process.on("SIGTERM",function(){return __awaiter(i,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),process.on("SIGQUIT",function(){return __awaiter(i,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance",process.env.NODE_APP_INSTANCE),this._methodManager=method_manager_1.MethodManager.create(null,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._workerServerManager=worker_server_manager_1.WorkerServerManager.create(this._methodManager,this.getServerConfig()),"0"===process.env.WORKER_INDEX&&(this._cronManager=cron_manager_1.CronManager.create())):(console.log("Running as a Server instance",process.env.NODE_APP_INSTANCE),this._websocketManager=websocket_manager_1.WebSocketManager.create(this),this._methodManager=method_manager_1.MethodManager.create(this._websocketManager,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._workerDispatcherManager=worker_dispatcher_manager_1.WorkerDispatcherManager.create(this._websocketManager,this._methodManager),this._subscriptionManager=subscription_manager_1.SubscriptionManager.create(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.startServerInstance(),this.listen()):(console.log("Running with Workers Disabled",process.env.NODE_APP_INSTANCE),this._websocketManager=websocket_manager_1.WebSocketManager.create(this),this._methodManager=method_manager_1.MethodManager.create(this._websocketManager,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=subscription_manager_1.SubscriptionManager.create(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=cron_manager_1.CronManager.create(),this.startServerInstance(),this.listen()),[2]}})})},ResolveIOMainServer.prototype.startServerInstance=function(){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.NODE_APP_INSTANCE?parseInt("808"+process.env.NODE_APP_INSTANCE):8080,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),(0,health_1.setupHealthRoutes)(this._app),"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.safeShutdown=function(){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:if(this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length||this._workerDispatcherManager&&!this._workerDispatcherManager.isSafeShutdown())return[3,7];if(!resolveio_server_app_1.ResolveIOServer.getMongoConnection())return[3,5];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1)];case 2:return e.sent(),console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0),[3,4];case 3:return e.sent(),process.exit(1),[3,4];case 4:return[3,6];case 5:process.exit(0),e.label=6;case 6:return[3,8];case 7:this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){r._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){return __awaiter(r,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),e.label=8;case 8:return[2]}})})},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var r=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({server:this._serverHTTP,verifyClient:this.publicProgram?null:function(s,o){var e;r._rebootFlag?o(!1,409,"Unable To Process"):("DEBUG"===r.LOGGER&&console.log("Verify Client",s,o),s.req.url&&s.req.url.includes("workerToken=")?(s.req.url.split("workerToken=")[1]||"")===resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN?o(!0):o(!1,401,"Unauthorized"):(e=s.req.headers["sec-websocket-protocol"].split(/,/),(s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().SEC_ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_SECONDARY_URL)&&(e=e[0])?jwt.verify(e,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,n){return __awaiter(r,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(o(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:s.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(r=e.sent())?(s.req.user=r.fullname,s.req.user_readonly=r.readonly||!1,s.req.doc_user=r,o(!0)):o(!1),[3,5];case 4:return e.sent(),o(!1),[3,5];case 5:return[2]}})})}):o(!1,401,"Unauthorized")))}})},ResolveIOMainServer.prototype.listen=function(){var e=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running HTTP/WS server on port %s",e._portHTTP)}),this._serverWSS.on("connection",function(o,i){return __awaiter(e,void 0,void 0,function(){var r,t,n,s=this;return __generator(this,function(e){switch(e.label){case 0:return i.url&&i.url.includes("workerToken=")?(r=(0,common_1.objectIdHexString)(),o.id_worker=r,console.log(new Date,process.env.NODE_APP_INSTANCE,"Worker Connected",process.env.NODE_APP_INSTANCE),this._workerDispatcherManager.addWorker(o),n=null,this._workerDispatcherManager.sendWorkerPayload(o,"ping"),t=setInterval(function(){n?(n=null,s._workerDispatcherManager.sendWorkerPayload(o,"ping")):(s._workerDispatcherManager.disconnectWorker(o.id_worker),o.close())},3e4),o.on("message",function(e){"ping"===(e="string"!=typeof e?e.toString():e)?s._workerDispatcherManager.sendWorkerPayload(o,"pong"):"pong"===e?n=new Date:s._workerDispatcherManager.handleWorkerMessage(o.id_worker,e)}),o.on("close",function(){s._workerDispatcherManager.disconnectWorker(o.id_worker),console.log(new Date,"Worker disconnected:",r),t&&clearInterval(t)}),o.on("error",function(e){s._workerDispatcherManager.disconnectWorker(o.id_worker),console.error("Error on WS Worker",e),o.close()}),[3,3]):[3,1];case 1:return o.id_socket=(0,common_1.objectIdHexString)(),o.id_user=i.id_user,o.user=i.user,o.user_readonly=i.user_readonly,o.doc_user=i.doc_user,this._websocketManager.addWebSocket(o),[4,this._subscriptionManager.createLoggedInUser(o.id_socket)];case 2:e.sent(),setTimeout(function(){o.pingTime=new Date,o.send("ping",function(r){return __awaiter(s,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(o)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})})},5e3),"DEBUG"===this.LOGGER&&console.log("Connection from user: "+i.user),o.isAlive=!0,o.retryCnt=0,o.on("message",function(n){return __awaiter(s,void 0,void 0,function(){var r,t;return __generator(this,function(e){switch(e.label){case 0:this._debugMsgRecv+=1,r=[],e.label=1;case 1:return e.trys.push([1,2,,4]),r=JSON.parse(n,common_1.dateReviver),[3,4];case 2:return t=e.sent(),console.log("Error - JSON.parse",n),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n,t]))];case 3:return e.sent(),[2];case 4:return[4,this.processSocketMessage(o,r)];case 5:return e.sent(),[2]}})})}).on("end",function(){o.close()}).on("error",function(){o.close()}).on("close",function(){return __awaiter(s,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.unsubscribeWS(o)];case 1:return e.sent(),[2]}})})}),e.label=3;case 3:return[2]}})})}),setInterval(function(){return __awaiter(e,void 0,void 0,function(){var r,n,t,s,o,i,a,c=this;return __generator(this,function(e){switch(e.label){case 0:r=function(t){return __generator(this,function(e){switch(e.label){case 0:return t.pingTime&&2e4<=Date.now()-t.pingTime.getTime()?!1!==t.isAlive?[3,4]:(t.retryCnt++,3<=t.retryCnt?[4,n.unsubscribeWS(t)]:[3,2]):[3,5];case 1:return e.sent(),[3,3];case 2:t.pingTime=new Date,t.send("ping",function(r){return __awaiter(c,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(t)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),e.label=3;case 3:return[3,5];case 4:t.retryCnt=0,t.isAlive=!1,t.pingTime=new Date,t.send("ping",function(r){return __awaiter(c,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(t)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),e.label=5;case 5:return[2]}})},n=this,e.label=1;case 1:e.trys.push([1,6,7,8]),t=__values(this._serverWSS.clients),s=t.next(),e.label=2;case 2:return s.done?[3,5]:(o=s.value,[5,r(o)]);case 3:e.sent(),e.label=4;case 4:return s=t.next(),[3,2];case 5:return[3,8];case 6:return o=e.sent(),i={error:o},[3,8];case 7:try{s&&!s.done&&(a=t.return)&&a.call(t)}finally{if(i)throw i.error}return[7];case 8:return[2]}})})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(i,a){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o;return __generator(this,function(e){switch(e.label){case 0:if("string"==typeof a&&"ping"===a)return i&&i.readyState===i.OPEN&&i.send("pong"),[2];if("string"==typeof a&&"pong"===a)return i.isAlive=!0,i.pongTime=new Date,i.latency=moment.duration(moment(i.pongTime).diff(i.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(i),[2];if(!Array.isArray(a[0]))return console.log("Invalid message format (expected array of arrays)",a),[2];e.label=1;case 1:e.trys.push([1,6,7,8]),r=__values(a),t=r.next(),e.label=2;case 2:return t.done?[3,5]:(n=t.value,[4,this.handleClientMessage(i,n)]);case 3:e.sent(),e.label=4;case 4:return t=r.next(),[3,2];case 5:return[3,8];case 6:return n=e.sent(),s={error:n},[3,8];case 7:try{t&&!t.done&&(o=r.return)&&o.call(r)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})},ResolveIOMainServer.prototype.handleClientMessage=function(p,f){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,c,l,u,_,g,h,d,v;return __generator(this,function(e){switch(e.label){case 0:return(r=f[0],t=f[1],n=f[2],s=f[3],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||p.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||p.doc_user.roles.super_admin)?"subscription"!==s?[3,4]:(i=f[4],o=f[5],"sub"!==i?[3,2]:[4,this._subscriptionManager.subscribe(r,t,p,n,o,f.slice(6))]):[2];case 1:return e.sent(),[3,3];case 2:this._subscriptionManager.unsubscribe(r,t,p,n,o,f.slice(6)),e.label=3;case 3:return[3,22];case 4:if(this.publicProgram||"offline"!==s)return[3,16];i={messageId:n,hasError:!1,data:"ACK"},p&&p.readyState===p.OPEN&&this._websocketManager.send(p,i),this._offlineUpdates.push(p),a=f[4],c=0,e.label=5;case 5:if(!(c<a.length))return[3,15];if(l=a[c],l=l.data,l.shift(),l.shift(),v=l.shift(),l.shift(),d=l.shift(),v={messageId:v,hasError:!1,data:"ACK"},p&&p.readyState===p.OPEN&&this._websocketManager.send(p,v),"insertDocument"===d&&"driver-gps"===l[0])return[3,14];if("reportBuilderGetResults"!==d&&"reportBuilderGetDistinctValue"!==d&&"reportBuilderBuildTree"!==d&&"generatePDF"!==d&&"getWOOfflineData"!==d&&"countQuery"!==d&&"countWithQuery"!==d&&"countCollectionWithQuery"!==d&&"find"!==d&&"findOne"!==d&&"findWithOptions"!==d&&"getDrivers"!==d&&"processAirdropDistribution"!==d&&"qbHandleResponse"!==d){if("https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL)return[3,6];resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([l]))<1e6?JSON.stringify([l],null,2):"Too Big",method:d,id_user:p.id_user||"",user:p.user||"",messageId:n,route:r}})}return[3,8];case 6:return[4,log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([l]))<1e6?JSON.stringify([l],null,2):"Too Big",method:d,id_user:p.id_user||"",user:p.user||"",messageId:n,route:r,client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 7:e.sent(),e.label=8;case 8:if(!this._methodManager._methods[d])return[3,13];e.label=9;case 9:return e.trys.push([9,11,,12]),[4,(v=this._methodManager.callMethod).call.apply(v,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:p.id_user,user:p.user,id_ws:p.id_socket}),d],__read(l),!1))];case 10:return e.sent(),[3,12];case 11:return h=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(h,null,2)),[3,12];case 12:return"updateDocumentOffline"!==d&&"updateDocumentPropsOffline"!==d||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l[0]),[3,14];case 13:console.log("Offline - Could not find method: "+d),e.label=14;case 14:return c++,[3,5];case 15:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(p.id_socket),1),[3,22];case 16:if(u=__spreadArray([],__read(f),!1),u.shift(),u.shift(),_=u.shift(),"method"!==u.shift())return[3,22];if(g=u.shift(),p.user_readonly)return[2];if("reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g){if("https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL)return[3,17];resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([u]))<1e6?JSON.stringify([u],null,2):"Too Big",method:g,id_user:p.id_user||"",user:p.user||"",messageId:n,route:r}})}return[3,19];case 17:return[4,log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([u]))<1e6?JSON.stringify([u],null,2):"Too Big",method:g,id_user:p.id_user||"",user:p.user||"",messageId:n,route:r,client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 18:e.sent(),e.label=19;case 19:return(h={messageId:_,hasError:!1,data:"ACK"},p&&p.readyState===p.OPEN&&this._websocketManager.send(p,h),(d=this._methodManager.getMethod(g))&&!d.skipWorker&&this._isWorkersEnabled&&"find"!==g&&"insertDocument"!==g&&"countWithQuery"!==g&&"findOne"!==g&&"updateDocumentProps"!==g&&"findWithOptions"!==g&&"updateDocument"!==g&&"insertErrorLog"!==g&&"removeDocument"!==g&&"supportCreateBillingUser"!==g&&"getSignedUrl"!==g&&"getSignedUrls"!==g&&"getSignedUrlWithId"!==g&&"incorrectUser"!==g&&"reloadWS"!==g&&"reconnectWS"!==g&&"disconnectWS"!==g)?(this._workerDispatcherManager.sendClientTask(_,g,u,{id_user:p.id_user,user:p.user,id_ws:p.id_socket}),[3,22]):[3,20];case 20:return[4,this.callMethodLocally(p,_,g,u)];case 21:e.sent(),e.label=22;case 22:return[2]}})})},ResolveIOMainServer.prototype.callMethodLocally=function(s,o,i,a){return __awaiter(this,void 0,void 0,function(){var r,t,n;return __generator(this,function(e){switch(e.label){case 0:r={messageId:o,hasError:!1,data:null},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(n=this._methodManager.callMethod).call.apply(n,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:s.id_user,user:s.user,id_ws:s.id_socket}),i],__read(a),!1))];case 2:return n=e.sent(),r.data=n,[3,4];case 3:return t=e.sent(),r.hasError=!0,r.data=t||"Unknown error",[3,4];case 4:return s&&s.readyState===s.OPEN&&this._websocketManager.send(s,r),[2]}})})},ResolveIOMainServer.prototype.unsubscribeWS=function(r){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._subscriptionManager&&this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",r.user,r.id_socket),[4,this._subscriptionManager.unsubscribeAll(r)];case 1:return e.sent(),r.removeAllListeners(),r=null,[2]}})})},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return resolveio_server_app_1.ResolveIOServer.getServerConfig()},ResolveIOMainServer.prototype.getWorkerDispatcherManager=function(){return this._workerDispatcherManager},ResolveIOMainServer.prototype.getWorkerServerManager=function(){return this._workerServerManager},ResolveIOMainServer}();exports.ResolveIOMainServer=ResolveIOMainServer;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,n,s,o){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((o=o.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,s){var o,i,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(t){return function(e){var r=[t,e];if(o)throw new TypeError("Generator is already executing.");for(;c=l&&r[l=0]?0:c;)try{if(o=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return c.label++,{value:r[1],done:!1};case 5:c.label++,i=r[1],r=[0];continue;case 7:r=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){c=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))c.label=r[1];else if(6===r[0]&&c.label<a[1])c.label=a[1],a=r;else{if(!(a&&c.label<a[2])){a[2]&&c.ops.pop(),c.trys.pop();continue}c.label=a[2],c.ops.push(r)}}r=s.call(n,c)}catch(e){r=[6,e],i=0}finally{o=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var n,s,o=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(n=o.next()).done;)i.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(t=o.return)&&t.call(o)}finally{if(s)throw s.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var n,s=0,o=r.length;s<o;s++)!n&&s in r||((n=n||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(n||Array.prototype.slice.call(r))},bodyParser=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("body-parser")),express=require("express"),xmlParser=require("express-xml-bodyparser"),http_1=require("http"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),WebSocket=require("ws"),log_collection_1=require("./collections/log.collection"),user_collection_1=require("./collections/user.collection"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),monitor_manager_1=require("./managers/monitor.manager"),subscription_manager_1=require("./managers/subscription.manager"),common_1=require("./util/common"),mongodb_1=require("mongodb"),auth_1=require("./http/auth"),health_1=require("./http/health"),home_1=require("./http/home"),websocket_manager_1=require("./managers/websocket.manager"),worker_dispatcher_manager_1=require("./managers/worker-dispatcher.manager"),worker_server_manager_1=require("./managers/worker-server.manager"),resolveio_server_app_1=require("./resolveio-server-app"),ResolveIOMainServer=function(){function ResolveIOMainServer(){this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._safeShutdown=!1}return ResolveIOMainServer.create=function(){return __awaiter(this,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return[4,(r=new ResolveIOMainServer).initialize()];case 1:return e.sent(),[2,r]}})})},ResolveIOMainServer.prototype.initialize=function(){return __awaiter(this,void 0,void 0,function(){var r,o,i=this;return __generator(this,function(e){switch(e.label){case 0:return this._serverStartTime=new Date,this._lastErrorMsg=null,r=this,[4,monitor_manager_1.MonitorManager.create()];case 1:return r._monitorManager=e.sent(),this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){i._subscriptionManager&&i._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",i._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",i._debugMsgQueue)),i._debugMsgQueue=0,i._debugMsgRecv=0},6e4),o=!1,setTimeout(function(){o=!0},5e3),process.removeAllListeners("unhandledRejection"),process.on("unhandledRejection",function(n,s){return __awaiter(i,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return(this._subscriptionManager.getEnableDebug()&&console.error(new Date,"ERROR DETECTED w/ Debug Flag Active: unhandledRejection",[n,s]),!n||"MongoError"!==n.name||48!==n.code&&26!==n.code&&11e3!==n.code&&251!==n.code)?!n||"MongoServerError"!==n.name||o&&26!==n.code&&11e3!==n.code&&86!==n.code&&251!==n.code?(console.error(new Date,"Unhandled Rejection at Promise",[n,s]),r=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.stack},null,2))]):[3,2]:[3,3]):[2]:[2];case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,11];case 3:return n&&"MongoError"===n.name&&"not master"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,11];case 6:return n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,11];case 9:return n?"StatusError"!==n.name&&""!==n.message&&60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,11]:[3,11];case 10:e.sent(),e.label=11;case 11:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(i,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){return __awaiter(i,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),process.on("SIGTERM",function(){return __awaiter(i,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),process.on("SIGQUIT",function(){return __awaiter(i,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._rebootFlag=!0,this._serverHTTP&&this._serverHTTP.close(),[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance",process.env.NODE_APP_INSTANCE),this._methodManager=method_manager_1.MethodManager.create(null,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._workerServerManager=worker_server_manager_1.WorkerServerManager.create(this._methodManager,this.getServerConfig()),"0"===process.env.WORKER_INDEX&&(this._cronManager=cron_manager_1.CronManager.create())):(console.log("Running as a Server instance",process.env.NODE_APP_INSTANCE),this._websocketManager=websocket_manager_1.WebSocketManager.create(this),this._methodManager=method_manager_1.MethodManager.create(this._websocketManager,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._workerDispatcherManager=worker_dispatcher_manager_1.WorkerDispatcherManager.create(this._websocketManager,this._methodManager),this._subscriptionManager=subscription_manager_1.SubscriptionManager.create(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.startServerInstance(),this.listen()):(console.log("Running with Workers Disabled",process.env.NODE_APP_INSTANCE),this._websocketManager=websocket_manager_1.WebSocketManager.create(this),this._methodManager=method_manager_1.MethodManager.create(this._websocketManager,this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=subscription_manager_1.SubscriptionManager.create(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=cron_manager_1.CronManager.create(),this.startServerInstance(),this.listen()),[2]}})})},ResolveIOMainServer.prototype.startServerInstance=function(){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.NODE_APP_INSTANCE?parseInt("808"+process.env.NODE_APP_INSTANCE):8080,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),(0,health_1.setupHealthRoutes)(this._app),"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.safeShutdown=function(){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:if(this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length||this._workerDispatcherManager&&!this._workerDispatcherManager.isSafeShutdown())return[3,7];if(!resolveio_server_app_1.ResolveIOServer.getMongoConnection())return[3,5];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1)];case 2:return e.sent(),console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0),[3,4];case 3:return e.sent(),process.exit(1),[3,4];case 4:return[3,6];case 5:process.exit(0),e.label=6;case 6:return[3,8];case 7:this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){r._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){return __awaiter(r,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.safeShutdown()];case 1:return e.sent(),[2]}})})}),e.label=8;case 8:return[2]}})})},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var r=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({server:this._serverHTTP,verifyClient:this.publicProgram?null:function(s,o){var e;r._rebootFlag?o(!1,409,"Unable To Process"):("DEBUG"===r.LOGGER&&console.log("Verify Client",s,o),s.req.url&&s.req.url.includes("workerToken=")?(s.req.url.split("workerToken=")[1]||"")===resolveio_server_app_1.ResolveIOServer.getServerConfig().WORKER_TOKEN?o(!0):o(!1,401,"Unauthorized"):(e=s.req.headers["sec-websocket-protocol"].split(/,/),(s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().SEC_ROOT_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_URL||s.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_SECONDARY_URL)&&(e=e[0])?jwt.verify(e,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,n){return __awaiter(r,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(o(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:s.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(r=e.sent())?(s.req.user=r.fullname,s.req.user_readonly=r.readonly||!1,s.req.doc_user=r,o(!0)):o(!1),[3,5];case 4:return e.sent(),o(!1),[3,5];case 5:return[2]}})})}):o(!1,401,"Unauthorized")))}})},ResolveIOMainServer.prototype.listen=function(){var e=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running HTTP/WS server on port %s",e._portHTTP)}),this._serverWSS.on("connection",function(o,i){return __awaiter(e,void 0,void 0,function(){var r,t,n,s=this;return __generator(this,function(e){switch(e.label){case 0:return i.url&&i.url.includes("workerToken=")?(r=(0,common_1.objectIdHexString)(),o.id_worker=r,console.log(new Date,process.env.NODE_APP_INSTANCE,"Worker Connected",process.env.NODE_APP_INSTANCE),this._workerDispatcherManager.addWorker(o),n=null,this._workerDispatcherManager.sendWorkerPayload(o,"ping"),t=setInterval(function(){n?(n=null,s._workerDispatcherManager.sendWorkerPayload(o,"ping")):(s._workerDispatcherManager.disconnectWorker(o.id_worker),o.close())},3e4),o.on("message",function(e){"ping"===(e="string"!=typeof e?e.toString():e)?s._workerDispatcherManager.sendWorkerPayload(o,"pong"):"pong"===e?n=new Date:s._workerDispatcherManager.handleWorkerMessage(o.id_worker,e)}),o.on("close",function(){s._workerDispatcherManager.disconnectWorker(o.id_worker),console.log(new Date,"Worker disconnected:",r),t&&clearInterval(t)}),o.on("error",function(e){s._workerDispatcherManager.disconnectWorker(o.id_worker),console.error("Error on WS Worker",e),o.close()}),[3,3]):[3,1];case 1:return o.id_socket=(0,common_1.objectIdHexString)(),o.id_user=i.id_user,o.user=i.user,o.user_readonly=i.user_readonly,o.doc_user=i.doc_user,this._websocketManager.addWebSocket(o),[4,this._subscriptionManager.createLoggedInUser(o.id_socket)];case 2:e.sent(),setTimeout(function(){o.pingTime=new Date,o.send("ping",function(r){return __awaiter(s,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(o)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})})},5e3),"DEBUG"===this.LOGGER&&console.log("Connection from user: "+i.user),o.isAlive=!0,o.retryCnt=0,o.on("message",function(n){return __awaiter(s,void 0,void 0,function(){var r,t;return __generator(this,function(e){switch(e.label){case 0:this._debugMsgRecv+=1,r=[],e.label=1;case 1:return e.trys.push([1,2,,4]),r=JSON.parse(n,common_1.dateReviver),[3,4];case 2:return t=e.sent(),console.log("Error - JSON.parse",n),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n,t]))];case 3:return e.sent(),[2];case 4:return[4,this.processSocketMessage(o,r)];case 5:return e.sent(),[2]}})})}).on("end",function(){o.close()}).on("error",function(){o.close()}).on("close",function(){return __awaiter(s,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.unsubscribeWS(o)];case 1:return e.sent(),[2]}})})}),e.label=3;case 3:return[2]}})})}),setInterval(function(){return __awaiter(e,void 0,void 0,function(){var r,n,t,s,o,i,a,c=this;return __generator(this,function(e){switch(e.label){case 0:r=function(t){return __generator(this,function(e){switch(e.label){case 0:return t.pingTime&&2e4<=Date.now()-t.pingTime.getTime()?!1!==t.isAlive?[3,4]:(t.retryCnt++,3<=t.retryCnt?[4,n.unsubscribeWS(t)]:[3,2]):[3,5];case 1:return e.sent(),[3,3];case 2:t.pingTime=new Date,t.send("ping",function(r){return __awaiter(c,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(t)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),e.label=3;case 3:return[3,5];case 4:t.retryCnt=0,t.isAlive=!1,t.pingTime=new Date,t.send("ping",function(r){return __awaiter(c,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return r?(this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),[4,this.unsubscribeWS(t)]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),e.label=5;case 5:return[2]}})},n=this,e.label=1;case 1:e.trys.push([1,6,7,8]),t=__values(this._serverWSS.clients),s=t.next(),e.label=2;case 2:return s.done?[3,5]:(o=s.value,[5,r(o)]);case 3:e.sent(),e.label=4;case 4:return s=t.next(),[3,2];case 5:return[3,8];case 6:return o=e.sent(),i={error:o},[3,8];case 7:try{s&&!s.done&&(a=t.return)&&a.call(t)}finally{if(i)throw i.error}return[7];case 8:return[2]}})})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(i,a){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o;return __generator(this,function(e){switch(e.label){case 0:if("string"==typeof a&&"ping"===a)return i&&i.readyState===i.OPEN&&i.send("pong"),[2];if("string"==typeof a&&"pong"===a)return i.isAlive=!0,i.pongTime=new Date,i.latency=moment.duration(moment(i.pongTime).diff(i.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(i),[2];if(!Array.isArray(a[0]))return console.log("Invalid message format (expected array of arrays)",a),[2];e.label=1;case 1:e.trys.push([1,6,7,8]),r=__values(a),t=r.next(),e.label=2;case 2:return t.done?[3,5]:(n=t.value,[4,this.handleClientMessage(i,n)]);case 3:e.sent(),e.label=4;case 4:return t=r.next(),[3,2];case 5:return[3,8];case 6:return n=e.sent(),s={error:n},[3,8];case 7:try{t&&!t.done&&(o=r.return)&&o.call(r)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})},ResolveIOMainServer.prototype.handleClientMessage=function(p,f){return __awaiter(this,void 0,void 0,function(){var r,t,n,s,o,i,a,c,l,u,_,g,h,d,v;return __generator(this,function(e){switch(e.label){case 0:return(r=f[0],t=f[1],n=f[2],s=f[3],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||p.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||p.doc_user.roles.super_admin)?"subscription"!==s?[3,4]:(i=f[4],o=f[5],"sub"!==i?[3,2]:[4,this._subscriptionManager.subscribe(r,t,p,n,o,f.slice(6))]):[2];case 1:return e.sent(),[3,3];case 2:this._subscriptionManager.unsubscribe(r,t,p,n,o,f.slice(6)),e.label=3;case 3:return[3,22];case 4:if(this.publicProgram||"offline"!==s)return[3,16];i={messageId:n,hasError:!1,data:"ACK"},p&&p.readyState===p.OPEN&&this._websocketManager.send(p,i),this._offlineUpdates.push(p),a=f[4],c=0,e.label=5;case 5:if(!(c<a.length))return[3,15];if(l=a[c],l=l.data,l.shift(),l.shift(),v=l.shift(),l.shift(),d=l.shift(),v={messageId:v,hasError:!1,data:"ACK"},p&&p.readyState===p.OPEN&&this._websocketManager.send(p,v),"insertDocument"===d&&"driver-gps"===l[0])return[3,14];if("reportBuilderGetResults"!==d&&"reportBuilderGetDistinctValue"!==d&&"reportBuilderBuildTree"!==d&&"generatePDF"!==d&&"getWOOfflineData"!==d&&"countQuery"!==d&&"countWithQuery"!==d&&"countCollectionWithQuery"!==d&&"find"!==d&&"findOne"!==d&&"findWithOptions"!==d&&"getDrivers"!==d&&"processAirdropDistribution"!==d&&"qbHandleResponse"!==d){if("https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL)return[3,6];resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([l]))<1e6?JSON.stringify([l],null,2):"Too Big",method:d,id_user:p.id_user||"",user:p.user||"",messageId:n,route:r}})}return[3,8];case 6:return[4,log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([l]))<1e6?JSON.stringify([l],null,2):"Too Big",method:d,id_user:p.id_user||"",user:p.user||"",messageId:n,route:r,client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 7:e.sent(),e.label=8;case 8:if(!this._methodManager._methods[d])return[3,13];e.label=9;case 9:return e.trys.push([9,11,,12]),[4,(v=this._methodManager.callMethod).call.apply(v,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:p.id_user,user:p.user,id_ws:p.id_socket}),d],__read(l),!1))];case 10:return e.sent(),[3,12];case 11:return h=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(h,null,2)),[3,12];case 12:return"updateDocumentOffline"!==d&&"updateDocumentPropsOffline"!==d||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(l[0]),[3,14];case 13:console.log("Offline - Could not find method: "+d),e.label=14;case 14:return c++,[3,5];case 15:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(p.id_socket),1),[3,22];case 16:if(u=__spreadArray([],__read(f),!1),u.shift(),u.shift(),_=u.shift(),"method"!==u.shift())return[3,22];if(g=u.shift(),p.user_readonly)return[2];if("reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g){if("https://resolveio.com"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||"http://localhost:4200"===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL)return[3,17];resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log",data:{_id:(0,common_1.objectIdHexString)(),createdAt:new Date,type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([u]))<1e6?JSON.stringify([u],null,2):"Too Big",method:g,id_user:p.id_user||"",user:p.user||"",messageId:n,route:r}})}return[3,19];case 17:return[4,log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([u]))<1e6?JSON.stringify([u],null,2):"Too Big",method:g,id_user:p.id_user||"",user:p.user||"",messageId:n,route:r,client:"ResolveIO",instance:"backend.resolveio.com",instance_index:process.env.NODE_APP_INSTANCE||""})];case 18:e.sent(),e.label=19;case 19:return(h={messageId:_,hasError:!1,data:"ACK"},p&&p.readyState===p.OPEN&&this._websocketManager.send(p,h),(d=this._methodManager.getMethod(g))&&!d.skipWorker&&this._isWorkersEnabled&&"find"!==g&&"insertDocument"!==g&&"countWithQuery"!==g&&"findOne"!==g&&"updateDocumentProps"!==g&&"findWithOptions"!==g&&"updateDocument"!==g&&"insertErrorLog"!==g&&"removeDocument"!==g&&"supportCreateBillingUser"!==g&&"getSignedUrl"!==g&&"getSignedUrls"!==g&&"getSignedUrlWithId"!==g&&"incorrectUser"!==g&&"reloadWS"!==g&&"reconnectWS"!==g&&"disconnectWS"!==g)?(this._workerDispatcherManager.sendClientTask(_,g,u,{id_user:p.id_user,user:p.user,id_ws:p.id_socket}),[3,22]):[3,20];case 20:return[4,this.callMethodLocally(p,_,g,u)];case 21:e.sent(),e.label=22;case 22:return[2]}})})},ResolveIOMainServer.prototype.callMethodLocally=function(s,o,i,a){return __awaiter(this,void 0,void 0,function(){var r,t,n;return __generator(this,function(e){switch(e.label){case 0:r={messageId:o,hasError:!1,data:null},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(n=this._methodManager.callMethod).call.apply(n,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:s.id_user,user:s.user,id_ws:s.id_socket}),i],__read(a),!1))];case 2:return n=e.sent(),r.data=n,[3,4];case 3:return t=e.sent(),r.hasError=!0,r.data=t||"Unknown error",[3,4];case 4:return s&&s.readyState===s.OPEN&&this._websocketManager.send(s,r),[2]}})})},ResolveIOMainServer.prototype.unsubscribeWS=function(r){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this._subscriptionManager&&this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",r.user,r.id_socket),[4,this._subscriptionManager.unsubscribeAll(r)];case 1:return e.sent(),r.removeAllListeners(),r=null,[2]}})})},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return resolveio_server_app_1.ResolveIOServer.getServerConfig()},ResolveIOMainServer.prototype.getWorkerDispatcherManager=function(){return this._workerDispatcherManager},ResolveIOMainServer.prototype.getWorkerServerManager=function(){return this._workerServerManager},ResolveIOMainServer}();exports.ResolveIOMainServer=ResolveIOMainServer;
2
2
  //# sourceMappingURL=server-app.js.map
package/server-app.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server-app.ts"],"names":["bodyParser","require","express","xmlParser","http_1","jwt","moment","WebSocket","log_collection_1","user_collection_1","cron_manager_1","method_manager_1","monitor_manager_1","subscription_manager_1","common_1","mongodb_1","auth_1","health_1","home_1","websocket_manager_1","worker_dispatcher_manager_1","worker_server_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","create","resolveioMainServer","initialize","_a","sent","prototype","_serverStartTime","Date","MonitorManager","_monitorManager","_b","_monitorManagerFunction","MonitorManagerFunction","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_this","_subscriptionManager","getEnableDebug","console","log","initServerFlag","setTimeout","removeAllListeners","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","_methodManager","sendEmail","ResolveIOServer","getServerConfig","JSON","stringify","name","message","stack","exit","_serverHTTP","close","safeShutdown","NODE_APP_INSTANCE","MethodManager","_workerServerManager","WorkerServerManager","WORKER_INDEX","_cronManager","CronManager","_websocketManager","WebSocketManager","_workerDispatcherManager","WorkerDispatcherManager","SubscriptionManager","_serverWSS","startServerInstance","listen","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","parseInt","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","getActiveMonitorFunctions","length","isSafeShutdown","getMongoConnection","setImmediate","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","ws","push","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","server","verifyClient","info","cb","token","url","includes","split","infoData","headers","origin","verify","err","decoded","Users","findById","user","fullname","readonly","workerId_1","objectIdHexString","addWorker","lastComm_1","sendWorkerPayload","interval_1","disconnectWorker","toString","handleWorkerMessage","clearInterval","addWebSocket","createLoggedInUser","send","unsubscribeWS","socketData","parse","e_1","processSocketMessage","now","getTime","this_1","_e","__values","value","readyState","OPEN","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","socketData_1_1","handleClientMessage","msg","messageRoute","messageDate","messageId","type","some","a","roles","groups","views","b","super_admin","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","data","offlineUpdates","i","update","shift","updateMessageId","method","serverResMethod","getLocalLogManager","writeLog","_id","createdAt","collection","id_document","payload","getBinarySize","id_user","route","Logs","insertOne","client","instance","instance_index","_methods","callMethod","call","apply","__spreadArray","Object","assign","id_ws","__read","err_1","getMongoManager","invalidateQueryCache","splice","map","indexOf","dataCopy","msgId","methodName","ack","getMethod","skipWorker","sendClientTask","callMethodLocally","params","result","err_2","unsubscribeAll","getApp","getWorkerDispatcherManager","getWorkerServerManager","exports"],"mappings":"+xEAAAA,Y,0FAAAC,QAAA,aAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,UAAAF,QAAA,wBAAA,EACAG,OAAAH,QAAA,MAAA,EACAI,IAAAJ,QAAA,cAAA,EACAK,OAAAL,QAAA,iBAAA,EACAM,UAAAN,QAAA,IAAA,EAEAO,iBAAAP,QAAA,8BAAA,EACAQ,kBAAAR,QAAA,+BAAA,EACAS,eAAAT,QAAA,yBAAA,EACAU,iBAAAV,QAAA,2BAAA,EACAW,kBAAAX,QAAA,4BAAA,EACAY,uBAAAZ,QAAA,iCAAA,EAEAa,SAAAb,QAAA,eAAA,EAEAc,UAAAd,QAAA,SAAA,EACAe,OAAAf,QAAA,aAAA,EACAgB,SAAAhB,QAAA,eAAA,EACAiB,OAAAjB,QAAA,aAAA,EAEAkB,oBAAAlB,QAAA,8BAAA,EACAmB,4BAAAnB,QAAA,sCAAA,EACAoB,wBAAApB,QAAA,kCAAA,EACAqB,uBAAArB,QAAA,wBAAA,EAEAsB,oBAAA,WAkCC,SAAAA,sBA7BQC,KAAAC,gBAAkB,GACnBD,KAAAE,QAAU,CAAA,EACTF,KAAAG,gBAAkB,CAAA,EAClBH,KAAAI,cAAgB,CAAA,EAChBJ,KAAAK,YAAc,CAAA,EAEdL,KAAAM,OAAS,QAQTN,KAAAO,cAA0B,GAK1BP,KAAAQ,cAAsB,KAEtBR,KAAAS,cAAgB,EAChBT,KAAAU,eAAiB,EAEjBV,KAAAW,kBAAoB,CAAA,EACpBX,KAAAY,kBAAoB,CAAA,EAEpBZ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AAAA","file":"server-app.js","sourcesContent":["import * as bodyParser from 'body-parser';\nimport * as express from 'express';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport { createServer, Server } from 'http';\nimport * as jwt from 'jsonwebtoken';\nimport * as moment from 'moment-timezone';\nimport * as WebSocket from 'ws';\n\nimport { Logs } from './collections/log.collection';\nimport { Users } from './collections/user.collection';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { ServerResponseModel } from './models/server-message.model';\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\n\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { setupHomeRoutes } from './http/home';\n\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { WorkerDispatcherManager } from './managers/worker-dispatcher.manager';\nimport { WorkerServerManager } from './managers/worker-server.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\tprivate _workerDispatcherManager: WorkerDispatcherManager;\n\tprivate _workerServerManager: WorkerServerManager;\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tconstructor() {}\n\n\tstatic async create() {\n\t\tconst resolveioMainServer = new ResolveIOMainServer();\n\t\tawait resolveioMainServer.initialize();\n\t\treturn resolveioMainServer;\n\t}\n\n\tprivate async initialize() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = await MonitorManager.create();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tlet initServerFlag = false;\n\n\t\tsetTimeout(() => {\n\t\t\tinitServerFlag = true;\n\t\t}, 5000);\n\n\t\tprocess.removeAllListeners('unhandledRejection');\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && (error['code'] === 48 || error['code'] === 26 || error['code'] === 11000 || error['code'] === 251)) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tif (error && error['name'] === 'MongoServerError' && (!initServerFlag || error['code'] === 26 || error['code'] === 11000 || error['code'] === 86 || error['code'] === 251)) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n\t\tif (this._isWorkersEnabled) {\n\t\t\tif (this._isWorkerInstance) {\n\t\t\t\tconsole.log('Running as a Worker instance', process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis._methodManager = MethodManager.create(null, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._workerServerManager = WorkerServerManager.create(this._methodManager, this.getServerConfig());\n\n\t\t\t\tif (process.env.WORKER_INDEX === '0') {\n\t\t\t\t\tthis._cronManager = CronManager.create();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('Running as a Server instance', process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\t\tthis._methodManager = MethodManager.create(this._websocketManager, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._workerDispatcherManager = WorkerDispatcherManager.create(this._websocketManager, this._methodManager);\n\t\t\t\tthis._subscriptionManager = SubscriptionManager.create(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.startServerInstance();\n\t\t\t\tthis.listen();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log('Running with Workers Disabled', process.env.NODE_APP_INSTANCE);\n\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\tthis._methodManager = MethodManager.create(this._websocketManager, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = SubscriptionManager.create(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\tthis._cronManager = CronManager.create();\n\t\t\tthis.startServerInstance();\n\t\t\tthis.listen();\n\t\t}\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.NODE_APP_INSTANCE ? parseInt('808' + process.env.NODE_APP_INSTANCE) : 8080;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\tsetupHealthRoutes(this._app);\n\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length\n\t\t\t&& !this._offlineUpdates.length && (!this._workerDispatcherManager || this._workerDispatcherManager.isSafeShutdown())\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\ttry {\n\t\t\t\t\tawait ResolveIOServer.getMongoConnection().close(false);\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t\tcatch { \n\t\t\t\t\tprocess.exit(1); \n\t\t\t\t};\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), 'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length,\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000;\n\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tserver: this._serverHTTP,\n\t\t\tverifyClient: this.publicProgram ? null : (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\t// If it's a worker, we might skip token checks or do a simple check:\n\t\t\t\t\tif (info.req.url && info.req.url.includes('workerToken=')) {\n\t\t\t\t\t\tlet urlParts = info.req.url.split('workerToken='); \n\t\t\t\t\t\tlet workerToken = urlParts[1] || '';\n\n\t\t\t\t\t\tif (workerToken === ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {\n\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tinfo.origin !== ResolveIOServer.getServerConfig()['ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']\n\t\t\t\t\t) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, ResolveIOServer.getServerConfig()['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\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}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Listen for connections from clients or workers.\n\t */\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running HTTP/WS server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('connection', async (ws, req) => {\n\t\t\tif (req.url && req.url.includes('workerToken=')) {\n\t\t\t\t// It's a WORKER\n\t\t\t\tlet workerId = objectIdHexString();\n\t\t\t\tws['id_worker'] = workerId;\n\n\t\t\t\tconsole.log(new Date(), process.env.NODE_APP_INSTANCE, 'Worker Connected', process.env.NODE_APP_INSTANCE);\n\n\t\t\t\tthis._workerDispatcherManager.addWorker(ws);\n\n\t\t\t\tlet interval = null;\n\t\t\t\tlet lastComm = null;\n\n\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'ping');\n\t\n\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\t\t\t\t\t\tws.close();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'ping');\n\t\t\t\t\t}\n\t\t\t\t}, 30000);\n\n\t\t\t\tws.on('message', (message: any) => {\n\t\t\t\t\t// console.log(new Date(), 'Message Recv', message);\n\n\t\t\t\t\tif (typeof message !== 'string') {\n\t\t\t\t\t\tmessage = message.toString();\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log(new Date(), 'String Message Recv', message);\n\n\t\t\t\t\tif (message === 'ping') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'pong');\n\t\t\t\t\t}\n\t\t\t\t\telse if (message === 'pong') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._workerDispatcherManager.handleWorkerMessage(ws['id_worker'], message);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\n\t\t\t\t\tconsole.log(new Date(), 'Worker disconnected:', workerId);\n\t\t\t\t\t\n\t\t\t\t\tif (interval) {\n\t\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('error', (error) => {\n\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\n\t\t\t\t\tconsole.error('Error on WS Worker', error);\n\t\t\t\t\tws.close();\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Normal client\n\t\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\t\tawait this._subscriptionManager.createLoggedInUser(ws['id_socket']);\n\t\t\t\t\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}, 5000);\n\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Connection from user: ' + req['user']);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['retryCnt'] = 0;\n\n\t\t\t\tws.on('message', async (message: string) => {\n\t\t\t\t\tthis._debugMsgRecv += 1;\n\t\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\tawait this._methodManager.sendEmail(\n\t\t\t\t\t\t\t'dev@resolveio.com', \n\t\t\t\t\t\t\t'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], \n\t\t\t\t\t\t\tJSON.stringify([message, e])\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// call our existing processSocketMessage\n\t\t\t\t\tawait this.processSocketMessage(ws, socketData);\n\t\t\t\t})\n\t\t\t\t.on('end', () => {\n\t\t\t\t\tws.close();\n\t\t\t\t})\n\t\t\t\t.on('error', () => {\n\t\t\t\t\tws.close()\n\t\t\t\t})\n\t\t\t\t.on('close', async () => {\n\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\t// Keep alive timer\n\t\tsetInterval(async () => {\n\t\t\tfor (let ws of this._serverWSS.clients) {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= 20000) {\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\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}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\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}\n\t\t}, 20000);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any) {\n\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tws.send('pong');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\tws['isAlive'] = true;\n\t\t\tws['pongTime'] = new Date();\n\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\treturn;\n\t\t}\n\n\t\t// If the top level is not an array, let's skip\n\t\tif (!Array.isArray(socketData[0])) {\n\t\t\tconsole.log('Invalid message format (expected array of arrays)', socketData);\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle each sub-message\n\t\tfor (let message of socketData) {\n\t\t\tawait this.handleClientMessage(ws, message);\n\t\t}\n\t}\n\n\tprivate async handleClientMessage(ws: WebSocket, msg: any[]): Promise<void> {\n\t\t// This is basically your old logic from processSocketMessage,\n\t\t// but we'll insert our worker-queue logic for \"method\" calls.\n\n\t\tlet messageRoute = msg[0];\n\t\tlet messageDate = msg[1];\n\t\tlet messageId = msg[2];\n\t\tlet type = msg[3];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = msg[4];\n\t\t\tlet pub = msg[5];\n\n\t\t\tif (subType === 'sub') {\n\t\t\t\tawait this._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = msg[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution' && method !== 'qbHandleResponse') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([data])) < 1000000 ? JSON.stringify([data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\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\telse {\n\t\t\t\t\t\tawait Logs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([data])) < 1000000 ? JSON.stringify([data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || ''\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethod.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse {\n\t\t\t// It's presumably a 'method' or something else\n\t\t\tlet dataCopy = [...msg];\n\n\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\tlet route = dataCopy.shift();\n\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\tlet date = dataCopy.shift();\n\t\t\tlet msgId = dataCopy.shift();\n\t\t\tlet msgType = dataCopy.shift();\n\t\t\t\n\t\t\tif (msgType === 'method') {\n\t\t\t\tlet methodName = dataCopy.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (methodName !== 'reportBuilderGetResults' && methodName !== 'reportBuilderGetDistinctValue' && methodName !== 'reportBuilderBuildTree' && methodName !== 'generatePDF' && methodName !== 'getWOOfflineData' && methodName !== 'countQuery' && methodName !== 'countWithQuery' && methodName !== 'countCollectionWithQuery' && methodName !== 'find' && methodName !== 'findOne' && methodName !== 'findWithOptions' && methodName !== 'getDrivers' && methodName !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([dataCopy])) < 1000000 ? JSON.stringify([dataCopy], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\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\telse {\n\t\t\t\t\t\tawait Logs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([dataCopy])) < 1000000 ? JSON.stringify([dataCopy], null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || ''\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Immediately ACK\n\t\t\t\tlet ack: ServerResponseModel = {\n\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, ack);\n\t\t\t\t}\n\n\t\t\t\tlet method = this._methodManager.getMethod(methodName);\n\n\t\t\t\tif (method && \n\t\t\t\t\t!method.skipWorker &&\n\t\t\t\t\tthis._isWorkersEnabled && \n\t\t\t\t\tmethodName !== 'find' &&\n\t\t\t\t\tmethodName !== 'insertDocument' &&\n\t\t\t\t\tmethodName !== 'countWithQuery' &&\n\t\t\t\t\tmethodName !== 'findOne' &&\n\t\t\t\t\tmethodName !== 'updateDocumentProps' &&\n\t\t\t\t\tmethodName !== 'findWithOptions' &&\n\t\t\t\t\tmethodName !== 'updateDocument' &&\n\t\t\t\t\tmethodName !== 'insertErrorLog' &&\n\t\t\t\t\tmethodName !== 'removeDocument' &&\n\t\t\t\t\tmethodName !== 'supportCreateBillingUser' &&\n\t\t\t\t\tmethodName !== 'getSignedUrl' &&\n\t\t\t\t\tmethodName !== 'getSignedUrls' &&\n\t\t\t\t\tmethodName !== 'getSignedUrlWithId' &&\n\t\t\t\t\tmethodName !== 'incorrectUser' &&\n\t\t\t\t\tmethodName !== 'reloadWS' &&\n\t\t\t\t\tmethodName !== 'reconnectWS' &&\n\t\t\t\t\tmethodName !== 'disconnectWS'\n\t\t\t\t) {\t\t\t\t\t\n\t\t\t\t\tthis._workerDispatcherManager.sendClientTask(msgId, methodName, dataCopy, {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// No worker available: do method locally\n\t\t\t\t\tawait this.callMethodLocally(ws, msgId, methodName, dataCopy);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * callMethodLocally is your old approach for invoking the method in-process.\n\t */\n\tprivate async callMethodLocally(ws: WebSocket, messageId: number, method: string, params: any[]) {\n\t\tlet serverRes: ServerResponseModel = {\n\t\t\tmessageId: messageId,\n\t\t\thasError: false,\n\t\t\tdata: null\n\t\t};\n\n\t\ttry {\n\t\t\t// You can keep your logging code (LogMethodLatencies, Logs.insertOne, etc.)\n\t\t\tlet result = await this._methodManager.callMethod.call(\n\t\t\t\tObject.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t}),\n\t\t\t\tmethod,\n\t\t\t\t...params\n\t\t\t);\n\n\t\t\tserverRes.data = result;\n\t\t}\n\t\tcatch (err) {\n\t\t\tserverRes.hasError = true;\n\t\t\tserverRes.data = err || 'Unknown error';\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t}\n\t}\n\n\t\n\n\t/**\n\t * Cleanly remove a client from the subscription manager, etc.\n\t */\n\tpublic async unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tawait this._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn ResolveIOServer.getServerConfig();\n\t}\n\n\tpublic getWorkerDispatcherManager() {\n\t\treturn this._workerDispatcherManager;\n\t}\n\n\tpublic getWorkerServerManager() {\n\t\treturn this._workerServerManager;\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/server-app.ts"],"names":["bodyParser","require","express","xmlParser","http_1","jwt","moment","WebSocket","log_collection_1","user_collection_1","cron_manager_1","method_manager_1","monitor_manager_1","subscription_manager_1","common_1","mongodb_1","auth_1","health_1","home_1","websocket_manager_1","worker_dispatcher_manager_1","worker_server_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_safeShutdown","create","resolveioMainServer","initialize","_a","sent","prototype","_serverStartTime","Date","MonitorManager","_monitorManager","_b","_monitorManagerFunction","MonitorManagerFunction","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_this","_subscriptionManager","getEnableDebug","console","log","initServerFlag","setTimeout","removeAllListeners","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","_methodManager","sendEmail","ResolveIOServer","getServerConfig","JSON","stringify","name","message","stack","exit","_serverHTTP","close","safeShutdown","NODE_APP_INSTANCE","MethodManager","_workerServerManager","WorkerServerManager","WORKER_INDEX","_cronManager","CronManager","_websocketManager","WebSocketManager","_workerDispatcherManager","WorkerDispatcherManager","SubscriptionManager","_serverWSS","startServerInstance","listen","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","parseInt","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","getActiveMonitorFunctions","length","isSafeShutdown","getMongoConnection","setImmediate","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","ws","push","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","server","verifyClient","info","cb","token","url","includes","split","infoData","headers","origin","verify","err","decoded","Users","findById","user","fullname","readonly","workerId_1","objectIdHexString","addWorker","lastComm_1","sendWorkerPayload","interval_1","disconnectWorker","toString","handleWorkerMessage","clearInterval","addWebSocket","createLoggedInUser","send","unsubscribeWS","socketData","parse","e_1","processSocketMessage","now","getTime","this_1","_e","__values","value","readyState","OPEN","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","socketData_1_1","handleClientMessage","msg","messageRoute","messageDate","messageId","type","some","a","roles","groups","views","b","super_admin","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","data","offlineUpdates","i","update","shift","updateMessageId","method","serverResMethod","getLocalLogManager","writeLog","_id","createdAt","collection","id_document","payload","getBinarySize","id_user","route","Logs","insertOne","client","instance","instance_index","_methods","callMethod","call","apply","__spreadArray","Object","assign","id_ws","__read","err_1","getMongoManager","invalidateQueryCache","splice","map","indexOf","dataCopy","msgId","methodName","ack","getMethod","skipWorker","sendClientTask","callMethodLocally","params","result","err_2","unsubscribeAll","getApp","getWorkerDispatcherManager","getWorkerServerManager","exports"],"mappings":"+xEAAAA,Y,0FAAAC,QAAA,aAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,UAAAF,QAAA,wBAAA,EACAG,OAAAH,QAAA,MAAA,EACAI,IAAAJ,QAAA,cAAA,EACAK,OAAAL,QAAA,iBAAA,EACAM,UAAAN,QAAA,IAAA,EAEAO,iBAAAP,QAAA,8BAAA,EACAQ,kBAAAR,QAAA,+BAAA,EACAS,eAAAT,QAAA,yBAAA,EACAU,iBAAAV,QAAA,2BAAA,EACAW,kBAAAX,QAAA,4BAAA,EACAY,uBAAAZ,QAAA,iCAAA,EAEAa,SAAAb,QAAA,eAAA,EAEAc,UAAAd,QAAA,SAAA,EACAe,OAAAf,QAAA,aAAA,EACAgB,SAAAhB,QAAA,eAAA,EACAiB,OAAAjB,QAAA,aAAA,EAEAkB,oBAAAlB,QAAA,8BAAA,EACAmB,4BAAAnB,QAAA,sCAAA,EACAoB,wBAAApB,QAAA,kCAAA,EACAqB,uBAAArB,QAAA,wBAAA,EAEAsB,oBAAA,WAkCC,SAAAA,sBA7BQC,KAAAC,gBAAkB,GACnBD,KAAAE,QAAU,CAAA,EACTF,KAAAG,gBAAkB,CAAA,EAClBH,KAAAI,cAAgB,CAAA,EAChBJ,KAAAK,YAAc,CAAA,EAEdL,KAAAM,OAAS,QAQTN,KAAAO,cAA0B,GAK1BP,KAAAQ,cAAsB,KAEtBR,KAAAS,cAAgB,EAChBT,KAAAU,eAAiB,EAEjBV,KAAAW,kBAAoB,CAAA,EACpBX,KAAAY,kBAAoB,CAAA,EAEpBZ,KAAAa,cAAgB,CAAA,CAET,CA44BhB,OA14Bcd,oBAAAe,OAAb,W,gHAEC,MAAA,CAAA,GADMC,EAAsB,IAAIhB,qBACNiB,WAAU,G,OACpC,OADAC,EA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'body-parser';\nimport * as express from 'express';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport { createServer, Server } from 'http';\nimport * as jwt from 'jsonwebtoken';\nimport * as moment from 'moment-timezone';\nimport * as WebSocket from 'ws';\n\nimport { Logs } from './collections/log.collection';\nimport { Users } from './collections/user.collection';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { ServerResponseModel } from './models/server-message.model';\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\n\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { setupHomeRoutes } from './http/home';\n\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { WorkerDispatcherManager } from './managers/worker-dispatcher.manager';\nimport { WorkerServerManager } from './managers/worker-server.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\tprivate _workerDispatcherManager: WorkerDispatcherManager;\n\tprivate _workerServerManager: WorkerServerManager;\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\n\tprivate _safeShutdown = false;\n\n\tconstructor() {}\n\n\tstatic async create() {\n\t\tconst resolveioMainServer = new ResolveIOMainServer();\n\t\tawait resolveioMainServer.initialize();\n\t\treturn resolveioMainServer;\n\t}\n\n\tprivate async initialize() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = await MonitorManager.create();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tlet initServerFlag = false;\n\n\t\tsetTimeout(() => {\n\t\t\tinitServerFlag = true;\n\t\t}, 5000);\n\n\t\tprocess.removeAllListeners('unhandledRejection');\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.error(new Date(), 'ERROR DETECTED w/ Debug Flag Active: unhandledRejection', [error, rej]);\n\t\t\t}\n\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && (error['code'] === 48 || error['code'] === 26 || error['code'] === 11000 || error['code'] === 251)) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tif (error && error['name'] === 'MongoServerError' && (!initServerFlag || error['code'] === 26 || error['code'] === 11000 || error['code'] === 86 || error['code'] === 251)) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', async () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tawait this.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n\t\tif (this._isWorkersEnabled) {\n\t\t\tif (this._isWorkerInstance) {\n\t\t\t\tconsole.log('Running as a Worker instance', process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis._methodManager = MethodManager.create(null, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._workerServerManager = WorkerServerManager.create(this._methodManager, this.getServerConfig());\n\n\t\t\t\tif (process.env.WORKER_INDEX === '0') {\n\t\t\t\t\tthis._cronManager = CronManager.create();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log('Running as a Server instance', process.env.NODE_APP_INSTANCE);\n\t\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\t\tthis._methodManager = MethodManager.create(this._websocketManager, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._workerDispatcherManager = WorkerDispatcherManager.create(this._websocketManager, this._methodManager);\n\t\t\t\tthis._subscriptionManager = SubscriptionManager.create(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.startServerInstance();\n\t\t\t\tthis.listen();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log('Running with Workers Disabled', process.env.NODE_APP_INSTANCE);\n\t\t\tthis._websocketManager = WebSocketManager.create(this);\n\t\t\tthis._methodManager = MethodManager.create(this._websocketManager, this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = SubscriptionManager.create(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\tthis._cronManager = CronManager.create();\n\t\t\tthis.startServerInstance();\n\t\t\tthis.listen();\n\t\t}\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.NODE_APP_INSTANCE ? parseInt('808' + process.env.NODE_APP_INSTANCE) : 8080;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\tsetupHealthRoutes(this._app);\n\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length\n\t\t\t&& !this._offlineUpdates.length && (!this._workerDispatcherManager || this._workerDispatcherManager.isSafeShutdown())\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\ttry {\n\t\t\t\t\tawait ResolveIOServer.getMongoConnection().close(false);\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t\tcatch { \n\t\t\t\t\tprocess.exit(1); \n\t\t\t\t};\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), 'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length,\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000;\n\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tserver: this._serverHTTP,\n\t\t\tverifyClient: this.publicProgram ? null : (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\t// If it's a worker, we might skip token checks or do a simple check:\n\t\t\t\t\tif (info.req.url && info.req.url.includes('workerToken=')) {\n\t\t\t\t\t\tlet urlParts = info.req.url.split('workerToken='); \n\t\t\t\t\t\tlet workerToken = urlParts[1] || '';\n\n\t\t\t\t\t\tif (workerToken === ResolveIOServer.getServerConfig()['WORKER_TOKEN']) {\n\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tinfo.origin !== ResolveIOServer.getServerConfig()['ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL']\n\t\t\t\t\t\t&& info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']\n\t\t\t\t\t) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, ResolveIOServer.getServerConfig()['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\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}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Listen for connections from clients or workers.\n\t */\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running HTTP/WS server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('connection', async (ws, req) => {\n\t\t\tif (req.url && req.url.includes('workerToken=')) {\n\t\t\t\t// It's a WORKER\n\t\t\t\tlet workerId = objectIdHexString();\n\t\t\t\tws['id_worker'] = workerId;\n\n\t\t\t\tconsole.log(new Date(), process.env.NODE_APP_INSTANCE, 'Worker Connected', process.env.NODE_APP_INSTANCE);\n\n\t\t\t\tthis._workerDispatcherManager.addWorker(ws);\n\n\t\t\t\tlet interval = null;\n\t\t\t\tlet lastComm = null;\n\n\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'ping');\n\t\n\t\t\t\tinterval = setInterval(() => {\n\t\t\t\t\tif (!lastComm) {\n\t\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\t\t\t\t\t\tws.close();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlastComm = null;\n\t\t\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'ping');\n\t\t\t\t\t}\n\t\t\t\t}, 30000);\n\n\t\t\t\tws.on('message', (message: any) => {\n\t\t\t\t\t// console.log(new Date(), 'Message Recv', message);\n\n\t\t\t\t\tif (typeof message !== 'string') {\n\t\t\t\t\t\tmessage = message.toString();\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log(new Date(), 'String Message Recv', message);\n\n\t\t\t\t\tif (message === 'ping') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tthis._workerDispatcherManager.sendWorkerPayload(ws, 'pong');\n\t\t\t\t\t}\n\t\t\t\t\telse if (message === 'pong') {\n\t\t\t\t\t\t// console.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t\tlastComm = new Date();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis._workerDispatcherManager.handleWorkerMessage(ws['id_worker'], message);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\n\t\t\t\t\tconsole.log(new Date(), 'Worker disconnected:', workerId);\n\t\t\t\t\t\n\t\t\t\t\tif (interval) {\n\t\t\t\t\t\tclearInterval(interval);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tws.on('error', (error) => {\n\t\t\t\t\tthis._workerDispatcherManager.disconnectWorker(ws['id_worker']);\n\n\t\t\t\t\tconsole.error('Error on WS Worker', error);\n\t\t\t\t\tws.close();\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Normal client\n\t\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\t\tawait this._subscriptionManager.createLoggedInUser(ws['id_socket']);\n\t\t\t\t\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}, 5000);\n\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Connection from user: ' + req['user']);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tws['isAlive'] = true;\n\t\t\t\tws['retryCnt'] = 0;\n\n\t\t\t\tws.on('message', async (message: string) => {\n\t\t\t\t\tthis._debugMsgRecv += 1;\n\t\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\tawait this._methodManager.sendEmail(\n\t\t\t\t\t\t\t'dev@resolveio.com', \n\t\t\t\t\t\t\t'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], \n\t\t\t\t\t\t\tJSON.stringify([message, e])\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// call our existing processSocketMessage\n\t\t\t\t\tawait this.processSocketMessage(ws, socketData);\n\t\t\t\t})\n\t\t\t\t.on('end', () => {\n\t\t\t\t\tws.close();\n\t\t\t\t})\n\t\t\t\t.on('error', () => {\n\t\t\t\t\tws.close()\n\t\t\t\t})\n\t\t\t\t.on('close', async () => {\n\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\t// Keep alive timer\n\t\tsetInterval(async () => {\n\t\t\tfor (let ws of this._serverWSS.clients) {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= 20000) {\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\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}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', async (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tawait this.unsubscribeWS(ws);\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}\n\t\t}, 20000);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any) {\n\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tws.send('pong');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\tws['isAlive'] = true;\n\t\t\tws['pongTime'] = new Date();\n\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\treturn;\n\t\t}\n\n\t\t// If the top level is not an array, let's skip\n\t\tif (!Array.isArray(socketData[0])) {\n\t\t\tconsole.log('Invalid message format (expected array of arrays)', socketData);\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle each sub-message\n\t\tfor (let message of socketData) {\n\t\t\tawait this.handleClientMessage(ws, message);\n\t\t}\n\t}\n\n\tprivate async handleClientMessage(ws: WebSocket, msg: any[]): Promise<void> {\n\t\t// This is basically your old logic from processSocketMessage,\n\t\t// but we'll insert our worker-queue logic for \"method\" calls.\n\n\t\tlet messageRoute = msg[0];\n\t\tlet messageDate = msg[1];\n\t\tlet messageId = msg[2];\n\t\tlet type = msg[3];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = msg[4];\n\t\t\tlet pub = msg[5];\n\n\t\t\tif (subType === 'sub') {\n\t\t\t\tawait this._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, msg.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = msg[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution' && method !== 'qbHandleResponse') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([data])) < 1000000 ? JSON.stringify([data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\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\telse {\n\t\t\t\t\t\tawait Logs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([data])) < 1000000 ? JSON.stringify([data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || ''\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethod.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse {\n\t\t\t// It's presumably a 'method' or something else\n\t\t\tlet dataCopy = [...msg];\n\n\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\tlet route = dataCopy.shift();\n\t\t\t// eslint-disable-next-line no-unused-vars\n\t\t\tlet date = dataCopy.shift();\n\t\t\tlet msgId = dataCopy.shift();\n\t\t\tlet msgType = dataCopy.shift();\n\t\t\t\n\t\t\tif (msgType === 'method') {\n\t\t\t\tlet methodName = dataCopy.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (methodName !== 'reportBuilderGetResults' && methodName !== 'reportBuilderGetDistinctValue' && methodName !== 'reportBuilderBuildTree' && methodName !== 'generatePDF' && methodName !== 'getWOOfflineData' && methodName !== 'countQuery' && methodName !== 'countWithQuery' && methodName !== 'countCollectionWithQuery' && methodName !== 'find' && methodName !== 'findOne' && methodName !== 'findWithOptions' && methodName !== 'getDrivers' && methodName !== 'processAirdropDistribution') {\n\t\t\t\t\tif (\n\t\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t\t) {\n\t\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\t\ttype: 'log',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([dataCopy])) < 1000000 ? JSON.stringify([dataCopy], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\t\troute: messageRoute\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\telse {\n\t\t\t\t\t\tawait Logs.insertOne({\n\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([dataCopy])) < 1000000 ? JSON.stringify([dataCopy], null, 2) : 'Too Big',\n\t\t\t\t\t\t\tmethod: methodName,\n\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\troute: messageRoute,\n\t\t\t\t\t\t\tclient: 'ResolveIO',\n\t\t\t\t\t\t\tinstance: 'backend.resolveio.com',\n\t\t\t\t\t\t\tinstance_index: process.env.NODE_APP_INSTANCE || ''\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Immediately ACK\n\t\t\t\tlet ack: ServerResponseModel = {\n\t\t\t\t\tmessageId: msgId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, ack);\n\t\t\t\t}\n\n\t\t\t\tlet method = this._methodManager.getMethod(methodName);\n\n\t\t\t\tif (method && \n\t\t\t\t\t!method.skipWorker &&\n\t\t\t\t\tthis._isWorkersEnabled && \n\t\t\t\t\tmethodName !== 'find' &&\n\t\t\t\t\tmethodName !== 'insertDocument' &&\n\t\t\t\t\tmethodName !== 'countWithQuery' &&\n\t\t\t\t\tmethodName !== 'findOne' &&\n\t\t\t\t\tmethodName !== 'updateDocumentProps' &&\n\t\t\t\t\tmethodName !== 'findWithOptions' &&\n\t\t\t\t\tmethodName !== 'updateDocument' &&\n\t\t\t\t\tmethodName !== 'insertErrorLog' &&\n\t\t\t\t\tmethodName !== 'removeDocument' &&\n\t\t\t\t\tmethodName !== 'supportCreateBillingUser' &&\n\t\t\t\t\tmethodName !== 'getSignedUrl' &&\n\t\t\t\t\tmethodName !== 'getSignedUrls' &&\n\t\t\t\t\tmethodName !== 'getSignedUrlWithId' &&\n\t\t\t\t\tmethodName !== 'incorrectUser' &&\n\t\t\t\t\tmethodName !== 'reloadWS' &&\n\t\t\t\t\tmethodName !== 'reconnectWS' &&\n\t\t\t\t\tmethodName !== 'disconnectWS'\n\t\t\t\t) {\t\t\t\t\t\n\t\t\t\t\tthis._workerDispatcherManager.sendClientTask(msgId, methodName, dataCopy, {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// No worker available: do method locally\n\t\t\t\t\tawait this.callMethodLocally(ws, msgId, methodName, dataCopy);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * callMethodLocally is your old approach for invoking the method in-process.\n\t */\n\tprivate async callMethodLocally(ws: WebSocket, messageId: number, method: string, params: any[]) {\n\t\tlet serverRes: ServerResponseModel = {\n\t\t\tmessageId: messageId,\n\t\t\thasError: false,\n\t\t\tdata: null\n\t\t};\n\n\t\ttry {\n\t\t\t// You can keep your logging code (LogMethodLatencies, Logs.insertOne, etc.)\n\t\t\tlet result = await this._methodManager.callMethod.call(\n\t\t\t\tObject.assign({}, this._methodManager, MethodManager.prototype, {\n\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\tid_ws: ws['id_socket']\n\t\t\t\t}),\n\t\t\t\tmethod,\n\t\t\t\t...params\n\t\t\t);\n\n\t\t\tserverRes.data = result;\n\t\t}\n\t\tcatch (err) {\n\t\t\tserverRes.hasError = true;\n\t\t\tserverRes.data = err || 'Unknown error';\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t}\n\t}\n\n\t\n\n\t/**\n\t * Cleanly remove a client from the subscription manager, etc.\n\t */\n\tpublic async unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tawait this._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn ResolveIOServer.getServerConfig();\n\t}\n\n\tpublic getWorkerDispatcherManager() {\n\t\treturn this._workerDispatcherManager;\n\t}\n\n\tpublic getWorkerServerManager() {\n\t\treturn this._workerServerManager;\n\t}\n}"]}